writting you first linux kernel module - uni-hamburg.de · • error number defini$ons at ... •...
TRANSCRIPT
Wri$ngyourfirstLinuxkernelmodule
Prak$kumKernelProgrammingUniversityofHamburgScien$ficCompu$ng
Wintersemester2015/2016
Konstan$nosChasapisKonstan$nos.chasapis@informa$k.uni-hamburg.de
Outline
• Beforeyoustart• Helloworldmodule• Build,loadandunload• UserVSKernelspaceprogramming
18/11/15 Kernel Module Demo 1
Beforeyoustart
• Defineyourmodule’sgoal• Defineyourmodulebehaviour• Knowyourhardwarespecifica$ons
– Ifyouarebuildingadevicedriveryoushouldhavethemanual
• Documenta$on– /usr/src/linux/Documenta$on– make{htmldocs|psdocs|pdfdocks|
rUdocks}– /usr/src/linux/Documenta$on/DocBook
18/11/15 Kernel Module Demo 2
Roleofthedevicedriver• SoXwarelayerbetweenapplica$onanddevice
“blackboxes”– Offerabstrac$on
• Makehardwareavailabletousers– Hidecomplexity
• Userdoesnotneedtoknowtheirimplementa$on• Providemechanismnotpolicy
– Mechanism• Providingtheflexibilityandtheabilitythedevice
supports– Policy
• Controllinghowthesecapabili$esarebeingused
18/11/15 Kernel Module Demo 3
Roleofthedevicedriver
• Policy-freecharacteris$cs– Synchronousandasynchronousopera$ons– Exploitthefullcapabili$esofthehardware– OXenaclientlibraryisprovidedaswell
• Providescapabili$esthatdonotneedtobeimplementedinsidethemodule
18/11/15 Kernel Module Demo 4
Outline
• Beforeyoustart• Helloworldmodule• Build,loadandunload• UserVSKernelspaceprogramming
18/11/15 Kernel Module Demo 5
Helloworldmodule/*theshutdownfunc/on*/
sta$cvoid__exithello_exit(void){printk("Goodbye,!\n");}
/*declareswhichfunc/onwillbe
invokedwhenthemoduleisremoved*/module_exit(hello_exit);
/*headerfiles*/#include<linux/module.h>#include<linux/init.h>/*theini/aliza/onfunc/on*/
sta$cint__inithello_init(void){printk("Helloworld!\n");return0;/*success*/}/*declareswhichfunc/onwillbeinvokedwhenthemoduleisloaded*/module_init(hello_init);
18/11/15 Kernel Module Demo 6
Ini$aliza$onfunc$on• Eachmodulemustuseone• Declaredassta$c• __init<name>
– Useonlyatini$aliza$on• __initdata
– Markini$aliza$ondata• Doesnotacceptparameters• Returnserrorcode• Kerneldropsinitfunc$onanddata
– Makesthememoryavailabletothesystem
sta$cint__inithello_init(void){printk("Helloworld!\n");return0;/*success*/}module_init(hello_init);
18/11/15 Kernel Module Demo 7
Shutdownfunc$on• Onlyifyouneedtounloadthemodule
• Declaredassta$c• __exit<name>
– onlyatshutdown• module_exit(<name>)
• Ifnotdefined– Modulescannotbeunloaded
• Thebuildinmodulesdonotrequireshutdown
sta$cvoid__exithello_exit(void){printk("Goodbye,!\n");}
module_exit(hello_exit);
18/11/15 Kernel Module Demo 8
printk
• SimilartoprinUbut:– Printstothekernellogfile– Doesnotsupportalltheformaongparameters
• Veryexpensiveopera$on– Lotsofprintk’scansignificantlyslowdownthe
system• Acceptsloglevels
– Ahinttothekerneltodecideifitshouldprintthestringtothelogfile
– DefaultKERN_WARNING18/11/15 Kernel Module Demo 9
printk-loglevels• KERN_EMER
– Anemergencycondi$on
• KERN_ALERT,
– requiresimmediatearen$on
• KERN_CRIT
• KERN_ERR
• KERN_WARNING
• KERN_NOTICE
• KERN_INFO
• KERN_DEBUG18/11/15 Kernel Module Demo 10
Moduleparameters• Passparameterstothemodulethrough
– insmod– modprobe
• modprobereadsparametersthought– /etc/modprobe
• Readparametervaluewhilemoduleisloaded– catsys/module/<mod_na>/parameters/
<param_na>
18/11/15 Kernel Module Demo 11
Moduleparameters
• Parameterdeclara$on– module_param(name,type,permission)
• Permissionsmodesareasfileaccessmodes• Parameterstypes:
– bool,inbool(invertedbool)– charp,string– int,long,short– uint,ulong,ushort
• Alsoacceptsarraysparameters– module_param_array(name,type,nump,
perm)
18/11/15 Kernel Module Demo 12
Errorhandling
• Failuremayoccurduringini$aliza$onphase– memoryalloca$on– deviceisbusy
• con$nueordrop?– Ifwedrop
• undoanyregistra$onac$vi$esperformedbefore• incasewefailtounregisterthekernelgoesinto
unstablemode• Recoveryisusuallyhandlewiththegoto
statement
18/11/15 Kernel Module Demo 13
Errorhandling• Errornumberdefini$onsat<linux/errno.h>
– Returnnega$vevalues-errorcode;• #defineEPERM 1 /*Opera$onnotpermired*/• #defineENOENT2 /*Nosuchfileordirectory*/• #defineEIO 5 /*I/Oerror*/• #defineENOEXEC 8 /*Execformaterror*/• #defineEAGAIN 11 /*Tryagain*/• #defineENOMEM 12 /*Outofmemory*/• #defineEACCES13/*Permissiondenied*/• #defineENOSYS 38 /*Func$onnotimplemented*/• #defineENOTEMPTY39/*Directorynotempty*/
18/11/15 Kernel Module Demo 14
Outline
• Beforeyoustart• Helloworldmodule• Build,loadandunload• UserVSKernelspaceprogramming
18/11/15 Kernel Module Demo 15
Compile
• kbuild– thesystemthatisusedtocompilekernel
modules– /Documenta$on/kbuild/
• Youmusthaveapre-buildkernelwithconfigura$onandheaderfiles
• Manydistribu$onshavepackagesfortherequiredfilesandtools– kernel-develpackageforCentOS
18/11/15 Kernel Module Demo 16
Compilecommand
• make-C$KDIRM=$PWD[target]– $KDIR
• thedirectorywherethekernelsourceislocated.• makewillchangethedirectoryforthecompileand
willreturnaXerthecompile
– M=$PWD• Informskbuildthatanexternalmoduleisbeing
build.• ThevalueofMistheabsolutepaththedirectory
thatcontainsthesourcecodeofthemodule
18/11/15 Kernel Module Demo 17
makecommandtargets• modules
– Thedefaulttargetthatcanbeignored• modules_install
– Installstheexternalmodules– Thedefaultloca$onis/lib/modules/<kernel_release>/
extra/• clean
– removeallgeneratedfilesinthemoduledirectoryonly• help
– listtheavailabletargetfortheexternalmodules
18/11/15 Kernel Module Demo 18
kbuildfile• Containsthenameofthemodule(s)beingbuilt,alongwiththe
requisitesourcefiles– obj-m:=<m_name>.o
• kbuildwillbuild<m_name>.ofrom<m_name>.c– Thenitwilllinkitandwillresultinthekernelmodule
<m_name>.ko– Anaddi$onallineisneededtoaddmorefiles
• <module_name>-y:=<src1>.o<src2>.o....– Includefilesanddirectories
• standardfilesusing#include<file>• ccflags-y:=-Iinclude_path
18/11/15 Kernel Module Demo 19
Module.symversfile
• ModuleversioningisenabledbytheCONFIG_MODVERSIONStag
• ItisusedasasimpleApplica$onBinaryInterface(ABI)consistencycheck
• Itcontainsalistofallexportedsymbolsfromakernelbuild
• /proc/kallsyms
18/11/15 Kernel Module Demo 20
insmod(insertmodule)• loadthemoduleintothekernel
• triggerstheexecu$onofthemodule_initfunc$on
• Similartotheldinuserspace• Loadthemodulecodeanddataintothekernel
memory• Linksanyunresolvedsymbolinthemoduletothe
symboltableofthekernel• Acceptscommandlinearguments
• Parameterstothekernelmodule• Addanentryat/proc/modules• Formoredetailscheckkernel/module.c
Kernel
Module
.init_module
18/11/15 Kernel Module Demo 21
rmmod(removemodule)• Removes/unloadsthemodulefromthekernel• Mustfreememoryandreleaserecourse• Incaseoffailurethekernels$llbelievesthat
themoduleisinuse• Incasethatrmmodfailstherebootprocessis
requiredtocleanthesystemsstate
Kernel
Module
.exit_module
18/11/15 Kernel Module Demo 22
Moretools• lsmod(listmodules)
– Listofthecurrentloadedmodules• modprobe(similartoinsmod)
– Searchforsymbolsthatarenotcurrentlydefinedinthekernel– Incasethattherearethensearchforinkernelmodulestofind
modulesthatcontainthesesymbols– Itloadsthesemodulesintothekernel
• depmod– Createsadependencyfile,usedbymodprobe
• modinfo– Showsinforma$onaboutaLinuxKernelmodule
18/11/15 Kernel Module Demo 23
Versiondependency• Moduleshavetoberecompiledforeachversion
– datastructuresandfunc$onprototypescanchangesfromversiontoversion
– duringcompila$onthemoduleislinkedagainstafilenamedvermagic.o
– Thisfilecontainstargetkernelversion,compilerversionetc.
• Incasethatthemoduleiscompileagainstdifferentkernelversion– insmod:Invalidmoduleformat
18/11/15 Kernel Module Demo 24
Versiondependency(cont.)• Macrostodefinekernelversionduringcompila$onfoundin/
linux/version.h– UTS_RELEASE,theversionofthiskerneltree– LINUX_VERSION_CODE,binaryrepresenta$onofthe
kernelversion– KERNEL_VERSION(major,minor,release),buildaninter
versioncode
18/11/15 Kernel Module Demo 25
KernelSymbolTable• Kernelhasalreadyexportedsymbols• Loadedmodulescanexportnewsymbols
– offertheirfunc$onalitytoothermodules• Stackmodulesontopofothermodules
– Reducecomplexityofthemodules– Addflexibilitytochoosemodulesdependingonthespecific
hardware• Macrostoexportnewsymbols
– EXPORT_SYMBOL(name);– EXPORT_SYMBOL_GPL(make);
• Expandintospecificvariabledeclara$onsstoredinthemoduleexecutablefile
18/11/15 Kernel Module Demo 26
dkms
• DynamicKernelModuleSupport– Frameworkthatenablesgenera$ngLinux
kernelmoduleswhosesourcesgenerallyresideoutsidethekernelsourcetree
– Usedtoautoma$callyrebuiltmoduleswhenanewkernelisinstalled
– Itisincludedinmanydistribu$ons
18/11/15 Kernel Module Demo 27
Outline
• Beforeyoustart• Helloworldmodule• Build,loadandunload• UserVSKernelspaceprogramming
18/11/15 Kernel Module Demo 28
UserVS.Kernelprogramming• kernelmoduleprogramming
– similartoeventdrivenprogramming• initfunc$on
– says:heyIamhere,Iwillserveyourrequestsfromnowandon
• exitfunc$on– says:Iamgoingtoleaveyou..don'tbothertryingto
findmeanymore• Unload
– shouldreleaseanyresourcethatthemodulehadacquired
18/11/15 Kernel Module Demo 29
UserVS.Kernelprogramming• kernelmodulerunsinkernelspace
– Coreoftheopera$ngsystem– Privilegedopera$ngsystemfunc$ons– Fullaccesstoallmemoryandmachinehardware– Kerneladdressspace
• Userprogramsruninuserspace– Itrestrictsuserprogramssotheycan'tmessresourcesowned
byotherprogramsorbytheOSkernel– Limitedabilitytodobadthingslikecrashingthemachine
18/11/15 Kernel Module Demo 30
UserVS.Kernelprogramming• SystemcallsSwitchbetweenuserandkernel• Memoryhandling
– mallocisClibrarycall-NOTasystemcall• Usebrksystemcall
– Kernelallocatesvirtualmemoryareafortheapplica$on
– Lacksofmemoryprotec$on• Portability
– Kernelmodulesworkwithspecificversionanddistribu$onofthekernelandmightbeplaUorm-specific
18/11/15 Kernel Module Demo 31
UserVS.Kernelprogramming• Kerneldoesnothavestandardheaders
– IsnotlinkedagainstthestandardClibrary– However,manyfunc$onsareimplementedinsidetheLinux
kernel• Cannotexecuteeasilyfloa$ngpointopera$ons
– Floa$ngpointopera$onsarearchitecturedependent– Usually,implementedwithtraps,(triggerintegertofloa$ng
pointmodetransi$on)– Inthekernelspaceitrequiressavingandrestoringthefloa$ng
pointopera$onsmanually• Smallfixedsizestack
– Configurableatcompile$me(4KBor8KB)18/11/15 Kernel Module Demo 32