xv6, line by line
lab 4
Lab 44 CPU time accounting and a time command

Lab 4 · reveal · 16 steps · 7 commits

CPU time accounting and a time command: the reference solution

You teach the kernel to keep, for every process, how much time it spent running in user mode and how much in the kernel, and you add a time command:

$ time cputest spin 1000
real 1.955
user 1.950
sys  0.003

Measuring time sounds simple until you ask the questions this lab is built on. Which clock do you use when every hart takes its own timer interrupt but only one of them counts ticks? Exactly where does a process stop being “in user mode”: at the ecall, or at the first line of C? What happens to its clock while it sleeps, while it waits for a hart, and on the hart it lands on afterwards? Whose time is an interrupt that arrives on behalf of some other process? Who may read a dying process’s numbers, and under which lock? You answer each one, then measure the answers on three harts: the clock you chose against the one you rejected.

Each step shows one change on the branch ext/04-cputime, the code around it, and the state of the machine when that code runs.

The route
  1. 1Five counters in the private part of struct proc kernel/proc.h
  2. 2freeproc gives the next process a clean slate kernel/proc.c
  3. 3The first C after a trap ends the user stretch kernel/trap.c
  4. 4The last C before the return ends the kernel stretch kernel/trap.c
  5. 5Between the C code and the mode switch kernel/trampoline.S
  6. 6sched stops the clock before the switch kernel/proc.c
  7. 7Running again, perhaps on another hart kernel/proc.c
  8. 8A timer interrupt from user mode kernel/trap.c
  9. 9A new process starts its clock in forkret kernel/proc.c
  10. 10The zombie's last charge kernel/proc.c
  11. 11wait passes the child's time to the parent kernel/proc.c
  12. 12One struct crosses the boundary kernel/cputime.h
  13. 13The clock's rate, from the machine kernel/param.h
  14. 14Reading the running clock with interrupts off kernel/sysproc.c
  15. 15time reads the totals before and after user/time.c
  16. 16The test measures what a program can see user/cputest.c

Keys: ← → step · Home start