New and easy strace framework.
[akaros.git] / kern / drivers / dev / proc.c
1 /*
2  * This file is part of the UCB release of Plan 9. It is subject to the license
3  * terms in the LICENSE file found in the top-level directory of this
4  * distribution and at http://akaros.cs.berkeley.edu/files/Plan9License. No
5  * part of the UCB release of Plan 9, including this file, may be copied,
6  * modified, propagated, or distributed except according to the terms contained
7  * in the LICENSE file.
8  */
9
10 //#define DEBUG
11 /* proc on plan 9 has lots of capabilities, some of which we might
12  * want for akaros:
13  * debug control
14  * event tracing
15  * process control (no need for signal system call, etc.)
16  * textual status
17  * rather than excise code that won't work, I'm bracketing it with
18  * #if 0 until we know we don't want it
19  */
20 #include <vfs.h>
21 #include <kfs.h>
22 #include <slab.h>
23 #include <kmalloc.h>
24 #include <kref.h>
25 #include <string.h>
26 #include <stdio.h>
27 #include <assert.h>
28 #include <error.h>
29 #include <cpio.h>
30 #include <pmap.h>
31 #include <smp.h>
32 #include <arch/vmm/vmm.h>
33 #include <ros/vmm.h>
34
35 struct dev procdevtab;
36
37 static char *devname(void)
38 {
39         return procdevtab.name;
40 }
41
42 enum {
43         Qdir,
44         Qtrace,
45         Qtracepids,
46         Qns,
47         Qargs,
48         Qctl,
49         Qfd,
50         Qfpregs,
51         Qkregs,
52         Qmem,
53         Qnote,
54         Qnoteid,
55         Qnotepg,
56         Qproc,
57         Qregs,
58         Qsegment,
59         Qstatus,
60         Qstrace,
61         Qvmstatus,
62         Qtext,
63         Qwait,
64         Qprofile,
65         Qsyscall,
66         Qcore,
67 };
68
69 enum {
70         CMclose,
71         CMclosefiles,
72         CMfixedpri,
73         CMhang,
74         CMkill,
75         CMnohang,
76         CMnoswap,
77         CMpri,
78         CMprivate,
79         CMprofile,
80         CMstart,
81         CMstartstop,
82         CMstartsyscall,
83         CMstop,
84         CMtrace,
85         CMwaitstop,
86         CMwired,
87         CMcore,
88         CMvminit,
89         CMvmstart,
90         CMvmkill,
91         CMstraceme,
92         CMstraceall,
93         CMstraceoff,
94 };
95
96 enum {
97         Nevents = 0x4000,
98         Emask = Nevents - 1,
99         Ntracedpids = 1024,
100         STATSIZE = 8 + 1 + 10 + 1 + 6 + 2,
101 };
102
103 /*
104  * Status, fd, and ns are left fully readable (0444) because of their use in debugging,
105  * particularly on shared servers.
106  * Arguably, ns and fd shouldn't be readable; if you'd prefer, change them to 0000
107  */
108 struct dirtab procdir[] = {
109         {"args", {Qargs}, 0, 0660},
110         {"ctl", {Qctl}, 0, 0660},
111         {"fd", {Qfd}, 0, 0444},
112         {"fpregs", {Qfpregs}, 0, 0000},
113         //  {"kregs",   {Qkregs},   sizeof(Ureg),       0600},
114         {"mem", {Qmem}, 0, 0000},
115         {"note", {Qnote}, 0, 0000},
116         {"noteid", {Qnoteid}, 0, 0664},
117         {"notepg", {Qnotepg}, 0, 0000},
118         {"ns", {Qns}, 0, 0444},
119         {"proc", {Qproc}, 0, 0400},
120         //  {"regs",        {Qregs},    sizeof(Ureg),       0000},
121         {"segment", {Qsegment}, 0, 0444},
122         {"status", {Qstatus}, STATSIZE, 0444},
123         {"strace", {Qstrace}, 0, 0666},
124         {"vmstatus", {Qvmstatus}, 0, 0444},
125         {"text", {Qtext}, 0, 0000},
126         {"wait", {Qwait}, 0, 0400},
127         {"profile", {Qprofile}, 0, 0400},
128         {"syscall", {Qsyscall}, 0, 0400},
129         {"core", {Qcore}, 0, 0444},
130 };
131
132 static
133 struct cmdtab proccmd[] = {
134         {CMclose, "close", 2},
135         {CMclosefiles, "closefiles", 1},
136         {CMfixedpri, "fixedpri", 2},
137         {CMhang, "hang", 1},
138         {CMnohang, "nohang", 1},
139         {CMnoswap, "noswap", 1},
140         {CMkill, "kill", 1},
141         {CMpri, "pri", 2},
142         {CMprivate, "private", 1},
143         {CMprofile, "profile", 1},
144         {CMstart, "start", 1},
145         {CMstartstop, "startstop", 1},
146         {CMstartsyscall, "startsyscall", 1},
147         {CMstop, "stop", 1},
148         {CMtrace, "trace", 0},
149         {CMwaitstop, "waitstop", 1},
150         {CMwired, "wired", 2},
151         {CMcore, "core", 2},
152         {CMcore, "core", 2},
153         {CMcore, "core", 2},
154         {CMvminit, "vminit", 0},
155         {CMvmstart, "vmstart", 0},
156         {CMvmkill, "vmkill", 0},
157         {CMstraceme, "straceme", 0},
158         {CMstraceall, "straceall", 0},
159         {CMstraceoff, "straceoff", 0},
160 };
161
162 /*
163  * struct qids are, in path:
164  *       5 bits of file type (qids above) (old comment said 4 here)
165  *      23 bits of process slot number + 1 (pid + 1 is stored)
166  *           in vers,
167  *      32 bits of pid, for consistency checking
168  * If notepg, c->pgrpid.path is pgrp slot, .vers is noteid.
169  */
170 #define QSHIFT  5       /* location in qid of proc slot # */
171 #define SLOTBITS 23     /* number of bits in the slot */
172 #define QIDMASK ((1<<QSHIFT)-1)
173 #define SLOTMASK        (((1<<SLOTBITS)-1) << QSHIFT)
174
175 #define QID(q)          ((((uint32_t)(q).path)&QIDMASK)>>0)
176 #define SLOT(q)         (((((uint32_t)(q).path)&SLOTMASK)>>QSHIFT)-1)
177 #define PID(q)          ((q).vers)
178 #define NOTEID(q)       ((q).vers)
179
180 static void procctlreq(struct proc *, char *, int);
181 static int procctlmemio(struct proc *, uintptr_t, int, void *, int);
182 //static struct chan*   proctext(struct chan*, struct proc*);
183 //static Segment* txt2data(struct proc*, Segment*);
184 //static int    procstopped(void*);
185 static void mntscan(struct mntwalk *, struct proc *);
186
187 //static Traceevent *tevents;
188 static char *tpids, *tpidsc, *tpidse;
189 static spinlock_t tlock;
190 static int topens;
191 static int tproduced, tconsumed;
192 //static void notrace(struct proc*, int, int64_t);
193
194 //void (*proctrace)(struct proc*, int, int64_t) = notrace;
195
196 #if 0
197 static void profclock(Ureg * ur, Timer *)
198 {
199         Tos *tos;
200
201         if (up == NULL || current->state != Running)
202                 return;
203
204         /* user profiling clock */
205         if (userureg(ur)) {
206                 tos = (Tos *) (USTKTOP - sizeof(Tos));
207                 tos->clock += TK2MS(1);
208                 segclock(userpc(ur));
209         }
210 }
211 #endif
212 static int
213 procgen(struct chan *c, char *name, struct dirtab *tab, int unused, int s,
214                 struct dir *dp)
215 {
216         struct qid qid;
217         struct proc *p;
218         char *ename;
219
220         int pid;
221         uint32_t path, perm, len;
222         if (s == DEVDOTDOT) {
223                 mkqid(&qid, Qdir, 0, QTDIR);
224                 devdir(c, qid, devname(), 0, eve, 0555, dp);
225                 return 1;
226         }
227
228         if (c->qid.path == Qdir) {
229                 if (s == 0) {
230                         strlcpy(get_cur_genbuf(), "trace", GENBUF_SZ);
231                         mkqid(&qid, Qtrace, -1, QTFILE);
232                         devdir(c, qid, get_cur_genbuf(), 0, eve, 0444, dp);
233                         return 1;
234                 }
235                 if (s == 1) {
236                         strlcpy(get_cur_genbuf(), "tracepids", GENBUF_SZ);
237                         mkqid(&qid, Qtracepids, -1, QTFILE);
238                         devdir(c, qid, get_cur_genbuf(), 0, eve, 0444, dp);
239                         return 1;
240                 }
241                 s -= 2;
242                 if (name != NULL) {
243                         /* ignore s and use name to find pid */
244                         pid = strtol(name, &ename, 10);
245                         if (pid <= 0 || ename[0] != '\0')
246                                 return -1;
247                         p = pid2proc(pid);
248                         if (!p)
249                                 return -1;
250                         /* Need to update s, so that it's the correct 'index' for our proc
251                          * (aka, the pid).  We use s later when making the qid. */
252                         s = pid;
253                 } else {
254                         /* This is a shitty iterator, and the list isn't guaranteed to give
255                          * you the same ordering twice in a row. (procs come and go). */
256                         p = pid_nth(s);
257                         if (!p)
258                                 return -1;
259                         pid = p->pid;
260                 }
261
262                 snprintf(get_cur_genbuf(), GENBUF_SZ, "%u", pid);
263                 /*
264                  * String comparison is done in devwalk so
265                  * name must match its formatted pid.
266                  */
267                 if (name != NULL && strcmp(name, get_cur_genbuf()) != 0) {
268                         printk("pid-name mismatch, name: %s, pid %d\n", name, pid);
269                         kref_put(&p->p_kref);
270                         return -1;
271                 }
272                 mkqid(&qid, (s + 1) << QSHIFT, pid, QTDIR);
273                 devdir(c, qid, get_cur_genbuf(), 0, p->user, DMDIR | 0555, dp);
274                 kref_put(&p->p_kref);
275                 return 1;
276         }
277         if (c->qid.path == Qtrace) {
278                 strlcpy(get_cur_genbuf(), "trace", GENBUF_SZ);
279                 mkqid(&qid, Qtrace, -1, QTFILE);
280                 devdir(c, qid, get_cur_genbuf(), 0, eve, 0444, dp);
281                 return 1;
282         }
283         if (c->qid.path == Qtracepids) {
284                 strlcpy(get_cur_genbuf(), "tracepids", GENBUF_SZ);
285                 mkqid(&qid, Qtracepids, -1, QTFILE);
286                 devdir(c, qid, get_cur_genbuf(), 0, eve, 0444, dp);
287                 return 1;
288         }
289         if (s >= ARRAY_SIZE(procdir))
290                 return -1;
291         if (tab)
292                 panic("procgen");
293
294         tab = &procdir[s];
295         /* path is everything other than the QID part.  Not sure from the orig code
296          * if they wanted just the pid part (SLOTMASK) or everything above QID */
297         path = c->qid.path & ~QIDMASK;  /* slot component */
298         if ((p = pid2proc(SLOT(c->qid))) == NULL)
299                 return -1;
300         perm = 0444 | tab->perm;
301 #if 0
302         if (perm == 0)
303                 perm = p->procmode;
304         else    /* just copy read bits */
305                 perm |= p->procmode & 0444;
306 #endif
307
308         len = tab->length;
309 #if 0
310         switch (QID(c->qid)) {
311                 case Qwait:
312                         len = p->nwait; /* incorrect size, but >0 means there's something to read */
313                         break;
314                 case Qprofile:
315                         q = p->seg[TSEG];
316                         if (q && q->profile) {
317                                 len = (q->top - q->base) >> LRESPROF;
318                                 len *= sizeof(*q->profile);
319                         }
320                         break;
321         }
322 #endif
323
324         mkqid(&qid, path | tab->qid.path, c->qid.vers, QTFILE);
325         devdir(c, qid, tab->name, len, p->user, perm, dp);
326         kref_put(&p->p_kref);
327         return 1;
328 }
329
330 #if 0
331 static void notrace(struct proc *, Tevent, int64_t)
332 {
333 }
334
335 static spinlock_t tlck = SPINLOCK_INITIALIZER_IRQSAVE;
336
337 static void _proctrace(struct proc *p, Tevent etype, int64_t ts)
338 {
339         Traceevent *te;
340         int tp;
341
342         ilock(&tlck);
343         if (p->trace == 0 || topens == 0 || tproduced - tconsumed >= Nevents) {
344                 iunlock(&tlck);
345                 return;
346         }
347         tp = tproduced++;
348         iunlock(&tlck);
349
350         te = &tevents[tp & Emask];
351         te->pid = p->pid;
352         te->etype = etype;
353         if (ts == 0)
354                 te->time = todget(NULL);
355         else
356                 te->time = ts;
357         te->core = m->machno;
358 }
359
360 void proctracepid(struct proc *p)
361 {
362         if (p->trace == 1 && proctrace != notrace) {
363                 p->trace = 2;
364                 ilock(&tlck);
365                 tpidsc = seprint(tpidsc, tpidse, "%d %s\n", p->pid, p->text);
366                 iunlock(&tlck);
367         }
368 }
369
370 #endif
371 static void procinit(void)
372 {
373 #if 0
374         if (conf.nproc >= (SLOTMASK >> QSHIFT) - 1)
375                 printd("warning: too many procs for devproc\n");
376         addclock0link((void (*)(void))profclock, 113);  /* Relative prime to HZ */
377 #endif
378 }
379
380 static struct chan *procattach(char *spec)
381 {
382         return devattach(devname(), spec);
383 }
384
385 static struct walkqid *procwalk(struct chan *c, struct chan *nc, char **name,
386                                                                 int nname)
387 {
388         return devwalk(c, nc, name, nname, 0, 0, procgen);
389 }
390
391 static int procstat(struct chan *c, uint8_t * db, int n)
392 {
393         return devstat(c, db, n, 0, 0, procgen);
394 }
395
396 /*
397  *  none can't read or write state on other
398  *  processes.  This is to contain access of
399  *  servers running as none should they be
400  *  subverted by, for example, a stack attack.
401  */
402 static void nonone(struct proc *p)
403 {
404         return;
405 #if 0
406         if (p == up)
407                 return;
408         if (strcmp(current->user, "none") != 0)
409                 return;
410         if (iseve())
411                 return;
412         error(EPERM, ERROR_FIXME);
413 #endif
414 }
415
416 static struct chan *procopen(struct chan *c, int omode)
417 {
418         ERRSTACK(2);
419         struct proc *p;
420         struct pgrp *pg;
421         struct chan *tc;
422         int pid;
423
424         if (c->qid.type & QTDIR)
425                 return devopen(c, omode, 0, 0, procgen);
426
427         if (QID(c->qid) == Qtrace) {
428                 error(ENOSYS, ERROR_FIXME);
429 #if 0
430                 if (omode != OREAD)
431                         error(EPERM, ERROR_FIXME);
432                 lock(&tlock);
433                 if (waserror()) {
434                         unlock(&tlock);
435                         nexterror();
436                 }
437                 if (topens > 0)
438                         error(EFAIL, "already open");
439                 topens++;
440                 if (tevents == NULL) {
441                         tevents = (Traceevent *) kzmalloc(sizeof(Traceevent) * Nevents,
442                                                                                           KMALLOC_WAIT);
443                         if (tevents == NULL)
444                                 error(ENOMEM, ERROR_FIXME);
445                         tpids = kzmalloc(Ntracedpids * 20, KMALLOC_WAIT);
446                         if (tpids == NULL) {
447                                 kfree(tpids);
448                                 tpids = NULL;
449                                 error(ENOMEM, ERROR_FIXME);
450                         }
451                         tpidsc = tpids;
452                         tpidse = tpids + Ntracedpids * 20;
453                         *tpidsc = 0;
454                         tproduced = tconsumed = 0;
455                 }
456                 proctrace = _proctrace;
457                 poperror();
458                 unlock(&tlock);
459
460                 c->mode = openmode(omode);
461                 c->flag |= COPEN;
462                 c->offset = 0;
463                 return c;
464 #endif
465         }
466         if (QID(c->qid) == Qtracepids) {
467                 error(ENOSYS, ERROR_FIXME);
468 #if 0
469                 if (omode != OREAD)
470                         error(EPERM, ERROR_FIXME);
471                 c->mode = openmode(omode);
472                 c->flag |= COPEN;
473                 c->offset = 0;
474                 return c;
475 #endif
476         }
477         if ((p = pid2proc(SLOT(c->qid))) == NULL)
478                 error(ESRCH, ERROR_FIXME);
479         //qlock(&p->debug);
480         if (waserror()) {
481                 //qunlock(&p->debug);
482                 kref_put(&p->p_kref);
483                 nexterror();
484         }
485         pid = PID(c->qid);
486         if (p->pid != pid)
487                 error(ESRCH, ERROR_FIXME);
488
489         omode = openmode(omode);
490
491         switch (QID(c->qid)) {
492                 case Qtext:
493                         error(ENOSYS, ERROR_FIXME);
494 /*
495                         if (omode != OREAD)
496                                 error(EPERM, ERROR_FIXME);
497                         tc = proctext(c, p);
498                         tc->offset = 0;
499                         poperror();
500                         qunlock(&p->debug);
501                         kref_put(&p->p_kref);
502                         cclose(c);
503                         return tc;
504 */
505                 case Qproc:
506                 case Qsegment:
507                 case Qprofile:
508                 case Qfd:
509                         if (omode != O_READ)
510                                 error(EPERM, ERROR_FIXME);
511                         break;
512
513                 case Qnote:
514 //          if (p->privatemem)
515                         error(EPERM, ERROR_FIXME);
516                         break;
517
518                 case Qmem:
519 //          if (p->privatemem)
520                         error(EPERM, ERROR_FIXME);
521                         //nonone(p);
522                         break;
523
524                 case Qargs:
525                 case Qnoteid:
526                 case Qwait:
527                 case Qregs:
528                 case Qfpregs:
529                 case Qkregs:
530                 case Qsyscall:
531                 case Qcore:
532                         nonone(p);
533                         break;
534
535                 case Qns:
536                         if (omode != O_READ)
537                                 error(EPERM, ERROR_FIXME);
538                         c->aux = kzmalloc(sizeof(struct mntwalk), KMALLOC_WAIT);
539                         break;
540                 case Qstatus:
541                 case Qvmstatus:
542                 case Qctl:
543                         break;
544
545                 case Qstrace:
546                         if (!p->strace)
547                                 error(ENOENT, "Process does not have tracing enabled");
548                         /* the ref we are upping is the one we put in __proc_free, which is
549                          * the one we got from CMstrace{on,me}.  We have a ref on p, so we
550                          * know we won't free until we decref the proc. */
551                         kref_get(&p->strace->users, 1);
552                         c->aux = p->strace;
553                         break;
554                 case Qnotepg:
555                         error(ENOSYS, ERROR_FIXME);
556 #if 0
557                         nonone(p);
558                         pg = p->pgrp;
559                         if (pg == NULL)
560                                 error(ESRCH, ERROR_FIXME);
561                         if (omode != OWRITE || pg->pgrpid == 1)
562                                 error(EPERM, ERROR_FIXME);
563                         c->pgrpid.path = pg->pgrpid + 1;
564                         c->pgrpid.vers = p->noteid;
565 #endif
566                         break;
567
568                 default:
569                         printk("procopen %#llux\n", c->qid.path);
570                         error(EINVAL, ERROR_FIXME);
571         }
572
573         /* Affix pid to qid */
574 //  if (p->state != Dead)
575         c->qid.vers = p->pid;
576         /* make sure the process slot didn't get reallocated while we were playing */
577         //coherence();
578         /* TODO: think about what we really want here.  In akaros, we wouldn't have
579          * our pid changed like that. */
580         if (p->pid != pid)
581                 error(ESRCH, ERROR_FIXME);
582
583         tc = devopen(c, omode, 0, 0, procgen);
584         poperror();
585         //qunlock(&p->debug);
586         kref_put(&p->p_kref);
587         return tc;
588 }
589
590 static int procwstat(struct chan *c, uint8_t * db, int n)
591 {
592         ERRSTACK(2);
593         error(ENOSYS, ERROR_FIXME);
594 #if 0
595         struct proc *p;
596         struct dir *d;
597
598         if (c->qid.type & QTDIR)
599                 error(EPERM, ERROR_FIXME);
600
601         if (QID(c->qid) == Qtrace)
602                 return devwstat(c, db, n);
603
604         if ((p = pid2proc(SLOT(c->qid))) == NULL)
605                 error(ESRCH, ERROR_FIXME);
606         nonone(p);
607         d = NULL;
608         qlock(&p->debug);
609         if (waserror()) {
610                 qunlock(&p->debug);
611                 kref_put(&p->p_kref);
612                 kfree(d);
613                 nexterror();
614         }
615
616         if (p->pid != PID(c->qid))
617                 error(ESRCH, ERROR_FIXME);
618
619         if (strcmp(current->user, p->user) != 0 && strcmp(current->user, eve) != 0)
620                 error(EPERM, ERROR_FIXME);
621
622         d = kzmalloc(sizeof(struct dir) + n, KMALLOC_WAIT);
623         n = convM2D(db, n, &d[0], (char *)&d[1]);
624         if (n == 0)
625                 error(ENOENT, ERROR_FIXME);
626         if (!emptystr(d->uid) && strcmp(d->uid, p->user) != 0) {
627                 if (strcmp(current->user, eve) != 0)
628                         error(EPERM, ERROR_FIXME);
629                 else
630                         kstrdup(&p->user, d->uid);
631         }
632         if (d->mode != ~0UL)
633                 p->procmode = d->mode & 0777;
634
635         poperror();
636         qunlock(&p->debug);
637         kref_put(&p->p_kref);
638         kfree(d);
639
640         return n;
641 #endif
642 }
643
644 #if 0
645 static long procoffset(long offset, char *va, int *np)
646 {
647         if (offset > 0) {
648                 offset -= *np;
649                 if (offset < 0) {
650                         memmove(va, va + *np + offset, -offset);
651                         *np = -offset;
652                 } else
653                         *np = 0;
654         }
655         return offset;
656 }
657
658 static int procqidwidth(struct chan *c)
659 {
660         char buf[32];
661
662         return sprint(buf, "%lu", c->qid.vers);
663 }
664
665 int procfdprint(struct chan *c, int fd, int w, char *s, int ns)
666 {
667         int n;
668
669         if (w == 0)
670                 w = procqidwidth(c);
671         n = snprint(s, ns,
672                                 "%3d %.2s %C %4ud (%.16llux %*lud %.2ux) %5ld %8lld %s\n", fd,
673                                 &"r w rw"[(c->mode & 3) << 1], c->dev->dc, c->devno,
674                                 c->qid.path, w, c->qid.vers, c->qid.type, c->iounit, c->offset,
675                                 c->name->s);
676         return n;
677 }
678
679 static int procfds(struct proc *p, char *va, int count, long offset)
680 {
681         ERRSTACK(2);
682         struct fgrp *f;
683         struct chan *c;
684         char buf[256];
685         int n, i, w, ww;
686         char *a;
687
688         /* print to buf to avoid holding fgrp lock while writing to user space */
689         if (count > sizeof buf)
690                 count = sizeof buf;
691         a = buf;
692
693         qlock(&p->debug);
694         f = p->fgrp;
695         if (f == NULL) {
696                 qunlock(&p->debug);
697                 return 0;
698         }
699         lock(f);
700         if (waserror()) {
701                 unlock(f);
702                 qunlock(&p->debug);
703                 nexterror();
704         }
705
706         n = readstr(0, a, count, p->dot->name->s);
707         n += snprint(a + n, count - n, "\n");
708         offset = procoffset(offset, a, &n);
709         /* compute width of qid.path */
710         w = 0;
711         for (i = 0; i <= f->maxfd; i++) {
712                 c = f->fd[i];
713                 if (c == NULL)
714                         continue;
715                 ww = procqidwidth(c);
716                 if (ww > w)
717                         w = ww;
718         }
719         for (i = 0; i <= f->maxfd; i++) {
720                 c = f->fd[i];
721                 if (c == NULL)
722                         continue;
723                 n += procfdprint(c, i, w, a + n, count - n);
724                 offset = procoffset(offset, a, &n);
725         }
726         poperror();
727         unlock(f);
728         qunlock(&p->debug);
729
730         /* copy result to user space, now that locks are released */
731         memmove(va, buf, n);
732
733         return n;
734 }
735 #endif
736 static void procclose(struct chan *c)
737 {
738         if (QID(c->qid) == Qtrace) {
739                 spin_lock(&tlock);
740                 if (topens > 0)
741                         topens--;
742                 /* ??
743                    if(topens == 0)
744                    proctrace = notrace;
745                  */
746                 spin_unlock(&tlock);
747         }
748         if (QID(c->qid) == Qsyscall) {
749                 if (c->aux)
750                         qclose(c->aux);
751                 c->aux = NULL;
752         }
753         if (QID(c->qid) == Qns && c->aux != 0)
754                 kfree(c->aux);
755         if (QID(c->qid) == Qstrace && c->aux != 0) {
756                 struct strace *s = c->aux;
757
758                 kref_put(&s->users);
759                 c->aux = NULL;
760         }
761 }
762
763 void int2flag(int flag, char *s)
764 {
765         if (flag == 0) {
766                 *s = '\0';
767                 return;
768         }
769         *s++ = '-';
770         if (flag & MAFTER)
771                 *s++ = 'a';
772         if (flag & MBEFORE)
773                 *s++ = 'b';
774         if (flag & MCREATE)
775                 *s++ = 'c';
776         if (flag & MCACHE)
777                 *s++ = 'C';
778         *s = '\0';
779 }
780
781 #if 0
782 static char *argcpy(char *s, char *p)
783 {
784         char *t, *tp, *te;
785         int n;
786
787         n = p - s;
788         if (n > 128)
789                 n = 128;
790         if (n <= 0) {
791                 t = kzmalloc(1, KMALLOC_WAIT);
792                 *t = 0;
793                 return t;
794         }
795         t = kzmalloc(n, KMALLOC_WAIT);
796         tp = t;
797         te = t + n;
798
799         while (tp + 1 < te) {
800                 for (p--; p > s && p[-1] != 0; p--) ;
801                 tp = seprint(tp, te, "%q ", p);
802                 if (p == s)
803                         break;
804         }
805         if (*tp == ' ')
806                 *tp = 0;
807         return t;
808 }
809
810 static int procargs(struct proc *p, char *buf, int nbuf)
811 {
812         char *s;
813
814         if (p->setargs == 0) {
815                 s = argcpy(p->args, p->args + p->nargs);
816                 kfree(p->args);
817                 p->nargs = strlen(s);
818                 p->args = s;
819                 p->setargs = 1;
820         }
821         return snprint(buf, nbuf, "%s", p->args);
822 }
823
824 static int eventsavailable(void *)
825 {
826         return tproduced > tconsumed;
827 }
828 #endif
829 static long procread(struct chan *c, void *va, long n, int64_t off)
830 {
831         ERRSTACK(5);
832         struct proc *p;
833         long l, r;
834         int i, j, navail, pid, rsize;
835         char flag[10], *sps, *srv, statbuf[512];
836         uintptr_t offset, u;
837         int tesz;
838         uint8_t *rptr;
839         struct mntwalk *mw;
840         struct strace *s;
841
842         if (c->qid.type & QTDIR) {
843                 int nn;
844                 printd("procread: dir\n");
845                 nn = devdirread(c, va, n, 0, 0, procgen);
846                 printd("procread: %d\n", nn);
847                 return nn;
848         }
849
850         offset = off;
851 #if 0
852         if (QID(c->qid) == Qtrace) {
853                 if (!eventsavailable(NULL))
854                         return 0;
855
856                 rptr = va;
857                 tesz = BIT32SZ + BIT32SZ + BIT64SZ + BIT32SZ;
858                 navail = tproduced - tconsumed;
859                 if (navail > n / tesz)
860                         navail = n / tesz;
861                 while (navail > 0) {
862                         PBIT32(rptr, tevents[tconsumed & Emask].pid);
863                         rptr += BIT32SZ;
864                         PBIT32(rptr, tevents[tconsumed & Emask].etype);
865                         rptr += BIT32SZ;
866                         PBIT64(rptr, tevents[tconsumed & Emask].time);
867                         rptr += BIT64SZ;
868                         PBIT32(rptr, tevents[tconsumed & Emask].core);
869                         rptr += BIT32SZ;
870                         tconsumed++;
871                         navail--;
872                 }
873                 return rptr - (uint8_t *) va;
874         }
875
876         if (QID(c->qid) == Qtracepids)
877                 if (tpids == NULL)
878                         return 0;
879                 else
880                         return readstr(off, va, n, tpids);
881 #endif
882         if ((p = pid2proc(SLOT(c->qid))) == NULL)
883                 error(ESRCH, "%d: no such process", SLOT(c->qid));
884         if (p->pid != PID(c->qid)) {
885                 kref_put(&p->p_kref);
886                 error(ESRCH, "weird: p->pid is %d, PID(c->qid) is %d: mismatch",
887                       p->pid, PID(c->qid));
888         }
889         switch (QID(c->qid)) {
890                 default:
891                         kref_put(&p->p_kref);
892                         break;
893 #if 0
894 #warning check refcnting in here
895                 case Qargs:
896                         qlock(&p->debug);
897                         j = procargs(p, current->genbuf, sizeof current->genbuf);
898                         qunlock(&p->debug);
899                         kref_put(&p->p_kref);
900                         if (offset >= j)
901                                 return 0;
902                         if (offset + n > j)
903                                 n = j - offset;
904                         memmove(va, &current->genbuf[offset], n);
905                         return n;
906
907                 case Qsyscall:
908                         if (p->syscalltrace == NULL)
909                                 return 0;
910                         return readstr(offset, va, n, p->syscalltrace);
911
912                 case Qcore:
913                         i = 0;
914                         ac = p->ac;
915                         wired = p->wired;
916                         if (ac != NULL)
917                                 i = ac->machno;
918                         else if (wired != NULL)
919                                 i = wired->machno;
920                         snprint(statbuf, sizeof statbuf, "%d\n", i);
921                         return readstr(offset, va, n, statbuf);
922
923                 case Qmem:
924                         if (offset < KZERO
925                                 || (offset >= USTKTOP - USTKSIZE && offset < USTKTOP)) {
926                                 r = procctlmemio(p, offset, n, va, 1);
927                                 kref_put(&p->p_kref);
928                                 return r;
929                         }
930
931                         if (!iseve()) {
932                                 kref_put(&p->p_kref);
933                                 error(EPERM, ERROR_FIXME);
934                         }
935
936                         /* validate kernel addresses */
937                         if (offset < PTR2UINT(end)) {
938                                 if (offset + n > PTR2UINT(end))
939                                         n = PTR2UINT(end) - offset;
940                                 memmove(va, UINT2PTR(offset), n);
941                                 kref_put(&p->p_kref);
942                                 return n;
943                         }
944                         for (i = 0; i < nelem(conf.mem); i++) {
945                                 cm = &conf.mem[i];
946                                 /* klimit-1 because klimit might be zero! */
947                                 if (cm->kbase <= offset && offset <= cm->klimit - 1) {
948                                         if (offset + n >= cm->klimit - 1)
949                                                 n = cm->klimit - offset;
950                                         memmove(va, UINT2PTR(offset), n);
951                                         kref_put(&p->p_kref);
952                                         return n;
953                                 }
954                         }
955                         kref_put(&p->p_kref);
956                         error(EINVAL, ERROR_FIXME);
957
958                 case Qprofile:
959                         s = p->seg[TSEG];
960                         if (s == 0 || s->profile == 0)
961                                 error(EFAIL, "profile is off");
962                         i = (s->top - s->base) >> LRESPROF;
963                         i *= sizeof(*s->profile);
964                         if (offset >= i) {
965                                 kref_put(&p->p_kref);
966                                 return 0;
967                         }
968                         if (offset + n > i)
969                                 n = i - offset;
970                         memmove(va, ((char *)s->profile) + offset, n);
971                         kref_put(&p->p_kref);
972                         return n;
973
974                 case Qnote:
975                         qlock(&p->debug);
976                         if (waserror()) {
977                                 qunlock(&p->debug);
978                                 kref_put(&p->p_kref);
979                                 nexterror();
980                         }
981                         if (p->pid != PID(c->qid))
982                                 error(ESRCH, ERROR_FIXME);
983                         if (n < 1)      /* must accept at least the '\0' */
984                                 error(ENAMETOOLONG, ERROR_FIXME);
985                         if (p->nnote == 0)
986                                 n = 0;
987                         else {
988                                 i = strlen(p->note[0].msg) + 1;
989                                 if (i > n)
990                                         i = n;
991                                 rptr = va;
992                                 memmove(rptr, p->note[0].msg, i);
993                                 rptr[i - 1] = '\0';
994                                 p->nnote--;
995                                 memmove(p->note, p->note + 1, p->nnote * sizeof(Note));
996                                 n = i;
997                         }
998                         if (p->nnote == 0)
999                                 p->notepending = 0;
1000                         poperror();
1001                         qunlock(&p->debug);
1002                         kref_put(&p->p_kref);
1003                         return n;
1004
1005                 case Qproc:
1006                         if (offset >= sizeof(struct proc)) {
1007                                 kref_put(&p->p_kref);
1008                                 return 0;
1009                         }
1010                         if (offset + n > sizeof(struct proc))
1011                                 n = sizeof(struct proc) - offset;
1012                         memmove(va, ((char *)p) + offset, n);
1013                         kref_put(&p->p_kref);
1014                         return n;
1015
1016                 case Qregs:
1017                         rptr = (uint8_t *) p->dbgreg;
1018                         rsize = sizeof(Ureg);
1019 regread:
1020                         if (rptr == 0) {
1021                                 kref_put(&p->p_kref);
1022                                 error(ENODATA, ERROR_FIXME);
1023                         }
1024                         if (offset >= rsize) {
1025                                 kref_put(&p->p_kref);
1026                                 return 0;
1027                         }
1028                         if (offset + n > rsize)
1029                                 n = rsize - offset;
1030                         memmove(va, rptr + offset, n);
1031                         kref_put(&p->p_kref);
1032                         return n;
1033
1034                 case Qkregs:
1035                         memset(&kur, 0, sizeof(Ureg));
1036                         setkernur(&kur, p);
1037                         rptr = (uint8_t *) & kur;
1038                         rsize = sizeof(Ureg);
1039                         goto regread;
1040
1041                 case Qfpregs:
1042                         r = fpudevprocio(p, va, n, offset, 0);
1043                         kref_put(&p->p_kref);
1044                         return r;
1045
1046                 case Qstatus:
1047                         if (offset >= STATSIZE) {
1048                                 kref_put(&p->p_kref);
1049                                 return 0;
1050                         }
1051                         if (offset + n > STATSIZE)
1052                                 n = STATSIZE - offset;
1053
1054                         sps = p->psstate;
1055                         if (sps == 0)
1056                                 sps = statename[p->state];
1057                         memset(statbuf, ' ', sizeof statbuf);
1058                         j = 2 * KNAMELEN + 12;
1059                         snprint(statbuf, j + 1, "%-*.*s%-*.*s%-12.11s",
1060                                         KNAMELEN, KNAMELEN - 1, p->text,
1061                                         KNAMELEN, KNAMELEN - 1, p->user, sps);
1062
1063                         for (i = 0; i < 6; i++) {
1064                                 l = p->time[i];
1065                                 if (i == TReal)
1066                                         l = sys->ticks - l;
1067                                 l = TK2MS(l);
1068                                 readnum(0, statbuf + j + NUMSIZE * i, NUMSIZE, l, NUMSIZE);
1069                         }
1070                         /* ignore stack, which is mostly non-existent */
1071                         u = 0;
1072                         for (i = 1; i < NSEG; i++) {
1073                                 s = p->seg[i];
1074                                 if (s)
1075                                         u += s->top - s->base;
1076                         }
1077                         readnum(0, statbuf + j + NUMSIZE * 6, NUMSIZE, u >> 10u, NUMSIZE);      /* wrong size */
1078                         readnum(0, statbuf + j + NUMSIZE * 7, NUMSIZE, p->basepri, NUMSIZE);
1079                         readnum(0, statbuf + j + NUMSIZE * 8, NUMSIZE, p->priority,
1080                                         NUMSIZE);
1081
1082                         /*
1083                          * NIX: added # of traps, syscalls, and iccs
1084                          */
1085                         readnum(0, statbuf + j + NUMSIZE * 9, NUMSIZE, p->ntrap, NUMSIZE);
1086                         readnum(0, statbuf + j + NUMSIZE * 10, NUMSIZE, p->nintr, NUMSIZE);
1087                         readnum(0, statbuf + j + NUMSIZE * 11, NUMSIZE, p->nsyscall,
1088                                         NUMSIZE);
1089                         readnum(0, statbuf + j + NUMSIZE * 12, NUMSIZE, p->nicc, NUMSIZE);
1090                         readnum(0, statbuf + j + NUMSIZE * 13, NUMSIZE, p->nactrap,
1091                                         NUMSIZE);
1092                         readnum(0, statbuf + j + NUMSIZE * 14, NUMSIZE, p->nacsyscall,
1093                                         NUMSIZE);
1094                         memmove(va, statbuf + offset, n);
1095                         kref_put(&p->p_kref);
1096                         return n;
1097
1098                 case Qsegment:
1099                         j = 0;
1100                         for (i = 0; i < NSEG; i++) {
1101                                 sg = p->seg[i];
1102                                 if (sg == 0)
1103                                         continue;
1104                                 j += sprint(statbuf + j, "%-6s %c%c %p %p %4d\n",
1105                                                         sname[sg->type & SG_TYPE],
1106                                                         sg->type & SG_RONLY ? 'R' : ' ',
1107                                                         sg->profile ? 'P' : ' ',
1108                                                         sg->base, sg->top, sg->ref);
1109                         }
1110                         kref_put(&p->p_kref);
1111                         if (offset >= j)
1112                                 return 0;
1113                         if (offset + n > j)
1114                                 n = j - offset;
1115                         if (n == 0 && offset == 0)
1116                                 exhausted("segments");
1117                         memmove(va, &statbuf[offset], n);
1118                         return n;
1119
1120                 case Qwait:
1121                         if (!canqlock(&p->qwaitr)) {
1122                                 kref_put(&p->p_kref);
1123                                 error(EBUSY, ERROR_FIXME);
1124                         }
1125
1126                         if (waserror()) {
1127                                 qunlock(&p->qwaitr);
1128                                 kref_put(&p->p_kref);
1129                                 nexterror();
1130                         }
1131
1132                         lock(&p->exl);
1133                         if (up == p && p->nchild == 0 && p->waitq == 0) {
1134                                 unlock(&p->exl);
1135                                 error(ECHILD, ERROR_FIXME);
1136                         }
1137                         pid = p->pid;
1138                         while (p->waitq == 0) {
1139                                 unlock(&p->exl);
1140                                 rendez_sleep(&p->waitr, haswaitq, p);
1141                                 if (p->pid != pid)
1142                                         error(ESRCH, ERROR_FIXME);
1143                                 lock(&p->exl);
1144                         }
1145                         wq = p->waitq;
1146                         p->waitq = wq->next;
1147                         p->nwait--;
1148                         unlock(&p->exl);
1149
1150                         poperror();
1151                         qunlock(&p->qwaitr);
1152                         kref_put(&p->p_kref);
1153                         n = snprint(va, n, "%d %lu %lud %lud %q",
1154                                                 wq->w.pid,
1155                                                 wq->w.time[TUser], wq->w.time[TSys], wq->w.time[TReal],
1156                                                 wq->w.msg);
1157                         kfree(wq);
1158                         return n;
1159 #endif
1160                 case Qstrace:
1161                         s = c->aux;
1162                         /* We need to decref, so that p can get freed while we are blocked
1163                          * on the qread.  in proc_free, the strace is released that will
1164                          * qhangup that will wake us up. */
1165                         kref_put(&p->p_kref);
1166                         n = qread(s->q, va, n);
1167                         return n;
1168
1169                 case Qstatus:{
1170                                 /* the old code grew the stack and was hideous.
1171                                  * status is not a high frequency operation; just malloc. */
1172                                 char *buf = kmalloc(4096, KMALLOC_WAIT);
1173                                 char *s = buf, *e = buf + 4096;
1174                                 int i;
1175
1176                                 s = seprintf(s, e,
1177                                          "%8d %-*s %-10s %6d", p->pid, PROC_PROGNAME_SZ,
1178                                          p->progname, procstate2str(p->state),
1179                                          p->ppid);
1180                                 if (p->strace)
1181                                         s = seprintf(s, e, " %d trace users %d traced procs",
1182                                                      kref_refcnt(&p->strace->users),
1183                                                      kref_refcnt(&p->strace->procs));
1184                                 kref_put(&p->p_kref);
1185                                 i = readstr(off, va, n, buf);
1186                                 kfree(buf);
1187                                 return i;
1188                         }
1189
1190                 case Qvmstatus:
1191                         {
1192                                 char buf[50*65 + 2];
1193                                 int i, offset;
1194                                 offset=0;
1195                                 offset += snprintf(buf+offset, sizeof(buf)-offset, "{\n");
1196                                 for (i = 0; i < 65; i++) {
1197                                         if (p->vmm.vmexits[i] != 0) {
1198                                                 offset += snprintf(buf+offset, sizeof(buf)-offset,
1199                                                                    "\"%s\":\"%lld\",\n",
1200                                                                    VMX_EXIT_REASON_NAMES[i],
1201                                                                    p->vmm.vmexits[i]);
1202                                         }
1203                                 }
1204                                 offset += snprintf(buf+offset, sizeof(buf)-offset, "}\n");
1205                                 kref_put(&p->p_kref);
1206                                 return readstr(off, va, n, buf);
1207                         }
1208                 case Qns:
1209                         //qlock(&p->debug);
1210                         if (waserror()) {
1211                                 //qunlock(&p->debug);
1212                                 kref_put(&p->p_kref);
1213                                 nexterror();
1214                         }
1215                         if (p->pgrp == NULL || p->pid != PID(c->qid))
1216                                 error(ESRCH, ERROR_FIXME);
1217                         mw = c->aux;
1218                         if (mw->cddone) {
1219                                 poperror();
1220                                 //qunlock(&p->debug);
1221                                 kref_put(&p->p_kref);
1222                                 return 0;
1223                         }
1224                         mntscan(mw, p);
1225                         if (mw->mh == 0) {
1226                                 mw->cddone = 1;
1227                                 i = snprintf(va, n, "cd %s\n", p->dot->name->s);
1228                                 poperror();
1229                                 //qunlock(&p->debug);
1230                                 kref_put(&p->p_kref);
1231                                 return i;
1232                         }
1233                         int2flag(mw->cm->mflag, flag);
1234                         if (strcmp(mw->cm->to->name->s, "#M") == 0) {
1235                                 srv = srvname(mw->cm->to->mchan);
1236                                 i = snprintf(va, n, "mount %s %s %s %s\n", flag,
1237                                                          srv == NULL ? mw->cm->to->mchan->name->s : srv,
1238                                                          mw->mh->from->name->s,
1239                                                          mw->cm->spec ? mw->cm->spec : "");
1240                                 kfree(srv);
1241                         } else
1242                                 i = snprintf(va, n, "bind %s %s %s\n", flag,
1243                                                          mw->cm->to->name->s, mw->mh->from->name->s);
1244                         poperror();
1245                         //qunlock(&p->debug);
1246                         kref_put(&p->p_kref);
1247                         return i;
1248 #if 0
1249                 case Qnoteid:
1250                         r = readnum(offset, va, n, p->noteid, NUMSIZE);
1251                         kref_put(&p->p_kref);
1252                         return r;
1253                 case Qfd:
1254                         r = procfds(p, va, n, offset);
1255                         kref_put(&p->p_kref);
1256                         return r;
1257 #endif
1258         }
1259
1260
1261         error(EINVAL, "QID %d did not match any QIDs for #proc", QID(c->qid));
1262         return 0;       /* not reached */
1263 }
1264
1265 static void mntscan(struct mntwalk *mw, struct proc *p)
1266 {
1267         struct pgrp *pg;
1268         struct mount *t;
1269         struct mhead *f;
1270         int best, i, last, nxt;
1271
1272         pg = p->pgrp;
1273         rlock(&pg->ns);
1274
1275         nxt = 0;
1276         best = (int)(~0U >> 1); /* largest 2's complement int */
1277
1278         last = 0;
1279         if (mw->mh)
1280                 last = mw->cm->mountid;
1281
1282         for (i = 0; i < MNTHASH; i++) {
1283                 for (f = pg->mnthash[i]; f; f = f->hash) {
1284                         for (t = f->mount; t; t = t->next) {
1285                                 if (mw->mh == 0 || (t->mountid > last && t->mountid < best)) {
1286                                         mw->cm = t;
1287                                         mw->mh = f;
1288                                         best = mw->cm->mountid;
1289                                         nxt = 1;
1290                                 }
1291                         }
1292                 }
1293         }
1294         if (nxt == 0)
1295                 mw->mh = 0;
1296
1297         runlock(&pg->ns);
1298 }
1299
1300 static long procwrite(struct chan *c, void *va, long n, int64_t off)
1301 {
1302         ERRSTACK(2);
1303
1304         struct proc *p, *t;
1305         int i, id, l;
1306         char *args;
1307         uintptr_t offset;
1308
1309         if (c->qid.type & QTDIR)
1310                 error(EISDIR, ERROR_FIXME);
1311
1312         if ((p = pid2proc(SLOT(c->qid))) == NULL)
1313                 error(ESRCH, ERROR_FIXME);
1314
1315         if (waserror()) {
1316                 kref_put(&p->p_kref);
1317                 nexterror();
1318         }
1319         if (p->pid != PID(c->qid))
1320                 error(ESRCH, ERROR_FIXME);
1321
1322         offset = off;
1323
1324         switch (QID(c->qid)) {
1325 #if 0
1326                 case Qargs:
1327                         if (n == 0)
1328                                 error(EINVAL, ERROR_FIXME);
1329                         if (n >= sizeof buf - strlen(p->text) - 1)
1330                                 error(E2BIG, ERROR_FIXME);
1331                         l = snprintf(buf, sizeof buf, "%s [%s]", p->text, (char *)va);
1332                         args = kzmalloc(l + 1, KMALLOC_WAIT);
1333                         if (args == NULL)
1334                                 error(ENOMEM, ERROR_FIXME);
1335                         memmove(args, buf, l);
1336                         args[l] = 0;
1337                         kfree(p->args);
1338                         p->nargs = l;
1339                         p->args = args;
1340                         p->setargs = 1;
1341                         break;
1342
1343                 case Qmem:
1344                         if (p->state != Stopped)
1345                                 error(EINVAL, ERROR_FIXME);
1346
1347                         n = procctlmemio(p, offset, n, va, 0);
1348                         break;
1349
1350                 case Qregs:
1351                         if (offset >= sizeof(Ureg))
1352                                 n = 0;
1353                         else if (offset + n > sizeof(Ureg))
1354                                 n = sizeof(Ureg) - offset;
1355                         if (p->dbgreg == 0)
1356                                 error(ENODATA, ERROR_FIXME);
1357                         setregisters(p->dbgreg, (char *)(p->dbgreg) + offset, va, n);
1358                         break;
1359
1360                 case Qfpregs:
1361                         n = fpudevprocio(p, va, n, offset, 1);
1362                         break;
1363 #endif
1364                 case Qctl:
1365                         procctlreq(p, va, n);
1366                         break;
1367
1368                 /* this lets your write a marker into the data stream,
1369                  * which is a very powerful tool. */
1370                 case Qstrace:
1371                         assert(c->aux);
1372                         /* it is possible that the q hungup and is closed.  that would be
1373                          * the case if all of the procs closed and decref'd.  if the q is
1374                          * closed, qwrite() will throw an error. */
1375                         n = qwrite(((struct strace*)c->aux)->q, va, n);
1376                         break;
1377                 default:
1378                         error(EFAIL, "unknown qid %#llux in procwrite\n", c->qid.path);
1379         }
1380         poperror();
1381         kref_put(&p->p_kref);
1382         return n;
1383 }
1384
1385 struct dev procdevtab __devtab = {
1386         .name = "proc",
1387
1388         .reset = devreset,
1389         .init = procinit,
1390         .shutdown = devshutdown,
1391         .attach = procattach,
1392         .walk = procwalk,
1393         .stat = procstat,
1394         .open = procopen,
1395         .create = devcreate,
1396         .close = procclose,
1397         .read = procread,
1398         .bread = devbread,
1399         .write = procwrite,
1400         .bwrite = devbwrite,
1401         .remove = devremove,
1402         .wstat = procwstat,
1403         .power = devpower,
1404         .chaninfo = devchaninfo,
1405 };
1406
1407 #if 0
1408 static struct chan *proctext(struct chan *c, struct proc *p)
1409 {
1410         ERRSTACK(2);
1411         struct chan *tc;
1412         Image *i;
1413         Segment *s;
1414
1415         s = p->seg[TSEG];
1416         if (s == 0)
1417                 error(ENOENT, ERROR_FIXME);
1418         if (p->state == Dead)
1419                 error(ESRCH, ERROR_FIXME);
1420
1421         lock(s);
1422         i = s->image;
1423         if (i == 0) {
1424                 unlock(s);
1425                 error(ESRCH, ERROR_FIXME);
1426         }
1427         unlock(s);
1428
1429         lock(i);
1430         if (waserror()) {
1431                 unlock(i);
1432                 nexterror();
1433         }
1434
1435         tc = i->c;
1436         if (tc == 0)
1437                 error(ESRCH, ERROR_FIXME);
1438
1439         /* TODO: what do you want here?  you can't get a kref and have the new val
1440          * be 1.  Here is the old code: if (kref_get(&tc->ref, 1) == 1 || ... ) */
1441         if (kref_refcnt(&tc->ref, 1) == 1 || (tc->flag & COPEN) == 0
1442                 || tc->mode != OREAD) {
1443                 cclose(tc);
1444                 error(ESRCH, ERROR_FIXME);
1445         }
1446
1447         if (p->pid != PID(c->qid)) {
1448                 cclose(tc);
1449                 error(ESRCH, ERROR_FIXME);
1450         }
1451
1452         poperror();
1453         unlock(i);
1454
1455         return tc;
1456 }
1457
1458 /* TODO: this will fail at compile time, since we don't have a proc-wide rendez,
1459  * among other things, and we'll need to rewrite this for akaros */
1460 void procstopwait(struct proc *p, int ctl)
1461 {
1462         ERRSTACK(2);
1463         int pid;
1464
1465         if (p->pdbg)
1466                 error(EBUSY, ERROR_FIXME);
1467         if (procstopped(p) || p->state == Broken)
1468                 return;
1469
1470         if (ctl != 0)
1471                 p->procctl = ctl;
1472         p->pdbg = up;
1473         pid = p->pid;
1474         qunlock(&p->debug);
1475         current->psstate = "Stopwait";
1476         if (waserror()) {
1477                 p->pdbg = 0;
1478                 qlock(&p->debug);
1479                 nexterror();
1480         }
1481         rendez_sleep(&current->sleep, procstopped, p);
1482         poperror();
1483         qlock(&p->debug);
1484         if (p->pid != pid)
1485                 error(ESRCH, ERROR_FIXME);
1486 }
1487
1488 #endif
1489 static void procctlcloseone(struct proc *p, int fd)
1490 {
1491 // TODO: resolve this and sys_close
1492         struct file *file = get_file_from_fd(&p->open_files, fd);
1493         int retval = 0;
1494         printd("%s %d\n", __func__, fd);
1495         /* VFS */
1496         if (file) {
1497                 put_file_from_fd(&p->open_files, fd);
1498                 kref_put(&file->f_kref);        /* Drop the ref from get_file */
1499                 return;
1500         }
1501         /* 9ns, should also handle errors (bad FD, etc) */
1502         retval = sysclose(fd);
1503         return;
1504
1505         //sys_close(p, fd);
1506 }
1507
1508 void procctlclosefiles(struct proc *p, int all, int fd)
1509 {
1510         int i;
1511
1512         if (all)
1513                 for (i = 0; i < NR_FILE_DESC_MAX; i++)
1514                         procctlcloseone(p, i);
1515         else
1516                 procctlcloseone(p, fd);
1517 }
1518
1519 static void strace_shutdown(struct kref *a)
1520 {
1521         struct strace *strace = container_of(a, struct strace, procs);
1522
1523         qhangup(strace->q, "No more traces");
1524 }
1525
1526 static void strace_release(struct kref *a)
1527 {
1528         struct strace *strace = container_of(a, struct strace, users);
1529
1530         qfree(strace->q);
1531         kfree(strace);
1532 }
1533
1534 static void procctlreq(struct proc *p, char *va, int n)
1535 {
1536         ERRSTACK(1);
1537         int8_t irq_state = 0;
1538         int npc, pri, core;
1539         struct cmdbuf *cb;
1540         struct cmdtab *ct;
1541         int64_t time;
1542         char *e;
1543         struct strace *strace;
1544
1545         cb = parsecmd(va, n);
1546         if (waserror()) {
1547                 kfree(cb);
1548                 nexterror();
1549         }
1550
1551         ct = lookupcmd(cb, proccmd, ARRAY_SIZE(proccmd));
1552
1553         switch (ct->index) {
1554         case CMstraceall:
1555         case CMstraceme:
1556                 /* common allocation.  if we inherited, we might have one already */
1557                 if (!p->strace) {
1558                         strace = kmalloc(sizeof(*p->strace), KMALLOC_WAIT);
1559                         strace->q = qopen(65536, Qdropoverflow|Qcoalesce, NULL, NULL);
1560                         /* both of these refs are put when the proc is freed.  procs is for
1561                          * every process that has this p->strace.  users is procs + every
1562                          * user (e.g. from open()).
1563                          *
1564                          * it is possible to kref_put the procs kref in proc_destroy, which
1565                          * would make strace's job easier (no need to do an async wait on
1566                          * the child), and we wouldn't need to decref p in
1567                          * procread(Qstrace).  But the downside is that proc_destroy races
1568                          * with us here with the kref initialization. */
1569                         kref_init(&strace->procs, strace_shutdown, 1);
1570                         kref_init(&strace->users, strace_release, 1);
1571                         if (!atomic_cas_ptr((void**)&p->strace, 0, strace)) {
1572                                 /* someone else won the race and installed strace. */
1573                                 qfree(strace->q);
1574                                 kfree(strace);
1575                                 error(EAGAIN, "Concurrent strace init, try again");
1576                         }
1577                 }
1578                 break;
1579         }
1580
1581         /* actually do the command. */
1582         switch (ct->index) {
1583         case CMvmstart:
1584         case CMvmkill:
1585         default:
1586                 error(EFAIL, "Command not implemented");
1587                 break;
1588         case CMtrace:
1589                 systrace_trace_pid(p);
1590                 break;
1591         case CMclose:
1592                 procctlclosefiles(p, 0, atoi(cb->f[1]));
1593                 break;
1594         case CMclosefiles:
1595                 procctlclosefiles(p, 1, 0);
1596                 break;
1597 #if 0
1598                 we may want this.Let us pause a proc.case CMhang:p->hang = 1;
1599                 break;
1600 #endif
1601         case CMkill:
1602                 p = pid2proc(strtol(cb->f[1], 0, 0));
1603                 if (!p)
1604                         error(EFAIL, "No such proc\n");
1605
1606                 enable_irqsave(&irq_state);
1607                 proc_destroy(p);
1608                 disable_irqsave(&irq_state);
1609                 proc_decref(p);
1610                 /* this is a little ghetto. it's not fully free yet, but we are also
1611                  * slowing it down by messing with it, esp with the busy waiting on a
1612                  * hyperthreaded core. */
1613                 spin_on(p->env_cr3);
1614                 break;
1615         case CMvminit:
1616                 break;
1617         case CMstraceme:
1618                 p->strace_on = TRUE;
1619                 p->strace_inherit = FALSE;
1620                 break;
1621         case CMstraceall:
1622                 p->strace_on = TRUE;
1623                 p->strace_inherit = TRUE;
1624                 break;
1625         case CMstraceoff:
1626                 p->strace_on = FALSE;
1627                 p->strace_inherit = FALSE;
1628                 break;
1629         }
1630         poperror();
1631         kfree(cb);
1632 }
1633
1634 #if 0
1635 static int procstopped(void *a)
1636 {
1637         struct proc *p = a;
1638         return p->state == Stopped;
1639 }
1640
1641 static int
1642 procctlmemio(struct proc *p, uintptr_t offset, int n, void *va, int read)
1643 {
1644         KMap *k;
1645         Pte *pte;
1646         Page *pg;
1647         Segment *s;
1648         uintptr_t soff, l;                      /* hmmmm */
1649         uint8_t *b;
1650         uintmem pgsz;
1651
1652         for (;;) {
1653                 s = seg(p, offset, 1);
1654                 if (s == 0)
1655                         error(EINVAL, ERROR_FIXME);
1656
1657                 if (offset + n >= s->top)
1658                         n = s->top - offset;
1659
1660                 if (!read && (s->type & SG_TYPE) == SG_TEXT)
1661                         s = txt2data(p, s);
1662
1663                 s->steal++;
1664                 soff = offset - s->base;
1665                 if (waserror()) {
1666                         s->steal--;
1667                         nexterror();
1668                 }
1669                 if (fixfault(s, offset, read, 0, s->color) == 0)
1670                         break;
1671                 poperror();
1672                 s->steal--;
1673         }
1674         poperror();
1675         pte = s->map[soff / PTEMAPMEM];
1676         if (pte == 0)
1677                 panic("procctlmemio");
1678         pgsz = m->pgsz[s->pgszi];
1679         pg = pte->pages[(soff & (PTEMAPMEM - 1)) / pgsz];
1680         if (pagedout(pg))
1681                 panic("procctlmemio1");
1682
1683         l = pgsz - (offset & (pgsz - 1));
1684         if (n > l)
1685                 n = l;
1686
1687         k = kmap(pg);
1688         if (waserror()) {
1689                 s->steal--;
1690                 kunmap(k);
1691                 nexterror();
1692         }
1693         b = (uint8_t *) VA(k);
1694         b += offset & (pgsz - 1);
1695         if (read == 1)
1696                 memmove(va, b, n);      /* This can fault */
1697         else
1698                 memmove(b, va, n);
1699         poperror();
1700         kunmap(k);
1701
1702         /* Ensure the process sees text page changes */
1703         if (s->flushme)
1704                 memset(pg->cachectl, PG_TXTFLUSH, sizeof(pg->cachectl));
1705
1706         s->steal--;
1707
1708         if (read == 0)
1709                 p->newtlb = 1;
1710
1711         return n;
1712 }
1713
1714 static Segment *txt2data(struct proc *p, Segment * s)
1715 {
1716         int i;
1717         Segment *ps;
1718
1719         ps = newseg(SG_DATA, s->base, s->size);
1720         ps->image = s->image;
1721         kref_get(&ps->image->ref, 1);
1722         ps->fstart = s->fstart;
1723         ps->flen = s->flen;
1724         ps->flushme = 1;
1725
1726         qlock(&p->seglock);
1727         for (i = 0; i < NSEG; i++)
1728                 if (p->seg[i] == s)
1729                         break;
1730         if (i == NSEG)
1731                 panic("segment gone");
1732
1733         qunlock(&s->lk);
1734         putseg(s);
1735         qlock(&ps->lk);
1736         p->seg[i] = ps;
1737         qunlock(&p->seglock);
1738
1739         return ps;
1740 }
1741
1742 Segment *data2txt(Segment * s)
1743 {
1744         Segment *ps;
1745
1746         ps = newseg(SG_TEXT, s->base, s->size);
1747         ps->image = s->image;
1748         kref_get(&ps->image->ref, 1);
1749         ps->fstart = s->fstart;
1750         ps->flen = s->flen;
1751         ps->flushme = 1;
1752
1753         return ps;
1754 }
1755 #endif