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