xref: /freebsd/sys/dev/usb/misc/udbp.c (revision ca987d4641cdcd7f27e153db17c5bf064934faf5)
1 /*-
2  * Copyright (c) 1996-2000 Whistle Communications, Inc.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of author nor the names of its
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY NICK HIBMA AND CONTRIBUTORS
18  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
19  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
21  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27  * POSSIBILITY OF SUCH DAMAGE.
28  *
29  */
30 
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
33 
34 /* Driver for arbitrary double bulk pipe devices.
35  * The driver assumes that there will be the same driver on the other side.
36  *
37  * XXX Some more information on what the framing of the IP packets looks like.
38  *
39  * To take full advantage of bulk transmission, packets should be chosen
40  * between 1k and 5k in size (1k to make sure the sending side starts
41  * streaming, and <5k to avoid overflowing the system with small TDs).
42  */
43 
44 
45 /* probe/attach/detach:
46  *  Connect the driver to the hardware and netgraph
47  *
48  *  The reason we submit a bulk in transfer is that USB does not know about
49  *  interrupts. The bulk transfer continuously polls the device for data.
50  *  While the device has no data available, the device NAKs the TDs. As soon
51  *  as there is data, the transfer happens and the data comes flowing in.
52  *
53  *  In case you were wondering, interrupt transfers happen exactly that way.
54  *  It therefore doesn't make sense to use the interrupt pipe to signal
55  *  'data ready' and then schedule a bulk transfer to fetch it. That would
56  *  incur a 2ms delay at least, without reducing bandwidth requirements.
57  *
58  */
59 
60 #include <sys/stdint.h>
61 #include <sys/stddef.h>
62 #include <sys/param.h>
63 #include <sys/queue.h>
64 #include <sys/types.h>
65 #include <sys/systm.h>
66 #include <sys/kernel.h>
67 #include <sys/bus.h>
68 #include <sys/module.h>
69 #include <sys/lock.h>
70 #include <sys/mutex.h>
71 #include <sys/condvar.h>
72 #include <sys/sysctl.h>
73 #include <sys/sx.h>
74 #include <sys/unistd.h>
75 #include <sys/callout.h>
76 #include <sys/malloc.h>
77 #include <sys/priv.h>
78 
79 #include <dev/usb/usb.h>
80 #include <dev/usb/usbdi.h>
81 #include <dev/usb/usbdi_util.h>
82 #include "usbdevs.h"
83 
84 #define	USB_DEBUG_VAR udbp_debug
85 #include <dev/usb/usb_debug.h>
86 
87 #include <sys/mbuf.h>
88 
89 #include <netgraph/ng_message.h>
90 #include <netgraph/netgraph.h>
91 #include <netgraph/ng_parse.h>
92 #include <netgraph/bluetooth/include/ng_bluetooth.h>
93 
94 #include <dev/usb/misc/udbp.h>
95 
96 #ifdef USB_DEBUG
97 static int udbp_debug = 0;
98 
99 static SYSCTL_NODE(_hw_usb, OID_AUTO, udbp, CTLFLAG_RW, 0, "USB udbp");
100 SYSCTL_INT(_hw_usb_udbp, OID_AUTO, debug, CTLFLAG_RWTUN,
101     &udbp_debug, 0, "udbp debug level");
102 #endif
103 
104 #define	UDBP_TIMEOUT	2000		/* timeout on outbound transfers, in
105 					 * msecs */
106 #define	UDBP_BUFFERSIZE	MCLBYTES	/* maximum number of bytes in one
107 					 * transfer */
108 #define	UDBP_T_WR       0
109 #define	UDBP_T_RD       1
110 #define	UDBP_T_WR_CS    2
111 #define	UDBP_T_RD_CS    3
112 #define	UDBP_T_MAX      4
113 #define	UDBP_Q_MAXLEN   50
114 
115 struct udbp_softc {
116 
117 	struct mtx sc_mtx;
118 	struct ng_bt_mbufq sc_xmitq_hipri;	/* hi-priority transmit queue */
119 	struct ng_bt_mbufq sc_xmitq;	/* low-priority transmit queue */
120 
121 	struct usb_xfer *sc_xfer[UDBP_T_MAX];
122 	node_p	sc_node;		/* back pointer to node */
123 	hook_p	sc_hook;		/* pointer to the hook */
124 	struct mbuf *sc_bulk_in_buffer;
125 
126 	uint32_t sc_packets_in;		/* packets in from downstream */
127 	uint32_t sc_packets_out;	/* packets out towards downstream */
128 
129 	uint8_t	sc_flags;
130 #define	UDBP_FLAG_READ_STALL    0x01	/* read transfer stalled */
131 #define	UDBP_FLAG_WRITE_STALL   0x02	/* write transfer stalled */
132 
133 	uint8_t	sc_name[16];
134 };
135 
136 /* prototypes */
137 
138 static int udbp_modload(module_t mod, int event, void *data);
139 
140 static device_probe_t udbp_probe;
141 static device_attach_t udbp_attach;
142 static device_detach_t udbp_detach;
143 
144 static usb_callback_t udbp_bulk_read_callback;
145 static usb_callback_t udbp_bulk_read_clear_stall_callback;
146 static usb_callback_t udbp_bulk_write_callback;
147 static usb_callback_t udbp_bulk_write_clear_stall_callback;
148 
149 static void	udbp_bulk_read_complete(node_p, hook_p, void *, int);
150 
151 static ng_constructor_t	ng_udbp_constructor;
152 static ng_rcvmsg_t	ng_udbp_rcvmsg;
153 static ng_shutdown_t	ng_udbp_rmnode;
154 static ng_newhook_t	ng_udbp_newhook;
155 static ng_connect_t	ng_udbp_connect;
156 static ng_rcvdata_t	ng_udbp_rcvdata;
157 static ng_disconnect_t	ng_udbp_disconnect;
158 
159 /* Parse type for struct ngudbpstat */
160 static const struct ng_parse_struct_field
161 	ng_udbp_stat_type_fields[] = NG_UDBP_STATS_TYPE_INFO;
162 
163 static const struct ng_parse_type ng_udbp_stat_type = {
164 	&ng_parse_struct_type,
165 	&ng_udbp_stat_type_fields
166 };
167 
168 /* List of commands and how to convert arguments to/from ASCII */
169 static const struct ng_cmdlist ng_udbp_cmdlist[] = {
170 	{
171 		NGM_UDBP_COOKIE,
172 		NGM_UDBP_GET_STATUS,
173 		"getstatus",
174 		NULL,
175 		&ng_udbp_stat_type,
176 	},
177 	{
178 		NGM_UDBP_COOKIE,
179 		NGM_UDBP_SET_FLAG,
180 		"setflag",
181 		&ng_parse_int32_type,
182 		NULL
183 	},
184 	{0}
185 };
186 
187 /* Netgraph node type descriptor */
188 static struct ng_type ng_udbp_typestruct = {
189 	.version = NG_ABI_VERSION,
190 	.name = NG_UDBP_NODE_TYPE,
191 	.constructor = ng_udbp_constructor,
192 	.rcvmsg = ng_udbp_rcvmsg,
193 	.shutdown = ng_udbp_rmnode,
194 	.newhook = ng_udbp_newhook,
195 	.connect = ng_udbp_connect,
196 	.rcvdata = ng_udbp_rcvdata,
197 	.disconnect = ng_udbp_disconnect,
198 	.cmdlist = ng_udbp_cmdlist,
199 };
200 
201 /* USB config */
202 static const struct usb_config udbp_config[UDBP_T_MAX] = {
203 
204 	[UDBP_T_WR] = {
205 		.type = UE_BULK,
206 		.endpoint = UE_ADDR_ANY,
207 		.direction = UE_DIR_OUT,
208 		.bufsize = UDBP_BUFFERSIZE,
209 		.flags = {.pipe_bof = 1,.force_short_xfer = 1,},
210 		.callback = &udbp_bulk_write_callback,
211 		.timeout = UDBP_TIMEOUT,
212 	},
213 
214 	[UDBP_T_RD] = {
215 		.type = UE_BULK,
216 		.endpoint = UE_ADDR_ANY,
217 		.direction = UE_DIR_IN,
218 		.bufsize = UDBP_BUFFERSIZE,
219 		.flags = {.pipe_bof = 1,.short_xfer_ok = 1,},
220 		.callback = &udbp_bulk_read_callback,
221 	},
222 
223 	[UDBP_T_WR_CS] = {
224 		.type = UE_CONTROL,
225 		.endpoint = 0x00,	/* Control pipe */
226 		.direction = UE_DIR_ANY,
227 		.bufsize = sizeof(struct usb_device_request),
228 		.callback = &udbp_bulk_write_clear_stall_callback,
229 		.timeout = 1000,	/* 1 second */
230 		.interval = 50,	/* 50ms */
231 	},
232 
233 	[UDBP_T_RD_CS] = {
234 		.type = UE_CONTROL,
235 		.endpoint = 0x00,	/* Control pipe */
236 		.direction = UE_DIR_ANY,
237 		.bufsize = sizeof(struct usb_device_request),
238 		.callback = &udbp_bulk_read_clear_stall_callback,
239 		.timeout = 1000,	/* 1 second */
240 		.interval = 50,	/* 50ms */
241 	},
242 };
243 
244 static devclass_t udbp_devclass;
245 
246 static device_method_t udbp_methods[] = {
247 	/* Device interface */
248 	DEVMETHOD(device_probe, udbp_probe),
249 	DEVMETHOD(device_attach, udbp_attach),
250 	DEVMETHOD(device_detach, udbp_detach),
251 
252 	DEVMETHOD_END
253 };
254 
255 static driver_t udbp_driver = {
256 	.name = "udbp",
257 	.methods = udbp_methods,
258 	.size = sizeof(struct udbp_softc),
259 };
260 
261 static const STRUCT_USB_HOST_ID udbp_devs[] = {
262 	{USB_VPI(USB_VENDOR_BELKIN, USB_PRODUCT_BELKIN_F5U258, 0)},
263 	{USB_VPI(USB_VENDOR_NETCHIP, USB_PRODUCT_NETCHIP_TURBOCONNECT, 0)},
264 	{USB_VPI(USB_VENDOR_NETCHIP, USB_PRODUCT_NETCHIP_GADGETZERO, 0)},
265 	{USB_VPI(USB_VENDOR_PROLIFIC, USB_PRODUCT_PROLIFIC_PL2301, 0)},
266 	{USB_VPI(USB_VENDOR_PROLIFIC, USB_PRODUCT_PROLIFIC_PL2302, 0)},
267 	{USB_VPI(USB_VENDOR_PROLIFIC, USB_PRODUCT_PROLIFIC_PL27A1, 0)},
268 	{USB_VPI(USB_VENDOR_ANCHOR, USB_PRODUCT_ANCHOR_EZLINK, 0)},
269 	{USB_VPI(USB_VENDOR_GENESYS, USB_PRODUCT_GENESYS_GL620USB, 0)},
270 };
271 
272 DRIVER_MODULE(udbp, uhub, udbp_driver, udbp_devclass, udbp_modload, 0);
273 MODULE_DEPEND(udbp, netgraph, NG_ABI_VERSION, NG_ABI_VERSION, NG_ABI_VERSION);
274 MODULE_DEPEND(udbp, usb, 1, 1, 1);
275 MODULE_VERSION(udbp, 1);
276 USB_PNP_HOST_INFO(udbp_devs);
277 
278 static int
279 udbp_modload(module_t mod, int event, void *data)
280 {
281 	int error;
282 
283 	switch (event) {
284 	case MOD_LOAD:
285 		error = ng_newtype(&ng_udbp_typestruct);
286 		if (error != 0) {
287 			printf("%s: Could not register "
288 			    "Netgraph node type, error=%d\n",
289 			    NG_UDBP_NODE_TYPE, error);
290 		}
291 		break;
292 
293 	case MOD_UNLOAD:
294 		error = ng_rmtype(&ng_udbp_typestruct);
295 		break;
296 
297 	default:
298 		error = EOPNOTSUPP;
299 		break;
300 	}
301 	return (error);
302 }
303 
304 static int
305 udbp_probe(device_t dev)
306 {
307 	struct usb_attach_arg *uaa = device_get_ivars(dev);
308 
309 	if (uaa->usb_mode != USB_MODE_HOST)
310 		return (ENXIO);
311 	if (uaa->info.bConfigIndex != 0)
312 		return (ENXIO);
313 	if (uaa->info.bIfaceIndex != 0)
314 		return (ENXIO);
315 
316 	return (usbd_lookup_id_by_uaa(udbp_devs, sizeof(udbp_devs), uaa));
317 }
318 
319 static int
320 udbp_attach(device_t dev)
321 {
322 	struct usb_attach_arg *uaa = device_get_ivars(dev);
323 	struct udbp_softc *sc = device_get_softc(dev);
324 	int error;
325 
326 	device_set_usb_desc(dev);
327 
328 	snprintf(sc->sc_name, sizeof(sc->sc_name),
329 	    "%s", device_get_nameunit(dev));
330 
331 	mtx_init(&sc->sc_mtx, "udbp lock", NULL, MTX_DEF | MTX_RECURSE);
332 
333 	error = usbd_transfer_setup(uaa->device, &uaa->info.bIfaceIndex,
334 	    sc->sc_xfer, udbp_config, UDBP_T_MAX, sc, &sc->sc_mtx);
335 	if (error) {
336 		DPRINTF("error=%s\n", usbd_errstr(error));
337 		goto detach;
338 	}
339 	NG_BT_MBUFQ_INIT(&sc->sc_xmitq, UDBP_Q_MAXLEN);
340 
341 	NG_BT_MBUFQ_INIT(&sc->sc_xmitq_hipri, UDBP_Q_MAXLEN);
342 
343 	/* create Netgraph node */
344 
345 	if (ng_make_node_common(&ng_udbp_typestruct, &sc->sc_node) != 0) {
346 		printf("%s: Could not create Netgraph node\n",
347 		    sc->sc_name);
348 		sc->sc_node = NULL;
349 		goto detach;
350 	}
351 	/* name node */
352 
353 	if (ng_name_node(sc->sc_node, sc->sc_name) != 0) {
354 		printf("%s: Could not name node\n",
355 		    sc->sc_name);
356 		NG_NODE_UNREF(sc->sc_node);
357 		sc->sc_node = NULL;
358 		goto detach;
359 	}
360 	NG_NODE_SET_PRIVATE(sc->sc_node, sc);
361 
362 	/* the device is now operational */
363 
364 	return (0);			/* success */
365 
366 detach:
367 	udbp_detach(dev);
368 	return (ENOMEM);		/* failure */
369 }
370 
371 static int
372 udbp_detach(device_t dev)
373 {
374 	struct udbp_softc *sc = device_get_softc(dev);
375 
376 	/* destroy Netgraph node */
377 
378 	if (sc->sc_node != NULL) {
379 		NG_NODE_SET_PRIVATE(sc->sc_node, NULL);
380 		ng_rmnode_self(sc->sc_node);
381 		sc->sc_node = NULL;
382 	}
383 	/* free USB transfers, if any */
384 
385 	usbd_transfer_unsetup(sc->sc_xfer, UDBP_T_MAX);
386 
387 	mtx_destroy(&sc->sc_mtx);
388 
389 	/* destroy queues */
390 
391 	NG_BT_MBUFQ_DESTROY(&sc->sc_xmitq);
392 	NG_BT_MBUFQ_DESTROY(&sc->sc_xmitq_hipri);
393 
394 	/* extra check */
395 
396 	if (sc->sc_bulk_in_buffer) {
397 		m_freem(sc->sc_bulk_in_buffer);
398 		sc->sc_bulk_in_buffer = NULL;
399 	}
400 	return (0);			/* success */
401 }
402 
403 static void
404 udbp_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error)
405 {
406 	struct udbp_softc *sc = usbd_xfer_softc(xfer);
407 	struct usb_page_cache *pc;
408 	struct mbuf *m;
409 	int actlen;
410 
411 	usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL);
412 
413 	switch (USB_GET_STATE(xfer)) {
414 	case USB_ST_TRANSFERRED:
415 
416 		/* allocate new mbuf */
417 
418 		MGETHDR(m, M_NOWAIT, MT_DATA);
419 
420 		if (m == NULL) {
421 			goto tr_setup;
422 		}
423 
424 		if (!(MCLGET(m, M_NOWAIT))) {
425 			m_freem(m);
426 			goto tr_setup;
427 		}
428 		m->m_pkthdr.len = m->m_len = actlen;
429 
430 		pc = usbd_xfer_get_frame(xfer, 0);
431 		usbd_copy_out(pc, 0, m->m_data, actlen);
432 
433 		sc->sc_bulk_in_buffer = m;
434 
435 		DPRINTF("received package %d bytes\n", actlen);
436 
437 	case USB_ST_SETUP:
438 tr_setup:
439 		if (sc->sc_bulk_in_buffer) {
440 			ng_send_fn(sc->sc_node, NULL, &udbp_bulk_read_complete, NULL, 0);
441 			return;
442 		}
443 		if (sc->sc_flags & UDBP_FLAG_READ_STALL) {
444 			usbd_transfer_start(sc->sc_xfer[UDBP_T_RD_CS]);
445 			return;
446 		}
447 		usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
448 		usbd_transfer_submit(xfer);
449 		return;
450 
451 	default:			/* Error */
452 		if (error != USB_ERR_CANCELLED) {
453 			/* try to clear stall first */
454 			sc->sc_flags |= UDBP_FLAG_READ_STALL;
455 			usbd_transfer_start(sc->sc_xfer[UDBP_T_RD_CS]);
456 		}
457 		return;
458 
459 	}
460 }
461 
462 static void
463 udbp_bulk_read_clear_stall_callback(struct usb_xfer *xfer, usb_error_t error)
464 {
465 	struct udbp_softc *sc = usbd_xfer_softc(xfer);
466 	struct usb_xfer *xfer_other = sc->sc_xfer[UDBP_T_RD];
467 
468 	if (usbd_clear_stall_callback(xfer, xfer_other)) {
469 		DPRINTF("stall cleared\n");
470 		sc->sc_flags &= ~UDBP_FLAG_READ_STALL;
471 		usbd_transfer_start(xfer_other);
472 	}
473 }
474 
475 static void
476 udbp_bulk_read_complete(node_p node, hook_p hook, void *arg1, int arg2)
477 {
478 	struct udbp_softc *sc = NG_NODE_PRIVATE(node);
479 	struct mbuf *m;
480 	int error;
481 
482 	if (sc == NULL) {
483 		return;
484 	}
485 	mtx_lock(&sc->sc_mtx);
486 
487 	m = sc->sc_bulk_in_buffer;
488 
489 	if (m) {
490 
491 		sc->sc_bulk_in_buffer = NULL;
492 
493 		if ((sc->sc_hook == NULL) ||
494 		    NG_HOOK_NOT_VALID(sc->sc_hook)) {
495 			DPRINTF("No upstream hook\n");
496 			goto done;
497 		}
498 		sc->sc_packets_in++;
499 
500 		NG_SEND_DATA_ONLY(error, sc->sc_hook, m);
501 
502 		m = NULL;
503 	}
504 done:
505 	if (m) {
506 		m_freem(m);
507 	}
508 	/* start USB bulk-in transfer, if not already started */
509 
510 	usbd_transfer_start(sc->sc_xfer[UDBP_T_RD]);
511 
512 	mtx_unlock(&sc->sc_mtx);
513 }
514 
515 static void
516 udbp_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error)
517 {
518 	struct udbp_softc *sc = usbd_xfer_softc(xfer);
519 	struct usb_page_cache *pc;
520 	struct mbuf *m;
521 
522 	switch (USB_GET_STATE(xfer)) {
523 	case USB_ST_TRANSFERRED:
524 
525 		sc->sc_packets_out++;
526 
527 	case USB_ST_SETUP:
528 		if (sc->sc_flags & UDBP_FLAG_WRITE_STALL) {
529 			usbd_transfer_start(sc->sc_xfer[UDBP_T_WR_CS]);
530 			return;
531 		}
532 		/* get next mbuf, if any */
533 
534 		NG_BT_MBUFQ_DEQUEUE(&sc->sc_xmitq_hipri, m);
535 		if (m == NULL) {
536 			NG_BT_MBUFQ_DEQUEUE(&sc->sc_xmitq, m);
537 			if (m == NULL) {
538 				DPRINTF("Data queue is empty\n");
539 				return;
540 			}
541 		}
542 		if (m->m_pkthdr.len > MCLBYTES) {
543 			DPRINTF("truncating large packet "
544 			    "from %d to %d bytes\n", m->m_pkthdr.len,
545 			    MCLBYTES);
546 			m->m_pkthdr.len = MCLBYTES;
547 		}
548 		pc = usbd_xfer_get_frame(xfer, 0);
549 		usbd_m_copy_in(pc, 0, m, 0, m->m_pkthdr.len);
550 
551 		usbd_xfer_set_frame_len(xfer, 0, m->m_pkthdr.len);
552 
553 		DPRINTF("packet out: %d bytes\n", m->m_pkthdr.len);
554 
555 		m_freem(m);
556 
557 		usbd_transfer_submit(xfer);
558 		return;
559 
560 	default:			/* Error */
561 		if (error != USB_ERR_CANCELLED) {
562 			/* try to clear stall first */
563 			sc->sc_flags |= UDBP_FLAG_WRITE_STALL;
564 			usbd_transfer_start(sc->sc_xfer[UDBP_T_WR_CS]);
565 		}
566 		return;
567 
568 	}
569 }
570 
571 static void
572 udbp_bulk_write_clear_stall_callback(struct usb_xfer *xfer, usb_error_t error)
573 {
574 	struct udbp_softc *sc = usbd_xfer_softc(xfer);
575 	struct usb_xfer *xfer_other = sc->sc_xfer[UDBP_T_WR];
576 
577 	if (usbd_clear_stall_callback(xfer, xfer_other)) {
578 		DPRINTF("stall cleared\n");
579 		sc->sc_flags &= ~UDBP_FLAG_WRITE_STALL;
580 		usbd_transfer_start(xfer_other);
581 	}
582 }
583 
584 /***********************************************************************
585  * Start of Netgraph methods
586  **********************************************************************/
587 
588 /*
589  * If this is a device node so this work is done in the attach()
590  * routine and the constructor will return EINVAL as you should not be able
591  * to create nodes that depend on hardware (unless you can add the hardware :)
592  */
593 static int
594 ng_udbp_constructor(node_p node)
595 {
596 	return (EINVAL);
597 }
598 
599 /*
600  * Give our ok for a hook to be added...
601  * If we are not running this might kick a device into life.
602  * Possibly decode information out of the hook name.
603  * Add the hook's private info to the hook structure.
604  * (if we had some). In this example, we assume that there is a
605  * an array of structs, called 'channel' in the private info,
606  * one for each active channel. The private
607  * pointer of each hook points to the appropriate UDBP_hookinfo struct
608  * so that the source of an input packet is easily identified.
609  */
610 static int
611 ng_udbp_newhook(node_p node, hook_p hook, const char *name)
612 {
613 	struct udbp_softc *sc = NG_NODE_PRIVATE(node);
614 	int32_t error = 0;
615 
616 	if (strcmp(name, NG_UDBP_HOOK_NAME)) {
617 		return (EINVAL);
618 	}
619 	mtx_lock(&sc->sc_mtx);
620 
621 	if (sc->sc_hook != NULL) {
622 		error = EISCONN;
623 	} else {
624 		sc->sc_hook = hook;
625 		NG_HOOK_SET_PRIVATE(hook, NULL);
626 	}
627 
628 	mtx_unlock(&sc->sc_mtx);
629 
630 	return (error);
631 }
632 
633 /*
634  * Get a netgraph control message.
635  * Check it is one we understand. If needed, send a response.
636  * We could save the address for an async action later, but don't here.
637  * Always free the message.
638  * The response should be in a malloc'd region that the caller can 'free'.
639  * A response is not required.
640  * Theoretically you could respond defferently to old message types if
641  * the cookie in the header didn't match what we consider to be current
642  * (so that old userland programs could continue to work).
643  */
644 static int
645 ng_udbp_rcvmsg(node_p node, item_p item, hook_p lasthook)
646 {
647 	struct udbp_softc *sc = NG_NODE_PRIVATE(node);
648 	struct ng_mesg *resp = NULL;
649 	int error = 0;
650 	struct ng_mesg *msg;
651 
652 	NGI_GET_MSG(item, msg);
653 	/* Deal with message according to cookie and command */
654 	switch (msg->header.typecookie) {
655 	case NGM_UDBP_COOKIE:
656 		switch (msg->header.cmd) {
657 		case NGM_UDBP_GET_STATUS:
658 			{
659 				struct ngudbpstat *stats;
660 
661 				NG_MKRESPONSE(resp, msg, sizeof(*stats), M_NOWAIT);
662 				if (!resp) {
663 					error = ENOMEM;
664 					break;
665 				}
666 				stats = (struct ngudbpstat *)resp->data;
667 				mtx_lock(&sc->sc_mtx);
668 				stats->packets_in = sc->sc_packets_in;
669 				stats->packets_out = sc->sc_packets_out;
670 				mtx_unlock(&sc->sc_mtx);
671 				break;
672 			}
673 		case NGM_UDBP_SET_FLAG:
674 			if (msg->header.arglen != sizeof(uint32_t)) {
675 				error = EINVAL;
676 				break;
677 			}
678 			DPRINTF("flags = 0x%08x\n",
679 			    *((uint32_t *)msg->data));
680 			break;
681 		default:
682 			error = EINVAL;	/* unknown command */
683 			break;
684 		}
685 		break;
686 	default:
687 		error = EINVAL;		/* unknown cookie type */
688 		break;
689 	}
690 
691 	/* Take care of synchronous response, if any */
692 	NG_RESPOND_MSG(error, node, item, resp);
693 	NG_FREE_MSG(msg);
694 	return (error);
695 }
696 
697 /*
698  * Accept data from the hook and queue it for output.
699  */
700 static int
701 ng_udbp_rcvdata(hook_p hook, item_p item)
702 {
703 	struct udbp_softc *sc = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
704 	struct ng_bt_mbufq *queue_ptr;
705 	struct mbuf *m;
706 	struct ng_tag_prio *ptag;
707 	int error;
708 
709 	if (sc == NULL) {
710 		NG_FREE_ITEM(item);
711 		return (EHOSTDOWN);
712 	}
713 	NGI_GET_M(item, m);
714 	NG_FREE_ITEM(item);
715 
716 	/*
717 	 * Now queue the data for when it can be sent
718 	 */
719 	ptag = (void *)m_tag_locate(m, NGM_GENERIC_COOKIE,
720 	    NG_TAG_PRIO, NULL);
721 
722 	if (ptag && (ptag->priority > NG_PRIO_CUTOFF))
723 		queue_ptr = &sc->sc_xmitq_hipri;
724 	else
725 		queue_ptr = &sc->sc_xmitq;
726 
727 	mtx_lock(&sc->sc_mtx);
728 
729 	if (NG_BT_MBUFQ_FULL(queue_ptr)) {
730 		NG_BT_MBUFQ_DROP(queue_ptr);
731 		NG_FREE_M(m);
732 		error = ENOBUFS;
733 	} else {
734 		NG_BT_MBUFQ_ENQUEUE(queue_ptr, m);
735 		/*
736 		 * start bulk-out transfer, if not already started:
737 		 */
738 		usbd_transfer_start(sc->sc_xfer[UDBP_T_WR]);
739 		error = 0;
740 	}
741 
742 	mtx_unlock(&sc->sc_mtx);
743 
744 	return (error);
745 }
746 
747 /*
748  * Do local shutdown processing..
749  * We are a persistent device, we refuse to go away, and
750  * only remove our links and reset ourself.
751  */
752 static int
753 ng_udbp_rmnode(node_p node)
754 {
755 	struct udbp_softc *sc = NG_NODE_PRIVATE(node);
756 
757 	/* Let old node go */
758 	NG_NODE_SET_PRIVATE(node, NULL);
759 	NG_NODE_UNREF(node);		/* forget it ever existed */
760 
761 	if (sc == NULL) {
762 		goto done;
763 	}
764 	/* Create Netgraph node */
765 	if (ng_make_node_common(&ng_udbp_typestruct, &sc->sc_node) != 0) {
766 		printf("%s: Could not create Netgraph node\n",
767 		    sc->sc_name);
768 		sc->sc_node = NULL;
769 		goto done;
770 	}
771 	/* Name node */
772 	if (ng_name_node(sc->sc_node, sc->sc_name) != 0) {
773 		printf("%s: Could not name Netgraph node\n",
774 		    sc->sc_name);
775 		NG_NODE_UNREF(sc->sc_node);
776 		sc->sc_node = NULL;
777 		goto done;
778 	}
779 	NG_NODE_SET_PRIVATE(sc->sc_node, sc);
780 
781 done:
782 	if (sc) {
783 		mtx_unlock(&sc->sc_mtx);
784 	}
785 	return (0);
786 }
787 
788 /*
789  * This is called once we've already connected a new hook to the other node.
790  * It gives us a chance to balk at the last minute.
791  */
792 static int
793 ng_udbp_connect(hook_p hook)
794 {
795 	struct udbp_softc *sc = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
796 
797 	/* probably not at splnet, force outward queueing */
798 	NG_HOOK_FORCE_QUEUE(NG_HOOK_PEER(hook));
799 
800 	mtx_lock(&sc->sc_mtx);
801 
802 	sc->sc_flags |= (UDBP_FLAG_READ_STALL |
803 	    UDBP_FLAG_WRITE_STALL);
804 
805 	/* start bulk-in transfer */
806 	usbd_transfer_start(sc->sc_xfer[UDBP_T_RD]);
807 
808 	/* start bulk-out transfer */
809 	usbd_transfer_start(sc->sc_xfer[UDBP_T_WR]);
810 
811 	mtx_unlock(&sc->sc_mtx);
812 
813 	return (0);
814 }
815 
816 /*
817  * Dook disconnection
818  *
819  * For this type, removal of the last link destroys the node
820  */
821 static int
822 ng_udbp_disconnect(hook_p hook)
823 {
824 	struct udbp_softc *sc = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
825 	int error = 0;
826 
827 	if (sc != NULL) {
828 
829 		mtx_lock(&sc->sc_mtx);
830 
831 		if (hook != sc->sc_hook) {
832 			error = EINVAL;
833 		} else {
834 
835 			/* stop bulk-in transfer */
836 			usbd_transfer_stop(sc->sc_xfer[UDBP_T_RD_CS]);
837 			usbd_transfer_stop(sc->sc_xfer[UDBP_T_RD]);
838 
839 			/* stop bulk-out transfer */
840 			usbd_transfer_stop(sc->sc_xfer[UDBP_T_WR_CS]);
841 			usbd_transfer_stop(sc->sc_xfer[UDBP_T_WR]);
842 
843 			/* cleanup queues */
844 			NG_BT_MBUFQ_DRAIN(&sc->sc_xmitq);
845 			NG_BT_MBUFQ_DRAIN(&sc->sc_xmitq_hipri);
846 
847 			if (sc->sc_bulk_in_buffer) {
848 				m_freem(sc->sc_bulk_in_buffer);
849 				sc->sc_bulk_in_buffer = NULL;
850 			}
851 			sc->sc_hook = NULL;
852 		}
853 
854 		mtx_unlock(&sc->sc_mtx);
855 	}
856 	if ((NG_NODE_NUMHOOKS(NG_HOOK_NODE(hook)) == 0)
857 	    && (NG_NODE_IS_VALID(NG_HOOK_NODE(hook))))
858 		ng_rmnode_self(NG_HOOK_NODE(hook));
859 
860 	return (error);
861 }
862