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