0% found this document useful (0 votes)
13 views

EmbeddedSoftware2

The document provides an overview of embedded systems and Linux kernel features, including kernel design goals, architectural approaches, and system lifecycle. It explains the boot process, system calls, and the structure of the Linux source tree, detailing components such as drivers, filesystems, and memory management. Additionally, it discusses the role of system calls in interfacing user-level processes with hardware, emphasizing the importance of security and portability.

Uploaded by

Ramiz Karaeski
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

EmbeddedSoftware2

The document provides an overview of embedded systems and Linux kernel features, including kernel design goals, architectural approaches, and system lifecycle. It explains the boot process, system calls, and the structure of the Linux source tree, detailing components such as drivers, filesystems, and memory management. Additionally, it discusses the role of system calls in interfacing user-level processes with hardware, emphasizing the importance of security and portability.

Uploaded by

Ramiz Karaeski
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 75

Embedded Systems

Prof. Dr. Faruk Bağcı


Prof. Dr. Mesut Güneş

Prof. Dr. Faruk Bağcı


CHAPTER OVERVIEW

• Introduction to Embedded Systems


• Embedded & Real-time Operating Systems
• Linux Kernel
• Peripheral Access
• Threads & Processes
• Memory
• Inter-process Communication
• Real-time Scheduling
• Interrupt Handling
• Advanced Topics

Prof. Dr. Faruk Bağcı


LINUX FEATURES

• UNIX-like operating system.


• Features:
• Preemptive multitasking.
• Virtual memory (protected memory, paging).
• Shared libraries.
• Demand loading, dynamic kernel modules.
• Shared copy-on-write executables.
• TCP/IP networking.
• SMP support.
• Open source.
WHAT’S A KERNEL?

• AKA: executive, system monitor.


• Controls and mediates access to hardware.
• Implements and supports fundamental abstractions:
• Processes, files, devices etc.
• Schedules / allocates system resources:
• Memory, CPU, disk, descriptors, etc.
• Enforces security and protection.
• Responds to user requests for service (system calls).
• Etc…etc…
KERNEL DESIGN GOALS

• Performance: efficiency, speed.


• Utilize resources to capacity with low overhead.
• Stability: robustness, resilience.
• Uptime, graceful degradation.
• Capability: features, flexibility, compatibility.
• Security, protection.
• Protect users from each other & system from bad users.
• Portability.
• Extensibility.
EXAMPLE “CORE” KERNEL

Applications

System Libraries (libc)

System Call Interface

I/O Related Process Related


Modules

File Systems Scheduler


Networking Memory Management
Device Drivers IPC

Architecture-Dependent Code

Hardware
ARCHITECTURAL APPROACHES

• Monolithic.
• Layered.
• Modularized.
• Micro-kernel.
• Virtual machine.
LINUX SOURCE TREE LAYOUT

/usr/src/linux scripts
Documentation

init ipc kernel net


arch
lib mm
drivers fs
include

acorn 802
atm adfs asm-alpha appletalk
alpha block affs adfs atm
asm-arm affs
arm cdrom autofs asm-generic ax25
i386 char autofs4 autofs bridge
asm-i386 autofs4
ia64 dio bfs asm-ia64 core
m68k fc4 code bfs decnet
asm-m68k code
mips i2c cramfs asm-mips econet
mips64 i2o devfs cramfs ethernet
asm-mips64 devfs
ppc ide devpts linux ipv4
s390 ieee1394 efs devpts ipv6
math-emu efs
sh isdn ext2 net ipx
sparc macintosh fat ext2 irda
pcmcia fat
sparc64 misc hfs scsi khttpd
net hpfs hfs lapb
video … hpfs …
… … …
LINUX/ARCH

• Subdirectories for each current port.


