net: cdc_ncm: always reallocate tx_curr_skb when tx_max increases
[platform/kernel/linux-rpi.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 struct cdc_ncm_stats {
69         char stat_string[ETH_GSTRING_LEN];
70         int sizeof_stat;
71         int stat_offset;
72 };
73
74 #define CDC_NCM_STAT(str, m) { \
75                 .stat_string = str, \
76                 .sizeof_stat = sizeof(((struct cdc_ncm_ctx *)0)->m), \
77                 .stat_offset = offsetof(struct cdc_ncm_ctx, m) }
78 #define CDC_NCM_SIMPLE_STAT(m)  CDC_NCM_STAT(__stringify(m), m)
79
80 static const struct cdc_ncm_stats cdc_ncm_gstrings_stats[] = {
81         CDC_NCM_SIMPLE_STAT(tx_reason_ntb_full),
82         CDC_NCM_SIMPLE_STAT(tx_reason_ndp_full),
83         CDC_NCM_SIMPLE_STAT(tx_reason_timeout),
84         CDC_NCM_SIMPLE_STAT(tx_reason_max_datagram),
85         CDC_NCM_SIMPLE_STAT(tx_overhead),
86         CDC_NCM_SIMPLE_STAT(tx_ntbs),
87         CDC_NCM_SIMPLE_STAT(rx_overhead),
88         CDC_NCM_SIMPLE_STAT(rx_ntbs),
89 };
90
91 static int cdc_ncm_get_sset_count(struct net_device __always_unused *netdev, int sset)
92 {
93         switch (sset) {
94         case ETH_SS_STATS:
95                 return ARRAY_SIZE(cdc_ncm_gstrings_stats);
96         default:
97                 return -EOPNOTSUPP;
98         }
99 }
100
101 static void cdc_ncm_get_ethtool_stats(struct net_device *netdev,
102                                     struct ethtool_stats __always_unused *stats,
103                                     u64 *data)
104 {
105         struct usbnet *dev = netdev_priv(netdev);
106         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
107         int i;
108         char *p = NULL;
109
110         for (i = 0; i < ARRAY_SIZE(cdc_ncm_gstrings_stats); i++) {
111                 p = (char *)ctx + cdc_ncm_gstrings_stats[i].stat_offset;
112                 data[i] = (cdc_ncm_gstrings_stats[i].sizeof_stat == sizeof(u64)) ? *(u64 *)p : *(u32 *)p;
113         }
114 }
115
116 static void cdc_ncm_get_strings(struct net_device __always_unused *netdev, u32 stringset, u8 *data)
117 {
118         u8 *p = data;
119         int i;
120
121         switch (stringset) {
122         case ETH_SS_STATS:
123                 for (i = 0; i < ARRAY_SIZE(cdc_ncm_gstrings_stats); i++) {
124                         memcpy(p, cdc_ncm_gstrings_stats[i].stat_string, ETH_GSTRING_LEN);
125                         p += ETH_GSTRING_LEN;
126                 }
127         }
128 }
129
130 static int cdc_ncm_get_coalesce(struct net_device *netdev,
131                                 struct ethtool_coalesce *ec)
132 {
133         struct usbnet *dev = netdev_priv(netdev);
134         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
135
136         /* assuming maximum sized dgrams and ignoring NDPs */
137         ec->rx_max_coalesced_frames = ctx->rx_max / ctx->max_datagram_size;
138         ec->tx_max_coalesced_frames = ctx->tx_max / ctx->max_datagram_size;
139
140         /* the timer will fire CDC_NCM_TIMER_PENDING_CNT times in a row */
141         ec->tx_coalesce_usecs = ctx->timer_interval / (NSEC_PER_USEC / CDC_NCM_TIMER_PENDING_CNT);
142         return 0;
143 }
144
145 static void cdc_ncm_update_rxtx_max(struct usbnet *dev, u32 new_rx, u32 new_tx);
146
147 static int cdc_ncm_set_coalesce(struct net_device *netdev,
148                                 struct ethtool_coalesce *ec)
149 {
150         struct usbnet *dev = netdev_priv(netdev);
151         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
152         u32 new_rx_max = ctx->rx_max;
153         u32 new_tx_max = ctx->tx_max;
154
155         /* assuming maximum sized dgrams and a single NDP */
156         if (ec->rx_max_coalesced_frames)
157                 new_rx_max = ec->rx_max_coalesced_frames * ctx->max_datagram_size;
158         if (ec->tx_max_coalesced_frames)
159                 new_tx_max = ec->tx_max_coalesced_frames * ctx->max_datagram_size;
160
161         if (ec->tx_coalesce_usecs &&
162             (ec->tx_coalesce_usecs < CDC_NCM_TIMER_INTERVAL_MIN * CDC_NCM_TIMER_PENDING_CNT ||
163              ec->tx_coalesce_usecs > CDC_NCM_TIMER_INTERVAL_MAX * CDC_NCM_TIMER_PENDING_CNT))
164                 return -EINVAL;
165
166         spin_lock_bh(&ctx->mtx);
167         ctx->timer_interval = ec->tx_coalesce_usecs * (NSEC_PER_USEC / CDC_NCM_TIMER_PENDING_CNT);
168         if (!ctx->timer_interval)
169                 ctx->tx_timer_pending = 0;
170         spin_unlock_bh(&ctx->mtx);
171
172         /* inform device of new values */
173         if (new_rx_max != ctx->rx_max || new_tx_max != ctx->tx_max)
174                 cdc_ncm_update_rxtx_max(dev, new_rx_max, new_tx_max);
175         return 0;
176 }
177
178 static const struct ethtool_ops cdc_ncm_ethtool_ops = {
179         .get_settings      = usbnet_get_settings,
180         .set_settings      = usbnet_set_settings,
181         .get_link          = usbnet_get_link,
182         .nway_reset        = usbnet_nway_reset,
183         .get_drvinfo       = usbnet_get_drvinfo,
184         .get_msglevel      = usbnet_get_msglevel,
185         .set_msglevel      = usbnet_set_msglevel,
186         .get_ts_info       = ethtool_op_get_ts_info,
187         .get_sset_count    = cdc_ncm_get_sset_count,
188         .get_strings       = cdc_ncm_get_strings,
189         .get_ethtool_stats = cdc_ncm_get_ethtool_stats,
190         .get_coalesce      = cdc_ncm_get_coalesce,
191         .set_coalesce      = cdc_ncm_set_coalesce,
192 };
193
194 /* handle rx_max and tx_max changes */
195 static void cdc_ncm_update_rxtx_max(struct usbnet *dev, u32 new_rx, u32 new_tx)
196 {
197         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
198         u8 iface_no = ctx->control->cur_altsetting->desc.bInterfaceNumber;
199         u32 val, max, min;
200
201         /* clamp new_rx to sane values */
202         min = USB_CDC_NCM_NTB_MIN_IN_SIZE;
203         max = min_t(u32, CDC_NCM_NTB_MAX_SIZE_RX, le32_to_cpu(ctx->ncm_parm.dwNtbInMaxSize));
204
205         /* dwNtbInMaxSize spec violation? Use MIN size for both limits */
206         if (max < min) {
207                 dev_warn(&dev->intf->dev, "dwNtbInMaxSize=%u is too small. Using %u\n",
208                          le32_to_cpu(ctx->ncm_parm.dwNtbInMaxSize), min);
209                 max = min;
210         }
211
212         val = clamp_t(u32, new_rx, min, max);
213         if (val != new_rx) {
214                 dev_dbg(&dev->intf->dev, "rx_max must be in the [%u, %u] range. Using %u\n",
215                         min, max, val);
216         }
217
218         /* usbnet use these values for sizing rx queues */
219         dev->rx_urb_size = val;
220
221         /* inform device about NTB input size changes */
222         if (val != ctx->rx_max) {
223                 __le32 dwNtbInMaxSize = cpu_to_le32(val);
224
225                 dev_info(&dev->intf->dev, "setting rx_max = %u\n", val);
226
227                 /* need to unlink rx urbs before increasing buffer size */
228                 if (netif_running(dev->net) && dev->rx_urb_size > ctx->rx_max)
229                         usbnet_unlink_rx_urbs(dev);
230
231                 /* tell device to use new size */
232                 if (usbnet_write_cmd(dev, USB_CDC_SET_NTB_INPUT_SIZE,
233                                      USB_TYPE_CLASS | USB_DIR_OUT
234                                      | USB_RECIP_INTERFACE,
235                                      0, iface_no, &dwNtbInMaxSize, 4) < 0)
236                         dev_dbg(&dev->intf->dev, "Setting NTB Input Size failed\n");
237                 else
238                         ctx->rx_max = val;
239         }
240
241         /* clamp new_tx to sane values */
242         min = ctx->max_datagram_size + ctx->max_ndp_size + sizeof(struct usb_cdc_ncm_nth16);
243         max = min_t(u32, CDC_NCM_NTB_MAX_SIZE_TX, le32_to_cpu(ctx->ncm_parm.dwNtbOutMaxSize));
244
245         /* some devices set dwNtbOutMaxSize too low for the above default */
246         min = min(min, max);
247
248         val = clamp_t(u32, new_tx, min, max);
249         if (val != new_tx) {
250                 dev_dbg(&dev->intf->dev, "tx_max must be in the [%u, %u] range. Using %u\n",
251                         min, max, val);
252         }
253         if (val != ctx->tx_max)
254                 dev_info(&dev->intf->dev, "setting tx_max = %u\n", val);
255
256         /* Adding a pad byte here if necessary simplifies the handling
257          * in cdc_ncm_fill_tx_frame, making tx_max always represent
258          * the real skb max size.
259          *
260          * We cannot use dev->maxpacket here because this is called from
261          * .bind which is called before usbnet sets up dev->maxpacket
262          */
263         if (val != le32_to_cpu(ctx->ncm_parm.dwNtbOutMaxSize) &&
264             val % usb_maxpacket(dev->udev, dev->out, 1) == 0)
265                 val++;
266
267         /* we might need to flush any pending tx buffers if running */
268         if (netif_running(dev->net) && val > ctx->tx_max) {
269                 netif_tx_lock_bh(dev->net);
270                 usbnet_start_xmit(NULL, dev->net);
271                 /* make sure tx_curr_skb is reallocated if it was empty */
272                 if (ctx->tx_curr_skb) {
273                         dev_kfree_skb_any(ctx->tx_curr_skb);
274                         ctx->tx_curr_skb = NULL;
275                 }
276                 ctx->tx_max = val;
277                 netif_tx_unlock_bh(dev->net);
278         } else {
279                 ctx->tx_max = val;
280         }
281
282         dev->hard_mtu = ctx->tx_max;
283
284         /* max qlen depend on hard_mtu and rx_urb_size */
285         usbnet_update_max_qlen(dev);
286
287         /* never pad more than 3 full USB packets per transfer */
288         ctx->min_tx_pkt = clamp_t(u16, ctx->tx_max - 3 * usb_maxpacket(dev->udev, dev->out, 1),
289                                   CDC_NCM_MIN_TX_PKT, ctx->tx_max);
290 }
291
292 /* helpers for NCM and MBIM differences */
293 static u8 cdc_ncm_flags(struct usbnet *dev)
294 {
295         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
296
297         if (cdc_ncm_comm_intf_is_mbim(dev->intf->cur_altsetting) && ctx->mbim_desc)
298                 return ctx->mbim_desc->bmNetworkCapabilities;
299         if (ctx->func_desc)
300                 return ctx->func_desc->bmNetworkCapabilities;
301         return 0;
302 }
303
304 static int cdc_ncm_eth_hlen(struct usbnet *dev)
305 {
306         if (cdc_ncm_comm_intf_is_mbim(dev->intf->cur_altsetting))
307                 return 0;
308         return ETH_HLEN;
309 }
310
311 static u32 cdc_ncm_min_dgram_size(struct usbnet *dev)
312 {
313         if (cdc_ncm_comm_intf_is_mbim(dev->intf->cur_altsetting))
314                 return CDC_MBIM_MIN_DATAGRAM_SIZE;
315         return CDC_NCM_MIN_DATAGRAM_SIZE;
316 }
317
318 static u32 cdc_ncm_max_dgram_size(struct usbnet *dev)
319 {
320         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
321
322         if (cdc_ncm_comm_intf_is_mbim(dev->intf->cur_altsetting) && ctx->mbim_desc)
323                 return le16_to_cpu(ctx->mbim_desc->wMaxSegmentSize);
324         if (ctx->ether_desc)
325                 return le16_to_cpu(ctx->ether_desc->wMaxSegmentSize);
326         return CDC_NCM_MAX_DATAGRAM_SIZE;
327 }
328
329 /* initial one-time device setup.  MUST be called with the data interface
330  * in altsetting 0
331  */
332 static int cdc_ncm_init(struct usbnet *dev)
333 {
334         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
335         u8 iface_no = ctx->control->cur_altsetting->desc.bInterfaceNumber;
336         int err;
337
338         err = usbnet_read_cmd(dev, USB_CDC_GET_NTB_PARAMETERS,
339                               USB_TYPE_CLASS | USB_DIR_IN
340                               |USB_RECIP_INTERFACE,
341                               0, iface_no, &ctx->ncm_parm,
342                               sizeof(ctx->ncm_parm));
343         if (err < 0) {
344                 dev_err(&dev->intf->dev, "failed GET_NTB_PARAMETERS\n");
345                 return err; /* GET_NTB_PARAMETERS is required */
346         }
347
348         /* set CRC Mode */
349         if (cdc_ncm_flags(dev) & USB_CDC_NCM_NCAP_CRC_MODE) {
350                 dev_dbg(&dev->intf->dev, "Setting CRC mode off\n");
351                 err = usbnet_write_cmd(dev, USB_CDC_SET_CRC_MODE,
352                                        USB_TYPE_CLASS | USB_DIR_OUT
353                                        | USB_RECIP_INTERFACE,
354                                        USB_CDC_NCM_CRC_NOT_APPENDED,
355                                        iface_no, NULL, 0);
356                 if (err < 0)
357                         dev_err(&dev->intf->dev, "SET_CRC_MODE failed\n");
358         }
359
360         /* set NTB format, if both formats are supported.
361          *
362          * "The host shall only send this command while the NCM Data
363          *  Interface is in alternate setting 0."
364          */
365         if (le16_to_cpu(ctx->ncm_parm.bmNtbFormatsSupported) &
366                                                 USB_CDC_NCM_NTB32_SUPPORTED) {
367                 dev_dbg(&dev->intf->dev, "Setting NTB format to 16-bit\n");
368                 err = usbnet_write_cmd(dev, USB_CDC_SET_NTB_FORMAT,
369                                        USB_TYPE_CLASS | USB_DIR_OUT
370                                        | USB_RECIP_INTERFACE,
371                                        USB_CDC_NCM_NTB16_FORMAT,
372                                        iface_no, NULL, 0);
373                 if (err < 0)
374                         dev_err(&dev->intf->dev, "SET_NTB_FORMAT failed\n");
375         }
376
377         /* set initial device values */
378         ctx->rx_max = le32_to_cpu(ctx->ncm_parm.dwNtbInMaxSize);
379         ctx->tx_max = le32_to_cpu(ctx->ncm_parm.dwNtbOutMaxSize);
380         ctx->tx_remainder = le16_to_cpu(ctx->ncm_parm.wNdpOutPayloadRemainder);
381         ctx->tx_modulus = le16_to_cpu(ctx->ncm_parm.wNdpOutDivisor);
382         ctx->tx_ndp_modulus = le16_to_cpu(ctx->ncm_parm.wNdpOutAlignment);
383         /* devices prior to NCM Errata shall set this field to zero */
384         ctx->tx_max_datagrams = le16_to_cpu(ctx->ncm_parm.wNtbOutMaxDatagrams);
385
386         dev_dbg(&dev->intf->dev,
387                 "dwNtbInMaxSize=%u dwNtbOutMaxSize=%u wNdpOutPayloadRemainder=%u wNdpOutDivisor=%u wNdpOutAlignment=%u wNtbOutMaxDatagrams=%u flags=0x%x\n",
388                 ctx->rx_max, ctx->tx_max, ctx->tx_remainder, ctx->tx_modulus,
389                 ctx->tx_ndp_modulus, ctx->tx_max_datagrams, cdc_ncm_flags(dev));
390
391         /* max count of tx datagrams */
392         if ((ctx->tx_max_datagrams == 0) ||
393                         (ctx->tx_max_datagrams > CDC_NCM_DPT_DATAGRAMS_MAX))
394                 ctx->tx_max_datagrams = CDC_NCM_DPT_DATAGRAMS_MAX;
395
396         /* set up maximum NDP size */
397         ctx->max_ndp_size = sizeof(struct usb_cdc_ncm_ndp16) + (ctx->tx_max_datagrams + 1) * sizeof(struct usb_cdc_ncm_dpe16);
398
399         /* initial coalescing timer interval */
400         ctx->timer_interval = CDC_NCM_TIMER_INTERVAL_USEC * NSEC_PER_USEC;
401
402         return 0;
403 }
404
405 /* set a new max datagram size */
406 static void cdc_ncm_set_dgram_size(struct usbnet *dev, int new_size)
407 {
408         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
409         u8 iface_no = ctx->control->cur_altsetting->desc.bInterfaceNumber;
410         __le16 max_datagram_size;
411         u16 mbim_mtu;
412         int err;
413
414         /* set default based on descriptors */
415         ctx->max_datagram_size = clamp_t(u32, new_size,
416                                          cdc_ncm_min_dgram_size(dev),
417                                          CDC_NCM_MAX_DATAGRAM_SIZE);
418
419         /* inform the device about the selected Max Datagram Size? */
420         if (!(cdc_ncm_flags(dev) & USB_CDC_NCM_NCAP_MAX_DATAGRAM_SIZE))
421                 goto out;
422
423         /* read current mtu value from device */
424         err = usbnet_read_cmd(dev, USB_CDC_GET_MAX_DATAGRAM_SIZE,
425                               USB_TYPE_CLASS | USB_DIR_IN | USB_RECIP_INTERFACE,
426                               0, iface_no, &max_datagram_size, 2);
427         if (err < 0) {
428                 dev_dbg(&dev->intf->dev, "GET_MAX_DATAGRAM_SIZE failed\n");
429                 goto out;
430         }
431
432         if (le16_to_cpu(max_datagram_size) == ctx->max_datagram_size)
433                 goto out;
434
435         max_datagram_size = cpu_to_le16(ctx->max_datagram_size);
436         err = usbnet_write_cmd(dev, USB_CDC_SET_MAX_DATAGRAM_SIZE,
437                                USB_TYPE_CLASS | USB_DIR_OUT | USB_RECIP_INTERFACE,
438                                0, iface_no, &max_datagram_size, 2);
439         if (err < 0)
440                 dev_dbg(&dev->intf->dev, "SET_MAX_DATAGRAM_SIZE failed\n");
441
442 out:
443         /* set MTU to max supported by the device if necessary */
444         dev->net->mtu = min_t(int, dev->net->mtu, ctx->max_datagram_size - cdc_ncm_eth_hlen(dev));
445
446         /* do not exceed operater preferred MTU */
447         if (ctx->mbim_extended_desc) {
448                 mbim_mtu = le16_to_cpu(ctx->mbim_extended_desc->wMTU);
449                 if (mbim_mtu != 0 && mbim_mtu < dev->net->mtu)
450                         dev->net->mtu = mbim_mtu;
451         }
452 }
453
454 static void cdc_ncm_fix_modulus(struct usbnet *dev)
455 {
456         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
457         u32 val;
458
459         /*
460          * verify that the structure alignment is:
461          * - power of two
462          * - not greater than the maximum transmit length
463          * - not less than four bytes
464          */
465         val = ctx->tx_ndp_modulus;
466
467         if ((val < USB_CDC_NCM_NDP_ALIGN_MIN_SIZE) ||
468             (val != ((-val) & val)) || (val >= ctx->tx_max)) {
469                 dev_dbg(&dev->intf->dev, "Using default alignment: 4 bytes\n");
470                 ctx->tx_ndp_modulus = USB_CDC_NCM_NDP_ALIGN_MIN_SIZE;
471         }
472
473         /*
474          * verify that the payload alignment is:
475          * - power of two
476          * - not greater than the maximum transmit length
477          * - not less than four bytes
478          */
479         val = ctx->tx_modulus;
480
481         if ((val < USB_CDC_NCM_NDP_ALIGN_MIN_SIZE) ||
482             (val != ((-val) & val)) || (val >= ctx->tx_max)) {
483                 dev_dbg(&dev->intf->dev, "Using default transmit modulus: 4 bytes\n");
484                 ctx->tx_modulus = USB_CDC_NCM_NDP_ALIGN_MIN_SIZE;
485         }
486
487         /* verify the payload remainder */
488         if (ctx->tx_remainder >= ctx->tx_modulus) {
489                 dev_dbg(&dev->intf->dev, "Using default transmit remainder: 0 bytes\n");
490                 ctx->tx_remainder = 0;
491         }
492
493         /* adjust TX-remainder according to NCM specification. */
494         ctx->tx_remainder = ((ctx->tx_remainder - cdc_ncm_eth_hlen(dev)) &
495                              (ctx->tx_modulus - 1));
496 }
497
498 static int cdc_ncm_setup(struct usbnet *dev)
499 {
500         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
501         u32 def_rx, def_tx;
502
503         /* be conservative when selecting intial buffer size to
504          * increase the number of hosts this will work for
505          */
506         def_rx = min_t(u32, CDC_NCM_NTB_DEF_SIZE_RX,
507                        le32_to_cpu(ctx->ncm_parm.dwNtbInMaxSize));
508         def_tx = min_t(u32, CDC_NCM_NTB_DEF_SIZE_TX,
509                        le32_to_cpu(ctx->ncm_parm.dwNtbOutMaxSize));
510
511         /* clamp rx_max and tx_max and inform device */
512         cdc_ncm_update_rxtx_max(dev, def_rx, def_tx);
513
514         /* sanitize the modulus and remainder values */
515         cdc_ncm_fix_modulus(dev);
516
517         /* set max datagram size */
518         cdc_ncm_set_dgram_size(dev, cdc_ncm_max_dgram_size(dev));
519         return 0;
520 }
521
522 static void
523 cdc_ncm_find_endpoints(struct usbnet *dev, struct usb_interface *intf)
524 {
525         struct usb_host_endpoint *e, *in = NULL, *out = NULL;
526         u8 ep;
527
528         for (ep = 0; ep < intf->cur_altsetting->desc.bNumEndpoints; ep++) {
529
530                 e = intf->cur_altsetting->endpoint + ep;
531                 switch (e->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) {
532                 case USB_ENDPOINT_XFER_INT:
533                         if (usb_endpoint_dir_in(&e->desc)) {
534                                 if (!dev->status)
535                                         dev->status = e;
536                         }
537                         break;
538
539                 case USB_ENDPOINT_XFER_BULK:
540                         if (usb_endpoint_dir_in(&e->desc)) {
541                                 if (!in)
542                                         in = e;
543                         } else {
544                                 if (!out)
545                                         out = e;
546                         }
547                         break;
548
549                 default:
550                         break;
551                 }
552         }
553         if (in && !dev->in)
554                 dev->in = usb_rcvbulkpipe(dev->udev,
555                                           in->desc.bEndpointAddress &
556                                           USB_ENDPOINT_NUMBER_MASK);
557         if (out && !dev->out)
558                 dev->out = usb_sndbulkpipe(dev->udev,
559                                            out->desc.bEndpointAddress &
560                                            USB_ENDPOINT_NUMBER_MASK);
561 }
562
563 static void cdc_ncm_free(struct cdc_ncm_ctx *ctx)
564 {
565         if (ctx == NULL)
566                 return;
567
568         if (ctx->tx_rem_skb != NULL) {
569                 dev_kfree_skb_any(ctx->tx_rem_skb);
570                 ctx->tx_rem_skb = NULL;
571         }
572
573         if (ctx->tx_curr_skb != NULL) {
574                 dev_kfree_skb_any(ctx->tx_curr_skb);
575                 ctx->tx_curr_skb = NULL;
576         }
577
578         kfree(ctx);
579 }
580
581 int cdc_ncm_bind_common(struct usbnet *dev, struct usb_interface *intf, u8 data_altsetting)
582 {
583         const struct usb_cdc_union_desc *union_desc = NULL;
584         struct cdc_ncm_ctx *ctx;
585         struct usb_driver *driver;
586         u8 *buf;
587         int len;
588         int temp;
589         u8 iface_no;
590
591         ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
592         if (!ctx)
593                 return -ENOMEM;
594
595         hrtimer_init(&ctx->tx_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
596         ctx->tx_timer.function = &cdc_ncm_tx_timer_cb;
597         ctx->bh.data = (unsigned long)dev;
598         ctx->bh.func = cdc_ncm_txpath_bh;
599         atomic_set(&ctx->stop, 0);
600         spin_lock_init(&ctx->mtx);
601
602         /* store ctx pointer in device data field */
603         dev->data[0] = (unsigned long)ctx;
604
605         /* only the control interface can be successfully probed */
606         ctx->control = intf;
607
608         /* get some pointers */
609         driver = driver_of(intf);
610         buf = intf->cur_altsetting->extra;
611         len = intf->cur_altsetting->extralen;
612
613         /* parse through descriptors associated with control interface */
614         while ((len > 0) && (buf[0] > 2) && (buf[0] <= len)) {
615
616                 if (buf[1] != USB_DT_CS_INTERFACE)
617                         goto advance;
618
619                 switch (buf[2]) {
620                 case USB_CDC_UNION_TYPE:
621                         if (buf[0] < sizeof(*union_desc))
622                                 break;
623
624                         union_desc = (const struct usb_cdc_union_desc *)buf;
625                         /* the master must be the interface we are probing */
626                         if (intf->cur_altsetting->desc.bInterfaceNumber !=
627                             union_desc->bMasterInterface0) {
628                                 dev_dbg(&intf->dev, "bogus CDC Union\n");
629                                 goto error;
630                         }
631                         ctx->data = usb_ifnum_to_if(dev->udev,
632                                                     union_desc->bSlaveInterface0);
633                         break;
634
635                 case USB_CDC_ETHERNET_TYPE:
636                         if (buf[0] < sizeof(*(ctx->ether_desc)))
637                                 break;
638
639                         ctx->ether_desc =
640                                         (const struct usb_cdc_ether_desc *)buf;
641                         break;
642
643                 case USB_CDC_NCM_TYPE:
644                         if (buf[0] < sizeof(*(ctx->func_desc)))
645                                 break;
646
647                         ctx->func_desc = (const struct usb_cdc_ncm_desc *)buf;
648                         break;
649
650                 case USB_CDC_MBIM_TYPE:
651                         if (buf[0] < sizeof(*(ctx->mbim_desc)))
652                                 break;
653
654                         ctx->mbim_desc = (const struct usb_cdc_mbim_desc *)buf;
655                         break;
656
657                 case USB_CDC_MBIM_EXTENDED_TYPE:
658                         if (buf[0] < sizeof(*(ctx->mbim_extended_desc)))
659                                 break;
660
661                         ctx->mbim_extended_desc =
662                                 (const struct usb_cdc_mbim_extended_desc *)buf;
663                         break;
664
665                 default:
666                         break;
667                 }
668 advance:
669                 /* advance to next descriptor */
670                 temp = buf[0];
671                 buf += temp;
672                 len -= temp;
673         }
674
675         /* some buggy devices have an IAD but no CDC Union */
676         if (!union_desc && intf->intf_assoc && intf->intf_assoc->bInterfaceCount == 2) {
677                 ctx->data = usb_ifnum_to_if(dev->udev, intf->cur_altsetting->desc.bInterfaceNumber + 1);
678                 dev_dbg(&intf->dev, "CDC Union missing - got slave from IAD\n");
679         }
680
681         /* check if we got everything */
682         if (!ctx->data) {
683                 dev_dbg(&intf->dev, "CDC Union missing and no IAD found\n");
684                 goto error;
685         }
686         if (cdc_ncm_comm_intf_is_mbim(intf->cur_altsetting)) {
687                 if (!ctx->mbim_desc) {
688                         dev_dbg(&intf->dev, "MBIM functional descriptor missing\n");
689                         goto error;
690                 }
691         } else {
692                 if (!ctx->ether_desc || !ctx->func_desc) {
693                         dev_dbg(&intf->dev, "NCM or ECM functional descriptors missing\n");
694                         goto error;
695                 }
696         }
697
698         /* claim data interface, if different from control */
699         if (ctx->data != ctx->control) {
700                 temp = usb_driver_claim_interface(driver, ctx->data, dev);
701                 if (temp) {
702                         dev_dbg(&intf->dev, "failed to claim data intf\n");
703                         goto error;
704                 }
705         }
706
707         iface_no = ctx->data->cur_altsetting->desc.bInterfaceNumber;
708
709         /* reset data interface */
710         temp = usb_set_interface(dev->udev, iface_no, 0);
711         if (temp) {
712                 dev_dbg(&intf->dev, "set interface failed\n");
713                 goto error2;
714         }
715
716         /* initialize basic device settings */
717         if (cdc_ncm_init(dev))
718                 goto error2;
719
720         /* configure data interface */
721         temp = usb_set_interface(dev->udev, iface_no, data_altsetting);
722         if (temp) {
723                 dev_dbg(&intf->dev, "set interface failed\n");
724                 goto error2;
725         }
726
727         cdc_ncm_find_endpoints(dev, ctx->data);
728         cdc_ncm_find_endpoints(dev, ctx->control);
729         if (!dev->in || !dev->out || !dev->status) {
730                 dev_dbg(&intf->dev, "failed to collect endpoints\n");
731                 goto error2;
732         }
733
734         usb_set_intfdata(ctx->data, dev);
735         usb_set_intfdata(ctx->control, dev);
736
737         if (ctx->ether_desc) {
738                 temp = usbnet_get_ethernet_addr(dev, ctx->ether_desc->iMACAddress);
739                 if (temp) {
740                         dev_dbg(&intf->dev, "failed to get mac address\n");
741                         goto error2;
742                 }
743                 dev_info(&intf->dev, "MAC-Address: %pM\n", dev->net->dev_addr);
744         }
745
746         /* finish setting up the device specific data */
747         cdc_ncm_setup(dev);
748
749         /* override ethtool_ops */
750         dev->net->ethtool_ops = &cdc_ncm_ethtool_ops;
751
752         return 0;
753
754 error2:
755         usb_set_intfdata(ctx->control, NULL);
756         usb_set_intfdata(ctx->data, NULL);
757         if (ctx->data != ctx->control)
758                 usb_driver_release_interface(driver, ctx->data);
759 error:
760         cdc_ncm_free((struct cdc_ncm_ctx *)dev->data[0]);
761         dev->data[0] = 0;
762         dev_info(&intf->dev, "bind() failure\n");
763         return -ENODEV;
764 }
765 EXPORT_SYMBOL_GPL(cdc_ncm_bind_common);
766
767 void cdc_ncm_unbind(struct usbnet *dev, struct usb_interface *intf)
768 {
769         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
770         struct usb_driver *driver = driver_of(intf);
771
772         if (ctx == NULL)
773                 return;         /* no setup */
774
775         atomic_set(&ctx->stop, 1);
776
777         if (hrtimer_active(&ctx->tx_timer))
778                 hrtimer_cancel(&ctx->tx_timer);
779
780         tasklet_kill(&ctx->bh);
781
782         /* handle devices with combined control and data interface */
783         if (ctx->control == ctx->data)
784                 ctx->data = NULL;
785
786         /* disconnect master --> disconnect slave */
787         if (intf == ctx->control && ctx->data) {
788                 usb_set_intfdata(ctx->data, NULL);
789                 usb_driver_release_interface(driver, ctx->data);
790                 ctx->data = NULL;
791
792         } else if (intf == ctx->data && ctx->control) {
793                 usb_set_intfdata(ctx->control, NULL);
794                 usb_driver_release_interface(driver, ctx->control);
795                 ctx->control = NULL;
796         }
797
798         usb_set_intfdata(intf, NULL);
799         cdc_ncm_free(ctx);
800 }
801 EXPORT_SYMBOL_GPL(cdc_ncm_unbind);
802
803 /* Return the number of the MBIM control interface altsetting iff it
804  * is preferred and available,
805  */
806 u8 cdc_ncm_select_altsetting(struct usb_interface *intf)
807 {
808         struct usb_host_interface *alt;
809
810         /* The MBIM spec defines a NCM compatible default altsetting,
811          * which we may have matched:
812          *
813          *  "Functions that implement both NCM 1.0 and MBIM (an
814          *   “NCM/MBIM function”) according to this recommendation
815          *   shall provide two alternate settings for the
816          *   Communication Interface.  Alternate setting 0, and the
817          *   associated class and endpoint descriptors, shall be
818          *   constructed according to the rules given for the
819          *   Communication Interface in section 5 of [USBNCM10].
820          *   Alternate setting 1, and the associated class and
821          *   endpoint descriptors, shall be constructed according to
822          *   the rules given in section 6 (USB Device Model) of this
823          *   specification."
824          */
825         if (intf->num_altsetting < 2)
826                 return intf->cur_altsetting->desc.bAlternateSetting;
827
828         if (prefer_mbim) {
829                 alt = usb_altnum_to_altsetting(intf, CDC_NCM_COMM_ALTSETTING_MBIM);
830                 if (alt && cdc_ncm_comm_intf_is_mbim(alt))
831                         return CDC_NCM_COMM_ALTSETTING_MBIM;
832         }
833         return CDC_NCM_COMM_ALTSETTING_NCM;
834 }
835 EXPORT_SYMBOL_GPL(cdc_ncm_select_altsetting);
836
837 static int cdc_ncm_bind(struct usbnet *dev, struct usb_interface *intf)
838 {
839         int ret;
840
841         /* MBIM backwards compatible function? */
842         if (cdc_ncm_select_altsetting(intf) != CDC_NCM_COMM_ALTSETTING_NCM)
843                 return -ENODEV;
844
845         /* The NCM data altsetting is fixed */
846         ret = cdc_ncm_bind_common(dev, intf, CDC_NCM_DATA_ALTSETTING_NCM);
847
848         /*
849          * We should get an event when network connection is "connected" or
850          * "disconnected". Set network connection in "disconnected" state
851          * (carrier is OFF) during attach, so the IP network stack does not
852          * start IPv6 negotiation and more.
853          */
854         usbnet_link_change(dev, 0, 0);
855         return ret;
856 }
857
858 static void cdc_ncm_align_tail(struct sk_buff *skb, size_t modulus, size_t remainder, size_t max)
859 {
860         size_t align = ALIGN(skb->len, modulus) - skb->len + remainder;
861
862         if (skb->len + align > max)
863                 align = max - skb->len;
864         if (align && skb_tailroom(skb) >= align)
865                 memset(skb_put(skb, align), 0, align);
866 }
867
868 /* return a pointer to a valid struct usb_cdc_ncm_ndp16 of type sign, possibly
869  * allocating a new one within skb
870  */
871 static struct usb_cdc_ncm_ndp16 *cdc_ncm_ndp(struct cdc_ncm_ctx *ctx, struct sk_buff *skb, __le32 sign, size_t reserve)
872 {
873         struct usb_cdc_ncm_ndp16 *ndp16 = NULL;
874         struct usb_cdc_ncm_nth16 *nth16 = (void *)skb->data;
875         size_t ndpoffset = le16_to_cpu(nth16->wNdpIndex);
876
877         /* follow the chain of NDPs, looking for a match */
878         while (ndpoffset) {
879                 ndp16 = (struct usb_cdc_ncm_ndp16 *)(skb->data + ndpoffset);
880                 if  (ndp16->dwSignature == sign)
881                         return ndp16;
882                 ndpoffset = le16_to_cpu(ndp16->wNextNdpIndex);
883         }
884
885         /* align new NDP */
886         cdc_ncm_align_tail(skb, ctx->tx_ndp_modulus, 0, ctx->tx_max);
887
888         /* verify that there is room for the NDP and the datagram (reserve) */
889         if ((ctx->tx_max - skb->len - reserve) < ctx->max_ndp_size)
890                 return NULL;
891
892         /* link to it */
893         if (ndp16)
894                 ndp16->wNextNdpIndex = cpu_to_le16(skb->len);
895         else
896                 nth16->wNdpIndex = cpu_to_le16(skb->len);
897
898         /* push a new empty NDP */
899         ndp16 = (struct usb_cdc_ncm_ndp16 *)memset(skb_put(skb, ctx->max_ndp_size), 0, ctx->max_ndp_size);
900         ndp16->dwSignature = sign;
901         ndp16->wLength = cpu_to_le16(sizeof(struct usb_cdc_ncm_ndp16) + sizeof(struct usb_cdc_ncm_dpe16));
902         return ndp16;
903 }
904
905 struct sk_buff *
906 cdc_ncm_fill_tx_frame(struct usbnet *dev, struct sk_buff *skb, __le32 sign)
907 {
908         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
909         struct usb_cdc_ncm_nth16 *nth16;
910         struct usb_cdc_ncm_ndp16 *ndp16;
911         struct sk_buff *skb_out;
912         u16 n = 0, index, ndplen;
913         u8 ready2send = 0;
914
915         /* if there is a remaining skb, it gets priority */
916         if (skb != NULL) {
917                 swap(skb, ctx->tx_rem_skb);
918                 swap(sign, ctx->tx_rem_sign);
919         } else {
920                 ready2send = 1;
921         }
922
923         /* check if we are resuming an OUT skb */
924         skb_out = ctx->tx_curr_skb;
925
926         /* allocate a new OUT skb */
927         if (!skb_out) {
928                 skb_out = alloc_skb(ctx->tx_max, GFP_ATOMIC);
929                 if (skb_out == NULL) {
930                         if (skb != NULL) {
931                                 dev_kfree_skb_any(skb);
932                                 dev->net->stats.tx_dropped++;
933                         }
934                         goto exit_no_skb;
935                 }
936                 /* fill out the initial 16-bit NTB header */
937                 nth16 = (struct usb_cdc_ncm_nth16 *)memset(skb_put(skb_out, sizeof(struct usb_cdc_ncm_nth16)), 0, sizeof(struct usb_cdc_ncm_nth16));
938                 nth16->dwSignature = cpu_to_le32(USB_CDC_NCM_NTH16_SIGN);
939                 nth16->wHeaderLength = cpu_to_le16(sizeof(struct usb_cdc_ncm_nth16));
940                 nth16->wSequence = cpu_to_le16(ctx->tx_seq++);
941
942                 /* count total number of frames in this NTB */
943                 ctx->tx_curr_frame_num = 0;
944
945                 /* recent payload counter for this skb_out */
946                 ctx->tx_curr_frame_payload = 0;
947         }
948
949         for (n = ctx->tx_curr_frame_num; n < ctx->tx_max_datagrams; n++) {
950                 /* send any remaining skb first */
951                 if (skb == NULL) {
952                         skb = ctx->tx_rem_skb;
953                         sign = ctx->tx_rem_sign;
954                         ctx->tx_rem_skb = NULL;
955
956                         /* check for end of skb */
957                         if (skb == NULL)
958                                 break;
959                 }
960
961                 /* get the appropriate NDP for this skb */
962                 ndp16 = cdc_ncm_ndp(ctx, skb_out, sign, skb->len + ctx->tx_modulus + ctx->tx_remainder);
963
964                 /* align beginning of next frame */
965                 cdc_ncm_align_tail(skb_out,  ctx->tx_modulus, ctx->tx_remainder, ctx->tx_max);
966
967                 /* check if we had enough room left for both NDP and frame */
968                 if (!ndp16 || skb_out->len + skb->len > ctx->tx_max) {
969                         if (n == 0) {
970                                 /* won't fit, MTU problem? */
971                                 dev_kfree_skb_any(skb);
972                                 skb = NULL;
973                                 dev->net->stats.tx_dropped++;
974                         } else {
975                                 /* no room for skb - store for later */
976                                 if (ctx->tx_rem_skb != NULL) {
977                                         dev_kfree_skb_any(ctx->tx_rem_skb);
978                                         dev->net->stats.tx_dropped++;
979                                 }
980                                 ctx->tx_rem_skb = skb;
981                                 ctx->tx_rem_sign = sign;
982                                 skb = NULL;
983                                 ready2send = 1;
984                                 ctx->tx_reason_ntb_full++;      /* count reason for transmitting */
985                         }
986                         break;
987                 }
988
989                 /* calculate frame number withing this NDP */
990                 ndplen = le16_to_cpu(ndp16->wLength);
991                 index = (ndplen - sizeof(struct usb_cdc_ncm_ndp16)) / sizeof(struct usb_cdc_ncm_dpe16) - 1;
992
993                 /* OK, add this skb */
994                 ndp16->dpe16[index].wDatagramLength = cpu_to_le16(skb->len);
995                 ndp16->dpe16[index].wDatagramIndex = cpu_to_le16(skb_out->len);
996                 ndp16->wLength = cpu_to_le16(ndplen + sizeof(struct usb_cdc_ncm_dpe16));
997                 memcpy(skb_put(skb_out, skb->len), skb->data, skb->len);
998                 ctx->tx_curr_frame_payload += skb->len; /* count real tx payload data */
999                 dev_kfree_skb_any(skb);
1000                 skb = NULL;
1001
1002                 /* send now if this NDP is full */
1003                 if (index >= CDC_NCM_DPT_DATAGRAMS_MAX) {
1004                         ready2send = 1;
1005                         ctx->tx_reason_ndp_full++;      /* count reason for transmitting */
1006                         break;
1007                 }
1008         }
1009
1010         /* free up any dangling skb */
1011         if (skb != NULL) {
1012                 dev_kfree_skb_any(skb);
1013                 skb = NULL;
1014                 dev->net->stats.tx_dropped++;
1015         }
1016
1017         ctx->tx_curr_frame_num = n;
1018
1019         if (n == 0) {
1020                 /* wait for more frames */
1021                 /* push variables */
1022                 ctx->tx_curr_skb = skb_out;
1023                 goto exit_no_skb;
1024
1025         } else if ((n < ctx->tx_max_datagrams) && (ready2send == 0) && (ctx->timer_interval > 0)) {
1026                 /* wait for more frames */
1027                 /* push variables */
1028                 ctx->tx_curr_skb = skb_out;
1029                 /* set the pending count */
1030                 if (n < CDC_NCM_RESTART_TIMER_DATAGRAM_CNT)
1031                         ctx->tx_timer_pending = CDC_NCM_TIMER_PENDING_CNT;
1032                 goto exit_no_skb;
1033
1034         } else {
1035                 if (n == ctx->tx_max_datagrams)
1036                         ctx->tx_reason_max_datagram++;  /* count reason for transmitting */
1037                 /* frame goes out */
1038                 /* variables will be reset at next call */
1039         }
1040
1041         /* If collected data size is less or equal ctx->min_tx_pkt
1042          * bytes, we send buffers as it is. If we get more data, it
1043          * would be more efficient for USB HS mobile device with DMA
1044          * engine to receive a full size NTB, than canceling DMA
1045          * transfer and receiving a short packet.
1046          *
1047          * This optimization support is pointless if we end up sending
1048          * a ZLP after full sized NTBs.
1049          */
1050         if (!(dev->driver_info->flags & FLAG_SEND_ZLP) &&
1051             skb_out->len > ctx->min_tx_pkt)
1052                 memset(skb_put(skb_out, ctx->tx_max - skb_out->len), 0,
1053                        ctx->tx_max - skb_out->len);
1054         else if (skb_out->len < ctx->tx_max && (skb_out->len % dev->maxpacket) == 0)
1055                 *skb_put(skb_out, 1) = 0;       /* force short packet */
1056
1057         /* set final frame length */
1058         nth16 = (struct usb_cdc_ncm_nth16 *)skb_out->data;
1059         nth16->wBlockLength = cpu_to_le16(skb_out->len);
1060
1061         /* return skb */
1062         ctx->tx_curr_skb = NULL;
1063         dev->net->stats.tx_packets += ctx->tx_curr_frame_num;
1064
1065         /* keep private stats: framing overhead and number of NTBs */
1066         ctx->tx_overhead += skb_out->len - ctx->tx_curr_frame_payload;
1067         ctx->tx_ntbs++;
1068
1069         /* usbnet has already counted all the framing overhead.
1070          * Adjust the stats so that the tx_bytes counter show real
1071          * payload data instead.
1072          */
1073         dev->net->stats.tx_bytes -= skb_out->len - ctx->tx_curr_frame_payload;
1074
1075         return skb_out;
1076
1077 exit_no_skb:
1078         /* Start timer, if there is a remaining non-empty skb */
1079         if (ctx->tx_curr_skb != NULL && n > 0)
1080                 cdc_ncm_tx_timeout_start(ctx);
1081         return NULL;
1082 }
1083 EXPORT_SYMBOL_GPL(cdc_ncm_fill_tx_frame);
1084
1085 static void cdc_ncm_tx_timeout_start(struct cdc_ncm_ctx *ctx)
1086 {
1087         /* start timer, if not already started */
1088         if (!(hrtimer_active(&ctx->tx_timer) || atomic_read(&ctx->stop)))
1089                 hrtimer_start(&ctx->tx_timer,
1090                                 ktime_set(0, ctx->timer_interval),
1091                                 HRTIMER_MODE_REL);
1092 }
1093
1094 static enum hrtimer_restart cdc_ncm_tx_timer_cb(struct hrtimer *timer)
1095 {
1096         struct cdc_ncm_ctx *ctx =
1097                         container_of(timer, struct cdc_ncm_ctx, tx_timer);
1098
1099         if (!atomic_read(&ctx->stop))
1100                 tasklet_schedule(&ctx->bh);
1101         return HRTIMER_NORESTART;
1102 }
1103
1104 static void cdc_ncm_txpath_bh(unsigned long param)
1105 {
1106         struct usbnet *dev = (struct usbnet *)param;
1107         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
1108
1109         spin_lock_bh(&ctx->mtx);
1110         if (ctx->tx_timer_pending != 0) {
1111                 ctx->tx_timer_pending--;
1112                 cdc_ncm_tx_timeout_start(ctx);
1113                 spin_unlock_bh(&ctx->mtx);
1114         } else if (dev->net != NULL) {
1115                 ctx->tx_reason_timeout++;       /* count reason for transmitting */
1116                 spin_unlock_bh(&ctx->mtx);
1117                 netif_tx_lock_bh(dev->net);
1118                 usbnet_start_xmit(NULL, dev->net);
1119                 netif_tx_unlock_bh(dev->net);
1120         } else {
1121                 spin_unlock_bh(&ctx->mtx);
1122         }
1123 }
1124
1125 struct sk_buff *
1126 cdc_ncm_tx_fixup(struct usbnet *dev, struct sk_buff *skb, gfp_t flags)
1127 {
1128         struct sk_buff *skb_out;
1129         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
1130
1131         /*
1132          * The Ethernet API we are using does not support transmitting
1133          * multiple Ethernet frames in a single call. This driver will
1134          * accumulate multiple Ethernet frames and send out a larger
1135          * USB frame when the USB buffer is full or when a single jiffies
1136          * timeout happens.
1137          */
1138         if (ctx == NULL)
1139                 goto error;
1140
1141         spin_lock_bh(&ctx->mtx);
1142         skb_out = cdc_ncm_fill_tx_frame(dev, skb, cpu_to_le32(USB_CDC_NCM_NDP16_NOCRC_SIGN));
1143         spin_unlock_bh(&ctx->mtx);
1144         return skb_out;
1145
1146 error:
1147         if (skb != NULL)
1148                 dev_kfree_skb_any(skb);
1149
1150         return NULL;
1151 }
1152 EXPORT_SYMBOL_GPL(cdc_ncm_tx_fixup);
1153
1154 /* verify NTB header and return offset of first NDP, or negative error */
1155 int cdc_ncm_rx_verify_nth16(struct cdc_ncm_ctx *ctx, struct sk_buff *skb_in)
1156 {
1157         struct usbnet *dev = netdev_priv(skb_in->dev);
1158         struct usb_cdc_ncm_nth16 *nth16;
1159         int len;
1160         int ret = -EINVAL;
1161
1162         if (ctx == NULL)
1163                 goto error;
1164
1165         if (skb_in->len < (sizeof(struct usb_cdc_ncm_nth16) +
1166                                         sizeof(struct usb_cdc_ncm_ndp16))) {
1167                 netif_dbg(dev, rx_err, dev->net, "frame too short\n");
1168                 goto error;
1169         }
1170
1171         nth16 = (struct usb_cdc_ncm_nth16 *)skb_in->data;
1172
1173         if (nth16->dwSignature != cpu_to_le32(USB_CDC_NCM_NTH16_SIGN)) {
1174                 netif_dbg(dev, rx_err, dev->net,
1175                           "invalid NTH16 signature <%#010x>\n",
1176                           le32_to_cpu(nth16->dwSignature));
1177                 goto error;
1178         }
1179
1180         len = le16_to_cpu(nth16->wBlockLength);
1181         if (len > ctx->rx_max) {
1182                 netif_dbg(dev, rx_err, dev->net,
1183                           "unsupported NTB block length %u/%u\n", len,
1184                           ctx->rx_max);
1185                 goto error;
1186         }
1187
1188         if ((ctx->rx_seq + 1) != le16_to_cpu(nth16->wSequence) &&
1189             (ctx->rx_seq || le16_to_cpu(nth16->wSequence)) &&
1190             !((ctx->rx_seq == 0xffff) && !le16_to_cpu(nth16->wSequence))) {
1191                 netif_dbg(dev, rx_err, dev->net,
1192                           "sequence number glitch prev=%d curr=%d\n",
1193                           ctx->rx_seq, le16_to_cpu(nth16->wSequence));
1194         }
1195         ctx->rx_seq = le16_to_cpu(nth16->wSequence);
1196
1197         ret = le16_to_cpu(nth16->wNdpIndex);
1198 error:
1199         return ret;
1200 }
1201 EXPORT_SYMBOL_GPL(cdc_ncm_rx_verify_nth16);
1202
1203 /* verify NDP header and return number of datagrams, or negative error */
1204 int cdc_ncm_rx_verify_ndp16(struct sk_buff *skb_in, int ndpoffset)
1205 {
1206         struct usbnet *dev = netdev_priv(skb_in->dev);
1207         struct usb_cdc_ncm_ndp16 *ndp16;
1208         int ret = -EINVAL;
1209
1210         if ((ndpoffset + sizeof(struct usb_cdc_ncm_ndp16)) > skb_in->len) {
1211                 netif_dbg(dev, rx_err, dev->net, "invalid NDP offset  <%u>\n",
1212                           ndpoffset);
1213                 goto error;
1214         }
1215         ndp16 = (struct usb_cdc_ncm_ndp16 *)(skb_in->data + ndpoffset);
1216
1217         if (le16_to_cpu(ndp16->wLength) < USB_CDC_NCM_NDP16_LENGTH_MIN) {
1218                 netif_dbg(dev, rx_err, dev->net, "invalid DPT16 length <%u>\n",
1219                           le16_to_cpu(ndp16->wLength));
1220                 goto error;
1221         }
1222
1223         ret = ((le16_to_cpu(ndp16->wLength) -
1224                                         sizeof(struct usb_cdc_ncm_ndp16)) /
1225                                         sizeof(struct usb_cdc_ncm_dpe16));
1226         ret--; /* we process NDP entries except for the last one */
1227
1228         if ((sizeof(struct usb_cdc_ncm_ndp16) +
1229              ret * (sizeof(struct usb_cdc_ncm_dpe16))) > skb_in->len) {
1230                 netif_dbg(dev, rx_err, dev->net, "Invalid nframes = %d\n", ret);
1231                 ret = -EINVAL;
1232         }
1233
1234 error:
1235         return ret;
1236 }
1237 EXPORT_SYMBOL_GPL(cdc_ncm_rx_verify_ndp16);
1238
1239 int cdc_ncm_rx_fixup(struct usbnet *dev, struct sk_buff *skb_in)
1240 {
1241         struct sk_buff *skb;
1242         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
1243         int len;
1244         int nframes;
1245         int x;
1246         int offset;
1247         struct usb_cdc_ncm_ndp16 *ndp16;
1248         struct usb_cdc_ncm_dpe16 *dpe16;
1249         int ndpoffset;
1250         int loopcount = 50; /* arbitrary max preventing infinite loop */
1251         u32 payload = 0;
1252
1253         ndpoffset = cdc_ncm_rx_verify_nth16(ctx, skb_in);
1254         if (ndpoffset < 0)
1255                 goto error;
1256
1257 next_ndp:
1258         nframes = cdc_ncm_rx_verify_ndp16(skb_in, ndpoffset);
1259         if (nframes < 0)
1260                 goto error;
1261
1262         ndp16 = (struct usb_cdc_ncm_ndp16 *)(skb_in->data + ndpoffset);
1263
1264         if (ndp16->dwSignature != cpu_to_le32(USB_CDC_NCM_NDP16_NOCRC_SIGN)) {
1265                 netif_dbg(dev, rx_err, dev->net,
1266                           "invalid DPT16 signature <%#010x>\n",
1267                           le32_to_cpu(ndp16->dwSignature));
1268                 goto err_ndp;
1269         }
1270         dpe16 = ndp16->dpe16;
1271
1272         for (x = 0; x < nframes; x++, dpe16++) {
1273                 offset = le16_to_cpu(dpe16->wDatagramIndex);
1274                 len = le16_to_cpu(dpe16->wDatagramLength);
1275
1276                 /*
1277                  * CDC NCM ch. 3.7
1278                  * All entries after first NULL entry are to be ignored
1279                  */
1280                 if ((offset == 0) || (len == 0)) {
1281                         if (!x)
1282                                 goto err_ndp; /* empty NTB */
1283                         break;
1284                 }
1285
1286                 /* sanity checking */
1287                 if (((offset + len) > skb_in->len) ||
1288                                 (len > ctx->rx_max) || (len < ETH_HLEN)) {
1289                         netif_dbg(dev, rx_err, dev->net,
1290                                   "invalid frame detected (ignored) offset[%u]=%u, length=%u, skb=%p\n",
1291                                   x, offset, len, skb_in);
1292                         if (!x)
1293                                 goto err_ndp;
1294                         break;
1295
1296                 } else {
1297                         /* create a fresh copy to reduce truesize */
1298                         skb = netdev_alloc_skb_ip_align(dev->net,  len);
1299                         if (!skb)
1300                                 goto error;
1301                         memcpy(skb_put(skb, len), skb_in->data + offset, len);
1302                         usbnet_skb_return(dev, skb);
1303                         payload += len; /* count payload bytes in this NTB */
1304                 }
1305         }
1306 err_ndp:
1307         /* are there more NDPs to process? */
1308         ndpoffset = le16_to_cpu(ndp16->wNextNdpIndex);
1309         if (ndpoffset && loopcount--)
1310                 goto next_ndp;
1311
1312         /* update stats */
1313         ctx->rx_overhead += skb_in->len - payload;
1314         ctx->rx_ntbs++;
1315
1316         return 1;
1317 error:
1318         return 0;
1319 }
1320 EXPORT_SYMBOL_GPL(cdc_ncm_rx_fixup);
1321
1322 static void
1323 cdc_ncm_speed_change(struct usbnet *dev,
1324                      struct usb_cdc_speed_change *data)
1325 {
1326         uint32_t rx_speed = le32_to_cpu(data->DLBitRRate);
1327         uint32_t tx_speed = le32_to_cpu(data->ULBitRate);
1328
1329         /*
1330          * Currently the USB-NET API does not support reporting the actual
1331          * device speed. Do print it instead.
1332          */
1333         if ((tx_speed > 1000000) && (rx_speed > 1000000)) {
1334                 netif_info(dev, link, dev->net,
1335                            "%u mbit/s downlink %u mbit/s uplink\n",
1336                            (unsigned int)(rx_speed / 1000000U),
1337                            (unsigned int)(tx_speed / 1000000U));
1338         } else {
1339                 netif_info(dev, link, dev->net,
1340                            "%u kbit/s downlink %u kbit/s uplink\n",
1341                            (unsigned int)(rx_speed / 1000U),
1342                            (unsigned int)(tx_speed / 1000U));
1343         }
1344 }
1345
1346 static void cdc_ncm_status(struct usbnet *dev, struct urb *urb)
1347 {
1348         struct cdc_ncm_ctx *ctx;
1349         struct usb_cdc_notification *event;
1350
1351         ctx = (struct cdc_ncm_ctx *)dev->data[0];
1352
1353         if (urb->actual_length < sizeof(*event))
1354                 return;
1355
1356         /* test for split data in 8-byte chunks */
1357         if (test_and_clear_bit(EVENT_STS_SPLIT, &dev->flags)) {
1358                 cdc_ncm_speed_change(dev,
1359                       (struct usb_cdc_speed_change *)urb->transfer_buffer);
1360                 return;
1361         }
1362
1363         event = urb->transfer_buffer;
1364
1365         switch (event->bNotificationType) {
1366         case USB_CDC_NOTIFY_NETWORK_CONNECTION:
1367                 /*
1368                  * According to the CDC NCM specification ch.7.1
1369                  * USB_CDC_NOTIFY_NETWORK_CONNECTION notification shall be
1370                  * sent by device after USB_CDC_NOTIFY_SPEED_CHANGE.
1371                  */
1372                 netif_info(dev, link, dev->net,
1373                            "network connection: %sconnected\n",
1374                            !!event->wValue ? "" : "dis");
1375                 usbnet_link_change(dev, !!event->wValue, 0);
1376                 break;
1377
1378         case USB_CDC_NOTIFY_SPEED_CHANGE:
1379                 if (urb->actual_length < (sizeof(*event) +
1380                                         sizeof(struct usb_cdc_speed_change)))
1381                         set_bit(EVENT_STS_SPLIT, &dev->flags);
1382                 else
1383                         cdc_ncm_speed_change(dev,
1384                                              (struct usb_cdc_speed_change *)&event[1]);
1385                 break;
1386
1387         default:
1388                 dev_dbg(&dev->udev->dev,
1389                         "NCM: unexpected notification 0x%02x!\n",
1390                         event->bNotificationType);
1391                 break;
1392         }
1393 }
1394
1395 static const struct driver_info cdc_ncm_info = {
1396         .description = "CDC NCM",
1397         .flags = FLAG_POINTTOPOINT | FLAG_NO_SETINT | FLAG_MULTI_PACKET,
1398         .bind = cdc_ncm_bind,
1399         .unbind = cdc_ncm_unbind,
1400         .manage_power = usbnet_manage_power,
1401         .status = cdc_ncm_status,
1402         .rx_fixup = cdc_ncm_rx_fixup,
1403         .tx_fixup = cdc_ncm_tx_fixup,
1404 };
1405
1406 /* Same as cdc_ncm_info, but with FLAG_WWAN */
1407 static const struct driver_info wwan_info = {
1408         .description = "Mobile Broadband Network Device",
1409         .flags = FLAG_POINTTOPOINT | FLAG_NO_SETINT | FLAG_MULTI_PACKET
1410                         | FLAG_WWAN,
1411         .bind = cdc_ncm_bind,
1412         .unbind = cdc_ncm_unbind,
1413         .manage_power = usbnet_manage_power,
1414         .status = cdc_ncm_status,
1415         .rx_fixup = cdc_ncm_rx_fixup,
1416         .tx_fixup = cdc_ncm_tx_fixup,
1417 };
1418
1419 /* Same as wwan_info, but with FLAG_NOARP  */
1420 static const struct driver_info wwan_noarp_info = {
1421         .description = "Mobile Broadband Network Device (NO ARP)",
1422         .flags = FLAG_POINTTOPOINT | FLAG_NO_SETINT | FLAG_MULTI_PACKET
1423                         | FLAG_WWAN | FLAG_NOARP,
1424         .bind = cdc_ncm_bind,
1425         .unbind = cdc_ncm_unbind,
1426         .manage_power = usbnet_manage_power,
1427         .status = cdc_ncm_status,
1428         .rx_fixup = cdc_ncm_rx_fixup,
1429         .tx_fixup = cdc_ncm_tx_fixup,
1430 };
1431
1432 static const struct usb_device_id cdc_devs[] = {
1433         /* Ericsson MBM devices like F5521gw */
1434         { .match_flags = USB_DEVICE_ID_MATCH_INT_INFO
1435                 | USB_DEVICE_ID_MATCH_VENDOR,
1436           .idVendor = 0x0bdb,
1437           .bInterfaceClass = USB_CLASS_COMM,
1438           .bInterfaceSubClass = USB_CDC_SUBCLASS_NCM,
1439           .bInterfaceProtocol = USB_CDC_PROTO_NONE,
1440           .driver_info = (unsigned long) &wwan_info,
1441         },
1442
1443         /* Dell branded MBM devices like DW5550 */
1444         { .match_flags = USB_DEVICE_ID_MATCH_INT_INFO
1445                 | USB_DEVICE_ID_MATCH_VENDOR,
1446           .idVendor = 0x413c,
1447           .bInterfaceClass = USB_CLASS_COMM,
1448           .bInterfaceSubClass = USB_CDC_SUBCLASS_NCM,
1449           .bInterfaceProtocol = USB_CDC_PROTO_NONE,
1450           .driver_info = (unsigned long) &wwan_info,
1451         },
1452
1453         /* Toshiba branded MBM devices */
1454         { .match_flags = USB_DEVICE_ID_MATCH_INT_INFO
1455                 | USB_DEVICE_ID_MATCH_VENDOR,
1456           .idVendor = 0x0930,
1457           .bInterfaceClass = USB_CLASS_COMM,
1458           .bInterfaceSubClass = USB_CDC_SUBCLASS_NCM,
1459           .bInterfaceProtocol = USB_CDC_PROTO_NONE,
1460           .driver_info = (unsigned long) &wwan_info,
1461         },
1462
1463         /* tag Huawei devices as wwan */
1464         { USB_VENDOR_AND_INTERFACE_INFO(0x12d1,
1465                                         USB_CLASS_COMM,
1466                                         USB_CDC_SUBCLASS_NCM,
1467                                         USB_CDC_PROTO_NONE),
1468           .driver_info = (unsigned long)&wwan_info,
1469         },
1470
1471         /* Infineon(now Intel) HSPA Modem platform */
1472         { USB_DEVICE_AND_INTERFACE_INFO(0x1519, 0x0443,
1473                 USB_CLASS_COMM,
1474                 USB_CDC_SUBCLASS_NCM, USB_CDC_PROTO_NONE),
1475           .driver_info = (unsigned long)&wwan_noarp_info,
1476         },
1477
1478         /* Generic CDC-NCM devices */
1479         { USB_INTERFACE_INFO(USB_CLASS_COMM,
1480                 USB_CDC_SUBCLASS_NCM, USB_CDC_PROTO_NONE),
1481                 .driver_info = (unsigned long)&cdc_ncm_info,
1482         },
1483         {
1484         },
1485 };
1486 MODULE_DEVICE_TABLE(usb, cdc_devs);
1487
1488 static struct usb_driver cdc_ncm_driver = {
1489         .name = "cdc_ncm",
1490         .id_table = cdc_devs,
1491         .probe = usbnet_probe,
1492         .disconnect = usbnet_disconnect,
1493         .suspend = usbnet_suspend,
1494         .resume = usbnet_resume,
1495         .reset_resume = usbnet_resume,
1496         .supports_autosuspend = 1,
1497         .disable_hub_initiated_lpm = 1,
1498 };
1499
1500 module_usb_driver(cdc_ncm_driver);
1501
1502 MODULE_AUTHOR("Hans Petter Selasky");
1503 MODULE_DESCRIPTION("USB CDC NCM host driver");
1504 MODULE_LICENSE("Dual BSD/GPL");