]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/netmap/netmap_freebsd.c
move netmap_getna() to a freebsd-specific file
[FreeBSD/FreeBSD.git] / sys / dev / netmap / netmap_freebsd.c
1 /*
2  * Copyright (C) 2013-2014 Universita` di Pisa. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *   1. Redistributions of source code must retain the above copyright
8  *      notice, this list of conditions and the following disclaimer.
9  *   2. Redistributions in binary form must reproduce the above copyright
10  *      notice, this list of conditions and the following disclaimer in the
11  *      documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
14  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
17  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23  * SUCH DAMAGE.
24  */
25
26 /* $FreeBSD$ */
27
28 #include <sys/types.h>
29 #include <sys/module.h>
30 #include <sys/errno.h>
31 #include <sys/param.h>  /* defines used in kernel.h */
32 #include <sys/poll.h>  /* POLLIN, POLLOUT */
33 #include <sys/kernel.h> /* types used in module initialization */
34 #include <sys/conf.h>   /* DEV_MODULE */
35 #include <sys/endian.h>
36
37 #include <sys/rwlock.h>
38
39 #include <vm/vm.h>      /* vtophys */
40 #include <vm/pmap.h>    /* vtophys */
41 #include <vm/vm_param.h>
42 #include <vm/vm_object.h>
43 #include <vm/vm_page.h>
44 #include <vm/vm_pager.h>
45 #include <vm/uma.h>
46
47
48 #include <sys/malloc.h>
49 #include <sys/socket.h> /* sockaddrs */
50 #include <sys/selinfo.h>
51 #include <net/if.h>
52 #include <net/if_var.h>
53 #include <machine/bus.h>        /* bus_dmamap_* */
54 #include <netinet/in.h>         /* in6_cksum_pseudo() */
55 #include <machine/in_cksum.h>  /* in_pseudo(), in_cksum_hdr() */
56
57 #include <net/netmap.h>
58 #include <dev/netmap/netmap_kern.h>
59 #include <dev/netmap/netmap_mem2.h>
60
61
62 /* ======================== FREEBSD-SPECIFIC ROUTINES ================== */
63
64 rawsum_t nm_csum_raw(uint8_t *data, size_t len, rawsum_t cur_sum)
65 {
66         /* TODO XXX please use the FreeBSD implementation for this. */
67         uint16_t *words = (uint16_t *)data;
68         int nw = len / 2;
69         int i;
70
71         for (i = 0; i < nw; i++)
72                 cur_sum += be16toh(words[i]);
73
74         if (len & 1)
75                 cur_sum += (data[len-1] << 8);
76
77         return cur_sum;
78 }
79
80 /* Fold a raw checksum: 'cur_sum' is in host byte order, while the
81  * return value is in network byte order.
82  */
83 uint16_t nm_csum_fold(rawsum_t cur_sum)
84 {
85         /* TODO XXX please use the FreeBSD implementation for this. */
86         while (cur_sum >> 16)
87                 cur_sum = (cur_sum & 0xFFFF) + (cur_sum >> 16);
88
89         return htobe16((~cur_sum) & 0xFFFF);
90 }
91
92 uint16_t nm_csum_ipv4(struct nm_iphdr *iph)
93 {
94 #if 0
95         return in_cksum_hdr((void *)iph);
96 #else
97         return nm_csum_fold(nm_csum_raw((uint8_t*)iph, sizeof(struct nm_iphdr), 0));
98 #endif
99 }
100
101 void nm_csum_tcpudp_ipv4(struct nm_iphdr *iph, void *data,
102                                         size_t datalen, uint16_t *check)
103 {
104 #ifdef INET
105         uint16_t pseudolen = datalen + iph->protocol;
106
107         /* Compute and insert the pseudo-header cheksum. */
108         *check = in_pseudo(iph->saddr, iph->daddr,
109                                  htobe16(pseudolen));
110         /* Compute the checksum on TCP/UDP header + payload
111          * (includes the pseudo-header).
112          */
113         *check = nm_csum_fold(nm_csum_raw(data, datalen, 0));
114 #else
115         static int notsupported = 0;
116         if (!notsupported) {
117                 notsupported = 1;
118                 D("inet4 segmentation not supported");
119         }
120 #endif
121 }
122
123 void nm_csum_tcpudp_ipv6(struct nm_ipv6hdr *ip6h, void *data,
124                                         size_t datalen, uint16_t *check)
125 {
126 #ifdef INET6
127         *check = in6_cksum_pseudo((void*)ip6h, datalen, ip6h->nexthdr, 0);
128         *check = nm_csum_fold(nm_csum_raw(data, datalen, 0));
129 #else
130         static int notsupported = 0;
131         if (!notsupported) {
132                 notsupported = 1;
133                 D("inet6 segmentation not supported");
134         }
135 #endif
136 }
137
138
139 /*
140  * Intercept the rx routine in the standard device driver.
141  * Second argument is non-zero to intercept, 0 to restore
142  */
143 int
144 netmap_catch_rx(struct netmap_adapter *na, int intercept)
145 {
146         struct netmap_generic_adapter *gna = (struct netmap_generic_adapter *)na;
147         struct ifnet *ifp = na->ifp;
148
149         if (intercept) {
150                 if (gna->save_if_input) {
151                         D("cannot intercept again");
152                         return EINVAL; /* already set */
153                 }
154                 gna->save_if_input = ifp->if_input;
155                 ifp->if_input = generic_rx_handler;
156         } else {
157                 if (!gna->save_if_input){
158                         D("cannot restore");
159                         return EINVAL;  /* not saved */
160                 }
161                 ifp->if_input = gna->save_if_input;
162                 gna->save_if_input = NULL;
163         }
164
165         return 0;
166 }
167
168
169 /*
170  * Intercept the packet steering routine in the tx path,
171  * so that we can decide which queue is used for an mbuf.
172  * Second argument is non-zero to intercept, 0 to restore.
173  * On freebsd we just intercept if_transmit.
174  */
175 void
176 netmap_catch_tx(struct netmap_generic_adapter *gna, int enable)
177 {
178         struct netmap_adapter *na = &gna->up.up;
179         struct ifnet *ifp = na->ifp;
180
181         if (enable) {
182                 na->if_transmit = ifp->if_transmit;
183                 ifp->if_transmit = netmap_transmit;
184         } else {
185                 ifp->if_transmit = na->if_transmit;
186         }
187 }
188
189
190 /*
191  * Transmit routine used by generic_netmap_txsync(). Returns 0 on success
192  * and non-zero on error (which may be packet drops or other errors).
193  * addr and len identify the netmap buffer, m is the (preallocated)
194  * mbuf to use for transmissions.
195  *
196  * We should add a reference to the mbuf so the m_freem() at the end
197  * of the transmission does not consume resources.
198  *
199  * On FreeBSD, and on multiqueue cards, we can force the queue using
200  *      if ((m->m_flags & M_FLOWID) != 0)
201  *              i = m->m_pkthdr.flowid % adapter->num_queues;
202  *      else
203  *              i = curcpu % adapter->num_queues;
204  *
205  */
206 int
207 generic_xmit_frame(struct ifnet *ifp, struct mbuf *m,
208         void *addr, u_int len, u_int ring_nr)
209 {
210         int ret;
211
212         m->m_len = m->m_pkthdr.len = 0;
213
214         // copy data to the mbuf
215         m_copyback(m, 0, len, addr);
216         // inc refcount. We are alone, so we can skip the atomic
217         atomic_fetchadd_int(m->m_ext.ref_cnt, 1);
218         m->m_flags |= M_FLOWID;
219         m->m_pkthdr.flowid = ring_nr;
220         m->m_pkthdr.rcvif = ifp; /* used for tx notification */
221         ret = NA(ifp)->if_transmit(ifp, m);
222         return ret;
223 }
224
225
226 #if __FreeBSD_version >= 1100005
227 struct netmap_adapter *
228 netmap_getna(if_t ifp)
229 {
230         return (NA((struct ifnet *)ifp));
231 }
232 #endif /* __FreeBSD_version >= 1100005 */
233
234 /*
235  * The following two functions are empty until we have a generic
236  * way to extract the info from the ifp
237  */
238 int
239 generic_find_num_desc(struct ifnet *ifp, unsigned int *tx, unsigned int *rx)
240 {
241         D("called");
242         return 0;
243 }
244
245
246 void
247 generic_find_num_queues(struct ifnet *ifp, u_int *txq, u_int *rxq)
248 {
249         D("called");
250         *txq = netmap_generic_rings;
251         *rxq = netmap_generic_rings;
252 }
253
254
255 void netmap_mitigation_init(struct nm_generic_mit *mit, struct netmap_adapter *na)
256 {
257         ND("called");
258         mit->mit_pending = 0;
259         mit->mit_na = na;
260 }
261
262
263 void netmap_mitigation_start(struct nm_generic_mit *mit)
264 {
265         ND("called");
266 }
267
268
269 void netmap_mitigation_restart(struct nm_generic_mit *mit)
270 {
271         ND("called");
272 }
273
274
275 int netmap_mitigation_active(struct nm_generic_mit *mit)
276 {
277         ND("called");
278         return 0;
279 }
280
281
282 void netmap_mitigation_cleanup(struct nm_generic_mit *mit)
283 {
284         ND("called");
285 }
286
287
288 /*
289  * In order to track whether pages are still mapped, we hook into
290  * the standard cdev_pager and intercept the constructor and
291  * destructor.
292  */
293
294 struct netmap_vm_handle_t {
295         struct cdev             *dev;
296         struct netmap_priv_d    *priv;
297 };
298
299
300 static int
301 netmap_dev_pager_ctor(void *handle, vm_ooffset_t size, vm_prot_t prot,
302     vm_ooffset_t foff, struct ucred *cred, u_short *color)
303 {
304         struct netmap_vm_handle_t *vmh = handle;
305
306         if (netmap_verbose)
307                 D("handle %p size %jd prot %d foff %jd",
308                         handle, (intmax_t)size, prot, (intmax_t)foff);
309         dev_ref(vmh->dev);
310         return 0;
311 }
312
313
314 static void
315 netmap_dev_pager_dtor(void *handle)
316 {
317         struct netmap_vm_handle_t *vmh = handle;
318         struct cdev *dev = vmh->dev;
319         struct netmap_priv_d *priv = vmh->priv;
320
321         if (netmap_verbose)
322                 D("handle %p", handle);
323         netmap_dtor(priv);
324         free(vmh, M_DEVBUF);
325         dev_rel(dev);
326 }
327
328
329 static int
330 netmap_dev_pager_fault(vm_object_t object, vm_ooffset_t offset,
331         int prot, vm_page_t *mres)
332 {
333         struct netmap_vm_handle_t *vmh = object->handle;
334         struct netmap_priv_d *priv = vmh->priv;
335         vm_paddr_t paddr;
336         vm_page_t page;
337         vm_memattr_t memattr;
338         vm_pindex_t pidx;
339
340         ND("object %p offset %jd prot %d mres %p",
341                         object, (intmax_t)offset, prot, mres);
342         memattr = object->memattr;
343         pidx = OFF_TO_IDX(offset);
344         paddr = netmap_mem_ofstophys(priv->np_mref, offset);
345         if (paddr == 0)
346                 return VM_PAGER_FAIL;
347
348         if (((*mres)->flags & PG_FICTITIOUS) != 0) {
349                 /*
350                  * If the passed in result page is a fake page, update it with
351                  * the new physical address.
352                  */
353                 page = *mres;
354                 vm_page_updatefake(page, paddr, memattr);
355         } else {
356                 /*
357                  * Replace the passed in reqpage page with our own fake page and
358                  * free up the all of the original pages.
359                  */
360 #ifndef VM_OBJECT_WUNLOCK       /* FreeBSD < 10.x */
361 #define VM_OBJECT_WUNLOCK VM_OBJECT_UNLOCK
362 #define VM_OBJECT_WLOCK VM_OBJECT_LOCK
363 #endif /* VM_OBJECT_WUNLOCK */
364
365                 VM_OBJECT_WUNLOCK(object);
366                 page = vm_page_getfake(paddr, memattr);
367                 VM_OBJECT_WLOCK(object);
368                 vm_page_lock(*mres);
369                 vm_page_free(*mres);
370                 vm_page_unlock(*mres);
371                 *mres = page;
372                 vm_page_insert(page, object, pidx);
373         }
374         page->valid = VM_PAGE_BITS_ALL;
375         return (VM_PAGER_OK);
376 }
377
378
379 static struct cdev_pager_ops netmap_cdev_pager_ops = {
380         .cdev_pg_ctor = netmap_dev_pager_ctor,
381         .cdev_pg_dtor = netmap_dev_pager_dtor,
382         .cdev_pg_fault = netmap_dev_pager_fault,
383 };
384
385
386 static int
387 netmap_mmap_single(struct cdev *cdev, vm_ooffset_t *foff,
388         vm_size_t objsize,  vm_object_t *objp, int prot)
389 {
390         int error;
391         struct netmap_vm_handle_t *vmh;
392         struct netmap_priv_d *priv;
393         vm_object_t obj;
394
395         if (netmap_verbose)
396                 D("cdev %p foff %jd size %jd objp %p prot %d", cdev,
397                     (intmax_t )*foff, (intmax_t )objsize, objp, prot);
398
399         vmh = malloc(sizeof(struct netmap_vm_handle_t), M_DEVBUF,
400                               M_NOWAIT | M_ZERO);
401         if (vmh == NULL)
402                 return ENOMEM;
403         vmh->dev = cdev;
404
405         NMG_LOCK();
406         error = devfs_get_cdevpriv((void**)&priv);
407         if (error)
408                 goto err_unlock;
409         vmh->priv = priv;
410         priv->np_refcount++;
411         NMG_UNLOCK();
412
413         error = netmap_get_memory(priv);
414         if (error)
415                 goto err_deref;
416
417         obj = cdev_pager_allocate(vmh, OBJT_DEVICE,
418                 &netmap_cdev_pager_ops, objsize, prot,
419                 *foff, NULL);
420         if (obj == NULL) {
421                 D("cdev_pager_allocate failed");
422                 error = EINVAL;
423                 goto err_deref;
424         }
425
426         *objp = obj;
427         return 0;
428
429 err_deref:
430         NMG_LOCK();
431         priv->np_refcount--;
432 err_unlock:
433         NMG_UNLOCK();
434 // err:
435         free(vmh, M_DEVBUF);
436         return error;
437 }
438
439
440 // XXX can we remove this ?
441 static int
442 netmap_close(struct cdev *dev, int fflag, int devtype, struct thread *td)
443 {
444         if (netmap_verbose)
445                 D("dev %p fflag 0x%x devtype %d td %p",
446                         dev, fflag, devtype, td);
447         return 0;
448 }
449
450
451 static int
452 netmap_open(struct cdev *dev, int oflags, int devtype, struct thread *td)
453 {
454         struct netmap_priv_d *priv;
455         int error;
456
457         (void)dev;
458         (void)oflags;
459         (void)devtype;
460         (void)td;
461
462         // XXX wait or nowait ?
463         priv = malloc(sizeof(struct netmap_priv_d), M_DEVBUF,
464                               M_NOWAIT | M_ZERO);
465         if (priv == NULL)
466                 return ENOMEM;
467
468         error = devfs_set_cdevpriv(priv, netmap_dtor);
469         if (error)
470                 return error;
471
472         priv->np_refcount = 1;
473
474         return 0;
475 }
476
477 /******************** kqueue support ****************/
478
479 /*
480  * The OS_selwakeup also needs to issue a KNOTE_UNLOCKED.
481  * We use a non-zero argument to distinguish the call from the one
482  * in kevent_scan() which instead also needs to run netmap_poll().
483  * The knote uses a global mutex for the time being. We might
484  * try to reuse the one in the si, but it is not allocated
485  * permanently so it might be a bit tricky.
486  *
487  * The *kqfilter function registers one or another f_event
488  * depending on read or write mode.
489  * In the call to f_event() td_fpop is NULL so any child function
490  * calling devfs_get_cdevpriv() would fail - and we need it in
491  * netmap_poll(). As a workaround we store priv into kn->kn_hook
492  * and pass it as first argument to netmap_poll(), which then
493  * uses the failure to tell that we are called from f_event()
494  * and do not need the selrecord().
495  */
496
497 void freebsd_selwakeup(struct selinfo *si, int pri);
498
499 void
500 freebsd_selwakeup(struct selinfo *si, int pri)
501 {
502         if (netmap_verbose)
503                 D("on knote %p", &si->si_note);
504         selwakeuppri(si, pri);
505         /* use a non-zero hint to tell the notification from the
506          * call done in kqueue_scan() which uses 0
507          */
508         KNOTE_UNLOCKED(&si->si_note, 0x100 /* notification */);
509 }
510
511 static void
512 netmap_knrdetach(struct knote *kn)
513 {
514         struct netmap_priv_d *priv = (struct netmap_priv_d *)kn->kn_hook;
515         struct selinfo *si = priv->np_rxsi;
516
517         D("remove selinfo %p", si);
518         knlist_remove(&si->si_note, kn, 0);
519 }
520
521 static void
522 netmap_knwdetach(struct knote *kn)
523 {
524         struct netmap_priv_d *priv = (struct netmap_priv_d *)kn->kn_hook;
525         struct selinfo *si = priv->np_txsi;
526
527         D("remove selinfo %p", si);
528         knlist_remove(&si->si_note, kn, 0);
529 }
530
531 /*
532  * callback from notifies (generated externally) and our
533  * calls to kevent(). The former we just return 1 (ready)
534  * since we do not know better.
535  * In the latter we call netmap_poll and return 0/1 accordingly.
536  */
537 static int
538 netmap_knrw(struct knote *kn, long hint, int events)
539 {
540         struct netmap_priv_d *priv;
541         int revents;
542
543         if (hint != 0) {
544                 ND(5, "call from notify");
545                 return 1; /* assume we are ready */
546         }
547         priv = kn->kn_hook;
548         /* the notification may come from an external thread,
549          * in which case we do not want to run the netmap_poll
550          * This should be filtered above, but check just in case.
551          */
552         if (curthread != priv->np_td) { /* should not happen */
553                 RD(5, "curthread changed %p %p", curthread, priv->np_td);
554                 return 1;
555         } else {
556                 revents = netmap_poll((void *)priv, events, curthread);
557                 return (events & revents) ? 1 : 0;
558         }
559 }
560
561 static int
562 netmap_knread(struct knote *kn, long hint)
563 {
564         return netmap_knrw(kn, hint, POLLIN);
565 }
566
567 static int
568 netmap_knwrite(struct knote *kn, long hint)
569 {
570         return netmap_knrw(kn, hint, POLLOUT);
571 }
572
573 static struct filterops netmap_rfiltops = {
574         .f_isfd = 1,
575         .f_detach = netmap_knrdetach,
576         .f_event = netmap_knread,
577 };
578
579 static struct filterops netmap_wfiltops = {
580         .f_isfd = 1,
581         .f_detach = netmap_knwdetach,
582         .f_event = netmap_knwrite,
583 };
584
585
586 /*
587  * This is called when a thread invokes kevent() to record
588  * a change in the configuration of the kqueue().
589  * The 'priv' should be the same as in the netmap device.
590  */
591 static int
592 netmap_kqfilter(struct cdev *dev, struct knote *kn)
593 {
594         struct netmap_priv_d *priv;
595         int error;
596         struct netmap_adapter *na;
597         struct selinfo *si;
598         int ev = kn->kn_filter;
599
600         if (ev != EVFILT_READ && ev != EVFILT_WRITE) {
601                 D("bad filter request %d", ev);
602                 return 1;
603         }
604         error = devfs_get_cdevpriv((void**)&priv);
605         if (error) {
606                 D("device not yet setup");
607                 return 1;
608         }
609         na = priv->np_na;
610         if (na == NULL) {
611                 D("no netmap adapter for this file descriptor");
612                 return 1;
613         }
614         /* the si is indicated in the priv */
615         si = (ev == EVFILT_WRITE) ? priv->np_txsi : priv->np_rxsi;
616         // XXX lock(priv) ?
617         kn->kn_fop = (ev == EVFILT_WRITE) ?
618                 &netmap_wfiltops : &netmap_rfiltops;
619         kn->kn_hook = priv;
620         knlist_add(&si->si_note, kn, 1);
621         // XXX unlock(priv)
622         ND("register %p %s td %p priv %p kn %p np_nifp %p kn_fp/fpop %s",
623                 na, na->ifp->if_xname, curthread, priv, kn,
624                 priv->np_nifp,
625                 kn->kn_fp == curthread->td_fpop ? "match" : "MISMATCH");
626         return 0;
627 }
628
629 struct cdevsw netmap_cdevsw = {
630         .d_version = D_VERSION,
631         .d_name = "netmap",
632         .d_open = netmap_open,
633         .d_mmap_single = netmap_mmap_single,
634         .d_ioctl = netmap_ioctl,
635         .d_poll = netmap_poll,
636         .d_kqfilter = netmap_kqfilter,
637         .d_close = netmap_close,
638 };
639 /*--- end of kqueue support ----*/
640
641 /*
642  * Kernel entry point.
643  *
644  * Initialize/finalize the module and return.
645  *
646  * Return 0 on success, errno on failure.
647  */
648 static int
649 netmap_loader(__unused struct module *module, int event, __unused void *arg)
650 {
651         int error = 0;
652
653         switch (event) {
654         case MOD_LOAD:
655                 error = netmap_init();
656                 break;
657
658         case MOD_UNLOAD:
659                 netmap_fini();
660                 break;
661
662         default:
663                 error = EOPNOTSUPP;
664                 break;
665         }
666
667         return (error);
668 }
669
670
671 DEV_MODULE(netmap, netmap_loader, NULL);