• Each contains kernel, lib, mm, boot and other directories whose
contents override code stubs in architecture independent code.
• lib contains highly-optimized common utility routines such as
memcpy, checksums, etc.
• arch as of 2.4:
• alpha, arm, i386, ia64, m68k, mips, mips64.
• ppc, s390, sh, sparc, sparc64.
LINUX/DRIVERS

• Largest amount of code in the kernel tree (~1.5M).


• device, bus, platform and general directories.
• drivers/char – n_tty.c is the default line discipline.
• drivers/block – elevator.c, genhd.c, linear.c, ll_rw_blk.c, raidN.c.
• drivers/net –specific drivers and general routines Space.c and net_init.c.
• drivers/scsi – scsi_*.c files are generic; sd.c (disk), sr.c (CD-ROM), st.c (tape), sg.c
(generic).
• General:
• cdrom, ide, isdn, parport, pcmcia, pnp, sound, telephony, video.
• Buses – fc4, i2c, nubus, pci, sbus, tc, usb.
• Platforms – acorn, macintosh, s390, sgi.
LINUX/FS

• Contains:
• virtual filesystem (VFS) framework.
• subdirectories for actual filesystems.
• vfs-related files:
• exec.c, binfmt_*.c - files for mapping new process images.
• devices.c, blk_dev.c – device registration, block device support.
• super.c, filesystems.c.
• inode.c, dcache.c, namei.c, buffer.c, file_table.c.
• open.c, read_write.c, select.c, pipe.c, fifo.c.
• fcntl.c, ioctl.c, locks.c, dquot.c, stat.c.
LINUX/INCLUDE

• include/asm-*:
• Architecture-dependent include subdirectories.
• include/linux:
• Header info needed both by the kernel and user apps.
• Usually linked to /usr/include/linux.
• Kernel-only portions guarded by #ifdefs
• #ifdef __KERNEL__
• /* kernel stuff */
• #endif
• Other directories:
• math-emu, net, pcmcia, scsi, video.
LINUX/INIT

• Just two files: version.c, main.c.


• version.c – contains the version banner that prints at boot.
• main.c – architecture-independent boot code.
• start_kernel is the primary entry point.
LINUX/IPC

• System V IPC facilities.


• If disabled at compile-time, util.c exports stubs that simply return –
ENOSYS.
• One file for each facility:
• sem.c – semaphores.
• shm.c – shared memory.
• msg.c – message queues.
LINUX/KERNEL

• The core kernel code.


• sched.c – “the main kernel file”:
• scheduler, wait queues, timers, alarms, task queues.
• Process control:
• fork.c, exec.c, signal.c, exit.c etc…
• Kernel module support:
• kmod.c, ksyms.c, module.c.
• Other operations:
• time.c, resource.c, dma.c, softirq.c, itimer.c.
• printk.c, info.c, panic.c, sysctl.c, sys.c.
LINUX/LIB

• kernel code cannot call standard C library routines.


• Files:
• brlock.c – “Big Reader” spinlocks.
• cmdline.c – kernel command line parsing routines.
• errno.c – global definition of errno.
• inflate.c – “gunzip” part of gzip.c used during boot.
• string.c – portable string code.
• Usually replaced by optimized, architecture-dependent routines.
• vsprintf.c – libc replacement.
LINUX/MM

• Paging and swapping:


• swap.c, swapfile.c (paging devices), swap_state.c (cache).
• vmscan.c – paging policies, kswapd.
• page_io.c – low-level page transfer.
• Allocation and deallocation:
• slab.c – slab allocator.
• page_alloc.c – page-based allocator.
• vmalloc.c – kernel virtual-memory allocator.
• Memory mapping:
• memory.c – paging, fault-handling, page table code.
• filemap.c – file mapping.
• mmap.c, mremap.c, mlock.c, mprotect.c.
LINUX/SCRIPTS

• Scripts for:
• Menu-based kernel configuration.
• Kernel patching.
• Generating kernel documentation.
SUMMARY

• Linux is a modular, UNIX-like monolithic kernel.


