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

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

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

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

A sample program (misc-pr ogs/heartbeat.c) that flashes a keyboard LED in a heartbeat fashion is available in thesources on the O’Reilly FTP site.If the keyboard isn’t accepting input, the best thing to do is log into the systemthrough your network and kill any offending processes, or reset the keyboard(with kbd_mode –a). However, discovering that the hang is only a keyboardlockup is of little use if you don’t have a network available to help you recover.

Ifthis is the case, you could set up alternative input devices to be able at least toreboot the system cleanly. A shutdown and reboot cycle is easier on your computer than hitting the so-called big red button, and it saves you from the lengthyfsck scanning of your disks.Such an alternative input device can be, for example, the mouse.

Version 1.10 ornewer of the gpm mouse server features a command-line option to enable a similar capability, but it works only in text mode. If you don’t have a network connection and run in graphics mode, we suggest running some custom solution, like aswitch connected to the DCD pin of the serial line and a script that polls for statuschange.An indispensable tool for these situations is the “magic SysRq key,” which is available on more architectures in 2.2 and later kernels. Magic SysRq is invoked withthe combination of the ALT and SysRq keys on the PC keyboard, or with the ALTand Stop keys on SPARC keyboards. A third key, pressed along with these two,performs one of a number of useful actions, as follows:rTurns off keyboard raw mode in situations where you cannot run kbd_mode.kInvokes the “secure attention” (SAK) function.

SAK will kill all processes running on the current console, leaving you with a clean terminal.sPerforms an emergency synchronization of all disks.uAttempts to remount all disks in a read-only mode. This operation, usuallyinvoked immediately after s, can save a lot of filesystem checking time incases where the system is in serious trouble.bImmediately reboots the system. Be sure to synchronize and remount the disksfirst.pPrints the current register information.tPrints the current task list.mPrints memory information.Other magic SysRq functions exist; see sysrq.txt in the Documentation directory ofthe kernel source for the full list.

Note that magic SysRq must be explicitly enabledin the kernel configuration, and that most distributions do not enable it, for11922 June 2001 16:35http://openlib.org.uaChapter 4: Debugging Techniquesobvious security reasons. For a system used to develop drivers, however, enablingmagic SysRq is worth the trouble of building a new kernel in itself. Magic SysRqmust be enabled at runtime with a command like the following:echo 1 > /proc/sys/kernel/sysrqAnother precaution to use when reproducing system hangs is to mount all yourdisks as read-only (or unmount them). If the disks are read-only or unmounted,there’s no risk of damaging the filesystem or leaving it in an inconsistent state.Another possibility is using a computer that mounts all of its filesystems via NFS,the network file system.

The “NFS-Root” capability must be enabled in the kernel,and special parameters must be passed at boot time. In this case you’ll avoid anyfilesystem corruption without even resorting to SysRq, because filesystem coherence is managed by the NFS server, which is not brought down by your devicedriver.Debuggers and Related ToolsThe last resort in debugging modules is using a debugger to step through thecode, watching the value of variables and machine registers. This approach istime-consuming and should be avoided whenever possible. Nonetheless, the finegrained perspective on the code that is achieved through a debugger is sometimesinvaluable.Using an interactive debugger on the kernel is a challenge. The kernel runs in itsown address space on the behalf of all the processes on the system.

As a result, anumber of common capabilities provided by user-space debuggers, such as breakpoints and single-stepping, are harder to come by in the kernel. In this section welook at several ways of debugging the kernel; each of them has advantages anddisadvantages.Using gdbgdb can be quite useful for looking at the system internals. Proficient use of thedebugger at this level requires some confidence with gdb commands, some understanding of assembly code for the target platform, and the ability to match sourcecode and optimized assembly.The debugger must be invoked as though the kernel were an application.

In addition to specifying the filename for the uncompressed kernel image, you need toprovide the name of a core file on the command line. For a running kernel, thatcore file is the kernel core image, /pr oc/kcore. A typical invocation of gdb lookslike the following:gdb /usr/src/linux/vmlinux /proc/kcoreThe first argument is the name of the uncompressed kernel executable, not thezImage or bzImage or anything compressed.12022 June 2001 16:35http://openlib.org.uaDebuggers and Related ToolsThe second argument on the gdb command line is the name of the core file. Likeany file in /pr oc, /pr oc/kcore is generated when it is read.

