This repository has been archived by the owner on Aug 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsched.c
75 lines (65 loc) · 1.43 KB
/
sched.c
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
/*
Task scheduling.
*/
#include "defs.h"
#define MAX_TASKS 10
#define STACK_SIZE 1024
uint8 task_stacks[MAX_TASKS][STACK_SIZE];
Context tasks[MAX_TASKS];
Context os_context;
Context *current_context;
int _num_of_tasks = 0; // number of tasks
int _current_task = -1; // current task id, init to -1 if no task
/*
Initialize scheduler.
*/
void sched_init(void)
{
// initialize `mscratch` to 0
write_mscratch(0);
// enable machine mode software interrupts
write_mie(read_mie() | MIE_MSIE);
}
/*
Sign up a user task.
Return -1 means fail.
*/
int task_create(void *routine_entry)
{
// return 0 - success
// return -1 - fail
if (_num_of_tasks < MAX_TASKS)
{
tasks[_num_of_tasks].sp = (regis)&task_stacks[_num_of_tasks][STACK_SIZE - 1];
tasks[_num_of_tasks].pc = (regis)routine_entry;
_num_of_tasks++;
return 0;
}
return -1;
}
/*
User task hand out control to OS actively.
AKA cooperative multitasking.
*/
void task_yield(void)
{
uint32 id = read_mhartid();
// write clint.msip to 1
write_clint_msip_one(id);
return;
}
/*
Scheduler to decide what task to run next.
Go through all tasks iteratively and serves FIFO.
*/
void task_scheduler(void)
{
if (_num_of_tasks <= 0)
{
panic("No task is running yet!");
return;
}
_current_task = (_current_task + 1) % _num_of_tasks;
Context *next = &(tasks[_current_task]);
switch_to(next);
}