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

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

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

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

kdb also starts up when a kernel oops happens, or when a breakpointis hit. In any case, you will see a message that looks something like this:Entering kdb (0xc1278000) on processor 1 due to Keyboard Entry[1]kdb>12222 June 2001 16:35http://openlib.org.uaDebuggers and Related ToolsNote that just about everything the kernel does stops when kdb is running. Nothing else should be running on a system where you invoke kdb; in particular, youshould not have networking turned on—unless, of course, you are debugging anetwork driver. It is generally a good idea to boot the system in single-user modeif you will be using kdb.As an example, consider a quick scull debugging session.

Assuming that the driveris already loaded, we can tell kdb to set a breakpoint in scull_r ead as follows:[1]kdb> bp scull_readInstruction(i) BP #0 at 0xc8833514 (scull_read)is enabled on cpu 1[1]kdb> goThe bp command tells kdb to stop the next time the kernel enters scull_r ead. Wethen type go to continue execution. After putting something into one of the sculldevices, we can attempt to read it by running cat under a shell on another terminal, yielding the following:Entering kdb (0xc3108000) on processor 0 due to Breakpoint @ 0xc8833515Instruction(i) breakpoint #0 at 0xc8833514scull_read+0x1:movl%esp,%ebp[0]kdb>We are now positioned at the beginning of scull_r ead. To see how we got there,we can get a stack trace:[0]kdb> btEBPEIP0xc3109c5c 0xc88335150xc3109fbc 0xfc458b100x1000, 0x804ad78)0xbffffc88 0xc010bec0[0]kdb>Function(args)scull_read+0x1scull_read+0x33c255fc( 0x3, 0x803ad78, 0x1000,system_callkdb attempts to print out the arguments to every function in the call trace.

It getsconfused, however, by optimization tricks used by the compiler. Thus it prints fivearguments for scull_r ead, which only has four.Time to look at some data. The mds command manipulates data; we can query thevalue of the scull_devices pointer with a command like:[0]kdb> mds scull_devices 1c8836104: c4c125c0 ....Here we asked for one (four-byte) word of data starting at the location ofscull_devices; the answer tells us that our device array was allocated startingat the address c4c125c0. To look at a device structure itself we need to use thataddress:12322 June 2001 16:35http://openlib.org.uaChapter 4: Debugging Techniques[0]kdb> mds c4c125c0c4c125c0: c3785000 ....c4c125c4: 00000000 ....c4c125c8: 00000fa0 ....c4c125cc: 000003e8 ....c4c125d0: 0000009a ....c4c125d4: 00000000 ....c4c125d8: 00000000 ....c4c125dc: 00000001 ....The eight lines here correspond to the eight fields in the Scull_Dev structure.Thus we see that the memory for the first device is allocated at 0xc3785000, thatthere is no next item in the list, that the quantum is 4000 (hex fa0) and the arraysize is 1000 (hex 3e8), that there are 154 bytes of data in the device (hex 9a), andso on.kdb can change data as well.

Suppose we wanted to trim some of the data fromthe device:[0]kdb> mm c4c125d0 0x500xc4c125d0 = 0x50A subsequent cat on the device will now return less data than before.kdb has a number of other capabilities, including single-stepping (by instructions,not lines of C source code), setting breakpoints on data access, disassemblingcode, stepping through linked lists, accessing register data, and more. After youhave applied the kdb patch, a full set of manual pages can be found in the Documentation/kdb directory in your kernel source tree.The Integrated Kernel Debugger PatchA number of kernel developers have contributed to an unofficial patch called theintegrated kernel debugger, or IKD. IKD provides a number of interesting kerneldebugging facilities.

The x86 is the primary platform for this patch, but much of itworks on other architectures as well. As of this writing, the IKD patch can befound at ftp://ftp.ker nel.org/pub/linux/ker nel/people/andrea/ikd. It is a patch thatmust be applied to the source for your kernel; the patch is version specific, so besure to download the one that matches the kernel you are working with.One of the features of the IKD patch is a kernel stack debugger. If you turn thisfeature on, the kernel will check the amount of free space on the kernel stack atevery function call, and force an oops if it gets too small.

