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

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

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

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

Two address ranges, 512 MB each, are directly mapped tophysical addresses. Any memory access to either of those address ranges bypassesthe MMU, and any access to one of those ranges bypasses the cache as well. Asection of these 512 megabytes is reserved for peripheral devices, and drivers canaccess their I/O memory directly by using the noncached address range.Other platforms have other means to offer directly mapped address ranges: someof them have special address spaces to dereference physical addresses (for example, SPARC64 uses a special ‘‘address space identifier’’ for this aim), and others usevirtual addresses set up to bypass processor caches.When you need to access a directly mapped I/O memory area, you still shouldn’tdereference your I/O pointers, even though, on some architectures, you may wellbe able to get away with doing exactly that.

To write code that will work acrosssystems and kernel versions, however, you must avoid direct accesses and insteaduse the following functions.unsigned readb(address);unsigned readw(address);unsigned readl(address);These macros are used to retrieve 8-bit, 16-bit, and 32-bit data values from I/Omemory. The advantage of using macros is the typelessness of the argument:address is cast before being used, because the value ‘‘is not clearly either aninteger or a pointer, and we will accept both’’ (from asm-alpha/io.h).

Neitherthe reading nor the writing functions check the validity of address, becausethey are meant to be as fast as pointer dereferencing (we already know thatsometimes they actually expand into pointer dereferencing).void writeb(unsigned value, address);void writew(unsigned value, address);void writel(unsigned value, address);Like the previous functions, these functions (macros) are used to write 8-bit,16-bit, and 32-bit data items.24022 June 2001 16:39http://openlib.org.uaUsing I/O Memorymemset_io(address, value, count);When you need to call memset on I/O memory, this function does what youneed, while keeping the semantics of the original memset.memcpy_fromio(dest, source, num);memcpy_toio(dest, source, num);These functions move blocks of data to and from I/O memory and behavelike the C library routine memcpy.In modern versions of the kernel, these functions are available across all architectures. The implementation will vary, however; on some they are macros thatexpand to pointer operations, and on others they are real functions.

As a driverwriter, however, you need not worry about how they work, as long as you usethem.Some 64-bit platformsmemory operations onleftover from the timesnaming used for 32-bitwould make things stillalso offer readq and writeq, for quad-word (eight-byte)the PCI bus. The quad-word nomenclature is a historicalwhen all real processors had 16-bit words. Actually, the Lvalues has become incorrect too, but renaming everythingmore confused.Reusing short for I/O MemoryThe short sample module, introduced earlier to access I/O ports, can be used toaccess I/O memory as well. To this aim, you must tell it to use I/O memory atload time; also, you’ll need to change the base address to make it point to yourI/O region.For example, this is how we used short to light the debug LEDs on a MIPS development board:mips.root# ./short_load use_mem=1 base=0xb7ffffc0mips.root# echo -n 7 > /dev/short0Use of short for I/O memory is the same as it is for I/O ports; however, since nopausing or string instructions exist for I/O memory, access to /dev/short0p and/dev/short0s performs the same operation as /dev/short0.The following fragment shows the loop used by short in writing to a memory location:while (count--) {writeb(*(ptr++), address);wmb();}Note the use of a write memory barrier here.

Because writeb likely turns into adirect assignment on many architectures, the memory barrier is needed to ensurethat the writes happen in the expected order.24122 June 2001 16:39http://openlib.org.uaChapter 8: Hardware ManagementSoftware-Mapped I/O MemoryThe MIPS class of processors notwithstanding, directly mapped I/O memory ispretty rare in the current platform arena; this is especially true when a peripheralbus is used with memory-mapped devices (which is most of the time).The most common hardware and software arrangement for I/O memory is this:devices live at well-known physical addresses, but the CPU has no predefined virtual address to access them. The well-known physical address can be either hardwired in the device or assigned by system firmware at boot time.

The former istrue, for example, of ISA devices, whose addresses are either burned in devicelogic circuits, statically assigned in local device memory, or set by means of physical jumpers. The latter is true of PCI devices, whose addresses are assigned by system software and written to device memory, where they persist only while thedevice is powered on.Either way, for software to access I/O memory, there must be a way to assign avirtual address to the device. This is the role of the ior emap function, introducedin “vmalloc and Friends.” The function, which was covered in the previous chapterbecause it is related to memory use, is designed specifically to assign virtualaddresses to I/O memory regions. Moreover, kernel developers implementedior emap so that it doesn’t do anything if applied to directly mapped I/O addresses.Once equipped with ior emap (and iounmap), a device driver can access any I/Omemory address, whether it is directly mapped to virtual address space or not.Remember, though, that these addresses should not be dereferenced directly;instead, functions like readb should be used.

