1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
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 /* $FreeBSD: stable/12/sys/dev/netmap/netmap_freebsd.c 372829 2022-12-31 12:30:28Z git2svn $ */
29 #include "opt_inet.h"
30 #include "opt_inet6.h"
31 
32 #include <sys/param.h>
33 #include <sys/module.h>
34 #include <sys/errno.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,struct ifnet * ifp)173 netmap_ifnet_arrival_handler(void *arg __unused, struct ifnet *ifp)
174 {
175 	netmap_undo_zombie(ifp);
176 }
177 
178 static void
netmap_ifnet_departure_handler(void * arg __unused,struct ifnet * ifp)179 netmap_ifnet_departure_handler(void *arg __unused, struct ifnet *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(struct ifnet * ifp)211 nm_os_ifnet_mtu(struct ifnet *ifp)
212 {
213 	return ifp->if_mtu;
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 cheksum. */
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(struct ifnet * ifp,struct mbuf * m,struct mbuf * prev)296 nm_os_send_up(struct ifnet *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(struct ifnet * ifp,struct mbuf * m)317 freebsd_generic_rx_handler(struct ifnet *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 	stolen = generic_rx_handler(ifp, m);
328 	if (!stolen) {
329 		struct netmap_generic_adapter *gna =
330 				(struct netmap_generic_adapter *)NA(ifp);
331 		gna->save_if_input(ifp, m);
332 	}
333 }
334 
335 /*
336  * Intercept the rx routine in the standard device driver.
337  * Second argument is non-zero to intercept, 0 to restore
338  */
339 int
nm_os_catch_rx(struct netmap_generic_adapter * gna,int intercept)340 nm_os_catch_rx(struct netmap_generic_adapter *gna, int intercept)
341 {
342 	struct netmap_adapter *na = &gna->up.up;
343 	struct ifnet *ifp = na->ifp;
344 	int ret = 0;
345 
346 	nm_os_ifnet_lock();
347 	if (intercept) {
348 		if (gna->save_if_input) {
349 			nm_prerr("RX on %s already intercepted", na->name);
350 			ret = EBUSY; /* already set */
351 			goto out;
352 		}
353 		gna->save_if_input = ifp->if_input;
354 		ifp->if_input = freebsd_generic_rx_handler;
355 	} else {
356 		if (!gna->save_if_input) {
357 			nm_prerr("Failed to undo RX intercept on %s",
358 				na->name);
359 			ret = EINVAL;  /* not saved */
360 			goto out;
361 		}
362 		ifp->if_input = gna->save_if_input;
363 		gna->save_if_input = NULL;
364 	}
365 out:
366 	nm_os_ifnet_unlock();
367 
368 	return ret;
369 }
370 
371 
372 /*
373  * Intercept the packet steering routine in the tx path,
374  * so that we can decide which queue is used for an mbuf.
375  * Second argument is non-zero to intercept, 0 to restore.
376  * On freebsd we just intercept if_transmit.
377  */
378 int
nm_os_catch_tx(struct netmap_generic_adapter * gna,int intercept)379 nm_os_catch_tx(struct netmap_generic_adapter *gna, int intercept)
380 {
381 	struct netmap_adapter *na = &gna->up.up;
382 	struct ifnet *ifp = netmap_generic_getifp(gna);
383 
384 	nm_os_ifnet_lock();
385 	if (intercept) {
386 		na->if_transmit = ifp->if_transmit;
387 		ifp->if_transmit = netmap_transmit;
388 	} else {
389 		ifp->if_transmit = na->if_transmit;
390 	}
391 	nm_os_ifnet_unlock();
392 
393 	return 0;
394 }
395 
396 
397 /*
398  * Transmit routine used by generic_netmap_txsync(). Returns 0 on success
399  * and non-zero on error (which may be packet drops or other errors).
400  * addr and len identify the netmap buffer, m is the (preallocated)
401  * mbuf to use for transmissions.
402  *
403  * We should add a reference to the mbuf so the m_freem() at the end
404  * of the transmission does not consume resources.
405  *
406  * On FreeBSD, and on multiqueue cards, we can force the queue using
407  *      if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE)
408  *              i = m->m_pkthdr.flowid % adapter->num_queues;
409  *      else
410  *              i = curcpu % adapter->num_queues;
411  *
412  */
413 int
nm_os_generic_xmit_frame(struct nm_os_gen_arg * a)414 nm_os_generic_xmit_frame(struct nm_os_gen_arg *a)
415 {
416 	int ret;
417 	u_int len = a->len;
418 	struct ifnet *ifp = a->ifp;
419 	struct mbuf *m = a->m;
420 
421 	/* Link the external storage to
422 	 * the netmap buffer, so that no copy is necessary. */
423 	m->m_ext.ext_buf = m->m_data = a->addr;
424 	m->m_ext.ext_size = len;
425 
426 	m->m_flags |= M_PKTHDR;
427 	m->m_len = m->m_pkthdr.len = len;
428 
429 	/* mbuf refcnt is not contended, no need to use atomic
430 	 * (a memory barrier is enough). */
431 	SET_MBUF_REFCNT(m, 2);
432 	M_HASHTYPE_SET(m, M_HASHTYPE_OPAQUE);
433 	m->m_pkthdr.flowid = a->ring_nr;
434 	m->m_pkthdr.rcvif = ifp; /* used for tx notification */
435 	CURVNET_SET(ifp->if_vnet);
436 	ret = NA(ifp)->if_transmit(ifp, m);
437 	CURVNET_RESTORE();
438 	return ret ? -1 : 0;
439 }
440 
441 
442 struct netmap_adapter *
netmap_getna(if_t ifp)443 netmap_getna(if_t ifp)
444 {
445 	return (NA((struct ifnet *)ifp));
446 }
447 
448 /*
449  * The following two functions are empty until we have a generic
450  * way to extract the info from the ifp
451  */
452 int
nm_os_generic_find_num_desc(struct ifnet * ifp,unsigned int * tx,unsigned int * rx)453 nm_os_generic_find_num_desc(struct ifnet *ifp, unsigned int *tx, unsigned int *rx)
454 {
455 	return 0;
456 }
457 
458 
459 void
nm_os_generic_find_num_queues(struct ifnet * ifp,u_int * txq,u_int * rxq)460 nm_os_generic_find_num_queues(struct ifnet *ifp, u_int *txq, u_int *rxq)
461 {
462 	unsigned num_rings = netmap_generic_rings ? netmap_generic_rings : 1;
463 
464 	*txq = num_rings;
465 	*rxq = num_rings;
466 }
467 
468 void
nm_os_generic_set_features(struct netmap_generic_adapter * gna)469 nm_os_generic_set_features(struct netmap_generic_adapter *gna)
470 {
471 
472 	gna->rxsg = 1; /* Supported through m_copydata. */
473 	gna->txqdisc = 0; /* Not supported. */
474 }
475 
476 void
nm_os_mitigation_init(struct nm_generic_mit * mit,int idx,struct netmap_adapter * na)477 nm_os_mitigation_init(struct nm_generic_mit *mit, int idx, struct netmap_adapter *na)
478 {
479 	mit->mit_pending = 0;
480 	mit->mit_ring_idx = idx;
481 	mit->mit_na = na;
482 }
483 
484 
485 void
nm_os_mitigation_start(struct nm_generic_mit * mit)486 nm_os_mitigation_start(struct nm_generic_mit *mit)
487 {
488 }
489 
490 
491 void
nm_os_mitigation_restart(struct nm_generic_mit * mit)492 nm_os_mitigation_restart(struct nm_generic_mit *mit)
493 {
494 }
495 
496 
497 int
nm_os_mitigation_active(struct nm_generic_mit * mit)498 nm_os_mitigation_active(struct nm_generic_mit *mit)
499 {
500 
501 	return 0;
502 }
503 
504 
505 void
nm_os_mitigation_cleanup(struct nm_generic_mit * mit)506 nm_os_mitigation_cleanup(struct nm_generic_mit *mit)
507 {
508 }
509 
510 static int
nm_vi_dummy(struct ifnet * ifp,u_long cmd,caddr_t addr)511 nm_vi_dummy(struct ifnet *ifp, u_long cmd, caddr_t addr)
512 {
513 
514 	return EINVAL;
515 }
516 
517 static void
nm_vi_start(struct ifnet * ifp)518 nm_vi_start(struct ifnet *ifp)
519 {
520 	panic("nm_vi_start() must not be called");
521 }
522 
523 /*
524  * Index manager of persistent virtual interfaces.
525  * It is used to decide the lowest byte of the MAC address.
526  * We use the same algorithm with management of bridge port index.
527  */
528 #define NM_VI_MAX	255
529 static struct {
530 	uint8_t index[NM_VI_MAX]; /* XXX just for a reasonable number */
531 	uint8_t active;
532 	struct mtx lock;
533 } nm_vi_indices;
534 
535 void
nm_os_vi_init_index(void)536 nm_os_vi_init_index(void)
537 {
538 	int i;
539 	for (i = 0; i < NM_VI_MAX; i++)
540 		nm_vi_indices.index[i] = i;
541 	nm_vi_indices.active = 0;
542 	mtx_init(&nm_vi_indices.lock, "nm_vi_indices_lock", NULL, MTX_DEF);
543 }
544 
545 /* return -1 if no index available */
546 static int
nm_vi_get_index(void)547 nm_vi_get_index(void)
548 {
549 	int ret;
550 
551 	mtx_lock(&nm_vi_indices.lock);
552 	ret = nm_vi_indices.active == NM_VI_MAX ? -1 :
553 		nm_vi_indices.index[nm_vi_indices.active++];
554 	mtx_unlock(&nm_vi_indices.lock);
555 	return ret;
556 }
557 
558 static void
nm_vi_free_index(uint8_t val)559 nm_vi_free_index(uint8_t val)
560 {
561 	int i, lim;
562 
563 	mtx_lock(&nm_vi_indices.lock);
564 	lim = nm_vi_indices.active;
565 	for (i = 0; i < lim; i++) {
566 		if (nm_vi_indices.index[i] == val) {
567 			/* swap index[lim-1] and j */
568 			int tmp = nm_vi_indices.index[lim-1];
569 			nm_vi_indices.index[lim-1] = val;
570 			nm_vi_indices.index[i] = tmp;
571 			nm_vi_indices.active--;
572 			break;
573 		}
574 	}
575 	if (lim == nm_vi_indices.active)
576 		nm_prerr("Index %u not found", val);
577 	mtx_unlock(&nm_vi_indices.lock);
578 }
579 #undef NM_VI_MAX
580 
581 /*
582  * Implementation of a netmap-capable virtual interface that
583  * registered to the system.
584  * It is based on if_tap.c and ip_fw_log.c in FreeBSD 9.
585  *
586  * Note: Linux sets refcount to 0 on allocation of net_device,
587  * then increments it on registration to the system.
588  * FreeBSD sets refcount to 1 on if_alloc(), and does not
589  * increment this refcount on if_attach().
590  */
591 int
nm_os_vi_persist(const char * name,struct ifnet ** ret)592 nm_os_vi_persist(const char *name, struct ifnet **ret)
593 {
594 	struct ifnet *ifp;
595 	u_short macaddr_hi;
596 	uint32_t macaddr_mid;
597 	u_char eaddr[6];
598 	int unit = nm_vi_get_index(); /* just to decide MAC address */
599 
600 	if (unit < 0)
601 		return EBUSY;
602 	/*
603 	 * We use the same MAC address generation method with tap
604 	 * except for the highest octet is 00:be instead of 00:bd
605 	 */
606 	macaddr_hi = htons(0x00be); /* XXX tap + 1 */
607 	macaddr_mid = (uint32_t) ticks;
608 	bcopy(&macaddr_hi, eaddr, sizeof(short));
609 	bcopy(&macaddr_mid, &eaddr[2], sizeof(uint32_t));
610 	eaddr[5] = (uint8_t)unit;
611 
612 	ifp = if_alloc(IFT_ETHER);
613 	if (ifp == NULL) {
614 		nm_prerr("if_alloc failed");
615 		return ENOMEM;
616 	}
617 	if_initname(ifp, name, IF_DUNIT_NONE);
618 	ifp->if_mtu = 65536;
619 	ifp->if_flags = IFF_UP | IFF_SIMPLEX | IFF_MULTICAST;
620 	ifp->if_init = (void *)nm_vi_dummy;
621 	ifp->if_ioctl = nm_vi_dummy;
622 	ifp->if_start = nm_vi_start;
623 	ifp->if_mtu = ETHERMTU;
624 	IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen);
625 	ifp->if_capabilities |= IFCAP_LINKSTATE;
626 	ifp->if_capenable |= IFCAP_LINKSTATE;
627 
628 	ether_ifattach(ifp, eaddr);
629 	*ret = ifp;
630 	return 0;
631 }
632 
633 /* unregister from the system and drop the final refcount */
634 void
nm_os_vi_detach(struct ifnet * ifp)635 nm_os_vi_detach(struct ifnet *ifp)
636 {
637 	nm_vi_free_index(((char *)IF_LLADDR(ifp))[5]);
638 	ether_ifdetach(ifp);
639 	if_free(ifp);
640 }
641 
642 #ifdef WITH_EXTMEM
643 #include <vm/vm_map.h>
644 #include <vm/vm_extern.h>
645 #include <vm/vm_kern.h>
646 struct nm_os_extmem {
647 	vm_object_t obj;
648 	vm_offset_t kva;
649 	vm_offset_t size;
650 	uintptr_t scan;
651 };
652 
653 void
nm_os_extmem_delete(struct nm_os_extmem * e)654 nm_os_extmem_delete(struct nm_os_extmem *e)
655 {
656 	nm_prinf("freeing %zx bytes", (size_t)e->size);
657 	vm_map_remove(kernel_map, e->kva, e->kva + e->size);
658 	nm_os_free(e);
659 }
660 
661 char *
nm_os_extmem_nextpage(struct nm_os_extmem * e)662 nm_os_extmem_nextpage(struct nm_os_extmem *e)
663 {
664 	char *rv = NULL;
665 	if (e->scan < e->kva + e->size) {
666 		rv = (char *)e->scan;
667 		e->scan += PAGE_SIZE;
668 	}
669 	return rv;
670 }
671 
672 int
nm_os_extmem_isequal(struct nm_os_extmem * e1,struct nm_os_extmem * e2)673 nm_os_extmem_isequal(struct nm_os_extmem *e1, struct nm_os_extmem *e2)
674 {
675 	return (e1->obj == e2->obj);
676 }
677 
678 int
nm_os_extmem_nr_pages(struct nm_os_extmem * e)679 nm_os_extmem_nr_pages(struct nm_os_extmem *e)
680 {
681 	return e->size >> PAGE_SHIFT;
682 }
683 
684 struct nm_os_extmem *
nm_os_extmem_create(unsigned long p,struct nmreq_pools_info * pi,int * perror)685 nm_os_extmem_create(unsigned long p, struct nmreq_pools_info *pi, int *perror)
686 {
687 	vm_map_t map;
688 	vm_map_entry_t entry;
689 	vm_object_t obj;
690 	vm_prot_t prot;
691 	vm_pindex_t index;
692 	boolean_t wired;
693 	struct nm_os_extmem *e = NULL;
694 	int rv, error = 0;
695 
696 	e = nm_os_malloc(sizeof(*e));
697 	if (e == NULL) {
698 		error = ENOMEM;
699 		goto out;
700 	}
701 
702 	map = &curthread->td_proc->p_vmspace->vm_map;
703 	rv = vm_map_lookup(&map, p, VM_PROT_RW, &entry,
704 			&obj, &index, &prot, &wired);
705 	if (rv != KERN_SUCCESS) {
706 		nm_prerr("address %lx not found", p);
707 		error = vm_mmap_to_errno(rv);
708 		goto out_free;
709 	}
710 	vm_object_reference(obj);
711 
712 	/* check that we are given the whole vm_object ? */
713 	vm_map_lookup_done(map, entry);
714 
715 	e->obj = obj;
716 	/* Wire the memory and add the vm_object to the kernel map,
717 	 * to make sure that it is not freed even if all the processes
718 	 * that are mmap()ing should munmap() it.
719 	 */
720 	e->kva = vm_map_min(kernel_map);
721 	e->size = obj->size << PAGE_SHIFT;
722 	rv = vm_map_find(kernel_map, obj, 0, &e->kva, e->size, 0,
723 			VMFS_OPTIMAL_SPACE, VM_PROT_READ | VM_PROT_WRITE,
724 			VM_PROT_READ | VM_PROT_WRITE, 0);
725 	if (rv != KERN_SUCCESS) {
726 		nm_prerr("vm_map_find(%zx) failed", (size_t)e->size);
727 		error = vm_mmap_to_errno(rv);
728 		goto out_rel;
729 	}
730 	rv = vm_map_wire(kernel_map, e->kva, e->kva + e->size,
731 			VM_MAP_WIRE_SYSTEM | VM_MAP_WIRE_NOHOLES);
732 	if (rv != KERN_SUCCESS) {
733 		nm_prerr("vm_map_wire failed");
734 		error = vm_mmap_to_errno(rv);
735 		goto out_rem;
736 	}
737 
738 	e->scan = e->kva;
739 
740 	return e;
741 
742 out_rem:
743 	vm_map_remove(kernel_map, e->kva, e->kva + e->size);
744 out_rel:
745 	vm_object_deallocate(e->obj);
746 	e->obj = NULL;
747 out_free:
748 	nm_os_free(e);
749 out:
750 	if (perror)
751 		*perror = error;
752 	return NULL;
753 }
754 #endif /* WITH_EXTMEM */
755 
756 /* ================== PTNETMAP GUEST SUPPORT ==================== */
757 
758 #ifdef WITH_PTNETMAP
759 #include <sys/bus.h>
760 #include <sys/rman.h>
761 #include <machine/bus.h>        /* bus_dmamap_* */
762 #include <machine/resource.h>
763 #include <dev/pci/pcivar.h>
764 #include <dev/pci/pcireg.h>
765 /*
766  * ptnetmap memory device (memdev) for freebsd guest,
767  * ssed to expose host netmap memory to the guest through a PCI BAR.
768  */
769 
770 /*
771  * ptnetmap memdev private data structure
772  */
773 struct ptnetmap_memdev {
774 	device_t dev;
775 	struct resource *pci_io;
776 	struct resource *pci_mem;
777 	struct netmap_mem_d *nm_mem;
778 };
779 
780 static int	ptn_memdev_probe(device_t);
781 static int	ptn_memdev_attach(device_t);
782 static int	ptn_memdev_detach(device_t);
783 static int	ptn_memdev_shutdown(device_t);
784 
785 static device_method_t ptn_memdev_methods[] = {
786 	DEVMETHOD(device_probe, ptn_memdev_probe),
787 	DEVMETHOD(device_attach, ptn_memdev_attach),
788 	DEVMETHOD(device_detach, ptn_memdev_detach),
789 	DEVMETHOD(device_shutdown, ptn_memdev_shutdown),
790 	DEVMETHOD_END
791 };
792 
793 static driver_t ptn_memdev_driver = {
794 	PTNETMAP_MEMDEV_NAME,
795 	ptn_memdev_methods,
796 	sizeof(struct ptnetmap_memdev),
797 };
798 
799 /* We use (SI_ORDER_MIDDLE+1) here, see DEV_MODULE_ORDERED() invocation
800  * below. */
801 static devclass_t ptnetmap_devclass;
802 DRIVER_MODULE_ORDERED(ptn_memdev, pci, ptn_memdev_driver, ptnetmap_devclass,
803 		      NULL, NULL, SI_ORDER_MIDDLE + 1);
804 
805 /*
806  * Map host netmap memory through PCI-BAR in the guest OS,
807  * returning physical (nm_paddr) and virtual (nm_addr) addresses
808  * of the netmap memory mapped in the guest.
809  */
810 int
nm_os_pt_memdev_iomap(struct ptnetmap_memdev * ptn_dev,vm_paddr_t * nm_paddr,void ** nm_addr,uint64_t * mem_size)811 nm_os_pt_memdev_iomap(struct ptnetmap_memdev *ptn_dev, vm_paddr_t *nm_paddr,
812 		      void **nm_addr, uint64_t *mem_size)
813 {
814 	int rid;
815 
816 	nm_prinf("ptn_memdev_driver iomap");
817 
818 	rid = PCIR_BAR(PTNETMAP_MEM_PCI_BAR);
819 	*mem_size = bus_read_4(ptn_dev->pci_io, PTNET_MDEV_IO_MEMSIZE_HI);
820 	*mem_size = bus_read_4(ptn_dev->pci_io, PTNET_MDEV_IO_MEMSIZE_LO) |
821 			(*mem_size << 32);
822 
823 	/* map memory allocator */
824 	ptn_dev->pci_mem = bus_alloc_resource(ptn_dev->dev, SYS_RES_MEMORY,
825 			&rid, 0, ~0, *mem_size, RF_ACTIVE);
826 	if (ptn_dev->pci_mem == NULL) {
827 		*nm_paddr = 0;
828 		*nm_addr = NULL;
829 		return ENOMEM;
830 	}
831 
832 	*nm_paddr = rman_get_start(ptn_dev->pci_mem);
833 	*nm_addr = rman_get_virtual(ptn_dev->pci_mem);
834 
835 	nm_prinf("=== BAR %d start %lx len %lx mem_size %lx ===",
836 			PTNETMAP_MEM_PCI_BAR,
837 			(unsigned long)(*nm_paddr),
838 			(unsigned long)rman_get_size(ptn_dev->pci_mem),
839 			(unsigned long)*mem_size);
840 	return (0);
841 }
842 
843 uint32_t
nm_os_pt_memdev_ioread(struct ptnetmap_memdev * ptn_dev,unsigned int reg)844 nm_os_pt_memdev_ioread(struct ptnetmap_memdev *ptn_dev, unsigned int reg)
845 {
846 	return bus_read_4(ptn_dev->pci_io, reg);
847 }
848 
849 /* Unmap host netmap memory. */
850 void
nm_os_pt_memdev_iounmap(struct ptnetmap_memdev * ptn_dev)851 nm_os_pt_memdev_iounmap(struct ptnetmap_memdev *ptn_dev)
852 {
853 	nm_prinf("ptn_memdev_driver iounmap");
854 
855 	if (ptn_dev->pci_mem) {
856 		bus_release_resource(ptn_dev->dev, SYS_RES_MEMORY,
857 			PCIR_BAR(PTNETMAP_MEM_PCI_BAR), ptn_dev->pci_mem);
858 		ptn_dev->pci_mem = NULL;
859 	}
860 }
861 
862 /* Device identification routine, return BUS_PROBE_DEFAULT on success,
863  * positive on failure */
864 static int
ptn_memdev_probe(device_t dev)865 ptn_memdev_probe(device_t dev)
866 {
867 	char desc[256];
868 
869 	if (pci_get_vendor(dev) != PTNETMAP_PCI_VENDOR_ID)
870 		return (ENXIO);
871 	if (pci_get_device(dev) != PTNETMAP_PCI_DEVICE_ID)
872 		return (ENXIO);
873 
874 	snprintf(desc, sizeof(desc), "%s PCI adapter",
875 			PTNETMAP_MEMDEV_NAME);
876 	device_set_desc_copy(dev, desc);
877 
878 	return (BUS_PROBE_DEFAULT);
879 }
880 
881 /* Device initialization routine. */
882 static int
ptn_memdev_attach(device_t dev)883 ptn_memdev_attach(device_t dev)
884 {
885 	struct ptnetmap_memdev *ptn_dev;
886 	int rid;
887 	uint16_t mem_id;
888 
889 	ptn_dev = device_get_softc(dev);
890 	ptn_dev->dev = dev;
891 
892 	pci_enable_busmaster(dev);
893 
894 	rid = PCIR_BAR(PTNETMAP_IO_PCI_BAR);
895 	ptn_dev->pci_io = bus_alloc_resource_any(dev, SYS_RES_IOPORT, &rid,
896 						 RF_ACTIVE);
897 	if (ptn_dev->pci_io == NULL) {
898 	        device_printf(dev, "cannot map I/O space\n");
899 	        return (ENXIO);
900 	}
901 
902 	mem_id = bus_read_4(ptn_dev->pci_io, PTNET_MDEV_IO_MEMID);
903 
904 	/* create guest allocator */
905 	ptn_dev->nm_mem = netmap_mem_pt_guest_attach(ptn_dev, mem_id);
906 	if (ptn_dev->nm_mem == NULL) {
907 		ptn_memdev_detach(dev);
908 	        return (ENOMEM);
909 	}
910 	netmap_mem_get(ptn_dev->nm_mem);
911 
912 	nm_prinf("ptnetmap memdev attached, host memid: %u", mem_id);
913 
914 	return (0);
915 }
916 
917 /* Device removal routine. */
918 static int
ptn_memdev_detach(device_t dev)919 ptn_memdev_detach(device_t dev)
920 {
921 	struct ptnetmap_memdev *ptn_dev;
922 
923 	ptn_dev = device_get_softc(dev);
924 
925 	if (ptn_dev->nm_mem) {
926 		nm_prinf("ptnetmap memdev detached, host memid %u",
927 			netmap_mem_get_id(ptn_dev->nm_mem));
928 		netmap_mem_put(ptn_dev->nm_mem);
929 		ptn_dev->nm_mem = NULL;
930 	}
931 	if (ptn_dev->pci_mem) {
932 		bus_release_resource(dev, SYS_RES_MEMORY,
933 			PCIR_BAR(PTNETMAP_MEM_PCI_BAR), ptn_dev->pci_mem);
934 		ptn_dev->pci_mem = NULL;
935 	}
936 	if (ptn_dev->pci_io) {
937 		bus_release_resource(dev, SYS_RES_IOPORT,
938 			PCIR_BAR(PTNETMAP_IO_PCI_BAR), ptn_dev->pci_io);
939 		ptn_dev->pci_io = NULL;
940 	}
941 
942 	return (0);
943 }
944 
945 static int
ptn_memdev_shutdown(device_t dev)946 ptn_memdev_shutdown(device_t dev)
947 {
948 	return bus_generic_shutdown(dev);
949 }
950 
951 #endif /* WITH_PTNETMAP */
952 
953 /*
954  * In order to track whether pages are still mapped, we hook into
955  * the standard cdev_pager and intercept the constructor and
956  * destructor.
957  */
958 
959 struct netmap_vm_handle_t {
960 	struct cdev 		*dev;
961 	struct netmap_priv_d	*priv;
962 };
963 
964 
965 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)966 netmap_dev_pager_ctor(void *handle, vm_ooffset_t size, vm_prot_t prot,
967 		vm_ooffset_t foff, struct ucred *cred, u_short *color)
968 {
969 	struct netmap_vm_handle_t *vmh = handle;
970 
971 	if (netmap_verbose)
972 		nm_prinf("handle %p size %jd prot %d foff %jd",
973 			handle, (intmax_t)size, prot, (intmax_t)foff);
974 	if (color)
975 		*color = 0;
976 	dev_ref(vmh->dev);
977 	return 0;
978 }
979 
980 
981 static void
netmap_dev_pager_dtor(void * handle)982 netmap_dev_pager_dtor(void *handle)
983 {
984 	struct netmap_vm_handle_t *vmh = handle;
985 	struct cdev *dev = vmh->dev;
986 	struct netmap_priv_d *priv = vmh->priv;
987 
988 	if (netmap_verbose)
989 		nm_prinf("handle %p", handle);
990 	netmap_dtor(priv);
991 	free(vmh, M_DEVBUF);
992 	dev_rel(dev);
993 }
994 
995 
996 static int
netmap_dev_pager_fault(vm_object_t object,vm_ooffset_t offset,int prot,vm_page_t * mres)997 netmap_dev_pager_fault(vm_object_t object, vm_ooffset_t offset,
998 	int prot, vm_page_t *mres)
999 {
1000 	struct netmap_vm_handle_t *vmh = object->handle;
1001 	struct netmap_priv_d *priv = vmh->priv;
1002 	struct netmap_adapter *na = priv->np_na;
1003 	vm_paddr_t paddr;
1004 	vm_page_t page;
1005 	vm_memattr_t memattr;
1006 	vm_pindex_t pidx;
1007 
1008 	nm_prdis("object %p offset %jd prot %d mres %p",
1009 			object, (intmax_t)offset, prot, mres);
1010 	memattr = object->memattr;
1011 	pidx = OFF_TO_IDX(offset);
1012 	paddr = netmap_mem_ofstophys(na->nm_mem, offset);
1013 	if (paddr == 0)
1014 		return VM_PAGER_FAIL;
1015 
1016 	if (((*mres)->flags & PG_FICTITIOUS) != 0) {
1017 		/*
1018 		 * If the passed in result page is a fake page, update it with
1019 		 * the new physical address.
1020 		 */
1021 		page = *mres;
1022 		vm_page_updatefake(page, paddr, memattr);
1023 	} else {
1024 		/*
1025 		 * Replace the passed in reqpage page with our own fake page and
1026 		 * free up the all of the original pages.
1027 		 */
1028 #ifndef VM_OBJECT_WUNLOCK	/* FreeBSD < 10.x */
1029 #define VM_OBJECT_WUNLOCK VM_OBJECT_UNLOCK
1030 #define VM_OBJECT_WLOCK	VM_OBJECT_LOCK
1031 #endif /* VM_OBJECT_WUNLOCK */
1032 
1033 		VM_OBJECT_WUNLOCK(object);
1034 		page = vm_page_getfake(paddr, memattr);
1035 		VM_OBJECT_WLOCK(object);
1036 		vm_page_lock(*mres);
1037 		vm_page_free(*mres);
1038 		vm_page_unlock(*mres);
1039 		*mres = page;
1040 		vm_page_insert(page, object, pidx);
1041 	}
1042 	page->valid = VM_PAGE_BITS_ALL;
1043 	return (VM_PAGER_OK);
1044 }
1045 
1046 
1047 static struct cdev_pager_ops netmap_cdev_pager_ops = {
1048 	.cdev_pg_ctor = netmap_dev_pager_ctor,
1049 	.cdev_pg_dtor = netmap_dev_pager_dtor,
1050 	.cdev_pg_fault = netmap_dev_pager_fault,
1051 };
1052 
1053 
1054 static int
netmap_mmap_single(struct cdev * cdev,vm_ooffset_t * foff,vm_size_t objsize,vm_object_t * objp,int prot)1055 netmap_mmap_single(struct cdev *cdev, vm_ooffset_t *foff,
1056 	vm_size_t objsize,  vm_object_t *objp, int prot)
1057 {
1058 	int error;
1059 	struct netmap_vm_handle_t *vmh;
1060 	struct netmap_priv_d *priv;
1061 	vm_object_t obj;
1062 
1063 	if (netmap_verbose)
1064 		nm_prinf("cdev %p foff %jd size %jd objp %p prot %d", cdev,
1065 		    (intmax_t )*foff, (intmax_t )objsize, objp, prot);
1066 
1067 	vmh = malloc(sizeof(struct netmap_vm_handle_t), M_DEVBUF,
1068 			      M_NOWAIT | M_ZERO);
1069 	if (vmh == NULL)
1070 		return ENOMEM;
1071 	vmh->dev = cdev;
1072 
1073 	NMG_LOCK();
1074 	error = devfs_get_cdevpriv((void**)&priv);
1075 	if (error)
1076 		goto err_unlock;
1077 	if (priv->np_nifp == NULL) {
1078 		error = EINVAL;
1079 		goto err_unlock;
1080 	}
1081 	vmh->priv = priv;
1082 	priv->np_refs++;
1083 	NMG_UNLOCK();
1084 
1085 	obj = cdev_pager_allocate(vmh, OBJT_DEVICE,
1086 		&netmap_cdev_pager_ops, objsize, prot,
1087 		*foff, NULL);
1088 	if (obj == NULL) {
1089 		nm_prerr("cdev_pager_allocate failed");
1090 		error = EINVAL;
1091 		goto err_deref;
1092 	}
1093 
1094 	*objp = obj;
1095 	return 0;
1096 
1097 err_deref:
1098 	NMG_LOCK();
1099 	priv->np_refs--;
1100 err_unlock:
1101 	NMG_UNLOCK();
1102 // err:
1103 	free(vmh, M_DEVBUF);
1104 	return error;
1105 }
1106 
1107 /*
1108  * On FreeBSD the close routine is only called on the last close on
1109  * the device (/dev/netmap) so we cannot do anything useful.
1110  * To track close() on individual file descriptors we pass netmap_dtor() to
1111  * devfs_set_cdevpriv() on open(). The FreeBSD kernel will call the destructor
1112  * when the last fd pointing to the device is closed.
1113  *
1114  * Note that FreeBSD does not even munmap() on close() so we also have
1115  * to track mmap() ourselves, and postpone the call to
1116  * netmap_dtor() is called when the process has no open fds and no active
1117  * memory maps on /dev/netmap, as in linux.
1118  */
1119 static int
netmap_close(struct cdev * dev,int fflag,int devtype,struct thread * td)1120 netmap_close(struct cdev *dev, int fflag, int devtype, struct thread *td)
1121 {
1122 	if (netmap_verbose)
1123 		nm_prinf("dev %p fflag 0x%x devtype %d td %p",
1124 			dev, fflag, devtype, td);
1125 	return 0;
1126 }
1127 
1128 
1129 static int
netmap_open(struct cdev * dev,int oflags,int devtype,struct thread * td)1130 netmap_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
1131 {
1132 	struct netmap_priv_d *priv;
1133 	int error;
1134 
1135 	(void)dev;
1136 	(void)oflags;
1137 	(void)devtype;
1138 	(void)td;
1139 
1140 	NMG_LOCK();
1141 	priv = netmap_priv_new();
1142 	if (priv == NULL) {
1143 		error = ENOMEM;
1144 		goto out;
1145 	}
1146 	error = devfs_set_cdevpriv(priv, netmap_dtor);
1147 	if (error) {
1148 		netmap_priv_delete(priv);
1149 	}
1150 out:
1151 	NMG_UNLOCK();
1152 	return error;
1153 }
1154 
1155 /******************** kthread wrapper ****************/
1156 #include <sys/sysproto.h>
1157 u_int
nm_os_ncpus(void)1158 nm_os_ncpus(void)
1159 {
1160 	return mp_maxid + 1;
1161 }
1162 
1163 struct nm_kctx_ctx {
1164 	/* Userspace thread (kthread creator). */
1165 	struct thread *user_td;
1166 
1167 	/* worker function and parameter */
1168 	nm_kctx_worker_fn_t worker_fn;
1169 	void *worker_private;
1170 
1171 	struct nm_kctx *nmk;
1172 
1173 	/* integer to manage multiple worker contexts (e.g., RX or TX on ptnetmap) */
1174 	long type;
1175 };
1176 
1177 struct nm_kctx {
1178 	struct thread *worker;
1179 	struct mtx worker_lock;
1180 	struct nm_kctx_ctx worker_ctx;
1181 	int run;			/* used to stop kthread */
1182 	int attach_user;		/* kthread attached to user_process */
1183 	int affinity;
1184 };
1185 
1186 static void
nm_kctx_worker(void * data)1187 nm_kctx_worker(void *data)
1188 {
1189 	struct nm_kctx *nmk = data;
1190 	struct nm_kctx_ctx *ctx = &nmk->worker_ctx;
1191 
1192 	if (nmk->affinity >= 0) {
1193 		thread_lock(curthread);
1194 		sched_bind(curthread, nmk->affinity);
1195 		thread_unlock(curthread);
1196 	}
1197 
1198 	while (nmk->run) {
1199 		/*
1200 		 * check if the parent process dies
1201 		 * (when kthread is attached to user process)
1202 		 */
1203 		if (ctx->user_td) {
1204 			PROC_LOCK(curproc);
1205 			thread_suspend_check(0);
1206 			PROC_UNLOCK(curproc);
1207 		} else {
1208 			kthread_suspend_check();
1209 		}
1210 
1211 		/* Continuously execute worker process. */
1212 		ctx->worker_fn(ctx->worker_private); /* worker body */
1213 	}
1214 
1215 	kthread_exit();
1216 }
1217 
1218 void
nm_os_kctx_worker_setaff(struct nm_kctx * nmk,int affinity)1219 nm_os_kctx_worker_setaff(struct nm_kctx *nmk, int affinity)
1220 {
1221 	nmk->affinity = affinity;
1222 }
1223 
1224 struct nm_kctx *
nm_os_kctx_create(struct nm_kctx_cfg * cfg,void * opaque)1225 nm_os_kctx_create(struct nm_kctx_cfg *cfg, void *opaque)
1226 {
1227 	struct nm_kctx *nmk = NULL;
1228 
1229 	nmk = malloc(sizeof(*nmk),  M_DEVBUF, M_NOWAIT | M_ZERO);
1230 	if (!nmk)
1231 		return NULL;
1232 
1233 	mtx_init(&nmk->worker_lock, "nm_kthread lock", NULL, MTX_DEF);
1234 	nmk->worker_ctx.worker_fn = cfg->worker_fn;
1235 	nmk->worker_ctx.worker_private = cfg->worker_private;
1236 	nmk->worker_ctx.type = cfg->type;
1237 	nmk->affinity = -1;
1238 
1239 	/* attach kthread to user process (ptnetmap) */
1240 	nmk->attach_user = cfg->attach_user;
1241 
1242 	return nmk;
1243 }
1244 
1245 int
nm_os_kctx_worker_start(struct nm_kctx * nmk)1246 nm_os_kctx_worker_start(struct nm_kctx *nmk)
1247 {
1248 	struct proc *p = NULL;
1249 	int error = 0;
1250 
1251 	/* Temporarily disable this function as it is currently broken
1252 	 * and causes kernel crashes. The failure can be triggered by
1253 	 * the "vale_polling_enable_disable" test in ctrl-api-test.c. */
1254 	return EOPNOTSUPP;
1255 
1256 	if (nmk->worker)
1257 		return EBUSY;
1258 
1259 	/* check if we want to attach kthread to user process */
1260 	if (nmk->attach_user) {
1261 		nmk->worker_ctx.user_td = curthread;
1262 		p = curthread->td_proc;
1263 	}
1264 
1265 	/* enable kthread main loop */
1266 	nmk->run = 1;
1267 	/* create kthread */
1268 	if((error = kthread_add(nm_kctx_worker, nmk, p,
1269 			&nmk->worker, RFNOWAIT /* to be checked */, 0, "nm-kthread-%ld",
1270 			nmk->worker_ctx.type))) {
1271 		goto err;
1272 	}
1273 
1274 	nm_prinf("nm_kthread started td %p", nmk->worker);
1275 
1276 	return 0;
1277 err:
1278 	nm_prerr("nm_kthread start failed err %d", error);
1279 	nmk->worker = NULL;
1280 	return error;
1281 }
1282 
1283 void
nm_os_kctx_worker_stop(struct nm_kctx * nmk)1284 nm_os_kctx_worker_stop(struct nm_kctx *nmk)
1285 {
1286 	if (!nmk->worker)
1287 		return;
1288 
1289 	/* tell to kthread to exit from main loop */
1290 	nmk->run = 0;
1291 
1292 	/* wake up kthread if it sleeps */
1293 	kthread_resume(nmk->worker);
1294 
1295 	nmk->worker = NULL;
1296 }
1297 
1298 void
nm_os_kctx_destroy(struct nm_kctx * nmk)1299 nm_os_kctx_destroy(struct nm_kctx *nmk)
1300 {
1301 	if (!nmk)
1302 		return;
1303 
1304 	if (nmk->worker)
1305 		nm_os_kctx_worker_stop(nmk);
1306 
1307 	free(nmk, M_DEVBUF);
1308 }
1309 
1310 /******************** kqueue support ****************/
1311 
1312 /*
1313  * In addition to calling selwakeuppri(), nm_os_selwakeup() also
1314  * needs to call knote() to wake up kqueue listeners.
1315  * This operation is deferred to a taskqueue in order to avoid possible
1316  * lock order reversals; these may happen because knote() grabs a
1317  * private lock associated to the 'si' (see struct selinfo,
1318  * struct nm_selinfo, and nm_os_selinfo_init), and nm_os_selwakeup()
1319  * can be called while holding the lock associated to a different
1320  * 'si'.
1321  * When calling knote() we use a non-zero 'hint' argument to inform
1322  * the netmap_knrw() function that it is being called from
1323  * 'nm_os_selwakeup'; this is necessary because when netmap_knrw() is
1324  * called by the kevent subsystem (i.e. kevent_scan()) we also need to
1325  * call netmap_poll().
1326  *
1327  * The netmap_kqfilter() function registers one or another f_event
1328  * depending on read or write mode. A pointer to the struct
1329  * 'netmap_priv_d' is stored into kn->kn_hook, so that it can later
1330  * be passed to netmap_poll(). We pass NULL as a third argument to
1331  * netmap_poll(), so that the latter only runs the txsync/rxsync
1332  * (if necessary), and skips the nm_os_selrecord() calls.
1333  */
1334 
1335 
1336 void
nm_os_selwakeup(struct nm_selinfo * si)1337 nm_os_selwakeup(struct nm_selinfo *si)
1338 {
1339 	selwakeuppri(&si->si, PI_NET);
1340 	if (si->kqueue_users > 0) {
1341 		taskqueue_enqueue(si->ntfytq, &si->ntfytask);
1342 	}
1343 }
1344 
1345 void
nm_os_selrecord(struct thread * td,struct nm_selinfo * si)1346 nm_os_selrecord(struct thread *td, struct nm_selinfo *si)
1347 {
1348 	selrecord(td, &si->si);
1349 }
1350 
1351 static void
netmap_knrdetach(struct knote * kn)1352 netmap_knrdetach(struct knote *kn)
1353 {
1354 	struct netmap_priv_d *priv = (struct netmap_priv_d *)kn->kn_hook;
1355 	struct nm_selinfo *si = priv->np_si[NR_RX];
1356 
1357 	knlist_remove(&si->si.si_note, kn, /*islocked=*/0);
1358 	NMG_LOCK();
1359 	KASSERT(si->kqueue_users > 0, ("kqueue_user underflow on %s",
1360 	    si->mtxname));
1361 	si->kqueue_users--;
1362 	nm_prinf("kqueue users for %s: %d", si->mtxname, si->kqueue_users);
1363 	NMG_UNLOCK();
1364 }
1365 
1366 static void
netmap_knwdetach(struct knote * kn)1367 netmap_knwdetach(struct knote *kn)
1368 {
1369 	struct netmap_priv_d *priv = (struct netmap_priv_d *)kn->kn_hook;
1370 	struct nm_selinfo *si = priv->np_si[NR_TX];
1371 
1372 	knlist_remove(&si->si.si_note, kn, /*islocked=*/0);
1373 	NMG_LOCK();
1374 	si->kqueue_users--;
1375 	nm_prinf("kqueue users for %s: %d", si->mtxname, si->kqueue_users);
1376 	NMG_UNLOCK();
1377 }
1378 
1379 /*
1380  * Callback triggered by netmap notifications (see netmap_notify()),
1381  * and by the application calling kevent(). In the former case we
1382  * just return 1 (events ready), since we are not able to do better.
1383  * In the latter case we use netmap_poll() to see which events are
1384  * ready.
1385  */
1386 static int
netmap_knrw(struct knote * kn,long hint,int events)1387 netmap_knrw(struct knote *kn, long hint, int events)
1388 {
1389 	struct netmap_priv_d *priv;
1390 	int revents;
1391 
1392 	if (hint != 0) {
1393 		/* Called from netmap_notify(), typically from a
1394 		 * thread different from the one issuing kevent().
1395 		 * Assume we are ready. */
1396 		return 1;
1397 	}
1398 
1399 	/* Called from kevent(). */
1400 	priv = kn->kn_hook;
1401 	revents = netmap_poll(priv, events, /*thread=*/NULL);
1402 
1403 	return (events & revents) ? 1 : 0;
1404 }
1405 
1406 static int
netmap_knread(struct knote * kn,long hint)1407 netmap_knread(struct knote *kn, long hint)
1408 {
1409 	return netmap_knrw(kn, hint, POLLIN);
1410 }
1411 
1412 static int
netmap_knwrite(struct knote * kn,long hint)1413 netmap_knwrite(struct knote *kn, long hint)
1414 {
1415 	return netmap_knrw(kn, hint, POLLOUT);
1416 }
1417 
1418 static struct filterops netmap_rfiltops = {
1419 	.f_isfd = 1,
1420 	.f_detach = netmap_knrdetach,
1421 	.f_event = netmap_knread,
1422 };
1423 
1424 static struct filterops netmap_wfiltops = {
1425 	.f_isfd = 1,
1426 	.f_detach = netmap_knwdetach,
1427 	.f_event = netmap_knwrite,
1428 };
1429 
1430 
1431 /*
1432  * This is called when a thread invokes kevent() to record
1433  * a change in the configuration of the kqueue().
1434  * The 'priv' is the one associated to the open netmap device.
1435  */
1436 static int
netmap_kqfilter(struct cdev * dev,struct knote * kn)1437 netmap_kqfilter(struct cdev *dev, struct knote *kn)
1438 {
1439 	struct netmap_priv_d *priv;
1440 	int error;
1441 	struct netmap_adapter *na;
1442 	struct nm_selinfo *si;
1443 	int ev = kn->kn_filter;
1444 
1445 	if (ev != EVFILT_READ && ev != EVFILT_WRITE) {
1446 		nm_prerr("bad filter request %d", ev);
1447 		return 1;
1448 	}
1449 	error = devfs_get_cdevpriv((void**)&priv);
1450 	if (error) {
1451 		nm_prerr("device not yet setup");
1452 		return 1;
1453 	}
1454 	na = priv->np_na;
1455 	if (na == NULL) {
1456 		nm_prerr("no netmap adapter for this file descriptor");
1457 		return 1;
1458 	}
1459 	/* the si is indicated in the priv */
1460 	si = priv->np_si[(ev == EVFILT_WRITE) ? NR_TX : NR_RX];
1461 	kn->kn_fop = (ev == EVFILT_WRITE) ?
1462 		&netmap_wfiltops : &netmap_rfiltops;
1463 	kn->kn_hook = priv;
1464 	NMG_LOCK();
1465 	si->kqueue_users++;
1466 	nm_prinf("kqueue users for %s: %d", si->mtxname, si->kqueue_users);
1467 	NMG_UNLOCK();
1468 	knlist_add(&si->si.si_note, kn, /*islocked=*/0);
1469 
1470 	return 0;
1471 }
1472 
1473 static int
freebsd_netmap_poll(struct cdev * cdevi __unused,int events,struct thread * td)1474 freebsd_netmap_poll(struct cdev *cdevi __unused, int events, struct thread *td)
1475 {
1476 	struct netmap_priv_d *priv;
1477 	if (devfs_get_cdevpriv((void **)&priv)) {
1478 		return POLLERR;
1479 	}
1480 	return netmap_poll(priv, events, td);
1481 }
1482 
1483 static int
freebsd_netmap_ioctl(struct cdev * dev __unused,u_long cmd,caddr_t data,int ffla __unused,struct thread * td)1484 freebsd_netmap_ioctl(struct cdev *dev __unused, u_long cmd, caddr_t data,
1485 		int ffla __unused, struct thread *td)
1486 {
1487 	int error;
1488 	struct netmap_priv_d *priv;
1489 
1490 	CURVNET_SET(TD_TO_VNET(td));
1491 	error = devfs_get_cdevpriv((void **)&priv);
1492 	if (error) {
1493 		/* XXX ENOENT should be impossible, since the priv
1494 		 * is now created in the open */
1495 		if (error == ENOENT)
1496 			error = ENXIO;
1497 		goto out;
1498 	}
1499 	error = netmap_ioctl(priv, cmd, data, td, /*nr_body_is_user=*/1);
1500 out:
1501 	CURVNET_RESTORE();
1502 
1503 	return error;
1504 }
1505 
1506 void
nm_os_onattach(struct ifnet * ifp)1507 nm_os_onattach(struct ifnet *ifp)
1508 {
1509 	ifp->if_capabilities |= IFCAP_NETMAP;
1510 }
1511 
1512 void
nm_os_onenter(struct ifnet * ifp)1513 nm_os_onenter(struct ifnet *ifp)
1514 {
1515 	struct netmap_adapter *na = NA(ifp);
1516 
1517 	na->if_transmit = ifp->if_transmit;
1518 	ifp->if_transmit = netmap_transmit;
1519 	ifp->if_capenable |= IFCAP_NETMAP;
1520 }
1521 
1522 void
nm_os_onexit(struct ifnet * ifp)1523 nm_os_onexit(struct ifnet *ifp)
1524 {
1525 	struct netmap_adapter *na = NA(ifp);
1526 
1527 	ifp->if_transmit = na->if_transmit;
1528 	ifp->if_capenable &= ~IFCAP_NETMAP;
1529 }
1530 
1531 extern struct cdevsw netmap_cdevsw; /* XXX used in netmap.c, should go elsewhere */
1532 struct cdevsw netmap_cdevsw = {
1533 	.d_version = D_VERSION,
1534 	.d_name = "netmap",
1535 	.d_open = netmap_open,
1536 	.d_mmap_single = netmap_mmap_single,
1537 	.d_ioctl = freebsd_netmap_ioctl,
1538 	.d_poll = freebsd_netmap_poll,
1539 	.d_kqfilter = netmap_kqfilter,
1540 	.d_close = netmap_close,
1541 };
1542 /*--- end of kqueue support ----*/
1543 
1544 /*
1545  * Kernel entry point.
1546  *
1547  * Initialize/finalize the module and return.
1548  *
1549  * Return 0 on success, errno on failure.
1550  */
1551 static int
netmap_loader(__unused struct module * module,int event,__unused void * arg)1552 netmap_loader(__unused struct module *module, int event, __unused void *arg)
1553 {
1554 	int error = 0;
1555 
1556 	switch (event) {
1557 	case MOD_LOAD:
1558 		error = netmap_init();
1559 		break;
1560 
1561 	case MOD_UNLOAD:
1562 		/*
1563 		 * if some one is still using netmap,
1564 		 * then the module can not be unloaded.
1565 		 */
1566 		if (netmap_use_count) {
1567 			nm_prerr("netmap module can not be unloaded - netmap_use_count: %d",
1568 					netmap_use_count);
1569 			error = EBUSY;
1570 			break;
1571 		}
1572 		netmap_fini();
1573 		break;
1574 
1575 	default:
1576 		error = EOPNOTSUPP;
1577 		break;
1578 	}
1579 
1580 	return (error);
1581 }
1582 
1583 #ifdef DEV_MODULE_ORDERED
1584 /*
1585  * The netmap module contains three drivers: (i) the netmap character device
1586  * driver; (ii) the ptnetmap memdev PCI device driver, (iii) the ptnet PCI
1587  * device driver. The attach() routines of both (ii) and (iii) need the
1588  * lock of the global allocator, and such lock is initialized in netmap_init(),
1589  * which is part of (i).
1590  * Therefore, we make sure that (i) is loaded before (ii) and (iii), using
1591  * the 'order' parameter of driver declaration macros. For (i), we specify
1592  * SI_ORDER_MIDDLE, while higher orders are used with the DRIVER_MODULE_ORDERED
1593  * macros for (ii) and (iii).
1594  */
1595 DEV_MODULE_ORDERED(netmap, netmap_loader, NULL, SI_ORDER_MIDDLE);
1596 #else /* !DEV_MODULE_ORDERED */
1597 DEV_MODULE(netmap, netmap_loader, NULL);
1598 #endif /* DEV_MODULE_ORDERED  */
1599 MODULE_DEPEND(netmap, pci, 1, 1, 1);
1600 MODULE_VERSION(netmap, 1);
1601 /* reduce conditional code */
1602 // linux API, use for the knlist in FreeBSD
1603 /* use a private mutex for the knlist */
1604