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

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

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

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

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

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

This modularity makes Linux driverseasy to write, to the point that there are now hundreds of them available.There are a number of reasons to be interested in the writing of Linux devicedrivers. The rate at which new hardware becomes available (and obsolete!) aloneguarantees that driver writers will be busy for the foreseeable future. Individualsmay need to know about drivers in order to gain access to a particular device thatis of interest to them.

Hardware vendors, by making a Linux driver available fortheir products, can add the large and growing Linux user base to their potentialmarkets. And the open source nature of the Linux system means that if the driverwriter wishes, the source to a driver can be quickly disseminated to millions ofusers.122 June 2001 16:32http://openlib.org.uaChapter 1: An Introduction to Device DriversThis book will teach you how to write your own drivers and how to hack aroundin related parts of the kernel. We have taken a device-independent approach; theprogramming techniques and interfaces are presented, whenever possible, withoutbeing tied to any specific device. Each driver is different; as a driver writer, youwill need to understand your specific device well.

But most of the principles andbasic techniques are the same for all drivers. This book cannot teach you aboutyour device, but it will give you a handle on the background you need to makeyour device work.As you learn to write drivers, you will find out a lot about the Linux kernel in general; this may help you understand how your machine works and why thingsaren’t always as fast as you expect or don’t do quite what you want. We’ll introduce new ideas gradually, starting off with very simple drivers and building uponthem; every new concept will be accompanied by sample code that doesn’t needspecial hardware to be tested.This chapter doesn’t actually get into writing code. However, we introduce somebackground concepts about the Linux kernel that you’ll be glad you know later,when we do launch into programming.The Role of the Device DriverAs a programmer, you will be able to make your own choices about your driver,choosing an acceptable trade-off between the programming time required and theflexibility of the result.

Though it may appear strange to say that a driver is “flexible,” we like this word because it emphasizes that the role of a device driver isproviding mechanism, not policy.The distinction between mechanism and policy is one of the best ideas behind theUnix design. Most programming problems can indeed be split into two parts:“what capabilities are to be provided” (the mechanism) and “how those capabilities can be used” (the policy). If the two issues are addressed by different parts ofthe program, or even by different programs altogether, the software package ismuch easier to develop and to adapt to particular needs.For example, Unix management of the graphic display is split between the Xserver, which knows the hardware and offers a unified interface to user programs,and the window and session managers, which implement a particular policy without knowing anything about the hardware.

People can use the same window manager on different hardware, and different users can run different configurations onthe same workstation. Even completely different desktop environments, such asKDE and GNOME, can coexist on the same system. Another example is the layered structure of TCP/IP networking: the operating system offers the socketabstraction, which implements no policy regarding the data to be transferred,while different servers are in charge of the services (and their associated policies).222 June 2001 16:32http://openlib.org.uaThe Role of the Device DriverMoreover, a server like ftpd provides the file transfer mechanism, while users canuse whatever client they prefer; both command-line and graphic clients exist, andanyone can write a new user interface to transfer files.Where drivers are concerned, the same separation of mechanism and policyapplies.

The floppy driver is policy free — its role is only to show the diskette as acontinuous array of data blocks. Higher levels of the system provide policies, suchas who may access the floppy drive, whether the drive is accessed directly or via afilesystem, and whether users may mount filesystems on the drive. Since differentenvironments usually need to use hardware in different ways, it’s important to beas policy free as possible.When writing drivers, a programmer should pay particular attention to this fundamental concept: write kernel code to access the hardware, but don’t force particular policies on the user, since different users have different needs.

The drivershould deal with making the hardware available, leaving all the issues about howto use the hardware to the applications. A driver, then, is flexible if it offers accessto the hardware capabilities without adding constraints. Sometimes, however,some policy decisions must be made.

For example, a digital I/O driver may onlyoffer byte-wide access to the hardware in order to avoid the extra code needed tohandle individual bits.You can also look at your driver from a different perspective: it is a software layerthat lies between the applications and the actual device. This privileged role of thedriver allows the driver programmer to choose exactly how the device shouldappear: different drivers can offer different capabilities, even for the same device.The actual driver design should be a balance between many different considerations. For instance, a single device may be used concurrently by different programs, and the driver programmer has complete freedom to determine how tohandle concurrency.

