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