Linux Device Drivers 2nd Edition, страница 11

PDF-файл Linux Device Drivers 2nd Edition, страница 11 Основы автоматизированного проектирования (ОАП) (17688): Книга - 3 семестрLinux Device Drivers 2nd Edition: Основы автоматизированного проектирования (ОАП) - PDF, страница 11 (17688) - СтудИзба2018-01-10СтудИзба

Описание файла

PDF-файл из архива "Linux Device Drivers 2nd Edition", который расположен в категории "". Всё это находится в предмете "основы автоматизированного проектирования (оап)" из 3 семестр, которые можно найти в файловом архиве МГТУ им. Н.Э.Баумана. Не смотря на прямую связь этого архива с МГТУ им. Н.Э.Баумана, его также можно найти и в других разделах. Архив можно найти в разделе "книги и методические указания", в предмете "основы автоматизированного производства (оап)" в общих файлах.

Просмотр PDF-файла онлайн

Текст 11 страницы из PDF

We normallyhate to use goto, but in our opinion this is one situation (well, the only situation)where it is useful. In the kernel, goto is often used as shown here to deal witherrors.The following sample code (using fictitious registration and unregistration functions) behaves correctly if initialization fails at any point.3022 June 2001 16:34http://openlib.org.uaInitialization and Shutdownint init_module(void){int err;/* registration takes a pointer and a name */err = register_this(ptr1, "skull");if (err) goto fail_this;err = register_that(ptr2, "skull");if (err) goto fail_that;err = register_those(ptr3, "skull");if (err) goto fail_those;return 0; /* success */fail_those: unregister_that(ptr2, "skull");fail_that: unregister_this(ptr1, "skull");fail_this: return err; /* propagate the error */}This code attempts to register three (fictitious) facilities.

The goto statement isused in case of failure to cause the unregistration of only the facilities that hadbeen successfully registered before things went bad.Another option, requiring no hairy goto statements, is keeping track of what hasbeen successfully registered and calling cleanup_module in case of any error. Thecleanup function will only unroll the steps that have been successfully accomplished. This alternative, however, requires more code and more CPU time, so infast paths you’ll still resort to goto as the best error-recovery tool. The returnvalue of init_module, err, is an error code.

In the Linux kernel, error codes arenegative numbers belonging to the set defined in <linux/errno.h>. If youwant to generate your own error codes instead of returning what you get fromother functions, you should include <linux/errno.h> in order to use symbolicvalues such as -ENODEV, -ENOMEM, and so on. It is always good practice toreturn appropriate error codes, because user programs can turn them to meaningful strings using perr or or similar means. (However, it’s interesting to note that several versions of modutils returned a “Device busy” message for any error returnedby init_module ; the problem has only been fixed in recent releases.)Obviously, cleanup_module must undo any registration performed by init_module, and it is customary (but not mandatory) to unregister facilities in the reverseorder used to register them:void cleanup_module(void){unregister_those(ptr3, "skull");unregister_that(ptr2, "skull");unregister_this(ptr1, "skull");return;}3122 June 2001 16:34http://openlib.org.uaChapter 2: Building and Running ModulesIf your initialization and cleanup are more complex than dealing with a few items,the goto approach may become difficult to manage, because all the cleanup codemust be repeated within init_module, with several labels intermixed.

Sometimes,therefore, a different layout of the code proves more successful.What you’d do to minimize code duplication and keep everything streamlined is tocall cleanup_module from within init_module whenever an error occurs. Thecleanup function, then, must check the status of each item before undoing its registration. In its simplest form, the code looks like the following:struct something *item1;struct somethingelse *item2;int stuff_ok;void cleanup_module(void){if (item1)release_thing(item1);if (item2)release_thing2(item2);if (stuff_ok)unregister_stuff();return;}int init_module(void){int err = -ENOMEM;item1 = allocate_thing(arguments);item2 = allocate_thing2(arguments2);if (!item2 || !item2)goto fail;err = register_stuff(item1, item2);if (!err)stuff_ok = 1;elsegoto fail;return 0; /* success */fail:cleanup_module();return err;}As shown in this code, you may or may not need external flags to mark success ofthe initialization step, depending on the semantics of the registration/allocationfunction you call.

