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