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

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

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

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

In the early days of the Linux kernel,one could simply assign a pointer to an ISA address of interest, then dereference itdirectly. In the modern world, though, we must work with the virtual memory system and remap the memory range first. This mapping is done with ior emap, asexplained earlier for short:#define ISA_BASE#define ISA_MAX0xA00000x100000/* for general memory access *//* this line appears in silly_init */io_base = ioremap(ISA_BASE, ISA_MAX - ISA_BASE);ior emap returns a pointer value that can be used with readb and the other functions explained in the section “Directly Mapped Memory.”Let’s look back at our sample module to see how these functions might be used./dev/sillyb, featuring minor number 0, accesses I/O memory with readb andwriteb.

The following code shows the implementation for read, which makes theaddress range 0xA0000-0xFFFFF available as a virtual file in the range0-0x5FFFF. The read function is structured as a switch statement over the different access modes; here is the sillyb case:24422 June 2001 16:39http://openlib.org.uaUsing I/O Memorycase M_8:while (count) {*ptr = readb(add);add++; count--; ptr++;}break;The next two devices are /dev/sillyw (minor number 1) and /dev/sillyl (minor number 2). They act like /dev/sillyb, except that they use 16-bit and 32-bit functions.Here’s the write implementation of sillyl, again part of a switch:case M_32:while (count >= 4) {writel(*(u32 *)ptr, add);add+=4; count-=4; ptr+=4;}break;The last device is /dev/sillycp (minor number 3), which uses the memcpy_*io functions to perform the same task. Here’s the core of its read implementation:case M_memcpy:memcpy_fromio(ptr, add, count);break;Because ior emap was used to provide access to the ISA memory area, silly mustinvoke iounmap when the module is unloaded:iounmap(io_base);isa_readb and FriendsA look at the kernel source will turn up another set of routines with names likeisa_r eadb.

In fact, each of the functions just described has an isa_ equivalent.These functions provide access to ISA memory without the need for a separateior emap step. The word from the kernel developers, however, is that these functions are intended to be temporary driver-porting aids, and that they may go awayin the future. Their use is thus best avoided.Probing for ISA MemoryEven though most modern devices rely on better I/O bus architectures, like PCI,sometimes programmers must still deal with ISA devices and their I/O memory, sowe’ll spend a page on this issue. We won’t touch high ISA memory (the so-calledmemory hole in the 14 MB to 16 MB physical address range), because that kind ofI/O memory is extremely rare nowadays and is not supported by the majority ofmodern motherboards or by the kernel.

To access that range of I/O memory you’dneed to hack the kernel initialization sequence, and that is better not coveredhere.24522 June 2001 16:39http://openlib.org.uaChapter 8: Hardware ManagementWhen using ISA memory-mapped devices, the driver writer often ignores whererelevant I/O memory is located in the physical address space, since the actualaddress is usually assigned by the user among a range of possible addresses. Or itmay be necessary simply to see if a device is present at a given address or not.The memory resource management scheme can be helpful in probing, since it willidentify regions of memory that have already been claimed by another driver. Theresource manager, however, cannot tell you about devices whose drivers have notbeen loaded, or whether a given region contains the device that you are interestedin.

Thus, it can still be necessary to actually probe memory to see what is there.There are three distinct cases that you will encounter: that RAM is mapped to theaddress, that ROM is there (the VGA BIOS, for example), or that the area is free.The skull sample source shows a way to deal with such memory, but since skull isnot related to any physical device, it just prints information about the 640 KB to 1MB memory region and then exits. However, the code used to analyze memory isworth describing, since it shows how memory probes can be done.The code to check for RAM segments makes use of cli to disable interrupts,because these segments can be identified only by physically writing and rereadingdata, and real RAM might be changed by an interrupt handler in the middle of ourtests. The following code is not completely foolproof, because it might mistakeRAM memory on acquisition boards for empty regions if a device is actively writing to its own memory while this code is scanning the area.

