kandroid_3rd_seminar_20090327_session_3_ARM_Architecture_Linux_Device_Driver_Model
description
Transcript of kandroid_3rd_seminar_20090327_session_3_ARM_Architecture_Linux_Device_Driver_Model
2009 제3회 Korea Android 세미나
ARM Processor & Linux Device Driver Model
숭실대학교 OSLab : 국중진 (tipsiness@gmail com)
2009. 3. 27.
숭실대학교 OSLab. : 국중진 ([email protected])
Contents
ARM11 F tARM11 FeaturesDefinition of the Device DriverT di i l D i M d lTraditional Driver ModelsLinux Device Driver ModelExamples of the Device DriverPorting Drivers to the New Driver ModelReferences
23rd Korea Android Seminar - www.kandroid.org
Evolution of the ARM Architecture
Feature set as ARM versions
ArchitectureFeature Set
ArchitectureThumb® DSP JazelleTM Media
V4T √
V5TE √ √
√ √ √V5TEJ √ √ √
V6 √ √ √ √
33rd Korea Android Seminar - www.kandroid.org
ARM11 Family
ARM1136J(F)-S
Processors for network infrastructure, consumer, and automotive infotainmentas with all ARM11 family, media processing extensions offer up to 1.9x acceleration of media-processing tasks (e.g. MPEG4 encode)instruction and data cache sizes are configurableoptional Tightly Coupled Memories can be added to accelerate interrupt phandling and data-processingAMBA 2 AHB interfaces compatible with a wide range of system IP and
43rd Korea Android Seminar - www.kandroid.org
with a wide range of system IP and peripherals
ARM11 Family
ARM1156T2(F)-SHi h f f High performance processors for automotive, data storage, imaging and embedded controli t th l t t ARM Th b 2 incorporate the latest ARM Thumb-2 tech
higher code density and instruction set efficiencyefficiencyThumb-2 tech. uses 31% less memory than pure 32-bit, while delivering up to 38% better performance
ARM1156T2F-S includes as integrated floating point coprocessor
ideal for embedded control applications developed from mathematical modelsdeveloped from mathematical models
enhanced Memory Protection Unit(MPU)id l d th f b dd d
53rd Korea Android Seminar - www.kandroid.org
ideal upgrade path for embedded control applications
ARM11 Family
ARM1176JZ(F)-S
Applications processors for consumer and wirelessARM Jazelle® technologygyARM TrustZone technologyintegrated floating point coprocessor:coprocessor:
suitable for embedded 3D-graphics applications
Offering higher system bus g g ybandwidth
AXI interfaces compatible with the latest AMBATM 3 AXITM
63rd Korea Android Seminar - www.kandroid.org
ARM11 Family
ARM11 MPCore
contains 1~4 processors delivering up to 2600 Dhrystone MIPS of performance
73rd Korea Android Seminar - www.kandroid.org
ARM11 Family
Applications
ARM1136J(F)-S ARM1156T2(F)-S ARM1176JZ(F)-S ARM11 MPCore
Infotainment, P t iInfotainment,DVD N i tiAutomotive
Infotainment,DVD, Navigation
Power train,body * DVD, Navigation,
Image and speech recognition
Computer PDA Printer, PDAPDA, Printer, Industrial Kiosks Computer PDA ,
Data storage PDA Industrial, Kiosks, Server blade
ConsumerDigital TV, DVD,PVR, gamesSet top Box
Digital camera Set-top Box*DTV, IPSTB, DSC,Camcorder, Games boxSet-top Box Games box
Industrial - Embedded control EPOS Terminal -
Networking Infrastructure,Switch/Router Modem *
CPE Terminals,Switch/Router,NAS
Smartphone, Combined apps, Mobile gaming
83rd Korea Android Seminar - www.kandroid.org
Wireless Applications processor
Base station Baseband processor for Smartphone
Mobile gaming,PDA, Media Player
S3C6410 Mobile Processor
93rd Korea Android Seminar - www.kandroid.org
S3C6410 Key Features
ARM1176ZJF 533/667 MHz VFP/SIMD65 l 65nm low-power processDVFS power managementD di d 32 DDR/DDR 32 SDR/SDRDedicated x32 mDDR/DDR, x32 mSDR/SDRWVGA or higher display resolutionHard-wired 3D GFX accelerator
4M triangles/secondOpenGL ES 1 1/2 0OpenGL ES 1.1/2.0
32-channel DMA
103rd Korea Android Seminar - www.kandroid.org
S3C6410 Key Features
Hard-wired multimedia (>WVGA)MPEG 4 SP codec: SD/D1 >30fpsMPEG-4 SP codec: SD/D1 >30fpsH.264/263 BP codec: SD/D1 >30fpsVC-1 (WMV9) decoder: SD/D1 >30fpsVC 1 (WMV9) decoder: SD/D1 >30fpsJPEG/2D hardwareHardware rotator & post processorTV-out (DAC + image enhancer)
Security H/W: DES/3DES, AES, SHA-1Pin compatible with S3C6400 & S3C6430Package: 424 pins, 13X13, 0.5mm pitch FBGA
113rd Korea Android Seminar - www.kandroid.org
S3C6410 Key Features
High-speed connectivityUART interfacing BT EDR 2 0 up to 3MbpsUART interfacing BT EDR 2.0 up to 3MbpsHigh-speed SPI, 50Mbps for mobile TVUSB 2.0 OTGUSB 2.0 OTGHigh-speed MMC 8-bit 50MHz, MMC+/eMMCSDHC 4-bit 50MHz for high-densitySD cards/iNAND 2.0 and WiFi 802.11a/b/gI2S for 5.1-channel Dolby and stereo audio
123rd Korea Android Seminar - www.kandroid.org
S3C6410 Key Features
BOM cost savings by integrating:USB host 1 1/USB2 0 OTG PHYsUSB host 1.1/USB2.0 OTG PHYs12-bit ADC with TS + built-in FETsDirect boot/NAND FS for NAND SLC/MLC, moviNAND, Direct boot/NAND FS for NAND SLC/MLC, moviNAND, iNAND, OneNANDTV-out DAC integration
l k d llBuilt-in keypad controller
133rd Korea Android Seminar - www.kandroid.org
Samsung S3C6410
Point of differences
143rd Korea Android Seminar - www.kandroid.org
Samsung S3C6410
Point of differences – con’t
153rd Korea Android Seminar - www.kandroid.org
Samsung S3C6410
Point of differences – con’t
163rd Korea Android Seminar - www.kandroid.org
S3C6410 New Functionality
New FunctionalityAdded Clock Gating SFRs (3D I2S V40 MEMO)Added Clock Gating SFRs (3D, I2S_V40, MEMO)Added Clock Source Select SFR (I2S_V40)Extended ARM Divider Ratio (Max. Divider value 8 16)Extended ARM Divider Ratio (Max. Divider value 8 16)Added Clock divider value for Camera I/FAdded DMA select register for Modem I/FAdded SROMC address expand register between DMC0 and SROMCAdditional Power Domain SRFs (3D)Additional Power Domain SRFs (3D)Added Operating Mode (Synchronous mode)Added DEEP_STOP Wake-up status register
173rd Korea Android Seminar - www.kandroid.org
S3C6410 Memory
Behavior for accessing reserved address regionsregions
Accesses to reserved address region returns ERROR response (IP Based reserved region)gcf.) S3C6400: returns OKAY response
Clock domain for OneNAND controllerOneNAND controllers shares AHB clock domain with other memory controllersmemory controllerscf.) S3C6400: separate clock domain
183rd Korea Android Seminar - www.kandroid.org
S3C6410 DRAM
New programmable optionsDPD supportDPD supportVariable number of auto-refresh requests before priority changeg
New functionalityImproved pipeline stagesImproved write terminationAuto self refresh entryAuto self refresh entry
193rd Korea Android Seminar - www.kandroid.org
S3C6410 NAND Flash
NAND controller compare
203rd Korea Android Seminar - www.kandroid.org
AMBA 3 AXI
Pipelined interconnect for high speed operationoperation
Efficient bridging between frequencies for power management
Simultaneous read and write transactions
Efficient support of high initial latency peripheralsperipherals
http://www arm com/products/solutions/axi spec htmlhttp://www.arm.com/products/solutions/axi_spec.html
213rd Korea Android Seminar - www.kandroid.org
Definition of the Device Driver
Device DriverSW component within the kernel enables to use devicesSW component within the kernel enables to use devices
FunctionalitiesControls the devicesInterface between kernel and deviceDynamic loading and unloadingDynamic loading and unloadingAccess controlAbstracted view of devices
223rd Korea Android Seminar - www.kandroid.org
General Devices
Secondary storage
Main memory
Input device
Output device
p
CPU
233rd Korea Android Seminar - www.kandroid.org
Communication Device
Mobile Specific Devices
Smart-phone, PDA, CellularCPU : ARM9/11 XScale DSPCPU : ARM9/11, XScale, DSP, …Memory: NOR flash, SRAMStorage: NAND flashStorage: NAND flashInput: Key pad, Touch ScreenOutput: LCD, Sound, MultimediaCommunication
WLANCDMACDMAIrDA, Bluetooth UART, USB
http://www.kogan.com.au
243rd Korea Android Seminar - www.kandroid.org
Devices, Drivers, and Kernel Structure
The System Call InterfaceThe System Call Interface
Kernel
subsystems
Features
Process
management
Memory
managementFilesystems
Device
controlNetworking
Concurrency, Virtual Files and dirs: ttys & Features
implemented
S ft
Concurrency,
multitasking
Virtual
memory
Files and dirs:
the VFS
ttys &
Device accessConnectivity
File system
TypesNetwork
subsystem
Software
support
Arch-dependent
code
Memory
manager
Block devices
Character
devices
IF drivers
Hardware
CPU Memory Disks & CDs Consoles, etc. Network IF
Hardware
“Linux Device Drivers 3rd”
253rd Korea Android Seminar - www.kandroid.org
Linux Device Drivers 3rd , Jonathan Corbet, Alessandro Rubini & Greg Kroah-Hartman,O’REILLY, 2005.
Traditional Driver Model
Tree-like structure (or list)
No uniformity across the different bus types
“The Linux Kernel Device Model”, Patrick Mochel, Proceedings of the Ottawa Linux Symposium June 2002
263rd Korea Android Seminar - www.kandroid.org
Proceedings of the Ottawa Linux Symposium, June, 2002.
Character Devices
Character device can be accessed as byte stream (like a file)stream (like a file)
Char driver implements at least open, read, i d l llwrite, and close system calls
Char device examplesptext console (/dev/console), serial port (/dev/ttyS#)
Char devices are accessed by node filesChar devices are accessed by node files
Most char devices are just data channels: only access sequentiallyonly access sequentially
273rd Korea Android Seminar - www.kandroid.org
Block Devices
Block device can host a filesystem
Allows applications to read and write a block device (different from UNIX)
What’s the difference from char device ?Data is managed internally by the kernel, and thus in the g y y ,kernel/driver software interfaceDifference between block and char is transparent to the useruser
283rd Korea Android Seminar - www.kandroid.org
Network Devices(Interfaces)
Network transaction is made through an interfaceinterfaceIF is a H/W device, but it might be a pure S/W device (like loopback)S/W device (like loopback)Network IF is in charge of sending/receiving data packets, driven by the network data packets, driven by the network subsystem of the kernelNetwork driver only handles packetsy pKernel calls functions related to packet transmissionNot a stream-oriented device, network IF isn’t mapped to a node
293rd Korea Android Seminar - www.kandroid.org
Other Types of Devices
USB, IEEE1394, PCI, and so onHost device structuresHost-device structures
Host BridgeAudio
PCI BridgePCI Bridge
USB Controller
ISA Bridge
303rd Korea Android Seminar - www.kandroid.org
Other Types of Devices
USB, IEEE1394, PCI, and so onDriver structure for host device typeDriver structure for host-device type
ftdi_sio/pl2303
usb-uhci
usbserial
_ /p
usbcore
usb-mass storage
ieee1394 core
ohci1394
1394
ieee1394_core
libraw1394
dv1394/eth1394
313rd Korea Android Seminar - www.kandroid.org
raw1394
Current Driver Model
Uniform data model for describing a bus and the devicesthe devices
Unified bus model includes:common attributescommon callbacks
ObjectivesComplex device structure Simply well-abstracted device structuredevice structureDownstream accessUser interfaceUser interface
323rd Korea Android Seminar - www.kandroid.org
udev
Escape from traditional Unix’s device management style: statically creation of nodemanagement style: statically creation of node
devfs can create dynamic device node, h h b d f i d ill however the burden of naming nodes still rested
Udev arrived on the scene to push device management to user space
333rd Korea Android Seminar - www.kandroid.org
udev
Precedence worksKernel sysfs supportKernel sysfs supportuserspace daemons and utility: udevd, udevinfouser specified rules: /etc/udev/rules.duser specified rules: /etc/udev/rules.d
What to do with the udev ?pre udev days you must figure out the associated names pre-udev days, you must figure out the associated names before use the devicesBut with udev, you can consistently view the devices irrespective of the order in which they are plugged in or out
343rd Korea Android Seminar - www.kandroid.org
udev example
udevinfoudevinfo a p /sys/block/sdb1udevinfo -a -p /sys/block/sdb1
353rd Korea Android Seminar - www.kandroid.org
udev example
Add new rules/etc/udev/rules d/40 usbdisk rules/etc/udev/rules.d/40-usbdisk.rules
KERNEL==“sd*”, SUBSYSTEM==“scsi”, ATTRS{model}==“mini-plus”, SYMLINK+=“usbhd%n”
udevtestudevtest /etc/udev/rules d/40 usbdisk rulesudevtest /etc/udev/rules.d/40-usbdisk.rules
363rd Korea Android Seminar - www.kandroid.org
Kobjects and Subsystems
kobjectsConsolidate common aspects of driver model objectsConsolidate common aspects of driver model objectsSimple object type designed to provide a foundation for more complex object typesj
subsystemsDescribe and manage sets of kobjectsConsolidate and unify driver model objects and functions
373rd Korea Android Seminar - www.kandroid.org
kobject Reference
kobject structure<linux/kobject h><linux/kobject.h>
kobject methodsInitializationInitialization
void kobject_init(struct kobject *kobj);int kobject_set_name(struct kobject *kobj, const char *f )*format, …);
Reference count managementstruct kobject *kobject get(struct kobject *kobj);struct kobject kobject_get(struct kobject kobj);void kobject_put(struct kobject *kobj);
To get the kobj_type associated with a given kobjectk b * k ( k b *k b )struct kobj_type *get_ktype(struct kobject *kobj);
383rd Korea Android Seminar - www.kandroid.org
kobject Reference
kset methodskset initialization & registrationkset initialization & registration
void kset_init(struct kobject *kobj);int kset_add(struct kobject *kobj);int kset_register(struct kobject *kobj);void kset_unregister(struct kobject *kobj);
subsystem macrossubsystem macrosDeclaration of subsystem
decl subsys(name, type, hotplug ops);decl_subsys(name, type, hotplug_ops);
subsystem operationsvoid subsystem_init(struct subsystem *subsys);int subsystem_register(struct subsystem *subsys);void subsystem_unregister(struct subsystem *subsys);struct subsystem *subsys get(struct subsystem *subsys);
393rd Korea Android Seminar - www.kandroid.org
y y _g ( y y );void subsys_put(struct subsystem *subsys);
sysfs Filesystem
In-memory filesystem for exporting object and attributesand attributes
Directly related to the kobject infrastructure
Uses the kobject hierarchy information to determine where to create an object’s jdirectory
Enables sysfs to expose object hierarchies Enables sysfs to expose object hierarchies with no additional overhead
403rd Korea Android Seminar - www.kandroid.org
sysfs References
sysfs structure<linux/sysfs h><linux/sysfs.h>
sysfs methodsAttribute create & remove Attribute create & remove
int sysfs_create_file(struct kobject *kobj, struct attribute *attr);i f fil ( k bj *k bj ib int sysfs_remove_file(struct kobject *kobj, struct attribute *attr);int sysfs_create_bin_file(struct kobject *kobj, structbin_attribute *attr);int sysfs_remove_bin_file(struct kobject *kobj, structbin_attribute *attr);int sysfs_create_link(struct kobject *kobj, struct kobject*target, char *name);int sysfs remove link(struct kobject *kobj, char *name);
413rd Korea Android Seminar - www.kandroid.org
int sysfs_remove_link(struct kobject kobj, char name);
Hotplug
Driver model supports dynamic addition and removal of all object typesremoval of all object types
When a device’s physical or logical status h h d i d l h changes, the driver model executes the user
mode program in /proc/sys/kernel/hotplug
User mode agent (/sbin/hotplug) invoke user-defined policy
Loading or unloading a driver moduleConfiguring a deviceExecuting a script or applicationExecuting a script or application
423rd Korea Android Seminar - www.kandroid.org
Devices
Contains the electrical components to perform its specified functionperform its specified function
Driver model defines ‘struct device’ to d ib d i i d d f h b i describe a device independent of the bus it resides on
struct device members:meta data device, reference countlinkage informationphysical attributes
433rd Korea Android Seminar - www.kandroid.org
Buses
Bus driver is a set of code that communicates with a peripheral bus:with a peripheral bus:
PCI, USB, SCSI, IDE, PCMCIA
D i d l d fi ‘ b ’ Driver model defines ‘struct bus_type’ to represent instances of bus drivers
443rd Korea Android Seminar - www.kandroid.org
Device Drivers
Device driver is a body of code implements interfaces of a device classinterfaces of a device class
Drivers are specific to both their class and bbus
Driver model defines ‘struct device_driver’ to describe device drivers
Device drivers are optional and may be Device drivers are optional and may be loaded as modules
453rd Korea Android Seminar - www.kandroid.org
Buses, Devices, & Drivers References
Bus methodsBus registration & unregistrationBus registration & unregistration
int bus_register(struct bus_type *bus);void bus_unregister(struct bus_type *bus);
Iteration over each of the devices and driversint bus_for_each_dev(struct bus_type *bus, struct device *start void *data int (*fn)(struct device * void *));start, void data, int ( fn)(struct device , void ));int bus_for_each_drv(struct bus_type *bus, structdevice_driver *start, void *data, int (*fn)(structdevice driver * void *));device_driver *, void *));
Declaration bus attributes, create and removeBUS_ATTR(name, mode, show, store);int bus_create_file(struct bus_type *bus, structbus_attribute *attr);void bus remove file(struct bus type *bus, struct
463rd Korea Android Seminar - www.kandroid.org
_ _ ( _ yp ,bus_attribute *attr);
Buses, Devices, & Drivers References
Device methodsDevice registration & unregistrationDevice registration & unregistration
int device_register(struct device *dev);void device_unregister(struct device *dev);
Declaration device attributes, create and removeDEVICE_ATTR(name, mode, show, store);int device create file(struct device *dev structint device_create_file(struct device *dev, structdevice_attribute *attr);void device_remove_file(struct device *dev, structd i tt ib t * tt )device_attribute *attr);
473rd Korea Android Seminar - www.kandroid.org
Buses, Devices, & Drivers References
Driver methodsDriver registration & unregistrationDriver registration & unregistration
int driver_register(struct device_driver *drv);void driver_unregister(struct device_driver *drv);
Declaration driver attributes, create and removeDRIVER_ATTR(name, mode, show, store);int driver create file(struct device driver *drv structint driver_create_file(struct device_driver *drv, structdriver_attribute *attr);void driver_remove_file(struct device_driver *dev, structd i tt ib t * tt )driver_attribute *attr);
483rd Korea Android Seminar - www.kandroid.org
Device Classes
Device class describes a function that a device performs regardless of the busdevice performs, regardless of the bus
Audio output devicesNetwork devicesNetwork devicesDisksInput devices
Device class is characterized by a set of interfaces allow user processes to pcommunicate with devices of their type
493rd Korea Android Seminar - www.kandroid.org
Class References
Class methodsclass simple interface class_simple interface
struct class_simple *class_simple_create(struct module *owner, char *name);void class_simple_destroy(struct class_simple *cs);struct class_device *class_simple_device_add(structclass_simple *cs, dev_t devnum, struct device *device, p , , ,const char *fmt, …);void class_simple_device_remove(dev_t dev);int class simple set hotplug(struct class simple *cs intint class_simple_set_hotplug(struct class_simple cs, int(*hotplug)(struct class_device *dev, char **envp, intnum_envp, char *buffer, int buffer_size));
503rd Korea Android Seminar - www.kandroid.org
Class References
Class methodsClass registration & unregistrationClass registration & unregistration
int class_register(struct class *cls);void class_unregister(struct class *cls);
Declaration class attributes, create and removeCLASS_ATTR(name, mode, show, store);int class create file(struct class *cls const structint class_create_file(struct class *cls, const structclass_attribute *attr);void class_remove_file(struct class *cls, const structl tt ib t * tt )class_attribute *attr);
513rd Korea Android Seminar - www.kandroid.org
Class References
Class methodsClass device interfaceClass device interface
int class_device_register(struct class_device *cd);void class_device_unregister(struct class_device *cd);int class_device_rename(struct class_device *cd, char *new_name);CLASS DEVICE ATTR(name, mode, show, store);CLASS_DEVICE_ATTR(name, mode, show, store);int class_device_creat_file(struct class_device *cls, const struct class_device_attribute *attr);void class device remove file(struct class device *cls const void class_device_remove_file(struct class_device *cls, const struct class_device_attribute *attr);int class_interface_register(struct class_interface *intf);
d l f ( l f * f)void class_interface_unregister(struct class_interface *intf);
523rd Korea Android Seminar - www.kandroid.org
Platform and System Devices
Platform DevicesIntegral part of the platform and the physical makeup of Integral part of the platform and the physical makeup of the system board
Legacy I/O devicesHost bridges
System DevicesyIntegrated devices such as processors, interrupt controllers, and system timersD t f ll l d/ it tiDo not follow normal read/write semantics
533rd Korea Android Seminar - www.kandroid.org
How to Search a Driver
e.g. Network Driver
Usage :
# ls /sys/class/net
th0 leth0 lo
# basename `readlink \
/sys/class/net/eth0/device/driver/module`
r8169
# cd /usr/src/kernels/linux-2.6.17
# find -type f -name Makefile | xargs grep r8169
./drivers/net/Makefile:obj-$(CONFIG_R8169) += r8169.o
543rd Korea Android Seminar - www.kandroid.org
How to Search a Driver
e.g. USB Driver
Usage :
# ls /sys/class/tty/ | grep USB
tt USB0ttyUSB0
# basename `readlink \
/sys/class/tty/ttyUSB0/device/driver/module`
pl2303
# cd /usr/src/kernels/linux-2.6.17
# find -type f -name Makefile | xargs grep pl2303
./drivers/usb/serial/Makefile:obj-$(CONFIG_USB_SERIAL_PL2303) += pl2303.o
553rd Korea Android Seminar - www.kandroid.org
Bus, Device, and Class Structure
How to connectDevice Type Device Function
Buses Devices Classes
Inputusb pci()
Input
devs
driver device dev 0:10 Mouse 1
usb-hid usb 2
port 1
563rd Korea Android Seminar - www.kandroid.org
dev 1:1-0
Driver Example (simple driver model)
#include <linux/fs.h>
#include <linux/cdev.h>
#include <linux/parport.h>
#include <asm/uaccess.h>/
#include <linux/platform_device.h>
#define DEVICE_NAME "led"
static dev_t dev_number;
static struct class *led class;static struct class led_class;
struct cdev led_cdev;
struct pardevice *pdev;
int led_open(struct inode *inode, struct file *file)
{{
return 0;
}
ssize_t led_write(struct file *file, const char *buf, size_t count, loff_t *ppos)
{
char kbuf;char kbuf;
if (copy_from_user(&kbuf, buf, 1)) return -EFAULT;
parport_claim_or_block(pdev);
parport_write_data(pdev->port, kbuf);
parport_release(pdev);
return count;
}
int led_release(struct inode *inode, struct file *file)
{
return 0;
573rd Korea Android Seminar - www.kandroid.org
}
Driver Example (simple driver model)
static struct file_operations led_fops = {
.owner = THIS_MODULE,
.open = led_open,
.write = led_write,,
.release = led_release,
};
static int led_preempt(void *handle)
{
return 1;return 1;
}
static void led_attach(struct parport *port)
{
pdev = parport_register_device(port, DEVICE_NAME, led_preempt, NULL, NULL, 0, NULL);
if (pdev == NULL) printk("Bad register\n");if (pdev == NULL) printk( Bad register\n );
}
static void led_detach(struct parport *port)
{
}
static struct parport_driver led_driver = {
.name = "led",
.attach = led_attach,
.detach = led_detach,
};
583rd Korea Android Seminar - www.kandroid.org
Driver Example (simple driver model)
int __init led_init(void)
{
if (alloc_chrdev_region(&dev_number, 0, 1, DEVICE_NAME) < 0)
{{
printk(KERN_DEBUG "Can't register device\n");
return -1;
}
led_class = class_create(THIS_MODULE, DEVICE_NAME);
if (IS ERR(led class)) printk("Bad class create\n");if (IS_ERR(led_class)) printk( Bad class create\n );
cdev_init(&led_cdev, &led_fops);
led_cdev.owner = THIS_MODULE;
if (cdev add(&led cdev dev number 1))if (cdev_add(&led_cdev, dev_number, 1))
{
printk("Bad cdev add\n");
return 1;
}
class device create(led class NULL dev number NULL DEVICE NAME);class_device_create(led_class, NULL, dev_number, NULL, DEVICE_NAME);
if (parport_register_driver(&led_driver))
{
printk(KERN_ERR "Bad Parport Register\n");
return -EIO;
}}
printk("LED Driver Initialized.\n");
return 0;
}
593rd Korea Android Seminar - www.kandroid.org
Driver Example (simple driver model)
void __exit led_cleanup(void)
{
unregister_chrdev_region(dev_number, 1);
class_device_destroy(led_class, dev_number);y( , );
class_destroy(led_class);
return;
}
module_init(led_init);
module exit(led cleanup);module_exit(led_cleanup);
MODULE_LICENSE("GPL");
603rd Korea Android Seminar - www.kandroid.org
Driver Example (driver model with sysfs)
#include <linux/fs.h>
#include <linux/cdev.h>
#include <linux/parport.h>
#include <asm/uaccess.h>
#include <linux/pci.h>
static dev_t dev_number;
static struct class *led_class;
struct cdev led_cdev;
struct pardevice *pdev;
struct kobject kobj;
struct led_attr {
struct attribute attr;
ssize_t (*show)(char *);
ssize_t (*store)(const char *, size_t count);
};
#define glow_show_led(number) \
static ssize_t \
glow_led_##number(const char *buffer, size_t count) \
{ \
unsigned char buf; \
i l \int value; \
\
sscanf(buffer, "%d", &value); \
\
parport_claim_or_block(pdev); \
buf = parport_read_data(pdev->port); \
if (value) { \
parport_write_data(pdev->port, buf | (1<<number)); \
} else { \
parport_write_data(pdev->port, buf & ~(1<<number)); \
} \
parport_release(pdev); \
613rd Korea Android Seminar - www.kandroid.org
return count; \
} \
Driver Example (driver model with sysfs)
static ssize_t show_led_##number(char *buffer) \
{ \
unsigned char buf; \
\\
parport_claim_or_block(pdev); \
\
buf = parport_read_data(pdev->port); \
parport_release(pdev); \
if (buf & (1 << number)) { \
return sprintf(buffer "ON\n"); \return sprintf(buffer, ON\n ); \
} else { \
return sprintf(buffer, "OFF\n"); \
} \
} \
\
static struct led attr led##number \static struct led_attr led##number = \
__ATTR(led#number, 0644, show_led_##number, glow_led_##number);
glow_show_led(0); glow_show_led(1); glow_show_led(2);
glow_show_led(3); glow_show_led(4); glow_show_led(5);
glow_show_led(6); glow_show_led(7); \
623rd Korea Android Seminar - www.kandroid.org
Driver Example (driver model with sysfs)
#define DEVICE_NAME "led"
static int led_preempt(void *handle)
{
return 1;
}
static void led_attach(struct parport *port)
{
pdev = parport register device(port, DEVICE NAME, led preempt, NULL, NULL, 0, NULL);pdev parport_register_device(port, DEVICE_NAME, led_preempt, NULL, NULL, 0, NULL);
if (pdev == NULL) printk("Bad register\n");
}
static ssize_t l_show(struct kobject *kobj, struct attribute *a, char *buf)
{{
int ret;
struct led_attr *lattr = container_of(a, struct led_attr, attr);
ret = lattr->show ? lattr->show(buf) : -EIO;
return ret;
}}
static ssize_t l_store(struct kobject *kobj, struct attribute *a, const char *buf, size_t count)
{
int ret;
struct led_attr *lattr = container_of(a, struct led_attr, attr);
ret = lattr->store ? lattr->store(buf, count) : -EIO;
return ret;
}
static struct sysfs_ops sysfs_ops = {
633rd Korea Android Seminar - www.kandroid.org
.show = l_show,
.store = l_store,
};
Driver Example (driver model with sysfs)
static struct attribute *led_attrs[] = {
&led0.attr,
&led1.attr,
&led2.attr,
&led3.attr,
&led4.attr,
&led5.attr,
&led6.attr,
&led7.attr,
NULL
};
static struct parport_driver led_driver = {p p _ _ {
.name = "led",
.attach = led_attach,
};
int __init led_init(void) {
struct class_device *c_d;
if (alloc chrdev region(&dev number 0 1 DEVICE NAME) < 0) {if (alloc_chrdev_region(&dev_number, 0, 1, DEVICE_NAME) < 0) {
printk(KERN_DEBUG "Can't register new device\n");
return -1;
}
led_class = class_create(THIS_MODULE, "pardevice");
if (IS ERR(led class)) printk("Bad class create\n");if (IS_ERR(led_class)) printk( Bad class create\n );
c_d = class_device_create(led_class, NULL, dev_number, NULL, DEVICE_NAME);
if (parport_register_driver(&led_driver)) {
printk(KERN_ERR "Bad Parport Register\n");
t EIOreturn -EIO;
}
kobj.parent = &c_d->kobj;
strlcpy(kobj.name, "control", KOBJ_NAME_LEN);
kobj.ktype = NULL;
kobject_register(&kobj);
643rd Korea Android Seminar - www.kandroid.org
printk("LED Driver Initialized\n");
return 0;
}
Driver Example (driver model with sysfs)
void led_cleanup(void)
{
kobject_unregister(&kobj);
class_device_destroy(led_class, dev_number);
class_destroy(led_class);
return;
}
module_init(led_init);
module_exit(led_cleanup);
MODULE_LICENSE("GPL");
Usage :
bash# echo 1 > /sys/class/pardevice/led/control/led0
653rd Korea Android Seminar - www.kandroid.org
Device Creation Process (e.g. PCI dev)
initialize registerregisterinitializedevice
registerkobject
registerdevice
pci_hotplug hotplugdev_hotplug
pci_bus_match
pci device probe
call_usermodehelperbus
match
probepci_device_probe
Kobject core
probe
Driver core
driverprobe
driver
createsysfs links
bind deviceto driver
initializesdevice
PCI driver
663rd Korea Android Seminar - www.kandroid.org
Tying the Pieces of the Device Model
modprobe rtc rtc_init()
misc_register (&rtc_dev)UserSpace
KernelSpace
class_device_register ()
p p
kobject_add () kobject_uevent(KOBJ_ADD)
class_device_create_file ()
sysfs_create_dir () class_device_add_attrs ()
sysfs_create_file () kobject_uevent_env ()
class_device_create_file ()
udevd receives the uevent vianetlink sockets and creates
/sys/class/misc/rtc/
/sys/class/misc/rtc/uevent/dev nodes after consulting its rules database
sysfs_create_file ()“Essential Linux Device Drivers”,
673rd Korea Android Seminar - www.kandroid.org
/sys/class/misc/rtc/dev /dev/rtc
,Alan Cox, Prentice Hall, 2008.
Trade-Offs
Writing a char driver is no longer as simple as it used to be in the days of 2 4 kernel !!it used to be in the days of 2.4 kernel !!
We must know the more abstractions:cdev, sysfs, kobjects, classes, class device, and parport
The abstractions bring several advantages:g gbug-free building blockscode reuseelegant design
683rd Korea Android Seminar - www.kandroid.org
Porting Drivers to the New Driver Model
Processstep 0 : read include/linux/device hstep 0 : read include/linux/device.hstep 1 : registering the bus driverstep 2 : registering devicesstep 2 : registering devicesstep 3 : registering driversstep 4 : define generic methods for driversstep 5 : support generic driver bindingstep 6 : supply a hotplug callbackstep 7 : cleaning up the bus driverstep 7 : cleaning up the bus driver
693rd Korea Android Seminar - www.kandroid.org
References
http://www.arm.com/products/CPUs/families/ARM11Family.htmlhttp://www.samsung.com“Linux Device Drivers 3rd”, Jonathan Corbet, Alessandro Rubini & Greg Kroah-Hartman, O’REILLY, 2005.“The Linux Kernel Device Model”, Patrick Mochel, Proceedings of the Ottawa Linux Symposium, June, 2002. y p , ,“Essential Linux Device Drivers”, Alan Cox, Prentice Hall, 2008.http://www.kogan.com.auhttp://www.reactivated.net/writing_udev_rules.html“리눅스 커널 In a Nutshell”, Greg Kroah-Hartman (국중진, 정석용 역), 프리렉, 2009.
703rd Korea Android Seminar - www.kandroid.org
Q&A
http://cafe.naver.com/linuxdevdrv한국전자산업진흥회 (htt // d k )한국전자산업진흥회 (http://educ.or.kr)
713rd Korea Android Seminar - www.kandroid.org