]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/net/netmap_user.h
Teach if_smsc to get MAC from bootargs.
[FreeBSD/FreeBSD.git] / sys / net / netmap_user.h
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (C) 2011-2016 Universita` di Pisa
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
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  *
32  * Functions and macros to manipulate netmap structures and packets
33  * in userspace. See netmap(4) for more information.
34  *
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)
41  *
42  * From there:
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.
46  *
47  *      ring->slot[i] gives us the i-th slot (we can access
48  *              directly len, flags, buf_idx)
49  *
50  *      char *buf = NETMAP_BUF(ring, x) returns a pointer to
51  *              the buffer numbered x
52  *
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);
56  *
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
61  * packets out.
62  *
63  * In order to use these, include #define NETMAP_WITH_LIBS
64  * in the source file that invokes these functions.
65  */
66
67 #ifndef _NET_NETMAP_USER_H_
68 #define _NET_NETMAP_USER_H_
69
70 #define NETMAP_DEVICE_NAME "/dev/netmap"
71
72 #ifdef __CYGWIN__
73 /*
74  * we can compile userspace apps with either cygwin or msvc,
75  * and we use _WIN32 to identify windows specific code
76  */
77 #ifndef _WIN32
78 #define _WIN32
79 #endif  /* _WIN32 */
80
81 #endif  /* __CYGWIN__ */
82
83 #ifdef _WIN32
84 #undef NETMAP_DEVICE_NAME
85 #define NETMAP_DEVICE_NAME "/proc/sys/DosDevices/Global/netmap"
86 #include <windows.h>
87 #include <WinDef.h>
88 #include <sys/cygwin.h>
89 #endif /* _WIN32 */
90
91 #include <stdint.h>
92 #include <sys/socket.h>         /* apple needs sockaddr */
93 #include <net/if.h>             /* IFNAMSIZ */
94 #include <ctype.h>
95 #include <string.h>     /* memset */
96 #include <sys/time.h>   /* gettimeofday */
97
98 #ifndef likely
99 #define likely(x)       __builtin_expect(!!(x), 1)
100 #define unlikely(x)     __builtin_expect(!!(x), 0)
101 #endif /* likely and unlikely */
102
103 #include <net/netmap.h>
104
105 /* helper macro */
106 #define _NETMAP_OFFSET(type, ptr, offset) \
107         ((type)(void *)((char *)(ptr) + (offset)))
108
109 #define NETMAP_IF(_base, _ofs)  _NETMAP_OFFSET(struct netmap_if *, _base, _ofs)
110
111 #define NETMAP_TXRING(nifp, index) _NETMAP_OFFSET(struct netmap_ring *, \
112         nifp, (nifp)->ring_ofs[index] )
113
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] )
117
118 #define NETMAP_BUF(ring, index)                         \
119         ((char *)(ring) + (ring)->buf_ofs + ((size_t)(index)*(ring)->nr_buf_size))
120
121 #define NETMAP_BUF_IDX(ring, buf)                       \
122         ( ((char *)(buf) - ((char *)(ring) + (ring)->buf_ofs) ) / \
123                 (ring)->nr_buf_size )
124
125 static inline uint32_t
126 nm_ring_next(struct netmap_ring *r, uint32_t i)
127 {
128         return ( unlikely(i + 1 == r->num_slots) ? 0 : i + 1);
129 }
130
131 /*
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)
134  */
135 static inline int
136 nm_tx_pending(struct netmap_ring *r)
137 {
138         return nm_ring_next(r, r->tail) != r->head;
139 }
140
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)
145 {
146         int ret = ring->tail - ring->head;
147         if (ret < 0)
148                 ret += ring->num_slots;
149         return ret;
150 }
151
152 #ifndef ND /* debug macros */
153 /* debug support */
154 #define ND(_fmt, ...) do {} while(0)
155 #define D(_fmt, ...)                                            \
156         do {                                                    \
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__);     \
162         } while (0)
163
164 /* Rate limited version of "D", lps indicates how many per second */
165 #define RD(lps, format, ...)                                    \
166     do {                                                        \
167         static int __t0, __cnt;                                 \
168         struct timeval __xxts;                                  \
169         gettimeofday(&__xxts, NULL);                            \
170         if (__t0 != __xxts.tv_sec) {                            \
171             __t0 = __xxts.tv_sec;                               \
172             __cnt = 0;                                          \
173         }                                                       \
174         if (__cnt++ < lps) {                                    \
175             D(format, ##__VA_ARGS__);                           \
176         }                                                       \
177     } while (0)
178 #endif
179
180 /*
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.
185  */
186 static inline void
187 nm_pkt_copy(const void *_src, void *_dst, int l)
188 {
189         const uint64_t *src = (const uint64_t *)_src;
190         uint64_t *dst = (uint64_t *)_dst;
191
192         if (unlikely(l >= 1024 || l % 64)) {
193                 memcpy(dst, src, l);
194                 return;
195         }
196         for (; likely(l > 0); l-=64) {
197                 *dst++ = *src++;
198                 *dst++ = *src++;
199                 *dst++ = *src++;
200                 *dst++ = *src++;
201                 *dst++ = *src++;
202                 *dst++ = *src++;
203                 *dst++ = *src++;
204                 *dst++ = *src++;
205         }
206 }
207
208 #ifdef NETMAP_WITH_LIBS
209 /*
210  * Support for simple I/O libraries.
211  * Include other system headers required for compiling this.
212  */
213
214 #ifndef HAVE_NETMAP_WITH_LIBS
215 #define HAVE_NETMAP_WITH_LIBS
216
217 #include <stdio.h>
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() */
224 #include <signal.h>
225 #include <stdlib.h>
226
227 struct nm_pkthdr {      /* first part is the same as pcap_pkthdr */
228         struct timeval  ts;
229         uint32_t        caplen;
230         uint32_t        len;
231
232         uint64_t flags; /* NM_MORE_PKTS etc */
233 #define NM_MORE_PKTS    1
234         struct nm_desc *d;
235         struct netmap_slot *slot;
236         uint8_t *buf;
237 };
238
239 struct nm_stat {        /* same as pcap_stat    */
240         u_int   ps_recv;
241         u_int   ps_drop;
242         u_int   ps_ifdrop;
243 #ifdef WIN32 /* XXX or _WIN32 ? */
244         u_int   bs_capt;
245 #endif /* WIN32 */
246 };
247
248 #define NM_ERRBUF_SIZE  512
249
250 struct nm_desc {
251         struct nm_desc *self; /* point to self if netmap. */
252         int fd;
253         void *mem;
254         size_t memsize;
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;
261
262         /*
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.
269          */
270         struct netmap_ring * const some_ring;
271         void * const buf_start;
272         void * const buf_end;
273         /* parameters from pcap_open_live */
274         int snaplen;
275         int promisc;
276         int to_ms;
277         char *errbuf;
278
279         /* save flags so we can restore them on close */
280         uint32_t if_flags;
281         uint32_t if_reqcap;
282         uint32_t if_curcap;
283
284         struct nm_stat st;
285         char msg[NM_ERRBUF_SIZE];
286 };
287
288 /*
289  * when the descriptor is open correctly, d->self == d
290  * Eventually we should also use some magic number.
291  */
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)
295
296 /*
297  * The callback, invoked on each received packet. Same as libpcap
298  */
299 typedef void (*nm_cb_t)(u_char *, const struct nm_pkthdr *, const u_char *d);
300
301 /*
302  *--- the pcap-like API ---
303  *
304  * nm_open() opens a file descriptor, binds to a port and maps memory.
305  *
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,
314  *              in any order:
315  *              x               exclusive access
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)
321  *
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.
330  */
331
332 static struct nm_desc *nm_open(const char *ifname, const struct nmreq *req,
333         uint64_t flags, const struct nm_desc *arg);
334
335 /*
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.
342  */
343 enum {
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 */
350 };
351
352 /*
353  * nm_close()   closes and restores the port to its previous state
354  */
355
356 static int nm_close(struct nm_desc *);
357
358 /*
359  * nm_mmap()    do mmap or inherit from parent if the nr_arg2
360  *              (memory block) matches.
361  */
362
363 static int nm_mmap(struct nm_desc *, const struct nm_desc *);
364
365 /*
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()
369  */
370
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 *);
374
375 #ifdef _WIN32
376
377 intptr_t _get_osfhandle(int); /* defined in io.h in windows */
378
379 /*
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.
383  */
384 struct win_netmap_fd_list {
385         struct win_netmap_fd_list *next;
386         int win_netmap_fd;
387         HANDLE win_netmap_handle;
388 };
389
390 /*
391  * list head containing all the netmap opened fd and their
392  * windows HANDLE counterparts
393  */
394 static struct win_netmap_fd_list *win_netmap_fd_list_head;
395
396 static void
397 win_insert_fd_record(int fd)
398 {
399         struct win_netmap_fd_list *curr;
400
401         for (curr = win_netmap_fd_list_head; curr; curr = curr->next) {
402                 if (fd == curr->win_netmap_fd) {
403                         return;
404                 }
405         }
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;
411 }
412
413 void
414 win_remove_fd_record(int fd)
415 {
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)
420                         continue;
421                 /* found the entry */
422                 if (prev == NULL) { /* we are freeing the first entry */
423                         win_netmap_fd_list_head = curr->next;
424                 } else {
425                         prev->next = curr->next;
426                 }
427                 free(curr);
428                 break;
429         }
430 }
431
432 HANDLE
433 win_get_netmap_handle(int fd)
434 {
435         struct win_netmap_fd_list *curr;
436
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;
440                 }
441         }
442         return NULL;
443 }
444
445 /*
446  * we need to wrap ioctl and mmap, at least for the netmap file descriptors
447  */
448
449 /*
450  * use this function only from netmap_user.h internal functions
451  * same as ioctl, returns 0 on success and -1 on error
452  */
453 static int
454 win_nm_ioctl_internal(HANDLE h, int32_t ctlCode, void *arg)
455 {
456         DWORD bReturn = 0, szIn, szOut;
457         BOOL ioctlReturnStatus;
458         void *inParam = arg, *outParam = arg;
459
460         switch (ctlCode) {
461         case NETMAP_POLL:
462                 szIn = sizeof(POLL_REQUEST_DATA);
463                 szOut = sizeof(POLL_REQUEST_DATA);
464                 break;
465         case NETMAP_MMAP:
466                 szIn = 0;
467                 szOut = sizeof(void*);
468                 inParam = NULL; /* nothing on input */
469                 break;
470         case NIOCTXSYNC:
471         case NIOCRXSYNC:
472                 szIn = 0;
473                 szOut = 0;
474                 break;
475         case NIOCREGIF:
476                 szIn = sizeof(struct nmreq);
477                 szOut = sizeof(struct nmreq);
478                 break;
479         case NIOCCONFIG:
480                 D("unsupported NIOCCONFIG!");
481                 return -1;
482
483         default: /* a regular ioctl */
484                 D("invalid ioctl %x on netmap fd", ctlCode);
485                 return -1;
486         }
487
488         ioctlReturnStatus = DeviceIoControl(h,
489                                 ctlCode, inParam, szIn,
490                                 outParam, szOut,
491                                 &bReturn, NULL);
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;
495 }
496
497 /*
498  * this function is what must be called from user-space programs
499  * same as ioctl, returns 0 on success and -1 on error
500  */
501 static int
502 win_nm_ioctl(int fd, int32_t ctlCode, void *arg)
503 {
504         HANDLE h = win_get_netmap_handle(fd);
505
506         if (h == NULL) {
507                 return ioctl(fd, ctlCode, arg);
508         } else {
509                 return win_nm_ioctl_internal(h, ctlCode, arg);
510         }
511 }
512
513 #define ioctl win_nm_ioctl /* from now on, within this file ... */
514
515 /*
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
519  */
520 static void *
521 win32_mmap_emulated(void *addr, size_t length, int prot, int flags, int fd, int32_t offset)
522 {
523         HANDLE h = win_get_netmap_handle(fd);
524
525         if (h == NULL) {
526                 return mmap(addr, length, prot, flags, fd, offset);
527         } else {
528                 MEMORY_ENTRY ret;
529
530                 return win_nm_ioctl_internal(h, NETMAP_MMAP, &ret) ?
531                         NULL : ret.pUsermodeVirtualAddress;
532         }
533 }
534
535 #define mmap win32_mmap_emulated
536
537 #include <sys/poll.h> /* XXX needed to use the structure pollfd */
538
539 static int
540 win_nm_poll(struct pollfd *fds, int nfds, int timeout)
541 {
542         HANDLE h;
543
544         if (nfds != 1 || fds == NULL || (h = win_get_netmap_handle(fds->fd)) == NULL) {;
545                 return poll(fds, nfds, timeout);
546         } else {
547                 POLL_REQUEST_DATA prd;
548
549                 prd.timeout = timeout;
550                 prd.events = fds->events;
551
552                 win_nm_ioctl_internal(h, NETMAP_POLL, &prd);
553                 if ((prd.revents == POLLERR) || (prd.revents == STATUS_TIMEOUT)) {
554                         return -1;
555                 }
556                 return 1;
557         }
558 }
559
560 #define poll win_nm_poll
561
562 static int
563 win_nm_open(char* pathname, int flags)
564 {
565
566         if (strcmp(pathname, NETMAP_DEVICE_NAME) == 0) {
567                 int fd = open(NETMAP_DEVICE_NAME, O_RDWR);
568                 if (fd < 0) {
569                         return -1;
570                 }
571
572                 win_insert_fd_record(fd);
573                 return fd;
574         } else {
575                 return open(pathname, flags);
576         }
577 }
578
579 #define open win_nm_open
580
581 static int
582 win_nm_close(int fd)
583 {
584         if (fd != -1) {
585                 close(fd);
586                 if (win_get_netmap_handle(fd) != NULL) {
587                         win_remove_fd_record(fd);
588                 }
589         }
590         return 0;
591 }
592
593 #define close win_nm_close
594
595 #endif /* _WIN32 */
596
597 static int
598 nm_is_identifier(const char *s, const char *e)
599 {
600         for (; s != e; s++) {
601                 if (!isalnum(*s) && *s != '_') {
602                         return 0;
603                 }
604         }
605
606         return 1;
607 }
608
609 #define MAXERRMSG 80
610 static int
611 nm_parse(const char *ifname, struct nm_desc *d, char *err)
612 {
613         int is_vale;
614         const char *port = NULL;
615         const char *vpname = NULL;
616         u_int namelen;
617         uint32_t nr_ringid = 0, nr_flags;
618         char errmsg[MAXERRMSG] = "", *tmp;
619         long num;
620         uint16_t nr_arg2 = 0;
621         enum { P_START, P_RNGSFXOK, P_GETNUM, P_FLAGS, P_FLAGSOK, P_MEMID } p_state;
622
623         errno = 0;
624
625         is_vale = (ifname[0] == 'v');
626         if (is_vale) {
627                 port = index(ifname, ':');
628                 if (port == NULL) {
629                         snprintf(errmsg, MAXERRMSG,
630                                  "missing ':' in vale name");
631                         goto fail;
632                 }
633
634                 if (!nm_is_identifier(ifname + 4, port)) {
635                         snprintf(errmsg, MAXERRMSG, "invalid bridge name");
636                         goto fail;
637                 }
638
639                 vpname = ++port;
640         } else {
641                 ifname += 7;
642                 port = ifname;
643         }
644
645         /* scan for a separator */
646         for (; *port && !index("-*^{}/@", *port); port++)
647                 ;
648
649         if (is_vale && !nm_is_identifier(vpname, port)) {
650                 snprintf(errmsg, MAXERRMSG, "invalid bridge port name");
651                 goto fail;
652         }
653
654         namelen = port - ifname;
655         if (namelen >= sizeof(d->req.nr_name)) {
656                 snprintf(errmsg, MAXERRMSG, "name too long");
657                 goto fail;
658         }
659         memcpy(d->req.nr_name, ifname, namelen);
660         d->req.nr_name[namelen] = '\0';
661
662         p_state = P_START;
663         nr_flags = NR_REG_ALL_NIC; /* default for no suffix */
664         while (*port) {
665                 switch (p_state) {
666                 case P_START:
667                         switch (*port) {
668                         case '^': /* only SW ring */
669                                 nr_flags = NR_REG_SW;
670                                 p_state = P_RNGSFXOK;
671                                 break;
672                         case '*': /* NIC and SW */
673                                 nr_flags = NR_REG_NIC_SW;
674                                 p_state = P_RNGSFXOK;
675                                 break;
676                         case '-': /* one NIC ring pair */
677                                 nr_flags = NR_REG_ONE_NIC;
678                                 p_state = P_GETNUM;
679                                 break;
680                         case '{': /* pipe (master endpoint) */
681                                 nr_flags = NR_REG_PIPE_MASTER;
682                                 p_state = P_GETNUM;
683                                 break;
684                         case '}': /* pipe (slave endpoint) */
685                                 nr_flags = NR_REG_PIPE_SLAVE;
686                                 p_state = P_GETNUM;
687                                 break;
688                         case '/': /* start of flags */
689                                 p_state = P_FLAGS;
690                                 break;
691                         case '@': /* start of memid */
692                                 p_state = P_MEMID;
693                                 break;
694                         default:
695                                 snprintf(errmsg, MAXERRMSG, "unknown modifier: '%c'", *port);
696                                 goto fail;
697                         }
698                         port++;
699                         break;
700                 case P_RNGSFXOK:
701                         switch (*port) {
702                         case '/':
703                                 p_state = P_FLAGS;
704                                 break;
705                         case '@':
706                                 p_state = P_MEMID;
707                                 break;
708                         default:
709                                 snprintf(errmsg, MAXERRMSG, "unexpected character: '%c'", *port);
710                                 goto fail;
711                         }
712                         port++;
713                         break;
714                 case P_GETNUM:
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);
719                                 goto fail;
720                         }
721                         port = tmp;
722                         nr_ringid = num & NETMAP_RING_MASK;
723                         p_state = P_RNGSFXOK;
724                         break;
725                 case P_FLAGS:
726                 case P_FLAGSOK:
727                         if (*port == '@') {
728                                 port++;
729                                 p_state = P_MEMID;
730                                 break;
731                         }
732                         switch (*port) {
733                         case 'x':
734                                 nr_flags |= NR_EXCLUSIVE;
735                                 break;
736                         case 'z':
737                                 nr_flags |= NR_ZCOPY_MON;
738                                 break;
739                         case 't':
740                                 nr_flags |= NR_MONITOR_TX;
741                                 break;
742                         case 'r':
743                                 nr_flags |= NR_MONITOR_RX;
744                                 break;
745                         case 'R':
746                                 nr_flags |= NR_RX_RINGS_ONLY;
747                                 break;
748                         case 'T':
749                                 nr_flags |= NR_TX_RINGS_ONLY;
750                                 break;
751                         default:
752                                 snprintf(errmsg, MAXERRMSG, "unrecognized flag: '%c'", *port);
753                                 goto fail;
754                         }
755                         port++;
756                         p_state = P_FLAGSOK;
757                         break;
758                 case P_MEMID:
759                         if (nr_arg2 != 0) {
760                                 snprintf(errmsg, MAXERRMSG, "double setting of memid");
761                                 goto fail;
762                         }
763                         num = strtol(port, &tmp, 10);
764                         if (num <= 0) {
765                                 snprintf(errmsg, MAXERRMSG, "invalid memid %ld, must be >0", num);
766                                 goto fail;
767                         }
768                         port = tmp;
769                         nr_arg2 = num;
770                         p_state = P_RNGSFXOK;
771                         break;
772                 }
773         }
774         if (p_state != P_START && p_state != P_RNGSFXOK && p_state != P_FLAGSOK) {
775                 snprintf(errmsg, MAXERRMSG, "unexpected end of port name");
776                 goto fail;
777         }
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" : "");
783
784         d->req.nr_flags |= nr_flags;
785         d->req.nr_ringid |= nr_ringid;
786         d->req.nr_arg2 = nr_arg2;
787
788         d->self = d;
789
790         return 0;
791 fail:
792         if (!errno)
793                 errno = EINVAL;
794         if (err)
795                 strncpy(err, errmsg, MAXERRMSG);
796         return -1;
797 }
798
799 /*
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
809  */
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)
813 {
814         struct nm_desc *d = NULL;
815         const struct nm_desc *parent = arg;
816         char errmsg[MAXERRMSG] = "";
817         uint32_t nr_reg;
818
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 */
822                 return NULL;
823         }
824
825         d = (struct nm_desc *)calloc(1, sizeof(*d));
826         if (d == NULL) {
827                 snprintf(errmsg, MAXERRMSG, "nm_desc alloc failure");
828                 errno = ENOMEM;
829                 return NULL;
830         }
831         d->self = d;    /* set this early so nm_close() works */
832         d->fd = open(NETMAP_DEVICE_NAME, O_RDWR);
833         if (d->fd < 0) {
834                 snprintf(errmsg, MAXERRMSG, "cannot open /dev/netmap: %s", strerror(errno));
835                 goto fail;
836         }
837
838         if (req)
839                 d->req = *req;
840
841         if (!(new_flags & NM_OPEN_IFNAME)) {
842                 if (nm_parse(ifname, d, errmsg) < 0)
843                         goto fail;
844         }
845
846         d->req.nr_version = NETMAP_API;
847         d->req.nr_ringid &= NETMAP_RING_MASK;
848
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;
858                 }
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;
869                 }
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;
878                 }
879         }
880         /* add the *XPOLL flags */
881         d->req.nr_ringid |= new_flags & (NETMAP_NO_TX_POLL | NETMAP_DO_RX_POLL);
882
883         if (ioctl(d->fd, NIOCREGIF, &d->req)) {
884                 snprintf(errmsg, MAXERRMSG, "NIOCREGIF failed: %s", strerror(errno));
885                 goto fail;
886         }
887
888         nr_reg = d->req.nr_flags & NR_REG_MASK;
889
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;
907         } else { /* pipes */
908                 d->first_tx_ring = d->last_tx_ring = 0;
909                 d->first_rx_ring = d->last_rx_ring = 0;
910         }
911
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));
915                 goto fail;
916         }
917
918 #ifdef DEBUG_NETMAP_USER
919     { /* debugging code */
920         int i;
921
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);
928         }
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);
932         }
933     }
934 #endif /* debugging */
935
936         d->cur_tx_ring = d->first_tx_ring;
937         d->cur_rx_ring = d->first_rx_ring;
938         return d;
939
940 fail:
941         nm_close(d);
942         if (errmsg[0])
943                 D("%s %s", errmsg, ifname);
944         if (errno == 0)
945                 errno = EINVAL;
946         return NULL;
947 }
948
949 static int
950 nm_close(struct nm_desc *d)
951 {
952         /*
953          * ugly trick to avoid unused warnings
954          */
955         static void *__xxzt[] __attribute__ ((unused))  =
956                 { (void *)nm_open, (void *)nm_inject,
957                   (void *)nm_dispatch, (void *)nm_nextpkt } ;
958
959         if (d == NULL || d->self != d)
960                 return EINVAL;
961         if (d->done_mmap && d->mem)
962                 munmap(d->mem, d->memsize);
963         if (d->fd != -1) {
964                 close(d->fd);
965         }
966
967         bzero(d, sizeof(*d));
968         free(d);
969         return 0;
970 }
971
972
973 static int
974 nm_mmap(struct nm_desc *d, const struct nm_desc *parent)
975 {
976         if (d->done_mmap)
977                 return 0;
978
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;
985         } else {
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,
989                                 d->fd, 0);
990                 if (d->mem == MAP_FAILED) {
991                         goto fail;
992                 }
993                 d->done_mmap = 1;
994         }
995         {
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);
1001                 }
1002
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;
1008         }
1009
1010         return 0;
1011
1012 fail:
1013         return EINVAL;
1014 }
1015
1016 /*
1017  * Same prototype as pcap_inject(), only need to cast.
1018  */
1019 static int
1020 nm_inject(struct nm_desc *d, const void *buf, size_t size)
1021 {
1022         u_int c, n = d->last_tx_ring - d->first_tx_ring + 1,
1023                 ri = d->cur_tx_ring;
1024
1025         for (c = 0; c < n ; c++, ri++) {
1026                 /* compute current ring to use */
1027                 struct netmap_ring *ring;
1028                 uint32_t i, j, idx;
1029                 size_t rem;
1030
1031                 if (ri > d->last_tx_ring)
1032                         ri = d->first_tx_ring;
1033                 ring = NETMAP_TXRING(d->nifp, ri);
1034                 rem = size;
1035                 j = ring->cur;
1036                 while (rem > ring->nr_buf_size && j != ring->tail) {
1037                         rem -= ring->nr_buf_size;
1038                         j = nm_ring_next(ring, j);
1039                 }
1040                 if (j == ring->tail && rem > 0)
1041                         continue;
1042                 i = ring->cur;
1043                 while (i != j) {
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;
1050                 }
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;
1057                 return size;
1058         }
1059         return 0; /* fail */
1060 }
1061
1062 /*
1063  * Same prototype as pcap_dispatch(), only need to cast.
1064  */
1065 static int
1066 nm_dispatch(struct nm_desc *d, int cnt, nm_cb_t cb, u_char *arg)
1067 {
1068         int n = d->last_rx_ring - d->first_rx_ring + 1;
1069         int c, got = 0, ri = d->cur_rx_ring;
1070         d->hdr.buf = NULL;
1071         d->hdr.flags = NM_MORE_PKTS;
1072         d->hdr.d = d;
1073
1074         if (cnt == 0)
1075                 cnt = -1;
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
1079          */
1080         for (c=0; c < n && cnt != got; c++, ri++) {
1081                 /* compute current ring to use */
1082                 struct netmap_ring *ring;
1083
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++) {
1088                         u_int idx, i;
1089                         u_char *oldbuf;
1090                         struct netmap_slot *slot;
1091                         if (d->hdr.buf) { /* from previous round */
1092                                 cb(arg, &d->hdr, d->hdr.buf);
1093                         }
1094                         i = ring->cur;
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;
1100                         d->hdr.slot = slot;
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) {
1105                                 u_char *nbuf;
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;
1114                                         oldbuf = nbuf;
1115                                 } else {
1116                                         oldbuf = NULL;
1117                                 }
1118                         }
1119                         d->hdr.ts = ring->ts;
1120                         ring->head = ring->cur = nm_ring_next(ring, i);
1121                 }
1122         }
1123         if (d->hdr.buf) { /* from previous round */
1124                 d->hdr.flags = 0;
1125                 cb(arg, &d->hdr, d->hdr.buf);
1126         }
1127         return got;
1128 }
1129
1130 static u_char *
1131 nm_nextpkt(struct nm_desc *d, struct nm_pkthdr *hdr)
1132 {
1133         int ri = d->cur_rx_ring;
1134
1135         do {
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);
1142
1143                         // __builtin_prefetch(buf);
1144                         hdr->ts = ring->ts;
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
1149                          * the future.
1150                          */
1151                         ring->head = ring->cur;
1152                         d->cur_rx_ring = ri;
1153                         return buf;
1154                 }
1155                 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 */
1160 }
1161
1162 #endif /* !HAVE_NETMAP_WITH_LIBS */
1163
1164 #endif /* NETMAP_WITH_LIBS */
1165
1166 #endif /* _NET_NETMAP_USER_H_ */