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