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