美文网首页Linux内核
编写一个简单的操作系统内核(Linux Kernel)

编写一个简单的操作系统内核(Linux Kernel)

作者: Minority | 来源:发表于2020-05-10 11:03 被阅读0次

    本文为课程实验,based on mengning mykernel 2.0,后续进阶见调试跟踪Linux内核的启动过程

    1. 准备工作


    使用cat /proc/version使用查看系统版本

    Develop your own OS kernel by reusing Linux infrastructure, based on x86-64/Linux Kernel 4.15.0. mykernel 1.0 based on IA32/Linux Kernel 3.9.4.

    2. 配置并编译mykernel 2.0


    wget https://raw.github.com/mengning/mykernel/master/mykernel-2.0_for_linux-5.4.34.patch
    sudo apt install axel
    axel -n 20 https://mirrors.edge.kernel.org/pub/linux/kernel/v5.x/linux-5.4.34.tar.xz
    xz -d linux-5.4.34.tar.xz
    tar -xvf linux-5.4.34.tar   # or tar -xvf linux-5.4.34.tar.gz
    cd linux-5.4.34
    patch -p1 < ../mykernel-2.0_for_linux-5.4.34.patch
    sudo apt install build-essential libncurses-dev bison flex libssl-dev libelf-dev
    make defconfig # Default configuration is based on 'x86_64_defconfig'
    make -j$(nproc) # 编译的时间比较久
    sudo apt install qemu # install QEMU
    qemu-system-x86_64 -kernel arch/x86/boot/bzImage
    
    编译完的运行结果

    从qemu窗口中您可以看到my_start_kernel在执行,同时my_timer_handler时钟中断处理程序周期性执行。

    可能报出的错误及解决方法:

    执行wget https://raw.github.com/mengning/mykernel/master/mykernel-2.0_for_linux-5.4.34.patch时可能会报以下错误:

    Connecting to raw.githubusercontent.com(raw.githubusercontent.com)|151.101.228.133|:443... failed: Connection refused.
    

    原因是GitHub的raw.githubusercontent.com域名解析被污染了,可以在https://www.ipaddress.com/查询raw.githubusercontent.com的真实IP,然后修改hosts,在/etc/hosts/中绑定查到的host,例如

    sudo vim /etc/hosts
    #绑定host
    199.232.28.133 raw.githubusercontent.com
    

    修改完hosts如果还不能成功运行,执行以下命令,取消证书的检查即可

     wget --no-check-certificate https://raw.github.com/mengning/mykernel/master/mykernel-2.0_for_linux-5.4.34.patch
    

    3. 添加简单时间片轮转调度模块


    在mymain.c基础上继续写进程描述PCB和进程链表管理等代码,在myinterrupt.c的基础上完成进程切换代码。首先在mykernel目录下增加一个mypcb.h 头文件,用来定义进程控制块(Process Control Block),也就是进程结构体的定义,在Linux内核中是struct tast_struct结构体。

    
    /*
     *  linux/mykernel/mypcb.h
     * [https://github.com/mengning/mykernel/blob/master/mypcb.h](https://github.com/mengning/mykernel/blob/master/mypcb.h)
     */
    
    
    #define MAX_TASK_NUM        4
    #define KERNEL_STACK_SIZE   1024*8
    
    
    /* CPU-specific state of this task */
    struct Thread {
        unsigned long       ip;
        unsigned long       sp;
    };
    
    
    typedef struct PCB{
        int pid;
        volatile long state; /* -1 unrunnable, 0 runnable, >0 stopped */
        char stack[KERNEL_STACK_SIZE];
        /* CPU-specific state of this task */
        struct Thread thread;
        unsigned long   task_entry;
        struct PCB *next;
    }tPCB;
    
    
    void my_schedule(void);
    

    对mymain.c进行修改,这里是mykernel内核代码的入口,负责初始化内核的各个组成部分。在Linux内核源代码中,实际的内核入口是init/main.c中的start_kernel(void)函数。

    /*
     *  linux/mykernel/mymain.c
     */
     
    #include "mypcb.h"
    
    
    tPCB task[MAX_TASK_NUM];
    tPCB * my_current_task = NULL;
    volatile int my_need_sched = 0;
    
    
    void my_process(void);
    
    
    void __init my_start_kernel(void)
    {
        int pid = 0;
        int i;
        /* Initialize process 0*/
        task[pid].pid = pid;
        task[pid].state = 0;/* -1 unrunnable, 0 runnable, >0 stopped */
        task[pid].task_entry = task[pid].thread.ip = (unsigned long)my_process;
        task[pid].thread.sp = (unsigned long)&task[pid].stack[KERNEL_STACK_SIZE-1];
        task[pid].next = &task[pid];
        /*fork more process */
        for(i=1;i<MAX_TASK_NUM;i++)
        {
            memcpy(&task[i],&task[0],sizeof(tPCB));
            task[i].pid = i;
            task[i].state = -1;
            task[i].thread.sp = (unsigned long)&task[i].stack[KERNEL_STACK_SIZE-1];
            task[i].next = task[i-1].next;
            task[i-1].next = &task[i];
        }
        /* start process 0 by task[0] */
        pid = 0;
        my_current_task = &task[pid];
        asm volatile(
            "movq %1,%%rsp\n\t"  /* set task[pid].thread.sp to rsp */
            "pushq %1\n\t"          /* push rbp */
            "pushq %0\n\t"          /* push task[pid].thread.ip */
            "ret\n\t"              /* pop task[pid].thread.ip to rip */
            :
            : "c" (task[pid].thread.ip),"d" (task[pid].thread.sp)   /* input c or d mean %ecx/%edx*/
        );
    }
    

    在mymain.c中添加了my_process函数,用来作为进程的代码模拟一个个进程,只是我们这里采用的是进程运行完一个时间片后主动让出CPU的方式,没有采用中断的时机完成进程切换,因为中断机制实现起来较为复杂,等后续部分再逐渐深入。

    void my_process(void)
    {
        int i = 0;
        while(1)
        {
            i++;
            if(i%10000000 == 0)
            {
                printk(KERN_NOTICE "this is process %d -\n",my_current_task->pid);
                if(my_need_sched == 1)
                {
                    my_need_sched = 0;
                    my_schedule();
                }
                printk(KERN_NOTICE "this is process %d +\n",my_current_task->pid);
            }
        }
    }
    

    进程运行过程中是怎么知道时间片消耗完了呢?这就需要时钟中断处理过程中记录时间片。对myinterrupt.c中修改my_timer_handler用来记录时间片。

    
    /*
     *  linux/mykernel/myinterrupt.c
     */
    #include "mypcb.h"
    
    
    extern tPCB task[MAX_TASK_NUM];
    extern tPCB * my_current_task;
    extern volatile int my_need_sched;
    volatile int time_count = 0;
    
    
    /*
     * Called by timer interrupt.
     */
    void my_timer_handler(void)
    {
        if(time_count%1000 == 0 && my_need_sched != 1)
        {
            printk(KERN_NOTICE ">>>my_timer_handler here<<<\n");
            my_need_sched = 1;
        }
        time_count ++ ;
        return;
    }
    

    对myinterrupt.c进行修改,主要是增加了进程切换的代码my_schedule(void)函数,在Linux内核源代码中对应的是schedule(void)函数。

    
    void my_schedule(void)
    {
        tPCB * next;
        tPCB * prev;
    
    
        if(my_current_task == NULL
            || my_current_task->next == NULL)
        {
          return;
        }
        printk(KERN_NOTICE ">>>my_schedule<<<\n");
        /* schedule */
        next = my_current_task->next;
        prev = my_current_task;
        if(next->state == 0)/* -1 unrunnable, 0 runnable, >0 stopped */
        {
          my_current_task = next;
          printk(KERN_NOTICE ">>>switch %d to %d<<<\n",prev->pid,next->pid);
          /* switch to next process */
          asm volatile(
             "pushq %%rbp\n\t"       /* save rbp of prev */
             "movq %%rsp,%0\n\t"     /* save rsp of prev */
             "movq %2,%%rsp\n\t"     /* restore  rsp of next */
             "movq $1f,%1\n\t"       /* save rip of prev */
             "pushq %3\n\t"
             "ret\n\t"               /* restore  rip of next */
             "1:\t"                  /* next process start here */
             "popq %%rbp\n\t"
            : "=m" (prev->thread.sp),"=m" (prev->thread.ip)
            : "m" (next->thread.sp),"m" (next->thread.ip)
          );
        }
        return;
    }
    

    修改完成之后运行以下命令重新编译运行:

    make clean
    make
    qemu-system-x86_64 -kernel arch/x86/boot/bzImage
    
    带有进程切换的内核

    可能报出的错误及解决方法:

    在修改完代码后执行make会出现以下错误:

    mykernel/mymain.c: Assembler messages:
    mykernel/mymain.c:48: 错误: bad register name `%rsp'
    mykernel/mymain.c:49: 错误: unsupported instruction `push'
    mykernel/mymain.c:50: 错误: unsupported instruction `push'
    scripts/Makefile.build:265: recipe for target 'mykernel/mymain.o' failed
    make[1]: *** [mykernel/mymain.o] Error 1
    Makefile:1691: recipe for target 'mykernel' failed
    make: *** [mykernel] Error 2
    

    看到错误的第一反应该是寄存器的位数不支持,所以我就把上述代码中的所有rsp、rbp寄存器改成了esp、ebp寄存器。pushq和movq都改成了pushl和movl,然后使用make再重新编译。结果倒是不报错了,qemu正常启动,但是却一直卡在了Booting from ROM....

    最后的做法是改回了原来的代码,然后使用make clean和两次make然后又运行成功了?!如果出现这种错误你也可以试一试......

    4. 代码分析


    4.1 时间片轮转调度模块代码分析

    最终修改完成的mypcb.hmymain.cmyinterrupt.c文件内容如下(使用注释解释):

    /*
     *  linux/mykernel/mymain.c
     *
     *  Kernel internal my_start_kernel
     *  Change IA32 to x86-64 arch, 2020/4/26
     *
     *  Copyright (C) 2013, 2020  Mengning
     *  
     */
    #include <linux/types.h>
    #include <linux/string.h>
    #include <linux/ctype.h>
    #include <linux/tty.h>
    #include <linux/vmalloc.h>
    
    
    #include "mypcb.h"
    
    tPCB task[MAX_TASK_NUM];     //声明tPCB类型的数组
    tPCB * my_current_task = NULL;    //声明当前task的指针
    volatile int my_need_sched = 0;     //判断是否需要调度
    
    void my_process(void);
    
    /** 从my_start_kernel开始执行,实际的内核入口是init/main.c中的start_kernel(void)函数 **/
    void __init my_start_kernel(void)
    {
        int pid = 0;
        int i;
        /* Initialize process 0*/
        task[pid].pid = pid;      //初始化0号进程
        task[pid].state = 0;/* -1 unrunnable, 0 runnable, >0 stopped */
        task[pid].task_entry = task[pid].thread.ip = (unsigned long)my_process;   //入口
        task[pid].thread.sp = (unsigned long)&task[pid].stack[KERNEL_STACK_SIZE-1];
        task[pid].next = &task[pid];
        /*
        ======= fork more process =======
        Linux创建子进程时,也是使用fork复制进程,然后改变一些关键信息,比如进程PID等
        */
        for(i=1;i<MAX_TASK_NUM;i++)   
        {
            memcpy(&task[i],&task[0],sizeof(tPCB));
            task[i].pid = i;
            task[i].thread.sp = (unsigned long)(&task[i].stack[KERNEL_STACK_SIZE-1]);
            task[i].next = task[i-1].next;
            task[i-1].next = &task[i];
        }
        /* start process 0 by task[0] */
        pid = 0;
        my_current_task = &task[pid];
        asm volatile(
            "movq %1,%%rsp\n\t"     /* set task[pid].thread.sp to rsp */
            "pushq %1\n\t"             /* push rbp */
            "pushq %0\n\t"             /* push task[pid].thread.ip */
            "ret\n\t"                 /* pop task[pid].thread.ip to rip */
            : 
            : "c" (task[pid].thread.ip),"d" (task[pid].thread.sp)    /* input c or d mean %ecx/%edx*/
        );
    } 
    
    int i = 0;
    
    /** 进程运行体:用来作为进程的代码模拟一个个进程 **/
    void my_process(void)
    {    
        while(1)
        {
            i++;
            if(i%10000000 == 0)
            {
                printk(KERN_NOTICE "this is process %d -\n",my_current_task->pid);
                if(my_need_sched == 1)    //判断是否需要调度
                {
                    my_need_sched = 0;
                    my_schedule();
                }
                printk(KERN_NOTICE "this is process %d +\n",my_current_task->pid);
            }     
        }
    }
    
    /*
     *  linux/mykernel/mypcb.h
     *
     *  Kernel internal PCB types
     *
     *  Copyright (C) 2013  Mengning
     *
     */
    
    /** 定义进程的最大数量和内核栈的大小 **/
    #define MAX_TASK_NUM        4
    #define KERNEL_STACK_SIZE   1024*2
    /* CPU-specific state of this task */
    
    //存储ip,sp
    struct Thread {
        unsigned long        ip;
        unsigned long        sp;
    };
    
    typedef struct PCB{
        int pid;    //进程的id
        volatile long state;    /* 定义进程状态: -1 unrunnable, 0 runnable, >0 stopped */
        unsigned long stack[KERNEL_STACK_SIZE];  //进程堆栈
        /* CPU-specific state of this task */
        struct Thread thread;
        unsigned long    task_entry;      //进程入口,
        struct PCB *next;    //指向下一个进程PCB
    }tPCB;
    
    //调度函数
    void my_schedule(void);
    
    /*
     *  linux/mykernel/myinterrupt.c
     *
     *  Kernel internal my_timer_handler
     *  Change IA32 to x86-64 arch, 2020/4/26
     *
     *  Copyright (C) 2013, 2020  Mengning
     *
     */
    #include <linux/types.h>
    #include <linux/string.h>
    #include <linux/ctype.h>
    #include <linux/tty.h>
    #include <linux/vmalloc.h>
    
    #include "mypcb.h"
    
    /* task:任务队列
     * my_current_task:当前运行的进程
     * my_need_sched:调度标示
     * time_count:计数器
     */
    extern tPCB task[MAX_TASK_NUM];
    extern tPCB * my_current_task;
    extern volatile int my_need_sched;
    volatile int time_count = 0;
    
    /* 模拟时钟中断 */
    void my_timer_handler(void)
    {
        if(time_count%1000 == 0 && my_need_sched != 1)   //控制时间片的大小,设置调度的标志
        {
            printk(KERN_NOTICE ">>>my_timer_handler here<<<\n");
            my_need_sched = 1;
        } 
        time_count ++ ;  
        return;      
    }
    /* 进程切换 */
    void my_schedule(void)   
    {
        tPCB * next;
        tPCB * prev;
    
        if(my_current_task == NULL 
            || my_current_task->next == NULL){
            return;
        }
        printk(KERN_NOTICE ">>>my_schedule<<<\n");
        /* schedule */
        next = my_current_task->next;
        prev = my_current_task;
        if(next->state == 0)/* -1 unrunnable, 0 runnable, >0 stopped 根据下一个进程的状态来判断是否切换*/
        {        
            my_current_task = next; 
            printk(KERN_NOTICE ">>>switch %d to %d<<<\n",prev->pid,next->pid);  
            /* switch to next process */
            asm volatile(    
                "pushq %%rbp\n\t"         /* save rbp of prev */
                "movq %%rsp,%0\n\t"     /* save rsp of prev */
                "movq %2,%%rsp\n\t"     /* restore  rsp of next */
                "movq $1f,%1\n\t"       /* save rip of prev ,%1f指接下来的标号为1的位置*/    
                "pushq %3\n\t" 
                "ret\n\t"                 /* restore  rip of next */
                "1:\t"                  /* next process start here */
                "popq %%rbp\n\t"
                : "=m" (prev->thread.sp),"=m" (prev->thread.ip)
                : "m" (next->thread.sp),"m" (next->thread.ip)
            ); 
        }  
        return;    
    }
    

    4.2 操作系统内核核心功能及运行工作机制分析

    4.2.0 准备工作:内嵌汇编语法
    内嵌汇编语法
    ============================ 示例 ==============================
    /* 下面的%0和%1代表第一个参数和第二个参数,其index是从输出部分算起,到输入部分结束 
      "=m" 表示内存变量只写
      "r"表示将输入变量放入通用寄存器
      %%表示转移字符
      $0表示立即数0
    */
    int main(void){
        int input, output, temp;
        input = 1;
        __asm__ __volatile__(
            "movl $0, %%eax; \n\t"       // eax = 0
            "movl %%eax, %1; \n\t"      // temp = 0
            "movl %2, %%eax; \n\t"      // eax = input = 1
            "movl %%eax, %0; \n\t"      // output = eax = 1
            :"=m"(output), "=m"(temp)    // $0 = output  $1 = temp
            :"r"(input)   // $2 = input
            :"eax");
        // 输出为 0, 1
        printf("%d, %d \n",temp, output);
        return 0;
    }
    
    4.2.1 启动执行第一个进程的关键汇编代码分析
    asm volatile(
        "movq %1,%%rsp\n\t" /* 将进程原堆栈栈顶的地址存入RSP寄存器 */
        "pushq %1\n\t"      /* 将当前RBP寄存器值压栈 */
        "pushq %0\n\t"      /* 将当前进程的RIP压栈 */
        "ret\n\t"           /* ret命令正好可以让压栈的进程RIP保存到RIP寄存器中 */
        :
        : "c" (task[pid].thread.ip),"d" (task[pid].thread.sp)
    );
    

    由于启动的第一个进程是我们自己初始化好的0号进程,所以上面代码的task[pid].thread.iptask[pid].thread.sp分别为0号进程ip和sp。

    • movq %1,%%rsp:将RSP寄存器指向进程0的堆栈栈底
    • pushq %1:本来应该压栈当前进程的RBP,因为是空栈,所以RSP与RBP相同,这里简化起见,直接使用进程的堆栈栈顶的值task[pid].thread.sp,之后RSP = RSP - 8(堆栈地址空间从高到低,位数为64位)
    • pushq %0:将当前进程的RIP(这里是初始化的值my_process(void)函数的位置)入栈,RSP = RSP - 8
    • ret:将栈顶位置的task[0].thread.ip,也就是my_process(void)函数的地址放入RIP寄存器中,RSP = RSP + 8,修改IP的内容,从而实现近转移
    4.2.2 进程上下文切换的关键代码分析
        printk(KERN_NOTICE ">>>switch %d to %d<<<\n",prev->pid,next->pid);  
            /* switch to next process */
            asm volatile(   
                "pushq %%rbp\n\t"       /* save rbp of prev */
                "movq %%rsp,%0\n\t"     /* save rsp of prev */
                "movq %2,%%rsp\n\t"     /* restore  rsp of next */
                "movq $1f,%1\n\t"       /* save rip of prev */  
                "pushq %3\n\t" 
                "ret\n\t"               /* restore  rip of next */
                "1:\t"                  /* next process start here */
                "popq %%rbp\n\t"
                : "=m" (prev->thread.sp),"=m" (prev->thread.ip)
                : "m" (next->thread.sp),"m" (next->thread.ip)
            ); 
    

    为了简便,假设系统只有两个进程,分别是进程0和进程1。进程0由内核启动时初始化执行,然后需要进程调度和进程切换,然后开始执行进程1。进程切换过程中进程0和进程1的堆栈和相关寄存器的变化过程大致如下:

    • pushq %%rbp:保存0号进程的rbp,rsp = rsp - 8(x86向下增长)
    • movq %%rsp,%0:把0号进程的rsp保存在prev->thread.sp变量中
    • movq %2,%%rsp:rsp指向1号进程的栈顶
    • movq $1f,%1:其中的$1f是magic number,指的是下面的1:的地址,这句的作用是prev->thread.ip = $1f
    • pushq %3:把即将执行的next进程的指令地址next->thread.ip入栈,这时的next->thread.ip可能是进程1的起点my_process(void)函数,也可能是$1f(标号1)。第一次被执行从头开始为进程1的起点my_process(void)函数,其余的情况均为$1f(标号1),因为next进程如果之前运行过那么它就一定曾经也作为prev进程被进程切换过
    • ret:就是将压入栈中的next->thread.ip放入RIP寄存器,为什么不直接放入RIP寄存器呢?因为程序不能直接使用RIP寄存器,只能通过call、ret等指令间接改变RIP寄存器。使用ret从而实现近转移
    • 1::标号1是一个特殊的地址位置,该位置的地址是$1f。
    • popq %%rbp:像这段代码的第一句pushq %%rbp一样,进程切换时会把当前栈的基址RBP保存在栈顶。所以本条命令的作用就是将1号进程堆栈基地址从堆栈中恢复到RBP寄存器中,从而完成进程的切换,即RBP和RSP都指向了进程1的堆栈。

    参考文章:

    相关文章

      网友评论

        本文标题:编写一个简单的操作系统内核(Linux Kernel)

        本文链接:https://www.haomeiwen.com/subject/qwvdnhtx.html