]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/netmap/netmap_kern.h
Merge compiler-rt trunk r351319, and resolve conflicts.
[FreeBSD/FreeBSD.git] / sys / dev / netmap / netmap_kern.h
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (C) 2011-2014 Matteo Landi, Luigi Rizzo
5  * Copyright (C) 2013-2016 Universita` di Pisa
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *   1. Redistributions of source code must retain the above copyright
12  *      notice, this list of conditions and the following disclaimer.
13  *   2. Redistributions in binary form must reproduce the above copyright
14  *      notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29
30 /*
31  * $FreeBSD$
32  *
33  * The header contains the definitions of constants and function
34  * prototypes used only in kernelspace.
35  */
36
37 #ifndef _NET_NETMAP_KERN_H_
38 #define _NET_NETMAP_KERN_H_
39
40 #if defined(linux)
41
42 #if defined(CONFIG_NETMAP_EXTMEM)
43 #define WITH_EXTMEM
44 #endif
45 #if  defined(CONFIG_NETMAP_VALE)
46 #define WITH_VALE
47 #endif
48 #if defined(CONFIG_NETMAP_PIPE)
49 #define WITH_PIPES
50 #endif
51 #if defined(CONFIG_NETMAP_MONITOR)
52 #define WITH_MONITOR
53 #endif
54 #if defined(CONFIG_NETMAP_GENERIC)
55 #define WITH_GENERIC
56 #endif
57 #if defined(CONFIG_NETMAP_PTNETMAP)
58 #define WITH_PTNETMAP
59 #endif
60 #if defined(CONFIG_NETMAP_SINK)
61 #define WITH_SINK
62 #endif
63 #if defined(CONFIG_NETMAP_NULL)
64 #define WITH_NMNULL
65 #endif
66
67 #elif defined (_WIN32)
68 #define WITH_VALE       // comment out to disable VALE support
69 #define WITH_PIPES
70 #define WITH_MONITOR
71 #define WITH_GENERIC
72 #define WITH_NMNULL
73
74 #else   /* neither linux nor windows */
75 #define WITH_VALE       // comment out to disable VALE support
76 #define WITH_PIPES
77 #define WITH_MONITOR
78 #define WITH_GENERIC
79 #define WITH_PTNETMAP   /* ptnetmap guest support */
80 #define WITH_EXTMEM
81 #define WITH_NMNULL
82 #endif
83
84 #if defined(__FreeBSD__)
85 #include <sys/selinfo.h>
86
87 #define likely(x)       __builtin_expect((long)!!(x), 1L)
88 #define unlikely(x)     __builtin_expect((long)!!(x), 0L)
89 #define __user
90
91 #define NM_LOCK_T       struct mtx      /* low level spinlock, used to protect queues */
92
93 #define NM_MTX_T        struct sx       /* OS-specific mutex (sleepable) */
94 #define NM_MTX_INIT(m)          sx_init(&(m), #m)
95 #define NM_MTX_DESTROY(m)       sx_destroy(&(m))
96 #define NM_MTX_LOCK(m)          sx_xlock(&(m))
97 #define NM_MTX_SPINLOCK(m)      while (!sx_try_xlock(&(m))) ;
98 #define NM_MTX_UNLOCK(m)        sx_xunlock(&(m))
99 #define NM_MTX_ASSERT(m)        sx_assert(&(m), SA_XLOCKED)
100
101 #define NM_SELINFO_T    struct nm_selinfo
102 #define NM_SELRECORD_T  struct thread
103 #define MBUF_LEN(m)     ((m)->m_pkthdr.len)
104 #define MBUF_TXQ(m)     ((m)->m_pkthdr.flowid)
105 #define MBUF_TRANSMIT(na, ifp, m)       ((na)->if_transmit(ifp, m))
106 #define GEN_TX_MBUF_IFP(m)      ((m)->m_pkthdr.rcvif)
107
108 #define NM_ATOMIC_T     volatile int /* required by atomic/bitops.h */
109 /* atomic operations */
110 #include <machine/atomic.h>
111 #define NM_ATOMIC_TEST_AND_SET(p)       (!atomic_cmpset_acq_int((p), 0, 1))
112 #define NM_ATOMIC_CLEAR(p)              atomic_store_rel_int((p), 0)
113
114 #if __FreeBSD_version >= 1100030
115 #define WNA(_ifp)       (_ifp)->if_netmap
116 #else /* older FreeBSD */
117 #define WNA(_ifp)       (_ifp)->if_pspare[0]
118 #endif /* older FreeBSD */
119
120 #if __FreeBSD_version >= 1100005
121 struct netmap_adapter *netmap_getna(if_t ifp);
122 #endif
123
124 #if __FreeBSD_version >= 1100027
125 #define MBUF_REFCNT(m)          ((m)->m_ext.ext_count)
126 #define SET_MBUF_REFCNT(m, x)   (m)->m_ext.ext_count = x
127 #else
128 #define MBUF_REFCNT(m)          ((m)->m_ext.ref_cnt ? *((m)->m_ext.ref_cnt) : -1)
129 #define SET_MBUF_REFCNT(m, x)   *((m)->m_ext.ref_cnt) = x
130 #endif
131
132 #define MBUF_QUEUED(m)          1
133
134 struct nm_selinfo {
135         struct selinfo si;
136         struct mtx m;
137 };
138
139
140 struct hrtimer {
141     /* Not used in FreeBSD. */
142 };
143
144 #define NM_BNS_GET(b)
145 #define NM_BNS_PUT(b)
146
147 #elif defined (linux)
148
149 #define NM_LOCK_T       safe_spinlock_t // see bsd_glue.h
150 #define NM_SELINFO_T    wait_queue_head_t
151 #define MBUF_LEN(m)     ((m)->len)
152 #define MBUF_TRANSMIT(na, ifp, m)                                                       \
153         ({                                                                              \
154                 /* Avoid infinite recursion with generic. */                            \
155                 m->priority = NM_MAGIC_PRIORITY_TX;                                     \
156                 (((struct net_device_ops *)(na)->if_transmit)->ndo_start_xmit(m, ifp)); \
157                 0;                                                                      \
158         })
159
160 /* See explanation in nm_os_generic_xmit_frame. */
161 #define GEN_TX_MBUF_IFP(m)      ((struct ifnet *)skb_shinfo(m)->destructor_arg)
162
163 #define NM_ATOMIC_T     volatile long unsigned int
164
165 #define NM_MTX_T        struct mutex    /* OS-specific sleepable lock */
166 #define NM_MTX_INIT(m)  mutex_init(&(m))
167 #define NM_MTX_DESTROY(m)       do { (void)(m); } while (0)
168 #define NM_MTX_LOCK(m)          mutex_lock(&(m))
169 #define NM_MTX_UNLOCK(m)        mutex_unlock(&(m))
170 #define NM_MTX_ASSERT(m)        mutex_is_locked(&(m))
171
172 #ifndef DEV_NETMAP
173 #define DEV_NETMAP
174 #endif /* DEV_NETMAP */
175
176 #elif defined (__APPLE__)
177
178 #warning apple support is incomplete.
179 #define likely(x)       __builtin_expect(!!(x), 1)
180 #define unlikely(x)     __builtin_expect(!!(x), 0)
181 #define NM_LOCK_T       IOLock *
182 #define NM_SELINFO_T    struct selinfo
183 #define MBUF_LEN(m)     ((m)->m_pkthdr.len)
184
185 #elif defined (_WIN32)
186 #include "../../../WINDOWS/win_glue.h"
187
188 #define NM_SELRECORD_T          IO_STACK_LOCATION
189 #define NM_SELINFO_T            win_SELINFO             // see win_glue.h
190 #define NM_LOCK_T               win_spinlock_t  // see win_glue.h
191 #define NM_MTX_T                KGUARDED_MUTEX  /* OS-specific mutex (sleepable) */
192
193 #define NM_MTX_INIT(m)          KeInitializeGuardedMutex(&m);
194 #define NM_MTX_DESTROY(m)       do { (void)(m); } while (0)
195 #define NM_MTX_LOCK(m)          KeAcquireGuardedMutex(&(m))
196 #define NM_MTX_UNLOCK(m)        KeReleaseGuardedMutex(&(m))
197 #define NM_MTX_ASSERT(m)        assert(&m.Count>0)
198
199 //These linknames are for the NDIS driver
200 #define NETMAP_NDIS_LINKNAME_STRING             L"\\DosDevices\\NMAPNDIS"
201 #define NETMAP_NDIS_NTDEVICE_STRING             L"\\Device\\NMAPNDIS"
202
203 //Definition of internal driver-to-driver ioctl codes
204 #define NETMAP_KERNEL_XCHANGE_POINTERS          _IO('i', 180)
205 #define NETMAP_KERNEL_SEND_SHUTDOWN_SIGNAL      _IO_direct('i', 195)
206
207 typedef struct hrtimer{
208         KTIMER timer;
209         BOOLEAN active;
210         KDPC deferred_proc;
211 };
212
213 /* MSVC does not have likely/unlikely support */
214 #ifdef _MSC_VER
215 #define likely(x)       (x)
216 #define unlikely(x)     (x)
217 #else
218 #define likely(x)       __builtin_expect((long)!!(x), 1L)
219 #define unlikely(x)     __builtin_expect((long)!!(x), 0L)
220 #endif //_MSC_VER
221
222 #else
223
224 #error unsupported platform
225
226 #endif /* end - platform-specific code */
227
228 #ifndef _WIN32 /* support for emulated sysctl */
229 #define SYSBEGIN(x)
230 #define SYSEND
231 #endif /* _WIN32 */
232
233 #define NM_ACCESS_ONCE(x)       (*(volatile __typeof__(x) *)&(x))
234
235 #define NMG_LOCK_T              NM_MTX_T
236 #define NMG_LOCK_INIT()         NM_MTX_INIT(netmap_global_lock)
237 #define NMG_LOCK_DESTROY()      NM_MTX_DESTROY(netmap_global_lock)
238 #define NMG_LOCK()              NM_MTX_LOCK(netmap_global_lock)
239 #define NMG_UNLOCK()            NM_MTX_UNLOCK(netmap_global_lock)
240 #define NMG_LOCK_ASSERT()       NM_MTX_ASSERT(netmap_global_lock)
241
242 #if defined(__FreeBSD__)
243 #define nm_prerr_int    printf
244 #define nm_prinf_int    printf
245 #elif defined (_WIN32)
246 #define nm_prerr_int    DbgPrint
247 #define nm_prinf_int    DbgPrint
248 #elif defined(linux)
249 #define nm_prerr_int(fmt, arg...)    printk(KERN_ERR fmt, ##arg)
250 #define nm_prinf_int(fmt, arg...)    printk(KERN_INFO fmt, ##arg)
251 #endif
252
253 #define nm_prinf(format, ...)                                   \
254         do {                                                    \
255                 struct timeval __xxts;                          \
256                 microtime(&__xxts);                             \
257                 nm_prinf_int("%03d.%06d [%4d] %-25s " format "\n",\
258                 (int)__xxts.tv_sec % 1000, (int)__xxts.tv_usec, \
259                 __LINE__, __FUNCTION__, ##__VA_ARGS__);         \
260         } while (0)
261
262 #define nm_prerr(format, ...)                                   \
263         do {                                                    \
264                 struct timeval __xxts;                          \
265                 microtime(&__xxts);                             \
266                 nm_prerr_int("%03d.%06d [%4d] %-25s " format "\n",\
267                 (int)__xxts.tv_sec % 1000, (int)__xxts.tv_usec, \
268                 __LINE__, __FUNCTION__, ##__VA_ARGS__);         \
269         } while (0)
270
271 /* Disabled printf (used to be ND). */
272 #define nm_prdis(format, ...)
273
274 /* Rate limited, lps indicates how many per second. */
275 #define nm_prlim(lps, format, ...)                              \
276         do {                                                    \
277                 static int t0, __cnt;                           \
278                 if (t0 != time_second) {                        \
279                         t0 = time_second;                       \
280                         __cnt = 0;                              \
281                 }                                               \
282                 if (__cnt++ < lps)                              \
283                         nm_prinf(format, ##__VA_ARGS__);        \
284         } while (0)
285
286 /* Old macros. */
287 #define ND      nm_prdis
288 #define D       nm_prerr
289 #define RD      nm_prlim
290
291 struct netmap_adapter;
292 struct nm_bdg_fwd;
293 struct nm_bridge;
294 struct netmap_priv_d;
295 struct nm_bdg_args;
296
297 /* os-specific NM_SELINFO_T initialzation/destruction functions */
298 void nm_os_selinfo_init(NM_SELINFO_T *);
299 void nm_os_selinfo_uninit(NM_SELINFO_T *);
300
301 const char *nm_dump_buf(char *p, int len, int lim, char *dst);
302
303 void nm_os_selwakeup(NM_SELINFO_T *si);
304 void nm_os_selrecord(NM_SELRECORD_T *sr, NM_SELINFO_T *si);
305
306 int nm_os_ifnet_init(void);
307 void nm_os_ifnet_fini(void);
308 void nm_os_ifnet_lock(void);
309 void nm_os_ifnet_unlock(void);
310
311 unsigned nm_os_ifnet_mtu(struct ifnet *ifp);
312
313 void nm_os_get_module(void);
314 void nm_os_put_module(void);
315
316 void netmap_make_zombie(struct ifnet *);
317 void netmap_undo_zombie(struct ifnet *);
318
319 /* os independent alloc/realloc/free */
320 void *nm_os_malloc(size_t);
321 void *nm_os_vmalloc(size_t);
322 void *nm_os_realloc(void *, size_t new_size, size_t old_size);
323 void nm_os_free(void *);
324 void nm_os_vfree(void *);
325
326 /* os specific attach/detach enter/exit-netmap-mode routines */
327 void nm_os_onattach(struct ifnet *);
328 void nm_os_ondetach(struct ifnet *);
329 void nm_os_onenter(struct ifnet *);
330 void nm_os_onexit(struct ifnet *);
331
332 /* passes a packet up to the host stack.
333  * If the packet is sent (or dropped) immediately it returns NULL,
334  * otherwise it links the packet to prev and returns m.
335  * In this case, a final call with m=NULL and prev != NULL will send up
336  * the entire chain to the host stack.
337  */
338 void *nm_os_send_up(struct ifnet *, struct mbuf *m, struct mbuf *prev);
339
340 int nm_os_mbuf_has_seg_offld(struct mbuf *m);
341 int nm_os_mbuf_has_csum_offld(struct mbuf *m);
342
343 #include "netmap_mbq.h"
344
345 extern NMG_LOCK_T       netmap_global_lock;
346
347 enum txrx { NR_RX = 0, NR_TX = 1, NR_TXRX };
348
349 static __inline const char*
350 nm_txrx2str(enum txrx t)
351 {
352         return (t== NR_RX ? "RX" : "TX");
353 }
354
355 static __inline enum txrx
356 nm_txrx_swap(enum txrx t)
357 {
358         return (t== NR_RX ? NR_TX : NR_RX);
359 }
360
361 #define for_rx_tx(t)    for ((t) = 0; (t) < NR_TXRX; (t)++)
362
363 #ifdef WITH_MONITOR
364 struct netmap_zmon_list {
365         struct netmap_kring *next;
366         struct netmap_kring *prev;
367 };
368 #endif /* WITH_MONITOR */
369
370 /*
371  * private, kernel view of a ring. Keeps track of the status of
372  * a ring across system calls.
373  *
374  *      nr_hwcur        index of the next buffer to refill.
375  *                      It corresponds to ring->head
376  *                      at the time the system call returns.
377  *
378  *      nr_hwtail       index of the first buffer owned by the kernel.
379  *                      On RX, hwcur->hwtail are receive buffers
380  *                      not yet released. hwcur is advanced following
381  *                      ring->head, hwtail is advanced on incoming packets,
382  *                      and a wakeup is generated when hwtail passes ring->cur
383  *                          On TX, hwcur->rcur have been filled by the sender
384  *                      but not sent yet to the NIC; rcur->hwtail are available
385  *                      for new transmissions, and hwtail->hwcur-1 are pending
386  *                      transmissions not yet acknowledged.
387  *
388  * The indexes in the NIC and netmap rings are offset by nkr_hwofs slots.
389  * This is so that, on a reset, buffers owned by userspace are not
390  * modified by the kernel. In particular:
391  * RX rings: the next empty buffer (hwtail + hwofs) coincides with
392  *      the next empty buffer as known by the hardware (next_to_check or so).
393  * TX rings: hwcur + hwofs coincides with next_to_send
394  *
395  * The following fields are used to implement lock-free copy of packets
396  * from input to output ports in VALE switch:
397  *      nkr_hwlease     buffer after the last one being copied.
398  *                      A writer in nm_bdg_flush reserves N buffers
399  *                      from nr_hwlease, advances it, then does the
400  *                      copy outside the lock.
401  *                      In RX rings (used for VALE ports),
402  *                      nkr_hwtail <= nkr_hwlease < nkr_hwcur+N-1
403  *                      In TX rings (used for NIC or host stack ports)
404  *                      nkr_hwcur <= nkr_hwlease < nkr_hwtail
405  *      nkr_leases      array of nkr_num_slots where writers can report
406  *                      completion of their block. NR_NOSLOT (~0) indicates
407  *                      that the writer has not finished yet
408  *      nkr_lease_idx   index of next free slot in nr_leases, to be assigned
409  *
410  * The kring is manipulated by txsync/rxsync and generic netmap function.
411  *
412  * Concurrent rxsync or txsync on the same ring are prevented through
413  * by nm_kr_(try)lock() which in turn uses nr_busy. This is all we need
414  * for NIC rings, and for TX rings attached to the host stack.
415  *
416  * RX rings attached to the host stack use an mbq (rx_queue) on both
417  * rxsync_from_host() and netmap_transmit(). The mbq is protected
418  * by its internal lock.
419  *
420  * RX rings attached to the VALE switch are accessed by both senders
421  * and receiver. They are protected through the q_lock on the RX ring.
422  */
423 struct netmap_kring {
424         struct netmap_ring      *ring;
425
426         uint32_t        nr_hwcur;  /* should be nr_hwhead */
427         uint32_t        nr_hwtail;
428
429         /*
430          * Copies of values in user rings, so we do not need to look
431          * at the ring (which could be modified). These are set in the
432          * *sync_prologue()/finalize() routines.
433          */
434         uint32_t        rhead;
435         uint32_t        rcur;
436         uint32_t        rtail;
437
438         uint32_t        nr_kflags;      /* private driver flags */
439 #define NKR_PENDINTR    0x1             // Pending interrupt.
440 #define NKR_EXCLUSIVE   0x2             /* exclusive binding */
441 #define NKR_FORWARD     0x4             /* (host ring only) there are
442                                            packets to forward
443                                          */
444 #define NKR_NEEDRING    0x8             /* ring needed even if users==0
445                                          * (used internally by pipes and
446                                          *  by ptnetmap host ports)
447                                          */
448 #define NKR_NOINTR      0x10            /* don't use interrupts on this ring */
449 #define NKR_FAKERING    0x20            /* don't allocate/free buffers */
450
451         uint32_t        nr_mode;
452         uint32_t        nr_pending_mode;
453 #define NKR_NETMAP_OFF  0x0
454 #define NKR_NETMAP_ON   0x1
455
456         uint32_t        nkr_num_slots;
457
458         /*
459          * On a NIC reset, the NIC ring indexes may be reset but the
460          * indexes in the netmap rings remain the same. nkr_hwofs
461          * keeps track of the offset between the two.
462          */
463         int32_t         nkr_hwofs;
464
465         /* last_reclaim is opaque marker to help reduce the frequency
466          * of operations such as reclaiming tx buffers. A possible use
467          * is set it to ticks and do the reclaim only once per tick.
468          */
469         uint64_t        last_reclaim;
470
471
472         NM_SELINFO_T    si;             /* poll/select wait queue */
473         NM_LOCK_T       q_lock;         /* protects kring and ring. */
474         NM_ATOMIC_T     nr_busy;        /* prevent concurrent syscalls */
475
476         /* the adapter the owns this kring */
477         struct netmap_adapter *na;
478
479         /* the adapter that wants to be notified when this kring has
480          * new slots avaialable. This is usually the same as the above,
481          * but wrappers may let it point to themselves
482          */
483         struct netmap_adapter *notify_na;
484
485         /* The following fields are for VALE switch support */
486         struct nm_bdg_fwd *nkr_ft;
487         uint32_t        *nkr_leases;
488 #define NR_NOSLOT       ((uint32_t)~0)  /* used in nkr_*lease* */
489         uint32_t        nkr_hwlease;
490         uint32_t        nkr_lease_idx;
491
492         /* while nkr_stopped is set, no new [tr]xsync operations can
493          * be started on this kring.
494          * This is used by netmap_disable_all_rings()
495          * to find a synchronization point where critical data
496          * structures pointed to by the kring can be added or removed
497          */
498         volatile int nkr_stopped;
499
500         /* Support for adapters without native netmap support.
501          * On tx rings we preallocate an array of tx buffers
502          * (same size as the netmap ring), on rx rings we
503          * store incoming mbufs in a queue that is drained by
504          * a rxsync.
505          */
506         struct mbuf     **tx_pool;
507         struct mbuf     *tx_event;      /* TX event used as a notification */
508         NM_LOCK_T       tx_event_lock;  /* protects the tx_event mbuf */
509         struct mbq      rx_queue;       /* intercepted rx mbufs. */
510
511         uint32_t        users;          /* existing bindings for this ring */
512
513         uint32_t        ring_id;        /* kring identifier */
514         enum txrx       tx;             /* kind of ring (tx or rx) */
515         char name[64];                  /* diagnostic */
516
517         /* [tx]sync callback for this kring.
518          * The default nm_kring_create callback (netmap_krings_create)
519          * sets the nm_sync callback of each hardware tx(rx) kring to
520          * the corresponding nm_txsync(nm_rxsync) taken from the
521          * netmap_adapter; moreover, it sets the sync callback
522          * of the host tx(rx) ring to netmap_txsync_to_host
523          * (netmap_rxsync_from_host).
524          *
525          * Overrides: the above configuration is not changed by
526          * any of the nm_krings_create callbacks.
527          */
528         int (*nm_sync)(struct netmap_kring *kring, int flags);
529         int (*nm_notify)(struct netmap_kring *kring, int flags);
530
531 #ifdef WITH_PIPES
532         struct netmap_kring *pipe;      /* if this is a pipe ring,
533                                          * pointer to the other end
534                                          */
535         uint32_t pipe_tail;             /* hwtail updated by the other end */
536 #endif /* WITH_PIPES */
537
538         int (*save_notify)(struct netmap_kring *kring, int flags);
539
540 #ifdef WITH_MONITOR
541         /* array of krings that are monitoring this kring */
542         struct netmap_kring **monitors;
543         uint32_t max_monitors; /* current size of the monitors array */
544         uint32_t n_monitors;    /* next unused entry in the monitor array */
545         uint32_t mon_pos[NR_TXRX]; /* index of this ring in the monitored ring array */
546         uint32_t mon_tail;  /* last seen slot on rx */
547
548         /* circular list of zero-copy monitors */
549         struct netmap_zmon_list zmon_list[NR_TXRX];
550
551         /*
552          * Monitors work by intercepting the sync and notify callbacks of the
553          * monitored krings. This is implemented by replacing the pointers
554          * above and saving the previous ones in mon_* pointers below
555          */
556         int (*mon_sync)(struct netmap_kring *kring, int flags);
557         int (*mon_notify)(struct netmap_kring *kring, int flags);
558
559 #endif
560 }
561 #ifdef _WIN32
562 __declspec(align(64));
563 #else
564 __attribute__((__aligned__(64)));
565 #endif
566
567 /* return 1 iff the kring needs to be turned on */
568 static inline int
569 nm_kring_pending_on(struct netmap_kring *kring)
570 {
571         return kring->nr_pending_mode == NKR_NETMAP_ON &&
572                kring->nr_mode == NKR_NETMAP_OFF;
573 }
574
575 /* return 1 iff the kring needs to be turned off */
576 static inline int
577 nm_kring_pending_off(struct netmap_kring *kring)
578 {
579         return kring->nr_pending_mode == NKR_NETMAP_OFF &&
580                kring->nr_mode == NKR_NETMAP_ON;
581 }
582
583 /* return the next index, with wraparound */
584 static inline uint32_t
585 nm_next(uint32_t i, uint32_t lim)
586 {
587         return unlikely (i == lim) ? 0 : i + 1;
588 }
589
590
591 /* return the previous index, with wraparound */
592 static inline uint32_t
593 nm_prev(uint32_t i, uint32_t lim)
594 {
595         return unlikely (i == 0) ? lim : i - 1;
596 }
597
598
599 /*
600  *
601  * Here is the layout for the Rx and Tx rings.
602
603        RxRING                            TxRING
604
605       +-----------------+            +-----------------+
606       |                 |            |                 |
607       |      free       |            |      free       |
608       +-----------------+            +-----------------+
609 head->| owned by user   |<-hwcur     | not sent to nic |<-hwcur
610       |                 |            | yet             |
611       +-----------------+            |                 |
612  cur->| available to    |            |                 |
613       | user, not read  |            +-----------------+
614       | yet             |       cur->| (being          |
615       |                 |            |  prepared)      |
616       |                 |            |                 |
617       +-----------------+            +     ------      +
618 tail->|                 |<-hwtail    |                 |<-hwlease
619       | (being          | ...        |                 | ...
620       |  prepared)      | ...        |                 | ...
621       +-----------------+ ...        |                 | ...
622       |                 |<-hwlease   +-----------------+
623       |                 |      tail->|                 |<-hwtail
624       |                 |            |                 |
625       |                 |            |                 |
626       |                 |            |                 |
627       +-----------------+            +-----------------+
628
629  * The cur/tail (user view) and hwcur/hwtail (kernel view)
630  * are used in the normal operation of the card.
631  *
632  * When a ring is the output of a switch port (Rx ring for
633  * a VALE port, Tx ring for the host stack or NIC), slots
634  * are reserved in blocks through 'hwlease' which points
635  * to the next unused slot.
636  * On an Rx ring, hwlease is always after hwtail,
637  * and completions cause hwtail to advance.
638  * On a Tx ring, hwlease is always between cur and hwtail,
639  * and completions cause cur to advance.
640  *
641  * nm_kr_space() returns the maximum number of slots that
642  * can be assigned.
643  * nm_kr_lease() reserves the required number of buffers,
644  *    advances nkr_hwlease and also returns an entry in
645  *    a circular array where completions should be reported.
646  */
647
648 struct lut_entry;
649 #ifdef __FreeBSD__
650 #define plut_entry lut_entry
651 #endif
652
653 struct netmap_lut {
654         struct lut_entry *lut;
655         struct plut_entry *plut;
656         uint32_t objtotal;      /* max buffer index */
657         uint32_t objsize;       /* buffer size */
658 };
659
660 struct netmap_vp_adapter; // forward
661 struct nm_bridge;
662
663 /* Struct to be filled by nm_config callbacks. */
664 struct nm_config_info {
665         unsigned num_tx_rings;
666         unsigned num_rx_rings;
667         unsigned num_tx_descs;
668         unsigned num_rx_descs;
669         unsigned rx_buf_maxsize;
670 };
671
672 /*
673  * default type for the magic field.
674  * May be overriden in glue code.
675  */
676 #ifndef NM_OS_MAGIC
677 #define NM_OS_MAGIC uint32_t
678 #endif /* !NM_OS_MAGIC */
679
680 /*
681  * The "struct netmap_adapter" extends the "struct adapter"
682  * (or equivalent) device descriptor.
683  * It contains all base fields needed to support netmap operation.
684  * There are in fact different types of netmap adapters
685  * (native, generic, VALE switch...) so a netmap_adapter is
686  * just the first field in the derived type.
687  */
688 struct netmap_adapter {
689         /*
690          * On linux we do not have a good way to tell if an interface
691          * is netmap-capable. So we always use the following trick:
692          * NA(ifp) points here, and the first entry (which hopefully
693          * always exists and is at least 32 bits) contains a magic
694          * value which we can use to detect that the interface is good.
695          */
696         NM_OS_MAGIC magic;
697         uint32_t na_flags;      /* enabled, and other flags */
698 #define NAF_SKIP_INTR   1       /* use the regular interrupt handler.
699                                  * useful during initialization
700                                  */
701 #define NAF_SW_ONLY     2       /* forward packets only to sw adapter */
702 #define NAF_BDG_MAYSLEEP 4      /* the bridge is allowed to sleep when
703                                  * forwarding packets coming from this
704                                  * interface
705                                  */
706 #define NAF_MEM_OWNER   8       /* the adapter uses its own memory area
707                                  * that cannot be changed
708                                  */
709 #define NAF_NATIVE      16      /* the adapter is native.
710                                  * Virtual ports (non persistent vale ports,
711                                  * pipes, monitors...) should never use
712                                  * this flag.
713                                  */
714 #define NAF_NETMAP_ON   32      /* netmap is active (either native or
715                                  * emulated). Where possible (e.g. FreeBSD)
716                                  * IFCAP_NETMAP also mirrors this flag.
717                                  */
718 #define NAF_HOST_RINGS  64      /* the adapter supports the host rings */
719 #define NAF_FORCE_NATIVE 128    /* the adapter is always NATIVE */
720 /* free */
721 #define NAF_MOREFRAG    512     /* the adapter supports NS_MOREFRAG */
722 #define NAF_ZOMBIE      (1U<<30) /* the nic driver has been unloaded */
723 #define NAF_BUSY        (1U<<31) /* the adapter is used internally and
724                                   * cannot be registered from userspace
725                                   */
726         int active_fds; /* number of user-space descriptors using this
727                          interface, which is equal to the number of
728                          struct netmap_if objs in the mapped region. */
729
730         u_int num_rx_rings; /* number of adapter receive rings */
731         u_int num_tx_rings; /* number of adapter transmit rings */
732         u_int num_host_rx_rings; /* number of host receive rings */
733         u_int num_host_tx_rings; /* number of host transmit rings */
734
735         u_int num_tx_desc;  /* number of descriptor in each queue */
736         u_int num_rx_desc;
737
738         /* tx_rings and rx_rings are private but allocated as a
739          * contiguous chunk of memory. Each array has N+K entries,
740          * N for the hardware rings and K for the host rings.
741          */
742         struct netmap_kring **tx_rings; /* array of TX rings. */
743         struct netmap_kring **rx_rings; /* array of RX rings. */
744
745         void *tailroom;                /* space below the rings array */
746                                        /* (used for leases) */
747
748
749         NM_SELINFO_T si[NR_TXRX];       /* global wait queues */
750
751         /* count users of the global wait queues */
752         int si_users[NR_TXRX];
753
754         void *pdev; /* used to store pci device */
755
756         /* copy of if_qflush and if_transmit pointers, to intercept
757          * packets from the network stack when netmap is active.
758          */
759         int     (*if_transmit)(struct ifnet *, struct mbuf *);
760
761         /* copy of if_input for netmap_send_up() */
762         void     (*if_input)(struct ifnet *, struct mbuf *);
763
764         /* Back reference to the parent ifnet struct. Used for
765          * hardware ports (emulated netmap included). */
766         struct ifnet *ifp; /* adapter is ifp->if_softc */
767
768         /*---- callbacks for this netmap adapter -----*/
769         /*
770          * nm_dtor() is the cleanup routine called when destroying
771          *      the adapter.
772          *      Called with NMG_LOCK held.
773          *
774          * nm_register() is called on NIOCREGIF and close() to enter
775          *      or exit netmap mode on the NIC
776          *      Called with NNG_LOCK held.
777          *
778          * nm_txsync() pushes packets to the underlying hw/switch
779          *
780          * nm_rxsync() collects packets from the underlying hw/switch
781          *
782          * nm_config() returns configuration information from the OS
783          *      Called with NMG_LOCK held.
784          *
785          * nm_krings_create() create and init the tx_rings and
786          *      rx_rings arrays of kring structures. In particular,
787          *      set the nm_sync callbacks for each ring.
788          *      There is no need to also allocate the corresponding
789          *      netmap_rings, since netmap_mem_rings_create() will always
790          *      be called to provide the missing ones.
791          *      Called with NNG_LOCK held.
792          *
793          * nm_krings_delete() cleanup and delete the tx_rings and rx_rings
794          *      arrays
795          *      Called with NMG_LOCK held.
796          *
797          * nm_notify() is used to act after data have become available
798          *      (or the stopped state of the ring has changed)
799          *      For hw devices this is typically a selwakeup(),
800          *      but for NIC/host ports attached to a switch (or vice-versa)
801          *      we also need to invoke the 'txsync' code downstream.
802          *      This callback pointer is actually used only to initialize
803          *      kring->nm_notify.
804          *      Return values are the same as for netmap_rx_irq().
805          */
806         void (*nm_dtor)(struct netmap_adapter *);
807
808         int (*nm_register)(struct netmap_adapter *, int onoff);
809         void (*nm_intr)(struct netmap_adapter *, int onoff);
810
811         int (*nm_txsync)(struct netmap_kring *kring, int flags);
812         int (*nm_rxsync)(struct netmap_kring *kring, int flags);
813         int (*nm_notify)(struct netmap_kring *kring, int flags);
814 #define NAF_FORCE_READ      1
815 #define NAF_FORCE_RECLAIM   2
816 #define NAF_CAN_FORWARD_DOWN 4
817         /* return configuration information */
818         int (*nm_config)(struct netmap_adapter *, struct nm_config_info *info);
819         int (*nm_krings_create)(struct netmap_adapter *);
820         void (*nm_krings_delete)(struct netmap_adapter *);
821         /*
822          * nm_bdg_attach() initializes the na_vp field to point
823          *      to an adapter that can be attached to a VALE switch. If the
824          *      current adapter is already a VALE port, na_vp is simply a cast;
825          *      otherwise, na_vp points to a netmap_bwrap_adapter.
826          *      If applicable, this callback also initializes na_hostvp,
827          *      that can be used to connect the adapter host rings to the
828          *      switch.
829          *      Called with NMG_LOCK held.
830          *
831          * nm_bdg_ctl() is called on the actual attach/detach to/from
832          *      to/from the switch, to perform adapter-specific
833          *      initializations
834          *      Called with NMG_LOCK held.
835          */
836         int (*nm_bdg_attach)(const char *bdg_name, struct netmap_adapter *,
837                         struct nm_bridge *);
838         int (*nm_bdg_ctl)(struct nmreq_header *, struct netmap_adapter *);
839
840         /* adapter used to attach this adapter to a VALE switch (if any) */
841         struct netmap_vp_adapter *na_vp;
842         /* adapter used to attach the host rings of this adapter
843          * to a VALE switch (if any) */
844         struct netmap_vp_adapter *na_hostvp;
845
846         /* standard refcount to control the lifetime of the adapter
847          * (it should be equal to the lifetime of the corresponding ifp)
848          */
849         int na_refcount;
850
851         /* memory allocator (opaque)
852          * We also cache a pointer to the lut_entry for translating
853          * buffer addresses, the total number of buffers and the buffer size.
854          */
855         struct netmap_mem_d *nm_mem;
856         struct netmap_mem_d *nm_mem_prev;
857         struct netmap_lut na_lut;
858
859         /* additional information attached to this adapter
860          * by other netmap subsystems. Currently used by
861          * bwrap, LINUX/v1000 and ptnetmap
862          */
863         void *na_private;
864
865         /* array of pipes that have this adapter as a parent */
866         struct netmap_pipe_adapter **na_pipes;
867         int na_next_pipe;       /* next free slot in the array */
868         int na_max_pipes;       /* size of the array */
869
870         /* Offset of ethernet header for each packet. */
871         u_int virt_hdr_len;
872
873         /* Max number of bytes that the NIC can store in the buffer
874          * referenced by each RX descriptor. This translates to the maximum
875          * bytes that a single netmap slot can reference. Larger packets
876          * require NS_MOREFRAG support. */
877         unsigned rx_buf_maxsize;
878
879         char name[NETMAP_REQ_IFNAMSIZ]; /* used at least by pipes */
880
881 #ifdef WITH_MONITOR
882         unsigned long   monitor_id;     /* debugging */
883 #endif
884 };
885
886 static __inline u_int
887 nma_get_ndesc(struct netmap_adapter *na, enum txrx t)
888 {
889         return (t == NR_TX ? na->num_tx_desc : na->num_rx_desc);
890 }
891
892 static __inline void
893 nma_set_ndesc(struct netmap_adapter *na, enum txrx t, u_int v)
894 {
895         if (t == NR_TX)
896                 na->num_tx_desc = v;
897         else
898                 na->num_rx_desc = v;
899 }
900
901 static __inline u_int
902 nma_get_nrings(struct netmap_adapter *na, enum txrx t)
903 {
904         return (t == NR_TX ? na->num_tx_rings : na->num_rx_rings);
905 }
906
907 static __inline u_int
908 nma_get_host_nrings(struct netmap_adapter *na, enum txrx t)
909 {
910         return (t == NR_TX ? na->num_host_tx_rings : na->num_host_rx_rings);
911 }
912
913 static __inline void
914 nma_set_nrings(struct netmap_adapter *na, enum txrx t, u_int v)
915 {
916         if (t == NR_TX)
917                 na->num_tx_rings = v;
918         else
919                 na->num_rx_rings = v;
920 }
921
922 static __inline void
923 nma_set_host_nrings(struct netmap_adapter *na, enum txrx t, u_int v)
924 {
925         if (t == NR_TX)
926                 na->num_host_tx_rings = v;
927         else
928                 na->num_host_rx_rings = v;
929 }
930
931 static __inline struct netmap_kring**
932 NMR(struct netmap_adapter *na, enum txrx t)
933 {
934         return (t == NR_TX ? na->tx_rings : na->rx_rings);
935 }
936
937 int nma_intr_enable(struct netmap_adapter *na, int onoff);
938
939 /*
940  * If the NIC is owned by the kernel
941  * (i.e., bridge), neither another bridge nor user can use it;
942  * if the NIC is owned by a user, only users can share it.
943  * Evaluation must be done under NMG_LOCK().
944  */
945 #define NETMAP_OWNED_BY_KERN(na)        ((na)->na_flags & NAF_BUSY)
946 #define NETMAP_OWNED_BY_ANY(na) \
947         (NETMAP_OWNED_BY_KERN(na) || ((na)->active_fds > 0))
948
949 /*
950  * derived netmap adapters for various types of ports
951  */
952 struct netmap_vp_adapter {      /* VALE software port */
953         struct netmap_adapter up;
954
955         /*
956          * Bridge support:
957          *
958          * bdg_port is the port number used in the bridge;
959          * na_bdg points to the bridge this NA is attached to.
960          */
961         int bdg_port;
962         struct nm_bridge *na_bdg;
963         int retry;
964         int autodelete; /* remove the ifp on last reference */
965
966         /* Maximum Frame Size, used in bdg_mismatch_datapath() */
967         u_int mfs;
968         /* Last source MAC on this port */
969         uint64_t last_smac;
970 };
971
972
973 struct netmap_hw_adapter {      /* physical device */
974         struct netmap_adapter up;
975
976 #ifdef linux
977         struct net_device_ops nm_ndo;
978         struct ethtool_ops    nm_eto;
979 #endif
980         const struct ethtool_ops*   save_ethtool;
981
982         int (*nm_hw_register)(struct netmap_adapter *, int onoff);
983 };
984
985 #ifdef WITH_GENERIC
986 /* Mitigation support. */
987 struct nm_generic_mit {
988         struct hrtimer mit_timer;
989         int mit_pending;
990         int mit_ring_idx;  /* index of the ring being mitigated */
991         struct netmap_adapter *mit_na;  /* backpointer */
992 };
993
994 struct netmap_generic_adapter { /* emulated device */
995         struct netmap_hw_adapter up;
996
997         /* Pointer to a previously used netmap adapter. */
998         struct netmap_adapter *prev;
999
1000         /* Emulated netmap adapters support:
1001          *  - save_if_input saves the if_input hook (FreeBSD);
1002          *  - mit implements rx interrupt mitigation;
1003          */
1004         void (*save_if_input)(struct ifnet *, struct mbuf *);
1005
1006         struct nm_generic_mit *mit;
1007 #ifdef linux
1008         netdev_tx_t (*save_start_xmit)(struct mbuf *, struct ifnet *);
1009 #endif
1010         /* Is the adapter able to use multiple RX slots to scatter
1011          * each packet pushed up by the driver? */
1012         int rxsg;
1013
1014         /* Is the transmission path controlled by a netmap-aware
1015          * device queue (i.e. qdisc on linux)? */
1016         int txqdisc;
1017 };
1018 #endif  /* WITH_GENERIC */
1019
1020 static __inline u_int
1021 netmap_real_rings(struct netmap_adapter *na, enum txrx t)
1022 {
1023         return nma_get_nrings(na, t) +
1024                 !!(na->na_flags & NAF_HOST_RINGS) * nma_get_host_nrings(na, t);
1025 }
1026
1027 /* account for fake rings */
1028 static __inline u_int
1029 netmap_all_rings(struct netmap_adapter *na, enum txrx t)
1030 {
1031         return max(nma_get_nrings(na, t) + 1, netmap_real_rings(na, t));
1032 }
1033
1034 int netmap_default_bdg_attach(const char *name, struct netmap_adapter *na,
1035                 struct nm_bridge *);
1036 struct nm_bdg_polling_state;
1037 /*
1038  * Bridge wrapper for non VALE ports attached to a VALE switch.
1039  *
1040  * The real device must already have its own netmap adapter (hwna).
1041  * The bridge wrapper and the hwna adapter share the same set of
1042  * netmap rings and buffers, but they have two separate sets of
1043  * krings descriptors, with tx/rx meanings swapped:
1044  *
1045  *                                  netmap
1046  *           bwrap     krings       rings      krings      hwna
1047  *         +------+   +------+     +-----+    +------+   +------+
1048  *         |tx_rings->|      |\   /|     |----|      |<-tx_rings|
1049  *         |      |   +------+ \ / +-----+    +------+   |      |
1050  *         |      |             X                        |      |
1051  *         |      |            / \                       |      |
1052  *         |      |   +------+/   \+-----+    +------+   |      |
1053  *         |rx_rings->|      |     |     |----|      |<-rx_rings|
1054  *         |      |   +------+     +-----+    +------+   |      |
1055  *         +------+                                      +------+
1056  *
1057  * - packets coming from the bridge go to the brwap rx rings,
1058  *   which are also the hwna tx rings.  The bwrap notify callback
1059  *   will then complete the hwna tx (see netmap_bwrap_notify).
1060  *
1061  * - packets coming from the outside go to the hwna rx rings,
1062  *   which are also the bwrap tx rings.  The (overwritten) hwna
1063  *   notify method will then complete the bridge tx
1064  *   (see netmap_bwrap_intr_notify).
1065  *
1066  *   The bridge wrapper may optionally connect the hwna 'host' rings
1067  *   to the bridge. This is done by using a second port in the
1068  *   bridge and connecting it to the 'host' netmap_vp_adapter
1069  *   contained in the netmap_bwrap_adapter. The brwap host adapter
1070  *   cross-links the hwna host rings in the same way as shown above.
1071  *
1072  * - packets coming from the bridge and directed to the host stack
1073  *   are handled by the bwrap host notify callback
1074  *   (see netmap_bwrap_host_notify)
1075  *
1076  * - packets coming from the host stack are still handled by the
1077  *   overwritten hwna notify callback (netmap_bwrap_intr_notify),
1078  *   but are diverted to the host adapter depending on the ring number.
1079  *
1080  */
1081 struct netmap_bwrap_adapter {
1082         struct netmap_vp_adapter up;
1083         struct netmap_vp_adapter host;  /* for host rings */
1084         struct netmap_adapter *hwna;    /* the underlying device */
1085
1086         /*
1087          * When we attach a physical interface to the bridge, we
1088          * allow the controlling process to terminate, so we need
1089          * a place to store the n_detmap_priv_d data structure.
1090          * This is only done when physical interfaces
1091          * are attached to a bridge.
1092          */
1093         struct netmap_priv_d *na_kpriv;
1094         struct nm_bdg_polling_state *na_polling_state;
1095         /* we overwrite the hwna->na_vp pointer, so we save
1096          * here its original value, to be restored at detach
1097          */
1098         struct netmap_vp_adapter *saved_na_vp;
1099 };
1100 int nm_bdg_polling(struct nmreq_header *hdr);
1101
1102 #ifdef WITH_VALE
1103 int netmap_vale_attach(struct nmreq_header *hdr, void *auth_token);
1104 int netmap_vale_detach(struct nmreq_header *hdr, void *auth_token);
1105 int netmap_vale_list(struct nmreq_header *hdr);
1106 int netmap_vi_create(struct nmreq_header *hdr, int);
1107 int nm_vi_create(struct nmreq_header *);
1108 int nm_vi_destroy(const char *name);
1109 #else /* !WITH_VALE */
1110 #define netmap_vi_create(hdr, a) (EOPNOTSUPP)
1111 #endif /* WITH_VALE */
1112
1113 #ifdef WITH_PIPES
1114
1115 #define NM_MAXPIPES     64      /* max number of pipes per adapter */
1116
1117 struct netmap_pipe_adapter {
1118         /* pipe identifier is up.name */
1119         struct netmap_adapter up;
1120
1121 #define NM_PIPE_ROLE_MASTER     0x1
1122 #define NM_PIPE_ROLE_SLAVE      0x2
1123         int role;       /* either NM_PIPE_ROLE_MASTER or NM_PIPE_ROLE_SLAVE */
1124
1125         struct netmap_adapter *parent; /* adapter that owns the memory */
1126         struct netmap_pipe_adapter *peer; /* the other end of the pipe */
1127         int peer_ref;           /* 1 iff we are holding a ref to the peer */
1128         struct ifnet *parent_ifp;       /* maybe null */
1129
1130         u_int parent_slot; /* index in the parent pipe array */
1131 };
1132
1133 #endif /* WITH_PIPES */
1134
1135 #ifdef WITH_NMNULL
1136 struct netmap_null_adapter {
1137         struct netmap_adapter up;
1138 };
1139 #endif /* WITH_NMNULL */
1140
1141
1142 /* return slots reserved to rx clients; used in drivers */
1143 static inline uint32_t
1144 nm_kr_rxspace(struct netmap_kring *k)
1145 {
1146         int space = k->nr_hwtail - k->nr_hwcur;
1147         if (space < 0)
1148                 space += k->nkr_num_slots;
1149         ND("preserving %d rx slots %d -> %d", space, k->nr_hwcur, k->nr_hwtail);
1150
1151         return space;
1152 }
1153
1154 /* return slots reserved to tx clients */
1155 #define nm_kr_txspace(_k) nm_kr_rxspace(_k)
1156
1157
1158 /* True if no space in the tx ring, only valid after txsync_prologue */
1159 static inline int
1160 nm_kr_txempty(struct netmap_kring *kring)
1161 {
1162         return kring->rcur == kring->nr_hwtail;
1163 }
1164
1165 /* True if no more completed slots in the rx ring, only valid after
1166  * rxsync_prologue */
1167 #define nm_kr_rxempty(_k)       nm_kr_txempty(_k)
1168
1169 /*
1170  * protect against multiple threads using the same ring.
1171  * also check that the ring has not been stopped or locked
1172  */
1173 #define NM_KR_BUSY      1       /* some other thread is syncing the ring */
1174 #define NM_KR_STOPPED   2       /* unbounded stop (ifconfig down or driver unload) */
1175 #define NM_KR_LOCKED    3       /* bounded, brief stop for mutual exclusion */
1176
1177
1178 /* release the previously acquired right to use the *sync() methods of the ring */
1179 static __inline void nm_kr_put(struct netmap_kring *kr)
1180 {
1181         NM_ATOMIC_CLEAR(&kr->nr_busy);
1182 }
1183
1184
1185 /* true if the ifp that backed the adapter has disappeared (e.g., the
1186  * driver has been unloaded)
1187  */
1188 static inline int nm_iszombie(struct netmap_adapter *na);
1189
1190 /* try to obtain exclusive right to issue the *sync() operations on the ring.
1191  * The right is obtained and must be later relinquished via nm_kr_put() if and
1192  * only if nm_kr_tryget() returns 0.
1193  * If can_sleep is 1 there are only two other possible outcomes:
1194  * - the function returns NM_KR_BUSY
1195  * - the function returns NM_KR_STOPPED and sets the POLLERR bit in *perr
1196  *   (if non-null)
1197  * In both cases the caller will typically skip the ring, possibly collecting
1198  * errors along the way.
1199  * If the calling context does not allow sleeping, the caller must pass 0 in can_sleep.
1200  * In the latter case, the function may also return NM_KR_LOCKED and leave *perr
1201  * untouched: ideally, the caller should try again at a later time.
1202  */
1203 static __inline int nm_kr_tryget(struct netmap_kring *kr, int can_sleep, int *perr)
1204 {
1205         int busy = 1, stopped;
1206         /* check a first time without taking the lock
1207          * to avoid starvation for nm_kr_get()
1208          */
1209 retry:
1210         stopped = kr->nkr_stopped;
1211         if (unlikely(stopped)) {
1212                 goto stop;
1213         }
1214         busy = NM_ATOMIC_TEST_AND_SET(&kr->nr_busy);
1215         /* we should not return NM_KR_BUSY if the ring was
1216          * actually stopped, so check another time after
1217          * the barrier provided by the atomic operation
1218          */
1219         stopped = kr->nkr_stopped;
1220         if (unlikely(stopped)) {
1221                 goto stop;
1222         }
1223
1224         if (unlikely(nm_iszombie(kr->na))) {
1225                 stopped = NM_KR_STOPPED;
1226                 goto stop;
1227         }
1228
1229         return unlikely(busy) ? NM_KR_BUSY : 0;
1230
1231 stop:
1232         if (!busy)
1233                 nm_kr_put(kr);
1234         if (stopped == NM_KR_STOPPED) {
1235 /* if POLLERR is defined we want to use it to simplify netmap_poll().
1236  * Otherwise, any non-zero value will do.
1237  */
1238 #ifdef POLLERR
1239 #define NM_POLLERR POLLERR
1240 #else
1241 #define NM_POLLERR 1
1242 #endif /* POLLERR */
1243                 if (perr)
1244                         *perr |= NM_POLLERR;
1245 #undef NM_POLLERR
1246         } else if (can_sleep) {
1247                 tsleep(kr, 0, "NM_KR_TRYGET", 4);
1248                 goto retry;
1249         }
1250         return stopped;
1251 }
1252
1253 /* put the ring in the 'stopped' state and wait for the current user (if any) to
1254  * notice. stopped must be either NM_KR_STOPPED or NM_KR_LOCKED
1255  */
1256 static __inline void nm_kr_stop(struct netmap_kring *kr, int stopped)
1257 {
1258         kr->nkr_stopped = stopped;
1259         while (NM_ATOMIC_TEST_AND_SET(&kr->nr_busy))
1260                 tsleep(kr, 0, "NM_KR_GET", 4);
1261 }
1262
1263 /* restart a ring after a stop */
1264 static __inline void nm_kr_start(struct netmap_kring *kr)
1265 {
1266         kr->nkr_stopped = 0;
1267         nm_kr_put(kr);
1268 }
1269
1270
1271 /*
1272  * The following functions are used by individual drivers to
1273  * support netmap operation.
1274  *
1275  * netmap_attach() initializes a struct netmap_adapter, allocating the
1276  *      struct netmap_ring's and the struct selinfo.
1277  *
1278  * netmap_detach() frees the memory allocated by netmap_attach().
1279  *
1280  * netmap_transmit() replaces the if_transmit routine of the interface,
1281  *      and is used to intercept packets coming from the stack.
1282  *
1283  * netmap_load_map/netmap_reload_map are helper routines to set/reset
1284  *      the dmamap for a packet buffer
1285  *
1286  * netmap_reset() is a helper routine to be called in the hw driver
1287  *      when reinitializing a ring. It should not be called by
1288  *      virtual ports (vale, pipes, monitor)
1289  */
1290 int netmap_attach(struct netmap_adapter *);
1291 int netmap_attach_ext(struct netmap_adapter *, size_t size, int override_reg);
1292 void netmap_detach(struct ifnet *);
1293 int netmap_transmit(struct ifnet *, struct mbuf *);
1294 struct netmap_slot *netmap_reset(struct netmap_adapter *na,
1295         enum txrx tx, u_int n, u_int new_cur);
1296 int netmap_ring_reinit(struct netmap_kring *);
1297 int netmap_rings_config_get(struct netmap_adapter *, struct nm_config_info *);
1298
1299 /* Return codes for netmap_*x_irq. */
1300 enum {
1301         /* Driver should do normal interrupt processing, e.g. because
1302          * the interface is not in netmap mode. */
1303         NM_IRQ_PASS = 0,
1304         /* Port is in netmap mode, and the interrupt work has been
1305          * completed. The driver does not have to notify netmap
1306          * again before the next interrupt. */
1307         NM_IRQ_COMPLETED = -1,
1308         /* Port is in netmap mode, but the interrupt work has not been
1309          * completed. The driver has to make sure netmap will be
1310          * notified again soon, even if no more interrupts come (e.g.
1311          * on Linux the driver should not call napi_complete()). */
1312         NM_IRQ_RESCHED = -2,
1313 };
1314
1315 /* default functions to handle rx/tx interrupts */
1316 int netmap_rx_irq(struct ifnet *, u_int, u_int *);
1317 #define netmap_tx_irq(_n, _q) netmap_rx_irq(_n, _q, NULL)
1318 int netmap_common_irq(struct netmap_adapter *, u_int, u_int *work_done);
1319
1320
1321 #ifdef WITH_VALE
1322 /* functions used by external modules to interface with VALE */
1323 #define netmap_vp_to_ifp(_vp)   ((_vp)->up.ifp)
1324 #define netmap_ifp_to_vp(_ifp)  (NA(_ifp)->na_vp)
1325 #define netmap_ifp_to_host_vp(_ifp) (NA(_ifp)->na_hostvp)
1326 #define netmap_bdg_idx(_vp)     ((_vp)->bdg_port)
1327 const char *netmap_bdg_name(struct netmap_vp_adapter *);
1328 #else /* !WITH_VALE */
1329 #define netmap_vp_to_ifp(_vp)   NULL
1330 #define netmap_ifp_to_vp(_ifp)  NULL
1331 #define netmap_ifp_to_host_vp(_ifp) NULL
1332 #define netmap_bdg_idx(_vp)     -1
1333 #endif /* WITH_VALE */
1334
1335 static inline int
1336 nm_netmap_on(struct netmap_adapter *na)
1337 {
1338         return na && na->na_flags & NAF_NETMAP_ON;
1339 }
1340
1341 static inline int
1342 nm_native_on(struct netmap_adapter *na)
1343 {
1344         return nm_netmap_on(na) && (na->na_flags & NAF_NATIVE);
1345 }
1346
1347 static inline int
1348 nm_iszombie(struct netmap_adapter *na)
1349 {
1350         return na == NULL || (na->na_flags & NAF_ZOMBIE);
1351 }
1352
1353 static inline void
1354 nm_update_hostrings_mode(struct netmap_adapter *na)
1355 {
1356         /* Process nr_mode and nr_pending_mode for host rings. */
1357         na->tx_rings[na->num_tx_rings]->nr_mode =
1358                 na->tx_rings[na->num_tx_rings]->nr_pending_mode;
1359         na->rx_rings[na->num_rx_rings]->nr_mode =
1360                 na->rx_rings[na->num_rx_rings]->nr_pending_mode;
1361 }
1362
1363 void nm_set_native_flags(struct netmap_adapter *);
1364 void nm_clear_native_flags(struct netmap_adapter *);
1365
1366 /*
1367  * nm_*sync_prologue() functions are used in ioctl/poll and ptnetmap
1368  * kthreads.
1369  * We need netmap_ring* parameter, because in ptnetmap it is decoupled
1370  * from host kring.
1371  * The user-space ring pointers (head/cur/tail) are shared through
1372  * CSB between host and guest.
1373  */
1374
1375 /*
1376  * validates parameters in the ring/kring, returns a value for head
1377  * If any error, returns ring_size to force a reinit.
1378  */
1379 uint32_t nm_txsync_prologue(struct netmap_kring *, struct netmap_ring *);
1380
1381
1382 /*
1383  * validates parameters in the ring/kring, returns a value for head
1384  * If any error, returns ring_size lim to force a reinit.
1385  */
1386 uint32_t nm_rxsync_prologue(struct netmap_kring *, struct netmap_ring *);
1387
1388
1389 /* check/fix address and len in tx rings */
1390 #if 1 /* debug version */
1391 #define NM_CHECK_ADDR_LEN(_na, _a, _l)  do {                            \
1392         if (_a == NETMAP_BUF_BASE(_na) || _l > NETMAP_BUF_SIZE(_na)) {  \
1393                 RD(5, "bad addr/len ring %d slot %d idx %d len %d",     \
1394                         kring->ring_id, nm_i, slot->buf_idx, len);      \
1395                 if (_l > NETMAP_BUF_SIZE(_na))                          \
1396                         _l = NETMAP_BUF_SIZE(_na);                      \
1397         } } while (0)
1398 #else /* no debug version */
1399 #define NM_CHECK_ADDR_LEN(_na, _a, _l)  do {                            \
1400                 if (_l > NETMAP_BUF_SIZE(_na))                          \
1401                         _l = NETMAP_BUF_SIZE(_na);                      \
1402         } while (0)
1403 #endif
1404
1405
1406 /*---------------------------------------------------------------*/
1407 /*
1408  * Support routines used by netmap subsystems
1409  * (native drivers, VALE, generic, pipes, monitors, ...)
1410  */
1411
1412
1413 /* common routine for all functions that create a netmap adapter. It performs
1414  * two main tasks:
1415  * - if the na points to an ifp, mark the ifp as netmap capable
1416  *   using na as its native adapter;
1417  * - provide defaults for the setup callbacks and the memory allocator
1418  */
1419 int netmap_attach_common(struct netmap_adapter *);
1420 /* fill priv->np_[tr]xq{first,last} using the ringid and flags information
1421  * coming from a struct nmreq_register
1422  */
1423 int netmap_interp_ringid(struct netmap_priv_d *priv, uint32_t nr_mode,
1424                         uint16_t nr_ringid, uint64_t nr_flags);
1425 /* update the ring parameters (number and size of tx and rx rings).
1426  * It calls the nm_config callback, if available.
1427  */
1428 int netmap_update_config(struct netmap_adapter *na);
1429 /* create and initialize the common fields of the krings array.
1430  * using the information that must be already available in the na.
1431  * tailroom can be used to request the allocation of additional
1432  * tailroom bytes after the krings array. This is used by
1433  * netmap_vp_adapter's (i.e., VALE ports) to make room for
1434  * leasing-related data structures
1435  */
1436 int netmap_krings_create(struct netmap_adapter *na, u_int tailroom);
1437 /* deletes the kring array of the adapter. The array must have
1438  * been created using netmap_krings_create
1439  */
1440 void netmap_krings_delete(struct netmap_adapter *na);
1441
1442 int netmap_hw_krings_create(struct netmap_adapter *na);
1443 void netmap_hw_krings_delete(struct netmap_adapter *na);
1444
1445 /* set the stopped/enabled status of ring
1446  * When stopping, they also wait for all current activity on the ring to
1447  * terminate. The status change is then notified using the na nm_notify
1448  * callback.
1449  */
1450 void netmap_set_ring(struct netmap_adapter *, u_int ring_id, enum txrx, int stopped);
1451 /* set the stopped/enabled status of all rings of the adapter. */
1452 void netmap_set_all_rings(struct netmap_adapter *, int stopped);
1453 /* convenience wrappers for netmap_set_all_rings */
1454 void netmap_disable_all_rings(struct ifnet *);
1455 void netmap_enable_all_rings(struct ifnet *);
1456
1457 int netmap_buf_size_validate(const struct netmap_adapter *na, unsigned mtu);
1458 int netmap_do_regif(struct netmap_priv_d *priv, struct netmap_adapter *na,
1459                 uint32_t nr_mode, uint16_t nr_ringid, uint64_t nr_flags);
1460 void netmap_do_unregif(struct netmap_priv_d *priv);
1461
1462 u_int nm_bound_var(u_int *v, u_int dflt, u_int lo, u_int hi, const char *msg);
1463 int netmap_get_na(struct nmreq_header *hdr, struct netmap_adapter **na,
1464                 struct ifnet **ifp, struct netmap_mem_d *nmd, int create);
1465 void netmap_unget_na(struct netmap_adapter *na, struct ifnet *ifp);
1466 int netmap_get_hw_na(struct ifnet *ifp,
1467                 struct netmap_mem_d *nmd, struct netmap_adapter **na);
1468
1469 #ifdef WITH_VALE
1470 uint32_t netmap_vale_learning(struct nm_bdg_fwd *ft, uint8_t *dst_ring,
1471                 struct netmap_vp_adapter *, void *private_data);
1472
1473 /* these are redefined in case of no VALE support */
1474 int netmap_get_vale_na(struct nmreq_header *hdr, struct netmap_adapter **na,
1475                 struct netmap_mem_d *nmd, int create);
1476 void *netmap_vale_create(const char *bdg_name, int *return_status);
1477 int netmap_vale_destroy(const char *bdg_name, void *auth_token);
1478
1479 #else /* !WITH_VALE */
1480 #define netmap_bdg_learning(_1, _2, _3, _4)     0
1481 #define netmap_get_vale_na(_1, _2, _3, _4)      0
1482 #define netmap_bdg_create(_1, _2)       NULL
1483 #define netmap_bdg_destroy(_1, _2)      0
1484 #endif /* !WITH_VALE */
1485
1486 #ifdef WITH_PIPES
1487 /* max number of pipes per device */
1488 #define NM_MAXPIPES     64      /* XXX this should probably be a sysctl */
1489 void netmap_pipe_dealloc(struct netmap_adapter *);
1490 int netmap_get_pipe_na(struct nmreq_header *hdr, struct netmap_adapter **na,
1491                         struct netmap_mem_d *nmd, int create);
1492 #else /* !WITH_PIPES */
1493 #define NM_MAXPIPES     0
1494 #define netmap_pipe_alloc(_1, _2)       0
1495 #define netmap_pipe_dealloc(_1)
1496 #define netmap_get_pipe_na(hdr, _2, _3, _4)     \
1497         ((strchr(hdr->nr_name, '{') != NULL || strchr(hdr->nr_name, '}') != NULL) ? EOPNOTSUPP : 0)
1498 #endif
1499
1500 #ifdef WITH_MONITOR
1501 int netmap_get_monitor_na(struct nmreq_header *hdr, struct netmap_adapter **na,
1502                 struct netmap_mem_d *nmd, int create);
1503 void netmap_monitor_stop(struct netmap_adapter *na);
1504 #else
1505 #define netmap_get_monitor_na(hdr, _2, _3, _4) \
1506         (((struct nmreq_register *)(uintptr_t)hdr->nr_body)->nr_flags & (NR_MONITOR_TX | NR_MONITOR_RX) ? EOPNOTSUPP : 0)
1507 #endif
1508
1509 #ifdef WITH_NMNULL
1510 int netmap_get_null_na(struct nmreq_header *hdr, struct netmap_adapter **na,
1511                 struct netmap_mem_d *nmd, int create);
1512 #else /* !WITH_NMNULL */
1513 #define netmap_get_null_na(hdr, _2, _3, _4) \
1514         (((struct nmreq_register *)(uintptr_t)hdr->nr_body)->nr_flags & (NR_MONITOR_TX | NR_MONITOR_RX) ? EOPNOTSUPP : 0)
1515 #endif /* WITH_NMNULL */
1516
1517 #ifdef CONFIG_NET_NS
1518 struct net *netmap_bns_get(void);
1519 void netmap_bns_put(struct net *);
1520 void netmap_bns_getbridges(struct nm_bridge **, u_int *);
1521 #else
1522 extern struct nm_bridge *nm_bridges;
1523 #define netmap_bns_get()
1524 #define netmap_bns_put(_1)
1525 #define netmap_bns_getbridges(b, n) \
1526         do { *b = nm_bridges; *n = NM_BRIDGES; } while (0)
1527 #endif
1528
1529 /* Various prototypes */
1530 int netmap_poll(struct netmap_priv_d *, int events, NM_SELRECORD_T *td);
1531 int netmap_init(void);
1532 void netmap_fini(void);
1533 int netmap_get_memory(struct netmap_priv_d* p);
1534 void netmap_dtor(void *data);
1535
1536 int netmap_ioctl(struct netmap_priv_d *priv, u_long cmd, caddr_t data,
1537                 struct thread *, int nr_body_is_user);
1538 int netmap_ioctl_legacy(struct netmap_priv_d *priv, u_long cmd, caddr_t data,
1539                         struct thread *td);
1540 size_t nmreq_size_by_type(uint16_t nr_reqtype);
1541
1542 /* netmap_adapter creation/destruction */
1543
1544 // #define NM_DEBUG_PUTGET 1
1545
1546 #ifdef NM_DEBUG_PUTGET
1547
1548 #define NM_DBG(f) __##f
1549
1550 void __netmap_adapter_get(struct netmap_adapter *na);
1551
1552 #define netmap_adapter_get(na)                          \
1553         do {                                            \
1554                 struct netmap_adapter *__na = na;       \
1555                 D("getting %p:%s (%d)", __na, (__na)->name, (__na)->na_refcount);       \
1556                 __netmap_adapter_get(__na);             \
1557         } while (0)
1558
1559 int __netmap_adapter_put(struct netmap_adapter *na);
1560
1561 #define netmap_adapter_put(na)                          \
1562         ({                                              \
1563                 struct netmap_adapter *__na = na;       \
1564                 D("putting %p:%s (%d)", __na, (__na)->name, (__na)->na_refcount);       \
1565                 __netmap_adapter_put(__na);             \
1566         })
1567
1568 #else /* !NM_DEBUG_PUTGET */
1569
1570 #define NM_DBG(f) f
1571 void netmap_adapter_get(struct netmap_adapter *na);
1572 int netmap_adapter_put(struct netmap_adapter *na);
1573
1574 #endif /* !NM_DEBUG_PUTGET */
1575
1576
1577 /*
1578  * module variables
1579  */
1580 #define NETMAP_BUF_BASE(_na)    ((_na)->na_lut.lut[0].vaddr)
1581 #define NETMAP_BUF_SIZE(_na)    ((_na)->na_lut.objsize)
1582 extern int netmap_no_pendintr;
1583 extern int netmap_mitigate;
1584 extern int netmap_verbose;
1585 #ifdef CONFIG_NETMAP_DEBUG
1586 extern int netmap_debug;                /* for debugging */
1587 #else /* !CONFIG_NETMAP_DEBUG */
1588 #define netmap_debug (0)
1589 #endif /* !CONFIG_NETMAP_DEBUG */
1590 enum {                                  /* debug flags */
1591         NM_DEBUG_ON = 1,                /* generic debug messsages */
1592         NM_DEBUG_HOST = 0x2,            /* debug host stack */
1593         NM_DEBUG_RXSYNC = 0x10,         /* debug on rxsync/txsync */
1594         NM_DEBUG_TXSYNC = 0x20,
1595         NM_DEBUG_RXINTR = 0x100,        /* debug on rx/tx intr (driver) */
1596         NM_DEBUG_TXINTR = 0x200,
1597         NM_DEBUG_NIC_RXSYNC = 0x1000,   /* debug on rx/tx intr (driver) */
1598         NM_DEBUG_NIC_TXSYNC = 0x2000,
1599         NM_DEBUG_MEM = 0x4000,          /* verbose memory allocations/deallocations */
1600         NM_DEBUG_VALE = 0x8000,         /* debug messages from memory allocators */
1601         NM_DEBUG_BDG = NM_DEBUG_VALE,
1602 };
1603
1604 extern int netmap_txsync_retry;
1605 extern int netmap_flags;
1606 extern int netmap_generic_hwcsum;
1607 extern int netmap_generic_mit;
1608 extern int netmap_generic_ringsize;
1609 extern int netmap_generic_rings;
1610 #ifdef linux
1611 extern int netmap_generic_txqdisc;
1612 #endif
1613
1614 /*
1615  * NA returns a pointer to the struct netmap adapter from the ifp.
1616  * WNA is os-specific and must be defined in glue code.
1617  */
1618 #define NA(_ifp)        ((struct netmap_adapter *)WNA(_ifp))
1619
1620 /*
1621  * we provide a default implementation of NM_ATTACH_NA/NM_DETACH_NA
1622  * based on the WNA field.
1623  * Glue code may override this by defining its own NM_ATTACH_NA
1624  */
1625 #ifndef NM_ATTACH_NA
1626 /*
1627  * On old versions of FreeBSD, NA(ifp) is a pspare. On linux we
1628  * overload another pointer in the netdev.
1629  *
1630  * We check if NA(ifp) is set and its first element has a related
1631  * magic value. The capenable is within the struct netmap_adapter.
1632  */
1633 #define NETMAP_MAGIC    0x52697a7a
1634
1635 #define NM_NA_VALID(ifp)        (NA(ifp) &&             \
1636         ((uint32_t)(uintptr_t)NA(ifp) ^ NA(ifp)->magic) == NETMAP_MAGIC )
1637
1638 #define NM_ATTACH_NA(ifp, na) do {                                      \
1639         WNA(ifp) = na;                                                  \
1640         if (NA(ifp))                                                    \
1641                 NA(ifp)->magic =                                        \
1642                         ((uint32_t)(uintptr_t)NA(ifp)) ^ NETMAP_MAGIC;  \
1643 } while(0)
1644 #define NM_RESTORE_NA(ifp, na)  WNA(ifp) = na;
1645
1646 #define NM_DETACH_NA(ifp)       do { WNA(ifp) = NULL; } while (0)
1647 #define NM_NA_CLASH(ifp)        (NA(ifp) && !NM_NA_VALID(ifp))
1648 #endif /* !NM_ATTACH_NA */
1649
1650
1651 #define NM_IS_NATIVE(ifp)       (NM_NA_VALID(ifp) && NA(ifp)->nm_dtor == netmap_hw_dtor)
1652
1653 #if defined(__FreeBSD__)
1654
1655 /* Assigns the device IOMMU domain to an allocator.
1656  * Returns -ENOMEM in case the domain is different */
1657 #define nm_iommu_group_id(dev) (0)
1658
1659 /* Callback invoked by the dma machinery after a successful dmamap_load */
1660 static void netmap_dmamap_cb(__unused void *arg,
1661     __unused bus_dma_segment_t * segs, __unused int nseg, __unused int error)
1662 {
1663 }
1664
1665 /* bus_dmamap_load wrapper: call aforementioned function if map != NULL.
1666  * XXX can we do it without a callback ?
1667  */
1668 static inline int
1669 netmap_load_map(struct netmap_adapter *na,
1670         bus_dma_tag_t tag, bus_dmamap_t map, void *buf)
1671 {
1672         if (map)
1673                 bus_dmamap_load(tag, map, buf, NETMAP_BUF_SIZE(na),
1674                     netmap_dmamap_cb, NULL, BUS_DMA_NOWAIT);
1675         return 0;
1676 }
1677
1678 static inline void
1679 netmap_unload_map(struct netmap_adapter *na,
1680         bus_dma_tag_t tag, bus_dmamap_t map)
1681 {
1682         if (map)
1683                 bus_dmamap_unload(tag, map);
1684 }
1685
1686 #define netmap_sync_map(na, tag, map, sz, t)
1687
1688 /* update the map when a buffer changes. */
1689 static inline void
1690 netmap_reload_map(struct netmap_adapter *na,
1691         bus_dma_tag_t tag, bus_dmamap_t map, void *buf)
1692 {
1693         if (map) {
1694                 bus_dmamap_unload(tag, map);
1695                 bus_dmamap_load(tag, map, buf, NETMAP_BUF_SIZE(na),
1696                     netmap_dmamap_cb, NULL, BUS_DMA_NOWAIT);
1697         }
1698 }
1699
1700 #elif defined(_WIN32)
1701
1702 #else /* linux */
1703
1704 int nm_iommu_group_id(bus_dma_tag_t dev);
1705 #include <linux/dma-mapping.h>
1706
1707 /*
1708  * on linux we need
1709  *      dma_map_single(&pdev->dev, virt_addr, len, direction)
1710  *      dma_unmap_single(&adapter->pdev->dev, phys_addr, len, direction)
1711  */
1712 #if 0
1713         struct e1000_buffer *buffer_info =  &tx_ring->buffer_info[l];
1714         /* set time_stamp *before* dma to help avoid a possible race */
1715         buffer_info->time_stamp = jiffies;
1716         buffer_info->mapped_as_page = false;
1717         buffer_info->length = len;
1718         //buffer_info->next_to_watch = l;
1719         /* reload dma map */
1720         dma_unmap_single(&adapter->pdev->dev, buffer_info->dma,
1721                         NETMAP_BUF_SIZE, DMA_TO_DEVICE);
1722         buffer_info->dma = dma_map_single(&adapter->pdev->dev,
1723                         addr, NETMAP_BUF_SIZE, DMA_TO_DEVICE);
1724
1725         if (dma_mapping_error(&adapter->pdev->dev, buffer_info->dma)) {
1726                 D("dma mapping error");
1727                 /* goto dma_error; See e1000_put_txbuf() */
1728                 /* XXX reset */
1729         }
1730         tx_desc->buffer_addr = htole64(buffer_info->dma); //XXX
1731
1732 #endif
1733
1734 static inline int
1735 netmap_load_map(struct netmap_adapter *na,
1736         bus_dma_tag_t tag, bus_dmamap_t map, void *buf, u_int size)
1737 {
1738         if (map) {
1739                 *map = dma_map_single(na->pdev, buf, size,
1740                                       DMA_BIDIRECTIONAL);
1741                 if (dma_mapping_error(na->pdev, *map)) {
1742                         *map = 0;
1743                         return ENOMEM;
1744                 }
1745         }
1746         return 0;
1747 }
1748
1749 static inline void
1750 netmap_unload_map(struct netmap_adapter *na,
1751         bus_dma_tag_t tag, bus_dmamap_t map, u_int sz)
1752 {
1753         if (*map) {
1754                 dma_unmap_single(na->pdev, *map, sz,
1755                                  DMA_BIDIRECTIONAL);
1756         }
1757 }
1758
1759 #ifdef NETMAP_LINUX_HAVE_DMASYNC
1760 static inline void
1761 netmap_sync_map_cpu(struct netmap_adapter *na,
1762         bus_dma_tag_t tag, bus_dmamap_t map, u_int sz, enum txrx t)
1763 {
1764         if (*map) {
1765                 dma_sync_single_for_cpu(na->pdev, *map, sz,
1766                         (t == NR_TX ? DMA_TO_DEVICE : DMA_FROM_DEVICE));
1767         }
1768 }
1769
1770 static inline void
1771 netmap_sync_map_dev(struct netmap_adapter *na,
1772         bus_dma_tag_t tag, bus_dmamap_t map, u_int sz, enum txrx t)
1773 {
1774         if (*map) {
1775                 dma_sync_single_for_device(na->pdev, *map, sz,
1776                         (t == NR_TX ? DMA_TO_DEVICE : DMA_FROM_DEVICE));
1777         }
1778 }
1779
1780 static inline void
1781 netmap_reload_map(struct netmap_adapter *na,
1782         bus_dma_tag_t tag, bus_dmamap_t map, void *buf)
1783 {
1784         u_int sz = NETMAP_BUF_SIZE(na);
1785
1786         if (*map) {
1787                 dma_unmap_single(na->pdev, *map, sz,
1788                                 DMA_BIDIRECTIONAL);
1789         }
1790
1791         *map = dma_map_single(na->pdev, buf, sz,
1792                                 DMA_BIDIRECTIONAL);
1793 }
1794 #else /* !NETMAP_LINUX_HAVE_DMASYNC */
1795 #define netmap_sync_map_cpu(na, tag, map, sz, t)
1796 #define netmap_sync_map_dev(na, tag, map, sz, t)
1797 #endif /* NETMAP_LINUX_HAVE_DMASYNC */
1798
1799 #endif /* linux */
1800
1801
1802 /*
1803  * functions to map NIC to KRING indexes (n2k) and vice versa (k2n)
1804  */
1805 static inline int
1806 netmap_idx_n2k(struct netmap_kring *kr, int idx)
1807 {
1808         int n = kr->nkr_num_slots;
1809
1810         if (likely(kr->nkr_hwofs == 0)) {
1811                 return idx;
1812         }
1813
1814         idx += kr->nkr_hwofs;
1815         if (idx < 0)
1816                 return idx + n;
1817         else if (idx < n)
1818                 return idx;
1819         else
1820                 return idx - n;
1821 }
1822
1823
1824 static inline int
1825 netmap_idx_k2n(struct netmap_kring *kr, int idx)
1826 {
1827         int n = kr->nkr_num_slots;
1828
1829         if (likely(kr->nkr_hwofs == 0)) {
1830                 return idx;
1831         }
1832
1833         idx -= kr->nkr_hwofs;
1834         if (idx < 0)
1835                 return idx + n;
1836         else if (idx < n)
1837                 return idx;
1838         else
1839                 return idx - n;
1840 }
1841
1842
1843 /* Entries of the look-up table. */
1844 #ifdef __FreeBSD__
1845 struct lut_entry {
1846         void *vaddr;            /* virtual address. */
1847         vm_paddr_t paddr;       /* physical address. */
1848 };
1849 #else /* linux & _WIN32 */
1850 /* dma-mapping in linux can assign a buffer a different address
1851  * depending on the device, so we need to have a separate
1852  * physical-address look-up table for each na.
1853  * We can still share the vaddrs, though, therefore we split
1854  * the lut_entry structure.
1855  */
1856 struct lut_entry {
1857         void *vaddr;            /* virtual address. */
1858 };
1859
1860 struct plut_entry {
1861         vm_paddr_t paddr;       /* physical address. */
1862 };
1863 #endif /* linux & _WIN32 */
1864
1865 struct netmap_obj_pool;
1866
1867 /*
1868  * NMB return the virtual address of a buffer (buffer 0 on bad index)
1869  * PNMB also fills the physical address
1870  */
1871 static inline void *
1872 NMB(struct netmap_adapter *na, struct netmap_slot *slot)
1873 {
1874         struct lut_entry *lut = na->na_lut.lut;
1875         uint32_t i = slot->buf_idx;
1876         return (unlikely(i >= na->na_lut.objtotal)) ?
1877                 lut[0].vaddr : lut[i].vaddr;
1878 }
1879
1880 static inline void *
1881 PNMB(struct netmap_adapter *na, struct netmap_slot *slot, uint64_t *pp)
1882 {
1883         uint32_t i = slot->buf_idx;
1884         struct lut_entry *lut = na->na_lut.lut;
1885         struct plut_entry *plut = na->na_lut.plut;
1886         void *ret = (i >= na->na_lut.objtotal) ? lut[0].vaddr : lut[i].vaddr;
1887
1888 #ifdef _WIN32
1889         *pp = (i >= na->na_lut.objtotal) ? (uint64_t)plut[0].paddr.QuadPart : (uint64_t)plut[i].paddr.QuadPart;
1890 #else
1891         *pp = (i >= na->na_lut.objtotal) ? plut[0].paddr : plut[i].paddr;
1892 #endif
1893         return ret;
1894 }
1895
1896
1897 /*
1898  * Structure associated to each netmap file descriptor.
1899  * It is created on open and left unbound (np_nifp == NULL).
1900  * A successful NIOCREGIF will set np_nifp and the first few fields;
1901  * this is protected by a global lock (NMG_LOCK) due to low contention.
1902  *
1903  * np_refs counts the number of references to the structure: one for the fd,
1904  * plus (on FreeBSD) one for each active mmap which we track ourselves
1905  * (linux automatically tracks them, but FreeBSD does not).
1906  * np_refs is protected by NMG_LOCK.
1907  *
1908  * Read access to the structure is lock free, because ni_nifp once set
1909  * can only go to 0 when nobody is using the entry anymore. Readers
1910  * must check that np_nifp != NULL before using the other fields.
1911  */
1912 struct netmap_priv_d {
1913         struct netmap_if * volatile np_nifp;    /* netmap if descriptor. */
1914
1915         struct netmap_adapter   *np_na;
1916         struct ifnet    *np_ifp;
1917         uint32_t        np_flags;       /* from the ioctl */
1918         u_int           np_qfirst[NR_TXRX],
1919                         np_qlast[NR_TXRX]; /* range of tx/rx rings to scan */
1920         uint16_t        np_txpoll;
1921         uint16_t        np_kloop_state; /* use with NMG_LOCK held */
1922 #define NM_SYNC_KLOOP_RUNNING   (1 << 0)
1923 #define NM_SYNC_KLOOP_STOPPING  (1 << 1)
1924         int             np_sync_flags; /* to be passed to nm_sync */
1925
1926         int             np_refs;        /* use with NMG_LOCK held */
1927
1928         /* pointers to the selinfo to be used for selrecord.
1929          * Either the local or the global one depending on the
1930          * number of rings.
1931          */
1932         NM_SELINFO_T *np_si[NR_TXRX];
1933
1934         /* In the optional CSB mode, the user must specify the start address
1935          * of two arrays of Communication Status Block (CSB) entries, for the
1936          * two directions (kernel read application write, and kernel write
1937          * application read).
1938          * The number of entries must agree with the number of rings bound to
1939          * the netmap file descriptor. The entries corresponding to the TX
1940          * rings are laid out before the ones corresponding to the RX rings.
1941          *
1942          * Array of CSB entries for application --> kernel communication
1943          * (N entries). */
1944         struct nm_csb_atok      *np_csb_atok_base;
1945         /* Array of CSB entries for kernel --> application communication
1946          * (N entries). */
1947         struct nm_csb_ktoa      *np_csb_ktoa_base;
1948
1949         struct thread   *np_td;         /* kqueue, just debugging */
1950 #ifdef linux
1951         struct file     *np_filp;  /* used by sync kloop */
1952 #endif /* linux */
1953 };
1954
1955 struct netmap_priv_d *netmap_priv_new(void);
1956 void netmap_priv_delete(struct netmap_priv_d *);
1957
1958 static inline int nm_kring_pending(struct netmap_priv_d *np)
1959 {
1960         struct netmap_adapter *na = np->np_na;
1961         enum txrx t;
1962         int i;
1963
1964         for_rx_tx(t) {
1965                 for (i = np->np_qfirst[t]; i < np->np_qlast[t]; i++) {
1966                         struct netmap_kring *kring = NMR(na, t)[i];
1967                         if (kring->nr_mode != kring->nr_pending_mode) {
1968                                 return 1;
1969                         }
1970                 }
1971         }
1972         return 0;
1973 }
1974
1975 /* call with NMG_LOCK held */
1976 static __inline int
1977 nm_si_user(struct netmap_priv_d *priv, enum txrx t)
1978 {
1979         return (priv->np_na != NULL &&
1980                 (priv->np_qlast[t] - priv->np_qfirst[t] > 1));
1981 }
1982
1983 #ifdef WITH_PIPES
1984 int netmap_pipe_txsync(struct netmap_kring *txkring, int flags);
1985 int netmap_pipe_rxsync(struct netmap_kring *rxkring, int flags);
1986 #endif /* WITH_PIPES */
1987
1988 #ifdef WITH_MONITOR
1989
1990 struct netmap_monitor_adapter {
1991         struct netmap_adapter up;
1992
1993         struct netmap_priv_d priv;
1994         uint32_t flags;
1995 };
1996
1997 #endif /* WITH_MONITOR */
1998
1999
2000 #ifdef WITH_GENERIC
2001 /*
2002  * generic netmap emulation for devices that do not have
2003  * native netmap support.
2004  */
2005 int generic_netmap_attach(struct ifnet *ifp);
2006 int generic_rx_handler(struct ifnet *ifp, struct mbuf *m);;
2007
2008 int nm_os_catch_rx(struct netmap_generic_adapter *gna, int intercept);
2009 int nm_os_catch_tx(struct netmap_generic_adapter *gna, int intercept);
2010
2011 int na_is_generic(struct netmap_adapter *na);
2012
2013 /*
2014  * the generic transmit routine is passed a structure to optionally
2015  * build a queue of descriptors, in an OS-specific way.
2016  * The payload is at addr, if non-null, and the routine should send or queue
2017  * the packet, returning 0 if successful, 1 on failure.
2018  *
2019  * At the end, if head is non-null, there will be an additional call
2020  * to the function with addr = NULL; this should tell the OS-specific
2021  * routine to send the queue and free any resources. Failure is ignored.
2022  */
2023 struct nm_os_gen_arg {
2024         struct ifnet *ifp;
2025         void *m;        /* os-specific mbuf-like object */
2026         void *head, *tail; /* tailq, if the OS-specific routine needs to build one */
2027         void *addr;     /* payload of current packet */
2028         u_int len;      /* packet length */
2029         u_int ring_nr;  /* packet length */
2030         u_int qevent;   /* in txqdisc mode, place an event on this mbuf */
2031 };
2032
2033 int nm_os_generic_xmit_frame(struct nm_os_gen_arg *);
2034 int nm_os_generic_find_num_desc(struct ifnet *ifp, u_int *tx, u_int *rx);
2035 void nm_os_generic_find_num_queues(struct ifnet *ifp, u_int *txq, u_int *rxq);
2036 void nm_os_generic_set_features(struct netmap_generic_adapter *gna);
2037
2038 static inline struct ifnet*
2039 netmap_generic_getifp(struct netmap_generic_adapter *gna)
2040 {
2041         if (gna->prev)
2042             return gna->prev->ifp;
2043
2044         return gna->up.up.ifp;
2045 }
2046
2047 void netmap_generic_irq(struct netmap_adapter *na, u_int q, u_int *work_done);
2048
2049 //#define RATE_GENERIC  /* Enables communication statistics for generic. */
2050 #ifdef RATE_GENERIC
2051 void generic_rate(int txp, int txs, int txi, int rxp, int rxs, int rxi);
2052 #else
2053 #define generic_rate(txp, txs, txi, rxp, rxs, rxi)
2054 #endif
2055
2056 /*
2057  * netmap_mitigation API. This is used by the generic adapter
2058  * to reduce the number of interrupt requests/selwakeup
2059  * to clients on incoming packets.
2060  */
2061 void nm_os_mitigation_init(struct nm_generic_mit *mit, int idx,
2062                                 struct netmap_adapter *na);
2063 void nm_os_mitigation_start(struct nm_generic_mit *mit);
2064 void nm_os_mitigation_restart(struct nm_generic_mit *mit);
2065 int nm_os_mitigation_active(struct nm_generic_mit *mit);
2066 void nm_os_mitigation_cleanup(struct nm_generic_mit *mit);
2067 #else /* !WITH_GENERIC */
2068 #define generic_netmap_attach(ifp)      (EOPNOTSUPP)
2069 #define na_is_generic(na)               (0)
2070 #endif /* WITH_GENERIC */
2071
2072 /* Shared declarations for the VALE switch. */
2073
2074 /*
2075  * Each transmit queue accumulates a batch of packets into
2076  * a structure before forwarding. Packets to the same
2077  * destination are put in a list using ft_next as a link field.
2078  * ft_frags and ft_next are valid only on the first fragment.
2079  */
2080 struct nm_bdg_fwd {     /* forwarding entry for a bridge */
2081         void *ft_buf;           /* netmap or indirect buffer */
2082         uint8_t ft_frags;       /* how many fragments (only on 1st frag) */
2083         uint16_t ft_offset;     /* dst port (unused) */
2084         uint16_t ft_flags;      /* flags, e.g. indirect */
2085         uint16_t ft_len;        /* src fragment len */
2086         uint16_t ft_next;       /* next packet to same destination */
2087 };
2088
2089 /* struct 'virtio_net_hdr' from linux. */
2090 struct nm_vnet_hdr {
2091 #define VIRTIO_NET_HDR_F_NEEDS_CSUM     1       /* Use csum_start, csum_offset */
2092 #define VIRTIO_NET_HDR_F_DATA_VALID    2        /* Csum is valid */
2093     uint8_t flags;
2094 #define VIRTIO_NET_HDR_GSO_NONE         0       /* Not a GSO frame */
2095 #define VIRTIO_NET_HDR_GSO_TCPV4        1       /* GSO frame, IPv4 TCP (TSO) */
2096 #define VIRTIO_NET_HDR_GSO_UDP          3       /* GSO frame, IPv4 UDP (UFO) */
2097 #define VIRTIO_NET_HDR_GSO_TCPV6        4       /* GSO frame, IPv6 TCP */
2098 #define VIRTIO_NET_HDR_GSO_ECN          0x80    /* TCP has ECN set */
2099     uint8_t gso_type;
2100     uint16_t hdr_len;
2101     uint16_t gso_size;
2102     uint16_t csum_start;
2103     uint16_t csum_offset;
2104 };
2105
2106 #define WORST_CASE_GSO_HEADER   (14+40+60)  /* IPv6 + TCP */
2107
2108 /* Private definitions for IPv4, IPv6, UDP and TCP headers. */
2109
2110 struct nm_iphdr {
2111         uint8_t         version_ihl;
2112         uint8_t         tos;
2113         uint16_t        tot_len;
2114         uint16_t        id;
2115         uint16_t        frag_off;
2116         uint8_t         ttl;
2117         uint8_t         protocol;
2118         uint16_t        check;
2119         uint32_t        saddr;
2120         uint32_t        daddr;
2121         /*The options start here. */
2122 };
2123
2124 struct nm_tcphdr {
2125         uint16_t        source;
2126         uint16_t        dest;
2127         uint32_t        seq;
2128         uint32_t        ack_seq;
2129         uint8_t         doff;  /* Data offset + Reserved */
2130         uint8_t         flags;
2131         uint16_t        window;
2132         uint16_t        check;
2133         uint16_t        urg_ptr;
2134 };
2135
2136 struct nm_udphdr {
2137         uint16_t        source;
2138         uint16_t        dest;
2139         uint16_t        len;
2140         uint16_t        check;
2141 };
2142
2143 struct nm_ipv6hdr {
2144         uint8_t         priority_version;
2145         uint8_t         flow_lbl[3];
2146
2147         uint16_t        payload_len;
2148         uint8_t         nexthdr;
2149         uint8_t         hop_limit;
2150
2151         uint8_t         saddr[16];
2152         uint8_t         daddr[16];
2153 };
2154
2155 /* Type used to store a checksum (in host byte order) that hasn't been
2156  * folded yet.
2157  */
2158 #define rawsum_t uint32_t
2159
2160 rawsum_t nm_os_csum_raw(uint8_t *data, size_t len, rawsum_t cur_sum);
2161 uint16_t nm_os_csum_ipv4(struct nm_iphdr *iph);
2162 void nm_os_csum_tcpudp_ipv4(struct nm_iphdr *iph, void *data,
2163                       size_t datalen, uint16_t *check);
2164 void nm_os_csum_tcpudp_ipv6(struct nm_ipv6hdr *ip6h, void *data,
2165                       size_t datalen, uint16_t *check);
2166 uint16_t nm_os_csum_fold(rawsum_t cur_sum);
2167
2168 void bdg_mismatch_datapath(struct netmap_vp_adapter *na,
2169                            struct netmap_vp_adapter *dst_na,
2170                            const struct nm_bdg_fwd *ft_p,
2171                            struct netmap_ring *dst_ring,
2172                            u_int *j, u_int lim, u_int *howmany);
2173
2174 /* persistent virtual port routines */
2175 int nm_os_vi_persist(const char *, struct ifnet **);
2176 void nm_os_vi_detach(struct ifnet *);
2177 void nm_os_vi_init_index(void);
2178
2179 /*
2180  * kernel thread routines
2181  */
2182 struct nm_kctx; /* OS-specific kernel context - opaque */
2183 typedef void (*nm_kctx_worker_fn_t)(void *data);
2184
2185 /* kthread configuration */
2186 struct nm_kctx_cfg {
2187         long                    type;           /* kthread type/identifier */
2188         nm_kctx_worker_fn_t     worker_fn;      /* worker function */
2189         void                    *worker_private;/* worker parameter */
2190         int                     attach_user;    /* attach kthread to user process */
2191 };
2192 /* kthread configuration */
2193 struct nm_kctx *nm_os_kctx_create(struct nm_kctx_cfg *cfg,
2194                                         void *opaque);
2195 int nm_os_kctx_worker_start(struct nm_kctx *);
2196 void nm_os_kctx_worker_stop(struct nm_kctx *);
2197 void nm_os_kctx_destroy(struct nm_kctx *);
2198 void nm_os_kctx_worker_setaff(struct nm_kctx *, int);
2199 u_int nm_os_ncpus(void);
2200
2201 int netmap_sync_kloop(struct netmap_priv_d *priv,
2202                       struct nmreq_header *hdr);
2203 int netmap_sync_kloop_stop(struct netmap_priv_d *priv);
2204
2205 #ifdef WITH_PTNETMAP
2206 /* ptnetmap guest routines */
2207
2208 /*
2209  * ptnetmap_memdev routines used to talk with ptnetmap_memdev device driver
2210  */
2211 struct ptnetmap_memdev;
2212 int nm_os_pt_memdev_iomap(struct ptnetmap_memdev *, vm_paddr_t *, void **,
2213                           uint64_t *);
2214 void nm_os_pt_memdev_iounmap(struct ptnetmap_memdev *);
2215 uint32_t nm_os_pt_memdev_ioread(struct ptnetmap_memdev *, unsigned int);
2216
2217 /*
2218  * netmap adapter for guest ptnetmap ports
2219  */
2220 struct netmap_pt_guest_adapter {
2221         /* The netmap adapter to be used by netmap applications.
2222          * This field must be the first, to allow upcast. */
2223         struct netmap_hw_adapter hwup;
2224
2225         /* The netmap adapter to be used by the driver. */
2226         struct netmap_hw_adapter dr;
2227
2228         /* Reference counter to track users of backend netmap port: the
2229          * network stack and netmap clients.
2230          * Used to decide when we need (de)allocate krings/rings and
2231          * start (stop) ptnetmap kthreads. */
2232         int backend_users;
2233
2234 };
2235
2236 int netmap_pt_guest_attach(struct netmap_adapter *na,
2237                         unsigned int nifp_offset,
2238                         unsigned int memid);
2239 bool netmap_pt_guest_txsync(struct nm_csb_atok *atok,
2240                         struct nm_csb_ktoa *ktoa,
2241                         struct netmap_kring *kring, int flags);
2242 bool netmap_pt_guest_rxsync(struct nm_csb_atok *atok,
2243                         struct nm_csb_ktoa *ktoa,
2244                         struct netmap_kring *kring, int flags);
2245 int ptnet_nm_krings_create(struct netmap_adapter *na);
2246 void ptnet_nm_krings_delete(struct netmap_adapter *na);
2247 void ptnet_nm_dtor(struct netmap_adapter *na);
2248
2249 /* Guest driver: Write kring pointers (cur, head) to the CSB.
2250  * This routine is coupled with ptnetmap_host_read_kring_csb(). */
2251 static inline void
2252 ptnetmap_guest_write_kring_csb(struct nm_csb_atok *atok, uint32_t cur,
2253                                uint32_t head)
2254 {
2255     /*
2256      * We need to write cur and head to the CSB but we cannot do it atomically.
2257      * There is no way we can prevent the host from reading the updated value
2258      * of one of the two and the old value of the other. However, if we make
2259      * sure that the host never reads a value of head more recent than the
2260      * value of cur we are safe. We can allow the host to read a value of cur
2261      * more recent than the value of head, since in the netmap ring cur can be
2262      * ahead of head and cur cannot wrap around head because it must be behind
2263      * tail. Inverting the order of writes below could instead result into the
2264      * host to think head went ahead of cur, which would cause the sync
2265      * prologue to fail.
2266      *
2267      * The following memory barrier scheme is used to make this happen:
2268      *
2269      *          Guest              Host
2270      *
2271      *          STORE(cur)         LOAD(head)
2272      *          mb() <-----------> mb()
2273      *          STORE(head)        LOAD(cur)
2274      */
2275     atok->cur = cur;
2276     nm_stst_barrier();
2277     atok->head = head;
2278 }
2279
2280 /* Guest driver: Read kring pointers (hwcur, hwtail) from the CSB.
2281  * This routine is coupled with ptnetmap_host_write_kring_csb(). */
2282 static inline void
2283 ptnetmap_guest_read_kring_csb(struct nm_csb_ktoa *ktoa,
2284                               struct netmap_kring *kring)
2285 {
2286     /*
2287      * We place a memory barrier to make sure that the update of hwtail never
2288      * overtakes the update of hwcur.
2289      * (see explanation in ptnetmap_host_write_kring_csb).
2290      */
2291     kring->nr_hwtail = ktoa->hwtail;
2292     nm_stst_barrier();
2293     kring->nr_hwcur = ktoa->hwcur;
2294 }
2295
2296 /* Helper function wrapping ptnetmap_guest_read_kring_csb(). */
2297 static inline void
2298 ptnet_sync_tail(struct nm_csb_ktoa *ktoa, struct netmap_kring *kring)
2299 {
2300         struct netmap_ring *ring = kring->ring;
2301
2302         /* Update hwcur and hwtail as known by the host. */
2303         ptnetmap_guest_read_kring_csb(ktoa, kring);
2304
2305         /* nm_sync_finalize */
2306         ring->tail = kring->rtail = kring->nr_hwtail;
2307 }
2308 #endif /* WITH_PTNETMAP */
2309
2310 #ifdef __FreeBSD__
2311 /*
2312  * FreeBSD mbuf allocator/deallocator in emulation mode:
2313  */
2314 #if __FreeBSD_version < 1100000
2315
2316 /*
2317  * For older versions of FreeBSD:
2318  *
2319  * We allocate EXT_PACKET mbuf+clusters, but need to set M_NOFREE
2320  * so that the destructor, if invoked, will not free the packet.
2321  * In principle we should set the destructor only on demand,
2322  * but since there might be a race we better do it on allocation.
2323  * As a consequence, we also need to set the destructor or we
2324  * would leak buffers.
2325  */
2326
2327 /* mbuf destructor, also need to change the type to EXT_EXTREF,
2328  * add an M_NOFREE flag, and then clear the flag and
2329  * chain into uma_zfree(zone_pack, mf)
2330  * (or reinstall the buffer ?)
2331  */
2332 #define SET_MBUF_DESTRUCTOR(m, fn)      do {            \
2333         (m)->m_ext.ext_free = (void *)fn;       \
2334         (m)->m_ext.ext_type = EXT_EXTREF;       \
2335 } while (0)
2336
2337 static int
2338 void_mbuf_dtor(struct mbuf *m, void *arg1, void *arg2)
2339 {
2340         /* restore original mbuf */
2341         m->m_ext.ext_buf = m->m_data = m->m_ext.ext_arg1;
2342         m->m_ext.ext_arg1 = NULL;
2343         m->m_ext.ext_type = EXT_PACKET;
2344         m->m_ext.ext_free = NULL;
2345         if (MBUF_REFCNT(m) == 0)
2346                 SET_MBUF_REFCNT(m, 1);
2347         uma_zfree(zone_pack, m);
2348
2349         return 0;
2350 }
2351
2352 static inline struct mbuf *
2353 nm_os_get_mbuf(struct ifnet *ifp, int len)
2354 {
2355         struct mbuf *m;
2356
2357         (void)ifp;
2358         m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
2359         if (m) {
2360                 /* m_getcl() (mb_ctor_mbuf) has an assert that checks that
2361                  * M_NOFREE flag is not specified as third argument,
2362                  * so we have to set M_NOFREE after m_getcl(). */
2363                 m->m_flags |= M_NOFREE;
2364                 m->m_ext.ext_arg1 = m->m_ext.ext_buf; // XXX save
2365                 m->m_ext.ext_free = (void *)void_mbuf_dtor;
2366                 m->m_ext.ext_type = EXT_EXTREF;
2367                 ND(5, "create m %p refcnt %d", m, MBUF_REFCNT(m));
2368         }
2369         return m;
2370 }
2371
2372 #else /* __FreeBSD_version >= 1100000 */
2373
2374 /*
2375  * Newer versions of FreeBSD, using a straightforward scheme.
2376  *
2377  * We allocate mbufs with m_gethdr(), since the mbuf header is needed
2378  * by the driver. We also attach a customly-provided external storage,
2379  * which in this case is a netmap buffer. When calling m_extadd(), however
2380  * we pass a NULL address, since the real address (and length) will be
2381  * filled in by nm_os_generic_xmit_frame() right before calling
2382  * if_transmit().
2383  *
2384  * The dtor function does nothing, however we need it since mb_free_ext()
2385  * has a KASSERT(), checking that the mbuf dtor function is not NULL.
2386  */
2387
2388 #if __FreeBSD_version <= 1200050
2389 static void void_mbuf_dtor(struct mbuf *m, void *arg1, void *arg2) { }
2390 #else  /* __FreeBSD_version >= 1200051 */
2391 /* The arg1 and arg2 pointers argument were removed by r324446, which
2392  * in included since version 1200051. */
2393 static void void_mbuf_dtor(struct mbuf *m) { }
2394 #endif /* __FreeBSD_version >= 1200051 */
2395
2396 #define SET_MBUF_DESTRUCTOR(m, fn)      do {            \
2397         (m)->m_ext.ext_free = (fn != NULL) ?            \
2398             (void *)fn : (void *)void_mbuf_dtor;        \
2399 } while (0)
2400
2401 static inline struct mbuf *
2402 nm_os_get_mbuf(struct ifnet *ifp, int len)
2403 {
2404         struct mbuf *m;
2405
2406         (void)ifp;
2407         (void)len;
2408
2409         m = m_gethdr(M_NOWAIT, MT_DATA);
2410         if (m == NULL) {
2411                 return m;
2412         }
2413
2414         m_extadd(m, NULL /* buf */, 0 /* size */, void_mbuf_dtor,
2415                  NULL, NULL, 0, EXT_NET_DRV);
2416
2417         return m;
2418 }
2419
2420 #endif /* __FreeBSD_version >= 1100000 */
2421 #endif /* __FreeBSD__ */
2422
2423 struct nmreq_option * nmreq_findoption(struct nmreq_option *, uint16_t);
2424 int nmreq_checkduplicate(struct nmreq_option *);
2425
2426 int netmap_init_bridges(void);
2427 void netmap_uninit_bridges(void);
2428
2429 /* Functions to read and write CSB fields from the kernel. */
2430 #if defined (linux)
2431 #define CSB_READ(csb, field, r) (get_user(r, &csb->field))
2432 #define CSB_WRITE(csb, field, v) (put_user(v, &csb->field))
2433 #else  /* ! linux */
2434 #define CSB_READ(csb, field, r) (r = fuword32(&csb->field))
2435 #define CSB_WRITE(csb, field, v) (suword32(&csb->field, v))
2436 #endif /* ! linux */
2437
2438 #endif /* _NET_NETMAP_KERN_H_ */