Have #ip protocol's connect()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 void 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                         error(EFAIL, "address in use");
873                 }
874         }
875         c->lport = lport;
876         qunlock(&p->qlock);
877 }
878
879 /*
880  *  pick a local port and set it
881  */
882 static void setlport(struct conv *c)
883 {
884         struct Proto *p;
885         uint16_t *pp;
886         int x, found;
887
888         p = c->p;
889         if (c->restricted)
890                 pp = &p->nextrport;
891         else
892                 pp = &p->nextport;
893         qlock(&p->qlock);
894         for (;; (*pp)++) {
895                 /*
896                  * Fsproto initialises p->nextport to 0 and the restricted
897                  * ports (p->nextrport) to 600.
898                  * Restricted ports must lie between 600 and 1024.
899                  * For the initial condition or if the unrestricted port number
900                  * has wrapped round, select a random port between 5000 and 1<<15
901                  * to start at.
902                  */
903                 if (c->restricted) {
904                         if (*pp >= 1024)
905                                 *pp = 600;
906                 } else
907                         while (*pp < 5000)
908                                 urandom_read(pp, sizeof(*pp));
909
910                 found = 0;
911                 for (x = 0; x < p->nc; x++) {
912                         if (p->conv[x] == NULL)
913                                 break;
914                         if (p->conv[x]->lport == *pp) {
915                                 found = 1;
916                                 break;
917                         }
918                 }
919                 if (!found)
920                         break;
921         }
922         c->lport = (*pp)++;
923         qunlock(&p->qlock);
924 }
925
926 /*
927  *  set a local address and port from a string of the form
928  *      [address!]port[!r]
929  */
930 static void setladdrport(struct conv *c, char *str, int announcing)
931 {
932         char *p;
933         uint16_t lport;
934         uint8_t addr[IPaddrlen];
935
936         /*
937          *  ignore restricted part if it exists.  it's
938          *  meaningless on local ports.
939          */
940         p = strchr(str, '!');
941         if (p != NULL) {
942                 *p++ = 0;
943                 if (strcmp(p, "r") == 0)
944                         p = NULL;
945         }
946
947         c->lport = 0;
948         if (p == NULL) {
949                 if (announcing)
950                         ipmove(c->laddr, IPnoaddr);
951                 else
952                         setladdr(c);
953                 p = str;
954         } else {
955                 if (strcmp(str, "*") == 0)
956                         ipmove(c->laddr, IPnoaddr);
957                 else {
958                         parseip(addr, str);
959                         if (ipforme(c->p->f, addr))
960                                 ipmove(c->laddr, addr);
961                         else
962                                 error(EFAIL, "not a local IP address");
963                 }
964         }
965
966         /* one process can get all connections */
967         if (announcing && strcmp(p, "*") == 0) {
968                 if (!iseve())
969                         error(EPERM, ERROR_FIXME);
970                 setluniqueport(c, 0);
971         }
972
973         lport = atoi(p);
974         if (lport <= 0)
975                 setlport(c);
976         else
977                 setluniqueport(c, lport);
978 }
979
980 static void setraddrport(struct conv *c, char *str)
981 {
982         char *p;
983
984         p = strchr(str, '!');
985         if (p == NULL)
986                 error(EFAIL, "malformed address");
987         *p++ = 0;
988         parseip(c->raddr, str);
989         c->rport = atoi(p);
990         p = strchr(p, '!');
991         if (p) {
992                 if (strstr(p, "!r") != NULL)
993                         c->restricted = 1;
994         }
995 }
996
997 /*
998  *  called by protocol connect routine to set addresses
999  */
1000 void Fsstdconnect(struct conv *c, char *argv[], int argc)
1001 {
1002         switch (argc) {
1003                 default:
1004                         error(EINVAL, "bad args to %s", __func__);
1005                 case 2:
1006                         setraddrport(c, argv[1]);
1007                         setladdr(c);
1008                         setlport(c);
1009                         break;
1010                 case 3:
1011                         setraddrport(c, argv[1]);
1012                         setladdrport(c, argv[2], 0);
1013                         break;
1014         }
1015
1016         if ((memcmp(c->raddr, v4prefix, IPv4off) == 0 &&
1017                  memcmp(c->laddr, v4prefix, IPv4off) == 0)
1018                 || ipcmp(c->raddr, IPnoaddr) == 0)
1019                 c->ipversion = V4;
1020         else
1021                 c->ipversion = V6;
1022 }
1023
1024 /*
1025  *  initiate connection and sleep till its set up
1026  */
1027 static int connected(void *a)
1028 {
1029         return ((struct conv *)a)->state == Connected;
1030 }
1031
1032 static void connectctlmsg(struct Proto *x, struct conv *c, struct cmdbuf *cb)
1033 {
1034         ERRSTACK(1);
1035         char *p;
1036
1037         if (c->state != 0)
1038                 error(EBUSY, ERROR_FIXME);
1039         c->state = Connecting;
1040         c->cerr[0] = '\0';
1041         if (x->connect == NULL)
1042                 error(EFAIL, "connect not supported");
1043         x->connect(c, cb->f, cb->nf);
1044
1045         qunlock(&c->qlock);
1046         if (waserror()) {
1047                 qlock(&c->qlock);
1048                 nexterror();
1049         }
1050         rendez_sleep(&c->cr, connected, c);
1051         qlock(&c->qlock);
1052         poperror();
1053
1054         if (c->cerr[0] != '\0')
1055                 error(EFAIL, c->cerr);
1056 }
1057
1058 /*
1059  *  called by protocol announce routine to set addresses
1060  */
1061 char *Fsstdannounce(struct conv *c, char *argv[], int argc)
1062 {
1063         ERRSTACK(1);
1064
1065         memset(c->raddr, 0, sizeof(c->raddr));
1066         c->rport = 0;
1067         switch (argc) {
1068                 default:
1069                         return "bad args to announce";
1070                 case 2:
1071                         if (waserror()) {
1072                                 poperror();
1073                                 return current_errstr();
1074                         }
1075                         setladdrport(c, argv[1], 1);
1076                         poperror();
1077                         break;
1078         }
1079         return 0;
1080 }
1081
1082 /*
1083  *  initiate announcement and sleep till its set up
1084  */
1085 static int announced(void *a)
1086 {
1087         return ((struct conv *)a)->state == Announced;
1088 }
1089
1090 static void announcectlmsg(struct Proto *x, struct conv *c, struct cmdbuf *cb)
1091 {
1092         ERRSTACK(1);
1093         char *p;
1094
1095         if (c->state != 0)
1096                 error(EBUSY, ERROR_FIXME);
1097         c->state = Announcing;
1098         c->cerr[0] = '\0';
1099         if (x->announce == NULL)
1100                 error(EFAIL, "announce not supported");
1101         p = x->announce(c, cb->f, cb->nf);
1102         if (p != NULL)
1103                 error(EFAIL, p);
1104
1105         qunlock(&c->qlock);
1106         if (waserror()) {
1107                 qlock(&c->qlock);
1108                 nexterror();
1109         }
1110         rendez_sleep(&c->cr, announced, c);
1111         qlock(&c->qlock);
1112         poperror();
1113
1114         if (c->cerr[0] != '\0')
1115                 error(EFAIL, c->cerr);
1116 }
1117
1118 /*
1119  *  called by protocol bind routine to set addresses
1120  */
1121 char *Fsstdbind(struct conv *c, char *argv[], int argc)
1122 {
1123         ERRSTACK(1);
1124
1125         switch (argc) {
1126                 default:
1127                         return "bad args to bind";
1128                 case 2:
1129                         if (waserror()) {
1130                                 poperror();
1131                                 return current_errstr();
1132                         }
1133                         setladdrport(c, argv[1], 0);
1134                         poperror();
1135                         break;
1136         }
1137         return 0;
1138 }
1139
1140 void Fsconvnonblock(struct conv *cv, bool onoff)
1141 {
1142         qnonblock(cv->wq, onoff);
1143         qnonblock(cv->rq, onoff);
1144         cv->nonblock = onoff;
1145 }
1146
1147 static void bindctlmsg(struct Proto *x, struct conv *c, struct cmdbuf *cb)
1148 {
1149         char *p;
1150
1151         if (x->bind == NULL)
1152                 p = Fsstdbind(c, cb->f, cb->nf);
1153         else
1154                 p = x->bind(c, cb->f, cb->nf);
1155         if (p != NULL)
1156                 error(EFAIL, p);
1157 }
1158
1159 static void nonblockctlmsg(struct conv *c, struct cmdbuf *cb)
1160 {
1161         if (cb->nf < 2)
1162                 goto err;
1163         if (!strcmp(cb->f[1], "on"))
1164                 Fsconvnonblock(c, TRUE);
1165         else if (!strcmp(cb->f[1], "off"))
1166                 Fsconvnonblock(c, FALSE);
1167         else
1168                 goto err;
1169         return;
1170 err:
1171         error(EINVAL, "nonblock [on|off]");
1172 }
1173
1174 static void tosctlmsg(struct conv *c, struct cmdbuf *cb)
1175 {
1176         if (cb->nf < 2)
1177                 c->tos = 0;
1178         else
1179                 c->tos = atoi(cb->f[1]);
1180 }
1181
1182 static void ttlctlmsg(struct conv *c, struct cmdbuf *cb)
1183 {
1184         if (cb->nf < 2)
1185                 c->ttl = MAXTTL;
1186         else
1187                 c->ttl = atoi(cb->f[1]);
1188 }
1189
1190 static long ipwrite(struct chan *ch, void *v, long n, int64_t off)
1191 {
1192         ERRSTACK(1);
1193         struct conv *c;
1194         struct Proto *x;
1195         char *p;
1196         struct cmdbuf *cb;
1197         uint8_t ia[IPaddrlen], ma[IPaddrlen];
1198         struct Fs *f;
1199         char *a;
1200
1201         a = v;
1202         f = ipfs[ch->dev];
1203
1204         switch (TYPE(ch->qid)) {
1205                 default:
1206                         error(EPERM, ERROR_FIXME);
1207                 case Qdata:
1208                         x = f->p[PROTO(ch->qid)];
1209                         c = x->conv[CONV(ch->qid)];
1210                         qwrite(c->wq, a, n);
1211                         break;
1212                 case Qarp:
1213                         return arpwrite(f, a, n);
1214                 case Qiproute:
1215                         return routewrite(f, ch, a, n);
1216                 case Qlog:
1217                         netlogctl(f, a, n);
1218                         return n;
1219                 case Qndb:
1220                         return ndbwrite(f, a, off, n);
1221                 case Qctl:
1222                         x = f->p[PROTO(ch->qid)];
1223                         c = x->conv[CONV(ch->qid)];
1224                         cb = parsecmd(a, n);
1225
1226                         qlock(&c->qlock);
1227                         if (waserror()) {
1228                                 qunlock(&c->qlock);
1229                                 kfree(cb);
1230                                 nexterror();
1231                         }
1232                         if (cb->nf < 1)
1233                                 error(EFAIL, "short control request");
1234                         if (strcmp(cb->f[0], "connect") == 0)
1235                                 connectctlmsg(x, c, cb);
1236                         else if (strcmp(cb->f[0], "announce") == 0)
1237                                 announcectlmsg(x, c, cb);
1238                         else if (strcmp(cb->f[0], "bind") == 0)
1239                                 bindctlmsg(x, c, cb);
1240                         else if (strcmp(cb->f[0], "nonblock") == 0)
1241                                 nonblockctlmsg(c, cb);
1242                         else if (strcmp(cb->f[0], "ttl") == 0)
1243                                 ttlctlmsg(c, cb);
1244                         else if (strcmp(cb->f[0], "tos") == 0)
1245                                 tosctlmsg(c, cb);
1246                         else if (strcmp(cb->f[0], "ignoreadvice") == 0)
1247                                 c->ignoreadvice = 1;
1248                         else if (strcmp(cb->f[0], "addmulti") == 0) {
1249                                 if (cb->nf < 2)
1250                                         error(EFAIL, "addmulti needs interface address");
1251                                 if (cb->nf == 2) {
1252                                         if (!ipismulticast(c->raddr))
1253                                                 error(EFAIL, "addmulti for a non multicast address");
1254                                         parseip(ia, cb->f[1]);
1255                                         ipifcaddmulti(c, c->raddr, ia);
1256                                 } else {
1257                                         parseip(ma, cb->f[2]);
1258                                         if (!ipismulticast(ma))
1259                                                 error(EFAIL, "addmulti for a non multicast address");
1260                                         parseip(ia, cb->f[1]);
1261                                         ipifcaddmulti(c, ma, ia);
1262                                 }
1263                         } else if (strcmp(cb->f[0], "remmulti") == 0) {
1264                                 if (cb->nf < 2)
1265                                         error(EFAIL, "remmulti needs interface address");
1266                                 if (!ipismulticast(c->raddr))
1267                                         error(EFAIL, "remmulti for a non multicast address");
1268                                 parseip(ia, cb->f[1]);
1269                                 ipifcremmulti(c, c->raddr, ia);
1270                         } else if (x->ctl != NULL) {
1271                                 x->ctl(c, cb->f, cb->nf);
1272                         } else
1273                                 error(EFAIL, "unknown control request");
1274                         qunlock(&c->qlock);
1275                         kfree(cb);
1276                         poperror();
1277         }
1278         return n;
1279 }
1280
1281 static long ipbwrite(struct chan *ch, struct block *bp, uint32_t offset)
1282 {
1283         struct conv *c;
1284         struct Proto *x;
1285         struct Fs *f;
1286         int n;
1287
1288         switch (TYPE(ch->qid)) {
1289                 case Qdata:
1290                         f = ipfs[ch->dev];
1291                         x = f->p[PROTO(ch->qid)];
1292                         c = x->conv[CONV(ch->qid)];
1293                         if (bp->next)
1294                                 bp = concatblock(bp);
1295                         n = BLEN(bp);
1296                         qbwrite(c->wq, bp);
1297                         return n;
1298                 default:
1299                         return devbwrite(ch, bp, offset);
1300         }
1301 }
1302
1303 static void ip_wake_cb(struct queue *q, void *data, int filter)
1304 {
1305         struct conv *conv = (struct conv*)data;
1306         struct fd_tap *tap_i;
1307         /* For these two, we want to ignore events on the opposite end of the
1308          * queues.  For instance, we want to know when the WQ is writable.  Our
1309          * writes will actually make it readable - we don't want to trigger a tap
1310          * for that.  However, qio doesn't know how/why we are using a queue, or
1311          * even who the ends are (hence the callbacks) */
1312         if ((filter & FDTAP_FILT_READABLE) && (q == conv->wq))
1313                 return;
1314         if ((filter & FDTAP_FILT_WRITABLE) && (q == conv->rq))
1315                 return;
1316         /* At this point, we have an event we want to send to our taps (if any).
1317          * The lock protects list integrity and the existence of the tap.
1318          *
1319          * Previously, I thought of using the conv qlock.  That actually breaks, due
1320          * to weird usages of the qlock (someone holds it for a long time, blocking
1321          * the inbound wakeup from etherread4).
1322          *
1323          * I opted for a spinlock for a couple reasons:
1324          * - fire_tap should not block.  ideally it'll be fast too (it's mostly a
1325          * send_event).
1326          * - our callers might not want to block.  A lot of network wakeups will
1327          * come network processes (etherread4) or otherwise unrelated to this
1328          * particular conversation.  I'd rather do something like fire off a KMSG
1329          * than block those.
1330          * - if fire_tap takes a while, holding the lock only slows down other
1331          * events on this *same* conversation, or other tap registration.  not a
1332          * huge deal. */
1333         spin_lock(&conv->tap_lock);
1334         SLIST_FOREACH(tap_i, &conv->data_taps, link)
1335                 fire_tap(tap_i, filter);
1336         spin_unlock(&conv->tap_lock);
1337 }
1338
1339 int iptapfd(struct chan *chan, struct fd_tap *tap, int cmd)
1340 {
1341         struct conv *conv;
1342         struct Proto *x;
1343         struct Fs *f;
1344         int ret;
1345
1346         #define DEVIP_LEGAL_DATA_TAPS (FDTAP_FILT_READABLE | FDTAP_FILT_WRITABLE | \
1347                                        FDTAP_FILT_HANGUP | FDTAP_FILT_PRIORITY |   \
1348                                        FDTAP_FILT_ERROR)
1349         #define DEVIP_LEGAL_LISTEN_TAPS (FDTAP_FILT_READABLE | FDTAP_FILT_HANGUP)
1350
1351         /* That's a lot of pointers to get to the conv! */
1352         f = ipfs[chan->dev];
1353         x = f->p[PROTO(chan->qid)];
1354         conv = x->conv[CONV(chan->qid)];
1355
1356         switch (TYPE(chan->qid)) {
1357                 case Qdata:
1358                         if (tap->filter & ~DEVIP_LEGAL_DATA_TAPS) {
1359                                 set_errno(ENOSYS);
1360                                 set_errstr("Unsupported #%s data tap %p, must be %p", devname(),
1361                                            tap->filter, DEVIP_LEGAL_DATA_TAPS);
1362                                 return -1;
1363                         }
1364                         spin_lock(&conv->tap_lock);
1365                         switch (cmd) {
1366                                 case (FDTAP_CMD_ADD):
1367                                         if (SLIST_EMPTY(&conv->data_taps)) {
1368                                                 qio_set_wake_cb(conv->rq, ip_wake_cb, conv);
1369                                                 qio_set_wake_cb(conv->wq, ip_wake_cb, conv);
1370                                         }
1371                                         SLIST_INSERT_HEAD(&conv->data_taps, tap, link);
1372                                         ret = 0;
1373                                         break;
1374                                 case (FDTAP_CMD_REM):
1375                                         SLIST_REMOVE(&conv->data_taps, tap, fd_tap, link);
1376                                         if (SLIST_EMPTY(&conv->data_taps)) {
1377                                                 qio_set_wake_cb(conv->rq, 0, conv);
1378                                                 qio_set_wake_cb(conv->wq, 0, conv);
1379                                         }
1380                                         ret = 0;
1381                                         break;
1382                                 default:
1383                                         set_errno(ENOSYS);
1384                                         set_errstr("Unsupported #%s data tap command %p",
1385                                                    devname(), cmd);
1386                                         ret = -1;
1387                         }
1388                         spin_unlock(&conv->tap_lock);
1389                         return ret;
1390                 case Qlisten:
1391                         if (tap->filter & ~DEVIP_LEGAL_LISTEN_TAPS) {
1392                                 set_errno(ENOSYS);
1393                                 set_errstr("Unsupported #%s listen tap %p, must be %p",
1394                                            devname(), tap->filter, DEVIP_LEGAL_LISTEN_TAPS);
1395                                 return -1;
1396                         }
1397                         spin_lock(&conv->tap_lock);
1398                         switch (cmd) {
1399                                 case (FDTAP_CMD_ADD):
1400                                         SLIST_INSERT_HEAD(&conv->listen_taps, tap, link);
1401                                         ret = 0;
1402                                         break;
1403                                 case (FDTAP_CMD_REM):
1404                                         SLIST_REMOVE(&conv->listen_taps, tap, fd_tap, link);
1405                                         ret = 0;
1406                                         break;
1407                                 default:
1408                                         set_errno(ENOSYS);
1409                                         set_errstr("Unsupported #%s listen tap command %p",
1410                                                    devname(), cmd);
1411                                         ret = -1;
1412                         }
1413                         spin_unlock(&conv->tap_lock);
1414                         return ret;
1415                 default:
1416                         set_errno(ENOSYS);
1417                         set_errstr("Can't tap #%s file type %d", devname(),
1418                                    TYPE(chan->qid));
1419                         return -1;
1420         }
1421 }
1422
1423 struct dev ipdevtab __devtab = {
1424         .name = "ip",
1425
1426         .reset = ipreset,
1427         .init = ipinit,
1428         .shutdown = devshutdown,
1429         .attach = ipattach,
1430         .walk = ipwalk,
1431         .stat = ipstat,
1432         .open = ipopen,
1433         .create = devcreate,
1434         .close = ipclose,
1435         .read = ipread,
1436         .bread = ipbread,
1437         .write = ipwrite,
1438         .bwrite = ipbwrite,
1439         .remove = devremove,
1440         .wstat = ipwstat,
1441         .power = devpower,
1442         .chaninfo = ipchaninfo,
1443         .tapfd = iptapfd,
1444 };
1445
1446 int Fsproto(struct Fs *f, struct Proto *p)
1447 {
1448         if (f->np >= Maxproto)
1449                 return -1;
1450
1451         qlock_init(&p->qlock);
1452         p->f = f;
1453
1454         if (p->ipproto > 0) {
1455                 if (f->t2p[p->ipproto] != NULL)
1456                         return -1;
1457                 f->t2p[p->ipproto] = p;
1458         }
1459
1460         p->qid.type = QTDIR;
1461         p->qid.path = QID(f->np, 0, Qprotodir);
1462         p->conv = kzmalloc(sizeof(struct conv *) * (p->nc + 1), 0);
1463         if (p->conv == NULL)
1464                 panic("Fsproto");
1465
1466         p->x = f->np;
1467         p->nextport = 0;
1468         p->nextrport = 600;
1469         f->p[f->np++] = p;
1470
1471         return 0;
1472 }
1473
1474 /*
1475  *  return true if this protocol is
1476  *  built in
1477  */
1478 int Fsbuiltinproto(struct Fs *f, uint8_t proto)
1479 {
1480         return f->t2p[proto] != NULL;
1481 }
1482
1483 /*
1484  *  called with protocol locked
1485  */
1486 struct conv *Fsprotoclone(struct Proto *p, char *user)
1487 {
1488         struct conv *c, **pp, **ep;
1489
1490 retry:
1491         c = NULL;
1492         ep = &p->conv[p->nc];
1493         for (pp = p->conv; pp < ep; pp++) {
1494                 c = *pp;
1495                 if (c == NULL) {
1496                         c = kzmalloc(sizeof(struct conv), 0);
1497                         if (c == NULL)
1498                                 error(ENOMEM, ERROR_FIXME);
1499                         qlock_init(&c->qlock);
1500                         qlock_init(&c->listenq);
1501                         rendez_init(&c->cr);
1502                         rendez_init(&c->listenr);
1503                         SLIST_INIT(&c->data_taps);      /* already = 0; set to be futureproof */
1504                         SLIST_INIT(&c->listen_taps);
1505                         spinlock_init(&c->tap_lock);
1506                         qlock(&c->qlock);
1507                         c->p = p;
1508                         c->x = pp - p->conv;
1509                         if (p->ptclsize != 0) {
1510                                 c->ptcl = kzmalloc(p->ptclsize, 0);
1511                                 if (c->ptcl == NULL) {
1512                                         kfree(c);
1513                                         error(ENOMEM, ERROR_FIXME);
1514                                 }
1515                         }
1516                         *pp = c;
1517                         p->ac++;
1518                         c->eq = qopen(1024, Qmsg, 0, 0);
1519                         (*p->create) (c);
1520                         assert(c->rq && c->wq);
1521                         break;
1522                 }
1523                 if (canqlock(&c->qlock)) {
1524                         /*
1525                          *  make sure both processes and protocol
1526                          *  are done with this Conv
1527                          */
1528                         if (c->inuse == 0 && (p->inuse == NULL || (*p->inuse) (c) == 0))
1529                                 break;
1530
1531                         qunlock(&c->qlock);
1532                 }
1533         }
1534         if (pp >= ep) {
1535                 if (p->gc != NULL && (*p->gc) (p))
1536                         goto retry;
1537                 return NULL;
1538         }
1539
1540         c->inuse = 1;
1541         kstrdup(&c->owner, user);
1542         c->perm = 0660;
1543         c->state = Idle;
1544         ipmove(c->laddr, IPnoaddr);
1545         ipmove(c->raddr, IPnoaddr);
1546         c->r = NULL;
1547         c->rgen = 0;
1548         c->lport = 0;
1549         c->rport = 0;
1550         c->restricted = 0;
1551         c->ttl = MAXTTL;
1552         c->tos = DFLTTOS;
1553         c->nonblock = FALSE;
1554         qreopen(c->rq);
1555         qreopen(c->wq);
1556         qreopen(c->eq);
1557
1558         qunlock(&c->qlock);
1559         return c;
1560 }
1561
1562 int Fsconnected(struct conv *c, char *msg)
1563 {
1564         if (msg != NULL && *msg != '\0')
1565                 strlcpy(c->cerr, msg, sizeof(c->cerr));
1566
1567         switch (c->state) {
1568                 case Announcing:
1569                         c->state = Announced;
1570                         break;
1571
1572                 case Connecting:
1573                         c->state = Connected;
1574                         break;
1575         }
1576
1577         rendez_wakeup(&c->cr);
1578         return 0;
1579 }
1580
1581 struct Proto *Fsrcvpcol(struct Fs *f, uint8_t proto)
1582 {
1583         if (f->ipmux)
1584                 return f->ipmux;
1585         else
1586                 return f->t2p[proto];
1587 }
1588
1589 struct Proto *Fsrcvpcolx(struct Fs *f, uint8_t proto)
1590 {
1591         return f->t2p[proto];
1592 }
1593
1594 static void fire_listener_taps(struct conv *conv)
1595 {
1596         struct fd_tap *tap_i;
1597         if (SLIST_EMPTY(&conv->listen_taps))
1598                 return;
1599         spin_lock(&conv->tap_lock);
1600         SLIST_FOREACH(tap_i, &conv->listen_taps, link)
1601                 fire_tap(tap_i, FDTAP_FILT_READABLE);
1602         spin_unlock(&conv->tap_lock);
1603 }
1604
1605 /*
1606  *  called with protocol locked
1607  */
1608 struct conv *Fsnewcall(struct conv *c, uint8_t * raddr, uint16_t rport,
1609                                            uint8_t * laddr, uint16_t lport, uint8_t version)
1610 {
1611         struct conv *nc;
1612         struct conv **l;
1613         int i;
1614
1615         qlock(&c->qlock);
1616         i = 0;
1617         for (l = &c->incall; *l; l = &(*l)->next)
1618                 i++;
1619         if (i >= Maxincall) {
1620                 qunlock(&c->qlock);
1621                 return NULL;
1622         }
1623
1624         /* find a free conversation */
1625         nc = Fsprotoclone(c->p, network);
1626         if (nc == NULL) {
1627                 qunlock(&c->qlock);
1628                 return NULL;
1629         }
1630         ipmove(nc->raddr, raddr);
1631         nc->rport = rport;
1632         ipmove(nc->laddr, laddr);
1633         nc->lport = lport;
1634         nc->next = NULL;
1635         *l = nc;
1636         nc->state = Connected;
1637         nc->ipversion = version;
1638
1639         qunlock(&c->qlock);
1640
1641         rendez_wakeup(&c->listenr);
1642         fire_listener_taps(c);
1643
1644         return nc;
1645 }
1646
1647 static long ndbwrite(struct Fs *f, char *a, uint32_t off, int n)
1648 {
1649         if (off > strlen(f->ndb))
1650                 error(EIO, ERROR_FIXME);
1651         if (off + n >= sizeof(f->ndb) - 1)
1652                 error(EIO, ERROR_FIXME);
1653         memmove(f->ndb + off, a, n);
1654         f->ndb[off + n] = 0;
1655         f->ndbvers++;
1656         f->ndbmtime = seconds();
1657         return n;
1658 }
1659
1660 uint32_t scalednconv(void)
1661 {
1662         //if(conf.npage*BY2PG >= 128*MB)
1663         return Nchans * 4;
1664         //  return Nchans;
1665 }