C语言应用场景:操作系统开发

C语言是操作系统开发的首选语言,几乎所有主流操作系统(Linux、Windows、macOS等)的内核都是用C语言编写的。本文将深入探讨C语言在操作系统开发中的核心作用和关键技术。

1. 为什么选择C语言开发操作系统

1.1 C语言的优势

  1. 接近硬件:可以直接操作内存地址和硬件寄存器
  2. 高效性:编译后的代码执行效率高,适合系统级编程
  3. 可控性:程序员可以精确控制内存分配和释放
  4. 可移植性:相对容易移植到不同的硬件平台
  5. 成熟稳定:经过几十年的发展,工具链和生态系统完善

1.2 操作系统开发的特殊要求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <stdint.h>
#include <stdbool.h>

// 操作系统开发的特殊要求示例

// 1. 直接内存访问
#define MEMORY_BASE_ADDR 0x80000000
#define IO_REGISTER_ADDR 0x40000000

// 直接操作物理内存
void write_physical_memory(uint32_t addr, uint32_t value) {
volatile uint32_t* ptr = (volatile uint32_t*)addr;
*ptr = value;
}

uint32_t read_physical_memory(uint32_t addr) {
volatile uint32_t* ptr = (volatile uint32_t*)addr;
return *ptr;
}

// 2. 中断处理
typedef struct {
uint32_t r0, r1, r2, r3;
uint32_t r12, lr, pc, psr;
} interrupt_frame_t;

// 中断服务程序必须快速执行
void __attribute__((interrupt)) timer_interrupt_handler(void) {
// 清除中断标志
write_physical_memory(IO_REGISTER_ADDR + 0x10, 1);

// 更新系统时钟
system_tick_count++;

// 触发任务调度
schedule_next_task();
}

// 3. 内存对齐要求
typedef struct __attribute__((packed)) {
uint8_t type;
uint16_t size;
uint32_t address;
uint64_t timestamp;
} memory_descriptor_t;

// 4. 原子操作
static volatile uint32_t spinlock = 0;

void acquire_spinlock(volatile uint32_t* lock) {
while (__sync_lock_test_and_set(lock, 1)) {
// 自旋等待
__asm__ volatile ("nop");
}
}

void release_spinlock(volatile uint32_t* lock) {
__sync_lock_release(lock);
}

// 5. 内联汇编
void enable_interrupts(void) {
__asm__ volatile ("cpsie i" : : : "memory");
}

void disable_interrupts(void) {
__asm__ volatile ("cpsid i" : : : "memory");
}

uint32_t get_cpu_id(void) {
uint32_t cpu_id;
__asm__ volatile ("mrc p15, 0, %0, c0, c0, 5" : "=r" (cpu_id));
return cpu_id & 0x3;
}

2. 内核开发基础

2.1 内核启动过程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
#include <stdint.h>
#include <string.h>

// 内核启动相关数据结构
typedef struct {
uint32_t magic;
uint32_t flags;
uint32_t checksum;
uint32_t header_addr;
uint32_t load_addr;
uint32_t load_end_addr;
uint32_t bss_end_addr;
uint32_t entry_addr;
} multiboot_header_t;

typedef struct {
uint32_t mem_lower;
uint32_t mem_upper;
uint32_t boot_device;
uint32_t cmdline;
uint32_t mods_count;
uint32_t mods_addr;
// ... 其他字段
} multiboot_info_t;

// 内核入口点
void kernel_main(multiboot_info_t* mbi) {
// 1. 初始化终端输出
terminal_initialize();
printf("内核启动中...\n");

// 2. 检查启动信息
if (mbi->flags & 0x1) {
printf("可用内存: %dKB - %dKB\n", mbi->mem_lower, mbi->mem_upper);
}

// 3. 初始化内存管理
memory_manager_init(mbi);
printf("内存管理器初始化完成\n");

// 4. 初始化中断系统
interrupt_init();
printf("中断系统初始化完成\n");

// 5. 初始化进程调度器
scheduler_init();
printf("进程调度器初始化完成\n");

// 6. 初始化文件系统
filesystem_init();
printf("文件系统初始化完成\n");

// 7. 启动第一个用户进程
create_init_process();
printf("用户进程启动\n");

// 8. 开始调度
enable_interrupts();
scheduler_start();

// 内核主循环
while (1) {
halt_cpu();
}
}

// 简单的终端输出实现
#define VGA_WIDTH 80
#define VGA_HEIGHT 25
#define VGA_MEMORY 0xB8000

static uint16_t* vga_buffer = (uint16_t*)VGA_MEMORY;
static size_t terminal_row = 0;
static size_t terminal_column = 0;
static uint8_t terminal_color = 0x0F; // 白色前景,黑色背景

void terminal_initialize(void) {
terminal_row = 0;
terminal_column = 0;

// 清屏
for (size_t y = 0; y < VGA_HEIGHT; y++) {
for (size_t x = 0; x < VGA_WIDTH; x++) {
const size_t index = y * VGA_WIDTH + x;
vga_buffer[index] = ' ' | (terminal_color << 8);
}
}
}

void terminal_putchar(char c) {
if (c == '\n') {
terminal_column = 0;
if (++terminal_row == VGA_HEIGHT) {
// 滚屏
for (size_t y = 0; y < VGA_HEIGHT - 1; y++) {
for (size_t x = 0; x < VGA_WIDTH; x++) {
vga_buffer[y * VGA_WIDTH + x] = vga_buffer[(y + 1) * VGA_WIDTH + x];
}
}
// 清除最后一行
for (size_t x = 0; x < VGA_WIDTH; x++) {
vga_buffer[(VGA_HEIGHT - 1) * VGA_WIDTH + x] = ' ' | (terminal_color << 8);
}
terminal_row = VGA_HEIGHT - 1;
}
return;
}

const size_t index = terminal_row * VGA_WIDTH + terminal_column;
vga_buffer[index] = c | (terminal_color << 8);

if (++terminal_column == VGA_WIDTH) {
terminal_column = 0;
if (++terminal_row == VGA_HEIGHT) {
terminal_row = 0;
}
}
}

void terminal_write_string(const char* data) {
size_t len = strlen(data);
for (size_t i = 0; i < len; i++) {
terminal_putchar(data[i]);
}
}

// 简单的printf实现
void printf(const char* format, ...) {
// 这里简化实现,实际需要完整的格式化支持
terminal_write_string(format);
}

2.2 中断和异常处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
#include <stdint.h>

// 中断描述符表项
typedef struct {
uint16_t offset_low;
uint16_t selector;
uint8_t zero;
uint8_t type_attr;
uint16_t offset_high;
} __attribute__((packed)) idt_entry_t;

// IDT指针
typedef struct {
uint16_t limit;
uint32_t base;
} __attribute__((packed)) idt_ptr_t;

#define IDT_ENTRIES 256
static idt_entry_t idt[IDT_ENTRIES];
static idt_ptr_t idt_ptr;

// 中断处理函数类型
typedef void (*interrupt_handler_t)(void);

// 中断处理函数表
static interrupt_handler_t interrupt_handlers[IDT_ENTRIES];

// 设置IDT表项
void idt_set_gate(uint8_t num, uint32_t base, uint16_t sel, uint8_t flags) {
idt[num].offset_low = base & 0xFFFF;
idt[num].offset_high = (base >> 16) & 0xFFFF;
idt[num].selector = sel;
idt[num].zero = 0;
idt[num].type_attr = flags;
}

// 初始化中断系统
void interrupt_init(void) {
idt_ptr.limit = sizeof(idt_entry_t) * IDT_ENTRIES - 1;
idt_ptr.base = (uint32_t)&idt;

// 清空IDT
memset(&idt, 0, sizeof(idt_entry_t) * IDT_ENTRIES);

// 设置异常处理程序
idt_set_gate(0, (uint32_t)divide_error_handler, 0x08, 0x8E);
idt_set_gate(1, (uint32_t)debug_handler, 0x08, 0x8E);
idt_set_gate(2, (uint32_t)nmi_handler, 0x08, 0x8E);
idt_set_gate(3, (uint32_t)breakpoint_handler, 0x08, 0x8E);
idt_set_gate(4, (uint32_t)overflow_handler, 0x08, 0x8E);
idt_set_gate(5, (uint32_t)bounds_handler, 0x08, 0x8E);
idt_set_gate(6, (uint32_t)invalid_opcode_handler, 0x08, 0x8E);
idt_set_gate(7, (uint32_t)device_not_available_handler, 0x08, 0x8E);
idt_set_gate(8, (uint32_t)double_fault_handler, 0x08, 0x8E);
idt_set_gate(10, (uint32_t)invalid_tss_handler, 0x08, 0x8E);
idt_set_gate(11, (uint32_t)segment_not_present_handler, 0x08, 0x8E);
idt_set_gate(12, (uint32_t)stack_fault_handler, 0x08, 0x8E);
idt_set_gate(13, (uint32_t)general_protection_handler, 0x08, 0x8E);
idt_set_gate(14, (uint32_t)page_fault_handler, 0x08, 0x8E);

// 设置硬件中断处理程序
idt_set_gate(32, (uint32_t)timer_interrupt_handler, 0x08, 0x8E);
idt_set_gate(33, (uint32_t)keyboard_interrupt_handler, 0x08, 0x8E);

// 设置系统调用
idt_set_gate(0x80, (uint32_t)syscall_handler, 0x08, 0xEE);

// 加载IDT
__asm__ volatile ("lidt %0" : : "m" (idt_ptr));
}

