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