xref: /freebsd/sys/dev/usb/misc/udbp.c (revision 41059135ce931c0f1014a999ffabc6bc470ce856)
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_ANCHOR, USB_PRODUCT_ANCHOR_EZLINK, 0)},
268 	{USB_VPI(USB_VENDOR_GENESYS, USB_PRODUCT_GENESYS_GL620USB, 0)},
269 };
270 
271 DRIVER_MODULE(udbp, uhub, udbp_driver, udbp_devclass, udbp_modload, 0);
272 MODULE_DEPEND(udbp, netgraph, NG_ABI_VERSION, NG_ABI_VERSION, NG_ABI_VERSION);
273 MODULE_DEPEND(udbp, usb, 1, 1, 1);
274 MODULE_VERSION(udbp, 1);
275 USB_PNP_HOST_INFO(udbp_devs);
276 
277 static int
278 udbp_modload(module_t mod, int event, void *data)
279 {
280 	int error;
281 
282 	switch (event) {
283 	case MOD_LOAD:
284 		error = ng_newtype(&ng_udbp_typestruct);
285 		if (error != 0) {
286 			printf("%s: Could not register "
287 			    "Netgraph node type, error=%d\n",
288 			    NG_UDBP_NODE_TYPE, error);
289 		}
290 		break;
291 
292 	case MOD_UNLOAD:
293 		error = ng_rmtype(&ng_udbp_typestruct);
294 		break;
295 
296 	default:
297 		error = EOPNOTSUPP;
298 		break;
299 	}
300 	return (error);
301 }
302 
303 static int
304 udbp_probe(device_t dev)
305 {
306 	struct usb_attach_arg *uaa = device_get_ivars(dev);
307 
308 	if (uaa->usb_mode != USB_MODE_HOST)
309 		return (ENXIO);
310 	if (uaa->info.bConfigIndex != 0)
311 		return (ENXIO);
312 	if (uaa->info.bIfaceIndex != 0)
313 		return (ENXIO);
314 
315 	return (usbd_lookup_id_by_uaa(udbp_devs, sizeof(udbp_devs), uaa));
316 }
317 
318 static int
319 udbp_attach(device_t dev)
320 {
321 	struct usb_attach_arg *uaa = device_get_ivars(dev);
322 	struct udbp_softc *sc = device_get_softc(dev);
323 	int error;
324 
325 	device_set_usb_desc(dev);
326 
327 	snprintf(sc->sc_name, sizeof(sc->sc_name),
328 	    "%s", device_get_nameunit(dev));
329 
330 	mtx_init(&sc->sc_mtx, "udbp lock", NULL, MTX_DEF | MTX_RECURSE);
331 
332 	error = usbd_transfer_setup(uaa->device, &uaa->info.bIfaceIndex,
333 	    sc->sc_xfer, udbp_config, UDBP_T_MAX, sc, &sc->sc_mtx);
334 	if (error) {
335 		DPRINTF("error=%s\n", usbd_errstr(error));
336 		goto detach;
337 	}
338 	NG_BT_MBUFQ_INIT(&sc->sc_xmitq, UDBP_Q_MAXLEN);
339 
340 	NG_BT_MBUFQ_INIT(&sc->sc_xmitq_hipri, UDBP_Q_MAXLEN);
341 
342 	/* create Netgraph node */
343 
344 	if (ng_make_node_common(&ng_udbp_typestruct, &sc->sc_node) != 0) {
345 		printf("%s: Could not create Netgraph node\n",
346 		    sc->sc_name);
347 		sc->sc_node = NULL;
348 		goto detach;
349 	}
350 	/* name node */
351 
352 	if (ng_name_node(sc->sc_node, sc->sc_name) != 0) {
353 		printf("%s: Could not name node\n",
354 		    sc->sc_name);
355 		NG_NODE_UNREF(sc->sc_node);
356 		sc->sc_node = NULL;
357 		goto detach;
358 	}
359 	NG_NODE_SET_PRIVATE(sc->sc_node, sc);
360 
361 	/* the device is now operational */
362 
363 	return (0);			/* success */
364 
365 detach:
366 	udbp_detach(dev);
367 	return (ENOMEM);		/* failure */
368 }
369 
370 static int
371 udbp_detach(device_t dev)
372 {
373 	struct udbp_softc *sc = device_get_softc(dev);
374 
375 	/* destroy Netgraph node */
376 
377 	if (sc->sc_node != NULL) {
378 		NG_NODE_SET_PRIVATE(sc->sc_node, NULL);
379 		ng_rmnode_self(sc->sc_node);
380 		sc->sc_node = NULL;
381 	}
382 	/* free USB transfers, if any */
383 
384 	usbd_transfer_unsetup(sc->sc_xfer, UDBP_T_MAX);
385 
386 	mtx_destroy(&sc->sc_mtx);
387 
388 	/* destroy queues */
389 
390 	NG_BT_MBUFQ_DESTROY(&sc->sc_xmitq);
391 	NG_BT_MBUFQ_DESTROY(&sc->sc_xmitq_hipri);
392 
393 	/* extra check */
394 
395 	if (sc->sc_bulk_in_buffer) {
396 		m_freem(sc->sc_bulk_in_buffer);
397 		sc->sc_bulk_in_buffer = NULL;
398 	}
399 	return (0);			/* success */
400 }
401 
402 static void
403 udbp_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error)
404 {
405 	struct udbp_softc *sc = usbd_xfer_softc(xfer);
406 	struct usb_page_cache *pc;
407 	struct mbuf *m;
408 	int actlen;
409 
410 	usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL);
411 
412 	switch (USB_GET_STATE(xfer)) {
413 	case USB_ST_TRANSFERRED:
414 
415 		/* allocate new mbuf */
416 
417 		MGETHDR(m, M_NOWAIT, MT_DATA);
418 
419 		if (m == NULL) {
420 			goto tr_setup;
421 		}
422 
423 		if (!(MCLGET(m, M_NOWAIT))) {
424 			m_freem(m);
425 			goto tr_setup;
426 		}
427 		m->m_pkthdr.len = m->m_len = actlen;
428 
429 		pc = usbd_xfer_get_frame(xfer, 0);
430 		usbd_copy_out(pc, 0, m->m_data, actlen);
431 
432 		sc->sc_bulk_in_buffer = m;
433 
434 		DPRINTF("received package %d bytes\n", actlen);
435 
436 	case USB_ST_SETUP:
437 tr_setup:
438 		if (sc->sc_bulk_in_buffer) {
439 			ng_send_fn(sc->sc_node, NULL, &udbp_bulk_read_complete, NULL, 0);
440 			return;
441 		}
442 		if (sc->sc_flags & UDBP_FLAG_READ_STALL) {
443 			usbd_transfer_start(sc->sc_xfer[UDBP_T_RD_CS]);
444 			return;
445 		}
446 		usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
447 		usbd_transfer_submit(xfer);
448 		return;
449 
450 	default:			/* Error */
451 		if (error != USB_ERR_CANCELLED) {
452 			/* try to clear stall first */
453 			sc->sc_flags |= UDBP_FLAG_READ_STALL;
454 			usbd_transfer_start(sc->sc_xfer[UDBP_T_RD_CS]);
455 		}
456 		return;
457 
458 	}
459 }
460 
461 static void
462 udbp_bulk_read_clear_stall_callback(struct usb_xfer *xfer, usb_error_t error)
463 {
464 	struct udbp_softc *sc = usbd_xfer_softc(xfer);
465 	struct usb_xfer *xfer_other = sc->sc_xfer[UDBP_T_RD];
466 
467 	if (usbd_clear_stall_callback(xfer, xfer_other)) {
468 		DPRINTF("stall cleared\n");
469 		sc->sc_flags &= ~UDBP_FLAG_READ_STALL;
470 		usbd_transfer_start(xfer_other);
471 	}
472 }
473 
474 static void
475 udbp_bulk_read_complete(node_p node, hook_p hook, void *arg1, int arg2)
476 {
477 	struct udbp_softc *sc = NG_NODE_PRIVATE(node);
478 	struct mbuf *m;
479 	int error;
480 
481 	if (sc == NULL) {
482 		return;
483 	}
484 	mtx_lock(&sc->sc_mtx);
485 
486 	m = sc->sc_bulk_in_buffer;
487 
488 	if (m) {
489 
490 		sc->sc_bulk_in_buffer = NULL;
491 
492 		if ((sc->sc_hook == NULL) ||
493 		    NG_HOOK_NOT_VALID(sc->sc_hook)) {
494 			DPRINTF("No upstream hook\n");
495 			goto done;
496 		}
497 		sc->sc_packets_in++;
498 
499 		NG_SEND_DATA_ONLY(error, sc->sc_hook, m);
500 
501 		m = NULL;
502 	}
503 done:
504 	if (m) {
505 		m_freem(m);
506 	}
507 	/* start USB bulk-in transfer, if not already started */
508 
509 	usbd_transfer_start(sc->sc_xfer[UDBP_T_RD]);
510 
511 	mtx_unlock(&sc->sc_mtx);
512 }
513 
514 static void
515 udbp_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error)
516 {
517 	struct udbp_softc *sc = usbd_xfer_softc(xfer);
518 	struct usb_page_cache *pc;
519 	struct mbuf *m;
520 
521 	switch (USB_GET_STATE(xfer)) {
522 	case USB_ST_TRANSFERRED:
523 
524 		sc->sc_packets_out++;
525 
526 	case USB_ST_SETUP:
527 		if (sc->sc_flags & UDBP_FLAG_WRITE_STALL) {
528 			usbd_transfer_start(sc->sc_xfer[UDBP_T_WR_CS]);
529 			return;
530 		}
531 		/* get next mbuf, if any */
532 
533 		NG_BT_MBUFQ_DEQUEUE(&sc->sc_xmitq_hipri, m);
534 		if (m == NULL) {
535 			NG_BT_MBUFQ_DEQUEUE(&sc->sc_xmitq, m);
536 			if (m == NULL) {
537 				DPRINTF("Data queue is empty\n");
538 				return;
539 			}
540 		}
541 		if (m->m_pkthdr.len > MCLBYTES) {
542 			DPRINTF("truncating large packet "
543 			    "from %d to %d bytes\n", m->m_pkthdr.len,
544 			    MCLBYTES);
545 			m->m_pkthdr.len = MCLBYTES;
546 		}
547 		pc = usbd_xfer_get_frame(xfer, 0);
548 		usbd_m_copy_in(pc, 0, m, 0, m->m_pkthdr.len);
549 
550 		usbd_xfer_set_frame_len(xfer, 0, m->m_pkthdr.len);
551 
552 		DPRINTF("packet out: %d bytes\n", m->m_pkthdr.len);
553 
554 		m_freem(m);
555 
556 		usbd_transfer_submit(xfer);
557 		return;
558 
559 	default:			/* Error */
560 		if (error != USB_ERR_CANCELLED) {
561 			/* try to clear stall first */
562 			sc->sc_flags |= UDBP_FLAG_WRITE_STALL;
563 			usbd_transfer_start(sc->sc_xfer[UDBP_T_WR_CS]);
564 		}
565 		return;
566 
567 	}
568 }
569 
570 static void
571 udbp_bulk_write_clear_stall_callback(struct usb_xfer *xfer, usb_error_t error)
572 {
573 	struct udbp_softc *sc = usbd_xfer_softc(xfer);
574 	struct usb_xfer *xfer_other = sc->sc_xfer[UDBP_T_WR];
575 
576 	if (usbd_clear_stall_callback(xfer, xfer_other)) {
577 		DPRINTF("stall cleared\n");
578 		sc->sc_flags &= ~UDBP_FLAG_WRITE_STALL;
579 		usbd_transfer_start(xfer_other);
580 	}
581 }
582 
583 /***********************************************************************
584  * Start of Netgraph methods
585  **********************************************************************/
586 
587 /*
588  * If this is a device node so this work is done in the attach()
589  * routine and the constructor will return EINVAL as you should not be able
590  * to create nodes that depend on hardware (unless you can add the hardware :)
591  */
592 static int
593 ng_udbp_constructor(node_p node)
594 {
595 	return (EINVAL);
596 }
597 
598 /*
599  * Give our ok for a hook to be added...
600  * If we are not running this might kick a device into life.
601  * Possibly decode information out of the hook name.
602  * Add the hook's private info to the hook structure.
603  * (if we had some). In this example, we assume that there is a
604  * an array of structs, called 'channel' in the private info,
605  * one for each active channel. The private
606  * pointer of each hook points to the appropriate UDBP_hookinfo struct
607  * so that the source of an input packet is easily identified.
608  */
609 static int
610 ng_udbp_newhook(node_p node, hook_p hook, const char *name)
611 {
612 	struct udbp_softc *sc = NG_NODE_PRIVATE(node);
613 	int32_t error = 0;
614 
615 	if (strcmp(name, NG_UDBP_HOOK_NAME)) {
616 		return (EINVAL);
617 	}
618 	mtx_lock(&sc->sc_mtx);
619 
620 	if (sc->sc_hook != NULL) {
621 		error = EISCONN;
622 	} else {
623 		sc->sc_hook = hook;
624 		NG_HOOK_SET_PRIVATE(hook, NULL);
625 	}
626 
627 	mtx_unlock(&sc->sc_mtx);
628 
629 	return (error);
630 }
631 
632 /*
633  * Get a netgraph control message.
634  * Check it is one we understand. If needed, send a response.
635  * We could save the address for an async action later, but don't here.
636  * Always free the message.
637  * The response should be in a malloc'd region that the caller can 'free'.
638  * A response is not required.
639  * Theoretically you could respond defferently to old message types if
640  * the cookie in the header didn't match what we consider to be current
641  * (so that old userland programs could continue to work).
642  */
643 static int
644 ng_udbp_rcvmsg(node_p node, item_p item, hook_p lasthook)
645 {
646 	struct udbp_softc *sc = NG_NODE_PRIVATE(node);
647 	struct ng_mesg *resp = NULL;
648 	int error = 0;
649 	struct ng_mesg *msg;
650 
651 	NGI_GET_MSG(item, msg);
652 	/* Deal with message according to cookie and command */
653 	switch (msg->header.typecookie) {
654 	case NGM_UDBP_COOKIE:
655 		switch (msg->header.cmd) {
656 		case NGM_UDBP_GET_STATUS:
657 			{
658 				struct ngudbpstat *stats;
659 
660 				NG_MKRESPONSE(resp, msg, sizeof(*stats), M_NOWAIT);
661 				if (!resp) {
662 					error = ENOMEM;
663 					break;
664 				}
665 				stats = (struct ngudbpstat *)resp->data;
666 				mtx_lock(&sc->sc_mtx);
667 				stats->packets_in = sc->sc_packets_in;
668 				stats->packets_out = sc->sc_packets_out;
669 				mtx_unlock(&sc->sc_mtx);
670 				break;
671 			}
672 		case NGM_UDBP_SET_FLAG:
673 			if (msg->header.arglen != sizeof(uint32_t)) {
674 				error = EINVAL;
675 				break;
676 			}
677 			DPRINTF("flags = 0x%08x\n",
678 			    *((uint32_t *)msg->data));
679 			break;
680 		default:
681 			error = EINVAL;	/* unknown command */
682 			break;
683 		}
684 		break;
685 	default:
686 		error = EINVAL;		/* unknown cookie type */
687 		break;
688 	}
689 
690 	/* Take care of synchronous response, if any */
691 	NG_RESPOND_MSG(error, node, item, resp);
692 	NG_FREE_MSG(msg);
693 	return (error);
694 }
695 
696 /*
697  * Accept data from the hook and queue it for output.
698  */
699 static int
700 ng_udbp_rcvdata(hook_p hook, item_p item)
701 {
702 	struct udbp_softc *sc = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
703 	struct ng_bt_mbufq *queue_ptr;
704 	struct mbuf *m;
705 	struct ng_tag_prio *ptag;
706 	int error;
707 
708 	if (sc == NULL) {
709 		NG_FREE_ITEM(item);
710 		return (EHOSTDOWN);
711 	}
712 	NGI_GET_M(item, m);
713 	NG_FREE_ITEM(item);
714 
715 	/*
716 	 * Now queue the data for when it can be sent
717 	 */
718 	ptag = (void *)m_tag_locate(m, NGM_GENERIC_COOKIE,
719 	    NG_TAG_PRIO, NULL);
720 
721 	if (ptag && (ptag->priority > NG_PRIO_CUTOFF))
722 		queue_ptr = &sc->sc_xmitq_hipri;
723 	else
724 		queue_ptr = &sc->sc_xmitq;
725 
726 	mtx_lock(&sc->sc_mtx);
727 
728 	if (NG_BT_MBUFQ_FULL(queue_ptr)) {
729 		NG_BT_MBUFQ_DROP(queue_ptr);
730 		NG_FREE_M(m);
731 		error = ENOBUFS;
732 	} else {
733 		NG_BT_MBUFQ_ENQUEUE(queue_ptr, m);
734 		/*
735 		 * start bulk-out transfer, if not already started:
736 		 */
737 		usbd_transfer_start(sc->sc_xfer[UDBP_T_WR]);
738 		error = 0;
739 	}
740 
741 	mtx_unlock(&sc->sc_mtx);
742 
743 	return (error);
744 }
745 
746 /*
747  * Do local shutdown processing..
748  * We are a persistent device, we refuse to go away, and
749  * only remove our links and reset ourself.
750  */
751 static int
752 ng_udbp_rmnode(node_p node)
753 {
754 	struct udbp_softc *sc = NG_NODE_PRIVATE(node);
755 
756 	/* Let old node go */
757 	NG_NODE_SET_PRIVATE(node, NULL);
758 	NG_NODE_UNREF(node);		/* forget it ever existed */
759 
760 	if (sc == NULL) {
761 		goto done;
762 	}
763 	/* Create Netgraph node */
764 	if (ng_make_node_common(&ng_udbp_typestruct, &sc->sc_node) != 0) {
765 		printf("%s: Could not create Netgraph node\n",
766 		    sc->sc_name);
767 		sc->sc_node = NULL;
768 		goto done;
769 	}
770 	/* Name node */
771 	if (ng_name_node(sc->sc_node, sc->sc_name) != 0) {
772 		printf("%s: Could not name Netgraph node\n",
773 		    sc->sc_name);
774 		NG_NODE_UNREF(sc->sc_node);
775 		sc->sc_node = NULL;
776 		goto done;
777 	}
778 	NG_NODE_SET_PRIVATE(sc->sc_node, sc);
779 
780 done:
781 	if (sc) {
782 		mtx_unlock(&sc->sc_mtx);
783 	}
784 	return (0);
785 }
786 
787 /*
788  * This is called once we've already connected a new hook to the other node.
789  * It gives us a chance to balk at the last minute.
790  */
791 static int
792 ng_udbp_connect(hook_p hook)
793 {
794 	struct udbp_softc *sc = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
795 
796 	/* probably not at splnet, force outward queueing */
797 	NG_HOOK_FORCE_QUEUE(NG_HOOK_PEER(hook));
798 
799 	mtx_lock(&sc->sc_mtx);
800 
801 	sc->sc_flags |= (UDBP_FLAG_READ_STALL |
802 	    UDBP_FLAG_WRITE_STALL);
803 
804 	/* start bulk-in transfer */
805 	usbd_transfer_start(sc->sc_xfer[UDBP_T_RD]);
806 
807 	/* start bulk-out transfer */
808 	usbd_transfer_start(sc->sc_xfer[UDBP_T_WR]);
809 
810 	mtx_unlock(&sc->sc_mtx);
811 
812 	return (0);
813 }
814 
815 /*
816  * Dook disconnection
817  *
818  * For this type, removal of the last link destroys the node
819  */
820 static int
821 ng_udbp_disconnect(hook_p hook)
822 {
823 	struct udbp_softc *sc = NG_NODE_PRIVATE(NG_HOOK_NODE(hook));
824 	int error = 0;
825 
826 	if (sc != NULL) {
827 
828 		mtx_lock(&sc->sc_mtx);
829 
830 		if (hook != sc->sc_hook) {
831 			error = EINVAL;
832 		} else {
833 
834 			/* stop bulk-in transfer */
835 			usbd_transfer_stop(sc->sc_xfer[UDBP_T_RD_CS]);
836 			usbd_transfer_stop(sc->sc_xfer[UDBP_T_RD]);
837 
838 			/* stop bulk-out transfer */
839 			usbd_transfer_stop(sc->sc_xfer[UDBP_T_WR_CS]);
840 			usbd_transfer_stop(sc->sc_xfer[UDBP_T_WR]);
841 
842 			/* cleanup queues */
843 			NG_BT_MBUFQ_DRAIN(&sc->sc_xmitq);
844 			NG_BT_MBUFQ_DRAIN(&sc->sc_xmitq_hipri);
845 
846 			if (sc->sc_bulk_in_buffer) {
847 				m_freem(sc->sc_bulk_in_buffer);
848 				sc->sc_bulk_in_buffer = NULL;
849 			}
850 			sc->sc_hook = NULL;
851 		}
852 
853 		mtx_unlock(&sc->sc_mtx);
854 	}
855 	if ((NG_NODE_NUMHOOKS(NG_HOOK_NODE(hook)) == 0)
856 	    && (NG_NODE_IS_VALID(NG_HOOK_NODE(hook))))
857 		ng_rmnode_self(NG_HOOK_NODE(hook));
858 
859 	return (error);
860 }
861