However, this situation is quite unlikely to happen.unsigned char oldval, newval; /* values read from memory*/unsigned long flags;/* used to hold system flags */unsigned long add, i;void *base;/* Use ioremap to get a handle on our region */base = ioremap(ISA_REGION_BEGIN, ISA_REGION_END - ISA_REGION_BEGIN);base -= ISA_REGION_BEGIN; /* Do the offset once *//* probe all the memory hole in 2-KB steps */for (add = ISA_REGION_BEGIN; add < ISA_REGION_END; add += STEP) {/** Check for an already allocated region.*/if (check_mem_region (add, 2048)) {printk(KERN_INFO "%lx: Allocated\n", add);continue;}/** Read and write the beginning of the region and see what happens.*/save_flags(flags);cli();oldval = readb (base + add); /* Read a byte */24622 June 2001 16:39http://openlib.org.uaUsing I/O Memorywriteb (oldvalˆ0xff, base + add);mb();newval = readb (base + add);writeb (oldval, base + add);restore_flags(flags);if ((oldvalˆnewval) == 0xff) { /* we reread our change: it’s RAM */printk(KERN_INFO "%lx: RAM\n", add);continue;}if ((oldvalˆnewval) != 0) { /* random bits changed: it’s empty */printk(KERN_INFO "%lx: empty\n", add);continue;}/** Expansion ROM (executed at boot time by the BIOS)* has a signature where the first byte is 0x55, the second 0xaa,* and the third byte indicates the size of such ROM*/if ( (oldval == 0x55) && (readb (base + add + 1) == 0xaa)) {int size = 512 * readb (base + add + 2);printk(KERN_INFO "%lx: Expansion ROM, %i bytes\n",add, size);add += (size & ˜2048) - 2048; /* skip it */continue;}/** If the tests above failed, we still don’t know if it is ROM or* empty.

Since empty memory can appear as 0x00, 0xff, or the low* address byte, we must probe multiple bytes: if at least one of* them is different from these three values, then this is ROM* (though not boot ROM).*/printk(KERN_INFO "%lx: ", add);for (i=0; i<5; i++) {unsigned long radd = add + 57*(i+1); /* a "random" value */unsigned char val = readb (base + radd);if (val && val != 0xFF && val != ((unsigned long) radd&0xFF))break;}printk("%s\n", i==5 ? "empty" : "ROM");}Detecting memory doesn’t cause collisions with other devices, as long as you takecare to restore any byte you modified while you were probing.

It is worth notingthat it is always possible that writing to another device’s memory will cause thatdevice to do something undesirable. In general, this method of probing memoryshould be avoided if possible, but it’s not always possible when dealing with olderhardware.24722 June 2001 16:39http://openlib.org.uaChapter 8: Hardware ManagementBackward CompatibilityHappily, little has changed with regard to basic hardware access. There are just afew things that need to be kept in mind when writing backward-compatibledrivers.Hardware memory barriers didn’t exist in version 2.0 of the kernel.

There was noneed for such ordering instructions on the platforms then supported. Including sysdep.h in your driver will fix the problem by defining hardware barriers to be thesame as software barriers.Similarly, not all of the port-access functions (inb and friends) were supported onall architectures in older kernels. The string functions, in particular, tended to beabsent. We don’t provide the missing functions in our sysdep.h facility: it won’t bean easy task to perform cleanly and most likely is not worth the effort, given thehardware dependency of those functions.In Linux 2.0, ior emap and iounmap were called vr emap and vfr ee, respectively.The parameters and the functionality were the same.

Thus, a couple of definitionsthat map the functions to their older counterpart are often enough.Unfortunately, while vr emap worked just like ior emap for providing access to‘‘high’’ memory (such as that on PCI cards), it did refuse to remap the ISA memoryranges. Back in those days, access to this memory was done via direct pointers, sothere was no need to remap that address space. Thus, a more complete solution toimplement ior emap for Linux 2.0 running on the x86 platform is as follows:extern inline void *ioremap(unsigned long phys_addr, unsigned long size){if (phys_addr >= 0xA0000 && phys_addr + size <= 0x100000)return (void *)phys_addr;return vremap(phys_addr, size);}extern inline void iounmap(void *addr){if ((unsigned long)addr >= 0xA0000&& (unsigned long)addr < 0x100000)return;vfree(addr);}If you include sysdep.h in your drivers you’ll be able to use ior emap with no problems even when accessing ISA memory.Allocation of memory regions (check_mem_r egion and friends) was introduced inkernel 2.3.17.

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

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

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

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