xref: /freebsd/sys/dev/usb/net/if_cdce.c (revision ec0ea6efa1ad229d75c394c1a9b9cac33af2b1d3)
1 /*	$NetBSD: if_cdce.c,v 1.4 2004/10/24 12:50:54 augustss Exp $ */
2 
3 /*-
4  * SPDX-License-Identifier: BSD-4-Clause
5  *
6  * Copyright (c) 1997, 1998, 1999, 2000-2003 Bill Paul <wpaul@windriver.com>
7  * Copyright (c) 2003-2005 Craig Boston
8  * Copyright (c) 2004 Daniel Hartmeier
9  * Copyright (c) 2009 Hans Petter Selasky
10  * All rights reserved.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. All advertising materials mentioning features or use of this software
21  *    must display the following acknowledgement:
22  *	This product includes software developed by Bill Paul.
23  * 4. Neither the name of the author nor the names of any co-contributors
24  *    may be used to endorse or promote products derived from this software
25  *    without specific prior written permission.
26  *
27  * THIS SOFTWARE IS PROVIDED BY Bill Paul AND CONTRIBUTORS ``AS IS'' AND
28  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30  * ARE DISCLAIMED.  IN NO EVENT SHALL Bill Paul, THE VOICES IN HIS HEAD OR
31  * THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
32  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
33  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
34  * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
35  * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
36  * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
37  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38  */
39 
40 /*
41  * USB Communication Device Class (Ethernet Networking Control Model)
42  * http://www.usb.org/developers/devclass_docs/usbcdc11.pdf
43  */
44 
45 /*
46  * USB Network Control Model (NCM)
47  * http://www.usb.org/developers/devclass_docs/NCM10.zip
48  */
49 
50 #include <sys/cdefs.h>
51 __FBSDID("$FreeBSD$");
52 
53 #include <sys/gsb_crc32.h>
54 #include <sys/eventhandler.h>
55 #include <sys/stdint.h>
56 #include <sys/stddef.h>
57 #include <sys/queue.h>
58 #include <sys/systm.h>
59 #include <sys/socket.h>
60 #include <sys/kernel.h>
61 #include <sys/bus.h>
62 #include <sys/module.h>
63 #include <sys/lock.h>
64 #include <sys/mutex.h>
65 #include <sys/condvar.h>
66 #include <sys/sysctl.h>
67 #include <sys/sx.h>
68 #include <sys/unistd.h>
69 #include <sys/callout.h>
70 #include <sys/malloc.h>
71 #include <sys/priv.h>
72 
73 #include <net/if.h>
74 #include <net/if_var.h>
75 
76 #include <dev/usb/usb.h>
77 #include <dev/usb/usbdi.h>
78 #include <dev/usb/usbdi_util.h>
79 #include <dev/usb/usb_cdc.h>
80 #include "usbdevs.h"
81 
82 #define	USB_DEBUG_VAR cdce_debug
83 #include <dev/usb/usb_debug.h>
84 #include <dev/usb/usb_process.h>
85 #include <dev/usb/usb_msctest.h>
86 #include "usb_if.h"
87 
88 #include <dev/usb/net/usb_ethernet.h>
89 #include <dev/usb/net/if_cdcereg.h>
90 
91 static device_probe_t cdce_probe;
92 static device_attach_t cdce_attach;
93 static device_detach_t cdce_detach;
94 static device_suspend_t cdce_suspend;
95 static device_resume_t cdce_resume;
96 static usb_handle_request_t cdce_handle_request;
97 
98 static usb_callback_t cdce_bulk_write_callback;
99 static usb_callback_t cdce_bulk_read_callback;
100 static usb_callback_t cdce_intr_read_callback;
101 static usb_callback_t cdce_intr_write_callback;
102 
103 #if CDCE_HAVE_NCM
104 static usb_callback_t cdce_ncm_bulk_write_callback;
105 static usb_callback_t cdce_ncm_bulk_read_callback;
106 #endif
107 
108 static uether_fn_t cdce_attach_post;
109 static uether_fn_t cdce_init;
110 static uether_fn_t cdce_stop;
111 static uether_fn_t cdce_start;
112 static uether_fn_t cdce_setmulti;
113 static uether_fn_t cdce_setpromisc;
114 static int cdce_attach_post_sub(struct usb_ether *);
115 static int cdce_ioctl(struct ifnet *, u_long, caddr_t);
116 static int cdce_media_change_cb(struct ifnet *);
117 static void cdce_media_status_cb(struct ifnet *, struct ifmediareq *);
118 
119 static uint32_t	cdce_m_crc32(struct mbuf *, uint32_t, uint32_t);
120 static void	cdce_set_filter(struct usb_ether *);
121 
122 #ifdef USB_DEBUG
123 static int cdce_debug = 0;
124 static int cdce_tx_interval = 0;
125 
126 static SYSCTL_NODE(_hw_usb, OID_AUTO, cdce, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
127     "USB CDC-Ethernet");
128 SYSCTL_INT(_hw_usb_cdce, OID_AUTO, debug, CTLFLAG_RWTUN, &cdce_debug, 0,
129     "Debug level");
130 SYSCTL_INT(_hw_usb_cdce, OID_AUTO, interval, CTLFLAG_RWTUN, &cdce_tx_interval, 0,
131     "NCM transmit interval in ms");
132 #else
133 #define cdce_debug 0
134 #endif
135 
136 static const struct usb_config cdce_config[CDCE_N_TRANSFER] = {
137 	[CDCE_BULK_RX] = {
138 		.type = UE_BULK,
139 		.endpoint = UE_ADDR_ANY,
140 		.direction = UE_DIR_RX,
141 		.if_index = 0,
142 		.frames = CDCE_FRAMES_MAX,
143 		.bufsize = (CDCE_FRAMES_MAX * MCLBYTES),
144 		.flags = {.pipe_bof = 1,.short_frames_ok = 1,.short_xfer_ok = 1,.ext_buffer = 1,},
145 		.callback = cdce_bulk_read_callback,
146 		.timeout = 0,	/* no timeout */
147 		.usb_mode = USB_MODE_DUAL,	/* both modes */
148 	},
149 
150 	[CDCE_BULK_TX] = {
151 		.type = UE_BULK,
152 		.endpoint = UE_ADDR_ANY,
153 		.direction = UE_DIR_TX,
154 		.if_index = 0,
155 		.frames = CDCE_FRAMES_MAX,
156 		.bufsize = (CDCE_FRAMES_MAX * MCLBYTES),
157 		.flags = {.pipe_bof = 1,.force_short_xfer = 1,.ext_buffer = 1,},
158 		.callback = cdce_bulk_write_callback,
159 		.timeout = 10000,	/* 10 seconds */
160 		.usb_mode = USB_MODE_DUAL,	/* both modes */
161 	},
162 
163 	[CDCE_INTR_RX] = {
164 		.type = UE_INTERRUPT,
165 		.endpoint = UE_ADDR_ANY,
166 		.direction = UE_DIR_RX,
167 		.if_index = 1,
168 		.bufsize = CDCE_IND_SIZE_MAX,
169 		.flags = {.pipe_bof = 1,.short_xfer_ok = 1,.no_pipe_ok = 1,},
170 		.callback = cdce_intr_read_callback,
171 		.timeout = 0,
172 		.usb_mode = USB_MODE_HOST,
173 	},
174 
175 	[CDCE_INTR_TX] = {
176 		.type = UE_INTERRUPT,
177 		.endpoint = UE_ADDR_ANY,
178 		.direction = UE_DIR_TX,
179 		.if_index = 1,
180 		.bufsize = CDCE_IND_SIZE_MAX,
181 		.flags = {.pipe_bof = 1,.force_short_xfer = 1,.no_pipe_ok = 1,},
182 		.callback = cdce_intr_write_callback,
183 		.timeout = 10000,	/* 10 seconds */
184 		.usb_mode = USB_MODE_DEVICE,
185 	},
186 };
187 
188 #if CDCE_HAVE_NCM
189 static const struct usb_config cdce_ncm_config[CDCE_N_TRANSFER] = {
190 	[CDCE_BULK_RX] = {
191 		.type = UE_BULK,
192 		.endpoint = UE_ADDR_ANY,
193 		.direction = UE_DIR_RX,
194 		.if_index = 0,
195 		.frames = CDCE_NCM_RX_FRAMES_MAX,
196 		.bufsize = (CDCE_NCM_RX_FRAMES_MAX * CDCE_NCM_RX_MAXLEN),
197 		.flags = {.pipe_bof = 1,.short_frames_ok = 1,.short_xfer_ok = 1,},
198 		.callback = cdce_ncm_bulk_read_callback,
199 		.timeout = 0,	/* no timeout */
200 		.usb_mode = USB_MODE_DUAL,	/* both modes */
201 	},
202 
203 	[CDCE_BULK_TX] = {
204 		.type = UE_BULK,
205 		.endpoint = UE_ADDR_ANY,
206 		.direction = UE_DIR_TX,
207 		.if_index = 0,
208 		.frames = CDCE_NCM_TX_FRAMES_MAX,
209 		.bufsize = (CDCE_NCM_TX_FRAMES_MAX * CDCE_NCM_TX_MAXLEN),
210 		.flags = {.pipe_bof = 1,},
211 		.callback = cdce_ncm_bulk_write_callback,
212 		.timeout = 10000,	/* 10 seconds */
213 		.usb_mode = USB_MODE_DUAL,	/* both modes */
214 	},
215 
216 	[CDCE_INTR_RX] = {
217 		.type = UE_INTERRUPT,
218 		.endpoint = UE_ADDR_ANY,
219 		.direction = UE_DIR_RX,
220 		.if_index = 1,
221 		.bufsize = CDCE_IND_SIZE_MAX,
222 		.flags = {.pipe_bof = 1,.short_xfer_ok = 1,.no_pipe_ok = 1,},
223 		.callback = cdce_intr_read_callback,
224 		.timeout = 0,
225 		.usb_mode = USB_MODE_HOST,
226 	},
227 
228 	[CDCE_INTR_TX] = {
229 		.type = UE_INTERRUPT,
230 		.endpoint = UE_ADDR_ANY,
231 		.direction = UE_DIR_TX,
232 		.if_index = 1,
233 		.bufsize = CDCE_IND_SIZE_MAX,
234 		.flags = {.pipe_bof = 1,.force_short_xfer = 1,.no_pipe_ok = 1,},
235 		.callback = cdce_intr_write_callback,
236 		.timeout = 10000,	/* 10 seconds */
237 		.usb_mode = USB_MODE_DEVICE,
238 	},
239 };
240 #endif
241 
242 static device_method_t cdce_methods[] = {
243 	/* USB interface */
244 	DEVMETHOD(usb_handle_request, cdce_handle_request),
245 
246 	/* Device interface */
247 	DEVMETHOD(device_probe, cdce_probe),
248 	DEVMETHOD(device_attach, cdce_attach),
249 	DEVMETHOD(device_detach, cdce_detach),
250 	DEVMETHOD(device_suspend, cdce_suspend),
251 	DEVMETHOD(device_resume, cdce_resume),
252 
253 	DEVMETHOD_END
254 };
255 
256 static driver_t cdce_driver = {
257 	.name = "cdce",
258 	.methods = cdce_methods,
259 	.size = sizeof(struct cdce_softc),
260 };
261 
262 static devclass_t cdce_devclass;
263 static eventhandler_tag cdce_etag;
264 
265 static int  cdce_driver_loaded(struct module *, int, void *);
266 
267 static const STRUCT_USB_HOST_ID cdce_switch_devs[] = {
268 	{USB_VPI(USB_VENDOR_HUAWEI, USB_PRODUCT_HUAWEI_E3272_INIT, MSC_EJECT_HUAWEI2)},
269 };
270 
271 static const STRUCT_USB_HOST_ID cdce_host_devs[] = {
272 	{USB_VPI(USB_VENDOR_ACERLABS, USB_PRODUCT_ACERLABS_M5632, CDCE_FLAG_NO_UNION)},
273 	{USB_VPI(USB_VENDOR_AMBIT, USB_PRODUCT_AMBIT_NTL_250, CDCE_FLAG_NO_UNION)},
274 	{USB_VPI(USB_VENDOR_COMPAQ, USB_PRODUCT_COMPAQ_IPAQLINUX, CDCE_FLAG_NO_UNION)},
275 	{USB_VPI(USB_VENDOR_GMATE, USB_PRODUCT_GMATE_YP3X00, CDCE_FLAG_NO_UNION)},
276 	{USB_VPI(USB_VENDOR_MOTOROLA2, USB_PRODUCT_MOTOROLA2_USBLAN, CDCE_FLAG_ZAURUS | CDCE_FLAG_NO_UNION)},
277 	{USB_VPI(USB_VENDOR_MOTOROLA2, USB_PRODUCT_MOTOROLA2_USBLAN2, CDCE_FLAG_ZAURUS | CDCE_FLAG_NO_UNION)},
278 	{USB_VPI(USB_VENDOR_PROLIFIC, USB_PRODUCT_PROLIFIC_PL2501, CDCE_FLAG_NO_UNION)},
279 	{USB_VPI(USB_VENDOR_SHARP, USB_PRODUCT_SHARP_SL5500, CDCE_FLAG_ZAURUS)},
280 	{USB_VPI(USB_VENDOR_SHARP, USB_PRODUCT_SHARP_SL5600, CDCE_FLAG_ZAURUS | CDCE_FLAG_NO_UNION)},
281 	{USB_VPI(USB_VENDOR_SHARP, USB_PRODUCT_SHARP_SLA300, CDCE_FLAG_ZAURUS | CDCE_FLAG_NO_UNION)},
282 	{USB_VPI(USB_VENDOR_SHARP, USB_PRODUCT_SHARP_SLC700, CDCE_FLAG_ZAURUS | CDCE_FLAG_NO_UNION)},
283 	{USB_VPI(USB_VENDOR_SHARP, USB_PRODUCT_SHARP_SLC750, CDCE_FLAG_ZAURUS | CDCE_FLAG_NO_UNION)},
284 	{USB_VPI(USB_VENDOR_REALTEK, USB_PRODUCT_REALTEK_RTL8156, 0)},
285 
286 	{USB_VENDOR(USB_VENDOR_HUAWEI), USB_IFACE_CLASS(UICLASS_VENDOR),
287 		USB_IFACE_SUBCLASS(0x02), USB_IFACE_PROTOCOL(0x16),
288 		USB_DRIVER_INFO(0)},
289 	{USB_VENDOR(USB_VENDOR_HUAWEI), USB_IFACE_CLASS(UICLASS_VENDOR),
290 		USB_IFACE_SUBCLASS(0x02), USB_IFACE_PROTOCOL(0x46),
291 		USB_DRIVER_INFO(0)},
292 	{USB_VENDOR(USB_VENDOR_HUAWEI), USB_IFACE_CLASS(UICLASS_VENDOR),
293 		USB_IFACE_SUBCLASS(0x02), USB_IFACE_PROTOCOL(0x76),
294 		USB_DRIVER_INFO(0)},
295 	{USB_VENDOR(USB_VENDOR_HUAWEI), USB_IFACE_CLASS(UICLASS_VENDOR),
296 		USB_IFACE_SUBCLASS(0x03), USB_IFACE_PROTOCOL(0x16),
297 		USB_DRIVER_INFO(0)},
298 };
299 
300 static const STRUCT_USB_DUAL_ID cdce_dual_devs[] = {
301 	{USB_IF_CSI(UICLASS_CDC, UISUBCLASS_ETHERNET_NETWORKING_CONTROL_MODEL, 0)},
302 	{USB_IF_CSI(UICLASS_CDC, UISUBCLASS_MOBILE_DIRECT_LINE_MODEL, 0)},
303 	{USB_IF_CSI(UICLASS_CDC, UISUBCLASS_NETWORK_CONTROL_MODEL, 0)},
304 };
305 
306 DRIVER_MODULE(cdce, uhub, cdce_driver, cdce_devclass, cdce_driver_loaded, 0);
307 MODULE_VERSION(cdce, 1);
308 MODULE_DEPEND(cdce, uether, 1, 1, 1);
309 MODULE_DEPEND(cdce, usb, 1, 1, 1);
310 MODULE_DEPEND(cdce, ether, 1, 1, 1);
311 USB_PNP_DEVICE_INFO(cdce_switch_devs);
312 USB_PNP_HOST_INFO(cdce_host_devs);
313 USB_PNP_DUAL_INFO(cdce_dual_devs);
314 
315 static const struct usb_ether_methods cdce_ue_methods = {
316 	.ue_attach_post = cdce_attach_post,
317 	.ue_attach_post_sub = cdce_attach_post_sub,
318 	.ue_start = cdce_start,
319 	.ue_init = cdce_init,
320 	.ue_stop = cdce_stop,
321 	.ue_setmulti = cdce_setmulti,
322 	.ue_setpromisc = cdce_setpromisc,
323 };
324 
325 #if CDCE_HAVE_NCM
326 /*------------------------------------------------------------------------*
327  *	cdce_ncm_init
328  *
329  * Return values:
330  * 0: Success
331  * Else: Failure
332  *------------------------------------------------------------------------*/
333 static uint8_t
334 cdce_ncm_init(struct cdce_softc *sc)
335 {
336 	struct usb_ncm_parameters temp;
337 	struct usb_device_request req;
338 	struct usb_ncm_func_descriptor *ufd;
339 	uint8_t value[8];
340 	int err;
341 
342 	ufd = usbd_find_descriptor(sc->sc_ue.ue_udev, NULL,
343 	    sc->sc_ifaces_index[1], UDESC_CS_INTERFACE, 0xFF,
344 	    UCDC_NCM_FUNC_DESC_SUBTYPE, 0xFF);
345 
346 	/* verify length of NCM functional descriptor */
347 	if (ufd != NULL) {
348 		if (ufd->bLength < sizeof(*ufd))
349 			ufd = NULL;
350 		else
351 			DPRINTFN(1, "Found NCM functional descriptor.\n");
352 	}
353 
354 	req.bmRequestType = UT_READ_CLASS_INTERFACE;
355 	req.bRequest = UCDC_NCM_GET_NTB_PARAMETERS;
356 	USETW(req.wValue, 0);
357 	req.wIndex[0] = sc->sc_ifaces_index[1];
358 	req.wIndex[1] = 0;
359 	USETW(req.wLength, sizeof(temp));
360 
361 	err = usbd_do_request_flags(sc->sc_ue.ue_udev, NULL, &req,
362 	    &temp, 0, NULL, 1000 /* ms */);
363 	if (err)
364 		return (1);
365 
366 	/* Read correct set of parameters according to device mode */
367 
368 	if (usbd_get_mode(sc->sc_ue.ue_udev) == USB_MODE_HOST) {
369 		sc->sc_ncm.rx_max = UGETDW(temp.dwNtbInMaxSize);
370 		sc->sc_ncm.tx_max = UGETDW(temp.dwNtbOutMaxSize);
371 		sc->sc_ncm.tx_remainder = UGETW(temp.wNdpOutPayloadRemainder);
372 		sc->sc_ncm.tx_modulus = UGETW(temp.wNdpOutDivisor);
373 		sc->sc_ncm.tx_struct_align = UGETW(temp.wNdpOutAlignment);
374 		sc->sc_ncm.tx_nframe = UGETW(temp.wNtbOutMaxDatagrams);
375 	} else {
376 		sc->sc_ncm.rx_max = UGETDW(temp.dwNtbOutMaxSize);
377 		sc->sc_ncm.tx_max = UGETDW(temp.dwNtbInMaxSize);
378 		sc->sc_ncm.tx_remainder = UGETW(temp.wNdpInPayloadRemainder);
379 		sc->sc_ncm.tx_modulus = UGETW(temp.wNdpInDivisor);
380 		sc->sc_ncm.tx_struct_align = UGETW(temp.wNdpInAlignment);
381 		sc->sc_ncm.tx_nframe = UGETW(temp.wNtbOutMaxDatagrams);
382 	}
383 
384 	/* Verify maximum receive length */
385 
386 	if ((sc->sc_ncm.rx_max < 32) ||
387 	    (sc->sc_ncm.rx_max > CDCE_NCM_RX_MAXLEN)) {
388 		DPRINTFN(1, "Using default maximum receive length\n");
389 		sc->sc_ncm.rx_max = CDCE_NCM_RX_MAXLEN;
390 	}
391 
392 	/* Verify maximum transmit length */
393 
394 	if ((sc->sc_ncm.tx_max < 32) ||
395 	    (sc->sc_ncm.tx_max > CDCE_NCM_TX_MAXLEN)) {
396 		DPRINTFN(1, "Using default maximum transmit length\n");
397 		sc->sc_ncm.tx_max = CDCE_NCM_TX_MAXLEN;
398 	}
399 
400 	/*
401 	 * Verify that the structure alignment is:
402 	 * - power of two
403 	 * - not greater than the maximum transmit length
404 	 * - not less than four bytes
405 	 */
406 	if ((sc->sc_ncm.tx_struct_align < 4) ||
407 	    (sc->sc_ncm.tx_struct_align !=
408 	     ((-sc->sc_ncm.tx_struct_align) & sc->sc_ncm.tx_struct_align)) ||
409 	    (sc->sc_ncm.tx_struct_align >= sc->sc_ncm.tx_max)) {
410 		DPRINTFN(1, "Using default other alignment: 4 bytes\n");
411 		sc->sc_ncm.tx_struct_align = 4;
412 	}
413 
414 	/*
415 	 * Verify that the payload alignment is:
416 	 * - power of two
417 	 * - not greater than the maximum transmit length
418 	 * - not less than four bytes
419 	 */
420 	if ((sc->sc_ncm.tx_modulus < 4) ||
421 	    (sc->sc_ncm.tx_modulus !=
422 	     ((-sc->sc_ncm.tx_modulus) & sc->sc_ncm.tx_modulus)) ||
423 	    (sc->sc_ncm.tx_modulus >= sc->sc_ncm.tx_max)) {
424 		DPRINTFN(1, "Using default transmit modulus: 4 bytes\n");
425 		sc->sc_ncm.tx_modulus = 4;
426 	}
427 
428 	/* Verify that the payload remainder */
429 
430 	if ((sc->sc_ncm.tx_remainder >= sc->sc_ncm.tx_modulus)) {
431 		DPRINTFN(1, "Using default transmit remainder: 0 bytes\n");
432 		sc->sc_ncm.tx_remainder = 0;
433 	}
434 
435 	/*
436 	 * Offset the TX remainder so that IP packet payload starts at
437 	 * the tx_modulus. This is not too clear in the specification.
438 	 */
439 
440 	sc->sc_ncm.tx_remainder =
441 	    (sc->sc_ncm.tx_remainder - ETHER_HDR_LEN) &
442 	    (sc->sc_ncm.tx_modulus - 1);
443 
444 	/* Verify max datagrams */
445 
446 	if (sc->sc_ncm.tx_nframe == 0 ||
447 	    sc->sc_ncm.tx_nframe > (CDCE_NCM_SUBFRAMES_MAX - 1)) {
448 		DPRINTFN(1, "Using default max "
449 		    "subframes: %u units\n", CDCE_NCM_SUBFRAMES_MAX - 1);
450 		/* need to reserve one entry for zero padding */
451 		sc->sc_ncm.tx_nframe = (CDCE_NCM_SUBFRAMES_MAX - 1);
452 	}
453 
454 	/* Additional configuration, will fail in device side mode, which is OK. */
455 
456 	req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
457 	req.bRequest = UCDC_NCM_SET_NTB_INPUT_SIZE;
458 	USETW(req.wValue, 0);
459 	req.wIndex[0] = sc->sc_ifaces_index[1];
460 	req.wIndex[1] = 0;
461 
462 	if (ufd != NULL &&
463 	    (ufd->bmNetworkCapabilities & UCDC_NCM_CAP_MAX_DGRAM)) {
464 		USETW(req.wLength, 8);
465 		USETDW(value, sc->sc_ncm.rx_max);
466 		USETW(value + 4, (CDCE_NCM_SUBFRAMES_MAX - 1));
467 		USETW(value + 6, 0);
468 	} else {
469 		USETW(req.wLength, 4);
470 		USETDW(value, sc->sc_ncm.rx_max);
471  	}
472 
473 	err = usbd_do_request_flags(sc->sc_ue.ue_udev, NULL, &req,
474 	    &value, 0, NULL, 1000 /* ms */);
475 	if (err) {
476 		DPRINTFN(1, "Setting input size "
477 		    "to %u failed.\n", sc->sc_ncm.rx_max);
478 	}
479 
480 	req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
481 	req.bRequest = UCDC_NCM_SET_CRC_MODE;
482 	USETW(req.wValue, 0);	/* no CRC */
483 	req.wIndex[0] = sc->sc_ifaces_index[1];
484 	req.wIndex[1] = 0;
485 	USETW(req.wLength, 0);
486 
487 	err = usbd_do_request_flags(sc->sc_ue.ue_udev, NULL, &req,
488 	    NULL, 0, NULL, 1000 /* ms */);
489 	if (err) {
490 		DPRINTFN(1, "Setting CRC mode to off failed.\n");
491 	}
492 
493 	req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
494 	req.bRequest = UCDC_NCM_SET_NTB_FORMAT;
495 	USETW(req.wValue, 0);	/* NTB-16 */
496 	req.wIndex[0] = sc->sc_ifaces_index[1];
497 	req.wIndex[1] = 0;
498 	USETW(req.wLength, 0);
499 
500 	err = usbd_do_request_flags(sc->sc_ue.ue_udev, NULL, &req,
501 	    NULL, 0, NULL, 1000 /* ms */);
502 	if (err) {
503 		DPRINTFN(1, "Setting NTB format to 16-bit failed.\n");
504 	}
505 
506 	return (0);		/* success */
507 }
508 #endif
509 
510 static void
511 cdce_test_autoinst(void *arg, struct usb_device *udev,
512     struct usb_attach_arg *uaa)
513 {
514 	struct usb_interface *iface;
515 	struct usb_interface_descriptor *id;
516 
517 	if (uaa->dev_state != UAA_DEV_READY)
518 		return;
519 
520 	iface = usbd_get_iface(udev, 0);
521 	if (iface == NULL)
522 		return;
523 	id = iface->idesc;
524 	if (id == NULL || id->bInterfaceClass != UICLASS_MASS)
525 		return;
526 	if (usbd_lookup_id_by_uaa(cdce_switch_devs, sizeof(cdce_switch_devs), uaa))
527 		return;		/* no device match */
528 
529 	if (usb_msc_eject(udev, 0, USB_GET_DRIVER_INFO(uaa)) == 0) {
530 		/* success, mark the udev as disappearing */
531 		uaa->dev_state = UAA_DEV_EJECTING;
532 	}
533 }
534 
535 static int
536 cdce_driver_loaded(struct module *mod, int what, void *arg)
537 {
538 	switch (what) {
539 	case MOD_LOAD:
540 		/* register our autoinstall handler */
541 		cdce_etag = EVENTHANDLER_REGISTER(usb_dev_configured,
542 		    cdce_test_autoinst, NULL, EVENTHANDLER_PRI_ANY);
543 		return (0);
544 	case MOD_UNLOAD:
545 		EVENTHANDLER_DEREGISTER(usb_dev_configured, cdce_etag);
546 		return (0);
547 	default:
548 		return (EOPNOTSUPP);
549 	}
550 }
551 
552 static int
553 cdce_probe(device_t dev)
554 {
555 	struct usb_attach_arg *uaa = device_get_ivars(dev);
556 	int error;
557 
558 	error = usbd_lookup_id_by_uaa(cdce_host_devs, sizeof(cdce_host_devs), uaa);
559 	if (error)
560 		error = usbd_lookup_id_by_uaa(cdce_dual_devs, sizeof(cdce_dual_devs), uaa);
561 	return (error);
562 }
563 
564 static void
565 cdce_attach_post(struct usb_ether *ue)
566 {
567 	/* no-op */
568 	return;
569 }
570 
571 static int
572 cdce_attach_post_sub(struct usb_ether *ue)
573 {
574 	struct cdce_softc *sc = uether_getsc(ue);
575 	struct ifnet *ifp = uether_getifp(ue);
576 
577 	/* mostly copied from usb_ethernet.c */
578 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
579 	ifp->if_start = uether_start;
580 	ifp->if_ioctl = cdce_ioctl;
581 	ifp->if_init = uether_init;
582 	IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen);
583 	ifp->if_snd.ifq_drv_maxlen = ifqmaxlen;
584 	IFQ_SET_READY(&ifp->if_snd);
585 
586 	if ((sc->sc_flags & CDCE_FLAG_VLAN) == CDCE_FLAG_VLAN)
587 		if_setcapabilitiesbit(ifp, IFCAP_VLAN_MTU, 0);
588 
589 	if_setcapabilitiesbit(ifp, IFCAP_LINKSTATE, 0);
590 	if_setcapenable(ifp, if_getcapabilities(ifp));
591 
592 	ifmedia_init(&sc->sc_media, IFM_IMASK, cdce_media_change_cb,
593 	    cdce_media_status_cb);
594 	ifmedia_add(&sc->sc_media, IFM_ETHER | IFM_AUTO, 0, NULL);
595 	ifmedia_set(&sc->sc_media, IFM_ETHER | IFM_AUTO);
596 	sc->sc_media.ifm_media = sc->sc_media.ifm_cur->ifm_media;
597 	CDCE_LOCK(sc);
598 	cdce_set_filter(ue);
599 	CDCE_UNLOCK(sc);
600 
601 	return 0;
602 }
603 
604 static int
605 cdce_attach(device_t dev)
606 {
607 	struct cdce_softc *sc = device_get_softc(dev);
608 	struct usb_ether *ue = &sc->sc_ue;
609 	struct usb_attach_arg *uaa = device_get_ivars(dev);
610 	struct usb_interface *iface;
611 	const struct usb_cdc_union_descriptor *ud;
612 	const struct usb_interface_descriptor *id;
613 	const struct usb_cdc_ethernet_descriptor *ued;
614 	const struct usb_config *pcfg;
615 	uint32_t seed;
616 	int error;
617 	uint8_t i;
618 	uint8_t data_iface_no;
619 	char eaddr_str[5 * ETHER_ADDR_LEN];	/* approx */
620 
621 	sc->sc_flags = USB_GET_DRIVER_INFO(uaa);
622 	sc->sc_ue.ue_udev = uaa->device;
623 
624 	device_set_usb_desc(dev);
625 
626 	mtx_init(&sc->sc_mtx, device_get_nameunit(dev), NULL, MTX_DEF);
627 
628 	ud = usbd_find_descriptor
629 	    (uaa->device, NULL, uaa->info.bIfaceIndex,
630 	    UDESC_CS_INTERFACE, 0xFF, UDESCSUB_CDC_UNION, 0xFF);
631 
632 	if ((ud == NULL) || (ud->bLength < sizeof(*ud)) ||
633 	    (sc->sc_flags & CDCE_FLAG_NO_UNION)) {
634 		DPRINTFN(1, "No union descriptor!\n");
635 		sc->sc_ifaces_index[0] = uaa->info.bIfaceIndex;
636 		sc->sc_ifaces_index[1] = uaa->info.bIfaceIndex;
637 		goto alloc_transfers;
638 	}
639 	data_iface_no = ud->bSlaveInterface[0];
640 
641 	for (i = 0;; i++) {
642 		iface = usbd_get_iface(uaa->device, i);
643 
644 		if (iface) {
645 			id = usbd_get_interface_descriptor(iface);
646 
647 			if (id && (id->bInterfaceNumber == data_iface_no)) {
648 				sc->sc_ifaces_index[0] = i;
649 				sc->sc_ifaces_index[1] = uaa->info.bIfaceIndex;
650 				usbd_set_parent_iface(uaa->device, i, uaa->info.bIfaceIndex);
651 				break;
652 			}
653 		} else {
654 			device_printf(dev, "no data interface found\n");
655 			goto detach;
656 		}
657 	}
658 
659 	/*
660 	 * <quote>
661 	 *
662 	 *  The Data Class interface of a networking device shall have
663 	 *  a minimum of two interface settings. The first setting
664 	 *  (the default interface setting) includes no endpoints and
665 	 *  therefore no networking traffic is exchanged whenever the
666 	 *  default interface setting is selected. One or more
667 	 *  additional interface settings are used for normal
668 	 *  operation, and therefore each includes a pair of endpoints
669 	 *  (one IN, and one OUT) to exchange network traffic. Select
670 	 *  an alternate interface setting to initialize the network
671 	 *  aspects of the device and to enable the exchange of
672 	 *  network traffic.
673 	 *
674 	 * </quote>
675 	 *
676 	 * Some devices, most notably cable modems, include interface
677 	 * settings that have no IN or OUT endpoint, therefore loop
678 	 * through the list of all available interface settings
679 	 * looking for one with both IN and OUT endpoints.
680 	 */
681 
682 alloc_transfers:
683 
684 	pcfg = cdce_config;	/* Default Configuration */
685 
686 	for (i = 0; i != 32; i++) {
687 		error = usbd_set_alt_interface_index(uaa->device,
688 		    sc->sc_ifaces_index[0], i);
689 		if (error)
690 			break;
691 #if CDCE_HAVE_NCM
692 		if ((i == 0) && (cdce_ncm_init(sc) == 0))
693 			pcfg = cdce_ncm_config;
694 #endif
695 		error = usbd_transfer_setup(uaa->device,
696 		    sc->sc_ifaces_index, sc->sc_xfer,
697 		    pcfg, CDCE_N_TRANSFER, sc, &sc->sc_mtx);
698 
699 		if (error == 0)
700 			break;
701 	}
702 
703 	if (error || (i == 32)) {
704 		device_printf(dev, "No valid alternate "
705 		    "setting found\n");
706 		goto detach;
707 	}
708 
709 	ued = usbd_find_descriptor
710 	    (uaa->device, NULL, uaa->info.bIfaceIndex,
711 	    UDESC_CS_INTERFACE, 0xFF, UDESCSUB_CDC_ENF, 0xFF);
712 
713 	if ((ued == NULL) || (ued->bLength < sizeof(*ued))) {
714 		error = USB_ERR_INVAL;
715 	} else {
716 		/*
717 		 * ECM 1.2 doesn't say it excludes the CRC, but states that it's
718 		 * normally 1514, which excludes the CRC.
719 		 */
720 		DPRINTF("max segsize: %d\n", UGETW(ued->wMaxSegmentSize));
721 		if (UGETW(ued->wMaxSegmentSize) >= (ETHER_MAX_LEN - ETHER_CRC_LEN + ETHER_VLAN_ENCAP_LEN))
722 			sc->sc_flags |= CDCE_FLAG_VLAN;
723 
724 		error = usbd_req_get_string_any(uaa->device, NULL,
725 		    eaddr_str, sizeof(eaddr_str), ued->iMacAddress);
726 	}
727 
728 	if (error) {
729 		/* fake MAC address */
730 
731 		device_printf(dev, "faking MAC address\n");
732 		seed = ticks;
733 		sc->sc_ue.ue_eaddr[0] = 0x2a;
734 		memcpy(&sc->sc_ue.ue_eaddr[1], &seed, sizeof(uint32_t));
735 		sc->sc_ue.ue_eaddr[5] = device_get_unit(dev);
736 
737 	} else {
738 		memset(sc->sc_ue.ue_eaddr, 0, sizeof(sc->sc_ue.ue_eaddr));
739 
740 		for (i = 0; i != (ETHER_ADDR_LEN * 2); i++) {
741 			char c = eaddr_str[i];
742 
743 			if ('0' <= c && c <= '9')
744 				c -= '0';
745 			else if (c != 0)
746 				c -= 'A' - 10;
747 			else
748 				break;
749 
750 			c &= 0xf;
751 
752 			if ((i & 1) == 0)
753 				c <<= 4;
754 			sc->sc_ue.ue_eaddr[i / 2] |= c;
755 		}
756 
757 		if (uaa->usb_mode == USB_MODE_DEVICE) {
758 			/*
759 			 * Do not use the same MAC address like the peer !
760 			 */
761 			sc->sc_ue.ue_eaddr[5] ^= 0xFF;
762 		}
763 	}
764 
765 	ue->ue_sc = sc;
766 	ue->ue_dev = dev;
767 	ue->ue_udev = uaa->device;
768 	ue->ue_mtx = &sc->sc_mtx;
769 	ue->ue_methods = &cdce_ue_methods;
770 
771 	error = uether_ifattach(ue);
772 	if (error) {
773 		device_printf(dev, "could not attach interface\n");
774 		goto detach;
775 	}
776 	return (0);			/* success */
777 
778 detach:
779 	cdce_detach(dev);
780 	return (ENXIO);			/* failure */
781 }
782 
783 static int
784 cdce_detach(device_t dev)
785 {
786 	struct cdce_softc *sc = device_get_softc(dev);
787 	struct usb_ether *ue = &sc->sc_ue;
788 
789 	/* stop all USB transfers first */
790 	usbd_transfer_unsetup(sc->sc_xfer, CDCE_N_TRANSFER);
791 	uether_ifdetach(ue);
792 	mtx_destroy(&sc->sc_mtx);
793 
794 	ifmedia_removeall(&sc->sc_media);
795 
796 	return (0);
797 }
798 
799 static void
800 cdce_start(struct usb_ether *ue)
801 {
802 	struct cdce_softc *sc = uether_getsc(ue);
803 
804 	/*
805 	 * Start the USB transfers, if not already started:
806 	 */
807 	usbd_transfer_start(sc->sc_xfer[CDCE_BULK_TX]);
808 	usbd_transfer_start(sc->sc_xfer[CDCE_BULK_RX]);
809 }
810 
811 static int
812 cdce_ioctl(struct ifnet *ifp, u_long command, caddr_t data)
813 {
814 	struct usb_ether *ue = ifp->if_softc;
815 	struct cdce_softc *sc = uether_getsc(ue);
816 	struct ifreq *ifr = (struct ifreq *)data;
817 	int error;
818 
819 	error = 0;
820 
821 	switch(command) {
822 	case SIOCGIFMEDIA:
823 	case SIOCSIFMEDIA:
824 		error = ifmedia_ioctl(ifp, ifr, &sc->sc_media, command);
825 		break;
826 	default:
827 		error = uether_ioctl(ifp, command, data);
828 		break;
829 	}
830 
831 	return (error);
832 }
833 
834 static void
835 cdce_free_queue(struct mbuf **ppm, uint8_t n)
836 {
837 	uint8_t x;
838 	for (x = 0; x != n; x++) {
839 		if (ppm[x] != NULL) {
840 			m_freem(ppm[x]);
841 			ppm[x] = NULL;
842 		}
843 	}
844 }
845 
846 static int
847 cdce_media_change_cb(struct ifnet *ifp)
848 {
849 
850 	return (EOPNOTSUPP);
851 }
852 
853 static void
854 cdce_media_status_cb(struct ifnet *ifp, struct ifmediareq *ifmr)
855 {
856 
857 	if ((if_getflags(ifp) & IFF_UP) == 0)
858 		return;
859 
860 	ifmr->ifm_active = IFM_ETHER;
861 	ifmr->ifm_status = IFM_AVALID;
862 	ifmr->ifm_status |=
863 	    ifp->if_link_state == LINK_STATE_UP ? IFM_ACTIVE : 0;
864 }
865 
866 static void
867 cdce_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error)
868 {
869 	struct cdce_softc *sc = usbd_xfer_softc(xfer);
870 	struct ifnet *ifp = uether_getifp(&sc->sc_ue);
871 	struct mbuf *m;
872 	struct mbuf *mt;
873 	uint32_t crc;
874 	uint8_t x;
875 	int actlen, aframes;
876 
877 	usbd_xfer_status(xfer, &actlen, NULL, &aframes, NULL);
878 
879 	DPRINTFN(1, "\n");
880 
881 	switch (USB_GET_STATE(xfer)) {
882 	case USB_ST_TRANSFERRED:
883 		DPRINTFN(11, "transfer complete: %u bytes in %u frames\n",
884 		    actlen, aframes);
885 
886 		if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1);
887 
888 		/* free all previous TX buffers */
889 		cdce_free_queue(sc->sc_tx_buf, CDCE_FRAMES_MAX);
890 
891 		/* FALLTHROUGH */
892 	case USB_ST_SETUP:
893 tr_setup:
894 		for (x = 0; x != CDCE_FRAMES_MAX; x++) {
895 			IFQ_DRV_DEQUEUE(&ifp->if_snd, m);
896 
897 			if (m == NULL)
898 				break;
899 
900 			if (sc->sc_flags & CDCE_FLAG_ZAURUS) {
901 				/*
902 				 * Zaurus wants a 32-bit CRC appended
903 				 * to every frame
904 				 */
905 
906 				crc = cdce_m_crc32(m, 0, m->m_pkthdr.len);
907 				crc = htole32(crc);
908 
909 				if (!m_append(m, 4, (void *)&crc)) {
910 					m_freem(m);
911 					if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
912 					continue;
913 				}
914 			}
915 			if (m->m_len != m->m_pkthdr.len) {
916 				mt = m_defrag(m, M_NOWAIT);
917 				if (mt == NULL) {
918 					m_freem(m);
919 					if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
920 					continue;
921 				}
922 				m = mt;
923 			}
924 			if (m->m_pkthdr.len > MCLBYTES) {
925 				m->m_pkthdr.len = MCLBYTES;
926 			}
927 			sc->sc_tx_buf[x] = m;
928 			usbd_xfer_set_frame_data(xfer, x, m->m_data, m->m_len);
929 
930 			/*
931 			 * If there's a BPF listener, bounce a copy of
932 			 * this frame to him:
933 			 */
934 			BPF_MTAP(ifp, m);
935 		}
936 		if (x != 0) {
937 			usbd_xfer_set_frames(xfer, x);
938 
939 			usbd_transfer_submit(xfer);
940 		}
941 		break;
942 
943 	default:			/* Error */
944 		DPRINTFN(11, "transfer error, %s\n",
945 		    usbd_errstr(error));
946 
947 		/* free all previous TX buffers */
948 		cdce_free_queue(sc->sc_tx_buf, CDCE_FRAMES_MAX);
949 
950 		/* count output errors */
951 		if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
952 
953 		if (error != USB_ERR_CANCELLED) {
954 			if (usbd_get_mode(sc->sc_ue.ue_udev) == USB_MODE_HOST) {
955 				/* try to clear stall first */
956 				usbd_xfer_set_stall(xfer);
957 			}
958 			goto tr_setup;
959 		}
960 		break;
961 	}
962 }
963 
964 static int32_t
965 cdce_m_crc32_cb(void *arg, void *src, uint32_t count)
966 {
967 	uint32_t *p_crc = arg;
968 
969 	*p_crc = crc32_raw(src, count, *p_crc);
970 	return (0);
971 }
972 
973 static uint32_t
974 cdce_m_crc32(struct mbuf *m, uint32_t src_offset, uint32_t src_len)
975 {
976 	uint32_t crc = 0xFFFFFFFF;
977 	int error;
978 
979 	error = m_apply(m, src_offset, src_len, cdce_m_crc32_cb, &crc);
980 	return (crc ^ 0xFFFFFFFF);
981 }
982 
983 static void
984 cdce_init(struct usb_ether *ue)
985 {
986 	struct cdce_softc *sc = uether_getsc(ue);
987 	struct ifnet *ifp = uether_getifp(ue);
988 
989 	CDCE_LOCK_ASSERT(sc, MA_OWNED);
990 
991 	ifp->if_drv_flags |= IFF_DRV_RUNNING;
992 
993 	/* start interrupt transfer */
994 	usbd_transfer_start(sc->sc_xfer[CDCE_INTR_RX]);
995 	usbd_transfer_start(sc->sc_xfer[CDCE_INTR_TX]);
996 
997 	/*
998 	 * Stall data write direction, which depends on USB mode.
999 	 *
1000 	 * Some USB host stacks (e.g. Mac OS X) don't clears stall
1001 	 * bit as it should, so set it in our host mode only.
1002 	 */
1003 	if (usbd_get_mode(sc->sc_ue.ue_udev) == USB_MODE_HOST)
1004 		usbd_xfer_set_stall(sc->sc_xfer[CDCE_BULK_TX]);
1005 
1006 	/* start data transfers */
1007 	cdce_start(ue);
1008 }
1009 
1010 static void
1011 cdce_stop(struct usb_ether *ue)
1012 {
1013 	struct cdce_softc *sc = uether_getsc(ue);
1014 	struct ifnet *ifp = uether_getifp(ue);
1015 
1016 	CDCE_LOCK_ASSERT(sc, MA_OWNED);
1017 
1018 	ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
1019 
1020 	/*
1021 	 * stop all the transfers, if not already stopped:
1022 	 */
1023 	usbd_transfer_stop(sc->sc_xfer[CDCE_BULK_RX]);
1024 	usbd_transfer_stop(sc->sc_xfer[CDCE_BULK_TX]);
1025 	usbd_transfer_stop(sc->sc_xfer[CDCE_INTR_RX]);
1026 	usbd_transfer_stop(sc->sc_xfer[CDCE_INTR_TX]);
1027 }
1028 
1029 static void
1030 cdce_setmulti(struct usb_ether *ue)
1031 {
1032 
1033 	cdce_set_filter(ue);
1034 }
1035 
1036 static void
1037 cdce_setpromisc(struct usb_ether *ue)
1038 {
1039 
1040 	cdce_set_filter(ue);
1041 }
1042 
1043 static void
1044 cdce_set_filter(struct usb_ether *ue)
1045 {
1046 	struct cdce_softc *sc = uether_getsc(ue);
1047 	struct ifnet *ifp = uether_getifp(ue);
1048 	struct usb_device_request req;
1049 	uint16_t value;
1050 
1051 	value = CDC_PACKET_TYPE_DIRECTED | CDC_PACKET_TYPE_BROADCAST;
1052 	if (if_getflags(ifp) & IFF_PROMISC)
1053 		value |= CDC_PACKET_TYPE_PROMISC;
1054 	if (if_getflags(ifp) & IFF_ALLMULTI)
1055 		value |= CDC_PACKET_TYPE_ALL_MULTICAST;
1056 
1057 	req.bmRequestType = UT_CLASS | UT_INTERFACE;
1058 	req.bRequest = CDC_SET_ETHERNET_PACKET_FILTER;
1059 	USETW(req.wValue, value);
1060 	req.wIndex[0] = sc->sc_ifaces_index[1];
1061 	req.wIndex[1] = 0;
1062 	USETW(req.wLength, 0);
1063 
1064 	/*
1065 	 * Function below will drop the sc mutex.
1066 	 * We can do that since we're called from a separate task,
1067 	 * that simply wraps the setpromisc/setmulti methods.
1068 	 */
1069 	usbd_do_request(sc->sc_ue.ue_udev, &sc->sc_mtx, &req, NULL);
1070 }
1071 
1072 static int
1073 cdce_suspend(device_t dev)
1074 {
1075 	device_printf(dev, "Suspending\n");
1076 	return (0);
1077 }
1078 
1079 static int
1080 cdce_resume(device_t dev)
1081 {
1082 	device_printf(dev, "Resuming\n");
1083 	return (0);
1084 }
1085 
1086 static void
1087 cdce_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error)
1088 {
1089 	struct cdce_softc *sc = usbd_xfer_softc(xfer);
1090 	struct mbuf *m;
1091 	uint8_t x;
1092 	int actlen;
1093 	int aframes;
1094 	int len;
1095 
1096 	usbd_xfer_status(xfer, &actlen, NULL, &aframes, NULL);
1097 
1098 	switch (USB_GET_STATE(xfer)) {
1099 	case USB_ST_TRANSFERRED:
1100 
1101 		DPRINTF("received %u bytes in %u frames\n", actlen, aframes);
1102 
1103 		for (x = 0; x != aframes; x++) {
1104 			m = sc->sc_rx_buf[x];
1105 			sc->sc_rx_buf[x] = NULL;
1106 			len = usbd_xfer_frame_len(xfer, x);
1107 
1108 			/* Strip off CRC added by Zaurus, if any */
1109 			if ((sc->sc_flags & CDCE_FLAG_ZAURUS) && len >= 14)
1110 				len -= 4;
1111 
1112 			if (len < (int)sizeof(struct ether_header)) {
1113 				m_freem(m);
1114 				continue;
1115 			}
1116 			/* queue up mbuf */
1117 			uether_rxmbuf(&sc->sc_ue, m, len);
1118 		}
1119 
1120 		/* FALLTHROUGH */
1121 	case USB_ST_SETUP:
1122 		/*
1123 		 * TODO: Implement support for multi frame transfers,
1124 		 * when the USB hardware supports it.
1125 		 */
1126 		for (x = 0; x != 1; x++) {
1127 			if (sc->sc_rx_buf[x] == NULL) {
1128 				m = uether_newbuf();
1129 				if (m == NULL)
1130 					goto tr_stall;
1131 				sc->sc_rx_buf[x] = m;
1132 			} else {
1133 				m = sc->sc_rx_buf[x];
1134 			}
1135 
1136 			usbd_xfer_set_frame_data(xfer, x, m->m_data, m->m_len);
1137 		}
1138 		/* set number of frames and start hardware */
1139 		usbd_xfer_set_frames(xfer, x);
1140 		usbd_transfer_submit(xfer);
1141 		/* flush any received frames */
1142 		uether_rxflush(&sc->sc_ue);
1143 		break;
1144 
1145 	default:			/* Error */
1146 		DPRINTF("error = %s\n",
1147 		    usbd_errstr(error));
1148 
1149 		if (error != USB_ERR_CANCELLED) {
1150 tr_stall:
1151 			if (usbd_get_mode(sc->sc_ue.ue_udev) == USB_MODE_HOST) {
1152 				/* try to clear stall first */
1153 				usbd_xfer_set_stall(xfer);
1154 				usbd_xfer_set_frames(xfer, 0);
1155 				usbd_transfer_submit(xfer);
1156 			}
1157 			break;
1158 		}
1159 
1160 		/* need to free the RX-mbufs when we are cancelled */
1161 		cdce_free_queue(sc->sc_rx_buf, CDCE_FRAMES_MAX);
1162 		break;
1163 	}
1164 }
1165 
1166 static void
1167 cdce_intr_read_callback(struct usb_xfer *xfer, usb_error_t error)
1168 {
1169 	u_char buf[CDCE_IND_SIZE_MAX];
1170 	struct usb_cdc_notification ucn;
1171 	struct cdce_softc *sc;
1172 	struct ifnet *ifp;
1173 	struct usb_page_cache *pc;
1174 	int off, actlen;
1175 	uint32_t downrate, uprate;
1176 
1177 	sc = usbd_xfer_softc(xfer);
1178 	ifp = uether_getifp(&sc->sc_ue);
1179 	pc = usbd_xfer_get_frame(xfer, 0);
1180 
1181 	usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL);
1182 
1183 	switch (USB_GET_STATE(xfer)) {
1184 	case USB_ST_TRANSFERRED:
1185 		if (USB_DEBUG_VAR)
1186 			usbd_copy_out(pc, 0, buf, MIN(actlen, sizeof buf));
1187 		DPRINTF("Received %d bytes: %*D\n", actlen,
1188 		    (int)MIN(actlen, sizeof buf), buf, "");
1189 
1190 		off = 0;
1191 		while (actlen - off >= UCDC_NOTIFICATION_LENGTH) {
1192 			usbd_copy_out(pc, off, &ucn, UCDC_NOTIFICATION_LENGTH);
1193 
1194 			do {
1195 				if (ucn.bmRequestType != 0xa1)
1196 					break;
1197 
1198 				switch (ucn.bNotification) {
1199 				case UCDC_N_NETWORK_CONNECTION:
1200 					DPRINTF("changing link state: %d\n",
1201 					    UGETW(ucn.wValue));
1202 					if_link_state_change(ifp,
1203 					    UGETW(ucn.wValue) ? LINK_STATE_UP :
1204 					    LINK_STATE_DOWN);
1205 					break;
1206 
1207 				case UCDC_N_CONNECTION_SPEED_CHANGE:
1208 					if (UGETW(ucn.wLength) != 8)
1209 						break;
1210 
1211 					usbd_copy_out(pc, off +
1212 					    UCDC_NOTIFICATION_LENGTH,
1213 					    &ucn.data, UGETW(ucn.wLength));
1214 					downrate = UGETDW(ucn.data);
1215 					uprate = UGETDW(ucn.data);
1216 					if (downrate != uprate)
1217 						break;
1218 
1219 					/* set rate */
1220 					DPRINTF("changing baudrate: %u\n",
1221 					    downrate);
1222 					if_setbaudrate(ifp, downrate);
1223 					break;
1224 
1225 				default:
1226 					break;
1227 				}
1228 			} while (0);
1229 
1230 			off += UCDC_NOTIFICATION_LENGTH + UGETW(ucn.wLength);
1231 		}
1232 
1233 		/* FALLTHROUGH */
1234 	case USB_ST_SETUP:
1235 tr_setup:
1236 		usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
1237 		usbd_transfer_submit(xfer);
1238 		break;
1239 
1240 	default:			/* Error */
1241 		if (error != USB_ERR_CANCELLED) {
1242 			/* start clear stall */
1243 			if (usbd_get_mode(sc->sc_ue.ue_udev) == USB_MODE_HOST)
1244 				usbd_xfer_set_stall(xfer);
1245 			goto tr_setup;
1246 		}
1247 		break;
1248 	}
1249 }
1250 
1251 static void
1252 cdce_intr_write_callback(struct usb_xfer *xfer, usb_error_t error)
1253 {
1254 	struct cdce_softc *sc = usbd_xfer_softc(xfer);
1255 	struct usb_cdc_notification req;
1256 	struct usb_page_cache *pc;
1257 	uint32_t speed;
1258 	int actlen;
1259 
1260 	usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL);
1261 
1262 	switch (USB_GET_STATE(xfer)) {
1263 	case USB_ST_TRANSFERRED:
1264 
1265 		DPRINTF("Transferred %d bytes\n", actlen);
1266 
1267 		switch (sc->sc_notify_state) {
1268 		case CDCE_NOTIFY_NETWORK_CONNECTION:
1269 			sc->sc_notify_state = CDCE_NOTIFY_SPEED_CHANGE;
1270 			break;
1271 		case CDCE_NOTIFY_SPEED_CHANGE:
1272 			sc->sc_notify_state = CDCE_NOTIFY_DONE;
1273 			break;
1274 		default:
1275 			break;
1276 		}
1277 
1278 		/* FALLTHROUGH */
1279 	case USB_ST_SETUP:
1280 tr_setup:
1281 		/*
1282 		 * Inform host about connection. Required according to USB CDC
1283 		 * specification and communicating to Mac OS X USB host stack.
1284 		 * Some of the values seems ignored by Mac OS X though.
1285 		 */
1286 		if (sc->sc_notify_state == CDCE_NOTIFY_NETWORK_CONNECTION) {
1287 			req.bmRequestType = UCDC_NOTIFICATION;
1288 			req.bNotification = UCDC_N_NETWORK_CONNECTION;
1289 			req.wIndex[0] = sc->sc_ifaces_index[1];
1290 			req.wIndex[1] = 0;
1291 			USETW(req.wValue, 1); /* Connected */
1292 			USETW(req.wLength, 0);
1293 
1294 			pc = usbd_xfer_get_frame(xfer, 0);
1295 			usbd_copy_in(pc, 0, &req, sizeof(req));
1296 			usbd_xfer_set_frame_len(xfer, 0, sizeof(req));
1297 			usbd_xfer_set_frames(xfer, 1);
1298 			usbd_transfer_submit(xfer);
1299 
1300 		} else if (sc->sc_notify_state == CDCE_NOTIFY_SPEED_CHANGE) {
1301 			req.bmRequestType = UCDC_NOTIFICATION;
1302 			req.bNotification = UCDC_N_CONNECTION_SPEED_CHANGE;
1303 			req.wIndex[0] = sc->sc_ifaces_index[1];
1304 			req.wIndex[1] = 0;
1305 			USETW(req.wValue, 0);
1306 			USETW(req.wLength, 8);
1307 
1308 			/* Peak theoretical bulk trasfer rate in bits/s */
1309 			if (usbd_get_speed(sc->sc_ue.ue_udev) != USB_SPEED_FULL)
1310 				speed = (13 * 512 * 8 * 1000 * 8);
1311 			else
1312 				speed = (19 * 64 * 1 * 1000 * 8);
1313 
1314 			USETDW(req.data + 0, speed); /* Upstream bit rate */
1315 			USETDW(req.data + 4, speed); /* Downstream bit rate */
1316 
1317 			pc = usbd_xfer_get_frame(xfer, 0);
1318 			usbd_copy_in(pc, 0, &req, sizeof(req));
1319 			usbd_xfer_set_frame_len(xfer, 0, sizeof(req));
1320 			usbd_xfer_set_frames(xfer, 1);
1321 			usbd_transfer_submit(xfer);
1322 		}
1323 		break;
1324 
1325 	default:			/* Error */
1326 		if (error != USB_ERR_CANCELLED) {
1327 			if (usbd_get_mode(sc->sc_ue.ue_udev) == USB_MODE_HOST) {
1328 				/* start clear stall */
1329 				usbd_xfer_set_stall(xfer);
1330 			}
1331 			goto tr_setup;
1332 		}
1333 		break;
1334 	}
1335 }
1336 
1337 static int
1338 cdce_handle_request(device_t dev,
1339     const void *preq, void **pptr, uint16_t *plen,
1340     uint16_t offset, uint8_t *pstate)
1341 {
1342 	struct cdce_softc *sc = device_get_softc(dev);
1343 	const struct usb_device_request *req = preq;
1344 	uint8_t is_complete = *pstate;
1345 
1346 	/*
1347 	 * When Mac OS X resumes after suspending it expects
1348 	 * to be notified again after this request.
1349 	 */
1350 	if (req->bmRequestType == UT_WRITE_CLASS_INTERFACE && \
1351 	    req->bRequest == UCDC_NCM_SET_ETHERNET_PACKET_FILTER) {
1352 		if (is_complete == 1) {
1353 			mtx_lock(&sc->sc_mtx);
1354 			sc->sc_notify_state = CDCE_NOTIFY_SPEED_CHANGE;
1355 			usbd_transfer_start(sc->sc_xfer[CDCE_INTR_TX]);
1356 			mtx_unlock(&sc->sc_mtx);
1357 		}
1358 
1359 		return (0);
1360 	}
1361 
1362 	return (ENXIO);			/* use builtin handler */
1363 }
1364 
1365 #if CDCE_HAVE_NCM
1366 static void
1367 cdce_ncm_tx_zero(struct usb_page_cache *pc,
1368     uint32_t start, uint32_t end)
1369 {
1370 	if (start >= CDCE_NCM_TX_MAXLEN)
1371 		return;
1372 	if (end > CDCE_NCM_TX_MAXLEN)
1373 		end = CDCE_NCM_TX_MAXLEN;
1374 
1375 	usbd_frame_zero(pc, start, end - start);
1376 }
1377 
1378 static uint8_t
1379 cdce_ncm_fill_tx_frames(struct usb_xfer *xfer, uint8_t index)
1380 {
1381 	struct cdce_softc *sc = usbd_xfer_softc(xfer);
1382 	struct ifnet *ifp = uether_getifp(&sc->sc_ue);
1383 	struct usb_page_cache *pc = usbd_xfer_get_frame(xfer, index);
1384 	struct mbuf *m;
1385 	uint32_t rem;
1386 	uint32_t offset;
1387 	uint32_t last_offset;
1388 	uint16_t n;
1389 	uint8_t retval;
1390 
1391 	usbd_xfer_set_frame_offset(xfer, index * CDCE_NCM_TX_MAXLEN, index);
1392 
1393 	offset = sizeof(sc->sc_ncm.hdr) +
1394 	    sizeof(sc->sc_ncm.dpt) + sizeof(sc->sc_ncm.dp);
1395 
1396 	/* Store last valid offset before alignment */
1397 	last_offset = offset;
1398 
1399 	/* Align offset */
1400 	offset = CDCE_NCM_ALIGN(sc->sc_ncm.tx_remainder,
1401 	    offset, sc->sc_ncm.tx_modulus);
1402 
1403 	/* Zero pad */
1404 	cdce_ncm_tx_zero(pc, last_offset, offset);
1405 
1406 	/* buffer full */
1407 	retval = 2;
1408 
1409 	for (n = 0; n != sc->sc_ncm.tx_nframe; n++) {
1410 		/* check if end of transmit buffer is reached */
1411 
1412 		if (offset >= sc->sc_ncm.tx_max)
1413 			break;
1414 
1415 		/* compute maximum buffer size */
1416 
1417 		rem = sc->sc_ncm.tx_max - offset;
1418 
1419 		IFQ_DRV_DEQUEUE(&(ifp->if_snd), m);
1420 
1421 		if (m == NULL) {
1422 			/* buffer not full */
1423 			retval = 1;
1424 			break;
1425 		}
1426 
1427 		if (m->m_pkthdr.len > (int)rem) {
1428 			if (n == 0) {
1429 				/* The frame won't fit in our buffer */
1430 				DPRINTFN(1, "Frame too big to be transmitted!\n");
1431 				m_freem(m);
1432 				if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
1433 				n--;
1434 				continue;
1435 			}
1436 			/* Wait till next buffer becomes ready */
1437 			IFQ_DRV_PREPEND(&(ifp->if_snd), m);
1438 			break;
1439 		}
1440 		usbd_m_copy_in(pc, offset, m, 0, m->m_pkthdr.len);
1441 
1442 		USETW(sc->sc_ncm.dp[n].wFrameLength, m->m_pkthdr.len);
1443 		USETW(sc->sc_ncm.dp[n].wFrameIndex, offset);
1444 
1445 		/* Update offset */
1446 		offset += m->m_pkthdr.len;
1447 
1448 		/* Store last valid offset before alignment */
1449 		last_offset = offset;
1450 
1451 		/* Align offset */
1452 		offset = CDCE_NCM_ALIGN(sc->sc_ncm.tx_remainder,
1453 		    offset, sc->sc_ncm.tx_modulus);
1454 
1455 		/* Zero pad */
1456 		cdce_ncm_tx_zero(pc, last_offset, offset);
1457 
1458 		/*
1459 		 * If there's a BPF listener, bounce a copy
1460 		 * of this frame to him:
1461 		 */
1462 		BPF_MTAP(ifp, m);
1463 
1464 		/* Free mbuf */
1465 
1466 		m_freem(m);
1467 
1468 		/* Pre-increment interface counter */
1469 
1470 		if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1);
1471 	}
1472 
1473 	if (n == 0)
1474 		return (0);
1475 
1476 	rem = (sizeof(sc->sc_ncm.dpt) + (4 * n) + 4);
1477 
1478 	USETW(sc->sc_ncm.dpt.wLength, rem);
1479 
1480 	/* zero the rest of the data pointer entries */
1481 	for (; n != CDCE_NCM_SUBFRAMES_MAX; n++) {
1482 		USETW(sc->sc_ncm.dp[n].wFrameLength, 0);
1483 		USETW(sc->sc_ncm.dp[n].wFrameIndex, 0);
1484 	}
1485 
1486 	offset = last_offset;
1487 
1488 	/* Align offset */
1489 	offset = CDCE_NCM_ALIGN(0, offset, CDCE_NCM_TX_MINLEN);
1490 
1491 	/* Optimise, save bandwidth and force short termination */
1492 	if (offset >= sc->sc_ncm.tx_max)
1493 		offset = sc->sc_ncm.tx_max;
1494 	else
1495 		offset ++;
1496 
1497 	/* Zero pad */
1498 	cdce_ncm_tx_zero(pc, last_offset, offset);
1499 
1500 	/* set frame length */
1501 	usbd_xfer_set_frame_len(xfer, index, offset);
1502 
1503 	/* Fill out 16-bit header */
1504 	sc->sc_ncm.hdr.dwSignature[0] = 'N';
1505 	sc->sc_ncm.hdr.dwSignature[1] = 'C';
1506 	sc->sc_ncm.hdr.dwSignature[2] = 'M';
1507 	sc->sc_ncm.hdr.dwSignature[3] = 'H';
1508 	USETW(sc->sc_ncm.hdr.wHeaderLength, sizeof(sc->sc_ncm.hdr));
1509 	USETW(sc->sc_ncm.hdr.wBlockLength, offset);
1510 	USETW(sc->sc_ncm.hdr.wSequence, sc->sc_ncm.tx_seq);
1511 	USETW(sc->sc_ncm.hdr.wDptIndex, sizeof(sc->sc_ncm.hdr));
1512 
1513 	sc->sc_ncm.tx_seq++;
1514 
1515 	/* Fill out 16-bit frame table header */
1516 	sc->sc_ncm.dpt.dwSignature[0] = 'N';
1517 	sc->sc_ncm.dpt.dwSignature[1] = 'C';
1518 	sc->sc_ncm.dpt.dwSignature[2] = 'M';
1519 	sc->sc_ncm.dpt.dwSignature[3] = '0';
1520 	USETW(sc->sc_ncm.dpt.wNextNdpIndex, 0);		/* reserved */
1521 
1522 	usbd_copy_in(pc, 0, &(sc->sc_ncm.hdr), sizeof(sc->sc_ncm.hdr));
1523 	usbd_copy_in(pc, sizeof(sc->sc_ncm.hdr), &(sc->sc_ncm.dpt),
1524 	    sizeof(sc->sc_ncm.dpt));
1525 	usbd_copy_in(pc, sizeof(sc->sc_ncm.hdr) + sizeof(sc->sc_ncm.dpt),
1526 	    &(sc->sc_ncm.dp), sizeof(sc->sc_ncm.dp));
1527 	return (retval);
1528 }
1529 
1530 static void
1531 cdce_ncm_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error)
1532 {
1533 	struct cdce_softc *sc = usbd_xfer_softc(xfer);
1534 	struct ifnet *ifp = uether_getifp(&sc->sc_ue);
1535 	uint16_t x;
1536 	uint8_t temp;
1537 	int actlen;
1538 	int aframes;
1539 
1540 	switch (USB_GET_STATE(xfer)) {
1541 	case USB_ST_TRANSFERRED:
1542 
1543 		usbd_xfer_status(xfer, &actlen, NULL, &aframes, NULL);
1544 
1545 		DPRINTFN(10, "transfer complete: "
1546 		    "%u bytes in %u frames\n", actlen, aframes);
1547 
1548 	case USB_ST_SETUP:
1549 		for (x = 0; x != CDCE_NCM_TX_FRAMES_MAX; x++) {
1550 			temp = cdce_ncm_fill_tx_frames(xfer, x);
1551 			if (temp == 0)
1552 				break;
1553 			if (temp == 1) {
1554 				x++;
1555 				break;
1556 			}
1557 		}
1558 
1559 		if (x != 0) {
1560 #ifdef USB_DEBUG
1561 			usbd_xfer_set_interval(xfer, cdce_tx_interval);
1562 #endif
1563 			usbd_xfer_set_frames(xfer, x);
1564 			usbd_transfer_submit(xfer);
1565 		}
1566 		break;
1567 
1568 	default:			/* Error */
1569 		DPRINTFN(10, "Transfer error: %s\n",
1570 		    usbd_errstr(error));
1571 
1572 		/* update error counter */
1573 		if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
1574 
1575 		if (error != USB_ERR_CANCELLED) {
1576 			if (usbd_get_mode(sc->sc_ue.ue_udev) == USB_MODE_HOST) {
1577 				/* try to clear stall first */
1578 				usbd_xfer_set_stall(xfer);
1579 				usbd_xfer_set_frames(xfer, 0);
1580 				usbd_transfer_submit(xfer);
1581 			}
1582 		}
1583 		break;
1584 	}
1585 }
1586 
1587 static void
1588 cdce_ncm_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error)
1589 {
1590 	struct cdce_softc *sc = usbd_xfer_softc(xfer);
1591 	struct usb_page_cache *pc = usbd_xfer_get_frame(xfer, 0);
1592 	struct ifnet *ifp = uether_getifp(&sc->sc_ue);
1593 	struct mbuf *m;
1594 	int sumdata;
1595 	int sumlen;
1596 	int actlen;
1597 	int aframes;
1598 	int temp;
1599 	int nframes;
1600 	int x;
1601 	int offset;
1602 
1603 	switch (USB_GET_STATE(xfer)) {
1604 	case USB_ST_TRANSFERRED:
1605 
1606 		usbd_xfer_status(xfer, &actlen, &sumlen, &aframes, NULL);
1607 
1608 		DPRINTFN(1, "received %u bytes in %u frames\n",
1609 		    actlen, aframes);
1610 
1611 		if (actlen < (int)(sizeof(sc->sc_ncm.hdr) +
1612 		    sizeof(sc->sc_ncm.dpt))) {
1613 			DPRINTFN(1, "frame too short\n");
1614 			goto tr_setup;
1615 		}
1616 		usbd_copy_out(pc, 0, &(sc->sc_ncm.hdr),
1617 		    sizeof(sc->sc_ncm.hdr));
1618 
1619 		if ((sc->sc_ncm.hdr.dwSignature[0] != 'N') ||
1620 		    (sc->sc_ncm.hdr.dwSignature[1] != 'C') ||
1621 		    (sc->sc_ncm.hdr.dwSignature[2] != 'M') ||
1622 		    (sc->sc_ncm.hdr.dwSignature[3] != 'H')) {
1623 			DPRINTFN(1, "invalid HDR signature: "
1624 			    "0x%02x:0x%02x:0x%02x:0x%02x\n",
1625 			    sc->sc_ncm.hdr.dwSignature[0],
1626 			    sc->sc_ncm.hdr.dwSignature[1],
1627 			    sc->sc_ncm.hdr.dwSignature[2],
1628 			    sc->sc_ncm.hdr.dwSignature[3]);
1629 			goto tr_stall;
1630 		}
1631 		temp = UGETW(sc->sc_ncm.hdr.wBlockLength);
1632 		if (temp > sumlen) {
1633 			DPRINTFN(1, "unsupported block length %u/%u\n",
1634 			    temp, sumlen);
1635 			goto tr_stall;
1636 		}
1637 		temp = UGETW(sc->sc_ncm.hdr.wDptIndex);
1638 		if ((int)(temp + sizeof(sc->sc_ncm.dpt)) > actlen) {
1639 			DPRINTFN(1, "invalid DPT index: 0x%04x\n", temp);
1640 			goto tr_stall;
1641 		}
1642 		usbd_copy_out(pc, temp, &(sc->sc_ncm.dpt),
1643 		    sizeof(sc->sc_ncm.dpt));
1644 
1645 		if ((sc->sc_ncm.dpt.dwSignature[0] != 'N') ||
1646 		    (sc->sc_ncm.dpt.dwSignature[1] != 'C') ||
1647 		    (sc->sc_ncm.dpt.dwSignature[2] != 'M') ||
1648 		    (sc->sc_ncm.dpt.dwSignature[3] != '0')) {
1649 			DPRINTFN(1, "invalid DPT signature"
1650 			    "0x%02x:0x%02x:0x%02x:0x%02x\n",
1651 			    sc->sc_ncm.dpt.dwSignature[0],
1652 			    sc->sc_ncm.dpt.dwSignature[1],
1653 			    sc->sc_ncm.dpt.dwSignature[2],
1654 			    sc->sc_ncm.dpt.dwSignature[3]);
1655 			goto tr_stall;
1656 		}
1657 		nframes = UGETW(sc->sc_ncm.dpt.wLength) / 4;
1658 
1659 		/* Subtract size of header and last zero padded entry */
1660 		if (nframes >= (2 + 1))
1661 			nframes -= (2 + 1);
1662 		else
1663 			nframes = 0;
1664 
1665 		DPRINTFN(1, "nframes = %u\n", nframes);
1666 
1667 		temp += sizeof(sc->sc_ncm.dpt);
1668 
1669 		if ((temp + (4 * nframes)) > actlen)
1670 			goto tr_stall;
1671 
1672 		if (nframes > CDCE_NCM_SUBFRAMES_MAX) {
1673 			DPRINTFN(1, "Truncating number of frames from %u to %u\n",
1674 			    nframes, CDCE_NCM_SUBFRAMES_MAX);
1675 			nframes = CDCE_NCM_SUBFRAMES_MAX;
1676 		}
1677 		usbd_copy_out(pc, temp, &(sc->sc_ncm.dp), (4 * nframes));
1678 
1679 		sumdata = 0;
1680 
1681 		for (x = 0; x != nframes; x++) {
1682 			offset = UGETW(sc->sc_ncm.dp[x].wFrameIndex);
1683 			temp = UGETW(sc->sc_ncm.dp[x].wFrameLength);
1684 
1685 			if ((offset == 0) ||
1686 			    (temp < (int)sizeof(struct ether_header)) ||
1687 			    (temp > (MCLBYTES - ETHER_ALIGN))) {
1688 				DPRINTFN(1, "NULL frame detected at %d\n", x);
1689 				m = NULL;
1690 				/* silently ignore this frame */
1691 				continue;
1692 			} else if ((offset + temp) > actlen) {
1693 				DPRINTFN(1, "invalid frame "
1694 				    "detected at %d\n", x);
1695 				m = NULL;
1696 				/* silently ignore this frame */
1697 				continue;
1698 			} else if (temp > (int)(MHLEN - ETHER_ALIGN)) {
1699 				m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
1700 			} else {
1701 				m = m_gethdr(M_NOWAIT, MT_DATA);
1702 			}
1703 
1704 			DPRINTFN(16, "frame %u, offset = %u, length = %u \n",
1705 			    x, offset, temp);
1706 
1707 			/* check if we have a buffer */
1708 			if (m) {
1709 				m->m_len = m->m_pkthdr.len = temp + ETHER_ALIGN;
1710 				m_adj(m, ETHER_ALIGN);
1711 
1712 				usbd_copy_out(pc, offset, m->m_data, temp);
1713 
1714 				/* enqueue */
1715 				uether_rxmbuf(&sc->sc_ue, m, temp);
1716 
1717 				sumdata += temp;
1718 			} else {
1719 				if_inc_counter(ifp, IFCOUNTER_IERRORS, 1);
1720 			}
1721 		}
1722 
1723 		DPRINTFN(1, "Efficiency: %u/%u bytes\n", sumdata, actlen);
1724 
1725 	case USB_ST_SETUP:
1726 tr_setup:
1727 		usbd_xfer_set_frame_len(xfer, 0, sc->sc_ncm.rx_max);
1728 		usbd_xfer_set_frames(xfer, 1);
1729 		usbd_transfer_submit(xfer);
1730 		uether_rxflush(&sc->sc_ue);	/* must be last */
1731 		break;
1732 
1733 	default:			/* Error */
1734 		DPRINTFN(1, "error = %s\n",
1735 		    usbd_errstr(error));
1736 
1737 		if (error != USB_ERR_CANCELLED) {
1738 tr_stall:
1739 			if (usbd_get_mode(sc->sc_ue.ue_udev) == USB_MODE_HOST) {
1740 				/* try to clear stall first */
1741 				usbd_xfer_set_stall(xfer);
1742 				usbd_xfer_set_frames(xfer, 0);
1743 				usbd_transfer_submit(xfer);
1744 			}
1745 		}
1746 		break;
1747 	}
1748 }
1749 #endif
1750