xv6能夠運行多cpu的計算機上,這個os使用mycpu函數來標識初當前的cpu,使用struct cpu結構體來記錄當前的CPU狀態。使用cpus這些狀態存放於cpus數組中,使用ncpu來標誌cpu的個數。api
1 // Per-CPU state 2 struct cpu { 3 uchar apicid; // Local APIC ID 每一個cpu都有一個惟一硬件ID,這個ID能夠lapicid()函數進行獲取,而後存放於這個字段中。 4 struct context *scheduler; // swtch() here to enter scheduler 5 struct taskstate ts; // Used by x86 to find stack for interrupt 6 struct segdesc gdt[NSEGS]; // x86 global descriptor table 7 volatile uint started; // Has the CPU started? 8 int ncli; // Depth of pushcli nesting. 9 int intena; // Were interrupts enabled before pushcli? 10 struct proc *proc; // The process running on this cpu or null 11 }; 12 13 extern struct cpu cpus[NCPU]; //當前系統中存在的CPU 14 extern int ncpu;
如下函數主要功能是獲取 運行當前代碼的cpu對應的ID,而後經過這個ID在cpus數組中進行匹配,獲得當前CPU信息(這個cpu信息是已經事先經過程序獲取的)數組
35 // Must be called with interrupts disabled to avoid the caller being 36 // rescheduled between reading lapicid and running through the loop. 37 struct cpu* 38 mycpu(void) 39 { 40 int apicid, i; 41 42 if(readeflags()&FL_IF) 43 panic("mycpu called with interrupts enabled\n"); 44 45 apicid = lapicid(); 46 // APIC IDs are not guaranteed to be contiguous. Maybe we should have 47 // a reverse map, or reserve a register to store &cpus[i]. 48 for (i = 0; i < ncpu; ++i) { 49 if (cpus[i].apicid == apicid) 50 return &cpus[i]; 51 } 52 panic("unknown apicid\n"); 53 }