]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/dev/hyperv/netvsc/hv_netvsc_drv_freebsd.c
MFC 295304,295305,295306
[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/queue.h>
70 #include <sys/lock.h>
71 #include <sys/sx.h>
72 #include <sys/sysctl.h>
73
74 #include <net/if.h>
75 #include <net/if_arp.h>
76 #include <net/ethernet.h>
77 #include <net/if_dl.h>
78 #include <net/if_media.h>
79
80 #include <net/bpf.h>
81
82 #include <net/if_types.h>
83 #include <net/if_vlan_var.h>
84 #include <net/if.h>
85
86 #include <netinet/in_systm.h>
87 #include <netinet/in.h>
88 #include <netinet/ip.h>
89 #include <netinet/if_ether.h>
90 #include <netinet/tcp.h>
91 #include <netinet/udp.h>
92 #include <netinet/ip6.h>
93
94 #include <vm/vm.h>
95 #include <vm/vm_param.h>
96 #include <vm/vm_kern.h>
97 #include <vm/pmap.h>
98
99 #include <machine/bus.h>
100 #include <machine/resource.h>
101 #include <machine/frame.h>
102 #include <machine/vmparam.h>
103
104 #include <sys/bus.h>
105 #include <sys/rman.h>
106 #include <sys/mutex.h>
107 #include <sys/errno.h>
108 #include <sys/types.h>
109 #include <machine/atomic.h>
110
111 #include <machine/intr_machdep.h>
112
113 #include <machine/in_cksum.h>
114
115 #include <dev/hyperv/include/hyperv.h>
116 #include "hv_net_vsc.h"
117 #include "hv_rndis.h"
118 #include "hv_rndis_filter.h"
119
120
121 /* Short for Hyper-V network interface */
122 #define NETVSC_DEVNAME    "hn"
123
124 /*
125  * It looks like offset 0 of buf is reserved to hold the softc pointer.
126  * The sc pointer evidently not needed, and is not presently populated.
127  * The packet offset is where the netvsc_packet starts in the buffer.
128  */
129 #define HV_NV_SC_PTR_OFFSET_IN_BUF         0
130 #define HV_NV_PACKET_OFFSET_IN_BUF         16
131
132 /* YYY should get it from the underlying channel */
133 #define HN_TX_DESC_CNT                  512
134
135 #define HN_LROENT_CNT_DEF               128
136
137 #define HN_RNDIS_MSG_LEN                \
138     (sizeof(rndis_msg) +                \
139      RNDIS_VLAN_PPI_SIZE +              \
140      RNDIS_TSO_PPI_SIZE +               \
141      RNDIS_CSUM_PPI_SIZE)
142 #define HN_RNDIS_MSG_BOUNDARY           PAGE_SIZE
143 #define HN_RNDIS_MSG_ALIGN              CACHE_LINE_SIZE
144
145 #define HN_TX_DATA_BOUNDARY             PAGE_SIZE
146 #define HN_TX_DATA_MAXSIZE              IP_MAXPACKET
147 #define HN_TX_DATA_SEGSIZE              PAGE_SIZE
148 #define HN_TX_DATA_SEGCNT_MAX           \
149     (NETVSC_PACKET_MAXPAGE - HV_RF_NUM_TX_RESERVED_PAGE_BUFS)
150
151 #define HN_DIRECT_TX_SIZE_DEF           128
152
153 struct hn_txdesc {
154         SLIST_ENTRY(hn_txdesc) link;
155         struct mbuf     *m;
156         struct hn_softc *sc;
157         int             refs;
158         uint32_t        flags;          /* HN_TXD_FLAG_ */
159         netvsc_packet   netvsc_pkt;     /* XXX to be removed */
160
161         bus_dmamap_t    data_dmap;
162
163         bus_addr_t      rndis_msg_paddr;
164         rndis_msg       *rndis_msg;
165         bus_dmamap_t    rndis_msg_dmap;
166 };
167
168 #define HN_TXD_FLAG_ONLIST      0x1
169 #define HN_TXD_FLAG_DMAMAP      0x2
170
171 /*
172  * Only enable UDP checksum offloading when it is on 2012R2 or
173  * later.  UDP checksum offloading doesn't work on earlier
174  * Windows releases.
175  */
176 #define HN_CSUM_ASSIST_WIN8     (CSUM_TCP)
177 #define HN_CSUM_ASSIST          (CSUM_IP | CSUM_UDP | CSUM_TCP)
178
179 /* XXX move to netinet/tcp_lro.h */
180 #define HN_LRO_HIWAT_MAX                                65535
181 #define HN_LRO_HIWAT_DEF                                HN_LRO_HIWAT_MAX
182 /* YYY 2*MTU is a bit rough, but should be good enough. */
183 #define HN_LRO_HIWAT_MTULIM(ifp)                        (2 * (ifp)->if_mtu)
184 #define HN_LRO_HIWAT_ISVALID(sc, hiwat)                 \
185     ((hiwat) >= HN_LRO_HIWAT_MTULIM((sc)->hn_ifp) ||    \
186      (hiwat) <= HN_LRO_HIWAT_MAX)
187
188 /*
189  * Be aware that this sleepable mutex will exhibit WITNESS errors when
190  * certain TCP and ARP code paths are taken.  This appears to be a
191  * well-known condition, as all other drivers checked use a sleeping
192  * mutex to protect their transmit paths.
193  * Also Be aware that mutexes do not play well with semaphores, and there
194  * is a conflicting semaphore in a certain channel code path.
195  */
196 #define NV_LOCK_INIT(_sc, _name) \
197             mtx_init(&(_sc)->hn_lock, _name, MTX_NETWORK_LOCK, MTX_DEF)
198 #define NV_LOCK(_sc)            mtx_lock(&(_sc)->hn_lock)
199 #define NV_TRYLOCK(_sc)         mtx_trylock(&(_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 /* Trust tcp segements verification on host side. */
212 static int hn_trust_hosttcp = 1;
213 TUNABLE_INT("dev.hn.trust_hosttcp", &hn_trust_hosttcp);
214
215 /* Trust udp datagrams verification on host side. */
216 static int hn_trust_hostudp = 1;
217 TUNABLE_INT("dev.hn.trust_hostudp", &hn_trust_hostudp);
218
219 /* Trust ip packets verification on host side. */
220 static int hn_trust_hostip = 1;
221 TUNABLE_INT("dev.hn.trust_hostip", &hn_trust_hostip);
222
223 #if __FreeBSD_version >= 1100045
224 /* Limit TSO burst size */
225 static int hn_tso_maxlen = 0;
226 TUNABLE_INT("dev.hn.tso_maxlen", &hn_tso_maxlen);
227 #endif
228
229 /* Limit chimney send size */
230 static int hn_tx_chimney_size = 0;
231 TUNABLE_INT("dev.hn.tx_chimney_size", &hn_tx_chimney_size);
232
233 /* Limit the size of packet for direct transmission */
234 static int hn_direct_tx_size = HN_DIRECT_TX_SIZE_DEF;
235 TUNABLE_INT("dev.hn.direct_tx_size", &hn_direct_tx_size);
236
237 #if defined(INET) || defined(INET6)
238 #if __FreeBSD_version >= 1100095
239 static int hn_lro_entry_count = HN_LROENT_CNT_DEF;
240 TUNABLE_INT("dev.hn.lro_entry_count", &hn_lro_entry_count);
241 #endif
242 #endif
243
244 /*
245  * Forward declarations
246  */
247 static void hn_stop(hn_softc_t *sc);
248 static void hn_ifinit_locked(hn_softc_t *sc);
249 static void hn_ifinit(void *xsc);
250 static int  hn_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data);
251 static int hn_start_locked(struct ifnet *ifp, int len);
252 static void hn_start(struct ifnet *ifp);
253 static void hn_start_txeof(struct ifnet *ifp);
254 static int hn_ifmedia_upd(struct ifnet *ifp);
255 static void hn_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr);
256 #ifdef HN_LRO_HIWAT
257 static int hn_lro_hiwat_sysctl(SYSCTL_HANDLER_ARGS);
258 #endif
259 static int hn_trust_hcsum_sysctl(SYSCTL_HANDLER_ARGS);
260 static int hn_tx_chimney_size_sysctl(SYSCTL_HANDLER_ARGS);
261 static int hn_check_iplen(const struct mbuf *, int);
262 static int hn_create_tx_ring(struct hn_softc *sc);
263 static void hn_destroy_tx_ring(struct hn_softc *sc);
264 static void hn_start_taskfunc(void *xsc, int pending);
265 static void hn_txeof_taskfunc(void *xsc, int pending);
266 static int hn_encap(struct hn_softc *, struct hn_txdesc *, struct mbuf **);
267
268 static __inline void
269 hn_set_lro_hiwat(struct hn_softc *sc, int hiwat)
270 {
271         sc->hn_lro_hiwat = hiwat;
272 #ifdef HN_LRO_HIWAT
273         sc->hn_lro.lro_hiwat = sc->hn_lro_hiwat;
274 #endif
275 }
276
277 static int
278 hn_ifmedia_upd(struct ifnet *ifp __unused)
279 {
280
281         return EOPNOTSUPP;
282 }
283
284 static void
285 hn_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr)
286 {
287         struct hn_softc *sc = ifp->if_softc;
288
289         ifmr->ifm_status = IFM_AVALID;
290         ifmr->ifm_active = IFM_ETHER;
291
292         if (!sc->hn_carrier) {
293                 ifmr->ifm_active |= IFM_NONE;
294                 return;
295         }
296         ifmr->ifm_status |= IFM_ACTIVE;
297         ifmr->ifm_active |= IFM_10G_T | IFM_FDX;
298 }
299
300 /* {F8615163-DF3E-46c5-913F-F2D2F965ED0E} */
301 static const hv_guid g_net_vsc_device_type = {
302         .data = {0x63, 0x51, 0x61, 0xF8, 0x3E, 0xDF, 0xc5, 0x46,
303                 0x91, 0x3F, 0xF2, 0xD2, 0xF9, 0x65, 0xED, 0x0E}
304 };
305
306 /*
307  * Standard probe entry point.
308  *
309  */
310 static int
311 netvsc_probe(device_t dev)
312 {
313         const char *p;
314
315         p = vmbus_get_type(dev);
316         if (!memcmp(p, &g_net_vsc_device_type.data, sizeof(hv_guid))) {
317                 device_set_desc(dev, "Synthetic Network Interface");
318                 if (bootverbose)
319                         printf("Netvsc probe... DONE \n");
320
321                 return (BUS_PROBE_DEFAULT);
322         }
323
324         return (ENXIO);
325 }
326
327 /*
328  * Standard attach entry point.
329  *
330  * Called when the driver is loaded.  It allocates needed resources,
331  * and initializes the "hardware" and software.
332  */
333 static int
334 netvsc_attach(device_t dev)
335 {
336         struct hv_device *device_ctx = vmbus_get_devctx(dev);
337         netvsc_device_info device_info;
338         hn_softc_t *sc;
339         int unit = device_get_unit(dev);
340         struct ifnet *ifp = NULL;
341         struct sysctl_oid_list *child;
342         struct sysctl_ctx_list *ctx;
343         int error;
344 #if __FreeBSD_version >= 1100045
345         int tso_maxlen;
346 #endif
347 #if defined(INET) || defined(INET6)
348 #if __FreeBSD_version >= 1100095
349         int lroent_cnt;
350 #endif
351 #endif
352
353         sc = device_get_softc(dev);
354         if (sc == NULL) {
355                 return (ENOMEM);
356         }
357
358         bzero(sc, sizeof(hn_softc_t));
359         sc->hn_unit = unit;
360         sc->hn_dev = dev;
361         sc->hn_lro_hiwat = HN_LRO_HIWAT_DEF;
362         sc->hn_direct_tx_size = hn_direct_tx_size;
363         if (hn_trust_hosttcp)
364                 sc->hn_trust_hcsum |= HN_TRUST_HCSUM_TCP;
365         if (hn_trust_hostudp)
366                 sc->hn_trust_hcsum |= HN_TRUST_HCSUM_UDP;
367         if (hn_trust_hostip)
368                 sc->hn_trust_hcsum |= HN_TRUST_HCSUM_IP;
369
370         sc->hn_tx_taskq = taskqueue_create_fast("hn_tx", M_WAITOK,
371             taskqueue_thread_enqueue, &sc->hn_tx_taskq);
372         taskqueue_start_threads(&sc->hn_tx_taskq, 1, PI_NET, "%s tx",
373             device_get_nameunit(dev));
374         TASK_INIT(&sc->hn_start_task, 0, hn_start_taskfunc, sc);
375         TASK_INIT(&sc->hn_txeof_task, 0, hn_txeof_taskfunc, sc);
376
377         error = hn_create_tx_ring(sc);
378         if (error)
379                 goto failed;
380
381         NV_LOCK_INIT(sc, "NetVSCLock");
382
383         sc->hn_dev_obj = device_ctx;
384
385         ifp = sc->hn_ifp = sc->arpcom.ac_ifp = if_alloc(IFT_ETHER);
386         ifp->if_softc = sc;
387
388         if_initname(ifp, device_get_name(dev), device_get_unit(dev));
389         ifp->if_dunit = unit;
390         ifp->if_dname = NETVSC_DEVNAME;
391
392         ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
393         ifp->if_ioctl = hn_ioctl;
394         ifp->if_start = hn_start;
395         ifp->if_init = hn_ifinit;
396         /* needed by hv_rf_on_device_add() code */
397         ifp->if_mtu = ETHERMTU;
398         IFQ_SET_MAXLEN(&ifp->if_snd, 512);
399         ifp->if_snd.ifq_drv_maxlen = 511;
400         IFQ_SET_READY(&ifp->if_snd);
401
402         ifmedia_init(&sc->hn_media, 0, hn_ifmedia_upd, hn_ifmedia_sts);
403         ifmedia_add(&sc->hn_media, IFM_ETHER | IFM_AUTO, 0, NULL);
404         ifmedia_set(&sc->hn_media, IFM_ETHER | IFM_AUTO);
405         /* XXX ifmedia_set really should do this for us */
406         sc->hn_media.ifm_media = sc->hn_media.ifm_cur->ifm_media;
407
408         /*
409          * Tell upper layers that we support full VLAN capability.
410          */
411         ifp->if_data.ifi_hdrlen = sizeof(struct ether_vlan_header);
412         ifp->if_capabilities |=
413             IFCAP_VLAN_HWTAGGING | IFCAP_VLAN_MTU | IFCAP_HWCSUM | IFCAP_TSO |
414             IFCAP_LRO;
415         ifp->if_capenable |=
416             IFCAP_VLAN_HWTAGGING | IFCAP_VLAN_MTU | IFCAP_HWCSUM | IFCAP_TSO |
417             IFCAP_LRO;
418
419         if (hv_vmbus_protocal_version >= HV_VMBUS_VERSION_WIN8_1)
420                 sc->hn_csum_assist = HN_CSUM_ASSIST;
421         else
422                 sc->hn_csum_assist = HN_CSUM_ASSIST_WIN8;
423         ifp->if_hwassist = sc->hn_csum_assist | CSUM_TSO;
424
425         error = hv_rf_on_device_add(device_ctx, &device_info);
426         if (error)
427                 goto failed;
428
429         if (device_info.link_state == 0) {
430                 sc->hn_carrier = 1;
431         }
432
433 #if defined(INET) || defined(INET6)
434 #if __FreeBSD_version >= 1100095
435         lroent_cnt = hn_lro_entry_count;
436         if (lroent_cnt < TCP_LRO_ENTRIES)
437                 lroent_cnt = TCP_LRO_ENTRIES;
438         tcp_lro_init_args(&sc->hn_lro, ifp, lroent_cnt, 0);
439         device_printf(dev, "LRO: entry count %d\n", lroent_cnt);
440 #else
441         tcp_lro_init(&sc->hn_lro);
442         /* Driver private LRO settings */
443         sc->hn_lro.ifp = ifp;
444 #endif
445 #ifdef HN_LRO_HIWAT
446         sc->hn_lro.lro_hiwat = sc->hn_lro_hiwat;
447 #endif
448 #endif  /* INET || INET6 */
449
450 #if __FreeBSD_version >= 1100045
451         tso_maxlen = hn_tso_maxlen;
452         if (tso_maxlen <= 0 || tso_maxlen > IP_MAXPACKET)
453                 tso_maxlen = IP_MAXPACKET;
454
455         ifp->if_hw_tsomaxsegcount = HN_TX_DATA_SEGCNT_MAX;
456         ifp->if_hw_tsomaxsegsize = PAGE_SIZE;
457         ifp->if_hw_tsomax = tso_maxlen -
458             (ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN);
459 #endif
460
461         ether_ifattach(ifp, device_info.mac_addr);
462
463 #if __FreeBSD_version >= 1100045
464         if_printf(ifp, "TSO: %u/%u/%u\n", ifp->if_hw_tsomax,
465             ifp->if_hw_tsomaxsegcount, ifp->if_hw_tsomaxsegsize);
466 #endif
467
468         sc->hn_tx_chimney_max = sc->net_dev->send_section_size;
469         sc->hn_tx_chimney_size = sc->hn_tx_chimney_max;
470         if (hn_tx_chimney_size > 0 &&
471             hn_tx_chimney_size < sc->hn_tx_chimney_max)
472                 sc->hn_tx_chimney_size = hn_tx_chimney_size;
473
474         ctx = device_get_sysctl_ctx(dev);
475         child = SYSCTL_CHILDREN(device_get_sysctl_tree(dev));
476
477         SYSCTL_ADD_INT(ctx, child, OID_AUTO, "lro_queued",
478             CTLFLAG_RW, &sc->hn_lro.lro_queued, 0, "LRO queued");
479         SYSCTL_ADD_INT(ctx, child, OID_AUTO, "lro_flushed",
480             CTLFLAG_RW, &sc->hn_lro.lro_flushed, 0, "LRO flushed");
481         SYSCTL_ADD_ULONG(ctx, child, OID_AUTO, "lro_tried",
482             CTLFLAG_RW, &sc->hn_lro_tried, "# of LRO tries");
483 #ifdef HN_LRO_HIWAT
484         SYSCTL_ADD_PROC(ctx, child, OID_AUTO, "lro_hiwat",
485             CTLTYPE_INT | CTLFLAG_RW, sc, 0, hn_lro_hiwat_sysctl,
486             "I", "LRO high watermark");
487 #endif
488         SYSCTL_ADD_PROC(ctx, child, OID_AUTO, "trust_hosttcp",
489             CTLTYPE_INT | CTLFLAG_RW, sc, HN_TRUST_HCSUM_TCP,
490             hn_trust_hcsum_sysctl, "I",
491             "Trust tcp segement verification on host side, "
492             "when csum info is missing");
493         SYSCTL_ADD_PROC(ctx, child, OID_AUTO, "trust_hostudp",
494             CTLTYPE_INT | CTLFLAG_RW, sc, HN_TRUST_HCSUM_UDP,
495             hn_trust_hcsum_sysctl, "I",
496             "Trust udp datagram verification on host side, "
497             "when csum info is missing");
498         SYSCTL_ADD_PROC(ctx, child, OID_AUTO, "trust_hostip",
499             CTLTYPE_INT | CTLFLAG_RW, sc, HN_TRUST_HCSUM_IP,
500             hn_trust_hcsum_sysctl, "I",
501             "Trust ip packet verification on host side, "
502             "when csum info is missing");
503         SYSCTL_ADD_ULONG(ctx, child, OID_AUTO, "csum_ip",
504             CTLFLAG_RW, &sc->hn_csum_ip, "RXCSUM IP");
505         SYSCTL_ADD_ULONG(ctx, child, OID_AUTO, "csum_tcp",
506             CTLFLAG_RW, &sc->hn_csum_tcp, "RXCSUM TCP");
507         SYSCTL_ADD_ULONG(ctx, child, OID_AUTO, "csum_udp",
508             CTLFLAG_RW, &sc->hn_csum_udp, "RXCSUM UDP");
509         SYSCTL_ADD_ULONG(ctx, child, OID_AUTO, "csum_trusted",
510             CTLFLAG_RW, &sc->hn_csum_trusted,
511             "# of packets that we trust host's csum verification");
512         SYSCTL_ADD_ULONG(ctx, child, OID_AUTO, "small_pkts",
513             CTLFLAG_RW, &sc->hn_small_pkts, "# of small packets received");
514         SYSCTL_ADD_ULONG(ctx, child, OID_AUTO, "no_txdescs",
515             CTLFLAG_RW, &sc->hn_no_txdescs, "# of times short of TX descs");
516         SYSCTL_ADD_ULONG(ctx, child, OID_AUTO, "send_failed",
517             CTLFLAG_RW, &sc->hn_send_failed, "# of hyper-v sending failure");
518         SYSCTL_ADD_ULONG(ctx, child, OID_AUTO, "txdma_failed",
519             CTLFLAG_RW, &sc->hn_txdma_failed, "# of TX DMA failure");
520         SYSCTL_ADD_ULONG(ctx, child, OID_AUTO, "tx_collapsed",
521             CTLFLAG_RW, &sc->hn_tx_collapsed, "# of TX mbuf collapsed");
522         SYSCTL_ADD_ULONG(ctx, child, OID_AUTO, "tx_chimney",
523             CTLFLAG_RW, &sc->hn_tx_chimney, "# of chimney send");
524         SYSCTL_ADD_INT(ctx, child, OID_AUTO, "txdesc_cnt",
525             CTLFLAG_RD, &sc->hn_txdesc_cnt, 0, "# of total TX descs");
526         SYSCTL_ADD_INT(ctx, child, OID_AUTO, "txdesc_avail",
527             CTLFLAG_RD, &sc->hn_txdesc_avail, 0, "# of available TX descs");
528         SYSCTL_ADD_INT(ctx, child, OID_AUTO, "tx_chimney_max",
529             CTLFLAG_RD, &sc->hn_tx_chimney_max, 0,
530             "Chimney send packet size upper boundary");
531         SYSCTL_ADD_PROC(ctx, child, OID_AUTO, "tx_chimney_size",
532             CTLTYPE_INT | CTLFLAG_RW, sc, 0, hn_tx_chimney_size_sysctl,
533             "I", "Chimney send packet size limit");
534         SYSCTL_ADD_INT(ctx, child, OID_AUTO, "direct_tx_size",
535             CTLFLAG_RW, &sc->hn_direct_tx_size, 0,
536             "Size of the packet for direct transmission");
537         SYSCTL_ADD_INT(ctx, child, OID_AUTO, "sched_tx",
538             CTLFLAG_RW, &sc->hn_sched_tx, 0,
539             "Always schedule transmission "
540             "instead of doing direct transmission");
541
542         if (unit == 0) {
543                 struct sysctl_ctx_list *dc_ctx;
544                 struct sysctl_oid_list *dc_child;
545                 devclass_t dc;
546
547                 /*
548                  * Add sysctl nodes for devclass
549                  */
550                 dc = device_get_devclass(dev);
551                 dc_ctx = devclass_get_sysctl_ctx(dc);
552                 dc_child = SYSCTL_CHILDREN(devclass_get_sysctl_tree(dc));
553
554                 SYSCTL_ADD_INT(dc_ctx, dc_child, OID_AUTO, "trust_hosttcp",
555                     CTLFLAG_RD, &hn_trust_hosttcp, 0,
556                     "Trust tcp segement verification on host side, "
557                     "when csum info is missing (global setting)");
558                 SYSCTL_ADD_INT(dc_ctx, dc_child, OID_AUTO, "trust_hostudp",
559                     CTLFLAG_RD, &hn_trust_hostudp, 0,
560                     "Trust udp datagram verification on host side, "
561                     "when csum info is missing (global setting)");
562                 SYSCTL_ADD_INT(dc_ctx, dc_child, OID_AUTO, "trust_hostip",
563                     CTLFLAG_RD, &hn_trust_hostip, 0,
564                     "Trust ip packet verification on host side, "
565                     "when csum info is missing (global setting)");
566                 SYSCTL_ADD_INT(dc_ctx, dc_child, OID_AUTO, "tx_chimney_size",
567                     CTLFLAG_RD, &hn_tx_chimney_size, 0,
568                     "Chimney send packet size limit");
569 #if __FreeBSD_version >= 1100045
570                 SYSCTL_ADD_INT(dc_ctx, dc_child, OID_AUTO, "tso_maxlen",
571                     CTLFLAG_RD, &hn_tso_maxlen, 0, "TSO burst limit");
572 #endif
573                 SYSCTL_ADD_INT(dc_ctx, dc_child, OID_AUTO, "direct_tx_size",
574                     CTLFLAG_RD, &hn_direct_tx_size, 0,
575                     "Size of the packet for direct transmission");
576 #if defined(INET) || defined(INET6)
577 #if __FreeBSD_version >= 1100095
578                 SYSCTL_ADD_INT(dc_ctx, dc_child, OID_AUTO, "lro_entry_count",
579                     CTLFLAG_RD, &hn_lro_entry_count, 0, "LRO entry count");
580 #endif
581 #endif
582         }
583
584         return (0);
585 failed:
586         hn_destroy_tx_ring(sc);
587         if (ifp != NULL)
588                 if_free(ifp);
589         return (error);
590 }
591
592 /*
593  * Standard detach entry point
594  */
595 static int
596 netvsc_detach(device_t dev)
597 {
598         struct hn_softc *sc = device_get_softc(dev);
599         struct hv_device *hv_device = vmbus_get_devctx(dev); 
600
601         if (bootverbose)
602                 printf("netvsc_detach\n");
603
604         /*
605          * XXXKYS:  Need to clean up all our
606          * driver state; this is the driver
607          * unloading.
608          */
609
610         /*
611          * XXXKYS:  Need to stop outgoing traffic and unregister
612          * the netdevice.
613          */
614
615         hv_rf_on_device_remove(hv_device, HV_RF_NV_DESTROY_CHANNEL);
616
617         taskqueue_drain(sc->hn_tx_taskq, &sc->hn_start_task);
618         taskqueue_drain(sc->hn_tx_taskq, &sc->hn_txeof_task);
619         taskqueue_free(sc->hn_tx_taskq);
620
621         ifmedia_removeall(&sc->hn_media);
622 #if defined(INET) || defined(INET6)
623         tcp_lro_free(&sc->hn_lro);
624 #endif
625         hn_destroy_tx_ring(sc);
626
627         return (0);
628 }
629
630 /*
631  * Standard shutdown entry point
632  */
633 static int
634 netvsc_shutdown(device_t dev)
635 {
636         return (0);
637 }
638
639 static __inline int
640 hn_txdesc_dmamap_load(struct hn_softc *sc, struct hn_txdesc *txd,
641     struct mbuf **m_head, bus_dma_segment_t *segs, int *nsegs)
642 {
643         struct mbuf *m = *m_head;
644         int error;
645
646         error = bus_dmamap_load_mbuf_sg(sc->hn_tx_data_dtag, txd->data_dmap,
647             m, segs, nsegs, BUS_DMA_NOWAIT);
648         if (error == EFBIG) {
649                 struct mbuf *m_new;
650
651                 m_new = m_collapse(m, M_NOWAIT, HN_TX_DATA_SEGCNT_MAX);
652                 if (m_new == NULL)
653                         return ENOBUFS;
654                 else
655                         *m_head = m = m_new;
656                 sc->hn_tx_collapsed++;
657
658                 error = bus_dmamap_load_mbuf_sg(sc->hn_tx_data_dtag,
659                     txd->data_dmap, m, segs, nsegs, BUS_DMA_NOWAIT);
660         }
661         if (!error) {
662                 bus_dmamap_sync(sc->hn_tx_data_dtag, txd->data_dmap,
663                     BUS_DMASYNC_PREWRITE);
664                 txd->flags |= HN_TXD_FLAG_DMAMAP;
665         }
666         return error;
667 }
668
669 static __inline void
670 hn_txdesc_dmamap_unload(struct hn_softc *sc, struct hn_txdesc *txd)
671 {
672
673         if (txd->flags & HN_TXD_FLAG_DMAMAP) {
674                 bus_dmamap_sync(sc->hn_tx_data_dtag,
675                     txd->data_dmap, BUS_DMASYNC_POSTWRITE);
676                 bus_dmamap_unload(sc->hn_tx_data_dtag,
677                     txd->data_dmap);
678                 txd->flags &= ~HN_TXD_FLAG_DMAMAP;
679         }
680 }
681
682 static __inline int
683 hn_txdesc_put(struct hn_softc *sc, struct hn_txdesc *txd)
684 {
685
686         KASSERT((txd->flags & HN_TXD_FLAG_ONLIST) == 0,
687             ("put an onlist txd %#x", txd->flags));
688
689         KASSERT(txd->refs > 0, ("invalid txd refs %d", txd->refs));
690         if (atomic_fetchadd_int(&txd->refs, -1) != 1)
691                 return 0;
692
693         hn_txdesc_dmamap_unload(sc, txd);
694         if (txd->m != NULL) {
695                 m_freem(txd->m);
696                 txd->m = NULL;
697         }
698
699         txd->flags |= HN_TXD_FLAG_ONLIST;
700
701         mtx_lock_spin(&sc->hn_txlist_spin);
702         KASSERT(sc->hn_txdesc_avail >= 0 &&
703             sc->hn_txdesc_avail < sc->hn_txdesc_cnt,
704             ("txdesc_put: invalid txd avail %d", sc->hn_txdesc_avail));
705         sc->hn_txdesc_avail++;
706         SLIST_INSERT_HEAD(&sc->hn_txlist, txd, link);
707         mtx_unlock_spin(&sc->hn_txlist_spin);
708
709         return 1;
710 }
711
712 static __inline struct hn_txdesc *
713 hn_txdesc_get(struct hn_softc *sc)
714 {
715         struct hn_txdesc *txd;
716
717         mtx_lock_spin(&sc->hn_txlist_spin);
718         txd = SLIST_FIRST(&sc->hn_txlist);
719         if (txd != NULL) {
720                 KASSERT(sc->hn_txdesc_avail > 0,
721                     ("txdesc_get: invalid txd avail %d", sc->hn_txdesc_avail));
722                 sc->hn_txdesc_avail--;
723                 SLIST_REMOVE_HEAD(&sc->hn_txlist, link);
724         }
725         mtx_unlock_spin(&sc->hn_txlist_spin);
726
727         if (txd != NULL) {
728                 KASSERT(txd->m == NULL && txd->refs == 0 &&
729                     (txd->flags & HN_TXD_FLAG_ONLIST), ("invalid txd"));
730                 txd->flags &= ~HN_TXD_FLAG_ONLIST;
731                 txd->refs = 1;
732         }
733         return txd;
734 }
735
736 static __inline void
737 hn_txdesc_hold(struct hn_txdesc *txd)
738 {
739
740         /* 0->1 transition will never work */
741         KASSERT(txd->refs > 0, ("invalid refs %d", txd->refs));
742         atomic_add_int(&txd->refs, 1);
743 }
744
745 /*
746  * Send completion processing
747  *
748  * Note:  It looks like offset 0 of buf is reserved to hold the softc
749  * pointer.  The sc pointer is not currently needed in this function, and
750  * it is not presently populated by the TX function.
751  */
752 void
753 netvsc_xmit_completion(void *context)
754 {
755         netvsc_packet *packet = context;
756         struct hn_txdesc *txd;
757         struct hn_softc *sc;
758
759         txd = (struct hn_txdesc *)(uintptr_t)
760             packet->compl.send.send_completion_tid;
761
762         sc = txd->sc;
763         sc->hn_txeof = 1;
764         hn_txdesc_put(sc, txd);
765 }
766
767 void
768 netvsc_channel_rollup(struct hv_device *device_ctx)
769 {
770         struct hn_softc *sc = device_get_softc(device_ctx->device);
771 #if defined(INET) || defined(INET6)
772         struct lro_ctrl *lro = &sc->hn_lro;
773         struct lro_entry *queued;
774
775         while ((queued = SLIST_FIRST(&lro->lro_active)) != NULL) {
776                 SLIST_REMOVE_HEAD(&lro->lro_active, next);
777                 tcp_lro_flush(lro, queued);
778         }
779 #endif
780
781         if (!sc->hn_txeof)
782                 return;
783
784         sc->hn_txeof = 0;
785         hn_start_txeof(sc->hn_ifp);
786 }
787
788 /*
789  * NOTE:
790  * This this function fails, then both txd and m_head0 will be freed
791  */
792 static int
793 hn_encap(struct hn_softc *sc, struct hn_txdesc *txd, struct mbuf **m_head0)
794 {
795         bus_dma_segment_t segs[HN_TX_DATA_SEGCNT_MAX];
796         int error, nsegs, i;
797         struct mbuf *m_head = *m_head0;
798         netvsc_packet *packet;
799         rndis_msg *rndis_mesg;
800         rndis_packet *rndis_pkt;
801         rndis_per_packet_info *rppi;
802         uint32_t rndis_msg_size;
803
804         packet = &txd->netvsc_pkt;
805         packet->is_data_pkt = TRUE;
806         packet->tot_data_buf_len = m_head->m_pkthdr.len;
807
808         /*
809          * extension points to the area reserved for the
810          * rndis_filter_packet, which is placed just after
811          * the netvsc_packet (and rppi struct, if present;
812          * length is updated later).
813          */
814         rndis_mesg = txd->rndis_msg;
815         /* XXX not necessary */
816         memset(rndis_mesg, 0, HN_RNDIS_MSG_LEN);
817         rndis_mesg->ndis_msg_type = REMOTE_NDIS_PACKET_MSG;
818
819         rndis_pkt = &rndis_mesg->msg.packet;
820         rndis_pkt->data_offset = sizeof(rndis_packet);
821         rndis_pkt->data_length = packet->tot_data_buf_len;
822         rndis_pkt->per_pkt_info_offset = sizeof(rndis_packet);
823
824         rndis_msg_size = RNDIS_MESSAGE_SIZE(rndis_packet);
825
826         if (m_head->m_flags & M_VLANTAG) {
827                 ndis_8021q_info *rppi_vlan_info;
828
829                 rndis_msg_size += RNDIS_VLAN_PPI_SIZE;
830                 rppi = hv_set_rppi_data(rndis_mesg, RNDIS_VLAN_PPI_SIZE,
831                     ieee_8021q_info);
832
833                 rppi_vlan_info = (ndis_8021q_info *)((uint8_t *)rppi +
834                     rppi->per_packet_info_offset);
835                 rppi_vlan_info->u1.s1.vlan_id =
836                     m_head->m_pkthdr.ether_vtag & 0xfff;
837         }
838
839         if (m_head->m_pkthdr.csum_flags & CSUM_TSO) {
840                 rndis_tcp_tso_info *tso_info;   
841                 struct ether_vlan_header *eh;
842                 int ether_len;
843
844                 /*
845                  * XXX need m_pullup and use mtodo
846                  */
847                 eh = mtod(m_head, struct ether_vlan_header*);
848                 if (eh->evl_encap_proto == htons(ETHERTYPE_VLAN))
849                         ether_len = ETHER_HDR_LEN + ETHER_VLAN_ENCAP_LEN;
850                 else
851                         ether_len = ETHER_HDR_LEN;
852
853                 rndis_msg_size += RNDIS_TSO_PPI_SIZE;
854                 rppi = hv_set_rppi_data(rndis_mesg, RNDIS_TSO_PPI_SIZE,
855                     tcp_large_send_info);
856
857                 tso_info = (rndis_tcp_tso_info *)((uint8_t *)rppi +
858                     rppi->per_packet_info_offset);
859                 tso_info->lso_v2_xmit.type =
860                     RNDIS_TCP_LARGE_SEND_OFFLOAD_V2_TYPE;
861
862 #ifdef INET
863                 if (m_head->m_pkthdr.csum_flags & CSUM_IP_TSO) {
864                         struct ip *ip =
865                             (struct ip *)(m_head->m_data + ether_len);
866                         unsigned long iph_len = ip->ip_hl << 2;
867                         struct tcphdr *th =
868                             (struct tcphdr *)((caddr_t)ip + iph_len);
869
870                         tso_info->lso_v2_xmit.ip_version =
871                             RNDIS_TCP_LARGE_SEND_OFFLOAD_IPV4;
872                         ip->ip_len = 0;
873                         ip->ip_sum = 0;
874
875                         th->th_sum = in_pseudo(ip->ip_src.s_addr,
876                             ip->ip_dst.s_addr, htons(IPPROTO_TCP));
877                 }
878 #endif
879 #if defined(INET6) && defined(INET)
880                 else
881 #endif
882 #ifdef INET6
883                 {
884                         struct ip6_hdr *ip6 = (struct ip6_hdr *)
885                             (m_head->m_data + ether_len);
886                         struct tcphdr *th = (struct tcphdr *)(ip6 + 1);
887
888                         tso_info->lso_v2_xmit.ip_version =
889                             RNDIS_TCP_LARGE_SEND_OFFLOAD_IPV6;
890                         ip6->ip6_plen = 0;
891                         th->th_sum = in6_cksum_pseudo(ip6, 0, IPPROTO_TCP, 0);
892                 }
893 #endif
894                 tso_info->lso_v2_xmit.tcp_header_offset = 0;
895                 tso_info->lso_v2_xmit.mss = m_head->m_pkthdr.tso_segsz;
896         } else if (m_head->m_pkthdr.csum_flags & sc->hn_csum_assist) {
897                 rndis_tcp_ip_csum_info *csum_info;
898
899                 rndis_msg_size += RNDIS_CSUM_PPI_SIZE;
900                 rppi = hv_set_rppi_data(rndis_mesg, RNDIS_CSUM_PPI_SIZE,
901                     tcpip_chksum_info);
902                 csum_info = (rndis_tcp_ip_csum_info *)((uint8_t *)rppi +
903                     rppi->per_packet_info_offset);
904
905                 csum_info->xmit.is_ipv4 = 1;
906                 if (m_head->m_pkthdr.csum_flags & CSUM_IP)
907                         csum_info->xmit.ip_header_csum = 1;
908
909                 if (m_head->m_pkthdr.csum_flags & CSUM_TCP) {
910                         csum_info->xmit.tcp_csum = 1;
911                         csum_info->xmit.tcp_header_offset = 0;
912                 } else if (m_head->m_pkthdr.csum_flags & CSUM_UDP) {
913                         csum_info->xmit.udp_csum = 1;
914                 }
915         }
916
917         rndis_mesg->msg_len = packet->tot_data_buf_len + rndis_msg_size;
918         packet->tot_data_buf_len = rndis_mesg->msg_len;
919
920         /*
921          * Chimney send, if the packet could fit into one chimney buffer.
922          */
923         if (packet->tot_data_buf_len < sc->hn_tx_chimney_size) {
924                 netvsc_dev *net_dev = sc->net_dev;
925                 uint32_t send_buf_section_idx;
926
927                 send_buf_section_idx =
928                     hv_nv_get_next_send_section(net_dev);
929                 if (send_buf_section_idx !=
930                     NVSP_1_CHIMNEY_SEND_INVALID_SECTION_INDEX) {
931                         uint8_t *dest = ((uint8_t *)net_dev->send_buf +
932                             (send_buf_section_idx *
933                              net_dev->send_section_size));
934
935                         memcpy(dest, rndis_mesg, rndis_msg_size);
936                         dest += rndis_msg_size;
937                         m_copydata(m_head, 0, m_head->m_pkthdr.len, dest);
938
939                         packet->send_buf_section_idx = send_buf_section_idx;
940                         packet->send_buf_section_size =
941                             packet->tot_data_buf_len;
942                         packet->page_buf_count = 0;
943                         sc->hn_tx_chimney++;
944                         goto done;
945                 }
946         }
947
948         error = hn_txdesc_dmamap_load(sc, txd, &m_head, segs, &nsegs);
949         if (error) {
950                 int freed;
951
952                 /*
953                  * This mbuf is not linked w/ the txd yet, so free it now.
954                  */
955                 m_freem(m_head);
956                 *m_head0 = NULL;
957
958                 freed = hn_txdesc_put(sc, txd);
959                 KASSERT(freed != 0,
960                     ("fail to free txd upon txdma error"));
961
962                 sc->hn_txdma_failed++;
963                 if_inc_counter(sc->hn_ifp, IFCOUNTER_OERRORS, 1);
964                 return error;
965         }
966         *m_head0 = m_head;
967
968         packet->page_buf_count = nsegs + HV_RF_NUM_TX_RESERVED_PAGE_BUFS;
969
970         /* send packet with page buffer */
971         packet->page_buffers[0].pfn = atop(txd->rndis_msg_paddr);
972         packet->page_buffers[0].offset = txd->rndis_msg_paddr & PAGE_MASK;
973         packet->page_buffers[0].length = rndis_msg_size;
974
975         /*
976          * Fill the page buffers with mbuf info starting at index
977          * HV_RF_NUM_TX_RESERVED_PAGE_BUFS.
978          */
979         for (i = 0; i < nsegs; ++i) {
980                 hv_vmbus_page_buffer *pb = &packet->page_buffers[
981                     i + HV_RF_NUM_TX_RESERVED_PAGE_BUFS];
982
983                 pb->pfn = atop(segs[i].ds_addr);
984                 pb->offset = segs[i].ds_addr & PAGE_MASK;
985                 pb->length = segs[i].ds_len;
986         }
987
988         packet->send_buf_section_idx =
989             NVSP_1_CHIMNEY_SEND_INVALID_SECTION_INDEX;
990         packet->send_buf_section_size = 0;
991 done:
992         txd->m = m_head;
993
994         /* Set the completion routine */
995         packet->compl.send.on_send_completion = netvsc_xmit_completion;
996         packet->compl.send.send_completion_context = packet;
997         packet->compl.send.send_completion_tid = (uint64_t)(uintptr_t)txd;
998
999         return 0;
1000 }
1001
1002 /*
1003  * Start a transmit of one or more packets
1004  */
1005 static int
1006 hn_start_locked(struct ifnet *ifp, int len)
1007 {
1008         struct hn_softc *sc = ifp->if_softc;
1009         struct hv_device *device_ctx = vmbus_get_devctx(sc->hn_dev);
1010
1011         if ((ifp->if_drv_flags & (IFF_DRV_RUNNING | IFF_DRV_OACTIVE)) !=
1012             IFF_DRV_RUNNING)
1013                 return 0;
1014
1015         while (!IFQ_DRV_IS_EMPTY(&ifp->if_snd)) {
1016                 int error, send_failed = 0;
1017                 struct hn_txdesc *txd;
1018                 struct mbuf *m_head;
1019
1020                 IFQ_DRV_DEQUEUE(&ifp->if_snd, m_head);
1021                 if (m_head == NULL)
1022                         break;
1023
1024                 if (len > 0 && m_head->m_pkthdr.len > len) {
1025                         /*
1026                          * This sending could be time consuming; let callers
1027                          * dispatch this packet sending (and sending of any
1028                          * following up packets) to tx taskqueue.
1029                          */
1030                         IF_PREPEND(&ifp->if_snd, m_head);
1031                         return 1;
1032                 }
1033
1034                 txd = hn_txdesc_get(sc);
1035                 if (txd == NULL) {
1036                         sc->hn_no_txdescs++;
1037                         IF_PREPEND(&ifp->if_snd, m_head);
1038                         atomic_set_int(&ifp->if_drv_flags, IFF_DRV_OACTIVE);
1039                         break;
1040                 }
1041
1042                 error = hn_encap(sc, txd, &m_head);
1043                 if (error) {
1044                         /* Both txd and m_head are freed */
1045                         continue;
1046                 }
1047 again:
1048                 /*
1049                  * Make sure that txd is not freed before ETHER_BPF_MTAP.
1050                  */
1051                 hn_txdesc_hold(txd);
1052                 error = hv_nv_on_send(device_ctx, &txd->netvsc_pkt);
1053                 if (!error) {
1054                         ETHER_BPF_MTAP(ifp, m_head);
1055                         if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1);
1056                 }
1057                 hn_txdesc_put(sc, txd);
1058
1059                 if (__predict_false(error)) {
1060                         int freed;
1061
1062                         /*
1063                          * This should "really rarely" happen.
1064                          *
1065                          * XXX Too many RX to be acked or too many sideband
1066                          * commands to run?  Ask netvsc_channel_rollup()
1067                          * to kick start later.
1068                          */
1069                         sc->hn_txeof = 1;
1070                         if (!send_failed) {
1071                                 sc->hn_send_failed++;
1072                                 send_failed = 1;
1073                                 /*
1074                                  * Try sending again after set hn_txeof;
1075                                  * in case that we missed the last
1076                                  * netvsc_channel_rollup().
1077                                  */
1078                                 goto again;
1079                         }
1080                         if_printf(ifp, "send failed\n");
1081
1082                         /*
1083                          * This mbuf will be prepended, don't free it
1084                          * in hn_txdesc_put(); only unload it from the
1085                          * DMA map in hn_txdesc_put(), if it was loaded.
1086                          */
1087                         txd->m = NULL;
1088                         freed = hn_txdesc_put(sc, txd);
1089                         KASSERT(freed != 0,
1090                             ("fail to free txd upon send error"));
1091
1092                         sc->hn_send_failed++;
1093                         IF_PREPEND(&ifp->if_snd, m_head);
1094                         atomic_set_int(&ifp->if_drv_flags, IFF_DRV_OACTIVE);
1095                         break;
1096                 }
1097         }
1098         return 0;
1099 }
1100
1101 /*
1102  * Link up/down notification
1103  */
1104 void
1105 netvsc_linkstatus_callback(struct hv_device *device_obj, uint32_t status)
1106 {
1107         hn_softc_t *sc = device_get_softc(device_obj->device);
1108
1109         if (sc == NULL) {
1110                 return;
1111         }
1112
1113         if (status == 1) {
1114                 sc->hn_carrier = 1;
1115         } else {
1116                 sc->hn_carrier = 0;
1117         }
1118 }
1119
1120 /*
1121  * Append the specified data to the indicated mbuf chain,
1122  * Extend the mbuf chain if the new data does not fit in
1123  * existing space.
1124  *
1125  * This is a minor rewrite of m_append() from sys/kern/uipc_mbuf.c.
1126  * There should be an equivalent in the kernel mbuf code,
1127  * but there does not appear to be one yet.
1128  *
1129  * Differs from m_append() in that additional mbufs are
1130  * allocated with cluster size MJUMPAGESIZE, and filled
1131  * accordingly.
1132  *
1133  * Return 1 if able to complete the job; otherwise 0.
1134  */
1135 static int
1136 hv_m_append(struct mbuf *m0, int len, c_caddr_t cp)
1137 {
1138         struct mbuf *m, *n;
1139         int remainder, space;
1140
1141         for (m = m0; m->m_next != NULL; m = m->m_next)
1142                 ;
1143         remainder = len;
1144         space = M_TRAILINGSPACE(m);
1145         if (space > 0) {
1146                 /*
1147                  * Copy into available space.
1148                  */
1149                 if (space > remainder)
1150                         space = remainder;
1151                 bcopy(cp, mtod(m, caddr_t) + m->m_len, space);
1152                 m->m_len += space;
1153                 cp += space;
1154                 remainder -= space;
1155         }
1156         while (remainder > 0) {
1157                 /*
1158                  * Allocate a new mbuf; could check space
1159                  * and allocate a cluster instead.
1160                  */
1161                 n = m_getjcl(M_DONTWAIT, m->m_type, 0, MJUMPAGESIZE);
1162                 if (n == NULL)
1163                         break;
1164                 n->m_len = min(MJUMPAGESIZE, remainder);
1165                 bcopy(cp, mtod(n, caddr_t), n->m_len);
1166                 cp += n->m_len;
1167                 remainder -= n->m_len;
1168                 m->m_next = n;
1169                 m = n;
1170         }
1171         if (m0->m_flags & M_PKTHDR)
1172                 m0->m_pkthdr.len += len - remainder;
1173
1174         return (remainder == 0);
1175 }
1176
1177
1178 /*
1179  * Called when we receive a data packet from the "wire" on the
1180  * specified device
1181  *
1182  * Note:  This is no longer used as a callback
1183  */
1184 int
1185 netvsc_recv(struct hv_device *device_ctx, netvsc_packet *packet,
1186     rndis_tcp_ip_csum_info *csum_info)
1187 {
1188         hn_softc_t *sc = (hn_softc_t *)device_get_softc(device_ctx->device);
1189         struct mbuf *m_new;
1190         struct ifnet *ifp;
1191         device_t dev = device_ctx->device;
1192         int size, do_lro = 0, do_csum = 1;
1193
1194         if (sc == NULL) {
1195                 return (0); /* TODO: KYS how can this be! */
1196         }
1197
1198         ifp = sc->hn_ifp;
1199         
1200         ifp = sc->arpcom.ac_ifp;
1201
1202         if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
1203                 return (0);
1204         }
1205
1206         /*
1207          * Bail out if packet contains more data than configured MTU.
1208          */
1209         if (packet->tot_data_buf_len > (ifp->if_mtu + ETHER_HDR_LEN)) {
1210                 return (0);
1211         } else if (packet->tot_data_buf_len <= MHLEN) {
1212                 m_new = m_gethdr(M_NOWAIT, MT_DATA);
1213                 if (m_new == NULL)
1214                         return (0);
1215                 memcpy(mtod(m_new, void *), packet->data,
1216                     packet->tot_data_buf_len);
1217                 m_new->m_pkthdr.len = m_new->m_len = packet->tot_data_buf_len;
1218                 sc->hn_small_pkts++;
1219         } else {
1220                 /*
1221                  * Get an mbuf with a cluster.  For packets 2K or less,
1222                  * get a standard 2K cluster.  For anything larger, get a
1223                  * 4K cluster.  Any buffers larger than 4K can cause problems
1224                  * if looped around to the Hyper-V TX channel, so avoid them.
1225                  */
1226                 size = MCLBYTES;
1227                 if (packet->tot_data_buf_len > MCLBYTES) {
1228                         /* 4096 */
1229                         size = MJUMPAGESIZE;
1230                 }
1231
1232                 m_new = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR, size);
1233                 if (m_new == NULL) {
1234                         device_printf(dev, "alloc mbuf failed.\n");
1235                         return (0);
1236                 }
1237
1238                 hv_m_append(m_new, packet->tot_data_buf_len, packet->data);
1239         }
1240         m_new->m_pkthdr.rcvif = ifp;
1241
1242         if (__predict_false((ifp->if_capenable & IFCAP_RXCSUM) == 0))
1243                 do_csum = 0;
1244
1245         /* receive side checksum offload */
1246         if (csum_info != NULL) {
1247                 /* IP csum offload */
1248                 if (csum_info->receive.ip_csum_succeeded && do_csum) {
1249                         m_new->m_pkthdr.csum_flags |=
1250                             (CSUM_IP_CHECKED | CSUM_IP_VALID);
1251                         sc->hn_csum_ip++;
1252                 }
1253
1254                 /* TCP/UDP csum offload */
1255                 if ((csum_info->receive.tcp_csum_succeeded ||
1256                      csum_info->receive.udp_csum_succeeded) && do_csum) {
1257                         m_new->m_pkthdr.csum_flags |=
1258                             (CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
1259                         m_new->m_pkthdr.csum_data = 0xffff;
1260                         if (csum_info->receive.tcp_csum_succeeded)
1261                                 sc->hn_csum_tcp++;
1262                         else
1263                                 sc->hn_csum_udp++;
1264                 }
1265
1266                 if (csum_info->receive.ip_csum_succeeded &&
1267                     csum_info->receive.tcp_csum_succeeded)
1268                         do_lro = 1;
1269         } else {
1270                 const struct ether_header *eh;
1271                 uint16_t etype;
1272                 int hoff;
1273
1274                 hoff = sizeof(*eh);
1275                 if (m_new->m_len < hoff)
1276                         goto skip;
1277                 eh = mtod(m_new, struct ether_header *);
1278                 etype = ntohs(eh->ether_type);
1279                 if (etype == ETHERTYPE_VLAN) {
1280                         const struct ether_vlan_header *evl;
1281
1282                         hoff = sizeof(*evl);
1283                         if (m_new->m_len < hoff)
1284                                 goto skip;
1285                         evl = mtod(m_new, struct ether_vlan_header *);
1286                         etype = ntohs(evl->evl_proto);
1287                 }
1288
1289                 if (etype == ETHERTYPE_IP) {
1290                         int pr;
1291
1292                         pr = hn_check_iplen(m_new, hoff);
1293                         if (pr == IPPROTO_TCP) {
1294                                 if (do_csum &&
1295                                     (sc->hn_trust_hcsum & HN_TRUST_HCSUM_TCP)) {
1296                                         sc->hn_csum_trusted++;
1297                                         m_new->m_pkthdr.csum_flags |=
1298                                            (CSUM_IP_CHECKED | CSUM_IP_VALID |
1299                                             CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
1300                                         m_new->m_pkthdr.csum_data = 0xffff;
1301                                 }
1302                                 /* Rely on SW csum verification though... */
1303                                 do_lro = 1;
1304                         } else if (pr == IPPROTO_UDP) {
1305                                 if (do_csum &&
1306                                     (sc->hn_trust_hcsum & HN_TRUST_HCSUM_UDP)) {
1307                                         sc->hn_csum_trusted++;
1308                                         m_new->m_pkthdr.csum_flags |=
1309                                            (CSUM_IP_CHECKED | CSUM_IP_VALID |
1310                                             CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
1311                                         m_new->m_pkthdr.csum_data = 0xffff;
1312                                 }
1313                         } else if (pr != IPPROTO_DONE && do_csum &&
1314                             (sc->hn_trust_hcsum & HN_TRUST_HCSUM_IP)) {
1315                                 sc->hn_csum_trusted++;
1316                                 m_new->m_pkthdr.csum_flags |=
1317                                     (CSUM_IP_CHECKED | CSUM_IP_VALID);
1318                         }
1319                 }
1320         }
1321 skip:
1322         if ((packet->vlan_tci != 0) &&
1323             (ifp->if_capenable & IFCAP_VLAN_HWTAGGING) != 0) {
1324                 m_new->m_pkthdr.ether_vtag = packet->vlan_tci;
1325                 m_new->m_flags |= M_VLANTAG;
1326         }
1327
1328         /*
1329          * Note:  Moved RX completion back to hv_nv_on_receive() so all
1330          * messages (not just data messages) will trigger a response.
1331          */
1332
1333         ifp->if_ipackets++;
1334
1335         if ((ifp->if_capenable & IFCAP_LRO) && do_lro) {
1336 #if defined(INET) || defined(INET6)
1337                 struct lro_ctrl *lro = &sc->hn_lro;
1338
1339                 if (lro->lro_cnt) {
1340                         sc->hn_lro_tried++;
1341                         if (tcp_lro_rx(lro, m_new, 0) == 0) {
1342                                 /* DONE! */
1343                                 return 0;
1344                         }
1345                 }
1346 #endif
1347         }
1348
1349         /* We're not holding the lock here, so don't release it */
1350         (*ifp->if_input)(ifp, m_new);
1351
1352         return (0);
1353 }
1354
1355 void
1356 netvsc_recv_rollup(struct hv_device *device_ctx __unused)
1357 {
1358 }
1359
1360 /*
1361  * Rules for using sc->temp_unusable:
1362  * 1.  sc->temp_unusable can only be read or written while holding NV_LOCK()
1363  * 2.  code reading sc->temp_unusable under NV_LOCK(), and finding 
1364  *     sc->temp_unusable set, must release NV_LOCK() and exit
1365  * 3.  to retain exclusive control of the interface,
1366  *     sc->temp_unusable must be set by code before releasing NV_LOCK()
1367  * 4.  only code setting sc->temp_unusable can clear sc->temp_unusable
1368  * 5.  code setting sc->temp_unusable must eventually clear sc->temp_unusable
1369  */
1370
1371 /*
1372  * Standard ioctl entry point.  Called when the user wants to configure
1373  * the interface.
1374  */
1375 static int
1376 hn_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1377 {
1378         hn_softc_t *sc = ifp->if_softc;
1379         struct ifreq *ifr = (struct ifreq *)data;
1380 #ifdef INET
1381         struct ifaddr *ifa = (struct ifaddr *)data;
1382 #endif
1383         netvsc_device_info device_info;
1384         struct hv_device *hn_dev;
1385         int mask, error = 0;
1386         int retry_cnt = 500;
1387         
1388         switch(cmd) {
1389
1390         case SIOCSIFADDR:
1391 #ifdef INET
1392                 if (ifa->ifa_addr->sa_family == AF_INET) {
1393                         ifp->if_flags |= IFF_UP;
1394                         if (!(ifp->if_drv_flags & IFF_DRV_RUNNING))
1395                                 hn_ifinit(sc);
1396                         arp_ifinit(ifp, ifa);
1397                 } else
1398 #endif
1399                 error = ether_ioctl(ifp, cmd, data);
1400                 break;
1401         case SIOCSIFMTU:
1402                 hn_dev = vmbus_get_devctx(sc->hn_dev);
1403
1404                 /* Check MTU value change */
1405                 if (ifp->if_mtu == ifr->ifr_mtu)
1406                         break;
1407
1408                 if (ifr->ifr_mtu > NETVSC_MAX_CONFIGURABLE_MTU) {
1409                         error = EINVAL;
1410                         break;
1411                 }
1412
1413                 /* Obtain and record requested MTU */
1414                 ifp->if_mtu = ifr->ifr_mtu;
1415                 /*
1416                  * Make sure that LRO high watermark is still valid,
1417                  * after MTU change (the 2*MTU limit).
1418                  */
1419                 if (!HN_LRO_HIWAT_ISVALID(sc, sc->hn_lro_hiwat))
1420                         hn_set_lro_hiwat(sc, HN_LRO_HIWAT_MTULIM(ifp));
1421
1422                 do {
1423                         NV_LOCK(sc);
1424                         if (!sc->temp_unusable) {
1425                                 sc->temp_unusable = TRUE;
1426                                 retry_cnt = -1;
1427                         }
1428                         NV_UNLOCK(sc);
1429                         if (retry_cnt > 0) {
1430                                 retry_cnt--;
1431                                 DELAY(5 * 1000);
1432                         }
1433                 } while (retry_cnt > 0);
1434
1435                 if (retry_cnt == 0) {
1436                         error = EINVAL;
1437                         break;
1438                 }
1439
1440                 /* We must remove and add back the device to cause the new
1441                  * MTU to take effect.  This includes tearing down, but not
1442                  * deleting the channel, then bringing it back up.
1443                  */
1444                 error = hv_rf_on_device_remove(hn_dev, HV_RF_NV_RETAIN_CHANNEL);
1445                 if (error) {
1446                         NV_LOCK(sc);
1447                         sc->temp_unusable = FALSE;
1448                         NV_UNLOCK(sc);
1449                         break;
1450                 }
1451                 error = hv_rf_on_device_add(hn_dev, &device_info);
1452                 if (error) {
1453                         NV_LOCK(sc);
1454                         sc->temp_unusable = FALSE;
1455                         NV_UNLOCK(sc);
1456                         break;
1457                 }
1458
1459                 sc->hn_tx_chimney_max = sc->net_dev->send_section_size;
1460                 if (sc->hn_tx_chimney_size > sc->hn_tx_chimney_max)
1461                         sc->hn_tx_chimney_size = sc->hn_tx_chimney_max;
1462                 hn_ifinit_locked(sc);
1463
1464                 NV_LOCK(sc);
1465                 sc->temp_unusable = FALSE;
1466                 NV_UNLOCK(sc);
1467                 break;
1468         case SIOCSIFFLAGS:
1469                 do {
1470                        NV_LOCK(sc);
1471                        if (!sc->temp_unusable) {
1472                                sc->temp_unusable = TRUE;
1473                                retry_cnt = -1;
1474                        }
1475                        NV_UNLOCK(sc);
1476                        if (retry_cnt > 0) {
1477                                 retry_cnt--;
1478                                 DELAY(5 * 1000);
1479                        }
1480                 } while (retry_cnt > 0);
1481
1482                 if (retry_cnt == 0) {
1483                        error = EINVAL;
1484                        break;
1485                 }
1486
1487                 if (ifp->if_flags & IFF_UP) {
1488                         /*
1489                          * If only the state of the PROMISC flag changed,
1490                          * then just use the 'set promisc mode' command
1491                          * instead of reinitializing the entire NIC. Doing
1492                          * a full re-init means reloading the firmware and
1493                          * waiting for it to start up, which may take a
1494                          * second or two.
1495                          */
1496 #ifdef notyet
1497                         /* Fixme:  Promiscuous mode? */
1498                         if (ifp->if_drv_flags & IFF_DRV_RUNNING &&
1499                             ifp->if_flags & IFF_PROMISC &&
1500                             !(sc->hn_if_flags & IFF_PROMISC)) {
1501                                 /* do something here for Hyper-V */
1502                         } else if (ifp->if_drv_flags & IFF_DRV_RUNNING &&
1503                             !(ifp->if_flags & IFF_PROMISC) &&
1504                             sc->hn_if_flags & IFF_PROMISC) {
1505                                 /* do something here for Hyper-V */
1506                         } else
1507 #endif
1508                                 hn_ifinit_locked(sc);
1509                 } else {
1510                         if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1511                                 hn_stop(sc);
1512                         }
1513                 }
1514                 NV_LOCK(sc);
1515                 sc->temp_unusable = FALSE;
1516                 NV_UNLOCK(sc);
1517                 sc->hn_if_flags = ifp->if_flags;
1518                 error = 0;
1519                 break;
1520         case SIOCSIFCAP:
1521                 NV_LOCK(sc);
1522
1523                 mask = ifr->ifr_reqcap ^ ifp->if_capenable;
1524                 if (mask & IFCAP_TXCSUM) {
1525                         ifp->if_capenable ^= IFCAP_TXCSUM;
1526                         if (ifp->if_capenable & IFCAP_TXCSUM)
1527                                 ifp->if_hwassist |= sc->hn_csum_assist;
1528                         else
1529                                 ifp->if_hwassist &= ~sc->hn_csum_assist;
1530                 }
1531
1532                 if (mask & IFCAP_RXCSUM)
1533                         ifp->if_capenable ^= IFCAP_RXCSUM;
1534
1535                 if (mask & IFCAP_LRO)
1536                         ifp->if_capenable ^= IFCAP_LRO;
1537
1538                 if (mask & IFCAP_TSO4) {
1539                         ifp->if_capenable ^= IFCAP_TSO4;
1540                         if (ifp->if_capenable & IFCAP_TSO4)
1541                                 ifp->if_hwassist |= CSUM_IP_TSO;
1542                         else
1543                                 ifp->if_hwassist &= ~CSUM_IP_TSO;
1544                 }
1545
1546                 if (mask & IFCAP_TSO6) {
1547                         ifp->if_capenable ^= IFCAP_TSO6;
1548                         if (ifp->if_capenable & IFCAP_TSO6)
1549                                 ifp->if_hwassist |= CSUM_IP6_TSO;
1550                         else
1551                                 ifp->if_hwassist &= ~CSUM_IP6_TSO;
1552                 }
1553
1554                 NV_UNLOCK(sc);
1555                 error = 0;
1556                 break;
1557         case SIOCADDMULTI:
1558         case SIOCDELMULTI:
1559 #ifdef notyet
1560                 /* Fixme:  Multicast mode? */
1561                 if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1562                         NV_LOCK(sc);
1563                         netvsc_setmulti(sc);
1564                         NV_UNLOCK(sc);
1565                         error = 0;
1566                 }
1567 #endif
1568                 error = EINVAL;
1569                 break;
1570         case SIOCSIFMEDIA:
1571         case SIOCGIFMEDIA:
1572                 error = ifmedia_ioctl(ifp, ifr, &sc->hn_media, cmd);
1573                 break;
1574         default:
1575                 error = ether_ioctl(ifp, cmd, data);
1576                 break;
1577         }
1578
1579         return (error);
1580 }
1581
1582 /*
1583  *
1584  */
1585 static void
1586 hn_stop(hn_softc_t *sc)
1587 {
1588         struct ifnet *ifp;
1589         int ret;
1590         struct hv_device *device_ctx = vmbus_get_devctx(sc->hn_dev);
1591
1592         ifp = sc->hn_ifp;
1593
1594         if (bootverbose)
1595                 printf(" Closing Device ...\n");
1596
1597         atomic_clear_int(&ifp->if_drv_flags,
1598             (IFF_DRV_RUNNING | IFF_DRV_OACTIVE));
1599         if_link_state_change(ifp, LINK_STATE_DOWN);
1600         sc->hn_initdone = 0;
1601
1602         ret = hv_rf_on_close(device_ctx);
1603 }
1604
1605 /*
1606  * FreeBSD transmit entry point
1607  */
1608 static void
1609 hn_start(struct ifnet *ifp)
1610 {
1611         struct hn_softc *sc = ifp->if_softc;
1612
1613         if (sc->hn_sched_tx)
1614                 goto do_sched;
1615
1616         if (NV_TRYLOCK(sc)) {
1617                 int sched;
1618
1619                 sched = hn_start_locked(ifp, sc->hn_direct_tx_size);
1620                 NV_UNLOCK(sc);
1621                 if (!sched)
1622                         return;
1623         }
1624 do_sched:
1625         taskqueue_enqueue_fast(sc->hn_tx_taskq, &sc->hn_start_task);
1626 }
1627
1628 static void
1629 hn_start_txeof(struct ifnet *ifp)
1630 {
1631         struct hn_softc *sc = ifp->if_softc;
1632
1633         if (sc->hn_sched_tx)
1634                 goto do_sched;
1635
1636         if (NV_TRYLOCK(sc)) {
1637                 int sched;
1638
1639                 atomic_clear_int(&ifp->if_drv_flags, IFF_DRV_OACTIVE);
1640                 sched = hn_start_locked(ifp, sc->hn_direct_tx_size);
1641                 NV_UNLOCK(sc);
1642                 if (sched) {
1643                         taskqueue_enqueue_fast(sc->hn_tx_taskq,
1644                             &sc->hn_start_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 NV_LOCK to avoid possible
1652                  * races.
1653                  */
1654                 atomic_clear_int(&ifp->if_drv_flags, IFF_DRV_OACTIVE);
1655                 taskqueue_enqueue_fast(sc->hn_tx_taskq, &sc->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;
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         atomic_clear_int(&ifp->if_drv_flags, IFF_DRV_OACTIVE);
1684         atomic_set_int(&ifp->if_drv_flags, IFF_DRV_RUNNING);
1685         if_link_state_change(ifp, LINK_STATE_UP);
1686 }
1687
1688 /*
1689  *
1690  */
1691 static void
1692 hn_ifinit(void *xsc)
1693 {
1694         hn_softc_t *sc = xsc;
1695
1696         NV_LOCK(sc);
1697         if (sc->temp_unusable) {
1698                 NV_UNLOCK(sc);
1699                 return;
1700         }
1701         sc->temp_unusable = TRUE;
1702         NV_UNLOCK(sc);
1703
1704         hn_ifinit_locked(sc);
1705
1706         NV_LOCK(sc);
1707         sc->temp_unusable = FALSE;
1708         NV_UNLOCK(sc);
1709 }
1710
1711 #ifdef LATER
1712 /*
1713  *
1714  */
1715 static void
1716 hn_watchdog(struct ifnet *ifp)
1717 {
1718         hn_softc_t *sc;
1719         sc = ifp->if_softc;
1720
1721         printf("hn%d: watchdog timeout -- resetting\n", sc->hn_unit);
1722         hn_ifinit(sc);    /*???*/
1723         ifp->if_oerrors++;
1724 }
1725 #endif
1726
1727 #ifdef HN_LRO_HIWAT
1728 static int
1729 hn_lro_hiwat_sysctl(SYSCTL_HANDLER_ARGS)
1730 {
1731         struct hn_softc *sc = arg1;
1732         int hiwat, error;
1733
1734         hiwat = sc->hn_lro_hiwat;
1735         error = sysctl_handle_int(oidp, &hiwat, 0, req);
1736         if (error || req->newptr == NULL)
1737                 return error;
1738
1739         if (!HN_LRO_HIWAT_ISVALID(sc, hiwat))
1740                 return EINVAL;
1741
1742         if (sc->hn_lro_hiwat != hiwat)
1743                 hn_set_lro_hiwat(sc, hiwat);
1744         return 0;
1745 }
1746 #endif  /* HN_LRO_HIWAT */
1747
1748 static int
1749 hn_trust_hcsum_sysctl(SYSCTL_HANDLER_ARGS)
1750 {
1751         struct hn_softc *sc = arg1;
1752         int hcsum = arg2;
1753         int on, error;
1754
1755         on = 0;
1756         if (sc->hn_trust_hcsum & hcsum)
1757                 on = 1;
1758
1759         error = sysctl_handle_int(oidp, &on, 0, req);
1760         if (error || req->newptr == NULL)
1761                 return error;
1762
1763         NV_LOCK(sc);
1764         if (on)
1765                 sc->hn_trust_hcsum |= hcsum;
1766         else
1767                 sc->hn_trust_hcsum &= ~hcsum;
1768         NV_UNLOCK(sc);
1769         return 0;
1770 }
1771
1772 static int
1773 hn_tx_chimney_size_sysctl(SYSCTL_HANDLER_ARGS)
1774 {
1775         struct hn_softc *sc = arg1;
1776         int chimney_size, error;
1777
1778         chimney_size = sc->hn_tx_chimney_size;
1779         error = sysctl_handle_int(oidp, &chimney_size, 0, req);
1780         if (error || req->newptr == NULL)
1781                 return error;
1782
1783         if (chimney_size > sc->hn_tx_chimney_max || chimney_size <= 0)
1784                 return EINVAL;
1785
1786         if (sc->hn_tx_chimney_size != chimney_size)
1787                 sc->hn_tx_chimney_size = chimney_size;
1788         return 0;
1789 }
1790
1791 static int
1792 hn_check_iplen(const struct mbuf *m, int hoff)
1793 {
1794         const struct ip *ip;
1795         int len, iphlen, iplen;
1796         const struct tcphdr *th;
1797         int thoff;                              /* TCP data offset */
1798
1799         len = hoff + sizeof(struct ip);
1800
1801         /* The packet must be at least the size of an IP header. */
1802         if (m->m_pkthdr.len < len)
1803                 return IPPROTO_DONE;
1804
1805         /* The fixed IP header must reside completely in the first mbuf. */
1806         if (m->m_len < len)
1807                 return IPPROTO_DONE;
1808
1809         ip = mtodo(m, hoff);
1810
1811         /* Bound check the packet's stated IP header length. */
1812         iphlen = ip->ip_hl << 2;
1813         if (iphlen < sizeof(struct ip))         /* minimum header length */
1814                 return IPPROTO_DONE;
1815
1816         /* The full IP header must reside completely in the one mbuf. */
1817         if (m->m_len < hoff + iphlen)
1818                 return IPPROTO_DONE;
1819
1820         iplen = ntohs(ip->ip_len);
1821
1822         /*
1823          * Check that the amount of data in the buffers is as
1824          * at least much as the IP header would have us expect.
1825          */
1826         if (m->m_pkthdr.len < hoff + iplen)
1827                 return IPPROTO_DONE;
1828
1829         /*
1830          * Ignore IP fragments.
1831          */
1832         if (ntohs(ip->ip_off) & (IP_OFFMASK | IP_MF))
1833                 return IPPROTO_DONE;
1834
1835         /*
1836          * The TCP/IP or UDP/IP header must be entirely contained within
1837          * the first fragment of a packet.
1838          */
1839         switch (ip->ip_p) {
1840         case IPPROTO_TCP:
1841                 if (iplen < iphlen + sizeof(struct tcphdr))
1842                         return IPPROTO_DONE;
1843                 if (m->m_len < hoff + iphlen + sizeof(struct tcphdr))
1844                         return IPPROTO_DONE;
1845                 th = (const struct tcphdr *)((const uint8_t *)ip + iphlen);
1846                 thoff = th->th_off << 2;
1847                 if (thoff < sizeof(struct tcphdr) || thoff + iphlen > iplen)
1848                         return IPPROTO_DONE;
1849                 if (m->m_len < hoff + iphlen + thoff)
1850                         return IPPROTO_DONE;
1851                 break;
1852         case IPPROTO_UDP:
1853                 if (iplen < iphlen + sizeof(struct udphdr))
1854                         return IPPROTO_DONE;
1855                 if (m->m_len < hoff + iphlen + sizeof(struct udphdr))
1856                         return IPPROTO_DONE;
1857                 break;
1858         default:
1859                 if (iplen < iphlen)
1860                         return IPPROTO_DONE;
1861                 break;
1862         }
1863         return ip->ip_p;
1864 }
1865
1866 static void
1867 hn_dma_map_paddr(void *arg, bus_dma_segment_t *segs, int nseg, int error)
1868 {
1869         bus_addr_t *paddr = arg;
1870
1871         if (error)
1872                 return;
1873
1874         KASSERT(nseg == 1, ("too many segments %d!", nseg));
1875         *paddr = segs->ds_addr;
1876 }
1877
1878 static int
1879 hn_create_tx_ring(struct hn_softc *sc)
1880 {
1881         bus_dma_tag_t parent_dtag;
1882         int error, i;
1883
1884         sc->hn_txdesc_cnt = HN_TX_DESC_CNT;
1885         sc->hn_txdesc = malloc(sizeof(struct hn_txdesc) * sc->hn_txdesc_cnt,
1886             M_NETVSC, M_WAITOK | M_ZERO);
1887         SLIST_INIT(&sc->hn_txlist);
1888         mtx_init(&sc->hn_txlist_spin, "hn txlist", NULL, MTX_SPIN);
1889
1890         parent_dtag = bus_get_dma_tag(sc->hn_dev);
1891
1892         /* DMA tag for RNDIS messages. */
1893         error = bus_dma_tag_create(parent_dtag, /* parent */
1894             HN_RNDIS_MSG_ALIGN,         /* alignment */
1895             HN_RNDIS_MSG_BOUNDARY,      /* boundary */
1896             BUS_SPACE_MAXADDR,          /* lowaddr */
1897             BUS_SPACE_MAXADDR,          /* highaddr */
1898             NULL, NULL,                 /* filter, filterarg */
1899             HN_RNDIS_MSG_LEN,           /* maxsize */
1900             1,                          /* nsegments */
1901             HN_RNDIS_MSG_LEN,           /* maxsegsize */
1902             0,                          /* flags */
1903             NULL,                       /* lockfunc */
1904             NULL,                       /* lockfuncarg */
1905             &sc->hn_tx_rndis_dtag);
1906         if (error) {
1907                 device_printf(sc->hn_dev, "failed to create rndis dmatag\n");
1908                 return error;
1909         }
1910
1911         /* DMA tag for data. */
1912         error = bus_dma_tag_create(parent_dtag, /* parent */
1913             1,                          /* alignment */
1914             HN_TX_DATA_BOUNDARY,        /* boundary */
1915             BUS_SPACE_MAXADDR,          /* lowaddr */
1916             BUS_SPACE_MAXADDR,          /* highaddr */
1917             NULL, NULL,                 /* filter, filterarg */
1918             HN_TX_DATA_MAXSIZE,         /* maxsize */
1919             HN_TX_DATA_SEGCNT_MAX,      /* nsegments */
1920             HN_TX_DATA_SEGSIZE,         /* maxsegsize */
1921             0,                          /* flags */
1922             NULL,                       /* lockfunc */
1923             NULL,                       /* lockfuncarg */
1924             &sc->hn_tx_data_dtag);
1925         if (error) {
1926                 device_printf(sc->hn_dev, "failed to create data dmatag\n");
1927                 return error;
1928         }
1929
1930         for (i = 0; i < sc->hn_txdesc_cnt; ++i) {
1931                 struct hn_txdesc *txd = &sc->hn_txdesc[i];
1932
1933                 txd->sc = sc;
1934
1935                 /*
1936                  * Allocate and load RNDIS messages.
1937                  */
1938                 error = bus_dmamem_alloc(sc->hn_tx_rndis_dtag,
1939                     (void **)&txd->rndis_msg,
1940                     BUS_DMA_WAITOK | BUS_DMA_COHERENT,
1941                     &txd->rndis_msg_dmap);
1942                 if (error) {
1943                         device_printf(sc->hn_dev,
1944                             "failed to allocate rndis_msg, %d\n", i);
1945                         return error;
1946                 }
1947
1948                 error = bus_dmamap_load(sc->hn_tx_rndis_dtag,
1949                     txd->rndis_msg_dmap,
1950                     txd->rndis_msg, HN_RNDIS_MSG_LEN,
1951                     hn_dma_map_paddr, &txd->rndis_msg_paddr,
1952                     BUS_DMA_NOWAIT);
1953                 if (error) {
1954                         device_printf(sc->hn_dev,
1955                             "failed to load rndis_msg, %d\n", i);
1956                         bus_dmamem_free(sc->hn_tx_rndis_dtag,
1957                             txd->rndis_msg, txd->rndis_msg_dmap);
1958                         return error;
1959                 }
1960
1961                 /* DMA map for TX data. */
1962                 error = bus_dmamap_create(sc->hn_tx_data_dtag, 0,
1963                     &txd->data_dmap);
1964                 if (error) {
1965                         device_printf(sc->hn_dev,
1966                             "failed to allocate tx data dmamap\n");
1967                         bus_dmamap_unload(sc->hn_tx_rndis_dtag,
1968                             txd->rndis_msg_dmap);
1969                         bus_dmamem_free(sc->hn_tx_rndis_dtag,
1970                             txd->rndis_msg, txd->rndis_msg_dmap);
1971                         return error;
1972                 }
1973
1974                 /* All set, put it to list */
1975                 txd->flags |= HN_TXD_FLAG_ONLIST;
1976                 SLIST_INSERT_HEAD(&sc->hn_txlist, txd, link);
1977         }
1978         sc->hn_txdesc_avail = sc->hn_txdesc_cnt;
1979
1980         return 0;
1981 }
1982
1983 static void
1984 hn_destroy_tx_ring(struct hn_softc *sc)
1985 {
1986         struct hn_txdesc *txd;
1987
1988         while ((txd = SLIST_FIRST(&sc->hn_txlist)) != NULL) {
1989                 KASSERT(txd->m == NULL, ("still has mbuf installed"));
1990                 KASSERT((txd->flags & HN_TXD_FLAG_DMAMAP) == 0,
1991                     ("still dma mapped"));
1992                 SLIST_REMOVE_HEAD(&sc->hn_txlist, link);
1993
1994                 bus_dmamap_unload(sc->hn_tx_rndis_dtag,
1995                     txd->rndis_msg_dmap);
1996                 bus_dmamem_free(sc->hn_tx_rndis_dtag,
1997                     txd->rndis_msg, txd->rndis_msg_dmap);
1998
1999                 bus_dmamap_destroy(sc->hn_tx_data_dtag, txd->data_dmap);
2000         }
2001
2002         if (sc->hn_tx_data_dtag != NULL)
2003                 bus_dma_tag_destroy(sc->hn_tx_data_dtag);
2004         if (sc->hn_tx_rndis_dtag != NULL)
2005                 bus_dma_tag_destroy(sc->hn_tx_rndis_dtag);
2006         free(sc->hn_txdesc, M_NETVSC);
2007         mtx_destroy(&sc->hn_txlist_spin);
2008 }
2009
2010 static void
2011 hn_start_taskfunc(void *xsc, int pending __unused)
2012 {
2013         struct hn_softc *sc = xsc;
2014
2015         NV_LOCK(sc);
2016         hn_start_locked(sc->hn_ifp, 0);
2017         NV_UNLOCK(sc);
2018 }
2019
2020 static void
2021 hn_txeof_taskfunc(void *xsc, int pending __unused)
2022 {
2023         struct hn_softc *sc = xsc;
2024         struct ifnet *ifp = sc->hn_ifp;
2025
2026         NV_LOCK(sc);
2027         atomic_clear_int(&ifp->if_drv_flags, IFF_DRV_OACTIVE);
2028         hn_start_locked(ifp, 0);
2029         NV_UNLOCK(sc);
2030 }
2031
2032 static device_method_t netvsc_methods[] = {
2033         /* Device interface */
2034         DEVMETHOD(device_probe,         netvsc_probe),
2035         DEVMETHOD(device_attach,        netvsc_attach),
2036         DEVMETHOD(device_detach,        netvsc_detach),
2037         DEVMETHOD(device_shutdown,      netvsc_shutdown),
2038
2039         { 0, 0 }
2040 };
2041
2042 static driver_t netvsc_driver = {
2043         NETVSC_DEVNAME,
2044         netvsc_methods,
2045         sizeof(hn_softc_t)
2046 };
2047
2048 static devclass_t netvsc_devclass;
2049
2050 DRIVER_MODULE(hn, vmbus, netvsc_driver, netvsc_devclass, 0, 0);
2051 MODULE_VERSION(hn, 1);
2052 MODULE_DEPEND(hn, vmbus, 1, 1, 1);