33#include "loader.h"
44#include "trap.h"
55#include "vm.h"
6+ #include "queue.h"
67
78struct proc pool [NPROC ];
89__attribute__((aligned (16 ))) char kstack [NPROC ][PAGE_SIZE ];
@@ -11,6 +12,7 @@ __attribute__((aligned(4096))) char trapframe[NPROC][TRAP_PAGE_SIZE];
1112extern char boot_stack_top [];
1213struct proc * current_proc ;
1314struct proc idle ;
15+ struct queue task_queue ;
1416
1517int threadid ()
1618{
@@ -39,6 +41,7 @@ void proc_init()
3941 idle .kstack = (uint64 )boot_stack_top ;
4042 idle .pid = IDLE_PID ;
4143 current_proc = & idle ;
44+ init_queue (& task_queue );
4245}
4346
4447int allocpid ()
@@ -47,6 +50,24 @@ int allocpid()
4750 return PID ++ ;
4851}
4952
53+ struct proc * fetch_task ()
54+ {
55+ int index = pop_queue (& task_queue );
56+ if (index < 0 ) {
57+ debugf ("No task to fetch\n" );
58+ return NULL ;
59+ }
60+ debugf ("fetch task %d(pid=%d) from task queue\n" , index ,
61+ pool [index ].pid );
62+ return pool + index ;
63+ }
64+
65+ void add_task (struct proc * p )
66+ {
67+ push_queue (& task_queue , p - pool );
68+ debugf ("add task %d(pid=%d) to task queue\n" , p - pool , p -> pid );
69+ }
70+
5071// Look in the process table for an UNUSED proc.
5172// If found, initialize state required to run in the kernel.
5273// If there are no free procs, or a memory allocation fails, return 0.
@@ -98,19 +119,27 @@ void scheduler()
98119{
99120 struct proc * p ;
100121 for (;;) {
101- int has_proc = 0 ;
122+ /* int has_proc = 0;
102123 for (p = pool; p < &pool[NPROC]; p++) {
103124 if (p->state == RUNNABLE) {
104125 has_proc = 1;
105- debugf ("swtich to proc %d" , p - pool );
126+ tracef ("swtich to proc %d", p - pool);
106127 p->state = RUNNING;
107128 current_proc = p;
108129 swtch(&idle.context, &p->context);
109130 }
110131 }
111132 if(has_proc == 0) {
112133 panic("all app are over!\n");
134+ }*/
135+ p = fetch_task ();
136+ if (p == NULL ) {
137+ panic ("all app are over!\n" );
113138 }
139+ tracef ("swtich to proc %d" , p - pool );
140+ p -> state = RUNNING ;
141+ current_proc = p ;
142+ swtch (& idle .context , & p -> context );
114143 }
115144}
116145
@@ -133,6 +162,7 @@ void sched()
133162void yield ()
134163{
135164 current_proc -> state = RUNNABLE ;
165+ add_task (current_proc );
136166 sched ();
137167}
138168
@@ -186,6 +216,7 @@ int fork()
186216 np -> trapframe -> a0 = 0 ;
187217 np -> parent = p ;
188218 np -> state = RUNNABLE ;
219+ add_task (np );
189220 return np -> pid ;
190221}
191222
@@ -266,6 +297,7 @@ int wait(int pid, int *code)
266297 return -1 ;
267298 }
268299 p -> state = RUNNABLE ;
300+ add_task (p );
269301 sched ();
270302 }
271303}
0 commit comments