We could thus arrange short to workwith both MIPS I/O memory and the more common ISA/PCI x86 memory byequipping the module with ior emap/iounmap calls whenever the use_memparameter is set.Before we show how short calls the functions, we’d better review the prototypesof the functions and introduce a few details that we passed over in the previouschapter.The functions are called according to the following definition:#include <asm/io.h>void *ioremap(unsigned long phys_addr, unsigned long size);void *ioremap_nocache(unsigned long phys_addr, unsigned long size);void iounmap(void * addr);First of all, you’ll notice the new function ior emap_nocache.

We didn’t cover it inChapter 7, because its meaning is definitely hardware related. Quoting from one ofthe kernel headers: ‘‘It’s useful if some control registers are in such an area andwrite combining or read caching is not desirable.’’ Actually, the function’s implementation is identical to ior emap on most computer platforms: in situations inwhich all of I/O memory is already visible through noncacheable addresses,there’s no reason to implement a separate, noncaching version of ior emap.24222 June 2001 16:39http://openlib.org.uaUsing I/O MemoryAnother important feature of ior emap is the different behavior of the 2.0 versionwith respect to later ones. Under Linux 2.0, the function (called, remember,vr emap at the time) refused to remap any non-page-aligned memory region.

Thiswas a sensible choice, since at CPU level everything happens with page-sizedgranularity. However, sometimes you need to map small regions of I/O registerswhose (physical) address is not page aligned. To fit this new need, version 2.1.131and later of the kernel are able to remap unaligned addresses.Our short module, in order to be backward portable to version 2.0 and to be ableto access non-page-aligned registers, includes the following code instead of callingior emap directly:/* Remap a not (necessarily) aligned port region */void *short_remap(unsigned long phys_addr){/* The code comes mainly from arch/any/mm/ioremap.c */unsigned long offset, last_addr, size;last_addr = phys_addr + SHORT_NR_PORTS - 1;offset = phys_addr & ˜PAGE_MASK;/* Adjust the begin and end to remap a full page */phys_addr &= PAGE_MASK;size = PAGE_ALIGN(last_addr) - phys_addr;return ioremap(phys_addr, size) + offset;}/* Unmap a region obtained with short_remap */void short_unmap(void *virt_add){iounmap((void *)((unsigned long)virt_add & PAGE_MASK));}ISA Memory Below 1 MBOne of the most well-known I/O memory regions is the ISA range as found onpersonal computers.

This is the memory range between 640 KB (0xA0000) and 1MB (0x100000). It thus appears right in the middle of regular system RAM. Thispositioning may seem a little strange; it is an artifact of a decision made in theearly 1980s, when 640 KB of memory seemed like more than anybody would everbe able to use.This memory range belongs to the non-directly-mapped class of memory.* You* Actually, this is not completely true.

The memory range is so small and so frequentlyused that the kernel builds page tables at boot time to access those addresses. However,the virtual address used to access them is not the same as the physical address, and thusior emap is needed anyway. Moreover, version 2.0 of the kernel had that range directlymapped. See “Backward Compatibility” for 2.0 issues.24322 June 2001 16:39http://openlib.org.uaChapter 8: Hardware Managementcan read/write a few bytes in that memory range using the short module asexplained previously, that is, by setting use_mem at load time.Although ISA I/O memory exists only in x86-class computers, we think it’s worthspending a few words and a sample driver on it.We are not going to discuss PCI memory in this chapter, since it is the cleanestkind of I/O memory: once you know the physical address you can simply remapand access it.

The ‘‘problem’’ with PCI I/O memory is that it doesn’t lend itself to aworking example for this chapter, because we can’t know in advance the physicaladdresses your PCI memory is mapped to, nor whether it’s safe to access either ofthose ranges. We chose to describe the ISA memory range because it’s both lessclean and more suitable to running sample code.To demonstrate access to ISA memory, we will make use of yet another silly littlemodule (part of the sample sources). In fact, this one is called silly, as an acronymfor Simple Tool for Unloading and Printing ISA Data, or something like that.The module supplements the functionality of short by giving access to the whole384-KB memory space and by showing all the different I/O functions.

It featuresfour device nodes that perform the same task using different data transfer functions. The silly devices act as a window over I/O memory, in a way similar to/dev/mem. You can read and write data, and lseek to an arbitrary I/O memoryaddress.Because silly provides access to ISA memory, it must start by mapping the physicalISA addresses into kernel virtual addresses.

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

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

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

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