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

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

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

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

If the priority isless than the integer variable console_loglevel, the message is displayed. Ifboth klogd and syslogd are running on the system, kernel messages are appendedto /var/log/messages (or otherwise treated depending on your syslogd configuration), independent of console_loglevel. If klogd is not running, the messagewon’t reach user space unless you read /pr oc/kmsg.9822 June 2001 16:35http://openlib.org.uaDebugging by PrintingThe variable console_loglevel is initialized to DEFAULT_CONSOLE_LOGLEVEL and can be modified through the sys_syslog system call. Oneway to change it is by specifying the –c switch when invoking klogd, as specifiedin the klogd manpage. Note that to change the current value, you must first killklogd and then restart it with the –c option.

Alternatively, you can write a programto change the console loglevel. You’ll find a version of such a program in miscpr ogs/setlevel.c in the source files provided on the O’Reilly FTP site. The new levelis specified as an integer value between 1 and 8, inclusive. If it is set to 1, onlymessages of level 0 (KERN_EMERG) will reach the console; if it is set to 8, all messages, including debugging ones, will be displayed.You’ll probably want to lower the loglevel if you work on the console and youexperience a kernel fault (see “Debugging System Faults” later in this chapter),because the fault-handling code raises the console_loglevel to its maximumvalue, causing every subsequent message to appear on the console.

You’ll want toraise the loglevel if you need to see your debugging messages; this is useful if youare developing kernel code remotely and the text console is not being used for aninteractive session.From version 2.1.31 on it is possible to read and modify the console loglevel usingthe text file /pr oc/sys/kernel/printk. The file hosts four integer values. You may beinterested in the first two: the current console loglevel and the default level formessages. With recent kernels, for instance, you can cause all kernel messages toappear at the console by simply entering# echo 8 > /proc/sys/kernel/printkIf you run 2.0, however, you still need the setlevel tool.It should now be apparent why the hello.c sample had the <1> markers; they arethere to make sure that the messages appear on the console.Linux allows for some flexibility in console logging policies by letting you sendmessages to a specific virtual console (if your console lives on the text screen).

