Главная » Просмотр файлов » Linux Device Drivers 2nd Edition

Linux Device Drivers 2nd Edition (779877), страница 95

Файл №779877 Linux Device Drivers 2nd Edition (Linux Device Drivers 2nd Edition) 95 страницаLinux Device Drivers 2nd Edition (779877) страница 952018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 95)

Some systems even have a pagemapping scheme that can make arbitrary pages appear contiguous to the peripheral bus.At the lowest level (again, we’ll look at a higher-level solution shortly), the Linuxkernel provides a portable solution by exporting the following functions, definedin <asm/io.h>:unsigned long virt_to_bus(volatile void * address);void * bus_to_virt(unsigned long address);The virt_to_bus conversion must be used when the driver needs to send addressinformation to an I/O device (such as an expansion board or the DMA controller),while bus_to_virt must be used when address information is received from hardware connected to the bus.DMA on the PCI BusThe 2.4 kernel includes a flexible mechanism that supports PCI DMA (also knownas bus mastering).

It handles the details of buffer allocation and can deal with setting up the bus hardware for multipage transfers on hardware that supports them.This code also takes care of situations in which a buffer lives in a non-DMA-capable zone of memory, though only on some platforms and at a computational cost(as we will see later).40422 June 2001 16:42http://openlib.org.uaDirect Memory Access and Bus MasteringThe functions in this section require a struct pci_dev structure for yourdevice.

The details of setting up a PCI device are covered in Chapter 15. Note,however, that the routines described here can also be used with ISA devices; inthat case, the struct pci_dev pointer should simply be passed in as NULL.Drivers that use the following functions should include <linux/pci.h>.Dealing with difficult hardwareThe first question that must be answered before performing DMA is whether thegiven device is capable of such operation on the current host.

Many PCI devicesfail to implement the full 32-bit bus address space, often because they are modified versions of old ISA hardware. The Linux kernel will attempt to work withsuch devices, but it is not always possible.The function pci_dma_supported should be called for any device that has addressing limitations:int pci_dma_supported(struct pci_dev *pdev, dma_addr_t mask);Here, mask is a simple bit mask describing which address bits the device can successfully use.

If the return value is nonzero, DMA is possible, and your drivershould set the dma_mask field in the PCI device structure to the mask value. For adevice that can only handle 16-bit addresses, you might use a call like this:if (pci_dma_supported (pdev, 0xffff))pdev->dma_mask = 0xffff;else {card->use_dma = 0;/* We’ll have to live without DMA */printk (KERN_WARN, "mydev: DMA not supported\n");}As of kernel 2.4.3, a new function, pci_set_dma_mask, has been provided. Thisfunction has the following prototype:int pci_set_dma_mask(struct pci_dev *pdev, dma_addr_t mask);If DMA can be supported with the given mask, this function returns 0 and sets thedma_mask field; otherwise, -EIO is returned.For devices that can handle 32-bit addresses, there is no need to callpci_dma_supported.DMA mappingsA DMA mapping is a combination of allocating a DMA buffer and generating anaddress for that buffer that is accessible by the device. In many cases, getting thataddress involves a simple call to virt_to_bus; some hardware, however, requiresthat mapping registers be set up in the bus hardware as well.

Mapping registers40522 June 2001 16:42http://openlib.org.uaChapter 13: mmap and DMAare an equivalent of virtual memory for peripherals. On systems where these registers are used, peripherals have a relatively small, dedicated range of addresses towhich they may perform DMA. Those addresses are remapped, via the mappingregisters, into system RAM. Mapping registers have some nice features, includingthe ability to make several distributed pages appear contiguous in the device’saddress space. Not all architectures have mapping registers, however; in particular,the popular PC platform has no mapping registers.Setting up a useful address for the device may also, in some cases, require theestablishment of a bounce buffer. Bounce buffers are created when a driverattempts to perform DMA on an address that is not reachable by the peripheraldevice — a high-memory address, for example.

Data is then copied to and from thebounce buffer as needed. Making code work properly with bounce buffersrequires adherence to some rules, as we will see shortly.The DMA mapping sets up a new type, dma_addr_t, to represent bus addresses.Variables of type dma_addr_t should be treated as opaque by the driver; theonly allowable operations are to pass them to the DMA support routines and tothe device itself.The PCI code distinguishes between two types of DMA mappings, depending onhow long the DMA buffer is expected to stay around:Consistent DMA mappingsThese exist for the life of the driver.

