xref: /freebsd/sys/dev/netmap/netmap_monitor.c (revision fe6060f10f634930ff71b7c50291ddc610da2475)
1 /*
2  * Copyright (C) 2014-2016 Giuseppe Lettieri
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  *   1. Redistributions of source code must retain the above copyright
9  *      notice, this list of conditions and the following disclaimer.
10  *   2. Redistributions in binary form must reproduce the above copyright
11  *      notice, this list of conditions and the following disclaimer in the
12  *      documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 /*
28  * $FreeBSD$
29  *
30  * Monitors
31  *
32  * netmap monitors can be used to do monitoring of network traffic
33  * on another adapter, when the latter adapter is working in netmap mode.
34  *
35  * Monitors offer to userspace the same interface as any other netmap port,
36  * with as many pairs of netmap rings as the monitored adapter.
37  * However, only the rx rings are actually used. Each monitor rx ring receives
38  * the traffic transiting on both the tx and rx corresponding rings in the
39  * monitored adapter. During registration, the user can choose if she wants
40  * to intercept tx only, rx only, or both tx and rx traffic.
41  * The slots containing traffic intercepted in the tx direction will have
42  * the NS_TXMON flag set.
43  *
44  * If the monitor is not able to cope with the stream of frames, excess traffic
45  * will be dropped.
46  *
47  * If the monitored adapter leaves netmap mode, the monitor has to be restarted.
48  *
49  * Monitors can be either zero-copy or copy-based.
50  *
51  * Copy monitors see the frames before they are consumed:
52  *
53  *  - For tx traffic, this is when the application sends them, before they are
54  *    passed down to the adapter.
55  *
56  *  - For rx traffic, this is when they are received by the adapter, before
57  *    they are sent up to the application, if any (note that, if no
58  *    application is reading from a monitored ring, the ring will eventually
59  *    fill up and traffic will stop).
60  *
61  * Zero-copy monitors only see the frames after they have been consumed:
62  *
63  *  - For tx traffic, this is after the slots containing the frames have been
64  *    marked as free. Note that this may happen at a considerably delay after
65  *    frame transmission, since freeing of slots is often done lazily.
66  *
67  *  - For rx traffic, this is after the consumer on the monitored adapter
68  *    has released them. In most cases, the consumer is a userspace
69  *    application which may have modified the frame contents.
70  *
71  * Several copy or zero-copy monitors may be active on any ring.
72  *
73  */
74 
75 
76 #if defined(__FreeBSD__)
77 #include <sys/cdefs.h> /* prerequisite */
78 
79 #include <sys/types.h>
80 #include <sys/errno.h>
81 #include <sys/param.h>	/* defines used in kernel.h */
82 #include <sys/kernel.h>	/* types used in module initialization */
83 #include <sys/malloc.h>
84 #include <sys/poll.h>
85 #include <sys/lock.h>
86 #include <sys/rwlock.h>
87 #include <sys/selinfo.h>
88 #include <sys/sysctl.h>
89 #include <sys/socket.h> /* sockaddrs */
90 #include <net/if.h>
91 #include <net/if_var.h>
92 #include <machine/bus.h>	/* bus_dmamap_* */
93 #include <sys/refcount.h>
94 
95 
96 #elif defined(linux)
97 
98 #include "bsd_glue.h"
99 
100 #elif defined(__APPLE__)
101 
102 #warning OSX support is only partial
103 #include "osx_glue.h"
104 
105 #elif defined(_WIN32)
106 #include "win_glue.h"
107 #else
108 
109 #error	Unsupported platform
110 
111 #endif /* unsupported */
112 
113 /*
114  * common headers
115  */
116 
117 #include <net/netmap.h>
118 #include <dev/netmap/netmap_kern.h>
119 #include <dev/netmap/netmap_mem2.h>
120 
121 #ifdef WITH_MONITOR
122 
123 #define NM_MONITOR_MAXSLOTS 4096
124 
125 /*
126  ********************************************************************
127  * functions common to both kind of monitors
128  ********************************************************************
129  */
130 
131 static int netmap_zmon_reg(struct netmap_adapter *, int);
132 static int
133 nm_is_zmon(struct netmap_adapter *na)
134 {
135 	return na->nm_register == netmap_zmon_reg;
136 }
137 
138 /* nm_sync callback for the monitor's own tx rings.
139  * This makes no sense and always returns error
140  */
141 static int
142 netmap_monitor_txsync(struct netmap_kring *kring, int flags)
143 {
144 	nm_prlim(1, "%s %x", kring->name, flags);
145 	return EIO;
146 }
147 
148 /* nm_sync callback for the monitor's own rx rings.
149  * Note that the lock in netmap_zmon_parent_sync only protects
150  * writers among themselves. Synchronization between writers
151  * (i.e., netmap_zmon_parent_txsync and netmap_zmon_parent_rxsync)
152  * and readers (i.e., netmap_zmon_rxsync) relies on memory barriers.
153  */
154 static int
155 netmap_monitor_rxsync(struct netmap_kring *kring, int flags)
156 {
157 	struct netmap_monitor_adapter *mna =
158 		(struct netmap_monitor_adapter *)kring->na;
159 	if (unlikely(mna->priv.np_na == NULL)) {
160 		/* parent left netmap mode */
161 		return EIO;
162 	}
163 	nm_prdis("%s %x", kring->name, flags);
164 	kring->nr_hwcur = kring->rhead;
165 	mb();
166 	return 0;
167 }
168 
169 /* nm_krings_create callbacks for monitors.
170  */
171 static int
172 netmap_monitor_krings_create(struct netmap_adapter *na)
173 {
174 	int error = netmap_krings_create(na, 0);
175 	enum txrx t;
176 
177 	if (error)
178 		return error;
179 	/* override the host rings callbacks */
180 	for_rx_tx(t) {
181 		int i;
182 		u_int first = nma_get_nrings(na, t);
183 		for (i = 0; i < nma_get_host_nrings(na, t); i++) {
184 			struct netmap_kring *kring = NMR(na, t)[first + i];
185 			kring->nm_sync = t == NR_TX ? netmap_monitor_txsync :
186 						      netmap_monitor_rxsync;
187 		}
188 	}
189 	return 0;
190 }
191 
192 /* nm_krings_delete callback for monitors */
193 static void
194 netmap_monitor_krings_delete(struct netmap_adapter *na)
195 {
196 	netmap_krings_delete(na);
197 }
198 
199 
200 static u_int
201 nm_txrx2flag(enum txrx t)
202 {
203 	return (t == NR_RX ? NR_MONITOR_RX : NR_MONITOR_TX);
204 }
205 
206 /* allocate the monitors array in the monitored kring */
207 static int
208 nm_monitor_alloc(struct netmap_kring *kring, u_int n)
209 {
210 	size_t old_len, len;
211 	struct netmap_kring **nm;
212 
213 	if (n <= kring->max_monitors)
214 		/* we already have more entries that requested */
215 		return 0;
216 
217 	old_len = sizeof(struct netmap_kring *)*kring->max_monitors;
218 	len = sizeof(struct netmap_kring *) * n;
219 	nm = nm_os_realloc(kring->monitors, len, old_len);
220 	if (nm == NULL)
221 		return ENOMEM;
222 
223 	kring->monitors = nm;
224 	kring->max_monitors = n;
225 
226 	return 0;
227 }
228 
229 /* deallocate the parent array in the parent adapter */
230 static void
231 nm_monitor_dealloc(struct netmap_kring *kring)
232 {
233 	if (kring->monitors) {
234 		if (kring->n_monitors > 0) {
235 			nm_prerr("freeing not empty monitor array for %s (%d dangling monitors)!",
236 			    kring->name, kring->n_monitors);
237 		}
238 		nm_os_free(kring->monitors);
239 		kring->monitors = NULL;
240 		kring->max_monitors = 0;
241 		kring->n_monitors = 0;
242 	}
243 }
244 
245 /* returns 1 iff kring has no monitors */
246 static inline int
247 nm_monitor_none(struct netmap_kring *kring)
248 {
249 	return kring->n_monitors == 0 &&
250 		kring->zmon_list[NR_TX].next == NULL &&
251 		kring->zmon_list[NR_RX].next == NULL;
252 }
253 
254 /*
255  * monitors work by replacing the nm_sync() and possibly the
256  * nm_notify() callbacks in the monitored rings.
257  */
258 static int netmap_zmon_parent_txsync(struct netmap_kring *, int);
259 static int netmap_zmon_parent_rxsync(struct netmap_kring *, int);
260 static int netmap_monitor_parent_txsync(struct netmap_kring *, int);
261 static int netmap_monitor_parent_rxsync(struct netmap_kring *, int);
262 static int netmap_monitor_parent_notify(struct netmap_kring *, int);
263 
264 static int
265 nm_monitor_dummycb(struct netmap_kring *kring, int flags)
266 {
267 	(void)kring;
268 	(void)flags;
269 	return 0;
270 }
271 
272 static void
273 nm_monitor_intercept_callbacks(struct netmap_kring *kring)
274 {
275 	nm_prdis("intercept callbacks on %s", kring->name);
276 	kring->mon_sync = kring->nm_sync != NULL ?
277 		kring->nm_sync : nm_monitor_dummycb;
278 	kring->mon_notify = kring->nm_notify;
279 	if (kring->tx == NR_TX) {
280 		kring->nm_sync = netmap_monitor_parent_txsync;
281 	} else {
282 		kring->nm_sync = netmap_monitor_parent_rxsync;
283 		kring->nm_notify = netmap_monitor_parent_notify;
284 		kring->mon_tail = kring->nr_hwtail;
285 	}
286 }
287 
288 static void
289 nm_monitor_restore_callbacks(struct netmap_kring *kring)
290 {
291 	nm_prdis("restoring callbacks on %s", kring->name);
292 	kring->nm_sync = kring->mon_sync;
293 	kring->mon_sync = NULL;
294 	if (kring->tx == NR_RX) {
295 		kring->nm_notify = kring->mon_notify;
296 	}
297 	kring->mon_notify = NULL;
298 }
299 
300 static struct netmap_kring *
301 nm_zmon_list_head(struct netmap_kring *mkring, enum txrx t)
302 {
303 	struct netmap_adapter *na = mkring->na;
304 	struct netmap_kring *kring = mkring;
305 	struct netmap_zmon_list *z = &kring->zmon_list[t];
306 	/* reach the head of the list */
307 	while (nm_is_zmon(na) && z->prev != NULL) {
308 		kring = z->prev;
309 		na = kring->na;
310 		z = &kring->zmon_list[t];
311 	}
312 	return nm_is_zmon(na) ? NULL : kring;
313 }
314 
315 /* add the monitor mkring to the list of monitors of kring.
316  * If this is the first monitor, intercept the callbacks
317  */
318 static int
319 netmap_monitor_add(struct netmap_kring *mkring, struct netmap_kring *kring, int zmon)
320 {
321 	int error = NM_IRQ_COMPLETED;
322 	enum txrx t = kring->tx;
323 	struct netmap_zmon_list *z = &kring->zmon_list[t];
324 	struct netmap_zmon_list *mz = &mkring->zmon_list[t];
325 	struct netmap_kring *ikring = kring;
326 
327 	/* a zero-copy monitor which is not the first in the list
328 	 * must monitor the previous monitor
329 	 */
330 	if (zmon && z->prev != NULL)
331 		ikring = z->prev; /* tail of the list */
332 
333 	/* synchronize with concurrently running nm_sync()s */
334 	nm_kr_stop(kring, NM_KR_LOCKED);
335 
336 	if (nm_monitor_none(ikring)) {
337 		/* this is the first monitor, intercept the callbacks */
338 		nm_prdis("%s: intercept callbacks on %s", mkring->name, ikring->name);
339 		nm_monitor_intercept_callbacks(ikring);
340 	}
341 
342 	if (zmon) {
343 		/* append the zmon to the list */
344 		ikring->zmon_list[t].next = mkring;
345 		z->prev = mkring; /* new tail */
346 		mz->prev = ikring;
347 		mz->next = NULL;
348 		/* grab a reference to the previous netmap adapter
349 		 * in the chain (this may be the monitored port
350 		 * or another zero-copy monitor)
351 		 */
352 		netmap_adapter_get(ikring->na);
353 	} else {
354 		/* make sure the monitor array exists and is big enough */
355 		error = nm_monitor_alloc(kring, kring->n_monitors + 1);
356 		if (error)
357 			goto out;
358 		kring->monitors[kring->n_monitors] = mkring;
359 		mkring->mon_pos[kring->tx] = kring->n_monitors;
360 		kring->n_monitors++;
361 	}
362 
363 out:
364 	nm_kr_start(kring);
365 	return error;
366 }
367 
368 /* remove the monitor mkring from the list of monitors of kring.
369  * If this is the last monitor, restore the original callbacks
370  */
371 static void
372 netmap_monitor_del(struct netmap_kring *mkring, struct netmap_kring *kring, enum txrx t)
373 {
374 	int zmon = nm_is_zmon(mkring->na);
375 	struct netmap_zmon_list *mz = &mkring->zmon_list[t];
376 	struct netmap_kring *ikring = kring;
377 
378 
379 	if (zmon) {
380 		/* get to the head of the list */
381 		kring = nm_zmon_list_head(mkring, t);
382 		ikring = mz->prev;
383 	}
384 
385 	/* synchronize with concurrently running nm_sync()s
386 	 * if kring is NULL (orphaned list) the monitored port
387 	 * has exited netmap mode, so there is nothing to stop
388 	 */
389 	if (kring != NULL)
390 		nm_kr_stop(kring, NM_KR_LOCKED);
391 
392 	if (zmon) {
393 		/* remove the monitor from the list */
394 		if (mz->next != NULL) {
395 			mz->next->zmon_list[t].prev = mz->prev;
396 			/* we also need to let the next monitor drop the
397 			 * reference to us and grab the reference to the
398 			 * previous ring owner, instead
399 			 */
400 			if (mz->prev != NULL)
401 				netmap_adapter_get(mz->prev->na);
402 			netmap_adapter_put(mkring->na);
403 		} else if (kring != NULL) {
404 			/* in the monitored kring, prev is actually the
405 			 * pointer to the tail of the list
406 			 */
407 			kring->zmon_list[t].prev =
408 				(mz->prev != kring ? mz->prev : NULL);
409 		}
410 		if (mz->prev != NULL) {
411 			netmap_adapter_put(mz->prev->na);
412 			mz->prev->zmon_list[t].next = mz->next;
413 		}
414 		mz->prev = NULL;
415 		mz->next = NULL;
416 	} else {
417 		/* this is a copy monitor */
418 		uint32_t mon_pos = mkring->mon_pos[kring->tx];
419 		kring->n_monitors--;
420 		if (mon_pos != kring->n_monitors) {
421 			kring->monitors[mon_pos] =
422 				kring->monitors[kring->n_monitors];
423 			kring->monitors[mon_pos]->mon_pos[kring->tx] = mon_pos;
424 		}
425 		kring->monitors[kring->n_monitors] = NULL;
426 		if (kring->n_monitors == 0) {
427 			nm_monitor_dealloc(kring);
428 		}
429 	}
430 
431 	if (ikring != NULL && nm_monitor_none(ikring)) {
432 		/* this was the last monitor, restore the callbacks */
433 		nm_monitor_restore_callbacks(ikring);
434 	}
435 
436 	if (kring != NULL)
437 		nm_kr_start(kring);
438 }
439 
440 
441 /* This is called when the monitored adapter leaves netmap mode
442  * (see netmap_do_unregif).
443  * We need to notify the monitors that the monitored rings are gone.
444  * We do this by setting their mna->priv.np_na to NULL.
445  * Note that the rings are already stopped when this happens, so
446  * no monitor ring callback can be active.
447  */
448 void
449 netmap_monitor_stop(struct netmap_adapter *na)
450 {
451 	enum txrx t;
452 
453 	for_rx_tx(t) {
454 		u_int i;
455 
456 		for (i = 0; i < netmap_all_rings(na, t); i++) {
457 			struct netmap_kring *kring = NMR(na, t)[i];
458 			struct netmap_zmon_list *z = &kring->zmon_list[t];
459 			u_int j;
460 
461 			for (j = 0; j < kring->n_monitors; j++) {
462 				struct netmap_kring *mkring =
463 					kring->monitors[j];
464 				struct netmap_monitor_adapter *mna =
465 					(struct netmap_monitor_adapter *)mkring->na;
466 				/* forget about this adapter */
467 				if (mna->priv.np_na != NULL) {
468 					netmap_adapter_put(mna->priv.np_na);
469 					mna->priv.np_na = NULL;
470 				}
471 				kring->monitors[j] = NULL;
472 			}
473 
474 			if (!nm_is_zmon(na)) {
475 				/* we are the head of at most one list */
476 				struct netmap_kring *zkring;
477 				for (zkring = z->next; zkring != NULL;
478 						zkring = zkring->zmon_list[t].next)
479 				{
480 					struct netmap_monitor_adapter *next =
481 						(struct netmap_monitor_adapter *)zkring->na;
482 					/* let the monitor forget about us */
483 					netmap_adapter_put(next->priv.np_na); /* nop if null */
484 					next->priv.np_na = NULL;
485 				}
486 				/* orphan the zmon list */
487 				if (z->next != NULL)
488 					z->next->zmon_list[t].prev = NULL;
489 				z->next = NULL;
490 				z->prev = NULL;
491 			}
492 
493 			if (!nm_monitor_none(kring)) {
494 
495 				kring->n_monitors = 0;
496 				nm_monitor_dealloc(kring);
497 				nm_monitor_restore_callbacks(kring);
498 			}
499 		}
500 	}
501 }
502 
503 
504 /* common functions for the nm_register() callbacks of both kind of
505  * monitors.
506  */
507 static int
508 netmap_monitor_reg_common(struct netmap_adapter *na, int onoff, int zmon)
509 {
510 	struct netmap_monitor_adapter *mna =
511 		(struct netmap_monitor_adapter *)na;
512 	struct netmap_priv_d *priv = &mna->priv;
513 	struct netmap_adapter *pna = priv->np_na;
514 	struct netmap_kring *kring, *mkring;
515 	int i;
516 	enum txrx t, s;
517 
518 	nm_prdis("%p: onoff %d", na, onoff);
519 	if (onoff) {
520 		if (pna == NULL) {
521 			/* parent left netmap mode, fatal */
522 			nm_prerr("%s: parent left netmap mode", na->name);
523 			return ENXIO;
524 		}
525 		for_rx_tx(t) {
526 			for (i = 0; i < netmap_all_rings(na, t); i++) {
527 				mkring = NMR(na, t)[i];
528 				if (!nm_kring_pending_on(mkring))
529 					continue;
530 				mkring->nr_mode = NKR_NETMAP_ON;
531 				if (t == NR_TX)
532 					continue;
533 				for_rx_tx(s) {
534 					if (i > nma_get_nrings(pna, s))
535 						continue;
536 					if (mna->flags & nm_txrx2flag(s)) {
537 						kring = NMR(pna, s)[i];
538 						netmap_monitor_add(mkring, kring, zmon);
539 					}
540 				}
541 			}
542 		}
543 		na->na_flags |= NAF_NETMAP_ON;
544 	} else {
545 		if (na->active_fds == 0)
546 			na->na_flags &= ~NAF_NETMAP_ON;
547 		for_rx_tx(t) {
548 			for (i = 0; i < netmap_all_rings(na, t); i++) {
549 				mkring = NMR(na, t)[i];
550 				if (!nm_kring_pending_off(mkring))
551 					continue;
552 				mkring->nr_mode = NKR_NETMAP_OFF;
553 				if (t == NR_TX)
554 					continue;
555 				/* we cannot access the parent krings if the parent
556 				 * has left netmap mode. This is signaled by a NULL
557 				 * pna pointer
558 				 */
559 				if (pna == NULL)
560 					continue;
561 				for_rx_tx(s) {
562 					if (i > nma_get_nrings(pna, s))
563 						continue;
564 					if (mna->flags & nm_txrx2flag(s)) {
565 						kring = NMR(pna, s)[i];
566 						netmap_monitor_del(mkring, kring, s);
567 					}
568 				}
569 			}
570 		}
571 	}
572 	return 0;
573 }
574 
575 /*
576  ****************************************************************
577  * functions specific for zero-copy monitors
578  ****************************************************************
579  */
580 
581 /*
582  * Common function for both zero-copy tx and rx nm_sync()
583  * callbacks
584  */
585 static int
586 netmap_zmon_parent_sync(struct netmap_kring *kring, int flags, enum txrx tx)
587 {
588 	struct netmap_kring *mkring = kring->zmon_list[tx].next;
589 	struct netmap_ring *ring = kring->ring, *mring;
590 	int error = 0;
591 	int rel_slots, free_slots, busy, sent = 0;
592 	u_int beg, end, i;
593 	u_int lim = kring->nkr_num_slots - 1,
594 	      mlim; // = mkring->nkr_num_slots - 1;
595 	uint16_t txmon = kring->tx == NR_TX ? NS_TXMON : 0;
596 
597 	if (mkring == NULL) {
598 		nm_prlim(5, "NULL monitor on %s", kring->name);
599 		return 0;
600 	}
601 	mring = mkring->ring;
602 	mlim = mkring->nkr_num_slots - 1;
603 
604 	/* get the released slots (rel_slots) */
605 	if (tx == NR_TX) {
606 		beg = kring->nr_hwtail + 1;
607 		error = kring->mon_sync(kring, flags);
608 		if (error)
609 			return error;
610 		end = kring->nr_hwtail + 1;
611 	} else { /* NR_RX */
612 		beg = kring->nr_hwcur;
613 		end = kring->rhead;
614 	}
615 
616 	rel_slots = end - beg;
617 	if (rel_slots < 0)
618 		rel_slots += kring->nkr_num_slots;
619 
620 	if (!rel_slots) {
621 		/* no released slots, but we still need
622 		 * to call rxsync if this is a rx ring
623 		 */
624 		goto out_rxsync;
625 	}
626 
627 	/* we need to lock the monitor receive ring, since it
628 	 * is the target of bot tx and rx traffic from the monitored
629 	 * adapter
630 	 */
631 	mtx_lock(&mkring->q_lock);
632 	/* get the free slots available on the monitor ring */
633 	i = mkring->nr_hwtail;
634 	busy = i - mkring->nr_hwcur;
635 	if (busy < 0)
636 		busy += mkring->nkr_num_slots;
637 	free_slots = mlim - busy;
638 
639 	if (!free_slots)
640 		goto out;
641 
642 	/* swap min(free_slots, rel_slots) slots */
643 	if (free_slots < rel_slots) {
644 		beg += (rel_slots - free_slots);
645 		rel_slots = free_slots;
646 	}
647 	if (unlikely(beg >= kring->nkr_num_slots))
648 		beg -= kring->nkr_num_slots;
649 
650 	sent = rel_slots;
651 	for ( ; rel_slots; rel_slots--) {
652 		struct netmap_slot *s = &ring->slot[beg];
653 		struct netmap_slot *ms = &mring->slot[i];
654 		uint32_t tmp;
655 
656 		tmp = ms->buf_idx;
657 		ms->buf_idx = s->buf_idx;
658 		s->buf_idx = tmp;
659 		nm_prdis(5, "beg %d buf_idx %d", beg, tmp);
660 
661 		tmp = ms->len;
662 		ms->len = s->len;
663 		s->len = tmp;
664 
665 		ms->flags = (s->flags & ~NS_TXMON) | txmon;
666 		s->flags |= NS_BUF_CHANGED;
667 
668 		beg = nm_next(beg, lim);
669 		i = nm_next(i, mlim);
670 
671 	}
672 	mb();
673 	mkring->nr_hwtail = i;
674 
675 out:
676 	mtx_unlock(&mkring->q_lock);
677 
678 	if (sent) {
679 		/* notify the new frames to the monitor */
680 		mkring->nm_notify(mkring, 0);
681 	}
682 
683 out_rxsync:
684 	if (tx == NR_RX)
685 		error = kring->mon_sync(kring, flags);
686 
687 	return error;
688 }
689 
690 /* callback used to replace the nm_sync callback in the monitored tx rings */
691 static int
692 netmap_zmon_parent_txsync(struct netmap_kring *kring, int flags)
693 {
694 	return netmap_zmon_parent_sync(kring, flags, NR_TX);
695 }
696 
697 /* callback used to replace the nm_sync callback in the monitored rx rings */
698 static int
699 netmap_zmon_parent_rxsync(struct netmap_kring *kring, int flags)
700 {
701 	return netmap_zmon_parent_sync(kring, flags, NR_RX);
702 }
703 
704 static int
705 netmap_zmon_reg(struct netmap_adapter *na, int onoff)
706 {
707 	return netmap_monitor_reg_common(na, onoff, 1 /* zcopy */);
708 }
709 
710 /* nm_dtor callback for monitors */
711 static void
712 netmap_zmon_dtor(struct netmap_adapter *na)
713 {
714 	struct netmap_monitor_adapter *mna =
715 		(struct netmap_monitor_adapter *)na;
716 	struct netmap_priv_d *priv = &mna->priv;
717 	struct netmap_adapter *pna = priv->np_na;
718 
719 	netmap_adapter_put(pna);
720 }
721 
722 /*
723  ****************************************************************
724  * functions specific for copy monitors
725  ****************************************************************
726  */
727 
728 static void
729 netmap_monitor_parent_sync(struct netmap_kring *kring, u_int first_new, int new_slots)
730 {
731 	u_int j;
732 	uint16_t txmon = kring->tx == NR_TX ? NS_TXMON : 0;
733 
734 	for (j = 0; j < kring->n_monitors; j++) {
735 		struct netmap_kring *mkring = kring->monitors[j];
736 		u_int i, mlim, beg;
737 		int free_slots, busy, sent = 0, m;
738 		u_int lim = kring->nkr_num_slots - 1;
739 		struct netmap_ring *ring = kring->ring, *mring = mkring->ring;
740 		u_int max_len;
741 		mlim = mkring->nkr_num_slots - 1;
742 
743 		/* we need to lock the monitor receive ring, since it
744 		 * is the target of bot tx and rx traffic from the monitored
745 		 * adapter
746 		 */
747 		mtx_lock(&mkring->q_lock);
748 		/* get the free slots available on the monitor ring */
749 		i = mkring->nr_hwtail;
750 		busy = i - mkring->nr_hwcur;
751 		if (busy < 0)
752 			busy += mkring->nkr_num_slots;
753 		free_slots = mlim - busy;
754 
755 		if (!free_slots)
756 			goto out;
757 
758 		/* copy min(free_slots, new_slots) slots */
759 		m = new_slots;
760 		beg = first_new;
761 		if (free_slots < m) {
762 			beg += (m - free_slots);
763 			if (beg >= kring->nkr_num_slots)
764 				beg -= kring->nkr_num_slots;
765 			m = free_slots;
766 		}
767 
768 		for ( ; m; m--) {
769 			struct netmap_slot *s = &ring->slot[beg];
770 			struct netmap_slot *ms = &mring->slot[i];
771 			u_int copy_len = s->len;
772 			char *src = NMB_O(kring, s),
773 			     *dst = NMB_O(mkring, ms);
774 
775 			max_len = NETMAP_BUF_SIZE(mkring->na) - nm_get_offset(mkring, ms);
776 			if (unlikely(copy_len > max_len)) {
777 				nm_prlim(5, "%s->%s: truncating %d to %d", kring->name,
778 						mkring->name, copy_len, max_len);
779 				copy_len = max_len;
780 			}
781 
782 			memcpy(dst, src, copy_len);
783 			ms->len = copy_len;
784 			ms->flags = (s->flags & ~NS_TXMON) | txmon;
785 			sent++;
786 
787 			beg = nm_next(beg, lim);
788 			i = nm_next(i, mlim);
789 		}
790 		mb();
791 		mkring->nr_hwtail = i;
792 	out:
793 		mtx_unlock(&mkring->q_lock);
794 
795 		if (sent) {
796 			/* notify the new frames to the monitor */
797 			mkring->nm_notify(mkring, 0);
798 		}
799 	}
800 }
801 
802 /* callback used to replace the nm_sync callback in the monitored tx rings */
803 static int
804 netmap_monitor_parent_txsync(struct netmap_kring *kring, int flags)
805 {
806 	u_int first_new;
807 	int new_slots;
808 
809 	/* get the new slots */
810 	if (kring->n_monitors > 0) {
811 		first_new = kring->nr_hwcur;
812 		new_slots = kring->rhead - first_new;
813 		if (new_slots < 0)
814 			new_slots += kring->nkr_num_slots;
815 		if (new_slots)
816 			netmap_monitor_parent_sync(kring, first_new, new_slots);
817 	}
818 	if (kring->zmon_list[NR_TX].next != NULL) {
819 		return netmap_zmon_parent_txsync(kring, flags);
820 	}
821 	return kring->mon_sync(kring, flags);
822 }
823 
824 /* callback used to replace the nm_sync callback in the monitored rx rings */
825 static int
826 netmap_monitor_parent_rxsync(struct netmap_kring *kring, int flags)
827 {
828 	u_int first_new;
829 	int new_slots, error;
830 
831 	/* get the new slots */
832 	if (kring->zmon_list[NR_RX].next != NULL) {
833 		error = netmap_zmon_parent_rxsync(kring, flags);
834 	} else {
835 		error =  kring->mon_sync(kring, flags);
836 	}
837 	if (error)
838 		return error;
839 	if (kring->n_monitors > 0) {
840 		first_new = kring->mon_tail;
841 		new_slots = kring->nr_hwtail - first_new;
842 		if (new_slots < 0)
843 			new_slots += kring->nkr_num_slots;
844 		if (new_slots)
845 			netmap_monitor_parent_sync(kring, first_new, new_slots);
846 		kring->mon_tail = kring->nr_hwtail;
847 	}
848 	return 0;
849 }
850 
851 /* callback used to replace the nm_notify() callback in the monitored rx rings */
852 static int
853 netmap_monitor_parent_notify(struct netmap_kring *kring, int flags)
854 {
855 	int (*notify)(struct netmap_kring*, int);
856 	nm_prdis(5, "%s %x", kring->name, flags);
857 	/* ?xsync callbacks have tryget called by their callers
858 	 * (NIOCREGIF and poll()), but here we have to call it
859 	 * by ourself
860 	 */
861 	if (nm_kr_tryget(kring, 0, NULL)) {
862 		/* in all cases, just skip the sync */
863 		return NM_IRQ_COMPLETED;
864 	}
865 	if (kring->n_monitors > 0) {
866 		netmap_monitor_parent_rxsync(kring, NAF_FORCE_READ);
867 	}
868 	if (nm_monitor_none(kring)) {
869 		/* we are no longer monitoring this ring, so both
870 		 * mon_sync and mon_notify are NULL
871 		 */
872 		notify = kring->nm_notify;
873 	} else {
874 		notify = kring->mon_notify;
875 	}
876 	nm_kr_put(kring);
877 	return notify(kring, flags);
878 }
879 
880 
881 static int
882 netmap_monitor_reg(struct netmap_adapter *na, int onoff)
883 {
884 	return netmap_monitor_reg_common(na, onoff, 0 /* no zcopy */);
885 }
886 
887 static void
888 netmap_monitor_dtor(struct netmap_adapter *na)
889 {
890 	struct netmap_monitor_adapter *mna =
891 		(struct netmap_monitor_adapter *)na;
892 	struct netmap_priv_d *priv = &mna->priv;
893 	struct netmap_adapter *pna = priv->np_na;
894 
895 	netmap_adapter_put(pna);
896 }
897 
898 
899 /* check if req is a request for a monitor adapter that we can satisfy */
900 int
901 netmap_get_monitor_na(struct nmreq_header *hdr, struct netmap_adapter **na,
902 			struct netmap_mem_d *nmd, int create)
903 {
904 	struct nmreq_register *req = (struct nmreq_register *)(uintptr_t)hdr->nr_body;
905 	struct nmreq_register preq;
906 	struct netmap_adapter *pna; /* parent adapter */
907 	struct netmap_monitor_adapter *mna;
908 	struct ifnet *ifp = NULL;
909 	int  error;
910 	int zcopy = (req->nr_flags & NR_ZCOPY_MON);
911 
912 	if (zcopy) {
913 		req->nr_flags |= (NR_MONITOR_TX | NR_MONITOR_RX);
914 	}
915 	if ((req->nr_flags & (NR_MONITOR_TX | NR_MONITOR_RX)) == 0) {
916 		nm_prdis("not a monitor");
917 		return 0;
918 	}
919 	/* this is a request for a monitor adapter */
920 
921 	nm_prdis("flags %lx", req->nr_flags);
922 
923 	/* First, try to find the adapter that we want to monitor.
924 	 * We use the same req, after we have turned off the monitor flags.
925 	 * In this way we can potentially monitor everything netmap understands,
926 	 * except other monitors.
927 	 */
928 	memcpy(&preq, req, sizeof(preq));
929 	preq.nr_flags &= ~(NR_MONITOR_TX | NR_MONITOR_RX | NR_ZCOPY_MON);
930 	hdr->nr_body = (uintptr_t)&preq;
931 	error = netmap_get_na(hdr, &pna, &ifp, nmd, create);
932 	hdr->nr_body = (uintptr_t)req;
933 	if (error) {
934 		nm_prerr("parent lookup failed: %d", error);
935 		return error;
936 	}
937 	nm_prdis("found parent: %s", pna->name);
938 
939 	if (!nm_netmap_on(pna)) {
940 		/* parent not in netmap mode */
941 		/* XXX we can wait for the parent to enter netmap mode,
942 		 * by intercepting its nm_register callback (2014-03-16)
943 		 */
944 		nm_prerr("%s not in netmap mode", pna->name);
945 		error = EINVAL;
946 		goto put_out;
947 	}
948 
949 	mna = nm_os_malloc(sizeof(*mna));
950 	if (mna == NULL) {
951 		error = ENOMEM;
952 		goto put_out;
953 	}
954 	mna->priv.np_na = pna;
955 
956 	/* grab all the rings we need in the parent */
957 	error = netmap_interp_ringid(&mna->priv, hdr);
958 	if (error) {
959 		nm_prerr("ringid error");
960 		goto free_out;
961 	}
962 	snprintf(mna->up.name, sizeof(mna->up.name), "%s/%s%s%s#%lu", pna->name,
963 			zcopy ? "z" : "",
964 			(req->nr_flags & NR_MONITOR_RX) ? "r" : "",
965 			(req->nr_flags & NR_MONITOR_TX) ? "t" : "",
966 			pna->monitor_id++);
967 
968 	/* the monitor supports the host rings iff the parent does */
969 	mna->up.na_flags |= (pna->na_flags & NAF_HOST_RINGS) & ~NAF_OFFSETS;
970 	if (!zcopy)
971 		mna->up.na_flags |= NAF_OFFSETS;
972 	/* a do-nothing txsync: monitors cannot be used to inject packets */
973 	mna->up.nm_txsync = netmap_monitor_txsync;
974 	mna->up.nm_rxsync = netmap_monitor_rxsync;
975 	mna->up.nm_krings_create = netmap_monitor_krings_create;
976 	mna->up.nm_krings_delete = netmap_monitor_krings_delete;
977 	mna->up.num_tx_rings = 1; // XXX what should we do here with chained zmons?
978 	/* we set the number of our rx_rings to be max(num_rx_rings, num_rx_rings)
979 	 * in the parent
980 	 */
981 	mna->up.num_rx_rings = pna->num_rx_rings;
982 	if (pna->num_tx_rings > pna->num_rx_rings)
983 		mna->up.num_rx_rings = pna->num_tx_rings;
984 	/* by default, the number of slots is the same as in
985 	 * the parent rings, but the user may ask for a different
986 	 * number
987 	 */
988 	mna->up.num_tx_desc = req->nr_tx_slots;
989 	nm_bound_var(&mna->up.num_tx_desc, pna->num_tx_desc,
990 			1, NM_MONITOR_MAXSLOTS, NULL);
991 	mna->up.num_rx_desc = req->nr_rx_slots;
992 	nm_bound_var(&mna->up.num_rx_desc, pna->num_rx_desc,
993 			1, NM_MONITOR_MAXSLOTS, NULL);
994 	if (zcopy) {
995 		mna->up.nm_register = netmap_zmon_reg;
996 		mna->up.nm_dtor = netmap_zmon_dtor;
997 		/* to have zero copy, we need to use the same memory allocator
998 		 * as the monitored port
999 		 */
1000 		mna->up.nm_mem = netmap_mem_get(pna->nm_mem);
1001 		/* and the allocator cannot be changed */
1002 		mna->up.na_flags |= NAF_MEM_OWNER;
1003 	} else {
1004 		mna->up.nm_register = netmap_monitor_reg;
1005 		mna->up.nm_dtor = netmap_monitor_dtor;
1006 		mna->up.nm_mem = netmap_mem_private_new(
1007 				mna->up.num_tx_rings,
1008 				mna->up.num_tx_desc,
1009 				mna->up.num_rx_rings,
1010 				mna->up.num_rx_desc,
1011 				0, /* extra bufs */
1012 				0, /* pipes */
1013 				&error);
1014 		if (mna->up.nm_mem == NULL)
1015 			goto put_out;
1016 	}
1017 
1018 	error = netmap_attach_common(&mna->up);
1019 	if (error) {
1020 		nm_prerr("netmap_attach_common failed");
1021 		goto mem_put_out;
1022 	}
1023 
1024 	/* remember the traffic directions we have to monitor */
1025 	mna->flags = (req->nr_flags & (NR_MONITOR_TX | NR_MONITOR_RX | NR_ZCOPY_MON));
1026 
1027 	*na = &mna->up;
1028 	netmap_adapter_get(*na);
1029 
1030 	/* keep the reference to the parent */
1031 	nm_prdis("monitor ok");
1032 
1033 	/* drop the reference to the ifp, if any */
1034 	if (ifp)
1035 		if_rele(ifp);
1036 
1037 	return 0;
1038 
1039 mem_put_out:
1040 	netmap_mem_put(mna->up.nm_mem);
1041 free_out:
1042 	nm_os_free(mna);
1043 put_out:
1044 	netmap_unget_na(pna, ifp);
1045 	return error;
1046 }
1047 
1048 
1049 #endif /* WITH_MONITOR */
1050