• Kernel is the heart of the OS that executes with special hardware
permission (kernel mode).
• “Core kernel” provides framework, data structures, support for
drivers, modules, subsystems.
• Architecture dependent source sub-trees live in /arch.
BOOTING AND KERNEL
INITIALIZATION
SYSTEM LIFECYCLE: UPS & DOWNS

Power Power
on off
Boot Kernel OS RUN! Shut
Init Init down
BOOT TERMINOLOGY

• Loader:
• Program that moves bits from disk (usually)
to memory and then transfers CPU control to the newly
“loaded” bits (executable).
• Bootloader / Bootstrap:
• Program that loads the “first program” (the kernel).
• Boot PROM / PROM Monitor / BIOS:
• Persistent code that is “already loaded” on power-up.
• Boot Manager:
• Program that lets you choose the “first program” to load.
LILO: LINUX LOADER

• A versatile boot manager that supports:


• Choice of Linux kernels.
• Boot time kernel parameters.
• Booting non-Linux kernels.
• A variety of configurations.
• Characteristics:
• Lives in MBR or partition boot sector.
• Has no knowledge of filesystem structure so…
• Builds a sector “map file” (block map) to find kernel.
• /sbin/lilo – “map installer”.
• /etc/lilo.conf is lilo configuration file.
EXAMPLE LILO.CONF FILE

boot=/dev/hda
map=/boot/map
install=/boot/boot.b
prompt
timeout=50
default=linux

image=/boot/vmlinuz-2.2.12-20
label=linux
initrd=/boot/initrd-2.2.12-20.img
read-only
root=/dev/hda1
/SBIN/INIT

• Ancestor of all processes (except idle/swapper process).


• Controls transitions between “runlevels”:
• 0: shutdown
• 1: single-user
• 2: multi-user (no NFS)
• 3: full multi-user
• 5: X11
• 6: reboot
• Executes startup/shutdown scripts for each runlevel.
SHUTDOWN

• Use /bin/shutdown to avoid data loss and filesystem corruption.


• Shutdown inhibits login, asks init to send SIGTERM to all processes,
then SIGKILL.
• Low-level commands: halt, reboot, poweroff.
• Use -h, -r or -p options to shutdown instead.
• Ctrl-Alt-Delete “Vulcan neck pinch”:
• defined by a line in /etc/inittab.
• ca::ctrlaltdel:/sbin/shutdown -t3 -r now.
ADVANCED BOOT CONCEPTS

• Initial ramdisk (initrd) – two-stage boot for flexibility:


• First mount “initial” ramdisk as root.
• Execute linuxrc to perform additional setup, configuration.
• Finally mount “real” root and continue.
• See Documentation/initrd.txt for details.
• Also see “man initrd”.

• Net booting:
• Remote root (Diskless-root-HOWTO).
• Diskless boot (Diskless-HOWTO).
SUMMARY

• Bootstrapping a system is a complex, device-dependent process that involves


transition from hardware, to firmware, to software.
• Booting within the constraints of the Intel architecture is especially complex and
usually involves firmware support (BIOS) and a boot manager (LILO).
• /sbin/lilo is a “map installer” that reads configuration information and writes a
boot sector and block map files used during boot.
• start_kernel is Linux “main” and sets up process context before spawning process
0 (idle) and process 1 (init).
• The init() function performs high-level initialization before exec’ing the user-level
init process.
SYSTEM CALLS
SYSTEM CALLS

• Interface between user-level processes and hardware devices.


• CPU, memory, disks etc.
• Make programming easier:
• Let kernel take care of hardware-specific issues.
• Increase system security:
• Let kernel check requested service via syscall.
• Provide portability:
• Maintain interface but change functional implementation.
POSIX APIS

• API = Application Programmer Interface.


