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);
191 * since the bss/data segments are now shareable,
192 * any mmu info about this process is now stale
193 * (i.e. has bad properties) and has to be discarded.
196 p->basepri = up->basepri;
197 p->priority = up->basepri;
198 p->fixedpri = up->fixedpri;
202 procwired(p, wm->machno);
214 return (cp[0]<<24) | (cp[1]<<16) | (cp[2]<<8) | cp[3];
225 char *a, *charp, *args, *file, *file0;
226 char *progarg[sizeof(Exec)/2+1], *elem, progelem[64];
227 ulong ssize, spage, nargs, nbytes, n, bssend;
230 char line[sizeof(Exec)];
233 ulong magic, text, entry, data, bss;
238 validaddr(arg[0], 1, 0);
239 file0 = validnamedup((char*)arg[0], 1);
247 tc = namec(file, Aopen, OEXEC, 0);
253 kstrdup(&elem, up->genbuf);
255 n = devtab[tc->type]->read(tc, &exec, sizeof(Exec), 0);
258 magic = l2be(exec.magic);
259 text = l2be(exec.text);
260 entry = l2be(exec.entry);
261 if(n==sizeof(Exec) && (magic == AOUT_MAGIC)){
262 if(text >= USTKTOP-UTZERO
263 || entry < UTZERO+sizeof(Exec)
264 || entry >= UTZERO+sizeof(Exec)+text)
266 break; /* for binary */
270 * Process #! /bin/sh args ...
272 memmove(line, &exec, sizeof(Exec));
273 if(indir || line[0]!='#' || line[1]!='!')
275 n = shargs(line, n, progarg);
280 * First arg becomes complete file name
284 validaddr(arg[1], BY2WD, 1);
287 if(strlen(elem) >= sizeof progelem)
289 strcpy(progelem, elem);
290 progarg[0] = progelem;
295 data = l2be(exec.data);
296 bss = l2be(exec.bss);
297 t = (UTZERO+sizeof(Exec)+text+(BY2PG-1)) & ~(BY2PG-1);
298 d = (t + data + (BY2PG-1)) & ~(BY2PG-1);
299 bssend = t + data + bss;
300 b = (bssend + (BY2PG-1)) & ~(BY2PG-1);
301 if(t >= KZERO || d >= KZERO || b >= KZERO)
305 * Args: pass 1: count
307 nbytes = sizeof(Tos); /* hole for profiling clock at top of stack (and more) */
313 nbytes += strlen(a) + 1;
318 argp = (char**)arg[1];
319 validaddr((ulong)argp, BY2WD, 0);
322 if(((ulong)argp&(BY2PG-1)) < BY2WD)
323 validaddr((ulong)argp, BY2WD, 0);
324 validaddr((ulong)a, 1, 0);
325 nbytes += ((char*)vmemchr(a, 0, 0x7FFFFFFF) - a) + 1;
328 ssize = BY2WD*(nargs+1) + ((nbytes+(BY2WD-1)) & ~(BY2WD-1));
331 * 8-byte align SP for those (e.g. sparc) that need it.
332 * execregs() will subtract another 4 bytes for argc.
336 spage = (ssize+(BY2PG-1)) >> PGSHIFT;
339 * Build the stack segment, putting it in kernel virtual for the moment
346 qunlock(&up->seglock);
349 up->seg[ESEG] = newseg(SG_STACK, TSTKTOP-USTKSIZE, USTKSIZE/BY2PG);
352 * Args: pass 2: assemble; the pages will be faulted in
354 tos = (Tos*)(TSTKTOP - sizeof(Tos));
355 tos->cyclefreq = m->cyclefreq;
356 cycles((uvlong*)&tos->pcycles);
357 tos->pcycles = -tos->pcycles;
358 tos->kcycles = tos->pcycles;
360 argv = (char**)(TSTKTOP - ssize);
361 charp = (char*)(TSTKTOP - nbytes);
366 argp = (char**)arg[1];
368 for(i=0; i<nargs; i++){
369 if(indir && *argp==0) {
371 argp = (char**)arg[1];
373 *argv++ = charp + (USTKTOP-TSTKTOP);
374 n = strlen(*argp) + 1;
375 memmove(charp, *argp++, n);
382 elem = nil; /* so waserror() won't free elem */
385 /* copy args; easiest from new process's stack */
387 if(n > 128) /* don't waste too much space on huge arg lists */
392 up->args = smalloc(n);
393 memmove(up->args, args, n);
394 if(n>0 && up->args[n-1]!='\0'){
395 /* make sure last arg is NUL-terminated */
396 /* put NUL at UTF-8 character boundary */
398 if(fullrune(up->args+i, n-i))
408 * Special segments are maintained across exec
410 for(i = SSEG; i <= BSEG; i++) {
412 /* prevent a second free if we have an error */
415 for(i = BSEG+1; i < NSEG; i++) {
417 if(s != 0 && (s->type&SG_CEXEC)) {
427 for(i=0; i<=f->maxfd; i++)
430 /* Text. Shared. Attaches to cache image if possible */
431 /* attachimage returns a locked cache image */
432 img = attachimage(SG_TEXT|SG_RONLY, tc, UTZERO, (t-UTZERO)>>PGSHIFT);
437 ts->flen = sizeof(Exec)+text;
441 s = newseg(SG_DATA, t, (d-t)>>PGSHIFT);
444 /* Attached by hand */
447 s->fstart = ts->fstart+ts->flen;
450 /* BSS. Zero fill on demand */
451 up->seg[BSEG] = newseg(SG_BSS, d, (b-d)>>PGSHIFT);
459 qunlock(&up->seglock);
460 poperror(); /* seglock */
461 poperror(); /* elem */
462 s->base = USTKTOP-USTKSIZE;
464 relocateseg(s, USTKTOP-TSTKTOP);
467 * '/' processes are higher priority (hack to make /ip more responsive).
469 if(devtab[tc->type]->dc == L'/')
470 up->basepri = PriRoot;
471 up->priority = up->basepri;
476 * At this point, the mmu contains info about the old address
477 * space and needs to be flushed
488 up->procctl = Proc_stopme;
490 return execregs(entry, ssize, nargs);
494 shargs(char *s, int n, char **ap)
499 n -= 2; /* skip #! */
500 for(i=0; s[i]!='\n'; i++)
507 while(*s==' ' || *s=='\t')
514 while(*s && *s!=' ' && *s!='\t')
538 if (up->edf && (up->edf->flags & Admitted))
546 tsleep(&up->sleep, return0, 0, n);
553 return procalarm(arg[0]);
560 char *inval = "invalid exit string";
563 status = (char*)arg[0];
568 validaddr((ulong)status, 1, 0);
569 if(vmemchr(status, 0, ERRMAX) == 0){
570 memmove(buf, status, ERRMAX);
579 return 0; /* not reached */
592 validaddr(arg[0], sizeof(OWaitmsg), 1);
596 ow = (OWaitmsg*)arg[0];
597 readnum(0, ow->pid, NUMSIZE, w.pid, NUMSIZE);
598 readnum(0, ow->time+TUser*NUMSIZE, NUMSIZE, w.time[TUser], NUMSIZE);
599 readnum(0, ow->time+TSys*NUMSIZE, NUMSIZE, w.time[TSys], NUMSIZE);
600 readnum(0, ow->time+TReal*NUMSIZE, NUMSIZE, w.time[TReal], NUMSIZE);
601 strncpy(ow->msg, w.msg, sizeof(ow->msg));
602 ow->msg[sizeof(ow->msg)-1] = '\0';
616 validaddr(arg[0], n, 1);
620 i = snprint((char*)arg[0], n, "%d %lud %lud %lud %q",
622 w.time[TUser], w.time[TSys], w.time[TReal],
629 werrstr(char *fmt, ...)
637 vseprint(up->syserrstr, up->syserrstr+ERRMAX, fmt, va);
642 generrstr(char *buf, uint nbuf)
648 validaddr((ulong)buf, nbuf, 1);
649 if(nbuf > sizeof tmp)
651 memmove(tmp, buf, nbuf);
653 /* make sure it's NUL-terminated */
655 memmove(buf, up->syserrstr, nbuf);
657 memmove(up->syserrstr, tmp, nbuf);
662 syserrstr(ulong *arg)
664 return generrstr((char*)arg[0], arg[1]);
667 /* compatibility for old binaries */
669 sys_errstr(ulong *arg)
671 return generrstr((char*)arg[0], 64);
675 sysnotify(ulong *arg)
678 validaddr(arg[0], sizeof(ulong), 0);
679 up->notify = (int(*)(void*, char*))(arg[0]);
686 if(arg[0]!=NRSTR && !up->notified)
692 syssegbrk(ulong *arg)
699 for(i = 0; i < NSEG; i++) {
701 if(s == 0 || addr < s->base || addr >= s->top)
703 switch(s->type&SG_TYPE) {
709 return ibrk(arg[1], i);
714 return 0; /* not reached */
718 syssegattach(ulong *arg)
720 return segattach(up, arg[0], (char*)arg[1], arg[2], arg[3]);
724 syssegdetach(ulong *arg)
732 qunlock(&up->seglock);
738 for(i = 0; i < NSEG; i++)
741 if((addr >= s->base && addr < s->top) ||
742 (s->top == s->base && addr == s->base))
751 * Check we are not detaching the initial stack segment.
753 if(s == up->seg[SSEG]){
760 qunlock(&up->seglock);
763 /* Ensure we flush any entries from the lost segment */
769 syssegfree(ulong *arg)
775 s = seg(up, from, 1);
778 to = (from + arg[1]) & ~(BY2PG-1);
779 from = PGROUND(from);
786 mfreeseg(s, from, (to - from) / BY2PG);
793 /* For binary compatibility */
797 return ibrk(arg[0], BSEG);
801 sysrendezvous(ulong *arg)
807 l = &REND(up->rgrp, tag);
808 up->rendval = ~(uintptr)0;
811 for(p = *l; p; p = p->rendhash) {
812 if(p->rendtag == tag) {
826 /* Going to sleep here */
828 up->rendval = arg[1];
831 up->state = Rendezvous;
840 * The implementation of semaphores is complicated by needing
841 * to avoid rescheduling in syssemrelease, so that it is safe
842 * to call from real-time processes. This means syssemrelease
843 * cannot acquire any qlocks, only spin locks.
845 * Semacquire and semrelease must both manipulate the semaphore
846 * wait list. Lock-free linked lists only exist in theory, not
847 * in practice, so the wait list is protected by a spin lock.
849 * The semaphore value *addr is stored in user memory, so it
850 * cannot be read or written while holding spin locks.
852 * Thus, we can access the list only when holding the lock, and
853 * we can access the semaphore only when not holding the lock.
854 * This makes things interesting. Note that sleep's condition function
855 * is called while holding two locks - r and up->rlock - so it cannot
856 * access the semaphore value either.
858 * An acquirer announces its intention to try for the semaphore
859 * by putting a Sema structure onto the wait list and then
860 * setting Sema.waiting. After one last check of semaphore,
861 * the acquirer sleeps until Sema.waiting==0. A releaser of n
862 * must wake up n acquirers who have Sema.waiting set. It does
863 * this by clearing Sema.waiting and then calling wakeup.
865 * There are three interesting races here.
867 * The first is that in this particular sleep/wakeup usage, a single
868 * wakeup can rouse a process from two consecutive sleeps!
871 * (a) set Sema.waiting = 1
873 * (b) set Sema.waiting = 0
874 * (a) check Sema.waiting inside sleep, return w/o sleeping
875 * (a) try for semaphore, fail
876 * (a) set Sema.waiting = 1
881 * This is okay - semacquire will just go around the loop
882 * again. It does mean that at the top of the for(;;) loop in
883 * semacquire, phore.waiting might already be set to 1.
885 * The second is that a releaser might wake an acquirer who is
886 * interrupted before he can acquire the lock. Since
887 * release(n) issues only n wakeup calls -- only n can be used
888 * anyway -- if the interrupted process is not going to use his
889 * wakeup call he must pass it on to another acquirer.
891 * The third race is similar to the second but more subtle. An
892 * acquirer sets waiting=1 and then does a final canacquire()
893 * before going to sleep. The opposite order would result in
894 * missing wakeups that happen between canacquire and
895 * waiting=1. (In fact, the whole point of Sema.waiting is to
896 * avoid missing wakeups between canacquire() and sleep().) But
897 * there can be spurious wakeups between a successful
898 * canacquire() and the following semdequeue(). This wakeup is
899 * not useful to the acquirer, since he has already acquired
900 * the semaphore. Like in the previous case, though, the
901 * acquirer must pass the wakeup call along.
903 * This is all rather subtle. The code below has been verified
904 * with the spin model /sys/src/9/port/semaphore.p. The
905 * original code anticipated the second race but not the first
906 * or third, which were caught only with spin. The first race
907 * is mentioned in /sys/doc/sleep.ps, but I'd forgotten about it.
908 * It was lucky that my abstract model of sleep/wakeup still managed
909 * to preserve that behavior.
911 * I remain slightly concerned about memory coherence
912 * outside of locks. The spin model does not take
913 * queued processor writes into account so we have to
914 * think hard. The only variables accessed outside locks
915 * are the semaphore value itself and the boolean flag
916 * Sema.waiting. The value is only accessed with cmpswap,
917 * whose job description includes doing the right thing as
918 * far as memory coherence across processors. That leaves
919 * Sema.waiting. To handle it, we call coherence() before each
920 * read and after each write. - rsc
923 /* Add semaphore p with addr a to list in seg. */
925 semqueue(Segment *s, long *a, Sema *p)
927 memset(p, 0, sizeof *p);
929 lock(&s->sema); /* uses s->sema.Rendez.Lock, but no one else is */
931 p->prev = s->sema.prev;
937 /* Remove semaphore p from list in seg. */
939 semdequeue(Segment *s, Sema *p)
942 p->next->prev = p->prev;
943 p->prev->next = p->next;
947 /* Wake up n waiters with addr a on list in seg. */
949 semwakeup(Segment *s, long *a, long n)
954 for(p=s->sema.next; p!=&s->sema && n>0; p=p->next){
955 if(p->addr == a && p->waiting){
965 /* Add delta to semaphore and wake up waiters as appropriate. */
967 semrelease(Segment *s, long *addr, long delta)
973 while(!cmpswap(addr, value, value+delta));
974 semwakeup(s, addr, delta);
978 /* Try to acquire semaphore using compare-and-swap */
980 canacquire(long *addr)
984 while((value=*addr) > 0)
985 if(cmpswap(addr, value, value-1))
990 /* Should we wake up? */
995 return !((Sema*)p)->waiting;
998 /* Acquire semaphore (subtract 1). */
1000 semacquire(Segment *s, long *addr, int block)
1005 if(canacquire(addr))
1011 semqueue(s, addr, &phore);
1015 if(canacquire(addr)){
1021 sleep(&phore, semawoke, &phore);
1024 semdequeue(s, &phore);
1025 coherence(); /* not strictly necessary due to lock in semdequeue */
1027 semwakeup(s, addr, 1);
1034 syssemacquire(ulong *arg)
1040 validaddr(arg[0], sizeof(long), 1);
1042 addr = (long*)arg[0];
1045 if((s = seg(up, (ulong)addr, 0)) == nil)
1049 return semacquire(s, addr, block);
1053 syssemrelease(ulong *arg)
1058 validaddr(arg[0], sizeof(long), 1);
1060 addr = (long*)arg[0];
1063 if((s = seg(up, (ulong)addr, 0)) == nil)
1065 if(delta < 0 || *addr < 0)
1067 return semrelease(s, addr, arg[1]);