Parallelize bridge_input step 1.8/2:
[dragonfly.git] / sys / net / bridge / if_bridge.c
1 /*
2  * Copyright 2001 Wasabi Systems, Inc.
3  * All rights reserved.
4  *
5  * Written by Jason R. Thorpe for Wasabi Systems, Inc.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. All advertising materials mentioning features or use of this software
16  *    must display the following acknowledgement:
17  *      This product includes software developed for the NetBSD Project by
18  *      Wasabi Systems, Inc.
19  * 4. The name of Wasabi Systems, Inc. may not be used to endorse
20  *    or promote products derived from this software without specific prior
21  *    written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY WASABI SYSTEMS, INC. ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
25  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
26  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL WASABI SYSTEMS, INC
27  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33  * POSSIBILITY OF SUCH DAMAGE.
34  */
35
36 /*
37  * Copyright (c) 1999, 2000 Jason L. Wright (jason@thought.net)
38  * All rights reserved.
39  *
40  * Redistribution and use in source and binary forms, with or without
41  * modification, are permitted provided that the following conditions
42  * are met:
43  * 1. Redistributions of source code must retain the above copyright
44  *    notice, this list of conditions and the following disclaimer.
45  * 2. Redistributions in binary form must reproduce the above copyright
46  *    notice, this list of conditions and the following disclaimer in the
47  *    documentation and/or other materials provided with the distribution.
48  * 3. All advertising materials mentioning features or use of this software
49  *    must display the following acknowledgement:
50  *      This product includes software developed by Jason L. Wright
51  * 4. The name of the author may not be used to endorse or promote products
52  *    derived from this software without specific prior written permission.
53  *
54  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
55  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
56  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
57  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
58  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
59  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
60  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
62  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
63  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
64  * POSSIBILITY OF SUCH DAMAGE.
65  *
66  * $OpenBSD: if_bridge.c,v 1.60 2001/06/15 03:38:33 itojun Exp $
67  * $NetBSD: if_bridge.c,v 1.31 2005/06/01 19:45:34 jdc Exp $
68  * $FreeBSD: src/sys/net/if_bridge.c,v 1.26 2005/10/13 23:05:55 thompsa Exp $
69  * $DragonFly: src/sys/net/bridge/if_bridge.c,v 1.52 2008/11/21 11:11:03 sephe Exp $
70  */
71
72 /*
73  * Network interface bridge support.
74  *
75  * TODO:
76  *
77  *      - Currently only supports Ethernet-like interfaces (Ethernet,
78  *        802.11, VLANs on Ethernet, etc.)  Figure out a nice way
79  *        to bridge other types of interfaces (FDDI-FDDI, and maybe
80  *        consider heterogenous bridges).
81  *
82  *
83  * Bridge's route information is duplicated to each CPUs:
84  *
85  *      CPU0          CPU1          CPU2          CPU3
86  * +-----------+ +-----------+ +-----------+ +-----------+
87  * |  rtnode   | |  rtnode   | |  rtnode   | |  rtnode   |
88  * |           | |           | |           | |           |
89  * | dst eaddr | | dst eaddr | | dst eaddr | | dst eaddr |
90  * +-----------+ +-----------+ +-----------+ +-----------+
91  *       |         |                     |         |
92  *       |         |                     |         |
93  *       |         |     +----------+    |         |
94  *       |         |     |  rtinfo  |    |         |
95  *       |         +---->|          |<---+         |
96  *       |               |  flags   |              |
97  *       +-------------->|  timeout |<-------------+
98  *                       |  dst_ifp |
99  *                       +----------+
100  *
101  * We choose to put timeout and dst_ifp into shared part, so updating
102  * them will be cheaper than using message forwarding.  Also there is
103  * not need to use spinlock to protect the updating: timeout and dst_ifp
104  * is not related and specific field's updating order has no importance.
105  * The cache pollution by the share part should not be heavy: in a stable
106  * setup, dst_ifp probably will be not changed in rtnode's life time,
107  * while timeout is refreshed once per second; most of the time, timeout
108  * and dst_ifp are read-only accessed.
109  *
110  *
111  * Bridge route information installation on bridge_input path:
112  *
113  *      CPU0           CPU1         CPU2          CPU3
114  *
115  *                               tcp_thread2
116  *                                    |
117  *                                alloc nmsg
118  *                    snd nmsg        |
119  *                    w/o rtinfo      |
120  *      ifnet0<-----------------------+
121  *        |                           :
122  *    lookup dst                      :
123  *   rtnode exists?(Y)free nmsg       :
124  *        |(N)                        :
125  *        |
126  *  alloc rtinfo
127  *  alloc rtnode
128  * install rtnode
129  *        |
130  *        +---------->ifnet1
131  *        : fwd nmsg    |
132  *        : w/ rtinfo   |
133  *        :             |
134  *        :             |
135  *                 alloc rtnode
136  *               (w/ nmsg's rtinfo)
137  *                install rtnode
138  *                      |
139  *                      +---------->ifnet2
140  *                      : fwd nmsg    |
141  *                      : w/ rtinfo   |
142  *                      :             |
143  *                      :         same as ifnet1
144  *                                    |
145  *                                    +---------->ifnet3
146  *                                    : fwd nmsg    |
147  *                                    : w/ rtinfo   |
148  *                                    :             |
149  *                                    :         same as ifnet1
150  *                                               free nmsg
151  *                                                  :
152  *                                                  :
153  *
154  * The netmsgs forwarded between protocol threads and ifnet threads are
155  * allocated with (M_WAITOK|M_NULLOK), so it will not fail under most
156  * cases (route information is too precious to be not installed :).
157  * Since multiple threads may try to install route information for the
158  * same dst eaddr, we look up route information in ifnet0.  However, this
159  * looking up only need to be performed on ifnet0, which is the start
160  * point of the route information installation process.
161  *
162  *
163  * Bridge route information deleting/flushing:
164  *
165  *  CPU0            CPU1             CPU2             CPU3
166  *
167  * netisr0
168  *   |
169  * find suitable rtnodes,
170  * mark their rtinfo dead
171  *   |
172  *   | domsg <------------------------------------------+
173  *   |                                                  | replymsg
174  *   |                                                  |
175  *   V     fwdmsg           fwdmsg           fwdmsg     |
176  * ifnet0 --------> ifnet1 --------> ifnet2 --------> ifnet3
177  * delete rtnodes   delete rtnodes   delete rtnodes   delete rtnodes
178  * w/ dead rtinfo   w/ dead rtinfo   w/ dead rtinfo   w/ dead rtinfo
179  *                                                    free dead rtinfos
180  *
181  * All deleting/flushing operations are serialized by netisr0, so each
182  * operation only reaps the route information marked dead by itself.
183  *
184  *
185  * Bridge route information adding/deleting/flushing:
186  * Since all operation is serialized by the fixed message flow between
187  * ifnet threads, it is not possible to create corrupted per-cpu route
188  * information.
189  */
190
191 #include "opt_inet.h"
192 #include "opt_inet6.h"
193
194 #include <sys/param.h>
195 #include <sys/mbuf.h>
196 #include <sys/malloc.h>
197 #include <sys/protosw.h>
198 #include <sys/systm.h>
199 #include <sys/time.h>
200 #include <sys/socket.h> /* for net/if.h */
201 #include <sys/sockio.h>
202 #include <sys/ctype.h>  /* string functions */
203 #include <sys/kernel.h>
204 #include <sys/random.h>
205 #include <sys/sysctl.h>
206 #include <sys/module.h>
207 #include <sys/proc.h>
208 #include <sys/lock.h>
209 #include <sys/thread.h>
210 #include <sys/thread2.h>
211 #include <sys/mpipe.h>
212
213 #include <net/bpf.h>
214 #include <net/if.h>
215 #include <net/if_dl.h>
216 #include <net/if_types.h>
217 #include <net/if_var.h>
218 #include <net/pfil.h>
219 #include <net/ifq_var.h>
220 #include <net/if_clone.h>
221
222 #include <netinet/in.h> /* for struct arpcom */
223 #include <netinet/in_systm.h>
224 #include <netinet/in_var.h>
225 #include <netinet/ip.h>
226 #include <netinet/ip_var.h>
227 #ifdef INET6
228 #include <netinet/ip6.h>
229 #include <netinet6/ip6_var.h>
230 #endif
231 #include <netinet/if_ether.h> /* for struct arpcom */
232 #include <net/bridge/if_bridgevar.h>
233 #include <net/if_llc.h>
234 #include <net/netmsg2.h>
235
236 #include <net/route.h>
237 #include <sys/in_cksum.h>
238
239 /*
240  * Size of the route hash table.  Must be a power of two.
241  */
242 #ifndef BRIDGE_RTHASH_SIZE
243 #define BRIDGE_RTHASH_SIZE              1024
244 #endif
245
246 #define BRIDGE_RTHASH_MASK              (BRIDGE_RTHASH_SIZE - 1)
247
248 /*
249  * Maximum number of addresses to cache.
250  */
251 #ifndef BRIDGE_RTABLE_MAX
252 #define BRIDGE_RTABLE_MAX               100
253 #endif
254
255 /*
256  * Spanning tree defaults.
257  */
258 #define BSTP_DEFAULT_MAX_AGE            (20 * 256)
259 #define BSTP_DEFAULT_HELLO_TIME         (2 * 256)
260 #define BSTP_DEFAULT_FORWARD_DELAY      (15 * 256)
261 #define BSTP_DEFAULT_HOLD_TIME          (1 * 256)
262 #define BSTP_DEFAULT_BRIDGE_PRIORITY    0x8000
263 #define BSTP_DEFAULT_PORT_PRIORITY      0x80
264 #define BSTP_DEFAULT_PATH_COST          55
265
266 /*
267  * Timeout (in seconds) for entries learned dynamically.
268  */
269 #ifndef BRIDGE_RTABLE_TIMEOUT
270 #define BRIDGE_RTABLE_TIMEOUT           (20 * 60)       /* same as ARP */
271 #endif
272
273 /*
274  * Number of seconds between walks of the route list.
275  */
276 #ifndef BRIDGE_RTABLE_PRUNE_PERIOD
277 #define BRIDGE_RTABLE_PRUNE_PERIOD      (5 * 60)
278 #endif
279
280 /*
281  * List of capabilities to mask on the member interface.
282  */
283 #define BRIDGE_IFCAPS_MASK              IFCAP_TXCSUM
284
285 typedef int     (*bridge_ctl_t)(struct bridge_softc *, void *);
286
287 struct netmsg_brctl {
288         struct netmsg           bc_nmsg;
289         bridge_ctl_t            bc_func;
290         struct bridge_softc     *bc_sc;
291         void                    *bc_arg;
292 };
293
294 struct netmsg_brsaddr {
295         struct netmsg           br_nmsg;
296         struct bridge_softc     *br_softc;
297         struct ifnet            *br_dst_if;
298         struct bridge_rtinfo    *br_rtinfo;
299         int                     br_setflags;
300         uint8_t                 br_dst[ETHER_ADDR_LEN];
301         uint8_t                 br_flags;
302 };
303
304 struct netmsg_braddbif {
305         struct netmsg           br_nmsg;
306         struct bridge_softc     *br_softc;
307         struct bridge_ifinfo    *br_bif_info;
308         struct ifnet            *br_bif_ifp;
309 };
310
311 struct netmsg_brdelbif {
312         struct netmsg           br_nmsg;
313         struct bridge_softc     *br_softc;
314         struct bridge_ifinfo    *br_bif_info;
315         struct bridge_iflist_head *br_bif_list;
316 };
317
318 struct netmsg_brsflags {
319         struct netmsg           br_nmsg;
320         struct bridge_softc     *br_softc;
321         struct bridge_ifinfo    *br_bif_info;
322         uint32_t                br_bif_flags;
323 };
324
325 eventhandler_tag        bridge_detach_cookie = NULL;
326
327 extern  struct mbuf *(*bridge_input_p)(struct ifnet *, struct mbuf *);
328 extern  int (*bridge_output_p)(struct ifnet *, struct mbuf *);
329 extern  void (*bridge_dn_p)(struct mbuf *, struct ifnet *);
330
331 static int      bridge_rtable_prune_period = BRIDGE_RTABLE_PRUNE_PERIOD;
332
333 static int      bridge_clone_create(struct if_clone *, int);
334 static void     bridge_clone_destroy(struct ifnet *);
335
336 static int      bridge_ioctl(struct ifnet *, u_long, caddr_t, struct ucred *);
337 static void     bridge_mutecaps(struct bridge_ifinfo *, struct ifnet *, int);
338 static void     bridge_ifdetach(void *, struct ifnet *);
339 static void     bridge_init(void *);
340 static void     bridge_stop(struct ifnet *);
341 static void     bridge_start(struct ifnet *);
342 static struct mbuf *bridge_input(struct ifnet *, struct mbuf *);
343 static int      bridge_output(struct ifnet *, struct mbuf *);
344
345 static void     bridge_forward(struct bridge_softc *, struct mbuf *m);
346
347 static void     bridge_timer_handler(struct netmsg *);
348 static void     bridge_timer(void *);
349
350 static void     bridge_broadcast(struct bridge_softc *, struct ifnet *,
351                     struct mbuf *, int);
352 static void     bridge_span(struct bridge_softc *, struct mbuf *);
353
354 static int      bridge_rtupdate(struct bridge_softc *, const uint8_t *,
355                     struct ifnet *, uint8_t);
356 static struct ifnet *bridge_rtlookup(struct bridge_softc *, const uint8_t *);
357 static void     bridge_rtreap(struct bridge_softc *);
358 static void     bridge_rttrim(struct bridge_softc *);
359 static int      bridge_rtage_finddead(struct bridge_softc *);
360 static void     bridge_rtage(struct bridge_softc *);
361 static void     bridge_rtflush(struct bridge_softc *, int);
362 static int      bridge_rtdaddr(struct bridge_softc *, const uint8_t *);
363 static int      bridge_rtsaddr(struct bridge_softc *, const uint8_t *,
364                     struct ifnet *, uint8_t);
365 static void     bridge_rtmsg_sync(struct bridge_softc *sc);
366 static void     bridge_rtreap_handler(struct netmsg *);
367 static void     bridge_rtinstall_handler(struct netmsg *);
368 static int      bridge_rtinstall_oncpu(struct bridge_softc *, const uint8_t *,
369                     struct ifnet *, int, uint8_t, struct bridge_rtinfo **);
370
371 static void     bridge_rtable_init(struct bridge_softc *);
372 static void     bridge_rtable_fini(struct bridge_softc *);
373
374 static int      bridge_rtnode_addr_cmp(const uint8_t *, const uint8_t *);
375 static struct bridge_rtnode *bridge_rtnode_lookup(struct bridge_softc *,
376                     const uint8_t *);
377 static void     bridge_rtnode_insert(struct bridge_softc *,
378                     struct bridge_rtnode *);
379 static void     bridge_rtnode_destroy(struct bridge_softc *,
380                     struct bridge_rtnode *);
381
382 static struct bridge_iflist *bridge_lookup_member(struct bridge_softc *,
383                     const char *name);
384 static struct bridge_iflist *bridge_lookup_member_if(struct bridge_softc *,
385                     struct ifnet *ifp);
386 static struct bridge_iflist *bridge_lookup_member_ifinfo(struct bridge_softc *,
387                     struct bridge_ifinfo *);
388 static void     bridge_delete_member(struct bridge_softc *,
389                     struct bridge_iflist *, int);
390 static void     bridge_delete_span(struct bridge_softc *,
391                     struct bridge_iflist *);
392
393 static int      bridge_control(struct bridge_softc *, u_long,
394                                bridge_ctl_t, void *);
395 static int      bridge_ioctl_init(struct bridge_softc *, void *);
396 static int      bridge_ioctl_stop(struct bridge_softc *, void *);
397 static int      bridge_ioctl_add(struct bridge_softc *, void *);
398 static int      bridge_ioctl_del(struct bridge_softc *, void *);
399 static int      bridge_ioctl_gifflags(struct bridge_softc *, void *);
400 static int      bridge_ioctl_sifflags(struct bridge_softc *, void *);
401 static int      bridge_ioctl_scache(struct bridge_softc *, void *);
402 static int      bridge_ioctl_gcache(struct bridge_softc *, void *);
403 static int      bridge_ioctl_gifs(struct bridge_softc *, void *);
404 static int      bridge_ioctl_rts(struct bridge_softc *, void *);
405 static int      bridge_ioctl_saddr(struct bridge_softc *, void *);
406 static int      bridge_ioctl_sto(struct bridge_softc *, void *);
407 static int      bridge_ioctl_gto(struct bridge_softc *, void *);
408 static int      bridge_ioctl_daddr(struct bridge_softc *, void *);
409 static int      bridge_ioctl_flush(struct bridge_softc *, void *);
410 static int      bridge_ioctl_gpri(struct bridge_softc *, void *);
411 static int      bridge_ioctl_spri(struct bridge_softc *, void *);
412 static int      bridge_ioctl_ght(struct bridge_softc *, void *);
413 static int      bridge_ioctl_sht(struct bridge_softc *, void *);
414 static int      bridge_ioctl_gfd(struct bridge_softc *, void *);
415 static int      bridge_ioctl_sfd(struct bridge_softc *, void *);
416 static int      bridge_ioctl_gma(struct bridge_softc *, void *);
417 static int      bridge_ioctl_sma(struct bridge_softc *, void *);
418 static int      bridge_ioctl_sifprio(struct bridge_softc *, void *);
419 static int      bridge_ioctl_sifcost(struct bridge_softc *, void *);
420 static int      bridge_ioctl_addspan(struct bridge_softc *, void *);
421 static int      bridge_ioctl_delspan(struct bridge_softc *, void *);
422 static int      bridge_pfil(struct mbuf **, struct ifnet *, struct ifnet *,
423                     int);
424 static int      bridge_ip_checkbasic(struct mbuf **mp);
425 #ifdef INET6
426 static int      bridge_ip6_checkbasic(struct mbuf **mp);
427 #endif /* INET6 */
428 static int      bridge_fragment(struct ifnet *, struct mbuf *,
429                     struct ether_header *, int, struct llc *);
430 static void     bridge_enqueue_internal(struct ifnet *, struct mbuf *m,
431                                         netisr_fn_t);
432 static void     bridge_enqueue_handler(struct netmsg *);
433 static void     bridge_pfil_enqueue_handler(struct netmsg *);
434 static void     bridge_pfil_enqueue(struct ifnet *, struct mbuf *, int);
435 static void     bridge_handoff(struct ifnet *, struct mbuf *);
436
437 static void     bridge_del_bif_handler(struct netmsg *);
438 static void     bridge_add_bif_handler(struct netmsg *);
439 static void     bridge_set_bifflags_handler(struct netmsg *);
440 static void     bridge_del_bif(struct bridge_softc *, struct bridge_ifinfo *,
441                     struct bridge_iflist_head *);
442 static void     bridge_add_bif(struct bridge_softc *, struct bridge_ifinfo *,
443                     struct ifnet *);
444 static void     bridge_set_bifflags(struct bridge_softc *,
445                     struct bridge_ifinfo *, uint32_t);
446
447 SYSCTL_DECL(_net_link);
448 SYSCTL_NODE(_net_link, IFT_BRIDGE, bridge, CTLFLAG_RW, 0, "Bridge");
449
450 static int pfil_onlyip = 1; /* only pass IP[46] packets when pfil is enabled */
451 static int pfil_bridge = 1; /* run pfil hooks on the bridge interface */
452 static int pfil_member = 1; /* run pfil hooks on the member interface */
453 SYSCTL_INT(_net_link_bridge, OID_AUTO, pfil_onlyip, CTLFLAG_RW,
454     &pfil_onlyip, 0, "Only pass IP packets when pfil is enabled");
455 SYSCTL_INT(_net_link_bridge, OID_AUTO, pfil_bridge, CTLFLAG_RW,
456     &pfil_bridge, 0, "Packet filter on the bridge interface");
457 SYSCTL_INT(_net_link_bridge, OID_AUTO, pfil_member, CTLFLAG_RW,
458     &pfil_member, 0, "Packet filter on the member interface");
459
460 struct bridge_control_arg {
461         union {
462                 struct ifbreq ifbreq;
463                 struct ifbifconf ifbifconf;
464                 struct ifbareq ifbareq;
465                 struct ifbaconf ifbaconf;
466                 struct ifbrparam ifbrparam;
467         } bca_u;
468         int     bca_len;
469         void    *bca_uptr;
470         void    *bca_kptr;
471 };
472
473 struct bridge_control {
474         bridge_ctl_t    bc_func;
475         int             bc_argsize;
476         int             bc_flags;
477 };
478
479 #define BC_F_COPYIN             0x01    /* copy arguments in */
480 #define BC_F_COPYOUT            0x02    /* copy arguments out */
481 #define BC_F_SUSER              0x04    /* do super-user check */
482
483 const struct bridge_control bridge_control_table[] = {
484         { bridge_ioctl_add,             sizeof(struct ifbreq),
485           BC_F_COPYIN|BC_F_SUSER },
486         { bridge_ioctl_del,             sizeof(struct ifbreq),
487           BC_F_COPYIN|BC_F_SUSER },
488
489         { bridge_ioctl_gifflags,        sizeof(struct ifbreq),
490           BC_F_COPYIN|BC_F_COPYOUT },
491         { bridge_ioctl_sifflags,        sizeof(struct ifbreq),
492           BC_F_COPYIN|BC_F_SUSER },
493
494         { bridge_ioctl_scache,          sizeof(struct ifbrparam),
495           BC_F_COPYIN|BC_F_SUSER },
496         { bridge_ioctl_gcache,          sizeof(struct ifbrparam),
497           BC_F_COPYOUT },
498
499         { bridge_ioctl_gifs,            sizeof(struct ifbifconf),
500           BC_F_COPYIN|BC_F_COPYOUT },
501         { bridge_ioctl_rts,             sizeof(struct ifbaconf),
502           BC_F_COPYIN|BC_F_COPYOUT },
503
504         { bridge_ioctl_saddr,           sizeof(struct ifbareq),
505           BC_F_COPYIN|BC_F_SUSER },
506
507         { bridge_ioctl_sto,             sizeof(struct ifbrparam),
508           BC_F_COPYIN|BC_F_SUSER },
509         { bridge_ioctl_gto,             sizeof(struct ifbrparam),
510           BC_F_COPYOUT },
511
512         { bridge_ioctl_daddr,           sizeof(struct ifbareq),
513           BC_F_COPYIN|BC_F_SUSER },
514
515         { bridge_ioctl_flush,           sizeof(struct ifbreq),
516           BC_F_COPYIN|BC_F_SUSER },
517
518         { bridge_ioctl_gpri,            sizeof(struct ifbrparam),
519           BC_F_COPYOUT },
520         { bridge_ioctl_spri,            sizeof(struct ifbrparam),
521           BC_F_COPYIN|BC_F_SUSER },
522
523         { bridge_ioctl_ght,             sizeof(struct ifbrparam),
524           BC_F_COPYOUT },
525         { bridge_ioctl_sht,             sizeof(struct ifbrparam),
526           BC_F_COPYIN|BC_F_SUSER },
527
528         { bridge_ioctl_gfd,             sizeof(struct ifbrparam),
529           BC_F_COPYOUT },
530         { bridge_ioctl_sfd,             sizeof(struct ifbrparam),
531           BC_F_COPYIN|BC_F_SUSER },
532
533         { bridge_ioctl_gma,             sizeof(struct ifbrparam),
534           BC_F_COPYOUT },
535         { bridge_ioctl_sma,             sizeof(struct ifbrparam),
536           BC_F_COPYIN|BC_F_SUSER },
537
538         { bridge_ioctl_sifprio,         sizeof(struct ifbreq),
539           BC_F_COPYIN|BC_F_SUSER },
540
541         { bridge_ioctl_sifcost,         sizeof(struct ifbreq),
542           BC_F_COPYIN|BC_F_SUSER },
543
544         { bridge_ioctl_addspan,         sizeof(struct ifbreq),
545           BC_F_COPYIN|BC_F_SUSER },
546         { bridge_ioctl_delspan,         sizeof(struct ifbreq),
547           BC_F_COPYIN|BC_F_SUSER },
548 };
549 static const int bridge_control_table_size =
550     sizeof(bridge_control_table) / sizeof(bridge_control_table[0]);
551
552 LIST_HEAD(, bridge_softc) bridge_list;
553
554 struct if_clone bridge_cloner = IF_CLONE_INITIALIZER("bridge",
555                                 bridge_clone_create,
556                                 bridge_clone_destroy, 0, IF_MAXUNIT);
557
558 static int
559 bridge_modevent(module_t mod, int type, void *data)
560 {
561         switch (type) {
562         case MOD_LOAD:
563                 LIST_INIT(&bridge_list);
564                 if_clone_attach(&bridge_cloner);
565                 bridge_input_p = bridge_input;
566                 bridge_output_p = bridge_output;
567                 bridge_detach_cookie = EVENTHANDLER_REGISTER(
568                     ifnet_detach_event, bridge_ifdetach, NULL,
569                     EVENTHANDLER_PRI_ANY);
570 #if notyet
571                 bstp_linkstate_p = bstp_linkstate;
572 #endif
573                 break;
574         case MOD_UNLOAD:
575                 if (!LIST_EMPTY(&bridge_list))
576                         return (EBUSY);
577                 EVENTHANDLER_DEREGISTER(ifnet_detach_event,
578                     bridge_detach_cookie);
579                 if_clone_detach(&bridge_cloner);
580                 bridge_input_p = NULL;
581                 bridge_output_p = NULL;
582 #if notyet
583                 bstp_linkstate_p = NULL;
584 #endif
585                 break;
586         default:
587                 return (EOPNOTSUPP);
588         }
589         return (0);
590 }
591
592 static moduledata_t bridge_mod = {
593         "if_bridge",
594         bridge_modevent,
595         0
596 };
597
598 DECLARE_MODULE(if_bridge, bridge_mod, SI_SUB_PSEUDO, SI_ORDER_ANY);
599
600
601 /*
602  * bridge_clone_create:
603  *
604  *      Create a new bridge instance.
605  */
606 static int
607 bridge_clone_create(struct if_clone *ifc, int unit)
608 {
609         struct bridge_softc *sc;
610         struct ifnet *ifp;
611         u_char eaddr[6];
612         int cpu;
613
614         sc = kmalloc(sizeof(*sc), M_DEVBUF, M_WAITOK | M_ZERO);
615         ifp = sc->sc_ifp = &sc->sc_if;
616
617         sc->sc_brtmax = BRIDGE_RTABLE_MAX;
618         sc->sc_brttimeout = BRIDGE_RTABLE_TIMEOUT;
619         sc->sc_bridge_max_age = BSTP_DEFAULT_MAX_AGE;
620         sc->sc_bridge_hello_time = BSTP_DEFAULT_HELLO_TIME;
621         sc->sc_bridge_forward_delay = BSTP_DEFAULT_FORWARD_DELAY;
622         sc->sc_bridge_priority = BSTP_DEFAULT_BRIDGE_PRIORITY;
623         sc->sc_hold_time = BSTP_DEFAULT_HOLD_TIME;
624
625         /* Initialize our routing table. */
626         bridge_rtable_init(sc);
627
628         callout_init(&sc->sc_brcallout);
629         netmsg_init(&sc->sc_brtimemsg, &netisr_adone_rport,
630                     MSGF_DROPABLE | MSGF_PRIORITY, bridge_timer_handler);
631         sc->sc_brtimemsg.nm_lmsg.u.ms_resultp = sc;
632
633         callout_init(&sc->sc_bstpcallout);
634         netmsg_init(&sc->sc_bstptimemsg, &netisr_adone_rport,
635                     MSGF_DROPABLE | MSGF_PRIORITY, bstp_tick_handler);
636         sc->sc_bstptimemsg.nm_lmsg.u.ms_resultp = sc;
637
638         /* Initialize per-cpu member iface lists */
639         sc->sc_iflists = kmalloc(sizeof(*sc->sc_iflists) * ncpus,
640                                  M_DEVBUF, M_WAITOK);
641         for (cpu = 0; cpu < ncpus; ++cpu)
642                 LIST_INIT(&sc->sc_iflists[cpu]);
643
644         LIST_INIT(&sc->sc_spanlist);
645
646         ifp->if_softc = sc;
647         if_initname(ifp, ifc->ifc_name, unit);
648         ifp->if_mtu = ETHERMTU;
649         ifp->if_flags = IFF_BROADCAST | IFF_MULTICAST;
650         ifp->if_ioctl = bridge_ioctl;
651         ifp->if_start = bridge_start;
652         ifp->if_init = bridge_init;
653         ifp->if_type = IFT_BRIDGE;
654         ifq_set_maxlen(&ifp->if_snd, ifqmaxlen);
655         ifp->if_snd.ifq_maxlen = ifqmaxlen;
656         ifq_set_ready(&ifp->if_snd);
657         ifp->if_hdrlen = ETHER_HDR_LEN;
658
659         /*
660          * Generate a random ethernet address and use the private AC:DE:48
661          * OUI code.
662          */
663         {
664                 int rnd = karc4random();
665                 bcopy(&rnd, &eaddr[0], 4); /* ETHER_ADDR_LEN == 6 */
666                 rnd = karc4random();
667                 bcopy(&rnd, &eaddr[2], 4); /* ETHER_ADDR_LEN == 6 */
668         }
669         eaddr[0] &= ~1;         /* clear multicast bit */
670         eaddr[0] |= 2;          /* set the LAA bit */
671
672         ether_ifattach(ifp, eaddr, NULL);
673         /* Now undo some of the damage... */
674         ifp->if_baudrate = 0;
675         ifp->if_type = IFT_BRIDGE;
676
677         crit_enter();   /* XXX MP */
678         LIST_INSERT_HEAD(&bridge_list, sc, sc_list);
679         crit_exit();
680
681         return (0);
682 }
683
684 static void
685 bridge_delete_dispatch(struct netmsg *nmsg)
686 {
687         struct lwkt_msg *lmsg = &nmsg->nm_lmsg;
688         struct bridge_softc *sc = lmsg->u.ms_resultp;
689         struct ifnet *bifp = sc->sc_ifp;
690         struct bridge_iflist *bif;
691
692         lwkt_serialize_enter(bifp->if_serializer);
693
694         while ((bif = LIST_FIRST(&sc->sc_iflists[mycpuid])) != NULL)
695                 bridge_delete_member(sc, bif, 0);
696
697         while ((bif = LIST_FIRST(&sc->sc_spanlist)) != NULL)
698                 bridge_delete_span(sc, bif);
699
700         lwkt_serialize_exit(bifp->if_serializer);
701
702         lwkt_replymsg(lmsg, 0);
703 }
704
705 /*
706  * bridge_clone_destroy:
707  *
708  *      Destroy a bridge instance.
709  */
710 static void
711 bridge_clone_destroy(struct ifnet *ifp)
712 {
713         struct bridge_softc *sc = ifp->if_softc;
714         struct lwkt_msg *lmsg;
715         struct netmsg nmsg;
716
717         lwkt_serialize_enter(ifp->if_serializer);
718
719         bridge_stop(ifp);
720         ifp->if_flags &= ~IFF_UP;
721
722         lwkt_serialize_exit(ifp->if_serializer);
723
724         netmsg_init(&nmsg, &curthread->td_msgport, 0, bridge_delete_dispatch);
725         lmsg = &nmsg.nm_lmsg;
726         lmsg->u.ms_resultp = sc;
727         lwkt_domsg(BRIDGE_CFGPORT, lmsg, 0);
728
729         crit_enter();   /* XXX MP */
730         LIST_REMOVE(sc, sc_list);
731         crit_exit();
732
733         ether_ifdetach(ifp);
734
735         /* Tear down the routing table. */
736         bridge_rtable_fini(sc);
737
738         /* Free per-cpu member iface lists */
739         kfree(sc->sc_iflists, M_DEVBUF);
740
741         kfree(sc, M_DEVBUF);
742 }
743
744 /*
745  * bridge_ioctl:
746  *
747  *      Handle a control request from the operator.
748  */
749 static int
750 bridge_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data, struct ucred *cr)
751 {
752         struct bridge_softc *sc = ifp->if_softc;
753         struct bridge_control_arg args;
754         struct ifdrv *ifd = (struct ifdrv *) data;
755         const struct bridge_control *bc;
756         int error = 0;
757
758         ASSERT_SERIALIZED(ifp->if_serializer);
759
760         switch (cmd) {
761         case SIOCADDMULTI:
762         case SIOCDELMULTI:
763                 break;
764
765         case SIOCGDRVSPEC:
766         case SIOCSDRVSPEC:
767                 if (ifd->ifd_cmd >= bridge_control_table_size) {
768                         error = EINVAL;
769                         break;
770                 }
771                 bc = &bridge_control_table[ifd->ifd_cmd];
772
773                 if (cmd == SIOCGDRVSPEC &&
774                     (bc->bc_flags & BC_F_COPYOUT) == 0) {
775                         error = EINVAL;
776                         break;
777                 } else if (cmd == SIOCSDRVSPEC &&
778                            (bc->bc_flags & BC_F_COPYOUT)) {
779                         error = EINVAL;
780                         break;
781                 }
782
783                 if (bc->bc_flags & BC_F_SUSER) {
784                         error = suser_cred(cr, NULL_CRED_OKAY);
785                         if (error)
786                                 break;
787                 }
788
789                 if (ifd->ifd_len != bc->bc_argsize ||
790                     ifd->ifd_len > sizeof(args.bca_u)) {
791                         error = EINVAL;
792                         break;
793                 }
794
795                 memset(&args, 0, sizeof(args));
796                 if (bc->bc_flags & BC_F_COPYIN) {
797                         error = copyin(ifd->ifd_data, &args.bca_u,
798                                        ifd->ifd_len);
799                         if (error)
800                                 break;
801                 }
802
803                 error = bridge_control(sc, cmd, bc->bc_func, &args);
804                 if (error) {
805                         KKASSERT(args.bca_len == 0 && args.bca_kptr == NULL);
806                         break;
807                 }
808
809                 if (bc->bc_flags & BC_F_COPYOUT) {
810                         error = copyout(&args, ifd->ifd_data, ifd->ifd_len);
811                         if (args.bca_len != 0) {
812                                 KKASSERT(args.bca_kptr != NULL);
813                                 if (!error) {
814                                         error = copyout(args.bca_kptr,
815                                                 args.bca_uptr, args.bca_len);
816                                 }
817                                 kfree(args.bca_kptr, M_TEMP);
818                         } else {
819                                 KKASSERT(args.bca_kptr == NULL);
820                         }
821                 } else {
822                         KKASSERT(args.bca_len == 0 && args.bca_kptr == NULL);
823                 }
824                 break;
825
826         case SIOCSIFFLAGS:
827                 if (!(ifp->if_flags & IFF_UP) &&
828                     (ifp->if_flags & IFF_RUNNING)) {
829                         /*
830                          * If interface is marked down and it is running,
831                          * then stop it.
832                          */
833                         bridge_stop(ifp);
834                 } else if ((ifp->if_flags & IFF_UP) &&
835                     !(ifp->if_flags & IFF_RUNNING)) {
836                         /*
837                          * If interface is marked up and it is stopped, then
838                          * start it.
839                          */
840                         ifp->if_init(sc);
841                 }
842                 break;
843
844         case SIOCSIFMTU:
845                 /* Do not allow the MTU to be changed on the bridge */
846                 error = EINVAL;
847                 break;
848
849         default:
850                 error = ether_ioctl(ifp, cmd, data);
851                 break;
852         }
853         return (error);
854 }
855
856 /*
857  * bridge_mutecaps:
858  *
859  *      Clear or restore unwanted capabilities on the member interface
860  */
861 static void
862 bridge_mutecaps(struct bridge_ifinfo *bif_info, struct ifnet *ifp, int mute)
863 {
864         struct ifreq ifr;
865         int error;
866
867         if (ifp->if_ioctl == NULL)
868                 return;
869
870         bzero(&ifr, sizeof(ifr));
871         ifr.ifr_reqcap = ifp->if_capenable;
872
873         if (mute) {
874                 /* mask off and save capabilities */
875                 bif_info->bifi_mutecap = ifr.ifr_reqcap & BRIDGE_IFCAPS_MASK;
876                 if (bif_info->bifi_mutecap != 0)
877                         ifr.ifr_reqcap &= ~BRIDGE_IFCAPS_MASK;
878         } else {
879                 /* restore muted capabilities */
880                 ifr.ifr_reqcap |= bif_info->bifi_mutecap;
881         }
882
883         if (bif_info->bifi_mutecap != 0) {
884                 lwkt_serialize_enter(ifp->if_serializer);
885                 error = ifp->if_ioctl(ifp, SIOCSIFCAP, (caddr_t)&ifr, NULL);
886                 lwkt_serialize_exit(ifp->if_serializer);
887         }
888 }
889
890 /*
891  * bridge_lookup_member:
892  *
893  *      Lookup a bridge member interface.
894  */
895 static struct bridge_iflist *
896 bridge_lookup_member(struct bridge_softc *sc, const char *name)
897 {
898         struct bridge_iflist *bif;
899
900         LIST_FOREACH(bif, &sc->sc_iflists[mycpuid], bif_next) {
901                 if (strcmp(bif->bif_ifp->if_xname, name) == 0)
902                         return (bif);
903         }
904         return (NULL);
905 }
906
907 /*
908  * bridge_lookup_member_if:
909  *
910  *      Lookup a bridge member interface by ifnet*.
911  */
912 static struct bridge_iflist *
913 bridge_lookup_member_if(struct bridge_softc *sc, struct ifnet *member_ifp)
914 {
915         struct bridge_iflist *bif;
916
917         LIST_FOREACH(bif, &sc->sc_iflists[mycpuid], bif_next) {
918                 if (bif->bif_ifp == member_ifp)
919                         return (bif);
920         }
921         return (NULL);
922 }
923
924 /*
925  * bridge_lookup_member_ifinfo:
926  *
927  *      Lookup a bridge member interface by bridge_ifinfo.
928  */
929 static struct bridge_iflist *
930 bridge_lookup_member_ifinfo(struct bridge_softc *sc,
931                             struct bridge_ifinfo *bif_info)
932 {
933         struct bridge_iflist *bif;
934
935         LIST_FOREACH(bif, &sc->sc_iflists[mycpuid], bif_next) {
936                 if (bif->bif_info == bif_info)
937                         return (bif);
938         }
939         return (NULL);
940 }
941
942 /*
943  * bridge_delete_member:
944  *
945  *      Delete the specified member interface.
946  */
947 static void
948 bridge_delete_member(struct bridge_softc *sc, struct bridge_iflist *bif,
949     int gone)
950 {
951         struct ifnet *ifs = bif->bif_ifp;
952         struct ifnet *bifp = sc->sc_ifp;
953         struct bridge_ifinfo *bif_info = bif->bif_info;
954         struct bridge_iflist_head saved_bifs;
955
956         ASSERT_SERIALIZED(bifp->if_serializer);
957         KKASSERT(bif_info != NULL);
958
959         ifs->if_bridge = NULL;
960
961         /*
962          * Release bridge interface's serializer:
963          * - To avoid possible dead lock.
964          * - Various sync operation will block the current thread.
965          */
966         lwkt_serialize_exit(bifp->if_serializer);
967
968         if (!gone) {
969                 switch (ifs->if_type) {
970                 case IFT_ETHER:
971                 case IFT_L2VLAN:
972                         /*
973                          * Take the interface out of promiscuous mode.
974                          */
975                         ifpromisc(ifs, 0);
976                         bridge_mutecaps(bif_info, ifs, 0);
977                         break;
978
979                 case IFT_GIF:
980                         break;
981
982                 default:
983                         panic("bridge_delete_member: impossible");
984                         break;
985                 }
986         }
987
988         /*
989          * Remove bifs from percpu linked list.
990          *
991          * Removed bifs are not freed immediately, instead,
992          * they are saved in saved_bifs.  They will be freed
993          * after we make sure that no one is accessing them,
994          * i.e. after following netmsg_service_sync()
995          */
996         LIST_INIT(&saved_bifs);
997         bridge_del_bif(sc, bif_info, &saved_bifs);
998
999         /*
1000          * Make sure that all protocol threads:
1001          * o  see 'ifs' if_bridge is changed
1002          * o  know that bif is removed from the percpu linked list
1003          */
1004         netmsg_service_sync();
1005
1006         /*
1007          * Free the removed bifs
1008          */
1009         KKASSERT(!LIST_EMPTY(&saved_bifs));
1010         while ((bif = LIST_FIRST(&saved_bifs)) != NULL) {
1011                 LIST_REMOVE(bif, bif_next);
1012                 kfree(bif, M_DEVBUF);
1013         }
1014
1015         /* See the comment in bridge_ioctl_stop() */
1016         bridge_rtmsg_sync(sc);
1017         bridge_rtdelete(sc, ifs, IFBF_FLUSHALL);
1018
1019         lwkt_serialize_enter(bifp->if_serializer);
1020
1021         if (bifp->if_flags & IFF_RUNNING)
1022                 bstp_initialization(sc);
1023
1024         /*
1025          * Free the bif_info after bstp_initialization(), so that
1026          * bridge_softc.sc_root_port will not reference a dangling
1027          * pointer.
1028          */
1029         kfree(bif_info, M_DEVBUF);
1030 }
1031
1032 /*
1033  * bridge_delete_span:
1034  *
1035  *      Delete the specified span interface.
1036  */
1037 static void
1038 bridge_delete_span(struct bridge_softc *sc, struct bridge_iflist *bif)
1039 {
1040         KASSERT(bif->bif_ifp->if_bridge == NULL,
1041             ("%s: not a span interface", __func__));
1042
1043         LIST_REMOVE(bif, bif_next);
1044         kfree(bif, M_DEVBUF);
1045 }
1046
1047 static int
1048 bridge_ioctl_init(struct bridge_softc *sc, void *arg __unused)
1049 {
1050         struct ifnet *ifp = sc->sc_ifp;
1051
1052         if (ifp->if_flags & IFF_RUNNING)
1053                 return 0;
1054
1055         callout_reset(&sc->sc_brcallout, bridge_rtable_prune_period * hz,
1056             bridge_timer, sc);
1057
1058         ifp->if_flags |= IFF_RUNNING;
1059         bstp_initialization(sc);
1060         return 0;
1061 }
1062
1063 static int
1064 bridge_ioctl_stop(struct bridge_softc *sc, void *arg __unused)
1065 {
1066         struct ifnet *ifp = sc->sc_ifp;
1067         struct lwkt_msg *lmsg;
1068
1069         if ((ifp->if_flags & IFF_RUNNING) == 0)
1070                 return 0;
1071
1072         callout_stop(&sc->sc_brcallout);
1073
1074         crit_enter();
1075         lmsg = &sc->sc_brtimemsg.nm_lmsg;
1076         if ((lmsg->ms_flags & MSGF_DONE) == 0) {
1077                 /* Pending to be processed; drop it */
1078                 lwkt_dropmsg(lmsg);
1079         }
1080         crit_exit();
1081
1082         bstp_stop(sc);
1083
1084         ifp->if_flags &= ~IFF_RUNNING;
1085
1086         lwkt_serialize_exit(ifp->if_serializer);
1087
1088         /* Let everyone know that we are stopped */
1089         netmsg_service_sync();
1090
1091         /*
1092          * Sync ifnetX msgports in the order we forward rtnode
1093          * installation message.  This is used to make sure that
1094          * all rtnode installation messages sent by bridge_rtupdate()
1095          * during above netmsg_service_sync() are flushed.
1096          */
1097         bridge_rtmsg_sync(sc);
1098         bridge_rtflush(sc, IFBF_FLUSHDYN);
1099
1100         lwkt_serialize_enter(ifp->if_serializer);
1101         return 0;
1102 }
1103
1104 static int
1105 bridge_ioctl_add(struct bridge_softc *sc, void *arg)
1106 {
1107         struct ifbreq *req = arg;
1108         struct bridge_iflist *bif;
1109         struct bridge_ifinfo *bif_info;
1110         struct ifnet *ifs, *bifp;
1111         int error = 0;
1112
1113         bifp = sc->sc_ifp;
1114         ASSERT_SERIALIZED(bifp->if_serializer);
1115
1116         ifs = ifunit(req->ifbr_ifsname);
1117         if (ifs == NULL)
1118                 return (ENOENT);
1119
1120         /* If it's in the span list, it can't be a member. */
1121         LIST_FOREACH(bif, &sc->sc_spanlist, bif_next)
1122                 if (ifs == bif->bif_ifp)
1123                         return (EBUSY);
1124
1125         /* Allow the first Ethernet member to define the MTU */
1126         if (ifs->if_type != IFT_GIF) {
1127                 if (LIST_EMPTY(&sc->sc_iflists[mycpuid])) {
1128                         bifp->if_mtu = ifs->if_mtu;
1129                 } else if (bifp->if_mtu != ifs->if_mtu) {
1130                         if_printf(bifp, "invalid MTU for %s\n", ifs->if_xname);
1131                         return (EINVAL);
1132                 }
1133         }
1134
1135         if (ifs->if_bridge == sc)
1136                 return (EEXIST);
1137
1138         if (ifs->if_bridge != NULL)
1139                 return (EBUSY);
1140
1141         bif_info = kmalloc(sizeof(*bif_info), M_DEVBUF, M_WAITOK | M_ZERO);
1142         bif_info->bifi_priority = BSTP_DEFAULT_PORT_PRIORITY;
1143         bif_info->bifi_path_cost = BSTP_DEFAULT_PATH_COST;
1144         bif_info->bifi_ifp = ifs;
1145
1146         /*
1147          * Release bridge interface's serializer:
1148          * - To avoid possible dead lock.
1149          * - Various sync operation will block the current thread.
1150          */
1151         lwkt_serialize_exit(bifp->if_serializer);
1152
1153         switch (ifs->if_type) {
1154         case IFT_ETHER:
1155         case IFT_L2VLAN:
1156                 /*
1157                  * Place the interface into promiscuous mode.
1158                  */
1159                 error = ifpromisc(ifs, 1);
1160                 if (error) {
1161                         lwkt_serialize_enter(bifp->if_serializer);
1162                         goto out;
1163                 }
1164                 bridge_mutecaps(bif_info, ifs, 1);
1165                 break;
1166
1167         case IFT_GIF: /* :^) */
1168                 break;
1169
1170         default:
1171                 error = EINVAL;
1172                 lwkt_serialize_enter(bifp->if_serializer);
1173                 goto out;
1174         }
1175
1176         /*
1177          * Add bifs to percpu linked lists
1178          */
1179         bridge_add_bif(sc, bif_info, ifs);
1180
1181         lwkt_serialize_enter(bifp->if_serializer);
1182
1183         if (bifp->if_flags & IFF_RUNNING)
1184                 bstp_initialization(sc);
1185         else
1186                 bstp_stop(sc);
1187
1188         /*
1189          * Everything has been setup, so let the member interface
1190          * deliver packets to this bridge on its input/output path.
1191          */
1192         ifs->if_bridge = sc;
1193 out:
1194         if (error) {
1195                 if (bif_info != NULL)
1196                         kfree(bif_info, M_DEVBUF);
1197         }
1198         return (error);
1199 }
1200
1201 static int
1202 bridge_ioctl_del(struct bridge_softc *sc, void *arg)
1203 {
1204         struct ifbreq *req = arg;
1205         struct bridge_iflist *bif;
1206
1207         bif = bridge_lookup_member(sc, req->ifbr_ifsname);
1208         if (bif == NULL)
1209                 return (ENOENT);
1210
1211         bridge_delete_member(sc, bif, 0);
1212
1213         return (0);
1214 }
1215
1216 static int
1217 bridge_ioctl_gifflags(struct bridge_softc *sc, void *arg)
1218 {
1219         struct ifbreq *req = arg;
1220         struct bridge_iflist *bif;
1221
1222         bif = bridge_lookup_member(sc, req->ifbr_ifsname);
1223         if (bif == NULL)
1224                 return (ENOENT);
1225
1226         req->ifbr_ifsflags = bif->bif_flags;
1227         req->ifbr_state = bif->bif_state;
1228         req->ifbr_priority = bif->bif_priority;
1229         req->ifbr_path_cost = bif->bif_path_cost;
1230         req->ifbr_portno = bif->bif_ifp->if_index & 0xff;
1231
1232         return (0);
1233 }
1234
1235 static int
1236 bridge_ioctl_sifflags(struct bridge_softc *sc, void *arg)
1237 {
1238         struct ifbreq *req = arg;
1239         struct bridge_iflist *bif;
1240         struct ifnet *bifp = sc->sc_ifp;
1241
1242         bif = bridge_lookup_member(sc, req->ifbr_ifsname);
1243         if (bif == NULL)
1244                 return (ENOENT);
1245
1246         if (req->ifbr_ifsflags & IFBIF_SPAN) {
1247                 /* SPAN is readonly */
1248                 return (EINVAL);
1249         }
1250
1251         if (req->ifbr_ifsflags & IFBIF_STP) {
1252                 switch (bif->bif_ifp->if_type) {
1253                 case IFT_ETHER:
1254                         /* These can do spanning tree. */
1255                         break;
1256
1257                 default:
1258                         /* Nothing else can. */
1259                         return (EINVAL);
1260                 }
1261         }
1262
1263         lwkt_serialize_exit(bifp->if_serializer);
1264         bridge_set_bifflags(sc, bif->bif_info, req->ifbr_ifsflags);
1265         lwkt_serialize_enter(bifp->if_serializer);
1266
1267         if (bifp->if_flags & IFF_RUNNING)
1268                 bstp_initialization(sc);
1269
1270         return (0);
1271 }
1272
1273 static int
1274 bridge_ioctl_scache(struct bridge_softc *sc, void *arg)
1275 {
1276         struct ifbrparam *param = arg;
1277         struct ifnet *ifp = sc->sc_ifp;
1278
1279         sc->sc_brtmax = param->ifbrp_csize;
1280
1281         lwkt_serialize_exit(ifp->if_serializer);
1282         bridge_rttrim(sc);
1283         lwkt_serialize_enter(ifp->if_serializer);
1284
1285         return (0);
1286 }
1287
1288 static int
1289 bridge_ioctl_gcache(struct bridge_softc *sc, void *arg)
1290 {
1291         struct ifbrparam *param = arg;
1292
1293         param->ifbrp_csize = sc->sc_brtmax;
1294
1295         return (0);
1296 }
1297
1298 static int
1299 bridge_ioctl_gifs(struct bridge_softc *sc, void *arg)
1300 {
1301         struct bridge_control_arg *bc_arg = arg;
1302         struct ifbifconf *bifc = arg;
1303         struct bridge_iflist *bif;
1304         struct ifbreq *breq;
1305         int count, len;
1306
1307         count = 0;
1308         LIST_FOREACH(bif, &sc->sc_iflists[mycpuid], bif_next)
1309                 count++;
1310         LIST_FOREACH(bif, &sc->sc_spanlist, bif_next)
1311                 count++;
1312
1313         if (bifc->ifbic_len == 0) {
1314                 bifc->ifbic_len = sizeof(*breq) * count;
1315                 return 0;
1316         } else if (count == 0 || bifc->ifbic_len < sizeof(*breq)) {
1317                 bifc->ifbic_len = 0;
1318                 return 0;
1319         }
1320
1321         len = min(bifc->ifbic_len, sizeof(*breq) * count);
1322         KKASSERT(len >= sizeof(*breq));
1323
1324         breq = kmalloc(len, M_TEMP, M_INTWAIT | M_NULLOK | M_ZERO);
1325         if (breq == NULL) {
1326                 bifc->ifbic_len = 0;
1327                 return ENOMEM;
1328         }
1329         bc_arg->bca_kptr = breq;
1330
1331         count = 0;
1332         LIST_FOREACH(bif, &sc->sc_iflists[mycpuid], bif_next) {
1333                 if (len < sizeof(*breq))
1334                         break;
1335
1336                 strlcpy(breq->ifbr_ifsname, bif->bif_ifp->if_xname,
1337                         sizeof(breq->ifbr_ifsname));
1338                 breq->ifbr_ifsflags = bif->bif_flags;
1339                 breq->ifbr_state = bif->bif_state;
1340                 breq->ifbr_priority = bif->bif_priority;
1341                 breq->ifbr_path_cost = bif->bif_path_cost;
1342                 breq->ifbr_portno = bif->bif_ifp->if_index & 0xff;
1343                 breq++;
1344                 count++;
1345                 len -= sizeof(*breq);
1346         }
1347         LIST_FOREACH(bif, &sc->sc_spanlist, bif_next) {
1348                 if (len < sizeof(*breq))
1349                         break;
1350
1351                 strlcpy(breq->ifbr_ifsname, bif->bif_ifp->if_xname,
1352                         sizeof(breq->ifbr_ifsname));
1353                 breq->ifbr_ifsflags = bif->bif_flags;
1354                 breq->ifbr_portno = bif->bif_ifp->if_index & 0xff;
1355                 breq++;
1356                 count++;
1357                 len -= sizeof(*breq);
1358         }
1359
1360         bifc->ifbic_len = sizeof(*breq) * count;
1361         KKASSERT(bifc->ifbic_len > 0);
1362
1363         bc_arg->bca_len = bifc->ifbic_len;
1364         bc_arg->bca_uptr = bifc->ifbic_req;
1365         return 0;
1366 }
1367
1368 static int
1369 bridge_ioctl_rts(struct bridge_softc *sc, void *arg)
1370 {
1371         struct bridge_control_arg *bc_arg = arg;
1372         struct ifbaconf *bac = arg;
1373         struct bridge_rtnode *brt;
1374         struct ifbareq *bareq;
1375         int count, len;
1376
1377         count = 0;
1378         LIST_FOREACH(brt, &sc->sc_rtlists[mycpuid], brt_list)
1379                 count++;
1380
1381         if (bac->ifbac_len == 0) {
1382                 bac->ifbac_len = sizeof(*bareq) * count;
1383                 return 0;
1384         } else if (count == 0 || bac->ifbac_len < sizeof(*bareq)) {
1385                 bac->ifbac_len = 0;
1386                 return 0;
1387         }
1388
1389         len = min(bac->ifbac_len, sizeof(*bareq) * count);
1390         KKASSERT(len >= sizeof(*bareq));
1391
1392         bareq = kmalloc(len, M_TEMP, M_INTWAIT | M_NULLOK | M_ZERO);
1393         if (bareq == NULL) {
1394                 bac->ifbac_len = 0;
1395                 return ENOMEM;
1396         }
1397         bc_arg->bca_kptr = bareq;
1398
1399         count = 0;
1400         LIST_FOREACH(brt, &sc->sc_rtlists[mycpuid], brt_list) {
1401                 struct bridge_rtinfo *bri = brt->brt_info;
1402                 unsigned long expire;
1403
1404                 if (len < sizeof(*bareq))
1405                         break;
1406
1407                 strlcpy(bareq->ifba_ifsname, bri->bri_ifp->if_xname,
1408                         sizeof(bareq->ifba_ifsname));
1409                 memcpy(bareq->ifba_dst, brt->brt_addr, sizeof(brt->brt_addr));
1410                 expire = bri->bri_expire;
1411                 if ((bri->bri_flags & IFBAF_TYPEMASK) == IFBAF_DYNAMIC &&
1412                     time_second < expire)
1413                         bareq->ifba_expire = expire - time_second;
1414                 else
1415                         bareq->ifba_expire = 0;
1416                 bareq->ifba_flags = bri->bri_flags;
1417                 bareq++;
1418                 count++;
1419                 len -= sizeof(*bareq);
1420         }
1421
1422         bac->ifbac_len = sizeof(*bareq) * count;
1423         KKASSERT(bac->ifbac_len > 0);
1424
1425         bc_arg->bca_len = bac->ifbac_len;
1426         bc_arg->bca_uptr = bac->ifbac_req;
1427         return 0;
1428 }
1429
1430 static int
1431 bridge_ioctl_saddr(struct bridge_softc *sc, void *arg)
1432 {
1433         struct ifbareq *req = arg;
1434         struct bridge_iflist *bif;
1435         struct ifnet *ifp = sc->sc_ifp;
1436         int error;
1437
1438         ASSERT_SERIALIZED(ifp->if_serializer);
1439
1440         bif = bridge_lookup_member(sc, req->ifba_ifsname);
1441         if (bif == NULL)
1442                 return (ENOENT);
1443
1444         lwkt_serialize_exit(ifp->if_serializer);
1445         error = bridge_rtsaddr(sc, req->ifba_dst, bif->bif_ifp,
1446                                req->ifba_flags);
1447         lwkt_serialize_enter(ifp->if_serializer);
1448         return (error);
1449 }
1450
1451 static int
1452 bridge_ioctl_sto(struct bridge_softc *sc, void *arg)
1453 {
1454         struct ifbrparam *param = arg;
1455
1456         sc->sc_brttimeout = param->ifbrp_ctime;
1457
1458         return (0);
1459 }
1460
1461 static int
1462 bridge_ioctl_gto(struct bridge_softc *sc, void *arg)
1463 {
1464         struct ifbrparam *param = arg;
1465
1466         param->ifbrp_ctime = sc->sc_brttimeout;
1467
1468         return (0);
1469 }
1470
1471 static int
1472 bridge_ioctl_daddr(struct bridge_softc *sc, void *arg)
1473 {
1474         struct ifbareq *req = arg;
1475         struct ifnet *ifp = sc->sc_ifp;
1476         int error;
1477
1478         lwkt_serialize_exit(ifp->if_serializer);
1479         error = bridge_rtdaddr(sc, req->ifba_dst);
1480         lwkt_serialize_enter(ifp->if_serializer);
1481         return error;
1482 }
1483
1484 static int
1485 bridge_ioctl_flush(struct bridge_softc *sc, void *arg)
1486 {
1487         struct ifbreq *req = arg;
1488         struct ifnet *ifp = sc->sc_ifp;
1489
1490         lwkt_serialize_exit(ifp->if_serializer);
1491         bridge_rtflush(sc, req->ifbr_ifsflags);
1492         lwkt_serialize_enter(ifp->if_serializer);
1493
1494         return (0);
1495 }
1496
1497 static int
1498 bridge_ioctl_gpri(struct bridge_softc *sc, void *arg)
1499 {
1500         struct ifbrparam *param = arg;
1501
1502         param->ifbrp_prio = sc->sc_bridge_priority;
1503
1504         return (0);
1505 }
1506
1507 static int
1508 bridge_ioctl_spri(struct bridge_softc *sc, void *arg)
1509 {
1510         struct ifbrparam *param = arg;
1511
1512         sc->sc_bridge_priority = param->ifbrp_prio;
1513
1514         if (sc->sc_ifp->if_flags & IFF_RUNNING)
1515                 bstp_initialization(sc);
1516
1517         return (0);
1518 }
1519
1520 static int
1521 bridge_ioctl_ght(struct bridge_softc *sc, void *arg)
1522 {
1523         struct ifbrparam *param = arg;
1524
1525         param->ifbrp_hellotime = sc->sc_bridge_hello_time >> 8;
1526
1527         return (0);
1528 }
1529
1530 static int
1531 bridge_ioctl_sht(struct bridge_softc *sc, void *arg)
1532 {
1533         struct ifbrparam *param = arg;
1534
1535         if (param->ifbrp_hellotime == 0)
1536                 return (EINVAL);
1537         sc->sc_bridge_hello_time = param->ifbrp_hellotime << 8;
1538
1539         if (sc->sc_ifp->if_flags & IFF_RUNNING)
1540                 bstp_initialization(sc);
1541
1542         return (0);
1543 }
1544
1545 static int
1546 bridge_ioctl_gfd(struct bridge_softc *sc, void *arg)
1547 {
1548         struct ifbrparam *param = arg;
1549
1550         param->ifbrp_fwddelay = sc->sc_bridge_forward_delay >> 8;
1551
1552         return (0);
1553 }
1554
1555 static int
1556 bridge_ioctl_sfd(struct bridge_softc *sc, void *arg)
1557 {
1558         struct ifbrparam *param = arg;
1559
1560         if (param->ifbrp_fwddelay == 0)
1561                 return (EINVAL);
1562         sc->sc_bridge_forward_delay = param->ifbrp_fwddelay << 8;
1563
1564         if (sc->sc_ifp->if_flags & IFF_RUNNING)
1565                 bstp_initialization(sc);
1566
1567         return (0);
1568 }
1569
1570 static int
1571 bridge_ioctl_gma(struct bridge_softc *sc, void *arg)
1572 {
1573         struct ifbrparam *param = arg;
1574
1575         param->ifbrp_maxage = sc->sc_bridge_max_age >> 8;
1576
1577         return (0);
1578 }
1579
1580 static int
1581 bridge_ioctl_sma(struct bridge_softc *sc, void *arg)
1582 {
1583         struct ifbrparam *param = arg;
1584
1585         if (param->ifbrp_maxage == 0)
1586                 return (EINVAL);
1587         sc->sc_bridge_max_age = param->ifbrp_maxage << 8;
1588
1589         if (sc->sc_ifp->if_flags & IFF_RUNNING)
1590                 bstp_initialization(sc);
1591
1592         return (0);
1593 }
1594
1595 static int
1596 bridge_ioctl_sifprio(struct bridge_softc *sc, void *arg)
1597 {
1598         struct ifbreq *req = arg;
1599         struct bridge_iflist *bif;
1600
1601         bif = bridge_lookup_member(sc, req->ifbr_ifsname);
1602         if (bif == NULL)
1603                 return (ENOENT);
1604
1605         bif->bif_priority = req->ifbr_priority;
1606
1607         if (sc->sc_ifp->if_flags & IFF_RUNNING)
1608                 bstp_initialization(sc);
1609
1610         return (0);
1611 }
1612
1613 static int
1614 bridge_ioctl_sifcost(struct bridge_softc *sc, void *arg)
1615 {
1616         struct ifbreq *req = arg;
1617         struct bridge_iflist *bif;
1618
1619         bif = bridge_lookup_member(sc, req->ifbr_ifsname);
1620         if (bif == NULL)
1621                 return (ENOENT);
1622
1623         bif->bif_path_cost = req->ifbr_path_cost;
1624
1625         if (sc->sc_ifp->if_flags & IFF_RUNNING)
1626                 bstp_initialization(sc);
1627
1628         return (0);
1629 }
1630
1631 static int
1632 bridge_ioctl_addspan(struct bridge_softc *sc, void *arg)
1633 {
1634         struct ifbreq *req = arg;
1635         struct bridge_iflist *bif;
1636         struct ifnet *ifs;
1637
1638         ifs = ifunit(req->ifbr_ifsname);
1639         if (ifs == NULL)
1640                 return (ENOENT);
1641
1642         LIST_FOREACH(bif, &sc->sc_spanlist, bif_next)
1643                 if (ifs == bif->bif_ifp)
1644                         return (EBUSY);
1645
1646         if (ifs->if_bridge != NULL)
1647                 return (EBUSY);
1648
1649         switch (ifs->if_type) {
1650                 case IFT_ETHER:
1651                 case IFT_GIF:
1652                 case IFT_L2VLAN:
1653                         break;
1654                 default:
1655                         return (EINVAL);
1656         }
1657
1658         bif = kmalloc(sizeof(*bif), M_DEVBUF, M_WAITOK | M_ZERO);
1659         bif->bif_ifp = ifs;
1660         bif->bif_flags = IFBIF_SPAN;
1661         /* NOTE: span bif does not need bridge_ifinfo */
1662
1663         LIST_INSERT_HEAD(&sc->sc_spanlist, bif, bif_next);
1664
1665         return (0);
1666 }
1667
1668 static int
1669 bridge_ioctl_delspan(struct bridge_softc *sc, void *arg)
1670 {
1671         struct ifbreq *req = arg;
1672         struct bridge_iflist *bif;
1673         struct ifnet *ifs;
1674
1675         ifs = ifunit(req->ifbr_ifsname);
1676         if (ifs == NULL)
1677                 return (ENOENT);
1678
1679         LIST_FOREACH(bif, &sc->sc_spanlist, bif_next)
1680                 if (ifs == bif->bif_ifp)
1681                         break;
1682
1683         if (bif == NULL)
1684                 return (ENOENT);
1685
1686         bridge_delete_span(sc, bif);
1687
1688         return (0);
1689 }
1690
1691 static void
1692 bridge_ifdetach_dispatch(struct netmsg *nmsg)
1693 {
1694         struct lwkt_msg *lmsg = &nmsg->nm_lmsg;
1695         struct ifnet *ifp, *bifp;
1696         struct bridge_softc *sc;
1697         struct bridge_iflist *bif;
1698
1699         ifp = lmsg->u.ms_resultp;
1700         sc = ifp->if_bridge;
1701
1702         /* Check if the interface is a bridge member */
1703         if (sc != NULL) {
1704                 bifp = sc->sc_ifp;
1705
1706                 lwkt_serialize_enter(bifp->if_serializer);
1707
1708                 bif = bridge_lookup_member_if(sc, ifp);
1709                 if (bif != NULL) {
1710                         bridge_delete_member(sc, bif, 1);
1711                 } else {
1712                         /* XXX Why bif will be NULL? */
1713                 }
1714
1715                 lwkt_serialize_exit(bifp->if_serializer);
1716                 goto reply;
1717         }
1718
1719         crit_enter();   /* XXX MP */
1720
1721         /* Check if the interface is a span port */
1722         LIST_FOREACH(sc, &bridge_list, sc_list) {
1723                 bifp = sc->sc_ifp;
1724
1725                 lwkt_serialize_enter(bifp->if_serializer);
1726
1727                 LIST_FOREACH(bif, &sc->sc_spanlist, bif_next)
1728                         if (ifp == bif->bif_ifp) {
1729                                 bridge_delete_span(sc, bif);
1730                                 break;
1731                         }
1732
1733                 lwkt_serialize_exit(bifp->if_serializer);
1734         }
1735
1736         crit_exit();
1737
1738 reply:
1739         lwkt_replymsg(lmsg, 0);
1740 }
1741
1742 /*
1743  * bridge_ifdetach:
1744  *
1745  *      Detach an interface from a bridge.  Called when a member
1746  *      interface is detaching.
1747  */
1748 static void
1749 bridge_ifdetach(void *arg __unused, struct ifnet *ifp)
1750 {
1751         struct lwkt_msg *lmsg;
1752         struct netmsg nmsg;
1753
1754         netmsg_init(&nmsg, &curthread->td_msgport, 0, bridge_ifdetach_dispatch);
1755         lmsg = &nmsg.nm_lmsg;
1756         lmsg->u.ms_resultp = ifp;
1757
1758         lwkt_domsg(BRIDGE_CFGPORT, lmsg, 0);
1759 }
1760
1761 /*
1762  * bridge_init:
1763  *
1764  *      Initialize a bridge interface.
1765  */
1766 static void
1767 bridge_init(void *xsc)
1768 {
1769         bridge_control(xsc, SIOCSIFFLAGS, bridge_ioctl_init, NULL);
1770 }
1771
1772 /*
1773  * bridge_stop:
1774  *
1775  *      Stop the bridge interface.
1776  */
1777 static void
1778 bridge_stop(struct ifnet *ifp)
1779 {
1780         bridge_control(ifp->if_softc, SIOCSIFFLAGS, bridge_ioctl_stop, NULL);
1781 }
1782
1783 static void
1784 bridge_enqueue_internal(struct ifnet *dst_ifp, struct mbuf *m,
1785                         netisr_fn_t handler)
1786 {
1787         struct netmsg_packet *nmp;
1788         lwkt_port_t port;
1789         int cpu = mycpu->gd_cpuid;
1790
1791         nmp = &m->m_hdr.mh_netmsg;
1792         netmsg_init(&nmp->nm_netmsg, &netisr_apanic_rport, 0, handler);
1793         nmp->nm_packet = m;
1794         nmp->nm_netmsg.nm_lmsg.u.ms_resultp = dst_ifp;
1795
1796         port = cpu_portfn(cpu);
1797         lwkt_sendmsg(port, &nmp->nm_netmsg.nm_lmsg);
1798 }
1799
1800 static void
1801 bridge_pfil_enqueue(struct ifnet *dst_ifp, struct mbuf *m,
1802                     int runfilt)
1803 {
1804         netisr_fn_t handler;
1805
1806         if (runfilt && (inet_pfil_hook.ph_hashooks > 0
1807 #ifdef INET6
1808             || inet6_pfil_hook.ph_hashooks > 0
1809 #endif
1810             )) {
1811                 handler = bridge_pfil_enqueue_handler;
1812         } else {
1813                 handler = bridge_enqueue_handler;
1814         }
1815         bridge_enqueue_internal(dst_ifp, m, handler);
1816 }
1817
1818 /*
1819  * bridge_enqueue:
1820  *
1821  *      Enqueue a packet on a bridge member interface.
1822  *
1823  */
1824 void
1825 bridge_enqueue(struct ifnet *dst_ifp, struct mbuf *m)
1826 {
1827         bridge_enqueue_internal(dst_ifp, m, bridge_enqueue_handler);
1828 }
1829
1830 /*
1831  * bridge_output:
1832  *
1833  *      Send output from a bridge member interface.  This
1834  *      performs the bridging function for locally originated
1835  *      packets.
1836  *
1837  *      The mbuf has the Ethernet header already attached.  We must
1838  *      enqueue or free the mbuf before returning.
1839  */
1840 static int
1841 bridge_output(struct ifnet *ifp, struct mbuf *m)
1842 {
1843         struct bridge_softc *sc = ifp->if_bridge;
1844         struct ether_header *eh;
1845         struct ifnet *dst_if;
1846
1847         ASSERT_NOT_SERIALIZED(ifp->if_serializer);
1848
1849         /*
1850          * Make sure that we are still a member of a bridge interface.
1851          */
1852         if (sc == NULL) {
1853                 m_freem(m);
1854                 return (0);
1855         }
1856
1857         if (m->m_len < ETHER_HDR_LEN) {
1858                 m = m_pullup(m, ETHER_HDR_LEN);
1859                 if (m == NULL)
1860                         return (0);
1861         }
1862
1863         /* Serialize our bridge interface. */
1864         lwkt_serialize_enter(sc->sc_ifp->if_serializer);
1865
1866         eh = mtod(m, struct ether_header *);
1867
1868         /*
1869          * If bridge is down, but the original output interface is up,
1870          * go ahead and send out that interface.  Otherwise, the packet
1871          * is dropped below.
1872          */
1873         if ((sc->sc_ifp->if_flags & IFF_RUNNING) == 0) {
1874                 dst_if = ifp;
1875                 goto sendunicast;
1876         }
1877
1878         /*
1879          * If the packet is a multicast, or we don't know a better way to
1880          * get there, send to all interfaces.
1881          */
1882         if (ETHER_IS_MULTICAST(eh->ether_dhost))
1883                 dst_if = NULL;
1884         else
1885                 dst_if = bridge_rtlookup(sc, eh->ether_dhost);
1886         if (dst_if == NULL) {
1887                 struct bridge_iflist *bif;
1888                 struct mbuf *mc;
1889                 int used = 0;
1890
1891                 bridge_span(sc, m);
1892
1893                 /*
1894                  * Following loop is MPSAFE; nothing is blocking
1895                  * in the loop body.
1896                  */
1897                 LIST_FOREACH(bif, &sc->sc_iflists[mycpuid], bif_next) {
1898                         dst_if = bif->bif_ifp;
1899                         if ((dst_if->if_flags & IFF_RUNNING) == 0)
1900                                 continue;
1901
1902                         /*
1903                          * If this is not the original output interface,
1904                          * and the interface is participating in spanning
1905                          * tree, make sure the port is in a state that
1906                          * allows forwarding.
1907                          */
1908                         if (dst_if != ifp &&
1909                             (bif->bif_flags & IFBIF_STP) != 0) {
1910                                 switch (bif->bif_state) {
1911                                 case BSTP_IFSTATE_BLOCKING:
1912                                 case BSTP_IFSTATE_LISTENING:
1913                                 case BSTP_IFSTATE_DISABLED:
1914                                         continue;
1915                                 }
1916                         }
1917
1918                         if (LIST_NEXT(bif, bif_next) == NULL) {
1919                                 used = 1;
1920                                 mc = m;
1921                         } else {
1922                                 mc = m_copypacket(m, MB_DONTWAIT);
1923                                 if (mc == NULL) {
1924                                         sc->sc_ifp->if_oerrors++;
1925                                         continue;
1926                                 }
1927                         }
1928                         bridge_enqueue(dst_if, mc);
1929                 }
1930                 if (used == 0)
1931                         m_freem(m);
1932                 lwkt_serialize_exit(sc->sc_ifp->if_serializer);
1933                 return (0);
1934         }
1935
1936 sendunicast:
1937         /*
1938          * XXX Spanning tree consideration here?
1939          */
1940
1941         bridge_span(sc, m);
1942         lwkt_serialize_exit(sc->sc_ifp->if_serializer);
1943         if ((dst_if->if_flags & IFF_RUNNING) == 0)
1944                 m_freem(m);
1945         else
1946                 bridge_enqueue(dst_if, m);
1947         return (0);
1948 }
1949
1950 /*
1951  * bridge_start:
1952  *
1953  *      Start output on a bridge.
1954  *
1955  */
1956 static void
1957 bridge_start(struct ifnet *ifp)
1958 {
1959         struct bridge_softc *sc = ifp->if_softc;
1960
1961         ASSERT_SERIALIZED(ifp->if_serializer);
1962
1963         ifp->if_flags |= IFF_OACTIVE;
1964         for (;;) {
1965                 struct ifnet *dst_if = NULL;
1966                 struct ether_header *eh;
1967                 struct mbuf *m;
1968
1969                 m = ifq_dequeue(&ifp->if_snd, NULL);
1970                 if (m == NULL)
1971                         break;
1972
1973                 if (m->m_len < sizeof(*eh)) {
1974                         m = m_pullup(m, sizeof(*eh));
1975                         if (m == NULL) {
1976                                 ifp->if_oerrors++;
1977                                 continue;
1978                         }
1979                 }
1980                 eh = mtod(m, struct ether_header *);
1981
1982                 BPF_MTAP(ifp, m);
1983                 ifp->if_opackets++;
1984
1985                 if ((m->m_flags & (M_BCAST|M_MCAST)) == 0)
1986                         dst_if = bridge_rtlookup(sc, eh->ether_dhost);
1987
1988                 if (dst_if == NULL)
1989                         bridge_broadcast(sc, ifp, m, 0);
1990                 else
1991                         bridge_enqueue(dst_if, m);
1992         }
1993         ifp->if_flags &= ~IFF_OACTIVE;
1994 }
1995
1996 /*
1997  * bridge_forward:
1998  *
1999  *      The forwarding function of the bridge.
2000  */
2001 static void
2002 bridge_forward(struct bridge_softc *sc, struct mbuf *m)
2003 {
2004         struct bridge_iflist *bif;
2005         struct ifnet *src_if, *dst_if, *ifp;
2006         struct ether_header *eh;
2007
2008         src_if = m->m_pkthdr.rcvif;
2009         ifp = sc->sc_ifp;
2010
2011         ASSERT_SERIALIZED(ifp->if_serializer);
2012
2013         ifp->if_ipackets++;
2014         ifp->if_ibytes += m->m_pkthdr.len;
2015
2016         /*
2017          * Look up the bridge_iflist.
2018          */
2019         bif = bridge_lookup_member_if(sc, src_if);
2020         if (bif == NULL) {
2021                 /* Interface is not a bridge member (anymore?) */
2022                 m_freem(m);
2023                 return;
2024         }
2025
2026         if (bif->bif_flags & IFBIF_STP) {
2027                 switch (bif->bif_state) {
2028                 case BSTP_IFSTATE_BLOCKING:
2029                 case BSTP_IFSTATE_LISTENING:
2030                 case BSTP_IFSTATE_DISABLED:
2031                         m_freem(m);
2032                         return;
2033                 }
2034         }
2035
2036         eh = mtod(m, struct ether_header *);
2037
2038         /*
2039          * If the interface is learning, and the source
2040          * address is valid and not multicast, record
2041          * the address.
2042          */
2043         if ((bif->bif_flags & IFBIF_LEARNING) != 0 &&
2044             ETHER_IS_MULTICAST(eh->ether_shost) == 0 &&
2045             (eh->ether_shost[0] == 0 &&
2046              eh->ether_shost[1] == 0 &&
2047              eh->ether_shost[2] == 0 &&
2048              eh->ether_shost[3] == 0 &&
2049              eh->ether_shost[4] == 0 &&
2050              eh->ether_shost[5] == 0) == 0)
2051                 bridge_rtupdate(sc, eh->ether_shost, src_if, IFBAF_DYNAMIC);
2052
2053         if ((bif->bif_flags & IFBIF_STP) != 0 &&
2054             bif->bif_state == BSTP_IFSTATE_LEARNING) {
2055                 m_freem(m);
2056                 return;
2057         }
2058
2059         /*
2060          * At this point, the port either doesn't participate
2061          * in spanning tree or it is in the forwarding state.
2062          */
2063
2064         /*
2065          * If the packet is unicast, destined for someone on
2066          * "this" side of the bridge, drop it.
2067          */
2068         if ((m->m_flags & (M_BCAST|M_MCAST)) == 0) {
2069                 dst_if = bridge_rtlookup(sc, eh->ether_dhost);
2070                 if (src_if == dst_if) {
2071                         m_freem(m);
2072                         return;
2073                 }
2074         } else {
2075                 /* ...forward it to all interfaces. */
2076                 sc->sc_ifp->if_imcasts++;
2077                 dst_if = NULL;
2078         }
2079
2080         if (dst_if == NULL) {
2081                 bridge_broadcast(sc, src_if, m, 1);
2082                 return;
2083         }
2084
2085         /*
2086          * At this point, we're dealing with a unicast frame
2087          * going to a different interface.
2088          */
2089         if ((dst_if->if_flags & IFF_RUNNING) == 0) {
2090                 m_freem(m);
2091                 return;
2092         }
2093         bif = bridge_lookup_member_if(sc, dst_if);
2094         if (bif == NULL) {
2095                 /* Not a member of the bridge (anymore?) */
2096                 m_freem(m);
2097                 return;
2098         }
2099
2100         if (bif->bif_flags & IFBIF_STP) {
2101                 switch (bif->bif_state) {
2102                 case BSTP_IFSTATE_DISABLED:
2103                 case BSTP_IFSTATE_BLOCKING:
2104                         m_freem(m);
2105                         return;
2106                 }
2107         }
2108
2109         lwkt_serialize_exit(ifp->if_serializer);
2110
2111         /* run the packet filter */
2112         if (inet_pfil_hook.ph_hashooks > 0
2113 #ifdef INET6
2114             || inet6_pfil_hook.ph_hashooks > 0
2115 #endif
2116             ) {
2117                 if (bridge_pfil(&m, ifp, src_if, PFIL_IN) != 0)
2118                         goto done;
2119                 if (m == NULL)
2120                         goto done;
2121
2122                 if (bridge_pfil(&m, ifp, dst_if, PFIL_OUT) != 0)
2123                         goto done;
2124                 if (m == NULL)
2125                         goto done;
2126         }
2127         bridge_handoff(dst_if, m);
2128
2129         /*
2130          * ifp's serializer was held on entry and is expected to be held
2131          * on return.
2132          */
2133 done:
2134         lwkt_serialize_enter(ifp->if_serializer);
2135 }
2136
2137 /*
2138  * bridge_input:
2139  *
2140  *      Receive input from a member interface.  Queue the packet for
2141  *      bridging if it is not for us.
2142  */
2143 static struct mbuf *
2144 bridge_input(struct ifnet *ifp, struct mbuf *m)
2145 {
2146         struct bridge_softc *sc = ifp->if_bridge;
2147         struct bridge_iflist *bif;
2148         struct ifnet *bifp, *new_ifp;
2149         struct ether_header *eh;
2150         struct mbuf *mc, *mc2;
2151
2152         /*
2153          * Make sure that we are still a member of a bridge interface.
2154          */
2155         if (sc == NULL)
2156                 return m;
2157
2158         new_ifp = NULL;
2159         bifp = sc->sc_ifp;
2160
2161         lwkt_serialize_enter(bifp->if_serializer);
2162
2163         if ((bifp->if_flags & IFF_RUNNING) == 0)
2164                 goto out;
2165
2166         /*
2167          * Implement support for bridge monitoring. If this flag has been
2168          * set on this interface, discard the packet once we push it through
2169          * the bpf(4) machinery, but before we do, increment the byte and
2170          * packet counters associated with this interface.
2171          */
2172          if ((bifp->if_flags & IFF_MONITOR) != 0) {
2173                 m->m_pkthdr.rcvif = bifp;
2174                 BPF_MTAP(bifp, m);
2175                 bifp->if_ipackets++;
2176                 bifp->if_ibytes += m->m_pkthdr.len;
2177                 m_freem(m);
2178                 m = NULL;
2179                 goto out;
2180         }
2181
2182         eh = mtod(m, struct ether_header *);
2183
2184         m->m_flags &= ~M_PROTO1; /* XXX Hack - loop prevention */
2185
2186         if (memcmp(eh->ether_dhost, IF_LLADDR(bifp), ETHER_ADDR_LEN) == 0) {
2187                 /*
2188                  * If the packet is for us, set the packets source as the
2189                  * bridge, and return the packet back to ifnet.if_input for
2190                  * local processing.
2191                  */
2192                 KASSERT(bifp->if_bridge == NULL,
2193                         ("loop created in bridge_input"));
2194                 new_ifp = bifp;
2195                 goto out;
2196         }
2197
2198         /*
2199          * Tap all packets arriving on the bridge, no matter if
2200          * they are local destinations or not.  In is in.
2201          */
2202         BPF_MTAP(bifp, m);
2203
2204         bif = bridge_lookup_member_if(sc, ifp);
2205         if (bif == NULL)
2206                 goto out;
2207
2208         bridge_span(sc, m);
2209
2210         if (m->m_flags & (M_BCAST | M_MCAST)) {
2211                 /* Tap off 802.1D packets; they do not get forwarded. */
2212                 if (memcmp(eh->ether_dhost, bstp_etheraddr,
2213                     ETHER_ADDR_LEN) == 0) {
2214                         m = bstp_input(sc, bif, m);
2215                         KASSERT(m == NULL,
2216                                 ("attempt to deliver 802.1D packet\n"));
2217                         goto out;
2218                 }
2219
2220                 if (bif->bif_flags & IFBIF_STP) {
2221                         switch (bif->bif_state) {
2222                         case BSTP_IFSTATE_BLOCKING:
2223                         case BSTP_IFSTATE_LISTENING:
2224                         case BSTP_IFSTATE_DISABLED:
2225                                 goto out;
2226                         }
2227                 }
2228
2229                 /*
2230                  * Make a deep copy of the packet and enqueue the copy
2231                  * for bridge processing; return the original packet for
2232                  * local processing.
2233                  */
2234                 mc = m_dup(m, MB_DONTWAIT);
2235                 if (mc == NULL)
2236                         goto out;
2237
2238                 bridge_forward(sc, mc);
2239
2240                 /*
2241                  * Reinject the mbuf as arriving on the bridge so we have a
2242                  * chance at claiming multicast packets. We can not loop back
2243                  * here from ether_input as a bridge is never a member of a
2244                  * bridge.
2245                  */
2246                 KASSERT(bifp->if_bridge == NULL,
2247                         ("loop created in bridge_input"));
2248                 mc2 = m_dup(m, MB_DONTWAIT);
2249 #ifdef notyet
2250                 if (mc2 != NULL) {
2251                         /* Keep the layer3 header aligned */
2252                         int i = min(mc2->m_pkthdr.len, max_protohdr);
2253                         mc2 = m_copyup(mc2, i, ETHER_ALIGN);
2254                 }
2255 #endif
2256                 if (mc2 != NULL) {
2257                         mc2->m_pkthdr.rcvif = bifp;
2258                         bifp->if_ipackets++;
2259                         bifp->if_input(bifp, mc2);
2260                 }
2261
2262                 /* Return the original packet for local processing. */
2263                 goto out;
2264         }
2265
2266         if (bif->bif_flags & IFBIF_STP) {
2267                 switch (bif->bif_state) {
2268                 case BSTP_IFSTATE_BLOCKING:
2269                 case BSTP_IFSTATE_LISTENING:
2270                 case BSTP_IFSTATE_DISABLED:
2271                         goto out;
2272                 }
2273         }
2274
2275         /*
2276          * Unicast.  Make sure it's not for us.
2277          *
2278          * This loop is MPSAFE; the only blocking operation (bridge_rtupdate)
2279          * is followed by breaking out of the loop.
2280          */
2281         LIST_FOREACH(bif, &sc->sc_iflists[mycpuid], bif_next) {
2282                 if (bif->bif_ifp->if_type != IFT_ETHER)
2283                         continue;
2284
2285                 /* It is destined for us. */
2286                 if (memcmp(IF_LLADDR(bif->bif_ifp), eh->ether_dhost,
2287                     ETHER_ADDR_LEN) == 0) {
2288                         if (bif->bif_ifp != ifp) {
2289                                 /* XXX loop prevention */
2290                                 m->m_flags |= M_PROTO1;
2291                                 new_ifp = bif->bif_ifp;
2292                         }
2293                         if (bif->bif_flags & IFBIF_LEARNING) {
2294                                 bridge_rtupdate(sc, eh->ether_shost,
2295                                                 ifp, IFBAF_DYNAMIC);
2296                         }
2297                         goto out;
2298                 }
2299
2300                 /* We just received a packet that we sent out. */
2301                 if (memcmp(IF_LLADDR(bif->bif_ifp), eh->ether_shost,
2302                     ETHER_ADDR_LEN) == 0) {
2303                         m_freem(m);
2304                         m = NULL;
2305                         goto out;
2306                 }
2307         }
2308
2309         /* Perform the bridge forwarding function. */
2310         bridge_forward(sc, m);
2311         m = NULL;
2312 out:
2313         lwkt_serialize_exit(bifp->if_serializer);
2314
2315         if (new_ifp != NULL) {
2316                 lwkt_serialize_enter(new_ifp->if_serializer);
2317
2318                 m->m_pkthdr.rcvif = new_ifp;
2319                 new_ifp->if_ipackets++;
2320                 new_ifp->if_input(new_ifp, m);
2321                 m = NULL;
2322
2323                 lwkt_serialize_exit(new_ifp->if_serializer);
2324         }
2325         return (m);
2326 }
2327
2328 /*
2329  * bridge_broadcast:
2330  *
2331  *      Send a frame to all interfaces that are members of
2332  *      the bridge, except for the one on which the packet
2333  *      arrived.
2334  */
2335 static void
2336 bridge_broadcast(struct bridge_softc *sc, struct ifnet *src_if,
2337     struct mbuf *m, int runfilt)
2338 {
2339         struct bridge_iflist *bif;
2340         struct mbuf *mc;
2341         struct ifnet *dst_if, *bifp;
2342         int used = 0;
2343
2344         bifp = sc->sc_ifp;
2345
2346         ASSERT_SERIALIZED(bifp->if_serializer);
2347
2348         /* run the packet filter */
2349         if (runfilt && (inet_pfil_hook.ph_hashooks > 0
2350 #ifdef INET6
2351             || inet6_pfil_hook.ph_hashooks > 0
2352 #endif
2353             )) {
2354                 lwkt_serialize_exit(bifp->if_serializer);
2355
2356                 /* Filter on the bridge interface before broadcasting */
2357
2358                 if (bridge_pfil(&m, bifp, src_if, PFIL_IN) != 0)
2359                         goto filt;
2360                 if (m == NULL)
2361                         goto filt;
2362
2363                 if (bridge_pfil(&m, bifp, NULL, PFIL_OUT) != 0)
2364                         m = NULL;
2365 filt:
2366                 lwkt_serialize_enter(bifp->if_serializer);
2367                 if (m == NULL)
2368                         return;
2369         }
2370
2371         /*
2372          * Following loop is MPSAFE; nothing is blocking
2373          * in the loop body.
2374          */
2375         LIST_FOREACH(bif, &sc->sc_iflists[mycpuid], bif_next) {
2376                 dst_if = bif->bif_ifp;
2377                 if (dst_if == src_if)
2378                         continue;
2379
2380                 if (bif->bif_flags & IFBIF_STP) {
2381                         switch (bif->bif_state) {
2382                         case BSTP_IFSTATE_BLOCKING:
2383                         case BSTP_IFSTATE_DISABLED:
2384                                 continue;
2385                         }
2386                 }
2387
2388                 if ((bif->bif_flags & IFBIF_DISCOVER) == 0 &&
2389                     (m->m_flags & (M_BCAST|M_MCAST)) == 0)
2390                         continue;
2391
2392                 if ((dst_if->if_flags & IFF_RUNNING) == 0)
2393                         continue;
2394
2395                 if (LIST_NEXT(bif, bif_next) == NULL) {
2396                         mc = m;
2397                         used = 1;
2398                 } else {
2399                         mc = m_copypacket(m, MB_DONTWAIT);
2400                         if (mc == NULL) {
2401                                 sc->sc_ifp->if_oerrors++;
2402                                 continue;
2403                         }
2404                 }
2405                 bridge_pfil_enqueue(dst_if, mc, runfilt);
2406         }
2407         if (used == 0)
2408                 m_freem(m);
2409 }
2410
2411 /*
2412  * bridge_span:
2413  *
2414  *      Duplicate a packet out one or more interfaces that are in span mode,
2415  *      the original mbuf is unmodified.
2416  */
2417 static void
2418 bridge_span(struct bridge_softc *sc, struct mbuf *m)
2419 {
2420         struct bridge_iflist *bif;
2421         struct ifnet *dst_if;
2422         struct mbuf *mc;
2423
2424         if (LIST_EMPTY(&sc->sc_spanlist))
2425                 return;
2426
2427         LIST_FOREACH(bif, &sc->sc_spanlist, bif_next) {
2428                 dst_if = bif->bif_ifp;
2429
2430                 if ((dst_if->if_flags & IFF_RUNNING) == 0)
2431                         continue;
2432
2433                 mc = m_copypacket(m, MB_DONTWAIT);
2434                 if (mc == NULL) {
2435                         sc->sc_ifp->if_oerrors++;
2436                         continue;
2437                 }
2438
2439                 bridge_enqueue(dst_if, mc);
2440         }
2441 }
2442
2443 static void
2444 bridge_rtmsg_sync_handler(struct netmsg *nmsg)
2445 {
2446         ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
2447 }
2448
2449 static void
2450 bridge_rtmsg_sync(struct bridge_softc *sc)
2451 {
2452         struct netmsg nmsg;
2453
2454         ASSERT_NOT_SERIALIZED(sc->sc_ifp->if_serializer);
2455
2456         netmsg_init(&nmsg, &curthread->td_msgport, 0,
2457                     bridge_rtmsg_sync_handler);
2458         ifnet_domsg(&nmsg.nm_lmsg, 0);
2459 }
2460
2461 static __inline void
2462 bridge_rtinfo_update(struct bridge_rtinfo *bri, struct ifnet *dst_if,
2463                      int setflags, uint8_t flags, uint32_t timeo)
2464 {
2465         if ((bri->bri_flags & IFBAF_TYPEMASK) == IFBAF_DYNAMIC &&
2466             bri->bri_ifp != dst_if)
2467                 bri->bri_ifp = dst_if;
2468         if ((flags & IFBAF_TYPEMASK) == IFBAF_DYNAMIC &&
2469             bri->bri_expire != time_second + timeo)
2470                 bri->bri_expire = time_second + timeo;
2471         if (setflags)
2472                 bri->bri_flags = flags;
2473 }
2474
2475 static int
2476 bridge_rtinstall_oncpu(struct bridge_softc *sc, const uint8_t *dst,
2477                        struct ifnet *dst_if, int setflags, uint8_t flags,
2478                        struct bridge_rtinfo **bri0)
2479 {
2480         struct bridge_rtnode *brt;
2481         struct bridge_rtinfo *bri;
2482
2483         if (mycpuid == 0) {
2484                 brt = bridge_rtnode_lookup(sc, dst);
2485                 if (brt != NULL) {
2486                         /*
2487                          * rtnode for 'dst' already exists.  We inform the
2488                          * caller about this by leaving bri0 as NULL.  The
2489                          * caller will terminate the intallation upon getting
2490                          * NULL bri0.  However, we still need to update the
2491                          * rtinfo.
2492                          */
2493                         KKASSERT(*bri0 == NULL);
2494
2495                         /* Update rtinfo */
2496                         bridge_rtinfo_update(brt->brt_info, dst_if, setflags,
2497                                              flags, sc->sc_brttimeout);
2498                         return 0;
2499                 }
2500
2501                 /*
2502                  * We only need to check brtcnt on CPU0, since if limit
2503                  * is to be exceeded, ENOSPC is returned.  Caller knows
2504                  * this and will terminate the installation.
2505                  */
2506                 if (sc->sc_brtcnt >= sc->sc_brtmax)
2507                         return ENOSPC;
2508
2509                 KKASSERT(*bri0 == NULL);
2510                 bri = kmalloc(sizeof(struct bridge_rtinfo), M_DEVBUF,
2511                                   M_WAITOK | M_ZERO);
2512                 *bri0 = bri;
2513
2514                 /* Setup rtinfo */
2515                 bri->bri_flags = IFBAF_DYNAMIC;
2516                 bridge_rtinfo_update(bri, dst_if, setflags, flags,
2517                                      sc->sc_brttimeout);
2518         } else {
2519                 bri = *bri0;
2520                 KKASSERT(bri != NULL);
2521         }
2522
2523         brt = kmalloc(sizeof(struct bridge_rtnode), M_DEVBUF,
2524                       M_WAITOK | M_ZERO);
2525         memcpy(brt->brt_addr, dst, ETHER_ADDR_LEN);
2526         brt->brt_info = bri;
2527
2528         bridge_rtnode_insert(sc, brt);
2529         return 0;
2530 }
2531
2532 static void
2533 bridge_rtinstall_handler(struct netmsg *nmsg)
2534 {
2535         struct netmsg_brsaddr *brmsg = (struct netmsg_brsaddr *)nmsg;
2536         int error;
2537
2538         error = bridge_rtinstall_oncpu(brmsg->br_softc,
2539                                        brmsg->br_dst, brmsg->br_dst_if,
2540                                        brmsg->br_setflags, brmsg->br_flags,
2541                                        &brmsg->br_rtinfo);
2542         if (error) {
2543                 KKASSERT(mycpuid == 0 && brmsg->br_rtinfo == NULL);
2544                 lwkt_replymsg(&nmsg->nm_lmsg, error);
2545                 return;
2546         } else if (brmsg->br_rtinfo == NULL) {
2547                 /* rtnode already exists for 'dst' */
2548                 KKASSERT(mycpuid == 0);
2549                 lwkt_replymsg(&nmsg->nm_lmsg, 0);
2550                 return;
2551         }
2552         ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
2553 }
2554
2555 /*
2556  * bridge_rtupdate:
2557  *
2558  *      Add/Update a bridge routing entry.
2559  */
2560 static int
2561 bridge_rtupdate(struct bridge_softc *sc, const uint8_t *dst,
2562                 struct ifnet *dst_if, uint8_t flags)
2563 {
2564         struct bridge_rtnode *brt;
2565
2566         /*
2567          * A route for this destination might already exist.  If so,
2568          * update it, otherwise create a new one.
2569          */
2570         if ((brt = bridge_rtnode_lookup(sc, dst)) == NULL) {
2571                 struct netmsg_brsaddr *brmsg;
2572
2573                 if (sc->sc_brtcnt >= sc->sc_brtmax)
2574                         return ENOSPC;
2575
2576                 brmsg = kmalloc(sizeof(*brmsg), M_LWKTMSG, M_WAITOK | M_NULLOK);
2577                 if (brmsg == NULL)
2578                         return ENOMEM;
2579
2580                 netmsg_init(&brmsg->br_nmsg, &netisr_afree_rport, 0,
2581                             bridge_rtinstall_handler);
2582                 memcpy(brmsg->br_dst, dst, ETHER_ADDR_LEN);
2583                 brmsg->br_dst_if = dst_if;
2584                 brmsg->br_flags = flags;
2585                 brmsg->br_setflags = 0;
2586                 brmsg->br_softc = sc;
2587                 brmsg->br_rtinfo = NULL;
2588
2589                 ifnet_sendmsg(&brmsg->br_nmsg.nm_lmsg, 0);
2590                 return 0;
2591         }
2592         bridge_rtinfo_update(brt->brt_info, dst_if, 0, flags,
2593                              sc->sc_brttimeout);
2594         return 0;
2595 }
2596
2597 static int
2598 bridge_rtsaddr(struct bridge_softc *sc, const uint8_t *dst,
2599                struct ifnet *dst_if, uint8_t flags)
2600 {
2601         struct netmsg_brsaddr brmsg;
2602
2603         ASSERT_NOT_SERIALIZED(sc->sc_ifp->if_serializer);
2604
2605         netmsg_init(&brmsg.br_nmsg, &curthread->td_msgport, MSGF_PRIORITY,
2606                     bridge_rtinstall_handler);
2607         memcpy(brmsg.br_dst, dst, ETHER_ADDR_LEN);
2608         brmsg.br_dst_if = dst_if;
2609         brmsg.br_flags = flags;
2610         brmsg.br_setflags = 1;
2611         brmsg.br_softc = sc;
2612         brmsg.br_rtinfo = NULL;
2613
2614         return ifnet_domsg(&brmsg.br_nmsg.nm_lmsg, 0);
2615 }
2616
2617 /*
2618  * bridge_rtlookup:
2619  *
2620  *      Lookup the destination interface for an address.
2621  */
2622 static struct ifnet *
2623 bridge_rtlookup(struct bridge_softc *sc, const uint8_t *addr)
2624 {
2625         struct bridge_rtnode *brt;
2626
2627         if ((brt = bridge_rtnode_lookup(sc, addr)) == NULL)
2628                 return NULL;
2629         return brt->brt_info->bri_ifp;
2630 }
2631
2632 static void
2633 bridge_rtreap_handler(struct netmsg *nmsg)
2634 {
2635         struct bridge_softc *sc = nmsg->nm_lmsg.u.ms_resultp;
2636         struct bridge_rtnode *brt, *nbrt;
2637
2638         LIST_FOREACH_MUTABLE(brt, &sc->sc_rtlists[mycpuid], brt_list, nbrt) {
2639                 if (brt->brt_info->bri_dead)
2640                         bridge_rtnode_destroy(sc, brt);
2641         }
2642         ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
2643 }
2644
2645 static void
2646 bridge_rtreap(struct bridge_softc *sc)
2647 {
2648         struct netmsg nmsg;
2649
2650         ASSERT_NOT_SERIALIZED(sc->sc_ifp->if_serializer);
2651
2652         netmsg_init(&nmsg, &curthread->td_msgport, 0, bridge_rtreap_handler);
2653         nmsg.nm_lmsg.u.ms_resultp = sc;
2654
2655         ifnet_domsg(&nmsg.nm_lmsg, 0);
2656 }
2657
2658 /*
2659  * bridge_rttrim:
2660  *
2661  *      Trim the routine table so that we have a number
2662  *      of routing entries less than or equal to the
2663  *      maximum number.
2664  */
2665 static void
2666 bridge_rttrim(struct bridge_softc *sc)
2667 {
2668         struct bridge_rtnode *brt;
2669         int dead;
2670
2671         ASSERT_NOT_SERIALIZED(sc->sc_ifp->if_serializer);
2672
2673         /* Make sure we actually need to do this. */
2674         if (sc->sc_brtcnt <= sc->sc_brtmax)
2675                 return;
2676
2677         /*
2678          * Find out how many rtnodes are dead
2679          */
2680         dead = bridge_rtage_finddead(sc);
2681         KKASSERT(dead <= sc->sc_brtcnt);
2682
2683         if (sc->sc_brtcnt - dead <= sc->sc_brtmax) {
2684                 /* Enough dead rtnodes are found */
2685                 bridge_rtreap(sc);
2686                 return;
2687         }
2688
2689         /*
2690          * Kill some dynamic rtnodes to meet the brtmax
2691          */
2692         LIST_FOREACH(brt, &sc->sc_rtlists[mycpuid], brt_list) {
2693                 struct bridge_rtinfo *bri = brt->brt_info;
2694
2695                 if (bri->bri_dead) {
2696                         /*
2697                          * We have counted this rtnode in
2698                          * bridge_rtage_finddead()
2699                          */
2700                         continue;
2701                 }
2702
2703                 if ((bri->bri_flags & IFBAF_TYPEMASK) == IFBAF_DYNAMIC) {
2704                         bri->bri_dead = 1;
2705                         ++dead;
2706                         KKASSERT(dead <= sc->sc_brtcnt);
2707
2708                         if (sc->sc_brtcnt - dead <= sc->sc_brtmax) {
2709                                 /* Enough rtnodes are collected */
2710                                 break;
2711                         }
2712                 }
2713         }
2714         if (dead)
2715                 bridge_rtreap(sc);
2716 }
2717
2718 /*
2719  * bridge_timer:
2720  *
2721  *      Aging timer for the bridge.
2722  */
2723 static void
2724 bridge_timer(void *arg)
2725 {
2726         struct bridge_softc *sc = arg;
2727         struct lwkt_msg *lmsg;
2728
2729         KKASSERT(mycpuid == BRIDGE_CFGCPU);
2730
2731         crit_enter();
2732
2733         if (callout_pending(&sc->sc_brcallout) ||
2734             !callout_active(&sc->sc_brcallout)) {
2735                 crit_exit();
2736                 return;
2737         }
2738         callout_deactivate(&sc->sc_brcallout);
2739
2740         lmsg = &sc->sc_brtimemsg.nm_lmsg;
2741         KKASSERT(lmsg->ms_flags & MSGF_DONE);
2742         lwkt_sendmsg(BRIDGE_CFGPORT, lmsg);
2743
2744         crit_exit();
2745 }
2746
2747 static void
2748 bridge_timer_handler(struct netmsg *nmsg)
2749 {
2750         struct bridge_softc *sc = nmsg->nm_lmsg.u.ms_resultp;
2751
2752         KKASSERT(&curthread->td_msgport == BRIDGE_CFGPORT);
2753
2754         crit_enter();
2755         /* Reply ASAP */
2756         lwkt_replymsg(&nmsg->nm_lmsg, 0);
2757         crit_exit();
2758
2759         bridge_rtage(sc);
2760         if (sc->sc_ifp->if_flags & IFF_RUNNING) {
2761                 callout_reset(&sc->sc_brcallout,
2762                     bridge_rtable_prune_period * hz, bridge_timer, sc);
2763         }
2764 }
2765
2766 static int
2767 bridge_rtage_finddead(struct bridge_softc *sc)
2768 {
2769         struct bridge_rtnode *brt;
2770         int dead = 0;
2771
2772         LIST_FOREACH(brt, &sc->sc_rtlists[mycpuid], brt_list) {
2773                 struct bridge_rtinfo *bri = brt->brt_info;
2774
2775                 if ((bri->bri_flags & IFBAF_TYPEMASK) == IFBAF_DYNAMIC &&
2776                     time_second >= bri->bri_expire) {
2777                         bri->bri_dead = 1;
2778                         ++dead;
2779                         KKASSERT(dead <= sc->sc_brtcnt);
2780                 }
2781         }
2782         return dead;
2783 }
2784
2785 /*
2786  * bridge_rtage:
2787  *
2788  *      Perform an aging cycle.
2789  */
2790 static void
2791 bridge_rtage(struct bridge_softc *sc)
2792 {
2793         ASSERT_NOT_SERIALIZED(sc->sc_ifp->if_serializer);
2794
2795         if (bridge_rtage_finddead(sc))
2796                 bridge_rtreap(sc);
2797 }
2798
2799 /*
2800  * bridge_rtflush:
2801  *
2802  *      Remove all dynamic addresses from the bridge.
2803  */
2804 static void
2805 bridge_rtflush(struct bridge_softc *sc, int full)
2806 {
2807         struct bridge_rtnode *brt;
2808         int reap;
2809
2810         ASSERT_NOT_SERIALIZED(sc->sc_ifp->if_serializer);
2811
2812         reap = 0;
2813         LIST_FOREACH(brt, &sc->sc_rtlists[mycpuid], brt_list) {
2814                 struct bridge_rtinfo *bri = brt->brt_info;
2815
2816                 if (full ||
2817                     (bri->bri_flags & IFBAF_TYPEMASK) == IFBAF_DYNAMIC) {
2818                         bri->bri_dead = 1;
2819                         reap = 1;
2820                 }
2821         }
2822         if (reap)
2823                 bridge_rtreap(sc);
2824 }
2825
2826 /*
2827  * bridge_rtdaddr:
2828  *
2829  *      Remove an address from the table.
2830  */
2831 static int
2832 bridge_rtdaddr(struct bridge_softc *sc, const uint8_t *addr)
2833 {
2834         struct bridge_rtnode *brt;
2835
2836         ASSERT_NOT_SERIALIZED(sc->sc_ifp->if_serializer);
2837
2838         if ((brt = bridge_rtnode_lookup(sc, addr)) == NULL)
2839                 return (ENOENT);
2840
2841         /* TODO: add a cheaper delete operation */
2842         brt->brt_info->bri_dead = 1;
2843         bridge_rtreap(sc);
2844         return (0);
2845 }
2846
2847 /*
2848  * bridge_rtdelete:
2849  *
2850  *      Delete routes to a speicifc member interface.
2851  */
2852 void
2853 bridge_rtdelete(struct bridge_softc *sc, struct ifnet *ifp, int full)
2854 {
2855         struct bridge_rtnode *brt;
2856         int reap;
2857
2858         ASSERT_NOT_SERIALIZED(sc->sc_ifp->if_serializer);
2859
2860         reap = 0;
2861         LIST_FOREACH(brt, &sc->sc_rtlists[mycpuid], brt_list) {
2862                 struct bridge_rtinfo *bri = brt->brt_info;
2863
2864                 if (bri->bri_ifp == ifp &&
2865                     (full ||
2866                      (bri->bri_flags & IFBAF_TYPEMASK) == IFBAF_DYNAMIC)) {
2867                         bri->bri_dead = 1;
2868                         reap = 1;
2869                 }
2870         }
2871         if (reap)
2872                 bridge_rtreap(sc);
2873 }
2874
2875 /*
2876  * bridge_rtable_init:
2877  *
2878  *      Initialize the route table for this bridge.
2879  */
2880 static void
2881 bridge_rtable_init(struct bridge_softc *sc)
2882 {
2883         int cpu;
2884
2885         /*
2886          * Initialize per-cpu hash tables
2887          */
2888         sc->sc_rthashs = kmalloc(sizeof(*sc->sc_rthashs) * ncpus,
2889                                  M_DEVBUF, M_WAITOK);
2890         for (cpu = 0; cpu < ncpus; ++cpu) {
2891                 int i;
2892
2893                 sc->sc_rthashs[cpu] =
2894                 kmalloc(sizeof(struct bridge_rtnode_head) * BRIDGE_RTHASH_SIZE,
2895                         M_DEVBUF, M_WAITOK);
2896
2897                 for (i = 0; i < BRIDGE_RTHASH_SIZE; i++)
2898                         LIST_INIT(&sc->sc_rthashs[cpu][i]);
2899         }
2900         sc->sc_rthash_key = karc4random();
2901
2902         /*
2903          * Initialize per-cpu lists
2904          */
2905         sc->sc_rtlists = kmalloc(sizeof(struct bridge_rtnode_head) * ncpus,
2906                                  M_DEVBUF, M_WAITOK);
2907         for (cpu = 0; cpu < ncpus; ++cpu)
2908                 LIST_INIT(&sc->sc_rtlists[cpu]);
2909 }
2910
2911 /*
2912  * bridge_rtable_fini:
2913  *
2914  *      Deconstruct the route table for this bridge.
2915  */
2916 static void
2917 bridge_rtable_fini(struct bridge_softc *sc)
2918 {
2919         int cpu;
2920
2921         /*
2922          * Free per-cpu hash tables
2923          */
2924         for (cpu = 0; cpu < ncpus; ++cpu)
2925                 kfree(sc->sc_rthashs[cpu], M_DEVBUF);
2926         kfree(sc->sc_rthashs, M_DEVBUF);
2927
2928         /*
2929          * Free per-cpu lists
2930          */
2931         kfree(sc->sc_rtlists, M_DEVBUF);
2932 }
2933
2934 /*
2935  * The following hash function is adapted from "Hash Functions" by Bob Jenkins
2936  * ("Algorithm Alley", Dr. Dobbs Journal, September 1997).
2937  */
2938 #define mix(a, b, c)                                                    \
2939 do {                                                                    \
2940         a -= b; a -= c; a ^= (c >> 13);                                 \
2941         b -= c; b -= a; b ^= (a << 8);                                  \
2942         c -= a; c -= b; c ^= (b >> 13);                                 \
2943         a -= b; a -= c; a ^= (c >> 12);                                 \
2944         b -= c; b -= a; b ^= (a << 16);                                 \
2945         c -= a; c -= b; c ^= (b >> 5);                                  \
2946         a -= b; a -= c; a ^= (c >> 3);                                  \
2947         b -= c; b -= a; b ^= (a << 10);                                 \
2948         c -= a; c -= b; c ^= (b >> 15);                                 \
2949 } while (/*CONSTCOND*/0)
2950
2951 static __inline uint32_t
2952 bridge_rthash(struct bridge_softc *sc, const uint8_t *addr)
2953 {
2954         uint32_t a = 0x9e3779b9, b = 0x9e3779b9, c = sc->sc_rthash_key;
2955
2956         b += addr[5] << 8;
2957         b += addr[4];
2958         a += addr[3] << 24;
2959         a += addr[2] << 16;
2960         a += addr[1] << 8;
2961         a += addr[0];
2962
2963         mix(a, b, c);
2964
2965         return (c & BRIDGE_RTHASH_MASK);
2966 }
2967
2968 #undef mix
2969
2970 static int
2971 bridge_rtnode_addr_cmp(const uint8_t *a, const uint8_t *b)
2972 {
2973         int i, d;
2974
2975         for (i = 0, d = 0; i < ETHER_ADDR_LEN && d == 0; i++) {
2976                 d = ((int)a[i]) - ((int)b[i]);
2977         }
2978
2979         return (d);
2980 }
2981
2982 /*
2983  * bridge_rtnode_lookup:
2984  *
2985  *      Look up a bridge route node for the specified destination.
2986  */
2987 static struct bridge_rtnode *
2988 bridge_rtnode_lookup(struct bridge_softc *sc, const uint8_t *addr)
2989 {
2990         struct bridge_rtnode *brt;
2991         uint32_t hash;
2992         int dir;
2993
2994         hash = bridge_rthash(sc, addr);
2995         LIST_FOREACH(brt, &sc->sc_rthashs[mycpuid][hash], brt_hash) {
2996                 dir = bridge_rtnode_addr_cmp(addr, brt->brt_addr);
2997                 if (dir == 0)
2998                         return (brt);
2999                 if (dir > 0)
3000                         return (NULL);
3001         }
3002
3003         return (NULL);
3004 }
3005
3006 /*
3007  * bridge_rtnode_insert:
3008  *
3009  *      Insert the specified bridge node into the route table.
3010  *      Caller has to make sure that rtnode does not exist.
3011  */
3012 static void
3013 bridge_rtnode_insert(struct bridge_softc *sc, struct bridge_rtnode *brt)
3014 {
3015         struct bridge_rtnode *lbrt;
3016         uint32_t hash;
3017         int dir;
3018
3019         hash = bridge_rthash(sc, brt->brt_addr);
3020
3021         lbrt = LIST_FIRST(&sc->sc_rthashs[mycpuid][hash]);
3022         if (lbrt == NULL) {
3023                 LIST_INSERT_HEAD(&sc->sc_rthashs[mycpuid][hash], brt, brt_hash);
3024                 goto out;
3025         }
3026
3027         do {
3028                 dir = bridge_rtnode_addr_cmp(brt->brt_addr, lbrt->brt_addr);
3029                 KASSERT(dir != 0, ("rtnode already exist\n"));
3030
3031                 if (dir > 0) {
3032                         LIST_INSERT_BEFORE(lbrt, brt, brt_hash);
3033                         goto out;
3034                 }
3035                 if (LIST_NEXT(lbrt, brt_hash) == NULL) {
3036                         LIST_INSERT_AFTER(lbrt, brt, brt_hash);
3037                         goto out;
3038                 }
3039                 lbrt = LIST_NEXT(lbrt, brt_hash);
3040         } while (lbrt != NULL);
3041
3042         panic("no suitable position found for rtnode\n");
3043 out:
3044         LIST_INSERT_HEAD(&sc->sc_rtlists[mycpuid], brt, brt_list);
3045         if (mycpuid == 0) {
3046                 /*
3047                  * Update the brtcnt.
3048                  * We only need to do it once and we do it on CPU0.
3049                  */
3050                 sc->sc_brtcnt++;
3051         }
3052 }
3053
3054 /*
3055  * bridge_rtnode_destroy:
3056  *
3057  *      Destroy a bridge rtnode.
3058  */
3059 static void
3060 bridge_rtnode_destroy(struct bridge_softc *sc, struct bridge_rtnode *brt)
3061 {
3062         LIST_REMOVE(brt, brt_hash);
3063         LIST_REMOVE(brt, brt_list);
3064
3065         if (mycpuid + 1 == ncpus) {
3066                 /* Free rtinfo associated with rtnode on the last cpu */
3067                 kfree(brt->brt_info, M_DEVBUF);
3068         }
3069         kfree(brt, M_DEVBUF);
3070
3071         if (mycpuid == 0) {
3072                 /* Update brtcnt only on CPU0 */
3073                 sc->sc_brtcnt--;
3074         }
3075 }
3076
3077 static __inline int
3078 bridge_post_pfil(struct mbuf *m)
3079 {
3080         if (m->m_pkthdr.fw_flags & IPFORWARD_MBUF_TAGGED)
3081                 return EOPNOTSUPP;
3082
3083         /* Not yet */
3084         if (m->m_pkthdr.fw_flags & DUMMYNET_MBUF_TAGGED)
3085                 return EOPNOTSUPP;
3086
3087         return 0;
3088 }
3089
3090 /*
3091  * Send bridge packets through pfil if they are one of the types pfil can deal
3092  * with, or if they are ARP or REVARP.  (pfil will pass ARP and REVARP without
3093  * question.) If *bifp or *ifp are NULL then packet filtering is skipped for
3094  * that interface.
3095  */
3096 static int
3097 bridge_pfil(struct mbuf **mp, struct ifnet *bifp, struct ifnet *ifp, int dir)
3098 {
3099         int snap, error, i, hlen;
3100         struct ether_header *eh1, eh2;
3101         struct ip *ip;
3102         struct llc llc1;
3103         u_int16_t ether_type;
3104
3105         snap = 0;
3106         error = -1;     /* Default error if not error == 0 */
3107
3108         if (pfil_bridge == 0 && pfil_member == 0)
3109                 return (0); /* filtering is disabled */
3110
3111         i = min((*mp)->m_pkthdr.len, max_protohdr);
3112         if ((*mp)->m_len < i) {
3113             *mp = m_pullup(*mp, i);
3114             if (*mp == NULL) {
3115                 kprintf("%s: m_pullup failed\n", __func__);
3116                 return (-1);
3117             }
3118         }
3119
3120         eh1 = mtod(*mp, struct ether_header *);
3121         ether_type = ntohs(eh1->ether_type);
3122
3123         /*
3124          * Check for SNAP/LLC.
3125          */
3126         if (ether_type < ETHERMTU) {
3127                 struct llc *llc2 = (struct llc *)(eh1 + 1);
3128
3129                 if ((*mp)->m_len >= ETHER_HDR_LEN + 8 &&
3130                     llc2->llc_dsap == LLC_SNAP_LSAP &&
3131                     llc2->llc_ssap == LLC_SNAP_LSAP &&
3132                     llc2->llc_control == LLC_UI) {
3133                         ether_type = htons(llc2->llc_un.type_snap.ether_type);
3134                         snap = 1;
3135                 }
3136         }
3137
3138         /*
3139          * If we're trying to filter bridge traffic, don't look at anything
3140          * other than IP and ARP traffic.  If the filter doesn't understand
3141          * IPv6, don't allow IPv6 through the bridge either.  This is lame
3142          * since if we really wanted, say, an AppleTalk filter, we are hosed,
3143          * but of course we don't have an AppleTalk filter to begin with.
3144          * (Note that since pfil doesn't understand ARP it will pass *ALL*
3145          * ARP traffic.)
3146          */
3147         switch (ether_type) {
3148                 case ETHERTYPE_ARP:
3149                 case ETHERTYPE_REVARP:
3150                         return (0); /* Automatically pass */
3151                 case ETHERTYPE_IP:
3152 #ifdef INET6
3153                 case ETHERTYPE_IPV6:
3154 #endif /* INET6 */
3155                         break;
3156                 default:
3157                         /*
3158                          * Check to see if the user wants to pass non-ip
3159                          * packets, these will not be checked by pfil(9) and
3160                          * passed unconditionally so the default is to drop.
3161                          */
3162                         if (pfil_onlyip)
3163                                 goto bad;
3164         }
3165
3166         /* Strip off the Ethernet header and keep a copy. */
3167         m_copydata(*mp, 0, ETHER_HDR_LEN, (caddr_t) &eh2);
3168         m_adj(*mp, ETHER_HDR_LEN);
3169
3170         /* Strip off snap header, if present */
3171         if (snap) {
3172                 m_copydata(*mp, 0, sizeof(struct llc), (caddr_t) &llc1);
3173                 m_adj(*mp, sizeof(struct llc));
3174         }
3175
3176         /*
3177          * Check the IP header for alignment and errors
3178          */
3179         if (dir == PFIL_IN) {
3180                 switch (ether_type) {
3181                         case ETHERTYPE_IP:
3182                                 error = bridge_ip_checkbasic(mp);
3183                                 break;
3184 #ifdef INET6
3185                         case ETHERTYPE_IPV6:
3186                                 error = bridge_ip6_checkbasic(mp);
3187                                 break;
3188 #endif /* INET6 */
3189                         default:
3190                                 error = 0;
3191                 }
3192                 if (error)
3193                         goto bad;
3194         }
3195
3196         error = 0;
3197
3198         /*
3199          * Run the packet through pfil
3200          */
3201         switch (ether_type)
3202         {
3203         case ETHERTYPE_IP :
3204                 /*
3205                  * before calling the firewall, swap fields the same as
3206                  * IP does. here we assume the header is contiguous
3207                  */
3208                 ip = mtod(*mp, struct ip *);
3209
3210                 ip->ip_len = ntohs(ip->ip_len);
3211                 ip->ip_off = ntohs(ip->ip_off);
3212
3213                 /*
3214                  * Run pfil on the member interface and the bridge, both can
3215                  * be skipped by clearing pfil_member or pfil_bridge.
3216                  *
3217                  * Keep the order:
3218                  *   in_if -> bridge_if -> out_if
3219                  */
3220                 if (pfil_bridge && dir == PFIL_OUT && bifp != NULL) {
3221                         error = pfil_run_hooks(&inet_pfil_hook, mp, bifp, dir);
3222                         if (*mp == NULL || error != 0) /* filter may consume */
3223                                 break;
3224                         error = bridge_post_pfil(*mp);
3225                         if (error)
3226                                 break;
3227                 }
3228
3229                 if (pfil_member && ifp != NULL) {
3230                         error = pfil_run_hooks(&inet_pfil_hook, mp, ifp, dir);
3231                         if (*mp == NULL || error != 0) /* filter may consume */
3232                                 break;
3233                         error = bridge_post_pfil(*mp);
3234                         if (error)
3235                                 break;
3236                 }
3237
3238                 if (pfil_bridge && dir == PFIL_IN && bifp != NULL) {
3239                         error = pfil_run_hooks(&inet_pfil_hook, mp, bifp, dir);
3240                         if (*mp == NULL || error != 0) /* filter may consume */
3241                                 break;
3242                         error = bridge_post_pfil(*mp);
3243                         if (error)
3244                                 break;
3245                 }
3246
3247                 /* check if we need to fragment the packet */
3248                 if (pfil_member && ifp != NULL && dir == PFIL_OUT) {
3249                         i = (*mp)->m_pkthdr.len;
3250                         if (i > ifp->if_mtu) {
3251                                 error = bridge_fragment(ifp, *mp, &eh2, snap,
3252                                             &llc1);
3253                                 return (error);
3254                         }
3255                 }
3256
3257                 /* Recalculate the ip checksum and restore byte ordering */
3258                 ip = mtod(*mp, struct ip *);
3259                 hlen = ip->ip_hl << 2;
3260                 if (hlen < sizeof(struct ip))
3261                         goto bad;
3262                 if (hlen > (*mp)->m_len) {
3263                         if ((*mp = m_pullup(*mp, hlen)) == 0)
3264                                 goto bad;
3265                         ip = mtod(*mp, struct ip *);
3266                         if (ip == NULL)
3267                                 goto bad;
3268                 }
3269                 ip->ip_len = htons(ip->ip_len);
3270                 ip->ip_off = htons(ip->ip_off);
3271                 ip->ip_sum = 0;
3272                 if (hlen == sizeof(struct ip))
3273                         ip->ip_sum = in_cksum_hdr(ip);
3274                 else
3275                         ip->ip_sum = in_cksum(*mp, hlen);
3276
3277                 break;
3278 #ifdef INET6
3279         case ETHERTYPE_IPV6 :
3280                 if (pfil_bridge && dir == PFIL_OUT && bifp != NULL)
3281                         error = pfil_run_hooks(&inet6_pfil_hook, mp, bifp,
3282                                         dir);
3283
3284                 if (*mp == NULL || error != 0) /* filter may consume */
3285                         break;
3286
3287                 if (pfil_member && ifp != NULL)
3288                         error = pfil_run_hooks(&inet6_pfil_hook, mp, ifp,
3289                                         dir);
3290
3291                 if (*mp == NULL || error != 0) /* filter may consume */
3292                         break;
3293
3294                 if (pfil_bridge && dir == PFIL_IN && bifp != NULL)
3295                         error = pfil_run_hooks(&inet6_pfil_hook, mp, bifp,
3296                                         dir);
3297                 break;
3298 #endif
3299         default :
3300                 error = 0;
3301                 break;
3302         }
3303
3304         if (*mp == NULL)
3305                 return (error);
3306         if (error != 0)
3307                 goto bad;
3308
3309         error = -1;
3310
3311         /*
3312          * Finally, put everything back the way it was and return
3313          */
3314         if (snap) {
3315                 M_PREPEND(*mp, sizeof(struct llc), MB_DONTWAIT);
3316                 if (*mp == NULL)
3317                         return (error);
3318                 bcopy(&llc1, mtod(*mp, caddr_t), sizeof(struct llc));
3319         }
3320
3321         M_PREPEND(*mp, ETHER_HDR_LEN, MB_DONTWAIT);
3322         if (*mp == NULL)
3323                 return (error);
3324         bcopy(&eh2, mtod(*mp, caddr_t), ETHER_HDR_LEN);
3325
3326         return (0);
3327
3328 bad:
3329         m_freem(*mp);
3330         *mp = NULL;
3331         return (error);
3332 }
3333
3334 /*
3335  * Perform basic checks on header size since
3336  * pfil assumes ip_input has already processed
3337  * it for it.  Cut-and-pasted from ip_input.c.
3338  * Given how simple the IPv6 version is,
3339  * does the IPv4 version really need to be
3340  * this complicated?
3341  *
3342  * XXX Should we update ipstat here, or not?
3343  * XXX Right now we update ipstat but not
3344  * XXX csum_counter.
3345  */
3346 static int
3347 bridge_ip_checkbasic(struct mbuf **mp)
3348 {
3349         struct mbuf *m = *mp;
3350         struct ip *ip;
3351         int len, hlen;
3352         u_short sum;
3353
3354         if (*mp == NULL)
3355                 return (-1);
3356 #if notyet
3357         if (IP_HDR_ALIGNED_P(mtod(m, caddr_t)) == 0) {
3358                 if ((m = m_copyup(m, sizeof(struct ip),
3359                         (max_linkhdr + 3) & ~3)) == NULL) {
3360                         /* XXXJRT new stat, please */
3361                         ipstat.ips_toosmall++;
3362                         goto bad;
3363                 }
3364         } else
3365 #endif
3366 #ifndef __predict_false
3367 #define __predict_false(x) x
3368 #endif
3369          if (__predict_false(m->m_len < sizeof (struct ip))) {
3370                 if ((m = m_pullup(m, sizeof (struct ip))) == NULL) {
3371                         ipstat.ips_toosmall++;
3372                         goto bad;
3373                 }
3374         }
3375         ip = mtod(m, struct ip *);
3376         if (ip == NULL) goto bad;
3377
3378         if (ip->ip_v != IPVERSION) {
3379                 ipstat.ips_badvers++;
3380                 goto bad;
3381         }
3382         hlen = ip->ip_hl << 2;
3383         if (hlen < sizeof(struct ip)) { /* minimum header length */
3384                 ipstat.ips_badhlen++;
3385                 goto bad;
3386         }
3387         if (hlen > m->m_len) {
3388                 if ((m = m_pullup(m, hlen)) == 0) {
3389                         ipstat.ips_badhlen++;
3390                         goto bad;
3391                 }
3392                 ip = mtod(m, struct ip *);
3393                 if (ip == NULL) goto bad;
3394         }
3395
3396         if (m->m_pkthdr.csum_flags & CSUM_IP_CHECKED) {
3397                 sum = !(m->m_pkthdr.csum_flags & CSUM_IP_VALID);
3398         } else {
3399                 if (hlen == sizeof(struct ip)) {
3400                         sum = in_cksum_hdr(ip);
3401                 } else {
3402                         sum = in_cksum(m, hlen);
3403                 }
3404         }
3405         if (sum) {
3406                 ipstat.ips_badsum++;
3407                 goto bad;
3408         }
3409
3410         /* Retrieve the packet length. */
3411         len = ntohs(ip->ip_len);
3412
3413         /*
3414          * Check for additional length bogosity
3415          */
3416         if (len < hlen) {
3417                 ipstat.ips_badlen++;
3418                 goto bad;
3419         }
3420
3421         /*
3422          * Check that the amount of data in the buffers
3423          * is as at least much as the IP header would have us expect.
3424          * Drop packet if shorter than we expect.
3425          */
3426         if (m->m_pkthdr.len < len) {
3427                 ipstat.ips_tooshort++;
3428                 goto bad;
3429         }
3430
3431         /* Checks out, proceed */
3432         *mp = m;
3433         return (0);
3434
3435 bad:
3436         *mp = m;
3437         return (-1);
3438 }
3439
3440 #ifdef INET6
3441 /*
3442  * Same as above, but for IPv6.
3443  * Cut-and-pasted from ip6_input.c.
3444  * XXX Should we update ip6stat, or not?
3445  */
3446 static int
3447 bridge_ip6_checkbasic(struct mbuf **mp)
3448 {
3449         struct mbuf *m = *mp;
3450         struct ip6_hdr *ip6;
3451
3452         /*
3453          * If the IPv6 header is not aligned, slurp it up into a new
3454          * mbuf with space for link headers, in the event we forward
3455          * it.  Otherwise, if it is aligned, make sure the entire base
3456          * IPv6 header is in the first mbuf of the chain.
3457          */
3458 #if notyet
3459         if (IP6_HDR_ALIGNED_P(mtod(m, caddr_t)) == 0) {
3460                 struct ifnet *inifp = m->m_pkthdr.rcvif;
3461                 if ((m = m_copyup(m, sizeof(struct ip6_hdr),
3462                             (max_linkhdr + 3) & ~3)) == NULL) {
3463                         /* XXXJRT new stat, please */
3464                         ip6stat.ip6s_toosmall++;
3465                         in6_ifstat_inc(inifp, ifs6_in_hdrerr);
3466                         goto bad;
3467                 }
3468         } else
3469 #endif
3470         if (__predict_false(m->m_len < sizeof(struct ip6_hdr))) {
3471                 struct ifnet *inifp = m->m_pkthdr.rcvif;
3472                 if ((m = m_pullup(m, sizeof(struct ip6_hdr))) == NULL) {
3473                         ip6stat.ip6s_toosmall++;
3474                         in6_ifstat_inc(inifp, ifs6_in_hdrerr);
3475                         goto bad;
3476                 }
3477         }
3478
3479         ip6 = mtod(m, struct ip6_hdr *);
3480
3481         if ((ip6->ip6_vfc & IPV6_VERSION_MASK) != IPV6_VERSION) {
3482                 ip6stat.ip6s_badvers++;
3483                 in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_hdrerr);
3484                 goto bad;
3485         }
3486
3487         /* Checks out, proceed */
3488         *mp = m;
3489         return (0);
3490
3491 bad:
3492         *mp = m;
3493         return (-1);
3494 }
3495 #endif /* INET6 */
3496
3497 /*
3498  * bridge_fragment:
3499  *
3500  *      Return a fragmented mbuf chain.
3501  */
3502 static int
3503 bridge_fragment(struct ifnet *ifp, struct mbuf *m, struct ether_header *eh,
3504     int snap, struct llc *llc)
3505 {
3506         struct mbuf *m0;
3507         struct ip *ip;
3508         int error = -1;
3509
3510         if (m->m_len < sizeof(struct ip) &&
3511             (m = m_pullup(m, sizeof(struct ip))) == NULL)
3512                 goto out;
3513         ip = mtod(m, struct ip *);
3514
3515         error = ip_fragment(ip, &m, ifp->if_mtu, ifp->if_hwassist,
3516                     CSUM_DELAY_IP);
3517         if (error)
3518                 goto out;
3519
3520         /* walk the chain and re-add the Ethernet header */
3521         for (m0 = m; m0; m0 = m0->m_nextpkt) {
3522                 if (error == 0) {
3523                         if (snap) {
3524                                 M_PREPEND(m0, sizeof(struct llc), MB_DONTWAIT);
3525                                 if (m0 == NULL) {
3526                                         error = ENOBUFS;
3527                                         continue;
3528                                 }
3529                                 bcopy(llc, mtod(m0, caddr_t),
3530                                     sizeof(struct llc));
3531                         }
3532                         M_PREPEND(m0, ETHER_HDR_LEN, MB_DONTWAIT);
3533                         if (m0 == NULL) {
3534                                 error = ENOBUFS;
3535                                 continue;
3536                         }
3537                         bcopy(eh, mtod(m0, caddr_t), ETHER_HDR_LEN);
3538                 } else 
3539                         m_freem(m);
3540         }
3541
3542         if (error == 0)
3543                 ipstat.ips_fragmented++;
3544
3545         return (error);
3546
3547 out:
3548         if (m != NULL)
3549                 m_freem(m);
3550         return (error);
3551 }
3552
3553 static void
3554 bridge_enqueue_handler(struct netmsg *nmsg)
3555 {
3556         struct netmsg_packet *nmp;
3557         struct ifnet *dst_ifp;
3558         struct mbuf *m;
3559
3560         nmp = (struct netmsg_packet *)nmsg;
3561         m = nmp->nm_packet;
3562         dst_ifp = nmp->nm_netmsg.nm_lmsg.u.ms_resultp;
3563
3564         bridge_handoff(dst_ifp, m);
3565 }
3566
3567 static void
3568 bridge_pfil_enqueue_handler(struct netmsg *nmsg)
3569 {
3570         struct netmsg_packet *nmp;
3571         struct ifnet *dst_ifp;
3572         struct mbuf *m;
3573
3574         nmp = (struct netmsg_packet *)nmsg;
3575         m = nmp->nm_packet;
3576         dst_ifp = nmp->nm_netmsg.nm_lmsg.u.ms_resultp;
3577
3578         /*
3579          * Filter on the output interface. Pass a NULL bridge interface
3580          * pointer so we do not redundantly filter on the bridge for
3581          * each interface we broadcast on.
3582          */
3583         if (inet_pfil_hook.ph_hashooks > 0
3584 #ifdef INET6
3585             || inet6_pfil_hook.ph_hashooks > 0
3586 #endif
3587             ) {
3588                 if (bridge_pfil(&m, NULL, dst_ifp, PFIL_OUT) != 0)
3589                         return;
3590                 if (m == NULL)
3591                         return;
3592         }
3593         bridge_handoff(dst_ifp, m);
3594 }
3595
3596 static void
3597 bridge_handoff(struct ifnet *dst_ifp, struct mbuf *m)
3598 {
3599         struct mbuf *m0;
3600
3601         lwkt_serialize_enter(dst_ifp->if_serializer);
3602
3603         /* We may be sending a fragment so traverse the mbuf */
3604         for (; m; m = m0) {
3605                 struct altq_pktattr pktattr;
3606
3607                 m0 = m->m_nextpkt;
3608                 m->m_nextpkt = NULL;
3609
3610                 if (ifq_is_enabled(&dst_ifp->if_snd))
3611                         altq_etherclassify(&dst_ifp->if_snd, m, &pktattr);
3612
3613                 ifq_handoff(dst_ifp, m, &pktattr);
3614         }
3615
3616         lwkt_serialize_exit(dst_ifp->if_serializer);
3617 }
3618
3619 static void
3620 bridge_control_dispatch(struct netmsg *nmsg)
3621 {
3622         struct netmsg_brctl *bc_msg = (struct netmsg_brctl *)nmsg;
3623         struct ifnet *bifp = bc_msg->bc_sc->sc_ifp;
3624         int error;
3625
3626         lwkt_serialize_enter(bifp->if_serializer);
3627         error = bc_msg->bc_func(bc_msg->bc_sc, bc_msg->bc_arg);
3628         lwkt_serialize_exit(bifp->if_serializer);
3629
3630         lwkt_replymsg(&nmsg->nm_lmsg, error);
3631 }
3632
3633 static int
3634 bridge_control(struct bridge_softc *sc, u_long cmd,
3635                bridge_ctl_t bc_func, void *bc_arg)
3636 {
3637         struct ifnet *bifp = sc->sc_ifp;
3638         struct netmsg_brctl bc_msg;
3639         struct netmsg *nmsg;
3640         int error;
3641
3642         ASSERT_SERIALIZED(bifp->if_serializer);
3643
3644         bzero(&bc_msg, sizeof(bc_msg));
3645         nmsg = &bc_msg.bc_nmsg;
3646
3647         netmsg_init(nmsg, &curthread->td_msgport, 0, bridge_control_dispatch);
3648         bc_msg.bc_func = bc_func;
3649         bc_msg.bc_sc = sc;
3650         bc_msg.bc_arg = bc_arg;
3651
3652         lwkt_serialize_exit(bifp->if_serializer);
3653         error = lwkt_domsg(BRIDGE_CFGPORT, &nmsg->nm_lmsg, 0);
3654         lwkt_serialize_enter(bifp->if_serializer);
3655         return error;
3656 }
3657
3658 static void
3659 bridge_add_bif_handler(struct netmsg *nmsg)
3660 {
3661         struct netmsg_braddbif *amsg = (struct netmsg_braddbif *)nmsg;
3662         struct bridge_softc *sc;
3663         struct bridge_iflist *bif;
3664
3665         sc = amsg->br_softc;
3666
3667         bif = kmalloc(sizeof(*bif), M_DEVBUF, M_WAITOK | M_ZERO);
3668         bif->bif_ifp = amsg->br_bif_ifp;
3669         bif->bif_flags = IFBIF_LEARNING | IFBIF_DISCOVER;
3670         bif->bif_onlist = 1;
3671         bif->bif_info = amsg->br_bif_info;
3672
3673         LIST_INSERT_HEAD(&sc->sc_iflists[mycpuid], bif, bif_next);
3674
3675         ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
3676 }
3677
3678 static void
3679 bridge_add_bif(struct bridge_softc *sc, struct bridge_ifinfo *bif_info,
3680                struct ifnet *ifp)
3681 {
3682         struct netmsg_braddbif amsg;
3683
3684         ASSERT_NOT_SERIALIZED(sc->sc_ifp->if_serializer);
3685
3686         netmsg_init(&amsg.br_nmsg, &curthread->td_msgport, 0,
3687                     bridge_add_bif_handler);
3688         amsg.br_softc = sc;
3689         amsg.br_bif_info = bif_info;
3690         amsg.br_bif_ifp = ifp;
3691
3692         ifnet_domsg(&amsg.br_nmsg.nm_lmsg, 0);
3693 }
3694
3695 static void
3696 bridge_del_bif_handler(struct netmsg *nmsg)
3697 {
3698         struct netmsg_brdelbif *dmsg = (struct netmsg_brdelbif *)nmsg;
3699         struct bridge_softc *sc;
3700         struct bridge_iflist *bif;
3701
3702         sc = dmsg->br_softc;
3703
3704         /*
3705          * Locate the bif associated with the br_bif_info
3706          * on the current CPU
3707          */
3708         bif = bridge_lookup_member_ifinfo(sc, dmsg->br_bif_info);
3709         KKASSERT(bif != NULL && bif->bif_onlist);
3710
3711         /* Remove the bif from the current CPU's iflist */
3712         bif->bif_onlist = 0;
3713         LIST_REMOVE(bif, bif_next);
3714
3715         /* Save the removed bif for later freeing */
3716         LIST_INSERT_HEAD(dmsg->br_bif_list, bif, bif_next);
3717
3718         ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
3719 }
3720
3721 static void
3722 bridge_del_bif(struct bridge_softc *sc, struct bridge_ifinfo *bif_info,
3723                struct bridge_iflist_head *saved_bifs)
3724 {
3725         struct netmsg_brdelbif dmsg;
3726
3727         ASSERT_NOT_SERIALIZED(sc->sc_ifp->if_serializer);
3728
3729         netmsg_init(&dmsg.br_nmsg, &curthread->td_msgport, 0,
3730                     bridge_del_bif_handler);
3731         dmsg.br_softc = sc;
3732         dmsg.br_bif_info = bif_info;
3733         dmsg.br_bif_list = saved_bifs;
3734
3735         ifnet_domsg(&dmsg.br_nmsg.nm_lmsg, 0);
3736 }
3737
3738 static void
3739 bridge_set_bifflags_handler(struct netmsg *nmsg)
3740 {
3741         struct netmsg_brsflags *smsg = (struct netmsg_brsflags *)nmsg;
3742         struct bridge_softc *sc;
3743         struct bridge_iflist *bif;
3744
3745         sc = smsg->br_softc;
3746
3747         /*
3748          * Locate the bif associated with the br_bif_info
3749          * on the current CPU
3750          */
3751         bif = bridge_lookup_member_ifinfo(sc, smsg->br_bif_info);
3752         KKASSERT(bif != NULL && bif->bif_onlist);
3753
3754         bif->bif_flags = smsg->br_bif_flags;
3755
3756         ifnet_forwardmsg(&nmsg->nm_lmsg, mycpuid + 1);
3757 }
3758
3759 static void
3760 bridge_set_bifflags(struct bridge_softc *sc, struct bridge_ifinfo *bif_info,
3761                     uint32_t bif_flags)
3762 {
3763         struct netmsg_brsflags smsg;
3764
3765         ASSERT_NOT_SERIALIZED(sc->sc_ifp->if_serializer);
3766
3767         netmsg_init(&smsg.br_nmsg, &curthread->td_msgport, 0,
3768                     bridge_set_bifflags_handler);
3769         smsg.br_softc = sc;
3770         smsg.br_bif_info = bif_info;
3771         smsg.br_bif_flags = bif_flags;
3772
3773         ifnet_domsg(&smsg.br_nmsg.nm_lmsg, 0);
3774 }