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

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

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

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

We’ll revisit these topics in Chapter 13.* It’s interesting to note that the limit is only in force for the ISA bus; an x86 device thatplugs into the PCI bus can perform DMA with all nor mal memory.21022 June 2001 16:38http://openlib.org.uaLookaside CachesThe Size ArgumentThe kernel manages the system’s physical memory, which is available only inpage-sized chunks. As a result, kmalloc looks rather different than a typical userspace malloc implementation.

A simple, heap-oriented allocation technique wouldquickly run into trouble; it would have a hard time working around the pageboundaries. Thus, the kernel uses a special page-oriented allocation technique toget the best use from the system’s RAM.Linux handles memory allocation by creating a set of pools of memory objects offixed sizes. Allocation requests are handled by going to a pool that holds sufficiently large objects, and handing an entire memory chunk back to the requester.The memory management scheme is quite complex, and the details of it are notnormally all that interesting to device driver writers.

After all, the implementationcan change—as it did in the 2.1.38 kernel — without affecting the interface seen bythe rest of the kernel.The one thing driver developers should keep in mind, though, is that the kernelcan allocate only certain predefined fixed-size byte arrays. If you ask for an arbitrary amount of memory, you’re likely to get slightly more than you asked for, upto twice as much.

Also, programmers should remember that the minimum memorythat kmalloc handles is as big as 32 or 64, depending on the page size used by thecurrent architecture.The data sizes available are generally powers of two. In the 2.0 kernel, the available sizes were actually slightly less than a power of two, due to control flagsadded by the management system.

If you keep this fact in mind, you’ll use memory more efficiently. For example, if you need a buffer of about 2000 bytes andrun Linux 2.0, you’re better off asking for 2000 bytes, rather than 2048. Requestingexactly a power of two is the worst possible case with any kernel older than2.1.38 — the kernel will allocate twice as much as you requested. This is why scullused 4000 bytes per quantum instead of 4096.You can find the exact values used for the allocation blocks in mm/kmalloc.c (withthe 2.0 kernel) or mm/slab.c (in current kernels), but remember that they canchange again without notice.

The trick of allocating less than 4 KB works well forscull with all 2.x kernels, but it’s not guaranteed to be optimal in the future.In any case, the maximum size that can be allocated by kmalloc is 128 KB—slightly less with 2.0 kernels. If you need more than a few kilobytes, however,there are better ways than kmalloc to obtain memory, as outlined next.Lookaside CachesA device driver often ends up allocating many objects of the same size, over andover. Given that the kernel already maintains a set of memory pools of objects thatare all the same size, why not add some special pools for these high-volume21122 June 2001 16:38http://openlib.org.uaChapter 7: Getting Hold of Memoryobjects? In fact, the kernel does implement this sort of lookaside cache.

Devicedrivers normally do not exhibit the sort of memory behavior that justifies using alookaside cache, but there can be exceptions; the USB and ISDN drivers in Linux2.4 use caches.Linux memory caches have a type of kmem_cache_t and are created with a callto kmem_cache_cr eate:kmem_cache_t * kmem_cache_create(const char *name, size_t size,size_t offset, unsigned long flags,void (*constructor)(void *, kmem_cache_t *,unsigned long flags),void (*destructor)(void *, kmem_cache_t *,unsigned long flags) );The function creates a new cache object that can host any number of memoryareas all of the same size, specified by the size argument.

The name argument isassociated with this cache and functions as housekeeping information usable intracking problems; usually, it is set to the name of the type of structure that will becached. The maximum length for the name is 20 characters, including the trailingterminator.The offset is the offset of the first object in the page; it can be used to ensure aparticular alignment for the allocated objects, but you most likely will use 0 torequest the default value. flags controls how allocation is done, and is a bitmask of the following flags:SLAB_NO_REAPSetting this flag protects the cache from being reduced when the system islooking for memory.

You would not usually need to set this flag.SLAB_HWCACHE_ALIGNThis flag requires each data object to be aligned to a cache line; actual alignment depends on the cache layout of the host platform. This is usually a goodchoice.SLAB_CACHE_DMAThis flag requires each data object to be allocated in DMA-capable memory.The constructor and destructor arguments to the function are optionalfunctions (but there can be no destructor without a constructor); the former can beused to initialize newly allocated objects and the latter can be used to “clean up”objects prior to their memory being released back to the system as a whole.Constructors and destructors can be useful, but there are a few constraints that youshould keep in mind. A constructor is called when the memory for a set of objectsis allocated; because that memory may hold several objects, the constructor maybe called multiple times.

You cannot assume that the constructor will be called as21222 June 2001 16:38http://openlib.org.uaLookaside Cachesan immediate effect of allocating an object. Similarly, destructors can be called atsome unknown future time, not immediately after an object has been freed. Constructors and destructors may or may not be allowed to sleep, according towhether they are passed the SLAB_CTOR_ATOMIC flag (where CTOR is short forconstructor).For convenience, a programmer can use the same function for both the constructor and destructor; the slab allocator always passes the SLAB_CTOR_CONSTRUCTOR flag when the callee is a constructor.Once a cache of objects is created, you can allocate objects from it by callingkmem_cache_alloc:void *kmem_cache_alloc(kmem_cache_t *cache, int flags);Here, the cache argument is the cache you have created previously; the flags arethe same as you would pass to kmalloc, and are consulted if kmem_cache_allocneeds to go out and allocate more memory itself.To free an object, use kmem_cache_fr ee:void kmem_cache_free(kmem_cache_t *cache, const void *obj);When driver code is finished with the cache, typically when the module isunloaded, it should free its cache as follows:int kmem_cache_destroy(kmem_cache_t *cache);The destroy option will succeed only if all objects allocated from the cache havebeen returned to it.

