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

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

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

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

It now lives on its own FTP site and is maintainedindependently of the kernel. Even if you are working with an older kernel, youprobably should go to ftp://ftp.ocs.com.au/pub/ksymoops and get an updated version of the tool.To operate at its best, ksymoops needs a lot of information in addition to the errormessage; you can use command-line options to tell it where to find the variousitems. The program needs the following items:A System.map fileThis map must correspond to the kernel that was running at the time the oopsoccurred.

The default is /usr/src/linux/System.map.A list of modulesksymoops needs to know what modules were loaded when the oops occurred,in order to extract symbolic information from them. If you do not supply thislist, ksymoops will look at /pr oc/modules.11422 June 2001 16:35http://openlib.org.uaDebugging System FaultsA list of kernel symbols defined when the oops occurredThe default is to get this list from /pr oc/ksyms.A copy of the kernel image that was runningNote that ksymoops needs a straight kernel image, not the compressed version(vmlinuz, zImage, or bzImage) that most systems boot. The default is to useno kernel image because most people don’t keep it.

If you have the exactimage handy, you should tell the program where it is by using the -v option.The locations of the object files for any kernel modules that were loadedksymoops will look in the standard directories for modules, but during development you will almost certainly have to tell it where your module lives usingthe -o optionAlthough ksymoops will go to files in /pr oc for some of its needed information, theresults can be unreliable. The system, of course, will almost certainly have beenrebooted between the time the oops occurs and when ksymoops is run, and theinformation from /pr oc may not match the state of affairs when the failureoccurred.

When possible, it is better to save copies of /pr oc/modules and/pr oc/ksyms prior to causing the oops to happen.We urge driver developers to read the manual page for ksymoops because it is avery informative document.The last argument on the tool’s command line is the location of the oops message;if it is missing, the tool will read stdin in the best Unix tradition. The messagecan be recovered from the system logs with luck; in the case of a very bad crashyou may end up writing it down off the screen and typing it back in (unless youwere using a serial console, a nice tool for kernel developers).Note that ksymoops will be confused by an oops message that has already beenprocessed by klogd.

If you are running klogd, and your system is still running afteran oops occurs, a clean oops message can often be obtained by invoking thedmesg command.If you do not provide all of the listed information explicitly, ksymoops will issuewarnings. It will also issue warnings about things like loaded modules that defineno symbols. A warning-free run of ksymoops is rare.Output from ksymoops tends to look like the following:>>EIP; c48370c3 <[faulty]faulty_write+3/20><=====Trace; c01356e6 <sys_write+d6/100>Trace; c010b860 <system_call+34/38>Code; c48370c3 <[faulty]faulty_write+3/20>00000000 <_EIP>:Code; c48370c3 <[faulty]faulty_write+3/20><=====0:c7 05 00 00 00movl$0x0,0x0<=====Code; c48370c8 <[faulty]faulty_write+8/20>5:00 00 00 00 0011522 June 2001 16:35http://openlib.org.uaChapter 4: Debugging TechniquesCode;a:Code;c:Code;e:Code;f:Code;10:Code;15:c48370cd <[faulty]faulty_write+d/20>31 c0xorl%eax,%eaxc48370cf <[faulty]faulty_write+f/20>89 ecmovl%ebp,%espc48370d1 <[faulty]faulty_write+11/20>5dpopl%ebpc48370d2 <[faulty]faulty_write+12/20>c3retc48370d3 <[faulty]faulty_write+13/20>8d b6 00 00 00leal0x0(%esi),%esic48370d8 <[faulty]faulty_write+18/20>00As you can see, ksymoops provides EIP and kernel stack information much likeklogd does, but more precisely and in hexadecimal.

You’ll note that thefaulty_write function is correctly reported to be 0x20 bytes long. This is becauseksymoops reads the object file of your module and extracts all available information.In this case, moreover, you also get an assembly language dump of the codewhere the fault occurred. This information can often be used to figure out exactlywhat was happening; here it’s clearly an instruction that writes a 0 to address 0.One interesting feature of ksymoops is that it is ported to nearly all the platformswhere Linux runs and exploits the bfd (binary format description) library in orderto support several computer architectures at the same time. To step outside of thePC world, let’s see how the same oops message appears on the SPARC64 platform(several lines have been broken for typographical needs):Unable to handle kernel NULL pointer dereferencetsk->mm->context = 0000000000000734tsk->mm->pgd = fffff80003499000\/ ____"@’/ ..