• Function defn specifying how to obtain service.
• By contrast, a system call is an explicit request to kernel made via a software
interrupt.
• Standard C library (libc) contains wrapper routines that make system calls.
• e.g., malloc, free are libc routines that use the brk system call.
• POSIX-compliant = having a standard set of APIs.
• Non-UNIX systems can be POSIX-compliant if they offer the required set of APIs.
LINUX SYSTEM CALLS (1)

Invoked by executing int $0x80.


• Programmed exception vector number 128.
• CPU switches to kernel mode & executes a kernel function.
• Calling process passes syscall number identifying system call in
eax register (on Intel processors).
• Syscall handler responsible for:
• Saving registers on kernel mode stack.
• Invoking syscall service routine.
• Exiting by calling ret_from_sys_call().
LINUX SYSTEM CALLS (2)

• System call dispatch table:


• Associates syscall number with corresponding service routine.
• Stored in sys_call_table array having up to NR_syscall entries
(usually 256 maximum).
• nth entry contains service routine address of syscall n.
INITIALIZING SYSTEM CALLS

• trap_init() called during kernel initialization sets up the IDT


(interrupt descriptor table) entry corresponding to vector 128:
• set_system_gate(0x80, &system_call);
• A system gate descriptor is placed in the IDT, identifying address of
system_call routine.
• Does not disable maskable interrupts.
• Sets the descriptor privilege level (DPL) to 3:
• Allows User Mode processes to invoke exception handlers (i.e. syscall routines).
THE SYSTEM_CALL() FUNCTION

• Saves syscall number & CPU registers used by exception handler on


the stack, except those automatically saved by control unit.
• Checks for valid system call.
• Invokes specific service routine associated with syscall number
(contained in eax):
• call *sys_call_table(0, %eax, 4)
• Return code of system call is stored in eax.
PARAMETER PASSING

• On the 32-bit Intel 80x86:


• 6 registers are used to store syscall parameters.
• eax (syscall number).
• ebx, ecx, edx, esi, edi store parameters to syscall service routine,
identified by syscall number.
WRAPPER ROUTINES

• Kernel code (e.g., kernel threads) cannot use library routines.


• _syscall0 … _syscall5 macros define wrapper routines for
system calls with up to 5 parameters.
• e.g., _syscall3(int,write,int,fd,
const char *,buf,unsigned int,count)
EXAMPLE: “HELLO, WORLD!”
.data # section declaration

msg:
.string "Hello, world!\n" # our dear string
len = . - msg # length of our dear string

.text # section declaration

# we must export the entry point to the ELF linker or


.global _start # loader. They conventionally recognize _start as their
# entry point. Use ld -e foo to override the default.

_start:

# write our string to stdout

movl $len,%edx # third argument: message length


movl $msg,%ecx # second argument: pointer to message to write
movl $1,%ebx # first argument: file handle (stdout)
movl $4,%eax # system call number (sys_write)
int $0x80 # call kernel

# and exit

movl $0,%ebx # first argument: exit code


movl $1,%eax # system call number (sys_exit)
int $0x80 # call kernel
LINUX FILES RELATING TO SYSCALLS

• Main files:
• arch/i386/kernel/entry.S
• System call and low-level fault handling routines.
• include/asm-i386/unistd.h
• System call numbers and macros.
• kernel/sys.c
• System call service routines.
ARCH/I386/KERNEL/ENTRY.S

.data
ENTRY(sys_call_table)
.long SYMBOL_NAME(sys_ni_syscall) /* 0 - old "setup()" system
call*/
.long SYMBOL_NAME(sys_exit)
.long SYMBOL_NAME(sys_fork)
.long SYMBOL_NAME(sys_read)
.long SYMBOL_NAME(sys_write)

Add system calls by appending entry to sys_call_table:


.long SYMBOL_NAME(sys_my_system_call)
INCLUDE/ASM-I386/UNISTD.H

• Each system call needs a number in the system call table:


• e.g., #define __NR_write 4
• #define __NR_my_system_call nnn, where nnn is next free entry
in system call table.
KERNEL/SYS.C

