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);
270 tc = namec(file, Aopen, OEXEC, 0);
276 kstrdup(&elem, up->genbuf);
278 n = devtab[tc->type]->read(tc, &exec, sizeof(Exec), 0);
281 magic = l2be(exec.magic);
282 text = l2be(exec.text);
283 entry = l2be(exec.entry);
284 if(n==sizeof(Exec) && (magic == AOUT_MAGIC)){
285 if(text >= USTKTOP-UTZERO
286 || entry < UTZERO+sizeof(Exec)
287 || entry >= UTZERO+sizeof(Exec)+text)
289 break; /* for binary */
293 * Process #! /bin/sh args ...
295 memmove(line, &exec, sizeof(Exec));
296 if(indir || line[0]!='#' || line[1]!='!')
298 n = shargs(line, n, progarg);
303 * First arg becomes complete file name
307 validaddr(arg[1], BY2WD, 1);
310 if(strlen(elem) >= sizeof progelem)
312 strcpy(progelem, elem);
313 progarg[0] = progelem;
318 data = l2be(exec.data);
319 bss = l2be(exec.bss);
320 t = (UTZERO+sizeof(Exec)+text+(BY2PG-1)) & ~(BY2PG-1);
321 d = (t + data + (BY2PG-1)) & ~(BY2PG-1);
322 bssend = t + data + bss;
323 b = (bssend + (BY2PG-1)) & ~(BY2PG-1);
324 if(t >= KZERO || d >= KZERO || b >= KZERO)
328 * Args: pass 1: count
330 nbytes = sizeof(Tos); /* hole for profiling clock at top of stack (and more) */
336 nbytes += strlen(a) + 1;
341 argp = (char**)arg[1];
342 validaddr((ulong)argp, BY2WD, 0);
345 if(((ulong)argp&(BY2PG-1)) < BY2WD)
346 validaddr((ulong)argp, BY2WD, 0);
347 validaddr((ulong)a, 1, 0);
348 nbytes += ((char*)vmemchr(a, 0, 0x7FFFFFFF) - a) + 1;
351 ssize = BY2WD*(nargs+1) + ((nbytes+(BY2WD-1)) & ~(BY2WD-1));
354 * 8-byte align SP for those (e.g. sparc) that need it.
355 * execregs() will subtract another 4 bytes for argc.
360 if(PGROUND(ssize) >= USTKSIZE)
364 * Build the stack segment, putting it in kernel virtual for the moment
368 qunlock(&up->seglock);
377 } while((s = isoverlap(up, tstk-USTKSIZE, USTKSIZE)) != nil);
378 up->seg[ESEG] = newseg(SG_STACK, tstk-USTKSIZE, USTKSIZE/BY2PG);
381 * Args: pass 2: assemble; the pages will be faulted in
383 tos = (Tos*)(tstk - sizeof(Tos));
384 tos->cyclefreq = m->cyclefreq;
389 argv = (char**)(tstk - ssize);
390 charp = (char*)(tstk - nbytes);
395 argp = (char**)arg[1];
397 for(i=0; i<nargs; i++){
398 if(indir && *argp==0) {
400 argp = (char**)arg[1];
402 *argv++ = charp + (USTKTOP-tstk);
403 n = strlen(*argp) + 1;
404 memmove(charp, *argp++, n);
411 /* copy args; easiest from new process's stack */
413 if(n > 128) /* don't waste too much space on huge arg lists */
418 up->args = smalloc(n);
419 memmove(up->args, args, n);
420 if(n>0 && up->args[n-1]!='\0'){
421 /* make sure last arg is NUL-terminated */
422 /* put NUL at UTF-8 character boundary */
424 if(fullrune(up->args+i, n-i))
434 * Special segments are maintained across exec
436 for(i = SSEG; i <= BSEG; i++) {
438 /* prevent a second free if we have an error */
441 for(i = ESEG+1; i < NSEG; i++) {
443 if(s != 0 && (s->type&SG_CEXEC) != 0) {
452 if((f = up->fgrp) != nil){
453 for(i=0; i<=f->maxfd; i++)
457 /* Text. Shared. Attaches to cache image if possible */
458 /* attachimage returns a locked cache image */
459 img = attachimage(SG_TEXT|SG_RONLY, tc, UTZERO, (t-UTZERO)>>PGSHIFT);
464 ts->flen = sizeof(Exec)+text;
468 s = newseg(SG_DATA, t, (d-t)>>PGSHIFT);
471 /* Attached by hand */
474 s->fstart = ts->fstart+ts->flen;
477 /* BSS. Zero fill on demand */
478 up->seg[BSEG] = newseg(SG_BSS, d, (b-d)>>PGSHIFT);
485 s->base = USTKTOP-USTKSIZE;
487 relocateseg(s, USTKTOP-tstk);
489 qunlock(&up->seglock);
490 poperror(); /* seglock */
493 * '/' processes are higher priority (hack to make /ip more responsive).
495 if(devtab[tc->type]->dc == L'/')
496 up->basepri = PriRoot;
497 up->priority = up->basepri;
500 poperror(); /* file0 */
512 * At this point, the mmu contains info about the old address
513 * space and needs to be flushed
518 up->procctl = Proc_stopme;
519 return execregs(entry, ssize, nargs);
523 shargs(char *s, int n, char **ap)
528 n -= 2; /* skip #! */
529 for(i=0; s[i]!='\n'; i++)
536 while(*s==' ' || *s=='\t')
543 while(*s && *s!=' ' && *s!='\t')
567 if (up->edf && (up->edf->flags & Admitted))
575 tsleep(&up->sleep, return0, 0, n);
582 return procalarm(arg[0]);
589 char *inval = "invalid exit string";
592 status = (char*)arg[0];
597 validaddr((ulong)status, 1, 0);
598 if(vmemchr(status, 0, ERRMAX) == 0){
599 memmove(buf, status, ERRMAX);
608 return 0; /* not reached */
621 validaddr(arg[0], sizeof(OWaitmsg), 1);
625 ow = (OWaitmsg*)arg[0];
626 readnum(0, ow->pid, NUMSIZE, w.pid, NUMSIZE);
627 readnum(0, ow->time+TUser*NUMSIZE, NUMSIZE, w.time[TUser], NUMSIZE);
628 readnum(0, ow->time+TSys*NUMSIZE, NUMSIZE, w.time[TSys], NUMSIZE);
629 readnum(0, ow->time+TReal*NUMSIZE, NUMSIZE, w.time[TReal], NUMSIZE);
630 strncpy(ow->msg, w.msg, sizeof(ow->msg)-1);
631 ow->msg[sizeof(ow->msg)-1] = '\0';
645 validaddr(arg[0], n, 1);
649 i = snprint((char*)arg[0], n, "%d %lud %lud %lud %q",
651 w.time[TUser], w.time[TSys], w.time[TReal],
658 werrstr(char *fmt, ...)
666 vseprint(up->syserrstr, up->syserrstr+ERRMAX, fmt, va);
671 generrstr(char *buf, uint nbuf)
677 validaddr((ulong)buf, nbuf, 1);
678 if(nbuf > sizeof tmp)
680 memmove(tmp, buf, nbuf);
682 /* make sure it's NUL-terminated */
684 memmove(buf, up->syserrstr, nbuf);
686 memmove(up->syserrstr, tmp, nbuf);
691 syserrstr(ulong *arg)
693 return generrstr((char*)arg[0], arg[1]);
696 /* compatibility for old binaries */
698 sys_errstr(ulong *arg)
700 return generrstr((char*)arg[0], 64);
704 sysnotify(ulong *arg)
707 validaddr(arg[0], sizeof(ulong), 0);
708 up->notify = (int(*)(void*, char*))(arg[0]);
715 if(arg[0]!=NRSTR && !up->notified)
721 syssegbrk(ulong *arg)
728 for(i = 0; i < NSEG; i++) {
730 if(s == 0 || addr < s->base || addr >= s->top)
732 switch(s->type&SG_TYPE) {
738 return ibrk(arg[1], i);
743 return 0; /* not reached */
747 syssegattach(ulong *arg)
749 return segattach(up, arg[0], (char*)arg[1], arg[2], arg[3]);
753 syssegdetach(ulong *arg)
761 qunlock(&up->seglock);
767 for(i = 0; i < NSEG; i++)
770 if((addr >= s->base && addr < s->top) ||
771 (s->top == s->base && addr == s->base))
780 * Check we are not detaching the initial stack segment.
782 if(s == up->seg[SSEG]){
789 qunlock(&up->seglock);
792 /* Ensure we flush any entries from the lost segment */
798 syssegfree(ulong *arg)
804 s = seg(up, from, 1);
807 to = (from + arg[1]) & ~(BY2PG-1);
808 from = PGROUND(from);
815 mfreeseg(s, from, (to - from) / BY2PG);
822 /* For binary compatibility */
826 return ibrk(arg[0], BSEG);
830 sysrendezvous(ulong *arg)
836 l = &REND(up->rgrp, tag);
839 for(p = *l; p; p = p->rendhash) {
840 if(p->rendtag == tag) {
853 /* Going to sleep here */
855 up->rendval = arg[1];
858 up->state = Rendezvous;
867 * The implementation of semaphores is complicated by needing
868 * to avoid rescheduling in syssemrelease, so that it is safe
869 * to call from real-time processes. This means syssemrelease
870 * cannot acquire any qlocks, only spin locks.
872 * Semacquire and semrelease must both manipulate the semaphore
873 * wait list. Lock-free linked lists only exist in theory, not
874 * in practice, so the wait list is protected by a spin lock.
876 * The semaphore value *addr is stored in user memory, so it
877 * cannot be read or written while holding spin locks.
879 * Thus, we can access the list only when holding the lock, and
880 * we can access the semaphore only when not holding the lock.
881 * This makes things interesting. Note that sleep's condition function
882 * is called while holding two locks - r and up->rlock - so it cannot
883 * access the semaphore value either.
885 * An acquirer announces its intention to try for the semaphore
886 * by putting a Sema structure onto the wait list and then
887 * setting Sema.waiting. After one last check of semaphore,
888 * the acquirer sleeps until Sema.waiting==0. A releaser of n
889 * must wake up n acquirers who have Sema.waiting set. It does
890 * this by clearing Sema.waiting and then calling wakeup.
892 * There are three interesting races here.
894 * The first is that in this particular sleep/wakeup usage, a single
895 * wakeup can rouse a process from two consecutive sleeps!
898 * (a) set Sema.waiting = 1
900 * (b) set Sema.waiting = 0
901 * (a) check Sema.waiting inside sleep, return w/o sleeping
902 * (a) try for semaphore, fail
903 * (a) set Sema.waiting = 1
908 * This is okay - semacquire will just go around the loop
909 * again. It does mean that at the top of the for(;;) loop in
910 * semacquire, phore.waiting might already be set to 1.
912 * The second is that a releaser might wake an acquirer who is
913 * interrupted before he can acquire the lock. Since
914 * release(n) issues only n wakeup calls -- only n can be used
915 * anyway -- if the interrupted process is not going to use his
916 * wakeup call he must pass it on to another acquirer.
918 * The third race is similar to the second but more subtle. An
919 * acquirer sets waiting=1 and then does a final canacquire()
920 * before going to sleep. The opposite order would result in
921 * missing wakeups that happen between canacquire and
922 * waiting=1. (In fact, the whole point of Sema.waiting is to
923 * avoid missing wakeups between canacquire() and sleep().) But
924 * there can be spurious wakeups between a successful
925 * canacquire() and the following semdequeue(). This wakeup is
926 * not useful to the acquirer, since he has already acquired
927 * the semaphore. Like in the previous case, though, the
928 * acquirer must pass the wakeup call along.
930 * This is all rather subtle. The code below has been verified
931 * with the spin model /sys/src/9/port/semaphore.p. The
932 * original code anticipated the second race but not the first
933 * or third, which were caught only with spin. The first race
934 * is mentioned in /sys/doc/sleep.ps, but I'd forgotten about it.
935 * It was lucky that my abstract model of sleep/wakeup still managed
936 * to preserve that behavior.
938 * I remain slightly concerned about memory coherence
939 * outside of locks. The spin model does not take
940 * queued processor writes into account so we have to
941 * think hard. The only variables accessed outside locks
942 * are the semaphore value itself and the boolean flag
943 * Sema.waiting. The value is only accessed with cmpswap,
944 * whose job description includes doing the right thing as
945 * far as memory coherence across processors. That leaves
946 * Sema.waiting. To handle it, we call coherence() before each
947 * read and after each write. - rsc
950 /* Add semaphore p with addr a to list in seg. */
952 semqueue(Segment *s, long *a, Sema *p)
954 memset(p, 0, sizeof *p);
956 lock(&s->sema); /* uses s->sema.Rendez.Lock, but no one else is */
958 p->prev = s->sema.prev;
964 /* Remove semaphore p from list in seg. */
966 semdequeue(Segment *s, Sema *p)
969 p->next->prev = p->prev;
970 p->prev->next = p->next;
974 /* Wake up n waiters with addr a on list in seg. */
976 semwakeup(Segment *s, long *a, long n)
981 for(p=s->sema.next; p!=&s->sema && n>0; p=p->next){
982 if(p->addr == a && p->waiting){
992 /* Add delta to semaphore and wake up waiters as appropriate. */
994 semrelease(Segment *s, long *addr, long delta)
1000 while(!cmpswap(addr, value, value+delta));
1001 semwakeup(s, addr, delta);
1005 /* Try to acquire semaphore using compare-and-swap */
1007 canacquire(long *addr)
1011 while((value=*addr) > 0)
1012 if(cmpswap(addr, value, value-1))
1017 /* Should we wake up? */
1022 return !((Sema*)p)->waiting;
1025 /* Acquire semaphore (subtract 1). */
1027 semacquire(Segment *s, long *addr, int block)
1032 if(canacquire(addr))
1038 semqueue(s, addr, &phore);
1042 if(canacquire(addr)){
1048 sleep(&phore, semawoke, &phore);
1051 semdequeue(s, &phore);
1052 coherence(); /* not strictly necessary due to lock in semdequeue */
1054 semwakeup(s, addr, 1);
1060 /* Acquire semaphore or time-out */
1062 tsemacquire(Segment *s, long *addr, ulong ms)
1064 int acquired, timedout;
1068 if(canacquire(addr))
1072 acquired = timedout = 0;
1073 semqueue(s, addr, &phore);
1077 if(canacquire(addr)){
1084 tsleep(&phore, semawoke, &phore, ms);
1085 elms = TK2MS(m->ticks - t);
1093 semdequeue(s, &phore);
1094 coherence(); /* not strictly necessary due to lock in semdequeue */
1096 semwakeup(s, addr, 1);
1105 syssemacquire(ulong *arg)
1111 validaddr(arg[0], sizeof(long), 1);
1113 addr = (long*)arg[0];
1116 if((s = seg(up, (ulong)addr, 0)) == nil)
1120 return semacquire(s, addr, block);
1124 systsemacquire(ulong *arg)
1130 validaddr(arg[0], sizeof(long), 1);
1132 addr = (long*)arg[0];
1135 if((s = seg(up, (ulong)addr, 0)) == nil)
1139 return tsemacquire(s, addr, ms);
1143 syssemrelease(ulong *arg)
1148 validaddr(arg[0], sizeof(long), 1);
1150 addr = (long*)arg[0];
1153 if((s = seg(up, (ulong)addr, 0)) == nil)
1155 /* delta == 0 is a no-op, not a release */
1156 if(delta < 0 || *addr < 0)
1158 return semrelease(s, addr, delta);