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

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

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

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

The header and macros are specific to PC-class processors; other platforms may need asm constructs toachieve similar results.extern struct timeval xtime;The current time, as calculated at the last timer tick.20522 June 2001 16:37http://openlib.org.uaChapter 6: Flow of Time#include <linux/time.h>void do_gettimeofday(struct timeval *tv);void get_fast_time(struct timeval *tv);The functions return the current time; the former is very high resolution, thelatter may be faster while giving coarser resolution.#include <linux/delay.h>void udelay(unsigned long usecs);void mdelay(unsigned long msecs);The functions introduce delays of an integer number of microseconds and milliseconds.

The former should be used to wait for no longer than one millisecond; the latter should be used with extreme care because these delays areboth busy-loops.int in_interrupt();Returns nonzero if the processor is currently running in interrupt mode.#include <linux/tqueue.h>DECLARE_TASK_QUEUE(variablename);The macro declares a new variable and initializes it.void queue_task(struct tq_struct *task, task_queue *list);The function registers a task for later execution.void run_task_queue(task_queue *list);This function consumes a task queue.task_queue tq_immediate, tq_timer;These predefined task queues are run as soon as possible (for tq_immediate), or after each timer tick (for tq_timer).int schedule_task(struct tq_struct *task);Schedules a task to be run on the scheduler queue.#include <linux/interrupt.h>DECLARE_TASKLET(name, function, data)DECLARE_TASKLET_DISABLED(name, function, data)Declare a tasklet structure that will call the given function (passing it the givenunsigned long data) when the tasklet is executed.

The second form initializes the tasklet to a disabled state, keeping it from running until it is explicitlyenabled.void tasklet_schedule(struct tasklet_struct *tasklet);Schedules the given tasklet for running. If the tasklet is enabled, it will be runshortly on the same CPU that ran the first call to tasklet_schedule.20622 June 2001 16:37http://openlib.org.uaQuick Referencetasklet_enable(struct tasklet_struct *tasklet);tasklet_disable(struct tasklet_struct *tasklet);These functions respectively enable and disable the given tasklet. A disabledtasklet can be scheduled, but will not run until it has been enabled again.void tasklet_kill(struct tasklet_struct *tasklet);Causes an ‘‘infinitely rescheduling’’ tasklet to cease execution.

This functioncan block and may not be called in interrupt time.#include <linux/timer.h>void init_timer(struct timer_list * timer);This function initializes a newly allocated timer.void add_timer(struct timer_list * timer);This function inserts the timer into the global list of pending timers.int mod_timer(struct timer_list *timer, unsigned longexpires);This function is used to change the expiration time of an already scheduledtimer structure.int del_timer(struct timer_list * timer);del_timer removes a timer from the list of pending timers.

If the timer wasactually queued, del_timer returns 1; otherwise, it returns 0.int del_timer_sync(struct timer_list *timer);This function is similar to del_timer, but guarantees that the function is notcurrently running on other CPUs.20722 June 2001 16:37http://openlib.org.uaCHAPTER SEVENGETTING HOLD OFMEMORYThus far, we have used kmalloc and kfr ee for the allocation and freeing of memory. The Linux kernel offers a richer set of memory allocation primitives, however.In this chapter we look at other ways of making use of memory in device driversand at how to make the best use of your system’s memory resources.

We will notget into how the different architectures actually administer memory. Modules arenot involved in issues of segmentation, paging, and so on, since the kernel offersa unified memory management interface to the drivers. In addition, we won’tdescribe the internal details of memory management in this chapter, but will deferit to ‘‘Memory Management in Linux’’ in Chapter 13.The Real Story of kmallocThe kmalloc allocation engine is a powerful tool, and easily learned because of itssimilarity to malloc. The function is fast—unless it blocks—and it doesn’t clear thememory it obtains; the allocated region still holds its previous content.

The allocated region is also contiguous in physical memory. In the next few sections, wetalk in detail about kmalloc, so you can compare it with the memory allocationtechniques that we discuss later.The Flags ArgumentThe first argument to kmalloc is the size of the block to be allocated. The secondargument, the allocation flags, is much more interesting, because it controls thebehavior of kmalloc in a number of ways.The most-used flag, GFP_KERNEL, means that the allocation (internally performedby calling, eventually, get_fr ee_pages, which is the source of the GFP_ prefix) isperformed on behalf of a process running in kernel space. In other words, this20822 June 2001 16:38http://openlib.org.uaThe Real Story of kmallocmeans that the calling function is executing a system call on behalf of a process.Using GFP_KERNEL means that kmalloc can put the current process to sleep waiting for a page when called in low-memory situations.

