2 * SPDX-License-Identifier: BSD-2-Clause
4 * Copyright (C) 2011-2016 Universita` di Pisa
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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.
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
32 * Functions and macros to manipulate netmap structures and packets
33 * in userspace. See netmap(4) for more information.
35 * The address of the struct netmap_if, say nifp, is computed from the
36 * value returned from ioctl(.., NIOCREG, ...) and the mmap region:
37 * ioctl(fd, NIOCREG, &req);
38 * mem = mmap(0, ... );
39 * nifp = NETMAP_IF(mem, req.nr_nifp);
40 * (so simple, we could just do it manually)
43 * struct netmap_ring *NETMAP_TXRING(nifp, index)
44 * struct netmap_ring *NETMAP_RXRING(nifp, index)
45 * we can access ring->cur, ring->head, ring->tail, etc.
47 * ring->slot[i] gives us the i-th slot (we can access
48 * directly len, flags, buf_idx)
50 * char *buf = NETMAP_BUF(ring, x) returns a pointer to
51 * the buffer numbered x
53 * All ring indexes (head, cur, tail) should always move forward.
54 * To compute the next index in a circular ring you can use
55 * i = nm_ring_next(ring, i);
57 * To ease porting apps from pcap to netmap we supply a few functions
58 * that can be called to open, close, read and write on netmap in a way
59 * similar to libpcap. Note that the read/write function depend on
60 * an ioctl()/select()/poll() being issued to refill rings or push
63 * In order to use these, include #define NETMAP_WITH_LIBS
64 * in the source file that invokes these functions.
67 #ifndef _NET_NETMAP_USER_H_
68 #define _NET_NETMAP_USER_H_
70 #define NETMAP_DEVICE_NAME "/dev/netmap"
74 * we can compile userspace apps with either cygwin or msvc,
75 * and we use _WIN32 to identify windows specific code
81 #endif /* __CYGWIN__ */
84 #undef NETMAP_DEVICE_NAME
85 #define NETMAP_DEVICE_NAME "/proc/sys/DosDevices/Global/netmap"
88 #include <sys/cygwin.h>
92 #include <sys/socket.h> /* apple needs sockaddr */
93 #include <net/if.h> /* IFNAMSIZ */
95 #include <string.h> /* memset */
96 #include <sys/time.h> /* gettimeofday */
99 #define likely(x) __builtin_expect(!!(x), 1)
100 #define unlikely(x) __builtin_expect(!!(x), 0)
101 #endif /* likely and unlikely */
103 #include <net/netmap.h>
106 #define _NETMAP_OFFSET(type, ptr, offset) \
107 ((type)(void *)((char *)(ptr) + (offset)))
109 #define NETMAP_IF(_base, _ofs) _NETMAP_OFFSET(struct netmap_if *, _base, _ofs)
111 #define NETMAP_TXRING(nifp, index) _NETMAP_OFFSET(struct netmap_ring *, \
112 nifp, (nifp)->ring_ofs[index] )
114 #define NETMAP_RXRING(nifp, index) _NETMAP_OFFSET(struct netmap_ring *, \
115 nifp, (nifp)->ring_ofs[index + (nifp)->ni_tx_rings + \
116 (nifp)->ni_host_tx_rings] )
118 #define NETMAP_BUF(ring, index) \
119 ((char *)(ring) + (ring)->buf_ofs + ((size_t)(index)*(ring)->nr_buf_size))
121 #define NETMAP_BUF_IDX(ring, buf) \
122 ( ((char *)(buf) - ((char *)(ring) + (ring)->buf_ofs) ) / \
123 (ring)->nr_buf_size )
125 static inline uint32_t
126 nm_ring_next(struct netmap_ring *r, uint32_t i)
128 return ( unlikely(i + 1 == r->num_slots) ? 0 : i + 1);
132 * Return 1 if we have pending transmissions in the tx ring.
133 * When everything is complete ring->head = ring->tail + 1 (modulo ring size)
136 nm_tx_pending(struct netmap_ring *r)
138 return nm_ring_next(r, r->tail) != r->head;
141 /* Compute the number of slots available in the netmap ring. We use
142 * ring->head as explained in the comment above nm_ring_empty(). */
143 static inline uint32_t
144 nm_ring_space(struct netmap_ring *ring)
146 int ret = ring->tail - ring->head;
148 ret += ring->num_slots;
152 #ifndef ND /* debug macros */
154 #define ND(_fmt, ...) do {} while(0)
155 #define D(_fmt, ...) \
157 struct timeval _t0; \
158 gettimeofday(&_t0, NULL); \
159 fprintf(stderr, "%03d.%06d %s [%d] " _fmt "\n", \
160 (int)(_t0.tv_sec % 1000), (int)_t0.tv_usec, \
161 __FUNCTION__, __LINE__, ##__VA_ARGS__); \
164 /* Rate limited version of "D", lps indicates how many per second */
165 #define RD(lps, format, ...) \
167 static int __t0, __cnt; \
168 struct timeval __xxts; \
169 gettimeofday(&__xxts, NULL); \
170 if (__t0 != __xxts.tv_sec) { \
171 __t0 = __xxts.tv_sec; \
174 if (__cnt++ < lps) { \
175 D(format, ##__VA_ARGS__); \
181 * this is a slightly optimized copy routine which rounds
182 * to multiple of 64 bytes and is often faster than dealing
183 * with other odd sizes. We assume there is enough room
184 * in the source and destination buffers.
187 nm_pkt_copy(const void *_src, void *_dst, int l)
189 const uint64_t *src = (const uint64_t *)_src;
190 uint64_t *dst = (uint64_t *)_dst;
192 if (unlikely(l >= 1024 || l % 64)) {
196 for (; likely(l > 0); l-=64) {
208 #ifdef NETMAP_WITH_LIBS
210 * Support for simple I/O libraries.
211 * Include other system headers required for compiling this.
214 #ifndef HAVE_NETMAP_WITH_LIBS
215 #define HAVE_NETMAP_WITH_LIBS
218 #include <sys/time.h>
219 #include <sys/mman.h>
220 #include <sys/ioctl.h>
221 #include <sys/errno.h> /* EINVAL */
222 #include <fcntl.h> /* O_RDWR */
223 #include <unistd.h> /* close() */
227 struct nm_pkthdr { /* first part is the same as pcap_pkthdr */
232 uint64_t flags; /* NM_MORE_PKTS etc */
233 #define NM_MORE_PKTS 1
235 struct netmap_slot *slot;
239 struct nm_stat { /* same as pcap_stat */
243 #ifdef WIN32 /* XXX or _WIN32 ? */
248 #define NM_ERRBUF_SIZE 512
251 struct nm_desc *self; /* point to self if netmap. */
255 int done_mmap; /* set if mem is the result of mmap */
256 struct netmap_if * const nifp;
257 uint16_t first_tx_ring, last_tx_ring, cur_tx_ring;
258 uint16_t first_rx_ring, last_rx_ring, cur_rx_ring;
259 struct nmreq req; /* also contains the nr_name = ifname */
260 struct nm_pkthdr hdr;
263 * The memory contains netmap_if, rings and then buffers.
264 * Given a pointer (e.g. to nm_inject) we can compare with
265 * mem/buf_start/buf_end to tell if it is a buffer or
266 * some other descriptor in our region.
267 * We also store a pointer to some ring as it helps in the
268 * translation from buffer indexes to addresses.
270 struct netmap_ring * const some_ring;
271 void * const buf_start;
272 void * const buf_end;
273 /* parameters from pcap_open_live */
279 /* save flags so we can restore them on close */
285 char msg[NM_ERRBUF_SIZE];
289 * when the descriptor is open correctly, d->self == d
290 * Eventually we should also use some magic number.
292 #define P2NMD(p) ((const struct nm_desc *)(p))
293 #define IS_NETMAP_DESC(d) ((d) && P2NMD(d)->self == P2NMD(d))
294 #define NETMAP_FD(d) (P2NMD(d)->fd)
297 * The callback, invoked on each received packet. Same as libpcap
299 typedef void (*nm_cb_t)(u_char *, const struct nm_pkthdr *, const u_char *d);
302 *--- the pcap-like API ---
304 * nm_open() opens a file descriptor, binds to a port and maps memory.
306 * ifname (netmap:foo or vale:foo) is the port name
307 * a suffix can indicate the following:
308 * ^ bind the host (sw) ring pair
309 * * bind host and NIC ring pairs
310 * -NN bind individual NIC ring pair
311 * {NN bind master side of pipe NN
312 * }NN bind slave side of pipe NN
313 * a suffix starting with / and the following flags,
316 * z zero copy monitor (both tx and rx)
317 * t monitor tx side (copy monitor)
318 * r monitor rx side (copy monitor)
319 * R bind only RX ring(s)
320 * T bind only TX ring(s)
322 * req provides the initial values of nmreq before parsing ifname.
323 * Remember that the ifname parsing will override the ring
324 * number in nm_ringid, and part of nm_flags;
325 * flags special functions, normally 0
326 * indicates which fields of *arg are significant
327 * arg special functions, normally NULL
328 * if passed a netmap_desc with mem != NULL,
329 * use that memory instead of mmap.
332 static struct nm_desc *nm_open(const char *ifname, const struct nmreq *req,
333 uint64_t flags, const struct nm_desc *arg);
336 * nm_open can import some fields from the parent descriptor.
337 * These flags control which ones.
338 * Also in flags you can specify NETMAP_NO_TX_POLL and NETMAP_DO_RX_POLL,
339 * which set the initial value for these flags.
340 * Note that the 16 low bits of the flags are reserved for data
341 * that may go into the nmreq.
344 NM_OPEN_NO_MMAP = 0x040000, /* reuse mmap from parent */
345 NM_OPEN_IFNAME = 0x080000, /* nr_name, nr_ringid, nr_flags */
346 NM_OPEN_ARG1 = 0x100000,
347 NM_OPEN_ARG2 = 0x200000,
348 NM_OPEN_ARG3 = 0x400000,
349 NM_OPEN_RING_CFG = 0x800000, /* tx|rx rings|slots */
353 * nm_close() closes and restores the port to its previous state
356 static int nm_close(struct nm_desc *);
359 * nm_mmap() do mmap or inherit from parent if the nr_arg2
360 * (memory block) matches.
363 static int nm_mmap(struct nm_desc *, const struct nm_desc *);
366 * nm_inject() is the same as pcap_inject()
367 * nm_dispatch() is the same as pcap_dispatch()
368 * nm_nextpkt() is the same as pcap_next()
371 static int nm_inject(struct nm_desc *, const void *, size_t);
372 static int nm_dispatch(struct nm_desc *, int, nm_cb_t, u_char *);
373 static u_char *nm_nextpkt(struct nm_desc *, struct nm_pkthdr *);
377 intptr_t _get_osfhandle(int); /* defined in io.h in windows */
380 * In windows we do not have yet native poll support, so we keep track
381 * of file descriptors associated to netmap ports to emulate poll on
382 * them and fall back on regular poll on other file descriptors.
384 struct win_netmap_fd_list {
385 struct win_netmap_fd_list *next;
387 HANDLE win_netmap_handle;
391 * list head containing all the netmap opened fd and their
392 * windows HANDLE counterparts
394 static struct win_netmap_fd_list *win_netmap_fd_list_head;
397 win_insert_fd_record(int fd)
399 struct win_netmap_fd_list *curr;
401 for (curr = win_netmap_fd_list_head; curr; curr = curr->next) {
402 if (fd == curr->win_netmap_fd) {
406 curr = calloc(1, sizeof(*curr));
407 curr->next = win_netmap_fd_list_head;
408 curr->win_netmap_fd = fd;
409 curr->win_netmap_handle = IntToPtr(_get_osfhandle(fd));
410 win_netmap_fd_list_head = curr;
414 win_remove_fd_record(int fd)
416 struct win_netmap_fd_list *curr = win_netmap_fd_list_head;
417 struct win_netmap_fd_list *prev = NULL;
418 for (; curr ; prev = curr, curr = curr->next) {
419 if (fd != curr->win_netmap_fd)
421 /* found the entry */
422 if (prev == NULL) { /* we are freeing the first entry */
423 win_netmap_fd_list_head = curr->next;
425 prev->next = curr->next;
433 win_get_netmap_handle(int fd)
435 struct win_netmap_fd_list *curr;
437 for (curr = win_netmap_fd_list_head; curr; curr = curr->next) {
438 if (fd == curr->win_netmap_fd) {
439 return curr->win_netmap_handle;
446 * we need to wrap ioctl and mmap, at least for the netmap file descriptors
450 * use this function only from netmap_user.h internal functions
451 * same as ioctl, returns 0 on success and -1 on error
454 win_nm_ioctl_internal(HANDLE h, int32_t ctlCode, void *arg)
456 DWORD bReturn = 0, szIn, szOut;
457 BOOL ioctlReturnStatus;
458 void *inParam = arg, *outParam = arg;
462 szIn = sizeof(POLL_REQUEST_DATA);
463 szOut = sizeof(POLL_REQUEST_DATA);
467 szOut = sizeof(void*);
468 inParam = NULL; /* nothing on input */
476 szIn = sizeof(struct nmreq);
477 szOut = sizeof(struct nmreq);
480 D("unsupported NIOCCONFIG!");
483 default: /* a regular ioctl */
484 D("invalid ioctl %x on netmap fd", ctlCode);
488 ioctlReturnStatus = DeviceIoControl(h,
489 ctlCode, inParam, szIn,
492 // XXX note windows returns 0 on error or async call, 1 on success
493 // we could call GetLastError() to figure out what happened
494 return ioctlReturnStatus ? 0 : -1;
498 * this function is what must be called from user-space programs
499 * same as ioctl, returns 0 on success and -1 on error
502 win_nm_ioctl(int fd, int32_t ctlCode, void *arg)
504 HANDLE h = win_get_netmap_handle(fd);
507 return ioctl(fd, ctlCode, arg);
509 return win_nm_ioctl_internal(h, ctlCode, arg);
513 #define ioctl win_nm_ioctl /* from now on, within this file ... */
516 * We cannot use the native mmap on windows
517 * The only parameter used is "fd", the other ones are just declared to
518 * make this signature comparable to the FreeBSD/Linux one
521 win32_mmap_emulated(void *addr, size_t length, int prot, int flags, int fd, int32_t offset)
523 HANDLE h = win_get_netmap_handle(fd);
526 return mmap(addr, length, prot, flags, fd, offset);
530 return win_nm_ioctl_internal(h, NETMAP_MMAP, &ret) ?
531 NULL : ret.pUsermodeVirtualAddress;
535 #define mmap win32_mmap_emulated
537 #include <sys/poll.h> /* XXX needed to use the structure pollfd */
540 win_nm_poll(struct pollfd *fds, int nfds, int timeout)
544 if (nfds != 1 || fds == NULL || (h = win_get_netmap_handle(fds->fd)) == NULL) {;
545 return poll(fds, nfds, timeout);
547 POLL_REQUEST_DATA prd;
549 prd.timeout = timeout;
550 prd.events = fds->events;
552 win_nm_ioctl_internal(h, NETMAP_POLL, &prd);
553 if ((prd.revents == POLLERR) || (prd.revents == STATUS_TIMEOUT)) {
560 #define poll win_nm_poll
563 win_nm_open(char* pathname, int flags)
566 if (strcmp(pathname, NETMAP_DEVICE_NAME) == 0) {
567 int fd = open(NETMAP_DEVICE_NAME, O_RDWR);
572 win_insert_fd_record(fd);
575 return open(pathname, flags);
579 #define open win_nm_open
586 if (win_get_netmap_handle(fd) != NULL) {
587 win_remove_fd_record(fd);
593 #define close win_nm_close
598 nm_is_identifier(const char *s, const char *e)
600 for (; s != e; s++) {
601 if (!isalnum(*s) && *s != '_') {
611 nm_parse(const char *ifname, struct nm_desc *d, char *err)
614 const char *port = NULL;
615 const char *vpname = NULL;
617 uint32_t nr_ringid = 0, nr_flags;
618 char errmsg[MAXERRMSG] = "", *tmp;
620 uint16_t nr_arg2 = 0;
621 enum { P_START, P_RNGSFXOK, P_GETNUM, P_FLAGS, P_FLAGSOK, P_MEMID } p_state;
625 is_vale = (ifname[0] == 'v');
627 port = index(ifname, ':');
629 snprintf(errmsg, MAXERRMSG,
630 "missing ':' in vale name");
634 if (!nm_is_identifier(ifname + 4, port)) {
635 snprintf(errmsg, MAXERRMSG, "invalid bridge name");
645 /* scan for a separator */
646 for (; *port && !index("-*^{}/@", *port); port++)
649 if (is_vale && !nm_is_identifier(vpname, port)) {
650 snprintf(errmsg, MAXERRMSG, "invalid bridge port name");
654 namelen = port - ifname;
655 if (namelen >= sizeof(d->req.nr_name)) {
656 snprintf(errmsg, MAXERRMSG, "name too long");
659 memcpy(d->req.nr_name, ifname, namelen);
660 d->req.nr_name[namelen] = '\0';
663 nr_flags = NR_REG_ALL_NIC; /* default for no suffix */
668 case '^': /* only SW ring */
669 nr_flags = NR_REG_SW;
670 p_state = P_RNGSFXOK;
672 case '*': /* NIC and SW */
673 nr_flags = NR_REG_NIC_SW;
674 p_state = P_RNGSFXOK;
676 case '-': /* one NIC ring pair */
677 nr_flags = NR_REG_ONE_NIC;
680 case '{': /* pipe (master endpoint) */
681 nr_flags = NR_REG_PIPE_MASTER;
684 case '}': /* pipe (slave endpoint) */
685 nr_flags = NR_REG_PIPE_SLAVE;
688 case '/': /* start of flags */
691 case '@': /* start of memid */
695 snprintf(errmsg, MAXERRMSG, "unknown modifier: '%c'", *port);
709 snprintf(errmsg, MAXERRMSG, "unexpected character: '%c'", *port);
715 num = strtol(port, &tmp, 10);
716 if (num < 0 || num >= NETMAP_RING_MASK) {
717 snprintf(errmsg, MAXERRMSG, "'%ld' out of range [0, %d)",
718 num, NETMAP_RING_MASK);
722 nr_ringid = num & NETMAP_RING_MASK;
723 p_state = P_RNGSFXOK;
734 nr_flags |= NR_EXCLUSIVE;
737 nr_flags |= NR_ZCOPY_MON;
740 nr_flags |= NR_MONITOR_TX;
743 nr_flags |= NR_MONITOR_RX;
746 nr_flags |= NR_RX_RINGS_ONLY;
749 nr_flags |= NR_TX_RINGS_ONLY;
752 snprintf(errmsg, MAXERRMSG, "unrecognized flag: '%c'", *port);
760 snprintf(errmsg, MAXERRMSG, "double setting of memid");
763 num = strtol(port, &tmp, 10);
765 snprintf(errmsg, MAXERRMSG, "invalid memid %ld, must be >0", num);
770 p_state = P_RNGSFXOK;
774 if (p_state != P_START && p_state != P_RNGSFXOK && p_state != P_FLAGSOK) {
775 snprintf(errmsg, MAXERRMSG, "unexpected end of port name");
778 ND("flags: %s %s %s %s",
779 (nr_flags & NR_EXCLUSIVE) ? "EXCLUSIVE" : "",
780 (nr_flags & NR_ZCOPY_MON) ? "ZCOPY_MON" : "",
781 (nr_flags & NR_MONITOR_TX) ? "MONITOR_TX" : "",
782 (nr_flags & NR_MONITOR_RX) ? "MONITOR_RX" : "");
784 d->req.nr_flags |= nr_flags;
785 d->req.nr_ringid |= nr_ringid;
786 d->req.nr_arg2 = nr_arg2;
795 strncpy(err, errmsg, MAXERRMSG);
800 * Try to open, return descriptor if successful, NULL otherwise.
801 * An invalid netmap name will return errno = 0;
802 * You can pass a pointer to a pre-filled nm_desc to add special
803 * parameters. Flags is used as follows
804 * NM_OPEN_NO_MMAP use the memory from arg, only XXX avoid mmap
805 * if the nr_arg2 (memory block) matches.
806 * NM_OPEN_ARG1 use req.nr_arg1 from arg
807 * NM_OPEN_ARG2 use req.nr_arg2 from arg
808 * NM_OPEN_RING_CFG user ring config from arg
810 static struct nm_desc *
811 nm_open(const char *ifname, const struct nmreq *req,
812 uint64_t new_flags, const struct nm_desc *arg)
814 struct nm_desc *d = NULL;
815 const struct nm_desc *parent = arg;
816 char errmsg[MAXERRMSG] = "";
819 if (strncmp(ifname, "netmap:", 7) &&
820 strncmp(ifname, NM_BDG_NAME, strlen(NM_BDG_NAME))) {
821 errno = 0; /* name not recognised, not an error */
825 d = (struct nm_desc *)calloc(1, sizeof(*d));
827 snprintf(errmsg, MAXERRMSG, "nm_desc alloc failure");
831 d->self = d; /* set this early so nm_close() works */
832 d->fd = open(NETMAP_DEVICE_NAME, O_RDWR);
834 snprintf(errmsg, MAXERRMSG, "cannot open /dev/netmap: %s", strerror(errno));
841 if (!(new_flags & NM_OPEN_IFNAME)) {
842 if (nm_parse(ifname, d, errmsg) < 0)
846 d->req.nr_version = NETMAP_API;
847 d->req.nr_ringid &= NETMAP_RING_MASK;
849 /* optionally import info from parent */
850 if (IS_NETMAP_DESC(parent) && new_flags) {
851 if (new_flags & NM_OPEN_ARG1)
852 D("overriding ARG1 %d", parent->req.nr_arg1);
853 d->req.nr_arg1 = new_flags & NM_OPEN_ARG1 ?
854 parent->req.nr_arg1 : 4;
855 if (new_flags & NM_OPEN_ARG2) {
856 D("overriding ARG2 %d", parent->req.nr_arg2);
857 d->req.nr_arg2 = parent->req.nr_arg2;
859 if (new_flags & NM_OPEN_ARG3)
860 D("overriding ARG3 %d", parent->req.nr_arg3);
861 d->req.nr_arg3 = new_flags & NM_OPEN_ARG3 ?
862 parent->req.nr_arg3 : 0;
863 if (new_flags & NM_OPEN_RING_CFG) {
864 D("overriding RING_CFG");
865 d->req.nr_tx_slots = parent->req.nr_tx_slots;
866 d->req.nr_rx_slots = parent->req.nr_rx_slots;
867 d->req.nr_tx_rings = parent->req.nr_tx_rings;
868 d->req.nr_rx_rings = parent->req.nr_rx_rings;
870 if (new_flags & NM_OPEN_IFNAME) {
871 D("overriding ifname %s ringid 0x%x flags 0x%x",
872 parent->req.nr_name, parent->req.nr_ringid,
873 parent->req.nr_flags);
874 memcpy(d->req.nr_name, parent->req.nr_name,
875 sizeof(d->req.nr_name));
876 d->req.nr_ringid = parent->req.nr_ringid;
877 d->req.nr_flags = parent->req.nr_flags;
880 /* add the *XPOLL flags */
881 d->req.nr_ringid |= new_flags & (NETMAP_NO_TX_POLL | NETMAP_DO_RX_POLL);
883 if (ioctl(d->fd, NIOCREGIF, &d->req)) {
884 snprintf(errmsg, MAXERRMSG, "NIOCREGIF failed: %s", strerror(errno));
888 nr_reg = d->req.nr_flags & NR_REG_MASK;
890 if (nr_reg == NR_REG_SW) { /* host stack */
891 d->first_tx_ring = d->last_tx_ring = d->req.nr_tx_rings;
892 d->first_rx_ring = d->last_rx_ring = d->req.nr_rx_rings;
893 } else if (nr_reg == NR_REG_ALL_NIC) { /* only nic */
894 d->first_tx_ring = 0;
895 d->first_rx_ring = 0;
896 d->last_tx_ring = d->req.nr_tx_rings - 1;
897 d->last_rx_ring = d->req.nr_rx_rings - 1;
898 } else if (nr_reg == NR_REG_NIC_SW) {
899 d->first_tx_ring = 0;
900 d->first_rx_ring = 0;
901 d->last_tx_ring = d->req.nr_tx_rings;
902 d->last_rx_ring = d->req.nr_rx_rings;
903 } else if (nr_reg == NR_REG_ONE_NIC) {
904 /* XXX check validity */
905 d->first_tx_ring = d->last_tx_ring =
906 d->first_rx_ring = d->last_rx_ring = d->req.nr_ringid & NETMAP_RING_MASK;
908 d->first_tx_ring = d->last_tx_ring = 0;
909 d->first_rx_ring = d->last_rx_ring = 0;
912 /* if parent is defined, do nm_mmap() even if NM_OPEN_NO_MMAP is set */
913 if ((!(new_flags & NM_OPEN_NO_MMAP) || parent) && nm_mmap(d, parent)) {
914 snprintf(errmsg, MAXERRMSG, "mmap failed: %s", strerror(errno));
918 #ifdef DEBUG_NETMAP_USER
919 { /* debugging code */
922 D("%s tx %d .. %d %d rx %d .. %d %d", ifname,
923 d->first_tx_ring, d->last_tx_ring, d->req.nr_tx_rings,
924 d->first_rx_ring, d->last_rx_ring, d->req.nr_rx_rings);
925 for (i = 0; i <= d->req.nr_tx_rings; i++) {
926 struct netmap_ring *r = NETMAP_TXRING(d->nifp, i);
927 D("TX%d %p h %d c %d t %d", i, r, r->head, r->cur, r->tail);
929 for (i = 0; i <= d->req.nr_rx_rings; i++) {
930 struct netmap_ring *r = NETMAP_RXRING(d->nifp, i);
931 D("RX%d %p h %d c %d t %d", i, r, r->head, r->cur, r->tail);
934 #endif /* debugging */
936 d->cur_tx_ring = d->first_tx_ring;
937 d->cur_rx_ring = d->first_rx_ring;
943 D("%s %s", errmsg, ifname);
950 nm_close(struct nm_desc *d)
953 * ugly trick to avoid unused warnings
955 static void *__xxzt[] __attribute__ ((unused)) =
956 { (void *)nm_open, (void *)nm_inject,
957 (void *)nm_dispatch, (void *)nm_nextpkt } ;
959 if (d == NULL || d->self != d)
961 if (d->done_mmap && d->mem)
962 munmap(d->mem, d->memsize);
967 bzero(d, sizeof(*d));
974 nm_mmap(struct nm_desc *d, const struct nm_desc *parent)
979 if (IS_NETMAP_DESC(parent) && parent->mem &&
980 parent->req.nr_arg2 == d->req.nr_arg2) {
981 /* do not mmap, inherit from parent */
982 D("do not mmap, inherit from parent");
983 d->memsize = parent->memsize;
984 d->mem = parent->mem;
986 /* XXX TODO: check if memsize is too large (or there is overflow) */
987 d->memsize = d->req.nr_memsize;
988 d->mem = mmap(0, d->memsize, PROT_WRITE | PROT_READ, MAP_SHARED,
990 if (d->mem == MAP_FAILED) {
996 struct netmap_if *nifp = NETMAP_IF(d->mem, d->req.nr_offset);
997 struct netmap_ring *r = NETMAP_RXRING(nifp, d->first_rx_ring);
998 if ((void *)r == (void *)nifp) {
999 /* the descriptor is open for TX only */
1000 r = NETMAP_TXRING(nifp, d->first_tx_ring);
1003 *(struct netmap_if **)(uintptr_t)&(d->nifp) = nifp;
1004 *(struct netmap_ring **)(uintptr_t)&d->some_ring = r;
1005 *(void **)(uintptr_t)&d->buf_start = NETMAP_BUF(r, 0);
1006 *(void **)(uintptr_t)&d->buf_end =
1007 (char *)d->mem + d->memsize;
1017 * Same prototype as pcap_inject(), only need to cast.
1020 nm_inject(struct nm_desc *d, const void *buf, size_t size)
1022 u_int c, n = d->last_tx_ring - d->first_tx_ring + 1,
1023 ri = d->cur_tx_ring;
1025 for (c = 0; c < n ; c++, ri++) {
1026 /* compute current ring to use */
1027 struct netmap_ring *ring;
1031 if (ri > d->last_tx_ring)
1032 ri = d->first_tx_ring;
1033 ring = NETMAP_TXRING(d->nifp, ri);
1036 while (rem > ring->nr_buf_size && j != ring->tail) {
1037 rem -= ring->nr_buf_size;
1038 j = nm_ring_next(ring, j);
1040 if (j == ring->tail && rem > 0)
1044 idx = ring->slot[i].buf_idx;
1045 ring->slot[i].len = ring->nr_buf_size;
1046 ring->slot[i].flags = NS_MOREFRAG;
1047 nm_pkt_copy(buf, NETMAP_BUF(ring, idx), ring->nr_buf_size);
1048 i = nm_ring_next(ring, i);
1049 buf = (const char *)buf + ring->nr_buf_size;
1051 idx = ring->slot[i].buf_idx;
1052 ring->slot[i].len = rem;
1053 ring->slot[i].flags = 0;
1054 nm_pkt_copy(buf, NETMAP_BUF(ring, idx), rem);
1055 ring->head = ring->cur = nm_ring_next(ring, i);
1056 d->cur_tx_ring = ri;
1059 return 0; /* fail */
1063 * Same prototype as pcap_dispatch(), only need to cast.
1066 nm_dispatch(struct nm_desc *d, int cnt, nm_cb_t cb, u_char *arg)
1068 int n = d->last_rx_ring - d->first_rx_ring + 1;
1069 int c, got = 0, ri = d->cur_rx_ring;
1071 d->hdr.flags = NM_MORE_PKTS;
1076 /* cnt == -1 means infinite, but rings have a finite amount
1077 * of buffers and the int is large enough that we never wrap,
1078 * so we can omit checking for -1
1080 for (c=0; c < n && cnt != got; c++, ri++) {
1081 /* compute current ring to use */
1082 struct netmap_ring *ring;
1084 if (ri > d->last_rx_ring)
1085 ri = d->first_rx_ring;
1086 ring = NETMAP_RXRING(d->nifp, ri);
1087 for ( ; !nm_ring_empty(ring) && cnt != got; got++) {
1090 struct netmap_slot *slot;
1091 if (d->hdr.buf) { /* from previous round */
1092 cb(arg, &d->hdr, d->hdr.buf);
1095 slot = &ring->slot[i];
1096 idx = slot->buf_idx;
1097 /* d->cur_rx_ring doesn't change inside this loop, but
1098 * set it here, so it reflects d->hdr.buf's ring */
1099 d->cur_rx_ring = ri;
1101 oldbuf = d->hdr.buf = (u_char *)NETMAP_BUF(ring, idx);
1102 // __builtin_prefetch(buf);
1103 d->hdr.len = d->hdr.caplen = slot->len;
1104 while (slot->flags & NS_MOREFRAG) {
1106 u_int oldlen = slot->len;
1107 i = nm_ring_next(ring, i);
1108 slot = &ring->slot[i];
1109 d->hdr.len += slot->len;
1110 nbuf = (u_char *)NETMAP_BUF(ring, slot->buf_idx);
1111 if (oldbuf != NULL && nbuf - oldbuf == (int)ring->nr_buf_size &&
1112 oldlen == ring->nr_buf_size) {
1113 d->hdr.caplen += slot->len;
1119 d->hdr.ts = ring->ts;
1120 ring->head = ring->cur = nm_ring_next(ring, i);
1123 if (d->hdr.buf) { /* from previous round */
1125 cb(arg, &d->hdr, d->hdr.buf);
1131 nm_nextpkt(struct nm_desc *d, struct nm_pkthdr *hdr)
1133 int ri = d->cur_rx_ring;
1136 /* compute current ring to use */
1137 struct netmap_ring *ring = NETMAP_RXRING(d->nifp, ri);
1138 if (!nm_ring_empty(ring)) {
1139 u_int i = ring->cur;
1140 u_int idx = ring->slot[i].buf_idx;
1141 u_char *buf = (u_char *)NETMAP_BUF(ring, idx);
1143 // __builtin_prefetch(buf);
1145 hdr->len = hdr->caplen = ring->slot[i].len;
1146 ring->cur = nm_ring_next(ring, i);
1147 /* we could postpone advancing head if we want
1148 * to hold the buffer. This can be supported in
1151 ring->head = ring->cur;
1152 d->cur_rx_ring = ri;
1156 if (ri > d->last_rx_ring)
1157 ri = d->first_rx_ring;
1158 } while (ri != d->cur_rx_ring);
1159 return NULL; /* nothing found */
1162 #endif /* !HAVE_NETMAP_WITH_LIBS */
1164 #endif /* NETMAP_WITH_LIBS */
1166 #endif /* _NET_NETMAP_USER_H_ */