3 #include "../port/lib.h"
7 #include "../port/error.h"
12 int shargs(char*, int, char**);
14 extern void checkpages(void);
15 extern void checkpagerefs(void);
37 /* Check flags before we commit */
38 if((flag & (RFFDG|RFCFDG)) == (RFFDG|RFCFDG))
40 if((flag & (RFNAMEG|RFCNAMEG)) == (RFNAMEG|RFCNAMEG))
42 if((flag & (RFENVG|RFCENVG)) == (RFENVG|RFCENVG))
45 if((flag&RFPROC) == 0) {
46 if(flag & (RFMEM|RFNOWAIT))
48 if(flag & (RFFDG|RFCFDG)) {
51 up->fgrp = dupfgrp(ofg);
53 up->fgrp = dupfgrp(nil);
56 if(flag & (RFNAMEG|RFCNAMEG)) {
60 pgrpcpy(up->pgrp, opg);
61 /* inherit noattach */
62 up->pgrp->noattach = opg->noattach;
66 up->pgrp->noattach = 1;
72 if(flag & (RFENVG|RFCENVG)) {
74 up->egrp = smalloc(sizeof(Egrp));
77 envcpy(up->egrp, oeg);
81 up->noteid = pidalloc(0);
87 p->fpsave = up->fpsave;
88 p->scallnr = up->scallnr;
95 memmove(p->note, up->note, sizeof(p->note));
96 p->privatemem = up->privatemem;
97 p->noswap = up->noswap;
100 p->lastnote = up->lastnote;
101 p->notify = up->notify;
105 /* Make a new set of memory segments */
109 qunlock(&p->seglock);
112 for(i = 0; i < NSEG; i++)
114 p->seg[i] = dupseg(up->seg, i, n);
115 qunlock(&p->seglock);
118 /* File descriptors */
119 if(flag & (RFFDG|RFCFDG)) {
121 p->fgrp = dupfgrp(up->fgrp);
123 p->fgrp = dupfgrp(nil);
131 if(flag & (RFNAMEG|RFCNAMEG)) {
134 pgrpcpy(p->pgrp, up->pgrp);
135 /* inherit noattach */
136 p->pgrp->noattach = up->pgrp->noattach;
143 p->pgrp->noattach = 1;
152 /* Environment group */
153 if(flag & (RFENVG|RFCENVG)) {
154 p->egrp = smalloc(sizeof(Egrp));
157 envcpy(p->egrp, up->egrp);
164 p->procmode = up->procmode;
165 if(up->procctl == Proc_tracesyscall)
166 p->procctl = Proc_tracesyscall;
168 /* Craft a return frame which will cause the child to pop out of
169 * the scheduler in user mode with the return register zero
171 forkchild(p, up->dbgreg);
174 if((flag&RFNOWAIT) == 0){
175 p->parentpid = up->pid;
180 if((flag&RFNOTEG) == 0)
181 p->noteid = up->noteid;
183 p->fpstate = up->fpstate;
185 memset(p->time, 0, sizeof(p->time));
186 p->time[TReal] = MACHP(0)->ticks;
188 kstrdup(&p->text, up->text);
189 kstrdup(&p->user, up->user);
194 * since the bss/data segments are now shareable,
195 * any mmu info about this process is now stale
196 * (i.e. has bad properties) and has to be discarded.
199 p->basepri = up->basepri;
200 p->priority = up->basepri;
201 p->fixedpri = up->fixedpri;
205 procwired(p, wm->machno);
217 return (cp[0]<<24) | (cp[1]<<16) | (cp[2]<<8) | cp[3];
228 char *a, *charp, *args, *file, *file0;
229 char *progarg[sizeof(Exec)/2+1], *elem, progelem[64];
230 ulong ssize, spage, nargs, nbytes, n, bssend;
233 char line[sizeof(Exec)];
236 ulong magic, text, entry, data, bss;
242 validaddr(arg[0], 1, 0);
243 file0 = validnamedup((char*)arg[0], 1);
247 /* Disaster after commit */
249 pexit(up->errstr, 1);
254 tc = namec(file, Aopen, OEXEC, 0);
260 kstrdup(&elem, up->genbuf);
262 n = devtab[tc->type]->read(tc, &exec, sizeof(Exec), 0);
265 magic = l2be(exec.magic);
266 text = l2be(exec.text);
267 entry = l2be(exec.entry);
268 if(n==sizeof(Exec) && (magic == AOUT_MAGIC)){
269 if(text >= USTKTOP-UTZERO
270 || entry < UTZERO+sizeof(Exec)
271 || entry >= UTZERO+sizeof(Exec)+text)
273 break; /* for binary */
277 * Process #! /bin/sh args ...
279 memmove(line, &exec, sizeof(Exec));
280 if(indir || line[0]!='#' || line[1]!='!')
282 n = shargs(line, n, progarg);
287 * First arg becomes complete file name
291 validaddr(arg[1], BY2WD, 1);
294 if(strlen(elem) >= sizeof progelem)
296 strcpy(progelem, elem);
297 progarg[0] = progelem;
302 data = l2be(exec.data);
303 bss = l2be(exec.bss);
304 t = (UTZERO+sizeof(Exec)+text+(BY2PG-1)) & ~(BY2PG-1);
305 d = (t + data + (BY2PG-1)) & ~(BY2PG-1);
306 bssend = t + data + bss;
307 b = (bssend + (BY2PG-1)) & ~(BY2PG-1);
308 if(t >= KZERO || d >= KZERO || b >= KZERO)
312 * Args: pass 1: count
314 nbytes = sizeof(Tos); /* hole for profiling clock at top of stack (and more) */
320 nbytes += strlen(a) + 1;
325 argp = (char**)arg[1];
326 validaddr((ulong)argp, BY2WD, 0);
329 if(((ulong)argp&(BY2PG-1)) < BY2WD)
330 validaddr((ulong)argp, BY2WD, 0);
331 validaddr((ulong)a, 1, 0);
332 nbytes += ((char*)vmemchr(a, 0, 0x7FFFFFFF) - a) + 1;
335 ssize = BY2WD*(nargs+1) + ((nbytes+(BY2WD-1)) & ~(BY2WD-1));
338 * 8-byte align SP for those (e.g. sparc) that need it.
339 * execregs() will subtract another 4 bytes for argc.
343 spage = (ssize+(BY2PG-1)) >> PGSHIFT;
346 * Build the stack segment, putting it in kernel virtual for the moment
353 qunlock(&up->seglock);
356 up->seg[ESEG] = newseg(SG_STACK, TSTKTOP-USTKSIZE, USTKSIZE/BY2PG);
359 * Args: pass 2: assemble; the pages will be faulted in
361 tos = (Tos*)(TSTKTOP - sizeof(Tos));
362 tos->cyclefreq = m->cyclefreq;
367 argv = (char**)(TSTKTOP - ssize);
368 charp = (char*)(TSTKTOP - nbytes);
373 argp = (char**)arg[1];
375 for(i=0; i<nargs; i++){
376 if(indir && *argp==0) {
378 argp = (char**)arg[1];
380 *argv++ = charp + (USTKTOP-TSTKTOP);
381 n = strlen(*argp) + 1;
382 memmove(charp, *argp++, n);
386 file0 = nil; /* so waserror() won't free file0 */
391 elem = nil; /* so waserror() won't free elem */
394 /* copy args; easiest from new process's stack */
396 if(n > 128) /* don't waste too much space on huge arg lists */
401 up->args = smalloc(n);
402 memmove(up->args, args, n);
403 if(n>0 && up->args[n-1]!='\0'){
404 /* make sure last arg is NUL-terminated */
405 /* put NUL at UTF-8 character boundary */
407 if(fullrune(up->args+i, n-i))
420 * Special segments are maintained across exec
422 for(i = SSEG; i <= BSEG; i++) {
424 /* prevent a second free if we have an error */
427 for(i = BSEG+1; i < NSEG; i++) {
429 if(s != 0 && (s->type&SG_CEXEC)) {
439 for(i=0; i<=f->maxfd; i++)
442 /* Text. Shared. Attaches to cache image if possible */
443 /* attachimage returns a locked cache image */
444 img = attachimage(SG_TEXT|SG_RONLY, tc, UTZERO, (t-UTZERO)>>PGSHIFT);
449 ts->flen = sizeof(Exec)+text;
453 s = newseg(SG_DATA, t, (d-t)>>PGSHIFT);
456 /* Attached by hand */
459 s->fstart = ts->fstart+ts->flen;
462 /* BSS. Zero fill on demand */
463 up->seg[BSEG] = newseg(SG_BSS, d, (b-d)>>PGSHIFT);
470 s->base = USTKTOP-USTKSIZE;
472 relocateseg(s, USTKTOP-TSTKTOP);
474 qunlock(&up->seglock);
475 poperror(); /* seglock */
478 * '/' processes are higher priority (hack to make /ip more responsive).
480 if(devtab[tc->type]->dc == L'/')
481 up->basepri = PriRoot;
482 up->priority = up->basepri;
485 poperror(); /* elem */
496 * At this point, the mmu contains info about the old address
497 * space and needs to be flushed
502 up->procctl = Proc_stopme;
503 return execregs(entry, ssize, nargs);
507 shargs(char *s, int n, char **ap)
512 n -= 2; /* skip #! */
513 for(i=0; s[i]!='\n'; i++)
520 while(*s==' ' || *s=='\t')
527 while(*s && *s!=' ' && *s!='\t')
551 if (up->edf && (up->edf->flags & Admitted))
559 tsleep(&up->sleep, return0, 0, n);
566 return procalarm(arg[0]);
573 char *inval = "invalid exit string";
576 status = (char*)arg[0];
581 validaddr((ulong)status, 1, 0);
582 if(vmemchr(status, 0, ERRMAX) == 0){
583 memmove(buf, status, ERRMAX);
592 return 0; /* not reached */
605 validaddr(arg[0], sizeof(OWaitmsg), 1);
609 ow = (OWaitmsg*)arg[0];
610 readnum(0, ow->pid, NUMSIZE, w.pid, NUMSIZE);
611 readnum(0, ow->time+TUser*NUMSIZE, NUMSIZE, w.time[TUser], NUMSIZE);
612 readnum(0, ow->time+TSys*NUMSIZE, NUMSIZE, w.time[TSys], NUMSIZE);
613 readnum(0, ow->time+TReal*NUMSIZE, NUMSIZE, w.time[TReal], NUMSIZE);
614 strncpy(ow->msg, w.msg, sizeof(ow->msg)-1);
615 ow->msg[sizeof(ow->msg)-1] = '\0';
629 validaddr(arg[0], n, 1);
633 i = snprint((char*)arg[0], n, "%d %lud %lud %lud %q",
635 w.time[TUser], w.time[TSys], w.time[TReal],
642 werrstr(char *fmt, ...)
650 vseprint(up->syserrstr, up->syserrstr+ERRMAX, fmt, va);
655 generrstr(char *buf, uint nbuf)
661 validaddr((ulong)buf, nbuf, 1);
662 if(nbuf > sizeof tmp)
664 memmove(tmp, buf, nbuf);
666 /* make sure it's NUL-terminated */
668 memmove(buf, up->syserrstr, nbuf);
670 memmove(up->syserrstr, tmp, nbuf);
675 syserrstr(ulong *arg)
677 return generrstr((char*)arg[0], arg[1]);
680 /* compatibility for old binaries */
682 sys_errstr(ulong *arg)
684 return generrstr((char*)arg[0], 64);
688 sysnotify(ulong *arg)
691 validaddr(arg[0], sizeof(ulong), 0);
692 up->notify = (int(*)(void*, char*))(arg[0]);
699 if(arg[0]!=NRSTR && !up->notified)
705 syssegbrk(ulong *arg)
712 for(i = 0; i < NSEG; i++) {
714 if(s == 0 || addr < s->base || addr >= s->top)
716 switch(s->type&SG_TYPE) {
722 return ibrk(arg[1], i);
727 return 0; /* not reached */
731 syssegattach(ulong *arg)
733 return segattach(up, arg[0], (char*)arg[1], arg[2], arg[3]);
737 syssegdetach(ulong *arg)
745 qunlock(&up->seglock);
751 for(i = 0; i < NSEG; i++)
754 if((addr >= s->base && addr < s->top) ||
755 (s->top == s->base && addr == s->base))
764 * Check we are not detaching the initial stack segment.
766 if(s == up->seg[SSEG]){
773 qunlock(&up->seglock);
776 /* Ensure we flush any entries from the lost segment */
782 syssegfree(ulong *arg)
788 s = seg(up, from, 1);
791 to = (from + arg[1]) & ~(BY2PG-1);
792 from = PGROUND(from);
799 mfreeseg(s, from, (to - from) / BY2PG);
806 /* For binary compatibility */
810 return ibrk(arg[0], BSEG);
814 sysrendezvous(ulong *arg)
820 l = &REND(up->rgrp, tag);
823 for(p = *l; p; p = p->rendhash) {
824 if(p->rendtag == tag) {
837 /* Going to sleep here */
839 up->rendval = arg[1];
842 up->state = Rendezvous;
851 * The implementation of semaphores is complicated by needing
852 * to avoid rescheduling in syssemrelease, so that it is safe
853 * to call from real-time processes. This means syssemrelease
854 * cannot acquire any qlocks, only spin locks.
856 * Semacquire and semrelease must both manipulate the semaphore
857 * wait list. Lock-free linked lists only exist in theory, not
858 * in practice, so the wait list is protected by a spin lock.
860 * The semaphore value *addr is stored in user memory, so it
861 * cannot be read or written while holding spin locks.
863 * Thus, we can access the list only when holding the lock, and
864 * we can access the semaphore only when not holding the lock.
865 * This makes things interesting. Note that sleep's condition function
866 * is called while holding two locks - r and up->rlock - so it cannot
867 * access the semaphore value either.
869 * An acquirer announces its intention to try for the semaphore
870 * by putting a Sema structure onto the wait list and then
871 * setting Sema.waiting. After one last check of semaphore,
872 * the acquirer sleeps until Sema.waiting==0. A releaser of n
873 * must wake up n acquirers who have Sema.waiting set. It does
874 * this by clearing Sema.waiting and then calling wakeup.
876 * There are three interesting races here.
878 * The first is that in this particular sleep/wakeup usage, a single
879 * wakeup can rouse a process from two consecutive sleeps!
882 * (a) set Sema.waiting = 1
884 * (b) set Sema.waiting = 0
885 * (a) check Sema.waiting inside sleep, return w/o sleeping
886 * (a) try for semaphore, fail
887 * (a) set Sema.waiting = 1
892 * This is okay - semacquire will just go around the loop
893 * again. It does mean that at the top of the for(;;) loop in
894 * semacquire, phore.waiting might already be set to 1.
896 * The second is that a releaser might wake an acquirer who is
897 * interrupted before he can acquire the lock. Since
898 * release(n) issues only n wakeup calls -- only n can be used
899 * anyway -- if the interrupted process is not going to use his
900 * wakeup call he must pass it on to another acquirer.
902 * The third race is similar to the second but more subtle. An
903 * acquirer sets waiting=1 and then does a final canacquire()
904 * before going to sleep. The opposite order would result in
905 * missing wakeups that happen between canacquire and
906 * waiting=1. (In fact, the whole point of Sema.waiting is to
907 * avoid missing wakeups between canacquire() and sleep().) But
908 * there can be spurious wakeups between a successful
909 * canacquire() and the following semdequeue(). This wakeup is
910 * not useful to the acquirer, since he has already acquired
911 * the semaphore. Like in the previous case, though, the
912 * acquirer must pass the wakeup call along.
914 * This is all rather subtle. The code below has been verified
915 * with the spin model /sys/src/9/port/semaphore.p. The
916 * original code anticipated the second race but not the first
917 * or third, which were caught only with spin. The first race
918 * is mentioned in /sys/doc/sleep.ps, but I'd forgotten about it.
919 * It was lucky that my abstract model of sleep/wakeup still managed
920 * to preserve that behavior.
922 * I remain slightly concerned about memory coherence
923 * outside of locks. The spin model does not take
924 * queued processor writes into account so we have to
925 * think hard. The only variables accessed outside locks
926 * are the semaphore value itself and the boolean flag
927 * Sema.waiting. The value is only accessed with cmpswap,
928 * whose job description includes doing the right thing as
929 * far as memory coherence across processors. That leaves
930 * Sema.waiting. To handle it, we call coherence() before each
931 * read and after each write. - rsc
934 /* Add semaphore p with addr a to list in seg. */
936 semqueue(Segment *s, long *a, Sema *p)
938 memset(p, 0, sizeof *p);
940 lock(&s->sema); /* uses s->sema.Rendez.Lock, but no one else is */
942 p->prev = s->sema.prev;
948 /* Remove semaphore p from list in seg. */
950 semdequeue(Segment *s, Sema *p)
953 p->next->prev = p->prev;
954 p->prev->next = p->next;
958 /* Wake up n waiters with addr a on list in seg. */
960 semwakeup(Segment *s, long *a, long n)
965 for(p=s->sema.next; p!=&s->sema && n>0; p=p->next){
966 if(p->addr == a && p->waiting){
976 /* Add delta to semaphore and wake up waiters as appropriate. */
978 semrelease(Segment *s, long *addr, long delta)
984 while(!cmpswap(addr, value, value+delta));
985 semwakeup(s, addr, delta);
989 /* Try to acquire semaphore using compare-and-swap */
991 canacquire(long *addr)
995 while((value=*addr) > 0)
996 if(cmpswap(addr, value, value-1))
1001 /* Should we wake up? */
1006 return !((Sema*)p)->waiting;
1009 /* Acquire semaphore (subtract 1). */
1011 semacquire(Segment *s, long *addr, int block)
1016 if(canacquire(addr))
1022 semqueue(s, addr, &phore);
1026 if(canacquire(addr)){
1032 sleep(&phore, semawoke, &phore);
1035 semdequeue(s, &phore);
1036 coherence(); /* not strictly necessary due to lock in semdequeue */
1038 semwakeup(s, addr, 1);
1044 /* Acquire semaphore or time-out */
1046 tsemacquire(Segment *s, long *addr, ulong ms)
1048 int acquired, timedout;
1052 if(canacquire(addr))
1056 acquired = timedout = 0;
1057 semqueue(s, addr, &phore);
1061 if(canacquire(addr)){
1068 tsleep(&phore, semawoke, &phore, ms);
1069 elms = TK2MS(m->ticks - t);
1077 semdequeue(s, &phore);
1078 coherence(); /* not strictly necessary due to lock in semdequeue */
1080 semwakeup(s, addr, 1);
1089 syssemacquire(ulong *arg)
1095 validaddr(arg[0], sizeof(long), 1);
1097 addr = (long*)arg[0];
1100 if((s = seg(up, (ulong)addr, 0)) == nil)
1104 return semacquire(s, addr, block);
1108 systsemacquire(ulong *arg)
1114 validaddr(arg[0], sizeof(long), 1);
1116 addr = (long*)arg[0];
1119 if((s = seg(up, (ulong)addr, 0)) == nil)
1123 return tsemacquire(s, addr, ms);
1127 syssemrelease(ulong *arg)
1132 validaddr(arg[0], sizeof(long), 1);
1134 addr = (long*)arg[0];
1137 if((s = seg(up, (ulong)addr, 0)) == nil)
1139 if(delta < 0 || *addr < 0)
1141 return semrelease(s, addr, arg[1]);