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