09292012-02-final
Post on 01-Nov-2014
106 Views
Preview:
TRANSCRIPT
2011 資訊軟體技術人才培訓
Android多核心嵌入式多媒體系統設計與實作
Linux Device Driver架構簡介
賴槿峰 (Chin-Feng Lai) Assistant Professor, institute of CSIE, National Ilan University
Sep 29th 2011 © 2011 MMN Lab. All Rights Reserved
1
• Introduction
• The Role of Driver
• Device Driver Concepts
• Driver Methods
• Module Utilities
• Module Build Infrastructure
• Lab
2
Outline
•Introduction •The Role of Driver •Device Driver Concepts •Driver Methods •Module Utilities •Module Build Infrastructure •Lab
3 3
Hardware Bootloader
Linux Kernel
(driver)
File
System
Introduction
• Android system and Embedded system
4
• Device Driver in Linux android Kernel
• distinct “black boxes” that make a particular piece of hardware
respond to a well-defined internal programming interface
• hide the complexity and variability of the hardware device from
the user
• map standardized calls to device-specific operations that act on
real hardware
• Android is a Linux-based architecture. In addition to the
original Linux driver, Android need other additional device
driver, like Android Logger, Binder, Low Memory killer,
Power Management for android(wakelock), ASHMEM, etc.
5
Introduction
• Android additional kernel driver
6
Introduction
driver Features 2.6.23 2.6.35 2.6.27 2.6.29
Alarm Driver
Android Logger (logcat)
Low Memory Killer
Wakelock (power management)
USB Gadget
ASHMEM (shared memory)
PMEM (memory allocator)
X86 Support
driver/staging/Android
•Introduction •The Role of Driver •Device Driver Concepts •Driver Methods •Module Utilities •Module Build Infrastructure •Lab
7 7
• General Driver for Linux kernel
• A software layer above hardware
• Provide method to operate hardware
• Driver provide mechanism , Not policy
• Provide user more flexible operation
8
The Role of Driver
• Main Driver Type in Linux
• General GPIO Driver
– Target specific GPIO driver
• Audio Driver
– alsa、oss
• Video Driver
– v4l、v4l2、framebuffer
• Storage Driver
– Support for mass storage access
• Network Driver
– Support network routing and buffer handling
• USB
– HID、Mass Storage、Printer、Hub、Video、Wireless Controller
9
The Role of Driver
• Linux Driver Architecture
Audio Driver
User Application
Hardware
System Call Interface
Virtual File System (VFS)
Video Driver
Device interface
open , ioctl , close ,read , write
10
GPIO Driver
Hardware
Kernel
Android HAL
Android Framework
Android Application User Mode
Kernel Mode
Hardware
Linux Embedded system Android Embedded system
The Role of Driver
• General GPIO Driver
• The way we driver the general purpose input output hardware
• The GPIO driver usually via hardware address mapping to
control I/O status
• GPIO drivers usually are character device type
• Audio Driver
• The sound subsystem manage all the sound feature in linux
kernel
• There are different type of hardware specification support in
kernel source tree , which locate in kernel/sound
• There are two main group support sound system , ex : alsa , oss
11
The Role of Driver
• Video Driver
• Linux Video Device Driver is a middle role of user program and
hardware
• The Video Driver is responsible for pushing decoded raw data to
display interface
• The development of Linux video driver can classify by two group ,
the one is the video for Linux series(V4L 、V4L2) and
Framebuffer
12
The Role of Driver
•Introduction •The Role of Driver •Device Driver Concepts •Driver Methods •Module Utilities •Module Build Infrastructure •Lab
13 13
14
Device Driver Concepts
• Process management
• Determinate process’s life cycle, control process I/O and
distribute CPU resource for scheduler.
• Memory Management
• Communicate with memory management subsystem , ex: malloc
/ free
• File System
• Kernel support multiple file system
• Device Control
• System call will be mapping to corresponding hardware device,
every device has unique code to operate , call device driver
• Networking
• The kernel provide send/receive mechanism to handle
incoming data
15
Device Driver Concepts
• Loadable Modules
• extend at runtime the set of features offered by the kernel
• offers support for quite a few different types (or classes) of
modules
• Each module is made up of object code (not linked into a
complete executable) that can be dynamically linked to the
running kernel by the insmod program and can be unlinked by
the rmmod program
16
Device Driver Concepts
• Classes of Devices and Modules
• The Linux way of looking at devices distinguishes between three
fundamental device types
• char module
• block module
• network module
• the programmer can choose to build huge modules mplementing
different drivers in a single chunk of code
• Good programmers usually create a different module for each
new functionality they implement, because decomposition is a
key element of scalability and extendability
17
Device Driver Concepts
• Character Devices Modules
• A character device is one that can be accessed as a stream of
bytes
• Store data through device file
• Implements at least the open、close、read、write system calls
• EX : Console (/dev/console) 、 Serial Ports (/dev/ttyS0)
• char devices that look like data areas, and you can move back
and forth in them(applications can access the whole acquired
image using mmap or lseek)
18
Device Driver Concepts
• Block Devices Modules
• block devices are accessed by file system nodes in the /dev
directory
• Like a char device, each block device is accessed through a
filesystem node
• In linux, block and char device only differ in the way of data
management internally by the kernel
• a block device can only handle I/O operations that transfer one
or more whole blocks (usually 512 bytes in length)
19
Device Driver Concepts
• Network Interface
• Any data transmission must pass through the interface
• A network interface is in charge of sending and receiving data
packages. A network driver knows nothing about individual
connections; it only handles packets.
• Network driver provide queue function to handle unexpectedly
data transfer
• The Unix way to provide access to interfaces is still by assigning
a unique name to them (such as eth0)
• Communication between the kernel and a network device driver
is completely different from that used with char and block drivers.
Instead of read and write, the kernel calls functions related to
packet transmission.
20
Device Driver Concepts
•Introduction •The Role of Driver •Device Driver Concepts •Driver Methods •Module Utilities •Module Build Infrastructure •Lab
21 21
• Introduce to basic mechanism for communicating with a
device driver from a user space program
• Device nodes on your file system provide the glue
between your userspace application and the device
driver
• Major Number & Minor Number
• Driver File System Operations
• Device Nodes and mknod
22
Driver Methods
• Major Number & Minor Number
• Char devices are accessed through names in the file system .
Those names are called special files or device files or simply
nodes of the file system tree
• major : 12-bits & minor : 20-bits (Kernel 2.6)
• Major number (0~255)
• The major number identifies the driver associated with the device
• Minor number (0~255)
• The minor number is used only by the driver specified by the minor
number.
23
Driver Methods
• Major Number & Minor Number
24
C:char driver node B:Block driver node P:Pipe noode
Driver Methods
• Major Number & Minor Number
• Registered devices are visible in /proc/devices
– Can be used to find free Major Num
– # cat /proc/devices
• A list of the most common devices can be found in
– # kernel_source/Documentation/devices.txt
• Major number : 60-63 、120-127、240.254
– LOCAL/EXPERIMENTAL use
25
Driver Methods
• Major Number & Minor Number
• In the Kernel, dev_ttype is used to hold device numbers(major &
minor)
– defined in <linux/types.h>
• dev_t data type (Major and Minor Num)
– Define in <linux/kdev_t.h>
– Kernel data type to represent a major / minor number pair
– Linux 2.6: 32 bit size (major: 12 bits, minor: 20 bits)
• To obtain the major or minor parts of a dev_t, use:
– MAJOR(dev_tdev);
– MINOR(dev_tdev);
• Major and minor numbers turn them into a dev_t, use:
– MKDEV(int major_num, int minor_num);
26
Driver Methods
• Major Number & Minor Number - Allocating and Freeing
Device Numbers
• register_chrdev_region(dev_tfirst, unsigned intcount, char*name);
– first:Thebeginning device number of the range you would like to
allocate
– count: The total number of contiguous device numbers
– name: Device Name
• alloc_chrdev_region(dev_t*dev,unsignedintfirstminor, unsigned
intcount,char*name)
– dev: An output-only parameter which hold the first number in your
allocated range on successful completion
– first:The requested first minor number to use; it is usually 0.
• Free Device Number
– void unregister_chrdev_region(dev_tfirst,unsignedintcount);
27
Driver Methods
• Driver File System Operation
• Most of the fundamental driver operations involve three
important kernel data structures
– file_operations
– file
– and inode
• After the device driver is loaded into a live kernel, the first action
we must take is to prepare the driver for subsequent operations
– open and release method
– read and write method
– ioctl
28
Driver Methods
• Driver File System Operation
• File_Operations
– Define in <linux/fs.h>
– File data structure just like an Object
– File_operations just like a method in Object
– File_operations data structure usually name as “xxx_fops”
– Every method must point to specific function
29
Driver Methods
• Driver File System Operation • File_Operations - File Operations corresponding to user-space I/O
function
30
Driver Methods
Device File
System interface call
File operations open , ioctl ,
release ,read ,write
• Define on linux/fs.h • Implement file_operaions on your moduls
/*NCKU MMN LAB SAMPLE CODE*/ #include <linux/fs.h> struct memory_dev *memory_devices; int memory_major = 0; struct file_operations memory_fops = { .read = memory_read, .write = memory_write, .open = memory_open, .release = memory_release, .owner = THIS_MODULE, }
• Driver File System Operation
• File structure
– Define in <linux/fs.h>
– File represent open file
– Every open file mapping a specific struct file in kernel-space
– file refers to the structure and filp to a pointer to the structure.
– Example:
int memory_open(struct inode *inode, struct file *filp)
31
Driver Methods
• Driver File System Operation
• File structure
– The most important fields of struct file are shown here, let we face some
real C code and describe the field in more detail
– struct file_operations *f_op
• The operations associated with the file. The kernel assigns the pointer
as part of its implementation of open and then reads it when it needs to
dispatch any operations
– unsigned int f_flags
• Define in “kernel_source/include/linux/fcntl.h”
• A driver should check the flag
(O_RDONLY,、O_NONBLOCK、O_SYNC)
– mode_t f_mode
• The file mode identifies the file as either readable or writable(or both)
32
Driver Methods
• Driver File System Operation
• inode structure
– The inode structure is used by the kernel internally to represent files.
– it is different from the file structure
– The inode structure contains a great deal of information about the file – Example:major and minor number etc
– dev_t i_rdev;
• For inodes that represent device files, this field contains the actual
device number.
– struct cdev *i_cdev;
• struct cdev is the kernel’s internal structure that represents char
devices; this field contains a pointer to that structure when the inode
refers to a char device file.
33
Driver Methods
• Driver File System Operation
• Operation Flow
– A module runs in kernel space, whereas applications run in user space. This
concept is at the base of operating systems theory.
34
Driver Methods
Events User space Kernel space
Load module insmod Module_init()
Open device open open()
Read device Ioctl Ioctl() -> read()
Write device Ioctl Ioctl() -> write()
Close device Close release()
Remove device rmmod Module_exit()
File_operation
• Driver File System Operation
• Open and Release method
– The kernel keeps a counter of how many times a file structure is being used
– they just increment the counter , when use open method to creates a new
file structure
– The close system call executes the release method only when the counter
for the file structure drops to 0,
– Define in “kernel_source/include/linux/module.h”
• MOD_INC_USE_COUNT (increase the counter)
• MOD_DEC_USE_COUNT (decrease the counter)
35
Driver Methods
• Driver File System Operation
• Open method
– Check for device-specific errors
– Initialize the device if it is being opened for the first time
– Update the f_op pointer, if necessary
– Allocate and fill any data structure to be put in filp->private_data
– Check major and minor number”
• Prototype
– int (*open)(struct inode *inode, struct file *filp);
36
Driver Methods
• Driver File System Operation
• release method
– device_close() or device_release()
– Deallocate anything that open allocated in filp->private_date
– Shut down the device on last close
• Prototype
– int memory_release(struct inode *inode, struct file *filp)
37
Driver Methods
• Driver File System Operation
• Before read and write method - Kmalloc
– Memory management in Linux kernel
– A call to kmalloc attempts to allocate size bytes of memory
• void *kmalloc (size_t size, int flags);
– To free a block of memory
• void kfree(void *ptr);
– Flag define in “kernel_source/include/linux/slab.h”
– GFP_ATOMIC
• Used to allocate memory from interrupt handlers and other code
outside of a process context Never sleeps.
– GFP_KERNEL
• Normal allocation of kernel memory. May sleep
– GFP_USER
• – Used to allocate memory for userspace pages; it may sleep
38
Driver Methods
• Driver File System Operation
• read and write method
– ssize_t read (struct file *filp, char __user *buff,size_t count, loff_t *offp)
– ssize_t write (struct file *filp, const char __user *buff,size_t count,
loff_t *offp)
» filp:file pointer
» buff : user buffer holding the data to be written or the empty buffer
where the newly read data should be placed. Finally
» count: size of the requested data transfer
» offp : “long offset type” object that indicates the file position the user
is accessing
39
Driver Methods
• Driver File System Operation
• read and write method
– Kernel can’t dereference directly from userspace
» User-space pointer may not be valid
» User-space memory is paged -> page fault
» It may provide an open doorway to access memory anywhere in the
system
– Define in “kernel_source/include/linux/uaccess.h”
» unsigned long copy_to_user
(void __user *to,const void *from,unsigned long count);
» unsigned long copy_from_user
(void *to,const void __user *from,unsigned long count);
40
Driver Methods
• Driver File System Operation
• read and write method
41
Driver Methods
• Driver File System Operation
• read method
– return value equals count -> transfer successfully
– return value is positive and less than count -> only part of the data has been
transferred
– return value is zero -> EOF
– return value is negative -> error, check <linux/error.h>
• write method
– return value equals count -> write successfully
– return value is positive and less than count ->only part of the data has been
written
– return value is zero -> nothing was written
– return value is negative -> error, check <linux/error.h>
42
Driver Methods
• Driver File System Operation
• ioctl method
– Most drivers need—in addition to the bility to read and write the device—the
ability to perform various types of hardware control via the device driver.
– Ioctl() system call provide device-specific command for device driver
– Prototypes of ioctl function
– In kernel space
» int (*ioctl) (struct inode *inode, struct file *filp,unsigned int cmd,
unsigned long arg);
– In User space
» int ioctl(int fd, unsigned long cmd, ...);
– Parameter
» inode:inode of the device file
» filp:file pointer of the device file
» cmd:the I/O command index number explained later
» arg:additional optional argument passed by user to driver
43
Driver Methods
• Driver File System Operation
• ioctl method
– The cmd magic numbers. See include/asm/ioctl.h and
documentation/ioctl-number.txt to avoid used magic numbers
– Fields in cmd parameter:type,number,direction, size
– Type(magic number)
» Just choose one number,This field is 8 bits wide (_IOC_TYPEBITS)
– Number(ordinal number)
» The ordinal (sequential) number. It’s eight bits (_IOC_NRBITS) wide
– Direction(The direction of data transfer)
» _IOC_NONE、_IOC_READ、_IOC_WRITE
» Data transfer is seen from the application’s point of view
– Size
» The size of user data
» The width of this field is architecture dependent,but is usually 13 or 14
bits
44
Driver Methods
• Driver File System Operation
• ioctl method
– Encode
» _IO (type, number)
» _IOR (type, number, datatype)
» _IOW (type, number , datatype)
» _IOWR (type, number , datatype)
– Decode
» _IOC_DIR (nr)
» _IOC_TYPE (nr)
» _IOC_NR (nr)
» _IOC_SIZE (nr)
45
Driver Methods
• Driver File System Operation
• ioctl method
– Return value
» The default error returned when invalid cmd parameter is sent is not
quite regulated
» POSIX: return –ENOTTY (inappropriate ioctl for device)
» The other way: return –EINVAL (invalid parameter)
– int access_ok(int type, const void *addr,unsigned long size);
– • Type
» The first argument should be either VERIFY_READ or
VERIFY_WRITE
– • Addr
» The addr argument holds a user-space address
– • Size
» size is a byte count.
46
Driver Methods
• Device Nodes and mknod
• A device node is a special file type in Linux that represents a
device
• Virtually all Linux distributions keep device nodes in a common
location, in a directory called /dev
• A dedicated utility is used to create a device node on a file
system. This utility is called mknod.
• Example:
– Host$ mknod /dev/mmn c 123 3
– Host$ ls -l /dev/mmn
– crw-r--r-- 1 root root 123, 3 Jul 14 2011 /dev/mmn
47
Driver Methods
Device type Major number Minor number Device name
• For more detail, please refer to the following information
and book.
48
Driver Methods
Linux Device Driver 3rd http://oreilly.com/catalog/linuxdrive3/book/index.csp
•Introduction •The Role of Driver •Device Driver Concepts •Driver Methods •Module Utilities •Module Build Infrastructure •Lab
49 49
• A number of small utilities are used to manage device
driver modules.(just for user space)
• Module Utilities are used to manage the insertion,
removal, and listing of device driver modules. We
covered the details of the module utilities used for these
functions.
• insmod
• lsmod
• modprobe
• depmod
• rmmod
• modinfo
50
Method Utilities
• Insmod
• The insmod utility is the simplest way to insert a module into a
running kernel. You supply a complete pathname, and insmod
does the work.
• Example:How to loads the module hello1.ko into the kernel.
– Host$ insmod /lib/modules/2.6.14/driver/examples/hello1.ko
• Many device driver modules can accept parameters to modify
their behavior Examples include enabling debug mode, setting
verbose reporting, or specifying module-specific options. The
insmod utility accepts parameters
51
Method Utilities
• Insmod
use insmod to insert our example module, and add the debug_enable option
Host$ insmod /lib/modules/.../examples/hello1.ko debug_enable=1
Hello Example Init - debug mode is enabled
Or, if we omit the optional module parameter:
Host$ insmod /lib/modules/.../examples/hello1.ko
Hello Example Init - debug mode is disabled
52
Method Utilities
/* Example Minimal Character Device Driver */ #include <linux/module.h> static int debug_enable = 0; /* Added driver parameter */ module_param(debug_enable, int, 0); /* and these 2 lines */ MODULE_PARM_DESC(debug_enable, "Enable module debug mode."); static int __init hello_init(void) static void __exit hello_exit(void) module_init(hello_init); module_exit(hello_exit); MODULE_AUTHOR("Chris Hallinan"); MODULE_DESCRIPTION("Hello World Example"); MODULE_LICENSE("GPL");
Driver module code
53
Method Utilities
• lsmod
• The lsmod utility is also quite trivial. It simply displays a
formatted list of the modules that are inserted into the kernel
Host$ lsmod
Module Size Used by
ext3 121096 0
jbd 49656 1 ext3
loop 12712 0
mmn 1414 0
• modprobe
• The A module depends on the B module. The modprobe utility
can discover this relationship and load the dependent modules in
the proper order. The following command loads both the A.ko
and B.ko driver modules:
– Host$ modprobe A
• modprobe can be used to remove modules, use parameter “-r”
– Host$ modprobe –r A
• The modprobe utility is driven by a configuration file called
modprobe.conf. This enables a system developer to associate
devices with device drivers
54
Method Utilities
• depmod
• The depmod utility plays a key role in this process. When
modprobe is executed, it searches for a file called modules.dep
in the same location where the modules are installed. The
depmod utility creates this module-dependency
• modules.dep contains a list of all the modules that the kernel
build system is configured for, along with dependency
information for each. It is a simple file format
• modules.dep is located on “/lib/module/2.6.xxxx”
55
Method Utilities
56
Method Utilities
• rmmod
• This utility is also quite trivial. It simply removes a module from a
running kernel
• It should be noted that, unlike modprobe, rmmod does not
remove dependent modules. Use modprobe -r for this.
Host$ rmmod hello1
Hello Example Exit
• modinfo
• Modules information contain full filename of the device driver
module, author, and license information
• These are simply tags for use by the module utilities and do not
affect the behavior of the device driver itself
57
Method Utilities
Host$ modinfo mmn filename: /lib/modules/.../char/examples/mmn.ko author: madraziw description: MMN lab say Hello World Example license: GPL vermagic: 2.6.28 ARMv7 gcc-3.4 Depends:parm: debug_enable:Enable module debug mode. (int) Host$
•Introduction •The Role of Driver •Device Driver Concepts •Driver Methods •Module Utilities •Module Build Infrastructure •Lab
58
59
Module Build Infrastructure
• A device driver must be compiled against the kernel on which it will execute. Although it is possible to load and execute kernel modules built against a different kernel version. The easiest way to do this is to build the module within the kernel's own source tree. This ensures that as the developer changes the kernel configuration, his custom driver is automatically rebuilt with the correct kernel configuration. It is certainly possible to build your drivers outside of the kernel source tree.
• When start lab time, we will describe more detail
information
•Introduction
•The Role of Driver
•Device Driver Concepts
•Driver Methods
•Module Utilities
•Module Build Infrastructure
•Lab
60 60
• Lab Purpose
• Learn how to write application program in the user space and
kernel module program in the kernel space and control LED
harware on the DevKit8000
• led_dev.c
• The led driver , must be added in kernel source , and built in module
type.
• led_test.c
• The led user-space program , you can type command to control led .
61
Lab
• LED Driver
• Edit led_dev.c in kernel source tree
• {source}/driver/misc/leddev.c
• Edit Makefile in misc folder
• {source}/driver/misc/Makefile
• Edit Kconfig in misc folder
• {source}/driver/misc/Kconfig
• kconfig Prototype • Config、tristate or bool、depend on
• default
• y:built‐in
• m:module
• n:no select
.
62
Lab
• kconfig .
63
Lab
config LEDDEV tristate “LED Driver” default n
• obj$(CONFIG_LEDDEV) += leddev.o
.
64
Lab - Makefile
• led_dev.c • Lab blank 1
– Fill the correct memory address
• Lab blank 2
– Register the device number use MINOR function
– The input parameter is the major/minor number data structure in inode .
• Lab blank 3
– gpio_fops , you must point to the mapping function.
• Lab blank 4
– gpio_dev , fill the correct file_operation data structure.
.
65
Lab
Blank 1 & 2
• The Control Register Address
• Get device number use MINOR function
66
Blank 3 & 4
• gpio_fops data structure
• gpio_dev data structure
67
• led_test.c
• The user-space control program
• Fill the blank , to open the correct device file in /dev/xxx
• Use arm-none-linux-gnueabi-gcc to compile this program
• arm-none-linux-gnueabi-gcc led_test.c –o led_test
.
68
Lab
• step
1. Back to source folder
2. Host$ cp
arch/arm/configs/omap3_devkit8000_defconfig .config
3. Host$ make menuconfig
4. Host$ make
5. Host$ make uImage
6. Find led_dev.ko in {source}/ drivers/misc folder and
uImage in {source}/arch/arm/boot
7. Copy led_dev.ko 、 led_test 、uImage to your SDcard
9. Boot the linux on devkit8000
.
69
Lab
• Make menuconfig
• Device Driver
-> Misc devices
-> <M> LED Driver
.
70
Lab
• Traget$ Ismod led_dev.ko
• Check /dev/ledcontrol exist or not
.
71
Lab
• Let us execute and see result • Target$ ./led_test 2 on
• Target$./led_test 2 off
• Target$./led_test 3 on
• Target$./led_test 3 off
.
72
Lab
• Appendix – OMAP3530 Hardware Block
.
73
Lab
• Appendix – GPIO Block Overview
.
74
Lab
• Appendix – GPIO_OE
.
75
Lab
• Appendix – GPIO_DATAOUT
.
76
Lab
• Appendix – GPIO_SETDATAOUT
.
77
Lab
• Appendix – GPIO_CLEARDATAOUT
.
78
Lab
top related