// 通用中断处理程序
void interrupt_handler(uint32_t interrupt_number, uint32_t error_code) {
printf("收到中断: %d, 错误码: %d\n", interrupt_number, error_code);

if (interrupt_handlers[interrupt_number]) {
interrupt_handlers[interrupt_number]();
}

// 发送EOI信号给PIC
if (interrupt_number >= 32 && interrupt_number < 48) {
if (interrupt_number >= 40) {
outb(0xA0, 0x20); // 从PIC
}
outb(0x20, 0x20); // 主PIC
}
}

// 注册中断处理函数
void register_interrupt_handler(uint8_t n, interrupt_handler_t handler) {
interrupt_handlers[n] = handler;
}

// 页错误处理
void page_fault_handler(void) {
uint32_t faulting_address;
__asm__ volatile ("mov %%cr2, %0" : "=r" (faulting_address));

printf("页错误! 地址: 0x%x\n", faulting_address);

// 这里应该实现页错误的具体处理逻辑
// 比如按需分页、写时复制等

// 暂时挂起系统
while (1) {
halt_cpu();
}
}

// 定时器中断处理
static uint32_t timer_ticks = 0;

void timer_handler(void) {
timer_ticks++;

// 每100个时钟周期进行一次任务调度
if (timer_ticks % 100 == 0) {
schedule();
}
}

// 键盘中断处理
void keyboard_handler(void) {
uint8_t scancode = inb(0x60);

// 处理键盘扫描码
if (scancode & 0x80) {
// 按键释放
printf("按键释放: %d\n", scancode & 0x7F);
} else {
// 按键按下
printf("按键按下: %d\n", scancode);
}
}

// 端口I/O函数
void outb(uint16_t port, uint8_t value) {
__asm__ volatile ("outb %0, %1" : : "a"(value), "Nd"(port));
}

uint8_t inb(uint16_t port) {
uint8_t ret;
__asm__ volatile ("inb %1, %0" : "=a"(ret) : "Nd"(port));
return ret;
}

void halt_cpu(void) {
__asm__ volatile ("hlt");
}

3. 进程管理

3.1 进程控制块(PCB)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
#include <stdint.h>
#include <stdbool.h>

// 进程状态
typedef enum {
PROCESS_STATE_READY,
PROCESS_STATE_RUNNING,
PROCESS_STATE_BLOCKED,
PROCESS_STATE_TERMINATED
} process_state_t;

// 进程优先级
typedef enum {
PRIORITY_HIGH = 0,
PRIORITY_NORMAL = 1,
PRIORITY_LOW = 2,
PRIORITY_IDLE = 3
} process_priority_t;

// CPU寄存器状态
typedef struct {
uint32_t eax, ebx, ecx, edx;
uint32_t esi, edi, esp, ebp;
uint32_t eip, eflags;
uint16_t cs, ds, es, fs, gs, ss;
} cpu_state_t;

// 进程控制块
typedef struct process {
uint32_t pid; // 进程ID
char name[32]; // 进程名称
process_state_t state; // 进程状态
process_priority_t priority; // 优先级

cpu_state_t cpu_state; // CPU状态
uint32_t* page_directory; // 页目录

uint32_t stack_base; // 栈基址
uint32_t stack_size; // 栈大小
uint32_t heap_base; // 堆基址
uint32_t heap_size; // 堆大小

uint32_t time_slice; // 时间片
uint32_t time_used; // 已使用时间
uint32_t total_time; // 总运行时间

struct process* parent; // 父进程
struct process* next; // 下一个进程
struct process* prev; // 上一个进程

// 文件描述符表
struct file* files[32];

// 信号处理
uint32_t signal_mask;
void (*signal_handlers[32])(int);

// 等待队列
struct process* wait_queue;
int exit_code;

uint32_t creation_time;
uint32_t last_scheduled;
} process_t;

// 进程调度器
typedef struct {
process_t* current_process;
process_t* ready_queue[4]; // 按优先级分组的就绪队列
process_t* blocked_queue;
uint32_t next_pid;
uint32_t process_count;
uint32_t context_switches;
} scheduler_t;

static scheduler_t scheduler = {0};

// 创建新进程
process_t* create_process(const char* name, void* entry_point, process_priority_t priority) {
process_t* process = kmalloc(sizeof(process_t));
if (!process) {
return NULL;
}

// 初始化进程控制块
process->pid = scheduler.next_pid++;
strncpy(process->name, name, sizeof(process->name) - 1);
process->name[sizeof(process->name) - 1] = '\0';
process->state = PROCESS_STATE_READY;
process->priority = priority;

// 分配页目录
process->page_directory = create_page_directory();

// 分配栈空间
process->stack_size = 4096; // 4KB栈
process->stack_base = allocate_virtual_memory(process->stack_size);

// 初始化CPU状态
memset(&process->cpu_state, 0, sizeof(cpu_state_t));
process->cpu_state.eip = (uint32_t)entry_point;
process->cpu_state.esp = process->stack_base + process->stack_size - 4;
process->cpu_state.cs = 0x08; // 内核代码段
process->cpu_state.ds = process->cpu_state.es =
process->cpu_state.fs = process->cpu_state.gs =
process->cpu_state.ss = 0x10; // 内核数据段
process->cpu_state.eflags = 0x202; // 启用中断

// 初始化时间片
process->time_slice = 10; // 10ms
process->time_used = 0;
process->total_time = 0;

// 设置父进程
process->parent = scheduler.current_process;

// 初始化文件描述符表
memset(process->files, 0, sizeof(process->files));

// 初始化信号处理
process->signal_mask = 0;
memset(process->signal_handlers, 0, sizeof(process->signal_handlers));

process->creation_time = get_system_time();
process->last_scheduled = 0;

// 添加到就绪队列
add_to_ready_queue(process);

scheduler.process_count++;

printf("创建进程: PID=%d, 名称=%s, 优先级=%d\n",
process->pid, process->name, process->priority);

return process;
}

// 添加进程到就绪队列
void add_to_ready_queue(process_t* process) {
process->state = PROCESS_STATE_READY;

// 添加到对应优先级的队列头部
process->next = scheduler.ready_queue[process->priority];
if (scheduler.ready_queue[process->priority]) {
scheduler.ready_queue[process->priority]->prev = process;
}
process->prev = NULL;
scheduler.ready_queue[process->priority] = process;
}

// 从就绪队列移除进程
void remove_from_ready_queue(process_t* process) {
if (process->prev) {
process->prev->next = process->next;
} else {
scheduler.ready_queue[process->priority] = process->next;
}

if (process->next) {
process->next->prev = process->prev;
}

process->next = process->prev = NULL;
}

// 选择下一个要运行的进程
process_t* select_next_process(void) {
// 按优先级顺序查找就绪进程
for (int priority = PRIORITY_HIGH; priority <= PRIORITY_IDLE; priority++) {
if (scheduler.ready_queue[priority]) {
process_t* process = scheduler.ready_queue[priority];
remove_from_ready_queue(process);
return process;
}
}

return NULL; // 没有就绪进程
}

// 进程调度
void schedule(void) {
if (!scheduler.current_process) {
// 第一次调度
scheduler.current_process = select_next_process();
if (scheduler.current_process) {
scheduler.current_process->state = PROCESS_STATE_RUNNING;
scheduler.current_process->last_scheduled = get_system_time();
switch_to_process(scheduler.current_process);
}
return;
}

process_t* current = scheduler.current_process;
process_t* next = select_next_process();

if (!next) {
// 没有其他就绪进程,继续运行当前进程
return;
}

// 保存当前进程状态
if (current->state == PROCESS_STATE_RUNNING) {
current->time_used += get_system_time() - current->last_scheduled;

// 检查时间片是否用完
if (current->time_used >= current->time_slice) {
current->time_used = 0;
add_to_ready_queue(current);
} else {
// 时间片未用完,重新加入队列头部
add_to_ready_queue(current);
}
}

// 切换到新进程
scheduler.current_process = next;
next->state = PROCESS_STATE_RUNNING;
next->last_scheduled = get_system_time();
scheduler.context_switches++;

printf("进程切换: %s (PID=%d) -> %s (PID=%d)\n",
current->name, current->pid, next->name, next->pid);

context_switch(current, next);
}