\‘@"/_| \_ _/ |_\\_ _U_/ls(16740): OopsTSTATE: 0000004400009601 TPC: 0000000001000128 TNPC: 0000000000457fbc \Y: 00800000g0: 000000007002ea88 g1: 0000000000000004 g2: 0000000070029fb0 \g3: 0000000000000018g4: fffff80000000000 g5: 0000000000000001 g6: fffff8000119c000 \g7: 0000000000000001o0: 0000000000000000 o1: 000000007001a000 o2: 0000000000000178 \o3: fffff8001224f168o4: 0000000001000120 o5: 0000000000000000 sp: fffff8000119f621 \ret_pc: 0000000000457fb4l0: fffff800122376c0 l1: ffffffffffffffea l2: 000000000002c400 \l3: 000000000002c400l4: 0000000000000000 l5: 0000000000000000 l6: 0000000000019c00 \l7: 0000000070028cbci0: fffff8001224f140 i1: 000000007001a000 i2: 0000000000000178 \11622 June 2001 16:35http://openlib.org.uaDebugging System Faultsi3: 000000000002c400i4: 000000000002c400 i5: 000000000002c000 i6: fffff8000119f6e1 \i7: 0000000000410114Caller[0000000000410114]Caller[000000007007cba4]Instruction DUMP: 01000000 90102000 81c3e008 <c0202000> \30680005 01000000 01000000 01000000 01000000Note how the instruction dump doesn’t start from the instruction that caused thefault but three instructions earlier: that’s because the RISC platforms execute several instructions in parallel and may generate deferred exceptions, so one must beable to look back at the last few instructions.This is what ksymoops prints when fed with input data starting at the TSTATE line:>>TPC; 0000000001000128 <[faulty].text.start+88/a0><=====>>O7; 0000000000457fb4 <sys_write+114/160>>>I7; 0000000000410114 <linux_sparc_syscall+34/40>Trace; 0000000000410114 <linux_sparc_syscall+34/40>Trace; 000000007007cba4 <END_OF_CODE+6f07c40d/????>Code; 000000000100011c <[faulty].text.start+7c/a0>0000000000000000 <_TPC>:Code; 000000000100011c <[faulty].text.start+7c/a0>0:01 00 00 00nopCode; 0000000001000120 <[faulty].text.start+80/a0>4:90 10 20 00clr %o0! 0 <_TPC>Code; 0000000001000124 <[faulty].text.start+84/a0>8:81 c3 e0 08retlCode; 0000000001000128 <[faulty].text.start+88/a0><=====c:c0 20 20 00clr [ %g0 ]<=====Code; 000000000100012c <[faulty].text.start+8c/a0>10:30 68 00 05b,a%xcc, 24 <_TPC+0x24> \0000000001000140 <[faulty]faulty_write+0/20>Code; 0000000001000130 <[faulty].text.start+90/a0>14:01 00 00 00nopCode; 0000000001000134 <[faulty].text.start+94/a0>18:01 00 00 00nopCode; 0000000001000138 <[faulty].text.start+98/a0>1c:01 00 00 00nopCode; 000000000100013c <[faulty].text.start+9c/a0>20:01 00 00 00nopTo print the disassembled code shown we had to tell ksymoops the target file format and architecture (this is needed because the native architecture for SPARC64user space is 32 bit).

In this case, the options -t elf64-sparc -a sparc:v9 did the job.You may complain that this call trace doesn’t carry any interesting information;however, the SPARC processors don’t save all the call trace on the stack: the O7and I7 registers hold the instruction pointers of the last two calling functions,which is why they are shown near the call trace. In this case, the faulty instructionwas in a function invoked by sys_write.11722 June 2001 16:35http://openlib.org.uaChapter 4: Debugging TechniquesNote that, whatever the platform/architecture pair, the format used to show disassembled code is the same as that used by the objdump program.

objdump is apowerful utility; if you want to look at the whole function that failed, you caninvoke the command objdump –d faulty.o (once again, on SPARC64, you needspecial options: —target elf64-sparc—architectur e sparc:v9). For more information on objdump and its command-line options, see the manpage for the command.Learning to decode an oops message requires some practice and an understandingof the target processor you are using, as well as of the conventions used to represent assembly language, but it’s worth doing.

The time spent learning will bequickly repaid. Even if you have previous expertise with the PC assembly language under non-Unix operating systems, you may need to devote some time tolearning, because the Unix syntax is different from Intel syntax. (A good description of the differences is in the Info documentation file for as, in the chapter called“i386-specific.”)System HangsAlthough most bugs in kernel code end up as oops messages, sometimes they cancompletely hang the system.

If the system hangs, no message is printed. For example, if the code enters an endless loop, the kernel stops scheduling, and the system doesn’t respond to any action, including the magic CTRL-ALT-DELcombination. You have two choices for dealing with system hangs—either preventthem beforehand or be able to debug them after the fact.You can prevent an endless loop by inserting schedule invocations at strategicpoints.

The schedule call (as you might guess) invokes the scheduler and thusallows other processes to steal CPU time from the current process. If a process islooping in kernel space due to a bug in your driver, the schedule calls enable youto kill the process, after tracing what is happening.You should be aware, of course, that any call to schedule may create an additionalsource of reentrant calls to your driver, since it allows other processes to run. Thisreentrancy should not normally be a problem, assuming that you have used suitable locking in your driver. Be sure, however, not to call schedule any time thatyour driver is holding a spinlock.If your driver really hangs the system, and you don’t know where to insert schedule calls, the best way to go is to add some print messages and write them to theconsole (by changing the console_loglevel value).Sometimes the system may appear to be hung, but it isn’t.

This can happen, forexample, if the keyboard remains locked in some strange way. These false hangscan be detected by looking at the output of a program you keep running for justthis purpose. A clock or system load meter on your display is a good status monitor; as long as it continues to update, the scheduler is working. If you are notusing a graphic display, you can check the scheduler by running a program that11822 June 2001 16:35http://openlib.org.uaDebugging System Faultsflashes the keyboard LEDs, turns on the floppy motor every now and then, or ticksthe speaker—conventional beeps are quite annoying and should be avoided; lookfor the KDMKTONE ioctl command instead.

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

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

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

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