Home

Linux Kernel and Driver Development Training Linux Kernel and

image

Contents

1. Warning Error management removed uart_register_driver amp atmel_uart platform_driver_register katmel_serial_driver return 0 static void __exit atmel_serial_exit void platform_driver_unregister amp atmel_serial_driver uart_unregister_driver amp atmel_uart module_init atmel_serial_init module_exit atmel_serial_exit gt Can be allocated statically or dynamically gt Usually registered at probe time and unregistered at remove time gt Most important fields gt vvvvyvyy iotype type of I O access usually UPIO_MEM for memory mapped devices mapbase physical address of the registers irq the IRQ channel number membase the virtual address of the registers uartclk the clock rate ops pointer to the operations dev pointer to the device platform_device or other Q static int __devinit atmel_serial_probe struct platform_device pdev struct atmel_uart_port port port amp atmel_ports pdev gt id port gt backup_imr 0 atmel_init_port port pdev uart_add_one_port amp atmel_uart amp port gt uart platform_set_drvdata pdev port return 0 static int __devexit atmel_serial_remove struct platform_device pdev struct uart_port port platform_get_drvdata pdev platform_set_drvdata pdev NULL uart_remove_one_port amp atmel_uart port return 0 static void __devinit atmel_init_port struct atmel_uart_port
2. The thread is elected by the scheduler gt TASK_RUNNING TASK_RUNNING Ready but not running Actually running The thread is preempted by the scheduler to run a higher priority task TASK_INTERRUPTIBLE TASK_UNINTERRUPTIBLE or TASK_KILLABLE Waiting The event occurs or the process receives a signal Thread becomes runnable again Decides to sleep on a wait queue for a specific event 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 Sleeping Read Device File return Other Processes are scheduled Wake up Ask for data Data Ready Notification Sleeping is needed when a process user space or kernel space is waiting for data LE 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 wait_queue_head_t queue init_waitqueue_head amp queue LE gt Several ways to make a kernel process sleep gt void wait_event queue condition gt Sleeps until the task is woken up and the given C expression is true Caution can t be
3. Other fields F gt Spinlock taken released with protection against interrupts static unsigned int ulite_tx_empty struct uart_port port unsigned long flags spin_lock_irqsave amp port gt lock flags Do something spin_unlock_irgrestore amp port gt lock flags 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 gt Holding multiple locks is risky Os 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 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 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 operat
4. 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 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 gt Whatever the power management implementation CPU specific 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 userspace 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 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 Ne
5. 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 As in the Free Software and Open Source community cooperation during practical labs is valuable in this training session gt f 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 your 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 gt This memento sheet gives command examples for the most typical needs looking for files extracting a tar archive gt It saves us 1 day of UNIX Linux command line training gt Our best tip in the comm
6. gt rtl8150 network driver rt18150 has a reference to net_device struct rt18150 unsigned long flags struct usb_device udev struct tasklet_struct tl struct net_device netdev Lose F 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 platform_device structure to find the structure describing the logical device F Q static int serial_imx_probe struct platform_ device pdev 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 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 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 uart_remove_one_port amp imx_reg
7. amp sport gt port ey static int rt18150_probe struct usb_interface intf const struct usb_device_id id rt18150_t dev struct net_device netdev netdev alloc_etherdev sizeof rt18150_t dev netdev_priv netdev usb_set_intfdata intf dev SET_NETDEV_DEV netdev amp intf gt dev Essel F static void rt18150_disconnect struct usb_interface intf rt18150_t dev usb_get_intfdata intf LE gt SPlis called non dynamic as it doesn t support runtime enumeration of devices the system needs to know which devices are on which SPI bus and at which location gt The SPI infrastructure in the kernel is in drivers spi gt drivers spi spi c is the core which implements the struct bus_type for spi gt It allows registration of adapter drivers using spi_register_master and registration of device drivers using spi_register_driver drivers spi contains many adapter drivers for various platforms Atmel OMAP Xilinx Samsung etc gt Most of them are platform_drivers or of_platform_drivers one pci_driver one amba_driver one partport_driver drivers spi spidev c provides an infrastructure to access SPI bus from userspace SPI device drivers are present all over the kernel tree Kernel Frameworks SPI Device Drivers Os static struct resource spi0_resources fo start AT91SAM9260_BASE_SPIO end AT91SAM9260_BASE_SPIO SZ_16K 1 flags IORE
8. electrons com mailman listinfo newsletter gt News and discussions LinkedIn http linkedin com groups Free Electrons 4501089 gt Quick news Twitter http twitter com free_electrons LE Generic course information Gr gory Cl ment Michael Opdenacker Maxime Ripard S bastien Jan Thomas Petazzoni Free Electrons Copyright 2004 2013 Free Electrons Creative Commons BY SA 3 0 license Corrections suggestions contributions and translations are welcome Free Electrons Embedded Linux Developers Calao Systems USB A9263 Supported in mainstream Linux since version 2 6 27 gt AT91SAM9263 ARM CPU gt 64 MB RAM 256 MB flash gt 2 USB 2 0 host 1 USB device gt 100 Mbit Ethernet port gt Powered by USB gt Serial and JTAG through this USB port gt Multiple extension boards gt Approximately 160 EUR V A T not included During the lectures gt Don t hesitate to ask questions Other people in the audience may have similar questions too This helps the trainer to detect any explanation that wasn t clear or detailed enough Don t hesitate to share your experience for example to compare Linux Android with other operating systems used in your company Your point of view is most valuable because it can be similar to your colleagues and different from the trainer s Your participation can make our session more interactive and make the topics easier to learn
9. Q dts v1 memreserve 0x1c000000 0x04000000 include tegra20 dtsi 1 model NVIDIA Tegra2 Harmony evaluation board compatible nvidia harmony nvidia tegra20 chosen bootargs vmalloc 192M video tegrafb console ttyS0 115200n8 J memory 0 reg lt 0x00000000 0x40000000 gt J i2c 7000c000 clock frequency lt 400000 gt codec wm8903 1a compatible wlf wm8903 reg lt Oxla gt interrupts lt 347 gt gpio controller gpio cells lt 2 gt 0x8000 Not configured gpio cfg lt 0x8000 0x8000 O 0x8000 0x8000 gt F 3 F gt The device tree source dts is compiled into a device tree blob dtb using a device tree compiler dtc gt The dtb is an efficient binary data structure gt The dtb is either appended to the kernel image or better passed by the bootloader to the kernel gt At runtime the kernel parses the device tree to find out gt which devices are present gt what drivers are needed gt which parameters should be used to initialize the devices gt On ARM device tree support is only beginning gt Porting Linux to a new board is easy when Linux already supports the evaluation kit development board for your CPU gt Most work has already been done and it is just a matter of customizing devices instantiated on your boards and their settings gt Therefore look for how the development board is supported or at least for a similar board
10. 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 LE static int rt18150_probe struct usb_interface intf const struct usb_device_id id rt18150_t dev struct net_device netdev netdev alloc_etherdev sizeof rt18150_t Esaad dev netdev_priv netdev tasklet_init amp dev gt tl rx_fixup unsigned long dev spin_lock_init amp dev gt rx_pool_lock Css netdev gt netdev_ops amp rt18150_netdev_ops alloc_all_urbs dev usb_set_intfdata intf dev SET_NETDEV_DEV netdev amp intf gt dev register_netdev netdev return 0 Char Driver pa Char Driver 12C Device Driver 12C Thermometer 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 userspace 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 conn
11. close fd LE 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 since kernel 2 6 32 gt udev daemon solution used by desktop and server Linux systems gt mdev program a lighter solution than udev Character drivers gt Except for storage device drivers most drivers for devices with input and output flows are implemented as character drivers gt So most drivers you will face will be character drivers LE gt User space needs gt The name of a device file in dev to interact with the device driver through regular file operations open read write close gt The kernel needs gt To know which driver is in charge of device files with a given major minor number pair gt For a given driver to have handlers file operations to execute when user space opens reads writes or closes the device file copy_to_user copy_from_user LE gt Four major steps gt Implement operations corresponding to the system calls an application can apply to a file file operations gt Define a file_operations structure
12. gt Enumerate the devices view their interconnections link the devices to their buses and drivers etc gt Understanding the device model is necessary to understand how device drivers fit into the Linux kernel architecture gt The gt gt It is gt gt td v first component of the device model is the bus driver One bus driver for each type of bus USB PCI SPI MMC 12C etc responsible for Registering the bus type struct bus_type Allowing the registration of adapter drivers USB controllers I2C adapters etc able of detecting 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 structure typically xxx_driver and xxx_device gt Core infrastructure bus driver gt drivers usb core gt The 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 gt Toillustrate how drivers are implemented to
13. gt In your new branch implement your changes gt 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 check_patch pl strict file lt file gt gt If needed fix indenting rule violations gt indent linux lt file gt Qo 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 smtppass xxx 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
14. gt Ina later slide we will see how to use git config to set the SMTP server port user and password 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 hjemli net git cgit 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 In addition to the official Linus Torvalds tree you might want to use other development or experimental trees gt
15. gt ignore_status_mask 0 if termios gt c_iflag amp IGNPAR port gt ignore_status_mask ATMEL_US_FRAME ATMEL_US_PARE if termios gt c_iflag amp IGNBRK port gt ignore_status_mask ATMEL_US_RXBRK if termios gt c_iflag amp IGNPAR port gt ignore_status_mask ATMEL_US_OVRE The serial_core maintains a timeout that corresponds to the duration it takes to send the full transmit FIFO This timeout has to be updated uart_update_timeout port termios gt c_cflag baud Finally apply the mode and baud rate modifications Interrupts transmission and reception are disabled when the modifications are made Save and disable interrupts imr UART_GET_IMR port UART_PUT_IDR port 1 disable receiver and transmitter UART_PUT_CR port ATMEL_US_TXDIS ATMEL_US_RXDIS set the parity stop bits and data size UART_PUT_MR port mode set the baud rate UART_PUT_BRGR port quot UART_PUT_CR port ATMEL_US_RSTSTA ATMEL_US_RSTRX UART_PUT_CR port ATMEL_US_TXEN ATMEL_US_RXEN restore interrupts UART_PUT_IER port imr CTS flow control and modem status interrupts if UART_ENABLE_MS port termios gt c_cflag port gt ops gt enable_ms port LE gt To allows early boot messages to be printed the kernel provides a separate but related facility console gt This console can be enabled using the console kernel argument gt
16. mmap void start size_t length int prot int flags int fd off_t 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 gt Character driver implement an mmap file operation and add it to the driver file operations int 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 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 int remap_pfn_range struct vm_area_struct unsigned long virt_addr unsigned long pfn unsigned long size pgprot_t VMA struct Starting user virtual address pfn of the starting physical address Mapping size Page permissions LE static int 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
17. return 0 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 mem gt Examples b byte h half w word gt devmem2 0x000c0004 h reading gt devmem2 0x000c0008 w Oxffffffff writing gt devmem is now available in BusyBox making it even easier to use 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 DMA gt 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 Bu
18. static int __init hello_init void pr_alert Good morrow pr_alert to this fair assembly n return 0 static void __exit hello_exit void pr_alert Alas poor world what treasure pr_alert hast thou lost n module_init hello_init module_exit hello_exit MODULE_LICENSE GPL MODULE_DESCRIPTION Greeting module MODULE_AUTHOR William Shakespeare Oo gt __init gt removed after initialization static kernel or module gt __exit gt discarded when module compiled statically into the kernel gt Example available on http free electrons com doc c hello c 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 v v v From a kernel module only a limited number of kernel functions can be called Functions and variables have to be explicitly exported by the kernel to be visible from a kernel module Two macros are
19. 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 gt unsigned long get_zeroed_page int flags gt Returns the virtual address of a free page initialized to zero gt unsigned long __get_free_page int flags gt Same but doesn t initialize the contents gt unsigned long __get_free_pages int flags unsigned int 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 gt void free_page unsigned long addr gt Frees one page gt void free_pages unsigned long addr unsigned int order gt Frees multiple pages Need to use the same order as in allocation LE 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 interr
20. CPUs that reorder instructions and SMP gt See Documentation memory barriers txt for details 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 tile powerpc unicore32 s390 CONFIG_STRICT_DEVMEM option to restrict dev mem non RAM addresses for security reasons Linux 3 6 status gt Make a remote connection to your board through ssh gt Access to the system console through the network gt Reserve the I O memory addresses used by the serial port gt Read device registers and write data to them to send characters on the serial port Device Files gt One of the kernel important role is to allow applications to access hardware devices gt In the Linux kernel most devices are presented to userspace applications through two different abstractions gt Character device gt Block device gt Internally the kernel identifies each device by a triplet of information gt Type character or block gt Major typically the category of device gt Minor typically the identifier of the device gt Block devices gt device composed of fixed sized blocks that can be read and written to store data gt Used for hard disks USB keys SD car
21. F fb_release fb_check_var fb_set_par fb_setcolreg xxxfb_setcolreg fb_blank xxxfb_blank fb_pan_display xxxfb_pan_display fb_ioctl fb_mmap xxxfb_mmap fb_open xxxfb_open fb_read xxxfb_read fb_write xxxfb_write xxxfb_release xxxfb_check_var xxxfb_set_par fb_fillrect xxxfb_fillrect fb_copyarea xxxfb_copyarea fb_imageblit xxxfb_imageblit fb_cursor xxxfb_cursor fb_rotate xxxfb_rotate fb_sync xxxfb_sync xxxfb_ioctl Needed Needed Needed Optional LE gt In the probe function registration of the framebuffer device and operations static int __devinit xxxfb_probe struct pci_dev dev const struct pci_device_id ent struct fb_info info info framebuffer_alloc sizeof struct xxx_par device 451 info gt fbops amp xxxfb_ops if register_framebuffer info gt 0 return EINVAL gt register_framebuffer will create the character device that can be used by userspace applications with the generic framebuffer API gt The 2 6 kernel included a significant new feature a unified device model gt Instead of having different ad hoc mechanisms in the various subsystems the device model unifies the description of the devices and their topology gt Minimization of code duplication gt Common facilities reference counting event notification power management etc
22. IrDA MTD drivers in userspace kernel debugging etc gt Probably the most wide ranging and complete Linux device driver book I ve read Alan Cox Useful Reading 2 gt Writing Linux Device drivers September 2009 gt http wuw coopj com F Writing gt Self published by Jerry Cooperstein Linux Device Drivers gt Available like any other book Amazon and others gr 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 6 36 Free Electrons Kernel drivers and embedded Linux development consulting training and support http free electrons com 462 496 gt Linux Device Drivers 3rd edition Feb 2005 gt http www oreilly com catalog linuxdrive3 By Jonathan Corbet Alessandro Rubini Greg Kroah Hartman O Reilly Freely available on line Great companion to the printed book for easy electronic searches http lwn net Kernel LDD3 1 PDF file per chapter http free electrons com community kernel 1dd3 single PDF file Getting outdated but still useful for Linux device driver writers JONATHAN CORBET ALESSANDRO RUBINI amp GREG KROAH HARTMAN O REILLY _ Linux Kernel gt Linux Kernel Development 3rd Edition Development Jun 2010 gt Robert Love Novell Press gt http free electrons c
23. Kernel Lock gone now gt Allows to extend the driver capabilities beyond the limited read write API gt For example changing 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 ioctl system call Can be an integer an address etc gt The semantic of cmd and arg is driver specific Q static long phantom_ioctl struct file file unsigned int cmd unsigned long arg struct phm_reg r void __user argp void __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 amp r sizeof r return EFAULT Do something break default return ENOTTY F return 0 Selected excerpt from drivers misc phantom c int main void int 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 gt Defining a file_operations structure include lt linux fs h gt static struct file_operations acme_fops owner THIS_MODULE read acme_read write acme_write gt You just need to supply the functions you implemented Defaults for other functions such as open release are f
24. 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 Free Electrons Kernel drivers and embedded Linux development consulting training and support http free electrons com 344 496 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 F And the list of devices is added to the system during board initialization static void __init mxiads_init void Cral platform_add_devices devices ARRAY_SIZE devices MACHINE_START MX1ADS Freescale MX1ADS Lisce init_machine mxiads_init MACHINE_END LE gt Each device managed by a particular driver typically uses different hardware resources addresses for the I O registers DMA channels IRQ lines etc gt Such information can be represented using the struct resource and an array of struct resource is associated to a platform_device gt Allows a driver to be instantiated for multiple devices functioning similarly but with different addresses IRQs etc static struct resource imx_uarti_resource
25. 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 Or contact the mailing list for the subsystem you re dealing with linux usb devel linux mtd Don t ask the maintainer directly Most mailing lists come with a FAQ page Make sure you read it before contacting the mailing list Useful IRC resources are available too for example on http kernelnewbies org Refrain from contacting the Linux Kernel mailing list unless you re an experienced developer and need advice 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 If 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 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 Com
26. 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 is an engineering company not a training company gt Training is just one of our activities gt Whether they are directly employed by Free Electrons or whether they are external developers that we know very well all our trainers are engineers first with extensive on the job experience gt Free Electrons engineers spend most of their time on technical projects and share this experience through training sessions and by keeping our training materials up to date gt All our trainers also spend a lot of time contributing to the user and developer community by contributing to projects such as the Linux kernel Buildroot and Barebox and or by sharing technical information through blog posts training materials and talks at international conferences gt Created in 2004 gt Locations Orange Toulouse Saint Etienne Lyon France gt Serving customers all around the world See http free electrons com company customers gt Head count 7 Only Free Software enthusiasts gt Focus Embedded Linux Linux kernel Android Free Software Open Source for embedde
27. associating function pointers to their implementation in your driver gt Reserve a set of major and minors for your driver gt Tell the kernel to associate the reserved major and minor to your file operations gt This is a very common design scheme in the Linux kernel gt A common kernel infrastructure defines a set of operations to be implemented by a driver and functions to register your driver gt Your driver only needs to implement this set of well defined operations gt Before registering character devices you have to define file_operations called fops for the device files gt The file_operations structure is generic to all files handled by the Linux kernel It contains many operations that aren t needed for character drivers LE gt Here are the most important operations for a character driver All of them are optional struct file_operations ssize_t read struct file char __user size_t loff_t ssize_t write struct file const char __user size_t loff_t long unlocked_ioctl struct file unsigned int unsigned long int xmmap struct file struct vm_area_struct int open struct inode struct file int release struct inode struct file gt int foo_open struct inode i struct file f gt Called when user space opens the device file gt inode is a structure that uniquely represent a file in the system be it a regular file a directory a
28. atmel_port struct platform_ device pdev struct uart_port port amp atmelt_port gt uart struct atmel_uart_data xdata pdev gt dev platform_ data port gt iotype UPIO_MEM port gt flags UPF_BOOT_AUTOCONF port gt ops amp atmel_pops port gt fifosize 1 port gt line pdev gt id port gt dev amp pdev gt dev port gt mapbase pdev gt resource 0 start port gt irq pdev gt resourcel i start tasklet_init amp atmel_port gt tasklet atmel_tasklet_func unsigned long port if data gt regs Already mapped by setup code port gt membase data gt regs else port gt flags UPF_IOREMAP port gt membase NULL for console the clock could already be configured if atmel_port gt clk atmel_port gt clk clk_get amp pdev gt dev usart clk_enable atmel_port gt c1k port gt uartclk clk_get_rate atmel_port gt clk clk_disable atmel_port gt clk only enable clock when USART is in use gt Important operations gt tx_empty tells whether the transmission FIFO is empty or not set_mctr1 and get_mctr1 allow to set and get the modem control parameters RTS DTR LOOP etc start_tx and stop_tx to start and stop the transmission gt stop_rx to stop the reception gt startup and shutdown called when the port is opened closed request_port and release_port request release 1 0 or memory regions set_te
29. bit processors with or without MMU and gcc support gt 32 bit architectures arch subdirectories Examples arm avr32 blackfin m68k microblaze mips score sparc um gt 64 bit architectures Examples alpha arm64 ia64 sparc64 tile gt 32 64 bit architectures Examples powerpc x86 sh gt Find details in kernel sources arch lt arch gt Kconfig arch lt arch gt README or Documentation lt arch gt gt The main interface between the kernel and userspace 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 userspace applications usually never make a system call directly but rather use the corresponding C library function gt Linux makes system and kernel information available in user space through virtual filesystems gt Virtual filesystems allow applications to see directories and files that do not exist on any real storage they are created on the fly by the kernel gt The two most important virtual filesystems are gt proc usually mounted on proc Operating system related information processes memory management parameters gt s
30. but doesn t scale well Saves a few hundreds of KB in small systems depends on CONFIG_EXPERT gt SLUB the new default allocator since 2 6 23 simpler than SLAB scaling much better in particular for huge systems and creating less fragmentation e Choose SLAB allocator NEW SLAB SLAB fe SLUB Unqueued Allocator NEW SLUB oSLOB Simple Allocator SLOB 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 next power of two size 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 gt Per allocation 4 MB gt Total allocations 128 MB gt Should be used as the primary allocator unless there is a strong reason to use another one gt include lt linux slab h gt gt void kmalloc size_t size int flags gt Allocate size bytes and return a pointer to the area virtual address gt size number of bytes to allocate gt flags same flags as the page allocator gt void kfree const void objp gt Free an alloc
31. by hand it s strongly recommended to run make oldconfig afterwards make allnoconfig gt Only sets strongly recommended settings to y v Sets all other settings to n v Very useful in embedded systems to select only the minimum required set of features and drivers v Much more convenient than unselecting hundreds of features one by one A frequent problem gt After changing several kernel configuration settings your kernel no longer works gt If 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 allnoconfig keep this config old backup copy gt The set of configuration options is architecture dependent 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 Gs gt General setup gt Local version append to kernel release allows to concatenate an arbitr
32. 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 LE 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 unsigned long copy_to_user void __user to const void from unsigned long n gt unsigned long copy_from_user void to const void __user from unsigned long n gt The return value must be checked Zero on success non zero on failure If non zero the convention is to return EFAULT Gs OxFFFFFFFF void to void from 0xC0000000 copy_from_user copy_to_user void __user from void __user to 0x00000000 gt Having to copy data to our from an intermediate kernel buffer is expensive gt Zero copy options are possible gt mmap system call to allow user space to directly access memory mapped I O space covered in the mmap section gt get_user_pages to get a mapping to user pages without having to copy them See http j mp oPW6Fb Kernel API doc This API is more complex to use though Q static ssize_t acme_read struct file file char _
33. for bootloaders Composite kernel binary object image lib1funcs o asm wrapper around piggy gz bootstrapcode ELF object LE gt Located in arch lt arch gt boot compressed gt head o gt Architecture specific initialization code gt This is what is executed by the bootloader gt head cpu o here head xscale o gt CPU specific initialization code gt decompress o misc o gt Decompression code gt piggy lt compressionformat gt o gt The kernel itself gt Responsible for uncompressing the kernel itself and jumping to its entry point gt The uncompression code jumps into the main kernel entry point typically located in arch lt arch gt kernel head S whose job is to Check the architecture processor and machine type Configure the MMU create page table entries and enable virtual memory Calls the start_kernel function in init main c Same code for all architectures Anybody interested in kernel startup should study this file v v Y T v gt Calls setup_arch amp command_line gt Function defined in arch lt arch gt kernel setup c gt Copying the command line from where the bootloader left it gt On arm this function calls setup_processor in which CPU information is displayed and setup_machine locating the machine in the list of supported machines gt Initializes the console as early as possible to get error messages gt Initializes many subsystems
34. 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 Qc 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 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 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 Gs gt
35. gt gt Examples subject lines PATCH omitted Documentation prctl seccomp_filter PCI release busn when removing bus ARM add support for xz kernel decompression gt Remove previously generated patches gt rm 00 patch gt 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 gt You can run a last check on all your patches easy gt scripts check_patch pl strict 00 patch gt Now send your patches to yourself gt git send email compose to me mydomain com 00 patch gt 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 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 lina
36. gt xzcat diff_file xz patch p lt n gt bzcat diff_file bz2 patch p lt n gt gt zcat diff _file gz patch p lt n gt gt Notes gt n number of directory levels to skip in the file paths gt You can reverse apply a patch with the R option gt You can test a patch with dry run option Linux patches gt Always applied to the x y lt z 1 gt version Can be downloaded in gzip bzip2 or xz much smaller compressed files gt Always produced for n 1 that s what everybody does do it too gt Need to run the patch command inside the kernel source directory gt Linux patch command line example cd linux 3 0 xzcat patch 3 1 xz patch p1 xzcat patch 3 1 3 xz patch p1 cd mv linux 3 0 linux 3 1 3 Gs Kernel Source Code Gr gory Cl ment Michael Opdenacker Maxime Ripard S bastien Jan Thomas Petazzoni Free Electrons Copyright 2004 2013 Free Electrons Creative Commons BY SA 3 0 license Corrections suggestions contributions and translations are welcome Free Electrons Embedded Linux Developers Linux Code and Device Drivers gt The APls covered in these training slides should be compliant with Linux 3 6 gt We may also mention features in more recent kernels 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 lib
37. handlers gt Feature supported for the most popular CPU architectures gt Details available in the kernel documentation Documentation DocBook kgdb gt Recommended to turn 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 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 SyrRq g gt On your workstation start gdb as follows gt gdb vmlinux gt gdb set remotebaud 115200 gt gdb target remote dev ttyS0 gt Once connected you can debug a kernel the way you would debug an application program gt Two types of JTAG dongles gt Those offering a gdb compatible interface over a serial port or an Ethernet connexion 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 the bridge between the gdb debugging language and the JTAG dongle specific language gt See the very complete documentation http openocd sourceforge net d
38. is enabled to provide very early debugging messages on the serial port gt Boot parameters gt boot_params is the location where the bootloader has left the boot parameters the kernel command line gt The bootloader can override this address in register r2 gt See also Documentation arm Booting for the details of the environment expected by the kernel when booted gt The timer field points to a struct sys_timer structure that describes the system timer gt Used to generate the periodic tick at HZ frequency to call the scheduler periodically gt On the Calao board the system timer is defined by the at91sam926x_timer structure in at91sam926x_time c gt It contains the interrupt handler called at HZ frequency gt It is integrated with the clockevents and the clocksource infrastructures gt See include linux clocksource h and include linux clockchips h for details Os gt The map_ gt gt io function points to ek_map_io which gt Initializes the CPU using at91sam9263_initialize Map I O space Register and initialize the clocks gt Configures the debug serial port and set the console to be on this serial port gt Called at the very beginning of the C code execution gt vvvy init main c start_kernel arch arm kernel setup c setup_arch arch arm mm mmu c paging_init arch arm mm mmu c devicemaps_init mdesc gt map_io gt init_irq to initialize the IRQ hardware specifi
39. needed after removing the module 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 Linux Kernel in a Nutshell Dec 2006 gt By Greg Kroah Hartman O Reilly http www kroah com 1kn gt A good reference book and guide on configuring compiling and managing the Linux kernel sources gt Freely available on line Great companion to the printed book for KERNEL easy electronic searches IN A NUTSHELL Available as single PDF file on ee De http free electrons com ha community kernel 1kn gt Our rating 2 stars LE Embedded Linux driver development Gr gory Cl ment Michael Opdenacker Maxime Ripard S bastien Jan Thomas Petazzoni Free Electrons Copyright 2004 2013 Free Electrons Creative Commons BY SA 3 0 license Corrections suggestions contributions and translations are welcome Free Electrons Embedded Linux Developers Loadable Kernel Modules Oo hello c include lt linux init h gt include lt linux module h gt include lt linux kernel h gt
40. nwfpe vfp oprofile tools v And many directories for different SoC families gt mach directories mach pxa for PXA CPUs mach imx for Freescale iMX CPUs etc gt Each of these directories contain gt Support for the SoC family GPIO clocks pinmux power management interrupt controller etc gt Support for several boards using this SoC v Some CPU types share some code in directories named plat gt Taking the case of the Calao USB A9263 board which uses a AT91SAM9263 CPU gt arch arm mach at91 gt AT91 generic code gt clock c gt leds c gt irq c gt pm c gt CPU specific code for the AT91SAM9263 gt at91sam9263 c gt at9i1sam926x_time c gt at91sam9263_devices c gt Board specific code gt board usb a9263 c gt For the rest of this presentation we will focus on board support only gt configuration option must be defined for the board in arch arm mach at91 Kconfig config MACH_USB_A9263 bool CALAO USB A9263 depends on ARCH_AT91SAM9263 help Select this if you are using a Calao Systems USB A9263 lt http www calao systems com gt gt This option must depend on the CPU type option corresponding to the CPU used in the board gt Here the option is ARCH_AT91SAM9263 defined in the same file gt A default configuration file for the board can optionally be stored in arch arm configs For our board it s at91sam9263_defconfig gt The source files corresponding to the board
41. step of Linux booting gt First tries to open a console gt Then tries to run the init process effectively turning the current kernel thread into the userspace init process Q static noinline int init_post void __releases kernel_lock need to finish all async __init code before freeing the memory async_synchronize_full free_initmem mark_rodata_ro system_state SYSTEM_RUNNING numa_default_policy current gt signal gt flags SIGNAL_UNKILLABLE if ramdisk_execute_command run_init_process ramdisk_execute_command printk KERN_WARNING Failed to execute s n ramdisk_execute_command We try each of these until one succeeds The Bourne shell can be used instead of init if we are trying to recover a really broken machine if execute_command run_init_process execute_command printk KERN_WARNING Failed to execute s Attempting defaults n execute_command x run_init_process sbin init run_init_process etc init run_init_process bin init run_init_process bin sh panic No init found Try passing init option to kernel See Linux Documentation init txt System Initialization System operation init process gt The bootloader executes bootstrap code gt Bootstrap code initializes the processor and board and uncompresses the kernel code to RAM and calls the kernel s start_kernel function gt Copies the command line from
42. 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 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 modules endif gt For KDIR you can either set gt full kernel source directory configured and compiled gt or just kernel headers directory minimum needed 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 Kernel drivers and embedded Linux development consulting training and support http free electrons com 1390 4096 v v To be compiled a kernel module needs access to the kernel headers containing the definitions of functions types and
43. the driver gt The device drivers rely on the bus infrastructure to enumerate the devices and communicate with them System Call Interface Character Driver Val Driver Framebuffer Driver USB Storage Driver IDE Driver Serial Driver Kernel option CONFIG_FB gt menuconfig FB gt tristate Support for frame buffer devices Implemented in drivers video gt fb c fbmem c fbmon c fbcmap c fbsysfs c modedb c fbcvt c Implements a single character driver and defines the user kernel API gt First part of include linux fb h 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__ 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_ioctl gt xxxfb_blank gt xxxfb_mmap gt xxxfb_pan_display LE gt After the implementation of the operations definition of a struct fb_ops structure static struct fb_ops xxxfb_ops owner THIS_MODULE
44. to the kernel log from userspace too echo Debug info gt dev kmsg 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 Gs gt When loading a module fails insmod often doesn t give you enough details 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 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 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
45. up gt port if options Helper function from serial_core that parses the console string uart_parse_options options amp baud amp parity amp bits amp flow Helper function from serial_core that calls the gt set_termios operation with the proper arguments to configure the port return uart_set_options port co baud parity bits flow Q static void serial_txx9_console_putchar struct uart_port port int ch struct uart_txx9_port up struct uart_txx9_port port Busy wait for transmitter ready and output a single character wait_for_xmitr up sio_out up TXX9_SITFIFO ch static void serial_txx9_console_write struct console co const char s unsigned int count struct uart_txx9_port up amp serial_txx9_ports co gt index unsigned int ier flcr Disable interrupts ier sio_in up TXX9_SIDICR sio_out up TXX9_SIDICR 0 Disable flow control flcr sio_in up TXX9_SIFLCR if up gt port flags amp UPF_CONS_FLOW amp amp flcr amp TXX9_SIFLCR_TES sio_out up TXX9_SIFLCR flcr amp TXX9_SIFLCR_TES Helper function from serial_core that repeatedly calls the given putchar callback uart_console_write amp up gt port s count serial_txx9_console_putchar Re enable interrupts wait_for_xmitr up sio_out up TXX9_SIFLCR flcr sio_out up TXX9_SIDICR ier gt Improve the character driver of th
46. with the same CPU gt For example review the few differences between the Calao gil a9260 board and Atmel s sam9260 Evaluation Kit gt meld board sam9260ek c board qil a9260 c gt Similarly you will find very few differences in U boot between code for a board and for the corresponding evaluation board LE Power Management Gr gory Cl ment Michael Opdenacker Maxime Ripard S bastien Jan Thomas Petazzoni Free Electrons Copyright 2004 2013 Free Electrons Creative Commons BY SA 3 0 license Corrections suggestions contributions and translations are welcome Free Electrons Embedded Linux Developers gt Several power management building blocks gt Suspend and resume gt CPUidle gt Runtime power management gt Frequency and voltage scaling gt Applications gt Independent building blocks that can be improved gradually during development 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 http free electrons com kerneldoc latest DocBook kernel api cik 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 gt The clock framework API and the clk structure are usually impleme
47. 0 2 3 4 3 etc gt It effectively only removes a digit compared to the previous numbering scheme LE gt The official list of changes for each Linux release is just a huge list of individual patches commit aa6e52a35d388e730f4df0ec2ec48294590cc459 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_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 read
48. 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 drivers many network protocols support many architectures and filesystems gt The Linux core scheduler memory management is pretty small As of kernel version 3 2 gt drivers 53 65 gt scripts 0 44 gt arch 20 78 gt security 0 40 gt fs 6 88 gt crypto 0 38 gt sound 5 04 gt lib 0 30 gt net 4 33 gt block 0 13 gt include 3 80 gt ipc 0 04 gt firmware 1 46 gt virt 0 03 gt kernel 1 10 gt init 0 03 gt tools 0 56 gt samples 0 02 gt mm 0 53 gt usr 0 LE gt Full tarballs gt Contain the complete kernel sources long to download and uncompress but must be done at least once gt Example http www kernel org pub linux kernel v3 0 linux 3 1 3 tar xz gt Extract command tar Jxf linux 3 1 3 tar xz gt Incremental patches between versions gt It assumes you already have a base version and you apply the correct patches in the right order Quick to download and apply gt Examples http www kernel org pub linux kernel v3 0 patch 3 1 xz 3 0 to 3 1 http www kernel org pub linux kernel v3 0 patch 3 1 3 xz 3 1 to 3 1 3 gt All previous kernel versions are ava
49. Gs Linux Kernel and Driver Development Training Gr gory Cl ment Michael Opdenacker Maxime Ripard S bastien Jan Thomas Petazzoni Free Electrons Copyright 2004 2013 Free Electrons Creative Commons BY SA 3 0 license Latest update March 29 2013 Document updates and sources http free electrons com doc training linux kernel Corrections suggestions contributions and translations are welcome Free Electrons Embedded Linux Developers LE Copyright 2004 2013 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 gt Electronic copies of your particular version of the materials are available on http free electrons com doc training linux kernel gt Open the corresponding documents
50. INERS update Blackfin items Merge git igit kemel org pub scmiinux kerneligitjelb sesi rc fixes 2 6 SCSI nic Add new Cisco PCI Express FCoE HBA hugh update email address Merge branch merge of git git kemel org pub scm inuxkemel gitbenhipou Linus Torvalds lt toi 2009 06 01 17 02 05 Florian Faineli lt fo 2008 06 01 11 43 17 Linus Torvalds lt toi 2009 05 30 16 57 33 Li Yang lt leoli tree 2008 05 22 10 39 59 Linus Torvalds lt tol 2009 05 30 01 07 39 Paulius Zaleckas lt 2009 05 28 15 41 36 Thomas Dahimanr 2009 05 28 23 34 30 Joe Perches lt joe 2009 05 28 23 34 18 Miko Frysingor lt va 2009 05 18 10 33 07 Mike Frysingor lt va 2009 05 24 08 13 15 Linus Torvaids lt toi 2009 05 23 22 44 00 Abhijeet Joglekar lt 2009 04 18 03 33 26 Hugh Dickins lt hug 2009 05 21 21 33 58 Linus Torvalds lt toi 2009 05 05 17 25 37 SHATD 33716295303 cd1aaasesanatenzTensoanca7 gt Row 2 1300 j Find next prev commit containing Exact Allfields _search Diff Oldversion Newversion Linesofcontext 2 _ Ignore space change Patch Tree Comments MAINTAINERS Author Florian Fainelli lt florian openwrt org gt 2009 06 01 11 4 David S Miller lt davemfdavenloft net gt 2009 06 01 11 6e429101849416551150dad451F Branches master remotes origin master Follows v2 6 30 rc5 precedes v2 6 30 r08 This patch adds me as the maintainer of t
51. R ret TIOCM_DSR if status amp ATMEL_US_RI ret TIOCM_RI return ret gt The termios functions describe general terminal interface that is provided to control asynchronous communication ports gt mechanism to control from userspace serial port parameters such as gt Speed gt Parity gt Byte size gt Stop bit gt Hardware handshake gt Etc gt See termios 3 for details LE gt The set_termios operation must gt apply configuration changes according to the arguments gt update port gt read_config_mask and port gt ignore_config_mask to indicate the events we are interested in receiving gt static void set_termios struct uart_port port struct ktermios termios struct ktermios old gt port the port termios the new values and old the old values gt Relevant ktermios structure fields are gt c_cflag with word size stop bits parity reception enable CTS status change reporting enable modem status change reporting gt c_iflag with frame and parity errors reporting break event reporting LE static void atmel_set_termios struct uart_port port struct ktermios termios struct ktermios old unsigned long flags unsigned int mode imr quot baud mode __raw_readl port gt membase REG_MODE baud uart_get_baud_rate port termios old 0 port gt uartclk 16 Read current configuration quot uart_get_divisor port baud Compu
52. SOURCE_MEM i start AT91SAM9260_ID_SPIO end AT91SAM9260_ID_SPIO flags IORESOURCE_IRQ Fs static struct platform device at91sam9260_spi0_device name atmel_spi id 0 dev dma_mask amp spi_dmamask coherent_dma_mask DMA_BIT_MASK 32 F resource spi0_resources num_resources ARRAY_SIZE spi0_resources Free Electrons Kernel drivers and embedded Linux development consulting training and support http free electrons com 358 496 Gs gt Registration of SPI devices with spi_register_board_info registration of SPI adapter with platform_device_register void __init at91_add_device_spi struct spi_board_info devices int nr_devices Erat spi_register_board_info devices nr_devices Configure SPI bus es if enable_spi0 at91_set_A_periph AT91_PIN_PAO 0 SPIO_MISO at91_set_A_periph AT91_PIN_PA1 0 SPIO_MOSI at91_set_A_periph AT91_PIN_PA2 0 SPI1_SPCK at91_clock_associate spi0_clk amp at91sam9260_spi0_device dev spi cik platform_device_register kat91sam9260_spi0_device Essl LE gt One spi_board_info structure for each SPI device connected to the system static struct spi_board_info dk_spi_devices DataFlash chip modalias mtd_dataflash chip_select 0 max_speed_hz 15 1000 1000 UR6HCPS2 SP40 PS2 to SPI adapter modalias ur6hcps2 chip_select 1 max_speed
53. 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 gt 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 gt Get the contents of the tree gt git fetch rt gt Switch to one of the branches gt git checkout rt master 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 gt Either create a new branch starting from the current commit in the master branch gt git checkout b feature gt 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
54. The driver developer must gt Implement a console_write operation called to print characters on the console gt Implement a console_setup operation called to parse the console argument gt Declare a struct console structure gt Register the console using a console_initcall function LE static struct console serial_txx9_ console name TXX9_TTY_NAME write serial_txx9_console_ write Helper function from the serial_core layer device uart_console_device setup serial_txx9_console_setup Ask for the kernel messages buffered during boot to be printed to the console when activated flags CON_PRINTBUFFER index i data amp serial_txx9_reg static int __init serial_txx9_console_init void register_console amp serial_txx9_console return 0 This will make sure the function is called early during the boot process start_kernel calls console_init that calls our function console_initcall serial_txx9_console_init Q static int __init serial_txx9_console_setup struct console co char options struct uart_port port struct uart_txx9_port up int baud 9600 int bits 8 int parity n int flow n if co gt index gt UART_NR co gt index 0 up amp serial_txx9_ports co gt index port amp up gt port if port gt ops return ENODEV Function shared with the normal serial driver serial_txx9_initialize amp
55. _NORMAL ZONE_DMA 0x00000000 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 memory gt Mapping must be requested explicitly gt Limited addresses ranges reserved for this usage gt See http lwn net Articles 75174 for useful explanations 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 through bigger pages 2 MB pages on x86 with PAE gt Note that each user space process is still limited to a 3 GB memory space 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
56. _hz 250 1000 Ess 3 static void __init dk_board_init void Es at91_add_device_spi dk_spi_devices ARRAY_SIZE dk_spi_devices Eg gt Taken from arch arm mach at91 board dk c Qo gt Kernel documentation gt Documentation driver model gt Documentation filesystems sysfs txt gt The kernel source code gt Full of examples of other drivers Gs Serial Drivers Free Electrons Gr gory Cl ment Michael Opdenacker ae Maxime Ripard S bastien Jan Thomas Developers Petazzoni Free Electrons Copyright 2004 2013 Free Electrons Creative Commons BY SA 3 0 license Corrections suggestions contributions and translations are welcome Line Character Driver Discipline TTY Core gt To be properly integrated in a Linux system serial ports must be visible as TTY devices from userspace applications gt Therefore the serial driver must be part of the kernel TTY subsystem gt Until 2 6 serial drivers were implemented directly behind the TTY core gt A lot of complexity was involved gt Since 2 6 a specialized TTY driver serial_core eases the development of serial drivers gt See include linux serial_core h for the main definitions of the serial_core infrastructure gt The line discipline that cooks the data exchanged with the tty driver For normal serial ports N_TTY is used LE gt A data structure representing a driver uart_driver gt Single instance
57. _transmit port struct circ_buf xmit amp port gt state gt xmit if uart_circ_empty xmit uart_tx_stopped port disable_interrupt_on_txrdy return while uart_circ_empty xmit if __raw_readl port gt membase UART_REG1 amp UART_TX_FULL break __raw_writel xmit gt buf xmit gt tail port gt membase UART_REG2 xmit gt tail xmit gt tail 1 amp UART_XMIT_SIZE 1 port gt icount txt F if uart_circ_chars_pending xmit lt WAKEUP_CHARS uart_write_wakeup port Free Electrons Kernel drivers and embedded Linux development consulting training and support http free electrons com 377 496 LE gt On reception usually in an interrupt handler the driver must gt Increment port gt icount rx gt Call uart_handle_break if a BRK has been received and if it returns TRUE skip to the next character gt If an error occurred increment port gt icount parity port gt icount frame port gt icount overrun depending on the error type gt Calluart_handle_sysrq_char with the received character and if it returns TRUE skip to the next character gt Call uart_insert_char with the received character and a status gt Status is TTY_NORMAL is everything is OK or TTY_BREAK TTY_PARITY TTY_FRAME in case of error gt Call tty_flip_buffer_push to push data to the TTY layer Gs gt Part of the reception work is dedicated to handling Sysrq gt Sys
58. 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 process to kill to retrieve some memory That s better than letting the system freeze 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 Some Kernel Code vmalloc Allocator 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 gt Appropriate for medium size allocations gt page is usually 4K but can be made greater in some architectures sh mips
59. and line shell always hit the Tab key to complete command names and file paths This avoids 95 of typing mistakes gt Get an electronic copy on http free electrons com docs command line gt The vi editor is very useful to make quick changes to files in a 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 docs command line gt You can also take the quick tutorial by running vimtutor This is a worthy investment LE Linux Kernel Introduction Gr gory Cl ment Michael Opdenacker Maxime Ripard S bastien Jan Thomas Petazzoni Free Electrons Copyright 2004 2013 Free Electrons Creative Commons BY SA 3 0 license Corrections suggestions contributions and translations are welcome Free Electrons Embedded Linux Developers Linux features Qc User app B User app A Library A C library Call to services Event notification information exposition l Linux kernel A Manage hardware Event notification Hardware Free Electrons Kernel drivers and embedded Linux development consulting training and support http free electrons com 18 4096 gt The Linux kernel is one component of a system which also requires libraries and application
60. ary string to the kernel version that a user can get using uname r Very useful for support gt Support for swap can usually be disabled on most embedded devices gt Configure standard kernel features expert users allows to remove features from the kernel to reduce its size Powerful but use with care gt Loadable module support gt Allows to enable or completely disable module support If your system doesn t need kernel modules best to disable since it saves a significant amount of space and memory gt Enable the block layer gt If CONFIG_EXPERT is enabled the block layer can be completely removed Embedded systems using only flash storage can safely disable the block layer gt Processor type and features x86 or System type ARM or CPU selection MIPS gt Allows to select the CPU or machine for which the kernel must be compiled gt On x86 only optimization related on other architectures very important since there s no compatibility Os gt Kernel features gt Tickless system which allows to disable the regular timer tick and use on demand ticks instead Improves power savings gt High resolution timer support By default the resolution of timer is the tick resolution With high resolution timers the resolution is as precise as the hardware can give gt Preemptible kernel enables the preemption inside the kernel code the userspace code is always preemptible See our real time presentation for detai
61. ated area gt Example drivers infiniband core cache c struct ib_update_work work work kmalloc sizeof work GFP_ATOMIC kfree work gt void kzalloc size_t size gfp_t flags gt Allocates a zero initialized buffer gt void kcalloc size_t n size_t size gfp_t flags gt Allocates memory for an array of n elements of size size and zeroes its contents gt void krealloc const void p size_t new_size gfp_t 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 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 void vmalloc unsigned long size gt Returns a virtual address gt void vfree void addr LE gt Debugging features available since 2 6 31 gt Kmemcheck gt Dynamic checker for access to uninitialized memo
62. ated 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 gt The internal kernel API to implement kernel code can undergo changes between two stable 2 6 x or 3 x releases A stand alone driver compiled for a given version may no longer compile or work on a more recent one See Documentation stable_api_nonsense txt in kernel sources for reasons why gt Of course the external API must not change system calls proc sys as it could break existing programs New features can be added but kernel developers try to keep backward compatibility with earlier versions at least for 1 or several years gt Whenever a developer changes an internal API s he also has to update all kernel code which uses it Nothing broken gt Works great for code in the mainline kernel tree gt Difficult to keep in line for out of tree or closed source drivers gt USB example gt Linux has updated its USB internal API at least 3 times fixes security issues support for high speed devices and has now the fastest USB bus speeds compared to other systems Windows XP also had to rewrite its USB stack 3 times But because of closed source binary drivers that can t be updated they had to keep backward compatibility with all earlie
63. c dev_nr inode_nr Nice tutorial on http sources redhat com systemtap tutorial pdf gt Capability to add static markers to kernel code gt Almost no impact on performance until the marker is dynamically enabled by inserting a probe kernel module gt Useful to insert trace points that won t be impacted by changes in the Linux kernel sources gt See marker and probe example in samples markers in the kernel sources gt See http en wikipedia org wiki Kernel_marker Gs gt http lttng org gt The successor of the Linux Trace Toolkit LTT gt Toolkit allowing to collect and analyze tracing information from the kernel based on kernel markers and kernel tracepoints gt So far based on kernel patches but doing its best to use in tree solutions and to be merged in the future gt Very precise timestamps very little overhead gt Useful documentation on http 1ttng org documentation gt Viewer for LTTng traces gt Support for huge traces tested with 15 GB ones gt Can combine multiple tracefiles in a single view gt Graphical or text interface gt See http 1lttng org files lttv doc user_guide 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 mmap Possibility to ha
64. c details gt Implemented by ek_init_irq which calls at91sam9263_init_interrupts in at91sam9263 c which mainly calls at91_aic_init in irq c gt Initialize the interrupt controller assign the priorities gt Register the IRQ chip irg_chip structure to the kernel generic IRQ infrastructure so that the kernel knows how to ack mask unmask the IRQs gt Called a little bit later than map_io gt init main c start_kernel gt arch arm kernel irq c init_IRQ gt init_arch_irq equal to mdesc gt init_irq gt init _machine completes the initialization of the board by registering all platform devices gt Called by customize_machines in arch arm kernel setup c gt This function is an arch_initcall list of functions whose address is stored in a specific ELF section by levels gt At the end of kernel initialization just before running the first userspace program init gt gt gt gt init main c kernel_init init main c do_basic_setup init main c do_initcalls Calls all initcalls level by level gt For the Calao board implemented in ek_board_init gt Registers serial ports USB host USB device SPI Ethernet NAND flash 2IC buttons and LEDs gt Uses at91_add_ device _ x helpers defined in at91sam9263_devices c gt These helpers call platform_device_register to register the different platform_device structures defined in the same file gt For some devices the board s
65. ces are now managed with Git http git scm com gt You can browse Linus Git tree if you just need to check a few files http git kernel org p linux kernel git torvalds linux git a tree http j mp Qa0rzP gt You can also directly use Git on your workstation gt Debian Ubuntu install the git package v Choose a Git development tree on http git kernel org Get a local copy clone of this tree gt git clone git git kernel org pub scm linux kernel git torvalds linux git v gt Update your copy whenever needed git pull v More details in our chapter about Git Kernel source management tools gt http cscope sourceforge net gt gt Tool to browse source code mainly C but also C or Java Supports huge projects like the Linux kernel Takes less than 1 min to index Linux 2 6 17 sources fast gt Can be used from editors like vim and emacs In Linux kernel sources run it with cscope Rk see man cscope for details KScope graphical front end kscope package in Ubuntu 12 04 and later Allows searching for a symbol a definition functions strings files etc l request_irq Function y_enable_irg bar to display more lled by this funct lling this func rings Free Electrons Kernel drivers and embedded Linux development consulting training and support http free electrons com 72 496 gt http sourceforge net projects lxr gt Gener
66. constants Two solutions gt Full kernel sources gt Only kernel headers 1inux headers packages in Debian Ubuntu distributions The sources or headers must be configured gt Many macros or functions depend on the configuration kernel module compiled against version X of kernel headers will not load in kernel version Y gt modprobe insmod will say Invalid module format Gs 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 drivers 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 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 example
67. d 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 gt Engineers recruited in the heart of the embedded Linux developer community gt We are very familiar with the best solutions the community offers to product developers gt Contributing as much as possible to the community code documentation knowledge sharing financial support gt Our engineers regularly go to the top technical conferences We know other developers very well gt Nothing proprietary in Free Electrons Everything we produce for our company is shared and transparent in particular training materials and even evaluations from all our training sessions gt Linux kernel and board support package development to support new an custom hardware bootloader initialization device drivers power management gt Linux kernel mainlining integrate support for your hardware in the official Linux kernel sources gt Android porting and customization gt System development and building environment Buildroot OpenEmbedded and Yocto support gt System integration choosing the best components and making a custom system gt Boot time reduction gt All our training materials http free electrons com docs gt Technical blog http free electrons com blog gt Quarterly newsletter http lists free
68. ddr_t handle LE gt Works on buffers already allocated by the driver include lt linux dmapool h gt dma_addr_t dma_map_single struct device void size_t enum dma_data_direction xx J device structure input buffer to use buffer size Either DMA_BIDIRECTIONAL DMA_TO_DEVICE or DMA_FROM_DEVICE void dma_unmap_single struct device dev dma_addr_t handdle size_t size enum dma_data_direction dir 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 Use locking to prevent CPU access to the buffer 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 Kernel Architecture for Device Drivers Application Userspace Kernel 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 VAL serial etc gt The framework allows to factorize the common parts of drivers for the same type of devices gt From userspace they are still seen as character devices by the applications gt The framework allows to provide a coherent userspace interface ioctl etc for every type of device regardless of
69. ds etc gt Character devices gt Originally an infinite stream of bytes with no beginning no end no size The pure example a serial port gt Used for serial ports terminals but also sound cards video acquisition devices frame buffers gt Most of the devices that are not block devices are represented as character devices by the Linux kernel v A very important Unix design decision was to represent most of the system objects as files It allows applications to manipulate all system objects with the normal file API open read write close etc So devices had to be represented as files to the applications This is done through a special artifact called a device file It is a special type of file that associates a file name visible to userspace applications to the triplet type major minor that the kernel understands All device files are by convention stored in the dev directory Example of device files in a Linux system 1s 1 dev ttyS0 dev tty1 dev sdal dev sda2 dev zero brw rw 1 root disk 8 1 2011 05 27 08 56 dev sdai brw rw 1 root disk 8 2 2011 05 27 08 56 dev sda2 CiN 1 root root 4 1 2011 05 27 08 57 dev tty1 crw rw 1 root dialout 4 64 2011 05 27 08 56 dev ttyS0 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 int fd fd open dev ttyS0 O_RDWR write fd Hello 5
70. e gt Copy the final kernel image to the target storage gt can be ulmage zImage vmlinux bzImage in arch lt arch gt boot 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 LE 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 and many more documented in Documentation kernel parameters txt in the 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 gt Set up a cross compiling environment gt Cross compile a kernel for an ARM target
71. e previous labs to make it a real serial driver LE Kernel Initialization Gr gory Cl ment Michael Opdenacker Maxime Ripard S bastien Jan Thomas Petazzoni Free Electrons Copyright 2004 2013 Free Electrons Creative Commons BY SA 3 0 license Corrections suggestions contributions and translations are welcome Free Electrons Embedded Linux Developers Bootloader Low level hardware initialization Fetch and copy the Linux kernel to RAM init process System initialization from userspace Os How the kernel bootstraps itself appears in kernel building Example on ARM pxa cpu in Linux 2 6 36 LD vmlinux SYSMAP System map SYSMAP tmp_System map OBJCOPY arch arm boot Image Kernel arch arm boot Image is ready AS arch arm boot compressed head o GZIP arch arm boot compressed piggy gzip AS arch arm boot compressed piggy gzip o cc arch arm boot compressed misc o cc arch arm boot compressed decompress o AS arch arm boot compressed head xscale o SHIPPED arch arm boot compressed libifuncs S AS arch arm boot compressed libifuncs o LD arch arm boot compressed vmlinux OBJCOPY arch arm boot zImage Kernel arch arm boot zImage is ready as vmlinux piggy gz vmlinux zimage Kernel Proper Stripped Kernel Raw kernel Binary executable Binary Object ELF object Compressed Kernel Binary in arch lt arch gt Kernel image boot compressed
72. e other version control systems Git encourages the use of branches Don t hesitate to use them v v v v v Create a branch gt git branch lt branchname gt Move to this branch gt git checkout lt branchname gt Both at once create and switch to branch gt git checkout b lt branchname gt List of local branches gt git branch List of all branches including remote branches gt git branch a 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 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 yourbranch 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
73. e_cdev gt In the init function initialize the structure cdev_init amp acme_cdev amp acme_fops gt Then now that your structure is ready add it to the system int cdev_add struct cdev p Character device structure dev_t dev Starting device major minor unsigned count Number of devices gt After this function call the kernel knows the association between the major minor numbers and the file operations Your device is ready to be used gt Example continued if cdev_add amp acme_cdev acme_dev acme_count printk KERN_ERR Char driver registration failed n Os gt First delete your character device gt void cdev_del struct cdev p gt Then and only then free the device number gt void unregister_chrdev_region dev_t from unsigned count gt Example continued cdev_del amp acme_cdev unregister_chrdev_region acme_dev acme_count Qo gt The kernel convention for error management is gt Return O on success gt Return a negative error code on failure gt Error codes gt include asm generic errno base h gt include asm generic errno h Qo static static static static static static static static void acme_buf int acme_bufsize 8192 int acme_count 1 dev_t acme_dev MKDEV 202 128 struct cdev acme_cdev ssize_t acme_read ssize_t acme_write const struct file_operations acme_fo
74. ected to Very useful gt Take your time to explore sys on your workstation gt On embedded systems devices are often not connected through a bus allowing enumeration hotplugging and providing unique identifiers for devices gt However we still want the devices to be part of the device model gt The solution to this is the platform driver platform device infrastructure gt The platform devices are the devices that are directly connected to the CPU without any kind of bus Os 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 Fa gt And registers its driver to the platform driver infrastructure static int __init imx_serial_init void ret platform_driver_register amp serial_imx_driver static void __exit imx_serial_cleanup void platform_driver_unregister amp serial_imx_driver Free Electrons Kernel drivers and embedded Linux development consulting training and support http free electrons com 343 496 LE gt As platform devices cannot be detected dynamically they are defined statically gt By direct instantiation of struct platform_device structures as done on some ARM platforms Definition done in the board specific or SoC specific code gt By using
75. egion unsigned long start unsigned long len char name gt void release_mem_region unsigned long start unsigned long len 00000000 0009efff 0009f000 0009ffFF 000a0000 000bffff 000c0000 000cffff 000f0000 000ffFFF 00100000 3ffadfff 00100000 0030afff 0030b000 003b4bff 3ffae000 3fffffff 40000000 400003ff 40001000 40001fff 40400000 407fffff 40800000 40bfffff a0000000 a0000fff e8000000 efffffff 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_socketO PCI Bus 01 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 1 O memory is not mapped by default in virtual memory gt The ioremap function satisfies this need include lt asm io h gt void ioremap unsigned long phys_addr unsigned long size void iounmap void address gt Caution check that ioremap doesn t return a NULL address Kernel registers User Physical Memory Address Space Virtual Memory Address Space ioremap OxFFEBCO0 4096 OxCDEFAOOO 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
76. eks At regular intervals during the bug fixing period 2 6 x 1 rcY test versions are released When considered sufficiently stable kernel 2 6 x 1 is released and the process starts again 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 1 Bug fix P versions 3 1 1 3 1 2 3 1 3 3 1 4 i 3 2 1 gt Issue bug and security fixes only released for most recent stable kernel versions gt Some people need to have a recent kernel but with long term support for security stable updates mainline gt You could get long term support from a b dd d Li id stable commercial embedded Linux provider e gt You could reuse sources for the kernel Zone 3 stable used in Ubuntu Long Term Support ays releases 5 years of free security updates stable gt 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 3 7 1 3 7 3 6 11 EOL 3 5 7 EOL 3 4 24 3 2 35 3 0 57 2 6 34 13 2 6 32 60 linux next next 20121220 gt From 2003 to 2011 the official kernel versions were named 270X gt Linux 3 0 was released in July 2011 gt There is no change to the development model only a change to the numbering scheme gt Official kernel versions will be named 3 x 3 0 3 1 3 2 etc gt Stabilized versions will be named 3 x y 3
77. en using shared IRQs vvvvy gt void free_irq unsigned int irq void dev_id Qc gt Main irq_flags bit values can be combined none is fine too 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 gt IRQF_SAMPLE_RANDOM gt Use the IRQ arrival time to feed the kernel random number generator 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 since 2 6 36 Therefore they have to complete their job quickly enough to avoiding blocking interrupts for too long 39 41 42 43 44 52 IPIO IPI1 IPI2 IPI3 IPI4 LOC Err 196407 0 CPU1 0 GIC TWL6030 PIH 0 GIC 13 dbg irq 0 GIC 13 app irq 0 GIC prem 0 GIC DMA 0 GIC gpmc 0 Timer broadcast interrupts 25663 Rescheduling interrupts 0 Function call interrupts 173 Single function call interrupts 0 CPU stop interrupts 136995 Local timer interrupts Os gt irqreturn_t foo_interrupt int irq void dev_id gt irq the IRQ number gt dev_id the opaque p
78. eople making changes v Cost free maintenance security fixes and improvements gt Easy access to your sources by users gt Many more people reviewing your code gt Possible to implement device drivers in user space gt Such drivers just need access to the devices through minimum generic kernel drivers gt Examples gt Printer and scanner drivers on top of generic parallel port or USB drivers gt X drivers low level kernel drivers user space X drivers gt Userspace drivers based on UIO See Documentation DocBook uio howto in the kernel documentation for details about UIO and the Using UIO on an Embedded platform talk at ELC 2008 http j mp tBzayM LE 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 gt Can be swapped out kernel code cannot be gt Can use floating point computation gt Less in kernel complexity gt Drawbacks gt Less straightforward to handle interrupts gt Increased latency vs kernel code Linux sources gt arch lt architecture gt gt Architecture specific code gt arch lt architecture gt include asm gt Architecture and machine dependent headers gt arch lt architecture gt mach lt machine gt gt Machine board specific code gt bloc
79. epends on lt choice gt Location gt System Type gt TI OMAP Common Features gt OMAP System Type lt choice gt y I Q Looks for a keyword in the parameter name Allows to select or unselect found parameters X Search Config x Find mtd Search Option Physical address of DiskOnChip 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 ARM Firmware Suite partition parsing NEW OPMC551 Debugging Command line partition table parsing lv 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 Compiled as a module separate file CONFIG _IS09660 FS m Driver options 21SO 9660 CDROM file system support CONFIG_JOLIET y gt 2Microsoft Joliet CDROM extensions CONFIG_ZISOFS y gt 2Transparent decompression extension aUDF file system support Compiled statically into the kernel CONFIG UDF_FS y Options are grouped by sections a
80. ernel 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 gt You don t have to write your driver from scratch You can reuse code from similar free software drivers gt You get free community contributions support code review and testing Proprietary drivers even with sources don t get any gt Your drivers can be freely shipped by others mainly by distributions gt Closed source drivers often support a given kernel version A system with closed source drivers from 2 different sources is unmanageable gt Users and the community get a positive image of your company Makes it easier to hire talented developers gt You don t have to supply binary driver releases for each kernel version and patch version closed source drivers gt Drivers have all privileges You need the sources to make sure that a driver is not a security risk gt Your drivers can be statically compiled into the kernel useful to have a kernel image with all drivers needed at boot time v Once your sources are accepted in the mainline tree they are maintained by p
81. ers Prepare your lab environment gt Download the lab archive gt Enforce correct permissions LE Embedded Linux Kernel Usage Gr gory Cl ment Michael Opdenacker Maxime Ripard S bastien Jan Thomas Petazzoni Free Electrons Copyright 2004 2013 Free Electrons Creative Commons BY SA 3 0 license Corrections suggestions contributions and translations are welcome Free Electrons Embedded Linux Developers Linux kernel sources LE gt The official version of the Linux kernel as released by Linus Torvalds is available at http www kernel org gt This version follows the well defined development model of the kernel gt However it may not contain the latest development from a specific area due to the organization of the development model and because features in development might not be ready for mainline inclusion 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 They generally don t release official versions only development trees are available gt Linux 3 1 sources Raw size 434 MB 39 400 files approx 14 800 000 lines gzip compressed tar archive 93 MB bzip2 compressed tar archive 74 MB better xz compressed tar archive 62 MB best gt Minimum Linux 2 6
82. f an already defined variable type either byte short ushort int uint long ulong charp or bool checked at compile time perm for sys module lt module_name gt parameters lt param gt 0 no such module parameter value file Example int irg 5 module_param irq int S_IRUGO Modules parameter arrays are also possible with module_param_array but they are less common gt Create compile and load your first module gt Add module parameters gt Access kernel internals from your module Memory Management Q OxFFFFFFFF Physical Address Space OxFFFFFFFF 0xC0000600 1 0 Memory 3 Process 1 1 0 Memory 2 0x00000000 1 0 Memory 1 OxFFFFFFFF Kernel 0xC0000000 Process 2 0x00000000 0x00000000 Gs OxFFFFFFFF 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 gt Complete 3GB exclusive mapping available for each user space process gt Process code and data program stack gt Memory 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 0xC0000000 0x00000000 Physical Address Space 1 0 Memory RA OxFFFFFFFF 0xC0000000 ZONE_HIGHMEM ZONE
83. for each driver gt uart_register_driver and uart_unregister_driver gt A data structure representing a port uart_port gt One instance for each port several per driver are possible gt uart_add_one_port and uart_remove_one_port gt A data structure containing the pointers to the operations uart_ops gt Linked from uart_port through the ops field LE gt Usually gt Defined statically in the driver gt Registered in module_init gt Unregistered in module_cleanup gt Contains gt owner usually set to THIS_MODULE gt driver_name gt dev_name the device name prefix usually ttyS gt major and minor gt Use TTY_MAJOR and 64 to get the normal numbers But they might conflict with the 8250 reserved numbers gt nr the maximum number of ports gt cons pointer to the console device covered later LE static struct uart_driver atmel_uart owner THIS _MODULE driver_name atmel_serial dev_name ATMEL_DEVICENAME major SERIAL_ATMEL_MAJOR minor MINOR_START nr ATMEL_MAX_UART cons ATMEL_CONSOLE_DEVICE static struct platform_driver atmel_serial_driver probe atmel_serial_probe remove __devexit_p atmel_serial_remove suspend atmel_serial_suspend resume atmel_serial_resume driver name atmel_usart owner THIS_MODULE 3 3 Example code from drivers serial atmel_serial c Gs static int __init atmel_serial_init void
84. git log will list all the commits The latest commit is the first commit 4371ee353c3fc41aad9458b8e8e627eb508bc9a3 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 Q gt gitk is a graphical tool that represents the history of the current Git repository gt Can be installed from the gitk p ackage File Edit View Merge git igi kernel org pub scm inux kemelgitdavem net 2 8 MAINTAINERS take maintainership of the cpmac Ethemet driver Merge branch fixes of git gitkemel orgipub scm inuxkemelgitdbw asy fsldma update mailing ist address in MAINTAINERS Merge master kemeLorg home mk 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 subseribers only markings on Blackfin lists MAINTA
85. gt The most common graphical interface to configure the kernel gt Make sure you read help gt introduction useful options v File browser easier to load configuration files v Search interface to look for parameters v Required Debian Ubuntu packages 1ibqt4 dev g 1ibqt3 mt dev for older kernel releases Option Option General setup of IRQ subsystem 5 OMAP System Type RCU Subsystem FOTI OMAP1 OControl Group support ONamespaces support BConfigure standard kernel Features expert users Kernel Performance Events And Counters L GCOV based kernel profiling BEnable loadable module support BlEnable the block layer i Partition Types 10 Schedulers System Type i Tl OMAP2 3 4 Specific Features Bus support OPCCard PCMCIA CardBus support Kernel Features Boot options Er CPU Power Management Lcpu Frequency scaling Floating point emulation F Userspace binary Formats Power management options E BNetworking support Eat Li ki OMAP Feature Selections OSmartReflex support Reset unused clocks during boot 5 ZOMAP multiplexing support Multiplexing debug output BWarn about pins the bootloader didn t set up OMailbox Framework support Buse 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 D
86. he CPNAC ART Ethernet driver Signed off by Florian Fainelli lt florian openwrt org gt Signed off by David S Miller lt davem davemLoft net gt 32bc66d6d0ede9bD dee9ebac295bdb7ed751d6b Merge branch merge of git 8625317ae09 Merge git git kernel org pul MAINTAINERS take maintainership of the cpmac Ethernet driver 7 lpub scm linux kernel git torvalds linux 2 6 git commitdiff gt Another great tool is the Web interface to Git For the kernel it is available at http git kernel org Fee git summary shortlog log commit commitdiff tree commit search raw merge 8623661 84047e3 Merge branch tracing urgent for linus of git git kernel org pub scm linux kernel master Linus Torvalds Thu 11 Jun 2009 02 58 10 0000 19 58 0700 tracing urgent for linus of git git kernel org pub scm linux kernel git tip linux 2 6 tip function graph always initialize task ret_stack function graph move initialization of new tasks up in fork function graph add memory barriers for accessing task s ret_stack function graph enable the stack after initialization of other variables function graph only allocate init tasks if it was not already done Manually fix trivial conflict in kernel trace ftrace c kernel fork c patch blob history kernel trace ftrace c patch blob history kernel trace trace_functions_graph c patch blob hi
87. he 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 linux gnueabi gcc the prefix is arm linux gnueabi 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 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 linux 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 linux 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
88. hscreens tablets etc Character devices contains various device drivers amongst them gt serial port controller drivers gt PTY driver needed for things like SSH or telnet gt 12C SPI 1 wire support for the popular embedded buses Hardware monitoring support infrastructure and drivers for thermal sensors gt Device drivers cont gt gt Watchdog support Multifunction drivers are drivers that do not fit in any other category because the device offers multiple functionality at the same time Multimedia support contains the V4L and DVB subsystems for video capture webcams AM FM cards DVB adapters gt Graphics support infrastructure and drivers for framebuffers gt Sound card support the OSS and ALSA sound infrastructures and the corresponding drivers HID devices support for the devices that conform to the HID specification Human Input Devices Gs gt Device drivers cont gt vvvvyy USB support Infrastructure Host controller drivers Device drivers for devices connected to the embedded system Gadget controller drivers Gadget drivers to let the embedded system act as a mass storage device a serial port or an Ethernet adapter MMC SD SDIO support LED support Real Time Clock drivers Voltage and current regulators Staging drivers crappy drivers being cleaned up NN vv gt For some categories of devices the driver is not implemented inside the kernel gt Printers g
89. ic source indexing tool and code browser gt Web server based very easy and fast to 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 1xr free electrons com server cred internals h user_namespace init_user_ns kret refcount ATOMIC_INIT 1 eat root_user 27 EXPORT_SYMBOL_GPL init_user_ns Free Electrons Kernel drivers and embedded Linux development consulting training and support http free electrons com 74 496 v Get the Linux kernel sources v Apply patches v Explore sources manually gt Use automated tools to explore the source code Kernel configuration 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 gt The kernel contains thousands of device dri
90. ilable in http kernel org pub linux kernel Free Electrons Kernel drivers and embedded Linux development consulting training and support http free electrons com 40 496 LE gt A patch is the difference between two source trees gt Computed with the diff tool or with more elaborate version control systems gt They are very common in the open source community gt Excerpt from a patch diff Nru a Makefile b Makefile a Makefile 2005 03 04 09 27 15 08 00 b Makefile 2005 03 04 09 27 15 08 00 1 7 1 7 VERSION 2 PATCHLEVEL 6 SUBLEVEL 11 EXTRAVERSION EXTRAVERSION 1 NAME Woozy Numbat DOCUMENTATION One section per modified file starting with a header diff Nru a Makefile b Makefile a Makefile 2005 03 04 09 27 15 08 00 b Makefile 2005 03 04 09 27 15 08 00 One sub section per modified part of the file starting with header with the affected line numbers 1 7 1 7 Three lines of context before the change VERSION 2 PATCHLEVEL 6 SUBLEVEL 11 The change itself EXTRAVERSION EXTRAVERSION 1 Three lines of context after the change NAME Woozy Numbat DOCUMENTATION The patch command gt gt Takes the patch contents on its standard input Applies the modifications described by the patch into the current directory patch usage examples gt gt gt patch p lt n gt lt diff_file cat diff_file patch p lt n
91. in 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 void mutex_init struct mutex lock gt void 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 int 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 int mutex_lock_interruptible struct mutex lock gt Same but can be interrupted by any signal Gs gt int mutex_trylock struct mutex lock gt Never waits Returns a non zero value if the mutex is not available gt int mutex_is_locked struct mutex lock gt Just tells whether the mutex is locked or not gt void mutex_unlock struct mutex lock gt Releases the lock Do it as soon as you leave the critical section 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 inte
92. ine if you do not implement anything special Oo gt Kernel data type to represent a major minor number pair Also called a device number Defined in linux kdev_t h 32 bit size major 12 bits minor 20 bits Macro to compose the device number Y Yv v gt MKDEV int major int minor Macro to extract the minor and major numbers gt MAJOR dev_t dev gt MINOR dev_t dev Y Os include lt linux fs h gt int register_chrdev_region dev_t from Starting device number unsigned count Number of device numbers const char name Registered name Returns 0 if the allocation was successful Example static dev_t acme_dev MKDEV 202 128 if register_chrdev_region acme_dev acme_count acme pr_err Failed to allocate device number n Qc gt If you don t have fixed device numbers assigned to your driver gt Better not to choose arbitrary ones There could be conflicts with other drivers gt The kernel API offers an alloc_chrdev_region function to have the kernel allocate free ones for you You can find the allocated major number in proc devices Character devices 1 mem 4 tty 4 ttys 5 dev tty 5 dev console Block devices 1 ramdisk 7 loop 8 sd 9 md 11 sr 179 mmc 254 mdp gt The kernel represents character drivers with a cdev structure gt Declare this structure globally within your module include lt linux cdev h gt static struct cdev acm
93. initializes variables that couldn t be statically initialized This only exists for built in code not for modules define pure_initcall fn __define_initcall 0 fn 1 define core_initcall fn __define_initcall i fn 1 define core_initcall_sync fn __define_initcall is fn is define postcore_initcall fn __define_initcall 2 fn 2 define postcore_initcall_sync fn __define_initcall 2s fn 2s define arch_initcall fn __define_initcall 3 fn 3 define arch_initcall_sync fn __define_initcall 3s fn 3s define subsys_initcall fn __define_initcall 4 fn 4 define subsys_initcall_sync fn __define_initcall 4s fn 4s define fs_initcall fn _ define_initcall 5 fn 5 define fs_initcall_sync fn __define_initcall 5s fn 5s define rootfs_initcall fn __define_initcall rootfs fn rootfs define device_initcall fn __define_initcall 6 fn 6 define device_initcall_sync fn __define_initcall 6s fn 6s define late_initcall fn __define_initcall 7 fn 7 define late_initcall_sync fn __define_initcall 7s fn 7s Defined in include linux init h Oo From arch arm mach pxa 1pd270 c Linux 2 6 36 static int __init lpd270_irq_device_init void int ret ENODEV if machine_is_logicpd_pxa270 ret sysdev_class_register amp lpd270_irq_sysclass if ret 0 ret sysdev_register amp lpd270_irq_device return ret device_initcall 1pd270_irq_device_init Qo gt The last
94. interrupted can t kill the user space process gt int wait_event_killable queue condition gt Can be interrupted but only by a fatal signal SIGKILL Returns ERESTARSYS if interrupted gt int wait_event_interruptible queue condition gt Can be interrupted by any signal Returns ERESTARTSYS if interrupted gt int wait_event_timeout queue condition timeout 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 int 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 ret wait_event_interruptible sonypi_device fifo_proc_list kfifo_len sonypi_device fifo 0 if ret return ret Qo gt Typically done by interrupt handlers when data sleeping processes are waiting for becomes 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 gt wait_event_interruptible puts a task in a non exclusive wait gt All non exclusive tasks are woken up by wake_up wake_up_interruptible gt wait_event_interruptible_exclusive puts a task in an exclusive wait gt wake_up wake_up_inte
95. ions 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 void atomic_set atomic_t v int i gt int atomic_read atomic_t v gt Operations without return value gt gt gt gt void void void void atomic_inc atomic_t v atomic_dec atomic_t v atomic_add int i atomic_t v atomic_sub int i atomic_t v LE gt Similar functions testing the result gt int atomic_inc_and_test gt int atomic_dec_and_test gt int atomic_sub_and_test gt Functions returning the new value gt int atomic_inc_return gt int atomic_dec_return gt int atomic_add_return gt int atomic_sub_return gt Supply very fast atomic operations gt On most platforms apply to an unsigned long type gt Apply to a void type on a few others gt Set clear toggle a given bit gt void set_bit int nr unsigned long addr gt void clear_bit int nr unsigned long addr gt void change_bit int nr unsigned long addr gt Test bit value gt int test_bit int nr unsigned long addr gt Test and modify return the previous value gt int test_and_set_bit gt int test_and_clear_bit gt int test_and_change_bit gt Add locking to the driver to prevent concurrent accesses to shared resource
96. ity 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 Qc gt A virtual filesystem to export debugging information to user space gt Kernel configuration DEBUG_FS gt Kernel hacking gt Debug Filesystem gt The debugging interface disappears when Debugfs is configured out gt You can mount it as follows gt sudo mount t debugfs none sys kernel debug gt First described on http lwn net Articles 115405 gt API documented in the Linux Kernel Filesystem API gt Documentation DocBook filesystems v Create a sub directory for your driver gt struct dentry debugfs_create_dir const char name struct dentry parent v Expose an integer as a file in DebugFS gt struct dentry debugfs_create_ u x 8 16 32 const char name mode_t mode struct dentry parent u8 value gt u for decimal representa
97. ivers 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 LE 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 exclude the feature gt int options to specify integer values gt string options to specify string values 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 make xconfig
98. k gt Block layer core gt COPYING gt Linux copying conditions GNU GPL gt CREDITS gt Linux main contributors gt crypto gt Cryptographic libraries gt Documentation gt Kernel documentation Don t miss it gt drivers gt All device drivers except sound ones usb pci gt fs gt Filesystems fs ext3 etc gt include gt Kernel headers gt include linux gt Linux kernel core headers gt init gt Linux initialization including main c gt ipc gt Code used for process communication gt Kbuild gt Part of the kernel build system 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 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 gt usr gt Code to generate an initramfs cpio archive gt Useful if you are involved in kernel development or if you found a bug in the source code gt Kernel development sour
99. ls gt Power management gt Global power management option needed for all power management related features gt Suspend to RAM CPU frequency scaling CPU idle control suspend to disk Gs gt Networking support gt The network stack gt Networking options gt Unix sockets needed for a form of inter process communication gt TCP IP protocol with options for multicast routing tunneling Ipsec Ipv6 congestion algorithms etc gt Other protocols such as DCCP SCTP TIPC ATM gt Ethernet bridging QoS etc gt Support for other types of network gt CAN bus Infrared Bluetooth Wireless stack WiMax stack etc gt Device drivers gt MTD is the subsystem for flash NOR NAND OneNand battery backed memory etc gt Parallel port support gt Block devices a few misc block drivers such as loopback NBD etc gt ATA ATAPI support for IDE disk CD ROM and tapes A new stack exists gt SCSI gt The SCSI core needed not only for SCSI devices but also for USB mass storage devices SATA and PATA hard drives etc gt SCSI controller drivers Gs gt Device drivers cont gt gt gt SATA and PATA the new stack for hard disks relies on SCSI RAID and LVM to aggregate hard drivers and do replication Network device support with the network controller drivers Ethernet Wireless but also PPP Input device support for all types of input devices keyboards mice joysticks touc
100. munity by Jonathan Corbet A Guide To The Kernel Development Process http j mp tX2Ld6 gt Use git to prepare make your changes gt Don t merge patches addressing different issues gt Make sure that your changes compile well and if possible run well gt Run Linux patch checks scripts checkpatch pl gt Send the patches to yourself first as an inline attachment This is required to let people reply to parts of your patches Make sure your patches still applies See Documentation email clients txt for help configuring e mail clients Best to use git send email which never corrupts patches gt Run scripts get_maintainer pl on your patches to know who you should send them to References gt 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 kernel Subscribe to finance the editors 7 month Articles available for non subscribers after 1 week gt Essential Linux Device Drivers April 2008 gt http free electrons com redirect eldd book html gt By Sreekrishnan Venkateswaran an embedded IBM engineer with more than as 10 years of experience Essential Linux Device Drivers gt Covers a wide range of topics not et covered by LDD serial drivers input Aeae an otaona drivers 12C PCMCIA and Compact Flash PCI USB video drivers audio drivers block drivers network drivers Bluetooth
101. n 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 Qc 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 1ib 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_oss gt modules dep Module dependencies gt modules symbols Tells which module a given symbol belongs to 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 Cross compiling the kernel When you compile a Linux kernel for another CPU architecture gt Much faster than compiling natively when t
102. n support several boards gt The right structure is chosen at boot time gt In the ARM architecture each board type is identified by a machine type number gt The latest machine type numbers list can be found at http www arm linux org uk developer machines download php gt A copy of it exists in the kernel tree in arch arm tools mach types gt For the Calao board gt usb_a9263 MACH_USB_A9263 USB_A9263 1710 gt At compile time this file is processed to generate a header file include asm arm mach types h gt For the Calao board gt define MACH_TYPE_USB_A9263 1710 gt And a few other macros in the same file gt The machine type number is set in the MACHINE_START definition gt MACHINE_START USB_A9263 CALAO USB_A9263 gt At run time the machine type number of the board on which the kernel is running is passed by the bootloader in register rl gt Very early in the boot process arch arm kernel head S the kernel calls __lookup_machine_type in arch arm kernel head common S gt __lookup_machine_type looks at all the machine_desc structures of the special ELF section gt If it doesn t find the requested number prints a message and stops gt If found it knows the machine descriptions and continues the boot process gt Early debugging gt phys_io is the physical address of the I O space gt io_pg_offset is the offset in the page table to remap the I O space gt These are used when CONFIG_DEBUG_LL
103. nd 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 LE 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 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 Kernel drivers and embedded Linux development consulting training and support http free electrons com 89 496 LE make nconfig gt newer similar text interface me Bus options PCI etc gt gt More user friendly for ee example easier to access mie 1 cryptogr cos help information D ni Le gt Required Debian packages i F SE F E A E e E o libncurses dev 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
104. nded 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 gt Statically gt DEFINE_SPINLOCK my_lock gt Dynamically gt void spin_lock_init spinlock_t lock LE gt Several variants depending on where the spinlock is called gt void spin_lock spinlock_t lock gt void spin_unlock spinlock_t lock gt Doesn t disable interrupts Used for locking in process context critical sections in which you do not want to sleep gt void spin_lock_irqsave spinlock_t lock unsigned long flags gt void spin_unlock_irqrestore spinlock_t lock unsigned long 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 gt void spin_lock_bh spinlock_t lock gt void spin_unlock_bh spinlock_t 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 gt Spinlock structure embedded into uart_port struct uart_port spinlock_t lock
105. ng kernel trace functions read and write variables follow pointers gather statistics Eliminates the need to modify the kernel sources to add one s own instrumentation to investigated a functional or performance problem Uses a simple scripting language Several example scripts and probe points are available Based on the Kprobes instrumentation infrastructure See Documentation kprobes txt in kernel sources Now supported on most popular CPUs Q usr bin env stap Using statistics and maps to examine kernel memory allocations global kmalloc probe kernel function __kmalloc kmalloc execname lt lt lt size Exit after 10 seconds probe timer ms 10000 exit probe end foreach name in kmalloc printf Allocations for s n name printf Count d allocations n count kmalloc name printf Sum 4 Kbytes n sum kmalloc name 1024 printf Average d bytes n avg kmalloc name printf Min 4 bytes n min kmalloc name printf Max Za bytes n max kmalloc name print nAllocations by size in bytes n print hist_log kmalloc name printf M n n x Qc usr bin env stap Logs each file read performed by each process probe kernel function vfs_read dev_nr file gt f_dentry gt d_inode gt i_sb gt s_dev inode_nr file gt f_dentry gt d_inode gt i_ino printf s d s Ox x d n execname pid probefun
106. nted by each architecture code duplication gt See arch arm mach at91 clock c for an example gt This is also where all clocks are defined gt Clocks are identified by a name string specific to a given platform gt Drivers can then use the clock API Example from drivers net macb c gt clk_get called from the probe function to get the definition of a clock for the current board get its frequency and run clk_enable gt clk_put called from the remove function to release the reference to the clock after calling clk_disable Os From arch arm mach at91 clock c 2 6 36 static void __clk_disable struct clk clk BUG_ON clk gt users 0 if clk gt users 0 amp amp clk gt mode Call the hardware function switching off this clock clk gt mode clk 0 if clk gt parent __clk_disable clk gt parent static void pmc_sys_mode struct clk clk int is_on if is_on at91_sys_write AT91_PMC_SCER clk gt pmc_mask else at91_sys_write AT91_PMC_SCDR clk gt pmc_mask Qo gt Infrastructure in the kernel to support suspend and resume gt Platform hooks gt prepare enter finish valid ina 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 platform_driver usb_driver etc gt See drivers net macb c
107. ocumentation online docs gt For each board you ll need an OpenOCD configuration file ask your supplier gt See very useful details on using Eclipse gcc gdb OpenOCD on Windows similar usage gt http www2 amontec com sdk4arm ext jlynch tutorial 20061124 pdf gt http www yagarto de howto yagarto2 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 If your kernel doesn t boot yet or hangs without any message you can activate the low level debugging option Kernel Hacking section only available on arm and unicore32 CONFIG_DEBUG_LL y gt Techniques to locate the C instruction which caused an oops gt http kerneltrap org node 3648 LE gt kexec system call makes it possible to call a new kernel Step 2 Kemel without rebooting and going Don Le through the BIOS firmware gt Idea after a kernel panic make Step 3 Analyze gt crashed kernel RAM the kernel automatically execute a new clean kernel from a reserved location in RAM to perform post mortem analysis of the memory of the crashed kernel Step 1 Copy debug kerne to reserved RAM gt See Documentation kdump kdump txt in the kernel sources for details Gs gt http sourceware org systemtap gt vvvvysy Infrastructure to add instrumentation to a runni
108. 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 Qo IRQ12 IRQ42 Once all softirqs are finished is is control is given back to the triggered triggered scheduler Once all IRQ handlers have been executed softirqs are executed 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 softirqs 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 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 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 sim
109. ointer that was passed to 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 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 gt 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 12C 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 gt int request_threaded_irq unsigned int irq irq_handler_t handler irq_handler_t thread_fn unsigned long flags const char name void dev gt handler hard IRQ handler gt thread_fn executed in a thread LE 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
110. om redir 1kd3 book html gt A very synthetic and pleasant way to learn about kernel subsystems beyond the needs of device driver writers i THE LINUX gt The Linux Programming Interface Oct PROGRAMMING 2010 INTERFACE gt Michael Kerrisk No Starch Press mean ern gt http man7 org tlpi gt gold mine about the kernel interface and how to use it 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 wuw tux org 1kml 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 gt Embedded Linux Conference http embeddedlinuxconference com gt gt gt gt gt Organized by the CE Linux Forum in California San Francisco April in Europe October November Very interesting kernel and userspace topics for embedded systems developers Presentation slides freely available gt Linux Plumbers http linuxplumbersconf org gt Conference on the low level plumbing of Linux kernel audio power management de
111. on a single architecture with always the same toolchain you could even put these settings in your bashrc file to make them permanent and visible from any terminal Default configuration files available per board or per CPU family 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 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 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 configuration processor and architecture specific options specific drivers etc gt Many options will be identical filesystems network protocol architecture independent drivers etc gt Make sure you have the support for the right CPU the right board and the right device drivers gt Run mak
112. ows kernel code and applications to set their requirements in terms of gt CPU DMA latency gt Network latency gt Network throughput gt According to these requirements PM QoS allows kernel drivers to adjust their power management gt See Documentation power pm_qos_interface txt and Mark Gross presentation at ELC 2008 gt Still in very early deployment only 4 drivers in 2 6 36 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 consumer interface for device drivers i e users gt Regulator driver interface for regulator drivers gt Machine interface for board configuration gt sysfs interface for userspace 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 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 hook
113. pecific code does the registration itself buttons or passes board specific data to the registration helper USB host and device NAND Ethernet etc gt The at91sam9263 devices c file doesn t implement the drivers for the platform devices gt The drivers are implemented at different places of the kernel tree gt For the Calao board gt USB host driver at91_ohci drivers usb host ohci at91 c USB device driver at91_udc drivers usb gadget at91_udc c gt Ethernet driver macb drivers net macb c gt NAND driver atmel_nand drivers mtd nand atmel_nand c I2C on GPIO driver i2c gpio drivers i2c busses i2c gpio c gt SPI driver atmel_spi drivers spi atmel_spi c gt Buttons driver gpio keys drivers input keyboard gpio_keys c gt All these drivers are selected by the default configuration file gt The ARM architecture is migrating to the device tree gt The Device Tree is a data structure for describing hardware Instead of describing the hardware in C a special data structure external to the kernel is used Allows to more easily port the kernel to newer platforms and to make a single kernel image support multiple platforms ARM architecture is being consolidated The clock API is being converted to a proper framework with drivers in drivers clk The GPIO support is being converted as proper GPIO drivers in drivers gpio The pin muxing support is being converted as drivers in drivers pinctrl
114. platform gt Boot this kernel from a directory on your workstation accessed by the board through NFS Using kernel 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 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 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
115. ply 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 LE The tasklet function static void atmel_tasklet_func unsigned long data struct uart_port port struct uart_port data El Registering the tasklet init function tasklet_init amp atmel_port gt tasklet atmel_tasklet_func unsigned long port En LE Removing the tasklet cleanup function Lis tasklet_kill amp atmel_port gt tasklet La Triggering execution of the tasklet somewhere function tasklet_schedule amp atmel_port gt tasklet 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 gt Device driver gt When the device file is first opened register an interrupt handler for the device s interrup
116. ps owner THIS_MODULE read acme_read write acme_write Q static int _init acme_init void int err acme_buf ioremap ACME_PHYS acme_bufsize if acme_buf err ENOMEM goto err_exit J if register_chrdev_region acme_dev acme_count acme err ENODEV goto err_free_buf cdev_init amp acme_cdev amp acme_fops if cdev_add amp acme_cdev acme_dev acme_count err ENODEV goto err_dev_unregister return 0 err_dev_unregister unregister_chrdev_region acme_dev acme_count err_free_buf iounmap acme_buf err_exit return err Oo static void __exit acme_exit void cdev_del amp acme_cdev unregister_chrdev_region acme_dev acme_count iounmap acme_buf module_init acme_init module_exit acme_exit Kernel character device writer v gt Define the file operations callbacks for the device file read write ioctl gt In the module init function reserve major and minor numbers with register_chrdev_region init a cdev structure with your file operations and add it to the system with cdev_add gt User space system administration gt Load the character driver module gt Create device files with matching major and minor numbers if needed The device file is ready to use gt User space system user gt Open the device file read write or send ioctl s to it Kernel v gt Executes
117. r implementation This is very costly development security stability performance gt See Myths Lies and Truths about the Linux Kernel by Greg K H for details about the kernel development process http kroah com log linux ols_2006_keynote html v gt No memory protection v Accessing illegal memory locations result in often fatal kernel oopses Fixed size stack 8 or 4 KB Unlike in userspace there s no way to make it grow Kernel memory can t be swapped out for the same reasons v v 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 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 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 k
118. rary routines No C used see http www tux org lkm1 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 6 1 gcc C Extensions html Y v v v gt The kernel has to be standalone and can t use user space code gt Userspace 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 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_le32 gt be32_to_cpu gt le32_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 gt Never use floating point numbers in kernel code Your code may be run on a processor without a floating point unit like on ARM gt Don t be confused with floating point rel
119. rits from struct driver which is defined by the device model static struct usb_driver rt18150_driver name rt18150 probe rt18150_probe disconnect rt18150_disconnect id_table rt18150_table suspend rt18150_suspend resume rt18150_resume gt When the driver is loaded or unloaded it must register or unregister itself from the USB core Done using usb_register and usb_deregister provided by the USB core static int __init usb_rt18150_init void return usb_register amp rt18150_driver static void __exit usb_rt18150_exit void usb_deregister amp rt18150_driver module_init usb_rt18150_init module_exit usb_rt18150_exit 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 gt The USB core now knows the association between the vendor product IDs of rt18150 and the usb_driver structure of this driver Step 2 USB core looks up the registered IDs and finds the matching driver Step 1 a new Step 3 The USB core calls USB device is the probe method of the detected with usb driver structure registered ID X Y by the rtl8150 driver gt The probe method receives as argument a structure describing the device usually specialized by the bus infrastructure pci_dev usb_interface etc gt
120. rmios change port parameters gt See the detailed description in Documentation serial driver The start_tx method should start transmitting characters over the serial port The characters to transmit are stored in a circular buffer implemented by a struct uart_circ structure It contains gt buf the buffer of characters gt tail the index of the next character to transmit After transmit tail must be updated using tail tail amp UART_XMIT_SIZE 1 Utility functions on uart_circ gt uart_circ_empty tells whether the circular buffer is empty gt uart_circ_chars_pending returns the number of characters left to transmit From an uart_port pointer this structure can be reached using port gt state gt xmit LE foo_uart_putc struct uart_port port unsigned char c while __raw_readl port gt membase UART_REG1 amp UART_TX_FULL cpu_relax __raw_writel c port gt membase UART_REG2 foo_uart_start_tx struct uart_port port struct circ_buf xmit amp port gt state gt xmit while uart_circ_empty xmit foo_uart_putc port xmit gt buf xmit gt tail xmit gt tail xmit gt tail 1 amp UART_XMIT_SIZE 1 port gt icount txt foo_uart_interrupt int irq void dev_id Less if interrupt_cause amp END_OF_TRANSMISSION foo_uart_handle_transmit port Posel foo_uart_start_tx struct uart_port port enable_interrupt_on_txrdy i LE foo_uart_handle
121. ro 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 LE gt If 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 Os gt We 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 book git scm com 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 jame
122. rq are special commands that can be sent to the kernel to make it reboot unmount filesystems dump the task state nice real time tasks etc gt These commands are implemented at the lowest possible level so that even if the system is locked you can recover it gt Through serial port send a BRK character send the character of the Sysrq command gt See Documentation sysrq txt gt In the driver gt uart_handle_break saves the current time 5 seconds in a variable gt uart_handle_sysrq_char will test if the current time is below the saved time and if so will trigger the execution of the Sysrq command Os foo_receive_chars struct uart_port port int limit 256 while limit gt 0 status __raw_readl port gt membase REG_STATUS ch __raw_readl port gt membase REG_DATA flag TTY_NORMAL if status amp BREAK port gt icount break if uart_handle_break port continue else if status amp PARITY port gt icount parity else if status amp FRAME port gt icount frame else if status amp OVERRUN port gt icount overrun Eies status amp port gt read_status_mask if status amp BREAK flag TTY_BREAK else if status amp PARITY flag TTY_PARITY else if status amp FRAME flag TTY_FRAME if uart_handle_sysrq_char port ch continue uart_insert_char port status OVERRUN ch flag spin_unlock amp port gt lock
123. rruptible wakes up all non exclusive tasks and only one exclusive task gt wake_up_all wake_up_interruptible_all 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 gt The scheduler doesn t keep evaluating the sleeping condition define __wait_event wq condition do DEFINE_WAIT __wait for G 4 prepare_to_wait amp wq amp __wait TASK_UNINTERRUPTIBLE if condition break schedule finish_wait amp wq amp __wait while 0 CCC CC LF A Fo FC A EF Ff Gs gt wait_event_interruptible queue condition gt The process is put in the TASK_INTERRUPTIBLE state gt wake_up_interruptible amp queue gt All processes waiting in queue are woken up so they get scheduled later and have the opportunity to reevaluate the condition Interrupt Management Gs gt Defined in include linux interrupt h gt int request_irq unsigned int irq irq_handler_t handler unsigned long irq_flags const char devname void dev_id irq is the requested IRQ channel handler is a pointer to the IRQ handler irq_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_irq wh
124. ry gt Only available on x86 so far Linux 3 6 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 gt Both have a significant overhead Only use them in development Useful general purpose kernel APIs Oo gt In linux string h gt Memory related memset memcpy memmove memscan memcmp memchr gt String related strcpy strcat strcmp 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_strtoll gt Other string functions sprintf sscanf gt Convenient linked list facility in Linux list h gt Used in thousands of places in the kernel gt Add a 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 Remo
125. s 0 start 0x00206000 end 0x002060FF flags IORESOURCE_MEM 3 fil start UART1_MINT_RX end UART1_MINT_RX flags IORESOURCE_IRQ Fy gt When a 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 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 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 platform_data LE gt The i MX serial port driver defines the following structure to be passed through platform_data struct imxuart_platform_data int xinit struct platform_ device pdev void exit struct platform_ device pdev unsigned int flags void irda_enable int enable unsigned int irda_inv_rx 1 unsigned int irda_inv_tx 1 unsigned short
126. s Debugging and tracing Os 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 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 gt They take a pointer to struct device as first argument covered later 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 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 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 gt Each message is associated to a prior
127. s bottomley git ogg gt Get familiar with git by contributing to a real project the Linux kernel gt Send your patches to the maintainers and mailing lists Gs Last slides Gr gory Cl ment Michael Opdenacker Maxime Ripard S bastien Jan Thomas Petazzoni Free Electrons Copyright 2004 2013 Free Electrons Creative Commons BY SA 3 0 license Corrections suggestions contributions and translations are welcome Free Electrons Embedded Linux Developers gt Clean up files that are easy to retrieve remove downloads gt Generate an archive of your lab directory Qo Please take a few minutes to rate this training session by answering our on line survey http free electrons com doc training linux kernel survey html Thank you And may the Source be with you
128. s 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 gt Documentation power in the Linux kernel sources gt Will give you many useful details v http lesswatts org gt Intel effort trying to create a Linux power saving community gt Mainly targets Intel processors gt Lots of useful resources gt http wiki linaro org WorkingGroups PowerManagement gt Ongoing developments on the ARM platform v Tips and ideas for prolonging battery life gt http j mp fVdxKh gt Suspend and resume your Linux system gt Change the CPU frequency of your system LE Kernel Advice and Resources Gr gory Cl ment Michael Opdenacker Maxime Ripard S bastien Jan Thomas Petazzoni Free Electrons Copyright 2004 2013 Free Electrons Creative Commons BY SA 3 0 license Corrections suggestions contributions and translations are welcome Free Electrons Embedded Linux Developers Advice gt If 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 LE gt If you have
129. s like drivers with several source files or drivers in their own subdirectory etc LE gt The old school way gt Before making your changes make sure you have two kernel trees cp a linux 3 5 5 linux 3 5 5 patch gt Make your changes in linux 3 5 5 patch gt Run make distclean to keep only source files gt Create a patch file diff Nur linux 3 5 5 linux 3 5 5 patch gt patchfile gt Not convenient does not scale to multiple patches gt The new school ways gt Use quilt tool to manage a stack of patches gt Use git revision control system used by the Linux kernel developers Qo hello_param c include lt linux init h gt include lt linux module h gt include lt linux moduleparam h gt MODULE_LICENSE GPL A couple of parameters 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 static int __init hello_init void int i for i 0 i lt howmany i pr_alert d Hello s n i whom return 0 static void __exit hello_exit void pr_alert Goodbye cruel s n whom module_init hello_init module_exit hello_exit Thanks to Jonathan Corbet for the example Example available on http free electrons com doc c hello_param c Oo include lt linux moduleparam h gt module_param name name o
130. s 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 hundreds of people contribute to each kernel release individuals or companies big and small gt The whole Linux sources are Free Software released under the GNU General Public License version 2 GPL v2 gt For the Linux kernel this basically implies that gt When you receive or buy a device with Linux on it you should receive the Linux sources with the right to study modify and redistribute them gt When you produce Linux based devices you must release the sources to the recipient with the same rights with no restriction 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 gt See the arch directory in the kernel sources gt Minimum 32
131. see the code gt Eventually calls rest_init Q static noinline void __init_refok rest_init void __releases kernel_lock int pid rcu_scheduler_starting We need to spawn init first so that it obtains pid 1 however the init task will end up wanting to create kthreads which if we schedule it before we create kthreadd will OOPS kernel_thread kernel_init NULL CLONE_FS CLONE_SIGHAND numa_default_policy pid kernel_thread kthreadd NULL CLONE_FS CLONE_FILES rcu_read_lock kthreadd_task find_task_by_pid_ns pid amp init_pid_ns rcu_read_unlock complete amp kthreadd_done The boot idle thread must execute schedule at least once to get things moving init_idle_bootup_task current preempt_enable_no_resched schedule preempt_disable Call into cpu_idle with preempt disabled cpu_idle Oo gt kernel_init does two main things gt Call do_basic_setup gt Once kernel services are ready start device initialization Linux 2 6 36 code excerpt static void __init do_basic_setup void cpuset_init_smp usermodehelper_init init_tmpfs 0 driver_init init_irq_proc do_ctors do_initcalls gt Call init_post Q Calls pluggable hooks registered with the macros below Advantage the generic code doesn t have to know about them A pure initcall has no dependencies on anything else and purely
132. store instructions 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 unsigned long start unsigned long len char name gt Tries to reserve the given region and returns NULL if unsuccessful gt request_region 0x0170 8 idei gt void release_region unsigned long start unsigned long len 0000 001f dmat 0020 0021 pic1 0040 0043 timerO 0050 0053 timeri 0070 0077 rtc 0080 008f dma page reg 00a0 00a1 pic2 00c0 00df dma2 00f0 00ff fpu 0170 0177 idel 01f0 01f7 ideOd 0376 0376 idel 03f6 03f6 ide0 03f8 03ff serial 0800 087f 0000 00 1f 0 LE gt Functions to read write bytes b word w and longs 1 to 1 O ports gt unsigned in bwl unsigned port gt void out bwl value unsigned long port gt And the strings variants often more efficient than the corresponding C loop if the processor supports such operations gt void ins bwl unsigned port void addr unsigned long count gt void outs bwl unsigned port void addr unsigned long count gt Examples gt read 8 bits gt oldlcr inb baseio UART_LCR gt write 8 bits gt outb MOXA_MUST_ENTER_ENCHANCE baseio UART_LCR Oo gt Functions equivalent to request_region and release_region but for I O memory gt struct resource request_mem_r
133. story diff git rnel fork c b kernel fork c index 5449efb bb762b4 100644 file a kernel fork c b kernel fork c 981 6 981 8 static struct task_struct copy_process unsigned long clone_flags if p goto fork_out ftrace_graph_init_task p rt_nutex_init_task p ifdef CONFIG PROVE LOCKING 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 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 gt The list of existing tags can be found using gt git tag 1 gt To check out a working copy of the repository at a given tag gt git checkout lt tagname gt gt To get the list of changes between a given tag and the latest available version gt git log v2 6 30 master gt List of changes with diff on a given file between two tags gt git log p v2 6 29 v2 6 30 MAINTAINERS gt With gitk gt gitk v2 6 30 master 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 Unlik
134. support must be associated with the configuration option of the board obj CONFIG_MACH_USB_A9263 board usb a9263 0 gt This is done in arch arm mach at91 Makefile obj y irq o gpio o obj CONFIG_AT91_PMC_UNIT clock o obj y leds o obj CONFIG_PM pm o obj CONFIG_AT91_SLOW_CLOCK pm_slowclock o gt The Makefile also tells which files are compiled for every AT91 CPU gt And which files for our particular CPU the AT91SAM9263 obj CONFIG_ARCH_AT91SAM9263 at91sam9263 0 at91sam926x_time o at91sam9263_devices o sam9_smc o LE gt Each board is defined by a machine structure gt The word machine is quite confusing since every mach directory contains several machine definitions one for each board using a given CPU type gt For the Calao board at the end of arch arm mach at91 board usb a926x c MACHINE_START USB_A9263 CALAO USB_A9263 Maintainer calao systems phys_io AT91_BASE_SYS io_pg_offst AT91_VA_BASE_SYS gt gt 18 amp Oxfffc boot_params AT91_SDRAM_BASE 0x100 timer amp at91sam926x_timer map_io ek_map_io init_irq ek_init_irq init_machine ek_board_init MACHINE_END gt MACHINE_START and MACHINE_END gt Macros defined in arch arm include asm mach arch h gt They are helpers to define a struct machine_desc structure stored in a specific ELF section gt Several machine _desc structures can be defined in a kernel which means that the kernel ca
135. symbolic link a character or block device gt 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 int foo_release struct inode i struct file f gt Called when user space closes the file LE gt ssize t foo_read struct file f __user char xbuf size_t sz loff_t 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 Oo gt ssize_t foo_write struct file f __user const char buf size_t sz loff_t 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 gt Kernel code isn t allowed to directly access user space memory using memcpy or direct pointer dereferencing gt Doing so
136. t Scanners gt Graphics drivers used by X org gt Some USB devices gt For these devices the kernel only provides a mechanism to access the hardware the driver is implemented in userspace gt File systems gt Yv v yv gt The common Linux filesystems for block devices ext2 ext3 ext4 Less common filesystems XFS JFS ReiserFS GFS2 OCFS2 Btrfs CD ROM filesystems 1509660 UDF DOS Windows filesystems FAT and NTFS Pseudo filesystems proc and sysfs Miscellaneous filesystems with amongst other flash filesystems such as JFFS2 UBIFS SquashFS cramfs Network filesystems with mainly NFS and SMB CIFS gt Kernel hacking gt Debugging features useful for kernel developers Compiling and installing the kernel for the host system LE gt make gt in the main kernel source directory gt Remember to run make j 4 if you have multiple CPU cores to speed up the compilation process 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 All kernel modules spread over the kernel source tree as ko files Gs gt make install gt Does the installation for the host system by default so needs to be ru
137. t channel gt 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 gt Tasklet gt Process the data gt Wake up processes waiting for the data gt Device driver gt When the device is no longer opened by any process unregister the interrupt handler gt Adding read capability to the character 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 Concurrent Access to Resources LE 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 and for the shared resources use locking Process 1 Process 2 Success Try Aga
138. t the DMA does not access to the CPU cache so one 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 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 gt To make sure you ve got enough RAM for big DMA transfers gt Example assuming you have 32 MB of RAM and need 2 MB for DMA gt Boot your kernel with mem 30 gt The kernel will just use the first 30 MB of RAM Driver code can now reclaim the 2 MB left v dmabuf ioremap Ox1e00000 Start 30 MB 0x200000 Size 2 MB 5 gt You can also use mem to reserve specific RAM areas for specific devices DSP video device gt Panda board example gt mem 456M 0x80000000 mem 512M 0xA0000000 LE 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 gt The Y
139. te the mode modification for the byte size parameter switch termios gt c_cflag amp CSIZE case CS5 mode ATMEL_US_CHRL_5 break case CS6 mode ATMEL_US_CHRL_6 break ere default mode ATMEL_US_CHRL_8 break Compute the mode modification for the stop bit if termios gt c_cflag amp CSTOPB mode ATMEL_US_NBSTOP_2 Compute the mode modification for parity if termios gt c_cflag amp PARENB Mark or Space parity if termios gt c_cflag amp CMSPAR if termios gt c_cflag amp PARODD mode ATMEL_US_PAR_MARK else mode ATMEL_US_PAR_SPACE else if termios gt c_cflag amp PARODD mode ATMEL_US_PAR_ODD else mode ATMEL_US_PAR_EVEN else mode ATMEL_US_PAR_NONE Compute the mode modification for CTS reporting if termios gt c_cflag amp CRTSCTS mode ATMEL_US_USMODE_HWHS else mode ATMEL_US_USMODE_NORMAL Free Electrons Kernel drivers and embedded Linux development consulting training and support http free electrons com 388 496 Compute the read_status_mask and ignore_status_mask according to the events we re interested in These values are used in the interrupt handler port gt read_status_mask ATMEL_US_OVRE if termios gt c_iflag amp INPCK port gt read_status_mask ATMEL_US_FRAME ATMEL_US_PARE if termios gt c_iflag amp BRKINT PARMRK port gt read_status_mask ATMEL_US_RXBRK port
140. th 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 LE 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 userspace daemon gt This infrastructure can be controlled from sys devices system cpu cpu lt n gt cpufreq gt CPU support code in architecture dependent files Example to read arch arm plat omap cpu omap c gt Must implement the operations of the cpufreq_driver structure and register them using cpufreq_register_driver gt gt gt gt gt See init for initialization exit for cleanup verify to verify the user chosen policy setpolicy or target to actually perform the frequency change Documentation cpu freq for useful explanations gt PM QoS is a framework developed by Intel introduced in 2 6 25 gt It all
141. the bootloader gt Identifies the processor and machine gt Initializes the console gt Initializes kernel services memory allocation scheduling file cache gt Creates a new kernel thread future init process and continues in the idle loop gt Initializes devices and execute initcalls LE Porting the Linux Kernel to an ARM Board Gr gory Cl ment Michael Opdenacker Maxime Ripard S bastien Jan Thomas Petazzoni Free Electrons Copyright 2004 2013 Free Electrons Creative Commons BY SA 3 0 license Corrections suggestions contributions and translations are welcome Free Electrons Embedded Linux Developers 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 the methods to port the Linux kernel to a new board are therefore very architecture dependent gt For example PowerPC and ARM are very different gt PowerPC relies on device trees to describe hardware details gt ARM relies on source code only but the migration to device tree is in progress gt This presentation is focused on the ARM architecture only v In the source tree each architecture has its own directory gt arch arm for the ARM architecture v This directory contains generic ARM code gt boot common configs kernel lib mm
142. the corresponding file operations gt Writing a simple character driver to write data to the serial port gt On your workstation checking that transmitted data are received correctly gt Exchanging data between userspace and kernel space gt Practicing with the character device driver API gt Using kernel standard error codes Processes and scheduling LE 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 gt The kernel represents each thread running in the system by a structure of type 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 Same process after pthread_create Process after fork EXIT ZOMBIE Task terminated but its resources Thread Created are not freed yet Waiting for its by fork or parent to acknowledge pthread_create its death
143. tion gt x for hexadecimal representation v Expose a binary blob as a file in DebugFS gt struct dentry debugfs_create_blob const char name mode_t mode struct dentry parent struct debugfs_blob_wrapper blob v Also possible to support writable DebugFS files or customize the output using the more generic debugfs_create_file function 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 preferred gt Using printk The pr_ and dev_ functions are preferred LE gt Allows to run multiple debug rescue commands even when the kernel seems to be in deep trouble gt On PC Alt SysRq lt character gt gt On embedded break character on the serial line lt character gt gt Example commands gt n makes RT processes nice able t shows the kernel stack of all sleeping processes gt w shows the kernel stack of all running processes gt b reboot the system gt You can even register your own Y gt Detailed in Documentation sysrq txt 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
144. transceiver_delay gt The MX1ADS board code instantiates such a structure static struct imxuart_platform_ data uarti_pdata flags IMXUART_HAVE_RTSCTS gt The uart_pdata structure is associated to the platform_device in the MX1ADS board file the real code is slightly more complicated struct platform_device mxiads_uarti name imx uart dev platform_data amp uarti_pdata Fa resource imx_uarti_ resources area 3 The driver can access the platform data static int 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 Erai gt Each framework defines a structure that a device driver must register to be recognized as a device in this framework gt uart_port for serial port netdev for network devices 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 Or by storing a reference to the appropriate framework structure Gs gt i MX serial driver imx_port is a subclass of uart_port struct imx_port struct uart_port port struct timer_list timer unsigned int old_status int txirq rxirq rtsirq unsigned int have_rtscts 1 Paai
145. tty_flip_buffer_push port gt state gt port tty spin_lock amp port gt lock Os gt Set using the set_mctrl operation gt The mctrl argument can be a mask of TIOCM_RTS request to send TIOCM_DTR Data Terminal Ready TIOCM_OUT1 TIOCM_OUT2 TIOCM_LOOP enable loop mode gt If a bit is set in mctr1 the signal must be driven active if the bit is cleared the signal must be driven inactive gt Status using the get_mctrl operation gt Must return read hardware status and return a combination of TIOCM_CD Carrier Detect TIOCM_CTS Clear to Send TIOCM_DSR Data Set Ready and TIOCM_RI Ring Indicator LE foo_set_mctrl struct uart_port uart u_int mctrl unsigned int control 0 mode 0 if mctrl amp TIOCM_RTS control ATMEL_US_RTSEN else control ATMEL_US_RTSDIS if mctrl amp TIOCM_DTS control ATMEL_US_DTREN else control ATMEL_US_DTRDIS __raw_writel port gt membase REG_CTRL control if mctrl amp TIOCM_LOOP mode ATMEL_US_CHMODE_LOC_LOOP else mode ATMEL_US_CHMODE_NORMAL __raw_writel port gt membase REG_MODE mode LE foo_get_mctrl struct uart_port uart u_int mctrl unsigned int status ret 0 status __raw_readl port gt membase REG_STATUS The control signals are active low if status amp ATMEL_US_DCD ret TIOCM_CD if status amp ATMEL_US_CTS ret TIOCM_CTS if status amp ATMEL_US_DS
146. unsigned read bwl void addr void write bwl unsigned val void addr gt To do raw access without endianness conversion unsigned __raw_read bwl void addr void __raw_write bwl unsigned val void addr gt Example gt 32 bits write __raw_writel i lt lt KS8695_IRQ_UART_TX membase KS8695_INTST 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 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 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
147. upt 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 gt Others are defined in include linux gfp h 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 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 Allocated 512 bytes object AKiB page Free 1024 bytes object Objects of 1024 byte 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 original well proven allocator in Linux 2 6 gt SLOB much simpler More space efficient
148. 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 A normal driver should not need any non exported function GPL Module A void func4 EXPORT SYMBOL GPL func4 func1 func2 FETE func3 void func1 func4 void func2 EXPORT_SYMBOL func2 void func3 EXPORT_SYMBOL_GPL func3 func1 func1 func2 func2 func3 func3 func4 func4 GPL Module C func1 func2 func3 func4 Gs 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 LE 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
149. user buf size_t count loff_t ppos The acme_buf address corresponds to a device 1 0 memory area of size acme_bufsize obtained with ioremap int remaining_size transfer_size remaining_size acme_bufsize int xppos bytes left to transfer if remaining_size 0 All read returning 0 End Of File return 0 Size of this transfer transfer_size min_t int remaining_size count if copy_to_user buf to acme_buf ppos from transfer_size return EFAULT else Increase the position in the open file ppos transfer_size return transfer_size Piece of code available at http free electrons com doc c acme c Q static ssize_t acme_write struct file file const char __user buf size_t count loff_t ppos int remaining_bytes Number of bytes not written yet in the device remaining_bytes acme_bufsize ppos if count gt remaining_bytes Can t write beyond the end of the device return EI0 if copy_from_user acme_buf ppos to buf from count return EFAULT else Increase the position in the open file ppos count return count x Piece of code available at http free electrons com doc c acme c gt long unlocked_ioctl struct file f unsigned int cmd unsigned long arg gt Associated to the ioct1 system call gt Called unlocked because it didn t hold the Big
150. v v kernel DMA utilities can take care of Either allocating a buffer in a cache coherent area Or making sure caches are flushed when required Managing the DMA mappings and IOMMU if any See Documentation DMA API txt for details about the Linux DMA generic API Most subsystems such as PCI or USB supply their own DMA API derived from the generic one May be sufficient for most needs 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 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 Some optimizations also available gt The recommended solution Yv Yv v LE gt The kernel takes care of both buffer allocation and mapping include lt asm dma mapping h gt void Output buffer address dma_alloc_coherent struct device dev device structure size_t size Needed buffer size in bytes dma_addr_t handle Output DMA bus address gfp t gfp Standard GFP flags J void dma_free_coherent struct device dev size_t size void cpu_addr dma_a
151. ve 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 Oo 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 LE Define the global list static LIST_HEAD tc_list gt From drivers misc atmel_tclib c static int __init tc_probe struct platform_device pdev struct atmel_tc tc tc kzalloc 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 unsigned block const char name struct atmel_tc tc Iterate over the list elements list_for_each_entry tc amp tc_list node Do something with tc I O Memory and Ports gt MMIO gt Same address bus to address memory and I 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 Physical Memory Separate 1 0 address space address space accessed with accessed with specific instructions normal load
152. ve parts of the virtual address space of a program mapped to the contents of a file v v Particularly useful when the file is a device file 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 start end 7 4516d04000 7 4516d06000 7 4516d07000 7 4516d0b000 7 4518728000 7 451874f000 7 451874f000 7 451894f000 7 451894f000 7 4518951000 7 4518951000 7 4518952000 7 451da4f000 7 451dc3f 000 7f451de3e000 7f451de41000 7f451de41000 7f451de4c000 perm rw s rw s r xp D Pp rw p r xp L lt 2 rw p offset major minor inode mapped file name 1152a2000 00 05 8406 120f9e000 00 05 8406 00000000 00027000 00027000 00029000 00000000 001ef000 0012000 08 08 08 08 08 08 08 oi 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 anan N D N D Process Access Virtual Memory Access Physical Address Physical Virtual Physical Address Address Space Space LE gt Open the device file gt Call the mmap system call see man mmap for details void
153. vers 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 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 boot config 3 2 0 31 generic 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 dr
154. vice management multimedia etc gt linux conf au http linux org au conf gt gt In Australia New Zealand Features a few presentations by key kernel hackers gt Don t miss our free conference videos on http free electrons com community videos conferences gt ARM Linux project http www arm linux org uk gt Developer documentation http wwuw arm linux org uk developer gt linux arm kernel mailing list http lists infradead org mailman listinfo linux arm kernel gt FAQ http wwuw arm linux 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 LE Introduction to Git Gr gory Cl ment Michael Opdenacker Maxime Ripard S bastien Jan Thomas Petazzoni Free Electrons Copyright 2004 2013 Free Electrons Creative Commons BY SA 3 0 license Corrections suggestions contributions and translations are welcome Free Electrons Embedded Linux Developers gt 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 gt gt gt
155. w 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 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 LE 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 cpuidle files under arch arm gt See Documentation cpuidle in kernel sources gt http wuw lesswatts org projects powertop gt Wi
156. 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 c LE 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 1ib 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_SP128AR USB_DEVICE VENDOR_ID_LONGSHINE PRODUCT_ID_LCS8138TX USB_DEVICE VENDOR_ID_0Q0 PRODUCT_ID_RTL8150 USB_DEVICE VENDOR_ID_ZYXEL PRODUCT_ID_PRESTIGE MODULE_DEVICE_TABLE usb rt18150_table 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 inhe
157. ysfs usually mounted on sys Representation of the system as a set of devices and buses Information about these devices Linux versioning scheme and development process 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 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 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 major changes in existing subsystems gt So far there was no need to create a new development branch such as 2 7 which would massively break compatibility with the stable branch gt Thanks to this more features are released to users at a faster pace Since 2 6 14 the kernel developers agreed on the following development model gt After the release of a 2 6 x version a two weeks merge window opens during which major additions are merged The merge window is closed by the release of test version 2 6 x 1 rel The bug fixing period opens for 6 to 10 we

Download Pdf Manuals

image

Related Search

Related Contents

Service Manual  IBM DR550 User's Manual  Da instalação à impressão  Manual VDR-1500 HDD  Samsung GT-S8500 Manual de Usuario  NeatWork: A user guide  Manual de usuario VideoMeeting Tablet/Smartphone  取扱説明書DL  USM36シリーズ  

Copyright © All rights reserved.
Failed to retrieve file