• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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: releng/12.2/sys/dev/usb/net/if_cdce.c 328162 2018-01-19 12:59:14Z hselasky $");
52 
53 #include "los_crc32.h"
54 
55 #include "implementation/global_implementation.h"
56 #include "usb_ethernet.h"
57 #include "if_cdcereg.h"
58 
59 static device_probe_t cdce_probe;
60 static device_attach_t cdce_attach;
61 static device_detach_t cdce_detach;
62 static device_suspend_t cdce_suspend;
63 static device_resume_t cdce_resume;
64 static usb_handle_request_t cdce_handle_request;
65 
66 static usb_callback_t cdce_bulk_write_callback;
67 static usb_callback_t cdce_bulk_read_callback;
68 static usb_callback_t cdce_intr_read_callback;
69 static usb_callback_t cdce_intr_write_callback;
70 
71 #if CDCE_HAVE_NCM
72 static usb_callback_t cdce_ncm_bulk_write_callback;
73 static usb_callback_t cdce_ncm_bulk_read_callback;
74 #endif
75 
76 static uether_fn_t cdce_attach_post;
77 static uether_fn_t cdce_init;
78 static uether_fn_t cdce_stop;
79 static uether_fn_t cdce_start;
80 static uether_fn_t cdce_setmulti;
81 static uether_fn_t cdce_setpromisc;
82 
83 static uint32_t cdce_m_crc32(struct pbuf *, uint32_t, uint32_t);
84 
85 #undef USB_DEBUG_VAR
86 #define	USB_DEBUG_VAR	cdce_debug
87 #ifdef LOSCFG_USB_DEBUG
88 static int cdce_debug = 0;
89 void
usb_cdce_debug_func(int level)90 usb_cdce_debug_func(int level)
91 {
92 	cdce_debug = level;
93 	PRINTK("The level of usb cdce debug is %d\n", level);
94 }
95 DEBUG_MODULE(cdce, usb_cdce_debug_func);
96 #endif
97 
98 static const struct usb_config cdce_config[CDCE_N_TRANSFER] = {
99 
100 	[CDCE_BULK_RX] = {
101 		.type = UE_BULK,
102 		.endpoint = UE_ADDR_ANY,
103 		.direction = UE_DIR_RX,
104 		.if_index = 0,
105 		.frames = CDCE_FRAMES_MAX,
106 		.bufsize = (CDCE_FRAMES_MAX * MCLBYTES),
107 		.flags = {.pipe_bof = 1,.short_frames_ok = 1,.short_xfer_ok = 1,.ext_buffer = 1,},
108 		.callback = cdce_bulk_read_callback,
109 		.timeout = 0,	/* no timeout */
110 		.usb_mode = USB_MODE_DUAL,	/* both modes */
111 	},
112 
113 	[CDCE_BULK_TX] = {
114 		.type = UE_BULK,
115 		.endpoint = UE_ADDR_ANY,
116 		.direction = UE_DIR_TX,
117 		.if_index = 0,
118 		.frames = CDCE_FRAMES_MAX,
119 		.bufsize = (CDCE_FRAMES_MAX * MCLBYTES),
120 		.flags = {.pipe_bof = 1,.force_short_xfer = 1,.ext_buffer = 1,},
121 		.callback = cdce_bulk_write_callback,
122 		.timeout = 10000,	/* 10 seconds */
123 		.usb_mode = USB_MODE_DUAL,	/* both modes */
124 	},
125 
126 	[CDCE_INTR_RX] = {
127 		.type = UE_INTERRUPT,
128 		.endpoint = UE_ADDR_ANY,
129 		.direction = UE_DIR_RX,
130 		.if_index = 1,
131 		.bufsize = CDCE_IND_SIZE_MAX,
132 		.flags = {.pipe_bof = 1,.short_xfer_ok = 1,.no_pipe_ok = 1,},
133 		.callback = cdce_intr_read_callback,
134 		.timeout = 0,
135 		.usb_mode = USB_MODE_HOST,
136 	},
137 
138 	[CDCE_INTR_TX] = {
139 		.type = UE_INTERRUPT,
140 		.endpoint = UE_ADDR_ANY,
141 		.direction = UE_DIR_TX,
142 		.if_index = 1,
143 		.bufsize = CDCE_IND_SIZE_MAX,
144 		.flags = {.pipe_bof = 1,.force_short_xfer = 1,.no_pipe_ok = 1,},
145 		.callback = cdce_intr_write_callback,
146 		.timeout = 10000,	/* 10 seconds */
147 		.usb_mode = USB_MODE_DEVICE,
148 	},
149 };
150 
151 #if CDCE_HAVE_NCM
152 static const struct usb_config cdce_ncm_config[CDCE_N_TRANSFER] = {
153 
154 	[CDCE_BULK_RX] = {
155 		.type = UE_BULK,
156 		.endpoint = UE_ADDR_ANY,
157 		.direction = UE_DIR_RX,
158 		.if_index = 0,
159 		.frames = CDCE_NCM_RX_FRAMES_MAX,
160 		.bufsize = (CDCE_NCM_RX_FRAMES_MAX * CDCE_NCM_RX_MAXLEN),
161 		.flags = {.pipe_bof = 1,.short_frames_ok = 1,.short_xfer_ok = 1,},
162 		.callback = cdce_ncm_bulk_read_callback,
163 		.timeout = 0,	/* no timeout */
164 		.usb_mode = USB_MODE_DUAL,	/* both modes */
165 	},
166 
167 	[CDCE_BULK_TX] = {
168 		.type = UE_BULK,
169 		.endpoint = UE_ADDR_ANY,
170 		.direction = UE_DIR_TX,
171 		.if_index = 0,
172 		.frames = CDCE_NCM_TX_FRAMES_MAX,
173 		.bufsize = (CDCE_NCM_TX_FRAMES_MAX * CDCE_NCM_TX_MAXLEN),
174 		.flags = {.pipe_bof = 1,},
175 		.callback = cdce_ncm_bulk_write_callback,
176 		.timeout = 10000,	/* 10 seconds */
177 		.usb_mode = USB_MODE_DUAL,	/* both modes */
178 	},
179 
180 	[CDCE_INTR_RX] = {
181 		.type = UE_INTERRUPT,
182 		.endpoint = UE_ADDR_ANY,
183 		.direction = UE_DIR_RX,
184 		.if_index = 1,
185 		.bufsize = CDCE_IND_SIZE_MAX,
186 		.flags = {.pipe_bof = 1,.short_xfer_ok = 1,.no_pipe_ok = 1,},
187 		.callback = cdce_intr_read_callback,
188 		.timeout = 0,
189 		.usb_mode = USB_MODE_HOST,
190 	},
191 
192 	[CDCE_INTR_TX] = {
193 		.type = UE_INTERRUPT,
194 		.endpoint = UE_ADDR_ANY,
195 		.direction = UE_DIR_TX,
196 		.if_index = 1,
197 		.bufsize = CDCE_IND_SIZE_MAX,
198 		.flags = {.pipe_bof = 1,.force_short_xfer = 1,.no_pipe_ok = 1,},
199 		.callback = cdce_intr_write_callback,
200 		.timeout = 10000,	/* 10 seconds */
201 		.usb_mode = USB_MODE_DEVICE,
202 	},
203 };
204 #endif
205 
206 static device_method_t cdce_methods[] = {
207 	/* USB interface */
208 	DEVMETHOD(usb_handle_request, cdce_handle_request),
209 
210 	/* Device interface */
211 	DEVMETHOD(device_probe, cdce_probe),
212 	DEVMETHOD(device_attach, cdce_attach),
213 	DEVMETHOD(device_detach, cdce_detach),
214 	DEVMETHOD(device_suspend, cdce_suspend),
215 	DEVMETHOD(device_resume, cdce_resume),
216 
217 	DEVMETHOD_END
218 };
219 
220 static driver_t cdce_driver = {
221 	.name = "cdce",
222 	.methods = cdce_methods,
223 	.size = sizeof(struct cdce_softc),
224 };
225 
226 static devclass_t cdce_devclass;
227 
228 DRIVER_MODULE(cdce, uhub, cdce_driver, cdce_devclass, NULL, 0);
229 
230 static const struct usb_ether_methods cdce_ue_methods = {
231 	.ue_attach_post = cdce_attach_post,
232 	.ue_start = cdce_start,
233 	.ue_init = cdce_init,
234 	.ue_stop = cdce_stop,
235 	.ue_setmulti = cdce_setmulti,
236 	.ue_setpromisc = cdce_setpromisc,
237 };
238 
239 static const STRUCT_USB_HOST_ID cdce_host_devs[] = {
240 
241 };
242 
243 static const STRUCT_USB_DUAL_ID cdce_dual_devs[] = {
244 	{USB_IF_CSI(UICLASS_CDC, UISUBCLASS_ETHERNET_NETWORKING_CONTROL_MODEL, 0)},
245 	{USB_IF_CSI(UICLASS_CDC, UISUBCLASS_MOBILE_DIRECT_LINE_MODEL, 0)},
246 	{USB_IF_CSI(UICLASS_CDC, UISUBCLASS_NETWORK_CONTROL_MODEL, 0)},
247 };
248 
249 #if CDCE_HAVE_NCM
250 /*------------------------------------------------------------------------*
251  *	cdce_ncm_init
252  *
253  * Return values:
254  * 0: Success
255  * Else: Failure
256  *------------------------------------------------------------------------*/
257 static uint8_t
cdce_ncm_init(struct cdce_softc * sc)258 cdce_ncm_init(struct cdce_softc *sc)
259 {
260 	struct usb_ncm_parameters temp;
261 	struct usb_device_request req;
262 	struct usb_ncm_func_descriptor *ufd;
263 	uint8_t value[8];
264 	int err;
265 
266 	DPRINTFN(1, "\n");
267 
268 	ufd = usbd_find_descriptor(sc->sc_ue.ue_udev, NULL,
269 							    sc->sc_ifaces_index[1], UDESC_CS_INTERFACE, 0xFF,
270 							    UCDC_NCM_FUNC_DESC_SUBTYPE, 0xFF);
271 
272 	/* verify length of NCM functional descriptor */
273 	if (ufd != NULL) {
274 		if (ufd->bLength < sizeof(*ufd))
275 			ufd = NULL;
276 		else
277 			DPRINTFN(1, "Found NCM functional descriptor.\n");
278 	}
279 
280 	req.bmRequestType = UT_READ_CLASS_INTERFACE;
281 	req.bRequest = UCDC_NCM_GET_NTB_PARAMETERS;
282 	USETW(req.wValue, 0);
283 	req.wIndex[0] = sc->sc_ifaces_index[1];
284 	req.wIndex[1] = 0;
285 	USETW(req.wLength, sizeof(temp));
286 
287 	err = usbd_do_request_flags(sc->sc_ue.ue_udev, NULL, &req,
288 							    &temp, 0, NULL, 1000 /* ms */);
289 	if (err){
290 		DPRINTFN(1, "request error!\n");
291 		return (1);
292 	}
293 	/* Read correct set of parameters according to device mode */
294 	DPRINTFN(1, "line %d!\n",__LINE__);
295 
296 	if (usbd_get_mode(sc->sc_ue.ue_udev) == USB_MODE_HOST) {
297 		sc->sc_ncm.rx_max = UGETDW(temp.dwNtbInMaxSize);
298 		sc->sc_ncm.tx_max = UGETDW(temp.dwNtbOutMaxSize);
299 		sc->sc_ncm.tx_remainder = UGETW(temp.wNdpOutPayloadRemainder);
300 		sc->sc_ncm.tx_modulus = UGETW(temp.wNdpOutDivisor);
301 		sc->sc_ncm.tx_struct_align = UGETW(temp.wNdpOutAlignment);
302 		sc->sc_ncm.tx_nframe = UGETW(temp.wNtbOutMaxDatagrams);
303 	} else {
304 		sc->sc_ncm.rx_max = UGETDW(temp.dwNtbOutMaxSize);
305 		sc->sc_ncm.tx_max = UGETDW(temp.dwNtbInMaxSize);
306 		sc->sc_ncm.tx_remainder = UGETW(temp.wNdpInPayloadRemainder);
307 		sc->sc_ncm.tx_modulus = UGETW(temp.wNdpInDivisor);
308 		sc->sc_ncm.tx_struct_align = UGETW(temp.wNdpInAlignment);
309 		sc->sc_ncm.tx_nframe = UGETW(temp.wNtbOutMaxDatagrams);
310 	}
311 
312 	/* Verify maximum receive length */
313 
314 	if ((sc->sc_ncm.rx_max < 32) ||
315 	    (sc->sc_ncm.rx_max > CDCE_NCM_RX_MAXLEN)) {
316 		DPRINTFN(1, "Using default maximum receive length\n");
317 		sc->sc_ncm.rx_max = CDCE_NCM_RX_MAXLEN;
318 	}
319 
320 	/* Verify maximum transmit length */
321 
322 	if ((sc->sc_ncm.tx_max < 32) ||
323 	    (sc->sc_ncm.tx_max > CDCE_NCM_TX_MAXLEN)) {
324 		DPRINTFN(1, "Using default maximum transmit length\n");
325 		sc->sc_ncm.tx_max = CDCE_NCM_TX_MAXLEN;
326 	}
327 
328 	/*
329 	 * Verify that the structure alignment is:
330 	 * - power of two
331 	 * - not greater than the maximum transmit length
332 	 * - not less than four bytes
333 	 */
334 	if ((sc->sc_ncm.tx_struct_align < 4) ||
335 	    (sc->sc_ncm.tx_struct_align !=
336 	    ((-sc->sc_ncm.tx_struct_align) & sc->sc_ncm.tx_struct_align)) ||
337 	    (sc->sc_ncm.tx_struct_align >= sc->sc_ncm.tx_max)) {
338 		DPRINTFN(1, "Using default other alignment: 4 bytes\n");
339 		sc->sc_ncm.tx_struct_align = 4;
340 	}
341 
342 	/*
343 	 * Verify that the payload alignment is:
344 	 * - power of two
345 	 * - not greater than the maximum transmit length
346 	 * - not less than four bytes
347 	 */
348 	if ((sc->sc_ncm.tx_modulus < 4) ||
349 	    (sc->sc_ncm.tx_modulus !=
350 	    ((-sc->sc_ncm.tx_modulus) & sc->sc_ncm.tx_modulus)) ||
351 	    (sc->sc_ncm.tx_modulus >= sc->sc_ncm.tx_max)) {
352 		DPRINTFN(1, "Using default transmit modulus: 4 bytes\n");
353 		sc->sc_ncm.tx_modulus = 4;
354 	}
355 
356 	/* Verify that the payload remainder */
357 
358 	if ((sc->sc_ncm.tx_remainder >= sc->sc_ncm.tx_modulus)) {
359 		DPRINTFN(1, "Using default transmit remainder: 0 bytes\n");
360 		sc->sc_ncm.tx_remainder = 0;
361 	}
362 
363 	/*
364 	 * Offset the TX remainder so that IP packet payload starts at
365 	 * the tx_modulus. This is not too clear in the specification.
366 	 */
367 
368 	sc->sc_ncm.tx_remainder =
369 	    (sc->sc_ncm.tx_remainder - ETHER_HDR_LEN) &
370 	    (sc->sc_ncm.tx_modulus - 1);
371 
372 	/* Verify max datagrams */
373 
374 	if (sc->sc_ncm.tx_nframe == 0 ||
375 	    sc->sc_ncm.tx_nframe > (CDCE_NCM_SUBFRAMES_MAX - 1)) {
376 		DPRINTFN(1, "Using default max "
377 		    "subframes: %u units\n", CDCE_NCM_SUBFRAMES_MAX - 1);
378 		/* need to reserve one entry for zero padding */
379 		sc->sc_ncm.tx_nframe = (CDCE_NCM_SUBFRAMES_MAX - 1);
380 	}
381 
382 	/* Additional configuration, will fail in device side mode, which is OK. */
383 
384 	req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
385 	req.bRequest = UCDC_NCM_SET_NTB_INPUT_SIZE;
386 	USETW(req.wValue, 0);
387 	req.wIndex[0] = sc->sc_ifaces_index[1];
388 	req.wIndex[1] = 0;
389 
390 	if ((ufd != NULL) &&
391 	    (ufd->bmNetworkCapabilities & UCDC_NCM_CAP_MAX_DGRAM)) {
392 		USETW(req.wLength, 8);
393 		USETDW(value, sc->sc_ncm.rx_max);
394 		USETW(value + 4, (CDCE_NCM_SUBFRAMES_MAX - 1));
395 		USETW(value + 6, 0);
396 	} else {
397 		USETW(req.wLength, 4);
398 		USETDW(value, sc->sc_ncm.rx_max);
399 	}
400 
401 	err = usbd_do_request_flags(sc->sc_ue.ue_udev, NULL, &req,
402 							    &value, 0, NULL, 1000 /* ms */);
403 	if (err) {
404 		DPRINTFN(1, "Setting input size "
405 			    "to %u failed.\n", sc->sc_ncm.rx_max);
406 	}
407 
408 	req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
409 	req.bRequest = UCDC_NCM_SET_CRC_MODE;
410 	USETW(req.wValue, 0);	/* no CRC */
411 	req.wIndex[0] = sc->sc_ifaces_index[1];
412 	req.wIndex[1] = 0;
413 	USETW(req.wLength, 0);
414 
415 	err = usbd_do_request_flags(sc->sc_ue.ue_udev, NULL, &req,
416 	    NULL, 0, NULL, 1000 /* ms */);
417 	if (err) {
418 		DPRINTFN(1, "Setting CRC mode to off failed.\n");
419 	}
420 
421 	req.bmRequestType = UT_WRITE_CLASS_INTERFACE;
422 	req.bRequest = UCDC_NCM_SET_NTB_FORMAT;
423 	USETW(req.wValue, 0);	/* NTB-16 */
424 	req.wIndex[0] = sc->sc_ifaces_index[1];
425 	req.wIndex[1] = 0;
426 	USETW(req.wLength, 0);
427 
428 	err = usbd_do_request_flags(sc->sc_ue.ue_udev, NULL, &req,
429 	    NULL, 0, NULL, 1000 /* ms */);
430 	if (err) {
431 		DPRINTFN(1, "Setting NTB format to 16-bit failed.\n");
432 	}
433 
434 	DPRINTFN(1, " -->end!\n");
435 
436 	return (0);		/* success */
437 }
438 #endif
439 
440 static int
cdce_probe(device_t dev)441 cdce_probe(device_t dev)
442 {
443 	struct usb_attach_arg *uaa = (struct usb_attach_arg *)device_get_ivars(dev);
444 	int error;
445 
446 	error = usbd_lookup_id_by_uaa(cdce_host_devs, sizeof(cdce_host_devs), uaa);
447 
448 	if (error)
449 		error = usbd_lookup_id_by_uaa(cdce_dual_devs, sizeof(cdce_dual_devs), uaa);
450 	return (error);
451 }
452 
453 static void
cdce_attach_post(struct usb_ether * ue)454 cdce_attach_post(struct usb_ether *ue)
455 {
456 	/* no-op */
457 	return;
458 }
459 
460 static int
cdce_attach(device_t dev)461 cdce_attach(device_t dev)
462 {
463 	struct cdce_softc *sc = (struct cdce_softc *)device_get_softc(dev);
464 	struct usb_ether *ue = &sc->sc_ue;
465 	struct usb_attach_arg *uaa = (struct usb_attach_arg *)device_get_ivars(dev);
466 	struct usb_interface *iface;
467 	const struct usb_cdc_union_descriptor *ud;
468 	const struct usb_interface_descriptor *id;
469 	const struct usb_cdc_ethernet_descriptor *ued;
470 	const struct usb_config *pcfg;
471 	uint32_t seed;
472 	usb_error_t error;
473 	uint8_t i;
474 	uint8_t data_iface_no;
475 	char eaddr_str[5 * NETIF_MAX_HWADDR_LEN];	/* approx */
476 
477 	DPRINTFN(1, "\n");
478 
479 	sc->sc_flags = USB_GET_DRIVER_INFO(uaa);
480 	sc->sc_ue.ue_udev = uaa->device;
481 
482 	device_set_usb_desc(dev);
483 
484 	mtx_init(&sc->sc_mtx, device_get_nameunit(dev), NULL, MTX_DEF);
485 
486 	ud = (const struct usb_cdc_union_descriptor *)usbd_find_descriptor
487 	    (uaa->device, NULL, uaa->info.bIfaceIndex, UDESC_CS_INTERFACE,
488 	    0xFF, UDESCSUB_CDC_UNION, 0xFF);
489 
490 	if ((ud == NULL) || (ud->bLength < sizeof(*ud)) ||
491 	    (sc->sc_flags & CDCE_FLAG_NO_UNION)) {
492 		DPRINTFN(1, "No union descriptor!\n");
493 		sc->sc_ifaces_index[0] = uaa->info.bIfaceIndex;
494 		sc->sc_ifaces_index[1] = uaa->info.bIfaceIndex;
495 		goto alloc_transfers;
496 	}
497 	data_iface_no = ud->bSlaveInterface[0];
498 	DPRINTFN(1, "data_iface_no = %d!\n", data_iface_no);
499 
500 	for (i = 0;; i++) {
501 
502 		iface = usbd_get_iface(uaa->device, i);
503 
504 		if (iface) {
505 
506 			id = usbd_get_interface_descriptor(iface);
507 
508 			if (id && (id->bInterfaceNumber == data_iface_no)) {
509 				sc->sc_ifaces_index[0] = i;
510 				sc->sc_ifaces_index[1] = uaa->info.bIfaceIndex;
511 				DPRINTFN(1, "index 0 = %d, index 1 = %d!\n", i, uaa->info.bIfaceIndex);
512 				usbd_set_parent_iface(uaa->device, i, uaa->info.bIfaceIndex);
513 				break;
514 			}
515 		} else {
516 			device_printf(dev, "no data interface found\n");
517 			goto detach;
518 		}
519 	}
520 
521 	/*
522 	 * <quote>
523 	 *
524 	 *  The Data Class interface of a networking device shall have
525 	 *  a minimum of two interface settings. The first setting
526 	 *  (the default interface setting) includes no endpoints and
527 	 *  therefore no networking traffic is exchanged whenever the
528 	 *  default interface setting is selected. One or more
529 	 *  additional interface settings are used for normal
530 	 *  operation, and therefore each includes a pair of endpoints
531 	 *  (one IN, and one OUT) to exchange network traffic. Select
532 	 *  an alternate interface setting to initialize the network
533 	 *  aspects of the device and to enable the exchange of
534 	 *  network traffic.
535 	 *
536 	 * </quote>
537 	 *
538 	 * Some devices, most notably cable modems, include interface
539 	 * settings that have no IN or OUT endpoint, therefore loop
540 	 * through the list of all available interface settings
541 	 * looking for one with both IN and OUT endpoints.
542 	 */
543 
544 alloc_transfers:
545 
546 	pcfg = cdce_config;	/* Default Configuration */
547 
548 	for (i = 0; i != 32; i++) {
549 		error = usbd_set_alt_interface_index(uaa->device,
550 		    sc->sc_ifaces_index[0], i);
551 		if (error) {
552 			break;
553 		}
554 
555 #if CDCE_HAVE_NCM
556 		if ((i == 0) && (cdce_ncm_init(sc) == 0))
557 			pcfg = cdce_ncm_config;
558 #endif
559 		error = usbd_transfer_setup(uaa->device,
560 		    sc->sc_ifaces_index, sc->sc_xfer,
561 		    pcfg, CDCE_N_TRANSFER, sc, &sc->sc_mtx);
562 
563 		if (error == 0) {
564 			break;
565 		}
566 	}
567 
568 	if (error || (i == 32)) {
569 		device_printf(dev, "No valid alternate "
570 		    "setting found\n");
571 		goto detach;
572 	}
573 
574 	ued = (const struct usb_cdc_ethernet_descriptor *)usbd_find_descriptor
575 	    (uaa->device, NULL, uaa->info.bIfaceIndex, UDESC_CS_INTERFACE,
576 	    0xFF, UDESCSUB_CDC_ENF, 0xFF);
577 
578 	if ((ued == NULL) || (ued->bLength < sizeof(*ued))) {
579 		error = USB_ERR_INVAL;
580 	} else {
581 		error = usbd_req_get_string_any(uaa->device, NULL,
582 		    eaddr_str, sizeof(eaddr_str), ued->iMacAddress);
583 	}
584 
585 	if (error) {
586 
587 		/* fake MAC address */
588 
589 		device_printf(dev, "faking MAC address\n");
590 		seed = CUR_TICKS;
591 		(void)memcpy_s(&sc->sc_ue.ue_eaddr[1], (NETIF_MAX_HWADDR_LEN - 2), &seed, sizeof(uint32_t));
592 		sc->sc_ue.ue_eaddr[0] = 0x2a;
593 		sc->sc_ue.ue_eaddr[5] = device_get_unit(dev);
594 
595 	} else {
596 
597 		(void)memset_s(sc->sc_ue.ue_eaddr, sizeof(sc->sc_ue.ue_eaddr), 0, sizeof(sc->sc_ue.ue_eaddr));
598 
599 		for (i = 0; i != (NETIF_MAX_HWADDR_LEN * 2); i++) {
600 
601 			char c = eaddr_str[i];
602 
603 			if (('0' <= c) && (c <= '9'))
604 				c -= '0';
605 			else if (c != 0)
606 				c -= 'A' - 10;
607 			else
608 				break;
609 
610 			c &= 0xf;
611 
612 			if ((i & 1) == 0)
613 				c <<= 4;
614 			sc->sc_ue.ue_eaddr[i / 2] |= c;
615 		}
616 
617 		if (uaa->usb_mode == USB_MODE_DEVICE) {
618 			/*
619 			 * Do not use the same MAC address like the peer !
620 			 */
621 			sc->sc_ue.ue_eaddr[5] ^= 0xFF;
622 		}
623 	}
624 
625 	ue->ue_sc = sc;
626 	ue->ue_dev = dev;
627 	ue->ue_udev = uaa->device;
628 	ue->ue_mtx = &sc->sc_mtx;
629 	ue->ue_methods = &cdce_ue_methods;
630 
631 	error = (usb_error_t)uether_ifattach(ue);
632 	if (error) {
633 		device_printf(dev, "could not attach interface\n");
634 		goto detach;
635 	}
636 	return (0);			/* success */
637 
638 detach:
639 	(void)cdce_detach(dev);
640 	return (ENXIO);			/* failure */
641 }
642 
643 static int
cdce_detach(device_t dev)644 cdce_detach(device_t dev)
645 {
646 	struct cdce_softc *sc = (struct cdce_softc *)device_get_softc(dev);
647 	struct usb_ether *ue = &sc->sc_ue;
648 
649 	/* stop all USB transfers first */
650 	usbd_transfer_unsetup(sc->sc_xfer, CDCE_N_TRANSFER);
651 	uether_ifdetach(ue);
652 	mtx_destroy(&sc->sc_mtx);
653 
654 	return (0);
655 }
656 
657 static void
cdce_start(struct usb_ether * ue)658 cdce_start(struct usb_ether *ue)
659 {
660 	struct cdce_softc *sc = (struct cdce_softc *)uether_getsc(ue);
661 
662 	DPRINTFN(1, "\n");
663 	/*
664 	 * Start the USB transfers, if not already started:
665 	 */
666 	usbd_transfer_start(sc->sc_xfer[CDCE_BULK_TX]);
667 	usbd_transfer_start(sc->sc_xfer[CDCE_BULK_RX]);
668 }
669 
670 static void
cdce_free_queue(struct pbuf ** ppm,uint8_t n)671 cdce_free_queue(struct pbuf **ppm, uint8_t n)
672 {
673 	uint8_t x;
674 	for (x = 0; x != n; x++) {
675 		if (ppm[x] != NULL) {
676 			uether_freebuf(ppm[x]);
677 			ppm[x] = NULL;
678 		}
679 	}
680 }
681 
682 /*
683  * There is something wrong with the original function and delete the code;
684  * If you want to use, you should realize it again.
685  */
686 int
pbuf_append(struct pbuf * m0,int length,void * cp)687 pbuf_append(struct pbuf *m0, int length, void* cp)
688 {
689 	return (0);
690 }
691 
692 
693 
694 static void
cdce_bulk_write_callback(struct usb_xfer * xfer,usb_error_t error)695 cdce_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error)
696 {
697 	struct cdce_softc *sc = (struct cdce_softc *)usbd_xfer_softc(xfer);
698 	struct usb_ether *ue = &sc->sc_ue;
699 	struct pbuf *m;
700 	uint32_t crc;
701 	uint8_t x;
702 	int actlen, aframes;
703 
704 	DPRINTFN(10, "\n");
705 
706 	usbd_xfer_status(xfer, &actlen, NULL, &aframes, NULL);
707 
708 	switch (USB_GET_STATE(xfer)) {
709 	case USB_ST_TRANSFERRED:
710 		DPRINTFN(10, "transfer complete: %u bytes in %u frames\n",actlen, aframes);
711 
712 		/* free all previous TX buffers */
713 		cdce_free_queue(sc->sc_tx_buf, CDCE_FRAMES_MAX);
714 
715 		/* FALLTHROUGH */
716 	case USB_ST_SETUP:
717 tr_setup:
718 		for (x = 0; x != CDCE_FRAMES_MAX; x++) {
719 			UE_LOCK(ue);
720 			IF_DEQUEUE(&(ue->ue_txq), m);
721 			UE_UNLOCK(ue);
722 			if (m == NULL)
723 				break;
724 
725 			if (sc->sc_flags & CDCE_FLAG_ZAURUS) {
726 				/*
727 				 * Zaurus wants a 32-bit CRC appended
728 				 * to every frame
729 				 */
730 
731 				crc = cdce_m_crc32(m, 0, m->len);
732 				crc = htole32(crc);
733 
734 				if (!pbuf_append(m, 4, (void *)&crc)) {
735 					free(m);
736 					continue;
737 				}
738 			}
739 
740 			sc->sc_tx_buf[x] = m;
741 			usbd_xfer_set_frame_data(xfer, x, m->payload, m->len);
742 
743 			/*
744 			 * If there's a BPF listener, bounce a copy of
745 			 * this frame to him:
746 			 */
747 		}
748 		if (x != 0) {
749 			usbd_xfer_set_frames(xfer, x);
750 			usbd_transfer_submit(xfer);
751 		}
752 		break;
753 
754 	default:			/* Error */
755 		DPRINTFN(11, "transfer error, %s\n",usbd_errstr(error));
756 		PRINTK("transfer error, %s\n",usbd_errstr(error));
757 
758 		/* free all previous TX buffers */
759 		cdce_free_queue(sc->sc_tx_buf, CDCE_FRAMES_MAX);
760 
761 		if (error != USB_ERR_CANCELLED) {
762 			/* try to clear stall first */
763 			usbd_xfer_set_stall(xfer);
764 			goto tr_setup;
765 		}
766 		break;
767 	}
768 }
769 
770 static uint32_t
cdce_m_crc32(struct pbuf * m,uint32_t src_offset,uint32_t src_len)771 cdce_m_crc32(struct pbuf *m, uint32_t src_offset, uint32_t src_len)
772 {
773 	uint32_t crc = 0xFFFFFFFF;
774 
775 	crc = crc32(crc, m->payload, src_len);
776 	return (crc ^ 0xFFFFFFFF);
777 }
778 
779 static void
cdce_init(struct usb_ether * ue)780 cdce_init(struct usb_ether *ue)
781 {
782 	struct cdce_softc *sc = (struct cdce_softc *)uether_getsc(ue);
783 	struct los_eth_driver *ifp = ue->ue_drv_sc;
784 	struct eth_drv_sc *drv_sc = (struct eth_drv_sc *)ifp->driver_context;
785 
786 	DPRINTFN(1, "\n");
787 
788 	CDCE_LOCK_ASSERT(sc, MA_OWNED);
789 
790 	drv_sc->state |= IFF_DRV_RUNNING;
791 
792 	/* start interrupt transfer */
793 	usbd_transfer_start(sc->sc_xfer[CDCE_INTR_RX]);
794 	usbd_transfer_start(sc->sc_xfer[CDCE_INTR_TX]);
795 
796 	/*
797 	 * Stall data write direction, which depends on USB mode.
798 	 *
799 	 * Some USB host stacks (e.g. Mac OS X) don't clears stall
800 	 * bit as it should, so set it in our host mode only.
801 	 */
802 	if (usbd_get_mode(sc->sc_ue.ue_udev) == USB_MODE_HOST)
803 		usbd_xfer_set_stall(sc->sc_xfer[CDCE_BULK_TX]);
804 
805 	/* start data transfers */
806 	cdce_start(ue);
807 }
808 
809 static void
cdce_stop(struct usb_ether * ue)810 cdce_stop(struct usb_ether *ue)
811 {
812 	struct cdce_softc *sc = (struct cdce_softc *)uether_getsc(ue);
813 	struct los_eth_driver *ifp = ue->ue_drv_sc;
814 	struct eth_drv_sc *drv_sc = (struct eth_drv_sc *)ifp->driver_context;
815 
816 	DPRINTFN(1, "\n");
817 
818 	CDCE_LOCK_ASSERT(sc, MA_OWNED);
819 
820 	drv_sc->state &= ~IFF_DRV_RUNNING;
821 
822 	/*
823 	 * stop all the transfers, if not already stopped:
824 	 */
825 	usbd_transfer_stop(sc->sc_xfer[CDCE_BULK_RX]);
826 	usbd_transfer_stop(sc->sc_xfer[CDCE_BULK_TX]);
827 	usbd_transfer_stop(sc->sc_xfer[CDCE_INTR_RX]);
828 	usbd_transfer_stop(sc->sc_xfer[CDCE_INTR_TX]);
829 }
830 
831 static void
cdce_setmulti(struct usb_ether * ue)832 cdce_setmulti(struct usb_ether *ue)
833 {
834 	/* no-op */
835 	return;
836 }
837 
838 static void
cdce_setpromisc(struct usb_ether * ue)839 cdce_setpromisc(struct usb_ether *ue)
840 {
841 	/* no-op */
842 	return;
843 }
844 
845 static int
cdce_suspend(device_t dev)846 cdce_suspend(device_t dev)
847 {
848 	device_printf(dev, "Suspending\n");
849 	return (0);
850 }
851 
852 static int
cdce_resume(device_t dev)853 cdce_resume(device_t dev)
854 {
855 	device_printf(dev, "Resuming\n");
856 	return (0);
857 }
858 
859 static void
cdce_bulk_read_callback(struct usb_xfer * xfer,usb_error_t error)860 cdce_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error)
861 {
862 	struct cdce_softc *sc = (struct cdce_softc *)usbd_xfer_softc(xfer);
863 	struct pbuf *m;
864 	uint8_t x;
865 	int actlen;
866 	int aframes;
867 	int len;
868 
869 	DPRINTFN(1, "\n");
870 	usbd_xfer_status(xfer, &actlen, NULL, &aframes, NULL);
871 
872 	switch (USB_GET_STATE(xfer)) {
873 	case USB_ST_TRANSFERRED:
874 
875 		DPRINTF("received %u bytes in %u frames\n", actlen, aframes);
876 
877 		for (x = 0; x != aframes; x++) {
878 
879 			m = sc->sc_rx_buf[x];
880 			sc->sc_rx_buf[x] = NULL;
881 			len = usbd_xfer_frame_len(xfer, x);
882 
883 			/* Strip off CRC added by Zaurus, if any */
884 			if ((sc->sc_flags & CDCE_FLAG_ZAURUS) && len >= 14)
885 				len -= 4;
886 
887 			if (len < (int)sizeof(struct ether_header)) {
888 				uether_freebuf(m);
889 				continue;
890 			}
891 			/* queue up mbuf */
892 			(void)uether_rxmbuf(&sc->sc_ue, m, len);
893 		}
894 
895 		/* FALLTHROUGH */
896 	case USB_ST_SETUP:
897 		/*
898 		 * TODO: Implement support for multi frame transfers,
899 		 * when the USB hardware supports it.
900 		 */
901 		for (x = 0; x != 1; x++) { /* why x is alway 0? */
902 			if (sc->sc_rx_buf[x] == NULL) {
903 				m = uether_newbuf(MAX_ETH_MSG);
904 				if (m == NULL)
905 					goto tr_stall;
906 				sc->sc_rx_buf[x] = m;
907 			} else {
908 				m = sc->sc_rx_buf[x];
909 			}
910 
911 			DPRINTFN(1, "new buffer length %d\n", m->len);
912 			usbd_xfer_set_frame_data(xfer, x, m->payload, m->len);
913 		}
914 		/* set number of frames and start hardware */
915 		usbd_xfer_set_frames(xfer, x);
916 		usbd_transfer_submit(xfer);
917 		/* flush any received frames */
918 		uether_rxflush(&sc->sc_ue);
919 		break;
920 
921 	default:			/* Error */
922 		DPRINTF("error = %s\n",usbd_errstr(error));
923 
924 		if (error != USB_ERR_CANCELLED) {
925 tr_stall:
926 			/* try to clear stall first */
927 			usbd_xfer_set_stall(xfer);
928 			usbd_xfer_set_frames(xfer, 0);
929 			usbd_transfer_submit(xfer);
930 			break;
931 		}
932 
933 		/* need to free the RX-mbufs when we are cancelled */
934 		cdce_free_queue(sc->sc_rx_buf, CDCE_FRAMES_MAX);
935 		break;
936 	}
937 }
938 
939 static void
cdce_intr_read_callback(struct usb_xfer * xfer,usb_error_t error)940 cdce_intr_read_callback(struct usb_xfer *xfer, usb_error_t error)
941 {
942 	int actlen;
943 
944 	DPRINTFN(1, "\n");
945 
946 	usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL);
947 
948 	switch (USB_GET_STATE(xfer)) {
949 	case USB_ST_TRANSFERRED:
950 
951 		DPRINTF("cdce_intr_read_callback Received %d bytes\n", actlen);
952 
953 		/* TODO: decode some indications */
954 
955 		/* FALLTHROUGH */
956 	case USB_ST_SETUP:
957 tr_setup:
958 		usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
959 		usbd_transfer_submit(xfer);
960 		break;
961 
962 	default:			/* Error */
963 		if (error != USB_ERR_CANCELLED) {
964 			/* start clear stall */
965 			usbd_xfer_set_stall(xfer);
966 			goto tr_setup;
967 		}
968 		break;
969 	}
970 }
971 
972 static void
cdce_intr_write_callback(struct usb_xfer * xfer,usb_error_t error)973 cdce_intr_write_callback(struct usb_xfer *xfer, usb_error_t error)
974 {
975 	struct cdce_softc *sc = usbd_xfer_softc(xfer);
976 	struct usb_cdc_notification req;
977 	struct usb_page_cache *pc;
978 	uint32_t speed;
979 	int actlen;
980 
981 	DPRINTFN(1, "\n");
982 
983 	usbd_xfer_status(xfer, &actlen, NULL, NULL, NULL);
984 
985 	switch (USB_GET_STATE(xfer)) {
986 	case USB_ST_TRANSFERRED:
987 
988 		DPRINTF("Transferred %d bytes\n", actlen);
989 
990 		switch (sc->sc_notify_state) {
991 		case CDCE_NOTIFY_NETWORK_CONNECTION:
992 			sc->sc_notify_state = CDCE_NOTIFY_SPEED_CHANGE;
993 			break;
994 		case CDCE_NOTIFY_SPEED_CHANGE:
995 			sc->sc_notify_state = CDCE_NOTIFY_DONE;
996 			break;
997 		default:
998 			break;
999 		}
1000 		/* FALLTHROUGH */
1001 	case USB_ST_SETUP:
1002 tr_setup:
1003 		/*
1004 		 * Inform host about connection. Required according to USB CDC
1005 		 * specification and communicating to Mac OS X USB host stack.
1006 		 * Some of the values seems ignored by Mac OS X though.
1007 		 */
1008 		if (sc->sc_notify_state == CDCE_NOTIFY_NETWORK_CONNECTION) {
1009 			req.bmRequestType = UCDC_NOTIFICATION;
1010 			req.bNotification = UCDC_N_NETWORK_CONNECTION;
1011 			req.wIndex[0] = sc->sc_ifaces_index[1];
1012 			req.wIndex[1] = 0;
1013 			USETW(req.wValue, 1); /* Connected */
1014 			USETW(req.wLength, 0);
1015 
1016 			pc = usbd_xfer_get_frame(xfer, 0);
1017 			usbd_copy_in(pc, 0, &req, sizeof(req));
1018 			usbd_xfer_set_frame_len(xfer, 0, sizeof(req));
1019 			usbd_xfer_set_frames(xfer, 1);
1020 			usbd_transfer_submit(xfer);
1021 		} else if (sc->sc_notify_state == CDCE_NOTIFY_SPEED_CHANGE) {
1022 			req.bmRequestType = UCDC_NOTIFICATION;
1023 			req.bNotification = UCDC_N_CONNECTION_SPEED_CHANGE;
1024 			req.wIndex[0] = sc->sc_ifaces_index[1];
1025 			req.wIndex[1] = 0;
1026 			USETW(req.wValue, 0);
1027 			USETW(req.wLength, 8);
1028 
1029 			/* Peak theoretical bulk trasfer rate in bits/s */
1030 			if (usbd_get_speed(sc->sc_ue.ue_udev) != USB_SPEED_FULL)
1031 				speed = (13 * 512 * 8 * 1000 * 8);
1032 			else
1033 				speed = (19 * 64 * 1 * 1000 * 8);
1034 
1035 			USETDW(req.data + 0, speed); /* Upstream bit rate */
1036 			USETDW(req.data + 4, speed); /* Downstream bit rate */
1037 
1038 			pc = usbd_xfer_get_frame(xfer, 0);
1039 			usbd_copy_in(pc, 0, &req, sizeof(req));
1040 			usbd_xfer_set_frame_len(xfer, 0, sizeof(req));
1041 			usbd_xfer_set_frames(xfer, 1);
1042 			usbd_transfer_submit(xfer);
1043 		}
1044 		break;
1045 
1046 	default:			/* Error */
1047 		if (error != USB_ERR_CANCELLED) {
1048 			/* start clear stall */
1049 			usbd_xfer_set_stall(xfer);
1050 			goto tr_setup;
1051 		}
1052 		break;
1053 	}
1054 }
1055 
1056 static int
cdce_handle_request(device_t dev,const void * preq,void ** pptr,uint16_t * plen,uint16_t offset,uint8_t * pstate)1057 cdce_handle_request(device_t dev,
1058     const void *preq, void **pptr, uint16_t *plen,
1059     uint16_t offset, uint8_t *pstate)
1060 {
1061 	struct cdce_softc *sc = device_get_softc(dev);
1062 	const struct usb_device_request *req = preq;
1063 	uint8_t is_complete = *pstate;
1064 
1065 	/*
1066 	 * When Mac OS X resumes after suspending it expects
1067 	 * to be notified again after this request.
1068 	 */
1069 	if (req->bmRequestType == UT_WRITE_CLASS_INTERFACE && \
1070 	    req->bRequest == UCDC_NCM_SET_ETHERNET_PACKET_FILTER) {
1071 
1072 		if (is_complete == 1) {
1073 			mtx_lock(&sc->sc_mtx);
1074 			sc->sc_notify_state = CDCE_NOTIFY_SPEED_CHANGE;
1075 			usbd_transfer_start(sc->sc_xfer[CDCE_INTR_TX]);
1076 			mtx_unlock(&sc->sc_mtx);
1077 		}
1078 
1079 		return (0);
1080 	}
1081 
1082 	return (ENXIO);	 /* use builtin handler */
1083 }
1084 
1085 #if CDCE_HAVE_NCM
1086 static void
cdce_ncm_tx_zero(struct usb_page_cache * pc,uint32_t start,uint32_t end)1087 cdce_ncm_tx_zero(struct usb_page_cache *pc,
1088     uint32_t start, uint32_t end)
1089 {
1090 	DPRINTFN(1, "\n");
1091 
1092 	if (start >= CDCE_NCM_TX_MAXLEN)
1093 		return;
1094 	if (end > CDCE_NCM_TX_MAXLEN)
1095 		end = CDCE_NCM_TX_MAXLEN;
1096 
1097 	usbd_frame_zero(pc, start, end - start);
1098 }
1099 
1100 static uint8_t
cdce_ncm_fill_tx_frames(struct usb_xfer * xfer,uint8_t index)1101 cdce_ncm_fill_tx_frames(struct usb_xfer *xfer, uint8_t index)
1102 {
1103 	struct cdce_softc *sc = usbd_xfer_softc(xfer);
1104 	struct usb_ether *ue = &sc->sc_ue;
1105 	struct usb_page_cache *pc = usbd_xfer_get_frame(xfer, index);
1106 	struct pbuf *m;
1107 	uint32_t rem;
1108 	uint32_t offset;
1109 	uint32_t last_offset;
1110 	uint16_t n;
1111 	uint8_t retval;
1112 
1113 	DPRINTFN(1, "\n");
1114 
1115 	usbd_xfer_set_frame_offset(xfer, index * CDCE_NCM_TX_MAXLEN, index);
1116 
1117 	offset = sizeof(sc->sc_ncm.hdr) +
1118 	    sizeof(sc->sc_ncm.dpt) + sizeof(sc->sc_ncm.dp);
1119 
1120 	/* Store last valid offset before alignment */
1121 	last_offset = offset;
1122 
1123 	/* Align offset */
1124 	offset = CDCE_NCM_ALIGN(sc->sc_ncm.tx_remainder,
1125 	    offset, sc->sc_ncm.tx_modulus);
1126 
1127 	/* Zero pad */
1128 	cdce_ncm_tx_zero(pc, last_offset, offset);
1129 
1130 	/* buffer full */
1131 	retval = 2;
1132 
1133 	for (n = 0; n != sc->sc_ncm.tx_nframe; n++) {
1134 
1135 		/* check if end of transmit buffer is reached */
1136 
1137 		if (offset >= sc->sc_ncm.tx_max)
1138 			break;
1139 
1140 		/* compute maximum buffer size */
1141 
1142 		rem = sc->sc_ncm.tx_max - offset;
1143 
1144 		IF_DEQUEUE(&(ue->ue_txq), m);
1145 
1146 		if (m == NULL) {
1147 			/* buffer not full */
1148 			retval = 1;
1149 			break;
1150 		}
1151 
1152 		if (m->len > (int)rem) {
1153 			if (n == 0) {
1154 				/* The frame won't fit in our buffer */
1155 				DPRINTFN(1, "Frame too big to be transmitted!\n");
1156 				pbuf_free(m);
1157 				n--;
1158 				continue;
1159 			}
1160 			/* Wait till next buffer becomes ready */
1161 			IF_PREPEND(&(ue->ue_txq), m);
1162 			break;
1163 		}
1164 		usbd_copy_in(pc, offset, m->payload, m->len);
1165 
1166 		USETW(sc->sc_ncm.dp[n].wFrameLength, m->len);
1167 		USETW(sc->sc_ncm.dp[n].wFrameIndex, offset);
1168 
1169 		/* Update offset */
1170 		offset += m->len;
1171 
1172 		/* Store last valid offset before alignment */
1173 		last_offset = offset;
1174 
1175 		/* Align offset */
1176 		offset = CDCE_NCM_ALIGN(sc->sc_ncm.tx_remainder,
1177 		    offset, sc->sc_ncm.tx_modulus);
1178 
1179 		/* Zero pad */
1180 		cdce_ncm_tx_zero(pc, last_offset, offset);
1181 
1182 		/* Free mbuf */
1183 		pbuf_free(m);
1184 	}
1185 
1186 	if (n == 0)
1187 		return (0);
1188 
1189 	rem = (sizeof(sc->sc_ncm.dpt) + (4 * n) + 4);
1190 
1191 	USETW(sc->sc_ncm.dpt.wLength, rem);
1192 
1193 	/* zero the rest of the data pointer entries */
1194 	for (; n != CDCE_NCM_SUBFRAMES_MAX; n++) {
1195 		USETW(sc->sc_ncm.dp[n].wFrameLength, 0);
1196 		USETW(sc->sc_ncm.dp[n].wFrameIndex, 0);
1197 	}
1198 
1199 	offset = last_offset;
1200 
1201 	/* Align offset */
1202 	offset = CDCE_NCM_ALIGN(0, offset, CDCE_NCM_TX_MINLEN);
1203 
1204 	/* Optimise, save bandwidth and force short termination */
1205 	if (offset >= sc->sc_ncm.tx_max)
1206 		offset = sc->sc_ncm.tx_max;
1207 	else
1208 		offset ++;
1209 
1210 	/* Zero pad */
1211 	cdce_ncm_tx_zero(pc, last_offset, offset);
1212 
1213 	/* set frame length */
1214 	usbd_xfer_set_frame_len(xfer, index, offset);
1215 
1216 	/* Fill out 16-bit header */
1217 	sc->sc_ncm.hdr.dwSignature[0] = 'N';
1218 	sc->sc_ncm.hdr.dwSignature[1] = 'C';
1219 	sc->sc_ncm.hdr.dwSignature[2] = 'M';
1220 	sc->sc_ncm.hdr.dwSignature[3] = 'H';
1221 	USETW(sc->sc_ncm.hdr.wHeaderLength, sizeof(sc->sc_ncm.hdr));
1222 	USETW(sc->sc_ncm.hdr.wBlockLength, offset);
1223 	USETW(sc->sc_ncm.hdr.wSequence, sc->sc_ncm.tx_seq);
1224 	USETW(sc->sc_ncm.hdr.wDptIndex, sizeof(sc->sc_ncm.hdr));
1225 
1226 	sc->sc_ncm.tx_seq++;
1227 
1228 	/* Fill out 16-bit frame table header */
1229 	sc->sc_ncm.dpt.dwSignature[0] = 'N';
1230 	sc->sc_ncm.dpt.dwSignature[1] = 'C';
1231 	sc->sc_ncm.dpt.dwSignature[2] = 'M';
1232 	sc->sc_ncm.dpt.dwSignature[3] = '0';
1233 	USETW(sc->sc_ncm.dpt.wNextNdpIndex, 0);		/* reserved */
1234 
1235 	usbd_copy_in(pc, 0, &(sc->sc_ncm.hdr), sizeof(sc->sc_ncm.hdr));
1236 	usbd_copy_in(pc, sizeof(sc->sc_ncm.hdr), &(sc->sc_ncm.dpt),
1237 	    sizeof(sc->sc_ncm.dpt));
1238 	usbd_copy_in(pc, sizeof(sc->sc_ncm.hdr) + sizeof(sc->sc_ncm.dpt),
1239 	    &(sc->sc_ncm.dp), sizeof(sc->sc_ncm.dp));
1240 	return (retval);
1241 }
1242 
1243 static void
cdce_ncm_bulk_write_callback(struct usb_xfer * xfer,usb_error_t error)1244 cdce_ncm_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error)
1245 {
1246 	uint16_t x;
1247 	uint8_t temp;
1248 	int actlen;
1249 	int aframes;
1250 
1251 	DPRINTFN(1, "\n");
1252 
1253 	switch (USB_GET_STATE(xfer)) {
1254 	case USB_ST_TRANSFERRED:
1255 
1256 		usbd_xfer_status(xfer, &actlen, NULL, &aframes, NULL);
1257 
1258 		DPRINTFN(10, "transfer complete: "
1259 			"%u bytes in %u frames\n", actlen, aframes);
1260 
1261 	case USB_ST_SETUP:
1262 		for (x = 0; x != CDCE_NCM_TX_FRAMES_MAX; x++) {
1263 			temp = cdce_ncm_fill_tx_frames(xfer, x);
1264 			if (temp == 0)
1265 				break;
1266 			if (temp == 1) {
1267 				x++;
1268 				break;
1269 			}
1270 		}
1271 
1272 		if (x != 0) {
1273 #ifdef LOSCFG_USB_DEBUG
1274 			usbd_xfer_set_interval(xfer, cdce_tx_interval);
1275 #endif
1276 			usbd_xfer_set_frames(xfer, x);
1277 			usbd_transfer_submit(xfer);
1278 		}
1279 		break;
1280 
1281 	default:			/* Error */
1282 		DPRINTFN(10, "Transfer error: %s\n",
1283 		    usbd_errstr(error));
1284 
1285 		if (error != USB_ERR_CANCELLED) {
1286 			/* try to clear stall first */
1287 			usbd_xfer_set_stall(xfer);
1288 			usbd_xfer_set_frames(xfer, 0);
1289 			usbd_transfer_submit(xfer);
1290 		}
1291 		break;
1292 	}
1293 }
1294 
1295 static void
cdce_ncm_bulk_read_callback(struct usb_xfer * xfer,usb_error_t error)1296 cdce_ncm_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error)
1297 {
1298 	struct cdce_softc *sc = usbd_xfer_softc(xfer);
1299 	struct usb_page_cache *pc = usbd_xfer_get_frame(xfer, 0);
1300 	struct pbuf *m;
1301 	int sumdata;
1302 	int sumlen;
1303 	int actlen;
1304 	int aframes;
1305 	int temp;
1306 	int nframes;
1307 	int x;
1308 	int offset;
1309 
1310 	DPRINTFN(1, "\n");
1311 
1312 	switch (USB_GET_STATE(xfer)) {
1313 	case USB_ST_TRANSFERRED:
1314 
1315 		usbd_xfer_status(xfer, &actlen, &sumlen, &aframes, NULL);
1316 
1317 		DPRINTFN(1, "received %u bytes in %u frames\n",
1318 		    actlen, aframes);
1319 
1320 		if (actlen < (int)(sizeof(sc->sc_ncm.hdr) +
1321 		    sizeof(sc->sc_ncm.dpt))) {
1322 			DPRINTFN(1, "frame too short\n");
1323 			goto tr_setup;
1324 		}
1325 		usbd_copy_out(pc, 0, &(sc->sc_ncm.hdr),
1326 		    sizeof(sc->sc_ncm.hdr));
1327 
1328 		if ((sc->sc_ncm.hdr.dwSignature[0] != 'N') ||
1329 		    (sc->sc_ncm.hdr.dwSignature[1] != 'C') ||
1330 		    (sc->sc_ncm.hdr.dwSignature[2] != 'M') ||
1331 		    (sc->sc_ncm.hdr.dwSignature[3] != 'H')) {
1332 			DPRINTFN(1, "invalid HDR signature: "
1333 			    "0x%02x:0x%02x:0x%02x:0x%02x\n",
1334 			    sc->sc_ncm.hdr.dwSignature[0],
1335 			    sc->sc_ncm.hdr.dwSignature[1],
1336 			    sc->sc_ncm.hdr.dwSignature[2],
1337 			    sc->sc_ncm.hdr.dwSignature[3]);
1338 			goto tr_stall;
1339 		}
1340 		temp = UGETW(sc->sc_ncm.hdr.wBlockLength);
1341 		if (temp > sumlen) {
1342 			DPRINTFN(1, "unsupported block length %u/%u\n",
1343 			    temp, sumlen);
1344 			goto tr_stall;
1345 		}
1346 		temp = UGETW(sc->sc_ncm.hdr.wDptIndex);
1347 		if ((int)(temp + sizeof(sc->sc_ncm.dpt)) > actlen) {
1348 			DPRINTFN(1, "invalid DPT index: 0x%04x\n", temp);
1349 			goto tr_stall;
1350 		}
1351 		usbd_copy_out(pc, temp, &(sc->sc_ncm.dpt),
1352 		    sizeof(sc->sc_ncm.dpt));
1353 
1354 		if ((sc->sc_ncm.dpt.dwSignature[0] != 'N') ||
1355 		    (sc->sc_ncm.dpt.dwSignature[1] != 'C') ||
1356 		    (sc->sc_ncm.dpt.dwSignature[2] != 'M') ||
1357 		    (sc->sc_ncm.dpt.dwSignature[3] != '0')) {
1358 			DPRINTFN(1, "invalid DPT signature"
1359 			    "0x%02x:0x%02x:0x%02x:0x%02x\n",
1360 			    sc->sc_ncm.dpt.dwSignature[0],
1361 			    sc->sc_ncm.dpt.dwSignature[1],
1362 			    sc->sc_ncm.dpt.dwSignature[2],
1363 			    sc->sc_ncm.dpt.dwSignature[3]);
1364 			goto tr_stall;
1365 		}
1366 		nframes = UGETW(sc->sc_ncm.dpt.wLength) / 4;
1367 
1368 		/* Subtract size of header and last zero padded entry */
1369 		if (nframes >= (2 + 1))
1370 			nframes -= (2 + 1);
1371 		else
1372 			nframes = 0;
1373 
1374 		DPRINTFN(1, "nframes = %u\n", nframes);
1375 
1376 		temp += sizeof(sc->sc_ncm.dpt);
1377 
1378 		if ((temp + (4 * nframes)) > actlen)
1379 			goto tr_stall;
1380 
1381 		if (nframes > CDCE_NCM_SUBFRAMES_MAX) {
1382 			DPRINTFN(1, "Truncating number of frames from %u to %u\n",
1383 			    nframes, CDCE_NCM_SUBFRAMES_MAX);
1384 			nframes = CDCE_NCM_SUBFRAMES_MAX;
1385 		}
1386 		usbd_copy_out(pc, temp, &(sc->sc_ncm.dp), (4 * nframes));
1387 
1388 		sumdata = 0;
1389 
1390 		for (x = 0; x != nframes; x++) {
1391 
1392 			offset = UGETW(sc->sc_ncm.dp[x].wFrameIndex);
1393 			temp = UGETW(sc->sc_ncm.dp[x].wFrameLength);
1394 
1395 			if ((offset == 0) ||
1396 			    (temp < (int)sizeof(struct ether_header)) ||
1397 			    (temp > (MCLBYTES - ETHER_ALIGN))) {
1398 				DPRINTFN(1, "NULL frame detected at %d\n", x);
1399 				m = NULL;
1400 				/* silently ignore this frame */
1401 				continue;
1402 			} else if ((offset + temp) > actlen) {
1403 				DPRINTFN(1, "invalid frame "
1404 				    "detected at %d\n", x);
1405 				m = NULL;
1406 				/* silently ignore this frame */
1407 				continue;
1408 			} else {
1409 				/* if the tmep here is fragmentary,you could do deallocation */
1410 				m = pbuf_alloc(PBUF_RAW, temp+ETH_PAD_SIZE, PBUF_RAM);
1411 			}
1412 
1413 			DPRINTFN(16, "frame %u, offset = %u, length = %u \n",
1414 			    x, offset, temp);
1415 
1416 			/* check if we have a buffer */
1417 			if (m) {
1418 				#if ETH_PAD_SIZE
1419 					pbuf_header(m, -ETH_PAD_SIZE); /* drop the padding word */
1420 				#endif
1421 
1422 				usbd_copy_out(pc, offset, m->payload, temp);
1423 
1424 				#if ETH_PAD_SIZE
1425 					pbuf_header(m, ETH_PAD_SIZE); /* drop the padding word */
1426 				#endif
1427 
1428 				/* enqueue */
1429 				uether_rxmbuf(&sc->sc_ue, m, temp);
1430 
1431 				sumdata += temp;
1432 			}
1433 		}
1434 
1435 		DPRINTFN(1, "Efficiency: %u/%u bytes\n", sumdata, actlen);
1436 
1437 	case USB_ST_SETUP:
1438 tr_setup:
1439 		usbd_xfer_set_frame_len(xfer, 0, sc->sc_ncm.rx_max);
1440 		usbd_xfer_set_frames(xfer, 1);
1441 		usbd_transfer_submit(xfer);
1442 		uether_rxflush(&sc->sc_ue);	/* must be last */
1443 		break;
1444 
1445 	default:			/* Error */
1446 		DPRINTFN(1, "error = %s\n",
1447 		    usbd_errstr(error));
1448 
1449 		if (error != USB_ERR_CANCELLED) {
1450 tr_stall:
1451 			/* try to clear stall first */
1452 			usbd_xfer_set_stall(xfer);
1453 			usbd_xfer_set_frames(xfer, 0);
1454 			usbd_transfer_submit(xfer);
1455 		}
1456 		break;
1457 	}
1458 }
1459 #endif
1460 
1461 #undef USB_DEBUG_VAR
1462