A module should thus check the return status fromkmem_cache_destr oy; a failure indicates some sort of memory leak within themodule (since some of the objects have been dropped).One side benefit to using lookaside caches is that the kernel maintains statistics oncache usage. There is even a kernel configuration option that enables the collection of extra statistical information, but at a noticeable runtime cost. Cache statistics may be obtained from /pr oc/slabinfo.A scull Based on the Slab Caches: scullcTime for an example.

scullc is a cut-down version of the scull module that implements only the bare device — the persistent memory region. Unlike scull, whichuses kmalloc, scullc uses memory caches. The size of the quantum can be modified at compile time and at load time, but not at runtime—that would require creating a new memory cache, and we didn’t want to deal with these unneededdetails. The sample module refuses to compile with version 2.0 of the kernelbecause memory caches were not there, as explained in “Backward Compatibility”later in the chapter.21322 June 2001 16:38http://openlib.org.uaChapter 7: Getting Hold of Memoryscullc is a complete example that can be used to make tests. It differs from scullonly in a few lines of code.

This is how it allocates memory quanta:/* Allocate a quantum using the memory cache */if (!dptr->data[s_pos]) {dptr->data[s_pos] =kmem_cache_alloc(scullc_cache, GFP_KERNEL);if (!dptr->data[s_pos])goto nomem;memset(dptr->data[s_pos], 0, scullc_quantum);}And these lines release memory:for (i = 0; i < qset; i++)if (dptr->data[i])kmem_cache_free(scullc_cache, dptr->data[i]);kfree(dptr->data);To support use of scullc_cache, these few lines are included in the file atproper places:/* declare one cache pointer: use it for all devices */kmem_cache_t *scullc_cache;/* init_module: create a cache for our quanta */scullc_cache =kmem_cache_create("scullc", scullc_quantum,0, SLAB_HWCACHE_ALIGN,NULL, NULL); /* no ctor/dtor */if (!scullc_cache) {result = -ENOMEM;goto fail_malloc2;}/* cleanup_module: release the cache of our quanta */kmem_cache_destroy(scullc_cache);The main differences in passing from scull to scullc are a slight speed improvement and better memory use.

Since quanta are allocated from a pool of memoryfragments of exactly the right size, their placement in memory is as dense as possible, as opposed to scull quanta, which bring in an unpredictable memory fragmentation.get_free_page and FriendsIf a module needs to allocate big chunks of memory, it is usually better to use apage-oriented technique. Requesting whole pages also has other advantages,which will be introduced later, in “The mmap Device Operation” in Chapter 13.21422 June 2001 16:38http://openlib.org.uaget_free_page and FriendsTo allocate pages, the following functions are available:get_zer oed_pageReturns a pointer to a new page and fills the page with zeros._ _get_fr ee_pageSimilar to get_zer oed_page, but doesn’t clear the page._ _get_fr ee_pagesAllocates and returns a pointer to the first byte of a memory area that is several (physically contiguous) pages long, but doesn’t zero the area._ _get_dma_ pagesSimilar to get_fr ee_pages, but guarantees that the allocated memory is DMAcapable.

If you use version 2.2 or later of the kernel, you can simply use_ _get_fr ee_pages and pass the _ _GFP_DMA flag; if you want backward compatibility with 2.0, you need to call this function instead.The prototypes for the functions follow:unsignedunsignedunsignedunsignedlonglonglonglongget_zeroed_page(int flags);_ _get_free_page(int flags);_ _get_free_pages(int flags, unsigned long order);_ _get_dma_pages(int flags, unsigned long order);The flags argument works in the same way as with kmalloc; usually eitherGFP_KERNEL or GFP_ATOMIC is used, perhaps with the addition of the_ _GFP_DMA flag (for memory that can be used for direct memory access operations) or _ _GFP_HIGHMEM when high memory can be used. order is the basetwo logarithm of the number of pages you are requesting or freeing (i.e., log2N).For example, order is 0 if you want one page and 3 if you request eight pages.If order is too big (no contiguous area of that size is available), the page allocation will fail.

The maximum value of order was 5 in Linux 2.0 (corresponding to32 pages) and 9 with later versions (corresponding to 512 pages: 2 MB on mostplatforms). Anyway, the bigger order is, the more likely it is that the allocationwill fail.When a program is done with the pages, it can free them with one of the following functions. The first function is a macro that falls back on the second:void free_page(unsigned long addr);void free_pages(unsigned long addr, unsigned long order);If you try to free a different number of pages than you allocated, the memory mapwill become corrupted and the system will get in trouble at a later time.It’s worth stressing that get_fr ee_pages and the other functions can be called at anytime, subject to the same rules we saw for kmalloc. The functions can fail to allocate memory in certain circumstances, particularly when GFP_ATOMIC is used.Therefore, the program calling these allocation functions must be prepared to handle an allocation failure.21522 June 2001 16:38http://openlib.org.uaChapter 7: Getting Hold of MemoryIt has been said that if you want to live dangerously, you can assume that neitherkmalloc nor the underlying get_fr ee_pages will ever fail when called with a priorityof GFP_KERNEL.

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

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

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

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