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