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

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

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

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

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

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

kunmap deletes the mapping for the given page.42122 June 2001 16:42http://openlib.org.uaChapter 13: mmap and DMA#include <linux/iobuf.h>void kiobuf_init(struct kiobuf *iobuf);int alloc_kiovec(int number, struct kiobuf **iobuf);void free_kiovec(int number, struct kiobuf **iobuf);These functions handle the allocation, initialization, and freeing of kernel I/Obuffers. kiobuf_init initializes a single kiobuf, but is rarely used; alloc_kiovec,which allocates and initializes a vector of kiobufs, is usually used instead. Avector of kiobufs is freed with fr ee_kiovec.int lock_kiovec(int nr, struct kiobuf *iovec[], int wait);int unlock_kiovec(int nr, struct kiobuf *iovec[]);These functions lock a kiovec in memory, and release it.

They are unnecessarywhen using kiobufs for I/O to user-space memory.int map_user_kiobuf(int rw, struct kiobuf *iobuf, unsignedlong address, size_t len);void unmap_kiobuf(struct kiobuf *iobuf);map_user_kiobuf maps a buffer in user space into the given kernel I/O buffer;unmap_kiobuf undoes that mapping.#include <asm/io.h>unsigned long virt_to_bus(volatile void * address);void * bus_to_virt(unsigned long address);These functions convert between kernel virtual and bus addresses. Busaddresses must be used to talk to peripheral devices.#include <linux/pci.h>The header file required to define the following functions.int pci_dma_supported(struct pci_dev *pdev, dma_addr_tmask);For peripherals that cannot address the full 32-bit range, this function determines whether DMA can be supported at all on the host system.void *pci_alloc_consistent(struct pci_dev *pdev, size_tsize, dma_addr_t *bus_addr)void pci_free_consistent(struct pci_dev *pdev, size_t size,void *cpuaddr, dma_handle_t bus_addr);These functions allocate and free consistent DMA mappings, for a buffer thatwill last the lifetime of the driver.PCI_DMA_TODEVICEPCI_DMA_FROMDEVICEPCI_DMA_BIDIRECTIONALPCI_DMA_NONEThese symbols are used to tell the streaming mapping functions the directionin which data will be moving to or from the buffer.42222 June 2001 16:42http://openlib.org.uaQuick Referencedma_addr_t pci_map_single(struct pci_dev *pdev, void*buffer, size_t size, int direction);void pci_unmap_single(struct pci_dev *pdev, dma_addr_tbus_addr, size_t size, int direction);Create and destroy a single-use, streaming DMA mapping.void pci_sync_single(struct pci_dev *pdev, dma_handle_tbus_addr, size_t size, int direction)Synchronizes a buffer that has a streaming mapping.

This function must beused if the processor must access a buffer while the streaming mapping is inplace (i.e., while the device owns the buffer).struct scatterlist { /* . . . */ };dma_addr_t sg_dma_address(struct scatterlist *sg);unsigned int sg_dma_len(struct scatterlist *sg);The scatterlist structure describes an I/O operation that involves morethan one buffer. The macros sg_dma_addr ess and sg_dma_len may be used toextract bus addresses and buffer lengths to pass to the device when implementing scatter-gather operations.pci_map_sg(struct pci_dev *pdev, struct scatterlist *list,int nents, int direction);pci_unmap_sg(struct pci_dev *pdev, struct scatterlist *list,int nents, int direction);pci_dma_sync_sg(struct pci_dev *pdev, struct scatterlist*sg, int nents, int direction)pci_map_sg maps a scatter-gather operation, and pci_unmap_sg undoes thatmapping.

If the buffers must be accessed while the mapping is active,pci_dma_sync_sg may be used to synchronize things./proc/dmaThis file contains a textual snapshot of the allocated channels in the DMA controllers. PCI-based DMA is not shown because each board works independently, without the need to allocate a channel in the DMA controller.#include <asm/dma.h>This header defines or prototypes all the functions and macros related toDMA. It must be included to use any of the following symbols.int request_dma(unsigned int channel, const char *name);void free_dma(unsigned int channel);These functions access the DMA registry. Registration must be performedbefore using ISA DMA channels.42322 June 2001 16:42http://openlib.org.uaChapter 13: mmap and DMAunsigned long claim_dma_lock();void release_dma_lock(unsigned long flags);These functions acquire and release the DMA spinlock, which must be heldprior to calling the other ISA DMA functions described later in this list.

Theyalso disable and reenable interrupts on the local processor.void set_dma_mode(unsigned int channel, char mode);void set_dma_addr(unsigned int channel, unsigned int addr);void set_dma_count(unsigned int channel, unsigned intcount);These functions are used to program DMA information in the DMA controller.addr is a bus address.void disable_dma(unsigned int channel);void enable_dma(unsigned int channel);A DMA channel must be disabled during configuration. These functionschange the status of the DMA channel.int get_dma_residue(unsigned int channel);If the driver needs to know how a DMA transfer is proceeding, it can call thisfunction, which returns the number of data transfers that are yet to be completed.

