]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/net/if_lagg.c
Remove nested epochs from lagg(4).
[FreeBSD/FreeBSD.git] / sys / net / if_lagg.c
1 /*      $OpenBSD: if_trunk.c,v 1.30 2007/01/31 06:20:19 reyk Exp $      */
2
3 /*
4  * Copyright (c) 2005, 2006 Reyk Floeter <reyk@openbsd.org>
5  * Copyright (c) 2007 Andrew Thompson <thompsa@FreeBSD.org>
6  * Copyright (c) 2014, 2016 Marcelo Araujo <araujo@FreeBSD.org>
7  *
8  * Permission to use, copy, modify, and distribute this software for any
9  * purpose with or without fee is hereby granted, provided that the above
10  * copyright notice and this permission notice appear in all copies.
11  *
12  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
13  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
14  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
15  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
16  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
17  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
18  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19  */
20
21 #include <sys/cdefs.h>
22 __FBSDID("$FreeBSD$");
23
24 #include "opt_inet.h"
25 #include "opt_inet6.h"
26 #include "opt_ratelimit.h"
27
28 #include <sys/param.h>
29 #include <sys/kernel.h>
30 #include <sys/malloc.h>
31 #include <sys/mbuf.h>
32 #include <sys/queue.h>
33 #include <sys/socket.h>
34 #include <sys/sockio.h>
35 #include <sys/sysctl.h>
36 #include <sys/module.h>
37 #include <sys/priv.h>
38 #include <sys/systm.h>
39 #include <sys/proc.h>
40 #include <sys/lock.h>
41 #include <sys/rmlock.h>
42 #include <sys/sx.h>
43 #include <sys/taskqueue.h>
44 #include <sys/eventhandler.h>
45
46 #include <net/ethernet.h>
47 #include <net/if.h>
48 #include <net/if_clone.h>
49 #include <net/if_arp.h>
50 #include <net/if_dl.h>
51 #include <net/if_media.h>
52 #include <net/if_types.h>
53 #include <net/if_var.h>
54 #include <net/bpf.h>
55 #include <net/vnet.h>
56
57 #if defined(INET) || defined(INET6)
58 #include <netinet/in.h>
59 #include <netinet/ip.h>
60 #endif
61 #ifdef INET
62 #include <netinet/in_systm.h>
63 #include <netinet/if_ether.h>
64 #endif
65
66 #ifdef INET6
67 #include <netinet/ip6.h>
68 #include <netinet6/in6_var.h>
69 #include <netinet6/in6_ifattach.h>
70 #endif
71
72 #include <net/if_vlan_var.h>
73 #include <net/if_lagg.h>
74 #include <net/ieee8023ad_lacp.h>
75
76 #define LAGG_RLOCK()    struct epoch_tracker lagg_et; epoch_enter_preempt(net_epoch_preempt, &lagg_et)
77 #define LAGG_RUNLOCK()  epoch_exit_preempt(net_epoch_preempt, &lagg_et)
78 #define LAGG_RLOCK_ASSERT()     MPASS(in_epoch(net_epoch_preempt))
79 #define LAGG_UNLOCK_ASSERT()    MPASS(!in_epoch(net_epoch_preempt))
80
81 #define LAGG_SX_INIT(_sc)       sx_init(&(_sc)->sc_sx, "if_lagg sx")
82 #define LAGG_SX_DESTROY(_sc)    sx_destroy(&(_sc)->sc_sx)
83 #define LAGG_XLOCK(_sc)         sx_xlock(&(_sc)->sc_sx)
84 #define LAGG_XUNLOCK(_sc)       sx_xunlock(&(_sc)->sc_sx)
85 #define LAGG_SXLOCK_ASSERT(_sc) sx_assert(&(_sc)->sc_sx, SA_LOCKED)
86 #define LAGG_XLOCK_ASSERT(_sc)  sx_assert(&(_sc)->sc_sx, SA_XLOCKED)
87
88 /* Special flags we should propagate to the lagg ports. */
89 static struct {
90         int flag;
91         int (*func)(struct ifnet *, int);
92 } lagg_pflags[] = {
93         {IFF_PROMISC, ifpromisc},
94         {IFF_ALLMULTI, if_allmulti},
95         {0, NULL}
96 };
97
98 VNET_DEFINE(SLIST_HEAD(__trhead, lagg_softc), lagg_list); /* list of laggs */
99 #define V_lagg_list     VNET(lagg_list)
100 VNET_DEFINE_STATIC(struct mtx, lagg_list_mtx);
101 #define V_lagg_list_mtx VNET(lagg_list_mtx)
102 #define LAGG_LIST_LOCK_INIT(x)          mtx_init(&V_lagg_list_mtx, \
103                                         "if_lagg list", NULL, MTX_DEF)
104 #define LAGG_LIST_LOCK_DESTROY(x)       mtx_destroy(&V_lagg_list_mtx)
105 #define LAGG_LIST_LOCK(x)               mtx_lock(&V_lagg_list_mtx)
106 #define LAGG_LIST_UNLOCK(x)             mtx_unlock(&V_lagg_list_mtx)
107 eventhandler_tag        lagg_detach_cookie = NULL;
108
109 static int      lagg_clone_create(struct if_clone *, int, caddr_t);
110 static void     lagg_clone_destroy(struct ifnet *);
111 VNET_DEFINE_STATIC(struct if_clone *, lagg_cloner);
112 #define V_lagg_cloner   VNET(lagg_cloner)
113 static const char laggname[] = "lagg";
114
115 static void     lagg_capabilities(struct lagg_softc *);
116 static int      lagg_port_create(struct lagg_softc *, struct ifnet *);
117 static int      lagg_port_destroy(struct lagg_port *, int);
118 static struct mbuf *lagg_input(struct ifnet *, struct mbuf *);
119 static void     lagg_linkstate(struct lagg_softc *);
120 static void     lagg_port_state(struct ifnet *, int);
121 static int      lagg_port_ioctl(struct ifnet *, u_long, caddr_t);
122 static int      lagg_port_output(struct ifnet *, struct mbuf *,
123                     const struct sockaddr *, struct route *);
124 static void     lagg_port_ifdetach(void *arg __unused, struct ifnet *);
125 #ifdef LAGG_PORT_STACKING
126 static int      lagg_port_checkstacking(struct lagg_softc *);
127 #endif
128 static void     lagg_port2req(struct lagg_port *, struct lagg_reqport *);
129 static void     lagg_init(void *);
130 static void     lagg_stop(struct lagg_softc *);
131 static int      lagg_ioctl(struct ifnet *, u_long, caddr_t);
132 #ifdef RATELIMIT
133 static int      lagg_snd_tag_alloc(struct ifnet *,
134                     union if_snd_tag_alloc_params *,
135                     struct m_snd_tag **);
136 static void     lagg_snd_tag_free(struct m_snd_tag *);
137 #endif
138 static int      lagg_setmulti(struct lagg_port *);
139 static int      lagg_clrmulti(struct lagg_port *);
140 static  int     lagg_setcaps(struct lagg_port *, int cap);
141 static  int     lagg_setflag(struct lagg_port *, int, int,
142                     int (*func)(struct ifnet *, int));
143 static  int     lagg_setflags(struct lagg_port *, int status);
144 static uint64_t lagg_get_counter(struct ifnet *ifp, ift_counter cnt);
145 static int      lagg_transmit(struct ifnet *, struct mbuf *);
146 static void     lagg_qflush(struct ifnet *);
147 static int      lagg_media_change(struct ifnet *);
148 static void     lagg_media_status(struct ifnet *, struct ifmediareq *);
149 static struct lagg_port *lagg_link_active(struct lagg_softc *,
150             struct lagg_port *);
151
152 /* Simple round robin */
153 static void     lagg_rr_attach(struct lagg_softc *);
154 static int      lagg_rr_start(struct lagg_softc *, struct mbuf *);
155 static struct mbuf *lagg_rr_input(struct lagg_softc *, struct lagg_port *,
156                     struct mbuf *);
157
158 /* Active failover */
159 static int      lagg_fail_start(struct lagg_softc *, struct mbuf *);
160 static struct mbuf *lagg_fail_input(struct lagg_softc *, struct lagg_port *,
161                     struct mbuf *);
162
163 /* Loadbalancing */
164 static void     lagg_lb_attach(struct lagg_softc *);
165 static void     lagg_lb_detach(struct lagg_softc *);
166 static int      lagg_lb_port_create(struct lagg_port *);
167 static void     lagg_lb_port_destroy(struct lagg_port *);
168 static int      lagg_lb_start(struct lagg_softc *, struct mbuf *);
169 static struct mbuf *lagg_lb_input(struct lagg_softc *, struct lagg_port *,
170                     struct mbuf *);
171 static int      lagg_lb_porttable(struct lagg_softc *, struct lagg_port *);
172
173 /* Broadcast */
174 static int    lagg_bcast_start(struct lagg_softc *, struct mbuf *);
175 static struct mbuf *lagg_bcast_input(struct lagg_softc *, struct lagg_port *,
176                     struct mbuf *);
177
178 /* 802.3ad LACP */
179 static void     lagg_lacp_attach(struct lagg_softc *);
180 static void     lagg_lacp_detach(struct lagg_softc *);
181 static int      lagg_lacp_start(struct lagg_softc *, struct mbuf *);
182 static struct mbuf *lagg_lacp_input(struct lagg_softc *, struct lagg_port *,
183                     struct mbuf *);
184 static void     lagg_lacp_lladdr(struct lagg_softc *);
185
186 /* lagg protocol table */
187 static const struct lagg_proto {
188         lagg_proto      pr_num;
189         void            (*pr_attach)(struct lagg_softc *);
190         void            (*pr_detach)(struct lagg_softc *);
191         int             (*pr_start)(struct lagg_softc *, struct mbuf *);
192         struct mbuf *   (*pr_input)(struct lagg_softc *, struct lagg_port *,
193                             struct mbuf *);
194         int             (*pr_addport)(struct lagg_port *);
195         void            (*pr_delport)(struct lagg_port *);
196         void            (*pr_linkstate)(struct lagg_port *);
197         void            (*pr_init)(struct lagg_softc *);
198         void            (*pr_stop)(struct lagg_softc *);
199         void            (*pr_lladdr)(struct lagg_softc *);
200         void            (*pr_request)(struct lagg_softc *, void *);
201         void            (*pr_portreq)(struct lagg_port *, void *);
202 } lagg_protos[] = {
203     {
204         .pr_num = LAGG_PROTO_NONE
205     },
206     {
207         .pr_num = LAGG_PROTO_ROUNDROBIN,
208         .pr_attach = lagg_rr_attach,
209         .pr_start = lagg_rr_start,
210         .pr_input = lagg_rr_input,
211     },
212     {
213         .pr_num = LAGG_PROTO_FAILOVER,
214         .pr_start = lagg_fail_start,
215         .pr_input = lagg_fail_input,
216     },
217     {
218         .pr_num = LAGG_PROTO_LOADBALANCE,
219         .pr_attach = lagg_lb_attach,
220         .pr_detach = lagg_lb_detach,
221         .pr_start = lagg_lb_start,
222         .pr_input = lagg_lb_input,
223         .pr_addport = lagg_lb_port_create,
224         .pr_delport = lagg_lb_port_destroy,
225     },
226     {
227         .pr_num = LAGG_PROTO_LACP,
228         .pr_attach = lagg_lacp_attach,
229         .pr_detach = lagg_lacp_detach,
230         .pr_start = lagg_lacp_start,
231         .pr_input = lagg_lacp_input,
232         .pr_addport = lacp_port_create,
233         .pr_delport = lacp_port_destroy,
234         .pr_linkstate = lacp_linkstate,
235         .pr_init = lacp_init,
236         .pr_stop = lacp_stop,
237         .pr_lladdr = lagg_lacp_lladdr,
238         .pr_request = lacp_req,
239         .pr_portreq = lacp_portreq,
240     },
241     {
242         .pr_num = LAGG_PROTO_BROADCAST,
243         .pr_start = lagg_bcast_start,
244         .pr_input = lagg_bcast_input,
245     },
246 };
247
248 SYSCTL_DECL(_net_link);
249 SYSCTL_NODE(_net_link, OID_AUTO, lagg, CTLFLAG_RW, 0,
250     "Link Aggregation");
251
252 /* Allow input on any failover links */
253 VNET_DEFINE_STATIC(int, lagg_failover_rx_all);
254 #define V_lagg_failover_rx_all  VNET(lagg_failover_rx_all)
255 SYSCTL_INT(_net_link_lagg, OID_AUTO, failover_rx_all, CTLFLAG_RW | CTLFLAG_VNET,
256     &VNET_NAME(lagg_failover_rx_all), 0,
257     "Accept input from any interface in a failover lagg");
258
259 /* Default value for using flowid */
260 VNET_DEFINE_STATIC(int, def_use_flowid) = 0;
261 #define V_def_use_flowid        VNET(def_use_flowid)
262 SYSCTL_INT(_net_link_lagg, OID_AUTO, default_use_flowid, CTLFLAG_RWTUN,
263     &VNET_NAME(def_use_flowid), 0,
264     "Default setting for using flow id for load sharing");
265
266 /* Default value for flowid shift */
267 VNET_DEFINE_STATIC(int, def_flowid_shift) = 16;
268 #define V_def_flowid_shift      VNET(def_flowid_shift)
269 SYSCTL_INT(_net_link_lagg, OID_AUTO, default_flowid_shift, CTLFLAG_RWTUN,
270     &VNET_NAME(def_flowid_shift), 0,
271     "Default setting for flowid shift for load sharing");
272
273 static void
274 vnet_lagg_init(const void *unused __unused)
275 {
276
277         LAGG_LIST_LOCK_INIT();
278         SLIST_INIT(&V_lagg_list);
279         V_lagg_cloner = if_clone_simple(laggname, lagg_clone_create,
280             lagg_clone_destroy, 0);
281 }
282 VNET_SYSINIT(vnet_lagg_init, SI_SUB_PROTO_IFATTACHDOMAIN, SI_ORDER_ANY,
283     vnet_lagg_init, NULL);
284
285 static void
286 vnet_lagg_uninit(const void *unused __unused)
287 {
288
289         if_clone_detach(V_lagg_cloner);
290         LAGG_LIST_LOCK_DESTROY();
291 }
292 VNET_SYSUNINIT(vnet_lagg_uninit, SI_SUB_INIT_IF, SI_ORDER_ANY,
293     vnet_lagg_uninit, NULL);
294
295 static int
296 lagg_modevent(module_t mod, int type, void *data)
297 {
298
299         switch (type) {
300         case MOD_LOAD:
301                 lagg_input_p = lagg_input;
302                 lagg_linkstate_p = lagg_port_state;
303                 lagg_detach_cookie = EVENTHANDLER_REGISTER(
304                     ifnet_departure_event, lagg_port_ifdetach, NULL,
305                     EVENTHANDLER_PRI_ANY);
306                 break;
307         case MOD_UNLOAD:
308                 EVENTHANDLER_DEREGISTER(ifnet_departure_event,
309                     lagg_detach_cookie);
310                 lagg_input_p = NULL;
311                 lagg_linkstate_p = NULL;
312                 break;
313         default:
314                 return (EOPNOTSUPP);
315         }
316         return (0);
317 }
318
319 static moduledata_t lagg_mod = {
320         "if_lagg",
321         lagg_modevent,
322         0
323 };
324
325 DECLARE_MODULE(if_lagg, lagg_mod, SI_SUB_PSEUDO, SI_ORDER_ANY);
326 MODULE_VERSION(if_lagg, 1);
327
328 static void
329 lagg_proto_attach(struct lagg_softc *sc, lagg_proto pr)
330 {
331
332         LAGG_XLOCK_ASSERT(sc);
333         KASSERT(sc->sc_proto == LAGG_PROTO_NONE, ("%s: sc %p has proto",
334             __func__, sc));
335
336         if (sc->sc_ifflags & IFF_DEBUG)
337                 if_printf(sc->sc_ifp, "using proto %u\n", pr);
338
339         if (lagg_protos[pr].pr_attach != NULL)
340                 lagg_protos[pr].pr_attach(sc);
341         sc->sc_proto = pr;
342 }
343
344 static void
345 lagg_proto_detach(struct lagg_softc *sc)
346 {
347         lagg_proto pr;
348
349         LAGG_XLOCK_ASSERT(sc);
350         pr = sc->sc_proto;
351         sc->sc_proto = LAGG_PROTO_NONE;
352
353         if (lagg_protos[pr].pr_detach != NULL)
354                 lagg_protos[pr].pr_detach(sc);
355 }
356
357 static int
358 lagg_proto_start(struct lagg_softc *sc, struct mbuf *m)
359 {
360
361         return (lagg_protos[sc->sc_proto].pr_start(sc, m));
362 }
363
364 static struct mbuf *
365 lagg_proto_input(struct lagg_softc *sc, struct lagg_port *lp, struct mbuf *m)
366 {
367
368         return (lagg_protos[sc->sc_proto].pr_input(sc, lp, m));
369 }
370
371 static int
372 lagg_proto_addport(struct lagg_softc *sc, struct lagg_port *lp)
373 {
374
375         if (lagg_protos[sc->sc_proto].pr_addport == NULL)
376                 return (0);
377         else
378                 return (lagg_protos[sc->sc_proto].pr_addport(lp));
379 }
380
381 static void
382 lagg_proto_delport(struct lagg_softc *sc, struct lagg_port *lp)
383 {
384
385         if (lagg_protos[sc->sc_proto].pr_delport != NULL)
386                 lagg_protos[sc->sc_proto].pr_delport(lp);
387 }
388
389 static void
390 lagg_proto_linkstate(struct lagg_softc *sc, struct lagg_port *lp)
391 {
392
393         if (lagg_protos[sc->sc_proto].pr_linkstate != NULL)
394                 lagg_protos[sc->sc_proto].pr_linkstate(lp);
395 }
396
397 static void
398 lagg_proto_init(struct lagg_softc *sc)
399 {
400
401         if (lagg_protos[sc->sc_proto].pr_init != NULL)
402                 lagg_protos[sc->sc_proto].pr_init(sc);
403 }
404
405 static void
406 lagg_proto_stop(struct lagg_softc *sc)
407 {
408
409         if (lagg_protos[sc->sc_proto].pr_stop != NULL)
410                 lagg_protos[sc->sc_proto].pr_stop(sc);
411 }
412
413 static void
414 lagg_proto_lladdr(struct lagg_softc *sc)
415 {
416
417         if (lagg_protos[sc->sc_proto].pr_lladdr != NULL)
418                 lagg_protos[sc->sc_proto].pr_lladdr(sc);
419 }
420
421 static void
422 lagg_proto_request(struct lagg_softc *sc, void *v)
423 {
424
425         if (lagg_protos[sc->sc_proto].pr_request != NULL)
426                 lagg_protos[sc->sc_proto].pr_request(sc, v);
427 }
428
429 static void
430 lagg_proto_portreq(struct lagg_softc *sc, struct lagg_port *lp, void *v)
431 {
432
433         if (lagg_protos[sc->sc_proto].pr_portreq != NULL)
434                 lagg_protos[sc->sc_proto].pr_portreq(lp, v);
435 }
436
437 /*
438  * This routine is run via an vlan
439  * config EVENT
440  */
441 static void
442 lagg_register_vlan(void *arg, struct ifnet *ifp, u_int16_t vtag)
443 {
444         struct lagg_softc *sc = ifp->if_softc;
445         struct lagg_port *lp;
446
447         if (ifp->if_softc !=  arg)   /* Not our event */
448                 return;
449
450         LAGG_RLOCK();
451         CK_SLIST_FOREACH(lp, &sc->sc_ports, lp_entries)
452                 EVENTHANDLER_INVOKE(vlan_config, lp->lp_ifp, vtag);
453         LAGG_RUNLOCK();
454 }
455
456 /*
457  * This routine is run via an vlan
458  * unconfig EVENT
459  */
460 static void
461 lagg_unregister_vlan(void *arg, struct ifnet *ifp, u_int16_t vtag)
462 {
463         struct lagg_softc *sc = ifp->if_softc;
464         struct lagg_port *lp;
465
466         if (ifp->if_softc !=  arg)   /* Not our event */
467                 return;
468
469         LAGG_RLOCK();
470         CK_SLIST_FOREACH(lp, &sc->sc_ports, lp_entries)
471                 EVENTHANDLER_INVOKE(vlan_unconfig, lp->lp_ifp, vtag);
472         LAGG_RUNLOCK();
473 }
474
475 static int
476 lagg_clone_create(struct if_clone *ifc, int unit, caddr_t params)
477 {
478         struct lagg_softc *sc;
479         struct ifnet *ifp;
480         static const u_char eaddr[6];   /* 00:00:00:00:00:00 */
481
482         sc = malloc(sizeof(*sc), M_DEVBUF, M_WAITOK|M_ZERO);
483         ifp = sc->sc_ifp = if_alloc(IFT_ETHER);
484         if (ifp == NULL) {
485                 free(sc, M_DEVBUF);
486                 return (ENOSPC);
487         }
488         LAGG_SX_INIT(sc);
489
490         LAGG_XLOCK(sc);
491         if (V_def_use_flowid)
492                 sc->sc_opts |= LAGG_OPT_USE_FLOWID;
493         sc->flowid_shift = V_def_flowid_shift;
494
495         /* Hash all layers by default */
496         sc->sc_flags = MBUF_HASHFLAG_L2|MBUF_HASHFLAG_L3|MBUF_HASHFLAG_L4;
497
498         lagg_proto_attach(sc, LAGG_PROTO_DEFAULT);
499
500         CK_SLIST_INIT(&sc->sc_ports);
501
502         /* Initialise pseudo media types */
503         ifmedia_init(&sc->sc_media, 0, lagg_media_change,
504             lagg_media_status);
505         ifmedia_add(&sc->sc_media, IFM_ETHER | IFM_AUTO, 0, NULL);
506         ifmedia_set(&sc->sc_media, IFM_ETHER | IFM_AUTO);
507
508         if_initname(ifp, laggname, unit);
509         ifp->if_softc = sc;
510         ifp->if_transmit = lagg_transmit;
511         ifp->if_qflush = lagg_qflush;
512         ifp->if_init = lagg_init;
513         ifp->if_ioctl = lagg_ioctl;
514         ifp->if_get_counter = lagg_get_counter;
515         ifp->if_flags = IFF_SIMPLEX | IFF_BROADCAST | IFF_MULTICAST;
516 #ifdef RATELIMIT
517         ifp->if_snd_tag_alloc = lagg_snd_tag_alloc;
518         ifp->if_snd_tag_free = lagg_snd_tag_free;
519 #endif
520         ifp->if_capenable = ifp->if_capabilities = IFCAP_HWSTATS;
521
522         /*
523          * Attach as an ordinary ethernet device, children will be attached
524          * as special device IFT_IEEE8023ADLAG.
525          */
526         ether_ifattach(ifp, eaddr);
527
528         sc->vlan_attach = EVENTHANDLER_REGISTER(vlan_config,
529                 lagg_register_vlan, sc, EVENTHANDLER_PRI_FIRST);
530         sc->vlan_detach = EVENTHANDLER_REGISTER(vlan_unconfig,
531                 lagg_unregister_vlan, sc, EVENTHANDLER_PRI_FIRST);
532
533         /* Insert into the global list of laggs */
534         LAGG_LIST_LOCK();
535         SLIST_INSERT_HEAD(&V_lagg_list, sc, sc_entries);
536         LAGG_LIST_UNLOCK();
537         LAGG_XUNLOCK(sc);
538
539         return (0);
540 }
541
542 static void
543 lagg_clone_destroy(struct ifnet *ifp)
544 {
545         struct lagg_softc *sc = (struct lagg_softc *)ifp->if_softc;
546         struct lagg_port *lp;
547
548         LAGG_XLOCK(sc);
549         sc->sc_destroying = 1;
550         lagg_stop(sc);
551         ifp->if_flags &= ~IFF_UP;
552
553         EVENTHANDLER_DEREGISTER(vlan_config, sc->vlan_attach);
554         EVENTHANDLER_DEREGISTER(vlan_unconfig, sc->vlan_detach);
555
556         /* Shutdown and remove lagg ports */
557         while ((lp = CK_SLIST_FIRST(&sc->sc_ports)) != NULL)
558                 lagg_port_destroy(lp, 1);
559
560         /* Unhook the aggregation protocol */
561         lagg_proto_detach(sc);
562         LAGG_XUNLOCK(sc);
563
564         ifmedia_removeall(&sc->sc_media);
565         ether_ifdetach(ifp);
566         if_free(ifp);
567
568         LAGG_LIST_LOCK();
569         SLIST_REMOVE(&V_lagg_list, sc, lagg_softc, sc_entries);
570         LAGG_LIST_UNLOCK();
571
572         LAGG_SX_DESTROY(sc);
573         free(sc, M_DEVBUF);
574 }
575
576 static void
577 lagg_capabilities(struct lagg_softc *sc)
578 {
579         struct lagg_port *lp;
580         int cap, ena, pena;
581         uint64_t hwa;
582         struct ifnet_hw_tsomax hw_tsomax;
583
584         LAGG_XLOCK_ASSERT(sc);
585
586         /* Get common enabled capabilities for the lagg ports */
587         ena = ~0;
588         CK_SLIST_FOREACH(lp, &sc->sc_ports, lp_entries)
589                 ena &= lp->lp_ifp->if_capenable;
590         ena = (ena == ~0 ? 0 : ena);
591
592         /*
593          * Apply common enabled capabilities back to the lagg ports.
594          * May require several iterations if they are dependent.
595          */
596         do {
597                 pena = ena;
598                 CK_SLIST_FOREACH(lp, &sc->sc_ports, lp_entries) {
599                         lagg_setcaps(lp, ena);
600                         ena &= lp->lp_ifp->if_capenable;
601                 }
602         } while (pena != ena);
603
604         /* Get other capabilities from the lagg ports */
605         cap = ~0;
606         hwa = ~(uint64_t)0;
607         memset(&hw_tsomax, 0, sizeof(hw_tsomax));
608         CK_SLIST_FOREACH(lp, &sc->sc_ports, lp_entries) {
609                 cap &= lp->lp_ifp->if_capabilities;
610                 hwa &= lp->lp_ifp->if_hwassist;
611                 if_hw_tsomax_common(lp->lp_ifp, &hw_tsomax);
612         }
613         cap = (cap == ~0 ? 0 : cap);
614         hwa = (hwa == ~(uint64_t)0 ? 0 : hwa);
615
616         if (sc->sc_ifp->if_capabilities != cap ||
617             sc->sc_ifp->if_capenable != ena ||
618             sc->sc_ifp->if_hwassist != hwa ||
619             if_hw_tsomax_update(sc->sc_ifp, &hw_tsomax) != 0) {
620                 sc->sc_ifp->if_capabilities = cap;
621                 sc->sc_ifp->if_capenable = ena;
622                 sc->sc_ifp->if_hwassist = hwa;
623                 getmicrotime(&sc->sc_ifp->if_lastchange);
624
625                 if (sc->sc_ifflags & IFF_DEBUG)
626                         if_printf(sc->sc_ifp,
627                             "capabilities 0x%08x enabled 0x%08x\n", cap, ena);
628         }
629 }
630
631 static int
632 lagg_port_create(struct lagg_softc *sc, struct ifnet *ifp)
633 {
634         struct lagg_softc *sc_ptr;
635         struct lagg_port *lp, *tlp;
636         struct ifreq ifr;
637         int error, i, oldmtu;
638         uint64_t *pval;
639
640         LAGG_XLOCK_ASSERT(sc);
641
642         if (sc->sc_ifp == ifp) {
643                 if_printf(sc->sc_ifp,
644                     "cannot add a lagg to itself as a port\n");
645                 return (EINVAL);
646         }
647
648         /* Limit the maximal number of lagg ports */
649         if (sc->sc_count >= LAGG_MAX_PORTS)
650                 return (ENOSPC);
651
652         /* Check if port has already been associated to a lagg */
653         if (ifp->if_lagg != NULL) {
654                 /* Port is already in the current lagg? */
655                 lp = (struct lagg_port *)ifp->if_lagg;
656                 if (lp->lp_softc == sc)
657                         return (EEXIST);
658                 return (EBUSY);
659         }
660
661         /* XXX Disallow non-ethernet interfaces (this should be any of 802) */
662         if (ifp->if_type != IFT_ETHER && ifp->if_type != IFT_L2VLAN)
663                 return (EPROTONOSUPPORT);
664
665         /* Allow the first Ethernet member to define the MTU */
666         oldmtu = -1;
667         if (CK_SLIST_EMPTY(&sc->sc_ports)) {
668                 sc->sc_ifp->if_mtu = ifp->if_mtu;
669         } else if (sc->sc_ifp->if_mtu != ifp->if_mtu) {
670                 if (ifp->if_ioctl == NULL) {
671                         if_printf(sc->sc_ifp, "cannot change MTU for %s\n",
672                             ifp->if_xname);
673                         return (EINVAL);
674                 }
675                 oldmtu = ifp->if_mtu;
676                 strlcpy(ifr.ifr_name, ifp->if_xname, sizeof(ifr.ifr_name));
677                 ifr.ifr_mtu = sc->sc_ifp->if_mtu;
678                 error = (*ifp->if_ioctl)(ifp, SIOCSIFMTU, (caddr_t)&ifr);
679                 if (error != 0) {
680                         if_printf(sc->sc_ifp, "invalid MTU for %s\n",
681                             ifp->if_xname);
682                         return (error);
683                 }
684                 ifr.ifr_mtu = oldmtu;
685         }
686
687         lp = malloc(sizeof(struct lagg_port), M_DEVBUF, M_WAITOK|M_ZERO);
688         lp->lp_softc = sc;
689
690         /* Check if port is a stacked lagg */
691         LAGG_LIST_LOCK();
692         SLIST_FOREACH(sc_ptr, &V_lagg_list, sc_entries) {
693                 if (ifp == sc_ptr->sc_ifp) {
694                         LAGG_LIST_UNLOCK();
695                         free(lp, M_DEVBUF);
696                         if (oldmtu != -1)
697                                 (*ifp->if_ioctl)(ifp, SIOCSIFMTU,
698                                     (caddr_t)&ifr);
699                         return (EINVAL);
700                         /* XXX disable stacking for the moment, its untested */
701 #ifdef LAGG_PORT_STACKING
702                         lp->lp_flags |= LAGG_PORT_STACK;
703                         if (lagg_port_checkstacking(sc_ptr) >=
704                             LAGG_MAX_STACKING) {
705                                 LAGG_LIST_UNLOCK();
706                                 free(lp, M_DEVBUF);
707                                 if (oldmtu != -1)
708                                         (*ifp->if_ioctl)(ifp, SIOCSIFMTU,
709                                             (caddr_t)&ifr);
710                                 return (E2BIG);
711                         }
712 #endif
713                 }
714         }
715         LAGG_LIST_UNLOCK();
716
717         if_ref(ifp);
718         lp->lp_ifp = ifp;
719
720         bcopy(IF_LLADDR(ifp), lp->lp_lladdr, ETHER_ADDR_LEN);
721         lp->lp_ifcapenable = ifp->if_capenable;
722         if (CK_SLIST_EMPTY(&sc->sc_ports)) {
723                 bcopy(IF_LLADDR(ifp), IF_LLADDR(sc->sc_ifp), ETHER_ADDR_LEN);
724                 lagg_proto_lladdr(sc);
725                 EVENTHANDLER_INVOKE(iflladdr_event, sc->sc_ifp);
726         } else {
727                 if_setlladdr(ifp, IF_LLADDR(sc->sc_ifp), ETHER_ADDR_LEN);
728         }
729         lagg_setflags(lp, 1);
730
731         if (CK_SLIST_EMPTY(&sc->sc_ports))
732                 sc->sc_primary = lp;
733
734         /* Change the interface type */
735         lp->lp_iftype = ifp->if_type;
736         ifp->if_type = IFT_IEEE8023ADLAG;
737         ifp->if_lagg = lp;
738         lp->lp_ioctl = ifp->if_ioctl;
739         ifp->if_ioctl = lagg_port_ioctl;
740         lp->lp_output = ifp->if_output;
741         ifp->if_output = lagg_port_output;
742
743         /* Read port counters */
744         pval = lp->port_counters.val;
745         for (i = 0; i < IFCOUNTERS; i++, pval++)
746                 *pval = ifp->if_get_counter(ifp, i);
747
748         /*
749          * Insert into the list of ports.
750          * Keep ports sorted by if_index. It is handy, when configuration
751          * is predictable and `ifconfig laggN create ...` command
752          * will lead to the same result each time.
753          */
754         CK_SLIST_FOREACH(tlp, &sc->sc_ports, lp_entries) {
755                 if (tlp->lp_ifp->if_index < ifp->if_index && (
756                     CK_SLIST_NEXT(tlp, lp_entries) == NULL ||
757                     ((struct  lagg_port*)CK_SLIST_NEXT(tlp, lp_entries))->lp_ifp->if_index >
758                     ifp->if_index))
759                         break;
760         }
761         if (tlp != NULL)
762                 CK_SLIST_INSERT_AFTER(tlp, lp, lp_entries);
763         else
764                 CK_SLIST_INSERT_HEAD(&sc->sc_ports, lp, lp_entries);
765         sc->sc_count++;
766
767         lagg_setmulti(lp);
768
769
770         if ((error = lagg_proto_addport(sc, lp)) != 0) {
771                 /* Remove the port, without calling pr_delport. */
772                 lagg_port_destroy(lp, 0);
773                 if (oldmtu != -1)
774                         (*ifp->if_ioctl)(ifp, SIOCSIFMTU, (caddr_t)&ifr);
775                 return (error);
776         }
777
778         /* Update lagg capabilities */
779         lagg_capabilities(sc);
780         lagg_linkstate(sc);
781
782         return (0);
783 }
784
785 #ifdef LAGG_PORT_STACKING
786 static int
787 lagg_port_checkstacking(struct lagg_softc *sc)
788 {
789         struct lagg_softc *sc_ptr;
790         struct lagg_port *lp;
791         int m = 0;
792
793         LAGG_SXLOCK_ASSERT(sc);
794         CK_SLIST_FOREACH(lp, &sc->sc_ports, lp_entries) {
795                 if (lp->lp_flags & LAGG_PORT_STACK) {
796                         sc_ptr = (struct lagg_softc *)lp->lp_ifp->if_softc;
797                         m = MAX(m, lagg_port_checkstacking(sc_ptr));
798                 }
799         }
800
801         return (m + 1);
802 }
803 #endif
804
805 static void
806 lagg_port_destroy_cb(epoch_context_t ec)
807 {
808         struct lagg_port *lp;
809         struct ifnet *ifp;
810
811         lp = __containerof(ec, struct lagg_port, lp_epoch_ctx);
812         ifp = lp->lp_ifp;
813
814         if_rele(ifp);
815         free(lp, M_DEVBUF);
816 }
817
818 static int
819 lagg_port_destroy(struct lagg_port *lp, int rundelport)
820 {
821         struct lagg_softc *sc = lp->lp_softc;
822         struct lagg_port *lp_ptr, *lp0;
823         struct ifnet *ifp = lp->lp_ifp;
824         uint64_t *pval, vdiff;
825         int i;
826
827         LAGG_XLOCK_ASSERT(sc);
828
829         if (rundelport)
830                 lagg_proto_delport(sc, lp);
831
832         if (lp->lp_detaching == 0)
833                 lagg_clrmulti(lp);
834
835         /* Restore interface */
836         ifp->if_type = lp->lp_iftype;
837         ifp->if_ioctl = lp->lp_ioctl;
838         ifp->if_output = lp->lp_output;
839         ifp->if_lagg = NULL;
840
841         /* Update detached port counters */
842         pval = lp->port_counters.val;
843         for (i = 0; i < IFCOUNTERS; i++, pval++) {
844                 vdiff = ifp->if_get_counter(ifp, i) - *pval;
845                 sc->detached_counters.val[i] += vdiff;
846         }
847
848         /* Finally, remove the port from the lagg */
849         CK_SLIST_REMOVE(&sc->sc_ports, lp, lagg_port, lp_entries);
850         sc->sc_count--;
851
852         /* Update the primary interface */
853         if (lp == sc->sc_primary) {
854                 uint8_t lladdr[ETHER_ADDR_LEN];
855
856                 if ((lp0 = CK_SLIST_FIRST(&sc->sc_ports)) == NULL)
857                         bzero(&lladdr, ETHER_ADDR_LEN);
858                 else
859                         bcopy(lp0->lp_lladdr, lladdr, ETHER_ADDR_LEN);
860                 sc->sc_primary = lp0;
861                 if (sc->sc_destroying == 0) {
862                         bcopy(lladdr, IF_LLADDR(sc->sc_ifp), ETHER_ADDR_LEN);
863                         lagg_proto_lladdr(sc);
864                         EVENTHANDLER_INVOKE(iflladdr_event, sc->sc_ifp);
865                 }
866
867                 /*
868                  * Update lladdr for each port (new primary needs update
869                  * as well, to switch from old lladdr to its 'real' one)
870                  */
871                 CK_SLIST_FOREACH(lp_ptr, &sc->sc_ports, lp_entries)
872                         if_setlladdr(lp_ptr->lp_ifp, lladdr, ETHER_ADDR_LEN);
873         }
874
875         if (lp->lp_ifflags)
876                 if_printf(ifp, "%s: lp_ifflags unclean\n", __func__);
877
878         if (lp->lp_detaching == 0) {
879                 lagg_setflags(lp, 0);
880                 lagg_setcaps(lp, lp->lp_ifcapenable);
881                 if_setlladdr(ifp, lp->lp_lladdr, ETHER_ADDR_LEN);
882         }
883
884         /*
885          * free port and release it's ifnet reference after a grace period has
886          * elapsed.
887          */
888         epoch_call(net_epoch_preempt, &lp->lp_epoch_ctx, lagg_port_destroy_cb);
889         /* Update lagg capabilities */
890         lagg_capabilities(sc);
891         lagg_linkstate(sc);
892
893         return (0);
894 }
895
896 static int
897 lagg_port_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
898 {
899         struct lagg_reqport *rp = (struct lagg_reqport *)data;
900         struct lagg_softc *sc;
901         struct lagg_port *lp = NULL;
902         int error = 0;
903
904         /* Should be checked by the caller */
905         if (ifp->if_type != IFT_IEEE8023ADLAG ||
906             (lp = ifp->if_lagg) == NULL || (sc = lp->lp_softc) == NULL)
907                 goto fallback;
908
909         switch (cmd) {
910         case SIOCGLAGGPORT:
911                 if (rp->rp_portname[0] == '\0' ||
912                     ifunit(rp->rp_portname) != ifp) {
913                         error = EINVAL;
914                         break;
915                 }
916
917                 LAGG_RLOCK();
918                 if ((lp = ifp->if_lagg) == NULL || lp->lp_softc != sc) {
919                         error = ENOENT;
920                         LAGG_RUNLOCK();
921                         break;
922                 }
923
924                 lagg_port2req(lp, rp);
925                 LAGG_RUNLOCK();
926                 break;
927
928         case SIOCSIFCAP:
929                 if (lp->lp_ioctl == NULL) {
930                         error = EINVAL;
931                         break;
932                 }
933                 error = (*lp->lp_ioctl)(ifp, cmd, data);
934                 if (error)
935                         break;
936
937                 /* Update lagg interface capabilities */
938                 LAGG_XLOCK(sc);
939                 lagg_capabilities(sc);
940                 LAGG_XUNLOCK(sc);
941                 VLAN_CAPABILITIES(sc->sc_ifp);
942                 break;
943
944         case SIOCSIFMTU:
945                 /* Do not allow the MTU to be changed once joined */
946                 error = EINVAL;
947                 break;
948
949         default:
950                 goto fallback;
951         }
952
953         return (error);
954
955 fallback:
956         if (lp != NULL && lp->lp_ioctl != NULL)
957                 return ((*lp->lp_ioctl)(ifp, cmd, data));
958
959         return (EINVAL);
960 }
961
962 /*
963  * Requests counter @cnt data. 
964  *
965  * Counter value is calculated the following way:
966  * 1) for each port, sum  difference between current and "initial" measurements.
967  * 2) add lagg logical interface counters.
968  * 3) add data from detached_counters array.
969  *
970  * We also do the following things on ports attach/detach:
971  * 1) On port attach we store all counters it has into port_counter array. 
972  * 2) On port detach we add the different between "initial" and
973  *   current counters data to detached_counters array.
974  */
975 static uint64_t
976 lagg_get_counter(struct ifnet *ifp, ift_counter cnt)
977 {
978         struct lagg_softc *sc;
979         struct lagg_port *lp;
980         struct ifnet *lpifp;
981         uint64_t newval, oldval, vsum;
982
983         /* Revise this when we've got non-generic counters. */
984         KASSERT(cnt < IFCOUNTERS, ("%s: invalid cnt %d", __func__, cnt));
985
986         sc = (struct lagg_softc *)ifp->if_softc;
987
988         vsum = 0;
989         LAGG_RLOCK();
990         CK_SLIST_FOREACH(lp, &sc->sc_ports, lp_entries) {
991                 /* Saved attached value */
992                 oldval = lp->port_counters.val[cnt];
993                 /* current value */
994                 lpifp = lp->lp_ifp;
995                 newval = lpifp->if_get_counter(lpifp, cnt);
996                 /* Calculate diff and save new */
997                 vsum += newval - oldval;
998         }
999         LAGG_RUNLOCK();
1000
1001         /*
1002          * Add counter data which might be added by upper
1003          * layer protocols operating on logical interface.
1004          */
1005         vsum += if_get_counter_default(ifp, cnt);
1006
1007         /*
1008          * Add counter data from detached ports counters
1009          */
1010         vsum += sc->detached_counters.val[cnt];
1011
1012
1013         return (vsum);
1014 }
1015
1016 /*
1017  * For direct output to child ports.
1018  */
1019 static int
1020 lagg_port_output(struct ifnet *ifp, struct mbuf *m,
1021         const struct sockaddr *dst, struct route *ro)
1022 {
1023         struct lagg_port *lp = ifp->if_lagg;
1024
1025         switch (dst->sa_family) {
1026                 case pseudo_AF_HDRCMPLT:
1027                 case AF_UNSPEC:
1028                         return ((*lp->lp_output)(ifp, m, dst, ro));
1029         }
1030
1031         /* drop any other frames */
1032         m_freem(m);
1033         return (ENETDOWN);
1034 }
1035
1036 static void
1037 lagg_port_ifdetach(void *arg __unused, struct ifnet *ifp)
1038 {
1039         struct lagg_port *lp;
1040         struct lagg_softc *sc;
1041
1042         if ((lp = ifp->if_lagg) == NULL)
1043                 return;
1044         /* If the ifnet is just being renamed, don't do anything. */
1045         if (ifp->if_flags & IFF_RENAMING)
1046                 return;
1047
1048         sc = lp->lp_softc;
1049
1050         LAGG_XLOCK(sc);
1051         lp->lp_detaching = 1;
1052         lagg_port_destroy(lp, 1);
1053         LAGG_XUNLOCK(sc);
1054         VLAN_CAPABILITIES(sc->sc_ifp);
1055 }
1056
1057 static void
1058 lagg_port2req(struct lagg_port *lp, struct lagg_reqport *rp)
1059 {
1060         struct lagg_softc *sc = lp->lp_softc;
1061
1062         strlcpy(rp->rp_ifname, sc->sc_ifname, sizeof(rp->rp_ifname));
1063         strlcpy(rp->rp_portname, lp->lp_ifp->if_xname, sizeof(rp->rp_portname));
1064         rp->rp_prio = lp->lp_prio;
1065         rp->rp_flags = lp->lp_flags;
1066         lagg_proto_portreq(sc, lp, &rp->rp_psc);
1067
1068         /* Add protocol specific flags */
1069         switch (sc->sc_proto) {
1070                 case LAGG_PROTO_FAILOVER:
1071                         if (lp == sc->sc_primary)
1072                                 rp->rp_flags |= LAGG_PORT_MASTER;
1073                         if (lp == lagg_link_active(sc, sc->sc_primary))
1074                                 rp->rp_flags |= LAGG_PORT_ACTIVE;
1075                         break;
1076
1077                 case LAGG_PROTO_ROUNDROBIN:
1078                 case LAGG_PROTO_LOADBALANCE:
1079                 case LAGG_PROTO_BROADCAST:
1080                         if (LAGG_PORTACTIVE(lp))
1081                                 rp->rp_flags |= LAGG_PORT_ACTIVE;
1082                         break;
1083
1084                 case LAGG_PROTO_LACP:
1085                         /* LACP has a different definition of active */
1086                         if (lacp_isactive(lp))
1087                                 rp->rp_flags |= LAGG_PORT_ACTIVE;
1088                         if (lacp_iscollecting(lp))
1089                                 rp->rp_flags |= LAGG_PORT_COLLECTING;
1090                         if (lacp_isdistributing(lp))
1091                                 rp->rp_flags |= LAGG_PORT_DISTRIBUTING;
1092                         break;
1093         }
1094
1095 }
1096
1097 static void
1098 lagg_init(void *xsc)
1099 {
1100         struct lagg_softc *sc = (struct lagg_softc *)xsc;
1101         struct ifnet *ifp = sc->sc_ifp;
1102         struct lagg_port *lp;
1103
1104         LAGG_XLOCK(sc);
1105         if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1106                 LAGG_XUNLOCK(sc);
1107                 return;
1108         }
1109
1110         ifp->if_drv_flags |= IFF_DRV_RUNNING;
1111
1112         /*
1113          * Update the port lladdrs if needed.
1114          * This might be if_setlladdr() notification
1115          * that lladdr has been changed.
1116          */
1117         CK_SLIST_FOREACH(lp, &sc->sc_ports, lp_entries) {
1118                 if (memcmp(IF_LLADDR(ifp), IF_LLADDR(lp->lp_ifp),
1119                     ETHER_ADDR_LEN) != 0)
1120                         if_setlladdr(lp->lp_ifp, IF_LLADDR(ifp), ETHER_ADDR_LEN);
1121         }
1122
1123         lagg_proto_init(sc);
1124
1125         LAGG_XUNLOCK(sc);
1126 }
1127
1128 static void
1129 lagg_stop(struct lagg_softc *sc)
1130 {
1131         struct ifnet *ifp = sc->sc_ifp;
1132
1133         LAGG_XLOCK_ASSERT(sc);
1134
1135         if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0)
1136                 return;
1137
1138         ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
1139
1140         lagg_proto_stop(sc);
1141 }
1142
1143 static int
1144 lagg_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1145 {
1146         struct lagg_softc *sc = (struct lagg_softc *)ifp->if_softc;
1147         struct lagg_reqall *ra = (struct lagg_reqall *)data;
1148         struct lagg_reqopts *ro = (struct lagg_reqopts *)data;
1149         struct lagg_reqport *rp = (struct lagg_reqport *)data, rpbuf;
1150         struct lagg_reqflags *rf = (struct lagg_reqflags *)data;
1151         struct ifreq *ifr = (struct ifreq *)data;
1152         struct lagg_port *lp;
1153         struct ifnet *tpif;
1154         struct thread *td = curthread;
1155         char *buf, *outbuf;
1156         int count, buflen, len, error = 0;
1157
1158         bzero(&rpbuf, sizeof(rpbuf));
1159
1160         switch (cmd) {
1161         case SIOCGLAGG:
1162                 LAGG_XLOCK(sc);
1163                 buflen = sc->sc_count * sizeof(struct lagg_reqport);
1164                 outbuf = malloc(buflen, M_TEMP, M_WAITOK | M_ZERO);
1165                 ra->ra_proto = sc->sc_proto;
1166                 lagg_proto_request(sc, &ra->ra_psc);
1167                 count = 0;
1168                 buf = outbuf;
1169                 len = min(ra->ra_size, buflen);
1170                 CK_SLIST_FOREACH(lp, &sc->sc_ports, lp_entries) {
1171                         if (len < sizeof(rpbuf))
1172                                 break;
1173
1174                         lagg_port2req(lp, &rpbuf);
1175                         memcpy(buf, &rpbuf, sizeof(rpbuf));
1176                         count++;
1177                         buf += sizeof(rpbuf);
1178                         len -= sizeof(rpbuf);
1179                 }
1180                 LAGG_XUNLOCK(sc);
1181                 ra->ra_ports = count;
1182                 ra->ra_size = count * sizeof(rpbuf);
1183                 error = copyout(outbuf, ra->ra_port, ra->ra_size);
1184                 free(outbuf, M_TEMP);
1185                 break;
1186         case SIOCSLAGG:
1187                 error = priv_check(td, PRIV_NET_LAGG);
1188                 if (error)
1189                         break;
1190                 if (ra->ra_proto >= LAGG_PROTO_MAX) {
1191                         error = EPROTONOSUPPORT;
1192                         break;
1193                 }
1194
1195                 LAGG_XLOCK(sc);
1196                 lagg_proto_detach(sc);
1197                 LAGG_UNLOCK_ASSERT();
1198                 lagg_proto_attach(sc, ra->ra_proto);
1199                 LAGG_XUNLOCK(sc);
1200                 break;
1201         case SIOCGLAGGOPTS:
1202                 LAGG_XLOCK(sc);
1203                 ro->ro_opts = sc->sc_opts;
1204                 if (sc->sc_proto == LAGG_PROTO_LACP) {
1205                         struct lacp_softc *lsc;
1206
1207                         lsc = (struct lacp_softc *)sc->sc_psc;
1208                         if (lsc->lsc_debug.lsc_tx_test != 0)
1209                                 ro->ro_opts |= LAGG_OPT_LACP_TXTEST;
1210                         if (lsc->lsc_debug.lsc_rx_test != 0)
1211                                 ro->ro_opts |= LAGG_OPT_LACP_RXTEST;
1212                         if (lsc->lsc_strict_mode != 0)
1213                                 ro->ro_opts |= LAGG_OPT_LACP_STRICT;
1214                         if (lsc->lsc_fast_timeout != 0)
1215                                 ro->ro_opts |= LAGG_OPT_LACP_TIMEOUT;
1216
1217                         ro->ro_active = sc->sc_active;
1218                 } else {
1219                         ro->ro_active = 0;
1220                         CK_SLIST_FOREACH(lp, &sc->sc_ports, lp_entries)
1221                                 ro->ro_active += LAGG_PORTACTIVE(lp);
1222                 }
1223                 ro->ro_bkt = sc->sc_bkt;
1224                 ro->ro_flapping = sc->sc_flapping;
1225                 ro->ro_flowid_shift = sc->flowid_shift;
1226                 LAGG_XUNLOCK(sc);
1227                 break;
1228         case SIOCSLAGGOPTS:
1229                 if (sc->sc_proto == LAGG_PROTO_ROUNDROBIN) {
1230                         if (ro->ro_bkt == 0)
1231                                 sc->sc_bkt = 1; // Minimum 1 packet per iface.
1232                         else
1233                                 sc->sc_bkt = ro->ro_bkt;
1234                 }
1235                 error = priv_check(td, PRIV_NET_LAGG);
1236                 if (error)
1237                         break;
1238                 if (ro->ro_opts == 0)
1239                         break;
1240                 /*
1241                  * Set options.  LACP options are stored in sc->sc_psc,
1242                  * not in sc_opts.
1243                  */
1244                 int valid, lacp;
1245
1246                 switch (ro->ro_opts) {
1247                 case LAGG_OPT_USE_FLOWID:
1248                 case -LAGG_OPT_USE_FLOWID:
1249                 case LAGG_OPT_FLOWIDSHIFT:
1250                         valid = 1;
1251                         lacp = 0;
1252                         break;
1253                 case LAGG_OPT_LACP_TXTEST:
1254                 case -LAGG_OPT_LACP_TXTEST:
1255                 case LAGG_OPT_LACP_RXTEST:
1256                 case -LAGG_OPT_LACP_RXTEST:
1257                 case LAGG_OPT_LACP_STRICT:
1258                 case -LAGG_OPT_LACP_STRICT:
1259                 case LAGG_OPT_LACP_TIMEOUT:
1260                 case -LAGG_OPT_LACP_TIMEOUT:
1261                         valid = lacp = 1;
1262                         break;
1263                 default:
1264                         valid = lacp = 0;
1265                         break;
1266                 }
1267
1268                 LAGG_XLOCK(sc);
1269
1270                 if (valid == 0 ||
1271                     (lacp == 1 && sc->sc_proto != LAGG_PROTO_LACP)) {
1272                         /* Invalid combination of options specified. */
1273                         error = EINVAL;
1274                         LAGG_XUNLOCK(sc);
1275                         break;  /* Return from SIOCSLAGGOPTS. */ 
1276                 }
1277                 /*
1278                  * Store new options into sc->sc_opts except for
1279                  * FLOWIDSHIFT and LACP options.
1280                  */
1281                 if (lacp == 0) {
1282                         if (ro->ro_opts == LAGG_OPT_FLOWIDSHIFT)
1283                                 sc->flowid_shift = ro->ro_flowid_shift;
1284                         else if (ro->ro_opts > 0)
1285                                 sc->sc_opts |= ro->ro_opts;
1286                         else
1287                                 sc->sc_opts &= ~ro->ro_opts;
1288                 } else {
1289                         struct lacp_softc *lsc;
1290                         struct lacp_port *lp;
1291
1292                         lsc = (struct lacp_softc *)sc->sc_psc;
1293
1294                         switch (ro->ro_opts) {
1295                         case LAGG_OPT_LACP_TXTEST:
1296                                 lsc->lsc_debug.lsc_tx_test = 1;
1297                                 break;
1298                         case -LAGG_OPT_LACP_TXTEST:
1299                                 lsc->lsc_debug.lsc_tx_test = 0;
1300                                 break;
1301                         case LAGG_OPT_LACP_RXTEST:
1302                                 lsc->lsc_debug.lsc_rx_test = 1;
1303                                 break;
1304                         case -LAGG_OPT_LACP_RXTEST:
1305                                 lsc->lsc_debug.lsc_rx_test = 0;
1306                                 break;
1307                         case LAGG_OPT_LACP_STRICT:
1308                                 lsc->lsc_strict_mode = 1;
1309                                 break;
1310                         case -LAGG_OPT_LACP_STRICT:
1311                                 lsc->lsc_strict_mode = 0;
1312                                 break;
1313                         case LAGG_OPT_LACP_TIMEOUT:
1314                                 LACP_LOCK(lsc);
1315                                 LIST_FOREACH(lp, &lsc->lsc_ports, lp_next)
1316                                         lp->lp_state |= LACP_STATE_TIMEOUT;
1317                                 LACP_UNLOCK(lsc);
1318                                 lsc->lsc_fast_timeout = 1;
1319                                 break;
1320                         case -LAGG_OPT_LACP_TIMEOUT:
1321                                 LACP_LOCK(lsc);
1322                                 LIST_FOREACH(lp, &lsc->lsc_ports, lp_next)
1323                                         lp->lp_state &= ~LACP_STATE_TIMEOUT;
1324                                 LACP_UNLOCK(lsc);
1325                                 lsc->lsc_fast_timeout = 0;
1326                                 break;
1327                         }
1328                 }
1329                 LAGG_XUNLOCK(sc);
1330                 break;
1331         case SIOCGLAGGFLAGS:
1332                 rf->rf_flags = 0;
1333                 LAGG_XLOCK(sc);
1334                 if (sc->sc_flags & MBUF_HASHFLAG_L2)
1335                         rf->rf_flags |= LAGG_F_HASHL2;
1336                 if (sc->sc_flags & MBUF_HASHFLAG_L3)
1337                         rf->rf_flags |= LAGG_F_HASHL3;
1338                 if (sc->sc_flags & MBUF_HASHFLAG_L4)
1339                         rf->rf_flags |= LAGG_F_HASHL4;
1340                 LAGG_XUNLOCK(sc);
1341                 break;
1342         case SIOCSLAGGHASH:
1343                 error = priv_check(td, PRIV_NET_LAGG);
1344                 if (error)
1345                         break;
1346                 if ((rf->rf_flags & LAGG_F_HASHMASK) == 0) {
1347                         error = EINVAL;
1348                         break;
1349                 }
1350                 LAGG_XLOCK(sc);
1351                 sc->sc_flags = 0;
1352                 if (rf->rf_flags & LAGG_F_HASHL2)
1353                         sc->sc_flags |= MBUF_HASHFLAG_L2;
1354                 if (rf->rf_flags & LAGG_F_HASHL3)
1355                         sc->sc_flags |= MBUF_HASHFLAG_L3;
1356                 if (rf->rf_flags & LAGG_F_HASHL4)
1357                         sc->sc_flags |= MBUF_HASHFLAG_L4;
1358                 LAGG_XUNLOCK(sc);
1359                 break;
1360         case SIOCGLAGGPORT:
1361                 if (rp->rp_portname[0] == '\0' ||
1362                     (tpif = ifunit_ref(rp->rp_portname)) == NULL) {
1363                         error = EINVAL;
1364                         break;
1365                 }
1366
1367                 LAGG_RLOCK();
1368                 if ((lp = (struct lagg_port *)tpif->if_lagg) == NULL ||
1369                     lp->lp_softc != sc) {
1370                         error = ENOENT;
1371                         LAGG_RUNLOCK();
1372                         if_rele(tpif);
1373                         break;
1374                 }
1375
1376                 lagg_port2req(lp, rp);
1377                 LAGG_RUNLOCK();
1378                 if_rele(tpif);
1379                 break;
1380         case SIOCSLAGGPORT:
1381                 error = priv_check(td, PRIV_NET_LAGG);
1382                 if (error)
1383                         break;
1384                 if (rp->rp_portname[0] == '\0' ||
1385                     (tpif = ifunit_ref(rp->rp_portname)) == NULL) {
1386                         error = EINVAL;
1387                         break;
1388                 }
1389 #ifdef INET6
1390                 /*
1391                  * A laggport interface should not have inet6 address
1392                  * because two interfaces with a valid link-local
1393                  * scope zone must not be merged in any form.  This
1394                  * restriction is needed to prevent violation of
1395                  * link-local scope zone.  Attempts to add a laggport
1396                  * interface which has inet6 addresses triggers
1397                  * removal of all inet6 addresses on the member
1398                  * interface.
1399                  */
1400                 if (in6ifa_llaonifp(tpif)) {
1401                         in6_ifdetach(tpif);
1402                                 if_printf(sc->sc_ifp,
1403                                     "IPv6 addresses on %s have been removed "
1404                                     "before adding it as a member to prevent "
1405                                     "IPv6 address scope violation.\n",
1406                                     tpif->if_xname);
1407                 }
1408 #endif
1409                 LAGG_XLOCK(sc);
1410                 error = lagg_port_create(sc, tpif);
1411                 LAGG_XUNLOCK(sc);
1412                 if_rele(tpif);
1413                 VLAN_CAPABILITIES(ifp);
1414                 break;
1415         case SIOCSLAGGDELPORT:
1416                 error = priv_check(td, PRIV_NET_LAGG);
1417                 if (error)
1418                         break;
1419                 if (rp->rp_portname[0] == '\0' ||
1420                     (tpif = ifunit_ref(rp->rp_portname)) == NULL) {
1421                         error = EINVAL;
1422                         break;
1423                 }
1424
1425                 LAGG_XLOCK(sc);
1426                 if ((lp = (struct lagg_port *)tpif->if_lagg) == NULL ||
1427                     lp->lp_softc != sc) {
1428                         error = ENOENT;
1429                         LAGG_XUNLOCK(sc);
1430                         if_rele(tpif);
1431                         break;
1432                 }
1433
1434                 error = lagg_port_destroy(lp, 1);
1435                 LAGG_XUNLOCK(sc);
1436                 if_rele(tpif);
1437                 VLAN_CAPABILITIES(ifp);
1438                 break;
1439         case SIOCSIFFLAGS:
1440                 /* Set flags on ports too */
1441                 LAGG_XLOCK(sc);
1442                 CK_SLIST_FOREACH(lp, &sc->sc_ports, lp_entries) {
1443                         lagg_setflags(lp, 1);
1444                 }
1445
1446                 if (!(ifp->if_flags & IFF_UP) &&
1447                     (ifp->if_drv_flags & IFF_DRV_RUNNING)) {
1448                         /*
1449                          * If interface is marked down and it is running,
1450                          * then stop and disable it.
1451                          */
1452                         lagg_stop(sc);
1453                         LAGG_XUNLOCK(sc);
1454                 } else if ((ifp->if_flags & IFF_UP) &&
1455                     !(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
1456                         /*
1457                          * If interface is marked up and it is stopped, then
1458                          * start it.
1459                          */
1460                         LAGG_XUNLOCK(sc);
1461                         (*ifp->if_init)(sc);
1462                 } else
1463                         LAGG_XUNLOCK(sc);
1464                 break;
1465         case SIOCADDMULTI:
1466         case SIOCDELMULTI:
1467                 LAGG_XLOCK(sc);
1468                 CK_SLIST_FOREACH(lp, &sc->sc_ports, lp_entries) {
1469                         lagg_clrmulti(lp);
1470                         lagg_setmulti(lp);
1471                 }
1472                 LAGG_XUNLOCK(sc);
1473                 error = 0;
1474                 break;
1475         case SIOCSIFMEDIA:
1476         case SIOCGIFMEDIA:
1477                 error = ifmedia_ioctl(ifp, ifr, &sc->sc_media, cmd);
1478                 break;
1479
1480         case SIOCSIFCAP:
1481                 LAGG_XLOCK(sc);
1482                 CK_SLIST_FOREACH(lp, &sc->sc_ports, lp_entries) {
1483                         if (lp->lp_ioctl != NULL)
1484                                 (*lp->lp_ioctl)(lp->lp_ifp, cmd, data);
1485                 }
1486                 lagg_capabilities(sc);
1487                 LAGG_XUNLOCK(sc);
1488                 VLAN_CAPABILITIES(ifp);
1489                 error = 0;
1490                 break;
1491
1492         case SIOCSIFMTU:
1493                 LAGG_XLOCK(sc);
1494                 CK_SLIST_FOREACH(lp, &sc->sc_ports, lp_entries) {
1495                         if (lp->lp_ioctl != NULL)
1496                                 error = (*lp->lp_ioctl)(lp->lp_ifp, cmd, data);
1497                         else
1498                                 error = EINVAL;
1499                         if (error != 0) {
1500                                 if_printf(ifp,
1501                                     "failed to change MTU to %d on port %s, "
1502                                     "reverting all ports to original MTU (%d)\n",
1503                                     ifr->ifr_mtu, lp->lp_ifp->if_xname, ifp->if_mtu);
1504                                 break;
1505                         }
1506                 }
1507                 if (error == 0) {
1508                         ifp->if_mtu = ifr->ifr_mtu;
1509                 } else {
1510                         /* set every port back to the original MTU */
1511                         ifr->ifr_mtu = ifp->if_mtu;
1512                         CK_SLIST_FOREACH(lp, &sc->sc_ports, lp_entries) {
1513                                 if (lp->lp_ioctl != NULL)
1514                                         (*lp->lp_ioctl)(lp->lp_ifp, cmd, data);
1515                         }
1516                 }
1517                 LAGG_XUNLOCK(sc);
1518                 break;
1519
1520         default:
1521                 error = ether_ioctl(ifp, cmd, data);
1522                 break;
1523         }
1524         return (error);
1525 }
1526
1527 #ifdef RATELIMIT
1528 static int
1529 lagg_snd_tag_alloc(struct ifnet *ifp,
1530     union if_snd_tag_alloc_params *params,
1531     struct m_snd_tag **ppmt)
1532 {
1533         struct lagg_softc *sc = (struct lagg_softc *)ifp->if_softc;
1534         struct lagg_port *lp;
1535         struct lagg_lb *lb;
1536         uint32_t p;
1537
1538         LAGG_RLOCK();
1539         switch (sc->sc_proto) {
1540         case LAGG_PROTO_FAILOVER:
1541                 lp = lagg_link_active(sc, sc->sc_primary);
1542                 break;
1543         case LAGG_PROTO_LOADBALANCE:
1544                 if ((sc->sc_opts & LAGG_OPT_USE_FLOWID) == 0 ||
1545                     params->hdr.flowtype == M_HASHTYPE_NONE) {
1546                         LAGG_RUNLOCK();
1547                         return (EOPNOTSUPP);
1548                 }
1549                 p = params->hdr.flowid >> sc->flowid_shift;
1550                 p %= sc->sc_count;
1551                 lb = (struct lagg_lb *)sc->sc_psc;
1552                 lp = lb->lb_ports[p];
1553                 lp = lagg_link_active(sc, lp);
1554                 break;
1555         case LAGG_PROTO_LACP:
1556                 if ((sc->sc_opts & LAGG_OPT_USE_FLOWID) == 0 ||
1557                     params->hdr.flowtype == M_HASHTYPE_NONE) {
1558                         LAGG_RUNLOCK();
1559                         return (EOPNOTSUPP);
1560                 }
1561                 lp = lacp_select_tx_port_by_hash(sc, params->hdr.flowid);
1562                 break;
1563         default:
1564                 LAGG_RUNLOCK();
1565                 return (EOPNOTSUPP);
1566         }
1567         if (lp == NULL) {
1568                 LAGG_RUNLOCK();
1569                 return (EOPNOTSUPP);
1570         }
1571         ifp = lp->lp_ifp;
1572         LAGG_RUNLOCK();
1573         if (ifp == NULL || ifp->if_snd_tag_alloc == NULL ||
1574             (ifp->if_capenable & IFCAP_TXRTLMT) == 0)
1575                 return (EOPNOTSUPP);
1576
1577         /* forward allocation request */
1578         return (ifp->if_snd_tag_alloc(ifp, params, ppmt));
1579 }
1580
1581 static void
1582 lagg_snd_tag_free(struct m_snd_tag *tag)
1583 {
1584         tag->ifp->if_snd_tag_free(tag);
1585 }
1586
1587 #endif
1588
1589 static int
1590 lagg_setmulti(struct lagg_port *lp)
1591 {
1592         struct lagg_softc *sc = lp->lp_softc;
1593         struct ifnet *ifp = lp->lp_ifp;
1594         struct ifnet *scifp = sc->sc_ifp;
1595         struct lagg_mc *mc;
1596         struct ifmultiaddr *ifma;
1597         int error;
1598
1599         IF_ADDR_WLOCK(scifp);
1600         CK_STAILQ_FOREACH(ifma, &scifp->if_multiaddrs, ifma_link) {
1601                 if (ifma->ifma_addr->sa_family != AF_LINK)
1602                         continue;
1603                 mc = malloc(sizeof(struct lagg_mc), M_DEVBUF, M_NOWAIT);
1604                 if (mc == NULL) {
1605                         IF_ADDR_WUNLOCK(scifp);
1606                         return (ENOMEM);
1607                 }
1608                 bcopy(ifma->ifma_addr, &mc->mc_addr,
1609                     ifma->ifma_addr->sa_len);
1610                 mc->mc_addr.sdl_index = ifp->if_index;
1611                 mc->mc_ifma = NULL;
1612                 SLIST_INSERT_HEAD(&lp->lp_mc_head, mc, mc_entries);
1613         }
1614         IF_ADDR_WUNLOCK(scifp);
1615         SLIST_FOREACH (mc, &lp->lp_mc_head, mc_entries) {
1616                 error = if_addmulti(ifp,
1617                     (struct sockaddr *)&mc->mc_addr, &mc->mc_ifma);
1618                 if (error)
1619                         return (error);
1620         }
1621         return (0);
1622 }
1623
1624 static int
1625 lagg_clrmulti(struct lagg_port *lp)
1626 {
1627         struct lagg_mc *mc;
1628
1629         LAGG_XLOCK_ASSERT(lp->lp_softc);
1630         while ((mc = SLIST_FIRST(&lp->lp_mc_head)) != NULL) {
1631                 SLIST_REMOVE(&lp->lp_mc_head, mc, lagg_mc, mc_entries);
1632                 if (mc->mc_ifma && lp->lp_detaching == 0)
1633                         if_delmulti_ifma(mc->mc_ifma);
1634                 free(mc, M_DEVBUF);
1635         }
1636         return (0);
1637 }
1638
1639 static int
1640 lagg_setcaps(struct lagg_port *lp, int cap)
1641 {
1642         struct ifreq ifr;
1643
1644         if (lp->lp_ifp->if_capenable == cap)
1645                 return (0);
1646         if (lp->lp_ioctl == NULL)
1647                 return (ENXIO);
1648         ifr.ifr_reqcap = cap;
1649         return ((*lp->lp_ioctl)(lp->lp_ifp, SIOCSIFCAP, (caddr_t)&ifr));
1650 }
1651
1652 /* Handle a ref counted flag that should be set on the lagg port as well */
1653 static int
1654 lagg_setflag(struct lagg_port *lp, int flag, int status,
1655     int (*func)(struct ifnet *, int))
1656 {
1657         struct lagg_softc *sc = lp->lp_softc;
1658         struct ifnet *scifp = sc->sc_ifp;
1659         struct ifnet *ifp = lp->lp_ifp;
1660         int error;
1661
1662         LAGG_XLOCK_ASSERT(sc);
1663
1664         status = status ? (scifp->if_flags & flag) : 0;
1665         /* Now "status" contains the flag value or 0 */
1666
1667         /*
1668          * See if recorded ports status is different from what
1669          * we want it to be.  If it is, flip it.  We record ports
1670          * status in lp_ifflags so that we won't clear ports flag
1671          * we haven't set.  In fact, we don't clear or set ports
1672          * flags directly, but get or release references to them.
1673          * That's why we can be sure that recorded flags still are
1674          * in accord with actual ports flags.
1675          */
1676         if (status != (lp->lp_ifflags & flag)) {
1677                 error = (*func)(ifp, status);
1678                 if (error)
1679                         return (error);
1680                 lp->lp_ifflags &= ~flag;
1681                 lp->lp_ifflags |= status;
1682         }
1683         return (0);
1684 }
1685
1686 /*
1687  * Handle IFF_* flags that require certain changes on the lagg port
1688  * if "status" is true, update ports flags respective to the lagg
1689  * if "status" is false, forcedly clear the flags set on port.
1690  */
1691 static int
1692 lagg_setflags(struct lagg_port *lp, int status)
1693 {
1694         int error, i;
1695
1696         for (i = 0; lagg_pflags[i].flag; i++) {
1697                 error = lagg_setflag(lp, lagg_pflags[i].flag,
1698                     status, lagg_pflags[i].func);
1699                 if (error)
1700                         return (error);
1701         }
1702         return (0);
1703 }
1704
1705 static int
1706 lagg_transmit(struct ifnet *ifp, struct mbuf *m)
1707 {
1708         struct lagg_softc *sc = (struct lagg_softc *)ifp->if_softc;
1709         int error;
1710
1711         LAGG_RLOCK();
1712         /* We need a Tx algorithm and at least one port */
1713         if (sc->sc_proto == LAGG_PROTO_NONE || sc->sc_count == 0) {
1714                 LAGG_RUNLOCK();
1715                 m_freem(m);
1716                 if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
1717                 return (ENXIO);
1718         }
1719
1720         ETHER_BPF_MTAP(ifp, m);
1721
1722         error = lagg_proto_start(sc, m);
1723         LAGG_RUNLOCK();
1724
1725         if (error != 0)
1726                 if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
1727
1728         return (error);
1729 }
1730
1731 /*
1732  * The ifp->if_qflush entry point for lagg(4) is no-op.
1733  */
1734 static void
1735 lagg_qflush(struct ifnet *ifp __unused)
1736 {
1737 }
1738
1739 static struct mbuf *
1740 lagg_input(struct ifnet *ifp, struct mbuf *m)
1741 {
1742         struct lagg_port *lp = ifp->if_lagg;
1743         struct lagg_softc *sc = lp->lp_softc;
1744         struct ifnet *scifp = sc->sc_ifp;
1745
1746         LAGG_RLOCK();
1747         if ((scifp->if_drv_flags & IFF_DRV_RUNNING) == 0 ||
1748             lp->lp_detaching != 0 ||
1749             sc->sc_proto == LAGG_PROTO_NONE) {
1750                 LAGG_RUNLOCK();
1751                 m_freem(m);
1752                 return (NULL);
1753         }
1754
1755         ETHER_BPF_MTAP(scifp, m);
1756
1757         m = lagg_proto_input(sc, lp, m);
1758         if (m != NULL && (scifp->if_flags & IFF_MONITOR) != 0) {
1759                 m_freem(m);
1760                 m = NULL;
1761         }
1762
1763         LAGG_RUNLOCK();
1764         return (m);
1765 }
1766
1767 static int
1768 lagg_media_change(struct ifnet *ifp)
1769 {
1770         struct lagg_softc *sc = (struct lagg_softc *)ifp->if_softc;
1771
1772         if (sc->sc_ifflags & IFF_DEBUG)
1773                 printf("%s\n", __func__);
1774
1775         /* Ignore */
1776         return (0);
1777 }
1778
1779 static void
1780 lagg_media_status(struct ifnet *ifp, struct ifmediareq *imr)
1781 {
1782         struct lagg_softc *sc = (struct lagg_softc *)ifp->if_softc;
1783         struct lagg_port *lp;
1784
1785         imr->ifm_status = IFM_AVALID;
1786         imr->ifm_active = IFM_ETHER | IFM_AUTO;
1787
1788         LAGG_RLOCK();
1789         CK_SLIST_FOREACH(lp, &sc->sc_ports, lp_entries) {
1790                 if (LAGG_PORTACTIVE(lp))
1791                         imr->ifm_status |= IFM_ACTIVE;
1792         }
1793         LAGG_RUNLOCK();
1794 }
1795
1796 static void
1797 lagg_linkstate(struct lagg_softc *sc)
1798 {
1799         struct lagg_port *lp;
1800         int new_link = LINK_STATE_DOWN;
1801         uint64_t speed;
1802
1803         LAGG_XLOCK_ASSERT(sc);
1804
1805         /* LACP handles link state itself */
1806         if (sc->sc_proto == LAGG_PROTO_LACP)
1807                 return;
1808
1809         /* Our link is considered up if at least one of our ports is active */
1810         LAGG_RLOCK();
1811         CK_SLIST_FOREACH(lp, &sc->sc_ports, lp_entries) {
1812                 if (lp->lp_ifp->if_link_state == LINK_STATE_UP) {
1813                         new_link = LINK_STATE_UP;
1814                         break;
1815                 }
1816         }
1817         LAGG_RUNLOCK();
1818         if_link_state_change(sc->sc_ifp, new_link);
1819
1820         /* Update if_baudrate to reflect the max possible speed */
1821         switch (sc->sc_proto) {
1822                 case LAGG_PROTO_FAILOVER:
1823                         sc->sc_ifp->if_baudrate = sc->sc_primary != NULL ?
1824                             sc->sc_primary->lp_ifp->if_baudrate : 0;
1825                         break;
1826                 case LAGG_PROTO_ROUNDROBIN:
1827                 case LAGG_PROTO_LOADBALANCE:
1828                 case LAGG_PROTO_BROADCAST:
1829                         speed = 0;
1830                         LAGG_RLOCK();
1831                         CK_SLIST_FOREACH(lp, &sc->sc_ports, lp_entries)
1832                                 speed += lp->lp_ifp->if_baudrate;
1833                         LAGG_RUNLOCK();
1834                         sc->sc_ifp->if_baudrate = speed;
1835                         break;
1836                 case LAGG_PROTO_LACP:
1837                         /* LACP updates if_baudrate itself */
1838                         break;
1839         }
1840 }
1841
1842 static void
1843 lagg_port_state(struct ifnet *ifp, int state)
1844 {
1845         struct lagg_port *lp = (struct lagg_port *)ifp->if_lagg;
1846         struct lagg_softc *sc = NULL;
1847
1848         if (lp != NULL)
1849                 sc = lp->lp_softc;
1850         if (sc == NULL)
1851                 return;
1852
1853         LAGG_XLOCK(sc);
1854         lagg_linkstate(sc);
1855         lagg_proto_linkstate(sc, lp);
1856         LAGG_XUNLOCK(sc);
1857 }
1858
1859 struct lagg_port *
1860 lagg_link_active(struct lagg_softc *sc, struct lagg_port *lp)
1861 {
1862         struct lagg_port *lp_next, *rval = NULL;
1863
1864         /*
1865          * Search a port which reports an active link state.
1866          */
1867
1868         /*
1869          * This is called with either LAGG_RLOCK() held or
1870          * LAGG_XLOCK(sc) held.
1871          */
1872         if (!in_epoch(net_epoch_preempt))
1873                 LAGG_XLOCK_ASSERT(sc);
1874
1875         if (lp == NULL)
1876                 goto search;
1877         if (LAGG_PORTACTIVE(lp)) {
1878                 rval = lp;
1879                 goto found;
1880         }
1881         if ((lp_next = CK_SLIST_NEXT(lp, lp_entries)) != NULL &&
1882             LAGG_PORTACTIVE(lp_next)) {
1883                 rval = lp_next;
1884                 goto found;
1885         }
1886
1887 search:
1888         CK_SLIST_FOREACH(lp_next, &sc->sc_ports, lp_entries) {
1889                 if (LAGG_PORTACTIVE(lp_next)) {
1890                         return (lp_next);
1891                 }
1892         }
1893 found:
1894         return (rval);
1895 }
1896
1897 int
1898 lagg_enqueue(struct ifnet *ifp, struct mbuf *m)
1899 {
1900
1901         return (ifp->if_transmit)(ifp, m);
1902 }
1903
1904 /*
1905  * Simple round robin aggregation
1906  */
1907 static void
1908 lagg_rr_attach(struct lagg_softc *sc)
1909 {
1910         sc->sc_seq = 0;
1911         sc->sc_bkt_count = sc->sc_bkt;
1912 }
1913
1914 static int
1915 lagg_rr_start(struct lagg_softc *sc, struct mbuf *m)
1916 {
1917         struct lagg_port *lp;
1918         uint32_t p;
1919
1920         if (sc->sc_bkt_count == 0 && sc->sc_bkt > 0)
1921                 sc->sc_bkt_count = sc->sc_bkt;
1922
1923         if (sc->sc_bkt > 0) {
1924                 atomic_subtract_int(&sc->sc_bkt_count, 1);
1925         if (atomic_cmpset_int(&sc->sc_bkt_count, 0, sc->sc_bkt))
1926                 p = atomic_fetchadd_32(&sc->sc_seq, 1);
1927         else
1928                 p = sc->sc_seq; 
1929         } else
1930                 p = atomic_fetchadd_32(&sc->sc_seq, 1);
1931
1932         p %= sc->sc_count;
1933         lp = CK_SLIST_FIRST(&sc->sc_ports);
1934
1935         while (p--)
1936                 lp = CK_SLIST_NEXT(lp, lp_entries);
1937
1938         /*
1939          * Check the port's link state. This will return the next active
1940          * port if the link is down or the port is NULL.
1941          */
1942         if ((lp = lagg_link_active(sc, lp)) == NULL) {
1943                 m_freem(m);
1944                 return (ENETDOWN);
1945         }
1946
1947         /* Send mbuf */
1948         return (lagg_enqueue(lp->lp_ifp, m));
1949 }
1950
1951 static struct mbuf *
1952 lagg_rr_input(struct lagg_softc *sc, struct lagg_port *lp, struct mbuf *m)
1953 {
1954         struct ifnet *ifp = sc->sc_ifp;
1955
1956         /* Just pass in the packet to our lagg device */
1957         m->m_pkthdr.rcvif = ifp;
1958
1959         return (m);
1960 }
1961
1962 /*
1963  * Broadcast mode
1964  */
1965 static int
1966 lagg_bcast_start(struct lagg_softc *sc, struct mbuf *m)
1967 {
1968         int active_ports = 0;
1969         int errors = 0;
1970         int ret;
1971         struct lagg_port *lp, *last = NULL;
1972         struct mbuf *m0;
1973
1974         LAGG_RLOCK_ASSERT();
1975         CK_SLIST_FOREACH(lp, &sc->sc_ports, lp_entries) {
1976                 if (!LAGG_PORTACTIVE(lp))
1977                         continue;
1978
1979                 active_ports++;
1980
1981                 if (last != NULL) {
1982                         m0 = m_copym(m, 0, M_COPYALL, M_NOWAIT);
1983                         if (m0 == NULL) {
1984                                 ret = ENOBUFS;
1985                                 errors++;
1986                                 break;
1987                         }
1988
1989                         ret = lagg_enqueue(last->lp_ifp, m0);
1990                         if (ret != 0)
1991                                 errors++;
1992                 }
1993                 last = lp;
1994         }
1995
1996         if (last == NULL) {
1997                 m_freem(m);
1998                 return (ENOENT);
1999         }
2000         if ((last = lagg_link_active(sc, last)) == NULL) {
2001                 m_freem(m);
2002                 return (ENETDOWN);
2003         }
2004
2005         ret = lagg_enqueue(last->lp_ifp, m);
2006         if (ret != 0)
2007                 errors++;
2008
2009         if (errors == 0)
2010                 return (ret);
2011
2012         return (0);
2013 }
2014
2015 static struct mbuf*
2016 lagg_bcast_input(struct lagg_softc *sc, struct lagg_port *lp, struct mbuf *m)
2017 {
2018         struct ifnet *ifp = sc->sc_ifp;
2019
2020         /* Just pass in the packet to our lagg device */
2021         m->m_pkthdr.rcvif = ifp;
2022         return (m);
2023 }
2024
2025 /*
2026  * Active failover
2027  */
2028 static int
2029 lagg_fail_start(struct lagg_softc *sc, struct mbuf *m)
2030 {
2031         struct lagg_port *lp;
2032
2033         /* Use the master port if active or the next available port */
2034         if ((lp = lagg_link_active(sc, sc->sc_primary)) == NULL) {
2035                 m_freem(m);
2036                 return (ENETDOWN);
2037         }
2038
2039         /* Send mbuf */
2040         return (lagg_enqueue(lp->lp_ifp, m));
2041 }
2042
2043 static struct mbuf *
2044 lagg_fail_input(struct lagg_softc *sc, struct lagg_port *lp, struct mbuf *m)
2045 {
2046         struct ifnet *ifp = sc->sc_ifp;
2047         struct lagg_port *tmp_tp;
2048
2049         if (lp == sc->sc_primary || V_lagg_failover_rx_all) {
2050                 m->m_pkthdr.rcvif = ifp;
2051                 return (m);
2052         }
2053
2054         if (!LAGG_PORTACTIVE(sc->sc_primary)) {
2055                 tmp_tp = lagg_link_active(sc, sc->sc_primary);
2056                 /*
2057                  * If tmp_tp is null, we've received a packet when all
2058                  * our links are down. Weird, but process it anyways.
2059                  */
2060                 if ((tmp_tp == NULL || tmp_tp == lp)) {
2061                         m->m_pkthdr.rcvif = ifp;
2062                         return (m);
2063                 }
2064         }
2065
2066         m_freem(m);
2067         return (NULL);
2068 }
2069
2070 /*
2071  * Loadbalancing
2072  */
2073 static void
2074 lagg_lb_attach(struct lagg_softc *sc)
2075 {
2076         struct lagg_port *lp;
2077         struct lagg_lb *lb;
2078
2079         LAGG_XLOCK_ASSERT(sc);
2080         lb = malloc(sizeof(struct lagg_lb), M_DEVBUF, M_WAITOK | M_ZERO);
2081         lb->lb_key = m_ether_tcpip_hash_init();
2082         sc->sc_psc = lb;
2083
2084         CK_SLIST_FOREACH(lp, &sc->sc_ports, lp_entries)
2085                 lagg_lb_port_create(lp);
2086 }
2087
2088 static void
2089 lagg_lb_detach(struct lagg_softc *sc)
2090 {
2091         struct lagg_lb *lb;
2092
2093         lb = (struct lagg_lb *)sc->sc_psc;
2094         if (lb != NULL)
2095                 free(lb, M_DEVBUF);
2096 }
2097
2098 static int
2099 lagg_lb_porttable(struct lagg_softc *sc, struct lagg_port *lp)
2100 {
2101         struct lagg_lb *lb = (struct lagg_lb *)sc->sc_psc;
2102         struct lagg_port *lp_next;
2103         int i = 0, rv;
2104
2105         rv = 0;
2106         bzero(&lb->lb_ports, sizeof(lb->lb_ports));
2107         LAGG_XLOCK_ASSERT(sc);
2108         CK_SLIST_FOREACH(lp_next, &sc->sc_ports, lp_entries) {
2109                 if (lp_next == lp)
2110                         continue;
2111                 if (i >= LAGG_MAX_PORTS) {
2112                         rv = EINVAL;
2113                         break;
2114                 }
2115                 if (sc->sc_ifflags & IFF_DEBUG)
2116                         printf("%s: port %s at index %d\n",
2117                             sc->sc_ifname, lp_next->lp_ifp->if_xname, i);
2118                 lb->lb_ports[i++] = lp_next;
2119         }
2120
2121         return (rv);
2122 }
2123
2124 static int
2125 lagg_lb_port_create(struct lagg_port *lp)
2126 {
2127         struct lagg_softc *sc = lp->lp_softc;
2128         return (lagg_lb_porttable(sc, NULL));
2129 }
2130
2131 static void
2132 lagg_lb_port_destroy(struct lagg_port *lp)
2133 {
2134         struct lagg_softc *sc = lp->lp_softc;
2135         lagg_lb_porttable(sc, lp);
2136 }
2137
2138 static int
2139 lagg_lb_start(struct lagg_softc *sc, struct mbuf *m)
2140 {
2141         struct lagg_lb *lb = (struct lagg_lb *)sc->sc_psc;
2142         struct lagg_port *lp = NULL;
2143         uint32_t p = 0;
2144
2145         if ((sc->sc_opts & LAGG_OPT_USE_FLOWID) &&
2146             M_HASHTYPE_GET(m) != M_HASHTYPE_NONE)
2147                 p = m->m_pkthdr.flowid >> sc->flowid_shift;
2148         else
2149                 p = m_ether_tcpip_hash(sc->sc_flags, m, lb->lb_key);
2150         p %= sc->sc_count;
2151         lp = lb->lb_ports[p];
2152
2153         /*
2154          * Check the port's link state. This will return the next active
2155          * port if the link is down or the port is NULL.
2156          */
2157         if ((lp = lagg_link_active(sc, lp)) == NULL) {
2158                 m_freem(m);
2159                 return (ENETDOWN);
2160         }
2161
2162         /* Send mbuf */
2163         return (lagg_enqueue(lp->lp_ifp, m));
2164 }
2165
2166 static struct mbuf *
2167 lagg_lb_input(struct lagg_softc *sc, struct lagg_port *lp, struct mbuf *m)
2168 {
2169         struct ifnet *ifp = sc->sc_ifp;
2170
2171         /* Just pass in the packet to our lagg device */
2172         m->m_pkthdr.rcvif = ifp;
2173
2174         return (m);
2175 }
2176
2177 /*
2178  * 802.3ad LACP
2179  */
2180 static void
2181 lagg_lacp_attach(struct lagg_softc *sc)
2182 {
2183         struct lagg_port *lp;
2184
2185         lacp_attach(sc);
2186         LAGG_XLOCK_ASSERT(sc);
2187         CK_SLIST_FOREACH(lp, &sc->sc_ports, lp_entries)
2188                 lacp_port_create(lp);
2189 }
2190
2191 static void
2192 lagg_lacp_detach(struct lagg_softc *sc)
2193 {
2194         struct lagg_port *lp;
2195         void *psc;
2196
2197         LAGG_XLOCK_ASSERT(sc);
2198         CK_SLIST_FOREACH(lp, &sc->sc_ports, lp_entries)
2199                 lacp_port_destroy(lp);
2200
2201         psc = sc->sc_psc;
2202         sc->sc_psc = NULL;
2203         lacp_detach(psc);
2204 }
2205
2206 static void
2207 lagg_lacp_lladdr(struct lagg_softc *sc)
2208 {
2209         struct lagg_port *lp;
2210
2211         LAGG_SXLOCK_ASSERT(sc);
2212
2213         /* purge all the lacp ports */
2214         CK_SLIST_FOREACH(lp, &sc->sc_ports, lp_entries)
2215                 lacp_port_destroy(lp);
2216
2217         /* add them back in */
2218         CK_SLIST_FOREACH(lp, &sc->sc_ports, lp_entries)
2219                 lacp_port_create(lp);
2220 }
2221
2222 static int
2223 lagg_lacp_start(struct lagg_softc *sc, struct mbuf *m)
2224 {
2225         struct lagg_port *lp;
2226
2227         lp = lacp_select_tx_port(sc, m);
2228         if (lp == NULL) {
2229                 m_freem(m);
2230                 return (ENETDOWN);
2231         }
2232
2233         /* Send mbuf */
2234         return (lagg_enqueue(lp->lp_ifp, m));
2235 }
2236
2237 static struct mbuf *
2238 lagg_lacp_input(struct lagg_softc *sc, struct lagg_port *lp, struct mbuf *m)
2239 {
2240         struct ifnet *ifp = sc->sc_ifp;
2241         struct ether_header *eh;
2242         u_short etype;
2243
2244         eh = mtod(m, struct ether_header *);
2245         etype = ntohs(eh->ether_type);
2246
2247         /* Tap off LACP control messages */
2248         if ((m->m_flags & M_VLANTAG) == 0 && etype == ETHERTYPE_SLOW) {
2249                 m = lacp_input(lp, m);
2250                 if (m == NULL)
2251                         return (NULL);
2252         }
2253
2254         /*
2255          * If the port is not collecting or not in the active aggregator then
2256          * free and return.
2257          */
2258         if (lacp_iscollecting(lp) == 0 || lacp_isactive(lp) == 0) {
2259                 m_freem(m);
2260                 return (NULL);
2261         }
2262
2263         m->m_pkthdr.rcvif = ifp;
2264         return (m);
2265 }
2266