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