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