Linux Device Drivers 2nd Edition, страница 98

PDF-файл Linux Device Drivers 2nd Edition, страница 98 Основы автоматизированного проектирования (ОАП) (17688): Книга - 3 семестрLinux Device Drivers 2nd Edition: Основы автоматизированного проектирования (ОАП) - PDF, страница 98 (17688) - СтудИзба2018-01-10СтудИзба

Описание файла

PDF-файл из архива "Linux Device Drivers 2nd Edition", который расположен в категории "". Всё это находится в предмете "основы автоматизированного проектирования (оап)" из 3 семестр, которые можно найти в файловом архиве МГТУ им. Н.Э.Баумана. Не смотря на прямую связь этого архива с МГТУ им. Н.Э.Баумана, его также можно найти и в других разделах. Архив можно найти в разделе "книги и методические указания", в предмете "основы автоматизированного производства (оап)" в общих файлах.

Просмотр PDF-файла онлайн

Текст 98 страницы из PDF

The flip-flop is used to control accessto 16-bit registers. The registers are accessed by two consecutive 8-bit operations, and the flip-flop is used to select the least significant byte (when it isclear) or the most significant byte (when it is set). The flip-flop automaticallytoggles when 8 bits have been transferred; the programmer must clear the flipflop (to set it to a known state) before accessing the DMA registers.Using these functions, a driver can implement a function like the following to prepare for a DMA transfer:int dad_dma_prepare(int channel, int mode, unsigned int buf,unsigned int count){unsigned long flags;flags = claim_dma_lock();disable_dma(channel);clear_dma_ff(channel);set_dma_mode(channel, mode);set_dma_addr(channel, virt_to_bus(buf));set_dma_count(channel, count);enable_dma(channel);release_dma_lock(flags);41722 June 2001 16:42http://openlib.org.uaChapter 13: mmap and DMAreturn 0;}A function like the next one, then, is used to check for successful completion ofDMA:int dad_dma_isdone(int channel){int residue;unsigned long flags = claim_dma_lock ();residue = get_dma_residue(channel);release_dma_lock(flags);return (residue == 0);}The only thing that remains to be done is to configure the device board.

Thisdevice-specific task usually consists of reading or writing a few I/O ports. Devicesdiffer in significant ways. For example, some devices expect the programmer totell the hardware how big the DMA buffer is, and sometimes the driver has to reada value that is hardwired into the device. For configuring the board, the hardwaremanual is your only friend.Backward CompatibilityAs with other parts of the kernel, both memory mapping and DMA have seen anumber of changes over the years.

This section describes the things a driver writermust take into account in order to write portable code.Changes to Memory ManagementThe 2.3 development series saw major changes in the way memory managementworked. The 2.2 kernel was quite limited in the amount of memory it could use,especially on 32-bit processors. With 2.4, those limits have been lifted; Linux isnow able to manage all the memory that the processor is able to address. Somethings have had to change to make all this possible; overall, however, the scale ofthe changes at the API level is surprisingly small.As we have seen, the 2.4 kernel makes extensive use of pointers to structpage to refer to specific pages in memory.

This structure has been present inLinux for a long time, but it was not previously used to refer to the pages themselves; instead, the kernel used logical addresses.Thus, for example, pte_ page returned an unsigned long value instead ofstruct page *. The virt_to_ page macro did not exist at all; if you needed tofind a struct page entry you had to go directly to the memory map to get it.The macro MAP_NR would turn a logical address into an index in mem_map; thus,the current virt_to_ page macro could be defined (and, in sysdep.h in the samplecode, is defined) as follows:41822 June 2001 16:42http://openlib.org.uaBackward Compatibility#ifdef MAP_NR#define virt_to_page(page) (mem_map + MAP_NR(page))#endifThe MAP_NR macro went away when virt_to_ page was introduced. The get_ pagemacro also didn’t exist prior to 2.4, so sysdep.h defines it as follows:#ifndef get_page# define get_page(p) atomic_inc(&(p)->count)#endifstruct page has also changed with time; in particular, the virtual field ispresent in Linux 2.4 only.The page_table_lock was introduced in 2.3.10.

Earlier code would obtain the‘‘big kernel lock’’ (by calling lock_ker nel and unlock_ker nel) before traversingpage tables.The vm_area_struct structure saw a number of changes in the 2.3 development series, and more in 2.1. These included the following:•The vm_pgoff field was called vm_offset in 2.2 and before. It was an offset in bytes, not pages.•The vm_private_data field did not exist in Linux 2.2, so drivers had noway of storing their own information in the VMA.

A number of them did soanyway, using the vm_pte field, but it would be safer to obtain the minordevice number from vm_file and use it to retrieve the needed information.•The 2.4 kernel initializes the vm_file pointer before calling the mmapmethod. In 2.2, drivers had to assign that value themselves, using the filestructure passed in as an argument.•The vm_file pointer did not exist at all in 2.0 kernels; instead, there was avm_inode pointer pointing to the inode structure. This field needed to beassigned by the driver; it was also necessary to increment inode->i_countin the mmap method.•The VM_RESERVED flag was added in kernel 2.4.0-test10.There have also been changes to the the various vm_ops methods stored in theVMA:•2.2 and earlier kernels had a method called advise, which was never actuallyused by the kernel.

There was also a swapin method, which was used to bringin memory from backing store; it was not generally of interest to driver writers.•The nopage and wppage methods returned unsigned long (i.e., a logicaladdress) in 2.2, rather than struct page *.41922 June 2001 16:42http://openlib.org.uaChapter 13: mmap and DMA•The NOPAGE_SIGBUS and NOPAGE_OOM return codes for nopage did notexist.

nopage simply returned 0 to indicate a problem and send a bus signalto the affected process.Because nopage used to return unsigned long, its job was to return the logicaladdress of the page of interest, rather than its mem_map entry.There was, of course, no high-memory support in older kernels. All memory hadlogical addresses, and the kmap and kunmap functions did not exist.In the 2.0 kernel, the init_mm structure was not exported to modules. Thus, amodule that wished to access init_mm had to dig through the task table to find it(as part of the init process).

When running on a 2.0 kernel, scullp finds init_mmwith this bit of code:static struct mm_struct *init_mm_ptr;#define init_mm (*init_mm_ptr) /* to avoid ifdefs later */static void retrieve_init_mm_ptr(void){struct task_struct *p;for (p = current ; (p = p->next_task) != current ; )if (p->pid == 0)break;init_mm_ptr = p->mm;}The 2.0 kernel also lacked the distinction between logical and physical addresses,so the _ _va and _ _pa macros did not exist. There was no need for them at thattime.Another thing the 2.0 kernel did not have was maintenance of the module’s usagecount in the presence of memory-mapped areas.

Drivers that implement mmapunder 2.0 need to provide open and close VMA operations to adjust the usagecount themselves. The sample source modules that implement mmap providethese operations.Finally, the 2.0 version of the driver mmap method, like most others, had astruct inode argument; the method’s prototype wasint (*mmap)(struct inode *inode, struct file *filp,struct vm_area_struct *vma);Changes to DMAThe PCI DMA interface as described earlier did not exist prior to kernel 2.3.41.Before then, DMA was handled in a more direct—and system-dependent—way.Buffers were ‘‘mapped’’ by calling virt_to_bus, and there was no general interfacefor handling bus-mapping registers.42022 June 2001 16:42http://openlib.org.uaQuick ReferenceFor those who need to write portable PCI drivers, sysdep.h in the sample codeincludes a simple implementation of the 2.4 DMA interface that may be used onolder kernels.The ISA interface, on the other hand, is almost unchanged since Linux 2.0.

ISA isan old architecture, after all, and there have not been a whole lot of changes tokeep up with. The only addition was the DMA spinlock in 2.2; prior to that kernel,there was no need to protect against conflicting access to the DMA controller. Versions of these functions have been defined in sysdep.h; they disable and restoreinterrupts, but perform no other function.Quick ReferenceThis chapter introduced the following symbols related to memory handling. Thelist doesn’t include the symbols introduced in the first section, as that section is ahuge list in itself and those symbols are rarely useful to device drivers.#include <linux/mm.h>All the functions and structures related to memory management are prototyped and defined in this header.int remap_page_range(unsigned long virt_add, unsigned longphys_add, unsigned long size, pgprot_t prot);This function sits at the heart of mmap.

It maps size bytes of physicaladdresses, starting at phys_addr, to the virtual address virt_add. The protection bits associated with the virtual space are specified in prot.struct page *virt_to_page(void *kaddr);void *page_address(struct page *page);These macros convert between kernel logical addresses and their associatedmemory map entries. page_addr ess only works for low-memory pages, orhigh-memory pages that have been explicitly mapped.void *_ _va(unsigned long physaddr);unsigned long _ _pa(void *kaddr);These macros convert between kernel logical addresses and physicaladdresses.unsigned long kmap(struct page *page);void kunmap(struct page *page);kmap returns a kernel virtual address that is mapped to the given page, creating the mapping if need be.

Свежие статьи
Популярно сейчас
А знаете ли Вы, что из года в год задания практически не меняются? Математика, преподаваемая в учебных заведениях, никак не менялась минимум 30 лет. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
5259
Авторов
на СтудИзбе
421
Средний доход
с одного платного файла
Обучение Подробнее