]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/dev/hyperv/netvsc/hv_netvsc_drv_freebsd.c
MFC 302632-302634
[FreeBSD/stable/10.git] / sys / dev / hyperv / netvsc / hv_netvsc_drv_freebsd.c
1 /*-
2  * Copyright (c) 2010-2012 Citrix Inc.
3  * Copyright (c) 2009-2012,2016 Microsoft Corp.
4  * Copyright (c) 2012 NetApp Inc.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice unmodified, this list of conditions, and the following
12  *    disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28
29 /*-
30  * Copyright (c) 2004-2006 Kip Macy
31  * All rights reserved.
32  *
33  * Redistribution and use in source and binary forms, with or without
34  * modification, are permitted provided that the following conditions
35  * are met:
36  * 1. Redistributions of source code must retain the above copyright
37  *    notice, this list of conditions and the following disclaimer.
38  * 2. Redistributions in binary form must reproduce the above copyright
39  *    notice, this list of conditions and the following disclaimer in the
40  *    documentation and/or other materials provided with the distribution.
41  *
42  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
43  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
44  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
45  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
46  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
47  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
48  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
49  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
50  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
51  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
52  * SUCH DAMAGE.
53  */
54
55 #include <sys/cdefs.h>
56 __FBSDID("$FreeBSD$");
57
58 #include "opt_inet6.h"
59 #include "opt_inet.h"
60
61 #include <sys/param.h>
62 #include <sys/systm.h>
63 #include <sys/sockio.h>
64 #include <sys/mbuf.h>
65 #include <sys/malloc.h>
66 #include <sys/module.h>
67 #include <sys/kernel.h>
68 #include <sys/socket.h>
69 #include <sys/proc.h>
70 #include <sys/queue.h>
71 #include <sys/lock.h>
72 #include <sys/sx.h>
73 #include <sys/sysctl.h>
74 #include <sys/buf_ring.h>
75
76 #include <net/if.h>
77 #include <net/if_arp.h>
78 #include <net/ethernet.h>
79 #include <net/if_dl.h>
80 #include <net/if_media.h>
81
82 #include <net/bpf.h>
83
84 #include <net/if_types.h>
85 #include <net/if_vlan_var.h>
86 #include <net/if.h>
87
88 #include <netinet/in_systm.h>
89 #include <netinet/in.h>
90 #include <netinet/ip.h>
91 #include <netinet/if_ether.h>
92 #include <netinet/tcp.h>
93 #include <netinet/udp.h>
94 #include <netinet/ip6.h>
95
96 #include <vm/vm.h>
97 #include <vm/vm_param.h>
98 #include <vm/vm_kern.h>
99 #include <vm/pmap.h>
100
101 #include <machine/bus.h>
102 #include <machine/resource.h>
103 #include <machine/frame.h>
104 #include <machine/vmparam.h>
105
106 #include <sys/bus.h>
107 #include <sys/rman.h>
108 #include <sys/mutex.h>
109 #include <sys/errno.h>
110 #include <sys/types.h>
111 #include <machine/atomic.h>
112
113 #include <machine/intr_machdep.h>
114
115 #include <machine/in_cksum.h>
116
117 #include <dev/hyperv/include/hyperv.h>
118 #include <dev/hyperv/include/hyperv_busdma.h>
119
120 #include "hv_net_vsc.h"
121 #include "hv_rndis.h"
122 #include "hv_rndis_filter.h"
123 #include "vmbus_if.h"
124
125 #define hv_chan_rxr     hv_chan_priv1
126 #define hv_chan_txr     hv_chan_priv2
127
128 /* Short for Hyper-V network interface */
129 #define NETVSC_DEVNAME    "hn"
130
131 /*
132  * It looks like offset 0 of buf is reserved to hold the softc pointer.
133  * The sc pointer evidently not needed, and is not presently populated.
134  * The packet offset is where the netvsc_packet starts in the buffer.
135  */
136 #define HV_NV_SC_PTR_OFFSET_IN_BUF         0
137 #define HV_NV_PACKET_OFFSET_IN_BUF         16
138
139 /* YYY should get it from the underlying channel */
140 #define HN_TX_DESC_CNT                  512
141
142 #define HN_LROENT_CNT_DEF               128
143
144 #define HN_RING_CNT_DEF_MAX             8
145
146 #define HN_RNDIS_MSG_LEN                \
147     (sizeof(rndis_msg) +                \
148      RNDIS_HASHVAL_PPI_SIZE +           \
149      RNDIS_VLAN_PPI_SIZE +              \
150      RNDIS_TSO_PPI_SIZE +               \
151      RNDIS_CSUM_PPI_SIZE)
152 #define HN_RNDIS_MSG_BOUNDARY           PAGE_SIZE
153 #define HN_RNDIS_MSG_ALIGN              CACHE_LINE_SIZE
154
155 #define HN_TX_DATA_BOUNDARY             PAGE_SIZE
156 #define HN_TX_DATA_MAXSIZE              IP_MAXPACKET
157 #define HN_TX_DATA_SEGSIZE              PAGE_SIZE
158 #define HN_TX_DATA_SEGCNT_MAX           \
159     (NETVSC_PACKET_MAXPAGE - HV_RF_NUM_TX_RESERVED_PAGE_BUFS)
160
161 #define HN_DIRECT_TX_SIZE_DEF           128
162
163 #define HN_EARLY_TXEOF_THRESH           8
164
165 struct hn_txdesc {
166 #ifndef HN_USE_TXDESC_BUFRING
167         SLIST_ENTRY(hn_txdesc) link;
168 #endif
169         struct mbuf     *m;
170         struct hn_tx_ring *txr;
171         int             refs;
172         uint32_t        flags;          /* HN_TXD_FLAG_ */
173         netvsc_packet   netvsc_pkt;     /* XXX to be removed */
174
175         bus_dmamap_t    data_dmap;
176
177         bus_addr_t      rndis_msg_paddr;
178         rndis_msg       *rndis_msg;
179         bus_dmamap_t    rndis_msg_dmap;
180 };
181
182 #define HN_TXD_FLAG_ONLIST      0x1
183 #define HN_TXD_FLAG_DMAMAP      0x2
184
185 /*
186  * Only enable UDP checksum offloading when it is on 2012R2 or
187  * later.  UDP checksum offloading doesn't work on earlier
188  * Windows releases.
189  */
190 #define HN_CSUM_ASSIST_WIN8     (CSUM_IP | CSUM_TCP)
191 #define HN_CSUM_ASSIST          (CSUM_IP | CSUM_UDP | CSUM_TCP)
192
193 #define HN_LRO_LENLIM_MULTIRX_DEF       (12 * ETHERMTU)
194 #define HN_LRO_LENLIM_DEF               (25 * ETHERMTU)
195 /* YYY 2*MTU is a bit rough, but should be good enough. */
196 #define HN_LRO_LENLIM_MIN(ifp)          (2 * (ifp)->if_mtu)
197
198 #define HN_LRO_ACKCNT_DEF               1
199
200 /*
201  * Be aware that this sleepable mutex will exhibit WITNESS errors when
202  * certain TCP and ARP code paths are taken.  This appears to be a
203  * well-known condition, as all other drivers checked use a sleeping
204  * mutex to protect their transmit paths.
205  * Also Be aware that mutexes do not play well with semaphores, and there
206  * is a conflicting semaphore in a certain channel code path.
207  */
208 #define NV_LOCK_INIT(_sc, _name) \
209             mtx_init(&(_sc)->hn_lock, _name, MTX_NETWORK_LOCK, MTX_DEF)
210 #define NV_LOCK(_sc)            mtx_lock(&(_sc)->hn_lock)
211 #define NV_LOCK_ASSERT(_sc)     mtx_assert(&(_sc)->hn_lock, MA_OWNED)
212 #define NV_UNLOCK(_sc)          mtx_unlock(&(_sc)->hn_lock)
213 #define NV_LOCK_DESTROY(_sc)    mtx_destroy(&(_sc)->hn_lock)
214
215
216 /*
217  * Globals
218  */
219
220 int hv_promisc_mode = 0;    /* normal mode by default */
221
222 SYSCTL_NODE(_hw, OID_AUTO, hn, CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
223     "Hyper-V network interface");
224
225 /* Trust tcp segements verification on host side. */
226 static int hn_trust_hosttcp = 1;
227 SYSCTL_INT(_hw_hn, OID_AUTO, trust_hosttcp, CTLFLAG_RDTUN,
228     &hn_trust_hosttcp, 0,
229     "Trust tcp segement verification on host side, "
230     "when csum info is missing (global setting)");
231
232 /* Trust udp datagrams verification on host side. */
233 static int hn_trust_hostudp = 1;
234 SYSCTL_INT(_hw_hn, OID_AUTO, trust_hostudp, CTLFLAG_RDTUN,
235     &hn_trust_hostudp, 0,
236     "Trust udp datagram verification on host side, "
237     "when csum info is missing (global setting)");
238
239 /* Trust ip packets verification on host side. */
240 static int hn_trust_hostip = 1;
241 SYSCTL_INT(_hw_hn, OID_AUTO, trust_hostip, CTLFLAG_RDTUN,
242     &hn_trust_hostip, 0,
243     "Trust ip packet verification on host side, "
244     "when csum info is missing (global setting)");
245
246 /* Limit TSO burst size */
247 static int hn_tso_maxlen = 0;
248 SYSCTL_INT(_hw_hn, OID_AUTO, tso_maxlen, CTLFLAG_RDTUN,
249     &hn_tso_maxlen, 0, "TSO burst limit");
250
251 /* Limit chimney send size */
252 static int hn_tx_chimney_size = 0;
253 SYSCTL_INT(_hw_hn, OID_AUTO, tx_chimney_size, CTLFLAG_RDTUN,
254     &hn_tx_chimney_size, 0, "Chimney send packet size limit");
255
256 /* Limit the size of packet for direct transmission */
257 static int hn_direct_tx_size = HN_DIRECT_TX_SIZE_DEF;
258 SYSCTL_INT(_hw_hn, OID_AUTO, direct_tx_size, CTLFLAG_RDTUN,
259     &hn_direct_tx_size, 0, "Size of the packet for direct transmission");
260
261 #if defined(INET) || defined(INET6)
262 #if __FreeBSD_version >= 1100095
263 static int hn_lro_entry_count = HN_LROENT_CNT_DEF;
264 SYSCTL_INT(_hw_hn, OID_AUTO, lro_entry_count, CTLFLAG_RDTUN,
265     &hn_lro_entry_count, 0, "LRO entry count");
266 #endif
267 #endif
268
269 static int hn_share_tx_taskq = 0;
270 SYSCTL_INT(_hw_hn, OID_AUTO, share_tx_taskq, CTLFLAG_RDTUN,
271     &hn_share_tx_taskq, 0, "Enable shared TX taskqueue");
272
273 static struct taskqueue *hn_tx_taskq;
274
275 #ifndef HN_USE_TXDESC_BUFRING
276 static int hn_use_txdesc_bufring = 0;
277 #else
278 static int hn_use_txdesc_bufring = 1;
279 #endif
280 SYSCTL_INT(_hw_hn, OID_AUTO, use_txdesc_bufring, CTLFLAG_RD,
281     &hn_use_txdesc_bufring, 0, "Use buf_ring for TX descriptors");
282
283 static int hn_bind_tx_taskq = -1;
284 SYSCTL_INT(_hw_hn, OID_AUTO, bind_tx_taskq, CTLFLAG_RDTUN,
285     &hn_bind_tx_taskq, 0, "Bind TX taskqueue to the specified cpu");
286
287 static int hn_use_if_start = 0;
288 SYSCTL_INT(_hw_hn, OID_AUTO, use_if_start, CTLFLAG_RDTUN,
289     &hn_use_if_start, 0, "Use if_start TX method");
290
291 static int hn_chan_cnt = 0;
292 SYSCTL_INT(_hw_hn, OID_AUTO, chan_cnt, CTLFLAG_RDTUN,
293     &hn_chan_cnt, 0,
294     "# of channels to use; each channel has one RX ring and one TX ring");
295
296 static int hn_tx_ring_cnt = 0;
297 SYSCTL_INT(_hw_hn, OID_AUTO, tx_ring_cnt, CTLFLAG_RDTUN,
298     &hn_tx_ring_cnt, 0, "# of TX rings to use");
299
300 static int hn_tx_swq_depth = 0;
301 SYSCTL_INT(_hw_hn, OID_AUTO, tx_swq_depth, CTLFLAG_RDTUN,
302     &hn_tx_swq_depth, 0, "Depth of IFQ or BUFRING");
303
304 #if __FreeBSD_version >= 1100095
305 static u_int hn_lro_mbufq_depth = 0;
306 SYSCTL_UINT(_hw_hn, OID_AUTO, lro_mbufq_depth, CTLFLAG_RDTUN,
307     &hn_lro_mbufq_depth, 0, "Depth of LRO mbuf queue");
308 #endif
309
310 static u_int hn_cpu_index;
311
312 /*
313  * Forward declarations
314  */
315 static void hn_stop(hn_softc_t *sc);
316 static void hn_ifinit_locked(hn_softc_t *sc);
317 static void hn_ifinit(void *xsc);
318 static int  hn_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data);
319 static int hn_start_locked(struct hn_tx_ring *txr, int len);
320 static void hn_start(struct ifnet *ifp);
321 static void hn_start_txeof(struct hn_tx_ring *);
322 static int hn_ifmedia_upd(struct ifnet *ifp);
323 static void hn_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr);
324 #if __FreeBSD_version >= 1100099
325 static int hn_lro_lenlim_sysctl(SYSCTL_HANDLER_ARGS);
326 static int hn_lro_ackcnt_sysctl(SYSCTL_HANDLER_ARGS);
327 #endif
328 static int hn_trust_hcsum_sysctl(SYSCTL_HANDLER_ARGS);
329 static int hn_tx_chimney_size_sysctl(SYSCTL_HANDLER_ARGS);
330 #if __FreeBSD_version < 1100095
331 static int hn_rx_stat_int_sysctl(SYSCTL_HANDLER_ARGS);
332 #else
333 static int hn_rx_stat_u64_sysctl(SYSCTL_HANDLER_ARGS);
334 #endif
335 static int hn_rx_stat_ulong_sysctl(SYSCTL_HANDLER_ARGS);
336 static int hn_tx_stat_ulong_sysctl(SYSCTL_HANDLER_ARGS);
337 static int hn_tx_conf_int_sysctl(SYSCTL_HANDLER_ARGS);
338 static int hn_check_iplen(const struct mbuf *, int);
339 static int hn_create_tx_ring(struct hn_softc *, int);
340 static void hn_destroy_tx_ring(struct hn_tx_ring *);
341 static int hn_create_tx_data(struct hn_softc *, int);
342 static void hn_destroy_tx_data(struct hn_softc *);
343 static void hn_start_taskfunc(void *, int);
344 static void hn_start_txeof_taskfunc(void *, int);
345 static void hn_stop_tx_tasks(struct hn_softc *);
346 static int hn_encap(struct hn_tx_ring *, struct hn_txdesc *, struct mbuf **);
347 static void hn_create_rx_data(struct hn_softc *sc, int);
348 static void hn_destroy_rx_data(struct hn_softc *sc);
349 static void hn_set_tx_chimney_size(struct hn_softc *, int);
350 static void hn_channel_attach(struct hn_softc *, struct hv_vmbus_channel *);
351 static void hn_subchan_attach(struct hn_softc *, struct hv_vmbus_channel *);
352 static void hn_subchan_setup(struct hn_softc *);
353
354 static int hn_transmit(struct ifnet *, struct mbuf *);
355 static void hn_xmit_qflush(struct ifnet *);
356 static int hn_xmit(struct hn_tx_ring *, int);
357 static void hn_xmit_txeof(struct hn_tx_ring *);
358 static void hn_xmit_taskfunc(void *, int);
359 static void hn_xmit_txeof_taskfunc(void *, int);
360
361 #if __FreeBSD_version >= 1100099
362 static void
363 hn_set_lro_lenlim(struct hn_softc *sc, int lenlim)
364 {
365         int i;
366
367         for (i = 0; i < sc->hn_rx_ring_inuse; ++i)
368                 sc->hn_rx_ring[i].hn_lro.lro_length_lim = lenlim;
369 }
370 #endif
371
372 static int
373 hn_get_txswq_depth(const struct hn_tx_ring *txr)
374 {
375
376         KASSERT(txr->hn_txdesc_cnt > 0, ("tx ring is not setup yet"));
377         if (hn_tx_swq_depth < txr->hn_txdesc_cnt)
378                 return txr->hn_txdesc_cnt;
379         return hn_tx_swq_depth;
380 }
381
382 static int
383 hn_ifmedia_upd(struct ifnet *ifp __unused)
384 {
385
386         return EOPNOTSUPP;
387 }
388
389 static void
390 hn_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr)
391 {
392         struct hn_softc *sc = ifp->if_softc;
393
394         ifmr->ifm_status = IFM_AVALID;
395         ifmr->ifm_active = IFM_ETHER;
396
397         if (!sc->hn_carrier) {
398                 ifmr->ifm_active |= IFM_NONE;
399                 return;
400         }
401         ifmr->ifm_status |= IFM_ACTIVE;
402         ifmr->ifm_active |= IFM_10G_T | IFM_FDX;
403 }
404
405 /* {F8615163-DF3E-46c5-913F-F2D2F965ED0E} */
406 static const hv_guid g_net_vsc_device_type = {
407         .data = {0x63, 0x51, 0x61, 0xF8, 0x3E, 0xDF, 0xc5, 0x46,
408                 0x91, 0x3F, 0xF2, 0xD2, 0xF9, 0x65, 0xED, 0x0E}
409 };
410
411 /*
412  * Standard probe entry point.
413  *
414  */
415 static int
416 netvsc_probe(device_t dev)
417 {
418         const char *p;
419
420         p = vmbus_get_type(dev);
421         if (!memcmp(p, &g_net_vsc_device_type.data, sizeof(hv_guid))) {
422                 device_set_desc(dev, "Hyper-V Network Interface");
423                 if (bootverbose)
424                         printf("Netvsc probe... DONE \n");
425
426                 return (BUS_PROBE_DEFAULT);
427         }
428
429         return (ENXIO);
430 }
431
432 static void
433 hn_cpuset_setthread_task(void *xmask, int pending __unused)
434 {
435         cpuset_t *mask = xmask;
436         int error;
437
438         error = cpuset_setthread(curthread->td_tid, mask);
439         if (error) {
440                 panic("curthread=%ju: can't pin; error=%d",
441                     (uintmax_t)curthread->td_tid, error);
442         }
443 }
444
445 /*
446  * Standard attach entry point.
447  *
448  * Called when the driver is loaded.  It allocates needed resources,
449  * and initializes the "hardware" and software.
450  */
451 static int
452 netvsc_attach(device_t dev)
453 {
454         struct hv_device *device_ctx = vmbus_get_devctx(dev);
455         struct hv_vmbus_channel *pri_chan;
456         netvsc_device_info device_info;
457         hn_softc_t *sc;
458         int unit = device_get_unit(dev);
459         struct ifnet *ifp = NULL;
460         int error, ring_cnt, tx_ring_cnt;
461         int tso_maxlen;
462
463         sc = device_get_softc(dev);
464
465         sc->hn_unit = unit;
466         sc->hn_dev = dev;
467
468         if (hn_tx_taskq == NULL) {
469                 sc->hn_tx_taskq = taskqueue_create("hn_tx", M_WAITOK,
470                     taskqueue_thread_enqueue, &sc->hn_tx_taskq);
471                 taskqueue_start_threads(&sc->hn_tx_taskq, 1, PI_NET, "%s tx",
472                     device_get_nameunit(dev));
473                 if (hn_bind_tx_taskq >= 0) {
474                         int cpu = hn_bind_tx_taskq;
475                         struct task cpuset_task;
476                         cpuset_t cpu_set;
477
478                         if (cpu > mp_ncpus - 1)
479                                 cpu = mp_ncpus - 1;
480                         CPU_SETOF(cpu, &cpu_set);
481                         TASK_INIT(&cpuset_task, 0, hn_cpuset_setthread_task,
482                             &cpu_set);
483                         taskqueue_enqueue(sc->hn_tx_taskq, &cpuset_task);
484                         taskqueue_drain(sc->hn_tx_taskq, &cpuset_task);
485                 }
486         } else {
487                 sc->hn_tx_taskq = hn_tx_taskq;
488         }
489         NV_LOCK_INIT(sc, "NetVSCLock");
490
491         sc->hn_dev_obj = device_ctx;
492
493         ifp = sc->hn_ifp = sc->arpcom.ac_ifp = if_alloc(IFT_ETHER);
494         ifp->if_softc = sc;
495         if_initname(ifp, device_get_name(dev), device_get_unit(dev));
496
497         /*
498          * Figure out the # of RX rings (ring_cnt) and the # of TX rings
499          * to use (tx_ring_cnt).
500          *
501          * NOTE:
502          * The # of RX rings to use is same as the # of channels to use.
503          */
504         ring_cnt = hn_chan_cnt;
505         if (ring_cnt <= 0) {
506                 /* Default */
507                 ring_cnt = mp_ncpus;
508                 if (ring_cnt > HN_RING_CNT_DEF_MAX)
509                         ring_cnt = HN_RING_CNT_DEF_MAX;
510         } else if (ring_cnt > mp_ncpus) {
511                 ring_cnt = mp_ncpus;
512         }
513
514         tx_ring_cnt = hn_tx_ring_cnt;
515         if (tx_ring_cnt <= 0 || tx_ring_cnt > ring_cnt)
516                 tx_ring_cnt = ring_cnt;
517         if (hn_use_if_start) {
518                 /* ifnet.if_start only needs one TX ring. */
519                 tx_ring_cnt = 1;
520         }
521
522         /*
523          * Set the leader CPU for channels.
524          */
525         sc->hn_cpu = atomic_fetchadd_int(&hn_cpu_index, ring_cnt) % mp_ncpus;
526
527         error = hn_create_tx_data(sc, tx_ring_cnt);
528         if (error)
529                 goto failed;
530         hn_create_rx_data(sc, ring_cnt);
531
532         /*
533          * Associate the first TX/RX ring w/ the primary channel.
534          */
535         pri_chan = device_ctx->channel;
536         KASSERT(HV_VMBUS_CHAN_ISPRIMARY(pri_chan), ("not primary channel"));
537         KASSERT(pri_chan->offer_msg.offer.sub_channel_index == 0,
538             ("primary channel subidx %u",
539              pri_chan->offer_msg.offer.sub_channel_index));
540         hn_channel_attach(sc, pri_chan);
541
542         ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
543         ifp->if_ioctl = hn_ioctl;
544         ifp->if_init = hn_ifinit;
545         /* needed by hv_rf_on_device_add() code */
546         ifp->if_mtu = ETHERMTU;
547         if (hn_use_if_start) {
548                 int qdepth = hn_get_txswq_depth(&sc->hn_tx_ring[0]);
549
550                 ifp->if_start = hn_start;
551                 IFQ_SET_MAXLEN(&ifp->if_snd, qdepth);
552                 ifp->if_snd.ifq_drv_maxlen = qdepth - 1;
553                 IFQ_SET_READY(&ifp->if_snd);
554         } else {
555                 ifp->if_transmit = hn_transmit;
556                 ifp->if_qflush = hn_xmit_qflush;
557         }
558
559         ifmedia_init(&sc->hn_media, 0, hn_ifmedia_upd, hn_ifmedia_sts);
560         ifmedia_add(&sc->hn_media, IFM_ETHER | IFM_AUTO, 0, NULL);
561         ifmedia_set(&sc->hn_media, IFM_ETHER | IFM_AUTO);
562         /* XXX ifmedia_set really should do this for us */
563         sc->hn_media.ifm_media = sc->hn_media.ifm_cur->ifm_media;
564
565         /*
566          * Tell upper layers that we support full VLAN capability.
567          */
568         ifp->if_data.ifi_hdrlen = sizeof(struct ether_vlan_header);
569         ifp->if_capabilities |=
570             IFCAP_VLAN_HWTAGGING | IFCAP_VLAN_MTU | IFCAP_HWCSUM | IFCAP_TSO |
571             IFCAP_LRO;
572         ifp->if_capenable |=
573             IFCAP_VLAN_HWTAGGING | IFCAP_VLAN_MTU | IFCAP_HWCSUM | IFCAP_TSO |
574             IFCAP_LRO;
575         ifp->if_hwassist = sc->hn_tx_ring[0].hn_csum_assist | CSUM_TSO;
576
577         error = hv_rf_on_device_add(device_ctx, &device_info, ring_cnt);
578         if (error)
579                 goto failed;
580         KASSERT(sc->net_dev->num_channel > 0 &&
581             sc->net_dev->num_channel <= sc->hn_rx_ring_inuse,
582             ("invalid channel count %u, should be less than %d",
583              sc->net_dev->num_channel, sc->hn_rx_ring_inuse));
584
585         /*
586          * Set the # of TX/RX rings that could be used according to
587          * the # of channels that host offered.
588          */
589         if (sc->hn_tx_ring_inuse > sc->net_dev->num_channel)
590                 sc->hn_tx_ring_inuse = sc->net_dev->num_channel;
591         sc->hn_rx_ring_inuse = sc->net_dev->num_channel;
592         device_printf(dev, "%d TX ring, %d RX ring\n",
593             sc->hn_tx_ring_inuse, sc->hn_rx_ring_inuse);
594
595         if (sc->net_dev->num_channel > 1)
596                 hn_subchan_setup(sc);
597
598 #if __FreeBSD_version >= 1100099
599         if (sc->hn_rx_ring_inuse > 1) {
600                 /*
601                  * Reduce TCP segment aggregation limit for multiple
602                  * RX rings to increase ACK timeliness.
603                  */
604                 hn_set_lro_lenlim(sc, HN_LRO_LENLIM_MULTIRX_DEF);
605         }
606 #endif
607
608         if (device_info.link_state == 0) {
609                 sc->hn_carrier = 1;
610         }
611
612         tso_maxlen = hn_tso_maxlen;
613         if (tso_maxlen <= 0 || tso_maxlen > IP_MAXPACKET)
614                 tso_maxlen = IP_MAXPACKET;
615
616         ifp->if_hw_tsomaxsegcount = HN_TX_DATA_SEGCNT_MAX;
617         ifp->if_hw_tsomaxsegsize = PAGE_SIZE;
618         ifp->if_hw_tsomax = tso_maxlen -
619             (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
620
621         ether_ifattach(ifp, device_info.mac_addr);
622
623         if_printf(ifp, "TSO: %u/%u/%u\n", ifp->if_hw_tsomax,
624             ifp->if_hw_tsomaxsegcount, ifp->if_hw_tsomaxsegsize);
625
626         sc->hn_tx_chimney_max = sc->net_dev->send_section_size;
627         hn_set_tx_chimney_size(sc, sc->hn_tx_chimney_max);
628         if (hn_tx_chimney_size > 0 &&
629             hn_tx_chimney_size < sc->hn_tx_chimney_max)
630                 hn_set_tx_chimney_size(sc, hn_tx_chimney_size);
631
632         return (0);
633 failed:
634         hn_destroy_tx_data(sc);
635         if (ifp != NULL)
636                 if_free(ifp);
637         return (error);
638 }
639
640 /*
641  * Standard detach entry point
642  */
643 static int
644 netvsc_detach(device_t dev)
645 {
646         struct hn_softc *sc = device_get_softc(dev);
647         struct hv_device *hv_device = vmbus_get_devctx(dev); 
648
649         if (bootverbose)
650                 printf("netvsc_detach\n");
651
652         /*
653          * XXXKYS:  Need to clean up all our
654          * driver state; this is the driver
655          * unloading.
656          */
657
658         /*
659          * XXXKYS:  Need to stop outgoing traffic and unregister
660          * the netdevice.
661          */
662
663         hv_rf_on_device_remove(hv_device, HV_RF_NV_DESTROY_CHANNEL);
664
665         hn_stop_tx_tasks(sc);
666
667         ifmedia_removeall(&sc->hn_media);
668         hn_destroy_rx_data(sc);
669         hn_destroy_tx_data(sc);
670
671         if (sc->hn_tx_taskq != hn_tx_taskq)
672                 taskqueue_free(sc->hn_tx_taskq);
673
674         return (0);
675 }
676
677 /*
678  * Standard shutdown entry point
679  */
680 static int
681 netvsc_shutdown(device_t dev)
682 {
683         return (0);
684 }
685
686 static __inline int
687 hn_txdesc_dmamap_load(struct hn_tx_ring *txr, struct hn_txdesc *txd,
688     struct mbuf **m_head, bus_dma_segment_t *segs, int *nsegs)
689 {
690         struct mbuf *m = *m_head;
691         int error;
692
693         error = bus_dmamap_load_mbuf_sg(txr->hn_tx_data_dtag, txd->data_dmap,
694             m, segs, nsegs, BUS_DMA_NOWAIT);
695         if (error == EFBIG) {
696                 struct mbuf *m_new;
697
698                 m_new = m_collapse(m, M_NOWAIT, HN_TX_DATA_SEGCNT_MAX);
699                 if (m_new == NULL)
700                         return ENOBUFS;
701                 else
702                         *m_head = m = m_new;
703                 txr->hn_tx_collapsed++;
704
705                 error = bus_dmamap_load_mbuf_sg(txr->hn_tx_data_dtag,
706                     txd->data_dmap, m, segs, nsegs, BUS_DMA_NOWAIT);
707         }
708         if (!error) {
709                 bus_dmamap_sync(txr->hn_tx_data_dtag, txd->data_dmap,
710                     BUS_DMASYNC_PREWRITE);
711                 txd->flags |= HN_TXD_FLAG_DMAMAP;
712         }
713         return error;
714 }
715
716 static __inline void
717 hn_txdesc_dmamap_unload(struct hn_tx_ring *txr, struct hn_txdesc *txd)
718 {
719
720         if (txd->flags & HN_TXD_FLAG_DMAMAP) {
721                 bus_dmamap_sync(txr->hn_tx_data_dtag,
722                     txd->data_dmap, BUS_DMASYNC_POSTWRITE);
723                 bus_dmamap_unload(txr->hn_tx_data_dtag,
724                     txd->data_dmap);
725                 txd->flags &= ~HN_TXD_FLAG_DMAMAP;
726         }
727 }
728
729 static __inline int
730 hn_txdesc_put(struct hn_tx_ring *txr, struct hn_txdesc *txd)
731 {
732
733         KASSERT((txd->flags & HN_TXD_FLAG_ONLIST) == 0,
734             ("put an onlist txd %#x", txd->flags));
735
736         KASSERT(txd->refs > 0, ("invalid txd refs %d", txd->refs));
737         if (atomic_fetchadd_int(&txd->refs, -1) != 1)
738                 return 0;
739
740         hn_txdesc_dmamap_unload(txr, txd);
741         if (txd->m != NULL) {
742                 m_freem(txd->m);
743                 txd->m = NULL;
744         }
745
746         txd->flags |= HN_TXD_FLAG_ONLIST;
747
748 #ifndef HN_USE_TXDESC_BUFRING
749         mtx_lock_spin(&txr->hn_txlist_spin);
750         KASSERT(txr->hn_txdesc_avail >= 0 &&
751             txr->hn_txdesc_avail < txr->hn_txdesc_cnt,
752             ("txdesc_put: invalid txd avail %d", txr->hn_txdesc_avail));
753         txr->hn_txdesc_avail++;
754         SLIST_INSERT_HEAD(&txr->hn_txlist, txd, link);
755         mtx_unlock_spin(&txr->hn_txlist_spin);
756 #else
757         atomic_add_int(&txr->hn_txdesc_avail, 1);
758         buf_ring_enqueue(txr->hn_txdesc_br, txd);
759 #endif
760
761         return 1;
762 }
763
764 static __inline struct hn_txdesc *
765 hn_txdesc_get(struct hn_tx_ring *txr)
766 {
767         struct hn_txdesc *txd;
768
769 #ifndef HN_USE_TXDESC_BUFRING
770         mtx_lock_spin(&txr->hn_txlist_spin);
771         txd = SLIST_FIRST(&txr->hn_txlist);
772         if (txd != NULL) {
773                 KASSERT(txr->hn_txdesc_avail > 0,
774                     ("txdesc_get: invalid txd avail %d", txr->hn_txdesc_avail));
775                 txr->hn_txdesc_avail--;
776                 SLIST_REMOVE_HEAD(&txr->hn_txlist, link);
777         }
778         mtx_unlock_spin(&txr->hn_txlist_spin);
779 #else
780         txd = buf_ring_dequeue_sc(txr->hn_txdesc_br);
781 #endif
782
783         if (txd != NULL) {
784 #ifdef HN_USE_TXDESC_BUFRING
785                 atomic_subtract_int(&txr->hn_txdesc_avail, 1);
786 #endif
787                 KASSERT(txd->m == NULL && txd->refs == 0 &&
788                     (txd->flags & HN_TXD_FLAG_ONLIST), ("invalid txd"));
789                 txd->flags &= ~HN_TXD_FLAG_ONLIST;
790                 txd->refs = 1;
791         }
792         return txd;
793 }
794
795 static __inline void
796 hn_txdesc_hold(struct hn_txdesc *txd)
797 {
798
799         /* 0->1 transition will never work */
800         KASSERT(txd->refs > 0, ("invalid refs %d", txd->refs));
801         atomic_add_int(&txd->refs, 1);
802 }
803
804 static __inline void
805 hn_txeof(struct hn_tx_ring *txr)
806 {
807         txr->hn_has_txeof = 0;
808         txr->hn_txeof(txr);
809 }
810
811 static void
812 hn_tx_done(struct hv_vmbus_channel *chan, void *xpkt)
813 {
814         netvsc_packet *packet = xpkt;
815         struct hn_txdesc *txd;
816         struct hn_tx_ring *txr;
817
818         txd = (struct hn_txdesc *)(uintptr_t)
819             packet->compl.send.send_completion_tid;
820
821         txr = txd->txr;
822         KASSERT(txr->hn_chan == chan,
823             ("channel mismatch, on channel%u, should be channel%u",
824              chan->offer_msg.offer.sub_channel_index,
825              txr->hn_chan->offer_msg.offer.sub_channel_index));
826
827         txr->hn_has_txeof = 1;
828         hn_txdesc_put(txr, txd);
829
830         ++txr->hn_txdone_cnt;
831         if (txr->hn_txdone_cnt >= HN_EARLY_TXEOF_THRESH) {
832                 txr->hn_txdone_cnt = 0;
833                 if (txr->hn_oactive)
834                         hn_txeof(txr);
835         }
836 }
837
838 void
839 netvsc_channel_rollup(struct hv_vmbus_channel *chan)
840 {
841         struct hn_tx_ring *txr = chan->hv_chan_txr;
842 #if defined(INET) || defined(INET6)
843         struct hn_rx_ring *rxr = chan->hv_chan_rxr;
844         struct lro_ctrl *lro = &rxr->hn_lro;
845         struct lro_entry *queued;
846
847         while ((queued = SLIST_FIRST(&lro->lro_active)) != NULL) {
848                 SLIST_REMOVE_HEAD(&lro->lro_active, next);
849                 tcp_lro_flush(lro, queued);
850         }
851 #endif
852
853         /*
854          * NOTE:
855          * 'txr' could be NULL, if multiple channels and
856          * ifnet.if_start method are enabled.
857          */
858         if (txr == NULL || !txr->hn_has_txeof)
859                 return;
860
861         txr->hn_txdone_cnt = 0;
862         hn_txeof(txr);
863 }
864
865 /*
866  * NOTE:
867  * If this function fails, then both txd and m_head0 will be freed.
868  */
869 static int
870 hn_encap(struct hn_tx_ring *txr, struct hn_txdesc *txd, struct mbuf **m_head0)
871 {
872         bus_dma_segment_t segs[HN_TX_DATA_SEGCNT_MAX];
873         int error, nsegs, i;
874         struct mbuf *m_head = *m_head0;
875         netvsc_packet *packet;
876         rndis_msg *rndis_mesg;
877         rndis_packet *rndis_pkt;
878         rndis_per_packet_info *rppi;
879         struct rndis_hash_value *hash_value;
880         uint32_t rndis_msg_size;
881
882         packet = &txd->netvsc_pkt;
883         packet->is_data_pkt = TRUE;
884         packet->tot_data_buf_len = m_head->m_pkthdr.len;
885
886         /*
887          * extension points to the area reserved for the
888          * rndis_filter_packet, which is placed just after
889          * the netvsc_packet (and rppi struct, if present;
890          * length is updated later).
891          */
892         rndis_mesg = txd->rndis_msg;
893         /* XXX not necessary */
894         memset(rndis_mesg, 0, HN_RNDIS_MSG_LEN);
895         rndis_mesg->ndis_msg_type = REMOTE_NDIS_PACKET_MSG;
896
897         rndis_pkt = &rndis_mesg->msg.packet;
898         rndis_pkt->data_offset = sizeof(rndis_packet);
899         rndis_pkt->data_length = packet->tot_data_buf_len;
900         rndis_pkt->per_pkt_info_offset = sizeof(rndis_packet);
901
902         rndis_msg_size = RNDIS_MESSAGE_SIZE(rndis_packet);
903
904         /*
905          * Set the hash value for this packet, so that the host could
906          * dispatch the TX done event for this packet back to this TX
907          * ring's channel.
908          */
909         rndis_msg_size += RNDIS_HASHVAL_PPI_SIZE;
910         rppi = hv_set_rppi_data(rndis_mesg, RNDIS_HASHVAL_PPI_SIZE,
911             nbl_hash_value);
912         hash_value = (struct rndis_hash_value *)((uint8_t *)rppi +
913             rppi->per_packet_info_offset);
914         hash_value->hash_value = txr->hn_tx_idx;
915
916         if (m_head->m_flags & M_VLANTAG) {
917                 ndis_8021q_info *rppi_vlan_info;
918
919                 rndis_msg_size += RNDIS_VLAN_PPI_SIZE;
920                 rppi = hv_set_rppi_data(rndis_mesg, RNDIS_VLAN_PPI_SIZE,
921                     ieee_8021q_info);
922
923                 rppi_vlan_info = (ndis_8021q_info *)((uint8_t *)rppi +
924                     rppi->per_packet_info_offset);
925                 rppi_vlan_info->u1.s1.vlan_id =
926                     m_head->m_pkthdr.ether_vtag & 0xfff;
927         }
928
929         if (m_head->m_pkthdr.csum_flags & CSUM_TSO) {
930                 rndis_tcp_tso_info *tso_info;   
931                 struct ether_vlan_header *eh;
932                 int ether_len;
933
934                 /*
935                  * XXX need m_pullup and use mtodo
936                  */
937                 eh = mtod(m_head, struct ether_vlan_header*);
938                 if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN))
939                         ether_len = ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN;
940                 else
941                         ether_len = ETHER_HDR_LEN;
942
943                 rndis_msg_size += RNDIS_TSO_PPI_SIZE;
944                 rppi = hv_set_rppi_data(rndis_mesg, RNDIS_TSO_PPI_SIZE,
945                     tcp_large_send_info);
946
947                 tso_info = (rndis_tcp_tso_info *)((uint8_t *)rppi +
948                     rppi->per_packet_info_offset);
949                 tso_info->lso_v2_xmit.type =
950                     RNDIS_TCP_LARGE_SEND_OFFLOAD_V2_TYPE;
951
952 #ifdef INET
953                 if (m_head->m_pkthdr.csum_flags & CSUM_IP_TSO) {
954                         struct ip *ip =
955                             (struct ip *)(m_head->m_data + ether_len);
956                         unsigned long iph_len = ip->ip_hl << 2;
957                         struct tcphdr *th =
958                             (struct tcphdr *)((caddr_t)ip + iph_len);
959
960                         tso_info->lso_v2_xmit.ip_version =
961                             RNDIS_TCP_LARGE_SEND_OFFLOAD_IPV4;
962                         ip->ip_len = 0;
963                         ip->ip_sum = 0;
964
965                         th->th_sum = in_pseudo(ip->ip_src.s_addr,
966                             ip->ip_dst.s_addr, htons(IPPROTO_TCP));
967                 }
968 #endif
969 #if defined(INET6) && defined(INET)
970                 else
971 #endif
972 #ifdef INET6
973                 {
974                         struct ip6_hdr *ip6 = (struct ip6_hdr *)
975                             (m_head->m_data + ether_len);
976                         struct tcphdr *th = (struct tcphdr *)(ip6 + 1);
977
978                         tso_info->lso_v2_xmit.ip_version =
979                             RNDIS_TCP_LARGE_SEND_OFFLOAD_IPV6;
980                         ip6->ip6_plen = 0;
981                         th->th_sum = in6_cksum_pseudo(ip6, 0, IPPROTO_TCP, 0);
982                 }
983 #endif
984                 tso_info->lso_v2_xmit.tcp_header_offset = 0;
985                 tso_info->lso_v2_xmit.mss = m_head->m_pkthdr.tso_segsz;
986         } else if (m_head->m_pkthdr.csum_flags & txr->hn_csum_assist) {
987                 rndis_tcp_ip_csum_info *csum_info;
988
989                 rndis_msg_size += RNDIS_CSUM_PPI_SIZE;
990                 rppi = hv_set_rppi_data(rndis_mesg, RNDIS_CSUM_PPI_SIZE,
991                     tcpip_chksum_info);
992                 csum_info = (rndis_tcp_ip_csum_info *)((uint8_t *)rppi +
993                     rppi->per_packet_info_offset);
994
995                 csum_info->xmit.is_ipv4 = 1;
996                 if (m_head->m_pkthdr.csum_flags & CSUM_IP)
997                         csum_info->xmit.ip_header_csum = 1;
998
999                 if (m_head->m_pkthdr.csum_flags & CSUM_TCP) {
1000                         csum_info->xmit.tcp_csum = 1;
1001                         csum_info->xmit.tcp_header_offset = 0;
1002                 } else if (m_head->m_pkthdr.csum_flags & CSUM_UDP) {
1003                         csum_info->xmit.udp_csum = 1;
1004                 }
1005         }
1006
1007         rndis_mesg->msg_len = packet->tot_data_buf_len + rndis_msg_size;
1008         packet->tot_data_buf_len = rndis_mesg->msg_len;
1009
1010         /*
1011          * Chimney send, if the packet could fit into one chimney buffer.
1012          */
1013         if (packet->tot_data_buf_len < txr->hn_tx_chimney_size) {
1014                 netvsc_dev *net_dev = txr->hn_sc->net_dev;
1015                 uint32_t send_buf_section_idx;
1016
1017                 txr->hn_tx_chimney_tried++;
1018                 send_buf_section_idx =
1019                     hv_nv_get_next_send_section(net_dev);
1020                 if (send_buf_section_idx !=
1021                     NVSP_1_CHIMNEY_SEND_INVALID_SECTION_INDEX) {
1022                         uint8_t *dest = ((uint8_t *)net_dev->send_buf +
1023                             (send_buf_section_idx *
1024                              net_dev->send_section_size));
1025
1026                         memcpy(dest, rndis_mesg, rndis_msg_size);
1027                         dest += rndis_msg_size;
1028                         m_copydata(m_head, 0, m_head->m_pkthdr.len, dest);
1029
1030                         packet->send_buf_section_idx = send_buf_section_idx;
1031                         packet->send_buf_section_size =
1032                             packet->tot_data_buf_len;
1033                         packet->page_buf_count = 0;
1034                         txr->hn_tx_chimney++;
1035                         goto done;
1036                 }
1037         }
1038
1039         error = hn_txdesc_dmamap_load(txr, txd, &m_head, segs, &nsegs);
1040         if (error) {
1041                 int freed;
1042
1043                 /*
1044                  * This mbuf is not linked w/ the txd yet, so free it now.
1045                  */
1046                 m_freem(m_head);
1047                 *m_head0 = NULL;
1048
1049                 freed = hn_txdesc_put(txr, txd);
1050                 KASSERT(freed != 0,
1051                     ("fail to free txd upon txdma error"));
1052
1053                 txr->hn_txdma_failed++;
1054                 if_inc_counter(txr->hn_sc->hn_ifp, IFCOUNTER_OERRORS, 1);
1055                 return error;
1056         }
1057         *m_head0 = m_head;
1058
1059         packet->page_buf_count = nsegs + HV_RF_NUM_TX_RESERVED_PAGE_BUFS;
1060
1061         /* send packet with page buffer */
1062         packet->page_buffers[0].pfn = atop(txd->rndis_msg_paddr);
1063         packet->page_buffers[0].offset = txd->rndis_msg_paddr & PAGE_MASK;
1064         packet->page_buffers[0].length = rndis_msg_size;
1065
1066         /*
1067          * Fill the page buffers with mbuf info starting at index
1068          * HV_RF_NUM_TX_RESERVED_PAGE_BUFS.
1069          */
1070         for (i = 0; i < nsegs; ++i) {
1071                 hv_vmbus_page_buffer *pb = &packet->page_buffers[
1072                     i + HV_RF_NUM_TX_RESERVED_PAGE_BUFS];
1073
1074                 pb->pfn = atop(segs[i].ds_addr);
1075                 pb->offset = segs[i].ds_addr & PAGE_MASK;
1076                 pb->length = segs[i].ds_len;
1077         }
1078
1079         packet->send_buf_section_idx =
1080             NVSP_1_CHIMNEY_SEND_INVALID_SECTION_INDEX;
1081         packet->send_buf_section_size = 0;
1082 done:
1083         txd->m = m_head;
1084
1085         /* Set the completion routine */
1086         packet->compl.send.on_send_completion = hn_tx_done;
1087         packet->compl.send.send_completion_context = packet;
1088         packet->compl.send.send_completion_tid = (uint64_t)(uintptr_t)txd;
1089
1090         return 0;
1091 }
1092
1093 /*
1094  * NOTE:
1095  * If this function fails, then txd will be freed, but the mbuf
1096  * associated w/ the txd will _not_ be freed.
1097  */
1098 static int
1099 hn_send_pkt(struct ifnet *ifp, struct hn_tx_ring *txr, struct hn_txdesc *txd)
1100 {
1101         int error, send_failed = 0;
1102
1103 again:
1104         /*
1105          * Make sure that txd is not freed before ETHER_BPF_MTAP.
1106          */
1107         hn_txdesc_hold(txd);
1108         error = hv_nv_on_send(txr->hn_chan, &txd->netvsc_pkt);
1109         if (!error) {
1110                 ETHER_BPF_MTAP(ifp, txd->m);
1111                 if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1);
1112                 if (!hn_use_if_start) {
1113                         if_inc_counter(ifp, IFCOUNTER_OBYTES,
1114                             txd->m->m_pkthdr.len);
1115                         if (txd->m->m_flags & M_MCAST)
1116                                 if_inc_counter(ifp, IFCOUNTER_OMCASTS, 1);
1117                 }
1118                 txr->hn_pkts++;
1119         }
1120         hn_txdesc_put(txr, txd);
1121
1122         if (__predict_false(error)) {
1123                 int freed;
1124
1125                 /*
1126                  * This should "really rarely" happen.
1127                  *
1128                  * XXX Too many RX to be acked or too many sideband
1129                  * commands to run?  Ask netvsc_channel_rollup()
1130                  * to kick start later.
1131                  */
1132                 txr->hn_has_txeof = 1;
1133                 if (!send_failed) {
1134                         txr->hn_send_failed++;
1135                         send_failed = 1;
1136                         /*
1137                          * Try sending again after set hn_has_txeof;
1138                          * in case that we missed the last
1139                          * netvsc_channel_rollup().
1140                          */
1141                         goto again;
1142                 }
1143                 if_printf(ifp, "send failed\n");
1144
1145                 /*
1146                  * Caller will perform further processing on the
1147                  * associated mbuf, so don't free it in hn_txdesc_put();
1148                  * only unload it from the DMA map in hn_txdesc_put(),
1149                  * if it was loaded.
1150                  */
1151                 txd->m = NULL;
1152                 freed = hn_txdesc_put(txr, txd);
1153                 KASSERT(freed != 0,
1154                     ("fail to free txd upon send error"));
1155
1156                 txr->hn_send_failed++;
1157         }
1158         return error;
1159 }
1160
1161 /*
1162  * Start a transmit of one or more packets
1163  */
1164 static int
1165 hn_start_locked(struct hn_tx_ring *txr, int len)
1166 {
1167         struct hn_softc *sc = txr->hn_sc;
1168         struct ifnet *ifp = sc->hn_ifp;
1169
1170         KASSERT(hn_use_if_start,
1171             ("hn_start_locked is called, when if_start is disabled"));
1172         KASSERT(txr == &sc->hn_tx_ring[0], ("not the first TX ring"));
1173         mtx_assert(&txr->hn_tx_lock, MA_OWNED);
1174
1175         if ((ifp->if_drv_flags & (IFF_DRV_RUNNING | IFF_DRV_OACTIVE)) !=
1176             IFF_DRV_RUNNING)
1177                 return 0;
1178
1179         while (!IFQ_DRV_IS_EMPTY(&ifp->if_snd)) {
1180                 struct hn_txdesc *txd;
1181                 struct mbuf *m_head;
1182                 int error;
1183
1184                 IFQ_DRV_DEQUEUE(&ifp->if_snd, m_head);
1185                 if (m_head == NULL)
1186                         break;
1187
1188                 if (len > 0 && m_head->m_pkthdr.len > len) {
1189                         /*
1190                          * This sending could be time consuming; let callers
1191                          * dispatch this packet sending (and sending of any
1192                          * following up packets) to tx taskqueue.
1193                          */
1194                         IFQ_DRV_PREPEND(&ifp->if_snd, m_head);
1195                         return 1;
1196                 }
1197
1198                 txd = hn_txdesc_get(txr);
1199                 if (txd == NULL) {
1200                         txr->hn_no_txdescs++;
1201                         IFQ_DRV_PREPEND(&ifp->if_snd, m_head);
1202                         atomic_set_int(&ifp->if_drv_flags, IFF_DRV_OACTIVE);
1203                         break;
1204                 }
1205
1206                 error = hn_encap(txr, txd, &m_head);
1207                 if (error) {
1208                         /* Both txd and m_head are freed */
1209                         continue;
1210                 }
1211
1212                 error = hn_send_pkt(ifp, txr, txd);
1213                 if (__predict_false(error)) {
1214                         /* txd is freed, but m_head is not */
1215                         IFQ_DRV_PREPEND(&ifp->if_snd, m_head);
1216                         atomic_set_int(&ifp->if_drv_flags, IFF_DRV_OACTIVE);
1217                         break;
1218                 }
1219         }
1220         return 0;
1221 }
1222
1223 /*
1224  * Link up/down notification
1225  */
1226 void
1227 netvsc_linkstatus_callback(struct hv_device *device_obj, uint32_t status)
1228 {
1229         hn_softc_t *sc = device_get_softc(device_obj->device);
1230
1231         if (status == 1) {
1232                 sc->hn_carrier = 1;
1233         } else {
1234                 sc->hn_carrier = 0;
1235         }
1236 }
1237
1238 /*
1239  * Append the specified data to the indicated mbuf chain,
1240  * Extend the mbuf chain if the new data does not fit in
1241  * existing space.
1242  *
1243  * This is a minor rewrite of m_append() from sys/kern/uipc_mbuf.c.
1244  * There should be an equivalent in the kernel mbuf code,
1245  * but there does not appear to be one yet.
1246  *
1247  * Differs from m_append() in that additional mbufs are
1248  * allocated with cluster size MJUMPAGESIZE, and filled
1249  * accordingly.
1250  *
1251  * Return 1 if able to complete the job; otherwise 0.
1252  */
1253 static int
1254 hv_m_append(struct mbuf *m0, int len, c_caddr_t cp)
1255 {
1256         struct mbuf *m, *n;
1257         int remainder, space;
1258
1259         for (m = m0; m->m_next != NULL; m = m->m_next)
1260                 ;
1261         remainder = len;
1262         space = M_TRAILINGSPACE(m);
1263         if (space > 0) {
1264                 /*
1265                  * Copy into available space.
1266                  */
1267                 if (space > remainder)
1268                         space = remainder;
1269                 bcopy(cp, mtod(m, caddr_t) + m->m_len, space);
1270                 m->m_len += space;
1271                 cp += space;
1272                 remainder -= space;
1273         }
1274         while (remainder > 0) {
1275                 /*
1276                  * Allocate a new mbuf; could check space
1277                  * and allocate a cluster instead.
1278                  */
1279                 n = m_getjcl(M_DONTWAIT, m->m_type, 0, MJUMPAGESIZE);
1280                 if (n == NULL)
1281                         break;
1282                 n->m_len = min(MJUMPAGESIZE, remainder);
1283                 bcopy(cp, mtod(n, caddr_t), n->m_len);
1284                 cp += n->m_len;
1285                 remainder -= n->m_len;
1286                 m->m_next = n;
1287                 m = n;
1288         }
1289         if (m0->m_flags & M_PKTHDR)
1290                 m0->m_pkthdr.len += len - remainder;
1291
1292         return (remainder == 0);
1293 }
1294
1295 #if defined(INET) || defined(INET6)
1296 static __inline int
1297 hn_lro_rx(struct lro_ctrl *lc, struct mbuf *m)
1298 {
1299 #if __FreeBSD_version >= 1100095
1300         if (hn_lro_mbufq_depth) {
1301                 tcp_lro_queue_mbuf(lc, m);
1302                 return 0;
1303         }
1304 #endif
1305         return tcp_lro_rx(lc, m, 0);
1306 }
1307 #endif
1308
1309 /*
1310  * Called when we receive a data packet from the "wire" on the
1311  * specified device
1312  *
1313  * Note:  This is no longer used as a callback
1314  */
1315 int
1316 netvsc_recv(struct hv_vmbus_channel *chan, netvsc_packet *packet,
1317     const rndis_tcp_ip_csum_info *csum_info,
1318     const struct rndis_hash_info *hash_info,
1319     const struct rndis_hash_value *hash_value)
1320 {
1321         struct hn_rx_ring *rxr = chan->hv_chan_rxr;
1322         struct ifnet *ifp = rxr->hn_ifp;
1323         struct mbuf *m_new;
1324         int size, do_lro = 0, do_csum = 1;
1325
1326         if (!(ifp->if_drv_flags & IFF_DRV_RUNNING))
1327                 return (0);
1328
1329         /*
1330          * Bail out if packet contains more data than configured MTU.
1331          */
1332         if (packet->tot_data_buf_len > (ifp->if_mtu + ETHER_HDR_LEN)) {
1333                 return (0);
1334         } else if (packet->tot_data_buf_len <= MHLEN) {
1335                 m_new = m_gethdr(M_NOWAIT, MT_DATA);
1336                 if (m_new == NULL) {
1337                         if_inc_counter(ifp, IFCOUNTER_IQDROPS, 1);
1338                         return (0);
1339                 }
1340                 memcpy(mtod(m_new, void *), packet->data,
1341                     packet->tot_data_buf_len);
1342                 m_new->m_pkthdr.len = m_new->m_len = packet->tot_data_buf_len;
1343                 rxr->hn_small_pkts++;
1344         } else {
1345                 /*
1346                  * Get an mbuf with a cluster.  For packets 2K or less,
1347                  * get a standard 2K cluster.  For anything larger, get a
1348                  * 4K cluster.  Any buffers larger than 4K can cause problems
1349                  * if looped around to the Hyper-V TX channel, so avoid them.
1350                  */
1351                 size = MCLBYTES;
1352                 if (packet->tot_data_buf_len > MCLBYTES) {
1353                         /* 4096 */
1354                         size = MJUMPAGESIZE;
1355                 }
1356
1357                 m_new = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, size);
1358                 if (m_new == NULL) {
1359                         if_inc_counter(ifp, IFCOUNTER_IQDROPS, 1);
1360                         return (0);
1361                 }
1362
1363                 hv_m_append(m_new, packet->tot_data_buf_len, packet->data);
1364         }
1365         m_new->m_pkthdr.rcvif = ifp;
1366
1367         if (__predict_false((ifp->if_capenable & IFCAP_RXCSUM) == 0))
1368                 do_csum = 0;
1369
1370         /* receive side checksum offload */
1371         if (csum_info != NULL) {
1372                 /* IP csum offload */
1373                 if (csum_info->receive.ip_csum_succeeded && do_csum) {
1374                         m_new->m_pkthdr.csum_flags |=
1375                             (CSUM_IP_CHECKED | CSUM_IP_VALID);
1376                         rxr->hn_csum_ip++;
1377                 }
1378
1379                 /* TCP/UDP csum offload */
1380                 if ((csum_info->receive.tcp_csum_succeeded ||
1381                      csum_info->receive.udp_csum_succeeded) && do_csum) {
1382                         m_new->m_pkthdr.csum_flags |=
1383                             (CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
1384                         m_new->m_pkthdr.csum_data = 0xffff;
1385                         if (csum_info->receive.tcp_csum_succeeded)
1386                                 rxr->hn_csum_tcp++;
1387                         else
1388                                 rxr->hn_csum_udp++;
1389                 }
1390
1391                 if (csum_info->receive.ip_csum_succeeded &&
1392                     csum_info->receive.tcp_csum_succeeded)
1393                         do_lro = 1;
1394         } else {
1395                 const struct ether_header *eh;
1396                 uint16_t etype;
1397                 int hoff;
1398
1399                 hoff = sizeof(*eh);
1400                 if (m_new->m_len < hoff)
1401                         goto skip;
1402                 eh = mtod(m_new, struct ether_header *);
1403                 etype = ntohs(eh->ether_type);
1404                 if (etype == ETHERTYPE_VLAN) {
1405                         const struct ether_vlan_header *evl;
1406
1407                         hoff = sizeof(*evl);
1408                         if (m_new->m_len < hoff)
1409                                 goto skip;
1410                         evl = mtod(m_new, struct ether_vlan_header *);
1411                         etype = ntohs(evl->evl_proto);
1412                 }
1413
1414                 if (etype == ETHERTYPE_IP) {
1415                         int pr;
1416
1417                         pr = hn_check_iplen(m_new, hoff);
1418                         if (pr == IPPROTO_TCP) {
1419                                 if (do_csum &&
1420                                     (rxr->hn_trust_hcsum &
1421                                      HN_TRUST_HCSUM_TCP)) {
1422                                         rxr->hn_csum_trusted++;
1423                                         m_new->m_pkthdr.csum_flags |=
1424                                            (CSUM_IP_CHECKED | CSUM_IP_VALID |
1425                                             CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
1426                                         m_new->m_pkthdr.csum_data = 0xffff;
1427                                 }
1428                                 do_lro = 1;
1429                         } else if (pr == IPPROTO_UDP) {
1430                                 if (do_csum &&
1431                                     (rxr->hn_trust_hcsum &
1432                                      HN_TRUST_HCSUM_UDP)) {
1433                                         rxr->hn_csum_trusted++;
1434                                         m_new->m_pkthdr.csum_flags |=
1435                                            (CSUM_IP_CHECKED | CSUM_IP_VALID |
1436                                             CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
1437                                         m_new->m_pkthdr.csum_data = 0xffff;
1438                                 }
1439                         } else if (pr != IPPROTO_DONE && do_csum &&
1440                             (rxr->hn_trust_hcsum & HN_TRUST_HCSUM_IP)) {
1441                                 rxr->hn_csum_trusted++;
1442                                 m_new->m_pkthdr.csum_flags |=
1443                                     (CSUM_IP_CHECKED | CSUM_IP_VALID);
1444                         }
1445                 }
1446         }
1447 skip:
1448         if ((packet->vlan_tci != 0) &&
1449             (ifp->if_capenable & IFCAP_VLAN_HWTAGGING) != 0) {
1450                 m_new->m_pkthdr.ether_vtag = packet->vlan_tci;
1451                 m_new->m_flags |= M_VLANTAG;
1452         }
1453
1454         if (hash_info != NULL && hash_value != NULL) {
1455                 int hash_type = M_HASHTYPE_OPAQUE;
1456
1457                 rxr->hn_rss_pkts++;
1458                 m_new->m_pkthdr.flowid = hash_value->hash_value;
1459                 if ((hash_info->hash_info & NDIS_HASH_FUNCTION_MASK) ==
1460                     NDIS_HASH_FUNCTION_TOEPLITZ) {
1461                         uint32_t type =
1462                             (hash_info->hash_info & NDIS_HASH_TYPE_MASK);
1463
1464                         switch (type) {
1465                         case NDIS_HASH_IPV4:
1466                                 hash_type = M_HASHTYPE_RSS_IPV4;
1467                                 break;
1468
1469                         case NDIS_HASH_TCP_IPV4:
1470                                 hash_type = M_HASHTYPE_RSS_TCP_IPV4;
1471                                 break;
1472
1473                         case NDIS_HASH_IPV6:
1474                                 hash_type = M_HASHTYPE_RSS_IPV6;
1475                                 break;
1476
1477                         case NDIS_HASH_IPV6_EX:
1478                                 hash_type = M_HASHTYPE_RSS_IPV6_EX;
1479                                 break;
1480
1481                         case NDIS_HASH_TCP_IPV6:
1482                                 hash_type = M_HASHTYPE_RSS_TCP_IPV6;
1483                                 break;
1484
1485                         case NDIS_HASH_TCP_IPV6_EX:
1486                                 hash_type = M_HASHTYPE_RSS_TCP_IPV6_EX;
1487                                 break;
1488                         }
1489                 }
1490                 M_HASHTYPE_SET(m_new, hash_type);
1491         } else {
1492                 if (hash_value != NULL)
1493                         m_new->m_pkthdr.flowid = hash_value->hash_value;
1494                 else
1495                         m_new->m_pkthdr.flowid = rxr->hn_rx_idx;
1496                 M_HASHTYPE_SET(m_new, M_HASHTYPE_OPAQUE);
1497         }
1498
1499         /*
1500          * Note:  Moved RX completion back to hv_nv_on_receive() so all
1501          * messages (not just data messages) will trigger a response.
1502          */
1503
1504         ifp->if_ipackets++;
1505         rxr->hn_pkts++;
1506
1507         if ((ifp->if_capenable & IFCAP_LRO) && do_lro) {
1508 #if defined(INET) || defined(INET6)
1509                 struct lro_ctrl *lro = &rxr->hn_lro;
1510
1511                 if (lro->lro_cnt) {
1512                         rxr->hn_lro_tried++;
1513                         if (hn_lro_rx(lro, m_new) == 0) {
1514                                 /* DONE! */
1515                                 return 0;
1516                         }
1517                 }
1518 #endif
1519         }
1520
1521         /* We're not holding the lock here, so don't release it */
1522         (*ifp->if_input)(ifp, m_new);
1523
1524         return (0);
1525 }
1526
1527 /*
1528  * Rules for using sc->temp_unusable:
1529  * 1.  sc->temp_unusable can only be read or written while holding NV_LOCK()
1530  * 2.  code reading sc->temp_unusable under NV_LOCK(), and finding 
1531  *     sc->temp_unusable set, must release NV_LOCK() and exit
1532  * 3.  to retain exclusive control of the interface,
1533  *     sc->temp_unusable must be set by code before releasing NV_LOCK()
1534  * 4.  only code setting sc->temp_unusable can clear sc->temp_unusable
1535  * 5.  code setting sc->temp_unusable must eventually clear sc->temp_unusable
1536  */
1537
1538 /*
1539  * Standard ioctl entry point.  Called when the user wants to configure
1540  * the interface.
1541  */
1542 static int
1543 hn_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1544 {
1545         hn_softc_t *sc = ifp->if_softc;
1546         struct ifreq *ifr = (struct ifreq *)data;
1547 #ifdef INET
1548         struct ifaddr *ifa = (struct ifaddr *)data;
1549 #endif
1550         netvsc_device_info device_info;
1551         struct hv_device *hn_dev;
1552         int mask, error = 0;
1553         int retry_cnt = 500;
1554         
1555         switch(cmd) {
1556
1557         case SIOCSIFADDR:
1558 #ifdef INET
1559                 if (ifa->ifa_addr->sa_family == AF_INET) {
1560                         ifp->if_flags |= IFF_UP;
1561                         if (!(ifp->if_drv_flags & IFF_DRV_RUNNING))
1562                                 hn_ifinit(sc);
1563                         arp_ifinit(ifp, ifa);
1564                 } else
1565 #endif
1566                 error = ether_ioctl(ifp, cmd, data);
1567                 break;
1568         case SIOCSIFMTU:
1569                 hn_dev = vmbus_get_devctx(sc->hn_dev);
1570
1571                 /* Check MTU value change */
1572                 if (ifp->if_mtu == ifr->ifr_mtu)
1573                         break;
1574
1575                 if (ifr->ifr_mtu > NETVSC_MAX_CONFIGURABLE_MTU) {
1576                         error = EINVAL;
1577                         break;
1578                 }
1579
1580                 /* Obtain and record requested MTU */
1581                 ifp->if_mtu = ifr->ifr_mtu;
1582
1583 #if __FreeBSD_version >= 1100099
1584                 /*
1585                  * Make sure that LRO aggregation length limit is still
1586                  * valid, after the MTU change.
1587                  */
1588                 NV_LOCK(sc);
1589                 if (sc->hn_rx_ring[0].hn_lro.lro_length_lim <
1590                     HN_LRO_LENLIM_MIN(ifp))
1591                         hn_set_lro_lenlim(sc, HN_LRO_LENLIM_MIN(ifp));
1592                 NV_UNLOCK(sc);
1593 #endif
1594
1595                 do {
1596                         NV_LOCK(sc);
1597                         if (!sc->temp_unusable) {
1598                                 sc->temp_unusable = TRUE;
1599                                 retry_cnt = -1;
1600                         }
1601                         NV_UNLOCK(sc);
1602                         if (retry_cnt > 0) {
1603                                 retry_cnt--;
1604                                 DELAY(5 * 1000);
1605                         }
1606                 } while (retry_cnt > 0);
1607
1608                 if (retry_cnt == 0) {
1609                         error = EINVAL;
1610                         break;
1611                 }
1612
1613                 /* We must remove and add back the device to cause the new
1614                  * MTU to take effect.  This includes tearing down, but not
1615                  * deleting the channel, then bringing it back up.
1616                  */
1617                 error = hv_rf_on_device_remove(hn_dev, HV_RF_NV_RETAIN_CHANNEL);
1618                 if (error) {
1619                         NV_LOCK(sc);
1620                         sc->temp_unusable = FALSE;
1621                         NV_UNLOCK(sc);
1622                         break;
1623                 }
1624
1625                 /* Wait for subchannels to be destroyed */
1626                 vmbus_drain_subchan(hn_dev->channel);
1627
1628                 error = hv_rf_on_device_add(hn_dev, &device_info,
1629                     sc->hn_rx_ring_inuse);
1630                 if (error) {
1631                         NV_LOCK(sc);
1632                         sc->temp_unusable = FALSE;
1633                         NV_UNLOCK(sc);
1634                         break;
1635                 }
1636                 KASSERT(sc->hn_rx_ring_cnt == sc->net_dev->num_channel,
1637                     ("RX ring count %d and channel count %u mismatch",
1638                      sc->hn_rx_ring_cnt, sc->net_dev->num_channel));
1639                 if (sc->net_dev->num_channel > 1) {
1640                         int r;
1641
1642                         /*
1643                          * Skip the rings on primary channel; they are
1644                          * handled by the hv_rf_on_device_add() above.
1645                          */
1646                         for (r = 1; r < sc->hn_rx_ring_cnt; ++r) {
1647                                 sc->hn_rx_ring[r].hn_rx_flags &=
1648                                     ~HN_RX_FLAG_ATTACHED;
1649                         }
1650                         for (r = 1; r < sc->hn_tx_ring_cnt; ++r) {
1651                                 sc->hn_tx_ring[r].hn_tx_flags &=
1652                                     ~HN_TX_FLAG_ATTACHED;
1653                         }
1654                         hn_subchan_setup(sc);
1655                 }
1656
1657                 sc->hn_tx_chimney_max = sc->net_dev->send_section_size;
1658                 if (sc->hn_tx_ring[0].hn_tx_chimney_size >
1659                     sc->hn_tx_chimney_max)
1660                         hn_set_tx_chimney_size(sc, sc->hn_tx_chimney_max);
1661
1662                 hn_ifinit_locked(sc);
1663
1664                 NV_LOCK(sc);
1665                 sc->temp_unusable = FALSE;
1666                 NV_UNLOCK(sc);
1667                 break;
1668         case SIOCSIFFLAGS:
1669                 do {
1670                        NV_LOCK(sc);
1671                        if (!sc->temp_unusable) {
1672                                sc->temp_unusable = TRUE;
1673                                retry_cnt = -1;
1674                        }
1675                        NV_UNLOCK(sc);
1676                        if (retry_cnt > 0) {
1677                                 retry_cnt--;
1678                                 DELAY(5 * 1000);
1679                        }
1680                 } while (retry_cnt > 0);
1681
1682                 if (retry_cnt == 0) {
1683                        error = EINVAL;
1684                        break;
1685                 }
1686
1687                 if (ifp->if_flags & IFF_UP) {
1688                         /*
1689                          * If only the state of the PROMISC flag changed,
1690                          * then just use the 'set promisc mode' command
1691                          * instead of reinitializing the entire NIC. Doing
1692                          * a full re-init means reloading the firmware and
1693                          * waiting for it to start up, which may take a
1694                          * second or two.
1695                          */
1696 #ifdef notyet
1697                         /* Fixme:  Promiscuous mode? */
1698                         if (ifp->if_drv_flags & IFF_DRV_RUNNING &&
1699                             ifp->if_flags & IFF_PROMISC &&
1700                             !(sc->hn_if_flags & IFF_PROMISC)) {
1701                                 /* do something here for Hyper-V */
1702                         } else if (ifp->if_drv_flags & IFF_DRV_RUNNING &&
1703                             !(ifp->if_flags & IFF_PROMISC) &&
1704                             sc->hn_if_flags & IFF_PROMISC) {
1705                                 /* do something here for Hyper-V */
1706                         } else
1707 #endif
1708                                 hn_ifinit_locked(sc);
1709                 } else {
1710                         if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1711                                 hn_stop(sc);
1712                         }
1713                 }
1714                 NV_LOCK(sc);
1715                 sc->temp_unusable = FALSE;
1716                 NV_UNLOCK(sc);
1717                 sc->hn_if_flags = ifp->if_flags;
1718                 error = 0;
1719                 break;
1720         case SIOCSIFCAP:
1721                 NV_LOCK(sc);
1722
1723                 mask = ifr->ifr_reqcap ^ ifp->if_capenable;
1724                 if (mask & IFCAP_TXCSUM) {
1725                         ifp->if_capenable ^= IFCAP_TXCSUM;
1726                         if (ifp->if_capenable & IFCAP_TXCSUM) {
1727                                 ifp->if_hwassist |=
1728                                     sc->hn_tx_ring[0].hn_csum_assist;
1729                         } else {
1730                                 ifp->if_hwassist &=
1731                                     ~sc->hn_tx_ring[0].hn_csum_assist;
1732                         }
1733                 }
1734
1735                 if (mask & IFCAP_RXCSUM)
1736                         ifp->if_capenable ^= IFCAP_RXCSUM;
1737
1738                 if (mask & IFCAP_LRO)
1739                         ifp->if_capenable ^= IFCAP_LRO;
1740
1741                 if (mask & IFCAP_TSO4) {
1742                         ifp->if_capenable ^= IFCAP_TSO4;
1743                         if (ifp->if_capenable & IFCAP_TSO4)
1744                                 ifp->if_hwassist |= CSUM_IP_TSO;
1745                         else
1746                                 ifp->if_hwassist &= ~CSUM_IP_TSO;
1747                 }
1748
1749                 if (mask & IFCAP_TSO6) {
1750                         ifp->if_capenable ^= IFCAP_TSO6;
1751                         if (ifp->if_capenable & IFCAP_TSO6)
1752                                 ifp->if_hwassist |= CSUM_IP6_TSO;
1753                         else
1754                                 ifp->if_hwassist &= ~CSUM_IP6_TSO;
1755                 }
1756
1757                 NV_UNLOCK(sc);
1758                 error = 0;
1759                 break;
1760         case SIOCADDMULTI:
1761         case SIOCDELMULTI:
1762 #ifdef notyet
1763                 /* Fixme:  Multicast mode? */
1764                 if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1765                         NV_LOCK(sc);
1766                         netvsc_setmulti(sc);
1767                         NV_UNLOCK(sc);
1768                         error = 0;
1769                 }
1770 #endif
1771                 error = EINVAL;
1772                 break;
1773         case SIOCSIFMEDIA:
1774         case SIOCGIFMEDIA:
1775                 error = ifmedia_ioctl(ifp, ifr, &sc->hn_media, cmd);
1776                 break;
1777         default:
1778                 error = ether_ioctl(ifp, cmd, data);
1779                 break;
1780         }
1781
1782         return (error);
1783 }
1784
1785 /*
1786  *
1787  */
1788 static void
1789 hn_stop(hn_softc_t *sc)
1790 {
1791         struct ifnet *ifp;
1792         int ret, i;
1793         struct hv_device *device_ctx = vmbus_get_devctx(sc->hn_dev);
1794
1795         ifp = sc->hn_ifp;
1796
1797         if (bootverbose)
1798                 printf(" Closing Device ...\n");
1799
1800         atomic_clear_int(&ifp->if_drv_flags,
1801             (IFF_DRV_RUNNING | IFF_DRV_OACTIVE));
1802         for (i = 0; i < sc->hn_tx_ring_inuse; ++i)
1803                 sc->hn_tx_ring[i].hn_oactive = 0;
1804
1805         if_link_state_change(ifp, LINK_STATE_DOWN);
1806         sc->hn_initdone = 0;
1807
1808         ret = hv_rf_on_close(device_ctx);
1809 }
1810
1811 /*
1812  * FreeBSD transmit entry point
1813  */
1814 static void
1815 hn_start(struct ifnet *ifp)
1816 {
1817         struct hn_softc *sc = ifp->if_softc;
1818         struct hn_tx_ring *txr = &sc->hn_tx_ring[0];
1819
1820         if (txr->hn_sched_tx)
1821                 goto do_sched;
1822
1823         if (mtx_trylock(&txr->hn_tx_lock)) {
1824                 int sched;
1825
1826                 sched = hn_start_locked(txr, txr->hn_direct_tx_size);
1827                 mtx_unlock(&txr->hn_tx_lock);
1828                 if (!sched)
1829                         return;
1830         }
1831 do_sched:
1832         taskqueue_enqueue(txr->hn_tx_taskq, &txr->hn_tx_task);
1833 }
1834
1835 static void
1836 hn_start_txeof(struct hn_tx_ring *txr)
1837 {
1838         struct hn_softc *sc = txr->hn_sc;
1839         struct ifnet *ifp = sc->hn_ifp;
1840
1841         KASSERT(txr == &sc->hn_tx_ring[0], ("not the first TX ring"));
1842
1843         if (txr->hn_sched_tx)
1844                 goto do_sched;
1845
1846         if (mtx_trylock(&txr->hn_tx_lock)) {
1847                 int sched;
1848
1849                 atomic_clear_int(&ifp->if_drv_flags, IFF_DRV_OACTIVE);
1850                 sched = hn_start_locked(txr, txr->hn_direct_tx_size);
1851                 mtx_unlock(&txr->hn_tx_lock);
1852                 if (sched) {
1853                         taskqueue_enqueue(txr->hn_tx_taskq,
1854                             &txr->hn_tx_task);
1855                 }
1856         } else {
1857 do_sched:
1858                 /*
1859                  * Release the OACTIVE earlier, with the hope, that
1860                  * others could catch up.  The task will clear the
1861                  * flag again with the hn_tx_lock to avoid possible
1862                  * races.
1863                  */
1864                 atomic_clear_int(&ifp->if_drv_flags, IFF_DRV_OACTIVE);
1865                 taskqueue_enqueue(txr->hn_tx_taskq, &txr->hn_txeof_task);
1866         }
1867 }
1868
1869 /*
1870  *
1871  */
1872 static void
1873 hn_ifinit_locked(hn_softc_t *sc)
1874 {
1875         struct ifnet *ifp;
1876         struct hv_device *device_ctx = vmbus_get_devctx(sc->hn_dev);
1877         int ret, i;
1878
1879         ifp = sc->hn_ifp;
1880
1881         if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1882                 return;
1883         }
1884
1885         hv_promisc_mode = 1;
1886
1887         ret = hv_rf_on_open(device_ctx);
1888         if (ret != 0) {
1889                 return;
1890         } else {
1891                 sc->hn_initdone = 1;
1892         }
1893
1894         atomic_clear_int(&ifp->if_drv_flags, IFF_DRV_OACTIVE);
1895         for (i = 0; i < sc->hn_tx_ring_inuse; ++i)
1896                 sc->hn_tx_ring[i].hn_oactive = 0;
1897
1898         atomic_set_int(&ifp->if_drv_flags, IFF_DRV_RUNNING);
1899         if_link_state_change(ifp, LINK_STATE_UP);
1900 }
1901
1902 /*
1903  *
1904  */
1905 static void
1906 hn_ifinit(void *xsc)
1907 {
1908         hn_softc_t *sc = xsc;
1909
1910         NV_LOCK(sc);
1911         if (sc->temp_unusable) {
1912                 NV_UNLOCK(sc);
1913                 return;
1914         }
1915         sc->temp_unusable = TRUE;
1916         NV_UNLOCK(sc);
1917
1918         hn_ifinit_locked(sc);
1919
1920         NV_LOCK(sc);
1921         sc->temp_unusable = FALSE;
1922         NV_UNLOCK(sc);
1923 }
1924
1925 #ifdef LATER
1926 /*
1927  *
1928  */
1929 static void
1930 hn_watchdog(struct ifnet *ifp)
1931 {
1932         hn_softc_t *sc;
1933         sc = ifp->if_softc;
1934
1935         printf("hn%d: watchdog timeout -- resetting\n", sc->hn_unit);
1936         hn_ifinit(sc);    /*???*/
1937         ifp->if_oerrors++;
1938 }
1939 #endif
1940
1941 #if __FreeBSD_version >= 1100099
1942
1943 static int
1944 hn_lro_lenlim_sysctl(SYSCTL_HANDLER_ARGS)
1945 {
1946         struct hn_softc *sc = arg1;
1947         unsigned int lenlim;
1948         int error;
1949
1950         lenlim = sc->hn_rx_ring[0].hn_lro.lro_length_lim;
1951         error = sysctl_handle_int(oidp, &lenlim, 0, req);
1952         if (error || req->newptr == NULL)
1953                 return error;
1954
1955         if (lenlim < HN_LRO_LENLIM_MIN(sc->hn_ifp) ||
1956             lenlim > TCP_LRO_LENGTH_MAX)
1957                 return EINVAL;
1958
1959         NV_LOCK(sc);
1960         hn_set_lro_lenlim(sc, lenlim);
1961         NV_UNLOCK(sc);
1962         return 0;
1963 }
1964
1965 static int
1966 hn_lro_ackcnt_sysctl(SYSCTL_HANDLER_ARGS)
1967 {
1968         struct hn_softc *sc = arg1;
1969         int ackcnt, error, i;
1970
1971         /*
1972          * lro_ackcnt_lim is append count limit,
1973          * +1 to turn it into aggregation limit.
1974          */
1975         ackcnt = sc->hn_rx_ring[0].hn_lro.lro_ackcnt_lim + 1;
1976         error = sysctl_handle_int(oidp, &ackcnt, 0, req);
1977         if (error || req->newptr == NULL)
1978                 return error;
1979
1980         if (ackcnt < 2 || ackcnt > (TCP_LRO_ACKCNT_MAX + 1))
1981                 return EINVAL;
1982
1983         /*
1984          * Convert aggregation limit back to append
1985          * count limit.
1986          */
1987         --ackcnt;
1988         NV_LOCK(sc);
1989         for (i = 0; i < sc->hn_rx_ring_inuse; ++i)
1990                 sc->hn_rx_ring[i].hn_lro.lro_ackcnt_lim = ackcnt;
1991         NV_UNLOCK(sc);
1992         return 0;
1993 }
1994
1995 #endif
1996
1997 static int
1998 hn_trust_hcsum_sysctl(SYSCTL_HANDLER_ARGS)
1999 {
2000         struct hn_softc *sc = arg1;
2001         int hcsum = arg2;
2002         int on, error, i;
2003
2004         on = 0;
2005         if (sc->hn_rx_ring[0].hn_trust_hcsum & hcsum)
2006                 on = 1;
2007
2008         error = sysctl_handle_int(oidp, &on, 0, req);
2009         if (error || req->newptr == NULL)
2010                 return error;
2011
2012         NV_LOCK(sc);
2013         for (i = 0; i < sc->hn_rx_ring_inuse; ++i) {
2014                 struct hn_rx_ring *rxr = &sc->hn_rx_ring[i];
2015
2016                 if (on)
2017                         rxr->hn_trust_hcsum |= hcsum;
2018                 else
2019                         rxr->hn_trust_hcsum &= ~hcsum;
2020         }
2021         NV_UNLOCK(sc);
2022         return 0;
2023 }
2024
2025 static int
2026 hn_tx_chimney_size_sysctl(SYSCTL_HANDLER_ARGS)
2027 {
2028         struct hn_softc *sc = arg1;
2029         int chimney_size, error;
2030
2031         chimney_size = sc->hn_tx_ring[0].hn_tx_chimney_size;
2032         error = sysctl_handle_int(oidp, &chimney_size, 0, req);
2033         if (error || req->newptr == NULL)
2034                 return error;
2035
2036         if (chimney_size > sc->hn_tx_chimney_max || chimney_size <= 0)
2037                 return EINVAL;
2038
2039         hn_set_tx_chimney_size(sc, chimney_size);
2040         return 0;
2041 }
2042
2043 #if __FreeBSD_version < 1100095
2044 static int
2045 hn_rx_stat_int_sysctl(SYSCTL_HANDLER_ARGS)
2046 {
2047         struct hn_softc *sc = arg1;
2048         int ofs = arg2, i, error;
2049         struct hn_rx_ring *rxr;
2050         uint64_t stat;
2051
2052         stat = 0;
2053         for (i = 0; i < sc->hn_rx_ring_inuse; ++i) {
2054                 rxr = &sc->hn_rx_ring[i];
2055                 stat += *((int *)((uint8_t *)rxr + ofs));
2056         }
2057
2058         error = sysctl_handle_64(oidp, &stat, 0, req);
2059         if (error || req->newptr == NULL)
2060                 return error;
2061
2062         /* Zero out this stat. */
2063         for (i = 0; i < sc->hn_rx_ring_inuse; ++i) {
2064                 rxr = &sc->hn_rx_ring[i];
2065                 *((int *)((uint8_t *)rxr + ofs)) = 0;
2066         }
2067         return 0;
2068 }
2069 #else
2070 static int
2071 hn_rx_stat_u64_sysctl(SYSCTL_HANDLER_ARGS)
2072 {
2073         struct hn_softc *sc = arg1;
2074         int ofs = arg2, i, error;
2075         struct hn_rx_ring *rxr;
2076         uint64_t stat;
2077
2078         stat = 0;
2079         for (i = 0; i < sc->hn_rx_ring_inuse; ++i) {
2080                 rxr = &sc->hn_rx_ring[i];
2081                 stat += *((uint64_t *)((uint8_t *)rxr + ofs));
2082         }
2083
2084         error = sysctl_handle_64(oidp, &stat, 0, req);
2085         if (error || req->newptr == NULL)
2086                 return error;
2087
2088         /* Zero out this stat. */
2089         for (i = 0; i < sc->hn_rx_ring_inuse; ++i) {
2090                 rxr = &sc->hn_rx_ring[i];
2091                 *((uint64_t *)((uint8_t *)rxr + ofs)) = 0;
2092         }
2093         return 0;
2094 }
2095
2096 #endif
2097
2098 static int
2099 hn_rx_stat_ulong_sysctl(SYSCTL_HANDLER_ARGS)
2100 {
2101         struct hn_softc *sc = arg1;
2102         int ofs = arg2, i, error;
2103         struct hn_rx_ring *rxr;
2104         u_long stat;
2105
2106         stat = 0;
2107         for (i = 0; i < sc->hn_rx_ring_cnt; ++i) {
2108                 rxr = &sc->hn_rx_ring[i];
2109                 stat += *((u_long *)((uint8_t *)rxr + ofs));
2110         }
2111
2112         error = sysctl_handle_long(oidp, &stat, 0, req);
2113         if (error || req->newptr == NULL)
2114                 return error;
2115
2116         /* Zero out this stat. */
2117         for (i = 0; i < sc->hn_rx_ring_cnt; ++i) {
2118                 rxr = &sc->hn_rx_ring[i];
2119                 *((u_long *)((uint8_t *)rxr + ofs)) = 0;
2120         }
2121         return 0;
2122 }
2123
2124 static int
2125 hn_tx_stat_ulong_sysctl(SYSCTL_HANDLER_ARGS)
2126 {
2127         struct hn_softc *sc = arg1;
2128         int ofs = arg2, i, error;
2129         struct hn_tx_ring *txr;
2130         u_long stat;
2131
2132         stat = 0;
2133         for (i = 0; i < sc->hn_tx_ring_inuse; ++i) {
2134                 txr = &sc->hn_tx_ring[i];
2135                 stat += *((u_long *)((uint8_t *)txr + ofs));
2136         }
2137
2138         error = sysctl_handle_long(oidp, &stat, 0, req);
2139         if (error || req->newptr == NULL)
2140                 return error;
2141
2142         /* Zero out this stat. */
2143         for (i = 0; i < sc->hn_tx_ring_inuse; ++i) {
2144                 txr = &sc->hn_tx_ring[i];
2145                 *((u_long *)((uint8_t *)txr + ofs)) = 0;
2146         }
2147         return 0;
2148 }
2149
2150 static int
2151 hn_tx_conf_int_sysctl(SYSCTL_HANDLER_ARGS)
2152 {
2153         struct hn_softc *sc = arg1;
2154         int ofs = arg2, i, error, conf;
2155         struct hn_tx_ring *txr;
2156
2157         txr = &sc->hn_tx_ring[0];
2158         conf = *((int *)((uint8_t *)txr + ofs));
2159
2160         error = sysctl_handle_int(oidp, &conf, 0, req);
2161         if (error || req->newptr == NULL)
2162                 return error;
2163
2164         NV_LOCK(sc);
2165         for (i = 0; i < sc->hn_tx_ring_inuse; ++i) {
2166                 txr = &sc->hn_tx_ring[i];
2167                 *((int *)((uint8_t *)txr + ofs)) = conf;
2168         }
2169         NV_UNLOCK(sc);
2170
2171         return 0;
2172 }
2173
2174 static int
2175 hn_check_iplen(const struct mbuf *m, int hoff)
2176 {
2177         const struct ip *ip;
2178         int len, iphlen, iplen;
2179         const struct tcphdr *th;
2180         int thoff;                              /* TCP data offset */
2181
2182         len = hoff + sizeof(struct ip);
2183
2184         /* The packet must be at least the size of an IP header. */
2185         if (m->m_pkthdr.len < len)
2186                 return IPPROTO_DONE;
2187
2188         /* The fixed IP header must reside completely in the first mbuf. */
2189         if (m->m_len < len)
2190                 return IPPROTO_DONE;
2191
2192         ip = mtodo(m, hoff);
2193
2194         /* Bound check the packet's stated IP header length. */
2195         iphlen = ip->ip_hl << 2;
2196         if (iphlen < sizeof(struct ip))         /* minimum header length */
2197                 return IPPROTO_DONE;
2198
2199         /* The full IP header must reside completely in the one mbuf. */
2200         if (m->m_len < hoff + iphlen)
2201                 return IPPROTO_DONE;
2202
2203         iplen = ntohs(ip->ip_len);
2204
2205         /*
2206          * Check that the amount of data in the buffers is as
2207          * at least much as the IP header would have us expect.
2208          */
2209         if (m->m_pkthdr.len < hoff + iplen)
2210                 return IPPROTO_DONE;
2211
2212         /*
2213          * Ignore IP fragments.
2214          */
2215         if (ntohs(ip->ip_off) & (IP_OFFMASK | IP_MF))
2216                 return IPPROTO_DONE;
2217
2218         /*
2219          * The TCP/IP or UDP/IP header must be entirely contained within
2220          * the first fragment of a packet.
2221          */
2222         switch (ip->ip_p) {
2223         case IPPROTO_TCP:
2224                 if (iplen < iphlen + sizeof(struct tcphdr))
2225                         return IPPROTO_DONE;
2226                 if (m->m_len < hoff + iphlen + sizeof(struct tcphdr))
2227                         return IPPROTO_DONE;
2228                 th = (const struct tcphdr *)((const uint8_t *)ip + iphlen);
2229                 thoff = th->th_off << 2;
2230                 if (thoff < sizeof(struct tcphdr) || thoff + iphlen > iplen)
2231                         return IPPROTO_DONE;
2232                 if (m->m_len < hoff + iphlen + thoff)
2233                         return IPPROTO_DONE;
2234                 break;
2235         case IPPROTO_UDP:
2236                 if (iplen < iphlen + sizeof(struct udphdr))
2237                         return IPPROTO_DONE;
2238                 if (m->m_len < hoff + iphlen + sizeof(struct udphdr))
2239                         return IPPROTO_DONE;
2240                 break;
2241         default:
2242                 if (iplen < iphlen)
2243                         return IPPROTO_DONE;
2244                 break;
2245         }
2246         return ip->ip_p;
2247 }
2248
2249 static void
2250 hn_create_rx_data(struct hn_softc *sc, int ring_cnt)
2251 {
2252         struct sysctl_oid_list *child;
2253         struct sysctl_ctx_list *ctx;
2254         device_t dev = sc->hn_dev;
2255 #if defined(INET) || defined(INET6)
2256 #if __FreeBSD_version >= 1100095
2257         int lroent_cnt;
2258 #endif
2259 #endif
2260         int i;
2261
2262         sc->hn_rx_ring_cnt = ring_cnt;
2263         sc->hn_rx_ring_inuse = sc->hn_rx_ring_cnt;
2264
2265         sc->hn_rx_ring = malloc(sizeof(struct hn_rx_ring) * sc->hn_rx_ring_cnt,
2266             M_NETVSC, M_WAITOK | M_ZERO);
2267
2268 #if defined(INET) || defined(INET6)
2269 #if __FreeBSD_version >= 1100095
2270         lroent_cnt = hn_lro_entry_count;
2271         if (lroent_cnt < TCP_LRO_ENTRIES)
2272                 lroent_cnt = TCP_LRO_ENTRIES;
2273         device_printf(dev, "LRO: entry count %d\n", lroent_cnt);
2274 #endif
2275 #endif  /* INET || INET6 */
2276
2277         ctx = device_get_sysctl_ctx(dev);
2278         child = SYSCTL_CHILDREN(device_get_sysctl_tree(dev));
2279
2280         /* Create dev.hn.UNIT.rx sysctl tree */
2281         sc->hn_rx_sysctl_tree = SYSCTL_ADD_NODE(ctx, child, OID_AUTO, "rx",
2282             CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "");
2283
2284         for (i = 0; i < sc->hn_rx_ring_cnt; ++i) {
2285                 struct hn_rx_ring *rxr = &sc->hn_rx_ring[i];
2286
2287                 if (hn_trust_hosttcp)
2288                         rxr->hn_trust_hcsum |= HN_TRUST_HCSUM_TCP;
2289                 if (hn_trust_hostudp)
2290                         rxr->hn_trust_hcsum |= HN_TRUST_HCSUM_UDP;
2291                 if (hn_trust_hostip)
2292                         rxr->hn_trust_hcsum |= HN_TRUST_HCSUM_IP;
2293                 rxr->hn_ifp = sc->hn_ifp;
2294                 rxr->hn_rx_idx = i;
2295
2296                 /*
2297                  * Initialize LRO.
2298                  */
2299 #if defined(INET) || defined(INET6)
2300 #if __FreeBSD_version >= 1100095
2301                 tcp_lro_init_args(&rxr->hn_lro, sc->hn_ifp, lroent_cnt,
2302                     hn_lro_mbufq_depth);
2303 #else
2304                 tcp_lro_init(&rxr->hn_lro);
2305                 rxr->hn_lro.ifp = sc->hn_ifp;
2306 #endif
2307 #if __FreeBSD_version >= 1100099
2308                 rxr->hn_lro.lro_length_lim = HN_LRO_LENLIM_DEF;
2309                 rxr->hn_lro.lro_ackcnt_lim = HN_LRO_ACKCNT_DEF;
2310 #endif
2311 #endif  /* INET || INET6 */
2312
2313                 if (sc->hn_rx_sysctl_tree != NULL) {
2314                         char name[16];
2315
2316                         /*
2317                          * Create per RX ring sysctl tree:
2318                          * dev.hn.UNIT.rx.RINGID
2319                          */
2320                         snprintf(name, sizeof(name), "%d", i);
2321                         rxr->hn_rx_sysctl_tree = SYSCTL_ADD_NODE(ctx,
2322                             SYSCTL_CHILDREN(sc->hn_rx_sysctl_tree),
2323                             OID_AUTO, name, CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "");
2324
2325                         if (rxr->hn_rx_sysctl_tree != NULL) {
2326                                 SYSCTL_ADD_ULONG(ctx,
2327                                     SYSCTL_CHILDREN(rxr->hn_rx_sysctl_tree),
2328                                     OID_AUTO, "packets", CTLFLAG_RW,
2329                                     &rxr->hn_pkts, "# of packets received");
2330                                 SYSCTL_ADD_ULONG(ctx,
2331                                     SYSCTL_CHILDREN(rxr->hn_rx_sysctl_tree),
2332                                     OID_AUTO, "rss_pkts", CTLFLAG_RW,
2333                                     &rxr->hn_rss_pkts,
2334                                     "# of packets w/ RSS info received");
2335                         }
2336                 }
2337         }
2338
2339         SYSCTL_ADD_PROC(ctx, child, OID_AUTO, "lro_queued",
2340             CTLTYPE_U64 | CTLFLAG_RW | CTLFLAG_MPSAFE, sc,
2341             __offsetof(struct hn_rx_ring, hn_lro.lro_queued),
2342 #if __FreeBSD_version < 1100095
2343             hn_rx_stat_int_sysctl,
2344 #else
2345             hn_rx_stat_u64_sysctl,
2346 #endif
2347             "LU", "LRO queued");
2348         SYSCTL_ADD_PROC(ctx, child, OID_AUTO, "lro_flushed",
2349             CTLTYPE_U64 | CTLFLAG_RW | CTLFLAG_MPSAFE, sc,
2350             __offsetof(struct hn_rx_ring, hn_lro.lro_flushed),
2351 #if __FreeBSD_version < 1100095
2352             hn_rx_stat_int_sysctl,
2353 #else
2354             hn_rx_stat_u64_sysctl,
2355 #endif
2356             "LU", "LRO flushed");
2357         SYSCTL_ADD_PROC(ctx, child, OID_AUTO, "lro_tried",
2358             CTLTYPE_ULONG | CTLFLAG_RW | CTLFLAG_MPSAFE, sc,
2359             __offsetof(struct hn_rx_ring, hn_lro_tried),
2360             hn_rx_stat_ulong_sysctl, "LU", "# of LRO tries");
2361 #if __FreeBSD_version >= 1100099
2362         SYSCTL_ADD_PROC(ctx, child, OID_AUTO, "lro_length_lim",
2363             CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
2364             hn_lro_lenlim_sysctl, "IU",
2365             "Max # of data bytes to be aggregated by LRO");
2366         SYSCTL_ADD_PROC(ctx, child, OID_AUTO, "lro_ackcnt_lim",
2367             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
2368             hn_lro_ackcnt_sysctl, "I",
2369             "Max # of ACKs to be aggregated by LRO");
2370 #endif
2371         SYSCTL_ADD_PROC(ctx, child, OID_AUTO, "trust_hosttcp",
2372             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, HN_TRUST_HCSUM_TCP,
2373             hn_trust_hcsum_sysctl, "I",
2374             "Trust tcp segement verification on host side, "
2375             "when csum info is missing");
2376         SYSCTL_ADD_PROC(ctx, child, OID_AUTO, "trust_hostudp",
2377             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, HN_TRUST_HCSUM_UDP,
2378             hn_trust_hcsum_sysctl, "I",
2379             "Trust udp datagram verification on host side, "
2380             "when csum info is missing");
2381         SYSCTL_ADD_PROC(ctx, child, OID_AUTO, "trust_hostip",
2382             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, HN_TRUST_HCSUM_IP,
2383             hn_trust_hcsum_sysctl, "I",
2384             "Trust ip packet verification on host side, "
2385             "when csum info is missing");
2386         SYSCTL_ADD_PROC(ctx, child, OID_AUTO, "csum_ip",
2387             CTLTYPE_ULONG | CTLFLAG_RW | CTLFLAG_MPSAFE, sc,
2388             __offsetof(struct hn_rx_ring, hn_csum_ip),
2389             hn_rx_stat_ulong_sysctl, "LU", "RXCSUM IP");
2390         SYSCTL_ADD_PROC(ctx, child, OID_AUTO, "csum_tcp",
2391             CTLTYPE_ULONG | CTLFLAG_RW | CTLFLAG_MPSAFE, sc,
2392             __offsetof(struct hn_rx_ring, hn_csum_tcp),
2393             hn_rx_stat_ulong_sysctl, "LU", "RXCSUM TCP");
2394         SYSCTL_ADD_PROC(ctx, child, OID_AUTO, "csum_udp",
2395             CTLTYPE_ULONG | CTLFLAG_RW | CTLFLAG_MPSAFE, sc,
2396             __offsetof(struct hn_rx_ring, hn_csum_udp),
2397             hn_rx_stat_ulong_sysctl, "LU", "RXCSUM UDP");
2398         SYSCTL_ADD_PROC(ctx, child, OID_AUTO, "csum_trusted",
2399             CTLTYPE_ULONG | CTLFLAG_RW | CTLFLAG_MPSAFE, sc,
2400             __offsetof(struct hn_rx_ring, hn_csum_trusted),
2401             hn_rx_stat_ulong_sysctl, "LU",
2402             "# of packets that we trust host's csum verification");
2403         SYSCTL_ADD_PROC(ctx, child, OID_AUTO, "small_pkts",
2404             CTLTYPE_ULONG | CTLFLAG_RW | CTLFLAG_MPSAFE, sc,
2405             __offsetof(struct hn_rx_ring, hn_small_pkts),
2406             hn_rx_stat_ulong_sysctl, "LU", "# of small packets received");
2407         SYSCTL_ADD_INT(ctx, child, OID_AUTO, "rx_ring_cnt",
2408             CTLFLAG_RD, &sc->hn_rx_ring_cnt, 0, "# created RX rings");
2409         SYSCTL_ADD_INT(ctx, child, OID_AUTO, "rx_ring_inuse",
2410             CTLFLAG_RD, &sc->hn_rx_ring_inuse, 0, "# used RX rings");
2411 }
2412
2413 static void
2414 hn_destroy_rx_data(struct hn_softc *sc)
2415 {
2416 #if defined(INET) || defined(INET6)
2417         int i;
2418 #endif
2419
2420         if (sc->hn_rx_ring_cnt == 0)
2421                 return;
2422
2423 #if defined(INET) || defined(INET6)
2424         for (i = 0; i < sc->hn_rx_ring_cnt; ++i)
2425                 tcp_lro_free(&sc->hn_rx_ring[i].hn_lro);
2426 #endif
2427         free(sc->hn_rx_ring, M_NETVSC);
2428         sc->hn_rx_ring = NULL;
2429
2430         sc->hn_rx_ring_cnt = 0;
2431         sc->hn_rx_ring_inuse = 0;
2432 }
2433
2434 static int
2435 hn_create_tx_ring(struct hn_softc *sc, int id)
2436 {
2437         struct hn_tx_ring *txr = &sc->hn_tx_ring[id];
2438         device_t dev = sc->hn_dev;
2439         bus_dma_tag_t parent_dtag;
2440         int error, i;
2441         uint32_t version;
2442
2443         txr->hn_sc = sc;
2444         txr->hn_tx_idx = id;
2445
2446 #ifndef HN_USE_TXDESC_BUFRING
2447         mtx_init(&txr->hn_txlist_spin, "hn txlist", NULL, MTX_SPIN);
2448 #endif
2449         mtx_init(&txr->hn_tx_lock, "hn tx", NULL, MTX_DEF);
2450
2451         txr->hn_txdesc_cnt = HN_TX_DESC_CNT;
2452         txr->hn_txdesc = malloc(sizeof(struct hn_txdesc) * txr->hn_txdesc_cnt,
2453             M_NETVSC, M_WAITOK | M_ZERO);
2454 #ifndef HN_USE_TXDESC_BUFRING
2455         SLIST_INIT(&txr->hn_txlist);
2456 #else
2457         txr->hn_txdesc_br = buf_ring_alloc(txr->hn_txdesc_cnt, M_NETVSC,
2458             M_WAITOK, &txr->hn_tx_lock);
2459 #endif
2460
2461         txr->hn_tx_taskq = sc->hn_tx_taskq;
2462
2463         if (hn_use_if_start) {
2464                 txr->hn_txeof = hn_start_txeof;
2465                 TASK_INIT(&txr->hn_tx_task, 0, hn_start_taskfunc, txr);
2466                 TASK_INIT(&txr->hn_txeof_task, 0, hn_start_txeof_taskfunc, txr);
2467         } else {
2468                 int br_depth;
2469
2470                 txr->hn_txeof = hn_xmit_txeof;
2471                 TASK_INIT(&txr->hn_tx_task, 0, hn_xmit_taskfunc, txr);
2472                 TASK_INIT(&txr->hn_txeof_task, 0, hn_xmit_txeof_taskfunc, txr);
2473
2474                 br_depth = hn_get_txswq_depth(txr);
2475                 txr->hn_mbuf_br = buf_ring_alloc(br_depth, M_NETVSC,
2476                     M_WAITOK, &txr->hn_tx_lock);
2477         }
2478
2479         txr->hn_direct_tx_size = hn_direct_tx_size;
2480         version = VMBUS_GET_VERSION(device_get_parent(dev), dev);
2481         if (version >= VMBUS_VERSION_WIN8_1) {
2482                 txr->hn_csum_assist = HN_CSUM_ASSIST;
2483         } else {
2484                 txr->hn_csum_assist = HN_CSUM_ASSIST_WIN8;
2485                 if (id == 0) {
2486                         device_printf(dev, "bus version %u.%u, "
2487                             "no UDP checksum offloading\n",
2488                             VMBUS_VERSION_MAJOR(version),
2489                             VMBUS_VERSION_MINOR(version));
2490                 }
2491         }
2492
2493         /*
2494          * Always schedule transmission instead of trying to do direct
2495          * transmission.  This one gives the best performance so far.
2496          */
2497         txr->hn_sched_tx = 1;
2498
2499         parent_dtag = bus_get_dma_tag(dev);
2500
2501         /* DMA tag for RNDIS messages. */
2502         error = bus_dma_tag_create(parent_dtag, /* parent */
2503             HN_RNDIS_MSG_ALIGN,         /* alignment */
2504             HN_RNDIS_MSG_BOUNDARY,      /* boundary */
2505             BUS_SPACE_MAXADDR,          /* lowaddr */
2506             BUS_SPACE_MAXADDR,          /* highaddr */
2507             NULL, NULL,                 /* filter, filterarg */
2508             HN_RNDIS_MSG_LEN,           /* maxsize */
2509             1,                          /* nsegments */
2510             HN_RNDIS_MSG_LEN,           /* maxsegsize */
2511             0,                          /* flags */
2512             NULL,                       /* lockfunc */
2513             NULL,                       /* lockfuncarg */
2514             &txr->hn_tx_rndis_dtag);
2515         if (error) {
2516                 device_printf(dev, "failed to create rndis dmatag\n");
2517                 return error;
2518         }
2519
2520         /* DMA tag for data. */
2521         error = bus_dma_tag_create(parent_dtag, /* parent */
2522             1,                          /* alignment */
2523             HN_TX_DATA_BOUNDARY,        /* boundary */
2524             BUS_SPACE_MAXADDR,          /* lowaddr */
2525             BUS_SPACE_MAXADDR,          /* highaddr */
2526             NULL, NULL,                 /* filter, filterarg */
2527             HN_TX_DATA_MAXSIZE,         /* maxsize */
2528             HN_TX_DATA_SEGCNT_MAX,      /* nsegments */
2529             HN_TX_DATA_SEGSIZE,         /* maxsegsize */
2530             0,                          /* flags */
2531             NULL,                       /* lockfunc */
2532             NULL,                       /* lockfuncarg */
2533             &txr->hn_tx_data_dtag);
2534         if (error) {
2535                 device_printf(dev, "failed to create data dmatag\n");
2536                 return error;
2537         }
2538
2539         for (i = 0; i < txr->hn_txdesc_cnt; ++i) {
2540                 struct hn_txdesc *txd = &txr->hn_txdesc[i];
2541
2542                 txd->txr = txr;
2543
2544                 /*
2545                  * Allocate and load RNDIS messages.
2546                  */
2547                 error = bus_dmamem_alloc(txr->hn_tx_rndis_dtag,
2548                     (void **)&txd->rndis_msg,
2549                     BUS_DMA_WAITOK | BUS_DMA_COHERENT,
2550                     &txd->rndis_msg_dmap);
2551                 if (error) {
2552                         device_printf(dev,
2553                             "failed to allocate rndis_msg, %d\n", i);
2554                         return error;
2555                 }
2556
2557                 error = bus_dmamap_load(txr->hn_tx_rndis_dtag,
2558                     txd->rndis_msg_dmap,
2559                     txd->rndis_msg, HN_RNDIS_MSG_LEN,
2560                     hyperv_dma_map_paddr, &txd->rndis_msg_paddr,
2561                     BUS_DMA_NOWAIT);
2562                 if (error) {
2563                         device_printf(dev,
2564                             "failed to load rndis_msg, %d\n", i);
2565                         bus_dmamem_free(txr->hn_tx_rndis_dtag,
2566                             txd->rndis_msg, txd->rndis_msg_dmap);
2567                         return error;
2568                 }
2569
2570                 /* DMA map for TX data. */
2571                 error = bus_dmamap_create(txr->hn_tx_data_dtag, 0,
2572                     &txd->data_dmap);
2573                 if (error) {
2574                         device_printf(dev,
2575                             "failed to allocate tx data dmamap\n");
2576                         bus_dmamap_unload(txr->hn_tx_rndis_dtag,
2577                             txd->rndis_msg_dmap);
2578                         bus_dmamem_free(txr->hn_tx_rndis_dtag,
2579                             txd->rndis_msg, txd->rndis_msg_dmap);
2580                         return error;
2581                 }
2582
2583                 /* All set, put it to list */
2584                 txd->flags |= HN_TXD_FLAG_ONLIST;
2585 #ifndef HN_USE_TXDESC_BUFRING
2586                 SLIST_INSERT_HEAD(&txr->hn_txlist, txd, link);
2587 #else
2588                 buf_ring_enqueue(txr->hn_txdesc_br, txd);
2589 #endif
2590         }
2591         txr->hn_txdesc_avail = txr->hn_txdesc_cnt;
2592
2593         if (sc->hn_tx_sysctl_tree != NULL) {
2594                 struct sysctl_oid_list *child;
2595                 struct sysctl_ctx_list *ctx;
2596                 char name[16];
2597
2598                 /*
2599                  * Create per TX ring sysctl tree:
2600                  * dev.hn.UNIT.tx.RINGID
2601                  */
2602                 ctx = device_get_sysctl_ctx(dev);
2603                 child = SYSCTL_CHILDREN(sc->hn_tx_sysctl_tree);
2604
2605                 snprintf(name, sizeof(name), "%d", id);
2606                 txr->hn_tx_sysctl_tree = SYSCTL_ADD_NODE(ctx, child, OID_AUTO,
2607                     name, CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "");
2608
2609                 if (txr->hn_tx_sysctl_tree != NULL) {
2610                         child = SYSCTL_CHILDREN(txr->hn_tx_sysctl_tree);
2611
2612                         SYSCTL_ADD_INT(ctx, child, OID_AUTO, "txdesc_avail",
2613                             CTLFLAG_RD, &txr->hn_txdesc_avail, 0,
2614                             "# of available TX descs");
2615                         if (!hn_use_if_start) {
2616                                 SYSCTL_ADD_INT(ctx, child, OID_AUTO, "oactive",
2617                                     CTLFLAG_RD, &txr->hn_oactive, 0,
2618                                     "over active");
2619                         }
2620                         SYSCTL_ADD_ULONG(ctx, child, OID_AUTO, "packets",
2621                             CTLFLAG_RW, &txr->hn_pkts,
2622                             "# of packets transmitted");
2623                 }
2624         }
2625
2626         return 0;
2627 }
2628
2629 static void
2630 hn_txdesc_dmamap_destroy(struct hn_txdesc *txd)
2631 {
2632         struct hn_tx_ring *txr = txd->txr;
2633
2634         KASSERT(txd->m == NULL, ("still has mbuf installed"));
2635         KASSERT((txd->flags & HN_TXD_FLAG_DMAMAP) == 0, ("still dma mapped"));
2636
2637         bus_dmamap_unload(txr->hn_tx_rndis_dtag, txd->rndis_msg_dmap);
2638         bus_dmamem_free(txr->hn_tx_rndis_dtag, txd->rndis_msg,
2639             txd->rndis_msg_dmap);
2640         bus_dmamap_destroy(txr->hn_tx_data_dtag, txd->data_dmap);
2641 }
2642
2643 static void
2644 hn_destroy_tx_ring(struct hn_tx_ring *txr)
2645 {
2646         struct hn_txdesc *txd;
2647
2648         if (txr->hn_txdesc == NULL)
2649                 return;
2650
2651 #ifndef HN_USE_TXDESC_BUFRING
2652         while ((txd = SLIST_FIRST(&txr->hn_txlist)) != NULL) {
2653                 SLIST_REMOVE_HEAD(&txr->hn_txlist, link);
2654                 hn_txdesc_dmamap_destroy(txd);
2655         }
2656 #else
2657         mtx_lock(&txr->hn_tx_lock);
2658         while ((txd = buf_ring_dequeue_sc(txr->hn_txdesc_br)) != NULL)
2659                 hn_txdesc_dmamap_destroy(txd);
2660         mtx_unlock(&txr->hn_tx_lock);
2661 #endif
2662
2663         if (txr->hn_tx_data_dtag != NULL)
2664                 bus_dma_tag_destroy(txr->hn_tx_data_dtag);
2665         if (txr->hn_tx_rndis_dtag != NULL)
2666                 bus_dma_tag_destroy(txr->hn_tx_rndis_dtag);
2667
2668 #ifdef HN_USE_TXDESC_BUFRING
2669         buf_ring_free(txr->hn_txdesc_br, M_NETVSC);
2670 #endif
2671
2672         free(txr->hn_txdesc, M_NETVSC);
2673         txr->hn_txdesc = NULL;
2674
2675         if (txr->hn_mbuf_br != NULL)
2676                 buf_ring_free(txr->hn_mbuf_br, M_NETVSC);
2677
2678 #ifndef HN_USE_TXDESC_BUFRING
2679         mtx_destroy(&txr->hn_txlist_spin);
2680 #endif
2681         mtx_destroy(&txr->hn_tx_lock);
2682 }
2683
2684 static int
2685 hn_create_tx_data(struct hn_softc *sc, int ring_cnt)
2686 {
2687         struct sysctl_oid_list *child;
2688         struct sysctl_ctx_list *ctx;
2689         int i;
2690
2691         sc->hn_tx_ring_cnt = ring_cnt;
2692         sc->hn_tx_ring_inuse = sc->hn_tx_ring_cnt;
2693
2694         sc->hn_tx_ring = malloc(sizeof(struct hn_tx_ring) * sc->hn_tx_ring_cnt,
2695             M_NETVSC, M_WAITOK | M_ZERO);
2696
2697         ctx = device_get_sysctl_ctx(sc->hn_dev);
2698         child = SYSCTL_CHILDREN(device_get_sysctl_tree(sc->hn_dev));
2699
2700         /* Create dev.hn.UNIT.tx sysctl tree */
2701         sc->hn_tx_sysctl_tree = SYSCTL_ADD_NODE(ctx, child, OID_AUTO, "tx",
2702             CTLFLAG_RD | CTLFLAG_MPSAFE, 0, "");
2703
2704         for (i = 0; i < sc->hn_tx_ring_cnt; ++i) {
2705                 int error;
2706
2707                 error = hn_create_tx_ring(sc, i);
2708                 if (error)
2709                         return error;
2710         }
2711
2712         SYSCTL_ADD_PROC(ctx, child, OID_AUTO, "no_txdescs",
2713             CTLTYPE_ULONG | CTLFLAG_RW | CTLFLAG_MPSAFE, sc,
2714             __offsetof(struct hn_tx_ring, hn_no_txdescs),
2715             hn_tx_stat_ulong_sysctl, "LU", "# of times short of TX descs");
2716         SYSCTL_ADD_PROC(ctx, child, OID_AUTO, "send_failed",
2717             CTLTYPE_ULONG | CTLFLAG_RW | CTLFLAG_MPSAFE, sc,
2718             __offsetof(struct hn_tx_ring, hn_send_failed),
2719             hn_tx_stat_ulong_sysctl, "LU", "# of hyper-v sending failure");
2720         SYSCTL_ADD_PROC(ctx, child, OID_AUTO, "txdma_failed",
2721             CTLTYPE_ULONG | CTLFLAG_RW | CTLFLAG_MPSAFE, sc,
2722             __offsetof(struct hn_tx_ring, hn_txdma_failed),
2723             hn_tx_stat_ulong_sysctl, "LU", "# of TX DMA failure");
2724         SYSCTL_ADD_PROC(ctx, child, OID_AUTO, "tx_collapsed",
2725             CTLTYPE_ULONG | CTLFLAG_RW | CTLFLAG_MPSAFE, sc,
2726             __offsetof(struct hn_tx_ring, hn_tx_collapsed),
2727             hn_tx_stat_ulong_sysctl, "LU", "# of TX mbuf collapsed");
2728         SYSCTL_ADD_PROC(ctx, child, OID_AUTO, "tx_chimney",
2729             CTLTYPE_ULONG | CTLFLAG_RW | CTLFLAG_MPSAFE, sc,
2730             __offsetof(struct hn_tx_ring, hn_tx_chimney),
2731             hn_tx_stat_ulong_sysctl, "LU", "# of chimney send");
2732         SYSCTL_ADD_PROC(ctx, child, OID_AUTO, "tx_chimney_tried",
2733             CTLTYPE_ULONG | CTLFLAG_RW | CTLFLAG_MPSAFE, sc,
2734             __offsetof(struct hn_tx_ring, hn_tx_chimney_tried),
2735             hn_tx_stat_ulong_sysctl, "LU", "# of chimney send tries");
2736         SYSCTL_ADD_INT(ctx, child, OID_AUTO, "txdesc_cnt",
2737             CTLFLAG_RD, &sc->hn_tx_ring[0].hn_txdesc_cnt, 0,
2738             "# of total TX descs");
2739         SYSCTL_ADD_INT(ctx, child, OID_AUTO, "tx_chimney_max",
2740             CTLFLAG_RD, &sc->hn_tx_chimney_max, 0,
2741             "Chimney send packet size upper boundary");
2742         SYSCTL_ADD_PROC(ctx, child, OID_AUTO, "tx_chimney_size",
2743             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
2744             hn_tx_chimney_size_sysctl,
2745             "I", "Chimney send packet size limit");
2746         SYSCTL_ADD_PROC(ctx, child, OID_AUTO, "direct_tx_size",
2747             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc,
2748             __offsetof(struct hn_tx_ring, hn_direct_tx_size),
2749             hn_tx_conf_int_sysctl, "I",
2750             "Size of the packet for direct transmission");
2751         SYSCTL_ADD_PROC(ctx, child, OID_AUTO, "sched_tx",
2752             CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc,
2753             __offsetof(struct hn_tx_ring, hn_sched_tx),
2754             hn_tx_conf_int_sysctl, "I",
2755             "Always schedule transmission "
2756             "instead of doing direct transmission");
2757         SYSCTL_ADD_INT(ctx, child, OID_AUTO, "tx_ring_cnt",
2758             CTLFLAG_RD, &sc->hn_tx_ring_cnt, 0, "# created TX rings");
2759         SYSCTL_ADD_INT(ctx, child, OID_AUTO, "tx_ring_inuse",
2760             CTLFLAG_RD, &sc->hn_tx_ring_inuse, 0, "# used TX rings");
2761
2762         return 0;
2763 }
2764
2765 static void
2766 hn_set_tx_chimney_size(struct hn_softc *sc, int chimney_size)
2767 {
2768         int i;
2769
2770         NV_LOCK(sc);
2771         for (i = 0; i < sc->hn_tx_ring_inuse; ++i)
2772                 sc->hn_tx_ring[i].hn_tx_chimney_size = chimney_size;
2773         NV_UNLOCK(sc);
2774 }
2775
2776 static void
2777 hn_destroy_tx_data(struct hn_softc *sc)
2778 {
2779         int i;
2780
2781         if (sc->hn_tx_ring_cnt == 0)
2782                 return;
2783
2784         for (i = 0; i < sc->hn_tx_ring_cnt; ++i)
2785                 hn_destroy_tx_ring(&sc->hn_tx_ring[i]);
2786
2787         free(sc->hn_tx_ring, M_NETVSC);
2788         sc->hn_tx_ring = NULL;
2789
2790         sc->hn_tx_ring_cnt = 0;
2791         sc->hn_tx_ring_inuse = 0;
2792 }
2793
2794 static void
2795 hn_start_taskfunc(void *xtxr, int pending __unused)
2796 {
2797         struct hn_tx_ring *txr = xtxr;
2798
2799         mtx_lock(&txr->hn_tx_lock);
2800         hn_start_locked(txr, 0);
2801         mtx_unlock(&txr->hn_tx_lock);
2802 }
2803
2804 static void
2805 hn_start_txeof_taskfunc(void *xtxr, int pending __unused)
2806 {
2807         struct hn_tx_ring *txr = xtxr;
2808
2809         mtx_lock(&txr->hn_tx_lock);
2810         atomic_clear_int(&txr->hn_sc->hn_ifp->if_drv_flags, IFF_DRV_OACTIVE);
2811         hn_start_locked(txr, 0);
2812         mtx_unlock(&txr->hn_tx_lock);
2813 }
2814
2815 static void
2816 hn_stop_tx_tasks(struct hn_softc *sc)
2817 {
2818         int i;
2819
2820         for (i = 0; i < sc->hn_tx_ring_inuse; ++i) {
2821                 struct hn_tx_ring *txr = &sc->hn_tx_ring[i];
2822
2823                 taskqueue_drain(txr->hn_tx_taskq, &txr->hn_tx_task);
2824                 taskqueue_drain(txr->hn_tx_taskq, &txr->hn_txeof_task);
2825         }
2826 }
2827
2828 static int
2829 hn_xmit(struct hn_tx_ring *txr, int len)
2830 {
2831         struct hn_softc *sc = txr->hn_sc;
2832         struct ifnet *ifp = sc->hn_ifp;
2833         struct mbuf *m_head;
2834
2835         mtx_assert(&txr->hn_tx_lock, MA_OWNED);
2836         KASSERT(hn_use_if_start == 0,
2837             ("hn_xmit is called, when if_start is enabled"));
2838
2839         if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 || txr->hn_oactive)
2840                 return 0;
2841
2842         while ((m_head = drbr_peek(ifp, txr->hn_mbuf_br)) != NULL) {
2843                 struct hn_txdesc *txd;
2844                 int error;
2845
2846                 if (len > 0 && m_head->m_pkthdr.len > len) {
2847                         /*
2848                          * This sending could be time consuming; let callers
2849                          * dispatch this packet sending (and sending of any
2850                          * following up packets) to tx taskqueue.
2851                          */
2852                         drbr_putback(ifp, txr->hn_mbuf_br, m_head);
2853                         return 1;
2854                 }
2855
2856                 txd = hn_txdesc_get(txr);
2857                 if (txd == NULL) {
2858                         txr->hn_no_txdescs++;
2859                         drbr_putback(ifp, txr->hn_mbuf_br, m_head);
2860                         txr->hn_oactive = 1;
2861                         break;
2862                 }
2863
2864                 error = hn_encap(txr, txd, &m_head);
2865                 if (error) {
2866                         /* Both txd and m_head are freed; discard */
2867                         drbr_advance(ifp, txr->hn_mbuf_br);
2868                         continue;
2869                 }
2870
2871                 error = hn_send_pkt(ifp, txr, txd);
2872                 if (__predict_false(error)) {
2873                         /* txd is freed, but m_head is not */
2874                         drbr_putback(ifp, txr->hn_mbuf_br, m_head);
2875                         txr->hn_oactive = 1;
2876                         break;
2877                 }
2878
2879                 /* Sent */
2880                 drbr_advance(ifp, txr->hn_mbuf_br);
2881         }
2882         return 0;
2883 }
2884
2885 static int
2886 hn_transmit(struct ifnet *ifp, struct mbuf *m)
2887 {
2888         struct hn_softc *sc = ifp->if_softc;
2889         struct hn_tx_ring *txr;
2890         int error, idx = 0;
2891
2892         /*
2893          * Select the TX ring based on flowid
2894          */
2895         if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE)
2896                 idx = m->m_pkthdr.flowid % sc->hn_tx_ring_inuse;
2897         txr = &sc->hn_tx_ring[idx];
2898
2899         error = drbr_enqueue(ifp, txr->hn_mbuf_br, m);
2900         if (error) {
2901                 if_inc_counter(ifp, IFCOUNTER_OQDROPS, 1);
2902                 return error;
2903         }
2904
2905         if (txr->hn_oactive)
2906                 return 0;
2907
2908         if (txr->hn_sched_tx)
2909                 goto do_sched;
2910
2911         if (mtx_trylock(&txr->hn_tx_lock)) {
2912                 int sched;
2913
2914                 sched = hn_xmit(txr, txr->hn_direct_tx_size);
2915                 mtx_unlock(&txr->hn_tx_lock);
2916                 if (!sched)
2917                         return 0;
2918         }
2919 do_sched:
2920         taskqueue_enqueue(txr->hn_tx_taskq, &txr->hn_tx_task);
2921         return 0;
2922 }
2923
2924 static void
2925 hn_xmit_qflush(struct ifnet *ifp)
2926 {
2927         struct hn_softc *sc = ifp->if_softc;
2928         int i;
2929
2930         for (i = 0; i < sc->hn_tx_ring_inuse; ++i) {
2931                 struct hn_tx_ring *txr = &sc->hn_tx_ring[i];
2932                 struct mbuf *m;
2933
2934                 mtx_lock(&txr->hn_tx_lock);
2935                 while ((m = buf_ring_dequeue_sc(txr->hn_mbuf_br)) != NULL)
2936                         m_freem(m);
2937                 mtx_unlock(&txr->hn_tx_lock);
2938         }
2939         if_qflush(ifp);
2940 }
2941
2942 static void
2943 hn_xmit_txeof(struct hn_tx_ring *txr)
2944 {
2945
2946         if (txr->hn_sched_tx)
2947                 goto do_sched;
2948
2949         if (mtx_trylock(&txr->hn_tx_lock)) {
2950                 int sched;
2951
2952                 txr->hn_oactive = 0;
2953                 sched = hn_xmit(txr, txr->hn_direct_tx_size);
2954                 mtx_unlock(&txr->hn_tx_lock);
2955                 if (sched) {
2956                         taskqueue_enqueue(txr->hn_tx_taskq,
2957                             &txr->hn_tx_task);
2958                 }
2959         } else {
2960 do_sched:
2961                 /*
2962                  * Release the oactive earlier, with the hope, that
2963                  * others could catch up.  The task will clear the
2964                  * oactive again with the hn_tx_lock to avoid possible
2965                  * races.
2966                  */
2967                 txr->hn_oactive = 0;
2968                 taskqueue_enqueue(txr->hn_tx_taskq, &txr->hn_txeof_task);
2969         }
2970 }
2971
2972 static void
2973 hn_xmit_taskfunc(void *xtxr, int pending __unused)
2974 {
2975         struct hn_tx_ring *txr = xtxr;
2976
2977         mtx_lock(&txr->hn_tx_lock);
2978         hn_xmit(txr, 0);
2979         mtx_unlock(&txr->hn_tx_lock);
2980 }
2981
2982 static void
2983 hn_xmit_txeof_taskfunc(void *xtxr, int pending __unused)
2984 {
2985         struct hn_tx_ring *txr = xtxr;
2986
2987         mtx_lock(&txr->hn_tx_lock);
2988         txr->hn_oactive = 0;
2989         hn_xmit(txr, 0);
2990         mtx_unlock(&txr->hn_tx_lock);
2991 }
2992
2993 static void
2994 hn_channel_attach(struct hn_softc *sc, struct hv_vmbus_channel *chan)
2995 {
2996         struct hn_rx_ring *rxr;
2997         int idx;
2998
2999         idx = chan->offer_msg.offer.sub_channel_index;
3000
3001         KASSERT(idx >= 0 && idx < sc->hn_rx_ring_inuse,
3002             ("invalid channel index %d, should > 0 && < %d",
3003              idx, sc->hn_rx_ring_inuse));
3004         rxr = &sc->hn_rx_ring[idx];
3005         KASSERT((rxr->hn_rx_flags & HN_RX_FLAG_ATTACHED) == 0,
3006             ("RX ring %d already attached", idx));
3007         rxr->hn_rx_flags |= HN_RX_FLAG_ATTACHED;
3008
3009         chan->hv_chan_rxr = rxr;
3010         if (bootverbose) {
3011                 if_printf(sc->hn_ifp, "link RX ring %d to channel%u\n",
3012                     idx, chan->offer_msg.child_rel_id);
3013         }
3014
3015         if (idx < sc->hn_tx_ring_inuse) {
3016                 struct hn_tx_ring *txr = &sc->hn_tx_ring[idx];
3017
3018                 KASSERT((txr->hn_tx_flags & HN_TX_FLAG_ATTACHED) == 0,
3019                     ("TX ring %d already attached", idx));
3020                 txr->hn_tx_flags |= HN_TX_FLAG_ATTACHED;
3021
3022                 chan->hv_chan_txr = txr;
3023                 txr->hn_chan = chan;
3024                 if (bootverbose) {
3025                         if_printf(sc->hn_ifp, "link TX ring %d to channel%u\n",
3026                             idx, chan->offer_msg.child_rel_id);
3027                 }
3028         }
3029
3030         /* Bind channel to a proper CPU */
3031         vmbus_channel_cpu_set(chan, (sc->hn_cpu + idx) % mp_ncpus);
3032 }
3033
3034 static void
3035 hn_subchan_attach(struct hn_softc *sc, struct hv_vmbus_channel *chan)
3036 {
3037
3038         KASSERT(!HV_VMBUS_CHAN_ISPRIMARY(chan),
3039             ("subchannel callback on primary channel"));
3040         KASSERT(chan->offer_msg.offer.sub_channel_index > 0,
3041             ("invalid channel subidx %u",
3042              chan->offer_msg.offer.sub_channel_index));
3043         hn_channel_attach(sc, chan);
3044 }
3045
3046 static void
3047 hn_subchan_setup(struct hn_softc *sc)
3048 {
3049         struct hv_device *device_ctx = vmbus_get_devctx(sc->hn_dev);
3050         struct hv_vmbus_channel **subchan;
3051         int subchan_cnt = sc->net_dev->num_channel - 1;
3052         int i;
3053
3054         /* Wait for sub-channels setup to complete. */
3055         subchan = vmbus_get_subchan(device_ctx->channel, subchan_cnt);
3056
3057         /* Attach the sub-channels. */
3058         for (i = 0; i < subchan_cnt; ++i) {
3059                 /* NOTE: Calling order is critical. */
3060                 hn_subchan_attach(sc, subchan[i]);
3061                 hv_nv_subchan_attach(subchan[i]);
3062         }
3063
3064         /* Release the sub-channels */
3065         vmbus_rel_subchan(subchan, subchan_cnt);
3066         if_printf(sc->hn_ifp, "%d sub-channels setup done\n", subchan_cnt);
3067 }
3068
3069 static void
3070 hn_tx_taskq_create(void *arg __unused)
3071 {
3072         if (!hn_share_tx_taskq)
3073                 return;
3074
3075         hn_tx_taskq = taskqueue_create("hn_tx", M_WAITOK,
3076             taskqueue_thread_enqueue, &hn_tx_taskq);
3077         taskqueue_start_threads(&hn_tx_taskq, 1, PI_NET, "hn tx");
3078         if (hn_bind_tx_taskq >= 0) {
3079                 int cpu = hn_bind_tx_taskq;
3080                 struct task cpuset_task;
3081                 cpuset_t cpu_set;
3082
3083                 if (cpu > mp_ncpus - 1)
3084                         cpu = mp_ncpus - 1;
3085                 CPU_SETOF(cpu, &cpu_set);
3086                 TASK_INIT(&cpuset_task, 0, hn_cpuset_setthread_task, &cpu_set);
3087                 taskqueue_enqueue(hn_tx_taskq, &cpuset_task);
3088                 taskqueue_drain(hn_tx_taskq, &cpuset_task);
3089         }
3090 }
3091 SYSINIT(hn_txtq_create, SI_SUB_DRIVERS, SI_ORDER_FIRST,
3092     hn_tx_taskq_create, NULL);
3093
3094 static void
3095 hn_tx_taskq_destroy(void *arg __unused)
3096 {
3097         if (hn_tx_taskq != NULL)
3098                 taskqueue_free(hn_tx_taskq);
3099 }
3100 SYSUNINIT(hn_txtq_destroy, SI_SUB_DRIVERS, SI_ORDER_FIRST,
3101     hn_tx_taskq_destroy, NULL);
3102
3103 static device_method_t netvsc_methods[] = {
3104         /* Device interface */
3105         DEVMETHOD(device_probe,         netvsc_probe),
3106         DEVMETHOD(device_attach,        netvsc_attach),
3107         DEVMETHOD(device_detach,        netvsc_detach),
3108         DEVMETHOD(device_shutdown,      netvsc_shutdown),
3109
3110         { 0, 0 }
3111 };
3112
3113 static driver_t netvsc_driver = {
3114         NETVSC_DEVNAME,
3115         netvsc_methods,
3116         sizeof(hn_softc_t)
3117 };
3118
3119 static devclass_t netvsc_devclass;
3120
3121 DRIVER_MODULE(hn, vmbus, netvsc_driver, netvsc_devclass, 0, 0);
3122 MODULE_VERSION(hn, 1);
3123 MODULE_DEPEND(hn, vmbus, 1, 1, 1);