Merge from vendor branch CVS:
[dragonfly.git] / sys / net / bpf.c
1 /*
2  * Copyright (c) 1990, 1991, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from the Stanford/CMU enet packet filter,
6  * (net/enet.c) distributed as part of 4.3BSD, and code contributed
7  * to Berkeley by Steven McCanne and Van Jacobson both of Lawrence
8  * Berkeley Laboratory.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *      This product includes software developed by the University of
21  *      California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *      @(#)bpf.c       8.2 (Berkeley) 3/28/94
39  *
40  * $FreeBSD: src/sys/net/bpf.c,v 1.59.2.12 2002/04/14 21:41:48 luigi Exp $
41  * $DragonFly: src/sys/net/bpf.c,v 1.27 2005/06/03 18:19:51 swildner Exp $
42  */
43
44 #include "use_bpf.h"
45
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/conf.h>
49 #include <sys/malloc.h>
50 #include <sys/mbuf.h>
51 #include <sys/time.h>
52 #include <sys/proc.h>
53 #include <sys/signalvar.h>
54 #include <sys/filio.h>
55 #include <sys/sockio.h>
56 #include <sys/ttycom.h>
57 #include <sys/filedesc.h>
58
59 #include <sys/poll.h>
60
61 #include <sys/socket.h>
62 #include <sys/vnode.h>
63
64 #include <sys/thread2.h>
65
66 #include <net/if.h>
67 #include <net/bpf.h>
68 #include <net/bpfdesc.h>
69
70 #include <netinet/in.h>
71 #include <netinet/if_ether.h>
72 #include <sys/kernel.h>
73 #include <sys/sysctl.h>
74
75 MALLOC_DEFINE(M_BPF, "BPF", "BPF data");
76
77 #if NBPF > 0
78
79 /*
80  * The default read buffer size is patchable.
81  */
82 static int bpf_bufsize = BPF_DEFAULTBUFSIZE;
83 SYSCTL_INT(_debug, OID_AUTO, bpf_bufsize, CTLFLAG_RW,
84            &bpf_bufsize, 0, "");
85 static int bpf_maxbufsize = BPF_MAXBUFSIZE;
86 SYSCTL_INT(_debug, OID_AUTO, bpf_maxbufsize, CTLFLAG_RW,
87            &bpf_maxbufsize, 0, "");
88
89 /*
90  *  bpf_iflist is the list of interfaces; each corresponds to an ifnet
91  */
92 static struct bpf_if    *bpf_iflist;
93
94 static int      bpf_allocbufs(struct bpf_d *);
95 static void     bpf_attachd(struct bpf_d *d, struct bpf_if *bp);
96 static void     bpf_detachd(struct bpf_d *d);
97 static void     bpf_freed(struct bpf_d *);
98 static void     bpf_mcopy(const void *, void *, size_t);
99 static int      bpf_movein(struct uio *, int, struct mbuf **,
100                            struct sockaddr *, int *);
101 static int      bpf_setif(struct bpf_d *, struct ifreq *);
102 static void     bpf_timed_out(void *);
103 static void     bpf_wakeup(struct bpf_d *);
104 static void     catchpacket(struct bpf_d *, u_char *, u_int, u_int,
105                             void (*)(const void *, void *, size_t));
106 static void     reset_d(struct bpf_d *);
107 static int      bpf_setf(struct bpf_d *, struct bpf_program *);
108 static int      bpf_getdltlist(struct bpf_d *, struct bpf_dltlist *);
109 static int      bpf_setdlt(struct bpf_d *, u_int);
110 static void     bpf_drvinit(void *unused);
111
112 static d_open_t         bpfopen;
113 static d_close_t        bpfclose;
114 static d_read_t         bpfread;
115 static d_write_t        bpfwrite;
116 static d_ioctl_t        bpfioctl;
117 static d_poll_t         bpfpoll;
118
119 #define CDEV_MAJOR 23
120 static struct cdevsw bpf_cdevsw = {
121         /* name */      "bpf",
122         /* maj */       CDEV_MAJOR,
123         /* flags */     0,
124         /* port */      NULL,
125         /* clone */     NULL,
126
127         /* open */      bpfopen,
128         /* close */     bpfclose,
129         /* read */      bpfread,
130         /* write */     bpfwrite,
131         /* ioctl */     bpfioctl,
132         /* poll */      bpfpoll,
133         /* mmap */      nommap,
134         /* strategy */  nostrategy,
135         /* dump */      nodump,
136         /* psize */     nopsize
137 };
138
139
140 static int
141 bpf_movein(struct uio *uio, int linktype, struct mbuf **mp,
142            struct sockaddr *sockp, int *datlen)
143 {
144         struct mbuf *m;
145         int error;
146         int len;
147         int hlen;
148
149         /*
150          * Build a sockaddr based on the data link layer type.
151          * We do this at this level because the ethernet header
152          * is copied directly into the data field of the sockaddr.
153          * In the case of SLIP, there is no header and the packet
154          * is forwarded as is.
155          * Also, we are careful to leave room at the front of the mbuf
156          * for the link level header.
157          */
158         switch (linktype) {
159
160         case DLT_SLIP:
161                 sockp->sa_family = AF_INET;
162                 hlen = 0;
163                 break;
164
165         case DLT_EN10MB:
166                 sockp->sa_family = AF_UNSPEC;
167                 /* XXX Would MAXLINKHDR be better? */
168                 hlen = sizeof(struct ether_header);
169                 break;
170
171         case DLT_FDDI:
172                 sockp->sa_family = AF_IMPLINK;
173                 hlen = 0;
174                 break;
175
176         case DLT_RAW:
177         case DLT_NULL:
178                 sockp->sa_family = AF_UNSPEC;
179                 hlen = 0;
180                 break;
181
182         case DLT_ATM_RFC1483:
183                 /*
184                  * en atm driver requires 4-byte atm pseudo header.
185                  * though it isn't standard, vpi:vci needs to be
186                  * specified anyway.
187                  */
188                 sockp->sa_family = AF_UNSPEC;
189                 hlen = 12;      /* XXX 4(ATM_PH) + 3(LLC) + 5(SNAP) */
190                 break;
191
192         case DLT_PPP:
193                 sockp->sa_family = AF_UNSPEC;
194                 hlen = 4;       /* This should match PPP_HDRLEN */
195                 break;
196
197         default:
198                 return(EIO);
199         }
200
201         len = uio->uio_resid;
202         *datlen = len - hlen;
203         if ((unsigned)len > MCLBYTES)
204                 return(EIO);
205
206         MGETHDR(m, MB_WAIT, MT_DATA);
207         if (m == NULL)
208                 return(ENOBUFS);
209         if (len > MHLEN) {
210                 MCLGET(m, MB_WAIT);
211                 if (!(m->m_flags & M_EXT)) {
212                         error = ENOBUFS;
213                         goto bad;
214                 }
215         }
216         m->m_pkthdr.len = m->m_len = len;
217         m->m_pkthdr.rcvif = NULL;
218         *mp = m;
219         /*
220          * Make room for link header.
221          */
222         if (hlen != 0) {
223                 m->m_pkthdr.len -= hlen;
224                 m->m_len -= hlen;
225                 m->m_data += hlen; /* XXX */
226                 error = uiomove(sockp->sa_data, hlen, uio);
227                 if (error)
228                         goto bad;
229         }
230         error = uiomove(mtod(m, caddr_t), len - hlen, uio);
231         if (!error)
232                 return(0);
233 bad:
234         m_freem(m);
235         return(error);
236 }
237
238 /*
239  * Attach file to the bpf interface, i.e. make d listen on bp.
240  * Must be called at splimp.
241  */
242 static void
243 bpf_attachd(struct bpf_d *d, struct bpf_if *bp)
244 {
245         /*
246          * Point d at bp, and add d to the interface's list of listeners.
247          * Finally, point the driver's bpf cookie at the interface so
248          * it will divert packets to bpf.
249          */
250         d->bd_bif = bp;
251         SLIST_INSERT_HEAD(&bp->bif_dlist, d, bd_next);
252         *bp->bif_driverp = bp;
253 }
254
255 /*
256  * Detach a file from its interface.
257  */
258 static void
259 bpf_detachd(struct bpf_d *d)
260 {
261         int error;
262         struct bpf_if *bp;
263         struct ifnet *ifp;
264
265         bp = d->bd_bif;
266         ifp = bp->bif_ifp;
267
268         /* Remove d from the interface's descriptor list. */
269         SLIST_REMOVE(&bp->bif_dlist, d, bpf_d, bd_next);
270
271         if (SLIST_EMPTY(&bp->bif_dlist)) {
272                 /*
273                  * Let the driver know that there are no more listeners.
274                  */
275                 *bp->bif_driverp = NULL;
276         }
277         d->bd_bif = NULL;
278         /*
279          * Check if this descriptor had requested promiscuous mode.
280          * If so, turn it off.
281          */
282         if (d->bd_promisc) {
283                 d->bd_promisc = 0;
284                 error = ifpromisc(ifp, 0);
285                 if (error != 0 && error != ENXIO) {
286                         /*
287                          * ENXIO can happen if a pccard is unplugged,
288                          * Something is really wrong if we were able to put
289                          * the driver into promiscuous mode, but can't
290                          * take it out.
291                          */
292                         if_printf(ifp, "bpf_detach: ifpromisc failed(%d)\n",
293                                   error);
294                 }
295         }
296 }
297
298 /*
299  * Open ethernet device.  Returns ENXIO for illegal minor device number,
300  * EBUSY if file is open by another process.
301  */
302 /* ARGSUSED */
303 static int
304 bpfopen(dev_t dev, int flags, int fmt, struct thread *td)
305 {
306         struct bpf_d *d;
307         struct proc *p = td->td_proc;
308
309         KKASSERT(p != NULL);
310
311         if (p->p_ucred->cr_prison)
312                 return(EPERM);
313
314         d = dev->si_drv1;
315         /*
316          * Each minor can be opened by only one process.  If the requested
317          * minor is in use, return EBUSY.
318          */
319         if (d != NULL)
320                 return(EBUSY);
321         make_dev(&bpf_cdevsw, minor(dev), 0, 0, 0600, "bpf%d", lminor(dev));
322         MALLOC(d, struct bpf_d *, sizeof *d, M_BPF, M_WAITOK | M_ZERO);
323         dev->si_drv1 = d;
324         d->bd_bufsize = bpf_bufsize;
325         d->bd_sig = SIGIO;
326         d->bd_seesent = 1;
327         callout_init(&d->bd_callout);
328         return(0);
329 }
330
331 /*
332  * Close the descriptor by detaching it from its interface,
333  * deallocating its buffers, and marking it free.
334  */
335 /* ARGSUSED */
336 static int
337 bpfclose(dev_t dev, int flags, int fmt, struct thread *td)
338 {
339         struct bpf_d *d = dev->si_drv1;
340
341         funsetown(d->bd_sigio);
342         crit_enter();
343         if (d->bd_state == BPF_WAITING)
344                 callout_stop(&d->bd_callout);
345         d->bd_state = BPF_IDLE;
346         if (d->bd_bif != NULL)
347                 bpf_detachd(d);
348         crit_exit();
349         bpf_freed(d);
350         dev->si_drv1 = NULL;
351         free(d, M_BPF);
352
353         return(0);
354 }
355
356 /*
357  * Rotate the packet buffers in descriptor d.  Move the store buffer
358  * into the hold slot, and the free buffer into the store slot.
359  * Zero the length of the new store buffer.
360  */
361 #define ROTATE_BUFFERS(d) \
362         (d)->bd_hbuf = (d)->bd_sbuf; \
363         (d)->bd_hlen = (d)->bd_slen; \
364         (d)->bd_sbuf = (d)->bd_fbuf; \
365         (d)->bd_slen = 0; \
366         (d)->bd_fbuf = NULL;
367 /*
368  *  bpfread - read next chunk of packets from buffers
369  */
370 static int
371 bpfread(dev_t dev, struct uio *uio, int ioflag)
372 {
373         struct bpf_d *d = dev->si_drv1;
374         int timed_out;
375         int error;
376
377         /*
378          * Restrict application to use a buffer the same size as
379          * as kernel buffers.
380          */
381         if (uio->uio_resid != d->bd_bufsize)
382                 return(EINVAL);
383
384         crit_enter();
385         if (d->bd_state == BPF_WAITING)
386                 callout_stop(&d->bd_callout);
387         timed_out = (d->bd_state == BPF_TIMED_OUT);
388         d->bd_state = BPF_IDLE;
389         /*
390          * If the hold buffer is empty, then do a timed sleep, which
391          * ends when the timeout expires or when enough packets
392          * have arrived to fill the store buffer.
393          */
394         while (d->bd_hbuf == NULL) {
395                 if ((d->bd_immediate || timed_out) && d->bd_slen != 0) {
396                         /*
397                          * A packet(s) either arrived since the previous
398                          * read or arrived while we were asleep.
399                          * Rotate the buffers and return what's here.
400                          */
401                         ROTATE_BUFFERS(d);
402                         break;
403                 }
404
405                 /*
406                  * No data is available, check to see if the bpf device
407                  * is still pointed at a real interface.  If not, return
408                  * ENXIO so that the userland process knows to rebind
409                  * it before using it again.
410                  */
411                 if (d->bd_bif == NULL) {
412                         crit_exit();
413                         return(ENXIO);
414                 }
415
416                 if (ioflag & IO_NDELAY) {
417                         crit_exit();
418                         return(EWOULDBLOCK);
419                 }
420                 error = tsleep(d, PCATCH, "bpf", d->bd_rtout);
421                 if (error == EINTR || error == ERESTART) {
422                         crit_exit();
423                         return(error);
424                 }
425                 if (error == EWOULDBLOCK) {
426                         /*
427                          * On a timeout, return what's in the buffer,
428                          * which may be nothing.  If there is something
429                          * in the store buffer, we can rotate the buffers.
430                          */
431                         if (d->bd_hbuf)
432                                 /*
433                                  * We filled up the buffer in between
434                                  * getting the timeout and arriving
435                                  * here, so we don't need to rotate.
436                                  */
437                                 break;
438
439                         if (d->bd_slen == 0) {
440                                 crit_exit();
441                                 return(0);
442                         }
443                         ROTATE_BUFFERS(d);
444                         break;
445                 }
446         }
447         /*
448          * At this point, we know we have something in the hold slot.
449          */
450         crit_exit();
451
452         /*
453          * Move data from hold buffer into user space.
454          * We know the entire buffer is transferred since
455          * we checked above that the read buffer is bpf_bufsize bytes.
456          */
457         error = uiomove(d->bd_hbuf, d->bd_hlen, uio);
458
459         crit_enter();
460         d->bd_fbuf = d->bd_hbuf;
461         d->bd_hbuf = NULL;
462         d->bd_hlen = 0;
463         crit_exit();
464
465         return(error);
466 }
467
468
469 /*
470  * If there are processes sleeping on this descriptor, wake them up.
471  */
472 static void
473 bpf_wakeup(struct bpf_d *d)
474 {
475         if (d->bd_state == BPF_WAITING) {
476                 callout_stop(&d->bd_callout);
477                 d->bd_state = BPF_IDLE;
478         }
479         wakeup(d);
480         if (d->bd_async && d->bd_sig && d->bd_sigio)
481                 pgsigio(d->bd_sigio, d->bd_sig, 0);
482
483         selwakeup(&d->bd_sel);
484         /* XXX */
485         d->bd_sel.si_pid = 0;
486 }
487
488 static void
489 bpf_timed_out(void *arg)
490 {
491         struct bpf_d *d = (struct bpf_d *)arg;
492
493         crit_enter();
494         if (d->bd_state == BPF_WAITING) {
495                 d->bd_state = BPF_TIMED_OUT;
496                 if (d->bd_slen != 0)
497                         bpf_wakeup(d);
498         }
499         crit_exit();
500 }
501
502 static  int
503 bpfwrite(dev_t dev, struct uio *uio, int ioflag)
504 {
505         struct bpf_d *d = dev->si_drv1;
506         struct ifnet *ifp;
507         struct mbuf *m;
508         int error;
509         static struct sockaddr dst;
510         int datlen;
511
512         if (d->bd_bif == NULL)
513                 return(ENXIO);
514
515         ifp = d->bd_bif->bif_ifp;
516
517         if (uio->uio_resid == 0)
518                 return(0);
519
520         error = bpf_movein(uio, (int)d->bd_bif->bif_dlt, &m, &dst, &datlen);
521         if (error)
522                 return(error);
523
524         if (datlen > ifp->if_mtu)
525                 return(EMSGSIZE);
526
527         if (d->bd_hdrcmplt)
528                 dst.sa_family = pseudo_AF_HDRCMPLT;
529
530         crit_enter();
531         error = (*ifp->if_output)(ifp, m, &dst, (struct rtentry *)NULL);
532         crit_exit();
533         /*
534          * The driver frees the mbuf.
535          */
536         return(error);
537 }
538
539 /*
540  * Reset a descriptor by flushing its packet buffer and clearing the
541  * receive and drop counts.  Should be called at splimp.
542  */
543 static void
544 reset_d(struct bpf_d *d)
545 {
546         if (d->bd_hbuf) {
547                 /* Free the hold buffer. */
548                 d->bd_fbuf = d->bd_hbuf;
549                 d->bd_hbuf = NULL;
550         }
551         d->bd_slen = 0;
552         d->bd_hlen = 0;
553         d->bd_rcount = 0;
554         d->bd_dcount = 0;
555 }
556
557 /*
558  *  FIONREAD            Check for read packet available.
559  *  SIOCGIFADDR         Get interface address - convenient hook to driver.
560  *  BIOCGBLEN           Get buffer len [for read()].
561  *  BIOCSETF            Set ethernet read filter.
562  *  BIOCFLUSH           Flush read packet buffer.
563  *  BIOCPROMISC         Put interface into promiscuous mode.
564  *  BIOCGDLT            Get link layer type.
565  *  BIOCGETIF           Get interface name.
566  *  BIOCSETIF           Set interface.
567  *  BIOCSRTIMEOUT       Set read timeout.
568  *  BIOCGRTIMEOUT       Get read timeout.
569  *  BIOCGSTATS          Get packet stats.
570  *  BIOCIMMEDIATE       Set immediate mode.
571  *  BIOCVERSION         Get filter language version.
572  *  BIOCGHDRCMPLT       Get "header already complete" flag
573  *  BIOCSHDRCMPLT       Set "header already complete" flag
574  *  BIOCGSEESENT        Get "see packets sent" flag
575  *  BIOCSSEESENT        Set "see packets sent" flag
576  */
577 /* ARGSUSED */
578 static int
579 bpfioctl(dev_t dev, u_long cmd, caddr_t addr, int flags, struct thread *td)
580 {
581         struct bpf_d *d = dev->si_drv1;
582         int error = 0;
583
584         crit_enter();
585         if (d->bd_state == BPF_WAITING)
586                 callout_stop(&d->bd_callout);
587         d->bd_state = BPF_IDLE;
588         crit_exit();
589
590         switch (cmd) {
591
592         default:
593                 error = EINVAL;
594                 break;
595
596         /*
597          * Check for read packet available.
598          */
599         case FIONREAD:
600                 {
601                         int n;
602
603                         crit_enter();
604                         n = d->bd_slen;
605                         if (d->bd_hbuf)
606                                 n += d->bd_hlen;
607                         crit_exit();
608
609                         *(int *)addr = n;
610                         break;
611                 }
612
613         case SIOCGIFADDR:
614                 {
615                         struct ifnet *ifp;
616
617                         if (d->bd_bif == NULL)
618                                 error = EINVAL;
619                         else {
620                                 ifp = d->bd_bif->bif_ifp;
621                                 error = (*ifp->if_ioctl)(ifp, cmd, addr,
622                                                          td->td_proc->p_ucred);
623                         }
624                         break;
625                 }
626
627         /*
628          * Get buffer len [for read()].
629          */
630         case BIOCGBLEN:
631                 *(u_int *)addr = d->bd_bufsize;
632                 break;
633
634         /*
635          * Set buffer length.
636          */
637         case BIOCSBLEN:
638                 if (d->bd_bif != 0)
639                         error = EINVAL;
640                 else {
641                         u_int size = *(u_int *)addr;
642
643                         if (size > bpf_maxbufsize)
644                                 *(u_int *)addr = size = bpf_maxbufsize;
645                         else if (size < BPF_MINBUFSIZE)
646                                 *(u_int *)addr = size = BPF_MINBUFSIZE;
647                         d->bd_bufsize = size;
648                 }
649                 break;
650
651         /*
652          * Set link layer read filter.
653          */
654         case BIOCSETF:
655                 error = bpf_setf(d, (struct bpf_program *)addr);
656                 break;
657
658         /*
659          * Flush read packet buffer.
660          */
661         case BIOCFLUSH:
662                 crit_enter();
663                 reset_d(d);
664                 crit_exit();
665                 break;
666
667         /*
668          * Put interface into promiscuous mode.
669          */
670         case BIOCPROMISC:
671                 if (d->bd_bif == NULL) {
672                         /*
673                          * No interface attached yet.
674                          */
675                         error = EINVAL;
676                         break;
677                 }
678                 crit_enter();
679                 if (d->bd_promisc == 0) {
680                         error = ifpromisc(d->bd_bif->bif_ifp, 1);
681                         if (error == 0)
682                                 d->bd_promisc = 1;
683                 }
684                 crit_exit();
685                 break;
686
687         /*
688          * Get device parameters.
689          */
690         case BIOCGDLT:
691                 if (d->bd_bif == NULL)
692                         error = EINVAL;
693                 else
694                         *(u_int *)addr = d->bd_bif->bif_dlt;
695                 break;
696
697         /*
698          * Get a list of supported data link types.
699          */
700         case BIOCGDLTLIST:
701                 if (d->bd_bif == NULL)
702                         error = EINVAL;
703                 else
704                         error = bpf_getdltlist(d, (struct bpf_dltlist *)addr);
705                 break;
706
707         /*
708          * Set data link type.
709          */
710         case BIOCSDLT:
711                 if (d->bd_bif == NULL)
712                         error = EINVAL;
713                 else
714                         error = bpf_setdlt(d, *(u_int *)addr);
715                 break;
716
717         /*
718          * Get interface name.
719          */
720         case BIOCGETIF:
721                 if (d->bd_bif == NULL) {
722                         error = EINVAL;
723                 } else {
724                         struct ifnet *const ifp = d->bd_bif->bif_ifp;
725                         struct ifreq *const ifr = (struct ifreq *)addr;
726
727                         strlcpy(ifr->ifr_name, ifp->if_xname,
728                                 sizeof ifr->ifr_name);
729                 }
730                 break;
731
732         /*
733          * Set interface.
734          */
735         case BIOCSETIF:
736                 error = bpf_setif(d, (struct ifreq *)addr);
737                 break;
738
739         /*
740          * Set read timeout.
741          */
742         case BIOCSRTIMEOUT:
743                 {
744                         struct timeval *tv = (struct timeval *)addr;
745
746                         /*
747                          * Subtract 1 tick from tvtohz() since this isn't
748                          * a one-shot timer.
749                          */
750                         if ((error = itimerfix(tv)) == 0)
751                                 d->bd_rtout = tvtohz_low(tv);
752                         break;
753                 }
754
755         /*
756          * Get read timeout.
757          */
758         case BIOCGRTIMEOUT:
759                 {
760                         struct timeval *tv = (struct timeval *)addr;
761
762                         tv->tv_sec = d->bd_rtout / hz;
763                         tv->tv_usec = (d->bd_rtout % hz) * tick;
764                         break;
765                 }
766
767         /*
768          * Get packet stats.
769          */
770         case BIOCGSTATS:
771                 {
772                         struct bpf_stat *bs = (struct bpf_stat *)addr;
773
774                         bs->bs_recv = d->bd_rcount;
775                         bs->bs_drop = d->bd_dcount;
776                         break;
777                 }
778
779         /*
780          * Set immediate mode.
781          */
782         case BIOCIMMEDIATE:
783                 d->bd_immediate = *(u_int *)addr;
784                 break;
785
786         case BIOCVERSION:
787                 {
788                         struct bpf_version *bv = (struct bpf_version *)addr;
789
790                         bv->bv_major = BPF_MAJOR_VERSION;
791                         bv->bv_minor = BPF_MINOR_VERSION;
792                         break;
793                 }
794
795         /*
796          * Get "header already complete" flag
797          */
798         case BIOCGHDRCMPLT:
799                 *(u_int *)addr = d->bd_hdrcmplt;
800                 break;
801
802         /*
803          * Set "header already complete" flag
804          */
805         case BIOCSHDRCMPLT:
806                 d->bd_hdrcmplt = *(u_int *)addr ? 1 : 0;
807                 break;
808
809         /*
810          * Get "see sent packets" flag
811          */
812         case BIOCGSEESENT:
813                 *(u_int *)addr = d->bd_seesent;
814                 break;
815
816         /*
817          * Set "see sent packets" flag
818          */
819         case BIOCSSEESENT:
820                 d->bd_seesent = *(u_int *)addr;
821                 break;
822
823         case FIONBIO:           /* Non-blocking I/O */
824                 break;
825
826         case FIOASYNC:          /* Send signal on receive packets */
827                 d->bd_async = *(int *)addr;
828                 break;
829
830         case FIOSETOWN:
831                 error = fsetown(*(int *)addr, &d->bd_sigio);
832                 break;
833
834         case FIOGETOWN:
835                 *(int *)addr = fgetown(d->bd_sigio);
836                 break;
837
838         /* This is deprecated, FIOSETOWN should be used instead. */
839         case TIOCSPGRP:
840                 error = fsetown(-(*(int *)addr), &d->bd_sigio);
841                 break;
842
843         /* This is deprecated, FIOGETOWN should be used instead. */
844         case TIOCGPGRP:
845                 *(int *)addr = -fgetown(d->bd_sigio);
846                 break;
847
848         case BIOCSRSIG:         /* Set receive signal */
849                 {
850                         u_int sig;
851
852                         sig = *(u_int *)addr;
853
854                         if (sig >= NSIG)
855                                 error = EINVAL;
856                         else
857                                 d->bd_sig = sig;
858                         break;
859                 }
860         case BIOCGRSIG:
861                 *(u_int *)addr = d->bd_sig;
862                 break;
863         }
864         return(error);
865 }
866
867 /*
868  * Set d's packet filter program to fp.  If this file already has a filter,
869  * free it and replace it.  Returns EINVAL for bogus requests.
870  */
871 static int
872 bpf_setf(struct bpf_d *d, struct bpf_program *fp)
873 {
874         struct bpf_insn *fcode, *old;
875         u_int flen, size;
876
877         old = d->bd_filter;
878         if (fp->bf_insns == NULL) {
879                 if (fp->bf_len != 0)
880                         return(EINVAL);
881                 crit_enter();
882                 d->bd_filter = NULL;
883                 reset_d(d);
884                 crit_exit();
885                 if (old != 0)
886                         free(old, M_BPF);
887                 return(0);
888         }
889         flen = fp->bf_len;
890         if (flen > BPF_MAXINSNS)
891                 return(EINVAL);
892
893         size = flen * sizeof *fp->bf_insns;
894         fcode = (struct bpf_insn *)malloc(size, M_BPF, M_WAITOK);
895         if (copyin(fp->bf_insns, fcode, size) == 0 &&
896             bpf_validate(fcode, (int)flen)) {
897                 crit_enter();
898                 d->bd_filter = fcode;
899                 reset_d(d);
900                 crit_exit();
901                 if (old != 0)
902                         free(old, M_BPF);
903
904                 return(0);
905         }
906         free(fcode, M_BPF);
907         return(EINVAL);
908 }
909
910 /*
911  * Detach a file from its current interface (if attached at all) and attach
912  * to the interface indicated by the name stored in ifr.
913  * Return an errno or 0.
914  */
915 static int
916 bpf_setif(struct bpf_d *d, struct ifreq *ifr)
917 {
918         struct bpf_if *bp;
919         int error;
920         struct ifnet *theywant;
921
922         theywant = ifunit(ifr->ifr_name);
923         if (theywant == NULL)
924                 return(ENXIO);
925
926         /*
927          * Look through attached interfaces for the named one.
928          */
929         for (bp = bpf_iflist; bp != 0; bp = bp->bif_next) {
930                 struct ifnet *ifp = bp->bif_ifp;
931
932                 if (ifp == NULL || ifp != theywant)
933                         continue;
934                 /* skip additional entry */
935                 if (bp->bif_driverp != &ifp->if_bpf)
936                         continue;
937                 /*
938                  * We found the requested interface.
939                  * If it's not up, return an error.
940                  * Allocate the packet buffers if we need to.
941                  * If we're already attached to requested interface,
942                  * just flush the buffer.
943                  */
944                 if (!(ifp->if_flags & IFF_UP))
945                         return(ENETDOWN);
946
947                 if (d->bd_sbuf == NULL) {
948                         error = bpf_allocbufs(d);
949                         if (error != 0)
950                                 return(error);
951                 }
952                 crit_enter();
953                 if (bp != d->bd_bif) {
954                         if (d->bd_bif != NULL) {
955                                 /*
956                                  * Detach if attached to something else.
957                                  */
958                                 bpf_detachd(d);
959                         }
960
961                         bpf_attachd(d, bp);
962                 }
963                 reset_d(d);
964                 crit_exit();
965                 return(0);
966         }
967
968         /* Not found. */
969         return(ENXIO);
970 }
971
972 /*
973  * Support for select() and poll() system calls
974  *
975  * Return true iff the specific operation will not block indefinitely.
976  * Otherwise, return false but make a note that a selwakeup() must be done.
977  */
978 int
979 bpfpoll(dev_t dev, int events, struct thread *td)
980 {
981         struct bpf_d *d;
982         int revents;
983
984         d = dev->si_drv1;
985         if (d->bd_bif == NULL)
986                 return(ENXIO);
987
988         revents = events & (POLLOUT | POLLWRNORM);
989         crit_enter();
990         if (events & (POLLIN | POLLRDNORM)) {
991                 /*
992                  * An imitation of the FIONREAD ioctl code.
993                  * XXX not quite.  An exact imitation:
994                  *      if (d->b_slen != 0 ||
995                  *          (d->bd_hbuf != NULL && d->bd_hlen != 0)
996                  */
997                 if (d->bd_hlen != 0 ||
998                     ((d->bd_immediate || d->bd_state == BPF_TIMED_OUT) &&
999                     d->bd_slen != 0))
1000                         revents |= events & (POLLIN | POLLRDNORM);
1001                 else {
1002                         selrecord(td, &d->bd_sel);
1003                         /* Start the read timeout if necessary. */
1004                         if (d->bd_rtout > 0 && d->bd_state == BPF_IDLE) {
1005                                 callout_reset(&d->bd_callout, d->bd_rtout,
1006                                     bpf_timed_out, d);
1007                                 d->bd_state = BPF_WAITING;
1008                         }
1009                 }
1010         }
1011         crit_exit();
1012         return(revents);
1013 }
1014
1015 /*
1016  * Process the packet pkt of length pktlen.  The packet is parsed
1017  * by each listener's filter, and if accepted, stashed into the
1018  * corresponding buffer.
1019  */
1020 void
1021 bpf_tap(struct bpf_if *bp, u_char *pkt, u_int pktlen)
1022 {
1023         struct bpf_d *d;
1024         u_int slen;
1025
1026         /*
1027          * Note that the ipl does not have to be raised at this point.
1028          * The only problem that could arise here is that if two different
1029          * interfaces shared any data.  This is not the case.
1030          */
1031         SLIST_FOREACH(d, &bp->bif_dlist, bd_next) {
1032                 ++d->bd_rcount;
1033                 slen = bpf_filter(d->bd_filter, pkt, pktlen, pktlen);
1034                 if (slen != 0)
1035                         catchpacket(d, pkt, pktlen, slen, ovbcopy);
1036         }
1037 }
1038
1039 /*
1040  * Copy data from an mbuf chain into a buffer.  This code is derived
1041  * from m_copydata in sys/uipc_mbuf.c.
1042  */
1043 static void
1044 bpf_mcopy(const void *src_arg, void *dst_arg, size_t len)
1045 {
1046         const struct mbuf *m;
1047         u_int count;
1048         u_char *dst;
1049
1050         m = src_arg;
1051         dst = dst_arg;
1052         while (len > 0) {
1053                 if (m == NULL)
1054                         panic("bpf_mcopy");
1055                 count = min(m->m_len, len);
1056                 bcopy(mtod(m, void *), dst, count);
1057                 m = m->m_next;
1058                 dst += count;
1059                 len -= count;
1060         }
1061 }
1062
1063 /*
1064  * Process the packet in the mbuf chain m.  The packet is parsed by each
1065  * listener's filter, and if accepted, stashed into the corresponding
1066  * buffer.
1067  */
1068 void
1069 bpf_mtap(struct bpf_if *bp, struct mbuf *m)
1070 {
1071         struct bpf_d *d;
1072         u_int pktlen, slen;
1073         struct mbuf *m0;
1074
1075         /* Don't compute pktlen, if no descriptor is attached. */
1076         if (SLIST_EMPTY(&bp->bif_dlist))
1077                 return;
1078
1079         pktlen = 0;
1080         for (m0 = m; m0 != NULL; m0 = m0->m_next)
1081                 pktlen += m0->m_len;
1082
1083         SLIST_FOREACH(d, &bp->bif_dlist, bd_next) {
1084                 if (!d->bd_seesent && (m->m_pkthdr.rcvif == NULL))
1085                         continue;
1086                 ++d->bd_rcount;
1087                 slen = bpf_filter(d->bd_filter, (u_char *)m, pktlen, 0);
1088                 if (slen != 0)
1089                         catchpacket(d, (u_char *)m, pktlen, slen, bpf_mcopy);
1090         }
1091 }
1092
1093 void
1094 bpf_mtap_family(struct bpf_if *bp, struct mbuf *m, sa_family_t family)
1095 {
1096         u_int family4;
1097
1098         KKASSERT(family != AF_UNSPEC);
1099         
1100         family4 = (u_int)family;
1101         bpf_ptap(bp, m, &family4, sizeof(family4));
1102 }
1103
1104 /*
1105  * Process the packet in the mbuf chain m with the header in m prepended.
1106  * The packet is parsed by each listener's filter, and if accepted,
1107  * stashed into the corresponding buffer.
1108  */
1109 void
1110 bpf_ptap(struct bpf_if *bp, struct mbuf *m, const void *data, u_int dlen)
1111 {
1112         struct mbuf mb;
1113
1114         /*
1115          * Craft on-stack mbuf suitable for passing to bpf_mtap.
1116          * Note that we cut corners here; we only setup what's
1117          * absolutely needed--this mbuf should never go anywhere else.
1118          */
1119         mb.m_next = m;
1120         mb.m_data = __DECONST(void *, data); /* LINTED */
1121         mb.m_len = dlen;
1122
1123         bpf_mtap(bp, &mb);
1124 }
1125
1126 /*
1127  * Move the packet data from interface memory (pkt) into the
1128  * store buffer.  Return 1 if it's time to wakeup a listener (buffer full),
1129  * otherwise 0.  "copy" is the routine called to do the actual data
1130  * transfer.  bcopy is passed in to copy contiguous chunks, while
1131  * bpf_mcopy is passed in to copy mbuf chains.  In the latter case,
1132  * pkt is really an mbuf.
1133  */
1134 static void
1135 catchpacket(struct bpf_d *d, u_char *pkt, u_int pktlen, u_int snaplen,
1136             void (*cpfn)(const void *, void *, size_t))
1137 {
1138         struct bpf_hdr *hp;
1139         int totlen, curlen;
1140         int hdrlen = d->bd_bif->bif_hdrlen;
1141         /*
1142          * Figure out how many bytes to move.  If the packet is
1143          * greater or equal to the snapshot length, transfer that
1144          * much.  Otherwise, transfer the whole packet (unless
1145          * we hit the buffer size limit).
1146          */
1147         totlen = hdrlen + min(snaplen, pktlen);
1148         if (totlen > d->bd_bufsize)
1149                 totlen = d->bd_bufsize;
1150
1151         /*
1152          * Round up the end of the previous packet to the next longword.
1153          */
1154         curlen = BPF_WORDALIGN(d->bd_slen);
1155         if (curlen + totlen > d->bd_bufsize) {
1156                 /*
1157                  * This packet will overflow the storage buffer.
1158                  * Rotate the buffers if we can, then wakeup any
1159                  * pending reads.
1160                  */
1161                 if (d->bd_fbuf == NULL) {
1162                         /*
1163                          * We haven't completed the previous read yet,
1164                          * so drop the packet.
1165                          */
1166                         ++d->bd_dcount;
1167                         return;
1168                 }
1169                 ROTATE_BUFFERS(d);
1170                 bpf_wakeup(d);
1171                 curlen = 0;
1172         }
1173         else if (d->bd_immediate || d->bd_state == BPF_TIMED_OUT)
1174                 /*
1175                  * Immediate mode is set, or the read timeout has
1176                  * already expired during a select call.  A packet
1177                  * arrived, so the reader should be woken up.
1178                  */
1179                 bpf_wakeup(d);
1180
1181         /*
1182          * Append the bpf header.
1183          */
1184         hp = (struct bpf_hdr *)(d->bd_sbuf + curlen);
1185         microtime(&hp->bh_tstamp);
1186         hp->bh_datalen = pktlen;
1187         hp->bh_hdrlen = hdrlen;
1188         /*
1189          * Copy the packet data into the store buffer and update its length.
1190          */
1191         (*cpfn)(pkt, (u_char *)hp + hdrlen, (hp->bh_caplen = totlen - hdrlen));
1192         d->bd_slen = curlen + totlen;
1193 }
1194
1195 /*
1196  * Initialize all nonzero fields of a descriptor.
1197  */
1198 static int
1199 bpf_allocbufs(struct bpf_d *d)
1200 {
1201         d->bd_fbuf = malloc(d->bd_bufsize, M_BPF, M_WAITOK);
1202         if (d->bd_fbuf == NULL)
1203                 return(ENOBUFS);
1204
1205         d->bd_sbuf = malloc(d->bd_bufsize, M_BPF, M_WAITOK);
1206         if (d->bd_sbuf == NULL) {
1207                 free(d->bd_fbuf, M_BPF);
1208                 return(ENOBUFS);
1209         }
1210         d->bd_slen = 0;
1211         d->bd_hlen = 0;
1212         return(0);
1213 }
1214
1215 /*
1216  * Free buffers currently in use by a descriptor.
1217  * Called on close.
1218  */
1219 static void
1220 bpf_freed(struct bpf_d *d)
1221 {
1222         /*
1223          * We don't need to lock out interrupts since this descriptor has
1224          * been detached from its interface and it yet hasn't been marked
1225          * free.
1226          */
1227         if (d->bd_sbuf != NULL) {
1228                 free(d->bd_sbuf, M_BPF);
1229                 if (d->bd_hbuf != NULL)
1230                         free(d->bd_hbuf, M_BPF);
1231                 if (d->bd_fbuf != NULL)
1232                         free(d->bd_fbuf, M_BPF);
1233         }
1234         if (d->bd_filter)
1235                 free(d->bd_filter, M_BPF);
1236 }
1237
1238 /*
1239  * Attach an interface to bpf.  ifp is a pointer to the structure
1240  * defining the interface to be attached, dlt is the link layer type,
1241  * and hdrlen is the fixed size of the link header (variable length
1242  * headers are not yet supported).
1243  */
1244 void
1245 bpfattach(struct ifnet *ifp, u_int dlt, u_int hdrlen)
1246 {
1247         bpfattach_dlt(ifp, dlt, hdrlen, &ifp->if_bpf);
1248 }
1249
1250 void
1251 bpfattach_dlt(struct ifnet *ifp, u_int dlt, u_int hdrlen, struct bpf_if **driverp)
1252 {
1253         struct bpf_if *bp;
1254
1255         bp = malloc(sizeof *bp, M_BPF, M_WAITOK | M_ZERO);
1256
1257         SLIST_INIT(&bp->bif_dlist);
1258         bp->bif_ifp = ifp;
1259         bp->bif_dlt = dlt;
1260         bp->bif_driverp = driverp;
1261         *bp->bif_driverp = NULL;
1262
1263         bp->bif_next = bpf_iflist;
1264         bpf_iflist = bp;
1265
1266         /*
1267          * Compute the length of the bpf header.  This is not necessarily
1268          * equal to SIZEOF_BPF_HDR because we want to insert spacing such
1269          * that the network layer header begins on a longword boundary (for
1270          * performance reasons and to alleviate alignment restrictions).
1271          */
1272         bp->bif_hdrlen = BPF_WORDALIGN(hdrlen + SIZEOF_BPF_HDR) - hdrlen;
1273
1274         if (bootverbose)
1275                 if_printf(ifp, "bpf attached\n");
1276 }
1277
1278 /*
1279  * Detach bpf from an interface.  This involves detaching each descriptor
1280  * associated with the interface, and leaving bd_bif NULL.  Notify each
1281  * descriptor as it's detached so that any sleepers wake up and get
1282  * ENXIO.
1283  */
1284 void
1285 bpfdetach(struct ifnet *ifp)
1286 {
1287         struct bpf_if *bp, *bp_prev;
1288         struct bpf_d *d;
1289
1290         crit_enter();
1291
1292         /* Locate BPF interface information */
1293         bp_prev = NULL;
1294         for (bp = bpf_iflist; bp != NULL; bp = bp->bif_next) {
1295                 if (ifp == bp->bif_ifp)
1296                         break;
1297                 bp_prev = bp;
1298         }
1299
1300         /* Interface wasn't attached */
1301         if (bp->bif_ifp == NULL) {
1302                 crit_exit();
1303                 printf("bpfdetach: %s was not attached\n", ifp->if_xname);
1304                 return;
1305         }
1306
1307         while ((d = SLIST_FIRST(&bp->bif_dlist)) != NULL) {
1308                 bpf_detachd(d);
1309                 bpf_wakeup(d);
1310         }
1311
1312         if (bp_prev != NULL)
1313                 bp_prev->bif_next = bp->bif_next;
1314         else
1315                 bpf_iflist = bp->bif_next;
1316
1317         free(bp, M_BPF);
1318
1319         crit_exit();
1320 }
1321
1322 /*
1323  * Get a list of available data link type of the interface.
1324  */
1325 static int
1326 bpf_getdltlist(struct bpf_d *d, struct bpf_dltlist *bfl)
1327 {
1328         int n, error;
1329         struct ifnet *ifp;
1330         struct bpf_if *bp;
1331
1332         ifp = d->bd_bif->bif_ifp;
1333         n = 0;
1334         error = 0;
1335         for (bp = bpf_iflist; bp != 0; bp = bp->bif_next) {
1336                 if (bp->bif_ifp != ifp)
1337                         continue;
1338                 if (bfl->bfl_list != NULL) {
1339                         if (n >= bfl->bfl_len) {
1340                                 return (ENOMEM);
1341                         }
1342                         error = copyout(&bp->bif_dlt,
1343                             bfl->bfl_list + n, sizeof(u_int));
1344                 }
1345                 n++;
1346         }
1347         bfl->bfl_len = n;
1348         return(error);
1349 }
1350
1351 /*
1352  * Set the data link type of a BPF instance.
1353  */
1354 static int
1355 bpf_setdlt(struct bpf_d *d, u_int dlt)
1356 {
1357         int error, opromisc;
1358         struct ifnet *ifp;
1359         struct bpf_if *bp;
1360
1361         if (d->bd_bif->bif_dlt == dlt)
1362                 return (0);
1363         ifp = d->bd_bif->bif_ifp;
1364         for (bp = bpf_iflist; bp != 0; bp = bp->bif_next) {
1365                 if (bp->bif_ifp == ifp && bp->bif_dlt == dlt)
1366                         break;
1367         }
1368         if (bp != NULL) {
1369                 opromisc = d->bd_promisc;
1370                 crit_enter();
1371                 bpf_detachd(d);
1372                 bpf_attachd(d, bp);
1373                 reset_d(d);
1374                 if (opromisc) {
1375                         error = ifpromisc(bp->bif_ifp, 1);
1376                         if (error)
1377                                 if_printf(bp->bif_ifp,
1378                                         "bpf_setdlt: ifpromisc failed (%d)\n",
1379                                         error);
1380                         else
1381                                 d->bd_promisc = 1;
1382                 }
1383                 crit_exit();
1384         }
1385         return(bp == NULL ? EINVAL : 0);
1386 }
1387
1388 static void
1389 bpf_drvinit(void *unused)
1390 {
1391         cdevsw_add(&bpf_cdevsw, 0, 0);
1392 }
1393
1394 SYSINIT(bpfdev,SI_SUB_DRIVERS,SI_ORDER_MIDDLE+CDEV_MAJOR,bpf_drvinit,NULL)
1395
1396 #else /* !BPF */
1397 /*
1398  * NOP stubs to allow bpf-using drivers to load and function.
1399  *
1400  * A 'better' implementation would allow the core bpf functionality
1401  * to be loaded at runtime.
1402  */
1403
1404 void
1405 bpf_tap(struct bpf_if *bp, u_char *pkt, u_int pktlen)
1406 {
1407 }
1408
1409 void
1410 bpf_mtap(struct bpf_if *bp, struct mbuf *m)
1411 {
1412 }
1413
1414 void
1415 bpf_ptap(struct bpf_if *bp, struct mbuf *m, const void *data, u_int dlen)
1416 {
1417 }
1418
1419 void
1420 bpfattach(struct ifnet *ifp, u_int dlt, u_int hdrlen)
1421 {
1422 }
1423
1424 void
1425 bpfattach_dlt(struct ifnet *ifp, u_int dlt, u_int hdrlen, struct bpf_if **driverp)
1426 {
1427 }
1428
1429 void
1430 bpfdetach(struct ifnet *ifp)
1431 {
1432 }
1433
1434 u_int
1435 bpf_filter(const struct bpf_insn *pc, u_char *p, u_int wirelen, u_int buflen)
1436 {
1437         return -1;      /* "no filter" behaviour */
1438 }
1439
1440 #endif /* !BPF */