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