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