A function that allocatesmemory using GFP_KERNEL must therefore be reentrant. While the current process sleeps, the kernel takes proper action to retrieve a memory page, either byflushing buffers to disk or by swapping out memory from a user process.GFP_KERNEL isn’t always the right allocation flag to use; sometimes kmalloc iscalled from outside a process’s context. This type of call can happen, for instance,in interrupt handlers, task queues, and kernel timers. In this case, the currentprocess should not be put to sleep, and the driver should use a flag ofGFP_ATOMIC instead. The kernel normally tries to keep some free pages aroundin order to fulfill atomic allocation. When GFP_ATOMIC is used, kmalloc can useeven the last free page.

If that last page does not exist, however, the allocation willfail.Other flags can be used in place of or in addition to GFP_KERNEL andGFP_ATOMIC, although those two cover most of the needs of device drivers. Allthe flags are defined in <linux/mm.h>: individual flags are prefixed with a double underscore, like _ _GFP_DMA; collections of flags lack the prefix and aresometimes called allocation priorities.GFP_KERNELNormal allocation of kernel memory.

May sleep.GFP_BUFFERUsed in managing the buffer cache, this priority allows the allocator to sleep.It differs from GFP_KERNEL in that fewer attempts will be made to free memory by flushing dirty pages to disk; the purpose here is to avoid deadlockswhen the I/O subsystems themselves need memory.GFP_ATOMICUsed to allocate memory from interrupt handlers and other code outside of aprocess context. Never sleeps.GFP_USERUsed to allocate memory on behalf of the user.

It may sleep, and is a low-priority request.GFP_HIGHUSERLike GFP_USER, but allocates from high memory, if any. High memory isdescribed in the next subsection._ _GFP_DMAThis flag requests memory usable in DMA data transfers to/from devices. Itsexact meaning is platform dependent, and the flag can be OR’d to eitherGFP_KERNEL or GFP_ATOMIC.20922 June 2001 16:38http://openlib.org.uaChapter 7: Getting Hold of Memory_ _GFP_HIGHMEMThe flag requests high memory, a platform-dependent feature that has noeffect on platforms that don’t support it.

It is part of the GFP_HIGHUSER maskand has little use elsewhere.Memory zonesBoth _ _GFP_DMA and _ _GFP_HIGHMEM have a platform-dependent role,although their use is valid for all platforms.Version 2.4 of the kernel knows about three memory zones: DMA-capable memory, normal memory, and high memory. While allocation normally happens in thenor mal zone, setting either of the bits just mentioned requires memory to be allocated from a different zone. The idea is that every computer platform that mustknow about special memory ranges (instead of considering all RAM equivalent)will fall into this abstraction.DMA-capable memory is the only memory that can be involved in DMA data transfers with peripheral devices.

This restriction arises when the address bus used toconnect peripheral devices to the processor is limited with respect to the addressbus used to access RAM. For example, on the x86, devices that plug into the ISAbus can only address memory from 0 to 16 MB. Other platforms have similarneeds, although usually less stringent than the ISA one.*High memory is memory that requires special handling to be accessed.

It made itsappearance in kernel memory management when support for the Pentium II Virtual Memory Extension was implemented during 2.3 development to access up to64 GB of physical memory. High memory is a concept that only applies to the x86and SPARC platforms, and the two implementations are different.Whenever a new page is allocated to fulfill the kmalloc request, the kernel buildsa list of zones that can be used in the search. If _ _GFP_DMA is specified, only theDMA zone is searched: if no memory is available at low addresses, allocation fails.If no special flag is present, both normal and DMA memory is searched; if_ _GFP_HIGHMEM is set, then all three zones are used to search a free page.If the platform has no concept of high memory or it has been disabled in the kernel configuration, _ _GFP_HIGHMEM is defined as 0 and has no effect.The mechanism behind memory zones is implemented in mm/page_alloc.c, whileinitialization of the zone resides in platform-specific files, usually in mm/init.cwithin the arch tree.

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

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

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

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