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;
166 /* Craft a return frame which will cause the child to pop out of
167 * the scheduler in user mode with the return register zero
169 forkchild(p, up->dbgreg);
172 if((flag&RFNOWAIT) == 0){
173 p->parentpid = up->pid;
178 if((flag&RFNOTEG) == 0)
179 p->noteid = up->noteid;
181 p->fpstate = up->fpstate;
183 memset(p->time, 0, sizeof(p->time));
184 p->time[TReal] = MACHP(0)->ticks;
186 kstrdup(&p->text, up->text);
187 kstrdup(&p->user, up->user);
192 * since the bss/data segments are now shareable,
193 * any mmu info about this process is now stale
194 * (i.e. has bad properties) and has to be discarded.
197 p->basepri = up->basepri;
198 p->priority = up->basepri;
199 p->fixedpri = up->fixedpri;
203 procwired(p, wm->machno);
215 return (cp[0]<<24) | (cp[1]<<16) | (cp[2]<<8) | cp[3];
226 char *a, *charp, *args, *file, *file0;
227 char *progarg[sizeof(Exec)/2+1], *elem, progelem[64];
228 ulong ssize, spage, nargs, nbytes, n, bssend;
231 char line[sizeof(Exec)];
234 ulong magic, text, entry, data, bss;
240 validaddr(arg[0], 1, 0);
241 file0 = validnamedup((char*)arg[0], 1);
245 /* Disaster after commit */
247 pexit(up->errstr, 1);
252 tc = namec(file, Aopen, OEXEC, 0);
258 kstrdup(&elem, up->genbuf);
260 n = devtab[tc->type]->read(tc, &exec, sizeof(Exec), 0);
263 magic = l2be(exec.magic);
264 text = l2be(exec.text);
265 entry = l2be(exec.entry);
266 if(n==sizeof(Exec) && (magic == AOUT_MAGIC)){
267 if(text >= USTKTOP-UTZERO
268 || entry < UTZERO+sizeof(Exec)
269 || entry >= UTZERO+sizeof(Exec)+text)
271 break; /* for binary */
275 * Process #! /bin/sh args ...
277 memmove(line, &exec, sizeof(Exec));
278 if(indir || line[0]!='#' || line[1]!='!')
280 n = shargs(line, n, progarg);
285 * First arg becomes complete file name
289 validaddr(arg[1], BY2WD, 1);
292 if(strlen(elem) >= sizeof progelem)
294 strcpy(progelem, elem);
295 progarg[0] = progelem;
300 data = l2be(exec.data);
301 bss = l2be(exec.bss);
302 t = (UTZERO+sizeof(Exec)+text+(BY2PG-1)) & ~(BY2PG-1);
303 d = (t + data + (BY2PG-1)) & ~(BY2PG-1);
304 bssend = t + data + bss;
305 b = (bssend + (BY2PG-1)) & ~(BY2PG-1);
306 if(t >= KZERO || d >= KZERO || b >= KZERO)
310 * Args: pass 1: count
312 nbytes = sizeof(Tos); /* hole for profiling clock at top of stack (and more) */
318 nbytes += strlen(a) + 1;
323 argp = (char**)arg[1];
324 validaddr((ulong)argp, BY2WD, 0);
327 if(((ulong)argp&(BY2PG-1)) < BY2WD)
328 validaddr((ulong)argp, BY2WD, 0);
329 validaddr((ulong)a, 1, 0);
330 nbytes += ((char*)vmemchr(a, 0, 0x7FFFFFFF) - a) + 1;
333 ssize = BY2WD*(nargs+1) + ((nbytes+(BY2WD-1)) & ~(BY2WD-1));
336 * 8-byte align SP for those (e.g. sparc) that need it.
337 * execregs() will subtract another 4 bytes for argc.
341 spage = (ssize+(BY2PG-1)) >> PGSHIFT;
344 * Build the stack segment, putting it in kernel virtual for the moment
351 qunlock(&up->seglock);
354 up->seg[ESEG] = newseg(SG_STACK, TSTKTOP-USTKSIZE, USTKSIZE/BY2PG);
357 * Args: pass 2: assemble; the pages will be faulted in
359 tos = (Tos*)(TSTKTOP - sizeof(Tos));
360 tos->cyclefreq = m->cyclefreq;
365 argv = (char**)(TSTKTOP - ssize);
366 charp = (char*)(TSTKTOP - nbytes);
371 argp = (char**)arg[1];
373 for(i=0; i<nargs; i++){
374 if(indir && *argp==0) {
376 argp = (char**)arg[1];
378 *argv++ = charp + (USTKTOP-TSTKTOP);
379 n = strlen(*argp) + 1;
380 memmove(charp, *argp++, n);
384 file0 = nil; /* so waserror() won't free file0 */
389 elem = nil; /* so waserror() won't free elem */
392 /* copy args; easiest from new process's stack */
394 if(n > 128) /* don't waste too much space on huge arg lists */
399 up->args = smalloc(n);
400 memmove(up->args, args, n);
401 if(n>0 && up->args[n-1]!='\0'){
402 /* make sure last arg is NUL-terminated */
403 /* put NUL at UTF-8 character boundary */
405 if(fullrune(up->args+i, n-i))
418 * Special segments are maintained across exec
420 for(i = SSEG; i <= BSEG; i++) {
422 /* prevent a second free if we have an error */
425 for(i = BSEG+1; i < NSEG; i++) {
427 if(s != 0 && (s->type&SG_CEXEC)) {
437 for(i=0; i<=f->maxfd; i++)
440 /* Text. Shared. Attaches to cache image if possible */
441 /* attachimage returns a locked cache image */
442 img = attachimage(SG_TEXT|SG_RONLY, tc, UTZERO, (t-UTZERO)>>PGSHIFT);
447 ts->flen = sizeof(Exec)+text;
451 s = newseg(SG_DATA, t, (d-t)>>PGSHIFT);
454 /* Attached by hand */
457 s->fstart = ts->fstart+ts->flen;
460 /* BSS. Zero fill on demand */
461 up->seg[BSEG] = newseg(SG_BSS, d, (b-d)>>PGSHIFT);
468 s->base = USTKTOP-USTKSIZE;
470 relocateseg(s, USTKTOP-TSTKTOP);
472 qunlock(&up->seglock);
473 poperror(); /* seglock */
476 * '/' processes are higher priority (hack to make /ip more responsive).
478 if(devtab[tc->type]->dc == L'/')
479 up->basepri = PriRoot;
480 up->priority = up->basepri;
483 poperror(); /* elem */
494 * At this point, the mmu contains info about the old address
495 * space and needs to be flushed
500 up->procctl = Proc_stopme;
501 return execregs(entry, ssize, nargs);
505 shargs(char *s, int n, char **ap)
510 n -= 2; /* skip #! */
511 for(i=0; s[i]!='\n'; i++)
518 while(*s==' ' || *s=='\t')
525 while(*s && *s!=' ' && *s!='\t')
549 if (up->edf && (up->edf->flags & Admitted))
557 tsleep(&up->sleep, return0, 0, n);
564 return procalarm(arg[0]);
571 char *inval = "invalid exit string";
574 status = (char*)arg[0];
579 validaddr((ulong)status, 1, 0);
580 if(vmemchr(status, 0, ERRMAX) == 0){
581 memmove(buf, status, ERRMAX);
590 return 0; /* not reached */
603 validaddr(arg[0], sizeof(OWaitmsg), 1);
607 ow = (OWaitmsg*)arg[0];
608 readnum(0, ow->pid, NUMSIZE, w.pid, NUMSIZE);
609 readnum(0, ow->time+TUser*NUMSIZE, NUMSIZE, w.time[TUser], NUMSIZE);
610 readnum(0, ow->time+TSys*NUMSIZE, NUMSIZE, w.time[TSys], NUMSIZE);
611 readnum(0, ow->time+TReal*NUMSIZE, NUMSIZE, w.time[TReal], NUMSIZE);
612 strncpy(ow->msg, w.msg, sizeof(ow->msg)-1);
613 ow->msg[sizeof(ow->msg)-1] = '\0';
627 validaddr(arg[0], n, 1);
631 i = snprint((char*)arg[0], n, "%d %lud %lud %lud %q",
633 w.time[TUser], w.time[TSys], w.time[TReal],
640 werrstr(char *fmt, ...)
648 vseprint(up->syserrstr, up->syserrstr+ERRMAX, fmt, va);
653 generrstr(char *buf, uint nbuf)
659 validaddr((ulong)buf, nbuf, 1);
660 if(nbuf > sizeof tmp)
662 memmove(tmp, buf, nbuf);
664 /* make sure it's NUL-terminated */
666 memmove(buf, up->syserrstr, nbuf);
668 memmove(up->syserrstr, tmp, nbuf);
673 syserrstr(ulong *arg)
675 return generrstr((char*)arg[0], arg[1]);
678 /* compatibility for old binaries */
680 sys_errstr(ulong *arg)
682 return generrstr((char*)arg[0], 64);
686 sysnotify(ulong *arg)
689 validaddr(arg[0], sizeof(ulong), 0);
690 up->notify = (int(*)(void*, char*))(arg[0]);
697 if(arg[0]!=NRSTR && !up->notified)
703 syssegbrk(ulong *arg)
710 for(i = 0; i < NSEG; i++) {
712 if(s == 0 || addr < s->base || addr >= s->top)
714 switch(s->type&SG_TYPE) {
720 return ibrk(arg[1], i);
725 return 0; /* not reached */
729 syssegattach(ulong *arg)
731 return segattach(up, arg[0], (char*)arg[1], arg[2], arg[3]);
735 syssegdetach(ulong *arg)
743 qunlock(&up->seglock);
749 for(i = 0; i < NSEG; i++)
752 if((addr >= s->base && addr < s->top) ||
753 (s->top == s->base && addr == s->base))
762 * Check we are not detaching the initial stack segment.
764 if(s == up->seg[SSEG]){
771 qunlock(&up->seglock);
774 /* Ensure we flush any entries from the lost segment */
780 syssegfree(ulong *arg)
786 s = seg(up, from, 1);
789 to = (from + arg[1]) & ~(BY2PG-1);
790 from = PGROUND(from);
797 mfreeseg(s, from, (to - from) / BY2PG);
804 /* For binary compatibility */
808 return ibrk(arg[0], BSEG);
812 sysrendezvous(ulong *arg)
818 l = &REND(up->rgrp, tag);
821 for(p = *l; p; p = p->rendhash) {
822 if(p->rendtag == tag) {
835 /* Going to sleep here */
837 up->rendval = arg[1];
840 up->state = Rendezvous;
849 * The implementation of semaphores is complicated by needing
850 * to avoid rescheduling in syssemrelease, so that it is safe
851 * to call from real-time processes. This means syssemrelease
852 * cannot acquire any qlocks, only spin locks.
854 * Semacquire and semrelease must both manipulate the semaphore
855 * wait list. Lock-free linked lists only exist in theory, not
856 * in practice, so the wait list is protected by a spin lock.
858 * The semaphore value *addr is stored in user memory, so it
859 * cannot be read or written while holding spin locks.
861 * Thus, we can access the list only when holding the lock, and
862 * we can access the semaphore only when not holding the lock.
863 * This makes things interesting. Note that sleep's condition function
864 * is called while holding two locks - r and up->rlock - so it cannot
865 * access the semaphore value either.
867 * An acquirer announces its intention to try for the semaphore
868 * by putting a Sema structure onto the wait list and then
869 * setting Sema.waiting. After one last check of semaphore,
870 * the acquirer sleeps until Sema.waiting==0. A releaser of n
871 * must wake up n acquirers who have Sema.waiting set. It does
872 * this by clearing Sema.waiting and then calling wakeup.
874 * There are three interesting races here.
876 * The first is that in this particular sleep/wakeup usage, a single
877 * wakeup can rouse a process from two consecutive sleeps!
880 * (a) set Sema.waiting = 1
882 * (b) set Sema.waiting = 0
883 * (a) check Sema.waiting inside sleep, return w/o sleeping
884 * (a) try for semaphore, fail
885 * (a) set Sema.waiting = 1
890 * This is okay - semacquire will just go around the loop
891 * again. It does mean that at the top of the for(;;) loop in
892 * semacquire, phore.waiting might already be set to 1.
894 * The second is that a releaser might wake an acquirer who is
895 * interrupted before he can acquire the lock. Since
896 * release(n) issues only n wakeup calls -- only n can be used
897 * anyway -- if the interrupted process is not going to use his
898 * wakeup call he must pass it on to another acquirer.
900 * The third race is similar to the second but more subtle. An
901 * acquirer sets waiting=1 and then does a final canacquire()
902 * before going to sleep. The opposite order would result in
903 * missing wakeups that happen between canacquire and
904 * waiting=1. (In fact, the whole point of Sema.waiting is to
905 * avoid missing wakeups between canacquire() and sleep().) But
906 * there can be spurious wakeups between a successful
907 * canacquire() and the following semdequeue(). This wakeup is
908 * not useful to the acquirer, since he has already acquired
909 * the semaphore. Like in the previous case, though, the
910 * acquirer must pass the wakeup call along.
912 * This is all rather subtle. The code below has been verified
913 * with the spin model /sys/src/9/port/semaphore.p. The
914 * original code anticipated the second race but not the first
915 * or third, which were caught only with spin. The first race
916 * is mentioned in /sys/doc/sleep.ps, but I'd forgotten about it.
917 * It was lucky that my abstract model of sleep/wakeup still managed
918 * to preserve that behavior.
920 * I remain slightly concerned about memory coherence
921 * outside of locks. The spin model does not take
922 * queued processor writes into account so we have to
923 * think hard. The only variables accessed outside locks
924 * are the semaphore value itself and the boolean flag
925 * Sema.waiting. The value is only accessed with cmpswap,
926 * whose job description includes doing the right thing as
927 * far as memory coherence across processors. That leaves
928 * Sema.waiting. To handle it, we call coherence() before each
929 * read and after each write. - rsc
932 /* Add semaphore p with addr a to list in seg. */
934 semqueue(Segment *s, long *a, Sema *p)
936 memset(p, 0, sizeof *p);
938 lock(&s->sema); /* uses s->sema.Rendez.Lock, but no one else is */
940 p->prev = s->sema.prev;
946 /* Remove semaphore p from list in seg. */
948 semdequeue(Segment *s, Sema *p)
951 p->next->prev = p->prev;
952 p->prev->next = p->next;
956 /* Wake up n waiters with addr a on list in seg. */
958 semwakeup(Segment *s, long *a, long n)
963 for(p=s->sema.next; p!=&s->sema && n>0; p=p->next){
964 if(p->addr == a && p->waiting){
974 /* Add delta to semaphore and wake up waiters as appropriate. */
976 semrelease(Segment *s, long *addr, long delta)
982 while(!cmpswap(addr, value, value+delta));
983 semwakeup(s, addr, delta);
987 /* Try to acquire semaphore using compare-and-swap */
989 canacquire(long *addr)
993 while((value=*addr) > 0)
994 if(cmpswap(addr, value, value-1))
999 /* Should we wake up? */
1004 return !((Sema*)p)->waiting;
1007 /* Acquire semaphore (subtract 1). */
1009 semacquire(Segment *s, long *addr, int block)
1014 if(canacquire(addr))
1020 semqueue(s, addr, &phore);
1024 if(canacquire(addr)){
1030 sleep(&phore, semawoke, &phore);
1033 semdequeue(s, &phore);
1034 coherence(); /* not strictly necessary due to lock in semdequeue */
1036 semwakeup(s, addr, 1);
1042 /* Acquire semaphore or time-out */
1044 tsemacquire(Segment *s, long *addr, ulong ms)
1046 int acquired, timedout;
1050 if(canacquire(addr))
1054 acquired = timedout = 0;
1055 semqueue(s, addr, &phore);
1059 if(canacquire(addr)){
1066 tsleep(&phore, semawoke, &phore, ms);
1067 elms = TK2MS(m->ticks - t);
1075 semdequeue(s, &phore);
1076 coherence(); /* not strictly necessary due to lock in semdequeue */
1078 semwakeup(s, addr, 1);
1087 syssemacquire(ulong *arg)
1093 validaddr(arg[0], sizeof(long), 1);
1095 addr = (long*)arg[0];
1098 if((s = seg(up, (ulong)addr, 0)) == nil)
1102 return semacquire(s, addr, block);
1106 systsemacquire(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 tsemacquire(s, addr, ms);
1125 syssemrelease(ulong *arg)
1130 validaddr(arg[0], sizeof(long), 1);
1132 addr = (long*)arg[0];
1135 if((s = seg(up, (ulong)addr, 0)) == nil)
1137 if(delta < 0 || *addr < 0)
1139 return semrelease(s, addr, arg[1]);