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