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

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

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

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

It assumes that there will neverbe a need to generate more than one page of data, and so ignores the start andoffset values. It is, however, careful not to overrun its buffer, just in case.A /pr oc function using the get_info interface would look very similar to the onejust shown, with the exception that the last two arguments would be missing. Theend-of-file condition, in this case, is signaled by returning less data than the callerexpects (i.e., less than count).Once you have a read_ proc function defined, you need to connect it to an entryin the /pr oc hierarchy.

There are two ways of setting up this connection, depending on what versions of the kernel you wish to support. The easiest method, onlyavailable in the 2.4 kernel (and 2.2 too if you use our sysdep.h header), is to simply call cr eate_pr oc_read_entry. Here is the call used by scull to make its /pr ocfunction available as /pr oc/scullmem:create_proc_read_entry("scullmem",0/* default mode */,NULL /* parent dir */,scull_read_procmem,NULL /* client data */);The arguments to this function are, as shown, the name of the /pr oc entry, the filepermissions to apply to the entry (the value 0 is treated as a special case and isturned to a default, world-readable mask), the proc_dir_entry pointer to theparent directory for this file (we use NULL to make the driver appear directlyunder /pr oc), the pointer to the read_ proc function, and the data pointer that willbe passed back to the read_ proc function.The directory entry pointer can be used to create entire directory hierarchies under/pr oc.

Note, however, that an entry may be more easily placed in a subdirectory of/pr oc simply by giving the directory name as part of the name of the entry—aslong as the directory itself already exists. For example, an emerging convention10622 June 2001 16:35http://openlib.org.uaDebugging by Queryingsays that /pr oc entries associated with device drivers should go in the subdirectorydriver/; scull could place its entry there simply by giving its name asdriver/scullmem.Entries in /pr oc, of course, should be removed when the module is unloaded.remove_ proc_entry is the function that undoes what cr eate_pr oc_read_entry did:remove_proc_entry("scullmem", NULL /* parent dir */);The alternative method for creating a /pr oc entry is to create and initialize aproc_dir_entry structure and pass it to pr oc_register_dynamic (version 2.0) orpr oc_register (version 2.2, which assumes a dynamic file if the inode number inthe structure is 0).

As an example, consider the following code that scull useswhen compiled against 2.0 headers:static int scull_get_info(char *buf, char **start, off_t offset,int len, int unused){int eof = 0;return scull_read_procmem (buf, start, offset, len, &eof, NULL);}struct proc_dir_entry scull_proc_entry = {namelen:8,name:"scullmem",mode:S_IFREG | S_IRUGO,nlink:1,get_info:scull_get_info,};static void scull_create_proc(){proc_register_dynamic(&proc_root, &scull_proc_entry);}static void scull_remove_proc(){proc_unregister(&proc_root, scull_proc_entry.low_ino);}The code declares a function using the get_info interface and fills in aproc_dir_entry structure that is registered with the filesystem.This code provides compatibility across the 2.0 and 2.2 kernels, with a little support from macro definitions in sysdep.h. It uses the get_info interface because the2.0 kernel did not support read_ proc.

Some more work with #ifdef could havemade it use read_ proc with Linux 2.2, but the benefits would be minor.10722 June 2001 16:35http://openlib.org.uaChapter 4: Debugging TechniquesThe ioctl Methodioctl, which we show you how to use in the next chapter, is a system call that actson a file descriptor; it receives a number that identifies a command to be performed and (optionally) another argument, usually a pointer.As an alternative to using the /pr oc filesystem, you can implement a few ioctl commands tailored for debugging.

These commands can copy relevant data structuresfrom the driver to user space, where you can examine them.Using ioctl this way to get information is somewhat more difficult than using /pr oc,because you need another program to issue the ioctl and display the results. Thisprogram must be written, compiled, and kept in sync with the module you’re testing. On the other hand, the driver’s code is easier than what is needed to implement a /pr oc fileThere are times when ioctl is the best way to get information, because it runsfaster than reading /pr oc.

