Skip to content

Instantly share code, notes, and snippets.

@cwfoo
Created October 19, 2021 13:13
Show Gist options
  • Save cwfoo/08ffe65faf3700b7d3633c82173dcedf to your computer and use it in GitHub Desktop.
Save cwfoo/08ffe65faf3700b7d3633c82173dcedf to your computer and use it in GitHub Desktop.
Prevent 100% CPU utilization by QEMU when running xv6 OS.
Patch for the xv6 operating system (version: xv6-rev11).
Prevents 100% CPU utilization by QEMU.
diff --git a/proc.c b/proc.c
index 806b1b1..bd35f7b 100644
--- a/proc.c
+++ b/proc.c
@@ -322,6 +322,7 @@ wait(void)
void
scheduler(void)
{
+ int ran;
struct proc *p;
struct cpu *c = mycpu();
c->proc = 0;
@@ -330,12 +331,16 @@ scheduler(void)
// Enable interrupts on this processor.
sti();
+ ran = 0;
+
// Loop over process table looking for process to run.
acquire(&ptable.lock);
for(p = ptable.proc; p < &ptable.proc[NPROC]; p++){
if(p->state != RUNNABLE)
continue;
+ ran = 1;
+
// Switch to chosen process. It is the process's job
// to release ptable.lock and then reacquire it
// before jumping back to us.
@@ -352,6 +357,9 @@ scheduler(void)
}
release(&ptable.lock);
+ if(ran == 0)
+ hlt();
+
}
}
diff --git a/x86.h b/x86.h
index 07312a5..578888f 100644
--- a/x86.h
+++ b/x86.h
@@ -144,6 +144,12 @@ lcr3(uint val)
asm volatile("movl %0,%%cr3" : : "r" (val));
}
+static inline void
+hlt()
+{
+ asm volatile("hlt" : : );
+}
+
//PAGEBREAK: 36
// Layout of the trap frame built on the stack by the
// hardware and by trapasm.S, and passed to trap().
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment