xref: /linux/drivers/usb/gadget/function/f_ecm.c (revision 5fd54ace4721fc5ce2bb5aef6318fcf17f421460)
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * f_ecm.c -- USB CDC Ethernet (ECM) link function driver
4  *
5  * Copyright (C) 2003-2005,2008 David Brownell
6  * Copyright (C) 2008 Nokia Corporation
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  */
13 
14 /* #define VERBOSE_DEBUG */
15 
16 #include <linux/slab.h>
17 #include <linux/kernel.h>
18 #include <linux/module.h>
19 #include <linux/device.h>
20 #include <linux/etherdevice.h>
21 
22 #include "u_ether.h"
23 #include "u_ether_configfs.h"
24 #include "u_ecm.h"
25 
26 
27 /*
28  * This function is a "CDC Ethernet Networking Control Model" (CDC ECM)
29  * Ethernet link.  The data transfer model is simple (packets sent and
30  * received over bulk endpoints using normal short packet termination),
31  * and the control model exposes various data and optional notifications.
32  *
33  * ECM is well standardized and (except for Microsoft) supported by most
34  * operating systems with USB host support.  It's the preferred interop
35  * solution for Ethernet over USB, at least for firmware based solutions.
36  * (Hardware solutions tend to be more minimalist.)  A newer and simpler
37  * "Ethernet Emulation Model" (CDC EEM) hasn't yet caught on.
38  *
39  * Note that ECM requires the use of "alternate settings" for its data
40  * interface.  This means that the set_alt() method has real work to do,
41  * and also means that a get_alt() method is required.
42  */
43 
44 
45 enum ecm_notify_state {
46 	ECM_NOTIFY_NONE,		/* don't notify */
47 	ECM_NOTIFY_CONNECT,		/* issue CONNECT next */
48 	ECM_NOTIFY_SPEED,		/* issue SPEED_CHANGE next */
49 };
50 
51 struct f_ecm {
52 	struct gether			port;
53 	u8				ctrl_id, data_id;
54 
55 	char				ethaddr[14];
56 
57 	struct usb_ep			*notify;
58 	struct usb_request		*notify_req;
59 	u8				notify_state;
60 	bool				is_open;
61 
62 	/* FIXME is_open needs some irq-ish locking
63 	 * ... possibly the same as port.ioport
64 	 */
65 };
66 
67 static inline struct f_ecm *func_to_ecm(struct usb_function *f)
68 {
69 	return container_of(f, struct f_ecm, port.func);
70 }
71 
72 /* peak (theoretical) bulk transfer rate in bits-per-second */
73 static inline unsigned ecm_bitrate(struct usb_gadget *g)
74 {
75 	if (gadget_is_superspeed(g) && g->speed == USB_SPEED_SUPER)
76 		return 13 * 1024 * 8 * 1000 * 8;
77 	else if (gadget_is_dualspeed(g) && g->speed == USB_SPEED_HIGH)
78 		return 13 * 512 * 8 * 1000 * 8;
79 	else
80 		return 19 * 64 * 1 * 1000 * 8;
81 }
82 
83 /*-------------------------------------------------------------------------*/
84 
85 /*
86  * Include the status endpoint if we can, even though it's optional.
87  *
88  * Use wMaxPacketSize big enough to fit CDC_NOTIFY_SPEED_CHANGE in one
89  * packet, to simplify cancellation; and a big transfer interval, to
90  * waste less bandwidth.
91  *
92  * Some drivers (like Linux 2.4 cdc-ether!) "need" it to exist even
93  * if they ignore the connect/disconnect notifications that real aether
94  * can provide.  More advanced cdc configurations might want to support
95  * encapsulated commands (vendor-specific, using control-OUT).
96  */
97 
98 #define ECM_STATUS_INTERVAL_MS		32
99 #define ECM_STATUS_BYTECOUNT		16	/* 8 byte header + data */
100 
101 
102 /* interface descriptor: */
103 
104 static struct usb_interface_assoc_descriptor
105 ecm_iad_descriptor = {
106 	.bLength =		sizeof ecm_iad_descriptor,
107 	.bDescriptorType =	USB_DT_INTERFACE_ASSOCIATION,
108 
109 	/* .bFirstInterface =	DYNAMIC, */
110 	.bInterfaceCount =	2,	/* control + data */
111 	.bFunctionClass =	USB_CLASS_COMM,
112 	.bFunctionSubClass =	USB_CDC_SUBCLASS_ETHERNET,
113 	.bFunctionProtocol =	USB_CDC_PROTO_NONE,
114 	/* .iFunction =		DYNAMIC */
115 };
116 
117 
118 static struct usb_interface_descriptor ecm_control_intf = {
119 	.bLength =		sizeof ecm_control_intf,
120 	.bDescriptorType =	USB_DT_INTERFACE,
121 
122 	/* .bInterfaceNumber = DYNAMIC */
123 	/* status endpoint is optional; this could be patched later */
124 	.bNumEndpoints =	1,
125 	.bInterfaceClass =	USB_CLASS_COMM,
126 	.bInterfaceSubClass =	USB_CDC_SUBCLASS_ETHERNET,
127 	.bInterfaceProtocol =	USB_CDC_PROTO_NONE,
128 	/* .iInterface = DYNAMIC */
129 };
130 
131 static struct usb_cdc_header_desc ecm_header_desc = {
132 	.bLength =		sizeof ecm_header_desc,
133 	.bDescriptorType =	USB_DT_CS_INTERFACE,
134 	.bDescriptorSubType =	USB_CDC_HEADER_TYPE,
135 
136 	.bcdCDC =		cpu_to_le16(0x0110),
137 };
138 
139 static struct usb_cdc_union_desc ecm_union_desc = {
140 	.bLength =		sizeof(ecm_union_desc),
141 	.bDescriptorType =	USB_DT_CS_INTERFACE,
142 	.bDescriptorSubType =	USB_CDC_UNION_TYPE,
143 	/* .bMasterInterface0 =	DYNAMIC */
144 	/* .bSlaveInterface0 =	DYNAMIC */
145 };
146 
147 static struct usb_cdc_ether_desc ecm_desc = {
148 	.bLength =		sizeof ecm_desc,
149 	.bDescriptorType =	USB_DT_CS_INTERFACE,
150 	.bDescriptorSubType =	USB_CDC_ETHERNET_TYPE,
151 
152 	/* this descriptor actually adds value, surprise! */
153 	/* .iMACAddress = DYNAMIC */
154 	.bmEthernetStatistics =	cpu_to_le32(0), /* no statistics */
155 	.wMaxSegmentSize =	cpu_to_le16(ETH_FRAME_LEN),
156 	.wNumberMCFilters =	cpu_to_le16(0),
157 	.bNumberPowerFilters =	0,
158 };
159 
160 /* the default data interface has no endpoints ... */
161 
162 static struct usb_interface_descriptor ecm_data_nop_intf = {
163 	.bLength =		sizeof ecm_data_nop_intf,
164 	.bDescriptorType =	USB_DT_INTERFACE,
165 
166 	.bInterfaceNumber =	1,
167 	.bAlternateSetting =	0,
168 	.bNumEndpoints =	0,
169 	.bInterfaceClass =	USB_CLASS_CDC_DATA,
170 	.bInterfaceSubClass =	0,
171 	.bInterfaceProtocol =	0,
172 	/* .iInterface = DYNAMIC */
173 };
174 
175 /* ... but the "real" data interface has two bulk endpoints */
176 
177 static struct usb_interface_descriptor ecm_data_intf = {
178 	.bLength =		sizeof ecm_data_intf,
179 	.bDescriptorType =	USB_DT_INTERFACE,
180 
181 	.bInterfaceNumber =	1,
182 	.bAlternateSetting =	1,
183 	.bNumEndpoints =	2,
184 	.bInterfaceClass =	USB_CLASS_CDC_DATA,
185 	.bInterfaceSubClass =	0,
186 	.bInterfaceProtocol =	0,
187 	/* .iInterface = DYNAMIC */
188 };
189 
190 /* full speed support: */
191 
192 static struct usb_endpoint_descriptor fs_ecm_notify_desc = {
193 	.bLength =		USB_DT_ENDPOINT_SIZE,
194 	.bDescriptorType =	USB_DT_ENDPOINT,
195 
196 	.bEndpointAddress =	USB_DIR_IN,
197 	.bmAttributes =		USB_ENDPOINT_XFER_INT,
198 	.wMaxPacketSize =	cpu_to_le16(ECM_STATUS_BYTECOUNT),
199 	.bInterval =		ECM_STATUS_INTERVAL_MS,
200 };
201 
202 static struct usb_endpoint_descriptor fs_ecm_in_desc = {
203 	.bLength =		USB_DT_ENDPOINT_SIZE,
204 	.bDescriptorType =	USB_DT_ENDPOINT,
205 
206 	.bEndpointAddress =	USB_DIR_IN,
207 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
208 };
209 
210 static struct usb_endpoint_descriptor fs_ecm_out_desc = {
211 	.bLength =		USB_DT_ENDPOINT_SIZE,
212 	.bDescriptorType =	USB_DT_ENDPOINT,
213 
214 	.bEndpointAddress =	USB_DIR_OUT,
215 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
216 };
217 
218 static struct usb_descriptor_header *ecm_fs_function[] = {
219 	/* CDC ECM control descriptors */
220 	(struct usb_descriptor_header *) &ecm_iad_descriptor,
221 	(struct usb_descriptor_header *) &ecm_control_intf,
222 	(struct usb_descriptor_header *) &ecm_header_desc,
223 	(struct usb_descriptor_header *) &ecm_union_desc,
224 	(struct usb_descriptor_header *) &ecm_desc,
225 
226 	/* NOTE: status endpoint might need to be removed */
227 	(struct usb_descriptor_header *) &fs_ecm_notify_desc,
228 
229 	/* data interface, altsettings 0 and 1 */
230 	(struct usb_descriptor_header *) &ecm_data_nop_intf,
231 	(struct usb_descriptor_header *) &ecm_data_intf,
232 	(struct usb_descriptor_header *) &fs_ecm_in_desc,
233 	(struct usb_descriptor_header *) &fs_ecm_out_desc,
234 	NULL,
235 };
236 
237 /* high speed support: */
238 
239 static struct usb_endpoint_descriptor hs_ecm_notify_desc = {
240 	.bLength =		USB_DT_ENDPOINT_SIZE,
241 	.bDescriptorType =	USB_DT_ENDPOINT,
242 
243 	.bEndpointAddress =	USB_DIR_IN,
244 	.bmAttributes =		USB_ENDPOINT_XFER_INT,
245 	.wMaxPacketSize =	cpu_to_le16(ECM_STATUS_BYTECOUNT),
246 	.bInterval =		USB_MS_TO_HS_INTERVAL(ECM_STATUS_INTERVAL_MS),
247 };
248 
249 static struct usb_endpoint_descriptor hs_ecm_in_desc = {
250 	.bLength =		USB_DT_ENDPOINT_SIZE,
251 	.bDescriptorType =	USB_DT_ENDPOINT,
252 
253 	.bEndpointAddress =	USB_DIR_IN,
254 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
255 	.wMaxPacketSize =	cpu_to_le16(512),
256 };
257 
258 static struct usb_endpoint_descriptor hs_ecm_out_desc = {
259 	.bLength =		USB_DT_ENDPOINT_SIZE,
260 	.bDescriptorType =	USB_DT_ENDPOINT,
261 
262 	.bEndpointAddress =	USB_DIR_OUT,
263 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
264 	.wMaxPacketSize =	cpu_to_le16(512),
265 };
266 
267 static struct usb_descriptor_header *ecm_hs_function[] = {
268 	/* CDC ECM control descriptors */
269 	(struct usb_descriptor_header *) &ecm_iad_descriptor,
270 	(struct usb_descriptor_header *) &ecm_control_intf,
271 	(struct usb_descriptor_header *) &ecm_header_desc,
272 	(struct usb_descriptor_header *) &ecm_union_desc,
273 	(struct usb_descriptor_header *) &ecm_desc,
274 
275 	/* NOTE: status endpoint might need to be removed */
276 	(struct usb_descriptor_header *) &hs_ecm_notify_desc,
277 
278 	/* data interface, altsettings 0 and 1 */
279 	(struct usb_descriptor_header *) &ecm_data_nop_intf,
280 	(struct usb_descriptor_header *) &ecm_data_intf,
281 	(struct usb_descriptor_header *) &hs_ecm_in_desc,
282 	(struct usb_descriptor_header *) &hs_ecm_out_desc,
283 	NULL,
284 };
285 
286 /* super speed support: */
287 
288 static struct usb_endpoint_descriptor ss_ecm_notify_desc = {
289 	.bLength =		USB_DT_ENDPOINT_SIZE,
290 	.bDescriptorType =	USB_DT_ENDPOINT,
291 
292 	.bEndpointAddress =	USB_DIR_IN,
293 	.bmAttributes =		USB_ENDPOINT_XFER_INT,
294 	.wMaxPacketSize =	cpu_to_le16(ECM_STATUS_BYTECOUNT),
295 	.bInterval =		USB_MS_TO_HS_INTERVAL(ECM_STATUS_INTERVAL_MS),
296 };
297 
298 static struct usb_ss_ep_comp_descriptor ss_ecm_intr_comp_desc = {
299 	.bLength =		sizeof ss_ecm_intr_comp_desc,
300 	.bDescriptorType =	USB_DT_SS_ENDPOINT_COMP,
301 
302 	/* the following 3 values can be tweaked if necessary */
303 	/* .bMaxBurst =		0, */
304 	/* .bmAttributes =	0, */
305 	.wBytesPerInterval =	cpu_to_le16(ECM_STATUS_BYTECOUNT),
306 };
307 
308 static struct usb_endpoint_descriptor ss_ecm_in_desc = {
309 	.bLength =		USB_DT_ENDPOINT_SIZE,
310 	.bDescriptorType =	USB_DT_ENDPOINT,
311 
312 	.bEndpointAddress =	USB_DIR_IN,
313 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
314 	.wMaxPacketSize =	cpu_to_le16(1024),
315 };
316 
317 static struct usb_endpoint_descriptor ss_ecm_out_desc = {
318 	.bLength =		USB_DT_ENDPOINT_SIZE,
319 	.bDescriptorType =	USB_DT_ENDPOINT,
320 
321 	.bEndpointAddress =	USB_DIR_OUT,
322 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
323 	.wMaxPacketSize =	cpu_to_le16(1024),
324 };
325 
326 static struct usb_ss_ep_comp_descriptor ss_ecm_bulk_comp_desc = {
327 	.bLength =		sizeof ss_ecm_bulk_comp_desc,
328 	.bDescriptorType =	USB_DT_SS_ENDPOINT_COMP,
329 
330 	/* the following 2 values can be tweaked if necessary */
331 	/* .bMaxBurst =		0, */
332 	/* .bmAttributes =	0, */
333 };
334 
335 static struct usb_descriptor_header *ecm_ss_function[] = {
336 	/* CDC ECM control descriptors */
337 	(struct usb_descriptor_header *) &ecm_iad_descriptor,
338 	(struct usb_descriptor_header *) &ecm_control_intf,
339 	(struct usb_descriptor_header *) &ecm_header_desc,
340 	(struct usb_descriptor_header *) &ecm_union_desc,
341 	(struct usb_descriptor_header *) &ecm_desc,
342 
343 	/* NOTE: status endpoint might need to be removed */
344 	(struct usb_descriptor_header *) &ss_ecm_notify_desc,
345 	(struct usb_descriptor_header *) &ss_ecm_intr_comp_desc,
346 
347 	/* data interface, altsettings 0 and 1 */
348 	(struct usb_descriptor_header *) &ecm_data_nop_intf,
349 	(struct usb_descriptor_header *) &ecm_data_intf,
350 	(struct usb_descriptor_header *) &ss_ecm_in_desc,
351 	(struct usb_descriptor_header *) &ss_ecm_bulk_comp_desc,
352 	(struct usb_descriptor_header *) &ss_ecm_out_desc,
353 	(struct usb_descriptor_header *) &ss_ecm_bulk_comp_desc,
354 	NULL,
355 };
356 
357 /* string descriptors: */
358 
359 static struct usb_string ecm_string_defs[] = {
360 	[0].s = "CDC Ethernet Control Model (ECM)",
361 	[1].s = "",
362 	[2].s = "CDC Ethernet Data",
363 	[3].s = "CDC ECM",
364 	{  } /* end of list */
365 };
366 
367 static struct usb_gadget_strings ecm_string_table = {
368 	.language =		0x0409,	/* en-us */
369 	.strings =		ecm_string_defs,
370 };
371 
372 static struct usb_gadget_strings *ecm_strings[] = {
373 	&ecm_string_table,
374 	NULL,
375 };
376 
377 /*-------------------------------------------------------------------------*/
378 
379 static void ecm_do_notify(struct f_ecm *ecm)
380 {
381 	struct usb_request		*req = ecm->notify_req;
382 	struct usb_cdc_notification	*event;
383 	struct usb_composite_dev	*cdev = ecm->port.func.config->cdev;
384 	__le32				*data;
385 	int				status;
386 
387 	/* notification already in flight? */
388 	if (!req)
389 		return;
390 
391 	event = req->buf;
392 	switch (ecm->notify_state) {
393 	case ECM_NOTIFY_NONE:
394 		return;
395 
396 	case ECM_NOTIFY_CONNECT:
397 		event->bNotificationType = USB_CDC_NOTIFY_NETWORK_CONNECTION;
398 		if (ecm->is_open)
399 			event->wValue = cpu_to_le16(1);
400 		else
401 			event->wValue = cpu_to_le16(0);
402 		event->wLength = 0;
403 		req->length = sizeof *event;
404 
405 		DBG(cdev, "notify connect %s\n",
406 				ecm->is_open ? "true" : "false");
407 		ecm->notify_state = ECM_NOTIFY_SPEED;
408 		break;
409 
410 	case ECM_NOTIFY_SPEED:
411 		event->bNotificationType = USB_CDC_NOTIFY_SPEED_CHANGE;
412 		event->wValue = cpu_to_le16(0);
413 		event->wLength = cpu_to_le16(8);
414 		req->length = ECM_STATUS_BYTECOUNT;
415 
416 		/* SPEED_CHANGE data is up/down speeds in bits/sec */
417 		data = req->buf + sizeof *event;
418 		data[0] = cpu_to_le32(ecm_bitrate(cdev->gadget));
419 		data[1] = data[0];
420 
421 		DBG(cdev, "notify speed %d\n", ecm_bitrate(cdev->gadget));
422 		ecm->notify_state = ECM_NOTIFY_NONE;
423 		break;
424 	}
425 	event->bmRequestType = 0xA1;
426 	event->wIndex = cpu_to_le16(ecm->ctrl_id);
427 
428 	ecm->notify_req = NULL;
429 	status = usb_ep_queue(ecm->notify, req, GFP_ATOMIC);
430 	if (status < 0) {
431 		ecm->notify_req = req;
432 		DBG(cdev, "notify --> %d\n", status);
433 	}
434 }
435 
436 static void ecm_notify(struct f_ecm *ecm)
437 {
438 	/* NOTE on most versions of Linux, host side cdc-ethernet
439 	 * won't listen for notifications until its netdevice opens.
440 	 * The first notification then sits in the FIFO for a long
441 	 * time, and the second one is queued.
442 	 */
443 	ecm->notify_state = ECM_NOTIFY_CONNECT;
444 	ecm_do_notify(ecm);
445 }
446 
447 static void ecm_notify_complete(struct usb_ep *ep, struct usb_request *req)
448 {
449 	struct f_ecm			*ecm = req->context;
450 	struct usb_composite_dev	*cdev = ecm->port.func.config->cdev;
451 	struct usb_cdc_notification	*event = req->buf;
452 
453 	switch (req->status) {
454 	case 0:
455 		/* no fault */
456 		break;
457 	case -ECONNRESET:
458 	case -ESHUTDOWN:
459 		ecm->notify_state = ECM_NOTIFY_NONE;
460 		break;
461 	default:
462 		DBG(cdev, "event %02x --> %d\n",
463 			event->bNotificationType, req->status);
464 		break;
465 	}
466 	ecm->notify_req = req;
467 	ecm_do_notify(ecm);
468 }
469 
470 static int ecm_setup(struct usb_function *f, const struct usb_ctrlrequest *ctrl)
471 {
472 	struct f_ecm		*ecm = func_to_ecm(f);
473 	struct usb_composite_dev *cdev = f->config->cdev;
474 	struct usb_request	*req = cdev->req;
475 	int			value = -EOPNOTSUPP;
476 	u16			w_index = le16_to_cpu(ctrl->wIndex);
477 	u16			w_value = le16_to_cpu(ctrl->wValue);
478 	u16			w_length = le16_to_cpu(ctrl->wLength);
479 
480 	/* composite driver infrastructure handles everything except
481 	 * CDC class messages; interface activation uses set_alt().
482 	 */
483 	switch ((ctrl->bRequestType << 8) | ctrl->bRequest) {
484 	case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
485 			| USB_CDC_SET_ETHERNET_PACKET_FILTER:
486 		/* see 6.2.30: no data, wIndex = interface,
487 		 * wValue = packet filter bitmap
488 		 */
489 		if (w_length != 0 || w_index != ecm->ctrl_id)
490 			goto invalid;
491 		DBG(cdev, "packet filter %02x\n", w_value);
492 		/* REVISIT locking of cdc_filter.  This assumes the UDC
493 		 * driver won't have a concurrent packet TX irq running on
494 		 * another CPU; or that if it does, this write is atomic...
495 		 */
496 		ecm->port.cdc_filter = w_value;
497 		value = 0;
498 		break;
499 
500 	/* and optionally:
501 	 * case USB_CDC_SEND_ENCAPSULATED_COMMAND:
502 	 * case USB_CDC_GET_ENCAPSULATED_RESPONSE:
503 	 * case USB_CDC_SET_ETHERNET_MULTICAST_FILTERS:
504 	 * case USB_CDC_SET_ETHERNET_PM_PATTERN_FILTER:
505 	 * case USB_CDC_GET_ETHERNET_PM_PATTERN_FILTER:
506 	 * case USB_CDC_GET_ETHERNET_STATISTIC:
507 	 */
508 
509 	default:
510 invalid:
511 		DBG(cdev, "invalid control req%02x.%02x v%04x i%04x l%d\n",
512 			ctrl->bRequestType, ctrl->bRequest,
513 			w_value, w_index, w_length);
514 	}
515 
516 	/* respond with data transfer or status phase? */
517 	if (value >= 0) {
518 		DBG(cdev, "ecm req%02x.%02x v%04x i%04x l%d\n",
519 			ctrl->bRequestType, ctrl->bRequest,
520 			w_value, w_index, w_length);
521 		req->zero = 0;
522 		req->length = value;
523 		value = usb_ep_queue(cdev->gadget->ep0, req, GFP_ATOMIC);
524 		if (value < 0)
525 			ERROR(cdev, "ecm req %02x.%02x response err %d\n",
526 					ctrl->bRequestType, ctrl->bRequest,
527 					value);
528 	}
529 
530 	/* device either stalls (value < 0) or reports success */
531 	return value;
532 }
533 
534 
535 static int ecm_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
536 {
537 	struct f_ecm		*ecm = func_to_ecm(f);
538 	struct usb_composite_dev *cdev = f->config->cdev;
539 
540 	/* Control interface has only altsetting 0 */
541 	if (intf == ecm->ctrl_id) {
542 		if (alt != 0)
543 			goto fail;
544 
545 		VDBG(cdev, "reset ecm control %d\n", intf);
546 		usb_ep_disable(ecm->notify);
547 		if (!(ecm->notify->desc)) {
548 			VDBG(cdev, "init ecm ctrl %d\n", intf);
549 			if (config_ep_by_speed(cdev->gadget, f, ecm->notify))
550 				goto fail;
551 		}
552 		usb_ep_enable(ecm->notify);
553 
554 	/* Data interface has two altsettings, 0 and 1 */
555 	} else if (intf == ecm->data_id) {
556 		if (alt > 1)
557 			goto fail;
558 
559 		if (ecm->port.in_ep->enabled) {
560 			DBG(cdev, "reset ecm\n");
561 			gether_disconnect(&ecm->port);
562 		}
563 
564 		if (!ecm->port.in_ep->desc ||
565 		    !ecm->port.out_ep->desc) {
566 			DBG(cdev, "init ecm\n");
567 			if (config_ep_by_speed(cdev->gadget, f,
568 					       ecm->port.in_ep) ||
569 			    config_ep_by_speed(cdev->gadget, f,
570 					       ecm->port.out_ep)) {
571 				ecm->port.in_ep->desc = NULL;
572 				ecm->port.out_ep->desc = NULL;
573 				goto fail;
574 			}
575 		}
576 
577 		/* CDC Ethernet only sends data in non-default altsettings.
578 		 * Changing altsettings resets filters, statistics, etc.
579 		 */
580 		if (alt == 1) {
581 			struct net_device	*net;
582 
583 			/* Enable zlps by default for ECM conformance;
584 			 * override for musb_hdrc (avoids txdma ovhead).
585 			 */
586 			ecm->port.is_zlp_ok =
587 				gadget_is_zlp_supported(cdev->gadget);
588 			ecm->port.cdc_filter = DEFAULT_FILTER;
589 			DBG(cdev, "activate ecm\n");
590 			net = gether_connect(&ecm->port);
591 			if (IS_ERR(net))
592 				return PTR_ERR(net);
593 		}
594 
595 		/* NOTE this can be a minor disagreement with the ECM spec,
596 		 * which says speed notifications will "always" follow
597 		 * connection notifications.  But we allow one connect to
598 		 * follow another (if the first is in flight), and instead
599 		 * just guarantee that a speed notification is always sent.
600 		 */
601 		ecm_notify(ecm);
602 	} else
603 		goto fail;
604 
605 	return 0;
606 fail:
607 	return -EINVAL;
608 }
609 
610 /* Because the data interface supports multiple altsettings,
611  * this ECM function *MUST* implement a get_alt() method.
612  */
613 static int ecm_get_alt(struct usb_function *f, unsigned intf)
614 {
615 	struct f_ecm		*ecm = func_to_ecm(f);
616 
617 	if (intf == ecm->ctrl_id)
618 		return 0;
619 	return ecm->port.in_ep->enabled ? 1 : 0;
620 }
621 
622 static void ecm_disable(struct usb_function *f)
623 {
624 	struct f_ecm		*ecm = func_to_ecm(f);
625 	struct usb_composite_dev *cdev = f->config->cdev;
626 
627 	DBG(cdev, "ecm deactivated\n");
628 
629 	if (ecm->port.in_ep->enabled)
630 		gether_disconnect(&ecm->port);
631 
632 	usb_ep_disable(ecm->notify);
633 	ecm->notify->desc = NULL;
634 }
635 
636 /*-------------------------------------------------------------------------*/
637 
638 /*
639  * Callbacks let us notify the host about connect/disconnect when the
640  * net device is opened or closed.
641  *
642  * For testing, note that link states on this side include both opened
643  * and closed variants of:
644  *
645  *   - disconnected/unconfigured
646  *   - configured but inactive (data alt 0)
647  *   - configured and active (data alt 1)
648  *
649  * Each needs to be tested with unplug, rmmod, SET_CONFIGURATION, and
650  * SET_INTERFACE (altsetting).  Remember also that "configured" doesn't
651  * imply the host is actually polling the notification endpoint, and
652  * likewise that "active" doesn't imply it's actually using the data
653  * endpoints for traffic.
654  */
655 
656 static void ecm_open(struct gether *geth)
657 {
658 	struct f_ecm		*ecm = func_to_ecm(&geth->func);
659 
660 	DBG(ecm->port.func.config->cdev, "%s\n", __func__);
661 
662 	ecm->is_open = true;
663 	ecm_notify(ecm);
664 }
665 
666 static void ecm_close(struct gether *geth)
667 {
668 	struct f_ecm		*ecm = func_to_ecm(&geth->func);
669 
670 	DBG(ecm->port.func.config->cdev, "%s\n", __func__);
671 
672 	ecm->is_open = false;
673 	ecm_notify(ecm);
674 }
675 
676 /*-------------------------------------------------------------------------*/
677 
678 /* ethernet function driver setup/binding */
679 
680 static int
681 ecm_bind(struct usb_configuration *c, struct usb_function *f)
682 {
683 	struct usb_composite_dev *cdev = c->cdev;
684 	struct f_ecm		*ecm = func_to_ecm(f);
685 	struct usb_string	*us;
686 	int			status;
687 	struct usb_ep		*ep;
688 
689 	struct f_ecm_opts	*ecm_opts;
690 
691 	if (!can_support_ecm(cdev->gadget))
692 		return -EINVAL;
693 
694 	ecm_opts = container_of(f->fi, struct f_ecm_opts, func_inst);
695 
696 	/*
697 	 * in drivers/usb/gadget/configfs.c:configfs_composite_bind()
698 	 * configurations are bound in sequence with list_for_each_entry,
699 	 * in each configuration its functions are bound in sequence
700 	 * with list_for_each_entry, so we assume no race condition
701 	 * with regard to ecm_opts->bound access
702 	 */
703 	if (!ecm_opts->bound) {
704 		mutex_lock(&ecm_opts->lock);
705 		gether_set_gadget(ecm_opts->net, cdev->gadget);
706 		status = gether_register_netdev(ecm_opts->net);
707 		mutex_unlock(&ecm_opts->lock);
708 		if (status)
709 			return status;
710 		ecm_opts->bound = true;
711 	}
712 
713 	us = usb_gstrings_attach(cdev, ecm_strings,
714 				 ARRAY_SIZE(ecm_string_defs));
715 	if (IS_ERR(us))
716 		return PTR_ERR(us);
717 	ecm_control_intf.iInterface = us[0].id;
718 	ecm_data_intf.iInterface = us[2].id;
719 	ecm_desc.iMACAddress = us[1].id;
720 	ecm_iad_descriptor.iFunction = us[3].id;
721 
722 	/* allocate instance-specific interface IDs */
723 	status = usb_interface_id(c, f);
724 	if (status < 0)
725 		goto fail;
726 	ecm->ctrl_id = status;
727 	ecm_iad_descriptor.bFirstInterface = status;
728 
729 	ecm_control_intf.bInterfaceNumber = status;
730 	ecm_union_desc.bMasterInterface0 = status;
731 
732 	status = usb_interface_id(c, f);
733 	if (status < 0)
734 		goto fail;
735 	ecm->data_id = status;
736 
737 	ecm_data_nop_intf.bInterfaceNumber = status;
738 	ecm_data_intf.bInterfaceNumber = status;
739 	ecm_union_desc.bSlaveInterface0 = status;
740 
741 	status = -ENODEV;
742 
743 	/* allocate instance-specific endpoints */
744 	ep = usb_ep_autoconfig(cdev->gadget, &fs_ecm_in_desc);
745 	if (!ep)
746 		goto fail;
747 	ecm->port.in_ep = ep;
748 
749 	ep = usb_ep_autoconfig(cdev->gadget, &fs_ecm_out_desc);
750 	if (!ep)
751 		goto fail;
752 	ecm->port.out_ep = ep;
753 
754 	/* NOTE:  a status/notification endpoint is *OPTIONAL* but we
755 	 * don't treat it that way.  It's simpler, and some newer CDC
756 	 * profiles (wireless handsets) no longer treat it as optional.
757 	 */
758 	ep = usb_ep_autoconfig(cdev->gadget, &fs_ecm_notify_desc);
759 	if (!ep)
760 		goto fail;
761 	ecm->notify = ep;
762 
763 	status = -ENOMEM;
764 
765 	/* allocate notification request and buffer */
766 	ecm->notify_req = usb_ep_alloc_request(ep, GFP_KERNEL);
767 	if (!ecm->notify_req)
768 		goto fail;
769 	ecm->notify_req->buf = kmalloc(ECM_STATUS_BYTECOUNT, GFP_KERNEL);
770 	if (!ecm->notify_req->buf)
771 		goto fail;
772 	ecm->notify_req->context = ecm;
773 	ecm->notify_req->complete = ecm_notify_complete;
774 
775 	/* support all relevant hardware speeds... we expect that when
776 	 * hardware is dual speed, all bulk-capable endpoints work at
777 	 * both speeds
778 	 */
779 	hs_ecm_in_desc.bEndpointAddress = fs_ecm_in_desc.bEndpointAddress;
780 	hs_ecm_out_desc.bEndpointAddress = fs_ecm_out_desc.bEndpointAddress;
781 	hs_ecm_notify_desc.bEndpointAddress =
782 		fs_ecm_notify_desc.bEndpointAddress;
783 
784 	ss_ecm_in_desc.bEndpointAddress = fs_ecm_in_desc.bEndpointAddress;
785 	ss_ecm_out_desc.bEndpointAddress = fs_ecm_out_desc.bEndpointAddress;
786 	ss_ecm_notify_desc.bEndpointAddress =
787 		fs_ecm_notify_desc.bEndpointAddress;
788 
789 	status = usb_assign_descriptors(f, ecm_fs_function, ecm_hs_function,
790 			ecm_ss_function, NULL);
791 	if (status)
792 		goto fail;
793 
794 	/* NOTE:  all that is done without knowing or caring about
795 	 * the network link ... which is unavailable to this code
796 	 * until we're activated via set_alt().
797 	 */
798 
799 	ecm->port.open = ecm_open;
800 	ecm->port.close = ecm_close;
801 
802 	DBG(cdev, "CDC Ethernet: %s speed IN/%s OUT/%s NOTIFY/%s\n",
803 			gadget_is_superspeed(c->cdev->gadget) ? "super" :
804 			gadget_is_dualspeed(c->cdev->gadget) ? "dual" : "full",
805 			ecm->port.in_ep->name, ecm->port.out_ep->name,
806 			ecm->notify->name);
807 	return 0;
808 
809 fail:
810 	if (ecm->notify_req) {
811 		kfree(ecm->notify_req->buf);
812 		usb_ep_free_request(ecm->notify, ecm->notify_req);
813 	}
814 
815 	ERROR(cdev, "%s: can't bind, err %d\n", f->name, status);
816 
817 	return status;
818 }
819 
820 static inline struct f_ecm_opts *to_f_ecm_opts(struct config_item *item)
821 {
822 	return container_of(to_config_group(item), struct f_ecm_opts,
823 			    func_inst.group);
824 }
825 
826 /* f_ecm_item_ops */
827 USB_ETHERNET_CONFIGFS_ITEM(ecm);
828 
829 /* f_ecm_opts_dev_addr */
830 USB_ETHERNET_CONFIGFS_ITEM_ATTR_DEV_ADDR(ecm);
831 
832 /* f_ecm_opts_host_addr */
833 USB_ETHERNET_CONFIGFS_ITEM_ATTR_HOST_ADDR(ecm);
834 
835 /* f_ecm_opts_qmult */
836 USB_ETHERNET_CONFIGFS_ITEM_ATTR_QMULT(ecm);
837 
838 /* f_ecm_opts_ifname */
839 USB_ETHERNET_CONFIGFS_ITEM_ATTR_IFNAME(ecm);
840 
841 static struct configfs_attribute *ecm_attrs[] = {
842 	&ecm_opts_attr_dev_addr,
843 	&ecm_opts_attr_host_addr,
844 	&ecm_opts_attr_qmult,
845 	&ecm_opts_attr_ifname,
846 	NULL,
847 };
848 
849 static struct config_item_type ecm_func_type = {
850 	.ct_item_ops	= &ecm_item_ops,
851 	.ct_attrs	= ecm_attrs,
852 	.ct_owner	= THIS_MODULE,
853 };
854 
855 static void ecm_free_inst(struct usb_function_instance *f)
856 {
857 	struct f_ecm_opts *opts;
858 
859 	opts = container_of(f, struct f_ecm_opts, func_inst);
860 	if (opts->bound)
861 		gether_cleanup(netdev_priv(opts->net));
862 	else
863 		free_netdev(opts->net);
864 	kfree(opts);
865 }
866 
867 static struct usb_function_instance *ecm_alloc_inst(void)
868 {
869 	struct f_ecm_opts *opts;
870 
871 	opts = kzalloc(sizeof(*opts), GFP_KERNEL);
872 	if (!opts)
873 		return ERR_PTR(-ENOMEM);
874 	mutex_init(&opts->lock);
875 	opts->func_inst.free_func_inst = ecm_free_inst;
876 	opts->net = gether_setup_default();
877 	if (IS_ERR(opts->net)) {
878 		struct net_device *net = opts->net;
879 		kfree(opts);
880 		return ERR_CAST(net);
881 	}
882 
883 	config_group_init_type_name(&opts->func_inst.group, "", &ecm_func_type);
884 
885 	return &opts->func_inst;
886 }
887 
888 static void ecm_free(struct usb_function *f)
889 {
890 	struct f_ecm *ecm;
891 	struct f_ecm_opts *opts;
892 
893 	ecm = func_to_ecm(f);
894 	opts = container_of(f->fi, struct f_ecm_opts, func_inst);
895 	kfree(ecm);
896 	mutex_lock(&opts->lock);
897 	opts->refcnt--;
898 	mutex_unlock(&opts->lock);
899 }
900 
901 static void ecm_unbind(struct usb_configuration *c, struct usb_function *f)
902 {
903 	struct f_ecm		*ecm = func_to_ecm(f);
904 
905 	DBG(c->cdev, "ecm unbind\n");
906 
907 	usb_free_all_descriptors(f);
908 
909 	kfree(ecm->notify_req->buf);
910 	usb_ep_free_request(ecm->notify, ecm->notify_req);
911 }
912 
913 static struct usb_function *ecm_alloc(struct usb_function_instance *fi)
914 {
915 	struct f_ecm	*ecm;
916 	struct f_ecm_opts *opts;
917 	int status;
918 
919 	/* allocate and initialize one new instance */
920 	ecm = kzalloc(sizeof(*ecm), GFP_KERNEL);
921 	if (!ecm)
922 		return ERR_PTR(-ENOMEM);
923 
924 	opts = container_of(fi, struct f_ecm_opts, func_inst);
925 	mutex_lock(&opts->lock);
926 	opts->refcnt++;
927 
928 	/* export host's Ethernet address in CDC format */
929 	status = gether_get_host_addr_cdc(opts->net, ecm->ethaddr,
930 					  sizeof(ecm->ethaddr));
931 	if (status < 12) {
932 		kfree(ecm);
933 		mutex_unlock(&opts->lock);
934 		return ERR_PTR(-EINVAL);
935 	}
936 	ecm_string_defs[1].s = ecm->ethaddr;
937 
938 	ecm->port.ioport = netdev_priv(opts->net);
939 	mutex_unlock(&opts->lock);
940 	ecm->port.cdc_filter = DEFAULT_FILTER;
941 
942 	ecm->port.func.name = "cdc_ethernet";
943 	/* descriptors are per-instance copies */
944 	ecm->port.func.bind = ecm_bind;
945 	ecm->port.func.unbind = ecm_unbind;
946 	ecm->port.func.set_alt = ecm_set_alt;
947 	ecm->port.func.get_alt = ecm_get_alt;
948 	ecm->port.func.setup = ecm_setup;
949 	ecm->port.func.disable = ecm_disable;
950 	ecm->port.func.free_func = ecm_free;
951 
952 	return &ecm->port.func;
953 }
954 
955 DECLARE_USB_FUNCTION_INIT(ecm, ecm_alloc_inst, ecm_alloc);
956 MODULE_LICENSE("GPL");
957 MODULE_AUTHOR("David Brownell");
958