96568ab7accb1ec01d19f01ce0297a16f779f45d
[dragonfly.git] / sys / netgraph7 / bluetooth / drivers / h4 / ng_h4.c
1 /*
2  * ng_h4.c
3  */
4
5 /*-
6  * Copyright (c) 2001-2002 Maksim Yevmenkin <m_evmenkin@yahoo.com>
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  *
30  * $Id: ng_h4.c,v 1.10 2005/10/31 17:57:43 max Exp $
31  * $FreeBSD: src/sys/netgraph/bluetooth/drivers/h4/ng_h4.c,v 1.17 2007/08/13 17:19:28 emax Exp $
32  * $DragonFly: src/sys/netgraph7/bluetooth/drivers/h4/ng_h4.c,v 1.2 2008/06/26 23:05:40 dillon Exp $
33  * $DragonFly: src/sys/netgraph7/bluetooth/drivers/h4/ng_h4.c,v 1.2 2008/06/26 23:05:40 dillon Exp $
34  * 
35  * Based on:
36  * ---------
37  *
38  * FreeBSD: src/sys/netgraph/ng_tty.c
39  * Author: Archie Cobbs <archie@freebsd.org>
40  *
41  */
42
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/kernel.h>
46 #include <sys/conf.h>
47 #include <sys/endian.h>
48 #include <sys/errno.h>
49 #include <sys/fcntl.h>
50 #include <sys/ioccom.h>
51 #include <sys/malloc.h>
52 #include <sys/mbuf.h>
53 #include <sys/priv.h>
54 #include <sys/socket.h>
55 #include <sys/tty.h>
56 #include <sys/ttycom.h>
57 #include <net/if.h>
58 #include <net/if_var.h>
59 #include "ng_message.h"
60 #include "netgraph.h"
61 #include "ng_parse.h"
62 #include "bluetooth/include/ng_bluetooth.h"
63 #include "bluetooth/include/ng_hci.h"
64 #include "bluetooth/include/ng_h4.h"
65 #include "bluetooth/drivers/h4/ng_h4_var.h"
66 #include "bluetooth/drivers/h4/ng_h4_prse.h"
67
68 /*****************************************************************************
69  *****************************************************************************
70  ** This node implements a Bluetooth HCI UART transport layer as per chapter
71  ** H4 of the Bluetooth Specification Book v1.1. It is a terminal line 
72  ** discipline that is also a netgraph node. Installing this line discipline 
73  ** on a terminal device instantiates a new netgraph node of this type, which 
74  ** allows access to the device via the "hook" hook of the node.
75  **
76  ** Once the line discipline is installed, you can find out the name of the 
77  ** corresponding netgraph node via a NGIOCGINFO ioctl().
78  *****************************************************************************
79  *****************************************************************************/
80
81 /* MALLOC define */
82 #ifndef NG_SEPARATE_MALLOC
83 MALLOC_DEFINE(M_NETGRAPH_H4, "netgraph_h4", "Netgraph Bluetooth H4 node");
84 #else
85 #define M_NETGRAPH_H4 M_NETGRAPH
86 #endif /* NG_SEPARATE_MALLOC */
87
88 /* Line discipline methods */
89 static int      ng_h4_open      (struct cdev *, struct tty *);
90 static int      ng_h4_close     (struct tty *, int);
91 static int      ng_h4_read      (struct tty *, struct uio *, int);
92 static int      ng_h4_write     (struct tty *, struct uio *, int);
93 static int      ng_h4_input     (int, struct tty *);
94 static int      ng_h4_start     (struct tty *);
95 static int      ng_h4_ioctl     (struct tty *, u_long, caddr_t, 
96                                         int, struct thread *);
97
98 /* Line discipline descriptor */
99 static struct linesw            ng_h4_disc = {
100         ng_h4_open,             /* open */
101         ng_h4_close,            /* close */
102         ng_h4_read,             /* read */
103         ng_h4_write,            /* write */
104         ng_h4_ioctl,            /* ioctl */
105         ng_h4_input,            /* input */
106         ng_h4_start,            /* start */
107         ttymodem                /* modem */
108 };
109
110 /* Netgraph methods */
111 static ng_constructor_t         ng_h4_constructor;
112 static ng_rcvmsg_t              ng_h4_rcvmsg;
113 static ng_shutdown_t            ng_h4_shutdown;
114 static ng_newhook_t             ng_h4_newhook;
115 static ng_connect_t             ng_h4_connect;
116 static ng_rcvdata_t             ng_h4_rcvdata;
117 static ng_disconnect_t          ng_h4_disconnect;
118
119 /* Other stuff */
120 static void     ng_h4_process_timeout   (node_p, hook_p, void *, int);
121 static int      ng_h4_mod_event         (module_t, int, void *);
122
123 /* Netgraph node type descriptor */
124 static struct ng_type           typestruct = {
125         .version =      NG_ABI_VERSION,
126         .name =         NG_H4_NODE_TYPE,
127         .mod_event =    ng_h4_mod_event,
128         .constructor =  ng_h4_constructor,
129         .rcvmsg =       ng_h4_rcvmsg,
130         .shutdown =     ng_h4_shutdown,
131         .newhook =      ng_h4_newhook,
132         .connect =      ng_h4_connect,
133         .rcvdata =      ng_h4_rcvdata,
134         .disconnect =   ng_h4_disconnect,
135         .cmdlist =      ng_h4_cmdlist
136 };
137 NETGRAPH_INIT(h4, &typestruct);
138 MODULE_VERSION(ng_h4, NG_BLUETOOTH_VERSION);
139
140 static int      ng_h4_node = 0;
141
142 /*****************************************************************************
143  *****************************************************************************
144  **                         Line discipline methods
145  *****************************************************************************
146  *****************************************************************************/
147
148 /*
149  * Set our line discipline on the tty.
150  */
151
152 static int
153 ng_h4_open(struct cdev *dev, struct tty *tp)
154 {
155         struct thread   *td = curthread;
156         char             name[NG_NODESIZ];
157         ng_h4_info_p     sc = NULL;
158         int              error;
159
160         /* Super-user only */
161         error = priv_check(td, PRIV_NETGRAPH_TTY); /* XXX */
162         if (error != 0)
163                 return (error);
164
165         /* Initialize private struct */
166         MALLOC(sc, ng_h4_info_p, sizeof(*sc), M_NETGRAPH_H4, M_WAITOK | M_NULLOK | M_ZERO);
167         if (sc == NULL)
168                 return (ENOMEM);
169
170         sc->tp = tp;
171         sc->debug = NG_H4_WARN_LEVEL;
172
173         sc->state = NG_H4_W4_PKT_IND;
174         sc->want = 1;
175         sc->got = 0;
176
177         mtx_init(&sc->outq.ifq_mtx, "ng_h4 node+queue", NULL, MTX_DEF);
178         IFQ_SET_MAXLEN(&sc->outq, NG_H4_DEFAULTQLEN);
179         ng_callout_init(&sc->timo);
180
181         NG_H4_LOCK(sc);
182
183         /* Setup netgraph node */
184         error = ng_make_node_common(&typestruct, &sc->node);
185         if (error != 0) {
186                 NG_H4_UNLOCK(sc);
187
188                 printf("%s: Unable to create new node!\n", __func__);
189
190                 mtx_destroy(&sc->outq.ifq_mtx);
191                 bzero(sc, sizeof(*sc));
192                 FREE(sc, M_NETGRAPH_H4);
193
194                 return (error);
195         }
196
197         /* Assign node its name */
198         snprintf(name, sizeof(name), "%s%d", typestruct.name, ng_h4_node ++);
199
200         error = ng_name_node(sc->node, name);
201         if (error != 0) {
202                 NG_H4_UNLOCK(sc);
203
204                 printf("%s: %s - node name exists?\n", __func__, name);
205
206                 NG_NODE_UNREF(sc->node);
207                 mtx_destroy(&sc->outq.ifq_mtx);
208                 bzero(sc, sizeof(*sc));
209                 FREE(sc, M_NETGRAPH_H4);
210
211                 return (error);
212         }
213
214         /* Set back pointers */
215         NG_NODE_SET_PRIVATE(sc->node, sc);
216         tp->t_lsc = (caddr_t) sc;
217
218         /* The node has to be a WRITER because data can change node status */
219         NG_NODE_FORCE_WRITER(sc->node);
220
221         /*
222          * Pre-allocate cblocks to the an appropriate amount.
223          * I'm not sure what is appropriate.
224          */
225
226         ttyflush(tp, FREAD | FWRITE);
227         clist_alloc_cblocks(&tp->t_canq, 0, 0);
228         clist_alloc_cblocks(&tp->t_rawq, 0, 0);
229         clist_alloc_cblocks(&tp->t_outq,
230                 MLEN + NG_H4_HIWATER, MLEN + NG_H4_HIWATER);
231
232         NG_H4_UNLOCK(sc);
233
234         return (error);
235 } /* ng_h4_open */
236
237 /*
238  * Line specific close routine, called from device close routine
239  * and from ttioctl. This causes the node to be destroyed as well.
240  */
241
242 static int
243 ng_h4_close(struct tty *tp, int flag)
244 {
245         ng_h4_info_p    sc = (ng_h4_info_p) tp->t_lsc;
246
247         ttyflush(tp, FREAD | FWRITE);
248         clist_free_cblocks(&tp->t_outq);
249
250         if (sc != NULL) {
251                 NG_H4_LOCK(sc);
252
253                 if (callout_pending(&sc->timo))
254                         ng_uncallout(&sc->timo, sc->node);
255
256                 tp->t_lsc = NULL;
257                 sc->dying = 1;
258
259                 NG_H4_UNLOCK(sc);
260
261                 ng_rmnode_self(sc->node);
262         }
263
264         return (0);
265 } /* ng_h4_close */
266
267 /*
268  * Once the device has been turned into a node, we don't allow reading.
269  */
270
271 static int
272 ng_h4_read(struct tty *tp, struct uio *uio, int flag)
273 {
274         return (EIO);
275 } /* ng_h4_read */
276
277 /*
278  * Once the device has been turned into a node, we don't allow writing.
279  */
280
281 static int
282 ng_h4_write(struct tty *tp, struct uio *uio, int flag)
283 {
284         return (EIO);
285 } /* ng_h4_write */
286
287 /*
288  * We implement the NGIOCGINFO ioctl() defined in ng_message.h.
289  */
290
291 static int
292 ng_h4_ioctl(struct tty *tp, u_long cmd, caddr_t data, int flag,
293                 struct thread *td)
294 {
295         ng_h4_info_p    sc = (ng_h4_info_p) tp->t_lsc;
296         int             error = 0;
297
298         if (sc == NULL)
299                 return (ENXIO);
300
301         NG_H4_LOCK(sc);
302
303         switch (cmd) {
304         case NGIOCGINFO:
305 #undef  NI
306 #define NI(x)   ((struct nodeinfo *)(x))
307
308                 bzero(data, sizeof(*NI(data)));
309
310                 if (NG_NODE_HAS_NAME(sc->node))
311                         strncpy(NI(data)->name, NG_NODE_NAME(sc->node), 
312                                 sizeof(NI(data)->name) - 1);
313
314                 strncpy(NI(data)->type, sc->node->nd_type->name, 
315                         sizeof(NI(data)->type) - 1);
316
317                 NI(data)->id = (u_int32_t) ng_node2ID(sc->node);
318                 NI(data)->hooks = NG_NODE_NUMHOOKS(sc->node);
319                 break;
320
321         default:
322                 error = ENOIOCTL;
323                 break;
324         }
325
326         NG_H4_UNLOCK(sc);
327
328         return (error);
329 } /* ng_h4_ioctl */
330
331 /*
332  * Receive data coming from the device. We get one character at a time, which 
333  * is kindof silly.
334  */
335
336 static int
337 ng_h4_input(int c, struct tty *tp)
338 {
339         ng_h4_info_p    sc = (ng_h4_info_p) tp->t_lsc;
340
341         if (sc == NULL || tp != sc->tp ||
342             sc->node == NULL || NG_NODE_NOT_VALID(sc->node))
343                 return (0);
344
345         NG_H4_LOCK(sc);
346
347         /* Check for error conditions */
348         if ((tp->t_state & TS_CONNECTED) == 0) {
349                 NG_H4_INFO("%s: %s - no carrier\n", __func__,
350                         NG_NODE_NAME(sc->node));
351
352                 sc->state = NG_H4_W4_PKT_IND;
353                 sc->want = 1;
354                 sc->got = 0;
355
356                 NG_H4_UNLOCK(sc);
357
358                 return (0); /* XXX Loss of synchronization here! */
359         }
360
361         /* Check for framing error or overrun on this char */
362         if (c & TTY_ERRORMASK) {
363                 NG_H4_ERR("%s: %s - line error %#x, c=%#x\n", __func__, 
364                         NG_NODE_NAME(sc->node), c & TTY_ERRORMASK,
365                         c & TTY_CHARMASK);
366
367                 NG_H4_STAT_IERROR(sc->stat);
368
369                 sc->state = NG_H4_W4_PKT_IND;
370                 sc->want = 1;
371                 sc->got = 0;
372
373                 NG_H4_UNLOCK(sc);
374
375                 return (0); /* XXX Loss of synchronization here! */
376         }
377
378         NG_H4_STAT_BYTES_RECV(sc->stat, 1);
379
380         /* Append char to mbuf */
381         if (sc->got >= sizeof(sc->ibuf)) {
382                 NG_H4_ALERT("%s: %s - input buffer overflow, c=%#x, got=%d\n",
383                         __func__, NG_NODE_NAME(sc->node), c & TTY_CHARMASK,
384                         sc->got);
385
386                 NG_H4_STAT_IERROR(sc->stat);
387
388                 sc->state = NG_H4_W4_PKT_IND;
389                 sc->want = 1;
390                 sc->got = 0;
391
392                 NG_H4_UNLOCK(sc);
393
394                 return (0); /* XXX Loss of synchronization here! */
395         }
396
397         sc->ibuf[sc->got ++] = (c & TTY_CHARMASK);
398
399         NG_H4_INFO("%s: %s - got char %#x, want=%d, got=%d\n", __func__,
400                 NG_NODE_NAME(sc->node), c, sc->want, sc->got);
401
402         if (sc->got < sc->want) {
403                 NG_H4_UNLOCK(sc);
404
405                 return (0); /* Wait for more */
406         }
407
408         switch (sc->state) {
409         /* Got packet indicator */
410         case NG_H4_W4_PKT_IND:
411                 NG_H4_INFO("%s: %s - got packet indicator %#x\n", __func__,
412                         NG_NODE_NAME(sc->node), sc->ibuf[0]);
413
414                 sc->state = NG_H4_W4_PKT_HDR;
415
416                 /*
417                  * Since packet indicator included in the packet header
418                  * just set sc->want to sizeof(packet header).
419                  */
420
421                 switch (sc->ibuf[0]) {
422                 case NG_HCI_ACL_DATA_PKT:
423                         sc->want = sizeof(ng_hci_acldata_pkt_t);
424                         break;
425
426                 case NG_HCI_SCO_DATA_PKT:
427                         sc->want = sizeof(ng_hci_scodata_pkt_t);
428                         break;
429
430                 case NG_HCI_EVENT_PKT:
431                         sc->want = sizeof(ng_hci_event_pkt_t);
432                         break;
433
434                 default:
435                         NG_H4_WARN("%s: %s - ignoring unknown packet " \
436                                 "type=%#x\n", __func__, NG_NODE_NAME(sc->node),
437                                 sc->ibuf[0]);
438
439                         NG_H4_STAT_IERROR(sc->stat);
440
441                         sc->state = NG_H4_W4_PKT_IND;
442                         sc->want = 1;
443                         sc->got = 0;
444                         break;
445                 }
446                 break;
447
448         /* Got packet header */
449         case NG_H4_W4_PKT_HDR:
450                 sc->state = NG_H4_W4_PKT_DATA;
451
452                 switch (sc->ibuf[0]) {
453                 case NG_HCI_ACL_DATA_PKT:
454                         c = le16toh(((ng_hci_acldata_pkt_t *)
455                                 (sc->ibuf))->length);
456                         break;
457
458                 case NG_HCI_SCO_DATA_PKT:
459                         c = ((ng_hci_scodata_pkt_t *)(sc->ibuf))->length;
460                         break;
461
462                 case NG_HCI_EVENT_PKT:
463                         c = ((ng_hci_event_pkt_t *)(sc->ibuf))->length;
464                         break;
465
466                 default:
467                         KASSERT((0), ("Invalid packet type=%#x\n",
468                                 sc->ibuf[0]));
469                         break;
470                 }
471
472                 NG_H4_INFO("%s: %s - got packet header, packet type=%#x, " \
473                         "packet size=%d, payload size=%d\n", __func__, 
474                         NG_NODE_NAME(sc->node), sc->ibuf[0], sc->got, c);
475
476                 if (c > 0) {
477                         sc->want += c;
478
479                         /* 
480                          * Try to prevent possible buffer overrun
481                          *
482                          * XXX I'm *really* confused here. It turns out
483                          * that Xircom card sends us packets with length
484                          * greater then 512 bytes! This is greater then
485                          * our old receive buffer (ibuf) size. In the same
486                          * time the card demands from us *not* to send 
487                          * packets greater then 192 bytes. Weird! How the 
488                          * hell i should know how big *receive* buffer 
489                          * should be? For now increase receiving buffer 
490                          * size to 1K and add the following check.
491                          */
492
493                         if (sc->want >= sizeof(sc->ibuf)) {
494                                 int     b;
495
496                                 NG_H4_ALERT("%s: %s - packet too big for " \
497                                         "buffer, type=%#x, got=%d, want=%d, " \
498                                         "length=%d\n", __func__, 
499                                         NG_NODE_NAME(sc->node), sc->ibuf[0],
500                                         sc->got, sc->want, c);
501
502                                 NG_H4_ALERT("Packet header:\n");
503                                 for (b = 0; b < sc->got; b++)
504                                         NG_H4_ALERT("%#x ", sc->ibuf[b]);
505                                 NG_H4_ALERT("\n");
506
507                                 /* Reset state */
508                                 NG_H4_STAT_IERROR(sc->stat);
509
510                                 sc->state = NG_H4_W4_PKT_IND;
511                                 sc->want = 1;
512                                 sc->got = 0;
513                         }
514
515                         break;
516                 }
517
518                 /* else FALLTHROUGH and deliver frame */
519                 /* XXX Is this true? Should we deliver empty frame? */
520
521         /* Got packet data */
522         case NG_H4_W4_PKT_DATA:
523                 NG_H4_INFO("%s: %s - got full packet, packet type=%#x, " \
524                         "packet size=%d\n", __func__,
525                         NG_NODE_NAME(sc->node), sc->ibuf[0], sc->got);
526
527                 if (sc->hook != NULL && NG_HOOK_IS_VALID(sc->hook)) {
528                         struct mbuf     *m = NULL;
529
530                         MGETHDR(m, MB_DONTWAIT, MT_DATA);
531                         if (m != NULL) {
532                                 m->m_pkthdr.len = 0;
533
534                                 /* XXX m_copyback() is stupid */
535                                 m->m_len = min(MHLEN, sc->got);
536
537                                 m_copyback(m, 0, sc->got, sc->ibuf);
538                                 NG_SEND_DATA_ONLY(c, sc->hook, m);
539                         } else {
540                                 NG_H4_ERR("%s: %s - could not get mbuf\n",
541                                         __func__, NG_NODE_NAME(sc->node));
542
543                                 NG_H4_STAT_IERROR(sc->stat);
544                         }
545                 }
546
547                 sc->state = NG_H4_W4_PKT_IND;
548                 sc->want = 1;
549                 sc->got = 0;
550
551                 NG_H4_STAT_PCKTS_RECV(sc->stat);
552                 break;
553
554         default:
555                 KASSERT((0), ("Invalid H4 node state=%d", sc->state));
556                 break;
557         }
558
559         NG_H4_UNLOCK(sc);
560
561         return (0);
562 } /* ng_h4_input */
563
564 /*
565  * This is called when the device driver is ready for more output. Called from 
566  * tty system. 
567  */
568
569 static int
570 ng_h4_start(struct tty *tp)
571 {
572         ng_h4_info_p     sc = (ng_h4_info_p) tp->t_lsc;
573         struct mbuf     *m = NULL;
574         int              size;
575
576         if (sc == NULL || tp != sc->tp || 
577             sc->node == NULL || NG_NODE_NOT_VALID(sc->node))
578                 return (0);
579
580 #if 0
581         while (tp->t_outq.c_cc < NG_H4_HIWATER) { /* XXX 2.2 specific ? */
582 #else
583         while (1) {
584 #endif
585                 /* Remove first mbuf from queue */
586                 IF_DEQUEUE(&sc->outq, m);
587                 if (m == NULL)
588                         break;
589
590                 /* Send as much of it as possible */
591                 while (m != NULL) {
592                         size = m->m_len - b_to_q(mtod(m, u_char *),
593                                         m->m_len, &tp->t_outq);
594
595                         NG_H4_LOCK(sc);
596                         NG_H4_STAT_BYTES_SENT(sc->stat, size);
597                         NG_H4_UNLOCK(sc);
598
599                         m->m_data += size;
600                         m->m_len -= size;
601                         if (m->m_len > 0)
602                                 break;  /* device can't take no more */
603
604                         m = m_free(m);
605                 }
606
607                 /* Put remainder of mbuf chain (if any) back on queue */
608                 if (m != NULL) {
609                         IF_PREPEND(&sc->outq, m);
610                         break;
611                 }
612
613                 /* Full packet has been sent */
614                 NG_H4_LOCK(sc);
615                 NG_H4_STAT_PCKTS_SENT(sc->stat);
616                 NG_H4_UNLOCK(sc);
617         }
618
619         /* 
620          * Call output process whether or not there is any output. We are
621          * being called in lieu of ttstart and must do what it would.
622          */
623
624         tt_oproc(sc->tp);
625
626         /*
627          * This timeout is needed for operation on a pseudo-tty, because the
628          * pty code doesn't call pppstart after it has drained the t_outq.
629          */
630
631         NG_H4_LOCK(sc);
632
633         if (!IFQ_IS_EMPTY(&sc->outq) && !callout_pending(&sc->timo))
634                 ng_callout(&sc->timo, sc->node, NULL, 1,
635                         ng_h4_process_timeout, NULL, 0);
636
637         NG_H4_UNLOCK(sc);
638
639         return (0);
640 } /* ng_h4_start */
641
642 /*****************************************************************************
643  *****************************************************************************
644  **                         Netgraph node methods
645  *****************************************************************************
646  *****************************************************************************/
647
648 /*
649  * Initialize a new node of this type. We only allow nodes to be created as 
650  * a result of setting the line discipline on a tty, so always return an error
651  * if not.
652  */
653
654 static int
655 ng_h4_constructor(node_p node)
656 {
657         return (EOPNOTSUPP);
658 } /* ng_h4_constructor */
659
660 /*
661  * Add a new hook. There can only be one.
662  */
663
664 static int
665 ng_h4_newhook(node_p node, hook_p hook, const char *name)
666 {
667         ng_h4_info_p    sc = (ng_h4_info_p) NG_NODE_PRIVATE(node);
668
669         if (strcmp(name, NG_H4_HOOK) != 0)
670                 return (EINVAL);
671
672         NG_H4_LOCK(sc);
673
674         if (sc->hook != NULL) {
675                 NG_H4_UNLOCK(sc);
676                 return (EISCONN);
677         }
678         sc->hook = hook;
679
680         NG_H4_UNLOCK(sc);
681
682         return (0);
683 } /* ng_h4_newhook */
684
685 /*
686  * Connect hook. Just say yes.
687  */
688
689 static int
690 ng_h4_connect(hook_p hook)
691 {
692         ng_h4_info_p    sc = (ng_h4_info_p) NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
693
694         if (hook != sc->hook)
695                 panic("%s: hook != sc->hook\n", __func__);
696
697         NG_HOOK_FORCE_QUEUE(NG_HOOK_PEER(hook));
698         NG_HOOK_FORCE_QUEUE(hook);
699
700         return (0);
701 } /* ng_h4_connect */
702
703 /*
704  * Disconnect the hook
705  */
706
707 static int
708 ng_h4_disconnect(hook_p hook)
709 {
710         ng_h4_info_p    sc = (ng_h4_info_p) NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
711
712         /*
713          * We need to check for sc != NULL because we can be called from
714          * ng_h4_close() via ng_rmnode_self()
715          */
716
717         if (sc != NULL) {
718                 if (hook != sc->hook)
719                         panic("%s: hook != sc->hook\n", __func__);
720
721                 NG_H4_LOCK(sc);
722
723                 /* XXX do we have to untimeout and drain out queue? */
724                 if (callout_pending(&sc->timo))
725                         ng_uncallout(&sc->timo, sc->node);
726
727                 _IF_DRAIN(&sc->outq); 
728
729                 sc->state = NG_H4_W4_PKT_IND;
730                 sc->want = 1;
731                 sc->got = 0;
732
733                 sc->hook = NULL;
734
735                 NG_H4_UNLOCK(sc);
736         }
737
738         return (0);
739 } /* ng_h4_disconnect */
740
741 /*
742  * Remove this node. The does the netgraph portion of the shutdown.
743  * This should only be called indirectly from ng_h4_close().
744  */
745
746 static int
747 ng_h4_shutdown(node_p node)
748 {
749         ng_h4_info_p    sc = (ng_h4_info_p) NG_NODE_PRIVATE(node);
750
751         NG_H4_LOCK(sc);
752
753         if (!sc->dying) {
754                 NG_H4_UNLOCK(sc);
755
756                 NG_NODE_REVIVE(node);   /* we will persist */
757
758                 return (EOPNOTSUPP);
759         }
760
761         NG_H4_UNLOCK(sc);
762
763         NG_NODE_SET_PRIVATE(node, NULL);
764
765         _IF_DRAIN(&sc->outq);
766
767         NG_NODE_UNREF(node);
768         mtx_destroy(&sc->outq.ifq_mtx);
769         bzero(sc, sizeof(*sc));
770         FREE(sc, M_NETGRAPH_H4);
771
772         return (0);
773 } /* ng_h4_shutdown */
774
775 /*
776  * Receive incoming data from Netgraph system. Put it on our
777  * output queue and start output if necessary.
778  */
779
780 static int
781 ng_h4_rcvdata(hook_p hook, item_p item)
782 {
783         ng_h4_info_p     sc = (ng_h4_info_p)NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
784         struct mbuf     *m = NULL;
785         int              qlen;
786
787         if (sc == NULL)
788                 return (EHOSTDOWN);
789
790         if (hook != sc->hook)
791                 panic("%s: hook != sc->hook\n", __func__);
792
793         NGI_GET_M(item, m);
794         NG_FREE_ITEM(item);
795
796         NG_H4_LOCK(sc);
797
798         if (_IF_QFULL(&sc->outq)) {
799                 NG_H4_ERR("%s: %s - dropping mbuf, len=%d\n", __func__,
800                         NG_NODE_NAME(sc->node), m->m_pkthdr.len);
801
802                 NG_H4_STAT_OERROR(sc->stat);
803                 _IF_DROP(&sc->outq);
804
805                 NG_H4_UNLOCK(sc);
806
807                 NG_FREE_M(m);
808
809                 return (ENOBUFS);
810         }
811
812         NG_H4_INFO("%s: %s - queue mbuf, len=%d\n", __func__,
813                 NG_NODE_NAME(sc->node), m->m_pkthdr.len);
814
815         _IF_ENQUEUE(&sc->outq, m);
816         qlen = _IF_QLEN(&sc->outq);
817
818         NG_H4_UNLOCK(sc);
819
820         /*
821          * If qlen > 1, then we should already have a scheduled callout
822          */
823
824         if (qlen == 1) {
825                 mtx_lock(&Giant);
826                 ng_h4_start(sc->tp);
827                 mtx_unlock(&Giant);
828         }
829
830         return (0);
831 } /* ng_h4_rcvdata */
832
833 /*
834  * Receive control message
835  */
836
837 static int
838 ng_h4_rcvmsg(node_p node, item_p item, hook_p lasthook)
839 {
840         ng_h4_info_p     sc = (ng_h4_info_p) NG_NODE_PRIVATE(node);
841         struct ng_mesg  *msg = NULL, *resp = NULL;
842         int              error = 0;
843
844         if (sc == NULL)
845                 return (EHOSTDOWN);
846
847         NGI_GET_MSG(item, msg);
848         NG_H4_LOCK(sc);
849
850         switch (msg->header.typecookie) {
851         case NGM_GENERIC_COOKIE:
852                 switch (msg->header.cmd) {
853                 case NGM_TEXT_STATUS:
854                         NG_MKRESPONSE(resp, msg, NG_TEXTRESPONSE, M_WAITOK | M_NULLOK);
855                         if (resp == NULL)
856                                 error = ENOMEM;
857                         else
858                                 snprintf(resp->data, NG_TEXTRESPONSE,
859                                         "Hook: %s\n"   \
860                                         "Debug: %d\n"  \
861                                         "State: %d\n"  \
862                                         "Queue: [have:%d,max:%d]\n" \
863                                         "Input: [got:%d,want:%d]",
864                                         (sc->hook != NULL)? NG_H4_HOOK : "",
865                                         sc->debug,
866                                         sc->state,
867                                         _IF_QLEN(&sc->outq),
868                                         sc->outq.ifq_maxlen,
869                                         sc->got,
870                                         sc->want);
871                         break;
872
873                 default:
874                         error = EINVAL;
875                         break;
876                 }
877                 break;
878
879         case NGM_H4_COOKIE:
880                 switch (msg->header.cmd) {
881                 case NGM_H4_NODE_RESET:
882                         _IF_DRAIN(&sc->outq); 
883                         sc->state = NG_H4_W4_PKT_IND;
884                         sc->want = 1;
885                         sc->got = 0;
886                         break;
887
888                 case NGM_H4_NODE_GET_STATE:
889                         NG_MKRESPONSE(resp, msg, sizeof(ng_h4_node_state_ep),
890                                 M_WAITOK | M_NULLOK);
891                         if (resp == NULL)
892                                 error = ENOMEM;
893                         else
894                                 *((ng_h4_node_state_ep *)(resp->data)) = 
895                                         sc->state;
896                         break;
897
898                 case NGM_H4_NODE_GET_DEBUG:
899                         NG_MKRESPONSE(resp, msg, sizeof(ng_h4_node_debug_ep),
900                                 M_WAITOK | M_NULLOK);
901                         if (resp == NULL)
902                                 error = ENOMEM;
903                         else
904                                 *((ng_h4_node_debug_ep *)(resp->data)) = 
905                                         sc->debug;
906                         break;
907
908                 case NGM_H4_NODE_SET_DEBUG:
909                         if (msg->header.arglen != sizeof(ng_h4_node_debug_ep))
910                                 error = EMSGSIZE;
911                         else
912                                 sc->debug =
913                                         *((ng_h4_node_debug_ep *)(msg->data));
914                         break;
915
916                 case NGM_H4_NODE_GET_QLEN:
917                         NG_MKRESPONSE(resp, msg, sizeof(ng_h4_node_qlen_ep),
918                                 M_WAITOK | M_NULLOK);
919                         if (resp == NULL)
920                                 error = ENOMEM;
921                         else
922                                 *((ng_h4_node_qlen_ep *)(resp->data)) = 
923                                         sc->outq.ifq_maxlen;
924                         break;
925
926                 case NGM_H4_NODE_SET_QLEN:
927                         if (msg->header.arglen != sizeof(ng_h4_node_qlen_ep))
928                                 error = EMSGSIZE;
929                         else if (*((ng_h4_node_qlen_ep *)(msg->data)) <= 0)
930                                 error = EINVAL;
931                         else
932                                 IFQ_SET_MAXLEN(&sc->outq,
933                                         *((ng_h4_node_qlen_ep *)(msg->data)));
934                         break;
935
936                 case NGM_H4_NODE_GET_STAT:
937                         NG_MKRESPONSE(resp, msg, sizeof(ng_h4_node_stat_ep),
938                                 M_WAITOK | M_NULLOK);
939                         if (resp == NULL)
940                                 error = ENOMEM;
941                         else
942                                 bcopy(&sc->stat, resp->data,
943                                         sizeof(ng_h4_node_stat_ep));
944                         break;
945
946                 case NGM_H4_NODE_RESET_STAT:
947                         NG_H4_STAT_RESET(sc->stat);
948                         break;
949
950                 default:
951                         error = EINVAL;
952                         break;
953                 }
954                 break;
955
956         default:
957                 error = EINVAL;
958                 break;
959         }
960
961         NG_H4_UNLOCK(sc);
962
963         NG_RESPOND_MSG(error, node, item, resp);
964         NG_FREE_MSG(msg);
965
966         return (error);
967 } /* ng_h4_rcvmsg */
968
969 /*
970  * Timeout processing function.
971  * We still have data to output to the device, so try sending more.
972  */
973
974 static void
975 ng_h4_process_timeout(node_p node, hook_p hook, void *arg1, int arg2)
976 {
977         ng_h4_info_p    sc = (ng_h4_info_p) NG_NODE_PRIVATE(node);
978
979         mtx_lock(&Giant);
980         ng_h4_start(sc->tp);
981         mtx_unlock(&Giant);
982 } /* ng_h4_process_timeout */
983
984 /*
985  * Handle loading and unloading for this node type
986  */
987
988 static int
989 ng_h4_mod_event(module_t mod, int event, void *data)
990 {
991         static int      ng_h4_ldisc;
992         int             error = 0;
993
994         switch (event) {
995         case MOD_LOAD:
996                 /* Register line discipline */
997                 mtx_lock(&Giant);
998                 ng_h4_ldisc = ldisc_register(H4DISC, &ng_h4_disc);
999                 mtx_unlock(&Giant);
1000
1001                 if (ng_h4_ldisc < 0) {
1002                         printf("%s: can't register H4 line discipline\n",
1003                                 __func__);
1004                         error = EIO;
1005                 }
1006                 break;
1007
1008         case MOD_UNLOAD:
1009                 /* Unregister line discipline */
1010                 mtx_lock(&Giant);
1011                 ldisc_deregister(ng_h4_ldisc);
1012                 mtx_unlock(&Giant);
1013                 break;
1014
1015         default:
1016                 error = EOPNOTSUPP;
1017                 break;
1018         }
1019
1020         return (error);
1021 } /* ng_h4_mod_event */
1022