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