• Service routine bodies are defined here:


• e.g., asmlinkage retval
sys_my_system_call (parameters) {
body of service routine;
return retval;
}
DEVICE DRIVERS
WHAT IS A DEVICE DRIVER?

• A programming module with interfaces


• Communication Medium between application/user and hardware
• In Unix,
• Kernel module
• device driver interface = file interface
• What are normal operations?
• Block vs. character
USER PROGRAM & KERNEL INTERFACE

Note: This picture is excerpted from Write a Linux Hardware Device Driver, Andrew O’Shauqhnessy, Unix world
LOADABLE KERNEL MODULE (LKM)

• A new kernel module can be added on the fly (while OS is still


running)
• LKMs are often called “kernel modules”
• They are not user program
TYPES OF LKM

• Device drivers
• Filesystem driver (one for ext2, MSDOS FAT16, 32, NFS)
• System calls
• Network Drivers
• TTY line disciplines. special terminal devices.
• Executable interpreters.
BASIC LKM (PROGRAM)

• Every LKM consist of two basic functions (minimum) :


int init_module(void) /*used for all initialition stuff*/
{
...
}
void cleanup_module(void) /*used for a clean shutdown*/
{
...
}
• Loading a module - normally retricted to root - is managed by issuing the follwing
command: # insmod module.o
LKM UTILITIES CMD
• insmod • lsmod
• Insert an LKM into the kernel. • List currently loaded LKMs.
• rmmod • modinfo
• Remove an LKM from the kernel. • Display contents of .modinfo section in an LKM
object file.
• depmod
• Determine interdependencies between LKMs. • modprobe
• Insert or remove an LKM or set of LKMs
• kerneld intelligently. For example, if you must load A
• Kerneld daemon program before loading B, Modprobe will automatically
load A when you tell it to load B.
• ksyms
• Display symbols that are exported by the
kernel for use by new LKMs.
COMMON LKM UTIL CMD

• Create a special device file


% mknode /dev/driver c 40 0
• Insert a new module
% insmod modname
• Remove a module
• %rmmod modname
• List module
% lsmod
Or % more /proc/modules
audio 37840 0
cmpci 24544 0
soundcore 4208 4 [audio cmpci]
nfsd 70464 8 (autoclean)
LINUX DEVICE DRIVERS

• A set of API subroutines (typically system calls) interface to hardware


• Hide implementation and hardware-specific details from a user
program
• Typically use a file interface metaphor
• Device is a special file
LINUX DEVICE DRIVERS (CONTINUED)

• Manage data flow between a user program and devices


• A self-contained component (add/remove from kernel)
• A user can access the device via file name in /dev , e.g. /dev/lp0
GENERAL IMPLEMENTATION STEPS

1. Understand the device characteristic and supported commands.


2. Map device specific operations to unix file operation
3. Select the device name (user interface)
• Namespace (2-3 characters, /dev/lp0)
4. (optional) select a major number and minor (a device special file creation) for
VFS interface
• Mapping the number to right device sub-routines
5. Implement file interface subroutines
6. Compile the device driver
7. Install the device driver module with loadable kernel module (LKM)
8. or Rebuild (compile) the kernel
READ/WRITE (I/O)

• Pooling (or synchronous)

• Interrupt based
DEVICE DRIVER INTERFACE

Note: This picture is excerpted from Write a Linux Hardware Device Driver, Andrew O’Shauqhnessy, Unix world
VSF & MAJOR NUMBER

• Principal interface between


a device driver and Linux
kernel
FILE OPERATION STRUCTURE

• struct file_operations • struct file_operations


Fops = { Fops = {
NULL, /* seek */ read: xxx_read,
xxx_read,
xxx_write, write: xxx_write,
NULL, /* readdir */ open: xxx_open,
NULL, /* select */ release:
NULL, /* ioctl */
NULL, /* mmap */ xxx_release, /*
xxx_open, a.k.a. close */
NULL, /* flush */ };
xxx_release /* a.k.a.
close */
• };

