xref: /freebsd-12.1/sys/dev/netmap/netmap_kern.h (revision 01e8e2c2)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (C) 2011-2014 Matteo Landi, Luigi Rizzo
5  * Copyright (C) 2013-2016 Universita` di Pisa
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *   1. Redistributions of source code must retain the above copyright
12  *      notice, this list of conditions and the following disclaimer.
13  *   2. Redistributions in binary form must reproduce the above copyright
14  *      notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 /*
31  * $FreeBSD$
32  *
33  * The header contains the definitions of constants and function
34  * prototypes used only in kernelspace.
35  */
36 
37 #ifndef _NET_NETMAP_KERN_H_
38 #define _NET_NETMAP_KERN_H_
39 
40 #if defined(linux)
41 
42 #if defined(CONFIG_NETMAP_EXTMEM)
43 #define WITH_EXTMEM
44 #endif
45 #if  defined(CONFIG_NETMAP_VALE)
46 #define WITH_VALE
47 #endif
48 #if defined(CONFIG_NETMAP_PIPE)
49 #define WITH_PIPES
50 #endif
51 #if defined(CONFIG_NETMAP_MONITOR)
52 #define WITH_MONITOR
53 #endif
54 #if defined(CONFIG_NETMAP_GENERIC)
55 #define WITH_GENERIC
56 #endif
57 #if defined(CONFIG_NETMAP_PTNETMAP)
58 #define WITH_PTNETMAP
59 #endif
60 #if defined(CONFIG_NETMAP_SINK)
61 #define WITH_SINK
62 #endif
63 #if defined(CONFIG_NETMAP_NULL)
64 #define WITH_NMNULL
65 #endif
66 
67 #elif defined (_WIN32)
68 #define WITH_VALE	// comment out to disable VALE support
69 #define WITH_PIPES
70 #define WITH_MONITOR
71 #define WITH_GENERIC
72 #define WITH_NMNULL
73 
74 #else	/* neither linux nor windows */
75 #define WITH_VALE	// comment out to disable VALE support
76 #define WITH_PIPES
77 #define WITH_MONITOR
78 #define WITH_GENERIC
79 #define WITH_PTNETMAP	/* ptnetmap guest support */
80 #define WITH_EXTMEM
81 #define WITH_NMNULL
82 #endif
83 
84 #if defined(__FreeBSD__)
85 #include <sys/selinfo.h>
86 
87 #define likely(x)	__builtin_expect((long)!!(x), 1L)
88 #define unlikely(x)	__builtin_expect((long)!!(x), 0L)
89 #define __user
90 
91 #define	NM_LOCK_T	struct mtx	/* low level spinlock, used to protect queues */
92 
93 #define NM_MTX_T	struct sx	/* OS-specific mutex (sleepable) */
94 #define NM_MTX_INIT(m)		sx_init(&(m), #m)
95 #define NM_MTX_DESTROY(m)	sx_destroy(&(m))
96 #define NM_MTX_LOCK(m)		sx_xlock(&(m))
97 #define NM_MTX_SPINLOCK(m)	while (!sx_try_xlock(&(m))) ;
98 #define NM_MTX_UNLOCK(m)	sx_xunlock(&(m))
99 #define NM_MTX_ASSERT(m)	sx_assert(&(m), SA_XLOCKED)
100 
101 #define	NM_SELINFO_T	struct nm_selinfo
102 #define NM_SELRECORD_T	struct thread
103 #define	MBUF_LEN(m)	((m)->m_pkthdr.len)
104 #define MBUF_TXQ(m)	((m)->m_pkthdr.flowid)
105 #define MBUF_TRANSMIT(na, ifp, m)	((na)->if_transmit(ifp, m))
106 #define	GEN_TX_MBUF_IFP(m)	((m)->m_pkthdr.rcvif)
107 
108 #define NM_ATOMIC_T	volatile int /* required by atomic/bitops.h */
109 /* atomic operations */
110 #include <machine/atomic.h>
111 #define NM_ATOMIC_TEST_AND_SET(p)       (!atomic_cmpset_acq_int((p), 0, 1))
112 #define NM_ATOMIC_CLEAR(p)              atomic_store_rel_int((p), 0)
113 
114 #if __FreeBSD_version >= 1100030
115 #define	WNA(_ifp)	(_ifp)->if_netmap
116 #else /* older FreeBSD */
117 #define	WNA(_ifp)	(_ifp)->if_pspare[0]
118 #endif /* older FreeBSD */
119 
120 #if __FreeBSD_version >= 1100005
121 struct netmap_adapter *netmap_getna(if_t ifp);
122 #endif
123 
124 #if __FreeBSD_version >= 1100027
125 #define MBUF_REFCNT(m)		((m)->m_ext.ext_count)
126 #define SET_MBUF_REFCNT(m, x)   (m)->m_ext.ext_count = x
127 #else
128 #define MBUF_REFCNT(m)		((m)->m_ext.ref_cnt ? *((m)->m_ext.ref_cnt) : -1)
129 #define SET_MBUF_REFCNT(m, x)   *((m)->m_ext.ref_cnt) = x
130 #endif
131 
132 #define MBUF_QUEUED(m)		1
133 
134 struct nm_selinfo {
135 	struct selinfo si;
136 	struct mtx m;
137 };
138 
139 
140 struct hrtimer {
141     /* Not used in FreeBSD. */
142 };
143 
144 #define NM_BNS_GET(b)
145 #define NM_BNS_PUT(b)
146 
147 #elif defined (linux)
148 
149 #define	NM_LOCK_T	safe_spinlock_t	// see bsd_glue.h
150 #define	NM_SELINFO_T	wait_queue_head_t
151 #define	MBUF_LEN(m)	((m)->len)
152 #define MBUF_TRANSMIT(na, ifp, m)							\
153 	({										\
154 		/* Avoid infinite recursion with generic. */				\
155 		m->priority = NM_MAGIC_PRIORITY_TX;					\
156 		(((struct net_device_ops *)(na)->if_transmit)->ndo_start_xmit(m, ifp));	\
157 		0;									\
158 	})
159 
160 /* See explanation in nm_os_generic_xmit_frame. */
161 #define	GEN_TX_MBUF_IFP(m)	((struct ifnet *)skb_shinfo(m)->destructor_arg)
162 
163 #define NM_ATOMIC_T	volatile long unsigned int
164 
165 #define NM_MTX_T	struct mutex	/* OS-specific sleepable lock */
166 #define NM_MTX_INIT(m)	mutex_init(&(m))
167 #define NM_MTX_DESTROY(m)	do { (void)(m); } while (0)
168 #define NM_MTX_LOCK(m)		mutex_lock(&(m))
169 #define NM_MTX_UNLOCK(m)	mutex_unlock(&(m))
170 #define NM_MTX_ASSERT(m)	mutex_is_locked(&(m))
171 
172 #ifndef DEV_NETMAP
173 #define DEV_NETMAP
174 #endif /* DEV_NETMAP */
175 
176 #elif defined (__APPLE__)
177 
178 #warning apple support is incomplete.
179 #define likely(x)	__builtin_expect(!!(x), 1)
180 #define unlikely(x)	__builtin_expect(!!(x), 0)
181 #define	NM_LOCK_T	IOLock *
182 #define	NM_SELINFO_T	struct selinfo
183 #define	MBUF_LEN(m)	((m)->m_pkthdr.len)
184 
185 #elif defined (_WIN32)
186 #include "../../../WINDOWS/win_glue.h"
187 
188 #define NM_SELRECORD_T		IO_STACK_LOCATION
189 #define NM_SELINFO_T		win_SELINFO		// see win_glue.h
190 #define NM_LOCK_T		win_spinlock_t	// see win_glue.h
191 #define NM_MTX_T		KGUARDED_MUTEX	/* OS-specific mutex (sleepable) */
192 
193 #define NM_MTX_INIT(m)		KeInitializeGuardedMutex(&m);
194 #define NM_MTX_DESTROY(m)	do { (void)(m); } while (0)
195 #define NM_MTX_LOCK(m)		KeAcquireGuardedMutex(&(m))
196 #define NM_MTX_UNLOCK(m)	KeReleaseGuardedMutex(&(m))
197 #define NM_MTX_ASSERT(m)	assert(&m.Count>0)
198 
199 //These linknames are for the NDIS driver
200 #define NETMAP_NDIS_LINKNAME_STRING             L"\\DosDevices\\NMAPNDIS"
201 #define NETMAP_NDIS_NTDEVICE_STRING             L"\\Device\\NMAPNDIS"
202 
203 //Definition of internal driver-to-driver ioctl codes
204 #define NETMAP_KERNEL_XCHANGE_POINTERS		_IO('i', 180)
205 #define NETMAP_KERNEL_SEND_SHUTDOWN_SIGNAL	_IO_direct('i', 195)
206 
207 typedef struct hrtimer{
208 	KTIMER timer;
209 	BOOLEAN active;
210 	KDPC deferred_proc;
211 };
212 
213 /* MSVC does not have likely/unlikely support */
214 #ifdef _MSC_VER
215 #define likely(x)	(x)
216 #define unlikely(x)	(x)
217 #else
218 #define likely(x)	__builtin_expect((long)!!(x), 1L)
219 #define unlikely(x)	__builtin_expect((long)!!(x), 0L)
220 #endif //_MSC_VER
221 
222 #else
223 
224 #error unsupported platform
225 
226 #endif /* end - platform-specific code */
227 
228 #ifndef _WIN32 /* support for emulated sysctl */
229 #define SYSBEGIN(x)
230 #define SYSEND
231 #endif /* _WIN32 */
232 
233 #define NM_ACCESS_ONCE(x)	(*(volatile __typeof__(x) *)&(x))
234 
235 #define	NMG_LOCK_T		NM_MTX_T
236 #define	NMG_LOCK_INIT()		NM_MTX_INIT(netmap_global_lock)
237 #define	NMG_LOCK_DESTROY()	NM_MTX_DESTROY(netmap_global_lock)
238 #define	NMG_LOCK()		NM_MTX_LOCK(netmap_global_lock)
239 #define	NMG_UNLOCK()		NM_MTX_UNLOCK(netmap_global_lock)
240 #define	NMG_LOCK_ASSERT()	NM_MTX_ASSERT(netmap_global_lock)
241 
242 #if defined(__FreeBSD__)
243 #define nm_prerr_int	printf
244 #define nm_prinf_int	printf
245 #elif defined (_WIN32)
246 #define nm_prerr_int	DbgPrint
247 #define nm_prinf_int	DbgPrint
248 #elif defined(linux)
249 #define nm_prerr_int(fmt, arg...)    printk(KERN_ERR fmt, ##arg)
250 #define nm_prinf_int(fmt, arg...)    printk(KERN_INFO fmt, ##arg)
251 #endif
252 
253 #define nm_prinf(format, ...)					\
254 	do {							\
255 		struct timeval __xxts;				\
256 		microtime(&__xxts);				\
257 		nm_prinf_int("%03d.%06d [%4d] %-25s " format "\n",\
258 		(int)__xxts.tv_sec % 1000, (int)__xxts.tv_usec,	\
259 		__LINE__, __FUNCTION__, ##__VA_ARGS__);		\
260 	} while (0)
261 
262 #define nm_prerr(format, ...)					\
263 	do {							\
264 		struct timeval __xxts;				\
265 		microtime(&__xxts);				\
266 		nm_prerr_int("%03d.%06d [%4d] %-25s " format "\n",\
267 		(int)__xxts.tv_sec % 1000, (int)__xxts.tv_usec,	\
268 		__LINE__, __FUNCTION__, ##__VA_ARGS__);		\
269 	} while (0)
270 
271 /* Disabled printf (used to be nm_prdis). */
272 #define nm_prdis(format, ...)
273 
274 /* Rate limited, lps indicates how many per second. */
275 #define nm_prlim(lps, format, ...)				\
276 	do {							\
277 		static int t0, __cnt;				\
278 		if (t0 != time_second) {			\
279 			t0 = time_second;			\
280 			__cnt = 0;				\
281 		}						\
282 		if (__cnt++ < lps)				\
283 			nm_prinf(format, ##__VA_ARGS__);	\
284 	} while (0)
285 
286 struct netmap_adapter;
287 struct nm_bdg_fwd;
288 struct nm_bridge;
289 struct netmap_priv_d;
290 struct nm_bdg_args;
291 
292 /* os-specific NM_SELINFO_T initialzation/destruction functions */
293 void nm_os_selinfo_init(NM_SELINFO_T *);
294 void nm_os_selinfo_uninit(NM_SELINFO_T *);
295 
296 const char *nm_dump_buf(char *p, int len, int lim, char *dst);
297 
298 void nm_os_selwakeup(NM_SELINFO_T *si);
299 void nm_os_selrecord(NM_SELRECORD_T *sr, NM_SELINFO_T *si);
300 
301 int nm_os_ifnet_init(void);
302 void nm_os_ifnet_fini(void);
303 void nm_os_ifnet_lock(void);
304 void nm_os_ifnet_unlock(void);
305 
306 unsigned nm_os_ifnet_mtu(struct ifnet *ifp);
307 
308 void nm_os_get_module(void);
309 void nm_os_put_module(void);
310 
311 void netmap_make_zombie(struct ifnet *);
312 void netmap_undo_zombie(struct ifnet *);
313 
314 /* os independent alloc/realloc/free */
315 void *nm_os_malloc(size_t);
316 void *nm_os_vmalloc(size_t);
317 void *nm_os_realloc(void *, size_t new_size, size_t old_size);
318 void nm_os_free(void *);
319 void nm_os_vfree(void *);
320 
321 /* os specific attach/detach enter/exit-netmap-mode routines */
322 void nm_os_onattach(struct ifnet *);
323 void nm_os_ondetach(struct ifnet *);
324 void nm_os_onenter(struct ifnet *);
325 void nm_os_onexit(struct ifnet *);
326 
327 /* passes a packet up to the host stack.
328  * If the packet is sent (or dropped) immediately it returns NULL,
329  * otherwise it links the packet to prev and returns m.
330  * In this case, a final call with m=NULL and prev != NULL will send up
331  * the entire chain to the host stack.
332  */
333 void *nm_os_send_up(struct ifnet *, struct mbuf *m, struct mbuf *prev);
334 
335 int nm_os_mbuf_has_seg_offld(struct mbuf *m);
336 int nm_os_mbuf_has_csum_offld(struct mbuf *m);
337 
338 #include "netmap_mbq.h"
339 
340 extern NMG_LOCK_T	netmap_global_lock;
341 
342 enum txrx { NR_RX = 0, NR_TX = 1, NR_TXRX };
343 
344 static __inline const char*
345 nm_txrx2str(enum txrx t)
346 {
347 	return (t== NR_RX ? "RX" : "TX");
348 }
349 
350 static __inline enum txrx
351 nm_txrx_swap(enum txrx t)
352 {
353 	return (t== NR_RX ? NR_TX : NR_RX);
354 }
355 
356 #define for_rx_tx(t)	for ((t) = 0; (t) < NR_TXRX; (t)++)
357 
358 #ifdef WITH_MONITOR
359 struct netmap_zmon_list {
360 	struct netmap_kring *next;
361 	struct netmap_kring *prev;
362 };
363 #endif /* WITH_MONITOR */
364 
365 /*
366  * private, kernel view of a ring. Keeps track of the status of
367  * a ring across system calls.
368  *
369  *	nr_hwcur	index of the next buffer to refill.
370  *			It corresponds to ring->head
371  *			at the time the system call returns.
372  *
373  *	nr_hwtail	index of the first buffer owned by the kernel.
374  *			On RX, hwcur->hwtail are receive buffers
375  *			not yet released. hwcur is advanced following
376  *			ring->head, hwtail is advanced on incoming packets,
377  *			and a wakeup is generated when hwtail passes ring->cur
378  *			    On TX, hwcur->rcur have been filled by the sender
379  *			but not sent yet to the NIC; rcur->hwtail are available
380  *			for new transmissions, and hwtail->hwcur-1 are pending
381  *			transmissions not yet acknowledged.
382  *
383  * The indexes in the NIC and netmap rings are offset by nkr_hwofs slots.
384  * This is so that, on a reset, buffers owned by userspace are not
385  * modified by the kernel. In particular:
386  * RX rings: the next empty buffer (hwtail + hwofs) coincides with
387  * 	the next empty buffer as known by the hardware (next_to_check or so).
388  * TX rings: hwcur + hwofs coincides with next_to_send
389  *
390  * The following fields are used to implement lock-free copy of packets
391  * from input to output ports in VALE switch:
392  *	nkr_hwlease	buffer after the last one being copied.
393  *			A writer in nm_bdg_flush reserves N buffers
394  *			from nr_hwlease, advances it, then does the
395  *			copy outside the lock.
396  *			In RX rings (used for VALE ports),
397  *			nkr_hwtail <= nkr_hwlease < nkr_hwcur+N-1
398  *			In TX rings (used for NIC or host stack ports)
399  *			nkr_hwcur <= nkr_hwlease < nkr_hwtail
400  *	nkr_leases	array of nkr_num_slots where writers can report
401  *			completion of their block. NR_NOSLOT (~0) indicates
402  *			that the writer has not finished yet
403  *	nkr_lease_idx	index of next free slot in nr_leases, to be assigned
404  *
405  * The kring is manipulated by txsync/rxsync and generic netmap function.
406  *
407  * Concurrent rxsync or txsync on the same ring are prevented through
408  * by nm_kr_(try)lock() which in turn uses nr_busy. This is all we need
409  * for NIC rings, and for TX rings attached to the host stack.
410  *
411  * RX rings attached to the host stack use an mbq (rx_queue) on both
412  * rxsync_from_host() and netmap_transmit(). The mbq is protected
413  * by its internal lock.
414  *
415  * RX rings attached to the VALE switch are accessed by both senders
416  * and receiver. They are protected through the q_lock on the RX ring.
417  */
418 struct netmap_kring {
419 	struct netmap_ring	*ring;
420 
421 	uint32_t	nr_hwcur;  /* should be nr_hwhead */
422 	uint32_t	nr_hwtail;
423 
424 	/*
425 	 * Copies of values in user rings, so we do not need to look
426 	 * at the ring (which could be modified). These are set in the
427 	 * *sync_prologue()/finalize() routines.
428 	 */
429 	uint32_t	rhead;
430 	uint32_t	rcur;
431 	uint32_t	rtail;
432 
433 	uint32_t	nr_kflags;	/* private driver flags */
434 #define NKR_PENDINTR	0x1		// Pending interrupt.
435 #define NKR_EXCLUSIVE	0x2		/* exclusive binding */
436 #define NKR_FORWARD	0x4		/* (host ring only) there are
437 					   packets to forward
438 					 */
439 #define NKR_NEEDRING	0x8		/* ring needed even if users==0
440 					 * (used internally by pipes and
441 					 *  by ptnetmap host ports)
442 					 */
443 #define NKR_NOINTR      0x10            /* don't use interrupts on this ring */
444 #define NKR_FAKERING	0x20		/* don't allocate/free buffers */
445 
446 	uint32_t	nr_mode;
447 	uint32_t	nr_pending_mode;
448 #define NKR_NETMAP_OFF	0x0
449 #define NKR_NETMAP_ON	0x1
450 
451 	uint32_t	nkr_num_slots;
452 
453 	/*
454 	 * On a NIC reset, the NIC ring indexes may be reset but the
455 	 * indexes in the netmap rings remain the same. nkr_hwofs
456 	 * keeps track of the offset between the two.
457 	 */
458 	int32_t		nkr_hwofs;
459 
460 	/* last_reclaim is opaque marker to help reduce the frequency
461 	 * of operations such as reclaiming tx buffers. A possible use
462 	 * is set it to ticks and do the reclaim only once per tick.
463 	 */
464 	uint64_t	last_reclaim;
465 
466 
467 	NM_SELINFO_T	si;		/* poll/select wait queue */
468 	NM_LOCK_T	q_lock;		/* protects kring and ring. */
469 	NM_ATOMIC_T	nr_busy;	/* prevent concurrent syscalls */
470 
471 	/* the adapter the owns this kring */
472 	struct netmap_adapter *na;
473 
474 	/* the adapter that wants to be notified when this kring has
475 	 * new slots avaialable. This is usually the same as the above,
476 	 * but wrappers may let it point to themselves
477 	 */
478 	struct netmap_adapter *notify_na;
479 
480 	/* The following fields are for VALE switch support */
481 	struct nm_bdg_fwd *nkr_ft;
482 	uint32_t	*nkr_leases;
483 #define NR_NOSLOT	((uint32_t)~0)	/* used in nkr_*lease* */
484 	uint32_t	nkr_hwlease;
485 	uint32_t	nkr_lease_idx;
486 
487 	/* while nkr_stopped is set, no new [tr]xsync operations can
488 	 * be started on this kring.
489 	 * This is used by netmap_disable_all_rings()
490 	 * to find a synchronization point where critical data
491 	 * structures pointed to by the kring can be added or removed
492 	 */
493 	volatile int nkr_stopped;
494 
495 	/* Support for adapters without native netmap support.
496 	 * On tx rings we preallocate an array of tx buffers
497 	 * (same size as the netmap ring), on rx rings we
498 	 * store incoming mbufs in a queue that is drained by
499 	 * a rxsync.
500 	 */
501 	struct mbuf	**tx_pool;
502 	struct mbuf	*tx_event;	/* TX event used as a notification */
503 	NM_LOCK_T	tx_event_lock;	/* protects the tx_event mbuf */
504 	struct mbq	rx_queue;       /* intercepted rx mbufs. */
505 
506 	uint32_t	users;		/* existing bindings for this ring */
507 
508 	uint32_t	ring_id;	/* kring identifier */
509 	enum txrx	tx;		/* kind of ring (tx or rx) */
510 	char name[64];			/* diagnostic */
511 
512 	/* [tx]sync callback for this kring.
513 	 * The default nm_kring_create callback (netmap_krings_create)
514 	 * sets the nm_sync callback of each hardware tx(rx) kring to
515 	 * the corresponding nm_txsync(nm_rxsync) taken from the
516 	 * netmap_adapter; moreover, it sets the sync callback
517 	 * of the host tx(rx) ring to netmap_txsync_to_host
518 	 * (netmap_rxsync_from_host).
519 	 *
520 	 * Overrides: the above configuration is not changed by
521 	 * any of the nm_krings_create callbacks.
522 	 */
523 	int (*nm_sync)(struct netmap_kring *kring, int flags);
524 	int (*nm_notify)(struct netmap_kring *kring, int flags);
525 
526 #ifdef WITH_PIPES
527 	struct netmap_kring *pipe;	/* if this is a pipe ring,
528 					 * pointer to the other end
529 					 */
530 	uint32_t pipe_tail;		/* hwtail updated by the other end */
531 #endif /* WITH_PIPES */
532 
533 	int (*save_notify)(struct netmap_kring *kring, int flags);
534 
535 #ifdef WITH_MONITOR
536 	/* array of krings that are monitoring this kring */
537 	struct netmap_kring **monitors;
538 	uint32_t max_monitors; /* current size of the monitors array */
539 	uint32_t n_monitors;	/* next unused entry in the monitor array */
540 	uint32_t mon_pos[NR_TXRX]; /* index of this ring in the monitored ring array */
541 	uint32_t mon_tail;  /* last seen slot on rx */
542 
543 	/* circular list of zero-copy monitors */
544 	struct netmap_zmon_list zmon_list[NR_TXRX];
545 
546 	/*
547 	 * Monitors work by intercepting the sync and notify callbacks of the
548 	 * monitored krings. This is implemented by replacing the pointers
549 	 * above and saving the previous ones in mon_* pointers below
550 	 */
551 	int (*mon_sync)(struct netmap_kring *kring, int flags);
552 	int (*mon_notify)(struct netmap_kring *kring, int flags);
553 
554 #endif
555 }
556 #ifdef _WIN32
557 __declspec(align(64));
558 #else
559 __attribute__((__aligned__(64)));
560 #endif
561 
562 /* return 1 iff the kring needs to be turned on */
563 static inline int
564 nm_kring_pending_on(struct netmap_kring *kring)
565 {
566 	return kring->nr_pending_mode == NKR_NETMAP_ON &&
567 	       kring->nr_mode == NKR_NETMAP_OFF;
568 }
569 
570 /* return 1 iff the kring needs to be turned off */
571 static inline int
572 nm_kring_pending_off(struct netmap_kring *kring)
573 {
574 	return kring->nr_pending_mode == NKR_NETMAP_OFF &&
575 	       kring->nr_mode == NKR_NETMAP_ON;
576 }
577 
578 /* return the next index, with wraparound */
579 static inline uint32_t
580 nm_next(uint32_t i, uint32_t lim)
581 {
582 	return unlikely (i == lim) ? 0 : i + 1;
583 }
584 
585 
586 /* return the previous index, with wraparound */
587 static inline uint32_t
588 nm_prev(uint32_t i, uint32_t lim)
589 {
590 	return unlikely (i == 0) ? lim : i - 1;
591 }
592 
593 
594 /*
595  *
596  * Here is the layout for the Rx and Tx rings.
597 
598        RxRING                            TxRING
599 
600       +-----------------+            +-----------------+
601       |                 |            |                 |
602       |      free       |            |      free       |
603       +-----------------+            +-----------------+
604 head->| owned by user   |<-hwcur     | not sent to nic |<-hwcur
605       |                 |            | yet             |
606       +-----------------+            |                 |
607  cur->| available to    |            |                 |
608       | user, not read  |            +-----------------+
609       | yet             |       cur->| (being          |
610       |                 |            |  prepared)      |
611       |                 |            |                 |
612       +-----------------+            +     ------      +
613 tail->|                 |<-hwtail    |                 |<-hwlease
614       | (being          | ...        |                 | ...
615       |  prepared)      | ...        |                 | ...
616       +-----------------+ ...        |                 | ...
617       |                 |<-hwlease   +-----------------+
618       |                 |      tail->|                 |<-hwtail
619       |                 |            |                 |
620       |                 |            |                 |
621       |                 |            |                 |
622       +-----------------+            +-----------------+
623 
624  * The cur/tail (user view) and hwcur/hwtail (kernel view)
625  * are used in the normal operation of the card.
626  *
627  * When a ring is the output of a switch port (Rx ring for
628  * a VALE port, Tx ring for the host stack or NIC), slots
629  * are reserved in blocks through 'hwlease' which points
630  * to the next unused slot.
631  * On an Rx ring, hwlease is always after hwtail,
632  * and completions cause hwtail to advance.
633  * On a Tx ring, hwlease is always between cur and hwtail,
634  * and completions cause cur to advance.
635  *
636  * nm_kr_space() returns the maximum number of slots that
637  * can be assigned.
638  * nm_kr_lease() reserves the required number of buffers,
639  *    advances nkr_hwlease and also returns an entry in
640  *    a circular array where completions should be reported.
641  */
642 
643 struct lut_entry;
644 #ifdef __FreeBSD__
645 #define plut_entry lut_entry
646 #endif
647 
648 struct netmap_lut {
649 	struct lut_entry *lut;
650 	struct plut_entry *plut;
651 	uint32_t objtotal;	/* max buffer index */
652 	uint32_t objsize;	/* buffer size */
653 };
654 
655 struct netmap_vp_adapter; // forward
656 struct nm_bridge;
657 
658 /* Struct to be filled by nm_config callbacks. */
659 struct nm_config_info {
660 	unsigned num_tx_rings;
661 	unsigned num_rx_rings;
662 	unsigned num_tx_descs;
663 	unsigned num_rx_descs;
664 	unsigned rx_buf_maxsize;
665 };
666 
667 /*
668  * default type for the magic field.
669  * May be overriden in glue code.
670  */
671 #ifndef NM_OS_MAGIC
672 #define NM_OS_MAGIC uint32_t
673 #endif /* !NM_OS_MAGIC */
674 
675 /*
676  * The "struct netmap_adapter" extends the "struct adapter"
677  * (or equivalent) device descriptor.
678  * It contains all base fields needed to support netmap operation.
679  * There are in fact different types of netmap adapters
680  * (native, generic, VALE switch...) so a netmap_adapter is
681  * just the first field in the derived type.
682  */
683 struct netmap_adapter {
684 	/*
685 	 * On linux we do not have a good way to tell if an interface
686 	 * is netmap-capable. So we always use the following trick:
687 	 * NA(ifp) points here, and the first entry (which hopefully
688 	 * always exists and is at least 32 bits) contains a magic
689 	 * value which we can use to detect that the interface is good.
690 	 */
691 	NM_OS_MAGIC magic;
692 	uint32_t na_flags;	/* enabled, and other flags */
693 #define NAF_SKIP_INTR	1	/* use the regular interrupt handler.
694 				 * useful during initialization
695 				 */
696 #define NAF_SW_ONLY	2	/* forward packets only to sw adapter */
697 #define NAF_BDG_MAYSLEEP 4	/* the bridge is allowed to sleep when
698 				 * forwarding packets coming from this
699 				 * interface
700 				 */
701 #define NAF_MEM_OWNER	8	/* the adapter uses its own memory area
702 				 * that cannot be changed
703 				 */
704 #define NAF_NATIVE      16      /* the adapter is native.
705 				 * Virtual ports (non persistent vale ports,
706 				 * pipes, monitors...) should never use
707 				 * this flag.
708 				 */
709 #define	NAF_NETMAP_ON	32	/* netmap is active (either native or
710 				 * emulated). Where possible (e.g. FreeBSD)
711 				 * IFCAP_NETMAP also mirrors this flag.
712 				 */
713 #define NAF_HOST_RINGS  64	/* the adapter supports the host rings */
714 #define NAF_FORCE_NATIVE 128	/* the adapter is always NATIVE */
715 /* free */
716 #define NAF_MOREFRAG	512	/* the adapter supports NS_MOREFRAG */
717 #define NAF_ZOMBIE	(1U<<30) /* the nic driver has been unloaded */
718 #define	NAF_BUSY	(1U<<31) /* the adapter is used internally and
719 				  * cannot be registered from userspace
720 				  */
721 	int active_fds; /* number of user-space descriptors using this
722 			 interface, which is equal to the number of
723 			 struct netmap_if objs in the mapped region. */
724 
725 	u_int num_rx_rings; /* number of adapter receive rings */
726 	u_int num_tx_rings; /* number of adapter transmit rings */
727 	u_int num_host_rx_rings; /* number of host receive rings */
728 	u_int num_host_tx_rings; /* number of host transmit rings */
729 
730 	u_int num_tx_desc;  /* number of descriptor in each queue */
731 	u_int num_rx_desc;
732 
733 	/* tx_rings and rx_rings are private but allocated as a
734 	 * contiguous chunk of memory. Each array has N+K entries,
735 	 * N for the hardware rings and K for the host rings.
736 	 */
737 	struct netmap_kring **tx_rings; /* array of TX rings. */
738 	struct netmap_kring **rx_rings; /* array of RX rings. */
739 
740 	void *tailroom;		       /* space below the rings array */
741 				       /* (used for leases) */
742 
743 
744 	NM_SELINFO_T si[NR_TXRX];	/* global wait queues */
745 
746 	/* count users of the global wait queues */
747 	int si_users[NR_TXRX];
748 
749 	void *pdev; /* used to store pci device */
750 
751 	/* copy of if_qflush and if_transmit pointers, to intercept
752 	 * packets from the network stack when netmap is active.
753 	 */
754 	int     (*if_transmit)(struct ifnet *, struct mbuf *);
755 
756 	/* copy of if_input for netmap_send_up() */
757 	void     (*if_input)(struct ifnet *, struct mbuf *);
758 
759 	/* Back reference to the parent ifnet struct. Used for
760 	 * hardware ports (emulated netmap included). */
761 	struct ifnet *ifp; /* adapter is ifp->if_softc */
762 
763 	/*---- callbacks for this netmap adapter -----*/
764 	/*
765 	 * nm_dtor() is the cleanup routine called when destroying
766 	 *	the adapter.
767 	 *	Called with NMG_LOCK held.
768 	 *
769 	 * nm_register() is called on NIOCREGIF and close() to enter
770 	 *	or exit netmap mode on the NIC
771 	 *	Called with NNG_LOCK held.
772 	 *
773 	 * nm_txsync() pushes packets to the underlying hw/switch
774 	 *
775 	 * nm_rxsync() collects packets from the underlying hw/switch
776 	 *
777 	 * nm_config() returns configuration information from the OS
778 	 *	Called with NMG_LOCK held.
779 	 *
780 	 * nm_krings_create() create and init the tx_rings and
781 	 * 	rx_rings arrays of kring structures. In particular,
782 	 * 	set the nm_sync callbacks for each ring.
783 	 * 	There is no need to also allocate the corresponding
784 	 * 	netmap_rings, since netmap_mem_rings_create() will always
785 	 * 	be called to provide the missing ones.
786 	 *	Called with NNG_LOCK held.
787 	 *
788 	 * nm_krings_delete() cleanup and delete the tx_rings and rx_rings
789 	 * 	arrays
790 	 *	Called with NMG_LOCK held.
791 	 *
792 	 * nm_notify() is used to act after data have become available
793 	 * 	(or the stopped state of the ring has changed)
794 	 *	For hw devices this is typically a selwakeup(),
795 	 *	but for NIC/host ports attached to a switch (or vice-versa)
796 	 *	we also need to invoke the 'txsync' code downstream.
797 	 *      This callback pointer is actually used only to initialize
798 	 *      kring->nm_notify.
799 	 *      Return values are the same as for netmap_rx_irq().
800 	 */
801 	void (*nm_dtor)(struct netmap_adapter *);
802 
803 	int (*nm_register)(struct netmap_adapter *, int onoff);
804 	void (*nm_intr)(struct netmap_adapter *, int onoff);
805 
806 	int (*nm_txsync)(struct netmap_kring *kring, int flags);
807 	int (*nm_rxsync)(struct netmap_kring *kring, int flags);
808 	int (*nm_notify)(struct netmap_kring *kring, int flags);
809 #define NAF_FORCE_READ      1
810 #define NAF_FORCE_RECLAIM   2
811 #define NAF_CAN_FORWARD_DOWN 4
812 	/* return configuration information */
813 	int (*nm_config)(struct netmap_adapter *, struct nm_config_info *info);
814 	int (*nm_krings_create)(struct netmap_adapter *);
815 	void (*nm_krings_delete)(struct netmap_adapter *);
816 	/*
817 	 * nm_bdg_attach() initializes the na_vp field to point
818 	 *      to an adapter that can be attached to a VALE switch. If the
819 	 *      current adapter is already a VALE port, na_vp is simply a cast;
820 	 *      otherwise, na_vp points to a netmap_bwrap_adapter.
821 	 *      If applicable, this callback also initializes na_hostvp,
822 	 *      that can be used to connect the adapter host rings to the
823 	 *      switch.
824 	 *      Called with NMG_LOCK held.
825 	 *
826 	 * nm_bdg_ctl() is called on the actual attach/detach to/from
827 	 *      to/from the switch, to perform adapter-specific
828 	 *      initializations
829 	 *      Called with NMG_LOCK held.
830 	 */
831 	int (*nm_bdg_attach)(const char *bdg_name, struct netmap_adapter *,
832 			struct nm_bridge *);
833 	int (*nm_bdg_ctl)(struct nmreq_header *, struct netmap_adapter *);
834 
835 	/* adapter used to attach this adapter to a VALE switch (if any) */
836 	struct netmap_vp_adapter *na_vp;
837 	/* adapter used to attach the host rings of this adapter
838 	 * to a VALE switch (if any) */
839 	struct netmap_vp_adapter *na_hostvp;
840 
841 	/* standard refcount to control the lifetime of the adapter
842 	 * (it should be equal to the lifetime of the corresponding ifp)
843 	 */
844 	int na_refcount;
845 
846 	/* memory allocator (opaque)
847 	 * We also cache a pointer to the lut_entry for translating
848 	 * buffer addresses, the total number of buffers and the buffer size.
849 	 */
850  	struct netmap_mem_d *nm_mem;
851 	struct netmap_mem_d *nm_mem_prev;
852 	struct netmap_lut na_lut;
853 
854 	/* additional information attached to this adapter
855 	 * by other netmap subsystems. Currently used by
856 	 * bwrap, LINUX/v1000 and ptnetmap
857 	 */
858 	void *na_private;
859 
860 	/* array of pipes that have this adapter as a parent */
861 	struct netmap_pipe_adapter **na_pipes;
862 	int na_next_pipe;	/* next free slot in the array */
863 	int na_max_pipes;	/* size of the array */
864 
865 	/* Offset of ethernet header for each packet. */
866 	u_int virt_hdr_len;
867 
868 	/* Max number of bytes that the NIC can store in the buffer
869 	 * referenced by each RX descriptor. This translates to the maximum
870 	 * bytes that a single netmap slot can reference. Larger packets
871 	 * require NS_MOREFRAG support. */
872 	unsigned rx_buf_maxsize;
873 
874 	char name[NETMAP_REQ_IFNAMSIZ]; /* used at least by pipes */
875 
876 #ifdef WITH_MONITOR
877 	unsigned long	monitor_id;	/* debugging */
878 #endif
879 };
880 
881 static __inline u_int
882 nma_get_ndesc(struct netmap_adapter *na, enum txrx t)
883 {
884 	return (t == NR_TX ? na->num_tx_desc : na->num_rx_desc);
885 }
886 
887 static __inline void
888 nma_set_ndesc(struct netmap_adapter *na, enum txrx t, u_int v)
889 {
890 	if (t == NR_TX)
891 		na->num_tx_desc = v;
892 	else
893 		na->num_rx_desc = v;
894 }
895 
896 static __inline u_int
897 nma_get_nrings(struct netmap_adapter *na, enum txrx t)
898 {
899 	return (t == NR_TX ? na->num_tx_rings : na->num_rx_rings);
900 }
901 
902 static __inline u_int
903 nma_get_host_nrings(struct netmap_adapter *na, enum txrx t)
904 {
905 	return (t == NR_TX ? na->num_host_tx_rings : na->num_host_rx_rings);
906 }
907 
908 static __inline void
909 nma_set_nrings(struct netmap_adapter *na, enum txrx t, u_int v)
910 {
911 	if (t == NR_TX)
912 		na->num_tx_rings = v;
913 	else
914 		na->num_rx_rings = v;
915 }
916 
917 static __inline void
918 nma_set_host_nrings(struct netmap_adapter *na, enum txrx t, u_int v)
919 {
920 	if (t == NR_TX)
921 		na->num_host_tx_rings = v;
922 	else
923 		na->num_host_rx_rings = v;
924 }
925 
926 static __inline struct netmap_kring**
927 NMR(struct netmap_adapter *na, enum txrx t)
928 {
929 	return (t == NR_TX ? na->tx_rings : na->rx_rings);
930 }
931 
932 int nma_intr_enable(struct netmap_adapter *na, int onoff);
933 
934 /*
935  * If the NIC is owned by the kernel
936  * (i.e., bridge), neither another bridge nor user can use it;
937  * if the NIC is owned by a user, only users can share it.
938  * Evaluation must be done under NMG_LOCK().
939  */
940 #define NETMAP_OWNED_BY_KERN(na)	((na)->na_flags & NAF_BUSY)
941 #define NETMAP_OWNED_BY_ANY(na) \
942 	(NETMAP_OWNED_BY_KERN(na) || ((na)->active_fds > 0))
943 
944 /*
945  * derived netmap adapters for various types of ports
946  */
947 struct netmap_vp_adapter {	/* VALE software port */
948 	struct netmap_adapter up;
949 
950 	/*
951 	 * Bridge support:
952 	 *
953 	 * bdg_port is the port number used in the bridge;
954 	 * na_bdg points to the bridge this NA is attached to.
955 	 */
956 	int bdg_port;
957 	struct nm_bridge *na_bdg;
958 	int retry;
959 	int autodelete; /* remove the ifp on last reference */
960 
961 	/* Maximum Frame Size, used in bdg_mismatch_datapath() */
962 	u_int mfs;
963 	/* Last source MAC on this port */
964 	uint64_t last_smac;
965 };
966 
967 
968 struct netmap_hw_adapter {	/* physical device */
969 	struct netmap_adapter up;
970 
971 #ifdef linux
972 	struct net_device_ops nm_ndo;
973 	struct ethtool_ops    nm_eto;
974 #endif
975 	const struct ethtool_ops*   save_ethtool;
976 
977 	int (*nm_hw_register)(struct netmap_adapter *, int onoff);
978 };
979 
980 #ifdef WITH_GENERIC
981 /* Mitigation support. */
982 struct nm_generic_mit {
983 	struct hrtimer mit_timer;
984 	int mit_pending;
985 	int mit_ring_idx;  /* index of the ring being mitigated */
986 	struct netmap_adapter *mit_na;  /* backpointer */
987 };
988 
989 struct netmap_generic_adapter {	/* emulated device */
990 	struct netmap_hw_adapter up;
991 
992 	/* Pointer to a previously used netmap adapter. */
993 	struct netmap_adapter *prev;
994 
995 	/* Emulated netmap adapters support:
996 	 *  - save_if_input saves the if_input hook (FreeBSD);
997 	 *  - mit implements rx interrupt mitigation;
998 	 */
999 	void (*save_if_input)(struct ifnet *, struct mbuf *);
1000 
1001 	struct nm_generic_mit *mit;
1002 #ifdef linux
1003         netdev_tx_t (*save_start_xmit)(struct mbuf *, struct ifnet *);
1004 #endif
1005 	/* Is the adapter able to use multiple RX slots to scatter
1006 	 * each packet pushed up by the driver? */
1007 	int rxsg;
1008 
1009 	/* Is the transmission path controlled by a netmap-aware
1010 	 * device queue (i.e. qdisc on linux)? */
1011 	int txqdisc;
1012 };
1013 #endif  /* WITH_GENERIC */
1014 
1015 static __inline u_int
1016 netmap_real_rings(struct netmap_adapter *na, enum txrx t)
1017 {
1018 	return nma_get_nrings(na, t) +
1019 		!!(na->na_flags & NAF_HOST_RINGS) * nma_get_host_nrings(na, t);
1020 }
1021 
1022 /* account for fake rings */
1023 static __inline u_int
1024 netmap_all_rings(struct netmap_adapter *na, enum txrx t)
1025 {
1026 	return max(nma_get_nrings(na, t) + 1, netmap_real_rings(na, t));
1027 }
1028 
1029 int netmap_default_bdg_attach(const char *name, struct netmap_adapter *na,
1030 		struct nm_bridge *);
1031 struct nm_bdg_polling_state;
1032 /*
1033  * Bridge wrapper for non VALE ports attached to a VALE switch.
1034  *
1035  * The real device must already have its own netmap adapter (hwna).
1036  * The bridge wrapper and the hwna adapter share the same set of
1037  * netmap rings and buffers, but they have two separate sets of
1038  * krings descriptors, with tx/rx meanings swapped:
1039  *
1040  *                                  netmap
1041  *           bwrap     krings       rings      krings      hwna
1042  *         +------+   +------+     +-----+    +------+   +------+
1043  *         |tx_rings->|      |\   /|     |----|      |<-tx_rings|
1044  *         |      |   +------+ \ / +-----+    +------+   |      |
1045  *         |      |             X                        |      |
1046  *         |      |            / \                       |      |
1047  *         |      |   +------+/   \+-----+    +------+   |      |
1048  *         |rx_rings->|      |     |     |----|      |<-rx_rings|
1049  *         |      |   +------+     +-----+    +------+   |      |
1050  *         +------+                                      +------+
1051  *
1052  * - packets coming from the bridge go to the brwap rx rings,
1053  *   which are also the hwna tx rings.  The bwrap notify callback
1054  *   will then complete the hwna tx (see netmap_bwrap_notify).
1055  *
1056  * - packets coming from the outside go to the hwna rx rings,
1057  *   which are also the bwrap tx rings.  The (overwritten) hwna
1058  *   notify method will then complete the bridge tx
1059  *   (see netmap_bwrap_intr_notify).
1060  *
1061  *   The bridge wrapper may optionally connect the hwna 'host' rings
1062  *   to the bridge. This is done by using a second port in the
1063  *   bridge and connecting it to the 'host' netmap_vp_adapter
1064  *   contained in the netmap_bwrap_adapter. The brwap host adapter
1065  *   cross-links the hwna host rings in the same way as shown above.
1066  *
1067  * - packets coming from the bridge and directed to the host stack
1068  *   are handled by the bwrap host notify callback
1069  *   (see netmap_bwrap_host_notify)
1070  *
1071  * - packets coming from the host stack are still handled by the
1072  *   overwritten hwna notify callback (netmap_bwrap_intr_notify),
1073  *   but are diverted to the host adapter depending on the ring number.
1074  *
1075  */
1076 struct netmap_bwrap_adapter {
1077 	struct netmap_vp_adapter up;
1078 	struct netmap_vp_adapter host;  /* for host rings */
1079 	struct netmap_adapter *hwna;	/* the underlying device */
1080 
1081 	/*
1082 	 * When we attach a physical interface to the bridge, we
1083 	 * allow the controlling process to terminate, so we need
1084 	 * a place to store the n_detmap_priv_d data structure.
1085 	 * This is only done when physical interfaces
1086 	 * are attached to a bridge.
1087 	 */
1088 	struct netmap_priv_d *na_kpriv;
1089 	struct nm_bdg_polling_state *na_polling_state;
1090 	/* we overwrite the hwna->na_vp pointer, so we save
1091 	 * here its original value, to be restored at detach
1092 	 */
1093 	struct netmap_vp_adapter *saved_na_vp;
1094 };
1095 int nm_bdg_polling(struct nmreq_header *hdr);
1096 
1097 #ifdef WITH_VALE
1098 int netmap_vale_attach(struct nmreq_header *hdr, void *auth_token);
1099 int netmap_vale_detach(struct nmreq_header *hdr, void *auth_token);
1100 int netmap_vale_list(struct nmreq_header *hdr);
1101 int netmap_vi_create(struct nmreq_header *hdr, int);
1102 int nm_vi_create(struct nmreq_header *);
1103 int nm_vi_destroy(const char *name);
1104 #else /* !WITH_VALE */
1105 #define netmap_vi_create(hdr, a) (EOPNOTSUPP)
1106 #endif /* WITH_VALE */
1107 
1108 #ifdef WITH_PIPES
1109 
1110 #define NM_MAXPIPES 	64	/* max number of pipes per adapter */
1111 
1112 struct netmap_pipe_adapter {
1113 	/* pipe identifier is up.name */
1114 	struct netmap_adapter up;
1115 
1116 #define NM_PIPE_ROLE_MASTER	0x1
1117 #define NM_PIPE_ROLE_SLAVE	0x2
1118 	int role;	/* either NM_PIPE_ROLE_MASTER or NM_PIPE_ROLE_SLAVE */
1119 
1120 	struct netmap_adapter *parent; /* adapter that owns the memory */
1121 	struct netmap_pipe_adapter *peer; /* the other end of the pipe */
1122 	int peer_ref;		/* 1 iff we are holding a ref to the peer */
1123 	struct ifnet *parent_ifp;	/* maybe null */
1124 
1125 	u_int parent_slot; /* index in the parent pipe array */
1126 };
1127 
1128 #endif /* WITH_PIPES */
1129 
1130 #ifdef WITH_NMNULL
1131 struct netmap_null_adapter {
1132 	struct netmap_adapter up;
1133 };
1134 #endif /* WITH_NMNULL */
1135 
1136 
1137 /* return slots reserved to rx clients; used in drivers */
1138 static inline uint32_t
1139 nm_kr_rxspace(struct netmap_kring *k)
1140 {
1141 	int space = k->nr_hwtail - k->nr_hwcur;
1142 	if (space < 0)
1143 		space += k->nkr_num_slots;
1144 	nm_prdis("preserving %d rx slots %d -> %d", space, k->nr_hwcur, k->nr_hwtail);
1145 
1146 	return space;
1147 }
1148 
1149 /* return slots reserved to tx clients */
1150 #define nm_kr_txspace(_k) nm_kr_rxspace(_k)
1151 
1152 
1153 /* True if no space in the tx ring, only valid after txsync_prologue */
1154 static inline int
1155 nm_kr_txempty(struct netmap_kring *kring)
1156 {
1157 	return kring->rhead == kring->nr_hwtail;
1158 }
1159 
1160 /* True if no more completed slots in the rx ring, only valid after
1161  * rxsync_prologue */
1162 #define nm_kr_rxempty(_k)	nm_kr_txempty(_k)
1163 
1164 /* True if the application needs to wait for more space on the ring
1165  * (more received packets or more free tx slots).
1166  * Only valid after *xsync_prologue. */
1167 static inline int
1168 nm_kr_wouldblock(struct netmap_kring *kring)
1169 {
1170 	return kring->rcur == kring->nr_hwtail;
1171 }
1172 
1173 /*
1174  * protect against multiple threads using the same ring.
1175  * also check that the ring has not been stopped or locked
1176  */
1177 #define NM_KR_BUSY	1	/* some other thread is syncing the ring */
1178 #define NM_KR_STOPPED	2	/* unbounded stop (ifconfig down or driver unload) */
1179 #define NM_KR_LOCKED	3	/* bounded, brief stop for mutual exclusion */
1180 
1181 
1182 /* release the previously acquired right to use the *sync() methods of the ring */
1183 static __inline void nm_kr_put(struct netmap_kring *kr)
1184 {
1185 	NM_ATOMIC_CLEAR(&kr->nr_busy);
1186 }
1187 
1188 
1189 /* true if the ifp that backed the adapter has disappeared (e.g., the
1190  * driver has been unloaded)
1191  */
1192 static inline int nm_iszombie(struct netmap_adapter *na);
1193 
1194 /* try to obtain exclusive right to issue the *sync() operations on the ring.
1195  * The right is obtained and must be later relinquished via nm_kr_put() if and
1196  * only if nm_kr_tryget() returns 0.
1197  * If can_sleep is 1 there are only two other possible outcomes:
1198  * - the function returns NM_KR_BUSY
1199  * - the function returns NM_KR_STOPPED and sets the POLLERR bit in *perr
1200  *   (if non-null)
1201  * In both cases the caller will typically skip the ring, possibly collecting
1202  * errors along the way.
1203  * If the calling context does not allow sleeping, the caller must pass 0 in can_sleep.
1204  * In the latter case, the function may also return NM_KR_LOCKED and leave *perr
1205  * untouched: ideally, the caller should try again at a later time.
1206  */
1207 static __inline int nm_kr_tryget(struct netmap_kring *kr, int can_sleep, int *perr)
1208 {
1209 	int busy = 1, stopped;
1210 	/* check a first time without taking the lock
1211 	 * to avoid starvation for nm_kr_get()
1212 	 */
1213 retry:
1214 	stopped = kr->nkr_stopped;
1215 	if (unlikely(stopped)) {
1216 		goto stop;
1217 	}
1218 	busy = NM_ATOMIC_TEST_AND_SET(&kr->nr_busy);
1219 	/* we should not return NM_KR_BUSY if the ring was
1220 	 * actually stopped, so check another time after
1221 	 * the barrier provided by the atomic operation
1222 	 */
1223 	stopped = kr->nkr_stopped;
1224 	if (unlikely(stopped)) {
1225 		goto stop;
1226 	}
1227 
1228 	if (unlikely(nm_iszombie(kr->na))) {
1229 		stopped = NM_KR_STOPPED;
1230 		goto stop;
1231 	}
1232 
1233 	return unlikely(busy) ? NM_KR_BUSY : 0;
1234 
1235 stop:
1236 	if (!busy)
1237 		nm_kr_put(kr);
1238 	if (stopped == NM_KR_STOPPED) {
1239 /* if POLLERR is defined we want to use it to simplify netmap_poll().
1240  * Otherwise, any non-zero value will do.
1241  */
1242 #ifdef POLLERR
1243 #define NM_POLLERR POLLERR
1244 #else
1245 #define NM_POLLERR 1
1246 #endif /* POLLERR */
1247 		if (perr)
1248 			*perr |= NM_POLLERR;
1249 #undef NM_POLLERR
1250 	} else if (can_sleep) {
1251 		tsleep(kr, 0, "NM_KR_TRYGET", 4);
1252 		goto retry;
1253 	}
1254 	return stopped;
1255 }
1256 
1257 /* put the ring in the 'stopped' state and wait for the current user (if any) to
1258  * notice. stopped must be either NM_KR_STOPPED or NM_KR_LOCKED
1259  */
1260 static __inline void nm_kr_stop(struct netmap_kring *kr, int stopped)
1261 {
1262 	kr->nkr_stopped = stopped;
1263 	while (NM_ATOMIC_TEST_AND_SET(&kr->nr_busy))
1264 		tsleep(kr, 0, "NM_KR_GET", 4);
1265 }
1266 
1267 /* restart a ring after a stop */
1268 static __inline void nm_kr_start(struct netmap_kring *kr)
1269 {
1270 	kr->nkr_stopped = 0;
1271 	nm_kr_put(kr);
1272 }
1273 
1274 
1275 /*
1276  * The following functions are used by individual drivers to
1277  * support netmap operation.
1278  *
1279  * netmap_attach() initializes a struct netmap_adapter, allocating the
1280  * 	struct netmap_ring's and the struct selinfo.
1281  *
1282  * netmap_detach() frees the memory allocated by netmap_attach().
1283  *
1284  * netmap_transmit() replaces the if_transmit routine of the interface,
1285  *	and is used to intercept packets coming from the stack.
1286  *
1287  * netmap_load_map/netmap_reload_map are helper routines to set/reset
1288  *	the dmamap for a packet buffer
1289  *
1290  * netmap_reset() is a helper routine to be called in the hw driver
1291  *	when reinitializing a ring. It should not be called by
1292  *	virtual ports (vale, pipes, monitor)
1293  */
1294 int netmap_attach(struct netmap_adapter *);
1295 int netmap_attach_ext(struct netmap_adapter *, size_t size, int override_reg);
1296 void netmap_detach(struct ifnet *);
1297 int netmap_transmit(struct ifnet *, struct mbuf *);
1298 struct netmap_slot *netmap_reset(struct netmap_adapter *na,
1299 	enum txrx tx, u_int n, u_int new_cur);
1300 int netmap_ring_reinit(struct netmap_kring *);
1301 int netmap_rings_config_get(struct netmap_adapter *, struct nm_config_info *);
1302 
1303 /* Return codes for netmap_*x_irq. */
1304 enum {
1305 	/* Driver should do normal interrupt processing, e.g. because
1306 	 * the interface is not in netmap mode. */
1307 	NM_IRQ_PASS = 0,
1308 	/* Port is in netmap mode, and the interrupt work has been
1309 	 * completed. The driver does not have to notify netmap
1310 	 * again before the next interrupt. */
1311 	NM_IRQ_COMPLETED = -1,
1312 	/* Port is in netmap mode, but the interrupt work has not been
1313 	 * completed. The driver has to make sure netmap will be
1314 	 * notified again soon, even if no more interrupts come (e.g.
1315 	 * on Linux the driver should not call napi_complete()). */
1316 	NM_IRQ_RESCHED = -2,
1317 };
1318 
1319 /* default functions to handle rx/tx interrupts */
1320 int netmap_rx_irq(struct ifnet *, u_int, u_int *);
1321 #define netmap_tx_irq(_n, _q) netmap_rx_irq(_n, _q, NULL)
1322 int netmap_common_irq(struct netmap_adapter *, u_int, u_int *work_done);
1323 
1324 
1325 #ifdef WITH_VALE
1326 /* functions used by external modules to interface with VALE */
1327 #define netmap_vp_to_ifp(_vp)	((_vp)->up.ifp)
1328 #define netmap_ifp_to_vp(_ifp)	(NA(_ifp)->na_vp)
1329 #define netmap_ifp_to_host_vp(_ifp) (NA(_ifp)->na_hostvp)
1330 #define netmap_bdg_idx(_vp)	((_vp)->bdg_port)
1331 const char *netmap_bdg_name(struct netmap_vp_adapter *);
1332 #else /* !WITH_VALE */
1333 #define netmap_vp_to_ifp(_vp)	NULL
1334 #define netmap_ifp_to_vp(_ifp)	NULL
1335 #define netmap_ifp_to_host_vp(_ifp) NULL
1336 #define netmap_bdg_idx(_vp)	-1
1337 #endif /* WITH_VALE */
1338 
1339 static inline int
1340 nm_netmap_on(struct netmap_adapter *na)
1341 {
1342 	return na && na->na_flags & NAF_NETMAP_ON;
1343 }
1344 
1345 static inline int
1346 nm_native_on(struct netmap_adapter *na)
1347 {
1348 	return nm_netmap_on(na) && (na->na_flags & NAF_NATIVE);
1349 }
1350 
1351 static inline int
1352 nm_iszombie(struct netmap_adapter *na)
1353 {
1354 	return na == NULL || (na->na_flags & NAF_ZOMBIE);
1355 }
1356 
1357 static inline void
1358 nm_update_hostrings_mode(struct netmap_adapter *na)
1359 {
1360 	/* Process nr_mode and nr_pending_mode for host rings. */
1361 	na->tx_rings[na->num_tx_rings]->nr_mode =
1362 		na->tx_rings[na->num_tx_rings]->nr_pending_mode;
1363 	na->rx_rings[na->num_rx_rings]->nr_mode =
1364 		na->rx_rings[na->num_rx_rings]->nr_pending_mode;
1365 }
1366 
1367 void nm_set_native_flags(struct netmap_adapter *);
1368 void nm_clear_native_flags(struct netmap_adapter *);
1369 
1370 void netmap_krings_mode_commit(struct netmap_adapter *na, int onoff);
1371 
1372 /*
1373  * nm_*sync_prologue() functions are used in ioctl/poll and ptnetmap
1374  * kthreads.
1375  * We need netmap_ring* parameter, because in ptnetmap it is decoupled
1376  * from host kring.
1377  * The user-space ring pointers (head/cur/tail) are shared through
1378  * CSB between host and guest.
1379  */
1380 
1381 /*
1382  * validates parameters in the ring/kring, returns a value for head
1383  * If any error, returns ring_size to force a reinit.
1384  */
1385 uint32_t nm_txsync_prologue(struct netmap_kring *, struct netmap_ring *);
1386 
1387 
1388 /*
1389  * validates parameters in the ring/kring, returns a value for head
1390  * If any error, returns ring_size lim to force a reinit.
1391  */
1392 uint32_t nm_rxsync_prologue(struct netmap_kring *, struct netmap_ring *);
1393 
1394 
1395 /* check/fix address and len in tx rings */
1396 #if 1 /* debug version */
1397 #define	NM_CHECK_ADDR_LEN(_na, _a, _l)	do {				\
1398 	if (_a == NETMAP_BUF_BASE(_na) || _l > NETMAP_BUF_SIZE(_na)) {	\
1399 		nm_prlim(5, "bad addr/len ring %d slot %d idx %d len %d",	\
1400 			kring->ring_id, nm_i, slot->buf_idx, len);	\
1401 		if (_l > NETMAP_BUF_SIZE(_na))				\
1402 			_l = NETMAP_BUF_SIZE(_na);			\
1403 	} } while (0)
1404 #else /* no debug version */
1405 #define	NM_CHECK_ADDR_LEN(_na, _a, _l)	do {				\
1406 		if (_l > NETMAP_BUF_SIZE(_na))				\
1407 			_l = NETMAP_BUF_SIZE(_na);			\
1408 	} while (0)
1409 #endif
1410 
1411 
1412 /*---------------------------------------------------------------*/
1413 /*
1414  * Support routines used by netmap subsystems
1415  * (native drivers, VALE, generic, pipes, monitors, ...)
1416  */
1417 
1418 
1419 /* common routine for all functions that create a netmap adapter. It performs
1420  * two main tasks:
1421  * - if the na points to an ifp, mark the ifp as netmap capable
1422  *   using na as its native adapter;
1423  * - provide defaults for the setup callbacks and the memory allocator
1424  */
1425 int netmap_attach_common(struct netmap_adapter *);
1426 /* fill priv->np_[tr]xq{first,last} using the ringid and flags information
1427  * coming from a struct nmreq_register
1428  */
1429 int netmap_interp_ringid(struct netmap_priv_d *priv, uint32_t nr_mode,
1430 			uint16_t nr_ringid, uint64_t nr_flags);
1431 /* update the ring parameters (number and size of tx and rx rings).
1432  * It calls the nm_config callback, if available.
1433  */
1434 int netmap_update_config(struct netmap_adapter *na);
1435 /* create and initialize the common fields of the krings array.
1436  * using the information that must be already available in the na.
1437  * tailroom can be used to request the allocation of additional
1438  * tailroom bytes after the krings array. This is used by
1439  * netmap_vp_adapter's (i.e., VALE ports) to make room for
1440  * leasing-related data structures
1441  */
1442 int netmap_krings_create(struct netmap_adapter *na, u_int tailroom);
1443 /* deletes the kring array of the adapter. The array must have
1444  * been created using netmap_krings_create
1445  */
1446 void netmap_krings_delete(struct netmap_adapter *na);
1447 
1448 int netmap_hw_krings_create(struct netmap_adapter *na);
1449 void netmap_hw_krings_delete(struct netmap_adapter *na);
1450 
1451 /* set the stopped/enabled status of ring
1452  * When stopping, they also wait for all current activity on the ring to
1453  * terminate. The status change is then notified using the na nm_notify
1454  * callback.
1455  */
1456 void netmap_set_ring(struct netmap_adapter *, u_int ring_id, enum txrx, int stopped);
1457 /* set the stopped/enabled status of all rings of the adapter. */
1458 void netmap_set_all_rings(struct netmap_adapter *, int stopped);
1459 /* convenience wrappers for netmap_set_all_rings */
1460 void netmap_disable_all_rings(struct ifnet *);
1461 void netmap_enable_all_rings(struct ifnet *);
1462 
1463 int netmap_buf_size_validate(const struct netmap_adapter *na, unsigned mtu);
1464 int netmap_do_regif(struct netmap_priv_d *priv, struct netmap_adapter *na,
1465 		uint32_t nr_mode, uint16_t nr_ringid, uint64_t nr_flags);
1466 void netmap_do_unregif(struct netmap_priv_d *priv);
1467 
1468 u_int nm_bound_var(u_int *v, u_int dflt, u_int lo, u_int hi, const char *msg);
1469 int netmap_get_na(struct nmreq_header *hdr, struct netmap_adapter **na,
1470 		struct ifnet **ifp, struct netmap_mem_d *nmd, int create);
1471 void netmap_unget_na(struct netmap_adapter *na, struct ifnet *ifp);
1472 int netmap_get_hw_na(struct ifnet *ifp,
1473 		struct netmap_mem_d *nmd, struct netmap_adapter **na);
1474 
1475 #ifdef WITH_VALE
1476 uint32_t netmap_vale_learning(struct nm_bdg_fwd *ft, uint8_t *dst_ring,
1477 		struct netmap_vp_adapter *, void *private_data);
1478 
1479 /* these are redefined in case of no VALE support */
1480 int netmap_get_vale_na(struct nmreq_header *hdr, struct netmap_adapter **na,
1481 		struct netmap_mem_d *nmd, int create);
1482 void *netmap_vale_create(const char *bdg_name, int *return_status);
1483 int netmap_vale_destroy(const char *bdg_name, void *auth_token);
1484 
1485 #else /* !WITH_VALE */
1486 #define netmap_bdg_learning(_1, _2, _3, _4)	0
1487 #define	netmap_get_vale_na(_1, _2, _3, _4)	0
1488 #define netmap_bdg_create(_1, _2)	NULL
1489 #define netmap_bdg_destroy(_1, _2)	0
1490 #endif /* !WITH_VALE */
1491 
1492 #ifdef WITH_PIPES
1493 /* max number of pipes per device */
1494 #define NM_MAXPIPES	64	/* XXX this should probably be a sysctl */
1495 void netmap_pipe_dealloc(struct netmap_adapter *);
1496 int netmap_get_pipe_na(struct nmreq_header *hdr, struct netmap_adapter **na,
1497 			struct netmap_mem_d *nmd, int create);
1498 #else /* !WITH_PIPES */
1499 #define NM_MAXPIPES	0
1500 #define netmap_pipe_alloc(_1, _2) 	0
1501 #define netmap_pipe_dealloc(_1)
1502 #define netmap_get_pipe_na(hdr, _2, _3, _4)	\
1503 	((strchr(hdr->nr_name, '{') != NULL || strchr(hdr->nr_name, '}') != NULL) ? EOPNOTSUPP : 0)
1504 #endif
1505 
1506 #ifdef WITH_MONITOR
1507 int netmap_get_monitor_na(struct nmreq_header *hdr, struct netmap_adapter **na,
1508 		struct netmap_mem_d *nmd, int create);
1509 void netmap_monitor_stop(struct netmap_adapter *na);
1510 #else
1511 #define netmap_get_monitor_na(hdr, _2, _3, _4) \
1512 	(((struct nmreq_register *)(uintptr_t)hdr->nr_body)->nr_flags & (NR_MONITOR_TX | NR_MONITOR_RX) ? EOPNOTSUPP : 0)
1513 #endif
1514 
1515 #ifdef WITH_NMNULL
1516 int netmap_get_null_na(struct nmreq_header *hdr, struct netmap_adapter **na,
1517 		struct netmap_mem_d *nmd, int create);
1518 #else /* !WITH_NMNULL */
1519 #define netmap_get_null_na(hdr, _2, _3, _4) \
1520 	(((struct nmreq_register *)(uintptr_t)hdr->nr_body)->nr_flags & (NR_MONITOR_TX | NR_MONITOR_RX) ? EOPNOTSUPP : 0)
1521 #endif /* WITH_NMNULL */
1522 
1523 #ifdef CONFIG_NET_NS
1524 struct net *netmap_bns_get(void);
1525 void netmap_bns_put(struct net *);
1526 void netmap_bns_getbridges(struct nm_bridge **, u_int *);
1527 #else
1528 extern struct nm_bridge *nm_bridges;
1529 #define netmap_bns_get()
1530 #define netmap_bns_put(_1)
1531 #define netmap_bns_getbridges(b, n) \
1532 	do { *b = nm_bridges; *n = NM_BRIDGES; } while (0)
1533 #endif
1534 
1535 /* Various prototypes */
1536 int netmap_poll(struct netmap_priv_d *, int events, NM_SELRECORD_T *td);
1537 int netmap_init(void);
1538 void netmap_fini(void);
1539 int netmap_get_memory(struct netmap_priv_d* p);
1540 void netmap_dtor(void *data);
1541 
1542 int netmap_ioctl(struct netmap_priv_d *priv, u_long cmd, caddr_t data,
1543 		struct thread *, int nr_body_is_user);
1544 int netmap_ioctl_legacy(struct netmap_priv_d *priv, u_long cmd, caddr_t data,
1545 			struct thread *td);
1546 size_t nmreq_size_by_type(uint16_t nr_reqtype);
1547 
1548 /* netmap_adapter creation/destruction */
1549 
1550 // #define NM_DEBUG_PUTGET 1
1551 
1552 #ifdef NM_DEBUG_PUTGET
1553 
1554 #define NM_DBG(f) __##f
1555 
1556 void __netmap_adapter_get(struct netmap_adapter *na);
1557 
1558 #define netmap_adapter_get(na) 				\
1559 	do {						\
1560 		struct netmap_adapter *__na = na;	\
1561 		nm_prinf("getting %p:%s (%d)", __na, (__na)->name, (__na)->na_refcount);	\
1562 		__netmap_adapter_get(__na);		\
1563 	} while (0)
1564 
1565 int __netmap_adapter_put(struct netmap_adapter *na);
1566 
1567 #define netmap_adapter_put(na)				\
1568 	({						\
1569 		struct netmap_adapter *__na = na;	\
1570 		nm_prinf("putting %p:%s (%d)", __na, (__na)->name, (__na)->na_refcount);	\
1571 		__netmap_adapter_put(__na);		\
1572 	})
1573 
1574 #else /* !NM_DEBUG_PUTGET */
1575 
1576 #define NM_DBG(f) f
1577 void netmap_adapter_get(struct netmap_adapter *na);
1578 int netmap_adapter_put(struct netmap_adapter *na);
1579 
1580 #endif /* !NM_DEBUG_PUTGET */
1581 
1582 
1583 /*
1584  * module variables
1585  */
1586 #define NETMAP_BUF_BASE(_na)	((_na)->na_lut.lut[0].vaddr)
1587 #define NETMAP_BUF_SIZE(_na)	((_na)->na_lut.objsize)
1588 extern int netmap_no_pendintr;
1589 extern int netmap_mitigate;
1590 extern int netmap_verbose;
1591 #ifdef CONFIG_NETMAP_DEBUG
1592 extern int netmap_debug;		/* for debugging */
1593 #else /* !CONFIG_NETMAP_DEBUG */
1594 #define netmap_debug (0)
1595 #endif /* !CONFIG_NETMAP_DEBUG */
1596 enum {                                  /* debug flags */
1597 	NM_DEBUG_ON = 1,		/* generic debug messsages */
1598 	NM_DEBUG_HOST = 0x2,            /* debug host stack */
1599 	NM_DEBUG_RXSYNC = 0x10,         /* debug on rxsync/txsync */
1600 	NM_DEBUG_TXSYNC = 0x20,
1601 	NM_DEBUG_RXINTR = 0x100,        /* debug on rx/tx intr (driver) */
1602 	NM_DEBUG_TXINTR = 0x200,
1603 	NM_DEBUG_NIC_RXSYNC = 0x1000,   /* debug on rx/tx intr (driver) */
1604 	NM_DEBUG_NIC_TXSYNC = 0x2000,
1605 	NM_DEBUG_MEM = 0x4000,		/* verbose memory allocations/deallocations */
1606 	NM_DEBUG_VALE = 0x8000,		/* debug messages from memory allocators */
1607 	NM_DEBUG_BDG = NM_DEBUG_VALE,
1608 };
1609 
1610 extern int netmap_txsync_retry;
1611 extern int netmap_flags;
1612 extern int netmap_generic_hwcsum;
1613 extern int netmap_generic_mit;
1614 extern int netmap_generic_ringsize;
1615 extern int netmap_generic_rings;
1616 #ifdef linux
1617 extern int netmap_generic_txqdisc;
1618 #endif
1619 
1620 /*
1621  * NA returns a pointer to the struct netmap adapter from the ifp.
1622  * WNA is os-specific and must be defined in glue code.
1623  */
1624 #define	NA(_ifp)	((struct netmap_adapter *)WNA(_ifp))
1625 
1626 /*
1627  * we provide a default implementation of NM_ATTACH_NA/NM_DETACH_NA
1628  * based on the WNA field.
1629  * Glue code may override this by defining its own NM_ATTACH_NA
1630  */
1631 #ifndef NM_ATTACH_NA
1632 /*
1633  * On old versions of FreeBSD, NA(ifp) is a pspare. On linux we
1634  * overload another pointer in the netdev.
1635  *
1636  * We check if NA(ifp) is set and its first element has a related
1637  * magic value. The capenable is within the struct netmap_adapter.
1638  */
1639 #define	NETMAP_MAGIC	0x52697a7a
1640 
1641 #define NM_NA_VALID(ifp)	(NA(ifp) &&		\
1642 	((uint32_t)(uintptr_t)NA(ifp) ^ NA(ifp)->magic) == NETMAP_MAGIC )
1643 
1644 #define	NM_ATTACH_NA(ifp, na) do {					\
1645 	WNA(ifp) = na;							\
1646 	if (NA(ifp))							\
1647 		NA(ifp)->magic = 					\
1648 			((uint32_t)(uintptr_t)NA(ifp)) ^ NETMAP_MAGIC;	\
1649 } while(0)
1650 #define NM_RESTORE_NA(ifp, na) 	WNA(ifp) = na;
1651 
1652 #define NM_DETACH_NA(ifp)	do { WNA(ifp) = NULL; } while (0)
1653 #define NM_NA_CLASH(ifp)	(NA(ifp) && !NM_NA_VALID(ifp))
1654 #endif /* !NM_ATTACH_NA */
1655 
1656 
1657 #define NM_IS_NATIVE(ifp)	(NM_NA_VALID(ifp) && NA(ifp)->nm_dtor == netmap_hw_dtor)
1658 
1659 #if defined(__FreeBSD__)
1660 
1661 /* Assigns the device IOMMU domain to an allocator.
1662  * Returns -ENOMEM in case the domain is different */
1663 #define nm_iommu_group_id(dev) (0)
1664 
1665 /* Callback invoked by the dma machinery after a successful dmamap_load */
1666 static void netmap_dmamap_cb(__unused void *arg,
1667     __unused bus_dma_segment_t * segs, __unused int nseg, __unused int error)
1668 {
1669 }
1670 
1671 /* bus_dmamap_load wrapper: call aforementioned function if map != NULL.
1672  * XXX can we do it without a callback ?
1673  */
1674 static inline int
1675 netmap_load_map(struct netmap_adapter *na,
1676 	bus_dma_tag_t tag, bus_dmamap_t map, void *buf)
1677 {
1678 	if (map)
1679 		bus_dmamap_load(tag, map, buf, NETMAP_BUF_SIZE(na),
1680 		    netmap_dmamap_cb, NULL, BUS_DMA_NOWAIT);
1681 	return 0;
1682 }
1683 
1684 static inline void
1685 netmap_unload_map(struct netmap_adapter *na,
1686         bus_dma_tag_t tag, bus_dmamap_t map)
1687 {
1688 	if (map)
1689 		bus_dmamap_unload(tag, map);
1690 }
1691 
1692 #define netmap_sync_map(na, tag, map, sz, t)
1693 
1694 /* update the map when a buffer changes. */
1695 static inline void
1696 netmap_reload_map(struct netmap_adapter *na,
1697 	bus_dma_tag_t tag, bus_dmamap_t map, void *buf)
1698 {
1699 	if (map) {
1700 		bus_dmamap_unload(tag, map);
1701 		bus_dmamap_load(tag, map, buf, NETMAP_BUF_SIZE(na),
1702 		    netmap_dmamap_cb, NULL, BUS_DMA_NOWAIT);
1703 	}
1704 }
1705 
1706 #elif defined(_WIN32)
1707 
1708 #else /* linux */
1709 
1710 int nm_iommu_group_id(bus_dma_tag_t dev);
1711 #include <linux/dma-mapping.h>
1712 
1713 /*
1714  * on linux we need
1715  *	dma_map_single(&pdev->dev, virt_addr, len, direction)
1716  *	dma_unmap_single(&adapter->pdev->dev, phys_addr, len, direction)
1717  */
1718 #if 0
1719 	struct e1000_buffer *buffer_info =  &tx_ring->buffer_info[l];
1720 	/* set time_stamp *before* dma to help avoid a possible race */
1721 	buffer_info->time_stamp = jiffies;
1722 	buffer_info->mapped_as_page = false;
1723 	buffer_info->length = len;
1724 	//buffer_info->next_to_watch = l;
1725 	/* reload dma map */
1726 	dma_unmap_single(&adapter->pdev->dev, buffer_info->dma,
1727 			NETMAP_BUF_SIZE, DMA_TO_DEVICE);
1728 	buffer_info->dma = dma_map_single(&adapter->pdev->dev,
1729 			addr, NETMAP_BUF_SIZE, DMA_TO_DEVICE);
1730 
1731 	if (dma_mapping_error(&adapter->pdev->dev, buffer_info->dma)) {
1732 		nm_prerr("dma mapping error");
1733 		/* goto dma_error; See e1000_put_txbuf() */
1734 		/* XXX reset */
1735 	}
1736 	tx_desc->buffer_addr = htole64(buffer_info->dma); //XXX
1737 
1738 #endif
1739 
1740 static inline int
1741 netmap_load_map(struct netmap_adapter *na,
1742 	bus_dma_tag_t tag, bus_dmamap_t map, void *buf, u_int size)
1743 {
1744 	if (map) {
1745 		*map = dma_map_single(na->pdev, buf, size,
1746 				      DMA_BIDIRECTIONAL);
1747 		if (dma_mapping_error(na->pdev, *map)) {
1748 			*map = 0;
1749 			return ENOMEM;
1750 		}
1751 	}
1752 	return 0;
1753 }
1754 
1755 static inline void
1756 netmap_unload_map(struct netmap_adapter *na,
1757 	bus_dma_tag_t tag, bus_dmamap_t map, u_int sz)
1758 {
1759 	if (*map) {
1760 		dma_unmap_single(na->pdev, *map, sz,
1761 				 DMA_BIDIRECTIONAL);
1762 	}
1763 }
1764 
1765 #ifdef NETMAP_LINUX_HAVE_DMASYNC
1766 static inline void
1767 netmap_sync_map_cpu(struct netmap_adapter *na,
1768 	bus_dma_tag_t tag, bus_dmamap_t map, u_int sz, enum txrx t)
1769 {
1770 	if (*map) {
1771 		dma_sync_single_for_cpu(na->pdev, *map, sz,
1772 			(t == NR_TX ? DMA_TO_DEVICE : DMA_FROM_DEVICE));
1773 	}
1774 }
1775 
1776 static inline void
1777 netmap_sync_map_dev(struct netmap_adapter *na,
1778 	bus_dma_tag_t tag, bus_dmamap_t map, u_int sz, enum txrx t)
1779 {
1780 	if (*map) {
1781 		dma_sync_single_for_device(na->pdev, *map, sz,
1782 			(t == NR_TX ? DMA_TO_DEVICE : DMA_FROM_DEVICE));
1783 	}
1784 }
1785 
1786 static inline void
1787 netmap_reload_map(struct netmap_adapter *na,
1788 	bus_dma_tag_t tag, bus_dmamap_t map, void *buf)
1789 {
1790 	u_int sz = NETMAP_BUF_SIZE(na);
1791 
1792 	if (*map) {
1793 		dma_unmap_single(na->pdev, *map, sz,
1794 				DMA_BIDIRECTIONAL);
1795 	}
1796 
1797 	*map = dma_map_single(na->pdev, buf, sz,
1798 				DMA_BIDIRECTIONAL);
1799 }
1800 #else /* !NETMAP_LINUX_HAVE_DMASYNC */
1801 #define netmap_sync_map_cpu(na, tag, map, sz, t)
1802 #define netmap_sync_map_dev(na, tag, map, sz, t)
1803 #endif /* NETMAP_LINUX_HAVE_DMASYNC */
1804 
1805 #endif /* linux */
1806 
1807 
1808 /*
1809  * functions to map NIC to KRING indexes (n2k) and vice versa (k2n)
1810  */
1811 static inline int
1812 netmap_idx_n2k(struct netmap_kring *kr, int idx)
1813 {
1814 	int n = kr->nkr_num_slots;
1815 
1816 	if (likely(kr->nkr_hwofs == 0)) {
1817 		return idx;
1818 	}
1819 
1820 	idx += kr->nkr_hwofs;
1821 	if (idx < 0)
1822 		return idx + n;
1823 	else if (idx < n)
1824 		return idx;
1825 	else
1826 		return idx - n;
1827 }
1828 
1829 
1830 static inline int
1831 netmap_idx_k2n(struct netmap_kring *kr, int idx)
1832 {
1833 	int n = kr->nkr_num_slots;
1834 
1835 	if (likely(kr->nkr_hwofs == 0)) {
1836 		return idx;
1837 	}
1838 
1839 	idx -= kr->nkr_hwofs;
1840 	if (idx < 0)
1841 		return idx + n;
1842 	else if (idx < n)
1843 		return idx;
1844 	else
1845 		return idx - n;
1846 }
1847 
1848 
1849 /* Entries of the look-up table. */
1850 #ifdef __FreeBSD__
1851 struct lut_entry {
1852 	void *vaddr;		/* virtual address. */
1853 	vm_paddr_t paddr;	/* physical address. */
1854 };
1855 #else /* linux & _WIN32 */
1856 /* dma-mapping in linux can assign a buffer a different address
1857  * depending on the device, so we need to have a separate
1858  * physical-address look-up table for each na.
1859  * We can still share the vaddrs, though, therefore we split
1860  * the lut_entry structure.
1861  */
1862 struct lut_entry {
1863 	void *vaddr;		/* virtual address. */
1864 };
1865 
1866 struct plut_entry {
1867 	vm_paddr_t paddr;	/* physical address. */
1868 };
1869 #endif /* linux & _WIN32 */
1870 
1871 struct netmap_obj_pool;
1872 
1873 /*
1874  * NMB return the virtual address of a buffer (buffer 0 on bad index)
1875  * PNMB also fills the physical address
1876  */
1877 static inline void *
1878 NMB(struct netmap_adapter *na, struct netmap_slot *slot)
1879 {
1880 	struct lut_entry *lut = na->na_lut.lut;
1881 	uint32_t i = slot->buf_idx;
1882 	return (unlikely(i >= na->na_lut.objtotal)) ?
1883 		lut[0].vaddr : lut[i].vaddr;
1884 }
1885 
1886 static inline void *
1887 PNMB(struct netmap_adapter *na, struct netmap_slot *slot, uint64_t *pp)
1888 {
1889 	uint32_t i = slot->buf_idx;
1890 	struct lut_entry *lut = na->na_lut.lut;
1891 	struct plut_entry *plut = na->na_lut.plut;
1892 	void *ret = (i >= na->na_lut.objtotal) ? lut[0].vaddr : lut[i].vaddr;
1893 
1894 #ifdef _WIN32
1895 	*pp = (i >= na->na_lut.objtotal) ? (uint64_t)plut[0].paddr.QuadPart : (uint64_t)plut[i].paddr.QuadPart;
1896 #else
1897 	*pp = (i >= na->na_lut.objtotal) ? plut[0].paddr : plut[i].paddr;
1898 #endif
1899 	return ret;
1900 }
1901 
1902 
1903 /*
1904  * Structure associated to each netmap file descriptor.
1905  * It is created on open and left unbound (np_nifp == NULL).
1906  * A successful NIOCREGIF will set np_nifp and the first few fields;
1907  * this is protected by a global lock (NMG_LOCK) due to low contention.
1908  *
1909  * np_refs counts the number of references to the structure: one for the fd,
1910  * plus (on FreeBSD) one for each active mmap which we track ourselves
1911  * (linux automatically tracks them, but FreeBSD does not).
1912  * np_refs is protected by NMG_LOCK.
1913  *
1914  * Read access to the structure is lock free, because ni_nifp once set
1915  * can only go to 0 when nobody is using the entry anymore. Readers
1916  * must check that np_nifp != NULL before using the other fields.
1917  */
1918 struct netmap_priv_d {
1919 	struct netmap_if * volatile np_nifp;	/* netmap if descriptor. */
1920 
1921 	struct netmap_adapter	*np_na;
1922 	struct ifnet	*np_ifp;
1923 	uint32_t	np_flags;	/* from the ioctl */
1924 	u_int		np_qfirst[NR_TXRX],
1925 			np_qlast[NR_TXRX]; /* range of tx/rx rings to scan */
1926 	uint16_t	np_txpoll;
1927 	uint16_t        np_kloop_state;	/* use with NMG_LOCK held */
1928 #define NM_SYNC_KLOOP_RUNNING	(1 << 0)
1929 #define NM_SYNC_KLOOP_STOPPING	(1 << 1)
1930 	int             np_sync_flags; /* to be passed to nm_sync */
1931 
1932 	int		np_refs;	/* use with NMG_LOCK held */
1933 
1934 	/* pointers to the selinfo to be used for selrecord.
1935 	 * Either the local or the global one depending on the
1936 	 * number of rings.
1937 	 */
1938 	NM_SELINFO_T *np_si[NR_TXRX];
1939 
1940 	/* In the optional CSB mode, the user must specify the start address
1941 	 * of two arrays of Communication Status Block (CSB) entries, for the
1942 	 * two directions (kernel read application write, and kernel write
1943 	 * application read).
1944 	 * The number of entries must agree with the number of rings bound to
1945 	 * the netmap file descriptor. The entries corresponding to the TX
1946 	 * rings are laid out before the ones corresponding to the RX rings.
1947 	 *
1948 	 * Array of CSB entries for application --> kernel communication
1949 	 * (N entries). */
1950 	struct nm_csb_atok	*np_csb_atok_base;
1951 	/* Array of CSB entries for kernel --> application communication
1952 	 * (N entries). */
1953 	struct nm_csb_ktoa	*np_csb_ktoa_base;
1954 
1955 #ifdef linux
1956 	struct file	*np_filp;  /* used by sync kloop */
1957 #endif /* linux */
1958 };
1959 
1960 struct netmap_priv_d *netmap_priv_new(void);
1961 void netmap_priv_delete(struct netmap_priv_d *);
1962 
1963 static inline int nm_kring_pending(struct netmap_priv_d *np)
1964 {
1965 	struct netmap_adapter *na = np->np_na;
1966 	enum txrx t;
1967 	int i;
1968 
1969 	for_rx_tx(t) {
1970 		for (i = np->np_qfirst[t]; i < np->np_qlast[t]; i++) {
1971 			struct netmap_kring *kring = NMR(na, t)[i];
1972 			if (kring->nr_mode != kring->nr_pending_mode) {
1973 				return 1;
1974 			}
1975 		}
1976 	}
1977 	return 0;
1978 }
1979 
1980 /* call with NMG_LOCK held */
1981 static __inline int
1982 nm_si_user(struct netmap_priv_d *priv, enum txrx t)
1983 {
1984 	return (priv->np_na != NULL &&
1985 		(priv->np_qlast[t] - priv->np_qfirst[t] > 1));
1986 }
1987 
1988 #ifdef WITH_PIPES
1989 int netmap_pipe_txsync(struct netmap_kring *txkring, int flags);
1990 int netmap_pipe_rxsync(struct netmap_kring *rxkring, int flags);
1991 int netmap_pipe_krings_create_both(struct netmap_adapter *na,
1992 				  struct netmap_adapter *ona);
1993 void netmap_pipe_krings_delete_both(struct netmap_adapter *na,
1994 				    struct netmap_adapter *ona);
1995 int netmap_pipe_reg_both(struct netmap_adapter *na,
1996 			 struct netmap_adapter *ona);
1997 #endif /* WITH_PIPES */
1998 
1999 #ifdef WITH_MONITOR
2000 
2001 struct netmap_monitor_adapter {
2002 	struct netmap_adapter up;
2003 
2004 	struct netmap_priv_d priv;
2005 	uint32_t flags;
2006 };
2007 
2008 #endif /* WITH_MONITOR */
2009 
2010 
2011 #ifdef WITH_GENERIC
2012 /*
2013  * generic netmap emulation for devices that do not have
2014  * native netmap support.
2015  */
2016 int generic_netmap_attach(struct ifnet *ifp);
2017 int generic_rx_handler(struct ifnet *ifp, struct mbuf *m);;
2018 
2019 int nm_os_catch_rx(struct netmap_generic_adapter *gna, int intercept);
2020 int nm_os_catch_tx(struct netmap_generic_adapter *gna, int intercept);
2021 
2022 int na_is_generic(struct netmap_adapter *na);
2023 
2024 /*
2025  * the generic transmit routine is passed a structure to optionally
2026  * build a queue of descriptors, in an OS-specific way.
2027  * The payload is at addr, if non-null, and the routine should send or queue
2028  * the packet, returning 0 if successful, 1 on failure.
2029  *
2030  * At the end, if head is non-null, there will be an additional call
2031  * to the function with addr = NULL; this should tell the OS-specific
2032  * routine to send the queue and free any resources. Failure is ignored.
2033  */
2034 struct nm_os_gen_arg {
2035 	struct ifnet *ifp;
2036 	void *m;	/* os-specific mbuf-like object */
2037 	void *head, *tail; /* tailq, if the OS-specific routine needs to build one */
2038 	void *addr;	/* payload of current packet */
2039 	u_int len;	/* packet length */
2040 	u_int ring_nr;	/* packet length */
2041 	u_int qevent;   /* in txqdisc mode, place an event on this mbuf */
2042 };
2043 
2044 int nm_os_generic_xmit_frame(struct nm_os_gen_arg *);
2045 int nm_os_generic_find_num_desc(struct ifnet *ifp, u_int *tx, u_int *rx);
2046 void nm_os_generic_find_num_queues(struct ifnet *ifp, u_int *txq, u_int *rxq);
2047 void nm_os_generic_set_features(struct netmap_generic_adapter *gna);
2048 
2049 static inline struct ifnet*
2050 netmap_generic_getifp(struct netmap_generic_adapter *gna)
2051 {
2052         if (gna->prev)
2053             return gna->prev->ifp;
2054 
2055         return gna->up.up.ifp;
2056 }
2057 
2058 void netmap_generic_irq(struct netmap_adapter *na, u_int q, u_int *work_done);
2059 
2060 //#define RATE_GENERIC  /* Enables communication statistics for generic. */
2061 #ifdef RATE_GENERIC
2062 void generic_rate(int txp, int txs, int txi, int rxp, int rxs, int rxi);
2063 #else
2064 #define generic_rate(txp, txs, txi, rxp, rxs, rxi)
2065 #endif
2066 
2067 /*
2068  * netmap_mitigation API. This is used by the generic adapter
2069  * to reduce the number of interrupt requests/selwakeup
2070  * to clients on incoming packets.
2071  */
2072 void nm_os_mitigation_init(struct nm_generic_mit *mit, int idx,
2073                                 struct netmap_adapter *na);
2074 void nm_os_mitigation_start(struct nm_generic_mit *mit);
2075 void nm_os_mitigation_restart(struct nm_generic_mit *mit);
2076 int nm_os_mitigation_active(struct nm_generic_mit *mit);
2077 void nm_os_mitigation_cleanup(struct nm_generic_mit *mit);
2078 #else /* !WITH_GENERIC */
2079 #define generic_netmap_attach(ifp)	(EOPNOTSUPP)
2080 #define na_is_generic(na)		(0)
2081 #endif /* WITH_GENERIC */
2082 
2083 /* Shared declarations for the VALE switch. */
2084 
2085 /*
2086  * Each transmit queue accumulates a batch of packets into
2087  * a structure before forwarding. Packets to the same
2088  * destination are put in a list using ft_next as a link field.
2089  * ft_frags and ft_next are valid only on the first fragment.
2090  */
2091 struct nm_bdg_fwd {	/* forwarding entry for a bridge */
2092 	void *ft_buf;		/* netmap or indirect buffer */
2093 	uint8_t ft_frags;	/* how many fragments (only on 1st frag) */
2094 	uint16_t ft_offset;	/* dst port (unused) */
2095 	uint16_t ft_flags;	/* flags, e.g. indirect */
2096 	uint16_t ft_len;	/* src fragment len */
2097 	uint16_t ft_next;	/* next packet to same destination */
2098 };
2099 
2100 /* struct 'virtio_net_hdr' from linux. */
2101 struct nm_vnet_hdr {
2102 #define VIRTIO_NET_HDR_F_NEEDS_CSUM     1	/* Use csum_start, csum_offset */
2103 #define VIRTIO_NET_HDR_F_DATA_VALID    2	/* Csum is valid */
2104     uint8_t flags;
2105 #define VIRTIO_NET_HDR_GSO_NONE         0       /* Not a GSO frame */
2106 #define VIRTIO_NET_HDR_GSO_TCPV4        1       /* GSO frame, IPv4 TCP (TSO) */
2107 #define VIRTIO_NET_HDR_GSO_UDP          3       /* GSO frame, IPv4 UDP (UFO) */
2108 #define VIRTIO_NET_HDR_GSO_TCPV6        4       /* GSO frame, IPv6 TCP */
2109 #define VIRTIO_NET_HDR_GSO_ECN          0x80    /* TCP has ECN set */
2110     uint8_t gso_type;
2111     uint16_t hdr_len;
2112     uint16_t gso_size;
2113     uint16_t csum_start;
2114     uint16_t csum_offset;
2115 };
2116 
2117 #define WORST_CASE_GSO_HEADER	(14+40+60)  /* IPv6 + TCP */
2118 
2119 /* Private definitions for IPv4, IPv6, UDP and TCP headers. */
2120 
2121 struct nm_iphdr {
2122 	uint8_t		version_ihl;
2123 	uint8_t		tos;
2124 	uint16_t	tot_len;
2125 	uint16_t	id;
2126 	uint16_t	frag_off;
2127 	uint8_t		ttl;
2128 	uint8_t		protocol;
2129 	uint16_t	check;
2130 	uint32_t	saddr;
2131 	uint32_t	daddr;
2132 	/*The options start here. */
2133 };
2134 
2135 struct nm_tcphdr {
2136 	uint16_t	source;
2137 	uint16_t	dest;
2138 	uint32_t	seq;
2139 	uint32_t	ack_seq;
2140 	uint8_t		doff;  /* Data offset + Reserved */
2141 	uint8_t		flags;
2142 	uint16_t	window;
2143 	uint16_t	check;
2144 	uint16_t	urg_ptr;
2145 };
2146 
2147 struct nm_udphdr {
2148 	uint16_t	source;
2149 	uint16_t	dest;
2150 	uint16_t	len;
2151 	uint16_t	check;
2152 };
2153 
2154 struct nm_ipv6hdr {
2155 	uint8_t		priority_version;
2156 	uint8_t		flow_lbl[3];
2157 
2158 	uint16_t	payload_len;
2159 	uint8_t		nexthdr;
2160 	uint8_t		hop_limit;
2161 
2162 	uint8_t		saddr[16];
2163 	uint8_t		daddr[16];
2164 };
2165 
2166 /* Type used to store a checksum (in host byte order) that hasn't been
2167  * folded yet.
2168  */
2169 #define rawsum_t uint32_t
2170 
2171 rawsum_t nm_os_csum_raw(uint8_t *data, size_t len, rawsum_t cur_sum);
2172 uint16_t nm_os_csum_ipv4(struct nm_iphdr *iph);
2173 void nm_os_csum_tcpudp_ipv4(struct nm_iphdr *iph, void *data,
2174 		      size_t datalen, uint16_t *check);
2175 void nm_os_csum_tcpudp_ipv6(struct nm_ipv6hdr *ip6h, void *data,
2176 		      size_t datalen, uint16_t *check);
2177 uint16_t nm_os_csum_fold(rawsum_t cur_sum);
2178 
2179 void bdg_mismatch_datapath(struct netmap_vp_adapter *na,
2180 			   struct netmap_vp_adapter *dst_na,
2181 			   const struct nm_bdg_fwd *ft_p,
2182 			   struct netmap_ring *dst_ring,
2183 			   u_int *j, u_int lim, u_int *howmany);
2184 
2185 /* persistent virtual port routines */
2186 int nm_os_vi_persist(const char *, struct ifnet **);
2187 void nm_os_vi_detach(struct ifnet *);
2188 void nm_os_vi_init_index(void);
2189 
2190 /*
2191  * kernel thread routines
2192  */
2193 struct nm_kctx; /* OS-specific kernel context - opaque */
2194 typedef void (*nm_kctx_worker_fn_t)(void *data);
2195 
2196 /* kthread configuration */
2197 struct nm_kctx_cfg {
2198 	long			type;		/* kthread type/identifier */
2199 	nm_kctx_worker_fn_t	worker_fn;	/* worker function */
2200 	void			*worker_private;/* worker parameter */
2201 	int			attach_user;	/* attach kthread to user process */
2202 };
2203 /* kthread configuration */
2204 struct nm_kctx *nm_os_kctx_create(struct nm_kctx_cfg *cfg,
2205 					void *opaque);
2206 int nm_os_kctx_worker_start(struct nm_kctx *);
2207 void nm_os_kctx_worker_stop(struct nm_kctx *);
2208 void nm_os_kctx_destroy(struct nm_kctx *);
2209 void nm_os_kctx_worker_setaff(struct nm_kctx *, int);
2210 u_int nm_os_ncpus(void);
2211 
2212 int netmap_sync_kloop(struct netmap_priv_d *priv,
2213 		      struct nmreq_header *hdr);
2214 int netmap_sync_kloop_stop(struct netmap_priv_d *priv);
2215 
2216 #ifdef WITH_PTNETMAP
2217 /* ptnetmap guest routines */
2218 
2219 /*
2220  * ptnetmap_memdev routines used to talk with ptnetmap_memdev device driver
2221  */
2222 struct ptnetmap_memdev;
2223 int nm_os_pt_memdev_iomap(struct ptnetmap_memdev *, vm_paddr_t *, void **,
2224                           uint64_t *);
2225 void nm_os_pt_memdev_iounmap(struct ptnetmap_memdev *);
2226 uint32_t nm_os_pt_memdev_ioread(struct ptnetmap_memdev *, unsigned int);
2227 
2228 /*
2229  * netmap adapter for guest ptnetmap ports
2230  */
2231 struct netmap_pt_guest_adapter {
2232         /* The netmap adapter to be used by netmap applications.
2233 	 * This field must be the first, to allow upcast. */
2234 	struct netmap_hw_adapter hwup;
2235 
2236         /* The netmap adapter to be used by the driver. */
2237         struct netmap_hw_adapter dr;
2238 
2239 	/* Reference counter to track users of backend netmap port: the
2240 	 * network stack and netmap clients.
2241 	 * Used to decide when we need (de)allocate krings/rings and
2242 	 * start (stop) ptnetmap kthreads. */
2243 	int backend_users;
2244 
2245 };
2246 
2247 int netmap_pt_guest_attach(struct netmap_adapter *na,
2248 			unsigned int nifp_offset,
2249 			unsigned int memid);
2250 bool netmap_pt_guest_txsync(struct nm_csb_atok *atok,
2251 			struct nm_csb_ktoa *ktoa,
2252 			struct netmap_kring *kring, int flags);
2253 bool netmap_pt_guest_rxsync(struct nm_csb_atok *atok,
2254 			struct nm_csb_ktoa *ktoa,
2255 			struct netmap_kring *kring, int flags);
2256 int ptnet_nm_krings_create(struct netmap_adapter *na);
2257 void ptnet_nm_krings_delete(struct netmap_adapter *na);
2258 void ptnet_nm_dtor(struct netmap_adapter *na);
2259 
2260 /* Helper function wrapping nm_sync_kloop_appl_read(). */
2261 static inline void
2262 ptnet_sync_tail(struct nm_csb_ktoa *ktoa, struct netmap_kring *kring)
2263 {
2264 	struct netmap_ring *ring = kring->ring;
2265 
2266 	/* Update hwcur and hwtail as known by the host. */
2267         nm_sync_kloop_appl_read(ktoa, &kring->nr_hwtail, &kring->nr_hwcur);
2268 
2269 	/* nm_sync_finalize */
2270 	ring->tail = kring->rtail = kring->nr_hwtail;
2271 }
2272 #endif /* WITH_PTNETMAP */
2273 
2274 #ifdef __FreeBSD__
2275 /*
2276  * FreeBSD mbuf allocator/deallocator in emulation mode:
2277  */
2278 #if __FreeBSD_version < 1100000
2279 
2280 /*
2281  * For older versions of FreeBSD:
2282  *
2283  * We allocate EXT_PACKET mbuf+clusters, but need to set M_NOFREE
2284  * so that the destructor, if invoked, will not free the packet.
2285  * In principle we should set the destructor only on demand,
2286  * but since there might be a race we better do it on allocation.
2287  * As a consequence, we also need to set the destructor or we
2288  * would leak buffers.
2289  */
2290 
2291 /* mbuf destructor, also need to change the type to EXT_EXTREF,
2292  * add an M_NOFREE flag, and then clear the flag and
2293  * chain into uma_zfree(zone_pack, mf)
2294  * (or reinstall the buffer ?)
2295  */
2296 #define SET_MBUF_DESTRUCTOR(m, fn)	do {		\
2297 	(m)->m_ext.ext_free = (void *)fn;	\
2298 	(m)->m_ext.ext_type = EXT_EXTREF;	\
2299 } while (0)
2300 
2301 static int
2302 void_mbuf_dtor(struct mbuf *m, void *arg1, void *arg2)
2303 {
2304 	/* restore original mbuf */
2305 	m->m_ext.ext_buf = m->m_data = m->m_ext.ext_arg1;
2306 	m->m_ext.ext_arg1 = NULL;
2307 	m->m_ext.ext_type = EXT_PACKET;
2308 	m->m_ext.ext_free = NULL;
2309 	if (MBUF_REFCNT(m) == 0)
2310 		SET_MBUF_REFCNT(m, 1);
2311 	uma_zfree(zone_pack, m);
2312 
2313 	return 0;
2314 }
2315 
2316 static inline struct mbuf *
2317 nm_os_get_mbuf(struct ifnet *ifp, int len)
2318 {
2319 	struct mbuf *m;
2320 
2321 	(void)ifp;
2322 	m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
2323 	if (m) {
2324 		/* m_getcl() (mb_ctor_mbuf) has an assert that checks that
2325 		 * M_NOFREE flag is not specified as third argument,
2326 		 * so we have to set M_NOFREE after m_getcl(). */
2327 		m->m_flags |= M_NOFREE;
2328 		m->m_ext.ext_arg1 = m->m_ext.ext_buf; // XXX save
2329 		m->m_ext.ext_free = (void *)void_mbuf_dtor;
2330 		m->m_ext.ext_type = EXT_EXTREF;
2331 		nm_prdis(5, "create m %p refcnt %d", m, MBUF_REFCNT(m));
2332 	}
2333 	return m;
2334 }
2335 
2336 #else /* __FreeBSD_version >= 1100000 */
2337 
2338 /*
2339  * Newer versions of FreeBSD, using a straightforward scheme.
2340  *
2341  * We allocate mbufs with m_gethdr(), since the mbuf header is needed
2342  * by the driver. We also attach a customly-provided external storage,
2343  * which in this case is a netmap buffer. When calling m_extadd(), however
2344  * we pass a NULL address, since the real address (and length) will be
2345  * filled in by nm_os_generic_xmit_frame() right before calling
2346  * if_transmit().
2347  *
2348  * The dtor function does nothing, however we need it since mb_free_ext()
2349  * has a KASSERT(), checking that the mbuf dtor function is not NULL.
2350  */
2351 
2352 #if __FreeBSD_version <= 1200050
2353 static void void_mbuf_dtor(struct mbuf *m, void *arg1, void *arg2) { }
2354 #else  /* __FreeBSD_version >= 1200051 */
2355 /* The arg1 and arg2 pointers argument were removed by r324446, which
2356  * in included since version 1200051. */
2357 static void void_mbuf_dtor(struct mbuf *m) { }
2358 #endif /* __FreeBSD_version >= 1200051 */
2359 
2360 #define SET_MBUF_DESTRUCTOR(m, fn)	do {		\
2361 	(m)->m_ext.ext_free = (fn != NULL) ?		\
2362 	    (void *)fn : (void *)void_mbuf_dtor;	\
2363 } while (0)
2364 
2365 static inline struct mbuf *
2366 nm_os_get_mbuf(struct ifnet *ifp, int len)
2367 {
2368 	struct mbuf *m;
2369 
2370 	(void)ifp;
2371 	(void)len;
2372 
2373 	m = m_gethdr(M_NOWAIT, MT_DATA);
2374 	if (m == NULL) {
2375 		return m;
2376 	}
2377 
2378 	m_extadd(m, NULL /* buf */, 0 /* size */, void_mbuf_dtor,
2379 		 NULL, NULL, 0, EXT_NET_DRV);
2380 
2381 	return m;
2382 }
2383 
2384 #endif /* __FreeBSD_version >= 1100000 */
2385 #endif /* __FreeBSD__ */
2386 
2387 struct nmreq_option * nmreq_findoption(struct nmreq_option *, uint16_t);
2388 int nmreq_checkduplicate(struct nmreq_option *);
2389 
2390 int netmap_init_bridges(void);
2391 void netmap_uninit_bridges(void);
2392 
2393 /* Functions to read and write CSB fields from the kernel. */
2394 #if defined (linux)
2395 #define CSB_READ(csb, field, r) (get_user(r, &csb->field))
2396 #define CSB_WRITE(csb, field, v) (put_user(v, &csb->field))
2397 #else  /* ! linux */
2398 #define CSB_READ(csb, field, r) (r = fuword32(&csb->field))
2399 #define CSB_WRITE(csb, field, v) (suword32(&csb->field, v))
2400 #endif /* ! linux */
2401 
2402 #endif /* _NET_NETMAP_KERN_H_ */
2403