GNU Linux-libre 4.14.330-gnu1
[releases.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/docs/devclass_docs/NCM10_012011.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/etherdevice.h>
45 #include <linux/ethtool.h>
46 #include <linux/workqueue.h>
47 #include <linux/mii.h>
48 #include <linux/crc32.h>
49 #include <linux/usb.h>
50 #include <linux/hrtimer.h>
51 #include <linux/atomic.h>
52 #include <linux/usb/usbnet.h>
53 #include <linux/usb/cdc.h>
54 #include <linux/usb/cdc_ncm.h>
55
56 #if IS_ENABLED(CONFIG_USB_NET_CDC_MBIM)
57 static bool prefer_mbim = true;
58 #else
59 static bool prefer_mbim;
60 #endif
61 module_param(prefer_mbim, bool, S_IRUGO | S_IWUSR);
62 MODULE_PARM_DESC(prefer_mbim, "Prefer MBIM setting on dual NCM/MBIM functions");
63
64 static void cdc_ncm_txpath_bh(unsigned long param);
65 static void cdc_ncm_tx_timeout_start(struct cdc_ncm_ctx *ctx);
66 static enum hrtimer_restart cdc_ncm_tx_timer_cb(struct hrtimer *hr_timer);
67 static struct usb_driver cdc_ncm_driver;
68
69 struct cdc_ncm_stats {
70         char stat_string[ETH_GSTRING_LEN];
71         int sizeof_stat;
72         int stat_offset;
73 };
74
75 #define CDC_NCM_STAT(str, m) { \
76                 .stat_string = str, \
77                 .sizeof_stat = sizeof(((struct cdc_ncm_ctx *)0)->m), \
78                 .stat_offset = offsetof(struct cdc_ncm_ctx, m) }
79 #define CDC_NCM_SIMPLE_STAT(m)  CDC_NCM_STAT(__stringify(m), m)
80
81 static const struct cdc_ncm_stats cdc_ncm_gstrings_stats[] = {
82         CDC_NCM_SIMPLE_STAT(tx_reason_ntb_full),
83         CDC_NCM_SIMPLE_STAT(tx_reason_ndp_full),
84         CDC_NCM_SIMPLE_STAT(tx_reason_timeout),
85         CDC_NCM_SIMPLE_STAT(tx_reason_max_datagram),
86         CDC_NCM_SIMPLE_STAT(tx_overhead),
87         CDC_NCM_SIMPLE_STAT(tx_ntbs),
88         CDC_NCM_SIMPLE_STAT(rx_overhead),
89         CDC_NCM_SIMPLE_STAT(rx_ntbs),
90 };
91
92 #define CDC_NCM_LOW_MEM_MAX_CNT 10
93
94 static int cdc_ncm_get_sset_count(struct net_device __always_unused *netdev, int sset)
95 {
96         switch (sset) {
97         case ETH_SS_STATS:
98                 return ARRAY_SIZE(cdc_ncm_gstrings_stats);
99         default:
100                 return -EOPNOTSUPP;
101         }
102 }
103
104 static void cdc_ncm_get_ethtool_stats(struct net_device *netdev,
105                                     struct ethtool_stats __always_unused *stats,
106                                     u64 *data)
107 {
108         struct usbnet *dev = netdev_priv(netdev);
109         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
110         int i;
111         char *p = NULL;
112
113         for (i = 0; i < ARRAY_SIZE(cdc_ncm_gstrings_stats); i++) {
114                 p = (char *)ctx + cdc_ncm_gstrings_stats[i].stat_offset;
115                 data[i] = (cdc_ncm_gstrings_stats[i].sizeof_stat == sizeof(u64)) ? *(u64 *)p : *(u32 *)p;
116         }
117 }
118
119 static void cdc_ncm_get_strings(struct net_device __always_unused *netdev, u32 stringset, u8 *data)
120 {
121         u8 *p = data;
122         int i;
123
124         switch (stringset) {
125         case ETH_SS_STATS:
126                 for (i = 0; i < ARRAY_SIZE(cdc_ncm_gstrings_stats); i++) {
127                         memcpy(p, cdc_ncm_gstrings_stats[i].stat_string, ETH_GSTRING_LEN);
128                         p += ETH_GSTRING_LEN;
129                 }
130         }
131 }
132
133 static void cdc_ncm_update_rxtx_max(struct usbnet *dev, u32 new_rx, u32 new_tx);
134
135 static const struct ethtool_ops cdc_ncm_ethtool_ops = {
136         .get_link          = usbnet_get_link,
137         .nway_reset        = usbnet_nway_reset,
138         .get_drvinfo       = usbnet_get_drvinfo,
139         .get_msglevel      = usbnet_get_msglevel,
140         .set_msglevel      = usbnet_set_msglevel,
141         .get_ts_info       = ethtool_op_get_ts_info,
142         .get_sset_count    = cdc_ncm_get_sset_count,
143         .get_strings       = cdc_ncm_get_strings,
144         .get_ethtool_stats = cdc_ncm_get_ethtool_stats,
145         .get_link_ksettings      = usbnet_get_link_ksettings,
146         .set_link_ksettings      = usbnet_set_link_ksettings,
147 };
148
149 static u32 cdc_ncm_check_rx_max(struct usbnet *dev, u32 new_rx)
150 {
151         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
152         u32 val, max, min;
153
154         /* clamp new_rx to sane values */
155         min = USB_CDC_NCM_NTB_MIN_IN_SIZE;
156         max = min_t(u32, CDC_NCM_NTB_MAX_SIZE_RX, le32_to_cpu(ctx->ncm_parm.dwNtbInMaxSize));
157
158         /* dwNtbInMaxSize spec violation? Use MIN size for both limits */
159         if (max < min) {
160                 dev_warn(&dev->intf->dev, "dwNtbInMaxSize=%u is too small. Using %u\n",
161                          le32_to_cpu(ctx->ncm_parm.dwNtbInMaxSize), min);
162                 max = min;
163         }
164
165         val = clamp_t(u32, new_rx, min, max);
166         if (val != new_rx)
167                 dev_dbg(&dev->intf->dev, "rx_max must be in the [%u, %u] range\n", min, max);
168
169         return val;
170 }
171
172 static u32 cdc_ncm_check_tx_max(struct usbnet *dev, u32 new_tx)
173 {
174         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
175         u32 val, max, min;
176
177         /* clamp new_tx to sane values */
178         if (ctx->is_ndp16)
179                 min = ctx->max_datagram_size + ctx->max_ndp_size + sizeof(struct usb_cdc_ncm_nth16);
180         else
181                 min = ctx->max_datagram_size + ctx->max_ndp_size + sizeof(struct usb_cdc_ncm_nth32);
182
183         if (le32_to_cpu(ctx->ncm_parm.dwNtbOutMaxSize) == 0)
184                 max = CDC_NCM_NTB_MAX_SIZE_TX; /* dwNtbOutMaxSize not set */
185         else
186                 max = clamp_t(u32, le32_to_cpu(ctx->ncm_parm.dwNtbOutMaxSize),
187                               USB_CDC_NCM_NTB_MIN_OUT_SIZE,
188                               CDC_NCM_NTB_MAX_SIZE_TX);
189
190         /* some devices set dwNtbOutMaxSize too low for the above default */
191         min = min(min, max);
192
193         val = clamp_t(u32, new_tx, min, max);
194         if (val != new_tx)
195                 dev_dbg(&dev->intf->dev, "tx_max must be in the [%u, %u] range\n", min, max);
196
197         return val;
198 }
199
200 static ssize_t cdc_ncm_show_min_tx_pkt(struct device *d, struct device_attribute *attr, char *buf)
201 {
202         struct usbnet *dev = netdev_priv(to_net_dev(d));
203         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
204
205         return sprintf(buf, "%u\n", ctx->min_tx_pkt);
206 }
207
208 static ssize_t cdc_ncm_show_rx_max(struct device *d, struct device_attribute *attr, char *buf)
209 {
210         struct usbnet *dev = netdev_priv(to_net_dev(d));
211         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
212
213         return sprintf(buf, "%u\n", ctx->rx_max);
214 }
215
216 static ssize_t cdc_ncm_show_tx_max(struct device *d, struct device_attribute *attr, char *buf)
217 {
218         struct usbnet *dev = netdev_priv(to_net_dev(d));
219         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
220
221         return sprintf(buf, "%u\n", ctx->tx_max);
222 }
223
224 static ssize_t cdc_ncm_show_tx_timer_usecs(struct device *d, struct device_attribute *attr, char *buf)
225 {
226         struct usbnet *dev = netdev_priv(to_net_dev(d));
227         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
228
229         return sprintf(buf, "%u\n", ctx->timer_interval / (u32)NSEC_PER_USEC);
230 }
231
232 static ssize_t cdc_ncm_store_min_tx_pkt(struct device *d,  struct device_attribute *attr, const char *buf, size_t len)
233 {
234         struct usbnet *dev = netdev_priv(to_net_dev(d));
235         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
236         unsigned long val;
237
238         /* no need to restrict values - anything from 0 to infinity is OK */
239         if (kstrtoul(buf, 0, &val))
240                 return -EINVAL;
241
242         ctx->min_tx_pkt = val;
243         return len;
244 }
245
246 static ssize_t cdc_ncm_store_rx_max(struct device *d,  struct device_attribute *attr, const char *buf, size_t len)
247 {
248         struct usbnet *dev = netdev_priv(to_net_dev(d));
249         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
250         unsigned long val;
251
252         if (kstrtoul(buf, 0, &val) || cdc_ncm_check_rx_max(dev, val) != val)
253                 return -EINVAL;
254
255         cdc_ncm_update_rxtx_max(dev, val, ctx->tx_max);
256         return len;
257 }
258
259 static ssize_t cdc_ncm_store_tx_max(struct device *d,  struct device_attribute *attr, const char *buf, size_t len)
260 {
261         struct usbnet *dev = netdev_priv(to_net_dev(d));
262         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
263         unsigned long val;
264
265         if (kstrtoul(buf, 0, &val) || cdc_ncm_check_tx_max(dev, val) != val)
266                 return -EINVAL;
267
268         cdc_ncm_update_rxtx_max(dev, ctx->rx_max, val);
269         return len;
270 }
271
272 static ssize_t cdc_ncm_store_tx_timer_usecs(struct device *d,  struct device_attribute *attr, const char *buf, size_t len)
273 {
274         struct usbnet *dev = netdev_priv(to_net_dev(d));
275         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
276         ssize_t ret;
277         unsigned long val;
278
279         ret = kstrtoul(buf, 0, &val);
280         if (ret)
281                 return ret;
282         if (val && (val < CDC_NCM_TIMER_INTERVAL_MIN || val > CDC_NCM_TIMER_INTERVAL_MAX))
283                 return -EINVAL;
284
285         spin_lock_bh(&ctx->mtx);
286         ctx->timer_interval = val * NSEC_PER_USEC;
287         if (!ctx->timer_interval)
288                 ctx->tx_timer_pending = 0;
289         spin_unlock_bh(&ctx->mtx);
290         return len;
291 }
292
293 static DEVICE_ATTR(min_tx_pkt, S_IRUGO | S_IWUSR, cdc_ncm_show_min_tx_pkt, cdc_ncm_store_min_tx_pkt);
294 static DEVICE_ATTR(rx_max, S_IRUGO | S_IWUSR, cdc_ncm_show_rx_max, cdc_ncm_store_rx_max);
295 static DEVICE_ATTR(tx_max, S_IRUGO | S_IWUSR, cdc_ncm_show_tx_max, cdc_ncm_store_tx_max);
296 static DEVICE_ATTR(tx_timer_usecs, S_IRUGO | S_IWUSR, cdc_ncm_show_tx_timer_usecs, cdc_ncm_store_tx_timer_usecs);
297
298 static ssize_t ndp_to_end_show(struct device *d, struct device_attribute *attr, char *buf)
299 {
300         struct usbnet *dev = netdev_priv(to_net_dev(d));
301         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
302
303         return sprintf(buf, "%c\n", ctx->drvflags & CDC_NCM_FLAG_NDP_TO_END ? 'Y' : 'N');
304 }
305
306 static ssize_t ndp_to_end_store(struct device *d,  struct device_attribute *attr, const char *buf, size_t len)
307 {
308         struct usbnet *dev = netdev_priv(to_net_dev(d));
309         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
310         bool enable;
311
312         if (strtobool(buf, &enable))
313                 return -EINVAL;
314
315         /* no change? */
316         if (enable == (ctx->drvflags & CDC_NCM_FLAG_NDP_TO_END))
317                 return len;
318
319         if (enable) {
320                 if (ctx->is_ndp16 && !ctx->delayed_ndp16) {
321                         ctx->delayed_ndp16 = kzalloc(ctx->max_ndp_size, GFP_KERNEL);
322                         if (!ctx->delayed_ndp16)
323                                 return -ENOMEM;
324                 }
325                 if (!ctx->is_ndp16 && !ctx->delayed_ndp32) {
326                         ctx->delayed_ndp32 = kzalloc(ctx->max_ndp_size, GFP_KERNEL);
327                         if (!ctx->delayed_ndp32)
328                                 return -ENOMEM;
329                 }
330         }
331
332         /* flush pending data before changing flag */
333         netif_tx_lock_bh(dev->net);
334         usbnet_start_xmit(NULL, dev->net);
335         spin_lock_bh(&ctx->mtx);
336         if (enable)
337                 ctx->drvflags |= CDC_NCM_FLAG_NDP_TO_END;
338         else
339                 ctx->drvflags &= ~CDC_NCM_FLAG_NDP_TO_END;
340         spin_unlock_bh(&ctx->mtx);
341         netif_tx_unlock_bh(dev->net);
342
343         return len;
344 }
345 static DEVICE_ATTR_RW(ndp_to_end);
346
347 #define NCM_PARM_ATTR(name, format, tocpu)                              \
348 static ssize_t cdc_ncm_show_##name(struct device *d, struct device_attribute *attr, char *buf) \
349 { \
350         struct usbnet *dev = netdev_priv(to_net_dev(d)); \
351         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0]; \
352         return sprintf(buf, format "\n", tocpu(ctx->ncm_parm.name));    \
353 } \
354 static DEVICE_ATTR(name, S_IRUGO, cdc_ncm_show_##name, NULL)
355
356 NCM_PARM_ATTR(bmNtbFormatsSupported, "0x%04x", le16_to_cpu);
357 NCM_PARM_ATTR(dwNtbInMaxSize, "%u", le32_to_cpu);
358 NCM_PARM_ATTR(wNdpInDivisor, "%u", le16_to_cpu);
359 NCM_PARM_ATTR(wNdpInPayloadRemainder, "%u", le16_to_cpu);
360 NCM_PARM_ATTR(wNdpInAlignment, "%u", le16_to_cpu);
361 NCM_PARM_ATTR(dwNtbOutMaxSize, "%u", le32_to_cpu);
362 NCM_PARM_ATTR(wNdpOutDivisor, "%u", le16_to_cpu);
363 NCM_PARM_ATTR(wNdpOutPayloadRemainder, "%u", le16_to_cpu);
364 NCM_PARM_ATTR(wNdpOutAlignment, "%u", le16_to_cpu);
365 NCM_PARM_ATTR(wNtbOutMaxDatagrams, "%u", le16_to_cpu);
366
367 static struct attribute *cdc_ncm_sysfs_attrs[] = {
368         &dev_attr_min_tx_pkt.attr,
369         &dev_attr_ndp_to_end.attr,
370         &dev_attr_rx_max.attr,
371         &dev_attr_tx_max.attr,
372         &dev_attr_tx_timer_usecs.attr,
373         &dev_attr_bmNtbFormatsSupported.attr,
374         &dev_attr_dwNtbInMaxSize.attr,
375         &dev_attr_wNdpInDivisor.attr,
376         &dev_attr_wNdpInPayloadRemainder.attr,
377         &dev_attr_wNdpInAlignment.attr,
378         &dev_attr_dwNtbOutMaxSize.attr,
379         &dev_attr_wNdpOutDivisor.attr,
380         &dev_attr_wNdpOutPayloadRemainder.attr,
381         &dev_attr_wNdpOutAlignment.attr,
382         &dev_attr_wNtbOutMaxDatagrams.attr,
383         NULL,
384 };
385
386 static const struct attribute_group cdc_ncm_sysfs_attr_group = {
387         .name = "cdc_ncm",
388         .attrs = cdc_ncm_sysfs_attrs,
389 };
390
391 /* handle rx_max and tx_max changes */
392 static void cdc_ncm_update_rxtx_max(struct usbnet *dev, u32 new_rx, u32 new_tx)
393 {
394         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
395         u8 iface_no = ctx->control->cur_altsetting->desc.bInterfaceNumber;
396         u32 val;
397
398         val = cdc_ncm_check_rx_max(dev, new_rx);
399
400         /* inform device about NTB input size changes */
401         if (val != ctx->rx_max) {
402                 __le32 dwNtbInMaxSize = cpu_to_le32(val);
403
404                 dev_info(&dev->intf->dev, "setting rx_max = %u\n", val);
405
406                 /* tell device to use new size */
407                 if (usbnet_write_cmd(dev, USB_CDC_SET_NTB_INPUT_SIZE,
408                                      USB_TYPE_CLASS | USB_DIR_OUT
409                                      | USB_RECIP_INTERFACE,
410                                      0, iface_no, &dwNtbInMaxSize, 4) < 0)
411                         dev_dbg(&dev->intf->dev, "Setting NTB Input Size failed\n");
412                 else
413                         ctx->rx_max = val;
414         }
415
416         /* usbnet use these values for sizing rx queues */
417         if (dev->rx_urb_size != ctx->rx_max) {
418                 dev->rx_urb_size = ctx->rx_max;
419                 if (netif_running(dev->net))
420                         usbnet_unlink_rx_urbs(dev);
421         }
422
423         val = cdc_ncm_check_tx_max(dev, new_tx);
424         if (val != ctx->tx_max)
425                 dev_info(&dev->intf->dev, "setting tx_max = %u\n", val);
426
427         /* Adding a pad byte here if necessary simplifies the handling
428          * in cdc_ncm_fill_tx_frame, making tx_max always represent
429          * the real skb max size.
430          *
431          * We cannot use dev->maxpacket here because this is called from
432          * .bind which is called before usbnet sets up dev->maxpacket
433          */
434         if (val != le32_to_cpu(ctx->ncm_parm.dwNtbOutMaxSize) &&
435             val % usb_maxpacket(dev->udev, dev->out, 1) == 0)
436                 val++;
437
438         /* we might need to flush any pending tx buffers if running */
439         if (netif_running(dev->net) && val > ctx->tx_max) {
440                 netif_tx_lock_bh(dev->net);
441                 usbnet_start_xmit(NULL, dev->net);
442                 /* make sure tx_curr_skb is reallocated if it was empty */
443                 if (ctx->tx_curr_skb) {
444                         dev_kfree_skb_any(ctx->tx_curr_skb);
445                         ctx->tx_curr_skb = NULL;
446                 }
447                 ctx->tx_max = val;
448                 netif_tx_unlock_bh(dev->net);
449         } else {
450                 ctx->tx_max = val;
451         }
452
453         dev->hard_mtu = ctx->tx_max;
454
455         /* max qlen depend on hard_mtu and rx_urb_size */
456         usbnet_update_max_qlen(dev);
457
458         /* never pad more than 3 full USB packets per transfer */
459         ctx->min_tx_pkt = clamp_t(u16, ctx->tx_max - 3 * usb_maxpacket(dev->udev, dev->out, 1),
460                                   CDC_NCM_MIN_TX_PKT, ctx->tx_max);
461 }
462
463 /* helpers for NCM and MBIM differences */
464 static u8 cdc_ncm_flags(struct usbnet *dev)
465 {
466         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
467
468         if (cdc_ncm_comm_intf_is_mbim(dev->intf->cur_altsetting) && ctx->mbim_desc)
469                 return ctx->mbim_desc->bmNetworkCapabilities;
470         if (ctx->func_desc)
471                 return ctx->func_desc->bmNetworkCapabilities;
472         return 0;
473 }
474
475 static int cdc_ncm_eth_hlen(struct usbnet *dev)
476 {
477         if (cdc_ncm_comm_intf_is_mbim(dev->intf->cur_altsetting))
478                 return 0;
479         return ETH_HLEN;
480 }
481
482 static u32 cdc_ncm_min_dgram_size(struct usbnet *dev)
483 {
484         if (cdc_ncm_comm_intf_is_mbim(dev->intf->cur_altsetting))
485                 return CDC_MBIM_MIN_DATAGRAM_SIZE;
486         return CDC_NCM_MIN_DATAGRAM_SIZE;
487 }
488
489 static u32 cdc_ncm_max_dgram_size(struct usbnet *dev)
490 {
491         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
492
493         if (cdc_ncm_comm_intf_is_mbim(dev->intf->cur_altsetting) && ctx->mbim_desc)
494                 return le16_to_cpu(ctx->mbim_desc->wMaxSegmentSize);
495         if (ctx->ether_desc)
496                 return le16_to_cpu(ctx->ether_desc->wMaxSegmentSize);
497         return CDC_NCM_MAX_DATAGRAM_SIZE;
498 }
499
500 /* initial one-time device setup.  MUST be called with the data interface
501  * in altsetting 0
502  */
503 static int cdc_ncm_init(struct usbnet *dev)
504 {
505         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
506         u8 iface_no = ctx->control->cur_altsetting->desc.bInterfaceNumber;
507         int err;
508
509         err = usbnet_read_cmd(dev, USB_CDC_GET_NTB_PARAMETERS,
510                               USB_TYPE_CLASS | USB_DIR_IN
511                               |USB_RECIP_INTERFACE,
512                               0, iface_no, &ctx->ncm_parm,
513                               sizeof(ctx->ncm_parm));
514         if (err < 0) {
515                 dev_err(&dev->intf->dev, "failed GET_NTB_PARAMETERS\n");
516                 return err; /* GET_NTB_PARAMETERS is required */
517         }
518
519         /* set CRC Mode */
520         if (cdc_ncm_flags(dev) & USB_CDC_NCM_NCAP_CRC_MODE) {
521                 dev_dbg(&dev->intf->dev, "Setting CRC mode off\n");
522                 err = usbnet_write_cmd(dev, USB_CDC_SET_CRC_MODE,
523                                        USB_TYPE_CLASS | USB_DIR_OUT
524                                        | USB_RECIP_INTERFACE,
525                                        USB_CDC_NCM_CRC_NOT_APPENDED,
526                                        iface_no, NULL, 0);
527                 if (err < 0)
528                         dev_err(&dev->intf->dev, "SET_CRC_MODE failed\n");
529         }
530
531         /* use ndp16 by default */
532         ctx->is_ndp16 = 1;
533
534         /* set NTB format, if both formats are supported.
535          *
536          * "The host shall only send this command while the NCM Data
537          *  Interface is in alternate setting 0."
538          */
539         if (le16_to_cpu(ctx->ncm_parm.bmNtbFormatsSupported) &
540                                                 USB_CDC_NCM_NTB32_SUPPORTED) {
541                 if (ctx->drvflags & CDC_NCM_FLAG_PREFER_NTB32) {
542                         ctx->is_ndp16 = 0;
543                         dev_dbg(&dev->intf->dev, "Setting NTB format to 32-bit\n");
544                         err = usbnet_write_cmd(dev, USB_CDC_SET_NTB_FORMAT,
545                                                USB_TYPE_CLASS | USB_DIR_OUT
546                                                | USB_RECIP_INTERFACE,
547                                                USB_CDC_NCM_NTB32_FORMAT,
548                                                iface_no, NULL, 0);
549                 } else {
550                         ctx->is_ndp16 = 1;
551                         dev_dbg(&dev->intf->dev, "Setting NTB format to 16-bit\n");
552                         err = usbnet_write_cmd(dev, USB_CDC_SET_NTB_FORMAT,
553                                                USB_TYPE_CLASS | USB_DIR_OUT
554                                                | USB_RECIP_INTERFACE,
555                                                USB_CDC_NCM_NTB16_FORMAT,
556                                                iface_no, NULL, 0);
557                 }
558                 if (err < 0) {
559                         ctx->is_ndp16 = 1;
560                         dev_err(&dev->intf->dev, "SET_NTB_FORMAT failed\n");
561                 }
562         }
563
564         /* set initial device values */
565         ctx->rx_max = le32_to_cpu(ctx->ncm_parm.dwNtbInMaxSize);
566         ctx->tx_max = le32_to_cpu(ctx->ncm_parm.dwNtbOutMaxSize);
567         ctx->tx_remainder = le16_to_cpu(ctx->ncm_parm.wNdpOutPayloadRemainder);
568         ctx->tx_modulus = le16_to_cpu(ctx->ncm_parm.wNdpOutDivisor);
569         ctx->tx_ndp_modulus = le16_to_cpu(ctx->ncm_parm.wNdpOutAlignment);
570         /* devices prior to NCM Errata shall set this field to zero */
571         ctx->tx_max_datagrams = le16_to_cpu(ctx->ncm_parm.wNtbOutMaxDatagrams);
572
573         dev_dbg(&dev->intf->dev,
574                 "dwNtbInMaxSize=%u dwNtbOutMaxSize=%u wNdpOutPayloadRemainder=%u wNdpOutDivisor=%u wNdpOutAlignment=%u wNtbOutMaxDatagrams=%u flags=0x%x\n",
575                 ctx->rx_max, ctx->tx_max, ctx->tx_remainder, ctx->tx_modulus,
576                 ctx->tx_ndp_modulus, ctx->tx_max_datagrams, cdc_ncm_flags(dev));
577
578         /* max count of tx datagrams */
579         if ((ctx->tx_max_datagrams == 0) ||
580                         (ctx->tx_max_datagrams > CDC_NCM_DPT_DATAGRAMS_MAX))
581                 ctx->tx_max_datagrams = CDC_NCM_DPT_DATAGRAMS_MAX;
582
583         /* set up maximum NDP size */
584         if (ctx->is_ndp16)
585                 ctx->max_ndp_size = sizeof(struct usb_cdc_ncm_ndp16) + (ctx->tx_max_datagrams + 1) * sizeof(struct usb_cdc_ncm_dpe16);
586         else
587                 ctx->max_ndp_size = sizeof(struct usb_cdc_ncm_ndp32) + (ctx->tx_max_datagrams + 1) * sizeof(struct usb_cdc_ncm_dpe32);
588
589         /* initial coalescing timer interval */
590         ctx->timer_interval = CDC_NCM_TIMER_INTERVAL_USEC * NSEC_PER_USEC;
591
592         return 0;
593 }
594
595 /* set a new max datagram size */
596 static void cdc_ncm_set_dgram_size(struct usbnet *dev, int new_size)
597 {
598         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
599         u8 iface_no = ctx->control->cur_altsetting->desc.bInterfaceNumber;
600         __le16 max_datagram_size;
601         u16 mbim_mtu;
602         int err;
603
604         /* set default based on descriptors */
605         ctx->max_datagram_size = clamp_t(u32, new_size,
606                                          cdc_ncm_min_dgram_size(dev),
607                                          CDC_NCM_MAX_DATAGRAM_SIZE);
608
609         /* inform the device about the selected Max Datagram Size? */
610         if (!(cdc_ncm_flags(dev) & USB_CDC_NCM_NCAP_MAX_DATAGRAM_SIZE))
611                 goto out;
612
613         /* read current mtu value from device */
614         err = usbnet_read_cmd(dev, USB_CDC_GET_MAX_DATAGRAM_SIZE,
615                               USB_TYPE_CLASS | USB_DIR_IN | USB_RECIP_INTERFACE,
616                               0, iface_no, &max_datagram_size, sizeof(max_datagram_size));
617         if (err != sizeof(max_datagram_size)) {
618                 dev_dbg(&dev->intf->dev, "GET_MAX_DATAGRAM_SIZE failed\n");
619                 goto out;
620         }
621
622         if (le16_to_cpu(max_datagram_size) == ctx->max_datagram_size)
623                 goto out;
624
625         max_datagram_size = cpu_to_le16(ctx->max_datagram_size);
626         err = usbnet_write_cmd(dev, USB_CDC_SET_MAX_DATAGRAM_SIZE,
627                                USB_TYPE_CLASS | USB_DIR_OUT | USB_RECIP_INTERFACE,
628                                0, iface_no, &max_datagram_size, sizeof(max_datagram_size));
629         if (err < 0)
630                 dev_dbg(&dev->intf->dev, "SET_MAX_DATAGRAM_SIZE failed\n");
631
632 out:
633         /* set MTU to max supported by the device if necessary */
634         dev->net->mtu = min_t(int, dev->net->mtu, ctx->max_datagram_size - cdc_ncm_eth_hlen(dev));
635
636         /* do not exceed operater preferred MTU */
637         if (ctx->mbim_extended_desc) {
638                 mbim_mtu = le16_to_cpu(ctx->mbim_extended_desc->wMTU);
639                 if (mbim_mtu != 0 && mbim_mtu < dev->net->mtu)
640                         dev->net->mtu = mbim_mtu;
641         }
642 }
643
644 static void cdc_ncm_fix_modulus(struct usbnet *dev)
645 {
646         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
647         u32 val;
648
649         /*
650          * verify that the structure alignment is:
651          * - power of two
652          * - not greater than the maximum transmit length
653          * - not less than four bytes
654          */
655         val = ctx->tx_ndp_modulus;
656
657         if ((val < USB_CDC_NCM_NDP_ALIGN_MIN_SIZE) ||
658             (val != ((-val) & val)) || (val >= ctx->tx_max)) {
659                 dev_dbg(&dev->intf->dev, "Using default alignment: 4 bytes\n");
660                 ctx->tx_ndp_modulus = USB_CDC_NCM_NDP_ALIGN_MIN_SIZE;
661         }
662
663         /*
664          * verify that the payload alignment is:
665          * - power of two
666          * - not greater than the maximum transmit length
667          * - not less than four bytes
668          */
669         val = ctx->tx_modulus;
670
671         if ((val < USB_CDC_NCM_NDP_ALIGN_MIN_SIZE) ||
672             (val != ((-val) & val)) || (val >= ctx->tx_max)) {
673                 dev_dbg(&dev->intf->dev, "Using default transmit modulus: 4 bytes\n");
674                 ctx->tx_modulus = USB_CDC_NCM_NDP_ALIGN_MIN_SIZE;
675         }
676
677         /* verify the payload remainder */
678         if (ctx->tx_remainder >= ctx->tx_modulus) {
679                 dev_dbg(&dev->intf->dev, "Using default transmit remainder: 0 bytes\n");
680                 ctx->tx_remainder = 0;
681         }
682
683         /* adjust TX-remainder according to NCM specification. */
684         ctx->tx_remainder = ((ctx->tx_remainder - cdc_ncm_eth_hlen(dev)) &
685                              (ctx->tx_modulus - 1));
686 }
687
688 static int cdc_ncm_setup(struct usbnet *dev)
689 {
690         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
691         u32 def_rx, def_tx;
692
693         /* be conservative when selecting intial buffer size to
694          * increase the number of hosts this will work for
695          */
696         def_rx = min_t(u32, CDC_NCM_NTB_DEF_SIZE_RX,
697                        le32_to_cpu(ctx->ncm_parm.dwNtbInMaxSize));
698         def_tx = min_t(u32, CDC_NCM_NTB_DEF_SIZE_TX,
699                        le32_to_cpu(ctx->ncm_parm.dwNtbOutMaxSize));
700
701         /* clamp rx_max and tx_max and inform device */
702         cdc_ncm_update_rxtx_max(dev, def_rx, def_tx);
703
704         /* sanitize the modulus and remainder values */
705         cdc_ncm_fix_modulus(dev);
706
707         /* set max datagram size */
708         cdc_ncm_set_dgram_size(dev, cdc_ncm_max_dgram_size(dev));
709         return 0;
710 }
711
712 static void
713 cdc_ncm_find_endpoints(struct usbnet *dev, struct usb_interface *intf)
714 {
715         struct usb_host_endpoint *e, *in = NULL, *out = NULL;
716         u8 ep;
717
718         for (ep = 0; ep < intf->cur_altsetting->desc.bNumEndpoints; ep++) {
719                 e = intf->cur_altsetting->endpoint + ep;
720
721                 /* ignore endpoints which cannot transfer data */
722                 if (!usb_endpoint_maxp(&e->desc))
723                         continue;
724
725                 switch (e->desc.bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) {
726                 case USB_ENDPOINT_XFER_INT:
727                         if (usb_endpoint_dir_in(&e->desc)) {
728                                 if (!dev->status)
729                                         dev->status = e;
730                         }
731                         break;
732
733                 case USB_ENDPOINT_XFER_BULK:
734                         if (usb_endpoint_dir_in(&e->desc)) {
735                                 if (!in)
736                                         in = e;
737                         } else {
738                                 if (!out)
739                                         out = e;
740                         }
741                         break;
742
743                 default:
744                         break;
745                 }
746         }
747         if (in && !dev->in)
748                 dev->in = usb_rcvbulkpipe(dev->udev,
749                                           in->desc.bEndpointAddress &
750                                           USB_ENDPOINT_NUMBER_MASK);
751         if (out && !dev->out)
752                 dev->out = usb_sndbulkpipe(dev->udev,
753                                            out->desc.bEndpointAddress &
754                                            USB_ENDPOINT_NUMBER_MASK);
755 }
756
757 static void cdc_ncm_free(struct cdc_ncm_ctx *ctx)
758 {
759         if (ctx == NULL)
760                 return;
761
762         if (ctx->tx_rem_skb != NULL) {
763                 dev_kfree_skb_any(ctx->tx_rem_skb);
764                 ctx->tx_rem_skb = NULL;
765         }
766
767         if (ctx->tx_curr_skb != NULL) {
768                 dev_kfree_skb_any(ctx->tx_curr_skb);
769                 ctx->tx_curr_skb = NULL;
770         }
771
772         if (ctx->is_ndp16)
773                 kfree(ctx->delayed_ndp16);
774         else
775                 kfree(ctx->delayed_ndp32);
776
777         kfree(ctx);
778 }
779
780 /* we need to override the usbnet change_mtu ndo for two reasons:
781  *  - respect the negotiated maximum datagram size
782  *  - avoid unwanted changes to rx and tx buffers
783  */
784 int cdc_ncm_change_mtu(struct net_device *net, int new_mtu)
785 {
786         struct usbnet *dev = netdev_priv(net);
787
788         net->mtu = new_mtu;
789         cdc_ncm_set_dgram_size(dev, new_mtu + cdc_ncm_eth_hlen(dev));
790
791         return 0;
792 }
793 EXPORT_SYMBOL_GPL(cdc_ncm_change_mtu);
794
795 static const struct net_device_ops cdc_ncm_netdev_ops = {
796         .ndo_open            = usbnet_open,
797         .ndo_stop            = usbnet_stop,
798         .ndo_start_xmit      = usbnet_start_xmit,
799         .ndo_tx_timeout      = usbnet_tx_timeout,
800         .ndo_get_stats64     = usbnet_get_stats64,
801         .ndo_change_mtu      = cdc_ncm_change_mtu,
802         .ndo_set_mac_address = eth_mac_addr,
803         .ndo_validate_addr   = eth_validate_addr,
804 };
805
806 int cdc_ncm_bind_common(struct usbnet *dev, struct usb_interface *intf, u8 data_altsetting, int drvflags)
807 {
808         struct cdc_ncm_ctx *ctx;
809         struct usb_driver *driver;
810         u8 *buf;
811         int len;
812         int temp;
813         u8 iface_no;
814         struct usb_cdc_parsed_header hdr;
815
816         ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
817         if (!ctx)
818                 return -ENOMEM;
819
820         hrtimer_init(&ctx->tx_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
821         ctx->tx_timer.function = &cdc_ncm_tx_timer_cb;
822         ctx->bh.data = (unsigned long)dev;
823         ctx->bh.func = cdc_ncm_txpath_bh;
824         atomic_set(&ctx->stop, 0);
825         spin_lock_init(&ctx->mtx);
826
827         /* store ctx pointer in device data field */
828         dev->data[0] = (unsigned long)ctx;
829
830         /* only the control interface can be successfully probed */
831         ctx->control = intf;
832
833         /* get some pointers */
834         driver = driver_of(intf);
835         buf = intf->cur_altsetting->extra;
836         len = intf->cur_altsetting->extralen;
837
838         /* parse through descriptors associated with control interface */
839         cdc_parse_cdc_header(&hdr, intf, buf, len);
840
841         if (hdr.usb_cdc_union_desc)
842                 ctx->data = usb_ifnum_to_if(dev->udev,
843                                             hdr.usb_cdc_union_desc->bSlaveInterface0);
844         ctx->ether_desc = hdr.usb_cdc_ether_desc;
845         ctx->func_desc = hdr.usb_cdc_ncm_desc;
846         ctx->mbim_desc = hdr.usb_cdc_mbim_desc;
847         ctx->mbim_extended_desc = hdr.usb_cdc_mbim_extended_desc;
848
849         /* some buggy devices have an IAD but no CDC Union */
850         if (!hdr.usb_cdc_union_desc && intf->intf_assoc && intf->intf_assoc->bInterfaceCount == 2) {
851                 ctx->data = usb_ifnum_to_if(dev->udev, intf->cur_altsetting->desc.bInterfaceNumber + 1);
852                 dev_dbg(&intf->dev, "CDC Union missing - got slave from IAD\n");
853         }
854
855         /* check if we got everything */
856         if (!ctx->data) {
857                 dev_dbg(&intf->dev, "CDC Union missing and no IAD found\n");
858                 goto error;
859         }
860         if (cdc_ncm_comm_intf_is_mbim(intf->cur_altsetting)) {
861                 if (!ctx->mbim_desc) {
862                         dev_dbg(&intf->dev, "MBIM functional descriptor missing\n");
863                         goto error;
864                 }
865         } else {
866                 if (!ctx->ether_desc || !ctx->func_desc) {
867                         dev_dbg(&intf->dev, "NCM or ECM functional descriptors missing\n");
868                         goto error;
869                 }
870         }
871
872         /* claim data interface, if different from control */
873         if (ctx->data != ctx->control) {
874                 temp = usb_driver_claim_interface(driver, ctx->data, dev);
875                 if (temp) {
876                         dev_dbg(&intf->dev, "failed to claim data intf\n");
877                         goto error;
878                 }
879         }
880
881         iface_no = ctx->data->cur_altsetting->desc.bInterfaceNumber;
882
883         /* Device-specific flags */
884         ctx->drvflags = drvflags;
885
886         /* Reset data interface. Some devices will not reset properly
887          * unless they are configured first.  Toggle the altsetting to
888          * force a reset.
889          * Some other devices do not work properly with this procedure
890          * that can be avoided using quirk CDC_MBIM_FLAG_AVOID_ALTSETTING_TOGGLE
891          */
892         if (!(ctx->drvflags & CDC_MBIM_FLAG_AVOID_ALTSETTING_TOGGLE))
893                 usb_set_interface(dev->udev, iface_no, data_altsetting);
894
895         temp = usb_set_interface(dev->udev, iface_no, 0);
896         if (temp) {
897                 dev_dbg(&intf->dev, "set interface failed\n");
898                 goto error2;
899         }
900
901         /* initialize basic device settings */
902         if (cdc_ncm_init(dev))
903                 goto error2;
904
905         /* Some firmwares need a pause here or they will silently fail
906          * to set up the interface properly.  This value was decided
907          * empirically on a Sierra Wireless MC7455 running 02.08.02.00
908          * firmware.
909          */
910         usleep_range(10000, 20000);
911
912         /* configure data interface */
913         temp = usb_set_interface(dev->udev, iface_no, data_altsetting);
914         if (temp) {
915                 dev_dbg(&intf->dev, "set interface failed\n");
916                 goto error2;
917         }
918
919         cdc_ncm_find_endpoints(dev, ctx->data);
920         cdc_ncm_find_endpoints(dev, ctx->control);
921         if (!dev->in || !dev->out || !dev->status) {
922                 dev_dbg(&intf->dev, "failed to collect endpoints\n");
923                 goto error2;
924         }
925
926         usb_set_intfdata(ctx->data, dev);
927         usb_set_intfdata(ctx->control, dev);
928
929         if (ctx->ether_desc) {
930                 temp = usbnet_get_ethernet_addr(dev, ctx->ether_desc->iMACAddress);
931                 if (temp) {
932                         dev_dbg(&intf->dev, "failed to get mac address\n");
933                         goto error2;
934                 }
935                 dev_info(&intf->dev, "MAC-Address: %pM\n", dev->net->dev_addr);
936         }
937
938         /* finish setting up the device specific data */
939         cdc_ncm_setup(dev);
940
941         /* Allocate the delayed NDP if needed. */
942         if (ctx->drvflags & CDC_NCM_FLAG_NDP_TO_END) {
943                 if (ctx->is_ndp16) {
944                         ctx->delayed_ndp16 = kzalloc(ctx->max_ndp_size, GFP_KERNEL);
945                         if (!ctx->delayed_ndp16)
946                                 goto error2;
947                 } else {
948                         ctx->delayed_ndp32 = kzalloc(ctx->max_ndp_size, GFP_KERNEL);
949                         if (!ctx->delayed_ndp32)
950                                 goto error2;
951                 }
952                 dev_info(&intf->dev, "NDP will be placed at end of frame for this device.");
953         }
954
955         /* override ethtool_ops */
956         dev->net->ethtool_ops = &cdc_ncm_ethtool_ops;
957
958         /* add our sysfs attrs */
959         dev->net->sysfs_groups[0] = &cdc_ncm_sysfs_attr_group;
960
961         /* must handle MTU changes */
962         dev->net->netdev_ops = &cdc_ncm_netdev_ops;
963         dev->net->max_mtu = cdc_ncm_max_dgram_size(dev) - cdc_ncm_eth_hlen(dev);
964
965         return 0;
966
967 error2:
968         usb_set_intfdata(ctx->control, NULL);
969         usb_set_intfdata(ctx->data, NULL);
970         if (ctx->data != ctx->control)
971                 usb_driver_release_interface(driver, ctx->data);
972 error:
973         cdc_ncm_free((struct cdc_ncm_ctx *)dev->data[0]);
974         dev->data[0] = 0;
975         dev_info(&intf->dev, "bind() failure\n");
976         return -ENODEV;
977 }
978 EXPORT_SYMBOL_GPL(cdc_ncm_bind_common);
979
980 void cdc_ncm_unbind(struct usbnet *dev, struct usb_interface *intf)
981 {
982         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
983         struct usb_driver *driver = driver_of(intf);
984
985         if (ctx == NULL)
986                 return;         /* no setup */
987
988         atomic_set(&ctx->stop, 1);
989
990         if (hrtimer_active(&ctx->tx_timer))
991                 hrtimer_cancel(&ctx->tx_timer);
992
993         tasklet_kill(&ctx->bh);
994
995         /* handle devices with combined control and data interface */
996         if (ctx->control == ctx->data)
997                 ctx->data = NULL;
998
999         /* disconnect master --> disconnect slave */
1000         if (intf == ctx->control && ctx->data) {
1001                 usb_set_intfdata(ctx->data, NULL);
1002                 usb_driver_release_interface(driver, ctx->data);
1003                 ctx->data = NULL;
1004
1005         } else if (intf == ctx->data && ctx->control) {
1006                 usb_set_intfdata(ctx->control, NULL);
1007                 usb_driver_release_interface(driver, ctx->control);
1008                 ctx->control = NULL;
1009         }
1010
1011         usb_set_intfdata(intf, NULL);
1012         cdc_ncm_free(ctx);
1013 }
1014 EXPORT_SYMBOL_GPL(cdc_ncm_unbind);
1015
1016 /* Return the number of the MBIM control interface altsetting iff it
1017  * is preferred and available,
1018  */
1019 u8 cdc_ncm_select_altsetting(struct usb_interface *intf)
1020 {
1021         struct usb_host_interface *alt;
1022
1023         /* The MBIM spec defines a NCM compatible default altsetting,
1024          * which we may have matched:
1025          *
1026          *  "Functions that implement both NCM 1.0 and MBIM (an
1027          *   “NCM/MBIM function”) according to this recommendation
1028          *   shall provide two alternate settings for the
1029          *   Communication Interface.  Alternate setting 0, and the
1030          *   associated class and endpoint descriptors, shall be
1031          *   constructed according to the rules given for the
1032          *   Communication Interface in section 5 of [USBNCM10].
1033          *   Alternate setting 1, and the associated class and
1034          *   endpoint descriptors, shall be constructed according to
1035          *   the rules given in section 6 (USB Device Model) of this
1036          *   specification."
1037          */
1038         if (intf->num_altsetting < 2)
1039                 return intf->cur_altsetting->desc.bAlternateSetting;
1040
1041         if (prefer_mbim) {
1042                 alt = usb_altnum_to_altsetting(intf, CDC_NCM_COMM_ALTSETTING_MBIM);
1043                 if (alt && cdc_ncm_comm_intf_is_mbim(alt))
1044                         return CDC_NCM_COMM_ALTSETTING_MBIM;
1045         }
1046         return CDC_NCM_COMM_ALTSETTING_NCM;
1047 }
1048 EXPORT_SYMBOL_GPL(cdc_ncm_select_altsetting);
1049
1050 static int cdc_ncm_bind(struct usbnet *dev, struct usb_interface *intf)
1051 {
1052         /* MBIM backwards compatible function? */
1053         if (cdc_ncm_select_altsetting(intf) != CDC_NCM_COMM_ALTSETTING_NCM)
1054                 return -ENODEV;
1055
1056         /* The NCM data altsetting is fixed, so we hard-coded it.
1057          * Additionally, generic NCM devices are assumed to accept arbitrarily
1058          * placed NDP.
1059          */
1060         return cdc_ncm_bind_common(dev, intf, CDC_NCM_DATA_ALTSETTING_NCM, 0);
1061 }
1062
1063 static void cdc_ncm_align_tail(struct sk_buff *skb, size_t modulus, size_t remainder, size_t max)
1064 {
1065         size_t align = ALIGN(skb->len, modulus) - skb->len + remainder;
1066
1067         if (skb->len + align > max)
1068                 align = max - skb->len;
1069         if (align && skb_tailroom(skb) >= align)
1070                 skb_put_zero(skb, align);
1071 }
1072
1073 /* return a pointer to a valid struct usb_cdc_ncm_ndp16 of type sign, possibly
1074  * allocating a new one within skb
1075  */
1076 static struct usb_cdc_ncm_ndp16 *cdc_ncm_ndp16(struct cdc_ncm_ctx *ctx, struct sk_buff *skb, __le32 sign, size_t reserve)
1077 {
1078         struct usb_cdc_ncm_ndp16 *ndp16 = NULL;
1079         struct usb_cdc_ncm_nth16 *nth16 = (void *)skb->data;
1080         size_t ndpoffset = le16_to_cpu(nth16->wNdpIndex);
1081
1082         /* If NDP should be moved to the end of the NCM package, we can't follow the
1083         * NTH16 header as we would normally do. NDP isn't written to the SKB yet, and
1084         * the wNdpIndex field in the header is actually not consistent with reality. It will be later.
1085         */
1086         if (ctx->drvflags & CDC_NCM_FLAG_NDP_TO_END) {
1087                 if (ctx->delayed_ndp16->dwSignature == sign)
1088                         return ctx->delayed_ndp16;
1089
1090                 /* We can only push a single NDP to the end. Return
1091                  * NULL to send what we've already got and queue this
1092                  * skb for later.
1093                  */
1094                 else if (ctx->delayed_ndp16->dwSignature)
1095                         return NULL;
1096         }
1097
1098         /* follow the chain of NDPs, looking for a match */
1099         while (ndpoffset) {
1100                 ndp16 = (struct usb_cdc_ncm_ndp16 *)(skb->data + ndpoffset);
1101                 if  (ndp16->dwSignature == sign)
1102                         return ndp16;
1103                 ndpoffset = le16_to_cpu(ndp16->wNextNdpIndex);
1104         }
1105
1106         /* align new NDP */
1107         if (!(ctx->drvflags & CDC_NCM_FLAG_NDP_TO_END))
1108                 cdc_ncm_align_tail(skb, ctx->tx_ndp_modulus, 0, ctx->tx_curr_size);
1109
1110         /* verify that there is room for the NDP and the datagram (reserve) */
1111         if ((ctx->tx_curr_size - skb->len - reserve) < ctx->max_ndp_size)
1112                 return NULL;
1113
1114         /* link to it */
1115         if (ndp16)
1116                 ndp16->wNextNdpIndex = cpu_to_le16(skb->len);
1117         else
1118                 nth16->wNdpIndex = cpu_to_le16(skb->len);
1119
1120         /* push a new empty NDP */
1121         if (!(ctx->drvflags & CDC_NCM_FLAG_NDP_TO_END))
1122                 ndp16 = skb_put_zero(skb, ctx->max_ndp_size);
1123         else
1124                 ndp16 = ctx->delayed_ndp16;
1125
1126         ndp16->dwSignature = sign;
1127         ndp16->wLength = cpu_to_le16(sizeof(struct usb_cdc_ncm_ndp16) + sizeof(struct usb_cdc_ncm_dpe16));
1128         return ndp16;
1129 }
1130
1131 static struct usb_cdc_ncm_ndp32 *cdc_ncm_ndp32(struct cdc_ncm_ctx *ctx, struct sk_buff *skb, __le32 sign, size_t reserve)
1132 {
1133         struct usb_cdc_ncm_ndp32 *ndp32 = NULL;
1134         struct usb_cdc_ncm_nth32 *nth32 = (void *)skb->data;
1135         size_t ndpoffset = le32_to_cpu(nth32->dwNdpIndex);
1136
1137         /* If NDP should be moved to the end of the NCM package, we can't follow the
1138          * NTH32 header as we would normally do. NDP isn't written to the SKB yet, and
1139          * the wNdpIndex field in the header is actually not consistent with reality. It will be later.
1140          */
1141         if (ctx->drvflags & CDC_NCM_FLAG_NDP_TO_END) {
1142                 if (ctx->delayed_ndp32->dwSignature == sign)
1143                         return ctx->delayed_ndp32;
1144
1145                 /* We can only push a single NDP to the end. Return
1146                  * NULL to send what we've already got and queue this
1147                  * skb for later.
1148                  */
1149                 else if (ctx->delayed_ndp32->dwSignature)
1150                         return NULL;
1151         }
1152
1153         /* follow the chain of NDPs, looking for a match */
1154         while (ndpoffset) {
1155                 ndp32 = (struct usb_cdc_ncm_ndp32 *)(skb->data + ndpoffset);
1156                 if  (ndp32->dwSignature == sign)
1157                         return ndp32;
1158                 ndpoffset = le32_to_cpu(ndp32->dwNextNdpIndex);
1159         }
1160
1161         /* align new NDP */
1162         if (!(ctx->drvflags & CDC_NCM_FLAG_NDP_TO_END))
1163                 cdc_ncm_align_tail(skb, ctx->tx_ndp_modulus, 0, ctx->tx_curr_size);
1164
1165         /* verify that there is room for the NDP and the datagram (reserve) */
1166         if ((ctx->tx_curr_size - skb->len - reserve) < ctx->max_ndp_size)
1167                 return NULL;
1168
1169         /* link to it */
1170         if (ndp32)
1171                 ndp32->dwNextNdpIndex = cpu_to_le32(skb->len);
1172         else
1173                 nth32->dwNdpIndex = cpu_to_le32(skb->len);
1174
1175         /* push a new empty NDP */
1176         if (!(ctx->drvflags & CDC_NCM_FLAG_NDP_TO_END))
1177                 ndp32 = skb_put_zero(skb, ctx->max_ndp_size);
1178         else
1179                 ndp32 = ctx->delayed_ndp32;
1180
1181         ndp32->dwSignature = sign;
1182         ndp32->wLength = cpu_to_le16(sizeof(struct usb_cdc_ncm_ndp32) + sizeof(struct usb_cdc_ncm_dpe32));
1183         return ndp32;
1184 }
1185
1186 struct sk_buff *
1187 cdc_ncm_fill_tx_frame(struct usbnet *dev, struct sk_buff *skb, __le32 sign)
1188 {
1189         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
1190         union {
1191                 struct usb_cdc_ncm_nth16 *nth16;
1192                 struct usb_cdc_ncm_nth32 *nth32;
1193         } nth;
1194         union {
1195                 struct usb_cdc_ncm_ndp16 *ndp16;
1196                 struct usb_cdc_ncm_ndp32 *ndp32;
1197         } ndp;
1198         struct sk_buff *skb_out;
1199         u16 n = 0, index, ndplen;
1200         u8 ready2send = 0;
1201         u32 delayed_ndp_size;
1202         size_t padding_count;
1203
1204         /* When our NDP gets written in cdc_ncm_ndp(), then skb_out->len gets updated
1205          * accordingly. Otherwise, we should check here.
1206          */
1207         if (ctx->drvflags & CDC_NCM_FLAG_NDP_TO_END)
1208                 delayed_ndp_size = ctx->max_ndp_size +
1209                         max_t(u32,
1210                               ctx->tx_ndp_modulus,
1211                               ctx->tx_modulus + ctx->tx_remainder) - 1;
1212         else
1213                 delayed_ndp_size = 0;
1214
1215         /* if there is a remaining skb, it gets priority */
1216         if (skb != NULL) {
1217                 swap(skb, ctx->tx_rem_skb);
1218                 swap(sign, ctx->tx_rem_sign);
1219         } else {
1220                 ready2send = 1;
1221         }
1222
1223         /* check if we are resuming an OUT skb */
1224         skb_out = ctx->tx_curr_skb;
1225
1226         /* allocate a new OUT skb */
1227         if (!skb_out) {
1228                 if (ctx->tx_low_mem_val == 0) {
1229                         ctx->tx_curr_size = ctx->tx_max;
1230                         skb_out = alloc_skb(ctx->tx_curr_size, GFP_ATOMIC);
1231                         /* If the memory allocation fails we will wait longer
1232                          * each time before attempting another full size
1233                          * allocation again to not overload the system
1234                          * further.
1235                          */
1236                         if (skb_out == NULL) {
1237                                 /* If even the smallest allocation fails, abort. */
1238                                 if (ctx->tx_curr_size == USB_CDC_NCM_NTB_MIN_OUT_SIZE)
1239                                         goto alloc_failed;
1240                                 ctx->tx_low_mem_max_cnt = min(ctx->tx_low_mem_max_cnt + 1,
1241                                                               (unsigned)CDC_NCM_LOW_MEM_MAX_CNT);
1242                                 ctx->tx_low_mem_val = ctx->tx_low_mem_max_cnt;
1243                         }
1244                 }
1245                 if (skb_out == NULL) {
1246                         /* See if a very small allocation is possible.
1247                          * We will send this packet immediately and hope
1248                          * that there is more memory available later.
1249                          */
1250                         if (skb)
1251                                 ctx->tx_curr_size = max(skb->len,
1252                                         (u32)USB_CDC_NCM_NTB_MIN_OUT_SIZE);
1253                         else
1254                                 ctx->tx_curr_size = USB_CDC_NCM_NTB_MIN_OUT_SIZE;
1255                         skb_out = alloc_skb(ctx->tx_curr_size, GFP_ATOMIC);
1256
1257                         /* No allocation possible so we will abort */
1258                         if (!skb_out)
1259                                 goto alloc_failed;
1260                         ctx->tx_low_mem_val--;
1261                 }
1262                 if (ctx->is_ndp16) {
1263                         /* fill out the initial 16-bit NTB header */
1264                         nth.nth16 = skb_put_zero(skb_out, sizeof(struct usb_cdc_ncm_nth16));
1265                         nth.nth16->dwSignature = cpu_to_le32(USB_CDC_NCM_NTH16_SIGN);
1266                         nth.nth16->wHeaderLength = cpu_to_le16(sizeof(struct usb_cdc_ncm_nth16));
1267                         nth.nth16->wSequence = cpu_to_le16(ctx->tx_seq++);
1268                 } else {
1269                         /* fill out the initial 32-bit NTB header */
1270                         nth.nth32 = skb_put_zero(skb_out, sizeof(struct usb_cdc_ncm_nth32));
1271                         nth.nth32->dwSignature = cpu_to_le32(USB_CDC_NCM_NTH32_SIGN);
1272                         nth.nth32->wHeaderLength = cpu_to_le16(sizeof(struct usb_cdc_ncm_nth32));
1273                         nth.nth32->wSequence = cpu_to_le16(ctx->tx_seq++);
1274                 }
1275
1276                 /* count total number of frames in this NTB */
1277                 ctx->tx_curr_frame_num = 0;
1278
1279                 /* recent payload counter for this skb_out */
1280                 ctx->tx_curr_frame_payload = 0;
1281         }
1282
1283         for (n = ctx->tx_curr_frame_num; n < ctx->tx_max_datagrams; n++) {
1284                 /* send any remaining skb first */
1285                 if (skb == NULL) {
1286                         skb = ctx->tx_rem_skb;
1287                         sign = ctx->tx_rem_sign;
1288                         ctx->tx_rem_skb = NULL;
1289
1290                         /* check for end of skb */
1291                         if (skb == NULL)
1292                                 break;
1293                 }
1294
1295                 /* get the appropriate NDP for this skb */
1296                 if (ctx->is_ndp16)
1297                         ndp.ndp16 = cdc_ncm_ndp16(ctx, skb_out, sign, skb->len + ctx->tx_modulus + ctx->tx_remainder);
1298                 else
1299                         ndp.ndp32 = cdc_ncm_ndp32(ctx, skb_out, sign, skb->len + ctx->tx_modulus + ctx->tx_remainder);
1300
1301                 /* align beginning of next frame */
1302                 cdc_ncm_align_tail(skb_out,  ctx->tx_modulus, ctx->tx_remainder, ctx->tx_curr_size);
1303
1304                 /* check if we had enough room left for both NDP and frame */
1305                 if ((ctx->is_ndp16 && !ndp.ndp16) || (!ctx->is_ndp16 && !ndp.ndp32) ||
1306                     skb_out->len + skb->len + delayed_ndp_size > ctx->tx_curr_size) {
1307                         if (n == 0) {
1308                                 /* won't fit, MTU problem? */
1309                                 dev_kfree_skb_any(skb);
1310                                 skb = NULL;
1311                                 dev->net->stats.tx_dropped++;
1312                         } else {
1313                                 /* no room for skb - store for later */
1314                                 if (ctx->tx_rem_skb != NULL) {
1315                                         dev_kfree_skb_any(ctx->tx_rem_skb);
1316                                         dev->net->stats.tx_dropped++;
1317                                 }
1318                                 ctx->tx_rem_skb = skb;
1319                                 ctx->tx_rem_sign = sign;
1320                                 skb = NULL;
1321                                 ready2send = 1;
1322                                 ctx->tx_reason_ntb_full++;      /* count reason for transmitting */
1323                         }
1324                         break;
1325                 }
1326
1327                 /* calculate frame number withing this NDP */
1328                 if (ctx->is_ndp16) {
1329                         ndplen = le16_to_cpu(ndp.ndp16->wLength);
1330                         index = (ndplen - sizeof(struct usb_cdc_ncm_ndp16)) / sizeof(struct usb_cdc_ncm_dpe16) - 1;
1331
1332                         /* OK, add this skb */
1333                         ndp.ndp16->dpe16[index].wDatagramLength = cpu_to_le16(skb->len);
1334                         ndp.ndp16->dpe16[index].wDatagramIndex = cpu_to_le16(skb_out->len);
1335                         ndp.ndp16->wLength = cpu_to_le16(ndplen + sizeof(struct usb_cdc_ncm_dpe16));
1336                 } else {
1337                         ndplen = le16_to_cpu(ndp.ndp32->wLength);
1338                         index = (ndplen - sizeof(struct usb_cdc_ncm_ndp32)) / sizeof(struct usb_cdc_ncm_dpe32) - 1;
1339
1340                         ndp.ndp32->dpe32[index].dwDatagramLength = cpu_to_le32(skb->len);
1341                         ndp.ndp32->dpe32[index].dwDatagramIndex = cpu_to_le32(skb_out->len);
1342                         ndp.ndp32->wLength = cpu_to_le16(ndplen + sizeof(struct usb_cdc_ncm_dpe32));
1343                 }
1344                 skb_put_data(skb_out, skb->data, skb->len);
1345                 ctx->tx_curr_frame_payload += skb->len; /* count real tx payload data */
1346                 dev_kfree_skb_any(skb);
1347                 skb = NULL;
1348
1349                 /* send now if this NDP is full */
1350                 if (index >= CDC_NCM_DPT_DATAGRAMS_MAX) {
1351                         ready2send = 1;
1352                         ctx->tx_reason_ndp_full++;      /* count reason for transmitting */
1353                         break;
1354                 }
1355         }
1356
1357         /* free up any dangling skb */
1358         if (skb != NULL) {
1359                 dev_kfree_skb_any(skb);
1360                 skb = NULL;
1361                 dev->net->stats.tx_dropped++;
1362         }
1363
1364         ctx->tx_curr_frame_num = n;
1365
1366         if (n == 0) {
1367                 /* wait for more frames */
1368                 /* push variables */
1369                 ctx->tx_curr_skb = skb_out;
1370                 goto exit_no_skb;
1371
1372         } else if ((n < ctx->tx_max_datagrams) && (ready2send == 0) && (ctx->timer_interval > 0)) {
1373                 /* wait for more frames */
1374                 /* push variables */
1375                 ctx->tx_curr_skb = skb_out;
1376                 /* set the pending count */
1377                 if (n < CDC_NCM_RESTART_TIMER_DATAGRAM_CNT)
1378                         ctx->tx_timer_pending = CDC_NCM_TIMER_PENDING_CNT;
1379                 goto exit_no_skb;
1380
1381         } else {
1382                 if (n == ctx->tx_max_datagrams)
1383                         ctx->tx_reason_max_datagram++;  /* count reason for transmitting */
1384                 /* frame goes out */
1385                 /* variables will be reset at next call */
1386         }
1387
1388         /* If requested, put NDP at end of frame. */
1389         if (ctx->drvflags & CDC_NCM_FLAG_NDP_TO_END) {
1390                 if (ctx->is_ndp16) {
1391                         nth.nth16 = (struct usb_cdc_ncm_nth16 *)skb_out->data;
1392                         cdc_ncm_align_tail(skb_out, ctx->tx_ndp_modulus, 0, ctx->tx_curr_size - ctx->max_ndp_size);
1393                         nth.nth16->wNdpIndex = cpu_to_le16(skb_out->len);
1394                         skb_put_data(skb_out, ctx->delayed_ndp16, ctx->max_ndp_size);
1395
1396                         /* Zero out delayed NDP - signature checking will naturally fail. */
1397                         ndp.ndp16 = memset(ctx->delayed_ndp16, 0, ctx->max_ndp_size);
1398                 } else {
1399                         nth.nth32 = (struct usb_cdc_ncm_nth32 *)skb_out->data;
1400                         cdc_ncm_align_tail(skb_out, ctx->tx_ndp_modulus, 0, ctx->tx_curr_size - ctx->max_ndp_size);
1401                         nth.nth32->dwNdpIndex = cpu_to_le32(skb_out->len);
1402                         skb_put_data(skb_out, ctx->delayed_ndp32, ctx->max_ndp_size);
1403
1404                         ndp.ndp32 = memset(ctx->delayed_ndp32, 0, ctx->max_ndp_size);
1405                 }
1406         }
1407
1408         /* If collected data size is less or equal ctx->min_tx_pkt
1409          * bytes, we send buffers as it is. If we get more data, it
1410          * would be more efficient for USB HS mobile device with DMA
1411          * engine to receive a full size NTB, than canceling DMA
1412          * transfer and receiving a short packet.
1413          *
1414          * This optimization support is pointless if we end up sending
1415          * a ZLP after full sized NTBs.
1416          */
1417         if (!(dev->driver_info->flags & FLAG_SEND_ZLP) &&
1418             skb_out->len > ctx->min_tx_pkt) {
1419                 padding_count = ctx->tx_curr_size - skb_out->len;
1420                 if (!WARN_ON(padding_count > ctx->tx_curr_size))
1421                         skb_put_zero(skb_out, padding_count);
1422         } else if (skb_out->len < ctx->tx_curr_size &&
1423                    (skb_out->len % dev->maxpacket) == 0) {
1424                 skb_put_u8(skb_out, 0); /* force short packet */
1425         }
1426
1427         /* set final frame length */
1428         if (ctx->is_ndp16) {
1429                 nth.nth16 = (struct usb_cdc_ncm_nth16 *)skb_out->data;
1430                 nth.nth16->wBlockLength = cpu_to_le16(skb_out->len);
1431         } else {
1432                 nth.nth32 = (struct usb_cdc_ncm_nth32 *)skb_out->data;
1433                 nth.nth32->dwBlockLength = cpu_to_le32(skb_out->len);
1434         }
1435
1436         /* return skb */
1437         ctx->tx_curr_skb = NULL;
1438
1439         /* keep private stats: framing overhead and number of NTBs */
1440         ctx->tx_overhead += skb_out->len - ctx->tx_curr_frame_payload;
1441         ctx->tx_ntbs++;
1442
1443         /* usbnet will count all the framing overhead by default.
1444          * Adjust the stats so that the tx_bytes counter show real
1445          * payload data instead.
1446          */
1447         usbnet_set_skb_tx_stats(skb_out, n,
1448                                 (long)ctx->tx_curr_frame_payload - skb_out->len);
1449
1450         return skb_out;
1451
1452 alloc_failed:
1453         if (skb) {
1454                 dev_kfree_skb_any(skb);
1455                 dev->net->stats.tx_dropped++;
1456         }
1457 exit_no_skb:
1458         /* Start timer, if there is a remaining non-empty skb */
1459         if (ctx->tx_curr_skb != NULL && n > 0)
1460                 cdc_ncm_tx_timeout_start(ctx);
1461         return NULL;
1462 }
1463 EXPORT_SYMBOL_GPL(cdc_ncm_fill_tx_frame);
1464
1465 static void cdc_ncm_tx_timeout_start(struct cdc_ncm_ctx *ctx)
1466 {
1467         /* start timer, if not already started */
1468         if (!(hrtimer_active(&ctx->tx_timer) || atomic_read(&ctx->stop)))
1469                 hrtimer_start(&ctx->tx_timer,
1470                                 ctx->timer_interval,
1471                                 HRTIMER_MODE_REL);
1472 }
1473
1474 static enum hrtimer_restart cdc_ncm_tx_timer_cb(struct hrtimer *timer)
1475 {
1476         struct cdc_ncm_ctx *ctx =
1477                         container_of(timer, struct cdc_ncm_ctx, tx_timer);
1478
1479         if (!atomic_read(&ctx->stop))
1480                 tasklet_schedule(&ctx->bh);
1481         return HRTIMER_NORESTART;
1482 }
1483
1484 static void cdc_ncm_txpath_bh(unsigned long param)
1485 {
1486         struct usbnet *dev = (struct usbnet *)param;
1487         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
1488
1489         spin_lock_bh(&ctx->mtx);
1490         if (ctx->tx_timer_pending != 0) {
1491                 ctx->tx_timer_pending--;
1492                 cdc_ncm_tx_timeout_start(ctx);
1493                 spin_unlock_bh(&ctx->mtx);
1494         } else if (dev->net != NULL) {
1495                 ctx->tx_reason_timeout++;       /* count reason for transmitting */
1496                 spin_unlock_bh(&ctx->mtx);
1497                 netif_tx_lock_bh(dev->net);
1498                 usbnet_start_xmit(NULL, dev->net);
1499                 netif_tx_unlock_bh(dev->net);
1500         } else {
1501                 spin_unlock_bh(&ctx->mtx);
1502         }
1503 }
1504
1505 struct sk_buff *
1506 cdc_ncm_tx_fixup(struct usbnet *dev, struct sk_buff *skb, gfp_t flags)
1507 {
1508         struct sk_buff *skb_out;
1509         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
1510
1511         /*
1512          * The Ethernet API we are using does not support transmitting
1513          * multiple Ethernet frames in a single call. This driver will
1514          * accumulate multiple Ethernet frames and send out a larger
1515          * USB frame when the USB buffer is full or when a single jiffies
1516          * timeout happens.
1517          */
1518         if (ctx == NULL)
1519                 goto error;
1520
1521         spin_lock_bh(&ctx->mtx);
1522
1523         if (ctx->is_ndp16)
1524                 skb_out = cdc_ncm_fill_tx_frame(dev, skb, cpu_to_le32(USB_CDC_NCM_NDP16_NOCRC_SIGN));
1525         else
1526                 skb_out = cdc_ncm_fill_tx_frame(dev, skb, cpu_to_le32(USB_CDC_NCM_NDP32_NOCRC_SIGN));
1527
1528         spin_unlock_bh(&ctx->mtx);
1529         return skb_out;
1530
1531 error:
1532         if (skb != NULL)
1533                 dev_kfree_skb_any(skb);
1534
1535         return NULL;
1536 }
1537 EXPORT_SYMBOL_GPL(cdc_ncm_tx_fixup);
1538
1539 /* verify NTB header and return offset of first NDP, or negative error */
1540 int cdc_ncm_rx_verify_nth16(struct cdc_ncm_ctx *ctx, struct sk_buff *skb_in)
1541 {
1542         struct usbnet *dev = netdev_priv(skb_in->dev);
1543         struct usb_cdc_ncm_nth16 *nth16;
1544         int len;
1545         int ret = -EINVAL;
1546
1547         if (ctx == NULL)
1548                 goto error;
1549
1550         if (skb_in->len < (sizeof(struct usb_cdc_ncm_nth16) +
1551                                         sizeof(struct usb_cdc_ncm_ndp16))) {
1552                 netif_dbg(dev, rx_err, dev->net, "frame too short\n");
1553                 goto error;
1554         }
1555
1556         nth16 = (struct usb_cdc_ncm_nth16 *)skb_in->data;
1557
1558         if (nth16->dwSignature != cpu_to_le32(USB_CDC_NCM_NTH16_SIGN)) {
1559                 netif_dbg(dev, rx_err, dev->net,
1560                           "invalid NTH16 signature <%#010x>\n",
1561                           le32_to_cpu(nth16->dwSignature));
1562                 goto error;
1563         }
1564
1565         len = le16_to_cpu(nth16->wBlockLength);
1566         if (len > ctx->rx_max) {
1567                 netif_dbg(dev, rx_err, dev->net,
1568                           "unsupported NTB block length %u/%u\n", len,
1569                           ctx->rx_max);
1570                 goto error;
1571         }
1572
1573         if ((ctx->rx_seq + 1) != le16_to_cpu(nth16->wSequence) &&
1574             (ctx->rx_seq || le16_to_cpu(nth16->wSequence)) &&
1575             !((ctx->rx_seq == 0xffff) && !le16_to_cpu(nth16->wSequence))) {
1576                 netif_dbg(dev, rx_err, dev->net,
1577                           "sequence number glitch prev=%d curr=%d\n",
1578                           ctx->rx_seq, le16_to_cpu(nth16->wSequence));
1579         }
1580         ctx->rx_seq = le16_to_cpu(nth16->wSequence);
1581
1582         ret = le16_to_cpu(nth16->wNdpIndex);
1583 error:
1584         return ret;
1585 }
1586 EXPORT_SYMBOL_GPL(cdc_ncm_rx_verify_nth16);
1587
1588 int cdc_ncm_rx_verify_nth32(struct cdc_ncm_ctx *ctx, struct sk_buff *skb_in)
1589 {
1590         struct usbnet *dev = netdev_priv(skb_in->dev);
1591         struct usb_cdc_ncm_nth32 *nth32;
1592         int len;
1593         int ret = -EINVAL;
1594
1595         if (ctx == NULL)
1596                 goto error;
1597
1598         if (skb_in->len < (sizeof(struct usb_cdc_ncm_nth32) +
1599                                         sizeof(struct usb_cdc_ncm_ndp32))) {
1600                 netif_dbg(dev, rx_err, dev->net, "frame too short\n");
1601                 goto error;
1602         }
1603
1604         nth32 = (struct usb_cdc_ncm_nth32 *)skb_in->data;
1605
1606         if (nth32->dwSignature != cpu_to_le32(USB_CDC_NCM_NTH32_SIGN)) {
1607                 netif_dbg(dev, rx_err, dev->net,
1608                           "invalid NTH32 signature <%#010x>\n",
1609                           le32_to_cpu(nth32->dwSignature));
1610                 goto error;
1611         }
1612
1613         len = le32_to_cpu(nth32->dwBlockLength);
1614         if (len > ctx->rx_max) {
1615                 netif_dbg(dev, rx_err, dev->net,
1616                           "unsupported NTB block length %u/%u\n", len,
1617                           ctx->rx_max);
1618                 goto error;
1619         }
1620
1621         if ((ctx->rx_seq + 1) != le16_to_cpu(nth32->wSequence) &&
1622             (ctx->rx_seq || le16_to_cpu(nth32->wSequence)) &&
1623             !((ctx->rx_seq == 0xffff) && !le16_to_cpu(nth32->wSequence))) {
1624                 netif_dbg(dev, rx_err, dev->net,
1625                           "sequence number glitch prev=%d curr=%d\n",
1626                           ctx->rx_seq, le16_to_cpu(nth32->wSequence));
1627         }
1628         ctx->rx_seq = le16_to_cpu(nth32->wSequence);
1629
1630         ret = le32_to_cpu(nth32->dwNdpIndex);
1631 error:
1632         return ret;
1633 }
1634 EXPORT_SYMBOL_GPL(cdc_ncm_rx_verify_nth32);
1635
1636 /* verify NDP header and return number of datagrams, or negative error */
1637 int cdc_ncm_rx_verify_ndp16(struct sk_buff *skb_in, int ndpoffset)
1638 {
1639         struct usbnet *dev = netdev_priv(skb_in->dev);
1640         struct usb_cdc_ncm_ndp16 *ndp16;
1641         int ret = -EINVAL;
1642
1643         if ((ndpoffset + sizeof(struct usb_cdc_ncm_ndp16)) > skb_in->len) {
1644                 netif_dbg(dev, rx_err, dev->net, "invalid NDP offset  <%u>\n",
1645                           ndpoffset);
1646                 goto error;
1647         }
1648         ndp16 = (struct usb_cdc_ncm_ndp16 *)(skb_in->data + ndpoffset);
1649
1650         if (le16_to_cpu(ndp16->wLength) < USB_CDC_NCM_NDP16_LENGTH_MIN) {
1651                 netif_dbg(dev, rx_err, dev->net, "invalid DPT16 length <%u>\n",
1652                           le16_to_cpu(ndp16->wLength));
1653                 goto error;
1654         }
1655
1656         ret = ((le16_to_cpu(ndp16->wLength) -
1657                                         sizeof(struct usb_cdc_ncm_ndp16)) /
1658                                         sizeof(struct usb_cdc_ncm_dpe16));
1659         ret--; /* we process NDP entries except for the last one */
1660
1661         if ((sizeof(struct usb_cdc_ncm_ndp16) +
1662              ret * (sizeof(struct usb_cdc_ncm_dpe16))) > skb_in->len) {
1663                 netif_dbg(dev, rx_err, dev->net, "Invalid nframes = %d\n", ret);
1664                 ret = -EINVAL;
1665         }
1666
1667 error:
1668         return ret;
1669 }
1670 EXPORT_SYMBOL_GPL(cdc_ncm_rx_verify_ndp16);
1671
1672 /* verify NDP header and return number of datagrams, or negative error */
1673 int cdc_ncm_rx_verify_ndp32(struct sk_buff *skb_in, int ndpoffset)
1674 {
1675         struct usbnet *dev = netdev_priv(skb_in->dev);
1676         struct usb_cdc_ncm_ndp32 *ndp32;
1677         int ret = -EINVAL;
1678
1679         if ((ndpoffset + sizeof(struct usb_cdc_ncm_ndp32)) > skb_in->len) {
1680                 netif_dbg(dev, rx_err, dev->net, "invalid NDP offset  <%u>\n",
1681                           ndpoffset);
1682                 goto error;
1683         }
1684         ndp32 = (struct usb_cdc_ncm_ndp32 *)(skb_in->data + ndpoffset);
1685
1686         if (le16_to_cpu(ndp32->wLength) < USB_CDC_NCM_NDP32_LENGTH_MIN) {
1687                 netif_dbg(dev, rx_err, dev->net, "invalid DPT32 length <%u>\n",
1688                           le16_to_cpu(ndp32->wLength));
1689                 goto error;
1690         }
1691
1692         ret = ((le16_to_cpu(ndp32->wLength) -
1693                                         sizeof(struct usb_cdc_ncm_ndp32)) /
1694                                         sizeof(struct usb_cdc_ncm_dpe32));
1695         ret--; /* we process NDP entries except for the last one */
1696
1697         if ((sizeof(struct usb_cdc_ncm_ndp32) +
1698              ret * (sizeof(struct usb_cdc_ncm_dpe32))) > skb_in->len) {
1699                 netif_dbg(dev, rx_err, dev->net, "Invalid nframes = %d\n", ret);
1700                 ret = -EINVAL;
1701         }
1702
1703 error:
1704         return ret;
1705 }
1706 EXPORT_SYMBOL_GPL(cdc_ncm_rx_verify_ndp32);
1707
1708 int cdc_ncm_rx_fixup(struct usbnet *dev, struct sk_buff *skb_in)
1709 {
1710         struct sk_buff *skb;
1711         struct cdc_ncm_ctx *ctx = (struct cdc_ncm_ctx *)dev->data[0];
1712         int len;
1713         int nframes;
1714         int x;
1715         int offset;
1716         union {
1717                 struct usb_cdc_ncm_ndp16 *ndp16;
1718                 struct usb_cdc_ncm_ndp32 *ndp32;
1719         } ndp;
1720         union {
1721                 struct usb_cdc_ncm_dpe16 *dpe16;
1722                 struct usb_cdc_ncm_dpe32 *dpe32;
1723         } dpe;
1724
1725         int ndpoffset;
1726         int loopcount = 50; /* arbitrary max preventing infinite loop */
1727         u32 payload = 0;
1728
1729         if (ctx->is_ndp16)
1730                 ndpoffset = cdc_ncm_rx_verify_nth16(ctx, skb_in);
1731         else
1732                 ndpoffset = cdc_ncm_rx_verify_nth32(ctx, skb_in);
1733
1734         if (ndpoffset < 0)
1735                 goto error;
1736
1737 next_ndp:
1738         if (ctx->is_ndp16) {
1739                 nframes = cdc_ncm_rx_verify_ndp16(skb_in, ndpoffset);
1740                 if (nframes < 0)
1741                         goto error;
1742
1743                 ndp.ndp16 = (struct usb_cdc_ncm_ndp16 *)(skb_in->data + ndpoffset);
1744
1745                 if (ndp.ndp16->dwSignature != cpu_to_le32(USB_CDC_NCM_NDP16_NOCRC_SIGN)) {
1746                         netif_dbg(dev, rx_err, dev->net,
1747                                   "invalid DPT16 signature <%#010x>\n",
1748                                   le32_to_cpu(ndp.ndp16->dwSignature));
1749                         goto err_ndp;
1750                 }
1751                 dpe.dpe16 = ndp.ndp16->dpe16;
1752         } else {
1753                 nframes = cdc_ncm_rx_verify_ndp32(skb_in, ndpoffset);
1754                 if (nframes < 0)
1755                         goto error;
1756
1757                 ndp.ndp32 = (struct usb_cdc_ncm_ndp32 *)(skb_in->data + ndpoffset);
1758
1759                 if (ndp.ndp32->dwSignature != cpu_to_le32(USB_CDC_NCM_NDP32_NOCRC_SIGN)) {
1760                         netif_dbg(dev, rx_err, dev->net,
1761                                   "invalid DPT32 signature <%#010x>\n",
1762                                   le32_to_cpu(ndp.ndp32->dwSignature));
1763                         goto err_ndp;
1764                 }
1765                 dpe.dpe32 = ndp.ndp32->dpe32;
1766         }
1767
1768         for (x = 0; x < nframes; x++) {
1769                 if (ctx->is_ndp16) {
1770                         offset = le16_to_cpu(dpe.dpe16->wDatagramIndex);
1771                         len = le16_to_cpu(dpe.dpe16->wDatagramLength);
1772                 } else {
1773                         offset = le32_to_cpu(dpe.dpe32->dwDatagramIndex);
1774                         len = le32_to_cpu(dpe.dpe32->dwDatagramLength);
1775                 }
1776
1777                 /*
1778                  * CDC NCM ch. 3.7
1779                  * All entries after first NULL entry are to be ignored
1780                  */
1781                 if ((offset == 0) || (len == 0)) {
1782                         if (!x)
1783                                 goto err_ndp; /* empty NTB */
1784                         break;
1785                 }
1786
1787                 /* sanity checking */
1788                 if (((offset + len) > skb_in->len) ||
1789                                 (len > ctx->rx_max) || (len < ETH_HLEN)) {
1790                         netif_dbg(dev, rx_err, dev->net,
1791                                   "invalid frame detected (ignored) offset[%u]=%u, length=%u, skb=%p\n",
1792                                   x, offset, len, skb_in);
1793                         if (!x)
1794                                 goto err_ndp;
1795                         break;
1796
1797                 } else {
1798                         /* create a fresh copy to reduce truesize */
1799                         skb = netdev_alloc_skb_ip_align(dev->net,  len);
1800                         if (!skb)
1801                                 goto error;
1802                         skb_put_data(skb, skb_in->data + offset, len);
1803                         usbnet_skb_return(dev, skb);
1804                         payload += len; /* count payload bytes in this NTB */
1805                 }
1806
1807                 if (ctx->is_ndp16)
1808                         dpe.dpe16++;
1809                 else
1810                         dpe.dpe32++;
1811         }
1812 err_ndp:
1813         /* are there more NDPs to process? */
1814         if (ctx->is_ndp16)
1815                 ndpoffset = le16_to_cpu(ndp.ndp16->wNextNdpIndex);
1816         else
1817                 ndpoffset = le32_to_cpu(ndp.ndp32->dwNextNdpIndex);
1818
1819         if (ndpoffset && loopcount--)
1820                 goto next_ndp;
1821
1822         /* update stats */
1823         ctx->rx_overhead += skb_in->len - payload;
1824         ctx->rx_ntbs++;
1825
1826         return 1;
1827 error:
1828         return 0;
1829 }
1830 EXPORT_SYMBOL_GPL(cdc_ncm_rx_fixup);
1831
1832 static void
1833 cdc_ncm_speed_change(struct usbnet *dev,
1834                      struct usb_cdc_speed_change *data)
1835 {
1836         uint32_t rx_speed = le32_to_cpu(data->DLBitRRate);
1837         uint32_t tx_speed = le32_to_cpu(data->ULBitRate);
1838
1839         /* if the speed hasn't changed, don't report it.
1840          * RTL8156 shipped before 2021 sends notification about every 32ms.
1841          */
1842         if (dev->rx_speed == rx_speed && dev->tx_speed == tx_speed)
1843                 return;
1844
1845         dev->rx_speed = rx_speed;
1846         dev->tx_speed = tx_speed;
1847
1848         /*
1849          * Currently the USB-NET API does not support reporting the actual
1850          * device speed. Do print it instead.
1851          */
1852         if ((tx_speed > 1000000) && (rx_speed > 1000000)) {
1853                 netif_info(dev, link, dev->net,
1854                            "%u mbit/s downlink %u mbit/s uplink\n",
1855                            (unsigned int)(rx_speed / 1000000U),
1856                            (unsigned int)(tx_speed / 1000000U));
1857         } else {
1858                 netif_info(dev, link, dev->net,
1859                            "%u kbit/s downlink %u kbit/s uplink\n",
1860                            (unsigned int)(rx_speed / 1000U),
1861                            (unsigned int)(tx_speed / 1000U));
1862         }
1863 }
1864
1865 static void cdc_ncm_status(struct usbnet *dev, struct urb *urb)
1866 {
1867         struct cdc_ncm_ctx *ctx;
1868         struct usb_cdc_notification *event;
1869
1870         ctx = (struct cdc_ncm_ctx *)dev->data[0];
1871
1872         if (urb->actual_length < sizeof(*event))
1873                 return;
1874
1875         /* test for split data in 8-byte chunks */
1876         if (test_and_clear_bit(EVENT_STS_SPLIT, &dev->flags)) {
1877                 cdc_ncm_speed_change(dev,
1878                       (struct usb_cdc_speed_change *)urb->transfer_buffer);
1879                 return;
1880         }
1881
1882         event = urb->transfer_buffer;
1883
1884         switch (event->bNotificationType) {
1885         case USB_CDC_NOTIFY_NETWORK_CONNECTION:
1886                 /*
1887                  * According to the CDC NCM specification ch.7.1
1888                  * USB_CDC_NOTIFY_NETWORK_CONNECTION notification shall be
1889                  * sent by device after USB_CDC_NOTIFY_SPEED_CHANGE.
1890                  */
1891                 if (netif_carrier_ok(dev->net) != !!event->wValue)
1892                         usbnet_link_change(dev, !!event->wValue, 0);
1893                 break;
1894
1895         case USB_CDC_NOTIFY_SPEED_CHANGE:
1896                 if (urb->actual_length < (sizeof(*event) +
1897                                         sizeof(struct usb_cdc_speed_change)))
1898                         set_bit(EVENT_STS_SPLIT, &dev->flags);
1899                 else
1900                         cdc_ncm_speed_change(dev,
1901                                              (struct usb_cdc_speed_change *)&event[1]);
1902                 break;
1903
1904         default:
1905                 dev_dbg(&dev->udev->dev,
1906                         "NCM: unexpected notification 0x%02x!\n",
1907                         event->bNotificationType);
1908                 break;
1909         }
1910 }
1911
1912 static const struct driver_info cdc_ncm_info = {
1913         .description = "CDC NCM",
1914         .flags = FLAG_POINTTOPOINT | FLAG_NO_SETINT | FLAG_MULTI_PACKET
1915                         | FLAG_LINK_INTR | FLAG_ETHER,
1916         .bind = cdc_ncm_bind,
1917         .unbind = cdc_ncm_unbind,
1918         .manage_power = usbnet_manage_power,
1919         .status = cdc_ncm_status,
1920         .rx_fixup = cdc_ncm_rx_fixup,
1921         .tx_fixup = cdc_ncm_tx_fixup,
1922 };
1923
1924 /* Same as cdc_ncm_info, but with FLAG_WWAN */
1925 static const struct driver_info wwan_info = {
1926         .description = "Mobile Broadband Network Device",
1927         .flags = FLAG_POINTTOPOINT | FLAG_NO_SETINT | FLAG_MULTI_PACKET
1928                         | FLAG_LINK_INTR | FLAG_WWAN,
1929         .bind = cdc_ncm_bind,
1930         .unbind = cdc_ncm_unbind,
1931         .manage_power = usbnet_manage_power,
1932         .status = cdc_ncm_status,
1933         .rx_fixup = cdc_ncm_rx_fixup,
1934         .tx_fixup = cdc_ncm_tx_fixup,
1935 };
1936
1937 /* Same as wwan_info, but with FLAG_NOARP  */
1938 static const struct driver_info wwan_noarp_info = {
1939         .description = "Mobile Broadband Network Device (NO ARP)",
1940         .flags = FLAG_POINTTOPOINT | FLAG_NO_SETINT | FLAG_MULTI_PACKET
1941                         | FLAG_LINK_INTR | FLAG_WWAN | FLAG_NOARP,
1942         .bind = cdc_ncm_bind,
1943         .unbind = cdc_ncm_unbind,
1944         .manage_power = usbnet_manage_power,
1945         .status = cdc_ncm_status,
1946         .rx_fixup = cdc_ncm_rx_fixup,
1947         .tx_fixup = cdc_ncm_tx_fixup,
1948 };
1949
1950 static const struct usb_device_id cdc_devs[] = {
1951         /* Ericsson MBM devices like F5521gw */
1952         { .match_flags = USB_DEVICE_ID_MATCH_INT_INFO
1953                 | USB_DEVICE_ID_MATCH_VENDOR,
1954           .idVendor = 0x0bdb,
1955           .bInterfaceClass = USB_CLASS_COMM,
1956           .bInterfaceSubClass = USB_CDC_SUBCLASS_NCM,
1957           .bInterfaceProtocol = USB_CDC_PROTO_NONE,
1958           .driver_info = (unsigned long) &wwan_info,
1959         },
1960
1961         /* Telit LE910 V2 */
1962         { USB_DEVICE_AND_INTERFACE_INFO(0x1bc7, 0x0036,
1963                 USB_CLASS_COMM,
1964                 USB_CDC_SUBCLASS_NCM, USB_CDC_PROTO_NONE),
1965           .driver_info = (unsigned long)&wwan_noarp_info,
1966         },
1967
1968         /* DW5812 LTE Verizon Mobile Broadband Card
1969          * Unlike DW5550 this device requires FLAG_NOARP
1970          */
1971         { USB_DEVICE_AND_INTERFACE_INFO(0x413c, 0x81bb,
1972                 USB_CLASS_COMM,
1973                 USB_CDC_SUBCLASS_NCM, USB_CDC_PROTO_NONE),
1974           .driver_info = (unsigned long)&wwan_noarp_info,
1975         },
1976
1977         /* DW5813 LTE AT&T Mobile Broadband Card
1978          * Unlike DW5550 this device requires FLAG_NOARP
1979          */
1980         { USB_DEVICE_AND_INTERFACE_INFO(0x413c, 0x81bc,
1981                 USB_CLASS_COMM,
1982                 USB_CDC_SUBCLASS_NCM, USB_CDC_PROTO_NONE),
1983           .driver_info = (unsigned long)&wwan_noarp_info,
1984         },
1985
1986         /* Dell branded MBM devices like DW5550 */
1987         { .match_flags = USB_DEVICE_ID_MATCH_INT_INFO
1988                 | USB_DEVICE_ID_MATCH_VENDOR,
1989           .idVendor = 0x413c,
1990           .bInterfaceClass = USB_CLASS_COMM,
1991           .bInterfaceSubClass = USB_CDC_SUBCLASS_NCM,
1992           .bInterfaceProtocol = USB_CDC_PROTO_NONE,
1993           .driver_info = (unsigned long) &wwan_info,
1994         },
1995
1996         /* Toshiba branded MBM devices */
1997         { .match_flags = USB_DEVICE_ID_MATCH_INT_INFO
1998                 | USB_DEVICE_ID_MATCH_VENDOR,
1999           .idVendor = 0x0930,
2000           .bInterfaceClass = USB_CLASS_COMM,
2001           .bInterfaceSubClass = USB_CDC_SUBCLASS_NCM,
2002           .bInterfaceProtocol = USB_CDC_PROTO_NONE,
2003           .driver_info = (unsigned long) &wwan_info,
2004         },
2005
2006         /* tag Huawei devices as wwan */
2007         { USB_VENDOR_AND_INTERFACE_INFO(0x12d1,
2008                                         USB_CLASS_COMM,
2009                                         USB_CDC_SUBCLASS_NCM,
2010                                         USB_CDC_PROTO_NONE),
2011           .driver_info = (unsigned long)&wwan_info,
2012         },
2013
2014         /* Infineon(now Intel) HSPA Modem platform */
2015         { USB_DEVICE_AND_INTERFACE_INFO(0x1519, 0x0443,
2016                 USB_CLASS_COMM,
2017                 USB_CDC_SUBCLASS_NCM, USB_CDC_PROTO_NONE),
2018           .driver_info = (unsigned long)&wwan_noarp_info,
2019         },
2020
2021         /* u-blox TOBY-L4 */
2022         { USB_DEVICE_AND_INTERFACE_INFO(0x1546, 0x1010,
2023                 USB_CLASS_COMM,
2024                 USB_CDC_SUBCLASS_NCM, USB_CDC_PROTO_NONE),
2025           .driver_info = (unsigned long)&wwan_info,
2026         },
2027
2028         /* Generic CDC-NCM devices */
2029         { USB_INTERFACE_INFO(USB_CLASS_COMM,
2030                 USB_CDC_SUBCLASS_NCM, USB_CDC_PROTO_NONE),
2031                 .driver_info = (unsigned long)&cdc_ncm_info,
2032         },
2033         {
2034         },
2035 };
2036 MODULE_DEVICE_TABLE(usb, cdc_devs);
2037
2038 static struct usb_driver cdc_ncm_driver = {
2039         .name = "cdc_ncm",
2040         .id_table = cdc_devs,
2041         .probe = usbnet_probe,
2042         .disconnect = usbnet_disconnect,
2043         .suspend = usbnet_suspend,
2044         .resume = usbnet_resume,
2045         .reset_resume = usbnet_resume,
2046         .supports_autosuspend = 1,
2047         .disable_hub_initiated_lpm = 1,
2048 };
2049
2050 module_usb_driver(cdc_ncm_driver);
2051
2052 MODULE_AUTHOR("Hans Petter Selasky");
2053 MODULE_DESCRIPTION("USB CDC NCM host driver");
2054 MODULE_LICENSE("Dual BSD/GPL");