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