if_vtnet - Default to link up, when VIRTIO_NET_F_STATUS is not negotiated.
[dragonfly.git] / sys / dev / virtual / virtio / net / if_vtnet.c
1 /*-
2  * Copyright (c) 2011, Bryan Venteicher <bryanv@FreeBSD.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice unmodified, this list of conditions, and the following
10  *    disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 /* Driver for VirtIO network devices. */
28
29 #include <sys/cdefs.h>
30
31 #include <sys/param.h>
32 #include <sys/systm.h>
33 #include <sys/kernel.h>
34 #include <sys/sockio.h>
35 #include <sys/mbuf.h>
36 #include <sys/malloc.h>
37 #include <sys/module.h>
38 #include <sys/socket.h>
39 #include <sys/sysctl.h>
40 #include <sys/taskqueue.h>
41 #include <sys/random.h>
42 #include <sys/sglist.h>
43 #include <sys/serialize.h>
44 #include <sys/bus.h>
45 #include <sys/rman.h>
46
47 #include <machine/limits.h>
48
49 #include <net/ethernet.h>
50 #include <net/if.h>
51 #include <net/if_arp.h>
52 #include <net/if_dl.h>
53 #include <net/if_types.h>
54 #include <net/if_media.h>
55 #include <net/vlan/if_vlan_var.h>
56 #include <net/vlan/if_vlan_ether.h>
57 #include <net/ifq_var.h>
58
59 #include <net/bpf.h>
60
61 #include <netinet/in_systm.h>
62 #include <netinet/in.h>
63 #include <netinet/ip.h>
64 #include <netinet/ip6.h>
65 #include <netinet/udp.h>
66 #include <netinet/tcp.h>
67
68 #include <dev/virtual/virtio/virtio/virtio.h>
69 #include <dev/virtual/virtio/virtio/virtqueue.h>
70 #include <dev/virtual/virtio/net/virtio_net.h>
71 #include <dev/virtual/virtio/net/if_vtnetvar.h>
72
73 #include "virtio_if.h"
74
75 MALLOC_DEFINE(M_VTNET, "VTNET_TX", "Outgoing VTNET TX frame header");
76
77 static int      vtnet_probe(device_t);
78 static int      vtnet_attach(device_t);
79 static int      vtnet_detach(device_t);
80 static int      vtnet_suspend(device_t);
81 static int      vtnet_resume(device_t);
82 static int      vtnet_shutdown(device_t);
83 static int      vtnet_config_change(device_t);
84
85 static void     vtnet_negotiate_features(struct vtnet_softc *);
86 static int      vtnet_alloc_virtqueues(struct vtnet_softc *);
87 static void     vtnet_get_hwaddr(struct vtnet_softc *);
88 static void     vtnet_set_hwaddr(struct vtnet_softc *);
89 static int      vtnet_is_link_up(struct vtnet_softc *);
90 static void     vtnet_update_link_status(struct vtnet_softc *);
91 #if 0
92 static void     vtnet_watchdog(struct vtnet_softc *);
93 #endif
94 static void     vtnet_config_change_task(void *, int);
95 static int      vtnet_setup_interface(struct vtnet_softc *);
96 static int      vtnet_change_mtu(struct vtnet_softc *, int);
97 static int      vtnet_ioctl(struct ifnet *, u_long, caddr_t, struct ucred *);
98
99 static int      vtnet_init_rx_vq(struct vtnet_softc *);
100 static void     vtnet_free_rx_mbufs(struct vtnet_softc *);
101 static void     vtnet_free_tx_mbufs(struct vtnet_softc *);
102 static void     vtnet_free_ctrl_vq(struct vtnet_softc *);
103
104 static struct mbuf * vtnet_alloc_rxbuf(struct vtnet_softc *, int,
105                     struct mbuf **);
106 static int      vtnet_replace_rxbuf(struct vtnet_softc *,
107                     struct mbuf *, int);
108 static int      vtnet_newbuf(struct vtnet_softc *);
109 static void     vtnet_discard_merged_rxbuf(struct vtnet_softc *, int);
110 static void     vtnet_discard_rxbuf(struct vtnet_softc *, struct mbuf *);
111 static int      vtnet_enqueue_rxbuf(struct vtnet_softc *, struct mbuf *);
112 static void     vtnet_vlan_tag_remove(struct mbuf *);
113 static int      vtnet_rx_csum(struct vtnet_softc *, struct mbuf *,
114                     struct virtio_net_hdr *);
115 static int      vtnet_rxeof_merged(struct vtnet_softc *, struct mbuf *, int);
116 static int      vtnet_rxeof(struct vtnet_softc *, int, int *);
117 static void     vtnet_rx_intr_task(void *);
118 static int      vtnet_rx_vq_intr(void *);
119
120 static void     vtnet_enqueue_txhdr(struct vtnet_softc *,
121                     struct vtnet_tx_header *);
122 static void     vtnet_txeof(struct vtnet_softc *);
123 static struct mbuf * vtnet_tx_offload(struct vtnet_softc *, struct mbuf *,
124                     struct virtio_net_hdr *);
125 static int      vtnet_enqueue_txbuf(struct vtnet_softc *, struct mbuf **,
126                     struct vtnet_tx_header *);
127 static int      vtnet_encap(struct vtnet_softc *, struct mbuf **);
128 static void     vtnet_start_locked(struct ifnet *, struct ifaltq_subque *);
129 static void     vtnet_start(struct ifnet *, struct ifaltq_subque *);
130 static void     vtnet_tick(void *);
131 static void     vtnet_tx_intr_task(void *);
132 static int      vtnet_tx_vq_intr(void *);
133
134 static void     vtnet_stop(struct vtnet_softc *);
135 static int      vtnet_virtio_reinit(struct vtnet_softc *);
136 static void     vtnet_init_locked(struct vtnet_softc *);
137 static void     vtnet_init(void *);
138
139 static void     vtnet_exec_ctrl_cmd(struct vtnet_softc *, void *,
140                     struct sglist *, int, int);
141
142 static int      vtnet_ctrl_mac_cmd(struct vtnet_softc *, uint8_t *);
143 static int      vtnet_ctrl_rx_cmd(struct vtnet_softc *, int, int);
144 static int      vtnet_set_promisc(struct vtnet_softc *, int);
145 static int      vtnet_set_allmulti(struct vtnet_softc *, int);
146 static void     vtnet_rx_filter(struct vtnet_softc *sc);
147 static void     vtnet_rx_filter_mac(struct vtnet_softc *);
148
149 static int      vtnet_exec_vlan_filter(struct vtnet_softc *, int, uint16_t);
150 static void     vtnet_rx_filter_vlan(struct vtnet_softc *);
151 static void     vtnet_update_vlan_filter(struct vtnet_softc *, int, uint16_t);
152 static void     vtnet_register_vlan(void *, struct ifnet *, uint16_t);
153 static void     vtnet_unregister_vlan(void *, struct ifnet *, uint16_t);
154
155 static int      vtnet_ifmedia_upd(struct ifnet *);
156 static void     vtnet_ifmedia_sts(struct ifnet *, struct ifmediareq *);
157
158 static void     vtnet_add_statistics(struct vtnet_softc *);
159
160 static int      vtnet_enable_rx_intr(struct vtnet_softc *);
161 static int      vtnet_enable_tx_intr(struct vtnet_softc *);
162 static void     vtnet_disable_rx_intr(struct vtnet_softc *);
163 static void     vtnet_disable_tx_intr(struct vtnet_softc *);
164
165 /* Tunables. */
166 static int vtnet_csum_disable = 0;
167 TUNABLE_INT("hw.vtnet.csum_disable", &vtnet_csum_disable);
168 static int vtnet_tso_disable = 1;
169 TUNABLE_INT("hw.vtnet.tso_disable", &vtnet_tso_disable);
170 static int vtnet_lro_disable = 0;
171 TUNABLE_INT("hw.vtnet.lro_disable", &vtnet_lro_disable);
172
173 /*
174  * Reducing the number of transmit completed interrupts can
175  * improve performance. To do so, the define below keeps the
176  * Tx vq interrupt disabled and adds calls to vtnet_txeof()
177  * in the start and watchdog paths. The price to pay for this
178  * is the m_free'ing of transmitted mbufs may be delayed until
179  * the watchdog fires.
180  */
181 #define VTNET_TX_INTR_MODERATION
182
183 static struct virtio_feature_desc vtnet_feature_desc[] = {
184         { VIRTIO_NET_F_CSUM,            "TxChecksum"    },
185         { VIRTIO_NET_F_GUEST_CSUM,      "RxChecksum"    },
186         { VIRTIO_NET_F_CTRL_GUEST_OFFLOADS, "DynOffload"        },
187         { VIRTIO_NET_F_MAC,             "MacAddress"    },
188         { VIRTIO_NET_F_GSO,             "TxAllGSO"      },
189         { VIRTIO_NET_F_GUEST_TSO4,      "RxTSOv4"       },
190         { VIRTIO_NET_F_GUEST_TSO6,      "RxTSOv6"       },
191         { VIRTIO_NET_F_GUEST_ECN,       "RxECN"         },
192         { VIRTIO_NET_F_GUEST_UFO,       "RxUFO"         },
193         { VIRTIO_NET_F_HOST_TSO4,       "TxTSOv4"       },
194         { VIRTIO_NET_F_HOST_TSO6,       "TxTSOv6"       },
195         { VIRTIO_NET_F_HOST_ECN,        "TxTSOECN"      },
196         { VIRTIO_NET_F_HOST_UFO,        "TxUFO"         },
197         { VIRTIO_NET_F_MRG_RXBUF,       "MrgRxBuf"      },
198         { VIRTIO_NET_F_STATUS,          "Status"        },
199         { VIRTIO_NET_F_CTRL_VQ,         "ControlVq"     },
200         { VIRTIO_NET_F_CTRL_RX,         "RxMode"        },
201         { VIRTIO_NET_F_CTRL_VLAN,       "VLanFilter"    },
202         { VIRTIO_NET_F_CTRL_RX_EXTRA,   "RxModeExtra"   },
203         { VIRTIO_NET_F_GUEST_ANNOUNCE,  "GuestAnnounce" },
204         { VIRTIO_NET_F_MQ,              "RFS"           },
205         { VIRTIO_NET_F_CTRL_MAC_ADDR,   "SetMacAddress" },
206         { 0, NULL }
207 };
208
209 static device_method_t vtnet_methods[] = {
210         /* Device methods. */
211         DEVMETHOD(device_probe,         vtnet_probe),
212         DEVMETHOD(device_attach,        vtnet_attach),
213         DEVMETHOD(device_detach,        vtnet_detach),
214         DEVMETHOD(device_suspend,       vtnet_suspend),
215         DEVMETHOD(device_resume,        vtnet_resume),
216         DEVMETHOD(device_shutdown,      vtnet_shutdown),
217
218         /* VirtIO methods. */
219         DEVMETHOD(virtio_config_change, vtnet_config_change),
220
221         DEVMETHOD_END
222 };
223
224 static driver_t vtnet_driver = {
225         "vtnet",
226         vtnet_methods,
227         sizeof(struct vtnet_softc)
228 };
229
230 static devclass_t vtnet_devclass;
231
232 DRIVER_MODULE(vtnet, virtio_pci, vtnet_driver, vtnet_devclass, NULL, NULL);
233 MODULE_VERSION(vtnet, 1);
234 MODULE_DEPEND(vtnet, virtio, 1, 1, 1);
235
236 static int
237 vtnet_probe(device_t dev)
238 {
239         if (virtio_get_device_type(dev) != VIRTIO_ID_NETWORK)
240                 return (ENXIO);
241
242         device_set_desc(dev, "VirtIO Networking Adapter");
243
244         return (BUS_PROBE_DEFAULT);
245 }
246
247 static int
248 vtnet_attach(device_t dev)
249 {
250         struct vtnet_softc *sc;
251         int error;
252
253         sc = device_get_softc(dev);
254         sc->vtnet_dev = dev;
255
256         lwkt_serialize_init(&sc->vtnet_slz);
257         callout_init(&sc->vtnet_tick_ch);
258
259         ifmedia_init(&sc->vtnet_media, IFM_IMASK, vtnet_ifmedia_upd,
260                      vtnet_ifmedia_sts);
261         ifmedia_add(&sc->vtnet_media, VTNET_MEDIATYPE, 0, NULL);
262         ifmedia_set(&sc->vtnet_media, VTNET_MEDIATYPE);
263
264         vtnet_add_statistics(sc);
265         SLIST_INIT(&sc->vtnet_txhdr_free);
266
267         /* Register our feature descriptions. */
268         virtio_set_feature_desc(dev, vtnet_feature_desc);
269         vtnet_negotiate_features(sc);
270
271         if (virtio_with_feature(dev, VIRTIO_RING_F_INDIRECT_DESC))
272                 sc->vtnet_flags |= VTNET_FLAG_INDIRECT;
273
274         if (virtio_with_feature(dev, VIRTIO_NET_F_MAC)) {
275                 /* This feature should always be negotiated. */
276                 sc->vtnet_flags |= VTNET_FLAG_MAC;
277         }
278
279         if (virtio_with_feature(dev, VIRTIO_NET_F_MRG_RXBUF)) {
280                 sc->vtnet_flags |= VTNET_FLAG_MRG_RXBUFS;
281                 sc->vtnet_hdr_size = sizeof(struct virtio_net_hdr_mrg_rxbuf);
282         } else {
283                 sc->vtnet_hdr_size = sizeof(struct virtio_net_hdr);
284         }
285
286         sc->vtnet_rx_mbuf_size = MCLBYTES;
287         sc->vtnet_rx_mbuf_count = VTNET_NEEDED_RX_MBUFS(sc);
288
289         if (virtio_with_feature(dev, VIRTIO_NET_F_CTRL_VQ)) {
290                 sc->vtnet_flags |= VTNET_FLAG_CTRL_VQ;
291
292                 if (virtio_with_feature(dev, VIRTIO_NET_F_CTRL_RX))
293                         sc->vtnet_flags |= VTNET_FLAG_CTRL_RX;
294                 if (virtio_with_feature(dev, VIRTIO_NET_F_CTRL_VLAN))
295                         sc->vtnet_flags |= VTNET_FLAG_VLAN_FILTER;
296                 if (virtio_with_feature(dev, VIRTIO_NET_F_CTRL_MAC_ADDR) &&
297                     virtio_with_feature(dev, VIRTIO_NET_F_CTRL_RX))
298                         sc->vtnet_flags |= VTNET_FLAG_CTRL_MAC;
299         }
300
301         /* Read (or generate) the MAC address for the adapter. */
302         vtnet_get_hwaddr(sc);
303
304         error = vtnet_alloc_virtqueues(sc);
305         if (error) {
306                 device_printf(dev, "cannot allocate virtqueues\n");
307                 goto fail;
308         }
309
310         error = vtnet_setup_interface(sc);
311         if (error) {
312                 device_printf(dev, "cannot setup interface\n");
313                 goto fail;
314         }
315
316         TASK_INIT(&sc->vtnet_cfgchg_task, 0, vtnet_config_change_task, sc);
317
318         error = virtio_setup_intr(dev, &sc->vtnet_slz);
319         if (error) {
320                 device_printf(dev, "cannot setup virtqueue interrupts\n");
321                 ether_ifdetach(sc->vtnet_ifp);
322                 goto fail;
323         }
324
325         /*
326          * Device defaults to promiscuous mode for backwards
327          * compatibility. Turn it off if possible.
328          */
329         if (sc->vtnet_flags & VTNET_FLAG_CTRL_RX) {
330                 lwkt_serialize_enter(&sc->vtnet_slz);
331                 if (vtnet_set_promisc(sc, 0) != 0) {
332                         sc->vtnet_ifp->if_flags |= IFF_PROMISC;
333                         device_printf(dev,
334                             "cannot disable promiscuous mode\n");
335                 }
336                 lwkt_serialize_exit(&sc->vtnet_slz);
337         } else
338                 sc->vtnet_ifp->if_flags |= IFF_PROMISC;
339
340 fail:
341         if (error)
342                 vtnet_detach(dev);
343
344         return (error);
345 }
346
347 static int
348 vtnet_detach(device_t dev)
349 {
350         struct vtnet_softc *sc;
351         struct ifnet *ifp;
352
353         sc = device_get_softc(dev);
354         ifp = sc->vtnet_ifp;
355
356         if (device_is_attached(dev)) {
357                 lwkt_serialize_enter(&sc->vtnet_slz);
358                 vtnet_stop(sc);
359                 lwkt_serialize_exit(&sc->vtnet_slz);
360
361                 callout_stop(&sc->vtnet_tick_ch);
362                 taskqueue_drain(taskqueue_swi, &sc->vtnet_cfgchg_task);
363
364                 ether_ifdetach(ifp);
365         }
366
367         if (sc->vtnet_vlan_attach != NULL) {
368                 EVENTHANDLER_DEREGISTER(vlan_config, sc->vtnet_vlan_attach);
369                 sc->vtnet_vlan_attach = NULL;
370         }
371         if (sc->vtnet_vlan_detach != NULL) {
372                 EVENTHANDLER_DEREGISTER(vlan_unconfig, sc->vtnet_vlan_detach);
373                 sc->vtnet_vlan_detach = NULL;
374         }
375
376         if (ifp) {
377                 if_free(ifp);
378                 sc->vtnet_ifp = NULL;
379         }
380
381         if (sc->vtnet_rx_vq != NULL)
382                 vtnet_free_rx_mbufs(sc);
383         if (sc->vtnet_tx_vq != NULL)
384                 vtnet_free_tx_mbufs(sc);
385         if (sc->vtnet_ctrl_vq != NULL)
386                 vtnet_free_ctrl_vq(sc);
387
388         if (sc->vtnet_txhdrarea != NULL) {
389                 contigfree(sc->vtnet_txhdrarea,
390                     sc->vtnet_txhdrcount * sizeof(struct vtnet_tx_header),
391                     M_VTNET);
392                 sc->vtnet_txhdrarea = NULL;
393         }
394         SLIST_INIT(&sc->vtnet_txhdr_free);
395         if (sc->vtnet_macfilter != NULL) {
396                 contigfree(sc->vtnet_macfilter,
397                     sizeof(struct vtnet_mac_filter), M_DEVBUF);
398                 sc->vtnet_macfilter = NULL;
399         }
400
401         ifmedia_removeall(&sc->vtnet_media);
402
403         return (0);
404 }
405
406 static int
407 vtnet_suspend(device_t dev)
408 {
409         struct vtnet_softc *sc;
410
411         sc = device_get_softc(dev);
412
413         lwkt_serialize_enter(&sc->vtnet_slz);
414         vtnet_stop(sc);
415         sc->vtnet_flags |= VTNET_FLAG_SUSPENDED;
416         lwkt_serialize_exit(&sc->vtnet_slz);
417
418         return (0);
419 }
420
421 static int
422 vtnet_resume(device_t dev)
423 {
424         struct vtnet_softc *sc;
425         struct ifnet *ifp;
426
427         sc = device_get_softc(dev);
428         ifp = sc->vtnet_ifp;
429
430         lwkt_serialize_enter(&sc->vtnet_slz);
431         if (ifp->if_flags & IFF_UP)
432                 vtnet_init_locked(sc);
433         sc->vtnet_flags &= ~VTNET_FLAG_SUSPENDED;
434         lwkt_serialize_exit(&sc->vtnet_slz);
435
436         return (0);
437 }
438
439 static int
440 vtnet_shutdown(device_t dev)
441 {
442
443         /*
444          * Suspend already does all of what we need to
445          * do here; we just never expect to be resumed.
446          */
447         return (vtnet_suspend(dev));
448 }
449
450 static int
451 vtnet_config_change(device_t dev)
452 {
453         struct vtnet_softc *sc;
454
455         sc = device_get_softc(dev);
456
457         taskqueue_enqueue(taskqueue_thread[mycpuid], &sc->vtnet_cfgchg_task);
458
459         return (1);
460 }
461
462 static void
463 vtnet_negotiate_features(struct vtnet_softc *sc)
464 {
465         device_t dev;
466         uint64_t mask, features;
467
468         dev = sc->vtnet_dev;
469         mask = 0;
470
471         if (vtnet_csum_disable)
472                 mask |= VIRTIO_NET_F_CSUM | VIRTIO_NET_F_GUEST_CSUM;
473
474         /*
475          * TSO and LRO are only available when their corresponding checksum
476          * offload feature is also negotiated.
477          */
478
479         if (vtnet_csum_disable || vtnet_tso_disable)
480                 mask |= VIRTIO_NET_F_HOST_TSO4 | VIRTIO_NET_F_HOST_TSO6 |
481                     VIRTIO_NET_F_HOST_ECN;
482
483         if (vtnet_csum_disable || vtnet_lro_disable)
484                 mask |= VTNET_LRO_FEATURES;
485
486         features = VTNET_FEATURES & ~mask;
487         features |= VIRTIO_F_NOTIFY_ON_EMPTY;
488         features |= VIRTIO_F_ANY_LAYOUT;
489         sc->vtnet_features = virtio_negotiate_features(dev, features);
490
491         if (virtio_with_feature(dev, VTNET_LRO_FEATURES) &&
492             virtio_with_feature(dev, VIRTIO_NET_F_MRG_RXBUF) == 0) {
493                 /*
494                  * LRO without mergeable buffers requires special care. This
495                  * is not ideal because every receive buffer must be large
496                  * enough to hold the maximum TCP packet, the Ethernet header,
497                  * and the header. This requires up to 34 descriptors with
498                  * MCLBYTES clusters. If we do not have indirect descriptors,
499                  * LRO is disabled since the virtqueue will not contain very
500                  * many receive buffers.
501                  */
502                 if (!virtio_with_feature(dev, VIRTIO_RING_F_INDIRECT_DESC)) {
503                         device_printf(dev,
504                             "LRO disabled due to both mergeable buffers and "
505                             "indirect descriptors not negotiated\n");
506
507                         features &= ~VTNET_LRO_FEATURES;
508                         sc->vtnet_features =
509                             virtio_negotiate_features(dev, features);
510                 } else
511                         sc->vtnet_flags |= VTNET_FLAG_LRO_NOMRG;
512         }
513 }
514
515 static int
516 vtnet_alloc_virtqueues(struct vtnet_softc *sc)
517 {
518         device_t dev;
519         struct vq_alloc_info vq_info[3];
520         int nvqs;
521
522         dev = sc->vtnet_dev;
523         nvqs = 2;
524
525         /*
526          * Indirect descriptors are not needed for the Rx
527          * virtqueue when mergeable buffers are negotiated.
528          * The header is placed inline with the data, not
529          * in a separate descriptor, and mbuf clusters are
530          * always physically contiguous.
531          */
532         if ((sc->vtnet_flags & VTNET_FLAG_MRG_RXBUFS) == 0) {
533                 sc->vtnet_rx_nsegs = (sc->vtnet_flags & VTNET_FLAG_LRO_NOMRG) ?
534                     VTNET_MAX_RX_SEGS : VTNET_MIN_RX_SEGS;
535         } else
536                 sc->vtnet_rx_nsegs = VTNET_MRG_RX_SEGS;
537
538         if (virtio_with_feature(dev, VIRTIO_NET_F_HOST_TSO4) ||
539             virtio_with_feature(dev, VIRTIO_NET_F_HOST_TSO6))
540                 sc->vtnet_tx_nsegs = VTNET_MAX_TX_SEGS;
541         else
542                 sc->vtnet_tx_nsegs = VTNET_MIN_TX_SEGS;
543
544         VQ_ALLOC_INFO_INIT(&vq_info[0], sc->vtnet_rx_nsegs,
545             vtnet_rx_vq_intr, sc, &sc->vtnet_rx_vq,
546             "%s receive", device_get_nameunit(dev));
547
548         VQ_ALLOC_INFO_INIT(&vq_info[1], sc->vtnet_tx_nsegs,
549             vtnet_tx_vq_intr, sc, &sc->vtnet_tx_vq,
550             "%s transmit", device_get_nameunit(dev));
551
552         if (sc->vtnet_flags & VTNET_FLAG_CTRL_VQ) {
553                 nvqs++;
554
555                 VQ_ALLOC_INFO_INIT(&vq_info[2], 0, NULL, NULL,
556                     &sc->vtnet_ctrl_vq, "%s control",
557                     device_get_nameunit(dev));
558         }
559
560         return (virtio_alloc_virtqueues(dev, 0, nvqs, vq_info));
561 }
562
563 static int
564 vtnet_setup_interface(struct vtnet_softc *sc)
565 {
566         device_t dev;
567         struct ifnet *ifp;
568         int i, tx_size;
569
570         dev = sc->vtnet_dev;
571
572         ifp = sc->vtnet_ifp = if_alloc(IFT_ETHER);
573         if (ifp == NULL) {
574                 device_printf(dev, "cannot allocate ifnet structure\n");
575                 return (ENOSPC);
576         }
577
578         ifp->if_softc = sc;
579         if_initname(ifp, device_get_name(dev), device_get_unit(dev));
580         ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
581         ifp->if_init = vtnet_init;
582         ifp->if_start = vtnet_start;
583         ifp->if_ioctl = vtnet_ioctl;
584
585         sc->vtnet_rx_size = virtqueue_size(sc->vtnet_rx_vq);
586         sc->vtnet_rx_process_limit = sc->vtnet_rx_size;
587
588         tx_size = virtqueue_size(sc->vtnet_tx_vq);
589         sc->vtnet_tx_size = tx_size;
590         /* Select size, such that we never run out of tx_header entries. */
591         if (sc->vtnet_flags & VTNET_FLAG_INDIRECT)
592                 sc->vtnet_txhdrcount = sc->vtnet_tx_size;
593         else
594                 sc->vtnet_txhdrcount = (sc->vtnet_tx_size / 2) + 1;
595         sc->vtnet_txhdrarea = contigmalloc(
596             sc->vtnet_txhdrcount * sizeof(struct vtnet_tx_header),
597             M_VTNET, M_WAITOK, 0, BUS_SPACE_MAXADDR, 4, 0);
598         if (sc->vtnet_txhdrarea == NULL) {
599                 device_printf(dev, "cannot contigmalloc the tx headers\n");
600                 return (ENOMEM);
601         }
602         for (i = 0; i < sc->vtnet_txhdrcount; i++)
603                 vtnet_enqueue_txhdr(sc, &sc->vtnet_txhdrarea[i]);
604         sc->vtnet_macfilter = contigmalloc(
605             sizeof(struct vtnet_mac_filter),
606             M_DEVBUF, M_WAITOK, 0, BUS_SPACE_MAXADDR, 4, 0);
607         if (sc->vtnet_macfilter == NULL) {
608                 device_printf(dev,
609                     "cannot contigmalloc the mac filter table\n");
610                 return (ENOMEM);
611         }
612         ifq_set_maxlen(&ifp->if_snd, tx_size - 1);
613         ifq_set_ready(&ifp->if_snd);
614
615         ether_ifattach(ifp, sc->vtnet_hwaddr, NULL);
616
617         /* Tell the upper layer(s) we support long frames. */
618         ifp->if_data.ifi_hdrlen = sizeof(struct ether_vlan_header);
619         ifp->if_capabilities |= IFCAP_JUMBO_MTU | IFCAP_VLAN_MTU;
620
621         if (virtio_with_feature(dev, VIRTIO_NET_F_CSUM)) {
622                 ifp->if_capabilities |= IFCAP_TXCSUM;
623
624                 if (virtio_with_feature(dev, VIRTIO_NET_F_HOST_TSO4))
625                         ifp->if_capabilities |= IFCAP_TSO4;
626                 if (virtio_with_feature(dev, VIRTIO_NET_F_HOST_TSO6))
627                         ifp->if_capabilities |= IFCAP_TSO6;
628                 if (ifp->if_capabilities & IFCAP_TSO)
629                         ifp->if_capabilities |= IFCAP_VLAN_HWTSO;
630
631                 if (virtio_with_feature(dev, VIRTIO_NET_F_HOST_ECN))
632                         sc->vtnet_flags |= VTNET_FLAG_TSO_ECN;
633         }
634
635         if (virtio_with_feature(dev, VIRTIO_NET_F_GUEST_CSUM)) {
636                 ifp->if_capabilities |= IFCAP_RXCSUM;
637
638                 if (virtio_with_feature(dev, VIRTIO_NET_F_GUEST_TSO4) ||
639                     virtio_with_feature(dev, VIRTIO_NET_F_GUEST_TSO6))
640                         ifp->if_capabilities |= IFCAP_LRO;
641         }
642
643         if (ifp->if_capabilities & IFCAP_HWCSUM) {
644                 /*
645                  * VirtIO does not support VLAN tagging, but we can fake
646                  * it by inserting and removing the 802.1Q header during
647                  * transmit and receive. We are then able to do checksum
648                  * offloading of VLAN frames.
649                  */
650                 ifp->if_capabilities |=
651                         IFCAP_VLAN_HWTAGGING | IFCAP_VLAN_HWCSUM;
652         }
653
654         ifp->if_capenable = ifp->if_capabilities;
655
656         /*
657          * Capabilities after here are not enabled by default.
658          */
659
660         if (sc->vtnet_flags & VTNET_FLAG_VLAN_FILTER) {
661                 ifp->if_capabilities |= IFCAP_VLAN_HWFILTER;
662
663                 sc->vtnet_vlan_attach = EVENTHANDLER_REGISTER(vlan_config,
664                     vtnet_register_vlan, sc, EVENTHANDLER_PRI_FIRST);
665                 sc->vtnet_vlan_detach = EVENTHANDLER_REGISTER(vlan_unconfig,
666                     vtnet_unregister_vlan, sc, EVENTHANDLER_PRI_FIRST);
667         }
668
669         return (0);
670 }
671
672 static void
673 vtnet_set_hwaddr(struct vtnet_softc *sc)
674 {
675         device_t dev;
676
677         dev = sc->vtnet_dev;
678
679         if ((sc->vtnet_flags & VTNET_FLAG_CTRL_MAC) &&
680             (sc->vtnet_flags & VTNET_FLAG_CTRL_RX)) {
681                 if (vtnet_ctrl_mac_cmd(sc, sc->vtnet_hwaddr) != 0)
682                         device_printf(dev, "unable to set MAC address\n");
683         } else if (sc->vtnet_flags & VTNET_FLAG_MAC) {
684                 virtio_write_device_config(dev,
685                     offsetof(struct virtio_net_config, mac),
686                     sc->vtnet_hwaddr, ETHER_ADDR_LEN);
687         }
688 }
689
690 static void
691 vtnet_get_hwaddr(struct vtnet_softc *sc)
692 {
693         device_t dev;
694
695         dev = sc->vtnet_dev;
696
697         if ((sc->vtnet_flags & VTNET_FLAG_MAC) == 0) {
698                 /*
699                  * Generate a random locally administered unicast address.
700                  *
701                  * It would be nice to generate the same MAC address across
702                  * reboots, but it seems all the hosts currently available
703                  * support the MAC feature, so this isn't too important.
704                  */
705                 sc->vtnet_hwaddr[0] = 0xB2;
706                 karc4rand(&sc->vtnet_hwaddr[1], ETHER_ADDR_LEN - 1);
707                 vtnet_set_hwaddr(sc);
708                 return;
709         }
710
711         virtio_read_device_config(dev,
712             offsetof(struct virtio_net_config, mac),
713             sc->vtnet_hwaddr, ETHER_ADDR_LEN);
714 }
715
716 static int
717 vtnet_is_link_up(struct vtnet_softc *sc)
718 {
719         device_t dev;
720         struct ifnet *ifp;
721         uint16_t status;
722
723         dev = sc->vtnet_dev;
724         ifp = sc->vtnet_ifp;
725
726         ASSERT_SERIALIZED(&sc->vtnet_slz);
727
728         if (virtio_with_feature(dev, VIRTIO_NET_F_STATUS)) {
729                 status = virtio_read_dev_config_2(dev,
730                                 offsetof(struct virtio_net_config, status));
731         } else {
732                 status = VIRTIO_NET_S_LINK_UP;
733         }
734
735         return ((status & VIRTIO_NET_S_LINK_UP) != 0);
736 }
737
738 static void
739 vtnet_update_link_status(struct vtnet_softc *sc)
740 {
741         device_t dev;
742         struct ifnet *ifp;
743         struct ifaltq_subque *ifsq;
744         int link;
745
746         dev = sc->vtnet_dev;
747         ifp = sc->vtnet_ifp;
748         ifsq = ifq_get_subq_default(&ifp->if_snd);
749
750         link = vtnet_is_link_up(sc);
751
752         if (link && ((sc->vtnet_flags & VTNET_FLAG_LINK) == 0)) {
753                 sc->vtnet_flags |= VTNET_FLAG_LINK;
754                 if (bootverbose)
755                         device_printf(dev, "Link is up\n");
756                 ifp->if_link_state = LINK_STATE_UP;
757                 if_link_state_change(ifp);
758                 if (!ifsq_is_empty(ifsq))
759                         vtnet_start_locked(ifp, ifsq);
760         } else if (!link && (sc->vtnet_flags & VTNET_FLAG_LINK)) {
761                 sc->vtnet_flags &= ~VTNET_FLAG_LINK;
762                 if (bootverbose)
763                         device_printf(dev, "Link is down\n");
764
765                 ifp->if_link_state = LINK_STATE_DOWN;
766                 if_link_state_change(ifp);
767         }
768 }
769
770 #if 0
771 static void
772 vtnet_watchdog(struct vtnet_softc *sc)
773 {
774         struct ifnet *ifp;
775
776         ifp = sc->vtnet_ifp;
777
778 #ifdef VTNET_TX_INTR_MODERATION
779         vtnet_txeof(sc);
780 #endif
781
782         if (sc->vtnet_watchdog_timer == 0 || --sc->vtnet_watchdog_timer)
783                 return;
784
785         if_printf(ifp, "watchdog timeout -- resetting\n");
786 #ifdef VTNET_DEBUG
787         virtqueue_dump(sc->vtnet_tx_vq);
788 #endif
789         ifp->if_oerrors++;
790         ifp->if_flags &= ~IFF_RUNNING;
791         vtnet_init_locked(sc);
792 }
793 #endif
794
795 static void
796 vtnet_config_change_task(void *arg, int pending)
797 {
798         struct vtnet_softc *sc;
799
800         sc = arg;
801
802         lwkt_serialize_enter(&sc->vtnet_slz);
803         vtnet_update_link_status(sc);
804         lwkt_serialize_exit(&sc->vtnet_slz);
805 }
806
807 static int
808 vtnet_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data,struct ucred *cr)
809 {
810         struct vtnet_softc *sc;
811         struct ifreq *ifr;
812         int reinit, mask, error;
813
814         sc = ifp->if_softc;
815         ifr = (struct ifreq *) data;
816         reinit = 0;
817         error = 0;
818
819         switch (cmd) {
820         case SIOCSIFMTU:
821                 if (ifr->ifr_mtu < ETHERMIN || ifr->ifr_mtu > VTNET_MAX_MTU)
822                         error = EINVAL;
823                 else if (ifp->if_mtu != ifr->ifr_mtu) {
824                         lwkt_serialize_enter(&sc->vtnet_slz);
825                         error = vtnet_change_mtu(sc, ifr->ifr_mtu);
826                         lwkt_serialize_exit(&sc->vtnet_slz);
827                 }
828                 break;
829
830         case SIOCSIFFLAGS:
831                 lwkt_serialize_enter(&sc->vtnet_slz);
832                 if ((ifp->if_flags & IFF_UP) == 0) {
833                         if (ifp->if_flags & IFF_RUNNING)
834                                 vtnet_stop(sc);
835                 } else if (ifp->if_flags & IFF_RUNNING) {
836                         if ((ifp->if_flags ^ sc->vtnet_if_flags) &
837                             (IFF_PROMISC | IFF_ALLMULTI)) {
838                                 if (sc->vtnet_flags & VTNET_FLAG_CTRL_RX)
839                                         vtnet_rx_filter(sc);
840                                 else
841                                         error = ENOTSUP;
842                         }
843                 } else
844                         vtnet_init_locked(sc);
845
846                 if (error == 0)
847                         sc->vtnet_if_flags = ifp->if_flags;
848                 lwkt_serialize_exit(&sc->vtnet_slz);
849                 break;
850
851         case SIOCADDMULTI:
852         case SIOCDELMULTI:
853                 lwkt_serialize_enter(&sc->vtnet_slz);
854                 if ((sc->vtnet_flags & VTNET_FLAG_CTRL_RX) &&
855                     (ifp->if_flags & IFF_RUNNING))
856                         vtnet_rx_filter_mac(sc);
857                 lwkt_serialize_exit(&sc->vtnet_slz);
858                 break;
859
860         case SIOCSIFMEDIA:
861         case SIOCGIFMEDIA:
862                 error = ifmedia_ioctl(ifp, ifr, &sc->vtnet_media, cmd);
863                 break;
864
865         case SIOCSIFCAP:
866                 mask = ifr->ifr_reqcap ^ ifp->if_capenable;
867
868                 lwkt_serialize_enter(&sc->vtnet_slz);
869
870                 if (mask & IFCAP_TXCSUM) {
871                         ifp->if_capenable ^= IFCAP_TXCSUM;
872                         if (ifp->if_capenable & IFCAP_TXCSUM)
873                                 ifp->if_hwassist |= VTNET_CSUM_OFFLOAD;
874                         else
875                                 ifp->if_hwassist &= ~VTNET_CSUM_OFFLOAD;
876                 }
877
878                 if (mask & IFCAP_TSO4) {
879                         ifp->if_capenable ^= IFCAP_TSO4;
880                         if (ifp->if_capenable & IFCAP_TSO4)
881                                 ifp->if_hwassist |= CSUM_TSO;
882                         else
883                                 ifp->if_hwassist &= ~CSUM_TSO;
884                 }
885
886                 if (mask & IFCAP_RXCSUM) {
887                         ifp->if_capenable ^= IFCAP_RXCSUM;
888                         reinit = 1;
889                 }
890
891                 if (mask & IFCAP_LRO) {
892                         ifp->if_capenable ^= IFCAP_LRO;
893                         reinit = 1;
894                 }
895
896                 if (mask & IFCAP_VLAN_HWFILTER) {
897                         ifp->if_capenable ^= IFCAP_VLAN_HWFILTER;
898                         reinit = 1;
899                 }
900
901                 if (mask & IFCAP_VLAN_HWTSO)
902                         ifp->if_capenable ^= IFCAP_VLAN_HWTSO;
903
904                 if (mask & IFCAP_VLAN_HWTAGGING)
905                         ifp->if_capenable ^= IFCAP_VLAN_HWTAGGING;
906
907                 if (reinit && (ifp->if_flags & IFF_RUNNING)) {
908                         ifp->if_flags &= ~IFF_RUNNING;
909                         vtnet_init_locked(sc);
910                 }
911                 //VLAN_CAPABILITIES(ifp);
912
913                 lwkt_serialize_exit(&sc->vtnet_slz);
914                 break;
915
916         default:
917                 error = ether_ioctl(ifp, cmd, data);
918                 break;
919         }
920
921         return (error);
922 }
923
924 static int
925 vtnet_change_mtu(struct vtnet_softc *sc, int new_mtu)
926 {
927         struct ifnet *ifp;
928         int new_frame_size, clsize;
929
930         ifp = sc->vtnet_ifp;
931
932         if ((sc->vtnet_flags & VTNET_FLAG_MRG_RXBUFS) == 0) {
933                 new_frame_size = sizeof(struct vtnet_rx_header) +
934                     sizeof(struct ether_vlan_header) + new_mtu;
935
936                 if (new_frame_size > MJUM9BYTES)
937                         return (EINVAL);
938
939                 if (new_frame_size <= MCLBYTES)
940                         clsize = MCLBYTES;
941                 else
942                         clsize = MJUM9BYTES;
943         } else {
944                 new_frame_size = sizeof(struct virtio_net_hdr_mrg_rxbuf) +
945                     sizeof(struct ether_vlan_header) + new_mtu;
946
947                 if (new_frame_size <= MCLBYTES)
948                         clsize = MCLBYTES;
949                 else
950                         clsize = MJUMPAGESIZE;
951         }
952
953         sc->vtnet_rx_mbuf_size = clsize;
954         sc->vtnet_rx_mbuf_count = VTNET_NEEDED_RX_MBUFS(sc);
955         KASSERT(sc->vtnet_rx_mbuf_count < VTNET_MAX_RX_SEGS,
956             ("too many rx mbufs: %d", sc->vtnet_rx_mbuf_count));
957
958         ifp->if_mtu = new_mtu;
959
960         if (ifp->if_flags & IFF_RUNNING) {
961                 ifp->if_flags &= ~IFF_RUNNING;
962                 vtnet_init_locked(sc);
963         }
964
965         return (0);
966 }
967
968 static int
969 vtnet_init_rx_vq(struct vtnet_softc *sc)
970 {
971         struct virtqueue *vq;
972         int nbufs, error;
973
974         vq = sc->vtnet_rx_vq;
975         nbufs = 0;
976         error = ENOSPC;
977
978         while (!virtqueue_full(vq)) {
979                 if ((error = vtnet_newbuf(sc)) != 0)
980                         break;
981                 nbufs++;
982         }
983
984         if (nbufs > 0) {
985                 virtqueue_notify(vq, &sc->vtnet_slz);
986
987                 /*
988                  * EMSGSIZE signifies the virtqueue did not have enough
989                  * entries available to hold the last mbuf. This is not
990                  * an error. We should not get ENOSPC since we check if
991                  * the virtqueue is full before attempting to add a
992                  * buffer.
993                  */
994                 if (error == EMSGSIZE)
995                         error = 0;
996         }
997
998         return (error);
999 }
1000
1001 static void
1002 vtnet_free_rx_mbufs(struct vtnet_softc *sc)
1003 {
1004         struct virtqueue *vq;
1005         struct mbuf *m;
1006         int last;
1007
1008         vq = sc->vtnet_rx_vq;
1009         last = 0;
1010
1011         while ((m = virtqueue_drain(vq, &last)) != NULL)
1012                 m_freem(m);
1013
1014         KASSERT(virtqueue_empty(vq), ("mbufs remaining in Rx Vq"));
1015 }
1016
1017 static void
1018 vtnet_free_tx_mbufs(struct vtnet_softc *sc)
1019 {
1020         struct virtqueue *vq;
1021         struct vtnet_tx_header *txhdr;
1022         int last;
1023
1024         vq = sc->vtnet_tx_vq;
1025         last = 0;
1026
1027         while ((txhdr = virtqueue_drain(vq, &last)) != NULL) {
1028                 m_freem(txhdr->vth_mbuf);
1029                 vtnet_enqueue_txhdr(sc, txhdr);
1030         }
1031
1032         KASSERT(virtqueue_empty(vq), ("mbufs remaining in Tx Vq"));
1033 }
1034
1035 static void
1036 vtnet_free_ctrl_vq(struct vtnet_softc *sc)
1037 {
1038         /*
1039          * The control virtqueue is only polled, therefore
1040          * it should already be empty.
1041          */
1042         KASSERT(virtqueue_empty(sc->vtnet_ctrl_vq),
1043                 ("Ctrl Vq not empty"));
1044 }
1045
1046 static struct mbuf *
1047 vtnet_alloc_rxbuf(struct vtnet_softc *sc, int nbufs, struct mbuf **m_tailp)
1048 {
1049         struct mbuf *m_head, *m_tail, *m;
1050         int i, clsize;
1051
1052         clsize = sc->vtnet_rx_mbuf_size;
1053
1054         /*use getcl instead of getjcl. see  if_mxge.c comment line 2398*/
1055         //m_head = m_getjcl(M_DONTWAIT, MT_DATA, M_PKTHDR, clsize);
1056         m_head = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR );
1057         if (m_head == NULL)
1058                 goto fail;
1059
1060         m_head->m_len = clsize;
1061         m_tail = m_head;
1062
1063         if (nbufs > 1) {
1064                 KASSERT(sc->vtnet_flags & VTNET_FLAG_LRO_NOMRG,
1065                         ("chained Rx mbuf requested without LRO_NOMRG"));
1066
1067                 for (i = 0; i < nbufs - 1; i++) {
1068                         //m = m_getjcl(M_DONTWAIT, MT_DATA, 0, clsize);
1069                         m = m_getcl(M_NOWAIT, MT_DATA, 0);
1070                         if (m == NULL)
1071                                 goto fail;
1072
1073                         m->m_len = clsize;
1074                         m_tail->m_next = m;
1075                         m_tail = m;
1076                 }
1077         }
1078
1079         if (m_tailp != NULL)
1080                 *m_tailp = m_tail;
1081
1082         return (m_head);
1083
1084 fail:
1085         sc->vtnet_stats.mbuf_alloc_failed++;
1086         m_freem(m_head);
1087
1088         return (NULL);
1089 }
1090
1091 static int
1092 vtnet_replace_rxbuf(struct vtnet_softc *sc, struct mbuf *m0, int len0)
1093 {
1094         struct mbuf *m, *m_prev;
1095         struct mbuf *m_new, *m_tail;
1096         int len, clsize, nreplace, error;
1097
1098         m = m0;
1099         m_prev = NULL;
1100         len = len0;
1101
1102         m_tail = NULL;
1103         clsize = sc->vtnet_rx_mbuf_size;
1104         nreplace = 0;
1105
1106         if (m->m_next != NULL)
1107                 KASSERT(sc->vtnet_flags & VTNET_FLAG_LRO_NOMRG,
1108                     ("chained Rx mbuf without LRO_NOMRG"));
1109
1110         /*
1111          * Since LRO_NOMRG mbuf chains are so large, we want to avoid
1112          * allocating an entire chain for each received frame. When
1113          * the received frame's length is less than that of the chain,
1114          * the unused mbufs are reassigned to the new chain.
1115          */
1116         while (len > 0) {
1117                 /*
1118                  * Something is seriously wrong if we received
1119                  * a frame larger than the mbuf chain. Drop it.
1120                  */
1121                 if (m == NULL) {
1122                         sc->vtnet_stats.rx_frame_too_large++;
1123                         return (EMSGSIZE);
1124                 }
1125
1126                 KASSERT(m->m_len == clsize,
1127                     ("mbuf length not expected cluster size: %d",
1128                     m->m_len));
1129
1130                 m->m_len = MIN(m->m_len, len);
1131                 len -= m->m_len;
1132
1133                 m_prev = m;
1134                 m = m->m_next;
1135                 nreplace++;
1136         }
1137
1138         KASSERT(m_prev != NULL, ("m_prev == NULL"));
1139         KASSERT(nreplace <= sc->vtnet_rx_mbuf_count,
1140                 ("too many replacement mbufs: %d/%d", nreplace,
1141                 sc->vtnet_rx_mbuf_count));
1142
1143         m_new = vtnet_alloc_rxbuf(sc, nreplace, &m_tail);
1144         if (m_new == NULL) {
1145                 m_prev->m_len = clsize;
1146                 return (ENOBUFS);
1147         }
1148
1149         /*
1150          * Move unused mbufs, if any, from the original chain
1151          * onto the end of the new chain.
1152          */
1153         if (m_prev->m_next != NULL) {
1154                 m_tail->m_next = m_prev->m_next;
1155                 m_prev->m_next = NULL;
1156         }
1157
1158         error = vtnet_enqueue_rxbuf(sc, m_new);
1159         if (error) {
1160                 /*
1161                  * BAD! We could not enqueue the replacement mbuf chain. We
1162                  * must restore the m0 chain to the original state if it was
1163                  * modified so we can subsequently discard it.
1164                  *
1165                  * NOTE: The replacement is suppose to be an identical copy
1166                  * to the one just dequeued so this is an unexpected error.
1167                  */
1168                 sc->vtnet_stats.rx_enq_replacement_failed++;
1169
1170                 if (m_tail->m_next != NULL) {
1171                         m_prev->m_next = m_tail->m_next;
1172                         m_tail->m_next = NULL;
1173                 }
1174
1175                 m_prev->m_len = clsize;
1176                 m_freem(m_new);
1177         }
1178
1179         return (error);
1180 }
1181
1182 static int
1183 vtnet_newbuf(struct vtnet_softc *sc)
1184 {
1185         struct mbuf *m;
1186         int error;
1187
1188         m = vtnet_alloc_rxbuf(sc, sc->vtnet_rx_mbuf_count, NULL);
1189         if (m == NULL)
1190                 return (ENOBUFS);
1191
1192         error = vtnet_enqueue_rxbuf(sc, m);
1193         if (error)
1194                 m_freem(m);
1195
1196         return (error);
1197 }
1198
1199 static void
1200 vtnet_discard_merged_rxbuf(struct vtnet_softc *sc, int nbufs)
1201 {
1202         struct virtqueue *vq;
1203         struct mbuf *m;
1204
1205         vq = sc->vtnet_rx_vq;
1206
1207         while (--nbufs > 0) {
1208                 if ((m = virtqueue_dequeue(vq, NULL)) == NULL)
1209                         break;
1210                 vtnet_discard_rxbuf(sc, m);
1211         }
1212 }
1213
1214 static void
1215 vtnet_discard_rxbuf(struct vtnet_softc *sc, struct mbuf *m)
1216 {
1217         int error;
1218
1219         /*
1220          * Requeue the discarded mbuf. This should always be
1221          * successful since it was just dequeued.
1222          */
1223         error = vtnet_enqueue_rxbuf(sc, m);
1224         KASSERT(error == 0, ("cannot requeue discarded mbuf"));
1225 }
1226
1227 static int
1228 vtnet_enqueue_rxbuf(struct vtnet_softc *sc, struct mbuf *m)
1229 {
1230         struct sglist sg;
1231         struct sglist_seg segs[VTNET_MAX_RX_SEGS];
1232         struct vtnet_rx_header *rxhdr;
1233         struct virtio_net_hdr *hdr;
1234         uint8_t *mdata;
1235         int offset, error;
1236
1237         ASSERT_SERIALIZED(&sc->vtnet_slz);
1238         if ((sc->vtnet_flags & VTNET_FLAG_LRO_NOMRG) == 0)
1239                 KASSERT(m->m_next == NULL, ("chained Rx mbuf"));
1240
1241         sglist_init(&sg, sc->vtnet_rx_nsegs, segs);
1242
1243         mdata = mtod(m, uint8_t *);
1244         offset = 0;
1245
1246         if ((sc->vtnet_flags & VTNET_FLAG_MRG_RXBUFS) == 0) {
1247                 rxhdr = (struct vtnet_rx_header *) mdata;
1248                 hdr = &rxhdr->vrh_hdr;
1249                 offset += sizeof(struct vtnet_rx_header);
1250
1251                 error = sglist_append(&sg, hdr, sc->vtnet_hdr_size);
1252                 KASSERT(error == 0, ("cannot add header to sglist"));
1253         }
1254
1255         error = sglist_append(&sg, mdata + offset, m->m_len - offset);
1256         if (error)
1257                 return (error);
1258
1259         if (m->m_next != NULL) {
1260                 error = sglist_append_mbuf(&sg, m->m_next);
1261                 if (error)
1262                         return (error);
1263         }
1264
1265         return (virtqueue_enqueue(sc->vtnet_rx_vq, m, &sg, 0, sg.sg_nseg));
1266 }
1267
1268 static void
1269 vtnet_vlan_tag_remove(struct mbuf *m)
1270 {
1271         struct ether_vlan_header *evl;
1272
1273         evl = mtod(m, struct ether_vlan_header *);
1274
1275         m->m_pkthdr.ether_vlantag = ntohs(evl->evl_tag);
1276         m->m_flags |= M_VLANTAG;
1277
1278         /* Strip the 802.1Q header. */
1279         bcopy((char *) evl, (char *) evl + ETHER_VLAN_ENCAP_LEN,
1280             ETHER_HDR_LEN - ETHER_TYPE_LEN);
1281         m_adj(m, ETHER_VLAN_ENCAP_LEN);
1282 }
1283
1284 /*
1285  * Alternative method of doing receive checksum offloading. Rather
1286  * than parsing the received frame down to the IP header, use the
1287  * csum_offset to determine which CSUM_* flags are appropriate. We
1288  * can get by with doing this only because the checksum offsets are
1289  * unique for the things we care about.
1290  */
1291 static int
1292 vtnet_rx_csum(struct vtnet_softc *sc, struct mbuf *m,
1293     struct virtio_net_hdr *hdr)
1294 {
1295         struct ether_header *eh;
1296         struct ether_vlan_header *evh;
1297         struct udphdr *udp;
1298         int csum_len;
1299         uint16_t eth_type;
1300
1301         csum_len = hdr->csum_start + hdr->csum_offset;
1302
1303         if (csum_len < sizeof(struct ether_header) + sizeof(struct ip))
1304                 return (1);
1305         if (m->m_len < csum_len)
1306                 return (1);
1307
1308         eh = mtod(m, struct ether_header *);
1309         eth_type = ntohs(eh->ether_type);
1310         if (eth_type == ETHERTYPE_VLAN) {
1311                 evh = mtod(m, struct ether_vlan_header *);
1312                 eth_type = ntohs(evh->evl_proto);
1313         }
1314
1315         if (eth_type != ETHERTYPE_IP && eth_type != ETHERTYPE_IPV6) {
1316                 sc->vtnet_stats.rx_csum_bad_ethtype++;
1317                 return (1);
1318         }
1319
1320         /* Use the offset to determine the appropriate CSUM_* flags. */
1321         switch (hdr->csum_offset) {
1322         case offsetof(struct udphdr, uh_sum):
1323                 if (m->m_len < hdr->csum_start + sizeof(struct udphdr))
1324                         return (1);
1325                 udp = (struct udphdr *)(mtod(m, uint8_t *) + hdr->csum_start);
1326                 if (udp->uh_sum == 0)
1327                         return (0);
1328
1329                 /* FALLTHROUGH */
1330
1331         case offsetof(struct tcphdr, th_sum):
1332                 m->m_pkthdr.csum_flags |= CSUM_DATA_VALID | CSUM_PSEUDO_HDR;
1333                 m->m_pkthdr.csum_data = 0xFFFF;
1334                 break;
1335
1336         default:
1337                 sc->vtnet_stats.rx_csum_bad_offset++;
1338                 return (1);
1339         }
1340
1341         sc->vtnet_stats.rx_csum_offloaded++;
1342
1343         return (0);
1344 }
1345
1346 static int
1347 vtnet_rxeof_merged(struct vtnet_softc *sc, struct mbuf *m_head, int nbufs)
1348 {
1349         struct ifnet *ifp;
1350         struct virtqueue *vq;
1351         struct mbuf *m, *m_tail;
1352         int len;
1353
1354         ifp = sc->vtnet_ifp;
1355         vq = sc->vtnet_rx_vq;
1356         m_tail = m_head;
1357
1358         while (--nbufs > 0) {
1359                 m = virtqueue_dequeue(vq, &len);
1360                 if (m == NULL) {
1361                         ifp->if_ierrors++;
1362                         goto fail;
1363                 }
1364
1365                 if (vtnet_newbuf(sc) != 0) {
1366                         ifp->if_iqdrops++;
1367                         vtnet_discard_rxbuf(sc, m);
1368                         if (nbufs > 1)
1369                                 vtnet_discard_merged_rxbuf(sc, nbufs);
1370                         goto fail;
1371                 }
1372
1373                 if (m->m_len < len)
1374                         len = m->m_len;
1375
1376                 m->m_len = len;
1377                 m->m_flags &= ~M_PKTHDR;
1378
1379                 m_head->m_pkthdr.len += len;
1380                 m_tail->m_next = m;
1381                 m_tail = m;
1382         }
1383
1384         return (0);
1385
1386 fail:
1387         sc->vtnet_stats.rx_mergeable_failed++;
1388         m_freem(m_head);
1389
1390         return (1);
1391 }
1392
1393 static int
1394 vtnet_rxeof(struct vtnet_softc *sc, int count, int *rx_npktsp)
1395 {
1396         struct virtio_net_hdr lhdr;
1397         struct ifnet *ifp;
1398         struct virtqueue *vq;
1399         struct mbuf *m;
1400         struct ether_header *eh;
1401         struct virtio_net_hdr *hdr;
1402         struct virtio_net_hdr_mrg_rxbuf *mhdr;
1403         int len, deq, nbufs, adjsz, rx_npkts;
1404
1405         ifp = sc->vtnet_ifp;
1406         vq = sc->vtnet_rx_vq;
1407         hdr = &lhdr;
1408         deq = 0;
1409         rx_npkts = 0;
1410
1411         ASSERT_SERIALIZED(&sc->vtnet_slz);
1412
1413         while (--count >= 0) {
1414                 m = virtqueue_dequeue(vq, &len);
1415                 if (m == NULL)
1416                         break;
1417                 deq++;
1418
1419                 if (len < sc->vtnet_hdr_size + ETHER_HDR_LEN) {
1420                         ifp->if_ierrors++;
1421                         vtnet_discard_rxbuf(sc, m);
1422                         continue;
1423                 }
1424
1425                 if ((sc->vtnet_flags & VTNET_FLAG_MRG_RXBUFS) == 0) {
1426                         nbufs = 1;
1427                         adjsz = sizeof(struct vtnet_rx_header);
1428                         /*
1429                          * Account for our pad between the header and
1430                          * the actual start of the frame.
1431                          */
1432                         len += VTNET_RX_HEADER_PAD;
1433                 } else {
1434                         mhdr = mtod(m, struct virtio_net_hdr_mrg_rxbuf *);
1435                         nbufs = mhdr->num_buffers;
1436                         adjsz = sizeof(struct virtio_net_hdr_mrg_rxbuf);
1437                 }
1438
1439                 if (vtnet_replace_rxbuf(sc, m, len) != 0) {
1440                         ifp->if_iqdrops++;
1441                         vtnet_discard_rxbuf(sc, m);
1442                         if (nbufs > 1)
1443                                 vtnet_discard_merged_rxbuf(sc, nbufs);
1444                         continue;
1445                 }
1446
1447                 m->m_pkthdr.len = len;
1448                 m->m_pkthdr.rcvif = ifp;
1449                 m->m_pkthdr.csum_flags = 0;
1450
1451                 if (nbufs > 1) {
1452                         if (vtnet_rxeof_merged(sc, m, nbufs) != 0)
1453                                 continue;
1454                 }
1455
1456                 ifp->if_ipackets++;
1457
1458                 /*
1459                  * Save copy of header before we strip it. For both mergeable
1460                  * and non-mergeable, the VirtIO header is placed first in the
1461                  * mbuf's data. We no longer need num_buffers, so always use a
1462                  * virtio_net_hdr.
1463                  */
1464                 memcpy(hdr, mtod(m, void *), sizeof(struct virtio_net_hdr));
1465                 m_adj(m, adjsz);
1466
1467                 if (ifp->if_capenable & IFCAP_VLAN_HWTAGGING) {
1468                         eh = mtod(m, struct ether_header *);
1469                         if (eh->ether_type == htons(ETHERTYPE_VLAN)) {
1470                                 vtnet_vlan_tag_remove(m);
1471
1472                                 /*
1473                                  * With the 802.1Q header removed, update the
1474                                  * checksum starting location accordingly.
1475                                  */
1476                                 if (hdr->flags & VIRTIO_NET_HDR_F_NEEDS_CSUM)
1477                                         hdr->csum_start -=
1478                                             ETHER_VLAN_ENCAP_LEN;
1479                         }
1480                 }
1481
1482                 if (ifp->if_capenable & IFCAP_RXCSUM &&
1483                     hdr->flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) {
1484                         if (vtnet_rx_csum(sc, m, hdr) != 0)
1485                                 sc->vtnet_stats.rx_csum_failed++;
1486                 }
1487
1488                 lwkt_serialize_exit(&sc->vtnet_slz);
1489                 rx_npkts++;
1490                 ifp->if_input(ifp, m, NULL, -1);
1491                 lwkt_serialize_enter(&sc->vtnet_slz);
1492
1493                 /*
1494                  * The interface may have been stopped while we were
1495                  * passing the packet up the network stack.
1496                  */
1497                 if ((ifp->if_flags & IFF_RUNNING) == 0)
1498                         break;
1499         }
1500
1501         virtqueue_notify(vq, &sc->vtnet_slz);
1502
1503         if (rx_npktsp != NULL)
1504                 *rx_npktsp = rx_npkts;
1505
1506         return (count > 0 ? 0 : EAGAIN);
1507 }
1508
1509 static void
1510 vtnet_rx_intr_task(void *arg)
1511 {
1512         struct vtnet_softc *sc;
1513         struct ifnet *ifp;
1514         int more;
1515
1516         sc = arg;
1517         ifp = sc->vtnet_ifp;
1518
1519 next:
1520 //      lwkt_serialize_enter(&sc->vtnet_slz);
1521
1522         if ((ifp->if_flags & IFF_RUNNING) == 0) {
1523                 vtnet_enable_rx_intr(sc);
1524 //              lwkt_serialize_exit(&sc->vtnet_slz);
1525                 return;
1526         }
1527
1528         more = vtnet_rxeof(sc, sc->vtnet_rx_process_limit, NULL);
1529         if (!more && vtnet_enable_rx_intr(sc) != 0) {
1530                 vtnet_disable_rx_intr(sc);
1531                 more = 1;
1532         }
1533
1534 //      lwkt_serialize_exit(&sc->vtnet_slz);
1535
1536         if (more) {
1537                 sc->vtnet_stats.rx_task_rescheduled++;
1538                 goto next;
1539         }
1540 }
1541
1542 static int
1543 vtnet_rx_vq_intr(void *xsc)
1544 {
1545         struct vtnet_softc *sc;
1546
1547         sc = xsc;
1548
1549         vtnet_disable_rx_intr(sc);
1550         vtnet_rx_intr_task(sc);
1551
1552         return (1);
1553 }
1554
1555 static void
1556 vtnet_enqueue_txhdr(struct vtnet_softc *sc, struct vtnet_tx_header *txhdr)
1557 {
1558         bzero(txhdr, sizeof(*txhdr));
1559         SLIST_INSERT_HEAD(&sc->vtnet_txhdr_free, txhdr, link);
1560 }
1561
1562 static void
1563 vtnet_txeof(struct vtnet_softc *sc)
1564 {
1565         struct virtqueue *vq;
1566         struct ifnet *ifp;
1567         struct vtnet_tx_header *txhdr;
1568         int deq;
1569
1570         vq = sc->vtnet_tx_vq;
1571         ifp = sc->vtnet_ifp;
1572         deq = 0;
1573
1574         ASSERT_SERIALIZED(&sc->vtnet_slz);
1575
1576         while ((txhdr = virtqueue_dequeue(vq, NULL)) != NULL) {
1577                 deq++;
1578                 ifp->if_opackets++;
1579                 m_freem(txhdr->vth_mbuf);
1580                 vtnet_enqueue_txhdr(sc, txhdr);
1581         }
1582
1583         if (deq > 0) {
1584                 ifq_clr_oactive(&ifp->if_snd);
1585                 if (virtqueue_empty(vq))
1586                         sc->vtnet_watchdog_timer = 0;
1587         }
1588 }
1589
1590 static struct mbuf *
1591 vtnet_tx_offload(struct vtnet_softc *sc, struct mbuf *m,
1592     struct virtio_net_hdr *hdr)
1593 {
1594         struct ifnet *ifp;
1595         struct ether_header *eh;
1596         struct ether_vlan_header *evh;
1597         struct ip *ip;
1598         struct ip6_hdr *ip6;
1599         struct tcphdr *tcp;
1600         int ip_offset;
1601         uint16_t eth_type, csum_start;
1602         uint8_t ip_proto, gso_type;
1603
1604         ifp = sc->vtnet_ifp;
1605         M_ASSERTPKTHDR(m);
1606
1607         ip_offset = sizeof(struct ether_header);
1608         if (m->m_len < ip_offset) {
1609                 if ((m = m_pullup(m, ip_offset)) == NULL)
1610                         return (NULL);
1611         }
1612
1613         eh = mtod(m, struct ether_header *);
1614         eth_type = ntohs(eh->ether_type);
1615         if (eth_type == ETHERTYPE_VLAN) {
1616                 ip_offset = sizeof(struct ether_vlan_header);
1617                 if (m->m_len < ip_offset) {
1618                         if ((m = m_pullup(m, ip_offset)) == NULL)
1619                                 return (NULL);
1620                 }
1621                 evh = mtod(m, struct ether_vlan_header *);
1622                 eth_type = ntohs(evh->evl_proto);
1623         }
1624
1625         switch (eth_type) {
1626         case ETHERTYPE_IP:
1627                 if (m->m_len < ip_offset + sizeof(struct ip)) {
1628                         m = m_pullup(m, ip_offset + sizeof(struct ip));
1629                         if (m == NULL)
1630                                 return (NULL);
1631                 }
1632
1633                 ip = (struct ip *)(mtod(m, uint8_t *) + ip_offset);
1634                 ip_proto = ip->ip_p;
1635                 csum_start = ip_offset + (ip->ip_hl << 2);
1636                 gso_type = VIRTIO_NET_HDR_GSO_TCPV4;
1637                 break;
1638
1639         case ETHERTYPE_IPV6:
1640                 if (m->m_len < ip_offset + sizeof(struct ip6_hdr)) {
1641                         m = m_pullup(m, ip_offset + sizeof(struct ip6_hdr));
1642                         if (m == NULL)
1643                                 return (NULL);
1644                 }
1645
1646                 ip6 = (struct ip6_hdr *)(mtod(m, uint8_t *) + ip_offset);
1647                 /*
1648                  * XXX Assume no extension headers are present. Presently,
1649                  * this will always be true in the case of TSO, and FreeBSD
1650                  * does not perform checksum offloading of IPv6 yet.
1651                  */
1652                 ip_proto = ip6->ip6_nxt;
1653                 csum_start = ip_offset + sizeof(struct ip6_hdr);
1654                 gso_type = VIRTIO_NET_HDR_GSO_TCPV6;
1655                 break;
1656
1657         default:
1658                 return (m);
1659         }
1660
1661         if (m->m_pkthdr.csum_flags & VTNET_CSUM_OFFLOAD) {
1662                 hdr->flags |= VIRTIO_NET_HDR_F_NEEDS_CSUM;
1663                 hdr->csum_start = csum_start;
1664                 hdr->csum_offset = m->m_pkthdr.csum_data;
1665
1666                 sc->vtnet_stats.tx_csum_offloaded++;
1667         }
1668
1669         if (m->m_pkthdr.csum_flags & CSUM_TSO) {
1670                 if (ip_proto != IPPROTO_TCP)
1671                         return (m);
1672
1673                 if (m->m_len < csum_start + sizeof(struct tcphdr)) {
1674                         m = m_pullup(m, csum_start + sizeof(struct tcphdr));
1675                         if (m == NULL)
1676                                 return (NULL);
1677                 }
1678
1679                 tcp = (struct tcphdr *)(mtod(m, uint8_t *) + csum_start);
1680                 hdr->gso_type = gso_type;
1681                 hdr->hdr_len = csum_start + (tcp->th_off << 2);
1682                 hdr->gso_size = m->m_pkthdr.tso_segsz;
1683
1684                 if (tcp->th_flags & TH_CWR) {
1685                         /*
1686                          * Drop if we did not negotiate VIRTIO_NET_F_HOST_ECN.
1687                          * ECN support is only configurable globally with the
1688                          * net.inet.tcp.ecn.enable sysctl knob.
1689                          */
1690                         if ((sc->vtnet_flags & VTNET_FLAG_TSO_ECN) == 0) {
1691                                 if_printf(ifp, "TSO with ECN not supported "
1692                                     "by host\n");
1693                                 m_freem(m);
1694                                 return (NULL);
1695                         }
1696
1697                         hdr->gso_type |= VIRTIO_NET_HDR_GSO_ECN;
1698                 }
1699
1700                 sc->vtnet_stats.tx_tso_offloaded++;
1701         }
1702
1703         return (m);
1704 }
1705
1706 static int
1707 vtnet_enqueue_txbuf(struct vtnet_softc *sc, struct mbuf **m_head,
1708     struct vtnet_tx_header *txhdr)
1709 {
1710         struct sglist sg;
1711         struct sglist_seg segs[VTNET_MAX_TX_SEGS];
1712         struct virtqueue *vq;
1713         struct mbuf *m;
1714         int error;
1715
1716         vq = sc->vtnet_tx_vq;
1717         m = *m_head;
1718
1719         sglist_init(&sg, sc->vtnet_tx_nsegs, segs);
1720         error = sglist_append(&sg, &txhdr->vth_uhdr, sc->vtnet_hdr_size);
1721         KASSERT(error == 0 && sg.sg_nseg == 1,
1722             ("%s: error %d adding header to sglist", __func__, error));
1723
1724         error = sglist_append_mbuf(&sg, m);
1725         if (error) {
1726                 m = m_defrag(m, M_NOWAIT);
1727                 if (m == NULL)
1728                         goto fail;
1729
1730                 *m_head = m;
1731                 sc->vtnet_stats.tx_defragged++;
1732
1733                 error = sglist_append_mbuf(&sg, m);
1734                 if (error)
1735                         goto fail;
1736         }
1737
1738         txhdr->vth_mbuf = m;
1739         error = virtqueue_enqueue(vq, txhdr, &sg, sg.sg_nseg, 0);
1740
1741         return (error);
1742
1743 fail:
1744         sc->vtnet_stats.tx_defrag_failed++;
1745         m_freem(*m_head);
1746         *m_head = NULL;
1747
1748         return (ENOBUFS);
1749 }
1750
1751 static struct mbuf *
1752 vtnet_vlan_tag_insert(struct mbuf *m)
1753 {
1754         struct mbuf *n;
1755         struct ether_vlan_header *evl;
1756
1757         if (M_WRITABLE(m) == 0) {
1758                 n = m_dup(m, M_NOWAIT);
1759                 m_freem(m);
1760                 if ((m = n) == NULL)
1761                         return (NULL);
1762         }
1763
1764         M_PREPEND(m, ETHER_VLAN_ENCAP_LEN, M_NOWAIT);
1765         if (m == NULL)
1766                 return (NULL);
1767         if (m->m_len < sizeof(struct ether_vlan_header)) {
1768                 m = m_pullup(m, sizeof(struct ether_vlan_header));
1769                 if (m == NULL)
1770                         return (NULL);
1771         }
1772
1773         /* Insert 802.1Q header into the existing Ethernet header. */
1774         evl = mtod(m, struct ether_vlan_header *);
1775         bcopy((char *) evl + ETHER_VLAN_ENCAP_LEN,
1776               (char *) evl, ETHER_HDR_LEN - ETHER_TYPE_LEN);
1777         evl->evl_encap_proto = htons(ETHERTYPE_VLAN);
1778         evl->evl_tag = htons(m->m_pkthdr.ether_vlantag);
1779         m->m_flags &= ~M_VLANTAG;
1780
1781         return (m);
1782 }
1783
1784 static int
1785 vtnet_encap(struct vtnet_softc *sc, struct mbuf **m_head)
1786 {
1787         struct vtnet_tx_header *txhdr;
1788         struct virtio_net_hdr *hdr;
1789         struct mbuf *m;
1790         int error;
1791
1792         txhdr = SLIST_FIRST(&sc->vtnet_txhdr_free);
1793         if (txhdr == NULL)
1794                 return (ENOBUFS);
1795         SLIST_REMOVE_HEAD(&sc->vtnet_txhdr_free, link);
1796
1797         /*
1798          * Always use the non-mergeable header to simplify things. When
1799          * the mergeable feature is negotiated, the num_buffers field
1800          * must be set to zero. We use vtnet_hdr_size later to enqueue
1801          * the correct header size to the host.
1802          */
1803         hdr = &txhdr->vth_uhdr.hdr;
1804         m = *m_head;
1805
1806         error = ENOBUFS;
1807
1808         if (m->m_flags & M_VLANTAG) {
1809                 //m = ether_vlanencap(m, m->m_pkthdr.ether_vtag);
1810                 m = vtnet_vlan_tag_insert(m);
1811                 if ((*m_head = m) == NULL)
1812                         goto fail;
1813                 m->m_flags &= ~M_VLANTAG;
1814         }
1815
1816         if (m->m_pkthdr.csum_flags != 0) {
1817                 m = vtnet_tx_offload(sc, m, hdr);
1818                 if ((*m_head = m) == NULL)
1819                         goto fail;
1820         }
1821
1822         error = vtnet_enqueue_txbuf(sc, m_head, txhdr);
1823 fail:
1824         if (error != 0)
1825                 vtnet_enqueue_txhdr(sc, txhdr);
1826         return (error);
1827 }
1828
1829 static void
1830 vtnet_start(struct ifnet *ifp, struct ifaltq_subque *ifsq)
1831 {
1832         struct vtnet_softc *sc;
1833
1834         sc = ifp->if_softc;
1835
1836         ASSERT_ALTQ_SQ_DEFAULT(ifp, ifsq);
1837         lwkt_serialize_enter(&sc->vtnet_slz);
1838         vtnet_start_locked(ifp, ifsq);
1839         lwkt_serialize_exit(&sc->vtnet_slz);
1840 }
1841
1842 static void
1843 vtnet_start_locked(struct ifnet *ifp, struct ifaltq_subque *ifsq)
1844 {
1845         struct vtnet_softc *sc;
1846         struct virtqueue *vq;
1847         struct mbuf *m0;
1848         int enq;
1849
1850         sc = ifp->if_softc;
1851         vq = sc->vtnet_tx_vq;
1852         enq = 0;
1853
1854         ASSERT_SERIALIZED(&sc->vtnet_slz);
1855
1856         if ((ifp->if_flags & (IFF_RUNNING)) !=
1857             IFF_RUNNING || ((sc->vtnet_flags & VTNET_FLAG_LINK) == 0))
1858                 return;
1859
1860 #ifdef VTNET_TX_INTR_MODERATION
1861         if (virtqueue_nused(vq) >= sc->vtnet_tx_size / 2)
1862                 vtnet_txeof(sc);
1863 #endif
1864
1865         while (!ifsq_is_empty(ifsq)) {
1866                 if (virtqueue_full(vq)) {
1867                         ifq_set_oactive(&ifp->if_snd);
1868                         break;
1869                 }
1870
1871                 m0 = ifq_dequeue(&ifp->if_snd);
1872                 if (m0 == NULL)
1873                         break;
1874
1875                 if (vtnet_encap(sc, &m0) != 0) {
1876                         if (m0 == NULL)
1877                                 break;
1878                         ifq_prepend(&ifp->if_snd, m0);
1879                         ifq_set_oactive(&ifp->if_snd);
1880                         break;
1881                 }
1882
1883                 enq++;
1884                 ETHER_BPF_MTAP(ifp, m0);
1885         }
1886
1887         if (enq > 0) {
1888                 virtqueue_notify(vq, &sc->vtnet_slz);
1889                 sc->vtnet_watchdog_timer = VTNET_WATCHDOG_TIMEOUT;
1890         }
1891 }
1892
1893 static void
1894 vtnet_tick(void *xsc)
1895 {
1896         struct vtnet_softc *sc;
1897
1898         sc = xsc;
1899
1900 #if 0
1901         ASSERT_SERIALIZED(&sc->vtnet_slz);
1902 #ifdef VTNET_DEBUG
1903         virtqueue_dump(sc->vtnet_rx_vq);
1904         virtqueue_dump(sc->vtnet_tx_vq);
1905 #endif
1906
1907         vtnet_watchdog(sc);
1908         callout_reset(&sc->vtnet_tick_ch, hz, vtnet_tick, sc);
1909 #endif
1910 }
1911
1912 static void
1913 vtnet_tx_intr_task(void *arg)
1914 {
1915         struct vtnet_softc *sc;
1916         struct ifnet *ifp;
1917         struct ifaltq_subque *ifsq;
1918
1919         sc = arg;
1920         ifp = sc->vtnet_ifp;
1921         ifsq = ifq_get_subq_default(&ifp->if_snd);
1922
1923 next:
1924 //      lwkt_serialize_enter(&sc->vtnet_slz);
1925
1926         if ((ifp->if_flags & IFF_RUNNING) == 0) {
1927                 vtnet_enable_tx_intr(sc);
1928 //              lwkt_serialize_exit(&sc->vtnet_slz);
1929                 return;
1930         }
1931
1932         vtnet_txeof(sc);
1933
1934         if (!ifsq_is_empty(ifsq))
1935                 vtnet_start_locked(ifp, ifsq);
1936
1937         if (vtnet_enable_tx_intr(sc) != 0) {
1938                 vtnet_disable_tx_intr(sc);
1939                 sc->vtnet_stats.tx_task_rescheduled++;
1940 //              lwkt_serialize_exit(&sc->vtnet_slz);
1941                 goto next;
1942         }
1943
1944 //      lwkt_serialize_exit(&sc->vtnet_slz);
1945 }
1946
1947 static int
1948 vtnet_tx_vq_intr(void *xsc)
1949 {
1950         struct vtnet_softc *sc;
1951
1952         sc = xsc;
1953
1954         vtnet_disable_tx_intr(sc);
1955         vtnet_tx_intr_task(sc);
1956
1957         return (1);
1958 }
1959
1960 static void
1961 vtnet_stop(struct vtnet_softc *sc)
1962 {
1963         device_t dev;
1964         struct ifnet *ifp;
1965
1966         dev = sc->vtnet_dev;
1967         ifp = sc->vtnet_ifp;
1968
1969         ASSERT_SERIALIZED(&sc->vtnet_slz);
1970
1971         sc->vtnet_watchdog_timer = 0;
1972         callout_stop(&sc->vtnet_tick_ch);
1973         ifq_clr_oactive(&ifp->if_snd);
1974         ifp->if_flags &= ~(IFF_RUNNING);
1975
1976         vtnet_disable_rx_intr(sc);
1977         vtnet_disable_tx_intr(sc);
1978
1979         /*
1980          * Stop the host VirtIO adapter. Note this will reset the host
1981          * adapter's state back to the pre-initialized state, so in
1982          * order to make the device usable again, we must drive it
1983          * through virtio_reinit() and virtio_reinit_complete().
1984          */
1985         virtio_stop(dev);
1986
1987         sc->vtnet_flags &= ~VTNET_FLAG_LINK;
1988
1989         vtnet_free_rx_mbufs(sc);
1990         vtnet_free_tx_mbufs(sc);
1991 }
1992
1993 static int
1994 vtnet_virtio_reinit(struct vtnet_softc *sc)
1995 {
1996         device_t dev;
1997         struct ifnet *ifp;
1998         uint64_t features;
1999         int error;
2000
2001         dev = sc->vtnet_dev;
2002         ifp = sc->vtnet_ifp;
2003         features = sc->vtnet_features;
2004
2005         /*
2006          * Re-negotiate with the host, removing any disabled receive
2007          * features. Transmit features are disabled only on our side
2008          * via if_capenable and if_hwassist.
2009          */
2010
2011         if (ifp->if_capabilities & IFCAP_RXCSUM) {
2012                 if ((ifp->if_capenable & IFCAP_RXCSUM) == 0)
2013                         features &= ~VIRTIO_NET_F_GUEST_CSUM;
2014         }
2015
2016         if (ifp->if_capabilities & IFCAP_LRO) {
2017                 if ((ifp->if_capenable & IFCAP_LRO) == 0)
2018                         features &= ~VTNET_LRO_FEATURES;
2019         }
2020
2021         if (ifp->if_capabilities & IFCAP_VLAN_HWFILTER) {
2022                 if ((ifp->if_capenable & IFCAP_VLAN_HWFILTER) == 0)
2023                         features &= ~VIRTIO_NET_F_CTRL_VLAN;
2024         }
2025
2026         error = virtio_reinit(dev, features);
2027         if (error)
2028                 device_printf(dev, "virtio reinit error %d\n", error);
2029
2030         return (error);
2031 }
2032
2033 static void
2034 vtnet_init_locked(struct vtnet_softc *sc)
2035 {
2036         device_t dev;
2037         struct ifnet *ifp;
2038         int error;
2039
2040         dev = sc->vtnet_dev;
2041         ifp = sc->vtnet_ifp;
2042
2043         ASSERT_SERIALIZED(&sc->vtnet_slz);
2044
2045         if (ifp->if_flags & IFF_RUNNING)
2046                 return;
2047
2048         /* Stop host's adapter, cancel any pending I/O. */
2049         vtnet_stop(sc);
2050
2051         /* Reinitialize the host device. */
2052         error = vtnet_virtio_reinit(sc);
2053         if (error) {
2054                 device_printf(dev,
2055                     "reinitialization failed, stopping device...\n");
2056                 vtnet_stop(sc);
2057                 return;
2058         }
2059
2060         /* Update host with assigned MAC address. */
2061         bcopy(IF_LLADDR(ifp), sc->vtnet_hwaddr, ETHER_ADDR_LEN);
2062         vtnet_set_hwaddr(sc);
2063
2064         ifp->if_hwassist = 0;
2065         if (ifp->if_capenable & IFCAP_TXCSUM)
2066                 ifp->if_hwassist |= VTNET_CSUM_OFFLOAD;
2067         if (ifp->if_capenable & IFCAP_TSO4)
2068                 ifp->if_hwassist |= CSUM_TSO;
2069
2070         error = vtnet_init_rx_vq(sc);
2071         if (error) {
2072                 device_printf(dev,
2073                     "cannot allocate mbufs for Rx virtqueue\n");
2074                 vtnet_stop(sc);
2075                 return;
2076         }
2077
2078         if (sc->vtnet_flags & VTNET_FLAG_CTRL_VQ) {
2079                 if (sc->vtnet_flags & VTNET_FLAG_CTRL_RX) {
2080                         /* Restore promiscuous and all-multicast modes. */
2081                         vtnet_rx_filter(sc);
2082
2083                         /* Restore filtered MAC addresses. */
2084                         vtnet_rx_filter_mac(sc);
2085                 }
2086
2087                 /* Restore VLAN filters. */
2088                 if (ifp->if_capenable & IFCAP_VLAN_HWFILTER)
2089                         vtnet_rx_filter_vlan(sc);
2090         }
2091
2092         {
2093                 vtnet_enable_rx_intr(sc);
2094                 vtnet_enable_tx_intr(sc);
2095         }
2096
2097         ifp->if_flags |= IFF_RUNNING;
2098         ifq_clr_oactive(&ifp->if_snd);
2099
2100         virtio_reinit_complete(dev);
2101
2102         vtnet_update_link_status(sc);
2103         callout_reset(&sc->vtnet_tick_ch, hz, vtnet_tick, sc);
2104 }
2105
2106 static void
2107 vtnet_init(void *xsc)
2108 {
2109         struct vtnet_softc *sc;
2110
2111         sc = xsc;
2112
2113         lwkt_serialize_enter(&sc->vtnet_slz);
2114         vtnet_init_locked(sc);
2115         lwkt_serialize_exit(&sc->vtnet_slz);
2116 }
2117
2118 static void
2119 vtnet_exec_ctrl_cmd(struct vtnet_softc *sc, void *cookie,
2120     struct sglist *sg, int readable, int writable)
2121 {
2122         struct virtqueue *vq;
2123         void *c;
2124
2125         vq = sc->vtnet_ctrl_vq;
2126
2127         ASSERT_SERIALIZED(&sc->vtnet_slz);
2128         KASSERT(sc->vtnet_flags & VTNET_FLAG_CTRL_VQ,
2129             ("no control virtqueue"));
2130         KASSERT(virtqueue_empty(vq),
2131             ("control command already enqueued"));
2132
2133         if (virtqueue_enqueue(vq, cookie, sg, readable, writable) != 0)
2134                 return;
2135
2136         virtqueue_notify(vq, &sc->vtnet_slz);
2137
2138         /*
2139          * Poll until the command is complete. Previously, we would
2140          * sleep until the control virtqueue interrupt handler woke
2141          * us up, but dropping the VTNET_MTX leads to serialization
2142          * difficulties.
2143          *
2144          * Furthermore, it appears QEMU/KVM only allocates three MSIX
2145          * vectors. Two of those vectors are needed for the Rx and Tx
2146          * virtqueues. We do not support sharing both a Vq and config
2147          * changed notification on the same MSIX vector.
2148          */
2149         c = virtqueue_poll(vq, NULL);
2150         KASSERT(c == cookie, ("unexpected control command response"));
2151 }
2152
2153 static int
2154 vtnet_ctrl_mac_cmd(struct vtnet_softc *sc, uint8_t *hwaddr)
2155 {
2156         struct {
2157                 struct virtio_net_ctrl_hdr hdr __aligned(2);
2158                 uint8_t pad1;
2159                 char aligned_hwaddr[ETHER_ADDR_LEN] __aligned(8);
2160                 uint8_t pad2;
2161                 uint8_t ack;
2162         } s;
2163         struct sglist_seg segs[3];
2164         struct sglist sg;
2165         int error;
2166
2167         s.hdr.class = VIRTIO_NET_CTRL_MAC;
2168         s.hdr.cmd = VIRTIO_NET_CTRL_MAC_ADDR_SET;
2169         s.ack = VIRTIO_NET_ERR;
2170
2171         /* Copy the mac address into physically contiguous memory */
2172         memcpy(s.aligned_hwaddr, hwaddr, ETHER_ADDR_LEN);
2173
2174         sglist_init(&sg, 3, segs);
2175         error = 0;
2176         error |= sglist_append(&sg, &s.hdr,
2177             sizeof(struct virtio_net_ctrl_hdr));
2178         error |= sglist_append(&sg, s.aligned_hwaddr, ETHER_ADDR_LEN);
2179         error |= sglist_append(&sg, &s.ack, sizeof(uint8_t));
2180         KASSERT(error == 0 && sg.sg_nseg == 3,
2181             ("%s: error %d adding set MAC msg to sglist", __func__, error));
2182
2183         vtnet_exec_ctrl_cmd(sc, &s.ack, &sg, sg.sg_nseg - 1, 1);
2184
2185         return (s.ack == VIRTIO_NET_OK ? 0 : EIO);
2186 }
2187
2188 static void
2189 vtnet_rx_filter(struct vtnet_softc *sc)
2190 {
2191         device_t dev;
2192         struct ifnet *ifp;
2193
2194         dev = sc->vtnet_dev;
2195         ifp = sc->vtnet_ifp;
2196
2197         ASSERT_SERIALIZED(&sc->vtnet_slz);
2198         KASSERT(sc->vtnet_flags & VTNET_FLAG_CTRL_RX,
2199             ("CTRL_RX feature not negotiated"));
2200
2201         if (vtnet_set_promisc(sc, ifp->if_flags & IFF_PROMISC) != 0)
2202                 device_printf(dev, "cannot %s promiscuous mode\n",
2203                     (ifp->if_flags & IFF_PROMISC) ? "enable" : "disable");
2204
2205         if (vtnet_set_allmulti(sc, ifp->if_flags & IFF_ALLMULTI) != 0)
2206                 device_printf(dev, "cannot %s all-multicast mode\n",
2207                     (ifp->if_flags & IFF_ALLMULTI) ? "enable" : "disable");
2208 }
2209
2210 static int
2211 vtnet_ctrl_rx_cmd(struct vtnet_softc *sc, int cmd, int on)
2212 {
2213         struct sglist_seg segs[3];
2214         struct sglist sg;
2215         struct {
2216                 struct virtio_net_ctrl_hdr hdr __aligned(2);
2217                 uint8_t pad1;
2218                 uint8_t onoff;
2219                 uint8_t pad2;
2220                 uint8_t ack;
2221         } s;
2222         int error;
2223
2224         KASSERT(sc->vtnet_flags & VTNET_FLAG_CTRL_RX,
2225             ("%s: CTRL_RX feature not negotiated", __func__));
2226
2227         s.hdr.class = VIRTIO_NET_CTRL_RX;
2228         s.hdr.cmd = cmd;
2229         s.onoff = !!on;
2230         s.ack = VIRTIO_NET_ERR;
2231
2232         sglist_init(&sg, 3, segs);
2233         error = 0;
2234         error |= sglist_append(&sg, &s.hdr, sizeof(struct virtio_net_ctrl_hdr));
2235         error |= sglist_append(&sg, &s.onoff, sizeof(uint8_t));
2236         error |= sglist_append(&sg, &s.ack, sizeof(uint8_t));
2237         KASSERT(error == 0 && sg.sg_nseg == 3,
2238             ("%s: error %d adding Rx message to sglist", __func__, error));
2239
2240         vtnet_exec_ctrl_cmd(sc, &s.ack, &sg, sg.sg_nseg - 1, 1);
2241
2242         return (s.ack == VIRTIO_NET_OK ? 0 : EIO);
2243 }
2244
2245 static int
2246 vtnet_set_promisc(struct vtnet_softc *sc, int on)
2247 {
2248
2249         return (vtnet_ctrl_rx_cmd(sc, VIRTIO_NET_CTRL_RX_PROMISC, on));
2250 }
2251
2252 static int
2253 vtnet_set_allmulti(struct vtnet_softc *sc, int on)
2254 {
2255
2256         return (vtnet_ctrl_rx_cmd(sc, VIRTIO_NET_CTRL_RX_ALLMULTI, on));
2257 }
2258
2259 static void
2260 vtnet_rx_filter_mac(struct vtnet_softc *sc)
2261 {
2262         struct virtio_net_ctrl_hdr hdr __aligned(2);
2263         struct vtnet_mac_filter *filter;
2264         struct sglist_seg segs[4];
2265         struct sglist sg;
2266         struct ifnet *ifp;
2267         struct ifaddr *ifa;
2268         struct ifaddr_container *ifac;
2269         struct ifmultiaddr *ifma;
2270         int ucnt, mcnt, promisc, allmulti, error;
2271         uint8_t ack;
2272
2273         ifp = sc->vtnet_ifp;
2274         ucnt = 0;
2275         mcnt = 0;
2276         promisc = 0;
2277         allmulti = 0;
2278
2279         ASSERT_SERIALIZED(&sc->vtnet_slz);
2280         KASSERT(sc->vtnet_flags & VTNET_FLAG_CTRL_RX,
2281             ("%s: CTRL_RX feature not negotiated", __func__));
2282
2283         /* Use the MAC filtering table allocated in vtnet_attach. */
2284         filter = sc->vtnet_macfilter;
2285         memset(filter, 0, sizeof(struct vtnet_mac_filter));
2286
2287         /* Unicast MAC addresses: */
2288         //if_addr_rlock(ifp);
2289         TAILQ_FOREACH(ifac, &ifp->if_addrheads[mycpuid], ifa_link) {
2290                 ifa = ifac->ifa;
2291                 if (ifa->ifa_addr->sa_family != AF_LINK)
2292                         continue;
2293                 else if (memcmp(LLADDR((struct sockaddr_dl *)ifa->ifa_addr),
2294                     sc->vtnet_hwaddr, ETHER_ADDR_LEN) == 0)
2295                         continue;
2296                 else if (ucnt == VTNET_MAX_MAC_ENTRIES) {
2297                         promisc = 1;
2298                         break;
2299                 }
2300
2301                 bcopy(LLADDR((struct sockaddr_dl *)ifa->ifa_addr),
2302                     &filter->vmf_unicast.macs[ucnt], ETHER_ADDR_LEN);
2303                 ucnt++;
2304         }
2305         //if_addr_runlock(ifp);
2306
2307         if (promisc != 0) {
2308                 filter->vmf_unicast.nentries = 0;
2309                 if_printf(ifp, "more than %d MAC addresses assigned, "
2310                     "falling back to promiscuous mode\n",
2311                     VTNET_MAX_MAC_ENTRIES);
2312         } else
2313                 filter->vmf_unicast.nentries = ucnt;
2314
2315         /* Multicast MAC addresses: */
2316         //if_maddr_rlock(ifp);
2317         TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2318                 if (ifma->ifma_addr->sa_family != AF_LINK)
2319                         continue;
2320                 else if (mcnt == VTNET_MAX_MAC_ENTRIES) {
2321                         allmulti = 1;
2322                         break;
2323                 }
2324
2325                 bcopy(LLADDR((struct sockaddr_dl *)ifma->ifma_addr),
2326                     &filter->vmf_multicast.macs[mcnt], ETHER_ADDR_LEN);
2327                 mcnt++;
2328         }
2329         //if_maddr_runlock(ifp);
2330
2331         if (allmulti != 0) {
2332                 filter->vmf_multicast.nentries = 0;
2333                 if_printf(ifp, "more than %d multicast MAC addresses "
2334                     "assigned, falling back to all-multicast mode\n",
2335                     VTNET_MAX_MAC_ENTRIES);
2336         } else
2337                 filter->vmf_multicast.nentries = mcnt;
2338
2339         if (promisc != 0 && allmulti != 0)
2340                 goto out;
2341
2342         hdr.class = VIRTIO_NET_CTRL_MAC;
2343         hdr.cmd = VIRTIO_NET_CTRL_MAC_TABLE_SET;
2344         ack = VIRTIO_NET_ERR;
2345
2346         sglist_init(&sg, 4, segs);
2347         error = 0;
2348         error |= sglist_append(&sg, &hdr, sizeof(struct virtio_net_ctrl_hdr));
2349         error |= sglist_append(&sg, &filter->vmf_unicast,
2350             sizeof(uint32_t) + filter->vmf_unicast.nentries * ETHER_ADDR_LEN);
2351         error |= sglist_append(&sg, &filter->vmf_multicast,
2352             sizeof(uint32_t) + filter->vmf_multicast.nentries * ETHER_ADDR_LEN);
2353         error |= sglist_append(&sg, &ack, sizeof(uint8_t));
2354         KASSERT(error == 0 && sg.sg_nseg == 4,
2355             ("%s: error %d adding MAC filter msg to sglist", __func__, error));
2356
2357         vtnet_exec_ctrl_cmd(sc, &ack, &sg, sg.sg_nseg - 1, 1);
2358
2359         if (ack != VIRTIO_NET_OK)
2360                 if_printf(ifp, "error setting host MAC filter table\n");
2361
2362 out:
2363         if (promisc != 0 && vtnet_set_promisc(sc, 1) != 0)
2364                 if_printf(ifp, "cannot enable promiscuous mode\n");
2365         if (allmulti != 0 && vtnet_set_allmulti(sc, 1) != 0)
2366                 if_printf(ifp, "cannot enable all-multicast mode\n");
2367 }
2368
2369 static int
2370 vtnet_exec_vlan_filter(struct vtnet_softc *sc, int add, uint16_t tag)
2371 {
2372         struct sglist_seg segs[3];
2373         struct sglist sg;
2374         struct {
2375                 struct virtio_net_ctrl_hdr hdr __aligned(2);
2376                 uint8_t pad1;
2377                 uint16_t tag;
2378                 uint8_t pad2;
2379                 uint8_t ack;
2380         } s;
2381         int error;
2382
2383         s.hdr.class = VIRTIO_NET_CTRL_VLAN;
2384         s.hdr.cmd = add ? VIRTIO_NET_CTRL_VLAN_ADD : VIRTIO_NET_CTRL_VLAN_DEL;
2385         s.tag = tag;
2386         s.ack = VIRTIO_NET_ERR;
2387
2388         sglist_init(&sg, 3, segs);
2389         error = 0;
2390         error |= sglist_append(&sg, &s.hdr, sizeof(struct virtio_net_ctrl_hdr));
2391         error |= sglist_append(&sg, &s.tag, sizeof(uint16_t));
2392         error |= sglist_append(&sg, &s.ack, sizeof(uint8_t));
2393         KASSERT(error == 0 && sg.sg_nseg == 3,
2394             ("%s: error %d adding VLAN message to sglist", __func__, error));
2395
2396         vtnet_exec_ctrl_cmd(sc, &s.ack, &sg, sg.sg_nseg - 1, 1);
2397
2398         return (s.ack == VIRTIO_NET_OK ? 0 : EIO);
2399 }
2400
2401 static void
2402 vtnet_rx_filter_vlan(struct vtnet_softc *sc)
2403 {
2404         uint32_t w;
2405         uint16_t tag;
2406         int i, bit, nvlans;
2407
2408         ASSERT_SERIALIZED(&sc->vtnet_slz);
2409         KASSERT(sc->vtnet_flags & VTNET_FLAG_VLAN_FILTER,
2410             ("%s: VLAN_FILTER feature not negotiated", __func__));
2411
2412         nvlans = sc->vtnet_nvlans;
2413
2414         /* Enable the filter for each configured VLAN. */
2415         for (i = 0; i < VTNET_VLAN_SHADOW_SIZE && nvlans > 0; i++) {
2416                 w = sc->vtnet_vlan_shadow[i];
2417                 while ((bit = ffs(w) - 1) != -1) {
2418                         w &= ~(1 << bit);
2419                         tag = sizeof(w) * CHAR_BIT * i + bit;
2420                         nvlans--;
2421
2422                         if (vtnet_exec_vlan_filter(sc, 1, tag) != 0) {
2423                                 device_printf(sc->vtnet_dev,
2424                                     "cannot enable VLAN %d filter\n", tag);
2425                         }
2426                 }
2427         }
2428
2429         KASSERT(nvlans == 0, ("VLAN count incorrect"));
2430 }
2431
2432 static void
2433 vtnet_update_vlan_filter(struct vtnet_softc *sc, int add, uint16_t tag)
2434 {
2435         struct ifnet *ifp;
2436         int idx, bit;
2437
2438         ifp = sc->vtnet_ifp;
2439         idx = (tag >> 5) & 0x7F;
2440         bit = tag & 0x1F;
2441
2442         if (tag == 0 || tag > 4095)
2443                 return;
2444
2445         lwkt_serialize_enter(&sc->vtnet_slz);
2446
2447         /* Update shadow VLAN table. */
2448         if (add) {
2449                 sc->vtnet_nvlans++;
2450                 sc->vtnet_vlan_shadow[idx] |= (1 << bit);
2451         } else {
2452                 sc->vtnet_nvlans--;
2453                 sc->vtnet_vlan_shadow[idx] &= ~(1 << bit);
2454         }
2455
2456         if (ifp->if_capenable & IFCAP_VLAN_HWFILTER &&
2457             vtnet_exec_vlan_filter(sc, add, tag) != 0) {
2458                 device_printf(sc->vtnet_dev,
2459                     "cannot %s VLAN %d %s the host filter table\n",
2460                     add ? "add" : "remove", tag, add ? "to" : "from");
2461         }
2462
2463         lwkt_serialize_exit(&sc->vtnet_slz);
2464 }
2465
2466 static void
2467 vtnet_register_vlan(void *arg, struct ifnet *ifp, uint16_t tag)
2468 {
2469
2470         if (ifp->if_softc != arg)
2471                 return;
2472
2473         vtnet_update_vlan_filter(arg, 1, tag);
2474 }
2475
2476 static void
2477 vtnet_unregister_vlan(void *arg, struct ifnet *ifp, uint16_t tag)
2478 {
2479
2480         if (ifp->if_softc != arg)
2481                 return;
2482
2483         vtnet_update_vlan_filter(arg, 0, tag);
2484 }
2485
2486 static int
2487 vtnet_ifmedia_upd(struct ifnet *ifp)
2488 {
2489         struct vtnet_softc *sc;
2490         struct ifmedia *ifm;
2491
2492         sc = ifp->if_softc;
2493         ifm = &sc->vtnet_media;
2494
2495         if (IFM_TYPE(ifm->ifm_media) != IFM_ETHER)
2496                 return (EINVAL);
2497
2498         return (0);
2499 }
2500
2501 static void
2502 vtnet_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr)
2503 {
2504         struct vtnet_softc *sc;
2505
2506         sc = ifp->if_softc;
2507
2508         ifmr->ifm_status = IFM_AVALID;
2509         ifmr->ifm_active = IFM_ETHER;
2510
2511         lwkt_serialize_enter(&sc->vtnet_slz);
2512         if (vtnet_is_link_up(sc) != 0) {
2513                 ifmr->ifm_status |= IFM_ACTIVE;
2514                 ifmr->ifm_active |= VTNET_MEDIATYPE;
2515         } else
2516                 ifmr->ifm_active |= IFM_NONE;
2517         lwkt_serialize_exit(&sc->vtnet_slz);
2518 }
2519
2520 static void
2521 vtnet_add_statistics(struct vtnet_softc *sc)
2522 {
2523         device_t dev;
2524         struct vtnet_statistics *stats;
2525         struct sysctl_ctx_list *ctx;
2526         struct sysctl_oid *tree;
2527         struct sysctl_oid_list *child;
2528
2529         dev = sc->vtnet_dev;
2530         stats = &sc->vtnet_stats;
2531         ctx = device_get_sysctl_ctx(dev);
2532         tree = device_get_sysctl_tree(dev);
2533         child = SYSCTL_CHILDREN(tree);
2534
2535         SYSCTL_ADD_UQUAD(ctx, child, OID_AUTO, "mbuf_alloc_failed",
2536             CTLFLAG_RD, &stats->mbuf_alloc_failed, 0,
2537             "Mbuf cluster allocation failures");
2538
2539         SYSCTL_ADD_UQUAD(ctx, child, OID_AUTO, "rx_frame_too_large",
2540             CTLFLAG_RD, &stats->rx_frame_too_large, 0,
2541             "Received frame larger than the mbuf chain");
2542         SYSCTL_ADD_UQUAD(ctx, child, OID_AUTO, "rx_enq_replacement_failed",
2543             CTLFLAG_RD, &stats->rx_enq_replacement_failed, 0,
2544             "Enqueuing the replacement receive mbuf failed");
2545         SYSCTL_ADD_UQUAD(ctx, child, OID_AUTO, "rx_mergeable_failed",
2546             CTLFLAG_RD, &stats->rx_mergeable_failed, 0,
2547             "Mergeable buffers receive failures");
2548         SYSCTL_ADD_UQUAD(ctx, child, OID_AUTO, "rx_csum_bad_ethtype",
2549             CTLFLAG_RD, &stats->rx_csum_bad_ethtype, 0,
2550             "Received checksum offloaded buffer with unsupported "
2551             "Ethernet type");
2552         SYSCTL_ADD_UQUAD(ctx, child, OID_AUTO, "rx_csum_bad_ipproto",
2553             CTLFLAG_RD, &stats->rx_csum_bad_ipproto, 0,
2554             "Received checksum offloaded buffer with incorrect IP protocol");
2555         SYSCTL_ADD_UQUAD(ctx, child, OID_AUTO, "rx_csum_bad_offset",
2556             CTLFLAG_RD, &stats->rx_csum_bad_offset, 0,
2557             "Received checksum offloaded buffer with incorrect offset");
2558         SYSCTL_ADD_UQUAD(ctx, child, OID_AUTO, "rx_csum_failed",
2559             CTLFLAG_RD, &stats->rx_csum_failed, 0,
2560             "Received buffer checksum offload failed");
2561         SYSCTL_ADD_UQUAD(ctx, child, OID_AUTO, "rx_csum_offloaded",
2562             CTLFLAG_RD, &stats->rx_csum_offloaded, 0,
2563             "Received buffer checksum offload succeeded");
2564         SYSCTL_ADD_UQUAD(ctx, child, OID_AUTO, "rx_task_rescheduled",
2565             CTLFLAG_RD, &stats->rx_task_rescheduled, 0,
2566             "Times the receive interrupt task rescheduled itself");
2567
2568         SYSCTL_ADD_UQUAD(ctx, child, OID_AUTO, "tx_csum_bad_ethtype",
2569             CTLFLAG_RD, &stats->tx_csum_bad_ethtype, 0,
2570             "Aborted transmit of checksum offloaded buffer with unknown "
2571             "Ethernet type");
2572         SYSCTL_ADD_UQUAD(ctx, child, OID_AUTO, "tx_tso_bad_ethtype",
2573             CTLFLAG_RD, &stats->tx_tso_bad_ethtype, 0,
2574             "Aborted transmit of TSO buffer with unknown Ethernet type");
2575         SYSCTL_ADD_UQUAD(ctx, child, OID_AUTO, "tx_defragged",
2576             CTLFLAG_RD, &stats->tx_defragged, 0,
2577             "Transmit mbufs defragged");
2578         SYSCTL_ADD_UQUAD(ctx, child, OID_AUTO, "tx_defrag_failed",
2579             CTLFLAG_RD, &stats->tx_defrag_failed, 0,
2580             "Aborted transmit of buffer because defrag failed");
2581         SYSCTL_ADD_UQUAD(ctx, child, OID_AUTO, "tx_csum_offloaded",
2582             CTLFLAG_RD, &stats->tx_csum_offloaded, 0,
2583             "Offloaded checksum of transmitted buffer");
2584         SYSCTL_ADD_UQUAD(ctx, child, OID_AUTO, "tx_tso_offloaded",
2585             CTLFLAG_RD, &stats->tx_tso_offloaded, 0,
2586             "Segmentation offload of transmitted buffer");
2587         SYSCTL_ADD_UQUAD(ctx, child, OID_AUTO, "tx_task_rescheduled",
2588             CTLFLAG_RD, &stats->tx_task_rescheduled, 0,
2589             "Times the transmit interrupt task rescheduled itself");
2590 }
2591
2592 static int
2593 vtnet_enable_rx_intr(struct vtnet_softc *sc)
2594 {
2595
2596         return (virtqueue_enable_intr(sc->vtnet_rx_vq));
2597 }
2598
2599 static void
2600 vtnet_disable_rx_intr(struct vtnet_softc *sc)
2601 {
2602
2603         virtqueue_disable_intr(sc->vtnet_rx_vq);
2604 }
2605
2606 static int
2607 vtnet_enable_tx_intr(struct vtnet_softc *sc)
2608 {
2609
2610 #ifdef VTNET_TX_INTR_MODERATION
2611         return (0);
2612 #else
2613         return (virtqueue_enable_intr(sc->vtnet_tx_vq));
2614 #endif
2615 }
2616
2617 static void
2618 vtnet_disable_tx_intr(struct vtnet_softc *sc)
2619 {
2620
2621         virtqueue_disable_intr(sc->vtnet_tx_vq);
2622 }