Have #ip's protocol ctl()s throw errors
[akaros.git] / kern / src / net / devip.c
1 /* Copyright © 1994-1999 Lucent Technologies Inc.  All rights reserved.
2  * Portions Copyright © 1997-1999 Vita Nuova Limited
3  * Portions Copyright © 2000-2007 Vita Nuova Holdings Limited
4  *                                (www.vitanuova.com)
5  * Revisions Copyright © 2000-2007 Lucent Technologies Inc. and others
6  *
7  * Modified for the Akaros operating system:
8  * Copyright (c) 2013-2014 The Regents of the University of California
9  * Copyright (c) 2013-2015 Google Inc.
10  *
11  * Permission is hereby granted, free of charge, to any person obtaining a copy
12  * of this software and associated documentation files (the "Software"), to deal
13  * in the Software without restriction, including without limitation the rights
14  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15  * copies of the Software, and to permit persons to whom the Software is
16  * furnished to do so, subject to the following conditions:
17  *
18  * The above copyright notice and this permission notice shall be included in
19  * all copies or substantial portions of the Software.
20  *
21  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
24  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27  * SOFTWARE. */
28
29 #include <vfs.h>
30 #include <kfs.h>
31 #include <slab.h>
32 #include <kmalloc.h>
33 #include <kref.h>
34 #include <string.h>
35 #include <stdio.h>
36 #include <assert.h>
37 #include <error.h>
38 #include <cpio.h>
39 #include <pmap.h>
40 #include <smp.h>
41 #include <ip.h>
42
43 struct dev ipdevtab;
44
45 static char *devname(void)
46 {
47         return ipdevtab.name;
48 }
49
50 enum {
51         Qtopdir = 1,                            /* top level directory */
52         Qtopbase,
53         Qarp = Qtopbase,
54         Qndb,
55         Qiproute,
56         Qiprouter,
57         Qipselftab,
58         Qlog,
59
60         Qprotodir,      /* directory for a protocol */
61         Qprotobase,
62         Qclone = Qprotobase,
63         Qstats,
64
65         Qconvdir,       /* directory for a conversation */
66         Qconvbase,
67         Qctl = Qconvbase,
68         Qdata,
69         Qerr,
70         Qlisten,
71         Qlocal,
72         Qremote,
73         Qstatus,
74         Qsnoop,
75
76         Logtype = 5,
77         Masktype = (1 << Logtype) - 1,
78         Logconv = 12,
79         Maskconv = (1 << Logconv) - 1,
80         Shiftconv = Logtype,
81         Logproto = 8,
82         Maskproto = (1 << Logproto) - 1,
83         Shiftproto = Logtype + Logconv,
84
85         Nfs = 32,
86 };
87 #define TYPE(x)         ( ((uint32_t)(x).path) & Masktype )
88 #define CONV(x)         ( (((uint32_t)(x).path) >> Shiftconv) & Maskconv )
89 #define PROTO(x)        ( (((uint32_t)(x).path) >> Shiftproto) & Maskproto )
90 #define QID(p, c, y)    ( ((p)<<(Shiftproto)) | ((c)<<Shiftconv) | (y))
91 static char network[] = "network";
92
93 qlock_t fslock;
94 struct Fs *ipfs[Nfs];                   /* attached fs's */
95 struct queue *qlog;
96
97 extern void nullmediumlink(void);
98 extern void pktmediumlink(void);
99 extern char *eve;
100 static long ndbwrite(struct Fs *, char *unused_char_p_t, uint32_t, int);
101 static void closeconv(struct conv *);
102
103 static inline int founddevdir(struct chan *c, struct qid q, char *n,
104                                                           int64_t length, char *user, long perm,
105                                                           struct dir *db)
106 {
107         devdir(c, q, n, length, user, perm, db);
108         return 1;
109 }
110
111 static int topdirgen(struct chan *c, struct dir *dp)
112 {
113         struct qid q;
114         mkqid(&q, QID(0, 0, Qtopdir), 0, QTDIR);
115         snprintf(get_cur_genbuf(), GENBUF_SZ, "#%s%lu", devname(), c->dev);
116         return founddevdir(c, q, get_cur_genbuf(), 0, network, 0555, dp);
117 }
118
119
120 static int ip3gen(struct chan *c, int i, struct dir *dp)
121 {
122         struct qid q;
123         struct conv *cv;
124         char *p;
125
126         cv = ipfs[c->dev]->p[PROTO(c->qid)]->conv[CONV(c->qid)];
127         if (cv->owner == NULL)
128                 kstrdup(&cv->owner, eve);
129         mkqid(&q, QID(PROTO(c->qid), CONV(c->qid), i), 0, QTFILE);
130
131         switch (i) {
132                 default:
133                         return -1;
134                 case Qctl:
135                         return founddevdir(c, q, "ctl", 0,
136                                                    cv->owner, cv->perm, dp);
137                 case Qdata:
138                         return founddevdir(c, q, "data", qlen(cv->rq),
139                                                            cv->owner, cv->perm, dp);
140                 case Qerr:
141                         return founddevdir(c, q, "err", qlen(cv->eq),
142                                                            cv->owner, cv->perm, dp);
143                 case Qlisten:
144                         return founddevdir(c, q, "listen", 0, cv->owner, cv->perm, dp);
145                 case Qlocal:
146                         p = "local";
147                         break;
148                 case Qremote:
149                         p = "remote";
150                         break;
151                 case Qsnoop:
152                         if (strcmp(cv->p->name, "ipifc") != 0)
153                                 return -1;
154                         return founddevdir(c, q, "snoop", qlen(cv->sq),
155                                                            cv->owner, 0400, dp);
156                 case Qstatus:
157                         p = "status";
158                         break;
159         }
160         return founddevdir(c, q, p, 0, cv->owner, 0444, dp);
161 }
162
163 static int ip2gen(struct chan *c, int i, struct dir *dp)
164 {
165         struct qid q;
166         mkqid(&q, QID(PROTO(c->qid), 0, i), 0, QTFILE);
167         switch (i) {
168                 case Qclone:
169                         return founddevdir(c, q, "clone", 0, network, 0666, dp);
170                 case Qstats:
171                         return founddevdir(c, q, "stats", 0, network, 0444, dp);
172         }
173         return -1;
174 }
175
176 static int ip1gen(struct chan *c, int i, struct dir *dp)
177 {
178         struct qid q;
179         char *p;
180         int prot;
181         int len = 0;
182         struct Fs *f;
183         extern uint32_t kerndate;
184
185         f = ipfs[c->dev];
186
187         prot = 0666;
188         mkqid(&q, QID(0, 0, i), 0, QTFILE);
189         switch (i) {
190                 default:
191                         return -1;
192                 case Qarp:
193                         p = "arp";
194                         break;
195                 case Qndb:
196                         p = "ndb";
197                         len = strlen(f->ndb);
198                         q.vers = f->ndbvers;
199                         break;
200                 case Qiproute:
201                         p = "iproute";
202                         break;
203                 case Qipselftab:
204                         p = "ipselftab";
205                         prot = 0444;
206                         break;
207                 case Qiprouter:
208                         p = "iprouter";
209                         break;
210                 case Qlog:
211                         p = "log";
212                         break;
213         }
214         devdir(c, q, p, len, network, prot, dp);
215         if (i == Qndb && f->ndbmtime > kerndate)
216                 dp->mtime = f->ndbmtime;
217         return 1;
218 }
219
220 static int
221 ipgen(struct chan *c, char *unused_char_p_t, struct dirtab *d, int unused_int,
222           int s, struct dir *dp)
223 {
224         struct qid q;
225         struct conv *cv;
226         struct Fs *f;
227
228         f = ipfs[c->dev];
229
230         switch (TYPE(c->qid)) {
231                 case Qtopdir:
232                         if (s == DEVDOTDOT)
233                                 return topdirgen(c, dp);
234                         if (s < f->np) {
235                                 if (f->p[s]->connect == NULL)
236                                         return 0;       /* protocol with no user interface */
237                                 mkqid(&q, QID(s, 0, Qprotodir), 0, QTDIR);
238                                 return founddevdir(c, q, f->p[s]->name, 0, network, 0555, dp);
239                         }
240                         s -= f->np;
241                         return ip1gen(c, s + Qtopbase, dp);
242                 case Qarp:
243                 case Qndb:
244                 case Qlog:
245                 case Qiproute:
246                 case Qiprouter:
247                 case Qipselftab:
248                         return ip1gen(c, TYPE(c->qid), dp);
249                 case Qprotodir:
250                         if (s == DEVDOTDOT)
251                                 return topdirgen(c, dp);
252                         else if (s < f->p[PROTO(c->qid)]->ac) {
253                                 cv = f->p[PROTO(c->qid)]->conv[s];
254                                 snprintf(get_cur_genbuf(), GENBUF_SZ, "%d", s);
255                                 mkqid(&q, QID(PROTO(c->qid), s, Qconvdir), 0, QTDIR);
256                                 return
257                                         founddevdir(c, q, get_cur_genbuf(), 0, cv->owner, 0555, dp);
258                         }
259                         s -= f->p[PROTO(c->qid)]->ac;
260                         return ip2gen(c, s + Qprotobase, dp);
261                 case Qclone:
262                 case Qstats:
263                         return ip2gen(c, TYPE(c->qid), dp);
264                 case Qconvdir:
265                         if (s == DEVDOTDOT) {
266                                 s = PROTO(c->qid);
267                                 mkqid(&q, QID(s, 0, Qprotodir), 0, QTDIR);
268                                 devdir(c, q, f->p[s]->name, 0, network, 0555, dp);
269                                 return 1;
270                         }
271                         return ip3gen(c, s + Qconvbase, dp);
272                 case Qctl:
273                 case Qdata:
274                 case Qerr:
275                 case Qlisten:
276                 case Qlocal:
277                 case Qremote:
278                 case Qstatus:
279                 case Qsnoop:
280                         return ip3gen(c, TYPE(c->qid), dp);
281         }
282         return -1;
283 }
284
285 static void ipinit(void)
286 {
287         qlock_init(&fslock);
288         nullmediumlink();
289         pktmediumlink();
290 /* if only
291         fmtinstall('i', eipfmt);
292         fmtinstall('I', eipfmt);
293         fmtinstall('E', eipfmt);
294         fmtinstall('V', eipfmt);
295         fmtinstall('M', eipfmt);
296 */
297 }
298
299 static void ipreset(void)
300 {
301 }
302
303 static struct Fs *ipgetfs(int dev)
304 {
305         extern void (*ipprotoinit[]) (struct Fs *);
306         struct Fs *f;
307         int i;
308
309         if (dev >= Nfs)
310                 return NULL;
311
312         qlock(&fslock);
313         if (ipfs[dev] == NULL) {
314                 f = kzmalloc(sizeof(struct Fs), KMALLOC_WAIT);
315                 rwinit(&f->rwlock);
316                 qlock_init(&f->iprouter.qlock);
317                 ip_init(f);
318                 arpinit(f);
319                 netloginit(f);
320                 for (i = 0; ipprotoinit[i]; i++)
321                         ipprotoinit[i] (f);
322                 f->dev = dev;
323                 ipfs[dev] = f;
324         }
325         qunlock(&fslock);
326
327         return ipfs[dev];
328 }
329
330 struct IPaux *newipaux(char *owner, char *tag)
331 {
332         struct IPaux *a;
333         int n;
334
335         a = kzmalloc(sizeof(*a), 0);
336         kstrdup(&a->owner, owner);
337         memset(a->tag, ' ', sizeof(a->tag));
338         n = strlen(tag);
339         if (n > sizeof(a->tag))
340                 n = sizeof(a->tag);
341         memmove(a->tag, tag, n);
342         return a;
343 }
344
345 #define ATTACHER(c) (((struct IPaux*)((c)->aux))->owner)
346
347 static struct chan *ipattach(char *spec)
348 {
349         struct chan *c;
350         int dev;
351
352         dev = atoi(spec);
353         if (dev >= Nfs)
354                 error(EFAIL, "bad specification");
355
356         ipgetfs(dev);
357         c = devattach(devname(), spec);
358         mkqid(&c->qid, QID(0, 0, Qtopdir), 0, QTDIR);
359         c->dev = dev;
360
361         c->aux = newipaux(commonuser(), "none");
362
363         return c;
364 }
365
366 static struct walkqid *ipwalk(struct chan *c, struct chan *nc, char **name,
367                                                           int nname)
368 {
369         struct IPaux *a = c->aux;
370         struct walkqid *w;
371
372         w = devwalk(c, nc, name, nname, NULL, 0, ipgen);
373         if (w != NULL && w->clone != NULL)
374                 w->clone->aux = newipaux(a->owner, a->tag);
375         return w;
376 }
377
378 static int ipstat(struct chan *c, uint8_t * db, int n)
379 {
380         return devstat(c, db, n, NULL, 0, ipgen);
381 }
382
383 static int should_wake(void *arg)
384 {
385         struct conv *cv = arg;
386         /* signal that the conv is closed */
387         if (qisclosed(cv->rq))
388                 return TRUE;
389         return cv->incall != NULL;
390 }
391
392 static struct chan *ipopen(struct chan *c, int omode)
393 {
394         ERRSTACK(2);
395         struct conv *cv, *nc;
396         struct Proto *p;
397         int perm;
398         struct Fs *f;
399
400         /* perm is a lone rwx, not the rwx------ from the conversion */
401         perm = omode_to_rwx(omode) >> 6;
402
403         f = ipfs[c->dev];
404
405         switch (TYPE(c->qid)) {
406                 default:
407                         break;
408                 case Qndb:
409                         if (omode & (O_WRITE | O_TRUNC) && !iseve())
410                                 error(EPERM, ERROR_FIXME);
411                         if ((omode & (O_WRITE | O_TRUNC)) == (O_WRITE | O_TRUNC))
412                                 f->ndb[0] = 0;
413                         break;
414                 case Qlog:
415                         netlogopen(f);
416                         break;
417                 case Qiprouter:
418                         iprouteropen(f);
419                         break;
420                 case Qiproute:
421                         break;
422                 case Qtopdir:
423                 case Qprotodir:
424                 case Qconvdir:
425                 case Qstatus:
426                 case Qremote:
427                 case Qlocal:
428                 case Qstats:
429                 case Qipselftab:
430                         if (omode & O_WRITE)
431                                 error(EPERM, ERROR_FIXME);
432                         break;
433                 case Qsnoop:
434                         if (omode & O_WRITE)
435                                 error(EPERM, ERROR_FIXME);
436                         p = f->p[PROTO(c->qid)];
437                         cv = p->conv[CONV(c->qid)];
438                         if (strcmp(ATTACHER(c), cv->owner) != 0 && !iseve())
439                                 error(EPERM, ERROR_FIXME);
440                         atomic_inc(&cv->snoopers);
441                         break;
442                 case Qclone:
443                         p = f->p[PROTO(c->qid)];
444                         qlock(&p->qlock);
445                         if (waserror()) {
446                                 qunlock(&p->qlock);
447                                 nexterror();
448                         }
449                         cv = Fsprotoclone(p, ATTACHER(c));
450                         qunlock(&p->qlock);
451                         poperror();
452                         if (cv == NULL) {
453                                 error(ENODEV, ERROR_FIXME);
454                                 break;
455                         }
456                         /* we only honor nonblock on a clone */
457                         if (c->flag & O_NONBLOCK)
458                                 Fsconvnonblock(cv, TRUE);
459                         mkqid(&c->qid, QID(p->x, cv->x, Qctl), 0, QTFILE);
460                         break;
461                 case Qdata:
462                 case Qctl:
463                 case Qerr:
464                         p = f->p[PROTO(c->qid)];
465                         qlock(&p->qlock);
466                         cv = p->conv[CONV(c->qid)];
467                         qlock(&cv->qlock);
468                         if (waserror()) {
469                                 qunlock(&cv->qlock);
470                                 qunlock(&p->qlock);
471                                 nexterror();
472                         }
473                         if ((perm & (cv->perm >> 6)) != perm) {
474                                 if (strcmp(ATTACHER(c), cv->owner) != 0)
475                                         error(EPERM, ERROR_FIXME);
476                                 if ((perm & cv->perm) != perm)
477                                         error(EPERM, ERROR_FIXME);
478
479                         }
480                         cv->inuse++;
481                         if (cv->inuse == 1) {
482                                 kstrdup(&cv->owner, ATTACHER(c));
483                                 cv->perm = 0660;
484                         }
485                         qunlock(&cv->qlock);
486                         qunlock(&p->qlock);
487                         poperror();
488                         break;
489                 case Qlisten:
490                         cv = f->p[PROTO(c->qid)]->conv[CONV(c->qid)];
491                         /* No permissions or Announce checks required.  We'll see if that's
492                          * a good idea or not. (the perm check would do nothing, as is,
493                          * since an O_PATH perm is 0).
494                          *
495                          * But we probably want to incref to keep the conversation around
496                          * until this FD/chan is closed.  #ip is a little weird in that
497                          * objects never really go away (high water mark for convs, you can
498                          * always find them in the ns).  I think it is possible to
499                          * namec/ipgen a chan, then have that conv close, then have that
500                          * chan be opened.  You can probably do this with a data file. */
501                         if (omode & O_PATH) {
502                                 qlock(&cv->qlock);
503                                 cv->inuse++;
504                                 qunlock(&cv->qlock);
505                                 break;
506                         }
507                         if ((perm & (cv->perm >> 6)) != perm) {
508                                 if (strcmp(ATTACHER(c), cv->owner) != 0)
509                                         error(EPERM, ERROR_FIXME);
510                                 if ((perm & cv->perm) != perm)
511                                         error(EPERM, ERROR_FIXME);
512
513                         }
514
515                         if (cv->state != Announced)
516                                 error(EFAIL, "not announced");
517
518                         if (waserror()) {
519                                 closeconv(cv);
520                                 nexterror();
521                         }
522                         qlock(&cv->qlock);
523                         cv->inuse++;
524                         qunlock(&cv->qlock);
525
526                         nc = NULL;
527                         while (nc == NULL) {
528                                 /* give up if we got a hangup */
529                                 if (qisclosed(cv->rq))
530                                         error(EFAIL, "listen hungup");
531
532                                 qlock(&cv->listenq);
533                                 if (waserror()) {
534                                         qunlock(&cv->listenq);
535                                         nexterror();
536                                 }
537                                 /* we can peek at incall without grabbing the cv qlock.  if
538                                  * anything is there, it'll remain there until we dequeue it.
539                                  * no one else can, since we hold the listenq lock */
540                                 if (cv->nonblock && !cv->incall)
541                                         error(EAGAIN, "listen queue empty");
542                                 /* wait for a connect */
543                                 rendez_sleep(&cv->listenr, should_wake, cv);
544
545                                 /* if there is a concurrent hangup, they will hold the qlock
546                                  * until the hangup is complete, including closing the cv->rq */
547                                 qlock(&cv->qlock);
548                                 nc = cv->incall;
549                                 if (nc != NULL) {
550                                         cv->incall = nc->next;
551                                         mkqid(&c->qid, QID(PROTO(c->qid), nc->x, Qctl), 0, QTFILE);
552                                         kstrdup(&cv->owner, ATTACHER(c));
553                                         /* O_NONBLOCK/CNONBLOCK when opening listen means the *new*
554                                          * conv is already non-blocking, like accept4() in Linux */
555                                         if (c->flag & O_NONBLOCK)
556                                                 Fsconvnonblock(nc, TRUE);
557                                 }
558                                 qunlock(&cv->qlock);
559
560                                 qunlock(&cv->listenq);
561                                 poperror();
562                         }
563                         closeconv(cv);
564                         poperror();
565                         break;
566         }
567         c->mode = openmode(omode);
568         c->flag |= COPEN;
569         c->offset = 0;
570         return c;
571 }
572
573 static int ipwstat(struct chan *c, uint8_t * dp, int n)
574 {
575         ERRSTACK(2);
576         struct dir *d;
577         struct conv *cv;
578         struct Fs *f;
579         struct Proto *p;
580
581         f = ipfs[c->dev];
582         switch (TYPE(c->qid)) {
583                 default:
584                         error(EPERM, ERROR_FIXME);
585                         break;
586                 case Qctl:
587                 case Qdata:
588                         break;
589         }
590
591         d = kzmalloc(sizeof(*d) + n, 0);
592         if (waserror()) {
593                 kfree(d);
594                 nexterror();
595         }
596         n = convM2D(dp, n, d, (char *)&d[1]);
597         if (n == 0)
598                 error(ENODATA, ERROR_FIXME);
599         p = f->p[PROTO(c->qid)];
600         cv = p->conv[CONV(c->qid)];
601         if (!iseve() && strcmp(ATTACHER(c), cv->owner) != 0)
602                 error(EPERM, ERROR_FIXME);
603         if (!emptystr(d->uid))
604                 kstrdup(&cv->owner, d->uid);
605         if (d->mode != ~0UL)
606                 cv->perm = d->mode & 0777;
607         poperror();
608         kfree(d);
609         return n;
610 }
611
612 /* Should be able to handle any file type chan. Feel free to extend it. */
613 static char *ipchaninfo(struct chan *ch, char *ret, size_t ret_l)
614 {
615         struct conv *conv;
616         struct Proto *proto;
617         char *p;
618         struct Fs *f;
619
620         f = ipfs[ch->dev];
621
622         switch (TYPE(ch->qid)) {
623                 default:
624                         ret = "Unknown type";
625                         break;
626                 case Qdata:
627                         proto = f->p[PROTO(ch->qid)];
628                         conv = proto->conv[CONV(ch->qid)];
629                         snprintf(ret, ret_l, "Qdata, proto %s, conv idx %d", proto->name,
630                                          conv->x);
631                         break;
632                 case Qarp:
633                         ret = "Qarp";
634                         break;
635                 case Qiproute:
636                         ret = "Qiproute";
637                         break;
638                 case Qlisten:
639                         proto = f->p[PROTO(ch->qid)];
640                         conv = proto->conv[CONV(ch->qid)];
641                         snprintf(ret, ret_l, "Qlisten, proto %s, conv idx %d", proto->name,
642                                          conv->x);
643                         break;
644                 case Qlog:
645                         ret = "Qlog";
646                         break;
647                 case Qndb:
648                         ret = "Qndb";
649                         break;
650                 case Qctl:
651                         proto = f->p[PROTO(ch->qid)];
652                         conv = proto->conv[CONV(ch->qid)];
653                         snprintf(ret, ret_l, "Qctl, proto %s, conv idx %d", proto->name,
654                                          conv->x);
655                         break;
656         }
657         return ret;
658 }
659
660 static void closeconv(struct conv *cv)
661 {
662         struct conv *nc;
663         struct Ipmulti *mp;
664
665         qlock(&cv->qlock);
666
667         if (--cv->inuse > 0) {
668                 qunlock(&cv->qlock);
669                 return;
670         }
671
672         /* close all incoming calls since no listen will ever happen */
673         for (nc = cv->incall; nc; nc = cv->incall) {
674                 cv->incall = nc->next;
675                 closeconv(nc);
676         }
677         cv->incall = NULL;
678
679         kstrdup(&cv->owner, network);
680         cv->perm = 0660;
681
682         while ((mp = cv->multi) != NULL)
683                 ipifcremmulti(cv, mp->ma, mp->ia);
684
685         cv->r = NULL;
686         cv->rgen = 0;
687         cv->p->close(cv);
688         cv->state = Idle;
689         qunlock(&cv->qlock);
690 }
691
692 static void ipclose(struct chan *c)
693 {
694         struct Fs *f;
695
696         f = ipfs[c->dev];
697         switch (TYPE(c->qid)) {
698                 default:
699                         break;
700                 case Qlog:
701                         if (c->flag & COPEN)
702                                 netlogclose(f);
703                         break;
704                 case Qiprouter:
705                         if (c->flag & COPEN)
706                                 iprouterclose(f);
707                         break;
708                 case Qdata:
709                 case Qctl:
710                 case Qerr:
711                 case Qlisten:
712                         if (c->flag & COPEN)
713                                 closeconv(f->p[PROTO(c->qid)]->conv[CONV(c->qid)]);
714                         break;
715                 case Qsnoop:
716                         if (c->flag & COPEN)
717                                 atomic_dec(&f->p[PROTO(c->qid)]->conv[CONV(c->qid)]->snoopers);
718                         break;
719         }
720         kfree(((struct IPaux *)c->aux)->owner);
721         kfree(c->aux);
722 }
723
724 enum {
725         Statelen = 32 * 1024,
726 };
727
728 static long ipread(struct chan *ch, void *a, long n, int64_t off)
729 {
730         struct conv *c;
731         struct Proto *x;
732         char *buf, *p;
733         long rv;
734         struct Fs *f;
735         uint32_t offset = off;
736         size_t sofar;
737
738         f = ipfs[ch->dev];
739
740         p = a;
741         switch (TYPE(ch->qid)) {
742                 default:
743                         error(EPERM, ERROR_FIXME);
744                 case Qtopdir:
745                 case Qprotodir:
746                 case Qconvdir:
747                         return devdirread(ch, a, n, 0, 0, ipgen);
748                 case Qarp:
749                         return arpread(f->arp, a, offset, n);
750                 case Qndb:
751                         return readstr(offset, a, n, f->ndb);
752                 case Qiproute:
753                         return routeread(f, a, offset, n);
754                 case Qiprouter:
755                         return iprouterread(f, a, n);
756                 case Qipselftab:
757                         return ipselftabread(f, a, offset, n);
758                 case Qlog:
759                         return netlogread(f, a, offset, n);
760                 case Qctl:
761                         snprintf(get_cur_genbuf(), GENBUF_SZ, "%lu", CONV(ch->qid));
762                         return readstr(offset, p, n, get_cur_genbuf());
763                 case Qremote:
764                         buf = kzmalloc(Statelen, 0);
765                         x = f->p[PROTO(ch->qid)];
766                         c = x->conv[CONV(ch->qid)];
767                         if (x->remote == NULL) {
768                                 snprintf(buf, Statelen, "%I!%d\n", c->raddr, c->rport);
769                         } else {
770                                 (*x->remote) (c, buf, Statelen - 2);
771                         }
772                         rv = readstr(offset, p, n, buf);
773                         kfree(buf);
774                         return rv;
775                 case Qlocal:
776                         buf = kzmalloc(Statelen, 0);
777                         x = f->p[PROTO(ch->qid)];
778                         c = x->conv[CONV(ch->qid)];
779                         if (x->local == NULL) {
780                                 snprintf(buf, Statelen, "%I!%d\n", c->laddr, c->lport);
781                         } else {
782                                 (*x->local) (c, buf, Statelen - 2);
783                         }
784                         rv = readstr(offset, p, n, buf);
785                         kfree(buf);
786                         return rv;
787                 case Qstatus:
788                         /* this all is a bit screwed up since the size of some state's
789                          * buffers will change from one invocation to another.  a reader
790                          * will come in and read the entire buffer.  then it will come again
791                          * and read from the next offset, expecting EOF.  if the buffer
792                          * changed sizes, it'll reprint the end of the buffer slightly. */
793                         buf = kzmalloc(Statelen, 0);
794                         x = f->p[PROTO(ch->qid)];
795                         c = x->conv[CONV(ch->qid)];
796                         sofar = (*x->state) (c, buf, Statelen - 2);
797                         sofar += snprintf(buf + sofar, Statelen - 2 - sofar, "nonblock %s\n",
798                                           c->nonblock ? "on" : "off");
799                         rv = readstr(offset, p, n, buf);
800                         kfree(buf);
801                         return rv;
802                 case Qdata:
803                         c = f->p[PROTO(ch->qid)]->conv[CONV(ch->qid)];
804                         return qread(c->rq, a, n);
805                 case Qerr:
806                         c = f->p[PROTO(ch->qid)]->conv[CONV(ch->qid)];
807                         return qread(c->eq, a, n);
808                 case Qsnoop:
809                         c = f->p[PROTO(ch->qid)]->conv[CONV(ch->qid)];
810                         return qread(c->sq, a, n);
811                 case Qstats:
812                         x = f->p[PROTO(ch->qid)];
813                         if (x->stats == NULL)
814                                 error(EFAIL, "stats not implemented");
815                         buf = kzmalloc(Statelen, 0);
816                         (*x->stats) (x, buf, Statelen);
817                         rv = readstr(offset, p, n, buf);
818                         kfree(buf);
819                         return rv;
820         }
821 }
822
823 static struct block *ipbread(struct chan *ch, long n, uint32_t offset)
824 {
825         struct conv *c;
826         struct Proto *x;
827         struct Fs *f;
828
829         switch (TYPE(ch->qid)) {
830                 case Qdata:
831                         f = ipfs[ch->dev];
832                         x = f->p[PROTO(ch->qid)];
833                         c = x->conv[CONV(ch->qid)];
834                         return qbread(c->rq, n);
835                 default:
836                         return devbread(ch, n, offset);
837         }
838 }
839
840 /*
841  *  set local address to be that of the ifc closest to remote address
842  */
843 static void setladdr(struct conv *c)
844 {
845         findlocalip(c->p->f, c->laddr, c->raddr);
846 }
847
848 /*
849  *  set a local port making sure the quad of raddr,rport,laddr,lport is unique
850  */
851 static char *setluniqueport(struct conv *c, int lport)
852 {
853         struct Proto *p;
854         struct conv *xp;
855         int x;
856
857         p = c->p;
858
859         qlock(&p->qlock);
860         for (x = 0; x < p->nc; x++) {
861                 xp = p->conv[x];
862                 if (xp == NULL)
863                         break;
864                 if (xp == c)
865                         continue;
866                 if ((xp->state == Connected || xp->state == Announced)
867                         && xp->lport == lport
868                         && xp->rport == c->rport
869                         && ipcmp(xp->raddr, c->raddr) == 0
870                         && ipcmp(xp->laddr, c->laddr) == 0) {
871                         qunlock(&p->qlock);
872                         return "address in use";
873                 }
874         }
875         c->lport = lport;
876         qunlock(&p->qlock);
877         return NULL;
878 }
879
880 /*
881  *  pick a local port and set it
882  */
883 static void setlport(struct conv *c)
884 {
885         struct Proto *p;
886         uint16_t *pp;
887         int x, found;
888
889         p = c->p;
890         if (c->restricted)
891                 pp = &p->nextrport;
892         else
893                 pp = &p->nextport;
894         qlock(&p->qlock);
895         for (;; (*pp)++) {
896                 /*
897                  * Fsproto initialises p->nextport to 0 and the restricted
898                  * ports (p->nextrport) to 600.
899                  * Restricted ports must lie between 600 and 1024.
900                  * For the initial condition or if the unrestricted port number
901                  * has wrapped round, select a random port between 5000 and 1<<15
902                  * to start at.
903                  */
904                 if (c->restricted) {
905                         if (*pp >= 1024)
906                                 *pp = 600;
907                 } else
908                         while (*pp < 5000)
909                                 urandom_read(pp, sizeof(*pp));
910
911                 found = 0;
912                 for (x = 0; x < p->nc; x++) {
913                         if (p->conv[x] == NULL)
914                                 break;
915                         if (p->conv[x]->lport == *pp) {
916                                 found = 1;
917                                 break;
918                         }
919                 }
920                 if (!found)
921                         break;
922         }
923         c->lport = (*pp)++;
924         qunlock(&p->qlock);
925 }
926
927 /*
928  *  set a local address and port from a string of the form
929  *      [address!]port[!r]
930  */
931 static char *setladdrport(struct conv *c, char *str, int announcing)
932 {
933         char *p;
934         char *rv;
935         uint16_t lport;
936         uint8_t addr[IPaddrlen];
937
938         rv = NULL;
939
940         /*
941          *  ignore restricted part if it exists.  it's
942          *  meaningless on local ports.
943          */
944         p = strchr(str, '!');
945         if (p != NULL) {
946                 *p++ = 0;
947                 if (strcmp(p, "r") == 0)
948                         p = NULL;
949         }
950
951         c->lport = 0;
952         if (p == NULL) {
953                 if (announcing)
954                         ipmove(c->laddr, IPnoaddr);
955                 else
956                         setladdr(c);
957                 p = str;
958         } else {
959                 if (strcmp(str, "*") == 0)
960                         ipmove(c->laddr, IPnoaddr);
961                 else {
962                         parseip(addr, str);
963                         if (ipforme(c->p->f, addr))
964                                 ipmove(c->laddr, addr);
965                         else
966                                 return "not a local IP address";
967                 }
968         }
969
970         /* one process can get all connections */
971         if (announcing && strcmp(p, "*") == 0) {
972                 if (!iseve())
973                         error(EPERM, ERROR_FIXME);
974                 return setluniqueport(c, 0);
975         }
976
977         lport = atoi(p);
978         if (lport <= 0)
979                 setlport(c);
980         else
981                 rv = setluniqueport(c, lport);
982         return rv;
983 }
984
985 static char *setraddrport(struct conv *c, char *str)
986 {
987         char *p;
988
989         p = strchr(str, '!');
990         if (p == NULL)
991                 return "malformed address";
992         *p++ = 0;
993         parseip(c->raddr, str);
994         c->rport = atoi(p);
995         p = strchr(p, '!');
996         if (p) {
997                 if (strstr(p, "!r") != NULL)
998                         c->restricted = 1;
999         }
1000         return NULL;
1001 }
1002
1003 /*
1004  *  called by protocol connect routine to set addresses
1005  */
1006 char *Fsstdconnect(struct conv *c, char *argv[], int argc)
1007 {
1008         char *p;
1009
1010         switch (argc) {
1011                 default:
1012                         return "bad args to connect";
1013                 case 2:
1014                         p = setraddrport(c, argv[1]);
1015                         if (p != NULL)
1016                                 return p;
1017                         setladdr(c);
1018                         setlport(c);
1019                         break;
1020                 case 3:
1021                         p = setraddrport(c, argv[1]);
1022                         if (p != NULL)
1023                                 return p;
1024                         p = setladdrport(c, argv[2], 0);
1025                         if (p != NULL)
1026                                 return p;
1027         }
1028
1029         if ((memcmp(c->raddr, v4prefix, IPv4off) == 0 &&
1030                  memcmp(c->laddr, v4prefix, IPv4off) == 0)
1031                 || ipcmp(c->raddr, IPnoaddr) == 0)
1032                 c->ipversion = V4;
1033         else
1034                 c->ipversion = V6;
1035
1036         return NULL;
1037 }
1038
1039 /*
1040  *  initiate connection and sleep till its set up
1041  */
1042 static int connected(void *a)
1043 {
1044         return ((struct conv *)a)->state == Connected;
1045 }
1046
1047 static void connectctlmsg(struct Proto *x, struct conv *c, struct cmdbuf *cb)
1048 {
1049         ERRSTACK(1);
1050         char *p;
1051
1052         if (c->state != 0)
1053                 error(EBUSY, ERROR_FIXME);
1054         c->state = Connecting;
1055         c->cerr[0] = '\0';
1056         if (x->connect == NULL)
1057                 error(EFAIL, "connect not supported");
1058         p = x->connect(c, cb->f, cb->nf);
1059         if (p != NULL)
1060                 error(EFAIL, p);
1061
1062         qunlock(&c->qlock);
1063         if (waserror()) {
1064                 qlock(&c->qlock);
1065                 nexterror();
1066         }
1067         rendez_sleep(&c->cr, connected, c);
1068         qlock(&c->qlock);
1069         poperror();
1070
1071         if (c->cerr[0] != '\0')
1072                 error(EFAIL, c->cerr);
1073 }
1074
1075 /*
1076  *  called by protocol announce routine to set addresses
1077  */
1078 char *Fsstdannounce(struct conv *c, char *argv[], int argc)
1079 {
1080         memset(c->raddr, 0, sizeof(c->raddr));
1081         c->rport = 0;
1082         switch (argc) {
1083                 default:
1084                         return "bad args to announce";
1085                 case 2:
1086                         return setladdrport(c, argv[1], 1);
1087         }
1088 }
1089
1090 /*
1091  *  initiate announcement and sleep till its set up
1092  */
1093 static int announced(void *a)
1094 {
1095         return ((struct conv *)a)->state == Announced;
1096 }
1097
1098 static void announcectlmsg(struct Proto *x, struct conv *c, struct cmdbuf *cb)
1099 {
1100         ERRSTACK(1);
1101         char *p;
1102
1103         if (c->state != 0)
1104                 error(EBUSY, ERROR_FIXME);
1105         c->state = Announcing;
1106         c->cerr[0] = '\0';
1107         if (x->announce == NULL)
1108                 error(EFAIL, "announce not supported");
1109         p = x->announce(c, cb->f, cb->nf);
1110         if (p != NULL)
1111                 error(EFAIL, p);
1112
1113         qunlock(&c->qlock);
1114         if (waserror()) {
1115                 qlock(&c->qlock);
1116                 nexterror();
1117         }
1118         rendez_sleep(&c->cr, announced, c);
1119         qlock(&c->qlock);
1120         poperror();
1121
1122         if (c->cerr[0] != '\0')
1123                 error(EFAIL, c->cerr);
1124 }
1125
1126 /*
1127  *  called by protocol bind routine to set addresses
1128  */
1129 char *Fsstdbind(struct conv *c, char *argv[], int argc)
1130 {
1131         switch (argc) {
1132                 default:
1133                         return "bad args to bind";
1134                 case 2:
1135                         return setladdrport(c, argv[1], 0);
1136         }
1137 }
1138
1139 void Fsconvnonblock(struct conv *cv, bool onoff)
1140 {
1141         qnonblock(cv->wq, onoff);
1142         qnonblock(cv->rq, onoff);
1143         cv->nonblock = onoff;
1144 }
1145
1146 static void bindctlmsg(struct Proto *x, struct conv *c, struct cmdbuf *cb)
1147 {
1148         char *p;
1149
1150         if (x->bind == NULL)
1151                 p = Fsstdbind(c, cb->f, cb->nf);
1152         else
1153                 p = x->bind(c, cb->f, cb->nf);
1154         if (p != NULL)
1155                 error(EFAIL, p);
1156 }
1157
1158 static void nonblockctlmsg(struct conv *c, struct cmdbuf *cb)
1159 {
1160         if (cb->nf < 2)
1161                 goto err;
1162         if (!strcmp(cb->f[1], "on"))
1163                 Fsconvnonblock(c, TRUE);
1164         else if (!strcmp(cb->f[1], "off"))
1165                 Fsconvnonblock(c, FALSE);
1166         else
1167                 goto err;
1168         return;
1169 err:
1170         error(EINVAL, "nonblock [on|off]");
1171 }
1172
1173 static void tosctlmsg(struct conv *c, struct cmdbuf *cb)
1174 {
1175         if (cb->nf < 2)
1176                 c->tos = 0;
1177         else
1178                 c->tos = atoi(cb->f[1]);
1179 }
1180
1181 static void ttlctlmsg(struct conv *c, struct cmdbuf *cb)
1182 {
1183         if (cb->nf < 2)
1184                 c->ttl = MAXTTL;
1185         else
1186                 c->ttl = atoi(cb->f[1]);
1187 }
1188
1189 static long ipwrite(struct chan *ch, void *v, long n, int64_t off)
1190 {
1191         ERRSTACK(1);
1192         struct conv *c;
1193         struct Proto *x;
1194         char *p;
1195         struct cmdbuf *cb;
1196         uint8_t ia[IPaddrlen], ma[IPaddrlen];
1197         struct Fs *f;
1198         char *a;
1199
1200         a = v;
1201         f = ipfs[ch->dev];
1202
1203         switch (TYPE(ch->qid)) {
1204                 default:
1205                         error(EPERM, ERROR_FIXME);
1206                 case Qdata:
1207                         x = f->p[PROTO(ch->qid)];
1208                         c = x->conv[CONV(ch->qid)];
1209                         qwrite(c->wq, a, n);
1210                         break;
1211                 case Qarp:
1212                         return arpwrite(f, a, n);
1213                 case Qiproute:
1214                         return routewrite(f, ch, a, n);
1215                 case Qlog:
1216                         netlogctl(f, a, n);
1217                         return n;
1218                 case Qndb:
1219                         return ndbwrite(f, a, off, n);
1220                 case Qctl:
1221                         x = f->p[PROTO(ch->qid)];
1222                         c = x->conv[CONV(ch->qid)];
1223                         cb = parsecmd(a, n);
1224
1225                         qlock(&c->qlock);
1226                         if (waserror()) {
1227                                 qunlock(&c->qlock);
1228                                 kfree(cb);
1229                                 nexterror();
1230                         }
1231                         if (cb->nf < 1)
1232                                 error(EFAIL, "short control request");
1233                         if (strcmp(cb->f[0], "connect") == 0)
1234                                 connectctlmsg(x, c, cb);
1235                         else if (strcmp(cb->f[0], "announce") == 0)
1236                                 announcectlmsg(x, c, cb);
1237                         else if (strcmp(cb->f[0], "bind") == 0)
1238                                 bindctlmsg(x, c, cb);
1239                         else if (strcmp(cb->f[0], "nonblock") == 0)
1240                                 nonblockctlmsg(c, cb);
1241                         else if (strcmp(cb->f[0], "ttl") == 0)
1242                                 ttlctlmsg(c, cb);
1243                         else if (strcmp(cb->f[0], "tos") == 0)
1244                                 tosctlmsg(c, cb);
1245                         else if (strcmp(cb->f[0], "ignoreadvice") == 0)
1246                                 c->ignoreadvice = 1;
1247                         else if (strcmp(cb->f[0], "addmulti") == 0) {
1248                                 if (cb->nf < 2)
1249                                         error(EFAIL, "addmulti needs interface address");
1250                                 if (cb->nf == 2) {
1251                                         if (!ipismulticast(c->raddr))
1252                                                 error(EFAIL, "addmulti for a non multicast address");
1253                                         parseip(ia, cb->f[1]);
1254                                         ipifcaddmulti(c, c->raddr, ia);
1255                                 } else {
1256                                         parseip(ma, cb->f[2]);
1257                                         if (!ipismulticast(ma))
1258                                                 error(EFAIL, "addmulti for a non multicast address");
1259                                         parseip(ia, cb->f[1]);
1260                                         ipifcaddmulti(c, ma, ia);
1261                                 }
1262                         } else if (strcmp(cb->f[0], "remmulti") == 0) {
1263                                 if (cb->nf < 2)
1264                                         error(EFAIL, "remmulti needs interface address");
1265                                 if (!ipismulticast(c->raddr))
1266                                         error(EFAIL, "remmulti for a non multicast address");
1267                                 parseip(ia, cb->f[1]);
1268                                 ipifcremmulti(c, c->raddr, ia);
1269                         } else if (x->ctl != NULL) {
1270                                 x->ctl(c, cb->f, cb->nf);
1271                         } else
1272                                 error(EFAIL, "unknown control request");
1273                         qunlock(&c->qlock);
1274                         kfree(cb);
1275                         poperror();
1276         }
1277         return n;
1278 }
1279
1280 static long ipbwrite(struct chan *ch, struct block *bp, uint32_t offset)
1281 {
1282         struct conv *c;
1283         struct Proto *x;
1284         struct Fs *f;
1285         int n;
1286
1287         switch (TYPE(ch->qid)) {
1288                 case Qdata:
1289                         f = ipfs[ch->dev];
1290                         x = f->p[PROTO(ch->qid)];
1291                         c = x->conv[CONV(ch->qid)];
1292                         if (bp->next)
1293                                 bp = concatblock(bp);
1294                         n = BLEN(bp);
1295                         qbwrite(c->wq, bp);
1296                         return n;
1297                 default:
1298                         return devbwrite(ch, bp, offset);
1299         }
1300 }
1301
1302 static void ip_wake_cb(struct queue *q, void *data, int filter)
1303 {
1304         struct conv *conv = (struct conv*)data;
1305         struct fd_tap *tap_i;
1306         /* For these two, we want to ignore events on the opposite end of the
1307          * queues.  For instance, we want to know when the WQ is writable.  Our
1308          * writes will actually make it readable - we don't want to trigger a tap
1309          * for that.  However, qio doesn't know how/why we are using a queue, or
1310          * even who the ends are (hence the callbacks) */
1311         if ((filter & FDTAP_FILT_READABLE) && (q == conv->wq))
1312                 return;
1313         if ((filter & FDTAP_FILT_WRITABLE) && (q == conv->rq))
1314                 return;
1315         /* At this point, we have an event we want to send to our taps (if any).
1316          * The lock protects list integrity and the existence of the tap.
1317          *
1318          * Previously, I thought of using the conv qlock.  That actually breaks, due
1319          * to weird usages of the qlock (someone holds it for a long time, blocking
1320          * the inbound wakeup from etherread4).
1321          *
1322          * I opted for a spinlock for a couple reasons:
1323          * - fire_tap should not block.  ideally it'll be fast too (it's mostly a
1324          * send_event).
1325          * - our callers might not want to block.  A lot of network wakeups will
1326          * come network processes (etherread4) or otherwise unrelated to this
1327          * particular conversation.  I'd rather do something like fire off a KMSG
1328          * than block those.
1329          * - if fire_tap takes a while, holding the lock only slows down other
1330          * events on this *same* conversation, or other tap registration.  not a
1331          * huge deal. */
1332         spin_lock(&conv->tap_lock);
1333         SLIST_FOREACH(tap_i, &conv->data_taps, link)
1334                 fire_tap(tap_i, filter);
1335         spin_unlock(&conv->tap_lock);
1336 }
1337
1338 int iptapfd(struct chan *chan, struct fd_tap *tap, int cmd)
1339 {
1340         struct conv *conv;
1341         struct Proto *x;
1342         struct Fs *f;
1343         int ret;
1344
1345         #define DEVIP_LEGAL_DATA_TAPS (FDTAP_FILT_READABLE | FDTAP_FILT_WRITABLE | \
1346                                        FDTAP_FILT_HANGUP | FDTAP_FILT_PRIORITY |   \
1347                                        FDTAP_FILT_ERROR)
1348         #define DEVIP_LEGAL_LISTEN_TAPS (FDTAP_FILT_READABLE | FDTAP_FILT_HANGUP)
1349
1350         /* That's a lot of pointers to get to the conv! */
1351         f = ipfs[chan->dev];
1352         x = f->p[PROTO(chan->qid)];
1353         conv = x->conv[CONV(chan->qid)];
1354
1355         switch (TYPE(chan->qid)) {
1356                 case Qdata:
1357                         if (tap->filter & ~DEVIP_LEGAL_DATA_TAPS) {
1358                                 set_errno(ENOSYS);
1359                                 set_errstr("Unsupported #%s data tap %p, must be %p", devname(),
1360                                            tap->filter, DEVIP_LEGAL_DATA_TAPS);
1361                                 return -1;
1362                         }
1363                         spin_lock(&conv->tap_lock);
1364                         switch (cmd) {
1365                                 case (FDTAP_CMD_ADD):
1366                                         if (SLIST_EMPTY(&conv->data_taps)) {
1367                                                 qio_set_wake_cb(conv->rq, ip_wake_cb, conv);
1368                                                 qio_set_wake_cb(conv->wq, ip_wake_cb, conv);
1369                                         }
1370                                         SLIST_INSERT_HEAD(&conv->data_taps, tap, link);
1371                                         ret = 0;
1372                                         break;
1373                                 case (FDTAP_CMD_REM):
1374                                         SLIST_REMOVE(&conv->data_taps, tap, fd_tap, link);
1375                                         if (SLIST_EMPTY(&conv->data_taps)) {
1376                                                 qio_set_wake_cb(conv->rq, 0, conv);
1377                                                 qio_set_wake_cb(conv->wq, 0, conv);
1378                                         }
1379                                         ret = 0;
1380                                         break;
1381                                 default:
1382                                         set_errno(ENOSYS);
1383                                         set_errstr("Unsupported #%s data tap command %p",
1384                                                    devname(), cmd);
1385                                         ret = -1;
1386                         }
1387                         spin_unlock(&conv->tap_lock);
1388                         return ret;
1389                 case Qlisten:
1390                         if (tap->filter & ~DEVIP_LEGAL_LISTEN_TAPS) {
1391                                 set_errno(ENOSYS);
1392                                 set_errstr("Unsupported #%s listen tap %p, must be %p",
1393                                            devname(), tap->filter, DEVIP_LEGAL_LISTEN_TAPS);
1394                                 return -1;
1395                         }
1396                         spin_lock(&conv->tap_lock);
1397                         switch (cmd) {
1398                                 case (FDTAP_CMD_ADD):
1399                                         SLIST_INSERT_HEAD(&conv->listen_taps, tap, link);
1400                                         ret = 0;
1401                                         break;
1402                                 case (FDTAP_CMD_REM):
1403                                         SLIST_REMOVE(&conv->listen_taps, tap, fd_tap, link);
1404                                         ret = 0;
1405                                         break;
1406                                 default:
1407                                         set_errno(ENOSYS);
1408                                         set_errstr("Unsupported #%s listen tap command %p",
1409                                                    devname(), cmd);
1410                                         ret = -1;
1411                         }
1412                         spin_unlock(&conv->tap_lock);
1413                         return ret;
1414                 default:
1415                         set_errno(ENOSYS);
1416                         set_errstr("Can't tap #%s file type %d", devname(),
1417                                    TYPE(chan->qid));
1418                         return -1;
1419         }
1420 }
1421
1422 struct dev ipdevtab __devtab = {
1423         .name = "ip",
1424
1425         .reset = ipreset,
1426         .init = ipinit,
1427         .shutdown = devshutdown,
1428         .attach = ipattach,
1429         .walk = ipwalk,
1430         .stat = ipstat,
1431         .open = ipopen,
1432         .create = devcreate,
1433         .close = ipclose,
1434         .read = ipread,
1435         .bread = ipbread,
1436         .write = ipwrite,
1437         .bwrite = ipbwrite,
1438         .remove = devremove,
1439         .wstat = ipwstat,
1440         .power = devpower,
1441         .chaninfo = ipchaninfo,
1442         .tapfd = iptapfd,
1443 };
1444
1445 int Fsproto(struct Fs *f, struct Proto *p)
1446 {
1447         if (f->np >= Maxproto)
1448                 return -1;
1449
1450         qlock_init(&p->qlock);
1451         p->f = f;
1452
1453         if (p->ipproto > 0) {
1454                 if (f->t2p[p->ipproto] != NULL)
1455                         return -1;
1456                 f->t2p[p->ipproto] = p;
1457         }
1458
1459         p->qid.type = QTDIR;
1460         p->qid.path = QID(f->np, 0, Qprotodir);
1461         p->conv = kzmalloc(sizeof(struct conv *) * (p->nc + 1), 0);
1462         if (p->conv == NULL)
1463                 panic("Fsproto");
1464
1465         p->x = f->np;
1466         p->nextport = 0;
1467         p->nextrport = 600;
1468         f->p[f->np++] = p;
1469
1470         return 0;
1471 }
1472
1473 /*
1474  *  return true if this protocol is
1475  *  built in
1476  */
1477 int Fsbuiltinproto(struct Fs *f, uint8_t proto)
1478 {
1479         return f->t2p[proto] != NULL;
1480 }
1481
1482 /*
1483  *  called with protocol locked
1484  */
1485 struct conv *Fsprotoclone(struct Proto *p, char *user)
1486 {
1487         struct conv *c, **pp, **ep;
1488
1489 retry:
1490         c = NULL;
1491         ep = &p->conv[p->nc];
1492         for (pp = p->conv; pp < ep; pp++) {
1493                 c = *pp;
1494                 if (c == NULL) {
1495                         c = kzmalloc(sizeof(struct conv), 0);
1496                         if (c == NULL)
1497                                 error(ENOMEM, ERROR_FIXME);
1498                         qlock_init(&c->qlock);
1499                         qlock_init(&c->listenq);
1500                         rendez_init(&c->cr);
1501                         rendez_init(&c->listenr);
1502                         SLIST_INIT(&c->data_taps);      /* already = 0; set to be futureproof */
1503                         SLIST_INIT(&c->listen_taps);
1504                         spinlock_init(&c->tap_lock);
1505                         qlock(&c->qlock);
1506                         c->p = p;
1507                         c->x = pp - p->conv;
1508                         if (p->ptclsize != 0) {
1509                                 c->ptcl = kzmalloc(p->ptclsize, 0);
1510                                 if (c->ptcl == NULL) {
1511                                         kfree(c);
1512                                         error(ENOMEM, ERROR_FIXME);
1513                                 }
1514                         }
1515                         *pp = c;
1516                         p->ac++;
1517                         c->eq = qopen(1024, Qmsg, 0, 0);
1518                         (*p->create) (c);
1519                         assert(c->rq && c->wq);
1520                         break;
1521                 }
1522                 if (canqlock(&c->qlock)) {
1523                         /*
1524                          *  make sure both processes and protocol
1525                          *  are done with this Conv
1526                          */
1527                         if (c->inuse == 0 && (p->inuse == NULL || (*p->inuse) (c) == 0))
1528                                 break;
1529
1530                         qunlock(&c->qlock);
1531                 }
1532         }
1533         if (pp >= ep) {
1534                 if (p->gc != NULL && (*p->gc) (p))
1535                         goto retry;
1536                 return NULL;
1537         }
1538
1539         c->inuse = 1;
1540         kstrdup(&c->owner, user);
1541         c->perm = 0660;
1542         c->state = Idle;
1543         ipmove(c->laddr, IPnoaddr);
1544         ipmove(c->raddr, IPnoaddr);
1545         c->r = NULL;
1546         c->rgen = 0;
1547         c->lport = 0;
1548         c->rport = 0;
1549         c->restricted = 0;
1550         c->ttl = MAXTTL;
1551         c->tos = DFLTTOS;
1552         c->nonblock = FALSE;
1553         qreopen(c->rq);
1554         qreopen(c->wq);
1555         qreopen(c->eq);
1556
1557         qunlock(&c->qlock);
1558         return c;
1559 }
1560
1561 int Fsconnected(struct conv *c, char *msg)
1562 {
1563         if (msg != NULL && *msg != '\0')
1564                 strlcpy(c->cerr, msg, sizeof(c->cerr));
1565
1566         switch (c->state) {
1567                 case Announcing:
1568                         c->state = Announced;
1569                         break;
1570
1571                 case Connecting:
1572                         c->state = Connected;
1573                         break;
1574         }
1575
1576         rendez_wakeup(&c->cr);
1577         return 0;
1578 }
1579
1580 struct Proto *Fsrcvpcol(struct Fs *f, uint8_t proto)
1581 {
1582         if (f->ipmux)
1583                 return f->ipmux;
1584         else
1585                 return f->t2p[proto];
1586 }
1587
1588 struct Proto *Fsrcvpcolx(struct Fs *f, uint8_t proto)
1589 {
1590         return f->t2p[proto];
1591 }
1592
1593 static void fire_listener_taps(struct conv *conv)
1594 {
1595         struct fd_tap *tap_i;
1596         if (SLIST_EMPTY(&conv->listen_taps))
1597                 return;
1598         spin_lock(&conv->tap_lock);
1599         SLIST_FOREACH(tap_i, &conv->listen_taps, link)
1600                 fire_tap(tap_i, FDTAP_FILT_READABLE);
1601         spin_unlock(&conv->tap_lock);
1602 }
1603
1604 /*
1605  *  called with protocol locked
1606  */
1607 struct conv *Fsnewcall(struct conv *c, uint8_t * raddr, uint16_t rport,
1608                                            uint8_t * laddr, uint16_t lport, uint8_t version)
1609 {
1610         struct conv *nc;
1611         struct conv **l;
1612         int i;
1613
1614         qlock(&c->qlock);
1615         i = 0;
1616         for (l = &c->incall; *l; l = &(*l)->next)
1617                 i++;
1618         if (i >= Maxincall) {
1619                 qunlock(&c->qlock);
1620                 return NULL;
1621         }
1622
1623         /* find a free conversation */
1624         nc = Fsprotoclone(c->p, network);
1625         if (nc == NULL) {
1626                 qunlock(&c->qlock);
1627                 return NULL;
1628         }
1629         ipmove(nc->raddr, raddr);
1630         nc->rport = rport;
1631         ipmove(nc->laddr, laddr);
1632         nc->lport = lport;
1633         nc->next = NULL;
1634         *l = nc;
1635         nc->state = Connected;
1636         nc->ipversion = version;
1637
1638         qunlock(&c->qlock);
1639
1640         rendez_wakeup(&c->listenr);
1641         fire_listener_taps(c);
1642
1643         return nc;
1644 }
1645
1646 static long ndbwrite(struct Fs *f, char *a, uint32_t off, int n)
1647 {
1648         if (off > strlen(f->ndb))
1649                 error(EIO, ERROR_FIXME);
1650         if (off + n >= sizeof(f->ndb) - 1)
1651                 error(EIO, ERROR_FIXME);
1652         memmove(f->ndb + off, a, n);
1653         f->ndb[off + n] = 0;
1654         f->ndbvers++;
1655         f->ndbmtime = seconds();
1656         return n;
1657 }
1658
1659 uint32_t scalednconv(void)
1660 {
1661         //if(conf.npage*BY2PG >= 128*MB)
1662         return Nchans * 4;
1663         //  return Nchans;
1664 }