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