// 上下文切换
void context_switch(process_t* from, process_t* to) {
// 保存当前进程的CPU状态
save_cpu_state(&from->cpu_state);

// 切换页目录
switch_page_directory(to->page_directory);

// 恢复新进程的CPU状态
restore_cpu_state(&to->cpu_state);
}

// 进程退出
void exit_process(int exit_code) {
process_t* process = scheduler.current_process;
if (!process) {
return;
}

printf("进程退出: %s (PID=%d), 退出码=%d\n",
process->name, process->pid, exit_code);

process->state = PROCESS_STATE_TERMINATED;
process->exit_code = exit_code;

// 释放资源
free_page_directory(process->page_directory);
free_virtual_memory(process->stack_base, process->stack_size);

// 关闭所有打开的文件
for (int i = 0; i < 32; i++) {
if (process->files[i]) {
close_file(process->files[i]);
}
}

// 唤醒等待该进程的父进程
if (process->parent && process->parent->state == PROCESS_STATE_BLOCKED) {
process->parent->state = PROCESS_STATE_READY;
add_to_ready_queue(process->parent);
}

scheduler.process_count--;

// 调度下一个进程
scheduler.current_process = NULL;
schedule();
}

// 阻塞当前进程
void block_current_process(void) {
process_t* process = scheduler.current_process;
if (!process) {
return;
}

process->state = PROCESS_STATE_BLOCKED;

// 添加到阻塞队列
process->next = scheduler.blocked_queue;
if (scheduler.blocked_queue) {
scheduler.blocked_queue->prev = process;
}
process->prev = NULL;
scheduler.blocked_queue = process;

// 调度下一个进程
scheduler.current_process = NULL;
schedule();
}

// 唤醒进程
void wakeup_process(process_t* process) {
if (process->state != PROCESS_STATE_BLOCKED) {
return;
}

// 从阻塞队列移除
if (process->prev) {
process->prev->next = process->next;
} else {
scheduler.blocked_queue = process->next;
}

if (process->next) {
process->next->prev = process->prev;
}

// 添加到就绪队列
add_to_ready_queue(process);

printf("唤醒进程: %s (PID=%d)\n", process->name, process->pid);
}

// 获取进程信息
void print_process_info(void) {
printf("\n=== 进程信息 ===\n");
printf("总进程数: %d\n", scheduler.process_count);
printf("上下文切换次数: %d\n", scheduler.context_switches);

if (scheduler.current_process) {
process_t* p = scheduler.current_process;
printf("当前进程: %s (PID=%d, 状态=%d, 优先级=%d)\n",
p->name, p->pid, p->state, p->priority);
printf(" 运行时间: %dms\n", p->total_time);
printf(" 创建时间: %d\n", p->creation_time);
}

printf("\n就绪队列:\n");
for (int priority = PRIORITY_HIGH; priority <= PRIORITY_IDLE; priority++) {
printf(" 优先级 %d: ", priority);
process_t* p = scheduler.ready_queue[priority];
while (p) {
printf("%s(PID=%d) ", p->name, p->pid);
p = p->next;
}
printf("\n");
}

printf("\n阻塞队列: ");
process_t* p = scheduler.blocked_queue;
while (p) {
printf("%s(PID=%d) ", p->name, p->pid);
p = p->next;
}
printf("\n\n");
}

4. 内存管理

4.1 物理内存管理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
#include <stdint.h>
#include <stdbool.h>

// 页面大小
#define PAGE_SIZE 4096
#define PAGE_SHIFT 12
#define PAGES_PER_BITMAP_ENTRY 32

// 内存区域类型
typedef enum {
MEMORY_TYPE_AVAILABLE = 1,
MEMORY_TYPE_RESERVED = 2,
MEMORY_TYPE_ACPI_RECLAIMABLE = 3,
MEMORY_TYPE_ACPI_NVS = 4,
MEMORY_TYPE_BAD = 5
} memory_type_t;

// 内存映射条目
typedef struct {
uint64_t base_addr;
uint64_t length;
uint32_t type;
uint32_t acpi_attrs;
} __attribute__((packed)) memory_map_entry_t;

// 物理内存管理器
typedef struct {
uint32_t total_memory; // 总内存大小
uint32_t available_memory; // 可用内存大小
uint32_t used_memory; // 已使用内存
uint32_t total_pages; // 总页数
uint32_t free_pages; // 空闲页数
uint32_t* page_bitmap; // 页面位图
uint32_t bitmap_size; // 位图大小
uint32_t first_free_page; // 第一个空闲页
} physical_memory_manager_t;

static physical_memory_manager_t pmm = {0};

// 初始化物理内存管理器
void physical_memory_init(multiboot_info_t* mbi) {
printf("初始化物理内存管理器...\n");

// 解析内存映射
if (!(mbi->flags & 0x40)) {
printf("错误: 没有内存映射信息\n");
return;
}

memory_map_entry_t* mmap = (memory_map_entry_t*)mbi->mmap_addr;
uint32_t mmap_length = mbi->mmap_length;

uint32_t max_addr = 0;

printf("内存映射:\n");
for (uint32_t i = 0; i < mmap_length; i += sizeof(memory_map_entry_t)) {
memory_map_entry_t* entry = (memory_map_entry_t*)((uint32_t)mmap + i);

printf(" 0x%08x - 0x%08x: ",
(uint32_t)entry->base_addr,
(uint32_t)(entry->base_addr + entry->length));

switch (entry->type) {
case MEMORY_TYPE_AVAILABLE:
printf("可用\n");
pmm.available_memory += entry->length;
if (entry->base_addr + entry->length > max_addr) {
max_addr = entry->base_addr + entry->length;
}
break;
case MEMORY_TYPE_RESERVED:
printf("保留\n");
break;
default:
printf("其他 (类型=%d)\n", entry->type);
break;
}
}

pmm.total_memory = max_addr;
pmm.total_pages = pmm.total_memory / PAGE_SIZE;
pmm.free_pages = pmm.available_memory / PAGE_SIZE;

// 分配页面位图
pmm.bitmap_size = (pmm.total_pages + PAGES_PER_BITMAP_ENTRY - 1) / PAGES_PER_BITMAP_ENTRY;
pmm.page_bitmap = (uint32_t*)kmalloc(pmm.bitmap_size * sizeof(uint32_t));

// 初始化位图 - 所有页面标记为已使用
memset(pmm.page_bitmap, 0xFF, pmm.bitmap_size * sizeof(uint32_t));

// 标记可用内存区域
for (uint32_t i = 0; i < mmap_length; i += sizeof(memory_map_entry_t)) {
memory_map_entry_t* entry = (memory_map_entry_t*)((uint32_t)mmap + i);

if (entry->type == MEMORY_TYPE_AVAILABLE) {
uint32_t start_page = entry->base_addr / PAGE_SIZE;
uint32_t end_page = (entry->base_addr + entry->length) / PAGE_SIZE;

for (uint32_t page = start_page; page < end_page; page++) {
clear_page_bit(page);
}
}
}

// 标记内核占用的页面
extern uint32_t kernel_start, kernel_end;
uint32_t kernel_start_page = (uint32_t)&kernel_start / PAGE_SIZE;
uint32_t kernel_end_page = ((uint32_t)&kernel_end + PAGE_SIZE - 1) / PAGE_SIZE;

for (uint32_t page = kernel_start_page; page < kernel_end_page; page++) {
set_page_bit(page);
pmm.free_pages--;
}

pmm.used_memory = pmm.available_memory - (pmm.free_pages * PAGE_SIZE);
pmm.first_free_page = 0;

printf("物理内存管理器初始化完成:\n");
printf(" 总内存: %d MB\n", pmm.total_memory / (1024 * 1024));
printf(" 可用内存: %d MB\n", pmm.available_memory / (1024 * 1024));
printf(" 总页数: %d\n", pmm.total_pages);
printf(" 空闲页数: %d\n", pmm.free_pages);
}

