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