If something in your kernel is causing stack corruption, this tool may help you to find it. There is also a“stack meter” feature that you can use to see how close to filling up the stack youget at any particular time.12422 June 2001 16:35http://openlib.org.uaDebuggers and Related ToolsThe IKD patch also includes some tools for finding kernel lockups. A “soft lockup”detector forces an oops if a kernel procedure goes for too long without scheduling. It is implemented by simply counting the number of function calls that aremade and shutting things down if that number exceeds a preconfigured threshold.Another feature can continuously print the program counter on a virtual consolefor truly last-resort lockup tracking. The semaphore deadlock detector forces anoops if a process spends too long waiting on a down call.Other debugging capabilities in IKD include the kernel trace capability, which canrecord the paths taken through the kernel code.

There are some memory debugging tools, including a leak detector and a couple of “poisoners,” that can be useful in tracking down memory corruption problems.Finally, IKD also includes a version of the kdb debugger discussed in the previoussection. As of this writing, however, the version of kdb included in the IKD patchis somewhat old. If you need kdb, we recommend that you go directly to thesource at oss.sgi.com for the current version.The kgdb Patchkgdb is a patch that allows the full use of the gdb debugger on the Linux kernel,but only on x86 systems. It works by hooking into the system to be debugged viaa serial line, with gdb running on the far end. You thus need two systems to usekgdb—one to run the debugger and one to run the kernel of interest.

Like kdb,kgdb is currently available from oss.sgi.com.Setting up kgdb involves installing a kernel patch and booting the modified kernel.You need to connect the two systems with a serial cable (of the null modem variety) and to install some support files on the gdb side of the connection. The patchplaces detailed instructions in the file Documentation/i386/gdb-serial.txt; we won’treproduce them here. Be sure to read the instructions on debugging modules:toward the end there are some nice gdb macros that have been written for thispurpose.Kernel Crash Dump AnalyzersCrash dump analyzers enable the system to record its state when an oops occurs,so that it may be examined at leisure afterward.

They can be especially useful ifyou are supporting a driver for a user at a different site. Users can be somewhatreluctant to copy down oops messages for you so installing a crash dump systemcan let you get the information you need to track down a user’s problem withoutrequiring work from him. It is thus not surprising that the available crash dumpanalyzers have been written by companies in the business of supporting systemsfor users.12522 June 2001 16:35http://openlib.org.uaChapter 4: Debugging TechniquesThere are currently two crash dump analyzer patches available for Linux. Bothwere relatively new when this section was written, and both were in a state offlux. Rather than provide detailed information that is likely to go out of date, we’llrestrict ourselves to providing an overview and pointers to where more information can be found.The first analyzer is LKCD (Linux Kernel Crash Dumps).

It’s available, once again,from oss.sgi.com. When a kernel oops occurs, LKCD will write a copy of the current system state (memory, primarily) into the dump device you specified inadvance. The dump device must be a system swap area. A utility called LCRASH isrun on the next reboot (before swapping is enabled) to generate a summary of thecrash, and optionally to save a copy of the dump in a conventional file. LCRASHcan be run interactively and provides a number of debugger-like commands forquerying the state of the system.LKCD is currently supported for the Intel 32-bit architecture only, and only workswith swap partitions on SCSI disks.Another crash dump facility is available from www.missioncriticallinux.com.

Thiscrash dump subsystem creates crash dump files directly in /var/dumps and doesnot use the swap area. That makes certain things easier, but it also means that thesystem will be modifying the file system while in a state where things are knownto have gone wrong. The crash dumps generated are in a standard core file format, so tools like gdb can be used for post-mortem analysis. This package alsoprovides a separate analyzer that is able to extract more information than gdb fromthe crash dump files.The User-Mode Linux PortUser-Mode Linux is an interesting concept.

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

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

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

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