1 /*
2  * f_rndis.c -- RNDIS link function driver
3  *
4  * Copyright (C) 2003-2005,2008 David Brownell
5  * Copyright (C) 2003-2004 Robert Schwebel, Benedikt Spranger
6  * Copyright (C) 2008 Nokia Corporation
7  * Copyright (C) 2009 Samsung Electronics
8  *                    Author: Michal Nazarewicz (mina86@mina86.com)
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  */
15 
16 /* #define VERBOSE_DEBUG */
17 
18 #include <linux/slab.h>
19 #include <linux/kernel.h>
20 #include <linux/module.h>
21 #include <linux/device.h>
22 #include <linux/etherdevice.h>
23 
24 #include <linux/atomic.h>
25 
26 #include "u_ether.h"
27 #include "u_ether_configfs.h"
28 #include "u_rndis.h"
29 #include "rndis.h"
30 #include "configfs.h"
31 
32 /*
33  * This function is an RNDIS Ethernet port -- a Microsoft protocol that's
34  * been promoted instead of the standard CDC Ethernet.  The published RNDIS
35  * spec is ambiguous, incomplete, and needlessly complex.  Variants such as
36  * ActiveSync have even worse status in terms of specification.
37  *
38  * In short:  it's a protocol controlled by (and for) Microsoft, not for an
39  * Open ecosystem or markets.  Linux supports it *only* because Microsoft
40  * doesn't support the CDC Ethernet standard.
41  *
42  * The RNDIS data transfer model is complex, with multiple Ethernet packets
43  * per USB message, and out of band data.  The control model is built around
44  * what's essentially an "RNDIS RPC" protocol.  It's all wrapped in a CDC ACM
45  * (modem, not Ethernet) veneer, with those ACM descriptors being entirely
46  * useless (they're ignored).  RNDIS expects to be the only function in its
47  * configuration, so it's no real help if you need composite devices; and
48  * it expects to be the first configuration too.
49  *
50  * There is a single technical advantage of RNDIS over CDC Ethernet, if you
51  * discount the fluff that its RPC can be made to deliver: it doesn't need
52  * a NOP altsetting for the data interface.  That lets it work on some of the
53  * "so smart it's stupid" hardware which takes over configuration changes
54  * from the software, and adds restrictions like "no altsettings".
55  *
56  * Unfortunately MSFT's RNDIS drivers are buggy.  They hang or oops, and
57  * have all sorts of contrary-to-specification oddities that can prevent
58  * them from working sanely.  Since bugfixes (or accurate specs, letting
59  * Linux work around those bugs) are unlikely to ever come from MSFT, you
60  * may want to avoid using RNDIS on purely operational grounds.
61  *
62  * Omissions from the RNDIS 1.0 specification include:
63  *
64  *   - Power management ... references data that's scattered around lots
65  *     of other documentation, which is incorrect/incomplete there too.
66  *
67  *   - There are various undocumented protocol requirements, like the need
68  *     to send garbage in some control-OUT messages.
69  *
70  *   - MS-Windows drivers sometimes emit undocumented requests.
71  */
72 
73 struct f_rndis {
74 	struct gether			port;
75 	u8				ctrl_id, data_id;
76 	u8				ethaddr[ETH_ALEN];
77 	u32				vendorID;
78 	const char			*manufacturer;
79 	struct rndis_params		*params;
80 
81 	struct usb_ep			*notify;
82 	struct usb_request		*notify_req;
83 	atomic_t			notify_count;
84 };
85 
86 static inline struct f_rndis *func_to_rndis(struct usb_function *f)
87 {
88 	return container_of(f, struct f_rndis, port.func);
89 }
90 
91 /* peak (theoretical) bulk transfer rate in bits-per-second */
92 static unsigned int bitrate(struct usb_gadget *g)
93 {
94 	if (gadget_is_superspeed(g) && g->speed == USB_SPEED_SUPER)
95 		return 13 * 1024 * 8 * 1000 * 8;
96 	else if (gadget_is_dualspeed(g) && g->speed == USB_SPEED_HIGH)
97 		return 13 * 512 * 8 * 1000 * 8;
98 	else
99 		return 19 * 64 * 1 * 1000 * 8;
100 }
101 
102 /*-------------------------------------------------------------------------*/
103 
104 /*
105  */
106 
107 #define RNDIS_STATUS_INTERVAL_MS	32
108 #define STATUS_BYTECOUNT		8	/* 8 bytes data */
109 
110 
111 /* interface descriptor: */
112 
113 static struct usb_interface_descriptor rndis_control_intf = {
114 	.bLength =		sizeof rndis_control_intf,
115 	.bDescriptorType =	USB_DT_INTERFACE,
116 
117 	/* .bInterfaceNumber = DYNAMIC */
118 	/* status endpoint is optional; this could be patched later */
119 	.bNumEndpoints =	1,
120 	.bInterfaceClass =	USB_CLASS_COMM,
121 	.bInterfaceSubClass =   USB_CDC_SUBCLASS_ACM,
122 	.bInterfaceProtocol =   USB_CDC_ACM_PROTO_VENDOR,
123 	/* .iInterface = DYNAMIC */
124 };
125 
126 static struct usb_cdc_header_desc header_desc = {
127 	.bLength =		sizeof header_desc,
128 	.bDescriptorType =	USB_DT_CS_INTERFACE,
129 	.bDescriptorSubType =	USB_CDC_HEADER_TYPE,
130 
131 	.bcdCDC =		cpu_to_le16(0x0110),
132 };
133 
134 static struct usb_cdc_call_mgmt_descriptor call_mgmt_descriptor = {
135 	.bLength =		sizeof call_mgmt_descriptor,
136 	.bDescriptorType =	USB_DT_CS_INTERFACE,
137 	.bDescriptorSubType =	USB_CDC_CALL_MANAGEMENT_TYPE,
138 
139 	.bmCapabilities =	0x00,
140 	.bDataInterface =	0x01,
141 };
142 
143 static struct usb_cdc_acm_descriptor rndis_acm_descriptor = {
144 	.bLength =		sizeof rndis_acm_descriptor,
145 	.bDescriptorType =	USB_DT_CS_INTERFACE,
146 	.bDescriptorSubType =	USB_CDC_ACM_TYPE,
147 
148 	.bmCapabilities =	0x00,
149 };
150 
151 static struct usb_cdc_union_desc rndis_union_desc = {
152 	.bLength =		sizeof(rndis_union_desc),
153 	.bDescriptorType =	USB_DT_CS_INTERFACE,
154 	.bDescriptorSubType =	USB_CDC_UNION_TYPE,
155 	/* .bMasterInterface0 =	DYNAMIC */
156 	/* .bSlaveInterface0 =	DYNAMIC */
157 };
158 
159 /* the data interface has two bulk endpoints */
160 
161 static struct usb_interface_descriptor rndis_data_intf = {
162 	.bLength =		sizeof rndis_data_intf,
163 	.bDescriptorType =	USB_DT_INTERFACE,
164 
165 	/* .bInterfaceNumber = DYNAMIC */
166 	.bNumEndpoints =	2,
167 	.bInterfaceClass =	USB_CLASS_CDC_DATA,
168 	.bInterfaceSubClass =	0,
169 	.bInterfaceProtocol =	0,
170 	/* .iInterface = DYNAMIC */
171 };
172 
173 
174 static struct usb_interface_assoc_descriptor
175 rndis_iad_descriptor = {
176 	.bLength =		sizeof rndis_iad_descriptor,
177 	.bDescriptorType =	USB_DT_INTERFACE_ASSOCIATION,
178 
179 	.bFirstInterface =	0, /* XXX, hardcoded */
180 	.bInterfaceCount = 	2,	// control + data
181 	.bFunctionClass =	USB_CLASS_COMM,
182 	.bFunctionSubClass =	USB_CDC_SUBCLASS_ETHERNET,
183 	.bFunctionProtocol =	USB_CDC_PROTO_NONE,
184 	/* .iFunction = DYNAMIC */
185 };
186 
187 /* full speed support: */
188 
189 static struct usb_endpoint_descriptor fs_notify_desc = {
190 	.bLength =		USB_DT_ENDPOINT_SIZE,
191 	.bDescriptorType =	USB_DT_ENDPOINT,
192 
193 	.bEndpointAddress =	USB_DIR_IN,
194 	.bmAttributes =		USB_ENDPOINT_XFER_INT,
195 	.wMaxPacketSize =	cpu_to_le16(STATUS_BYTECOUNT),
196 	.bInterval =		RNDIS_STATUS_INTERVAL_MS,
197 };
198 
199 static struct usb_endpoint_descriptor fs_in_desc = {
200 	.bLength =		USB_DT_ENDPOINT_SIZE,
201 	.bDescriptorType =	USB_DT_ENDPOINT,
202 
203 	.bEndpointAddress =	USB_DIR_IN,
204 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
205 };
206 
207 static struct usb_endpoint_descriptor fs_out_desc = {
208 	.bLength =		USB_DT_ENDPOINT_SIZE,
209 	.bDescriptorType =	USB_DT_ENDPOINT,
210 
211 	.bEndpointAddress =	USB_DIR_OUT,
212 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
213 };
214 
215 static struct usb_descriptor_header *eth_fs_function[] = {
216 	(struct usb_descriptor_header *) &rndis_iad_descriptor,
217 
218 	/* control interface matches ACM, not Ethernet */
219 	(struct usb_descriptor_header *) &rndis_control_intf,
220 	(struct usb_descriptor_header *) &header_desc,
221 	(struct usb_descriptor_header *) &call_mgmt_descriptor,
222 	(struct usb_descriptor_header *) &rndis_acm_descriptor,
223 	(struct usb_descriptor_header *) &rndis_union_desc,
224 	(struct usb_descriptor_header *) &fs_notify_desc,
225 
226 	/* data interface has no altsetting */
227 	(struct usb_descriptor_header *) &rndis_data_intf,
228 	(struct usb_descriptor_header *) &fs_in_desc,
229 	(struct usb_descriptor_header *) &fs_out_desc,
230 	NULL,
231 };
232 
233 /* high speed support: */
234 
235 static struct usb_endpoint_descriptor hs_notify_desc = {
236 	.bLength =		USB_DT_ENDPOINT_SIZE,
237 	.bDescriptorType =	USB_DT_ENDPOINT,
238 
239 	.bEndpointAddress =	USB_DIR_IN,
240 	.bmAttributes =		USB_ENDPOINT_XFER_INT,
241 	.wMaxPacketSize =	cpu_to_le16(STATUS_BYTECOUNT),
242 	.bInterval =		USB_MS_TO_HS_INTERVAL(RNDIS_STATUS_INTERVAL_MS)
243 };
244 
245 static struct usb_endpoint_descriptor hs_in_desc = {
246 	.bLength =		USB_DT_ENDPOINT_SIZE,
247 	.bDescriptorType =	USB_DT_ENDPOINT,
248 
249 	.bEndpointAddress =	USB_DIR_IN,
250 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
251 	.wMaxPacketSize =	cpu_to_le16(512),
252 };
253 
254 static struct usb_endpoint_descriptor hs_out_desc = {
255 	.bLength =		USB_DT_ENDPOINT_SIZE,
256 	.bDescriptorType =	USB_DT_ENDPOINT,
257 
258 	.bEndpointAddress =	USB_DIR_OUT,
259 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
260 	.wMaxPacketSize =	cpu_to_le16(512),
261 };
262 
263 static struct usb_descriptor_header *eth_hs_function[] = {
264 	(struct usb_descriptor_header *) &rndis_iad_descriptor,
265 
266 	/* control interface matches ACM, not Ethernet */
267 	(struct usb_descriptor_header *) &rndis_control_intf,
268 	(struct usb_descriptor_header *) &header_desc,
269 	(struct usb_descriptor_header *) &call_mgmt_descriptor,
270 	(struct usb_descriptor_header *) &rndis_acm_descriptor,
271 	(struct usb_descriptor_header *) &rndis_union_desc,
272 	(struct usb_descriptor_header *) &hs_notify_desc,
273 
274 	/* data interface has no altsetting */
275 	(struct usb_descriptor_header *) &rndis_data_intf,
276 	(struct usb_descriptor_header *) &hs_in_desc,
277 	(struct usb_descriptor_header *) &hs_out_desc,
278 	NULL,
279 };
280 
281 /* super speed support: */
282 
283 static struct usb_endpoint_descriptor ss_notify_desc = {
284 	.bLength =		USB_DT_ENDPOINT_SIZE,
285 	.bDescriptorType =	USB_DT_ENDPOINT,
286 
287 	.bEndpointAddress =	USB_DIR_IN,
288 	.bmAttributes =		USB_ENDPOINT_XFER_INT,
289 	.wMaxPacketSize =	cpu_to_le16(STATUS_BYTECOUNT),
290 	.bInterval =		USB_MS_TO_HS_INTERVAL(RNDIS_STATUS_INTERVAL_MS)
291 };
292 
293 static struct usb_ss_ep_comp_descriptor ss_intr_comp_desc = {
294 	.bLength =		sizeof ss_intr_comp_desc,
295 	.bDescriptorType =	USB_DT_SS_ENDPOINT_COMP,
296 
297 	/* the following 3 values can be tweaked if necessary */
298 	/* .bMaxBurst =		0, */
299 	/* .bmAttributes =	0, */
300 	.wBytesPerInterval =	cpu_to_le16(STATUS_BYTECOUNT),
301 };
302 
303 static struct usb_endpoint_descriptor ss_in_desc = {
304 	.bLength =		USB_DT_ENDPOINT_SIZE,
305 	.bDescriptorType =	USB_DT_ENDPOINT,
306 
307 	.bEndpointAddress =	USB_DIR_IN,
308 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
309 	.wMaxPacketSize =	cpu_to_le16(1024),
310 };
311 
312 static struct usb_endpoint_descriptor ss_out_desc = {
313 	.bLength =		USB_DT_ENDPOINT_SIZE,
314 	.bDescriptorType =	USB_DT_ENDPOINT,
315 
316 	.bEndpointAddress =	USB_DIR_OUT,
317 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
318 	.wMaxPacketSize =	cpu_to_le16(1024),
319 };
320 
321 static struct usb_ss_ep_comp_descriptor ss_bulk_comp_desc = {
322 	.bLength =		sizeof ss_bulk_comp_desc,
323 	.bDescriptorType =	USB_DT_SS_ENDPOINT_COMP,
324 
325 	/* the following 2 values can be tweaked if necessary */
326 	/* .bMaxBurst =		0, */
327 	/* .bmAttributes =	0, */
328 };
329 
330 static struct usb_descriptor_header *eth_ss_function[] = {
331 	(struct usb_descriptor_header *) &rndis_iad_descriptor,
332 
333 	/* control interface matches ACM, not Ethernet */
334 	(struct usb_descriptor_header *) &rndis_control_intf,
335 	(struct usb_descriptor_header *) &header_desc,
336 	(struct usb_descriptor_header *) &call_mgmt_descriptor,
337 	(struct usb_descriptor_header *) &rndis_acm_descriptor,
338 	(struct usb_descriptor_header *) &rndis_union_desc,
339 	(struct usb_descriptor_header *) &ss_notify_desc,
340 	(struct usb_descriptor_header *) &ss_intr_comp_desc,
341 
342 	/* data interface has no altsetting */
343 	(struct usb_descriptor_header *) &rndis_data_intf,
344 	(struct usb_descriptor_header *) &ss_in_desc,
345 	(struct usb_descriptor_header *) &ss_bulk_comp_desc,
346 	(struct usb_descriptor_header *) &ss_out_desc,
347 	(struct usb_descriptor_header *) &ss_bulk_comp_desc,
348 	NULL,
349 };
350 
351 /* string descriptors: */
352 
353 static struct usb_string rndis_string_defs[] = {
354 	[0].s = "RNDIS Communications Control",
355 	[1].s = "RNDIS Ethernet Data",
356 	[2].s = "RNDIS",
357 	{  } /* end of list */
358 };
359 
360 static struct usb_gadget_strings rndis_string_table = {
361 	.language =		0x0409,	/* en-us */
362 	.strings =		rndis_string_defs,
363 };
364 
365 static struct usb_gadget_strings *rndis_strings[] = {
366 	&rndis_string_table,
367 	NULL,
368 };
369 
370 /*-------------------------------------------------------------------------*/
371 
372 static struct sk_buff *rndis_add_header(struct gether *port,
373 					struct sk_buff *skb)
374 {
375 	struct sk_buff *skb2;
376 
377 	skb2 = skb_realloc_headroom(skb, sizeof(struct rndis_packet_msg_type));
378 	rndis_add_hdr(skb2);
379 
380 	dev_kfree_skb(skb);
381 	return skb2;
382 }
383 
384 static void rndis_response_available(void *_rndis)
385 {
386 	struct f_rndis			*rndis = _rndis;
387 	struct usb_request		*req = rndis->notify_req;
388 	struct usb_composite_dev	*cdev = rndis->port.func.config->cdev;
389 	__le32				*data = req->buf;
390 	int				status;
391 
392 	if (atomic_inc_return(&rndis->notify_count) != 1)
393 		return;
394 
395 	/* Send RNDIS RESPONSE_AVAILABLE notification; a
396 	 * USB_CDC_NOTIFY_RESPONSE_AVAILABLE "should" work too
397 	 *
398 	 * This is the only notification defined by RNDIS.
399 	 */
400 	data[0] = cpu_to_le32(1);
401 	data[1] = cpu_to_le32(0);
402 
403 	status = usb_ep_queue(rndis->notify, req, GFP_ATOMIC);
404 	if (status) {
405 		atomic_dec(&rndis->notify_count);
406 		DBG(cdev, "notify/0 --> %d\n", status);
407 	}
408 }
409 
410 static void rndis_response_complete(struct usb_ep *ep, struct usb_request *req)
411 {
412 	struct f_rndis			*rndis = req->context;
413 	struct usb_composite_dev	*cdev = rndis->port.func.config->cdev;
414 	int				status = req->status;
415 
416 	/* after TX:
417 	 *  - USB_CDC_GET_ENCAPSULATED_RESPONSE (ep0/control)
418 	 *  - RNDIS_RESPONSE_AVAILABLE (status/irq)
419 	 */
420 	switch (status) {
421 	case -ECONNRESET:
422 	case -ESHUTDOWN:
423 		/* connection gone */
424 		atomic_set(&rndis->notify_count, 0);
425 		break;
426 	default:
427 		DBG(cdev, "RNDIS %s response error %d, %d/%d\n",
428 			ep->name, status,
429 			req->actual, req->length);
430 		/* FALLTHROUGH */
431 	case 0:
432 		if (ep != rndis->notify)
433 			break;
434 
435 		/* handle multiple pending RNDIS_RESPONSE_AVAILABLE
436 		 * notifications by resending until we're done
437 		 */
438 		if (atomic_dec_and_test(&rndis->notify_count))
439 			break;
440 		status = usb_ep_queue(rndis->notify, req, GFP_ATOMIC);
441 		if (status) {
442 			atomic_dec(&rndis->notify_count);
443 			DBG(cdev, "notify/1 --> %d\n", status);
444 		}
445 		break;
446 	}
447 }
448 
449 static void rndis_command_complete(struct usb_ep *ep, struct usb_request *req)
450 {
451 	struct f_rndis			*rndis = req->context;
452 	int				status;
453 
454 	/* received RNDIS command from USB_CDC_SEND_ENCAPSULATED_COMMAND */
455 //	spin_lock(&dev->lock);
456 	status = rndis_msg_parser(rndis->params, (u8 *) req->buf);
457 	if (status < 0)
458 		pr_err("RNDIS command error %d, %d/%d\n",
459 			status, req->actual, req->length);
460 //	spin_unlock(&dev->lock);
461 }
462 
463 static int
464 rndis_setup(struct usb_function *f, const struct usb_ctrlrequest *ctrl)
465 {
466 	struct f_rndis		*rndis = func_to_rndis(f);
467 	struct usb_composite_dev *cdev = f->config->cdev;
468 	struct usb_request	*req = cdev->req;
469 	int			value = -EOPNOTSUPP;
470 	u16			w_index = le16_to_cpu(ctrl->wIndex);
471 	u16			w_value = le16_to_cpu(ctrl->wValue);
472 	u16			w_length = le16_to_cpu(ctrl->wLength);
473 
474 	/* composite driver infrastructure handles everything except
475 	 * CDC class messages; interface activation uses set_alt().
476 	 */
477 	switch ((ctrl->bRequestType << 8) | ctrl->bRequest) {
478 
479 	/* RNDIS uses the CDC command encapsulation mechanism to implement
480 	 * an RPC scheme, with much getting/setting of attributes by OID.
481 	 */
482 	case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
483 			| USB_CDC_SEND_ENCAPSULATED_COMMAND:
484 		if (w_value || w_index != rndis->ctrl_id)
485 			goto invalid;
486 		/* read the request; process it later */
487 		value = w_length;
488 		req->complete = rndis_command_complete;
489 		req->context = rndis;
490 		/* later, rndis_response_available() sends a notification */
491 		break;
492 
493 	case ((USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
494 			| USB_CDC_GET_ENCAPSULATED_RESPONSE:
495 		if (w_value || w_index != rndis->ctrl_id)
496 			goto invalid;
497 		else {
498 			u8 *buf;
499 			u32 n;
500 
501 			/* return the result */
502 			buf = rndis_get_next_response(rndis->params, &n);
503 			if (buf) {
504 				memcpy(req->buf, buf, n);
505 				req->complete = rndis_response_complete;
506 				req->context = rndis;
507 				rndis_free_response(rndis->params, buf);
508 				value = n;
509 			}
510 			/* else stalls ... spec says to avoid that */
511 		}
512 		break;
513 
514 	default:
515 invalid:
516 		VDBG(cdev, "invalid control req%02x.%02x v%04x i%04x l%d\n",
517 			ctrl->bRequestType, ctrl->bRequest,
518 			w_value, w_index, w_length);
519 	}
520 
521 	/* respond with data transfer or status phase? */
522 	if (value >= 0) {
523 		DBG(cdev, "rndis req%02x.%02x v%04x i%04x l%d\n",
524 			ctrl->bRequestType, ctrl->bRequest,
525 			w_value, w_index, w_length);
526 		req->zero = (value < w_length);
527 		req->length = value;
528 		value = usb_ep_queue(cdev->gadget->ep0, req, GFP_ATOMIC);
529 		if (value < 0)
530 			ERROR(cdev, "rndis response on err %d\n", value);
531 	}
532 
533 	/* device either stalls (value < 0) or reports success */
534 	return value;
535 }
536 
537 
538 static int rndis_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
539 {
540 	struct f_rndis		*rndis = func_to_rndis(f);
541 	struct usb_composite_dev *cdev = f->config->cdev;
542 
543 	/* we know alt == 0 */
544 
545 	if (intf == rndis->ctrl_id) {
546 		if (rndis->notify->driver_data) {
547 			VDBG(cdev, "reset rndis control %d\n", intf);
548 			usb_ep_disable(rndis->notify);
549 		}
550 		if (!rndis->notify->desc) {
551 			VDBG(cdev, "init rndis ctrl %d\n", intf);
552 			if (config_ep_by_speed(cdev->gadget, f, rndis->notify))
553 				goto fail;
554 		}
555 		usb_ep_enable(rndis->notify);
556 		rndis->notify->driver_data = rndis;
557 
558 	} else if (intf == rndis->data_id) {
559 		struct net_device	*net;
560 
561 		if (rndis->port.in_ep->driver_data) {
562 			DBG(cdev, "reset rndis\n");
563 			gether_disconnect(&rndis->port);
564 		}
565 
566 		if (!rndis->port.in_ep->desc || !rndis->port.out_ep->desc) {
567 			DBG(cdev, "init rndis\n");
568 			if (config_ep_by_speed(cdev->gadget, f,
569 					       rndis->port.in_ep) ||
570 			    config_ep_by_speed(cdev->gadget, f,
571 					       rndis->port.out_ep)) {
572 				rndis->port.in_ep->desc = NULL;
573 				rndis->port.out_ep->desc = NULL;
574 				goto fail;
575 			}
576 		}
577 
578 		/* Avoid ZLPs; they can be troublesome. */
579 		rndis->port.is_zlp_ok = false;
580 
581 		/* RNDIS should be in the "RNDIS uninitialized" state,
582 		 * either never activated or after rndis_uninit().
583 		 *
584 		 * We don't want data to flow here until a nonzero packet
585 		 * filter is set, at which point it enters "RNDIS data
586 		 * initialized" state ... but we do want the endpoints
587 		 * to be activated.  It's a strange little state.
588 		 *
589 		 * REVISIT the RNDIS gadget code has done this wrong for a
590 		 * very long time.  We need another call to the link layer
591 		 * code -- gether_updown(...bool) maybe -- to do it right.
592 		 */
593 		rndis->port.cdc_filter = 0;
594 
595 		DBG(cdev, "RNDIS RX/TX early activation ... \n");
596 		net = gether_connect(&rndis->port);
597 		if (IS_ERR(net))
598 			return PTR_ERR(net);
599 
600 		rndis_set_param_dev(rndis->params, net,
601 				&rndis->port.cdc_filter);
602 	} else
603 		goto fail;
604 
605 	return 0;
606 fail:
607 	return -EINVAL;
608 }
609 
610 static void rndis_disable(struct usb_function *f)
611 {
612 	struct f_rndis		*rndis = func_to_rndis(f);
613 	struct usb_composite_dev *cdev = f->config->cdev;
614 
615 	if (!rndis->notify->driver_data)
616 		return;
617 
618 	DBG(cdev, "rndis deactivated\n");
619 
620 	rndis_uninit(rndis->params);
621 	gether_disconnect(&rndis->port);
622 
623 	usb_ep_disable(rndis->notify);
624 	rndis->notify->driver_data = NULL;
625 }
626 
627 /*-------------------------------------------------------------------------*/
628 
629 /*
630  * This isn't quite the same mechanism as CDC Ethernet, since the
631  * notification scheme passes less data, but the same set of link
632  * states must be tested.  A key difference is that altsettings are
633  * not used to tell whether the link should send packets or not.
634  */
635 
636 static void rndis_open(struct gether *geth)
637 {
638 	struct f_rndis		*rndis = func_to_rndis(&geth->func);
639 	struct usb_composite_dev *cdev = geth->func.config->cdev;
640 
641 	DBG(cdev, "%s\n", __func__);
642 
643 	rndis_set_param_medium(rndis->params, RNDIS_MEDIUM_802_3,
644 				bitrate(cdev->gadget) / 100);
645 	rndis_signal_connect(rndis->params);
646 }
647 
648 static void rndis_close(struct gether *geth)
649 {
650 	struct f_rndis		*rndis = func_to_rndis(&geth->func);
651 
652 	DBG(geth->func.config->cdev, "%s\n", __func__);
653 
654 	rndis_set_param_medium(rndis->params, RNDIS_MEDIUM_802_3, 0);
655 	rndis_signal_disconnect(rndis->params);
656 }
657 
658 /*-------------------------------------------------------------------------*/
659 
660 /* Some controllers can't support RNDIS ... */
661 static inline bool can_support_rndis(struct usb_configuration *c)
662 {
663 	/* everything else is *presumably* fine */
664 	return true;
665 }
666 
667 /* ethernet function driver setup/binding */
668 
669 static int
670 rndis_bind(struct usb_configuration *c, struct usb_function *f)
671 {
672 	struct usb_composite_dev *cdev = c->cdev;
673 	struct f_rndis		*rndis = func_to_rndis(f);
674 	struct usb_string	*us;
675 	int			status;
676 	struct usb_ep		*ep;
677 
678 	struct f_rndis_opts *rndis_opts;
679 
680 	if (!can_support_rndis(c))
681 		return -EINVAL;
682 
683 	rndis_opts = container_of(f->fi, struct f_rndis_opts, func_inst);
684 
685 	if (cdev->use_os_string) {
686 		f->os_desc_table = kzalloc(sizeof(*f->os_desc_table),
687 					   GFP_KERNEL);
688 		if (!f->os_desc_table)
689 			return -ENOMEM;
690 		f->os_desc_n = 1;
691 		f->os_desc_table[0].os_desc = &rndis_opts->rndis_os_desc;
692 	}
693 
694 	/*
695 	 * in drivers/usb/gadget/configfs.c:configfs_composite_bind()
696 	 * configurations are bound in sequence with list_for_each_entry,
697 	 * in each configuration its functions are bound in sequence
698 	 * with list_for_each_entry, so we assume no race condition
699 	 * with regard to rndis_opts->bound access
700 	 */
701 	if (!rndis_opts->bound) {
702 		gether_set_gadget(rndis_opts->net, cdev->gadget);
703 		status = gether_register_netdev(rndis_opts->net);
704 		if (status)
705 			goto fail;
706 		rndis_opts->bound = true;
707 	}
708 
709 	us = usb_gstrings_attach(cdev, rndis_strings,
710 				 ARRAY_SIZE(rndis_string_defs));
711 	if (IS_ERR(us)) {
712 		status = PTR_ERR(us);
713 		goto fail;
714 	}
715 	rndis_control_intf.iInterface = us[0].id;
716 	rndis_data_intf.iInterface = us[1].id;
717 	rndis_iad_descriptor.iFunction = us[2].id;
718 
719 	/* allocate instance-specific interface IDs */
720 	status = usb_interface_id(c, f);
721 	if (status < 0)
722 		goto fail;
723 	rndis->ctrl_id = status;
724 	rndis_iad_descriptor.bFirstInterface = status;
725 
726 	rndis_control_intf.bInterfaceNumber = status;
727 	rndis_union_desc.bMasterInterface0 = status;
728 
729 	if (cdev->use_os_string)
730 		f->os_desc_table[0].if_id =
731 			rndis_iad_descriptor.bFirstInterface;
732 
733 	status = usb_interface_id(c, f);
734 	if (status < 0)
735 		goto fail;
736 	rndis->data_id = status;
737 
738 	rndis_data_intf.bInterfaceNumber = status;
739 	rndis_union_desc.bSlaveInterface0 = status;
740 
741 	status = -ENODEV;
742 
743 	/* allocate instance-specific endpoints */
744 	ep = usb_ep_autoconfig(cdev->gadget, &fs_in_desc);
745 	if (!ep)
746 		goto fail;
747 	rndis->port.in_ep = ep;
748 	ep->driver_data = cdev;	/* claim */
749 
750 	ep = usb_ep_autoconfig(cdev->gadget, &fs_out_desc);
751 	if (!ep)
752 		goto fail;
753 	rndis->port.out_ep = ep;
754 	ep->driver_data = cdev;	/* claim */
755 
756 	/* NOTE:  a status/notification endpoint is, strictly speaking,
757 	 * optional.  We don't treat it that way though!  It's simpler,
758 	 * and some newer profiles don't treat it as optional.
759 	 */
760 	ep = usb_ep_autoconfig(cdev->gadget, &fs_notify_desc);
761 	if (!ep)
762 		goto fail;
763 	rndis->notify = ep;
764 	ep->driver_data = cdev;	/* claim */
765 
766 	status = -ENOMEM;
767 
768 	/* allocate notification request and buffer */
769 	rndis->notify_req = usb_ep_alloc_request(ep, GFP_KERNEL);
770 	if (!rndis->notify_req)
771 		goto fail;
772 	rndis->notify_req->buf = kmalloc(STATUS_BYTECOUNT, GFP_KERNEL);
773 	if (!rndis->notify_req->buf)
774 		goto fail;
775 	rndis->notify_req->length = STATUS_BYTECOUNT;
776 	rndis->notify_req->context = rndis;
777 	rndis->notify_req->complete = rndis_response_complete;
778 
779 	/* support all relevant hardware speeds... we expect that when
780 	 * hardware is dual speed, all bulk-capable endpoints work at
781 	 * both speeds
782 	 */
783 	hs_in_desc.bEndpointAddress = fs_in_desc.bEndpointAddress;
784 	hs_out_desc.bEndpointAddress = fs_out_desc.bEndpointAddress;
785 	hs_notify_desc.bEndpointAddress = fs_notify_desc.bEndpointAddress;
786 
787 	ss_in_desc.bEndpointAddress = fs_in_desc.bEndpointAddress;
788 	ss_out_desc.bEndpointAddress = fs_out_desc.bEndpointAddress;
789 	ss_notify_desc.bEndpointAddress = fs_notify_desc.bEndpointAddress;
790 
791 	status = usb_assign_descriptors(f, eth_fs_function, eth_hs_function,
792 			eth_ss_function);
793 	if (status)
794 		goto fail;
795 
796 	rndis->port.open = rndis_open;
797 	rndis->port.close = rndis_close;
798 
799 	rndis_set_param_medium(rndis->params, RNDIS_MEDIUM_802_3, 0);
800 	rndis_set_host_mac(rndis->params, rndis->ethaddr);
801 
802 	if (rndis->manufacturer && rndis->vendorID &&
803 			rndis_set_param_vendor(rndis->params, rndis->vendorID,
804 					       rndis->manufacturer)) {
805 		status = -EINVAL;
806 		goto fail_free_descs;
807 	}
808 
809 	/* NOTE:  all that is done without knowing or caring about
810 	 * the network link ... which is unavailable to this code
811 	 * until we're activated via set_alt().
812 	 */
813 
814 	DBG(cdev, "RNDIS: %s speed IN/%s OUT/%s NOTIFY/%s\n",
815 			gadget_is_superspeed(c->cdev->gadget) ? "super" :
816 			gadget_is_dualspeed(c->cdev->gadget) ? "dual" : "full",
817 			rndis->port.in_ep->name, rndis->port.out_ep->name,
818 			rndis->notify->name);
819 	return 0;
820 
821 fail_free_descs:
822 	usb_free_all_descriptors(f);
823 fail:
824 	kfree(f->os_desc_table);
825 	f->os_desc_n = 0;
826 
827 	if (rndis->notify_req) {
828 		kfree(rndis->notify_req->buf);
829 		usb_ep_free_request(rndis->notify, rndis->notify_req);
830 	}
831 
832 	/* we might as well release our claims on endpoints */
833 	if (rndis->notify)
834 		rndis->notify->driver_data = NULL;
835 	if (rndis->port.out_ep)
836 		rndis->port.out_ep->driver_data = NULL;
837 	if (rndis->port.in_ep)
838 		rndis->port.in_ep->driver_data = NULL;
839 
840 	ERROR(cdev, "%s: can't bind, err %d\n", f->name, status);
841 
842 	return status;
843 }
844 
845 void rndis_borrow_net(struct usb_function_instance *f, struct net_device *net)
846 {
847 	struct f_rndis_opts *opts;
848 
849 	opts = container_of(f, struct f_rndis_opts, func_inst);
850 	if (opts->bound)
851 		gether_cleanup(netdev_priv(opts->net));
852 	else
853 		free_netdev(opts->net);
854 	opts->borrowed_net = opts->bound = true;
855 	opts->net = net;
856 }
857 EXPORT_SYMBOL_GPL(rndis_borrow_net);
858 
859 static inline struct f_rndis_opts *to_f_rndis_opts(struct config_item *item)
860 {
861 	return container_of(to_config_group(item), struct f_rndis_opts,
862 			    func_inst.group);
863 }
864 
865 /* f_rndis_item_ops */
866 USB_ETHERNET_CONFIGFS_ITEM(rndis);
867 
868 /* f_rndis_opts_dev_addr */
869 USB_ETHERNET_CONFIGFS_ITEM_ATTR_DEV_ADDR(rndis);
870 
871 /* f_rndis_opts_host_addr */
872 USB_ETHERNET_CONFIGFS_ITEM_ATTR_HOST_ADDR(rndis);
873 
874 /* f_rndis_opts_qmult */
875 USB_ETHERNET_CONFIGFS_ITEM_ATTR_QMULT(rndis);
876 
877 /* f_rndis_opts_ifname */
878 USB_ETHERNET_CONFIGFS_ITEM_ATTR_IFNAME(rndis);
879 
880 static struct configfs_attribute *rndis_attrs[] = {
881 	&f_rndis_opts_dev_addr.attr,
882 	&f_rndis_opts_host_addr.attr,
883 	&f_rndis_opts_qmult.attr,
884 	&f_rndis_opts_ifname.attr,
885 	NULL,
886 };
887 
888 static struct config_item_type rndis_func_type = {
889 	.ct_item_ops	= &rndis_item_ops,
890 	.ct_attrs	= rndis_attrs,
891 	.ct_owner	= THIS_MODULE,
892 };
893 
894 static void rndis_free_inst(struct usb_function_instance *f)
895 {
896 	struct f_rndis_opts *opts;
897 
898 	opts = container_of(f, struct f_rndis_opts, func_inst);
899 	if (!opts->borrowed_net) {
900 		if (opts->bound)
901 			gether_cleanup(netdev_priv(opts->net));
902 		else
903 			free_netdev(opts->net);
904 	}
905 
906 	kfree(opts->rndis_os_desc.group.default_groups); /* single VLA chunk */
907 	kfree(opts);
908 }
909 
910 static struct usb_function_instance *rndis_alloc_inst(void)
911 {
912 	struct f_rndis_opts *opts;
913 	struct usb_os_desc *descs[1];
914 	char *names[1];
915 
916 	opts = kzalloc(sizeof(*opts), GFP_KERNEL);
917 	if (!opts)
918 		return ERR_PTR(-ENOMEM);
919 	opts->rndis_os_desc.ext_compat_id = opts->rndis_ext_compat_id;
920 
921 	mutex_init(&opts->lock);
922 	opts->func_inst.free_func_inst = rndis_free_inst;
923 	opts->net = gether_setup_default();
924 	if (IS_ERR(opts->net)) {
925 		struct net_device *net = opts->net;
926 		kfree(opts);
927 		return ERR_CAST(net);
928 	}
929 	INIT_LIST_HEAD(&opts->rndis_os_desc.ext_prop);
930 
931 	descs[0] = &opts->rndis_os_desc;
932 	names[0] = "rndis";
933 	usb_os_desc_prepare_interf_dir(&opts->func_inst.group, 1, descs,
934 				       names, THIS_MODULE);
935 	config_group_init_type_name(&opts->func_inst.group, "",
936 				    &rndis_func_type);
937 
938 	return &opts->func_inst;
939 }
940 
941 static void rndis_free(struct usb_function *f)
942 {
943 	struct f_rndis *rndis;
944 	struct f_rndis_opts *opts;
945 
946 	rndis = func_to_rndis(f);
947 	rndis_deregister(rndis->params);
948 	opts = container_of(f->fi, struct f_rndis_opts, func_inst);
949 	kfree(rndis);
950 	mutex_lock(&opts->lock);
951 	opts->refcnt--;
952 	mutex_unlock(&opts->lock);
953 }
954 
955 static void rndis_unbind(struct usb_configuration *c, struct usb_function *f)
956 {
957 	struct f_rndis		*rndis = func_to_rndis(f);
958 
959 	kfree(f->os_desc_table);
960 	f->os_desc_n = 0;
961 	usb_free_all_descriptors(f);
962 
963 	kfree(rndis->notify_req->buf);
964 	usb_ep_free_request(rndis->notify, rndis->notify_req);
965 }
966 
967 static struct usb_function *rndis_alloc(struct usb_function_instance *fi)
968 {
969 	struct f_rndis	*rndis;
970 	struct f_rndis_opts *opts;
971 	struct rndis_params *params;
972 
973 	/* allocate and initialize one new instance */
974 	rndis = kzalloc(sizeof(*rndis), GFP_KERNEL);
975 	if (!rndis)
976 		return ERR_PTR(-ENOMEM);
977 
978 	opts = container_of(fi, struct f_rndis_opts, func_inst);
979 	mutex_lock(&opts->lock);
980 	opts->refcnt++;
981 
982 	gether_get_host_addr_u8(opts->net, rndis->ethaddr);
983 	rndis->vendorID = opts->vendor_id;
984 	rndis->manufacturer = opts->manufacturer;
985 
986 	rndis->port.ioport = netdev_priv(opts->net);
987 	mutex_unlock(&opts->lock);
988 	/* RNDIS activates when the host changes this filter */
989 	rndis->port.cdc_filter = 0;
990 
991 	/* RNDIS has special (and complex) framing */
992 	rndis->port.header_len = sizeof(struct rndis_packet_msg_type);
993 	rndis->port.wrap = rndis_add_header;
994 	rndis->port.unwrap = rndis_rm_hdr;
995 
996 	rndis->port.func.name = "rndis";
997 	/* descriptors are per-instance copies */
998 	rndis->port.func.bind = rndis_bind;
999 	rndis->port.func.unbind = rndis_unbind;
1000 	rndis->port.func.set_alt = rndis_set_alt;
1001 	rndis->port.func.setup = rndis_setup;
1002 	rndis->port.func.disable = rndis_disable;
1003 	rndis->port.func.free_func = rndis_free;
1004 
1005 	params = rndis_register(rndis_response_available, rndis);
1006 	if (IS_ERR(params)) {
1007 		kfree(rndis);
1008 		return ERR_CAST(params);
1009 	}
1010 	rndis->params = params;
1011 
1012 	return &rndis->port.func;
1013 }
1014 
1015 DECLARE_USB_FUNCTION_INIT(rndis, rndis_alloc_inst, rndis_alloc);
1016 MODULE_LICENSE("GPL");
1017 MODULE_AUTHOR("David Brownell");
1018