Home
Linux Kernel and Driver Development Training
Contents
1. gt foo_write struct file f const __user buf SZ off gt Called when user space uses the write system call on the device gt The opposite of read must read at most sz bytes from buf write it to the device update off and return the number of bytes written Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 212 473 Exchanging data with user space 1 3 gt Kernel code isn t allowed to directly access user space memory using memcpy or direct pointer dereferencing gt Doing so does not work on some architectures gt If the address passed by the application was invalid the application would segfault gt To keep the kernel code portable and have proper error handling your driver must use special kernel functions to exchange data with user space Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 213 473 Exchanging data with user space 2 3 gt A single value gt get_user v p gt The kernel variable v gets the value pointed by the user space pointer p gt put_user v p gt The value pointed by the user space pointer p is set to the contents of the kernel variable v gt A buffer gt copy_to_user __user to const from n gt copy_from_user to const __user from n gt The return value must be checked Zero on suc
2. Jre Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 367 473 Crystalfontz CFA 10036 bus UART gt Start of the internal SoC peripherals apb s0000000 apbh 80000000 apbx 80040000 gt The CFA 10036 has one debug UART so the corresponding controller is enabled duart serial 80074000 pinctrl names default pinctrl 0 lt amp duart_pins_b gt status okay os Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 368 473 Crystalfontz CFA 10036 Device Tree Muxing gt Definition of a few pins that will be muxed as GPIO for LEDs and reset pinctr1 80018000 ssd1306_cfai0036 ssd1306 10036 0 reg lt 0 gt fsl pinmux ids lt 0x2073 MX28_PAD_SSPO_D7__GPIO_2_7 gt fsl drive strength lt 0 gt fsl voltage lt 1 gt fsl pull up lt 0 gt led_pins_cfa10036 leds 1003600 reg lt 0 gt fsl pinmux ids lt 0x3043 MX28_PAD_AUART1_RX__GPI0_3_4 gt fsl drive strength lt 0 gt fsl voltage lt 1 gt fsl pull up lt 0 gt 3 3 Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 369 473 Crystalfontz CFA 10036 Device Tree LED gt One LED is connected to this platform Note the reference to the led_pins_cfa
3. static int serial_imx_remove struct platform_device pdev retrieve the imx_port from the platform_device struct imx_port sport platform_get_drvdata pdev ree uart_remove_one_port amp imx_reg amp sport gt port Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 232 473 Link Between Structures 3 4 static int ds1305_probe struct spi_device spi struct ds1305 ds1305 set up driver data ds1305 devm_kzalloc amp spi gt dev sizeof ds1305 GFP_KERNEL if ds1305 return ENOMEM ds1305 gt spi spi spi_set_drvdata spi ds1305 struct rtc_device parent register RTC from here on ds1305 gt ctrl needs locking ds1305 gt rtc devm_rtc_device_register amp spi gt dev dsi305 amp ds1305_ops THIS_MODULE static int ds1305_remove struct spi_device spi struct ds1305 ds1305 spi_get_drvdata spi Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 233 473 Link Between Structures 4 4 static int rt18150_probe struct usb_interface intf const struct usb_device_id id netdev struct usb_device udev interface_to_usbdev intf rt18150_t dev struct net_device netdev netdev alloc_etherdev sizeof rt18150_t dev netdev_priv netdev dev
4. owner THIS_MODULE fb_open xxxfb_open fb_read xxxfb_read fb_write xxxfb_write fb_release xxxfb_release fb_check_var xxxfb_check_var fb_set_par xxxfb_set_par fb_setcolreg xxxfb_setcolreg fb_blank xxxfb_blank fb_pan_display xxxfb_pan_display fb_fillrect xxxfb_fillrect fb_copyarea xxxfb_copyarea fb_imageblit xxxfb_imageblit fb_cursor xxxfb_cursor fb_rotate xxxfb_rotate fb_sync xxxfb_sync fb_ioctl xxxfb_ioctl fb_mmap xxxfb_mmap F Needed Needed Needed Optional Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 226 473 Framebuffer Driver Skeleton gt In the probe function registration of the framebuffer device and operations static xxxfb_probe struct pci_dev dev const struct pci_device_id ent struct fb_info info info framebuffer_alloc sizeof struct xxx_par device Leas info gt fbops amp xxxfb_ops if register_framebuffer info gt 0 return EINVAL sxe gt register_framebuffer will create the character device that can be used by user space applications with the generic framebuffer API Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 227 473 Driver specific Data Structure gt Each framew
5. 3 Start the kernel with bootz X Y or bootm X Y The in the middle indicates no initramfs v Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 92 473 K d li ernel command line gt In addition to the compile time configuration the kernel behaviour can be adjusted with no recompilation using the kernel command line gt The kernel command line is a string that defines various arguments to the kernel gt It is very important for system configuration gt root for the root filesystem covered later gt console for the destination of kernel messages gt Many more exist The most important ones are documented in Documentation kernel parameters txt in kernel sources gt This kernel command line is either gt Passed by the bootloader In U Boot the contents of the bootargs environment variable is automatically passed to the kernel gt Built into the kernel using the CONFIG_CMDLINE option Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 93 473 Practical lab Kernel compiling and booting 1st lab board and bootloader setup gt Prepare the board and access its serial port gt Configure its bootloader to use TFTP 2nd lab kernel compiling and booting gt Set up a cross compiling environment gt Cross compile a kernel for an ARM target p
6. A normal driver should not need any non exported function Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 110 473 Symbols exported to modules 2 2 GPL Module A void func4 EXPORT_SYMBOL_GPL func4 funcl func2 void func1 func3 func4 void func2 EXPORT_SYMBOL func2 void func3 EXPORT_SYMBOL_GPL func3 funcl funcl func2 func2 func3 func3 func4 func4 GPL Module C funcl func2 func3 func4 Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 111 473 Module Li odule License gt Several usages gt Used to restrict the kernel functions that the module can use if it isn t a GPL licensed module gt Difference between EXPORT_SYMBOL and EXPORT_SYMBOL_GPL gt Used by kernel developers to identify issues coming from proprietary drivers which they can t do anything about Tainted kernel notice in kernel crashes and oopses gt Useful for users to check that their system is 100 free check proc sys kernel tainted gt Values gt GPL compatible see include linux license h GPL GPL v2 GPL and additional rights Dual MIT GPL Dual BSD GPL Dual MPL GPL gt Proprietary Free Electrons Embedded Linux kernel drivers and Android development consulti
7. Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 29 473 Getting Linux sources gt The kernel sources are available from http kernel org pub linux kernel as full tarballs complete kernel sources and patches differences between two kernel versions gt However more and more people use the git version control system Absolutely needed for kernel development gt Fetch the entire kernel sources and history git clone git git kernel org pub scm linux kernel git torvalds linux git gt Create a branch that starts at a specific stable version git checkout b lt name of branch gt v3 11 gt Web interface available at http git kernel org cgit linux kernel git torvalds linux git tree gt Read more about Git at http git scm com Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 30 473 Linux kernel size 1 gt Linux 3 10 sources Raw size 573 MB 43 000 files approx 15 800 000 lines gzip compressed tar archive 105 MB bzip2 compressed tar archive 83 MB better xz compressed tar archive 69 MB best gt Minimum Linux 2 6 29 compiled kernel size with CONFIG_EMBEDDED for a kernel that boots a QEMU PC IDE hard drive ext2 filesystem ELF executable support 532 KB compressed 1325 KB raw gt Why are these sources so big Because they include thousands of device
8. Locations Orange Toulouse Saint Etienne Lyon France gt Serving customers all around the world See http free electrons com company customers gt Head count 9 Only Free Software enthusiasts gt Focus Embedded Linux Linux kernel Android Free Software Open Source for embedded and real time systems gt Activities development training consulting technical support gt Added value get the best of the user and development community and the resources it offers Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 5 473 Free Electrons on line resources gt All our training materials http free electrons com docs Technical blog http free electrons com blog Quarterly newsletter http lists free electrons com mailman listinfo newsletter News and discussions Google https plus google com FreeElectronsDevelopers News and discussions LinkedIn http linkedin com groups Free Electrons 4501089 Quick news Twitter http twitter com free_electrons Linux Cross Reference browse Linux kernel sources on line http lxr free electrons com Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 6 473 Mailing lists for session participants If you participated to a course taught by Free Electrons you can subscribe to our mail
9. Our rating 2 stars IN A NUTSHELL O REILLY Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 105 473 Developing Kernel Modules Developing Kernel H Modules Girone Free Electrons Copyright 2004 2014 Free Electrons Creative Commons BY SA 3 0 license Corrections suggestions contributions and translations are welcome Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 106 473 Hello Module 1 2 hello c include lt linux init h gt include lt linux module h gt include lt linux kernel h gt static int __init hello_init void pr_alert Good morrow to this fair assembly n return 0 static void __exit hello_exit void pr_alert Alas poor world what treasure hast thou lost n module_init hello_init module_exit hello_exit MODULE_LICENSE GPL MODULE_DESCRIPTION Greeting module MODULE_AUTHOR William Shakespeare Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 107 473 Hello Module 2 2 gt __init gt removed after initialization static kernel or module gt __exit gt discarded when module compiled statically into the kernel or when module unloading support is not enabled gt Example available on http git fre
10. T h e m ISC Free Electrons subsystem e Free Electrons Copyright 2004 2014 Free Electrons Creative Commons BY SA 3 0 license Corrections suggestions contributions and translations are welcome Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 284 473 Why a misc subsystem gt The kernel offers a large number of frameworks covering a wide range of device types input network video audio etc gt Those frameworks allow to factorize common functionality between drivers and offer a consistent API to user space applications However there are some devices that really do not fit in any of the existing frameworks gt Highly customized devices implemented in a FPGA or other weird devices for which implementing a complete framework is not useful The drivers for such devices could be implemented directly as raw character drivers But there is a subsystem that makes this work a little bit easier the misc subsystem gt It is really only a thin layer above the character driver API Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 285 473 Misc subsystem diagram User space application User space input input watchdog misc misc driver 1 driver 2 driver A drivera driver b Free Electrons Embedded Linux kernel drivers and Android dev
11. drivers and Android development consulting training and support http free electrons com 139 473 Driver Un Registration gt When the driver is loaded or unloaded it must register or unregister itself from the USB core gt Done using usb_register and usb_deregister provided by the USB core static _ init usb_rt18150_init return usb_register amp rt18150_driver Jr static _ exit usb_rt18150_exit usb_deregister amp rt18150_driver i module_init usb_rt18150_init module_exit usb_rt18150_exit gt Note this code has now been replaced by a shorter module_usb_driver macro call Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 140 473 At Initializati nitialization gt The USB adapter driver that corresponds to the USB controller of the system registers itself to the USB core gt The rt18150 USB device driver registers itself to the USB core usb _add_hcd usb_register rtl8150 gt The USB core now knows the association between the vendor product IDs of rt18150 and the struct usb_driver structure of this driver Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 141 473 When a Device is Detected Step 2 USB core looks up the registered IDs and finds the matching driver Step 1 a new Step 3 The U
12. drivers and Android development consulting training and support http free electrons com 71 473 Corresponding config file excerpt Options are grouped by sections and are prefixed with CONFIG_ CD ROM DVD Filesystems CONFIG_ISO9660_FS m CONFIG_JOLIET y CONFIG_ZISOFS y CONFIG_UDF_FS y CONFIG_UDF_NLS y DOS FAT NT Filesystems CONFIG_MSDOS_FS is not set CONFIG_VFAT_FS is not set CONFIG_NTFS_FS m CONFIG_NTFS_DEBUG is not set CONFIG_NTFS_RW y Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 72 473 k fi make gconfig make gconfig gt GTK based graphical configuration interface Functionality similar to that of make xconfig gt Just lacking a search functionality gt Required Debian packages libglade2 dev Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 73 473 k fi make menuconfig make menuconfig gt Useful when no graphics are available Pretty convenient too gt Same interface found in other tools BusyBox Buildroot gt Required Debian packages libncurses dev Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 74 473 k fi make nconfig make nconfig gt A newer similar text interface opti uta
13. gitk gt gitk is a graphical tool that represents the history of the current Git repository gt Can be installed from the gitk p ackage Be File Edit View TE E Help Merge git igit kerel org pub scm inux kemelgitidavem net 2 6 MAINTAINERS take maintainership of the cpmac Ethemet driver Merge branch fixes of git git keel org pub scri inux kemel givdjbw asy fsidma update mailing ist address in MAINTAINERS Merge master kemel org home rmk inux 2 6 arm MAINTAINER Add F entries for Gemini and FA526 MAINTAINERS change email address for Thomas Dahlmann MAINTAINERS pair EDAC E752x P and M entries MAINTAINERS drop subscribers only markings on Blackfin lists MAINTAINERS update Blackfin items Merge gitvigit kemel org pub scmiinux kemeligitjelb scsi rc tixes 2 6 SCSI nic Add new Cisco PCI Express FCoE HBA hugh update email address 53c3fc41aad9453b8e e SHAIID 43716 7en5 080343 lt gt Row Linus Torvalds lt io 2009 06 01 17 02 05 Florian Faineli lt fio 2008 06 01 11 43 17 Linus Torvalds lt toi 2008 05 30 16 57 33 Li Yang lt leoli tree 2008 05 22 10 39 59 Linus Torvalds lt tol 2008 05 30 01 07 39 Paulius Zaleckas lt 2009 05 28 15 41 36 Thomas Dahimanr 2009 06 28 23 34 30 Joe Perches lt joe 2009 05 28 23 34 18 Miko Frysinger lt va 2009 05 18 10 33 07 Mike Frysinger lt va 2009 05 24 08 13 1 Linus Torvalds lt to1 2009 05 23 22 44 00 Abhijeet Joglekar lt 2008 04
14. imx uart dev platform_data amp uart1_pdata resource imx_uarti_resources ES oll 3 gt The driver can access the platform data static serial_imx_probe struct platform_device pdev struct imxuart_platform_data pdata pdata pdev gt dev platform_data if pdata amp amp pdata gt flags amp IMXUART_HAVE_RTSCTS sport gt have_rtscts 1 ees Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 157 473 Device Tree gt On many embedded architectures manual instantiation of platform devices was considered to be too verbose and not easily maintainable Such architectures are moving or have moved to use the Device Tree It is a tree of nodes that models the hierarchy of devices in the system from the devices inside the processor to the devices on the board Each node can have a number of properties describing various properties of the devices addresses interrupts clocks etc At boot time the kernel is given a compiled version the Device Tree Blob which is parsed to instantiate all the devices described in the DT On ARM they are located in arch arm boot dts Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 158 473 Device Tree example uartO serial 44e09000 compatible ti omap3 uart ti hwmods uarti clock f
15. kernel Makefile config gt The module Makefile is interpreted with KERNELRELEASE undefined so it calls the kernel Makefile passing the module directory in the M variable gt The kernel Makefile knows how to compile a module and thanks to the M variable knows where the Makefile for our module is The module Makefile is interpreted with KERNELRELEASE defined so the kernel sees the obj m definition Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 115 473 Modules and Kernel Version To be compiled a kernel module needs access to the kernel headers containing the definitions of functions types and constants v Two solutions gt Full kernel sources gt Only kernel headers lLinux headers packages in Debian Ubuntu distributions gt The sources or headers must be configured gt Many macros or functions depend on the configuration A kernel module compiled against version X of kernel headers will not load in kernel version Y gt modprobe insmod will say Invalid module format v y Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 116 473 New Driver in Kernel Sources 1 2 gt To add a new driver to the kernel sources gt Add your new source file to the appropriate source directory Example drivers usb serial navman c gt Single file d
16. 4 64 2011 05 27 08 56 dev ttySO crw rw rw 1 root root 1 5 2011 05 27 08 56 dev zero Example C code that uses the usual file API to write data to a serial port fd fd open dev ttySO O_RDWR write fd Hello 5 close fd Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 204 473 Creating device files gt On a basic Linux system the device files have to be created manually using the mknod command gt mknod dev lt device gt clb major minor gt Needs root privileges gt Coherency between device files and devices handled by the kernel is left to the system developer gt On more elaborate Linux systems mechanisms can be added to create remove them automatically when devices appear and disappear gt devtmpfs virtual filesystem gt udev daemon solution used by desktop and server Linux systems gt mdev program a lighter solution than udev Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 205 473 Kernel frameworks for device drivers Character drivers Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 206 473 A character driver in the kernel gt From the point of view of an application a character device is essentially a file gt The driver of a
17. 473 Adding the support for a new ARM board Provided the SoC used on your board is supported by the Linux kernel 1 Create a Device Tree file in arch arm boot dts generally named lt soc name gt lt board name gt dts and make it include the relevant SoC dtsi file gt Your Device Tree will describe all the SoC peripherals that are enabled the pin muxing as well as all the devices on the board 2 Modify arch arm boot dts Makefile to make sure your Device Tree gets built as a DTB during the kernel build 3 If needed develop the missing device drivers for the devices that are on your board outside the SoC Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 363 473 Example of the Freescale iMX28 SoCs gt The hardware platform used in this training is based on the AM335x processor from Texas Instruments gt This platform inherits from the OMAP family of TI for which kernel support has been around for a long time gt Due to this and the complexity of the platform the AM335x and OMAP support in the kernel hasn t fully migrated yet to all the infrastructures created during the ARM cleanup gt Therefore to illustrate this section we will take the example of the Freescale iMX28 platform on which Free Electrons has worked specifically Free Electrons Embedded Linux kernel drivers and Android development consulting training and s
18. Android development consulting training and support http free electrons com 244 473 Practical lab Expose the Nunchuk to user space gt Extend the Nunchuk driver to expose the Nunchuk features to user space applications as an input device gt Test the operation of the Nunchuk using sample user space applications Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 245 473 Memory Management M emory Free Electrons Management pa Free Electrons Copyright 2004 2014 Free Electrons Creative Commons BY SA 3 0 license Corrections suggestions contributions and translations are welcome Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 246 473 Physical and Virtual Memory OxFFFFFFFF Kernel OxFFFFFFFF 9xC0000000 I O Memory 3 Process 1 I O Memory 2 0x00000000 I O Memory 1 OxFFFFFFFF Kernel 0xC0000000 Process 2 0x00000000 0x00000000 Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 247 473 Virtual Memory Organization gt 1GB reserved for kernel space gt Contains kernel code and core data structures identical in all address spaces gt Most memory can be a direct mapping of physical memory at a fixed offset OxFFFFF
19. Convenient linked list facility in Linux list h gt Used in thousands of places in the kernel gt Adda struct list_head member to the structure whose instances will be part of the linked list It is usually named node when each instance needs to only be part of a single list gt Define the list with the LIST_HEAD macro for a global list or define a struct list_head element and initialize it with INIT_LIST_HEAD for lists embedded in a structure gt Then use the list_ API to manipulate the list gt Add elements list_add list_add_tail gt Remove move or replace elements list_del list_move list_move_tail list_replace gt Test the list list_empty gt Iterate over the list list_for_each_ family of macros Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 125 473 Linked Lists Examples 1 gt From include linux atmel_tc h Definition of a list element with a struct list_head member struct atmel_tc some members struct list_head node F Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 126 473 Linked Lists Examples 2 gt From drivers misc atmel_tclib c Define the global list static LIST_HEAD tc_list static __init tc_probe struct platform_device pdev struct atmel_tc tc tc kzalloc
20. Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 372 473 Crystalfontz CFA 10036 Device Tree Breakout Boards gt The CFA 10036 can be plugged in other breakout boards and the device tree also allows us to describe this using includes For example the CFA 10057 include imx28 cfa10036 dts gt This allows to have a layered description This can also be done for boards that have a lot in common like the BeagleBone and the BeagleBone Black or the AT91 SAMA5D3 based boards Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 373 473 Crystalfontz CFA 10036 build the DTB gt To ensure that the Device Tree Blob gets built for this board Device Tree Source one need to ensure it is listed in arch arm boot dts Makefile dtb CONFIG_ARCH_MXS imx28 cfa10036 dtb imx28 cfa10037 dtb imx28 cfa10049 dtb imx28 cfal0055 dtb imx28 cfa10056 dtb imx28 cfa10057 dtb imx28 cfal0058 dtb imx28 evk dtb Cd nN oN CE Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 374 473 Understanding the SoC support gt Let s consider another ARM platform here the Marvell Armada 370 XP gt For this platform the core of the SoC support is located in arch arm mach mvebu gt The armada 370 xp
21. Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 62 473 Kernel configuration 1 gt The kernel contains thousands of device drivers filesystem drivers network protocols and other configurable items gt Thousands of options are available that are used to selectively compile parts of the kernel source code gt The kernel configuration is the process of defining the set of options with which you want your kernel to be compiled gt The set of options depends gt On your hardware for device drivers etc gt On the capabilities you would like to give to your kernel network capabilities filesystems real time etc Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 63 473 Kernel configuration 2 gt The configuration is stored in the config file at the root of kernel sources gt Simple text file key value style gt As options have dependencies typically never edited by hand but through graphical or text interfaces gt make xconfig make gconfig graphical gt make menuconfig make nconfig text gt You can switch from one to another they all load save the same config file and show the same set of options gt To modify a kernel in a GNU Linux distribution the configuration files are usually released in boot together with kernel images bo
22. Linux kernel drivers and Android development consulting training and support http free electrons com 48 473 Kernel Source Code Linux sources Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 49 473 Linux sources structure 1 5 gt arch lt ARCH gt gt gt gt gt Architecture specific code arch lt ARCH gt mach lt machine gt machine board specific code arch lt ARCH gt include asm architecture specific headers arch lt ARCH gt boot dts Device Tree source files for some architectures gt block gt Block layer core gt COPYING gt Linux copying conditions GNU GPL gt CREDITS gt Linux main contributors gt crypto gt Cryptographic libraries Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 50 473 Linux sources structure 2 5 gt Documentation gt Kernel documentation Don t miss it drivers gt All device drivers except sound ones usb pci firmware gt Legacy firmware images extracted from old drivers fs gt Filesystems fs ext3 etc include gt Kernel headers include linux gt Linux kernel core headers include uapi gt User space API headers init gt Linux initialization including main c ipc gt Code used for process communication Free Electron
23. Linux Code and Device Drivers Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 35 473 Programming language Implemented in C like all Unix systems C was created to implement the first Unix systems A little Assembly is used too gt CPU and machine initialization exceptions gt Critical library routines No C used see http www tux org 1km1 s15 3 All the code compiled with gcc gt Many gcc specific extensions used in the kernel code any ANSI C compiler will not compile the kernel gt A few alternate compilers are supported Intel and Marvell gt See http gcc gnu org onlinedocs gcc 4 9 0 gcec C Extensions html v v v v Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 36 473 No C library gt The kernel has to be standalone and can t use user space code gt User space is implemented on top of kernel services not the opposite gt Kernel code has to supply its own library implementations string utilities cryptography uncompression gt So you can t use standard C library functions in kernel code printf memset malloc gt Fortunately the kernel provides similar C functions for your convenience like printk memset kmalloc Free Electrons Embedded Linux kernel drivers and Android developm
24. Provided by the base clock framework Provided by the driver code Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 384 473 Clock Framework 3 The interface of the CCF divided into two halves gt Common Clock Framework core gt Common definition of struct clk gt Common implementation of the clk h API defined in drivers clk clk c gt struct clk_ops operations invoked by the clk API implementation gt Not supposed to be modified when adding a new driver gt Hardware specific gt Callbacks registered with struct clk_ops and the corresponding hardware specific structures gt Has to be written for each new hardware clock Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 385 473 Clock Framework 4 gt Hardware clock operations device tree gt The device tree is the mandatory way to declare a clock and to get its resources as for any other driver using DT we have to gt Parse the device tree to setup the clock the resources but also the properties are retrieved gt Declare the compatible clocks and associate it with an initialization function using CLK_OF_DECLARE Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 386 473 Suspend and Resume gt Infrastructure in the
25. SoC support was located in arch arm mach lt foo gt gt Each board supported by the kernel was associated to an unique machine ID gt The entire list of machine ID can be downloaded at http www arm linux org uk developer machines download php and one could freely register an additional one gt The Linux kernel was defining a machine structure for each board which associates the machine ID with a set of information and callbacks gt The bootloader had to pass the machine ID to the kernel in a specific ARM register Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 361 473 The Device Tree and the ARM cleanup gt As the ARM architecture gained significantly in popularity some major refactoring was needed gt First the Device Tree was introduced on ARM instead of using C code to describe SoCs and boards a specialized language is used gt Second many driver infrastructures were created to replace custom code in arch arm mach lt foo gt gt The common clock framework in drivers clk gt The pinctrl subsystem in drivers pinctrl gt The irqchip subsystem in drivers irgqchip gt The clocksource subsystem in drivers clocksource gt The amount of code in mach lt foo gt has now significantly reduced Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 362
26. a20 olinuxino micro green usr gpios lt amp pio 7 2 0 gt default state on F yi yi Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 196 473 Practical lab Communicate with the Nunchuk gt Configure the pinmuxing for the I2C bus used to communicate with the Nunchuk gt Validate that the I2C communication works with user space tools gt Extend the I2C driver started in the previous lab to communicate with the Nunchuk Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 197 473 Kernel frameworks for device drivers Kernel frameworks e for device drivers Embodied Lin Free Electrons Copyright 2004 2014 Free Electrons Creative Commons BY SA 3 0 license Corrections suggestions contributions and translations are welcome Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 198 473 Kernel and Device Drivers In Linux a driver is always interfacing with Application User space gt a framework that allows the driver to expose the hardware features to user space applications gt a bus infrastructure part of the device model to detect communicate with the hardware Kernel This section focuses on the kernel frameworks while th
27. and Android development consulting training and support http free electrons com 448 473 Process Access Virtual Memory Access Physical Address Virtual Physical Address Address Space Space Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 449 473 How to Impl t ow to Implemen gt Open the device file mmap User Space gt Call the mmap system call see man mmap for details i mmap start t length prot flags fd offset Often 0 preferred starting address Length of the mapped area Permissions read write execute Options shared mapping private copy Open file descriptor Offset in the file gt You get a virtual address you can write to or read from Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 450 473 How to Implement mmap Kernel Space gt Character driver implement an mmap file operation and add it to the driver file operations mmap struct file Open file structure struct vm_area_struct Kernel VMA structure gt Initialize the mapping gt Can be done in most cases with the remap_pfn_range function which takes care of most of the job Free Electrons Embedded Linux kernel drivers and Android development consulting training and support
28. as the page allocator v v gt kfree const objp v Free an allocated area gt Example drivers infiniband core cache c struct ib_update_work work work kmalloc sizeof work GFP_ATOMIC kfree work Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 263 473 kmalloc API 2 2 gt kzalloc size flags gt Allocates a zero initialized buffer gt kcalloc n size flags gt Allocates memory for an array of n elements of size size and zeroes its contents gt krealloc const xp new_size flags gt Changes the size of the buffer pointed by p to new_size by reallocating a new buffer and copying the data unless new_size fits within the alignment of the existing buffer Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 264 473 devm_ kmalloc functions gt Automatically free the allocated buffers when the corresponding device or module is unprobed gt Need to have a reference to a struct device gt devm_kmalloc struct device dev size flags gt devm_kzalloc struct device dev size flags gt devm_kcalloc struct device dev n size flags gt devm_kfree struct device dev p gt Useful to immediately free an allocated buffer See Documentation driver model devres txt for details about managed device reso
29. at a time gt A tasklet can be declared statically with the DECLARE_TASKLET macro or dynamically with the tasklet_init function A tasklet is simply implemented as a function Tasklets can easily be used by individual device drivers as opposed to softirqs gt The interrupt handler can schedule the execution of a tasklet with gt tasklet_schedule to get it executed in the TASKLET softirq gt tasklet_hi_schedule to get it executed in the HI softirq higher priority Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 319 473 Tasklet Example simplified atmel_serial c 1 2 The tasklet function static atmel_tasklet_func data struct uart_port port struct uart_port data F Registering the tasklet init function tasklet_init amp atmel_port gt tasklet atmel_tasklet_func port esc Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 320 473 Tasklet Example simplified atmel_serial c 2 2 Removing the tasklet cleanup function Laced tasklet_kill amp atmel_port gt tasklet er Triggering execution of the tasklet somewhere function tasklet_schedule amp atmel_port gt tasklet Free Electrons Embedded Linux kernel drivers and Android development consulting trai
30. c see code on the next slide contains the entry point of the SoC definition the DT_MACHINE_START MACHINE_END definition gt Defines the list of platform compatible strings that will match this platform in this case marvell armada 370 xp This allows the kernel to know which DT_MACHINE structure to use depending on the DTB that is passed at boot time gt Defines various callbacks for the platform initialization the most important one being the init_machine callback which calls of platform_populate This function travels through the Device Tree and instantiates all the devices Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 375 473 arch arm mach mvebu armada 370 xp c 9 static init armada_370_xp_dt_init of_platform_populate NULL of_default_bus_match_table NULL NULL F static const const armada_370_xp_dt_compat marvell armada 370 xp NULL 3 DT_MACHINE_START ARMADA_XP_DT Marvell Armada 370 XP Device Tree smp smp_ops armada_xp_smp_ops init_machine armada_370_xp_dt_init map_io armada_370_xp_map_io init_time armada_370_xp_timer_and_clk_init restart mvebu_restart dt_compat armada_370_xp_dt_compat MACHINE_END Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 376 473 Components of the minimal So
31. drivers many network protocols support many architectures and filesystems gt The Linux core scheduler memory management is pretty small Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 31 473 Li kernel size 2 inux kernel size 2 As of kernel version 3 10 gt drivers 49 4 gt arch 21 9 gt fs 6 0 gt include 4 7 gt sound 4 4 gt Documentation 4 0 gt net 3 9 gt firmware 1 0 gt kernel 1 0 gt tools 0 9 gt scripts 0 5 gt mm 0 5 gt crypto 0 4 gt security 0 4 gt lib 0 4 gt block 0 2 Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 32 473 Practical lab Get Linux Kernel Source Code gt Clone the mainline Linux source tree with git Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 33 473 Kernel Source Code Kernel Sou rce Free Electrons Code Saree Free Electrons Copyright 2004 2014 Free Electrons Creative Commons BY SA 3 0 license Corrections suggestions contributions and translations are welcome Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 34 473 Kernel Source Code
32. electrons com 69 473 make xconfig search interface Looks for a keyword in the parameter name Allows to select or unselect found parameters X Search Config x Find mtd JI Search NAND Flash support for Samsung S3C SoCs Support software BCH ECC ST Nomadik 8815 NAND support CFI Flash device mapped on AMD NetSc520 M Systems Disk On Chip Millennium only alternative driver DEPRECATED DARM Firmware Suite partition parsing NEW OPMC551 Debugging mmand line partition table parsing Physical address of DiskOnChip MTD_DOCPROBE_ADDRESS CONFIG_MTD_DOCPROBE_ADDRESS By default the probe for DiskOnChip devices will look for a DiskOnChip at every multiple of 0x2000 between 0xC8000 and OxEE000 This option allows you to specify a single address at which to probe for the device which is useful if you have other devices in that range which get upset when they are probed Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 70 473 Kernel configuration options Compiled as a module separate file CONFIG _IS09660_FS m Driver options alSO 9660 CDROM file system support CONFIG JOLIET y gt aMicrosoft Joliet CDROM extensions CONFIG_ZISOFS y gt sTransparent decompression extension aUDF file system support Compiled statically into the kernel CONFIG_UDF_FS y Free Electrons Embedded Linux kernel
33. for implementation details Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 306 473 Processes scheduling and interrupts Interrupt Management Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 307 473 Registering an interrupt handler 1 2 The managed API is recommended devm_request_irq struct device dev irq handler irq_flags const devname dev_id gt Register an interrupt handler device for automatic freeing at device or module release time gt irq is the requested IRQ channel For platform devices use platform_get_irgq to retrieve the interrupt number handler is a pointer to the IRQ handler irg_flags are option masks see next slide devname is the registered name dev_id is a pointer to some data It cannot be NULL as it is used as an identifier for free_irg when using shared IRQs v Yv v Y Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 308 473 Releasing an interrupt handler devm_free_irq struct device dev irq dev_id gt Explicitly release an interrupt handler Done automatically in normal situations Defined in include linux interrupt h Free Electrons Embedded Linux kernel drivers and Android development consulting training
34. gt Tells the kernel which driver is using which I O ports gt Allows to prevent other drivers from using the same I O ports but is purely voluntary gt struct resource request_region start len xname gt Tries to reserve the given region and returns NULL if unsuccessful gt request_region 0x0170 8 ide1 v release_region start len Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 271 473 proc ioports example x86 0000 001f 0080 008f 00c0 00df 0O0f0 O00ff 03f 8 O03ff 0800 087f dmal 0020 0021 0040 0043 0050 0053 0070 0077 dma page reg 00a0 00a1 dma2 fpu 0170 0177 01f0 O01f7 0376 0376 O3f6 O03f6 pici timer0 timeri rtc pic2 ide1 ide0 ide1 ide0 serial 0000 00 1f 0 Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 272 473 Accessing O ports gt Functions to read write bytes b word w and longs 1 to I O ports gt in bw1 port gt out bw1 value port gt And the strings variants often more efficient than the corresponding C loop if the processor supports such operations gt ins bw1 port addr count gt outs bw1 port addr count gt Examples gt read 8 bits gt oldlcr inb baseio UART_LCR gt write 8 bits g
35. have just seen the very basic features of Git gt A lot more interesting features are available rebasing bisection merging and more gt References gt Git Manual gt http schacon github com git user manual html gt Git Book gt http git scm com book gt Git official website gt http git scm com gt Video James Bottomley s tutorial on using Git gt http free electrons com pub video 2008 ols 01s2008 james bottomley git ogg Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 472 473 Practical lab Going further git gt Get familiar with git by contributing to a real project the Linux kernel gt Send your patches to the maintainers and mailing lists Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 473 473
36. http free electrons com 292 473 P thread rocess threa gt Confusion about the terms process thread and task gt In Unix a process is created using fork and is composed of gt An address space which contains the program code data stack shared libraries etc gt One thread that starts executing the main function gt Upon creation a process contains one thread gt Additional threads can be created inside an existing process using pthread_create gt They run in the same address space as the initial thread of the process gt They start executing a function passed as argument to pthread_create Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 293 473 Process thread kernel point of view gt The kernel represents each thread running in the system by a structure of type struct task_struct gt From a scheduling point of view it makes no difference between the initial thread of a process and all additional threads created dynamically using pthread_create Thread A Thread Thread A B Process after fork Same process after pthread _create Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 294 473 A thread life EXIT_ZOMBIE Task terminated but its resources Thread Created are not freed yet Waiting for its by fork or p
37. http free electrons com 428 473 Useful Online Resources gt Kernel documentation Documentation in kernel sources gt Available on line http free electrons com kerneldoc with HTML documentation extracted from source code gt Linux kernel mailing list FAQ gt http www tux org 1lkm1 gt Complete Linux kernel FAQ gt Read this before asking a question to the mailing list gt Kernel Newbies gt http kernelnewbies org gt Glossary articles presentations HOWTOs recommended reading useful tools for people getting familiar with Linux kernel or driver development gt Kernel glossary gt http kernelnewbies org KernelGlossary Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 429 473 International Conferences gt Embedded Linux Conference http embeddedlinuxconference com gt Organized by the CE Linux Forum gt in California San Francisco April gt in Europe October November gt Very interesting kernel and user space topics for embedded systems developers gt Presentation slides freely available gt Linux Plumbers http linuxplumbersconf org gt Conference on the low level plumbing of Linux kernel audio power management device management multimedia etc gt linux conf au http linux org au conf gt In Australia New Zealand gt Features a few presentations by key kernel hackers gt Don t
38. http free electrons com 451 473 remap_pfn_range gt pfn page frame number gt The most significant bits of the page address without the bits corresponding to the page size include lt linux mm h gt remap_pfn_range struct vm_area_struct VMA struct virt_addr Starting user virtual address pfn pfn of the starting physical address C size Mapping size gt prot Page permissions Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 452 473 Simple mmap Implementation static acme_mmap struct file file struct vm_area_struct vma size vma gt vm_end vma gt vm_start if size gt ACME_SIZE return EINVAL if remap_pfn_range vma vma gt vm_start ACME_PHYS gt gt PAGE_SHIFT size vma gt vm_page_prot return EAGAIN return 0 Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 453 473 devmem2 gt http free electrons com pub mirror devmem2 c by Jan Derk Bakker gt Very useful tool to directly peek read or poke write 1 0 addresses mapped in physical address space from a shell command line gt Very useful for early interaction experiments with a device without having to code and compile a driver gt Uses mmap to dev men gt Examples b byte h half w word gt
39. kernel debug First described on http lwn net Articles 115405 API documented in the Linux Kernel Filesystem API v y gt Documentation DocBook filesystems Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 347 473 DebugFS API gt Create a sub directory for your driver gt struct dentry debugfs_create_dir const xname struct dentry parent gt Expose an integer as a file in DebugFS gt struct dentry debugfs_create_ u x 8 16 32 const xname mode struct dentry parent u8 value gt u for decimal representation gt x for hexadecimal representation gt Expose a binary blob as a file in DebugFS gt struct dentry debugfs_create_blob const xname mode struct dentry parent struct debugfs_blob_wrapper blob gt Also possible to support writable DebugFS files or customize the output using the more generic debugfs_create_file function Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 348 473 Deprecated Debugging Mechanisms gt Some additional debugging mechanisms whose usage is now considered deprecated gt Adding special ioct1 commands for debugging purposes DebugFS is preferred gt Adding special entries in the proc filesystem DebugFS is preferred gt Adding special entries in the sysfs filesystem DebugFS is p
40. kernel to support suspend and resume gt Platform hooks gt prepare enter finish valid ina struct platform_suspend_ops structure gt Registered using the suspend_set_ops function gt See arch arm mach at91 pm c gt Device drivers gt suspend and resume hooks in the _driver structures struct platform_driver struct usb_driver etc gt See drivers net macb c Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 387 473 Board specific Power Management gt Typically takes care of battery and charging management gt Also defines presuspend and postsuspend handlers gt Example arch arm mach pxa spitz_pm c Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 388 473 arch arm mach cpu sleep S gt Assembly code implementing CPU specific suspend and resume code gt Note only found on arm just 3 other occurrences in other architectures with other paths gt First scenario only a suspend function The code goes in sleep state after enabling DRAM self refresh and continues with resume code gt Second scenario suspend and resume functions Resume functions called by the bootloader gt Examples to look at gt arch arm mach omap2 sleep24xx S 1st case gt arch arm mach pxa sleep S 2nd case Free Electrons Embedded Linu
41. mtd nand pxa3xx Add bad block handling Add support for flash based bad block table using Marvell s custom in flash bad block table layout The support is enabled a flash_bbt platform data or device tree parameter Signed off by Ezequiel Garcia lt ezequiel garciaefree electrons com gt Tested by Daniel Mack lt zonque gmail com gt Signed off by Brian Norris lt conputersforpeace gmail com gt Diffstat E p rw F r Documentation devicetree bindings mtd pxa3xx nand txt 2 rw r r drivers mtd nand pxa3xx_nand c 37 m 1W F F include linux plat orm_data mtd nand pxa3xx h 3m fil od diff git a Documentation devicetree bindings mtd pxa3xx nand txt b Documentation devicetree bindings mtd pxa3xx nand txt index beda390 55e0a56 190644 a Documentation devicetree bindings atd pxa3xx nand txt b Documentation devicetree bindings mtd pxa3xx nand txt 15 6 15 8 8 Optional properties marvell nand keep config Set to keep the NAND controller config as set by the bootloader num cs Nunber of chipselect lines to usw nand on flash bbt boolean to enable on flash bbt option if not present false Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com Update your Repository gt The repository that has been cloned at the beginning will change over time gt Updating your local repository to reflect the changes of the remote
42. need to take care of cache coherency cache content vs memory content Either flush or invalidate the cache lines corresponding to the buffer accessed by DMA and processor at strategic times Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 438 473 DMA Memory Constraints gt Need to use contiguous memory in physical space gt Can use any memory allocated by kmalloc up to 128 KB or __get_free_pages up to 8MB gt Can use block I O and networking buffers designed to support DMA gt Can not use vmalloc memory would have to setup DMA on each individual physical page Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 439 473 Memory Synchronization Issues gt Memory caching could interfere with DMA gt Before DMA to device gt Need to make sure that all writes to DMA buffer are committed gt After DMA from device gt Before drivers read from DMA buffer need to make sure that memory caches are flushed gt Bidirectional DMA gt Need to flush caches before and after the DMA transfer Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 440 473 Linux DMA API gt The kernel DMA utilities can take care of gt Either allocating a buffer in a cache cohere
43. of the device on the bus gt An array of such structures is registed on a per bus basis using i2c_register_board_info when the platform is initialized Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 173 473 Registering an 12C device non DT example static struct i2c_board_info lt board gt _i2c_devices __initdata I2C_BOARD_INFO cs42151 Ox4a 33 board_init T Here should be the registration of all devices including the I2C controller device i2c_register_board_info 0 lt board gt _i2c_devices ARRAY_SIZE lt board gt _i2c_devices More devices registered here J Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 174 473 Registering an I2C device in the DT gt In the Device Tree the I2C controller device is typically defined in the dtsi file that describes the processor gt Normally defined with status disabled gt At the board platform level gt the I2C controller device is enabled status okay gt the I2C bus frequency is defined using the clock frequency property gt the I2C devices on the bus are described as children of the 12C controller node where the reg property gives the I2C slave address on the bus Free Electrons Embedded Linux kernel drivers and Android development consult
44. on the number of allocated objects It uses the page allocator to allocate and free pages gt SLAB caches are used for data structures that are present in many many instances in the kernel directory entries file objects network packet descriptors process descriptors etc gt See proc slabinfo gt They are rarely used for individual drivers gt See include linux slab h for the API Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 259 473 SLAB Allocator 2 2 Objects of 512 byte Allocated 512 bytes object A4KiB page Free 1024 bytes object Objects of 1024 byte Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 260 473 Different SLAB Allocators gt There are three different but API compatible implementations of a SLAB allocator in the Linux kernel A particular implementation is chosen at configuration time gt SLAB legacy well proven allocator Still the default in most ARM defconfig files gt SLOB much simpler More space efficient but doesn t scale well Saves a few hundreds of KB in small systems depends on CONFIG_EXPERT Linux 3 13 on ARM used in 5 defconfig files gt SLUB more recent and simpler than SLAB scaling much better in particular for huge systems and creating less fragmentation Linux 3 13 on ARM used in 0 de
45. one gt Memory barriers are available to prevent this reordering gt rmb is a read memory barrier prevents reads to cross the barrier gt wmb is a write memory barrier gt mb is a read write memory barrier gt Starts to be a problem with CPUs that reorder instructions and SMP gt See Documentation memory barriers txt for details Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 281 473 dev mem gt Used to provide user space applications with direct access to physical addresses gt Usage open dev mem and read or write at given offset What you read or write is the value at the corresponding physical address gt Used by applications such as the X server to write directly to device memory gt On x86 arm arm64 tile powerpc unicore32 s390 CONFIG_STRICT_DEVMEM option to restrict dev mem non RAM addresses for security reasons Linux 3 10 status Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 282 473 Practical lab O Memory and Ports gt Add UART devices to the board device tree gt Access I O registers to control the device and send first characters to it Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 283 473 The misc subsystem
46. platform_data Mechanism gt In addition to the well defined resources many drivers require driver specific information for each platform device gt Such information can be passed using the struct platform_data field of struct device from which struct platform_device inherits gt As it is a void pointer it can be used to pass any type of information gt Typically each driver defines a structure to pass information through struct platform_data Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 155 473 platform_data example 1 2 gt The i MX serial port driver defines the following structure to be passed through struct platform_data struct imxuart_platform_data init struct platform_device pdev exit struct platform_device pdev flags irda_enable enable irda_inv_rx 1 irda_inv_tx 1 transceiver_delay Ip gt The MX1ADS board code instantiates such a structure static struct imxuart_platform_data uarti_pdata flags IMXUART_HAVE_RTSCTS IPS Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 156 473 platform_data Example 2 2 gt The uart_pdata structure is associated to the struct platform_device structure in the MX1ADS board file the real code is slightly more complicated struct platform_device mxlads_uarti name
47. sizeof struct atmel_tc GFP_KERNEL Add an element to the list list_add_tail amp tc gt node amp tc_list struct atmel_tc atmel_tc_alloc y block const xname struct atmel_tc tc Iterate over the list elements list_for_each_entry tc amp tc_list node Do something with tc Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 127 473 Linux device and driver model Linux device and Free Electrons driver model ented Linux Free Electrons Copyright 2004 2014 Free Electrons Creative Commons BY SA 3 0 license Corrections suggestions contributions and translations are welcome Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 128 473 Linux device and driver model Introduction Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 129 473 The need for a device model gt The Linux kernel runs on a wide range of architectures and hardware platforms and therefore needs to maximize the reusability of code between platforms gt For example we want the same USB device driver to be usable on a x86 PC or an ARM platform even though the USB controllers used on those platforms are different gt This requires a clean organization o
48. some ARM platforms Definition done in the board specific or SoC specific code gt By using a device tree as done on Power PC and on some ARM platforms from which struct platform_device structures are created gt Example on ARM where the instantiation is done in arch arm mach imx mxiads c static struct platform_device imx_uarti_device name imx uart id 0 num_resources ARRAY_SIZE imx_uarti_resources resource imx_uarti_resources dev platform_data amp uart_pdata PB Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 150 473 Platform device instantiation old style 2 2 gt The device is part of a list static struct platform_device devices __initdata amp cs89x0_device amp imx_uarti_device amp imx_uart2_device IB gt And the list of devices is added to the system during board initialization static __init mxtads_init Eee platform_add_devices devices ARRAY_SIZE devices MACHINE_START MX1ADS Freescale MX1ADS Leal init_machine mxiads_init MACHINE_END Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 151 473 The Resource Mechanism gt Each device managed by a particular driver typically uses different hardware resources addresses for the O registers DMA channels IRQ lin
49. support http free electrons com 134 473 Example USB Bus 1 2 USB Adapter USB Device driver B driver 1 Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 135 473 Example USB Bus 2 2 gt Core infrastructure bus driver gt drivers usb core gt struct bus_type is defined in drivers usb core driver c and registered in drivers usb core usb c gt Adapter drivers gt drivers usb host gt For EHCI UHCI OHCI XHCI and their implementations on various systems Atmel IXP Xilinx OMAP Samsung PXA etc gt Device drivers gt Everywhere in the kernel tree classified by their type Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 136 473 Example of Device Driver gt To illustrate how drivers are implemented to work with the device model we will study the source code of a driver for a USB network card gt It is USB device so it has to be a USB device driver gt It is a network device so it has to be a network device gt Most drivers rely on a bus infrastructure here USB and register themselves in a framework here network gt We will only look at the device driver side and not the adapter driver side gt The driver we will look at is drivers net usb rt18150 Free Electrons Embedded Linux kernel drivers and Android development consu
50. taken released with protection against interrupts static ulite_tx_empty struct uart_port port flags spin_lock_irqsave amp port gt lock flags Do something spin_unlock_irqrestore amp port gt lock flags Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 335 473 Deadlock Situations gt They can lock up your system Make sure they never happen gt Don t call a function that can try to get access to the same lock Get Lock 1 gt Holding multiple locks is risky Get Lock 1 Get Lock 2 Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 336 473 K lock validat ernel lock validator gt From Ingo Molnar and Arjan van de Ven gt Adds instrumentation to kernel locking code gt Detect violations of locking rules during system life such as gt Locks acquired in different order keeps track of locking sequences and compares them gt Spinlocks acquired in interrupt handlers and also in process context when interrupts are enabled gt Not suitable for production systems but acceptable overhead in development gt See Documentation lockdep design txt for details Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 337 473 Alternatives to L
51. the fly by the kernel gt The two most important pseudo filesystems are gt proc usually mounted on proc Operating system related information processes memory management parameters gt sysfs usually mounted on sys Representation of the system as a set of devices and buses Information about these devices Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 24 473 Inside the Linux kernel Linux Kernel Implemented mainly in C Written in a Device Tree L a little bit of assembly C specific language Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 25 473 Supported hardware architectures gt See the arch directory in the kernel sources gt Minimum 32 bit processors with or without MMU and gcc support gt 32 bit architectures arch subdirectories Examples arm avr32 blackfin c6x m68k microblaze mips score sparc um gt 64 bit architectures Examples alpha arm64 ia64 tile gt 32 64 bit architectures Examples powerpc x86 sh sparc gt Find details in kernel sources arch lt arch gt Kconfig arch lt arch gt README or Documentation lt arch gt Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 26 473 Embedded Linux Kernel Usage Embedded
52. you use git format patch to produce your patches you will need to update your branch and may need to group your changes in a different way one patch per commit gt Here s what we recommend gt Update your master branch gt git checkout master git pull gt Back to your branch implement the changes taking community feedback into account Commit these changes gt Still in your branch reorganize your commits and commit messages gt git rebase interactive origin master gt git rebase allows to rebase replay your changes starting from the latest commits in master In interactive mode it also allows you to merge edit and even reorder commits in an interactive way gt Third generate the new patches with git format patch Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 422 473 K IR ernel Resources Free Electrons Kernel Resources Bees Free Electrons Copyright 2004 2014 Free Electrons Creative Commons BY SA 3 0 license Corrections suggestions contributions and translations are welcome Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 423 473 Kernel Development News Linux Weekly News gt gt http lwn net The weekly digest off all Linux and free software information sources In depth technical discussions about the ke
53. 18 03 33 26 Hugh Dickins lt hug 2008 05 21 21 33 58 Merge branch merge of git git kemel org pub scrvinux kerel gibenhipow Linus Torvalds lt toi 2008 05 05 17 25 37 4 zij 1300 prev commit containing Exact All fields nwrt org gt 2009 0 MAINTAINERS take maint E the ne CEMAC ART Old version Newversion Lines of context 3 Ignore space change prac Ethernet driver Patch Tree Comments MAINTAINERS Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 461 473 Oo Visualize the History cgit gt Another great tool is cgit a web interface to Git For the kernel it is available at http git kernel org httos oit kerneLorg cait linux kernel ait torvalds linux ai m el 631137 Br c e agao index kernel git torvalds linux git Sa git Pam anes _ aids summary _refs__log ORME ditt stats leams oll author Ezequiel Garcia lt ezequiel garcia free electrons com gt 2013 11 14 21 25 28 GMT diff options committer Brian Norris lt computersforpeace gmall com gt 2014 01 03 19 22 12 GMT commit 778f2650279744e3 327ccdse7eb378040511373 patch Rare tree 545d7budde0c225etdbobe70te59t 06690555760 ea parent _56704d857acYalosdecsecteattasdcsbabdadse ditt mode unified
54. 45 473 mmap v Possibility to have parts of the virtual address space of a program mapped to the contents of a file Particularly useful when the file is a device file v v Allows to access device I O memory and ports without having to go through expensive read write or ioctl calls gt One can access to current mapped files by two means gt proc lt pid gt maps gt pmap lt pid gt Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 447 473 proc lt pid gt maps start end perm 7 4516d04000 7 4516d06000 rw s 7 4516d07000 7 4516d0b000 rw s 7 4518728000 7 451874f000 r xp 7 451874f000 7 451894f000 p 7 451894f000 7 4518951000 r p 7 4518951000 7 4518952000 rw p 7 451da4f000 7 451dc3f 000 r xp 7 451de3e000 7 451de41000 r p 7 451de41000 7 451de4c000 rw p offset major minor inode mapped file name 1152a2000 00 05 8406 120f9e000 00 05 8406 00000000 00027000 00027000 00029000 00000000 001ef000 001 2000 08 08 08 08 08 08 08 01 01 01 01 01 01 01 268909 268909 268909 268909 1549 1549 1549 dev dri card0 dev dri card0 1ib x86_64 linux gnu libexpat 1ib x86_64 linux gnu libexpat 1ib x86_64 linux gnu libexpat 1ib x86_64 linux gnu libexpat usr bin Xorg usr bin Xorg usr bin Xorg BREE annn NNNN Free Electrons Embedded Linux kernel drivers
55. 6 36 Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 426 473 Useful Reading 3 Linux Device Drivers 4th edition July 2015 estimated gt http shop oreilly com product 0636920030867 do gt By Jonathan Corbet Alessandro Rubini Greg Kroah Hartman Jessica McKellar O Reilly gt Expected to be a great book if as good as the previous edition Free PDF http free electrons com community kernel 1dd3 which is now out of date Linux Device Drivers 4D Jessica McKellar Alessandro Rubini Jonathan Corbet amp Greg Kroah Hartman Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 427 473 Useful Reading 4 gt Linux Kernel Development 3rd Edition Jun 2010 gt Robert Love Novell Press gt http free electrons com redir 1kd3 book html gt A very synthetic and pleasant way to learn about kernel subsystems beyond the needs of device driver writers gt The Linux Programming Interface Oct 2010 gt Michael Kerrisk No Starch Press gt http man7 org tlpi gt A gold mine about the kernel interface and how to use it Free Electrons Embedded Linux kernel drivers and Android development consulting training and support Linux Kernel Development THE LINUX PROGRAMMING INTERFACE Atin Handbook
56. A addr 0x6E Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 169 473 The I2C subsystem gt Like all bus subsystems the 12C subsystem is responsible for gt Providing an API to implement I2C controller drivers gt Providing an API to implement 12C device drivers in kernel space gt Providing an API to implement 12C device drivers in user space gt The core of the 12C subsystem is located in drivers i2c gt The I2C controller drivers are located in drivers i2c busses gt The I2C device drivers are located throughout drivers depending on the type of device ex drivers input for input devices Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 170 473 Registering an I2C device driver gt Like all bus subsystems the 12C subsystem defines a struct i2c_driver that inherits from struct device_driver and which must be instantiated and registered by each 12C device driver gt As usual this structure points to the gt probe and gt remove functions gt It also contains an id_table field that must point to a list of device IDs which is a list of tuples containing a string and some private driver data It is used for non DT based probing of I2C devices gt The i2c_add_driver and i2c_del_driver functions are used to register unregister the
57. BeagleBone board include am33xx dtsi compatible ti am33xx i x tes a compatible ti am335x bone ti am33xx uart serial 44e09000 feet compatible ti omap3 uart paxa to 1 44e09000 2 2 yeas uart serial 44e reg lt 0x44e09000 0x2000 gt pinctrl names default a mentee pinctrl 0 lt amp uart0_pins gt s status okay am33xx dtsi am335x bone dts Compiled DTB compatible ti am335x bone ti am33xx le sal ocp uartO serial 44e09000 Note the real DTB is in binary format compatible ti omap3 uart Here we show the text equivalent of the reg lt 0x44e09000 0x2000 gt DTB contents interrupts lt 72 gt pinctrl names default pinctrl 0 lt amp uart0_pins gt status okay am335x bone dtb Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 161 473 Device Tree compatible string gt With the device tree a device is bound with the corresponding driver using the compatible string gt The of_match_table field of struct device_driver lists the compatible strings supported by the driver if defined CONFIG_OF static const struct of_device_id omap_serial_of_match compatible ti omap2 uart compatible ti omap3 uart compatible ti omap4 uart 0 3 MODULE_DEVICE_TABLE of omap_serial_of_match endif static struct platform_driver seria
58. C support The minimal SoC support consists in gt An SoC entry point file arch arm mach mvebu armada 370 xp c gt At least one SoC dtsi DT and one board dts DT in arch arm boot dts gt A interrupt controller driver drivers irqchip irg armada 370 xp c gt A timer driver drivers clocksource time armada 370 xp c gt An earlyprintk implementation to get early messages from the console arch arm Kconfig debug and arch arm include debug gt A serial port driver in drivers tty serial For Armada 370 XP the 8250 driver drivers tty serial 8250 is used This allows to boot a minimal system up to user space using a root filesystem in initramfs Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 377 473 Extending the minimal SoC support Once the minimal SoC support is in place the following core components should be added gt Support for the clocks Usually requires some clock drivers as well as DT representations of the clocks See drivers clk mvebu for Armada 370 XP clock drivers gt Support for pin muxing through the pinctrl subsystem See drivers pinctr1 mvebu for the Armada 370 XP drivers gt Support for GPIOs through the GPIO subsystem See drivers gpio gpio mvebu c for the Armada 370 XP GPIO driver gt Support for SMP through struct smp_operations See arch arm mach mvebu platsmp c Free Electrons Embedded Linux kernel drive
59. FFF Kernel 0xc0000000 gt Complete 3GB exclusive mapping available for each user space process gt Process code and data program stack emory mapped files gt Not necessarily mapped to physical memory demand fault paging used for dynamic mapping to physical memory pages gt Differs from one address space to another Process n gt M 0x00000000 Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 248 473 Physical virtual memory mapping Physical Address Space I O Memory Kernel OxFFFFFFFF 0xC0000000 Process n 0x00000000 Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 249 473 Accessing more physical memory gt Only less than 1GB memory addressable directly through kernel virtual address space gt If more physical memory is present on the platform part of the memory will not be accessible by kernel space but can be used by user space gt To allow the kernel to access more physical memory gt Change 1GB 3GB memory split 2GB 2GB CONFIG_VMSPLIT_3G reduces total memory available for each process gt Change for a 64 bit architecture See Documentation x86 x86_64 mm txt for an example gt Activate highmem support if available for your architecture gt Allows kernel to map parts of its non directly accessible memor
60. Groups PowerManagement gt Ongoing developments on the ARM platform gt Tips and ideas for prolonging battery life gt http j mp fVdxkh Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 400 473 The kernel development and contribution process The kernel development and contribution Free Electrons process oe Free Electrons Copyright 2004 2014 Free Electrons Creative Commons BY SA 3 0 license Corrections suggestions contributions and translations are welcome Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 401 473 The kernel development and contribution process Linux versioning scheme and development process Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 402 473 Until 2 6 1 gt One stable major branch every 2 or 3 years gt Identified by an even middle number gt Examples 1 0 x 2 0 x 2 2 x 2 4 x gt One development branch to integrate new functionalities and major changes gt Identified by an odd middle number gt Examples 2 1 x 2 3 x 2 5 x gt After some time a development version becomes the new base version for the stable branch gt Minor releases once in while 2 2 23 2 5 12 etc Free Electrons Embedded Linux kernel dri
61. Linus Torvalds Linux kernel repository git clone git git kernel org pub scm linux kernel git torvalds linux git gt git is a special Git protocol Most repositories can also be accessed using http but this is slower gt After cloning in linux you have the repository and a working copy of the master branch Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 459 473 Explore the Hist xplore the History gt git log will list all the commits The latest commit is the first commit 4371ee353c3fc41aad9458b8e8e627 eb508bc9a3 Author Florian Fainelli lt florian openwrt org gt Date Mon Jun 1 02 43 17 2009 0700 MAINTAINERS take maintainership of the cpmac Ethernet driver This patch adds me as the maintainer of the CPMAC AR7 Ethernet driver Signed off by Florian Fainelli lt florian openwrt org gt Signed off by David S Miller lt davem davemloft net gt gt git log p will list the commits with the corresponding diff gt The history in Git is not linear like in CVS or SVN but it is a graph of commits gt Makes it a little bit more complicated to understand at the beginning gt But this is what allows the powerful features of Git distributed branching merging Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 460 473 Visualize the History
62. Linux Free Electrons Kernel Usage Embodied Lin Free Electrons Copyright 2004 2014 Free Electrons Creative Commons BY SA 3 0 license Corrections suggestions contributions and translations are welcome Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 27 473 Embedded Linux Kernel Usage Linux kernel sources Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 28 473 Location of kernel sources gt The official versions of the Linux kernel as released by Linus Torvalds are available at http www kernel org gt These versions follow the development model of the kernel gt However they may not contain the latest development from a specific area yet Some features in development might not be ready for mainline inclusion yet gt Many chip vendors supply their own kernel sources gt Focusing on hardware support first gt Can have a very important delta with mainline Linux gt Useful only when mainline hasn t caught up yet gt Many kernel sub communities maintain their own kernel with usually newer but less stable features gt Architecture communities ARM MIPS PowerPC etc device drivers communities 12C SPI USB PCI network etc other communities real time etc gt No official releases only development trees are available Free Electrons
63. Linux Kernel and Driver Development Training Linux Kernel and Driver Development Training Free Electrons Embedded Linux Developers Free Electrons Copyright 2004 2014 Free Electrons Creative Commons BY SA 3 0 license Latest update October 1 2014 Document updates and sources http free electrons com doc training linux kernel Corrections suggestions contributions and translations are welcome Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 1 473 Rights t ights to copy Copyright 2004 2014 Free Electrons License Creative Commons Attribution Share Alike 3 0 http creativecommons org licenses by sa 3 0 legalcode You are free gt to copy distribute display and perform the work gt to make derivative works gt to make commercial use of the work Under the following conditions gt Attribution You must give the original author credit gt Share Alike If you alter transform or build upon this work you may distribute the resulting work only under a license identical to this one gt For any reuse or distribution you must make clear to others the license terms of this work gt Any of these conditions can be waived if you get permission from the copyright holder Your fair use and other rights are in no way affected by the above Free Electrons Embedded Linux kernel drivers and Android developme
64. Only use them in development Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 267 473 Qs I O Memory and Ports I O Memory and Free Electrons Ports a Free Electrons Copyright 2004 2014 Free Electrons Creative Commons BY SA 3 0 license Corrections suggestions contributions and translations are welcome Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 268 473 Port 1 O vs Memory Mapped I O gt MMIO gt Same address bus to address memory and O devices gt Access to the I O devices using regular instructions gt Most widely used I O method across the different architectures supported by Linux gt PIO gt Different address spaces for memory and I O devices gt Uses a special class of CPU instructions to access I O devices gt Example on x86 IN and OUT instructions Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 269 473 MMIO vs PIO Ra PIO Registers Physical Memory Separate I O address space address space accessed with accessed with specific instructions normal load store instructions Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 270 473 Requesting I O ports
65. SB core calls USB device is the probe method of the detected with usb driver structure registered ID X Y by the rtl8150 driver rtl8150 Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 142 473 Probe Method gt The probe method receives as argument a structure describing the device usually specialized by the bus infrastructure struct pci_dev struct usb_interface etc gt This function is responsible for gt Initializing the device mapping O memory registering the interrupt handlers The bus infrastructure provides methods to get the addresses interrupt numbers and other device specific information gt Registering the device to the proper kernel framework for example the network infrastructure Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 143 473 Probe Method Example static rt18150_probe struct usb_interface intf const struct usb_device_id id dev struct net_device netdev netdev alloc_etherdev sizeof DDE Laced dev netdev_priv netdev tasklet_init amp dev gt tl rx_fixup dev spin_lock_init amp dev gt rx_pool_lock Estate netdev gt netdev_ops amp rt18150_netdev_ops alloc_all_urbs dev Kasra usb_set_intfdata intf dev SET_NETDEV_DEV netdev amp intf gt dev register_netdev netdev retur
66. a Kernel Developer gt Recommended resources gt See Documentation SubmittingPatches for guidelines and http kernelnewbies org UpstreamMerge for very helpful advice to have your changes merged upstream by Rik van Riel gt Watch the Write and Submit your first Linux kernel Patch talk by Greg K H http www youtube com watch v LLBrBBImJt4 gt How to Participate in the Linux Community by Jonathan Corbet A Guide To The Kernel Development Process http j mp tX2Ld6 Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 415 473 Contribute to the Linux Kernel 1 gt Clone Linus Torvalds tree gt git clone git git kernel org pub scm linux kernel git torvalds linux git gt Keep your tree up to date gt git pull gt Look at the master branch and check whether your issue change hasn t been solved implemented yet Also check the maintainer s git tree and mailing list see the MAINTAINERS file You may miss submissions that are not in mainline yet gt If the maintainer has its own git tree create a remote branch tracking this tree This is much better than creating another clone doesn t duplicate common stuff gt git remote add linux omap git git kernel org pub scm linux kernel git tmlind linux omap git gt git fetch linux omap Free Electrons Embedded Linux kernel drivers and Android development consulting trainin
67. a command and read write one byte of data gt See include uapi linux i2c h for the full list of existing functionalities Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 186 473 References gt http en wikipedia org wiki I2C general presentation of the I2C protocol gt Documentation i2c details about the Linux support for I2C gt gt gt gt gt writing clients how to write I2C device drivers instantiating devices how to instantiate devices smbus protocol details on the SMBus functions functionality how the functionality mechanism works and many more documentation files gt http free electrons com pub video 2012 elce elce 2012 anders board bringup i2c webm excellent talk You me and 12C from David Anders at ELCE 2012 Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 187 473 Qo Introduction to pin muxing Introduction to pin muxing ented Free Electrons Copyright 2004 2014 Free Electrons Creative Commons BY SA 3 0 license Corrections suggestions contributions and translations are welcome Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 188 473 What is pi ing at is pin muxing gt Modern SoCs System on Chip include more a
68. ails gt Details are often available in the kernel log gt Example sudo insmod intr_monitor ko insmod error inserting intr_monitor ko 1 Device or resource busy dmesg 17549774 552000 Failed to register handler for irq channel 2 Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 100 473 Module utilities 2 gt sudo modprobe lt module_name gt Most common usage of modprobe tries to load all the modules the given module depends on and then this module Lots of other options are available modprobe automatically looks in lib modules lt version gt for the object file corresponding to the given module name gt lsmod Displays the list of loaded modules Compare its output with the contents of proc modules Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 101 473 Module utilities 3 gt sudo rmmod lt module_name gt Tries to remove the given module Will only be allowed if the module is no longer in use for example no more processes opening a device file gt sudo modprobe r lt module_name gt Tries to remove the given module and all dependent modules which are no longer needed after removing the module Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons co
69. ameters that can be passed in how many times we say hello and to whom static char whom world module_param whom charp 0 static int howmany 1 module_param howmany int 0 Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 119 473 Hello Module with Parameters 2 2 static __init hello_init i for i 0 i lt howmany i pr_alert d Hello s n i whom return 0 static __exit hello_exit pr_alert Goodbye cruel s n whom module_init hello_init module_exit hello_exit Thanks to Jonathan Corbet for the example Source code available on http git free electrons com training materials plain code hello param hello_param c Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 120 473 Declaring a module parameter module_param name name of an already defined variable type either byte short ushort int uint long ulong charp bool or invbool checked at run time perm for sys module lt module_name gt parameters lt param gt O no such module parameter value file Example static int irq 5 module_param irq int S_IRUGO Modules parameter arrays are also possible with module_param_array Free Electrons Embedded Linux kernel drivers and Android development cons
70. and for the shared resources use locking Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 326 473 Concurrency protection with locks Process 1 Process 2 Success Try Again Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 327 473 Li t inux mutexes gt The kernel s main locking primitive gt The process requesting the lock blocks when the lock is already held Mutexes can therefore only be used in contexts where sleeping is allowed gt Mutex definition gt include lt linux mutex h gt gt Initializing a mutex statically gt DEFINE_MUTEX name gt Or initializing a mutex dynamically gt mutex_init struct mutex lock Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 328 473 Locking and Unlocking Mutexes 1 2 gt mutex_lock struct mutex lock gt Tries to lock the mutex sleeps otherwise gt Caution can t be interrupted resulting in processes you cannot kill gt mutex_lock_killable struct mutex lock gt Same but can be interrupted by a fatal SIGKILL signal If interrupted returns a non zero value and doesn t hold the lock Test the return value gt mutex_lock_interruptible struct mutex lock gt Same but can be interrupt
71. and support http free electrons com 309 473 Registering an interrupt handler 2 2 gt Main irg_flags bit values can be combined 0 when no flags are needed gt IRQF_SHARED gt The interrupt channel can be shared by several devices Requires a hardware status register telling whether an IRQ was raised or not Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 310 473 Interrupt handler constraints gt No guarantee in which address space the system will be in when the interrupt occurs can t transfer data to and from user space gt Interrupt handler execution is managed by the CPU not by the scheduler Handlers can t run actions that may sleep because there is nothing to resume their execution In particular need to allocate memory with GFP_ATOMIC gt Interrupt handlers are run with all interrupts disabled on the local CPU see http lwn net Articles 380931 Therefore they have to complete their job quickly enough to avoiding blocking interrupts for too long Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 311 473 proc interrupts on a Panda board CPUO CPU1 39 4 0 GIC TWL6030 PIH 41 0 0 GIC 13 dbg irq 42 0 0 GIC 13 app irq 43 0 0 GIC prem 44 20294 0 GIC DMA 52 0 0 GIC gpmc IPIO 0 0 Timer broadcast interrupts TETI 23095 25663 Resched
72. arent to acknowledge pthread_create its death The thread is elected by the scheduler y gt TASK_RUNNING TASK_RUNNING Ready but not running Actually running The thread is preempted by the scheduler to run a higher priority task The event occurs or the process F receives a signal Thread becomes TASK_INTERRUPTIBLE Decides to sleep on a wait queue runnable again TASK_UNINTERRUPTIBLE for a specific event or TASK_KILLABLE Waiting Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 295 473 Process continuing in user space or replaced by a higher priority process can be preempted Process executing in user space can be preempted System call or exception Kernel code executed on behalf of user space can be preempted too The execution of system calls takes place in the context of the thread requesting them Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 296 473 Processes scheduling and interrupts Sleeping Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 297 473 User space proces User Space Process return Read Device File Other Processes are scheduled Ask for data Data Ready Notification Sleeping is needed when a p
73. ass xxx Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 418 473 Contribute to the Linux Kernel 3 gt Group your changes by sets of logical changes corresponding to the set of patches that you wish to submit gt Commit and sign these groups of changes signing required by Linux developers gt git commit s gt Make sure your first description line is a useful summary and starts with the name of the modified subsystem This first description line will appear in your e mails gt The easiest way is to look at previous commit summaries on the main file you modify gt git log pretty oneline lt path to file gt gt Examples subject lines PATCH omitted Documentation prctl seccomp_filter PCI release busn when removing bus ARM add support for xz kernel decompression Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 419 473 Contribute to the Linux Kernel 4 gt Remove previously generated patches gt rm 00 patch Have git generate patches corresponding to your branch gt If your branch is based on mainline gt git format patch master lt your branch gt gt If your branch is based on a remote branch gt git format patch lt remote gt lt branch gt lt your branch gt You can run a last check on all your patches easy gt scripts checkpatch
74. bedded Linux kernel drivers and Android development consulting training and support http free electrons com 193 473 Defining pinctrl configurations gt The different pinctrl configurations must be defined as child nodes of the main pinctr device which controls the muxing of pins gt The configurations may be defined at gt the SoC level dtsi file for pin configurations that are often shared between multiple boards gt at the board level dts file for configurations that are board specific gt The pinctrl lt x gt property of the consumer device points to the pin configuration it needs through a DT phandle gt The description of the configurations is specific to each pinctrl driver See Documentation devicetree bindings pinctr1 for the DT bindings documentations Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 194 473 Example on OMAP AM33xx gt On OMAP AM33xx the pinctrl single driver is am33xx_pinmux pinmux 44e10800 i i2c0_pins pinmux_i2c0_pins used It is common between pinctrl single pins lt Iti S C d i2cO_sda i2cO_sda multiple SOUS and simply 0x188 PIN_INPUT_PULLUP MUX_MODEO allows to configure pins by fe 2c0_geliazel set rie Oxi8c PIN_INPUT_PULLUP MUX_MODEO writing a value to a register gt 7 5 gt In each pin configuration J a pinctrl single pins i2c0 i2ce44e0b000 s x pin
75. ble file to jorking support gt More user friendly for i example easier to access help information gt Required Debian packages libncurses dev USSF ASME EE RFS oN AREF Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 75 473 make oldconfig make oldconfig gt Needed very often gt Useful to upgrade a config file from an earlier kernel release gt Issues warnings for configuration parameters that no longer exist in the new kernel gt Asks for values for new parameters If you edit a config file by hand it s strongly recommended to run make oldconfig afterwards Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 76 473 Undoing configuration changes A frequent problem gt After changing several kernel configuration settings your kernel no longer works gt f you don t remember all the changes you made you can get back to your previous configuration cp config old config gt All the configuration interfaces of the kernel xconfig menuconfig oldconfig keep this config old backup copy Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 77 473 Configuration per architecture gt The set of configuration options is architecture dep
76. ce drivers The concept of kernel frameworks Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 220 473 Beyond character drivers kernel frameworks gt Many device drivers are not implemented directly as character drivers gt They are implemented under a framework specific to a given device type framebuffer V4L serial etc gt The framework allows to factorize the common parts of drivers for the same type of devices gt From user space they are still seen as character devices by the applications gt The framework allows to provide a coherent user space interface ioctl etc for every type of device regardless of the driver Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 221 473 Kernel Frameworks System Call Interface Character Driver Framebuffer Driver Driver Driver i USB Serial IDE a Storage Driver Driver 7 Driver Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com Kernel frameworks for device drivers Example of the framebuffer framework Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 223 473 Example Framebuffer Framework gt Kernel option CONFIG_FB gt m
77. cess non zero on failure If non zero the convention is to return EFAULT Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 214 473 Exchanging data with user space 3 3 OxFFFFFFFF void to void from 0xC0000000 copy_from_user copy_to_user void user from void user to 0x00000000 Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 215 473 Zero copy access to user memory gt Having to copy data to or from an intermediate kernel buffer can become expensive when the amount of data to transfer is large video gt Zero copy options are possible gt mmap system call to allow user space to directly access memory mapped I O space See our mmap chapter gt get_user_pages_fast to get a mapping to user pages without having to copy them See http j mp 1sML71P Kernel API doc This API is more complex to use though Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 216 473 unlocked_ioctl gt unlocked_ioctl struct file f cmd arg gt Associated to the ioct1 system call gt Called unlocked because it didn t hold the Big Kernel Lock gone now gt Allows to extend the driver capabilities beyond the limited read write API gt For example changing
78. ch lt arch gt boot gt copying the Device Tree Blob might be necessary as well they are available in arch lt arch gt boot dts gt make install is rarely used in embedded development as the kernel image is a single file easy to handle gt It is however possible to customize the make install behaviour in arch lt arch gt boot install sh gt make modules_install is used even in embedded development as it installs many modules and description files gt make INSTALL_MOD_PATH lt dir gt modules_install gt The INSTALL_MOD_PATH variable is needed to install the modules in the target root filesystem instead of your host root filesystem Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 91 473 Booting with U Boot Recent versions of U Boot can boot the zImage binary v v Older versions require a special kernel image format uImage gt ulmage is generated from zImage using the mkimage tool It is done automatically by the kernel make ulmage target gt On some ARM platforms make ulmage requires passing a LOADADDR environment variable which indicates at which physical memory address the kernel will be executed v In addition to the kernel image U Boot can also pass a Device Tree Blob to the kernel The typical boot process is therefore 1 Load zImage or uImage at address X in memory 2 Load lt board gt dtb at address Y in memory
79. character device must therefore implement operations that let applications think the device is a file open close read write etc gt In order to achieve this a character driver must implement the operations described in the struct file_operations structure and register them gt The Linux filesystem layer will ensure that the driver s operations are called when a user space application makes the corresponding system call Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 207 473 From user space to the kernel character devices copy_to_user copy_from_user Read Handler Write Handler Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 208 473 Fil ti ile operations gt Here are the most important operations for a character driver All of them are optional include lt linux fs h gt struct file_operations read struct file __user write struct file const __user unlocked_ioctl struct file Js mmap struct file struct vm_area_struct open struct inode struct file release struct inode struct file Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 209 473 open and release gt foo_open struc
80. ck Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 332 473 Using Spinlocks 1 2 gt Several variants depending on where the spinlock is called gt spin_lock lock gt spin_unlock lock gt Doesn t disable interrupts Used for locking in process context critical sections in which you do not want to sleep gt spin_lock_irgqsave lock flags gt spin_unlock_irqrestore lock flags gt Disables restores IRQs on the local CPU gt Typically used when the lock can be accessed in both process and interrupt context to prevent preemption by interrupts Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 333 473 Using Spinlocks 2 2 gt spin_lock_bh lock gt spin_unlock_bh lock gt Disables software interrupts but not hardware ones gt Useful to protect shared data accessed in process context and in a soft interrupt bottom half gt No need to disable hardware interrupts in this case gt Note that reader writer spinlocks also exist Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 334 473 Spinlock example gt Spinlock structure embedded into struct uart_port struct uart_port lock Other fields F gt Spinlock
81. com 412 473 Getting Help gt If you have a support contract ask your vendor gt Otherwise don t hesitate to share your questions and issues gt Either contact the Linux mailing list for your architecture like linux arm kernel or linuxsh dev gt Or contact the mailing list for the subsystem you re dealing with linux usb devel linux mtd Don t ask the maintainer directly gt Most mailing lists come with a FAQ page Make sure you read it before contacting the mailing list gt Useful IRC resources are available too for example on http kernelnewbies org gt Refrain from contacting the Linux Kernel mailing list unless you re an experienced developer and need advice Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 413 473 Reporting Linux Bugs gt First make sure you re using the latest version gt Make sure you investigate the issue as much as you can see Documentation BUG HUNTING gt Check for previous bugs reports Use web search engines accessing public mailing list archives gt f the subsystem you report a bug on has a mailing list use it Otherwise contact the official maintainer see the MAINTAINERS file Always give as many useful details as possible Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 414 473 How to Become
82. cter driver developed earlier gt Register an interrupt handler gt Waiting for data to be available in the read file operation gt Waking up the code when data are available from the device Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 324 473 Concurrent Access to Resources Locking Concurrent Access to Resources Free Electrons Locking rote Free Electrons Copyright 2004 2014 Free Electrons Creative Commons BY SA 3 0 license Corrections suggestions contributions and translations are welcome Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 325 473 Sources of concurrency issues gt In terms of concurrency the kernel has the same constraint as a multi threaded program its state is global and visible in all executions contexts gt Concurrency arises because of gt Interrupts which interrupts the current thread to execute an interrupt handler They may be using shared resources gt Kernel preemption if enabled causes the kernel to switch from the execution of one system call to another They may be using shared resources gt Multiprocessing in which case code is really executed in parallel on different processors and they may be using shared resources as well gt The solution is to keep as much local state as possible
83. ctrl names default a gives p of pinctrl 0 lt amp i2c0_pins gt register valuej pairs status okay needed to configure the clock frequency lt 400000 gt pins tps tps 2d reg lt 0x2d gt gt To know the correct values s one must use the SoC and F board datasheets Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 195 473 Example on Allwinner SoC SoC level arch arm boot dts sun7i a20 dtsi HA soc 01c00000 pio pinctr1 01c20800 compatible allwinner sun7i a20 pinctrl reg lt 0x01c20800 0x400 gt interrupts lt 0 28 1 gt uartO_pins_a uart0 O allwinner pins PB22 PB23 Sine allwinner function uart0 config allwinner drive lt 0 gt allwinner pull lt 0 gt F yi F H Board level arch arm boot dts sun7i a20 olinuxino micro dts TX soc 0l1c00000 pio pinctr1 01c20800 led_pins_olinuxino led_pins d allwinner pins PH2 pin E allwinner function gpio_out config allwinner drive lt 1 gt allwinner pull lt 0 gt i uart0 serial 01c28000 pinctrl names default pinctrl 0 lt amp uart _pins_a gt Enable UARTO and associate pin mux status okay config F J leds compatible gpio leds pinctrl names default Declare eo Pinctrl 0 lt amp led_pins_olinuxino gt device and associate green Leas label
84. d development consulting training and support http free electrons com 256 473 Page Allocator API Free Pages gt free_page addr gt Frees one page gt free_pages addr order gt Frees multiple pages Need to use the same order as in allocation Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 257 473 Page Allocator Flags gt The most common ones are gt GFP_KERNEL gt Standard kernel memory allocation The allocation may block in order to find enough available memory Fine for most needs except in interrupt handler context gt GFP_ATOMIC gt RAM allocated from code which is not allowed to block interrupt handlers or critical sections Never blocks allows to access emergency pools but can fail if no free memory is readily available gt GFP_DMA gt Allocates memory in an area of the physical memory usable for DMA transfers See our DMA chapter gt Others are defined in include linux gfp h Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 258 473 SLAB Allocator 1 2 gt The SLAB allocator allows to create caches which contains a set of objects of the same size gt The object size can be smaller or greater than the page size gt The SLAB allocator takes care of growing or reducing the size of the cache as needed depending
85. debug messages you re interested in gt When DEBUG is not defined and CONFIG_DYNAMIC_DEBUG is not enabled those messages are not compiled in Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 345 473 Configuring The Priority gt Each message is associated to a priority ranging from O for emergency to 7 for debug gt All the messages regardless of their priority are stored in the kernel log ring buffer gt Typically accessed using the dmesg command gt Some of the messages may appear on the console depending on their priority and the configuration of gt The loglevel kernel parameter which defines the priority above which messages are displayed on the console See Documentation kernel parameters txt for details gt The value of proc sys kernel printk which allows to change at runtime the priority above which messages are displayed on the console See Documentation sysctl kernel txt for details Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 346 473 DebugFS gt A virtual filesystem to export debugging information to user space gt Kernel configuration DEBUG_FS gt Kernel hacking gt Debug Filesystem v The debugging interface disappears when Debugfs is configured out gt You can mount it as follows gt sudo mount t debugfs none sys
86. devmem2 0x000c0004 h reading gt devmem2 0x000c0008 w Oxffffffff writing gt devmem is now available in BusyBox making it even easier to use Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 454 473 mmap Summary gt The device driver is loaded It defines an mmap file operation gt A user space process calls the mmap system call gt The mmap file operation is called gt It initializes the mapping using the device physical address gt The process gets a starting address to read from and write to depending on permissions gt The MMU automatically takes care of converting the process virtual addresses into physical ones gt Direct access to the hardware without any expensive read or write system calls Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 455 473 Backup slides Introduction to Git Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 456 473 What is Git gt A version control system like CVS SVN Perforce or ClearCase gt Originally developed for the Linux kernel development now used by a large number of projects including U Boot GNOME Buildroot uClibc and many more gt Contrary to CVS or SVN Git is a distributed version control system
87. driver gt If the driver doesn t do anything else in its init exit O functions it is advised to use the module_i2c_driver macro instead Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 171 473 Registering an 12C device driver example static const struct i2c_device_id lt driver gt _id lt device name gt 0 aL dp 3 MODULE_DEVICE_TABLE i2c lt driver gt _id ifdef CONFIG_OF static const struct of_device_id lt driver gt _dt_ids T compatible lt vendor gt lt device name gt T 3 3 MODULE_DEVICE_TABLE of lt driver gt _dt_ids endif static struct i2c_driver lt driver gt _driver probe lt driver gt _probe remove lt driver gt _remove id_table lt driver gt _id driver name lt driver name gt owner THIS_MODULE of_match_table of_match_ptr lt driver gt _dt_ids F J module_i2c_driver lt driver gt _driver Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 172 473 Registering an I2C device non DT gt On non DT platforms the struct i2c_board_info structure allows to describe how an 12C device is connected to a board gt Such structures are normally defined with the I2C_BOARD_INFO helper macro gt Takes as argument the device name and the slave address
88. e device model was covered earlier in this training Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 199 473 Kernel frameworks for device drivers User space vision of devices Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 200 473 Types of devices Under Linux there are essentially three types of devices gt Network devices They are represented as network interfaces visible in user space using ifconfig gt Block devices They are used to provide user space applications access to raw storage devices hard disks USB keys They are visible to the applications as device files in dev gt Character devices They are used to provide user space applications access to all other types of devices input sound graphics serial etc They are also visible to the applications as device files in dev Most devices are character devices so we will study those in more details Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 201 473 Major and minor numbers gt Within the kernel all block and character devices are identified using a major and a minor number gt The major number typically indicates the family of the device gt The minor number typically indicates the numbe
89. e only one application accesses the device Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 46 473 User space device drivers 2 3 gt Possibilities for userspace device drivers gt USB with ibusb http www libusb org gt SPI with spidev Documentation spi spidev gt 12C with i2cdev Documentation i2c dev interface gt Memory mapped devices with UIO including interrupt handling Documentation DocBook uio howto gt Certain classes of devices printers scanners 2D 3D graphics acceleration are typically handled partly in kernel space partly in user space Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 47 473 User space device drivers 3 3 gt Advantages gt No need for kernel coding skills Easier to reuse code between devices gt Drivers can be written in any language even Perl gt Drivers can be kept proprietary gt Driver code can be killed and debugged Cannot crash the kernel Can be swapped out kernel code cannot be Can use floating point computation Less in kernel complexity Potentially higher performances especially for memory mapped devices thanks to the avoidance of system calls gt Drawbacks gt Less straightforward to handle interrupts gt Increased interrupt latency vs kernel code vvvyy Free Electrons Embedded
90. e electrons com training materials plain code hello hello c Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 108 473 Hello Module Explanations gt Headers specific to the Linux kernel linux xxx h gt No access to the usual C library we re doing kernel programming gt An initialization function gt Called when the module is loaded returns an error code 0 on success negative value on failure gt Declared by the module_init macro the name of the function doesn t matter even though lt modulename gt _init is a convention gt A cleanup function gt Called when the module is unloaded gt Declared by the module_exit macro gt Metadata information declared using MODULE_LICENSE MODULE_DESCRIPTION and MODULE_AUTHOR Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 109 473 Symbols Exported to Modules 1 2 v From a kernel module only a limited number of kernel functions can be called v Functions and variables have to be explicitly exported by the kernel to be visible to a kernel module gt Two macros are used in the kernel to export functions and variables gt EXPORT_SYMBOL symbolname which exports a function or variable to all modules gt EXPORT_SYMBOL_GPL symbolname which exports a function or variable only to GPL modules v
91. e of hardware resources from different applications gt Example a single network interface is used by multiple user space applications through various network connections The kernel is responsible to multiplex the hardware resource Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 22 473 System calls gt The main interface between the kernel and user space is the set of system calls gt About 300 system calls that provide the main kernel services gt File and device operations networking operations inter process communication process management memory mapping timers threads synchronization primitives etc gt This interface is stable over time only new system calls can be added by the kernel developers gt This system call interface is wrapped by the C library and user space applications usually never make a system call directly but rather use the corresponding C library function Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 23 473 Pseudo fil t seudo filesystems gt Linux makes system and kernel information available in user space through pseudo filesystems sometimes also called virtual filesystems gt Pseudo filesystems allow applications to see directories and files that do not exist on any real storage they are created and updated on
92. eabi gcc the prefix is arm 1linux gnueabi Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 85 473 Specifying cross compilation 1 The CPU architecture and cross compiler prefix are defined through the ARCH and CROSS_COMPILE variables in the toplevel Makefile gt ARCH is the name of the architecture It is defined by the name of the subdirectory in arch in the kernel sources gt Example arm if you want to compile a kernel for the arm architecture gt CROSS_COMPILE is the prefix of the cross compilation tools gt Example arm linux if your compiler is arm linux gcc Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 86 473 Specifying cross compilation 2 Two solutions to define ARCH and CROSS_COMPILE gt Pass ARCH and CROSS_COMPILE on the make command line make ARCH arm CROSS_COMPILE arm 1linux Drawback it is easy to forget to pass these variables when you run any make command causing your build and configuration to be screwed up gt Define ARCH and CROSS_COMPILE as environment variables export ARCH arm export CROSS_COMPILE arm 1linux Drawback it only works inside the current shell or terminal You could put these settings in a file that you source every time you start working on the project If you only work on a single architecture with alway
93. each bus subsystem gt In order to explore the device model we will gt First look at a popular bus that offers dynamic enumeration the USB bus gt Continue by studying how buses that do not offer dynamic enumerations are handled Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 132 473 Bus Drivers gt The gt gt It is gt gt first component of the device model is the bus driver One bus driver for each type of bus USB PCI SPI MMC I2C etc responsible for Registering the bus type struct bus_type Allowing the registration of adapter drivers USB controllers I2C adapters etc able to detect the connected devices and providing a communication mechanism with the devices Allowing the registration of device drivers USB devices 12C devices PCI devices etc managing the devices Matching the device drivers against the devices detected by the adapter drivers gt Provides an API to both adapter drivers and device drivers gt Defining driver and device specific structures mainly struct usb_driver and struct usb_interface Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 133 473 Linux device and driver model Example of the USB bus Free Electrons Embedded Linux kernel drivers and Android development consulting training and
94. ead or write one word gt gt s32 i2c_smbus_read_word_data const struct i2c_client client u8 command s32 i2c_smbus_write_word_data const struct i2c_client client u8 command u16 value gt Write a command byte and read or write a block of data max 32 bytes gt s32 i2c_smbus_read_block_data const struct i2c_client client u8 command u8 values s32 i2c_smbus_write_block_data const struct i2c_client client u8 command u8 length const u8 values gt Write a command byte and read or write a block of data no limit gt gt s32 i2c_smbus_read_i2c_block_data const struct i2c_client client u8 command u8 length u8 values s32 i2c_smbus_write_i2c_block_data const struct i2c_client client u8 command u8 length const u8 values Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 185 473 I2C functionality gt Not all 12C controllers support all functionalities gt The I2C controller drivers therefore tell the I2C core which functionalities they support gt An 2C device driver must check that the functionalities they need are provided by the I2C controller in use on the system gt The i2c_check_functionality function allows to make such a check gt Examples of functionalities I 2C_FUNC_1I2C to be able to use the raw 12C functions I2C_FUNC_SMBUS_BYTE_DATA to be able to use SMBus commands to write
95. ectrons com 343 473 Debugging Using Messages gt Three APIs are available gt The old printk no longer recommended for new debugging messages gt The pr_ family of functions pr_emerg pr_alert pr_crit pr_err pr_warning pr_notice pr_info pr_cont and the special pr_debug see next page gt They take a classic format string with arguments gt Defined in include linux printk h gt The dev_ family of functions dev_emerg dev_alert dev_crit dev_err dev_warning dev_notice dev_info and the special dev_dbg see next page gt They take a pointer to struct device as first argument and then a format string with arguments gt Defined in include linux device h gt To be used in drivers integrated with the Linux device model Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 344 473 pr_debug and dev_dbg gt When the driver is compiled with DEBUG defined all those messages are compiled and printed at the debug level DEBUG can be defined by define DEBUG at the beginning of the driver or using ccflags CONFIG_DRIVER DDEBUG in the Makefile gt When the kernel is compiled with CONFIG_DYNAMIC_DEBUG then those messages can dynamically be enabled on a per file per module or per message basis gt See Documentation dynamic debug howto txt for details gt Very powerful feature to only get the
96. ed by any signal Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 329 473 Locking and Unlocking Mutexes 2 2 gt mutex_trylock struct mutex lock gt Never waits Returns a non zero value if the mutex is not available gt mutex_is_locked struct mutex lock gt Just tells whether the mutex is locked or not gt mutex_unlock struct mutex lock gt Releases the lock Do it as soon as you leave the critical section Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 330 473 I Spinlocks gt Locks to be used for code that is not allowed to sleep interrupt handlers or that doesn t want to sleep critical sections Be very careful not to call functions which can sleep gt Originally intended for multiprocessor systems gt Spinlocks never sleep and keep spinning in a loop until the lock is available gt Spinlocks cause kernel preemption to be disabled on the CPU executing them gt The critical section protected by a spinlock is not allowed to sleep Still Locked Spinlock Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 331 473 Initializing Spinlocks gt Statically gt DEFINE_SPINLOCK my_lock gt Dynamically gt spin_lock_init lo
97. elopment consulting training and support http free electrons com 286 473 Misc subsystem API 1 2 gt The misc subsystem API mainly provides two functions to register and unregister a single misc device gt int misc_register struct miscdevice misc gt int misc_deregister struct miscdevice misc gt A misc device is described by a struct miscdevice structure struct miscdevice minor const xname const struct file_operations fops struct list_head list struct device parent struct device this_device const c nodename mode Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 287 473 Misc subsystem API 2 2 The main fields to be filled in struct miscdevice are gt minor the minor number for the device or MISC_DYNAMIC_MINOR to get a minor number automatically assigned gt name name of the device which will be used to create the device node if devtmpfs is used gt fops pointer to a struct file_operations structure that describes which functions implement the read write ioctl etc operations gt parent the struct device that represents the hardware device exposed by this driver Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 288 473 User space API for misc devices gt misc devices are regular character device
98. ement the operations of the cpufreq_driver structure and register them using cpufreq_register_driver gt init for initialization gt exit for cleanup gt verify to verify the user chosen policy gt setpolicy or target to actually perform the frequency change gt See Documentation cpu freq for useful explanations Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 396 473 PM Quality Of Service interface gt Kernel and user mode interface for registering performance expectations by drivers subsystems and user space applications gt Two different PM QoS frameworks are available gt PM QoS classes for CPU DMA latency network latency and and network throughput gt The per device PM QoS framework API to manage per device latency gt According to these requirements PM QoS allows kernel drivers to adjust their power management gt See Documentation power pm_qos_interface txt gt Still in very early deployment only used in about 15 drivers in 3 12 Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 397 473 Regulator Framework gt Modern embedded hardware have hardware responsible for voltage and current regulation gt The regulator framework allows to take advantage of this hardware to save power when parts of the system are unused gt A con
99. endent gt Some configuration options are very architecture specific gt Most of the configuration options global kernel options network subsystem filesystems most of the device drivers are visible in all architectures v By default the kernel build system assumes that the kernel is being built for the host architecture i e native compilation v The architecture is not defined inside the configuration but at a higher level v We will see later how to override this behaviour to allow the configuration of kernels for a different architecture Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 78 473 Kernel Source Code Compiling and installing the kernel for the host system Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 79 473 Kernel compilation i gt make gt in the main kernel source directory gt Remember to run multiple jobs in parallel if you have multiple CPU cores Example make j 4 gt No need to run as root gt Generates gt vmlinux the raw uncompressed kernel image at the ELF format useful for debugging purposes but cannot be booted gt arch lt arch gt boot Image the final usually compressed kernel image that can be booted gt bzimage for x86 zImage for ARM vmImage gz for Blackfin etc gt arch lt arc
100. ent consulting training and support http free electrons com 37 473 Portability gt The Linux kernel code is designed to be portable gt All code outside arch should be portable gt To this aim the kernel provides macros and functions to abstract the architecture specific details gt Endianness gt cpu_to_be32 gt cpu_to_1e32 gt be32_to_cpu gt 1e32_to_cpu gt 1 O memory access gt Memory barriers to provide ordering guarantees if needed gt DMA API to flush and invalidate caches if needed Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 38 473 No floating point computation gt Never use floating point numbers in kernel code Your code may be run on a processor without a floating point unit like on certain ARM CPUs gt Don t be confused with floating point related configuration options gt They are related to the emulation of floating point operation performed by the user space applications triggering an exception into the kernel gt Using soft float i e emulation in user space is however recommended for performance reasons Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 39 473 No stable Linux internal API gt The internal kernel API to implement kernel code can undergo changes between two releases gt In tree drive
101. enuconfig FB gt tristate Support for frame buffer devices gt Implemented in drivers video gt fb c fbmem c fbmon c fbcmap c fbsysfs c modedb c fbcvt c gt Implements a single character driver and defines the user kernel API gt First part of include linux fb h gt Defines the set of operations a framebuffer driver must implement and helper functions for the drivers gt struct fb_ops gt Second part of include linux fb h in ifdef __KERNEL__ Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 224 473 Framebuffer Driver Skeleton gt Skeleton driver in drivers video skeletonfb c gt Implements the set of framebuffer specific operations defined by the struct fb_ops structure gt xxxfb_open gt xxxfb_fillrect gt xxxfb_read gt xxxfb_copyarea gt xxxfb_write gt xxxfb_imageblit gt xxxfb_release gt xxxfb_cursor gt xxxfb_checkvar gt xxxfb_rotate gt xxxfb_setpar gt xxxfb_sync gt xxxfb_setcolreg gt xxxfb_blank xxxfb_pan_display gt xxxfb_ioctl gt xxxfb_mmap v Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 225 473 Framebuffer Driver Skeleton gt After the implementation of the operations definition of a struct fb_ops structure static struct fb_ops xxxfb_ops
102. es etc gt Such information can be represented using struct resource and an array of struct resource is associated to a struct platform_device gt Allows a driver to be instantiated for multiple devices functioning similarly but with different addresses IRQs etc Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 152 473 Declaring resources static struct resource imx_uarti_resources fo start 0x00206000 end 0x002060FF flags IORESOURCE_MEM Do Ci start UART1_MINT_RX end UART1_MINT_RX flags IORESOURCE_IRQ Po Jrg Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 153 473 Using Resources gt When a struct platform_device is added to the system using platform_add_device the probe method of the platform driver gets called gt This method is responsible for initializing the hardware registering the device to the proper framework in our case the serial driver framework gt The platform driver has access to the I O resources res platform_get_resource pdev IORESOURCE_MEM 0 base ioremap res gt start PAGE_SIZE sport gt rxirq platform_get_irq pdev 0 Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 154 473
103. eturn gt t atomic_add_return gt int atomic_sub_return Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 340 473 Atomic Bit Operations Supply very fast atomic operations v v On most platforms apply to an unsigned long type v Apply to a void type on a few others gt Set clear toggle a given bit gt set_bit nr addr gt clear_bit nr addr gt change_bit nr addr gt Test bit value gt test_bit nr addr gt Test and modify return the previous value gt test_and_set_bit gt test_and_clear_bit gt test_and_change_bit Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 341 473 Practical lab Locking gt Add locking to the driver to prevent concurrent accesses to shared resources Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 342 473 K Debuggi ernel Debugging Free Electrons Kernel Debugging open ae Free Electrons Copyright 2004 2014 Free Electrons Creative Commons BY SA 3 0 license Corrections suggestions contributions and translations are welcome Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free el
104. f the code with the device drivers separated from the controller drivers the hardware description separated from the drivers themselves etc gt This is what the Linux kernel Device Model allows in addition to other advantages covered in this section Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 130 473 Kernel and Device Drivers In Linux a driver is always interfacing with Application User space gt a framework that allows the driver to expose the hardware features in a generic way gt a bus infrastructure part of the device model to detect communicate with the hardware Kernel This section focuses on the device model while kernel frameworks are covered later in this training Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 131 473 Device Model data structures gt The device model is organized around three main data structures gt The struct bus_type structure which represent one type of bus USB PCI 12C etc gt The struct device_driver structure which represents one driver capable of handling certain devices on a certain bus gt The struct device structure which represents one device connected to a bus gt The kernel uses inheritance to create more specialized versions of struct device_driver and struct device for
105. fconfig files Choose SLAB allocator NEW SLAB SLAB tf SLUB Unqueued Allocator NEW SLUB oSLOB Simple Allocator SLOB Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 261 473 Do kmalloc Allocator gt The kmalloc allocator is the general purpose memory allocator in the Linux kernel gt For small sizes it relies on generic SLAB caches named kmalloc XXX in proc slabinfo gt For larger sizes it relies on the page allocator gt The allocated area is guaranteed to be physically contiguous gt The allocated area size is rounded up to the size of the smallest SLAB cache in which it can fit while using the SLAB allocator directly allows to have more flexibility gt It uses the same flags as the page allocator GFP_KERNEL GFP_ATOMIC GFP_DMA etc with the same semantics gt Maximum sizes on x86 and arm see http j mp YIGq6w Per allocation 4 MB Total allocations 128 MB gt Should be used as the primary allocator unless there is a strong reason to use another one Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 262 473 kmalloc API 1 2 gt include lt linux slab h gt gt kmalloc si size flags kd Allocate size bytes and return a pointer to the area virtual address size number of bytes to allocate flags same flags
106. g and support http free electrons com 416 473 Contribute to the Linux Kernel 2 gt Either create a new branch starting from the current commit in the master branch gt git checkout b feature Or if more appropriate create a new branch starting from the maintainer s master branch gt git checkout b feature linux omap master remote tree remote branch In your new branch implement your changes Test your changes must at least compile them gt Run git add to add any new files to the index gt Check that each file you modified is ready for submission gt scripts checkpatch pl strict file lt file gt If needed fix indenting rule violations gt indent linux lt file gt Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 417 473 Configure git send email gt Make sure you already have configured your name and e mail address should be done before the first commit gt git config global user name My Name gt git config global user email me mydomain net gt Configure your SMTP settings Example for a Google Mail account gt git config global sendemail smtpserver smtp googlemail com gt git config global sendemail smtpserverport 587 gt git config global sendemail smtpencryption tls gt git config global sendemail smtpuser jdoe gmail com gt git config global sendemail smtpp
107. g and support http free electrons com 469 473 Sharing changes HTTP Hosting gt Create a bare version of your repository gt cd tmp gt git clone bare project project git gt touch project git git daemon export ok gt Transfer the contents of project git to a publicly visible place reachable read only by HTTP for everybody and read write by you through SSH gt Tell people to clone http yourhost com path to project git gt Push your changes using gt git push ssh yourhost com path toproject git srcbranch destbranch Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 470 473 Tracking Remote Trees In addition to the official Linus Torvalds tree you might want to use other development or experimental trees gt The OMAP tree at git git kernel org pub scm linux kernel git tmlind linux omap git gt The stable realtime tree at git git kernel org pub scm linux kernel git rt linux stable rt git v v The git remote command allows to manage remote trees gt git remote add rt git git kernel org pub scm linux kernel git rt linux stable rt git Get the contents of the tree gt git fetch rt Switch to one of the branches v v gt git checkout rt master Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 471 473 About Git gt We
108. gt gt gt gt gt No central repository Everybody has a local repository Local branches are possible and very important Easy exchange of code between developers Well suited to the collaborative development model used in open source projects Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 457 473 Install and Setup gt Git is available as a package in your distribution gt sudo apt get install git gt Everything is available through the git command gt git has many commands called using git lt command gt where lt command gt can be clone checkout branch etc gt Help can be found for a given command using git help lt command gt gt Setup your name and e mail address gt They will be referenced in each of your commits gt git config global user name My Name gt git config global user email me mydomain net Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 458 473 Cl R it one a Repository gt To start working on a project you use Git s clone operation gt With CVS or SVN you would have used the checkout operation to get a working copy of the project latest version gt With Git you get a full copy of the repository including the history which allows to perform most of the operations offline gt Cloning
109. gt udev udev dev gt netdev netdev usb device si usb_set_intfdata intf dev SET_NETDEV_DEV netdev amp intf gt dev ae d static void rt18150_disconnect struct usb_interface intf rtl8i50_t dev usb_get_intfdata intf Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 234 473 The input subsystem The in put Free Electrons subsystem Emig Free Electrons Copyright 2004 2014 Free Electrons Creative Commons BY SA 3 0 license Corrections suggestions contributions and translations are welcome Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 235 473 What is input subsystem gt The input subsystem takes care of all the input events coming from the human user gt Initially written to support the USB HID Human Interface Device devices it quickly grew up to handle all kind of inputs using USB or not keyboard mice joystick touchscreen etc gt The input subsystem is split in two parts gt Device drivers they talk to the hardware for example via USB and provide events keystrokes mouse movements touchscreen coordinates to the input core gt Event handlers they get events from drivers and pass them where needed via various interfaces most of the time through evdev gt In user space it is usually used by
110. h gt boot dts dtb compiled Device Tree files on some architectures gt All kernel modules spread over the kernel source tree as ko files Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 80 473 Kernel installation gt make install gt Does the installation for the host system by default so needs to be run as root Generally not used when compiling for an embedded system and it installs files on the development workstation gt Installs gt boot vmlinuz lt version gt Compressed kernel image Same as the one in arch lt arch gt boot gt boot System map lt version gt Stores kernel symbol addresses gt boot config lt version gt Kernel configuration for this version gt Typically re runs the bootloader configuration utility to take the new kernel into account Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 81 473 Module installati odule installation gt make modules_install gt Does the installation for the host system by default so needs to be run as root gt Installs all modules in lib modules lt version gt gt kernel Module ko Kernel Object files in the same directory structure as in the sources gt modules alias Module aliases for module loading utilities Example line alias sound service 0 snd_mixer_o
111. h this generally only happens with code submitted for the mainline kernel gt Your drivers can be freely and easily shipped by others for example by Linux distributions or embedded Linux build systems gt Pre compiled drivers work with only one kernel version and one specific configuration making life difficult for users who want to change the kernel version gt Legal certainty you are sure that a GPL driver is fine from a legal point of view Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 44 473 Advantages of in tree kernel drivers v Once your sources are accepted in the mainline tree they are maintained by people making changes v Near cost free maintenance security fixes and improvements gt Easy access to your sources by users gt Many more people reviewing your code Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 45 473 User space device drivers 1 3 gt In some cases it is possible to implement device drivers in user space gt Can be used when gt The kernel provides a mechanism that allows userspace applications to directly access the hardware gt There is no need to leverage an existing kernel subsystem such as the networking stack or filesystems gt There is no need for the kernel to act as a multiplexer for the devic
112. he methods to port the Linux kernel to a new board are therefore very architecture dependent gt For example some architectures use the Device Tree some do not gt This presentation is focused on the ARM architecture only Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 359 473 Architecture CPU and Machine gt In the source tree each architecture has its own directory gt arch arm for the ARM architecture gt This directory contains generic ARM code gt boot common configs kernel lib mm nwfpe vfp oprofile tools gt And many directories for different SoC families gt mach directories mach pxa for PXA CPUs mach imx for Freescale iMX CPUs etc gt Before the ARM cleanup those directories contained support for the SoC family GPIO clocks pinmux power management interrupt controller etc and for the various boards gt Nowadays they contain a lot less code essentially a small SoC description file power management and SMP code gt Some CPU types share some code in directories named plat gt Device Tree source files in arch arm boot dts Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 360 473 Before the Device Tree and ARM cleanup gt Until 2011 the ARM architecture wasn t using the Device Tree and a large portion of the
113. i0036 muxing configuration leds compatible gpio leds pinctrl names default pinctrl 0 lt amp led_pins_cfa10036 gt power gpios lt amp gpio3 4 1 gt default state on J Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 370 473 Crystalfontz CFA 10036 Device Tree SD Card USB gt The platform also has a USB port usb0 usb 80080000 pinctrl names default pinctrl 0 lt amp usb0_otg_cfa10036 gt status okay ig gt and an SD Card slot ssp0 ssp 80010000 compatible fsl imx28 mmc pinctrl names default pinctrl 0 lt amp mmcO_4bit_pins_a amp mmcO_cd_cfg amp mmcO_sck_cfg gt bus width lt 4 gt status okay Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 371 473 Crystalfontz CFA 10036 Device Tree 12C bus gt An I2C bus with a Solomon SSD1306 OLED display connected on it i2c0 i2c 80058000 pinctrl names default pinctrl 0 lt amp i2c0_pins_b gt clock frequency lt 400000 gt status okay ssd1306 oled 3c compatible solomon ssd1306fb i2c pinctrl names default pinctrl 0 lt amp ssd1306_cfa10036 gt reg lt 0x3c gt reset gpios lt amp gpio2 7 0 gt solomon height lt 32 gt solomon width lt 128 gt solomon page offset lt 0 gt
114. ing training and support http free electrons com 175 473 Registering an I2C device DT example 1 2 Definition of the 12C controller dtsi file i2c 7000c000 compatible nvidia tegra20 1i2c reg lt 0x7000c000 0x100 gt interrupts lt GIC_SPI 38 IRQ_TYPE_LEVEL_HIGH gt address cells lt 1 gt size cells lt 0 gt clocks lt amp tegra_car TEGRA20_CLK_I2C1 gt lt amp tegra_car TEGRA20_CLK_PLL_P_OUT3 gt clock names div clk fast clk status disabled Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 176 473 Registering an I2C device DT example 2 2 Definition of the 12C device dts file i2c 7000c000 status okay clock frequency lt 400000 gt alc5632 alc5632 1e compatible realtek alc5632 reg lt Oxile gt gpio controller gpio cells lt 2 gt Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 177 473 probe and remove gt The gt probe function is responsible for initializing the device and registering it in the appropriate kernel framework It receives as argument gt A struct i2c_client pointer which represents the 12C device itself This structure inherits from struct device gt A struct i2c_device_id pointer which points to the 12C device ID entry that matched the device that
115. ing lists dedicated to our training customers gt To ask questions about the topics covered by the courses and to get a first level of technical support for issues that your are facing in real life or with your own hardware gt To share your experience with other people having taken the same course and done the same practical labs gt To share further comments and suggestions about course contents gt To get news about important updates to the course materials See http free electrons com training mailing lists A simple way to register fill the form on http j mp 1r1HhkZ Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 7 473 Generic course information Generic course Free Electrons information Embed Linux Free Electrons Copyright 2004 2014 Free Electrons Creative Commons BY SA 3 0 license Corrections suggestions contributions and translations are welcome Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 8 473 Hardware used in this training session BeagleBone Black from CircuitCo gt Texas Instruments AM335x ARM Cortex A8 gt Powerful CPU with 3D acceleration additional processors PRUs and lots of peripherals gt 512 MB of RAM gt 2 GB of on board eMMC storage 4 GB in Rev C USB host and USB device ports micr
116. ing with the I2C device raw API The most basic API to communicate with the I2C device provides functions to either send or receive data gt int i2c_master_send struct i2c_client client const char buf int count Sends the contents of buf to the client gt int i2c_master_recv struct i2c_client client char buf int count Receives count bytes from the client and store them into buf Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 181 473 Communicating with the I2C device message transfer The message transfer API allows to describe transfers that consists of several messages with each message being a transaction in one direction gt int i2c_transfer struct i2c_adapter adap struct i2c_msg msg int num gt The struct i2c_adapter pointer can be found by using client gt adapter gt The struct i2c_msg structure defines the length location and direction of the message Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 182 473 I2C message transfer example struct i2c_msg msg 2 error u8 start_reg u8 buf i0 msg 0 addr client gt addr msg 0 flags 0 msg 0 len 1 msg 0 buf amp start_reg start_reg 0x10 msg i addr client gt addr msg i flags I2C_M_RD msg i len sizeof buf msg i buf buf error i2c_tra
117. inux user_namespace h gt 19 include lt 1inux proc_ns n gt 20 21 22 userns count is 1 for root user 4 for init_uts_ns 23 and 4 for 24 s 25 struct user_namespace init_user_ns 26 uid map 27 nr_extents 1 28 extent 0 29 first 9 30 lower_first 0 31 count 4294967295U Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 59 473 Practical lab Kernel Source Code Exploring gt Explore kernel sources manually gt Use automated tools to explore the source code Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 60 473 Kernel Source Code Kernel configuration Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 61 473 Kernel configuration and build system gt The kernel configuration and build system is based on multiple Makefiles gt One only interacts with the main Makefile present at the top directory of the kernel source tree gt Interaction takes place gt using the make tool which parses the Makefile gt through various targets defining which action should be done configuration compilation installation etc Run make help to see all available targets gt Example gt cd linux 3 6 x gt make lt target gt
118. is a derivative work of the kernel and therefore must be released under GPLv2 gt The validity of the GPL on this point has already been verified in courts gt However you re only required to do so gt At the time the device starts to be distributed gt To your customers not to the entire world Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 42 473 Proprietary code and the kernel gt It is illegal to distribute a binary kernel that includes statically compiled proprietary drivers gt The kernel modules are a gray area are they derived works of the kernel or not gt The general opinion of the kernel community is that proprietary drivers are bad http j mp fbyuuH gt From a legal point of view each driver is probably a different case gt Is it really useful to keep your drivers secret gt There are some examples of proprietary drivers like the Nvidia graphics drivers gt They use a wrapper between the driver and the kernel gt Unclear whether it makes it legal or not Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 43 473 Advantages of GPL drivers gt You don t have to write your driver from scratch You can reuse code from similar free software drivers gt You could get free community contributions support code review and testing thoug
119. is being probed gt The gt remove function is responsible for unregistering the device from the kernel framework and shut it down It receives as argument gt The same struct i2c_client pointer that was passed as argument to gt probe Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 178 473 Probe remove example static lt driver gt _probe struct i2c_client client const struct i2c_device_id id initialize device register to a kernel framework i2c_set_clientdata client lt private data gt return 0 static lt driver gt _remove struct i2c_client client lt private data gt i2c_get_clientdata client unregister device from kernel framework shut down the device return 0 Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 179 473 Practical lab Linux device model for an I2C driver gt Modify the Device Tree to instantiate an I2C device gt Implement a driver that registers as an 12C driver gt Make sure that the probe remove functions are called when there is a device driver match gt Explore the sysfs entries related to your driver and device Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 180 473 Communicat
120. it_event_interruptible_exclusive puts a task in an exclusive wait gt wake_up wake_up_interruptible wakes up all non exclusive tasks and only one exclusive task gt wake_up_all wake_up_interruptible_al1l wakes up all non exclusive and all exclusive tasks gt Exclusive sleeps are useful to avoid waking up multiple tasks when only one will be able to consume the event gt Non exclusive sleeps are useful when the event can benefit to multiple tasks Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 304 473 Sleeping and waking up Implementation 1 2 Task in TASK_RUNNING state wait_event Put task in state ASK_UNINTERRUPTIBLE Sleeping schedule Evaluate condition Put task in state TASK_RUNNING Continue execution Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 305 473 Sleeping and waking up Implementation 2 2 The scheduler doesn t keep evaluating the sleeping condition gt wait_event queue condition gt The process is put in the TASK_UNINTERRUPTIBLE state gt wake_up amp queue gt All processes waiting in queue are woken up so they get scheduled later and have the opportunity to evaluate the condition again and go back to sleep if it is not met See include linux wait h
121. kernel from a reserved location in RAM to perform post mortem analysis of the memory of the crashed kernel Step 3 Analyze crashed kernel RAM gt See Documentation kdump kdump txt in the kernel sources for details Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 356 473 Practical lab Kernel debugging gt Use the dynamic printk feature gt Add debugfs entries gt Load a broken driver and see it crash gt Analyze the error information dumped by the kernel gt Disassemble the code and locate the exact C instruction which caused the failure Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 357 473 Porting the Linux Kernel to an ARM Board Porting the Linux Kernel to an ARM Board cs Free Electrons Copyright 2004 2014 Free Electrons Creative Commons BY SA 3 0 license Corrections suggestions contributions and translations are welcome Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 358 473 Porting the Linux kernel gt The Linux kernel supports a lot of different CPU architectures gt Each of them is maintained by a different group of contributors gt See the MAINTAINERS file for details gt The organization of the source code and t
122. l val addr gt To do raw access without endianness conversion __raw_read bw1 addr __raw_write bwl val addr gt Example gt 32 bits write __raw_writel i lt lt KS8695_IRQ_UART_TX membase KS8695_INTST Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 279 473 New API for mixed accesses gt A new API allows to write drivers that can work on either devices accessed over PIO or MMIO A few drivers use it but there doesn t seem to be a consensus in the kernel community around it gt Mapping gt For PIO ioport_map and ioport_unmap They don t really map but they return a special iomem cookie gt For MMIO ioremap and iounmap As usual gt Access works both on addresses or cookies returned by ioport_map and ioremap gt ioread 8 16 32 and iowrite 8 16 32 for single access gt ioread 8 16 32 _rep and iowrite 8 16 32 _rep for repeated accesses Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 280 473 Avoiding I O access issues gt Caching on I O ports or memory already disabled gt Use the macros they do the right thing for your architecture gt The compiler and or CPU can reorder memory accesses which might cause troubles for your devices is they expect one register to be read written before another
123. l_omap_driver probe serial_omap_probe remove serial_omap_remove driver name DRIVER_NAME pm amp serial_omap_dev_pm_ops of_match_table of_match_ptr omap_serial_of_match Ty Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 162 473 Device Tree Resources gt The drivers will use the same mechanism that we saw previously to retrieve basic information interrupts numbers physical addresses etc gt The available resources list will be built up by the kernel at boot time from the device tree so that you don t need to make any unnecessary lookups to the DT when loading your driver gt Any additional information will be specific to a driver or the class it belongs to defining the bindings Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 163 473 Device Tree bindings gt The compatible string and the associated properties define what is called a device tree binding gt Device tree bindings are all documented in Documentation devicetree bindings gt Since the Device Tree is normally part of the kernel ABI the bindings must remain compatible over time gt A new kernel must be capable of using an old Device Tree gt This requires a very careful design of the bindings They are all reviewed on the devicetree vger kernel org
124. latform gt Boot this kernel from a directory on your workstation accessed by the board through NFS Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 94 473 Kernel Source Code Using kernel modules Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 95 473 Advantages of modules gt Modules make it easy to develop drivers without rebooting load test unload rebuild load gt Useful to keep the kernel image size to the minimum essential in GNU Linux distributions for PCs gt Also useful to reduce boot time you don t spend time initializing devices and kernel features that you only need later gt Caution once loaded have full control and privileges in the system No particular protection That s why only the root user can load and unload modules Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 96 473 Module dependencies gt Some kernel modules can depend on other modules which need to be loaded first gt Example the usb storage module depends on the scsi_mod libusual and usbcore modules gt Dependencies are described in 1ib modules lt kernel version gt modules dep This file is generated when you run make modules_install Free Electrons Embedded Lin
125. ll Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 19 473 Linux kernel key features Free Electrons Portability and hardware support Runs on most architectures Scalability Can run on super computers as well as on tiny devices 4 MB of RAM is enough Compliance to standards and interoperability Exhaustive networking support Security It can t hide its flaws Its code is reviewed by many experts Stability and reliability Modularity Can include only what a system needs even at run time Easy to program You can learn from existing code Many useful resources on the net Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 20 473 Linux kernel in the system User app B Library A User app A C library Call to services Event notification information exposition Linux kernel Manage hardware Event notification Hardware Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 21 473 Li k l i l inux kernel main roles gt Manage all the hardware resources CPU memory I O gt Provide a set of portable architecture and hardware independent APIs to allow user space applications and libraries to use the hardware resources gt Handle concurrent accesses and usag
126. lting training and support http free electrons com 137 473 Device Identifiers gt Defines the set of devices that this driver can manage so that the USB core knows for which devices this driver should be used gt The MODULE_DEVICE_TABLE macro allows depmod to extract at compile time the relation between device identifiers and drivers so that drivers can be loaded automatically by udev See lib modules uname r modules alias usbmap static struct usb_device_id rt18150_table USB_DEVICE VENDOR_ID_REALTEK PRODUCT_ID_RTL8150 USB_DEVICE VENDOR_ID_MELCO PRODUCT_ID_LUAKTX USB_DEVICE VENDOR_ID_MICRONET PRODUCT_ID_SP1i28AR USB_DEVICE VENDOR_ID_LONGSHINE PRODUCT_ID_LCS8138TX Eea IPE MODULE_DEVICE_TABLE usb rt18150_table Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 138 473 Instantiation of usb_driver gt struct usb_driver is a structure defined by the USB core Each USB device driver must instantiate it and register itself to the USB core using this structure gt This structure inherits from struct device_driver which is defined by the device model static struct usb_driver rt18150_driver mame rt18150 probe rt18150_probe disconnect rt18150_disconnect id_table rt18150_table Suspend rtl18150_suspend resume rt18150_resume Ie Free Electrons Embedded Linux kernel
127. m 102 473 Passing parameters to modules gt Find available parameters modinfo snd intel8x0m gt Through insmod sudo insmod snd intel8x0m ko index 2 gt Through modprobe Set parameters in etc modprobe conf or in any file in etc modprobe d options snd intel8x0m index 2 gt Through the kernel command line when the driver is built statically into the kernel snd intel8x0m index 2 gt snd intel8x0m is the driver name gt index is the driver parameter name gt 2 is the driver parameter value Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 103 473 Check module parameter values How to find the current values for the parameters of a loaded module gt Check sys module lt name gt parameters gt There is one file per parameter containing the parameter value Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 104 473 Useful reading Linux Kernel in a Nutshell Dec 2006 gt v v Free Electrons By Greg Kroah Hartman O Reilly http www kroah com 1kn A good reference book and guide on configuring compiling and managing the Linux kernel sources Freely available on line Great companion to the printed book for easy electronic searches Available as single PDF file on http free electrons com community kernel 1kn
128. m 381 473 Clock Framework 1 gt Generic framework to manage clocks used by devices in the system gt Allows to reference count clock users and to shutdown the unused clocks to save power gt Simple API described in Documentation DocBook kernel api clk html gt gt gt gt gt clk_get to get a reference to a clock clk_enable to start the clock clk_disable to stop the clock clk_put to free the clock source clk_get_rate to get the current rate Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 382 473 Clock Framework 2 gt The common clock framework gt Allows to declare the available clocks and their association to devices in the Device Tree preferred or statically in the source code old method Provides a debugfs representation of the clock tree Is implemented in drivers clk Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 383 473 Diagram overview of the common clock framework Uses the public clock API clk_get clk_put clk_prepare clk_unprepare Uses the clk_enable clk_disable clk_ops clk_get_rate etc P operations Describes relationships Which clocks are needed Device Tree Clock driver Clocks and their gt foo for the different devices Clock driver bar
129. mailing list gt A Device Tree binding should contain only a description of the hardware and not configuration gt An interrupt number can be part of the Device Tree as it describes the hardware gt But not whether DMA should be used for a device or not as it is a configuration choice Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 164 473 sysfs gt The bus device drivers etc structures are internal to the kernel gt The sysfs virtual filesystem offers a mechanism to export such information to user space gt Used for example by udev to provide automatic module loading firmware loading device file creation etc gt sysfs Is usually mounted in sys gt sys bus contains the list of buses gt sys devices contains the list of devices gt sys class enumerates devices by class net input block whatever the bus they are connected to Very useful gt Take your time to explore sys on your workstation Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 165 473 Ref eferences gt Device Tree for Dummies Thomas Petazzoni Apr 2014 http j mp 1jQU6NR gt Kernel documentation gt Documentation driver model gt Documentation devicetree gt Documentation filesystems sysfs txt gt The kernel source code gt Full of examples
130. miss our free conference videos on http free electrons com community videos conferences Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 430 473 ARM resources gt ARM Linux project http www arm linux org uk gt Developer documentation http www arm 1linux org uk developer gt linux arm kernel mailing list http lists infradead org mailman listinfo linux arm kernel gt FAQ http www arm 1linux org uk armlinux mlfaq php gt Linaro http linaro org gt Many optimizations and resources for recent ARM CPUs toolchains kernels debugging utilities gt ARM Limited http www linux arm com gt Wiki with links to useful developer resources gt See our Embedded Linux course for details about toolchains http free electrons com training embedded linux Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 431 473 Last slides Free Electrons Last slides Beas Free Electrons Copyright 2004 2014 Free Electrons Creative Commons BY SA 3 0 license Corrections suggestions contributions and translations are welcome Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 432 473 Evaluation f valuation form Please take a few minutes to rate this training
131. n 0 Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 144 473 The Model is Recursive Char Driver 12C Device Driver USB Adapter Driver PCI Device Driver PAC Tanneries Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 145 473 Linux device and driver model Platform drivers Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 146 473 Non discoverable buses gt On embedded systems devices are often not connected through a bus allowing enumeration hotplugging and providing unique identifiers for devices gt For example the devices on I2C buses or SPI buses or the devices directly part of the system on chip gt However we still want all of those devices to be part of the device model gt Such devices instead of being dynamically detected must be statically described in either gt The kernel source code gt The Device Tree a hardware description file used on some architectures Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 147 473 Platform devices gt Amongst the non discoverable devices a huge family are the devices that are directly part of a system on chip UART co
132. nd more hardware blocks many of which need to interface with the outside world using pins gt However the physical size of the chips remains small and therefore the number of available pins is limited gt For this reason not all of the internal hardware block features can be exposed on the pins simultaneously gt The pins are multiplexed they expose either the functionality of hardware block A or the functionality of hardware block B gt This multiplexing is usually software configurable Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 189 473 Pi mo A in muxing diagram Configuration IZ O0 SCL UART3 TX SPI1 MOSI 12CO SDA Configuration Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 190 473 Pin muxing in the Linux kernel gt Since Linux 3 2 a pinctrl subsystem has been added gt This subsystem located in drivers pinctr1 provides a generic subsystem to handle pin muxing It offers gt A pin muxing consumer interface for device drivers gt A pin muxing driver interface to implement the system on chip specific drivers that configure the muxing gt Most pinctrl drivers provide a Device Tree binding and the pin muxing must be described in the Device Tree gt The exact Device Tree binding depends on each driver Each binding i
133. ndition timeout gt gt Also stops sleeping when the task is woken up and the timeout expired Returns O if the timeout elapsed non zero if the condition was met gt wait_event_interruptible_timeout queue condition timeout gt Same as above interruptible Returns 0 if the timeout elapsed ERESTARTSYS if interrupted positive value if the condition was met Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 301 473 How to Sleep Example ret wait_event_interruptible sonypi_device fifo_proc_list kfifo_len sonypi_device fifo 0 if ret return ret Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 302 473 Waking up gt Typically done by interrupt handlers when data sleeping processes are waiting for become available gt wake_up amp queue gt Wakes up all processes in the wait queue gt wake_up_interruptible amp queue gt Wakes up all processes waiting in an interruptible sleep on the given queue Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 303 473 Exclusive vs non exclusive gt wait_event_interruptible puts a task ina non exclusive wait gt All non exclusive tasks are woken up by wake_up wake_up_interruptible gt wa
134. ng training and support http free electrons com 112 473 Compiling a Module gt Two solutions gt Out of tree gt When the code is outside of the kernel source tree in a different directory gt Advantage Might be easier to handle than modifications to the kernel itself gt Drawbacks Not integrated to the kernel configuration compilation process needs to be built separately the driver cannot be built statically gt Inside the kernel tree gt Well integrated into the kernel configuration compilation process gt Driver can be built statically if needed Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 113 473 Compiling an out of tree Module 1 2 gt The below Makefile should be reusable for any single file out of tree Linux module gt The source file is hello c gt Just run make to build the hello ko file ifneq KERNELRELEASE obj m hello o else KDIR path to kernel sources all lt tab gt MAKE C KDIR M PWD endif gt For KDIR you can either set gt full kernel source directory configured make modules_prepare gt or just kernel headers directory make headers_install Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 114 473 Compiling an out of tree Module 2 2 Kernel Sources path to kernel_source include
135. ng training and support http free electrons com 316 473 Top half and bottom half diagram IRQ12 IRQ42 Once all softirqs are finished is is control is given back to the triggered triggered scheduler Handler IRQ42 Once all IRQ handlers have been executed softirqs are executed Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 317 473 Softirqs gt Softirqs are a form of bottom half processing gt The softirqs handlers are executed with all interrupts enabled and a given softirq handler can run simultaneously on multiple CPUs gt They are executed once all interrupt handlers have completed before the kernel resumes scheduling processes so sleeping is not allowed gt The number of softirqs is fixed in the system so softirqs are not directly used by drivers but by complete kernel subsystems network etc gt The list of softirgs is defined in include linux interrupt h HI TIMER NET_TX NET_RX BLOCK BLOCK_IOPOLL TASKLET SCHED HRTIMER RCU gt The HI and TASKLET softirqs are used to execute tasklets Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 318 473 Tasklets gt Tasklets are executed within the HI and TASKLET softirqs They are executed with all interrupts enabled but a given tasklet is guaranteed to execute on a single CPU
136. ning and support http free electrons com 321 473 Workqueues gt Workqueues are a general mechanism for deferring work It is not limited in usage to handling interrupts gt The function registered as workqueue is executed in a thread which means gt All interrupts are enabled gt Sleeping is allowed gt A workqueue is registered with INIT_WORK and typically triggered with queue_work gt The complete API in include linux workqueue h provides many other possibilities creating its own workqueue threads etc Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 322 473 Interrupt management summary Device driver v gt When the device file is first opened register an interrupt handler for the device s interrupt channel v Interrupt handler gt Called when an interrupt is raised gt Acknowledge the interrupt gt If needed schedule a tasklet taking care of handling data Otherwise wake up processes waiting for the data Tasklet gt Process the data gt Wake up processes waiting for the data v v Device driver gt When the device is no longer opened by any process unregister the interrupt handler Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 323 473 Practical lab Interrupts gt Adding read capability to the chara
137. nsfer client gt adapter msg 2 Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 183 473 SMBus calls gt SMBus is a subset of the I2C protocol gt t defines a standard set of transactions for example to read or write a register into a device gt Linux provides SMBus functions that should be used when possible instead of the raw API if the I2C device uses this standard type of transactions gt Example the i2c_smbus_read_byte_data function allows to read one byte of data from a device register gt It does the following operations S Addr Wr A Comm A S Addr Rd A Data NA P gt Which means it first writes a one byte data command Comm and then reads back one byte of data Data v See Documentation i2c smbus protocol for details Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 184 473 List of SMBus functions gt Read write one byte gt gt s32 i2c_smbus_read_byte const struct i2c_client client s32 i2c_smbus_write_byte const struct i2c_client client u8 value gt Write a command byte and read or write one byte gt gt s32 i2c_smbus_read_byte_data const struct i2c_client client u8 command s32 i2c_smbus_write_byte_data const struct i2c_client client u8 command u8 value gt Write a command byte and r
138. nsulting training and support http free electrons com 465 473 B h ranches gt Create a branch gt git branch lt branchname gt gt Move to this branch gt git checkout lt branchname gt gt Both at once create and switch to branch gt git checkout b lt branchname gt gt List of local branches gt git branch gt List of all branches including remote branches gt git branch a Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 466 473 Making Changes gt Edit a file with your favorite text editor gt Get the status of your working copy gt git status gt Git has a feature called the index which allows you to stage your commits before committing them It allows to commit only part of your modifications by file or even by chunk gt On each modified file gt git add lt filename gt gt Then commit No need to be on line or connected to commit gt Linux requires the s option to sign your changes gt git commit s gt If all modified files should be part of the commit gt git commit as Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 467 473 Sharing Changes E mail gt The simplest way of sharing a few changes is to send patches by e mail gt The first step is to generate the patches gt git format patch n master lt yourb
139. nt consulting training and support http free electrons com 2 473 Electronic copies of these documents gt Electronic copies of your particular version of the materials are available on http free electrons com doc training avignon kernel oct 2014 gt Open the corresponding documents and use them throughout the course to look for explanations given earlier by the instructor gt You will need these electronic versions because we neither print any index nor any table of contents quite high environmental cost for little added value gt For future reference see the first slide to see where document updates will be available Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 3 473 Hyperlinks in the document There are many hyperlinks in the document gt Regular hyperlinks http kernel org gt Kernel documentation links Documentation kmemcheck txt gt Links to kernel source files and directories drivers input include linux fb h gt Links to the declarations definitions and instances of kernel symbols functions types data structures platform_get_irq GFP_KERNEL struct file_operations Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 4 473 Free Electrons at a glance gt Engineering company created in 2004 not a training company gt
140. nt area gt Or making sure caches are flushed when required gt Managing the DMA mappings and IOMMU if any gt See Documentation DMA API txt for details about the Linux DMA generic API gt Most subsystems such as PCI or USB supply their own DMA API derived from the generic one May be sufficient for most needs Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 441 473 Coherent or Streaming DMA Mappings gt Coherent mappings gt The kernel allocates a suitable buffer and sets the mapping for the driver Can simultaneously be accessed by the CPU and device So has to be in a cache coherent memory area Usually allocated for the whole time the module is loaded Can be expensive to setup and use on some platforms Yv vY Vv gt Streaming mappings gt The kernel just sets the mapping for a buffer provided by the driver gt Use a buffer already allocated by the driver gt Mapping set up for each transfer Keeps DMA registers free on the hardware gt The recommended solution Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 442 473 Allocating Coherent Mappings gt The kernel takes care of both buffer allocation and mapping include lt asm dma mapping h gt Qutput buffer address dma_alloc_coherent struct device dev device struc
141. ntrollers Ethernet controllers SPI or 12C controllers graphic or audio devices etc gt In the Linux kernel a special bus called the platform bus has been created to handle such devices gt It supports platform drivers that handle platform devices gt It works like any other bus USB PCI except that devices are enumerated statically instead of being discovered dynamically Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 148 473 Implementation of a Platform Driver gt The driver implements a struct platform_driver structure example taken from drivers serial imx c static struct platform_driver serial_imx_driver probe serial_imx_probe remove serial_imx_remove driver name imx uart owner THIS_MODULE i gt And registers its driver to the platform driver infrastructure static T init imx_serial_init at ret platform_driver_register amp serial_imx_driver i static _ exit imx_serial_cleanup af platform_driver_unregister amp serial_imx_driver i Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 149 473 Platform Device Instantiation old style 1 2 gt As platform devices cannot be detected dynamically they are defined statically gt By direct instantiation of struct platform_device structures as done on
142. oSD slot HDMI port 2 x 46 pins headers with access to many expansion buses 12C SPI UART and more gt A huge number of expansion boards called capes See http beagleboardtoys com yy vy Y Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 9 473 Shopping list hardware for this course gt BeagleBone Black Multiple distributors See http beagleboard org Products gt Nintendo Nunchuck with UEXT connector Olimex http j mp 1dTYLfs gt USB Serial Cable Male ends q Olimex http j mp 1eUuY2K gt USB Serial Cable Female ends Olimex http j mp 18Hk8yF gt Breadboard jumper wires Male ends Olimex http j mp IUaBsr Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 10 473 Participate During the lectures gt Don t hesitate to ask questions Other people in the audience may have similar questions too gt This helps the trainer to detect any explanation that wasn t clear or detailed enough gt Don t hesitate to share your experience for example to compare Linux Android with other operating systems used in your company gt Your point of view is most valuable because it can be similar to your colleagues and different from the trainer s gt Your participation can make our session more inte
143. ocking gt As we have just seen locking can have a strong negative impact on system performance In some situations you could do without it gt By using lock free algorithms like Read Copy Update RCU gt RCU API available in the kernel See http en wikipedia org wiki RCU gt When available use atomic operations Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 338 473 Atomic Variables 1 2 Useful when the shared resource is an integer value gt Even an instruction like n is not guaranteed to be atomic on all processors gt Atomic operations definitions gt include lt asm atomic h gt gt atomic_t gt Contains a signed integer at least 24 bits gt Atomic operations main ones gt Set or read the counter gt gt gt Operations without return value gt gt gt gt atomic_set atomic_read atomic_inc atomic_dec atomic_add atomic_sub V i v v v v v Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 339 473 Atomic Variables 2 2 gt Similar functions testing the result gt int atomic_inc_and_test gt atomic_dec_and_test gt int atomic_sub_and_test gt Functions returning the new value gt atomic_inc_return gt int atomic_dec_r
144. of other drivers Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 166 473 Introduction to the 12C subsystem Introduction to Free Electrons the I2C subsystem Embodied unur Free Electrons Copyright 2004 2014 Free Electrons Creative Commons BY SA 3 0 license Corrections suggestions contributions and translations are welcome Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 167 473 What is 12C A very commonly used low speed bus to connect on board devices to the processor gt Uses only two wires SDA for the data SCL for the clock gt It is a master slave bus only the master can initiate transactions and slaves can only reply to transactions initiated by masters gt In a Linux system the I2C controller embedded in the processor is typically the master controlling the bus gt Each slave device is identified by a unique I2C address Each transaction initiated by the master contains this address which allows the relevant slave to recognize that it should reply to this particular transaction Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 168 473 An 2C bus example Processor 12C controller 12C GPIO expander addr 0x2C addr 0x1
145. ons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 314 473 Threaded interrupts In 2 6 30 support for threaded interrupts has been added to the Linux kernel gt The interrupt handler is executed inside a thread gt Allows to block during the interrupt handler which is often needed for I2C SPI devices as the interrupt handler needs to communicate with them gt Allows to set a priority for the interrupt handler execution which is useful for real time usage of Linux devm_request_threaded_irq struct device dev irq handler thread_fn flags const xname xdev gt handler hard IRQ handler gt thread_fn executed in a thread Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 315 473 Top half and bottom half processing gt Splitting the execution of interrupt handlers in 2 parts gt Top half gt This is the real interrupt handler which should complete as quickly as possible since all interrupts are disabled If possible take the data out of the device and schedule a bottom half to handle it gt Bottom half gt Is the general Linux name for various mechanisms which allow to postpone the handling of interrupt related work Implemented in Linux as softirqs tasklets or workqueues Free Electrons Embedded Linux kernel drivers and Android development consulti
146. ork defines a structure that a device driver must register to be recognized as a device in this framework gt struct uart_port for serial port struct netdev for network devices struct fb_info for framebuffers etc gt In addition to this structure the driver usually needs to store additional information about its device gt This is typically done gt By subclassing the appropriate framework structure gt By storing a reference to the appropriate framework structure gt Or by including your information in the framework structure Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 228 473 Driver specific Data Structure Examples 1 2 gt i MX serial driver struct imx_port is a subclass of struct uart_port struct imx_port struct uart_port port struct timer_list timer old_status txirq rxirq rtsirq have_rtscts 1 EPPA gt dsl305 RTC driver struct ds1305 has a reference to struct rtc_device struct dsi305 struct spi_device spi struct rtc_device rtc aad 3 Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 229 473 Driver specific Data Structure Examples 2 2 gt rtl8150 network driver struct rt18150 has a reference to struct net_device and is allocated within that framework structure struct rt18150 flags struct usb_device
147. ort KVM Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 54 473 Kernel Source Code Kernel source management tools Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 55 473 Cscope gt Tool to browse source code mainly C but also C or Java gt Supports huge projects like the Linux kernel Typically takes less than 1 min to index the whole Linux sources gt In Linux kernel sources two ways of running it gt cscope Rk All files for all architectures at once gt make cscope cscope d scope out Only files for your current architecture gt Allows searching for a symbol a definition functions strings files etc gt Integration with editors like vim and emacs gt Dedicated graphical front end KScope gt http cscope sourceforge net Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 56 473 ymbol reque gt move the cursor between search results and commands 1 D exit cs Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 57 473 LXR Linux Cross Reference gt Generic source indexing tool and code browser gt Web server based very easy and fast to
148. ot config 3 2 0 31 generic Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 64 473 Kernel or module gt The kernel image is a single file resulting from the linking of all object files that correspond to features enabled in the configuration gt This is the file that gets loaded in memory by the bootloader gt All included features are therefore available as soon as the kernel starts at a time where no filesystem exists gt Some features device drivers filesystems etc can however be compiled as modules gt Those are plugins that can be loaded unloaded dynamically to add remove features to the kernel gt Each module is stored as a separate file in the filesystem and therefore access to a filesystem is mandatory to use modules gt This is not possible in the early boot procedure of the kernel because no filesystem is available Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 65 473 Kernel option types gt There are different types of options gt bool options they are either gt true to include the feature in the kernel or gt false to exclude the feature from the kernel gt tristate options they are either gt true to include the feature in the kernel image or gt module to include the feature as a kernel module or gt false to e
149. our knowledge gt Don t hesitate to report potential bugs to your instructor gt Don t hesitate to look for solutions on the Internet as well Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 13 473 gt Free Electrons Command memento sheet This memento sheet gives command examples for the most typical needs looking for files extracting a tar archive It saves us 1 day of UNIX Linux command line training Our best tip in the command line shell always hit the Tab key to complete command names and file paths This avoids 95 of typing mistakes Get an electronic copy on http free electrons com doc training embedded linux command_memento pdf Embedded Linux kernel drivers and Android development consulting training and support http free electrons com vi basic commands gt The vi editor is very useful to make quick changes to files in an embedded target gt Though not very user friendly at first vi is very powerful and its main 15 commands are easy to learn and are sufficient for 99 of everyone s needs gt Get an electronic copy on http free electrons com doc training embedded linux vi_memento pdf gt You can also take the quick tutorial by running vimtutor This is a worthy investment Free Electrons Embedded Linux kernel drivers and Android developmen
150. pdates The http kernel org front page shows which versions will be supported for some time up to 2 or 3 years and which ones won t be supported any more EOL End Of Life mainline stable stable longterm longterm longterm longterm longterm longterm linux next 3 14 rc8 2014 03 25 3 13 7 2014 03 24 3 11 10 EOL 2013 11 29 3 12 15 2014 03 26 3 10 34 2014 03 24 3 4 84 2014 03 24 3 255 2014 02 15 2 6 34 15 EOL 2014 02 10 2 6 32 61 2013 06 10 next 20140327 2014 03 27 Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 409 473 What s new in each Linux release gt The official list of changes for each Linux release is just a huge list of individual patches commit aa6e52a35d388e730 4df0ec2ec48294590cc459 Author Thomas Petazzoni lt thomas petazzoni free electrons com gt Date Wed Jul 13 11 29 17 2011 0200 at91 at91 ohci support overcurrent notification Several USB power switches AIC1526 or MIC2026 have a digital output that is used to notify that an overcurrent situation is taking place This digital outputs are typically connected to GPIO inputs of the processor and can be used to be notified of those overcurrent situations Therefore we add a new overcurrent_pin array in the at91_usbh_data structure so that boards can tell the AT91 OHCI driver which pins are used for the overcurrent notification and an overcurrent_
151. pl strict 00 patch Now send your patches to yourself gt git send email compose to me mydomain com 00 patch If you have just one patch or a trivial patch you can remove the empty line after In Reply To This way you won t add a summary e mail introducing your changes recommended otherwise Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 420 473 Contribute to the Linux Kernel 5 gt Check that you received your e mail properly and that it looks good gt Now find the maintainers for your patches scripts get_maintainer pl patches 00 patch Russell King lt linux arm linux org uk gt maintainer ARM PORT Nicolas Pitre lt nicolas pitre linaro org gt commit_signer 1 1 100 linux arm kernel lists infradead org open list ARM PORT linux kernel vger kernel org open list gt Now send your patches to each of these people and lists gt git send email compose to linux arm linux org uk to nicolas pitre linaro org to linux arm kernel lists infradead org to linux kernel vger kernel org 00 patch gt Wait for replies about your changes take the comments into account and resubmit if needed until your changes are eventually accepted Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 421 473 Contribute to the Linux Kernel 6 gt If
152. port http free electrons com 391 473 Saving Power in the Idle Loop gt The idle loop is what you run when there s nothing left to run in the system gt Implemented in all architectures in arch lt arch gt kernel process c gt Example to read look for cpu_idle in arch arm kernel process c gt Each ARM cpu defines its own arch_idle function gt The CPU can run power saving HLT instructions enter NAP mode and even disable the timers tickless systems gt See also http en wikipedia org wiki Idle_loop Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 392 473 Managing Idle gt Adding support for multiple idle levels gt Modern CPUs have several sleep states offering different power savings with associated wake up latencies gt Since 2 6 21 the dynamic tick feature allows to remove the periodic tick to save power and to know when the next event is scheduled for smarter sleeps gt CPUidle infrastructure to change sleep states gt Platform specific driver defining sleep states and transition operations gt Platform independent governors ladder and menu gt Available for x86 ACPI not supported yet by all ARM cpus look for cpuidie files under arch arm gt See Documentation cpuidle in kernel sources Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http f
153. put_dev dev struct input_keymap_entry ke eed open struct input_dev dev Esa event struct input_dev dev type code value gt Before being used this struct must be allocated and initialized struct input_dev input_allocate_device void gt After unregistering struct input_dev it must be freed void input_free_device struct input_dev dev Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 239 473 Input subsystem API 2 3 gt Depending on the type of event that will be generated the input bit fields evbit and keybit must be configured For example for a button we only generate EV_KEY type events and from those only BTN_O events code set_bit EV_KEY myinput_dev evbit set_bit BIN_O myinput_dev keybit gt set_bit is an atomic operation allowing to set a particular bit to 1 explained later gt Once the input device is allocated and filled the function to register it is int input_register_device struct input_dev gt When the driver will be unloaded the input device is unregistered using void input_unregister_device struct input_dev Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 240 473 Input subsystem API 3 3 gt The events are sent by the driver to the event handler using input_event struc
154. r of the device when they are for example several serial ports gt Most major and minor numbers are statically allocated and identical across all Linux systems gt They are defined in Documentation devices txt Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 202 473 Devices everything is a file v A very important Unix design decision was to represent most of the system objects as files gt It allows applications to manipulate all system objects with the normal file API open read write close etc gt So devices had to be represented as files to the applications gt This is done through a special artifact called a device file gt It is a special type of file that associates a file name visible to user space applications to the triplet type major minor that the kernel understands gt All device files are by convention stored in the dev directory Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 203 473 Device fil evice files examples Example of device files in a Linux system 1s 1 dev ttySO dev tty1 dev sda1 dev sda2 dev zero brw rw 1 root disk 8 1 2011 05 27 08 56 dev sdat brw rw 1 root disk 8 2 2011 05 27 08 56 dev sda2 crw 1 root root 4 1 2011 05 27 08 57 dev tty1 crw rw 1 root dialout
155. ractive and make the topics easier to learn Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 11 473 Practical lab guidelines During practical labs gt We cannot support more than 8 workstations at once each with its board and equipment Having more would make the whole class progress slower compromising the coverage of the whole training agenda exception for public sessions up to 10 people gt So if you are more than 8 participants please form up to 8 working groups gt Open the electronic copy of your lecture materials and use it throughout the practical labs to find the slides you need again gt Don t copy and paste from the PDF slides The slides contain UTF 8 characters that look the same as ASCII ones but won t be understood by shells or compilers Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 12 473 Cooperate As in the Free Software and Open Source community cooperation during practical labs is valuable in this training session gt If you complete your labs before other people don t hesitate to help other people and investigate the issues they face The faster we progress as a group the more time we have to explore extra topics gt Explain what you understood to other participants when needed It also helps to consolidate y
156. ranch gt gt Will generate one patch for each of the commits done on lt yourbranch gt gt The patch files will be 0001 0002 etc gt The second step is to send these patches by e mail gt git send email compose to email domain com 00 patch gt Required Ubuntu package git email gt Ina later slide we will see how to use git config to set the SMTP server port user and password Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 468 473 Sharing Changes Your Own Repository gt If you do a lot of changes and want to ease collaboration with others the best is to have your own public repository gt Use a git hosting service on the Internet gt Gitorious https gitorious org gt Open Source server Easiest For public repositories gt GitHub https github com gt For public repositories Have to pay for private repositories gt Publish on your own web server gt Easy to implement gt Just needs git software on the server and ssh access gt Drawback only supports http cloning less efficient gt Set up your own git server gt Most flexible solution gt Today s best solutions are gitolite https github com sitaramc gitolite for the server and cgit for the web interface http git zx2c4 com cgit about Free Electrons Embedded Linux kernel drivers and Android development consulting trainin
157. ree electrons com 254 473 P Allocat age Allocator gt Appropriate for medium size allocations gt A page is usually 4K but can be made greater in some architectures sh mips 4 8 16 or 64 KB but not configurable in x86 or arm gt Buddy allocator strategy so only allocations of power of two number of pages are possible 1 page 2 pages 4 pages 8 pages 16 pages etc gt Typical maximum size is 8192 KB but it might depend on the kernel configuration gt The allocated area is virtually contiguous of course but also physically contiguous It is allocated in the identity mapped part of the kernel memory space gt This means that large areas may not be available or hard to retrieve due to physical memory fragmentation Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 255 473 Page Allocator API Get free pages gt get_zeroed_page flags gt Returns the virtual address of a free page initialized to zero gt flags see the next pages for details gt __get_free_page flags gt Same but doesn t initialize the contents gt __get_free_pages flags order gt Returns the starting virtual address of an area of several contiguous pages in physical RAM with order being log2 number_of_pages Can be computed from the size with the get_order function Free Electrons Embedded Linux kernel drivers and Androi
158. ree electrons com 393 473 PowerT OP gt https 01 org powertop gt With dynamic ticks allows to fix parts of kernel code and applications that wake up the system too often gt PowerTOP allows to track the worst offenders gt Now available on ARM cpus implementing CPUidle gt Also gives you useful hints for reducing power Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 394 473 Frequency and Voltage Scaling 1 gt Frequency and voltage scaling possible through the cpufreq kernel infrastructure gt Generic infrastructure drivers cpufreq cpufreq c and include linux cpufreq h gt Generic governors responsible for deciding frequency and voltage transitions gt performance maximum frequency gt powersave minimum frequency gt ondemand measures CPU consumption to adjust frequency gt conservative often better than ondemand Only increases frequency gradually when the CPU gets loaded gt userspace leaves the decision to a user space daemon gt This infrastructure can be controlled from sys devices system cpu cpu lt n gt cpufreq Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 395 473 Frequency and Voltage Scaling 2 gt CPU support code in architecture dependent files Example to read arch arm plat omap cpu omap c gt Must impl
159. referred gt Using printk The pr_ and dev_ functions are preferred Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 349 473 Using Magic SysRq gt Allows to run multiple debug rescue commands even when the kernel seems to be in deep trouble gt gt On PC Alt SysRq lt character gt On embedded break character on the serial line lt character gt gt Example commands gt gt gt gt gt makes RT processes nice able shows the kernel stack of all sleeping processes shows the kernel stack of all running processes reboot the system You can even register your own ots 6 gt Detailed in Documentation sysrq txt Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 350 473 kgdb A Kernel Debugger gt The execution of the kernel is fully controlled by gdb from another machine connected through a serial line gt Can do almost everything including inserting breakpoints in interrupt handlers gt Feature supported for the most popular CPU architectures Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 351 473 Using kgdb 1 2 gt Details available in the kernel documentation Documentation DocBook kgdb gt Recommended to t
160. repository will be necessary from time to time gt git pull gt Internally does two things gt Fetch the new changes from the remote repository git fetch gt Merge them in the current branch git merge Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 463 473 Tags The list of existing tags can be found using v gt git tag 1 v To check out a working copy of the repository at a given tag gt git checkout lt tagname gt To get the list of changes between a given tag and the latest available version v gt git log v2 6 30 master v List of changes with diff on a given file between two tags gt git log p v2 6 29 v2 6 30 MAINTAINERS With gitk gt gitk v2 6 30 master v Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 464 473 Branches gt To start working on something the best is to make a branch gt It is local only nobody except you sees the branch gt It is fast gt It allows to split your work on different topics try something and throw it away gt It is cheap so even if you think you re doing something small and quick do a branch gt Unlike other version control systems Git encourages the use of branches Don t hesitate to use them Free Electrons Embedded Linux kernel drivers and Android development co
161. requency lt 48000000 gt reg lt 0x44e09000 0x2000 gt interrupts lt 72 gt status disabled gt serial 44e09000 is the node name gt uartoO is an alias that can be referred to in other parts of the DT as amp uart0O gt other lines are properties Their values are usually strings list of integers or references to other nodes Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 159 473 Device Tree inheritance 1 2 gt Each particular hardware platform has its own device tree gt However several hardware platforms use the same processor and often various processors in the same family share a number of similarities gt To allow this a device tree file can include another one The trees described by the including file overlays the tree described by the included file This can be done gt Either by using the include statement provided by the Device Tree language gt Either by using the include statement which requires calling the C preprocessor before parsing the Device Tree Linux currently uses either one technique or the other different from one ARM subarchitecture to another for example Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 160 473 Device Tree inheritance 2 2 Definition of the AM33xx SoC Definition of the
162. rivers and Android development consulting training and support http free electrons com 68 473 Option General setup FIRQ subsystem i CU Subsystem OControl Group support ONamespaces support Configure standard kernel Features expert users Kernel Performance Events And Counters GCOV based kernel profiling Enable loadable module support Enable the block layer Partition Types 10 Schedulers System Type T OMAP2 3 4 Specific Features Bus support OPCCard PCMCIA CardBus support Kernel Features Boot options CPU Power Management CPU Frequency scaling Floating point emulation Userspace binary Formats Power management options Networking support 2 Mabwiarckina ambiance gt Option OMAP System Type FOTI OMAP1 Q OMAP Feature Selections OSmartReflex support Reset unused clocks during boot F OMAP multiplexing support Multiplexing debug output warn about pins the bootloader didn t set up Mailbox Framework support Use 32KHz timer TI OMAP2 3 4 ARCH_OMAP2PLUS CONFIG_ARCH_OMAP2PLUS Systems based on OMAP2 OMAP3 or OMAP4 Symbol ARCH_OMAP2PLUS y Type boolean Prompt TI OMAP2 3 4 Defined at arch arm plat omap Kconfig 24 Depends on lt choice gt Location gt System Type gt TI OMAP Common Features gt OMAP System Type lt choice gt Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free
163. rivers in the common case even if the file is several thousand lines of code big Only really big drivers are split in several files or have their own directory gt Describe the configuration interface for your new driver by adding the following lines to the Kconfig file in this directory config USB_SERIAL_NAVMAN tristate USB Navman GPS device depends on USB_SERIAL help To compile this driver as a module choose M here the module will be called navman Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 117 473 New Driver in Kernel Sources 2 2 gt Add a line in the Makefile file based on the Kconfig setting obj CONFIG_USB_SERIAL_NAVMAN navman o gt It tells the kernel build system to build navman c when the USB_SERIAL_NAVMAN option is enabled It works both if compiled statically or as a module gt Run make xconfig and see your new options gt Run make and your new files are compiled gt See Documentation kbuild for details and more elaborate examples like drivers with several source files or drivers in their own subdirectory etc Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 118 473 Hello Module with Parameters 1 2 hello_param c include lt linux init h gt include lt linux module h gt MODULE_LICENSE GPL A couple of par
164. rnel Subscribe to finance the editors 7 month Articles available for non subscribers after 1 week Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 424 473 Useful Reading 1 Essential Linux Device Drivers April 2008 v v v Free Electrons http elinuxdd com By Sreekrishnan Venkateswaran an embedded IBM engineer with more than sean 10 years of experience _ Covers a wide range of topics not covered Essential Linux Device Drivers by LDD serial drivers input drivers 12C PCMCIA and Compact Flash PCI USB video drivers audio drivers block drivers network drivers Bluetooth IrDA MTD drivers in user space kernel debugging etc Probably the most wide ranging and complete Linux device driver book I ve read Alan Cox Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 425 473 Useful Reading 2 Writing Linux Device drivers September 2009 gt http www coopj com gt Self published by Jerry Cooperstein Writing gt Available like any other book Amazon RONE and others 4 guide with exercises gt Though not as thorough as the previous book on specific drivers still a good complement on multiple aspects of kernel and device driver development gt Based on Linux 2 6 31 gt Multiple exercises Updated solutions for 2
165. rocess user space or kernel space is waiting for data Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 298 473 How to sleep 1 3 gt Must declare a wait queue gt A wait queue will be used to store the list of threads waiting for an event gt Static queue declaration gt useful to declare as a global variable gt DECLARE_WAIT_QUEUE_HEAD module_queue gt Or dynamic queue declaration gt Useful to embed the wait queue inside another data structure queue init _waitqueue_head amp queue Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 299 473 How to sleep 2 3 gt Several ways to make a kernel process sleep gt wait_event queue condition gt Sleeps until the task is woken up and the given C expression is true Caution can t be interrupted can t kill the user space process gt wait_event_killable queue condition gt Can be interrupted but only by a fatal signal SIGKILL Returns ERESTARSYS if interrupted gt wait_event_interruptible queue condition gt Can be interrupted by any signal Returns ERESTARTSYS if interrupted Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 300 473 How to sleep 3 3 wait_event_timeout queue co
166. rocess to kill to retrieve some memory That s better than letting the system freeze Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 252 473 Back to kernel memory gt Kernel memory allocators see following slides allocate physical pages and kernel allocated memory cannot be swapped out so no fault handling required for kernel memory gt Most kernel memory allocation functions also return a kernel virtual address to be used within the kernel space gt Kernel memory low level allocator manages pages This is the finest granularity usually 4 KB architecture dependent gt However the kernel memory management handles smaller memory allocations through its allocator see SLAB allocators used by kmalloc Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 253 473 Allocators in the Kernel Some Kernel Code kmalloc allocator Uses a set of anonymous vmalloc Allocator SLAB caches Non physically contiguous memory SLAB Allocator Allows to create caches each cache storing objects of the same size Size can be lower or greater than a page size Page Allocator Allows to allocate contiguous areas of physical pages 4k 8k 16k 32k etc Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http f
167. rs and Android development consulting training and support http free electrons com 378 473 Adding device drivers Once the core pieces of the SoC support have been implemented the remaining part is to add drivers for the different hardware blocks gt gt gt Ethernet driver in drivers net ethernet mvneta c SATA driver in drivers ata sata_mv c I2C driver in drivers i2c busses i2c mv64xxx c SPI driver in drivers spi spi orion c PCle driver in drivers pci host pci mvebu c USB driver in drivers usb host ehci orion c etc Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 379 473 Power Management Power Free Electrons Management aS le Free Electrons Copyright 2004 2014 Free Electrons Creative Commons BY SA 3 0 license Corrections suggestions contributions and translations are welcome Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 380 473 PM Building Blocks gt Several power management building blocks Suspend and resume CPUidle Runtime power management Frequency and voltage scaling Applications vvvyy gt Independent building blocks that can be improved gradually during development Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons co
168. rs are updated by the developer proposing the API change works great for mainline code gt An out of tree driver compiled for a given version may no longer compile or work on a more recent one gt See Documentation stable_api_nonsense txt_ in kernel sources for reasons why gt Of course the kernel to userspace API does not change system calls proc sys as it would break existing programs Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 40 473 Kernel memory constraints gt No memory protection Accessing illegal memory locations result in often fatal kernel oopses Fixed size stack 8 or 4 KB Unlike in user space there s no way to make it grow Kernel memory can t be swapped out for the same reasons v v v Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 41 473 Linux kernel licensing constraints gt The Linux kernel is licensed under the GNU General Public License version 2 gt This license gives you the right to use study modify and share the software freely gt However when the software is redistributed either modified or unmodified the GPL requires that you redistribute the software under the same license with the source code gt If modifications are made to the Linux kernel for example to adapt it to your hardware it
169. s gt The operations they support in user space depends on the operations the kernel driver implements gt The open and close system calls to open close the device gt The read and write system calls to read write to from the device gt The ioct1 system call to call some driver specific operations Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 289 473 Practical lab Output only serial port driver gt Extend the driver started in the previous lab by registering it into the misc subsystem gt Implement serial output functionality through the misc subsystem gt Test serial output using user space applications Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 290 473 Processes scheduling and interrupts Processes sched uling and Free Electrons interrupts o Free Electrons Copyright 2004 2014 Free Electrons Creative Commons BY SA 3 0 license Corrections suggestions contributions and translations are welcome Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 291 473 Processes scheduling and interrupts Processes and scheduling Free Electrons Embedded Linux kernel drivers and Android development consulting training and support
170. s Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 51 473 Linux sources structure 3 5 gt Kbuild gt Part of the kernel build system gt Kconfig gt Top level description file for configuration parameters gt kernel gt Linux kernel core very small gt lib gt Misc library routines zlib crc32 gt MAINTAINERS gt Maintainers of each kernel part Very useful gt Makefile gt Top Linux Makefile sets arch and version gt mm gt Memory management code small too Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 52 473 Linux sources structure 4 5 gt net gt Network support code not drivers gt README gt Overview and building instructions gt REPORTING BUGS gt Bug report instructions gt samples gt Sample code markers kprobes kobjects gt scripts gt Scripts for internal or external use gt security gt Security model implementations SELinux gt sound gt Sound support code and drivers tools gt Code for various user space tools mostly C v Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 53 473 Linux sources structure 5 5 gt usr gt Code to generate an initramfs cpio archive gt virt gt Virtualization supp
171. s documented in Documentation devicetree bindings pinctrl Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 191 473 bs pinctrl subsystem diagram SoC specific pinctrl driver drivers pinctrl pinctri c Request pin muxing drivers pinctrl core devicetree pinconf pinmu SoC dtsi file Board dts GPIO driver drivers gpio gpio c Provides list of pin groups Provides associations between pin groups and devices kernel irq drivers gpio 192 473 Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com Device Tree binding for consumer devices gt The devices that require certains pins to be muxed will use the pinctrl lt x gt and pinctrl names Device Tree properties gt The pinctrl 0 pinctrl 1i pinctrl lt x gt properties link to a pin configuration for a given state of the device gt The pinctrl names property associates a name to each state The name default is special and is automatically selected by a device driver without having to make an explicit pinctrl function call gt In most cases the following is sufficient i2c 11000 pinctrl 0 lt amp pmx_twsi0 gt pinctrl names default 3 gt See Documentation devicetree bindings pinctrl pinctrl bindings txt for details Free Electrons Em
172. s the same toolchain you could even put these settings in your bashrc file to make them permanent and visible from any terminal Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 87 473 Predefined configuration files Default configuration files available per board or per CPU family v gt They are stored in arch lt arch gt configs and are just minimal config files gt This is the most common way of configuring a kernel for embedded platforms v Run make help to find if one is available for your platform v To load a default configuration file just run make acme_defconfig gt This will overwrite your existing config file To create your own default configuration file gt make savedefconfig to create a minimal configuration file gt mv defconfig arch lt arch gt configs myown_defconfig v Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 88 473 Configuring the kernel gt After loading a default configuration file you can adjust the configuration to your needs with the normal xconfig gconfig or menuconfig interfaces gt You can also start the configuration from scratch without loading a default configuration file gt As the architecture is different from your host architecture gt Some options will be different from the native config
173. session by answering our on line survey http free electrons com doc training avignon kernel oct 2014 survey html Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 433 473 Last slide Thank you And may the Source be with you Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 434 473 Backup slides i Free Electrons Backup slides ao Free Electrons Copyright 2004 2014 Free Electrons Creative Commons BY SA 3 0 license Corrections suggestions contributions and translations are welcome Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 435 473 DMA DMA Int ti ntegration Peripheral Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 437 473 Constraints with a DMA gt A DMA deals with physical addresses so gt gt The Programming a DMA requires retrieving a physical address at some point virtual addresses are usually used The memory accessed by the DMA shall be physically contiguous CPU can access memory through a data cache Using the cache can be more efficient faster accesses to the cache than the bus But the DMA does not access to the CPU cache so one
174. ss gt modules dep Module dependencies gt modules symbols Tells which module a given symbol belongs to Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 82 473 Kernel cleanup targets gt Clean up generated files to force re compilation make clean gt Remove all generated files Needed when switching from one architecture to another Caution it also removes your config file make mrproper gt Also remove editor backup and patch reject files mainly to generate patches make distclean Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 83 473 Kernel Source Code Cross compiling the kernel Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 84 473 Cross compiling the kernel When you compile a Linux kernel for another CPU architecture gt Much faster than compiling natively when the target system is much slower than your GNU Linux workstation gt Much easier as development tools for your GNU Linux workstation are much easier to find gt To make the difference with a native compiler cross compiler executables are prefixed by the name of the target system architecture and sometimes library Examples mips linux gcc the prefix is mips linux arm 1linux gnu
175. sumer interface for device drivers i e users gt Regulator driver interface for regulator drivers gt Machine interface for board configuration gt sysfs interface for user space gt Merged in Linux 2 6 27 gt See Documentation power regulator in kernel sources gt See Liam Girdwood s presentation at ELC 2008 http free electrons com blog elc 2008 report girdwood Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 398 473 BSP Work for a New Board gt In case you just need to create a BSP for your board and your CPU already has full PM support you should just need to gt Create clock definitions and bind your devices to them gt Implement PM handlers suspend resume in the drivers for your board specific devices gt Implement runtime PM handlers in your drivers gt Implement board specific power management if needed mainly battery management gt Implement regulator framework hooks for your board if needed gt All other parts of the PM infrastructure should be already there suspend resume cpuidle cpu frequency and voltage scaling Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 399 473 Useful Resources gt Documentation power in the Linux kernel sources gt Will give you many useful details gt http wiki linaro org Working
176. supported boolean to tell the driver whether overcurrent is supported or not The code has been largely borrowed from ohci da8xx c and ohci s3c2410 c Signed off by Thomas Petazzoni lt thomas petazzoni free electrons com gt Signed off by Nicolas Ferre lt nicolas ferre atmel com gt gt Very difficult to find out the key changes and to get the global picture out of individual changes gt Fortunately there are some useful resources available gt http wiki kernelnewbies org LinuxChanges gt http lwn net gt http linuxfr org for French readers Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 410 473 The kernel development and contribution process Contributing to the Linux kernel Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 411 473 Solving Issues gt f you face an issue and it doesn t look specific to your work but rather to the tools you are using it is very likely that someone else already faced it gt Search the Internet for similar error reports gt You have great chances of finding a solution or workaround or at least an explanation for your issue gt Otherwise reporting the issue is up to you Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons
177. t consulting training and support http free electrons com 15 473 Practical lab Training Setup Prepare your lab environment gt Download the lab archive gt Enforce correct permissions Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 16 473 Linux Kernel Introduction Lj nux Ke rnel Free Electrons Introduction Bees Free Electrons Copyright 2004 2014 Free Electrons Creative Commons BY SA 3 0 license Corrections suggestions contributions and translations are welcome Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 17 473 Linux Kernel Introduction Linux features Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 18 473 History gt The Linux kernel is one component of a system which also requires libraries and applications to provide features to end users gt The Linux kernel was created as a hobby in 1991 by a Finnish student Linus Torvalds gt Linux quickly started to be used as the kernel for free software operating systems gt Linus Torvalds has been able to create a large and dynamic developer and user community around Linux gt Nowadays more than one thousand people contribute to each kernel release individuals or companies big and sma
178. t mapped by default in virtual memory gt The ioremap function satisfies this need include lt asm io h gt __iomem ioremap phys_addr size iounmap __iomem addr gt Caution check that ioremap doesn t return a NULL address Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 276 473 Qo ioremap Kernel 1 a a 1 1 a Pa 1 1 a 1 a 1 User Physical Memory Address Space Virtual Memory Address Space ioremap OxFFEBCO0 4096 OxCDEFA000 Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 277 473 Managed API Using request_mem_region and ioremap in device drivers is now deprecated You should use the below managed functions instead which simplify driver coding and error handling gt devm_ioremap gt devm_iounmap gt devm_request_and_ioremap gt Takes care of both the request and remapping operations Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 278 473 Accessing MMIO devices gt Directly reading from or writing to addresses returned by ioremap pointer dereferencing may not work on some architectures gt To do PCl style little endian accesses conversion being done automatically read bw1 addr write bw
179. t outb MOXA_MUST_ENTER_ENCHANCE baseio UART_LCR Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 273 473 Requesting O memory gt Functions equivalent to request_region and release_region but for I O memory gt struct resource request_mem_region start len xname gt release_mem_region start len Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 274 473 proc iomem example 00000000 0009ef Ff 0009f000 0009ffff 000a0000 000bffff 000c0000 000cffff 000f0000 000ffffF 00100000 3ffadfff 00100000 0030af ff 0030b000 003b4bff 3ffae000 3fffffff 40000000 400003ff 40001000 40001fff 40400000 407fffff 40800000 40bfffff a0000000 a0000f ff e8000000 efffffff Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com System RAM reserved Video RAM area Video ROM System ROM System RAM Kernel code Kernel data reserved 0000 00 1f 1 0000 02 01 0 PCI CardBus 03 PCI CardBus 03 pcmcia_socket0O PCI Bus 01 275 473 Mapping O memory in virtual memory gt Load store instructions work with virtual addresses gt To access I O memory drivers need to have a virtual address that the processor can handle because I O memory is no
180. t inode i struct file f Called when user space opens the device file struct inode is a structure that uniquely represents a file in the system be it a regular file a directory a symbolic link a character or block device gt struct file is a structure created every time a file is opened Several file structures can point to the same inode structure gt Contains information like the current position the opening mode etc gt Has a void private_data pointer that one can freely use gt A pointer to the file structure is passed to all other operations gt foo_release struct inode i struct file f gt Called when user space closes the file Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 210 473 read gt foo_read struct file f __user buf SZ off gt Called when user space uses the read system call on the device gt Must read data from the device write at most sz bytes in the user space buffer buf and update the current position in the file off f is a pointer to the same file structure that was passed in the open operation gt Must return the number of bytes read gt On UNIX read operations typically block when there isn t enough data to read from the device Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 211 473 write
181. t input_dev dev unsigned int type unsigned int code int value gt The event types are documented in Documentation input event codes txt gt An event is composed by one or several input data changes packet of input data changes such as the button state the relative or absolute position along an axis etc gt After submitting potentially multiple events the input core must be notified by calling void input_sync struct input_dev dev gt The input subsystem provides other wrappers such as input_report_key input_report_abs Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 241 473 Polled input subclass P gt The input subsystem provides a subclass supporting simple input devices that do not raise interrupts but have to be periodically scanned or polled to detect changes in their state gt A polled input device is described by a struct input_polled_dev structure struct input_polled_dev private xopen struct input_polled_dev dev close struct input_polled_dev dev poll struct input_polled_dev dev poll_interval msec poll_interval_max msec poll_interval_min msec struct input_dev input private struct delayed_work work Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 242 473 Polled inp
182. the bridge between the gdb debugging language and the JTAG interface of the target CPU gt See the very complete documentation http openocd sourceforge net documentation online docs gt For each board you ll need an OpenOCD configuration file ask your supplier Development PC JTAG Rates ARM board openocd Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 354 473 More Kernel Debugging Tips gt Enable CONFIG_KALLSYMS_ALL gt General Setup gt Configure standard kernel features gt To get oops messages with symbol names instead of raw addresses gt This obsoletes the ksymoops tool gt On ARM if your kernel doesn t boot or hangs without any message you can activate early debugging options CONFIG_DEBUG_LL and CONFIG_EARLYPRINTK and add earlyprintk to the kernel command line gt Techniques to locate the C instruction which caused an oops http j mp 180MRHx Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 355 473 Kernel Crash Analysis with kexec kdump Standard gt kexec system call makes it Kamel T sepa coy lebug kernel possible to call a new kernel Step 2 Keme to reserved RAM without rebooting and going debug kernel through the BIOS firmware gt Idea after a kernel panic make the kernel automatically execute a new clean
183. the graphic stack such as X Org Wayland or Android s InputManager Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 236 473 Input subsystem diagram User space application Q User space Kernel polled input polled input driver 1 driver 2 Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 237 473 Input subsystem overview gt Kernel option CONFIG_INPUT gt menuconfig INPUT gt tristate Generic input layer needed for keyboard mouse gt Implemented in drivers input gt input c input polldev c evbug c gt Implements a single character driver and defines the user kernel API gt include uapi linux input h gt Defines the set of operations a input driver must implement and helper functions for the drivers gt struct input_dev for the device driver part gt struct input_handler for the event handler part gt include linux input h Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 238 473 Input subsystem API 1 3 gt An input device is described by a very long struct input_dev structure an excerpt is struct input_dev const name evbit BITS_TO_LONGS EV_CNT keybit BITS_TO_LONGS KEY_CNT getkeycode struct in
184. the speed of a serial port setting video output format querying a device serial number gt cmd is a number identifying the operation to perform gt arg is the optional argument passed as third argument of the ioct1 system call Can be an integer an address etc gt The semantic of cmd and arg is driver specific Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 217 473 ioctl example kernel side static phantom_ioct1 struct file file cmd arg struct phm_reg r user argp _ user arg switch cmd case PHN_SET_REG if copy_from_user amp r argp sizeof r return EFAULT Do something break case PHN_GET_REG if copy_to_user argp kr sizeof r return EFAULT Do something break default return ENOTTY return 0 Selected excerpt from drivers misc phantom c Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 218 473 loctl Example Application Side main fd ret struct phm_reg reg fd open dev phantom assert fd gt 0 reg fieldi 42 reg field2 67 ret ioctl fd PHN_SET_REG amp reg assert ret 0 return 0 Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 219 473 Kernel frameworks for devi
185. trons com 406 473 New development model Using merge and bug fixing windows 2 weeks 6 10 weeks Linus development process 3 1 3 2 rc1 3 2 rc2 3 2 rc3 3 2 rc4 3 2 rc5 3 2 i H Bug fix I I I H versions 3 1 1 3 1 2 3 1 3 3 1 4 i 3 2 1 Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 407 473 New development model Details gt After the release of a 3 x version for example a two weeks merge window opens during which major additions are merged gt The merge window is closed by the release of test version 3 x 1 re1 gt The bug fixing period opens for 6 to 10 weeks gt At regular intervals during the bug fixing period 3 x 1 rcY test versions are released gt When considered sufficiently stable kernel 3 x 1 is released and the process starts again Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 408 473 More stability for the kernel source tree gt Free Electrons Issue bug and security fixes only released for most recent stable kernel versions Some people need to have a recent kernel but with long term support for security updates You could get long term support from a commercial embedded Linux provider You could reuse sources for the kernel used in Ubuntu Long Term Support releases 5 years of free security u
186. ture t size Needed buffer size in bytes xhandle Output DMA bus address gfp Standard GFP flags dma_free_coherent struct device dev size vo cpu_addr lt ld handle Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 443 473 Setting up streaming mappings gt Works on buffers already allocated by the driver include lt linux dmapool h gt t dma_map_single struct device device structure id input buffer to use A buffer size enum dma_data_direction Either DMA_BIDIRECTIONAL DMA_TO_DEVICE or DMA_FROM_DEVICE id dma_unmap_single struct device dev dma_addr_t handdle t size enum dma_data_direction dir Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 444 473 DMA Streaming Mapping Notes gt When the mapping is active only the device should access the buffer potential cache issues otherwise gt The CPU can access the buffer only after unmapping gt Another reason if required this API can create an intermediate bounce buffer used if the given buffer is not usable for DMA gt The Linux API also supports scatter gather DMA streaming mappings Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 4
187. udev struct tasklet_struct tl struct net_device netdev EREA Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 230 473 Link Between Structures 1 4 gt The framework typically contains a struct device pointer that the driver must point to the corresponding struct device gt It s the relation between the logical device for example a network interface and the physical device for example the USB network adapter gt The device structure also contains a void pointer that the driver can freely use gt It s often use to link back the device to the higher level structure from the framework gt It allows for example from the struct platform_device structure to find the structure describing the logical device Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 231 473 Link Between Structures 2 4 static int serial_imx_probe struct platform_device pdev t struct imx_port sport setup the link between uart_port and the struct device inside the platform_device sport gt port dev amp pdev gt dev struct device setup the link between the struct device inside the platform device to the imx_port structure platform_set_drvdata pdev amp sport gt port uart_add_one_port amp imx_reg amp sport gt port
188. uling interrupts IPI2 0 0 Function call interrupts IPI3 231 173 Single function call interrupts IPI4 0 0 CPU stop interrupts LOC 196407 136995 Local timer interrupts Err 0 Note interrupt numbers shown on the left most column are virtual numbers when the Device Tree is used The real physical interrupt numbers are either shown as an additional column or can be seen in sys kernel debug irq_domain_mapping Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 312 473 Interrupt handler prototype gt foo_interrupt irq xdev_id gt irq the IRQ number gt dev_id the opaque pointer that was passed to devm_request_irq gt Return value gt IRQ_HANDLED recognized and handled interrupt gt IRQ_NONE not on a device managed by the module Useful to share interrupt channels and or report spurious interrupts to the kernel Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 313 473 Typical interrupt handler s job gt Acknowledge the interrupt to the device otherwise no more interrupts will be generated or the interrupt will keep firing over and over again gt Read write data from to the device gt Wake up any waiting process waiting for the completion of an operation typically using wait queues wake_up_interruptible amp module_queue Free Electr
189. ulting training and support http free electrons com 121 473 Practical lab Writing Modules gt Create compile and load your first module gt Add module parameters gt Access kernel internals from your module Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 122 473 Useful general purpose kernel APIs Useful genera p u rpose Free Electrons kernel APIs Emedaea Linux Free Electrons Copyright 2004 2014 Free Electrons Creative Commons BY SA 3 0 license Corrections suggestions contributions and translations are welcome Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 123 473 Memory string utilities gt In linux string h gt Memory related memset memcpy memmove memscan memcmp memchr gt String related strcpy strcat strcemp strchr strrchr strlen and variants gt Allocate and copy a string kstrdup kstrndup gt Allocate and copy a memory area kmemdup gt In linux kernel h gt String to int conversion simple_strtoul simple_strtol simple_strtoull simple_strtoll1 gt Other string functions sprintf sscanf Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 124 473 Linked lists gt
190. upport http free electrons com 364 473 Studying the Crystalfontz CFA 10036 platform gt Crystalfontz CFA 10036 Uses the Freescale iMX28 SoC from the MXS family 128MB of RAM gt 1 serial port 1 LED 1 12C bus equipped with an OLED display 1 SD Card slot v v v v Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 365 473 Crystalfontz CFA 10036 Device Tree header gt Mandatory Device Tree language definition dts v1i gt Include the dtsi file describing the SoC include im28 dtsi gt Start the root of the tree Vat gt A human readable string to describe the machine model Crystalfontz CFA 10036 Board gt A list of compatible strings from the most specific one to the most general one Can be used by kernel code to do a SoC or board specific check compatible crystalfontz cfa10036 fsl imx28 Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 366 473 Crystalfontz CFA 10036 Device Tree chosen memory gt Definition of the default kernel command line Some additional operating system specific entries can be added in chosen chosen bootargs console ttyS0 115200 earlyprintk Ig gt Definition of the size and location of the RAM memory device_type memory reg lt 0x40000000 0x8000000 gt 128 MB
191. uration processor and architecture specific options specific drivers etc gt Many options will be identical filesystems network protocols architecture independent drivers etc gt Make sure you have the support for the right CPU the right board and the right device drivers Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 89 473 Device Tree gt Many embedded architectures have a lot of non discoverable hardware Depending on the architecture such hardware is either described using C code directly within the kernel or using a special hardware description language in a Device Tree ARM PowerPC OpenRISC ARC Microblaze are examples of architectures using the Device Tree A Device Tree Source written by kernel developers is compiled into a binary Device Tree Blob passed at boot time to the kernel gt There is one different Device Tree for each board platform supported by the kernel available in arch arm boot dts lt board gt dtb The bootloader must load both the kernel image and the Device Tree Blob in memory before starting the kernel Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 90 473 Building and installing the kernel gt Run make gt Copy the final kernel image to the target storage gt can be ulmage zImage vmlinux bzImage in ar
192. urces Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 265 473 lloc Allocat Oo oc Allocator gt The vmalloc allocator can be used to obtain virtually contiguous memory zones but not physically contiguous The requested memory size is rounded up to the next page gt The allocated area is in the kernel space part of the address space but outside of the identically mapped area gt Allocations of fairly large areas is possible almost as big as total available memory see http j mp YIGq6W again since physical memory fragmentation is not an issue but areas cannot be used for DMA as DMA usually requires physically contiguous buffers gt API in include linux vmalloc h gt vmalloc size gt Returns a virtual address gt vfree xaddr Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 266 473 Kernel memory debugging gt Kmemcheck gt Dynamic checker for access to uninitialized memory gt Only available on x86 so far Linux 3 10 rc5 status but will help to improve architecture independent code anyway gt See Documentation kmemcheck txt for details gt Kmemleak gt Dynamic checker for memory leaks gt This feature is available for all architectures gt See Documentation kmemleak txt for details Both have a significant overhead
193. urn on CONFIG_FRAME_POINTER to aid in producing more reliable stack backtraces in gdb gt You must include a kgdb I O driver One of them is kgdb over serial console kgdboc kgdb over console enabled by CONFIG_KGDB_SERIAL_CONSOLE gt Configure kgdboc at boot time by passing to the kernel gt kgdboc lt tty device gt lt bauds gt gt For example kgdboc ttyS0 115200 Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 352 473 Using kgdb 2 2 gt Then also pass kgdbwait to the kernel it makes kgdb wait for a debugger connection gt Boot your kernel and when the console is initialized interrupt the kernel with Alt SysRq g gt On your workstation start gdb as follows gt gdb vmlinux gt gdb set remotebaud 115200 gt gdb target remote dev ttySO gt Once connected you can debug a kernel the way you would debug an application program Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 353 473 Debugging with a JTAG Interface gt Two types of JTAG dongles gt Those offering a gdb compatible interface over a serial port or an Ethernet connection gdb can directly connect to them gt Those not offering a gdb compatible interface are generally supported by OpenOCD Open On Chip Debugger http openocd sourceforge net gt OpenOCD is
194. use gt Very easy to find the declaration implementation or usage of symbols gt Supports C and C gt Supports huge code projects such as the Linux kernel 431 MB of source code in version 3 0 gt Takes a little time and patience to setup configuration indexing web server configuration gt You don t need to set up LXR by yourself Use our http lxr free electrons com server gt http sourceforge net projects lxr Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 58 473 Linux Cross Reference Free Electrons Embedded Linux Experts Source Navigation Diff Markup Identifier Search Freetext Search Version 2 6 32 2 6 33 2 6 24 2 6 35 2 6 36 2 6 37 2 6 38 2 6 39 3 0 3 1 3 2 3 3 3 43 5 3 6 3 7 3 8 3 9 3 10 3 113 12 Architecture x86 arm avr32 blackfin m68k M68knommu microblaze mips powerpc sh Linux kernel user c The user cache C Copyright 1991 2000 Linus Torvalds We have a per user structure to keep track of how many processes files etc the user has claimed in order to be able to have per user limits for system resources Beerousune 11 include lt linux init h gt 12 include lt linux sched h gt 143 include lt linux slab h gt 14 include lt linux bitops h gt 15 include lt Linux key h gt 46 include lt Linux interrupt h gt 47 include lt Linux export h gt 18 include lt 1
195. ut subsystem API gt Allocating freeing the struct input_polled_dev structure is done using gt input_allocate_polled_device gt input_free_polled_device gt Among the handlers of the struct input_polled_dev only the poll method is mandatory this function polls the device and posts input events gt The fields id name phys bits of struct input must be initialized too gt If none of the poll_interval fields are filled then the default poll interval is 500ms gt The device registration unregistration is done with gt input_register_polled_device struct input_polled_ dev dev gt input_unregister_polled_device struct input_ polled_dev dev Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 243 473 evdev user space interface gt The main user space interface to input devices is the event interface gt Each input device is represented as a dev input event lt X gt character device gt A user space application can use blocking and non blocking reads but also select to get notified of events after opening this device gt Each read will return struct input_event structures of the following format struct input_event struct timeval time type code value gt A very useful application for input device testing is evtest from http cgit freedesktop org evtest Free Electrons Embedded Linux kernel drivers and
196. ux kernel drivers and Android development consulting training and support http free electrons com 97 473 Kernel log When a new module is loaded related information is available in the kernel log gt The kernel keeps its messages in a circular buffer so that it doesn t consume more memory with many messages gt Kernel log messages are available through the dmesg command diagnostic message gt Kernel log messages are also displayed in the system console console messages can be filtered by level using the loglevel kernel parameter or completely disabled with the quiet parameter gt Note that you can write to the kernel log from user space too echo lt n gt Debug info gt dev kmsg Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 98 473 Module utilities 1 gt modinfo lt module_name gt modinfo lt module_path gt ko Gets information about a module parameters license description and dependencies Very useful before deciding to load a module or not gt sudo insmod lt module_path gt ko Tries to load the given module The full path to the module object file must be given Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 99 473 Understanding module loading issues gt When loading a module fails insmod often doesn t give you enough det
197. vers and Android development consulting training and support http free electrons com 403 473 Until 2 6 2 Stable 2 4 0 2 4 1 2 4 2 2 4 3 2 4 4 2 4 5 2 4 6 2 4 7 2 4 8 2 5 0 2 5 1 2 5 2 2 5 3 2 6 0 2 6 1 Development Stable Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 404 473 Changes since Linux 2 6 gt Since 2 6 0 kernel developers have been able to introduce lots of new features one by one on a steady pace without having to make disruptive changes to existing subsystems gt Since then there has been no need to create a new development branch massively breaking compatibility with the stable branch gt Thanks to this more features are released to users at a faster pace Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 405 473 3 x stable branch gt From 2003 to 2011 the official kernel versions were named 265 X gt Linux 3 0 was released in July 2011 gt This is only a change to the numbering scheme gt Official kernel versions are now named 3 x 3 0 3 1 3 2 etc gt Stabilized versions are named 3 x y 3 0 2 3 4 3 etc gt It effectively only removes a digit compared to the previous numbering scheme Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free elec
198. x kernel drivers and Android development consulting training and support http free electrons com 389 473 Triggering Suspend gt Whatever the power management implementation CPU specific struct suspend_ops functions are called by the enter_state function gt enter_state also takes care of executing the suspend and resume functions for your devices gt The execution of this function can be triggered from user space To suspend to RAM gt echo mem gt sys power state gt Can also use the s2ram program from http suspend sourceforge net gt Read kernel power suspend c Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 390 473 Runtime Power Management gt According to the kernel configuration interface Enable functionality allowing I O devices to be put into energy saving low power states at run time or autosuspended after a specified period of inactivity and woken up in response to a hardware generated wake up event or a driver s request gt New hooks must be added to the drivers runtime_suspend runtime_resume runtime_idle gt API and details on Documentation power runtime_pm txt gt See also Kevin Hilman s presentation at ELC Europe 2010 http elinux org images c cd ELC 2010 khilman Runtime PM odp Free Electrons Embedded Linux kernel drivers and Android development consulting training and sup
199. xclude the feature kd int options to specify integer values hex options to specify hexadecimal values string options to specify string values v v Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 66 473 Kernel option dependencies gt There are dependencies between kernel options gt For example enabling a network driver requires the network stack to be enabled gt Two types of dependencies gt depends on dependencies In this case option A that depends on option B is not visible until option B is enabled gt select dependencies In this case with option A depending on option B when option A is enabled option B is automatically enabled gt make xconfig allows to see all options even those that cannot be selected because of missing dependencies In this case they are displayed in gray Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 67 473 k fi make xconfig make xconfig gt The most common graphical interface to configure the kernel gt Make sure you read help gt introduction useful options gt File browser easier to load configuration files gt Search interface to look for parameters gt Required Debian Ubuntu packages libgt4 dev g libqt3 mt dev for older kernel releases Free Electrons Embedded Linux kernel d
200. y gt Mapping must be requested explicitly gt Limited addresses ranges reserved for this usage gt See http lwn net Articles 75174 for useful explanations Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 250 473 Accessing even more physical memory gt If your 32 bit platform hosts more than 4GB they just cannot be mapped gt PAE Physical Address Expansion may be supported by your architecture gt Adds some address extension bits used to index memory areas gt Allows accessing up to 64 GB of physical memory on x86 gt Note that each user space process is still limited to a 3 GB memory space Free Electrons Embedded Linux kernel drivers and Android development consulting training and support http free electrons com 251 473 Notes on user space memory gt New user space memory is allocated either from the already allocated process memory or using the mmap system call gt Note that memory allocated may not be physically allocated gt Kernel uses demand fault paging to allocate the physical page the physical page is allocated when access to the virtual address generates a page fault gt or may have been swapped out which also induces a page fault gt User space memory allocation is allowed to over commit memory more than available physical memory can lead to out of memory gt OOM killer kicks in and selects a p
Download Pdf Manuals
Related Search
Related Contents
Samsung Refrigerator Top Freezer User Manual Mototrbo DGP8050/DGP5050 Bedienungsanleitung Blu-ray Player Manual de instrucciones User manual WOW! iQ 310 MultiSync V321 MultiSync V421 MultiSync V461 MICR Basics Handbook Bedienungsanleitung Sanremo Roma Copyright © All rights reserved.
Failed to retrieve file