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

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

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

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

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

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

There is a set of functions (declared in <asm/sbus.h>) for performingDMA mappings on the SBus; they have names like sbus_alloc_consistent and41222 June 2001 16:42http://openlib.org.uaDirect Memory Access and Bus Masteringsbus_map_sg. In other words, the SBus DMA API looks almost exactly like the PCIinterface. A detailed look at the function definitions will be required before working with DMA on the SBus, but the concepts will match those discussed earlier forthe PCI bus.DMA for ISA DevicesThe ISA bus allows for two kinds of DMA transfers: native DMA and ISA bus master DMA.

Native DMA uses standard DMA-controller circuitry on the motherboardto drive the signal lines on the ISA bus. ISA bus master DMA, on the other hand, ishandled entirely by the peripheral device. The latter type of DMA is rarely usedand doesn’t require discussion here because it is similar to DMA for PCI devices, atleast from the driver’s point of view. An example of an ISA bus master is the 1542SCSI controller, whose driver is drivers/scsi/aha1542.c in the kernel sources.As far as native DMA is concerned, there are three entities involved in a DMA datatransfer on the ISA bus:The 8237 DMA controller (DMAC)The controller holds information about the DMA transfer, such as the direction, the memory address, and the size of the transfer. It also contains acounter that tracks the status of ongoing transfers.

When the controllerreceives a DMA request signal, it gains control of the bus and drives the signallines so that the device can read or write its data.The peripheral deviceThe device must activate the DMA request signal when it’s ready to transferdata. The actual transfer is managed by the DMAC; the hardware devicesequentially reads or writes data onto the bus when the controller strobes thedevice.

The device usually raises an interrupt when the transfer is over.The device driverThe driver has little to do: it provides the DMA controller with the direction,bus address, and size of the transfer. It also talks to its peripheral to prepare itfor transferring the data and responds to the interrupt when the DMA is over.The original DMA controller used in the PC could manage four “channels,” eachassociated with one set of DMA registers. Four devices could store their DMAinformation in the controller at the same time. Newer PCs contain the equivalentof two DMAC devices:* the second controller (master) is connected to the systemprocessor, and the first (slave) is connected to channel 0 of the second controller.†* These circuits are now part of the motherboard’s chipset, but a few years ago they weretwo separate 8237 chips.† The original PCs had only one controller; the second was added in 286-based platforms.However, the second controller is connected as the master because it handles 16-bittransfers; the first transfers only 8 bits at a time and is there for backward compatibility.41322 June 2001 16:42http://openlib.org.uaChapter 13: mmap and DMAThe channels are numbered from 0 to 7; channel 4 is not available to ISA peripherals because it is used internally to cascade the slave controller onto the master.The available channels are thus 0 to 3 on the slave (the 8-bit channels) and 5 to 7on the master (the 16-bit channels).

The size of any DMA transfer, as stored in thecontroller, is a 16-bit number representing the number of bus cycles. The maximum transfer size is therefore 64 KB for the slave controller and 128 KB for themaster.Because the DMA controller is a system-wide resource, the kernel helps deal withit. It uses a DMA registry to provide a request-and-free mechanism for the DMAchannels and a set of functions to configure channel information in the DMA controller.Registering DMA usageYou should be used to kernel registries — we’ve already seen them for I/O portsand interrupt lines. The DMA channel registry is similar to the others.

After<asm/dma.h> has been included, the following functions can be used to obtainand release ownership of a DMA channel:int request_dma(unsigned int channel, const char *name);void free_dma(unsigned int channel);The channel argument is a number between 0 and 7 or, more precisely, a positive number less than MAX_DMA_CHANNELS. On the PC, MAX_DMA_CHANNELS isdefined as 8, to match the hardware. The name argument is a string identifying thedevice. The specified name appears in the file /pr oc/dma, which can be read byuser programs.The return value from request_dma is 0 for success and -EINVAL or -EBUSY ifthere was an error.

The former means that the requested channel is out of range,and the latter means that another device is holding the channel.We recommend that you take the same care with DMA channels as with I/O portsand interrupt lines; requesting the channel at open time is much better thanrequesting it from the module initialization function. Delaying the request allowssome sharing between drivers; for example, your sound card and your analog I/Ointerface can share the DMA channel as long as they are not used at the sametime.We also suggest that you request the DMA channel after you’ve requested theinterrupt line and that you release it befor e the interrupt. This is the conventionalorder for requesting the two resources; following the convention avoids possibledeadlocks.

