vmm: Halt vcore 0 instead of spinning
[akaros.git] / user / vmm / sched.c
1 /* Copyright (c) 2016 Google Inc.
2  * Barret Rhoden <brho@cs.berkeley.edu>
3  * See LICENSE for details.
4  *
5  * 2LS for virtual machines */
6
7 #include <vmm/sched.h>
8 #include <vmm/vmm.h>
9 #include <vmm/vthread.h>
10 #include <sys/mman.h>
11 #include <stdlib.h>
12 #include <assert.h>
13 #include <parlib/spinlock.h>
14 #include <parlib/event.h>
15 #include <parlib/ucq.h>
16 #include <parlib/arch/trap.h>
17 #include <parlib/ros_debug.h>
18 #include <parlib/vcore_tick.h>
19 #include <parlib/slab.h>
20
21 int vmm_sched_period_usec = 1000;
22
23 /* For now, we only have one VM managed by the 2LS.  If we ever expand that,
24  * we'll need something analogous to current_uthread, so the 2LS knows which VM
25  * it is working on. */
26 static struct virtual_machine *current_vm;
27
28 static struct spin_pdr_lock queue_lock = SPINPDR_INITIALIZER;
29 /* Runnable queues, broken up by thread type. */
30 static struct vmm_thread_tq rnbl_tasks = TAILQ_HEAD_INITIALIZER(rnbl_tasks);
31 static struct vmm_thread_tq rnbl_guests = TAILQ_HEAD_INITIALIZER(rnbl_guests);
32 static struct vmm_thread **greedy_rnbl_guests;
33 /* Counts of *unblocked* threads.  Unblocked = Running + Runnable. */
34 static atomic_t nr_unblk_tasks;
35 static atomic_t nr_unblk_guests;
36 /* Global evq for all syscalls.  Could make this per vcore or whatever. */
37 static struct event_queue *sysc_evq;
38 static struct kmem_cache *task_thread_cache;
39
40 static void vmm_sched_init(void);
41 static void vmm_sched_entry(void);
42 static void vmm_thread_runnable(struct uthread *uth);
43 static void vmm_thread_paused(struct uthread *uth);
44 static void vmm_thread_blockon_sysc(struct uthread *uth, void *sysc);
45 static void vmm_thread_has_blocked(struct uthread *uth, int flags);
46 static void vmm_thread_refl_fault(struct uthread *uth,
47                                   struct user_context *ctx);
48 static void vmm_thread_exited(struct uthread *uth);
49 static struct uthread *vmm_thread_create(void *(*func)(void *), void *arg);
50
51 struct schedule_ops vmm_sched_ops = {
52         .sched_init = vmm_sched_init,
53         .sched_entry = vmm_sched_entry,
54         .thread_runnable = vmm_thread_runnable,
55         .thread_paused = vmm_thread_paused,
56         .thread_blockon_sysc = vmm_thread_blockon_sysc,
57         .thread_has_blocked = vmm_thread_has_blocked,
58         .thread_refl_fault = vmm_thread_refl_fault,
59         .thread_exited = vmm_thread_exited,
60         .thread_create = vmm_thread_create,
61 };
62
63 struct schedule_ops *sched_ops = &vmm_sched_ops;
64
65 /* Helpers */
66 static void vmm_handle_syscall(struct event_msg *ev_msg, unsigned int ev_type,
67                                void *data);
68 static void acct_thread_blocked(struct vmm_thread *vth);
69 static void acct_thread_unblocked(struct vmm_thread *vth);
70 static void enqueue_vmm_thread(struct vmm_thread *vth);
71 static int task_thread_ctor(void *obj, void *priv, int flags);
72 static void task_thread_dtor(void *obj, void *priv);
73 static struct vmm_thread *alloc_vmm_thread(struct virtual_machine *vm,
74                                            int type);
75 static void *__alloc_stack(size_t stacksize);
76 static void __free_stack(void *stacktop, size_t stacksize);
77
78 static bool sched_is_greedy(void)
79 {
80         return parlib_never_yield;
81 }
82
83 static unsigned int sched_nr_greedy_cores(void)
84 {
85         if (!current_vm)
86                 return 1;
87         return current_vm->nr_gpcs + 1;
88 }
89
90 static void restart_thread(struct syscall *sysc)
91 {
92         struct uthread *ut_restartee = (struct uthread*)sysc->u_data;
93
94         /* uthread stuff here: */
95         assert(ut_restartee);
96         assert(ut_restartee->sysc == sysc);     /* set in uthread.c */
97         ut_restartee->sysc = 0; /* so we don't 'reblock' on this later */
98         vmm_thread_runnable(ut_restartee);
99 }
100
101 static void vmm_handle_syscall(struct event_msg *ev_msg, unsigned int ev_type,
102                                void *data)
103 {
104         struct syscall *sysc;
105
106         /* I think we can make this assert now.  If not, check pthread.c. (concern
107          * was having old ev_qs firing and running this handler). */
108         assert(ev_msg);
109         sysc = ev_msg->ev_arg3;
110         assert(sysc);
111         restart_thread(sysc);
112 }
113
114 /* Helper: allocates a UCQ-based event queue suitable for syscalls.  Will
115  * attempt to route the notifs/IPIs to vcoreid */
116 static struct event_queue *setup_sysc_evq(int vcoreid)
117 {
118         struct event_queue *evq;
119         uintptr_t mmap_block;
120
121         mmap_block = (uintptr_t)mmap(0, PGSIZE * 2,
122                                      PROT_WRITE | PROT_READ,
123                                      MAP_POPULATE | MAP_ANONYMOUS | MAP_PRIVATE,
124                                      -1, 0);
125         evq = get_eventq_raw();
126         assert(mmap_block && evq);
127         evq->ev_flags = EVENT_IPI | EVENT_INDIR | EVENT_SPAM_INDIR | EVENT_WAKEUP;
128         evq->ev_vcore = vcoreid;
129         evq->ev_mbox->type = EV_MBOX_UCQ;
130         ucq_init_raw(&evq->ev_mbox->ucq, mmap_block, mmap_block + PGSIZE);
131         return evq;
132 }
133
134 static void vmm_sched_init(void)
135 {
136         struct task_thread *thread0;
137
138         /* Note that thread0 doesn't belong to a VM.  We can set this during
139          * vmm_init() if we need to. */
140         thread0 = (struct task_thread*)alloc_vmm_thread(0, VMM_THREAD_TASK);
141         assert(thread0);
142         acct_thread_unblocked((struct vmm_thread*)thread0);
143         thread0->stacksize = USTACK_NUM_PAGES * PGSIZE;
144         thread0->stacktop = (void*)USTACKTOP;
145         /* for lack of a better vcore, might as well send to 0 */
146         sysc_evq = setup_sysc_evq(0);
147         uthread_2ls_init((struct uthread*)thread0, vmm_handle_syscall, NULL);
148         task_thread_cache = kmem_cache_create("task threads",
149                                               sizeof(struct vmm_thread),
150                                               __alignof__(struct vmm_thread), 0,
151                                               task_thread_ctor, task_thread_dtor,
152                                               NULL);
153 }
154
155 /* The scheduling policy is encapsulated in the next few functions (from here
156  * down to sched_entry()). */
157
158 static int desired_nr_vcores(void)
159 {
160         /* Sanity checks on our accounting. */
161         assert(atomic_read(&nr_unblk_guests) >= 0);
162         assert(atomic_read(&nr_unblk_tasks) >= 0);
163         /* Lockless peak.  This is always an estimate.  Some of our tasks busy-wait,
164          * so it's not enough to just give us one vcore for all tasks, yet. */
165         return atomic_read(&nr_unblk_guests) + atomic_read(&nr_unblk_tasks);
166 }
167
168 static struct vmm_thread *__pop_first(struct vmm_thread_tq *tq)
169 {
170         struct vmm_thread *vth;
171
172         vth = TAILQ_FIRST(tq);
173         if (vth)
174                 TAILQ_REMOVE(tq, vth, tq_next);
175         return vth;
176 }
177
178 static struct vmm_thread *pick_a_thread_degraded(void)
179 {
180         struct vmm_thread *vth;
181
182         spin_pdr_lock(&queue_lock);
183         vth = __pop_first(&rnbl_tasks);
184         if (!vth)
185                 vth = __pop_first(&rnbl_guests);
186         spin_pdr_unlock(&queue_lock);
187         return vth;
188 }
189
190 /* We have plenty of cores - run whatever we want.  We'll prioritize tasks. */
191 static struct vmm_thread *pick_a_thread_plenty(void)
192 {
193         struct vmm_thread *vth = 0;
194
195         spin_pdr_lock(&queue_lock);
196         if (!vth)
197                 vth = __pop_first(&rnbl_tasks);
198         if (!vth)
199                 vth = __pop_first(&rnbl_guests);
200         spin_pdr_unlock(&queue_lock);
201         return vth;
202 }
203
204 static void yield_current_uth(void)
205 {
206         struct vmm_thread *vth;
207
208         if (!current_uthread)
209                 return;
210         vth = (struct vmm_thread*)stop_current_uthread();
211         enqueue_vmm_thread(vth);
212 }
213
214 /* Helper, tries to get the right number of vcores.  Returns TRUE if we think we
215  * have enough, FALSE otherwise.
216  *
217  * TODO: this doesn't handle a lot of issues, like preemption, how to
218  * run/yield our vcores, dynamic changes in the number of runnables, where
219  * to send events, how to avoid interfering with gpcs, etc. */
220 static bool try_to_get_vcores(void)
221 {
222         int nr_vcores_wanted;
223         bool have_enough;
224
225         if (sched_is_greedy())
226                 return num_vcores() == sched_nr_greedy_cores();
227         nr_vcores_wanted = desired_nr_vcores();
228         have_enough = nr_vcores_wanted <= num_vcores();
229         if (have_enough) {
230                 vcore_tick_disable();
231                 return TRUE;
232         }
233         vcore_tick_enable(vmm_sched_period_usec);
234         vcore_request_total(nr_vcores_wanted);
235         return FALSE;
236 }
237
238 static void stats_run_vth(struct vmm_thread *vth)
239 {
240         vth->nr_runs++;
241         if (vth->prev_vcoreid != vcore_id()) {
242                 vth->prev_vcoreid = vcore_id();
243                 vth->nr_resched++;
244         }
245 }
246
247 /* TODO: This assumes we get all of our vcores. */
248 static struct vmm_thread *sched_pick_thread_greedy(void)
249 {
250         struct vmm_thread *vth;
251
252         if (current_uthread) {
253                 stats_run_vth((struct vmm_thread*)current_uthread);
254                 run_current_uthread();
255         }
256         if (vcore_id() == 0) {
257                 spin_pdr_lock(&queue_lock);
258                 vth = __pop_first(&rnbl_tasks);
259                 spin_pdr_unlock(&queue_lock);
260                 return vth;
261         }
262         /* This races with enqueue_vmm_thread, which can run on another core.
263          * Here are the rules:
264          * - set when runnable (race free, only one state for the thread at a time)
265          * - cleared when we run it (race free, we're the only runners)
266          * - if we take an interrupt, we'll just run_current_uthread and not check
267          * - if we vmexit, we'll run the buddy directly */
268         assert(vcore_id() <= current_vm->nr_gpcs);
269         vth = greedy_rnbl_guests[vcore_id() - 1];
270         if (vth)
271                 greedy_rnbl_guests[vcore_id() - 1] = NULL;
272         return vth;
273 }
274
275 static struct vmm_thread *sched_pick_thread_nice(void)
276 {
277         struct vmm_thread *vth;
278         bool have_enough;
279
280         have_enough = try_to_get_vcores();
281         if (!have_enough && vcore_tick_poll()) {
282                 /* slightly less than ideal: we grab the queue lock twice */
283                 yield_current_uth();
284         }
285         if (current_uthread) {
286                 stats_run_vth((struct vmm_thread*)current_uthread);
287                 run_current_uthread();
288         }
289         if (have_enough)
290                 vth = pick_a_thread_plenty();
291         else
292                 vth = pick_a_thread_degraded();
293         return vth;
294 }
295
296 static void __attribute__((noreturn)) vmm_sched_entry(void)
297 {
298         struct vmm_thread *vth;
299
300         if (sched_is_greedy()) {
301                 vth = sched_pick_thread_greedy();
302                 if (!vth) {
303                         /* sys_halt_core will return, but we need to restart the vcore.  We
304                          * might have woke due to an event, and we'll need to handle_events
305                          * and other things dealt with by uthreads. */
306                         if (vcore_id() == 0)
307                                 sys_halt_core(0);
308                         /* In greedy mode, yield will abort and we'll just restart */
309                         vcore_yield_or_restart();
310                 }
311         } else {
312                 vth = sched_pick_thread_nice();
313                 if (!vth)
314                         vcore_yield_or_restart();
315         }
316         stats_run_vth(vth);
317         run_uthread((struct uthread*)vth);
318 }
319
320 static void vmm_thread_runnable(struct uthread *uth)
321 {
322         /* A thread that was blocked is now runnable.  This counts as becoming
323          * unblocked (running + runnable) */
324         acct_thread_unblocked((struct vmm_thread*)uth);
325         enqueue_vmm_thread((struct vmm_thread*)uth);
326 }
327
328 static void vmm_thread_paused(struct uthread *uth)
329 {
330         /* The thread stopped for some reason, usually a preemption.  We'd like to
331          * just run it whenever we get a chance.  Note that it didn't become
332          * 'blocked' - it's still runnable. */
333         enqueue_vmm_thread((struct vmm_thread*)uth);
334 }
335
336 static void vmm_thread_blockon_sysc(struct uthread *uth, void *syscall)
337 {
338         struct syscall *sysc = (struct syscall*)syscall;
339
340         acct_thread_blocked((struct vmm_thread*)uth);
341         sysc->u_data = uth;
342         if (!register_evq(sysc, sysc_evq)) {
343                 /* Lost the race with the call being done.  The kernel won't send the
344                  * event.  Just restart him. */
345                 restart_thread(sysc);
346         }
347         /* GIANT WARNING: do not touch the thread after this point. */
348 }
349
350 static void vmm_thread_has_blocked(struct uthread *uth, int flags)
351 {
352         /* The thread blocked on something like a mutex.  It's not runnable, so we
353          * don't need to put it on a list, but we do need to account for it not
354          * running.  We'll find out (via thread_runnable) when it starts up again.
355          */
356         acct_thread_blocked((struct vmm_thread*)uth);
357 }
358
359 static void refl_error(struct uthread *uth, unsigned int trap_nr,
360                        unsigned int err, unsigned long aux)
361 {
362         printf("Thread has unhandled fault: %d, err: %d, aux: %p\n",
363                trap_nr, err, aux);
364         /* Note that uthread.c already copied out our ctx into the uth
365          * struct */
366         print_user_context(&uth->u_ctx);
367         printf("Turn on printx to spew unhandled, malignant trap info\n");
368         exit(-1);
369 }
370
371 static bool handle_page_fault(struct uthread *uth, unsigned int err,
372                               unsigned long aux)
373 {
374         if (!(err & PF_VMR_BACKED))
375                 return FALSE;
376         syscall_async(&uth->local_sysc, SYS_populate_va, aux, 1);
377         __block_uthread_on_async_sysc(uth);
378         return TRUE;
379 }
380
381 static void vmm_thread_refl_hw_fault(struct uthread *uth,
382                                      unsigned int trap_nr,
383                                      unsigned int err, unsigned long aux)
384 {
385         switch (trap_nr) {
386         case HW_TRAP_PAGE_FAULT:
387                 if (!handle_page_fault(uth, err, aux))
388                         refl_error(uth, trap_nr, err, aux);
389                 break;
390         default:
391                 refl_error(uth, trap_nr, err, aux);
392         }
393 }
394
395 /* Yield callback for __ctlr_entry */
396 static void __swap_to_gth(struct uthread *uth, void *dummy)
397 {
398         struct ctlr_thread *cth = (struct ctlr_thread*)uth;
399
400         /* We just immediately run our buddy.  The ctlr and the guest are accounted
401          * together ("pass the token" back and forth). */
402         current_uthread = NULL;
403         stats_run_vth((struct vmm_thread*)cth->buddy);
404         run_uthread((struct uthread*)cth->buddy);
405         assert(0);
406 }
407
408 /* All ctrl threads start here, each time their guest has a fault.  They can
409  * block and unblock along the way.  Once a ctlr does its final uthread_yield,
410  * the next time it will start again from the top. */
411 static void __ctlr_entry(void)
412 {
413         struct ctlr_thread *cth = (struct ctlr_thread*)current_uthread;
414         struct virtual_machine *vm = gth_to_vm(cth->buddy);
415
416         if (!handle_vmexit(cth->buddy)) {
417                 struct vm_trapframe *vm_tf = gth_to_vmtf(cth->buddy);
418
419                 fprintf(stderr, "vmm: handle_vmexit returned false\n");
420                 fprintf(stderr, "Note: this may be a kernel module, not the kernel\n");
421                 fprintf(stderr, "RSP was %p, ", (void *)vm_tf->tf_rsp);
422                 fprintf(stderr, "RIP was %p:\n", (void *)vm_tf->tf_rip);
423                 /* TODO: properly walk the kernel page tables to map the tf_rip
424                  * to a physical address. For now, however, this hack is good
425                  * enough.
426                  */
427                 hexdump(stderr, (void *)(vm_tf->tf_rip & 0x3fffffff), 16);
428                 showstatus(stderr, cth->buddy);
429                 exit(0);
430         }
431         /* We want to atomically yield and start/reenqueue our buddy.  We do so in
432          * vcore context on the other side of the yield. */
433         uthread_yield(FALSE, __swap_to_gth, 0);
434 }
435
436 static void vmm_thread_refl_vm_fault(struct uthread *uth)
437 {
438         struct guest_thread *gth = (struct guest_thread*)uth;
439         struct ctlr_thread *cth = gth->buddy;
440
441         gth->nr_vmexits++;
442         /* The ctlr starts frm the top every time we get a new fault. */
443         cth->uthread.flags |= UTHREAD_SAVED;
444         init_user_ctx(&cth->uthread.u_ctx, (uintptr_t)&__ctlr_entry,
445                       (uintptr_t)(cth->stacktop));
446         /* We just immediately run our buddy.  The ctlr and the guest are accounted
447          * together ("pass the token" back and forth). */
448         current_uthread = NULL;
449         stats_run_vth((struct vmm_thread*)cth);
450         run_uthread((struct uthread*)cth);
451         assert(0);
452 }
453
454 static void vmm_thread_refl_fault(struct uthread *uth,
455                                   struct user_context *ctx)
456 {
457         switch (ctx->type) {
458         case ROS_HW_CTX:
459                 /* Guests should only ever VM exit */
460                 assert(((struct vmm_thread*)uth)->type != VMM_THREAD_GUEST);
461                 vmm_thread_refl_hw_fault(uth, __arch_refl_get_nr(ctx),
462                                          __arch_refl_get_err(ctx),
463                                          __arch_refl_get_aux(ctx));
464                 break;
465         case ROS_VM_CTX:
466                 vmm_thread_refl_vm_fault(uth);
467                 break;
468         default:
469                 assert(0);
470         }
471 }
472
473 static void task_thread_dtor(void *obj, void *priv)
474 {
475         struct task_thread *tth = (struct task_thread*)obj;
476
477         uthread_cleanup((struct uthread*)tth);
478         __free_stack(tth->stacktop, tth->stacksize);
479 }
480
481 static void task_thread_exit(struct task_thread *tth)
482 {
483         struct uthread *uth = (struct uthread*)tth;
484
485         if (uth->flags & UTHREAD_IS_THREAD0)
486                 return;
487         kmem_cache_free(task_thread_cache, tth);
488 }
489
490 static void ctlr_thread_exit(struct ctlr_thread *cth)
491 {
492         __vthread_exited((struct vthread*)cth->buddy);
493 }
494
495 static void vmm_thread_exited(struct uthread *uth)
496 {
497         struct vmm_thread *vth = (struct vmm_thread*)uth;
498
499         assert(vth->type != VMM_THREAD_GUEST);
500
501         acct_thread_blocked(vth);
502         switch (vth->type) {
503         case VMM_THREAD_TASK:
504                 task_thread_exit((struct task_thread*)uth);
505                 break;
506         case VMM_THREAD_CTLR:
507                 ctlr_thread_exit((struct ctlr_thread*)uth);
508                 break;
509         case VMM_THREAD_GUEST:
510                 panic("Guest threads shouldn't be able to exit");
511         }
512 }
513
514 static void destroy_guest_thread(struct guest_thread *gth)
515 {
516         struct ctlr_thread *cth = gth->buddy;
517
518         __free_stack(cth->stacktop, cth->stacksize);
519         uthread_cleanup((struct uthread*)cth);
520         free(cth);
521         uthread_cleanup((struct uthread*)gth);
522         free(gth);
523 }
524
525 struct guest_thread *create_guest_thread(struct virtual_machine *vm,
526                                          unsigned int gpcoreid,
527                                          struct vmm_gpcore_init *gpci)
528 {
529         struct guest_thread *gth;
530         struct ctlr_thread *cth;
531         /* Guests won't use TLS; they always operate in Ring V.  The controller
532          * might - not because of anything we do, but because of glibc calls. */
533         struct uth_thread_attr gth_attr = {.want_tls = FALSE};
534         struct uth_thread_attr cth_attr = {.want_tls = TRUE};
535
536         gth = (struct guest_thread*)alloc_vmm_thread(vm, VMM_THREAD_GUEST);
537         cth = (struct ctlr_thread*)alloc_vmm_thread(vm, VMM_THREAD_CTLR);
538         if (!gth || !cth) {
539                 free(gth);
540                 free(cth);
541                 return 0;
542         }
543         gth->buddy = cth;
544         cth->buddy = gth;
545         gth->gpc_id = gpcoreid;
546         gth->gpci = *gpci;
547         cth->stacksize = VMM_THR_STACKSIZE;
548         cth->stacktop = __alloc_stack(cth->stacksize);
549         if (!cth->stacktop) {
550                 free(gth);
551                 free(cth);
552                 return 0;
553         }
554         gth->uthread.u_ctx.type = ROS_VM_CTX;
555         gth->uthread.u_ctx.tf.vm_tf.tf_guest_pcoreid = gpcoreid;
556         uthread_init((struct uthread*)gth, &gth_attr);
557         uthread_init((struct uthread*)cth, &cth_attr);
558         gth->halt_mtx = uth_mutex_alloc();
559         gth->halt_cv = uth_cond_var_alloc();
560         return gth;
561 }
562
563 static void ev_handle_diag(struct event_msg *ev_msg, unsigned int ev_type,
564                            void *data)
565 {
566         struct virtual_machine *vm = current_vm;
567         struct guest_thread *gth;
568         struct ctlr_thread *cth;
569         bool reset = FALSE;
570
571         if (ev_msg && (ev_msg->ev_arg1 == 1))
572                 reset = TRUE;
573
574         fprintf(stderr, "\nSCHED stats:\n---------------\n");
575         for (int i = 0; i < vm->nr_gpcs; i++) {
576                 gth = gpcid_to_gth(vm, i);
577                 cth = gth->buddy;
578                 fprintf(stderr, "\tGPC %2d: %lu resched, %lu gth runs, %lu ctl runs, %lu user-handled vmexits\n",
579                                 i,
580                         ((struct vmm_thread*)gth)->nr_resched,
581                         ((struct vmm_thread*)gth)->nr_runs,
582                         ((struct vmm_thread*)cth)->nr_runs,
583                         gth->nr_vmexits);
584                 if (reset) {
585                     ((struct vmm_thread*)gth)->nr_resched = 0;
586                     ((struct vmm_thread*)gth)->nr_runs = 0;
587                     ((struct vmm_thread*)cth)->nr_runs = 0;
588                     gth->nr_vmexits = 0;
589                 }
590         }
591         fprintf(stderr, "\n\tNr unblocked gpc %lu, Nr unblocked tasks %lu\n",
592                 atomic_read(&nr_unblk_guests), atomic_read(&nr_unblk_tasks));
593 }
594
595 int vmm_init(struct virtual_machine *vm, struct vmm_gpcore_init *gpcis,
596              int flags)
597 {
598         struct guest_thread **gths;
599
600         if (current_vm)
601                 return -1;
602         current_vm = vm;
603         /* We should tell the kernel to create all of the GPCs we'll need in
604          * advance.
605          *
606          * We could create the others on the fly, but the kernel's answer for
607          * CPUID[0x1] will not have to total number of cores.  If we move that
608          * handler to userspace, we can create the SMP-booted GPCs on the fly.
609          *
610          * We'd also have to deal with gths[] growing dynamically, which would
611          * require synchronization. */
612         if (syscall(SYS_vmm_add_gpcs, vm->nr_gpcs, gpcis) != vm->nr_gpcs)
613                 return -1;
614         if (flags) {
615                 if (syscall(SYS_vmm_ctl, VMM_CTL_SET_FLAGS, flags))
616                         return -1;
617         }
618         gths = malloc(vm->nr_gpcs * sizeof(struct guest_thread *));
619         if (!gths)
620                 return -1;
621         for (int i = 0; i < vm->nr_gpcs; i++) {
622                 gths[i] = create_guest_thread(vm, i, &gpcis[i]);
623                 if (!gths[i]) {
624                         for (int j = 0; j < i; j++)
625                                 destroy_guest_thread(gths[j]);
626                         free(gths);
627                         return -1;
628                 }
629         }
630         wmb(); /* All gths posted before advertising. */
631         vm->__gths = gths;
632         uthread_mcp_init();
633         register_ev_handler(EV_FREE_APPLE_PIE, ev_handle_diag, NULL);
634         if (sched_is_greedy()) {
635                 greedy_rnbl_guests = calloc(vm->nr_gpcs, sizeof(struct vmm_thread *));
636                 assert(greedy_rnbl_guests);
637                 vcore_request_total(sched_nr_greedy_cores());
638                 syscall(SYS_vmm_ctl, VMM_CTL_SET_EXITS,
639                         syscall(SYS_vmm_ctl, VMM_CTL_GET_EXITS) &
640                                 ~(VMM_CTL_EXIT_HALT | VMM_CTL_EXIT_MWAIT));
641         }
642         return 0;
643 }
644
645 void start_guest_thread(struct guest_thread *gth)
646 {
647         acct_thread_unblocked((struct vmm_thread*)gth);
648         enqueue_vmm_thread((struct vmm_thread*)gth);
649 }
650
651 static void __task_thread_run(void)
652 {
653         struct task_thread *tth = (struct task_thread*)current_uthread;
654
655         uth_2ls_thread_exit(tth->func(tth->arg));
656 }
657
658 static int task_thread_ctor(void *obj, void *priv, int flags)
659 {
660         struct vmm_thread *vth = (struct vmm_thread*)obj;
661         struct task_thread *tth = (struct task_thread*)obj;
662
663         memset(vth, 0, sizeof(struct vmm_thread));
664         vth->type = VMM_THREAD_TASK;
665         vth->vm = current_vm;
666         tth->stacksize = VMM_THR_STACKSIZE;
667         tth->stacktop = __alloc_stack(tth->stacksize);
668         if (!tth->stacktop)
669                 return -1;
670         return 0;
671 }
672
673 /* Helper, creates and starts a task thread. */
674 static struct task_thread *__vmm_run_task(struct virtual_machine *vm,
675                                           void *(*func)(void *), void *arg,
676                                           struct uth_thread_attr *tth_attr)
677 {
678         struct task_thread *tth;
679
680         tth = kmem_cache_alloc(task_thread_cache, 0);
681         tth->func = func;
682         tth->arg = arg;
683         init_user_ctx(&tth->uthread.u_ctx, (uintptr_t)&__task_thread_run,
684                       (uintptr_t)(tth->stacktop));
685         uthread_init((struct uthread*)tth, tth_attr);
686         acct_thread_unblocked((struct vmm_thread*)tth);
687         enqueue_vmm_thread((struct vmm_thread*)tth);
688         return tth;
689 }
690
691 struct task_thread *vmm_run_task(struct virtual_machine *vm,
692                                  void *(*func)(void *), void *arg)
693 {
694         struct uth_thread_attr tth_attr = {.want_tls = TRUE, .detached = TRUE};
695
696         return __vmm_run_task(vm, func, arg, &tth_attr);
697 }
698
699 static struct uthread *vmm_thread_create(void *(*func)(void *), void *arg)
700 {
701         struct uth_thread_attr tth_attr = {.want_tls = TRUE, .detached = FALSE};
702         struct task_thread *tth;
703
704         /* It's OK to not have a VM for a generic thread */
705         tth = __vmm_run_task(NULL, func, arg, &tth_attr);
706         /* But just in case, let's poison it */
707         ((struct vmm_thread*)tth)->vm = (void*)0xdeadbeef;
708         return (struct uthread*)tth;
709 }
710
711 /* Helpers for tracking nr_unblk_* threads. */
712 static void acct_thread_blocked(struct vmm_thread *vth)
713 {
714         switch (vth->type) {
715         case VMM_THREAD_GUEST:
716         case VMM_THREAD_CTLR:
717                 atomic_dec(&nr_unblk_guests);
718                 break;
719         case VMM_THREAD_TASK:
720                 atomic_dec(&nr_unblk_tasks);
721                 break;
722         }
723 }
724
725 static void acct_thread_unblocked(struct vmm_thread *vth)
726 {
727         switch (vth->type) {
728         case VMM_THREAD_GUEST:
729         case VMM_THREAD_CTLR:
730                 atomic_inc(&nr_unblk_guests);
731                 break;
732         case VMM_THREAD_TASK:
733                 atomic_inc(&nr_unblk_tasks);
734                 break;
735         }
736 }
737
738 static void greedy_mark_guest_runnable(struct vmm_thread *vth)
739 {
740         int gpcid;
741
742         if (vth->type == VMM_THREAD_GUEST)
743                 gpcid = ((struct guest_thread*)vth)->gpc_id;
744         else
745                 gpcid = ((struct ctlr_thread*)vth)->buddy->gpc_id;
746         /* racing with the reader */
747         greedy_rnbl_guests[gpcid] = vth;
748 }
749
750 static void enqueue_vmm_thread(struct vmm_thread *vth)
751 {
752         switch (vth->type) {
753         case VMM_THREAD_GUEST:
754         case VMM_THREAD_CTLR:
755                 if (sched_is_greedy()) {
756                         greedy_mark_guest_runnable(vth);
757                 } else {
758                         spin_pdr_lock(&queue_lock);
759                         TAILQ_INSERT_TAIL(&rnbl_guests, vth, tq_next);
760                         spin_pdr_unlock(&queue_lock);
761                 }
762                 break;
763         case VMM_THREAD_TASK:
764                 spin_pdr_lock(&queue_lock);
765                 TAILQ_INSERT_TAIL(&rnbl_tasks, vth, tq_next);
766                 spin_pdr_unlock(&queue_lock);
767                 if (sched_is_greedy())
768                         vcore_wake(0, false);
769                 break;
770         default:
771                 panic("Bad vmm_thread type %p\n", vth->type);
772         }
773         try_to_get_vcores();
774 }
775
776 static struct vmm_thread *alloc_vmm_thread(struct virtual_machine *vm, int type)
777 {
778         struct vmm_thread *vth;
779         int ret;
780
781         ret = posix_memalign((void**)&vth, __alignof__(struct vmm_thread),
782                              sizeof(struct vmm_thread));
783         if (ret)
784                 return 0;
785         memset(vth, 0, sizeof(struct vmm_thread));
786         vth->type = type;
787         vth->vm = vm;
788         return vth;
789 }
790
791 static void __free_stack(void *stacktop, size_t stacksize)
792 {
793         munmap(stacktop - stacksize, stacksize);
794 }
795
796 static void *__alloc_stack(size_t stacksize)
797 {
798         int force_a_page_fault;
799         void *stacktop;
800         void *stackbot = mmap(0, stacksize, PROT_READ | PROT_WRITE | PROT_EXEC,
801                               MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
802
803         if (stackbot == MAP_FAILED)
804                 return 0;
805         stacktop = stackbot + stacksize;
806         /* Want the top of the stack populated, but not the rest of the stack;
807          * that'll grow on demand (up to stacksize, then will clobber memory). */
808         force_a_page_fault = ACCESS_ONCE(*(int*)(stacktop - sizeof(int)));
809         return stacktop;
810 }