《linux内核模块编程.pdf》由会员分享,可在线阅读,更多相关《linux内核模块编程.pdf(80页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。
1、The Linux Kernel Module Programming GuidePeter Jay SalzmanMichael BurianOri PomerantzCopyright 2001 Peter Jay Salzman20050526 ver 2.6.1The Linux Kernel Module Programming Guide is a free book;you may reproduce and/or modify it under theterms of the Open Software License,version 1.1.You can obtain a
2、copy of this license athttp:/opensource.org/licenses/osl.php.This book is distributed in the hope it will be useful,but without any warranty,without even the impliedwarranty of merchantability or fitness for a particular purpose.The author encourages wide distribution of this book for personal or co
3、mmercial use,provided the abovecopyright notice remains intact and the method adheres to the provisions of the Open Software License.Insummary,you may copy and distribute this book free of charge or for a profit.No explicit permission isrequired from the author for reproduction of this book in any m
4、edium,physical or electronic.Derivative works and translations of this document must be placed under the Open Software License,and theoriginal copyright notice must remain intact.If you have contributed new material to this book,you mustmake the material and source code available for your revisions.
5、Please make revisions and updates availabledirectly to the document maintainer,Peter Jay Salzman.This will allow for the merging ofupdates and provide consistent revisions to the Linux community.If you publish or distribute this book commercially,donations,royalties,and/or printed copies are greatly
6、appreciated by the author and the Linux Documentation Project(LDP).Contributing in this way shows yoursupport for free software and the LDP.If you have questions or comments,please contact the address above.Table of ContentsForeword.11.Authorship.12.Versioning and Notes.13.Acknowledgements.1Chapter
7、1.Introduction.21.1.What Is A Kernel Module?.21.2.How Do Modules Get Into The Kernel?.21.2.1.Before We Begin.3Chapter 2.Hello World.52.1.Hello,World(part 1):The Simplest Module.52.1.1.Introducing printk().62.2.Compiling Kernel Modules.62.3.Hello World(part 2).72.4.Hello World(part 3):The _init and _
8、exit Macros.82.5.Hello World(part 4):Licensing and Module Documentation.92.6.Passing Command Line Arguments to a Module.112.7.Modules Spanning Multiple Files.142.8.Building modules for a precompiled kernel.15Chapter 3.Preliminaries.173.1.Modules vs Programs.173.1.1.How modules begin and end.173.1.2.
9、Functions available to modules.173.1.3.User Space vs Kernel Space.183.1.4.Name Space.183.1.5.Code space.193.1.6.Device Drivers.19Chapter 4.Character Device Files.214.1.Character Device Drivers.214.1.1.The file_operations Structure.214.1.2.The file structure.224.1.3.Registering A Device.224.1.4.Unreg
10、istering A Device.234.1.5.chardev.c.234.1.6.Writing Modules for Multiple Kernel Versions.26Chapter 5.The/proc File System.285.1.The/proc File System.285.2.Read and Write a/proc File.305.3.Manage/proc file with standard filesystem.33Chapter 6.Using/proc For Input.386.1.TODO:Write a chapter about sysf
11、s.38The Linux Kernel Module Programming GuideiTable of ContentsChapter 7.Talking To Device Files.397.1.Talking to Device Files(writes and IOCTLs).39Chapter 8.System Calls.488.1.System Calls.48Chapter 9.Blocking Processes.539.1.Blocking Processes.53Chapter 10.Replacing Printks.6110.1.Replacing printk
12、.6110.2.Flashing keyboard LEDs.63Chapter 11.Scheduling Tasks.6611.1.Scheduling Tasks.66Chapter 12.Interrupt Handlers.7012.1.Interrupt Handlers.7012.1.1.Interrupt Handlers.7012.1.2.Keyboards on the Intel Architecture.70Chapter 13.Symmetric Multi Processing.7413.1.Symmetrical MultiProcessing.74Chapter
13、 14.Common Pitfalls.7514.1.Common Pitfalls.75Appendix A.Changes:2.0 To 2.2.76A.1.Changes between 2.4 and 2.6.76A.1.1.Changes between 2.4 and 2.6.76Appendix B.Where To Go From Here.77B.1.Where From Here?.77The Linux Kernel Module Programming GuideiiForeword1.AuthorshipThe Linux Kernel Module Programm
14、ing Guide was originally written for the 2.2 kernels by Ori Pomerantz.Eventually,Ori no longer had time to maintain the document.After all,the Linux kernel is a fast movingtarget.Peter Jay Salzman took over maintenance and updated it for the 2.4 kernels.Eventually,Peter nolonger had time to follow d
15、evelopments with the 2.6 kernel,so Michael Burian became a comaintainer toupdate the document for the 2.6 kernels.2.Versioning and NotesThe Linux kernel is a moving target.There has always been a question whether the LKMPG should removedeprecated information or keep it around for historical sake.Mic
16、hael Burian and I decided to create a newbranch of the LKMPG for each new stable kernel version.So version LKMPG 2.4.x will address Linux kernel2.4 and LKMPG 2.6.x will address Linux kernel 2.6.No attempt will be made to archive historicalinformation;a person wishing this information should read the
17、 appropriately versioned LKMPG.The source code and discussions should apply to most architectures,but I cant promise anything.Oneexception is Chapter 12,Interrupt Handlers,which should not work on any architecture except for x86.3.AcknowledgementsThe following people have contributed corrections or
18、good suggestions:Ignacio Martin,David Porter,DanielePaolo Scarpazza,Dimo Velev and Francois AudeonForeword1Chapter 1.Introduction1.1.What Is A Kernel Module?So,you want to write a kernel module.You know C,youve written a few normal programs to run asprocesses,and now you want to get to where the rea
19、l action is,to where a single wild pointer can wipe outyour file system and a core dump means a reboot.What exactly is a kernel module?Modules are pieces of code that can be loaded and unloaded into the kernelupon demand.They extend the functionality of the kernel without the need to reboot the syst
20、em.For example,one type of module is the device driver,which allows the kernel to access hardware connected to the system.Without modules,we would have to build monolithic kernels and add new functionality directly into thekernel image.Besides having larger kernels,this has the disadvantage of requi
21、ring us to rebuild and reboot thekernel every time we want new functionality.1.2.How Do Modules Get Into The Kernel?You can see what modules are already loaded into the kernel by running lsmod,which gets its information byreading the file/proc/modules.How do these modules find their way into the ker
22、nel?When the kernel needs a feature that is not resident inthe kernel,the kernel module daemon kmod1 execs modprobe to load the module in.modprobe is passed astring in one of two forms:A module name like softdog or ppp.A more generic identifier like charmajor1030.If modprobe is handed a generic iden
23、tifier,it first looks for that string in the file/etc/modprobe.conf.2 If it finds an alias line like:alias charmajor1030 softdogit knows that the generic identifier refers to the module softdog.ko.Next,modprobe looks through the file/lib/modules/version/modules.dep,to see if othermodules must be loa
24、ded before the requested module may be loaded.This file is created by depmod a andcontains module dependencies.For example,msdos.ko requires the fat.ko module to be already loadedinto the kernel.The requested module has a dependancy on another module if the other module definessymbols(variables or f
25、unctions)that the requested module uses.Lastly,modprobe uses insmod to first load any prerequisite modules into the kernel,and then the requestedmodule.modprobe directs insmod to/lib/modules/version/3,the standard directory for modules.insmod is intended to be fairly dumb about the location of modul
26、es,whereas modprobe is aware of the defaultlocation of modules,knows how to figure out the dependancies and load the modules in the right order.So forexample,if you wanted to load the msdos module,youd have to either run:insmod/lib/modules/2.6.11/kernel/fs/fat/fat.koinsmod/lib/modules/2.6.11/kernel/
27、fs/msdos/msdos.koChapter 1.Introduction2or:modprobe msdosWhat weve seen here is:insmod requires you to pass it full pathname and to insert the modules in the rightorder,while modprobe just takes the name,without any extension,and figures out all it needs to know byparsing/lib/modules/version/modules
28、.dep.Linux distros provide modprobe,insmod and depmod as a package called moduleinittools.In previousversions that package was called modutils.Some distros also set up some wrappers that allow both packagesto be installed parallel and do the right thing in order to be able to deal with 2.4 and 2.6 k
29、ernels.Users shouldnot need to care about the details,as long as theyre running recent versions of that tools.Now you know how modules get into the kernel.Theres a bit more to the story if you want to write your ownmodules which depend on other modules(we calling this stacking modules).But this will
30、 have to wait for afuture chapter.We have a lot to cover before addressing this relatively highlevel issue.1.2.1.Before We BeginBefore we delve into code,there are a few issues we need to cover.Everyones system is different andeveryone has their own groove.Getting your first hello world program to c
31、ompile and load correctly cansometimes be a trick.Rest assured,after you get over the initial hurdle of doing it for the first time,it will besmooth sailing thereafter.1.2.1.1.ModversioningA module compiled for one kernel wont load if you boot a different kernel unless you enableCONFIG_MODVERSIONS i
32、n the kernel.We wont go into module versioning until later in this guide.Untilwe cover modversions,the examples in the guide may not work if youre running a kernel with modversioningturned on.However,most stock Linux distro kernels come with it turned on.If youre having trouble loadingthe modules be
33、cause of versioning errors,compile a kernel with modversioning turned off.1.2.1.2.Using XIt is highly recommended that you type in,compile and load all the examples this guide discusses.Its alsohighly recommended you do this from a console.You should not be working on this stuff in X.Modules cant pr
34、int to the screen like printf()can,but they can log information and warnings,which endsup being printed on your screen,but only on a console.If you insmod a module from an xterm,theinformation and warnings will be logged,but only to your log files.You wont see it unless you look throughyour log file
35、s.To have immediate access to this information,do all your work from console.1.2.1.3.Compiling Issues and Kernel VersionVery often,Linux distros will distribute kernel source that has been patched in various nonstandard ways,which may cause trouble.A more common problem is that some Linux distros di
36、stribute incomplete kernel headers.Youll need tocompile your code using various header files from the Linux kernel.Murphys Law states that the headers thatare missing are exactly the ones that youll need for your module work.The Linux Kernel Module Programming GuideChapter 1.Introduction3To avoid th
37、ese two problems,I highly recommend that you download,compile and boot into a fresh,stockLinux kernel which can be downloaded from any of the Linux kernel mirror sites.See the Linux KernelHOWTO for more details.Ironically,this can also cause a problem.By default,gcc on your system may look for the k
38、ernel headers intheir default location rather than where you installed the new copy of the kernel(usually in/usr/src/.This can be fixed by using gccs I switch.The Linux Kernel Module Programming GuideChapter 1.Introduction4Chapter 2.Hello World2.1.Hello,World(part 1):The Simplest ModuleWhen the firs
39、t caveman programmer chiseled the first program on the walls of the first cave computer,it wasa program to paint the string Hello,world in Antelope pictures.Roman programming textbooks began withthe Salut,Mundi program.I dont know what happens to people who break with this tradition,but I think itss
40、afer not to find out.Well start with a series of hello world programs that demonstrate the different aspects ofthe basics of writing a kernel module.Heres the simplest module possible.Dont compile it yet;well cover module compilation in the next section.Example 21.hello1.c/*hello1.c The simplest ker
41、nel module.*/#include /*Needed by all modules*/#include /*Needed for KERN_INFO*/int init_module(void)printk(KERN_INFO Hello world 1.n);/*A non 0 return means init_module failed;module cant be loaded.*/return 0;void cleanup_module(void)printk(KERN_INFO Goodbye world 1.n);Kernel modules must have at l
42、east two functions:a start(initialization)function called init_module()which is called when the module is insmoded into the kernel,and an end(cleanup)function calledcleanup_module()which is called just before it is rmmoded.Actually,things have changed starting withkernel 2.3.13.You can now use whate
43、ver name you like for the start and end functions of a module,and youlllearn how to do this in Section 2.3.In fact,the new method is the preferred method.However,many peoplestill use init_module()and cleanup_module()for their start and end functions.Typically,init_module()either registers a handler
44、for something with the kernel,or it replaces one of thekernel functions with its own code(usually code to do something and then call the original function).Thecleanup_module()function is supposed to undo whatever init_module()did,so the module can beunloaded safely.Lastly,every kernel module needs t
45、o include linux/module.h.We needed to includelinux/kernel.h only for the macro expansion for the printk()log level,KERN_ALERT,which youlllearn about in Section 2.1.1.Chapter 2.Hello World52.1.1.Introducing printk()Despite what you might think,printk()was not meant to communicate information to the u
46、ser,eventhough we used it for exactly this purpose in hello1!It happens to be a logging mechanism for the kernel,and is used to log information or give warnings.Therefore,each printk()statement comes with a priority,which is the and KERN_ALERT you see.There are 8 priorities and the kernel has macros
47、 for them,soyou dont have to use cryptic numbers,and you can view them(and their meanings)in linux/kernel.h.If you dont specify a priority level,the default priority,DEFAULT_MESSAGE_LOGLEVEL,will be used.Take time to read through the priority macros.The header file also describes what each priority
48、means.Inpractise,dont use number,like.Always use the macro,like KERN_WARNING.If the priority is less than int console_loglevel,the message is printed on your current terminal.Ifboth syslogd and klogd are running,then the message will also get appended to/var/log/messages,whether it got printed to th
49、e console or not.We use a high priority,like KERN_ALERT,to make sure theprintk()messages get printed to your console rather than just logged to your logfile.When you write realmodules,youll want to use priorities that are meaningful for the situation at hand.2.2.Compiling Kernel ModulesKernel module
50、s need to be compiled a bit different than regular userspace apps.Former kernel versionsrequired us to care much about these settings,which are usually stored in Makefiles.Although hierarchicallyorganized,many redundant settings accumulated in sublevel Makefiles and made them large and ratherdifficu