I am writing a simple scheduler in which we iterate the process array and find all runnable processes and store it another array for lookup. I have a srand function call that will generate a number between 0 and the runnable processes. Using that index acquire that process from the runnable process array, run it then repeat. However I keep getting a panic kernel trap error if anyone can help.
void
scheduler(void)
{
struct proc *p;
struct cpu *c = mycpu();
struct proc *arr[NPROC];
c->proc = 0;
for(;;){
// Avoid deadlock by ensuring that devices can interrupt.
intr_on();
int i=0;
int runnableProc=0;
for(p = proc; p < &proc[NPROC]; p++) {
acquire(&p->lock);
if(p->state == RUNNABLE) {
// Switch to chosen process. It is the process's job
// to release its lock and then reacquire it
// before jumping back to us.
arr[i]=p;
runnableProc++;
i++;
}
release(&p->lock);
}
int randomNum=sys_srand()%runnableProc;
acquire(&arr[randomNum]->lock);
arr[randomNum]->state=RUNNING;
c->proc = arr[randomNum];
swtch(&c->context, &arr[randomNum]->context);
// Process is done running for now.
// It should have changed its p->state before coming back.
c->proc = 0;
release(&arr[randomNum]->lock);
}
}
I guess that
sys_srandis the problem, but I can’t find it in xv6 repos.Given its name,
sys_srandseems to be a system call, declared as taking no parameter (xxx sys_srand(void)) but I believe that it’s a syscall implementation ofsrandwhich takes an integer as parameter.So the problems are:
sys_xxxfrom the kernel instead of directly callingxxxfunction. (or what is called insys_srand())srandandrandfunctions.srandis to initialize the random generator seed (it should be called once per process) andrandwhich return a pseudo random number.In sort:
srandonce as your scheduler startsrandto pick a process to run.