Whether or not flags are needed, this kind of initialization scaleswell to a large number of items and is often better than the technique shownearlier.3222 June 2001 16:34http://openlib.org.uaInitialization and ShutdownThe Usage CountThe system keeps a usage count for every module in order to determine whetherthe module can be safely removed. The system needs this information because amodule can’t be unloaded if it is busy: you can’t remove a filesystem type whilethe filesystem is mounted, and you can’t drop a char device while a process isusing it, or you’ll experience some sort of segmentation fault or kernel panic whenwild pointers get dereferenced.In modern kernels, the system can automatically track the usage count for you,using a mechanism that we will see in the next chapter. There are still times, however, when you will need to adjust the usage count manually. Code that must beportable to older kernels must still use manual usage count maintenance as well.To work with the usage count, use these three macros:MOD_INC_USE_COUNTIncrements the count for the current moduleMOD_DEC_USE_COUNTDecrements the countMOD_IN_USEEvaluates to true if the count is not zeroThe macros are defined in <linux/module.h>, and they act on internal datastructures that shouldn’t be accessed directly by the programmer.

The internals ofmodule management changed a lot during 2.1 development and were completelyrewritten in 2.1.18, but the use of these macros did not change.Note that there’s no need to check for MOD_IN_USE from within cleanup_module,because the check is performed by the system call sys_delete_module (defined inker nel/module.c) in advance.Proper management of the module usage count is critical for system stability.Remember that the kernel can decide to try to unload your module at absolutelyany time. A common module programming error is to start a series of operations(in response, say, to an open request) and increment the usage count at the end. Ifthe kernel unloads the module halfway through those operations, chaos isensured.

To avoid this kind of problem, you should call MOD_INC_USE_COUNTbefor e doing almost anything else in a module.You won’t be able to unload a module if you lose track of the usage count. Thissituation may very well happen during development, so you should keep it inmind. For example, if a process gets destroyed because your driver dereferenced aNULL pointer, the driver won’t be able to close the device, and the usage countwon’t fall back to zero. One possible solution is to completely disable the usagecount during the debugging cycle by redefining both MOD_INC_USE_COUNT and3322 June 2001 16:34http://openlib.org.uaChapter 2: Building and Running ModulesMOD_DEC_USE_COUNT to no-ops.

Another solution is to use some other methodto force the counter to zero (you’ll see this done in the section “Using the ioctlArgument” in Chapter 5). Sanity checks should never be circumvented in a production module. For debugging, however, sometimes a brute-force attitude helpssave development time and is therefore acceptable.The current value of the usage count is found in the third field of each entry in/pr oc/modules. This file shows the modules currently loaded in the system, withone entry for each module.

The fields are the name of the module, the number ofbytes of memory it uses, and the current usage count. This is a typical /pr oc/modules file:parport_pc7604 1 (autoclean)lp4800 0 (unused)parport8084 1 [parport_probe parport_pc lp]lockd33256 1 (autoclean)sunrpc56612 1 (autoclean) [lockd]ds6252 1i8236522304 1pcmcia_core41280 0 [ds i82365]Here we see several modules in the system. Among other things, the parallel portmodules have been loaded in a stacked manner, as we saw in Figure 2-2.

The(autoclean) marker identifies modules managed by kmod or ker neld (seeChapter 11); the (unused) marker means exactly that. Other flags exist as well.In Linux 2.0, the second (size) field was expressed in pages (4 KB each on mostplatforms) rather than bytes.UnloadingTo unload a module, use the rmmod command. Its task is much simpler thanloading, since no linking has to be performed.

The command invokes thedelete_module system call, which calls cleanup_module in the module itself if theusage count is zero or returns an error otherwise.The cleanup_module implementation is in charge of unregistering every item thatwas registered by the module. Only the exported symbols are removed automatically.Explicit Initialization and Cleanup FunctionsAs we have seen, the kernel calls init_module to initialize a newly loaded module,and calls cleanup_module just before module removal.

In modern kernels, however, these functions often have different names. As of kernel 2.3.13, a facilityexists for explicitly naming the module initialization and cleanup routines; usingthis facility is the preferred programming style.3422 June 2001 16:34http://openlib.org.uaUsing ResourcesConsider an example. If your module names its initialization routine my_init(instead of init_module) and its cleanup routine my_cleanup, you would markthem with the following two lines (usually at the end of the source file):module_init(my_init);module_exit(my_cleanup);Note that your code must include <linux/init.h> to use module_init andmodule_exit.The advantage of doing things this way is that each initialization and cleanup function in the kernel can have a unique name, which helps with debugging.

Thesefunctions also make life easier for those writing drivers that work either as a module or built directly into the kernel. However, use of module_init and module_exitis not required if your initialization and cleanup functions use the old names. Infact, for modules, the only thing they do is define init_module and cleanup_module as new names for the given functions.If you dig through the kernel source (in versions 2.2 and later), you will likely seea slightly different form of declaration for module initialization and cleanup functions, which looks like the following:static int _ _init my_init(void){....}static void _ _exit my_cleanup(void){....}The attribute _ _init, when used in this way, will cause the initialization functionto be discarded, and its memory reclaimed, after initialization is complete.

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