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);
29 pexit("fork aborted", 1);
45 /* Check flags before we commit */
46 if((flag & (RFFDG|RFCFDG)) == (RFFDG|RFCFDG))
48 if((flag & (RFNAMEG|RFCNAMEG)) == (RFNAMEG|RFCNAMEG))
50 if((flag & (RFENVG|RFCENVG)) == (RFENVG|RFCENVG))
53 if((flag&RFPROC) == 0) {
54 if(flag & (RFMEM|RFNOWAIT))
56 if(flag & (RFFDG|RFCFDG)) {
59 up->fgrp = dupfgrp(ofg);
61 up->fgrp = dupfgrp(nil);
64 if(flag & (RFNAMEG|RFCNAMEG)) {
68 pgrpcpy(up->pgrp, opg);
69 /* inherit noattach */
70 up->pgrp->noattach = opg->noattach;
74 up->pgrp->noattach = 1;
80 if(flag & (RFENVG|RFCENVG)) {
82 up->egrp = smalloc(sizeof(Egrp));
85 envcpy(up->egrp, oeg);
89 up->noteid = pidalloc(0);
95 p->scallnr = up->scallnr;
102 memmove(p->note, up->note, sizeof(p->note));
103 p->privatemem = up->privatemem;
104 p->noswap = up->noswap;
105 p->nnote = up->nnote;
107 p->lastnote = up->lastnote;
108 p->notify = up->notify;
112 /* Abort the child process on error */
115 kprocchild(p, abortion, 0);
120 /* Make a new set of memory segments */
124 qunlock(&p->seglock);
127 for(i = 0; i < NSEG; i++)
129 p->seg[i] = dupseg(up->seg, i, n);
130 qunlock(&p->seglock);
133 /* File descriptors */
134 if(flag & (RFFDG|RFCFDG)) {
136 p->fgrp = dupfgrp(up->fgrp);
138 p->fgrp = dupfgrp(nil);
146 if(flag & (RFNAMEG|RFCNAMEG)) {
149 pgrpcpy(p->pgrp, up->pgrp);
150 /* inherit noattach */
151 p->pgrp->noattach = up->pgrp->noattach;
158 p->pgrp->noattach = 1;
167 /* Environment group */
168 if(flag & (RFENVG|RFCENVG)) {
169 p->egrp = smalloc(sizeof(Egrp));
172 envcpy(p->egrp, up->egrp);
179 p->procmode = up->procmode;
180 if(up->procctl == Proc_tracesyscall)
181 p->procctl = Proc_tracesyscall;
183 poperror(); /* abortion */
185 /* Craft a return frame which will cause the child to pop out of
186 * the scheduler in user mode with the return register zero
188 forkchild(p, up->dbgreg);
191 if((flag&RFNOWAIT) == 0){
192 p->parentpid = up->pid;
197 if((flag&RFNOTEG) == 0)
198 p->noteid = up->noteid;
201 memset(p->time, 0, sizeof(p->time));
202 p->time[TReal] = MACHP(0)->ticks;
204 kstrdup(&p->text, up->text);
205 kstrdup(&p->user, up->user);
210 * since the bss/data segments are now shareable,
211 * any mmu info about this process is now stale
212 * (i.e. has bad properties) and has to be discarded.
215 p->basepri = up->basepri;
216 p->priority = up->basepri;
217 p->fixedpri = up->fixedpri;
221 procwired(p, wm->machno);
233 return (cp[0]<<24) | (cp[1]<<16) | (cp[2]<<8) | cp[3];
244 char *a, *charp, *args, *file, *file0;
245 char *progarg[sizeof(Exec)/2+1], *elem, progelem[64];
246 ulong ssize, tstk, nargs, nbytes, n, bssend;
249 char line[sizeof(Exec)];
252 ulong magic, text, entry, data, bss;
257 validaddr(arg[0], 1, 0);
258 file0 = validnamedup((char*)arg[0], 1);
263 /* Disaster after commit */
265 pexit(up->errstr, 1);
271 tc = namec(file, Aopen, OEXEC, 0);
277 kstrdup(&elem, up->genbuf);
279 n = devtab[tc->type]->read(tc, &exec, sizeof(Exec), 0);
282 magic = l2be(exec.magic);
283 text = l2be(exec.text);
284 entry = l2be(exec.entry);
285 if(n==sizeof(Exec) && (magic == AOUT_MAGIC)){
286 if(text >= USTKTOP-UTZERO
287 || entry < UTZERO+sizeof(Exec)
288 || entry >= UTZERO+sizeof(Exec)+text)
290 break; /* for binary */
294 * Process #! /bin/sh args ...
296 memmove(line, &exec, sizeof(Exec));
297 if(indir || line[0]!='#' || line[1]!='!')
299 n = shargs(line, n, progarg);
304 * First arg becomes complete file name
308 validaddr(arg[1], BY2WD, 1);
311 if(strlen(elem) >= sizeof progelem)
313 strcpy(progelem, elem);
314 progarg[0] = progelem;
319 data = l2be(exec.data);
320 bss = l2be(exec.bss);
321 t = (UTZERO+sizeof(Exec)+text+(BY2PG-1)) & ~(BY2PG-1);
322 d = (t + data + (BY2PG-1)) & ~(BY2PG-1);
323 bssend = t + data + bss;
324 b = (bssend + (BY2PG-1)) & ~(BY2PG-1);
325 if(t >= KZERO || d >= KZERO || b >= KZERO)
329 * Args: pass 1: count
331 nbytes = sizeof(Tos); /* hole for profiling clock at top of stack (and more) */
337 nbytes += strlen(a) + 1;
342 argp = (char**)arg[1];
343 validaddr((ulong)argp, BY2WD, 0);
346 if(((ulong)argp&(BY2PG-1)) < BY2WD)
347 validaddr((ulong)argp, BY2WD, 0);
348 validaddr((ulong)a, 1, 0);
349 nbytes += ((char*)vmemchr(a, 0, 0x7FFFFFFF) - a) + 1;
352 ssize = BY2WD*(nargs+1) + ((nbytes+(BY2WD-1)) & ~(BY2WD-1));
355 * 8-byte align SP for those (e.g. sparc) that need it.
356 * execregs() will subtract another 4 bytes for argc.
361 if(PGROUND(ssize) >= USTKSIZE)
365 * Build the stack segment, putting it in kernel virtual for the moment
369 qunlock(&up->seglock);
378 } while((s = isoverlap(up, tstk-USTKSIZE, USTKSIZE)) != nil);
379 up->seg[ESEG] = newseg(SG_STACK, tstk-USTKSIZE, USTKSIZE/BY2PG);
382 * Args: pass 2: assemble; the pages will be faulted in
384 tos = (Tos*)(tstk - sizeof(Tos));
385 tos->cyclefreq = m->cyclefreq;
390 argv = (char**)(tstk - ssize);
391 charp = (char*)(tstk - nbytes);
396 argp = (char**)arg[1];
398 for(i=0; i<nargs; i++){
399 if(indir && *argp==0) {
401 argp = (char**)arg[1];
403 *argv++ = charp + (USTKTOP-tstk);
404 n = strlen(*argp) + 1;
405 memmove(charp, *argp++, n);
409 /* copy args; easiest from new process's stack */
411 if(n > 128) /* don't waste too much space on huge arg lists */
415 if(n>0 && a[n-1]!='\0'){
416 /* make sure last arg is NUL-terminated */
417 /* put NUL at UTF-8 character boundary */
419 if(fullrune(a+i, n-i))
428 * Special segments are maintained across exec
430 for(i = SSEG; i <= BSEG; i++) {
432 /* prevent a second free if we have an error */
435 for(i = ESEG+1; i < NSEG; i++) {
437 if(s != 0 && (s->type&SG_CEXEC) != 0) {
446 if((f = up->fgrp) != nil){
447 for(i=0; i<=f->maxfd; i++)
451 /* Text. Shared. Attaches to cache image if possible */
452 /* attachimage returns a locked cache image */
453 img = attachimage(SG_TEXT|SG_RONLY, tc, UTZERO, (t-UTZERO)>>PGSHIFT);
458 ts->flen = sizeof(Exec)+text;
462 s = newseg(SG_DATA, t, (d-t)>>PGSHIFT);
465 /* Attached by hand */
468 s->fstart = ts->fstart+ts->flen;
471 /* BSS. Zero fill on demand */
472 up->seg[BSEG] = newseg(SG_BSS, d, (b-d)>>PGSHIFT);
479 s->base = USTKTOP-USTKSIZE;
481 relocateseg(s, USTKTOP-tstk);
483 qunlock(&up->seglock);
484 poperror(); /* seglock */
487 * '/' processes are higher priority (hack to make /ip more responsive).
489 if(devtab[tc->type]->dc == L'/')
490 up->basepri = PriRoot;
491 up->priority = up->basepri;
494 poperror(); /* file0 */
513 * At this point, the mmu contains info about the old address
514 * space and needs to be flushed
519 up->procctl = Proc_stopme;
520 return execregs(entry, ssize, nargs);
524 shargs(char *s, int n, char **ap)
529 n -= 2; /* skip #! */
530 for(i=0; s[i]!='\n'; i++)
537 while(*s==' ' || *s=='\t')
544 while(*s && *s!=' ' && *s!='\t')
568 if (up->edf && (up->edf->flags & Admitted))
576 tsleep(&up->sleep, return0, 0, n);
583 return procalarm(arg[0]);
590 char *inval = "invalid exit string";
593 status = (char*)arg[0];
598 validaddr((ulong)status, 1, 0);
599 if(vmemchr(status, 0, ERRMAX) == 0){
600 memmove(buf, status, ERRMAX);
609 return 0; /* not reached */
622 validaddr(arg[0], sizeof(OWaitmsg), 1);
626 ow = (OWaitmsg*)arg[0];
627 readnum(0, ow->pid, NUMSIZE, w.pid, NUMSIZE);
628 readnum(0, ow->time+TUser*NUMSIZE, NUMSIZE, w.time[TUser], NUMSIZE);
629 readnum(0, ow->time+TSys*NUMSIZE, NUMSIZE, w.time[TSys], NUMSIZE);
630 readnum(0, ow->time+TReal*NUMSIZE, NUMSIZE, w.time[TReal], NUMSIZE);
631 strncpy(ow->msg, w.msg, sizeof(ow->msg)-1);
632 ow->msg[sizeof(ow->msg)-1] = '\0';
646 validaddr(arg[0], n, 1);
650 i = snprint((char*)arg[0], n, "%d %lud %lud %lud %q",
652 w.time[TUser], w.time[TSys], w.time[TReal],
659 werrstr(char *fmt, ...)
667 vseprint(up->syserrstr, up->syserrstr+ERRMAX, fmt, va);
672 generrstr(char *buf, uint nbuf)
678 validaddr((ulong)buf, nbuf, 1);
679 if(nbuf > sizeof tmp)
681 memmove(tmp, buf, nbuf);
683 /* make sure it's NUL-terminated */
685 memmove(buf, up->syserrstr, nbuf);
687 memmove(up->syserrstr, tmp, nbuf);
692 syserrstr(ulong *arg)
694 return generrstr((char*)arg[0], arg[1]);
697 /* compatibility for old binaries */
699 sys_errstr(ulong *arg)
701 return generrstr((char*)arg[0], 64);
705 sysnotify(ulong *arg)
708 validaddr(arg[0], sizeof(ulong), 0);
709 up->notify = (int(*)(void*, char*))(arg[0]);
716 if(arg[0]!=NRSTR && !up->notified)
722 syssegbrk(ulong *arg)
729 for(i = 0; i < NSEG; i++) {
731 if(s == 0 || addr < s->base || addr >= s->top)
733 switch(s->type&SG_TYPE) {
739 return ibrk(arg[1], i);
744 return 0; /* not reached */
748 syssegattach(ulong *arg)
750 return segattach(up, arg[0], (char*)arg[1], arg[2], arg[3]);
754 syssegdetach(ulong *arg)
762 qunlock(&up->seglock);
768 for(i = 0; i < NSEG; i++)
771 if((addr >= s->base && addr < s->top) ||
772 (s->top == s->base && addr == s->base))
781 * Check we are not detaching the initial stack segment.
783 if(s == up->seg[SSEG]){
790 qunlock(&up->seglock);
793 /* Ensure we flush any entries from the lost segment */
799 syssegfree(ulong *arg)
805 s = seg(up, from, 1);
808 to = (from + arg[1]) & ~(BY2PG-1);
809 from = PGROUND(from);
816 mfreeseg(s, from, (to - from) / BY2PG);
823 /* For binary compatibility */
827 return ibrk(arg[0], BSEG);
831 sysrendezvous(ulong *arg)
837 l = &REND(up->rgrp, tag);
840 for(p = *l; p; p = p->rendhash) {
841 if(p->rendtag == tag) {
854 /* Going to sleep here */
856 up->rendval = arg[1];
859 up->state = Rendezvous;
868 * The implementation of semaphores is complicated by needing
869 * to avoid rescheduling in syssemrelease, so that it is safe
870 * to call from real-time processes. This means syssemrelease
871 * cannot acquire any qlocks, only spin locks.
873 * Semacquire and semrelease must both manipulate the semaphore
874 * wait list. Lock-free linked lists only exist in theory, not
875 * in practice, so the wait list is protected by a spin lock.
877 * The semaphore value *addr is stored in user memory, so it
878 * cannot be read or written while holding spin locks.
880 * Thus, we can access the list only when holding the lock, and
881 * we can access the semaphore only when not holding the lock.
882 * This makes things interesting. Note that sleep's condition function
883 * is called while holding two locks - r and up->rlock - so it cannot
884 * access the semaphore value either.
886 * An acquirer announces its intention to try for the semaphore
887 * by putting a Sema structure onto the wait list and then
888 * setting Sema.waiting. After one last check of semaphore,
889 * the acquirer sleeps until Sema.waiting==0. A releaser of n
890 * must wake up n acquirers who have Sema.waiting set. It does
891 * this by clearing Sema.waiting and then calling wakeup.
893 * There are three interesting races here.
895 * The first is that in this particular sleep/wakeup usage, a single
896 * wakeup can rouse a process from two consecutive sleeps!
899 * (a) set Sema.waiting = 1
901 * (b) set Sema.waiting = 0
902 * (a) check Sema.waiting inside sleep, return w/o sleeping
903 * (a) try for semaphore, fail
904 * (a) set Sema.waiting = 1
909 * This is okay - semacquire will just go around the loop
910 * again. It does mean that at the top of the for(;;) loop in
911 * semacquire, phore.waiting might already be set to 1.
913 * The second is that a releaser might wake an acquirer who is
914 * interrupted before he can acquire the lock. Since
915 * release(n) issues only n wakeup calls -- only n can be used
916 * anyway -- if the interrupted process is not going to use his
917 * wakeup call he must pass it on to another acquirer.
919 * The third race is similar to the second but more subtle. An
920 * acquirer sets waiting=1 and then does a final canacquire()
921 * before going to sleep. The opposite order would result in
922 * missing wakeups that happen between canacquire and
923 * waiting=1. (In fact, the whole point of Sema.waiting is to
924 * avoid missing wakeups between canacquire() and sleep().) But
925 * there can be spurious wakeups between a successful
926 * canacquire() and the following semdequeue(). This wakeup is
927 * not useful to the acquirer, since he has already acquired
928 * the semaphore. Like in the previous case, though, the
929 * acquirer must pass the wakeup call along.
931 * This is all rather subtle. The code below has been verified
932 * with the spin model /sys/src/9/port/semaphore.p. The
933 * original code anticipated the second race but not the first
934 * or third, which were caught only with spin. The first race
935 * is mentioned in /sys/doc/sleep.ps, but I'd forgotten about it.
936 * It was lucky that my abstract model of sleep/wakeup still managed
937 * to preserve that behavior.
939 * I remain slightly concerned about memory coherence
940 * outside of locks. The spin model does not take
941 * queued processor writes into account so we have to
942 * think hard. The only variables accessed outside locks
943 * are the semaphore value itself and the boolean flag
944 * Sema.waiting. The value is only accessed with cmpswap,
945 * whose job description includes doing the right thing as
946 * far as memory coherence across processors. That leaves
947 * Sema.waiting. To handle it, we call coherence() before each
948 * read and after each write. - rsc
951 /* Add semaphore p with addr a to list in seg. */
953 semqueue(Segment *s, long *a, Sema *p)
955 memset(p, 0, sizeof *p);
957 lock(&s->sema); /* uses s->sema.Rendez.Lock, but no one else is */
959 p->prev = s->sema.prev;
965 /* Remove semaphore p from list in seg. */
967 semdequeue(Segment *s, Sema *p)
970 p->next->prev = p->prev;
971 p->prev->next = p->next;
975 /* Wake up n waiters with addr a on list in seg. */
977 semwakeup(Segment *s, long *a, long n)
982 for(p=s->sema.next; p!=&s->sema && n>0; p=p->next){
983 if(p->addr == a && p->waiting){
993 /* Add delta to semaphore and wake up waiters as appropriate. */
995 semrelease(Segment *s, long *addr, long delta)
1001 while(!cmpswap(addr, value, value+delta));
1002 semwakeup(s, addr, delta);
1006 /* Try to acquire semaphore using compare-and-swap */
1008 canacquire(long *addr)
1012 while((value=*addr) > 0)
1013 if(cmpswap(addr, value, value-1))
1018 /* Should we wake up? */
1023 return !((Sema*)p)->waiting;
1026 /* Acquire semaphore (subtract 1). */
1028 semacquire(Segment *s, long *addr, int block)
1033 if(canacquire(addr))
1039 semqueue(s, addr, &phore);
1043 if(canacquire(addr)){
1049 sleep(&phore, semawoke, &phore);
1052 semdequeue(s, &phore);
1053 coherence(); /* not strictly necessary due to lock in semdequeue */
1055 semwakeup(s, addr, 1);
1061 /* Acquire semaphore or time-out */
1063 tsemacquire(Segment *s, long *addr, ulong ms)
1065 int acquired, timedout;
1069 if(canacquire(addr))
1073 acquired = timedout = 0;
1074 semqueue(s, addr, &phore);
1078 if(canacquire(addr)){
1085 tsleep(&phore, semawoke, &phore, ms);
1086 elms = TK2MS(m->ticks - t);
1094 semdequeue(s, &phore);
1095 coherence(); /* not strictly necessary due to lock in semdequeue */
1097 semwakeup(s, addr, 1);
1106 syssemacquire(ulong *arg)
1112 validaddr(arg[0], sizeof(long), 1);
1114 addr = (long*)arg[0];
1117 if((s = seg(up, (ulong)addr, 0)) == nil)
1121 return semacquire(s, addr, block);
1125 systsemacquire(ulong *arg)
1131 validaddr(arg[0], sizeof(long), 1);
1133 addr = (long*)arg[0];
1136 if((s = seg(up, (ulong)addr, 0)) == nil)
1140 return tsemacquire(s, addr, ms);
1144 syssemrelease(ulong *arg)
1149 validaddr(arg[0], sizeof(long), 1);
1151 addr = (long*)arg[0];
1154 if((s = seg(up, (ulong)addr, 0)) == nil)
1156 /* delta == 0 is a no-op, not a release */
1157 if(delta < 0 || *addr < 0)
1159 return semrelease(s, addr, delta);