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