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)
65 #if __FreeBSD_version >= 1100005
66 struct netmap_adapter *netmap_getna(if_t ifp);
69 MALLOC_DECLARE(M_NETMAP);
71 // XXX linux struct, not used in FreeBSD
72 struct net_device_ops {
79 #define NM_LOCK_T safe_spinlock_t // see bsd_glue.h
80 #define NM_SELINFO_T wait_queue_head_t
81 #define MBUF_LEN(m) ((m)->len)
82 #define MBUF_IFP(m) ((m)->dev)
83 #define NM_SEND_UP(ifp, m) \
85 m->priority = NM_MAGIC_PRIORITY; \
89 #define NM_ATOMIC_T volatile long unsigned int
91 // XXX a mtx would suffice here too 20130404 gl
92 #define NMG_LOCK_T struct semaphore
93 #define NMG_LOCK_INIT() sema_init(&netmap_global_lock, 1)
94 #define NMG_LOCK_DESTROY()
95 #define NMG_LOCK() down(&netmap_global_lock)
96 #define NMG_UNLOCK() up(&netmap_global_lock)
97 #define NMG_LOCK_ASSERT() // XXX to be completed
101 #endif /* DEV_NETMAP */
104 * IFCAP_NETMAP goes into net_device's priv_flags (if_capenable).
105 * This was 16 bits up to linux 2.6.36, so we need a 16 bit value on older
106 * platforms and tolerate the clash with IFF_DYNAMIC and IFF_BRIDGE_PORT.
107 * For the 32-bit value, 0x100000 has no clashes until at least 3.5.1
109 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,37)
110 #define IFCAP_NETMAP 0x8000
112 #define IFCAP_NETMAP 0x200000
115 #elif defined (__APPLE__)
117 #warning apple support is incomplete.
118 #define likely(x) __builtin_expect(!!(x), 1)
119 #define unlikely(x) __builtin_expect(!!(x), 0)
120 #define NM_LOCK_T IOLock *
121 #define NM_SELINFO_T struct selinfo
122 #define MBUF_LEN(m) ((m)->m_pkthdr.len)
123 #define NM_SEND_UP(ifp, m) ((ifp)->if_input)(ifp, m)
127 #error unsupported platform
129 #endif /* end - platform-specific code */
131 #define ND(format, ...)
132 #define D(format, ...) \
134 struct timeval __xxts; \
135 microtime(&__xxts); \
136 printf("%03d.%06d [%4d] %-25s " format "\n", \
137 (int)__xxts.tv_sec % 1000, (int)__xxts.tv_usec, \
138 __LINE__, __FUNCTION__, ##__VA_ARGS__); \
141 /* rate limited, lps indicates how many per second */
142 #define RD(lps, format, ...) \
144 static int t0, __cnt; \
145 if (t0 != time_second) { \
150 D(format, ##__VA_ARGS__); \
153 struct netmap_adapter;
156 struct netmap_priv_d;
158 const char *nm_dump_buf(char *p, int len, int lim, char *dst);
160 #include "netmap_mbq.h"
162 extern NMG_LOCK_T netmap_global_lock;
165 * private, kernel view of a ring. Keeps track of the status of
166 * a ring across system calls.
168 * nr_hwcur index of the next buffer to refill.
169 * It corresponds to ring->head
170 * at the time the system call returns.
172 * nr_hwtail index of the first buffer owned by the kernel.
173 * On RX, hwcur->hwtail are receive buffers
174 * not yet released. hwcur is advanced following
175 * ring->head, hwtail is advanced on incoming packets,
176 * and a wakeup is generated when hwtail passes ring->cur
177 * On TX, hwcur->rcur have been filled by the sender
178 * but not sent yet to the NIC; rcur->hwtail are available
179 * for new transmissions, and hwtail->hwcur-1 are pending
180 * transmissions not yet acknowledged.
182 * The indexes in the NIC and netmap rings are offset by nkr_hwofs slots.
183 * This is so that, on a reset, buffers owned by userspace are not
184 * modified by the kernel. In particular:
185 * RX rings: the next empty buffer (hwtail + hwofs) coincides with
186 * the next empty buffer as known by the hardware (next_to_check or so).
187 * TX rings: hwcur + hwofs coincides with next_to_send
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_(try)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
443 * Called with NMG_LOCK held.
445 * nm_register() is called on NIOCREGIF and close() to enter
446 * or exit netmap mode on the NIC
447 * Called with NMG_LOCK held.
449 * nm_txsync() pushes packets to the underlying hw/switch
451 * nm_rxsync() collects packets from the underlying hw/switch
453 * nm_config() returns configuration information from the OS
454 * Called with NMG_LOCK held.
456 * nm_krings_create() create and init the krings array
457 * (the array layout must conform to the description
458 * found above the definition of netmap_krings_create)
460 * nm_krings_delete() cleanup and delete the kring array
462 * nm_notify() is used to act after data have become available
463 * (or the stopped state of the ring has changed)
464 * For hw devices this is typically a selwakeup(),
465 * but for NIC/host ports attached to a switch (or vice-versa)
466 * we also need to invoke the 'txsync' code downstream.
468 void (*nm_dtor)(struct netmap_adapter *);
470 int (*nm_register)(struct netmap_adapter *, int onoff);
472 int (*nm_txsync)(struct netmap_adapter *, u_int ring, int flags);
473 int (*nm_rxsync)(struct netmap_adapter *, u_int ring, int flags);
474 #define NAF_FORCE_READ 1
475 #define NAF_FORCE_RECLAIM 2
476 /* return configuration information */
477 int (*nm_config)(struct netmap_adapter *,
478 u_int *txr, u_int *txd, u_int *rxr, u_int *rxd);
479 int (*nm_krings_create)(struct netmap_adapter *);
480 void (*nm_krings_delete)(struct netmap_adapter *);
481 int (*nm_notify)(struct netmap_adapter *,
482 u_int ring, enum txrx, int flags);
483 #define NAF_DISABLE_NOTIFY 8
485 /* standard refcount to control the lifetime of the adapter
486 * (it should be equal to the lifetime of the corresponding ifp)
490 /* memory allocator (opaque)
491 * We also cache a pointer to the lut_entry for translating
492 * buffer addresses, and the total number of buffers.
494 struct netmap_mem_d *nm_mem;
495 struct lut_entry *na_lut;
496 uint32_t na_lut_objtotal; /* max buffer index */
498 /* used internally. If non-null, the interface cannot be bound
504 struct netmap_pipe_adapter **na_pipes;
507 #endif /* WITH_PIPES */
512 * If the NIC is owned by the kernel
513 * (i.e., bridge), neither another bridge nor user can use it;
514 * if the NIC is owned by a user, only users can share it.
515 * Evaluation must be done under NMG_LOCK().
517 #define NETMAP_OWNED_BY_KERN(na) (na->na_private)
518 #define NETMAP_OWNED_BY_ANY(na) \
519 (NETMAP_OWNED_BY_KERN(na) || (na->active_fds > 0))
523 * derived netmap adapters for various types of ports
525 struct netmap_vp_adapter { /* VALE software port */
526 struct netmap_adapter up;
531 * bdg_port is the port number used in the bridge;
532 * na_bdg points to the bridge this NA is attached to.
535 struct nm_bridge *na_bdg;
538 /* Offset of ethernet header for each packet. */
540 /* Maximum Frame Size, used in bdg_mismatch_datapath() */
545 struct netmap_hw_adapter { /* physical device */
546 struct netmap_adapter up;
548 struct net_device_ops nm_ndo; // XXX linux only
551 /* Mitigation support. */
552 struct nm_generic_mit {
553 struct hrtimer mit_timer;
555 struct netmap_adapter *mit_na; /* backpointer */
558 struct netmap_generic_adapter { /* emulated device */
559 struct netmap_hw_adapter up;
561 /* Pointer to a previously used netmap adapter. */
562 struct netmap_adapter *prev;
564 /* generic netmap adapters support:
565 * a net_device_ops struct overrides ndo_select_queue(),
566 * save_if_input saves the if_input hook (FreeBSD),
567 * mit implements rx interrupt mitigation,
569 struct net_device_ops generic_ndo;
570 void (*save_if_input)(struct ifnet *, struct mbuf *);
572 struct nm_generic_mit *mit;
574 netdev_tx_t (*save_start_xmit)(struct mbuf *, struct ifnet *);
579 netmap_real_tx_rings(struct netmap_adapter *na)
581 return na->num_tx_rings + !!(na->na_flags & NAF_HOST_RINGS);
585 netmap_real_rx_rings(struct netmap_adapter *na)
587 return na->num_rx_rings + !!(na->na_flags & NAF_HOST_RINGS);
593 * Bridge wrapper for non VALE ports attached to a VALE switch.
595 * The real device must already have its own netmap adapter (hwna).
596 * The bridge wrapper and the hwna adapter share the same set of
597 * netmap rings and buffers, but they have two separate sets of
598 * krings descriptors, with tx/rx meanings swapped:
601 * bwrap krings rings krings hwna
602 * +------+ +------+ +-----+ +------+ +------+
603 * |tx_rings->| |\ /| |----| |<-tx_rings|
604 * | | +------+ \ / +-----+ +------+ | |
607 * | | +------+/ \+-----+ +------+ | |
608 * |rx_rings->| | | |----| |<-rx_rings|
609 * | | +------+ +-----+ +------+ | |
612 * - packets coming from the bridge go to the brwap rx rings,
613 * which are also the hwna tx rings. The bwrap notify callback
614 * will then complete the hwna tx (see netmap_bwrap_notify).
616 * - packets coming from the outside go to the hwna rx rings,
617 * which are also the bwrap tx rings. The (overwritten) hwna
618 * notify method will then complete the bridge tx
619 * (see netmap_bwrap_intr_notify).
621 * The bridge wrapper may optionally connect the hwna 'host' rings
622 * to the bridge. This is done by using a second port in the
623 * bridge and connecting it to the 'host' netmap_vp_adapter
624 * contained in the netmap_bwrap_adapter. The brwap host adapter
625 * cross-links the hwna host rings in the same way as shown above.
627 * - packets coming from the bridge and directed to the host stack
628 * are handled by the bwrap host notify callback
629 * (see netmap_bwrap_host_notify)
631 * - packets coming from the host stack are still handled by the
632 * overwritten hwna notify callback (netmap_bwrap_intr_notify),
633 * but are diverted to the host adapter depending on the ring number.
636 struct netmap_bwrap_adapter {
637 struct netmap_vp_adapter up;
638 struct netmap_vp_adapter host; /* for host rings */
639 struct netmap_adapter *hwna; /* the underlying device */
641 /* backup of the hwna notify callback */
642 int (*save_notify)(struct netmap_adapter *,
643 u_int ring, enum txrx, int flags);
646 * When we attach a physical interface to the bridge, we
647 * allow the controlling process to terminate, so we need
648 * a place to store the netmap_priv_d data structure.
649 * This is only done when physical interfaces
650 * are attached to a bridge.
652 struct netmap_priv_d *na_kpriv;
656 #endif /* WITH_VALE */
660 #define NM_MAXPIPES 64 /* max number of pipes per adapter */
662 struct netmap_pipe_adapter {
663 struct netmap_adapter up;
665 u_int id; /* pipe identifier */
666 int role; /* either NR_REG_PIPE_MASTER or NR_REG_PIPE_SLAVE */
668 struct netmap_adapter *parent; /* adapter that owns the memory */
669 struct netmap_pipe_adapter *peer; /* the other end of the pipe */
670 int peer_ref; /* 1 iff we are holding a ref to the peer */
672 u_int parent_slot; /* index in the parent pipe array */
675 #endif /* WITH_PIPES */
678 /* return slots reserved to rx clients; used in drivers */
679 static inline uint32_t
680 nm_kr_rxspace(struct netmap_kring *k)
682 int space = k->nr_hwtail - k->nr_hwcur;
684 space += k->nkr_num_slots;
685 ND("preserving %d rx slots %d -> %d", space, k->nr_hwcur, k->nr_hwtail);
691 /* True if no space in the tx ring. only valid after txsync_prologue */
693 nm_kr_txempty(struct netmap_kring *kring)
695 return kring->rcur == kring->nr_hwtail;
700 * protect against multiple threads using the same ring.
701 * also check that the ring has not been stopped.
702 * We only care for 0 or !=0 as a return code.
705 #define NM_KR_STOPPED 2
708 static __inline void nm_kr_put(struct netmap_kring *kr)
710 NM_ATOMIC_CLEAR(&kr->nr_busy);
714 static __inline int nm_kr_tryget(struct netmap_kring *kr)
716 /* check a first time without taking the lock
717 * to avoid starvation for nm_kr_get()
719 if (unlikely(kr->nkr_stopped)) {
720 ND("ring %p stopped (%d)", kr, kr->nkr_stopped);
721 return NM_KR_STOPPED;
723 if (unlikely(NM_ATOMIC_TEST_AND_SET(&kr->nr_busy)))
725 /* check a second time with lock held */
726 if (unlikely(kr->nkr_stopped)) {
727 ND("ring %p stopped (%d)", kr, kr->nkr_stopped);
729 return NM_KR_STOPPED;
736 * The following functions are used by individual drivers to
737 * support netmap operation.
739 * netmap_attach() initializes a struct netmap_adapter, allocating the
740 * struct netmap_ring's and the struct selinfo.
742 * netmap_detach() frees the memory allocated by netmap_attach().
744 * netmap_transmit() replaces the if_transmit routine of the interface,
745 * and is used to intercept packets coming from the stack.
747 * netmap_load_map/netmap_reload_map are helper routines to set/reset
748 * the dmamap for a packet buffer
750 * netmap_reset() is a helper routine to be called in the driver
751 * when reinitializing a ring.
753 int netmap_attach(struct netmap_adapter *);
754 int netmap_attach_common(struct netmap_adapter *);
755 void netmap_detach_common(struct netmap_adapter *na);
756 void netmap_detach(struct ifnet *);
757 int netmap_transmit(struct ifnet *, struct mbuf *);
758 struct netmap_slot *netmap_reset(struct netmap_adapter *na,
759 enum txrx tx, u_int n, u_int new_cur);
760 int netmap_ring_reinit(struct netmap_kring *);
762 /* default functions to handle rx/tx interrupts */
763 int netmap_rx_irq(struct ifnet *, u_int, u_int *);
764 #define netmap_tx_irq(_n, _q) netmap_rx_irq(_n, _q, NULL)
765 void netmap_common_irq(struct ifnet *, u_int, u_int *work_done);
767 void netmap_disable_all_rings(struct ifnet *);
768 void netmap_enable_all_rings(struct ifnet *);
769 void netmap_disable_ring(struct netmap_kring *kr);
772 /* set/clear native flags and if_transmit/netdev_ops */
774 nm_set_native_flags(struct netmap_adapter *na)
776 struct ifnet *ifp = na->ifp;
778 na->na_flags |= (NAF_NATIVE_ON | NAF_NETMAP_ON);
779 #ifdef IFCAP_NETMAP /* or FreeBSD ? */
780 ifp->if_capenable |= IFCAP_NETMAP;
783 na->if_transmit = ifp->if_transmit;
784 ifp->if_transmit = netmap_transmit;
786 na->if_transmit = (void *)ifp->netdev_ops;
787 ifp->netdev_ops = &((struct netmap_hw_adapter *)na)->nm_ndo;
793 nm_clear_native_flags(struct netmap_adapter *na)
795 struct ifnet *ifp = na->ifp;
798 ifp->if_transmit = na->if_transmit;
800 ifp->netdev_ops = (void *)na->if_transmit;
802 na->na_flags &= ~(NAF_NATIVE_ON | NAF_NETMAP_ON);
803 #ifdef IFCAP_NETMAP /* or FreeBSD ? */
804 ifp->if_capenable &= ~IFCAP_NETMAP;
810 * validates parameters in the ring/kring, returns a value for head
811 * If any error, returns ring_size to force a reinit.
813 uint32_t nm_txsync_prologue(struct netmap_kring *);
817 * validates parameters in the ring/kring, returns a value for head,
818 * and the 'reserved' value in the argument.
819 * If any error, returns ring_size lim to force a reinit.
821 uint32_t nm_rxsync_prologue(struct netmap_kring *);
825 * update kring and ring at the end of txsync.
828 nm_txsync_finalize(struct netmap_kring *kring)
830 /* update ring tail to what the kernel knows */
831 kring->ring->tail = kring->rtail = kring->nr_hwtail;
833 /* note, head/rhead/hwcur might be behind cur/rcur
836 ND(5, "%s now hwcur %d hwtail %d head %d cur %d tail %d",
837 kring->name, kring->nr_hwcur, kring->nr_hwtail,
838 kring->rhead, kring->rcur, kring->rtail);
843 * update kring and ring at the end of rxsync
846 nm_rxsync_finalize(struct netmap_kring *kring)
848 /* tell userspace that there might be new packets */
849 //struct netmap_ring *ring = kring->ring;
850 ND("head %d cur %d tail %d -> %d", ring->head, ring->cur, ring->tail,
852 kring->ring->tail = kring->rtail = kring->nr_hwtail;
853 /* make a copy of the state for next round */
854 kring->rhead = kring->ring->head;
855 kring->rcur = kring->ring->cur;
859 /* check/fix address and len in tx rings */
860 #if 1 /* debug version */
861 #define NM_CHECK_ADDR_LEN(_a, _l) do { \
862 if (_a == netmap_buffer_base || _l > NETMAP_BUF_SIZE) { \
863 RD(5, "bad addr/len ring %d slot %d idx %d len %d", \
864 ring_nr, nm_i, slot->buf_idx, len); \
865 if (_l > NETMAP_BUF_SIZE) \
866 _l = NETMAP_BUF_SIZE; \
868 #else /* no debug version */
869 #define NM_CHECK_ADDR_LEN(_a, _l) do { \
870 if (_l > NETMAP_BUF_SIZE) \
871 _l = NETMAP_BUF_SIZE; \
876 /*---------------------------------------------------------------*/
878 * Support routines to be used with the VALE switch
880 int netmap_update_config(struct netmap_adapter *na);
881 int netmap_krings_create(struct netmap_adapter *na, u_int tailroom);
882 void netmap_krings_delete(struct netmap_adapter *na);
883 int netmap_rxsync_from_host(struct netmap_adapter *na, struct thread *td, void *pwait);
887 netmap_do_regif(struct netmap_priv_d *priv, struct netmap_adapter *na,
888 uint16_t ringid, uint32_t flags, int *err);
892 u_int nm_bound_var(u_int *v, u_int dflt, u_int lo, u_int hi, const char *msg);
893 int netmap_get_na(struct nmreq *nmr, struct netmap_adapter **na, int create);
894 int netmap_get_hw_na(struct ifnet *ifp, struct netmap_adapter **na);
899 * The following bridge-related functions are used by other
902 * VALE only supports unicast or broadcast. The lookup
903 * function can return 0 .. NM_BDG_MAXPORTS-1 for regular ports,
904 * NM_BDG_MAXPORTS for broadcast, NM_BDG_MAXPORTS+1 for unknown.
905 * XXX in practice "unknown" might be handled same as broadcast.
907 typedef u_int (*bdg_lookup_fn_t)(char *buf, u_int len,
908 uint8_t *ring_nr, struct netmap_vp_adapter *);
909 u_int netmap_bdg_learning(char *, u_int, uint8_t *,
910 struct netmap_vp_adapter *);
912 #define NM_BDG_MAXPORTS 254 /* up to 254 */
913 #define NM_BDG_BROADCAST NM_BDG_MAXPORTS
914 #define NM_BDG_NOPORT (NM_BDG_MAXPORTS+1)
916 #define NM_NAME "vale" /* prefix for bridge port name */
919 /* these are redefined in case of no VALE support */
920 int netmap_get_bdg_na(struct nmreq *nmr, struct netmap_adapter **na, int create);
921 void netmap_init_bridges(void);
922 int netmap_bdg_ctl(struct nmreq *nmr, bdg_lookup_fn_t func);
924 #else /* !WITH_VALE */
925 #define netmap_get_bdg_na(_1, _2, _3) 0
926 #define netmap_init_bridges(_1)
927 #define netmap_bdg_ctl(_1, _2) EINVAL
928 #endif /* !WITH_VALE */
931 /* max number of pipes per device */
932 #define NM_MAXPIPES 64 /* XXX how many? */
933 /* in case of no error, returns the actual number of pipes in nmr->nr_arg1 */
934 int netmap_pipe_alloc(struct netmap_adapter *, struct nmreq *nmr);
935 void netmap_pipe_dealloc(struct netmap_adapter *);
936 int netmap_get_pipe_na(struct nmreq *nmr, struct netmap_adapter **na, int create);
937 #else /* !WITH_PIPES */
938 #define NM_MAXPIPES 0
939 #define netmap_pipe_alloc(_1, _2) EOPNOTSUPP
940 #define netmap_pipe_dealloc(_1)
941 #define netmap_get_pipe_na(_1, _2, _3) 0
944 /* Various prototypes */
945 int netmap_poll(struct cdev *dev, int events, struct thread *td);
946 int netmap_init(void);
947 void netmap_fini(void);
948 int netmap_get_memory(struct netmap_priv_d* p);
949 void netmap_dtor(void *data);
950 int netmap_dtor_locked(struct netmap_priv_d *priv);
952 int netmap_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag, struct thread *td);
954 /* netmap_adapter creation/destruction */
955 #define NM_IFPNAME(ifp) ((ifp) ? (ifp)->if_xname : "zombie")
957 // #define NM_DEBUG_PUTGET 1
959 #ifdef NM_DEBUG_PUTGET
961 #define NM_DBG(f) __##f
963 void __netmap_adapter_get(struct netmap_adapter *na);
965 #define netmap_adapter_get(na) \
967 struct netmap_adapter *__na = na; \
968 D("getting %p:%s (%d)", __na, NM_IFPNAME(__na->ifp), __na->na_refcount); \
969 __netmap_adapter_get(__na); \
972 int __netmap_adapter_put(struct netmap_adapter *na);
974 #define netmap_adapter_put(na) \
976 struct netmap_adapter *__na = na; \
977 D("putting %p:%s (%d)", __na, NM_IFPNAME(__na->ifp), __na->na_refcount); \
978 __netmap_adapter_put(__na); \
981 #else /* !NM_DEBUG_PUTGET */
984 void netmap_adapter_get(struct netmap_adapter *na);
985 int netmap_adapter_put(struct netmap_adapter *na);
987 #endif /* !NM_DEBUG_PUTGET */
993 extern u_int netmap_buf_size;
994 #define NETMAP_BUF_SIZE netmap_buf_size // XXX remove
995 extern int netmap_mitigate; // XXX not really used
996 extern int netmap_no_pendintr;
997 extern u_int netmap_total_buffers; // global allocator
998 extern char *netmap_buffer_base; // global allocator
999 extern int netmap_verbose; // XXX debugging
1000 enum { /* verbose flags */
1001 NM_VERB_ON = 1, /* generic verbose */
1002 NM_VERB_HOST = 0x2, /* verbose host stack */
1003 NM_VERB_RXSYNC = 0x10, /* verbose on rxsync/txsync */
1004 NM_VERB_TXSYNC = 0x20,
1005 NM_VERB_RXINTR = 0x100, /* verbose on rx/tx intr (driver) */
1006 NM_VERB_TXINTR = 0x200,
1007 NM_VERB_NIC_RXSYNC = 0x1000, /* verbose on rx/tx intr (driver) */
1008 NM_VERB_NIC_TXSYNC = 0x2000,
1011 extern int netmap_txsync_retry;
1012 extern int netmap_generic_mit;
1013 extern int netmap_generic_ringsize;
1014 extern int netmap_generic_rings;
1017 * NA returns a pointer to the struct netmap adapter from the ifp,
1018 * WNA is used to write it.
1021 #define WNA(_ifp) (_ifp)->if_pspare[0]
1023 #define NA(_ifp) ((struct netmap_adapter *)WNA(_ifp))
1026 * Macros to determine if an interface is netmap capable or netmap enabled.
1027 * See the magic field in struct netmap_adapter.
1031 * on FreeBSD just use if_capabilities and if_capenable.
1033 #define NETMAP_CAPABLE(ifp) (NA(ifp) && \
1034 (ifp)->if_capabilities & IFCAP_NETMAP )
1036 #define NETMAP_SET_CAPABLE(ifp) \
1037 (ifp)->if_capabilities |= IFCAP_NETMAP
1043 * we check if NA(ifp) is set and its first element has a related
1044 * magic value. The capenable is within the struct netmap_adapter.
1046 #define NETMAP_MAGIC 0x52697a7a
1048 #define NETMAP_CAPABLE(ifp) (NA(ifp) && \
1049 ((uint32_t)(uintptr_t)NA(ifp) ^ NA(ifp)->magic) == NETMAP_MAGIC )
1051 #define NETMAP_SET_CAPABLE(ifp) \
1052 NA(ifp)->magic = ((uint32_t)(uintptr_t)NA(ifp)) ^ NETMAP_MAGIC
1058 /* Callback invoked by the dma machinery after a successful dmamap_load */
1059 static void netmap_dmamap_cb(__unused void *arg,
1060 __unused bus_dma_segment_t * segs, __unused int nseg, __unused int error)
1064 /* bus_dmamap_load wrapper: call aforementioned function if map != NULL.
1065 * XXX can we do it without a callback ?
1068 netmap_load_map(bus_dma_tag_t tag, bus_dmamap_t map, void *buf)
1071 bus_dmamap_load(tag, map, buf, NETMAP_BUF_SIZE,
1072 netmap_dmamap_cb, NULL, BUS_DMA_NOWAIT);
1075 /* update the map when a buffer changes. */
1077 netmap_reload_map(bus_dma_tag_t tag, bus_dmamap_t map, void *buf)
1080 bus_dmamap_unload(tag, map);
1081 bus_dmamap_load(tag, map, buf, NETMAP_BUF_SIZE,
1082 netmap_dmamap_cb, NULL, BUS_DMA_NOWAIT);
1089 * XXX How do we redefine these functions:
1092 * dma_map_single(&pdev->dev, virt_addr, len, direction)
1093 * dma_unmap_single(&adapter->pdev->dev, phys_addr, len, direction
1094 * The len can be implicit (on netmap it is NETMAP_BUF_SIZE)
1095 * unfortunately the direction is not, so we need to change
1096 * something to have a cross API
1098 #define netmap_load_map(_t, _m, _b)
1099 #define netmap_reload_map(_t, _m, _b)
1101 struct e1000_buffer *buffer_info = &tx_ring->buffer_info[l];
1102 /* set time_stamp *before* dma to help avoid a possible race */
1103 buffer_info->time_stamp = jiffies;
1104 buffer_info->mapped_as_page = false;
1105 buffer_info->length = len;
1106 //buffer_info->next_to_watch = l;
1107 /* reload dma map */
1108 dma_unmap_single(&adapter->pdev->dev, buffer_info->dma,
1109 NETMAP_BUF_SIZE, DMA_TO_DEVICE);
1110 buffer_info->dma = dma_map_single(&adapter->pdev->dev,
1111 addr, NETMAP_BUF_SIZE, DMA_TO_DEVICE);
1113 if (dma_mapping_error(&adapter->pdev->dev, buffer_info->dma)) {
1114 D("dma mapping error");
1115 /* goto dma_error; See e1000_put_txbuf() */
1118 tx_desc->buffer_addr = htole64(buffer_info->dma); //XXX
1123 * The bus_dmamap_sync() can be one of wmb() or rmb() depending on direction.
1125 #define bus_dmamap_sync(_a, _b, _c)
1131 * functions to map NIC to KRING indexes (n2k) and vice versa (k2n)
1134 netmap_idx_n2k(struct netmap_kring *kr, int idx)
1136 int n = kr->nkr_num_slots;
1137 idx += kr->nkr_hwofs;
1148 netmap_idx_k2n(struct netmap_kring *kr, int idx)
1150 int n = kr->nkr_num_slots;
1151 idx -= kr->nkr_hwofs;
1161 /* Entries of the look-up table. */
1163 void *vaddr; /* virtual address. */
1164 vm_paddr_t paddr; /* physical address. */
1167 struct netmap_obj_pool;
1168 extern struct lut_entry *netmap_buffer_lut;
1169 #define NMB_VA(i) (netmap_buffer_lut[i].vaddr)
1170 #define NMB_PA(i) (netmap_buffer_lut[i].paddr)
1173 * NMB return the virtual address of a buffer (buffer 0 on bad index)
1174 * PNMB also fills the physical address
1176 static inline void *
1177 NMB(struct netmap_slot *slot)
1179 uint32_t i = slot->buf_idx;
1180 return (unlikely(i >= netmap_total_buffers)) ? NMB_VA(0) : NMB_VA(i);
1183 static inline void *
1184 PNMB(struct netmap_slot *slot, uint64_t *pp)
1186 uint32_t i = slot->buf_idx;
1187 void *ret = (i >= netmap_total_buffers) ? NMB_VA(0) : NMB_VA(i);
1189 *pp = (i >= netmap_total_buffers) ? NMB_PA(0) : NMB_PA(i);
1193 /* Generic version of NMB, which uses device-specific memory. */
1194 static inline void *
1195 BDG_NMB(struct netmap_adapter *na, struct netmap_slot *slot)
1197 struct lut_entry *lut = na->na_lut;
1198 uint32_t i = slot->buf_idx;
1199 return (unlikely(i >= na->na_lut_objtotal)) ?
1200 lut[0].vaddr : lut[i].vaddr;
1205 void netmap_txsync_to_host(struct netmap_adapter *na);
1209 * Structure associated to each thread which registered an interface.
1211 * The first 4 fields of this structure are written by NIOCREGIF and
1212 * read by poll() and NIOC?XSYNC.
1214 * There is low contention among writers (a correct user program
1215 * should have none) and among writers and readers, so we use a
1216 * single global lock to protect the structure initialization;
1217 * since initialization involves the allocation of memory,
1218 * we reuse the memory allocator lock.
1220 * Read access to the structure is lock free. Readers must check that
1221 * np_nifp is not NULL before using the other fields.
1222 * If np_nifp is NULL initialization has not been performed,
1223 * so they should return an error to userspace.
1225 * The ref_done field is used to regulate access to the refcount in the
1226 * memory allocator. The refcount must be incremented at most once for
1227 * each open("/dev/netmap"). The increment is performed by the first
1228 * function that calls netmap_get_memory() (currently called by
1229 * mmap(), NIOCGINFO and NIOCREGIF).
1230 * If the refcount is incremented, it is then decremented when the
1231 * private structure is destroyed.
1233 struct netmap_priv_d {
1234 struct netmap_if * volatile np_nifp; /* netmap if descriptor. */
1236 struct netmap_adapter *np_na;
1237 uint32_t np_flags; /* from the ioctl */
1238 u_int np_txqfirst, np_txqlast; /* range of tx rings to scan */
1239 u_int np_rxqfirst, np_rxqlast; /* range of rx rings to scan */
1240 uint16_t np_txpoll; /* XXX and also np_rxpoll ? */
1242 struct netmap_mem_d *np_mref; /* use with NMG_LOCK held */
1243 /* np_refcount is only used on FreeBSD */
1244 int np_refcount; /* use with NMG_LOCK held */
1246 /* pointers to the selinfo to be used for selrecord.
1247 * Either the local or the global one depending on the
1250 NM_SELINFO_T *np_rxsi, *np_txsi;
1251 struct thread *np_td; /* kqueue, just debugging */
1256 * generic netmap emulation for devices that do not have
1257 * native netmap support.
1259 int generic_netmap_attach(struct ifnet *ifp);
1261 int netmap_catch_rx(struct netmap_adapter *na, int intercept);
1262 void generic_rx_handler(struct ifnet *ifp, struct mbuf *m);;
1263 void netmap_catch_tx(struct netmap_generic_adapter *na, int enable);
1264 int generic_xmit_frame(struct ifnet *ifp, struct mbuf *m, void *addr, u_int len, u_int ring_nr);
1265 int generic_find_num_desc(struct ifnet *ifp, u_int *tx, u_int *rx);
1266 void generic_find_num_queues(struct ifnet *ifp, u_int *txq, u_int *rxq);
1269 * netmap_mitigation API. This is used by the generic adapter
1270 * to reduce the number of interrupt requests/selwakeup
1271 * to clients on incoming packets.
1273 void netmap_mitigation_init(struct nm_generic_mit *mit, struct netmap_adapter *na);
1274 void netmap_mitigation_start(struct nm_generic_mit *mit);
1275 void netmap_mitigation_restart(struct nm_generic_mit *mit);
1276 int netmap_mitigation_active(struct nm_generic_mit *mit);
1277 void netmap_mitigation_cleanup(struct nm_generic_mit *mit);
1281 /* Shared declarations for the VALE switch. */
1284 * Each transmit queue accumulates a batch of packets into
1285 * a structure before forwarding. Packets to the same
1286 * destination are put in a list using ft_next as a link field.
1287 * ft_frags and ft_next are valid only on the first fragment.
1289 struct nm_bdg_fwd { /* forwarding entry for a bridge */
1290 void *ft_buf; /* netmap or indirect buffer */
1291 uint8_t ft_frags; /* how many fragments (only on 1st frag) */
1292 uint8_t _ft_port; /* dst port (unused) */
1293 uint16_t ft_flags; /* flags, e.g. indirect */
1294 uint16_t ft_len; /* src fragment len */
1295 uint16_t ft_next; /* next packet to same destination */
1298 /* struct 'virtio_net_hdr' from linux. */
1299 struct nm_vnet_hdr {
1300 #define VIRTIO_NET_HDR_F_NEEDS_CSUM 1 /* Use csum_start, csum_offset */
1301 #define VIRTIO_NET_HDR_F_DATA_VALID 2 /* Csum is valid */
1303 #define VIRTIO_NET_HDR_GSO_NONE 0 /* Not a GSO frame */
1304 #define VIRTIO_NET_HDR_GSO_TCPV4 1 /* GSO frame, IPv4 TCP (TSO) */
1305 #define VIRTIO_NET_HDR_GSO_UDP 3 /* GSO frame, IPv4 UDP (UFO) */
1306 #define VIRTIO_NET_HDR_GSO_TCPV6 4 /* GSO frame, IPv6 TCP */
1307 #define VIRTIO_NET_HDR_GSO_ECN 0x80 /* TCP has ECN set */
1311 uint16_t csum_start;
1312 uint16_t csum_offset;
1315 #define WORST_CASE_GSO_HEADER (14+40+60) /* IPv6 + TCP */
1317 /* Private definitions for IPv4, IPv6, UDP and TCP headers. */
1320 uint8_t version_ihl;
1330 /*The options start here. */
1338 uint8_t doff; /* Data offset + Reserved */
1353 uint8_t priority_version;
1354 uint8_t flow_lbl[3];
1356 uint16_t payload_len;
1364 /* Type used to store a checksum (in host byte order) that hasn't been
1367 #define rawsum_t uint32_t
1369 rawsum_t nm_csum_raw(uint8_t *data, size_t len, rawsum_t cur_sum);
1370 uint16_t nm_csum_ipv4(struct nm_iphdr *iph);
1371 void nm_csum_tcpudp_ipv4(struct nm_iphdr *iph, void *data,
1372 size_t datalen, uint16_t *check);
1373 void nm_csum_tcpudp_ipv6(struct nm_ipv6hdr *ip6h, void *data,
1374 size_t datalen, uint16_t *check);
1375 uint16_t nm_csum_fold(rawsum_t cur_sum);
1377 void bdg_mismatch_datapath(struct netmap_vp_adapter *na,
1378 struct netmap_vp_adapter *dst_na,
1379 struct nm_bdg_fwd *ft_p, struct netmap_ring *ring,
1380 u_int *j, u_int lim, u_int *howmany);
1381 #endif /* _NET_NETMAP_KERN_H_ */