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