基于时间片轮转多道程序内核代码的分析

本文介绍了基于Linux内核3.9.4的时间片轮转多道程序实验,通过分析代码展示了操作系统如何进行进程切换。在实验过程中,作者创建了简单的操作系统并在QEMU上运行,然后通过修改代码实现时间片轮转,观察到了从process3到process0的切换。代码分析部分重点讲解了mypcb.h、mymain.c和myinterrupt.c的作用,特别是进程控制块PCB结构体、进程状态管理和调度算法。实验总结强调了中断在进程调度中的关键角色以及对操作系统工作原理的理解。

学号尾号307+原创作品转载请注明出处 +《Linux操作系统分析》 孟宁
本实验资源链接:https://github.com/mengning/linuxkernel/

一、实验指导

sudo apt-get install qemu # install QEMU
sudo ln -s /usr/bin/qemu-system-i386 /usr/bin/qemu
wget https://www.kernel.org/pub/linux/kernel/v3.x/linux-3.9.4.tar.xz # download Linux Kernel 3.9.4 source code
wget https://raw.github.com/mengning/mykernel/master/mykernel_for_linux3.9.4sc.patch # download mykernel_for_linux3.9.4sc.patch
xz -d linux-3.9.4.tar.xz
tar -xvf linux-3.9.4.tar
cd linux-3.9.4
patch -p1 < ../mykernel_for_linux3.9.4sc.patch
make allnoconfig
make
qemu -kernel arch/x86/boot/bzImage 从qemu窗口中您可以看到my_start_kernel在执行,同时my_timer_handler时钟中断处理程序周期性执行。
cd mykernel 您可以看到qemu窗口输出的内容的代码mymain.c和myinterrupt.c
当前有一个CPU执行C代码的上下文环境,同时具有中断处理程序的上下文环境,我们初始化好了系统环境。
您只要在mymain.c基础上继续写进程描述PCB和进程链表管理等代码,在myinterrupt.c的基础上完成进程切换代码,一个可运行的小OS kernel就完成了。
start to write your own OS kernel,enjoy it!

二、实验准备

可以直接实验楼中进行实验,也可以自己搭建环境。
这里用的是用自己搭建的虚拟机环境。
根据上述的指导下载相应的 Linux Kernel 3.9.4 source codemykernel下的mymain.cmyinterrupt.cmypcb.h

三、实验过程

1.简单的操作系统
cd linux-3.9.4
patch -p1 < ../mykernel_for_linux3.9.4sc.patch
make allnoconfig
make #编译内核时间较长
qemu -kernel arch/x86/boot/bzImage 

在QEMU窗口中可以看到my_start_kernel在执行,同时my_timer_handler时钟中断处理程序周期性执行,运行结果如下:
在这里插入图片描述
在QEMU窗口,我们可以看到一个简单的操作系统已经跑起来了,当然这个系统很简单,只是不停的输出一些字符串:>>>>>my_timer_handler here <<<<< 和 my_start_kernel here 。

2.简单的时间片轮转多道程序

退出QEMU窗口,用上述下载的mymain.c、myiterrupt.c、mypcb.h替换和新建在mykernel中重新编译。

make allnoconfig
make #编译内核时间较长
qemu -kernel arch/x86/boot/bzImage 

运行结果如下:
在这里插入图片描述
从QEMU的窗口中可以看出,系统从执行process3切换到process0的过程。

三、代码分析

1.第一个实验

在这里插入图片描述
可以看到,在mymain.c的my_start_kernel函数中有一个循环,不停的输出 my_start_kernel here。
在这里插入图片描述
在myinterrupt.c中,可以看到一个会被时钟中断周期调用的函数my_timer_handler ,在这个函数里,会输出类似>>>>>my_timer_handler here <<<<< 的字符串。
通过这个实验我们可以知道,mykernel系统启动后,会:
1.调用my_start_kernel函数
2.周期性的调用my_timer_handler函数

2.时间片轮转多道程序

主要有三个文件,作用如下:

1.mypcb.h : 进程控制块PCB结构体定义。
2.mymain.c: 初始化各个进程并启动0号进程。
3.myinterrupt.c:时钟中断处理和进程调度算法。

1.mypcb.h

/*
 *  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 */
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);

在这个文件里,定义了 Thread 结构体,用于存储当前进程中正在执行的线程的ip和sp,PCB结构体中的各个字段含义如下
pid:进程号

state:进程状态,在模拟系统中,所有进程控制块信息都会被创建出来,其初始化值就是-1,如果被调度运行起来,其值就会变成0

stack:进程使用的堆栈

thread:当前正在执行的线程信息

task_entry:进程入口函数

next:指向下一个PCB,模拟系统中所有的PCB是以链表的形式组织起来的。

这里还有一个函数的声明 my_schedule,它的实现在my_interrupt.c中,在mymain.c中的各个进程函数会根据一个全局变量的状态来决定是否调用它,从而实现主动调度。

