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);
27 pexit("fork aborted", 1);
43 /* Check flags before we commit */
44 if((flag & (RFFDG|RFCFDG)) == (RFFDG|RFCFDG))
46 if((flag & (RFNAMEG|RFCNAMEG)) == (RFNAMEG|RFCNAMEG))
48 if((flag & (RFENVG|RFCENVG)) == (RFENVG|RFCENVG))
51 if((flag&RFPROC) == 0) {
52 if(flag & (RFMEM|RFNOWAIT))
54 if(flag & (RFFDG|RFCFDG)) {
57 up->fgrp = dupfgrp(ofg);
59 up->fgrp = dupfgrp(nil);
62 if(flag & (RFNAMEG|RFCNAMEG)) {
66 pgrpcpy(up->pgrp, opg);
67 /* inherit noattach */
68 up->pgrp->noattach = opg->noattach;
72 up->pgrp->noattach = 1;
78 if(flag & (RFENVG|RFCENVG)) {
80 up->egrp = smalloc(sizeof(Egrp));
83 envcpy(up->egrp, oeg);
87 up->noteid = pidalloc(0);
93 p->scallnr = up->scallnr;
100 memmove(p->note, up->note, sizeof(p->note));
101 p->privatemem = up->privatemem;
102 p->noswap = up->noswap;
103 p->nnote = up->nnote;
105 p->lastnote = up->lastnote;
106 p->notify = up->notify;
110 /* Abort the child process on error */
113 kprocchild(p, abortion, 0);
118 /* Make a new set of memory segments */
122 qunlock(&p->seglock);
125 for(i = 0; i < NSEG; i++)
127 p->seg[i] = dupseg(up->seg, i, n);
128 qunlock(&p->seglock);
131 /* File descriptors */
132 if(flag & (RFFDG|RFCFDG)) {
134 p->fgrp = dupfgrp(up->fgrp);
136 p->fgrp = dupfgrp(nil);
144 if(flag & (RFNAMEG|RFCNAMEG)) {
147 pgrpcpy(p->pgrp, up->pgrp);
148 /* inherit noattach */
149 p->pgrp->noattach = up->pgrp->noattach;
156 p->pgrp->noattach = 1;
165 /* Environment group */
166 if(flag & (RFENVG|RFCENVG)) {
167 p->egrp = smalloc(sizeof(Egrp));
170 envcpy(p->egrp, up->egrp);
177 p->procmode = up->procmode;
178 if(up->procctl == Proc_tracesyscall)
179 p->procctl = Proc_tracesyscall;
181 poperror(); /* abortion */
183 /* Craft a return frame which will cause the child to pop out of
184 * the scheduler in user mode with the return register zero
186 forkchild(p, up->dbgreg);
189 if((flag&RFNOWAIT) == 0){
190 p->parentpid = up->pid;
195 if((flag&RFNOTEG) == 0)
196 p->noteid = up->noteid;
199 memset(p->time, 0, sizeof(p->time));
200 p->time[TReal] = MACHP(0)->ticks;
202 kstrdup(&p->text, up->text);
203 kstrdup(&p->user, up->user);
208 * since the bss/data segments are now shareable,
209 * any mmu info about this process is now stale
210 * (i.e. has bad properties) and has to be discarded.
213 p->basepri = up->basepri;
214 p->priority = up->basepri;
215 p->fixedpri = up->fixedpri;
219 procwired(p, wm->machno);
231 return (cp[0]<<24) | (cp[1]<<16) | (cp[2]<<8) | cp[3];
242 char *a, *charp, *args, *file, *file0;
243 char *progarg[sizeof(Exec)/2+1], *elem, progelem[64];
244 ulong ssize, tstk, nargs, nbytes, n, bssend;
247 char line[sizeof(Exec)];
250 ulong magic, text, entry, data, bss;
255 validaddr(arg[0], 1, 0);
256 file0 = validnamedup((char*)arg[0], 1);
261 /* Disaster after commit */
263 pexit(up->errstr, 1);
268 tc = namec(file, Aopen, OEXEC, 0);
274 kstrdup(&elem, up->genbuf);
276 n = devtab[tc->type]->read(tc, &exec, sizeof(Exec), 0);
279 magic = l2be(exec.magic);
280 text = l2be(exec.text);
281 entry = l2be(exec.entry);
282 if(n==sizeof(Exec) && (magic == AOUT_MAGIC)){
283 if(text >= USTKTOP-UTZERO
284 || entry < UTZERO+sizeof(Exec)
285 || entry >= UTZERO+sizeof(Exec)+text)
287 break; /* for binary */
291 * Process #! /bin/sh args ...
293 memmove(line, &exec, sizeof(Exec));
294 if(indir || line[0]!='#' || line[1]!='!')
296 n = shargs(line, n, progarg);
301 * First arg becomes complete file name
305 validaddr(arg[1], BY2WD, 1);
308 if(strlen(elem) >= sizeof progelem)
310 strcpy(progelem, elem);
311 progarg[0] = progelem;
316 data = l2be(exec.data);
317 bss = l2be(exec.bss);
318 t = (UTZERO+sizeof(Exec)+text+(BY2PG-1)) & ~(BY2PG-1);
319 d = (t + data + (BY2PG-1)) & ~(BY2PG-1);
320 bssend = t + data + bss;
321 b = (bssend + (BY2PG-1)) & ~(BY2PG-1);
322 if(t >= KZERO || d >= KZERO || b >= KZERO)
326 * Args: pass 1: count
328 nbytes = sizeof(Tos); /* hole for profiling clock at top of stack (and more) */
334 nbytes += strlen(a) + 1;
339 argp = (char**)arg[1];
340 validaddr((ulong)argp, BY2WD, 0);
343 if(((ulong)argp&(BY2PG-1)) < BY2WD)
344 validaddr((ulong)argp, BY2WD, 0);
345 validaddr((ulong)a, 1, 0);
346 nbytes += ((char*)vmemchr(a, 0, 0x7FFFFFFF) - a) + 1;
349 ssize = BY2WD*(nargs+1) + ((nbytes+(BY2WD-1)) & ~(BY2WD-1));
352 * 8-byte align SP for those (e.g. sparc) that need it.
353 * execregs() will subtract another 4 bytes for argc.
358 if(PGROUND(ssize) >= USTKSIZE)
362 * Build the stack segment, putting it in kernel virtual for the moment
366 qunlock(&up->seglock);
375 } while((s = isoverlap(up, tstk-USTKSIZE, USTKSIZE)) != nil);
376 up->seg[ESEG] = newseg(SG_STACK, tstk-USTKSIZE, USTKSIZE/BY2PG);
379 * Args: pass 2: assemble; the pages will be faulted in
381 tos = (Tos*)(tstk - sizeof(Tos));
382 tos->cyclefreq = m->cyclefreq;
387 argv = (char**)(tstk - ssize);
388 charp = (char*)(tstk - nbytes);
393 argp = (char**)arg[1];
395 for(i=0; i<nargs; i++){
396 if(indir && *argp==0) {
398 argp = (char**)arg[1];
400 *argv++ = charp + (USTKTOP-tstk);
401 n = strlen(*argp) + 1;
402 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 */
416 up->args = smalloc(n);
417 memmove(up->args, args, n);
418 if(n>0 && up->args[n-1]!='\0'){
419 /* make sure last arg is NUL-terminated */
420 /* put NUL at UTF-8 character boundary */
422 if(fullrune(up->args+i, n-i))
432 * Special segments are maintained across exec
434 for(i = SSEG; i <= BSEG; i++) {
436 /* prevent a second free if we have an error */
439 for(i = ESEG+1; i < NSEG; i++) {
441 if(s != 0 && (s->type&SG_CEXEC) != 0) {
450 if((f = up->fgrp) != nil){
451 for(i=0; i<=f->maxfd; i++)
455 /* Text. Shared. Attaches to cache image if possible */
456 /* attachimage returns a locked cache image */
457 img = attachimage(SG_TEXT|SG_RONLY, tc, UTZERO, (t-UTZERO)>>PGSHIFT);
462 ts->flen = sizeof(Exec)+text;
466 s = newseg(SG_DATA, t, (d-t)>>PGSHIFT);
469 /* Attached by hand */
472 s->fstart = ts->fstart+ts->flen;
475 /* BSS. Zero fill on demand */
476 up->seg[BSEG] = newseg(SG_BSS, d, (b-d)>>PGSHIFT);
483 s->base = USTKTOP-USTKSIZE;
485 relocateseg(s, USTKTOP-tstk);
487 qunlock(&up->seglock);
488 poperror(); /* seglock */
491 * '/' processes are higher priority (hack to make /ip more responsive).
493 if(devtab[tc->type]->dc == L'/')
494 up->basepri = PriRoot;
495 up->priority = up->basepri;
498 poperror(); /* file0 */
510 * At this point, the mmu contains info about the old address
511 * space and needs to be flushed
516 up->procctl = Proc_stopme;
517 return execregs(entry, ssize, nargs);
521 shargs(char *s, int n, char **ap)
526 n -= 2; /* skip #! */
527 for(i=0; s[i]!='\n'; i++)
534 while(*s==' ' || *s=='\t')
541 while(*s && *s!=' ' && *s!='\t')
565 if (up->edf && (up->edf->flags & Admitted))
573 tsleep(&up->sleep, return0, 0, n);
580 return procalarm(arg[0]);
587 char *inval = "invalid exit string";
590 status = (char*)arg[0];
595 validaddr((ulong)status, 1, 0);
596 if(vmemchr(status, 0, ERRMAX) == 0){
597 memmove(buf, status, ERRMAX);
606 return 0; /* not reached */
619 validaddr(arg[0], sizeof(OWaitmsg), 1);
623 ow = (OWaitmsg*)arg[0];
624 readnum(0, ow->pid, NUMSIZE, w.pid, NUMSIZE);
625 readnum(0, ow->time+TUser*NUMSIZE, NUMSIZE, w.time[TUser], NUMSIZE);
626 readnum(0, ow->time+TSys*NUMSIZE, NUMSIZE, w.time[TSys], NUMSIZE);
627 readnum(0, ow->time+TReal*NUMSIZE, NUMSIZE, w.time[TReal], NUMSIZE);
628 strncpy(ow->msg, w.msg, sizeof(ow->msg)-1);
629 ow->msg[sizeof(ow->msg)-1] = '\0';
643 validaddr(arg[0], n, 1);
647 i = snprint((char*)arg[0], n, "%d %lud %lud %lud %q",
649 w.time[TUser], w.time[TSys], w.time[TReal],
656 werrstr(char *fmt, ...)
664 vseprint(up->syserrstr, up->syserrstr+ERRMAX, fmt, va);
669 generrstr(char *buf, uint nbuf)
675 validaddr((ulong)buf, nbuf, 1);
676 if(nbuf > sizeof tmp)
678 memmove(tmp, buf, nbuf);
680 /* make sure it's NUL-terminated */
682 memmove(buf, up->syserrstr, nbuf);
684 memmove(up->syserrstr, tmp, nbuf);
689 syserrstr(ulong *arg)
691 return generrstr((char*)arg[0], arg[1]);
694 /* compatibility for old binaries */
696 sys_errstr(ulong *arg)
698 return generrstr((char*)arg[0], 64);
702 sysnotify(ulong *arg)
705 validaddr(arg[0], sizeof(ulong), 0);
706 up->notify = (int(*)(void*, char*))(arg[0]);
713 if(arg[0]!=NRSTR && !up->notified)
719 syssegbrk(ulong *arg)
726 for(i = 0; i < NSEG; i++) {
728 if(s == 0 || addr < s->base || addr >= s->top)
730 switch(s->type&SG_TYPE) {
736 return ibrk(arg[1], i);
741 return 0; /* not reached */
745 syssegattach(ulong *arg)
747 return segattach(up, arg[0], (char*)arg[1], arg[2], arg[3]);
751 syssegdetach(ulong *arg)
759 qunlock(&up->seglock);
765 for(i = 0; i < NSEG; i++)
768 if((addr >= s->base && addr < s->top) ||
769 (s->top == s->base && addr == s->base))
778 * Check we are not detaching the initial stack segment.
780 if(s == up->seg[SSEG]){
787 qunlock(&up->seglock);
790 /* Ensure we flush any entries from the lost segment */
796 syssegfree(ulong *arg)
802 s = seg(up, from, 1);
805 to = (from + arg[1]) & ~(BY2PG-1);
806 from = PGROUND(from);
813 mfreeseg(s, from, (to - from) / BY2PG);
820 /* For binary compatibility */
824 return ibrk(arg[0], BSEG);
828 sysrendezvous(ulong *arg)
834 l = &REND(up->rgrp, tag);
837 for(p = *l; p; p = p->rendhash) {
838 if(p->rendtag == tag) {
851 /* Going to sleep here */
853 up->rendval = arg[1];
856 up->state = Rendezvous;
865 * The implementation of semaphores is complicated by needing
866 * to avoid rescheduling in syssemrelease, so that it is safe
867 * to call from real-time processes. This means syssemrelease
868 * cannot acquire any qlocks, only spin locks.
870 * Semacquire and semrelease must both manipulate the semaphore
871 * wait list. Lock-free linked lists only exist in theory, not
872 * in practice, so the wait list is protected by a spin lock.
874 * The semaphore value *addr is stored in user memory, so it
875 * cannot be read or written while holding spin locks.
877 * Thus, we can access the list only when holding the lock, and
878 * we can access the semaphore only when not holding the lock.
879 * This makes things interesting. Note that sleep's condition function
880 * is called while holding two locks - r and up->rlock - so it cannot
881 * access the semaphore value either.
883 * An acquirer announces its intention to try for the semaphore
884 * by putting a Sema structure onto the wait list and then
885 * setting Sema.waiting. After one last check of semaphore,
886 * the acquirer sleeps until Sema.waiting==0. A releaser of n
887 * must wake up n acquirers who have Sema.waiting set. It does
888 * this by clearing Sema.waiting and then calling wakeup.
890 * There are three interesting races here.
892 * The first is that in this particular sleep/wakeup usage, a single
893 * wakeup can rouse a process from two consecutive sleeps!
896 * (a) set Sema.waiting = 1
898 * (b) set Sema.waiting = 0
899 * (a) check Sema.waiting inside sleep, return w/o sleeping
900 * (a) try for semaphore, fail
901 * (a) set Sema.waiting = 1
906 * This is okay - semacquire will just go around the loop
907 * again. It does mean that at the top of the for(;;) loop in
908 * semacquire, phore.waiting might already be set to 1.
910 * The second is that a releaser might wake an acquirer who is
911 * interrupted before he can acquire the lock. Since
912 * release(n) issues only n wakeup calls -- only n can be used
913 * anyway -- if the interrupted process is not going to use his
914 * wakeup call he must pass it on to another acquirer.
916 * The third race is similar to the second but more subtle. An
917 * acquirer sets waiting=1 and then does a final canacquire()
918 * before going to sleep. The opposite order would result in
919 * missing wakeups that happen between canacquire and
920 * waiting=1. (In fact, the whole point of Sema.waiting is to
921 * avoid missing wakeups between canacquire() and sleep().) But
922 * there can be spurious wakeups between a successful
923 * canacquire() and the following semdequeue(). This wakeup is
924 * not useful to the acquirer, since he has already acquired
925 * the semaphore. Like in the previous case, though, the
926 * acquirer must pass the wakeup call along.
928 * This is all rather subtle. The code below has been verified
929 * with the spin model /sys/src/9/port/semaphore.p. The
930 * original code anticipated the second race but not the first
931 * or third, which were caught only with spin. The first race
932 * is mentioned in /sys/doc/sleep.ps, but I'd forgotten about it.
933 * It was lucky that my abstract model of sleep/wakeup still managed
934 * to preserve that behavior.
936 * I remain slightly concerned about memory coherence
937 * outside of locks. The spin model does not take
938 * queued processor writes into account so we have to
939 * think hard. The only variables accessed outside locks
940 * are the semaphore value itself and the boolean flag
941 * Sema.waiting. The value is only accessed with cmpswap,
942 * whose job description includes doing the right thing as
943 * far as memory coherence across processors. That leaves
944 * Sema.waiting. To handle it, we call coherence() before each
945 * read and after each write. - rsc
948 /* Add semaphore p with addr a to list in seg. */
950 semqueue(Segment *s, long *a, Sema *p)
952 memset(p, 0, sizeof *p);
954 lock(&s->sema); /* uses s->sema.Rendez.Lock, but no one else is */
956 p->prev = s->sema.prev;
962 /* Remove semaphore p from list in seg. */
964 semdequeue(Segment *s, Sema *p)
967 p->next->prev = p->prev;
968 p->prev->next = p->next;
972 /* Wake up n waiters with addr a on list in seg. */
974 semwakeup(Segment *s, long *a, long n)
979 for(p=s->sema.next; p!=&s->sema && n>0; p=p->next){
980 if(p->addr == a && p->waiting){
990 /* Add delta to semaphore and wake up waiters as appropriate. */
992 semrelease(Segment *s, long *addr, long delta)
998 while(!cmpswap(addr, value, value+delta));
999 semwakeup(s, addr, delta);
1003 /* Try to acquire semaphore using compare-and-swap */
1005 canacquire(long *addr)
1009 while((value=*addr) > 0)
1010 if(cmpswap(addr, value, value-1))
1015 /* Should we wake up? */
1020 return !((Sema*)p)->waiting;
1023 /* Acquire semaphore (subtract 1). */
1025 semacquire(Segment *s, long *addr, int block)
1030 if(canacquire(addr))
1036 semqueue(s, addr, &phore);
1040 if(canacquire(addr)){
1046 sleep(&phore, semawoke, &phore);
1049 semdequeue(s, &phore);
1050 coherence(); /* not strictly necessary due to lock in semdequeue */
1052 semwakeup(s, addr, 1);
1058 /* Acquire semaphore or time-out */
1060 tsemacquire(Segment *s, long *addr, ulong ms)
1062 int acquired, timedout;
1066 if(canacquire(addr))
1070 acquired = timedout = 0;
1071 semqueue(s, addr, &phore);
1075 if(canacquire(addr)){
1082 tsleep(&phore, semawoke, &phore, ms);
1083 elms = TK2MS(m->ticks - t);
1091 semdequeue(s, &phore);
1092 coherence(); /* not strictly necessary due to lock in semdequeue */
1094 semwakeup(s, addr, 1);
1103 syssemacquire(ulong *arg)
1109 validaddr(arg[0], sizeof(long), 1);
1111 addr = (long*)arg[0];
1114 if((s = seg(up, (ulong)addr, 0)) == nil)
1118 return semacquire(s, addr, block);
1122 systsemacquire(ulong *arg)
1128 validaddr(arg[0], sizeof(long), 1);
1130 addr = (long*)arg[0];
1133 if((s = seg(up, (ulong)addr, 0)) == nil)
1137 return tsemacquire(s, addr, ms);
1141 syssemrelease(ulong *arg)
1146 validaddr(arg[0], sizeof(long), 1);
1148 addr = (long*)arg[0];
1151 if((s = seg(up, (ulong)addr, 0)) == nil)
1153 /* delta == 0 is a no-op, not a release */
1154 if(delta < 0 || *addr < 0)
1156 return semrelease(s, addr, delta);