After successful completion of DMA, the function returns 0; the valueis unpredictable while data is being transferred.void clear_dma_ff(unsigned int channel)The DMA flip-flop is used by the controller to transfer 16-bit values by meansof two 8-bit operations. It must be cleared before sending any data to the controller.42422 June 2001 16:42http://openlib.org.uaCHAPTER FOURTEENNETWORK DRIVERSWe are now through discussing char and block drivers and are ready to move onto the fascinating world of networking. Network interfaces are the third standardclass of Linux devices, and this chapter describes how they interact with the rest ofthe kernel.The role of a network interface within the system is similar to that of a mountedblock device.

A block device registers its features in the blk_dev array and otherkernel structures, and it then “transmits” and “receives” blocks on request, bymeans of its request function. Similarly, a network interface must register itself inspecific data structures in order to be invoked when packets are exchanged withthe outside world.There are a few important differences between mounted disks and packet-deliveryinterfaces. To begin with, a disk exists as a special file in the /dev directory,whereas a network interface has no such entry point. The normal file operations(read, write, and so on) do not make sense when applied to network interfaces, soit is not possible to apply the Unix “everything is a file” approach to them. Thus,network interfaces exist in their own namespace and export a different set ofoperations.Although you may object that applications use the read and write system callswhen using sockets, those calls act on a software object that is distinct from theinterface.

Several hundred sockets can be multiplexed on the same physical interface.But the most important difference between the two is that block drivers operateonly in response to requests from the kernel, whereas network drivers receivepackets asynchronously from the outside. Thus, while a block driver is asked tosend a buffer toward the kernel, the network device asks to push incomingpackets toward the kernel.

The kernel interface for network drivers is designed forthis different mode of operation.42522 June 2001 16:43http://openlib.org.uaChapter 14: Network DriversNetwork drivers also have to be prepared to support a number of administrativetasks, such as setting addresses, modifying transmission parameters, and maintaining traffic and error statistics. The API for network drivers reflects this need, andthus looks somewhat different from the interfaces we have seen so far.The network subsystem of the Linux kernel is designed to be completely protocolindependent.

This applies to both networking protocols (IP versus IPX or otherprotocols) and hardware protocols (Ethernet versus token ring, etc.). Interactionbetween a network driver and the kernel proper deals with one network packet ata time; this allows protocol issues to be hidden neatly from the driver and thephysical transmission to be hidden from the protocol.This chapter describes how the network interfaces fit in with the rest of the Linuxkernel and shows a memory-based modularized network interface, which is called(you guessed it) snull.

To simplify the discussion, the interface uses the Ethernethardware protocol and transmits IP packets. The knowledge you acquire fromexamining snull can be readily applied to protocols other than IP, and writing anon-Ethernet driver is only different in tiny details related to the actual networkprotocol.This chapter doesn’t talk about IP numbering schemes, network protocols, orother general networking concepts.

Such topics are not (usually) of concern to thedriver writer, and it’s impossible to offer a satisfactory overview of networkingtechnology in less than a few hundred pages. The interested reader is urged torefer to other books describing networking issues.The networking subsystem has seen many changes over the years as the kerneldevelopers have striven to provide the best performance possible. The bulk of thischapter describes network drivers as they are implemented in the 2.4 kernel.

Onceagain, the sample code works on the 2.0 and 2.2 kernels as well, and we cover thedifferences between those kernels and 2.4 at the end of the chapter.One note on terminology is called for before getting into network devices. Thenetworking world uses the term octet to refer to a group of eight bits, which isgenerally the smallest unit understood by networking devices and protocols. Theterm byte is almost never encountered in this context. In keeping with standardusage, we will use octet when talking about networking devices.How snull Is DesignedThis section discusses the design concepts that led to the snull network interface.Although this information might appear to be of marginal use, failing to understand this driver might lead to problems while playing with the sample code.The first, and most important, design decision was that the sample interfacesshould remain independent of real hardware, just like most of the sample code42622 June 2001 16:43http://openlib.org.uaHow snull Is Designedused in this book.

This constraint led to something that resembles the loopbackinterface. snull is not a loopback interface, however; it simulates conversationswith real remote hosts in order to better demonstrate the task of writing a networkdriver. The Linux loopback driver is actually quite simple; it can be found indrivers/net/loopback.c.Another feature of snull is that it supports only IP traffic. This is a consequence ofthe internal workings of the interface —snull has to look inside and interpret thepackets to properly emulate a pair of hardware interfaces.

Real interfaces don’tdepend on the protocol being transmitted, and this limitation of snull doesn’taffect the fragments of code that are shown in this chapter.Assigning IP NumbersThe snull module creates two interfaces. These interfaces are different from a simple loopback in that whatever you transmit through one of the interfaces loopsback to the other one, not to itself.

It looks like you have two external links, butactually your computer is replying to itself.Unfortunately, this effect can’t be accomplished through IP-number assignmentalone, because the kernel wouldn’t send out a packet through interface A that wasdirected to its own interface B. Instead, it would use the loopback channel withoutpassing through snull. To be able to establish a communication through the snullinterfaces, the source and destination addresses need to be modified during datatransmission. In other words, packets sent through one of the interfaces should bereceived by the other, but the receiver of the outgoing packet shouldn’t be recognized as the local host.

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