基于mykernel2.0 编写一个操作系统内核

基于mykernel2.0 编写一个操作系统内核

一、实验要求

  1. 按照https://github.com/mengning/mykernel 的说明配置mykernel 2.0,熟悉Linux内核的编译;
  2. 基于mykernel 2.0编写一个操作系统内核,参照https://github.com/mengning/mykernel 提供的范例代码
  3. 简要分析操作系统内核核心功能及运行工作机制

二、实验目的

  1. 理解Linux操作系统内核工作原理;
  2. 理解进程调度和中断机制

三、实验环境

mac OS 15.4+Vmare Funsion + Ubuntu 18.04.1 LTS

四、实验步骤

1.下载mykernel并编译

在终端依次执行下述命令

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
cd linux-5.4.34
patch -p1 < ../mykernel-2.0_for_linux-5.4.34.patch
sudo apt install build-essential gcc-multilib  libncurses5-dev bison flex libssl-dev libelf-dev
sudo apt install qemu # install QEMU
make defconfig # Default configuration is based on 'x86_64_defconfig'
make -j$(nproc)

在这有一个错误需要注意一下:(最开始使用Cent os做的,这是遇到的问题之一:,放弃的原因是因为之前装的Cent os没界面,无法启动qemu)

解决方案:

Ubuntu:

apt install libelf-dev

apt install libssl-dev
CentOS:

yum install elfutils-libelf-devel

2.启动mykernel

qemu-system-x86_64 -kernel arch/x86/boot/bzImage

在执行了该命令后,会弹出如下一个窗口:可以看到mymain.c的代码在不停的执行的同时,会有一个周期性的时钟中断信号来触发myinterrupt.c的代码。

打开mymain.c和myinterrupt.c两个源代码可以看到,mymain.c中每100000计数输出my_start_kernel here,myinterrupt.c每200000计数输出my_timer_handler here。当前有一个CPU执行C代码的上下文环境,同时具有中断处理程序的上下文环境,我们通过Linux内核代码模拟了一个具有时钟中断和C代码执行环境的硬件平台。

