Appearance
Kernel and OS Architecture
The kernel is the central component of an operating system that runs in kernel spaceA special mode within the CPU that allows the kernel to access hardware directly on behalf of the user with privileged access to hardware. It acts as a bridge between user applications and hardware, providing essential services like process management, memory management, file systems, and device drivers.
Kernel Space vs User Space
Memory Protection Model
Modern operating systems use a dual-space architecture to protect the kernel from user programs:
cpp
Virtual Address Space:
┌─────────────────────────────────────┐
│ User Space │
│ (User Programs) │
│ ↓ │
│ ↓ │
├─────────────────────────────────────┤
│ Kernel Space │
│ (Operating System) │
│ ↑ │
│ ↑ │
└─────────────────────────────────────┘Among many things, the kernel is responsible for managing the physical memory and the virtual memory of the system. It is also responsible for managing the processes and threads, and access to hardware.
Key Differences
| Aspect | User Space | Kernel Space |
|---|---|---|
| Access Level | Unprivileged (Ring 3) | Privileged (Ring 0) |
| Memory Access | Limited to user memory | Can access all memory |
| Hardware Access | Through kernel requests | Direct hardware access |
| Crash Impact | Affects only the process | Can crash entire system |
| Execution Mode | User mode | Kernel mode |
Protection Mechanisms
cpp
// User space program - cannot access hardware directly
int main() {
int x = 10;
// Cannot directly access hardware registers
// Must request kernel services to access hardware
// Example: Reading from file requires kernel intervention
FILE* file = fopen("data.txt", "r"); // Kernel request
return 0;
}
// Kernel space code - can access hardware directly
void kernel_function() {
// Can directly manipulate hardware registers
outb(0x3F8, 0x41); // Direct I/O port access
// Can access any memory location
void* kernel_memory = kmalloc(1024); // Kernel memory allocation
}Kernel Responsibilities
1. Process Management
The kernel is responsible for creating, scheduling, and terminating processes:
cpp
// Kernel process management functions (simplified)
struct task_struct {
pid_t pid; // Process ID
struct mm_struct *mm; // Memory management
struct files_struct *files; // Open files
struct task_struct *parent; // Parent process
struct list_head children; // Child processes
int state; // Process state
int priority; // Scheduling priority
};
// Kernel creates new process
pid_t do_fork() {
struct task_struct *new_task = kmalloc(sizeof(struct task_struct));
// Copy parent's memory space
copy_mm(current, new_task);
// Set up new process context
setup_process_context(new_task);
// Add to scheduler
add_to_scheduler(new_task);
return new_task->pid;
}Key Responsibilities:
- Process creation:
fork(),exec(),exit() - Process scheduling: CPU time allocation
- Process synchronization: Mutexes, semaphores
- Inter-process communication: Pipes, sockets, shared memory
2. Memory Management
The kernel manages virtual memory, physical memory, and memory protection:
cpp
// Kernel memory management (simplified)
struct mm_struct {
unsigned long start_code; // Code segment start
unsigned long end_code; // Code segment end
unsigned long start_data; // Data segment start
unsigned long end_data; // Data segment end
unsigned long start_brk; // Heap start
unsigned long brk; // Current heap end
unsigned long start_stack; // Stack start
struct vm_area_struct *mmap; // Memory mapped regions
};
// Kernel handles page fault
void do_page_fault(struct pt_regs *regs, unsigned long address) {
if (is_valid_access(address)) {
// Allocate new page
struct page *page = alloc_page();
// Map virtual address to physical page
map_page(address, page);
} else {
// Invalid access - kill process
kill_process(current, SIGSEGV);
}
}Key Responsibilities:
- Virtual memory management: Page tables, address translation
- Physical memory allocation: Page frames, memory pools
- Memory protection: Read/write/execute permissions
- Memory mapping: File mapping, shared libraries
3. File System Management
The kernel provides a unified interface for accessing different storage devices:
cpp
// Kernel file system operations (simplified)
struct file_operations {
ssize_t (*read)(struct file *, char *, size_t, loff_t *);
ssize_t (*write)(struct file *, const char *, size_t, loff_t *);
int (*open)(struct inode *, struct file *);
int (*close)(struct inode *, struct file *);
int (*ioctl)(struct inode *, struct file *, unsigned int, unsigned long);
};
// Kernel handles file read request
ssize_t sys_read(int fd, char *buf, size_t count) {
struct file *file = get_file(fd);
if (!file) return -EBADF;
// Check permissions
if (!can_read(file)) return -EACCES;
// Call file system specific read function
return file->f_op->read(file, buf, count, &file->f_pos);
}Key Responsibilities:
- File operations: Open, read, write, close
- Directory management: Create, delete, list
- Device drivers: Hardware interface
- Caching: Buffer cache, page cache
4. Device Management
The kernel manages hardware devices through device drivers:
cpp
// Kernel device driver interface (simplified)
struct device_driver {
const char *name;
struct bus_type *bus;
int (*probe)(struct device *);
int (*remove)(struct device *);
void (*shutdown)(struct device *);
};
// Example: Simple keyboard driver
static int keyboard_probe(struct device *dev) {
// Initialize keyboard hardware
outb(0x60, 0xAE); // Enable keyboard
// Register interrupt handler
request_irq(1, keyboard_interrupt, IRQF_SHARED, "keyboard", dev);
return 0;
}
static irqreturn_t keyboard_interrupt(int irq, void *dev_id) {
unsigned char scancode = inb(0x60);
// Process key press/release
process_keyboard_input(scancode);
return IRQ_HANDLED;
}Key Responsibilities:
- Device drivers: Hardware-specific code
- Interrupt handling: Hardware event processing
- I/O management: Input/output operations
- Power management: Device power states
Interrupts and Interrupt Handling
What are Interrupts?
Interrupts are signals sent to the CPU by hardware devices or software to request immediate attention. They allow the CPU to respond to external events without constantly polling.
1. Hardware Interrupts (IRQs)
Generated by hardware devices:
cpp
// Common hardware interrupts
#define IRQ_TIMER 0 // System timer
#define IRQ_KEYBOARD 1 // Keyboard input
#define IRQ_SERIAL 4 // Serial port
#define IRQ_DISK 14 // Disk I/O
#define IRQ_NETWORK 11 // Network interfaceSome examples of hardware interrupts are:
- Timer interrupts: A timer interrupt runs after a certain amount of time has passed and allows the kernel to schedule tasks.
- Keyboard interrupts: A keyboard interrupt runs when a key is pressed and allows the kernel to handle the key press.
- Disk interrupts: A disk interrupt runs when a disk operation is completed and allows the kernel to handle the disk operation.
- Network interrupts: A network interrupt runs when a network operation is completed and allows the kernel to handle the network operation.
2. Software Interrupts
Generated by software (kernel requests):
cpp
// Software interrupt handler (simplified)
void software_interrupt_handler() {
// Handle software-generated interrupts
// These are used when user programs need kernel services
// Process the request
handle_kernel_request();
}Some examples of software interrupts are:
- Request to access hardware like filesystem, sending data over network, forking a process, etc.
- Exceptions: An exception is an error condition generated by the CPU for an error condition.
3. Exceptions
The CPU can generate interrupts on some hardware level errors:
cpp
// Common exceptions
#define EXCEPTION_DIVIDE_ERROR 0 // Division by zero
#define EXCEPTION_PAGE_FAULT 14 // Memory access violation
#define EXCEPTION_GENERAL_PROTECTION 13 // Invalid memory access - process trying to access memory it doesn't have access toInterrupt Handling Process
cpp
Hardware Event → Interrupt Controller → CPU → Interrupt Handler → Return to ProcessKey Concepts Summary
- Kernel is the core of the operating system with privileged access
- Kernel space vs user space provides security and stability
- Interrupts allow asynchronous event handling
- Kernel requests provide controlled access to kernel services
- Understanding kernel architecture is crucial for systems programming