1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
| int taskcreate(void (*fn)(void*), void *arg, uint stack){ int id; Task *t;
t = taskalloc(fn, arg, stack); taskcount++; id = t->id; if(nalltask%64 == 0){ alltask = realloc(alltask, (nalltask+64)*sizeof(alltask[0])); if(alltask == nil){ fprint(2, "out of memory\n"); abort(); } } t->alltaskslot = nalltask; alltask[nalltask++] = t; taskready(t); return id; }
static Task* taskalloc(void (*fn)(void*), void *arg, uint stack){ Task *t; sigset_t zero; uint x, y; ulong z;
t = malloc(sizeof *t+stack); if(t == nil){ fprint(2, "taskalloc malloc: %r\n"); abort(); } memset(t, 0, sizeof *t); t->stk = (uchar*)(t+1); t->stksize = stack; t->id = ++taskidgen; t->startfn = fn; t->startarg = arg;
memset(&t->context.uc, 0, sizeof t->context.uc); sigemptyset(&zero); sigprocmask(SIG_BLOCK, &zero, &t->context.uc.uc_sigmask);
if(getcontext(&t->context.uc) < 0){ fprint(2, "getcontext: %r\n"); abort(); }
t->context.uc.uc_stack.ss_sp = t->stk+8; t->context.uc.uc_stack.ss_size = t->stksize-64; #if defined(__sun__) && !defined(__MAKECONTEXT_V2_SOURCE) #warning "doing sun thing" t->context.uc.uc_stack.ss_sp = (char*)t->context.uc.uc_stack.ss_sp +t->context.uc.uc_stack.ss_size; #endif
z = (ulong)t; y = z; z >>= 16; x = z>>16; makecontext(&t->context.uc, (void(*)())taskstart, 2, y, x);
return t; }
#ifdef NEEDAMD64MAKECONTEXT void makecontext(ucontext_t *ucp, void (*func)(void), int argc, ...) { long *sp; va_list va;
memset(&ucp->uc_mcontext, 0, sizeof ucp->uc_mcontext); if(argc != 2) *(int*)0 = 0; va_start(va, argc); ucp->uc_mcontext.mc_rdi = va_arg(va, int); ucp->uc_mcontext.mc_rsi = va_arg(va, int); va_end(va); sp = (long*)ucp->uc_stack.ss_sp+ucp->uc_stack.ss_size/sizeof(long); sp -= argc; sp = (void*)((uintptr_t)sp - (uintptr_t)sp%16); *--sp = 0; ucp->uc_mcontext.mc_rip = (long)func; ucp->uc_mcontext.mc_rsp = (long)sp; } #endif
static void taskstart(uint y, uint x) { Task *t; ulong z; z = x<<16; z <<= 16; z |= y; t = (Task*)z;
t->startfn(t->startarg);
taskexit(0);
}
|