Watch out compatibility issue with Linux version


DEVICE SPECIAL FILE

• Device number
• Major (used to VFS mapping to right functions)
• Minor (sub-devices)
• mknod /dev/stk c 38 0
• ls –l /dev/tty
• crw-rw-rw- 1 root root 5, 0 Apr 21 18:33 /dev/tty
REGISTER AND UNREGISTER DEVICE

int init_module(void) /*used for all initialition stuff*/


{
/* Register the character device (atleast try) */
Major = register_chrdev(0,
DEVICE_NAME,
&Fops);
:

}
void cleanup_module(void) /*used for a clean shutdown*/

{ret = unregister_chrdev(Major, DEVICE_NAME);

...
}
REGISTER AND UNREGISTER DEVICE

• compile
-Wall -DMODULE -D__KERNEL__ -DLINUX –DDEBUG -I /usr/include/linux/version.h -
I/lib/modules/`uname -r`/build/include

• Install the module


%insmod module.o

• List the module


%lsmod
• If you let the system pick Major number, you can find the major
number (for special creation) by
% more /proc/devices
• Make a special file
% mknod /dev/device_name c major minor
DEVICE DRIVER TYPES

• A character device driver ( c )


• Most devices are this type (e.g.Modem, lp, USB
• No buffer.
• A block device driver (b)
• through a system buffer that acts as a data cache.
• Hard drive controller and HDs
IMPLEMENTATION

• Assuming that your device name is Xxx


• Xxx_init() initialize the device when OS is booted
• Xxx_open() open a device
• Xxx_read() read from kernel memory
• Xxx_write() write
• Xxx_release() clean-up (close)
• init_module()
• cleanup_module()
KERNEL FUNCTIONS
• add_timer() • irqaction()
• Causes a function to be executed when a given amount • Registers an interrupt like a signal.
of time has passed
• IS_*(inode)
• cli() • Tests if inode is on a file system mounted with the
• Prevents interrupts from being acknowledged corresponding flag.

• end_request() • kfree*()
• Called when a request has been satisfied or aborted • Frees memory previously allocated with kmalloc()

• free_irq() • kmalloc()
• Frees an IRQ previously acquired with request_irq() or • Allocates a chu nk of memory no larger than 4096 bytes.
irqaction()
• MAJOR()
• get_user*() • Reports the major device number for a device.
• Allows a driver to access data in user space, a memory
area distinct from the kernel • MINOR()
• Reports the minor device number for a device.
• inb(), inb_p()
• Reads a byte from a port. Here, inb() goes as fast as it
can, while inb_p() pauses before returning.
KERNEL FUNCTIONS

• memcpy_*fs() • select_wait()
• Copies chunks of memory between user space • Adds a process to the proper select_wait
and kernel space queue.
• outb(), outb_p()
• *sleep_on()
• Writes a byte to a port. Here, outb() goes as fast • Sleeps on an event, puts a wait_queue entry in
as it can, while outb_p() pauses before returning. the list so that the process can be awakened
• printk() on that event.
• A version of printf() for the kernel.
• sti()
• put_user*() • Allows interrupts to be acknowledged.
• Allows a driver to write data in user space.
• sys_get*()
• register_*dev() • System calls used to get information regarding
• Registers a device with the kernel. the process, user, or group.
• request_irq() • wake_up*()
• Requests an IRQ from the kernel, and, if • Wakes up a process that has been put to sleep
successful, installs an IRQ interrupt handler. by the matching *sleep_on() function.
LINUX INTERRUPT
HANDLING
INTERRUPTS

• Interrupts are events that alter sequence of instructions executed by a processor.


• Maskable interrupts:
• Sent to INTR pin of x86 processor. Disabled by clearing IF flag of eflags
register.
• Non-maskable interrupts:
• Sent to NMI pin of x86 processor. Not disabled by clearing IF flag.
• Exceptions:
• Can be caused by faults, traps, programmed exceptions (e.g., syscalls) &
hardware failures.
INTERRUPT & EXCEPTION VECTORS

• 256 8-bit vectors on x86 (0..255):


• Identify each interrupt or exception.
• Vectors:
• 0..31 for exceptions & non-maskable interrupts.
• 32..47 for interrupts caused by IRQs.
• 48..255 for “software interrupts”.
• Linux uses vector 128 (0x80) for system calls.
IRQS & INTERRUPTS

• Hardware device controllers that issue interrupt requests, do so on an IRQ


(Interrupt ReQuest) line.
• IRQ lines connect to input pins of interrupt controller (e.g., 8259A PIC).
• Interrupt controller repeatedly:
• Monitors IRQ lines for raised signals.
• Converts signal to vector & stores it in an I/O port for CPU to access via
data bus.
• Sends signal to INTR pin of CPU.
• Clears INTR line upon receipt of ack from CPU on designated I/O port.
EXAMPLE EXCEPTIONS

# Exception Exception Handler Signal


0 Divide Error divide_error() SIGFPE
1 Debug debug() SIGTRAP

6 Invalid Opcode invalip_op() SIGILL

14 Page Fault page_fault() SIGSEGV

INTERRUPT DESCRIPTOR TABLE

• A system Interrupt Descriptor Table (IDT) maps each vector to an


interrupt or exception handler.
• IDT has up to 256 8-byte descriptor entries.
• idtr register on x86 holds base address of IDT.
• Linux uses two types of descriptors:
• Interrupt gates & trap gates.
• Gate descriptors identify address of interrupt / exception handlers
• Interrupt gates clear IF flag, trap gates don’t.
INTERRUPT HANDLING

• CPU checks for interrupts after executing each instruction.


• If interrupt occurred, control unit:
• Determines vector i, corresponding to interrupt.
• Reads ith entry of IDT referenced by idtr.
• IDT entry contains a segment selector, identifying a segment descriptor in the global
descriptor table (GDT), that identifies a memory segment holding handler fn.
• Checks interrupt was issued by authorized source.
INTERRUPT HANDLING …CONTINUED…

• Control Unit then:


• Checks for a change in privilege level.
• If necessary, switches to new stack by:
• Loading ss & esp regs with values found in the task state segment (TSS) of current
process.
• Saving old ss & esp values.
• Saves state on stack including eflags, cs & eip.
• Loads cs & eip w/ segment selector & offset fields of gate descriptor in ith
entry of IDT.
• Interrupt handler is then executed!
PROTECTION ISSUES

• A general protection exception occurs if:


• Interrupt handler has lower privilege level than a program causing interrupt.
• Applications attempt to access interrupt or trap gates.
• What would it take to vector interrupts to user level?
• Programs execute with a current privilege level (CPL).
• e.g., If gate descriptor privilege level (DPL) is lower than CPL, a general
protection fault occurs.
GATES, GATES BUT NOT BILL GATES!

• Linux uses the following gate descriptors:


• Interrupt gate:
• DPL=0, so cannot be accessed by user mode progs.
• System gate:
• DPL=3, so can be accessed by user mode progs.
• e.g., vector 128 accessed via syscall triggered by int 0x80.
• Trap gate:
• DPL=0. Trap gates are used for activating exception handlers.
INITIALIZING IDT

• Linux uses the following functions:


• set_intr_gate(n, addr);
• set_trap_gate(n,addr);
• set_system_gate(n,addr);
• Insert gate descriptor into nth entry of IDT.
• addr identifies offset in kernel’s code segment, which is base address of interrupt
handler.
• DPL value depends on which fn (above) is called.
• e.g., set_system_gate(0x80,&system_call);

You might also like