// 设置页面位图位
void set_page_bit(uint32_t page) {
uint32_t index = page / PAGES_PER_BITMAP_ENTRY;
uint32_t bit = page % PAGES_PER_BITMAP_ENTRY;
pmm.page_bitmap[index] |= (1U << bit);
}

// 清除页面位图位
void clear_page_bit(uint32_t page) {
uint32_t index = page / PAGES_PER_BITMAP_ENTRY;
uint32_t bit = page % PAGES_PER_BITMAP_ENTRY;
pmm.page_bitmap[index] &= ~(1U << bit);
}

// 检查页面位图位
bool is_page_bit_set(uint32_t page) {
uint32_t index = page / PAGES_PER_BITMAP_ENTRY;
uint32_t bit = page % PAGES_PER_BITMAP_ENTRY;
return (pmm.page_bitmap[index] & (1U << bit)) != 0;
}

// 查找空闲页面
uint32_t find_free_page(void) {
// 从上次分配的位置开始查找
for (uint32_t page = pmm.first_free_page; page < pmm.total_pages; page++) {
if (!is_page_bit_set(page)) {
return page;
}
}

// 从头开始查找
for (uint32_t page = 0; page < pmm.first_free_page; page++) {
if (!is_page_bit_set(page)) {
return page;
}
}

return 0xFFFFFFFF; // 没有空闲页面
}

// 分配物理页面
uint32_t allocate_physical_page(void) {
if (pmm.free_pages == 0) {
printf("错误: 没有空闲物理页面\n");
return 0;
}

uint32_t page = find_free_page();
if (page == 0xFFFFFFFF) {
printf("错误: 无法找到空闲页面\n");
return 0;
}

set_page_bit(page);
pmm.free_pages--;
pmm.used_memory += PAGE_SIZE;
pmm.first_free_page = page + 1;

uint32_t physical_addr = page * PAGE_SIZE;

printf("分配物理页面: 页号=%d, 地址=0x%08x\n", page, physical_addr);

return physical_addr;
}

// 释放物理页面
void free_physical_page(uint32_t physical_addr) {
uint32_t page = physical_addr / PAGE_SIZE;

if (page >= pmm.total_pages) {
printf("错误: 无效的物理地址 0x%08x\n", physical_addr);
return;
}

if (!is_page_bit_set(page)) {
printf("警告: 重复释放页面 %d\n", page);
return;
}

clear_page_bit(page);
pmm.free_pages++;
pmm.used_memory -= PAGE_SIZE;

if (page < pmm.first_free_page) {
pmm.first_free_page = page;
}

printf("释放物理页面: 页号=%d, 地址=0x%08x\n", page, physical_addr);
}

// 分配连续的物理页面
uint32_t allocate_physical_pages(uint32_t count) {
if (count == 0 || pmm.free_pages < count) {
return 0;
}

// 查找连续的空闲页面
for (uint32_t start_page = 0; start_page <= pmm.total_pages - count; start_page++) {
bool found = true;

// 检查从start_page开始的count个页面是否都空闲
for (uint32_t i = 0; i < count; i++) {
if (is_page_bit_set(start_page + i)) {
found = false;
break;
}
}

if (found) {
// 分配这些页面
for (uint32_t i = 0; i < count; i++) {
set_page_bit(start_page + i);
}

pmm.free_pages -= count;
pmm.used_memory += count * PAGE_SIZE;

uint32_t physical_addr = start_page * PAGE_SIZE;

printf("分配连续物理页面: %d页, 起始地址=0x%08x\n", count, physical_addr);

return physical_addr;
}
}

printf("错误: 无法分配 %d 个连续页面\n", count);
return 0;
}

// 释放连续的物理页面
void free_physical_pages(uint32_t physical_addr, uint32_t count) {
uint32_t start_page = physical_addr / PAGE_SIZE;

for (uint32_t i = 0; i < count; i++) {
uint32_t page = start_page + i;

if (page >= pmm.total_pages) {
printf("错误: 无效的物理地址 0x%08x\n", physical_addr + i * PAGE_SIZE);
continue;
}

if (!is_page_bit_set(page)) {
printf("警告: 重复释放页面 %d\n", page);
continue;
}

clear_page_bit(page);
}

pmm.free_pages += count;
pmm.used_memory -= count * PAGE_SIZE;

printf("释放连续物理页面: %d页, 起始地址=0x%08x\n", count, physical_addr);
}

// 获取内存统计信息
void print_memory_stats(void) {
printf("\n=== 物理内存统计 ===\n");
printf("总内存: %d MB\n", pmm.total_memory / (1024 * 1024));
printf("可用内存: %d MB\n", pmm.available_memory / (1024 * 1024));
printf("已使用内存: %d MB\n", pmm.used_memory / (1024 * 1024));
printf("空闲内存: %d MB\n", (pmm.free_pages * PAGE_SIZE) / (1024 * 1024));
printf("总页数: %d\n", pmm.total_pages);
printf("空闲页数: %d\n", pmm.free_pages);
printf("内存使用率: %.1f%%\n",
(float)pmm.used_memory / pmm.available_memory * 100.0f);
printf("\n");
}

4.2 虚拟内存管理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
#include <stdint.h>
#include <stdbool.h>

// 页表项标志
#define PAGE_PRESENT 0x001
#define PAGE_WRITABLE 0x002
#define PAGE_USER 0x004
#define PAGE_ACCESSED 0x020
#define PAGE_DIRTY 0x040

// 虚拟地址空间布局
#define KERNEL_VIRTUAL_BASE 0xC0000000
#define USER_VIRTUAL_BASE 0x00400000
#define USER_STACK_BASE 0xBF000000
#define USER_HEAP_BASE 0x08000000

// 页目录和页表
typedef uint32_t page_directory_t[1024];
typedef uint32_t page_table_t[1024];

// 虚拟内存区域
typedef struct vm_area {
uint32_t start_addr;
uint32_t end_addr;
uint32_t flags;
struct vm_area* next;
} vm_area_t;

// 地址空间
typedef struct {
page_directory_t* page_directory;
vm_area_t* vm_areas;
uint32_t heap_start;
uint32_t heap_end;
uint32_t stack_start;
uint32_t stack_end;
} address_space_t;

static page_directory_t* kernel_page_directory;
static address_space_t kernel_address_space;

// 获取页目录项
uint32_t* get_page_directory_entry(page_directory_t* pd, uint32_t virtual_addr) {
uint32_t pd_index = virtual_addr >> 22;
return &(*pd)[pd_index];
}

// 获取页表项
uint32_t* get_page_table_entry(page_directory_t* pd, uint32_t virtual_addr) {
uint32_t pd_index = virtual_addr >> 22;
uint32_t pt_index = (virtual_addr >> 12) & 0x3FF;

uint32_t* pd_entry = &(*pd)[pd_index];

if (!(*pd_entry & PAGE_PRESENT)) {
return NULL;
}

page_table_t* page_table = (page_table_t*)(*pd_entry & 0xFFFFF000);
return &(*page_table)[pt_index];
}

// 创建页表
page_table_t* create_page_table(void) {
uint32_t physical_addr = allocate_physical_page();
if (!physical_addr) {
return NULL;
}

page_table_t* page_table = (page_table_t*)physical_addr;
memset(page_table, 0, sizeof(page_table_t));

return page_table;
}

// 映射页面
bool map_page(page_directory_t* pd, uint32_t virtual_addr, uint32_t physical_addr, uint32_t flags) {
uint32_t pd_index = virtual_addr >> 22;
uint32_t pt_index = (virtual_addr >> 12) & 0x3FF;

uint32_t* pd_entry = &(*pd)[pd_index];

// 如果页表不存在,创建新页表
if (!(*pd_entry & PAGE_PRESENT)) {
page_table_t* new_page_table = create_page_table();
if (!new_page_table) {
printf("错误: 无法创建页表\n");
return false;
}

*pd_entry = (uint32_t)new_page_table | PAGE_PRESENT | PAGE_WRITABLE | (flags & PAGE_USER);
}

// 获取页表
page_table_t* page_table = (page_table_t*)(*pd_entry & 0xFFFFF000);
uint32_t* pt_entry = &(*page_table)[pt_index];

// 检查页面是否已映射
if (*pt_entry & PAGE_PRESENT) {
printf("警告: 页面 0x%08x 已映射\n", virtual_addr);
return false;
}

// 设置页表项
*pt_entry = (physical_addr & 0xFFFFF000) | flags | PAGE_PRESENT;

// 刷新TLB
__asm__ volatile ("invlpg (%0)" : : "r" (virtual_addr) : "memory");

printf("映射页面: 虚拟=0x%08x -> 物理=0x%08x, 标志=0x%03x\n",
virtual_addr, physical_addr, flags);

return true;
}

