/*1* Copyright (c) 2000, 2001, 2002, 2003, 2004, 2005, 2008, 20092* The President and Fellows of Harvard College.3*4* Redistribution and use in source and binary forms, with or without5* modification, are permitted provided that the following conditions6* are met:7* 1. Redistributions of source code must retain the above copyright8* notice, this list of conditions and the following disclaimer.9* 2. Redistributions in binary form must reproduce the above copyright10* notice, this list of conditions and the following disclaimer in the11* documentation and/or other materials provided with the distribution.12* 3. Neither the name of the University nor the names of its contributors13* may be used to endorse or promote products derived from this software14* without specific prior written permission.15*16* THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY AND CONTRIBUTORS ``AS IS'' AND17* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE18* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE19* ARE DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY OR CONTRIBUTORS BE LIABLE20* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL21* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS22* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)23* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT24* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY25* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF26* SUCH DAMAGE.27*/2829/*30* Core kernel-level thread system.31*/3233#include <types.h>34#include <kern/errno.h>35#include <lib.h>36#include <array.h>37#include <cpu.h>38#include <spl.h>39#include <spinlock.h>40#include <wchan.h>41#include <thread.h>42#include <threadlist.h>43#include <threadprivate.h>44#include <current.h>45#include <synch.h>46#include <addrspace.h>47#include <mainbus.h>48#include <vnode.h>4950#include "opt-synchprobs.h"51#include "opt-defaultscheduler.h"525354/* Magic number used as a guard value on kernel thread stacks. */55#define THREAD_STACK_MAGIC 0xbaadf00d5657/* Wait channel. */58struct wchan {59const char *wc_name; /* name for this channel */60struct threadlist wc_threads; /* list of waiting threads */61struct spinlock wc_lock; /* lock for mutual exclusion */62};6364/* Master array of CPUs. */65DECLARRAY(cpu);66DEFARRAY(cpu, /*no inline*/ );67static struct cpuarray allcpus;6869/* Used to wait for secondary CPUs to come online. */70static struct semaphore *cpu_startup_sem;7172////////////////////////////////////////////////////////////7374/*75* Stick a magic number on the bottom end of the stack. This will76* (sometimes) catch kernel stack overflows. Use thread_checkstack()77* to test this.78*/79static80void81thread_checkstack_init(struct thread *thread)82{83((uint32_t *)thread->t_stack)[0] = THREAD_STACK_MAGIC;84((uint32_t *)thread->t_stack)[1] = THREAD_STACK_MAGIC;85((uint32_t *)thread->t_stack)[2] = THREAD_STACK_MAGIC;86((uint32_t *)thread->t_stack)[3] = THREAD_STACK_MAGIC;87}8889/*90* Check the magic number we put on the bottom end of the stack in91* thread_checkstack_init. If these assertions go off, it most likely92* means you overflowed your stack at some point, which can cause all93* kinds of mysterious other things to happen.94*95* Note that when ->t_stack is NULL, which is the case if the stack96* cannot be freed (which in turn is the case if the stack is the boot97* stack, and the thread is the boot thread) this doesn't do anything.98*/99static100void101thread_checkstack(struct thread *thread)102{103if (thread->t_stack != NULL) {104KASSERT(((uint32_t*)thread->t_stack)[0] == THREAD_STACK_MAGIC);105KASSERT(((uint32_t*)thread->t_stack)[1] == THREAD_STACK_MAGIC);106KASSERT(((uint32_t*)thread->t_stack)[2] == THREAD_STACK_MAGIC);107KASSERT(((uint32_t*)thread->t_stack)[3] == THREAD_STACK_MAGIC);108}109}110111/*112* Create a thread. This is used both to create a first thread113* for each CPU and to create subsequent forked threads.114*/115static116struct thread *117thread_create(const char *name)118{119struct thread *thread;120121DEBUGASSERT(name != NULL);122123thread = kmalloc(sizeof(*thread));124if (thread == NULL) {125return NULL;126}127128thread->t_name = kstrdup(name);129if (thread->t_name == NULL) {130kfree(thread);131return NULL;132}133thread->t_wchan_name = "NEW";134thread->t_state = S_READY;135136/* Thread subsystem fields */137thread_machdep_init(&thread->t_machdep);138threadlistnode_init(&thread->t_listnode, thread);139thread->t_stack = NULL;140thread->t_context = NULL;141thread->t_cpu = NULL;142/* Interrupt state fields */143thread->t_in_interrupt = false;144thread->t_curspl = IPL_HIGH;145thread->t_iplhigh_count = 1; /* corresponding to t_curspl */146thread->t_vmp_count = 0;147thread->t_clone = 0;148149/* VM fields */150thread->t_addrspace = NULL;151152/* VFS fields */153thread->t_cwd = NULL;154155/* If you add to struct thread, be sure to initialize here */156157return thread;158}159160/*161* Create a CPU structure. This is used for the bootup CPU and162* also for secondary CPUs.163*164* The hardware number (the number assigned by firmware or system165* board config or whatnot) is tracked separately because it is not166* necessarily anything sane or meaningful.167*/168struct cpu *169cpu_create(unsigned hardware_number)170{171struct cpu *c;172int result;173char namebuf[16];174175c = kmalloc(sizeof(*c));176if (c == NULL) {177panic("cpu_create: Out of memory\n");178}179180c->c_self = c;181c->c_hardware_number = hardware_number;182183c->c_curthread = NULL;184threadlist_init(&c->c_zombies);185c->c_hardclocks = 0;186187c->c_isidle = false;188threadlist_init(&c->c_runqueue);189spinlock_init(&c->c_runqueue_lock);190191c->c_ipi_pending = 0;192c->c_numshootdown = 0;193spinlock_init(&c->c_ipi_lock);194195result = cpuarray_add(&allcpus, c, &c->c_number);196if (result != 0) {197panic("cpu_create: array_add: %s\n", strerror(result));198}199200snprintf(namebuf, sizeof(namebuf), "<boot #%d>", c->c_number);201c->c_curthread = thread_create(namebuf);202if (c->c_curthread == NULL) {203panic("cpu_create: thread_create failed\n");204}205206if (c->c_number == 0) {207/*208* Leave c->c_curthread->t_stack NULL for the boot209* cpu. This means we're using the boot stack, which210* can't be freed. (Exercise: what would it take to211* make it possible to free the boot stack?)212*/213/*c->c_curthread->t_stack = ... */214}215else {216c->c_curthread->t_stack = kmalloc(STACK_SIZE);217if (c->c_curthread->t_stack == NULL) {218panic("cpu_create: couldn't allocate stack");219}220thread_checkstack_init(c->c_curthread);221}222c->c_curthread->t_cpu = c;223224cpu_machdep_init(c);225226return c;227}228229/*230* Destroy a thread.231*232* This function cannot be called in the victim thread's own context.233* Nor can it be called on a running thread.234*235* (Freeing the stack you're actually using to run is ... inadvisable.)236*/237static238void239thread_destroy(struct thread *thread)240{241KASSERT(thread != curthread);242KASSERT(thread->t_state != S_RUN);243244/*245* If you add things to struct thread, be sure to clean them up246* either here or in thread_exit(). (And not both...)247*/248249/* VFS fields, cleaned up in thread_exit */250KASSERT(thread->t_cwd == NULL);251252/* VM fields, cleaned up in thread_exit */253KASSERT(thread->t_addrspace == NULL);254255/* Thread subsystem fields */256if (thread->t_stack != NULL) {257kfree(thread->t_stack);258}259threadlistnode_cleanup(&thread->t_listnode);260thread_machdep_cleanup(&thread->t_machdep);261262/* sheer paranoia */263thread->t_wchan_name = "DESTROYED";264265kfree(thread->t_name);266kfree(thread);267}268269/*270* Clean up zombies. (Zombies are threads that have exited but still271* need to have thread_destroy called on them.)272*273* The list of zombies is per-cpu.274*/275static276void277exorcise(void)278{279struct thread *z;280281while ((z = threadlist_remhead(&curcpu->c_zombies)) != NULL) {282KASSERT(z != curthread);283KASSERT(z->t_state == S_ZOMBIE);284thread_destroy(z);285}286}287288/*289* On panic, stop the thread system (as much as is reasonably290* possible) to make sure we don't end up letting any other threads291* run.292*/293void294thread_panic(void)295{296/*297* Kill off other CPUs.298*299* We could wait for them to stop, except that they might not.300*/301ipi_broadcast(IPI_PANIC);302303/*304* Drop runnable threads on the floor.305*306* Don't try to get the run queue lock; we might not be able307* to. Instead, blat the list structure by hand, and take the308* risk that it might not be quite atomic.309*/310curcpu->c_runqueue.tl_count = 0;311curcpu->c_runqueue.tl_head.tln_next = NULL;312curcpu->c_runqueue.tl_tail.tln_prev = NULL;313314/*315* Ideally, we want to make sure sleeping threads don't wake316* up and start running. However, there's no good way to track317* down all the wchans floating around the system. Another318* alternative would be to set a global flag to make the wchan319* wakeup operations do nothing; but that would mean we320* ourselves couldn't sleep to wait for an I/O completion321* interrupt, and we'd like to be able to do that if the322* system isn't that badly hosed.323*324* So, do nothing else here.325*326* This may prove inadequate in practice and further steps327* might be needed. It may also be necessary to go through and328* forcibly unlock all locks or the like...329*/330}331332/*333* At system shutdown, ask the other CPUs to switch off.334*/335void336thread_shutdown(void)337{338/*339* Stop the other CPUs.340*341* We should probably wait for them to stop and shut them off342* on the system board.343*/344ipi_broadcast(IPI_OFFLINE);345}346347/*348* Thread system initialization.349*/350void351thread_bootstrap(void)352{353struct cpu *bootcpu;354struct thread *bootthread;355356cpuarray_init(&allcpus);357358/*359* Create the cpu structure for the bootup CPU, the one we're360* currently running on. Assume the hardware number is 0; that361* might be updated later by mainbus-type code. This also362* creates a thread structure for the first thread, the one363* that's already implicitly running when the kernel is364* started from the bootloader.365*/366bootcpu = cpu_create(0);367bootthread = bootcpu->c_curthread;368369/*370* Initializing curcpu and curthread is machine-dependent371* because either of curcpu and curthread might be defined in372* terms of the other.373*/374INIT_CURCPU(bootcpu, bootthread);375376/*377* Now make sure both t_cpu and c_curthread are set. This378* might be partially redundant with INIT_CURCPU depending on379* how things are defined.380*/381curthread->t_cpu = curcpu;382curcpu->c_curthread = curthread;383384/* Done */385}386387/*388* New CPUs come here once MD initialization is finished. curthread389* and curcpu should already be initialized.390*391* Other than clearing thread_start_cpus() to continue, we don't need392* to do anything. The startup thread can just exit; we only need it393* to be able to get into thread_switch() properly.394*/395void396cpu_hatch(unsigned software_number)397{398KASSERT(curcpu != NULL);399KASSERT(curthread != NULL);400KASSERT(curcpu->c_number == software_number);401402spl0();403404kprintf("cpu%u: %s\n", software_number, cpu_identify());405406V(cpu_startup_sem);407thread_exit();408}409410/*411* Start up secondary cpus. Called from boot().412*/413void414thread_start_cpus(void)415{416unsigned i;417418kprintf("cpu0: %s\n", cpu_identify());419420cpu_startup_sem = sem_create("cpu_hatch", 0);421mainbus_start_cpus();422423for (i=0; i<cpuarray_num(&allcpus) - 1; i++) {424P(cpu_startup_sem);425}426sem_destroy(cpu_startup_sem);427cpu_startup_sem = NULL;428}429430/*431* Make a thread runnable.432*433* targetcpu might be curcpu; it might not be, too.434*/435static436void437thread_make_runnable(struct thread *target, bool already_have_lock)438{439struct cpu *targetcpu;440bool isidle;441442/* Lock the run queue of the target thread's cpu. */443targetcpu = target->t_cpu;444445if (already_have_lock) {446/* The target thread's cpu should be already locked. */447KASSERT(spinlock_do_i_hold(&targetcpu->c_runqueue_lock));448}449else {450spinlock_acquire(&targetcpu->c_runqueue_lock);451}452453isidle = targetcpu->c_isidle;454threadlist_addtail(&targetcpu->c_runqueue, target);455if (isidle) {456/*457* Other processor is idle; send interrupt to make458* sure it unidles.459*/460ipi_send(targetcpu, IPI_UNIDLE);461}462463if (!already_have_lock) {464spinlock_release(&targetcpu->c_runqueue_lock);465}466}467468/*469* Create a new thread based on an existing one.470*471* The new thread has name NAME, and starts executing in function472* ENTRYPOINT. DATA1 and DATA2 are passed to ENTRYPOINT.473*474* The new thread is given no address space (the caller decides that)475* but inherits its current working directory from the caller. It will476* start on the same CPU as the caller, unless the scheduler477* intervenes first.478*/479int480thread_fork(const char *name,481void (*entrypoint)(void *data1, unsigned long data2),482void *data1, unsigned long data2,483struct thread **ret)484{485struct thread *newthread;486487newthread = thread_create(name);488if (newthread == NULL) {489return ENOMEM;490}491492/* Allocate a stack */493newthread->t_stack = kmalloc(STACK_SIZE);494if (newthread->t_stack == NULL) {495thread_destroy(newthread);496return ENOMEM;497}498thread_checkstack_init(newthread);499500/*501* Now we clone various fields from the parent thread.502*/503504/* Thread subsystem fields */505newthread->t_cpu = curthread->t_cpu;506507/* VM fields */508/* do not clone address space -- let caller decide on that */509510/* VFS fields */511if (curthread->t_cwd != NULL) {512VOP_INCREF(curthread->t_cwd);513newthread->t_cwd = curthread->t_cwd;514}515516/*517* Because new threads come out holding the cpu runqueue lock518* (see notes at bottom of thread_switch), we need to account519* for the spllower() that will be done releasing it.520*/521newthread->t_iplhigh_count++;522523/* Set up the switchframe so entrypoint() gets called */524switchframe_init(newthread, entrypoint, data1, data2);525526/* Lock the current cpu's run queue and make the new thread runnable */527thread_make_runnable(newthread, false);528529/*530* Return new thread structure if it's wanted. Note that using531* the thread structure from the parent thread should be done532* only with caution, because in general the child thread533* might exit at any time.534*/535if (ret != NULL) {536*ret = newthread;537}538539return 0;540}541542/*543* High level, machine-independent context switch code.544*545* The current thread is queued appropriately and its state is changed546* to NEWSTATE; another thread to run is selected and switched to.547*548* If NEWSTATE is S_SLEEP, the thread is queued on the wait channel549* WC. Otherwise WC should be NULL.550*/551static552void553thread_switch(threadstate_t newstate, struct wchan *wc)554{555struct thread *cur, *next;556int spl;557558DEBUGASSERT(curcpu->c_curthread == curthread);559DEBUGASSERT(curthread->t_cpu == curcpu->c_self);560561/* Explicitly disable interrupts on this processor */562spl = splhigh();563564cur = curthread;565566/*567* If we're idle, return without doing anything. This happens568* when the timer interrupt interrupts the idle loop.569*/570if (curcpu->c_isidle) {571splx(spl);572return;573}574575/* Check the stack guard band. */576thread_checkstack(cur);577578/* Lock the run queue. */579spinlock_acquire(&curcpu->c_runqueue_lock);580581/* Micro-optimization: if nothing to do, just return */582if (newstate == S_READY && threadlist_isempty(&curcpu->c_runqueue)) {583spinlock_release(&curcpu->c_runqueue_lock);584splx(spl);585return;586}587588/* Put the thread in the right place. */589switch (newstate) {590case S_RUN:591panic("Illegal S_RUN in thread_switch\n");592case S_READY:593thread_make_runnable(cur, true /*have lock*/);594break;595case S_SLEEP:596cur->t_wchan_name = wc->wc_name;597/*598* Add the thread to the list in the wait channel, and599* unlock same. To avoid a race with someone else600* calling wchan_wake*, we must keep the wchan locked601* from the point the caller of wchan_sleep locked it602* until the thread is on the list.603*604* (We could for symmetry relock the channel before605* returning from wchan_sleep, but we don't, for two606* reasons. One is that the caller is unlikely to need607* or want it locked and if it does can lock it itself608* without racing. Exercise: what's the other?)609*/610threadlist_addtail(&wc->wc_threads, cur);611wchan_unlock(wc);612break;613case S_ZOMBIE:614cur->t_wchan_name = "ZOMBIE";615threadlist_addtail(&curcpu->c_zombies, cur);616break;617}618cur->t_state = newstate;619620/*621* Get the next thread. While there isn't one, call md_idle().622* curcpu->c_isidle must be true when md_idle is623* called. Unlock the runqueue while idling too, to make sure624* things can be added to it.625*626* Note that we don't need to unlock the runqueue atomically627* with idling; becoming unidle requires receiving an628* interrupt (either a hardware interrupt or an interprocessor629* interrupt from another cpu posting a wakeup) and idling630* *is* atomic with respect to re-enabling interrupts.631*632* Note that c_isidle becomes true briefly even if we don't go633* idle. However, because one is supposed to hold the runqueue634* lock to look at it, this should not be visible or matter.635*/636637/* The current cpu is now idle. */638curcpu->c_isidle = true;639do {640next = threadlist_remhead(&curcpu->c_runqueue);641if (next == NULL) {642spinlock_release(&curcpu->c_runqueue_lock);643cpu_idle();644spinlock_acquire(&curcpu->c_runqueue_lock);645}646} while (next == NULL);647curcpu->c_isidle = false;648649/*650* Note that curcpu->c_curthread may be the same variable as651* curthread and it may not be, depending on how curthread and652* curcpu are defined by the MD code. We'll assign both and653* assume the compiler will optimize one away if they're the654* same.655*/656curcpu->c_curthread = next;657curthread = next;658659/* do the switch (in assembler in switch.S) */660switchframe_switch(&cur->t_context, &next->t_context);661662/*663* When we get to this point we are either running in the next664* thread, or have come back to the same thread again,665* depending on how you look at it. That is,666* switchframe_switch returns immediately in another thread667* context, which in general will be executing here with a668* different stack and different values in the local669* variables. (Although new threads go to thread_startup670* instead.) But, later on when the processor, or some671* processor, comes back to the previous thread, it's also672* executing here with the *same* value in the local673* variables.674*675* The upshot, however, is as follows:676*677* - The thread now currently running is "cur", not "next",678* because when we return from switchrame_switch on the679* same stack, we're back to the thread that680* switchframe_switch call switched away from, which is681* "cur".682*683* - "cur" is _not_ the thread that just *called*684* switchframe_switch.685*686* - If newstate is S_ZOMB we never get back here in that687* context at all.688*689* - If the thread just chosen to run ("next") was a new690* thread, we don't get to this code again until691* *another* context switch happens, because when new692* threads return from switchframe_switch they teleport693* to thread_startup.694*695* - At this point the thread whose stack we're now on may696* have been migrated to another cpu since it last ran.697*698* The above is inherently confusing and will probably take a699* while to get used to.700*701* However, the important part is that code placed here, after702* the call to switchframe_switch, does not necessarily run on703* every context switch. Thus any such code must be either704* skippable on some switches or also called from705* thread_startup.706*/707708709/* Clear the wait channel and set the thread state. */710cur->t_wchan_name = NULL;711cur->t_state = S_RUN;712713/* Unlock the run queue. */714spinlock_release(&curcpu->c_runqueue_lock);715716/* If we have an address space, activate it in the MMU. */717if (cur->t_addrspace != NULL) {718as_activate(cur->t_addrspace);719}720721/* Clean up dead threads. */722exorcise();723724/* Turn interrupts back on. */725splx(spl);726}727728/*729* This function is where new threads start running. The arguments730* ENTRYPOINT, DATA1, and DATA2 are passed through from thread_fork.731*732* Because new code comes here from inside the middle of733* thread_switch, the beginning part of this function must match the734* tail of thread_switch.735*/736void737thread_startup(void (*entrypoint)(void *data1, unsigned long data2),738void *data1, unsigned long data2)739{740struct thread *cur;741742cur = curthread;743744/* Clear the wait channel and set the thread state. */745cur->t_wchan_name = NULL;746cur->t_state = S_RUN;747748/* Release the runqueue lock acquired in thread_switch. */749spinlock_release(&curcpu->c_runqueue_lock);750751/* If we have an address space, activate it in the MMU. */752if (cur->t_addrspace != NULL) {753as_activate(cur->t_addrspace);754}755756/* Clean up dead threads. */757exorcise();758759/* Enable interrupts. */760spl0();761762#if OPT_SYNCHPROBS763/* Yield a random number of times to get a good mix of threads. */764{765int i, n;766n = random()%161 + random()%161;767for (i=0; i<n; i++) {768thread_yield();769}770}771#endif772773/* Call the function. */774entrypoint(data1, data2);775776/* Done. */777thread_exit();778}779780/*781* Cause the current thread to exit.782*783* The parts of the thread structure we don't actually need to run784* should be cleaned up right away. The rest has to wait until785* thread_destroy is called from exorcise().786*787* Does not return.788*/789void790thread_exit(void)791{792struct thread *cur;793794cur = curthread;795796/* VFS fields */797if (cur->t_cwd) {798VOP_DECREF(cur->t_cwd);799cur->t_cwd = NULL;800}801802/* VM fields */803if (cur->t_addrspace) {804/*805* Clear t_addrspace before calling as_destroy. Otherwise806* if as_destroy sleeps (which is quite possible) when we807* come back we'll call as_activate on a half-destroyed808* address space, which is usually messily fatal.809*/810struct addrspace *as = cur->t_addrspace;811cur->t_addrspace = NULL;812as_activate(NULL);813as_destroy(as);814}815816/* Check the stack guard band. */817thread_checkstack(cur);818819/* Interrupts off on this processor */820splhigh();821thread_switch(S_ZOMBIE, NULL);822panic("The zombie walks!\n");823}824825/*826* Yield the cpu to another process, but stay runnable.827*/828void829thread_yield(void)830{831thread_switch(S_READY, NULL);832}833834////////////////////////////////////////////////////////////835836/*837* Scheduler.838*839* This is called periodically from hardclock(). It should reshuffle840* the current CPU's run queue by job priority.841*/842843#if OPT_DEFAULTSCHEDULER844void845schedule(void)846{847// 28 Feb 2012 : GWA : Leave the default scheduler alone!848}849#else850void851schedule(void)852{853854}855856#endif857858/*859* Thread migration.860*861* This is also called periodically from hardclock(). If the current862* CPU is busy and other CPUs are idle, or less busy, it should move863* threads across to those other other CPUs.864*865* Migrating threads isn't free because of cache affinity; a thread's866* working cache set will end up having to be moved to the other CPU,867* which is fairly slow. The tradeoff between this performance loss868* and the performance loss due to underutilization of some CPUs is869* something that needs to be tuned and probably is workload-specific.870*871* For here and now, because we know we're running on System/161 and872* System/161 does not (yet) model such cache effects, we'll be very873* aggressive.874*/875void876thread_consider_migration(void)877{878unsigned my_count, total_count, one_share, to_send;879unsigned i, numcpus;880struct cpu *c;881struct threadlist victims;882struct thread *t;883884my_count = total_count = 0;885numcpus = cpuarray_num(&allcpus);886for (i=0; i<numcpus; i++) {887c = cpuarray_get(&allcpus, i);888spinlock_acquire(&c->c_runqueue_lock);889total_count += c->c_runqueue.tl_count;890if (c == curcpu->c_self) {891my_count = c->c_runqueue.tl_count;892}893spinlock_release(&c->c_runqueue_lock);894}895896one_share = DIVROUNDUP(total_count, numcpus);897if (my_count < one_share) {898return;899}900901to_send = my_count - one_share;902threadlist_init(&victims);903spinlock_acquire(&curcpu->c_runqueue_lock);904for (i=0; i<to_send; i++) {905t = threadlist_remtail(&curcpu->c_runqueue);906threadlist_addhead(&victims, t);907}908spinlock_release(&curcpu->c_runqueue_lock);909910for (i=0; i < numcpus && to_send > 0; i++) {911c = cpuarray_get(&allcpus, i);912if (c == curcpu->c_self) {913continue;914}915spinlock_acquire(&c->c_runqueue_lock);916while (c->c_runqueue.tl_count < one_share && to_send > 0) {917t = threadlist_remhead(&victims);918/*919* Ordinarily, curthread will not appear on920* the run queue. However, it can under the921* following circumstances:922* - it went to sleep;923* - the processor became idle, so it924* remained curthread;925* - it was reawakened, so it was put on the926* run queue;927* - and the processor hasn't fully unidled928* yet, so all these things are still true.929*930* If the timer interrupt happens at (almost)931* exactly the proper moment, we can come here932* while things are in this state and see933* curthread. However, *migrating* curthread934* can cause bad things to happen (Exercise:935* Why? And what?) so shuffle it to the end of936* the list and decrement to_send in order to937* skip it. Then it goes back on our own run938* queue below.939*/940if (t == curthread) {941threadlist_addtail(&victims, t);942to_send--;943continue;944}945946t->t_cpu = c;947threadlist_addtail(&c->c_runqueue, t);948DEBUG(DB_THREADS,949"Migrated thread %s: cpu %u -> %u",950t->t_name, curcpu->c_number, c->c_number);951to_send--;952if (c->c_isidle) {953/*954* Other processor is idle; send955* interrupt to make sure it unidles.956*/957ipi_send(c, IPI_UNIDLE);958}959}960spinlock_release(&c->c_runqueue_lock);961}962963/*964* Because the code above isn't atomic, the thread counts may have965* changed while we were working and we may end up with leftovers.966* Don't panic; just put them back on our own run queue.967*/968if (!threadlist_isempty(&victims)) {969spinlock_acquire(&curcpu->c_runqueue_lock);970while ((t = threadlist_remhead(&victims)) != NULL) {971threadlist_addtail(&curcpu->c_runqueue, t);972}973spinlock_release(&curcpu->c_runqueue_lock);974}975976KASSERT(threadlist_isempty(&victims));977threadlist_cleanup(&victims);978}979980////////////////////////////////////////////////////////////981982/*983* Wait channel functions984*/985986/*987* Create a wait channel. NAME is a symbolic string name for it.988* This is what's displayed by ps -alx in Unix.989*990* NAME should generally be a string constant. If it isn't, alternate991* arrangements should be made to free it after the wait channel is992* destroyed.993*/994struct wchan *995wchan_create(const char *name)996{997struct wchan *wc;998999wc = kmalloc(sizeof(*wc));1000if (wc == NULL) {1001return NULL;1002}1003spinlock_init(&wc->wc_lock);1004threadlist_init(&wc->wc_threads);1005wc->wc_name = name;1006return wc;1007}10081009/*1010* Destroy a wait channel. Must be empty and unlocked.1011* (The corresponding cleanup functions require this.)1012*/1013void1014wchan_destroy(struct wchan *wc)1015{1016spinlock_cleanup(&wc->wc_lock);1017threadlist_cleanup(&wc->wc_threads);1018kfree(wc);1019}10201021/*1022* Lock and unlock a wait channel, respectively.1023*/1024void1025wchan_lock(struct wchan *wc)1026{1027spinlock_acquire(&wc->wc_lock);1028}10291030void1031wchan_unlock(struct wchan *wc)1032{1033spinlock_release(&wc->wc_lock);1034}10351036/*1037* Yield the cpu to another process, and go to sleep, on the specified1038* wait channel WC. Calling wakeup on the channel will make the thread1039* runnable again. The channel must be locked, and will be *unlocked*1040* upon return.1041*/1042void1043wchan_sleep(struct wchan *wc)1044{1045/* may not sleep in an interrupt handler */1046KASSERT(!curthread->t_in_interrupt);10471048thread_switch(S_SLEEP, wc);1049}10501051/*1052* Wake up one thread sleeping on a wait channel.1053*/1054void1055wchan_wakeone(struct wchan *wc)1056{1057struct thread *target;10581059/* Lock the channel and grab a thread from it */1060spinlock_acquire(&wc->wc_lock);1061target = threadlist_remhead(&wc->wc_threads);1062/*1063* Nobody else can wake up this thread now, so we don't need1064* to hang onto the lock.1065*/1066spinlock_release(&wc->wc_lock);10671068if (target == NULL) {1069/* Nobody was sleeping. */1070return;1071}10721073thread_make_runnable(target, false);1074}10751076/*1077* Wake up all threads sleeping on a wait channel.1078*/1079void1080wchan_wakeall(struct wchan *wc)1081{1082struct thread *target;1083struct threadlist list;10841085threadlist_init(&list);10861087/*1088* Lock the channel and grab all the threads, moving them to a1089* private list.1090*/1091spinlock_acquire(&wc->wc_lock);1092while ((target = threadlist_remhead(&wc->wc_threads)) != NULL) {1093threadlist_addtail(&list, target);1094}1095/*1096* Nobody else can wake up these threads now, so we don't need1097* to hang onto the lock.1098*/1099spinlock_release(&wc->wc_lock);11001101/*1102* We could conceivably sort by cpu first to cause fewer lock1103* ops and fewer IPIs, but for now at least don't bother. Just1104* make each thread runnable.1105*/1106while ((target = threadlist_remhead(&list)) != NULL) {1107thread_make_runnable(target, false);1108}11091110threadlist_cleanup(&list);1111}11121113/*1114* Return nonzero if there are no threads sleeping on the channel.1115* This is meant to be used only for diagnostic purposes.1116*/1117bool1118wchan_isempty(struct wchan *wc)1119{1120bool ret;11211122spinlock_acquire(&wc->wc_lock);1123ret = threadlist_isempty(&wc->wc_threads);1124spinlock_release(&wc->wc_lock);11251126return ret;1127}11281129////////////////////////////////////////////////////////////11301131/*1132* Machine-independent IPI handling1133*/11341135/*1136* Send an IPI (inter-processor interrupt) to the specified CPU.1137*/1138void1139ipi_send(struct cpu *target, int code)1140{1141KASSERT(code >= 0 && code < 32);11421143spinlock_acquire(&target->c_ipi_lock);1144target->c_ipi_pending |= (uint32_t)1 << code;1145mainbus_send_ipi(target);1146spinlock_release(&target->c_ipi_lock);1147}11481149void1150ipi_broadcast(int code)1151{1152unsigned i;1153struct cpu *c;11541155for (i=0; i < cpuarray_num(&allcpus); i++) {1156c = cpuarray_get(&allcpus, i);1157if (c != curcpu->c_self) {1158ipi_send(c, code);1159}1160}1161}11621163void1164ipi_tlbshootdown_by_num( unsigned cpunum, const struct tlbshootdown *mapping ) {1165struct cpu *target;11661167target = cpuarray_get( &allcpus, cpunum );1168ipi_tlbshootdown( target, mapping );1169}11701171void1172ipi_tlbshootdown(struct cpu *target, const struct tlbshootdown *mapping)1173{1174int n;11751176spinlock_acquire(&target->c_ipi_lock);11771178n = target->c_numshootdown;1179if (n == TLBSHOOTDOWN_MAX) {1180target->c_numshootdown = TLBSHOOTDOWN_ALL;1181}1182else {1183target->c_shootdown[n] = *mapping;1184target->c_numshootdown = n+1;1185}11861187target->c_ipi_pending |= (uint32_t)1 << IPI_TLBSHOOTDOWN;1188mainbus_send_ipi(target);11891190spinlock_release(&target->c_ipi_lock);1191}11921193void1194interprocessor_interrupt(void)1195{1196uint32_t bits;1197int i;11981199spinlock_acquire(&curcpu->c_ipi_lock);1200bits = curcpu->c_ipi_pending;12011202if (bits & (1U << IPI_PANIC)) {1203/* panic on another cpu - just stop dead */1204cpu_halt();1205}1206if (bits & (1U << IPI_OFFLINE)) {1207/* offline request */1208spinlock_acquire(&curcpu->c_runqueue_lock);1209if (!curcpu->c_isidle) {1210kprintf("cpu%d: offline: warning: not idle\n",1211curcpu->c_number);1212}1213spinlock_release(&curcpu->c_runqueue_lock);1214kprintf("cpu%d: offline.\n", curcpu->c_number);1215cpu_halt();1216}1217if (bits & (1U << IPI_UNIDLE)) {1218/*1219* The cpu has already unidled itself to take the1220* interrupt; don't need to do anything else.1221*/1222}1223if (bits & (1U << IPI_TLBSHOOTDOWN)) {1224if (curcpu->c_numshootdown == TLBSHOOTDOWN_ALL) {1225vm_tlbshootdown_all();1226}1227else {1228for (i=0; i<curcpu->c_numshootdown; i++) {1229vm_tlbshootdown(&curcpu->c_shootdown[i]);1230}1231}1232curcpu->c_numshootdown = 0;1233}12341235curcpu->c_ipi_pending = 0;1236spinlock_release(&curcpu->c_ipi_lock);1237}123812391240