FreeBSD/Linux Kernel Cross Reference
sys/net/netmap_user.h
1 /*
2 * Copyright (C) 2011-2016 Universita` di Pisa
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 *
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25 * SUCH DAMAGE.
26 */
27
28 /*
29 * $FreeBSD$
30 *
31 * Functions and macros to manipulate netmap structures and packets
32 * in userspace. See netmap(4) for more information.
33 *
34 * The address of the struct netmap_if, say nifp, is computed from the
35 * value returned from ioctl(.., NIOCREG, ...) and the mmap region:
36 * ioctl(fd, NIOCREG, &req);
37 * mem = mmap(0, ... );
38 * nifp = NETMAP_IF(mem, req.nr_nifp);
39 * (so simple, we could just do it manually)
40 *
41 * From there:
42 * struct netmap_ring *NETMAP_TXRING(nifp, index)
43 * struct netmap_ring *NETMAP_RXRING(nifp, index)
44 * we can access ring->cur, ring->head, ring->tail, etc.
45 *
46 * ring->slot[i] gives us the i-th slot (we can access
47 * directly len, flags, buf_idx)
48 *
49 * char *buf = NETMAP_BUF(ring, x) returns a pointer to
50 * the buffer numbered x
51 *
52 * All ring indexes (head, cur, tail) should always move forward.
53 * To compute the next index in a circular ring you can use
54 * i = nm_ring_next(ring, i);
55 *
56 * To ease porting apps from pcap to netmap we supply a few fuctions
57 * that can be called to open, close, read and write on netmap in a way
58 * similar to libpcap. Note that the read/write function depend on
59 * an ioctl()/select()/poll() being issued to refill rings or push
60 * packets out.
61 *
62 * In order to use these, include #define NETMAP_WITH_LIBS
63 * in the source file that invokes these functions.
64 */
65
66 #ifndef _NET_NETMAP_USER_H_
67 #define _NET_NETMAP_USER_H_
68
69 #define NETMAP_DEVICE_NAME "/dev/netmap"
70
71 #ifdef __CYGWIN__
72 /*
73 * we can compile userspace apps with either cygwin or msvc,
74 * and we use _WIN32 to identify windows specific code
75 */
76 #ifndef _WIN32
77 #define _WIN32
78 #endif /* _WIN32 */
79
80 #endif /* __CYGWIN__ */
81
82 #ifdef _WIN32
83 #undef NETMAP_DEVICE_NAME
84 #define NETMAP_DEVICE_NAME "/proc/sys/DosDevices/Global/netmap"
85 #include <windows.h>
86 #include <WinDef.h>
87 #include <sys/cygwin.h>
88 #endif /* _WIN32 */
89
90 #include <stdint.h>
91 #include <sys/socket.h> /* apple needs sockaddr */
92 #include <net/if.h> /* IFNAMSIZ */
93 #include <ctype.h>
94
95 #ifndef likely
96 #define likely(x) __builtin_expect(!!(x), 1)
97 #define unlikely(x) __builtin_expect(!!(x), 0)
98 #endif /* likely and unlikely */
99
100 #include <net/netmap.h>
101
102 /* helper macro */
103 #define _NETMAP_OFFSET(type, ptr, offset) \
104 ((type)(void *)((char *)(ptr) + (offset)))
105
106 #define NETMAP_IF(_base, _ofs) _NETMAP_OFFSET(struct netmap_if *, _base, _ofs)
107
108 #define NETMAP_TXRING(nifp, index) _NETMAP_OFFSET(struct netmap_ring *, \
109 nifp, (nifp)->ring_ofs[index] )
110
111 #define NETMAP_RXRING(nifp, index) _NETMAP_OFFSET(struct netmap_ring *, \
112 nifp, (nifp)->ring_ofs[index + (nifp)->ni_tx_rings + 1] )
113
114 #define NETMAP_BUF(ring, index) \
115 ((char *)(ring) + (ring)->buf_ofs + ((index)*(ring)->nr_buf_size))
116
117 #define NETMAP_BUF_IDX(ring, buf) \
118 ( ((char *)(buf) - ((char *)(ring) + (ring)->buf_ofs) ) / \
119 (ring)->nr_buf_size )
120
121
122 static inline uint32_t
123 nm_ring_next(struct netmap_ring *r, uint32_t i)
124 {
125 return ( unlikely(i + 1 == r->num_slots) ? 0 : i + 1);
126 }
127
128
129 /*
130 * Return 1 if we have pending transmissions in the tx ring.
131 * When everything is complete ring->head = ring->tail + 1 (modulo ring size)
132 */
133 static inline int
134 nm_tx_pending(struct netmap_ring *r)
135 {
136 return nm_ring_next(r, r->tail) != r->head;
137 }
138
139 /* Compute the number of slots available in the netmap ring. We use
140 * ring->head as explained in the comment above nm_ring_empty(). */
141 static inline uint32_t
142 nm_ring_space(struct netmap_ring *ring)
143 {
144 int ret = ring->tail - ring->head;
145 if (ret < 0)
146 ret += ring->num_slots;
147 return ret;
148 }
149
150
151 #ifdef NETMAP_WITH_LIBS
152 /*
153 * Support for simple I/O libraries.
154 * Include other system headers required for compiling this.
155 */
156
157 #ifndef HAVE_NETMAP_WITH_LIBS
158 #define HAVE_NETMAP_WITH_LIBS
159
160 #include <stdio.h>
161 #include <sys/time.h>
162 #include <sys/mman.h>
163 #include <string.h> /* memset */
164 #include <sys/ioctl.h>
165 #include <sys/errno.h> /* EINVAL */
166 #include <fcntl.h> /* O_RDWR */
167 #include <unistd.h> /* close() */
168 #include <signal.h>
169 #include <stdlib.h>
170
171 #ifndef ND /* debug macros */
172 /* debug support */
173 #define ND(_fmt, ...) do {} while(0)
174 #define D(_fmt, ...) \
175 do { \
176 struct timeval _t0; \
177 gettimeofday(&_t0, NULL); \
178 fprintf(stderr, "%03d.%06d %s [%d] " _fmt "\n", \
179 (int)(_t0.tv_sec % 1000), (int)_t0.tv_usec, \
180 __FUNCTION__, __LINE__, ##__VA_ARGS__); \
181 } while (0)
182
183 /* Rate limited version of "D", lps indicates how many per second */
184 #define RD(lps, format, ...) \
185 do { \
186 static int __t0, __cnt; \
187 struct timeval __xxts; \
188 gettimeofday(&__xxts, NULL); \
189 if (__t0 != __xxts.tv_sec) { \
190 __t0 = __xxts.tv_sec; \
191 __cnt = 0; \
192 } \
193 if (__cnt++ < lps) { \
194 D(format, ##__VA_ARGS__); \
195 } \
196 } while (0)
197 #endif
198
199 struct nm_pkthdr { /* first part is the same as pcap_pkthdr */
200 struct timeval ts;
201 uint32_t caplen;
202 uint32_t len;
203
204 uint64_t flags; /* NM_MORE_PKTS etc */
205 #define NM_MORE_PKTS 1
206 struct nm_desc *d;
207 struct netmap_slot *slot;
208 uint8_t *buf;
209 };
210
211 struct nm_stat { /* same as pcap_stat */
212 u_int ps_recv;
213 u_int ps_drop;
214 u_int ps_ifdrop;
215 #ifdef WIN32 /* XXX or _WIN32 ? */
216 u_int bs_capt;
217 #endif /* WIN32 */
218 };
219
220 #define NM_ERRBUF_SIZE 512
221
222 struct nm_desc {
223 struct nm_desc *self; /* point to self if netmap. */
224 int fd;
225 void *mem;
226 uint32_t memsize;
227 int done_mmap; /* set if mem is the result of mmap */
228 struct netmap_if * const nifp;
229 uint16_t first_tx_ring, last_tx_ring, cur_tx_ring;
230 uint16_t first_rx_ring, last_rx_ring, cur_rx_ring;
231 struct nmreq req; /* also contains the nr_name = ifname */
232 struct nm_pkthdr hdr;
233
234 /*
235 * The memory contains netmap_if, rings and then buffers.
236 * Given a pointer (e.g. to nm_inject) we can compare with
237 * mem/buf_start/buf_end to tell if it is a buffer or
238 * some other descriptor in our region.
239 * We also store a pointer to some ring as it helps in the
240 * translation from buffer indexes to addresses.
241 */
242 struct netmap_ring * const some_ring;
243 void * const buf_start;
244 void * const buf_end;
245 /* parameters from pcap_open_live */
246 int snaplen;
247 int promisc;
248 int to_ms;
249 char *errbuf;
250
251 /* save flags so we can restore them on close */
252 uint32_t if_flags;
253 uint32_t if_reqcap;
254 uint32_t if_curcap;
255
256 struct nm_stat st;
257 char msg[NM_ERRBUF_SIZE];
258 };
259
260 /*
261 * when the descriptor is open correctly, d->self == d
262 * Eventually we should also use some magic number.
263 */
264 #define P2NMD(p) ((struct nm_desc *)(p))
265 #define IS_NETMAP_DESC(d) ((d) && P2NMD(d)->self == P2NMD(d))
266 #define NETMAP_FD(d) (P2NMD(d)->fd)
267
268
269 /*
270 * this is a slightly optimized copy routine which rounds
271 * to multiple of 64 bytes and is often faster than dealing
272 * with other odd sizes. We assume there is enough room
273 * in the source and destination buffers.
274 */
275 static inline void
276 nm_pkt_copy(const void *_src, void *_dst, int l)
277 {
278 const uint64_t *src = (const uint64_t *)_src;
279 uint64_t *dst = (uint64_t *)_dst;
280
281 if (unlikely(l >= 1024 || l % 64)) {
282 memcpy(dst, src, l);
283 return;
284 }
285 for (; likely(l > 0); l-=64) {
286 *dst++ = *src++;
287 *dst++ = *src++;
288 *dst++ = *src++;
289 *dst++ = *src++;
290 *dst++ = *src++;
291 *dst++ = *src++;
292 *dst++ = *src++;
293 *dst++ = *src++;
294 }
295 }
296
297
298 /*
299 * The callback, invoked on each received packet. Same as libpcap
300 */
301 typedef void (*nm_cb_t)(u_char *, const struct nm_pkthdr *, const u_char *d);
302
303 /*
304 *--- the pcap-like API ---
305 *
306 * nm_open() opens a file descriptor, binds to a port and maps memory.
307 *
308 * ifname (netmap:foo or vale:foo) is the port name
309 * a suffix can indicate the follwing:
310 * ^ bind the host (sw) ring pair
311 * * bind host and NIC ring pairs
312 * -NN bind individual NIC ring pair
313 * {NN bind master side of pipe NN
314 * }NN bind slave side of pipe NN
315 * a suffix starting with / and the following flags,
316 * in any order:
317 * x exclusive access
318 * z zero copy monitor (both tx and rx)
319 * t monitor tx side (copy monitor)
320 * r monitor rx side (copy monitor)
321 * R bind only RX ring(s)
322 * T bind only TX ring(s)
323 *
324 * req provides the initial values of nmreq before parsing ifname.
325 * Remember that the ifname parsing will override the ring
326 * number in nm_ringid, and part of nm_flags;
327 * flags special functions, normally 0
328 * indicates which fields of *arg are significant
329 * arg special functions, normally NULL
330 * if passed a netmap_desc with mem != NULL,
331 * use that memory instead of mmap.
332 */
333
334 static struct nm_desc *nm_open(const char *ifname, const struct nmreq *req,
335 uint64_t flags, const struct nm_desc *arg);
336
337 /*
338 * nm_open can import some fields from the parent descriptor.
339 * These flags control which ones.
340 * Also in flags you can specify NETMAP_NO_TX_POLL and NETMAP_DO_RX_POLL,
341 * which set the initial value for these flags.
342 * Note that the 16 low bits of the flags are reserved for data
343 * that may go into the nmreq.
344 */
345 enum {
346 NM_OPEN_NO_MMAP = 0x040000, /* reuse mmap from parent */
347 NM_OPEN_IFNAME = 0x080000, /* nr_name, nr_ringid, nr_flags */
348 NM_OPEN_ARG1 = 0x100000,
349 NM_OPEN_ARG2 = 0x200000,
350 NM_OPEN_ARG3 = 0x400000,
351 NM_OPEN_RING_CFG = 0x800000, /* tx|rx rings|slots */
352 };
353
354
355 /*
356 * nm_close() closes and restores the port to its previous state
357 */
358
359 static int nm_close(struct nm_desc *);
360
361 /*
362 * nm_mmap() do mmap or inherit from parent if the nr_arg2
363 * (memory block) matches.
364 */
365
366 static int nm_mmap(struct nm_desc *, const struct nm_desc *);
367
368 /*
369 * nm_inject() is the same as pcap_inject()
370 * nm_dispatch() is the same as pcap_dispatch()
371 * nm_nextpkt() is the same as pcap_next()
372 */
373
374 static int nm_inject(struct nm_desc *, const void *, size_t);
375 static int nm_dispatch(struct nm_desc *, int, nm_cb_t, u_char *);
376 static u_char *nm_nextpkt(struct nm_desc *, struct nm_pkthdr *);
377
378 #ifdef _WIN32
379
380 intptr_t _get_osfhandle(int); /* defined in io.h in windows */
381
382 /*
383 * In windows we do not have yet native poll support, so we keep track
384 * of file descriptors associated to netmap ports to emulate poll on
385 * them and fall back on regular poll on other file descriptors.
386 */
387 struct win_netmap_fd_list {
388 struct win_netmap_fd_list *next;
389 int win_netmap_fd;
390 HANDLE win_netmap_handle;
391 };
392
393 /*
394 * list head containing all the netmap opened fd and their
395 * windows HANDLE counterparts
396 */
397 static struct win_netmap_fd_list *win_netmap_fd_list_head;
398
399 static void
400 win_insert_fd_record(int fd)
401 {
402 struct win_netmap_fd_list *curr;
403
404 for (curr = win_netmap_fd_list_head; curr; curr = curr->next) {
405 if (fd == curr->win_netmap_fd) {
406 return;
407 }
408 }
409 curr = calloc(1, sizeof(*curr));
410 curr->next = win_netmap_fd_list_head;
411 curr->win_netmap_fd = fd;
412 curr->win_netmap_handle = IntToPtr(_get_osfhandle(fd));
413 win_netmap_fd_list_head = curr;
414 }
415
416 void
417 win_remove_fd_record(int fd)
418 {
419 struct win_netmap_fd_list *curr = win_netmap_fd_list_head;
420 struct win_netmap_fd_list *prev = NULL;
421 for (; curr ; prev = curr, curr = curr->next) {
422 if (fd != curr->win_netmap_fd)
423 continue;
424 /* found the entry */
425 if (prev == NULL) { /* we are freeing the first entry */
426 win_netmap_fd_list_head = curr->next;
427 } else {
428 prev->next = curr->next;
429 }
430 free(curr);
431 break;
432 }
433 }
434
435
436 HANDLE
437 win_get_netmap_handle(int fd)
438 {
439 struct win_netmap_fd_list *curr;
440
441 for (curr = win_netmap_fd_list_head; curr; curr = curr->next) {
442 if (fd == curr->win_netmap_fd) {
443 return curr->win_netmap_handle;
444 }
445 }
446 return NULL;
447 }
448
449 /*
450 * we need to wrap ioctl and mmap, at least for the netmap file descriptors
451 */
452
453 /*
454 * use this function only from netmap_user.h internal functions
455 * same as ioctl, returns 0 on success and -1 on error
456 */
457 static int
458 win_nm_ioctl_internal(HANDLE h, int32_t ctlCode, void *arg)
459 {
460 DWORD bReturn = 0, szIn, szOut;
461 BOOL ioctlReturnStatus;
462 void *inParam = arg, *outParam = arg;
463
464 switch (ctlCode) {
465 case NETMAP_POLL:
466 szIn = sizeof(POLL_REQUEST_DATA);
467 szOut = sizeof(POLL_REQUEST_DATA);
468 break;
469 case NETMAP_MMAP:
470 szIn = 0;
471 szOut = sizeof(void*);
472 inParam = NULL; /* nothing on input */
473 break;
474 case NIOCTXSYNC:
475 case NIOCRXSYNC:
476 szIn = 0;
477 szOut = 0;
478 break;
479 case NIOCREGIF:
480 szIn = sizeof(struct nmreq);
481 szOut = sizeof(struct nmreq);
482 break;
483 case NIOCCONFIG:
484 D("unsupported NIOCCONFIG!");
485 return -1;
486
487 default: /* a regular ioctl */
488 D("invalid ioctl %x on netmap fd", ctlCode);
489 return -1;
490 }
491
492 ioctlReturnStatus = DeviceIoControl(h,
493 ctlCode, inParam, szIn,
494 outParam, szOut,
495 &bReturn, NULL);
496 // XXX note windows returns 0 on error or async call, 1 on success
497 // we could call GetLastError() to figure out what happened
498 return ioctlReturnStatus ? 0 : -1;
499 }
500
501 /*
502 * this function is what must be called from user-space programs
503 * same as ioctl, returns 0 on success and -1 on error
504 */
505 static int
506 win_nm_ioctl(int fd, int32_t ctlCode, void *arg)
507 {
508 HANDLE h = win_get_netmap_handle(fd);
509
510 if (h == NULL) {
511 return ioctl(fd, ctlCode, arg);
512 } else {
513 return win_nm_ioctl_internal(h, ctlCode, arg);
514 }
515 }
516
517 #define ioctl win_nm_ioctl /* from now on, within this file ... */
518
519 /*
520 * We cannot use the native mmap on windows
521 * The only parameter used is "fd", the other ones are just declared to
522 * make this signature comparable to the FreeBSD/Linux one
523 */
524 static void *
525 win32_mmap_emulated(void *addr, size_t length, int prot, int flags, int fd, int32_t offset)
526 {
527 HANDLE h = win_get_netmap_handle(fd);
528
529 if (h == NULL) {
530 return mmap(addr, length, prot, flags, fd, offset);
531 } else {
532 MEMORY_ENTRY ret;
533
534 return win_nm_ioctl_internal(h, NETMAP_MMAP, &ret) ?
535 NULL : ret.pUsermodeVirtualAddress;
536 }
537 }
538
539 #define mmap win32_mmap_emulated
540
541 #include <sys/poll.h> /* XXX needed to use the structure pollfd */
542
543 static int
544 win_nm_poll(struct pollfd *fds, int nfds, int timeout)
545 {
546 HANDLE h;
547
548 if (nfds != 1 || fds == NULL || (h = win_get_netmap_handle(fds->fd)) == NULL) {;
549 return poll(fds, nfds, timeout);
550 } else {
551 POLL_REQUEST_DATA prd;
552
553 prd.timeout = timeout;
554 prd.events = fds->events;
555
556 win_nm_ioctl_internal(h, NETMAP_POLL, &prd);
557 if ((prd.revents == POLLERR) || (prd.revents == STATUS_TIMEOUT)) {
558 return -1;
559 }
560 return 1;
561 }
562 }
563
564 #define poll win_nm_poll
565
566 static int
567 win_nm_open(char* pathname, int flags)
568 {
569
570 if (strcmp(pathname, NETMAP_DEVICE_NAME) == 0) {
571 int fd = open(NETMAP_DEVICE_NAME, O_RDWR);
572 if (fd < 0) {
573 return -1;
574 }
575
576 win_insert_fd_record(fd);
577 return fd;
578 } else {
579 return open(pathname, flags);
580 }
581 }
582
583 #define open win_nm_open
584
585 static int
586 win_nm_close(int fd)
587 {
588 if (fd != -1) {
589 close(fd);
590 if (win_get_netmap_handle(fd) != NULL) {
591 win_remove_fd_record(fd);
592 }
593 }
594 return 0;
595 }
596
597 #define close win_nm_close
598
599 #endif /* _WIN32 */
600
601 static int
602 nm_is_identifier(const char *s, const char *e)
603 {
604 for (; s != e; s++) {
605 if (!isalnum(*s) && *s != '_') {
606 return 0;
607 }
608 }
609
610 return 1;
611 }
612
613 #define MAXERRMSG 80
614 static int
615 nm_parse(const char *ifname, struct nm_desc *d, char *err)
616 {
617 int is_vale;
618 const char *port = NULL;
619 const char *vpname = NULL;
620 u_int namelen;
621 uint32_t nr_ringid = 0, nr_flags;
622 char errmsg[MAXERRMSG] = "";
623 long num;
624 uint16_t nr_arg2 = 0;
625 enum { P_START, P_RNGSFXOK, P_GETNUM, P_FLAGS, P_FLAGSOK, P_MEMID } p_state;
626
627 errno = 0;
628
629 is_vale = (ifname[0] == 'v');
630 if (is_vale) {
631 port = index(ifname, ':');
632 if (port == NULL) {
633 snprintf(errmsg, MAXERRMSG,
634 "missing ':' in vale name");
635 goto fail;
636 }
637
638 if (!nm_is_identifier(ifname + 4, port)) {
639 snprintf(errmsg, MAXERRMSG, "invalid bridge name");
640 goto fail;
641 }
642
643 vpname = ++port;
644 } else {
645 ifname += 7;
646 port = ifname;
647 }
648
649 /* scan for a separator */
650 for (; *port && !index("-*^{}/@", *port); port++)
651 ;
652
653 if (is_vale && !nm_is_identifier(vpname, port)) {
654 snprintf(errmsg, MAXERRMSG, "invalid bridge port name");
655 goto fail;
656 }
657
658 namelen = port - ifname;
659 if (namelen >= sizeof(d->req.nr_name)) {
660 snprintf(errmsg, MAXERRMSG, "name too long");
661 goto fail;
662 }
663 memcpy(d->req.nr_name, ifname, namelen);
664 d->req.nr_name[namelen] = '\0';
665
666 p_state = P_START;
667 nr_flags = NR_REG_ALL_NIC; /* default for no suffix */
668 while (*port) {
669 switch (p_state) {
670 case P_START:
671 switch (*port) {
672 case '^': /* only SW ring */
673 nr_flags = NR_REG_SW;
674 p_state = P_RNGSFXOK;
675 break;
676 case '*': /* NIC and SW */
677 nr_flags = NR_REG_NIC_SW;
678 p_state = P_RNGSFXOK;
679 break;
680 case '-': /* one NIC ring pair */
681 nr_flags = NR_REG_ONE_NIC;
682 p_state = P_GETNUM;
683 break;
684 case '{': /* pipe (master endpoint) */
685 nr_flags = NR_REG_PIPE_MASTER;
686 p_state = P_GETNUM;
687 break;
688 case '}': /* pipe (slave endoint) */
689 nr_flags = NR_REG_PIPE_SLAVE;
690 p_state = P_GETNUM;
691 break;
692 case '/': /* start of flags */
693 p_state = P_FLAGS;
694 break;
695 case '@': /* start of memid */
696 p_state = P_MEMID;
697 break;
698 default:
699 snprintf(errmsg, MAXERRMSG, "unknown modifier: '%c'", *port);
700 goto fail;
701 }
702 port++;
703 break;
704 case P_RNGSFXOK:
705 switch (*port) {
706 case '/':
707 p_state = P_FLAGS;
708 break;
709 case '@':
710 p_state = P_MEMID;
711 break;
712 default:
713 snprintf(errmsg, MAXERRMSG, "unexpected character: '%c'", *port);
714 goto fail;
715 }
716 port++;
717 break;
718 case P_GETNUM:
719 num = strtol(port, (char **)&port, 10);
720 if (num < 0 || num >= NETMAP_RING_MASK) {
721 snprintf(errmsg, MAXERRMSG, "'%ld' out of range [0, %d)",
722 num, NETMAP_RING_MASK);
723 goto fail;
724 }
725 nr_ringid = num & NETMAP_RING_MASK;
726 p_state = P_RNGSFXOK;
727 break;
728 case P_FLAGS:
729 case P_FLAGSOK:
730 if (*port == '@') {
731 port++;
732 p_state = P_MEMID;
733 break;
734 }
735 switch (*port) {
736 case 'x':
737 nr_flags |= NR_EXCLUSIVE;
738 break;
739 case 'z':
740 nr_flags |= NR_ZCOPY_MON;
741 break;
742 case 't':
743 nr_flags |= NR_MONITOR_TX;
744 break;
745 case 'r':
746 nr_flags |= NR_MONITOR_RX;
747 break;
748 case 'R':
749 nr_flags |= NR_RX_RINGS_ONLY;
750 break;
751 case 'T':
752 nr_flags |= NR_TX_RINGS_ONLY;
753 break;
754 default:
755 snprintf(errmsg, MAXERRMSG, "unrecognized flag: '%c'", *port);
756 goto fail;
757 }
758 port++;
759 p_state = P_FLAGSOK;
760 break;
761 case P_MEMID:
762 if (nr_arg2 != 0) {
763 snprintf(errmsg, MAXERRMSG, "double setting of memid");
764 goto fail;
765 }
766 num = strtol(port, (char **)&port, 10);
767 if (num <= 0) {
768 snprintf(errmsg, MAXERRMSG, "invalid memid %ld, must be >0", num);
769 goto fail;
770 }
771 nr_arg2 = num;
772 p_state = P_RNGSFXOK;
773 break;
774 }
775 }
776 if (p_state != P_START && p_state != P_RNGSFXOK && p_state != P_FLAGSOK) {
777 snprintf(errmsg, MAXERRMSG, "unexpected end of port name");
778 goto fail;
779 }
780 ND("flags: %s %s %s %s",
781 (nr_flags & NR_EXCLUSIVE) ? "EXCLUSIVE" : "",
782 (nr_flags & NR_ZCOPY_MON) ? "ZCOPY_MON" : "",
783 (nr_flags & NR_MONITOR_TX) ? "MONITOR_TX" : "",
784 (nr_flags & NR_MONITOR_RX) ? "MONITOR_RX" : "");
785
786 d->req.nr_flags |= nr_flags;
787 d->req.nr_ringid |= nr_ringid;
788 d->req.nr_arg2 = nr_arg2;
789
790 d->self = d;
791
792 return 0;
793 fail:
794 if (!errno)
795 errno = EINVAL;
796 if (err)
797 strncpy(err, errmsg, MAXERRMSG);
798 return -1;
799 }
800
801 /*
802 * Try to open, return descriptor if successful, NULL otherwise.
803 * An invalid netmap name will return errno = 0;
804 * You can pass a pointer to a pre-filled nm_desc to add special
805 * parameters. Flags is used as follows
806 * NM_OPEN_NO_MMAP use the memory from arg, only XXX avoid mmap
807 * if the nr_arg2 (memory block) matches.
808 * NM_OPEN_ARG1 use req.nr_arg1 from arg
809 * NM_OPEN_ARG2 use req.nr_arg2 from arg
810 * NM_OPEN_RING_CFG user ring config from arg
811 */
812 static struct nm_desc *
813 nm_open(const char *ifname, const struct nmreq *req,
814 uint64_t new_flags, const struct nm_desc *arg)
815 {
816 struct nm_desc *d = NULL;
817 const struct nm_desc *parent = arg;
818 char errmsg[MAXERRMSG] = "";
819 uint32_t nr_reg;
820
821 if (strncmp(ifname, "netmap:", 7) &&
822 strncmp(ifname, NM_BDG_NAME, strlen(NM_BDG_NAME))) {
823 errno = 0; /* name not recognised, not an error */
824 return NULL;
825 }
826
827 d = (struct nm_desc *)calloc(1, sizeof(*d));
828 if (d == NULL) {
829 snprintf(errmsg, MAXERRMSG, "nm_desc alloc failure");
830 errno = ENOMEM;
831 return NULL;
832 }
833 d->self = d; /* set this early so nm_close() works */
834 d->fd = open(NETMAP_DEVICE_NAME, O_RDWR);
835 if (d->fd < 0) {
836 snprintf(errmsg, MAXERRMSG, "cannot open /dev/netmap: %s", strerror(errno));
837 goto fail;
838 }
839
840 if (req)
841 d->req = *req;
842
843 if (!(new_flags & NM_OPEN_IFNAME)) {
844 if (nm_parse(ifname, d, errmsg) < 0)
845 goto fail;
846 }
847
848 d->req.nr_version = NETMAP_API;
849 d->req.nr_ringid &= NETMAP_RING_MASK;
850
851 /* optionally import info from parent */
852 if (IS_NETMAP_DESC(parent) && new_flags) {
853 if (new_flags & NM_OPEN_ARG1)
854 D("overriding ARG1 %d", parent->req.nr_arg1);
855 d->req.nr_arg1 = new_flags & NM_OPEN_ARG1 ?
856 parent->req.nr_arg1 : 4;
857 if (new_flags & NM_OPEN_ARG2) {
858 D("overriding ARG2 %d", parent->req.nr_arg2);
859 d->req.nr_arg2 = parent->req.nr_arg2;
860 }
861 if (new_flags & NM_OPEN_ARG3)
862 D("overriding ARG3 %d", parent->req.nr_arg3);
863 d->req.nr_arg3 = new_flags & NM_OPEN_ARG3 ?
864 parent->req.nr_arg3 : 0;
865 if (new_flags & NM_OPEN_RING_CFG) {
866 D("overriding RING_CFG");
867 d->req.nr_tx_slots = parent->req.nr_tx_slots;
868 d->req.nr_rx_slots = parent->req.nr_rx_slots;
869 d->req.nr_tx_rings = parent->req.nr_tx_rings;
870 d->req.nr_rx_rings = parent->req.nr_rx_rings;
871 }
872 if (new_flags & NM_OPEN_IFNAME) {
873 D("overriding ifname %s ringid 0x%x flags 0x%x",
874 parent->req.nr_name, parent->req.nr_ringid,
875 parent->req.nr_flags);
876 memcpy(d->req.nr_name, parent->req.nr_name,
877 sizeof(d->req.nr_name));
878 d->req.nr_ringid = parent->req.nr_ringid;
879 d->req.nr_flags = parent->req.nr_flags;
880 }
881 }
882 /* add the *XPOLL flags */
883 d->req.nr_ringid |= new_flags & (NETMAP_NO_TX_POLL | NETMAP_DO_RX_POLL);
884
885 if (ioctl(d->fd, NIOCREGIF, &d->req)) {
886 snprintf(errmsg, MAXERRMSG, "NIOCREGIF failed: %s", strerror(errno));
887 goto fail;
888 }
889
890 nr_reg = d->req.nr_flags & NR_REG_MASK;
891
892 if (nr_reg == NR_REG_SW) { /* host stack */
893 d->first_tx_ring = d->last_tx_ring = d->req.nr_tx_rings;
894 d->first_rx_ring = d->last_rx_ring = d->req.nr_rx_rings;
895 } else if (nr_reg == NR_REG_ALL_NIC) { /* only nic */
896 d->first_tx_ring = 0;
897 d->first_rx_ring = 0;
898 d->last_tx_ring = d->req.nr_tx_rings - 1;
899 d->last_rx_ring = d->req.nr_rx_rings - 1;
900 } else if (nr_reg == NR_REG_NIC_SW) {
901 d->first_tx_ring = 0;
902 d->first_rx_ring = 0;
903 d->last_tx_ring = d->req.nr_tx_rings;
904 d->last_rx_ring = d->req.nr_rx_rings;
905 } else if (nr_reg == NR_REG_ONE_NIC) {
906 /* XXX check validity */
907 d->first_tx_ring = d->last_tx_ring =
908 d->first_rx_ring = d->last_rx_ring = d->req.nr_ringid & NETMAP_RING_MASK;
909 } else { /* pipes */
910 d->first_tx_ring = d->last_tx_ring = 0;
911 d->first_rx_ring = d->last_rx_ring = 0;
912 }
913
914 /* if parent is defined, do nm_mmap() even if NM_OPEN_NO_MMAP is set */
915 if ((!(new_flags & NM_OPEN_NO_MMAP) || parent) && nm_mmap(d, parent)) {
916 snprintf(errmsg, MAXERRMSG, "mmap failed: %s", strerror(errno));
917 goto fail;
918 }
919
920
921 #ifdef DEBUG_NETMAP_USER
922 { /* debugging code */
923 int i;
924
925 D("%s tx %d .. %d %d rx %d .. %d %d", ifname,
926 d->first_tx_ring, d->last_tx_ring, d->req.nr_tx_rings,
927 d->first_rx_ring, d->last_rx_ring, d->req.nr_rx_rings);
928 for (i = 0; i <= d->req.nr_tx_rings; i++) {
929 struct netmap_ring *r = NETMAP_TXRING(d->nifp, i);
930 D("TX%d %p h %d c %d t %d", i, r, r->head, r->cur, r->tail);
931 }
932 for (i = 0; i <= d->req.nr_rx_rings; i++) {
933 struct netmap_ring *r = NETMAP_RXRING(d->nifp, i);
934 D("RX%d %p h %d c %d t %d", i, r, r->head, r->cur, r->tail);
935 }
936 }
937 #endif /* debugging */
938
939 d->cur_tx_ring = d->first_tx_ring;
940 d->cur_rx_ring = d->first_rx_ring;
941 return d;
942
943 fail:
944 nm_close(d);
945 if (errmsg[0])
946 D("%s %s", errmsg, ifname);
947 if (errno == 0)
948 errno = EINVAL;
949 return NULL;
950 }
951
952
953 static int
954 nm_close(struct nm_desc *d)
955 {
956 /*
957 * ugly trick to avoid unused warnings
958 */
959 static void *__xxzt[] __attribute__ ((unused)) =
960 { (void *)nm_open, (void *)nm_inject,
961 (void *)nm_dispatch, (void *)nm_nextpkt } ;
962
963 if (d == NULL || d->self != d)
964 return EINVAL;
965 if (d->done_mmap && d->mem)
966 munmap(d->mem, d->memsize);
967 if (d->fd != -1) {
968 close(d->fd);
969 }
970
971 bzero(d, sizeof(*d));
972 free(d);
973 return 0;
974 }
975
976
977 static int
978 nm_mmap(struct nm_desc *d, const struct nm_desc *parent)
979 {
980 //XXX TODO: check if mmap is already done
981
982 if (IS_NETMAP_DESC(parent) && parent->mem &&
983 parent->req.nr_arg2 == d->req.nr_arg2) {
984 /* do not mmap, inherit from parent */
985 D("do not mmap, inherit from parent");
986 d->memsize = parent->memsize;
987 d->mem = parent->mem;
988 } else {
989 /* XXX TODO: check if memsize is too large (or there is overflow) */
990 d->memsize = d->req.nr_memsize;
991 d->mem = mmap(0, d->memsize, PROT_WRITE | PROT_READ, MAP_SHARED,
992 d->fd, 0);
993 if (d->mem == MAP_FAILED) {
994 goto fail;
995 }
996 d->done_mmap = 1;
997 }
998 {
999 struct netmap_if *nifp = NETMAP_IF(d->mem, d->req.nr_offset);
1000 struct netmap_ring *r = NETMAP_RXRING(nifp, d->first_rx_ring);
1001 if ((void *)r == (void *)nifp) {
1002 /* the descriptor is open for TX only */
1003 r = NETMAP_TXRING(nifp, d->first_tx_ring);
1004 }
1005
1006 *(struct netmap_if **)(uintptr_t)&(d->nifp) = nifp;
1007 *(struct netmap_ring **)(uintptr_t)&d->some_ring = r;
1008 *(void **)(uintptr_t)&d->buf_start = NETMAP_BUF(r, 0);
1009 *(void **)(uintptr_t)&d->buf_end =
1010 (char *)d->mem + d->memsize;
1011 }
1012
1013 return 0;
1014
1015 fail:
1016 return EINVAL;
1017 }
1018
1019 /*
1020 * Same prototype as pcap_inject(), only need to cast.
1021 */
1022 static int
1023 nm_inject(struct nm_desc *d, const void *buf, size_t size)
1024 {
1025 u_int c, n = d->last_tx_ring - d->first_tx_ring + 1,
1026 ri = d->cur_tx_ring;
1027
1028 for (c = 0; c < n ; c++, ri++) {
1029 /* compute current ring to use */
1030 struct netmap_ring *ring;
1031 uint32_t i, j, idx;
1032 size_t rem;
1033
1034 if (ri > d->last_tx_ring)
1035 ri = d->first_tx_ring;
1036 ring = NETMAP_TXRING(d->nifp, ri);
1037 rem = size;
1038 j = ring->cur;
1039 while (rem > ring->nr_buf_size && j != ring->tail) {
1040 rem -= ring->nr_buf_size;
1041 j = nm_ring_next(ring, j);
1042 }
1043 if (j == ring->tail && rem > 0)
1044 continue;
1045 i = ring->cur;
1046 while (i != j) {
1047 idx = ring->slot[i].buf_idx;
1048 ring->slot[i].len = ring->nr_buf_size;
1049 ring->slot[i].flags = NS_MOREFRAG;
1050 nm_pkt_copy(buf, NETMAP_BUF(ring, idx), ring->nr_buf_size);
1051 i = nm_ring_next(ring, i);
1052 buf = (char *)buf + ring->nr_buf_size;
1053 }
1054 idx = ring->slot[i].buf_idx;
1055 ring->slot[i].len = rem;
1056 ring->slot[i].flags = 0;
1057 nm_pkt_copy(buf, NETMAP_BUF(ring, idx), rem);
1058 ring->head = ring->cur = nm_ring_next(ring, i);
1059 d->cur_tx_ring = ri;
1060 return size;
1061 }
1062 return 0; /* fail */
1063 }
1064
1065
1066 /*
1067 * Same prototype as pcap_dispatch(), only need to cast.
1068 */
1069 static int
1070 nm_dispatch(struct nm_desc *d, int cnt, nm_cb_t cb, u_char *arg)
1071 {
1072 int n = d->last_rx_ring - d->first_rx_ring + 1;
1073 int c, got = 0, ri = d->cur_rx_ring;
1074 d->hdr.buf = NULL;
1075 d->hdr.flags = NM_MORE_PKTS;
1076 d->hdr.d = d;
1077
1078 if (cnt == 0)
1079 cnt = -1;
1080 /* cnt == -1 means infinite, but rings have a finite amount
1081 * of buffers and the int is large enough that we never wrap,
1082 * so we can omit checking for -1
1083 */
1084 for (c=0; c < n && cnt != got; c++, ri++) {
1085 /* compute current ring to use */
1086 struct netmap_ring *ring;
1087
1088 if (ri > d->last_rx_ring)
1089 ri = d->first_rx_ring;
1090 ring = NETMAP_RXRING(d->nifp, ri);
1091 for ( ; !nm_ring_empty(ring) && cnt != got; got++) {
1092 u_int idx, i;
1093 u_char *oldbuf;
1094 struct netmap_slot *slot;
1095 if (d->hdr.buf) { /* from previous round */
1096 cb(arg, &d->hdr, d->hdr.buf);
1097 }
1098 i = ring->cur;
1099 slot = &ring->slot[i];
1100 idx = slot->buf_idx;
1101 /* d->cur_rx_ring doesn't change inside this loop, but
1102 * set it here, so it reflects d->hdr.buf's ring */
1103 d->cur_rx_ring = ri;
1104 d->hdr.slot = slot;
1105 oldbuf = d->hdr.buf = (u_char *)NETMAP_BUF(ring, idx);
1106 // __builtin_prefetch(buf);
1107 d->hdr.len = d->hdr.caplen = slot->len;
1108 while (slot->flags & NS_MOREFRAG) {
1109 u_char *nbuf;
1110 u_int oldlen = slot->len;
1111 i = nm_ring_next(ring, i);
1112 slot = &ring->slot[i];
1113 d->hdr.len += slot->len;
1114 nbuf = (u_char *)NETMAP_BUF(ring, slot->buf_idx);
1115 if (oldbuf != NULL && nbuf - oldbuf == ring->nr_buf_size &&
1116 oldlen == ring->nr_buf_size) {
1117 d->hdr.caplen += slot->len;
1118 oldbuf = nbuf;
1119 } else {
1120 oldbuf = NULL;
1121 }
1122 }
1123 d->hdr.ts = ring->ts;
1124 ring->head = ring->cur = nm_ring_next(ring, i);
1125 }
1126 }
1127 if (d->hdr.buf) { /* from previous round */
1128 d->hdr.flags = 0;
1129 cb(arg, &d->hdr, d->hdr.buf);
1130 }
1131 return got;
1132 }
1133
1134 static u_char *
1135 nm_nextpkt(struct nm_desc *d, struct nm_pkthdr *hdr)
1136 {
1137 int ri = d->cur_rx_ring;
1138
1139 do {
1140 /* compute current ring to use */
1141 struct netmap_ring *ring = NETMAP_RXRING(d->nifp, ri);
1142 if (!nm_ring_empty(ring)) {
1143 u_int i = ring->cur;
1144 u_int idx = ring->slot[i].buf_idx;
1145 u_char *buf = (u_char *)NETMAP_BUF(ring, idx);
1146
1147 // __builtin_prefetch(buf);
1148 hdr->ts = ring->ts;
1149 hdr->len = hdr->caplen = ring->slot[i].len;
1150 ring->cur = nm_ring_next(ring, i);
1151 /* we could postpone advancing head if we want
1152 * to hold the buffer. This can be supported in
1153 * the future.
1154 */
1155 ring->head = ring->cur;
1156 d->cur_rx_ring = ri;
1157 return buf;
1158 }
1159 ri++;
1160 if (ri > d->last_rx_ring)
1161 ri = d->first_rx_ring;
1162 } while (ri != d->cur_rx_ring);
1163 return NULL; /* nothing found */
1164 }
1165
1166 #endif /* !HAVE_NETMAP_WITH_LIBS */
1167
1168 #endif /* NETMAP_WITH_LIBS */
1169
1170 #endif /* _NET_NETMAP_USER_H_ */
Cache object: 2ec1fada3f00dd56cd54b64c4bf3dfcc
|