// 取消映射页面
void unmap_page(page_directory_t* pd, uint32_t virtual_addr) {
uint32_t* pt_entry = get_page_table_entry(pd, virtual_addr);

if (!pt_entry || !(*pt_entry & PAGE_PRESENT)) {
printf("警告: 页面 0x%08x 未映射\n", virtual_addr);
return;
}

uint32_t physical_addr = *pt_entry & 0xFFFFF000;

// 清除页表项
*pt_entry = 0;

// 刷新TLB
__asm__ volatile ("invlpg (%0)" : : "r" (virtual_addr) : "memory");

// 释放物理页面
free_physical_page(physical_addr);

printf("取消映射页面: 虚拟=0x%08x, 物理=0x%08x\n", virtual_addr, physical_addr);
}

// 创建页目录
page_directory_t* create_page_directory(void) {
uint32_t physical_addr = allocate_physical_page();
if (!physical_addr) {
return NULL;
}

page_directory_t* pd = (page_directory_t*)physical_addr;
memset(pd, 0, sizeof(page_directory_t));

// 映射内核空间 (高1GB)
for (uint32_t i = 768; i < 1024; i++) {
(*pd)[i] = (*kernel_page_directory)[i];
}

return pd;
}

// 切换页目录
void switch_page_directory(page_directory_t* pd) {
uint32_t physical_addr = (uint32_t)pd;
__asm__ volatile ("mov %0, %%cr3" : : "r" (physical_addr));
}

// 初始化虚拟内存管理
void virtual_memory_init(void) {
printf("初始化虚拟内存管理...\n");

// 创建内核页目录
kernel_page_directory = create_page_directory();
if (!kernel_page_directory) {
printf("错误: 无法创建内核页目录\n");
return;
}

// 恒等映射前4MB (内核代码)
for (uint32_t addr = 0; addr < 0x400000; addr += PAGE_SIZE) {
map_page(kernel_page_directory, addr, addr, PAGE_WRITABLE);
}

// 映射内核到高地址空间
extern uint32_t kernel_start, kernel_end;
uint32_t kernel_size = (uint32_t)&kernel_end - (uint32_t)&kernel_start;
uint32_t kernel_pages = (kernel_size + PAGE_SIZE - 1) / PAGE_SIZE;

for (uint32_t i = 0; i < kernel_pages; i++) {
uint32_t physical_addr = (uint32_t)&kernel_start + i * PAGE_SIZE;
uint32_t virtual_addr = KERNEL_VIRTUAL_BASE + i * PAGE_SIZE;
map_page(kernel_page_directory, virtual_addr, physical_addr, PAGE_WRITABLE);
}

// 启用分页
switch_page_directory(kernel_page_directory);

uint32_t cr0;
__asm__ volatile ("mov %%cr0, %0" : "=r" (cr0));
cr0 |= 0x80000000; // 设置PG位
__asm__ volatile ("mov %0, %%cr0" : : "r" (cr0));

printf("虚拟内存管理初始化完成\n");
}

// 分配虚拟内存
uint32_t allocate_virtual_memory(uint32_t size) {
uint32_t pages = (size + PAGE_SIZE - 1) / PAGE_SIZE;

// 简化实现:从用户堆区域分配
static uint32_t next_virtual_addr = USER_HEAP_BASE;

uint32_t start_addr = next_virtual_addr;

for (uint32_t i = 0; i < pages; i++) {
uint32_t virtual_addr = start_addr + i * PAGE_SIZE;
uint32_t physical_addr = allocate_physical_page();

if (!physical_addr) {
// 回滚已分配的页面
for (uint32_t j = 0; j < i; j++) {
unmap_page(kernel_page_directory, start_addr + j * PAGE_SIZE);
}
return 0;
}

if (!map_page(kernel_page_directory, virtual_addr, physical_addr,
PAGE_WRITABLE | PAGE_USER)) {
free_physical_page(physical_addr);
// 回滚已分配的页面
for (uint32_t j = 0; j < i; j++) {
unmap_page(kernel_page_directory, start_addr + j * PAGE_SIZE);
}
return 0;
}
}

next_virtual_addr += pages * PAGE_SIZE;

printf("分配虚拟内存: 地址=0x%08x, 大小=%d字节\n", start_addr, size);

return start_addr;
}

// 释放虚拟内存
void free_virtual_memory(uint32_t virtual_addr, uint32_t size) {
uint32_t pages = (size + PAGE_SIZE - 1) / PAGE_SIZE;

for (uint32_t i = 0; i < pages; i++) {
uint32_t addr = virtual_addr + i * PAGE_SIZE;
unmap_page(kernel_page_directory, addr);
}

printf("释放虚拟内存: 地址=0x%08x, 大小=%d字节\n", virtual_addr, size);
}

// 页错误处理
void handle_page_fault(uint32_t error_code, uint32_t faulting_address) {
printf("页错误: 地址=0x%08x, 错误码=0x%08x\n", faulting_address, error_code);

bool present = error_code & 0x1;
bool write = error_code & 0x2;
bool user = error_code & 0x4;

printf(" 页面存在: %s\n", present ? "是" : "否");
printf(" 访问类型: %s\n", write ? "写" : "读");
printf(" 权限级别: %s\n", user ? "用户" : "内核");

if (!present) {
// 页面不存在,可能需要按需分页
printf(" 尝试按需分页...\n");

uint32_t physical_addr = allocate_physical_page();
if (physical_addr) {
if (map_page(kernel_page_directory, faulting_address & 0xFFFFF000,
physical_addr, PAGE_WRITABLE | PAGE_USER)) {
printf(" 按需分页成功\n");
return;
} else {
free_physical_page(physical_addr);
}
}

printf(" 按需分页失败\n");
} else {
printf(" 权限错误\n");
}

// 无法处理的页错误,终止进程
printf("致命页错误,终止当前进程\n");
exit_process(-1);
}

// 虚拟内存演示
void virtual_memory_demo(void) {
printf("=== 虚拟内存管理演示 ===\n");

// 分配一些虚拟内存
uint32_t addr1 = allocate_virtual_memory(4096);
uint32_t addr2 = allocate_virtual_memory(8192);
uint32_t addr3 = allocate_virtual_memory(16384);

printf("\n分配的虚拟地址:\n");
printf(" 地址1: 0x%08x (4KB)\n", addr1);
printf(" 地址2: 0x%08x (8KB)\n", addr2);
printf(" 地址3: 0x%08x (16KB)\n", addr3);

// 写入数据测试
if (addr1) {
uint32_t* ptr = (uint32_t*)addr1;
*ptr = 0x12345678;
printf("\n写入测试: 地址=0x%08x, 值=0x%08x\n", addr1, *ptr);
}

print_memory_stats();

// 释放内存
if (addr1) free_virtual_memory(addr1, 4096);
if (addr2) free_virtual_memory(addr2, 8192);
if (addr3) free_virtual_memory(addr3, 16384);

print_memory_stats();
}

5. 系统调用

5.1 系统调用接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
#include <stdint.h>

// 系统调用号
#define SYS_EXIT 1
#define SYS_FORK 2
#define SYS_READ 3
#define SYS_WRITE 4
#define SYS_OPEN 5
#define SYS_CLOSE 6
#define SYS_WAITPID 7
#define SYS_CREAT 8
#define SYS_LINK 9
#define SYS_UNLINK 10
#define SYS_EXECVE 11
#define SYS_CHDIR 12
#define SYS_TIME 13
#define SYS_MKNOD 14
#define SYS_CHMOD 15
#define SYS_GETPID 20
#define SYS_MOUNT 21
#define SYS_UMOUNT 22
#define SYS_GETUID 24
#define SYS_STIME 25
#define SYS_ALARM 27
#define SYS_FSTAT 28
#define SYS_PAUSE 29
#define SYS_UTIME 30
#define SYS_ACCESS 33
#define SYS_SYNC 36
#define SYS_KILL 37
#define SYS_RENAME 38
#define SYS_MKDIR 39
#define SYS_RMDIR 40
#define SYS_DUP 41
#define SYS_PIPE 42
#define SYS_TIMES 43
#define SYS_BRK 45
#define SYS_SIGNAL 48
#define SYS_IOCTL 54
#define SYS_FCNTL 55
#define SYS_DUP2 63
#define SYS_GETPPID 64
#define SYS_SETSID 66
#define SYS_SIGACTION 67
#define SYS_MMAP 90
#define SYS_MUNMAP 91

// 系统调用处理函数类型
typedef int (*syscall_handler_t)(uint32_t arg1, uint32_t arg2, uint32_t arg3, uint32_t arg4);

