netmap: lock(9), k*() foo, no ifdefs
[dragonfly.git] / sys / net / netmap / netmap_kern.h
1 /*
2  * Copyright (C) 2011-2013 Matteo Landi, Luigi Rizzo. All rights reserved.
3  * Copyright (C) 2013 Universita` di Pisa. All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *   1. Redistributions of source code must retain the above copyright
9  *      notice, this list of conditions and the following disclaimer.
10  *   2. Redistributions in binary form must reproduce the above copyright
11  *      notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26
27 /*
28  * $FreeBSD: head/sys/dev/netmap/netmap_kern.h 238985 2012-08-02 11:59:43Z luigi $
29  *
30  * The header contains the definitions of constants and function
31  * prototypes used only in kernelspace.
32  */
33
34 #ifndef _NET_NETMAP_KERN_H_
35 #define _NET_NETMAP_KERN_H_
36
37 #define WITH_VALE       // comment out to disable VALE support
38
39 #define likely(x)       __builtin_expect((long)!!(x), 1L)
40 #define unlikely(x)     __builtin_expect((long)!!(x), 0L)
41
42 #define NM_LOCK_T       struct lock
43 #define NMG_LOCK_T      struct lock
44 #define NMG_LOCK_INIT() lockinit(&netmap_global_lock, \
45                                 "netmap global lock", 0, 0)
46 #define NMG_LOCK_DESTROY()      lockuninit(&netmap_global_lock)
47 #define NMG_LOCK()      lockmgr(&netmap_global_lock, LK_EXCLUSIVE)
48 #define NMG_UNLOCK()    lockmgr(&netmap_global_lock, LK_RELEASE)
49 #define NMG_LOCK_ASSERT()       KKASSERT(lockcountnb(&netmap_global_lock))
50
51 #define NM_SELINFO_T    struct taskqueue *
52 #define MBUF_LEN(m)     ((m)->m_pkthdr.len)
53 #define MBUF_IFP(m)     ((m)->m_pkthdr.rcvif)
54 #define NM_SEND_UP(ifp, m)      ((ifp)->if_input)(ifp, m)
55
56 #define NM_ATOMIC_T     volatile int    // XXX ?
57 /* atomic operations */
58 #include <machine/atomic.h>
59 #define NM_ATOMIC_TEST_AND_SET(p)       (!atomic_cmpset_acq_int((p), 0, 1))
60 #define NM_ATOMIC_CLEAR(p)              atomic_store_rel_int((p), 0)
61
62 #define prefetch(x)     __builtin_prefetch(x)
63
64 MALLOC_DECLARE(M_NETMAP);
65
66 // XXX linux struct, not used in FreeBSD
67 struct net_device_ops {
68 };
69 struct hrtimer {
70 };
71
72 #define IFCAP_NETMAP    0x8000  /* XXX move to <net/if.h> */
73
74 #define ND(format, ...)
75 #define D(format, ...)                                          \
76         do {                                                    \
77                 struct timeval __xxts;                          \
78                 microtime(&__xxts);                             \
79                 kprintf("%03d.%06d %s [%d] " format "\n",       \
80                 (int)__xxts.tv_sec % 1000, (int)__xxts.tv_usec, \
81                 __FUNCTION__, __LINE__, ##__VA_ARGS__);         \
82         } while (0)
83
84 /* rate limited, lps indicates how many per second */
85 #define RD(lps, format, ...)                                    \
86         do {                                                    \
87                 static int t0, __cnt;                           \
88                 if (t0 != time_second) {                        \
89                         t0 = time_second;                       \
90                         __cnt = 0;                              \
91                 }                                               \
92                 if (__cnt++ < lps)                              \
93                         D(format, ##__VA_ARGS__);               \
94         } while (0)
95
96 struct netmap_adapter;
97 struct nm_bdg_fwd;
98 struct nm_bridge;
99 struct netmap_priv_d;
100
101 const char *nm_dump_buf(char *p, int len, int lim, char *dst);
102
103 #include "netmap_mbq.h"
104
105 extern NMG_LOCK_T       netmap_global_lock;
106
107 /*
108  * private, kernel view of a ring. Keeps track of the status of
109  * a ring across system calls.
110  *
111  *      nr_hwcur        index of the next buffer to refill.
112  *                      It corresponds to ring->cur - ring->reserved
113  *
114  *      nr_hwavail      the number of slots "owned" by userspace.
115  *                      nr_hwavail =:= ring->avail + ring->reserved
116  *
117  * The indexes in the NIC and netmap rings are offset by nkr_hwofs slots.
118  * This is so that, on a reset, buffers owned by userspace are not
119  * modified by the kernel. In particular:
120  * RX rings: the next empty buffer (hwcur + hwavail + hwofs) coincides with
121  *      the next empty buffer as known by the hardware (next_to_check or so).
122  * TX rings: hwcur + hwofs coincides with next_to_send
123  *
124  * Clients cannot issue concurrent syscall on a ring. The system
125  * detects this and reports an error using two flags,
126  * NKR_WBUSY and NKR_RBUSY
127  * For received packets, slot->flags is set to nkr_slot_flags
128  * so we can provide a proper initial value (e.g. set NS_FORWARD
129  * when operating in 'transparent' mode).
130  *
131  * The following fields are used to implement lock-free copy of packets
132  * from input to output ports in VALE switch:
133  *      nkr_hwlease     buffer after the last one being copied.
134  *                      A writer in nm_bdg_flush reserves N buffers
135  *                      from nr_hwlease, advances it, then does the
136  *                      copy outside the lock.
137  *                      In RX rings (used for VALE ports),
138  *                      nkr_hwcur + nkr_hwavail <= nkr_hwlease < nkr_hwcur+N-1
139  *                      In TX rings (used for NIC or host stack ports)
140  *                      nkr_hwcur <= nkr_hwlease < nkr_hwcur+ nkr_hwavail
141  *      nkr_leases      array of nkr_num_slots where writers can report
142  *                      completion of their block. NR_NOSLOT (~0) indicates
143  *                      that the writer has not finished yet
144  *      nkr_lease_idx   index of next free slot in nr_leases, to be assigned
145  *
146  * The kring is manipulated by txsync/rxsync and generic netmap function.
147  * q_lock is used to arbitrate access to the kring from within the netmap
148  * code, and this and other protections guarantee that there is never
149  * more than 1 concurrent call to txsync or rxsync. So we are free
150  * to manipulate the kring from within txsync/rxsync without any extra
151  * locks.
152  */
153 struct netmap_kring {
154         struct netmap_ring *ring;
155         uint32_t nr_hwcur;
156         uint32_t nr_hwavail;
157         uint32_t nr_kflags;     /* private driver flags */
158         int32_t nr_hwreserved;
159 #define NKR_PENDINTR    0x1     // Pending interrupt.
160         uint32_t nkr_num_slots;
161         int32_t nkr_hwofs;      /* offset between NIC and netmap ring */
162
163         uint16_t        nkr_slot_flags; /* initial value for flags */
164         struct netmap_adapter *na;
165         struct nm_bdg_fwd *nkr_ft;
166         uint32_t *nkr_leases;
167 #define NR_NOSLOT       ((uint32_t)~0)
168         uint32_t nkr_hwlease;
169         uint32_t nkr_lease_idx;
170
171         NM_SELINFO_T si;        /* poll/select wait queue */
172         NM_LOCK_T q_lock;       /* protects kring and ring. */
173         NM_ATOMIC_T nr_busy;    /* prevent concurrent syscalls */
174
175         volatile int nkr_stopped;
176
177         /* support for adapters without native netmap support.
178          * On tx rings we preallocate an array of tx buffers
179          * (same size as the netmap ring), on rx rings we
180          * store incoming packets in a queue.
181          * XXX who writes to the rx queue ?
182          */
183         struct mbuf **tx_pool;
184         u_int nr_ntc;                   /* Emulation of a next-to-clean RX ring pointer. */
185         struct mbq rx_queue;            /* A queue for intercepted rx mbufs. */
186
187 } __attribute__((__aligned__(64)));
188
189
190 /* return the next index, with wraparound */
191 static inline uint32_t
192 nm_next(uint32_t i, uint32_t lim)
193 {
194         return unlikely (i == lim) ? 0 : i + 1;
195 }
196
197 /*
198  *
199  * Here is the layout for the Rx and Tx rings.
200
201        RxRING                            TxRING
202
203       +-----------------+            +-----------------+
204       |                 |            |                 |
205       |XXX free slot XXX|            |XXX free slot XXX|
206       +-----------------+            +-----------------+
207       |                 |<-hwcur     |                 |<-hwcur
208       | reserved    h   |            | (ready          |
209       +-----------  w  -+            |  to be          |
210  cur->|             a   |            |  sent)      h   |
211       |             v   |            +----------   w   |
212       |             a   |       cur->| (being      a   |
213       |             i   |            |  prepared)  v   |
214       | avail       l   |            |             a   |
215       +-----------------+            +  a  ------  i   +
216       |                 | ...        |  v          l   |<-hwlease
217       | (being          | ...        |  a              | ...
218       |  prepared)      | ...        |  i              | ...
219       +-----------------+ ...        |  l              | ...
220       |                 |<-hwlease   +-----------------+
221       |                 |            |                 |
222       |                 |            |                 |
223       |                 |            |                 |
224       |                 |            |                 |
225       +-----------------+            +-----------------+
226
227  * The cur/avail (user view) and hwcur/hwavail (kernel view)
228  * are used in the normal operation of the card.
229  *
230  * When a ring is the output of a switch port (Rx ring for
231  * a VALE port, Tx ring for the host stack or NIC), slots
232  * are reserved in blocks through 'hwlease' which points
233  * to the next unused slot.
234  * On an Rx ring, hwlease is always after hwavail,
235  * and completions cause avail to advance.
236  * On a Tx ring, hwlease is always between cur and hwavail,
237  * and completions cause cur to advance.
238  *
239  * nm_kr_space() returns the maximum number of slots that
240  * can be assigned.
241  * nm_kr_lease() reserves the required number of buffers,
242  *    advances nkr_hwlease and also returns an entry in
243  *    a circular array where completions should be reported.
244  */
245
246
247
248
249 enum txrx { NR_RX = 0, NR_TX = 1 };
250
251 /*
252  * The "struct netmap_adapter" extends the "struct adapter"
253  * (or equivalent) device descriptor.
254  * It contains all base fields needed to support netmap operation.
255  * There are in fact different types of netmap adapters
256  * (native, generic, VALE switch...) so a netmap_adapter is
257  * just the first field in the derived type.
258  */
259 struct netmap_adapter {
260         /*
261          * On linux we do not have a good way to tell if an interface
262          * is netmap-capable. So we use the following trick:
263          * NA(ifp) points here, and the first entry (which hopefully
264          * always exists and is at least 32 bits) contains a magic
265          * value which we can use to detect that the interface is good.
266          */
267         uint32_t magic;
268         uint32_t na_flags;      /* future place for IFCAP_NETMAP */
269 #define NAF_SKIP_INTR   1       /* use the regular interrupt handler.
270                                  * useful during initialization
271                                  */
272 #define NAF_SW_ONLY     2       /* forward packets only to sw adapter */
273 #define NAF_BDG_MAYSLEEP 4      /* the bridge is allowed to sleep when
274                                  * forwarding packets coming from this
275                                  * interface
276                                  */
277 #define NAF_MEM_OWNER   8       /* the adapter is responsible for the
278                                  * deallocation of the memory allocator
279                                  */
280 #define NAF_NATIVE_ON   16      /* the adapter is native and the attached
281                                  * interface is in netmap mode
282                                  */
283         int active_fds; /* number of user-space descriptors using this
284                          interface, which is equal to the number of
285                          struct netmap_if objs in the mapped region. */
286
287         u_int num_rx_rings; /* number of adapter receive rings */
288         u_int num_tx_rings; /* number of adapter transmit rings */
289
290         u_int num_tx_desc; /* number of descriptor in each queue */
291         u_int num_rx_desc;
292
293         /* tx_rings and rx_rings are private but allocated
294          * as a contiguous chunk of memory. Each array has
295          * N+1 entries, for the adapter queues and for the host queue.
296          */
297         struct netmap_kring *tx_rings; /* array of TX rings. */
298         struct netmap_kring *rx_rings; /* array of RX rings. */
299         void *tailroom;                /* space below the rings array */
300                                        /* (used for leases) */
301
302         NM_SELINFO_T tx_si;             /* global tx wait queue */
303         NM_SELINFO_T rx_si;             /* global rx wait queue */
304
305         /* copy of if_qflush and if_transmit pointers, to intercept
306          * packets from the network stack when netmap is active.
307          */
308         int     (*if_transmit)(struct ifnet *, struct mbuf *);
309
310         /* references to the ifnet and device routines, used by
311          * the generic netmap functions.
312          */
313         struct ifnet *ifp; /* adapter is ifp->if_softc */
314
315         /* private cleanup */
316         void (*nm_dtor)(struct netmap_adapter *);
317
318         int (*nm_register)(struct netmap_adapter *, int onoff);
319
320         int (*nm_txsync)(struct netmap_adapter *, u_int ring, int flags);
321         int (*nm_rxsync)(struct netmap_adapter *, u_int ring, int flags);
322 #define NAF_FORCE_READ    1
323 #define NAF_FORCE_RECLAIM 2
324         /* return configuration information */
325         int (*nm_config)(struct netmap_adapter *,
326                 u_int *txr, u_int *txd, u_int *rxr, u_int *rxd);
327         int (*nm_krings_create)(struct netmap_adapter *);
328         void (*nm_krings_delete)(struct netmap_adapter *);
329         int (*nm_notify)(struct netmap_adapter *,
330                 u_int ring, enum txrx, int flags);
331 #define NAF_GLOBAL_NOTIFY 4
332 #define NAF_DISABLE_NOTIFY 8
333
334         /* standard refcount to control the lifetime of the adapter
335          * (it should be equal to the lifetime of the corresponding ifp)
336          */
337         int na_refcount;
338
339         /* memory allocator (opaque)
340          * We also cache a pointer to the lut_entry for translating
341          * buffer addresses, and the total number of buffers.
342          */
343         struct netmap_mem_d *nm_mem;
344         struct lut_entry *na_lut;
345         uint32_t na_lut_objtotal;       /* max buffer index */
346
347         /* used internally. If non-null, the interface cannot be bound
348          * from userspace
349          */
350         void *na_private;
351 };
352
353 /*
354  * If the NIC is owned by the kernel
355  * (i.e., bridge), neither another bridge nor user can use it;
356  * if the NIC is owned by a user, only users can share it.
357  * Evaluation must be done under NMG_LOCK().
358  */
359 #define NETMAP_OWNED_BY_KERN(na)        (na->na_private)
360 #define NETMAP_OWNED_BY_ANY(na) \
361         (NETMAP_OWNED_BY_KERN(na) || (na->active_fds > 0))
362
363
364 /*
365  * derived netmap adapters for various types of ports
366  */
367 struct netmap_vp_adapter {      /* VALE software port */
368         struct netmap_adapter up;
369
370         /*
371          * Bridge support:
372          *
373          * bdg_port is the port number used in the bridge;
374          * na_bdg points to the bridge this NA is attached to.
375          */
376         int bdg_port;
377         struct nm_bridge *na_bdg;
378         int retry;
379 };
380
381 struct netmap_hw_adapter {      /* physical device */
382         struct netmap_adapter up;
383
384         struct net_device_ops nm_ndo;   // XXX linux only
385 };
386
387 struct netmap_generic_adapter { /* non-native device */
388         struct netmap_hw_adapter up;
389
390         /* Pointer to a previously used netmap adapter. */
391         struct netmap_adapter *prev;
392
393         /* generic netmap adapters support:
394          * a net_device_ops struct overrides ndo_select_queue(),
395          * save_if_input saves the if_input hook (FreeBSD),
396          * mit_timer and mit_pending implement rx interrupt mitigation,
397          */
398         struct net_device_ops generic_ndo;
399         void (*save_if_input)(struct ifnet *, struct mbuf *);
400
401         struct hrtimer mit_timer;
402         int mit_pending;
403 };
404
405 #ifdef WITH_VALE
406
407 /* bridge wrapper for non VALE ports. It is used to connect real devices to the bridge.
408  *
409  * The real device must already have its own netmap adapter (hwna).  The
410  * bridge wrapper and the hwna adapter share the same set of netmap rings and
411  * buffers, but they have two separate sets of krings descriptors, with tx/rx
412  * meanings swapped:
413  *
414  *                                  netmap
415  *           bwrap     krings       rings      krings      hwna
416  *         +------+   +------+     +-----+    +------+   +------+
417  *         |tx_rings->|      |\   /|     |----|      |<-tx_rings|
418  *         |      |   +------+ \ / +-----+    +------+   |      |
419  *         |      |             X                        |      |
420  *         |      |            / \                       |      |
421  *         |      |   +------+/   \+-----+    +------+   |      |
422  *         |rx_rings->|      |     |     |----|      |<-rx_rings|
423  *         |      |   +------+     +-----+    +------+   |      |
424  *         +------+                                      +------+
425  *
426  * - packets coming from the bridge go to the brwap rx rings, which are also the
427  *   hwna tx rings.  The bwrap notify callback will then complete the hwna tx
428  *   (see netmap_bwrap_notify).
429  * - packets coming from the outside go to the hwna rx rings, which are also the
430  *   bwrap tx rings.  The (overwritten) hwna notify method will then complete
431  *   the bridge tx (see netmap_bwrap_intr_notify).
432  *
433  *   The bridge wrapper may optionally connect the hwna 'host' rings to the
434  *   bridge. This is done by using a second port in the bridge and connecting it
435  *   to the 'host' netmap_vp_adapter contained in the netmap_bwrap_adapter.
436  *   The brwap host adapter cross-links the hwna host rings in the same way as shown above.
437  *
438  * - packets coming from the bridge and directed to host stack are handled by the
439  *   bwrap host notify callback (see netmap_bwrap_host_notify)
440  * - packets coming from the host stack are still handled by the overwritten
441  *   hwna notify callback (netmap_bwrap_intr_notify), but are diverted to the
442  *   host adapter depending on the ring number.
443  *
444  */
445 struct netmap_bwrap_adapter {
446         struct netmap_vp_adapter up;
447         struct netmap_vp_adapter host;  /* for host rings */
448         struct netmap_adapter *hwna;    /* the underlying device */
449
450         /* backup of the hwna notify callback */
451         int (*save_notify)(struct netmap_adapter *,
452                         u_int ring, enum txrx, int flags);
453         /* When we attach a physical interface to the bridge, we
454          * allow the controlling process to terminate, so we need
455          * a place to store the netmap_priv_d data structure.
456          * This is only done when physical interfaces are attached to a bridge.
457          */
458         struct netmap_priv_d *na_kpriv;
459 };
460
461
462 /*
463  * Available space in the ring. Only used in VALE code
464  */
465 static inline uint32_t
466 nm_kr_space(struct netmap_kring *k, int is_rx)
467 {
468         int space;
469
470         if (is_rx) {
471                 int busy = k->nkr_hwlease - k->nr_hwcur + k->nr_hwreserved;
472                 if (busy < 0)
473                         busy += k->nkr_num_slots;
474                 space = k->nkr_num_slots - 1 - busy;
475         } else {
476                 space = k->nr_hwcur + k->nr_hwavail - k->nkr_hwlease;
477                 if (space < 0)
478                         space += k->nkr_num_slots;
479         }
480 #if 0
481         // sanity check
482         if (k->nkr_hwlease >= k->nkr_num_slots ||
483                 k->nr_hwcur >= k->nkr_num_slots ||
484                 k->nr_hwavail >= k->nkr_num_slots ||
485                 busy < 0 ||
486                 busy >= k->nkr_num_slots) {
487                 D("invalid kring, cur %d avail %d lease %d lease_idx %d lim %d",                        k->nr_hwcur, k->nr_hwavail, k->nkr_hwlease,
488                         k->nkr_lease_idx, k->nkr_num_slots);
489         }
490 #endif
491         return space;
492 }
493
494
495
496
497 /* make a lease on the kring for N positions. return the
498  * lease index
499  */
500 static inline uint32_t
501 nm_kr_lease(struct netmap_kring *k, u_int n, int is_rx)
502 {
503         uint32_t lim = k->nkr_num_slots - 1;
504         uint32_t lease_idx = k->nkr_lease_idx;
505
506         k->nkr_leases[lease_idx] = NR_NOSLOT;
507         k->nkr_lease_idx = nm_next(lease_idx, lim);
508
509         if (n > nm_kr_space(k, is_rx)) {
510                 D("invalid request for %d slots", n);
511                 panic("x");
512         }
513         /* XXX verify that there are n slots */
514         k->nkr_hwlease += n;
515         if (k->nkr_hwlease > lim)
516                 k->nkr_hwlease -= lim + 1;
517
518         if (k->nkr_hwlease >= k->nkr_num_slots ||
519                 k->nr_hwcur >= k->nkr_num_slots ||
520                 k->nr_hwavail >= k->nkr_num_slots ||
521                 k->nkr_lease_idx >= k->nkr_num_slots) {
522                 D("invalid kring %s, cur %d avail %d lease %d lease_idx %d lim %d",
523                         k->na->ifp->if_xname,
524                         k->nr_hwcur, k->nr_hwavail, k->nkr_hwlease,
525                         k->nkr_lease_idx, k->nkr_num_slots);
526         }
527         return lease_idx;
528 }
529
530 #endif /* WITH_VALE */
531
532 /* return update position */
533 static inline uint32_t
534 nm_kr_rxpos(struct netmap_kring *k)
535 {
536         uint32_t pos = k->nr_hwcur + k->nr_hwavail;
537         if (pos >= k->nkr_num_slots)
538                 pos -= k->nkr_num_slots;
539 #if 0
540         if (pos >= k->nkr_num_slots ||
541                 k->nkr_hwlease >= k->nkr_num_slots ||
542                 k->nr_hwcur >= k->nkr_num_slots ||
543                 k->nr_hwavail >= k->nkr_num_slots ||
544                 k->nkr_lease_idx >= k->nkr_num_slots) {
545                 D("invalid kring, cur %d avail %d lease %d lease_idx %d lim %d",                        k->nr_hwcur, k->nr_hwavail, k->nkr_hwlease,
546                         k->nkr_lease_idx, k->nkr_num_slots);
547         }
548 #endif
549         return pos;
550 }
551
552
553 /*
554  * protect against multiple threads using the same ring.
555  * also check that the ring has not been stopped.
556  * We only care for 0 or !=0 as a return code.
557  */
558 #define NM_KR_BUSY      1
559 #define NM_KR_STOPPED   2
560
561 static __inline void nm_kr_put(struct netmap_kring *kr)
562 {
563         NM_ATOMIC_CLEAR(&kr->nr_busy);
564 }
565
566 static __inline int nm_kr_tryget(struct netmap_kring *kr)
567 {
568         /* check a first time without taking the lock
569          * to avoid starvation for nm_kr_get()
570          */
571         if (unlikely(kr->nkr_stopped)) {
572                 ND("ring %p stopped (%d)", kr, kr->nkr_stopped);
573                 return NM_KR_STOPPED;
574         }
575         if (unlikely(NM_ATOMIC_TEST_AND_SET(&kr->nr_busy)))
576                 return NM_KR_BUSY;
577         /* check a second time with lock held */
578         if (unlikely(kr->nkr_stopped)) {
579                 ND("ring %p stopped (%d)", kr, kr->nkr_stopped);
580                 nm_kr_put(kr);
581                 return NM_KR_STOPPED;
582         }
583         return 0;
584 }
585
586
587 /*
588  * The following are support routines used by individual drivers to
589  * support netmap operation.
590  *
591  * netmap_attach() initializes a struct netmap_adapter, allocating the
592  *      struct netmap_ring's and the struct selinfo.
593  *
594  * netmap_detach() frees the memory allocated by netmap_attach().
595  *
596  * netmap_transmit() replaces the if_transmit routine of the interface,
597  *      and is used to intercept packets coming from the stack.
598  *
599  * netmap_load_map/netmap_reload_map are helper routines to set/reset
600  *      the dmamap for a packet buffer
601  *
602  * netmap_reset() is a helper routine to be called in the driver
603  *      when reinitializing a ring.
604  */
605 int netmap_attach(struct netmap_adapter *);
606 int netmap_attach_common(struct netmap_adapter *);
607 void netmap_detach_common(struct netmap_adapter *na);
608 void netmap_detach(struct ifnet *);
609 int netmap_transmit(struct ifnet *, struct mbuf *);
610 struct netmap_slot *netmap_reset(struct netmap_adapter *na,
611         enum txrx tx, u_int n, u_int new_cur);
612 int netmap_ring_reinit(struct netmap_kring *);
613
614
615 /*
616  * Support routines to be used with the VALE switch
617  */
618 int netmap_update_config(struct netmap_adapter *na);
619 int netmap_krings_create(struct netmap_adapter *na, u_int ntx, u_int nrx, u_int tailroom);
620 void netmap_krings_delete(struct netmap_adapter *na);
621
622 struct netmap_if *
623 netmap_do_regif(struct netmap_priv_d *priv, struct netmap_adapter *na,
624         uint16_t ringid, int *err);
625
626
627
628 u_int nm_bound_var(u_int *v, u_int dflt, u_int lo, u_int hi, const char *msg);
629 int netmap_get_na(struct nmreq *nmr, struct netmap_adapter **na, int create);
630 int netmap_get_hw_na(struct ifnet *ifp, struct netmap_adapter **na);
631
632 #ifdef WITH_VALE
633 /*
634  * The following bridge-related interfaces are used by other kernel modules
635  * In the version that only supports unicast or broadcast, the lookup
636  * function can return 0 .. NM_BDG_MAXPORTS-1 for regular ports,
637  * NM_BDG_MAXPORTS for broadcast, NM_BDG_MAXPORTS+1 for unknown.
638  * XXX in practice "unknown" might be handled same as broadcast.
639  */
640 typedef u_int (*bdg_lookup_fn_t)(char *buf, u_int len,
641                 uint8_t *ring_nr, struct netmap_vp_adapter *);
642 u_int netmap_bdg_learning(char *, u_int, uint8_t *,
643                 struct netmap_vp_adapter *);
644
645 #define NM_BDG_MAXPORTS         254     /* up to 254 */
646 #define NM_BDG_BROADCAST        NM_BDG_MAXPORTS
647 #define NM_BDG_NOPORT           (NM_BDG_MAXPORTS+1)
648
649 #define NM_NAME                 "vale"  /* prefix for bridge port name */
650
651
652 /* these are redefined in case of no VALE support */
653 int netmap_get_bdg_na(struct nmreq *nmr, struct netmap_adapter **na, int create);
654 void netmap_init_bridges(void);
655 int netmap_bdg_ctl(struct nmreq *nmr, bdg_lookup_fn_t func);
656
657 #else /* !WITH_VALE */
658 #define netmap_get_bdg_na(_1, _2, _3)   0
659 #define netmap_init_bridges(_1)
660 #define netmap_bdg_ctl(_1, _2)  EINVAL
661 #endif /* !WITH_VALE */
662
663 /* Various prototypes */
664 int netmap_poll(struct cdev *dev, int events, struct thread *td);
665
666
667 int netmap_init(void);
668 void netmap_fini(void);
669 int netmap_get_memory(struct netmap_priv_d* p);
670 void netmap_dtor(void *data);
671 int netmap_dtor_locked(struct netmap_priv_d *priv);
672
673 int netmap_ioctl(struct cdev *dev, u_long cmd, caddr_t data, int fflag, struct thread *td);
674
675 /* netmap_adapter creation/destruction */
676 #define NM_IFPNAME(ifp) ((ifp) ? (ifp)->if_xname : "zombie")
677 #define NM_DEBUG_PUTGET 1
678
679 #ifdef NM_DEBUG_PUTGET
680
681 #define NM_DBG(f) __##f
682
683 void __netmap_adapter_get(struct netmap_adapter *na);
684
685 #define netmap_adapter_get(na)                          \
686         do {                                            \
687                 struct netmap_adapter *__na = na;       \
688                 D("getting %p:%s (%d)", __na, NM_IFPNAME(__na->ifp), __na->na_refcount);        \
689                 __netmap_adapter_get(__na);             \
690         } while (0)
691
692 int __netmap_adapter_put(struct netmap_adapter *na);
693
694 #define netmap_adapter_put(na)                          \
695         do {                                            \
696                 struct netmap_adapter *__na = na;       \
697                 D("putting %p:%s (%d)", __na, NM_IFPNAME(__na->ifp), __na->na_refcount);        \
698                 __netmap_adapter_put(__na);             \
699         } while (0)
700
701 #else /* !NM_DEBUG_PUTGET */
702
703 #define NM_DBG(f) f
704 void netmap_adapter_get(struct netmap_adapter *na);
705 int netmap_adapter_put(struct netmap_adapter *na);
706
707 #endif /* !NM_DEBUG_PUTGET */
708
709
710
711 extern u_int netmap_buf_size;
712 #define NETMAP_BUF_SIZE netmap_buf_size // XXX remove
713 extern int netmap_mitigate;
714 extern int netmap_no_pendintr;
715 extern u_int netmap_total_buffers;
716 extern char *netmap_buffer_base;
717 extern int netmap_verbose;      // XXX debugging
718 enum {                                  /* verbose flags */
719         NM_VERB_ON = 1,                 /* generic verbose */
720         NM_VERB_HOST = 0x2,             /* verbose host stack */
721         NM_VERB_RXSYNC = 0x10,          /* verbose on rxsync/txsync */
722         NM_VERB_TXSYNC = 0x20,
723         NM_VERB_RXINTR = 0x100,         /* verbose on rx/tx intr (driver) */
724         NM_VERB_TXINTR = 0x200,
725         NM_VERB_NIC_RXSYNC = 0x1000,    /* verbose on rx/tx intr (driver) */
726         NM_VERB_NIC_TXSYNC = 0x2000,
727 };
728
729 extern int netmap_txsync_retry;
730 extern int netmap_generic_mit;
731 extern int netmap_generic_ringsize;
732
733 /*
734  * NA returns a pointer to the struct netmap adapter from the ifp,
735  * WNA is used to write it.
736  */
737 #ifndef WNA
738 #define WNA(_ifp)       (_ifp)->if_unused7      /* XXX better name ;) */
739 #endif
740 #define NA(_ifp)        ((struct netmap_adapter *)WNA(_ifp))
741
742 /*
743  * Macros to determine if an interface is netmap capable or netmap enabled.
744  * See the magic field in struct netmap_adapter.
745  */
746 /*
747  * on FreeBSD just use if_capabilities and if_capenable.
748  */
749 #define NETMAP_CAPABLE(ifp)     (NA(ifp) &&             \
750         (ifp)->if_capabilities & IFCAP_NETMAP )
751
752 #define NETMAP_SET_CAPABLE(ifp)                         \
753         (ifp)->if_capabilities |= IFCAP_NETMAP
754
755 /* Callback invoked by the dma machinery after a successfull dmamap_load */
756 static void netmap_dmamap_cb(__unused void *arg,
757     __unused bus_dma_segment_t * segs, __unused int nseg, __unused int error)
758 {
759 }
760
761 /* bus_dmamap_load wrapper: call aforementioned function if map != NULL.
762  * XXX can we do it without a callback ?
763  */
764 static inline void
765 netmap_load_map(bus_dma_tag_t tag, bus_dmamap_t map, void *buf)
766 {
767         if (map)
768                 bus_dmamap_load(tag, map, buf, NETMAP_BUF_SIZE,
769                     netmap_dmamap_cb, NULL, BUS_DMA_NOWAIT);
770 }
771
772 /* update the map when a buffer changes. */
773 static inline void
774 netmap_reload_map(bus_dma_tag_t tag, bus_dmamap_t map, void *buf)
775 {
776         if (map) {
777                 bus_dmamap_unload(tag, map);
778                 bus_dmamap_load(tag, map, buf, NETMAP_BUF_SIZE,
779                     netmap_dmamap_cb, NULL, BUS_DMA_NOWAIT);
780         }
781 }
782
783 /*
784  * functions to map NIC to KRING indexes (n2k) and vice versa (k2n)
785  */
786 static inline int
787 netmap_idx_n2k(struct netmap_kring *kr, int idx)
788 {
789         int n = kr->nkr_num_slots;
790         idx += kr->nkr_hwofs;
791         if (idx < 0)
792                 return idx + n;
793         else if (idx < n)
794                 return idx;
795         else
796                 return idx - n;
797 }
798
799
800 static inline int
801 netmap_idx_k2n(struct netmap_kring *kr, int idx)
802 {
803         int n = kr->nkr_num_slots;
804         idx -= kr->nkr_hwofs;
805         if (idx < 0)
806                 return idx + n;
807         else if (idx < n)
808                 return idx;
809         else
810                 return idx - n;
811 }
812
813
814 /* Entries of the look-up table. */
815 struct lut_entry {
816         void *vaddr;            /* virtual address. */
817         vm_paddr_t paddr;       /* physical address. */
818 };
819
820 struct netmap_obj_pool;
821 extern struct lut_entry *netmap_buffer_lut;
822 #define NMB_VA(i)       (netmap_buffer_lut[i].vaddr)
823 #define NMB_PA(i)       (netmap_buffer_lut[i].paddr)
824
825 /*
826  * NMB return the virtual address of a buffer (buffer 0 on bad index)
827  * PNMB also fills the physical address
828  */
829 static inline void *
830 NMB(struct netmap_slot *slot)
831 {
832         uint32_t i = slot->buf_idx;
833         return (unlikely(i >= netmap_total_buffers)) ?  NMB_VA(0) : NMB_VA(i);
834 }
835
836 static inline void *
837 PNMB(struct netmap_slot *slot, uint64_t *pp)
838 {
839         uint32_t i = slot->buf_idx;
840         void *ret = (i >= netmap_total_buffers) ? NMB_VA(0) : NMB_VA(i);
841
842         *pp = (i >= netmap_total_buffers) ? NMB_PA(0) : NMB_PA(i);
843         return ret;
844 }
845
846 /* Generic version of NMB, which uses device-specific memory. */
847 static inline void *
848 BDG_NMB(struct netmap_adapter *na, struct netmap_slot *slot)
849 {
850         struct lut_entry *lut = na->na_lut;
851         uint32_t i = slot->buf_idx;
852         return (unlikely(i >= na->na_lut_objtotal)) ?
853                 lut[0].vaddr : lut[i].vaddr;
854 }
855
856 /* default functions to handle rx/tx interrupts */
857 int netmap_rx_irq(struct ifnet *, u_int, u_int *);
858 #define netmap_tx_irq(_n, _q) netmap_rx_irq(_n, _q, NULL)
859 int netmap_common_irq(struct ifnet *, u_int, u_int *work_done);
860
861
862 void netmap_txsync_to_host(struct netmap_adapter *na);
863 void netmap_disable_all_rings(struct ifnet *);
864 void netmap_enable_all_rings(struct ifnet *);
865 void netmap_disable_ring(struct netmap_kring *kr);
866
867
868 /* Structure associated to each thread which registered an interface.
869  *
870  * The first 4 fields of this structure are written by NIOCREGIF and
871  * read by poll() and NIOC?XSYNC.
872  * There is low contention among writers (actually, a correct user program
873  * should have no contention among writers) and among writers and readers,
874  * so we use a single global lock to protect the structure initialization.
875  * Since initialization involves the allocation of memory, we reuse the memory
876  * allocator lock.
877  * Read access to the structure is lock free. Readers must check that
878  * np_nifp is not NULL before using the other fields.
879  * If np_nifp is NULL initialization has not been performed, so they should
880  * return an error to userlevel.
881  *
882  * The ref_done field is used to regulate access to the refcount in the
883  * memory allocator. The refcount must be incremented at most once for
884  * each open("/dev/netmap"). The increment is performed by the first
885  * function that calls netmap_get_memory() (currently called by
886  * mmap(), NIOCGINFO and NIOCREGIF).
887  * If the refcount is incremented, it is then decremented when the
888  * private structure is destroyed.
889  */
890 struct netmap_priv_d {
891         struct netmap_if * volatile np_nifp;    /* netmap if descriptor. */
892
893         struct netmap_adapter   *np_na;
894         int                     np_ringid;      /* from the ioctl */
895         u_int                   np_qfirst, np_qlast;    /* range of rings to scan */
896         uint16_t                np_txpoll;
897
898         struct netmap_mem_d     *np_mref;       /* use with NMG_LOCK held */
899         /* np_refcount is only used on FreeBSD */
900         int                     np_refcount;    /* use with NMG_LOCK held */
901 };
902
903
904 /*
905  * generic netmap emulation for devices that do not have
906  * native netmap support.
907  * XXX generic_netmap_register() is only exported to implement
908  *      nma_is_generic().
909  */
910 int generic_netmap_register(struct netmap_adapter *na, int enable);
911 int generic_netmap_attach(struct ifnet *ifp);
912
913 int netmap_catch_rx(struct netmap_adapter *na, int intercept);
914 void generic_rx_handler(struct ifnet *ifp, struct mbuf *m);;
915 void netmap_catch_packet_steering(struct netmap_generic_adapter *na, int enable);
916 int generic_xmit_frame(struct ifnet *ifp, struct mbuf *m, void *addr, u_int len, u_int ring_nr);
917 int generic_find_num_desc(struct ifnet *ifp, u_int *tx, u_int *rx);
918 void generic_find_num_queues(struct ifnet *ifp, u_int *txq, u_int *rxq);
919
920 static __inline int
921 nma_is_generic(struct netmap_adapter *na)
922 {
923         return na->nm_register == generic_netmap_register;
924 }
925
926 /*
927  * netmap_mitigation API. This is used by the generic adapter
928  * to reduce the number of interrupt requests/selwakeup
929  * to clients on incoming packets.
930  */
931 void netmap_mitigation_init(struct netmap_generic_adapter *na);
932 void netmap_mitigation_start(struct netmap_generic_adapter *na);
933 void netmap_mitigation_restart(struct netmap_generic_adapter *na);
934 int netmap_mitigation_active(struct netmap_generic_adapter *na);
935 void netmap_mitigation_cleanup(struct netmap_generic_adapter *na);
936
937 // int generic_timer_handler(struct hrtimer *t);
938
939 #endif /* _NET_NETMAP_KERN_H_ */