When the read systemcall executes in the /pr oc filesystem, it maps to a data-generation function ratherthan a data-retrieval one; we’ve already exploited this feature in “Using the /procFilesystem” earlier in this chapter. kcor e is used to represent the kernel “executable” in the format of a core file; it is a huge file because it represents thewhole kernel address space, which corresponds to all physical memory.

Fromwithin gdb, you can look at kernel variables by issuing the standard gdb commands. For example, p jiffies prints the number of clock ticks from system boot tothe current time.When you print data from gdb, the kernel is still running, and the various dataitems have different values at different times; gdb, however, optimizes access tothe core file by caching data that has already been read. If you try to look at thejiffies variable once again, you’ll get the same answer as before. Caching values to avoid extra disk access is a correct behavior for conventional core files, butis inconvenient when a “dynamic” core image is used. The solution is to issue thecommand cor e-file /pr oc/kcore whenever you want to flush the gdb cache; thedebugger prepares to use a new core file and discards any old information. Youwon’t, however, always need to issue cor e-file when reading a new datum; gdbreads the core in chunks of a few kilobytes and caches only chunks it has alreadyreferenced.Numerous capabilities normally provided by gdb are not available when you areworking with the kernel.

For example, gdb is not able to modify kernel data; itexpects to be running a program to be debugged under its own control beforeplaying with its memory image. It is also not possible to set breakpoints or watchpoints, or to single-step through kernel functions.If you compile the kernel with debugging support (–g ), the resulting vmlinux fileturns out to work better with gdb than the same file compiled without –g. Note,however, that a large amount of disk space is needed to compile the kernel withthe –g option (each object file and the kernel itself are three or more times biggerthan usual).On non-PC computers, the game is different.

On the Alpha, make boot strips thekernel before creating the bootable image, so you end up with both the vmlinuxand the vmlinux.gz files. The former is usable by gdb, and you can boot from thelatter. On the SPARC, the kernel (at least the 2.0 kernel) is not stripped by default.When you compile the kernel with –g and run the debugger using vmlinuxtogether with /pr oc/kcore, gdb can return a lot of information about the kernelinternals. You can, for example, use commands such as p *module_list, p *module_list->next, and p *chrdevs[4]->fops to dump structures. To get the best out of p,you’ll need to keep a kernel map and the source code handy.12122 June 2001 16:35http://openlib.org.uaChapter 4: Debugging TechniquesAnother useful task that gdb performs on the running kernel is disassembling functions, via the disassemble command (which can be abbreviated to disass) or the“examine instructions” (x/i) command.

The disassemble command can take as itsargument either a function name or a memory range, whereas x/i takes a singlememory address, also in the form of a symbol name. You can invoke, for example,x/20i to disassemble 20 instructions. Note that you can’t disassemble a modulefunction, because the debugger is acting on vmlinux, which doesn’t know aboutyour module. If you try to disassemble a module by address, gdb is most likely toreply “Cannot access memory at xxxx.” For the same reason, you can’t look at dataitems belonging to a module. They can be read from /dev/mem if you know theaddress of your variables, but it’s hard to make sense out of raw data extractedfrom system RAM.If you want to disassemble a module function, you’re better off running the objdump utility on the module object file. Unfortunately, the tool runs on the diskcopy of the file, not the running one; therefore, the addresses as shown by objdump will be the addresses before relocation, unrelated to the module’s executionenvironment.

Another disadvantage of disassembling an unlinked object file is thatfunction calls are still unresolved, so you can’t easily tell a call to printk from a callto kmalloc.As you see, gdb is a useful tool when your aim is to peek into the running kernel,but it lacks some features that are vital to debugging device drivers.The kdb Kernel DebuggerMany readers may be wondering why the kernel does not have anyadvanced debugging features built into it.

The answer, quite simply, is thatdoes not believe in interactive debuggers. He fears that they lead to poorthose which patch up symptoms rather than addressing the real cause oflems. Thus, no built-in debuggers.moreLinusfixes,prob-Other kernel developers, however, see an occasional use for interactive debuggingtools.

One such tool is the kdb built-in kernel debugger, available as a nonofficialpatch from oss.sgi.com. To use kdb, you must obtain the patch (be sure to get aversion that matches your kernel version), apply it, and rebuild and reinstall thekernel. Note that, as of this writing, kdb works only on IA-32 (x86) systems(though a version for the IA-64 existed for a while in the mainline kernel sourcebefore being removed).Once you are running a kdb-enabled kernel, there are a couple of ways to enterthe debugger. Hitting the Pause (or Break) key on the console will start up thedebugger.

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

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

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

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