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