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