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