OSDN Git Service

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