2.mymain.c

/*
 *  linux/mykernel/mymain.c
 *
 *  Kernel internal my_start_kernel
 *
 *  Copyright (C) 2013  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 * 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[0].pid=0;
    task[pid].state = 0;/* -1 unrunnable, 0 runnable, >0 stopped */
    task[pid].task_entry = task[pid].thread.ip = (unsigned long)my_process;//令0号进程的入口地址为my_process();
    task[pid].thread.sp = (unsigned long)&task[pid].stack[KERNEL_STACK_SIZE-1];//0号进程的栈顶为stack[]数组的最后一个元素
    task[pid].next = &task[pid];
    /*fork more process */
    for(i=1;i<MAX_TASK_NUM;i++)//根据0号进程,MAX_TASK_NUM=4最多只能复制出四个进程
    {
        memcpy(&task[i],&task[0],sizeof(tPCB));//void *memcpy(void *dest, const void *src, size_t n);从源src所指的内存地址的起始位置开始拷贝n个字节到目标dest所指的内存地址的起始位置中。
        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;//新创建的进程的第一个进程next指向0号进程的首地址
        task[i-1].next = &task[i];//前一个进程的next指向最新创建的进程的首地址,从而成为一个循环链表。
    }
    /* start process 0 by task[0] */
    pid = 0;
    my_current_task = &task[pid];//当前运行的进程设置为0号进程。
    asm volatile( //volatile 禁止编译器使用优化功能
        "movl %1,%%esp\n\t"     /* set task[pid].thread.sp to esp */
        "pushl %1\n\t"          /* push ebp */
        "pushl %0\n\t"          /* push task[pid].thread.ip */
        "ret\n\t"               /* pop task[pid].thread.ip to eip */
        "popl %%ebp\n\t"    //将一个进程的ebp 和 eip 分别压栈
        : 
        : "c" (task[pid].thread.ip),"d" (task[pid].thread.sp)   /* input c or d mean %ecx/%edx*/
    );
}   
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;//01轮换调度
                my_schedule();
            }
            printk(KERN_NOTICE "this is process %d +\n",my_current_task->pid);//打印+号
        }     
    }
}

正如前文所述,这里的函数 my_start_kernel 是系统启动后,最先调用的函数,在这个函数里完成了0号进程的初始化和启动,并创建了其它的进程PCB,以方便后面的调度。在模拟系统里,每个进程的函数代码都是一样的,即 my_process 函数,my_process 在执行的时候,会打印出当前进程的 id,从而使得我们能够看到当前哪个进程正在执行。

另外,在 my_process 也会检查一个全局标志变量 my_need_sched,一旦发现其值为 1 ,就调用 my_schedule 完成进程的调度。

0号线程的启动,采用了内联汇编代码完成,详细参见源码中的注释。

3.myinterrupt.c

/*
 *  linux/mykernel/myinterrupt.c
 *
 *  Kernel internal my_timer_handler
 *
 *  Copyright (C) 2013  Mengning
 *
 */
#include <linux/types.h>
#include <linux/string.h>
#include <linux/ctype.h>
#include <linux/tty.h>
#include <linux/vmalloc.h>

#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.
 * it runs in the name of current running process,
 * so it use kernel stack of current running process
 */
