]> git.lizzy.rs Git - plan9front.git/blob - sys/src/9/port/sysproc.c
devproc: remove pgrpid == 1 check for notepg open
[plan9front.git] / sys / src / 9 / port / sysproc.c
1 #include        "u.h"
2 #include        "tos.h"
3 #include        "../port/lib.h"
4 #include        "mem.h"
5 #include        "dat.h"
6 #include        "fns.h"
7 #include        "../port/error.h"
8 #include        "edf.h"
9
10 #include        <a.out.h>
11
12 int     shargs(char*, int, char**);
13
14 extern void checkpages(void);
15 extern void checkpagerefs(void);
16
17 long
18 sysr1(ulong*)
19 {
20         checkpagerefs();
21         return 0;
22 }
23
24 long
25 sysrfork(ulong *arg)
26 {
27         Proc *p;
28         int n, i;
29         Fgrp *ofg;
30         Pgrp *opg;
31         Rgrp *org;
32         Egrp *oeg;
33         ulong pid, flag;
34         Mach *wm;
35
36         flag = arg[0];
37         /* Check flags before we commit */
38         if((flag & (RFFDG|RFCFDG)) == (RFFDG|RFCFDG))
39                 error(Ebadarg);
40         if((flag & (RFNAMEG|RFCNAMEG)) == (RFNAMEG|RFCNAMEG))
41                 error(Ebadarg);
42         if((flag & (RFENVG|RFCENVG)) == (RFENVG|RFCENVG))
43                 error(Ebadarg);
44
45         if((flag&RFPROC) == 0) {
46                 if(flag & (RFMEM|RFNOWAIT))
47                         error(Ebadarg);
48                 if(flag & (RFFDG|RFCFDG)) {
49                         ofg = up->fgrp;
50                         if(flag & RFFDG)
51                                 up->fgrp = dupfgrp(ofg);
52                         else
53                                 up->fgrp = dupfgrp(nil);
54                         closefgrp(ofg);
55                 }
56                 if(flag & (RFNAMEG|RFCNAMEG)) {
57                         opg = up->pgrp;
58                         up->pgrp = newpgrp();
59                         if(flag & RFNAMEG)
60                                 pgrpcpy(up->pgrp, opg);
61                         /* inherit noattach */
62                         up->pgrp->noattach = opg->noattach;
63                         closepgrp(opg);
64                 }
65                 if(flag & RFNOMNT)
66                         up->pgrp->noattach = 1;
67                 if(flag & RFREND) {
68                         org = up->rgrp;
69                         up->rgrp = newrgrp();
70                         closergrp(org);
71                 }
72                 if(flag & (RFENVG|RFCENVG)) {
73                         oeg = up->egrp;
74                         up->egrp = smalloc(sizeof(Egrp));
75                         up->egrp->ref = 1;
76                         if(flag & RFENVG)
77                                 envcpy(up->egrp, oeg);
78                         closeegrp(oeg);
79                 }
80                 if(flag & RFNOTEG)
81                         up->noteid = pidalloc(0);
82                 return 0;
83         }
84
85         p = newproc();
86
87         p->fpsave = up->fpsave;
88         p->scallnr = up->scallnr;
89         p->s = up->s;
90         p->nerrlab = 0;
91         p->slash = up->slash;
92         p->dot = up->dot;
93         incref(p->dot);
94
95         memmove(p->note, up->note, sizeof(p->note));
96         p->privatemem = up->privatemem;
97         p->noswap = up->noswap;
98         p->nnote = up->nnote;
99         p->notified = 0;
100         p->lastnote = up->lastnote;
101         p->notify = up->notify;
102         p->ureg = up->ureg;
103         p->dbgreg = 0;
104
105         /* Make a new set of memory segments */
106         n = flag & RFMEM;
107         qlock(&p->seglock);
108         if(waserror()){
109                 qunlock(&p->seglock);
110                 nexterror();
111         }
112         for(i = 0; i < NSEG; i++)
113                 if(up->seg[i])
114                         p->seg[i] = dupseg(up->seg, i, n);
115         qunlock(&p->seglock);
116         poperror();
117
118         /* File descriptors */
119         if(flag & (RFFDG|RFCFDG)) {
120                 if(flag & RFFDG)
121                         p->fgrp = dupfgrp(up->fgrp);
122                 else
123                         p->fgrp = dupfgrp(nil);
124         }
125         else {
126                 p->fgrp = up->fgrp;
127                 incref(p->fgrp);
128         }
129
130         /* Process groups */
131         if(flag & (RFNAMEG|RFCNAMEG)) {
132                 p->pgrp = newpgrp();
133                 if(flag & RFNAMEG)
134                         pgrpcpy(p->pgrp, up->pgrp);
135                 /* inherit noattach */
136                 p->pgrp->noattach = up->pgrp->noattach;
137         }
138         else {
139                 p->pgrp = up->pgrp;
140                 incref(p->pgrp);
141         }
142         if(flag & RFNOMNT)
143                 p->pgrp->noattach = 1;
144
145         if(flag & RFREND)
146                 p->rgrp = newrgrp();
147         else {
148                 incref(up->rgrp);
149                 p->rgrp = up->rgrp;
150         }
151
152         /* Environment group */
153         if(flag & (RFENVG|RFCENVG)) {
154                 p->egrp = smalloc(sizeof(Egrp));
155                 p->egrp->ref = 1;
156                 if(flag & RFENVG)
157                         envcpy(p->egrp, up->egrp);
158         }
159         else {
160                 p->egrp = up->egrp;
161                 incref(p->egrp);
162         }
163         p->hang = up->hang;
164         p->procmode = up->procmode;
165
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
168          */
169         forkchild(p, up->dbgreg);
170
171         p->parent = up;
172         p->parentpid = up->pid;
173         if(flag&RFNOWAIT)
174                 p->parentpid = 0;
175         else {
176                 lock(&up->exl);
177                 up->nchild++;
178                 unlock(&up->exl);
179         }
180         if((flag&RFNOTEG) == 0)
181                 p->noteid = up->noteid;
182
183         p->fpstate = up->fpstate;
184         pid = p->pid;
185         memset(p->time, 0, sizeof(p->time));
186         p->time[TReal] = MACHP(0)->ticks;
187
188         kstrdup(&p->text, up->text);
189         kstrdup(&p->user, up->user);
190
191         procfork(p);
192
193         /*
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.
197          */
198         flushmmu();
199         p->basepri = up->basepri;
200         p->priority = up->basepri;
201         p->fixedpri = up->fixedpri;
202         p->mp = up->mp;
203         wm = up->wired;
204         if(wm)
205                 procwired(p, wm->machno);
206         ready(p);
207         sched();
208         return pid;
209 }
210
211 static ulong
212 l2be(long l)
213 {
214         uchar *cp;
215
216         cp = (uchar*)&l;
217         return (cp[0]<<24) | (cp[1]<<16) | (cp[2]<<8) | cp[3];
218 }
219
220 long
221 sysexec(ulong *arg)
222 {
223         Segment *s, *ts;
224         ulong t, d, b;
225         int i;
226         Chan *tc;
227         char **argv, **argp;
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;
231         int indir, commit;
232         Exec exec;
233         char line[sizeof(Exec)];
234         Fgrp *f;
235         Image *img;
236         ulong magic, text, entry, data, bss;
237         Tos *tos;
238
239         commit = 0;
240         indir = 0;
241         elem = nil;
242         validaddr(arg[0], 1, 0);
243         file0 = validnamedup((char*)arg[0], 1);
244         if(waserror()){
245                 free(file0);
246                 free(elem);
247                 /* Disaster after commit */
248                 if(commit)
249                         pexit(up->errstr, 1);
250                 nexterror();
251         }
252         file = file0;
253         for(;;){
254                 tc = namec(file, Aopen, OEXEC, 0);
255                 if(waserror()){
256                         cclose(tc);
257                         nexterror();
258                 }
259                 if(!indir)
260                         kstrdup(&elem, up->genbuf);
261
262                 n = devtab[tc->type]->read(tc, &exec, sizeof(Exec), 0);
263                 if(n < 2)
264                         error(Ebadexec);
265                 magic = l2be(exec.magic);
266                 text = l2be(exec.text);
267                 entry = l2be(exec.entry);
268                 if(n==sizeof(Exec) && (magic == AOUT_MAGIC)){
269                         if(text >= USTKTOP-UTZERO
270                         || entry < UTZERO+sizeof(Exec)
271                         || entry >= UTZERO+sizeof(Exec)+text)
272                                 error(Ebadexec);
273                         break; /* for binary */
274                 }
275
276                 /*
277                  * Process #! /bin/sh args ...
278                  */
279                 memmove(line, &exec, sizeof(Exec));
280                 if(indir || line[0]!='#' || line[1]!='!')
281                         error(Ebadexec);
282                 n = shargs(line, n, progarg);
283                 if(n == 0)
284                         error(Ebadexec);
285                 indir = 1;
286                 /*
287                  * First arg becomes complete file name
288                  */
289                 progarg[n++] = file;
290                 progarg[n] = 0;
291                 validaddr(arg[1], BY2WD, 1);
292                 arg[1] += BY2WD;
293                 file = progarg[0];
294                 if(strlen(elem) >= sizeof progelem)
295                         error(Ebadexec);
296                 strcpy(progelem, elem);
297                 progarg[0] = progelem;
298                 poperror();
299                 cclose(tc);
300         }
301
302         data = l2be(exec.data);
303         bss = l2be(exec.bss);
304         t = (UTZERO+sizeof(Exec)+text+(BY2PG-1)) & ~(BY2PG-1);
305         d = (t + data + (BY2PG-1)) & ~(BY2PG-1);
306         bssend = t + data + bss;
307         b = (bssend + (BY2PG-1)) & ~(BY2PG-1);
308         if(t >= KZERO || d >= KZERO || b >= KZERO)
309                 error(Ebadexec);
310
311         /*
312          * Args: pass 1: count
313          */
314         nbytes = sizeof(Tos);           /* hole for profiling clock at top of stack (and more) */
315         nargs = 0;
316         if(indir){
317                 argp = progarg;
318                 while(*argp){
319                         a = *argp++;
320                         nbytes += strlen(a) + 1;
321                         nargs++;
322                 }
323         }
324         evenaddr(arg[1]);
325         argp = (char**)arg[1];
326         validaddr((ulong)argp, BY2WD, 0);
327         while(*argp){
328                 a = *argp++;
329                 if(((ulong)argp&(BY2PG-1)) < BY2WD)
330                         validaddr((ulong)argp, BY2WD, 0);
331                 validaddr((ulong)a, 1, 0);
332                 nbytes += ((char*)vmemchr(a, 0, 0x7FFFFFFF) - a) + 1;
333                 nargs++;
334         }
335         ssize = BY2WD*(nargs+1) + ((nbytes+(BY2WD-1)) & ~(BY2WD-1));
336
337         /*
338          * 8-byte align SP for those (e.g. sparc) that need it.
339          * execregs() will subtract another 4 bytes for argc.
340          */
341         if((ssize+4) & 7)
342                 ssize += 4;
343         spage = (ssize+(BY2PG-1)) >> PGSHIFT;
344
345         /*
346          * Build the stack segment, putting it in kernel virtual for the moment
347          */
348         if(spage > TSTKSIZ)
349                 error(Enovmem);
350
351         qlock(&up->seglock);
352         if(waserror()){
353                 qunlock(&up->seglock);
354                 nexterror();
355         }
356         up->seg[ESEG] = newseg(SG_STACK, TSTKTOP-USTKSIZE, USTKSIZE/BY2PG);
357
358         /*
359          * Args: pass 2: assemble; the pages will be faulted in
360          */
361         tos = (Tos*)(TSTKTOP - sizeof(Tos));
362         tos->cyclefreq = m->cyclefreq;
363         tos->kcycles = 0;
364         tos->pcycles = 0;
365         tos->clock = 0;
366
367         argv = (char**)(TSTKTOP - ssize);
368         charp = (char*)(TSTKTOP - nbytes);
369         args = charp;
370         if(indir)
371                 argp = progarg;
372         else
373                 argp = (char**)arg[1];
374
375         for(i=0; i<nargs; i++){
376                 if(indir && *argp==0) {
377                         indir = 0;
378                         argp = (char**)arg[1];
379                 }
380                 *argv++ = charp + (USTKTOP-TSTKTOP);
381                 n = strlen(*argp) + 1;
382                 memmove(charp, *argp++, n);
383                 charp += n;
384         }
385         free(file0);
386         file0 = nil;    /* so waserror() won't free file0 */
387         USED(file0);
388
389         free(up->text);
390         up->text = elem;
391         elem = nil;     /* so waserror() won't free elem */
392         USED(elem);
393
394         /* copy args; easiest from new process's stack */
395         n = charp - args;
396         if(n > 128)     /* don't waste too much space on huge arg lists */
397                 n = 128;
398         a = up->args;
399         up->args = nil;
400         free(a);
401         up->args = smalloc(n);
402         memmove(up->args, args, n);
403         if(n>0 && up->args[n-1]!='\0'){
404                 /* make sure last arg is NUL-terminated */
405                 /* put NUL at UTF-8 character boundary */
406                 for(i=n-1; i>0; --i)
407                         if(fullrune(up->args+i, n-i))
408                                 break;
409                 up->args[i] = 0;
410                 n = i+1;
411         }
412         up->nargs = n;
413
414         commit = 1;
415         USED(commit);
416
417         /*
418          * Committed.
419          * Free old memory.
420          * Special segments are maintained across exec
421          */
422         for(i = SSEG; i <= BSEG; i++) {
423                 putseg(up->seg[i]);
424                 /* prevent a second free if we have an error */
425                 up->seg[i] = 0;
426         }
427         for(i = BSEG+1; i < NSEG; i++) {
428                 s = up->seg[i];
429                 if(s != 0 && (s->type&SG_CEXEC)) {
430                         putseg(s);
431                         up->seg[i] = 0;
432                 }
433         }
434
435         /*
436          * Close on exec
437          */
438         f = up->fgrp;
439         for(i=0; i<=f->maxfd; i++)
440                 fdclose(i, CCEXEC);
441
442         /* Text.  Shared. Attaches to cache image if possible */
443         /* attachimage returns a locked cache image */
444         img = attachimage(SG_TEXT|SG_RONLY, tc, UTZERO, (t-UTZERO)>>PGSHIFT);
445         ts = img->s;
446         up->seg[TSEG] = ts;
447         ts->flushme = 1;
448         ts->fstart = 0;
449         ts->flen = sizeof(Exec)+text;
450         unlock(img);
451
452         /* Data. Shared. */
453         s = newseg(SG_DATA, t, (d-t)>>PGSHIFT);
454         up->seg[DSEG] = s;
455
456         /* Attached by hand */
457         incref(img);
458         s->image = img;
459         s->fstart = ts->fstart+ts->flen;
460         s->flen = data;
461
462         /* BSS. Zero fill on demand */
463         up->seg[BSEG] = newseg(SG_BSS, d, (b-d)>>PGSHIFT);
464
465         /*
466          * Move the stack
467          */
468         s = up->seg[ESEG];
469         up->seg[ESEG] = 0;
470         s->base = USTKTOP-USTKSIZE;
471         s->top = USTKTOP;
472         relocateseg(s, USTKTOP-TSTKTOP);
473         up->seg[SSEG] = s;
474         qunlock(&up->seglock);
475         poperror();     /* seglock */
476
477         /*
478          *  '/' processes are higher priority (hack to make /ip more responsive).
479          */
480         if(devtab[tc->type]->dc == L'/')
481                 up->basepri = PriRoot;
482         up->priority = up->basepri;
483         cclose(tc);
484         poperror();     /* tc */
485         poperror();     /* elem */
486
487         qlock(&up->debug);
488         up->nnote = 0;
489         up->notify = 0;
490         up->notified = 0;
491         up->privatemem = 0;
492         procsetup(up);
493         qunlock(&up->debug);
494
495         /*
496          *  At this point, the mmu contains info about the old address
497          *  space and needs to be flushed
498          */
499         flushmmu();
500
501         if(up->hang)
502                 up->procctl = Proc_stopme;
503         return execregs(entry, ssize, nargs);
504 }
505
506 int
507 shargs(char *s, int n, char **ap)
508 {
509         int i;
510
511         s += 2;
512         n -= 2;         /* skip #! */
513         for(i=0; s[i]!='\n'; i++)
514                 if(i == n-1)
515                         return 0;
516         s[i] = 0;
517         *ap = 0;
518         i = 0;
519         for(;;) {
520                 while(*s==' ' || *s=='\t')
521                         s++;
522                 if(*s == 0)
523                         break;
524                 i++;
525                 *ap++ = s;
526                 *ap = 0;
527                 while(*s && *s!=' ' && *s!='\t')
528                         s++;
529                 if(*s == 0)
530                         break;
531                 else
532                         *s++ = 0;
533         }
534         return i;
535 }
536
537 int
538 return0(void*)
539 {
540         return 0;
541 }
542
543 long
544 syssleep(ulong *arg)
545 {
546
547         int n;
548
549         n = arg[0];
550         if(n <= 0) {
551                 if (up->edf && (up->edf->flags & Admitted))
552                         edfyield();
553                 else
554                         yield();
555                 return 0;
556         }
557         if(n < TK2MS(1))
558                 n = TK2MS(1);
559         tsleep(&up->sleep, return0, 0, n);
560         return 0;
561 }
562
563 long
564 sysalarm(ulong *arg)
565 {
566         return procalarm(arg[0]);
567 }
568
569 long
570 sysexits(ulong *arg)
571 {
572         char *status;
573         char *inval = "invalid exit string";
574         char buf[ERRMAX];
575
576         status = (char*)arg[0];
577         if(status){
578                 if(waserror())
579                         status = inval;
580                 else{
581                         validaddr((ulong)status, 1, 0);
582                         if(vmemchr(status, 0, ERRMAX) == 0){
583                                 memmove(buf, status, ERRMAX);
584                                 buf[ERRMAX-1] = 0;
585                                 status = buf;
586                         }
587                         poperror();
588                 }
589
590         }
591         pexit(status, 1);
592         return 0;               /* not reached */
593 }
594
595 long
596 sys_wait(ulong *arg)
597 {
598         int pid;
599         Waitmsg w;
600         OWaitmsg *ow;
601
602         if(arg[0] == 0)
603                 return pwait(nil);
604
605         validaddr(arg[0], sizeof(OWaitmsg), 1);
606         evenaddr(arg[0]);
607         pid = pwait(&w);
608         if(pid >= 0){
609                 ow = (OWaitmsg*)arg[0];
610                 readnum(0, ow->pid, NUMSIZE, w.pid, NUMSIZE);
611                 readnum(0, ow->time+TUser*NUMSIZE, NUMSIZE, w.time[TUser], NUMSIZE);
612                 readnum(0, ow->time+TSys*NUMSIZE, NUMSIZE, w.time[TSys], NUMSIZE);
613                 readnum(0, ow->time+TReal*NUMSIZE, NUMSIZE, w.time[TReal], NUMSIZE);
614                 strncpy(ow->msg, w.msg, sizeof(ow->msg)-1);
615                 ow->msg[sizeof(ow->msg)-1] = '\0';
616         }
617         return pid;
618 }
619
620 long
621 sysawait(ulong *arg)
622 {
623         int i;
624         int pid;
625         Waitmsg w;
626         ulong n;
627
628         n = arg[1];
629         validaddr(arg[0], n, 1);
630         pid = pwait(&w);
631         if(pid < 0)
632                 return -1;
633         i = snprint((char*)arg[0], n, "%d %lud %lud %lud %q",
634                 w.pid,
635                 w.time[TUser], w.time[TSys], w.time[TReal],
636                 w.msg);
637
638         return i;
639 }
640
641 void
642 werrstr(char *fmt, ...)
643 {
644         va_list va;
645
646         if(up == nil)
647                 return;
648
649         va_start(va, fmt);
650         vseprint(up->syserrstr, up->syserrstr+ERRMAX, fmt, va);
651         va_end(va);
652 }
653
654 static long
655 generrstr(char *buf, uint nbuf)
656 {
657         char tmp[ERRMAX];
658
659         if(nbuf == 0)
660                 error(Ebadarg);
661         validaddr((ulong)buf, nbuf, 1);
662         if(nbuf > sizeof tmp)
663                 nbuf = sizeof tmp;
664         memmove(tmp, buf, nbuf);
665
666         /* make sure it's NUL-terminated */
667         tmp[nbuf-1] = '\0';
668         memmove(buf, up->syserrstr, nbuf);
669         buf[nbuf-1] = '\0';
670         memmove(up->syserrstr, tmp, nbuf);
671         return 0;
672 }
673
674 long
675 syserrstr(ulong *arg)
676 {
677         return generrstr((char*)arg[0], arg[1]);
678 }
679
680 /* compatibility for old binaries */
681 long
682 sys_errstr(ulong *arg)
683 {
684         return generrstr((char*)arg[0], 64);
685 }
686
687 long
688 sysnotify(ulong *arg)
689 {
690         if(arg[0] != 0)
691                 validaddr(arg[0], sizeof(ulong), 0);
692         up->notify = (int(*)(void*, char*))(arg[0]);
693         return 0;
694 }
695
696 long
697 sysnoted(ulong *arg)
698 {
699         if(arg[0]!=NRSTR && !up->notified)
700                 error(Egreg);
701         return 0;
702 }
703
704 long
705 syssegbrk(ulong *arg)
706 {
707         int i;
708         ulong addr;
709         Segment *s;
710
711         addr = arg[0];
712         for(i = 0; i < NSEG; i++) {
713                 s = up->seg[i];
714                 if(s == 0 || addr < s->base || addr >= s->top)
715                         continue;
716                 switch(s->type&SG_TYPE) {
717                 case SG_TEXT:
718                 case SG_DATA:
719                 case SG_STACK:
720                         error(Ebadarg);
721                 default:
722                         return ibrk(arg[1], i);
723                 }
724         }
725
726         error(Ebadarg);
727         return 0;               /* not reached */
728 }
729
730 long
731 syssegattach(ulong *arg)
732 {
733         return segattach(up, arg[0], (char*)arg[1], arg[2], arg[3]);
734 }
735
736 long
737 syssegdetach(ulong *arg)
738 {
739         int i;
740         ulong addr;
741         Segment *s;
742
743         qlock(&up->seglock);
744         if(waserror()){
745                 qunlock(&up->seglock);
746                 nexterror();
747         }
748
749         s = 0;
750         addr = arg[0];
751         for(i = 0; i < NSEG; i++)
752                 if(s = up->seg[i]) {
753                         qlock(&s->lk);
754                         if((addr >= s->base && addr < s->top) ||
755                            (s->top == s->base && addr == s->base))
756                                 goto found;
757                         qunlock(&s->lk);
758                 }
759
760         error(Ebadarg);
761
762 found:
763         /*
764          * Check we are not detaching the initial stack segment.
765          */
766         if(s == up->seg[SSEG]){
767                 qunlock(&s->lk);
768                 error(Ebadarg);
769         }
770         up->seg[i] = 0;
771         qunlock(&s->lk);
772         putseg(s);
773         qunlock(&up->seglock);
774         poperror();
775
776         /* Ensure we flush any entries from the lost segment */
777         flushmmu();
778         return 0;
779 }
780
781 long
782 syssegfree(ulong *arg)
783 {
784         Segment *s;
785         ulong from, to;
786
787         from = arg[0];
788         s = seg(up, from, 1);
789         if(s == nil)
790                 error(Ebadarg);
791         to = (from + arg[1]) & ~(BY2PG-1);
792         from = PGROUND(from);
793
794         if(to > s->top) {
795                 qunlock(&s->lk);
796                 error(Ebadarg);
797         }
798
799         mfreeseg(s, from, (to - from) / BY2PG);
800         qunlock(&s->lk);
801         flushmmu();
802
803         return 0;
804 }
805
806 /* For binary compatibility */
807 long
808 sysbrk_(ulong *arg)
809 {
810         return ibrk(arg[0], BSEG);
811 }
812
813 long
814 sysrendezvous(ulong *arg)
815 {
816         uintptr tag, val;
817         Proc *p, **l;
818
819         tag = arg[0];
820         l = &REND(up->rgrp, tag);
821
822         lock(up->rgrp);
823         for(p = *l; p; p = p->rendhash) {
824                 if(p->rendtag == tag) {
825                         *l = p->rendhash;
826                         val = p->rendval;
827                         p->rendval = arg[1];
828                         unlock(up->rgrp);
829                         while(p->mach != 0)
830                                 ;
831                         ready(p);
832                         return val;
833                 }
834                 l = &p->rendhash;
835         }
836
837         /* Going to sleep here */
838         up->rendtag = tag;
839         up->rendval = arg[1];
840         up->rendhash = *l;
841         *l = up;
842         up->state = Rendezvous;
843         unlock(up->rgrp);
844
845         sched();
846
847         return up->rendval;
848 }
849
850 /*
851  * The implementation of semaphores is complicated by needing
852  * to avoid rescheduling in syssemrelease, so that it is safe
853  * to call from real-time processes.  This means syssemrelease
854  * cannot acquire any qlocks, only spin locks.
855  * 
856  * Semacquire and semrelease must both manipulate the semaphore
857  * wait list.  Lock-free linked lists only exist in theory, not
858  * in practice, so the wait list is protected by a spin lock.
859  * 
860  * The semaphore value *addr is stored in user memory, so it
861  * cannot be read or written while holding spin locks.
862  * 
863  * Thus, we can access the list only when holding the lock, and
864  * we can access the semaphore only when not holding the lock.
865  * This makes things interesting.  Note that sleep's condition function
866  * is called while holding two locks - r and up->rlock - so it cannot
867  * access the semaphore value either.
868  * 
869  * An acquirer announces its intention to try for the semaphore
870  * by putting a Sema structure onto the wait list and then
871  * setting Sema.waiting.  After one last check of semaphore,
872  * the acquirer sleeps until Sema.waiting==0.  A releaser of n
873  * must wake up n acquirers who have Sema.waiting set.  It does
874  * this by clearing Sema.waiting and then calling wakeup.
875  * 
876  * There are three interesting races here.  
877  
878  * The first is that in this particular sleep/wakeup usage, a single
879  * wakeup can rouse a process from two consecutive sleeps!  
880  * The ordering is:
881  * 
882  *      (a) set Sema.waiting = 1
883  *      (a) call sleep
884  *      (b) set Sema.waiting = 0
885  *      (a) check Sema.waiting inside sleep, return w/o sleeping
886  *      (a) try for semaphore, fail
887  *      (a) set Sema.waiting = 1
888  *      (a) call sleep
889  *      (b) call wakeup(a)
890  *      (a) wake up again
891  * 
892  * This is okay - semacquire will just go around the loop
893  * again.  It does mean that at the top of the for(;;) loop in
894  * semacquire, phore.waiting might already be set to 1.
895  * 
896  * The second is that a releaser might wake an acquirer who is
897  * interrupted before he can acquire the lock.  Since
898  * release(n) issues only n wakeup calls -- only n can be used
899  * anyway -- if the interrupted process is not going to use his
900  * wakeup call he must pass it on to another acquirer.
901  * 
902  * The third race is similar to the second but more subtle.  An
903  * acquirer sets waiting=1 and then does a final canacquire()
904  * before going to sleep.  The opposite order would result in
905  * missing wakeups that happen between canacquire and
906  * waiting=1.  (In fact, the whole point of Sema.waiting is to
907  * avoid missing wakeups between canacquire() and sleep().) But
908  * there can be spurious wakeups between a successful
909  * canacquire() and the following semdequeue().  This wakeup is
910  * not useful to the acquirer, since he has already acquired
911  * the semaphore.  Like in the previous case, though, the
912  * acquirer must pass the wakeup call along.
913  * 
914  * This is all rather subtle.  The code below has been verified
915  * with the spin model /sys/src/9/port/semaphore.p.  The
916  * original code anticipated the second race but not the first
917  * or third, which were caught only with spin.  The first race
918  * is mentioned in /sys/doc/sleep.ps, but I'd forgotten about it.
919  * It was lucky that my abstract model of sleep/wakeup still managed
920  * to preserve that behavior.
921  *
922  * I remain slightly concerned about memory coherence
923  * outside of locks.  The spin model does not take 
924  * queued processor writes into account so we have to
925  * think hard.  The only variables accessed outside locks
926  * are the semaphore value itself and the boolean flag
927  * Sema.waiting.  The value is only accessed with cmpswap,
928  * whose job description includes doing the right thing as
929  * far as memory coherence across processors.  That leaves
930  * Sema.waiting.  To handle it, we call coherence() before each
931  * read and after each write.           - rsc
932  */
933
934 /* Add semaphore p with addr a to list in seg. */
935 static void
936 semqueue(Segment *s, long *a, Sema *p)
937 {
938         memset(p, 0, sizeof *p);
939         p->addr = a;
940         lock(&s->sema); /* uses s->sema.Rendez.Lock, but no one else is */
941         p->next = &s->sema;
942         p->prev = s->sema.prev;
943         p->next->prev = p;
944         p->prev->next = p;
945         unlock(&s->sema);
946 }
947
948 /* Remove semaphore p from list in seg. */
949 static void
950 semdequeue(Segment *s, Sema *p)
951 {
952         lock(&s->sema);
953         p->next->prev = p->prev;
954         p->prev->next = p->next;
955         unlock(&s->sema);
956 }
957
958 /* Wake up n waiters with addr a on list in seg. */
959 static void
960 semwakeup(Segment *s, long *a, long n)
961 {
962         Sema *p;
963         
964         lock(&s->sema);
965         for(p=s->sema.next; p!=&s->sema && n>0; p=p->next){
966                 if(p->addr == a && p->waiting){
967                         p->waiting = 0;
968                         coherence();
969                         wakeup(p);
970                         n--;
971                 }
972         }
973         unlock(&s->sema);
974 }
975
976 /* Add delta to semaphore and wake up waiters as appropriate. */
977 static long
978 semrelease(Segment *s, long *addr, long delta)
979 {
980         long value;
981
982         do
983                 value = *addr;
984         while(!cmpswap(addr, value, value+delta));
985         semwakeup(s, addr, delta);
986         return value+delta;
987 }
988
989 /* Try to acquire semaphore using compare-and-swap */
990 static int
991 canacquire(long *addr)
992 {
993         long value;
994         
995         while((value=*addr) > 0)
996                 if(cmpswap(addr, value, value-1))
997                         return 1;
998         return 0;
999 }               
1000
1001 /* Should we wake up? */
1002 static int
1003 semawoke(void *p)
1004 {
1005         coherence();
1006         return !((Sema*)p)->waiting;
1007 }
1008
1009 /* Acquire semaphore (subtract 1). */
1010 static int
1011 semacquire(Segment *s, long *addr, int block)
1012 {
1013         int acquired;
1014         Sema phore;
1015
1016         if(canacquire(addr))
1017                 return 1;
1018         if(!block)
1019                 return 0;
1020
1021         acquired = 0;
1022         semqueue(s, addr, &phore);
1023         for(;;){
1024                 phore.waiting = 1;
1025                 coherence();
1026                 if(canacquire(addr)){
1027                         acquired = 1;
1028                         break;
1029                 }
1030                 if(waserror())
1031                         break;
1032                 sleep(&phore, semawoke, &phore);
1033                 poperror();
1034         }
1035         semdequeue(s, &phore);
1036         coherence();    /* not strictly necessary due to lock in semdequeue */
1037         if(!phore.waiting)
1038                 semwakeup(s, addr, 1);
1039         if(!acquired)
1040                 nexterror();
1041         return 1;
1042 }
1043
1044 /* Acquire semaphore or time-out */
1045 static int
1046 tsemacquire(Segment *s, long *addr, ulong ms)
1047 {
1048         int acquired, timedout;
1049         ulong t, elms;
1050         Sema phore;
1051
1052         if(canacquire(addr))
1053                 return 1;
1054         if(ms == 0)
1055                 return 0;
1056         acquired = timedout = 0;
1057         semqueue(s, addr, &phore);
1058         for(;;){
1059                 phore.waiting = 1;
1060                 coherence();
1061                 if(canacquire(addr)){
1062                         acquired = 1;
1063                         break;
1064                 }
1065                 if(waserror())
1066                         break;
1067                 t = m->ticks;
1068                 tsleep(&phore, semawoke, &phore, ms);
1069                 elms = TK2MS(m->ticks - t);
1070                 poperror();
1071                 if(elms >= ms){
1072                         timedout = 1;
1073                         break;
1074                 }
1075                 ms -= elms;
1076         }
1077         semdequeue(s, &phore);
1078         coherence();    /* not strictly necessary due to lock in semdequeue */
1079         if(!phore.waiting)
1080                 semwakeup(s, addr, 1);
1081         if(timedout)
1082                 return 0;
1083         if(!acquired)
1084                 nexterror();
1085         return 1;
1086 }
1087
1088 long
1089 syssemacquire(ulong *arg)
1090 {
1091         int block;
1092         long *addr;
1093         Segment *s;
1094
1095         validaddr(arg[0], sizeof(long), 1);
1096         evenaddr(arg[0]);
1097         addr = (long*)arg[0];
1098         block = arg[1];
1099         
1100         if((s = seg(up, (ulong)addr, 0)) == nil)
1101                 error(Ebadarg);
1102         if(*addr < 0)
1103                 error(Ebadarg);
1104         return semacquire(s, addr, block);
1105 }
1106
1107 long
1108 systsemacquire(ulong *arg)
1109 {
1110         long *addr;
1111         ulong ms;
1112         Segment *s;
1113
1114         validaddr(arg[0], sizeof(long), 1);
1115         evenaddr(arg[0]);
1116         addr = (long*)arg[0];
1117         ms = arg[1];
1118
1119         if((s = seg(up, (ulong)addr, 0)) == nil)
1120                 error(Ebadarg);
1121         if(*addr < 0)
1122                 error(Ebadarg);
1123         return tsemacquire(s, addr, ms);
1124 }
1125
1126 long
1127 syssemrelease(ulong *arg)
1128 {
1129         long *addr, delta;
1130         Segment *s;
1131
1132         validaddr(arg[0], sizeof(long), 1);
1133         evenaddr(arg[0]);
1134         addr = (long*)arg[0];
1135         delta = arg[1];
1136
1137         if((s = seg(up, (ulong)addr, 0)) == nil)
1138                 error(Ebadarg);
1139         if(delta < 0 || *addr < 0)
1140                 error(Ebadarg);
1141         return semrelease(s, addr, arg[1]);
1142 }