// 系统调用表
static syscall_handler_t syscall_table[256] = {0};

// 系统调用统计
typedef struct {
uint32_t call_count;
uint32_t total_time;
char name[32];
} syscall_stats_t;

static syscall_stats_t syscall_stats[256] = {0};

// 注册系统调用
void register_syscall(uint32_t syscall_num, syscall_handler_t handler, const char* name) {
if (syscall_num >= 256) {
printf("错误: 无效的系统调用号 %d\n", syscall_num);
return;
}

syscall_table[syscall_num] = handler;
strncpy(syscall_stats[syscall_num].name, name, sizeof(syscall_stats[syscall_num].name) - 1);

printf("注册系统调用: %d (%s)\n", syscall_num, name);
}

// 系统调用处理程序
void syscall_handler(uint32_t syscall_num, uint32_t arg1, uint32_t arg2, uint32_t arg3, uint32_t arg4) {
if (syscall_num >= 256 || !syscall_table[syscall_num]) {
printf("错误: 无效的系统调用 %d\n", syscall_num);
// 设置返回值为-1
__asm__ volatile ("movl $-1, %%eax" : : : "eax");
return;
}

uint32_t start_time = get_system_time();

// 调用系统调用处理函数
int result = syscall_table[syscall_num](arg1, arg2, arg3, arg4);

uint32_t end_time = get_system_time();

// 更新统计信息
syscall_stats[syscall_num].call_count++;
syscall_stats[syscall_num].total_time += (end_time - start_time);

printf("系统调用: %s(%d) = %d\n", syscall_stats[syscall_num].name, syscall_num, result);

// 设置返回值
__asm__ volatile ("movl %0, %%eax" : : "r" (result) : "eax");
}

// 具体的系统调用实现

// sys_exit - 进程退出
int sys_exit(uint32_t exit_code, uint32_t unused1, uint32_t unused2, uint32_t unused3) {
printf("进程退出: 退出码=%d\n", exit_code);
exit_process(exit_code);
return 0; // 不会执行到这里
}

// sys_getpid - 获取进程ID
int sys_getpid(uint32_t unused1, uint32_t unused2, uint32_t unused3, uint32_t unused4) {
if (scheduler.current_process) {
return scheduler.current_process->pid;
}
return -1;
}

// sys_write - 写文件
int sys_write(uint32_t fd, uint32_t buffer, uint32_t count, uint32_t unused) {
if (fd == 1 || fd == 2) { // stdout 或 stderr
char* buf = (char*)buffer;
for (uint32_t i = 0; i < count; i++) {
terminal_putchar(buf[i]);
}
return count;
}

// 其他文件描述符的处理
printf("写文件: fd=%d, 缓冲区=0x%08x, 大小=%d\n", fd, buffer, count);
return count;
}

// sys_read - 读文件
int sys_read(uint32_t fd, uint32_t buffer, uint32_t count, uint32_t unused) {
printf("读文件: fd=%d, 缓冲区=0x%08x, 大小=%d\n", fd, buffer, count);

if (fd == 0) { // stdin
// 简化实现:返回0表示EOF
return 0;
}

// 其他文件描述符的处理
return 0;
}

// sys_open - 打开文件
int sys_open(uint32_t pathname, uint32_t flags, uint32_t mode, uint32_t unused) {
char* path = (char*)pathname;
printf("打开文件: 路径=%s, 标志=0x%08x, 模式=0x%08x\n", path, flags, mode);

// 简化实现:返回一个虚拟的文件描述符
static int next_fd = 3;
return next_fd++;
}

// sys_close - 关闭文件
int sys_close(uint32_t fd, uint32_t unused1, uint32_t unused2, uint32_t unused3) {
printf("关闭文件: fd=%d\n", fd);
return 0;
}

// sys_fork - 创建子进程
int sys_fork(uint32_t unused1, uint32_t unused2, uint32_t unused3, uint32_t unused4) {
printf("创建子进程\n");

process_t* parent = scheduler.current_process;
if (!parent) {
return -1;
}

// 创建子进程
process_t* child = create_process(parent->name, NULL, parent->priority);
if (!child) {
return -1;
}

// 复制父进程的地址空间
// 这里简化实现,实际需要写时复制(COW)
memcpy(&child->cpu_state, &parent->cpu_state, sizeof(cpu_state_t));

// 设置返回值
child->cpu_state.eax = 0; // 子进程返回0

printf("fork: 父进程PID=%d, 子进程PID=%d\n", parent->pid, child->pid);

return child->pid; // 父进程返回子进程PID
}

// sys_brk - 调整堆大小
int sys_brk(uint32_t addr, uint32_t unused1, uint32_t unused2, uint32_t unused3) {
process_t* process = scheduler.current_process;
if (!process) {
return -1;
}

printf("调整堆大小: 新地址=0x%08x\n", addr);

if (addr == 0) {
// 返回当前堆顶
return process->heap_base + process->heap_size;
}

if (addr < process->heap_base) {
return -1; // 无效地址
}

uint32_t new_size = addr - process->heap_base;

if (new_size > process->heap_size) {
// 扩展堆
uint32_t additional_size = new_size - process->heap_size;
uint32_t additional_pages = (additional_size + PAGE_SIZE - 1) / PAGE_SIZE;

for (uint32_t i = 0; i < additional_pages; i++) {
uint32_t virtual_addr = process->heap_base + process->heap_size + i * PAGE_SIZE;
uint32_t physical_addr = allocate_physical_page();

if (!physical_addr || !map_page(process->page_directory, virtual_addr,
physical_addr, PAGE_WRITABLE | PAGE_USER)) {
return -1;
}
}

process->heap_size = new_size;
} else if (new_size < process->heap_size) {
// 收缩堆
uint32_t reduce_size = process->heap_size - new_size;
uint32_t reduce_pages = reduce_size / PAGE_SIZE;

for (uint32_t i = 0; i < reduce_pages; i++) {
uint32_t virtual_addr = process->heap_base + new_size + i * PAGE_SIZE;
unmap_page(process->page_directory, virtual_addr);
}

process->heap_size = new_size;
}

return addr;
}

// 初始化系统调用
void syscall_init(void) {
printf("初始化系统调用...\n");

// 注册基本系统调用
register_syscall(SYS_EXIT, sys_exit, "exit");
register_syscall(SYS_GETPID, sys_getpid, "getpid");
register_syscall(SYS_WRITE, sys_write, "write");
register_syscall(SYS_READ, sys_read, "read");
register_syscall(SYS_OPEN, sys_open, "open");
register_syscall(SYS_CLOSE, sys_close, "close");
register_syscall(SYS_FORK, sys_fork, "fork");
register_syscall(SYS_BRK, sys_brk, "brk");

printf("系统调用初始化完成\n");
}

// 用户空间系统调用包装函数
int user_write(int fd, const void* buffer, size_t count) {
int result;
__asm__ volatile (
"movl $4, %%eax\n" // SYS_WRITE
"movl %1, %%ebx\n" // fd
"movl %2, %%ecx\n" // buffer
"movl %3, %%edx\n" // count
"int $0x80\n" // 系统调用中断
"movl %%eax, %0\n" // 获取返回值
: "=m" (result)
: "m" (fd), "m" (buffer), "m" (count)
: "eax", "ebx", "ecx", "edx"
);
return result;
}

int user_getpid(void) {
int result;
__asm__ volatile (
"movl $20, %%eax\n" // SYS_GETPID
"int $0x80\n" // 系统调用中断
"movl %%eax, %0\n" // 获取返回值
: "=m" (result)
:
: "eax"
);
return result;
}

void user_exit(int exit_code) {
__asm__ volatile (
"movl $1, %%eax\n" // SYS_EXIT
"movl %0, %%ebx\n" // exit_code
"int $0x80\n" // 系统调用中断
:
: "m" (exit_code)
: "eax", "ebx"
);
}

// 系统调用统计
void print_syscall_stats(void) {
printf("\n=== 系统调用统计 ===\n");

for (int i = 0; i < 256; i++) {
if (syscall_stats[i].call_count > 0) {
printf("%s(%d): 调用%d次, 总时间%dms, 平均时间%.2fms\n",
syscall_stats[i].name, i,
syscall_stats[i].call_count,
syscall_stats[i].total_time,
(float)syscall_stats[i].total_time / syscall_stats[i].call_count);
}
}
printf("\n");
}

6. 文件系统基础

6.1 简单文件系统实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
#include <stdint.h>
#include <stdbool.h>
#include <string.h>

