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);
33 sysrfork(va_list list)
44 flag = va_arg(list, ulong);
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];
237 sysexec(va_list list)
242 char **argv, **argp, **argp0;
243 char *a, *charp, *args, *file, *file0;
244 char *progarg[sizeof(Exec)/2+1], *elem, progelem[64];
245 ulong magic, ssize, nargs, nbytes, n;
246 uintptr t, d, b, entry, bssend, text, data, bss, tstk, align;
249 char line[sizeof(Exec)];
255 file0 = va_arg(list, char*);
256 validaddr((uintptr)file0, 1, 0);
257 argp0 = va_arg(list, char**);
258 file0 = validnamedup(file0, 1);
263 /* Disaster after commit */
265 pexit(up->errstr, 1);
272 tc = namec(file, Aopen, OEXEC, 0);
278 kstrdup(&elem, up->genbuf);
280 n = devtab[tc->type]->read(tc, &exec, sizeof(Exec), 0);
283 magic = l2be(exec.magic);
284 text = l2be(exec.text);
285 entry = l2be(exec.entry);
286 if(n==sizeof(Exec) && (magic == AOUT_MAGIC)){
287 if(magic == S_MAGIC){
289 align = 0x200000ull; /* 2MB segment alignment for amd64 */
291 if(text >= (USTKTOP-USTKSIZE)-(UTZERO+sizeof(Exec))
292 || entry < UTZERO+sizeof(Exec)
293 || entry >= UTZERO+sizeof(Exec)+text)
295 break; /* for binary */
299 * Process #! /bin/sh args ...
301 memmove(line, &exec, sizeof(Exec));
302 if(indir || line[0]!='#' || line[1]!='!')
304 n = shargs(line, n, progarg);
309 * First arg becomes complete file name
315 if(strlen(elem) >= sizeof progelem)
317 strcpy(progelem, elem);
318 progarg[0] = progelem;
323 data = l2be(exec.data);
324 bss = l2be(exec.bss);
326 t = (UTZERO+sizeof(Exec)+text+align) & ~align;
328 d = (t + data + align) & ~align;
329 bssend = t + data + bss;
330 b = (bssend + align) & ~align;
331 if(t >= (USTKTOP-USTKSIZE) || d >= (USTKTOP-USTKSIZE) || b >= (USTKTOP-USTKSIZE))
335 * Args: pass 1: count
337 nbytes = sizeof(Tos); /* hole for profiling clock at top of stack (and more) */
343 nbytes += strlen(a) + 1;
348 evenaddr((uintptr)argp);
349 validaddr((uintptr)argp, BY2WD, 0);
352 if(((uintptr)argp&(BY2PG-1)) < BY2WD)
353 validaddr((uintptr)argp, BY2WD, 0);
354 validaddr((uintptr)a, 1, 0);
355 nbytes += ((char*)vmemchr(a, 0, 0x7FFFFFFF) - a) + 1;
358 ssize = BY2WD*(nargs+1) + ((nbytes+(BY2WD-1)) & ~(BY2WD-1));
361 * 8-byte align SP for those (e.g. sparc) that need it.
362 * execregs() will subtract another 4 bytes for argc.
364 if(BY2WD == 4 && (ssize+4) & 7)
367 if(PGROUND(ssize) >= USTKSIZE)
371 * Build the stack segment, putting it in kernel virtual for the moment
375 qunlock(&up->seglock);
384 } while((s = isoverlap(up, tstk-USTKSIZE, USTKSIZE)) != nil);
385 up->seg[ESEG] = newseg(SG_STACK, tstk-USTKSIZE, USTKSIZE/BY2PG);
388 * Args: pass 2: assemble; the pages will be faulted in
390 tos = (Tos*)(tstk - sizeof(Tos));
391 tos->cyclefreq = m->cyclefreq;
396 argv = (char**)(tstk - ssize);
397 charp = (char*)(tstk - nbytes);
404 for(i=0; i<nargs; i++){
405 if(indir && *argp==0) {
409 *argv++ = charp + (USTKTOP-tstk);
410 n = strlen(*argp) + 1;
411 memmove(charp, *argp++, n);
415 /* copy args; easiest from new process's stack */
417 if(n > 128) /* don't waste too much space on huge arg lists */
421 if(n>0 && args[n-1]!='\0'){
422 /* make sure last arg is NUL-terminated */
423 /* put NUL at UTF-8 character boundary */
425 if(fullrune(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 */
519 * At this point, the mmu contains info about the old address
520 * space and needs to be flushed
525 up->procctl = Proc_stopme;
526 return execregs(entry, ssize, nargs);
530 shargs(char *s, int n, char **ap)
535 n -= 2; /* skip #! */
536 for(i=0; s[i]!='\n'; i++)
543 while(*s==' ' || *s=='\t')
550 while(*s && *s!=' ' && *s!='\t')
567 syssleep(va_list list)
571 ms = va_arg(list, long);
573 if (up->edf && (up->edf->flags & Admitted))
580 tsleep(&up->sleep, return0, 0, ms);
586 sysalarm(va_list list)
588 return procalarm(va_arg(list, ulong));
593 sysexits(va_list list)
596 char *inval = "invalid exit string";
599 status = va_arg(list, char*);
604 validaddr((uintptr)status, 1, 0);
605 if(vmemchr(status, 0, ERRMAX) == 0){
606 memmove(buf, status, ERRMAX);
615 return 0; /* not reached */
619 sys_wait(va_list list)
625 ow = va_arg(list, OWaitmsg*);
629 validaddr((uintptr)ow, sizeof(OWaitmsg), 1);
630 evenaddr((uintptr)ow);
634 readnum(0, ow->pid, NUMSIZE, w.pid, NUMSIZE);
635 readnum(0, ow->time+TUser*NUMSIZE, NUMSIZE, w.time[TUser], NUMSIZE);
636 readnum(0, ow->time+TSys*NUMSIZE, NUMSIZE, w.time[TSys], NUMSIZE);
637 readnum(0, ow->time+TReal*NUMSIZE, NUMSIZE, w.time[TReal], NUMSIZE);
638 strncpy(ow->msg, w.msg, sizeof(ow->msg)-1);
639 ow->msg[sizeof(ow->msg)-1] = '\0';
645 sysawait(va_list list)
651 p = va_arg(list, char*);
652 n = va_arg(list, uint);
653 validaddr((uintptr)p, n, 1);
655 return (uintptr)snprint(p, n, "%d %lud %lud %lud %q",
657 w.time[TUser], w.time[TSys], w.time[TReal],
662 werrstr(char *fmt, ...)
670 vseprint(up->syserrstr, up->syserrstr+ERRMAX, fmt, va);
675 generrstr(char *buf, uint nbuf)
681 validaddr((uintptr)buf, nbuf, 1);
682 if(nbuf > sizeof tmp)
684 memmove(tmp, buf, nbuf);
686 /* make sure it's NUL-terminated */
688 memmove(buf, up->syserrstr, nbuf);
690 memmove(up->syserrstr, tmp, nbuf);
695 syserrstr(va_list list)
700 buf = va_arg(list, char*);
701 len = va_arg(list, uint);
702 return (uintptr)generrstr(buf, len);
705 /* compatibility for old binaries */
707 sys_errstr(va_list list)
709 return (uintptr)generrstr(va_arg(list, char*), 64);
713 sysnotify(va_list list)
715 int (*f)(void*, char*);
716 f = va_arg(list, void*);
718 validaddr((uintptr)f, sizeof(void*), 0);
724 sysnoted(va_list list)
726 if(va_arg(list, int) !=NRSTR && !up->notified)
732 syssegbrk(va_list list)
738 addr = va_arg(list, uintptr);
739 for(i = 0; i < NSEG; i++) {
741 if(s == 0 || addr < s->base || addr >= s->top)
743 switch(s->type&SG_TYPE) {
749 return (uintptr)ibrk(va_arg(list, uintptr), i);
753 return 0; /* not reached */
757 syssegattach(va_list list)
764 attr = va_arg(list, ulong);
765 name = va_arg(list, char*);
766 va = va_arg(list, uintptr);
767 len = va_arg(list, ulong);
768 return segattach(up, attr, name, va, len);
772 syssegdetach(va_list list)
778 addr = va_arg(list, uintptr);
782 qunlock(&up->seglock);
787 for(i = 0; i < NSEG; i++)
790 if((addr >= s->base && addr < s->top) ||
791 (s->top == s->base && addr == s->base))
800 * Check we are not detaching the initial stack segment.
802 if(s == up->seg[SSEG]){
809 qunlock(&up->seglock);
812 /* Ensure we flush any entries from the lost segment */
818 syssegfree(va_list list)
823 from = va_arg(list, uintptr);
824 s = seg(up, from, 1);
827 to = va_arg(list, ulong);
830 from = PGROUND(from);
837 mfreeseg(s, from, (to - from) / BY2PG);
843 /* For binary compatibility */
845 sysbrk_(va_list list)
847 return (uintptr)ibrk(va_arg(list, uintptr), BSEG);
851 sysrendezvous(va_list list)
853 uintptr tag, val, new;
856 tag = va_arg(list, uintptr);
857 new = va_arg(list, uintptr);
858 l = &REND(up->rgrp, tag);
861 for(p = *l; p; p = p->rendhash) {
862 if(p->rendtag == tag) {
875 /* Going to sleep here */
880 up->state = Rendezvous;
889 * The implementation of semaphores is complicated by needing
890 * to avoid rescheduling in syssemrelease, so that it is safe
891 * to call from real-time processes. This means syssemrelease
892 * cannot acquire any qlocks, only spin locks.
894 * Semacquire and semrelease must both manipulate the semaphore
895 * wait list. Lock-free linked lists only exist in theory, not
896 * in practice, so the wait list is protected by a spin lock.
898 * The semaphore value *addr is stored in user memory, so it
899 * cannot be read or written while holding spin locks.
901 * Thus, we can access the list only when holding the lock, and
902 * we can access the semaphore only when not holding the lock.
903 * This makes things interesting. Note that sleep's condition function
904 * is called while holding two locks - r and up->rlock - so it cannot
905 * access the semaphore value either.
907 * An acquirer announces its intention to try for the semaphore
908 * by putting a Sema structure onto the wait list and then
909 * setting Sema.waiting. After one last check of semaphore,
910 * the acquirer sleeps until Sema.waiting==0. A releaser of n
911 * must wake up n acquirers who have Sema.waiting set. It does
912 * this by clearing Sema.waiting and then calling wakeup.
914 * There are three interesting races here.
916 * The first is that in this particular sleep/wakeup usage, a single
917 * wakeup can rouse a process from two consecutive sleeps!
920 * (a) set Sema.waiting = 1
922 * (b) set Sema.waiting = 0
923 * (a) check Sema.waiting inside sleep, return w/o sleeping
924 * (a) try for semaphore, fail
925 * (a) set Sema.waiting = 1
930 * This is okay - semacquire will just go around the loop
931 * again. It does mean that at the top of the for(;;) loop in
932 * semacquire, phore.waiting might already be set to 1.
934 * The second is that a releaser might wake an acquirer who is
935 * interrupted before he can acquire the lock. Since
936 * release(n) issues only n wakeup calls -- only n can be used
937 * anyway -- if the interrupted process is not going to use his
938 * wakeup call he must pass it on to another acquirer.
940 * The third race is similar to the second but more subtle. An
941 * acquirer sets waiting=1 and then does a final canacquire()
942 * before going to sleep. The opposite order would result in
943 * missing wakeups that happen between canacquire and
944 * waiting=1. (In fact, the whole point of Sema.waiting is to
945 * avoid missing wakeups between canacquire() and sleep().) But
946 * there can be spurious wakeups between a successful
947 * canacquire() and the following semdequeue(). This wakeup is
948 * not useful to the acquirer, since he has already acquired
949 * the semaphore. Like in the previous case, though, the
950 * acquirer must pass the wakeup call along.
952 * This is all rather subtle. The code below has been verified
953 * with the spin model /sys/src/9/port/semaphore.p. The
954 * original code anticipated the second race but not the first
955 * or third, which were caught only with spin. The first race
956 * is mentioned in /sys/doc/sleep.ps, but I'd forgotten about it.
957 * It was lucky that my abstract model of sleep/wakeup still managed
958 * to preserve that behavior.
960 * I remain slightly concerned about memory coherence
961 * outside of locks. The spin model does not take
962 * queued processor writes into account so we have to
963 * think hard. The only variables accessed outside locks
964 * are the semaphore value itself and the boolean flag
965 * Sema.waiting. The value is only accessed with cmpswap,
966 * whose job description includes doing the right thing as
967 * far as memory coherence across processors. That leaves
968 * Sema.waiting. To handle it, we call coherence() before each
969 * read and after each write. - rsc
972 /* Add semaphore p with addr a to list in seg. */
974 semqueue(Segment *s, long *a, Sema *p)
976 memset(p, 0, sizeof *p);
978 lock(&s->sema); /* uses s->sema.Rendez.Lock, but no one else is */
980 p->prev = s->sema.prev;
986 /* Remove semaphore p from list in seg. */
988 semdequeue(Segment *s, Sema *p)
991 p->next->prev = p->prev;
992 p->prev->next = p->next;
996 /* Wake up n waiters with addr a on list in seg. */
998 semwakeup(Segment *s, long *a, long n)
1003 for(p=s->sema.next; p!=&s->sema && n>0; p=p->next){
1004 if(p->addr == a && p->waiting){
1014 /* Add delta to semaphore and wake up waiters as appropriate. */
1016 semrelease(Segment *s, long *addr, long delta)
1022 while(!cmpswap(addr, value, value+delta));
1023 semwakeup(s, addr, delta);
1027 /* Try to acquire semaphore using compare-and-swap */
1029 canacquire(long *addr)
1033 while((value=*addr) > 0)
1034 if(cmpswap(addr, value, value-1))
1039 /* Should we wake up? */
1044 return !((Sema*)p)->waiting;
1047 /* Acquire semaphore (subtract 1). */
1049 semacquire(Segment *s, long *addr, int block)
1054 if(canacquire(addr))
1060 semqueue(s, addr, &phore);
1064 if(canacquire(addr)){
1070 sleep(&phore, semawoke, &phore);
1073 semdequeue(s, &phore);
1074 coherence(); /* not strictly necessary due to lock in semdequeue */
1076 semwakeup(s, addr, 1);
1082 /* Acquire semaphore or time-out */
1084 tsemacquire(Segment *s, long *addr, ulong ms)
1086 int acquired, timedout;
1090 if(canacquire(addr))
1094 acquired = timedout = 0;
1095 semqueue(s, addr, &phore);
1099 if(canacquire(addr)){
1106 tsleep(&phore, semawoke, &phore, ms);
1107 elms = TK2MS(m->ticks - t);
1115 semdequeue(s, &phore);
1116 coherence(); /* not strictly necessary due to lock in semdequeue */
1118 semwakeup(s, addr, 1);
1127 syssemacquire(va_list list)
1133 addr = va_arg(list, long*);
1134 block = va_arg(list, int);
1135 evenaddr((uintptr)addr);
1136 s = seg(up, (uintptr)addr, 0);
1137 if(s == nil || (s->type&SG_RONLY) != 0 || (uintptr)addr+sizeof(long) > s->top){
1138 validaddr((uintptr)addr, sizeof(long), 1);
1143 return (uintptr)semacquire(s, addr, block);
1147 systsemacquire(va_list list)
1153 addr = va_arg(list, long*);
1154 ms = va_arg(list, ulong);
1155 evenaddr((uintptr)addr);
1156 s = seg(up, (uintptr)addr, 0);
1157 if(s == nil || (s->type&SG_RONLY) != 0 || (uintptr)addr+sizeof(long) > s->top){
1158 validaddr((uintptr)addr, sizeof(long), 1);
1163 return (uintptr)tsemacquire(s, addr, ms);
1167 syssemrelease(va_list list)
1172 addr = va_arg(list, long*);
1173 delta = va_arg(list, long);
1174 evenaddr((uintptr)addr);
1175 s = seg(up, (uintptr)addr, 0);
1176 if(s == nil || (s->type&SG_RONLY) != 0 || (uintptr)addr+sizeof(long) > s->top){
1177 validaddr((uintptr)addr, sizeof(long), 1);
1180 /* delta == 0 is a no-op, not a release */
1181 if(delta < 0 || *addr < 0)
1183 return (uintptr)semrelease(s, addr, delta);