Note that every device using DMA needs an IRQ line as well; otherwise, it couldn’t signal the completion of data transfer.41422 June 2001 16:42http://openlib.org.uaDirect Memory Access and Bus MasteringIn a typical case, the code for open looks like the following, which refers to ourhypothetical dad module. The dad device as shown uses a fast interrupt handlerwithout support for shared IRQ lines.int dad_open (struct inode *inode, struct file *filp){struct dad_device *my_device;/* ...

*/if ( (error = request_irq(my_device.irq, dad_interrupt,SA_INTERRUPT, "dad", NULL)) )return error; /* or implement blocking open */if ( (error = request_dma(my_device.dma, "dad")) ) {free_irq(my_device.irq, NULL);return error; /* or implement blocking open */}/* ... */return 0;}The close implementation that matches the open just shown looks like this:void dad_close (struct inode *inode, struct file *filp){struct dad_device *my_device;/* ... */free_dma(my_device.dma);free_irq(my_device.irq, NULL);/* ... */}As far as /pr oc/dma is concerned, here’s how the file looks on a system with thesound card installed:merlino% cat /proc/dma1: Sound Blaster84: cascadeIt’s interesting to note that the default sound driver gets the DMA channel at system boot and never releases it.

The cascade entry shown is a placeholder, indicating that channel 4 is not available to drivers, as explained earlier.Talking to the DMA controllerAfter registration, the main part of the driver’s job consists of configuring the DMAcontroller for proper operation. This task is not trivial, but fortunately the kernelexports all the functions needed by the typical driver.41522 June 2001 16:42http://openlib.org.uaChapter 13: mmap and DMAThe driver needs to configure the DMA controller either when read or write iscalled, or when preparing for asynchronous transfers. This latter task is performedeither at open time or in response to an ioctl command, depending on the driverand the policy it implements.

The code shown here is the code that is typicallycalled by the read or write device methods.This subsection provides a quick overview of the internals of the DMA controllerso you will understand the code introduced here. If you want to learn more, we’durge you to read <asm/dma.h> and some hardware manuals describing the PCarchitecture. In particular, we don’t deal with the issue of 8-bit versus 16-bit datatransfers.

If you are writing device drivers for ISA device boards, you should findthe relevant information in the hardware manuals for the devices.The DMA controller is a shared resource, and confusion could arise if more thanone processor attempts to program it simultaneously. For that reason, the controller is protected by a spinlock, called dma_spin_lock. Drivers should notmanipulate the lock directly, however; two functions have been provided to dothat for you:unsigned long claim_dma_lock();Acquires the DMA spinlock.

This function also blocks interrupts on the localprocessor; thus the return value is the usual ‘‘flags’’ value, which must be usedwhen reenabling interrupts.void release_dma_lock(unsigned long flags);Returns the DMA spinlock and restores the previous interrupt status.The spinlock should be held when using the functions described next. It shouldnot be held during the actual I/O, however.

A driver should never sleep whenholding a spinlock.The information that must be loaded into the controller is made up of three items:the RAM address, the number of atomic items that must be transferred (in bytes orwords), and the direction of the transfer. To this end, the following functions areexported by <asm/dma.h>:void set_dma_mode(unsigned int channel, char mode);Indicates whether the channel must read from the device (DMA_MODE_READ)or write to it (DMA_MODE_WRITE). A third mode exists, DMA_MODE_CASCADE, which is used to release control of the bus. Cascading is the way thefirst controller is connected to the top of the second, but it can also be usedby true ISA bus-master devices.

We won’t discuss bus mastering here.void set_dma_addr(unsigned int channel, unsigned int addr);Assigns the address of the DMA buffer. The function stores the 24 least significant bits of addr in the controller. The addr argument must be a bus address(see “Bus Addresses” earlier in this chapter).41622 June 2001 16:42http://openlib.org.uaDirect Memory Access and Bus Masteringvoid set_dma_count(unsigned int channel, unsigned intcount);Assigns the number of bytes to transfer. The count argument represents bytesfor 16-bit channels as well; in this case, the number must be even.In addition to these functions, there are a number of housekeeping facilities thatmust be used when dealing with DMA devices:void disable_dma(unsigned int channel);A DMA channel can be disabled within the controller.

The channel should bedisabled before the controller is configured, to prevent improper operation(the controller is programmed via eight-bit data transfers, and thus none of theprevious functions is executed atomically).void enable_dma(unsigned int channel);This function tells the controller that the DMA channel contains valid data.int get_dma_residue(unsigned int channel);The driver sometimes needs to know if a DMA transfer has been completed.This function returns the number of bytes that are still to be transferred. Thereturn value is 0 after a successful transfer and is unpredictable (but not 0)while the controller is working. The unpredictability reflects the fact that theresidue is a 16-bit value, which is obtained by two 8-bit input operations.void clear_dma_ff(unsigned int channel)This function clears the DMA flip-flop.

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