A consistently mapped buffer must besimultaneously available to both the CPU and the peripheral (other types ofmappings, as we will see later, can be available only to one or the other atany given time). The buffer should also, if possible, not have caching issuesthat could cause one not to see updates made by the other.Str eaming DMA mappingsThese are set up for a single operation. Some architectures allow for significant optimizations when streaming mappings are used, as we will see, butthese mappings also are subject to a stricter set of rules in how they may beaccessed. The kernel developers recommend the use of streaming mappingsover consistent mappings whenever possible.

There are two reasons for thisrecommendation. The first is that, on systems that support them, each DMAmapping uses one or more mapping registers on the bus. Consistent mappings, which have a long lifetime, can monopolize these registers for a longtime, even when they are not being used. The other reason is that, on somehardware, streaming mappings can be optimized in ways that are not availableto consistent mappings.The two mapping types must be manipulated in different ways; it’s time to look atthe details.40622 June 2001 16:42http://openlib.org.uaDirect Memory Access and Bus MasteringSetting up consistent DMA mappingsA driver can set up a consistent mapping with a call to pci_alloc_consistent:void *pci_alloc_consistent(struct pci_dev *pdev, size_t size,dma_addr_t *bus_addr);This function handles both the allocation and the mapping of the buffer. The firsttwo arguments are our PCI device structure and the size of the needed buffer.

Thefunction returns the result of the DMA mapping in two places. The return value isa kernel virtual address for the buffer, which may be used by the driver; the associated bus address, instead, is returned in bus_addr. Allocation is handled in thisfunction so that the buffer will be placed in a location that works with DMA; usually the memory is just allocated with get_fr ee_pages (but note that the size is inbytes, rather than an order value).Most architectures that support PCI perform the allocation at the GFP_ATOMIC priority, and thus do not sleep. The ARM port, however, is an exception to this rule.When the buffer is no longer needed (usually at module unload time), it should bereturned to the system with pci_fr ee_consistent:void pci_free_consistent(struct pci_dev *pdev, size_t size,void *cpu_addr, dma_handle_t bus_addr);Note that this function requires that both the CPU address and the bus address beprovided.Setting up streaming DMA mappingsStreaming mappings have a more complicated interface than the consistent variety,for a number of reasons.

These mappings expect to work with a buffer that hasalready been allocated by the driver, and thus have to deal with addresses thatthey did not choose. On some architectures, streaming mappings can also havemultiple, discontiguous pages and multipart “scatter-gather” buffers.When setting up a streaming mapping, you must tell the kernel in which directionthe data will be moving. Some symbols have been defined for this purpose:PCI_DMA_TODEVICEPCI_DMA_FROMDEVICEThese two symbols should be reasonably self-explanatory.

If data is being sentto the device (in response, perhaps, to a write system call), PCI_DMA_TODEVICE should be used; data going to the CPU, instead, will be marked withPCI_DMA_FROMDEVICE.40722 June 2001 16:42http://openlib.org.uaChapter 13: mmap and DMAPCI_DMA_BIDIRECTIONALIf data can move in either direction, use PCI_DMA_BIDIRECTIONAL.PCI_DMA_NONEThis symbol is provided only as a debugging aid. Attempts to use buffers withthis ‘‘direction’’ will cause a kernel panic.For a number of reasons that we will touch on shortly, it is important to pick theright value for the direction of a streaming DMA mapping. It may be tempting tojust pick PCI_DMA_BIDIRECTIONAL at all times, but on some architectures therewill be a performance penalty to pay for that choice.When you have a single buffer to transfer, map it with pci_map_single:dma_addr_t pci_map_single(struct pci_dev *pdev, void *buffer,size_t size, int direction);The return value is the bus address that you can pass to the device, or NULL ifsomething goes wrong.Once the transferpci_unmap_single:iscomplete,themappingshouldbedeletedwithvoid pci_unmap_single(struct pci_dev *pdev, dma_addr_t bus_addr,size_t size, int direction);Here, the size and direction arguments must match those used to map thebuffer.There are some important rules that apply to streaming DMA mappings:•The buffer must be used only for a transfer that matches the direction valuegiven when it was mapped.•Once a buffer has been mapped, it belongs to the device, not the processor.Until the buffer has been unmapped, the driver should not touch its contentsin any way.

Характеристики

Тип файла
PDF-файл
Размер
7,36 Mb
Тип материала
Высшее учебное заведение

Список файлов книги

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