2 * Copyright (C) 2011-2014 Matteo Landi, Luigi Rizzo. All rights reserved.
3 * Copyright (C) 2013-2014 Universita` di Pisa. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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.
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
30 * The header contains the definitions of constants and function
31 * prototypes used only in kernelspace.
34 #ifndef _NET_NETMAP_KERN_H_
35 #define _NET_NETMAP_KERN_H_
37 #define WITH_VALE // comment out to disable VALE support
40 #if defined(__FreeBSD__)
42 #define likely(x) __builtin_expect((long)!!(x), 1L)
43 #define unlikely(x) __builtin_expect((long)!!(x), 0L)
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)
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)
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)
66 MALLOC_DECLARE(M_NETMAP);
68 // XXX linux struct, not used in FreeBSD
69 struct net_device_ops {
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) \
82 m->priority = NM_MAGIC_PRIORITY; \
86 #define NM_ATOMIC_T volatile long unsigned int
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
98 #endif /* DEV_NETMAP */
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
106 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,37)
107 #define IFCAP_NETMAP 0x8000
109 #define IFCAP_NETMAP 0x200000
112 #elif defined (__APPLE__)
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)
124 #error unsupported platform
126 #endif /* end - platform-specific code */
128 #define ND(format, ...)
129 #define D(format, ...) \
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__); \
138 /* rate limited, lps indicates how many per second */
139 #define RD(lps, format, ...) \
141 static int t0, __cnt; \
142 if (t0 != time_second) { \
147 D(format, ##__VA_ARGS__); \
150 struct netmap_adapter;
153 struct netmap_priv_d;
155 const char *nm_dump_buf(char *p, int len, int lim, char *dst);
157 #include "netmap_mbq.h"
159 extern NMG_LOCK_T netmap_global_lock;
162 * private, kernel view of a ring. Keeps track of the status of
163 * a ring across system calls.
165 * nr_hwcur index of the next buffer to refill.
166 * It corresponds to ring->head
167 * at the time the system call returns.
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.
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
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).
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
208 * The kring is manipulated by txsync/rxsync and generic netmap function.
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.
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.
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.
221 struct netmap_kring {
222 struct netmap_ring *ring;
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.
236 uint32_t nr_kflags; /* private driver flags */
237 #define NKR_PENDINTR 0x1 // Pending interrupt.
238 uint32_t nkr_num_slots;
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.
247 uint16_t nkr_slot_flags; /* initial value for flags */
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.
253 uint64_t last_reclaim;
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 */
260 struct netmap_adapter *na;
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;
269 volatile int nkr_stopped; // XXX what for ?
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
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. */
281 uint32_t ring_id; /* debugging */
282 char name[64]; /* diagnostic */
284 int (*nm_sync)(struct netmap_kring *kring, int flags);
287 struct netmap_kring *pipe;
288 struct netmap_ring *save_ring;
289 #endif /* WITH_PIPES */
291 } __attribute__((__aligned__(64)));
294 /* return the next index, with wraparound */
295 static inline uint32_t
296 nm_next(uint32_t i, uint32_t lim)
298 return unlikely (i == lim) ? 0 : i + 1;
302 /* return the previous index, with wraparound */
303 static inline uint32_t
304 nm_prev(uint32_t i, uint32_t lim)
306 return unlikely (i == 0) ? lim : i - 1;
312 * Here is the layout for the Rx and Tx rings.
316 +-----------------+ +-----------------+
318 |XXX free slot XXX| |XXX free slot XXX|
319 +-----------------+ +-----------------+
320 head->| owned by user |<-hwcur | not sent to nic |<-hwcur
322 +-----------------+ | |
323 cur->| available to | | |
324 | user, not read | +-----------------+
325 | yet | cur->| (being |
328 +-----------------+ + ------ +
329 tail->| |<-hwtail | |<-hwlease
330 | (being | ... | | ...
331 | prepared) | ... | | ...
332 +-----------------+ ... | | ...
333 | |<-hwlease +-----------------+
334 | | tail->| |<-hwtail
338 +-----------------+ +-----------------+
340 * The cur/tail (user view) and hwcur/hwtail (kernel view)
341 * are used in the normal operation of the card.
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.
352 * nm_kr_space() returns the maximum number of slots that
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.
361 enum txrx { NR_RX = 0, NR_TX = 1 };
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.
371 struct netmap_adapter {
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.
380 uint32_t na_flags; /* enabled, and other flags */
381 #define NAF_SKIP_INTR 1 /* use the regular interrupt handler.
382 * useful during initialization
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
389 #define NAF_MEM_OWNER 8 /* the adapter is responsible for the
390 * deallocation of the memory allocator
392 #define NAF_NATIVE_ON 16 /* the adapter is native and the attached
393 * interface is in netmap mode
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.
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. */
404 u_int num_rx_rings; /* number of adapter receive rings */
405 u_int num_tx_rings; /* number of adapter transmit rings */
407 u_int num_tx_desc; /* number of descriptor in each queue */
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.
414 struct netmap_kring *tx_rings; /* array of TX rings. */
415 struct netmap_kring *rx_rings; /* array of RX rings. */
417 void *tailroom; /* space below the rings array */
418 /* (used for leases) */
421 NM_SELINFO_T tx_si, rx_si; /* global wait queues */
423 /* count users of the global wait queues */
424 int tx_si_users, rx_si_users;
426 /* copy of if_qflush and if_transmit pointers, to intercept
427 * packets from the network stack when netmap is active.
429 int (*if_transmit)(struct ifnet *, struct mbuf *);
431 /* copy of if_input for netmap_send_up() */
432 void (*if_input)(struct ifnet *, struct mbuf *);
434 /* references to the ifnet and device routines, used by
435 * the generic netmap functions.
437 struct ifnet *ifp; /* adapter is ifp->if_softc */
439 /*---- callbacks for this netmap adapter -----*/
441 * nm_dtor() is the cleanup routine called when destroying
444 * nm_register() is called on NIOCREGIF and close() to enter
445 * or exit netmap mode on the NIC
447 * nm_txsync() pushes packets to the underlying hw/switch
449 * nm_rxsync() collects packets from the underlying hw/switch
451 * nm_config() returns configuration information from the OS
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)
457 * nm_krings_delete() cleanup and delete the kring array
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.
465 /* private cleanup */
466 void (*nm_dtor)(struct netmap_adapter *);
468 int (*nm_register)(struct netmap_adapter *, int onoff);
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
483 /* standard refcount to control the lifetime of the adapter
484 * (it should be equal to the lifetime of the corresponding ifp)
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.
492 struct netmap_mem_d *nm_mem;
493 struct lut_entry *na_lut;
494 uint32_t na_lut_objtotal; /* max buffer index */
496 /* used internally. If non-null, the interface cannot be bound
502 struct netmap_pipe_adapter **na_pipes;
505 #endif /* WITH_PIPES */
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().
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))
521 * derived netmap adapters for various types of ports
523 struct netmap_vp_adapter { /* VALE software port */
524 struct netmap_adapter up;
529 * bdg_port is the port number used in the bridge;
530 * na_bdg points to the bridge this NA is attached to.
533 struct nm_bridge *na_bdg;
536 /* Offset of ethernet header for each packet. */
538 /* Maximum Frame Size, used in bdg_mismatch_datapath() */
543 struct netmap_hw_adapter { /* physical device */
544 struct netmap_adapter up;
546 struct net_device_ops nm_ndo; // XXX linux only
549 /* Mitigation support. */
550 struct nm_generic_mit {
551 struct hrtimer mit_timer;
553 struct netmap_adapter *mit_na; /* backpointer */
556 struct netmap_generic_adapter { /* emulated device */
557 struct netmap_hw_adapter up;
559 /* Pointer to a previously used netmap adapter. */
560 struct netmap_adapter *prev;
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,
567 struct net_device_ops generic_ndo;
568 void (*save_if_input)(struct ifnet *, struct mbuf *);
570 struct nm_generic_mit *mit;
572 netdev_tx_t (*save_start_xmit)(struct mbuf *, struct ifnet *);
577 netmap_real_tx_rings(struct netmap_adapter *na)
579 return na->num_tx_rings + !!(na->na_flags & NAF_HOST_RINGS);
583 netmap_real_rx_rings(struct netmap_adapter *na)
585 return na->num_rx_rings + !!(na->na_flags & NAF_HOST_RINGS);
591 * Bridge wrapper for non VALE ports attached to a VALE switch.
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:
599 * bwrap krings rings krings hwna
600 * +------+ +------+ +-----+ +------+ +------+
601 * |tx_rings->| |\ /| |----| |<-tx_rings|
602 * | | +------+ \ / +-----+ +------+ | |
605 * | | +------+/ \+-----+ +------+ | |
606 * |rx_rings->| | | |----| |<-rx_rings|
607 * | | +------+ +-----+ +------+ | |
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).
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).
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.
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)
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.
634 struct 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 */
639 /* backup of the hwna notify callback */
640 int (*save_notify)(struct netmap_adapter *,
641 u_int ring, enum txrx, int flags);
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.
650 struct netmap_priv_d *na_kpriv;
654 #endif /* WITH_VALE */
658 #define NM_MAXPIPES 64 /* max number of pipes per adapter */
660 struct netmap_pipe_adapter {
661 struct netmap_adapter up;
663 u_int id; /* pipe identifier */
664 int role; /* either NR_REG_PIPE_MASTER or NR_REG_PIPE_SLAVE */
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 */
670 u_int parent_slot; /* index in the parent pipe array */
673 #endif /* WITH_PIPES */
676 /* return slots reserved to rx clients; used in drivers */
677 static inline uint32_t
678 nm_kr_rxspace(struct netmap_kring *k)
680 int space = k->nr_hwtail - k->nr_hwcur;
682 space += k->nkr_num_slots;
683 ND("preserving %d rx slots %d -> %d", space, k->nr_hwcur, k->nr_hwtail);
689 /* True if no space in the tx ring. only valid after txsync_prologue */
691 nm_kr_txempty(struct netmap_kring *kring)
693 return kring->rcur == kring->nr_hwtail;
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.
703 #define NM_KR_STOPPED 2
706 static __inline void nm_kr_put(struct netmap_kring *kr)
708 NM_ATOMIC_CLEAR(&kr->nr_busy);
712 static __inline int nm_kr_tryget(struct netmap_kring *kr)
714 /* check a first time without taking the lock
715 * to avoid starvation for nm_kr_get()
717 if (unlikely(kr->nkr_stopped)) {
718 ND("ring %p stopped (%d)", kr, kr->nkr_stopped);
719 return NM_KR_STOPPED;
721 if (unlikely(NM_ATOMIC_TEST_AND_SET(&kr->nr_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);
727 return NM_KR_STOPPED;
734 * The following functions are used by individual drivers to
735 * support netmap operation.
737 * netmap_attach() initializes a struct netmap_adapter, allocating the
738 * struct netmap_ring's and the struct selinfo.
740 * netmap_detach() frees the memory allocated by netmap_attach().
742 * netmap_transmit() replaces the if_transmit routine of the interface,
743 * and is used to intercept packets coming from the stack.
745 * netmap_load_map/netmap_reload_map are helper routines to set/reset
746 * the dmamap for a packet buffer
748 * netmap_reset() is a helper routine to be called in the driver
749 * when reinitializing a ring.
751 int netmap_attach(struct netmap_adapter *);
752 int netmap_attach_common(struct netmap_adapter *);
753 void netmap_detach_common(struct netmap_adapter *na);
754 void netmap_detach(struct ifnet *);
755 int netmap_transmit(struct ifnet *, struct mbuf *);
756 struct netmap_slot *netmap_reset(struct netmap_adapter *na,
757 enum txrx tx, u_int n, u_int new_cur);
758 int netmap_ring_reinit(struct netmap_kring *);
760 /* default functions to handle rx/tx interrupts */
761 int netmap_rx_irq(struct ifnet *, u_int, u_int *);
762 #define netmap_tx_irq(_n, _q) netmap_rx_irq(_n, _q, NULL)
763 void netmap_common_irq(struct ifnet *, u_int, u_int *work_done);
765 void netmap_disable_all_rings(struct ifnet *);
766 void netmap_enable_all_rings(struct ifnet *);
767 void netmap_disable_ring(struct netmap_kring *kr);
770 /* set/clear native flags and if_transmit/netdev_ops */
772 nm_set_native_flags(struct netmap_adapter *na)
774 struct ifnet *ifp = na->ifp;
776 na->na_flags |= (NAF_NATIVE_ON | NAF_NETMAP_ON);
777 #ifdef IFCAP_NETMAP /* or FreeBSD ? */
778 ifp->if_capenable |= IFCAP_NETMAP;
781 na->if_transmit = ifp->if_transmit;
782 ifp->if_transmit = netmap_transmit;
784 na->if_transmit = (void *)ifp->netdev_ops;
785 ifp->netdev_ops = &((struct netmap_hw_adapter *)na)->nm_ndo;
791 nm_clear_native_flags(struct netmap_adapter *na)
793 struct ifnet *ifp = na->ifp;
796 ifp->if_transmit = na->if_transmit;
798 ifp->netdev_ops = (void *)na->if_transmit;
800 na->na_flags &= ~(NAF_NATIVE_ON | NAF_NETMAP_ON);
801 #ifdef IFCAP_NETMAP /* or FreeBSD ? */
802 ifp->if_capenable &= ~IFCAP_NETMAP;
808 * validates parameters in the ring/kring, returns a value for head
809 * If any error, returns ring_size to force a reinit.
811 uint32_t nm_txsync_prologue(struct netmap_kring *);
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.
819 uint32_t nm_rxsync_prologue(struct netmap_kring *);
823 * update kring and ring at the end of txsync.
826 nm_txsync_finalize(struct netmap_kring *kring)
828 /* update ring tail to what the kernel knows */
829 kring->ring->tail = kring->rtail = kring->nr_hwtail;
831 /* note, head/rhead/hwcur might be behind cur/rcur
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);
841 * update kring and ring at the end of rxsync
844 nm_rxsync_finalize(struct netmap_kring *kring)
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,
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;
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; \
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; \
874 /*---------------------------------------------------------------*/
876 * Support routines to be used with the VALE switch
878 int netmap_update_config(struct netmap_adapter *na);
879 int netmap_krings_create(struct netmap_adapter *na, u_int tailroom);
880 void netmap_krings_delete(struct netmap_adapter *na);
881 int netmap_rxsync_from_host(struct netmap_adapter *na, struct thread *td, void *pwait);
885 netmap_do_regif(struct netmap_priv_d *priv, struct netmap_adapter *na,
886 uint16_t ringid, uint32_t flags, int *err);
890 u_int nm_bound_var(u_int *v, u_int dflt, u_int lo, u_int hi, const char *msg);
891 int netmap_get_na(struct nmreq *nmr, struct netmap_adapter **na, int create);
892 int netmap_get_hw_na(struct ifnet *ifp, struct netmap_adapter **na);
897 * The following bridge-related functions are used by other
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.
905 typedef u_int (*bdg_lookup_fn_t)(char *buf, u_int len,
906 uint8_t *ring_nr, struct netmap_vp_adapter *);
907 u_int netmap_bdg_learning(char *, u_int, uint8_t *,
908 struct netmap_vp_adapter *);
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)
914 #define NM_NAME "vale" /* prefix for bridge port name */
917 /* these are redefined in case of no VALE support */
918 int netmap_get_bdg_na(struct nmreq *nmr, struct netmap_adapter **na, int create);
919 void netmap_init_bridges(void);
920 int netmap_bdg_ctl(struct nmreq *nmr, bdg_lookup_fn_t func);
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 */
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 */
932 int netmap_pipe_alloc(struct netmap_adapter *, struct nmreq *nmr);
933 void netmap_pipe_dealloc(struct netmap_adapter *);
934 int 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
942 /* Various prototypes */
943 int netmap_poll(struct cdev *dev, int events, struct thread *td);
944 int netmap_init(void);
945 void netmap_fini(void);
946 int netmap_get_memory(struct netmap_priv_d* p);
947 void netmap_dtor(void *data);
948 int netmap_dtor_locked(struct netmap_priv_d *priv);
950 int netmap_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag, struct thread *td);
952 /* netmap_adapter creation/destruction */
953 #define NM_IFPNAME(ifp) ((ifp) ? (ifp)->if_xname : "zombie")
955 // #define NM_DEBUG_PUTGET 1
957 #ifdef NM_DEBUG_PUTGET
959 #define NM_DBG(f) __##f
961 void __netmap_adapter_get(struct netmap_adapter *na);
963 #define netmap_adapter_get(na) \
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); \
970 int __netmap_adapter_put(struct netmap_adapter *na);
972 #define netmap_adapter_put(na) \
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); \
979 #else /* !NM_DEBUG_PUTGET */
982 void netmap_adapter_get(struct netmap_adapter *na);
983 int netmap_adapter_put(struct netmap_adapter *na);
985 #endif /* !NM_DEBUG_PUTGET */
991 extern u_int netmap_buf_size;
992 #define NETMAP_BUF_SIZE netmap_buf_size // XXX remove
993 extern int netmap_mitigate; // XXX not really used
994 extern int netmap_no_pendintr;
995 extern u_int netmap_total_buffers; // global allocator
996 extern char *netmap_buffer_base; // global allocator
997 extern int netmap_verbose; // XXX debugging
998 enum { /* 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,
1009 extern int netmap_txsync_retry;
1010 extern int netmap_generic_mit;
1011 extern int netmap_generic_ringsize;
1012 extern int netmap_generic_rings;
1015 * NA returns a pointer to the struct netmap adapter from the ifp,
1016 * WNA is used to write it.
1019 #define WNA(_ifp) (_ifp)->if_pspare[0]
1021 #define NA(_ifp) ((struct netmap_adapter *)WNA(_ifp))
1024 * Macros to determine if an interface is netmap capable or netmap enabled.
1025 * See the magic field in struct netmap_adapter.
1029 * on FreeBSD just use if_capabilities and if_capenable.
1031 #define NETMAP_CAPABLE(ifp) (NA(ifp) && \
1032 (ifp)->if_capabilities & IFCAP_NETMAP )
1034 #define NETMAP_SET_CAPABLE(ifp) \
1035 (ifp)->if_capabilities |= IFCAP_NETMAP
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.
1044 #define NETMAP_MAGIC 0x52697a7a
1046 #define NETMAP_CAPABLE(ifp) (NA(ifp) && \
1047 ((uint32_t)(uintptr_t)NA(ifp) ^ NA(ifp)->magic) == NETMAP_MAGIC )
1049 #define NETMAP_SET_CAPABLE(ifp) \
1050 NA(ifp)->magic = ((uint32_t)(uintptr_t)NA(ifp)) ^ NETMAP_MAGIC
1056 /* Callback invoked by the dma machinery after a successful dmamap_load */
1057 static void netmap_dmamap_cb(__unused void *arg,
1058 __unused bus_dma_segment_t * segs, __unused int nseg, __unused int error)
1062 /* bus_dmamap_load wrapper: call aforementioned function if map != NULL.
1063 * XXX can we do it without a callback ?
1066 netmap_load_map(bus_dma_tag_t tag, bus_dmamap_t map, void *buf)
1069 bus_dmamap_load(tag, map, buf, NETMAP_BUF_SIZE,
1070 netmap_dmamap_cb, NULL, BUS_DMA_NOWAIT);
1073 /* update the map when a buffer changes. */
1075 netmap_reload_map(bus_dma_tag_t tag, bus_dmamap_t map, void *buf)
1078 bus_dmamap_unload(tag, map);
1079 bus_dmamap_load(tag, map, buf, NETMAP_BUF_SIZE,
1080 netmap_dmamap_cb, NULL, BUS_DMA_NOWAIT);
1087 * XXX How do we redefine these functions:
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
1096 #define netmap_load_map(_t, _m, _b)
1097 #define netmap_reload_map(_t, _m, _b)
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);
1111 if (dma_mapping_error(&adapter->pdev->dev, buffer_info->dma)) {
1112 D("dma mapping error");
1113 /* goto dma_error; See e1000_put_txbuf() */
1116 tx_desc->buffer_addr = htole64(buffer_info->dma); //XXX
1121 * The bus_dmamap_sync() can be one of wmb() or rmb() depending on direction.
1123 #define bus_dmamap_sync(_a, _b, _c)
1129 * functions to map NIC to KRING indexes (n2k) and vice versa (k2n)
1132 netmap_idx_n2k(struct netmap_kring *kr, int idx)
1134 int n = kr->nkr_num_slots;
1135 idx += kr->nkr_hwofs;
1146 netmap_idx_k2n(struct netmap_kring *kr, int idx)
1148 int n = kr->nkr_num_slots;
1149 idx -= kr->nkr_hwofs;
1159 /* Entries of the look-up table. */
1161 void *vaddr; /* virtual address. */
1162 vm_paddr_t paddr; /* physical address. */
1165 struct netmap_obj_pool;
1166 extern 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)
1171 * NMB return the virtual address of a buffer (buffer 0 on bad index)
1172 * PNMB also fills the physical address
1174 static inline void *
1175 NMB(struct netmap_slot *slot)
1177 uint32_t i = slot->buf_idx;
1178 return (unlikely(i >= netmap_total_buffers)) ? NMB_VA(0) : NMB_VA(i);
1181 static inline void *
1182 PNMB(struct netmap_slot *slot, uint64_t *pp)
1184 uint32_t i = slot->buf_idx;
1185 void *ret = (i >= netmap_total_buffers) ? NMB_VA(0) : NMB_VA(i);
1187 *pp = (i >= netmap_total_buffers) ? NMB_PA(0) : NMB_PA(i);
1191 /* Generic version of NMB, which uses device-specific memory. */
1192 static inline void *
1193 BDG_NMB(struct netmap_adapter *na, struct netmap_slot *slot)
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;
1203 void netmap_txsync_to_host(struct netmap_adapter *na);
1207 * Structure associated to each thread which registered an interface.
1209 * The first 4 fields of this structure are written by NIOCREGIF and
1210 * read by poll() and NIOC?XSYNC.
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.
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.
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.
1231 struct netmap_priv_d {
1232 struct netmap_if * volatile np_nifp; /* netmap if descriptor. */
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 ? */
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 */
1244 /* pointers to the selinfo to be used for selrecord.
1245 * Either the local or the global one depending on the
1248 NM_SELINFO_T *np_rxsi, *np_txsi;
1249 struct thread *np_td; /* kqueue, just debugging */
1254 * generic netmap emulation for devices that do not have
1255 * native netmap support.
1257 int generic_netmap_attach(struct ifnet *ifp);
1259 int netmap_catch_rx(struct netmap_adapter *na, int intercept);
1260 void generic_rx_handler(struct ifnet *ifp, struct mbuf *m);;
1261 void netmap_catch_tx(struct netmap_generic_adapter *na, int enable);
1262 int generic_xmit_frame(struct ifnet *ifp, struct mbuf *m, void *addr, u_int len, u_int ring_nr);
1263 int generic_find_num_desc(struct ifnet *ifp, u_int *tx, u_int *rx);
1264 void generic_find_num_queues(struct ifnet *ifp, u_int *txq, u_int *rxq);
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.
1271 void netmap_mitigation_init(struct nm_generic_mit *mit, struct netmap_adapter *na);
1272 void netmap_mitigation_start(struct nm_generic_mit *mit);
1273 void netmap_mitigation_restart(struct nm_generic_mit *mit);
1274 int netmap_mitigation_active(struct nm_generic_mit *mit);
1275 void netmap_mitigation_cleanup(struct nm_generic_mit *mit);
1279 /* Shared declarations for the VALE switch. */
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.
1287 struct 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 */
1296 /* struct 'virtio_net_hdr' from linux. */
1297 struct 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 */
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 */
1309 uint16_t csum_start;
1310 uint16_t csum_offset;
1313 #define WORST_CASE_GSO_HEADER (14+40+60) /* IPv6 + TCP */
1315 /* Private definitions for IPv4, IPv6, UDP and TCP headers. */
1318 uint8_t version_ihl;
1328 /*The options start here. */
1336 uint8_t doff; /* Data offset + Reserved */
1351 uint8_t priority_version;
1352 uint8_t flow_lbl[3];
1354 uint16_t payload_len;
1362 /* Type used to store a checksum (in host byte order) that hasn't been
1365 #define rawsum_t uint32_t
1367 rawsum_t nm_csum_raw(uint8_t *data, size_t len, rawsum_t cur_sum);
1368 uint16_t nm_csum_ipv4(struct nm_iphdr *iph);
1369 void nm_csum_tcpudp_ipv4(struct nm_iphdr *iph, void *data,
1370 size_t datalen, uint16_t *check);
1371 void nm_csum_tcpudp_ipv6(struct nm_ipv6hdr *ip6h, void *data,
1372 size_t datalen, uint16_t *check);
1373 uint16_t nm_csum_fold(rawsum_t cur_sum);
1375 void 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);
1380 #endif /* _NET_NETMAP_KERN_H_ */