4e0149bc842b75a7373dc33064ecedc1a7af7450
[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("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);
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);
413                         break;
414                 case Qsnoop:
415                         if (omode & O_WRITE)
416                                 error(Eperm);
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);
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);
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);
457                                 if ((perm & cv->perm) != perm)
458                                         error(Eperm);
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);
491                                 if ((perm & cv->perm) != perm)
492                                         error(Eperm);
493
494                         }
495
496                         if (cv->state != Announced)
497                                 error("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("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                                         set_errno(EAGAIN);
523                                         error("listen queue empty");
524                                 }
525                                 /* wait for a connect */
526                                 rendez_sleep(&cv->listenr, should_wake, cv);
527
528                                 /* if there is a concurrent hangup, they will hold the qlock
529                                  * until the hangup is complete, including closing the cv->rq */
530                                 qlock(&cv->qlock);
531                                 nc = cv->incall;
532                                 if (nc != NULL) {
533                                         cv->incall = nc->next;
534                                         mkqid(&c->qid, QID(PROTO(c->qid), nc->x, Qctl), 0, QTFILE);
535                                         kstrdup(&cv->owner, ATTACHER(c));
536                                         /* O_NONBLOCK/CNONBLOCK when opening listen means the *new*
537                                          * conv is already non-blocking, like accept4() in Linux */
538                                         if (c->flag & O_NONBLOCK)
539                                                 Fsconvnonblock(nc, TRUE);
540                                 }
541                                 qunlock(&cv->qlock);
542
543                                 qunlock(&cv->listenq);
544                                 poperror();
545                         }
546                         closeconv(cv);
547                         poperror();
548                         break;
549         }
550         c->mode = openmode(omode);
551         c->flag |= COPEN;
552         c->offset = 0;
553         return c;
554 }
555
556 static int ipwstat(struct chan *c, uint8_t * dp, int n)
557 {
558         ERRSTACK(2);
559         struct dir *d;
560         struct conv *cv;
561         struct Fs *f;
562         struct Proto *p;
563
564         f = ipfs[c->dev];
565         switch (TYPE(c->qid)) {
566                 default:
567                         error(Eperm);
568                         break;
569                 case Qctl:
570                 case Qdata:
571                         break;
572         }
573
574         d = kzmalloc(sizeof(*d) + n, 0);
575         if (waserror()) {
576                 kfree(d);
577                 nexterror();
578         }
579         n = convM2D(dp, n, d, (char *)&d[1]);
580         if (n == 0)
581                 error(Eshortstat);
582         p = f->p[PROTO(c->qid)];
583         cv = p->conv[CONV(c->qid)];
584         if (!iseve() && strcmp(ATTACHER(c), cv->owner) != 0)
585                 error(Eperm);
586         if (!emptystr(d->uid))
587                 kstrdup(&cv->owner, d->uid);
588         if (d->mode != ~0UL)
589                 cv->perm = d->mode & 0777;
590         poperror();
591         kfree(d);
592         return n;
593 }
594
595 /* Should be able to handle any file type chan. Feel free to extend it. */
596 static char *ipchaninfo(struct chan *ch, char *ret, size_t ret_l)
597 {
598         struct conv *conv;
599         struct Proto *proto;
600         char *p;
601         struct Fs *f;
602
603         f = ipfs[ch->dev];
604
605         switch (TYPE(ch->qid)) {
606                 default:
607                         ret = "Unknown type";
608                         break;
609                 case Qdata:
610                         proto = f->p[PROTO(ch->qid)];
611                         conv = proto->conv[CONV(ch->qid)];
612                         snprintf(ret, ret_l, "Qdata, proto %s, conv idx %d", proto->name,
613                                          conv->x);
614                         break;
615                 case Qarp:
616                         ret = "Qarp";
617                         break;
618                 case Qiproute:
619                         ret = "Qiproute";
620                         break;
621                 case Qlisten:
622                         proto = f->p[PROTO(ch->qid)];
623                         conv = proto->conv[CONV(ch->qid)];
624                         snprintf(ret, ret_l, "Qlisten, proto %s, conv idx %d", proto->name,
625                                          conv->x);
626                         break;
627                 case Qlog:
628                         ret = "Qlog";
629                         break;
630                 case Qndb:
631                         ret = "Qndb";
632                         break;
633                 case Qctl:
634                         proto = f->p[PROTO(ch->qid)];
635                         conv = proto->conv[CONV(ch->qid)];
636                         snprintf(ret, ret_l, "Qctl, proto %s, conv idx %d", proto->name,
637                                          conv->x);
638                         break;
639         }
640         return ret;
641 }
642
643 static void closeconv(struct conv *cv)
644 {
645         struct conv *nc;
646         struct Ipmulti *mp;
647
648         qlock(&cv->qlock);
649
650         if (--cv->inuse > 0) {
651                 qunlock(&cv->qlock);
652                 return;
653         }
654
655         /* close all incoming calls since no listen will ever happen */
656         for (nc = cv->incall; nc; nc = cv->incall) {
657                 cv->incall = nc->next;
658                 closeconv(nc);
659         }
660         cv->incall = NULL;
661
662         kstrdup(&cv->owner, network);
663         cv->perm = 0660;
664
665         while ((mp = cv->multi) != NULL)
666                 ipifcremmulti(cv, mp->ma, mp->ia);
667
668         cv->r = NULL;
669         cv->rgen = 0;
670         cv->p->close(cv);
671         cv->state = Idle;
672         qunlock(&cv->qlock);
673 }
674
675 static void ipclose(struct chan *c)
676 {
677         struct Fs *f;
678
679         f = ipfs[c->dev];
680         switch (TYPE(c->qid)) {
681                 default:
682                         break;
683                 case Qlog:
684                         if (c->flag & COPEN)
685                                 netlogclose(f);
686                         break;
687                 case Qiprouter:
688                         if (c->flag & COPEN)
689                                 iprouterclose(f);
690                         break;
691                 case Qdata:
692                 case Qctl:
693                 case Qerr:
694                         if (c->flag & COPEN)
695                                 closeconv(f->p[PROTO(c->qid)]->conv[CONV(c->qid)]);
696                         break;
697                 case Qsnoop:
698                         if (c->flag & COPEN)
699                                 atomic_dec(&f->p[PROTO(c->qid)]->conv[CONV(c->qid)]->snoopers);
700                         break;
701         }
702         kfree(((struct IPaux *)c->aux)->owner);
703         kfree(c->aux);
704 }
705
706 enum {
707         Statelen = 32 * 1024,
708 };
709
710 static long ipread(struct chan *ch, void *a, long n, int64_t off)
711 {
712         struct conv *c;
713         struct Proto *x;
714         char *buf, *p;
715         long rv;
716         struct Fs *f;
717         uint32_t offset = off;
718         size_t sofar;
719
720         f = ipfs[ch->dev];
721
722         p = a;
723         switch (TYPE(ch->qid)) {
724                 default:
725                         error(Eperm);
726                 case Qtopdir:
727                 case Qprotodir:
728                 case Qconvdir:
729                         return devdirread(ch, a, n, 0, 0, ipgen);
730                 case Qarp:
731                         return arpread(f->arp, a, offset, n);
732                 case Qbootp:
733                         return bootpread(a, offset, n);
734                 case Qndb:
735                         return readstr(offset, a, n, f->ndb);
736                 case Qiproute:
737                         return routeread(f, a, offset, n);
738                 case Qiprouter:
739                         return iprouterread(f, a, n);
740                 case Qipselftab:
741                         return ipselftabread(f, a, offset, n);
742                 case Qlog:
743                         return netlogread(f, a, offset, n);
744                 case Qctl:
745                         snprintf(get_cur_genbuf(), GENBUF_SZ, "%lu", CONV(ch->qid));
746                         return readstr(offset, p, n, get_cur_genbuf());
747                 case Qremote:
748                         buf = kzmalloc(Statelen, 0);
749                         x = f->p[PROTO(ch->qid)];
750                         c = x->conv[CONV(ch->qid)];
751                         if (x->remote == NULL) {
752                                 snprintf(buf, Statelen, "%I!%d\n", c->raddr, c->rport);
753                         } else {
754                                 (*x->remote) (c, buf, Statelen - 2);
755                         }
756                         rv = readstr(offset, p, n, buf);
757                         kfree(buf);
758                         return rv;
759                 case Qlocal:
760                         buf = kzmalloc(Statelen, 0);
761                         x = f->p[PROTO(ch->qid)];
762                         c = x->conv[CONV(ch->qid)];
763                         if (x->local == NULL) {
764                                 snprintf(buf, Statelen, "%I!%d\n", c->laddr, c->lport);
765                         } else {
766                                 (*x->local) (c, buf, Statelen - 2);
767                         }
768                         rv = readstr(offset, p, n, buf);
769                         kfree(buf);
770                         return rv;
771                 case Qstatus:
772                         /* this all is a bit screwed up since the size of some state's
773                          * buffers will change from one invocation to another.  a reader
774                          * will come in and read the entire buffer.  then it will come again
775                          * and read from the next offset, expecting EOF.  if the buffer
776                          * changed sizes, it'll reprint the end of the buffer slightly. */
777                         buf = kzmalloc(Statelen, 0);
778                         x = f->p[PROTO(ch->qid)];
779                         c = x->conv[CONV(ch->qid)];
780                         sofar = (*x->state) (c, buf, Statelen - 2);
781                         sofar += snprintf(buf + sofar, Statelen - 2 - sofar, "nonblock %s\n",
782                                           c->nonblock ? "on" : "off");
783                         rv = readstr(offset, p, n, buf);
784                         kfree(buf);
785                         return rv;
786                 case Qdata:
787                         c = f->p[PROTO(ch->qid)]->conv[CONV(ch->qid)];
788                         return qread(c->rq, a, n);
789                 case Qerr:
790                         c = f->p[PROTO(ch->qid)]->conv[CONV(ch->qid)];
791                         return qread(c->eq, a, n);
792                 case Qsnoop:
793                         c = f->p[PROTO(ch->qid)]->conv[CONV(ch->qid)];
794                         return qread(c->sq, a, n);
795                 case Qstats:
796                         x = f->p[PROTO(ch->qid)];
797                         if (x->stats == NULL)
798                                 error("stats not implemented");
799                         buf = kzmalloc(Statelen, 0);
800                         (*x->stats) (x, buf, Statelen);
801                         rv = readstr(offset, p, n, buf);
802                         kfree(buf);
803                         return rv;
804         }
805 }
806
807 static struct block *ipbread(struct chan *ch, long n, uint32_t offset)
808 {
809         struct conv *c;
810         struct Proto *x;
811         struct Fs *f;
812
813         switch (TYPE(ch->qid)) {
814                 case Qdata:
815                         f = ipfs[ch->dev];
816                         x = f->p[PROTO(ch->qid)];
817                         c = x->conv[CONV(ch->qid)];
818                         return qbread(c->rq, n);
819                 default:
820                         return devbread(ch, n, offset);
821         }
822 }
823
824 /*
825  *  set local address to be that of the ifc closest to remote address
826  */
827 static void setladdr(struct conv *c)
828 {
829         findlocalip(c->p->f, c->laddr, c->raddr);
830 }
831
832 /*
833  *  set a local port making sure the quad of raddr,rport,laddr,lport is unique
834  */
835 static char *setluniqueport(struct conv *c, int lport)
836 {
837         struct Proto *p;
838         struct conv *xp;
839         int x;
840
841         p = c->p;
842
843         qlock(&p->qlock);
844         for (x = 0; x < p->nc; x++) {
845                 xp = p->conv[x];
846                 if (xp == NULL)
847                         break;
848                 if (xp == c)
849                         continue;
850                 if ((xp->state == Connected || xp->state == Announced)
851                         && xp->lport == lport
852                         && xp->rport == c->rport
853                         && ipcmp(xp->raddr, c->raddr) == 0
854                         && ipcmp(xp->laddr, c->laddr) == 0) {
855                         qunlock(&p->qlock);
856                         return "address in use";
857                 }
858         }
859         c->lport = lport;
860         qunlock(&p->qlock);
861         return NULL;
862 }
863
864 /*
865  *  pick a local port and set it
866  */
867 static void setlport(struct conv *c)
868 {
869         struct Proto *p;
870         uint16_t *pp;
871         int x, found;
872
873         p = c->p;
874         if (c->restricted)
875                 pp = &p->nextrport;
876         else
877                 pp = &p->nextport;
878         qlock(&p->qlock);
879         for (;; (*pp)++) {
880                 /*
881                  * Fsproto initialises p->nextport to 0 and the restricted
882                  * ports (p->nextrport) to 600.
883                  * Restricted ports must lie between 600 and 1024.
884                  * For the initial condition or if the unrestricted port number
885                  * has wrapped round, select a random port between 5000 and 1<<15
886                  * to start at.
887                  */
888                 if (c->restricted) {
889                         if (*pp >= 1024)
890                                 *pp = 600;
891                 } else
892                         while (*pp < 5000)
893                                 *pp = nrand(1 << 15);
894
895                 found = 0;
896                 for (x = 0; x < p->nc; x++) {
897                         if (p->conv[x] == NULL)
898                                 break;
899                         if (p->conv[x]->lport == *pp) {
900                                 found = 1;
901                                 break;
902                         }
903                 }
904                 if (!found)
905                         break;
906         }
907         c->lport = (*pp)++;
908         qunlock(&p->qlock);
909 }
910
911 /*
912  *  set a local address and port from a string of the form
913  *      [address!]port[!r]
914  */
915 static char *setladdrport(struct conv *c, char *str, int announcing)
916 {
917         char *p;
918         char *rv;
919         uint16_t lport;
920         uint8_t addr[IPaddrlen];
921
922         rv = NULL;
923
924         /*
925          *  ignore restricted part if it exists.  it's
926          *  meaningless on local ports.
927          */
928         p = strchr(str, '!');
929         if (p != NULL) {
930                 *p++ = 0;
931                 if (strcmp(p, "r") == 0)
932                         p = NULL;
933         }
934
935         c->lport = 0;
936         if (p == NULL) {
937                 if (announcing)
938                         ipmove(c->laddr, IPnoaddr);
939                 else
940                         setladdr(c);
941                 p = str;
942         } else {
943                 if (strcmp(str, "*") == 0)
944                         ipmove(c->laddr, IPnoaddr);
945                 else {
946                         parseip(addr, str);
947                         if (ipforme(c->p->f, addr))
948                                 ipmove(c->laddr, addr);
949                         else
950                                 return "not a local IP address";
951                 }
952         }
953
954         /* one process can get all connections */
955         if (announcing && strcmp(p, "*") == 0) {
956                 if (!iseve())
957                         error(Eperm);
958                 return setluniqueport(c, 0);
959         }
960
961         lport = atoi(p);
962         if (lport <= 0)
963                 setlport(c);
964         else
965                 rv = setluniqueport(c, lport);
966         return rv;
967 }
968
969 static char *setraddrport(struct conv *c, char *str)
970 {
971         char *p;
972
973         p = strchr(str, '!');
974         if (p == NULL)
975                 return "malformed address";
976         *p++ = 0;
977         parseip(c->raddr, str);
978         c->rport = atoi(p);
979         p = strchr(p, '!');
980         if (p) {
981                 if (strstr(p, "!r") != NULL)
982                         c->restricted = 1;
983         }
984         return NULL;
985 }
986
987 /*
988  *  called by protocol connect routine to set addresses
989  */
990 char *Fsstdconnect(struct conv *c, char *argv[], int argc)
991 {
992         char *p;
993
994         switch (argc) {
995                 default:
996                         return "bad args to connect";
997                 case 2:
998                         p = setraddrport(c, argv[1]);
999                         if (p != NULL)
1000                                 return p;
1001                         setladdr(c);
1002                         setlport(c);
1003                         break;
1004                 case 3:
1005                         p = setraddrport(c, argv[1]);
1006                         if (p != NULL)
1007                                 return p;
1008                         p = setladdrport(c, argv[2], 0);
1009                         if (p != NULL)
1010                                 return p;
1011         }
1012
1013         if ((memcmp(c->raddr, v4prefix, IPv4off) == 0 &&
1014                  memcmp(c->laddr, v4prefix, IPv4off) == 0)
1015                 || ipcmp(c->raddr, IPnoaddr) == 0)
1016                 c->ipversion = V4;
1017         else
1018                 c->ipversion = V6;
1019
1020         return NULL;
1021 }
1022
1023 /*
1024  *  initiate connection and sleep till its set up
1025  */
1026 static int connected(void *a)
1027 {
1028         return ((struct conv *)a)->state == Connected;
1029 }
1030
1031 static void connectctlmsg(struct Proto *x, struct conv *c, struct cmdbuf *cb)
1032 {
1033         ERRSTACK(1);
1034         char *p;
1035
1036         if (c->state != 0)
1037                 error(Econinuse);
1038         c->state = Connecting;
1039         c->cerr[0] = '\0';
1040         if (x->connect == NULL)
1041                 error("connect not supported");
1042         p = x->connect(c, cb->f, cb->nf);
1043         if (p != NULL)
1044                 error(p);
1045
1046         qunlock(&c->qlock);
1047         if (waserror()) {
1048                 qlock(&c->qlock);
1049                 nexterror();
1050         }
1051         rendez_sleep(&c->cr, connected, c);
1052         qlock(&c->qlock);
1053         poperror();
1054
1055         if (c->cerr[0] != '\0')
1056                 error(c->cerr);
1057 }
1058
1059 /*
1060  *  called by protocol announce routine to set addresses
1061  */
1062 char *Fsstdannounce(struct conv *c, char *argv[], int argc)
1063 {
1064         memset(c->raddr, 0, sizeof(c->raddr));
1065         c->rport = 0;
1066         switch (argc) {
1067                 default:
1068                         return "bad args to announce";
1069                 case 2:
1070                         return setladdrport(c, argv[1], 1);
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(Econinuse);
1089         c->state = Announcing;
1090         c->cerr[0] = '\0';
1091         if (x->announce == NULL)
1092                 error("announce not supported");
1093         p = x->announce(c, cb->f, cb->nf);
1094         if (p != NULL)
1095                 error(p);
1096
1097         qunlock(&c->qlock);
1098         if (waserror()) {
1099                 qlock(&c->qlock);
1100                 nexterror();
1101         }
1102         rendez_sleep(&c->cr, announced, c);
1103         qlock(&c->qlock);
1104         poperror();
1105
1106         if (c->cerr[0] != '\0')
1107                 error(c->cerr);
1108 }
1109
1110 /*
1111  *  called by protocol bind routine to set addresses
1112  */
1113 char *Fsstdbind(struct conv *c, char *argv[], int argc)
1114 {
1115         switch (argc) {
1116                 default:
1117                         return "bad args to bind";
1118                 case 2:
1119                         return setladdrport(c, argv[1], 0);
1120         }
1121 }
1122
1123 void Fsconvnonblock(struct conv *cv, bool onoff)
1124 {
1125         qnonblock(cv->wq, onoff);
1126         qnonblock(cv->rq, onoff);
1127         cv->nonblock = onoff;
1128 }
1129
1130 static void bindctlmsg(struct Proto *x, struct conv *c, struct cmdbuf *cb)
1131 {
1132         char *p;
1133
1134         if (x->bind == NULL)
1135                 p = Fsstdbind(c, cb->f, cb->nf);
1136         else
1137                 p = x->bind(c, cb->f, cb->nf);
1138         if (p != NULL)
1139                 error(p);
1140 }
1141
1142 static void nonblockctlmsg(struct conv *c, struct cmdbuf *cb)
1143 {
1144         if (cb->nf < 2)
1145                 goto err;
1146         if (!strcmp(cb->f[1], "on"))
1147                 Fsconvnonblock(c, TRUE);
1148         else if (!strcmp(cb->f[1], "off"))
1149                 Fsconvnonblock(c, FALSE);
1150         else
1151                 goto err;
1152         return;
1153 err:
1154         set_errno(EINVAL);
1155         error("nonblock [on|off]");
1156 }
1157
1158 static void tosctlmsg(struct conv *c, struct cmdbuf *cb)
1159 {
1160         if (cb->nf < 2)
1161                 c->tos = 0;
1162         else
1163                 c->tos = atoi(cb->f[1]);
1164 }
1165
1166 static void ttlctlmsg(struct conv *c, struct cmdbuf *cb)
1167 {
1168         if (cb->nf < 2)
1169                 c->ttl = MAXTTL;
1170         else
1171                 c->ttl = atoi(cb->f[1]);
1172 }
1173
1174 static long ipwrite(struct chan *ch, void *v, long n, int64_t off)
1175 {
1176         ERRSTACK(1);
1177         struct conv *c;
1178         struct Proto *x;
1179         char *p;
1180         struct cmdbuf *cb;
1181         uint8_t ia[IPaddrlen], ma[IPaddrlen];
1182         struct Fs *f;
1183         char *a;
1184
1185         a = v;
1186         f = ipfs[ch->dev];
1187
1188         switch (TYPE(ch->qid)) {
1189                 default:
1190                         error(Eperm);
1191                 case Qdata:
1192                         x = f->p[PROTO(ch->qid)];
1193                         c = x->conv[CONV(ch->qid)];
1194                         qwrite(c->wq, a, n);
1195                         break;
1196                 case Qarp:
1197                         return arpwrite(f, a, n);
1198                 case Qiproute:
1199                         return routewrite(f, ch, a, n);
1200                 case Qlog:
1201                         netlogctl(f, a, n);
1202                         return n;
1203                 case Qndb:
1204                         return ndbwrite(f, a, off, n);
1205                 case Qctl:
1206                         x = f->p[PROTO(ch->qid)];
1207                         c = x->conv[CONV(ch->qid)];
1208                         cb = parsecmd(a, n);
1209
1210                         qlock(&c->qlock);
1211                         if (waserror()) {
1212                                 qunlock(&c->qlock);
1213                                 kfree(cb);
1214                                 nexterror();
1215                         }
1216                         if (cb->nf < 1)
1217                                 error("short control request");
1218                         if (strcmp(cb->f[0], "connect") == 0)
1219                                 connectctlmsg(x, c, cb);
1220                         else if (strcmp(cb->f[0], "announce") == 0)
1221                                 announcectlmsg(x, c, cb);
1222                         else if (strcmp(cb->f[0], "bind") == 0)
1223                                 bindctlmsg(x, c, cb);
1224                         else if (strcmp(cb->f[0], "nonblock") == 0)
1225                                 nonblockctlmsg(c, cb);
1226                         else if (strcmp(cb->f[0], "ttl") == 0)
1227                                 ttlctlmsg(c, cb);
1228                         else if (strcmp(cb->f[0], "tos") == 0)
1229                                 tosctlmsg(c, cb);
1230                         else if (strcmp(cb->f[0], "ignoreadvice") == 0)
1231                                 c->ignoreadvice = 1;
1232                         else if (strcmp(cb->f[0], "addmulti") == 0) {
1233                                 if (cb->nf < 2)
1234                                         error("addmulti needs interface address");
1235                                 if (cb->nf == 2) {
1236                                         if (!ipismulticast(c->raddr))
1237                                                 error("addmulti for a non multicast address");
1238                                         parseip(ia, cb->f[1]);
1239                                         ipifcaddmulti(c, c->raddr, ia);
1240                                 } else {
1241                                         parseip(ma, cb->f[2]);
1242                                         if (!ipismulticast(ma))
1243                                                 error("addmulti for a non multicast address");
1244                                         parseip(ia, cb->f[1]);
1245                                         ipifcaddmulti(c, ma, ia);
1246                                 }
1247                         } else if (strcmp(cb->f[0], "remmulti") == 0) {
1248                                 if (cb->nf < 2)
1249                                         error("remmulti needs interface address");
1250                                 if (!ipismulticast(c->raddr))
1251                                         error("remmulti for a non multicast address");
1252                                 parseip(ia, cb->f[1]);
1253                                 ipifcremmulti(c, c->raddr, ia);
1254                         } else if (x->ctl != NULL) {
1255                                 p = x->ctl(c, cb->f, cb->nf);
1256                                 if (p != NULL)
1257                                         error(p);
1258                         } else
1259                                 error("unknown control request");
1260                         qunlock(&c->qlock);
1261                         kfree(cb);
1262                         poperror();
1263         }
1264         return n;
1265 }
1266
1267 static long ipbwrite(struct chan *ch, struct block *bp, uint32_t offset)
1268 {
1269         struct conv *c;
1270         struct Proto *x;
1271         struct Fs *f;
1272         int n;
1273
1274         switch (TYPE(ch->qid)) {
1275                 case Qdata:
1276                         f = ipfs[ch->dev];
1277                         x = f->p[PROTO(ch->qid)];
1278                         c = x->conv[CONV(ch->qid)];
1279                         if (bp->next)
1280                                 bp = concatblock(bp);
1281                         n = BLEN(bp);
1282                         qbwrite(c->wq, bp);
1283                         return n;
1284                 default:
1285                         return devbwrite(ch, bp, offset);
1286         }
1287 }
1288
1289 static void ip_wake_cb(struct queue *q, void *data, int filter)
1290 {
1291         struct conv *conv = (struct conv*)data;
1292         struct fd_tap *tap_i;
1293         /* For these two, we want to ignore events on the opposite end of the
1294          * queues.  For instance, we want to know when the WQ is writable.  Our
1295          * writes will actually make it readable - we don't want to trigger a tap
1296          * for that.  However, qio doesn't know how/why we are using a queue, or
1297          * even who the ends are (hence the callbacks) */
1298         if ((filter & FDTAP_FILT_READABLE) && (q == conv->wq))
1299                 return;
1300         if ((filter & FDTAP_FILT_WRITABLE) && (q == conv->rq))
1301                 return;
1302         /* At this point, we have an event we want to send to our taps (if any).
1303          * The lock protects list integrity and the existence of the tap.
1304          *
1305          * Previously, I thought of using the conv qlock.  That actually breaks, due
1306          * to weird usages of the qlock (someone holds it for a long time, blocking
1307          * the inbound wakeup from etherread4).
1308          *
1309          * I opted for a spinlock for a couple reasons:
1310          * - fire_tap should not block.  ideally it'll be fast too (it's mostly a
1311          * send_event).
1312          * - our callers might not want to block.  A lot of network wakeups will
1313          * come network processes (etherread4) or otherwise unrelated to this
1314          * particular conversation.  I'd rather do something like fire off a KMSG
1315          * than block those.
1316          * - if fire_tap takes a while, holding the lock only slows down other
1317          * events on this *same* conversation, or other tap registration.  not a
1318          * huge deal. */
1319         spin_lock(&conv->tap_lock);
1320         SLIST_FOREACH(tap_i, &conv->data_taps, link)
1321                 fire_tap(tap_i, filter);
1322         spin_unlock(&conv->tap_lock);
1323 }
1324
1325 int iptapfd(struct chan *chan, struct fd_tap *tap, int cmd)
1326 {
1327         struct conv *conv;
1328         struct Proto *x;
1329         struct Fs *f;
1330         int ret;
1331
1332         #define DEVIP_LEGAL_DATA_TAPS (FDTAP_FILT_READABLE | FDTAP_FILT_WRITABLE | \
1333                                        FDTAP_FILT_HANGUP)
1334         #define DEVIP_LEGAL_LISTEN_TAPS (FDTAP_FILT_READABLE | FDTAP_FILT_HANGUP)
1335
1336         /* That's a lot of pointers to get to the conv! */
1337         f = ipfs[chan->dev];
1338         x = f->p[PROTO(chan->qid)];
1339         conv = x->conv[CONV(chan->qid)];
1340
1341         switch (TYPE(chan->qid)) {
1342                 case Qdata:
1343                         if (tap->filter & ~DEVIP_LEGAL_DATA_TAPS) {
1344                                 set_errno(ENOSYS);
1345                                 set_errstr("Unsupported #%s data tap, must be %p", devname(),
1346                                            DEVIP_LEGAL_DATA_TAPS);
1347                                 return -1;
1348                         }
1349                         spin_lock(&conv->tap_lock);
1350                         switch (cmd) {
1351                                 case (FDTAP_CMD_ADD):
1352                                         if (SLIST_EMPTY(&conv->data_taps)) {
1353                                                 qio_set_wake_cb(conv->rq, ip_wake_cb, conv);
1354                                                 qio_set_wake_cb(conv->wq, ip_wake_cb, conv);
1355                                         }
1356                                         SLIST_INSERT_HEAD(&conv->data_taps, tap, link);
1357                                         ret = 0;
1358                                         break;
1359                                 case (FDTAP_CMD_REM):
1360                                         SLIST_REMOVE(&conv->data_taps, tap, fd_tap, link);
1361                                         if (SLIST_EMPTY(&conv->data_taps)) {
1362                                                 qio_set_wake_cb(conv->rq, 0, conv);
1363                                                 qio_set_wake_cb(conv->wq, 0, conv);
1364                                         }
1365                                         ret = 0;
1366                                         break;
1367                                 default:
1368                                         set_errno(ENOSYS);
1369                                         set_errstr("Unsupported #%s data tap command %p",
1370                                                    devname(), cmd);
1371                                         ret = -1;
1372                         }
1373                         spin_unlock(&conv->tap_lock);
1374                         return ret;
1375                 case Qlisten:
1376                         if (tap->filter & ~DEVIP_LEGAL_LISTEN_TAPS) {
1377                                 set_errno(ENOSYS);
1378                                 set_errstr("Unsupported #%s listen tap, must be %p", devname(),
1379                                            DEVIP_LEGAL_LISTEN_TAPS);
1380                                 return -1;
1381                         }
1382                         spin_lock(&conv->tap_lock);
1383                         switch (cmd) {
1384                                 case (FDTAP_CMD_ADD):
1385                                         SLIST_INSERT_HEAD(&conv->listen_taps, tap, link);
1386                                         ret = 0;
1387                                         break;
1388                                 case (FDTAP_CMD_REM):
1389                                         SLIST_REMOVE(&conv->listen_taps, tap, fd_tap, link);
1390                                         ret = 0;
1391                                         break;
1392                                 default:
1393                                         set_errno(ENOSYS);
1394                                         set_errstr("Unsupported #%s listen tap command %p",
1395                                                    devname(), cmd);
1396                                         ret = -1;
1397                         }
1398                         spin_unlock(&conv->tap_lock);
1399                         return ret;
1400                 default:
1401                         set_errno(ENOSYS);
1402                         set_errstr("Can't tap #%s file type %d", devname(),
1403                                    TYPE(chan->qid));
1404                         return -1;
1405         }
1406 }
1407
1408 struct dev ipdevtab __devtab = {
1409         .name = "ip",
1410
1411         .reset = ipreset,
1412         .init = ipinit,
1413         .shutdown = devshutdown,
1414         .attach = ipattach,
1415         .walk = ipwalk,
1416         .stat = ipstat,
1417         .open = ipopen,
1418         .create = devcreate,
1419         .close = ipclose,
1420         .read = ipread,
1421         .bread = ipbread,
1422         .write = ipwrite,
1423         .bwrite = ipbwrite,
1424         .remove = devremove,
1425         .wstat = ipwstat,
1426         .power = devpower,
1427         .chaninfo = ipchaninfo,
1428         .tapfd = iptapfd,
1429 };
1430
1431 int Fsproto(struct Fs *f, struct Proto *p)
1432 {
1433         if (f->np >= Maxproto)
1434                 return -1;
1435
1436         qlock_init(&p->qlock);
1437         p->f = f;
1438
1439         if (p->ipproto > 0) {
1440                 if (f->t2p[p->ipproto] != NULL)
1441                         return -1;
1442                 f->t2p[p->ipproto] = p;
1443         }
1444
1445         p->qid.type = QTDIR;
1446         p->qid.path = QID(f->np, 0, Qprotodir);
1447         p->conv = kzmalloc(sizeof(struct conv *) * (p->nc + 1), 0);
1448         if (p->conv == NULL)
1449                 panic("Fsproto");
1450
1451         p->x = f->np;
1452         p->nextport = 0;
1453         p->nextrport = 600;
1454         f->p[f->np++] = p;
1455
1456         return 0;
1457 }
1458
1459 /*
1460  *  return true if this protocol is
1461  *  built in
1462  */
1463 int Fsbuiltinproto(struct Fs *f, uint8_t proto)
1464 {
1465         return f->t2p[proto] != NULL;
1466 }
1467
1468 /*
1469  *  called with protocol locked
1470  */
1471 struct conv *Fsprotoclone(struct Proto *p, char *user)
1472 {
1473         struct conv *c, **pp, **ep;
1474
1475 retry:
1476         c = NULL;
1477         ep = &p->conv[p->nc];
1478         for (pp = p->conv; pp < ep; pp++) {
1479                 c = *pp;
1480                 if (c == NULL) {
1481                         c = kzmalloc(sizeof(struct conv), 0);
1482                         if (c == NULL)
1483                                 error(Enomem);
1484                         qlock_init(&c->qlock);
1485                         qlock_init(&c->listenq);
1486                         rendez_init(&c->cr);
1487                         rendez_init(&c->listenr);
1488                         SLIST_INIT(&c->data_taps);      /* already = 0; set to be futureproof */
1489                         SLIST_INIT(&c->listen_taps);
1490                         spinlock_init(&c->tap_lock);
1491                         qlock(&c->qlock);
1492                         c->p = p;
1493                         c->x = pp - p->conv;
1494                         if (p->ptclsize != 0) {
1495                                 c->ptcl = kzmalloc(p->ptclsize, 0);
1496                                 if (c->ptcl == NULL) {
1497                                         kfree(c);
1498                                         error(Enomem);
1499                                 }
1500                         }
1501                         *pp = c;
1502                         p->ac++;
1503                         c->eq = qopen(1024, Qmsg, 0, 0);
1504                         (*p->create) (c);
1505                         assert(c->rq && c->wq);
1506                         break;
1507                 }
1508                 if (canqlock(&c->qlock)) {
1509                         /*
1510                          *  make sure both processes and protocol
1511                          *  are done with this Conv
1512                          */
1513                         if (c->inuse == 0 && (p->inuse == NULL || (*p->inuse) (c) == 0))
1514                                 break;
1515
1516                         qunlock(&c->qlock);
1517                 }
1518         }
1519         if (pp >= ep) {
1520                 if (p->gc != NULL && (*p->gc) (p))
1521                         goto retry;
1522                 return NULL;
1523         }
1524
1525         c->inuse = 1;
1526         kstrdup(&c->owner, user);
1527         c->perm = 0660;
1528         c->state = Idle;
1529         ipmove(c->laddr, IPnoaddr);
1530         ipmove(c->raddr, IPnoaddr);
1531         c->r = NULL;
1532         c->rgen = 0;
1533         c->lport = 0;
1534         c->rport = 0;
1535         c->restricted = 0;
1536         c->ttl = MAXTTL;
1537         c->tos = DFLTTOS;
1538         c->nonblock = FALSE;
1539         qreopen(c->rq);
1540         qreopen(c->wq);
1541         qreopen(c->eq);
1542
1543         qunlock(&c->qlock);
1544         return c;
1545 }
1546
1547 int Fsconnected(struct conv *c, char *msg)
1548 {
1549         if (msg != NULL && *msg != '\0')
1550                 strncpy(c->cerr, msg, sizeof(c->cerr));
1551
1552         switch (c->state) {
1553
1554                 case Announcing:
1555                         c->state = Announced;
1556                         break;
1557
1558                 case Connecting:
1559                         c->state = Connected;
1560                         break;
1561         }
1562
1563         rendez_wakeup(&c->cr);
1564         return 0;
1565 }
1566
1567 struct Proto *Fsrcvpcol(struct Fs *f, uint8_t proto)
1568 {
1569         if (f->ipmux)
1570                 return f->ipmux;
1571         else
1572                 return f->t2p[proto];
1573 }
1574
1575 struct Proto *Fsrcvpcolx(struct Fs *f, uint8_t proto)
1576 {
1577         return f->t2p[proto];
1578 }
1579
1580 static void fire_listener_taps(struct conv *conv)
1581 {
1582         struct fd_tap *tap_i;
1583         if (SLIST_EMPTY(&conv->listen_taps))
1584                 return;
1585         spin_lock(&conv->tap_lock);
1586         SLIST_FOREACH(tap_i, &conv->listen_taps, link)
1587                 fire_tap(tap_i, FDTAP_FILT_READABLE);
1588         spin_unlock(&conv->tap_lock);
1589 }
1590
1591 /*
1592  *  called with protocol locked
1593  */
1594 struct conv *Fsnewcall(struct conv *c, uint8_t * raddr, uint16_t rport,
1595                                            uint8_t * laddr, uint16_t lport, uint8_t version)
1596 {
1597         struct conv *nc;
1598         struct conv **l;
1599         int i;
1600
1601         qlock(&c->qlock);
1602         i = 0;
1603         for (l = &c->incall; *l; l = &(*l)->next)
1604                 i++;
1605         if (i >= Maxincall) {
1606                 qunlock(&c->qlock);
1607                 return NULL;
1608         }
1609
1610         /* find a free conversation */
1611         nc = Fsprotoclone(c->p, network);
1612         if (nc == NULL) {
1613                 qunlock(&c->qlock);
1614                 return NULL;
1615         }
1616         ipmove(nc->raddr, raddr);
1617         nc->rport = rport;
1618         ipmove(nc->laddr, laddr);
1619         nc->lport = lport;
1620         nc->next = NULL;
1621         *l = nc;
1622         nc->state = Connected;
1623         nc->ipversion = version;
1624
1625         qunlock(&c->qlock);
1626
1627         rendez_wakeup(&c->listenr);
1628         fire_listener_taps(c);
1629
1630         return nc;
1631 }
1632
1633 static long ndbwrite(struct Fs *f, char *a, uint32_t off, int n)
1634 {
1635         if (off > strlen(f->ndb))
1636                 error(Eio);
1637         if (off + n >= sizeof(f->ndb) - 1)
1638                 error(Eio);
1639         memmove(f->ndb + off, a, n);
1640         f->ndb[off + n] = 0;
1641         f->ndbvers++;
1642         f->ndbmtime = seconds();
1643         return n;
1644 }
1645
1646 uint32_t scalednconv(void)
1647 {
1648         //if(conf.npage*BY2PG >= 128*MB)
1649         return Nchans * 4;
1650         //  return Nchans;
1651 }