1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * f_eem.c -- USB CDC Ethernet (EEM) link function driver
4  *
5  * Copyright (C) 2003-2005,2008 David Brownell
6  * Copyright (C) 2008 Nokia Corporation
7  * Copyright (C) 2009 EF Johnson Technologies
8  */
9 
10 #include <linux/kernel.h>
11 #include <linux/module.h>
12 #include <linux/device.h>
13 #include <linux/etherdevice.h>
14 #include <linux/crc32.h>
15 #include <linux/slab.h>
16 
17 #include "u_ether.h"
18 #include "u_ether_configfs.h"
19 #include "u_eem.h"
20 
21 #define EEM_HLEN 2
22 
23 /*
24  * This function is a "CDC Ethernet Emulation Model" (CDC EEM)
25  * Ethernet link.
26  */
27 
28 struct f_eem {
29 	struct gether			port;
30 	u8				ctrl_id;
31 };
32 
33 static inline struct f_eem *func_to_eem(struct usb_function *f)
34 {
35 	return container_of(f, struct f_eem, port.func);
36 }
37 
38 /*-------------------------------------------------------------------------*/
39 
40 /* interface descriptor: */
41 
42 static struct usb_interface_descriptor eem_intf = {
43 	.bLength =		sizeof eem_intf,
44 	.bDescriptorType =	USB_DT_INTERFACE,
45 
46 	/* .bInterfaceNumber = DYNAMIC */
47 	.bNumEndpoints =	2,
48 	.bInterfaceClass =	USB_CLASS_COMM,
49 	.bInterfaceSubClass =	USB_CDC_SUBCLASS_EEM,
50 	.bInterfaceProtocol =	USB_CDC_PROTO_EEM,
51 	/* .iInterface = DYNAMIC */
52 };
53 
54 /* full speed support: */
55 
56 static struct usb_endpoint_descriptor eem_fs_in_desc = {
57 	.bLength =		USB_DT_ENDPOINT_SIZE,
58 	.bDescriptorType =	USB_DT_ENDPOINT,
59 
60 	.bEndpointAddress =	USB_DIR_IN,
61 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
62 };
63 
64 static struct usb_endpoint_descriptor eem_fs_out_desc = {
65 	.bLength =		USB_DT_ENDPOINT_SIZE,
66 	.bDescriptorType =	USB_DT_ENDPOINT,
67 
68 	.bEndpointAddress =	USB_DIR_OUT,
69 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
70 };
71 
72 static struct usb_descriptor_header *eem_fs_function[] = {
73 	/* CDC EEM control descriptors */
74 	(struct usb_descriptor_header *) &eem_intf,
75 	(struct usb_descriptor_header *) &eem_fs_in_desc,
76 	(struct usb_descriptor_header *) &eem_fs_out_desc,
77 	NULL,
78 };
79 
80 /* high speed support: */
81 
82 static struct usb_endpoint_descriptor eem_hs_in_desc = {
83 	.bLength =		USB_DT_ENDPOINT_SIZE,
84 	.bDescriptorType =	USB_DT_ENDPOINT,
85 
86 	.bEndpointAddress =	USB_DIR_IN,
87 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
88 	.wMaxPacketSize =	cpu_to_le16(512),
89 };
90 
91 static struct usb_endpoint_descriptor eem_hs_out_desc = {
92 	.bLength =		USB_DT_ENDPOINT_SIZE,
93 	.bDescriptorType =	USB_DT_ENDPOINT,
94 
95 	.bEndpointAddress =	USB_DIR_OUT,
96 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
97 	.wMaxPacketSize =	cpu_to_le16(512),
98 };
99 
100 static struct usb_descriptor_header *eem_hs_function[] = {
101 	/* CDC EEM control descriptors */
102 	(struct usb_descriptor_header *) &eem_intf,
103 	(struct usb_descriptor_header *) &eem_hs_in_desc,
104 	(struct usb_descriptor_header *) &eem_hs_out_desc,
105 	NULL,
106 };
107 
108 /* super speed support: */
109 
110 static struct usb_endpoint_descriptor eem_ss_in_desc = {
111 	.bLength =		USB_DT_ENDPOINT_SIZE,
112 	.bDescriptorType =	USB_DT_ENDPOINT,
113 
114 	.bEndpointAddress =	USB_DIR_IN,
115 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
116 	.wMaxPacketSize =	cpu_to_le16(1024),
117 };
118 
119 static struct usb_endpoint_descriptor eem_ss_out_desc = {
120 	.bLength =		USB_DT_ENDPOINT_SIZE,
121 	.bDescriptorType =	USB_DT_ENDPOINT,
122 
123 	.bEndpointAddress =	USB_DIR_OUT,
124 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
125 	.wMaxPacketSize =	cpu_to_le16(1024),
126 };
127 
128 static struct usb_ss_ep_comp_descriptor eem_ss_bulk_comp_desc = {
129 	.bLength =		sizeof eem_ss_bulk_comp_desc,
130 	.bDescriptorType =	USB_DT_SS_ENDPOINT_COMP,
131 
132 	/* the following 2 values can be tweaked if necessary */
133 	/* .bMaxBurst =		0, */
134 	/* .bmAttributes =	0, */
135 };
136 
137 static struct usb_descriptor_header *eem_ss_function[] = {
138 	/* CDC EEM control descriptors */
139 	(struct usb_descriptor_header *) &eem_intf,
140 	(struct usb_descriptor_header *) &eem_ss_in_desc,
141 	(struct usb_descriptor_header *) &eem_ss_bulk_comp_desc,
142 	(struct usb_descriptor_header *) &eem_ss_out_desc,
143 	(struct usb_descriptor_header *) &eem_ss_bulk_comp_desc,
144 	NULL,
145 };
146 
147 /* string descriptors: */
148 
149 static struct usb_string eem_string_defs[] = {
150 	[0].s = "CDC Ethernet Emulation Model (EEM)",
151 	{  } /* end of list */
152 };
153 
154 static struct usb_gadget_strings eem_string_table = {
155 	.language =		0x0409,	/* en-us */
156 	.strings =		eem_string_defs,
157 };
158 
159 static struct usb_gadget_strings *eem_strings[] = {
160 	&eem_string_table,
161 	NULL,
162 };
163 
164 /*-------------------------------------------------------------------------*/
165 
166 static int eem_setup(struct usb_function *f, const struct usb_ctrlrequest *ctrl)
167 {
168 	struct usb_composite_dev *cdev = f->config->cdev;
169 	int			value = -EOPNOTSUPP;
170 	u16			w_index = le16_to_cpu(ctrl->wIndex);
171 	u16			w_value = le16_to_cpu(ctrl->wValue);
172 	u16			w_length = le16_to_cpu(ctrl->wLength);
173 
174 	DBG(cdev, "invalid control req%02x.%02x v%04x i%04x l%d\n",
175 		ctrl->bRequestType, ctrl->bRequest,
176 		w_value, w_index, w_length);
177 
178 	/* device either stalls (value < 0) or reports success */
179 	return value;
180 }
181 
182 
183 static int eem_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
184 {
185 	struct f_eem		*eem = func_to_eem(f);
186 	struct usb_composite_dev *cdev = f->config->cdev;
187 	struct net_device	*net;
188 
189 	/* we know alt == 0, so this is an activation or a reset */
190 	if (alt != 0)
191 		goto fail;
192 
193 	if (intf == eem->ctrl_id) {
194 		DBG(cdev, "reset eem\n");
195 		gether_disconnect(&eem->port);
196 
197 		if (!eem->port.in_ep->desc || !eem->port.out_ep->desc) {
198 			DBG(cdev, "init eem\n");
199 			if (config_ep_by_speed(cdev->gadget, f,
200 					       eem->port.in_ep) ||
201 			    config_ep_by_speed(cdev->gadget, f,
202 					       eem->port.out_ep)) {
203 				eem->port.in_ep->desc = NULL;
204 				eem->port.out_ep->desc = NULL;
205 				goto fail;
206 			}
207 		}
208 
209 		/* zlps should not occur because zero-length EEM packets
210 		 * will be inserted in those cases where they would occur
211 		 */
212 		eem->port.is_zlp_ok = 1;
213 		eem->port.cdc_filter = DEFAULT_FILTER;
214 		DBG(cdev, "activate eem\n");
215 		net = gether_connect(&eem->port);
216 		if (IS_ERR(net))
217 			return PTR_ERR(net);
218 	} else
219 		goto fail;
220 
221 	return 0;
222 fail:
223 	return -EINVAL;
224 }
225 
226 static void eem_disable(struct usb_function *f)
227 {
228 	struct f_eem		*eem = func_to_eem(f);
229 	struct usb_composite_dev *cdev = f->config->cdev;
230 
231 	DBG(cdev, "eem deactivated\n");
232 
233 	if (eem->port.in_ep->enabled)
234 		gether_disconnect(&eem->port);
235 }
236 
237 /*-------------------------------------------------------------------------*/
238 
239 /* EEM function driver setup/binding */
240 
241 static int eem_bind(struct usb_configuration *c, struct usb_function *f)
242 {
243 	struct usb_composite_dev *cdev = c->cdev;
244 	struct f_eem		*eem = func_to_eem(f);
245 	struct usb_string	*us;
246 	int			status;
247 	struct usb_ep		*ep;
248 
249 	struct f_eem_opts	*eem_opts;
250 
251 	eem_opts = container_of(f->fi, struct f_eem_opts, func_inst);
252 	/*
253 	 * in drivers/usb/gadget/configfs.c:configfs_composite_bind()
254 	 * configurations are bound in sequence with list_for_each_entry,
255 	 * in each configuration its functions are bound in sequence
256 	 * with list_for_each_entry, so we assume no race condition
257 	 * with regard to eem_opts->bound access
258 	 */
259 	if (!eem_opts->bound) {
260 		mutex_lock(&eem_opts->lock);
261 		gether_set_gadget(eem_opts->net, cdev->gadget);
262 		status = gether_register_netdev(eem_opts->net);
263 		mutex_unlock(&eem_opts->lock);
264 		if (status)
265 			return status;
266 		eem_opts->bound = true;
267 	}
268 
269 	us = usb_gstrings_attach(cdev, eem_strings,
270 				 ARRAY_SIZE(eem_string_defs));
271 	if (IS_ERR(us))
272 		return PTR_ERR(us);
273 	eem_intf.iInterface = us[0].id;
274 
275 	/* allocate instance-specific interface IDs */
276 	status = usb_interface_id(c, f);
277 	if (status < 0)
278 		goto fail;
279 	eem->ctrl_id = status;
280 	eem_intf.bInterfaceNumber = status;
281 
282 	status = -ENODEV;
283 
284 	/* allocate instance-specific endpoints */
285 	ep = usb_ep_autoconfig(cdev->gadget, &eem_fs_in_desc);
286 	if (!ep)
287 		goto fail;
288 	eem->port.in_ep = ep;
289 
290 	ep = usb_ep_autoconfig(cdev->gadget, &eem_fs_out_desc);
291 	if (!ep)
292 		goto fail;
293 	eem->port.out_ep = ep;
294 
295 	status = -ENOMEM;
296 
297 	/* support all relevant hardware speeds... we expect that when
298 	 * hardware is dual speed, all bulk-capable endpoints work at
299 	 * both speeds
300 	 */
301 	eem_hs_in_desc.bEndpointAddress = eem_fs_in_desc.bEndpointAddress;
302 	eem_hs_out_desc.bEndpointAddress = eem_fs_out_desc.bEndpointAddress;
303 
304 	eem_ss_in_desc.bEndpointAddress = eem_fs_in_desc.bEndpointAddress;
305 	eem_ss_out_desc.bEndpointAddress = eem_fs_out_desc.bEndpointAddress;
306 
307 	status = usb_assign_descriptors(f, eem_fs_function, eem_hs_function,
308 			eem_ss_function, NULL);
309 	if (status)
310 		goto fail;
311 
312 	DBG(cdev, "CDC Ethernet (EEM): %s speed IN/%s OUT/%s\n",
313 			gadget_is_superspeed(c->cdev->gadget) ? "super" :
314 			gadget_is_dualspeed(c->cdev->gadget) ? "dual" : "full",
315 			eem->port.in_ep->name, eem->port.out_ep->name);
316 	return 0;
317 
318 fail:
319 	ERROR(cdev, "%s: can't bind, err %d\n", f->name, status);
320 
321 	return status;
322 }
323 
324 static void eem_cmd_complete(struct usb_ep *ep, struct usb_request *req)
325 {
326 	struct sk_buff *skb = (struct sk_buff *)req->context;
327 
328 	dev_kfree_skb_any(skb);
329 }
330 
331 /*
332  * Add the EEM header and ethernet checksum.
333  * We currently do not attempt to put multiple ethernet frames
334  * into a single USB transfer
335  */
336 static struct sk_buff *eem_wrap(struct gether *port, struct sk_buff *skb)
337 {
338 	struct sk_buff	*skb2 = NULL;
339 	struct usb_ep	*in = port->in_ep;
340 	int		headroom, tailroom, padlen = 0;
341 	u16		len;
342 
343 	if (!skb)
344 		return NULL;
345 
346 	len = skb->len;
347 	headroom = skb_headroom(skb);
348 	tailroom = skb_tailroom(skb);
349 
350 	/* When (len + EEM_HLEN + ETH_FCS_LEN) % in->maxpacket) is 0,
351 	 * stick two bytes of zero-length EEM packet on the end.
352 	 */
353 	if (((len + EEM_HLEN + ETH_FCS_LEN) % in->maxpacket) == 0)
354 		padlen += 2;
355 
356 	if ((tailroom >= (ETH_FCS_LEN + padlen)) &&
357 			(headroom >= EEM_HLEN) && !skb_cloned(skb))
358 		goto done;
359 
360 	skb2 = skb_copy_expand(skb, EEM_HLEN, ETH_FCS_LEN + padlen, GFP_ATOMIC);
361 	dev_kfree_skb_any(skb);
362 	skb = skb2;
363 	if (!skb)
364 		return skb;
365 
366 done:
367 	/* use the "no CRC" option */
368 	put_unaligned_be32(0xdeadbeef, skb_put(skb, 4));
369 
370 	/* EEM packet header format:
371 	 * b0..13:	length of ethernet frame
372 	 * b14:		bmCRC (0 == sentinel CRC)
373 	 * b15:		bmType (0 == data)
374 	 */
375 	len = skb->len;
376 	put_unaligned_le16(len & 0x3FFF, skb_push(skb, 2));
377 
378 	/* add a zero-length EEM packet, if needed */
379 	if (padlen)
380 		put_unaligned_le16(0, skb_put(skb, 2));
381 
382 	return skb;
383 }
384 
385 /*
386  * Remove the EEM header.  Note that there can be many EEM packets in a single
387  * USB transfer, so we need to break them out and handle them independently.
388  */
389 static int eem_unwrap(struct gether *port,
390 			struct sk_buff *skb,
391 			struct sk_buff_head *list)
392 {
393 	struct usb_composite_dev	*cdev = port->func.config->cdev;
394 	int				status = 0;
395 
396 	do {
397 		struct sk_buff	*skb2;
398 		u16		header;
399 		u16		len = 0;
400 
401 		if (skb->len < EEM_HLEN) {
402 			status = -EINVAL;
403 			DBG(cdev, "invalid EEM header\n");
404 			goto error;
405 		}
406 
407 		/* remove the EEM header */
408 		header = get_unaligned_le16(skb->data);
409 		skb_pull(skb, EEM_HLEN);
410 
411 		/* EEM packet header format:
412 		 * b0..14:	EEM type dependent (data or command)
413 		 * b15:		bmType (0 == data, 1 == command)
414 		 */
415 		if (header & BIT(15)) {
416 			struct usb_request	*req = cdev->req;
417 			u16			bmEEMCmd;
418 
419 			/* EEM command packet format:
420 			 * b0..10:	bmEEMCmdParam
421 			 * b11..13:	bmEEMCmd
422 			 * b14:		reserved (must be zero)
423 			 * b15:		bmType (1 == command)
424 			 */
425 			if (header & BIT(14))
426 				continue;
427 
428 			bmEEMCmd = (header >> 11) & 0x7;
429 			switch (bmEEMCmd) {
430 			case 0: /* echo */
431 				len = header & 0x7FF;
432 				if (skb->len < len) {
433 					status = -EOVERFLOW;
434 					goto error;
435 				}
436 
437 				skb2 = skb_clone(skb, GFP_ATOMIC);
438 				if (unlikely(!skb2)) {
439 					DBG(cdev, "EEM echo response error\n");
440 					goto next;
441 				}
442 				skb_trim(skb2, len);
443 				put_unaligned_le16(BIT(15) | BIT(11) | len,
444 							skb_push(skb2, 2));
445 				skb_copy_bits(skb2, 0, req->buf, skb2->len);
446 				req->length = skb2->len;
447 				req->complete = eem_cmd_complete;
448 				req->zero = 1;
449 				req->context = skb2;
450 				if (usb_ep_queue(port->in_ep, req, GFP_ATOMIC))
451 					DBG(cdev, "echo response queue fail\n");
452 				break;
453 
454 			case 1:  /* echo response */
455 			case 2:  /* suspend hint */
456 			case 3:  /* response hint */
457 			case 4:  /* response complete hint */
458 			case 5:  /* tickle */
459 			default: /* reserved */
460 				continue;
461 			}
462 		} else {
463 			u32		crc, crc2;
464 			struct sk_buff	*skb3;
465 
466 			/* check for zero-length EEM packet */
467 			if (header == 0)
468 				continue;
469 
470 			/* EEM data packet format:
471 			 * b0..13:	length of ethernet frame
472 			 * b14:		bmCRC (0 == sentinel, 1 == calculated)
473 			 * b15:		bmType (0 == data)
474 			 */
475 			len = header & 0x3FFF;
476 			if ((skb->len < len)
477 					|| (len < (ETH_HLEN + ETH_FCS_LEN))) {
478 				status = -EINVAL;
479 				goto error;
480 			}
481 
482 			/* validate CRC */
483 			if (header & BIT(14)) {
484 				crc = get_unaligned_le32(skb->data + len
485 							- ETH_FCS_LEN);
486 				crc2 = ~crc32_le(~0,
487 						skb->data, len - ETH_FCS_LEN);
488 			} else {
489 				crc = get_unaligned_be32(skb->data + len
490 							- ETH_FCS_LEN);
491 				crc2 = 0xdeadbeef;
492 			}
493 			if (crc != crc2) {
494 				DBG(cdev, "invalid EEM CRC\n");
495 				goto next;
496 			}
497 
498 			skb2 = skb_clone(skb, GFP_ATOMIC);
499 			if (unlikely(!skb2)) {
500 				DBG(cdev, "unable to unframe EEM packet\n");
501 				continue;
502 			}
503 			skb_trim(skb2, len - ETH_FCS_LEN);
504 
505 			skb3 = skb_copy_expand(skb2,
506 						NET_IP_ALIGN,
507 						0,
508 						GFP_ATOMIC);
509 			if (unlikely(!skb3)) {
510 				dev_kfree_skb_any(skb2);
511 				continue;
512 			}
513 			dev_kfree_skb_any(skb2);
514 			skb_queue_tail(list, skb3);
515 		}
516 next:
517 		skb_pull(skb, len);
518 	} while (skb->len);
519 
520 error:
521 	dev_kfree_skb_any(skb);
522 	return status;
523 }
524 
525 static inline struct f_eem_opts *to_f_eem_opts(struct config_item *item)
526 {
527 	return container_of(to_config_group(item), struct f_eem_opts,
528 			    func_inst.group);
529 }
530 
531 /* f_eem_item_ops */
532 USB_ETHERNET_CONFIGFS_ITEM(eem);
533 
534 /* f_eem_opts_dev_addr */
535 USB_ETHERNET_CONFIGFS_ITEM_ATTR_DEV_ADDR(eem);
536 
537 /* f_eem_opts_host_addr */
538 USB_ETHERNET_CONFIGFS_ITEM_ATTR_HOST_ADDR(eem);
539 
540 /* f_eem_opts_qmult */
541 USB_ETHERNET_CONFIGFS_ITEM_ATTR_QMULT(eem);
542 
543 /* f_eem_opts_ifname */
544 USB_ETHERNET_CONFIGFS_ITEM_ATTR_IFNAME(eem);
545 
546 static struct configfs_attribute *eem_attrs[] = {
547 	&eem_opts_attr_dev_addr,
548 	&eem_opts_attr_host_addr,
549 	&eem_opts_attr_qmult,
550 	&eem_opts_attr_ifname,
551 	NULL,
552 };
553 
554 static const struct config_item_type eem_func_type = {
555 	.ct_item_ops	= &eem_item_ops,
556 	.ct_attrs	= eem_attrs,
557 	.ct_owner	= THIS_MODULE,
558 };
559 
560 static void eem_free_inst(struct usb_function_instance *f)
561 {
562 	struct f_eem_opts *opts;
563 
564 	opts = container_of(f, struct f_eem_opts, func_inst);
565 	if (opts->bound)
566 		gether_cleanup(netdev_priv(opts->net));
567 	else
568 		free_netdev(opts->net);
569 	kfree(opts);
570 }
571 
572 static struct usb_function_instance *eem_alloc_inst(void)
573 {
574 	struct f_eem_opts *opts;
575 
576 	opts = kzalloc(sizeof(*opts), GFP_KERNEL);
577 	if (!opts)
578 		return ERR_PTR(-ENOMEM);
579 	mutex_init(&opts->lock);
580 	opts->func_inst.free_func_inst = eem_free_inst;
581 	opts->net = gether_setup_default();
582 	if (IS_ERR(opts->net)) {
583 		struct net_device *net = opts->net;
584 		kfree(opts);
585 		return ERR_CAST(net);
586 	}
587 
588 	config_group_init_type_name(&opts->func_inst.group, "", &eem_func_type);
589 
590 	return &opts->func_inst;
591 }
592 
593 static void eem_free(struct usb_function *f)
594 {
595 	struct f_eem *eem;
596 	struct f_eem_opts *opts;
597 
598 	eem = func_to_eem(f);
599 	opts = container_of(f->fi, struct f_eem_opts, func_inst);
600 	kfree(eem);
601 	mutex_lock(&opts->lock);
602 	opts->refcnt--;
603 	mutex_unlock(&opts->lock);
604 }
605 
606 static void eem_unbind(struct usb_configuration *c, struct usb_function *f)
607 {
608 	DBG(c->cdev, "eem unbind\n");
609 
610 	usb_free_all_descriptors(f);
611 }
612 
613 static struct usb_function *eem_alloc(struct usb_function_instance *fi)
614 {
615 	struct f_eem	*eem;
616 	struct f_eem_opts *opts;
617 
618 	/* allocate and initialize one new instance */
619 	eem = kzalloc(sizeof(*eem), GFP_KERNEL);
620 	if (!eem)
621 		return ERR_PTR(-ENOMEM);
622 
623 	opts = container_of(fi, struct f_eem_opts, func_inst);
624 	mutex_lock(&opts->lock);
625 	opts->refcnt++;
626 
627 	eem->port.ioport = netdev_priv(opts->net);
628 	mutex_unlock(&opts->lock);
629 	eem->port.cdc_filter = DEFAULT_FILTER;
630 
631 	eem->port.func.name = "cdc_eem";
632 	/* descriptors are per-instance copies */
633 	eem->port.func.bind = eem_bind;
634 	eem->port.func.unbind = eem_unbind;
635 	eem->port.func.set_alt = eem_set_alt;
636 	eem->port.func.setup = eem_setup;
637 	eem->port.func.disable = eem_disable;
638 	eem->port.func.free_func = eem_free;
639 	eem->port.wrap = eem_wrap;
640 	eem->port.unwrap = eem_unwrap;
641 	eem->port.header_len = EEM_HLEN;
642 
643 	return &eem->port.func;
644 }
645 
646 DECLARE_USB_FUNCTION_INIT(eem, eem_alloc_inst, eem_alloc);
647 MODULE_LICENSE("GPL");
648 MODULE_AUTHOR("David Brownell");
649