// 文件系统常量
#define BLOCK_SIZE 512
#define MAX_FILENAME_LEN 255
#define MAX_FILES 1024
#define MAX_BLOCKS 8192
#define INODE_SIZE 128
#define DIRECT_BLOCKS 12
#define INDIRECT_BLOCKS 1
#define DOUBLE_INDIRECT 1

// 文件类型
typedef enum {
FILE_TYPE_REGULAR = 1,
FILE_TYPE_DIRECTORY = 2,
FILE_TYPE_SYMLINK = 3,
FILE_TYPE_DEVICE = 4
} file_type_t;

// inode结构
typedef struct {
uint32_t inode_num; // inode号
file_type_t type; // 文件类型
uint32_t size; // 文件大小
uint32_t blocks; // 占用的块数
uint32_t uid; // 用户ID
uint32_t gid; // 组ID
uint32_t mode; // 权限模式
uint32_t atime; // 访问时间
uint32_t mtime; // 修改时间
uint32_t ctime; // 创建时间
uint32_t direct_blocks[DIRECT_BLOCKS]; // 直接块
uint32_t indirect_block; // 间接块
uint32_t double_indirect_block; // 双重间接块
uint32_t link_count; // 硬链接数
uint8_t reserved[32]; // 保留字段
} inode_t;

// 目录项
typedef struct {
uint32_t inode_num; // inode号
uint16_t rec_len; // 记录长度
uint8_t name_len; // 文件名长度
uint8_t file_type; // 文件类型
char name[MAX_FILENAME_LEN]; // 文件名
} __attribute__((packed)) dir_entry_t;

// 超级块
typedef struct {
uint32_t magic; // 魔数
uint32_t block_count; // 总块数
uint32_t inode_count; // 总inode数
uint32_t free_blocks; // 空闲块数
uint32_t free_inodes; // 空闲inode数
uint32_t first_data_block; // 第一个数据块
uint32_t block_size; // 块大小
uint32_t inode_size; // inode大小
uint32_t blocks_per_group; // 每组块数
uint32_t inodes_per_group; // 每组inode数
uint32_t mount_time; // 挂载时间
uint32_t write_time; // 最后写入时间
uint16_t mount_count; // 挂载次数
uint16_t max_mount_count; // 最大挂载次数
uint16_t state; // 文件系统状态
uint16_t errors; // 错误处理方式
uint8_t uuid[16]; // UUID
char volume_name[16]; // 卷名
uint8_t reserved[1024 - 100]; // 保留空间
} __attribute__((packed)) superblock_t;

// 文件系统
typedef struct {
superblock_t* superblock; // 超级块
uint8_t* block_bitmap; // 块位图
uint8_t* inode_bitmap; // inode位图
inode_t* inode_table; // inode表
uint8_t* data_blocks; // 数据块
bool mounted; // 是否已挂载
} filesystem_t;

static filesystem_t fs = {0};

// 位图操作
void set_bit(uint8_t* bitmap, uint32_t bit) {
bitmap[bit / 8] |= (1 << (bit % 8));
}

void clear_bit(uint8_t* bitmap, uint32_t bit) {
bitmap[bit / 8] &= ~(1 << (bit % 8));
}

bool test_bit(uint8_t* bitmap, uint32_t bit) {
return (bitmap[bit / 8] & (1 << (bit % 8))) != 0;
}

// 查找空闲块
uint32_t find_free_block(void) {
for (uint32_t i = 0; i < fs.superblock->block_count; i++) {
if (!test_bit(fs.block_bitmap, i)) {
return i;
}
}
return 0; // 没有空闲块
}

// 查找空闲inode
uint32_t find_free_inode(void) {
for (uint32_t i = 1; i < fs.superblock->inode_count; i++) { // inode从1开始
if (!test_bit(fs.inode_bitmap, i)) {
return i;
}
}
return 0; // 没有空闲inode
}

// 分配块
uint32_t allocate_block(void) {
uint32_t block = find_free_block();
if (block == 0) {
printf("错误: 没有空闲块\n");
return 0;
}

set_bit(fs.block_bitmap, block);
fs.superblock->free_blocks--;

printf("分配块: %d\n", block);
return block;
}

// 释放块
void free_block(uint32_t block) {
if (block == 0 || block >= fs.superblock->block_count) {
printf("错误: 无效的块号 %d\n", block);
return;
}

clear_bit(fs.block_bitmap, block);
fs.superblock->free_blocks++;

printf("释放块: %d\n", block);
}

// 分配inode
uint32_t allocate_inode(void) {
uint32_t inode_num = find_free_inode();
if (inode_num == 0) {
printf("错误: 没有空闲inode\n");
return 0;
}

set_bit(fs.inode_bitmap, inode_num);
fs.superblock->free_inodes--;

// 初始化inode
inode_t* inode = &fs.inode_table[inode_num];
memset(inode, 0, sizeof(inode_t));
inode->inode_num = inode_num;
inode->ctime = inode->mtime = inode->atime = get_system_time();
inode->link_count = 1;

printf("分配inode: %d\n", inode_num);
return inode_num;
}

// 释放inode
void free_inode(uint32_t inode_num) {
if (inode_num == 0 || inode_num >= fs.superblock->inode_count) {
printf("错误: 无效的inode号 %d\n", inode_num);
return;
}

inode_t* inode = &fs.inode_table[inode_num];

// 释放数据块
for (int i = 0; i < DIRECT_BLOCKS; i++) {
if (inode->direct_blocks[i] != 0) {
free_block(inode->direct_blocks[i]);
}
}

// 释放间接块(简化实现)
if (inode->indirect_block != 0) {
free_block(inode->indirect_block);
}

clear_bit(fs.inode_bitmap, inode_num);
fs.superblock->free_inodes++;

memset(inode, 0, sizeof(inode_t));

printf("释放inode: %d\n", inode_num);
}

// 读取块
void read_block(uint32_t block_num, void* buffer) {
if (block_num >= fs.superblock->block_count) {
printf("错误: 无效的块号 %d\n", block_num);
return;
}

memcpy(buffer, &fs.data_blocks[block_num * BLOCK_SIZE], BLOCK_SIZE);
}

// 写入块
void write_block(uint32_t block_num, const void* buffer) {
if (block_num >= fs.superblock->block_count) {
printf("错误: 无效的块号 %d\n", block_num);
return;
}

memcpy(&fs.data_blocks[block_num * BLOCK_SIZE], buffer, BLOCK_SIZE);
}

// 创建文件
uint32_t create_file(const char* name, file_type_t type, uint32_t mode) {
uint32_t inode_num = allocate_inode();
if (inode_num == 0) {
return 0;
}

inode_t* inode = &fs.inode_table[inode_num];
inode->type = type;
inode->mode = mode;
inode->uid = 0; // root
inode->gid = 0; // root

if (type == FILE_TYPE_DIRECTORY) {
// 为目录分配一个数据块
uint32_t block = allocate_block();
if (block == 0) {
free_inode(inode_num);
return 0;
}

inode->direct_blocks[0] = block;
inode->size = BLOCK_SIZE;
inode->blocks = 1;

// 创建 . 和 .. 目录项
dir_entry_t dir_entries[2];

// . 目录项
dir_entries[0].inode_num = inode_num;
dir_entries[0].rec_len = sizeof(dir_entry_t);
dir_entries[0].name_len = 1;
dir_entries[0].file_type = FILE_TYPE_DIRECTORY;
strcpy(dir_entries[0].name, ".");

// .. 目录项(简化为指向自己)
dir_entries[1].inode_num = inode_num;
dir_entries[1].rec_len = sizeof(dir_entry_t);
dir_entries[1].name_len = 2;
dir_entries[1].file_type = FILE_TYPE_DIRECTORY;
strcpy(dir_entries[1].name, "..");

write_block(block, dir_entries);
}

printf("创建文件: %s, inode=%d, 类型=%d\n", name, inode_num, type);
return inode_num;
}

// 删除文件
void delete_file(uint32_t inode_num) {
if (inode_num == 0 || inode_num >= fs.superblock->inode_count) {
printf("错误: 无效的inode号 %d\n", inode_num);
return;
}

inode_t* inode = &fs.inode_table[inode_num];

if (inode->link_count > 1) {
inode->link_count--;
printf("减少硬链接计数: inode=%d, 链接数=%d\n", inode_num, inode->link_count);
return;
}

printf("删除文件: inode=%d\n", inode_num);
free_inode(inode_num);
}