If some work must be performed on the data before it’swritten to the screen, retrieving the data in binary form is more efficient than reading a text file. In addition, ioctl doesn’t require splitting data into fragments smallerthan a page.Another interesting advantage of the ioctl approach is that information-retrievalcommands can be left in the driver even when debugging would otherwise be disabled. Unlike a /pr oc file, which is visible to anyone who looks in the directory(and too many people are likely to wonder “what that strange file is”), undocumented ioctl commands are likely to remain unnoticed.

In addition, they will stillbe there should something weird happen to the driver. The only drawback is thatthe module will be slightly bigger.Debugging by WatchingSometimes minor problems can be tracked down by watching the behavior of anapplication in user space. Watching programs can also help in building confidencethat a driver is working correctly. For example, we were able to feel confidentabout scull after looking at how its read implementation reacted to read requestsfor different amounts of data.There are various ways to watch a user-space program working.

You can run adebugger on it to step through its functions, add print statements, or run the program under strace. Here we’ll discuss just the last technique, which is most interesting when the real goal is examining kernel code.The strace command is a powerful tool that shows all the system calls issued by auser-space program. Not only does it show the calls, but it can also show the arguments to the calls, as well as return values in symbolic form.

When a system call10822 June 2001 16:35http://openlib.org.uaDebugging by Watchingfails, both the symbolic value of the error (e.g., ENOMEM) and the correspondingstring (Out of memory) are displayed. strace has many command-line options;the most useful of which are –t to display the time when each call is executed, –Tto display the time spent in the call, –e to limit the types of calls traced, and –o toredirect the output to a file. By default, strace prints tracing information onstderr.strace receives information from the kernel itself. This means that a program canbe traced regardless of whether or not it was compiled with debugging support(the –g option to gcc) and whether or not it is stripped. You can also attach tracingto a running process, similar to the way a debugger can connect to a running process and control it.The trace information is often used to support bug reports sent to applicationdevelopers, but it’s also invaluable to kernel programmers.

We’ve seen how drivercode executes by reacting to system calls; strace allows us to check the consistency of input and output data of each call.For example,the following screen dump shows the last lines of running the command strace ls /dev > /dev/scull0 :[...]open("/dev", O_RDONLY|O_NONBLOCK)= 4fcntl(4, F_SETFD, FD_CLOEXEC)= 0brk(0x8055000)= 0x8055000lseek(4, 0, SEEK_CUR)= 0getdents(4, /* 70 entries */, 3933)= 1260[...]getdents(4, /* 0 entries */, 3933)= 0close(4)= 0fstat(1, {st_mode=S_IFCHR|0664, st_rdev=makedev(253, 0), ...}) = 0ioctl(1, TCGETS, 0xbffffa5c)= -1 ENOTTY (Inappropriate ioctlfor device)write(1, "MAKEDEV\natibm\naudio\naudio1\na"..., 4096) = 4000write(1, "d2\nsdd3\nsdd4\nsdd5\nsdd6\nsdd7"..., 96) = 96write(1, "4\nsde5\nsde6\nsde7\nsde8\nsde9\n"..., 3325) = 3325close(1)= 0_exit(0)= ?It’s apparent in the first write call that after ls finished looking in the target directory, it tried to write 4 KB.

Strangely (for ls), only four thousand bytes were written, and the operation was retried. However, we know that the writeimplementation in scull writes a single quantum at a time, so we could haveexpected the partial write. After a few steps, everything sweeps through, and theprogram exits successfully.As another example, let’s read the scull device (using the wc command):[...]open("/dev/scull0", O_RDONLY)= 4fstat(4, {st_mode=S_IFCHR|0664, st_rdev=makedev(253, 0), ...}) = 010922 June 2001 16:35http://openlib.org.uaChapter 4: Debugging Techniquesread(4, "MAKEDEV\natibm\naudio\naudio1\na"..., 16384) = 4000read(4, "d2\nsdd3\nsdd4\nsdd5\nsdd6\nsdd7"..., 16384) = 3421read(4, "", 16384)= 0fstat(1, {st_mode=S_IFCHR|0600, st_rdev=makedev(3, 7), ...}) = 0ioctl(1, TCGETS, {B38400 opost isig icanon echo ...}) = 0write(1, "7421 /dev/scull0\n", 20)= 20close(4)= 0_exit(0)= ?As expected, read is able to retrieve only four thousand bytes at a time, but thetotal amount of data is the same that was written in the previous example.

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

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

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

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