1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3 * f_ncm.c -- USB CDC Network (NCM) link function driver
4 *
5 * Copyright (C) 2010 Nokia Corporation
6 * Contact: Yauheni Kaliuta <yauheni.kaliuta@nokia.com>
7 *
8 * The driver borrows from f_ecm.c which is:
9 *
10 * Copyright (C) 2003-2005,2008 David Brownell
11 * Copyright (C) 2008 Nokia Corporation
12 */
13
14 #include <linux/kernel.h>
15 #include <linux/interrupt.h>
16 #include <linux/module.h>
17 #include <linux/device.h>
18 #include <linux/etherdevice.h>
19 #include <linux/crc32.h>
20
21 #include <linux/usb/cdc.h>
22
23 #include "u_ether.h"
24 #include "u_ether_configfs.h"
25 #include "u_ncm.h"
26
27 /*
28 * This function is a "CDC Network Control Model" (CDC NCM) Ethernet link.
29 * NCM is intended to be used with high-speed network attachments.
30 *
31 * Note that NCM requires the use of "alternate settings" for its data
32 * interface. This means that the set_alt() method has real work to do,
33 * and also means that a get_alt() method is required.
34 */
35
36 /* to trigger crc/non-crc ndp signature */
37
38 #define NCM_NDP_HDR_CRC_MASK 0x01000000
39 #define NCM_NDP_HDR_CRC 0x01000000
40 #define NCM_NDP_HDR_NOCRC 0x00000000
41
42 enum ncm_notify_state {
43 NCM_NOTIFY_NONE, /* don't notify */
44 NCM_NOTIFY_CONNECT, /* issue CONNECT next */
45 NCM_NOTIFY_SPEED, /* issue SPEED_CHANGE next */
46 };
47
48 struct f_ncm {
49 struct gether port;
50 u8 ctrl_id, data_id;
51
52 char ethaddr[14];
53
54 struct usb_ep *notify;
55 struct usb_request *notify_req;
56 u8 notify_state;
57 atomic_t notify_count;
58 bool is_open;
59
60 const struct ndp_parser_opts *parser_opts;
61 bool is_crc;
62 u32 ndp_sign;
63
64 /*
65 * for notification, it is accessed from both
66 * callback and ethernet open/close
67 */
68 spinlock_t lock;
69
70 struct net_device *netdev;
71
72 /* For multi-frame NDP TX */
73 struct sk_buff *skb_tx_data;
74 struct sk_buff *skb_tx_ndp;
75 u16 ndp_dgram_count;
76 bool timer_force_tx;
77 struct hrtimer task_timer;
78 bool timer_stopping;
79 };
80
func_to_ncm(struct usb_function * f)81 static inline struct f_ncm *func_to_ncm(struct usb_function *f)
82 {
83 return container_of(f, struct f_ncm, port.func);
84 }
85
86 /* peak (theoretical) bulk transfer rate in bits-per-second */
ncm_bitrate(struct usb_gadget * g)87 static inline unsigned ncm_bitrate(struct usb_gadget *g)
88 {
89 if (gadget_is_superspeed(g) && g->speed >= USB_SPEED_SUPER_PLUS)
90 return 4250000000U;
91 else if (gadget_is_superspeed(g) && g->speed == USB_SPEED_SUPER)
92 return 3750000000U;
93 else if (gadget_is_dualspeed(g) && g->speed == USB_SPEED_HIGH)
94 return 13 * 512 * 8 * 1000 * 8;
95 else
96 return 19 * 64 * 1 * 1000 * 8;
97 }
98
99 /*-------------------------------------------------------------------------*/
100
101 /*
102 * We cannot group frames so use just the minimal size which ok to put
103 * one max-size ethernet frame.
104 * If the host can group frames, allow it to do that, 16K is selected,
105 * because it's used by default by the current linux host driver
106 */
107 #define NTB_DEFAULT_IN_SIZE 16384
108 #define NTB_OUT_SIZE 16384
109
110 /* Allocation for storing the NDP, 32 should suffice for a
111 * 16k packet. This allows a maximum of 32 * 507 Byte packets to
112 * be transmitted in a single 16kB skb, though when sending full size
113 * packets this limit will be plenty.
114 * Smaller packets are not likely to be trying to maximize the
115 * throughput and will be mstly sending smaller infrequent frames.
116 */
117 #define TX_MAX_NUM_DPE 32
118
119 /* Delay for the transmit to wait before sending an unfilled NTB frame. */
120 #define TX_TIMEOUT_NSECS 300000
121
122 #define FORMATS_SUPPORTED (USB_CDC_NCM_NTB16_SUPPORTED | \
123 USB_CDC_NCM_NTB32_SUPPORTED)
124
125 static struct usb_cdc_ncm_ntb_parameters ntb_parameters = {
126 .wLength = cpu_to_le16(sizeof(ntb_parameters)),
127 .bmNtbFormatsSupported = cpu_to_le16(FORMATS_SUPPORTED),
128 .dwNtbInMaxSize = cpu_to_le32(NTB_DEFAULT_IN_SIZE),
129 .wNdpInDivisor = cpu_to_le16(4),
130 .wNdpInPayloadRemainder = cpu_to_le16(0),
131 .wNdpInAlignment = cpu_to_le16(4),
132
133 .dwNtbOutMaxSize = cpu_to_le32(NTB_OUT_SIZE),
134 .wNdpOutDivisor = cpu_to_le16(4),
135 .wNdpOutPayloadRemainder = cpu_to_le16(0),
136 .wNdpOutAlignment = cpu_to_le16(4),
137 };
138
139 /*
140 * Use wMaxPacketSize big enough to fit CDC_NOTIFY_SPEED_CHANGE in one
141 * packet, to simplify cancellation; and a big transfer interval, to
142 * waste less bandwidth.
143 */
144
145 #define NCM_STATUS_INTERVAL_MS 32
146 #define NCM_STATUS_BYTECOUNT 16 /* 8 byte header + data */
147
148 static struct usb_interface_assoc_descriptor ncm_iad_desc = {
149 .bLength = sizeof ncm_iad_desc,
150 .bDescriptorType = USB_DT_INTERFACE_ASSOCIATION,
151
152 /* .bFirstInterface = DYNAMIC, */
153 .bInterfaceCount = 2, /* control + data */
154 .bFunctionClass = USB_CLASS_COMM,
155 .bFunctionSubClass = USB_CDC_SUBCLASS_NCM,
156 .bFunctionProtocol = USB_CDC_PROTO_NONE,
157 /* .iFunction = DYNAMIC */
158 };
159
160 /* interface descriptor: */
161
162 static struct usb_interface_descriptor ncm_control_intf = {
163 .bLength = sizeof ncm_control_intf,
164 .bDescriptorType = USB_DT_INTERFACE,
165
166 /* .bInterfaceNumber = DYNAMIC */
167 .bNumEndpoints = 1,
168 .bInterfaceClass = USB_CLASS_COMM,
169 .bInterfaceSubClass = USB_CDC_SUBCLASS_NCM,
170 .bInterfaceProtocol = USB_CDC_PROTO_NONE,
171 /* .iInterface = DYNAMIC */
172 };
173
174 static struct usb_cdc_header_desc ncm_header_desc = {
175 .bLength = sizeof ncm_header_desc,
176 .bDescriptorType = USB_DT_CS_INTERFACE,
177 .bDescriptorSubType = USB_CDC_HEADER_TYPE,
178
179 .bcdCDC = cpu_to_le16(0x0110),
180 };
181
182 static struct usb_cdc_union_desc ncm_union_desc = {
183 .bLength = sizeof(ncm_union_desc),
184 .bDescriptorType = USB_DT_CS_INTERFACE,
185 .bDescriptorSubType = USB_CDC_UNION_TYPE,
186 /* .bMasterInterface0 = DYNAMIC */
187 /* .bSlaveInterface0 = DYNAMIC */
188 };
189
190 static struct usb_cdc_ether_desc ecm_desc = {
191 .bLength = sizeof ecm_desc,
192 .bDescriptorType = USB_DT_CS_INTERFACE,
193 .bDescriptorSubType = USB_CDC_ETHERNET_TYPE,
194
195 /* this descriptor actually adds value, surprise! */
196 /* .iMACAddress = DYNAMIC */
197 .bmEthernetStatistics = cpu_to_le32(0), /* no statistics */
198 .wMaxSegmentSize = cpu_to_le16(ETH_FRAME_LEN),
199 .wNumberMCFilters = cpu_to_le16(0),
200 .bNumberPowerFilters = 0,
201 };
202
203 #define NCAPS (USB_CDC_NCM_NCAP_ETH_FILTER | USB_CDC_NCM_NCAP_CRC_MODE)
204
205 static struct usb_cdc_ncm_desc ncm_desc = {
206 .bLength = sizeof ncm_desc,
207 .bDescriptorType = USB_DT_CS_INTERFACE,
208 .bDescriptorSubType = USB_CDC_NCM_TYPE,
209
210 .bcdNcmVersion = cpu_to_le16(0x0100),
211 /* can process SetEthernetPacketFilter */
212 .bmNetworkCapabilities = NCAPS,
213 };
214
215 /* the default data interface has no endpoints ... */
216
217 static struct usb_interface_descriptor ncm_data_nop_intf = {
218 .bLength = sizeof ncm_data_nop_intf,
219 .bDescriptorType = USB_DT_INTERFACE,
220
221 .bInterfaceNumber = 1,
222 .bAlternateSetting = 0,
223 .bNumEndpoints = 0,
224 .bInterfaceClass = USB_CLASS_CDC_DATA,
225 .bInterfaceSubClass = 0,
226 .bInterfaceProtocol = USB_CDC_NCM_PROTO_NTB,
227 /* .iInterface = DYNAMIC */
228 };
229
230 /* ... but the "real" data interface has two bulk endpoints */
231
232 static struct usb_interface_descriptor ncm_data_intf = {
233 .bLength = sizeof ncm_data_intf,
234 .bDescriptorType = USB_DT_INTERFACE,
235
236 .bInterfaceNumber = 1,
237 .bAlternateSetting = 1,
238 .bNumEndpoints = 2,
239 .bInterfaceClass = USB_CLASS_CDC_DATA,
240 .bInterfaceSubClass = 0,
241 .bInterfaceProtocol = USB_CDC_NCM_PROTO_NTB,
242 /* .iInterface = DYNAMIC */
243 };
244
245 /* full speed support: */
246
247 static struct usb_endpoint_descriptor fs_ncm_notify_desc = {
248 .bLength = USB_DT_ENDPOINT_SIZE,
249 .bDescriptorType = USB_DT_ENDPOINT,
250
251 .bEndpointAddress = USB_DIR_IN,
252 .bmAttributes = USB_ENDPOINT_XFER_INT,
253 .wMaxPacketSize = cpu_to_le16(NCM_STATUS_BYTECOUNT),
254 .bInterval = NCM_STATUS_INTERVAL_MS,
255 };
256
257 static struct usb_endpoint_descriptor fs_ncm_in_desc = {
258 .bLength = USB_DT_ENDPOINT_SIZE,
259 .bDescriptorType = USB_DT_ENDPOINT,
260
261 .bEndpointAddress = USB_DIR_IN,
262 .bmAttributes = USB_ENDPOINT_XFER_BULK,
263 };
264
265 static struct usb_endpoint_descriptor fs_ncm_out_desc = {
266 .bLength = USB_DT_ENDPOINT_SIZE,
267 .bDescriptorType = USB_DT_ENDPOINT,
268
269 .bEndpointAddress = USB_DIR_OUT,
270 .bmAttributes = USB_ENDPOINT_XFER_BULK,
271 };
272
273 static struct usb_descriptor_header *ncm_fs_function[] = {
274 (struct usb_descriptor_header *) &ncm_iad_desc,
275 /* CDC NCM control descriptors */
276 (struct usb_descriptor_header *) &ncm_control_intf,
277 (struct usb_descriptor_header *) &ncm_header_desc,
278 (struct usb_descriptor_header *) &ncm_union_desc,
279 (struct usb_descriptor_header *) &ecm_desc,
280 (struct usb_descriptor_header *) &ncm_desc,
281 (struct usb_descriptor_header *) &fs_ncm_notify_desc,
282 /* data interface, altsettings 0 and 1 */
283 (struct usb_descriptor_header *) &ncm_data_nop_intf,
284 (struct usb_descriptor_header *) &ncm_data_intf,
285 (struct usb_descriptor_header *) &fs_ncm_in_desc,
286 (struct usb_descriptor_header *) &fs_ncm_out_desc,
287 NULL,
288 };
289
290 /* high speed support: */
291
292 static struct usb_endpoint_descriptor hs_ncm_notify_desc = {
293 .bLength = USB_DT_ENDPOINT_SIZE,
294 .bDescriptorType = USB_DT_ENDPOINT,
295
296 .bEndpointAddress = USB_DIR_IN,
297 .bmAttributes = USB_ENDPOINT_XFER_INT,
298 .wMaxPacketSize = cpu_to_le16(NCM_STATUS_BYTECOUNT),
299 .bInterval = USB_MS_TO_HS_INTERVAL(NCM_STATUS_INTERVAL_MS),
300 };
301 static struct usb_endpoint_descriptor hs_ncm_in_desc = {
302 .bLength = USB_DT_ENDPOINT_SIZE,
303 .bDescriptorType = USB_DT_ENDPOINT,
304
305 .bEndpointAddress = USB_DIR_IN,
306 .bmAttributes = USB_ENDPOINT_XFER_BULK,
307 .wMaxPacketSize = cpu_to_le16(512),
308 };
309
310 static struct usb_endpoint_descriptor hs_ncm_out_desc = {
311 .bLength = USB_DT_ENDPOINT_SIZE,
312 .bDescriptorType = USB_DT_ENDPOINT,
313
314 .bEndpointAddress = USB_DIR_OUT,
315 .bmAttributes = USB_ENDPOINT_XFER_BULK,
316 .wMaxPacketSize = cpu_to_le16(512),
317 };
318
319 static struct usb_descriptor_header *ncm_hs_function[] = {
320 (struct usb_descriptor_header *) &ncm_iad_desc,
321 /* CDC NCM control descriptors */
322 (struct usb_descriptor_header *) &ncm_control_intf,
323 (struct usb_descriptor_header *) &ncm_header_desc,
324 (struct usb_descriptor_header *) &ncm_union_desc,
325 (struct usb_descriptor_header *) &ecm_desc,
326 (struct usb_descriptor_header *) &ncm_desc,
327 (struct usb_descriptor_header *) &hs_ncm_notify_desc,
328 /* data interface, altsettings 0 and 1 */
329 (struct usb_descriptor_header *) &ncm_data_nop_intf,
330 (struct usb_descriptor_header *) &ncm_data_intf,
331 (struct usb_descriptor_header *) &hs_ncm_in_desc,
332 (struct usb_descriptor_header *) &hs_ncm_out_desc,
333 NULL,
334 };
335
336
337 /* super speed support: */
338
339 static struct usb_endpoint_descriptor ss_ncm_notify_desc = {
340 .bLength = USB_DT_ENDPOINT_SIZE,
341 .bDescriptorType = USB_DT_ENDPOINT,
342
343 .bEndpointAddress = USB_DIR_IN,
344 .bmAttributes = USB_ENDPOINT_XFER_INT,
345 .wMaxPacketSize = cpu_to_le16(NCM_STATUS_BYTECOUNT),
346 .bInterval = USB_MS_TO_HS_INTERVAL(NCM_STATUS_INTERVAL_MS)
347 };
348
349 static struct usb_ss_ep_comp_descriptor ss_ncm_notify_comp_desc = {
350 .bLength = sizeof(ss_ncm_notify_comp_desc),
351 .bDescriptorType = USB_DT_SS_ENDPOINT_COMP,
352
353 /* the following 3 values can be tweaked if necessary */
354 /* .bMaxBurst = 0, */
355 /* .bmAttributes = 0, */
356 .wBytesPerInterval = cpu_to_le16(NCM_STATUS_BYTECOUNT),
357 };
358
359 static struct usb_endpoint_descriptor ss_ncm_in_desc = {
360 .bLength = USB_DT_ENDPOINT_SIZE,
361 .bDescriptorType = USB_DT_ENDPOINT,
362
363 .bEndpointAddress = USB_DIR_IN,
364 .bmAttributes = USB_ENDPOINT_XFER_BULK,
365 .wMaxPacketSize = cpu_to_le16(1024),
366 };
367
368 static struct usb_endpoint_descriptor ss_ncm_out_desc = {
369 .bLength = USB_DT_ENDPOINT_SIZE,
370 .bDescriptorType = USB_DT_ENDPOINT,
371
372 .bEndpointAddress = USB_DIR_OUT,
373 .bmAttributes = USB_ENDPOINT_XFER_BULK,
374 .wMaxPacketSize = cpu_to_le16(1024),
375 };
376
377 static struct usb_ss_ep_comp_descriptor ss_ncm_bulk_comp_desc = {
378 .bLength = sizeof(ss_ncm_bulk_comp_desc),
379 .bDescriptorType = USB_DT_SS_ENDPOINT_COMP,
380
381 /* the following 2 values can be tweaked if necessary */
382 /* .bMaxBurst = 0, */
383 /* .bmAttributes = 0, */
384 };
385
386 static struct usb_descriptor_header *ncm_ss_function[] = {
387 (struct usb_descriptor_header *) &ncm_iad_desc,
388 /* CDC NCM control descriptors */
389 (struct usb_descriptor_header *) &ncm_control_intf,
390 (struct usb_descriptor_header *) &ncm_header_desc,
391 (struct usb_descriptor_header *) &ncm_union_desc,
392 (struct usb_descriptor_header *) &ecm_desc,
393 (struct usb_descriptor_header *) &ncm_desc,
394 (struct usb_descriptor_header *) &ss_ncm_notify_desc,
395 (struct usb_descriptor_header *) &ss_ncm_notify_comp_desc,
396 /* data interface, altsettings 0 and 1 */
397 (struct usb_descriptor_header *) &ncm_data_nop_intf,
398 (struct usb_descriptor_header *) &ncm_data_intf,
399 (struct usb_descriptor_header *) &ss_ncm_in_desc,
400 (struct usb_descriptor_header *) &ss_ncm_bulk_comp_desc,
401 (struct usb_descriptor_header *) &ss_ncm_out_desc,
402 (struct usb_descriptor_header *) &ss_ncm_bulk_comp_desc,
403 NULL,
404 };
405
406 /* string descriptors: */
407
408 #define STRING_CTRL_IDX 0
409 #define STRING_MAC_IDX 1
410 #define STRING_DATA_IDX 2
411 #define STRING_IAD_IDX 3
412
413 static struct usb_string ncm_string_defs[] = {
414 [STRING_CTRL_IDX].s = "CDC Network Control Model (NCM)",
415 [STRING_MAC_IDX].s = "",
416 [STRING_DATA_IDX].s = "CDC Network Data",
417 [STRING_IAD_IDX].s = "CDC NCM",
418 { } /* end of list */
419 };
420
421 static struct usb_gadget_strings ncm_string_table = {
422 .language = 0x0409, /* en-us */
423 .strings = ncm_string_defs,
424 };
425
426 static struct usb_gadget_strings *ncm_strings[] = {
427 &ncm_string_table,
428 NULL,
429 };
430
431 /*
432 * Here are options for NCM Datagram Pointer table (NDP) parser.
433 * There are 2 different formats: NDP16 and NDP32 in the spec (ch. 3),
434 * in NDP16 offsets and sizes fields are 1 16bit word wide,
435 * in NDP32 -- 2 16bit words wide. Also signatures are different.
436 * To make the parser code the same, put the differences in the structure,
437 * and switch pointers to the structures when the format is changed.
438 */
439
440 struct ndp_parser_opts {
441 u32 nth_sign;
442 u32 ndp_sign;
443 unsigned nth_size;
444 unsigned ndp_size;
445 unsigned dpe_size;
446 unsigned ndplen_align;
447 /* sizes in u16 units */
448 unsigned dgram_item_len; /* index or length */
449 unsigned block_length;
450 unsigned ndp_index;
451 unsigned reserved1;
452 unsigned reserved2;
453 unsigned next_ndp_index;
454 };
455
456 #define INIT_NDP16_OPTS { \
457 .nth_sign = USB_CDC_NCM_NTH16_SIGN, \
458 .ndp_sign = USB_CDC_NCM_NDP16_NOCRC_SIGN, \
459 .nth_size = sizeof(struct usb_cdc_ncm_nth16), \
460 .ndp_size = sizeof(struct usb_cdc_ncm_ndp16), \
461 .dpe_size = sizeof(struct usb_cdc_ncm_dpe16), \
462 .ndplen_align = 4, \
463 .dgram_item_len = 1, \
464 .block_length = 1, \
465 .ndp_index = 1, \
466 .reserved1 = 0, \
467 .reserved2 = 0, \
468 .next_ndp_index = 1, \
469 }
470
471
472 #define INIT_NDP32_OPTS { \
473 .nth_sign = USB_CDC_NCM_NTH32_SIGN, \
474 .ndp_sign = USB_CDC_NCM_NDP32_NOCRC_SIGN, \
475 .nth_size = sizeof(struct usb_cdc_ncm_nth32), \
476 .ndp_size = sizeof(struct usb_cdc_ncm_ndp32), \
477 .dpe_size = sizeof(struct usb_cdc_ncm_dpe32), \
478 .ndplen_align = 8, \
479 .dgram_item_len = 2, \
480 .block_length = 2, \
481 .ndp_index = 2, \
482 .reserved1 = 1, \
483 .reserved2 = 2, \
484 .next_ndp_index = 2, \
485 }
486
487 static const struct ndp_parser_opts ndp16_opts = INIT_NDP16_OPTS;
488 static const struct ndp_parser_opts ndp32_opts = INIT_NDP32_OPTS;
489
put_ncm(__le16 ** p,unsigned size,unsigned val)490 static inline void put_ncm(__le16 **p, unsigned size, unsigned val)
491 {
492 switch (size) {
493 case 1:
494 put_unaligned_le16((u16)val, *p);
495 break;
496 case 2:
497 put_unaligned_le32((u32)val, *p);
498
499 break;
500 default:
501 BUG();
502 }
503
504 *p += size;
505 }
506
get_ncm(__le16 ** p,unsigned size)507 static inline unsigned get_ncm(__le16 **p, unsigned size)
508 {
509 unsigned tmp;
510
511 switch (size) {
512 case 1:
513 tmp = get_unaligned_le16(*p);
514 break;
515 case 2:
516 tmp = get_unaligned_le32(*p);
517 break;
518 default:
519 BUG();
520 }
521
522 *p += size;
523 return tmp;
524 }
525
526 /*-------------------------------------------------------------------------*/
527
ncm_reset_values(struct f_ncm * ncm)528 static inline void ncm_reset_values(struct f_ncm *ncm)
529 {
530 ncm->parser_opts = &ndp16_opts;
531 ncm->is_crc = false;
532 ncm->port.cdc_filter = DEFAULT_FILTER;
533
534 /* doesn't make sense for ncm, fixed size used */
535 ncm->port.header_len = 0;
536
537 ncm->port.fixed_out_len = le32_to_cpu(ntb_parameters.dwNtbOutMaxSize);
538 ncm->port.fixed_in_len = NTB_DEFAULT_IN_SIZE;
539 }
540
541 /*
542 * Context: ncm->lock held
543 */
ncm_do_notify(struct f_ncm * ncm)544 static void ncm_do_notify(struct f_ncm *ncm)
545 {
546 struct usb_request *req = ncm->notify_req;
547 struct usb_cdc_notification *event;
548 struct usb_composite_dev *cdev = ncm->port.func.config->cdev;
549 __le32 *data;
550 int status;
551
552 /* notification already in flight? */
553 if (atomic_read(&ncm->notify_count))
554 return;
555
556 event = req->buf;
557 switch (ncm->notify_state) {
558 case NCM_NOTIFY_NONE:
559 return;
560
561 case NCM_NOTIFY_CONNECT:
562 event->bNotificationType = USB_CDC_NOTIFY_NETWORK_CONNECTION;
563 if (ncm->is_open)
564 event->wValue = cpu_to_le16(1);
565 else
566 event->wValue = cpu_to_le16(0);
567 event->wLength = 0;
568 req->length = sizeof *event;
569
570 DBG(cdev, "notify connect %s\n",
571 ncm->is_open ? "true" : "false");
572 ncm->notify_state = NCM_NOTIFY_NONE;
573 break;
574
575 case NCM_NOTIFY_SPEED:
576 event->bNotificationType = USB_CDC_NOTIFY_SPEED_CHANGE;
577 event->wValue = cpu_to_le16(0);
578 event->wLength = cpu_to_le16(8);
579 req->length = NCM_STATUS_BYTECOUNT;
580
581 /* SPEED_CHANGE data is up/down speeds in bits/sec */
582 data = req->buf + sizeof *event;
583 data[0] = cpu_to_le32(ncm_bitrate(cdev->gadget));
584 data[1] = data[0];
585
586 DBG(cdev, "notify speed %d\n", ncm_bitrate(cdev->gadget));
587 ncm->notify_state = NCM_NOTIFY_CONNECT;
588 break;
589 }
590 event->bmRequestType = 0xA1;
591 event->wIndex = cpu_to_le16(ncm->ctrl_id);
592
593 atomic_inc(&ncm->notify_count);
594
595 /*
596 * In double buffering if there is a space in FIFO,
597 * completion callback can be called right after the call,
598 * so unlocking
599 */
600 spin_unlock(&ncm->lock);
601 status = usb_ep_queue(ncm->notify, req, GFP_ATOMIC);
602 spin_lock(&ncm->lock);
603 if (status < 0) {
604 atomic_dec(&ncm->notify_count);
605 DBG(cdev, "notify --> %d\n", status);
606 }
607 }
608
609 /*
610 * Context: ncm->lock held
611 */
ncm_notify(struct f_ncm * ncm)612 static void ncm_notify(struct f_ncm *ncm)
613 {
614 /*
615 * NOTE on most versions of Linux, host side cdc-ethernet
616 * won't listen for notifications until its netdevice opens.
617 * The first notification then sits in the FIFO for a long
618 * time, and the second one is queued.
619 *
620 * If ncm_notify() is called before the second (CONNECT)
621 * notification is sent, then it will reset to send the SPEED
622 * notificaion again (and again, and again), but it's not a problem
623 */
624 ncm->notify_state = NCM_NOTIFY_SPEED;
625 ncm_do_notify(ncm);
626 }
627
ncm_notify_complete(struct usb_ep * ep,struct usb_request * req)628 static void ncm_notify_complete(struct usb_ep *ep, struct usb_request *req)
629 {
630 struct f_ncm *ncm = req->context;
631 struct usb_composite_dev *cdev = ncm->port.func.config->cdev;
632 struct usb_cdc_notification *event = req->buf;
633
634 spin_lock(&ncm->lock);
635 switch (req->status) {
636 case 0:
637 VDBG(cdev, "Notification %02x sent\n",
638 event->bNotificationType);
639 atomic_dec(&ncm->notify_count);
640 break;
641 case -ECONNRESET:
642 case -ESHUTDOWN:
643 atomic_set(&ncm->notify_count, 0);
644 ncm->notify_state = NCM_NOTIFY_NONE;
645 break;
646 default:
647 DBG(cdev, "event %02x --> %d\n",
648 event->bNotificationType, req->status);
649 atomic_dec(&ncm->notify_count);
650 break;
651 }
652 ncm_do_notify(ncm);
653 spin_unlock(&ncm->lock);
654 }
655
ncm_ep0out_complete(struct usb_ep * ep,struct usb_request * req)656 static void ncm_ep0out_complete(struct usb_ep *ep, struct usb_request *req)
657 {
658 /* now for SET_NTB_INPUT_SIZE only */
659 unsigned in_size;
660 struct usb_function *f = req->context;
661 struct f_ncm *ncm = func_to_ncm(f);
662 struct usb_composite_dev *cdev = f->config->cdev;
663
664 req->context = NULL;
665 if (req->status || req->actual != req->length) {
666 DBG(cdev, "Bad control-OUT transfer\n");
667 goto invalid;
668 }
669
670 in_size = get_unaligned_le32(req->buf);
671 if (in_size < USB_CDC_NCM_NTB_MIN_IN_SIZE ||
672 in_size > le32_to_cpu(ntb_parameters.dwNtbInMaxSize)) {
673 DBG(cdev, "Got wrong INPUT SIZE (%d) from host\n", in_size);
674 goto invalid;
675 }
676
677 ncm->port.fixed_in_len = in_size;
678 VDBG(cdev, "Set NTB INPUT SIZE %d\n", in_size);
679 return;
680
681 invalid:
682 usb_ep_set_halt(ep);
683 return;
684 }
685
ncm_setup(struct usb_function * f,const struct usb_ctrlrequest * ctrl)686 static int ncm_setup(struct usb_function *f, const struct usb_ctrlrequest *ctrl)
687 {
688 struct f_ncm *ncm = func_to_ncm(f);
689 struct usb_composite_dev *cdev = f->config->cdev;
690 struct usb_request *req = cdev->req;
691 int value = -EOPNOTSUPP;
692 u16 w_index = le16_to_cpu(ctrl->wIndex);
693 u16 w_value = le16_to_cpu(ctrl->wValue);
694 u16 w_length = le16_to_cpu(ctrl->wLength);
695
696 /*
697 * composite driver infrastructure handles everything except
698 * CDC class messages; interface activation uses set_alt().
699 */
700 switch ((ctrl->bRequestType << 8) | ctrl->bRequest) {
701 case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
702 | USB_CDC_SET_ETHERNET_PACKET_FILTER:
703 /*
704 * see 6.2.30: no data, wIndex = interface,
705 * wValue = packet filter bitmap
706 */
707 if (w_length != 0 || w_index != ncm->ctrl_id)
708 goto invalid;
709 DBG(cdev, "packet filter %02x\n", w_value);
710 /*
711 * REVISIT locking of cdc_filter. This assumes the UDC
712 * driver won't have a concurrent packet TX irq running on
713 * another CPU; or that if it does, this write is atomic...
714 */
715 ncm->port.cdc_filter = w_value;
716 value = 0;
717 break;
718 /*
719 * and optionally:
720 * case USB_CDC_SEND_ENCAPSULATED_COMMAND:
721 * case USB_CDC_GET_ENCAPSULATED_RESPONSE:
722 * case USB_CDC_SET_ETHERNET_MULTICAST_FILTERS:
723 * case USB_CDC_SET_ETHERNET_PM_PATTERN_FILTER:
724 * case USB_CDC_GET_ETHERNET_PM_PATTERN_FILTER:
725 * case USB_CDC_GET_ETHERNET_STATISTIC:
726 */
727
728 case ((USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
729 | USB_CDC_GET_NTB_PARAMETERS:
730
731 if (w_length == 0 || w_value != 0 || w_index != ncm->ctrl_id)
732 goto invalid;
733 value = w_length > sizeof ntb_parameters ?
734 sizeof ntb_parameters : w_length;
735 memcpy(req->buf, &ntb_parameters, value);
736 VDBG(cdev, "Host asked NTB parameters\n");
737 break;
738
739 case ((USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
740 | USB_CDC_GET_NTB_INPUT_SIZE:
741
742 if (w_length < 4 || w_value != 0 || w_index != ncm->ctrl_id)
743 goto invalid;
744 put_unaligned_le32(ncm->port.fixed_in_len, req->buf);
745 value = 4;
746 VDBG(cdev, "Host asked INPUT SIZE, sending %d\n",
747 ncm->port.fixed_in_len);
748 break;
749
750 case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
751 | USB_CDC_SET_NTB_INPUT_SIZE:
752 {
753 if (w_length != 4 || w_value != 0 || w_index != ncm->ctrl_id)
754 goto invalid;
755 req->complete = ncm_ep0out_complete;
756 req->length = w_length;
757 req->context = f;
758
759 value = req->length;
760 break;
761 }
762
763 case ((USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
764 | USB_CDC_GET_NTB_FORMAT:
765 {
766 uint16_t format;
767
768 if (w_length < 2 || w_value != 0 || w_index != ncm->ctrl_id)
769 goto invalid;
770 format = (ncm->parser_opts == &ndp16_opts) ? 0x0000 : 0x0001;
771 put_unaligned_le16(format, req->buf);
772 value = 2;
773 VDBG(cdev, "Host asked NTB FORMAT, sending %d\n", format);
774 break;
775 }
776
777 case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
778 | USB_CDC_SET_NTB_FORMAT:
779 {
780 if (w_length != 0 || w_index != ncm->ctrl_id)
781 goto invalid;
782 switch (w_value) {
783 case 0x0000:
784 ncm->parser_opts = &ndp16_opts;
785 DBG(cdev, "NCM16 selected\n");
786 break;
787 case 0x0001:
788 ncm->parser_opts = &ndp32_opts;
789 DBG(cdev, "NCM32 selected\n");
790 break;
791 default:
792 goto invalid;
793 }
794 value = 0;
795 break;
796 }
797 case ((USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
798 | USB_CDC_GET_CRC_MODE:
799 {
800 uint16_t is_crc;
801
802 if (w_length < 2 || w_value != 0 || w_index != ncm->ctrl_id)
803 goto invalid;
804 is_crc = ncm->is_crc ? 0x0001 : 0x0000;
805 put_unaligned_le16(is_crc, req->buf);
806 value = 2;
807 VDBG(cdev, "Host asked CRC MODE, sending %d\n", is_crc);
808 break;
809 }
810
811 case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
812 | USB_CDC_SET_CRC_MODE:
813 {
814 int ndp_hdr_crc = 0;
815
816 if (w_length != 0 || w_index != ncm->ctrl_id)
817 goto invalid;
818 switch (w_value) {
819 case 0x0000:
820 ncm->is_crc = false;
821 ndp_hdr_crc = NCM_NDP_HDR_NOCRC;
822 DBG(cdev, "non-CRC mode selected\n");
823 break;
824 case 0x0001:
825 ncm->is_crc = true;
826 ndp_hdr_crc = NCM_NDP_HDR_CRC;
827 DBG(cdev, "CRC mode selected\n");
828 break;
829 default:
830 goto invalid;
831 }
832 ncm->ndp_sign = ncm->parser_opts->ndp_sign | ndp_hdr_crc;
833 value = 0;
834 break;
835 }
836
837 /* and disabled in ncm descriptor: */
838 /* case USB_CDC_GET_NET_ADDRESS: */
839 /* case USB_CDC_SET_NET_ADDRESS: */
840 /* case USB_CDC_GET_MAX_DATAGRAM_SIZE: */
841 /* case USB_CDC_SET_MAX_DATAGRAM_SIZE: */
842
843 default:
844 invalid:
845 DBG(cdev, "invalid control req%02x.%02x v%04x i%04x l%d\n",
846 ctrl->bRequestType, ctrl->bRequest,
847 w_value, w_index, w_length);
848 }
849
850 /* respond with data transfer or status phase? */
851 if (value >= 0) {
852 DBG(cdev, "ncm req%02x.%02x v%04x i%04x l%d\n",
853 ctrl->bRequestType, ctrl->bRequest,
854 w_value, w_index, w_length);
855 req->zero = 0;
856 req->length = value;
857 value = usb_ep_queue(cdev->gadget->ep0, req, GFP_ATOMIC);
858 if (value < 0)
859 ERROR(cdev, "ncm req %02x.%02x response err %d\n",
860 ctrl->bRequestType, ctrl->bRequest,
861 value);
862 }
863
864 /* device either stalls (value < 0) or reports success */
865 return value;
866 }
867
868
ncm_set_alt(struct usb_function * f,unsigned intf,unsigned alt)869 static int ncm_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
870 {
871 struct f_ncm *ncm = func_to_ncm(f);
872 struct usb_composite_dev *cdev = f->config->cdev;
873
874 /* Control interface has only altsetting 0 */
875 if (intf == ncm->ctrl_id) {
876 if (alt != 0)
877 goto fail;
878
879 DBG(cdev, "reset ncm control %d\n", intf);
880 usb_ep_disable(ncm->notify);
881
882 if (!(ncm->notify->desc)) {
883 DBG(cdev, "init ncm ctrl %d\n", intf);
884 if (config_ep_by_speed(cdev->gadget, f, ncm->notify))
885 goto fail;
886 }
887 usb_ep_enable(ncm->notify);
888
889 /* Data interface has two altsettings, 0 and 1 */
890 } else if (intf == ncm->data_id) {
891 if (alt > 1)
892 goto fail;
893
894 if (ncm->port.in_ep->enabled) {
895 DBG(cdev, "reset ncm\n");
896 ncm->timer_stopping = true;
897 ncm->netdev = NULL;
898 gether_disconnect(&ncm->port);
899 ncm_reset_values(ncm);
900 }
901
902 /*
903 * CDC Network only sends data in non-default altsettings.
904 * Changing altsettings resets filters, statistics, etc.
905 */
906 if (alt == 1) {
907 struct net_device *net;
908
909 if (!ncm->port.in_ep->desc ||
910 !ncm->port.out_ep->desc) {
911 DBG(cdev, "init ncm\n");
912 if (config_ep_by_speed(cdev->gadget, f,
913 ncm->port.in_ep) ||
914 config_ep_by_speed(cdev->gadget, f,
915 ncm->port.out_ep)) {
916 ncm->port.in_ep->desc = NULL;
917 ncm->port.out_ep->desc = NULL;
918 goto fail;
919 }
920 }
921
922 /* TODO */
923 /* Enable zlps by default for NCM conformance;
924 * override for musb_hdrc (avoids txdma ovhead)
925 */
926 ncm->port.is_zlp_ok =
927 gadget_is_zlp_supported(cdev->gadget);
928 ncm->port.cdc_filter = DEFAULT_FILTER;
929 DBG(cdev, "activate ncm\n");
930 net = gether_connect(&ncm->port);
931 if (IS_ERR(net))
932 return PTR_ERR(net);
933 ncm->netdev = net;
934 ncm->timer_stopping = false;
935 }
936
937 spin_lock(&ncm->lock);
938 ncm_notify(ncm);
939 spin_unlock(&ncm->lock);
940 } else
941 goto fail;
942
943 return 0;
944 fail:
945 return -EINVAL;
946 }
947
948 /*
949 * Because the data interface supports multiple altsettings,
950 * this NCM function *MUST* implement a get_alt() method.
951 */
ncm_get_alt(struct usb_function * f,unsigned intf)952 static int ncm_get_alt(struct usb_function *f, unsigned intf)
953 {
954 struct f_ncm *ncm = func_to_ncm(f);
955
956 if (intf == ncm->ctrl_id)
957 return 0;
958 return ncm->port.in_ep->enabled ? 1 : 0;
959 }
960
package_for_tx(struct f_ncm * ncm)961 static struct sk_buff *package_for_tx(struct f_ncm *ncm)
962 {
963 __le16 *ntb_iter;
964 struct sk_buff *skb2 = NULL;
965 unsigned ndp_pad;
966 unsigned ndp_index;
967 unsigned new_len;
968
969 const struct ndp_parser_opts *opts = ncm->parser_opts;
970 const int ndp_align = le16_to_cpu(ntb_parameters.wNdpInAlignment);
971 const int dgram_idx_len = 2 * 2 * opts->dgram_item_len;
972
973 /* Stop the timer */
974 hrtimer_try_to_cancel(&ncm->task_timer);
975
976 ndp_pad = ALIGN(ncm->skb_tx_data->len, ndp_align) -
977 ncm->skb_tx_data->len;
978 ndp_index = ncm->skb_tx_data->len + ndp_pad;
979 new_len = ndp_index + dgram_idx_len + ncm->skb_tx_ndp->len;
980
981 /* Set the final BlockLength and wNdpIndex */
982 ntb_iter = (void *) ncm->skb_tx_data->data;
983 /* Increment pointer to BlockLength */
984 ntb_iter += 2 + 1 + 1;
985 put_ncm(&ntb_iter, opts->block_length, new_len);
986 put_ncm(&ntb_iter, opts->ndp_index, ndp_index);
987
988 /* Set the final NDP wLength */
989 new_len = opts->ndp_size +
990 (ncm->ndp_dgram_count * dgram_idx_len);
991 ncm->ndp_dgram_count = 0;
992 /* Increment from start to wLength */
993 ntb_iter = (void *) ncm->skb_tx_ndp->data;
994 ntb_iter += 2;
995 put_unaligned_le16(new_len, ntb_iter);
996
997 /* Merge the skbs */
998 swap(skb2, ncm->skb_tx_data);
999 if (ncm->skb_tx_data) {
1000 dev_consume_skb_any(ncm->skb_tx_data);
1001 ncm->skb_tx_data = NULL;
1002 }
1003
1004 /* Insert NDP alignment. */
1005 skb_put_zero(skb2, ndp_pad);
1006
1007 /* Copy NTB across. */
1008 skb_put_data(skb2, ncm->skb_tx_ndp->data, ncm->skb_tx_ndp->len);
1009 dev_consume_skb_any(ncm->skb_tx_ndp);
1010 ncm->skb_tx_ndp = NULL;
1011
1012 /* Insert zero'd datagram. */
1013 skb_put_zero(skb2, dgram_idx_len);
1014
1015 return skb2;
1016 }
1017
ncm_wrap_ntb(struct gether * port,struct sk_buff * skb)1018 static struct sk_buff *ncm_wrap_ntb(struct gether *port,
1019 struct sk_buff *skb)
1020 {
1021 struct f_ncm *ncm = func_to_ncm(&port->func);
1022 struct sk_buff *skb2 = NULL;
1023 int ncb_len = 0;
1024 __le16 *ntb_data;
1025 __le16 *ntb_ndp;
1026 int dgram_pad;
1027
1028 unsigned max_size = ncm->port.fixed_in_len;
1029 const struct ndp_parser_opts *opts = ncm->parser_opts;
1030 const int ndp_align = le16_to_cpu(ntb_parameters.wNdpInAlignment);
1031 const int div = le16_to_cpu(ntb_parameters.wNdpInDivisor);
1032 const int rem = le16_to_cpu(ntb_parameters.wNdpInPayloadRemainder);
1033 const int dgram_idx_len = 2 * 2 * opts->dgram_item_len;
1034
1035 if (!skb && !ncm->skb_tx_data)
1036 return NULL;
1037
1038 if (skb) {
1039 /* Add the CRC if required up front */
1040 if (ncm->is_crc) {
1041 uint32_t crc;
1042 __le16 *crc_pos;
1043
1044 crc = ~crc32_le(~0,
1045 skb->data,
1046 skb->len);
1047 crc_pos = skb_put(skb, sizeof(uint32_t));
1048 put_unaligned_le32(crc, crc_pos);
1049 }
1050
1051 /* If the new skb is too big for the current NCM NTB then
1052 * set the current stored skb to be sent now and clear it
1053 * ready for new data.
1054 * NOTE: Assume maximum align for speed of calculation.
1055 */
1056 if (ncm->skb_tx_data
1057 && (ncm->ndp_dgram_count >= TX_MAX_NUM_DPE
1058 || (ncm->skb_tx_data->len +
1059 div + rem + skb->len +
1060 ncm->skb_tx_ndp->len + ndp_align + (2 * dgram_idx_len))
1061 > max_size)) {
1062 skb2 = package_for_tx(ncm);
1063 if (!skb2)
1064 goto err;
1065 }
1066
1067 if (!ncm->skb_tx_data) {
1068 ncb_len = opts->nth_size;
1069 dgram_pad = ALIGN(ncb_len, div) + rem - ncb_len;
1070 ncb_len += dgram_pad;
1071
1072 /* Create a new skb for the NTH and datagrams. */
1073 ncm->skb_tx_data = alloc_skb(max_size, GFP_ATOMIC);
1074 if (!ncm->skb_tx_data)
1075 goto err;
1076
1077 ncm->skb_tx_data->dev = ncm->netdev;
1078 ntb_data = skb_put_zero(ncm->skb_tx_data, ncb_len);
1079 /* dwSignature */
1080 put_unaligned_le32(opts->nth_sign, ntb_data);
1081 ntb_data += 2;
1082 /* wHeaderLength */
1083 put_unaligned_le16(opts->nth_size, ntb_data++);
1084
1085 /* Allocate an skb for storing the NDP,
1086 * TX_MAX_NUM_DPE should easily suffice for a
1087 * 16k packet.
1088 */
1089 ncm->skb_tx_ndp = alloc_skb((int)(opts->ndp_size
1090 + opts->dpe_size
1091 * TX_MAX_NUM_DPE),
1092 GFP_ATOMIC);
1093 if (!ncm->skb_tx_ndp)
1094 goto err;
1095
1096 ncm->skb_tx_ndp->dev = ncm->netdev;
1097 ntb_ndp = skb_put(ncm->skb_tx_ndp, opts->ndp_size);
1098 memset(ntb_ndp, 0, ncb_len);
1099 /* dwSignature */
1100 put_unaligned_le32(ncm->ndp_sign, ntb_ndp);
1101 ntb_ndp += 2;
1102
1103 /* There is always a zeroed entry */
1104 ncm->ndp_dgram_count = 1;
1105
1106 /* Note: we skip opts->next_ndp_index */
1107 }
1108
1109 /* Delay the timer. */
1110 hrtimer_start(&ncm->task_timer, TX_TIMEOUT_NSECS,
1111 HRTIMER_MODE_REL_SOFT);
1112
1113 /* Add the datagram position entries */
1114 ntb_ndp = skb_put_zero(ncm->skb_tx_ndp, dgram_idx_len);
1115
1116 ncb_len = ncm->skb_tx_data->len;
1117 dgram_pad = ALIGN(ncb_len, div) + rem - ncb_len;
1118 ncb_len += dgram_pad;
1119
1120 /* (d)wDatagramIndex */
1121 put_ncm(&ntb_ndp, opts->dgram_item_len, ncb_len);
1122 /* (d)wDatagramLength */
1123 put_ncm(&ntb_ndp, opts->dgram_item_len, skb->len);
1124 ncm->ndp_dgram_count++;
1125
1126 /* Add the new data to the skb */
1127 skb_put_zero(ncm->skb_tx_data, dgram_pad);
1128 skb_put_data(ncm->skb_tx_data, skb->data, skb->len);
1129 dev_consume_skb_any(skb);
1130 skb = NULL;
1131
1132 } else if (ncm->skb_tx_data && ncm->timer_force_tx) {
1133 /* If the tx was requested because of a timeout then send */
1134 skb2 = package_for_tx(ncm);
1135 if (!skb2)
1136 goto err;
1137 }
1138
1139 return skb2;
1140
1141 err:
1142 ncm->netdev->stats.tx_dropped++;
1143
1144 if (skb)
1145 dev_kfree_skb_any(skb);
1146 if (ncm->skb_tx_data)
1147 dev_kfree_skb_any(ncm->skb_tx_data);
1148 if (ncm->skb_tx_ndp)
1149 dev_kfree_skb_any(ncm->skb_tx_ndp);
1150
1151 return NULL;
1152 }
1153
1154 /*
1155 * The transmit should only be run if no skb data has been sent
1156 * for a certain duration.
1157 */
ncm_tx_timeout(struct hrtimer * data)1158 static enum hrtimer_restart ncm_tx_timeout(struct hrtimer *data)
1159 {
1160 struct f_ncm *ncm = container_of(data, struct f_ncm, task_timer);
1161
1162 /* Only send if data is available. */
1163 if (!ncm->timer_stopping && ncm->skb_tx_data) {
1164 ncm->timer_force_tx = true;
1165
1166 /* XXX This allowance of a NULL skb argument to ndo_start_xmit
1167 * XXX is not sane. The gadget layer should be redesigned so
1168 * XXX that the dev->wrap() invocations to build SKBs is transparent
1169 * XXX and performed in some way outside of the ndo_start_xmit
1170 * XXX interface.
1171 */
1172 ncm->netdev->netdev_ops->ndo_start_xmit(NULL, ncm->netdev);
1173
1174 ncm->timer_force_tx = false;
1175 }
1176 return HRTIMER_NORESTART;
1177 }
1178
ncm_unwrap_ntb(struct gether * port,struct sk_buff * skb,struct sk_buff_head * list)1179 static int ncm_unwrap_ntb(struct gether *port,
1180 struct sk_buff *skb,
1181 struct sk_buff_head *list)
1182 {
1183 struct f_ncm *ncm = func_to_ncm(&port->func);
1184 __le16 *tmp = (void *) skb->data;
1185 unsigned index, index2;
1186 int ndp_index;
1187 unsigned dg_len, dg_len2;
1188 unsigned ndp_len;
1189 unsigned block_len;
1190 struct sk_buff *skb2;
1191 int ret = -EINVAL;
1192 unsigned ntb_max = le32_to_cpu(ntb_parameters.dwNtbOutMaxSize);
1193 unsigned frame_max = le16_to_cpu(ecm_desc.wMaxSegmentSize);
1194 const struct ndp_parser_opts *opts = ncm->parser_opts;
1195 unsigned crc_len = ncm->is_crc ? sizeof(uint32_t) : 0;
1196 int dgram_counter;
1197
1198 /* dwSignature */
1199 if (get_unaligned_le32(tmp) != opts->nth_sign) {
1200 INFO(port->func.config->cdev, "Wrong NTH SIGN, skblen %d\n",
1201 skb->len);
1202 print_hex_dump(KERN_INFO, "HEAD:", DUMP_PREFIX_ADDRESS, 32, 1,
1203 skb->data, 32, false);
1204
1205 goto err;
1206 }
1207 tmp += 2;
1208 /* wHeaderLength */
1209 if (get_unaligned_le16(tmp++) != opts->nth_size) {
1210 INFO(port->func.config->cdev, "Wrong NTB headersize\n");
1211 goto err;
1212 }
1213 tmp++; /* skip wSequence */
1214
1215 block_len = get_ncm(&tmp, opts->block_length);
1216 /* (d)wBlockLength */
1217 if (block_len > ntb_max) {
1218 INFO(port->func.config->cdev, "OUT size exceeded\n");
1219 goto err;
1220 }
1221
1222 ndp_index = get_ncm(&tmp, opts->ndp_index);
1223
1224 /* Run through all the NDP's in the NTB */
1225 do {
1226 /*
1227 * NCM 3.2
1228 * dwNdpIndex
1229 */
1230 if (((ndp_index % 4) != 0) ||
1231 (ndp_index < opts->nth_size) ||
1232 (ndp_index > (block_len -
1233 opts->ndp_size))) {
1234 INFO(port->func.config->cdev, "Bad index: %#X\n",
1235 ndp_index);
1236 goto err;
1237 }
1238
1239 /*
1240 * walk through NDP
1241 * dwSignature
1242 */
1243 tmp = (void *)(skb->data + ndp_index);
1244 if (get_unaligned_le32(tmp) != ncm->ndp_sign) {
1245 INFO(port->func.config->cdev, "Wrong NDP SIGN\n");
1246 goto err;
1247 }
1248 tmp += 2;
1249
1250 ndp_len = get_unaligned_le16(tmp++);
1251 /*
1252 * NCM 3.3.1
1253 * wLength
1254 * entry is 2 items
1255 * item size is 16/32 bits, opts->dgram_item_len * 2 bytes
1256 * minimal: struct usb_cdc_ncm_ndpX + normal entry + zero entry
1257 * Each entry is a dgram index and a dgram length.
1258 */
1259 if ((ndp_len < opts->ndp_size
1260 + 2 * 2 * (opts->dgram_item_len * 2)) ||
1261 (ndp_len % opts->ndplen_align != 0)) {
1262 INFO(port->func.config->cdev, "Bad NDP length: %#X\n",
1263 ndp_len);
1264 goto err;
1265 }
1266 tmp += opts->reserved1;
1267 /* Check for another NDP (d)wNextNdpIndex */
1268 ndp_index = get_ncm(&tmp, opts->next_ndp_index);
1269 tmp += opts->reserved2;
1270
1271 ndp_len -= opts->ndp_size;
1272 index2 = get_ncm(&tmp, opts->dgram_item_len);
1273 dg_len2 = get_ncm(&tmp, opts->dgram_item_len);
1274 dgram_counter = 0;
1275
1276 do {
1277 index = index2;
1278 /* wDatagramIndex[0] */
1279 if ((index < opts->nth_size) ||
1280 (index > block_len - opts->dpe_size)) {
1281 INFO(port->func.config->cdev,
1282 "Bad index: %#X\n", index);
1283 goto err;
1284 }
1285
1286 dg_len = dg_len2;
1287 /*
1288 * wDatagramLength[0]
1289 * ethernet hdr + crc or larger than max frame size
1290 */
1291 if ((dg_len < 14 + crc_len) ||
1292 (dg_len > frame_max)) {
1293 INFO(port->func.config->cdev,
1294 "Bad dgram length: %#X\n", dg_len);
1295 goto err;
1296 }
1297 if (ncm->is_crc) {
1298 uint32_t crc, crc2;
1299
1300 crc = get_unaligned_le32(skb->data +
1301 index + dg_len -
1302 crc_len);
1303 crc2 = ~crc32_le(~0,
1304 skb->data + index,
1305 dg_len - crc_len);
1306 if (crc != crc2) {
1307 INFO(port->func.config->cdev,
1308 "Bad CRC\n");
1309 goto err;
1310 }
1311 }
1312
1313 index2 = get_ncm(&tmp, opts->dgram_item_len);
1314 dg_len2 = get_ncm(&tmp, opts->dgram_item_len);
1315
1316 /* wDatagramIndex[1] */
1317 if (index2 > block_len - opts->dpe_size) {
1318 INFO(port->func.config->cdev,
1319 "Bad index: %#X\n", index2);
1320 goto err;
1321 }
1322
1323 /*
1324 * Copy the data into a new skb.
1325 * This ensures the truesize is correct
1326 */
1327 skb2 = netdev_alloc_skb_ip_align(ncm->netdev,
1328 dg_len - crc_len);
1329 if (skb2 == NULL)
1330 goto err;
1331 skb_put_data(skb2, skb->data + index,
1332 dg_len - crc_len);
1333
1334 skb_queue_tail(list, skb2);
1335
1336 ndp_len -= 2 * (opts->dgram_item_len * 2);
1337
1338 dgram_counter++;
1339 if (index2 == 0 || dg_len2 == 0)
1340 break;
1341 } while (ndp_len > 2 * (opts->dgram_item_len * 2));
1342 } while (ndp_index);
1343
1344 dev_consume_skb_any(skb);
1345
1346 VDBG(port->func.config->cdev,
1347 "Parsed NTB with %d frames\n", dgram_counter);
1348 return 0;
1349 err:
1350 skb_queue_purge(list);
1351 dev_kfree_skb_any(skb);
1352 return ret;
1353 }
1354
ncm_disable(struct usb_function * f)1355 static void ncm_disable(struct usb_function *f)
1356 {
1357 struct f_ncm *ncm = func_to_ncm(f);
1358 struct usb_composite_dev *cdev = f->config->cdev;
1359
1360 DBG(cdev, "ncm deactivated\n");
1361
1362 if (ncm->port.in_ep->enabled) {
1363 ncm->timer_stopping = true;
1364 ncm->netdev = NULL;
1365 gether_disconnect(&ncm->port);
1366 }
1367
1368 if (ncm->notify->enabled) {
1369 usb_ep_disable(ncm->notify);
1370 ncm->notify->desc = NULL;
1371 }
1372 }
1373
1374 /*-------------------------------------------------------------------------*/
1375
1376 /*
1377 * Callbacks let us notify the host about connect/disconnect when the
1378 * net device is opened or closed.
1379 *
1380 * For testing, note that link states on this side include both opened
1381 * and closed variants of:
1382 *
1383 * - disconnected/unconfigured
1384 * - configured but inactive (data alt 0)
1385 * - configured and active (data alt 1)
1386 *
1387 * Each needs to be tested with unplug, rmmod, SET_CONFIGURATION, and
1388 * SET_INTERFACE (altsetting). Remember also that "configured" doesn't
1389 * imply the host is actually polling the notification endpoint, and
1390 * likewise that "active" doesn't imply it's actually using the data
1391 * endpoints for traffic.
1392 */
1393
ncm_open(struct gether * geth)1394 static void ncm_open(struct gether *geth)
1395 {
1396 struct f_ncm *ncm = func_to_ncm(&geth->func);
1397
1398 DBG(ncm->port.func.config->cdev, "%s\n", __func__);
1399
1400 spin_lock(&ncm->lock);
1401 ncm->is_open = true;
1402 ncm_notify(ncm);
1403 spin_unlock(&ncm->lock);
1404 }
1405
ncm_close(struct gether * geth)1406 static void ncm_close(struct gether *geth)
1407 {
1408 struct f_ncm *ncm = func_to_ncm(&geth->func);
1409
1410 DBG(ncm->port.func.config->cdev, "%s\n", __func__);
1411
1412 spin_lock(&ncm->lock);
1413 ncm->is_open = false;
1414 ncm_notify(ncm);
1415 spin_unlock(&ncm->lock);
1416 }
1417
1418 /*-------------------------------------------------------------------------*/
1419
1420 /* ethernet function driver setup/binding */
1421
ncm_bind(struct usb_configuration * c,struct usb_function * f)1422 static int ncm_bind(struct usb_configuration *c, struct usb_function *f)
1423 {
1424 struct usb_composite_dev *cdev = c->cdev;
1425 struct f_ncm *ncm = func_to_ncm(f);
1426 struct usb_string *us;
1427 int status;
1428 struct usb_ep *ep;
1429 struct f_ncm_opts *ncm_opts;
1430
1431 if (!can_support_ecm(cdev->gadget))
1432 return -EINVAL;
1433
1434 ncm_opts = container_of(f->fi, struct f_ncm_opts, func_inst);
1435 /*
1436 * in drivers/usb/gadget/configfs.c:configfs_composite_bind()
1437 * configurations are bound in sequence with list_for_each_entry,
1438 * in each configuration its functions are bound in sequence
1439 * with list_for_each_entry, so we assume no race condition
1440 * with regard to ncm_opts->bound access
1441 */
1442 if (!ncm_opts->bound) {
1443 mutex_lock(&ncm_opts->lock);
1444 gether_set_gadget(ncm_opts->net, cdev->gadget);
1445 status = gether_register_netdev(ncm_opts->net);
1446 mutex_unlock(&ncm_opts->lock);
1447 if (status)
1448 return status;
1449 ncm_opts->bound = true;
1450 }
1451 us = usb_gstrings_attach(cdev, ncm_strings,
1452 ARRAY_SIZE(ncm_string_defs));
1453 if (IS_ERR(us))
1454 return PTR_ERR(us);
1455 ncm_control_intf.iInterface = us[STRING_CTRL_IDX].id;
1456 ncm_data_nop_intf.iInterface = us[STRING_DATA_IDX].id;
1457 ncm_data_intf.iInterface = us[STRING_DATA_IDX].id;
1458 ecm_desc.iMACAddress = us[STRING_MAC_IDX].id;
1459 ncm_iad_desc.iFunction = us[STRING_IAD_IDX].id;
1460
1461 /* allocate instance-specific interface IDs */
1462 status = usb_interface_id(c, f);
1463 if (status < 0)
1464 goto fail;
1465 ncm->ctrl_id = status;
1466 ncm_iad_desc.bFirstInterface = status;
1467
1468 ncm_control_intf.bInterfaceNumber = status;
1469 ncm_union_desc.bMasterInterface0 = status;
1470
1471 status = usb_interface_id(c, f);
1472 if (status < 0)
1473 goto fail;
1474 ncm->data_id = status;
1475
1476 ncm_data_nop_intf.bInterfaceNumber = status;
1477 ncm_data_intf.bInterfaceNumber = status;
1478 ncm_union_desc.bSlaveInterface0 = status;
1479
1480 status = -ENODEV;
1481
1482 /* allocate instance-specific endpoints */
1483 ep = usb_ep_autoconfig(cdev->gadget, &fs_ncm_in_desc);
1484 if (!ep)
1485 goto fail;
1486 ncm->port.in_ep = ep;
1487
1488 ep = usb_ep_autoconfig(cdev->gadget, &fs_ncm_out_desc);
1489 if (!ep)
1490 goto fail;
1491 ncm->port.out_ep = ep;
1492
1493 ep = usb_ep_autoconfig(cdev->gadget, &fs_ncm_notify_desc);
1494 if (!ep)
1495 goto fail;
1496 ncm->notify = ep;
1497
1498 status = -ENOMEM;
1499
1500 /* allocate notification request and buffer */
1501 ncm->notify_req = usb_ep_alloc_request(ep, GFP_KERNEL);
1502 if (!ncm->notify_req)
1503 goto fail;
1504 ncm->notify_req->buf = kmalloc(NCM_STATUS_BYTECOUNT, GFP_KERNEL);
1505 if (!ncm->notify_req->buf)
1506 goto fail;
1507 ncm->notify_req->context = ncm;
1508 ncm->notify_req->complete = ncm_notify_complete;
1509
1510 /*
1511 * support all relevant hardware speeds... we expect that when
1512 * hardware is dual speed, all bulk-capable endpoints work at
1513 * both speeds
1514 */
1515 hs_ncm_in_desc.bEndpointAddress = fs_ncm_in_desc.bEndpointAddress;
1516 hs_ncm_out_desc.bEndpointAddress = fs_ncm_out_desc.bEndpointAddress;
1517 hs_ncm_notify_desc.bEndpointAddress =
1518 fs_ncm_notify_desc.bEndpointAddress;
1519
1520 ss_ncm_in_desc.bEndpointAddress = fs_ncm_in_desc.bEndpointAddress;
1521 ss_ncm_out_desc.bEndpointAddress = fs_ncm_out_desc.bEndpointAddress;
1522 ss_ncm_notify_desc.bEndpointAddress =
1523 fs_ncm_notify_desc.bEndpointAddress;
1524
1525 status = usb_assign_descriptors(f, ncm_fs_function, ncm_hs_function,
1526 ncm_ss_function, ncm_ss_function);
1527 if (status)
1528 goto fail;
1529
1530 /*
1531 * NOTE: all that is done without knowing or caring about
1532 * the network link ... which is unavailable to this code
1533 * until we're activated via set_alt().
1534 */
1535
1536 ncm->port.open = ncm_open;
1537 ncm->port.close = ncm_close;
1538
1539 hrtimer_init(&ncm->task_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_SOFT);
1540 ncm->task_timer.function = ncm_tx_timeout;
1541
1542 DBG(cdev, "CDC Network: %s speed IN/%s OUT/%s NOTIFY/%s\n",
1543 gadget_is_superspeed(c->cdev->gadget) ? "super" :
1544 gadget_is_dualspeed(c->cdev->gadget) ? "dual" : "full",
1545 ncm->port.in_ep->name, ncm->port.out_ep->name,
1546 ncm->notify->name);
1547 return 0;
1548
1549 fail:
1550 if (ncm->notify_req) {
1551 kfree(ncm->notify_req->buf);
1552 usb_ep_free_request(ncm->notify, ncm->notify_req);
1553 }
1554
1555 ERROR(cdev, "%s: can't bind, err %d\n", f->name, status);
1556
1557 return status;
1558 }
1559
to_f_ncm_opts(struct config_item * item)1560 static inline struct f_ncm_opts *to_f_ncm_opts(struct config_item *item)
1561 {
1562 return container_of(to_config_group(item), struct f_ncm_opts,
1563 func_inst.group);
1564 }
1565
1566 /* f_ncm_item_ops */
1567 USB_ETHERNET_CONFIGFS_ITEM(ncm);
1568
1569 /* f_ncm_opts_dev_addr */
1570 USB_ETHERNET_CONFIGFS_ITEM_ATTR_DEV_ADDR(ncm);
1571
1572 /* f_ncm_opts_host_addr */
1573 USB_ETHERNET_CONFIGFS_ITEM_ATTR_HOST_ADDR(ncm);
1574
1575 /* f_ncm_opts_qmult */
1576 USB_ETHERNET_CONFIGFS_ITEM_ATTR_QMULT(ncm);
1577
1578 /* f_ncm_opts_ifname */
1579 USB_ETHERNET_CONFIGFS_ITEM_ATTR_IFNAME(ncm);
1580
1581 static struct configfs_attribute *ncm_attrs[] = {
1582 &ncm_opts_attr_dev_addr,
1583 &ncm_opts_attr_host_addr,
1584 &ncm_opts_attr_qmult,
1585 &ncm_opts_attr_ifname,
1586 NULL,
1587 };
1588
1589 static const struct config_item_type ncm_func_type = {
1590 .ct_item_ops = &ncm_item_ops,
1591 .ct_attrs = ncm_attrs,
1592 .ct_owner = THIS_MODULE,
1593 };
1594
ncm_free_inst(struct usb_function_instance * f)1595 static void ncm_free_inst(struct usb_function_instance *f)
1596 {
1597 struct f_ncm_opts *opts;
1598
1599 opts = container_of(f, struct f_ncm_opts, func_inst);
1600 if (opts->bound)
1601 gether_cleanup(netdev_priv(opts->net));
1602 else
1603 free_netdev(opts->net);
1604 kfree(opts);
1605 }
1606
ncm_alloc_inst(void)1607 static struct usb_function_instance *ncm_alloc_inst(void)
1608 {
1609 struct f_ncm_opts *opts;
1610
1611 opts = kzalloc(sizeof(*opts), GFP_KERNEL);
1612 if (!opts)
1613 return ERR_PTR(-ENOMEM);
1614 mutex_init(&opts->lock);
1615 opts->func_inst.free_func_inst = ncm_free_inst;
1616 opts->net = gether_setup_default();
1617 if (IS_ERR(opts->net)) {
1618 struct net_device *net = opts->net;
1619 kfree(opts);
1620 return ERR_CAST(net);
1621 }
1622
1623 config_group_init_type_name(&opts->func_inst.group, "", &ncm_func_type);
1624
1625 return &opts->func_inst;
1626 }
1627
ncm_free(struct usb_function * f)1628 static void ncm_free(struct usb_function *f)
1629 {
1630 struct f_ncm *ncm;
1631 struct f_ncm_opts *opts;
1632
1633 ncm = func_to_ncm(f);
1634 opts = container_of(f->fi, struct f_ncm_opts, func_inst);
1635 kfree(ncm);
1636 mutex_lock(&opts->lock);
1637 opts->refcnt--;
1638 mutex_unlock(&opts->lock);
1639 }
1640
ncm_unbind(struct usb_configuration * c,struct usb_function * f)1641 static void ncm_unbind(struct usb_configuration *c, struct usb_function *f)
1642 {
1643 struct f_ncm *ncm = func_to_ncm(f);
1644
1645 DBG(c->cdev, "ncm unbind\n");
1646
1647 hrtimer_cancel(&ncm->task_timer);
1648
1649 ncm_string_defs[0].id = 0;
1650 usb_free_all_descriptors(f);
1651
1652 if (atomic_read(&ncm->notify_count)) {
1653 usb_ep_dequeue(ncm->notify, ncm->notify_req);
1654 atomic_set(&ncm->notify_count, 0);
1655 }
1656
1657 kfree(ncm->notify_req->buf);
1658 usb_ep_free_request(ncm->notify, ncm->notify_req);
1659 }
1660
ncm_alloc(struct usb_function_instance * fi)1661 static struct usb_function *ncm_alloc(struct usb_function_instance *fi)
1662 {
1663 struct f_ncm *ncm;
1664 struct f_ncm_opts *opts;
1665 int status;
1666
1667 /* allocate and initialize one new instance */
1668 ncm = kzalloc(sizeof(*ncm), GFP_KERNEL);
1669 if (!ncm)
1670 return ERR_PTR(-ENOMEM);
1671
1672 opts = container_of(fi, struct f_ncm_opts, func_inst);
1673 mutex_lock(&opts->lock);
1674 opts->refcnt++;
1675
1676 /* export host's Ethernet address in CDC format */
1677 status = gether_get_host_addr_cdc(opts->net, ncm->ethaddr,
1678 sizeof(ncm->ethaddr));
1679 if (status < 12) { /* strlen("01234567890a") */
1680 kfree(ncm);
1681 mutex_unlock(&opts->lock);
1682 return ERR_PTR(-EINVAL);
1683 }
1684 ncm_string_defs[STRING_MAC_IDX].s = ncm->ethaddr;
1685
1686 spin_lock_init(&ncm->lock);
1687 ncm_reset_values(ncm);
1688 ncm->port.ioport = netdev_priv(opts->net);
1689 mutex_unlock(&opts->lock);
1690 ncm->port.is_fixed = true;
1691 ncm->port.supports_multi_frame = true;
1692
1693 ncm->port.func.name = "cdc_network";
1694 /* descriptors are per-instance copies */
1695 ncm->port.func.bind = ncm_bind;
1696 ncm->port.func.unbind = ncm_unbind;
1697 ncm->port.func.set_alt = ncm_set_alt;
1698 ncm->port.func.get_alt = ncm_get_alt;
1699 ncm->port.func.setup = ncm_setup;
1700 ncm->port.func.disable = ncm_disable;
1701 ncm->port.func.free_func = ncm_free;
1702
1703 ncm->port.wrap = ncm_wrap_ntb;
1704 ncm->port.unwrap = ncm_unwrap_ntb;
1705
1706 return &ncm->port.func;
1707 }
1708
1709 DECLARE_USB_FUNCTION_INIT(ncm, ncm_alloc_inst, ncm_alloc);
1710 MODULE_LICENSE("GPL");
1711 MODULE_AUTHOR("Yauheni Kaliuta");
1712