]> git.karo-electronics.de Git - karo-tx-linux.git/blob - drivers/usb/gadget/f_ncm.c
Merge branch 'for-linus' of git://git.kernel.org/pub/scm/linux/kernel/git/wfg/writeback
[karo-tx-linux.git] / drivers / usb / gadget / 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  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
25  */
26
27 #include <linux/kernel.h>
28 #include <linux/device.h>
29 #include <linux/etherdevice.h>
30 #include <linux/crc32.h>
31
32 #include <linux/usb/cdc.h>
33
34 #include "u_ether.h"
35
36 /*
37  * This function is a "CDC Network Control Model" (CDC NCM) Ethernet link.
38  * NCM is intended to be used with high-speed network attachments.
39  *
40  * Note that NCM requires the use of "alternate settings" for its data
41  * interface.  This means that the set_alt() method has real work to do,
42  * and also means that a get_alt() method is required.
43  */
44
45 /* to trigger crc/non-crc ndp signature */
46
47 #define NCM_NDP_HDR_CRC_MASK    0x01000000
48 #define NCM_NDP_HDR_CRC         0x01000000
49 #define NCM_NDP_HDR_NOCRC       0x00000000
50
51 enum ncm_notify_state {
52         NCM_NOTIFY_NONE,                /* don't notify */
53         NCM_NOTIFY_CONNECT,             /* issue CONNECT next */
54         NCM_NOTIFY_SPEED,               /* issue SPEED_CHANGE next */
55 };
56
57 struct f_ncm {
58         struct gether                   port;
59         u8                              ctrl_id, data_id;
60
61         char                            ethaddr[14];
62
63         struct usb_ep                   *notify;
64         struct usb_request              *notify_req;
65         u8                              notify_state;
66         bool                            is_open;
67
68         struct ndp_parser_opts          *parser_opts;
69         bool                            is_crc;
70
71         /*
72          * for notification, it is accessed from both
73          * callback and ethernet open/close
74          */
75         spinlock_t                      lock;
76 };
77
78 static inline struct f_ncm *func_to_ncm(struct usb_function *f)
79 {
80         return container_of(f, struct f_ncm, port.func);
81 }
82
83 /* peak (theoretical) bulk transfer rate in bits-per-second */
84 static inline unsigned ncm_bitrate(struct usb_gadget *g)
85 {
86         if (gadget_is_dualspeed(g) && g->speed == USB_SPEED_HIGH)
87                 return 13 * 512 * 8 * 1000 * 8;
88         else
89                 return 19 *  64 * 1 * 1000 * 8;
90 }
91
92 /*-------------------------------------------------------------------------*/
93
94 /*
95  * We cannot group frames so use just the minimal size which ok to put
96  * one max-size ethernet frame.
97  * If the host can group frames, allow it to do that, 16K is selected,
98  * because it's used by default by the current linux host driver
99  */
100 #define NTB_DEFAULT_IN_SIZE     USB_CDC_NCM_NTB_MIN_IN_SIZE
101 #define NTB_OUT_SIZE            16384
102
103 /*
104  * skbs of size less than that will not be aligned
105  * to NCM's dwNtbInMaxSize to save bus bandwidth
106  */
107
108 #define MAX_TX_NONFIXED         (512 * 3)
109
110 #define FORMATS_SUPPORTED       (USB_CDC_NCM_NTB16_SUPPORTED |  \
111                                  USB_CDC_NCM_NTB32_SUPPORTED)
112
113 static struct usb_cdc_ncm_ntb_parameters ntb_parameters = {
114         .wLength = sizeof ntb_parameters,
115         .bmNtbFormatsSupported = cpu_to_le16(FORMATS_SUPPORTED),
116         .dwNtbInMaxSize = cpu_to_le32(NTB_DEFAULT_IN_SIZE),
117         .wNdpInDivisor = cpu_to_le16(4),
118         .wNdpInPayloadRemainder = cpu_to_le16(0),
119         .wNdpInAlignment = cpu_to_le16(4),
120
121         .dwNtbOutMaxSize = cpu_to_le32(NTB_OUT_SIZE),
122         .wNdpOutDivisor = cpu_to_le16(4),
123         .wNdpOutPayloadRemainder = cpu_to_le16(0),
124         .wNdpOutAlignment = cpu_to_le16(4),
125 };
126
127 /*
128  * Use wMaxPacketSize big enough to fit CDC_NOTIFY_SPEED_CHANGE in one
129  * packet, to simplify cancellation; and a big transfer interval, to
130  * waste less bandwidth.
131  */
132
133 #define LOG2_STATUS_INTERVAL_MSEC       5       /* 1 << 5 == 32 msec */
134 #define NCM_STATUS_BYTECOUNT            16      /* 8 byte header + data */
135
136 static struct usb_interface_assoc_descriptor ncm_iad_desc __initdata = {
137         .bLength =              sizeof ncm_iad_desc,
138         .bDescriptorType =      USB_DT_INTERFACE_ASSOCIATION,
139
140         /* .bFirstInterface =   DYNAMIC, */
141         .bInterfaceCount =      2,      /* control + data */
142         .bFunctionClass =       USB_CLASS_COMM,
143         .bFunctionSubClass =    USB_CDC_SUBCLASS_NCM,
144         .bFunctionProtocol =    USB_CDC_PROTO_NONE,
145         /* .iFunction =         DYNAMIC */
146 };
147
148 /* interface descriptor: */
149
150 static struct usb_interface_descriptor ncm_control_intf __initdata = {
151         .bLength =              sizeof ncm_control_intf,
152         .bDescriptorType =      USB_DT_INTERFACE,
153
154         /* .bInterfaceNumber = DYNAMIC */
155         .bNumEndpoints =        1,
156         .bInterfaceClass =      USB_CLASS_COMM,
157         .bInterfaceSubClass =   USB_CDC_SUBCLASS_NCM,
158         .bInterfaceProtocol =   USB_CDC_PROTO_NONE,
159         /* .iInterface = DYNAMIC */
160 };
161
162 static struct usb_cdc_header_desc ncm_header_desc __initdata = {
163         .bLength =              sizeof ncm_header_desc,
164         .bDescriptorType =      USB_DT_CS_INTERFACE,
165         .bDescriptorSubType =   USB_CDC_HEADER_TYPE,
166
167         .bcdCDC =               cpu_to_le16(0x0110),
168 };
169
170 static struct usb_cdc_union_desc ncm_union_desc __initdata = {
171         .bLength =              sizeof(ncm_union_desc),
172         .bDescriptorType =      USB_DT_CS_INTERFACE,
173         .bDescriptorSubType =   USB_CDC_UNION_TYPE,
174         /* .bMasterInterface0 = DYNAMIC */
175         /* .bSlaveInterface0 =  DYNAMIC */
176 };
177
178 static struct usb_cdc_ether_desc ecm_desc __initdata = {
179         .bLength =              sizeof ecm_desc,
180         .bDescriptorType =      USB_DT_CS_INTERFACE,
181         .bDescriptorSubType =   USB_CDC_ETHERNET_TYPE,
182
183         /* this descriptor actually adds value, surprise! */
184         /* .iMACAddress = DYNAMIC */
185         .bmEthernetStatistics = cpu_to_le32(0), /* no statistics */
186         .wMaxSegmentSize =      cpu_to_le16(ETH_FRAME_LEN),
187         .wNumberMCFilters =     cpu_to_le16(0),
188         .bNumberPowerFilters =  0,
189 };
190
191 #define NCAPS   (USB_CDC_NCM_NCAP_ETH_FILTER | USB_CDC_NCM_NCAP_CRC_MODE)
192
193 static struct usb_cdc_ncm_desc ncm_desc __initdata = {
194         .bLength =              sizeof ncm_desc,
195         .bDescriptorType =      USB_DT_CS_INTERFACE,
196         .bDescriptorSubType =   USB_CDC_NCM_TYPE,
197
198         .bcdNcmVersion =        cpu_to_le16(0x0100),
199         /* can process SetEthernetPacketFilter */
200         .bmNetworkCapabilities = NCAPS,
201 };
202
203 /* the default data interface has no endpoints ... */
204
205 static struct usb_interface_descriptor ncm_data_nop_intf __initdata = {
206         .bLength =              sizeof ncm_data_nop_intf,
207         .bDescriptorType =      USB_DT_INTERFACE,
208
209         .bInterfaceNumber =     1,
210         .bAlternateSetting =    0,
211         .bNumEndpoints =        0,
212         .bInterfaceClass =      USB_CLASS_CDC_DATA,
213         .bInterfaceSubClass =   0,
214         .bInterfaceProtocol =   USB_CDC_NCM_PROTO_NTB,
215         /* .iInterface = DYNAMIC */
216 };
217
218 /* ... but the "real" data interface has two bulk endpoints */
219
220 static struct usb_interface_descriptor ncm_data_intf __initdata = {
221         .bLength =              sizeof ncm_data_intf,
222         .bDescriptorType =      USB_DT_INTERFACE,
223
224         .bInterfaceNumber =     1,
225         .bAlternateSetting =    1,
226         .bNumEndpoints =        2,
227         .bInterfaceClass =      USB_CLASS_CDC_DATA,
228         .bInterfaceSubClass =   0,
229         .bInterfaceProtocol =   USB_CDC_NCM_PROTO_NTB,
230         /* .iInterface = DYNAMIC */
231 };
232
233 /* full speed support: */
234
235 static struct usb_endpoint_descriptor fs_ncm_notify_desc __initdata = {
236         .bLength =              USB_DT_ENDPOINT_SIZE,
237         .bDescriptorType =      USB_DT_ENDPOINT,
238
239         .bEndpointAddress =     USB_DIR_IN,
240         .bmAttributes =         USB_ENDPOINT_XFER_INT,
241         .wMaxPacketSize =       cpu_to_le16(NCM_STATUS_BYTECOUNT),
242         .bInterval =            1 << LOG2_STATUS_INTERVAL_MSEC,
243 };
244
245 static struct usb_endpoint_descriptor fs_ncm_in_desc __initdata = {
246         .bLength =              USB_DT_ENDPOINT_SIZE,
247         .bDescriptorType =      USB_DT_ENDPOINT,
248
249         .bEndpointAddress =     USB_DIR_IN,
250         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
251 };
252
253 static struct usb_endpoint_descriptor fs_ncm_out_desc __initdata = {
254         .bLength =              USB_DT_ENDPOINT_SIZE,
255         .bDescriptorType =      USB_DT_ENDPOINT,
256
257         .bEndpointAddress =     USB_DIR_OUT,
258         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
259 };
260
261 static struct usb_descriptor_header *ncm_fs_function[] __initdata = {
262         (struct usb_descriptor_header *) &ncm_iad_desc,
263         /* CDC NCM control descriptors */
264         (struct usb_descriptor_header *) &ncm_control_intf,
265         (struct usb_descriptor_header *) &ncm_header_desc,
266         (struct usb_descriptor_header *) &ncm_union_desc,
267         (struct usb_descriptor_header *) &ecm_desc,
268         (struct usb_descriptor_header *) &ncm_desc,
269         (struct usb_descriptor_header *) &fs_ncm_notify_desc,
270         /* data interface, altsettings 0 and 1 */
271         (struct usb_descriptor_header *) &ncm_data_nop_intf,
272         (struct usb_descriptor_header *) &ncm_data_intf,
273         (struct usb_descriptor_header *) &fs_ncm_in_desc,
274         (struct usb_descriptor_header *) &fs_ncm_out_desc,
275         NULL,
276 };
277
278 /* high speed support: */
279
280 static struct usb_endpoint_descriptor hs_ncm_notify_desc __initdata = {
281         .bLength =              USB_DT_ENDPOINT_SIZE,
282         .bDescriptorType =      USB_DT_ENDPOINT,
283
284         .bEndpointAddress =     USB_DIR_IN,
285         .bmAttributes =         USB_ENDPOINT_XFER_INT,
286         .wMaxPacketSize =       cpu_to_le16(NCM_STATUS_BYTECOUNT),
287         .bInterval =            LOG2_STATUS_INTERVAL_MSEC + 4,
288 };
289 static struct usb_endpoint_descriptor hs_ncm_in_desc __initdata = {
290         .bLength =              USB_DT_ENDPOINT_SIZE,
291         .bDescriptorType =      USB_DT_ENDPOINT,
292
293         .bEndpointAddress =     USB_DIR_IN,
294         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
295         .wMaxPacketSize =       cpu_to_le16(512),
296 };
297
298 static struct usb_endpoint_descriptor hs_ncm_out_desc __initdata = {
299         .bLength =              USB_DT_ENDPOINT_SIZE,
300         .bDescriptorType =      USB_DT_ENDPOINT,
301
302         .bEndpointAddress =     USB_DIR_OUT,
303         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
304         .wMaxPacketSize =       cpu_to_le16(512),
305 };
306
307 static struct usb_descriptor_header *ncm_hs_function[] __initdata = {
308         (struct usb_descriptor_header *) &ncm_iad_desc,
309         /* CDC NCM control descriptors */
310         (struct usb_descriptor_header *) &ncm_control_intf,
311         (struct usb_descriptor_header *) &ncm_header_desc,
312         (struct usb_descriptor_header *) &ncm_union_desc,
313         (struct usb_descriptor_header *) &ecm_desc,
314         (struct usb_descriptor_header *) &ncm_desc,
315         (struct usb_descriptor_header *) &hs_ncm_notify_desc,
316         /* data interface, altsettings 0 and 1 */
317         (struct usb_descriptor_header *) &ncm_data_nop_intf,
318         (struct usb_descriptor_header *) &ncm_data_intf,
319         (struct usb_descriptor_header *) &hs_ncm_in_desc,
320         (struct usb_descriptor_header *) &hs_ncm_out_desc,
321         NULL,
322 };
323
324 /* string descriptors: */
325
326 #define STRING_CTRL_IDX 0
327 #define STRING_MAC_IDX  1
328 #define STRING_DATA_IDX 2
329 #define STRING_IAD_IDX  3
330
331 static struct usb_string ncm_string_defs[] = {
332         [STRING_CTRL_IDX].s = "CDC Network Control Model (NCM)",
333         [STRING_MAC_IDX].s = NULL /* DYNAMIC */,
334         [STRING_DATA_IDX].s = "CDC Network Data",
335         [STRING_IAD_IDX].s = "CDC NCM",
336         {  } /* end of list */
337 };
338
339 static struct usb_gadget_strings ncm_string_table = {
340         .language =             0x0409, /* en-us */
341         .strings =              ncm_string_defs,
342 };
343
344 static struct usb_gadget_strings *ncm_strings[] = {
345         &ncm_string_table,
346         NULL,
347 };
348
349 /*
350  * Here are options for NCM Datagram Pointer table (NDP) parser.
351  * There are 2 different formats: NDP16 and NDP32 in the spec (ch. 3),
352  * in NDP16 offsets and sizes fields are 1 16bit word wide,
353  * in NDP32 -- 2 16bit words wide. Also signatures are different.
354  * To make the parser code the same, put the differences in the structure,
355  * and switch pointers to the structures when the format is changed.
356  */
357
358 struct ndp_parser_opts {
359         u32             nth_sign;
360         u32             ndp_sign;
361         unsigned        nth_size;
362         unsigned        ndp_size;
363         unsigned        ndplen_align;
364         /* sizes in u16 units */
365         unsigned        dgram_item_len; /* index or length */
366         unsigned        block_length;
367         unsigned        fp_index;
368         unsigned        reserved1;
369         unsigned        reserved2;
370         unsigned        next_fp_index;
371 };
372
373 #define INIT_NDP16_OPTS {                                       \
374                 .nth_sign = USB_CDC_NCM_NTH16_SIGN,             \
375                 .ndp_sign = USB_CDC_NCM_NDP16_NOCRC_SIGN,       \
376                 .nth_size = sizeof(struct usb_cdc_ncm_nth16),   \
377                 .ndp_size = sizeof(struct usb_cdc_ncm_ndp16),   \
378                 .ndplen_align = 4,                              \
379                 .dgram_item_len = 1,                            \
380                 .block_length = 1,                              \
381                 .fp_index = 1,                                  \
382                 .reserved1 = 0,                                 \
383                 .reserved2 = 0,                                 \
384                 .next_fp_index = 1,                             \
385         }
386
387
388 #define INIT_NDP32_OPTS {                                       \
389                 .nth_sign = USB_CDC_NCM_NTH32_SIGN,             \
390                 .ndp_sign = USB_CDC_NCM_NDP32_NOCRC_SIGN,       \
391                 .nth_size = sizeof(struct usb_cdc_ncm_nth32),   \
392                 .ndp_size = sizeof(struct usb_cdc_ncm_ndp32),   \
393                 .ndplen_align = 8,                              \
394                 .dgram_item_len = 2,                            \
395                 .block_length = 2,                              \
396                 .fp_index = 2,                                  \
397                 .reserved1 = 1,                                 \
398                 .reserved2 = 2,                                 \
399                 .next_fp_index = 2,                             \
400         }
401
402 static struct ndp_parser_opts ndp16_opts = INIT_NDP16_OPTS;
403 static struct ndp_parser_opts ndp32_opts = INIT_NDP32_OPTS;
404
405 static inline void put_ncm(__le16 **p, unsigned size, unsigned val)
406 {
407         switch (size) {
408         case 1:
409                 put_unaligned_le16((u16)val, *p);
410                 break;
411         case 2:
412                 put_unaligned_le32((u32)val, *p);
413
414                 break;
415         default:
416                 BUG();
417         }
418
419         *p += size;
420 }
421
422 static inline unsigned get_ncm(__le16 **p, unsigned size)
423 {
424         unsigned tmp;
425
426         switch (size) {
427         case 1:
428                 tmp = get_unaligned_le16(*p);
429                 break;
430         case 2:
431                 tmp = get_unaligned_le32(*p);
432                 break;
433         default:
434                 BUG();
435         }
436
437         *p += size;
438         return tmp;
439 }
440
441 /*-------------------------------------------------------------------------*/
442
443 static inline void ncm_reset_values(struct f_ncm *ncm)
444 {
445         ncm->parser_opts = &ndp16_opts;
446         ncm->is_crc = false;
447         ncm->port.cdc_filter = DEFAULT_FILTER;
448
449         /* doesn't make sense for ncm, fixed size used */
450         ncm->port.header_len = 0;
451
452         ncm->port.fixed_out_len = le32_to_cpu(ntb_parameters.dwNtbOutMaxSize);
453         ncm->port.fixed_in_len = NTB_DEFAULT_IN_SIZE;
454 }
455
456 /*
457  * Context: ncm->lock held
458  */
459 static void ncm_do_notify(struct f_ncm *ncm)
460 {
461         struct usb_request              *req = ncm->notify_req;
462         struct usb_cdc_notification     *event;
463         struct usb_composite_dev        *cdev = ncm->port.func.config->cdev;
464         __le32                          *data;
465         int                             status;
466
467         /* notification already in flight? */
468         if (!req)
469                 return;
470
471         event = req->buf;
472         switch (ncm->notify_state) {
473         case NCM_NOTIFY_NONE:
474                 return;
475
476         case NCM_NOTIFY_CONNECT:
477                 event->bNotificationType = USB_CDC_NOTIFY_NETWORK_CONNECTION;
478                 if (ncm->is_open)
479                         event->wValue = cpu_to_le16(1);
480                 else
481                         event->wValue = cpu_to_le16(0);
482                 event->wLength = 0;
483                 req->length = sizeof *event;
484
485                 DBG(cdev, "notify connect %s\n",
486                                 ncm->is_open ? "true" : "false");
487                 ncm->notify_state = NCM_NOTIFY_NONE;
488                 break;
489
490         case NCM_NOTIFY_SPEED:
491                 event->bNotificationType = USB_CDC_NOTIFY_SPEED_CHANGE;
492                 event->wValue = cpu_to_le16(0);
493                 event->wLength = cpu_to_le16(8);
494                 req->length = NCM_STATUS_BYTECOUNT;
495
496                 /* SPEED_CHANGE data is up/down speeds in bits/sec */
497                 data = req->buf + sizeof *event;
498                 data[0] = cpu_to_le32(ncm_bitrate(cdev->gadget));
499                 data[1] = data[0];
500
501                 DBG(cdev, "notify speed %d\n", ncm_bitrate(cdev->gadget));
502                 ncm->notify_state = NCM_NOTIFY_CONNECT;
503                 break;
504         }
505         event->bmRequestType = 0xA1;
506         event->wIndex = cpu_to_le16(ncm->ctrl_id);
507
508         ncm->notify_req = NULL;
509         /*
510          * In double buffering if there is a space in FIFO,
511          * completion callback can be called right after the call,
512          * so unlocking
513          */
514         spin_unlock(&ncm->lock);
515         status = usb_ep_queue(ncm->notify, req, GFP_ATOMIC);
516         spin_lock(&ncm->lock);
517         if (status < 0) {
518                 ncm->notify_req = req;
519                 DBG(cdev, "notify --> %d\n", status);
520         }
521 }
522
523 /*
524  * Context: ncm->lock held
525  */
526 static void ncm_notify(struct f_ncm *ncm)
527 {
528         /*
529          * NOTE on most versions of Linux, host side cdc-ethernet
530          * won't listen for notifications until its netdevice opens.
531          * The first notification then sits in the FIFO for a long
532          * time, and the second one is queued.
533          *
534          * If ncm_notify() is called before the second (CONNECT)
535          * notification is sent, then it will reset to send the SPEED
536          * notificaion again (and again, and again), but it's not a problem
537          */
538         ncm->notify_state = NCM_NOTIFY_SPEED;
539         ncm_do_notify(ncm);
540 }
541
542 static void ncm_notify_complete(struct usb_ep *ep, struct usb_request *req)
543 {
544         struct f_ncm                    *ncm = req->context;
545         struct usb_composite_dev        *cdev = ncm->port.func.config->cdev;
546         struct usb_cdc_notification     *event = req->buf;
547
548         spin_lock(&ncm->lock);
549         switch (req->status) {
550         case 0:
551                 VDBG(cdev, "Notification %02x sent\n",
552                      event->bNotificationType);
553                 break;
554         case -ECONNRESET:
555         case -ESHUTDOWN:
556                 ncm->notify_state = NCM_NOTIFY_NONE;
557                 break;
558         default:
559                 DBG(cdev, "event %02x --> %d\n",
560                         event->bNotificationType, req->status);
561                 break;
562         }
563         ncm->notify_req = req;
564         ncm_do_notify(ncm);
565         spin_unlock(&ncm->lock);
566 }
567
568 static void ncm_ep0out_complete(struct usb_ep *ep, struct usb_request *req)
569 {
570         /* now for SET_NTB_INPUT_SIZE only */
571         unsigned                in_size;
572         struct usb_function     *f = req->context;
573         struct f_ncm            *ncm = func_to_ncm(f);
574         struct usb_composite_dev *cdev = ep->driver_data;
575
576         req->context = NULL;
577         if (req->status || req->actual != req->length) {
578                 DBG(cdev, "Bad control-OUT transfer\n");
579                 goto invalid;
580         }
581
582         in_size = get_unaligned_le32(req->buf);
583         if (in_size < USB_CDC_NCM_NTB_MIN_IN_SIZE ||
584             in_size > le32_to_cpu(ntb_parameters.dwNtbInMaxSize)) {
585                 DBG(cdev, "Got wrong INPUT SIZE (%d) from host\n", in_size);
586                 goto invalid;
587         }
588
589         ncm->port.fixed_in_len = in_size;
590         VDBG(cdev, "Set NTB INPUT SIZE %d\n", in_size);
591         return;
592
593 invalid:
594         usb_ep_set_halt(ep);
595         return;
596 }
597
598 static int ncm_setup(struct usb_function *f, const struct usb_ctrlrequest *ctrl)
599 {
600         struct f_ncm            *ncm = func_to_ncm(f);
601         struct usb_composite_dev *cdev = f->config->cdev;
602         struct usb_request      *req = cdev->req;
603         int                     value = -EOPNOTSUPP;
604         u16                     w_index = le16_to_cpu(ctrl->wIndex);
605         u16                     w_value = le16_to_cpu(ctrl->wValue);
606         u16                     w_length = le16_to_cpu(ctrl->wLength);
607
608         /*
609          * composite driver infrastructure handles everything except
610          * CDC class messages; interface activation uses set_alt().
611          */
612         switch ((ctrl->bRequestType << 8) | ctrl->bRequest) {
613         case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
614                         | USB_CDC_SET_ETHERNET_PACKET_FILTER:
615                 /*
616                  * see 6.2.30: no data, wIndex = interface,
617                  * wValue = packet filter bitmap
618                  */
619                 if (w_length != 0 || w_index != ncm->ctrl_id)
620                         goto invalid;
621                 DBG(cdev, "packet filter %02x\n", w_value);
622                 /*
623                  * REVISIT locking of cdc_filter.  This assumes the UDC
624                  * driver won't have a concurrent packet TX irq running on
625                  * another CPU; or that if it does, this write is atomic...
626                  */
627                 ncm->port.cdc_filter = w_value;
628                 value = 0;
629                 break;
630         /*
631          * and optionally:
632          * case USB_CDC_SEND_ENCAPSULATED_COMMAND:
633          * case USB_CDC_GET_ENCAPSULATED_RESPONSE:
634          * case USB_CDC_SET_ETHERNET_MULTICAST_FILTERS:
635          * case USB_CDC_SET_ETHERNET_PM_PATTERN_FILTER:
636          * case USB_CDC_GET_ETHERNET_PM_PATTERN_FILTER:
637          * case USB_CDC_GET_ETHERNET_STATISTIC:
638          */
639
640         case ((USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
641                 | USB_CDC_GET_NTB_PARAMETERS:
642
643                 if (w_length == 0 || w_value != 0 || w_index != ncm->ctrl_id)
644                         goto invalid;
645                 value = w_length > sizeof ntb_parameters ?
646                         sizeof ntb_parameters : w_length;
647                 memcpy(req->buf, &ntb_parameters, value);
648                 VDBG(cdev, "Host asked NTB parameters\n");
649                 break;
650
651         case ((USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
652                 | USB_CDC_GET_NTB_INPUT_SIZE:
653
654                 if (w_length < 4 || w_value != 0 || w_index != ncm->ctrl_id)
655                         goto invalid;
656                 put_unaligned_le32(ncm->port.fixed_in_len, req->buf);
657                 value = 4;
658                 VDBG(cdev, "Host asked INPUT SIZE, sending %d\n",
659                      ncm->port.fixed_in_len);
660                 break;
661
662         case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
663                 | USB_CDC_SET_NTB_INPUT_SIZE:
664         {
665                 if (w_length != 4 || w_value != 0 || w_index != ncm->ctrl_id)
666                         goto invalid;
667                 req->complete = ncm_ep0out_complete;
668                 req->length = w_length;
669                 req->context = f;
670
671                 value = req->length;
672                 break;
673         }
674
675         case ((USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
676                 | USB_CDC_GET_NTB_FORMAT:
677         {
678                 uint16_t format;
679
680                 if (w_length < 2 || w_value != 0 || w_index != ncm->ctrl_id)
681                         goto invalid;
682                 format = (ncm->parser_opts == &ndp16_opts) ? 0x0000 : 0x0001;
683                 put_unaligned_le16(format, req->buf);
684                 value = 2;
685                 VDBG(cdev, "Host asked NTB FORMAT, sending %d\n", format);
686                 break;
687         }
688
689         case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
690                 | USB_CDC_SET_NTB_FORMAT:
691         {
692                 if (w_length != 0 || w_index != ncm->ctrl_id)
693                         goto invalid;
694                 switch (w_value) {
695                 case 0x0000:
696                         ncm->parser_opts = &ndp16_opts;
697                         DBG(cdev, "NCM16 selected\n");
698                         break;
699                 case 0x0001:
700                         ncm->parser_opts = &ndp32_opts;
701                         DBG(cdev, "NCM32 selected\n");
702                         break;
703                 default:
704                         goto invalid;
705                 }
706                 value = 0;
707                 break;
708         }
709         case ((USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
710                 | USB_CDC_GET_CRC_MODE:
711         {
712                 uint16_t is_crc;
713
714                 if (w_length < 2 || w_value != 0 || w_index != ncm->ctrl_id)
715                         goto invalid;
716                 is_crc = ncm->is_crc ? 0x0001 : 0x0000;
717                 put_unaligned_le16(is_crc, req->buf);
718                 value = 2;
719                 VDBG(cdev, "Host asked CRC MODE, sending %d\n", is_crc);
720                 break;
721         }
722
723         case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
724                 | USB_CDC_SET_CRC_MODE:
725         {
726                 int ndp_hdr_crc = 0;
727
728                 if (w_length != 0 || w_index != ncm->ctrl_id)
729                         goto invalid;
730                 switch (w_value) {
731                 case 0x0000:
732                         ncm->is_crc = false;
733                         ndp_hdr_crc = NCM_NDP_HDR_NOCRC;
734                         DBG(cdev, "non-CRC mode selected\n");
735                         break;
736                 case 0x0001:
737                         ncm->is_crc = true;
738                         ndp_hdr_crc = NCM_NDP_HDR_CRC;
739                         DBG(cdev, "CRC mode selected\n");
740                         break;
741                 default:
742                         goto invalid;
743                 }
744                 ncm->parser_opts->ndp_sign &= ~NCM_NDP_HDR_CRC_MASK;
745                 ncm->parser_opts->ndp_sign |= ndp_hdr_crc;
746                 value = 0;
747                 break;
748         }
749
750         /* and disabled in ncm descriptor: */
751         /* case USB_CDC_GET_NET_ADDRESS: */
752         /* case USB_CDC_SET_NET_ADDRESS: */
753         /* case USB_CDC_GET_MAX_DATAGRAM_SIZE: */
754         /* case USB_CDC_SET_MAX_DATAGRAM_SIZE: */
755
756         default:
757 invalid:
758                 DBG(cdev, "invalid control req%02x.%02x v%04x i%04x l%d\n",
759                         ctrl->bRequestType, ctrl->bRequest,
760                         w_value, w_index, w_length);
761         }
762
763         /* respond with data transfer or status phase? */
764         if (value >= 0) {
765                 DBG(cdev, "ncm req%02x.%02x v%04x i%04x l%d\n",
766                         ctrl->bRequestType, ctrl->bRequest,
767                         w_value, w_index, w_length);
768                 req->zero = 0;
769                 req->length = value;
770                 value = usb_ep_queue(cdev->gadget->ep0, req, GFP_ATOMIC);
771                 if (value < 0)
772                         ERROR(cdev, "ncm req %02x.%02x response err %d\n",
773                                         ctrl->bRequestType, ctrl->bRequest,
774                                         value);
775         }
776
777         /* device either stalls (value < 0) or reports success */
778         return value;
779 }
780
781
782 static int ncm_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
783 {
784         struct f_ncm            *ncm = func_to_ncm(f);
785         struct usb_composite_dev *cdev = f->config->cdev;
786
787         /* Control interface has only altsetting 0 */
788         if (intf == ncm->ctrl_id) {
789                 if (alt != 0)
790                         goto fail;
791
792                 if (ncm->notify->driver_data) {
793                         DBG(cdev, "reset ncm control %d\n", intf);
794                         usb_ep_disable(ncm->notify);
795                 }
796
797                 if (!(ncm->notify->desc)) {
798                         DBG(cdev, "init ncm ctrl %d\n", intf);
799                         if (config_ep_by_speed(cdev->gadget, f, ncm->notify))
800                                 goto fail;
801                 }
802                 usb_ep_enable(ncm->notify);
803                 ncm->notify->driver_data = ncm;
804
805         /* Data interface has two altsettings, 0 and 1 */
806         } else if (intf == ncm->data_id) {
807                 if (alt > 1)
808                         goto fail;
809
810                 if (ncm->port.in_ep->driver_data) {
811                         DBG(cdev, "reset ncm\n");
812                         gether_disconnect(&ncm->port);
813                         ncm_reset_values(ncm);
814                 }
815
816                 /*
817                  * CDC Network only sends data in non-default altsettings.
818                  * Changing altsettings resets filters, statistics, etc.
819                  */
820                 if (alt == 1) {
821                         struct net_device       *net;
822
823                         if (!ncm->port.in_ep->desc ||
824                             !ncm->port.out_ep->desc) {
825                                 DBG(cdev, "init ncm\n");
826                                 if (config_ep_by_speed(cdev->gadget, f,
827                                                        ncm->port.in_ep) ||
828                                     config_ep_by_speed(cdev->gadget, f,
829                                                        ncm->port.out_ep)) {
830                                         ncm->port.in_ep->desc = NULL;
831                                         ncm->port.out_ep->desc = NULL;
832                                         goto fail;
833                                 }
834                         }
835
836                         /* TODO */
837                         /* Enable zlps by default for NCM conformance;
838                          * override for musb_hdrc (avoids txdma ovhead)
839                          */
840                         ncm->port.is_zlp_ok = !(
841                                 gadget_is_musbhdrc(cdev->gadget)
842                                 );
843                         ncm->port.cdc_filter = DEFAULT_FILTER;
844                         DBG(cdev, "activate ncm\n");
845                         net = gether_connect(&ncm->port);
846                         if (IS_ERR(net))
847                                 return PTR_ERR(net);
848                 }
849
850                 spin_lock(&ncm->lock);
851                 ncm_notify(ncm);
852                 spin_unlock(&ncm->lock);
853         } else
854                 goto fail;
855
856         return 0;
857 fail:
858         return -EINVAL;
859 }
860
861 /*
862  * Because the data interface supports multiple altsettings,
863  * this NCM function *MUST* implement a get_alt() method.
864  */
865 static int ncm_get_alt(struct usb_function *f, unsigned intf)
866 {
867         struct f_ncm            *ncm = func_to_ncm(f);
868
869         if (intf == ncm->ctrl_id)
870                 return 0;
871         return ncm->port.in_ep->driver_data ? 1 : 0;
872 }
873
874 static struct sk_buff *ncm_wrap_ntb(struct gether *port,
875                                     struct sk_buff *skb)
876 {
877         struct f_ncm    *ncm = func_to_ncm(&port->func);
878         struct sk_buff  *skb2;
879         int             ncb_len = 0;
880         __le16          *tmp;
881         int             div = ntb_parameters.wNdpInDivisor;
882         int             rem = ntb_parameters.wNdpInPayloadRemainder;
883         int             pad;
884         int             ndp_align = ntb_parameters.wNdpInAlignment;
885         int             ndp_pad;
886         unsigned        max_size = ncm->port.fixed_in_len;
887         struct ndp_parser_opts *opts = ncm->parser_opts;
888         unsigned        crc_len = ncm->is_crc ? sizeof(uint32_t) : 0;
889
890         ncb_len += opts->nth_size;
891         ndp_pad = ALIGN(ncb_len, ndp_align) - ncb_len;
892         ncb_len += ndp_pad;
893         ncb_len += opts->ndp_size;
894         ncb_len += 2 * 2 * opts->dgram_item_len; /* Datagram entry */
895         ncb_len += 2 * 2 * opts->dgram_item_len; /* Zero datagram entry */
896         pad = ALIGN(ncb_len, div) + rem - ncb_len;
897         ncb_len += pad;
898
899         if (ncb_len + skb->len + crc_len > max_size) {
900                 dev_kfree_skb_any(skb);
901                 return NULL;
902         }
903
904         skb2 = skb_copy_expand(skb, ncb_len,
905                                max_size - skb->len - ncb_len - crc_len,
906                                GFP_ATOMIC);
907         dev_kfree_skb_any(skb);
908         if (!skb2)
909                 return NULL;
910
911         skb = skb2;
912
913         tmp = (void *) skb_push(skb, ncb_len);
914         memset(tmp, 0, ncb_len);
915
916         put_unaligned_le32(opts->nth_sign, tmp); /* dwSignature */
917         tmp += 2;
918         /* wHeaderLength */
919         put_unaligned_le16(opts->nth_size, tmp++);
920         tmp++; /* skip wSequence */
921         put_ncm(&tmp, opts->block_length, skb->len); /* (d)wBlockLength */
922         /* (d)wFpIndex */
923         /* the first pointer is right after the NTH + align */
924         put_ncm(&tmp, opts->fp_index, opts->nth_size + ndp_pad);
925
926         tmp = (void *)tmp + ndp_pad;
927
928         /* NDP */
929         put_unaligned_le32(opts->ndp_sign, tmp); /* dwSignature */
930         tmp += 2;
931         /* wLength */
932         put_unaligned_le16(ncb_len - opts->nth_size - pad, tmp++);
933
934         tmp += opts->reserved1;
935         tmp += opts->next_fp_index; /* skip reserved (d)wNextFpIndex */
936         tmp += opts->reserved2;
937
938         if (ncm->is_crc) {
939                 uint32_t crc;
940
941                 crc = ~crc32_le(~0,
942                                 skb->data + ncb_len,
943                                 skb->len - ncb_len);
944                 put_unaligned_le32(crc, skb->data + skb->len);
945                 skb_put(skb, crc_len);
946         }
947
948         /* (d)wDatagramIndex[0] */
949         put_ncm(&tmp, opts->dgram_item_len, ncb_len);
950         /* (d)wDatagramLength[0] */
951         put_ncm(&tmp, opts->dgram_item_len, skb->len - ncb_len);
952         /* (d)wDatagramIndex[1] and  (d)wDatagramLength[1] already zeroed */
953
954         if (skb->len > MAX_TX_NONFIXED)
955                 memset(skb_put(skb, max_size - skb->len),
956                        0, max_size - skb->len);
957
958         return skb;
959 }
960
961 static int ncm_unwrap_ntb(struct gether *port,
962                           struct sk_buff *skb,
963                           struct sk_buff_head *list)
964 {
965         struct f_ncm    *ncm = func_to_ncm(&port->func);
966         __le16          *tmp = (void *) skb->data;
967         unsigned        index, index2;
968         unsigned        dg_len, dg_len2;
969         unsigned        ndp_len;
970         struct sk_buff  *skb2;
971         int             ret = -EINVAL;
972         unsigned        max_size = le32_to_cpu(ntb_parameters.dwNtbOutMaxSize);
973         struct ndp_parser_opts *opts = ncm->parser_opts;
974         unsigned        crc_len = ncm->is_crc ? sizeof(uint32_t) : 0;
975         int             dgram_counter;
976
977         /* dwSignature */
978         if (get_unaligned_le32(tmp) != opts->nth_sign) {
979                 INFO(port->func.config->cdev, "Wrong NTH SIGN, skblen %d\n",
980                         skb->len);
981                 print_hex_dump(KERN_INFO, "HEAD:", DUMP_PREFIX_ADDRESS, 32, 1,
982                                skb->data, 32, false);
983
984                 goto err;
985         }
986         tmp += 2;
987         /* wHeaderLength */
988         if (get_unaligned_le16(tmp++) != opts->nth_size) {
989                 INFO(port->func.config->cdev, "Wrong NTB headersize\n");
990                 goto err;
991         }
992         tmp++; /* skip wSequence */
993
994         /* (d)wBlockLength */
995         if (get_ncm(&tmp, opts->block_length) > max_size) {
996                 INFO(port->func.config->cdev, "OUT size exceeded\n");
997                 goto err;
998         }
999
1000         index = get_ncm(&tmp, opts->fp_index);
1001         /* NCM 3.2 */
1002         if (((index % 4) != 0) && (index < opts->nth_size)) {
1003                 INFO(port->func.config->cdev, "Bad index: %x\n",
1004                         index);
1005                 goto err;
1006         }
1007
1008         /* walk through NDP */
1009         tmp = ((void *)skb->data) + index;
1010         if (get_unaligned_le32(tmp) != opts->ndp_sign) {
1011                 INFO(port->func.config->cdev, "Wrong NDP SIGN\n");
1012                 goto err;
1013         }
1014         tmp += 2;
1015
1016         ndp_len = get_unaligned_le16(tmp++);
1017         /*
1018          * NCM 3.3.1
1019          * entry is 2 items
1020          * item size is 16/32 bits, opts->dgram_item_len * 2 bytes
1021          * minimal: struct usb_cdc_ncm_ndpX + normal entry + zero entry
1022          */
1023         if ((ndp_len < opts->ndp_size + 2 * 2 * (opts->dgram_item_len * 2))
1024             || (ndp_len % opts->ndplen_align != 0)) {
1025                 INFO(port->func.config->cdev, "Bad NDP length: %x\n", ndp_len);
1026                 goto err;
1027         }
1028         tmp += opts->reserved1;
1029         tmp += opts->next_fp_index; /* skip reserved (d)wNextFpIndex */
1030         tmp += opts->reserved2;
1031
1032         ndp_len -= opts->ndp_size;
1033         index2 = get_ncm(&tmp, opts->dgram_item_len);
1034         dg_len2 = get_ncm(&tmp, opts->dgram_item_len);
1035         dgram_counter = 0;
1036
1037         do {
1038                 index = index2;
1039                 dg_len = dg_len2;
1040                 if (dg_len < 14 + crc_len) { /* ethernet header + crc */
1041                         INFO(port->func.config->cdev, "Bad dgram length: %x\n",
1042                              dg_len);
1043                         goto err;
1044                 }
1045                 if (ncm->is_crc) {
1046                         uint32_t crc, crc2;
1047
1048                         crc = get_unaligned_le32(skb->data +
1049                                                  index + dg_len - crc_len);
1050                         crc2 = ~crc32_le(~0,
1051                                          skb->data + index,
1052                                          dg_len - crc_len);
1053                         if (crc != crc2) {
1054                                 INFO(port->func.config->cdev, "Bad CRC\n");
1055                                 goto err;
1056                         }
1057                 }
1058
1059                 index2 = get_ncm(&tmp, opts->dgram_item_len);
1060                 dg_len2 = get_ncm(&tmp, opts->dgram_item_len);
1061
1062                 if (index2 == 0 || dg_len2 == 0) {
1063                         skb2 = skb;
1064                 } else {
1065                         skb2 = skb_clone(skb, GFP_ATOMIC);
1066                         if (skb2 == NULL)
1067                                 goto err;
1068                 }
1069
1070                 if (!skb_pull(skb2, index)) {
1071                         ret = -EOVERFLOW;
1072                         goto err;
1073                 }
1074
1075                 skb_trim(skb2, dg_len - crc_len);
1076                 skb_queue_tail(list, skb2);
1077
1078                 ndp_len -= 2 * (opts->dgram_item_len * 2);
1079
1080                 dgram_counter++;
1081
1082                 if (index2 == 0 || dg_len2 == 0)
1083                         break;
1084         } while (ndp_len > 2 * (opts->dgram_item_len * 2)); /* zero entry */
1085
1086         VDBG(port->func.config->cdev,
1087              "Parsed NTB with %d frames\n", dgram_counter);
1088         return 0;
1089 err:
1090         skb_queue_purge(list);
1091         dev_kfree_skb_any(skb);
1092         return ret;
1093 }
1094
1095 static void ncm_disable(struct usb_function *f)
1096 {
1097         struct f_ncm            *ncm = func_to_ncm(f);
1098         struct usb_composite_dev *cdev = f->config->cdev;
1099
1100         DBG(cdev, "ncm deactivated\n");
1101
1102         if (ncm->port.in_ep->driver_data)
1103                 gether_disconnect(&ncm->port);
1104
1105         if (ncm->notify->driver_data) {
1106                 usb_ep_disable(ncm->notify);
1107                 ncm->notify->driver_data = NULL;
1108                 ncm->notify->desc = NULL;
1109         }
1110 }
1111
1112 /*-------------------------------------------------------------------------*/
1113
1114 /*
1115  * Callbacks let us notify the host about connect/disconnect when the
1116  * net device is opened or closed.
1117  *
1118  * For testing, note that link states on this side include both opened
1119  * and closed variants of:
1120  *
1121  *   - disconnected/unconfigured
1122  *   - configured but inactive (data alt 0)
1123  *   - configured and active (data alt 1)
1124  *
1125  * Each needs to be tested with unplug, rmmod, SET_CONFIGURATION, and
1126  * SET_INTERFACE (altsetting).  Remember also that "configured" doesn't
1127  * imply the host is actually polling the notification endpoint, and
1128  * likewise that "active" doesn't imply it's actually using the data
1129  * endpoints for traffic.
1130  */
1131
1132 static void ncm_open(struct gether *geth)
1133 {
1134         struct f_ncm            *ncm = func_to_ncm(&geth->func);
1135
1136         DBG(ncm->port.func.config->cdev, "%s\n", __func__);
1137
1138         spin_lock(&ncm->lock);
1139         ncm->is_open = true;
1140         ncm_notify(ncm);
1141         spin_unlock(&ncm->lock);
1142 }
1143
1144 static void ncm_close(struct gether *geth)
1145 {
1146         struct f_ncm            *ncm = func_to_ncm(&geth->func);
1147
1148         DBG(ncm->port.func.config->cdev, "%s\n", __func__);
1149
1150         spin_lock(&ncm->lock);
1151         ncm->is_open = false;
1152         ncm_notify(ncm);
1153         spin_unlock(&ncm->lock);
1154 }
1155
1156 /*-------------------------------------------------------------------------*/
1157
1158 /* ethernet function driver setup/binding */
1159
1160 static int __init
1161 ncm_bind(struct usb_configuration *c, struct usb_function *f)
1162 {
1163         struct usb_composite_dev *cdev = c->cdev;
1164         struct f_ncm            *ncm = func_to_ncm(f);
1165         int                     status;
1166         struct usb_ep           *ep;
1167
1168         /* allocate instance-specific interface IDs */
1169         status = usb_interface_id(c, f);
1170         if (status < 0)
1171                 goto fail;
1172         ncm->ctrl_id = status;
1173         ncm_iad_desc.bFirstInterface = status;
1174
1175         ncm_control_intf.bInterfaceNumber = status;
1176         ncm_union_desc.bMasterInterface0 = status;
1177
1178         status = usb_interface_id(c, f);
1179         if (status < 0)
1180                 goto fail;
1181         ncm->data_id = status;
1182
1183         ncm_data_nop_intf.bInterfaceNumber = status;
1184         ncm_data_intf.bInterfaceNumber = status;
1185         ncm_union_desc.bSlaveInterface0 = status;
1186
1187         status = -ENODEV;
1188
1189         /* allocate instance-specific endpoints */
1190         ep = usb_ep_autoconfig(cdev->gadget, &fs_ncm_in_desc);
1191         if (!ep)
1192                 goto fail;
1193         ncm->port.in_ep = ep;
1194         ep->driver_data = cdev; /* claim */
1195
1196         ep = usb_ep_autoconfig(cdev->gadget, &fs_ncm_out_desc);
1197         if (!ep)
1198                 goto fail;
1199         ncm->port.out_ep = ep;
1200         ep->driver_data = cdev; /* claim */
1201
1202         ep = usb_ep_autoconfig(cdev->gadget, &fs_ncm_notify_desc);
1203         if (!ep)
1204                 goto fail;
1205         ncm->notify = ep;
1206         ep->driver_data = cdev; /* claim */
1207
1208         status = -ENOMEM;
1209
1210         /* allocate notification request and buffer */
1211         ncm->notify_req = usb_ep_alloc_request(ep, GFP_KERNEL);
1212         if (!ncm->notify_req)
1213                 goto fail;
1214         ncm->notify_req->buf = kmalloc(NCM_STATUS_BYTECOUNT, GFP_KERNEL);
1215         if (!ncm->notify_req->buf)
1216                 goto fail;
1217         ncm->notify_req->context = ncm;
1218         ncm->notify_req->complete = ncm_notify_complete;
1219
1220         /* copy descriptors, and track endpoint copies */
1221         f->descriptors = usb_copy_descriptors(ncm_fs_function);
1222         if (!f->descriptors)
1223                 goto fail;
1224
1225         /*
1226          * support all relevant hardware speeds... we expect that when
1227          * hardware is dual speed, all bulk-capable endpoints work at
1228          * both speeds
1229          */
1230         if (gadget_is_dualspeed(c->cdev->gadget)) {
1231                 hs_ncm_in_desc.bEndpointAddress =
1232                                 fs_ncm_in_desc.bEndpointAddress;
1233                 hs_ncm_out_desc.bEndpointAddress =
1234                                 fs_ncm_out_desc.bEndpointAddress;
1235                 hs_ncm_notify_desc.bEndpointAddress =
1236                                 fs_ncm_notify_desc.bEndpointAddress;
1237
1238                 /* copy descriptors, and track endpoint copies */
1239                 f->hs_descriptors = usb_copy_descriptors(ncm_hs_function);
1240                 if (!f->hs_descriptors)
1241                         goto fail;
1242         }
1243
1244         /*
1245          * NOTE:  all that is done without knowing or caring about
1246          * the network link ... which is unavailable to this code
1247          * until we're activated via set_alt().
1248          */
1249
1250         ncm->port.open = ncm_open;
1251         ncm->port.close = ncm_close;
1252
1253         DBG(cdev, "CDC Network: %s speed IN/%s OUT/%s NOTIFY/%s\n",
1254                         gadget_is_dualspeed(c->cdev->gadget) ? "dual" : "full",
1255                         ncm->port.in_ep->name, ncm->port.out_ep->name,
1256                         ncm->notify->name);
1257         return 0;
1258
1259 fail:
1260         if (f->descriptors)
1261                 usb_free_descriptors(f->descriptors);
1262
1263         if (ncm->notify_req) {
1264                 kfree(ncm->notify_req->buf);
1265                 usb_ep_free_request(ncm->notify, ncm->notify_req);
1266         }
1267
1268         /* we might as well release our claims on endpoints */
1269         if (ncm->notify)
1270                 ncm->notify->driver_data = NULL;
1271         if (ncm->port.out_ep->desc)
1272                 ncm->port.out_ep->driver_data = NULL;
1273         if (ncm->port.in_ep->desc)
1274                 ncm->port.in_ep->driver_data = NULL;
1275
1276         ERROR(cdev, "%s: can't bind, err %d\n", f->name, status);
1277
1278         return status;
1279 }
1280
1281 static void
1282 ncm_unbind(struct usb_configuration *c, struct usb_function *f)
1283 {
1284         struct f_ncm            *ncm = func_to_ncm(f);
1285
1286         DBG(c->cdev, "ncm unbind\n");
1287
1288         if (gadget_is_dualspeed(c->cdev->gadget))
1289                 usb_free_descriptors(f->hs_descriptors);
1290         usb_free_descriptors(f->descriptors);
1291
1292         kfree(ncm->notify_req->buf);
1293         usb_ep_free_request(ncm->notify, ncm->notify_req);
1294
1295         ncm_string_defs[1].s = NULL;
1296         kfree(ncm);
1297 }
1298
1299 /**
1300  * ncm_bind_config - add CDC Network link to a configuration
1301  * @c: the configuration to support the network link
1302  * @ethaddr: a buffer in which the ethernet address of the host side
1303  *      side of the link was recorded
1304  * Context: single threaded during gadget setup
1305  *
1306  * Returns zero on success, else negative errno.
1307  *
1308  * Caller must have called @gether_setup().  Caller is also responsible
1309  * for calling @gether_cleanup() before module unload.
1310  */
1311 int __init ncm_bind_config(struct usb_configuration *c, u8 ethaddr[ETH_ALEN])
1312 {
1313         struct f_ncm    *ncm;
1314         int             status;
1315
1316         if (!can_support_ecm(c->cdev->gadget) || !ethaddr)
1317                 return -EINVAL;
1318
1319         /* maybe allocate device-global string IDs */
1320         if (ncm_string_defs[0].id == 0) {
1321
1322                 /* control interface label */
1323                 status = usb_string_id(c->cdev);
1324                 if (status < 0)
1325                         return status;
1326                 ncm_string_defs[STRING_CTRL_IDX].id = status;
1327                 ncm_control_intf.iInterface = status;
1328
1329                 /* data interface label */
1330                 status = usb_string_id(c->cdev);
1331                 if (status < 0)
1332                         return status;
1333                 ncm_string_defs[STRING_DATA_IDX].id = status;
1334                 ncm_data_nop_intf.iInterface = status;
1335                 ncm_data_intf.iInterface = status;
1336
1337                 /* MAC address */
1338                 status = usb_string_id(c->cdev);
1339                 if (status < 0)
1340                         return status;
1341                 ncm_string_defs[STRING_MAC_IDX].id = status;
1342                 ecm_desc.iMACAddress = status;
1343
1344                 /* IAD */
1345                 status = usb_string_id(c->cdev);
1346                 if (status < 0)
1347                         return status;
1348                 ncm_string_defs[STRING_IAD_IDX].id = status;
1349                 ncm_iad_desc.iFunction = status;
1350         }
1351
1352         /* allocate and initialize one new instance */
1353         ncm = kzalloc(sizeof *ncm, GFP_KERNEL);
1354         if (!ncm)
1355                 return -ENOMEM;
1356
1357         /* export host's Ethernet address in CDC format */
1358         snprintf(ncm->ethaddr, sizeof ncm->ethaddr,
1359                 "%02X%02X%02X%02X%02X%02X",
1360                 ethaddr[0], ethaddr[1], ethaddr[2],
1361                 ethaddr[3], ethaddr[4], ethaddr[5]);
1362         ncm_string_defs[1].s = ncm->ethaddr;
1363
1364         spin_lock_init(&ncm->lock);
1365         ncm_reset_values(ncm);
1366         ncm->port.is_fixed = true;
1367
1368         ncm->port.func.name = "cdc_network";
1369         ncm->port.func.strings = ncm_strings;
1370         /* descriptors are per-instance copies */
1371         ncm->port.func.bind = ncm_bind;
1372         ncm->port.func.unbind = ncm_unbind;
1373         ncm->port.func.set_alt = ncm_set_alt;
1374         ncm->port.func.get_alt = ncm_get_alt;
1375         ncm->port.func.setup = ncm_setup;
1376         ncm->port.func.disable = ncm_disable;
1377
1378         ncm->port.wrap = ncm_wrap_ntb;
1379         ncm->port.unwrap = ncm_unwrap_ntb;
1380
1381         status = usb_add_function(c, &ncm->port.func);
1382         if (status) {
1383                 ncm_string_defs[1].s = NULL;
1384                 kfree(ncm);
1385         }
1386         return status;
1387 }