Bydefault, the “console” is the current virtual terminal. To select a different virtual terminal to receive messages, you can issue ioctl(TIOCLINUX) on any consoledevice. The following program, setconsole, can be used to choose which consolereceives kernel messages; it must be run by the superuser and is available in themisc-pr ogs directory.This is how the program works:int main(int argc, char **argv){char bytes[2] = {11,0}; /* 11 is the TIOCLINUX cmd number */if (argc==2) bytes[1] = atoi(argv[1]); /* the chosen console */else {fprintf(stderr, "%s: need a single arg\n",argv[0]); exit(1);}9922 June 2001 16:35http://openlib.org.uaChapter 4: Debugging Techniquesif (ioctl(STDIN_FILENO, TIOCLINUX, bytes)<0) {/* use stdin */fprintf(stderr,"%s: ioctl(stdin, TIOCLINUX): %s\n",argv[0], strerror(errno));exit(1);}exit(0);}setconsole uses the special ioctl command TIOCLINUX, which implements Linuxspecific functions.

To use TIOCLINUX, you pass it an argument that is a pointer toa byte array. The first byte of the array is a number that specifies the requestedsubcommand, and the following bytes are subcommand specific. In setconsole,subcommand 11 is used, and the next byte (stored in bytes[1]) identifies thevirtual console. The complete description of TIOCLINUX can be found indrivers/char/tty_io.c, in the kernel sources.How Messages Get LoggedThe printk function writes messages into a circular buffer that is LOG_BUF_LEN(defined in ker nel/printk.c) bytes long.

It then wakes any process that is waitingfor messages, that is, any process that is sleeping in the syslog system call or that isreading /pr oc/kmsg. These two interfaces to the logging engine are almost equivalent, but note that reading from /pr oc/kmsg consumes the data from the log buffer,whereas the syslog system call can optionally return log data while leaving it forother processes as well.

In general, reading the /pr oc file is easier, which is why itis the default behavior for klogd.If you happen to read the kernel messages by hand, after stopping klogd you’llfind that the /pr oc file looks like a FIFO, in that the reader blocks, waiting formore data. Obviously, you can’t read messages this way if klogd or another process is already reading the same data because you’ll contend for it.If the circular buffer fills up, printk wraps around and starts adding new data tothe beginning of the buffer, overwriting the oldest data. The logging process thusloses the oldest data. This problem is negligible compared with the advantages ofusing such a circular buffer.

For example, a circular buffer allows the system torun even without a logging process, while minimizing memory waste by overwriting old data should nobody read it. Another feature of the Linux approach to messaging is that printk can be invoked from anywhere, even from an interrupthandler, with no limit on how much data can be printed. The only disadvantage isthe possibility of losing some data.If the klogd process is running, it retrieves kernel messages and dispatches them tosyslogd, which in turn checks /etc/syslog.conf to find out how to deal with them.syslogd differentiates between messages according to a facility and a priority;allowable values for both the facility and the priority are defined in10022 June 2001 16:35http://openlib.org.uaDebugging by Printing<sys/syslog.h>.

Kernel messages are logged by the LOG_KERN facility, at apriority corresponding to the one used in printk (for example, LOG_ERR is usedfor KERN_ERR messages). If klogd isn’t running, data remains in the circular bufferuntil someone reads it or the buffer overflows.If you want to avoid clobbering your system log with the monitoring messagesfrom your driver, you can either specify the –f (file) option to klogd to instruct it tosave messages to a specific file, or modify /etc/syslog.conf to suit your needs.

Yetanother possibility is to take the brute-force approach: kill klogd and verboselyprint messages on an unused virtual terminal,* or issue the command cat/pr oc/kmsg from an unused xter m.Turning the Messages On and OffDuring the early stages of driver development, printk can help considerably indebugging and testing new code.

When you officially release the driver, on theother hand, you should remove, or at least disable, such print statements. Unfortunately, you’re likely to find that as soon as you think you no longer need the messages and remove them, you’ll implement a new feature in the driver (orsomebody will find a bug) and you’ll want to turn at least one of the messagesback on. There are several ways to solve both issues, to globally enable or disableyour debug messages and to turn individual messages on or off.Here we show one way to code printk calls so you can turn them on and off individually or globally; the technique depends on defining a macro that resolves to aprintk (or printf ) call when you want it to.•Each print statement can be enabled or disabled by removing or adding a single letter to the macro’s name.•All the messages can be disabled at once by changing the value of theCFLAGS variable before compiling.•The same print statement can be used in kernel code and user-level code, sothat the driver and test programs can be managed in the same way withregard to extra messages.The following code fragment implements these features and comes directly fromthe header scull.h.#undef PDEBUG/* undef it, just in case */#ifdef SCULL_DEBUG# ifdef _ _KERNEL_ _/* This one if debugging is on, and kernel space */#define PDEBUG(fmt, args...) printk( KERN_DEBUG "scull: " fmt,## args)* For example, use setlevel 8; setconsole 10 to set up terminal 10 to display messages.10122 June 2001 16:35http://openlib.org.uaChapter 4: Debugging Techniques#else/* This one for user space */#define PDEBUG(fmt, args...) fprintf(stderr, fmt, ## args)# endif#else# define PDEBUG(fmt, args...) /* not debugging: nothing */#endif#undef PDEBUGG#define PDEBUGG(fmt, args...) /* nothing: it’s a placeholder */The symbol PDEBUG depends on whether or not SCULL_DEBUG is defined, and itdisplays information in whatever manner is appropriate to the environment wherethe code is running: it uses the kernel call printk when it’s in the kernel, and thelibc call fprintf to the standard error when run in user space.

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

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

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

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