xref: /freebsd-12.1/sys/dev/netmap/if_ptnet.c (revision 185aba2d)
1 /*-
2  * Copyright (c) 2016, Vincenzo Maffione
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  * $FreeBSD$
27  */
28 
29 /* Driver for ptnet paravirtualized network device. */
30 
31 #include <sys/cdefs.h>
32 
33 #include <sys/types.h>
34 #include <sys/param.h>
35 #include <sys/systm.h>
36 #include <sys/kernel.h>
37 #include <sys/sockio.h>
38 #include <sys/mbuf.h>
39 #include <sys/malloc.h>
40 #include <sys/module.h>
41 #include <sys/socket.h>
42 #include <sys/sysctl.h>
43 #include <sys/lock.h>
44 #include <sys/mutex.h>
45 #include <sys/taskqueue.h>
46 #include <sys/smp.h>
47 #include <sys/time.h>
48 #include <machine/smp.h>
49 
50 #include <vm/uma.h>
51 #include <vm/vm.h>
52 #include <vm/pmap.h>
53 
54 #include <net/ethernet.h>
55 #include <net/if.h>
56 #include <net/if_var.h>
57 #include <net/if_arp.h>
58 #include <net/if_dl.h>
59 #include <net/if_types.h>
60 #include <net/if_media.h>
61 #include <net/if_vlan_var.h>
62 #include <net/bpf.h>
63 
64 #include <netinet/in_systm.h>
65 #include <netinet/in.h>
66 #include <netinet/ip.h>
67 #include <netinet/ip6.h>
68 #include <netinet6/ip6_var.h>
69 #include <netinet/udp.h>
70 #include <netinet/tcp.h>
71 #include <netinet/sctp.h>
72 
73 #include <machine/bus.h>
74 #include <machine/resource.h>
75 #include <sys/bus.h>
76 #include <sys/rman.h>
77 
78 #include <dev/pci/pcivar.h>
79 #include <dev/pci/pcireg.h>
80 
81 #include "opt_inet.h"
82 #include "opt_inet6.h"
83 
84 #include <sys/selinfo.h>
85 #include <net/netmap.h>
86 #include <dev/netmap/netmap_kern.h>
87 #include <net/netmap_virt.h>
88 #include <dev/netmap/netmap_mem2.h>
89 #include <dev/virtio/network/virtio_net.h>
90 
91 #ifndef INET
92 #error "INET not defined, cannot support offloadings"
93 #endif
94 
95 #if __FreeBSD_version >= 1100000
96 static uint64_t	ptnet_get_counter(if_t, ift_counter);
97 #else
98 typedef struct ifnet *if_t;
99 #define if_getsoftc(_ifp)   (_ifp)->if_softc
100 #endif
101 
102 //#define PTNETMAP_STATS
103 //#define DEBUG
104 #ifdef DEBUG
105 #define DBG(x) x
106 #else   /* !DEBUG */
107 #define DBG(x)
108 #endif  /* !DEBUG */
109 
110 extern int ptnet_vnet_hdr; /* Tunable parameter */
111 
112 struct ptnet_softc;
113 
114 struct ptnet_queue_stats {
115 	uint64_t	packets; /* if_[io]packets */
116 	uint64_t	bytes;	 /* if_[io]bytes */
117 	uint64_t	errors;	 /* if_[io]errors */
118 	uint64_t	iqdrops; /* if_iqdrops */
119 	uint64_t	mcasts;  /* if_[io]mcasts */
120 #ifdef PTNETMAP_STATS
121 	uint64_t	intrs;
122 	uint64_t	kicks;
123 #endif /* PTNETMAP_STATS */
124 };
125 
126 struct ptnet_queue {
127 	struct ptnet_softc		*sc;
128 	struct				resource *irq;
129 	void				*cookie;
130 	int				kring_id;
131 	struct ptnet_csb_gh		*ptgh;
132 	struct ptnet_csb_hg		*pthg;
133 	unsigned int			kick;
134 	struct mtx			lock;
135 	struct buf_ring			*bufring; /* for TX queues */
136 	struct ptnet_queue_stats	stats;
137 #ifdef PTNETMAP_STATS
138 	struct ptnet_queue_stats	last_stats;
139 #endif /* PTNETMAP_STATS */
140 	struct taskqueue		*taskq;
141 	struct task			task;
142 	char				lock_name[16];
143 };
144 
145 #define PTNET_Q_LOCK(_pq)	mtx_lock(&(_pq)->lock)
146 #define PTNET_Q_TRYLOCK(_pq)	mtx_trylock(&(_pq)->lock)
147 #define PTNET_Q_UNLOCK(_pq)	mtx_unlock(&(_pq)->lock)
148 
149 struct ptnet_softc {
150 	device_t		dev;
151 	if_t			ifp;
152 	struct ifmedia		media;
153 	struct mtx		lock;
154 	char			lock_name[16];
155 	char			hwaddr[ETHER_ADDR_LEN];
156 
157 	/* Mirror of PTFEAT register. */
158 	uint32_t		ptfeatures;
159 	unsigned int		vnet_hdr_len;
160 
161 	/* PCI BARs support. */
162 	struct resource		*iomem;
163 	struct resource		*msix_mem;
164 
165 	unsigned int		num_rings;
166 	unsigned int		num_tx_rings;
167 	struct ptnet_queue	*queues;
168 	struct ptnet_queue	*rxqueues;
169 	struct ptnet_csb_gh    *csb_gh;
170 	struct ptnet_csb_hg    *csb_hg;
171 
172 	unsigned int		min_tx_space;
173 
174 	struct netmap_pt_guest_adapter *ptna;
175 
176 	struct callout		tick;
177 #ifdef PTNETMAP_STATS
178 	struct timeval		last_ts;
179 #endif /* PTNETMAP_STATS */
180 };
181 
182 #define PTNET_CORE_LOCK(_sc)	mtx_lock(&(_sc)->lock)
183 #define PTNET_CORE_UNLOCK(_sc)	mtx_unlock(&(_sc)->lock)
184 
185 static int	ptnet_probe(device_t);
186 static int	ptnet_attach(device_t);
187 static int	ptnet_detach(device_t);
188 static int	ptnet_suspend(device_t);
189 static int	ptnet_resume(device_t);
190 static int	ptnet_shutdown(device_t);
191 
192 static void	ptnet_init(void *opaque);
193 static int	ptnet_ioctl(if_t ifp, u_long cmd, caddr_t data);
194 static int	ptnet_init_locked(struct ptnet_softc *sc);
195 static int	ptnet_stop(struct ptnet_softc *sc);
196 static int	ptnet_transmit(if_t ifp, struct mbuf *m);
197 static int	ptnet_drain_transmit_queue(struct ptnet_queue *pq,
198 					   unsigned int budget,
199 					   bool may_resched);
200 static void	ptnet_qflush(if_t ifp);
201 static void	ptnet_tx_task(void *context, int pending);
202 
203 static int	ptnet_media_change(if_t ifp);
204 static void	ptnet_media_status(if_t ifp, struct ifmediareq *ifmr);
205 #ifdef PTNETMAP_STATS
206 static void	ptnet_tick(void *opaque);
207 #endif
208 
209 static int	ptnet_irqs_init(struct ptnet_softc *sc);
210 static void	ptnet_irqs_fini(struct ptnet_softc *sc);
211 
212 static uint32_t ptnet_nm_ptctl(if_t ifp, uint32_t cmd);
213 static int	ptnet_nm_config(struct netmap_adapter *na, unsigned *txr,
214 				unsigned *txd, unsigned *rxr, unsigned *rxd);
215 static void	ptnet_update_vnet_hdr(struct ptnet_softc *sc);
216 static int	ptnet_nm_register(struct netmap_adapter *na, int onoff);
217 static int	ptnet_nm_txsync(struct netmap_kring *kring, int flags);
218 static int	ptnet_nm_rxsync(struct netmap_kring *kring, int flags);
219 static void	ptnet_nm_intr(struct netmap_adapter *na, int onoff);
220 
221 static void	ptnet_tx_intr(void *opaque);
222 static void	ptnet_rx_intr(void *opaque);
223 
224 static unsigned	ptnet_rx_discard(struct netmap_kring *kring,
225 				 unsigned int head);
226 static int	ptnet_rx_eof(struct ptnet_queue *pq, unsigned int budget,
227 			     bool may_resched);
228 static void	ptnet_rx_task(void *context, int pending);
229 
230 #ifdef DEVICE_POLLING
231 static poll_handler_t ptnet_poll;
232 #endif
233 
234 static device_method_t ptnet_methods[] = {
235 	DEVMETHOD(device_probe,			ptnet_probe),
236 	DEVMETHOD(device_attach,		ptnet_attach),
237 	DEVMETHOD(device_detach,		ptnet_detach),
238 	DEVMETHOD(device_suspend,		ptnet_suspend),
239 	DEVMETHOD(device_resume,		ptnet_resume),
240 	DEVMETHOD(device_shutdown,		ptnet_shutdown),
241 	DEVMETHOD_END
242 };
243 
244 static driver_t ptnet_driver = {
245 	"ptnet",
246 	ptnet_methods,
247 	sizeof(struct ptnet_softc)
248 };
249 
250 /* We use (SI_ORDER_MIDDLE+2) here, see DEV_MODULE_ORDERED() invocation. */
251 static devclass_t ptnet_devclass;
252 DRIVER_MODULE_ORDERED(ptnet, pci, ptnet_driver, ptnet_devclass,
253 		      NULL, NULL, SI_ORDER_MIDDLE + 2);
254 
255 static int
256 ptnet_probe(device_t dev)
257 {
258 	if (pci_get_vendor(dev) != PTNETMAP_PCI_VENDOR_ID ||
259 		pci_get_device(dev) != PTNETMAP_PCI_NETIF_ID) {
260 		return (ENXIO);
261 	}
262 
263 	device_set_desc(dev, "ptnet network adapter");
264 
265 	return (BUS_PROBE_DEFAULT);
266 }
267 
268 static inline void ptnet_kick(struct ptnet_queue *pq)
269 {
270 #ifdef PTNETMAP_STATS
271 	pq->stats.kicks ++;
272 #endif /* PTNETMAP_STATS */
273 	bus_write_4(pq->sc->iomem, pq->kick, 0);
274 }
275 
276 #define PTNET_BUF_RING_SIZE	4096
277 #define PTNET_RX_BUDGET		512
278 #define PTNET_RX_BATCH		1
279 #define PTNET_TX_BUDGET		512
280 #define PTNET_TX_BATCH		64
281 #define PTNET_HDR_SIZE		sizeof(struct virtio_net_hdr_mrg_rxbuf)
282 #define PTNET_MAX_PKT_SIZE	65536
283 
284 #define PTNET_CSUM_OFFLOAD	(CSUM_TCP | CSUM_UDP | CSUM_SCTP)
285 #define PTNET_CSUM_OFFLOAD_IPV6	(CSUM_TCP_IPV6 | CSUM_UDP_IPV6 |\
286 				 CSUM_SCTP_IPV6)
287 #define PTNET_ALL_OFFLOAD	(CSUM_TSO | PTNET_CSUM_OFFLOAD |\
288 				 PTNET_CSUM_OFFLOAD_IPV6)
289 
290 static int
291 ptnet_attach(device_t dev)
292 {
293 	uint32_t ptfeatures = 0;
294 	unsigned int num_rx_rings, num_tx_rings;
295 	struct netmap_adapter na_arg;
296 	unsigned int nifp_offset;
297 	struct ptnet_softc *sc;
298 	if_t ifp;
299 	uint32_t macreg;
300 	int err, rid;
301 	int i;
302 
303 	sc = device_get_softc(dev);
304 	sc->dev = dev;
305 
306 	/* Setup PCI resources. */
307 	pci_enable_busmaster(dev);
308 
309 	rid = PCIR_BAR(PTNETMAP_IO_PCI_BAR);
310 	sc->iomem = bus_alloc_resource_any(dev, SYS_RES_IOPORT, &rid,
311 					   RF_ACTIVE);
312 	if (sc->iomem == NULL) {
313 		device_printf(dev, "Failed to map I/O BAR\n");
314 		return (ENXIO);
315 	}
316 
317 	/* Negotiate features with the hypervisor. */
318 	if (ptnet_vnet_hdr) {
319 		ptfeatures |= PTNETMAP_F_VNET_HDR;
320 	}
321 	bus_write_4(sc->iomem, PTNET_IO_PTFEAT, ptfeatures); /* wanted */
322 	ptfeatures = bus_read_4(sc->iomem, PTNET_IO_PTFEAT); /* acked */
323 	sc->ptfeatures = ptfeatures;
324 
325 	num_tx_rings = bus_read_4(sc->iomem, PTNET_IO_NUM_TX_RINGS);
326 	num_rx_rings = bus_read_4(sc->iomem, PTNET_IO_NUM_RX_RINGS);
327 	sc->num_rings = num_tx_rings + num_rx_rings;
328 	sc->num_tx_rings = num_tx_rings;
329 
330 	if (sc->num_rings * sizeof(struct ptnet_csb_gh) > PAGE_SIZE) {
331 		device_printf(dev, "CSB cannot handle that many rings (%u)\n",
332 				sc->num_rings);
333 		err = ENOMEM;
334 		goto err_path;
335 	}
336 
337 	/* Allocate CSB and carry out CSB allocation protocol. */
338 	sc->csb_gh = contigmalloc(2*PAGE_SIZE, M_DEVBUF, M_NOWAIT | M_ZERO,
339 				  (size_t)0, -1UL, PAGE_SIZE, 0);
340 	if (sc->csb_gh == NULL) {
341 		device_printf(dev, "Failed to allocate CSB\n");
342 		err = ENOMEM;
343 		goto err_path;
344 	}
345 	sc->csb_hg = (struct ptnet_csb_hg *)(((char *)sc->csb_gh) + PAGE_SIZE);
346 
347 	{
348 		/*
349 		 * We use uint64_t rather than vm_paddr_t since we
350 		 * need 64 bit addresses even on 32 bit platforms.
351 		 */
352 		uint64_t paddr = vtophys(sc->csb_gh);
353 
354 		/* CSB allocation protocol: write to BAH first, then
355 		 * to BAL (for both GH and HG sections). */
356 		bus_write_4(sc->iomem, PTNET_IO_CSB_GH_BAH,
357 				(paddr >> 32) & 0xffffffff);
358 		bus_write_4(sc->iomem, PTNET_IO_CSB_GH_BAL,
359 				paddr & 0xffffffff);
360 		paddr = vtophys(sc->csb_hg);
361 		bus_write_4(sc->iomem, PTNET_IO_CSB_HG_BAH,
362 				(paddr >> 32) & 0xffffffff);
363 		bus_write_4(sc->iomem, PTNET_IO_CSB_HG_BAL,
364 				paddr & 0xffffffff);
365 	}
366 
367 	/* Allocate and initialize per-queue data structures. */
368 	sc->queues = malloc(sizeof(struct ptnet_queue) * sc->num_rings,
369 			    M_DEVBUF, M_NOWAIT | M_ZERO);
370 	if (sc->queues == NULL) {
371 		err = ENOMEM;
372 		goto err_path;
373 	}
374 	sc->rxqueues = sc->queues + num_tx_rings;
375 
376 	for (i = 0; i < sc->num_rings; i++) {
377 		struct ptnet_queue *pq = sc->queues + i;
378 
379 		pq->sc = sc;
380 		pq->kring_id = i;
381 		pq->kick = PTNET_IO_KICK_BASE + 4 * i;
382 		pq->ptgh = sc->csb_gh + i;
383 		pq->pthg = sc->csb_hg + i;
384 		snprintf(pq->lock_name, sizeof(pq->lock_name), "%s-%d",
385 			 device_get_nameunit(dev), i);
386 		mtx_init(&pq->lock, pq->lock_name, NULL, MTX_DEF);
387 		if (i >= num_tx_rings) {
388 			/* RX queue: fix kring_id. */
389 			pq->kring_id -= num_tx_rings;
390 		} else {
391 			/* TX queue: allocate buf_ring. */
392 			pq->bufring = buf_ring_alloc(PTNET_BUF_RING_SIZE,
393 						M_DEVBUF, M_NOWAIT, &pq->lock);
394 			if (pq->bufring == NULL) {
395 				err = ENOMEM;
396 				goto err_path;
397 			}
398 		}
399 	}
400 
401 	sc->min_tx_space = 64; /* Safe initial value. */
402 
403 	err = ptnet_irqs_init(sc);
404 	if (err) {
405 		goto err_path;
406 	}
407 
408 	/* Setup Ethernet interface. */
409 	sc->ifp = ifp = if_alloc(IFT_ETHER);
410 	if (ifp == NULL) {
411 		device_printf(dev, "Failed to allocate ifnet\n");
412 		err = ENOMEM;
413 		goto err_path;
414 	}
415 
416 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
417 	ifp->if_baudrate = IF_Gbps(10);
418 	ifp->if_softc = sc;
419 	ifp->if_flags = IFF_BROADCAST | IFF_MULTICAST | IFF_SIMPLEX;
420 	ifp->if_init = ptnet_init;
421 	ifp->if_ioctl = ptnet_ioctl;
422 #if __FreeBSD_version >= 1100000
423 	ifp->if_get_counter = ptnet_get_counter;
424 #endif
425 	ifp->if_transmit = ptnet_transmit;
426 	ifp->if_qflush = ptnet_qflush;
427 
428 	ifmedia_init(&sc->media, IFM_IMASK, ptnet_media_change,
429 		     ptnet_media_status);
430 	ifmedia_add(&sc->media, IFM_ETHER | IFM_10G_T | IFM_FDX, 0, NULL);
431 	ifmedia_set(&sc->media, IFM_ETHER | IFM_10G_T | IFM_FDX);
432 
433 	macreg = bus_read_4(sc->iomem, PTNET_IO_MAC_HI);
434 	sc->hwaddr[0] = (macreg >> 8) & 0xff;
435 	sc->hwaddr[1] = macreg & 0xff;
436 	macreg = bus_read_4(sc->iomem, PTNET_IO_MAC_LO);
437 	sc->hwaddr[2] = (macreg >> 24) & 0xff;
438 	sc->hwaddr[3] = (macreg >> 16) & 0xff;
439 	sc->hwaddr[4] = (macreg >> 8) & 0xff;
440 	sc->hwaddr[5] = macreg & 0xff;
441 
442 	ether_ifattach(ifp, sc->hwaddr);
443 
444 	ifp->if_hdrlen = sizeof(struct ether_vlan_header);
445 	ifp->if_capabilities |= IFCAP_JUMBO_MTU | IFCAP_VLAN_MTU;
446 
447 	if (sc->ptfeatures & PTNETMAP_F_VNET_HDR) {
448 		/* Similarly to what the vtnet driver does, we can emulate
449 		 * VLAN offloadings by inserting and removing the 802.1Q
450 		 * header during transmit and receive. We are then able
451 		 * to do checksum offloading of VLAN frames. */
452 		ifp->if_capabilities |= IFCAP_HWCSUM | IFCAP_HWCSUM_IPV6
453 					| IFCAP_VLAN_HWCSUM
454 					| IFCAP_TSO | IFCAP_LRO
455 					| IFCAP_VLAN_HWTSO
456 					| IFCAP_VLAN_HWTAGGING;
457 	}
458 
459 	ifp->if_capenable = ifp->if_capabilities;
460 #ifdef DEVICE_POLLING
461 	/* Don't enable polling by default. */
462 	ifp->if_capabilities |= IFCAP_POLLING;
463 #endif
464 	snprintf(sc->lock_name, sizeof(sc->lock_name),
465 		 "%s", device_get_nameunit(dev));
466 	mtx_init(&sc->lock, sc->lock_name, "ptnet core lock", MTX_DEF);
467 	callout_init_mtx(&sc->tick, &sc->lock, 0);
468 
469 	/* Prepare a netmap_adapter struct instance to do netmap_attach(). */
470 	nifp_offset = bus_read_4(sc->iomem, PTNET_IO_NIFP_OFS);
471 	memset(&na_arg, 0, sizeof(na_arg));
472 	na_arg.ifp = ifp;
473 	na_arg.num_tx_desc = bus_read_4(sc->iomem, PTNET_IO_NUM_TX_SLOTS);
474 	na_arg.num_rx_desc = bus_read_4(sc->iomem, PTNET_IO_NUM_RX_SLOTS);
475 	na_arg.num_tx_rings = num_tx_rings;
476 	na_arg.num_rx_rings = num_rx_rings;
477 	na_arg.nm_config = ptnet_nm_config;
478 	na_arg.nm_krings_create = ptnet_nm_krings_create;
479 	na_arg.nm_krings_delete = ptnet_nm_krings_delete;
480 	na_arg.nm_dtor = ptnet_nm_dtor;
481 	na_arg.nm_intr = ptnet_nm_intr;
482 	na_arg.nm_register = ptnet_nm_register;
483 	na_arg.nm_txsync = ptnet_nm_txsync;
484 	na_arg.nm_rxsync = ptnet_nm_rxsync;
485 
486 	netmap_pt_guest_attach(&na_arg, nifp_offset,
487                                 bus_read_4(sc->iomem, PTNET_IO_HOSTMEMID));
488 
489 	/* Now a netmap adapter for this ifp has been allocated, and it
490 	 * can be accessed through NA(ifp). We also have to initialize the CSB
491 	 * pointer. */
492 	sc->ptna = (struct netmap_pt_guest_adapter *)NA(ifp);
493 
494 	/* If virtio-net header was negotiated, set the virt_hdr_len field in
495 	 * the netmap adapter, to inform users that this netmap adapter requires
496 	 * the application to deal with the headers. */
497 	ptnet_update_vnet_hdr(sc);
498 
499 	device_printf(dev, "%s() completed\n", __func__);
500 
501 	return (0);
502 
503 err_path:
504 	ptnet_detach(dev);
505 	return err;
506 }
507 
508 static int
509 ptnet_detach(device_t dev)
510 {
511 	struct ptnet_softc *sc = device_get_softc(dev);
512 	int i;
513 
514 #ifdef DEVICE_POLLING
515 	if (sc->ifp->if_capenable & IFCAP_POLLING) {
516 		ether_poll_deregister(sc->ifp);
517 	}
518 #endif
519 	callout_drain(&sc->tick);
520 
521 	if (sc->queues) {
522 		/* Drain taskqueues before calling if_detach. */
523 		for (i = 0; i < sc->num_rings; i++) {
524 			struct ptnet_queue *pq = sc->queues + i;
525 
526 			if (pq->taskq) {
527 				taskqueue_drain(pq->taskq, &pq->task);
528 			}
529 		}
530 	}
531 
532 	if (sc->ifp) {
533 		ether_ifdetach(sc->ifp);
534 
535 		/* Uninitialize netmap adapters for this device. */
536 		netmap_detach(sc->ifp);
537 
538 		ifmedia_removeall(&sc->media);
539 		if_free(sc->ifp);
540 		sc->ifp = NULL;
541 	}
542 
543 	ptnet_irqs_fini(sc);
544 
545 	if (sc->csb_gh) {
546 		bus_write_4(sc->iomem, PTNET_IO_CSB_GH_BAH, 0);
547 		bus_write_4(sc->iomem, PTNET_IO_CSB_GH_BAL, 0);
548 		bus_write_4(sc->iomem, PTNET_IO_CSB_HG_BAH, 0);
549 		bus_write_4(sc->iomem, PTNET_IO_CSB_HG_BAL, 0);
550 		contigfree(sc->csb_gh, 2*PAGE_SIZE, M_DEVBUF);
551 		sc->csb_gh = NULL;
552 		sc->csb_hg = NULL;
553 	}
554 
555 	if (sc->queues) {
556 		for (i = 0; i < sc->num_rings; i++) {
557 			struct ptnet_queue *pq = sc->queues + i;
558 
559 			if (mtx_initialized(&pq->lock)) {
560 				mtx_destroy(&pq->lock);
561 			}
562 			if (pq->bufring != NULL) {
563 				buf_ring_free(pq->bufring, M_DEVBUF);
564 			}
565 		}
566 		free(sc->queues, M_DEVBUF);
567 		sc->queues = NULL;
568 	}
569 
570 	if (sc->iomem) {
571 		bus_release_resource(dev, SYS_RES_IOPORT,
572 				     PCIR_BAR(PTNETMAP_IO_PCI_BAR), sc->iomem);
573 		sc->iomem = NULL;
574 	}
575 
576 	mtx_destroy(&sc->lock);
577 
578 	device_printf(dev, "%s() completed\n", __func__);
579 
580 	return (0);
581 }
582 
583 static int
584 ptnet_suspend(device_t dev)
585 {
586 	struct ptnet_softc *sc;
587 
588 	sc = device_get_softc(dev);
589 	(void)sc;
590 
591 	return (0);
592 }
593 
594 static int
595 ptnet_resume(device_t dev)
596 {
597 	struct ptnet_softc *sc;
598 
599 	sc = device_get_softc(dev);
600 	(void)sc;
601 
602 	return (0);
603 }
604 
605 static int
606 ptnet_shutdown(device_t dev)
607 {
608 	/*
609 	 * Suspend already does all of what we need to
610 	 * do here; we just never expect to be resumed.
611 	 */
612 	return (ptnet_suspend(dev));
613 }
614 
615 static int
616 ptnet_irqs_init(struct ptnet_softc *sc)
617 {
618 	int rid = PCIR_BAR(PTNETMAP_MSIX_PCI_BAR);
619 	int nvecs = sc->num_rings;
620 	device_t dev = sc->dev;
621 	int err = ENOSPC;
622 	int cpu_cur;
623 	int i;
624 
625 	if (pci_find_cap(dev, PCIY_MSIX, NULL) != 0)  {
626 		device_printf(dev, "Could not find MSI-X capability\n");
627 		return (ENXIO);
628 	}
629 
630 	sc->msix_mem = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
631 					      &rid, RF_ACTIVE);
632 	if (sc->msix_mem == NULL) {
633 		device_printf(dev, "Failed to allocate MSIX PCI BAR\n");
634 		return (ENXIO);
635 	}
636 
637 	if (pci_msix_count(dev) < nvecs) {
638 		device_printf(dev, "Not enough MSI-X vectors\n");
639 		goto err_path;
640 	}
641 
642 	err = pci_alloc_msix(dev, &nvecs);
643 	if (err) {
644 		device_printf(dev, "Failed to allocate MSI-X vectors\n");
645 		goto err_path;
646 	}
647 
648 	for (i = 0; i < nvecs; i++) {
649 		struct ptnet_queue *pq = sc->queues + i;
650 
651 		rid = i + 1;
652 		pq->irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid,
653 						 RF_ACTIVE);
654 		if (pq->irq == NULL) {
655 			device_printf(dev, "Failed to allocate interrupt "
656 					   "for queue #%d\n", i);
657 			err = ENOSPC;
658 			goto err_path;
659 		}
660 	}
661 
662 	cpu_cur = CPU_FIRST();
663 	for (i = 0; i < nvecs; i++) {
664 		struct ptnet_queue *pq = sc->queues + i;
665 		void (*handler)(void *) = ptnet_tx_intr;
666 
667 		if (i >= sc->num_tx_rings) {
668 			handler = ptnet_rx_intr;
669 		}
670 		err = bus_setup_intr(dev, pq->irq, INTR_TYPE_NET | INTR_MPSAFE,
671 				     NULL /* intr_filter */, handler,
672 				     pq, &pq->cookie);
673 		if (err) {
674 			device_printf(dev, "Failed to register intr handler "
675 					   "for queue #%d\n", i);
676 			goto err_path;
677 		}
678 
679 		bus_describe_intr(dev, pq->irq, pq->cookie, "q%d", i);
680 #if 0
681 		bus_bind_intr(sc->dev, pq->irq, cpu_cur);
682 #endif
683 		cpu_cur = CPU_NEXT(cpu_cur);
684 	}
685 
686 	device_printf(dev, "Allocated %d MSI-X vectors\n", nvecs);
687 
688 	cpu_cur = CPU_FIRST();
689 	for (i = 0; i < nvecs; i++) {
690 		struct ptnet_queue *pq = sc->queues + i;
691 		static void (*handler)(void *context, int pending);
692 
693 		handler = (i < sc->num_tx_rings) ? ptnet_tx_task : ptnet_rx_task;
694 
695 		TASK_INIT(&pq->task, 0, handler, pq);
696 		pq->taskq = taskqueue_create_fast("ptnet_queue", M_NOWAIT,
697 					taskqueue_thread_enqueue, &pq->taskq);
698 		taskqueue_start_threads(&pq->taskq, 1, PI_NET, "%s-pq-%d",
699 					device_get_nameunit(sc->dev), cpu_cur);
700 		cpu_cur = CPU_NEXT(cpu_cur);
701 	}
702 
703 	return 0;
704 err_path:
705 	ptnet_irqs_fini(sc);
706 	return err;
707 }
708 
709 static void
710 ptnet_irqs_fini(struct ptnet_softc *sc)
711 {
712 	device_t dev = sc->dev;
713 	int i;
714 
715 	for (i = 0; i < sc->num_rings; i++) {
716 		struct ptnet_queue *pq = sc->queues + i;
717 
718 		if (pq->taskq) {
719 			taskqueue_free(pq->taskq);
720 			pq->taskq = NULL;
721 		}
722 
723 		if (pq->cookie) {
724 			bus_teardown_intr(dev, pq->irq, pq->cookie);
725 			pq->cookie = NULL;
726 		}
727 
728 		if (pq->irq) {
729 			bus_release_resource(dev, SYS_RES_IRQ, i + 1, pq->irq);
730 			pq->irq = NULL;
731 		}
732 	}
733 
734 	if (sc->msix_mem) {
735 		pci_release_msi(dev);
736 
737 		bus_release_resource(dev, SYS_RES_MEMORY,
738 				     PCIR_BAR(PTNETMAP_MSIX_PCI_BAR),
739 				     sc->msix_mem);
740 		sc->msix_mem = NULL;
741 	}
742 }
743 
744 static void
745 ptnet_init(void *opaque)
746 {
747 	struct ptnet_softc *sc = opaque;
748 
749 	PTNET_CORE_LOCK(sc);
750 	ptnet_init_locked(sc);
751 	PTNET_CORE_UNLOCK(sc);
752 }
753 
754 static int
755 ptnet_ioctl(if_t ifp, u_long cmd, caddr_t data)
756 {
757 	struct ptnet_softc *sc = if_getsoftc(ifp);
758 	device_t dev = sc->dev;
759 	struct ifreq *ifr = (struct ifreq *)data;
760 	int mask, err = 0;
761 
762 	switch (cmd) {
763 	case SIOCSIFFLAGS:
764 		device_printf(dev, "SIOCSIFFLAGS %x\n", ifp->if_flags);
765 		PTNET_CORE_LOCK(sc);
766 		if (ifp->if_flags & IFF_UP) {
767 			/* Network stack wants the iff to be up. */
768 			err = ptnet_init_locked(sc);
769 		} else {
770 			/* Network stack wants the iff to be down. */
771 			err = ptnet_stop(sc);
772 		}
773 		/* We don't need to do nothing to support IFF_PROMISC,
774 		 * since that is managed by the backend port. */
775 		PTNET_CORE_UNLOCK(sc);
776 		break;
777 
778 	case SIOCSIFCAP:
779 		device_printf(dev, "SIOCSIFCAP %x %x\n",
780 			      ifr->ifr_reqcap, ifp->if_capenable);
781 		mask = ifr->ifr_reqcap ^ ifp->if_capenable;
782 #ifdef DEVICE_POLLING
783 		if (mask & IFCAP_POLLING) {
784 			struct ptnet_queue *pq;
785 			int i;
786 
787 			if (ifr->ifr_reqcap & IFCAP_POLLING) {
788 				err = ether_poll_register(ptnet_poll, ifp);
789 				if (err) {
790 					break;
791 				}
792 				/* Stop queues and sync with taskqueues. */
793 				ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
794 				for (i = 0; i < sc->num_rings; i++) {
795 					pq = sc-> queues + i;
796 					/* Make sure the worker sees the
797 					 * IFF_DRV_RUNNING down. */
798 					PTNET_Q_LOCK(pq);
799 					pq->ptgh->guest_need_kick = 0;
800 					PTNET_Q_UNLOCK(pq);
801 					/* Wait for rescheduling to finish. */
802 					if (pq->taskq) {
803 						taskqueue_drain(pq->taskq,
804 								&pq->task);
805 					}
806 				}
807 				ifp->if_drv_flags |= IFF_DRV_RUNNING;
808 			} else {
809 				err = ether_poll_deregister(ifp);
810 				for (i = 0; i < sc->num_rings; i++) {
811 					pq = sc-> queues + i;
812 					PTNET_Q_LOCK(pq);
813 					pq->ptgh->guest_need_kick = 1;
814 					PTNET_Q_UNLOCK(pq);
815 				}
816 			}
817 		}
818 #endif  /* DEVICE_POLLING */
819 		ifp->if_capenable = ifr->ifr_reqcap;
820 		break;
821 
822 	case SIOCSIFMTU:
823 		/* We support any reasonable MTU. */
824 		if (ifr->ifr_mtu < ETHERMIN ||
825 				ifr->ifr_mtu > PTNET_MAX_PKT_SIZE) {
826 			err = EINVAL;
827 		} else {
828 			PTNET_CORE_LOCK(sc);
829 			ifp->if_mtu = ifr->ifr_mtu;
830 			PTNET_CORE_UNLOCK(sc);
831 		}
832 		break;
833 
834 	case SIOCSIFMEDIA:
835 	case SIOCGIFMEDIA:
836 		err = ifmedia_ioctl(ifp, ifr, &sc->media, cmd);
837 		break;
838 
839 	default:
840 		err = ether_ioctl(ifp, cmd, data);
841 		break;
842 	}
843 
844 	return err;
845 }
846 
847 static int
848 ptnet_init_locked(struct ptnet_softc *sc)
849 {
850 	if_t ifp = sc->ifp;
851 	struct netmap_adapter *na_dr = &sc->ptna->dr.up;
852 	struct netmap_adapter *na_nm = &sc->ptna->hwup.up;
853 	unsigned int nm_buf_size;
854 	int ret;
855 
856 	if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
857 		return 0; /* nothing to do */
858 	}
859 
860 	device_printf(sc->dev, "%s\n", __func__);
861 
862 	/* Translate offload capabilities according to if_capenable. */
863 	ifp->if_hwassist = 0;
864 	if (ifp->if_capenable & IFCAP_TXCSUM)
865 		ifp->if_hwassist |= PTNET_CSUM_OFFLOAD;
866 	if (ifp->if_capenable & IFCAP_TXCSUM_IPV6)
867 		ifp->if_hwassist |= PTNET_CSUM_OFFLOAD_IPV6;
868 	if (ifp->if_capenable & IFCAP_TSO4)
869 		ifp->if_hwassist |= CSUM_IP_TSO;
870 	if (ifp->if_capenable & IFCAP_TSO6)
871 		ifp->if_hwassist |= CSUM_IP6_TSO;
872 
873 	/*
874 	 * Prepare the interface for netmap mode access.
875 	 */
876 	netmap_update_config(na_dr);
877 
878 	ret = netmap_mem_finalize(na_dr->nm_mem, na_dr);
879 	if (ret) {
880 		device_printf(sc->dev, "netmap_mem_finalize() failed\n");
881 		return ret;
882 	}
883 
884 	if (sc->ptna->backend_regifs == 0) {
885 		ret = ptnet_nm_krings_create(na_nm);
886 		if (ret) {
887 			device_printf(sc->dev, "ptnet_nm_krings_create() "
888 					       "failed\n");
889 			goto err_mem_finalize;
890 		}
891 
892 		ret = netmap_mem_rings_create(na_dr);
893 		if (ret) {
894 			device_printf(sc->dev, "netmap_mem_rings_create() "
895 					       "failed\n");
896 			goto err_rings_create;
897 		}
898 
899 		ret = netmap_mem_get_lut(na_dr->nm_mem, &na_dr->na_lut);
900 		if (ret) {
901 			device_printf(sc->dev, "netmap_mem_get_lut() "
902 					       "failed\n");
903 			goto err_get_lut;
904 		}
905 	}
906 
907 	ret = ptnet_nm_register(na_dr, 1 /* on */);
908 	if (ret) {
909 		goto err_register;
910 	}
911 
912 	nm_buf_size = NETMAP_BUF_SIZE(na_dr);
913 
914 	KASSERT(nm_buf_size > 0, ("Invalid netmap buffer size"));
915 	sc->min_tx_space = PTNET_MAX_PKT_SIZE / nm_buf_size + 2;
916 	device_printf(sc->dev, "%s: min_tx_space = %u\n", __func__,
917 		      sc->min_tx_space);
918 #ifdef PTNETMAP_STATS
919 	callout_reset(&sc->tick, hz, ptnet_tick, sc);
920 #endif
921 
922 	ifp->if_drv_flags |= IFF_DRV_RUNNING;
923 
924 	return 0;
925 
926 err_register:
927 	memset(&na_dr->na_lut, 0, sizeof(na_dr->na_lut));
928 err_get_lut:
929 	netmap_mem_rings_delete(na_dr);
930 err_rings_create:
931 	ptnet_nm_krings_delete(na_nm);
932 err_mem_finalize:
933 	netmap_mem_deref(na_dr->nm_mem, na_dr);
934 
935 	return ret;
936 }
937 
938 /* To be called under core lock. */
939 static int
940 ptnet_stop(struct ptnet_softc *sc)
941 {
942 	if_t ifp = sc->ifp;
943 	struct netmap_adapter *na_dr = &sc->ptna->dr.up;
944 	struct netmap_adapter *na_nm = &sc->ptna->hwup.up;
945 	int i;
946 
947 	device_printf(sc->dev, "%s\n", __func__);
948 
949 	if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
950 		return 0; /* nothing to do */
951 	}
952 
953 	/* Clear the driver-ready flag, and synchronize with all the queues,
954 	 * so that after this loop we are sure nobody is working anymore with
955 	 * the device. This scheme is taken from the vtnet driver. */
956 	ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
957 	callout_stop(&sc->tick);
958 	for (i = 0; i < sc->num_rings; i++) {
959 		PTNET_Q_LOCK(sc->queues + i);
960 		PTNET_Q_UNLOCK(sc->queues + i);
961 	}
962 
963 	ptnet_nm_register(na_dr, 0 /* off */);
964 
965 	if (sc->ptna->backend_regifs == 0) {
966 		netmap_mem_rings_delete(na_dr);
967 		ptnet_nm_krings_delete(na_nm);
968 	}
969 	netmap_mem_deref(na_dr->nm_mem, na_dr);
970 
971 	return 0;
972 }
973 
974 static void
975 ptnet_qflush(if_t ifp)
976 {
977 	struct ptnet_softc *sc = if_getsoftc(ifp);
978 	int i;
979 
980 	/* Flush all the bufrings and do the interface flush. */
981 	for (i = 0; i < sc->num_rings; i++) {
982 		struct ptnet_queue *pq = sc->queues + i;
983 		struct mbuf *m;
984 
985 		PTNET_Q_LOCK(pq);
986 		if (pq->bufring) {
987 			while ((m = buf_ring_dequeue_sc(pq->bufring))) {
988 				m_freem(m);
989 			}
990 		}
991 		PTNET_Q_UNLOCK(pq);
992 	}
993 
994 	if_qflush(ifp);
995 }
996 
997 static int
998 ptnet_media_change(if_t ifp)
999 {
1000 	struct ptnet_softc *sc = if_getsoftc(ifp);
1001 	struct ifmedia *ifm = &sc->media;
1002 
1003 	if (IFM_TYPE(ifm->ifm_media) != IFM_ETHER) {
1004 		return EINVAL;
1005 	}
1006 
1007 	return 0;
1008 }
1009 
1010 #if __FreeBSD_version >= 1100000
1011 static uint64_t
1012 ptnet_get_counter(if_t ifp, ift_counter cnt)
1013 {
1014 	struct ptnet_softc *sc = if_getsoftc(ifp);
1015 	struct ptnet_queue_stats stats[2];
1016 	int i;
1017 
1018 	/* Accumulate statistics over the queues. */
1019 	memset(stats, 0, sizeof(stats));
1020 	for (i = 0; i < sc->num_rings; i++) {
1021 		struct ptnet_queue *pq = sc->queues + i;
1022 		int idx = (i < sc->num_tx_rings) ? 0 : 1;
1023 
1024 		stats[idx].packets	+= pq->stats.packets;
1025 		stats[idx].bytes	+= pq->stats.bytes;
1026 		stats[idx].errors	+= pq->stats.errors;
1027 		stats[idx].iqdrops	+= pq->stats.iqdrops;
1028 		stats[idx].mcasts	+= pq->stats.mcasts;
1029 	}
1030 
1031 	switch (cnt) {
1032 	case IFCOUNTER_IPACKETS:
1033 		return (stats[1].packets);
1034 	case IFCOUNTER_IQDROPS:
1035 		return (stats[1].iqdrops);
1036 	case IFCOUNTER_IERRORS:
1037 		return (stats[1].errors);
1038 	case IFCOUNTER_OPACKETS:
1039 		return (stats[0].packets);
1040 	case IFCOUNTER_OBYTES:
1041 		return (stats[0].bytes);
1042 	case IFCOUNTER_OMCASTS:
1043 		return (stats[0].mcasts);
1044 	default:
1045 		return (if_get_counter_default(ifp, cnt));
1046 	}
1047 }
1048 #endif
1049 
1050 
1051 #ifdef PTNETMAP_STATS
1052 /* Called under core lock. */
1053 static void
1054 ptnet_tick(void *opaque)
1055 {
1056 	struct ptnet_softc *sc = opaque;
1057 	int i;
1058 
1059 	for (i = 0; i < sc->num_rings; i++) {
1060 		struct ptnet_queue *pq = sc->queues + i;
1061 		struct ptnet_queue_stats cur = pq->stats;
1062 		struct timeval now;
1063 		unsigned int delta;
1064 
1065 		microtime(&now);
1066 		delta = now.tv_usec - sc->last_ts.tv_usec +
1067 			(now.tv_sec - sc->last_ts.tv_sec) * 1000000;
1068 		delta /= 1000; /* in milliseconds */
1069 
1070 		if (delta == 0)
1071 			continue;
1072 
1073 		device_printf(sc->dev, "#%d[%u ms]:pkts %lu, kicks %lu, "
1074 			      "intr %lu\n", i, delta,
1075 			      (cur.packets - pq->last_stats.packets),
1076 			      (cur.kicks - pq->last_stats.kicks),
1077 			      (cur.intrs - pq->last_stats.intrs));
1078 		pq->last_stats = cur;
1079 	}
1080 	microtime(&sc->last_ts);
1081 	callout_schedule(&sc->tick, hz);
1082 }
1083 #endif /* PTNETMAP_STATS */
1084 
1085 static void
1086 ptnet_media_status(if_t ifp, struct ifmediareq *ifmr)
1087 {
1088 	/* We are always active, as the backend netmap port is
1089 	 * always open in netmap mode. */
1090 	ifmr->ifm_status = IFM_AVALID | IFM_ACTIVE;
1091 	ifmr->ifm_active = IFM_ETHER | IFM_10G_T | IFM_FDX;
1092 }
1093 
1094 static uint32_t
1095 ptnet_nm_ptctl(if_t ifp, uint32_t cmd)
1096 {
1097 	struct ptnet_softc *sc = if_getsoftc(ifp);
1098 	/*
1099 	 * Write a command and read back error status,
1100 	 * with zero meaning success.
1101 	 */
1102 	bus_write_4(sc->iomem, PTNET_IO_PTCTL, cmd);
1103 	return bus_read_4(sc->iomem, PTNET_IO_PTCTL);
1104 }
1105 
1106 static int
1107 ptnet_nm_config(struct netmap_adapter *na, unsigned *txr, unsigned *txd,
1108 		unsigned *rxr, unsigned *rxd)
1109 {
1110 	struct ptnet_softc *sc = if_getsoftc(na->ifp);
1111 
1112 	*txr = bus_read_4(sc->iomem, PTNET_IO_NUM_TX_RINGS);
1113 	*rxr = bus_read_4(sc->iomem, PTNET_IO_NUM_RX_RINGS);
1114 	*txd = bus_read_4(sc->iomem, PTNET_IO_NUM_TX_SLOTS);
1115 	*rxd = bus_read_4(sc->iomem, PTNET_IO_NUM_RX_SLOTS);
1116 
1117 	device_printf(sc->dev, "txr %u, rxr %u, txd %u, rxd %u\n",
1118 		      *txr, *rxr, *txd, *rxd);
1119 
1120 	return 0;
1121 }
1122 
1123 static void
1124 ptnet_sync_from_csb(struct ptnet_softc *sc, struct netmap_adapter *na)
1125 {
1126 	int i;
1127 
1128 	/* Sync krings from the host, reading from
1129 	 * CSB. */
1130 	for (i = 0; i < sc->num_rings; i++) {
1131 		struct ptnet_csb_gh *ptgh = sc->queues[i].ptgh;
1132 		struct ptnet_csb_hg *pthg = sc->queues[i].pthg;
1133 		struct netmap_kring *kring;
1134 
1135 		if (i < na->num_tx_rings) {
1136 			kring = na->tx_rings + i;
1137 		} else {
1138 			kring = na->rx_rings + i - na->num_tx_rings;
1139 		}
1140 		kring->rhead = kring->ring->head = ptgh->head;
1141 		kring->rcur = kring->ring->cur = ptgh->cur;
1142 		kring->nr_hwcur = pthg->hwcur;
1143 		kring->nr_hwtail = kring->rtail =
1144 			kring->ring->tail = pthg->hwtail;
1145 
1146 		ND("%d,%d: csb {hc %u h %u c %u ht %u}", t, i,
1147 		   pthg->hwcur, ptgh->head, ptgh->cur,
1148 		   pthg->hwtail);
1149 		ND("%d,%d: kring {hc %u rh %u rc %u h %u c %u ht %u rt %u t %u}",
1150 		   t, i, kring->nr_hwcur, kring->rhead, kring->rcur,
1151 		   kring->ring->head, kring->ring->cur, kring->nr_hwtail,
1152 		   kring->rtail, kring->ring->tail);
1153 	}
1154 }
1155 
1156 static void
1157 ptnet_update_vnet_hdr(struct ptnet_softc *sc)
1158 {
1159 	unsigned int wanted_hdr_len = ptnet_vnet_hdr ? PTNET_HDR_SIZE : 0;
1160 
1161 	bus_write_4(sc->iomem, PTNET_IO_VNET_HDR_LEN, wanted_hdr_len);
1162 	sc->vnet_hdr_len = bus_read_4(sc->iomem, PTNET_IO_VNET_HDR_LEN);
1163 	sc->ptna->hwup.up.virt_hdr_len = sc->vnet_hdr_len;
1164 }
1165 
1166 static int
1167 ptnet_nm_register(struct netmap_adapter *na, int onoff)
1168 {
1169 	/* device-specific */
1170 	if_t ifp = na->ifp;
1171 	struct ptnet_softc *sc = if_getsoftc(ifp);
1172 	int native = (na == &sc->ptna->hwup.up);
1173 	struct ptnet_queue *pq;
1174 	enum txrx t;
1175 	int ret = 0;
1176 	int i;
1177 
1178 	if (!onoff) {
1179 		sc->ptna->backend_regifs--;
1180 	}
1181 
1182 	/* If this is the last netmap client, guest interrupt enable flags may
1183 	 * be in arbitrary state. Since these flags are going to be used also
1184 	 * by the netdevice driver, we have to make sure to start with
1185 	 * notifications enabled. Also, schedule NAPI to flush pending packets
1186 	 * in the RX rings, since we will not receive further interrupts
1187 	 * until these will be processed. */
1188 	if (native && !onoff && na->active_fds == 0) {
1189 		D("Exit netmap mode, re-enable interrupts");
1190 		for (i = 0; i < sc->num_rings; i++) {
1191 			pq = sc->queues + i;
1192 			pq->ptgh->guest_need_kick = 1;
1193 		}
1194 	}
1195 
1196 	if (onoff) {
1197 		if (sc->ptna->backend_regifs == 0) {
1198 			/* Initialize notification enable fields in the CSB. */
1199 			for (i = 0; i < sc->num_rings; i++) {
1200 				pq = sc->queues + i;
1201 				pq->pthg->host_need_kick = 1;
1202 				pq->ptgh->guest_need_kick =
1203 					(!(ifp->if_capenable & IFCAP_POLLING)
1204 						&& i >= sc->num_tx_rings);
1205 			}
1206 
1207 			/* Set the virtio-net header length. */
1208 			ptnet_update_vnet_hdr(sc);
1209 
1210 			/* Make sure the host adapter passed through is ready
1211 			 * for txsync/rxsync. */
1212 			ret = ptnet_nm_ptctl(ifp, PTNETMAP_PTCTL_CREATE);
1213 			if (ret) {
1214 				return ret;
1215 			}
1216 		}
1217 
1218 		/* Sync from CSB must be done after REGIF PTCTL. Skip this
1219 		 * step only if this is a netmap client and it is not the
1220 		 * first one. */
1221 		if ((!native && sc->ptna->backend_regifs == 0) ||
1222 				(native && na->active_fds == 0)) {
1223 			ptnet_sync_from_csb(sc, na);
1224 		}
1225 
1226 		/* If not native, don't call nm_set_native_flags, since we don't want
1227 		 * to replace if_transmit method, nor set NAF_NETMAP_ON */
1228 		if (native) {
1229 			for_rx_tx(t) {
1230 				for (i = 0; i <= nma_get_nrings(na, t); i++) {
1231 					struct netmap_kring *kring = &NMR(na, t)[i];
1232 
1233 					if (nm_kring_pending_on(kring)) {
1234 						kring->nr_mode = NKR_NETMAP_ON;
1235 					}
1236 				}
1237 			}
1238 			nm_set_native_flags(na);
1239 		}
1240 
1241 	} else {
1242 		if (native) {
1243 			nm_clear_native_flags(na);
1244 			for_rx_tx(t) {
1245 				for (i = 0; i <= nma_get_nrings(na, t); i++) {
1246 					struct netmap_kring *kring = &NMR(na, t)[i];
1247 
1248 					if (nm_kring_pending_off(kring)) {
1249 						kring->nr_mode = NKR_NETMAP_OFF;
1250 					}
1251 				}
1252 			}
1253 		}
1254 
1255 		/* Sync from CSB must be done before UNREGIF PTCTL, on the last
1256 		 * netmap client. */
1257 		if (native && na->active_fds == 0) {
1258 			ptnet_sync_from_csb(sc, na);
1259 		}
1260 
1261 		if (sc->ptna->backend_regifs == 0) {
1262 			ret = ptnet_nm_ptctl(ifp, PTNETMAP_PTCTL_DELETE);
1263 		}
1264 	}
1265 
1266 	if (onoff) {
1267 		sc->ptna->backend_regifs++;
1268 	}
1269 
1270 	return ret;
1271 }
1272 
1273 static int
1274 ptnet_nm_txsync(struct netmap_kring *kring, int flags)
1275 {
1276 	struct ptnet_softc *sc = if_getsoftc(kring->na->ifp);
1277 	struct ptnet_queue *pq = sc->queues + kring->ring_id;
1278 	bool notify;
1279 
1280 	notify = netmap_pt_guest_txsync(pq->ptgh, pq->pthg, kring, flags);
1281 	if (notify) {
1282 		ptnet_kick(pq);
1283 	}
1284 
1285 	return 0;
1286 }
1287 
1288 static int
1289 ptnet_nm_rxsync(struct netmap_kring *kring, int flags)
1290 {
1291 	struct ptnet_softc *sc = if_getsoftc(kring->na->ifp);
1292 	struct ptnet_queue *pq = sc->rxqueues + kring->ring_id;
1293 	bool notify;
1294 
1295 	notify = netmap_pt_guest_rxsync(pq->ptgh, pq->pthg, kring, flags);
1296 	if (notify) {
1297 		ptnet_kick(pq);
1298 	}
1299 
1300 	return 0;
1301 }
1302 
1303 static void
1304 ptnet_nm_intr(struct netmap_adapter *na, int onoff)
1305 {
1306 	struct ptnet_softc *sc = if_getsoftc(na->ifp);
1307 	int i;
1308 
1309 	for (i = 0; i < sc->num_rings; i++) {
1310 		struct ptnet_queue *pq = sc->queues + i;
1311 		pq->ptgh->guest_need_kick = onoff;
1312 	}
1313 }
1314 
1315 static void
1316 ptnet_tx_intr(void *opaque)
1317 {
1318 	struct ptnet_queue *pq = opaque;
1319 	struct ptnet_softc *sc = pq->sc;
1320 
1321 	DBG(device_printf(sc->dev, "Tx interrupt #%d\n", pq->kring_id));
1322 #ifdef PTNETMAP_STATS
1323 	pq->stats.intrs ++;
1324 #endif /* PTNETMAP_STATS */
1325 
1326 	if (netmap_tx_irq(sc->ifp, pq->kring_id) != NM_IRQ_PASS) {
1327 		return;
1328 	}
1329 
1330 	/* Schedule the tasqueue to flush process transmissions requests.
1331 	 * However, vtnet, if_em and if_igb just call ptnet_transmit() here,
1332 	 * at least when using MSI-X interrupts. The if_em driver, instead
1333 	 * schedule taskqueue when using legacy interrupts. */
1334 	taskqueue_enqueue(pq->taskq, &pq->task);
1335 }
1336 
1337 static void
1338 ptnet_rx_intr(void *opaque)
1339 {
1340 	struct ptnet_queue *pq = opaque;
1341 	struct ptnet_softc *sc = pq->sc;
1342 	unsigned int unused;
1343 
1344 	DBG(device_printf(sc->dev, "Rx interrupt #%d\n", pq->kring_id));
1345 #ifdef PTNETMAP_STATS
1346 	pq->stats.intrs ++;
1347 #endif /* PTNETMAP_STATS */
1348 
1349 	if (netmap_rx_irq(sc->ifp, pq->kring_id, &unused) != NM_IRQ_PASS) {
1350 		return;
1351 	}
1352 
1353 	/* Like vtnet, if_igb and if_em drivers when using MSI-X interrupts,
1354 	 * receive-side processing is executed directly in the interrupt
1355 	 * service routine. Alternatively, we may schedule the taskqueue. */
1356 	ptnet_rx_eof(pq, PTNET_RX_BUDGET, true);
1357 }
1358 
1359 /* The following offloadings-related functions are taken from the vtnet
1360  * driver, but the same functionality is required for the ptnet driver.
1361  * As a temporary solution, I copied this code from vtnet and I started
1362  * to generalize it (taking away driver-specific statistic accounting),
1363  * making as little modifications as possible.
1364  * In the future we need to share these functions between vtnet and ptnet.
1365  */
1366 static int
1367 ptnet_tx_offload_ctx(struct mbuf *m, int *etype, int *proto, int *start)
1368 {
1369 	struct ether_vlan_header *evh;
1370 	int offset;
1371 
1372 	evh = mtod(m, struct ether_vlan_header *);
1373 	if (evh->evl_encap_proto == htons(ETHERTYPE_VLAN)) {
1374 		/* BMV: We should handle nested VLAN tags too. */
1375 		*etype = ntohs(evh->evl_proto);
1376 		offset = sizeof(struct ether_vlan_header);
1377 	} else {
1378 		*etype = ntohs(evh->evl_encap_proto);
1379 		offset = sizeof(struct ether_header);
1380 	}
1381 
1382 	switch (*etype) {
1383 #if defined(INET)
1384 	case ETHERTYPE_IP: {
1385 		struct ip *ip, iphdr;
1386 		if (__predict_false(m->m_len < offset + sizeof(struct ip))) {
1387 			m_copydata(m, offset, sizeof(struct ip),
1388 			    (caddr_t) &iphdr);
1389 			ip = &iphdr;
1390 		} else
1391 			ip = (struct ip *)(m->m_data + offset);
1392 		*proto = ip->ip_p;
1393 		*start = offset + (ip->ip_hl << 2);
1394 		break;
1395 	}
1396 #endif
1397 #if defined(INET6)
1398 	case ETHERTYPE_IPV6:
1399 		*proto = -1;
1400 		*start = ip6_lasthdr(m, offset, IPPROTO_IPV6, proto);
1401 		/* Assert the network stack sent us a valid packet. */
1402 		KASSERT(*start > offset,
1403 		    ("%s: mbuf %p start %d offset %d proto %d", __func__, m,
1404 		    *start, offset, *proto));
1405 		break;
1406 #endif
1407 	default:
1408 		/* Here we should increment the tx_csum_bad_ethtype counter. */
1409 		return (EINVAL);
1410 	}
1411 
1412 	return (0);
1413 }
1414 
1415 static int
1416 ptnet_tx_offload_tso(if_t ifp, struct mbuf *m, int eth_type,
1417 		     int offset, bool allow_ecn, struct virtio_net_hdr *hdr)
1418 {
1419 	static struct timeval lastecn;
1420 	static int curecn;
1421 	struct tcphdr *tcp, tcphdr;
1422 
1423 	if (__predict_false(m->m_len < offset + sizeof(struct tcphdr))) {
1424 		m_copydata(m, offset, sizeof(struct tcphdr), (caddr_t) &tcphdr);
1425 		tcp = &tcphdr;
1426 	} else
1427 		tcp = (struct tcphdr *)(m->m_data + offset);
1428 
1429 	hdr->hdr_len = offset + (tcp->th_off << 2);
1430 	hdr->gso_size = m->m_pkthdr.tso_segsz;
1431 	hdr->gso_type = eth_type == ETHERTYPE_IP ? VIRTIO_NET_HDR_GSO_TCPV4 :
1432 	    VIRTIO_NET_HDR_GSO_TCPV6;
1433 
1434 	if (tcp->th_flags & TH_CWR) {
1435 		/*
1436 		 * Drop if VIRTIO_NET_F_HOST_ECN was not negotiated. In FreeBSD,
1437 		 * ECN support is not on a per-interface basis, but globally via
1438 		 * the net.inet.tcp.ecn.enable sysctl knob. The default is off.
1439 		 */
1440 		if (!allow_ecn) {
1441 			if (ppsratecheck(&lastecn, &curecn, 1))
1442 				if_printf(ifp,
1443 				    "TSO with ECN not negotiated with host\n");
1444 			return (ENOTSUP);
1445 		}
1446 		hdr->gso_type |= VIRTIO_NET_HDR_GSO_ECN;
1447 	}
1448 
1449 	/* Here we should increment tx_tso counter. */
1450 
1451 	return (0);
1452 }
1453 
1454 static struct mbuf *
1455 ptnet_tx_offload(if_t ifp, struct mbuf *m, bool allow_ecn,
1456 		 struct virtio_net_hdr *hdr)
1457 {
1458 	int flags, etype, csum_start, proto, error;
1459 
1460 	flags = m->m_pkthdr.csum_flags;
1461 
1462 	error = ptnet_tx_offload_ctx(m, &etype, &proto, &csum_start);
1463 	if (error)
1464 		goto drop;
1465 
1466 	if ((etype == ETHERTYPE_IP && flags & PTNET_CSUM_OFFLOAD) ||
1467 	    (etype == ETHERTYPE_IPV6 && flags & PTNET_CSUM_OFFLOAD_IPV6)) {
1468 		/*
1469 		 * We could compare the IP protocol vs the CSUM_ flag too,
1470 		 * but that really should not be necessary.
1471 		 */
1472 		hdr->flags |= VIRTIO_NET_HDR_F_NEEDS_CSUM;
1473 		hdr->csum_start = csum_start;
1474 		hdr->csum_offset = m->m_pkthdr.csum_data;
1475 		/* Here we should increment the tx_csum counter. */
1476 	}
1477 
1478 	if (flags & CSUM_TSO) {
1479 		if (__predict_false(proto != IPPROTO_TCP)) {
1480 			/* Likely failed to correctly parse the mbuf.
1481 			 * Here we should increment the tx_tso_not_tcp
1482 			 * counter. */
1483 			goto drop;
1484 		}
1485 
1486 		KASSERT(hdr->flags & VIRTIO_NET_HDR_F_NEEDS_CSUM,
1487 		    ("%s: mbuf %p TSO without checksum offload %#x",
1488 		    __func__, m, flags));
1489 
1490 		error = ptnet_tx_offload_tso(ifp, m, etype, csum_start,
1491 					     allow_ecn, hdr);
1492 		if (error)
1493 			goto drop;
1494 	}
1495 
1496 	return (m);
1497 
1498 drop:
1499 	m_freem(m);
1500 	return (NULL);
1501 }
1502 
1503 static void
1504 ptnet_vlan_tag_remove(struct mbuf *m)
1505 {
1506 	struct ether_vlan_header *evh;
1507 
1508 	evh = mtod(m, struct ether_vlan_header *);
1509 	m->m_pkthdr.ether_vtag = ntohs(evh->evl_tag);
1510 	m->m_flags |= M_VLANTAG;
1511 
1512 	/* Strip the 802.1Q header. */
1513 	bcopy((char *) evh, (char *) evh + ETHER_VLAN_ENCAP_LEN,
1514 	    ETHER_HDR_LEN - ETHER_TYPE_LEN);
1515 	m_adj(m, ETHER_VLAN_ENCAP_LEN);
1516 }
1517 
1518 /*
1519  * Use the checksum offset in the VirtIO header to set the
1520  * correct CSUM_* flags.
1521  */
1522 static int
1523 ptnet_rx_csum_by_offset(struct mbuf *m, uint16_t eth_type, int ip_start,
1524 			struct virtio_net_hdr *hdr)
1525 {
1526 #if defined(INET) || defined(INET6)
1527 	int offset = hdr->csum_start + hdr->csum_offset;
1528 #endif
1529 
1530 	/* Only do a basic sanity check on the offset. */
1531 	switch (eth_type) {
1532 #if defined(INET)
1533 	case ETHERTYPE_IP:
1534 		if (__predict_false(offset < ip_start + sizeof(struct ip)))
1535 			return (1);
1536 		break;
1537 #endif
1538 #if defined(INET6)
1539 	case ETHERTYPE_IPV6:
1540 		if (__predict_false(offset < ip_start + sizeof(struct ip6_hdr)))
1541 			return (1);
1542 		break;
1543 #endif
1544 	default:
1545 		/* Here we should increment the rx_csum_bad_ethtype counter. */
1546 		return (1);
1547 	}
1548 
1549 	/*
1550 	 * Use the offset to determine the appropriate CSUM_* flags. This is
1551 	 * a bit dirty, but we can get by with it since the checksum offsets
1552 	 * happen to be different. We assume the host host does not do IPv4
1553 	 * header checksum offloading.
1554 	 */
1555 	switch (hdr->csum_offset) {
1556 	case offsetof(struct udphdr, uh_sum):
1557 	case offsetof(struct tcphdr, th_sum):
1558 		m->m_pkthdr.csum_flags |= CSUM_DATA_VALID | CSUM_PSEUDO_HDR;
1559 		m->m_pkthdr.csum_data = 0xFFFF;
1560 		break;
1561 	case offsetof(struct sctphdr, checksum):
1562 		m->m_pkthdr.csum_flags |= CSUM_SCTP_VALID;
1563 		break;
1564 	default:
1565 		/* Here we should increment the rx_csum_bad_offset counter. */
1566 		return (1);
1567 	}
1568 
1569 	return (0);
1570 }
1571 
1572 static int
1573 ptnet_rx_csum_by_parse(struct mbuf *m, uint16_t eth_type, int ip_start,
1574 		       struct virtio_net_hdr *hdr)
1575 {
1576 	int offset, proto;
1577 
1578 	switch (eth_type) {
1579 #if defined(INET)
1580 	case ETHERTYPE_IP: {
1581 		struct ip *ip;
1582 		if (__predict_false(m->m_len < ip_start + sizeof(struct ip)))
1583 			return (1);
1584 		ip = (struct ip *)(m->m_data + ip_start);
1585 		proto = ip->ip_p;
1586 		offset = ip_start + (ip->ip_hl << 2);
1587 		break;
1588 	}
1589 #endif
1590 #if defined(INET6)
1591 	case ETHERTYPE_IPV6:
1592 		if (__predict_false(m->m_len < ip_start +
1593 		    sizeof(struct ip6_hdr)))
1594 			return (1);
1595 		offset = ip6_lasthdr(m, ip_start, IPPROTO_IPV6, &proto);
1596 		if (__predict_false(offset < 0))
1597 			return (1);
1598 		break;
1599 #endif
1600 	default:
1601 		/* Here we should increment the rx_csum_bad_ethtype counter. */
1602 		return (1);
1603 	}
1604 
1605 	switch (proto) {
1606 	case IPPROTO_TCP:
1607 		if (__predict_false(m->m_len < offset + sizeof(struct tcphdr)))
1608 			return (1);
1609 		m->m_pkthdr.csum_flags |= CSUM_DATA_VALID | CSUM_PSEUDO_HDR;
1610 		m->m_pkthdr.csum_data = 0xFFFF;
1611 		break;
1612 	case IPPROTO_UDP:
1613 		if (__predict_false(m->m_len < offset + sizeof(struct udphdr)))
1614 			return (1);
1615 		m->m_pkthdr.csum_flags |= CSUM_DATA_VALID | CSUM_PSEUDO_HDR;
1616 		m->m_pkthdr.csum_data = 0xFFFF;
1617 		break;
1618 	case IPPROTO_SCTP:
1619 		if (__predict_false(m->m_len < offset + sizeof(struct sctphdr)))
1620 			return (1);
1621 		m->m_pkthdr.csum_flags |= CSUM_SCTP_VALID;
1622 		break;
1623 	default:
1624 		/*
1625 		 * For the remaining protocols, FreeBSD does not support
1626 		 * checksum offloading, so the checksum will be recomputed.
1627 		 */
1628 #if 0
1629 		if_printf(ifp, "cksum offload of unsupported "
1630 		    "protocol eth_type=%#x proto=%d csum_start=%d "
1631 		    "csum_offset=%d\n", __func__, eth_type, proto,
1632 		    hdr->csum_start, hdr->csum_offset);
1633 #endif
1634 		break;
1635 	}
1636 
1637 	return (0);
1638 }
1639 
1640 /*
1641  * Set the appropriate CSUM_* flags. Unfortunately, the information
1642  * provided is not directly useful to us. The VirtIO header gives the
1643  * offset of the checksum, which is all Linux needs, but this is not
1644  * how FreeBSD does things. We are forced to peek inside the packet
1645  * a bit.
1646  *
1647  * It would be nice if VirtIO gave us the L4 protocol or if FreeBSD
1648  * could accept the offsets and let the stack figure it out.
1649  */
1650 static int
1651 ptnet_rx_csum(struct mbuf *m, struct virtio_net_hdr *hdr)
1652 {
1653 	struct ether_header *eh;
1654 	struct ether_vlan_header *evh;
1655 	uint16_t eth_type;
1656 	int offset, error;
1657 
1658 	eh = mtod(m, struct ether_header *);
1659 	eth_type = ntohs(eh->ether_type);
1660 	if (eth_type == ETHERTYPE_VLAN) {
1661 		/* BMV: We should handle nested VLAN tags too. */
1662 		evh = mtod(m, struct ether_vlan_header *);
1663 		eth_type = ntohs(evh->evl_proto);
1664 		offset = sizeof(struct ether_vlan_header);
1665 	} else
1666 		offset = sizeof(struct ether_header);
1667 
1668 	if (hdr->flags & VIRTIO_NET_HDR_F_NEEDS_CSUM)
1669 		error = ptnet_rx_csum_by_offset(m, eth_type, offset, hdr);
1670 	else
1671 		error = ptnet_rx_csum_by_parse(m, eth_type, offset, hdr);
1672 
1673 	return (error);
1674 }
1675 /* End of offloading-related functions to be shared with vtnet. */
1676 
1677 static inline void
1678 ptnet_sync_tail(struct ptnet_csb_hg *pthg, struct netmap_kring *kring)
1679 {
1680 	struct netmap_ring *ring = kring->ring;
1681 
1682 	/* Update hwcur and hwtail as known by the host. */
1683         ptnetmap_guest_read_kring_csb(pthg, kring);
1684 
1685 	/* nm_sync_finalize */
1686 	ring->tail = kring->rtail = kring->nr_hwtail;
1687 }
1688 
1689 static void
1690 ptnet_ring_update(struct ptnet_queue *pq, struct netmap_kring *kring,
1691 		  unsigned int head, unsigned int sync_flags)
1692 {
1693 	struct netmap_ring *ring = kring->ring;
1694 	struct ptnet_csb_gh *ptgh = pq->ptgh;
1695 	struct ptnet_csb_hg *pthg = pq->pthg;
1696 
1697 	/* Some packets have been pushed to the netmap ring. We have
1698 	 * to tell the host to process the new packets, updating cur
1699 	 * and head in the CSB. */
1700 	ring->head = ring->cur = head;
1701 
1702 	/* Mimic nm_txsync_prologue/nm_rxsync_prologue. */
1703 	kring->rcur = kring->rhead = head;
1704 
1705 	ptnetmap_guest_write_kring_csb(ptgh, kring->rcur, kring->rhead);
1706 
1707 	/* Kick the host if needed. */
1708 	if (NM_ACCESS_ONCE(pthg->host_need_kick)) {
1709 		ptgh->sync_flags = sync_flags;
1710 		ptnet_kick(pq);
1711 	}
1712 }
1713 
1714 #define PTNET_TX_NOSPACE(_h, _k, _min)	\
1715 	((((_h) < (_k)->rtail) ? 0 : (_k)->nkr_num_slots) + \
1716 		(_k)->rtail - (_h)) < (_min)
1717 
1718 /* This function may be called by the network stack, or by
1719  * by the taskqueue thread. */
1720 static int
1721 ptnet_drain_transmit_queue(struct ptnet_queue *pq, unsigned int budget,
1722 			   bool may_resched)
1723 {
1724 	struct ptnet_softc *sc = pq->sc;
1725 	bool have_vnet_hdr = sc->vnet_hdr_len;
1726 	struct netmap_adapter *na = &sc->ptna->dr.up;
1727 	if_t ifp = sc->ifp;
1728 	unsigned int batch_count = 0;
1729 	struct ptnet_csb_gh *ptgh;
1730 	struct ptnet_csb_hg *pthg;
1731 	struct netmap_kring *kring;
1732 	struct netmap_ring *ring;
1733 	struct netmap_slot *slot;
1734 	unsigned int count = 0;
1735 	unsigned int minspace;
1736 	unsigned int head;
1737 	unsigned int lim;
1738 	struct mbuf *mhead;
1739 	struct mbuf *mf;
1740 	int nmbuf_bytes;
1741 	uint8_t *nmbuf;
1742 
1743 	if (!PTNET_Q_TRYLOCK(pq)) {
1744 		/* We failed to acquire the lock, schedule the taskqueue. */
1745 		RD(1, "Deferring TX work");
1746 		if (may_resched) {
1747 			taskqueue_enqueue(pq->taskq, &pq->task);
1748 		}
1749 
1750 		return 0;
1751 	}
1752 
1753 	if (unlikely(!(ifp->if_drv_flags & IFF_DRV_RUNNING))) {
1754 		PTNET_Q_UNLOCK(pq);
1755 		RD(1, "Interface is down");
1756 		return ENETDOWN;
1757 	}
1758 
1759 	ptgh = pq->ptgh;
1760 	pthg = pq->pthg;
1761 	kring = na->tx_rings + pq->kring_id;
1762 	ring = kring->ring;
1763 	lim = kring->nkr_num_slots - 1;
1764 	head = ring->head;
1765 	minspace = sc->min_tx_space;
1766 
1767 	while (count < budget) {
1768 		if (PTNET_TX_NOSPACE(head, kring, minspace)) {
1769 			/* We ran out of slot, let's see if the host has
1770 			 * freed up some, by reading hwcur and hwtail from
1771 			 * the CSB. */
1772 			ptnet_sync_tail(pthg, kring);
1773 
1774 			if (PTNET_TX_NOSPACE(head, kring, minspace)) {
1775 				/* Still no slots available. Reactivate the
1776 				 * interrupts so that we can be notified
1777 				 * when some free slots are made available by
1778 				 * the host. */
1779 				ptgh->guest_need_kick = 1;
1780 
1781 				/* Double-check. */
1782 				ptnet_sync_tail(pthg, kring);
1783 				if (likely(PTNET_TX_NOSPACE(head, kring,
1784 							    minspace))) {
1785 					break;
1786 				}
1787 
1788 				RD(1, "Found more slots by doublecheck");
1789 				/* More slots were freed before reactivating
1790 				 * the interrupts. */
1791 				ptgh->guest_need_kick = 0;
1792 			}
1793 		}
1794 
1795 		mhead = drbr_peek(ifp, pq->bufring);
1796 		if (!mhead) {
1797 			break;
1798 		}
1799 
1800 		/* Initialize transmission state variables. */
1801 		slot = ring->slot + head;
1802 		nmbuf = NMB(na, slot);
1803 		nmbuf_bytes = 0;
1804 
1805 		/* If needed, prepare the virtio-net header at the beginning
1806 		 * of the first slot. */
1807 		if (have_vnet_hdr) {
1808 			struct virtio_net_hdr *vh =
1809 					(struct virtio_net_hdr *)nmbuf;
1810 
1811 			/* For performance, we could replace this memset() with
1812 			 * two 8-bytes-wide writes. */
1813 			memset(nmbuf, 0, PTNET_HDR_SIZE);
1814 			if (mhead->m_pkthdr.csum_flags & PTNET_ALL_OFFLOAD) {
1815 				mhead = ptnet_tx_offload(ifp, mhead, false,
1816 							 vh);
1817 				if (unlikely(!mhead)) {
1818 					/* Packet dropped because errors
1819 					 * occurred while preparing the vnet
1820 					 * header. Let's go ahead with the next
1821 					 * packet. */
1822 					pq->stats.errors ++;
1823 					drbr_advance(ifp, pq->bufring);
1824 					continue;
1825 				}
1826 			}
1827 			ND(1, "%s: [csum_flags %lX] vnet hdr: flags %x "
1828 			      "csum_start %u csum_ofs %u hdr_len = %u "
1829 			      "gso_size %u gso_type %x", __func__,
1830 			      mhead->m_pkthdr.csum_flags, vh->flags,
1831 			      vh->csum_start, vh->csum_offset, vh->hdr_len,
1832 			      vh->gso_size, vh->gso_type);
1833 
1834 			nmbuf += PTNET_HDR_SIZE;
1835 			nmbuf_bytes += PTNET_HDR_SIZE;
1836 		}
1837 
1838 		for (mf = mhead; mf; mf = mf->m_next) {
1839 			uint8_t *mdata = mf->m_data;
1840 			int mlen = mf->m_len;
1841 
1842 			for (;;) {
1843 				int copy = NETMAP_BUF_SIZE(na) - nmbuf_bytes;
1844 
1845 				if (mlen < copy) {
1846 					copy = mlen;
1847 				}
1848 				memcpy(nmbuf, mdata, copy);
1849 
1850 				mdata += copy;
1851 				mlen -= copy;
1852 				nmbuf += copy;
1853 				nmbuf_bytes += copy;
1854 
1855 				if (!mlen) {
1856 					break;
1857 				}
1858 
1859 				slot->len = nmbuf_bytes;
1860 				slot->flags = NS_MOREFRAG;
1861 
1862 				head = nm_next(head, lim);
1863 				KASSERT(head != ring->tail,
1864 					("Unexpectedly run out of TX space"));
1865 				slot = ring->slot + head;
1866 				nmbuf = NMB(na, slot);
1867 				nmbuf_bytes = 0;
1868 			}
1869 		}
1870 
1871 		/* Complete last slot and update head. */
1872 		slot->len = nmbuf_bytes;
1873 		slot->flags = 0;
1874 		head = nm_next(head, lim);
1875 
1876 		/* Consume the packet just processed. */
1877 		drbr_advance(ifp, pq->bufring);
1878 
1879 		/* Copy the packet to listeners. */
1880 		ETHER_BPF_MTAP(ifp, mhead);
1881 
1882 		pq->stats.packets ++;
1883 		pq->stats.bytes += mhead->m_pkthdr.len;
1884 		if (mhead->m_flags & M_MCAST) {
1885 			pq->stats.mcasts ++;
1886 		}
1887 
1888 		m_freem(mhead);
1889 
1890 		count ++;
1891 		if (++batch_count == PTNET_TX_BATCH) {
1892 			ptnet_ring_update(pq, kring, head, NAF_FORCE_RECLAIM);
1893 			batch_count = 0;
1894 		}
1895 	}
1896 
1897 	if (batch_count) {
1898 		ptnet_ring_update(pq, kring, head, NAF_FORCE_RECLAIM);
1899 	}
1900 
1901 	if (count >= budget && may_resched) {
1902 		DBG(RD(1, "out of budget: resched, %d mbufs pending\n",
1903 					drbr_inuse(ifp, pq->bufring)));
1904 		taskqueue_enqueue(pq->taskq, &pq->task);
1905 	}
1906 
1907 	PTNET_Q_UNLOCK(pq);
1908 
1909 	return count;
1910 }
1911 
1912 static int
1913 ptnet_transmit(if_t ifp, struct mbuf *m)
1914 {
1915 	struct ptnet_softc *sc = if_getsoftc(ifp);
1916 	struct ptnet_queue *pq;
1917 	unsigned int queue_idx;
1918 	int err;
1919 
1920 	DBG(device_printf(sc->dev, "transmit %p\n", m));
1921 
1922 	/* Insert 802.1Q header if needed. */
1923 	if (m->m_flags & M_VLANTAG) {
1924 		m = ether_vlanencap(m, m->m_pkthdr.ether_vtag);
1925 		if (m == NULL) {
1926 			return ENOBUFS;
1927 		}
1928 		m->m_flags &= ~M_VLANTAG;
1929 	}
1930 
1931 	/* Get the flow-id if available. */
1932 	queue_idx = (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE) ?
1933 		    m->m_pkthdr.flowid : curcpu;
1934 
1935 	if (unlikely(queue_idx >= sc->num_tx_rings)) {
1936 		queue_idx %= sc->num_tx_rings;
1937 	}
1938 
1939 	pq = sc->queues + queue_idx;
1940 
1941 	err = drbr_enqueue(ifp, pq->bufring, m);
1942 	if (err) {
1943 		/* ENOBUFS when the bufring is full */
1944 		RD(1, "%s: drbr_enqueue() failed %d\n",
1945 			__func__, err);
1946 		pq->stats.errors ++;
1947 		return err;
1948 	}
1949 
1950 	if (ifp->if_capenable & IFCAP_POLLING) {
1951 		/* If polling is on, the transmit queues will be
1952 		 * drained by the poller. */
1953 		return 0;
1954 	}
1955 
1956 	err = ptnet_drain_transmit_queue(pq, PTNET_TX_BUDGET, true);
1957 
1958 	return (err < 0) ? err : 0;
1959 }
1960 
1961 static unsigned int
1962 ptnet_rx_discard(struct netmap_kring *kring, unsigned int head)
1963 {
1964 	struct netmap_ring *ring = kring->ring;
1965 	struct netmap_slot *slot = ring->slot + head;
1966 
1967 	for (;;) {
1968 		head = nm_next(head, kring->nkr_num_slots - 1);
1969 		if (!(slot->flags & NS_MOREFRAG) || head == ring->tail) {
1970 			break;
1971 		}
1972 		slot = ring->slot + head;
1973 	}
1974 
1975 	return head;
1976 }
1977 
1978 static inline struct mbuf *
1979 ptnet_rx_slot(struct mbuf *mtail, uint8_t *nmbuf, unsigned int nmbuf_len)
1980 {
1981 	uint8_t *mdata = mtod(mtail, uint8_t *) + mtail->m_len;
1982 
1983 	do {
1984 		unsigned int copy;
1985 
1986 		if (mtail->m_len == MCLBYTES) {
1987 			struct mbuf *mf;
1988 
1989 			mf = m_getcl(M_NOWAIT, MT_DATA, 0);
1990 			if (unlikely(!mf)) {
1991 				return NULL;
1992 			}
1993 
1994 			mtail->m_next = mf;
1995 			mtail = mf;
1996 			mdata = mtod(mtail, uint8_t *);
1997 			mtail->m_len = 0;
1998 		}
1999 
2000 		copy = MCLBYTES - mtail->m_len;
2001 		if (nmbuf_len < copy) {
2002 			copy = nmbuf_len;
2003 		}
2004 
2005 		memcpy(mdata, nmbuf, copy);
2006 
2007 		nmbuf += copy;
2008 		nmbuf_len -= copy;
2009 		mdata += copy;
2010 		mtail->m_len += copy;
2011 	} while (nmbuf_len);
2012 
2013 	return mtail;
2014 }
2015 
2016 static int
2017 ptnet_rx_eof(struct ptnet_queue *pq, unsigned int budget, bool may_resched)
2018 {
2019 	struct ptnet_softc *sc = pq->sc;
2020 	bool have_vnet_hdr = sc->vnet_hdr_len;
2021 	struct ptnet_csb_gh *ptgh = pq->ptgh;
2022 	struct ptnet_csb_hg *pthg = pq->pthg;
2023 	struct netmap_adapter *na = &sc->ptna->dr.up;
2024 	struct netmap_kring *kring = na->rx_rings + pq->kring_id;
2025 	struct netmap_ring *ring = kring->ring;
2026 	unsigned int const lim = kring->nkr_num_slots - 1;
2027 	unsigned int batch_count = 0;
2028 	if_t ifp = sc->ifp;
2029 	unsigned int count = 0;
2030 	uint32_t head;
2031 
2032 	PTNET_Q_LOCK(pq);
2033 
2034 	if (unlikely(!(ifp->if_drv_flags & IFF_DRV_RUNNING))) {
2035 		goto unlock;
2036 	}
2037 
2038 	kring->nr_kflags &= ~NKR_PENDINTR;
2039 
2040 	head = ring->head;
2041 	while (count < budget) {
2042 		uint32_t prev_head = head;
2043 		struct mbuf *mhead, *mtail;
2044 		struct virtio_net_hdr *vh;
2045 		struct netmap_slot *slot;
2046 		unsigned int nmbuf_len;
2047 		uint8_t *nmbuf;
2048 		int deliver = 1; /* the mbuf to the network stack. */
2049 host_sync:
2050 		if (head == ring->tail) {
2051 			/* We ran out of slot, let's see if the host has
2052 			 * added some, by reading hwcur and hwtail from
2053 			 * the CSB. */
2054 			ptnet_sync_tail(pthg, kring);
2055 
2056 			if (head == ring->tail) {
2057 				/* Still no slots available. Reactivate
2058 				 * interrupts as they were disabled by the
2059 				 * host thread right before issuing the
2060 				 * last interrupt. */
2061 				ptgh->guest_need_kick = 1;
2062 
2063 				/* Double-check. */
2064 				ptnet_sync_tail(pthg, kring);
2065 				if (likely(head == ring->tail)) {
2066 					break;
2067 				}
2068 				ptgh->guest_need_kick = 0;
2069 			}
2070 		}
2071 
2072 		/* Initialize ring state variables, possibly grabbing the
2073 		 * virtio-net header. */
2074 		slot = ring->slot + head;
2075 		nmbuf = NMB(na, slot);
2076 		nmbuf_len = slot->len;
2077 
2078 		vh = (struct virtio_net_hdr *)nmbuf;
2079 		if (have_vnet_hdr) {
2080 			if (unlikely(nmbuf_len < PTNET_HDR_SIZE)) {
2081 				/* There is no good reason why host should
2082 				 * put the header in multiple netmap slots.
2083 				 * If this is the case, discard. */
2084 				RD(1, "Fragmented vnet-hdr: dropping");
2085 				head = ptnet_rx_discard(kring, head);
2086 				pq->stats.iqdrops ++;
2087 				deliver = 0;
2088 				goto skip;
2089 			}
2090 			ND(1, "%s: vnet hdr: flags %x csum_start %u "
2091 			      "csum_ofs %u hdr_len = %u gso_size %u "
2092 			      "gso_type %x", __func__, vh->flags,
2093 			      vh->csum_start, vh->csum_offset, vh->hdr_len,
2094 			      vh->gso_size, vh->gso_type);
2095 			nmbuf += PTNET_HDR_SIZE;
2096 			nmbuf_len -= PTNET_HDR_SIZE;
2097 		}
2098 
2099 		/* Allocate the head of a new mbuf chain.
2100 		 * We use m_getcl() to allocate an mbuf with standard cluster
2101 		 * size (MCLBYTES). In the future we could use m_getjcl()
2102 		 * to choose different sizes. */
2103 		mhead = mtail = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
2104 		if (unlikely(mhead == NULL)) {
2105 			device_printf(sc->dev, "%s: failed to allocate mbuf "
2106 				      "head\n", __func__);
2107 			pq->stats.errors ++;
2108 			break;
2109 		}
2110 
2111 		/* Initialize the mbuf state variables. */
2112 		mhead->m_pkthdr.len = nmbuf_len;
2113 		mtail->m_len = 0;
2114 
2115 		/* Scan all the netmap slots containing the current packet. */
2116 		for (;;) {
2117 			DBG(device_printf(sc->dev, "%s: h %u t %u rcv frag "
2118 					  "len %u, flags %u\n", __func__,
2119 					  head, ring->tail, slot->len,
2120 					  slot->flags));
2121 
2122 			mtail = ptnet_rx_slot(mtail, nmbuf, nmbuf_len);
2123 			if (unlikely(!mtail)) {
2124 				/* Ouch. We ran out of memory while processing
2125 				 * a packet. We have to restore the previous
2126 				 * head position, free the mbuf chain, and
2127 				 * schedule the taskqueue to give the packet
2128 				 * another chance. */
2129 				device_printf(sc->dev, "%s: failed to allocate"
2130 					" mbuf frag, reset head %u --> %u\n",
2131 					__func__, head, prev_head);
2132 				head = prev_head;
2133 				m_freem(mhead);
2134 				pq->stats.errors ++;
2135 				if (may_resched) {
2136 					taskqueue_enqueue(pq->taskq,
2137 							  &pq->task);
2138 				}
2139 				goto escape;
2140 			}
2141 
2142 			/* We have to increment head irrespective of the
2143 			 * NS_MOREFRAG being set or not. */
2144 			head = nm_next(head, lim);
2145 
2146 			if (!(slot->flags & NS_MOREFRAG)) {
2147 				break;
2148 			}
2149 
2150 			if (unlikely(head == ring->tail)) {
2151 				/* The very last slot prepared by the host has
2152 				 * the NS_MOREFRAG set. Drop it and continue
2153 				 * the outer cycle (to do the double-check). */
2154 				RD(1, "Incomplete packet: dropping");
2155 				m_freem(mhead);
2156 				pq->stats.iqdrops ++;
2157 				goto host_sync;
2158 			}
2159 
2160 			slot = ring->slot + head;
2161 			nmbuf = NMB(na, slot);
2162 			nmbuf_len = slot->len;
2163 			mhead->m_pkthdr.len += nmbuf_len;
2164 		}
2165 
2166 		mhead->m_pkthdr.rcvif = ifp;
2167 		mhead->m_pkthdr.csum_flags = 0;
2168 
2169 		/* Store the queue idx in the packet header. */
2170 		mhead->m_pkthdr.flowid = pq->kring_id;
2171 		M_HASHTYPE_SET(mhead, M_HASHTYPE_OPAQUE);
2172 
2173 		if (ifp->if_capenable & IFCAP_VLAN_HWTAGGING) {
2174 			struct ether_header *eh;
2175 
2176 			eh = mtod(mhead, struct ether_header *);
2177 			if (eh->ether_type == htons(ETHERTYPE_VLAN)) {
2178 				ptnet_vlan_tag_remove(mhead);
2179 				/*
2180 				 * With the 802.1Q header removed, update the
2181 				 * checksum starting location accordingly.
2182 				 */
2183 				if (vh->flags & VIRTIO_NET_HDR_F_NEEDS_CSUM)
2184 					vh->csum_start -= ETHER_VLAN_ENCAP_LEN;
2185 			}
2186 		}
2187 
2188 		if (have_vnet_hdr && (vh->flags & (VIRTIO_NET_HDR_F_NEEDS_CSUM
2189 					| VIRTIO_NET_HDR_F_DATA_VALID))) {
2190 			if (unlikely(ptnet_rx_csum(mhead, vh))) {
2191 				m_freem(mhead);
2192 				RD(1, "Csum offload error: dropping");
2193 				pq->stats.iqdrops ++;
2194 				deliver = 0;
2195 			}
2196 		}
2197 
2198 skip:
2199 		count ++;
2200 		if (++batch_count >= PTNET_RX_BATCH) {
2201 			/* Some packets have been (or will be) pushed to the network
2202 			 * stack. We need to update the CSB to tell the host about
2203 			 * the new ring->cur and ring->head (RX buffer refill). */
2204 			ptnet_ring_update(pq, kring, head, NAF_FORCE_READ);
2205 			batch_count = 0;
2206 		}
2207 
2208 		if (likely(deliver))  {
2209 			pq->stats.packets ++;
2210 			pq->stats.bytes += mhead->m_pkthdr.len;
2211 
2212 			PTNET_Q_UNLOCK(pq);
2213 			(*ifp->if_input)(ifp, mhead);
2214 			PTNET_Q_LOCK(pq);
2215 			/* The ring->head index (and related indices) are
2216 			 * updated under pq lock by ptnet_ring_update().
2217 			 * Since we dropped the lock to call if_input(), we
2218 			 * must reload ring->head and restart processing the
2219 			 * ring from there. */
2220 			head = ring->head;
2221 
2222 			if (unlikely(!(ifp->if_drv_flags & IFF_DRV_RUNNING))) {
2223 				/* The interface has gone down while we didn't
2224 				 * have the lock. Stop any processing and exit. */
2225 				goto unlock;
2226 			}
2227 		}
2228 	}
2229 escape:
2230 	if (batch_count) {
2231 		ptnet_ring_update(pq, kring, head, NAF_FORCE_READ);
2232 
2233 	}
2234 
2235 	if (count >= budget && may_resched) {
2236 		/* If we ran out of budget or the double-check found new
2237 		 * slots to process, schedule the taskqueue. */
2238 		DBG(RD(1, "out of budget: resched h %u t %u\n",
2239 					head, ring->tail));
2240 		taskqueue_enqueue(pq->taskq, &pq->task);
2241 	}
2242 unlock:
2243 	PTNET_Q_UNLOCK(pq);
2244 
2245 	return count;
2246 }
2247 
2248 static void
2249 ptnet_rx_task(void *context, int pending)
2250 {
2251 	struct ptnet_queue *pq = context;
2252 
2253 	DBG(RD(1, "%s: pq #%u\n", __func__, pq->kring_id));
2254 	ptnet_rx_eof(pq, PTNET_RX_BUDGET, true);
2255 }
2256 
2257 static void
2258 ptnet_tx_task(void *context, int pending)
2259 {
2260 	struct ptnet_queue *pq = context;
2261 
2262 	DBG(RD(1, "%s: pq #%u\n", __func__, pq->kring_id));
2263 	ptnet_drain_transmit_queue(pq, PTNET_TX_BUDGET, true);
2264 }
2265 
2266 #ifdef DEVICE_POLLING
2267 /* We don't need to handle differently POLL_AND_CHECK_STATUS and
2268  * POLL_ONLY, since we don't have an Interrupt Status Register. */
2269 static int
2270 ptnet_poll(if_t ifp, enum poll_cmd cmd, int budget)
2271 {
2272 	struct ptnet_softc *sc = if_getsoftc(ifp);
2273 	unsigned int queue_budget;
2274 	unsigned int count = 0;
2275 	bool borrow = false;
2276 	int i;
2277 
2278 	KASSERT(sc->num_rings > 0, ("Found no queues in while polling ptnet"));
2279 	queue_budget = MAX(budget / sc->num_rings, 1);
2280 	RD(1, "Per-queue budget is %d", queue_budget);
2281 
2282 	while (budget) {
2283 		unsigned int rcnt = 0;
2284 
2285 		for (i = 0; i < sc->num_rings; i++) {
2286 			struct ptnet_queue *pq = sc->queues + i;
2287 
2288 			if (borrow) {
2289 				queue_budget = MIN(queue_budget, budget);
2290 				if (queue_budget == 0) {
2291 					break;
2292 				}
2293 			}
2294 
2295 			if (i < sc->num_tx_rings) {
2296 				rcnt += ptnet_drain_transmit_queue(pq,
2297 						   queue_budget, false);
2298 			} else {
2299 				rcnt += ptnet_rx_eof(pq, queue_budget,
2300 						      false);
2301 			}
2302 		}
2303 
2304 		if (!rcnt) {
2305 			/* A scan of the queues gave no result, we can
2306 			 * stop here. */
2307 			break;
2308 		}
2309 
2310 		if (rcnt > budget) {
2311 			/* This may happen when initial budget < sc->num_rings,
2312 			 * since one packet budget is given to each queue
2313 			 * anyway. Just pretend we didn't eat "so much". */
2314 			rcnt = budget;
2315 		}
2316 		count += rcnt;
2317 		budget -= rcnt;
2318 		borrow = true;
2319 	}
2320 
2321 
2322 	return count;
2323 }
2324 #endif /* DEVICE_POLLING */
2325