void __init my_start_kernel(void)
{
    int i = 0;
    while(1)
    {
        i++;
        if(i%100000 == 0)
            pr_notice("my_start_kernel here  %d 
",i);
            
    }
}
void my_timer_handler(void)
{
    pr_notice("
>>>>>>>>>>>>>>>>>my_timer_handler here<<<<<<<<<<<<<<<<<<

");
}
3. 编写一个操作系统内核

参照-https://github.com/mengning/mykernel

3.1定义进程控制块(PCB)

既然要内核控制进程,那就要为进程设计一个数据结构来存储进程的信息,如下是PCB(进程控制块)的定义:

mypcb.h

#define MAX_TASK_NUM        4
#define KERNEL_STACK_SIZE   1024*2
/* 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 */
    unsigned long 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);

3.2修改mymain.c

在修改程序代码之前先对内联汇编代码进行一下解释:

asm volatile(
    "movq %1,%%rsp
	"     /* 将进程原堆栈栈顶的地址存⼊RSP寄存器 */
    "pushq %1
	"          /* 将当前RBP寄存器值压栈 */
    "pushq %0
	"         /* 将当前进程的RIP压栈 */
    "ret
	"              /* ret命令正好可以让压栈的进程RIP保存到RIP寄存器中 */
    :
    : "c" (task[pid].thread.ip),"d" (task[pid].thread.sp)   /* input c or d mean %ecx/%edx*/
);

 movq %1,%%rsp 将RSP寄存器指向进程0的堆栈栈底,task[pid].thread.sp初始值即为进程0的堆栈栈底。

 pushq %1  将当前RBP寄存器的值压栈,因为是空栈,所以RSP与RBP相同。这⾥简化起⻅,直接使⽤进程的堆栈栈顶的值task[pid].thread.sp,相应的RSP寄存器指向的位置也发⽣了变化,RSP = RSP - 8,RSP寄存器指向堆栈底部第⼀个64位的存储单元。

 pushq %0将当前进程的RIP(这⾥是初始化的值my_process(void)函数的位置)⼊栈,相应的RSP寄存器指向的位置也发⽣了变化,RSP = RSP - 8,RSP寄存器指向堆栈底部第⼆个64位的存储单元。

 ret将栈顶位置的task[0].thread.ip,也就是my_process(void)函数的地址放⼊RIP寄存器中,相应的RSP寄存器指向的位置也发⽣了变化,RSP = RSP + 8,RSP寄存器指向堆栈底部第⼀个64位的存储单元。

修改mymain.c中的my_start_kernel函数,并在其中实现了my_process函数,作为进程的代码模拟一个个进程,时间片轮转调度。

/*
 *  linux/mykernel/mymain.c
 *  Kernel internal my_start_kernel
 */
 #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 * my_current_task = NULL;
 volatile int my_need_sched = 0;
 
 void my_process(void);//模拟进程执行代码
 
 
 void __init my_start_kernel(void)
 {
     int pid = 0;//0号进程
     int i;
     /* 初始化0号进程PCB信息*/
     task[pid].pid = pid;
     task[pid].state = 0;/* -1 unrunnable, 0 runnable, >0 stopped */
    //任务入口地址,将my_process的地址赋给ip
     task[pid].task_entry = task[pid].thread.ip = (unsigned long)my_process;
     //0号进程PCB堆栈栈顶地址赋给sp
     task[pid].thread.sp = (unsigned long)&task[pid].stack[KERNEL_STACK_SIZE-1];
         //系统刚开始只有一个进程,下一个进程地址指向自身
     task[pid].next = &task[pid];
     /*fork more process */
         //复制0号进程创建更多进程,并对它们赋值,插入队列
     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] */
         //启动0号任务,开始执行0号进程
     pid = 0;
    my_current_task = &task[pid];//当前任务指针
         
         /*下面这一段是进程执行的关键汇编代码,下文会对其进行详细分析
           *  %1指task[pid].thread.sp,%0指task[pid].thread.ip
           */
     asm volatile(
         "movq %1,%%rsp
	"     /* set task[pid].thread.sp to rsp */
         "pushq %1
	"             /* push rbp */
         "pushq %0
	"             /* push task[pid].thread.ip */
        "ret
	"                 /* 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;

 //模拟进程执行过程,这⾥采⽤的是进程运⾏完⼀个时间⽚后主动让出CPU的⽅式。
 void my_process(void)
 {    
     while(1)
     {
         i++;
        if(i%10000000 == 0)
         {
             printk(KERN_NOTICE "this is process %d -
",my_current_task->pid);
           if(my_need_sched == 1)//判断是否需要调度
            {
                my_need_sched = 0;
                my_schedule();//执行调度
             }
             printk(KERN_NOTICE "this is process %d +
",my_current_task->pid);
         }     
    }

void __init my_start_kernel(void)函数是mykernel内核代码的⼊⼝,负责初始化内核的各个组成部分。在Linux内核源代码中,实际的内核⼊⼝是init/main.c中的start_kernel(void)函数。

在my_process函数的while循环里面可见,会不断检测全局变量my_need_sched的值,当my_need_sched的值从0变成1的时候,就需要发生进程调度,全局变量my_need_sched重新置为0,执行my_schedule()函数进行进程切换。

3.3修改myinterrupt.c

先对其中的数据结构进行解释:

asm volatile(    
    "pushq %%rbp
	"         /* save rbp of prev */
    "movq %%rsp,%0
	"     /* save rsp of prev */
    "movq %2,%%rsp
	"     /* restore  rsp of next */
    "movq $1f,%1
	"       /* save rip of prev */    
    "pushq %3
	" 
      "ret
	"                 /* restore  rip of next */
      "1:	"                  /* next process start here */
          "popq %%rbp
	"
         : "=m" (prev->thread.sp),"=m" (prev->thread.ip)
          : "m" (next->thread.sp),"m" (next->thread.ip)
);
 pushq %%rbp  保存prev进程(本例中指进程0)当前RBP寄存器的值到prev进程的堆栈;

 movq %%rsp,%0  保存prev进程(本例中指进程0)当前RSP寄存器的值到prev->thread.sp,这时RSP寄存器指向进程的栈顶地址,实际上就是将prev进程的栈顶地址保存;%0、%1...指这段汇编代码下面输入输出部分的编号。

 movq %2,%%rsp  将next进程的栈顶地址next->thread.sp放入RSP寄存器,完成了进程0和进程1的堆栈切换。

 movq $1f,%1  保存prev进程当前RIP寄存器值到prev->thread.ip,这里$1f是指标号1,恢复进程后从此执行。

 pushq %3  把即将执行的next进程的指令地址next->thread.ip入栈。

 ret  就是将压入栈中的next->thread.ip放入rip寄存器,rip寄存器现在存储next进程的指令。

 1: next 进程开始执行的位置。

 popq %%rbp  将next进程堆栈基地址从堆栈中恢复到RBP寄存器

修改源代码:

/*
 * Called by timer interrupt.
 * it runs in the name of current running process,
 * so it use kernel stack of current running process
 */
void my_timer_handler(void)
{
    if(time_count%1000 == 0 && my_need_sched != 1)//设置时间片的大小,时间片用完则开始调度
    {
        printk(KERN_NOTICE ">>>my_timer_handler here<<<
");
        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<<<
");
    /* 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<<<
",prev->pid,next->pid);  
        /* 进程切换 */
    //下面是进程切换的汇编代码,下文将进行详细分析
        asm volatile(    
            "pushq %%rbp
	"         /* save rbp of prev */
            "movq %%rsp,%0
	"     /* save rsp of prev */
            "movq %2,%%rsp
	"     /* restore  rsp of next */
            "movq $1f,%1
	"       /* save rip of prev */    
            "pushq %3
	" 
            "ret
	"                 /* restore  rip of next */
            "1:	"                  /* next process start here */
            "popq %%rbp
	"
            : "=m" (prev->thread.sp),"=m" (prev->thread.ip)
            : "m" (next->thread.sp),"m" (next->thread.ip)
        ); 
    }  
    return;    
}

mykernel提供了时钟中断机制,周期性执行my_time_handler中断处理程序,该函数定时观察my_need_sched是否不等于1,如果是则将其置为1,使myprocess执行my_schedule()。

my_schedule函数在PCB环形队中选择下一个进程进行执行,但对于处于不同状态的进程,调度方式略有不同,如果即将上CPU的进程之前已经运行过(即state为0),我们保存当前进程的信息,然后把下一个进程的信息写入到寄存器中,执行ret使下一个进程开始执行。

之前没有在运行态的(state不为0),我们先将其设置为运行态,我们这里需要初始化其ebp,因为该进程的堆栈是空栈esp=ebp。

3.4再次编译、运行

make defconfig # Default configuration is based on 'x86_64_defconfig'
make -j$(nproc)
qemu-system-x86_64 -kernel arch/x86/boot/bzImage

1805024-20200511234104763-1137623719

实验总结:

通过这次编写一个操作系统内核的实验,让我了解了进程切换调度的过程,在进程切换调度过程中,需要先保存当前进程的上下文环境,然后加载需要调度的进程执行环境。在这个过程中,需要结合进程堆栈,esp堆栈栈顶指针寄存器,ebp堆栈栈底指针寄存器以及eip指令寄存器来共同完成。

原文地址:https://www.cnblogs.com/AmosYang6814/p/12884510.html