You could implement memory mapping on the device independently of its hardware capabilities, or you could provide a user library to helpapplication programmers implement new policies on top of the available primitives, and so forth. One major consideration is the trade-off between the desire topresent the user with as many options as possible and the time in which you haveto do the writing as well as the need to keep things simple so that errors don’tcreep in.Policy-free drivers have a number of typical characteristics. These include supportfor both synchronous and asynchronous operation, the ability to be opened multiple times, the ability to exploit the full capabilities of the hardware, and the lack ofsoftware layers to “simplify things” or provide policy-related operations. Drivers ofthis sort not only work better for their end users, but also turn out to be easier towrite and maintain as well.

Being policy free is actually a common target for software designers.322 June 2001 16:32http://openlib.org.uaChapter 1: An Introduction to Device DriversMany device drivers, indeed, are released together with user programs to helpwith configuration and access to the target device. Those programs can range fromsimple utilities to complete graphical applications. Examples include the tunelpprogram, which adjusts how the parallel port printer driver operates, and thegraphical cardctl utility that is part of the PCMCIA driver package.

Often a clientlibrary is provided as well, which provides capabilities that do not need to beimplemented as part of the driver itself.The scope of this book is the kernel, so we’ll try not to deal with policy issues, orwith application programs or support libraries. Sometimes we’ll talk about differentpolicies and how to support them, but we won’t go into much detail about programs using the device or the policies they enforce. You should understand, however, that user programs are an integral part of a software package and that evenpolicy-free packages are distributed with configuration files that apply a defaultbehavior to the underlying mechanisms.Splitting the KernelIn a Unix system, several concurrent pr ocesses attend to different tasks. Each process asks for system resources, be it computing power, memory, network connectivity, or some other resource.

The ker nel is the big chunk of executable code incharge of handling all such requests. Though the distinction between the differentkernel tasks isn’t always clearly marked, the kernel’s role can be split, as shown inFigure 1-1, into the following parts:Pr ocess managementThe kernel is in charge of creating and destroying processes and handlingtheir connection to the outside world (input and output). Communicationamong different processes (through signals, pipes, or interprocess communication primitives) is basic to the overall system functionality and is also handledby the kernel.

In addition, the scheduler, which controls how processes sharethe CPU, is part of process management. More generally, the kernel’s processmanagement activity implements the abstraction of several processes on top ofa single CPU or a few of them.Memory managementThe computer’s memory is a major resource, and the policy used to deal withit is a critical one for system performance.

The kernel builds up a virtualaddressing space for any and all processes on top of the limited availableresources. The different parts of the kernel interact with the memory-management subsystem through a set of function calls, ranging from the simple malloc/fr ee pair to much more exotic functionalities.FilesystemsUnix is heavily based on the filesystem concept; almost everything in Unix canbe treated as a file. The kernel builds a structured filesystem on top ofunstructured hardware, and the resulting file abstraction is heavily used422 June 2001 16:32http://openlib.org.uaSplitting the KernelThe System Call InterfaceProcessmanagementMemorymanagementFilesystemsDevicecontrolNetworkingConcurrency,multitaskingVirtualmemoryFiles and dirs:the VFSTtys &device accessConnectivityArchdependentCodeMemorymanagerFile systemtypesCharacterdevicesNetworksubsystemKernelsubsystemsFeaturesimplementedSoftwaresupportBlock devicesIF driversHardwareCPUMemoryDisks & CDsConsoles,etc.Networkinterfacesfeatures implemented as modulesFigur e 1-1.

A split view of the kernelthroughout the whole system. In addition, Linux supports multiple filesystemtypes, that is, different ways of organizing data on the physical medium. Forexample, diskettes may be formatted with either the Linux-standard ext2filesystem or with the commonly used FAT filesystem.Device controlAlmost every system operation eventually maps to a physical device. With theexception of the processor, memory, and a very few other entities, any and alldevice control operations are performed by code that is specific to the devicebeing addressed. That code is called a device driver.

The kernel must haveembedded in it a device driver for every peripheral present on a system, fromthe hard drive to the keyboard and the tape streamer. This aspect of the kernel’s functions is our primary interest in this book.522 June 2001 16:32http://openlib.org.uaChapter 1: An Introduction to Device DriversNetworkingNetworking must be managed by the operating system because most networkoperations are not specific to a process: incoming packets are asynchronousevents.

The packets must be collected, identified, and dispatched before aprocess takes care of them. The system is in charge of delivering data packetsacross program and network interfaces, and it must control the execution ofprograms according to their network activity.

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