// 读取文件
int read_file(uint32_t inode_num, void* buffer, uint32_t offset, uint32_t size) {
if (inode_num == 0 || inode_num >= fs.superblock->inode_count) {
return -1;
}

inode_t* inode = &fs.inode_table[inode_num];

if (offset >= inode->size) {
return 0; // EOF
}

if (offset + size > inode->size) {
size = inode->size - offset;
}

uint32_t bytes_read = 0;
uint8_t* buf = (uint8_t*)buffer;

while (bytes_read < size) {
uint32_t block_index = (offset + bytes_read) / BLOCK_SIZE;
uint32_t block_offset = (offset + bytes_read) % BLOCK_SIZE;
uint32_t bytes_to_read = BLOCK_SIZE - block_offset;

if (bytes_to_read > size - bytes_read) {
bytes_to_read = size - bytes_read;
}

if (block_index >= DIRECT_BLOCKS) {
printf("错误: 不支持间接块读取\n");
break;
}

uint32_t block_num = inode->direct_blocks[block_index];
if (block_num == 0) {
// 稀疏文件,返回0
memset(buf + bytes_read, 0, bytes_to_read);
} else {
uint8_t block_buffer[BLOCK_SIZE];
read_block(block_num, block_buffer);
memcpy(buf + bytes_read, block_buffer + block_offset, bytes_to_read);
}

bytes_read += bytes_to_read;
}

inode->atime = get_system_time();

printf("读取文件: inode=%d, 偏移=%d, 大小=%d, 实际读取=%d\n",
inode_num, offset, size, bytes_read);

return bytes_read;
}

// 写入文件
int write_file(uint32_t inode_num, const void* buffer, uint32_t offset, uint32_t size) {
if (inode_num == 0 || inode_num >= fs.superblock->inode_count) {
return -1;
}

inode_t* inode = &fs.inode_table[inode_num];
const uint8_t* buf = (const uint8_t*)buffer;
uint32_t bytes_written = 0;

while (bytes_written < size) {
uint32_t block_index = (offset + bytes_written) / BLOCK_SIZE;
uint32_t block_offset = (offset + bytes_written) % BLOCK_SIZE;
uint32_t bytes_to_write = BLOCK_SIZE - block_offset;

if (bytes_to_write > size - bytes_written) {
bytes_to_write = size - bytes_written;
}

if (block_index >= DIRECT_BLOCKS) {
printf("错误: 不支持间接块写入\n");
break;
}

uint32_t block_num = inode->direct_blocks[block_index];
if (block_num == 0) {
// 分配新块
block_num = allocate_block();
if (block_num == 0) {
break;
}
inode->direct_blocks[block_index] = block_num;
inode->blocks++;
}

uint8_t block_buffer[BLOCK_SIZE];

if (block_offset != 0 || bytes_to_write != BLOCK_SIZE) {
// 部分块写入,需要先读取
read_block(block_num, block_buffer);
}

memcpy(block_buffer + block_offset, buf + bytes_written, bytes_to_write);
write_block(block_num, block_buffer);

bytes_written += bytes_to_write;
}

// 更新文件大小
if (offset + bytes_written > inode->size) {
inode->size = offset + bytes_written;
}

inode->mtime = get_system_time();

printf("写入文件: inode=%d, 偏移=%d, 大小=%d, 实际写入=%d\n",
inode_num, offset, size, bytes_written);

return bytes_written;
}

// 初始化文件系统
void filesystem_init(void) {
printf("初始化文件系统...\n");

// 分配内存
fs.superblock = (superblock_t*)kmalloc(sizeof(superblock_t));
fs.block_bitmap = (uint8_t*)kmalloc(MAX_BLOCKS / 8);
fs.inode_bitmap = (uint8_t*)kmalloc(MAX_FILES / 8);
fs.inode_table = (inode_t*)kmalloc(MAX_FILES * sizeof(inode_t));
fs.data_blocks = (uint8_t*)kmalloc(MAX_BLOCKS * BLOCK_SIZE);

if (!fs.superblock || !fs.block_bitmap || !fs.inode_bitmap ||
!fs.inode_table || !fs.data_blocks) {
printf("错误: 无法分配文件系统内存\n");
return;
}

// 初始化超级块
memset(fs.superblock, 0, sizeof(superblock_t));
fs.superblock->magic = 0xEF53; // ext2魔数
fs.superblock->block_count = MAX_BLOCKS;
fs.superblock->inode_count = MAX_FILES;
fs.superblock->free_blocks = MAX_BLOCKS;
fs.superblock->free_inodes = MAX_FILES - 1; // inode 0保留
fs.superblock->first_data_block = 1;
fs.superblock->block_size = BLOCK_SIZE;
fs.superblock->inode_size = INODE_SIZE;
fs.superblock->mount_time = get_system_time();
fs.superblock->state = 1; // 干净状态
strcpy(fs.superblock->volume_name, "SimpleFS");

// 初始化位图
memset(fs.block_bitmap, 0, MAX_BLOCKS / 8);
memset(fs.inode_bitmap, 0, MAX_FILES / 8);

// 保留块0和inode 0
set_bit(fs.block_bitmap, 0);
set_bit(fs.inode_bitmap, 0);
fs.superblock->free_blocks--;

// 初始化inode表
memset(fs.inode_table, 0, MAX_FILES * sizeof(inode_t));

// 初始化数据块
memset(fs.data_blocks, 0, MAX_BLOCKS * BLOCK_SIZE);

// 创建根目录
uint32_t root_inode = create_file("/", FILE_TYPE_DIRECTORY, 0755);
if (root_inode != 1) {
printf("错误: 无法创建根目录\n");
return;
}

fs.mounted = true;

printf("文件系统初始化完成:\n");
printf(" 总块数: %d\n", fs.superblock->block_count);
printf(" 总inode数: %d\n", fs.superblock->inode_count);
printf(" 块大小: %d字节\n", fs.superblock->block_size);
printf(" 根目录inode: %d\n", root_inode);
}

// 文件系统演示
void filesystem_demo(void) {
printf("=== 文件系统演示 ===\n");

// 创建一些文件
uint32_t file1 = create_file("test.txt", FILE_TYPE_REGULAR, 0644);
uint32_t file2 = create_file("data.bin", FILE_TYPE_REGULAR, 0644);
uint32_t dir1 = create_file("subdir", FILE_TYPE_DIRECTORY, 0755);

// 写入数据
const char* text = "Hello, World! This is a test file.";
write_file(file1, text, 0, strlen(text));

uint8_t binary_data[256];
for (int i = 0; i < 256; i++) {
binary_data[i] = i;
}
write_file(file2, binary_data, 0, 256);

// 读取数据
char read_buffer[100];
int bytes_read = read_file(file1, read_buffer, 0, sizeof(read_buffer) - 1);
read_buffer[bytes_read] = '\0';
printf("读取文本文件: %s\n", read_buffer);

uint8_t read_binary[256];
bytes_read = read_file(file2, read_binary, 0, 256);
printf("读取二进制文件: %d字节\n", bytes_read);

// 显示文件系统状态
printf("\n文件系统状态:\n");
printf(" 空闲块数: %d\n", fs.superblock->free_blocks);
printf(" 空闲inode数: %d\n", fs.superblock->free_inodes);

// 删除文件
delete_file(file2);

printf("删除文件后:\n");
printf(" 空闲块数: %d\n", fs.superblock->free_blocks);
printf(" 空闲inode数: %d\n", fs.superblock->free_inodes);
}

总结

C语言在操作系统开发中发挥着核心作用,其优势体现在:

技术特点:

  1. 底层控制:直接操作硬件和内存
  2. 高效执行:编译后代码性能优异
  3. 精确管理:完全控制资源分配和释放
  4. 系统接口:提供丰富的系统级编程接口
  5. 可移植性:相对容易移植到不同架构

核心技术:

  1. 内核开发:启动过程、中断处理、设备驱动
  2. 进程管理:进程创建、调度、同步、通信
  3. 内存管理:物理内存、虚拟内存、页面管理
  4. 文件系统:存储管理、文件操作、目录结构
  5. 系统调用:用户态与内核态的接口

实际应用:

  1. Linux内核:世界上最成功的开源操作系统
  2. Windows内核:微软操作系统的核心
  3. 嵌入式系统:实时操作系统和微内核
  4. 虚拟化技术:虚拟机监控器和容器技术
  5. 分布式系统:集群操作系统和云计算平台

开发要点:

  1. 深入理解计算机体系结构
  2. 掌握汇编语言和底层编程
  3. 熟悉硬件接口和设备编程
  4. 具备系统级调试和优化能力
  5. 遵循操作系统设计原则

通过C语言进行操作系统开发,可以构建高性能、高可靠性的系统软件,为上层应用提供稳定的运行环境。

版权所有,如有侵权请联系我