net: cdc_ncm: factor out one-time device initialization
[pandora-kernel.git] / drivers / net / usb / cdc_ncm.c
1 /*
2  * cdc_ncm.c
3  *
4  * Copyright (C) ST-Ericsson 2010-2012
5  * Contact: Alexey Orishko <alexey.orishko@stericsson.com>
6  * Original author: Hans Petter Selasky <hans.petter.selasky@stericsson.com>
7  *
8  * USB Host Driver for Network Control Model (NCM)
9  * http://www.usb.org/developers/devclass_docs/NCM10.zip
10  *
11  * The NCM encoding, decoding and initialization logic
12  * derives from FreeBSD 8.x. if_cdce.c and if_cdcereg.h
13  *
14  * This software is available to you under a choice of one of two
15  * licenses. You may choose this file to be licensed under the terms
16  * of the GNU General Public License (GPL) Version 2 or the 2-clause
17  * BSD license listed below:
18  *
19  * Redistribution and use in source and binary forms, with or without
20  * modification, are permitted provided that the following conditions
21  * are met:
22  * 1. Redistributions of source code must retain the above copyright
23  *    notice, this list of conditions and the following disclaimer.
24  * 2. Redistributions in binary form must reproduce the above copyright
25  *    notice, this list of conditions and the following disclaimer in the
26  *    documentation and/or other materials provided with the distribution.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
29  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
32  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38  * SUCH DAMAGE.
39  */
40
41 #include <linux/module.h>
42 #include <linux/netdevice.h>
43 #include <linux/ctype.h>
44 #include <linux/ethtool.h>
45 #include <linux/workqueue.h>
46 #include <linux/mii.h>
47 #include <linux/crc32.h>
48 #include <linux/usb.h>
49 #include <linux/hrtimer.h>
50 #include <linux/atomic.h>
51 #include <linux/usb/usbnet.h>
52 #include <linux/usb/cdc.h>
53 #include <linux/usb/cdc_ncm.h>
54
55 #if IS_ENABLED(CONFIG_USB_NET_CDC_MBIM)
56 static bool prefer_mbim = true;
57 #else
58 static bool prefer_mbim;
59 #endif
60 module_param(prefer_mbim, bool, S_IRUGO | S_IWUSR);
61 MODULE_PARM_DESC(prefer_mbim, "Prefer MBIM setting on dual NCM/MBIM functions");
62
63 static void cdc_ncm_txpath_bh(unsigned long param);
64 static void cdc_ncm_tx_timeout_start(struct cdc_ncm_ctx *ctx);
65 static enum hrtimer_restart cdc_ncm_tx_timer_cb(struct hrtimer *hr_timer);
66 static struct usb_driver cdc_ncm_driver;
67
68 /* handle rx_max and tx_max changes */
69 static void cdc_ncm_update_rxtx_max(struct usbnet *dev, u32 new_rx, u32 new_tx)
70 {
71         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
72         u8 iface_no = ctx->control->cur_altsetting->desc.bInterfaceNumber;
73         u32 val, max, min;
74
75         /* clamp new_rx to sane values */
76         min = USB_CDC_NCM_NTB_MIN_IN_SIZE;
77         max = min_t(u32, CDC_NCM_NTB_MAX_SIZE_RX, le32_to_cpu(ctx->ncm_parm.dwNtbInMaxSize));
78
79         /* dwNtbInMaxSize spec violation? Use MIN size for both limits */
80         if (max < min) {
81                 dev_warn(&dev->intf->dev, "dwNtbInMaxSize=%u is too small. Using %u\n",
82                          le32_to_cpu(ctx->ncm_parm.dwNtbInMaxSize), min);
83                 max = min;
84         }
85
86         val = clamp_t(u32, new_rx, min, max);
87         if (val != new_rx) {
88                 dev_dbg(&dev->intf->dev, "rx_max must be in the [%u, %u] range. Using %u\n",
89                         min, max, val);
90         }
91
92         /* inform device about NTB input size changes */
93         if (val != ctx->rx_max) {
94                 __le32 dwNtbInMaxSize = cpu_to_le32(val);
95
96                 dev_info(&dev->intf->dev, "setting rx_max = %u\n", val);
97                 if (usbnet_write_cmd(dev, USB_CDC_SET_NTB_INPUT_SIZE,
98                                      USB_TYPE_CLASS | USB_DIR_OUT
99                                      | USB_RECIP_INTERFACE,
100                                      0, iface_no, &dwNtbInMaxSize, 4) < 0)
101                         dev_dbg(&dev->intf->dev, "Setting NTB Input Size failed\n");
102                 else
103                         ctx->rx_max = val;
104         }
105
106         /* clamp new_tx to sane values */
107         min = CDC_NCM_MIN_HDR_SIZE + ctx->max_datagram_size;
108         max = min_t(u32, CDC_NCM_NTB_MAX_SIZE_TX, le32_to_cpu(ctx->ncm_parm.dwNtbOutMaxSize));
109
110         /* some devices set dwNtbOutMaxSize too low for the above default */
111         min = min(min, max);
112
113         val = clamp_t(u32, new_tx, min, max);
114         if (val != new_tx) {
115                 dev_dbg(&dev->intf->dev, "tx_max must be in the [%u, %u] range. Using %u\n",
116                         min, max, val);
117         }
118         if (val != ctx->tx_max)
119                 dev_info(&dev->intf->dev, "setting tx_max = %u\n", val);
120         ctx->tx_max = val;
121 }
122
123 /* helpers for NCM and MBIM differences */
124 static u8 cdc_ncm_flags(struct usbnet *dev)
125 {
126         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
127
128         if (cdc_ncm_comm_intf_is_mbim(dev->intf->cur_altsetting) && ctx->mbim_desc)
129                 return ctx->mbim_desc->bmNetworkCapabilities;
130         if (ctx->func_desc)
131                 return ctx->func_desc->bmNetworkCapabilities;
132         return 0;
133 }
134
135 static int cdc_ncm_eth_hlen(struct usbnet *dev)
136 {
137         if (cdc_ncm_comm_intf_is_mbim(dev->intf->cur_altsetting))
138                 return 0;
139         return ETH_HLEN;
140 }
141
142 static u32 cdc_ncm_min_dgram_size(struct usbnet *dev)
143 {
144         if (cdc_ncm_comm_intf_is_mbim(dev->intf->cur_altsetting))
145                 return CDC_MBIM_MIN_DATAGRAM_SIZE;
146         return CDC_NCM_MIN_DATAGRAM_SIZE;
147 }
148
149 static u32 cdc_ncm_max_dgram_size(struct usbnet *dev)
150 {
151         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
152
153         if (cdc_ncm_comm_intf_is_mbim(dev->intf->cur_altsetting) && ctx->mbim_desc)
154                 return le16_to_cpu(ctx->mbim_desc->wMaxSegmentSize);
155         if (ctx->ether_desc)
156                 return le16_to_cpu(ctx->ether_desc->wMaxSegmentSize);
157         return CDC_NCM_MAX_DATAGRAM_SIZE;
158 }
159
160 /* initial one-time device setup.  MUST be called with the data interface
161  * in altsetting 0
162  */
163 static int cdc_ncm_init(struct usbnet *dev)
164 {
165         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
166         u8 iface_no = ctx->control->cur_altsetting->desc.bInterfaceNumber;
167         int err;
168
169         err = usbnet_read_cmd(dev, USB_CDC_GET_NTB_PARAMETERS,
170                               USB_TYPE_CLASS | USB_DIR_IN
171                               |USB_RECIP_INTERFACE,
172                               0, iface_no, &ctx->ncm_parm,
173                               sizeof(ctx->ncm_parm));
174         if (err < 0) {
175                 dev_err(&dev->intf->dev, "failed GET_NTB_PARAMETERS\n");
176                 return err; /* GET_NTB_PARAMETERS is required */
177         }
178
179         /* set CRC Mode */
180         if (cdc_ncm_flags(dev) & USB_CDC_NCM_NCAP_CRC_MODE) {
181                 dev_dbg(&dev->intf->dev, "Setting CRC mode off\n");
182                 err = usbnet_write_cmd(dev, USB_CDC_SET_CRC_MODE,
183                                        USB_TYPE_CLASS | USB_DIR_OUT
184                                        | USB_RECIP_INTERFACE,
185                                        USB_CDC_NCM_CRC_NOT_APPENDED,
186                                        iface_no, NULL, 0);
187                 if (err < 0)
188                         dev_err(&dev->intf->dev, "SET_CRC_MODE failed\n");
189         }
190
191         /* set NTB format, if both formats are supported.
192          *
193          * "The host shall only send this command while the NCM Data
194          *  Interface is in alternate setting 0."
195          */
196         if (le16_to_cpu(ctx->ncm_parm.bmNtbFormatsSupported) & USB_CDC_NCM_NTH32_SIGN) {
197                 dev_dbg(&dev->intf->dev, "Setting NTB format to 16-bit\n");
198                 err = usbnet_write_cmd(dev, USB_CDC_SET_NTB_FORMAT,
199                                        USB_TYPE_CLASS | USB_DIR_OUT
200                                        | USB_RECIP_INTERFACE,
201                                        USB_CDC_NCM_NTB16_FORMAT,
202                                        iface_no, NULL, 0);
203                 if (err < 0)
204                         dev_err(&dev->intf->dev, "SET_NTB_FORMAT failed\n");
205         }
206
207         /* set initial device values */
208         ctx->rx_max = le32_to_cpu(ctx->ncm_parm.dwNtbInMaxSize);
209         ctx->tx_max = le32_to_cpu(ctx->ncm_parm.dwNtbOutMaxSize);
210         ctx->tx_remainder = le16_to_cpu(ctx->ncm_parm.wNdpOutPayloadRemainder);
211         ctx->tx_modulus = le16_to_cpu(ctx->ncm_parm.wNdpOutDivisor);
212         ctx->tx_ndp_modulus = le16_to_cpu(ctx->ncm_parm.wNdpOutAlignment);
213         /* devices prior to NCM Errata shall set this field to zero */
214         ctx->tx_max_datagrams = le16_to_cpu(ctx->ncm_parm.wNtbOutMaxDatagrams);
215
216         dev_dbg(&dev->intf->dev,
217                 "dwNtbInMaxSize=%u dwNtbOutMaxSize=%u wNdpOutPayloadRemainder=%u wNdpOutDivisor=%u wNdpOutAlignment=%u wNtbOutMaxDatagrams=%u flags=0x%x\n",
218                 ctx->rx_max, ctx->tx_max, ctx->tx_remainder, ctx->tx_modulus,
219                 ctx->tx_ndp_modulus, ctx->tx_max_datagrams, cdc_ncm_flags(dev));
220
221         /* max count of tx datagrams */
222         if ((ctx->tx_max_datagrams == 0) ||
223                         (ctx->tx_max_datagrams > CDC_NCM_DPT_DATAGRAMS_MAX))
224                 ctx->tx_max_datagrams = CDC_NCM_DPT_DATAGRAMS_MAX;
225
226         return 0;
227 }
228
229 /* set a new max datagram size */
230 static void cdc_ncm_set_dgram_size(struct usbnet *dev, int new_size)
231 {
232         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
233         u8 iface_no = ctx->control->cur_altsetting->desc.bInterfaceNumber;
234         __le16 max_datagram_size;
235         u16 mbim_mtu;
236         int err;
237
238         /* set default based on descriptors */
239         ctx->max_datagram_size = clamp_t(u32, new_size,
240                                          cdc_ncm_min_dgram_size(dev),
241                                          CDC_NCM_MAX_DATAGRAM_SIZE);
242
243         /* inform the device about the selected Max Datagram Size? */
244         if (!(cdc_ncm_flags(dev) & USB_CDC_NCM_NCAP_MAX_DATAGRAM_SIZE))
245                 goto out;
246
247         /* read current mtu value from device */
248         err = usbnet_read_cmd(dev, USB_CDC_GET_MAX_DATAGRAM_SIZE,
249                               USB_TYPE_CLASS | USB_DIR_IN | USB_RECIP_INTERFACE,
250                               0, iface_no, &max_datagram_size, 2);
251         if (err < 0) {
252                 dev_dbg(&dev->intf->dev, "GET_MAX_DATAGRAM_SIZE failed\n");
253                 goto out;
254         }
255
256         if (le16_to_cpu(max_datagram_size) == ctx->max_datagram_size)
257                 goto out;
258
259         max_datagram_size = cpu_to_le16(ctx->max_datagram_size);
260         err = usbnet_write_cmd(dev, USB_CDC_SET_MAX_DATAGRAM_SIZE,
261                                USB_TYPE_CLASS | USB_DIR_OUT | USB_RECIP_INTERFACE,
262                                0, iface_no, &max_datagram_size, 2);
263         if (err < 0)
264                 dev_dbg(&dev->intf->dev, "SET_MAX_DATAGRAM_SIZE failed\n");
265
266 out:
267         /* set MTU to max supported by the device if necessary */
268         dev->net->mtu = min_t(int, dev->net->mtu, ctx->max_datagram_size - cdc_ncm_eth_hlen(dev));
269
270         /* do not exceed operater preferred MTU */
271         if (ctx->mbim_extended_desc) {
272                 mbim_mtu = le16_to_cpu(ctx->mbim_extended_desc->wMTU);
273                 if (mbim_mtu != 0 && mbim_mtu < dev->net->mtu)
274                         dev->net->mtu = mbim_mtu;
275         }
276 }
277
278 static void cdc_ncm_fix_modulus(struct usbnet *dev)
279 {
280         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
281         u32 val;
282
283         /*
284          * verify that the structure alignment is:
285          * - power of two
286          * - not greater than the maximum transmit length
287          * - not less than four bytes
288          */
289         val = ctx->tx_ndp_modulus;
290
291         if ((val < USB_CDC_NCM_NDP_ALIGN_MIN_SIZE) ||
292             (val != ((-val) & val)) || (val >= ctx->tx_max)) {
293                 dev_dbg(&dev->intf->dev, "Using default alignment: 4 bytes\n");
294                 ctx->tx_ndp_modulus = USB_CDC_NCM_NDP_ALIGN_MIN_SIZE;
295         }
296
297         /*
298          * verify that the payload alignment is:
299          * - power of two
300          * - not greater than the maximum transmit length
301          * - not less than four bytes
302          */
303         val = ctx->tx_modulus;
304
305         if ((val < USB_CDC_NCM_NDP_ALIGN_MIN_SIZE) ||
306             (val != ((-val) & val)) || (val >= ctx->tx_max)) {
307                 dev_dbg(&dev->intf->dev, "Using default transmit modulus: 4 bytes\n");
308                 ctx->tx_modulus = USB_CDC_NCM_NDP_ALIGN_MIN_SIZE;
309         }
310
311         /* verify the payload remainder */
312         if (ctx->tx_remainder >= ctx->tx_modulus) {
313                 dev_dbg(&dev->intf->dev, "Using default transmit remainder: 0 bytes\n");
314                 ctx->tx_remainder = 0;
315         }
316
317         /* adjust TX-remainder according to NCM specification. */
318         ctx->tx_remainder = ((ctx->tx_remainder - cdc_ncm_eth_hlen(dev)) &
319                              (ctx->tx_modulus - 1));
320 }
321
322 static int cdc_ncm_setup(struct usbnet *dev)
323 {
324         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
325
326         /* initialize basic device settings */
327         cdc_ncm_init(dev);
328
329         /* clamp rx_max and tx_max and inform device */
330         cdc_ncm_update_rxtx_max(dev, le32_to_cpu(ctx->ncm_parm.dwNtbInMaxSize),
331                                 le32_to_cpu(ctx->ncm_parm.dwNtbOutMaxSize));
332
333         /* sanitize the modulus and remainder values */
334         cdc_ncm_fix_modulus(dev);
335
336         /* set max datagram size */
337         cdc_ncm_set_dgram_size(dev, cdc_ncm_max_dgram_size(dev));
338         return 0;
339 }
340
341 static void
342 cdc_ncm_find_endpoints(struct usbnet *dev, struct usb_interface *intf)
343 {
344         struct usb_host_endpoint *e, *in = NULL, *out = NULL;
345         u8 ep;
346
347         for (ep = 0; ep < intf->cur_altsetting->desc.bNumEndpoints; ep++) {
348
349                 e = intf->cur_altsetting->endpoint + ep;
350                 switch (e->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) {
351                 case USB_ENDPOINT_XFER_INT:
352                         if (usb_endpoint_dir_in(&e->desc)) {
353                                 if (!dev->status)
354                                         dev->status = e;
355                         }
356                         break;
357
358                 case USB_ENDPOINT_XFER_BULK:
359                         if (usb_endpoint_dir_in(&e->desc)) {
360                                 if (!in)
361                                         in = e;
362                         } else {
363                                 if (!out)
364                                         out = e;
365                         }
366                         break;
367
368                 default:
369                         break;
370                 }
371         }
372         if (in && !dev->in)
373                 dev->in = usb_rcvbulkpipe(dev->udev,
374                                           in->desc.bEndpointAddress &
375                                           USB_ENDPOINT_NUMBER_MASK);
376         if (out && !dev->out)
377                 dev->out = usb_sndbulkpipe(dev->udev,
378                                            out->desc.bEndpointAddress &
379                                            USB_ENDPOINT_NUMBER_MASK);
380 }
381
382 static void cdc_ncm_free(struct cdc_ncm_ctx *ctx)
383 {
384         if (ctx == NULL)
385                 return;
386
387         if (ctx->tx_rem_skb != NULL) {
388                 dev_kfree_skb_any(ctx->tx_rem_skb);
389                 ctx->tx_rem_skb = NULL;
390         }
391
392         if (ctx->tx_curr_skb != NULL) {
393                 dev_kfree_skb_any(ctx->tx_curr_skb);
394                 ctx->tx_curr_skb = NULL;
395         }
396
397         kfree(ctx);
398 }
399
400 int cdc_ncm_bind_common(struct usbnet *dev, struct usb_interface *intf, u8 data_altsetting)
401 {
402         const struct usb_cdc_union_desc *union_desc = NULL;
403         struct cdc_ncm_ctx *ctx;
404         struct usb_driver *driver;
405         u8 *buf;
406         int len;
407         int temp;
408         u8 iface_no;
409
410         ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
411         if (!ctx)
412                 return -ENOMEM;
413
414         hrtimer_init(&ctx->tx_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
415         ctx->tx_timer.function = &cdc_ncm_tx_timer_cb;
416         ctx->bh.data = (unsigned long)dev;
417         ctx->bh.func = cdc_ncm_txpath_bh;
418         atomic_set(&ctx->stop, 0);
419         spin_lock_init(&ctx->mtx);
420
421         /* store ctx pointer in device data field */
422         dev->data[0] = (unsigned long)ctx;
423
424         /* only the control interface can be successfully probed */
425         ctx->control = intf;
426
427         /* get some pointers */
428         driver = driver_of(intf);
429         buf = intf->cur_altsetting->extra;
430         len = intf->cur_altsetting->extralen;
431
432         /* parse through descriptors associated with control interface */
433         while ((len > 0) && (buf[0] > 2) && (buf[0] <= len)) {
434
435                 if (buf[1] != USB_DT_CS_INTERFACE)
436                         goto advance;
437
438                 switch (buf[2]) {
439                 case USB_CDC_UNION_TYPE:
440                         if (buf[0] < sizeof(*union_desc))
441                                 break;
442
443                         union_desc = (const struct usb_cdc_union_desc *)buf;
444                         /* the master must be the interface we are probing */
445                         if (intf->cur_altsetting->desc.bInterfaceNumber !=
446                             union_desc->bMasterInterface0) {
447                                 dev_dbg(&intf->dev, "bogus CDC Union\n");
448                                 goto error;
449                         }
450                         ctx->data = usb_ifnum_to_if(dev->udev,
451                                                     union_desc->bSlaveInterface0);
452                         break;
453
454                 case USB_CDC_ETHERNET_TYPE:
455                         if (buf[0] < sizeof(*(ctx->ether_desc)))
456                                 break;
457
458                         ctx->ether_desc =
459                                         (const struct usb_cdc_ether_desc *)buf;
460                         break;
461
462                 case USB_CDC_NCM_TYPE:
463                         if (buf[0] < sizeof(*(ctx->func_desc)))
464                                 break;
465
466                         ctx->func_desc = (const struct usb_cdc_ncm_desc *)buf;
467                         break;
468
469                 case USB_CDC_MBIM_TYPE:
470                         if (buf[0] < sizeof(*(ctx->mbim_desc)))
471                                 break;
472
473                         ctx->mbim_desc = (const struct usb_cdc_mbim_desc *)buf;
474                         break;
475
476                 case USB_CDC_MBIM_EXTENDED_TYPE:
477                         if (buf[0] < sizeof(*(ctx->mbim_extended_desc)))
478                                 break;
479
480                         ctx->mbim_extended_desc =
481                                 (const struct usb_cdc_mbim_extended_desc *)buf;
482                         break;
483
484                 default:
485                         break;
486                 }
487 advance:
488                 /* advance to next descriptor */
489                 temp = buf[0];
490                 buf += temp;
491                 len -= temp;
492         }
493
494         /* some buggy devices have an IAD but no CDC Union */
495         if (!union_desc && intf->intf_assoc && intf->intf_assoc->bInterfaceCount == 2) {
496                 ctx->data = usb_ifnum_to_if(dev->udev, intf->cur_altsetting->desc.bInterfaceNumber + 1);
497                 dev_dbg(&intf->dev, "CDC Union missing - got slave from IAD\n");
498         }
499
500         /* check if we got everything */
501         if (!ctx->data) {
502                 dev_dbg(&intf->dev, "CDC Union missing and no IAD found\n");
503                 goto error;
504         }
505         if (cdc_ncm_comm_intf_is_mbim(intf->cur_altsetting)) {
506                 if (!ctx->mbim_desc) {
507                         dev_dbg(&intf->dev, "MBIM functional descriptor missing\n");
508                         goto error;
509                 }
510         } else {
511                 if (!ctx->ether_desc || !ctx->func_desc) {
512                         dev_dbg(&intf->dev, "NCM or ECM functional descriptors missing\n");
513                         goto error;
514                 }
515         }
516
517         /* claim data interface, if different from control */
518         if (ctx->data != ctx->control) {
519                 temp = usb_driver_claim_interface(driver, ctx->data, dev);
520                 if (temp) {
521                         dev_dbg(&intf->dev, "failed to claim data intf\n");
522                         goto error;
523                 }
524         }
525
526         iface_no = ctx->data->cur_altsetting->desc.bInterfaceNumber;
527
528         /* reset data interface */
529         temp = usb_set_interface(dev->udev, iface_no, 0);
530         if (temp) {
531                 dev_dbg(&intf->dev, "set interface failed\n");
532                 goto error2;
533         }
534
535         /* initialize data interface */
536         if (cdc_ncm_setup(dev))
537                 goto error2;
538
539         /* configure data interface */
540         temp = usb_set_interface(dev->udev, iface_no, data_altsetting);
541         if (temp) {
542                 dev_dbg(&intf->dev, "set interface failed\n");
543                 goto error2;
544         }
545
546         cdc_ncm_find_endpoints(dev, ctx->data);
547         cdc_ncm_find_endpoints(dev, ctx->control);
548         if (!dev->in || !dev->out || !dev->status) {
549                 dev_dbg(&intf->dev, "failed to collect endpoints\n");
550                 goto error2;
551         }
552
553         usb_set_intfdata(ctx->data, dev);
554         usb_set_intfdata(ctx->control, dev);
555
556         if (ctx->ether_desc) {
557                 temp = usbnet_get_ethernet_addr(dev, ctx->ether_desc->iMACAddress);
558                 if (temp) {
559                         dev_dbg(&intf->dev, "failed to get mac address\n");
560                         goto error2;
561                 }
562                 dev_info(&intf->dev, "MAC-Address: %pM\n", dev->net->dev_addr);
563         }
564
565         /* usbnet use these values for sizing tx/rx queues */
566         dev->hard_mtu = ctx->tx_max;
567         dev->rx_urb_size = ctx->rx_max;
568
569         /* cdc_ncm_setup will override dwNtbOutMaxSize if it is
570          * outside the sane range. Adding a pad byte here if necessary
571          * simplifies the handling in cdc_ncm_fill_tx_frame, making
572          * tx_max always represent the real skb max size.
573          */
574         if (ctx->tx_max != le32_to_cpu(ctx->ncm_parm.dwNtbOutMaxSize) &&
575             ctx->tx_max % usb_maxpacket(dev->udev, dev->out, 1) == 0)
576                 ctx->tx_max++;
577
578         return 0;
579
580 error2:
581         usb_set_intfdata(ctx->control, NULL);
582         usb_set_intfdata(ctx->data, NULL);
583         if (ctx->data != ctx->control)
584                 usb_driver_release_interface(driver, ctx->data);
585 error:
586         cdc_ncm_free((struct cdc_ncm_ctx *)dev->data[0]);
587         dev->data[0] = 0;
588         dev_info(&intf->dev, "bind() failure\n");
589         return -ENODEV;
590 }
591 EXPORT_SYMBOL_GPL(cdc_ncm_bind_common);
592
593 void cdc_ncm_unbind(struct usbnet *dev, struct usb_interface *intf)
594 {
595         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
596         struct usb_driver *driver = driver_of(intf);
597
598         if (ctx == NULL)
599                 return;         /* no setup */
600
601         atomic_set(&ctx->stop, 1);
602
603         if (hrtimer_active(&ctx->tx_timer))
604                 hrtimer_cancel(&ctx->tx_timer);
605
606         tasklet_kill(&ctx->bh);
607
608         /* handle devices with combined control and data interface */
609         if (ctx->control == ctx->data)
610                 ctx->data = NULL;
611
612         /* disconnect master --> disconnect slave */
613         if (intf == ctx->control && ctx->data) {
614                 usb_set_intfdata(ctx->data, NULL);
615                 usb_driver_release_interface(driver, ctx->data);
616                 ctx->data = NULL;
617
618         } else if (intf == ctx->data && ctx->control) {
619                 usb_set_intfdata(ctx->control, NULL);
620                 usb_driver_release_interface(driver, ctx->control);
621                 ctx->control = NULL;
622         }
623
624         usb_set_intfdata(intf, NULL);
625         cdc_ncm_free(ctx);
626 }
627 EXPORT_SYMBOL_GPL(cdc_ncm_unbind);
628
629 /* Return the number of the MBIM control interface altsetting iff it
630  * is preferred and available,
631  */
632 u8 cdc_ncm_select_altsetting(struct usb_interface *intf)
633 {
634         struct usb_host_interface *alt;
635
636         /* The MBIM spec defines a NCM compatible default altsetting,
637          * which we may have matched:
638          *
639          *  "Functions that implement both NCM 1.0 and MBIM (an
640          *   “NCM/MBIM function”) according to this recommendation
641          *   shall provide two alternate settings for the
642          *   Communication Interface.  Alternate setting 0, and the
643          *   associated class and endpoint descriptors, shall be
644          *   constructed according to the rules given for the
645          *   Communication Interface in section 5 of [USBNCM10].
646          *   Alternate setting 1, and the associated class and
647          *   endpoint descriptors, shall be constructed according to
648          *   the rules given in section 6 (USB Device Model) of this
649          *   specification."
650          */
651         if (intf->num_altsetting < 2)
652                 return intf->cur_altsetting->desc.bAlternateSetting;
653
654         if (prefer_mbim) {
655                 alt = usb_altnum_to_altsetting(intf, CDC_NCM_COMM_ALTSETTING_MBIM);
656                 if (alt && cdc_ncm_comm_intf_is_mbim(alt))
657                         return CDC_NCM_COMM_ALTSETTING_MBIM;
658         }
659         return CDC_NCM_COMM_ALTSETTING_NCM;
660 }
661 EXPORT_SYMBOL_GPL(cdc_ncm_select_altsetting);
662
663 static int cdc_ncm_bind(struct usbnet *dev, struct usb_interface *intf)
664 {
665         int ret;
666
667         /* MBIM backwards compatible function? */
668         if (cdc_ncm_select_altsetting(intf) != CDC_NCM_COMM_ALTSETTING_NCM)
669                 return -ENODEV;
670
671         /* The NCM data altsetting is fixed */
672         ret = cdc_ncm_bind_common(dev, intf, CDC_NCM_DATA_ALTSETTING_NCM);
673
674         /*
675          * We should get an event when network connection is "connected" or
676          * "disconnected". Set network connection in "disconnected" state
677          * (carrier is OFF) during attach, so the IP network stack does not
678          * start IPv6 negotiation and more.
679          */
680         usbnet_link_change(dev, 0, 0);
681         return ret;
682 }
683
684 static void cdc_ncm_align_tail(struct sk_buff *skb, size_t modulus, size_t remainder, size_t max)
685 {
686         size_t align = ALIGN(skb->len, modulus) - skb->len + remainder;
687
688         if (skb->len + align > max)
689                 align = max - skb->len;
690         if (align && skb_tailroom(skb) >= align)
691                 memset(skb_put(skb, align), 0, align);
692 }
693
694 /* return a pointer to a valid struct usb_cdc_ncm_ndp16 of type sign, possibly
695  * allocating a new one within skb
696  */
697 static struct usb_cdc_ncm_ndp16 *cdc_ncm_ndp(struct cdc_ncm_ctx *ctx, struct sk_buff *skb, __le32 sign, size_t reserve)
698 {
699         struct usb_cdc_ncm_ndp16 *ndp16 = NULL;
700         struct usb_cdc_ncm_nth16 *nth16 = (void *)skb->data;
701         size_t ndpoffset = le16_to_cpu(nth16->wNdpIndex);
702
703         /* follow the chain of NDPs, looking for a match */
704         while (ndpoffset) {
705                 ndp16 = (struct usb_cdc_ncm_ndp16 *)(skb->data + ndpoffset);
706                 if  (ndp16->dwSignature == sign)
707                         return ndp16;
708                 ndpoffset = le16_to_cpu(ndp16->wNextNdpIndex);
709         }
710
711         /* align new NDP */
712         cdc_ncm_align_tail(skb, ctx->tx_ndp_modulus, 0, ctx->tx_max);
713
714         /* verify that there is room for the NDP and the datagram (reserve) */
715         if ((ctx->tx_max - skb->len - reserve) < CDC_NCM_NDP_SIZE)
716                 return NULL;
717
718         /* link to it */
719         if (ndp16)
720                 ndp16->wNextNdpIndex = cpu_to_le16(skb->len);
721         else
722                 nth16->wNdpIndex = cpu_to_le16(skb->len);
723
724         /* push a new empty NDP */
725         ndp16 = (struct usb_cdc_ncm_ndp16 *)memset(skb_put(skb, CDC_NCM_NDP_SIZE), 0, CDC_NCM_NDP_SIZE);
726         ndp16->dwSignature = sign;
727         ndp16->wLength = cpu_to_le16(sizeof(struct usb_cdc_ncm_ndp16) + sizeof(struct usb_cdc_ncm_dpe16));
728         return ndp16;
729 }
730
731 struct sk_buff *
732 cdc_ncm_fill_tx_frame(struct usbnet *dev, struct sk_buff *skb, __le32 sign)
733 {
734         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
735         struct usb_cdc_ncm_nth16 *nth16;
736         struct usb_cdc_ncm_ndp16 *ndp16;
737         struct sk_buff *skb_out;
738         u16 n = 0, index, ndplen;
739         u8 ready2send = 0;
740
741         /* if there is a remaining skb, it gets priority */
742         if (skb != NULL) {
743                 swap(skb, ctx->tx_rem_skb);
744                 swap(sign, ctx->tx_rem_sign);
745         } else {
746                 ready2send = 1;
747         }
748
749         /* check if we are resuming an OUT skb */
750         skb_out = ctx->tx_curr_skb;
751
752         /* allocate a new OUT skb */
753         if (!skb_out) {
754                 skb_out = alloc_skb(ctx->tx_max, GFP_ATOMIC);
755                 if (skb_out == NULL) {
756                         if (skb != NULL) {
757                                 dev_kfree_skb_any(skb);
758                                 dev->net->stats.tx_dropped++;
759                         }
760                         goto exit_no_skb;
761                 }
762                 /* fill out the initial 16-bit NTB header */
763                 nth16 = (struct usb_cdc_ncm_nth16 *)memset(skb_put(skb_out, sizeof(struct usb_cdc_ncm_nth16)), 0, sizeof(struct usb_cdc_ncm_nth16));
764                 nth16->dwSignature = cpu_to_le32(USB_CDC_NCM_NTH16_SIGN);
765                 nth16->wHeaderLength = cpu_to_le16(sizeof(struct usb_cdc_ncm_nth16));
766                 nth16->wSequence = cpu_to_le16(ctx->tx_seq++);
767
768                 /* count total number of frames in this NTB */
769                 ctx->tx_curr_frame_num = 0;
770         }
771
772         for (n = ctx->tx_curr_frame_num; n < ctx->tx_max_datagrams; n++) {
773                 /* send any remaining skb first */
774                 if (skb == NULL) {
775                         skb = ctx->tx_rem_skb;
776                         sign = ctx->tx_rem_sign;
777                         ctx->tx_rem_skb = NULL;
778
779                         /* check for end of skb */
780                         if (skb == NULL)
781                                 break;
782                 }
783
784                 /* get the appropriate NDP for this skb */
785                 ndp16 = cdc_ncm_ndp(ctx, skb_out, sign, skb->len + ctx->tx_modulus + ctx->tx_remainder);
786
787                 /* align beginning of next frame */
788                 cdc_ncm_align_tail(skb_out,  ctx->tx_modulus, ctx->tx_remainder, ctx->tx_max);
789
790                 /* check if we had enough room left for both NDP and frame */
791                 if (!ndp16 || skb_out->len + skb->len > ctx->tx_max) {
792                         if (n == 0) {
793                                 /* won't fit, MTU problem? */
794                                 dev_kfree_skb_any(skb);
795                                 skb = NULL;
796                                 dev->net->stats.tx_dropped++;
797                         } else {
798                                 /* no room for skb - store for later */
799                                 if (ctx->tx_rem_skb != NULL) {
800                                         dev_kfree_skb_any(ctx->tx_rem_skb);
801                                         dev->net->stats.tx_dropped++;
802                                 }
803                                 ctx->tx_rem_skb = skb;
804                                 ctx->tx_rem_sign = sign;
805                                 skb = NULL;
806                                 ready2send = 1;
807                         }
808                         break;
809                 }
810
811                 /* calculate frame number withing this NDP */
812                 ndplen = le16_to_cpu(ndp16->wLength);
813                 index = (ndplen - sizeof(struct usb_cdc_ncm_ndp16)) / sizeof(struct usb_cdc_ncm_dpe16) - 1;
814
815                 /* OK, add this skb */
816                 ndp16->dpe16[index].wDatagramLength = cpu_to_le16(skb->len);
817                 ndp16->dpe16[index].wDatagramIndex = cpu_to_le16(skb_out->len);
818                 ndp16->wLength = cpu_to_le16(ndplen + sizeof(struct usb_cdc_ncm_dpe16));
819                 memcpy(skb_put(skb_out, skb->len), skb->data, skb->len);
820                 dev_kfree_skb_any(skb);
821                 skb = NULL;
822
823                 /* send now if this NDP is full */
824                 if (index >= CDC_NCM_DPT_DATAGRAMS_MAX) {
825                         ready2send = 1;
826                         break;
827                 }
828         }
829
830         /* free up any dangling skb */
831         if (skb != NULL) {
832                 dev_kfree_skb_any(skb);
833                 skb = NULL;
834                 dev->net->stats.tx_dropped++;
835         }
836
837         ctx->tx_curr_frame_num = n;
838
839         if (n == 0) {
840                 /* wait for more frames */
841                 /* push variables */
842                 ctx->tx_curr_skb = skb_out;
843                 goto exit_no_skb;
844
845         } else if ((n < ctx->tx_max_datagrams) && (ready2send == 0)) {
846                 /* wait for more frames */
847                 /* push variables */
848                 ctx->tx_curr_skb = skb_out;
849                 /* set the pending count */
850                 if (n < CDC_NCM_RESTART_TIMER_DATAGRAM_CNT)
851                         ctx->tx_timer_pending = CDC_NCM_TIMER_PENDING_CNT;
852                 goto exit_no_skb;
853
854         } else {
855                 /* frame goes out */
856                 /* variables will be reset at next call */
857         }
858
859         /* If collected data size is less or equal CDC_NCM_MIN_TX_PKT
860          * bytes, we send buffers as it is. If we get more data, it
861          * would be more efficient for USB HS mobile device with DMA
862          * engine to receive a full size NTB, than canceling DMA
863          * transfer and receiving a short packet.
864          *
865          * This optimization support is pointless if we end up sending
866          * a ZLP after full sized NTBs.
867          */
868         if (!(dev->driver_info->flags & FLAG_SEND_ZLP) &&
869             skb_out->len > CDC_NCM_MIN_TX_PKT)
870                 memset(skb_put(skb_out, ctx->tx_max - skb_out->len), 0,
871                        ctx->tx_max - skb_out->len);
872         else if (skb_out->len < ctx->tx_max && (skb_out->len % dev->maxpacket) == 0)
873                 *skb_put(skb_out, 1) = 0;       /* force short packet */
874
875         /* set final frame length */
876         nth16 = (struct usb_cdc_ncm_nth16 *)skb_out->data;
877         nth16->wBlockLength = cpu_to_le16(skb_out->len);
878
879         /* return skb */
880         ctx->tx_curr_skb = NULL;
881         dev->net->stats.tx_packets += ctx->tx_curr_frame_num;
882         return skb_out;
883
884 exit_no_skb:
885         /* Start timer, if there is a remaining skb */
886         if (ctx->tx_curr_skb != NULL)
887                 cdc_ncm_tx_timeout_start(ctx);
888         return NULL;
889 }
890 EXPORT_SYMBOL_GPL(cdc_ncm_fill_tx_frame);
891
892 static void cdc_ncm_tx_timeout_start(struct cdc_ncm_ctx *ctx)
893 {
894         /* start timer, if not already started */
895         if (!(hrtimer_active(&ctx->tx_timer) || atomic_read(&ctx->stop)))
896                 hrtimer_start(&ctx->tx_timer,
897                                 ktime_set(0, CDC_NCM_TIMER_INTERVAL),
898                                 HRTIMER_MODE_REL);
899 }
900
901 static enum hrtimer_restart cdc_ncm_tx_timer_cb(struct hrtimer *timer)
902 {
903         struct cdc_ncm_ctx *ctx =
904                         container_of(timer, struct cdc_ncm_ctx, tx_timer);
905
906         if (!atomic_read(&ctx->stop))
907                 tasklet_schedule(&ctx->bh);
908         return HRTIMER_NORESTART;
909 }
910
911 static void cdc_ncm_txpath_bh(unsigned long param)
912 {
913         struct usbnet *dev = (struct usbnet *)param;
914         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
915
916         spin_lock_bh(&ctx->mtx);
917         if (ctx->tx_timer_pending != 0) {
918                 ctx->tx_timer_pending--;
919                 cdc_ncm_tx_timeout_start(ctx);
920                 spin_unlock_bh(&ctx->mtx);
921         } else if (dev->net != NULL) {
922                 spin_unlock_bh(&ctx->mtx);
923                 netif_tx_lock_bh(dev->net);
924                 usbnet_start_xmit(NULL, dev->net);
925                 netif_tx_unlock_bh(dev->net);
926         } else {
927                 spin_unlock_bh(&ctx->mtx);
928         }
929 }
930
931 struct sk_buff *
932 cdc_ncm_tx_fixup(struct usbnet *dev, struct sk_buff *skb, gfp_t flags)
933 {
934         struct sk_buff *skb_out;
935         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
936
937         /*
938          * The Ethernet API we are using does not support transmitting
939          * multiple Ethernet frames in a single call. This driver will
940          * accumulate multiple Ethernet frames and send out a larger
941          * USB frame when the USB buffer is full or when a single jiffies
942          * timeout happens.
943          */
944         if (ctx == NULL)
945                 goto error;
946
947         spin_lock_bh(&ctx->mtx);
948         skb_out = cdc_ncm_fill_tx_frame(dev, skb, cpu_to_le32(USB_CDC_NCM_NDP16_NOCRC_SIGN));
949         spin_unlock_bh(&ctx->mtx);
950         return skb_out;
951
952 error:
953         if (skb != NULL)
954                 dev_kfree_skb_any(skb);
955
956         return NULL;
957 }
958 EXPORT_SYMBOL_GPL(cdc_ncm_tx_fixup);
959
960 /* verify NTB header and return offset of first NDP, or negative error */
961 int cdc_ncm_rx_verify_nth16(struct cdc_ncm_ctx *ctx, struct sk_buff *skb_in)
962 {
963         struct usbnet *dev = netdev_priv(skb_in->dev);
964         struct usb_cdc_ncm_nth16 *nth16;
965         int len;
966         int ret = -EINVAL;
967
968         if (ctx == NULL)
969                 goto error;
970
971         if (skb_in->len < (sizeof(struct usb_cdc_ncm_nth16) +
972                                         sizeof(struct usb_cdc_ncm_ndp16))) {
973                 netif_dbg(dev, rx_err, dev->net, "frame too short\n");
974                 goto error;
975         }
976
977         nth16 = (struct usb_cdc_ncm_nth16 *)skb_in->data;
978
979         if (nth16->dwSignature != cpu_to_le32(USB_CDC_NCM_NTH16_SIGN)) {
980                 netif_dbg(dev, rx_err, dev->net,
981                           "invalid NTH16 signature <%#010x>\n",
982                           le32_to_cpu(nth16->dwSignature));
983                 goto error;
984         }
985
986         len = le16_to_cpu(nth16->wBlockLength);
987         if (len > ctx->rx_max) {
988                 netif_dbg(dev, rx_err, dev->net,
989                           "unsupported NTB block length %u/%u\n", len,
990                           ctx->rx_max);
991                 goto error;
992         }
993
994         if ((ctx->rx_seq + 1) != le16_to_cpu(nth16->wSequence) &&
995             (ctx->rx_seq || le16_to_cpu(nth16->wSequence)) &&
996             !((ctx->rx_seq == 0xffff) && !le16_to_cpu(nth16->wSequence))) {
997                 netif_dbg(dev, rx_err, dev->net,
998                           "sequence number glitch prev=%d curr=%d\n",
999                           ctx->rx_seq, le16_to_cpu(nth16->wSequence));
1000         }
1001         ctx->rx_seq = le16_to_cpu(nth16->wSequence);
1002
1003         ret = le16_to_cpu(nth16->wNdpIndex);
1004 error:
1005         return ret;
1006 }
1007 EXPORT_SYMBOL_GPL(cdc_ncm_rx_verify_nth16);
1008
1009 /* verify NDP header and return number of datagrams, or negative error */
1010 int cdc_ncm_rx_verify_ndp16(struct sk_buff *skb_in, int ndpoffset)
1011 {
1012         struct usbnet *dev = netdev_priv(skb_in->dev);
1013         struct usb_cdc_ncm_ndp16 *ndp16;
1014         int ret = -EINVAL;
1015
1016         if ((ndpoffset + sizeof(struct usb_cdc_ncm_ndp16)) > skb_in->len) {
1017                 netif_dbg(dev, rx_err, dev->net, "invalid NDP offset  <%u>\n",
1018                           ndpoffset);
1019                 goto error;
1020         }
1021         ndp16 = (struct usb_cdc_ncm_ndp16 *)(skb_in->data + ndpoffset);
1022
1023         if (le16_to_cpu(ndp16->wLength) < USB_CDC_NCM_NDP16_LENGTH_MIN) {
1024                 netif_dbg(dev, rx_err, dev->net, "invalid DPT16 length <%u>\n",
1025                           le16_to_cpu(ndp16->wLength));
1026                 goto error;
1027         }
1028
1029         ret = ((le16_to_cpu(ndp16->wLength) -
1030                                         sizeof(struct usb_cdc_ncm_ndp16)) /
1031                                         sizeof(struct usb_cdc_ncm_dpe16));
1032         ret--; /* we process NDP entries except for the last one */
1033
1034         if ((sizeof(struct usb_cdc_ncm_ndp16) +
1035              ret * (sizeof(struct usb_cdc_ncm_dpe16))) > skb_in->len) {
1036                 netif_dbg(dev, rx_err, dev->net, "Invalid nframes = %d\n", ret);
1037                 ret = -EINVAL;
1038         }
1039
1040 error:
1041         return ret;
1042 }
1043 EXPORT_SYMBOL_GPL(cdc_ncm_rx_verify_ndp16);
1044
1045 int cdc_ncm_rx_fixup(struct usbnet *dev, struct sk_buff *skb_in)
1046 {
1047         struct sk_buff *skb;
1048         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
1049         int len;
1050         int nframes;
1051         int x;
1052         int offset;
1053         struct usb_cdc_ncm_ndp16 *ndp16;
1054         struct usb_cdc_ncm_dpe16 *dpe16;
1055         int ndpoffset;
1056         int loopcount = 50; /* arbitrary max preventing infinite loop */
1057
1058         ndpoffset = cdc_ncm_rx_verify_nth16(ctx, skb_in);
1059         if (ndpoffset < 0)
1060                 goto error;
1061
1062 next_ndp:
1063         nframes = cdc_ncm_rx_verify_ndp16(skb_in, ndpoffset);
1064         if (nframes < 0)
1065                 goto error;
1066
1067         ndp16 = (struct usb_cdc_ncm_ndp16 *)(skb_in->data + ndpoffset);
1068
1069         if (ndp16->dwSignature != cpu_to_le32(USB_CDC_NCM_NDP16_NOCRC_SIGN)) {
1070                 netif_dbg(dev, rx_err, dev->net,
1071                           "invalid DPT16 signature <%#010x>\n",
1072                           le32_to_cpu(ndp16->dwSignature));
1073                 goto err_ndp;
1074         }
1075         dpe16 = ndp16->dpe16;
1076
1077         for (x = 0; x < nframes; x++, dpe16++) {
1078                 offset = le16_to_cpu(dpe16->wDatagramIndex);
1079                 len = le16_to_cpu(dpe16->wDatagramLength);
1080
1081                 /*
1082                  * CDC NCM ch. 3.7
1083                  * All entries after first NULL entry are to be ignored
1084                  */
1085                 if ((offset == 0) || (len == 0)) {
1086                         if (!x)
1087                                 goto err_ndp; /* empty NTB */
1088                         break;
1089                 }
1090
1091                 /* sanity checking */
1092                 if (((offset + len) > skb_in->len) ||
1093                                 (len > ctx->rx_max) || (len < ETH_HLEN)) {
1094                         netif_dbg(dev, rx_err, dev->net,
1095                                   "invalid frame detected (ignored) offset[%u]=%u, length=%u, skb=%p\n",
1096                                   x, offset, len, skb_in);
1097                         if (!x)
1098                                 goto err_ndp;
1099                         break;
1100
1101                 } else {
1102                         skb = skb_clone(skb_in, GFP_ATOMIC);
1103                         if (!skb)
1104                                 goto error;
1105                         skb->len = len;
1106                         skb->data = ((u8 *)skb_in->data) + offset;
1107                         skb_set_tail_pointer(skb, len);
1108                         usbnet_skb_return(dev, skb);
1109                 }
1110         }
1111 err_ndp:
1112         /* are there more NDPs to process? */
1113         ndpoffset = le16_to_cpu(ndp16->wNextNdpIndex);
1114         if (ndpoffset && loopcount--)
1115                 goto next_ndp;
1116
1117         return 1;
1118 error:
1119         return 0;
1120 }
1121 EXPORT_SYMBOL_GPL(cdc_ncm_rx_fixup);
1122
1123 static void
1124 cdc_ncm_speed_change(struct usbnet *dev,
1125                      struct usb_cdc_speed_change *data)
1126 {
1127         uint32_t rx_speed = le32_to_cpu(data->DLBitRRate);
1128         uint32_t tx_speed = le32_to_cpu(data->ULBitRate);
1129
1130         /*
1131          * Currently the USB-NET API does not support reporting the actual
1132          * device speed. Do print it instead.
1133          */
1134         if ((tx_speed > 1000000) && (rx_speed > 1000000)) {
1135                 netif_info(dev, link, dev->net,
1136                        "%u mbit/s downlink %u mbit/s uplink\n",
1137                        (unsigned int)(rx_speed / 1000000U),
1138                        (unsigned int)(tx_speed / 1000000U));
1139         } else {
1140                 netif_info(dev, link, dev->net,
1141                        "%u kbit/s downlink %u kbit/s uplink\n",
1142                        (unsigned int)(rx_speed / 1000U),
1143                        (unsigned int)(tx_speed / 1000U));
1144         }
1145 }
1146
1147 static void cdc_ncm_status(struct usbnet *dev, struct urb *urb)
1148 {
1149         struct cdc_ncm_ctx *ctx;
1150         struct usb_cdc_notification *event;
1151
1152         ctx = (struct cdc_ncm_ctx *)dev->data[0];
1153
1154         if (urb->actual_length < sizeof(*event))
1155                 return;
1156
1157         /* test for split data in 8-byte chunks */
1158         if (test_and_clear_bit(EVENT_STS_SPLIT, &dev->flags)) {
1159                 cdc_ncm_speed_change(dev,
1160                       (struct usb_cdc_speed_change *)urb->transfer_buffer);
1161                 return;
1162         }
1163
1164         event = urb->transfer_buffer;
1165
1166         switch (event->bNotificationType) {
1167         case USB_CDC_NOTIFY_NETWORK_CONNECTION:
1168                 /*
1169                  * According to the CDC NCM specification ch.7.1
1170                  * USB_CDC_NOTIFY_NETWORK_CONNECTION notification shall be
1171                  * sent by device after USB_CDC_NOTIFY_SPEED_CHANGE.
1172                  */
1173                 ctx->connected = le16_to_cpu(event->wValue);
1174                 netif_info(dev, link, dev->net,
1175                            "network connection: %sconnected\n",
1176                            ctx->connected ? "" : "dis");
1177                 usbnet_link_change(dev, ctx->connected, 0);
1178                 break;
1179
1180         case USB_CDC_NOTIFY_SPEED_CHANGE:
1181                 if (urb->actual_length < (sizeof(*event) +
1182                                         sizeof(struct usb_cdc_speed_change)))
1183                         set_bit(EVENT_STS_SPLIT, &dev->flags);
1184                 else
1185                         cdc_ncm_speed_change(dev,
1186                                              (struct usb_cdc_speed_change *)&event[1]);
1187                 break;
1188
1189         default:
1190                 dev_dbg(&dev->udev->dev,
1191                         "NCM: unexpected notification 0x%02x!\n",
1192                         event->bNotificationType);
1193                 break;
1194         }
1195 }
1196
1197 static int cdc_ncm_check_connect(struct usbnet *dev)
1198 {
1199         struct cdc_ncm_ctx *ctx;
1200
1201         ctx = (struct cdc_ncm_ctx *)dev->data[0];
1202         if (ctx == NULL)
1203                 return 1;       /* disconnected */
1204
1205         return !ctx->connected;
1206 }
1207
1208 static const struct driver_info cdc_ncm_info = {
1209         .description = "CDC NCM",
1210         .flags = FLAG_POINTTOPOINT | FLAG_NO_SETINT | FLAG_MULTI_PACKET,
1211         .bind = cdc_ncm_bind,
1212         .unbind = cdc_ncm_unbind,
1213         .check_connect = cdc_ncm_check_connect,
1214         .manage_power = usbnet_manage_power,
1215         .status = cdc_ncm_status,
1216         .rx_fixup = cdc_ncm_rx_fixup,
1217         .tx_fixup = cdc_ncm_tx_fixup,
1218 };
1219
1220 /* Same as cdc_ncm_info, but with FLAG_WWAN */
1221 static const struct driver_info wwan_info = {
1222         .description = "Mobile Broadband Network Device",
1223         .flags = FLAG_POINTTOPOINT | FLAG_NO_SETINT | FLAG_MULTI_PACKET
1224                         | FLAG_WWAN,
1225         .bind = cdc_ncm_bind,
1226         .unbind = cdc_ncm_unbind,
1227         .check_connect = cdc_ncm_check_connect,
1228         .manage_power = usbnet_manage_power,
1229         .status = cdc_ncm_status,
1230         .rx_fixup = cdc_ncm_rx_fixup,
1231         .tx_fixup = cdc_ncm_tx_fixup,
1232 };
1233
1234 /* Same as wwan_info, but with FLAG_NOARP  */
1235 static const struct driver_info wwan_noarp_info = {
1236         .description = "Mobile Broadband Network Device (NO ARP)",
1237         .flags = FLAG_POINTTOPOINT | FLAG_NO_SETINT | FLAG_MULTI_PACKET
1238                         | FLAG_WWAN | FLAG_NOARP,
1239         .bind = cdc_ncm_bind,
1240         .unbind = cdc_ncm_unbind,
1241         .check_connect = cdc_ncm_check_connect,
1242         .manage_power = usbnet_manage_power,
1243         .status = cdc_ncm_status,
1244         .rx_fixup = cdc_ncm_rx_fixup,
1245         .tx_fixup = cdc_ncm_tx_fixup,
1246 };
1247
1248 static const struct usb_device_id cdc_devs[] = {
1249         /* Ericsson MBM devices like F5521gw */
1250         { .match_flags = USB_DEVICE_ID_MATCH_INT_INFO
1251                 | USB_DEVICE_ID_MATCH_VENDOR,
1252           .idVendor = 0x0bdb,
1253           .bInterfaceClass = USB_CLASS_COMM,
1254           .bInterfaceSubClass = USB_CDC_SUBCLASS_NCM,
1255           .bInterfaceProtocol = USB_CDC_PROTO_NONE,
1256           .driver_info = (unsigned long) &wwan_info,
1257         },
1258
1259         /* Dell branded MBM devices like DW5550 */
1260         { .match_flags = USB_DEVICE_ID_MATCH_INT_INFO
1261                 | USB_DEVICE_ID_MATCH_VENDOR,
1262           .idVendor = 0x413c,
1263           .bInterfaceClass = USB_CLASS_COMM,
1264           .bInterfaceSubClass = USB_CDC_SUBCLASS_NCM,
1265           .bInterfaceProtocol = USB_CDC_PROTO_NONE,
1266           .driver_info = (unsigned long) &wwan_info,
1267         },
1268
1269         /* Toshiba branded MBM devices */
1270         { .match_flags = USB_DEVICE_ID_MATCH_INT_INFO
1271                 | USB_DEVICE_ID_MATCH_VENDOR,
1272           .idVendor = 0x0930,
1273           .bInterfaceClass = USB_CLASS_COMM,
1274           .bInterfaceSubClass = USB_CDC_SUBCLASS_NCM,
1275           .bInterfaceProtocol = USB_CDC_PROTO_NONE,
1276           .driver_info = (unsigned long) &wwan_info,
1277         },
1278
1279         /* tag Huawei devices as wwan */
1280         { USB_VENDOR_AND_INTERFACE_INFO(0x12d1,
1281                                         USB_CLASS_COMM,
1282                                         USB_CDC_SUBCLASS_NCM,
1283                                         USB_CDC_PROTO_NONE),
1284           .driver_info = (unsigned long)&wwan_info,
1285         },
1286
1287         /* Infineon(now Intel) HSPA Modem platform */
1288         { USB_DEVICE_AND_INTERFACE_INFO(0x1519, 0x0443,
1289                 USB_CLASS_COMM,
1290                 USB_CDC_SUBCLASS_NCM, USB_CDC_PROTO_NONE),
1291           .driver_info = (unsigned long)&wwan_noarp_info,
1292         },
1293
1294         /* Generic CDC-NCM devices */
1295         { USB_INTERFACE_INFO(USB_CLASS_COMM,
1296                 USB_CDC_SUBCLASS_NCM, USB_CDC_PROTO_NONE),
1297                 .driver_info = (unsigned long)&cdc_ncm_info,
1298         },
1299         {
1300         },
1301 };
1302 MODULE_DEVICE_TABLE(usb, cdc_devs);
1303
1304 static struct usb_driver cdc_ncm_driver = {
1305         .name = "cdc_ncm",
1306         .id_table = cdc_devs,
1307         .probe = usbnet_probe,
1308         .disconnect = usbnet_disconnect,
1309         .suspend = usbnet_suspend,
1310         .resume = usbnet_resume,
1311         .reset_resume = usbnet_resume,
1312         .supports_autosuspend = 1,
1313         .disable_hub_initiated_lpm = 1,
1314 };
1315
1316 module_usb_driver(cdc_ncm_driver);
1317
1318 MODULE_AUTHOR("Hans Petter Selasky");
1319 MODULE_DESCRIPTION("USB CDC NCM host driver");
1320 MODULE_LICENSE("Dual BSD/GPL");