net: Add a helper chan2conv()
[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 struct conv *chan2conv(struct chan *chan)
104 {
105         /* That's a lot of pointers to get to the conv! */
106         return ipfs[chan->dev]->p[PROTO(chan->qid)]->conv[CONV(chan->qid)];
107 }
108
109 static inline int founddevdir(struct chan *c, struct qid q, char *n,
110                                                           int64_t length, char *user, long perm,
111                                                           struct dir *db)
112 {
113         devdir(c, q, n, length, user, perm, db);
114         return 1;
115 }
116
117 static int topdirgen(struct chan *c, struct dir *dp)
118 {
119         struct qid q;
120         mkqid(&q, QID(0, 0, Qtopdir), 0, QTDIR);
121         snprintf(get_cur_genbuf(), GENBUF_SZ, "#%s%lu", devname(), c->dev);
122         return founddevdir(c, q, get_cur_genbuf(), 0, network, 0555, dp);
123 }
124
125
126 static int ip3gen(struct chan *c, int i, struct dir *dp)
127 {
128         struct qid q;
129         struct conv *cv;
130         char *p;
131
132         cv = chan2conv(c);
133         if (cv->owner == NULL)
134                 kstrdup(&cv->owner, eve);
135         mkqid(&q, QID(PROTO(c->qid), CONV(c->qid), i), 0, QTFILE);
136
137         switch (i) {
138                 default:
139                         return -1;
140                 case Qctl:
141                         return founddevdir(c, q, "ctl", 0,
142                                                    cv->owner, cv->perm, dp);
143                 case Qdata:
144                         return founddevdir(c, q, "data", qlen(cv->rq),
145                                                            cv->owner, cv->perm, dp);
146                 case Qerr:
147                         return founddevdir(c, q, "err", qlen(cv->eq),
148                                                            cv->owner, cv->perm, dp);
149                 case Qlisten:
150                         return founddevdir(c, q, "listen", 0, cv->owner, cv->perm, dp);
151                 case Qlocal:
152                         p = "local";
153                         break;
154                 case Qremote:
155                         p = "remote";
156                         break;
157                 case Qsnoop:
158                         if (strcmp(cv->p->name, "ipifc") != 0)
159                                 return -1;
160                         return founddevdir(c, q, "snoop", qlen(cv->sq),
161                                                            cv->owner, 0400, dp);
162                 case Qstatus:
163                         p = "status";
164                         break;
165         }
166         return founddevdir(c, q, p, 0, cv->owner, 0444, dp);
167 }
168
169 static int ip2gen(struct chan *c, int i, struct dir *dp)
170 {
171         struct qid q;
172         mkqid(&q, QID(PROTO(c->qid), 0, i), 0, QTFILE);
173         switch (i) {
174                 case Qclone:
175                         return founddevdir(c, q, "clone", 0, network, 0666, dp);
176                 case Qstats:
177                         return founddevdir(c, q, "stats", 0, network, 0444, dp);
178         }
179         return -1;
180 }
181
182 static int ip1gen(struct chan *c, int i, struct dir *dp)
183 {
184         struct qid q;
185         char *p;
186         int prot;
187         int len = 0;
188         struct Fs *f;
189         extern uint32_t kerndate;
190
191         f = ipfs[c->dev];
192
193         prot = 0666;
194         mkqid(&q, QID(0, 0, i), 0, QTFILE);
195         switch (i) {
196                 default:
197                         return -1;
198                 case Qarp:
199                         p = "arp";
200                         break;
201                 case Qndb:
202                         p = "ndb";
203                         len = strlen(f->ndb);
204                         q.vers = f->ndbvers;
205                         break;
206                 case Qiproute:
207                         p = "iproute";
208                         break;
209                 case Qipselftab:
210                         p = "ipselftab";
211                         prot = 0444;
212                         break;
213                 case Qiprouter:
214                         p = "iprouter";
215                         break;
216                 case Qlog:
217                         p = "log";
218                         break;
219         }
220         devdir(c, q, p, len, network, prot, dp);
221         if (i == Qndb && f->ndbmtime > kerndate)
222                 dp->mtime = f->ndbmtime;
223         return 1;
224 }
225
226 static int
227 ipgen(struct chan *c, char *unused_char_p_t, struct dirtab *d, int unused_int,
228           int s, struct dir *dp)
229 {
230         struct qid q;
231         struct conv *cv;
232         struct Fs *f;
233
234         f = ipfs[c->dev];
235
236         switch (TYPE(c->qid)) {
237                 case Qtopdir:
238                         if (s == DEVDOTDOT)
239                                 return topdirgen(c, dp);
240                         if (s < f->np) {
241                                 if (f->p[s]->connect == NULL)
242                                         return 0;       /* protocol with no user interface */
243                                 mkqid(&q, QID(s, 0, Qprotodir), 0, QTDIR);
244                                 return founddevdir(c, q, f->p[s]->name, 0, network, 0555, dp);
245                         }
246                         s -= f->np;
247                         return ip1gen(c, s + Qtopbase, dp);
248                 case Qarp:
249                 case Qndb:
250                 case Qlog:
251                 case Qiproute:
252                 case Qiprouter:
253                 case Qipselftab:
254                         return ip1gen(c, TYPE(c->qid), dp);
255                 case Qprotodir:
256                         if (s == DEVDOTDOT)
257                                 return topdirgen(c, dp);
258                         else if (s < f->p[PROTO(c->qid)]->ac) {
259                                 cv = f->p[PROTO(c->qid)]->conv[s];
260                                 snprintf(get_cur_genbuf(), GENBUF_SZ, "%d", s);
261                                 mkqid(&q, QID(PROTO(c->qid), s, Qconvdir), 0, QTDIR);
262                                 return
263                                         founddevdir(c, q, get_cur_genbuf(), 0, cv->owner, 0555, dp);
264                         }
265                         s -= f->p[PROTO(c->qid)]->ac;
266                         return ip2gen(c, s + Qprotobase, dp);
267                 case Qclone:
268                 case Qstats:
269                         return ip2gen(c, TYPE(c->qid), dp);
270                 case Qconvdir:
271                         if (s == DEVDOTDOT) {
272                                 s = PROTO(c->qid);
273                                 mkqid(&q, QID(s, 0, Qprotodir), 0, QTDIR);
274                                 devdir(c, q, f->p[s]->name, 0, network, 0555, dp);
275                                 return 1;
276                         }
277                         return ip3gen(c, s + Qconvbase, dp);
278                 case Qctl:
279                 case Qdata:
280                 case Qerr:
281                 case Qlisten:
282                 case Qlocal:
283                 case Qremote:
284                 case Qstatus:
285                 case Qsnoop:
286                         return ip3gen(c, TYPE(c->qid), dp);
287         }
288         return -1;
289 }
290
291 static void ipinit(void)
292 {
293         qlock_init(&fslock);
294         nullmediumlink();
295         pktmediumlink();
296 /* if only
297         fmtinstall('i', eipfmt);
298         fmtinstall('I', eipfmt);
299         fmtinstall('E', eipfmt);
300         fmtinstall('V', eipfmt);
301         fmtinstall('M', eipfmt);
302 */
303 }
304
305 static void ipreset(void)
306 {
307 }
308
309 static struct Fs *ipgetfs(int dev)
310 {
311         extern void (*ipprotoinit[]) (struct Fs *);
312         struct Fs *f;
313         int i;
314
315         if (dev >= Nfs)
316                 return NULL;
317
318         qlock(&fslock);
319         if (ipfs[dev] == NULL) {
320                 f = kzmalloc(sizeof(struct Fs), MEM_WAIT);
321                 rwinit(&f->rwlock);
322                 qlock_init(&f->iprouter.qlock);
323                 ip_init(f);
324                 arpinit(f);
325                 netloginit(f);
326                 for (i = 0; ipprotoinit[i]; i++)
327                         ipprotoinit[i] (f);
328                 f->dev = dev;
329                 ipfs[dev] = f;
330         }
331         qunlock(&fslock);
332
333         return ipfs[dev];
334 }
335
336 struct IPaux *newipaux(char *owner, char *tag)
337 {
338         struct IPaux *a;
339         int n;
340
341         a = kzmalloc(sizeof(*a), 0);
342         kstrdup(&a->owner, owner);
343         memset(a->tag, ' ', sizeof(a->tag));
344         n = strlen(tag);
345         if (n > sizeof(a->tag))
346                 n = sizeof(a->tag);
347         memmove(a->tag, tag, n);
348         return a;
349 }
350
351 #define ATTACHER(c) (((struct IPaux*)((c)->aux))->owner)
352
353 static struct chan *ipattach(char *spec)
354 {
355         struct chan *c;
356         int dev;
357
358         dev = atoi(spec);
359         if (dev >= Nfs)
360                 error(EFAIL, "bad specification");
361
362         ipgetfs(dev);
363         c = devattach(devname(), spec);
364         mkqid(&c->qid, QID(0, 0, Qtopdir), 0, QTDIR);
365         c->dev = dev;
366
367         c->aux = newipaux(commonuser(), "none");
368
369         return c;
370 }
371
372 static struct walkqid *ipwalk(struct chan *c, struct chan *nc, char **name,
373                                                           int nname)
374 {
375         struct IPaux *a = c->aux;
376         struct walkqid *w;
377
378         w = devwalk(c, nc, name, nname, NULL, 0, ipgen);
379         if (w != NULL && w->clone != NULL)
380                 w->clone->aux = newipaux(a->owner, a->tag);
381         return w;
382 }
383
384 static int ipstat(struct chan *c, uint8_t * db, int n)
385 {
386         return devstat(c, db, n, NULL, 0, ipgen);
387 }
388
389 static int should_wake(void *arg)
390 {
391         struct conv *cv = arg;
392         /* signal that the conv is closed */
393         if (qisclosed(cv->rq))
394                 return TRUE;
395         return cv->incall != NULL;
396 }
397
398 static struct chan *ipopen(struct chan *c, int omode)
399 {
400         ERRSTACK(2);
401         struct conv *cv, *nc;
402         struct Proto *p;
403         int perm;
404         struct Fs *f;
405
406         /* perm is a lone rwx, not the rwx------ from the conversion */
407         perm = omode_to_rwx(omode) >> 6;
408
409         f = ipfs[c->dev];
410
411         switch (TYPE(c->qid)) {
412                 default:
413                         break;
414                 case Qndb:
415                         if (omode & (O_WRITE | O_TRUNC) && !iseve())
416                                 error(EPERM, ERROR_FIXME);
417                         if ((omode & (O_WRITE | O_TRUNC)) == (O_WRITE | O_TRUNC))
418                                 f->ndb[0] = 0;
419                         break;
420                 case Qlog:
421                         netlogopen(f);
422                         break;
423                 case Qiprouter:
424                         iprouteropen(f);
425                         break;
426                 case Qiproute:
427                         break;
428                 case Qtopdir:
429                 case Qprotodir:
430                 case Qconvdir:
431                 case Qstatus:
432                 case Qremote:
433                 case Qlocal:
434                 case Qstats:
435                 case Qipselftab:
436                         if (omode & O_WRITE)
437                                 error(EPERM, ERROR_FIXME);
438                         break;
439                 case Qsnoop:
440                         if (omode & O_WRITE)
441                                 error(EPERM, ERROR_FIXME);
442                         p = f->p[PROTO(c->qid)];
443                         cv = p->conv[CONV(c->qid)];
444                         if (strcmp(ATTACHER(c), cv->owner) != 0 && !iseve())
445                                 error(EPERM, ERROR_FIXME);
446                         atomic_inc(&cv->snoopers);
447                         break;
448                 case Qclone:
449                         p = f->p[PROTO(c->qid)];
450                         qlock(&p->qlock);
451                         if (waserror()) {
452                                 qunlock(&p->qlock);
453                                 nexterror();
454                         }
455                         cv = Fsprotoclone(p, ATTACHER(c));
456                         qunlock(&p->qlock);
457                         poperror();
458                         if (cv == NULL) {
459                                 error(ENODEV, ERROR_FIXME);
460                                 break;
461                         }
462                         /* we only honor nonblock on a clone */
463                         if (c->flag & O_NONBLOCK)
464                                 Fsconvnonblock(cv, TRUE);
465                         mkqid(&c->qid, QID(p->x, cv->x, Qctl), 0, QTFILE);
466                         break;
467                 case Qdata:
468                 case Qctl:
469                 case Qerr:
470                         p = f->p[PROTO(c->qid)];
471                         qlock(&p->qlock);
472                         cv = p->conv[CONV(c->qid)];
473                         qlock(&cv->qlock);
474                         if (waserror()) {
475                                 qunlock(&cv->qlock);
476                                 qunlock(&p->qlock);
477                                 nexterror();
478                         }
479                         if ((perm & (cv->perm >> 6)) != perm) {
480                                 if (strcmp(ATTACHER(c), cv->owner) != 0)
481                                         error(EPERM, ERROR_FIXME);
482                                 if ((perm & cv->perm) != perm)
483                                         error(EPERM, ERROR_FIXME);
484
485                         }
486                         cv->inuse++;
487                         if (cv->inuse == 1) {
488                                 kstrdup(&cv->owner, ATTACHER(c));
489                                 cv->perm = 0660;
490                         }
491                         qunlock(&cv->qlock);
492                         qunlock(&p->qlock);
493                         poperror();
494                         break;
495                 case Qlisten:
496                         cv = f->p[PROTO(c->qid)]->conv[CONV(c->qid)];
497                         /* No permissions or Announce checks required.  We'll see if that's
498                          * a good idea or not. (the perm check would do nothing, as is,
499                          * since an O_PATH perm is 0).
500                          *
501                          * But we probably want to incref to keep the conversation around
502                          * until this FD/chan is closed.  #ip is a little weird in that
503                          * objects never really go away (high water mark for convs, you can
504                          * always find them in the ns).  I think it is possible to
505                          * namec/ipgen a chan, then have that conv close, then have that
506                          * chan be opened.  You can probably do this with a data file. */
507                         if (omode & O_PATH) {
508                                 qlock(&cv->qlock);
509                                 cv->inuse++;
510                                 qunlock(&cv->qlock);
511                                 break;
512                         }
513                         if ((perm & (cv->perm >> 6)) != perm) {
514                                 if (strcmp(ATTACHER(c), cv->owner) != 0)
515                                         error(EPERM, ERROR_FIXME);
516                                 if ((perm & cv->perm) != perm)
517                                         error(EPERM, ERROR_FIXME);
518
519                         }
520
521                         if (cv->state != Announced)
522                                 error(EFAIL, "not announced");
523
524                         if (waserror()) {
525                                 closeconv(cv);
526                                 nexterror();
527                         }
528                         qlock(&cv->qlock);
529                         cv->inuse++;
530                         qunlock(&cv->qlock);
531
532                         nc = NULL;
533                         while (nc == NULL) {
534                                 /* give up if we got a hangup */
535                                 if (qisclosed(cv->rq))
536                                         error(EFAIL, "listen hungup");
537
538                                 qlock(&cv->listenq);
539                                 if (waserror()) {
540                                         qunlock(&cv->listenq);
541                                         nexterror();
542                                 }
543                                 /* we can peek at incall without grabbing the cv qlock.  if
544                                  * anything is there, it'll remain there until we dequeue it.
545                                  * no one else can, since we hold the listenq lock */
546                                 if (cv->nonblock && !cv->incall)
547                                         error(EAGAIN, "listen queue empty");
548                                 /* wait for a connect */
549                                 rendez_sleep(&cv->listenr, should_wake, cv);
550
551                                 /* if there is a concurrent hangup, they will hold the qlock
552                                  * until the hangup is complete, including closing the cv->rq */
553                                 qlock(&cv->qlock);
554                                 nc = cv->incall;
555                                 if (nc != NULL) {
556                                         cv->incall = nc->next;
557                                         mkqid(&c->qid, QID(PROTO(c->qid), nc->x, Qctl), 0, QTFILE);
558                                         kstrdup(&cv->owner, ATTACHER(c));
559                                         /* O_NONBLOCK/CNONBLOCK when opening listen means the *new*
560                                          * conv is already non-blocking, like accept4() in Linux */
561                                         if (c->flag & O_NONBLOCK)
562                                                 Fsconvnonblock(nc, TRUE);
563                                 }
564                                 qunlock(&cv->qlock);
565
566                                 qunlock(&cv->listenq);
567                                 poperror();
568                         }
569                         closeconv(cv);
570                         poperror();
571                         break;
572         }
573         c->mode = openmode(omode);
574         c->flag |= COPEN;
575         c->offset = 0;
576         return c;
577 }
578
579 static int ipwstat(struct chan *c, uint8_t * dp, int n)
580 {
581         ERRSTACK(2);
582         struct dir *d;
583         struct conv *cv;
584         struct Fs *f;
585         struct Proto *p;
586
587         f = ipfs[c->dev];
588         switch (TYPE(c->qid)) {
589                 default:
590                         error(EPERM, ERROR_FIXME);
591                         break;
592                 case Qctl:
593                 case Qdata:
594                         break;
595         }
596
597         d = kzmalloc(sizeof(*d) + n, 0);
598         if (waserror()) {
599                 kfree(d);
600                 nexterror();
601         }
602         n = convM2D(dp, n, d, (char *)&d[1]);
603         if (n == 0)
604                 error(ENODATA, ERROR_FIXME);
605         p = f->p[PROTO(c->qid)];
606         cv = p->conv[CONV(c->qid)];
607         if (!iseve() && strcmp(ATTACHER(c), cv->owner) != 0)
608                 error(EPERM, ERROR_FIXME);
609         if (!emptystr(d->uid))
610                 kstrdup(&cv->owner, d->uid);
611         if (d->mode != ~0UL)
612                 cv->perm = d->mode & 0777;
613         poperror();
614         kfree(d);
615         return n;
616 }
617
618 /* Should be able to handle any file type chan. Feel free to extend it. */
619 static char *ipchaninfo(struct chan *ch, char *ret, size_t ret_l)
620 {
621         struct conv *conv;
622         struct Proto *proto;
623         char *p;
624         struct Fs *f;
625
626         f = ipfs[ch->dev];
627
628         switch (TYPE(ch->qid)) {
629                 default:
630                         ret = "Unknown type";
631                         break;
632                 case Qdata:
633                         proto = f->p[PROTO(ch->qid)];
634                         conv = proto->conv[CONV(ch->qid)];
635                         snprintf(ret, ret_l, "Qdata, %s %s proto %s, conv idx %d",
636                                  conv->nonblock ? "nonblock" : "block",
637                                  SLIST_EMPTY(&conv->data_taps) ? "untapped" : "tapped",
638                                  proto->name, conv->x);
639                         break;
640                 case Qarp:
641                         ret = "Qarp";
642                         break;
643                 case Qiproute:
644                         ret = "Qiproute";
645                         break;
646                 case Qlisten:
647                         proto = f->p[PROTO(ch->qid)];
648                         conv = proto->conv[CONV(ch->qid)];
649                         snprintf(ret, ret_l, "Qlisten, %s %s proto %s, conv idx %d",
650                                  conv->nonblock ? "nonblock" : "block",
651                                  SLIST_EMPTY(&conv->data_taps) ? "untapped" : "tapped",
652                                  proto->name, conv->x);
653                         break;
654                 case Qlog:
655                         ret = "Qlog";
656                         break;
657                 case Qndb:
658                         ret = "Qndb";
659                         break;
660                 case Qctl:
661                         proto = f->p[PROTO(ch->qid)];
662                         conv = proto->conv[CONV(ch->qid)];
663                         snprintf(ret, ret_l, "Qctl, proto %s, conv idx %d", proto->name,
664                                          conv->x);
665                         break;
666         }
667         return ret;
668 }
669
670 static void closeconv(struct conv *cv)
671 {
672         struct conv *nc;
673         struct Ipmulti *mp;
674
675         qlock(&cv->qlock);
676
677         if (--cv->inuse > 0) {
678                 qunlock(&cv->qlock);
679                 return;
680         }
681
682         /* close all incoming calls since no listen will ever happen */
683         for (nc = cv->incall; nc; nc = cv->incall) {
684                 cv->incall = nc->next;
685                 closeconv(nc);
686         }
687         cv->incall = NULL;
688
689         kstrdup(&cv->owner, network);
690         cv->perm = 0660;
691
692         while ((mp = cv->multi) != NULL)
693                 ipifcremmulti(cv, mp->ma, mp->ia);
694
695         cv->r = NULL;
696         cv->rgen = 0;
697         cv->p->close(cv);
698         cv->state = Idle;
699         qunlock(&cv->qlock);
700 }
701
702 static void ipclose(struct chan *c)
703 {
704         struct Fs *f;
705
706         f = ipfs[c->dev];
707         switch (TYPE(c->qid)) {
708                 default:
709                         break;
710                 case Qlog:
711                         if (c->flag & COPEN)
712                                 netlogclose(f);
713                         break;
714                 case Qiprouter:
715                         if (c->flag & COPEN)
716                                 iprouterclose(f);
717                         break;
718                 case Qdata:
719                 case Qctl:
720                 case Qerr:
721                 case Qlisten:
722                         if (c->flag & COPEN)
723                                 closeconv(f->p[PROTO(c->qid)]->conv[CONV(c->qid)]);
724                         break;
725                 case Qsnoop:
726                         if (c->flag & COPEN)
727                                 atomic_dec(&f->p[PROTO(c->qid)]->conv[CONV(c->qid)]->snoopers);
728                         break;
729         }
730         kfree(((struct IPaux *)c->aux)->owner);
731         kfree(c->aux);
732 }
733
734 enum {
735         Statelen = 32 * 1024,
736 };
737
738 static long ipread(struct chan *ch, void *a, long n, int64_t off)
739 {
740         struct conv *c;
741         struct Proto *x;
742         char *buf, *p;
743         long rv;
744         struct Fs *f;
745         uint32_t offset = off;
746         size_t sofar;
747
748         f = ipfs[ch->dev];
749
750         p = a;
751         switch (TYPE(ch->qid)) {
752                 default:
753                         error(EPERM, ERROR_FIXME);
754                 case Qtopdir:
755                 case Qprotodir:
756                 case Qconvdir:
757                         return devdirread(ch, a, n, 0, 0, ipgen);
758                 case Qarp:
759                         return arpread(f->arp, a, offset, n);
760                 case Qndb:
761                         return readstr(offset, a, n, f->ndb);
762                 case Qiproute:
763                         return routeread(f, a, offset, n);
764                 case Qiprouter:
765                         return iprouterread(f, a, n);
766                 case Qipselftab:
767                         return ipselftabread(f, a, offset, n);
768                 case Qlog:
769                         return netlogread(f, a, offset, n);
770                 case Qctl:
771                         snprintf(get_cur_genbuf(), GENBUF_SZ, "%lu", CONV(ch->qid));
772                         return readstr(offset, p, n, get_cur_genbuf());
773                 case Qremote:
774                         buf = kzmalloc(Statelen, 0);
775                         x = f->p[PROTO(ch->qid)];
776                         c = x->conv[CONV(ch->qid)];
777                         if (x->remote == NULL) {
778                                 snprintf(buf, Statelen, "%I!%d\n", c->raddr, c->rport);
779                         } else {
780                                 (*x->remote) (c, buf, Statelen - 2);
781                         }
782                         rv = readstr(offset, p, n, buf);
783                         kfree(buf);
784                         return rv;
785                 case Qlocal:
786                         buf = kzmalloc(Statelen, 0);
787                         x = f->p[PROTO(ch->qid)];
788                         c = x->conv[CONV(ch->qid)];
789                         if (x->local == NULL) {
790                                 snprintf(buf, Statelen, "%I!%d\n", c->laddr, c->lport);
791                         } else {
792                                 (*x->local) (c, buf, Statelen - 2);
793                         }
794                         rv = readstr(offset, p, n, buf);
795                         kfree(buf);
796                         return rv;
797                 case Qstatus:
798                         /* this all is a bit screwed up since the size of some state's
799                          * buffers will change from one invocation to another.  a reader
800                          * will come in and read the entire buffer.  then it will come again
801                          * and read from the next offset, expecting EOF.  if the buffer
802                          * changed sizes, it'll reprint the end of the buffer slightly. */
803                         buf = kzmalloc(Statelen, 0);
804                         x = f->p[PROTO(ch->qid)];
805                         c = x->conv[CONV(ch->qid)];
806                         sofar = (*x->state) (c, buf, Statelen - 2);
807                         sofar += snprintf(buf + sofar, Statelen - 2 - sofar, "nonblock %s\n",
808                                           c->nonblock ? "on" : "off");
809                         rv = readstr(offset, p, n, buf);
810                         kfree(buf);
811                         return rv;
812                 case Qdata:
813                         c = f->p[PROTO(ch->qid)]->conv[CONV(ch->qid)];
814                         return qread(c->rq, a, n);
815                 case Qerr:
816                         c = f->p[PROTO(ch->qid)]->conv[CONV(ch->qid)];
817                         return qread(c->eq, a, n);
818                 case Qsnoop:
819                         c = f->p[PROTO(ch->qid)]->conv[CONV(ch->qid)];
820                         return qread(c->sq, a, n);
821                 case Qstats:
822                         x = f->p[PROTO(ch->qid)];
823                         if (x->stats == NULL)
824                                 error(EFAIL, "stats not implemented");
825                         buf = kzmalloc(Statelen, 0);
826                         (*x->stats) (x, buf, Statelen);
827                         rv = readstr(offset, p, n, buf);
828                         kfree(buf);
829                         return rv;
830         }
831 }
832
833 static struct block *ipbread(struct chan *ch, long n, uint32_t offset)
834 {
835         struct conv *c;
836
837         switch (TYPE(ch->qid)) {
838                 case Qdata:
839                         c = chan2conv(ch);
840                         return qbread(c->rq, n);
841                 default:
842                         return devbread(ch, n, offset);
843         }
844 }
845
846 /*
847  *  set local address to be that of the ifc closest to remote address
848  */
849 static void setladdr(struct conv *c)
850 {
851         findlocalip(c->p->f, c->laddr, c->raddr);
852 }
853
854 /*
855  *  set a local port making sure the quad of raddr,rport,laddr,lport is unique
856  */
857 static void setluniqueport(struct conv *c, int lport)
858 {
859         struct Proto *p;
860         struct conv *xp;
861         int x;
862
863         p = c->p;
864
865         qlock(&p->qlock);
866         for (x = 0; x < p->nc; x++) {
867                 xp = p->conv[x];
868                 if (xp == NULL)
869                         break;
870                 if (xp == c)
871                         continue;
872                 if ((xp->state == Connected || xp->state == Announced)
873                         && xp->lport == lport
874                         && xp->rport == c->rport
875                         && ipcmp(xp->raddr, c->raddr) == 0
876                         && ipcmp(xp->laddr, c->laddr) == 0) {
877                         qunlock(&p->qlock);
878                         error(EFAIL, "address in use");
879                 }
880         }
881         c->lport = lport;
882         qunlock(&p->qlock);
883 }
884
885 /*
886  *  pick a local port and set it
887  */
888 static void setlport(struct conv *c)
889 {
890         struct Proto *p;
891         uint16_t *pp;
892         int x, found;
893
894         p = c->p;
895         if (c->restricted)
896                 pp = &p->nextrport;
897         else
898                 pp = &p->nextport;
899         qlock(&p->qlock);
900         for (;; (*pp)++) {
901                 /*
902                  * Fsproto initialises p->nextport to 0 and the restricted
903                  * ports (p->nextrport) to 600.
904                  * Restricted ports must lie between 600 and 1024.
905                  * For the initial condition or if the unrestricted port number
906                  * has wrapped round, select a random port between 5000 and 1<<15
907                  * to start at.
908                  */
909                 if (c->restricted) {
910                         if (*pp >= 1024)
911                                 *pp = 600;
912                 } else
913                         while (*pp < 5000)
914                                 urandom_read(pp, sizeof(*pp));
915
916                 found = 0;
917                 for (x = 0; x < p->nc; x++) {
918                         if (p->conv[x] == NULL)
919                                 break;
920                         if (p->conv[x]->lport == *pp) {
921                                 found = 1;
922                                 break;
923                         }
924                 }
925                 if (!found)
926                         break;
927         }
928         c->lport = (*pp)++;
929         qunlock(&p->qlock);
930 }
931
932 /*
933  *  set a local address and port from a string of the form
934  *      [address!]port[!r]
935  */
936 static void setladdrport(struct conv *c, char *str, int announcing)
937 {
938         char *p;
939         uint16_t lport;
940         uint8_t addr[IPaddrlen];
941
942         /*
943          *  ignore restricted part if it exists.  it's
944          *  meaningless on local ports.
945          */
946         p = strchr(str, '!');
947         if (p != NULL) {
948                 *p++ = 0;
949                 if (strcmp(p, "r") == 0)
950                         p = NULL;
951         }
952
953         c->lport = 0;
954         if (p == NULL) {
955                 if (announcing)
956                         ipmove(c->laddr, IPnoaddr);
957                 else
958                         setladdr(c);
959                 p = str;
960         } else {
961                 if (strcmp(str, "*") == 0)
962                         ipmove(c->laddr, IPnoaddr);
963                 else {
964                         parseip(addr, str);
965                         if (ipforme(c->p->f, addr))
966                                 ipmove(c->laddr, addr);
967                         else
968                                 error(EFAIL, "not a local IP address");
969                 }
970         }
971
972         /* one process can get all connections */
973         if (announcing && strcmp(p, "*") == 0) {
974                 if (!iseve())
975                         error(EPERM, ERROR_FIXME);
976                 setluniqueport(c, 0);
977         }
978
979         lport = atoi(p);
980         if (lport <= 0)
981                 setlport(c);
982         else
983                 setluniqueport(c, lport);
984 }
985
986 static void setraddrport(struct conv *c, char *str)
987 {
988         char *p;
989
990         p = strchr(str, '!');
991         if (p == NULL)
992                 error(EFAIL, "malformed address");
993         *p++ = 0;
994         parseip(c->raddr, str);
995         c->rport = atoi(p);
996         p = strchr(p, '!');
997         if (p) {
998                 if (strstr(p, "!r") != NULL)
999                         c->restricted = 1;
1000         }
1001 }
1002
1003 /*
1004  *  called by protocol connect routine to set addresses
1005  */
1006 void Fsstdconnect(struct conv *c, char *argv[], int argc)
1007 {
1008         switch (argc) {
1009                 default:
1010                         error(EINVAL, "bad args to %s", __func__);
1011                 case 2:
1012                         setraddrport(c, argv[1]);
1013                         setladdr(c);
1014                         setlport(c);
1015                         break;
1016                 case 3:
1017                         setraddrport(c, argv[1]);
1018                         setladdrport(c, argv[2], 0);
1019                         break;
1020         }
1021
1022         if ((memcmp(c->raddr, v4prefix, IPv4off) == 0 &&
1023                  memcmp(c->laddr, v4prefix, IPv4off) == 0)
1024                 || ipcmp(c->raddr, IPnoaddr) == 0)
1025                 c->ipversion = V4;
1026         else
1027                 c->ipversion = V6;
1028 }
1029
1030 /*
1031  *  initiate connection and sleep till its set up
1032  */
1033 static int connected(void *a)
1034 {
1035         return ((struct conv *)a)->state == Connected;
1036 }
1037
1038 static void connectctlmsg(struct Proto *x, struct conv *c, struct cmdbuf *cb)
1039 {
1040         ERRSTACK(1);
1041         char *p;
1042
1043         if (c->state != 0)
1044                 error(EBUSY, ERROR_FIXME);
1045         c->state = Connecting;
1046         c->cerr[0] = '\0';
1047         if (x->connect == NULL)
1048                 error(EFAIL, "connect not supported");
1049         x->connect(c, cb->f, cb->nf);
1050
1051         qunlock(&c->qlock);
1052         if (waserror()) {
1053                 qlock(&c->qlock);
1054                 nexterror();
1055         }
1056         rendez_sleep(&c->cr, connected, c);
1057         qlock(&c->qlock);
1058         poperror();
1059
1060         if (c->cerr[0] != '\0')
1061                 error(EFAIL, c->cerr);
1062 }
1063
1064 /*
1065  *  called by protocol announce routine to set addresses
1066  */
1067 void Fsstdannounce(struct conv *c, char *argv[], int argc)
1068 {
1069         memset(c->raddr, 0, sizeof(c->raddr));
1070         c->rport = 0;
1071         switch (argc) {
1072                 default:
1073                         error(EINVAL, "bad args to announce");
1074                 case 2:
1075                         setladdrport(c, argv[1], 1);
1076                         break;
1077         }
1078 }
1079
1080 /*
1081  *  initiate announcement and sleep till its set up
1082  */
1083 static int announced(void *a)
1084 {
1085         return ((struct conv *)a)->state == Announced;
1086 }
1087
1088 static void announcectlmsg(struct Proto *x, struct conv *c, struct cmdbuf *cb)
1089 {
1090         ERRSTACK(1);
1091         char *p;
1092
1093         if (c->state != 0)
1094                 error(EBUSY, ERROR_FIXME);
1095         c->state = Announcing;
1096         c->cerr[0] = '\0';
1097         if (x->announce == NULL)
1098                 error(EFAIL, "announce not supported");
1099         x->announce(c, cb->f, cb->nf);
1100
1101         qunlock(&c->qlock);
1102         if (waserror()) {
1103                 qlock(&c->qlock);
1104                 nexterror();
1105         }
1106         rendez_sleep(&c->cr, announced, c);
1107         qlock(&c->qlock);
1108         poperror();
1109
1110         if (c->cerr[0] != '\0')
1111                 error(EFAIL, c->cerr);
1112 }
1113
1114 /*
1115  *  called by protocol bind routine to set addresses
1116  */
1117 void Fsstdbind(struct conv *c, char *argv[], int argc)
1118 {
1119         switch (argc) {
1120                 default:
1121                         error(EINVAL, "bad args to bind");
1122                 case 2:
1123                         setladdrport(c, argv[1], 0);
1124                         break;
1125         }
1126 }
1127
1128 void Fsconvnonblock(struct conv *cv, bool onoff)
1129 {
1130         qnonblock(cv->wq, onoff);
1131         qnonblock(cv->rq, onoff);
1132         cv->nonblock = onoff;
1133 }
1134
1135 static void bindctlmsg(struct Proto *x, struct conv *c, struct cmdbuf *cb)
1136 {
1137         if (x->bind == NULL)
1138                 Fsstdbind(c, cb->f, cb->nf);
1139         else
1140                 x->bind(c, cb->f, cb->nf);
1141 }
1142
1143 static void nonblockctlmsg(struct conv *c, struct cmdbuf *cb)
1144 {
1145         if (cb->nf < 2)
1146                 goto err;
1147         if (!strcmp(cb->f[1], "on"))
1148                 Fsconvnonblock(c, TRUE);
1149         else if (!strcmp(cb->f[1], "off"))
1150                 Fsconvnonblock(c, FALSE);
1151         else
1152                 goto err;
1153         return;
1154 err:
1155         error(EINVAL, "nonblock [on|off]");
1156 }
1157
1158 static void shutdownctlmsg(struct conv *cv, struct cmdbuf *cb)
1159 {
1160         if (cb->nf < 2)
1161                 goto err;
1162         if (!strcmp(cb->f[1], "rd")) {
1163                 qhangup(cv->rq, "shutdown");
1164                 if (cv->p->shutdown)
1165                         cv->p->shutdown(cv, SHUT_RD);
1166         } else if (!strcmp(cb->f[1], "wr")) {
1167                 qhangup(cv->wq, "shutdown");
1168                 if (cv->p->shutdown)
1169                         cv->p->shutdown(cv, SHUT_WR);
1170         } else if (!strcmp(cb->f[1], "rdwr")) {
1171                 qhangup(cv->rq, "shutdown");
1172                 qhangup(cv->wq, "shutdown");
1173                 if (cv->p->shutdown)
1174                         cv->p->shutdown(cv, SHUT_RDWR);
1175         } else {
1176                 goto err;
1177         }
1178         return;
1179 err:
1180         error(EINVAL, "shutdown [rx|tx|rxtx]");
1181 }
1182
1183 static void tosctlmsg(struct conv *c, struct cmdbuf *cb)
1184 {
1185         if (cb->nf < 2)
1186                 c->tos = 0;
1187         else
1188                 c->tos = atoi(cb->f[1]);
1189 }
1190
1191 static void ttlctlmsg(struct conv *c, struct cmdbuf *cb)
1192 {
1193         if (cb->nf < 2)
1194                 c->ttl = MAXTTL;
1195         else
1196                 c->ttl = atoi(cb->f[1]);
1197 }
1198
1199 static long ipwrite(struct chan *ch, void *v, long n, int64_t off)
1200 {
1201         ERRSTACK(1);
1202         struct conv *c;
1203         struct Proto *x;
1204         char *p;
1205         struct cmdbuf *cb;
1206         uint8_t ia[IPaddrlen], ma[IPaddrlen];
1207         struct Fs *f;
1208         char *a;
1209
1210         a = v;
1211         f = ipfs[ch->dev];
1212
1213         switch (TYPE(ch->qid)) {
1214                 default:
1215                         error(EPERM, ERROR_FIXME);
1216                 case Qdata:
1217                         x = f->p[PROTO(ch->qid)];
1218                         c = x->conv[CONV(ch->qid)];
1219                         qwrite(c->wq, a, n);
1220                         break;
1221                 case Qarp:
1222                         return arpwrite(f, a, n);
1223                 case Qiproute:
1224                         return routewrite(f, ch, a, n);
1225                 case Qlog:
1226                         netlogctl(f, a, n);
1227                         return n;
1228                 case Qndb:
1229                         return ndbwrite(f, a, off, n);
1230                 case Qctl:
1231                         x = f->p[PROTO(ch->qid)];
1232                         c = x->conv[CONV(ch->qid)];
1233                         cb = parsecmd(a, n);
1234
1235                         qlock(&c->qlock);
1236                         if (waserror()) {
1237                                 qunlock(&c->qlock);
1238                                 kfree(cb);
1239                                 nexterror();
1240                         }
1241                         if (cb->nf < 1)
1242                                 error(EFAIL, "short control request");
1243                         if (strcmp(cb->f[0], "connect") == 0)
1244                                 connectctlmsg(x, c, cb);
1245                         else if (strcmp(cb->f[0], "announce") == 0)
1246                                 announcectlmsg(x, c, cb);
1247                         else if (strcmp(cb->f[0], "bind") == 0)
1248                                 bindctlmsg(x, c, cb);
1249                         else if (strcmp(cb->f[0], "nonblock") == 0)
1250                                 nonblockctlmsg(c, cb);
1251                         else if (strcmp(cb->f[0], "shutdown") == 0)
1252                                 shutdownctlmsg(c, cb);
1253                         else if (strcmp(cb->f[0], "ttl") == 0)
1254                                 ttlctlmsg(c, cb);
1255                         else if (strcmp(cb->f[0], "tos") == 0)
1256                                 tosctlmsg(c, cb);
1257                         else if (strcmp(cb->f[0], "ignoreadvice") == 0)
1258                                 c->ignoreadvice = 1;
1259                         else if (strcmp(cb->f[0], "addmulti") == 0) {
1260                                 if (cb->nf < 2)
1261                                         error(EFAIL, "addmulti needs interface address");
1262                                 if (cb->nf == 2) {
1263                                         if (!ipismulticast(c->raddr))
1264                                                 error(EFAIL, "addmulti for a non multicast address");
1265                                         parseip(ia, cb->f[1]);
1266                                         ipifcaddmulti(c, c->raddr, ia);
1267                                 } else {
1268                                         parseip(ma, cb->f[2]);
1269                                         if (!ipismulticast(ma))
1270                                                 error(EFAIL, "addmulti for a non multicast address");
1271                                         parseip(ia, cb->f[1]);
1272                                         ipifcaddmulti(c, ma, ia);
1273                                 }
1274                         } else if (strcmp(cb->f[0], "remmulti") == 0) {
1275                                 if (cb->nf < 2)
1276                                         error(EFAIL, "remmulti needs interface address");
1277                                 if (!ipismulticast(c->raddr))
1278                                         error(EFAIL, "remmulti for a non multicast address");
1279                                 parseip(ia, cb->f[1]);
1280                                 ipifcremmulti(c, c->raddr, ia);
1281                         } else if (x->ctl != NULL) {
1282                                 x->ctl(c, cb->f, cb->nf);
1283                         } else
1284                                 error(EFAIL, "unknown control request");
1285                         qunlock(&c->qlock);
1286                         kfree(cb);
1287                         poperror();
1288         }
1289         return n;
1290 }
1291
1292 static long ipbwrite(struct chan *ch, struct block *bp, uint32_t offset)
1293 {
1294         struct conv *c;
1295         int n;
1296
1297         switch (TYPE(ch->qid)) {
1298                 case Qdata:
1299                         c = chan2conv(ch);
1300                         if (bp->next)
1301                                 bp = concatblock(bp);
1302                         n = BLEN(bp);
1303                         qbwrite(c->wq, bp);
1304                         return n;
1305                 default:
1306                         return devbwrite(ch, bp, offset);
1307         }
1308 }
1309
1310 static void ip_wake_cb(struct queue *q, void *data, int filter)
1311 {
1312         struct conv *conv = (struct conv*)data;
1313         struct fd_tap *tap_i;
1314         /* For these two, we want to ignore events on the opposite end of the
1315          * queues.  For instance, we want to know when the WQ is writable.  Our
1316          * writes will actually make it readable - we don't want to trigger a tap
1317          * for that.  However, qio doesn't know how/why we are using a queue, or
1318          * even who the ends are (hence the callbacks) */
1319         if ((filter & FDTAP_FILT_READABLE) && (q == conv->wq))
1320                 return;
1321         if ((filter & FDTAP_FILT_WRITABLE) && (q == conv->rq))
1322                 return;
1323         /* At this point, we have an event we want to send to our taps (if any).
1324          * The lock protects list integrity and the existence of the tap.
1325          *
1326          * Previously, I thought of using the conv qlock.  That actually breaks, due
1327          * to weird usages of the qlock (someone holds it for a long time, blocking
1328          * the inbound wakeup from etherread4).
1329          *
1330          * I opted for a spinlock for a couple reasons:
1331          * - fire_tap should not block.  ideally it'll be fast too (it's mostly a
1332          * send_event).
1333          * - our callers might not want to block.  A lot of network wakeups will
1334          * come network processes (etherread4) or otherwise unrelated to this
1335          * particular conversation.  I'd rather do something like fire off a KMSG
1336          * than block those.
1337          * - if fire_tap takes a while, holding the lock only slows down other
1338          * events on this *same* conversation, or other tap registration.  not a
1339          * huge deal. */
1340         spin_lock(&conv->tap_lock);
1341         SLIST_FOREACH(tap_i, &conv->data_taps, link)
1342                 fire_tap(tap_i, filter);
1343         spin_unlock(&conv->tap_lock);
1344 }
1345
1346 int iptapfd(struct chan *chan, struct fd_tap *tap, int cmd)
1347 {
1348         struct conv *conv = chan2conv(chan);
1349         int ret;
1350
1351         #define DEVIP_LEGAL_DATA_TAPS (FDTAP_FILT_READABLE | FDTAP_FILT_WRITABLE | \
1352                                        FDTAP_FILT_HANGUP | FDTAP_FILT_PRIORITY |   \
1353                                        FDTAP_FILT_ERROR)
1354         #define DEVIP_LEGAL_LISTEN_TAPS (FDTAP_FILT_READABLE | FDTAP_FILT_HANGUP)
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 }