xref: /freebsd/sys/dev/netmap/netmap_kern.h (revision 6186fd1857626de0f7cb1a9e4dff19082f9ebb11)
1 /*
2  * Copyright (C) 2011-2014 Matteo Landi, Luigi Rizzo. All rights reserved.
3  * Copyright (C) 2013-2014 Universita` di Pisa. All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *   1. Redistributions of source code must retain the above copyright
9  *      notice, this list of conditions and the following disclaimer.
10  *   2. Redistributions in binary form must reproduce the above copyright
11  *      notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 /*
28  * $FreeBSD$
29  *
30  * The header contains the definitions of constants and function
31  * prototypes used only in kernelspace.
32  */
33 
34 #ifndef _NET_NETMAP_KERN_H_
35 #define _NET_NETMAP_KERN_H_
36 
37 #define WITH_VALE	// comment out to disable VALE support
38 #define WITH_PIPES
39 #define WITH_MONITOR
40 
41 #if defined(__FreeBSD__)
42 
43 #define likely(x)	__builtin_expect((long)!!(x), 1L)
44 #define unlikely(x)	__builtin_expect((long)!!(x), 0L)
45 
46 #define	NM_LOCK_T	struct mtx
47 #define	NMG_LOCK_T	struct sx
48 #define NMG_LOCK_INIT()	sx_init(&netmap_global_lock, \
49 				"netmap global lock")
50 #define NMG_LOCK_DESTROY()	sx_destroy(&netmap_global_lock)
51 #define NMG_LOCK()	sx_xlock(&netmap_global_lock)
52 #define NMG_UNLOCK()	sx_xunlock(&netmap_global_lock)
53 #define NMG_LOCK_ASSERT()	sx_assert(&netmap_global_lock, SA_XLOCKED)
54 
55 #define	NM_SELINFO_T	struct selinfo
56 #define	MBUF_LEN(m)	((m)->m_pkthdr.len)
57 #define	MBUF_IFP(m)	((m)->m_pkthdr.rcvif)
58 #define	NM_SEND_UP(ifp, m)	((NA(ifp))->if_input)(ifp, m)
59 
60 #define NM_ATOMIC_T	volatile int	// XXX ?
61 /* atomic operations */
62 #include <machine/atomic.h>
63 #define NM_ATOMIC_TEST_AND_SET(p)       (!atomic_cmpset_acq_int((p), 0, 1))
64 #define NM_ATOMIC_CLEAR(p)              atomic_store_rel_int((p), 0)
65 
66 #if __FreeBSD_version >= 1100030
67 #define	WNA(_ifp)	(_ifp)->if_netmap
68 #else /* older FreeBSD */
69 #define	WNA(_ifp)	(_ifp)->if_pspare[0]
70 #endif /* older FreeBSD */
71 
72 #if __FreeBSD_version >= 1100005
73 struct netmap_adapter *netmap_getna(if_t ifp);
74 #endif
75 
76 #if __FreeBSD_version >= 1100027
77 #define GET_MBUF_REFCNT(m)      ((m)->m_ext.ext_cnt ? *((m)->m_ext.ext_cnt) : -1)
78 #define SET_MBUF_REFCNT(m, x)   *((m)->m_ext.ext_cnt) = x
79 #define PNT_MBUF_REFCNT(m)      ((m)->m_ext.ext_cnt)
80 #else
81 #define GET_MBUF_REFCNT(m)      ((m)->m_ext.ref_cnt ? *((m)->m_ext.ref_cnt) : -1)
82 #define SET_MBUF_REFCNT(m, x)   *((m)->m_ext.ref_cnt) = x
83 #define PNT_MBUF_REFCNT(m)      ((m)->m_ext.ref_cnt)
84 #endif
85 
86 MALLOC_DECLARE(M_NETMAP);
87 
88 // XXX linux struct, not used in FreeBSD
89 struct net_device_ops {
90 };
91 struct ethtool_ops {
92 };
93 struct hrtimer {
94 };
95 
96 #elif defined (linux)
97 
98 #define	NM_LOCK_T	safe_spinlock_t	// see bsd_glue.h
99 #define	NM_SELINFO_T	wait_queue_head_t
100 #define	MBUF_LEN(m)	((m)->len)
101 #define	MBUF_IFP(m)	((m)->dev)
102 #define	NM_SEND_UP(ifp, m)  \
103                         do { \
104                             m->priority = NM_MAGIC_PRIORITY_RX; \
105                             netif_rx(m); \
106                         } while (0)
107 
108 #define NM_ATOMIC_T	volatile long unsigned int
109 
110 // XXX a mtx would suffice here too 20130404 gl
111 #define NMG_LOCK_T		struct semaphore
112 #define NMG_LOCK_INIT()		sema_init(&netmap_global_lock, 1)
113 #define NMG_LOCK_DESTROY()
114 #define NMG_LOCK()		down(&netmap_global_lock)
115 #define NMG_UNLOCK()		up(&netmap_global_lock)
116 #define NMG_LOCK_ASSERT()	//	XXX to be completed
117 
118 #ifndef DEV_NETMAP
119 #define DEV_NETMAP
120 #endif /* DEV_NETMAP */
121 
122 #elif defined (__APPLE__)
123 
124 #warning apple support is incomplete.
125 #define likely(x)	__builtin_expect(!!(x), 1)
126 #define unlikely(x)	__builtin_expect(!!(x), 0)
127 #define	NM_LOCK_T	IOLock *
128 #define	NM_SELINFO_T	struct selinfo
129 #define	MBUF_LEN(m)	((m)->m_pkthdr.len)
130 #define	NM_SEND_UP(ifp, m)	((ifp)->if_input)(ifp, m)
131 
132 #else
133 
134 #error unsupported platform
135 
136 #endif /* end - platform-specific code */
137 
138 #define ND(format, ...)
139 #define D(format, ...)						\
140 	do {							\
141 		struct timeval __xxts;				\
142 		microtime(&__xxts);				\
143 		printf("%03d.%06d [%4d] %-25s " format "\n",	\
144 		(int)__xxts.tv_sec % 1000, (int)__xxts.tv_usec,	\
145 		__LINE__, __FUNCTION__, ##__VA_ARGS__);		\
146 	} while (0)
147 
148 /* rate limited, lps indicates how many per second */
149 #define RD(lps, format, ...)					\
150 	do {							\
151 		static int t0, __cnt;				\
152 		if (t0 != time_second) {			\
153 			t0 = time_second;			\
154 			__cnt = 0;				\
155 		}						\
156 		if (__cnt++ < lps)				\
157 			D(format, ##__VA_ARGS__);		\
158 	} while (0)
159 
160 struct netmap_adapter;
161 struct nm_bdg_fwd;
162 struct nm_bridge;
163 struct netmap_priv_d;
164 
165 const char *nm_dump_buf(char *p, int len, int lim, char *dst);
166 
167 #include "netmap_mbq.h"
168 
169 extern NMG_LOCK_T	netmap_global_lock;
170 
171 /*
172  * private, kernel view of a ring. Keeps track of the status of
173  * a ring across system calls.
174  *
175  *	nr_hwcur	index of the next buffer to refill.
176  *			It corresponds to ring->head
177  *			at the time the system call returns.
178  *
179  *	nr_hwtail	index of the first buffer owned by the kernel.
180  *			On RX, hwcur->hwtail are receive buffers
181  *			not yet released. hwcur is advanced following
182  *			ring->head, hwtail is advanced on incoming packets,
183  *			and a wakeup is generated when hwtail passes ring->cur
184  *			    On TX, hwcur->rcur have been filled by the sender
185  *			but not sent yet to the NIC; rcur->hwtail are available
186  *			for new transmissions, and hwtail->hwcur-1 are pending
187  *			transmissions not yet acknowledged.
188  *
189  * The indexes in the NIC and netmap rings are offset by nkr_hwofs slots.
190  * This is so that, on a reset, buffers owned by userspace are not
191  * modified by the kernel. In particular:
192  * RX rings: the next empty buffer (hwtail + hwofs) coincides with
193  * 	the next empty buffer as known by the hardware (next_to_check or so).
194  * TX rings: hwcur + hwofs coincides with next_to_send
195  *
196  * For received packets, slot->flags is set to nkr_slot_flags
197  * so we can provide a proper initial value (e.g. set NS_FORWARD
198  * when operating in 'transparent' mode).
199  *
200  * The following fields are used to implement lock-free copy of packets
201  * from input to output ports in VALE switch:
202  *	nkr_hwlease	buffer after the last one being copied.
203  *			A writer in nm_bdg_flush reserves N buffers
204  *			from nr_hwlease, advances it, then does the
205  *			copy outside the lock.
206  *			In RX rings (used for VALE ports),
207  *			nkr_hwtail <= nkr_hwlease < nkr_hwcur+N-1
208  *			In TX rings (used for NIC or host stack ports)
209  *			nkr_hwcur <= nkr_hwlease < nkr_hwtail
210  *	nkr_leases	array of nkr_num_slots where writers can report
211  *			completion of their block. NR_NOSLOT (~0) indicates
212  *			that the writer has not finished yet
213  *	nkr_lease_idx	index of next free slot in nr_leases, to be assigned
214  *
215  * The kring is manipulated by txsync/rxsync and generic netmap function.
216  *
217  * Concurrent rxsync or txsync on the same ring are prevented through
218  * by nm_kr_(try)lock() which in turn uses nr_busy. This is all we need
219  * for NIC rings, and for TX rings attached to the host stack.
220  *
221  * RX rings attached to the host stack use an mbq (rx_queue) on both
222  * rxsync_from_host() and netmap_transmit(). The mbq is protected
223  * by its internal lock.
224  *
225  * RX rings attached to the VALE switch are accessed by both senders
226  * and receiver. They are protected through the q_lock on the RX ring.
227  */
228 struct netmap_kring {
229 	struct netmap_ring	*ring;
230 
231 	uint32_t	nr_hwcur;
232 	uint32_t	nr_hwtail;
233 
234 	/*
235 	 * Copies of values in user rings, so we do not need to look
236 	 * at the ring (which could be modified). These are set in the
237 	 * *sync_prologue()/finalize() routines.
238 	 */
239 	uint32_t	rhead;
240 	uint32_t	rcur;
241 	uint32_t	rtail;
242 
243 	uint32_t	nr_kflags;	/* private driver flags */
244 #define NKR_PENDINTR	0x1		// Pending interrupt.
245 	uint32_t	nkr_num_slots;
246 
247 	/*
248 	 * On a NIC reset, the NIC ring indexes may be reset but the
249 	 * indexes in the netmap rings remain the same. nkr_hwofs
250 	 * keeps track of the offset between the two.
251 	 */
252 	int32_t		nkr_hwofs;
253 
254 	uint16_t	nkr_slot_flags;	/* initial value for flags */
255 
256 	/* last_reclaim is opaque marker to help reduce the frequency
257 	 * of operations such as reclaiming tx buffers. A possible use
258 	 * is set it to ticks and do the reclaim only once per tick.
259 	 */
260 	uint64_t	last_reclaim;
261 
262 
263 	NM_SELINFO_T	si;		/* poll/select wait queue */
264 	NM_LOCK_T	q_lock;		/* protects kring and ring. */
265 	NM_ATOMIC_T	nr_busy;	/* prevent concurrent syscalls */
266 
267 	struct netmap_adapter *na;
268 
269 	/* The folloiwing fields are for VALE switch support */
270 	struct nm_bdg_fwd *nkr_ft;
271 	uint32_t	*nkr_leases;
272 #define NR_NOSLOT	((uint32_t)~0)	/* used in nkr_*lease* */
273 	uint32_t	nkr_hwlease;
274 	uint32_t	nkr_lease_idx;
275 
276 	/* while nkr_stopped is set, no new [tr]xsync operations can
277 	 * be started on this kring.
278 	 * This is used by netmap_disable_all_rings()
279 	 * to find a synchronization point where critical data
280 	 * structures pointed to by the kring can be added or removed
281 	 */
282 	volatile int nkr_stopped;
283 
284 	/* Support for adapters without native netmap support.
285 	 * On tx rings we preallocate an array of tx buffers
286 	 * (same size as the netmap ring), on rx rings we
287 	 * store incoming mbufs in a queue that is drained by
288 	 * a rxsync.
289 	 */
290 	struct mbuf **tx_pool;
291 	// u_int nr_ntc;		/* Emulation of a next-to-clean RX ring pointer. */
292 	struct mbq rx_queue;            /* intercepted rx mbufs. */
293 
294 	uint32_t	ring_id;	/* debugging */
295 	char name[64];			/* diagnostic */
296 
297 	/* [tx]sync callback for this kring.
298 	 * The default nm_kring_create callback (netmap_krings_create)
299 	 * sets the nm_sync callback of each hardware tx(rx) kring to
300 	 * the corresponding nm_txsync(nm_rxsync) taken from the
301 	 * netmap_adapter; moreover, it sets the sync callback
302 	 * of the host tx(rx) ring to netmap_txsync_to_host
303 	 * (netmap_rxsync_from_host).
304 	 *
305 	 * Overrides: the above configuration is not changed by
306 	 * any of the nm_krings_create callbacks.
307 	 */
308 	int (*nm_sync)(struct netmap_kring *kring, int flags);
309 
310 #ifdef WITH_PIPES
311 	struct netmap_kring *pipe;	/* if this is a pipe ring,
312 					 * pointer to the other end
313 					 */
314 	struct netmap_ring *save_ring;	/* pointer to hidden rings
315        					 * (see netmap_pipe.c for details)
316 					 */
317 #endif /* WITH_PIPES */
318 
319 #ifdef WITH_MONITOR
320 	/* pointer to the adapter that is monitoring this kring (if any)
321 	 */
322 	struct netmap_monitor_adapter *monitor;
323 	/*
324 	 * Monitors work by intercepting the txsync and/or rxsync of the
325 	 * monitored krings. This is implemented by replacing
326 	 * the nm_sync pointer above and saving the previous
327 	 * one in save_sync below.
328 	 */
329 	int (*save_sync)(struct netmap_kring *kring, int flags);
330 #endif
331 } __attribute__((__aligned__(64)));
332 
333 
334 /* return the next index, with wraparound */
335 static inline uint32_t
336 nm_next(uint32_t i, uint32_t lim)
337 {
338 	return unlikely (i == lim) ? 0 : i + 1;
339 }
340 
341 
342 /* return the previous index, with wraparound */
343 static inline uint32_t
344 nm_prev(uint32_t i, uint32_t lim)
345 {
346 	return unlikely (i == 0) ? lim : i - 1;
347 }
348 
349 
350 /*
351  *
352  * Here is the layout for the Rx and Tx rings.
353 
354        RxRING                            TxRING
355 
356       +-----------------+            +-----------------+
357       |                 |            |                 |
358       |XXX free slot XXX|            |XXX free slot XXX|
359       +-----------------+            +-----------------+
360 head->| owned by user   |<-hwcur     | not sent to nic |<-hwcur
361       |                 |            | yet             |
362       +-----------------+            |                 |
363  cur->| available to    |            |                 |
364       | user, not read  |            +-----------------+
365       | yet             |       cur->| (being          |
366       |                 |            |  prepared)      |
367       |                 |            |                 |
368       +-----------------+            +     ------      +
369 tail->|                 |<-hwtail    |                 |<-hwlease
370       | (being          | ...        |                 | ...
371       |  prepared)      | ...        |                 | ...
372       +-----------------+ ...        |                 | ...
373       |                 |<-hwlease   +-----------------+
374       |                 |      tail->|                 |<-hwtail
375       |                 |            |                 |
376       |                 |            |                 |
377       |                 |            |                 |
378       +-----------------+            +-----------------+
379 
380  * The cur/tail (user view) and hwcur/hwtail (kernel view)
381  * are used in the normal operation of the card.
382  *
383  * When a ring is the output of a switch port (Rx ring for
384  * a VALE port, Tx ring for the host stack or NIC), slots
385  * are reserved in blocks through 'hwlease' which points
386  * to the next unused slot.
387  * On an Rx ring, hwlease is always after hwtail,
388  * and completions cause hwtail to advance.
389  * On a Tx ring, hwlease is always between cur and hwtail,
390  * and completions cause cur to advance.
391  *
392  * nm_kr_space() returns the maximum number of slots that
393  * can be assigned.
394  * nm_kr_lease() reserves the required number of buffers,
395  *    advances nkr_hwlease and also returns an entry in
396  *    a circular array where completions should be reported.
397  */
398 
399 
400 
401 enum txrx { NR_RX = 0, NR_TX = 1 };
402 
403 struct netmap_vp_adapter; // forward
404 
405 /*
406  * The "struct netmap_adapter" extends the "struct adapter"
407  * (or equivalent) device descriptor.
408  * It contains all base fields needed to support netmap operation.
409  * There are in fact different types of netmap adapters
410  * (native, generic, VALE switch...) so a netmap_adapter is
411  * just the first field in the derived type.
412  */
413 struct netmap_adapter {
414 	/*
415 	 * On linux we do not have a good way to tell if an interface
416 	 * is netmap-capable. So we always use the following trick:
417 	 * NA(ifp) points here, and the first entry (which hopefully
418 	 * always exists and is at least 32 bits) contains a magic
419 	 * value which we can use to detect that the interface is good.
420 	 */
421 	uint32_t magic;
422 	uint32_t na_flags;	/* enabled, and other flags */
423 #define NAF_SKIP_INTR	1	/* use the regular interrupt handler.
424 				 * useful during initialization
425 				 */
426 #define NAF_SW_ONLY	2	/* forward packets only to sw adapter */
427 #define NAF_BDG_MAYSLEEP 4	/* the bridge is allowed to sleep when
428 				 * forwarding packets coming from this
429 				 * interface
430 				 */
431 #define NAF_MEM_OWNER	8	/* the adapter is responsible for the
432 				 * deallocation of the memory allocator
433 				 */
434 #define NAF_NATIVE_ON   16      /* the adapter is native and the attached
435 				 * interface is in netmap mode.
436 				 * Virtual ports (vale, pipe, monitor...)
437 				 * should never use this flag.
438 				 */
439 #define	NAF_NETMAP_ON	32	/* netmap is active (either native or
440 				 * emulated). Where possible (e.g. FreeBSD)
441 				 * IFCAP_NETMAP also mirrors this flag.
442 				 */
443 #define NAF_HOST_RINGS  64	/* the adapter supports the host rings */
444 #define NAF_FORCE_NATIVE 128	/* the adapter is always NATIVE */
445 #define	NAF_BUSY	(1U<<31) /* the adapter is used internally and
446 				  * cannot be registered from userspace
447 				  */
448 	int active_fds; /* number of user-space descriptors using this
449 			 interface, which is equal to the number of
450 			 struct netmap_if objs in the mapped region. */
451 
452 	u_int num_rx_rings; /* number of adapter receive rings */
453 	u_int num_tx_rings; /* number of adapter transmit rings */
454 
455 	u_int num_tx_desc; /* number of descriptor in each queue */
456 	u_int num_rx_desc;
457 
458 	/* tx_rings and rx_rings are private but allocated
459 	 * as a contiguous chunk of memory. Each array has
460 	 * N+1 entries, for the adapter queues and for the host queue.
461 	 */
462 	struct netmap_kring *tx_rings; /* array of TX rings. */
463 	struct netmap_kring *rx_rings; /* array of RX rings. */
464 
465 	void *tailroom;		       /* space below the rings array */
466 				       /* (used for leases) */
467 
468 
469 	NM_SELINFO_T tx_si, rx_si;	/* global wait queues */
470 
471 	/* count users of the global wait queues */
472 	int tx_si_users, rx_si_users;
473 
474 	void *pdev; /* used to store pci device */
475 
476 	/* copy of if_qflush and if_transmit pointers, to intercept
477 	 * packets from the network stack when netmap is active.
478 	 */
479 	int     (*if_transmit)(struct ifnet *, struct mbuf *);
480 
481 	/* copy of if_input for netmap_send_up() */
482 	void     (*if_input)(struct ifnet *, struct mbuf *);
483 
484 	/* references to the ifnet and device routines, used by
485 	 * the generic netmap functions.
486 	 */
487 	struct ifnet *ifp; /* adapter is ifp->if_softc */
488 
489 	/*---- callbacks for this netmap adapter -----*/
490 	/*
491 	 * nm_dtor() is the cleanup routine called when destroying
492 	 *	the adapter.
493 	 *	Called with NMG_LOCK held.
494 	 *
495 	 * nm_register() is called on NIOCREGIF and close() to enter
496 	 *	or exit netmap mode on the NIC
497 	 *	Called with NNG_LOCK held.
498 	 *
499 	 * nm_txsync() pushes packets to the underlying hw/switch
500 	 *
501 	 * nm_rxsync() collects packets from the underlying hw/switch
502 	 *
503 	 * nm_config() returns configuration information from the OS
504 	 *	Called with NMG_LOCK held.
505 	 *
506 	 * nm_krings_create() create and init the tx_rings and
507 	 * 	rx_rings arrays of kring structures. In particular,
508 	 * 	set the nm_sync callbacks for each ring.
509 	 * 	There is no need to also allocate the corresponding
510 	 * 	netmap_rings, since netmap_mem_rings_create() will always
511 	 * 	be called to provide the missing ones.
512 	 *	Called with NNG_LOCK held.
513 	 *
514 	 * nm_krings_delete() cleanup and delete the tx_rings and rx_rings
515 	 * 	arrays
516 	 *	Called with NMG_LOCK held.
517 	 *
518 	 * nm_notify() is used to act after data have become available
519 	 * 	(or the stopped state of the ring has changed)
520 	 *	For hw devices this is typically a selwakeup(),
521 	 *	but for NIC/host ports attached to a switch (or vice-versa)
522 	 *	we also need to invoke the 'txsync' code downstream.
523 	 */
524 	void (*nm_dtor)(struct netmap_adapter *);
525 
526 	int (*nm_register)(struct netmap_adapter *, int onoff);
527 
528 	int (*nm_txsync)(struct netmap_kring *kring, int flags);
529 	int (*nm_rxsync)(struct netmap_kring *kring, int flags);
530 #define NAF_FORCE_READ    1
531 #define NAF_FORCE_RECLAIM 2
532 	/* return configuration information */
533 	int (*nm_config)(struct netmap_adapter *,
534 		u_int *txr, u_int *txd, u_int *rxr, u_int *rxd);
535 	int (*nm_krings_create)(struct netmap_adapter *);
536 	void (*nm_krings_delete)(struct netmap_adapter *);
537 	int (*nm_notify)(struct netmap_adapter *,
538 		u_int ring, enum txrx, int flags);
539 #define NAF_DISABLE_NOTIFY 8	/* notify that the stopped state of the
540 				 * ring has changed (kring->nkr_stopped)
541 				 */
542 
543 #ifdef WITH_VALE
544 	/*
545 	 * nm_bdg_attach() initializes the na_vp field to point
546 	 *      to an adapter that can be attached to a VALE switch. If the
547 	 *      current adapter is already a VALE port, na_vp is simply a cast;
548 	 *      otherwise, na_vp points to a netmap_bwrap_adapter.
549 	 *      If applicable, this callback also initializes na_hostvp,
550 	 *      that can be used to connect the adapter host rings to the
551 	 *      switch.
552 	 *      Called with NMG_LOCK held.
553 	 *
554 	 * nm_bdg_ctl() is called on the actual attach/detach to/from
555 	 *      to/from the switch, to perform adapter-specific
556 	 *      initializations
557 	 *      Called with NMG_LOCK held.
558 	 */
559 	int (*nm_bdg_attach)(const char *bdg_name, struct netmap_adapter *);
560 	int (*nm_bdg_ctl)(struct netmap_adapter *, struct nmreq *, int);
561 
562 	/* adapter used to attach this adapter to a VALE switch (if any) */
563 	struct netmap_vp_adapter *na_vp;
564 	/* adapter used to attach the host rings of this adapter
565 	 * to a VALE switch (if any) */
566 	struct netmap_vp_adapter *na_hostvp;
567 #endif
568 
569 	/* standard refcount to control the lifetime of the adapter
570 	 * (it should be equal to the lifetime of the corresponding ifp)
571 	 */
572 	int na_refcount;
573 
574 	/* memory allocator (opaque)
575 	 * We also cache a pointer to the lut_entry for translating
576 	 * buffer addresses, and the total number of buffers.
577 	 */
578  	struct netmap_mem_d *nm_mem;
579 	struct lut_entry *na_lut;
580 	uint32_t na_lut_objtotal;	/* max buffer index */
581 	uint32_t na_lut_objsize;	/* buffer size */
582 
583 	/* additional information attached to this adapter
584 	 * by other netmap subsystems. Currently used by
585 	 * bwrap and LINUX/v1000.
586 	 */
587 	void *na_private;
588 
589 #ifdef WITH_PIPES
590 	/* array of pipes that have this adapter as a parent */
591 	struct netmap_pipe_adapter **na_pipes;
592 	int na_next_pipe;	/* next free slot in the array */
593 	int na_max_pipes;	/* size of the array */
594 #endif /* WITH_PIPES */
595 
596 	char name[64];
597 };
598 
599 
600 /*
601  * If the NIC is owned by the kernel
602  * (i.e., bridge), neither another bridge nor user can use it;
603  * if the NIC is owned by a user, only users can share it.
604  * Evaluation must be done under NMG_LOCK().
605  */
606 #define NETMAP_OWNED_BY_KERN(na)	((na)->na_flags & NAF_BUSY)
607 #define NETMAP_OWNED_BY_ANY(na) \
608 	(NETMAP_OWNED_BY_KERN(na) || ((na)->active_fds > 0))
609 
610 
611 /*
612  * derived netmap adapters for various types of ports
613  */
614 struct netmap_vp_adapter {	/* VALE software port */
615 	struct netmap_adapter up;
616 
617 	/*
618 	 * Bridge support:
619 	 *
620 	 * bdg_port is the port number used in the bridge;
621 	 * na_bdg points to the bridge this NA is attached to.
622 	 */
623 	int bdg_port;
624 	struct nm_bridge *na_bdg;
625 	int retry;
626 
627 	/* Offset of ethernet header for each packet. */
628 	u_int virt_hdr_len;
629 	/* Maximum Frame Size, used in bdg_mismatch_datapath() */
630 	u_int mfs;
631 };
632 
633 
634 struct netmap_hw_adapter {	/* physical device */
635 	struct netmap_adapter up;
636 
637 	struct net_device_ops nm_ndo;	// XXX linux only
638 	struct ethtool_ops    nm_eto;	// XXX linux only
639 	const struct ethtool_ops*   save_ethtool;
640 
641 	int (*nm_hw_register)(struct netmap_adapter *, int onoff);
642 };
643 
644 /* Mitigation support. */
645 struct nm_generic_mit {
646 	struct hrtimer mit_timer;
647 	int mit_pending;
648 	int mit_ring_idx;  /* index of the ring being mitigated */
649 	struct netmap_adapter *mit_na;  /* backpointer */
650 };
651 
652 struct netmap_generic_adapter {	/* emulated device */
653 	struct netmap_hw_adapter up;
654 
655 	/* Pointer to a previously used netmap adapter. */
656 	struct netmap_adapter *prev;
657 
658 	/* generic netmap adapters support:
659 	 * a net_device_ops struct overrides ndo_select_queue(),
660 	 * save_if_input saves the if_input hook (FreeBSD),
661 	 * mit implements rx interrupt mitigation,
662 	 */
663 	struct net_device_ops generic_ndo;
664 	void (*save_if_input)(struct ifnet *, struct mbuf *);
665 
666 	struct nm_generic_mit *mit;
667 #ifdef linux
668         netdev_tx_t (*save_start_xmit)(struct mbuf *, struct ifnet *);
669 #endif
670 };
671 
672 static __inline int
673 netmap_real_tx_rings(struct netmap_adapter *na)
674 {
675 	return na->num_tx_rings + !!(na->na_flags & NAF_HOST_RINGS);
676 }
677 
678 static __inline int
679 netmap_real_rx_rings(struct netmap_adapter *na)
680 {
681 	return na->num_rx_rings + !!(na->na_flags & NAF_HOST_RINGS);
682 }
683 
684 #ifdef WITH_VALE
685 
686 /*
687  * Bridge wrapper for non VALE ports attached to a VALE switch.
688  *
689  * The real device must already have its own netmap adapter (hwna).
690  * The bridge wrapper and the hwna adapter share the same set of
691  * netmap rings and buffers, but they have two separate sets of
692  * krings descriptors, with tx/rx meanings swapped:
693  *
694  *                                  netmap
695  *           bwrap     krings       rings      krings      hwna
696  *         +------+   +------+     +-----+    +------+   +------+
697  *         |tx_rings->|      |\   /|     |----|      |<-tx_rings|
698  *         |      |   +------+ \ / +-----+    +------+   |      |
699  *         |      |             X                        |      |
700  *         |      |            / \                       |      |
701  *         |      |   +------+/   \+-----+    +------+   |      |
702  *         |rx_rings->|      |     |     |----|      |<-rx_rings|
703  *         |      |   +------+     +-----+    +------+   |      |
704  *         +------+                                      +------+
705  *
706  * - packets coming from the bridge go to the brwap rx rings,
707  *   which are also the hwna tx rings.  The bwrap notify callback
708  *   will then complete the hwna tx (see netmap_bwrap_notify).
709  *
710  * - packets coming from the outside go to the hwna rx rings,
711  *   which are also the bwrap tx rings.  The (overwritten) hwna
712  *   notify method will then complete the bridge tx
713  *   (see netmap_bwrap_intr_notify).
714  *
715  *   The bridge wrapper may optionally connect the hwna 'host' rings
716  *   to the bridge. This is done by using a second port in the
717  *   bridge and connecting it to the 'host' netmap_vp_adapter
718  *   contained in the netmap_bwrap_adapter. The brwap host adapter
719  *   cross-links the hwna host rings in the same way as shown above.
720  *
721  * - packets coming from the bridge and directed to the host stack
722  *   are handled by the bwrap host notify callback
723  *   (see netmap_bwrap_host_notify)
724  *
725  * - packets coming from the host stack are still handled by the
726  *   overwritten hwna notify callback (netmap_bwrap_intr_notify),
727  *   but are diverted to the host adapter depending on the ring number.
728  *
729  */
730 struct netmap_bwrap_adapter {
731 	struct netmap_vp_adapter up;
732 	struct netmap_vp_adapter host;  /* for host rings */
733 	struct netmap_adapter *hwna;	/* the underlying device */
734 
735 	/* backup of the hwna notify callback */
736 	int (*save_notify)(struct netmap_adapter *,
737 			u_int ring, enum txrx, int flags);
738 	/* backup of the hwna memory allocator */
739 	struct netmap_mem_d *save_nmd;
740 
741 	/*
742 	 * When we attach a physical interface to the bridge, we
743 	 * allow the controlling process to terminate, so we need
744 	 * a place to store the n_detmap_priv_d data structure.
745 	 * This is only done when physical interfaces
746 	 * are attached to a bridge.
747 	 */
748 	struct netmap_priv_d *na_kpriv;
749 };
750 int netmap_bwrap_attach(const char *name, struct netmap_adapter *);
751 
752 
753 #endif /* WITH_VALE */
754 
755 #ifdef WITH_PIPES
756 
757 #define NM_MAXPIPES 	64	/* max number of pipes per adapter */
758 
759 struct netmap_pipe_adapter {
760 	struct netmap_adapter up;
761 
762 	u_int id; 	/* pipe identifier */
763 	int role;	/* either NR_REG_PIPE_MASTER or NR_REG_PIPE_SLAVE */
764 
765 	struct netmap_adapter *parent; /* adapter that owns the memory */
766 	struct netmap_pipe_adapter *peer; /* the other end of the pipe */
767 	int peer_ref;		/* 1 iff we are holding a ref to the peer */
768 
769 	u_int parent_slot; /* index in the parent pipe array */
770 };
771 
772 #endif /* WITH_PIPES */
773 
774 
775 /* return slots reserved to rx clients; used in drivers */
776 static inline uint32_t
777 nm_kr_rxspace(struct netmap_kring *k)
778 {
779 	int space = k->nr_hwtail - k->nr_hwcur;
780 	if (space < 0)
781 		space += k->nkr_num_slots;
782 	ND("preserving %d rx slots %d -> %d", space, k->nr_hwcur, k->nr_hwtail);
783 
784 	return space;
785 }
786 
787 
788 /* True if no space in the tx ring. only valid after txsync_prologue */
789 static inline int
790 nm_kr_txempty(struct netmap_kring *kring)
791 {
792 	return kring->rcur == kring->nr_hwtail;
793 }
794 
795 
796 /*
797  * protect against multiple threads using the same ring.
798  * also check that the ring has not been stopped.
799  * We only care for 0 or !=0 as a return code.
800  */
801 #define NM_KR_BUSY	1
802 #define NM_KR_STOPPED	2
803 
804 
805 static __inline void nm_kr_put(struct netmap_kring *kr)
806 {
807 	NM_ATOMIC_CLEAR(&kr->nr_busy);
808 }
809 
810 
811 static __inline int nm_kr_tryget(struct netmap_kring *kr)
812 {
813 	/* check a first time without taking the lock
814 	 * to avoid starvation for nm_kr_get()
815 	 */
816 	if (unlikely(kr->nkr_stopped)) {
817 		ND("ring %p stopped (%d)", kr, kr->nkr_stopped);
818 		return NM_KR_STOPPED;
819 	}
820 	if (unlikely(NM_ATOMIC_TEST_AND_SET(&kr->nr_busy)))
821 		return NM_KR_BUSY;
822 	/* check a second time with lock held */
823 	if (unlikely(kr->nkr_stopped)) {
824 		ND("ring %p stopped (%d)", kr, kr->nkr_stopped);
825 		nm_kr_put(kr);
826 		return NM_KR_STOPPED;
827 	}
828 	return 0;
829 }
830 
831 
832 /*
833  * The following functions are used by individual drivers to
834  * support netmap operation.
835  *
836  * netmap_attach() initializes a struct netmap_adapter, allocating the
837  * 	struct netmap_ring's and the struct selinfo.
838  *
839  * netmap_detach() frees the memory allocated by netmap_attach().
840  *
841  * netmap_transmit() replaces the if_transmit routine of the interface,
842  *	and is used to intercept packets coming from the stack.
843  *
844  * netmap_load_map/netmap_reload_map are helper routines to set/reset
845  *	the dmamap for a packet buffer
846  *
847  * netmap_reset() is a helper routine to be called in the hw driver
848  *	when reinitializing a ring. It should not be called by
849  *	virtual ports (vale, pipes, monitor)
850  */
851 int netmap_attach(struct netmap_adapter *);
852 void netmap_detach(struct ifnet *);
853 int netmap_transmit(struct ifnet *, struct mbuf *);
854 struct netmap_slot *netmap_reset(struct netmap_adapter *na,
855 	enum txrx tx, u_int n, u_int new_cur);
856 int netmap_ring_reinit(struct netmap_kring *);
857 
858 /* default functions to handle rx/tx interrupts */
859 int netmap_rx_irq(struct ifnet *, u_int, u_int *);
860 #define netmap_tx_irq(_n, _q) netmap_rx_irq(_n, _q, NULL)
861 void netmap_common_irq(struct ifnet *, u_int, u_int *work_done);
862 
863 
864 #ifdef WITH_VALE
865 /* functions used by external modules to interface with VALE */
866 #define netmap_vp_to_ifp(_vp)	((_vp)->up.ifp)
867 #define netmap_ifp_to_vp(_ifp)	(NA(_ifp)->na_vp)
868 #define netmap_ifp_to_host_vp(_ifp) (NA(_ifp)->na_hostvp)
869 #define netmap_bdg_idx(_vp)	((_vp)->bdg_port)
870 const char *netmap_bdg_name(struct netmap_vp_adapter *);
871 #else /* !WITH_VALE */
872 #define netmap_vp_to_ifp(_vp)	NULL
873 #define netmap_ifp_to_vp(_ifp)	NULL
874 #define netmap_ifp_to_host_vp(_ifp) NULL
875 #define netmap_bdg_idx(_vp)	-1
876 #define netmap_bdg_name(_vp)	NULL
877 #endif /* WITH_VALE */
878 
879 static inline int
880 nm_native_on(struct netmap_adapter *na)
881 {
882 	return na && na->na_flags & NAF_NATIVE_ON;
883 }
884 
885 static inline int
886 nm_netmap_on(struct netmap_adapter *na)
887 {
888 	return na && na->na_flags & NAF_NETMAP_ON;
889 }
890 
891 /* set/clear native flags and if_transmit/netdev_ops */
892 static inline void
893 nm_set_native_flags(struct netmap_adapter *na)
894 {
895 	struct ifnet *ifp = na->ifp;
896 
897 	na->na_flags |= (NAF_NATIVE_ON | NAF_NETMAP_ON);
898 #ifdef IFCAP_NETMAP /* or FreeBSD ? */
899 	ifp->if_capenable |= IFCAP_NETMAP;
900 #endif
901 #ifdef __FreeBSD__
902 	na->if_transmit = ifp->if_transmit;
903 	ifp->if_transmit = netmap_transmit;
904 #else
905 	na->if_transmit = (void *)ifp->netdev_ops;
906 	ifp->netdev_ops = &((struct netmap_hw_adapter *)na)->nm_ndo;
907 	((struct netmap_hw_adapter *)na)->save_ethtool = ifp->ethtool_ops;
908 	ifp->ethtool_ops = &((struct netmap_hw_adapter*)na)->nm_eto;
909 #endif
910 }
911 
912 
913 static inline void
914 nm_clear_native_flags(struct netmap_adapter *na)
915 {
916 	struct ifnet *ifp = na->ifp;
917 
918 #ifdef __FreeBSD__
919 	ifp->if_transmit = na->if_transmit;
920 #else
921 	ifp->netdev_ops = (void *)na->if_transmit;
922 	ifp->ethtool_ops = ((struct netmap_hw_adapter*)na)->save_ethtool;
923 #endif
924 	na->na_flags &= ~(NAF_NATIVE_ON | NAF_NETMAP_ON);
925 #ifdef IFCAP_NETMAP /* or FreeBSD ? */
926 	ifp->if_capenable &= ~IFCAP_NETMAP;
927 #endif
928 }
929 
930 
931 /*
932  * validates parameters in the ring/kring, returns a value for head
933  * If any error, returns ring_size to force a reinit.
934  */
935 uint32_t nm_txsync_prologue(struct netmap_kring *);
936 
937 
938 /*
939  * validates parameters in the ring/kring, returns a value for head,
940  * and the 'reserved' value in the argument.
941  * If any error, returns ring_size lim to force a reinit.
942  */
943 uint32_t nm_rxsync_prologue(struct netmap_kring *);
944 
945 
946 /*
947  * update kring and ring at the end of txsync.
948  */
949 static inline void
950 nm_txsync_finalize(struct netmap_kring *kring)
951 {
952 	/* update ring tail to what the kernel knows */
953 	kring->ring->tail = kring->rtail = kring->nr_hwtail;
954 
955 	/* note, head/rhead/hwcur might be behind cur/rcur
956 	 * if no carrier
957 	 */
958 	ND(5, "%s now hwcur %d hwtail %d head %d cur %d tail %d",
959 		kring->name, kring->nr_hwcur, kring->nr_hwtail,
960 		kring->rhead, kring->rcur, kring->rtail);
961 }
962 
963 
964 /*
965  * update kring and ring at the end of rxsync
966  */
967 static inline void
968 nm_rxsync_finalize(struct netmap_kring *kring)
969 {
970 	/* tell userspace that there might be new packets */
971 	//struct netmap_ring *ring = kring->ring;
972 	ND("head %d cur %d tail %d -> %d", ring->head, ring->cur, ring->tail,
973 		kring->nr_hwtail);
974 	kring->ring->tail = kring->rtail = kring->nr_hwtail;
975 	/* make a copy of the state for next round */
976 	kring->rhead = kring->ring->head;
977 	kring->rcur = kring->ring->cur;
978 }
979 
980 
981 /* check/fix address and len in tx rings */
982 #if 1 /* debug version */
983 #define	NM_CHECK_ADDR_LEN(_na, _a, _l)	do {				\
984 	if (_a == NETMAP_BUF_BASE(_na) || _l > NETMAP_BUF_SIZE(_na)) {	\
985 		RD(5, "bad addr/len ring %d slot %d idx %d len %d",	\
986 			kring->ring_id, nm_i, slot->buf_idx, len);	\
987 		if (_l > NETMAP_BUF_SIZE(_na))				\
988 			_l = NETMAP_BUF_SIZE(_na);			\
989 	} } while (0)
990 #else /* no debug version */
991 #define	NM_CHECK_ADDR_LEN(_na, _a, _l)	do {				\
992 		if (_l > NETMAP_BUF_SIZE(_na))				\
993 			_l = NETMAP_BUF_SIZE(_na);			\
994 	} while (0)
995 #endif
996 
997 
998 /*---------------------------------------------------------------*/
999 /*
1000  * Support routines used by netmap subsystems
1001  * (native drivers, VALE, generic, pipes, monitors, ...)
1002  */
1003 
1004 
1005 /* common routine for all functions that create a netmap adapter. It performs
1006  * two main tasks:
1007  * - if the na points to an ifp, mark the ifp as netmap capable
1008  *   using na as its native adapter;
1009  * - provide defaults for the setup callbacks and the memory allocator
1010  */
1011 int netmap_attach_common(struct netmap_adapter *);
1012 /* common actions to be performed on netmap adapter destruction */
1013 void netmap_detach_common(struct netmap_adapter *);
1014 /* fill priv->np_[tr]xq{first,last} using the ringid and flags information
1015  * coming from a struct nmreq
1016  */
1017 int netmap_interp_ringid(struct netmap_priv_d *priv, uint16_t ringid, uint32_t flags);
1018 /* update the ring parameters (number and size of tx and rx rings).
1019  * It calls the nm_config callback, if available.
1020  */
1021 int netmap_update_config(struct netmap_adapter *na);
1022 /* create and initialize the common fields of the krings array.
1023  * using the information that must be already available in the na.
1024  * tailroom can be used to request the allocation of additional
1025  * tailroom bytes after the krings array. This is used by
1026  * netmap_vp_adapter's (i.e., VALE ports) to make room for
1027  * leasing-related data structures
1028  */
1029 int netmap_krings_create(struct netmap_adapter *na, u_int tailroom);
1030 /* deletes the kring array of the adapter. The array must have
1031  * been created using netmap_krings_create
1032  */
1033 void netmap_krings_delete(struct netmap_adapter *na);
1034 
1035 /* set the stopped/enabled status of ring
1036  * When stopping, they also wait for all current activity on the ring to
1037  * terminate. The status change is then notified using the na nm_notify
1038  * callback.
1039  */
1040 void netmap_set_txring(struct netmap_adapter *, u_int ring_id, int stopped);
1041 void netmap_set_rxring(struct netmap_adapter *, u_int ring_id, int stopped);
1042 /* set the stopped/enabled status of all rings of the adapter. */
1043 void netmap_set_all_rings(struct netmap_adapter *, int stopped);
1044 /* convenience wrappers for netmap_set_all_rings, used in drivers */
1045 void netmap_disable_all_rings(struct ifnet *);
1046 void netmap_enable_all_rings(struct ifnet *);
1047 
1048 int netmap_rxsync_from_host(struct netmap_adapter *na, struct thread *td, void *pwait);
1049 
1050 struct netmap_if *
1051 netmap_do_regif(struct netmap_priv_d *priv, struct netmap_adapter *na,
1052 	uint16_t ringid, uint32_t flags, int *err);
1053 
1054 
1055 
1056 u_int nm_bound_var(u_int *v, u_int dflt, u_int lo, u_int hi, const char *msg);
1057 int netmap_get_na(struct nmreq *nmr, struct netmap_adapter **na, int create);
1058 int netmap_get_hw_na(struct ifnet *ifp, struct netmap_adapter **na);
1059 
1060 
1061 #ifdef WITH_VALE
1062 /*
1063  * The following bridge-related functions are used by other
1064  * kernel modules.
1065  *
1066  * VALE only supports unicast or broadcast. The lookup
1067  * function can return 0 .. NM_BDG_MAXPORTS-1 for regular ports,
1068  * NM_BDG_MAXPORTS for broadcast, NM_BDG_MAXPORTS+1 for unknown.
1069  * XXX in practice "unknown" might be handled same as broadcast.
1070  */
1071 typedef u_int (*bdg_lookup_fn_t)(struct nm_bdg_fwd *ft, uint8_t *ring_nr,
1072 		const struct netmap_vp_adapter *);
1073 typedef int (*bdg_config_fn_t)(struct nm_ifreq *);
1074 typedef void (*bdg_dtor_fn_t)(const struct netmap_vp_adapter *);
1075 struct netmap_bdg_ops {
1076 	bdg_lookup_fn_t lookup;
1077 	bdg_config_fn_t config;
1078 	bdg_dtor_fn_t	dtor;
1079 };
1080 
1081 u_int netmap_bdg_learning(struct nm_bdg_fwd *ft, uint8_t *dst_ring,
1082 		const struct netmap_vp_adapter *);
1083 
1084 #define	NM_BDG_MAXPORTS		254	/* up to 254 */
1085 #define	NM_BDG_BROADCAST	NM_BDG_MAXPORTS
1086 #define	NM_BDG_NOPORT		(NM_BDG_MAXPORTS+1)
1087 
1088 #define	NM_NAME			"vale"	/* prefix for bridge port name */
1089 
1090 /* these are redefined in case of no VALE support */
1091 int netmap_get_bdg_na(struct nmreq *nmr, struct netmap_adapter **na, int create);
1092 void netmap_init_bridges(void);
1093 int netmap_bdg_ctl(struct nmreq *nmr, struct netmap_bdg_ops *bdg_ops);
1094 int netmap_bdg_config(struct nmreq *nmr);
1095 
1096 #else /* !WITH_VALE */
1097 #define	netmap_get_bdg_na(_1, _2, _3)	0
1098 #define netmap_init_bridges(_1)
1099 #define	netmap_bdg_ctl(_1, _2)	EINVAL
1100 #endif /* !WITH_VALE */
1101 
1102 #ifdef WITH_PIPES
1103 /* max number of pipes per device */
1104 #define NM_MAXPIPES	64	/* XXX how many? */
1105 /* in case of no error, returns the actual number of pipes in nmr->nr_arg1 */
1106 int netmap_pipe_alloc(struct netmap_adapter *, struct nmreq *nmr);
1107 void netmap_pipe_dealloc(struct netmap_adapter *);
1108 int netmap_get_pipe_na(struct nmreq *nmr, struct netmap_adapter **na, int create);
1109 #else /* !WITH_PIPES */
1110 #define NM_MAXPIPES	0
1111 #define netmap_pipe_alloc(_1, _2) 	EOPNOTSUPP
1112 #define netmap_pipe_dealloc(_1)
1113 #define netmap_get_pipe_na(_1, _2, _3)	0
1114 #endif
1115 
1116 #ifdef WITH_MONITOR
1117 int netmap_get_monitor_na(struct nmreq *nmr, struct netmap_adapter **na, int create);
1118 #else
1119 #define netmap_get_monitor_na(_1, _2, _3) 0
1120 #endif
1121 
1122 /* Various prototypes */
1123 int netmap_poll(struct cdev *dev, int events, struct thread *td);
1124 int netmap_init(void);
1125 void netmap_fini(void);
1126 int netmap_get_memory(struct netmap_priv_d* p);
1127 void netmap_dtor(void *data);
1128 int netmap_dtor_locked(struct netmap_priv_d *priv);
1129 
1130 int netmap_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag, struct thread *td);
1131 
1132 /* netmap_adapter creation/destruction */
1133 
1134 // #define NM_DEBUG_PUTGET 1
1135 
1136 #ifdef NM_DEBUG_PUTGET
1137 
1138 #define NM_DBG(f) __##f
1139 
1140 void __netmap_adapter_get(struct netmap_adapter *na);
1141 
1142 #define netmap_adapter_get(na) 				\
1143 	do {						\
1144 		struct netmap_adapter *__na = na;	\
1145 		D("getting %p:%s (%d)", __na, (__na)->name, (__na)->na_refcount);	\
1146 		__netmap_adapter_get(__na);		\
1147 	} while (0)
1148 
1149 int __netmap_adapter_put(struct netmap_adapter *na);
1150 
1151 #define netmap_adapter_put(na)				\
1152 	({						\
1153 		struct netmap_adapter *__na = na;	\
1154 		D("putting %p:%s (%d)", __na, (__na)->name, (__na)->na_refcount);	\
1155 		__netmap_adapter_put(__na);		\
1156 	})
1157 
1158 #else /* !NM_DEBUG_PUTGET */
1159 
1160 #define NM_DBG(f) f
1161 void netmap_adapter_get(struct netmap_adapter *na);
1162 int netmap_adapter_put(struct netmap_adapter *na);
1163 
1164 #endif /* !NM_DEBUG_PUTGET */
1165 
1166 
1167 /*
1168  * module variables
1169  */
1170 #define NETMAP_BUF_BASE(na)	((na)->na_lut[0].vaddr)
1171 #define NETMAP_BUF_SIZE(na)	((na)->na_lut_objsize)
1172 extern int netmap_mitigate;	// XXX not really used
1173 extern int netmap_no_pendintr;
1174 extern int netmap_verbose;	// XXX debugging
1175 enum {                                  /* verbose flags */
1176 	NM_VERB_ON = 1,                 /* generic verbose */
1177 	NM_VERB_HOST = 0x2,             /* verbose host stack */
1178 	NM_VERB_RXSYNC = 0x10,          /* verbose on rxsync/txsync */
1179 	NM_VERB_TXSYNC = 0x20,
1180 	NM_VERB_RXINTR = 0x100,         /* verbose on rx/tx intr (driver) */
1181 	NM_VERB_TXINTR = 0x200,
1182 	NM_VERB_NIC_RXSYNC = 0x1000,    /* verbose on rx/tx intr (driver) */
1183 	NM_VERB_NIC_TXSYNC = 0x2000,
1184 };
1185 
1186 extern int netmap_txsync_retry;
1187 extern int netmap_generic_mit;
1188 extern int netmap_generic_ringsize;
1189 extern int netmap_generic_rings;
1190 
1191 /*
1192  * NA returns a pointer to the struct netmap adapter from the ifp,
1193  * WNA is used to write it.
1194  */
1195 #define	NA(_ifp)	((struct netmap_adapter *)WNA(_ifp))
1196 
1197 /*
1198  * Macros to determine if an interface is netmap capable or netmap enabled.
1199  * See the magic field in struct netmap_adapter.
1200  */
1201 #ifdef __FreeBSD__
1202 /*
1203  * on FreeBSD just use if_capabilities and if_capenable.
1204  */
1205 #define NETMAP_CAPABLE(ifp)	(NA(ifp) &&		\
1206 	(ifp)->if_capabilities & IFCAP_NETMAP )
1207 
1208 #define	NETMAP_SET_CAPABLE(ifp)				\
1209 	(ifp)->if_capabilities |= IFCAP_NETMAP
1210 
1211 #else	/* linux */
1212 
1213 /*
1214  * on linux:
1215  * we check if NA(ifp) is set and its first element has a related
1216  * magic value. The capenable is within the struct netmap_adapter.
1217  */
1218 #define	NETMAP_MAGIC	0x52697a7a
1219 
1220 #define NETMAP_CAPABLE(ifp)	(NA(ifp) &&		\
1221 	((uint32_t)(uintptr_t)NA(ifp) ^ NA(ifp)->magic) == NETMAP_MAGIC )
1222 
1223 #define	NETMAP_SET_CAPABLE(ifp)				\
1224 	NA(ifp)->magic = ((uint32_t)(uintptr_t)NA(ifp)) ^ NETMAP_MAGIC
1225 
1226 #endif	/* linux */
1227 
1228 #ifdef __FreeBSD__
1229 
1230 /* Assigns the device IOMMU domain to an allocator.
1231  * Returns -ENOMEM in case the domain is different */
1232 #define nm_iommu_group_id(dev) (0)
1233 
1234 /* Callback invoked by the dma machinery after a successful dmamap_load */
1235 static void netmap_dmamap_cb(__unused void *arg,
1236     __unused bus_dma_segment_t * segs, __unused int nseg, __unused int error)
1237 {
1238 }
1239 
1240 /* bus_dmamap_load wrapper: call aforementioned function if map != NULL.
1241  * XXX can we do it without a callback ?
1242  */
1243 static inline void
1244 netmap_load_map(struct netmap_adapter *na,
1245 	bus_dma_tag_t tag, bus_dmamap_t map, void *buf)
1246 {
1247 	if (map)
1248 		bus_dmamap_load(tag, map, buf, NETMAP_BUF_SIZE(na),
1249 		    netmap_dmamap_cb, NULL, BUS_DMA_NOWAIT);
1250 }
1251 
1252 static inline void
1253 netmap_unload_map(struct netmap_adapter *na,
1254         bus_dma_tag_t tag, bus_dmamap_t map)
1255 {
1256 	if (map)
1257 		bus_dmamap_unload(tag, map);
1258 }
1259 
1260 /* update the map when a buffer changes. */
1261 static inline void
1262 netmap_reload_map(struct netmap_adapter *na,
1263 	bus_dma_tag_t tag, bus_dmamap_t map, void *buf)
1264 {
1265 	if (map) {
1266 		bus_dmamap_unload(tag, map);
1267 		bus_dmamap_load(tag, map, buf, NETMAP_BUF_SIZE(na),
1268 		    netmap_dmamap_cb, NULL, BUS_DMA_NOWAIT);
1269 	}
1270 }
1271 
1272 #else /* linux */
1273 
1274 int nm_iommu_group_id(bus_dma_tag_t dev);
1275 extern size_t     netmap_mem_get_bufsize(struct netmap_mem_d *);
1276 #include <linux/dma-mapping.h>
1277 
1278 static inline void
1279 netmap_load_map(struct netmap_adapter *na,
1280 	bus_dma_tag_t tag, bus_dmamap_t map, void *buf)
1281 {
1282 	if (map) {
1283 		*map = dma_map_single(na->pdev, buf, netmap_mem_get_bufsize(na->nm_mem),
1284 				DMA_BIDIRECTIONAL);
1285 	}
1286 }
1287 
1288 static inline void
1289 netmap_unload_map(struct netmap_adapter *na,
1290 	bus_dma_tag_t tag, bus_dmamap_t map)
1291 {
1292 	u_int sz = netmap_mem_get_bufsize(na->nm_mem);
1293 
1294 	if (*map) {
1295 		dma_unmap_single(na->pdev, *map, sz,
1296 				DMA_BIDIRECTIONAL);
1297 	}
1298 }
1299 
1300 static inline void
1301 netmap_reload_map(struct netmap_adapter *na,
1302 	bus_dma_tag_t tag, bus_dmamap_t map, void *buf)
1303 {
1304 	u_int sz = netmap_mem_get_bufsize(na->nm_mem);
1305 
1306 	if (*map) {
1307 		dma_unmap_single(na->pdev, *map, sz,
1308 				DMA_BIDIRECTIONAL);
1309 	}
1310 
1311 	*map = dma_map_single(na->pdev, buf, sz,
1312 				DMA_BIDIRECTIONAL);
1313 }
1314 
1315 /*
1316  * XXX How do we redefine these functions:
1317  *
1318  * on linux we need
1319  *	dma_map_single(&pdev->dev, virt_addr, len, direction)
1320  *	dma_unmap_single(&adapter->pdev->dev, phys_addr, len, direction
1321  * The len can be implicit (on netmap it is NETMAP_BUF_SIZE)
1322  * unfortunately the direction is not, so we need to change
1323  * something to have a cross API
1324  */
1325 
1326 #if 0
1327 	struct e1000_buffer *buffer_info =  &tx_ring->buffer_info[l];
1328 	/* set time_stamp *before* dma to help avoid a possible race */
1329 	buffer_info->time_stamp = jiffies;
1330 	buffer_info->mapped_as_page = false;
1331 	buffer_info->length = len;
1332 	//buffer_info->next_to_watch = l;
1333 	/* reload dma map */
1334 	dma_unmap_single(&adapter->pdev->dev, buffer_info->dma,
1335 			NETMAP_BUF_SIZE, DMA_TO_DEVICE);
1336 	buffer_info->dma = dma_map_single(&adapter->pdev->dev,
1337 			addr, NETMAP_BUF_SIZE, DMA_TO_DEVICE);
1338 
1339 	if (dma_mapping_error(&adapter->pdev->dev, buffer_info->dma)) {
1340 		D("dma mapping error");
1341 		/* goto dma_error; See e1000_put_txbuf() */
1342 		/* XXX reset */
1343 	}
1344 	tx_desc->buffer_addr = htole64(buffer_info->dma); //XXX
1345 
1346 #endif
1347 
1348 /*
1349  * The bus_dmamap_sync() can be one of wmb() or rmb() depending on direction.
1350  */
1351 #define bus_dmamap_sync(_a, _b, _c)
1352 
1353 #endif /* linux */
1354 
1355 
1356 /*
1357  * functions to map NIC to KRING indexes (n2k) and vice versa (k2n)
1358  */
1359 static inline int
1360 netmap_idx_n2k(struct netmap_kring *kr, int idx)
1361 {
1362 	int n = kr->nkr_num_slots;
1363 	idx += kr->nkr_hwofs;
1364 	if (idx < 0)
1365 		return idx + n;
1366 	else if (idx < n)
1367 		return idx;
1368 	else
1369 		return idx - n;
1370 }
1371 
1372 
1373 static inline int
1374 netmap_idx_k2n(struct netmap_kring *kr, int idx)
1375 {
1376 	int n = kr->nkr_num_slots;
1377 	idx -= kr->nkr_hwofs;
1378 	if (idx < 0)
1379 		return idx + n;
1380 	else if (idx < n)
1381 		return idx;
1382 	else
1383 		return idx - n;
1384 }
1385 
1386 
1387 /* Entries of the look-up table. */
1388 struct lut_entry {
1389 	void *vaddr;		/* virtual address. */
1390 	vm_paddr_t paddr;	/* physical address. */
1391 };
1392 
1393 struct netmap_obj_pool;
1394 
1395 /*
1396  * NMB return the virtual address of a buffer (buffer 0 on bad index)
1397  * PNMB also fills the physical address
1398  */
1399 static inline void *
1400 NMB(struct netmap_adapter *na, struct netmap_slot *slot)
1401 {
1402 	struct lut_entry *lut = na->na_lut;
1403 	uint32_t i = slot->buf_idx;
1404 	return (unlikely(i >= na->na_lut_objtotal)) ?
1405 		lut[0].vaddr : lut[i].vaddr;
1406 }
1407 
1408 static inline void *
1409 PNMB(struct netmap_adapter *na, struct netmap_slot *slot, uint64_t *pp)
1410 {
1411 	uint32_t i = slot->buf_idx;
1412 	struct lut_entry *lut = na->na_lut;
1413 	void *ret = (i >= na->na_lut_objtotal) ? lut[0].vaddr : lut[i].vaddr;
1414 
1415 	*pp = (i >= na->na_lut_objtotal) ? lut[0].paddr : lut[i].paddr;
1416 	return ret;
1417 }
1418 
1419 /* Generic version of NMB, which uses device-specific memory. */
1420 
1421 
1422 
1423 void netmap_txsync_to_host(struct netmap_adapter *na);
1424 
1425 
1426 /*
1427  * Structure associated to each thread which registered an interface.
1428  *
1429  * The first 4 fields of this structure are written by NIOCREGIF and
1430  * read by poll() and NIOC?XSYNC.
1431  *
1432  * There is low contention among writers (a correct user program
1433  * should have none) and among writers and readers, so we use a
1434  * single global lock to protect the structure initialization;
1435  * since initialization involves the allocation of memory,
1436  * we reuse the memory allocator lock.
1437  *
1438  * Read access to the structure is lock free. Readers must check that
1439  * np_nifp is not NULL before using the other fields.
1440  * If np_nifp is NULL initialization has not been performed,
1441  * so they should return an error to userspace.
1442  *
1443  * The ref_done field is used to regulate access to the refcount in the
1444  * memory allocator. The refcount must be incremented at most once for
1445  * each open("/dev/netmap"). The increment is performed by the first
1446  * function that calls netmap_get_memory() (currently called by
1447  * mmap(), NIOCGINFO and NIOCREGIF).
1448  * If the refcount is incremented, it is then decremented when the
1449  * private structure is destroyed.
1450  */
1451 struct netmap_priv_d {
1452 	struct netmap_if * volatile np_nifp;	/* netmap if descriptor. */
1453 
1454 	struct netmap_adapter	*np_na;
1455 	uint32_t	np_flags;	/* from the ioctl */
1456 	u_int		np_txqfirst, np_txqlast; /* range of tx rings to scan */
1457 	u_int		np_rxqfirst, np_rxqlast; /* range of rx rings to scan */
1458 	uint16_t	np_txpoll;	/* XXX and also np_rxpoll ? */
1459 
1460 	struct netmap_mem_d     *np_mref;	/* use with NMG_LOCK held */
1461 	/* np_refcount is only used on FreeBSD */
1462 	int		np_refcount;	/* use with NMG_LOCK held */
1463 
1464 	/* pointers to the selinfo to be used for selrecord.
1465 	 * Either the local or the global one depending on the
1466 	 * number of rings.
1467 	 */
1468 	NM_SELINFO_T *np_rxsi, *np_txsi;
1469 	struct thread	*np_td;		/* kqueue, just debugging */
1470 };
1471 
1472 #ifdef WITH_MONITOR
1473 
1474 struct netmap_monitor_adapter {
1475 	struct netmap_adapter up;
1476 
1477 	struct netmap_priv_d priv;
1478 	uint32_t flags;
1479 };
1480 
1481 #endif /* WITH_MONITOR */
1482 
1483 
1484 /*
1485  * generic netmap emulation for devices that do not have
1486  * native netmap support.
1487  */
1488 int generic_netmap_attach(struct ifnet *ifp);
1489 
1490 int netmap_catch_rx(struct netmap_adapter *na, int intercept);
1491 void generic_rx_handler(struct ifnet *ifp, struct mbuf *m);;
1492 void netmap_catch_tx(struct netmap_generic_adapter *na, int enable);
1493 int generic_xmit_frame(struct ifnet *ifp, struct mbuf *m, void *addr, u_int len, u_int ring_nr);
1494 int generic_find_num_desc(struct ifnet *ifp, u_int *tx, u_int *rx);
1495 void generic_find_num_queues(struct ifnet *ifp, u_int *txq, u_int *rxq);
1496 
1497 //#define RATE_GENERIC  /* Enables communication statistics for generic. */
1498 #ifdef RATE_GENERIC
1499 void generic_rate(int txp, int txs, int txi, int rxp, int rxs, int rxi);
1500 #else
1501 #define generic_rate(txp, txs, txi, rxp, rxs, rxi)
1502 #endif
1503 
1504 /*
1505  * netmap_mitigation API. This is used by the generic adapter
1506  * to reduce the number of interrupt requests/selwakeup
1507  * to clients on incoming packets.
1508  */
1509 void netmap_mitigation_init(struct nm_generic_mit *mit, int idx,
1510                                 struct netmap_adapter *na);
1511 void netmap_mitigation_start(struct nm_generic_mit *mit);
1512 void netmap_mitigation_restart(struct nm_generic_mit *mit);
1513 int netmap_mitigation_active(struct nm_generic_mit *mit);
1514 void netmap_mitigation_cleanup(struct nm_generic_mit *mit);
1515 
1516 
1517 
1518 /* Shared declarations for the VALE switch. */
1519 
1520 /*
1521  * Each transmit queue accumulates a batch of packets into
1522  * a structure before forwarding. Packets to the same
1523  * destination are put in a list using ft_next as a link field.
1524  * ft_frags and ft_next are valid only on the first fragment.
1525  */
1526 struct nm_bdg_fwd {	/* forwarding entry for a bridge */
1527 	void *ft_buf;		/* netmap or indirect buffer */
1528 	uint8_t ft_frags;	/* how many fragments (only on 1st frag) */
1529 	uint8_t _ft_port;	/* dst port (unused) */
1530 	uint16_t ft_flags;	/* flags, e.g. indirect */
1531 	uint16_t ft_len;	/* src fragment len */
1532 	uint16_t ft_next;	/* next packet to same destination */
1533 };
1534 
1535 /* struct 'virtio_net_hdr' from linux. */
1536 struct nm_vnet_hdr {
1537 #define VIRTIO_NET_HDR_F_NEEDS_CSUM     1	/* Use csum_start, csum_offset */
1538 #define VIRTIO_NET_HDR_F_DATA_VALID    2	/* Csum is valid */
1539     uint8_t flags;
1540 #define VIRTIO_NET_HDR_GSO_NONE         0       /* Not a GSO frame */
1541 #define VIRTIO_NET_HDR_GSO_TCPV4        1       /* GSO frame, IPv4 TCP (TSO) */
1542 #define VIRTIO_NET_HDR_GSO_UDP          3       /* GSO frame, IPv4 UDP (UFO) */
1543 #define VIRTIO_NET_HDR_GSO_TCPV6        4       /* GSO frame, IPv6 TCP */
1544 #define VIRTIO_NET_HDR_GSO_ECN          0x80    /* TCP has ECN set */
1545     uint8_t gso_type;
1546     uint16_t hdr_len;
1547     uint16_t gso_size;
1548     uint16_t csum_start;
1549     uint16_t csum_offset;
1550 };
1551 
1552 #define WORST_CASE_GSO_HEADER	(14+40+60)  /* IPv6 + TCP */
1553 
1554 /* Private definitions for IPv4, IPv6, UDP and TCP headers. */
1555 
1556 struct nm_iphdr {
1557 	uint8_t		version_ihl;
1558 	uint8_t		tos;
1559 	uint16_t	tot_len;
1560 	uint16_t	id;
1561 	uint16_t	frag_off;
1562 	uint8_t		ttl;
1563 	uint8_t		protocol;
1564 	uint16_t	check;
1565 	uint32_t	saddr;
1566 	uint32_t	daddr;
1567 	/*The options start here. */
1568 };
1569 
1570 struct nm_tcphdr {
1571 	uint16_t	source;
1572 	uint16_t	dest;
1573 	uint32_t	seq;
1574 	uint32_t	ack_seq;
1575 	uint8_t		doff;  /* Data offset + Reserved */
1576 	uint8_t		flags;
1577 	uint16_t	window;
1578 	uint16_t	check;
1579 	uint16_t	urg_ptr;
1580 };
1581 
1582 struct nm_udphdr {
1583 	uint16_t	source;
1584 	uint16_t	dest;
1585 	uint16_t	len;
1586 	uint16_t	check;
1587 };
1588 
1589 struct nm_ipv6hdr {
1590 	uint8_t		priority_version;
1591 	uint8_t		flow_lbl[3];
1592 
1593 	uint16_t	payload_len;
1594 	uint8_t		nexthdr;
1595 	uint8_t		hop_limit;
1596 
1597 	uint8_t		saddr[16];
1598 	uint8_t		daddr[16];
1599 };
1600 
1601 /* Type used to store a checksum (in host byte order) that hasn't been
1602  * folded yet.
1603  */
1604 #define rawsum_t uint32_t
1605 
1606 rawsum_t nm_csum_raw(uint8_t *data, size_t len, rawsum_t cur_sum);
1607 uint16_t nm_csum_ipv4(struct nm_iphdr *iph);
1608 void nm_csum_tcpudp_ipv4(struct nm_iphdr *iph, void *data,
1609 		      size_t datalen, uint16_t *check);
1610 void nm_csum_tcpudp_ipv6(struct nm_ipv6hdr *ip6h, void *data,
1611 		      size_t datalen, uint16_t *check);
1612 uint16_t nm_csum_fold(rawsum_t cur_sum);
1613 
1614 void bdg_mismatch_datapath(struct netmap_vp_adapter *na,
1615 			   struct netmap_vp_adapter *dst_na,
1616 			   struct nm_bdg_fwd *ft_p, struct netmap_ring *ring,
1617 			   u_int *j, u_int lim, u_int *howmany);
1618 
1619 /* persistent virtual port routines */
1620 int nm_vi_persist(const char *, struct ifnet **);
1621 void nm_vi_detach(struct ifnet *);
1622 void nm_vi_init_index(void);
1623 
1624 #endif /* _NET_NETMAP_KERN_H_ */
1625