xref: /freebsd/sys/dev/netmap/netmap_freebsd.c (revision aa3860851b9f6a6002d135b1cac7736e0995eedc)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (C) 2013-2014 Universita` di Pisa. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
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 #include "opt_inet.h"
29 #include "opt_inet6.h"
30 
31 #include <sys/param.h>
32 #include <sys/module.h>
33 #include <sys/errno.h>
34 #include <sys/eventhandler.h>
35 #include <sys/jail.h>
36 #include <sys/poll.h>  /* POLLIN, POLLOUT */
37 #include <sys/kernel.h> /* types used in module initialization */
38 #include <sys/conf.h>	/* DEV_MODULE_ORDERED */
39 #include <sys/endian.h>
40 #include <sys/syscallsubr.h> /* kern_ioctl() */
41 
42 #include <sys/rwlock.h>
43 
44 #include <vm/vm.h>      /* vtophys */
45 #include <vm/pmap.h>    /* vtophys */
46 #include <vm/vm_param.h>
47 #include <vm/vm_object.h>
48 #include <vm/vm_page.h>
49 #include <vm/vm_pager.h>
50 #include <vm/uma.h>
51 
52 
53 #include <sys/malloc.h>
54 #include <sys/socket.h> /* sockaddrs */
55 #include <sys/selinfo.h>
56 #include <sys/kthread.h> /* kthread_add() */
57 #include <sys/proc.h> /* PROC_LOCK() */
58 #include <sys/unistd.h> /* RFNOWAIT */
59 #include <sys/sched.h> /* sched_bind() */
60 #include <sys/smp.h> /* mp_maxid */
61 #include <sys/taskqueue.h> /* taskqueue_enqueue(), taskqueue_create(), ... */
62 #include <net/if.h>
63 #include <net/if_var.h>
64 #include <net/if_types.h> /* IFT_ETHER */
65 #include <net/ethernet.h> /* ether_ifdetach */
66 #include <net/if_dl.h> /* LLADDR */
67 #include <machine/bus.h>        /* bus_dmamap_* */
68 #include <netinet/in.h>		/* in6_cksum_pseudo() */
69 #include <machine/in_cksum.h>  /* in_pseudo(), in_cksum_hdr() */
70 
71 #include <net/netmap.h>
72 #include <dev/netmap/netmap_kern.h>
73 #include <net/netmap_virt.h>
74 #include <dev/netmap/netmap_mem2.h>
75 
76 
77 /* ======================== FREEBSD-SPECIFIC ROUTINES ================== */
78 
79 static void
nm_kqueue_notify(void * opaque,int pending)80 nm_kqueue_notify(void *opaque, int pending)
81 {
82 	struct nm_selinfo *si = opaque;
83 
84 	/* We use a non-zero hint to distinguish this notification call
85 	 * from the call done in kqueue_scan(), which uses hint=0.
86 	 */
87 	KNOTE_UNLOCKED(&si->si.si_note, /*hint=*/0x100);
88 }
89 
nm_os_selinfo_init(NM_SELINFO_T * si,const char * name)90 int nm_os_selinfo_init(NM_SELINFO_T *si, const char *name) {
91 	int err;
92 
93 	TASK_INIT(&si->ntfytask, 0, nm_kqueue_notify, si);
94 	si->ntfytq = taskqueue_create(name, M_NOWAIT,
95 	    taskqueue_thread_enqueue, &si->ntfytq);
96 	if (si->ntfytq == NULL)
97 		return -ENOMEM;
98 	err = taskqueue_start_threads(&si->ntfytq, 1, PI_NET, "tq %s", name);
99 	if (err) {
100 		taskqueue_free(si->ntfytq);
101 		si->ntfytq = NULL;
102 		return err;
103 	}
104 
105 	snprintf(si->mtxname, sizeof(si->mtxname), "nmkl%s", name);
106 	mtx_init(&si->m, si->mtxname, NULL, MTX_DEF);
107 	knlist_init_mtx(&si->si.si_note, &si->m);
108 	si->kqueue_users = 0;
109 
110 	return (0);
111 }
112 
113 void
nm_os_selinfo_uninit(NM_SELINFO_T * si)114 nm_os_selinfo_uninit(NM_SELINFO_T *si)
115 {
116 	if (si->ntfytq == NULL) {
117 		return;	/* si was not initialized */
118 	}
119 	taskqueue_drain(si->ntfytq, &si->ntfytask);
120 	taskqueue_free(si->ntfytq);
121 	si->ntfytq = NULL;
122 	knlist_delete(&si->si.si_note, curthread, /*islocked=*/0);
123 	knlist_destroy(&si->si.si_note);
124 	/* now we don't need the mutex anymore */
125 	mtx_destroy(&si->m);
126 }
127 
128 void *
nm_os_malloc(size_t size)129 nm_os_malloc(size_t size)
130 {
131 	return malloc(size, M_DEVBUF, M_NOWAIT | M_ZERO);
132 }
133 
134 void *
nm_os_realloc(void * addr,size_t new_size,size_t old_size __unused)135 nm_os_realloc(void *addr, size_t new_size, size_t old_size __unused)
136 {
137 	return realloc(addr, new_size, M_DEVBUF, M_NOWAIT | M_ZERO);
138 }
139 
140 void
nm_os_free(void * addr)141 nm_os_free(void *addr)
142 {
143 	free(addr, M_DEVBUF);
144 }
145 
146 void
nm_os_ifnet_lock(void)147 nm_os_ifnet_lock(void)
148 {
149 	IFNET_RLOCK();
150 }
151 
152 void
nm_os_ifnet_unlock(void)153 nm_os_ifnet_unlock(void)
154 {
155 	IFNET_RUNLOCK();
156 }
157 
158 static int netmap_use_count = 0;
159 
160 void
nm_os_get_module(void)161 nm_os_get_module(void)
162 {
163 	netmap_use_count++;
164 }
165 
166 void
nm_os_put_module(void)167 nm_os_put_module(void)
168 {
169 	netmap_use_count--;
170 }
171 
172 static void
netmap_ifnet_arrival_handler(void * arg __unused,if_t ifp)173 netmap_ifnet_arrival_handler(void *arg __unused, if_t ifp)
174 {
175 	netmap_undo_zombie(ifp);
176 }
177 
178 static void
netmap_ifnet_departure_handler(void * arg __unused,if_t ifp)179 netmap_ifnet_departure_handler(void *arg __unused, if_t ifp)
180 {
181 	netmap_make_zombie(ifp);
182 }
183 
184 static eventhandler_tag nm_ifnet_ah_tag;
185 static eventhandler_tag nm_ifnet_dh_tag;
186 
187 int
nm_os_ifnet_init(void)188 nm_os_ifnet_init(void)
189 {
190 	nm_ifnet_ah_tag =
191 		EVENTHANDLER_REGISTER(ifnet_arrival_event,
192 				netmap_ifnet_arrival_handler,
193 				NULL, EVENTHANDLER_PRI_ANY);
194 	nm_ifnet_dh_tag =
195 		EVENTHANDLER_REGISTER(ifnet_departure_event,
196 				netmap_ifnet_departure_handler,
197 				NULL, EVENTHANDLER_PRI_ANY);
198 	return 0;
199 }
200 
201 void
nm_os_ifnet_fini(void)202 nm_os_ifnet_fini(void)
203 {
204 	EVENTHANDLER_DEREGISTER(ifnet_arrival_event,
205 			nm_ifnet_ah_tag);
206 	EVENTHANDLER_DEREGISTER(ifnet_departure_event,
207 			nm_ifnet_dh_tag);
208 }
209 
210 unsigned
nm_os_ifnet_mtu(if_t ifp)211 nm_os_ifnet_mtu(if_t ifp)
212 {
213 	return if_getmtu(ifp);
214 }
215 
216 rawsum_t
nm_os_csum_raw(uint8_t * data,size_t len,rawsum_t cur_sum)217 nm_os_csum_raw(uint8_t *data, size_t len, rawsum_t cur_sum)
218 {
219 	/* TODO XXX please use the FreeBSD implementation for this. */
220 	uint16_t *words = (uint16_t *)data;
221 	int nw = len / 2;
222 	int i;
223 
224 	for (i = 0; i < nw; i++)
225 		cur_sum += be16toh(words[i]);
226 
227 	if (len & 1)
228 		cur_sum += (data[len-1] << 8);
229 
230 	return cur_sum;
231 }
232 
233 /* Fold a raw checksum: 'cur_sum' is in host byte order, while the
234  * return value is in network byte order.
235  */
236 uint16_t
nm_os_csum_fold(rawsum_t cur_sum)237 nm_os_csum_fold(rawsum_t cur_sum)
238 {
239 	/* TODO XXX please use the FreeBSD implementation for this. */
240 	while (cur_sum >> 16)
241 		cur_sum = (cur_sum & 0xFFFF) + (cur_sum >> 16);
242 
243 	return htobe16((~cur_sum) & 0xFFFF);
244 }
245 
nm_os_csum_ipv4(struct nm_iphdr * iph)246 uint16_t nm_os_csum_ipv4(struct nm_iphdr *iph)
247 {
248 #if 0
249 	return in_cksum_hdr((void *)iph);
250 #else
251 	return nm_os_csum_fold(nm_os_csum_raw((uint8_t*)iph, sizeof(struct nm_iphdr), 0));
252 #endif
253 }
254 
255 void
nm_os_csum_tcpudp_ipv4(struct nm_iphdr * iph,void * data,size_t datalen,uint16_t * check)256 nm_os_csum_tcpudp_ipv4(struct nm_iphdr *iph, void *data,
257 					size_t datalen, uint16_t *check)
258 {
259 #ifdef INET
260 	uint16_t pseudolen = datalen + iph->protocol;
261 
262 	/* Compute and insert the pseudo-header checksum. */
263 	*check = in_pseudo(iph->saddr, iph->daddr,
264 				 htobe16(pseudolen));
265 	/* Compute the checksum on TCP/UDP header + payload
266 	 * (includes the pseudo-header).
267 	 */
268 	*check = nm_os_csum_fold(nm_os_csum_raw(data, datalen, 0));
269 #else
270 	static int notsupported = 0;
271 	if (!notsupported) {
272 		notsupported = 1;
273 		nm_prerr("inet4 segmentation not supported");
274 	}
275 #endif
276 }
277 
278 void
nm_os_csum_tcpudp_ipv6(struct nm_ipv6hdr * ip6h,void * data,size_t datalen,uint16_t * check)279 nm_os_csum_tcpudp_ipv6(struct nm_ipv6hdr *ip6h, void *data,
280 					size_t datalen, uint16_t *check)
281 {
282 #ifdef INET6
283 	*check = in6_cksum_pseudo((void*)ip6h, datalen, ip6h->nexthdr, 0);
284 	*check = nm_os_csum_fold(nm_os_csum_raw(data, datalen, 0));
285 #else
286 	static int notsupported = 0;
287 	if (!notsupported) {
288 		notsupported = 1;
289 		nm_prerr("inet6 segmentation not supported");
290 	}
291 #endif
292 }
293 
294 /* on FreeBSD we send up one packet at a time */
295 void *
nm_os_send_up(if_t ifp,struct mbuf * m,struct mbuf * prev)296 nm_os_send_up(if_t ifp, struct mbuf *m, struct mbuf *prev)
297 {
298 	NA(ifp)->if_input(ifp, m);
299 	return NULL;
300 }
301 
302 int
nm_os_mbuf_has_csum_offld(struct mbuf * m)303 nm_os_mbuf_has_csum_offld(struct mbuf *m)
304 {
305 	return m->m_pkthdr.csum_flags & (CSUM_TCP | CSUM_UDP | CSUM_SCTP |
306 					 CSUM_TCP_IPV6 | CSUM_UDP_IPV6 |
307 					 CSUM_SCTP_IPV6);
308 }
309 
310 int
nm_os_mbuf_has_seg_offld(struct mbuf * m)311 nm_os_mbuf_has_seg_offld(struct mbuf *m)
312 {
313 	return m->m_pkthdr.csum_flags & CSUM_TSO;
314 }
315 
316 static void
freebsd_generic_rx_handler(if_t ifp,struct mbuf * m)317 freebsd_generic_rx_handler(if_t ifp, struct mbuf *m)
318 {
319 	int stolen;
320 
321 	if (unlikely(!NM_NA_VALID(ifp))) {
322 		nm_prlim(1, "Warning: RX packet intercepted, but no"
323 				" emulated adapter");
324 		return;
325 	}
326 
327 	do {
328 		struct mbuf *n;
329 
330 		n = m->m_nextpkt;
331 		m->m_nextpkt = NULL;
332 		stolen = generic_rx_handler(ifp, m);
333 		if (!stolen) {
334 			NA(ifp)->if_input(ifp, m);
335 		}
336 		m = n;
337 	} while (m != NULL);
338 }
339 
340 /*
341  * Intercept the rx routine in the standard device driver.
342  * Second argument is non-zero to intercept, 0 to restore
343  */
344 int
nm_os_catch_rx(struct netmap_generic_adapter * gna,int intercept)345 nm_os_catch_rx(struct netmap_generic_adapter *gna, int intercept)
346 {
347 	struct netmap_adapter *na = &gna->up.up;
348 	if_t ifp = na->ifp;
349 	int ret = 0;
350 
351 	nm_os_ifnet_lock();
352 	if (intercept) {
353 		if_setcapenablebit(ifp, IFCAP_NETMAP, 0);
354 		if_setinputfn(ifp, freebsd_generic_rx_handler);
355 	} else {
356 		if_setcapenablebit(ifp, 0, IFCAP_NETMAP);
357 		if_setinputfn(ifp, na->if_input);
358 	}
359 	nm_os_ifnet_unlock();
360 
361 	return ret;
362 }
363 
364 
365 /*
366  * Intercept the packet steering routine in the tx path,
367  * so that we can decide which queue is used for an mbuf.
368  * Second argument is non-zero to intercept, 0 to restore.
369  * On freebsd we just intercept if_transmit.
370  */
371 int
nm_os_catch_tx(struct netmap_generic_adapter * gna,int intercept)372 nm_os_catch_tx(struct netmap_generic_adapter *gna, int intercept)
373 {
374 	struct netmap_adapter *na = &gna->up.up;
375 	if_t ifp = netmap_generic_getifp(gna);
376 
377 	nm_os_ifnet_lock();
378 	if (intercept) {
379 		na->if_transmit = if_gettransmitfn(ifp);
380 		if_settransmitfn(ifp, netmap_transmit);
381 	} else {
382 		if_settransmitfn(ifp, na->if_transmit);
383 	}
384 	nm_os_ifnet_unlock();
385 
386 	return 0;
387 }
388 
389 
390 /*
391  * Transmit routine used by generic_netmap_txsync(). Returns 0 on success
392  * and non-zero on error (which may be packet drops or other errors).
393  * addr and len identify the netmap buffer, m is the (preallocated)
394  * mbuf to use for transmissions.
395  *
396  * Zero-copy transmission is possible if netmap is attached directly to a
397  * hardware interface: when cleaning we simply wait for the mbuf cluster
398  * refcount to decrement to 1, indicating that the driver has completed
399  * transmission and is done with the buffer.  However, this approach can
400  * lead to queue deadlocks when attaching to software interfaces (e.g.,
401  * if_bridge) since we cannot rely on member ports to promptly reclaim
402  * transmitted mbufs.  Since there is no easy way to distinguish these
403  * cases, we currently always copy the buffer.
404  *
405  * On multiqueue cards, we can force the queue using
406  *      if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE)
407  *              i = m->m_pkthdr.flowid % adapter->num_queues;
408  *      else
409  *              i = curcpu % adapter->num_queues;
410  */
411 int
nm_os_generic_xmit_frame(struct nm_os_gen_arg * a)412 nm_os_generic_xmit_frame(struct nm_os_gen_arg *a)
413 {
414 	int ret;
415 	u_int len = a->len;
416 	if_t ifp = a->ifp;
417 	struct mbuf *m = a->m;
418 
419 	M_ASSERTPKTHDR(m);
420 	KASSERT((m->m_flags & M_EXT) != 0,
421 	    ("%s: mbuf %p has no cluster", __func__, m));
422 
423 	if (MBUF_REFCNT(m) != 1) {
424 		nm_prerr("invalid refcnt %d for %p", MBUF_REFCNT(m), m);
425 		panic("in generic_xmit_frame");
426 	}
427 	if (unlikely(m->m_ext.ext_size < len)) {
428 		nm_prlim(2, "size %d < len %d", m->m_ext.ext_size, len);
429 		len = m->m_ext.ext_size;
430 	}
431 
432 	m_copyback(m, 0, len, a->addr);
433 	m->m_len = m->m_pkthdr.len = len;
434 	SET_MBUF_REFCNT(m, 2);
435 	M_HASHTYPE_SET(m, M_HASHTYPE_OPAQUE);
436 	m->m_pkthdr.flowid = a->ring_nr;
437 	m->m_pkthdr.rcvif = ifp; /* used for tx notification */
438 	CURVNET_SET(if_getvnet(ifp));
439 	ret = NA(ifp)->if_transmit(ifp, m);
440 	CURVNET_RESTORE();
441 	return ret ? -1 : 0;
442 }
443 
444 struct netmap_adapter *
netmap_getna(if_t ifp)445 netmap_getna(if_t ifp)
446 {
447 	return (NA(ifp));
448 }
449 
450 /*
451  * The following two functions are empty until we have a generic
452  * way to extract the info from the ifp
453  */
454 int
nm_os_generic_find_num_desc(if_t ifp,unsigned int * tx,unsigned int * rx)455 nm_os_generic_find_num_desc(if_t ifp, unsigned int *tx, unsigned int *rx)
456 {
457 	return 0;
458 }
459 
460 
461 void
nm_os_generic_find_num_queues(if_t ifp,u_int * txq,u_int * rxq)462 nm_os_generic_find_num_queues(if_t ifp, u_int *txq, u_int *rxq)
463 {
464 	unsigned num_rings = netmap_generic_rings ? netmap_generic_rings : 1;
465 
466 	*txq = num_rings;
467 	*rxq = num_rings;
468 }
469 
470 void
nm_os_generic_set_features(struct netmap_generic_adapter * gna)471 nm_os_generic_set_features(struct netmap_generic_adapter *gna)
472 {
473 
474 	gna->rxsg = 1; /* Supported through m_copydata. */
475 	gna->txqdisc = 0; /* Not supported. */
476 }
477 
478 void
nm_os_mitigation_init(struct nm_generic_mit * mit,int idx,struct netmap_adapter * na)479 nm_os_mitigation_init(struct nm_generic_mit *mit, int idx, struct netmap_adapter *na)
480 {
481 	mit->mit_pending = 0;
482 	mit->mit_ring_idx = idx;
483 	mit->mit_na = na;
484 }
485 
486 
487 void
nm_os_mitigation_start(struct nm_generic_mit * mit)488 nm_os_mitigation_start(struct nm_generic_mit *mit)
489 {
490 }
491 
492 
493 void
nm_os_mitigation_restart(struct nm_generic_mit * mit)494 nm_os_mitigation_restart(struct nm_generic_mit *mit)
495 {
496 }
497 
498 
499 int
nm_os_mitigation_active(struct nm_generic_mit * mit)500 nm_os_mitigation_active(struct nm_generic_mit *mit)
501 {
502 
503 	return 0;
504 }
505 
506 
507 void
nm_os_mitigation_cleanup(struct nm_generic_mit * mit)508 nm_os_mitigation_cleanup(struct nm_generic_mit *mit)
509 {
510 }
511 
512 static int
nm_vi_dummy(if_t ifp,u_long cmd,caddr_t addr)513 nm_vi_dummy(if_t ifp, u_long cmd, caddr_t addr)
514 {
515 
516 	return EINVAL;
517 }
518 
519 static void
nm_vi_start(if_t ifp)520 nm_vi_start(if_t ifp)
521 {
522 	panic("nm_vi_start() must not be called");
523 }
524 
525 /*
526  * Index manager of persistent virtual interfaces.
527  * It is used to decide the lowest byte of the MAC address.
528  * We use the same algorithm with management of bridge port index.
529  */
530 #define NM_VI_MAX	255
531 static struct {
532 	uint8_t index[NM_VI_MAX]; /* XXX just for a reasonable number */
533 	uint8_t active;
534 	struct mtx lock;
535 } nm_vi_indices;
536 
537 void
nm_os_vi_init_index(void)538 nm_os_vi_init_index(void)
539 {
540 	int i;
541 	for (i = 0; i < NM_VI_MAX; i++)
542 		nm_vi_indices.index[i] = i;
543 	nm_vi_indices.active = 0;
544 	mtx_init(&nm_vi_indices.lock, "nm_vi_indices_lock", NULL, MTX_DEF);
545 }
546 
547 /* return -1 if no index available */
548 static int
nm_vi_get_index(void)549 nm_vi_get_index(void)
550 {
551 	int ret;
552 
553 	mtx_lock(&nm_vi_indices.lock);
554 	ret = nm_vi_indices.active == NM_VI_MAX ? -1 :
555 		nm_vi_indices.index[nm_vi_indices.active++];
556 	mtx_unlock(&nm_vi_indices.lock);
557 	return ret;
558 }
559 
560 static void
nm_vi_free_index(uint8_t val)561 nm_vi_free_index(uint8_t val)
562 {
563 	int i, lim;
564 
565 	mtx_lock(&nm_vi_indices.lock);
566 	lim = nm_vi_indices.active;
567 	for (i = 0; i < lim; i++) {
568 		if (nm_vi_indices.index[i] == val) {
569 			/* swap index[lim-1] and j */
570 			int tmp = nm_vi_indices.index[lim-1];
571 			nm_vi_indices.index[lim-1] = val;
572 			nm_vi_indices.index[i] = tmp;
573 			nm_vi_indices.active--;
574 			break;
575 		}
576 	}
577 	if (lim == nm_vi_indices.active)
578 		nm_prerr("Index %u not found", val);
579 	mtx_unlock(&nm_vi_indices.lock);
580 }
581 #undef NM_VI_MAX
582 
583 /*
584  * Implementation of a netmap-capable virtual interface that
585  * registered to the system.
586  * It is based on if_tap.c and ip_fw_log.c in FreeBSD 9.
587  *
588  * Note: Linux sets refcount to 0 on allocation of net_device,
589  * then increments it on registration to the system.
590  * FreeBSD sets refcount to 1 on if_alloc(), and does not
591  * increment this refcount on if_attach().
592  */
593 int
nm_os_vi_persist(const char * name,if_t * ret)594 nm_os_vi_persist(const char *name, if_t *ret)
595 {
596 	if_t ifp;
597 	u_short macaddr_hi;
598 	uint32_t macaddr_mid;
599 	u_char eaddr[6];
600 	int unit = nm_vi_get_index(); /* just to decide MAC address */
601 
602 	if (unit < 0)
603 		return EBUSY;
604 	/*
605 	 * We use the same MAC address generation method with tap
606 	 * except for the highest octet is 00:be instead of 00:bd
607 	 */
608 	macaddr_hi = htons(0x00be); /* XXX tap + 1 */
609 	macaddr_mid = (uint32_t) ticks;
610 	bcopy(&macaddr_hi, eaddr, sizeof(short));
611 	bcopy(&macaddr_mid, &eaddr[2], sizeof(uint32_t));
612 	eaddr[5] = (uint8_t)unit;
613 
614 	ifp = if_alloc(IFT_ETHER);
615 	if_initname(ifp, name, IF_DUNIT_NONE);
616 	if_setflags(ifp, IFF_UP | IFF_SIMPLEX | IFF_MULTICAST);
617 	if_setinitfn(ifp, (void *)nm_vi_dummy);
618 	if_setioctlfn(ifp, nm_vi_dummy);
619 	if_setstartfn(ifp, nm_vi_start);
620 	if_setmtu(ifp, ETHERMTU);
621 	if_setsendqlen(ifp, ifqmaxlen);
622 	if_setcapabilitiesbit(ifp, IFCAP_LINKSTATE, 0);
623 	if_setcapenablebit(ifp, IFCAP_LINKSTATE, 0);
624 
625 	ether_ifattach(ifp, eaddr);
626 	*ret = ifp;
627 	return 0;
628 }
629 
630 /* unregister from the system and drop the final refcount */
631 void
nm_os_vi_detach(if_t ifp)632 nm_os_vi_detach(if_t ifp)
633 {
634 	nm_vi_free_index(((char *)if_getlladdr(ifp))[5]);
635 	ether_ifdetach(ifp);
636 	if_free(ifp);
637 }
638 
639 #ifdef WITH_EXTMEM
640 #include <vm/vm_map.h>
641 #include <vm/vm_extern.h>
642 #include <vm/vm_kern.h>
643 struct nm_os_extmem {
644 	vm_object_t obj;
645 	vm_offset_t kva;
646 	vm_offset_t size;
647 	uintptr_t scan;
648 };
649 
650 void
nm_os_extmem_delete(struct nm_os_extmem * e)651 nm_os_extmem_delete(struct nm_os_extmem *e)
652 {
653 	nm_prinf("freeing %zx bytes", (size_t)e->size);
654 	vm_map_remove(kernel_map, e->kva, e->kva + e->size);
655 	nm_os_free(e);
656 }
657 
658 char *
nm_os_extmem_nextpage(struct nm_os_extmem * e)659 nm_os_extmem_nextpage(struct nm_os_extmem *e)
660 {
661 	char *rv = NULL;
662 	if (e->scan < e->kva + e->size) {
663 		rv = (char *)e->scan;
664 		e->scan += PAGE_SIZE;
665 	}
666 	return rv;
667 }
668 
669 int
nm_os_extmem_isequal(struct nm_os_extmem * e1,struct nm_os_extmem * e2)670 nm_os_extmem_isequal(struct nm_os_extmem *e1, struct nm_os_extmem *e2)
671 {
672 	return (e1->obj == e2->obj);
673 }
674 
675 int
nm_os_extmem_nr_pages(struct nm_os_extmem * e)676 nm_os_extmem_nr_pages(struct nm_os_extmem *e)
677 {
678 	return e->size >> PAGE_SHIFT;
679 }
680 
681 struct nm_os_extmem *
nm_os_extmem_create(unsigned long p,struct nmreq_pools_info * pi,int * perror)682 nm_os_extmem_create(unsigned long p, struct nmreq_pools_info *pi, int *perror)
683 {
684 	vm_map_t map;
685 	vm_map_entry_t entry;
686 	vm_object_t obj;
687 	vm_prot_t prot;
688 	vm_pindex_t index;
689 	boolean_t wired;
690 	struct nm_os_extmem *e = NULL;
691 	int rv, error = 0;
692 
693 	e = nm_os_malloc(sizeof(*e));
694 	if (e == NULL) {
695 		error = ENOMEM;
696 		goto out;
697 	}
698 
699 	map = &curthread->td_proc->p_vmspace->vm_map;
700 	rv = vm_map_lookup(&map, p, VM_PROT_RW, &entry,
701 			&obj, &index, &prot, &wired);
702 	if (rv != KERN_SUCCESS) {
703 		nm_prerr("address %lx not found", p);
704 		error = vm_mmap_to_errno(rv);
705 		goto out_free;
706 	}
707 	vm_object_reference(obj);
708 
709 	/* check that we are given the whole vm_object ? */
710 	vm_map_lookup_done(map, entry);
711 
712 	e->obj = obj;
713 	/* Wire the memory and add the vm_object to the kernel map,
714 	 * to make sure that it is not freed even if all the processes
715 	 * that are mmap()ing should munmap() it.
716 	 */
717 	e->kva = vm_map_min(kernel_map);
718 	e->size = obj->size << PAGE_SHIFT;
719 	rv = vm_map_find(kernel_map, obj, 0, &e->kva, e->size, 0,
720 			VMFS_OPTIMAL_SPACE, VM_PROT_READ | VM_PROT_WRITE,
721 			VM_PROT_READ | VM_PROT_WRITE, 0);
722 	if (rv != KERN_SUCCESS) {
723 		nm_prerr("vm_map_find(%zx) failed", (size_t)e->size);
724 		error = vm_mmap_to_errno(rv);
725 		goto out_rel;
726 	}
727 	rv = vm_map_wire(kernel_map, e->kva, e->kva + e->size,
728 			VM_MAP_WIRE_SYSTEM | VM_MAP_WIRE_NOHOLES);
729 	if (rv != KERN_SUCCESS) {
730 		nm_prerr("vm_map_wire failed");
731 		error = vm_mmap_to_errno(rv);
732 		goto out_rem;
733 	}
734 
735 	e->scan = e->kva;
736 
737 	return e;
738 
739 out_rem:
740 	vm_map_remove(kernel_map, e->kva, e->kva + e->size);
741 out_rel:
742 	vm_object_deallocate(e->obj);
743 	e->obj = NULL;
744 out_free:
745 	nm_os_free(e);
746 out:
747 	if (perror)
748 		*perror = error;
749 	return NULL;
750 }
751 #endif /* WITH_EXTMEM */
752 
753 /* ================== PTNETMAP GUEST SUPPORT ==================== */
754 
755 #ifdef WITH_PTNETMAP
756 #include <sys/bus.h>
757 #include <sys/rman.h>
758 #include <machine/bus.h>        /* bus_dmamap_* */
759 #include <machine/resource.h>
760 #include <dev/pci/pcivar.h>
761 #include <dev/pci/pcireg.h>
762 /*
763  * ptnetmap memory device (memdev) for freebsd guest,
764  * ssed to expose host netmap memory to the guest through a PCI BAR.
765  */
766 
767 /*
768  * ptnetmap memdev private data structure
769  */
770 struct ptnetmap_memdev {
771 	device_t dev;
772 	struct resource *pci_io;
773 	struct resource *pci_mem;
774 	struct netmap_mem_d *nm_mem;
775 };
776 
777 static int	ptn_memdev_probe(device_t);
778 static int	ptn_memdev_attach(device_t);
779 static int	ptn_memdev_detach(device_t);
780 static int	ptn_memdev_shutdown(device_t);
781 
782 static device_method_t ptn_memdev_methods[] = {
783 	DEVMETHOD(device_probe, ptn_memdev_probe),
784 	DEVMETHOD(device_attach, ptn_memdev_attach),
785 	DEVMETHOD(device_detach, ptn_memdev_detach),
786 	DEVMETHOD(device_shutdown, ptn_memdev_shutdown),
787 	DEVMETHOD_END
788 };
789 
790 static driver_t ptn_memdev_driver = {
791 	PTNETMAP_MEMDEV_NAME,
792 	ptn_memdev_methods,
793 	sizeof(struct ptnetmap_memdev),
794 };
795 
796 /* We use (SI_ORDER_MIDDLE+1) here, see DEV_MODULE_ORDERED() invocation
797  * below. */
798 DRIVER_MODULE_ORDERED(ptn_memdev, pci, ptn_memdev_driver, NULL, NULL,
799 		      SI_ORDER_MIDDLE + 1);
800 
801 /*
802  * Map host netmap memory through PCI-BAR in the guest OS,
803  * returning physical (nm_paddr) and virtual (nm_addr) addresses
804  * of the netmap memory mapped in the guest.
805  */
806 int
nm_os_pt_memdev_iomap(struct ptnetmap_memdev * ptn_dev,vm_paddr_t * nm_paddr,void ** nm_addr,uint64_t * mem_size)807 nm_os_pt_memdev_iomap(struct ptnetmap_memdev *ptn_dev, vm_paddr_t *nm_paddr,
808 		      void **nm_addr, uint64_t *mem_size)
809 {
810 	int rid;
811 
812 	nm_prinf("ptn_memdev_driver iomap");
813 
814 	rid = PCIR_BAR(PTNETMAP_MEM_PCI_BAR);
815 	*mem_size = bus_read_4(ptn_dev->pci_io, PTNET_MDEV_IO_MEMSIZE_HI);
816 	*mem_size = bus_read_4(ptn_dev->pci_io, PTNET_MDEV_IO_MEMSIZE_LO) |
817 			(*mem_size << 32);
818 
819 	/* map memory allocator */
820 	ptn_dev->pci_mem = bus_alloc_resource(ptn_dev->dev, SYS_RES_MEMORY,
821 			&rid, 0, ~0, *mem_size, RF_ACTIVE);
822 	if (ptn_dev->pci_mem == NULL) {
823 		*nm_paddr = 0;
824 		*nm_addr = NULL;
825 		return ENOMEM;
826 	}
827 
828 	*nm_paddr = rman_get_start(ptn_dev->pci_mem);
829 	*nm_addr = rman_get_virtual(ptn_dev->pci_mem);
830 
831 	nm_prinf("=== BAR %d start %lx len %lx mem_size %lx ===",
832 			PTNETMAP_MEM_PCI_BAR,
833 			(unsigned long)(*nm_paddr),
834 			(unsigned long)rman_get_size(ptn_dev->pci_mem),
835 			(unsigned long)*mem_size);
836 	return (0);
837 }
838 
839 uint32_t
nm_os_pt_memdev_ioread(struct ptnetmap_memdev * ptn_dev,unsigned int reg)840 nm_os_pt_memdev_ioread(struct ptnetmap_memdev *ptn_dev, unsigned int reg)
841 {
842 	return bus_read_4(ptn_dev->pci_io, reg);
843 }
844 
845 /* Unmap host netmap memory. */
846 void
nm_os_pt_memdev_iounmap(struct ptnetmap_memdev * ptn_dev)847 nm_os_pt_memdev_iounmap(struct ptnetmap_memdev *ptn_dev)
848 {
849 	nm_prinf("ptn_memdev_driver iounmap");
850 
851 	if (ptn_dev->pci_mem) {
852 		bus_release_resource(ptn_dev->dev, SYS_RES_MEMORY,
853 			PCIR_BAR(PTNETMAP_MEM_PCI_BAR), ptn_dev->pci_mem);
854 		ptn_dev->pci_mem = NULL;
855 	}
856 }
857 
858 /* Device identification routine, return BUS_PROBE_DEFAULT on success,
859  * positive on failure */
860 static int
ptn_memdev_probe(device_t dev)861 ptn_memdev_probe(device_t dev)
862 {
863 	if (pci_get_vendor(dev) != PTNETMAP_PCI_VENDOR_ID)
864 		return (ENXIO);
865 	if (pci_get_device(dev) != PTNETMAP_PCI_DEVICE_ID)
866 		return (ENXIO);
867 
868 	device_set_descf(dev, "%s PCI adapter", PTNETMAP_MEMDEV_NAME);
869 
870 	return (BUS_PROBE_DEFAULT);
871 }
872 
873 /* Device initialization routine. */
874 static int
ptn_memdev_attach(device_t dev)875 ptn_memdev_attach(device_t dev)
876 {
877 	struct ptnetmap_memdev *ptn_dev;
878 	int rid;
879 	uint16_t mem_id;
880 
881 	ptn_dev = device_get_softc(dev);
882 	ptn_dev->dev = dev;
883 
884 	pci_enable_busmaster(dev);
885 
886 	rid = PCIR_BAR(PTNETMAP_IO_PCI_BAR);
887 	ptn_dev->pci_io = bus_alloc_resource_any(dev, SYS_RES_IOPORT, &rid,
888 						 RF_ACTIVE);
889 	if (ptn_dev->pci_io == NULL) {
890 	        device_printf(dev, "cannot map I/O space\n");
891 	        return (ENXIO);
892 	}
893 
894 	mem_id = bus_read_4(ptn_dev->pci_io, PTNET_MDEV_IO_MEMID);
895 
896 	/* create guest allocator */
897 	ptn_dev->nm_mem = netmap_mem_pt_guest_attach(ptn_dev, mem_id);
898 	if (ptn_dev->nm_mem == NULL) {
899 		ptn_memdev_detach(dev);
900 	        return (ENOMEM);
901 	}
902 	netmap_mem_get(ptn_dev->nm_mem);
903 
904 	nm_prinf("ptnetmap memdev attached, host memid: %u", mem_id);
905 
906 	return (0);
907 }
908 
909 /* Device removal routine. */
910 static int
ptn_memdev_detach(device_t dev)911 ptn_memdev_detach(device_t dev)
912 {
913 	struct ptnetmap_memdev *ptn_dev;
914 
915 	ptn_dev = device_get_softc(dev);
916 
917 	if (ptn_dev->nm_mem) {
918 		nm_prinf("ptnetmap memdev detached, host memid %u",
919 			netmap_mem_get_id(ptn_dev->nm_mem));
920 		netmap_mem_put(ptn_dev->nm_mem);
921 		ptn_dev->nm_mem = NULL;
922 	}
923 	if (ptn_dev->pci_mem) {
924 		bus_release_resource(dev, SYS_RES_MEMORY,
925 			PCIR_BAR(PTNETMAP_MEM_PCI_BAR), ptn_dev->pci_mem);
926 		ptn_dev->pci_mem = NULL;
927 	}
928 	if (ptn_dev->pci_io) {
929 		bus_release_resource(dev, SYS_RES_IOPORT,
930 			PCIR_BAR(PTNETMAP_IO_PCI_BAR), ptn_dev->pci_io);
931 		ptn_dev->pci_io = NULL;
932 	}
933 
934 	return (0);
935 }
936 
937 static int
ptn_memdev_shutdown(device_t dev)938 ptn_memdev_shutdown(device_t dev)
939 {
940 	return bus_generic_shutdown(dev);
941 }
942 
943 #endif /* WITH_PTNETMAP */
944 
945 /*
946  * In order to track whether pages are still mapped, we hook into
947  * the standard cdev_pager and intercept the constructor and
948  * destructor.
949  */
950 
951 struct netmap_vm_handle_t {
952 	struct cdev 		*dev;
953 	struct netmap_priv_d	*priv;
954 };
955 
956 
957 static int
netmap_dev_pager_ctor(void * handle,vm_ooffset_t size,vm_prot_t prot,vm_ooffset_t foff,struct ucred * cred,u_short * color)958 netmap_dev_pager_ctor(void *handle, vm_ooffset_t size, vm_prot_t prot,
959 		vm_ooffset_t foff, struct ucred *cred, u_short *color)
960 {
961 	struct netmap_vm_handle_t *vmh = handle;
962 
963 	if (netmap_verbose)
964 		nm_prinf("handle %p size %jd prot %d foff %jd",
965 			handle, (intmax_t)size, prot, (intmax_t)foff);
966 	if (color)
967 		*color = 0;
968 	dev_ref(vmh->dev);
969 	return 0;
970 }
971 
972 
973 static void
netmap_dev_pager_dtor(void * handle)974 netmap_dev_pager_dtor(void *handle)
975 {
976 	struct netmap_vm_handle_t *vmh = handle;
977 	struct cdev *dev = vmh->dev;
978 	struct netmap_priv_d *priv = vmh->priv;
979 
980 	if (netmap_verbose)
981 		nm_prinf("handle %p", handle);
982 	netmap_dtor(priv);
983 	free(vmh, M_DEVBUF);
984 	dev_rel(dev);
985 }
986 
987 
988 static int
netmap_dev_pager_fault(vm_object_t object,vm_ooffset_t offset,int prot,vm_page_t * mres)989 netmap_dev_pager_fault(vm_object_t object, vm_ooffset_t offset,
990 	int prot, vm_page_t *mres)
991 {
992 	struct netmap_vm_handle_t *vmh = object->handle;
993 	struct netmap_priv_d *priv = vmh->priv;
994 	struct netmap_adapter *na = priv->np_na;
995 	vm_paddr_t paddr;
996 	vm_page_t page;
997 	vm_memattr_t memattr;
998 
999 	nm_prdis("object %p offset %jd prot %d mres %p",
1000 			object, (intmax_t)offset, prot, mres);
1001 	memattr = object->memattr;
1002 	paddr = netmap_mem_ofstophys(na->nm_mem, offset);
1003 	if (paddr == 0)
1004 		return VM_PAGER_FAIL;
1005 
1006 	if (((*mres)->flags & PG_FICTITIOUS) != 0) {
1007 		/*
1008 		 * If the passed in result page is a fake page, update it with
1009 		 * the new physical address.
1010 		 */
1011 		page = *mres;
1012 		vm_page_updatefake(page, paddr, memattr);
1013 	} else {
1014 		/*
1015 		 * Replace the passed in reqpage page with our own fake page and
1016 		 * free up the all of the original pages.
1017 		 */
1018 		VM_OBJECT_WUNLOCK(object);
1019 		page = vm_page_getfake(paddr, memattr);
1020 		VM_OBJECT_WLOCK(object);
1021 		vm_page_replace(page, object, (*mres)->pindex, *mres);
1022 		*mres = page;
1023 	}
1024 	page->valid = VM_PAGE_BITS_ALL;
1025 	return (VM_PAGER_OK);
1026 }
1027 
1028 
1029 static struct cdev_pager_ops netmap_cdev_pager_ops = {
1030 	.cdev_pg_ctor = netmap_dev_pager_ctor,
1031 	.cdev_pg_dtor = netmap_dev_pager_dtor,
1032 	.cdev_pg_fault = netmap_dev_pager_fault,
1033 };
1034 
1035 
1036 static int
netmap_mmap_single(struct cdev * cdev,vm_ooffset_t * foff,vm_size_t objsize,vm_object_t * objp,int prot)1037 netmap_mmap_single(struct cdev *cdev, vm_ooffset_t *foff,
1038 	vm_size_t objsize,  vm_object_t *objp, int prot)
1039 {
1040 	int error;
1041 	struct netmap_vm_handle_t *vmh;
1042 	struct netmap_priv_d *priv;
1043 	vm_object_t obj;
1044 
1045 	if (netmap_verbose)
1046 		nm_prinf("cdev %p foff %jd size %jd objp %p prot %d", cdev,
1047 		    (intmax_t )*foff, (intmax_t )objsize, objp, prot);
1048 
1049 	vmh = malloc(sizeof(struct netmap_vm_handle_t), M_DEVBUF,
1050 			      M_NOWAIT | M_ZERO);
1051 	if (vmh == NULL)
1052 		return ENOMEM;
1053 	vmh->dev = cdev;
1054 
1055 	NMG_LOCK();
1056 	error = devfs_get_cdevpriv((void**)&priv);
1057 	if (error)
1058 		goto err_unlock;
1059 	if (priv->np_nifp == NULL) {
1060 		error = EINVAL;
1061 		goto err_unlock;
1062 	}
1063 	vmh->priv = priv;
1064 	priv->np_refs++;
1065 	NMG_UNLOCK();
1066 
1067 	obj = cdev_pager_allocate(vmh, OBJT_DEVICE,
1068 		&netmap_cdev_pager_ops, objsize, prot,
1069 		*foff, NULL);
1070 	if (obj == NULL) {
1071 		nm_prerr("cdev_pager_allocate failed");
1072 		error = EINVAL;
1073 		goto err_deref;
1074 	}
1075 
1076 	*objp = obj;
1077 	return 0;
1078 
1079 err_deref:
1080 	NMG_LOCK();
1081 	priv->np_refs--;
1082 err_unlock:
1083 	NMG_UNLOCK();
1084 // err:
1085 	free(vmh, M_DEVBUF);
1086 	return error;
1087 }
1088 
1089 /*
1090  * On FreeBSD the close routine is only called on the last close on
1091  * the device (/dev/netmap) so we cannot do anything useful.
1092  * To track close() on individual file descriptors we pass netmap_dtor() to
1093  * devfs_set_cdevpriv() on open(). The FreeBSD kernel will call the destructor
1094  * when the last fd pointing to the device is closed.
1095  *
1096  * Note that FreeBSD does not even munmap() on close() so we also have
1097  * to track mmap() ourselves, and postpone the call to
1098  * netmap_dtor() is called when the process has no open fds and no active
1099  * memory maps on /dev/netmap, as in linux.
1100  */
1101 static int
netmap_close(struct cdev * dev,int fflag,int devtype,struct thread * td)1102 netmap_close(struct cdev *dev, int fflag, int devtype, struct thread *td)
1103 {
1104 	if (netmap_verbose)
1105 		nm_prinf("dev %p fflag 0x%x devtype %d td %p",
1106 			dev, fflag, devtype, td);
1107 	return 0;
1108 }
1109 
1110 
1111 static int
netmap_open(struct cdev * dev,int oflags,int devtype,struct thread * td)1112 netmap_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
1113 {
1114 	struct netmap_priv_d *priv;
1115 	int error;
1116 
1117 	(void)dev;
1118 	(void)oflags;
1119 	(void)devtype;
1120 	(void)td;
1121 
1122 	NMG_LOCK();
1123 	priv = netmap_priv_new();
1124 	if (priv == NULL) {
1125 		error = ENOMEM;
1126 		goto out;
1127 	}
1128 	error = devfs_set_cdevpriv(priv, netmap_dtor);
1129 	if (error) {
1130 		netmap_priv_delete(priv);
1131 	}
1132 out:
1133 	NMG_UNLOCK();
1134 	return error;
1135 }
1136 
1137 /******************** kthread wrapper ****************/
1138 #include <sys/sysproto.h>
1139 u_int
nm_os_ncpus(void)1140 nm_os_ncpus(void)
1141 {
1142 	return mp_maxid + 1;
1143 }
1144 
1145 struct nm_kctx_ctx {
1146 	/* Userspace thread (kthread creator). */
1147 	struct thread *user_td;
1148 
1149 	/* worker function and parameter */
1150 	nm_kctx_worker_fn_t worker_fn;
1151 	void *worker_private;
1152 
1153 	struct nm_kctx *nmk;
1154 
1155 	/* integer to manage multiple worker contexts (e.g., RX or TX on ptnetmap) */
1156 	long type;
1157 };
1158 
1159 struct nm_kctx {
1160 	struct thread *worker;
1161 	struct mtx worker_lock;
1162 	struct nm_kctx_ctx worker_ctx;
1163 	int run;			/* used to stop kthread */
1164 	int attach_user;		/* kthread attached to user_process */
1165 	int affinity;
1166 };
1167 
1168 static void
nm_kctx_worker(void * data)1169 nm_kctx_worker(void *data)
1170 {
1171 	struct nm_kctx *nmk = data;
1172 	struct nm_kctx_ctx *ctx = &nmk->worker_ctx;
1173 
1174 	if (nmk->affinity >= 0) {
1175 		thread_lock(curthread);
1176 		sched_bind(curthread, nmk->affinity);
1177 		thread_unlock(curthread);
1178 	}
1179 
1180 	while (nmk->run) {
1181 		/*
1182 		 * check if the parent process dies
1183 		 * (when kthread is attached to user process)
1184 		 */
1185 		if (ctx->user_td) {
1186 			PROC_LOCK(curproc);
1187 			thread_suspend_check(0);
1188 			PROC_UNLOCK(curproc);
1189 		} else {
1190 			kthread_suspend_check();
1191 		}
1192 
1193 		/* Continuously execute worker process. */
1194 		ctx->worker_fn(ctx->worker_private); /* worker body */
1195 	}
1196 
1197 	kthread_exit();
1198 }
1199 
1200 void
nm_os_kctx_worker_setaff(struct nm_kctx * nmk,int affinity)1201 nm_os_kctx_worker_setaff(struct nm_kctx *nmk, int affinity)
1202 {
1203 	nmk->affinity = affinity;
1204 }
1205 
1206 struct nm_kctx *
nm_os_kctx_create(struct nm_kctx_cfg * cfg,void * opaque)1207 nm_os_kctx_create(struct nm_kctx_cfg *cfg, void *opaque)
1208 {
1209 	struct nm_kctx *nmk = NULL;
1210 
1211 	nmk = malloc(sizeof(*nmk),  M_DEVBUF, M_NOWAIT | M_ZERO);
1212 	if (!nmk)
1213 		return NULL;
1214 
1215 	mtx_init(&nmk->worker_lock, "nm_kthread lock", NULL, MTX_DEF);
1216 	nmk->worker_ctx.worker_fn = cfg->worker_fn;
1217 	nmk->worker_ctx.worker_private = cfg->worker_private;
1218 	nmk->worker_ctx.type = cfg->type;
1219 	nmk->affinity = -1;
1220 
1221 	/* attach kthread to user process (ptnetmap) */
1222 	nmk->attach_user = cfg->attach_user;
1223 
1224 	return nmk;
1225 }
1226 
1227 int
nm_os_kctx_worker_start(struct nm_kctx * nmk)1228 nm_os_kctx_worker_start(struct nm_kctx *nmk)
1229 {
1230 	struct proc *p = NULL;
1231 	int error = 0;
1232 
1233 	/* Temporarily disable this function as it is currently broken
1234 	 * and causes kernel crashes. The failure can be triggered by
1235 	 * the "vale_polling_enable_disable" test in ctrl-api-test.c. */
1236 	return EOPNOTSUPP;
1237 
1238 	if (nmk->worker)
1239 		return EBUSY;
1240 
1241 	/* check if we want to attach kthread to user process */
1242 	if (nmk->attach_user) {
1243 		nmk->worker_ctx.user_td = curthread;
1244 		p = curthread->td_proc;
1245 	}
1246 
1247 	/* enable kthread main loop */
1248 	nmk->run = 1;
1249 	/* create kthread */
1250 	if((error = kthread_add(nm_kctx_worker, nmk, p,
1251 			&nmk->worker, RFNOWAIT /* to be checked */, 0, "nm-kthread-%ld",
1252 			nmk->worker_ctx.type))) {
1253 		goto err;
1254 	}
1255 
1256 	nm_prinf("nm_kthread started td %p", nmk->worker);
1257 
1258 	return 0;
1259 err:
1260 	nm_prerr("nm_kthread start failed err %d", error);
1261 	nmk->worker = NULL;
1262 	return error;
1263 }
1264 
1265 void
nm_os_kctx_worker_stop(struct nm_kctx * nmk)1266 nm_os_kctx_worker_stop(struct nm_kctx *nmk)
1267 {
1268 	if (!nmk->worker)
1269 		return;
1270 
1271 	/* tell to kthread to exit from main loop */
1272 	nmk->run = 0;
1273 
1274 	/* wake up kthread if it sleeps */
1275 	kthread_resume(nmk->worker);
1276 
1277 	nmk->worker = NULL;
1278 }
1279 
1280 void
nm_os_kctx_destroy(struct nm_kctx * nmk)1281 nm_os_kctx_destroy(struct nm_kctx *nmk)
1282 {
1283 	if (!nmk)
1284 		return;
1285 
1286 	if (nmk->worker)
1287 		nm_os_kctx_worker_stop(nmk);
1288 
1289 	free(nmk, M_DEVBUF);
1290 }
1291 
1292 /******************** kqueue support ****************/
1293 
1294 /*
1295  * In addition to calling selwakeuppri(), nm_os_selwakeup() also
1296  * needs to call knote() to wake up kqueue listeners.
1297  * This operation is deferred to a taskqueue in order to avoid possible
1298  * lock order reversals; these may happen because knote() grabs a
1299  * private lock associated to the 'si' (see struct selinfo,
1300  * struct nm_selinfo, and nm_os_selinfo_init), and nm_os_selwakeup()
1301  * can be called while holding the lock associated to a different
1302  * 'si'.
1303  * When calling knote() we use a non-zero 'hint' argument to inform
1304  * the netmap_knrw() function that it is being called from
1305  * 'nm_os_selwakeup'; this is necessary because when netmap_knrw() is
1306  * called by the kevent subsystem (i.e. kevent_scan()) we also need to
1307  * call netmap_poll().
1308  *
1309  * The netmap_kqfilter() function registers one or another f_event
1310  * depending on read or write mode. A pointer to the struct
1311  * 'netmap_priv_d' is stored into kn->kn_hook, so that it can later
1312  * be passed to netmap_poll(). We pass NULL as a third argument to
1313  * netmap_poll(), so that the latter only runs the txsync/rxsync
1314  * (if necessary), and skips the nm_os_selrecord() calls.
1315  */
1316 
1317 
1318 void
nm_os_selwakeup(struct nm_selinfo * si)1319 nm_os_selwakeup(struct nm_selinfo *si)
1320 {
1321 	selwakeuppri(&si->si, PI_NET);
1322 	if (si->kqueue_users > 0) {
1323 		taskqueue_enqueue(si->ntfytq, &si->ntfytask);
1324 	}
1325 }
1326 
1327 void
nm_os_selrecord(struct thread * td,struct nm_selinfo * si)1328 nm_os_selrecord(struct thread *td, struct nm_selinfo *si)
1329 {
1330 	selrecord(td, &si->si);
1331 }
1332 
1333 static void
netmap_knrdetach(struct knote * kn)1334 netmap_knrdetach(struct knote *kn)
1335 {
1336 	struct netmap_priv_d *priv = (struct netmap_priv_d *)kn->kn_hook;
1337 	struct nm_selinfo *si = priv->np_si[NR_RX];
1338 
1339 	knlist_remove(&si->si.si_note, kn, /*islocked=*/0);
1340 	NMG_LOCK();
1341 	KASSERT(si->kqueue_users > 0, ("kqueue_user underflow on %s",
1342 	    si->mtxname));
1343 	si->kqueue_users--;
1344 	nm_prinf("kqueue users for %s: %d", si->mtxname, si->kqueue_users);
1345 	NMG_UNLOCK();
1346 }
1347 
1348 static void
netmap_knwdetach(struct knote * kn)1349 netmap_knwdetach(struct knote *kn)
1350 {
1351 	struct netmap_priv_d *priv = (struct netmap_priv_d *)kn->kn_hook;
1352 	struct nm_selinfo *si = priv->np_si[NR_TX];
1353 
1354 	knlist_remove(&si->si.si_note, kn, /*islocked=*/0);
1355 	NMG_LOCK();
1356 	si->kqueue_users--;
1357 	nm_prinf("kqueue users for %s: %d", si->mtxname, si->kqueue_users);
1358 	NMG_UNLOCK();
1359 }
1360 
1361 /*
1362  * Callback triggered by netmap notifications (see netmap_notify()),
1363  * and by the application calling kevent(). In the former case we
1364  * just return 1 (events ready), since we are not able to do better.
1365  * In the latter case we use netmap_poll() to see which events are
1366  * ready.
1367  */
1368 static int
netmap_knrw(struct knote * kn,long hint,int events)1369 netmap_knrw(struct knote *kn, long hint, int events)
1370 {
1371 	struct netmap_priv_d *priv;
1372 	int revents;
1373 
1374 	if (hint != 0) {
1375 		/* Called from netmap_notify(), typically from a
1376 		 * thread different from the one issuing kevent().
1377 		 * Assume we are ready. */
1378 		return 1;
1379 	}
1380 
1381 	/* Called from kevent(). */
1382 	priv = kn->kn_hook;
1383 	revents = netmap_poll(priv, events, /*thread=*/NULL);
1384 
1385 	return (events & revents) ? 1 : 0;
1386 }
1387 
1388 static int
netmap_knread(struct knote * kn,long hint)1389 netmap_knread(struct knote *kn, long hint)
1390 {
1391 	return netmap_knrw(kn, hint, POLLIN);
1392 }
1393 
1394 static int
netmap_knwrite(struct knote * kn,long hint)1395 netmap_knwrite(struct knote *kn, long hint)
1396 {
1397 	return netmap_knrw(kn, hint, POLLOUT);
1398 }
1399 
1400 static struct filterops netmap_rfiltops = {
1401 	.f_isfd = 1,
1402 	.f_detach = netmap_knrdetach,
1403 	.f_event = netmap_knread,
1404 };
1405 
1406 static struct filterops netmap_wfiltops = {
1407 	.f_isfd = 1,
1408 	.f_detach = netmap_knwdetach,
1409 	.f_event = netmap_knwrite,
1410 };
1411 
1412 
1413 /*
1414  * This is called when a thread invokes kevent() to record
1415  * a change in the configuration of the kqueue().
1416  * The 'priv' is the one associated to the open netmap device.
1417  */
1418 static int
netmap_kqfilter(struct cdev * dev,struct knote * kn)1419 netmap_kqfilter(struct cdev *dev, struct knote *kn)
1420 {
1421 	struct netmap_priv_d *priv;
1422 	int error;
1423 	struct netmap_adapter *na;
1424 	struct nm_selinfo *si;
1425 	int ev = kn->kn_filter;
1426 
1427 	if (ev != EVFILT_READ && ev != EVFILT_WRITE) {
1428 		nm_prerr("bad filter request %d", ev);
1429 		return 1;
1430 	}
1431 	error = devfs_get_cdevpriv((void**)&priv);
1432 	if (error) {
1433 		nm_prerr("device not yet setup");
1434 		return 1;
1435 	}
1436 	na = priv->np_na;
1437 	if (na == NULL) {
1438 		nm_prerr("no netmap adapter for this file descriptor");
1439 		return 1;
1440 	}
1441 	/* the si is indicated in the priv */
1442 	si = priv->np_si[(ev == EVFILT_WRITE) ? NR_TX : NR_RX];
1443 	kn->kn_fop = (ev == EVFILT_WRITE) ?
1444 		&netmap_wfiltops : &netmap_rfiltops;
1445 	kn->kn_hook = priv;
1446 	NMG_LOCK();
1447 	si->kqueue_users++;
1448 	nm_prinf("kqueue users for %s: %d", si->mtxname, si->kqueue_users);
1449 	NMG_UNLOCK();
1450 	knlist_add(&si->si.si_note, kn, /*islocked=*/0);
1451 
1452 	return 0;
1453 }
1454 
1455 static int
freebsd_netmap_poll(struct cdev * cdevi __unused,int events,struct thread * td)1456 freebsd_netmap_poll(struct cdev *cdevi __unused, int events, struct thread *td)
1457 {
1458 	struct netmap_priv_d *priv;
1459 	if (devfs_get_cdevpriv((void **)&priv)) {
1460 		return POLLERR;
1461 	}
1462 	return netmap_poll(priv, events, td);
1463 }
1464 
1465 static int
freebsd_netmap_ioctl(struct cdev * dev __unused,u_long cmd,caddr_t data,int ffla __unused,struct thread * td)1466 freebsd_netmap_ioctl(struct cdev *dev __unused, u_long cmd, caddr_t data,
1467 		int ffla __unused, struct thread *td)
1468 {
1469 	int error;
1470 	struct netmap_priv_d *priv;
1471 
1472 	CURVNET_SET(TD_TO_VNET(td));
1473 	error = devfs_get_cdevpriv((void **)&priv);
1474 	if (error) {
1475 		/* XXX ENOENT should be impossible, since the priv
1476 		 * is now created in the open */
1477 		if (error == ENOENT)
1478 			error = ENXIO;
1479 		goto out;
1480 	}
1481 	error = netmap_ioctl(priv, cmd, data, td, /*nr_body_is_user=*/1);
1482 out:
1483 	CURVNET_RESTORE();
1484 
1485 	return error;
1486 }
1487 
1488 void
nm_os_onattach(if_t ifp)1489 nm_os_onattach(if_t ifp)
1490 {
1491 	if_setcapabilitiesbit(ifp, IFCAP_NETMAP, 0);
1492 }
1493 
1494 void
nm_os_onenter(if_t ifp)1495 nm_os_onenter(if_t ifp)
1496 {
1497 	struct netmap_adapter *na = NA(ifp);
1498 
1499 	na->if_transmit = if_gettransmitfn(ifp);
1500 	if_settransmitfn(ifp, netmap_transmit);
1501 	if_setcapenablebit(ifp, IFCAP_NETMAP, 0);
1502 }
1503 
1504 void
nm_os_onexit(if_t ifp)1505 nm_os_onexit(if_t ifp)
1506 {
1507 	struct netmap_adapter *na = NA(ifp);
1508 
1509 	if_settransmitfn(ifp, na->if_transmit);
1510 	if_setcapenablebit(ifp, 0, IFCAP_NETMAP);
1511 }
1512 
1513 extern struct cdevsw netmap_cdevsw; /* XXX used in netmap.c, should go elsewhere */
1514 struct cdevsw netmap_cdevsw = {
1515 	.d_version = D_VERSION,
1516 	.d_name = "netmap",
1517 	.d_open = netmap_open,
1518 	.d_mmap_single = netmap_mmap_single,
1519 	.d_ioctl = freebsd_netmap_ioctl,
1520 	.d_poll = freebsd_netmap_poll,
1521 	.d_kqfilter = netmap_kqfilter,
1522 	.d_close = netmap_close,
1523 };
1524 /*--- end of kqueue support ----*/
1525 
1526 /*
1527  * Kernel entry point.
1528  *
1529  * Initialize/finalize the module and return.
1530  *
1531  * Return 0 on success, errno on failure.
1532  */
1533 static int
netmap_loader(__unused struct module * module,int event,__unused void * arg)1534 netmap_loader(__unused struct module *module, int event, __unused void *arg)
1535 {
1536 	int error = 0;
1537 
1538 	switch (event) {
1539 	case MOD_LOAD:
1540 		error = netmap_init();
1541 		break;
1542 
1543 	case MOD_UNLOAD:
1544 		/*
1545 		 * if some one is still using netmap,
1546 		 * then the module can not be unloaded.
1547 		 */
1548 		if (netmap_use_count) {
1549 			nm_prerr("netmap module can not be unloaded - netmap_use_count: %d",
1550 					netmap_use_count);
1551 			error = EBUSY;
1552 			break;
1553 		}
1554 		netmap_fini();
1555 		break;
1556 
1557 	default:
1558 		error = EOPNOTSUPP;
1559 		break;
1560 	}
1561 
1562 	return (error);
1563 }
1564 
1565 #ifdef DEV_MODULE_ORDERED
1566 /*
1567  * The netmap module contains three drivers: (i) the netmap character device
1568  * driver; (ii) the ptnetmap memdev PCI device driver, (iii) the ptnet PCI
1569  * device driver. The attach() routines of both (ii) and (iii) need the
1570  * lock of the global allocator, and such lock is initialized in netmap_init(),
1571  * which is part of (i).
1572  * Therefore, we make sure that (i) is loaded before (ii) and (iii), using
1573  * the 'order' parameter of driver declaration macros. For (i), we specify
1574  * SI_ORDER_MIDDLE, while higher orders are used with the DRIVER_MODULE_ORDERED
1575  * macros for (ii) and (iii).
1576  */
1577 DEV_MODULE_ORDERED(netmap, netmap_loader, NULL, SI_ORDER_MIDDLE);
1578 #else /* !DEV_MODULE_ORDERED */
1579 DEV_MODULE(netmap, netmap_loader, NULL);
1580 #endif /* DEV_MODULE_ORDERED  */
1581 MODULE_DEPEND(netmap, pci, 1, 1, 1);
1582 MODULE_VERSION(netmap, 1);
1583 /* reduce conditional code */
1584 // linux API, use for the knlist in FreeBSD
1585 /* use a private mutex for the knlist */
1586