xref: /freebsd/sys/dev/netmap/netmap_kern.h (revision 2e159ef0b597a1f1b78c02b771524eabfa502626)
1 /*
2  * Copyright (C) 2011-2013 Matteo Landi, Luigi Rizzo. All rights reserved.
3  * Copyright (C) 2013 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 
39 #if defined(__FreeBSD__)
40 
41 #define likely(x)	__builtin_expect((long)!!(x), 1L)
42 #define unlikely(x)	__builtin_expect((long)!!(x), 0L)
43 
44 #define	NM_LOCK_T	struct mtx
45 #define	NMG_LOCK_T	struct mtx
46 #define NMG_LOCK_INIT()	mtx_init(&netmap_global_lock, \
47 				"netmap global lock", NULL, MTX_DEF)
48 #define NMG_LOCK_DESTROY()	mtx_destroy(&netmap_global_lock)
49 #define NMG_LOCK()	mtx_lock(&netmap_global_lock)
50 #define NMG_UNLOCK()	mtx_unlock(&netmap_global_lock)
51 #define NMG_LOCK_ASSERT()	mtx_assert(&netmap_global_lock, MA_OWNED)
52 
53 #define	NM_SELINFO_T	struct selinfo
54 #define	MBUF_LEN(m)	((m)->m_pkthdr.len)
55 #define	MBUF_IFP(m)	((m)->m_pkthdr.rcvif)
56 #define	NM_SEND_UP(ifp, m)	((ifp)->if_input)(ifp, m)
57 
58 #define NM_ATOMIC_T	volatile int	// XXX ?
59 /* atomic operations */
60 #include <machine/atomic.h>
61 #define NM_ATOMIC_TEST_AND_SET(p)       (!atomic_cmpset_acq_int((p), 0, 1))
62 #define NM_ATOMIC_CLEAR(p)              atomic_store_rel_int((p), 0)
63 
64 
65 MALLOC_DECLARE(M_NETMAP);
66 
67 // XXX linux struct, not used in FreeBSD
68 struct net_device_ops {
69 };
70 struct hrtimer {
71 };
72 
73 #elif defined (linux)
74 
75 #define	NM_LOCK_T	safe_spinlock_t	// see bsd_glue.h
76 #define	NM_SELINFO_T	wait_queue_head_t
77 #define	MBUF_LEN(m)	((m)->len)
78 #define	MBUF_IFP(m)	((m)->dev)
79 #define	NM_SEND_UP(ifp, m)	netif_rx(m)
80 
81 #define NM_ATOMIC_T	volatile long unsigned int
82 
83 // XXX a mtx would suffice here too 20130404 gl
84 #define NMG_LOCK_T		struct semaphore
85 #define NMG_LOCK_INIT()		sema_init(&netmap_global_lock, 1)
86 #define NMG_LOCK_DESTROY()
87 #define NMG_LOCK()		down(&netmap_global_lock)
88 #define NMG_UNLOCK()		up(&netmap_global_lock)
89 #define NMG_LOCK_ASSERT()	//	XXX to be completed
90 
91 #ifndef DEV_NETMAP
92 #define DEV_NETMAP
93 #endif /* DEV_NETMAP */
94 
95 /*
96  * IFCAP_NETMAP goes into net_device's priv_flags (if_capenable).
97  * This was 16 bits up to linux 2.6.36, so we need a 16 bit value on older
98  * platforms and tolerate the clash with IFF_DYNAMIC and IFF_BRIDGE_PORT.
99  * For the 32-bit value, 0x100000 has no clashes until at least 3.5.1
100  */
101 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,37)
102 #define IFCAP_NETMAP	0x8000
103 #else
104 #define IFCAP_NETMAP	0x200000
105 #endif
106 
107 #elif defined (__APPLE__)
108 
109 #warning apple support is incomplete.
110 #define likely(x)	__builtin_expect(!!(x), 1)
111 #define unlikely(x)	__builtin_expect(!!(x), 0)
112 #define	NM_LOCK_T	IOLock *
113 #define	NM_SELINFO_T	struct selinfo
114 #define	MBUF_LEN(m)	((m)->m_pkthdr.len)
115 #define	NM_SEND_UP(ifp, m)	((ifp)->if_input)(ifp, m)
116 
117 #else
118 
119 #error unsupported platform
120 
121 #endif /* end - platform-specific code */
122 
123 #define ND(format, ...)
124 #define D(format, ...)						\
125 	do {							\
126 		struct timeval __xxts;				\
127 		microtime(&__xxts);				\
128 		printf("%03d.%06d %s [%d] " format "\n",	\
129 		(int)__xxts.tv_sec % 1000, (int)__xxts.tv_usec,	\
130 		__FUNCTION__, __LINE__, ##__VA_ARGS__);		\
131 	} while (0)
132 
133 /* rate limited, lps indicates how many per second */
134 #define RD(lps, format, ...)					\
135 	do {							\
136 		static int t0, __cnt;				\
137 		if (t0 != time_second) {			\
138 			t0 = time_second;			\
139 			__cnt = 0;				\
140 		}						\
141 		if (__cnt++ < lps)				\
142 			D(format, ##__VA_ARGS__);		\
143 	} while (0)
144 
145 struct netmap_adapter;
146 struct nm_bdg_fwd;
147 struct nm_bridge;
148 struct netmap_priv_d;
149 
150 const char *nm_dump_buf(char *p, int len, int lim, char *dst);
151 
152 #include "netmap_mbq.h"
153 
154 extern NMG_LOCK_T	netmap_global_lock;
155 
156 /*
157  * private, kernel view of a ring. Keeps track of the status of
158  * a ring across system calls.
159  *
160  *	nr_hwcur	index of the next buffer to refill.
161  *			It corresponds to ring->cur - ring->reserved
162  *
163  *	nr_hwavail	the number of slots "owned" by userspace.
164  *			nr_hwavail =:= ring->avail + ring->reserved
165  *
166  * The indexes in the NIC and netmap rings are offset by nkr_hwofs slots.
167  * This is so that, on a reset, buffers owned by userspace are not
168  * modified by the kernel. In particular:
169  * RX rings: the next empty buffer (hwcur + hwavail + hwofs) coincides with
170  * 	the next empty buffer as known by the hardware (next_to_check or so).
171  * TX rings: hwcur + hwofs coincides with next_to_send
172  *
173  * Clients cannot issue concurrent syscall on a ring. The system
174  * detects this and reports an error using two flags,
175  * NKR_WBUSY and NKR_RBUSY
176  * For received packets, slot->flags is set to nkr_slot_flags
177  * so we can provide a proper initial value (e.g. set NS_FORWARD
178  * when operating in 'transparent' mode).
179  *
180  * The following fields are used to implement lock-free copy of packets
181  * from input to output ports in VALE switch:
182  *	nkr_hwlease	buffer after the last one being copied.
183  *			A writer in nm_bdg_flush reserves N buffers
184  *			from nr_hwlease, advances it, then does the
185  *			copy outside the lock.
186  *			In RX rings (used for VALE ports),
187  *			nkr_hwcur + nkr_hwavail <= nkr_hwlease < nkr_hwcur+N-1
188  *			In TX rings (used for NIC or host stack ports)
189  *			nkr_hwcur <= nkr_hwlease < nkr_hwcur+ nkr_hwavail
190  *	nkr_leases	array of nkr_num_slots where writers can report
191  *			completion of their block. NR_NOSLOT (~0) indicates
192  *			that the writer has not finished yet
193  *	nkr_lease_idx	index of next free slot in nr_leases, to be assigned
194  *
195  * The kring is manipulated by txsync/rxsync and generic netmap function.
196  * q_lock is used to arbitrate access to the kring from within the netmap
197  * code, and this and other protections guarantee that there is never
198  * more than 1 concurrent call to txsync or rxsync. So we are free
199  * to manipulate the kring from within txsync/rxsync without any extra
200  * locks.
201  */
202 struct netmap_kring {
203 	struct netmap_ring *ring;
204 	uint32_t nr_hwcur;
205 	uint32_t nr_hwavail;
206 	uint32_t nr_kflags;	/* private driver flags */
207 	int32_t nr_hwreserved;
208 #define NKR_PENDINTR	0x1	// Pending interrupt.
209 	uint32_t nkr_num_slots;
210 	int32_t	nkr_hwofs;	/* offset between NIC and netmap ring */
211 
212 	uint16_t	nkr_slot_flags;	/* initial value for flags */
213 	struct netmap_adapter *na;
214 	struct nm_bdg_fwd *nkr_ft;
215 	uint32_t *nkr_leases;
216 #define NR_NOSLOT	((uint32_t)~0)
217 	uint32_t nkr_hwlease;
218 	uint32_t nkr_lease_idx;
219 
220 	NM_SELINFO_T si;	/* poll/select wait queue */
221 	NM_LOCK_T q_lock;	/* protects kring and ring. */
222 	NM_ATOMIC_T nr_busy;	/* prevent concurrent syscalls */
223 
224 	volatile int nkr_stopped;
225 
226 	/* support for adapters without native netmap support.
227 	 * On tx rings we preallocate an array of tx buffers
228 	 * (same size as the netmap ring), on rx rings we
229 	 * store incoming packets in a queue.
230 	 * XXX who writes to the rx queue ?
231 	 */
232 	struct mbuf **tx_pool;
233 	u_int nr_ntc;                   /* Emulation of a next-to-clean RX ring pointer. */
234 	struct mbq rx_queue;            /* A queue for intercepted rx mbufs. */
235 
236 } __attribute__((__aligned__(64)));
237 
238 
239 /* return the next index, with wraparound */
240 static inline uint32_t
241 nm_next(uint32_t i, uint32_t lim)
242 {
243 	return unlikely (i == lim) ? 0 : i + 1;
244 }
245 
246 /*
247  *
248  * Here is the layout for the Rx and Tx rings.
249 
250        RxRING                            TxRING
251 
252       +-----------------+            +-----------------+
253       |                 |            |                 |
254       |XXX free slot XXX|            |XXX free slot XXX|
255       +-----------------+            +-----------------+
256       |                 |<-hwcur     |                 |<-hwcur
257       | reserved    h   |            | (ready          |
258       +-----------  w  -+            |  to be          |
259  cur->|             a   |            |  sent)      h   |
260       |             v   |            +----------   w   |
261       |             a   |       cur->| (being      a   |
262       |             i   |            |  prepared)  v   |
263       | avail       l   |            |             a   |
264       +-----------------+            +  a  ------  i   +
265       |                 | ...        |  v          l   |<-hwlease
266       | (being          | ...        |  a              | ...
267       |  prepared)      | ...        |  i              | ...
268       +-----------------+ ...        |  l              | ...
269       |                 |<-hwlease   +-----------------+
270       |                 |            |                 |
271       |                 |            |                 |
272       |                 |            |                 |
273       |                 |            |                 |
274       +-----------------+            +-----------------+
275 
276  * The cur/avail (user view) and hwcur/hwavail (kernel view)
277  * are used in the normal operation of the card.
278  *
279  * When a ring is the output of a switch port (Rx ring for
280  * a VALE port, Tx ring for the host stack or NIC), slots
281  * are reserved in blocks through 'hwlease' which points
282  * to the next unused slot.
283  * On an Rx ring, hwlease is always after hwavail,
284  * and completions cause avail to advance.
285  * On a Tx ring, hwlease is always between cur and hwavail,
286  * and completions cause cur to advance.
287  *
288  * nm_kr_space() returns the maximum number of slots that
289  * can be assigned.
290  * nm_kr_lease() reserves the required number of buffers,
291  *    advances nkr_hwlease and also returns an entry in
292  *    a circular array where completions should be reported.
293  */
294 
295 
296 
297 
298 enum txrx { NR_RX = 0, NR_TX = 1 };
299 
300 /*
301  * The "struct netmap_adapter" extends the "struct adapter"
302  * (or equivalent) device descriptor.
303  * It contains all base fields needed to support netmap operation.
304  * There are in fact different types of netmap adapters
305  * (native, generic, VALE switch...) so a netmap_adapter is
306  * just the first field in the derived type.
307  */
308 struct netmap_adapter {
309 	/*
310 	 * On linux we do not have a good way to tell if an interface
311 	 * is netmap-capable. So we always use the following trick:
312 	 * NA(ifp) points here, and the first entry (which hopefully
313 	 * always exists and is at least 32 bits) contains a magic
314 	 * value which we can use to detect that the interface is good.
315 	 */
316 	uint32_t magic;
317 	uint32_t na_flags;	/* enabled, and other flags */
318 #define NAF_SKIP_INTR	1	/* use the regular interrupt handler.
319 				 * useful during initialization
320 				 */
321 #define NAF_SW_ONLY	2	/* forward packets only to sw adapter */
322 #define NAF_BDG_MAYSLEEP 4	/* the bridge is allowed to sleep when
323 				 * forwarding packets coming from this
324 				 * interface
325 				 */
326 #define NAF_MEM_OWNER	8	/* the adapter is responsible for the
327 				 * deallocation of the memory allocator
328 				 */
329 #define NAF_NATIVE_ON   16      /* the adapter is native and the attached
330 				 * interface is in netmap mode
331 				 */
332 #define	NAF_NETMAP_ON	32	/* netmap is active (either native or
333 				 * emulated. Where possible (e.g. FreeBSD)
334 				 * IFCAP_NETMAP also mirrors this flag.
335 				 */
336 	int active_fds; /* number of user-space descriptors using this
337 			 interface, which is equal to the number of
338 			 struct netmap_if objs in the mapped region. */
339 
340 	u_int num_rx_rings; /* number of adapter receive rings */
341 	u_int num_tx_rings; /* number of adapter transmit rings */
342 
343 	u_int num_tx_desc; /* number of descriptor in each queue */
344 	u_int num_rx_desc;
345 
346 	/* tx_rings and rx_rings are private but allocated
347 	 * as a contiguous chunk of memory. Each array has
348 	 * N+1 entries, for the adapter queues and for the host queue.
349 	 */
350 	struct netmap_kring *tx_rings; /* array of TX rings. */
351 	struct netmap_kring *rx_rings; /* array of RX rings. */
352 	void *tailroom;		       /* space below the rings array */
353 				       /* (used for leases) */
354 
355 
356 	NM_SELINFO_T tx_si, rx_si;	/* global wait queues */
357 
358 	/* copy of if_qflush and if_transmit pointers, to intercept
359 	 * packets from the network stack when netmap is active.
360 	 */
361 	int     (*if_transmit)(struct ifnet *, struct mbuf *);
362 
363 	/* references to the ifnet and device routines, used by
364 	 * the generic netmap functions.
365 	 */
366 	struct ifnet *ifp; /* adapter is ifp->if_softc */
367 
368 	/* private cleanup */
369 	void (*nm_dtor)(struct netmap_adapter *);
370 
371 	int (*nm_register)(struct netmap_adapter *, int onoff);
372 
373 	int (*nm_txsync)(struct netmap_adapter *, u_int ring, int flags);
374 	int (*nm_rxsync)(struct netmap_adapter *, u_int ring, int flags);
375 #define NAF_FORCE_READ    1
376 #define NAF_FORCE_RECLAIM 2
377 	/* return configuration information */
378 	int (*nm_config)(struct netmap_adapter *,
379 		u_int *txr, u_int *txd, u_int *rxr, u_int *rxd);
380 	int (*nm_krings_create)(struct netmap_adapter *);
381 	void (*nm_krings_delete)(struct netmap_adapter *);
382 	int (*nm_notify)(struct netmap_adapter *,
383 		u_int ring, enum txrx, int flags);
384 #define NAF_GLOBAL_NOTIFY 4
385 #define NAF_DISABLE_NOTIFY 8
386 
387 	/* standard refcount to control the lifetime of the adapter
388 	 * (it should be equal to the lifetime of the corresponding ifp)
389 	 */
390 	int na_refcount;
391 
392 	/* memory allocator (opaque)
393 	 * We also cache a pointer to the lut_entry for translating
394 	 * buffer addresses, and the total number of buffers.
395 	 */
396  	struct netmap_mem_d *nm_mem;
397 	struct lut_entry *na_lut;
398 	uint32_t na_lut_objtotal;	/* max buffer index */
399 
400 	/* used internally. If non-null, the interface cannot be bound
401 	 * from userspace
402 	 */
403 	void *na_private;
404 };
405 
406 /*
407  * If the NIC is owned by the kernel
408  * (i.e., bridge), neither another bridge nor user can use it;
409  * if the NIC is owned by a user, only users can share it.
410  * Evaluation must be done under NMG_LOCK().
411  */
412 #define NETMAP_OWNED_BY_KERN(na)	(na->na_private)
413 #define NETMAP_OWNED_BY_ANY(na) \
414 	(NETMAP_OWNED_BY_KERN(na) || (na->active_fds > 0))
415 
416 
417 /*
418  * derived netmap adapters for various types of ports
419  */
420 struct netmap_vp_adapter {	/* VALE software port */
421 	struct netmap_adapter up;
422 
423 	/*
424 	 * Bridge support:
425 	 *
426 	 * bdg_port is the port number used in the bridge;
427 	 * na_bdg points to the bridge this NA is attached to.
428 	 */
429 	int bdg_port;
430 	struct nm_bridge *na_bdg;
431 	int retry;
432 
433 	u_int offset;   /* Offset of ethernet header for each packet. */
434 };
435 
436 struct netmap_hw_adapter {	/* physical device */
437 	struct netmap_adapter up;
438 
439 	struct net_device_ops nm_ndo;	// XXX linux only
440 };
441 
442 struct netmap_generic_adapter {	/* non-native device */
443 	struct netmap_hw_adapter up;
444 
445 	/* Pointer to a previously used netmap adapter. */
446 	struct netmap_adapter *prev;
447 
448 	/* generic netmap adapters support:
449 	 * a net_device_ops struct overrides ndo_select_queue(),
450 	 * save_if_input saves the if_input hook (FreeBSD),
451 	 * mit_timer and mit_pending implement rx interrupt mitigation,
452 	 */
453 	struct net_device_ops generic_ndo;
454 	void (*save_if_input)(struct ifnet *, struct mbuf *);
455 
456 	struct hrtimer mit_timer;
457 	int mit_pending;
458 };
459 
460 #ifdef WITH_VALE
461 
462 /* bridge wrapper for non VALE ports. It is used to connect real devices to the bridge.
463  *
464  * The real device must already have its own netmap adapter (hwna).  The
465  * bridge wrapper and the hwna adapter share the same set of netmap rings and
466  * buffers, but they have two separate sets of krings descriptors, with tx/rx
467  * meanings swapped:
468  *
469  *                                  netmap
470  *           bwrap     krings       rings      krings      hwna
471  *         +------+   +------+     +-----+    +------+   +------+
472  *         |tx_rings->|      |\   /|     |----|      |<-tx_rings|
473  *         |      |   +------+ \ / +-----+    +------+   |      |
474  *         |      |             X                        |      |
475  *         |      |            / \                       |      |
476  *         |      |   +------+/   \+-----+    +------+   |      |
477  *         |rx_rings->|      |     |     |----|      |<-rx_rings|
478  *         |      |   +------+     +-----+    +------+   |      |
479  *         +------+                                      +------+
480  *
481  * - packets coming from the bridge go to the brwap rx rings, which are also the
482  *   hwna tx rings.  The bwrap notify callback will then complete the hwna tx
483  *   (see netmap_bwrap_notify).
484  * - packets coming from the outside go to the hwna rx rings, which are also the
485  *   bwrap tx rings.  The (overwritten) hwna notify method will then complete
486  *   the bridge tx (see netmap_bwrap_intr_notify).
487  *
488  *   The bridge wrapper may optionally connect the hwna 'host' rings to the
489  *   bridge. This is done by using a second port in the bridge and connecting it
490  *   to the 'host' netmap_vp_adapter contained in the netmap_bwrap_adapter.
491  *   The brwap host adapter cross-links the hwna host rings in the same way as shown above.
492  *
493  * - packets coming from the bridge and directed to host stack are handled by the
494  *   bwrap host notify callback (see netmap_bwrap_host_notify)
495  * - packets coming from the host stack are still handled by the overwritten
496  *   hwna notify callback (netmap_bwrap_intr_notify), but are diverted to the
497  *   host adapter depending on the ring number.
498  *
499  */
500 struct netmap_bwrap_adapter {
501 	struct netmap_vp_adapter up;
502 	struct netmap_vp_adapter host;  /* for host rings */
503 	struct netmap_adapter *hwna;	/* the underlying device */
504 
505 	/* backup of the hwna notify callback */
506 	int (*save_notify)(struct netmap_adapter *,
507 			u_int ring, enum txrx, int flags);
508 	/* When we attach a physical interface to the bridge, we
509 	 * allow the controlling process to terminate, so we need
510 	 * a place to store the netmap_priv_d data structure.
511 	 * This is only done when physical interfaces are attached to a bridge.
512 	 */
513 	struct netmap_priv_d *na_kpriv;
514 };
515 
516 
517 /*
518  * Available space in the ring. Only used in VALE code
519  */
520 static inline uint32_t
521 nm_kr_space(struct netmap_kring *k, int is_rx)
522 {
523 	int space;
524 
525 	if (is_rx) {
526 		int busy = k->nkr_hwlease - k->nr_hwcur + k->nr_hwreserved;
527 		if (busy < 0)
528 			busy += k->nkr_num_slots;
529 		space = k->nkr_num_slots - 1 - busy;
530 	} else {
531 		space = k->nr_hwcur + k->nr_hwavail - k->nkr_hwlease;
532 		if (space < 0)
533 			space += k->nkr_num_slots;
534 	}
535 #if 0
536 	// sanity check
537 	if (k->nkr_hwlease >= k->nkr_num_slots ||
538 		k->nr_hwcur >= k->nkr_num_slots ||
539 		k->nr_hwavail >= k->nkr_num_slots ||
540 		busy < 0 ||
541 		busy >= k->nkr_num_slots) {
542 		D("invalid kring, cur %d avail %d lease %d lease_idx %d lim %d",			k->nr_hwcur, k->nr_hwavail, k->nkr_hwlease,
543 			k->nkr_lease_idx, k->nkr_num_slots);
544 	}
545 #endif
546 	return space;
547 }
548 
549 
550 
551 
552 /* make a lease on the kring for N positions. return the
553  * lease index
554  */
555 static inline uint32_t
556 nm_kr_lease(struct netmap_kring *k, u_int n, int is_rx)
557 {
558 	uint32_t lim = k->nkr_num_slots - 1;
559 	uint32_t lease_idx = k->nkr_lease_idx;
560 
561 	k->nkr_leases[lease_idx] = NR_NOSLOT;
562 	k->nkr_lease_idx = nm_next(lease_idx, lim);
563 
564 	if (n > nm_kr_space(k, is_rx)) {
565 		D("invalid request for %d slots", n);
566 		panic("x");
567 	}
568 	/* XXX verify that there are n slots */
569 	k->nkr_hwlease += n;
570 	if (k->nkr_hwlease > lim)
571 		k->nkr_hwlease -= lim + 1;
572 
573 	if (k->nkr_hwlease >= k->nkr_num_slots ||
574 		k->nr_hwcur >= k->nkr_num_slots ||
575 		k->nr_hwavail >= k->nkr_num_slots ||
576 		k->nkr_lease_idx >= k->nkr_num_slots) {
577 		D("invalid kring %s, cur %d avail %d lease %d lease_idx %d lim %d",
578 			k->na->ifp->if_xname,
579 			k->nr_hwcur, k->nr_hwavail, k->nkr_hwlease,
580 			k->nkr_lease_idx, k->nkr_num_slots);
581 	}
582 	return lease_idx;
583 }
584 
585 #endif /* WITH_VALE */
586 
587 /* return update position */
588 static inline uint32_t
589 nm_kr_rxpos(struct netmap_kring *k)
590 {
591 	uint32_t pos = k->nr_hwcur + k->nr_hwavail;
592 	if (pos >= k->nkr_num_slots)
593 		pos -= k->nkr_num_slots;
594 #if 0
595 	if (pos >= k->nkr_num_slots ||
596 		k->nkr_hwlease >= k->nkr_num_slots ||
597 		k->nr_hwcur >= k->nkr_num_slots ||
598 		k->nr_hwavail >= k->nkr_num_slots ||
599 		k->nkr_lease_idx >= k->nkr_num_slots) {
600 		D("invalid kring, cur %d avail %d lease %d lease_idx %d lim %d",			k->nr_hwcur, k->nr_hwavail, k->nkr_hwlease,
601 			k->nkr_lease_idx, k->nkr_num_slots);
602 	}
603 #endif
604 	return pos;
605 }
606 
607 
608 /*
609  * protect against multiple threads using the same ring.
610  * also check that the ring has not been stopped.
611  * We only care for 0 or !=0 as a return code.
612  */
613 #define NM_KR_BUSY	1
614 #define NM_KR_STOPPED	2
615 
616 static __inline void nm_kr_put(struct netmap_kring *kr)
617 {
618 	NM_ATOMIC_CLEAR(&kr->nr_busy);
619 }
620 
621 static __inline int nm_kr_tryget(struct netmap_kring *kr)
622 {
623 	/* check a first time without taking the lock
624 	 * to avoid starvation for nm_kr_get()
625 	 */
626 	if (unlikely(kr->nkr_stopped)) {
627 		ND("ring %p stopped (%d)", kr, kr->nkr_stopped);
628 		return NM_KR_STOPPED;
629 	}
630 	if (unlikely(NM_ATOMIC_TEST_AND_SET(&kr->nr_busy)))
631 		return NM_KR_BUSY;
632 	/* check a second time with lock held */
633 	if (unlikely(kr->nkr_stopped)) {
634 		ND("ring %p stopped (%d)", kr, kr->nkr_stopped);
635 		nm_kr_put(kr);
636 		return NM_KR_STOPPED;
637 	}
638 	return 0;
639 }
640 
641 
642 /*
643  * The following are support routines used by individual drivers to
644  * support netmap operation.
645  *
646  * netmap_attach() initializes a struct netmap_adapter, allocating the
647  * 	struct netmap_ring's and the struct selinfo.
648  *
649  * netmap_detach() frees the memory allocated by netmap_attach().
650  *
651  * netmap_transmit() replaces the if_transmit routine of the interface,
652  *	and is used to intercept packets coming from the stack.
653  *
654  * netmap_load_map/netmap_reload_map are helper routines to set/reset
655  *	the dmamap for a packet buffer
656  *
657  * netmap_reset() is a helper routine to be called in the driver
658  *	when reinitializing a ring.
659  */
660 int netmap_attach(struct netmap_adapter *);
661 int netmap_attach_common(struct netmap_adapter *);
662 void netmap_detach_common(struct netmap_adapter *na);
663 void netmap_detach(struct ifnet *);
664 int netmap_transmit(struct ifnet *, struct mbuf *);
665 struct netmap_slot *netmap_reset(struct netmap_adapter *na,
666 	enum txrx tx, u_int n, u_int new_cur);
667 int netmap_ring_reinit(struct netmap_kring *);
668 
669 /* set/clear native flags. XXX maybe also if_transmit ? */
670 static inline void
671 nm_set_native_flags(struct netmap_adapter *na)
672 {
673 	struct ifnet *ifp = na->ifp;
674 
675 	na->na_flags |= (NAF_NATIVE_ON | NAF_NETMAP_ON);
676 #ifdef IFCAP_NETMAP /* or FreeBSD ? */
677 	ifp->if_capenable |= IFCAP_NETMAP;
678 #endif
679 #ifdef __FreeBSD__
680 	na->if_transmit = ifp->if_transmit;
681 	ifp->if_transmit = netmap_transmit;
682 #else
683 	na->if_transmit = (void *)ifp->netdev_ops;
684 	ifp->netdev_ops = &((struct netmap_hw_adapter *)na)->nm_ndo;
685 #endif
686 }
687 
688 static inline void
689 nm_clear_native_flags(struct netmap_adapter *na)
690 {
691 	struct ifnet *ifp = na->ifp;
692 
693 #ifdef __FreeBSD__
694 	ifp->if_transmit = na->if_transmit;
695 #else
696 	ifp->netdev_ops = (void *)na->if_transmit;
697 #endif
698 	na->na_flags &= ~(NAF_NATIVE_ON | NAF_NETMAP_ON);
699 #ifdef IFCAP_NETMAP /* or FreeBSD ? */
700 	ifp->if_capenable &= ~IFCAP_NETMAP;
701 #endif
702 }
703 
704 /*
705  * validates parameters in the ring/kring, returns a value for cur,
706  * and the 'new_slots' value in the argument.
707  * If any error, returns cur > lim to force a reinit.
708  */
709 u_int nm_txsync_prologue(struct netmap_kring *, u_int *);
710 
711 /*
712  * validates parameters in the ring/kring, returns a value for cur,
713  * and the 'reserved' value in the argument.
714  * If any error, returns cur > lim to force a reinit.
715  */
716 u_int nm_rxsync_prologue(struct netmap_kring *, u_int *);
717 
718 /*
719  * update kring and ring at the end of txsync
720  */
721 static inline void
722 nm_txsync_finalize(struct netmap_kring *kring, u_int cur)
723 {
724 	/* recompute hwreserved */
725 	kring->nr_hwreserved = cur - kring->nr_hwcur;
726 	if (kring->nr_hwreserved < 0)
727 		kring->nr_hwreserved += kring->nkr_num_slots;
728 
729 	/* update avail and reserved to what the kernel knows */
730 	kring->ring->avail = kring->nr_hwavail;
731 	kring->ring->reserved = kring->nr_hwreserved;
732 }
733 
734 /* check/fix address and len in tx rings */
735 #if 1 /* debug version */
736 #define	NM_CHECK_ADDR_LEN(_a, _l)	do {				\
737 	if (_a == netmap_buffer_base || _l > NETMAP_BUF_SIZE) {		\
738 		RD(5, "bad addr/len ring %d slot %d idx %d len %d",	\
739 			ring_nr, nm_i, slot->buf_idx, len);		\
740 		if (_l > NETMAP_BUF_SIZE)				\
741 			_l = NETMAP_BUF_SIZE;				\
742 	} } while (0)
743 #else /* no debug version */
744 #define	NM_CHECK_ADDR_LEN(_a, _l)	do {				\
745 		if (_l > NETMAP_BUF_SIZE)				\
746 			_l = NETMAP_BUF_SIZE;				\
747 	} while (0)
748 #endif
749 
750 
751 /*---------------------------------------------------------------*/
752 /*
753  * Support routines to be used with the VALE switch
754  */
755 int netmap_update_config(struct netmap_adapter *na);
756 int netmap_krings_create(struct netmap_adapter *na, u_int ntx, u_int nrx, u_int tailroom);
757 void netmap_krings_delete(struct netmap_adapter *na);
758 
759 struct netmap_if *
760 netmap_do_regif(struct netmap_priv_d *priv, struct netmap_adapter *na,
761 	uint16_t ringid, int *err);
762 
763 
764 
765 u_int nm_bound_var(u_int *v, u_int dflt, u_int lo, u_int hi, const char *msg);
766 int netmap_get_na(struct nmreq *nmr, struct netmap_adapter **na, int create);
767 int netmap_get_hw_na(struct ifnet *ifp, struct netmap_adapter **na);
768 
769 #ifdef WITH_VALE
770 /*
771  * The following bridge-related interfaces are used by other kernel modules
772  * In the version that only supports unicast or broadcast, the lookup
773  * function can return 0 .. NM_BDG_MAXPORTS-1 for regular ports,
774  * NM_BDG_MAXPORTS for broadcast, NM_BDG_MAXPORTS+1 for unknown.
775  * XXX in practice "unknown" might be handled same as broadcast.
776  */
777 typedef u_int (*bdg_lookup_fn_t)(char *buf, u_int len,
778 		uint8_t *ring_nr, struct netmap_vp_adapter *);
779 u_int netmap_bdg_learning(char *, u_int, uint8_t *,
780 		struct netmap_vp_adapter *);
781 
782 #define	NM_BDG_MAXPORTS		254	/* up to 254 */
783 #define	NM_BDG_BROADCAST	NM_BDG_MAXPORTS
784 #define	NM_BDG_NOPORT		(NM_BDG_MAXPORTS+1)
785 
786 #define	NM_NAME			"vale"	/* prefix for bridge port name */
787 
788 
789 /* these are redefined in case of no VALE support */
790 int netmap_get_bdg_na(struct nmreq *nmr, struct netmap_adapter **na, int create);
791 void netmap_init_bridges(void);
792 int netmap_bdg_ctl(struct nmreq *nmr, bdg_lookup_fn_t func);
793 
794 #else /* !WITH_VALE */
795 #define	netmap_get_bdg_na(_1, _2, _3)	0
796 #define netmap_init_bridges(_1)
797 #define	netmap_bdg_ctl(_1, _2)	EINVAL
798 #endif /* !WITH_VALE */
799 
800 /* Various prototypes */
801 int netmap_poll(struct cdev *dev, int events, struct thread *td);
802 
803 
804 int netmap_init(void);
805 void netmap_fini(void);
806 int netmap_get_memory(struct netmap_priv_d* p);
807 void netmap_dtor(void *data);
808 int netmap_dtor_locked(struct netmap_priv_d *priv);
809 
810 int netmap_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag, struct thread *td);
811 
812 /* netmap_adapter creation/destruction */
813 #define NM_IFPNAME(ifp) ((ifp) ? (ifp)->if_xname : "zombie")
814 #define NM_DEBUG_PUTGET 1
815 
816 #ifdef NM_DEBUG_PUTGET
817 
818 #define NM_DBG(f) __##f
819 
820 void __netmap_adapter_get(struct netmap_adapter *na);
821 
822 #define netmap_adapter_get(na) 				\
823 	do {						\
824 		struct netmap_adapter *__na = na;	\
825 		D("getting %p:%s (%d)", __na, NM_IFPNAME(__na->ifp), __na->na_refcount);	\
826 		__netmap_adapter_get(__na);		\
827 	} while (0)
828 
829 int __netmap_adapter_put(struct netmap_adapter *na);
830 
831 #define netmap_adapter_put(na)				\
832 	do {						\
833 		struct netmap_adapter *__na = na;	\
834 		D("putting %p:%s (%d)", __na, NM_IFPNAME(__na->ifp), __na->na_refcount);	\
835 		__netmap_adapter_put(__na);		\
836 	} while (0)
837 
838 #else /* !NM_DEBUG_PUTGET */
839 
840 #define NM_DBG(f) f
841 void netmap_adapter_get(struct netmap_adapter *na);
842 int netmap_adapter_put(struct netmap_adapter *na);
843 
844 #endif /* !NM_DEBUG_PUTGET */
845 
846 
847 extern u_int netmap_buf_size;
848 #define NETMAP_BUF_SIZE	netmap_buf_size	// XXX remove
849 extern int netmap_mitigate;
850 extern int netmap_no_pendintr;
851 extern u_int netmap_total_buffers;
852 extern char *netmap_buffer_base;
853 extern int netmap_verbose;	// XXX debugging
854 enum {                                  /* verbose flags */
855 	NM_VERB_ON = 1,                 /* generic verbose */
856 	NM_VERB_HOST = 0x2,             /* verbose host stack */
857 	NM_VERB_RXSYNC = 0x10,          /* verbose on rxsync/txsync */
858 	NM_VERB_TXSYNC = 0x20,
859 	NM_VERB_RXINTR = 0x100,         /* verbose on rx/tx intr (driver) */
860 	NM_VERB_TXINTR = 0x200,
861 	NM_VERB_NIC_RXSYNC = 0x1000,    /* verbose on rx/tx intr (driver) */
862 	NM_VERB_NIC_TXSYNC = 0x2000,
863 };
864 
865 extern int netmap_txsync_retry;
866 extern int netmap_generic_mit;
867 extern int netmap_generic_ringsize;
868 
869 /*
870  * NA returns a pointer to the struct netmap adapter from the ifp,
871  * WNA is used to write it.
872  */
873 #ifndef WNA
874 #define	WNA(_ifp)	(_ifp)->if_pspare[0]
875 #endif
876 #define	NA(_ifp)	((struct netmap_adapter *)WNA(_ifp))
877 
878 /*
879  * Macros to determine if an interface is netmap capable or netmap enabled.
880  * See the magic field in struct netmap_adapter.
881  */
882 #ifdef __FreeBSD__
883 /*
884  * on FreeBSD just use if_capabilities and if_capenable.
885  */
886 #define NETMAP_CAPABLE(ifp)	(NA(ifp) &&		\
887 	(ifp)->if_capabilities & IFCAP_NETMAP )
888 
889 #define	NETMAP_SET_CAPABLE(ifp)				\
890 	(ifp)->if_capabilities |= IFCAP_NETMAP
891 
892 #else	/* linux */
893 
894 /*
895  * on linux:
896  * we check if NA(ifp) is set and its first element has a related
897  * magic value. The capenable is within the struct netmap_adapter.
898  */
899 #define	NETMAP_MAGIC	0x52697a7a
900 
901 #define NETMAP_CAPABLE(ifp)	(NA(ifp) &&		\
902 	((uint32_t)(uintptr_t)NA(ifp) ^ NA(ifp)->magic) == NETMAP_MAGIC )
903 
904 #define	NETMAP_SET_CAPABLE(ifp)				\
905 	NA(ifp)->magic = ((uint32_t)(uintptr_t)NA(ifp)) ^ NETMAP_MAGIC
906 
907 #endif	/* linux */
908 
909 #ifdef __FreeBSD__
910 
911 /* Callback invoked by the dma machinery after a successfull dmamap_load */
912 static void netmap_dmamap_cb(__unused void *arg,
913     __unused bus_dma_segment_t * segs, __unused int nseg, __unused int error)
914 {
915 }
916 
917 /* bus_dmamap_load wrapper: call aforementioned function if map != NULL.
918  * XXX can we do it without a callback ?
919  */
920 static inline void
921 netmap_load_map(bus_dma_tag_t tag, bus_dmamap_t map, void *buf)
922 {
923 	if (map)
924 		bus_dmamap_load(tag, map, buf, NETMAP_BUF_SIZE,
925 		    netmap_dmamap_cb, NULL, BUS_DMA_NOWAIT);
926 }
927 
928 /* update the map when a buffer changes. */
929 static inline void
930 netmap_reload_map(bus_dma_tag_t tag, bus_dmamap_t map, void *buf)
931 {
932 	if (map) {
933 		bus_dmamap_unload(tag, map);
934 		bus_dmamap_load(tag, map, buf, NETMAP_BUF_SIZE,
935 		    netmap_dmamap_cb, NULL, BUS_DMA_NOWAIT);
936 	}
937 }
938 
939 #else /* linux */
940 
941 /*
942  * XXX How do we redefine these functions:
943  *
944  * on linux we need
945  *	dma_map_single(&pdev->dev, virt_addr, len, direction)
946  *	dma_unmap_single(&adapter->pdev->dev, phys_addr, len, direction
947  * The len can be implicit (on netmap it is NETMAP_BUF_SIZE)
948  * unfortunately the direction is not, so we need to change
949  * something to have a cross API
950  */
951 #define netmap_load_map(_t, _m, _b)
952 #define netmap_reload_map(_t, _m, _b)
953 #if 0
954 	struct e1000_buffer *buffer_info =  &tx_ring->buffer_info[l];
955 	/* set time_stamp *before* dma to help avoid a possible race */
956 	buffer_info->time_stamp = jiffies;
957 	buffer_info->mapped_as_page = false;
958 	buffer_info->length = len;
959 	//buffer_info->next_to_watch = l;
960 	/* reload dma map */
961 	dma_unmap_single(&adapter->pdev->dev, buffer_info->dma,
962 			NETMAP_BUF_SIZE, DMA_TO_DEVICE);
963 	buffer_info->dma = dma_map_single(&adapter->pdev->dev,
964 			addr, NETMAP_BUF_SIZE, DMA_TO_DEVICE);
965 
966 	if (dma_mapping_error(&adapter->pdev->dev, buffer_info->dma)) {
967 		D("dma mapping error");
968 		/* goto dma_error; See e1000_put_txbuf() */
969 		/* XXX reset */
970 	}
971 	tx_desc->buffer_addr = htole64(buffer_info->dma); //XXX
972 
973 #endif
974 
975 /*
976  * The bus_dmamap_sync() can be one of wmb() or rmb() depending on direction.
977  */
978 #define bus_dmamap_sync(_a, _b, _c)
979 
980 #endif /* linux */
981 
982 
983 /*
984  * functions to map NIC to KRING indexes (n2k) and vice versa (k2n)
985  */
986 static inline int
987 netmap_idx_n2k(struct netmap_kring *kr, int idx)
988 {
989 	int n = kr->nkr_num_slots;
990 	idx += kr->nkr_hwofs;
991 	if (idx < 0)
992 		return idx + n;
993 	else if (idx < n)
994 		return idx;
995 	else
996 		return idx - n;
997 }
998 
999 
1000 static inline int
1001 netmap_idx_k2n(struct netmap_kring *kr, int idx)
1002 {
1003 	int n = kr->nkr_num_slots;
1004 	idx -= kr->nkr_hwofs;
1005 	if (idx < 0)
1006 		return idx + n;
1007 	else if (idx < n)
1008 		return idx;
1009 	else
1010 		return idx - n;
1011 }
1012 
1013 
1014 /* Entries of the look-up table. */
1015 struct lut_entry {
1016 	void *vaddr;		/* virtual address. */
1017 	vm_paddr_t paddr;	/* physical address. */
1018 };
1019 
1020 struct netmap_obj_pool;
1021 extern struct lut_entry *netmap_buffer_lut;
1022 #define NMB_VA(i)	(netmap_buffer_lut[i].vaddr)
1023 #define NMB_PA(i)	(netmap_buffer_lut[i].paddr)
1024 
1025 /*
1026  * NMB return the virtual address of a buffer (buffer 0 on bad index)
1027  * PNMB also fills the physical address
1028  */
1029 static inline void *
1030 NMB(struct netmap_slot *slot)
1031 {
1032 	uint32_t i = slot->buf_idx;
1033 	return (unlikely(i >= netmap_total_buffers)) ?  NMB_VA(0) : NMB_VA(i);
1034 }
1035 
1036 static inline void *
1037 PNMB(struct netmap_slot *slot, uint64_t *pp)
1038 {
1039 	uint32_t i = slot->buf_idx;
1040 	void *ret = (i >= netmap_total_buffers) ? NMB_VA(0) : NMB_VA(i);
1041 
1042 	*pp = (i >= netmap_total_buffers) ? NMB_PA(0) : NMB_PA(i);
1043 	return ret;
1044 }
1045 
1046 /* Generic version of NMB, which uses device-specific memory. */
1047 static inline void *
1048 BDG_NMB(struct netmap_adapter *na, struct netmap_slot *slot)
1049 {
1050 	struct lut_entry *lut = na->na_lut;
1051 	uint32_t i = slot->buf_idx;
1052 	return (unlikely(i >= na->na_lut_objtotal)) ?
1053 		lut[0].vaddr : lut[i].vaddr;
1054 }
1055 
1056 /* default functions to handle rx/tx interrupts */
1057 int netmap_rx_irq(struct ifnet *, u_int, u_int *);
1058 #define netmap_tx_irq(_n, _q) netmap_rx_irq(_n, _q, NULL)
1059 void netmap_common_irq(struct ifnet *, u_int, u_int *work_done);
1060 
1061 
1062 void netmap_txsync_to_host(struct netmap_adapter *na);
1063 void netmap_disable_all_rings(struct ifnet *);
1064 void netmap_enable_all_rings(struct ifnet *);
1065 void netmap_disable_ring(struct netmap_kring *kr);
1066 
1067 
1068 /* Structure associated to each thread which registered an interface.
1069  *
1070  * The first 4 fields of this structure are written by NIOCREGIF and
1071  * read by poll() and NIOC?XSYNC.
1072  * There is low contention among writers (actually, a correct user program
1073  * should have no contention among writers) and among writers and readers,
1074  * so we use a single global lock to protect the structure initialization.
1075  * Since initialization involves the allocation of memory, we reuse the memory
1076  * allocator lock.
1077  * Read access to the structure is lock free. Readers must check that
1078  * np_nifp is not NULL before using the other fields.
1079  * If np_nifp is NULL initialization has not been performed, so they should
1080  * return an error to userlevel.
1081  *
1082  * The ref_done field is used to regulate access to the refcount in the
1083  * memory allocator. The refcount must be incremented at most once for
1084  * each open("/dev/netmap"). The increment is performed by the first
1085  * function that calls netmap_get_memory() (currently called by
1086  * mmap(), NIOCGINFO and NIOCREGIF).
1087  * If the refcount is incremented, it is then decremented when the
1088  * private structure is destroyed.
1089  */
1090 struct netmap_priv_d {
1091 	struct netmap_if * volatile np_nifp;	/* netmap if descriptor. */
1092 
1093 	struct netmap_adapter	*np_na;
1094 	int		        np_ringid;	/* from the ioctl */
1095 	u_int		        np_qfirst, np_qlast;	/* range of rings to scan */
1096 	uint16_t	        np_txpoll;
1097 
1098 	struct netmap_mem_d     *np_mref;	/* use with NMG_LOCK held */
1099 	/* np_refcount is only used on FreeBSD */
1100 	int		        np_refcount;	/* use with NMG_LOCK held */
1101 };
1102 
1103 
1104 /*
1105  * generic netmap emulation for devices that do not have
1106  * native netmap support.
1107  * XXX generic_netmap_register() is only exported to implement
1108  *	nma_is_generic().
1109  */
1110 int generic_netmap_register(struct netmap_adapter *na, int enable);
1111 int generic_netmap_attach(struct ifnet *ifp);
1112 
1113 int netmap_catch_rx(struct netmap_adapter *na, int intercept);
1114 void generic_rx_handler(struct ifnet *ifp, struct mbuf *m);;
1115 void netmap_catch_packet_steering(struct netmap_generic_adapter *na, int enable);
1116 int generic_xmit_frame(struct ifnet *ifp, struct mbuf *m, void *addr, u_int len, u_int ring_nr);
1117 int generic_find_num_desc(struct ifnet *ifp, u_int *tx, u_int *rx);
1118 void generic_find_num_queues(struct ifnet *ifp, u_int *txq, u_int *rxq);
1119 
1120 static __inline int
1121 nma_is_generic(struct netmap_adapter *na)
1122 {
1123 	return na->nm_register == generic_netmap_register;
1124 }
1125 
1126 /*
1127  * netmap_mitigation API. This is used by the generic adapter
1128  * to reduce the number of interrupt requests/selwakeup
1129  * to clients on incoming packets.
1130  */
1131 void netmap_mitigation_init(struct netmap_generic_adapter *na);
1132 void netmap_mitigation_start(struct netmap_generic_adapter *na);
1133 void netmap_mitigation_restart(struct netmap_generic_adapter *na);
1134 int netmap_mitigation_active(struct netmap_generic_adapter *na);
1135 void netmap_mitigation_cleanup(struct netmap_generic_adapter *na);
1136 
1137 // int generic_timer_handler(struct hrtimer *t);
1138 
1139 #endif /* _NET_NETMAP_KERN_H_ */
1140