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