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 = incref(¬eidalloc);
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 up->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 p->parentpid = up->pid;
180 if((flag&RFNOTEG) == 0)
181 p->noteid = up->noteid;
183 p->fpstate = up->fpstate;
185 memset(p->time, 0, sizeof(p->time));
186 p->time[TReal] = MACHP(0)->ticks;
188 kstrdup(&p->text, up->text);
189 kstrdup(&p->user, up->user);
194 * since the bss/data segments are now shareable,
195 * any mmu info about this process is now stale
196 * (i.e. has bad properties) and has to be discarded.
199 p->basepri = up->basepri;
200 p->priority = up->basepri;
201 p->fixedpri = up->fixedpri;
205 procwired(p, wm->machno);
217 return (cp[0]<<24) | (cp[1]<<16) | (cp[2]<<8) | cp[3];
228 char *a, *charp, *args, *file, *file0;
229 char *progarg[sizeof(Exec)/2+1], *elem, progelem[64];
230 ulong ssize, spage, nargs, nbytes, n, bssend;
233 char line[sizeof(Exec)];
236 ulong magic, text, entry, data, bss;
241 validaddr(arg[0], 1, 0);
242 file0 = validnamedup((char*)arg[0], 1);
250 tc = namec(file, Aopen, OEXEC, 0);
256 kstrdup(&elem, up->genbuf);
258 n = devtab[tc->type]->read(tc, &exec, sizeof(Exec), 0);
261 magic = l2be(exec.magic);
262 text = l2be(exec.text);
263 entry = l2be(exec.entry);
264 if(n==sizeof(Exec) && (magic == AOUT_MAGIC)){
265 if(text >= USTKTOP-UTZERO
266 || entry < UTZERO+sizeof(Exec)
267 || entry >= UTZERO+sizeof(Exec)+text)
269 break; /* for binary */
273 * Process #! /bin/sh args ...
275 memmove(line, &exec, sizeof(Exec));
276 if(indir || line[0]!='#' || line[1]!='!')
278 n = shargs(line, n, progarg);
283 * First arg becomes complete file name
287 validaddr(arg[1], BY2WD, 1);
290 if(strlen(elem) >= sizeof progelem)
292 strcpy(progelem, elem);
293 progarg[0] = progelem;
298 data = l2be(exec.data);
299 bss = l2be(exec.bss);
300 t = (UTZERO+sizeof(Exec)+text+(BY2PG-1)) & ~(BY2PG-1);
301 d = (t + data + (BY2PG-1)) & ~(BY2PG-1);
302 bssend = t + data + bss;
303 b = (bssend + (BY2PG-1)) & ~(BY2PG-1);
304 if(t >= KZERO || d >= KZERO || b >= KZERO)
308 * Args: pass 1: count
310 nbytes = sizeof(Tos); /* hole for profiling clock at top of stack (and more) */
316 nbytes += strlen(a) + 1;
321 argp = (char**)arg[1];
322 validaddr((ulong)argp, BY2WD, 0);
325 if(((ulong)argp&(BY2PG-1)) < BY2WD)
326 validaddr((ulong)argp, BY2WD, 0);
327 validaddr((ulong)a, 1, 0);
328 nbytes += ((char*)vmemchr(a, 0, 0x7FFFFFFF) - a) + 1;
331 ssize = BY2WD*(nargs+1) + ((nbytes+(BY2WD-1)) & ~(BY2WD-1));
334 * 8-byte align SP for those (e.g. sparc) that need it.
335 * execregs() will subtract another 4 bytes for argc.
339 spage = (ssize+(BY2PG-1)) >> PGSHIFT;
342 * Build the stack segment, putting it in kernel virtual for the moment
349 qunlock(&up->seglock);
352 up->seg[ESEG] = newseg(SG_STACK, TSTKTOP-USTKSIZE, USTKSIZE/BY2PG);
355 * Args: pass 2: assemble; the pages will be faulted in
357 tos = (Tos*)(TSTKTOP - sizeof(Tos));
358 tos->cyclefreq = m->cyclefreq;
359 cycles((uvlong*)&tos->pcycles);
360 tos->pcycles = -tos->pcycles;
361 tos->kcycles = tos->pcycles;
363 argv = (char**)(TSTKTOP - ssize);
364 charp = (char*)(TSTKTOP - nbytes);
369 argp = (char**)arg[1];
371 for(i=0; i<nargs; i++){
372 if(indir && *argp==0) {
374 argp = (char**)arg[1];
376 *argv++ = charp + (USTKTOP-TSTKTOP);
377 n = strlen(*argp) + 1;
378 memmove(charp, *argp++, n);
385 elem = nil; /* so waserror() won't free elem */
388 /* copy args; easiest from new process's stack */
390 if(n > 128) /* don't waste too much space on huge arg lists */
395 up->args = smalloc(n);
396 memmove(up->args, args, n);
397 if(n>0 && up->args[n-1]!='\0'){
398 /* make sure last arg is NUL-terminated */
399 /* put NUL at UTF-8 character boundary */
401 if(fullrune(up->args+i, n-i))
411 * Special segments are maintained across exec
413 for(i = SSEG; i <= BSEG; i++) {
415 /* prevent a second free if we have an error */
418 for(i = BSEG+1; i < NSEG; i++) {
420 if(s != 0 && (s->type&SG_CEXEC)) {
430 for(i=0; i<=f->maxfd; i++)
433 /* Text. Shared. Attaches to cache image if possible */
434 /* attachimage returns a locked cache image */
435 img = attachimage(SG_TEXT|SG_RONLY, tc, UTZERO, (t-UTZERO)>>PGSHIFT);
440 ts->flen = sizeof(Exec)+text;
444 s = newseg(SG_DATA, t, (d-t)>>PGSHIFT);
447 /* Attached by hand */
450 s->fstart = ts->fstart+ts->flen;
453 /* BSS. Zero fill on demand */
454 up->seg[BSEG] = newseg(SG_BSS, d, (b-d)>>PGSHIFT);
462 qunlock(&up->seglock);
463 poperror(); /* seglock */
464 poperror(); /* elem */
465 s->base = USTKTOP-USTKSIZE;
467 relocateseg(s, USTKTOP-TSTKTOP);
470 * '/' processes are higher priority (hack to make /ip more responsive).
472 if(devtab[tc->type]->dc == L'/')
473 up->basepri = PriRoot;
474 up->priority = up->basepri;
487 * At this point, the mmu contains info about the old address
488 * space and needs to be flushed
493 up->procctl = Proc_stopme;
494 return execregs(entry, ssize, nargs);
498 shargs(char *s, int n, char **ap)
503 n -= 2; /* skip #! */
504 for(i=0; s[i]!='\n'; i++)
511 while(*s==' ' || *s=='\t')
518 while(*s && *s!=' ' && *s!='\t')
542 if (up->edf && (up->edf->flags & Admitted))
550 tsleep(&up->sleep, return0, 0, n);
557 return procalarm(arg[0]);
564 char *inval = "invalid exit string";
567 status = (char*)arg[0];
572 validaddr((ulong)status, 1, 0);
573 if(vmemchr(status, 0, ERRMAX) == 0){
574 memmove(buf, status, ERRMAX);
583 return 0; /* not reached */
596 validaddr(arg[0], sizeof(OWaitmsg), 1);
600 ow = (OWaitmsg*)arg[0];
601 readnum(0, ow->pid, NUMSIZE, w.pid, NUMSIZE);
602 readnum(0, ow->time+TUser*NUMSIZE, NUMSIZE, w.time[TUser], NUMSIZE);
603 readnum(0, ow->time+TSys*NUMSIZE, NUMSIZE, w.time[TSys], NUMSIZE);
604 readnum(0, ow->time+TReal*NUMSIZE, NUMSIZE, w.time[TReal], NUMSIZE);
605 strncpy(ow->msg, w.msg, sizeof(ow->msg));
606 ow->msg[sizeof(ow->msg)-1] = '\0';
620 validaddr(arg[0], n, 1);
624 i = snprint((char*)arg[0], n, "%d %lud %lud %lud %q",
626 w.time[TUser], w.time[TSys], w.time[TReal],
633 werrstr(char *fmt, ...)
641 vseprint(up->syserrstr, up->syserrstr+ERRMAX, fmt, va);
646 generrstr(char *buf, uint nbuf)
652 validaddr((ulong)buf, nbuf, 1);
653 if(nbuf > sizeof tmp)
655 memmove(tmp, buf, nbuf);
657 /* make sure it's NUL-terminated */
659 memmove(buf, up->syserrstr, nbuf);
661 memmove(up->syserrstr, tmp, nbuf);
666 syserrstr(ulong *arg)
668 return generrstr((char*)arg[0], arg[1]);
671 /* compatibility for old binaries */
673 sys_errstr(ulong *arg)
675 return generrstr((char*)arg[0], 64);
679 sysnotify(ulong *arg)
682 validaddr(arg[0], sizeof(ulong), 0);
683 up->notify = (int(*)(void*, char*))(arg[0]);
690 if(arg[0]!=NRSTR && !up->notified)
696 syssegbrk(ulong *arg)
703 for(i = 0; i < NSEG; i++) {
705 if(s == 0 || addr < s->base || addr >= s->top)
707 switch(s->type&SG_TYPE) {
713 return ibrk(arg[1], i);
718 return 0; /* not reached */
722 syssegattach(ulong *arg)
724 return segattach(up, arg[0], (char*)arg[1], arg[2], arg[3]);
728 syssegdetach(ulong *arg)
736 qunlock(&up->seglock);
742 for(i = 0; i < NSEG; i++)
745 if((addr >= s->base && addr < s->top) ||
746 (s->top == s->base && addr == s->base))
755 * Check we are not detaching the initial stack segment.
757 if(s == up->seg[SSEG]){
764 qunlock(&up->seglock);
767 /* Ensure we flush any entries from the lost segment */
773 syssegfree(ulong *arg)
779 s = seg(up, from, 1);
782 to = (from + arg[1]) & ~(BY2PG-1);
783 from = PGROUND(from);
790 mfreeseg(s, from, (to - from) / BY2PG);
797 /* For binary compatibility */
801 return ibrk(arg[0], BSEG);
805 sysrendezvous(ulong *arg)
811 l = &REND(up->rgrp, tag);
812 up->rendval = ~(uintptr)0;
815 for(p = *l; p; p = p->rendhash) {
816 if(p->rendtag == tag) {
830 /* Going to sleep here */
832 up->rendval = arg[1];
835 up->state = Rendezvous;
844 * The implementation of semaphores is complicated by needing
845 * to avoid rescheduling in syssemrelease, so that it is safe
846 * to call from real-time processes. This means syssemrelease
847 * cannot acquire any qlocks, only spin locks.
849 * Semacquire and semrelease must both manipulate the semaphore
850 * wait list. Lock-free linked lists only exist in theory, not
851 * in practice, so the wait list is protected by a spin lock.
853 * The semaphore value *addr is stored in user memory, so it
854 * cannot be read or written while holding spin locks.
856 * Thus, we can access the list only when holding the lock, and
857 * we can access the semaphore only when not holding the lock.
858 * This makes things interesting. Note that sleep's condition function
859 * is called while holding two locks - r and up->rlock - so it cannot
860 * access the semaphore value either.
862 * An acquirer announces its intention to try for the semaphore
863 * by putting a Sema structure onto the wait list and then
864 * setting Sema.waiting. After one last check of semaphore,
865 * the acquirer sleeps until Sema.waiting==0. A releaser of n
866 * must wake up n acquirers who have Sema.waiting set. It does
867 * this by clearing Sema.waiting and then calling wakeup.
869 * There are three interesting races here.
871 * The first is that in this particular sleep/wakeup usage, a single
872 * wakeup can rouse a process from two consecutive sleeps!
875 * (a) set Sema.waiting = 1
877 * (b) set Sema.waiting = 0
878 * (a) check Sema.waiting inside sleep, return w/o sleeping
879 * (a) try for semaphore, fail
880 * (a) set Sema.waiting = 1
885 * This is okay - semacquire will just go around the loop
886 * again. It does mean that at the top of the for(;;) loop in
887 * semacquire, phore.waiting might already be set to 1.
889 * The second is that a releaser might wake an acquirer who is
890 * interrupted before he can acquire the lock. Since
891 * release(n) issues only n wakeup calls -- only n can be used
892 * anyway -- if the interrupted process is not going to use his
893 * wakeup call he must pass it on to another acquirer.
895 * The third race is similar to the second but more subtle. An
896 * acquirer sets waiting=1 and then does a final canacquire()
897 * before going to sleep. The opposite order would result in
898 * missing wakeups that happen between canacquire and
899 * waiting=1. (In fact, the whole point of Sema.waiting is to
900 * avoid missing wakeups between canacquire() and sleep().) But
901 * there can be spurious wakeups between a successful
902 * canacquire() and the following semdequeue(). This wakeup is
903 * not useful to the acquirer, since he has already acquired
904 * the semaphore. Like in the previous case, though, the
905 * acquirer must pass the wakeup call along.
907 * This is all rather subtle. The code below has been verified
908 * with the spin model /sys/src/9/port/semaphore.p. The
909 * original code anticipated the second race but not the first
910 * or third, which were caught only with spin. The first race
911 * is mentioned in /sys/doc/sleep.ps, but I'd forgotten about it.
912 * It was lucky that my abstract model of sleep/wakeup still managed
913 * to preserve that behavior.
915 * I remain slightly concerned about memory coherence
916 * outside of locks. The spin model does not take
917 * queued processor writes into account so we have to
918 * think hard. The only variables accessed outside locks
919 * are the semaphore value itself and the boolean flag
920 * Sema.waiting. The value is only accessed with cmpswap,
921 * whose job description includes doing the right thing as
922 * far as memory coherence across processors. That leaves
923 * Sema.waiting. To handle it, we call coherence() before each
924 * read and after each write. - rsc
927 /* Add semaphore p with addr a to list in seg. */
929 semqueue(Segment *s, long *a, Sema *p)
931 memset(p, 0, sizeof *p);
933 lock(&s->sema); /* uses s->sema.Rendez.Lock, but no one else is */
935 p->prev = s->sema.prev;
941 /* Remove semaphore p from list in seg. */
943 semdequeue(Segment *s, Sema *p)
946 p->next->prev = p->prev;
947 p->prev->next = p->next;
951 /* Wake up n waiters with addr a on list in seg. */
953 semwakeup(Segment *s, long *a, long n)
958 for(p=s->sema.next; p!=&s->sema && n>0; p=p->next){
959 if(p->addr == a && p->waiting){
969 /* Add delta to semaphore and wake up waiters as appropriate. */
971 semrelease(Segment *s, long *addr, long delta)
977 while(!cmpswap(addr, value, value+delta));
978 semwakeup(s, addr, delta);
982 /* Try to acquire semaphore using compare-and-swap */
984 canacquire(long *addr)
988 while((value=*addr) > 0)
989 if(cmpswap(addr, value, value-1))
994 /* Should we wake up? */
999 return !((Sema*)p)->waiting;
1002 /* Acquire semaphore (subtract 1). */
1004 semacquire(Segment *s, long *addr, int block)
1009 if(canacquire(addr))
1015 semqueue(s, addr, &phore);
1019 if(canacquire(addr)){
1025 sleep(&phore, semawoke, &phore);
1028 semdequeue(s, &phore);
1029 coherence(); /* not strictly necessary due to lock in semdequeue */
1031 semwakeup(s, addr, 1);
1038 syssemacquire(ulong *arg)
1044 validaddr(arg[0], sizeof(long), 1);
1046 addr = (long*)arg[0];
1049 if((s = seg(up, (ulong)addr, 0)) == nil)
1053 return semacquire(s, addr, block);
1057 syssemrelease(ulong *arg)
1062 validaddr(arg[0], sizeof(long), 1);
1064 addr = (long*)arg[0];
1067 if((s = seg(up, (ulong)addr, 0)) == nil)
1069 if(delta < 0 || *addr < 0)
1071 return semrelease(s, addr, arg[1]);