Professional Documents
Culture Documents
July 2005
Darshak Vasavada
(darshak.vasavada@allgosystems.com) AllGo Embedded Systems Pvt Ltd, Bangalore, India.
www.allgosystems.com
GNU Free Documentation License Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.1 or any later version published by the Free Software Foundation. A copy of this license can be found at: http://www.fsf.org/copyleft/fdl.html
Contents
Perspective: where is Linux in the Embedded World? Sandbox: how to build and run a Linux system? Embedded Linux kernel Managing the CPU Managing memory File system I/O handling: Linux device drivers uClinux for processors without MMU Real-time implementations
Time plan
Session 1: Introduction (1.5 hours) Overview of the embedded system Configure, build and run a Linux system Sessions 2 & 3: Embedded Linux kernel: (3 hours) Process subsystem File subsystem & device drivers Session 4: Variants of embedded Linux (1.5 hours) uClinux Real-time implementations
References
Links and materials used in making this presentation: Linux for Embedded and Real-time applications; Doug Abbot (Newnes) Understanding Linux Kernel: Bovet and Cesati (OReilly) The Linux documentation project: http://www.tldp.org/ Tigran Aivazian, Linux kernel internals: http://www.faqs.org/docs/kernel_2_4/lki.html Process management: http://www.linux.com/guides/lki-2.shtml Memory management: Paul Wilsons VM overview: http://home.earthlink.net/~jknapka/linux-mm/vm_paulwilson.html Linux Memory management: http://linux-mm.org Programming IPC: Dave Marshalls course notes: http://www.cs.cf.ac.uk/Dave/C/ A tour of Linux VFS: http://www.tldp.org/LDP/khg/HyperNews/get/fs/vfstour.html Linux device drivers; Rubini and Corbet (OReilly) online at http://www.oreilly.com/catalog/linuxdrive2/index.html
Story of Unix
Failure of Multics Space travel on PDP7 by Ken Thompson, Dennis Ritchie The first commercial Unix system (text processing) on PDP-11 16 kbytes for the system 8 kbytes for the user programs 512 kbytes disk Limit of 64k per file Simultaneous development of C language 1973: first time, OS written in a high level language Got ported to a range of systems Became popular because of simple and consistent structure and ease of understanding and programming
Story of Linux
Andrew Tannenbaum & Minix Richard Stallman & FSF: GPL & programming environment (gcc, bash, utilities) Linus Torvald: the Linux kernel The internet community and the loads of software Applications Processors Drivers Optimizations and improvements Distributions Documentation Support
10
What is Linux?
Free? Royalty free? Open source? Community support? Kernel? Multi-tasking? File system? Networking? Device drivers? Programming environment? gcc, gdb, libraries? bash, vi, make? A whole lot of development tools? Connectivity? TCP/IP? ping, ftp, telnet, http, browsers? Applications? GUI? Web? Multimedia? All of these?!
11
Linux
To an end user GUI, multimedia, connectivity Free To a programmer A rich development environment System calls: processes, file system, networking To a Linux developer CPU management Memory management File management Device drivers
darshak.vasavada@allgosystems.com ASPICES 2005, Indian Institute of Science
12
Users view
Applications Free/open source applications Browsers, mailers, graphics, multimedia, Networking How are these implemented? Processes and threads File system File system mounted at / root Devices and hard-disks mounted at mount-points Multi-user system; user access: r-w-x Special user called root or the superuser Has full accesses to the entire directory structure
13
A programmers view
Programming environment Open source Shell make Compiler tools: gcc & Co Editors: vi, emacs, Simple shell programming tools: sed, grep, find, cut, Standard C libraries, X windows, GUI libraries System calls Simple and consistent structure The operating system services available as system calls Over 50 calls in the original Unix About 300 system calls in Linux
14
System calls
The OS is available as a set of system calls in C Files: Accessing files: creat, open, close, read, write, lseek Ownerships and permissions: chown, chmod Devices: open, close, read, write, ioctl Processes: Create and terminate: fork, exec and exit IPC: inter-process communication Semaphores, shared memory Message queues Pipes Signals
15
Internal view
Process subsystem Process creation, termination, scheduling Managing memory for processes Inter-process communication File subsystem Character special TTY, codec Block special HDD, CD Device drivers Hardware interface
16
Unix architecture (
User programs
)
User mode Kernel mode
libraries
IPC Sched MM
Char
Block
Software Hardware
17
18
19
Course Map
Introduction
Introduction Embedded Systems Overview Linux Sandbox Configure Build Run System call overview Process Sub-system VM Mgt CPU Processes Threads Sched IPC/ITC shm que sem sig File Sub-system File system Mounting File Directory Links Drivers Modules Drv struct Interrupt
uClinux
Real-time system
20
22
23
Example
system_init ();
ISR1: Receive data. If buffer full Generate EVENT1. ISR2: Transmit data. If buffer empty Generate EVENT2. ISR3: Generate EVENT3.
while (1) { switch (event) { case EVENT1: process_data1 (); break; case EVENT2: produce_data2 (); break; case EVENT3: run_state_machine (); break; /* etc. ... */
24
Memory map
Flash map
Vector table Initialization 1 Boot code RAM image ISRs Constants Data Stack
RAM map
Vector table Initialization 2 while (1) { ... |
25
Variants
ISR1 ISR2 ISR3 Scheduler function1 function2 function3
Job queues, non-preemptive scheduler Can prioritize the system activities The longest activity determines the system response
26
27
RTOS
Provides tasks for asynchronous execution Provides mechanisms for communication and synchronization between the tasks Event flags Semaphores Data queues Lets the application handle interrupts and devices directly
28
Example
Semaphore Circular buffer T1 T2
Double buffer
DMA
29
Cooperative multi-tasking
interrupt ISRs scheduler high priority low priority idle t
30
Performance matters!
Cooperative multi-tasking Fairness is not an issue Tasks and ISRs call OS as and when required A single task can potentially hog-up the system Protection (often) is not an issue Tasks are designed together Potential to corrupt each-others space Application specific driver model ISRs and devices directly handled by the application code Tasks communicate with ISRs with double buffers, flags and message queues Sometimes application tasks even turn off interrupts or the operating system scheduler
31
Debugger
RAM
Linker
32
Memory map
Flash map
Initialization 1 Boot code RAM image
RAM map
Initialization 2 RTOS code & data Task1 code Task2 code Task3 code ISRs Constants Data Task1 stack Task2 stack Task3 stack
33
34
3. Ports of desktop OS
Resources becoming powerful and inexpensive CPU/memory/hard disks Increasing functionalities Networking/GUI/file systems Run downloadable applications Pressure on product cycle time Trimmed down ports of desktop systems on embedded devices
35
Development model
T1
T2
App
App
App
ISR T3 ISR
System calls
Drivers
Hardware
36
37
Flash map
Boot code Compressed ( kernel + file system )
Monolith kernel + device drivers (code, data, stack) PAGE FRAME PAGE FRAME PAGE FRAME PAGE FRAME PAGE FRAME PAGE FRAME
38
Boot loader
Resides in ROM Downloads the operating system into the system memory Can download over UART or Ethernet Can flash the OS and boot from flash Contains initialization routines, drivers, file systems, network stack Can load a new version into flash Can boot the system from a remote host using ftp over network
39
40
Applications
Applications cross compiled with target specific libraries All applications in individual executables stored in the standard Unix file system The file system goes on the system as ROM/RAMFS
41
42
Cross Compile
Flash Programmer
Flash
Boot code
Boot Image
43
Kernel .o files
Kernel sources
uImage
Boot code
Kernel + rootfs
44
45
Target CPU+RAM+Flash
46
Course Map
Introduction
Introduction Embedded Systems Overview System call overview Process Sub-system VM Mgt CPU Processes Threads Sched IPC/ITC shm que sem sig File Sub-system File system Mounting File Directory Links Drivers Modules Drv struct Interrupt
uClinux
Real-time system
47
Sandbox
Look at the programming environment Load the boot loader: U-Boot Configure and build the Linux system Write an application Burn the Linux system on the flash Boot a Linux system from the flash Look at the memory map; find out the foot-print
48
50
Examples
printf (Hello, world!\n); p = (int *) malloc (n * sizeof (int)); fd = open (/dev/audio, O_RDONLY); while (1);
51
Processor modes
Supervisor mode Also known as kernel mode Has full control to all the processor resources User mode Does not have access to IO MMU Vector table Certain registers (e.g. processor mode) Privileged instructions Whenever attempted any of the above ... Generates an exception (access violation)
AllGo Embedded Systems http://www.allgosystems.com
53
main (){ int i, j; for (i = 0; ... j = ... printf (... write (1, ) return 0;
} _syscall (WRITE, )
User mode
trap handler:
Kernel mode
switch (ARG[0]) case WRITE: write functionality case READ: read functionality case FORK: fork functionality ...
write
read
fork
User mode
interrupt handler Handling device Transmitting data Receiving data Acknowledging interrupts
Kernel mode
55
Times up!
Task scheduling
main (){ FILE *fp; fp = fopen (..., fscanf (fp, ... main (){ int i, j; for (i = 0; ... j = ... printf (... return 0; } Timer Interrupt } return 0;
timer handler
Scheduler
56
You, idiot!
Segmentation violation Divide-by-zero Access violation
Exception: segmentation violation
} main (){ int i, *p; p = NULL; *p = 77; ... return 0;
User mode Kernel mode Exception handler Print the error message Terminate the process
57
Operating system
is a set of exception handlers traps for system calls software interrupts for exception handling hardware interrupts for device handling timer interrupts for scheduling A quick quiz: what happens when fopen? exit? malloc?
58
59
Unix architecture (
User programs
)
User mode Kernel mode
libraries
File Sub-system
Software Hardware
60
Course Map
Introduction
Introduction Embedded Systems Overview System call overview Process Sub-system VM Mgt CPU Processes Threads Sched IPC/ITC shm que sem sig File Sub-system File system Mounting File Directory Links Drivers Modules Drv struct Interrupt
uClinux
Real-time system
61
[ Process sub-system ]
What is a process?
A program in execution An application in action, a file with life A mechanism to share the CPU and memory amongst multiple applications Virtualization of CPU Each process thinks it has the entire CPU to itself Processes appear to be executing simultaneously to the end user Virtualization of memory Each process thinks it has the entire address space to itself
AllGo Embedded Systems http://www.allgosystems.com
63
64
Example
#include <stdio.h> int global; main () { int local; global = 1; local = 0; printf (hello, world!\n); return 0; }
EXE
File header Symbol table main = 0x1000, printf = 0x1200 global = 0x2000 Section text start = 0x1000, length = 0x1000 Opcodes for main, printf Section data start = 0x2000, length = 0x4 global Section data start = 0x2004, length = 0x40 string hello, world
65
Text
Data Heap
66
Executable: example
int global; main () { int local; global = 1; local = 0; printf (hello, world!\n); return 0; }
67
Example: continued
EXE
File header Symbol table main = 0x1000, printf = 0x1200 global = 0x2000 Section text start = 0x1000, length = 0x1000 Opcodes for main, printf Section data start = 0x2000, length = 0x4 global Section data start = 0x2004, length = 0x40 string hello, world
68
Virtualization of memory
Q. Is the entire process required to be loaded into the memory? A. The process address space can be larger than the physical memory available. B. Multiple processes may share the same addresses Therefore, virtualization of memory. Divide the process address space into a number of pages Divide the physical memory into a number of frames Load the pages into frames as and when required Perform the translation from virtual to physical addresses with the help of the processor hardware (MMU)
69
text
data
Page table
stack
70
text
data
Page table
stack
71
P2
Text Data
0x100 0x101 0x102 mpy r7,r3 add r7,r2 sub r3,r0
Text Data
Stack
FFFFFFFF
Stack
Quiz: I am debugging P1. I place a break-point and when the break-point hits: 1. I examine location 0x10003, what contents should I see? 2. If I see the list at location 0x101, what instruction should I find? 3. How can I list the opcodes of process2?
darshak.vasavada@allgosystems.com ASPICES 2005, Indian Institute of Science
72
Example
#include <stdio.h> #include <stdlib.h> int num; main (int argc, char *argv[]) { num = atoi (argv[1]); while (1) printf (*(%p) = %d\n, &num, num); return 0; }
73
74
Pages
Virtual page: a block of memory in the virtual address space Logical page: a block of memory that contains code or data. More than one virtual pages can map to a single logical page. Physical frame: a block of physical memory to which a logical page is mapped.
75
Pages
virtual pages regions logical pages physical frames
Proc A
4k 8k 4k
Proc B
4k 8k 4k
76
77
78
Example
What happens when you run a command from a shell (or run through GUI by double clicking)? $ ls 1 f.c f.h f.o a.out $
bash running, reads command ls bash calls fork bash continues running bash calls wait bash waiting bash comes out of wait bash continues running
79
fork example
if ((pid = fork()) == 0) { while (1) printf (child\n); } else { while (1) printf (parent of %d\n, pid); }
80
exec example
main (int argc, char *argv[], char *envp[]) { char *argv[] = {/home/dsv/bin/myprog, NULL}; if (execve (/home/dsv/bin/myprog, argv, envp) == -1) printf (error in exec.\n); else printf (exec successful.\n); }
81
Context switch
How to switch from a process to another process? Save the context of the old process Bring in the context of the new process What forms the context of a process? Virtualization of the CPU Registers including PC and SP Virtualization of memory Page tables
82
83
Thread
A function running asynchronously Example usage
int global; f1() f1 { thread_create (f2, ...); thread create global = 5; ... f1 continues } running f2() { ... global = 7; ...
f2 starts running
84
85
System calls
pthreads: available as a library libpthread.a pthread_create pthread_join pthread_cancel Light weight process: clone Kernel threads: kernel_thread
86
pthread example
main () { pthread_t thid; pthread_create (&thid, NULL, newthread, 0); for (j = 0; j < 10; j++) printf (I am the old thread.\n); pthread_join (&stat); } void *newthread (void *arg) { for (j = 0; j < 10; j++) printf (I am the new thread.\n); return NULL; }
darshak.vasavada@allgosystems.com ASPICES 2005, Indian Institute of Science
87
88
89
Level N
Zzz
Zzz
Zzz
Zzz
90
Scheduling - notes
Multi-level priority scheduling Static priorities: 1 to 99 Never changed by scheduler Useful for real-time implementation Badly written code can hog the system resources Dynamic priorities Assigned by the scheduler A process can only lower its priority by nice() call Scheduling policy SCHED_RR SCHED_FIFO SCHED_OTHER (conventional time-shared scheduler) A process run by root can choose the application policy
91
Process states
Executing: currently running Ready: can run, but not scheduled Suspended: waiting for input/output Stopped: by a signal (such as single stepping, suspended) Zombie: terminated; waiting for parents to read status
AllGo Embedded Systems http://www.allgosystems.com
92
IPC mechanisms
SYS-V IPC Pipes Shared memory Semaphore Message queues Signals Threads IPC Semaphore Message queues
93
Pipes
Useful for communication between parent-child or siblings Pipe call opens two files: one for reading, one for writing. The writer process writes into fd[1], reader process reads from fd[0].
P1
fd[1] fd[0]
fd[0] fd[1]
P2
94
if (fork()) { Used in shell: /* parent */ write (fd[1], buf, num_bytes); cat foo | grep bar } else { /* child */ read (fd[0], buf, num_bytes); }
The shell creates the pipe. Also creates two processes: cat and grep And two processes communicate through pipe.
95
Shared memory
Mechanism to share memory between two unrelated processes System calls shmget: get a shared memory shmat: attach the shared memory to a process shmdt: detach from the process Sharing memory between two threads How?
96
97
Semaphores
A mechanism for synchronization & mutual exclusion System calls: semget: get/create a semaphore semop: operate (post/wait) on a semaphore 0 = wait 1 = post POSIX semaphores Light weight compared to SYS-V semaphores sem_open: get/create a semaphore sem_wait: wait till a semaphore is post sem_post: post a semaphore
98
Semaphore: synchronization
#define KEY 0xBABADADA process_producer() { semid = semget (key, nsems, flg); /* write into shared memory */ strcpy (p_addr, hello!); sops[0].sem_op = 1; /* post */ semop (semid, sops, 0); } } #define KEY 0xBABADADA process_consumer() { semid = semget (key, ... sops[0].sem_op = 0; /* wait semop (semid, sops, 0); printf (%s\n, p_addr);
99
Message queues
Passing messages from one task to another System calls: msgget: create/get a message queue msgsnd/msgrcv: send/receive a message Posix message queues mq_open: create/get a message queue mq_send: send a message to the queue mq_receive: receive a message from the queue
101
102
Signals
Asynchronous notification to a process about an event Similar to an interrupt at a user level System calls kill(): send a signal to a process (misnomer ) signal(): specify the signal handler (similar to plugging an ISR in the vector table) Some examples of signals <sys/signal.h> SIGINT: when you try to stop a program by ^C SIGSEGV: segmentation violation SIGQUIT: kill 9 (can not be ignored or handled) SIGALRM: alarm expired (started by alarm()) SIGUSER: user defined signal
AllGo Embedded Systems http://www.allgosystems.com
103
Example
void sigint_handler () { signal (SIGINT, sigint_handler); printf (You pressed ^C!\n); } main () { signal (SIGINT, sigint_handler); while (1) ; } Quiz: How will you stop the above program?
darshak.vasavada@allgosystems.com ASPICES 2005, Indian Institute of Science
104
Course Map
Introduction
Introduction Embedded Systems Overview System call overview Process Sub-system VM Mgt CPU Processes Threads Sched IPC/ITC shm que sem sig File Sub-system File system Mounting File Directory Links Drivers Modules Drv struct Interrupt
uClinux
Real-time system
105
[ file sub-system ]
107
109
110
File system
Boot block: contains the boot code Super block: information about the file system Inode list: list of inodes (information about each file) Data blocks: disk blocks containing data
Boot block Super block Inode list
Data blocks
111
112
Structure of a file
File made up of a number of disk blocks A table-of-contents of the disk blocks in the inode Direct blocks, single, double and triple indirect blocks Directory Directory is a file too Contains information about the files Inode number File name
113
Super-block
The structure containing the information about the file system Size of the file system Free blocks (size, list of free blocks, index of the next free block) Free inodes (number of free inodes, list of free inodes, index of the next free inode)
114
115
mount
mount (/dev/disk1, /usr, 0); Check if super-user Add an entry in the mount table Open the device Read superblock into the buffer cache Read root inode Mark the mounted-on directory as the mount point
116
Mount/umount commands to mount and unmount the file systems # mount t ntfs /dev/hda5 /windows/s Automount: mount on use
117
118
Quiz: what happens to the link if the original file is deleted: In case of a hard link? In case of a soft link?
darshak.vasavada@allgosystems.com ASPICES 2005, Indian Institute of Science
119
Example: busybox
main (char *argv[], int argc) { if (argv[0] equals ls) do_ls (); if (argv[0] equals cp) do_cp (); ... $ $ $ $ cc bb.c o bb ln s bb ls ln s bb cp ls (runs ls) $ cp f1 f2 (runs cp)
darshak.vasavada@allgosystems.com ASPICES 2005, Indian Institute of Science
120
Course Map
Introduction
Introduction Embedded Systems Overview System call overview Process Sub-system VM Mgt CPU Processes Threads Sched IPC/ITC shm que sem sig File Sub-system File system Mounting Directory Links Drivers Modules Drv struct Interrupt
File
uClinux
Real-time system
121
[ IO sub-system ]
Loadable modules
Module is a .o file that can be dynamically loaded and linked into the kernel Once loaded, becomes a part of the kernel Modules commands: lsmod: display all the currently loaded modules modinfo: display module information Insmod/rmmod: insert/remove a single module modprobe: load module plus any dependencies Modules are used for dynamically adding device to the kernel
123
A simple module*
#define MODULE #include <linux/module.h> int init_module(void) { printk("<1>Hello, world\n"); return 0; } void cleanup_module(void) { printk("<1>Goodbye cruel world\n"); }
* For Linux v2.4.
darshak.vasavada@allgosystems.com ASPICES 2005, Indian Institute of Science
124
#: different in 2.6
darshak.vasavada@allgosystems.com ASPICES 2005, Indian Institute of Science
125
Device
Block device: hard disk, CDROM, SCSI Character device: TTY, I/O ports Has a file name (e.g. /dev/audio) Has an inode (type = block/char, permissions) System calls: open, read, write, close, ioctl Major device number Indicates the device type: for example, tty Minor device number Indicates an instance of the specified device For example: tty01, tty02, tty03
126
127
Device driver
A set of functions to access a device init, read, write, open, release, ioctl, Runs as a part of the kernel Can access all the peripherals & vector table Runs in real mode, no virtual memory How do these functions become a part of the kernel? Statically linked into the kernel (build time) Dynamically insterted as a module (run time) Registering a device Device functions are added into the device table
AllGo Embedded Systems http://www.allgosystems.com
128
129
kmalloc
Or system shutdown
Or uninit
130
131
132
Interrupt handling
Request IRQ A module should request an IRQ request_irq (irq, handler, flags, ); Free IRQ Free-up the IRQ Writing a handler Communication with the device Read/write into the device registers Clear the interrupt pending register Communication with the driver functions Data through buffers Synchronization through kernel events
AllGo Embedded Systems http://www.allgosystems.com
133
return; }
134
Tasklets
Issues in ISRs Too long to be in the interrupt context (Would disable other interrupts/tasks) Important enough not to be delayed Top half and bottom half Top half to execute the time-critical code in the ISR context Bottom half executed in kernel at a later point Tasklets DECLARE_TASKLET (name, function, data); Schedule from an ISR using tasklet_schedule().
135
Tasklet example
void interrupt_handler (void) { /* do device related processing */ ... /* schedule the tasklet */ tasklet_schedule (tasklet_function); } void tasklet_function (void) { /* tasklet functionality */ }
136
Course Map
Introduction
Introduction Embedded Systems Overview System call overview Process Sub-system VM Mgt CPU Processes Threads Sched IPC/ITC shm que sem sig File Sub-system File system Mounting File Directory Links Drivers Modules Drv struct Interrupt
uClinux
Real-time system
137
uClinux
Linux for the processors that do not have MMU No virtual memory management support Processes can see each others memory Processes can see kernel/driver memory No page tables Context switch faster Drivers and applications share the same place Faster communication Appropriate for DSPs and micro-controllers Included in the main-stream linux from 2.6 onwards
139
140
141
142
Approaches
Run the time-critical activities on a separate processor: Micro (OS, GUI, networking) with DSP (signal processing and fast interrupts) Use faster clock or more powerful processor May not gurantee a real-time Use light weight processes Use kernel threads and direct communication with the devices Run Linux over a small RTOS Improve Linux scheduler
143
RTLinux
Run Linux as a low priority task of a hard real-time kernel (www.fsmlabs.com)
144
Improvements to kernel
Real-time framework within the kernel (e.g. KURT) Real-time event handling modules RTmods (real-time modules): parts of application which require real-time performance RTmods run under kernel context Allows user apps to schedule events at a resolution of 10 us. Scheduler improvements Increase preemption points Simpler preemptive scheduler with less focus on fairness
145
Thanks!
(All is well that ends )