void my_timer_handler(void)
{
#if 1
    if(time_count%1000 == 0 && my_need_sched != 1)
    {
        printk(KERN_NOTICE ">>>my_timer_handler here<<<\n");
        my_need_sched = 1;
    } 
    time_count ++ ;  
#endif
    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;//my_current_task->next即为下一个将要运行的进程
    prev = my_current_task;//将当前进程设置为prev进程。
    if(next->state == 0)/*如果下一个将要运行的进程已经处于运行状态 -1 unrunnable, 0 runnable, >0 stopped */
    {
        /* switch to next process */ esp:栈顶指针 ebp:栈底指针 eip:下一条指令存放的内存地址
        asm volatile(   
            "pushl %%ebp\n\t"       /* 保存当前进程的ebp到自己的栈中。    save ebp */
            "movl %%esp,%0\n\t"     /* 保存当前进程的esp到自己的栈中。    save esp */
            "movl %2,%%esp\n\t"     /* 从next->thread.sp中弹出下一个进程的esp。与第二句相对应。   restore  esp */
            "movl $1f,%1\n\t"       /* 将下一个进程的eip设置为1f。$1f就是指标号1:的代码在内存中存储的地址  save eip */   
            "pushl %3\n\t"          /* 将next->thread.ip压入当前进程的栈中。*/
            "ret\n\t"               /* 从当前进程的栈中弹出刚刚压入的next->thread.ip。完成进程切换。  restore  eip */
            "1:\t"                  /* 即$1f指向的位置。next process start here */
            "popl %%ebp\n\t"        /* 切换到的进程把ebp从栈中弹出至ebp寄存器。与第一句相对应。*/
            : "=m" (prev->thread.sp),"=m" (prev->thread.ip)
            : "m" (next->thread.sp),"m" (next->thread.ip)
        ); 
        my_current_task = next; //当前进程切换为next
        printk(KERN_NOTICE ">>>switch %d to %d<<<\n",prev->pid,next->pid); //打印切换信息     
    }
    else//如果下一个将要运行的进程还从未运行过。
    {
        next->state = 0;//将其设置为运行状态。
        my_current_task = next;//当前进程切换为next
        printk(KERN_NOTICE ">>>switch %d to %d<<<\n",prev->pid,next->pid);//打印切换信息
        /* switch to new process */
        asm volatile(   
            "pushl %%ebp\n\t"       /* save ebp */
            "movl %%esp,%0\n\t"     /* save esp */
            "movl %2,%%esp\n\t"     /* restore  esp */
            "movl %2,%%ebp\n\t"     /* restore  ebp */
            "movl $1f,%1\n\t"       /* 将要被切换出去的进程的ip设置为$1f。这样等一下它被切换回来时(一定是运行状态)肯定会进入if判断分支,可以从if中的标号1处继续执行。  save eip */    
            "pushl %3\n\t"          /* 将next->thread.ip(因为它还没有被运行过,所以next->thread.ip现在仍处于初始状态,即指向my_process(),压入将要被切换出去的进程的堆栈。*/
            "ret\n\t"               /* 将刚刚压入的next->thread.ip出栈至eip,完成进程切换。   restore  eip */
            : "=m" (prev->thread.sp),"=m" (prev->thread.ip)
            : "m" (next->thread.sp),"m" (next->thread.ip)
        );          
    }

这里 my_timer_handler 函数会被内核周期性的调用,每调用1000次,就去将全局变量my_need_sched的值修改为1,通知正在执行的进程执行调度程序my_schedule。在my_schedule函数中,完成进程的切换。进程的切换分两种情况,一种情况是下一个进程没有被调度过,另外一种情况是下一个进程被调度过,可以通过下一个进程的state知道其状态。进程切换依然是通过内联汇编代码实现,无非是保存旧进程的eip和堆栈,将新进程的eip和堆栈的值存入对应的寄存器中,详见代码中的注释

四、总结

1. 操作系统是如何工作的

通过本次的实验让我认识到了,操作系统进程的切换都是通过中断来进行调度的,以及进程切换的时候各个寄存器保存的内容,如何完成进程切换的,以及如何保护现场有了深刻的理解。每个操作系统都有一个父进程,也就是我们所说的0号进程,操作系统的启动以及多进程的发展都是从该进程衍生而来的。本次实验使我深刻认识到了操作系统进程间的轮换调度。

2.遇到的问题

(一)编译时提示fatal error: linux/compiler-gcc7.h

找了网上的各种方法,最后发现版本不匹配,遂重新下载并配置了一个ubuntu环境,解决。

(二)sudo apt-get install qemu时提示Unable to locate package qemu

修改更新源的方法
sudo gedit /etc/apt/sources.list
#163源 直接添加在文件后面
deb http://mirrors.163.com/ubuntu/ precise main restricted
deb-src http://mirrors.163.com/ubuntu/ precise main restricted
deb http://mirrors.163.com/ubuntu/ precise-updates main restricted
deb-src http://mirrors.163.com/ubuntu/ precise-updates main restricted
deb http://mirrors.163.com/ubuntu/ precise universe
deb-src http://mirrors.163.com/ubuntu/ precise universe
deb http://mirrors.163.com/ubuntu/ precise-updates universe
deb-src http://mirrors.163.com/ubuntu/ precise-updates universe
deb http://mirrors.163.com/ubuntu/ precise multiverse
deb-src http://mirrors.163.com/ubuntu/ precise multiverse
deb http://mirrors.163.com/ubuntu/ precise-updates multiverse
deb-src http://mirrors.163.com/ubuntu/ precise-updates multiverse
deb http://mirrors.163.com/ubuntu/ precise-backports main restricted universe multiverse
deb-src http://mirrors.163.com/ubuntu/ precise-backports main restricted universe multiverse
deb http://mirrors.163.com/ubuntu/ precise-security main restricted
deb-src http://mirrors.163.com/ubuntu/ precise-security main restricted
deb http://mirrors.163.com/ubuntu/ precise-security universe
deb-src http://mirrors.163.com/ubuntu/ precise-security universe
deb http://mirrors.163.com/ubuntu/ precise-security multiverse
deb-src http://mirrors.163.com/ubuntu/ precise-security multiverse
deb http://extras.ubuntu.com/ubuntu precise main
deb-src http://extras.ubuntu.com/ubuntu precise main
再次输入
sudo apt-get update,
sudo apt-get upgrade。
即可

(三)第二个实验make时一直生成不了mymain.o

删除mypcb.h中# unsigned long 即可
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值