xref: /linux/drivers/net/bonding/bond_main.c (revision cf6d9fe09185aa7e296c24385940f29a1364e87d)
1 // SPDX-License-Identifier: GPL-1.0+
2 /*
3  * originally based on the dummy device.
4  *
5  * Copyright 1999, Thomas Davis, tadavis@lbl.gov.
6  * Based on dummy.c, and eql.c devices.
7  *
8  * bonding.c: an Ethernet Bonding driver
9  *
10  * This is useful to talk to a Cisco EtherChannel compatible equipment:
11  *	Cisco 5500
12  *	Sun Trunking (Solaris)
13  *	Alteon AceDirector Trunks
14  *	Linux Bonding
15  *	and probably many L2 switches ...
16  *
17  * How it works:
18  *    ifconfig bond0 ipaddress netmask up
19  *      will setup a network device, with an ip address.  No mac address
20  *	will be assigned at this time.  The hw mac address will come from
21  *	the first slave bonded to the channel.  All slaves will then use
22  *	this hw mac address.
23  *
24  *    ifconfig bond0 down
25  *         will release all slaves, marking them as down.
26  *
27  *    ifenslave bond0 eth0
28  *	will attach eth0 to bond0 as a slave.  eth0 hw mac address will either
29  *	a: be used as initial mac address
30  *	b: if a hw mac address already is there, eth0's hw mac address
31  *	   will then be set from bond0.
32  *
33  */
34 
35 #include <linux/kernel.h>
36 #include <linux/module.h>
37 #include <linux/types.h>
38 #include <linux/fcntl.h>
39 #include <linux/filter.h>
40 #include <linux/interrupt.h>
41 #include <linux/ptrace.h>
42 #include <linux/ioport.h>
43 #include <linux/in.h>
44 #include <net/ip.h>
45 #include <linux/ip.h>
46 #include <linux/icmp.h>
47 #include <linux/icmpv6.h>
48 #include <linux/tcp.h>
49 #include <linux/udp.h>
50 #include <linux/slab.h>
51 #include <linux/string.h>
52 #include <linux/init.h>
53 #include <linux/timer.h>
54 #include <linux/socket.h>
55 #include <linux/ctype.h>
56 #include <linux/inet.h>
57 #include <linux/bitops.h>
58 #include <linux/io.h>
59 #include <asm/dma.h>
60 #include <linux/uaccess.h>
61 #include <linux/errno.h>
62 #include <linux/netdevice.h>
63 #include <linux/inetdevice.h>
64 #include <linux/igmp.h>
65 #include <linux/etherdevice.h>
66 #include <linux/skbuff.h>
67 #include <net/sock.h>
68 #include <linux/rtnetlink.h>
69 #include <linux/smp.h>
70 #include <linux/if_ether.h>
71 #include <net/arp.h>
72 #include <linux/mii.h>
73 #include <linux/ethtool.h>
74 #include <linux/if_vlan.h>
75 #include <linux/if_bonding.h>
76 #include <linux/phy.h>
77 #include <linux/jiffies.h>
78 #include <linux/preempt.h>
79 #include <net/route.h>
80 #include <net/net_namespace.h>
81 #include <net/netns/generic.h>
82 #include <net/pkt_sched.h>
83 #include <linux/rculist.h>
84 #include <net/flow_dissector.h>
85 #include <net/xfrm.h>
86 #include <net/bonding.h>
87 #include <net/bond_3ad.h>
88 #include <net/bond_alb.h>
89 #if IS_ENABLED(CONFIG_TLS_DEVICE)
90 #include <net/tls.h>
91 #endif
92 #include <net/ip6_route.h>
93 #include <net/xdp.h>
94 
95 #include "bonding_priv.h"
96 
97 /*---------------------------- Module parameters ----------------------------*/
98 
99 /* monitor all links that often (in milliseconds). <=0 disables monitoring */
100 
101 static int max_bonds	= BOND_DEFAULT_MAX_BONDS;
102 static int tx_queues	= BOND_DEFAULT_TX_QUEUES;
103 static int num_peer_notif = 1;
104 static int miimon;
105 static int updelay;
106 static int downdelay;
107 static int use_carrier	= 1;
108 static char *mode;
109 static char *primary;
110 static char *primary_reselect;
111 static char *lacp_rate;
112 static int min_links;
113 static char *ad_select;
114 static char *xmit_hash_policy;
115 static int arp_interval;
116 static char *arp_ip_target[BOND_MAX_ARP_TARGETS];
117 static char *arp_validate;
118 static char *arp_all_targets;
119 static char *fail_over_mac;
120 static int all_slaves_active;
121 static struct bond_params bonding_defaults;
122 static int resend_igmp = BOND_DEFAULT_RESEND_IGMP;
123 static int packets_per_slave = 1;
124 static int lp_interval = BOND_ALB_DEFAULT_LP_INTERVAL;
125 
126 module_param(max_bonds, int, 0);
127 MODULE_PARM_DESC(max_bonds, "Max number of bonded devices");
128 module_param(tx_queues, int, 0);
129 MODULE_PARM_DESC(tx_queues, "Max number of transmit queues (default = 16)");
130 module_param_named(num_grat_arp, num_peer_notif, int, 0644);
131 MODULE_PARM_DESC(num_grat_arp, "Number of peer notifications to send on "
132 			       "failover event (alias of num_unsol_na)");
133 module_param_named(num_unsol_na, num_peer_notif, int, 0644);
134 MODULE_PARM_DESC(num_unsol_na, "Number of peer notifications to send on "
135 			       "failover event (alias of num_grat_arp)");
136 module_param(miimon, int, 0);
137 MODULE_PARM_DESC(miimon, "Link check interval in milliseconds");
138 module_param(updelay, int, 0);
139 MODULE_PARM_DESC(updelay, "Delay before considering link up, in milliseconds");
140 module_param(downdelay, int, 0);
141 MODULE_PARM_DESC(downdelay, "Delay before considering link down, "
142 			    "in milliseconds");
143 module_param(use_carrier, int, 0);
144 MODULE_PARM_DESC(use_carrier, "Use netif_carrier_ok (vs MII ioctls) in miimon; "
145 			      "0 for off, 1 for on (default)");
146 module_param(mode, charp, 0);
147 MODULE_PARM_DESC(mode, "Mode of operation; 0 for balance-rr, "
148 		       "1 for active-backup, 2 for balance-xor, "
149 		       "3 for broadcast, 4 for 802.3ad, 5 for balance-tlb, "
150 		       "6 for balance-alb");
151 module_param(primary, charp, 0);
152 MODULE_PARM_DESC(primary, "Primary network device to use");
153 module_param(primary_reselect, charp, 0);
154 MODULE_PARM_DESC(primary_reselect, "Reselect primary slave "
155 				   "once it comes up; "
156 				   "0 for always (default), "
157 				   "1 for only if speed of primary is "
158 				   "better, "
159 				   "2 for only on active slave "
160 				   "failure");
161 module_param(lacp_rate, charp, 0);
162 MODULE_PARM_DESC(lacp_rate, "LACPDU tx rate to request from 802.3ad partner; "
163 			    "0 for slow, 1 for fast");
164 module_param(ad_select, charp, 0);
165 MODULE_PARM_DESC(ad_select, "802.3ad aggregation selection logic; "
166 			    "0 for stable (default), 1 for bandwidth, "
167 			    "2 for count");
168 module_param(min_links, int, 0);
169 MODULE_PARM_DESC(min_links, "Minimum number of available links before turning on carrier");
170 
171 module_param(xmit_hash_policy, charp, 0);
172 MODULE_PARM_DESC(xmit_hash_policy, "balance-alb, balance-tlb, balance-xor, 802.3ad hashing method; "
173 				   "0 for layer 2 (default), 1 for layer 3+4, "
174 				   "2 for layer 2+3, 3 for encap layer 2+3, "
175 				   "4 for encap layer 3+4, 5 for vlan+srcmac");
176 module_param(arp_interval, int, 0);
177 MODULE_PARM_DESC(arp_interval, "arp interval in milliseconds");
178 module_param_array(arp_ip_target, charp, NULL, 0);
179 MODULE_PARM_DESC(arp_ip_target, "arp targets in n.n.n.n form");
180 module_param(arp_validate, charp, 0);
181 MODULE_PARM_DESC(arp_validate, "validate src/dst of ARP probes; "
182 			       "0 for none (default), 1 for active, "
183 			       "2 for backup, 3 for all");
184 module_param(arp_all_targets, charp, 0);
185 MODULE_PARM_DESC(arp_all_targets, "fail on any/all arp targets timeout; 0 for any (default), 1 for all");
186 module_param(fail_over_mac, charp, 0);
187 MODULE_PARM_DESC(fail_over_mac, "For active-backup, do not set all slaves to "
188 				"the same MAC; 0 for none (default), "
189 				"1 for active, 2 for follow");
190 module_param(all_slaves_active, int, 0);
191 MODULE_PARM_DESC(all_slaves_active, "Keep all frames received on an interface "
192 				     "by setting active flag for all slaves; "
193 				     "0 for never (default), 1 for always.");
194 module_param(resend_igmp, int, 0);
195 MODULE_PARM_DESC(resend_igmp, "Number of IGMP membership reports to send on "
196 			      "link failure");
197 module_param(packets_per_slave, int, 0);
198 MODULE_PARM_DESC(packets_per_slave, "Packets to send per slave in balance-rr "
199 				    "mode; 0 for a random slave, 1 packet per "
200 				    "slave (default), >1 packets per slave.");
201 module_param(lp_interval, uint, 0);
202 MODULE_PARM_DESC(lp_interval, "The number of seconds between instances where "
203 			      "the bonding driver sends learning packets to "
204 			      "each slaves peer switch. The default is 1.");
205 
206 /*----------------------------- Global variables ----------------------------*/
207 
208 #ifdef CONFIG_NET_POLL_CONTROLLER
209 atomic_t netpoll_block_tx = ATOMIC_INIT(0);
210 #endif
211 
212 unsigned int bond_net_id __read_mostly;
213 
214 static const struct flow_dissector_key flow_keys_bonding_keys[] = {
215 	{
216 		.key_id = FLOW_DISSECTOR_KEY_CONTROL,
217 		.offset = offsetof(struct flow_keys, control),
218 	},
219 	{
220 		.key_id = FLOW_DISSECTOR_KEY_BASIC,
221 		.offset = offsetof(struct flow_keys, basic),
222 	},
223 	{
224 		.key_id = FLOW_DISSECTOR_KEY_IPV4_ADDRS,
225 		.offset = offsetof(struct flow_keys, addrs.v4addrs),
226 	},
227 	{
228 		.key_id = FLOW_DISSECTOR_KEY_IPV6_ADDRS,
229 		.offset = offsetof(struct flow_keys, addrs.v6addrs),
230 	},
231 	{
232 		.key_id = FLOW_DISSECTOR_KEY_TIPC,
233 		.offset = offsetof(struct flow_keys, addrs.tipckey),
234 	},
235 	{
236 		.key_id = FLOW_DISSECTOR_KEY_PORTS,
237 		.offset = offsetof(struct flow_keys, ports),
238 	},
239 	{
240 		.key_id = FLOW_DISSECTOR_KEY_ICMP,
241 		.offset = offsetof(struct flow_keys, icmp),
242 	},
243 	{
244 		.key_id = FLOW_DISSECTOR_KEY_VLAN,
245 		.offset = offsetof(struct flow_keys, vlan),
246 	},
247 	{
248 		.key_id = FLOW_DISSECTOR_KEY_FLOW_LABEL,
249 		.offset = offsetof(struct flow_keys, tags),
250 	},
251 	{
252 		.key_id = FLOW_DISSECTOR_KEY_GRE_KEYID,
253 		.offset = offsetof(struct flow_keys, keyid),
254 	},
255 };
256 
257 static struct flow_dissector flow_keys_bonding __read_mostly;
258 
259 /*-------------------------- Forward declarations ---------------------------*/
260 
261 static int bond_init(struct net_device *bond_dev);
262 static void bond_uninit(struct net_device *bond_dev);
263 static void bond_get_stats(struct net_device *bond_dev,
264 			   struct rtnl_link_stats64 *stats);
265 static void bond_slave_arr_handler(struct work_struct *work);
266 static bool bond_time_in_interval(struct bonding *bond, unsigned long last_act,
267 				  int mod);
268 static void bond_netdev_notify_work(struct work_struct *work);
269 
270 /*---------------------------- General routines -----------------------------*/
271 
272 const char *bond_mode_name(int mode)
273 {
274 	static const char *names[] = {
275 		[BOND_MODE_ROUNDROBIN] = "load balancing (round-robin)",
276 		[BOND_MODE_ACTIVEBACKUP] = "fault-tolerance (active-backup)",
277 		[BOND_MODE_XOR] = "load balancing (xor)",
278 		[BOND_MODE_BROADCAST] = "fault-tolerance (broadcast)",
279 		[BOND_MODE_8023AD] = "IEEE 802.3ad Dynamic link aggregation",
280 		[BOND_MODE_TLB] = "transmit load balancing",
281 		[BOND_MODE_ALB] = "adaptive load balancing",
282 	};
283 
284 	if (mode < BOND_MODE_ROUNDROBIN || mode > BOND_MODE_ALB)
285 		return "unknown";
286 
287 	return names[mode];
288 }
289 
290 /**
291  * bond_dev_queue_xmit - Prepare skb for xmit.
292  *
293  * @bond: bond device that got this skb for tx.
294  * @skb: hw accel VLAN tagged skb to transmit
295  * @slave_dev: slave that is supposed to xmit this skbuff
296  */
297 netdev_tx_t bond_dev_queue_xmit(struct bonding *bond, struct sk_buff *skb,
298 			struct net_device *slave_dev)
299 {
300 	skb->dev = slave_dev;
301 
302 	BUILD_BUG_ON(sizeof(skb->queue_mapping) !=
303 		     sizeof(qdisc_skb_cb(skb)->slave_dev_queue_mapping));
304 	skb_set_queue_mapping(skb, qdisc_skb_cb(skb)->slave_dev_queue_mapping);
305 
306 	if (unlikely(netpoll_tx_running(bond->dev)))
307 		return bond_netpoll_send_skb(bond_get_slave_by_dev(bond, slave_dev), skb);
308 
309 	return dev_queue_xmit(skb);
310 }
311 
312 static bool bond_sk_check(struct bonding *bond)
313 {
314 	switch (BOND_MODE(bond)) {
315 	case BOND_MODE_8023AD:
316 	case BOND_MODE_XOR:
317 		if (bond->params.xmit_policy == BOND_XMIT_POLICY_LAYER34)
318 			return true;
319 		fallthrough;
320 	default:
321 		return false;
322 	}
323 }
324 
325 static bool bond_xdp_check(struct bonding *bond)
326 {
327 	switch (BOND_MODE(bond)) {
328 	case BOND_MODE_ROUNDROBIN:
329 	case BOND_MODE_ACTIVEBACKUP:
330 		return true;
331 	case BOND_MODE_8023AD:
332 	case BOND_MODE_XOR:
333 		/* vlan+srcmac is not supported with XDP as in most cases the 802.1q
334 		 * payload is not in the packet due to hardware offload.
335 		 */
336 		if (bond->params.xmit_policy != BOND_XMIT_POLICY_VLAN_SRCMAC)
337 			return true;
338 		fallthrough;
339 	default:
340 		return false;
341 	}
342 }
343 
344 /*---------------------------------- VLAN -----------------------------------*/
345 
346 /* In the following 2 functions, bond_vlan_rx_add_vid and bond_vlan_rx_kill_vid,
347  * We don't protect the slave list iteration with a lock because:
348  * a. This operation is performed in IOCTL context,
349  * b. The operation is protected by the RTNL semaphore in the 8021q code,
350  * c. Holding a lock with BH disabled while directly calling a base driver
351  *    entry point is generally a BAD idea.
352  *
353  * The design of synchronization/protection for this operation in the 8021q
354  * module is good for one or more VLAN devices over a single physical device
355  * and cannot be extended for a teaming solution like bonding, so there is a
356  * potential race condition here where a net device from the vlan group might
357  * be referenced (either by a base driver or the 8021q code) while it is being
358  * removed from the system. However, it turns out we're not making matters
359  * worse, and if it works for regular VLAN usage it will work here too.
360 */
361 
362 /**
363  * bond_vlan_rx_add_vid - Propagates adding an id to slaves
364  * @bond_dev: bonding net device that got called
365  * @proto: network protocol ID
366  * @vid: vlan id being added
367  */
368 static int bond_vlan_rx_add_vid(struct net_device *bond_dev,
369 				__be16 proto, u16 vid)
370 {
371 	struct bonding *bond = netdev_priv(bond_dev);
372 	struct slave *slave, *rollback_slave;
373 	struct list_head *iter;
374 	int res;
375 
376 	bond_for_each_slave(bond, slave, iter) {
377 		res = vlan_vid_add(slave->dev, proto, vid);
378 		if (res)
379 			goto unwind;
380 	}
381 
382 	return 0;
383 
384 unwind:
385 	/* unwind to the slave that failed */
386 	bond_for_each_slave(bond, rollback_slave, iter) {
387 		if (rollback_slave == slave)
388 			break;
389 
390 		vlan_vid_del(rollback_slave->dev, proto, vid);
391 	}
392 
393 	return res;
394 }
395 
396 /**
397  * bond_vlan_rx_kill_vid - Propagates deleting an id to slaves
398  * @bond_dev: bonding net device that got called
399  * @proto: network protocol ID
400  * @vid: vlan id being removed
401  */
402 static int bond_vlan_rx_kill_vid(struct net_device *bond_dev,
403 				 __be16 proto, u16 vid)
404 {
405 	struct bonding *bond = netdev_priv(bond_dev);
406 	struct list_head *iter;
407 	struct slave *slave;
408 
409 	bond_for_each_slave(bond, slave, iter)
410 		vlan_vid_del(slave->dev, proto, vid);
411 
412 	if (bond_is_lb(bond))
413 		bond_alb_clear_vlan(bond, vid);
414 
415 	return 0;
416 }
417 
418 /*---------------------------------- XFRM -----------------------------------*/
419 
420 #ifdef CONFIG_XFRM_OFFLOAD
421 /**
422  * bond_ipsec_dev - Get active device for IPsec offload
423  * @xs: pointer to transformer state struct
424  *
425  * Context: caller must hold rcu_read_lock.
426  *
427  * Return: the device for ipsec offload, or NULL if not exist.
428  **/
429 static struct net_device *bond_ipsec_dev(struct xfrm_state *xs)
430 {
431 	struct net_device *bond_dev = xs->xso.dev;
432 	struct bonding *bond;
433 	struct slave *slave;
434 
435 	if (!bond_dev)
436 		return NULL;
437 
438 	bond = netdev_priv(bond_dev);
439 	if (BOND_MODE(bond) != BOND_MODE_ACTIVEBACKUP)
440 		return NULL;
441 
442 	slave = rcu_dereference(bond->curr_active_slave);
443 	if (!slave)
444 		return NULL;
445 
446 	if (!xs->xso.real_dev)
447 		return NULL;
448 
449 	if (xs->xso.real_dev != slave->dev)
450 		pr_warn_ratelimited("%s: (slave %s): not same with IPsec offload real dev %s\n",
451 				    bond_dev->name, slave->dev->name, xs->xso.real_dev->name);
452 
453 	return slave->dev;
454 }
455 
456 /**
457  * bond_ipsec_add_sa - program device with a security association
458  * @xs: pointer to transformer state struct
459  * @extack: extack point to fill failure reason
460  **/
461 static int bond_ipsec_add_sa(struct xfrm_state *xs,
462 			     struct netlink_ext_ack *extack)
463 {
464 	struct net_device *bond_dev = xs->xso.dev;
465 	struct net_device *real_dev;
466 	netdevice_tracker tracker;
467 	struct bond_ipsec *ipsec;
468 	struct bonding *bond;
469 	struct slave *slave;
470 	int err;
471 
472 	if (!bond_dev)
473 		return -EINVAL;
474 
475 	rcu_read_lock();
476 	bond = netdev_priv(bond_dev);
477 	slave = rcu_dereference(bond->curr_active_slave);
478 	real_dev = slave ? slave->dev : NULL;
479 	netdev_hold(real_dev, &tracker, GFP_ATOMIC);
480 	rcu_read_unlock();
481 	if (!real_dev) {
482 		err = -ENODEV;
483 		goto out;
484 	}
485 
486 	if (!real_dev->xfrmdev_ops ||
487 	    !real_dev->xfrmdev_ops->xdo_dev_state_add ||
488 	    netif_is_bond_master(real_dev)) {
489 		NL_SET_ERR_MSG_MOD(extack, "Slave does not support ipsec offload");
490 		err = -EINVAL;
491 		goto out;
492 	}
493 
494 	ipsec = kmalloc(sizeof(*ipsec), GFP_KERNEL);
495 	if (!ipsec) {
496 		err = -ENOMEM;
497 		goto out;
498 	}
499 
500 	xs->xso.real_dev = real_dev;
501 	err = real_dev->xfrmdev_ops->xdo_dev_state_add(xs, extack);
502 	if (!err) {
503 		ipsec->xs = xs;
504 		INIT_LIST_HEAD(&ipsec->list);
505 		mutex_lock(&bond->ipsec_lock);
506 		list_add(&ipsec->list, &bond->ipsec_list);
507 		mutex_unlock(&bond->ipsec_lock);
508 	} else {
509 		kfree(ipsec);
510 	}
511 out:
512 	netdev_put(real_dev, &tracker);
513 	return err;
514 }
515 
516 static void bond_ipsec_add_sa_all(struct bonding *bond)
517 {
518 	struct net_device *bond_dev = bond->dev;
519 	struct net_device *real_dev;
520 	struct bond_ipsec *ipsec;
521 	struct slave *slave;
522 
523 	slave = rtnl_dereference(bond->curr_active_slave);
524 	real_dev = slave ? slave->dev : NULL;
525 	if (!real_dev)
526 		return;
527 
528 	mutex_lock(&bond->ipsec_lock);
529 	if (!real_dev->xfrmdev_ops ||
530 	    !real_dev->xfrmdev_ops->xdo_dev_state_add ||
531 	    netif_is_bond_master(real_dev)) {
532 		if (!list_empty(&bond->ipsec_list))
533 			slave_warn(bond_dev, real_dev,
534 				   "%s: no slave xdo_dev_state_add\n",
535 				   __func__);
536 		goto out;
537 	}
538 
539 	list_for_each_entry(ipsec, &bond->ipsec_list, list) {
540 		/* If new state is added before ipsec_lock acquired */
541 		if (ipsec->xs->xso.real_dev == real_dev)
542 			continue;
543 
544 		ipsec->xs->xso.real_dev = real_dev;
545 		if (real_dev->xfrmdev_ops->xdo_dev_state_add(ipsec->xs, NULL)) {
546 			slave_warn(bond_dev, real_dev, "%s: failed to add SA\n", __func__);
547 			ipsec->xs->xso.real_dev = NULL;
548 		}
549 	}
550 out:
551 	mutex_unlock(&bond->ipsec_lock);
552 }
553 
554 /**
555  * bond_ipsec_del_sa - clear out this specific SA
556  * @xs: pointer to transformer state struct
557  **/
558 static void bond_ipsec_del_sa(struct xfrm_state *xs)
559 {
560 	struct net_device *bond_dev = xs->xso.dev;
561 	struct net_device *real_dev;
562 	netdevice_tracker tracker;
563 	struct bond_ipsec *ipsec;
564 	struct bonding *bond;
565 	struct slave *slave;
566 
567 	if (!bond_dev)
568 		return;
569 
570 	rcu_read_lock();
571 	bond = netdev_priv(bond_dev);
572 	slave = rcu_dereference(bond->curr_active_slave);
573 	real_dev = slave ? slave->dev : NULL;
574 	netdev_hold(real_dev, &tracker, GFP_ATOMIC);
575 	rcu_read_unlock();
576 
577 	if (!slave)
578 		goto out;
579 
580 	if (!xs->xso.real_dev)
581 		goto out;
582 
583 	WARN_ON(xs->xso.real_dev != real_dev);
584 
585 	if (!real_dev->xfrmdev_ops ||
586 	    !real_dev->xfrmdev_ops->xdo_dev_state_delete ||
587 	    netif_is_bond_master(real_dev)) {
588 		slave_warn(bond_dev, real_dev, "%s: no slave xdo_dev_state_delete\n", __func__);
589 		goto out;
590 	}
591 
592 	real_dev->xfrmdev_ops->xdo_dev_state_delete(xs);
593 out:
594 	netdev_put(real_dev, &tracker);
595 	mutex_lock(&bond->ipsec_lock);
596 	list_for_each_entry(ipsec, &bond->ipsec_list, list) {
597 		if (ipsec->xs == xs) {
598 			list_del(&ipsec->list);
599 			kfree(ipsec);
600 			break;
601 		}
602 	}
603 	mutex_unlock(&bond->ipsec_lock);
604 }
605 
606 static void bond_ipsec_del_sa_all(struct bonding *bond)
607 {
608 	struct net_device *bond_dev = bond->dev;
609 	struct net_device *real_dev;
610 	struct bond_ipsec *ipsec;
611 	struct slave *slave;
612 
613 	slave = rtnl_dereference(bond->curr_active_slave);
614 	real_dev = slave ? slave->dev : NULL;
615 	if (!real_dev)
616 		return;
617 
618 	mutex_lock(&bond->ipsec_lock);
619 	list_for_each_entry(ipsec, &bond->ipsec_list, list) {
620 		if (!ipsec->xs->xso.real_dev)
621 			continue;
622 
623 		if (!real_dev->xfrmdev_ops ||
624 		    !real_dev->xfrmdev_ops->xdo_dev_state_delete ||
625 		    netif_is_bond_master(real_dev)) {
626 			slave_warn(bond_dev, real_dev,
627 				   "%s: no slave xdo_dev_state_delete\n",
628 				   __func__);
629 		} else {
630 			real_dev->xfrmdev_ops->xdo_dev_state_delete(ipsec->xs);
631 			if (real_dev->xfrmdev_ops->xdo_dev_state_free)
632 				real_dev->xfrmdev_ops->xdo_dev_state_free(ipsec->xs);
633 		}
634 	}
635 	mutex_unlock(&bond->ipsec_lock);
636 }
637 
638 static void bond_ipsec_free_sa(struct xfrm_state *xs)
639 {
640 	struct net_device *bond_dev = xs->xso.dev;
641 	struct net_device *real_dev;
642 	netdevice_tracker tracker;
643 	struct bonding *bond;
644 	struct slave *slave;
645 
646 	if (!bond_dev)
647 		return;
648 
649 	rcu_read_lock();
650 	bond = netdev_priv(bond_dev);
651 	slave = rcu_dereference(bond->curr_active_slave);
652 	real_dev = slave ? slave->dev : NULL;
653 	netdev_hold(real_dev, &tracker, GFP_ATOMIC);
654 	rcu_read_unlock();
655 
656 	if (!slave)
657 		goto out;
658 
659 	if (!xs->xso.real_dev)
660 		goto out;
661 
662 	WARN_ON(xs->xso.real_dev != real_dev);
663 
664 	if (real_dev && real_dev->xfrmdev_ops &&
665 	    real_dev->xfrmdev_ops->xdo_dev_state_free)
666 		real_dev->xfrmdev_ops->xdo_dev_state_free(xs);
667 out:
668 	netdev_put(real_dev, &tracker);
669 }
670 
671 /**
672  * bond_ipsec_offload_ok - can this packet use the xfrm hw offload
673  * @skb: current data packet
674  * @xs: pointer to transformer state struct
675  **/
676 static bool bond_ipsec_offload_ok(struct sk_buff *skb, struct xfrm_state *xs)
677 {
678 	struct net_device *real_dev;
679 	bool ok = false;
680 
681 	rcu_read_lock();
682 	real_dev = bond_ipsec_dev(xs);
683 	if (!real_dev)
684 		goto out;
685 
686 	if (!real_dev->xfrmdev_ops ||
687 	    !real_dev->xfrmdev_ops->xdo_dev_offload_ok ||
688 	    netif_is_bond_master(real_dev))
689 		goto out;
690 
691 	ok = real_dev->xfrmdev_ops->xdo_dev_offload_ok(skb, xs);
692 out:
693 	rcu_read_unlock();
694 	return ok;
695 }
696 
697 /**
698  * bond_advance_esn_state - ESN support for IPSec HW offload
699  * @xs: pointer to transformer state struct
700  **/
701 static void bond_advance_esn_state(struct xfrm_state *xs)
702 {
703 	struct net_device *real_dev;
704 
705 	rcu_read_lock();
706 	real_dev = bond_ipsec_dev(xs);
707 	if (!real_dev)
708 		goto out;
709 
710 	if (!real_dev->xfrmdev_ops ||
711 	    !real_dev->xfrmdev_ops->xdo_dev_state_advance_esn) {
712 		pr_warn_ratelimited("%s: %s doesn't support xdo_dev_state_advance_esn\n", __func__, real_dev->name);
713 		goto out;
714 	}
715 
716 	real_dev->xfrmdev_ops->xdo_dev_state_advance_esn(xs);
717 out:
718 	rcu_read_unlock();
719 }
720 
721 /**
722  * bond_xfrm_update_stats - Update xfrm state
723  * @xs: pointer to transformer state struct
724  **/
725 static void bond_xfrm_update_stats(struct xfrm_state *xs)
726 {
727 	struct net_device *real_dev;
728 
729 	rcu_read_lock();
730 	real_dev = bond_ipsec_dev(xs);
731 	if (!real_dev)
732 		goto out;
733 
734 	if (!real_dev->xfrmdev_ops ||
735 	    !real_dev->xfrmdev_ops->xdo_dev_state_update_stats) {
736 		pr_warn_ratelimited("%s: %s doesn't support xdo_dev_state_update_stats\n", __func__, real_dev->name);
737 		goto out;
738 	}
739 
740 	real_dev->xfrmdev_ops->xdo_dev_state_update_stats(xs);
741 out:
742 	rcu_read_unlock();
743 }
744 
745 static const struct xfrmdev_ops bond_xfrmdev_ops = {
746 	.xdo_dev_state_add = bond_ipsec_add_sa,
747 	.xdo_dev_state_delete = bond_ipsec_del_sa,
748 	.xdo_dev_state_free = bond_ipsec_free_sa,
749 	.xdo_dev_offload_ok = bond_ipsec_offload_ok,
750 	.xdo_dev_state_advance_esn = bond_advance_esn_state,
751 	.xdo_dev_state_update_stats = bond_xfrm_update_stats,
752 };
753 #endif /* CONFIG_XFRM_OFFLOAD */
754 
755 /*------------------------------- Link status -------------------------------*/
756 
757 /* Set the carrier state for the master according to the state of its
758  * slaves.  If any slaves are up, the master is up.  In 802.3ad mode,
759  * do special 802.3ad magic.
760  *
761  * Returns zero if carrier state does not change, nonzero if it does.
762  */
763 int bond_set_carrier(struct bonding *bond)
764 {
765 	struct list_head *iter;
766 	struct slave *slave;
767 
768 	if (!bond_has_slaves(bond))
769 		goto down;
770 
771 	if (BOND_MODE(bond) == BOND_MODE_8023AD)
772 		return bond_3ad_set_carrier(bond);
773 
774 	bond_for_each_slave(bond, slave, iter) {
775 		if (slave->link == BOND_LINK_UP) {
776 			if (!netif_carrier_ok(bond->dev)) {
777 				netif_carrier_on(bond->dev);
778 				return 1;
779 			}
780 			return 0;
781 		}
782 	}
783 
784 down:
785 	if (netif_carrier_ok(bond->dev)) {
786 		netif_carrier_off(bond->dev);
787 		return 1;
788 	}
789 	return 0;
790 }
791 
792 /* Get link speed and duplex from the slave's base driver
793  * using ethtool. If for some reason the call fails or the
794  * values are invalid, set speed and duplex to -1,
795  * and return. Return 1 if speed or duplex settings are
796  * UNKNOWN; 0 otherwise.
797  */
798 static int bond_update_speed_duplex(struct slave *slave)
799 {
800 	struct net_device *slave_dev = slave->dev;
801 	struct ethtool_link_ksettings ecmd;
802 	int res;
803 
804 	slave->speed = SPEED_UNKNOWN;
805 	slave->duplex = DUPLEX_UNKNOWN;
806 
807 	res = __ethtool_get_link_ksettings(slave_dev, &ecmd);
808 	if (res < 0)
809 		return 1;
810 	if (ecmd.base.speed == 0 || ecmd.base.speed == ((__u32)-1))
811 		return 1;
812 	switch (ecmd.base.duplex) {
813 	case DUPLEX_FULL:
814 	case DUPLEX_HALF:
815 		break;
816 	default:
817 		return 1;
818 	}
819 
820 	slave->speed = ecmd.base.speed;
821 	slave->duplex = ecmd.base.duplex;
822 
823 	return 0;
824 }
825 
826 const char *bond_slave_link_status(s8 link)
827 {
828 	switch (link) {
829 	case BOND_LINK_UP:
830 		return "up";
831 	case BOND_LINK_FAIL:
832 		return "going down";
833 	case BOND_LINK_DOWN:
834 		return "down";
835 	case BOND_LINK_BACK:
836 		return "going back";
837 	default:
838 		return "unknown";
839 	}
840 }
841 
842 /* if <dev> supports MII link status reporting, check its link status.
843  *
844  * We either do MII/ETHTOOL ioctls, or check netif_carrier_ok(),
845  * depending upon the setting of the use_carrier parameter.
846  *
847  * Return either BMSR_LSTATUS, meaning that the link is up (or we
848  * can't tell and just pretend it is), or 0, meaning that the link is
849  * down.
850  *
851  * If reporting is non-zero, instead of faking link up, return -1 if
852  * both ETHTOOL and MII ioctls fail (meaning the device does not
853  * support them).  If use_carrier is set, return whatever it says.
854  * It'd be nice if there was a good way to tell if a driver supports
855  * netif_carrier, but there really isn't.
856  */
857 static int bond_check_dev_link(struct bonding *bond,
858 			       struct net_device *slave_dev, int reporting)
859 {
860 	const struct net_device_ops *slave_ops = slave_dev->netdev_ops;
861 	int (*ioctl)(struct net_device *, struct ifreq *, int);
862 	struct ifreq ifr;
863 	struct mii_ioctl_data *mii;
864 
865 	if (!reporting && !netif_running(slave_dev))
866 		return 0;
867 
868 	if (bond->params.use_carrier)
869 		return netif_carrier_ok(slave_dev) ? BMSR_LSTATUS : 0;
870 
871 	/* Try to get link status using Ethtool first. */
872 	if (slave_dev->ethtool_ops->get_link)
873 		return slave_dev->ethtool_ops->get_link(slave_dev) ?
874 			BMSR_LSTATUS : 0;
875 
876 	/* Ethtool can't be used, fallback to MII ioctls. */
877 	ioctl = slave_ops->ndo_eth_ioctl;
878 	if (ioctl) {
879 		/* TODO: set pointer to correct ioctl on a per team member
880 		 *       bases to make this more efficient. that is, once
881 		 *       we determine the correct ioctl, we will always
882 		 *       call it and not the others for that team
883 		 *       member.
884 		 */
885 
886 		/* We cannot assume that SIOCGMIIPHY will also read a
887 		 * register; not all network drivers (e.g., e100)
888 		 * support that.
889 		 */
890 
891 		/* Yes, the mii is overlaid on the ifreq.ifr_ifru */
892 		strscpy_pad(ifr.ifr_name, slave_dev->name, IFNAMSIZ);
893 		mii = if_mii(&ifr);
894 		if (ioctl(slave_dev, &ifr, SIOCGMIIPHY) == 0) {
895 			mii->reg_num = MII_BMSR;
896 			if (ioctl(slave_dev, &ifr, SIOCGMIIREG) == 0)
897 				return mii->val_out & BMSR_LSTATUS;
898 		}
899 	}
900 
901 	/* If reporting, report that either there's no ndo_eth_ioctl,
902 	 * or both SIOCGMIIREG and get_link failed (meaning that we
903 	 * cannot report link status).  If not reporting, pretend
904 	 * we're ok.
905 	 */
906 	return reporting ? -1 : BMSR_LSTATUS;
907 }
908 
909 /*----------------------------- Multicast list ------------------------------*/
910 
911 /* Push the promiscuity flag down to appropriate slaves */
912 static int bond_set_promiscuity(struct bonding *bond, int inc)
913 {
914 	struct list_head *iter;
915 	int err = 0;
916 
917 	if (bond_uses_primary(bond)) {
918 		struct slave *curr_active = rtnl_dereference(bond->curr_active_slave);
919 
920 		if (curr_active)
921 			err = dev_set_promiscuity(curr_active->dev, inc);
922 	} else {
923 		struct slave *slave;
924 
925 		bond_for_each_slave(bond, slave, iter) {
926 			err = dev_set_promiscuity(slave->dev, inc);
927 			if (err)
928 				return err;
929 		}
930 	}
931 	return err;
932 }
933 
934 /* Push the allmulti flag down to all slaves */
935 static int bond_set_allmulti(struct bonding *bond, int inc)
936 {
937 	struct list_head *iter;
938 	int err = 0;
939 
940 	if (bond_uses_primary(bond)) {
941 		struct slave *curr_active = rtnl_dereference(bond->curr_active_slave);
942 
943 		if (curr_active)
944 			err = dev_set_allmulti(curr_active->dev, inc);
945 	} else {
946 		struct slave *slave;
947 
948 		bond_for_each_slave(bond, slave, iter) {
949 			err = dev_set_allmulti(slave->dev, inc);
950 			if (err)
951 				return err;
952 		}
953 	}
954 	return err;
955 }
956 
957 /* Retrieve the list of registered multicast addresses for the bonding
958  * device and retransmit an IGMP JOIN request to the current active
959  * slave.
960  */
961 static void bond_resend_igmp_join_requests_delayed(struct work_struct *work)
962 {
963 	struct bonding *bond = container_of(work, struct bonding,
964 					    mcast_work.work);
965 
966 	if (!rtnl_trylock()) {
967 		queue_delayed_work(bond->wq, &bond->mcast_work, 1);
968 		return;
969 	}
970 	call_netdevice_notifiers(NETDEV_RESEND_IGMP, bond->dev);
971 
972 	if (bond->igmp_retrans > 1) {
973 		bond->igmp_retrans--;
974 		queue_delayed_work(bond->wq, &bond->mcast_work, HZ/5);
975 	}
976 	rtnl_unlock();
977 }
978 
979 /* Flush bond's hardware addresses from slave */
980 static void bond_hw_addr_flush(struct net_device *bond_dev,
981 			       struct net_device *slave_dev)
982 {
983 	struct bonding *bond = netdev_priv(bond_dev);
984 
985 	dev_uc_unsync(slave_dev, bond_dev);
986 	dev_mc_unsync(slave_dev, bond_dev);
987 
988 	if (BOND_MODE(bond) == BOND_MODE_8023AD)
989 		dev_mc_del(slave_dev, lacpdu_mcast_addr);
990 }
991 
992 /*--------------------------- Active slave change ---------------------------*/
993 
994 /* Update the hardware address list and promisc/allmulti for the new and
995  * old active slaves (if any).  Modes that are not using primary keep all
996  * slaves up date at all times; only the modes that use primary need to call
997  * this function to swap these settings during a failover.
998  */
999 static void bond_hw_addr_swap(struct bonding *bond, struct slave *new_active,
1000 			      struct slave *old_active)
1001 {
1002 	if (old_active) {
1003 		if (bond->dev->flags & IFF_PROMISC)
1004 			dev_set_promiscuity(old_active->dev, -1);
1005 
1006 		if (bond->dev->flags & IFF_ALLMULTI)
1007 			dev_set_allmulti(old_active->dev, -1);
1008 
1009 		if (bond->dev->flags & IFF_UP)
1010 			bond_hw_addr_flush(bond->dev, old_active->dev);
1011 	}
1012 
1013 	if (new_active) {
1014 		/* FIXME: Signal errors upstream. */
1015 		if (bond->dev->flags & IFF_PROMISC)
1016 			dev_set_promiscuity(new_active->dev, 1);
1017 
1018 		if (bond->dev->flags & IFF_ALLMULTI)
1019 			dev_set_allmulti(new_active->dev, 1);
1020 
1021 		if (bond->dev->flags & IFF_UP) {
1022 			netif_addr_lock_bh(bond->dev);
1023 			dev_uc_sync(new_active->dev, bond->dev);
1024 			dev_mc_sync(new_active->dev, bond->dev);
1025 			netif_addr_unlock_bh(bond->dev);
1026 		}
1027 	}
1028 }
1029 
1030 /**
1031  * bond_set_dev_addr - clone slave's address to bond
1032  * @bond_dev: bond net device
1033  * @slave_dev: slave net device
1034  *
1035  * Should be called with RTNL held.
1036  */
1037 static int bond_set_dev_addr(struct net_device *bond_dev,
1038 			     struct net_device *slave_dev)
1039 {
1040 	int err;
1041 
1042 	slave_dbg(bond_dev, slave_dev, "bond_dev=%p slave_dev=%p slave_dev->addr_len=%d\n",
1043 		  bond_dev, slave_dev, slave_dev->addr_len);
1044 	err = dev_pre_changeaddr_notify(bond_dev, slave_dev->dev_addr, NULL);
1045 	if (err)
1046 		return err;
1047 
1048 	__dev_addr_set(bond_dev, slave_dev->dev_addr, slave_dev->addr_len);
1049 	bond_dev->addr_assign_type = NET_ADDR_STOLEN;
1050 	call_netdevice_notifiers(NETDEV_CHANGEADDR, bond_dev);
1051 	return 0;
1052 }
1053 
1054 static struct slave *bond_get_old_active(struct bonding *bond,
1055 					 struct slave *new_active)
1056 {
1057 	struct slave *slave;
1058 	struct list_head *iter;
1059 
1060 	bond_for_each_slave(bond, slave, iter) {
1061 		if (slave == new_active)
1062 			continue;
1063 
1064 		if (ether_addr_equal(bond->dev->dev_addr, slave->dev->dev_addr))
1065 			return slave;
1066 	}
1067 
1068 	return NULL;
1069 }
1070 
1071 /* bond_do_fail_over_mac
1072  *
1073  * Perform special MAC address swapping for fail_over_mac settings
1074  *
1075  * Called with RTNL
1076  */
1077 static void bond_do_fail_over_mac(struct bonding *bond,
1078 				  struct slave *new_active,
1079 				  struct slave *old_active)
1080 {
1081 	u8 tmp_mac[MAX_ADDR_LEN];
1082 	struct sockaddr_storage ss;
1083 	int rv;
1084 
1085 	switch (bond->params.fail_over_mac) {
1086 	case BOND_FOM_ACTIVE:
1087 		if (new_active) {
1088 			rv = bond_set_dev_addr(bond->dev, new_active->dev);
1089 			if (rv)
1090 				slave_err(bond->dev, new_active->dev, "Error %d setting bond MAC from slave\n",
1091 					  -rv);
1092 		}
1093 		break;
1094 	case BOND_FOM_FOLLOW:
1095 		/* if new_active && old_active, swap them
1096 		 * if just old_active, do nothing (going to no active slave)
1097 		 * if just new_active, set new_active to bond's MAC
1098 		 */
1099 		if (!new_active)
1100 			return;
1101 
1102 		if (!old_active)
1103 			old_active = bond_get_old_active(bond, new_active);
1104 
1105 		if (old_active) {
1106 			bond_hw_addr_copy(tmp_mac, new_active->dev->dev_addr,
1107 					  new_active->dev->addr_len);
1108 			bond_hw_addr_copy(ss.__data,
1109 					  old_active->dev->dev_addr,
1110 					  old_active->dev->addr_len);
1111 			ss.ss_family = new_active->dev->type;
1112 		} else {
1113 			bond_hw_addr_copy(ss.__data, bond->dev->dev_addr,
1114 					  bond->dev->addr_len);
1115 			ss.ss_family = bond->dev->type;
1116 		}
1117 
1118 		rv = dev_set_mac_address(new_active->dev,
1119 					 (struct sockaddr *)&ss, NULL);
1120 		if (rv) {
1121 			slave_err(bond->dev, new_active->dev, "Error %d setting MAC of new active slave\n",
1122 				  -rv);
1123 			goto out;
1124 		}
1125 
1126 		if (!old_active)
1127 			goto out;
1128 
1129 		bond_hw_addr_copy(ss.__data, tmp_mac,
1130 				  new_active->dev->addr_len);
1131 		ss.ss_family = old_active->dev->type;
1132 
1133 		rv = dev_set_mac_address(old_active->dev,
1134 					 (struct sockaddr *)&ss, NULL);
1135 		if (rv)
1136 			slave_err(bond->dev, old_active->dev, "Error %d setting MAC of old active slave\n",
1137 				  -rv);
1138 out:
1139 		break;
1140 	default:
1141 		netdev_err(bond->dev, "bond_do_fail_over_mac impossible: bad policy %d\n",
1142 			   bond->params.fail_over_mac);
1143 		break;
1144 	}
1145 
1146 }
1147 
1148 /**
1149  * bond_choose_primary_or_current - select the primary or high priority slave
1150  * @bond: our bonding struct
1151  *
1152  * - Check if there is a primary link. If the primary link was set and is up,
1153  *   go on and do link reselection.
1154  *
1155  * - If primary link is not set or down, find the highest priority link.
1156  *   If the highest priority link is not current slave, set it as primary
1157  *   link and do link reselection.
1158  */
1159 static struct slave *bond_choose_primary_or_current(struct bonding *bond)
1160 {
1161 	struct slave *prim = rtnl_dereference(bond->primary_slave);
1162 	struct slave *curr = rtnl_dereference(bond->curr_active_slave);
1163 	struct slave *slave, *hprio = NULL;
1164 	struct list_head *iter;
1165 
1166 	if (!prim || prim->link != BOND_LINK_UP) {
1167 		bond_for_each_slave(bond, slave, iter) {
1168 			if (slave->link == BOND_LINK_UP) {
1169 				hprio = hprio ?: slave;
1170 				if (slave->prio > hprio->prio)
1171 					hprio = slave;
1172 			}
1173 		}
1174 
1175 		if (hprio && hprio != curr) {
1176 			prim = hprio;
1177 			goto link_reselect;
1178 		}
1179 
1180 		if (!curr || curr->link != BOND_LINK_UP)
1181 			return NULL;
1182 		return curr;
1183 	}
1184 
1185 	if (bond->force_primary) {
1186 		bond->force_primary = false;
1187 		return prim;
1188 	}
1189 
1190 link_reselect:
1191 	if (!curr || curr->link != BOND_LINK_UP)
1192 		return prim;
1193 
1194 	/* At this point, prim and curr are both up */
1195 	switch (bond->params.primary_reselect) {
1196 	case BOND_PRI_RESELECT_ALWAYS:
1197 		return prim;
1198 	case BOND_PRI_RESELECT_BETTER:
1199 		if (prim->speed < curr->speed)
1200 			return curr;
1201 		if (prim->speed == curr->speed && prim->duplex <= curr->duplex)
1202 			return curr;
1203 		return prim;
1204 	case BOND_PRI_RESELECT_FAILURE:
1205 		return curr;
1206 	default:
1207 		netdev_err(bond->dev, "impossible primary_reselect %d\n",
1208 			   bond->params.primary_reselect);
1209 		return curr;
1210 	}
1211 }
1212 
1213 /**
1214  * bond_find_best_slave - select the best available slave to be the active one
1215  * @bond: our bonding struct
1216  */
1217 static struct slave *bond_find_best_slave(struct bonding *bond)
1218 {
1219 	struct slave *slave, *bestslave = NULL;
1220 	struct list_head *iter;
1221 	int mintime = bond->params.updelay;
1222 
1223 	slave = bond_choose_primary_or_current(bond);
1224 	if (slave)
1225 		return slave;
1226 
1227 	bond_for_each_slave(bond, slave, iter) {
1228 		if (slave->link == BOND_LINK_UP)
1229 			return slave;
1230 		if (slave->link == BOND_LINK_BACK && bond_slave_is_up(slave) &&
1231 		    slave->delay < mintime) {
1232 			mintime = slave->delay;
1233 			bestslave = slave;
1234 		}
1235 	}
1236 
1237 	return bestslave;
1238 }
1239 
1240 /* must be called in RCU critical section or with RTNL held */
1241 static bool bond_should_notify_peers(struct bonding *bond)
1242 {
1243 	struct slave *slave = rcu_dereference_rtnl(bond->curr_active_slave);
1244 
1245 	if (!slave || !bond->send_peer_notif ||
1246 	    bond->send_peer_notif %
1247 	    max(1, bond->params.peer_notif_delay) != 0 ||
1248 	    !netif_carrier_ok(bond->dev) ||
1249 	    test_bit(__LINK_STATE_LINKWATCH_PENDING, &slave->dev->state))
1250 		return false;
1251 
1252 	netdev_dbg(bond->dev, "bond_should_notify_peers: slave %s\n",
1253 		   slave ? slave->dev->name : "NULL");
1254 
1255 	return true;
1256 }
1257 
1258 /**
1259  * bond_change_active_slave - change the active slave into the specified one
1260  * @bond: our bonding struct
1261  * @new_active: the new slave to make the active one
1262  *
1263  * Set the new slave to the bond's settings and unset them on the old
1264  * curr_active_slave.
1265  * Setting include flags, mc-list, promiscuity, allmulti, etc.
1266  *
1267  * If @new's link state is %BOND_LINK_BACK we'll set it to %BOND_LINK_UP,
1268  * because it is apparently the best available slave we have, even though its
1269  * updelay hasn't timed out yet.
1270  *
1271  * Caller must hold RTNL.
1272  */
1273 void bond_change_active_slave(struct bonding *bond, struct slave *new_active)
1274 {
1275 	struct slave *old_active;
1276 
1277 	ASSERT_RTNL();
1278 
1279 	old_active = rtnl_dereference(bond->curr_active_slave);
1280 
1281 	if (old_active == new_active)
1282 		return;
1283 
1284 #ifdef CONFIG_XFRM_OFFLOAD
1285 	bond_ipsec_del_sa_all(bond);
1286 #endif /* CONFIG_XFRM_OFFLOAD */
1287 
1288 	if (new_active) {
1289 		new_active->last_link_up = jiffies;
1290 
1291 		if (new_active->link == BOND_LINK_BACK) {
1292 			if (bond_uses_primary(bond)) {
1293 				slave_info(bond->dev, new_active->dev, "making interface the new active one %d ms earlier\n",
1294 					   (bond->params.updelay - new_active->delay) * bond->params.miimon);
1295 			}
1296 
1297 			new_active->delay = 0;
1298 			bond_set_slave_link_state(new_active, BOND_LINK_UP,
1299 						  BOND_SLAVE_NOTIFY_NOW);
1300 
1301 			if (BOND_MODE(bond) == BOND_MODE_8023AD)
1302 				bond_3ad_handle_link_change(new_active, BOND_LINK_UP);
1303 
1304 			if (bond_is_lb(bond))
1305 				bond_alb_handle_link_change(bond, new_active, BOND_LINK_UP);
1306 		} else {
1307 			if (bond_uses_primary(bond))
1308 				slave_info(bond->dev, new_active->dev, "making interface the new active one\n");
1309 		}
1310 	}
1311 
1312 	if (bond_uses_primary(bond))
1313 		bond_hw_addr_swap(bond, new_active, old_active);
1314 
1315 	if (bond_is_lb(bond)) {
1316 		bond_alb_handle_active_change(bond, new_active);
1317 		if (old_active)
1318 			bond_set_slave_inactive_flags(old_active,
1319 						      BOND_SLAVE_NOTIFY_NOW);
1320 		if (new_active)
1321 			bond_set_slave_active_flags(new_active,
1322 						    BOND_SLAVE_NOTIFY_NOW);
1323 	} else {
1324 		rcu_assign_pointer(bond->curr_active_slave, new_active);
1325 	}
1326 
1327 	if (BOND_MODE(bond) == BOND_MODE_ACTIVEBACKUP) {
1328 		if (old_active)
1329 			bond_set_slave_inactive_flags(old_active,
1330 						      BOND_SLAVE_NOTIFY_NOW);
1331 
1332 		if (new_active) {
1333 			bool should_notify_peers = false;
1334 
1335 			bond_set_slave_active_flags(new_active,
1336 						    BOND_SLAVE_NOTIFY_NOW);
1337 
1338 			if (bond->params.fail_over_mac)
1339 				bond_do_fail_over_mac(bond, new_active,
1340 						      old_active);
1341 
1342 			if (netif_running(bond->dev)) {
1343 				bond->send_peer_notif =
1344 					bond->params.num_peer_notif *
1345 					max(1, bond->params.peer_notif_delay);
1346 				should_notify_peers =
1347 					bond_should_notify_peers(bond);
1348 			}
1349 
1350 			call_netdevice_notifiers(NETDEV_BONDING_FAILOVER, bond->dev);
1351 			if (should_notify_peers) {
1352 				bond->send_peer_notif--;
1353 				call_netdevice_notifiers(NETDEV_NOTIFY_PEERS,
1354 							 bond->dev);
1355 			}
1356 		}
1357 	}
1358 
1359 #ifdef CONFIG_XFRM_OFFLOAD
1360 	bond_ipsec_add_sa_all(bond);
1361 #endif /* CONFIG_XFRM_OFFLOAD */
1362 
1363 	/* resend IGMP joins since active slave has changed or
1364 	 * all were sent on curr_active_slave.
1365 	 * resend only if bond is brought up with the affected
1366 	 * bonding modes and the retransmission is enabled
1367 	 */
1368 	if (netif_running(bond->dev) && (bond->params.resend_igmp > 0) &&
1369 	    ((bond_uses_primary(bond) && new_active) ||
1370 	     BOND_MODE(bond) == BOND_MODE_ROUNDROBIN)) {
1371 		bond->igmp_retrans = bond->params.resend_igmp;
1372 		queue_delayed_work(bond->wq, &bond->mcast_work, 1);
1373 	}
1374 }
1375 
1376 /**
1377  * bond_select_active_slave - select a new active slave, if needed
1378  * @bond: our bonding struct
1379  *
1380  * This functions should be called when one of the following occurs:
1381  * - The old curr_active_slave has been released or lost its link.
1382  * - The primary_slave has got its link back.
1383  * - A slave has got its link back and there's no old curr_active_slave.
1384  *
1385  * Caller must hold RTNL.
1386  */
1387 void bond_select_active_slave(struct bonding *bond)
1388 {
1389 	struct slave *best_slave;
1390 	int rv;
1391 
1392 	ASSERT_RTNL();
1393 
1394 	best_slave = bond_find_best_slave(bond);
1395 	if (best_slave != rtnl_dereference(bond->curr_active_slave)) {
1396 		bond_change_active_slave(bond, best_slave);
1397 		rv = bond_set_carrier(bond);
1398 		if (!rv)
1399 			return;
1400 
1401 		if (netif_carrier_ok(bond->dev))
1402 			netdev_info(bond->dev, "active interface up!\n");
1403 		else
1404 			netdev_info(bond->dev, "now running without any active interface!\n");
1405 	}
1406 }
1407 
1408 #ifdef CONFIG_NET_POLL_CONTROLLER
1409 static inline int slave_enable_netpoll(struct slave *slave)
1410 {
1411 	struct netpoll *np;
1412 	int err = 0;
1413 
1414 	np = kzalloc(sizeof(*np), GFP_KERNEL);
1415 	err = -ENOMEM;
1416 	if (!np)
1417 		goto out;
1418 
1419 	err = __netpoll_setup(np, slave->dev);
1420 	if (err) {
1421 		kfree(np);
1422 		goto out;
1423 	}
1424 	slave->np = np;
1425 out:
1426 	return err;
1427 }
1428 static inline void slave_disable_netpoll(struct slave *slave)
1429 {
1430 	struct netpoll *np = slave->np;
1431 
1432 	if (!np)
1433 		return;
1434 
1435 	slave->np = NULL;
1436 
1437 	__netpoll_free(np);
1438 }
1439 
1440 static void bond_poll_controller(struct net_device *bond_dev)
1441 {
1442 	struct bonding *bond = netdev_priv(bond_dev);
1443 	struct slave *slave = NULL;
1444 	struct list_head *iter;
1445 	struct ad_info ad_info;
1446 
1447 	if (BOND_MODE(bond) == BOND_MODE_8023AD)
1448 		if (bond_3ad_get_active_agg_info(bond, &ad_info))
1449 			return;
1450 
1451 	bond_for_each_slave_rcu(bond, slave, iter) {
1452 		if (!bond_slave_is_up(slave))
1453 			continue;
1454 
1455 		if (BOND_MODE(bond) == BOND_MODE_8023AD) {
1456 			struct aggregator *agg =
1457 			    SLAVE_AD_INFO(slave)->port.aggregator;
1458 
1459 			if (agg &&
1460 			    agg->aggregator_identifier != ad_info.aggregator_id)
1461 				continue;
1462 		}
1463 
1464 		netpoll_poll_dev(slave->dev);
1465 	}
1466 }
1467 
1468 static void bond_netpoll_cleanup(struct net_device *bond_dev)
1469 {
1470 	struct bonding *bond = netdev_priv(bond_dev);
1471 	struct list_head *iter;
1472 	struct slave *slave;
1473 
1474 	bond_for_each_slave(bond, slave, iter)
1475 		if (bond_slave_is_up(slave))
1476 			slave_disable_netpoll(slave);
1477 }
1478 
1479 static int bond_netpoll_setup(struct net_device *dev)
1480 {
1481 	struct bonding *bond = netdev_priv(dev);
1482 	struct list_head *iter;
1483 	struct slave *slave;
1484 	int err = 0;
1485 
1486 	bond_for_each_slave(bond, slave, iter) {
1487 		err = slave_enable_netpoll(slave);
1488 		if (err) {
1489 			bond_netpoll_cleanup(dev);
1490 			break;
1491 		}
1492 	}
1493 	return err;
1494 }
1495 #else
1496 static inline int slave_enable_netpoll(struct slave *slave)
1497 {
1498 	return 0;
1499 }
1500 static inline void slave_disable_netpoll(struct slave *slave)
1501 {
1502 }
1503 static void bond_netpoll_cleanup(struct net_device *bond_dev)
1504 {
1505 }
1506 #endif
1507 
1508 /*---------------------------------- IOCTL ----------------------------------*/
1509 
1510 static netdev_features_t bond_fix_features(struct net_device *dev,
1511 					   netdev_features_t features)
1512 {
1513 	struct bonding *bond = netdev_priv(dev);
1514 	struct list_head *iter;
1515 	netdev_features_t mask;
1516 	struct slave *slave;
1517 
1518 	mask = features;
1519 
1520 	features &= ~NETIF_F_ONE_FOR_ALL;
1521 	features |= NETIF_F_ALL_FOR_ALL;
1522 
1523 	bond_for_each_slave(bond, slave, iter) {
1524 		features = netdev_increment_features(features,
1525 						     slave->dev->features,
1526 						     mask);
1527 	}
1528 	features = netdev_add_tso_features(features, mask);
1529 
1530 	return features;
1531 }
1532 
1533 #define BOND_VLAN_FEATURES	(NETIF_F_HW_CSUM | NETIF_F_SG | \
1534 				 NETIF_F_FRAGLIST | NETIF_F_GSO_SOFTWARE | \
1535 				 NETIF_F_HIGHDMA | NETIF_F_LRO)
1536 
1537 #define BOND_ENC_FEATURES	(NETIF_F_HW_CSUM | NETIF_F_SG | \
1538 				 NETIF_F_RXCSUM | NETIF_F_GSO_SOFTWARE)
1539 
1540 #define BOND_MPLS_FEATURES	(NETIF_F_HW_CSUM | NETIF_F_SG | \
1541 				 NETIF_F_GSO_SOFTWARE)
1542 
1543 
1544 static void bond_compute_features(struct bonding *bond)
1545 {
1546 	unsigned int dst_release_flag = IFF_XMIT_DST_RELEASE |
1547 					IFF_XMIT_DST_RELEASE_PERM;
1548 	netdev_features_t gso_partial_features = NETIF_F_GSO_ESP;
1549 	netdev_features_t vlan_features = BOND_VLAN_FEATURES;
1550 	netdev_features_t enc_features  = BOND_ENC_FEATURES;
1551 #ifdef CONFIG_XFRM_OFFLOAD
1552 	netdev_features_t xfrm_features  = BOND_XFRM_FEATURES;
1553 #endif /* CONFIG_XFRM_OFFLOAD */
1554 	netdev_features_t mpls_features  = BOND_MPLS_FEATURES;
1555 	struct net_device *bond_dev = bond->dev;
1556 	struct list_head *iter;
1557 	struct slave *slave;
1558 	unsigned short max_hard_header_len = ETH_HLEN;
1559 	unsigned int tso_max_size = TSO_MAX_SIZE;
1560 	u16 tso_max_segs = TSO_MAX_SEGS;
1561 
1562 	if (!bond_has_slaves(bond))
1563 		goto done;
1564 	vlan_features &= NETIF_F_ALL_FOR_ALL;
1565 	mpls_features &= NETIF_F_ALL_FOR_ALL;
1566 
1567 	bond_for_each_slave(bond, slave, iter) {
1568 		vlan_features = netdev_increment_features(vlan_features,
1569 			slave->dev->vlan_features, BOND_VLAN_FEATURES);
1570 
1571 		enc_features = netdev_increment_features(enc_features,
1572 							 slave->dev->hw_enc_features,
1573 							 BOND_ENC_FEATURES);
1574 
1575 #ifdef CONFIG_XFRM_OFFLOAD
1576 		xfrm_features = netdev_increment_features(xfrm_features,
1577 							  slave->dev->hw_enc_features,
1578 							  BOND_XFRM_FEATURES);
1579 #endif /* CONFIG_XFRM_OFFLOAD */
1580 
1581 		if (slave->dev->hw_enc_features & NETIF_F_GSO_PARTIAL)
1582 			gso_partial_features &= slave->dev->gso_partial_features;
1583 
1584 		mpls_features = netdev_increment_features(mpls_features,
1585 							  slave->dev->mpls_features,
1586 							  BOND_MPLS_FEATURES);
1587 
1588 		dst_release_flag &= slave->dev->priv_flags;
1589 		if (slave->dev->hard_header_len > max_hard_header_len)
1590 			max_hard_header_len = slave->dev->hard_header_len;
1591 
1592 		tso_max_size = min(tso_max_size, slave->dev->tso_max_size);
1593 		tso_max_segs = min(tso_max_segs, slave->dev->tso_max_segs);
1594 	}
1595 	bond_dev->hard_header_len = max_hard_header_len;
1596 
1597 	if (gso_partial_features & NETIF_F_GSO_ESP)
1598 		bond_dev->gso_partial_features |= NETIF_F_GSO_ESP;
1599 	else
1600 		bond_dev->gso_partial_features &= ~NETIF_F_GSO_ESP;
1601 
1602 done:
1603 	bond_dev->vlan_features = vlan_features;
1604 	bond_dev->hw_enc_features = enc_features | NETIF_F_GSO_ENCAP_ALL |
1605 				    NETIF_F_HW_VLAN_CTAG_TX |
1606 				    NETIF_F_HW_VLAN_STAG_TX;
1607 #ifdef CONFIG_XFRM_OFFLOAD
1608 	bond_dev->hw_enc_features |= xfrm_features;
1609 #endif /* CONFIG_XFRM_OFFLOAD */
1610 	bond_dev->mpls_features = mpls_features;
1611 	netif_set_tso_max_segs(bond_dev, tso_max_segs);
1612 	netif_set_tso_max_size(bond_dev, tso_max_size);
1613 
1614 	bond_dev->priv_flags &= ~IFF_XMIT_DST_RELEASE;
1615 	if ((bond_dev->priv_flags & IFF_XMIT_DST_RELEASE_PERM) &&
1616 	    dst_release_flag == (IFF_XMIT_DST_RELEASE | IFF_XMIT_DST_RELEASE_PERM))
1617 		bond_dev->priv_flags |= IFF_XMIT_DST_RELEASE;
1618 
1619 	netdev_change_features(bond_dev);
1620 }
1621 
1622 static void bond_setup_by_slave(struct net_device *bond_dev,
1623 				struct net_device *slave_dev)
1624 {
1625 	bool was_up = !!(bond_dev->flags & IFF_UP);
1626 
1627 	dev_close(bond_dev);
1628 
1629 	bond_dev->header_ops	    = slave_dev->header_ops;
1630 
1631 	bond_dev->type		    = slave_dev->type;
1632 	bond_dev->hard_header_len   = slave_dev->hard_header_len;
1633 	bond_dev->needed_headroom   = slave_dev->needed_headroom;
1634 	bond_dev->addr_len	    = slave_dev->addr_len;
1635 
1636 	memcpy(bond_dev->broadcast, slave_dev->broadcast,
1637 		slave_dev->addr_len);
1638 
1639 	if (slave_dev->flags & IFF_POINTOPOINT) {
1640 		bond_dev->flags &= ~(IFF_BROADCAST | IFF_MULTICAST);
1641 		bond_dev->flags |= (IFF_POINTOPOINT | IFF_NOARP);
1642 	}
1643 	if (was_up)
1644 		dev_open(bond_dev, NULL);
1645 }
1646 
1647 /* On bonding slaves other than the currently active slave, suppress
1648  * duplicates except for alb non-mcast/bcast.
1649  */
1650 static bool bond_should_deliver_exact_match(struct sk_buff *skb,
1651 					    struct slave *slave,
1652 					    struct bonding *bond)
1653 {
1654 	if (bond_is_slave_inactive(slave)) {
1655 		if (BOND_MODE(bond) == BOND_MODE_ALB &&
1656 		    skb->pkt_type != PACKET_BROADCAST &&
1657 		    skb->pkt_type != PACKET_MULTICAST)
1658 			return false;
1659 		return true;
1660 	}
1661 	return false;
1662 }
1663 
1664 static rx_handler_result_t bond_handle_frame(struct sk_buff **pskb)
1665 {
1666 	struct sk_buff *skb = *pskb;
1667 	struct slave *slave;
1668 	struct bonding *bond;
1669 	int (*recv_probe)(const struct sk_buff *, struct bonding *,
1670 			  struct slave *);
1671 	int ret = RX_HANDLER_ANOTHER;
1672 
1673 	skb = skb_share_check(skb, GFP_ATOMIC);
1674 	if (unlikely(!skb))
1675 		return RX_HANDLER_CONSUMED;
1676 
1677 	*pskb = skb;
1678 
1679 	slave = bond_slave_get_rcu(skb->dev);
1680 	bond = slave->bond;
1681 
1682 	recv_probe = READ_ONCE(bond->recv_probe);
1683 	if (recv_probe) {
1684 		ret = recv_probe(skb, bond, slave);
1685 		if (ret == RX_HANDLER_CONSUMED) {
1686 			consume_skb(skb);
1687 			return ret;
1688 		}
1689 	}
1690 
1691 	/*
1692 	 * For packets determined by bond_should_deliver_exact_match() call to
1693 	 * be suppressed we want to make an exception for link-local packets.
1694 	 * This is necessary for e.g. LLDP daemons to be able to monitor
1695 	 * inactive slave links without being forced to bind to them
1696 	 * explicitly.
1697 	 *
1698 	 * At the same time, packets that are passed to the bonding master
1699 	 * (including link-local ones) can have their originating interface
1700 	 * determined via PACKET_ORIGDEV socket option.
1701 	 */
1702 	if (bond_should_deliver_exact_match(skb, slave, bond)) {
1703 		if (is_link_local_ether_addr(eth_hdr(skb)->h_dest))
1704 			return RX_HANDLER_PASS;
1705 		return RX_HANDLER_EXACT;
1706 	}
1707 
1708 	skb->dev = bond->dev;
1709 
1710 	if (BOND_MODE(bond) == BOND_MODE_ALB &&
1711 	    netif_is_bridge_port(bond->dev) &&
1712 	    skb->pkt_type == PACKET_HOST) {
1713 
1714 		if (unlikely(skb_cow_head(skb,
1715 					  skb->data - skb_mac_header(skb)))) {
1716 			kfree_skb(skb);
1717 			return RX_HANDLER_CONSUMED;
1718 		}
1719 		bond_hw_addr_copy(eth_hdr(skb)->h_dest, bond->dev->dev_addr,
1720 				  bond->dev->addr_len);
1721 	}
1722 
1723 	return ret;
1724 }
1725 
1726 static enum netdev_lag_tx_type bond_lag_tx_type(struct bonding *bond)
1727 {
1728 	switch (BOND_MODE(bond)) {
1729 	case BOND_MODE_ROUNDROBIN:
1730 		return NETDEV_LAG_TX_TYPE_ROUNDROBIN;
1731 	case BOND_MODE_ACTIVEBACKUP:
1732 		return NETDEV_LAG_TX_TYPE_ACTIVEBACKUP;
1733 	case BOND_MODE_BROADCAST:
1734 		return NETDEV_LAG_TX_TYPE_BROADCAST;
1735 	case BOND_MODE_XOR:
1736 	case BOND_MODE_8023AD:
1737 		return NETDEV_LAG_TX_TYPE_HASH;
1738 	default:
1739 		return NETDEV_LAG_TX_TYPE_UNKNOWN;
1740 	}
1741 }
1742 
1743 static enum netdev_lag_hash bond_lag_hash_type(struct bonding *bond,
1744 					       enum netdev_lag_tx_type type)
1745 {
1746 	if (type != NETDEV_LAG_TX_TYPE_HASH)
1747 		return NETDEV_LAG_HASH_NONE;
1748 
1749 	switch (bond->params.xmit_policy) {
1750 	case BOND_XMIT_POLICY_LAYER2:
1751 		return NETDEV_LAG_HASH_L2;
1752 	case BOND_XMIT_POLICY_LAYER34:
1753 		return NETDEV_LAG_HASH_L34;
1754 	case BOND_XMIT_POLICY_LAYER23:
1755 		return NETDEV_LAG_HASH_L23;
1756 	case BOND_XMIT_POLICY_ENCAP23:
1757 		return NETDEV_LAG_HASH_E23;
1758 	case BOND_XMIT_POLICY_ENCAP34:
1759 		return NETDEV_LAG_HASH_E34;
1760 	case BOND_XMIT_POLICY_VLAN_SRCMAC:
1761 		return NETDEV_LAG_HASH_VLAN_SRCMAC;
1762 	default:
1763 		return NETDEV_LAG_HASH_UNKNOWN;
1764 	}
1765 }
1766 
1767 static int bond_master_upper_dev_link(struct bonding *bond, struct slave *slave,
1768 				      struct netlink_ext_ack *extack)
1769 {
1770 	struct netdev_lag_upper_info lag_upper_info;
1771 	enum netdev_lag_tx_type type;
1772 	int err;
1773 
1774 	type = bond_lag_tx_type(bond);
1775 	lag_upper_info.tx_type = type;
1776 	lag_upper_info.hash_type = bond_lag_hash_type(bond, type);
1777 
1778 	err = netdev_master_upper_dev_link(slave->dev, bond->dev, slave,
1779 					   &lag_upper_info, extack);
1780 	if (err)
1781 		return err;
1782 
1783 	slave->dev->flags |= IFF_SLAVE;
1784 	return 0;
1785 }
1786 
1787 static void bond_upper_dev_unlink(struct bonding *bond, struct slave *slave)
1788 {
1789 	netdev_upper_dev_unlink(slave->dev, bond->dev);
1790 	slave->dev->flags &= ~IFF_SLAVE;
1791 }
1792 
1793 static void slave_kobj_release(struct kobject *kobj)
1794 {
1795 	struct slave *slave = to_slave(kobj);
1796 	struct bonding *bond = bond_get_bond_by_slave(slave);
1797 
1798 	cancel_delayed_work_sync(&slave->notify_work);
1799 	if (BOND_MODE(bond) == BOND_MODE_8023AD)
1800 		kfree(SLAVE_AD_INFO(slave));
1801 
1802 	kfree(slave);
1803 }
1804 
1805 static struct kobj_type slave_ktype = {
1806 	.release = slave_kobj_release,
1807 #ifdef CONFIG_SYSFS
1808 	.sysfs_ops = &slave_sysfs_ops,
1809 #endif
1810 };
1811 
1812 static int bond_kobj_init(struct slave *slave)
1813 {
1814 	int err;
1815 
1816 	err = kobject_init_and_add(&slave->kobj, &slave_ktype,
1817 				   &(slave->dev->dev.kobj), "bonding_slave");
1818 	if (err)
1819 		kobject_put(&slave->kobj);
1820 
1821 	return err;
1822 }
1823 
1824 static struct slave *bond_alloc_slave(struct bonding *bond,
1825 				      struct net_device *slave_dev)
1826 {
1827 	struct slave *slave = NULL;
1828 
1829 	slave = kzalloc(sizeof(*slave), GFP_KERNEL);
1830 	if (!slave)
1831 		return NULL;
1832 
1833 	slave->bond = bond;
1834 	slave->dev = slave_dev;
1835 	INIT_DELAYED_WORK(&slave->notify_work, bond_netdev_notify_work);
1836 
1837 	if (bond_kobj_init(slave))
1838 		return NULL;
1839 
1840 	if (BOND_MODE(bond) == BOND_MODE_8023AD) {
1841 		SLAVE_AD_INFO(slave) = kzalloc(sizeof(struct ad_slave_info),
1842 					       GFP_KERNEL);
1843 		if (!SLAVE_AD_INFO(slave)) {
1844 			kobject_put(&slave->kobj);
1845 			return NULL;
1846 		}
1847 	}
1848 
1849 	return slave;
1850 }
1851 
1852 static void bond_fill_ifbond(struct bonding *bond, struct ifbond *info)
1853 {
1854 	info->bond_mode = BOND_MODE(bond);
1855 	info->miimon = bond->params.miimon;
1856 	info->num_slaves = bond->slave_cnt;
1857 }
1858 
1859 static void bond_fill_ifslave(struct slave *slave, struct ifslave *info)
1860 {
1861 	strcpy(info->slave_name, slave->dev->name);
1862 	info->link = slave->link;
1863 	info->state = bond_slave_state(slave);
1864 	info->link_failure_count = slave->link_failure_count;
1865 }
1866 
1867 static void bond_netdev_notify_work(struct work_struct *_work)
1868 {
1869 	struct slave *slave = container_of(_work, struct slave,
1870 					   notify_work.work);
1871 
1872 	if (rtnl_trylock()) {
1873 		struct netdev_bonding_info binfo;
1874 
1875 		bond_fill_ifslave(slave, &binfo.slave);
1876 		bond_fill_ifbond(slave->bond, &binfo.master);
1877 		netdev_bonding_info_change(slave->dev, &binfo);
1878 		rtnl_unlock();
1879 	} else {
1880 		queue_delayed_work(slave->bond->wq, &slave->notify_work, 1);
1881 	}
1882 }
1883 
1884 void bond_queue_slave_event(struct slave *slave)
1885 {
1886 	queue_delayed_work(slave->bond->wq, &slave->notify_work, 0);
1887 }
1888 
1889 void bond_lower_state_changed(struct slave *slave)
1890 {
1891 	struct netdev_lag_lower_state_info info;
1892 
1893 	info.link_up = slave->link == BOND_LINK_UP ||
1894 		       slave->link == BOND_LINK_FAIL;
1895 	info.tx_enabled = bond_is_active_slave(slave);
1896 	netdev_lower_state_changed(slave->dev, &info);
1897 }
1898 
1899 #define BOND_NL_ERR(bond_dev, extack, errmsg) do {		\
1900 	if (extack)						\
1901 		NL_SET_ERR_MSG(extack, errmsg);			\
1902 	else							\
1903 		netdev_err(bond_dev, "Error: %s\n", errmsg);	\
1904 } while (0)
1905 
1906 #define SLAVE_NL_ERR(bond_dev, slave_dev, extack, errmsg) do {		\
1907 	if (extack)							\
1908 		NL_SET_ERR_MSG(extack, errmsg);				\
1909 	else								\
1910 		slave_err(bond_dev, slave_dev, "Error: %s\n", errmsg);	\
1911 } while (0)
1912 
1913 /* The bonding driver uses ether_setup() to convert a master bond device
1914  * to ARPHRD_ETHER, that resets the target netdevice's flags so we always
1915  * have to restore the IFF_MASTER flag, and only restore IFF_SLAVE and IFF_UP
1916  * if they were set
1917  */
1918 static void bond_ether_setup(struct net_device *bond_dev)
1919 {
1920 	unsigned int flags = bond_dev->flags & (IFF_SLAVE | IFF_UP);
1921 
1922 	ether_setup(bond_dev);
1923 	bond_dev->flags |= IFF_MASTER | flags;
1924 	bond_dev->priv_flags &= ~IFF_TX_SKB_SHARING;
1925 }
1926 
1927 void bond_xdp_set_features(struct net_device *bond_dev)
1928 {
1929 	struct bonding *bond = netdev_priv(bond_dev);
1930 	xdp_features_t val = NETDEV_XDP_ACT_MASK;
1931 	struct list_head *iter;
1932 	struct slave *slave;
1933 
1934 	ASSERT_RTNL();
1935 
1936 	if (!bond_xdp_check(bond) || !bond_has_slaves(bond)) {
1937 		xdp_clear_features_flag(bond_dev);
1938 		return;
1939 	}
1940 
1941 	bond_for_each_slave(bond, slave, iter)
1942 		val &= slave->dev->xdp_features;
1943 
1944 	val &= ~NETDEV_XDP_ACT_XSK_ZEROCOPY;
1945 
1946 	xdp_set_features_flag(bond_dev, val);
1947 }
1948 
1949 /* enslave device <slave> to bond device <master> */
1950 int bond_enslave(struct net_device *bond_dev, struct net_device *slave_dev,
1951 		 struct netlink_ext_ack *extack)
1952 {
1953 	struct bonding *bond = netdev_priv(bond_dev);
1954 	const struct net_device_ops *slave_ops = slave_dev->netdev_ops;
1955 	struct slave *new_slave = NULL, *prev_slave;
1956 	struct sockaddr_storage ss;
1957 	int link_reporting;
1958 	int res = 0, i;
1959 
1960 	if (slave_dev->flags & IFF_MASTER &&
1961 	    !netif_is_bond_master(slave_dev)) {
1962 		BOND_NL_ERR(bond_dev, extack,
1963 			    "Device type (master device) cannot be enslaved");
1964 		return -EPERM;
1965 	}
1966 
1967 	if (!bond->params.use_carrier &&
1968 	    slave_dev->ethtool_ops->get_link == NULL &&
1969 	    slave_ops->ndo_eth_ioctl == NULL) {
1970 		slave_warn(bond_dev, slave_dev, "no link monitoring support\n");
1971 	}
1972 
1973 	/* already in-use? */
1974 	if (netdev_is_rx_handler_busy(slave_dev)) {
1975 		SLAVE_NL_ERR(bond_dev, slave_dev, extack,
1976 			     "Device is in use and cannot be enslaved");
1977 		return -EBUSY;
1978 	}
1979 
1980 	if (bond_dev == slave_dev) {
1981 		BOND_NL_ERR(bond_dev, extack, "Cannot enslave bond to itself.");
1982 		return -EPERM;
1983 	}
1984 
1985 	/* vlan challenged mutual exclusion */
1986 	/* no need to lock since we're protected by rtnl_lock */
1987 	if (slave_dev->features & NETIF_F_VLAN_CHALLENGED) {
1988 		slave_dbg(bond_dev, slave_dev, "is NETIF_F_VLAN_CHALLENGED\n");
1989 		if (vlan_uses_dev(bond_dev)) {
1990 			SLAVE_NL_ERR(bond_dev, slave_dev, extack,
1991 				     "Can not enslave VLAN challenged device to VLAN enabled bond");
1992 			return -EPERM;
1993 		} else {
1994 			slave_warn(bond_dev, slave_dev, "enslaved VLAN challenged slave. Adding VLANs will be blocked as long as it is part of bond.\n");
1995 		}
1996 	} else {
1997 		slave_dbg(bond_dev, slave_dev, "is !NETIF_F_VLAN_CHALLENGED\n");
1998 	}
1999 
2000 	if (slave_dev->features & NETIF_F_HW_ESP)
2001 		slave_dbg(bond_dev, slave_dev, "is esp-hw-offload capable\n");
2002 
2003 	/* Old ifenslave binaries are no longer supported.  These can
2004 	 * be identified with moderate accuracy by the state of the slave:
2005 	 * the current ifenslave will set the interface down prior to
2006 	 * enslaving it; the old ifenslave will not.
2007 	 */
2008 	if (slave_dev->flags & IFF_UP) {
2009 		SLAVE_NL_ERR(bond_dev, slave_dev, extack,
2010 			     "Device can not be enslaved while up");
2011 		return -EPERM;
2012 	}
2013 
2014 	/* set bonding device ether type by slave - bonding netdevices are
2015 	 * created with ether_setup, so when the slave type is not ARPHRD_ETHER
2016 	 * there is a need to override some of the type dependent attribs/funcs.
2017 	 *
2018 	 * bond ether type mutual exclusion - don't allow slaves of dissimilar
2019 	 * ether type (eg ARPHRD_ETHER and ARPHRD_INFINIBAND) share the same bond
2020 	 */
2021 	if (!bond_has_slaves(bond)) {
2022 		if (bond_dev->type != slave_dev->type) {
2023 			slave_dbg(bond_dev, slave_dev, "change device type from %d to %d\n",
2024 				  bond_dev->type, slave_dev->type);
2025 
2026 			res = call_netdevice_notifiers(NETDEV_PRE_TYPE_CHANGE,
2027 						       bond_dev);
2028 			res = notifier_to_errno(res);
2029 			if (res) {
2030 				slave_err(bond_dev, slave_dev, "refused to change device type\n");
2031 				return -EBUSY;
2032 			}
2033 
2034 			/* Flush unicast and multicast addresses */
2035 			dev_uc_flush(bond_dev);
2036 			dev_mc_flush(bond_dev);
2037 
2038 			if (slave_dev->type != ARPHRD_ETHER)
2039 				bond_setup_by_slave(bond_dev, slave_dev);
2040 			else
2041 				bond_ether_setup(bond_dev);
2042 
2043 			call_netdevice_notifiers(NETDEV_POST_TYPE_CHANGE,
2044 						 bond_dev);
2045 		}
2046 	} else if (bond_dev->type != slave_dev->type) {
2047 		SLAVE_NL_ERR(bond_dev, slave_dev, extack,
2048 			     "Device type is different from other slaves");
2049 		return -EINVAL;
2050 	}
2051 
2052 	if (slave_dev->type == ARPHRD_INFINIBAND &&
2053 	    BOND_MODE(bond) != BOND_MODE_ACTIVEBACKUP) {
2054 		SLAVE_NL_ERR(bond_dev, slave_dev, extack,
2055 			     "Only active-backup mode is supported for infiniband slaves");
2056 		res = -EOPNOTSUPP;
2057 		goto err_undo_flags;
2058 	}
2059 
2060 	if (!slave_ops->ndo_set_mac_address ||
2061 	    slave_dev->type == ARPHRD_INFINIBAND) {
2062 		slave_warn(bond_dev, slave_dev, "The slave device specified does not support setting the MAC address\n");
2063 		if (BOND_MODE(bond) == BOND_MODE_ACTIVEBACKUP &&
2064 		    bond->params.fail_over_mac != BOND_FOM_ACTIVE) {
2065 			if (!bond_has_slaves(bond)) {
2066 				bond->params.fail_over_mac = BOND_FOM_ACTIVE;
2067 				slave_warn(bond_dev, slave_dev, "Setting fail_over_mac to active for active-backup mode\n");
2068 			} else {
2069 				SLAVE_NL_ERR(bond_dev, slave_dev, extack,
2070 					     "Slave device does not support setting the MAC address, but fail_over_mac is not set to active");
2071 				res = -EOPNOTSUPP;
2072 				goto err_undo_flags;
2073 			}
2074 		}
2075 	}
2076 
2077 	call_netdevice_notifiers(NETDEV_JOIN, slave_dev);
2078 
2079 	/* If this is the first slave, then we need to set the master's hardware
2080 	 * address to be the same as the slave's.
2081 	 */
2082 	if (!bond_has_slaves(bond) &&
2083 	    bond->dev->addr_assign_type == NET_ADDR_RANDOM) {
2084 		res = bond_set_dev_addr(bond->dev, slave_dev);
2085 		if (res)
2086 			goto err_undo_flags;
2087 	}
2088 
2089 	new_slave = bond_alloc_slave(bond, slave_dev);
2090 	if (!new_slave) {
2091 		res = -ENOMEM;
2092 		goto err_undo_flags;
2093 	}
2094 
2095 	/* Set the new_slave's queue_id to be zero.  Queue ID mapping
2096 	 * is set via sysfs or module option if desired.
2097 	 */
2098 	new_slave->queue_id = 0;
2099 
2100 	/* Save slave's original mtu and then set it to match the bond */
2101 	new_slave->original_mtu = slave_dev->mtu;
2102 	res = dev_set_mtu(slave_dev, bond->dev->mtu);
2103 	if (res) {
2104 		slave_err(bond_dev, slave_dev, "Error %d calling dev_set_mtu\n", res);
2105 		goto err_free;
2106 	}
2107 
2108 	/* Save slave's original ("permanent") mac address for modes
2109 	 * that need it, and for restoring it upon release, and then
2110 	 * set it to the master's address
2111 	 */
2112 	bond_hw_addr_copy(new_slave->perm_hwaddr, slave_dev->dev_addr,
2113 			  slave_dev->addr_len);
2114 
2115 	if (!bond->params.fail_over_mac ||
2116 	    BOND_MODE(bond) != BOND_MODE_ACTIVEBACKUP) {
2117 		/* Set slave to master's mac address.  The application already
2118 		 * set the master's mac address to that of the first slave
2119 		 */
2120 		memcpy(ss.__data, bond_dev->dev_addr, bond_dev->addr_len);
2121 		ss.ss_family = slave_dev->type;
2122 		res = dev_set_mac_address(slave_dev, (struct sockaddr *)&ss,
2123 					  extack);
2124 		if (res) {
2125 			slave_err(bond_dev, slave_dev, "Error %d calling set_mac_address\n", res);
2126 			goto err_restore_mtu;
2127 		}
2128 	}
2129 
2130 	/* set no_addrconf flag before open to prevent IPv6 addrconf */
2131 	slave_dev->priv_flags |= IFF_NO_ADDRCONF;
2132 
2133 	/* open the slave since the application closed it */
2134 	res = dev_open(slave_dev, extack);
2135 	if (res) {
2136 		slave_err(bond_dev, slave_dev, "Opening slave failed\n");
2137 		goto err_restore_mac;
2138 	}
2139 
2140 	slave_dev->priv_flags |= IFF_BONDING;
2141 	/* initialize slave stats */
2142 	dev_get_stats(new_slave->dev, &new_slave->slave_stats);
2143 
2144 	if (bond_is_lb(bond)) {
2145 		/* bond_alb_init_slave() must be called before all other stages since
2146 		 * it might fail and we do not want to have to undo everything
2147 		 */
2148 		res = bond_alb_init_slave(bond, new_slave);
2149 		if (res)
2150 			goto err_close;
2151 	}
2152 
2153 	res = vlan_vids_add_by_dev(slave_dev, bond_dev);
2154 	if (res) {
2155 		slave_err(bond_dev, slave_dev, "Couldn't add bond vlan ids\n");
2156 		goto err_close;
2157 	}
2158 
2159 	prev_slave = bond_last_slave(bond);
2160 
2161 	new_slave->delay = 0;
2162 	new_slave->link_failure_count = 0;
2163 
2164 	if (bond_update_speed_duplex(new_slave) &&
2165 	    bond_needs_speed_duplex(bond))
2166 		new_slave->link = BOND_LINK_DOWN;
2167 
2168 	new_slave->last_rx = jiffies -
2169 		(msecs_to_jiffies(bond->params.arp_interval) + 1);
2170 	for (i = 0; i < BOND_MAX_ARP_TARGETS; i++)
2171 		new_slave->target_last_arp_rx[i] = new_slave->last_rx;
2172 
2173 	new_slave->last_tx = new_slave->last_rx;
2174 
2175 	if (bond->params.miimon && !bond->params.use_carrier) {
2176 		link_reporting = bond_check_dev_link(bond, slave_dev, 1);
2177 
2178 		if ((link_reporting == -1) && !bond->params.arp_interval) {
2179 			/* miimon is set but a bonded network driver
2180 			 * does not support ETHTOOL/MII and
2181 			 * arp_interval is not set.  Note: if
2182 			 * use_carrier is enabled, we will never go
2183 			 * here (because netif_carrier is always
2184 			 * supported); thus, we don't need to change
2185 			 * the messages for netif_carrier.
2186 			 */
2187 			slave_warn(bond_dev, slave_dev, "MII and ETHTOOL support not available for slave, and arp_interval/arp_ip_target module parameters not specified, thus bonding will not detect link failures! see bonding.txt for details\n");
2188 		} else if (link_reporting == -1) {
2189 			/* unable get link status using mii/ethtool */
2190 			slave_warn(bond_dev, slave_dev, "can't get link status from slave; the network driver associated with this interface does not support MII or ETHTOOL link status reporting, thus miimon has no effect on this interface\n");
2191 		}
2192 	}
2193 
2194 	/* check for initial state */
2195 	new_slave->link = BOND_LINK_NOCHANGE;
2196 	if (bond->params.miimon) {
2197 		if (bond_check_dev_link(bond, slave_dev, 0) == BMSR_LSTATUS) {
2198 			if (bond->params.updelay) {
2199 				bond_set_slave_link_state(new_slave,
2200 							  BOND_LINK_BACK,
2201 							  BOND_SLAVE_NOTIFY_NOW);
2202 				new_slave->delay = bond->params.updelay;
2203 			} else {
2204 				bond_set_slave_link_state(new_slave,
2205 							  BOND_LINK_UP,
2206 							  BOND_SLAVE_NOTIFY_NOW);
2207 			}
2208 		} else {
2209 			bond_set_slave_link_state(new_slave, BOND_LINK_DOWN,
2210 						  BOND_SLAVE_NOTIFY_NOW);
2211 		}
2212 	} else if (bond->params.arp_interval) {
2213 		bond_set_slave_link_state(new_slave,
2214 					  (netif_carrier_ok(slave_dev) ?
2215 					  BOND_LINK_UP : BOND_LINK_DOWN),
2216 					  BOND_SLAVE_NOTIFY_NOW);
2217 	} else {
2218 		bond_set_slave_link_state(new_slave, BOND_LINK_UP,
2219 					  BOND_SLAVE_NOTIFY_NOW);
2220 	}
2221 
2222 	if (new_slave->link != BOND_LINK_DOWN)
2223 		new_slave->last_link_up = jiffies;
2224 	slave_dbg(bond_dev, slave_dev, "Initial state of slave is BOND_LINK_%s\n",
2225 		  new_slave->link == BOND_LINK_DOWN ? "DOWN" :
2226 		  (new_slave->link == BOND_LINK_UP ? "UP" : "BACK"));
2227 
2228 	if (bond_uses_primary(bond) && bond->params.primary[0]) {
2229 		/* if there is a primary slave, remember it */
2230 		if (strcmp(bond->params.primary, new_slave->dev->name) == 0) {
2231 			rcu_assign_pointer(bond->primary_slave, new_slave);
2232 			bond->force_primary = true;
2233 		}
2234 	}
2235 
2236 	switch (BOND_MODE(bond)) {
2237 	case BOND_MODE_ACTIVEBACKUP:
2238 		bond_set_slave_inactive_flags(new_slave,
2239 					      BOND_SLAVE_NOTIFY_NOW);
2240 		break;
2241 	case BOND_MODE_8023AD:
2242 		/* in 802.3ad mode, the internal mechanism
2243 		 * will activate the slaves in the selected
2244 		 * aggregator
2245 		 */
2246 		bond_set_slave_inactive_flags(new_slave, BOND_SLAVE_NOTIFY_NOW);
2247 		/* if this is the first slave */
2248 		if (!prev_slave) {
2249 			SLAVE_AD_INFO(new_slave)->id = 1;
2250 			/* Initialize AD with the number of times that the AD timer is called in 1 second
2251 			 * can be called only after the mac address of the bond is set
2252 			 */
2253 			bond_3ad_initialize(bond);
2254 		} else {
2255 			SLAVE_AD_INFO(new_slave)->id =
2256 				SLAVE_AD_INFO(prev_slave)->id + 1;
2257 		}
2258 
2259 		bond_3ad_bind_slave(new_slave);
2260 		break;
2261 	case BOND_MODE_TLB:
2262 	case BOND_MODE_ALB:
2263 		bond_set_active_slave(new_slave);
2264 		bond_set_slave_inactive_flags(new_slave, BOND_SLAVE_NOTIFY_NOW);
2265 		break;
2266 	default:
2267 		slave_dbg(bond_dev, slave_dev, "This slave is always active in trunk mode\n");
2268 
2269 		/* always active in trunk mode */
2270 		bond_set_active_slave(new_slave);
2271 
2272 		/* In trunking mode there is little meaning to curr_active_slave
2273 		 * anyway (it holds no special properties of the bond device),
2274 		 * so we can change it without calling change_active_interface()
2275 		 */
2276 		if (!rcu_access_pointer(bond->curr_active_slave) &&
2277 		    new_slave->link == BOND_LINK_UP)
2278 			rcu_assign_pointer(bond->curr_active_slave, new_slave);
2279 
2280 		break;
2281 	} /* switch(bond_mode) */
2282 
2283 #ifdef CONFIG_NET_POLL_CONTROLLER
2284 	if (bond->dev->npinfo) {
2285 		if (slave_enable_netpoll(new_slave)) {
2286 			slave_info(bond_dev, slave_dev, "master_dev is using netpoll, but new slave device does not support netpoll\n");
2287 			res = -EBUSY;
2288 			goto err_detach;
2289 		}
2290 	}
2291 #endif
2292 
2293 	if (!(bond_dev->features & NETIF_F_LRO))
2294 		dev_disable_lro(slave_dev);
2295 
2296 	res = netdev_rx_handler_register(slave_dev, bond_handle_frame,
2297 					 new_slave);
2298 	if (res) {
2299 		slave_dbg(bond_dev, slave_dev, "Error %d calling netdev_rx_handler_register\n", res);
2300 		goto err_detach;
2301 	}
2302 
2303 	res = bond_master_upper_dev_link(bond, new_slave, extack);
2304 	if (res) {
2305 		slave_dbg(bond_dev, slave_dev, "Error %d calling bond_master_upper_dev_link\n", res);
2306 		goto err_unregister;
2307 	}
2308 
2309 	bond_lower_state_changed(new_slave);
2310 
2311 	res = bond_sysfs_slave_add(new_slave);
2312 	if (res) {
2313 		slave_dbg(bond_dev, slave_dev, "Error %d calling bond_sysfs_slave_add\n", res);
2314 		goto err_upper_unlink;
2315 	}
2316 
2317 	/* If the mode uses primary, then the following is handled by
2318 	 * bond_change_active_slave().
2319 	 */
2320 	if (!bond_uses_primary(bond)) {
2321 		/* set promiscuity level to new slave */
2322 		if (bond_dev->flags & IFF_PROMISC) {
2323 			res = dev_set_promiscuity(slave_dev, 1);
2324 			if (res)
2325 				goto err_sysfs_del;
2326 		}
2327 
2328 		/* set allmulti level to new slave */
2329 		if (bond_dev->flags & IFF_ALLMULTI) {
2330 			res = dev_set_allmulti(slave_dev, 1);
2331 			if (res) {
2332 				if (bond_dev->flags & IFF_PROMISC)
2333 					dev_set_promiscuity(slave_dev, -1);
2334 				goto err_sysfs_del;
2335 			}
2336 		}
2337 
2338 		if (bond_dev->flags & IFF_UP) {
2339 			netif_addr_lock_bh(bond_dev);
2340 			dev_mc_sync_multiple(slave_dev, bond_dev);
2341 			dev_uc_sync_multiple(slave_dev, bond_dev);
2342 			netif_addr_unlock_bh(bond_dev);
2343 
2344 			if (BOND_MODE(bond) == BOND_MODE_8023AD)
2345 				dev_mc_add(slave_dev, lacpdu_mcast_addr);
2346 		}
2347 	}
2348 
2349 	bond->slave_cnt++;
2350 	bond_compute_features(bond);
2351 	bond_set_carrier(bond);
2352 
2353 	if (bond_uses_primary(bond)) {
2354 		block_netpoll_tx();
2355 		bond_select_active_slave(bond);
2356 		unblock_netpoll_tx();
2357 	}
2358 
2359 	if (bond_mode_can_use_xmit_hash(bond))
2360 		bond_update_slave_arr(bond, NULL);
2361 
2362 
2363 	if (!slave_dev->netdev_ops->ndo_bpf ||
2364 	    !slave_dev->netdev_ops->ndo_xdp_xmit) {
2365 		if (bond->xdp_prog) {
2366 			SLAVE_NL_ERR(bond_dev, slave_dev, extack,
2367 				     "Slave does not support XDP");
2368 			res = -EOPNOTSUPP;
2369 			goto err_sysfs_del;
2370 		}
2371 	} else if (bond->xdp_prog) {
2372 		struct netdev_bpf xdp = {
2373 			.command = XDP_SETUP_PROG,
2374 			.flags   = 0,
2375 			.prog    = bond->xdp_prog,
2376 			.extack  = extack,
2377 		};
2378 
2379 		if (dev_xdp_prog_count(slave_dev) > 0) {
2380 			SLAVE_NL_ERR(bond_dev, slave_dev, extack,
2381 				     "Slave has XDP program loaded, please unload before enslaving");
2382 			res = -EOPNOTSUPP;
2383 			goto err_sysfs_del;
2384 		}
2385 
2386 		res = dev_xdp_propagate(slave_dev, &xdp);
2387 		if (res < 0) {
2388 			/* ndo_bpf() sets extack error message */
2389 			slave_dbg(bond_dev, slave_dev, "Error %d calling ndo_bpf\n", res);
2390 			goto err_sysfs_del;
2391 		}
2392 		if (bond->xdp_prog)
2393 			bpf_prog_inc(bond->xdp_prog);
2394 	}
2395 
2396 	bond_xdp_set_features(bond_dev);
2397 
2398 	slave_info(bond_dev, slave_dev, "Enslaving as %s interface with %s link\n",
2399 		   bond_is_active_slave(new_slave) ? "an active" : "a backup",
2400 		   new_slave->link != BOND_LINK_DOWN ? "an up" : "a down");
2401 
2402 	/* enslave is successful */
2403 	bond_queue_slave_event(new_slave);
2404 	return 0;
2405 
2406 /* Undo stages on error */
2407 err_sysfs_del:
2408 	bond_sysfs_slave_del(new_slave);
2409 
2410 err_upper_unlink:
2411 	bond_upper_dev_unlink(bond, new_slave);
2412 
2413 err_unregister:
2414 	netdev_rx_handler_unregister(slave_dev);
2415 
2416 err_detach:
2417 	vlan_vids_del_by_dev(slave_dev, bond_dev);
2418 	if (rcu_access_pointer(bond->primary_slave) == new_slave)
2419 		RCU_INIT_POINTER(bond->primary_slave, NULL);
2420 	if (rcu_access_pointer(bond->curr_active_slave) == new_slave) {
2421 		block_netpoll_tx();
2422 		bond_change_active_slave(bond, NULL);
2423 		bond_select_active_slave(bond);
2424 		unblock_netpoll_tx();
2425 	}
2426 	/* either primary_slave or curr_active_slave might've changed */
2427 	synchronize_rcu();
2428 	slave_disable_netpoll(new_slave);
2429 
2430 err_close:
2431 	if (!netif_is_bond_master(slave_dev))
2432 		slave_dev->priv_flags &= ~IFF_BONDING;
2433 	dev_close(slave_dev);
2434 
2435 err_restore_mac:
2436 	slave_dev->priv_flags &= ~IFF_NO_ADDRCONF;
2437 	if (!bond->params.fail_over_mac ||
2438 	    BOND_MODE(bond) != BOND_MODE_ACTIVEBACKUP) {
2439 		/* XXX TODO - fom follow mode needs to change master's
2440 		 * MAC if this slave's MAC is in use by the bond, or at
2441 		 * least print a warning.
2442 		 */
2443 		bond_hw_addr_copy(ss.__data, new_slave->perm_hwaddr,
2444 				  new_slave->dev->addr_len);
2445 		ss.ss_family = slave_dev->type;
2446 		dev_set_mac_address(slave_dev, (struct sockaddr *)&ss, NULL);
2447 	}
2448 
2449 err_restore_mtu:
2450 	dev_set_mtu(slave_dev, new_slave->original_mtu);
2451 
2452 err_free:
2453 	kobject_put(&new_slave->kobj);
2454 
2455 err_undo_flags:
2456 	/* Enslave of first slave has failed and we need to fix master's mac */
2457 	if (!bond_has_slaves(bond)) {
2458 		if (ether_addr_equal_64bits(bond_dev->dev_addr,
2459 					    slave_dev->dev_addr))
2460 			eth_hw_addr_random(bond_dev);
2461 		if (bond_dev->type != ARPHRD_ETHER) {
2462 			dev_close(bond_dev);
2463 			bond_ether_setup(bond_dev);
2464 		}
2465 	}
2466 
2467 	return res;
2468 }
2469 
2470 /* Try to release the slave device <slave> from the bond device <master>
2471  * It is legal to access curr_active_slave without a lock because all the function
2472  * is RTNL-locked. If "all" is true it means that the function is being called
2473  * while destroying a bond interface and all slaves are being released.
2474  *
2475  * The rules for slave state should be:
2476  *   for Active/Backup:
2477  *     Active stays on all backups go down
2478  *   for Bonded connections:
2479  *     The first up interface should be left on and all others downed.
2480  */
2481 static int __bond_release_one(struct net_device *bond_dev,
2482 			      struct net_device *slave_dev,
2483 			      bool all, bool unregister)
2484 {
2485 	struct bonding *bond = netdev_priv(bond_dev);
2486 	struct slave *slave, *oldcurrent;
2487 	struct sockaddr_storage ss;
2488 	int old_flags = bond_dev->flags;
2489 	netdev_features_t old_features = bond_dev->features;
2490 
2491 	/* slave is not a slave or master is not master of this slave */
2492 	if (!(slave_dev->flags & IFF_SLAVE) ||
2493 	    !netdev_has_upper_dev(slave_dev, bond_dev)) {
2494 		slave_dbg(bond_dev, slave_dev, "cannot release slave\n");
2495 		return -EINVAL;
2496 	}
2497 
2498 	block_netpoll_tx();
2499 
2500 	slave = bond_get_slave_by_dev(bond, slave_dev);
2501 	if (!slave) {
2502 		/* not a slave of this bond */
2503 		slave_info(bond_dev, slave_dev, "interface not enslaved\n");
2504 		unblock_netpoll_tx();
2505 		return -EINVAL;
2506 	}
2507 
2508 	bond_set_slave_inactive_flags(slave, BOND_SLAVE_NOTIFY_NOW);
2509 
2510 	bond_sysfs_slave_del(slave);
2511 
2512 	/* recompute stats just before removing the slave */
2513 	bond_get_stats(bond->dev, &bond->bond_stats);
2514 
2515 	if (bond->xdp_prog) {
2516 		struct netdev_bpf xdp = {
2517 			.command = XDP_SETUP_PROG,
2518 			.flags   = 0,
2519 			.prog	 = NULL,
2520 			.extack  = NULL,
2521 		};
2522 		if (dev_xdp_propagate(slave_dev, &xdp))
2523 			slave_warn(bond_dev, slave_dev, "failed to unload XDP program\n");
2524 	}
2525 
2526 	/* unregister rx_handler early so bond_handle_frame wouldn't be called
2527 	 * for this slave anymore.
2528 	 */
2529 	netdev_rx_handler_unregister(slave_dev);
2530 
2531 	if (BOND_MODE(bond) == BOND_MODE_8023AD)
2532 		bond_3ad_unbind_slave(slave);
2533 
2534 	bond_upper_dev_unlink(bond, slave);
2535 
2536 	if (bond_mode_can_use_xmit_hash(bond))
2537 		bond_update_slave_arr(bond, slave);
2538 
2539 	slave_info(bond_dev, slave_dev, "Releasing %s interface\n",
2540 		    bond_is_active_slave(slave) ? "active" : "backup");
2541 
2542 	oldcurrent = rcu_access_pointer(bond->curr_active_slave);
2543 
2544 	RCU_INIT_POINTER(bond->current_arp_slave, NULL);
2545 
2546 	if (!all && (!bond->params.fail_over_mac ||
2547 		     BOND_MODE(bond) != BOND_MODE_ACTIVEBACKUP)) {
2548 		if (ether_addr_equal_64bits(bond_dev->dev_addr, slave->perm_hwaddr) &&
2549 		    bond_has_slaves(bond))
2550 			slave_warn(bond_dev, slave_dev, "the permanent HWaddr of slave - %pM - is still in use by bond - set the HWaddr of slave to a different address to avoid conflicts\n",
2551 				   slave->perm_hwaddr);
2552 	}
2553 
2554 	if (rtnl_dereference(bond->primary_slave) == slave)
2555 		RCU_INIT_POINTER(bond->primary_slave, NULL);
2556 
2557 	if (oldcurrent == slave)
2558 		bond_change_active_slave(bond, NULL);
2559 
2560 	if (bond_is_lb(bond)) {
2561 		/* Must be called only after the slave has been
2562 		 * detached from the list and the curr_active_slave
2563 		 * has been cleared (if our_slave == old_current),
2564 		 * but before a new active slave is selected.
2565 		 */
2566 		bond_alb_deinit_slave(bond, slave);
2567 	}
2568 
2569 	if (all) {
2570 		RCU_INIT_POINTER(bond->curr_active_slave, NULL);
2571 	} else if (oldcurrent == slave) {
2572 		/* Note that we hold RTNL over this sequence, so there
2573 		 * is no concern that another slave add/remove event
2574 		 * will interfere.
2575 		 */
2576 		bond_select_active_slave(bond);
2577 	}
2578 
2579 	bond_set_carrier(bond);
2580 	if (!bond_has_slaves(bond))
2581 		eth_hw_addr_random(bond_dev);
2582 
2583 	unblock_netpoll_tx();
2584 	synchronize_rcu();
2585 	bond->slave_cnt--;
2586 
2587 	if (!bond_has_slaves(bond)) {
2588 		call_netdevice_notifiers(NETDEV_CHANGEADDR, bond->dev);
2589 		call_netdevice_notifiers(NETDEV_RELEASE, bond->dev);
2590 	}
2591 
2592 	bond_compute_features(bond);
2593 	if (!(bond_dev->features & NETIF_F_VLAN_CHALLENGED) &&
2594 	    (old_features & NETIF_F_VLAN_CHALLENGED))
2595 		slave_info(bond_dev, slave_dev, "last VLAN challenged slave left bond - VLAN blocking is removed\n");
2596 
2597 	vlan_vids_del_by_dev(slave_dev, bond_dev);
2598 
2599 	/* If the mode uses primary, then this case was handled above by
2600 	 * bond_change_active_slave(..., NULL)
2601 	 */
2602 	if (!bond_uses_primary(bond)) {
2603 		/* unset promiscuity level from slave
2604 		 * NOTE: The NETDEV_CHANGEADDR call above may change the value
2605 		 * of the IFF_PROMISC flag in the bond_dev, but we need the
2606 		 * value of that flag before that change, as that was the value
2607 		 * when this slave was attached, so we cache at the start of the
2608 		 * function and use it here. Same goes for ALLMULTI below
2609 		 */
2610 		if (old_flags & IFF_PROMISC)
2611 			dev_set_promiscuity(slave_dev, -1);
2612 
2613 		/* unset allmulti level from slave */
2614 		if (old_flags & IFF_ALLMULTI)
2615 			dev_set_allmulti(slave_dev, -1);
2616 
2617 		if (old_flags & IFF_UP)
2618 			bond_hw_addr_flush(bond_dev, slave_dev);
2619 	}
2620 
2621 	slave_disable_netpoll(slave);
2622 
2623 	/* close slave before restoring its mac address */
2624 	dev_close(slave_dev);
2625 
2626 	slave_dev->priv_flags &= ~IFF_NO_ADDRCONF;
2627 
2628 	if (bond->params.fail_over_mac != BOND_FOM_ACTIVE ||
2629 	    BOND_MODE(bond) != BOND_MODE_ACTIVEBACKUP) {
2630 		/* restore original ("permanent") mac address */
2631 		bond_hw_addr_copy(ss.__data, slave->perm_hwaddr,
2632 				  slave->dev->addr_len);
2633 		ss.ss_family = slave_dev->type;
2634 		dev_set_mac_address(slave_dev, (struct sockaddr *)&ss, NULL);
2635 	}
2636 
2637 	if (unregister)
2638 		__dev_set_mtu(slave_dev, slave->original_mtu);
2639 	else
2640 		dev_set_mtu(slave_dev, slave->original_mtu);
2641 
2642 	if (!netif_is_bond_master(slave_dev))
2643 		slave_dev->priv_flags &= ~IFF_BONDING;
2644 
2645 	bond_xdp_set_features(bond_dev);
2646 	kobject_put(&slave->kobj);
2647 
2648 	return 0;
2649 }
2650 
2651 /* A wrapper used because of ndo_del_link */
2652 int bond_release(struct net_device *bond_dev, struct net_device *slave_dev)
2653 {
2654 	return __bond_release_one(bond_dev, slave_dev, false, false);
2655 }
2656 
2657 /* First release a slave and then destroy the bond if no more slaves are left.
2658  * Must be under rtnl_lock when this function is called.
2659  */
2660 static int bond_release_and_destroy(struct net_device *bond_dev,
2661 				    struct net_device *slave_dev)
2662 {
2663 	struct bonding *bond = netdev_priv(bond_dev);
2664 	int ret;
2665 
2666 	ret = __bond_release_one(bond_dev, slave_dev, false, true);
2667 	if (ret == 0 && !bond_has_slaves(bond) &&
2668 	    bond_dev->reg_state != NETREG_UNREGISTERING) {
2669 		bond_dev->priv_flags |= IFF_DISABLE_NETPOLL;
2670 		netdev_info(bond_dev, "Destroying bond\n");
2671 		bond_remove_proc_entry(bond);
2672 		unregister_netdevice(bond_dev);
2673 	}
2674 	return ret;
2675 }
2676 
2677 static void bond_info_query(struct net_device *bond_dev, struct ifbond *info)
2678 {
2679 	struct bonding *bond = netdev_priv(bond_dev);
2680 
2681 	bond_fill_ifbond(bond, info);
2682 }
2683 
2684 static int bond_slave_info_query(struct net_device *bond_dev, struct ifslave *info)
2685 {
2686 	struct bonding *bond = netdev_priv(bond_dev);
2687 	struct list_head *iter;
2688 	int i = 0, res = -ENODEV;
2689 	struct slave *slave;
2690 
2691 	bond_for_each_slave(bond, slave, iter) {
2692 		if (i++ == (int)info->slave_id) {
2693 			res = 0;
2694 			bond_fill_ifslave(slave, info);
2695 			break;
2696 		}
2697 	}
2698 
2699 	return res;
2700 }
2701 
2702 /*-------------------------------- Monitoring -------------------------------*/
2703 
2704 /* called with rcu_read_lock() */
2705 static int bond_miimon_inspect(struct bonding *bond)
2706 {
2707 	bool ignore_updelay = false;
2708 	int link_state, commit = 0;
2709 	struct list_head *iter;
2710 	struct slave *slave;
2711 
2712 	if (BOND_MODE(bond) == BOND_MODE_ACTIVEBACKUP) {
2713 		ignore_updelay = !rcu_dereference(bond->curr_active_slave);
2714 	} else {
2715 		struct bond_up_slave *usable_slaves;
2716 
2717 		usable_slaves = rcu_dereference(bond->usable_slaves);
2718 
2719 		if (usable_slaves && usable_slaves->count == 0)
2720 			ignore_updelay = true;
2721 	}
2722 
2723 	bond_for_each_slave_rcu(bond, slave, iter) {
2724 		bond_propose_link_state(slave, BOND_LINK_NOCHANGE);
2725 
2726 		link_state = bond_check_dev_link(bond, slave->dev, 0);
2727 
2728 		switch (slave->link) {
2729 		case BOND_LINK_UP:
2730 			if (link_state)
2731 				continue;
2732 
2733 			bond_propose_link_state(slave, BOND_LINK_FAIL);
2734 			commit++;
2735 			slave->delay = bond->params.downdelay;
2736 			if (slave->delay && net_ratelimit()) {
2737 				slave_info(bond->dev, slave->dev, "link status down for %sinterface, disabling it in %d ms\n",
2738 					   (BOND_MODE(bond) ==
2739 					    BOND_MODE_ACTIVEBACKUP) ?
2740 					    (bond_is_active_slave(slave) ?
2741 					     "active " : "backup ") : "",
2742 					   bond->params.downdelay * bond->params.miimon);
2743 			}
2744 			fallthrough;
2745 		case BOND_LINK_FAIL:
2746 			if (link_state) {
2747 				/* recovered before downdelay expired */
2748 				bond_propose_link_state(slave, BOND_LINK_UP);
2749 				slave->last_link_up = jiffies;
2750 				if (net_ratelimit())
2751 					slave_info(bond->dev, slave->dev, "link status up again after %d ms\n",
2752 						   (bond->params.downdelay - slave->delay) *
2753 						   bond->params.miimon);
2754 				commit++;
2755 				continue;
2756 			}
2757 
2758 			if (slave->delay <= 0) {
2759 				bond_propose_link_state(slave, BOND_LINK_DOWN);
2760 				commit++;
2761 				continue;
2762 			}
2763 
2764 			slave->delay--;
2765 			break;
2766 
2767 		case BOND_LINK_DOWN:
2768 			if (!link_state)
2769 				continue;
2770 
2771 			bond_propose_link_state(slave, BOND_LINK_BACK);
2772 			commit++;
2773 			slave->delay = bond->params.updelay;
2774 
2775 			if (slave->delay && net_ratelimit()) {
2776 				slave_info(bond->dev, slave->dev, "link status up, enabling it in %d ms\n",
2777 					   ignore_updelay ? 0 :
2778 					   bond->params.updelay *
2779 					   bond->params.miimon);
2780 			}
2781 			fallthrough;
2782 		case BOND_LINK_BACK:
2783 			if (!link_state) {
2784 				bond_propose_link_state(slave, BOND_LINK_DOWN);
2785 				if (net_ratelimit())
2786 					slave_info(bond->dev, slave->dev, "link status down again after %d ms\n",
2787 						   (bond->params.updelay - slave->delay) *
2788 						   bond->params.miimon);
2789 				commit++;
2790 				continue;
2791 			}
2792 
2793 			if (ignore_updelay)
2794 				slave->delay = 0;
2795 
2796 			if (slave->delay <= 0) {
2797 				bond_propose_link_state(slave, BOND_LINK_UP);
2798 				commit++;
2799 				ignore_updelay = false;
2800 				continue;
2801 			}
2802 
2803 			slave->delay--;
2804 			break;
2805 		}
2806 	}
2807 
2808 	return commit;
2809 }
2810 
2811 static void bond_miimon_link_change(struct bonding *bond,
2812 				    struct slave *slave,
2813 				    char link)
2814 {
2815 	switch (BOND_MODE(bond)) {
2816 	case BOND_MODE_8023AD:
2817 		bond_3ad_handle_link_change(slave, link);
2818 		break;
2819 	case BOND_MODE_TLB:
2820 	case BOND_MODE_ALB:
2821 		bond_alb_handle_link_change(bond, slave, link);
2822 		break;
2823 	case BOND_MODE_XOR:
2824 		bond_update_slave_arr(bond, NULL);
2825 		break;
2826 	}
2827 }
2828 
2829 static void bond_miimon_commit(struct bonding *bond)
2830 {
2831 	struct slave *slave, *primary, *active;
2832 	bool do_failover = false;
2833 	struct list_head *iter;
2834 
2835 	ASSERT_RTNL();
2836 
2837 	bond_for_each_slave(bond, slave, iter) {
2838 		switch (slave->link_new_state) {
2839 		case BOND_LINK_NOCHANGE:
2840 			/* For 802.3ad mode, check current slave speed and
2841 			 * duplex again in case its port was disabled after
2842 			 * invalid speed/duplex reporting but recovered before
2843 			 * link monitoring could make a decision on the actual
2844 			 * link status
2845 			 */
2846 			if (BOND_MODE(bond) == BOND_MODE_8023AD &&
2847 			    slave->link == BOND_LINK_UP)
2848 				bond_3ad_adapter_speed_duplex_changed(slave);
2849 			continue;
2850 
2851 		case BOND_LINK_UP:
2852 			if (bond_update_speed_duplex(slave) &&
2853 			    bond_needs_speed_duplex(bond)) {
2854 				slave->link = BOND_LINK_DOWN;
2855 				if (net_ratelimit())
2856 					slave_warn(bond->dev, slave->dev,
2857 						   "failed to get link speed/duplex\n");
2858 				continue;
2859 			}
2860 			bond_set_slave_link_state(slave, BOND_LINK_UP,
2861 						  BOND_SLAVE_NOTIFY_NOW);
2862 			slave->last_link_up = jiffies;
2863 
2864 			primary = rtnl_dereference(bond->primary_slave);
2865 			if (BOND_MODE(bond) == BOND_MODE_8023AD) {
2866 				/* prevent it from being the active one */
2867 				bond_set_backup_slave(slave);
2868 			} else if (BOND_MODE(bond) != BOND_MODE_ACTIVEBACKUP) {
2869 				/* make it immediately active */
2870 				bond_set_active_slave(slave);
2871 			}
2872 
2873 			slave_info(bond->dev, slave->dev, "link status definitely up, %u Mbps %s duplex\n",
2874 				   slave->speed == SPEED_UNKNOWN ? 0 : slave->speed,
2875 				   slave->duplex ? "full" : "half");
2876 
2877 			bond_miimon_link_change(bond, slave, BOND_LINK_UP);
2878 
2879 			active = rtnl_dereference(bond->curr_active_slave);
2880 			if (!active || slave == primary || slave->prio > active->prio)
2881 				do_failover = true;
2882 
2883 			continue;
2884 
2885 		case BOND_LINK_DOWN:
2886 			if (slave->link_failure_count < UINT_MAX)
2887 				slave->link_failure_count++;
2888 
2889 			bond_set_slave_link_state(slave, BOND_LINK_DOWN,
2890 						  BOND_SLAVE_NOTIFY_NOW);
2891 
2892 			if (BOND_MODE(bond) == BOND_MODE_ACTIVEBACKUP ||
2893 			    BOND_MODE(bond) == BOND_MODE_8023AD)
2894 				bond_set_slave_inactive_flags(slave,
2895 							      BOND_SLAVE_NOTIFY_NOW);
2896 
2897 			slave_info(bond->dev, slave->dev, "link status definitely down, disabling slave\n");
2898 
2899 			bond_miimon_link_change(bond, slave, BOND_LINK_DOWN);
2900 
2901 			if (slave == rcu_access_pointer(bond->curr_active_slave))
2902 				do_failover = true;
2903 
2904 			continue;
2905 
2906 		default:
2907 			slave_err(bond->dev, slave->dev, "invalid new link %d on slave\n",
2908 				  slave->link_new_state);
2909 			bond_propose_link_state(slave, BOND_LINK_NOCHANGE);
2910 
2911 			continue;
2912 		}
2913 	}
2914 
2915 	if (do_failover) {
2916 		block_netpoll_tx();
2917 		bond_select_active_slave(bond);
2918 		unblock_netpoll_tx();
2919 	}
2920 
2921 	bond_set_carrier(bond);
2922 }
2923 
2924 /* bond_mii_monitor
2925  *
2926  * Really a wrapper that splits the mii monitor into two phases: an
2927  * inspection, then (if inspection indicates something needs to be done)
2928  * an acquisition of appropriate locks followed by a commit phase to
2929  * implement whatever link state changes are indicated.
2930  */
2931 static void bond_mii_monitor(struct work_struct *work)
2932 {
2933 	struct bonding *bond = container_of(work, struct bonding,
2934 					    mii_work.work);
2935 	bool should_notify_peers = false;
2936 	bool commit;
2937 	unsigned long delay;
2938 	struct slave *slave;
2939 	struct list_head *iter;
2940 
2941 	delay = msecs_to_jiffies(bond->params.miimon);
2942 
2943 	if (!bond_has_slaves(bond))
2944 		goto re_arm;
2945 
2946 	rcu_read_lock();
2947 	should_notify_peers = bond_should_notify_peers(bond);
2948 	commit = !!bond_miimon_inspect(bond);
2949 	if (bond->send_peer_notif) {
2950 		rcu_read_unlock();
2951 		if (rtnl_trylock()) {
2952 			bond->send_peer_notif--;
2953 			rtnl_unlock();
2954 		}
2955 	} else {
2956 		rcu_read_unlock();
2957 	}
2958 
2959 	if (commit) {
2960 		/* Race avoidance with bond_close cancel of workqueue */
2961 		if (!rtnl_trylock()) {
2962 			delay = 1;
2963 			should_notify_peers = false;
2964 			goto re_arm;
2965 		}
2966 
2967 		bond_for_each_slave(bond, slave, iter) {
2968 			bond_commit_link_state(slave, BOND_SLAVE_NOTIFY_LATER);
2969 		}
2970 		bond_miimon_commit(bond);
2971 
2972 		rtnl_unlock();	/* might sleep, hold no other locks */
2973 	}
2974 
2975 re_arm:
2976 	if (bond->params.miimon)
2977 		queue_delayed_work(bond->wq, &bond->mii_work, delay);
2978 
2979 	if (should_notify_peers) {
2980 		if (!rtnl_trylock())
2981 			return;
2982 		call_netdevice_notifiers(NETDEV_NOTIFY_PEERS, bond->dev);
2983 		rtnl_unlock();
2984 	}
2985 }
2986 
2987 static int bond_upper_dev_walk(struct net_device *upper,
2988 			       struct netdev_nested_priv *priv)
2989 {
2990 	__be32 ip = *(__be32 *)priv->data;
2991 
2992 	return ip == bond_confirm_addr(upper, 0, ip);
2993 }
2994 
2995 static bool bond_has_this_ip(struct bonding *bond, __be32 ip)
2996 {
2997 	struct netdev_nested_priv priv = {
2998 		.data = (void *)&ip,
2999 	};
3000 	bool ret = false;
3001 
3002 	if (ip == bond_confirm_addr(bond->dev, 0, ip))
3003 		return true;
3004 
3005 	rcu_read_lock();
3006 	if (netdev_walk_all_upper_dev_rcu(bond->dev, bond_upper_dev_walk, &priv))
3007 		ret = true;
3008 	rcu_read_unlock();
3009 
3010 	return ret;
3011 }
3012 
3013 #define BOND_VLAN_PROTO_NONE cpu_to_be16(0xffff)
3014 
3015 static bool bond_handle_vlan(struct slave *slave, struct bond_vlan_tag *tags,
3016 			     struct sk_buff *skb)
3017 {
3018 	struct net_device *bond_dev = slave->bond->dev;
3019 	struct net_device *slave_dev = slave->dev;
3020 	struct bond_vlan_tag *outer_tag = tags;
3021 
3022 	if (!tags || tags->vlan_proto == BOND_VLAN_PROTO_NONE)
3023 		return true;
3024 
3025 	tags++;
3026 
3027 	/* Go through all the tags backwards and add them to the packet */
3028 	while (tags->vlan_proto != BOND_VLAN_PROTO_NONE) {
3029 		if (!tags->vlan_id) {
3030 			tags++;
3031 			continue;
3032 		}
3033 
3034 		slave_dbg(bond_dev, slave_dev, "inner tag: proto %X vid %X\n",
3035 			  ntohs(outer_tag->vlan_proto), tags->vlan_id);
3036 		skb = vlan_insert_tag_set_proto(skb, tags->vlan_proto,
3037 						tags->vlan_id);
3038 		if (!skb) {
3039 			net_err_ratelimited("failed to insert inner VLAN tag\n");
3040 			return false;
3041 		}
3042 
3043 		tags++;
3044 	}
3045 	/* Set the outer tag */
3046 	if (outer_tag->vlan_id) {
3047 		slave_dbg(bond_dev, slave_dev, "outer tag: proto %X vid %X\n",
3048 			  ntohs(outer_tag->vlan_proto), outer_tag->vlan_id);
3049 		__vlan_hwaccel_put_tag(skb, outer_tag->vlan_proto,
3050 				       outer_tag->vlan_id);
3051 	}
3052 
3053 	return true;
3054 }
3055 
3056 /* We go to the (large) trouble of VLAN tagging ARP frames because
3057  * switches in VLAN mode (especially if ports are configured as
3058  * "native" to a VLAN) might not pass non-tagged frames.
3059  */
3060 static void bond_arp_send(struct slave *slave, int arp_op, __be32 dest_ip,
3061 			  __be32 src_ip, struct bond_vlan_tag *tags)
3062 {
3063 	struct net_device *bond_dev = slave->bond->dev;
3064 	struct net_device *slave_dev = slave->dev;
3065 	struct sk_buff *skb;
3066 
3067 	slave_dbg(bond_dev, slave_dev, "arp %d on slave: dst %pI4 src %pI4\n",
3068 		  arp_op, &dest_ip, &src_ip);
3069 
3070 	skb = arp_create(arp_op, ETH_P_ARP, dest_ip, slave_dev, src_ip,
3071 			 NULL, slave_dev->dev_addr, NULL);
3072 
3073 	if (!skb) {
3074 		net_err_ratelimited("ARP packet allocation failed\n");
3075 		return;
3076 	}
3077 
3078 	if (bond_handle_vlan(slave, tags, skb)) {
3079 		slave_update_last_tx(slave);
3080 		arp_xmit(skb);
3081 	}
3082 
3083 	return;
3084 }
3085 
3086 /* Validate the device path between the @start_dev and the @end_dev.
3087  * The path is valid if the @end_dev is reachable through device
3088  * stacking.
3089  * When the path is validated, collect any vlan information in the
3090  * path.
3091  */
3092 struct bond_vlan_tag *bond_verify_device_path(struct net_device *start_dev,
3093 					      struct net_device *end_dev,
3094 					      int level)
3095 {
3096 	struct bond_vlan_tag *tags;
3097 	struct net_device *upper;
3098 	struct list_head  *iter;
3099 
3100 	if (start_dev == end_dev) {
3101 		tags = kcalloc(level + 1, sizeof(*tags), GFP_ATOMIC);
3102 		if (!tags)
3103 			return ERR_PTR(-ENOMEM);
3104 		tags[level].vlan_proto = BOND_VLAN_PROTO_NONE;
3105 		return tags;
3106 	}
3107 
3108 	netdev_for_each_upper_dev_rcu(start_dev, upper, iter) {
3109 		tags = bond_verify_device_path(upper, end_dev, level + 1);
3110 		if (IS_ERR_OR_NULL(tags)) {
3111 			if (IS_ERR(tags))
3112 				return tags;
3113 			continue;
3114 		}
3115 		if (is_vlan_dev(upper)) {
3116 			tags[level].vlan_proto = vlan_dev_vlan_proto(upper);
3117 			tags[level].vlan_id = vlan_dev_vlan_id(upper);
3118 		}
3119 
3120 		return tags;
3121 	}
3122 
3123 	return NULL;
3124 }
3125 
3126 static void bond_arp_send_all(struct bonding *bond, struct slave *slave)
3127 {
3128 	struct rtable *rt;
3129 	struct bond_vlan_tag *tags;
3130 	__be32 *targets = bond->params.arp_targets, addr;
3131 	int i;
3132 
3133 	for (i = 0; i < BOND_MAX_ARP_TARGETS && targets[i]; i++) {
3134 		slave_dbg(bond->dev, slave->dev, "%s: target %pI4\n",
3135 			  __func__, &targets[i]);
3136 		tags = NULL;
3137 
3138 		/* Find out through which dev should the packet go */
3139 		rt = ip_route_output(dev_net(bond->dev), targets[i], 0, 0, 0,
3140 				     RT_SCOPE_LINK);
3141 		if (IS_ERR(rt)) {
3142 			/* there's no route to target - try to send arp
3143 			 * probe to generate any traffic (arp_validate=0)
3144 			 */
3145 			if (bond->params.arp_validate)
3146 				pr_warn_once("%s: no route to arp_ip_target %pI4 and arp_validate is set\n",
3147 					     bond->dev->name,
3148 					     &targets[i]);
3149 			bond_arp_send(slave, ARPOP_REQUEST, targets[i],
3150 				      0, tags);
3151 			continue;
3152 		}
3153 
3154 		/* bond device itself */
3155 		if (rt->dst.dev == bond->dev)
3156 			goto found;
3157 
3158 		rcu_read_lock();
3159 		tags = bond_verify_device_path(bond->dev, rt->dst.dev, 0);
3160 		rcu_read_unlock();
3161 
3162 		if (!IS_ERR_OR_NULL(tags))
3163 			goto found;
3164 
3165 		/* Not our device - skip */
3166 		slave_dbg(bond->dev, slave->dev, "no path to arp_ip_target %pI4 via rt.dev %s\n",
3167 			   &targets[i], rt->dst.dev ? rt->dst.dev->name : "NULL");
3168 
3169 		ip_rt_put(rt);
3170 		continue;
3171 
3172 found:
3173 		addr = bond_confirm_addr(rt->dst.dev, targets[i], 0);
3174 		ip_rt_put(rt);
3175 		bond_arp_send(slave, ARPOP_REQUEST, targets[i], addr, tags);
3176 		kfree(tags);
3177 	}
3178 }
3179 
3180 static void bond_validate_arp(struct bonding *bond, struct slave *slave, __be32 sip, __be32 tip)
3181 {
3182 	int i;
3183 
3184 	if (!sip || !bond_has_this_ip(bond, tip)) {
3185 		slave_dbg(bond->dev, slave->dev, "%s: sip %pI4 tip %pI4 not found\n",
3186 			   __func__, &sip, &tip);
3187 		return;
3188 	}
3189 
3190 	i = bond_get_targets_ip(bond->params.arp_targets, sip);
3191 	if (i == -1) {
3192 		slave_dbg(bond->dev, slave->dev, "%s: sip %pI4 not found in targets\n",
3193 			   __func__, &sip);
3194 		return;
3195 	}
3196 	slave->last_rx = jiffies;
3197 	slave->target_last_arp_rx[i] = jiffies;
3198 }
3199 
3200 static int bond_arp_rcv(const struct sk_buff *skb, struct bonding *bond,
3201 			struct slave *slave)
3202 {
3203 	struct arphdr *arp = (struct arphdr *)skb->data;
3204 	struct slave *curr_active_slave, *curr_arp_slave;
3205 	unsigned char *arp_ptr;
3206 	__be32 sip, tip;
3207 	unsigned int alen;
3208 
3209 	alen = arp_hdr_len(bond->dev);
3210 
3211 	if (alen > skb_headlen(skb)) {
3212 		arp = kmalloc(alen, GFP_ATOMIC);
3213 		if (!arp)
3214 			goto out_unlock;
3215 		if (skb_copy_bits(skb, 0, arp, alen) < 0)
3216 			goto out_unlock;
3217 	}
3218 
3219 	if (arp->ar_hln != bond->dev->addr_len ||
3220 	    skb->pkt_type == PACKET_OTHERHOST ||
3221 	    skb->pkt_type == PACKET_LOOPBACK ||
3222 	    arp->ar_hrd != htons(ARPHRD_ETHER) ||
3223 	    arp->ar_pro != htons(ETH_P_IP) ||
3224 	    arp->ar_pln != 4)
3225 		goto out_unlock;
3226 
3227 	arp_ptr = (unsigned char *)(arp + 1);
3228 	arp_ptr += bond->dev->addr_len;
3229 	memcpy(&sip, arp_ptr, 4);
3230 	arp_ptr += 4 + bond->dev->addr_len;
3231 	memcpy(&tip, arp_ptr, 4);
3232 
3233 	slave_dbg(bond->dev, slave->dev, "%s: %s/%d av %d sv %d sip %pI4 tip %pI4\n",
3234 		  __func__, slave->dev->name, bond_slave_state(slave),
3235 		  bond->params.arp_validate, slave_do_arp_validate(bond, slave),
3236 		  &sip, &tip);
3237 
3238 	curr_active_slave = rcu_dereference(bond->curr_active_slave);
3239 	curr_arp_slave = rcu_dereference(bond->current_arp_slave);
3240 
3241 	/* We 'trust' the received ARP enough to validate it if:
3242 	 *
3243 	 * (a) the slave receiving the ARP is active (which includes the
3244 	 * current ARP slave, if any), or
3245 	 *
3246 	 * (b) the receiving slave isn't active, but there is a currently
3247 	 * active slave and it received valid arp reply(s) after it became
3248 	 * the currently active slave, or
3249 	 *
3250 	 * (c) there is an ARP slave that sent an ARP during the prior ARP
3251 	 * interval, and we receive an ARP reply on any slave.  We accept
3252 	 * these because switch FDB update delays may deliver the ARP
3253 	 * reply to a slave other than the sender of the ARP request.
3254 	 *
3255 	 * Note: for (b), backup slaves are receiving the broadcast ARP
3256 	 * request, not a reply.  This request passes from the sending
3257 	 * slave through the L2 switch(es) to the receiving slave.  Since
3258 	 * this is checking the request, sip/tip are swapped for
3259 	 * validation.
3260 	 *
3261 	 * This is done to avoid endless looping when we can't reach the
3262 	 * arp_ip_target and fool ourselves with our own arp requests.
3263 	 */
3264 	if (bond_is_active_slave(slave))
3265 		bond_validate_arp(bond, slave, sip, tip);
3266 	else if (curr_active_slave &&
3267 		 time_after(slave_last_rx(bond, curr_active_slave),
3268 			    curr_active_slave->last_link_up))
3269 		bond_validate_arp(bond, slave, tip, sip);
3270 	else if (curr_arp_slave && (arp->ar_op == htons(ARPOP_REPLY)) &&
3271 		 bond_time_in_interval(bond, slave_last_tx(curr_arp_slave), 1))
3272 		bond_validate_arp(bond, slave, sip, tip);
3273 
3274 out_unlock:
3275 	if (arp != (struct arphdr *)skb->data)
3276 		kfree(arp);
3277 	return RX_HANDLER_ANOTHER;
3278 }
3279 
3280 #if IS_ENABLED(CONFIG_IPV6)
3281 static void bond_ns_send(struct slave *slave, const struct in6_addr *daddr,
3282 			 const struct in6_addr *saddr, struct bond_vlan_tag *tags)
3283 {
3284 	struct net_device *bond_dev = slave->bond->dev;
3285 	struct net_device *slave_dev = slave->dev;
3286 	struct in6_addr mcaddr;
3287 	struct sk_buff *skb;
3288 
3289 	slave_dbg(bond_dev, slave_dev, "NS on slave: dst %pI6c src %pI6c\n",
3290 		  daddr, saddr);
3291 
3292 	skb = ndisc_ns_create(slave_dev, daddr, saddr, 0);
3293 	if (!skb) {
3294 		net_err_ratelimited("NS packet allocation failed\n");
3295 		return;
3296 	}
3297 
3298 	addrconf_addr_solict_mult(daddr, &mcaddr);
3299 	if (bond_handle_vlan(slave, tags, skb)) {
3300 		slave_update_last_tx(slave);
3301 		ndisc_send_skb(skb, &mcaddr, saddr);
3302 	}
3303 }
3304 
3305 static void bond_ns_send_all(struct bonding *bond, struct slave *slave)
3306 {
3307 	struct in6_addr *targets = bond->params.ns_targets;
3308 	struct bond_vlan_tag *tags;
3309 	struct dst_entry *dst;
3310 	struct in6_addr saddr;
3311 	struct flowi6 fl6;
3312 	int i;
3313 
3314 	for (i = 0; i < BOND_MAX_NS_TARGETS && !ipv6_addr_any(&targets[i]); i++) {
3315 		slave_dbg(bond->dev, slave->dev, "%s: target %pI6c\n",
3316 			  __func__, &targets[i]);
3317 		tags = NULL;
3318 
3319 		/* Find out through which dev should the packet go */
3320 		memset(&fl6, 0, sizeof(struct flowi6));
3321 		fl6.daddr = targets[i];
3322 		fl6.flowi6_oif = bond->dev->ifindex;
3323 
3324 		dst = ip6_route_output(dev_net(bond->dev), NULL, &fl6);
3325 		if (dst->error) {
3326 			dst_release(dst);
3327 			/* there's no route to target - try to send arp
3328 			 * probe to generate any traffic (arp_validate=0)
3329 			 */
3330 			if (bond->params.arp_validate)
3331 				pr_warn_once("%s: no route to ns_ip6_target %pI6c and arp_validate is set\n",
3332 					     bond->dev->name,
3333 					     &targets[i]);
3334 			bond_ns_send(slave, &targets[i], &in6addr_any, tags);
3335 			continue;
3336 		}
3337 
3338 		/* bond device itself */
3339 		if (dst->dev == bond->dev)
3340 			goto found;
3341 
3342 		rcu_read_lock();
3343 		tags = bond_verify_device_path(bond->dev, dst->dev, 0);
3344 		rcu_read_unlock();
3345 
3346 		if (!IS_ERR_OR_NULL(tags))
3347 			goto found;
3348 
3349 		/* Not our device - skip */
3350 		slave_dbg(bond->dev, slave->dev, "no path to ns_ip6_target %pI6c via dst->dev %s\n",
3351 			  &targets[i], dst->dev ? dst->dev->name : "NULL");
3352 
3353 		dst_release(dst);
3354 		continue;
3355 
3356 found:
3357 		if (!ipv6_dev_get_saddr(dev_net(dst->dev), dst->dev, &targets[i], 0, &saddr))
3358 			bond_ns_send(slave, &targets[i], &saddr, tags);
3359 		else
3360 			bond_ns_send(slave, &targets[i], &in6addr_any, tags);
3361 
3362 		dst_release(dst);
3363 		kfree(tags);
3364 	}
3365 }
3366 
3367 static int bond_confirm_addr6(struct net_device *dev,
3368 			      struct netdev_nested_priv *priv)
3369 {
3370 	struct in6_addr *addr = (struct in6_addr *)priv->data;
3371 
3372 	return ipv6_chk_addr(dev_net(dev), addr, dev, 0);
3373 }
3374 
3375 static bool bond_has_this_ip6(struct bonding *bond, struct in6_addr *addr)
3376 {
3377 	struct netdev_nested_priv priv = {
3378 		.data = addr,
3379 	};
3380 	int ret = false;
3381 
3382 	if (bond_confirm_addr6(bond->dev, &priv))
3383 		return true;
3384 
3385 	rcu_read_lock();
3386 	if (netdev_walk_all_upper_dev_rcu(bond->dev, bond_confirm_addr6, &priv))
3387 		ret = true;
3388 	rcu_read_unlock();
3389 
3390 	return ret;
3391 }
3392 
3393 static void bond_validate_na(struct bonding *bond, struct slave *slave,
3394 			     struct in6_addr *saddr, struct in6_addr *daddr)
3395 {
3396 	int i;
3397 
3398 	/* Ignore NAs that:
3399 	 * 1. Source address is unspecified address.
3400 	 * 2. Dest address is neither all-nodes multicast address nor
3401 	 *    exist on bond interface.
3402 	 */
3403 	if (ipv6_addr_any(saddr) ||
3404 	    (!ipv6_addr_equal(daddr, &in6addr_linklocal_allnodes) &&
3405 	     !bond_has_this_ip6(bond, daddr))) {
3406 		slave_dbg(bond->dev, slave->dev, "%s: sip %pI6c tip %pI6c not found\n",
3407 			  __func__, saddr, daddr);
3408 		return;
3409 	}
3410 
3411 	i = bond_get_targets_ip6(bond->params.ns_targets, saddr);
3412 	if (i == -1) {
3413 		slave_dbg(bond->dev, slave->dev, "%s: sip %pI6c not found in targets\n",
3414 			  __func__, saddr);
3415 		return;
3416 	}
3417 	slave->last_rx = jiffies;
3418 	slave->target_last_arp_rx[i] = jiffies;
3419 }
3420 
3421 static int bond_na_rcv(const struct sk_buff *skb, struct bonding *bond,
3422 		       struct slave *slave)
3423 {
3424 	struct slave *curr_active_slave, *curr_arp_slave;
3425 	struct in6_addr *saddr, *daddr;
3426 	struct {
3427 		struct ipv6hdr ip6;
3428 		struct icmp6hdr icmp6;
3429 	} *combined, _combined;
3430 
3431 	if (skb->pkt_type == PACKET_OTHERHOST ||
3432 	    skb->pkt_type == PACKET_LOOPBACK)
3433 		goto out;
3434 
3435 	combined = skb_header_pointer(skb, 0, sizeof(_combined), &_combined);
3436 	if (!combined || combined->ip6.nexthdr != NEXTHDR_ICMP ||
3437 	    (combined->icmp6.icmp6_type != NDISC_NEIGHBOUR_SOLICITATION &&
3438 	     combined->icmp6.icmp6_type != NDISC_NEIGHBOUR_ADVERTISEMENT))
3439 		goto out;
3440 
3441 	saddr = &combined->ip6.saddr;
3442 	daddr = &combined->ip6.daddr;
3443 
3444 	slave_dbg(bond->dev, slave->dev, "%s: %s/%d av %d sv %d sip %pI6c tip %pI6c\n",
3445 		  __func__, slave->dev->name, bond_slave_state(slave),
3446 		  bond->params.arp_validate, slave_do_arp_validate(bond, slave),
3447 		  saddr, daddr);
3448 
3449 	curr_active_slave = rcu_dereference(bond->curr_active_slave);
3450 	curr_arp_slave = rcu_dereference(bond->current_arp_slave);
3451 
3452 	/* We 'trust' the received ARP enough to validate it if:
3453 	 * see bond_arp_rcv().
3454 	 */
3455 	if (bond_is_active_slave(slave))
3456 		bond_validate_na(bond, slave, saddr, daddr);
3457 	else if (curr_active_slave &&
3458 		 time_after(slave_last_rx(bond, curr_active_slave),
3459 			    curr_active_slave->last_link_up))
3460 		bond_validate_na(bond, slave, daddr, saddr);
3461 	else if (curr_arp_slave &&
3462 		 bond_time_in_interval(bond, slave_last_tx(curr_arp_slave), 1))
3463 		bond_validate_na(bond, slave, saddr, daddr);
3464 
3465 out:
3466 	return RX_HANDLER_ANOTHER;
3467 }
3468 #endif
3469 
3470 int bond_rcv_validate(const struct sk_buff *skb, struct bonding *bond,
3471 		      struct slave *slave)
3472 {
3473 #if IS_ENABLED(CONFIG_IPV6)
3474 	bool is_ipv6 = skb->protocol == __cpu_to_be16(ETH_P_IPV6);
3475 #endif
3476 	bool is_arp = skb->protocol == __cpu_to_be16(ETH_P_ARP);
3477 
3478 	slave_dbg(bond->dev, slave->dev, "%s: skb->dev %s\n",
3479 		  __func__, skb->dev->name);
3480 
3481 	/* Use arp validate logic for both ARP and NS */
3482 	if (!slave_do_arp_validate(bond, slave)) {
3483 		if ((slave_do_arp_validate_only(bond) && is_arp) ||
3484 #if IS_ENABLED(CONFIG_IPV6)
3485 		    (slave_do_arp_validate_only(bond) && is_ipv6) ||
3486 #endif
3487 		    !slave_do_arp_validate_only(bond))
3488 			slave->last_rx = jiffies;
3489 		return RX_HANDLER_ANOTHER;
3490 	} else if (is_arp) {
3491 		return bond_arp_rcv(skb, bond, slave);
3492 #if IS_ENABLED(CONFIG_IPV6)
3493 	} else if (is_ipv6) {
3494 		return bond_na_rcv(skb, bond, slave);
3495 #endif
3496 	} else {
3497 		return RX_HANDLER_ANOTHER;
3498 	}
3499 }
3500 
3501 static void bond_send_validate(struct bonding *bond, struct slave *slave)
3502 {
3503 	bond_arp_send_all(bond, slave);
3504 #if IS_ENABLED(CONFIG_IPV6)
3505 	bond_ns_send_all(bond, slave);
3506 #endif
3507 }
3508 
3509 /* function to verify if we're in the arp_interval timeslice, returns true if
3510  * (last_act - arp_interval) <= jiffies <= (last_act + mod * arp_interval +
3511  * arp_interval/2) . the arp_interval/2 is needed for really fast networks.
3512  */
3513 static bool bond_time_in_interval(struct bonding *bond, unsigned long last_act,
3514 				  int mod)
3515 {
3516 	int delta_in_ticks = msecs_to_jiffies(bond->params.arp_interval);
3517 
3518 	return time_in_range(jiffies,
3519 			     last_act - delta_in_ticks,
3520 			     last_act + mod * delta_in_ticks + delta_in_ticks/2);
3521 }
3522 
3523 /* This function is called regularly to monitor each slave's link
3524  * ensuring that traffic is being sent and received when arp monitoring
3525  * is used in load-balancing mode. if the adapter has been dormant, then an
3526  * arp is transmitted to generate traffic. see activebackup_arp_monitor for
3527  * arp monitoring in active backup mode.
3528  */
3529 static void bond_loadbalance_arp_mon(struct bonding *bond)
3530 {
3531 	struct slave *slave, *oldcurrent;
3532 	struct list_head *iter;
3533 	int do_failover = 0, slave_state_changed = 0;
3534 
3535 	if (!bond_has_slaves(bond))
3536 		goto re_arm;
3537 
3538 	rcu_read_lock();
3539 
3540 	oldcurrent = rcu_dereference(bond->curr_active_slave);
3541 	/* see if any of the previous devices are up now (i.e. they have
3542 	 * xmt and rcv traffic). the curr_active_slave does not come into
3543 	 * the picture unless it is null. also, slave->last_link_up is not
3544 	 * needed here because we send an arp on each slave and give a slave
3545 	 * as long as it needs to get the tx/rx within the delta.
3546 	 * TODO: what about up/down delay in arp mode? it wasn't here before
3547 	 *       so it can wait
3548 	 */
3549 	bond_for_each_slave_rcu(bond, slave, iter) {
3550 		unsigned long last_tx = slave_last_tx(slave);
3551 
3552 		bond_propose_link_state(slave, BOND_LINK_NOCHANGE);
3553 
3554 		if (slave->link != BOND_LINK_UP) {
3555 			if (bond_time_in_interval(bond, last_tx, 1) &&
3556 			    bond_time_in_interval(bond, slave->last_rx, 1)) {
3557 
3558 				bond_propose_link_state(slave, BOND_LINK_UP);
3559 				slave_state_changed = 1;
3560 
3561 				/* primary_slave has no meaning in round-robin
3562 				 * mode. the window of a slave being up and
3563 				 * curr_active_slave being null after enslaving
3564 				 * is closed.
3565 				 */
3566 				if (!oldcurrent) {
3567 					slave_info(bond->dev, slave->dev, "link status definitely up\n");
3568 					do_failover = 1;
3569 				} else {
3570 					slave_info(bond->dev, slave->dev, "interface is now up\n");
3571 				}
3572 			}
3573 		} else {
3574 			/* slave->link == BOND_LINK_UP */
3575 
3576 			/* not all switches will respond to an arp request
3577 			 * when the source ip is 0, so don't take the link down
3578 			 * if we don't know our ip yet
3579 			 */
3580 			if (!bond_time_in_interval(bond, last_tx, bond->params.missed_max) ||
3581 			    !bond_time_in_interval(bond, slave->last_rx, bond->params.missed_max)) {
3582 
3583 				bond_propose_link_state(slave, BOND_LINK_DOWN);
3584 				slave_state_changed = 1;
3585 
3586 				if (slave->link_failure_count < UINT_MAX)
3587 					slave->link_failure_count++;
3588 
3589 				slave_info(bond->dev, slave->dev, "interface is now down\n");
3590 
3591 				if (slave == oldcurrent)
3592 					do_failover = 1;
3593 			}
3594 		}
3595 
3596 		/* note: if switch is in round-robin mode, all links
3597 		 * must tx arp to ensure all links rx an arp - otherwise
3598 		 * links may oscillate or not come up at all; if switch is
3599 		 * in something like xor mode, there is nothing we can
3600 		 * do - all replies will be rx'ed on same link causing slaves
3601 		 * to be unstable during low/no traffic periods
3602 		 */
3603 		if (bond_slave_is_up(slave))
3604 			bond_send_validate(bond, slave);
3605 	}
3606 
3607 	rcu_read_unlock();
3608 
3609 	if (do_failover || slave_state_changed) {
3610 		if (!rtnl_trylock())
3611 			goto re_arm;
3612 
3613 		bond_for_each_slave(bond, slave, iter) {
3614 			if (slave->link_new_state != BOND_LINK_NOCHANGE)
3615 				slave->link = slave->link_new_state;
3616 		}
3617 
3618 		if (slave_state_changed) {
3619 			bond_slave_state_change(bond);
3620 			if (BOND_MODE(bond) == BOND_MODE_XOR)
3621 				bond_update_slave_arr(bond, NULL);
3622 		}
3623 		if (do_failover) {
3624 			block_netpoll_tx();
3625 			bond_select_active_slave(bond);
3626 			unblock_netpoll_tx();
3627 		}
3628 		rtnl_unlock();
3629 	}
3630 
3631 re_arm:
3632 	if (bond->params.arp_interval)
3633 		queue_delayed_work(bond->wq, &bond->arp_work,
3634 				   msecs_to_jiffies(bond->params.arp_interval));
3635 }
3636 
3637 /* Called to inspect slaves for active-backup mode ARP monitor link state
3638  * changes.  Sets proposed link state in slaves to specify what action
3639  * should take place for the slave.  Returns 0 if no changes are found, >0
3640  * if changes to link states must be committed.
3641  *
3642  * Called with rcu_read_lock held.
3643  */
3644 static int bond_ab_arp_inspect(struct bonding *bond)
3645 {
3646 	unsigned long last_tx, last_rx;
3647 	struct list_head *iter;
3648 	struct slave *slave;
3649 	int commit = 0;
3650 
3651 	bond_for_each_slave_rcu(bond, slave, iter) {
3652 		bond_propose_link_state(slave, BOND_LINK_NOCHANGE);
3653 		last_rx = slave_last_rx(bond, slave);
3654 
3655 		if (slave->link != BOND_LINK_UP) {
3656 			if (bond_time_in_interval(bond, last_rx, 1)) {
3657 				bond_propose_link_state(slave, BOND_LINK_UP);
3658 				commit++;
3659 			} else if (slave->link == BOND_LINK_BACK) {
3660 				bond_propose_link_state(slave, BOND_LINK_FAIL);
3661 				commit++;
3662 			}
3663 			continue;
3664 		}
3665 
3666 		/* Give slaves 2*delta after being enslaved or made
3667 		 * active.  This avoids bouncing, as the last receive
3668 		 * times need a full ARP monitor cycle to be updated.
3669 		 */
3670 		if (bond_time_in_interval(bond, slave->last_link_up, 2))
3671 			continue;
3672 
3673 		/* Backup slave is down if:
3674 		 * - No current_arp_slave AND
3675 		 * - more than (missed_max+1)*delta since last receive AND
3676 		 * - the bond has an IP address
3677 		 *
3678 		 * Note: a non-null current_arp_slave indicates
3679 		 * the curr_active_slave went down and we are
3680 		 * searching for a new one; under this condition
3681 		 * we only take the curr_active_slave down - this
3682 		 * gives each slave a chance to tx/rx traffic
3683 		 * before being taken out
3684 		 */
3685 		if (!bond_is_active_slave(slave) &&
3686 		    !rcu_access_pointer(bond->current_arp_slave) &&
3687 		    !bond_time_in_interval(bond, last_rx, bond->params.missed_max + 1)) {
3688 			bond_propose_link_state(slave, BOND_LINK_DOWN);
3689 			commit++;
3690 		}
3691 
3692 		/* Active slave is down if:
3693 		 * - more than missed_max*delta since transmitting OR
3694 		 * - (more than missed_max*delta since receive AND
3695 		 *    the bond has an IP address)
3696 		 */
3697 		last_tx = slave_last_tx(slave);
3698 		if (bond_is_active_slave(slave) &&
3699 		    (!bond_time_in_interval(bond, last_tx, bond->params.missed_max) ||
3700 		     !bond_time_in_interval(bond, last_rx, bond->params.missed_max))) {
3701 			bond_propose_link_state(slave, BOND_LINK_DOWN);
3702 			commit++;
3703 		}
3704 	}
3705 
3706 	return commit;
3707 }
3708 
3709 /* Called to commit link state changes noted by inspection step of
3710  * active-backup mode ARP monitor.
3711  *
3712  * Called with RTNL hold.
3713  */
3714 static void bond_ab_arp_commit(struct bonding *bond)
3715 {
3716 	bool do_failover = false;
3717 	struct list_head *iter;
3718 	unsigned long last_tx;
3719 	struct slave *slave;
3720 
3721 	bond_for_each_slave(bond, slave, iter) {
3722 		switch (slave->link_new_state) {
3723 		case BOND_LINK_NOCHANGE:
3724 			continue;
3725 
3726 		case BOND_LINK_UP:
3727 			last_tx = slave_last_tx(slave);
3728 			if (rtnl_dereference(bond->curr_active_slave) != slave ||
3729 			    (!rtnl_dereference(bond->curr_active_slave) &&
3730 			     bond_time_in_interval(bond, last_tx, 1))) {
3731 				struct slave *current_arp_slave;
3732 
3733 				current_arp_slave = rtnl_dereference(bond->current_arp_slave);
3734 				bond_set_slave_link_state(slave, BOND_LINK_UP,
3735 							  BOND_SLAVE_NOTIFY_NOW);
3736 				if (current_arp_slave) {
3737 					bond_set_slave_inactive_flags(
3738 						current_arp_slave,
3739 						BOND_SLAVE_NOTIFY_NOW);
3740 					RCU_INIT_POINTER(bond->current_arp_slave, NULL);
3741 				}
3742 
3743 				slave_info(bond->dev, slave->dev, "link status definitely up\n");
3744 
3745 				if (!rtnl_dereference(bond->curr_active_slave) ||
3746 				    slave == rtnl_dereference(bond->primary_slave) ||
3747 				    slave->prio > rtnl_dereference(bond->curr_active_slave)->prio)
3748 					do_failover = true;
3749 
3750 			}
3751 
3752 			continue;
3753 
3754 		case BOND_LINK_DOWN:
3755 			if (slave->link_failure_count < UINT_MAX)
3756 				slave->link_failure_count++;
3757 
3758 			bond_set_slave_link_state(slave, BOND_LINK_DOWN,
3759 						  BOND_SLAVE_NOTIFY_NOW);
3760 			bond_set_slave_inactive_flags(slave,
3761 						      BOND_SLAVE_NOTIFY_NOW);
3762 
3763 			slave_info(bond->dev, slave->dev, "link status definitely down, disabling slave\n");
3764 
3765 			if (slave == rtnl_dereference(bond->curr_active_slave)) {
3766 				RCU_INIT_POINTER(bond->current_arp_slave, NULL);
3767 				do_failover = true;
3768 			}
3769 
3770 			continue;
3771 
3772 		case BOND_LINK_FAIL:
3773 			bond_set_slave_link_state(slave, BOND_LINK_FAIL,
3774 						  BOND_SLAVE_NOTIFY_NOW);
3775 			bond_set_slave_inactive_flags(slave,
3776 						      BOND_SLAVE_NOTIFY_NOW);
3777 
3778 			/* A slave has just been enslaved and has become
3779 			 * the current active slave.
3780 			 */
3781 			if (rtnl_dereference(bond->curr_active_slave))
3782 				RCU_INIT_POINTER(bond->current_arp_slave, NULL);
3783 			continue;
3784 
3785 		default:
3786 			slave_err(bond->dev, slave->dev,
3787 				  "impossible: link_new_state %d on slave\n",
3788 				  slave->link_new_state);
3789 			continue;
3790 		}
3791 	}
3792 
3793 	if (do_failover) {
3794 		block_netpoll_tx();
3795 		bond_select_active_slave(bond);
3796 		unblock_netpoll_tx();
3797 	}
3798 
3799 	bond_set_carrier(bond);
3800 }
3801 
3802 /* Send ARP probes for active-backup mode ARP monitor.
3803  *
3804  * Called with rcu_read_lock held.
3805  */
3806 static bool bond_ab_arp_probe(struct bonding *bond)
3807 {
3808 	struct slave *slave, *before = NULL, *new_slave = NULL,
3809 		     *curr_arp_slave = rcu_dereference(bond->current_arp_slave),
3810 		     *curr_active_slave = rcu_dereference(bond->curr_active_slave);
3811 	struct list_head *iter;
3812 	bool found = false;
3813 	bool should_notify_rtnl = BOND_SLAVE_NOTIFY_LATER;
3814 
3815 	if (curr_arp_slave && curr_active_slave)
3816 		netdev_info(bond->dev, "PROBE: c_arp %s && cas %s BAD\n",
3817 			    curr_arp_slave->dev->name,
3818 			    curr_active_slave->dev->name);
3819 
3820 	if (curr_active_slave) {
3821 		bond_send_validate(bond, curr_active_slave);
3822 		return should_notify_rtnl;
3823 	}
3824 
3825 	/* if we don't have a curr_active_slave, search for the next available
3826 	 * backup slave from the current_arp_slave and make it the candidate
3827 	 * for becoming the curr_active_slave
3828 	 */
3829 
3830 	if (!curr_arp_slave) {
3831 		curr_arp_slave = bond_first_slave_rcu(bond);
3832 		if (!curr_arp_slave)
3833 			return should_notify_rtnl;
3834 	}
3835 
3836 	bond_for_each_slave_rcu(bond, slave, iter) {
3837 		if (!found && !before && bond_slave_is_up(slave))
3838 			before = slave;
3839 
3840 		if (found && !new_slave && bond_slave_is_up(slave))
3841 			new_slave = slave;
3842 		/* if the link state is up at this point, we
3843 		 * mark it down - this can happen if we have
3844 		 * simultaneous link failures and
3845 		 * reselect_active_interface doesn't make this
3846 		 * one the current slave so it is still marked
3847 		 * up when it is actually down
3848 		 */
3849 		if (!bond_slave_is_up(slave) && slave->link == BOND_LINK_UP) {
3850 			bond_set_slave_link_state(slave, BOND_LINK_DOWN,
3851 						  BOND_SLAVE_NOTIFY_LATER);
3852 			if (slave->link_failure_count < UINT_MAX)
3853 				slave->link_failure_count++;
3854 
3855 			bond_set_slave_inactive_flags(slave,
3856 						      BOND_SLAVE_NOTIFY_LATER);
3857 
3858 			slave_info(bond->dev, slave->dev, "backup interface is now down\n");
3859 		}
3860 		if (slave == curr_arp_slave)
3861 			found = true;
3862 	}
3863 
3864 	if (!new_slave && before)
3865 		new_slave = before;
3866 
3867 	if (!new_slave)
3868 		goto check_state;
3869 
3870 	bond_set_slave_link_state(new_slave, BOND_LINK_BACK,
3871 				  BOND_SLAVE_NOTIFY_LATER);
3872 	bond_set_slave_active_flags(new_slave, BOND_SLAVE_NOTIFY_LATER);
3873 	bond_send_validate(bond, new_slave);
3874 	new_slave->last_link_up = jiffies;
3875 	rcu_assign_pointer(bond->current_arp_slave, new_slave);
3876 
3877 check_state:
3878 	bond_for_each_slave_rcu(bond, slave, iter) {
3879 		if (slave->should_notify || slave->should_notify_link) {
3880 			should_notify_rtnl = BOND_SLAVE_NOTIFY_NOW;
3881 			break;
3882 		}
3883 	}
3884 	return should_notify_rtnl;
3885 }
3886 
3887 static void bond_activebackup_arp_mon(struct bonding *bond)
3888 {
3889 	bool should_notify_peers = false;
3890 	bool should_notify_rtnl = false;
3891 	int delta_in_ticks;
3892 
3893 	delta_in_ticks = msecs_to_jiffies(bond->params.arp_interval);
3894 
3895 	if (!bond_has_slaves(bond))
3896 		goto re_arm;
3897 
3898 	rcu_read_lock();
3899 
3900 	should_notify_peers = bond_should_notify_peers(bond);
3901 
3902 	if (bond_ab_arp_inspect(bond)) {
3903 		rcu_read_unlock();
3904 
3905 		/* Race avoidance with bond_close flush of workqueue */
3906 		if (!rtnl_trylock()) {
3907 			delta_in_ticks = 1;
3908 			should_notify_peers = false;
3909 			goto re_arm;
3910 		}
3911 
3912 		bond_ab_arp_commit(bond);
3913 
3914 		rtnl_unlock();
3915 		rcu_read_lock();
3916 	}
3917 
3918 	should_notify_rtnl = bond_ab_arp_probe(bond);
3919 	rcu_read_unlock();
3920 
3921 re_arm:
3922 	if (bond->params.arp_interval)
3923 		queue_delayed_work(bond->wq, &bond->arp_work, delta_in_ticks);
3924 
3925 	if (should_notify_peers || should_notify_rtnl) {
3926 		if (!rtnl_trylock())
3927 			return;
3928 
3929 		if (should_notify_peers) {
3930 			bond->send_peer_notif--;
3931 			call_netdevice_notifiers(NETDEV_NOTIFY_PEERS,
3932 						 bond->dev);
3933 		}
3934 		if (should_notify_rtnl) {
3935 			bond_slave_state_notify(bond);
3936 			bond_slave_link_notify(bond);
3937 		}
3938 
3939 		rtnl_unlock();
3940 	}
3941 }
3942 
3943 static void bond_arp_monitor(struct work_struct *work)
3944 {
3945 	struct bonding *bond = container_of(work, struct bonding,
3946 					    arp_work.work);
3947 
3948 	if (BOND_MODE(bond) == BOND_MODE_ACTIVEBACKUP)
3949 		bond_activebackup_arp_mon(bond);
3950 	else
3951 		bond_loadbalance_arp_mon(bond);
3952 }
3953 
3954 /*-------------------------- netdev event handling --------------------------*/
3955 
3956 /* Change device name */
3957 static int bond_event_changename(struct bonding *bond)
3958 {
3959 	bond_remove_proc_entry(bond);
3960 	bond_create_proc_entry(bond);
3961 
3962 	bond_debug_reregister(bond);
3963 
3964 	return NOTIFY_DONE;
3965 }
3966 
3967 static int bond_master_netdev_event(unsigned long event,
3968 				    struct net_device *bond_dev)
3969 {
3970 	struct bonding *event_bond = netdev_priv(bond_dev);
3971 
3972 	netdev_dbg(bond_dev, "%s called\n", __func__);
3973 
3974 	switch (event) {
3975 	case NETDEV_CHANGENAME:
3976 		return bond_event_changename(event_bond);
3977 	case NETDEV_UNREGISTER:
3978 		bond_remove_proc_entry(event_bond);
3979 #ifdef CONFIG_XFRM_OFFLOAD
3980 		xfrm_dev_state_flush(dev_net(bond_dev), bond_dev, true);
3981 #endif /* CONFIG_XFRM_OFFLOAD */
3982 		break;
3983 	case NETDEV_REGISTER:
3984 		bond_create_proc_entry(event_bond);
3985 		break;
3986 	default:
3987 		break;
3988 	}
3989 
3990 	return NOTIFY_DONE;
3991 }
3992 
3993 static int bond_slave_netdev_event(unsigned long event,
3994 				   struct net_device *slave_dev)
3995 {
3996 	struct slave *slave = bond_slave_get_rtnl(slave_dev), *primary;
3997 	struct bonding *bond;
3998 	struct net_device *bond_dev;
3999 
4000 	/* A netdev event can be generated while enslaving a device
4001 	 * before netdev_rx_handler_register is called in which case
4002 	 * slave will be NULL
4003 	 */
4004 	if (!slave) {
4005 		netdev_dbg(slave_dev, "%s called on NULL slave\n", __func__);
4006 		return NOTIFY_DONE;
4007 	}
4008 
4009 	bond_dev = slave->bond->dev;
4010 	bond = slave->bond;
4011 	primary = rtnl_dereference(bond->primary_slave);
4012 
4013 	slave_dbg(bond_dev, slave_dev, "%s called\n", __func__);
4014 
4015 	switch (event) {
4016 	case NETDEV_UNREGISTER:
4017 		if (bond_dev->type != ARPHRD_ETHER)
4018 			bond_release_and_destroy(bond_dev, slave_dev);
4019 		else
4020 			__bond_release_one(bond_dev, slave_dev, false, true);
4021 		break;
4022 	case NETDEV_UP:
4023 	case NETDEV_CHANGE:
4024 		/* For 802.3ad mode only:
4025 		 * Getting invalid Speed/Duplex values here will put slave
4026 		 * in weird state. Mark it as link-fail if the link was
4027 		 * previously up or link-down if it hasn't yet come up, and
4028 		 * let link-monitoring (miimon) set it right when correct
4029 		 * speeds/duplex are available.
4030 		 */
4031 		if (bond_update_speed_duplex(slave) &&
4032 		    BOND_MODE(bond) == BOND_MODE_8023AD) {
4033 			if (slave->last_link_up)
4034 				slave->link = BOND_LINK_FAIL;
4035 			else
4036 				slave->link = BOND_LINK_DOWN;
4037 		}
4038 
4039 		if (BOND_MODE(bond) == BOND_MODE_8023AD)
4040 			bond_3ad_adapter_speed_duplex_changed(slave);
4041 		fallthrough;
4042 	case NETDEV_DOWN:
4043 		/* Refresh slave-array if applicable!
4044 		 * If the setup does not use miimon or arpmon (mode-specific!),
4045 		 * then these events will not cause the slave-array to be
4046 		 * refreshed. This will cause xmit to use a slave that is not
4047 		 * usable. Avoid such situation by refeshing the array at these
4048 		 * events. If these (miimon/arpmon) parameters are configured
4049 		 * then array gets refreshed twice and that should be fine!
4050 		 */
4051 		if (bond_mode_can_use_xmit_hash(bond))
4052 			bond_update_slave_arr(bond, NULL);
4053 		break;
4054 	case NETDEV_CHANGEMTU:
4055 		/* TODO: Should slaves be allowed to
4056 		 * independently alter their MTU?  For
4057 		 * an active-backup bond, slaves need
4058 		 * not be the same type of device, so
4059 		 * MTUs may vary.  For other modes,
4060 		 * slaves arguably should have the
4061 		 * same MTUs. To do this, we'd need to
4062 		 * take over the slave's change_mtu
4063 		 * function for the duration of their
4064 		 * servitude.
4065 		 */
4066 		break;
4067 	case NETDEV_CHANGENAME:
4068 		/* we don't care if we don't have primary set */
4069 		if (!bond_uses_primary(bond) ||
4070 		    !bond->params.primary[0])
4071 			break;
4072 
4073 		if (slave == primary) {
4074 			/* slave's name changed - he's no longer primary */
4075 			RCU_INIT_POINTER(bond->primary_slave, NULL);
4076 		} else if (!strcmp(slave_dev->name, bond->params.primary)) {
4077 			/* we have a new primary slave */
4078 			rcu_assign_pointer(bond->primary_slave, slave);
4079 		} else { /* we didn't change primary - exit */
4080 			break;
4081 		}
4082 
4083 		netdev_info(bond->dev, "Primary slave changed to %s, reselecting active slave\n",
4084 			    primary ? slave_dev->name : "none");
4085 
4086 		block_netpoll_tx();
4087 		bond_select_active_slave(bond);
4088 		unblock_netpoll_tx();
4089 		break;
4090 	case NETDEV_FEAT_CHANGE:
4091 		if (!bond->notifier_ctx) {
4092 			bond->notifier_ctx = true;
4093 			bond_compute_features(bond);
4094 			bond->notifier_ctx = false;
4095 		}
4096 		break;
4097 	case NETDEV_RESEND_IGMP:
4098 		/* Propagate to master device */
4099 		call_netdevice_notifiers(event, slave->bond->dev);
4100 		break;
4101 	case NETDEV_XDP_FEAT_CHANGE:
4102 		bond_xdp_set_features(bond_dev);
4103 		break;
4104 	default:
4105 		break;
4106 	}
4107 
4108 	return NOTIFY_DONE;
4109 }
4110 
4111 /* bond_netdev_event: handle netdev notifier chain events.
4112  *
4113  * This function receives events for the netdev chain.  The caller (an
4114  * ioctl handler calling blocking_notifier_call_chain) holds the necessary
4115  * locks for us to safely manipulate the slave devices (RTNL lock,
4116  * dev_probe_lock).
4117  */
4118 static int bond_netdev_event(struct notifier_block *this,
4119 			     unsigned long event, void *ptr)
4120 {
4121 	struct net_device *event_dev = netdev_notifier_info_to_dev(ptr);
4122 
4123 	netdev_dbg(event_dev, "%s received %s\n",
4124 		   __func__, netdev_cmd_to_name(event));
4125 
4126 	if (!(event_dev->priv_flags & IFF_BONDING))
4127 		return NOTIFY_DONE;
4128 
4129 	if (event_dev->flags & IFF_MASTER) {
4130 		int ret;
4131 
4132 		ret = bond_master_netdev_event(event, event_dev);
4133 		if (ret != NOTIFY_DONE)
4134 			return ret;
4135 	}
4136 
4137 	if (event_dev->flags & IFF_SLAVE)
4138 		return bond_slave_netdev_event(event, event_dev);
4139 
4140 	return NOTIFY_DONE;
4141 }
4142 
4143 static struct notifier_block bond_netdev_notifier = {
4144 	.notifier_call = bond_netdev_event,
4145 };
4146 
4147 /*---------------------------- Hashing Policies -----------------------------*/
4148 
4149 /* Helper to access data in a packet, with or without a backing skb.
4150  * If skb is given the data is linearized if necessary via pskb_may_pull.
4151  */
4152 static inline const void *bond_pull_data(struct sk_buff *skb,
4153 					 const void *data, int hlen, int n)
4154 {
4155 	if (likely(n <= hlen))
4156 		return data;
4157 	else if (skb && likely(pskb_may_pull(skb, n)))
4158 		return skb->data;
4159 
4160 	return NULL;
4161 }
4162 
4163 /* L2 hash helper */
4164 static inline u32 bond_eth_hash(struct sk_buff *skb, const void *data, int mhoff, int hlen)
4165 {
4166 	struct ethhdr *ep;
4167 
4168 	data = bond_pull_data(skb, data, hlen, mhoff + sizeof(struct ethhdr));
4169 	if (!data)
4170 		return 0;
4171 
4172 	ep = (struct ethhdr *)(data + mhoff);
4173 	return ep->h_dest[5] ^ ep->h_source[5] ^ be16_to_cpu(ep->h_proto);
4174 }
4175 
4176 static bool bond_flow_ip(struct sk_buff *skb, struct flow_keys *fk, const void *data,
4177 			 int hlen, __be16 l2_proto, int *nhoff, int *ip_proto, bool l34)
4178 {
4179 	const struct ipv6hdr *iph6;
4180 	const struct iphdr *iph;
4181 
4182 	if (l2_proto == htons(ETH_P_IP)) {
4183 		data = bond_pull_data(skb, data, hlen, *nhoff + sizeof(*iph));
4184 		if (!data)
4185 			return false;
4186 
4187 		iph = (const struct iphdr *)(data + *nhoff);
4188 		iph_to_flow_copy_v4addrs(fk, iph);
4189 		*nhoff += iph->ihl << 2;
4190 		if (!ip_is_fragment(iph))
4191 			*ip_proto = iph->protocol;
4192 	} else if (l2_proto == htons(ETH_P_IPV6)) {
4193 		data = bond_pull_data(skb, data, hlen, *nhoff + sizeof(*iph6));
4194 		if (!data)
4195 			return false;
4196 
4197 		iph6 = (const struct ipv6hdr *)(data + *nhoff);
4198 		iph_to_flow_copy_v6addrs(fk, iph6);
4199 		*nhoff += sizeof(*iph6);
4200 		*ip_proto = iph6->nexthdr;
4201 	} else {
4202 		return false;
4203 	}
4204 
4205 	if (l34 && *ip_proto >= 0)
4206 		fk->ports.ports = __skb_flow_get_ports(skb, *nhoff, *ip_proto, data, hlen);
4207 
4208 	return true;
4209 }
4210 
4211 static u32 bond_vlan_srcmac_hash(struct sk_buff *skb, const void *data, int mhoff, int hlen)
4212 {
4213 	u32 srcmac_vendor = 0, srcmac_dev = 0;
4214 	struct ethhdr *mac_hdr;
4215 	u16 vlan = 0;
4216 	int i;
4217 
4218 	data = bond_pull_data(skb, data, hlen, mhoff + sizeof(struct ethhdr));
4219 	if (!data)
4220 		return 0;
4221 	mac_hdr = (struct ethhdr *)(data + mhoff);
4222 
4223 	for (i = 0; i < 3; i++)
4224 		srcmac_vendor = (srcmac_vendor << 8) | mac_hdr->h_source[i];
4225 
4226 	for (i = 3; i < ETH_ALEN; i++)
4227 		srcmac_dev = (srcmac_dev << 8) | mac_hdr->h_source[i];
4228 
4229 	if (skb && skb_vlan_tag_present(skb))
4230 		vlan = skb_vlan_tag_get(skb);
4231 
4232 	return vlan ^ srcmac_vendor ^ srcmac_dev;
4233 }
4234 
4235 /* Extract the appropriate headers based on bond's xmit policy */
4236 static bool bond_flow_dissect(struct bonding *bond, struct sk_buff *skb, const void *data,
4237 			      __be16 l2_proto, int nhoff, int hlen, struct flow_keys *fk)
4238 {
4239 	bool l34 = bond->params.xmit_policy == BOND_XMIT_POLICY_LAYER34;
4240 	int ip_proto = -1;
4241 
4242 	switch (bond->params.xmit_policy) {
4243 	case BOND_XMIT_POLICY_ENCAP23:
4244 	case BOND_XMIT_POLICY_ENCAP34:
4245 		memset(fk, 0, sizeof(*fk));
4246 		return __skb_flow_dissect(NULL, skb, &flow_keys_bonding,
4247 					  fk, data, l2_proto, nhoff, hlen, 0);
4248 	default:
4249 		break;
4250 	}
4251 
4252 	fk->ports.ports = 0;
4253 	memset(&fk->icmp, 0, sizeof(fk->icmp));
4254 	if (!bond_flow_ip(skb, fk, data, hlen, l2_proto, &nhoff, &ip_proto, l34))
4255 		return false;
4256 
4257 	/* ICMP error packets contains at least 8 bytes of the header
4258 	 * of the packet which generated the error. Use this information
4259 	 * to correlate ICMP error packets within the same flow which
4260 	 * generated the error.
4261 	 */
4262 	if (ip_proto == IPPROTO_ICMP || ip_proto == IPPROTO_ICMPV6) {
4263 		skb_flow_get_icmp_tci(skb, &fk->icmp, data, nhoff, hlen);
4264 		if (ip_proto == IPPROTO_ICMP) {
4265 			if (!icmp_is_err(fk->icmp.type))
4266 				return true;
4267 
4268 			nhoff += sizeof(struct icmphdr);
4269 		} else if (ip_proto == IPPROTO_ICMPV6) {
4270 			if (!icmpv6_is_err(fk->icmp.type))
4271 				return true;
4272 
4273 			nhoff += sizeof(struct icmp6hdr);
4274 		}
4275 		return bond_flow_ip(skb, fk, data, hlen, l2_proto, &nhoff, &ip_proto, l34);
4276 	}
4277 
4278 	return true;
4279 }
4280 
4281 static u32 bond_ip_hash(u32 hash, struct flow_keys *flow, int xmit_policy)
4282 {
4283 	hash ^= (__force u32)flow_get_u32_dst(flow) ^
4284 		(__force u32)flow_get_u32_src(flow);
4285 	hash ^= (hash >> 16);
4286 	hash ^= (hash >> 8);
4287 
4288 	/* discard lowest hash bit to deal with the common even ports pattern */
4289 	if (xmit_policy == BOND_XMIT_POLICY_LAYER34 ||
4290 		xmit_policy == BOND_XMIT_POLICY_ENCAP34)
4291 		return hash >> 1;
4292 
4293 	return hash;
4294 }
4295 
4296 /* Generate hash based on xmit policy. If @skb is given it is used to linearize
4297  * the data as required, but this function can be used without it if the data is
4298  * known to be linear (e.g. with xdp_buff).
4299  */
4300 static u32 __bond_xmit_hash(struct bonding *bond, struct sk_buff *skb, const void *data,
4301 			    __be16 l2_proto, int mhoff, int nhoff, int hlen)
4302 {
4303 	struct flow_keys flow;
4304 	u32 hash;
4305 
4306 	if (bond->params.xmit_policy == BOND_XMIT_POLICY_VLAN_SRCMAC)
4307 		return bond_vlan_srcmac_hash(skb, data, mhoff, hlen);
4308 
4309 	if (bond->params.xmit_policy == BOND_XMIT_POLICY_LAYER2 ||
4310 	    !bond_flow_dissect(bond, skb, data, l2_proto, nhoff, hlen, &flow))
4311 		return bond_eth_hash(skb, data, mhoff, hlen);
4312 
4313 	if (bond->params.xmit_policy == BOND_XMIT_POLICY_LAYER23 ||
4314 	    bond->params.xmit_policy == BOND_XMIT_POLICY_ENCAP23) {
4315 		hash = bond_eth_hash(skb, data, mhoff, hlen);
4316 	} else {
4317 		if (flow.icmp.id)
4318 			memcpy(&hash, &flow.icmp, sizeof(hash));
4319 		else
4320 			memcpy(&hash, &flow.ports.ports, sizeof(hash));
4321 	}
4322 
4323 	return bond_ip_hash(hash, &flow, bond->params.xmit_policy);
4324 }
4325 
4326 /**
4327  * bond_xmit_hash - generate a hash value based on the xmit policy
4328  * @bond: bonding device
4329  * @skb: buffer to use for headers
4330  *
4331  * This function will extract the necessary headers from the skb buffer and use
4332  * them to generate a hash based on the xmit_policy set in the bonding device
4333  */
4334 u32 bond_xmit_hash(struct bonding *bond, struct sk_buff *skb)
4335 {
4336 	if (bond->params.xmit_policy == BOND_XMIT_POLICY_ENCAP34 &&
4337 	    skb->l4_hash)
4338 		return skb->hash;
4339 
4340 	return __bond_xmit_hash(bond, skb, skb->data, skb->protocol,
4341 				0, skb_network_offset(skb),
4342 				skb_headlen(skb));
4343 }
4344 
4345 /**
4346  * bond_xmit_hash_xdp - generate a hash value based on the xmit policy
4347  * @bond: bonding device
4348  * @xdp: buffer to use for headers
4349  *
4350  * The XDP variant of bond_xmit_hash.
4351  */
4352 static u32 bond_xmit_hash_xdp(struct bonding *bond, struct xdp_buff *xdp)
4353 {
4354 	struct ethhdr *eth;
4355 
4356 	if (xdp->data + sizeof(struct ethhdr) > xdp->data_end)
4357 		return 0;
4358 
4359 	eth = (struct ethhdr *)xdp->data;
4360 
4361 	return __bond_xmit_hash(bond, NULL, xdp->data, eth->h_proto, 0,
4362 				sizeof(struct ethhdr), xdp->data_end - xdp->data);
4363 }
4364 
4365 /*-------------------------- Device entry points ----------------------------*/
4366 
4367 void bond_work_init_all(struct bonding *bond)
4368 {
4369 	INIT_DELAYED_WORK(&bond->mcast_work,
4370 			  bond_resend_igmp_join_requests_delayed);
4371 	INIT_DELAYED_WORK(&bond->alb_work, bond_alb_monitor);
4372 	INIT_DELAYED_WORK(&bond->mii_work, bond_mii_monitor);
4373 	INIT_DELAYED_WORK(&bond->arp_work, bond_arp_monitor);
4374 	INIT_DELAYED_WORK(&bond->ad_work, bond_3ad_state_machine_handler);
4375 	INIT_DELAYED_WORK(&bond->slave_arr_work, bond_slave_arr_handler);
4376 }
4377 
4378 static void bond_work_cancel_all(struct bonding *bond)
4379 {
4380 	cancel_delayed_work_sync(&bond->mii_work);
4381 	cancel_delayed_work_sync(&bond->arp_work);
4382 	cancel_delayed_work_sync(&bond->alb_work);
4383 	cancel_delayed_work_sync(&bond->ad_work);
4384 	cancel_delayed_work_sync(&bond->mcast_work);
4385 	cancel_delayed_work_sync(&bond->slave_arr_work);
4386 }
4387 
4388 static int bond_open(struct net_device *bond_dev)
4389 {
4390 	struct bonding *bond = netdev_priv(bond_dev);
4391 	struct list_head *iter;
4392 	struct slave *slave;
4393 
4394 	if (BOND_MODE(bond) == BOND_MODE_ROUNDROBIN && !bond->rr_tx_counter) {
4395 		bond->rr_tx_counter = alloc_percpu(u32);
4396 		if (!bond->rr_tx_counter)
4397 			return -ENOMEM;
4398 	}
4399 
4400 	/* reset slave->backup and slave->inactive */
4401 	if (bond_has_slaves(bond)) {
4402 		bond_for_each_slave(bond, slave, iter) {
4403 			if (bond_uses_primary(bond) &&
4404 			    slave != rcu_access_pointer(bond->curr_active_slave)) {
4405 				bond_set_slave_inactive_flags(slave,
4406 							      BOND_SLAVE_NOTIFY_NOW);
4407 			} else if (BOND_MODE(bond) != BOND_MODE_8023AD) {
4408 				bond_set_slave_active_flags(slave,
4409 							    BOND_SLAVE_NOTIFY_NOW);
4410 			}
4411 		}
4412 	}
4413 
4414 	if (bond_is_lb(bond)) {
4415 		/* bond_alb_initialize must be called before the timer
4416 		 * is started.
4417 		 */
4418 		if (bond_alb_initialize(bond, (BOND_MODE(bond) == BOND_MODE_ALB)))
4419 			return -ENOMEM;
4420 		if (bond->params.tlb_dynamic_lb || BOND_MODE(bond) == BOND_MODE_ALB)
4421 			queue_delayed_work(bond->wq, &bond->alb_work, 0);
4422 	}
4423 
4424 	if (bond->params.miimon)  /* link check interval, in milliseconds. */
4425 		queue_delayed_work(bond->wq, &bond->mii_work, 0);
4426 
4427 	if (bond->params.arp_interval) {  /* arp interval, in milliseconds. */
4428 		queue_delayed_work(bond->wq, &bond->arp_work, 0);
4429 		bond->recv_probe = bond_rcv_validate;
4430 	}
4431 
4432 	if (BOND_MODE(bond) == BOND_MODE_8023AD) {
4433 		queue_delayed_work(bond->wq, &bond->ad_work, 0);
4434 		/* register to receive LACPDUs */
4435 		bond->recv_probe = bond_3ad_lacpdu_recv;
4436 		bond_3ad_initiate_agg_selection(bond, 1);
4437 
4438 		bond_for_each_slave(bond, slave, iter)
4439 			dev_mc_add(slave->dev, lacpdu_mcast_addr);
4440 	}
4441 
4442 	if (bond_mode_can_use_xmit_hash(bond))
4443 		bond_update_slave_arr(bond, NULL);
4444 
4445 	return 0;
4446 }
4447 
4448 static int bond_close(struct net_device *bond_dev)
4449 {
4450 	struct bonding *bond = netdev_priv(bond_dev);
4451 	struct slave *slave;
4452 
4453 	bond_work_cancel_all(bond);
4454 	bond->send_peer_notif = 0;
4455 	if (bond_is_lb(bond))
4456 		bond_alb_deinitialize(bond);
4457 	bond->recv_probe = NULL;
4458 
4459 	if (bond_uses_primary(bond)) {
4460 		rcu_read_lock();
4461 		slave = rcu_dereference(bond->curr_active_slave);
4462 		if (slave)
4463 			bond_hw_addr_flush(bond_dev, slave->dev);
4464 		rcu_read_unlock();
4465 	} else {
4466 		struct list_head *iter;
4467 
4468 		bond_for_each_slave(bond, slave, iter)
4469 			bond_hw_addr_flush(bond_dev, slave->dev);
4470 	}
4471 
4472 	return 0;
4473 }
4474 
4475 /* fold stats, assuming all rtnl_link_stats64 fields are u64, but
4476  * that some drivers can provide 32bit values only.
4477  */
4478 static void bond_fold_stats(struct rtnl_link_stats64 *_res,
4479 			    const struct rtnl_link_stats64 *_new,
4480 			    const struct rtnl_link_stats64 *_old)
4481 {
4482 	const u64 *new = (const u64 *)_new;
4483 	const u64 *old = (const u64 *)_old;
4484 	u64 *res = (u64 *)_res;
4485 	int i;
4486 
4487 	for (i = 0; i < sizeof(*_res) / sizeof(u64); i++) {
4488 		u64 nv = new[i];
4489 		u64 ov = old[i];
4490 		s64 delta = nv - ov;
4491 
4492 		/* detects if this particular field is 32bit only */
4493 		if (((nv | ov) >> 32) == 0)
4494 			delta = (s64)(s32)((u32)nv - (u32)ov);
4495 
4496 		/* filter anomalies, some drivers reset their stats
4497 		 * at down/up events.
4498 		 */
4499 		if (delta > 0)
4500 			res[i] += delta;
4501 	}
4502 }
4503 
4504 #ifdef CONFIG_LOCKDEP
4505 static int bond_get_lowest_level_rcu(struct net_device *dev)
4506 {
4507 	struct net_device *ldev, *next, *now, *dev_stack[MAX_NEST_DEV + 1];
4508 	struct list_head *niter, *iter, *iter_stack[MAX_NEST_DEV + 1];
4509 	int cur = 0, max = 0;
4510 
4511 	now = dev;
4512 	iter = &dev->adj_list.lower;
4513 
4514 	while (1) {
4515 		next = NULL;
4516 		while (1) {
4517 			ldev = netdev_next_lower_dev_rcu(now, &iter);
4518 			if (!ldev)
4519 				break;
4520 
4521 			next = ldev;
4522 			niter = &ldev->adj_list.lower;
4523 			dev_stack[cur] = now;
4524 			iter_stack[cur++] = iter;
4525 			if (max <= cur)
4526 				max = cur;
4527 			break;
4528 		}
4529 
4530 		if (!next) {
4531 			if (!cur)
4532 				return max;
4533 			next = dev_stack[--cur];
4534 			niter = iter_stack[cur];
4535 		}
4536 
4537 		now = next;
4538 		iter = niter;
4539 	}
4540 
4541 	return max;
4542 }
4543 #endif
4544 
4545 static void bond_get_stats(struct net_device *bond_dev,
4546 			   struct rtnl_link_stats64 *stats)
4547 {
4548 	struct bonding *bond = netdev_priv(bond_dev);
4549 	struct rtnl_link_stats64 temp;
4550 	struct list_head *iter;
4551 	struct slave *slave;
4552 	int nest_level = 0;
4553 
4554 
4555 	rcu_read_lock();
4556 #ifdef CONFIG_LOCKDEP
4557 	nest_level = bond_get_lowest_level_rcu(bond_dev);
4558 #endif
4559 
4560 	spin_lock_nested(&bond->stats_lock, nest_level);
4561 	memcpy(stats, &bond->bond_stats, sizeof(*stats));
4562 
4563 	bond_for_each_slave_rcu(bond, slave, iter) {
4564 		const struct rtnl_link_stats64 *new =
4565 			dev_get_stats(slave->dev, &temp);
4566 
4567 		bond_fold_stats(stats, new, &slave->slave_stats);
4568 
4569 		/* save off the slave stats for the next run */
4570 		memcpy(&slave->slave_stats, new, sizeof(*new));
4571 	}
4572 
4573 	memcpy(&bond->bond_stats, stats, sizeof(*stats));
4574 	spin_unlock(&bond->stats_lock);
4575 	rcu_read_unlock();
4576 }
4577 
4578 static int bond_eth_ioctl(struct net_device *bond_dev, struct ifreq *ifr, int cmd)
4579 {
4580 	struct bonding *bond = netdev_priv(bond_dev);
4581 	struct mii_ioctl_data *mii = NULL;
4582 
4583 	netdev_dbg(bond_dev, "bond_eth_ioctl: cmd=%d\n", cmd);
4584 
4585 	switch (cmd) {
4586 	case SIOCGMIIPHY:
4587 		mii = if_mii(ifr);
4588 		if (!mii)
4589 			return -EINVAL;
4590 
4591 		mii->phy_id = 0;
4592 		fallthrough;
4593 	case SIOCGMIIREG:
4594 		/* We do this again just in case we were called by SIOCGMIIREG
4595 		 * instead of SIOCGMIIPHY.
4596 		 */
4597 		mii = if_mii(ifr);
4598 		if (!mii)
4599 			return -EINVAL;
4600 
4601 		if (mii->reg_num == 1) {
4602 			mii->val_out = 0;
4603 			if (netif_carrier_ok(bond->dev))
4604 				mii->val_out = BMSR_LSTATUS;
4605 		}
4606 
4607 		break;
4608 	default:
4609 		return -EOPNOTSUPP;
4610 	}
4611 
4612 	return 0;
4613 }
4614 
4615 static int bond_do_ioctl(struct net_device *bond_dev, struct ifreq *ifr, int cmd)
4616 {
4617 	struct bonding *bond = netdev_priv(bond_dev);
4618 	struct net_device *slave_dev = NULL;
4619 	struct ifbond k_binfo;
4620 	struct ifbond __user *u_binfo = NULL;
4621 	struct ifslave k_sinfo;
4622 	struct ifslave __user *u_sinfo = NULL;
4623 	struct bond_opt_value newval;
4624 	struct net *net;
4625 	int res = 0;
4626 
4627 	netdev_dbg(bond_dev, "bond_ioctl: cmd=%d\n", cmd);
4628 
4629 	switch (cmd) {
4630 	case SIOCBONDINFOQUERY:
4631 		u_binfo = (struct ifbond __user *)ifr->ifr_data;
4632 
4633 		if (copy_from_user(&k_binfo, u_binfo, sizeof(ifbond)))
4634 			return -EFAULT;
4635 
4636 		bond_info_query(bond_dev, &k_binfo);
4637 		if (copy_to_user(u_binfo, &k_binfo, sizeof(ifbond)))
4638 			return -EFAULT;
4639 
4640 		return 0;
4641 	case SIOCBONDSLAVEINFOQUERY:
4642 		u_sinfo = (struct ifslave __user *)ifr->ifr_data;
4643 
4644 		if (copy_from_user(&k_sinfo, u_sinfo, sizeof(ifslave)))
4645 			return -EFAULT;
4646 
4647 		res = bond_slave_info_query(bond_dev, &k_sinfo);
4648 		if (res == 0 &&
4649 		    copy_to_user(u_sinfo, &k_sinfo, sizeof(ifslave)))
4650 			return -EFAULT;
4651 
4652 		return res;
4653 	default:
4654 		break;
4655 	}
4656 
4657 	net = dev_net(bond_dev);
4658 
4659 	if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
4660 		return -EPERM;
4661 
4662 	slave_dev = __dev_get_by_name(net, ifr->ifr_slave);
4663 
4664 	slave_dbg(bond_dev, slave_dev, "slave_dev=%p:\n", slave_dev);
4665 
4666 	if (!slave_dev)
4667 		return -ENODEV;
4668 
4669 	switch (cmd) {
4670 	case SIOCBONDENSLAVE:
4671 		res = bond_enslave(bond_dev, slave_dev, NULL);
4672 		break;
4673 	case SIOCBONDRELEASE:
4674 		res = bond_release(bond_dev, slave_dev);
4675 		break;
4676 	case SIOCBONDSETHWADDR:
4677 		res = bond_set_dev_addr(bond_dev, slave_dev);
4678 		break;
4679 	case SIOCBONDCHANGEACTIVE:
4680 		bond_opt_initstr(&newval, slave_dev->name);
4681 		res = __bond_opt_set_notify(bond, BOND_OPT_ACTIVE_SLAVE,
4682 					    &newval);
4683 		break;
4684 	default:
4685 		res = -EOPNOTSUPP;
4686 	}
4687 
4688 	return res;
4689 }
4690 
4691 static int bond_siocdevprivate(struct net_device *bond_dev, struct ifreq *ifr,
4692 			       void __user *data, int cmd)
4693 {
4694 	struct ifreq ifrdata = { .ifr_data = data };
4695 
4696 	switch (cmd) {
4697 	case BOND_INFO_QUERY_OLD:
4698 		return bond_do_ioctl(bond_dev, &ifrdata, SIOCBONDINFOQUERY);
4699 	case BOND_SLAVE_INFO_QUERY_OLD:
4700 		return bond_do_ioctl(bond_dev, &ifrdata, SIOCBONDSLAVEINFOQUERY);
4701 	case BOND_ENSLAVE_OLD:
4702 		return bond_do_ioctl(bond_dev, ifr, SIOCBONDENSLAVE);
4703 	case BOND_RELEASE_OLD:
4704 		return bond_do_ioctl(bond_dev, ifr, SIOCBONDRELEASE);
4705 	case BOND_SETHWADDR_OLD:
4706 		return bond_do_ioctl(bond_dev, ifr, SIOCBONDSETHWADDR);
4707 	case BOND_CHANGE_ACTIVE_OLD:
4708 		return bond_do_ioctl(bond_dev, ifr, SIOCBONDCHANGEACTIVE);
4709 	}
4710 
4711 	return -EOPNOTSUPP;
4712 }
4713 
4714 static void bond_change_rx_flags(struct net_device *bond_dev, int change)
4715 {
4716 	struct bonding *bond = netdev_priv(bond_dev);
4717 
4718 	if (change & IFF_PROMISC)
4719 		bond_set_promiscuity(bond,
4720 				     bond_dev->flags & IFF_PROMISC ? 1 : -1);
4721 
4722 	if (change & IFF_ALLMULTI)
4723 		bond_set_allmulti(bond,
4724 				  bond_dev->flags & IFF_ALLMULTI ? 1 : -1);
4725 }
4726 
4727 static void bond_set_rx_mode(struct net_device *bond_dev)
4728 {
4729 	struct bonding *bond = netdev_priv(bond_dev);
4730 	struct list_head *iter;
4731 	struct slave *slave;
4732 
4733 	rcu_read_lock();
4734 	if (bond_uses_primary(bond)) {
4735 		slave = rcu_dereference(bond->curr_active_slave);
4736 		if (slave) {
4737 			dev_uc_sync(slave->dev, bond_dev);
4738 			dev_mc_sync(slave->dev, bond_dev);
4739 		}
4740 	} else {
4741 		bond_for_each_slave_rcu(bond, slave, iter) {
4742 			dev_uc_sync_multiple(slave->dev, bond_dev);
4743 			dev_mc_sync_multiple(slave->dev, bond_dev);
4744 		}
4745 	}
4746 	rcu_read_unlock();
4747 }
4748 
4749 static int bond_neigh_init(struct neighbour *n)
4750 {
4751 	struct bonding *bond = netdev_priv(n->dev);
4752 	const struct net_device_ops *slave_ops;
4753 	struct neigh_parms parms;
4754 	struct slave *slave;
4755 	int ret = 0;
4756 
4757 	rcu_read_lock();
4758 	slave = bond_first_slave_rcu(bond);
4759 	if (!slave)
4760 		goto out;
4761 	slave_ops = slave->dev->netdev_ops;
4762 	if (!slave_ops->ndo_neigh_setup)
4763 		goto out;
4764 
4765 	/* TODO: find another way [1] to implement this.
4766 	 * Passing a zeroed structure is fragile,
4767 	 * but at least we do not pass garbage.
4768 	 *
4769 	 * [1] One way would be that ndo_neigh_setup() never touch
4770 	 *     struct neigh_parms, but propagate the new neigh_setup()
4771 	 *     back to ___neigh_create() / neigh_parms_alloc()
4772 	 */
4773 	memset(&parms, 0, sizeof(parms));
4774 	ret = slave_ops->ndo_neigh_setup(slave->dev, &parms);
4775 
4776 	if (ret)
4777 		goto out;
4778 
4779 	if (parms.neigh_setup)
4780 		ret = parms.neigh_setup(n);
4781 out:
4782 	rcu_read_unlock();
4783 	return ret;
4784 }
4785 
4786 /* The bonding ndo_neigh_setup is called at init time beofre any
4787  * slave exists. So we must declare proxy setup function which will
4788  * be used at run time to resolve the actual slave neigh param setup.
4789  *
4790  * It's also called by master devices (such as vlans) to setup their
4791  * underlying devices. In that case - do nothing, we're already set up from
4792  * our init.
4793  */
4794 static int bond_neigh_setup(struct net_device *dev,
4795 			    struct neigh_parms *parms)
4796 {
4797 	/* modify only our neigh_parms */
4798 	if (parms->dev == dev)
4799 		parms->neigh_setup = bond_neigh_init;
4800 
4801 	return 0;
4802 }
4803 
4804 /* Change the MTU of all of a master's slaves to match the master */
4805 static int bond_change_mtu(struct net_device *bond_dev, int new_mtu)
4806 {
4807 	struct bonding *bond = netdev_priv(bond_dev);
4808 	struct slave *slave, *rollback_slave;
4809 	struct list_head *iter;
4810 	int res = 0;
4811 
4812 	netdev_dbg(bond_dev, "bond=%p, new_mtu=%d\n", bond, new_mtu);
4813 
4814 	bond_for_each_slave(bond, slave, iter) {
4815 		slave_dbg(bond_dev, slave->dev, "s %p c_m %p\n",
4816 			   slave, slave->dev->netdev_ops->ndo_change_mtu);
4817 
4818 		res = dev_set_mtu(slave->dev, new_mtu);
4819 
4820 		if (res) {
4821 			/* If we failed to set the slave's mtu to the new value
4822 			 * we must abort the operation even in ACTIVE_BACKUP
4823 			 * mode, because if we allow the backup slaves to have
4824 			 * different mtu values than the active slave we'll
4825 			 * need to change their mtu when doing a failover. That
4826 			 * means changing their mtu from timer context, which
4827 			 * is probably not a good idea.
4828 			 */
4829 			slave_dbg(bond_dev, slave->dev, "err %d setting mtu to %d\n",
4830 				  res, new_mtu);
4831 			goto unwind;
4832 		}
4833 	}
4834 
4835 	WRITE_ONCE(bond_dev->mtu, new_mtu);
4836 
4837 	return 0;
4838 
4839 unwind:
4840 	/* unwind from head to the slave that failed */
4841 	bond_for_each_slave(bond, rollback_slave, iter) {
4842 		int tmp_res;
4843 
4844 		if (rollback_slave == slave)
4845 			break;
4846 
4847 		tmp_res = dev_set_mtu(rollback_slave->dev, bond_dev->mtu);
4848 		if (tmp_res)
4849 			slave_dbg(bond_dev, rollback_slave->dev, "unwind err %d\n",
4850 				  tmp_res);
4851 	}
4852 
4853 	return res;
4854 }
4855 
4856 /* Change HW address
4857  *
4858  * Note that many devices must be down to change the HW address, and
4859  * downing the master releases all slaves.  We can make bonds full of
4860  * bonding devices to test this, however.
4861  */
4862 static int bond_set_mac_address(struct net_device *bond_dev, void *addr)
4863 {
4864 	struct bonding *bond = netdev_priv(bond_dev);
4865 	struct slave *slave, *rollback_slave;
4866 	struct sockaddr_storage *ss = addr, tmp_ss;
4867 	struct list_head *iter;
4868 	int res = 0;
4869 
4870 	if (BOND_MODE(bond) == BOND_MODE_ALB)
4871 		return bond_alb_set_mac_address(bond_dev, addr);
4872 
4873 
4874 	netdev_dbg(bond_dev, "%s: bond=%p\n", __func__, bond);
4875 
4876 	/* If fail_over_mac is enabled, do nothing and return success.
4877 	 * Returning an error causes ifenslave to fail.
4878 	 */
4879 	if (bond->params.fail_over_mac &&
4880 	    BOND_MODE(bond) == BOND_MODE_ACTIVEBACKUP)
4881 		return 0;
4882 
4883 	if (!is_valid_ether_addr(ss->__data))
4884 		return -EADDRNOTAVAIL;
4885 
4886 	bond_for_each_slave(bond, slave, iter) {
4887 		slave_dbg(bond_dev, slave->dev, "%s: slave=%p\n",
4888 			  __func__, slave);
4889 		res = dev_set_mac_address(slave->dev, addr, NULL);
4890 		if (res) {
4891 			/* TODO: consider downing the slave
4892 			 * and retry ?
4893 			 * User should expect communications
4894 			 * breakage anyway until ARP finish
4895 			 * updating, so...
4896 			 */
4897 			slave_dbg(bond_dev, slave->dev, "%s: err %d\n",
4898 				  __func__, res);
4899 			goto unwind;
4900 		}
4901 	}
4902 
4903 	/* success */
4904 	dev_addr_set(bond_dev, ss->__data);
4905 	return 0;
4906 
4907 unwind:
4908 	memcpy(tmp_ss.__data, bond_dev->dev_addr, bond_dev->addr_len);
4909 	tmp_ss.ss_family = bond_dev->type;
4910 
4911 	/* unwind from head to the slave that failed */
4912 	bond_for_each_slave(bond, rollback_slave, iter) {
4913 		int tmp_res;
4914 
4915 		if (rollback_slave == slave)
4916 			break;
4917 
4918 		tmp_res = dev_set_mac_address(rollback_slave->dev,
4919 					      (struct sockaddr *)&tmp_ss, NULL);
4920 		if (tmp_res) {
4921 			slave_dbg(bond_dev, rollback_slave->dev, "%s: unwind err %d\n",
4922 				   __func__, tmp_res);
4923 		}
4924 	}
4925 
4926 	return res;
4927 }
4928 
4929 /**
4930  * bond_get_slave_by_id - get xmit slave with slave_id
4931  * @bond: bonding device that is transmitting
4932  * @slave_id: slave id up to slave_cnt-1 through which to transmit
4933  *
4934  * This function tries to get slave with slave_id but in case
4935  * it fails, it tries to find the first available slave for transmission.
4936  */
4937 static struct slave *bond_get_slave_by_id(struct bonding *bond,
4938 					  int slave_id)
4939 {
4940 	struct list_head *iter;
4941 	struct slave *slave;
4942 	int i = slave_id;
4943 
4944 	/* Here we start from the slave with slave_id */
4945 	bond_for_each_slave_rcu(bond, slave, iter) {
4946 		if (--i < 0) {
4947 			if (bond_slave_can_tx(slave))
4948 				return slave;
4949 		}
4950 	}
4951 
4952 	/* Here we start from the first slave up to slave_id */
4953 	i = slave_id;
4954 	bond_for_each_slave_rcu(bond, slave, iter) {
4955 		if (--i < 0)
4956 			break;
4957 		if (bond_slave_can_tx(slave))
4958 			return slave;
4959 	}
4960 	/* no slave that can tx has been found */
4961 	return NULL;
4962 }
4963 
4964 /**
4965  * bond_rr_gen_slave_id - generate slave id based on packets_per_slave
4966  * @bond: bonding device to use
4967  *
4968  * Based on the value of the bonding device's packets_per_slave parameter
4969  * this function generates a slave id, which is usually used as the next
4970  * slave to transmit through.
4971  */
4972 static u32 bond_rr_gen_slave_id(struct bonding *bond)
4973 {
4974 	u32 slave_id;
4975 	struct reciprocal_value reciprocal_packets_per_slave;
4976 	int packets_per_slave = bond->params.packets_per_slave;
4977 
4978 	switch (packets_per_slave) {
4979 	case 0:
4980 		slave_id = get_random_u32();
4981 		break;
4982 	case 1:
4983 		slave_id = this_cpu_inc_return(*bond->rr_tx_counter);
4984 		break;
4985 	default:
4986 		reciprocal_packets_per_slave =
4987 			bond->params.reciprocal_packets_per_slave;
4988 		slave_id = this_cpu_inc_return(*bond->rr_tx_counter);
4989 		slave_id = reciprocal_divide(slave_id,
4990 					     reciprocal_packets_per_slave);
4991 		break;
4992 	}
4993 
4994 	return slave_id;
4995 }
4996 
4997 static struct slave *bond_xmit_roundrobin_slave_get(struct bonding *bond,
4998 						    struct sk_buff *skb)
4999 {
5000 	struct slave *slave;
5001 	int slave_cnt;
5002 	u32 slave_id;
5003 
5004 	/* Start with the curr_active_slave that joined the bond as the
5005 	 * default for sending IGMP traffic.  For failover purposes one
5006 	 * needs to maintain some consistency for the interface that will
5007 	 * send the join/membership reports.  The curr_active_slave found
5008 	 * will send all of this type of traffic.
5009 	 */
5010 	if (skb->protocol == htons(ETH_P_IP)) {
5011 		int noff = skb_network_offset(skb);
5012 		struct iphdr *iph;
5013 
5014 		if (unlikely(!pskb_may_pull(skb, noff + sizeof(*iph))))
5015 			goto non_igmp;
5016 
5017 		iph = ip_hdr(skb);
5018 		if (iph->protocol == IPPROTO_IGMP) {
5019 			slave = rcu_dereference(bond->curr_active_slave);
5020 			if (slave)
5021 				return slave;
5022 			return bond_get_slave_by_id(bond, 0);
5023 		}
5024 	}
5025 
5026 non_igmp:
5027 	slave_cnt = READ_ONCE(bond->slave_cnt);
5028 	if (likely(slave_cnt)) {
5029 		slave_id = bond_rr_gen_slave_id(bond) % slave_cnt;
5030 		return bond_get_slave_by_id(bond, slave_id);
5031 	}
5032 	return NULL;
5033 }
5034 
5035 static struct slave *bond_xdp_xmit_roundrobin_slave_get(struct bonding *bond,
5036 							struct xdp_buff *xdp)
5037 {
5038 	struct slave *slave;
5039 	int slave_cnt;
5040 	u32 slave_id;
5041 	const struct ethhdr *eth;
5042 	void *data = xdp->data;
5043 
5044 	if (data + sizeof(struct ethhdr) > xdp->data_end)
5045 		goto non_igmp;
5046 
5047 	eth = (struct ethhdr *)data;
5048 	data += sizeof(struct ethhdr);
5049 
5050 	/* See comment on IGMP in bond_xmit_roundrobin_slave_get() */
5051 	if (eth->h_proto == htons(ETH_P_IP)) {
5052 		const struct iphdr *iph;
5053 
5054 		if (data + sizeof(struct iphdr) > xdp->data_end)
5055 			goto non_igmp;
5056 
5057 		iph = (struct iphdr *)data;
5058 
5059 		if (iph->protocol == IPPROTO_IGMP) {
5060 			slave = rcu_dereference(bond->curr_active_slave);
5061 			if (slave)
5062 				return slave;
5063 			return bond_get_slave_by_id(bond, 0);
5064 		}
5065 	}
5066 
5067 non_igmp:
5068 	slave_cnt = READ_ONCE(bond->slave_cnt);
5069 	if (likely(slave_cnt)) {
5070 		slave_id = bond_rr_gen_slave_id(bond) % slave_cnt;
5071 		return bond_get_slave_by_id(bond, slave_id);
5072 	}
5073 	return NULL;
5074 }
5075 
5076 static netdev_tx_t bond_xmit_roundrobin(struct sk_buff *skb,
5077 					struct net_device *bond_dev)
5078 {
5079 	struct bonding *bond = netdev_priv(bond_dev);
5080 	struct slave *slave;
5081 
5082 	slave = bond_xmit_roundrobin_slave_get(bond, skb);
5083 	if (likely(slave))
5084 		return bond_dev_queue_xmit(bond, skb, slave->dev);
5085 
5086 	return bond_tx_drop(bond_dev, skb);
5087 }
5088 
5089 static struct slave *bond_xmit_activebackup_slave_get(struct bonding *bond)
5090 {
5091 	return rcu_dereference(bond->curr_active_slave);
5092 }
5093 
5094 /* In active-backup mode, we know that bond->curr_active_slave is always valid if
5095  * the bond has a usable interface.
5096  */
5097 static netdev_tx_t bond_xmit_activebackup(struct sk_buff *skb,
5098 					  struct net_device *bond_dev)
5099 {
5100 	struct bonding *bond = netdev_priv(bond_dev);
5101 	struct slave *slave;
5102 
5103 	slave = bond_xmit_activebackup_slave_get(bond);
5104 	if (slave)
5105 		return bond_dev_queue_xmit(bond, skb, slave->dev);
5106 
5107 	return bond_tx_drop(bond_dev, skb);
5108 }
5109 
5110 /* Use this to update slave_array when (a) it's not appropriate to update
5111  * slave_array right away (note that update_slave_array() may sleep)
5112  * and / or (b) RTNL is not held.
5113  */
5114 void bond_slave_arr_work_rearm(struct bonding *bond, unsigned long delay)
5115 {
5116 	queue_delayed_work(bond->wq, &bond->slave_arr_work, delay);
5117 }
5118 
5119 /* Slave array work handler. Holds only RTNL */
5120 static void bond_slave_arr_handler(struct work_struct *work)
5121 {
5122 	struct bonding *bond = container_of(work, struct bonding,
5123 					    slave_arr_work.work);
5124 	int ret;
5125 
5126 	if (!rtnl_trylock())
5127 		goto err;
5128 
5129 	ret = bond_update_slave_arr(bond, NULL);
5130 	rtnl_unlock();
5131 	if (ret) {
5132 		pr_warn_ratelimited("Failed to update slave array from WT\n");
5133 		goto err;
5134 	}
5135 	return;
5136 
5137 err:
5138 	bond_slave_arr_work_rearm(bond, 1);
5139 }
5140 
5141 static void bond_skip_slave(struct bond_up_slave *slaves,
5142 			    struct slave *skipslave)
5143 {
5144 	int idx;
5145 
5146 	/* Rare situation where caller has asked to skip a specific
5147 	 * slave but allocation failed (most likely!). BTW this is
5148 	 * only possible when the call is initiated from
5149 	 * __bond_release_one(). In this situation; overwrite the
5150 	 * skipslave entry in the array with the last entry from the
5151 	 * array to avoid a situation where the xmit path may choose
5152 	 * this to-be-skipped slave to send a packet out.
5153 	 */
5154 	for (idx = 0; slaves && idx < slaves->count; idx++) {
5155 		if (skipslave == slaves->arr[idx]) {
5156 			slaves->arr[idx] =
5157 				slaves->arr[slaves->count - 1];
5158 			slaves->count--;
5159 			break;
5160 		}
5161 	}
5162 }
5163 
5164 static void bond_set_slave_arr(struct bonding *bond,
5165 			       struct bond_up_slave *usable_slaves,
5166 			       struct bond_up_slave *all_slaves)
5167 {
5168 	struct bond_up_slave *usable, *all;
5169 
5170 	usable = rtnl_dereference(bond->usable_slaves);
5171 	rcu_assign_pointer(bond->usable_slaves, usable_slaves);
5172 	kfree_rcu(usable, rcu);
5173 
5174 	all = rtnl_dereference(bond->all_slaves);
5175 	rcu_assign_pointer(bond->all_slaves, all_slaves);
5176 	kfree_rcu(all, rcu);
5177 }
5178 
5179 static void bond_reset_slave_arr(struct bonding *bond)
5180 {
5181 	bond_set_slave_arr(bond, NULL, NULL);
5182 }
5183 
5184 /* Build the usable slaves array in control path for modes that use xmit-hash
5185  * to determine the slave interface -
5186  * (a) BOND_MODE_8023AD
5187  * (b) BOND_MODE_XOR
5188  * (c) (BOND_MODE_TLB || BOND_MODE_ALB) && tlb_dynamic_lb == 0
5189  *
5190  * The caller is expected to hold RTNL only and NO other lock!
5191  */
5192 int bond_update_slave_arr(struct bonding *bond, struct slave *skipslave)
5193 {
5194 	struct bond_up_slave *usable_slaves = NULL, *all_slaves = NULL;
5195 	struct slave *slave;
5196 	struct list_head *iter;
5197 	int agg_id = 0;
5198 	int ret = 0;
5199 
5200 	might_sleep();
5201 
5202 	usable_slaves = kzalloc(struct_size(usable_slaves, arr,
5203 					    bond->slave_cnt), GFP_KERNEL);
5204 	all_slaves = kzalloc(struct_size(all_slaves, arr,
5205 					 bond->slave_cnt), GFP_KERNEL);
5206 	if (!usable_slaves || !all_slaves) {
5207 		ret = -ENOMEM;
5208 		goto out;
5209 	}
5210 	if (BOND_MODE(bond) == BOND_MODE_8023AD) {
5211 		struct ad_info ad_info;
5212 
5213 		spin_lock_bh(&bond->mode_lock);
5214 		if (bond_3ad_get_active_agg_info(bond, &ad_info)) {
5215 			spin_unlock_bh(&bond->mode_lock);
5216 			pr_debug("bond_3ad_get_active_agg_info failed\n");
5217 			/* No active aggragator means it's not safe to use
5218 			 * the previous array.
5219 			 */
5220 			bond_reset_slave_arr(bond);
5221 			goto out;
5222 		}
5223 		spin_unlock_bh(&bond->mode_lock);
5224 		agg_id = ad_info.aggregator_id;
5225 	}
5226 	bond_for_each_slave(bond, slave, iter) {
5227 		if (skipslave == slave)
5228 			continue;
5229 
5230 		all_slaves->arr[all_slaves->count++] = slave;
5231 		if (BOND_MODE(bond) == BOND_MODE_8023AD) {
5232 			struct aggregator *agg;
5233 
5234 			agg = SLAVE_AD_INFO(slave)->port.aggregator;
5235 			if (!agg || agg->aggregator_identifier != agg_id)
5236 				continue;
5237 		}
5238 		if (!bond_slave_can_tx(slave))
5239 			continue;
5240 
5241 		slave_dbg(bond->dev, slave->dev, "Adding slave to tx hash array[%d]\n",
5242 			  usable_slaves->count);
5243 
5244 		usable_slaves->arr[usable_slaves->count++] = slave;
5245 	}
5246 
5247 	bond_set_slave_arr(bond, usable_slaves, all_slaves);
5248 	return ret;
5249 out:
5250 	if (ret != 0 && skipslave) {
5251 		bond_skip_slave(rtnl_dereference(bond->all_slaves),
5252 				skipslave);
5253 		bond_skip_slave(rtnl_dereference(bond->usable_slaves),
5254 				skipslave);
5255 	}
5256 	kfree_rcu(all_slaves, rcu);
5257 	kfree_rcu(usable_slaves, rcu);
5258 
5259 	return ret;
5260 }
5261 
5262 static struct slave *bond_xmit_3ad_xor_slave_get(struct bonding *bond,
5263 						 struct sk_buff *skb,
5264 						 struct bond_up_slave *slaves)
5265 {
5266 	struct slave *slave;
5267 	unsigned int count;
5268 	u32 hash;
5269 
5270 	hash = bond_xmit_hash(bond, skb);
5271 	count = slaves ? READ_ONCE(slaves->count) : 0;
5272 	if (unlikely(!count))
5273 		return NULL;
5274 
5275 	slave = slaves->arr[hash % count];
5276 	return slave;
5277 }
5278 
5279 static struct slave *bond_xdp_xmit_3ad_xor_slave_get(struct bonding *bond,
5280 						     struct xdp_buff *xdp)
5281 {
5282 	struct bond_up_slave *slaves;
5283 	unsigned int count;
5284 	u32 hash;
5285 
5286 	hash = bond_xmit_hash_xdp(bond, xdp);
5287 	slaves = rcu_dereference(bond->usable_slaves);
5288 	count = slaves ? READ_ONCE(slaves->count) : 0;
5289 	if (unlikely(!count))
5290 		return NULL;
5291 
5292 	return slaves->arr[hash % count];
5293 }
5294 
5295 /* Use this Xmit function for 3AD as well as XOR modes. The current
5296  * usable slave array is formed in the control path. The xmit function
5297  * just calculates hash and sends the packet out.
5298  */
5299 static netdev_tx_t bond_3ad_xor_xmit(struct sk_buff *skb,
5300 				     struct net_device *dev)
5301 {
5302 	struct bonding *bond = netdev_priv(dev);
5303 	struct bond_up_slave *slaves;
5304 	struct slave *slave;
5305 
5306 	slaves = rcu_dereference(bond->usable_slaves);
5307 	slave = bond_xmit_3ad_xor_slave_get(bond, skb, slaves);
5308 	if (likely(slave))
5309 		return bond_dev_queue_xmit(bond, skb, slave->dev);
5310 
5311 	return bond_tx_drop(dev, skb);
5312 }
5313 
5314 /* in broadcast mode, we send everything to all usable interfaces. */
5315 static netdev_tx_t bond_xmit_broadcast(struct sk_buff *skb,
5316 				       struct net_device *bond_dev)
5317 {
5318 	struct bonding *bond = netdev_priv(bond_dev);
5319 	struct slave *slave = NULL;
5320 	struct list_head *iter;
5321 	bool xmit_suc = false;
5322 	bool skb_used = false;
5323 
5324 	bond_for_each_slave_rcu(bond, slave, iter) {
5325 		struct sk_buff *skb2;
5326 
5327 		if (!(bond_slave_is_up(slave) && slave->link == BOND_LINK_UP))
5328 			continue;
5329 
5330 		if (bond_is_last_slave(bond, slave)) {
5331 			skb2 = skb;
5332 			skb_used = true;
5333 		} else {
5334 			skb2 = skb_clone(skb, GFP_ATOMIC);
5335 			if (!skb2) {
5336 				net_err_ratelimited("%s: Error: %s: skb_clone() failed\n",
5337 						    bond_dev->name, __func__);
5338 				continue;
5339 			}
5340 		}
5341 
5342 		if (bond_dev_queue_xmit(bond, skb2, slave->dev) == NETDEV_TX_OK)
5343 			xmit_suc = true;
5344 	}
5345 
5346 	if (!skb_used)
5347 		dev_kfree_skb_any(skb);
5348 
5349 	if (xmit_suc)
5350 		return NETDEV_TX_OK;
5351 
5352 	dev_core_stats_tx_dropped_inc(bond_dev);
5353 	return NET_XMIT_DROP;
5354 }
5355 
5356 /*------------------------- Device initialization ---------------------------*/
5357 
5358 /* Lookup the slave that corresponds to a qid */
5359 static inline int bond_slave_override(struct bonding *bond,
5360 				      struct sk_buff *skb)
5361 {
5362 	struct slave *slave = NULL;
5363 	struct list_head *iter;
5364 
5365 	if (!skb_rx_queue_recorded(skb))
5366 		return 1;
5367 
5368 	/* Find out if any slaves have the same mapping as this skb. */
5369 	bond_for_each_slave_rcu(bond, slave, iter) {
5370 		if (READ_ONCE(slave->queue_id) == skb_get_queue_mapping(skb)) {
5371 			if (bond_slave_is_up(slave) &&
5372 			    slave->link == BOND_LINK_UP) {
5373 				bond_dev_queue_xmit(bond, skb, slave->dev);
5374 				return 0;
5375 			}
5376 			/* If the slave isn't UP, use default transmit policy. */
5377 			break;
5378 		}
5379 	}
5380 
5381 	return 1;
5382 }
5383 
5384 
5385 static u16 bond_select_queue(struct net_device *dev, struct sk_buff *skb,
5386 			     struct net_device *sb_dev)
5387 {
5388 	/* This helper function exists to help dev_pick_tx get the correct
5389 	 * destination queue.  Using a helper function skips a call to
5390 	 * skb_tx_hash and will put the skbs in the queue we expect on their
5391 	 * way down to the bonding driver.
5392 	 */
5393 	u16 txq = skb_rx_queue_recorded(skb) ? skb_get_rx_queue(skb) : 0;
5394 
5395 	/* Save the original txq to restore before passing to the driver */
5396 	qdisc_skb_cb(skb)->slave_dev_queue_mapping = skb_get_queue_mapping(skb);
5397 
5398 	if (unlikely(txq >= dev->real_num_tx_queues)) {
5399 		do {
5400 			txq -= dev->real_num_tx_queues;
5401 		} while (txq >= dev->real_num_tx_queues);
5402 	}
5403 	return txq;
5404 }
5405 
5406 static struct net_device *bond_xmit_get_slave(struct net_device *master_dev,
5407 					      struct sk_buff *skb,
5408 					      bool all_slaves)
5409 {
5410 	struct bonding *bond = netdev_priv(master_dev);
5411 	struct bond_up_slave *slaves;
5412 	struct slave *slave = NULL;
5413 
5414 	switch (BOND_MODE(bond)) {
5415 	case BOND_MODE_ROUNDROBIN:
5416 		slave = bond_xmit_roundrobin_slave_get(bond, skb);
5417 		break;
5418 	case BOND_MODE_ACTIVEBACKUP:
5419 		slave = bond_xmit_activebackup_slave_get(bond);
5420 		break;
5421 	case BOND_MODE_8023AD:
5422 	case BOND_MODE_XOR:
5423 		if (all_slaves)
5424 			slaves = rcu_dereference(bond->all_slaves);
5425 		else
5426 			slaves = rcu_dereference(bond->usable_slaves);
5427 		slave = bond_xmit_3ad_xor_slave_get(bond, skb, slaves);
5428 		break;
5429 	case BOND_MODE_BROADCAST:
5430 		break;
5431 	case BOND_MODE_ALB:
5432 		slave = bond_xmit_alb_slave_get(bond, skb);
5433 		break;
5434 	case BOND_MODE_TLB:
5435 		slave = bond_xmit_tlb_slave_get(bond, skb);
5436 		break;
5437 	default:
5438 		/* Should never happen, mode already checked */
5439 		WARN_ONCE(true, "Unknown bonding mode");
5440 		break;
5441 	}
5442 
5443 	if (slave)
5444 		return slave->dev;
5445 	return NULL;
5446 }
5447 
5448 static void bond_sk_to_flow(struct sock *sk, struct flow_keys *flow)
5449 {
5450 	switch (sk->sk_family) {
5451 #if IS_ENABLED(CONFIG_IPV6)
5452 	case AF_INET6:
5453 		if (ipv6_only_sock(sk) ||
5454 		    ipv6_addr_type(&sk->sk_v6_daddr) != IPV6_ADDR_MAPPED) {
5455 			flow->control.addr_type = FLOW_DISSECTOR_KEY_IPV6_ADDRS;
5456 			flow->addrs.v6addrs.src = inet6_sk(sk)->saddr;
5457 			flow->addrs.v6addrs.dst = sk->sk_v6_daddr;
5458 			break;
5459 		}
5460 		fallthrough;
5461 #endif
5462 	default: /* AF_INET */
5463 		flow->control.addr_type = FLOW_DISSECTOR_KEY_IPV4_ADDRS;
5464 		flow->addrs.v4addrs.src = inet_sk(sk)->inet_rcv_saddr;
5465 		flow->addrs.v4addrs.dst = inet_sk(sk)->inet_daddr;
5466 		break;
5467 	}
5468 
5469 	flow->ports.src = inet_sk(sk)->inet_sport;
5470 	flow->ports.dst = inet_sk(sk)->inet_dport;
5471 }
5472 
5473 /**
5474  * bond_sk_hash_l34 - generate a hash value based on the socket's L3 and L4 fields
5475  * @sk: socket to use for headers
5476  *
5477  * This function will extract the necessary field from the socket and use
5478  * them to generate a hash based on the LAYER34 xmit_policy.
5479  * Assumes that sk is a TCP or UDP socket.
5480  */
5481 static u32 bond_sk_hash_l34(struct sock *sk)
5482 {
5483 	struct flow_keys flow;
5484 	u32 hash;
5485 
5486 	bond_sk_to_flow(sk, &flow);
5487 
5488 	/* L4 */
5489 	memcpy(&hash, &flow.ports.ports, sizeof(hash));
5490 	/* L3 */
5491 	return bond_ip_hash(hash, &flow, BOND_XMIT_POLICY_LAYER34);
5492 }
5493 
5494 static struct net_device *__bond_sk_get_lower_dev(struct bonding *bond,
5495 						  struct sock *sk)
5496 {
5497 	struct bond_up_slave *slaves;
5498 	struct slave *slave;
5499 	unsigned int count;
5500 	u32 hash;
5501 
5502 	slaves = rcu_dereference(bond->usable_slaves);
5503 	count = slaves ? READ_ONCE(slaves->count) : 0;
5504 	if (unlikely(!count))
5505 		return NULL;
5506 
5507 	hash = bond_sk_hash_l34(sk);
5508 	slave = slaves->arr[hash % count];
5509 
5510 	return slave->dev;
5511 }
5512 
5513 static struct net_device *bond_sk_get_lower_dev(struct net_device *dev,
5514 						struct sock *sk)
5515 {
5516 	struct bonding *bond = netdev_priv(dev);
5517 	struct net_device *lower = NULL;
5518 
5519 	rcu_read_lock();
5520 	if (bond_sk_check(bond))
5521 		lower = __bond_sk_get_lower_dev(bond, sk);
5522 	rcu_read_unlock();
5523 
5524 	return lower;
5525 }
5526 
5527 #if IS_ENABLED(CONFIG_TLS_DEVICE)
5528 static netdev_tx_t bond_tls_device_xmit(struct bonding *bond, struct sk_buff *skb,
5529 					struct net_device *dev)
5530 {
5531 	struct net_device *tls_netdev = rcu_dereference(tls_get_ctx(skb->sk)->netdev);
5532 
5533 	/* tls_netdev might become NULL, even if tls_is_skb_tx_device_offloaded
5534 	 * was true, if tls_device_down is running in parallel, but it's OK,
5535 	 * because bond_get_slave_by_dev has a NULL check.
5536 	 */
5537 	if (likely(bond_get_slave_by_dev(bond, tls_netdev)))
5538 		return bond_dev_queue_xmit(bond, skb, tls_netdev);
5539 	return bond_tx_drop(dev, skb);
5540 }
5541 #endif
5542 
5543 static netdev_tx_t __bond_start_xmit(struct sk_buff *skb, struct net_device *dev)
5544 {
5545 	struct bonding *bond = netdev_priv(dev);
5546 
5547 	if (bond_should_override_tx_queue(bond) &&
5548 	    !bond_slave_override(bond, skb))
5549 		return NETDEV_TX_OK;
5550 
5551 #if IS_ENABLED(CONFIG_TLS_DEVICE)
5552 	if (tls_is_skb_tx_device_offloaded(skb))
5553 		return bond_tls_device_xmit(bond, skb, dev);
5554 #endif
5555 
5556 	switch (BOND_MODE(bond)) {
5557 	case BOND_MODE_ROUNDROBIN:
5558 		return bond_xmit_roundrobin(skb, dev);
5559 	case BOND_MODE_ACTIVEBACKUP:
5560 		return bond_xmit_activebackup(skb, dev);
5561 	case BOND_MODE_8023AD:
5562 	case BOND_MODE_XOR:
5563 		return bond_3ad_xor_xmit(skb, dev);
5564 	case BOND_MODE_BROADCAST:
5565 		return bond_xmit_broadcast(skb, dev);
5566 	case BOND_MODE_ALB:
5567 		return bond_alb_xmit(skb, dev);
5568 	case BOND_MODE_TLB:
5569 		return bond_tlb_xmit(skb, dev);
5570 	default:
5571 		/* Should never happen, mode already checked */
5572 		netdev_err(dev, "Unknown bonding mode %d\n", BOND_MODE(bond));
5573 		WARN_ON_ONCE(1);
5574 		return bond_tx_drop(dev, skb);
5575 	}
5576 }
5577 
5578 static netdev_tx_t bond_start_xmit(struct sk_buff *skb, struct net_device *dev)
5579 {
5580 	struct bonding *bond = netdev_priv(dev);
5581 	netdev_tx_t ret = NETDEV_TX_OK;
5582 
5583 	/* If we risk deadlock from transmitting this in the
5584 	 * netpoll path, tell netpoll to queue the frame for later tx
5585 	 */
5586 	if (unlikely(is_netpoll_tx_blocked(dev)))
5587 		return NETDEV_TX_BUSY;
5588 
5589 	rcu_read_lock();
5590 	if (bond_has_slaves(bond))
5591 		ret = __bond_start_xmit(skb, dev);
5592 	else
5593 		ret = bond_tx_drop(dev, skb);
5594 	rcu_read_unlock();
5595 
5596 	return ret;
5597 }
5598 
5599 static struct net_device *
5600 bond_xdp_get_xmit_slave(struct net_device *bond_dev, struct xdp_buff *xdp)
5601 {
5602 	struct bonding *bond = netdev_priv(bond_dev);
5603 	struct slave *slave;
5604 
5605 	/* Caller needs to hold rcu_read_lock() */
5606 
5607 	switch (BOND_MODE(bond)) {
5608 	case BOND_MODE_ROUNDROBIN:
5609 		slave = bond_xdp_xmit_roundrobin_slave_get(bond, xdp);
5610 		break;
5611 
5612 	case BOND_MODE_ACTIVEBACKUP:
5613 		slave = bond_xmit_activebackup_slave_get(bond);
5614 		break;
5615 
5616 	case BOND_MODE_8023AD:
5617 	case BOND_MODE_XOR:
5618 		slave = bond_xdp_xmit_3ad_xor_slave_get(bond, xdp);
5619 		break;
5620 
5621 	default:
5622 		if (net_ratelimit())
5623 			netdev_err(bond_dev, "Unknown bonding mode %d for xdp xmit\n",
5624 				   BOND_MODE(bond));
5625 		return NULL;
5626 	}
5627 
5628 	if (slave)
5629 		return slave->dev;
5630 
5631 	return NULL;
5632 }
5633 
5634 static int bond_xdp_xmit(struct net_device *bond_dev,
5635 			 int n, struct xdp_frame **frames, u32 flags)
5636 {
5637 	int nxmit, err = -ENXIO;
5638 
5639 	rcu_read_lock();
5640 
5641 	for (nxmit = 0; nxmit < n; nxmit++) {
5642 		struct xdp_frame *frame = frames[nxmit];
5643 		struct xdp_frame *frames1[] = {frame};
5644 		struct net_device *slave_dev;
5645 		struct xdp_buff xdp;
5646 
5647 		xdp_convert_frame_to_buff(frame, &xdp);
5648 
5649 		slave_dev = bond_xdp_get_xmit_slave(bond_dev, &xdp);
5650 		if (!slave_dev) {
5651 			err = -ENXIO;
5652 			break;
5653 		}
5654 
5655 		err = slave_dev->netdev_ops->ndo_xdp_xmit(slave_dev, 1, frames1, flags);
5656 		if (err < 1)
5657 			break;
5658 	}
5659 
5660 	rcu_read_unlock();
5661 
5662 	/* If error happened on the first frame then we can pass the error up, otherwise
5663 	 * report the number of frames that were xmitted.
5664 	 */
5665 	if (err < 0)
5666 		return (nxmit == 0 ? err : nxmit);
5667 
5668 	return nxmit;
5669 }
5670 
5671 static int bond_xdp_set(struct net_device *dev, struct bpf_prog *prog,
5672 			struct netlink_ext_ack *extack)
5673 {
5674 	struct bonding *bond = netdev_priv(dev);
5675 	struct list_head *iter;
5676 	struct slave *slave, *rollback_slave;
5677 	struct bpf_prog *old_prog;
5678 	struct netdev_bpf xdp = {
5679 		.command = XDP_SETUP_PROG,
5680 		.flags   = 0,
5681 		.prog    = prog,
5682 		.extack  = extack,
5683 	};
5684 	int err;
5685 
5686 	ASSERT_RTNL();
5687 
5688 	if (!bond_xdp_check(bond)) {
5689 		BOND_NL_ERR(dev, extack,
5690 			    "No native XDP support for the current bonding mode");
5691 		return -EOPNOTSUPP;
5692 	}
5693 
5694 	old_prog = bond->xdp_prog;
5695 	bond->xdp_prog = prog;
5696 
5697 	bond_for_each_slave(bond, slave, iter) {
5698 		struct net_device *slave_dev = slave->dev;
5699 
5700 		if (!slave_dev->netdev_ops->ndo_bpf ||
5701 		    !slave_dev->netdev_ops->ndo_xdp_xmit) {
5702 			SLAVE_NL_ERR(dev, slave_dev, extack,
5703 				     "Slave device does not support XDP");
5704 			err = -EOPNOTSUPP;
5705 			goto err;
5706 		}
5707 
5708 		if (dev_xdp_prog_count(slave_dev) > 0) {
5709 			SLAVE_NL_ERR(dev, slave_dev, extack,
5710 				     "Slave has XDP program loaded, please unload before enslaving");
5711 			err = -EOPNOTSUPP;
5712 			goto err;
5713 		}
5714 
5715 		err = dev_xdp_propagate(slave_dev, &xdp);
5716 		if (err < 0) {
5717 			/* ndo_bpf() sets extack error message */
5718 			slave_err(dev, slave_dev, "Error %d calling ndo_bpf\n", err);
5719 			goto err;
5720 		}
5721 		if (prog)
5722 			bpf_prog_inc(prog);
5723 	}
5724 
5725 	if (prog) {
5726 		static_branch_inc(&bpf_master_redirect_enabled_key);
5727 	} else if (old_prog) {
5728 		bpf_prog_put(old_prog);
5729 		static_branch_dec(&bpf_master_redirect_enabled_key);
5730 	}
5731 
5732 	return 0;
5733 
5734 err:
5735 	/* unwind the program changes */
5736 	bond->xdp_prog = old_prog;
5737 	xdp.prog = old_prog;
5738 	xdp.extack = NULL; /* do not overwrite original error */
5739 
5740 	bond_for_each_slave(bond, rollback_slave, iter) {
5741 		struct net_device *slave_dev = rollback_slave->dev;
5742 		int err_unwind;
5743 
5744 		if (slave == rollback_slave)
5745 			break;
5746 
5747 		err_unwind = dev_xdp_propagate(slave_dev, &xdp);
5748 		if (err_unwind < 0)
5749 			slave_err(dev, slave_dev,
5750 				  "Error %d when unwinding XDP program change\n", err_unwind);
5751 		else if (xdp.prog)
5752 			bpf_prog_inc(xdp.prog);
5753 	}
5754 	return err;
5755 }
5756 
5757 static int bond_xdp(struct net_device *dev, struct netdev_bpf *xdp)
5758 {
5759 	switch (xdp->command) {
5760 	case XDP_SETUP_PROG:
5761 		return bond_xdp_set(dev, xdp->prog, xdp->extack);
5762 	default:
5763 		return -EINVAL;
5764 	}
5765 }
5766 
5767 static u32 bond_mode_bcast_speed(struct slave *slave, u32 speed)
5768 {
5769 	if (speed == 0 || speed == SPEED_UNKNOWN)
5770 		speed = slave->speed;
5771 	else
5772 		speed = min(speed, slave->speed);
5773 
5774 	return speed;
5775 }
5776 
5777 /* Set the BOND_PHC_INDEX flag to notify user space */
5778 static int bond_set_phc_index_flag(struct kernel_hwtstamp_config *kernel_cfg)
5779 {
5780 	struct ifreq *ifr = kernel_cfg->ifr;
5781 	struct hwtstamp_config cfg;
5782 
5783 	if (kernel_cfg->copied_to_user) {
5784 		/* Lower device has a legacy implementation */
5785 		if (copy_from_user(&cfg, ifr->ifr_data, sizeof(cfg)))
5786 			return -EFAULT;
5787 
5788 		cfg.flags |= HWTSTAMP_FLAG_BONDED_PHC_INDEX;
5789 		if (copy_to_user(ifr->ifr_data, &cfg, sizeof(cfg)))
5790 			return -EFAULT;
5791 	} else {
5792 		kernel_cfg->flags |= HWTSTAMP_FLAG_BONDED_PHC_INDEX;
5793 	}
5794 
5795 	return 0;
5796 }
5797 
5798 static int bond_hwtstamp_get(struct net_device *dev,
5799 			     struct kernel_hwtstamp_config *cfg)
5800 {
5801 	struct bonding *bond = netdev_priv(dev);
5802 	struct net_device *real_dev;
5803 	int err;
5804 
5805 	real_dev = bond_option_active_slave_get_rcu(bond);
5806 	if (!real_dev)
5807 		return -EOPNOTSUPP;
5808 
5809 	err = generic_hwtstamp_get_lower(real_dev, cfg);
5810 	if (err)
5811 		return err;
5812 
5813 	return bond_set_phc_index_flag(cfg);
5814 }
5815 
5816 static int bond_hwtstamp_set(struct net_device *dev,
5817 			     struct kernel_hwtstamp_config *cfg,
5818 			     struct netlink_ext_ack *extack)
5819 {
5820 	struct bonding *bond = netdev_priv(dev);
5821 	struct net_device *real_dev;
5822 	int err;
5823 
5824 	if (!(cfg->flags & HWTSTAMP_FLAG_BONDED_PHC_INDEX))
5825 		return -EOPNOTSUPP;
5826 
5827 	real_dev = bond_option_active_slave_get_rcu(bond);
5828 	if (!real_dev)
5829 		return -EOPNOTSUPP;
5830 
5831 	err = generic_hwtstamp_set_lower(real_dev, cfg, extack);
5832 	if (err)
5833 		return err;
5834 
5835 	return bond_set_phc_index_flag(cfg);
5836 }
5837 
5838 static int bond_ethtool_get_link_ksettings(struct net_device *bond_dev,
5839 					   struct ethtool_link_ksettings *cmd)
5840 {
5841 	struct bonding *bond = netdev_priv(bond_dev);
5842 	struct list_head *iter;
5843 	struct slave *slave;
5844 	u32 speed = 0;
5845 
5846 	cmd->base.duplex = DUPLEX_UNKNOWN;
5847 	cmd->base.port = PORT_OTHER;
5848 
5849 	/* Since bond_slave_can_tx returns false for all inactive or down slaves, we
5850 	 * do not need to check mode.  Though link speed might not represent
5851 	 * the true receive or transmit bandwidth (not all modes are symmetric)
5852 	 * this is an accurate maximum.
5853 	 */
5854 	bond_for_each_slave(bond, slave, iter) {
5855 		if (bond_slave_can_tx(slave)) {
5856 			bond_update_speed_duplex(slave);
5857 			if (slave->speed != SPEED_UNKNOWN) {
5858 				if (BOND_MODE(bond) == BOND_MODE_BROADCAST)
5859 					speed = bond_mode_bcast_speed(slave,
5860 								      speed);
5861 				else
5862 					speed += slave->speed;
5863 			}
5864 			if (cmd->base.duplex == DUPLEX_UNKNOWN &&
5865 			    slave->duplex != DUPLEX_UNKNOWN)
5866 				cmd->base.duplex = slave->duplex;
5867 		}
5868 	}
5869 	cmd->base.speed = speed ? : SPEED_UNKNOWN;
5870 
5871 	return 0;
5872 }
5873 
5874 static void bond_ethtool_get_drvinfo(struct net_device *bond_dev,
5875 				     struct ethtool_drvinfo *drvinfo)
5876 {
5877 	strscpy(drvinfo->driver, DRV_NAME, sizeof(drvinfo->driver));
5878 	snprintf(drvinfo->fw_version, sizeof(drvinfo->fw_version), "%d",
5879 		 BOND_ABI_VERSION);
5880 }
5881 
5882 static int bond_ethtool_get_ts_info(struct net_device *bond_dev,
5883 				    struct kernel_ethtool_ts_info *info)
5884 {
5885 	struct bonding *bond = netdev_priv(bond_dev);
5886 	struct kernel_ethtool_ts_info ts_info;
5887 	struct net_device *real_dev;
5888 	bool sw_tx_support = false;
5889 	struct list_head *iter;
5890 	struct slave *slave;
5891 	int ret = 0;
5892 
5893 	rcu_read_lock();
5894 	real_dev = bond_option_active_slave_get_rcu(bond);
5895 	dev_hold(real_dev);
5896 	rcu_read_unlock();
5897 
5898 	if (real_dev) {
5899 		ret = ethtool_get_ts_info_by_layer(real_dev, info);
5900 	} else {
5901 		/* Check if all slaves support software tx timestamping */
5902 		rcu_read_lock();
5903 		bond_for_each_slave_rcu(bond, slave, iter) {
5904 			ret = ethtool_get_ts_info_by_layer(slave->dev, &ts_info);
5905 			if (!ret && (ts_info.so_timestamping & SOF_TIMESTAMPING_TX_SOFTWARE)) {
5906 				sw_tx_support = true;
5907 				continue;
5908 			}
5909 
5910 			sw_tx_support = false;
5911 			break;
5912 		}
5913 		rcu_read_unlock();
5914 	}
5915 
5916 	if (sw_tx_support)
5917 		info->so_timestamping |= SOF_TIMESTAMPING_TX_SOFTWARE;
5918 
5919 	dev_put(real_dev);
5920 	return ret;
5921 }
5922 
5923 static const struct ethtool_ops bond_ethtool_ops = {
5924 	.get_drvinfo		= bond_ethtool_get_drvinfo,
5925 	.get_link		= ethtool_op_get_link,
5926 	.get_link_ksettings	= bond_ethtool_get_link_ksettings,
5927 	.get_ts_info		= bond_ethtool_get_ts_info,
5928 };
5929 
5930 static const struct net_device_ops bond_netdev_ops = {
5931 	.ndo_init		= bond_init,
5932 	.ndo_uninit		= bond_uninit,
5933 	.ndo_open		= bond_open,
5934 	.ndo_stop		= bond_close,
5935 	.ndo_start_xmit		= bond_start_xmit,
5936 	.ndo_select_queue	= bond_select_queue,
5937 	.ndo_get_stats64	= bond_get_stats,
5938 	.ndo_eth_ioctl		= bond_eth_ioctl,
5939 	.ndo_siocbond		= bond_do_ioctl,
5940 	.ndo_siocdevprivate	= bond_siocdevprivate,
5941 	.ndo_change_rx_flags	= bond_change_rx_flags,
5942 	.ndo_set_rx_mode	= bond_set_rx_mode,
5943 	.ndo_change_mtu		= bond_change_mtu,
5944 	.ndo_set_mac_address	= bond_set_mac_address,
5945 	.ndo_neigh_setup	= bond_neigh_setup,
5946 	.ndo_vlan_rx_add_vid	= bond_vlan_rx_add_vid,
5947 	.ndo_vlan_rx_kill_vid	= bond_vlan_rx_kill_vid,
5948 #ifdef CONFIG_NET_POLL_CONTROLLER
5949 	.ndo_netpoll_setup	= bond_netpoll_setup,
5950 	.ndo_netpoll_cleanup	= bond_netpoll_cleanup,
5951 	.ndo_poll_controller	= bond_poll_controller,
5952 #endif
5953 	.ndo_add_slave		= bond_enslave,
5954 	.ndo_del_slave		= bond_release,
5955 	.ndo_fix_features	= bond_fix_features,
5956 	.ndo_features_check	= passthru_features_check,
5957 	.ndo_get_xmit_slave	= bond_xmit_get_slave,
5958 	.ndo_sk_get_lower_dev	= bond_sk_get_lower_dev,
5959 	.ndo_bpf		= bond_xdp,
5960 	.ndo_xdp_xmit           = bond_xdp_xmit,
5961 	.ndo_xdp_get_xmit_slave = bond_xdp_get_xmit_slave,
5962 	.ndo_hwtstamp_get	= bond_hwtstamp_get,
5963 	.ndo_hwtstamp_set	= bond_hwtstamp_set,
5964 };
5965 
5966 static const struct device_type bond_type = {
5967 	.name = "bond",
5968 };
5969 
5970 static void bond_destructor(struct net_device *bond_dev)
5971 {
5972 	struct bonding *bond = netdev_priv(bond_dev);
5973 
5974 	if (bond->wq)
5975 		destroy_workqueue(bond->wq);
5976 
5977 	free_percpu(bond->rr_tx_counter);
5978 }
5979 
5980 void bond_setup(struct net_device *bond_dev)
5981 {
5982 	struct bonding *bond = netdev_priv(bond_dev);
5983 
5984 	spin_lock_init(&bond->mode_lock);
5985 	bond->params = bonding_defaults;
5986 
5987 	/* Initialize pointers */
5988 	bond->dev = bond_dev;
5989 
5990 	/* Initialize the device entry points */
5991 	ether_setup(bond_dev);
5992 	bond_dev->max_mtu = ETH_MAX_MTU;
5993 	bond_dev->netdev_ops = &bond_netdev_ops;
5994 	bond_dev->ethtool_ops = &bond_ethtool_ops;
5995 
5996 	bond_dev->needs_free_netdev = true;
5997 	bond_dev->priv_destructor = bond_destructor;
5998 
5999 	SET_NETDEV_DEVTYPE(bond_dev, &bond_type);
6000 
6001 	/* Initialize the device options */
6002 	bond_dev->flags |= IFF_MASTER;
6003 	bond_dev->priv_flags |= IFF_BONDING | IFF_UNICAST_FLT | IFF_NO_QUEUE;
6004 	bond_dev->priv_flags &= ~(IFF_XMIT_DST_RELEASE | IFF_TX_SKB_SHARING);
6005 
6006 #ifdef CONFIG_XFRM_OFFLOAD
6007 	/* set up xfrm device ops (only supported in active-backup right now) */
6008 	bond_dev->xfrmdev_ops = &bond_xfrmdev_ops;
6009 	INIT_LIST_HEAD(&bond->ipsec_list);
6010 	mutex_init(&bond->ipsec_lock);
6011 #endif /* CONFIG_XFRM_OFFLOAD */
6012 
6013 	/* don't acquire bond device's netif_tx_lock when transmitting */
6014 	bond_dev->lltx = true;
6015 
6016 	/* Don't allow bond devices to change network namespaces. */
6017 	bond_dev->netns_local = true;
6018 
6019 	/* By default, we declare the bond to be fully
6020 	 * VLAN hardware accelerated capable. Special
6021 	 * care is taken in the various xmit functions
6022 	 * when there are slaves that are not hw accel
6023 	 * capable
6024 	 */
6025 
6026 	bond_dev->hw_features = BOND_VLAN_FEATURES |
6027 				NETIF_F_HW_VLAN_CTAG_RX |
6028 				NETIF_F_HW_VLAN_CTAG_FILTER |
6029 				NETIF_F_HW_VLAN_STAG_RX |
6030 				NETIF_F_HW_VLAN_STAG_FILTER;
6031 
6032 	bond_dev->hw_features |= NETIF_F_GSO_ENCAP_ALL;
6033 	bond_dev->features |= bond_dev->hw_features;
6034 	bond_dev->features |= NETIF_F_HW_VLAN_CTAG_TX | NETIF_F_HW_VLAN_STAG_TX;
6035 #ifdef CONFIG_XFRM_OFFLOAD
6036 	bond_dev->hw_features |= BOND_XFRM_FEATURES;
6037 	/* Only enable XFRM features if this is an active-backup config */
6038 	if (BOND_MODE(bond) == BOND_MODE_ACTIVEBACKUP)
6039 		bond_dev->features |= BOND_XFRM_FEATURES;
6040 #endif /* CONFIG_XFRM_OFFLOAD */
6041 }
6042 
6043 /* Destroy a bonding device.
6044  * Must be under rtnl_lock when this function is called.
6045  */
6046 static void bond_uninit(struct net_device *bond_dev)
6047 {
6048 	struct bonding *bond = netdev_priv(bond_dev);
6049 	struct list_head *iter;
6050 	struct slave *slave;
6051 
6052 	bond_netpoll_cleanup(bond_dev);
6053 
6054 	/* Release the bonded slaves */
6055 	bond_for_each_slave(bond, slave, iter)
6056 		__bond_release_one(bond_dev, slave->dev, true, true);
6057 	netdev_info(bond_dev, "Released all slaves\n");
6058 
6059 #ifdef CONFIG_XFRM_OFFLOAD
6060 	mutex_destroy(&bond->ipsec_lock);
6061 #endif /* CONFIG_XFRM_OFFLOAD */
6062 
6063 	bond_set_slave_arr(bond, NULL, NULL);
6064 
6065 	list_del_rcu(&bond->bond_list);
6066 
6067 	bond_debug_unregister(bond);
6068 }
6069 
6070 /*------------------------- Module initialization ---------------------------*/
6071 
6072 static int __init bond_check_params(struct bond_params *params)
6073 {
6074 	int arp_validate_value, fail_over_mac_value, primary_reselect_value, i;
6075 	struct bond_opt_value newval;
6076 	const struct bond_opt_value *valptr;
6077 	int arp_all_targets_value = 0;
6078 	u16 ad_actor_sys_prio = 0;
6079 	u16 ad_user_port_key = 0;
6080 	__be32 arp_target[BOND_MAX_ARP_TARGETS] = { 0 };
6081 	int arp_ip_count;
6082 	int bond_mode	= BOND_MODE_ROUNDROBIN;
6083 	int xmit_hashtype = BOND_XMIT_POLICY_LAYER2;
6084 	int lacp_fast = 0;
6085 	int tlb_dynamic_lb;
6086 
6087 	/* Convert string parameters. */
6088 	if (mode) {
6089 		bond_opt_initstr(&newval, mode);
6090 		valptr = bond_opt_parse(bond_opt_get(BOND_OPT_MODE), &newval);
6091 		if (!valptr) {
6092 			pr_err("Error: Invalid bonding mode \"%s\"\n", mode);
6093 			return -EINVAL;
6094 		}
6095 		bond_mode = valptr->value;
6096 	}
6097 
6098 	if (xmit_hash_policy) {
6099 		if (bond_mode == BOND_MODE_ROUNDROBIN ||
6100 		    bond_mode == BOND_MODE_ACTIVEBACKUP ||
6101 		    bond_mode == BOND_MODE_BROADCAST) {
6102 			pr_info("xmit_hash_policy param is irrelevant in mode %s\n",
6103 				bond_mode_name(bond_mode));
6104 		} else {
6105 			bond_opt_initstr(&newval, xmit_hash_policy);
6106 			valptr = bond_opt_parse(bond_opt_get(BOND_OPT_XMIT_HASH),
6107 						&newval);
6108 			if (!valptr) {
6109 				pr_err("Error: Invalid xmit_hash_policy \"%s\"\n",
6110 				       xmit_hash_policy);
6111 				return -EINVAL;
6112 			}
6113 			xmit_hashtype = valptr->value;
6114 		}
6115 	}
6116 
6117 	if (lacp_rate) {
6118 		if (bond_mode != BOND_MODE_8023AD) {
6119 			pr_info("lacp_rate param is irrelevant in mode %s\n",
6120 				bond_mode_name(bond_mode));
6121 		} else {
6122 			bond_opt_initstr(&newval, lacp_rate);
6123 			valptr = bond_opt_parse(bond_opt_get(BOND_OPT_LACP_RATE),
6124 						&newval);
6125 			if (!valptr) {
6126 				pr_err("Error: Invalid lacp rate \"%s\"\n",
6127 				       lacp_rate);
6128 				return -EINVAL;
6129 			}
6130 			lacp_fast = valptr->value;
6131 		}
6132 	}
6133 
6134 	if (ad_select) {
6135 		bond_opt_initstr(&newval, ad_select);
6136 		valptr = bond_opt_parse(bond_opt_get(BOND_OPT_AD_SELECT),
6137 					&newval);
6138 		if (!valptr) {
6139 			pr_err("Error: Invalid ad_select \"%s\"\n", ad_select);
6140 			return -EINVAL;
6141 		}
6142 		params->ad_select = valptr->value;
6143 		if (bond_mode != BOND_MODE_8023AD)
6144 			pr_warn("ad_select param only affects 802.3ad mode\n");
6145 	} else {
6146 		params->ad_select = BOND_AD_STABLE;
6147 	}
6148 
6149 	if (max_bonds < 0) {
6150 		pr_warn("Warning: max_bonds (%d) not in range %d-%d, so it was reset to BOND_DEFAULT_MAX_BONDS (%d)\n",
6151 			max_bonds, 0, INT_MAX, BOND_DEFAULT_MAX_BONDS);
6152 		max_bonds = BOND_DEFAULT_MAX_BONDS;
6153 	}
6154 
6155 	if (miimon < 0) {
6156 		pr_warn("Warning: miimon module parameter (%d), not in range 0-%d, so it was reset to 0\n",
6157 			miimon, INT_MAX);
6158 		miimon = 0;
6159 	}
6160 
6161 	if (updelay < 0) {
6162 		pr_warn("Warning: updelay module parameter (%d), not in range 0-%d, so it was reset to 0\n",
6163 			updelay, INT_MAX);
6164 		updelay = 0;
6165 	}
6166 
6167 	if (downdelay < 0) {
6168 		pr_warn("Warning: downdelay module parameter (%d), not in range 0-%d, so it was reset to 0\n",
6169 			downdelay, INT_MAX);
6170 		downdelay = 0;
6171 	}
6172 
6173 	if ((use_carrier != 0) && (use_carrier != 1)) {
6174 		pr_warn("Warning: use_carrier module parameter (%d), not of valid value (0/1), so it was set to 1\n",
6175 			use_carrier);
6176 		use_carrier = 1;
6177 	}
6178 
6179 	if (num_peer_notif < 0 || num_peer_notif > 255) {
6180 		pr_warn("Warning: num_grat_arp/num_unsol_na (%d) not in range 0-255 so it was reset to 1\n",
6181 			num_peer_notif);
6182 		num_peer_notif = 1;
6183 	}
6184 
6185 	/* reset values for 802.3ad/TLB/ALB */
6186 	if (!bond_mode_uses_arp(bond_mode)) {
6187 		if (!miimon) {
6188 			pr_warn("Warning: miimon must be specified, otherwise bonding will not detect link failure, speed and duplex which are essential for 802.3ad operation\n");
6189 			pr_warn("Forcing miimon to 100msec\n");
6190 			miimon = BOND_DEFAULT_MIIMON;
6191 		}
6192 	}
6193 
6194 	if (tx_queues < 1 || tx_queues > 255) {
6195 		pr_warn("Warning: tx_queues (%d) should be between 1 and 255, resetting to %d\n",
6196 			tx_queues, BOND_DEFAULT_TX_QUEUES);
6197 		tx_queues = BOND_DEFAULT_TX_QUEUES;
6198 	}
6199 
6200 	if ((all_slaves_active != 0) && (all_slaves_active != 1)) {
6201 		pr_warn("Warning: all_slaves_active module parameter (%d), not of valid value (0/1), so it was set to 0\n",
6202 			all_slaves_active);
6203 		all_slaves_active = 0;
6204 	}
6205 
6206 	if (resend_igmp < 0 || resend_igmp > 255) {
6207 		pr_warn("Warning: resend_igmp (%d) should be between 0 and 255, resetting to %d\n",
6208 			resend_igmp, BOND_DEFAULT_RESEND_IGMP);
6209 		resend_igmp = BOND_DEFAULT_RESEND_IGMP;
6210 	}
6211 
6212 	bond_opt_initval(&newval, packets_per_slave);
6213 	if (!bond_opt_parse(bond_opt_get(BOND_OPT_PACKETS_PER_SLAVE), &newval)) {
6214 		pr_warn("Warning: packets_per_slave (%d) should be between 0 and %u resetting to 1\n",
6215 			packets_per_slave, USHRT_MAX);
6216 		packets_per_slave = 1;
6217 	}
6218 
6219 	if (bond_mode == BOND_MODE_ALB) {
6220 		pr_notice("In ALB mode you might experience client disconnections upon reconnection of a link if the bonding module updelay parameter (%d msec) is incompatible with the forwarding delay time of the switch\n",
6221 			  updelay);
6222 	}
6223 
6224 	if (!miimon) {
6225 		if (updelay || downdelay) {
6226 			/* just warn the user the up/down delay will have
6227 			 * no effect since miimon is zero...
6228 			 */
6229 			pr_warn("Warning: miimon module parameter not set and updelay (%d) or downdelay (%d) module parameter is set; updelay and downdelay have no effect unless miimon is set\n",
6230 				updelay, downdelay);
6231 		}
6232 	} else {
6233 		/* don't allow arp monitoring */
6234 		if (arp_interval) {
6235 			pr_warn("Warning: miimon (%d) and arp_interval (%d) can't be used simultaneously, disabling ARP monitoring\n",
6236 				miimon, arp_interval);
6237 			arp_interval = 0;
6238 		}
6239 
6240 		if ((updelay % miimon) != 0) {
6241 			pr_warn("Warning: updelay (%d) is not a multiple of miimon (%d), updelay rounded to %d ms\n",
6242 				updelay, miimon, (updelay / miimon) * miimon);
6243 		}
6244 
6245 		updelay /= miimon;
6246 
6247 		if ((downdelay % miimon) != 0) {
6248 			pr_warn("Warning: downdelay (%d) is not a multiple of miimon (%d), downdelay rounded to %d ms\n",
6249 				downdelay, miimon,
6250 				(downdelay / miimon) * miimon);
6251 		}
6252 
6253 		downdelay /= miimon;
6254 	}
6255 
6256 	if (arp_interval < 0) {
6257 		pr_warn("Warning: arp_interval module parameter (%d), not in range 0-%d, so it was reset to 0\n",
6258 			arp_interval, INT_MAX);
6259 		arp_interval = 0;
6260 	}
6261 
6262 	for (arp_ip_count = 0, i = 0;
6263 	     (arp_ip_count < BOND_MAX_ARP_TARGETS) && arp_ip_target[i]; i++) {
6264 		__be32 ip;
6265 
6266 		/* not a complete check, but good enough to catch mistakes */
6267 		if (!in4_pton(arp_ip_target[i], -1, (u8 *)&ip, -1, NULL) ||
6268 		    !bond_is_ip_target_ok(ip)) {
6269 			pr_warn("Warning: bad arp_ip_target module parameter (%s), ARP monitoring will not be performed\n",
6270 				arp_ip_target[i]);
6271 			arp_interval = 0;
6272 		} else {
6273 			if (bond_get_targets_ip(arp_target, ip) == -1)
6274 				arp_target[arp_ip_count++] = ip;
6275 			else
6276 				pr_warn("Warning: duplicate address %pI4 in arp_ip_target, skipping\n",
6277 					&ip);
6278 		}
6279 	}
6280 
6281 	if (arp_interval && !arp_ip_count) {
6282 		/* don't allow arping if no arp_ip_target given... */
6283 		pr_warn("Warning: arp_interval module parameter (%d) specified without providing an arp_ip_target parameter, arp_interval was reset to 0\n",
6284 			arp_interval);
6285 		arp_interval = 0;
6286 	}
6287 
6288 	if (arp_validate) {
6289 		if (!arp_interval) {
6290 			pr_err("arp_validate requires arp_interval\n");
6291 			return -EINVAL;
6292 		}
6293 
6294 		bond_opt_initstr(&newval, arp_validate);
6295 		valptr = bond_opt_parse(bond_opt_get(BOND_OPT_ARP_VALIDATE),
6296 					&newval);
6297 		if (!valptr) {
6298 			pr_err("Error: invalid arp_validate \"%s\"\n",
6299 			       arp_validate);
6300 			return -EINVAL;
6301 		}
6302 		arp_validate_value = valptr->value;
6303 	} else {
6304 		arp_validate_value = 0;
6305 	}
6306 
6307 	if (arp_all_targets) {
6308 		bond_opt_initstr(&newval, arp_all_targets);
6309 		valptr = bond_opt_parse(bond_opt_get(BOND_OPT_ARP_ALL_TARGETS),
6310 					&newval);
6311 		if (!valptr) {
6312 			pr_err("Error: invalid arp_all_targets_value \"%s\"\n",
6313 			       arp_all_targets);
6314 			arp_all_targets_value = 0;
6315 		} else {
6316 			arp_all_targets_value = valptr->value;
6317 		}
6318 	}
6319 
6320 	if (miimon) {
6321 		pr_info("MII link monitoring set to %d ms\n", miimon);
6322 	} else if (arp_interval) {
6323 		valptr = bond_opt_get_val(BOND_OPT_ARP_VALIDATE,
6324 					  arp_validate_value);
6325 		pr_info("ARP monitoring set to %d ms, validate %s, with %d target(s):",
6326 			arp_interval, valptr->string, arp_ip_count);
6327 
6328 		for (i = 0; i < arp_ip_count; i++)
6329 			pr_cont(" %s", arp_ip_target[i]);
6330 
6331 		pr_cont("\n");
6332 
6333 	} else if (max_bonds) {
6334 		/* miimon and arp_interval not set, we need one so things
6335 		 * work as expected, see bonding.txt for details
6336 		 */
6337 		pr_debug("Warning: either miimon or arp_interval and arp_ip_target module parameters must be specified, otherwise bonding will not detect link failures! see bonding.txt for details\n");
6338 	}
6339 
6340 	if (primary && !bond_mode_uses_primary(bond_mode)) {
6341 		/* currently, using a primary only makes sense
6342 		 * in active backup, TLB or ALB modes
6343 		 */
6344 		pr_warn("Warning: %s primary device specified but has no effect in %s mode\n",
6345 			primary, bond_mode_name(bond_mode));
6346 		primary = NULL;
6347 	}
6348 
6349 	if (primary && primary_reselect) {
6350 		bond_opt_initstr(&newval, primary_reselect);
6351 		valptr = bond_opt_parse(bond_opt_get(BOND_OPT_PRIMARY_RESELECT),
6352 					&newval);
6353 		if (!valptr) {
6354 			pr_err("Error: Invalid primary_reselect \"%s\"\n",
6355 			       primary_reselect);
6356 			return -EINVAL;
6357 		}
6358 		primary_reselect_value = valptr->value;
6359 	} else {
6360 		primary_reselect_value = BOND_PRI_RESELECT_ALWAYS;
6361 	}
6362 
6363 	if (fail_over_mac) {
6364 		bond_opt_initstr(&newval, fail_over_mac);
6365 		valptr = bond_opt_parse(bond_opt_get(BOND_OPT_FAIL_OVER_MAC),
6366 					&newval);
6367 		if (!valptr) {
6368 			pr_err("Error: invalid fail_over_mac \"%s\"\n",
6369 			       fail_over_mac);
6370 			return -EINVAL;
6371 		}
6372 		fail_over_mac_value = valptr->value;
6373 		if (bond_mode != BOND_MODE_ACTIVEBACKUP)
6374 			pr_warn("Warning: fail_over_mac only affects active-backup mode\n");
6375 	} else {
6376 		fail_over_mac_value = BOND_FOM_NONE;
6377 	}
6378 
6379 	bond_opt_initstr(&newval, "default");
6380 	valptr = bond_opt_parse(
6381 			bond_opt_get(BOND_OPT_AD_ACTOR_SYS_PRIO),
6382 				     &newval);
6383 	if (!valptr) {
6384 		pr_err("Error: No ad_actor_sys_prio default value");
6385 		return -EINVAL;
6386 	}
6387 	ad_actor_sys_prio = valptr->value;
6388 
6389 	valptr = bond_opt_parse(bond_opt_get(BOND_OPT_AD_USER_PORT_KEY),
6390 				&newval);
6391 	if (!valptr) {
6392 		pr_err("Error: No ad_user_port_key default value");
6393 		return -EINVAL;
6394 	}
6395 	ad_user_port_key = valptr->value;
6396 
6397 	bond_opt_initstr(&newval, "default");
6398 	valptr = bond_opt_parse(bond_opt_get(BOND_OPT_TLB_DYNAMIC_LB), &newval);
6399 	if (!valptr) {
6400 		pr_err("Error: No tlb_dynamic_lb default value");
6401 		return -EINVAL;
6402 	}
6403 	tlb_dynamic_lb = valptr->value;
6404 
6405 	if (lp_interval == 0) {
6406 		pr_warn("Warning: ip_interval must be between 1 and %d, so it was reset to %d\n",
6407 			INT_MAX, BOND_ALB_DEFAULT_LP_INTERVAL);
6408 		lp_interval = BOND_ALB_DEFAULT_LP_INTERVAL;
6409 	}
6410 
6411 	/* fill params struct with the proper values */
6412 	params->mode = bond_mode;
6413 	params->xmit_policy = xmit_hashtype;
6414 	params->miimon = miimon;
6415 	params->num_peer_notif = num_peer_notif;
6416 	params->arp_interval = arp_interval;
6417 	params->arp_validate = arp_validate_value;
6418 	params->arp_all_targets = arp_all_targets_value;
6419 	params->missed_max = 2;
6420 	params->updelay = updelay;
6421 	params->downdelay = downdelay;
6422 	params->peer_notif_delay = 0;
6423 	params->use_carrier = use_carrier;
6424 	params->lacp_active = 1;
6425 	params->lacp_fast = lacp_fast;
6426 	params->primary[0] = 0;
6427 	params->primary_reselect = primary_reselect_value;
6428 	params->fail_over_mac = fail_over_mac_value;
6429 	params->tx_queues = tx_queues;
6430 	params->all_slaves_active = all_slaves_active;
6431 	params->resend_igmp = resend_igmp;
6432 	params->min_links = min_links;
6433 	params->lp_interval = lp_interval;
6434 	params->packets_per_slave = packets_per_slave;
6435 	params->tlb_dynamic_lb = tlb_dynamic_lb;
6436 	params->ad_actor_sys_prio = ad_actor_sys_prio;
6437 	eth_zero_addr(params->ad_actor_system);
6438 	params->ad_user_port_key = ad_user_port_key;
6439 	params->coupled_control = 1;
6440 	if (packets_per_slave > 0) {
6441 		params->reciprocal_packets_per_slave =
6442 			reciprocal_value(packets_per_slave);
6443 	} else {
6444 		/* reciprocal_packets_per_slave is unused if
6445 		 * packets_per_slave is 0 or 1, just initialize it
6446 		 */
6447 		params->reciprocal_packets_per_slave =
6448 			(struct reciprocal_value) { 0 };
6449 	}
6450 
6451 	if (primary)
6452 		strscpy_pad(params->primary, primary, sizeof(params->primary));
6453 
6454 	memcpy(params->arp_targets, arp_target, sizeof(arp_target));
6455 #if IS_ENABLED(CONFIG_IPV6)
6456 	memset(params->ns_targets, 0, sizeof(struct in6_addr) * BOND_MAX_NS_TARGETS);
6457 #endif
6458 
6459 	return 0;
6460 }
6461 
6462 /* Called from registration process */
6463 static int bond_init(struct net_device *bond_dev)
6464 {
6465 	struct bonding *bond = netdev_priv(bond_dev);
6466 	struct bond_net *bn = net_generic(dev_net(bond_dev), bond_net_id);
6467 
6468 	netdev_dbg(bond_dev, "Begin bond_init\n");
6469 
6470 	bond->wq = alloc_ordered_workqueue("%s", WQ_MEM_RECLAIM,
6471 					   bond_dev->name);
6472 	if (!bond->wq)
6473 		return -ENOMEM;
6474 
6475 	bond->notifier_ctx = false;
6476 
6477 	spin_lock_init(&bond->stats_lock);
6478 	netdev_lockdep_set_classes(bond_dev);
6479 
6480 	list_add_tail_rcu(&bond->bond_list, &bn->dev_list);
6481 
6482 	bond_prepare_sysfs_group(bond);
6483 
6484 	bond_debug_register(bond);
6485 
6486 	/* Ensure valid dev_addr */
6487 	if (is_zero_ether_addr(bond_dev->dev_addr) &&
6488 	    bond_dev->addr_assign_type == NET_ADDR_PERM)
6489 		eth_hw_addr_random(bond_dev);
6490 
6491 	return 0;
6492 }
6493 
6494 unsigned int bond_get_num_tx_queues(void)
6495 {
6496 	return tx_queues;
6497 }
6498 
6499 /* Create a new bond based on the specified name and bonding parameters.
6500  * If name is NULL, obtain a suitable "bond%d" name for us.
6501  * Caller must NOT hold rtnl_lock; we need to release it here before we
6502  * set up our sysfs entries.
6503  */
6504 int bond_create(struct net *net, const char *name)
6505 {
6506 	struct net_device *bond_dev;
6507 	struct bonding *bond;
6508 	int res = -ENOMEM;
6509 
6510 	rtnl_lock();
6511 
6512 	bond_dev = alloc_netdev_mq(sizeof(struct bonding),
6513 				   name ? name : "bond%d", NET_NAME_UNKNOWN,
6514 				   bond_setup, tx_queues);
6515 	if (!bond_dev)
6516 		goto out;
6517 
6518 	bond = netdev_priv(bond_dev);
6519 	dev_net_set(bond_dev, net);
6520 	bond_dev->rtnl_link_ops = &bond_link_ops;
6521 
6522 	res = register_netdevice(bond_dev);
6523 	if (res < 0) {
6524 		free_netdev(bond_dev);
6525 		goto out;
6526 	}
6527 
6528 	netif_carrier_off(bond_dev);
6529 
6530 	bond_work_init_all(bond);
6531 
6532 out:
6533 	rtnl_unlock();
6534 	return res;
6535 }
6536 
6537 static int __net_init bond_net_init(struct net *net)
6538 {
6539 	struct bond_net *bn = net_generic(net, bond_net_id);
6540 
6541 	bn->net = net;
6542 	INIT_LIST_HEAD(&bn->dev_list);
6543 
6544 	bond_create_proc_dir(bn);
6545 	bond_create_sysfs(bn);
6546 
6547 	return 0;
6548 }
6549 
6550 /* According to commit 69b0216ac255 ("bonding: fix bonding_masters
6551  * race condition in bond unloading") we need to remove sysfs files
6552  * before we remove our devices (done later in bond_net_exit_batch_rtnl())
6553  */
6554 static void __net_exit bond_net_pre_exit(struct net *net)
6555 {
6556 	struct bond_net *bn = net_generic(net, bond_net_id);
6557 
6558 	bond_destroy_sysfs(bn);
6559 }
6560 
6561 static void __net_exit bond_net_exit_batch_rtnl(struct list_head *net_list,
6562 						struct list_head *dev_kill_list)
6563 {
6564 	struct bond_net *bn;
6565 	struct net *net;
6566 
6567 	/* Kill off any bonds created after unregistering bond rtnl ops */
6568 	list_for_each_entry(net, net_list, exit_list) {
6569 		struct bonding *bond, *tmp_bond;
6570 
6571 		bn = net_generic(net, bond_net_id);
6572 		list_for_each_entry_safe(bond, tmp_bond, &bn->dev_list, bond_list)
6573 			unregister_netdevice_queue(bond->dev, dev_kill_list);
6574 	}
6575 }
6576 
6577 /* According to commit 23fa5c2caae0 ("bonding: destroy proc directory
6578  * only after all bonds are gone") bond_destroy_proc_dir() is called
6579  * after bond_net_exit_batch_rtnl() has completed.
6580  */
6581 static void __net_exit bond_net_exit_batch(struct list_head *net_list)
6582 {
6583 	struct bond_net *bn;
6584 	struct net *net;
6585 
6586 	list_for_each_entry(net, net_list, exit_list) {
6587 		bn = net_generic(net, bond_net_id);
6588 		bond_destroy_proc_dir(bn);
6589 	}
6590 }
6591 
6592 static struct pernet_operations bond_net_ops = {
6593 	.init = bond_net_init,
6594 	.pre_exit = bond_net_pre_exit,
6595 	.exit_batch_rtnl = bond_net_exit_batch_rtnl,
6596 	.exit_batch = bond_net_exit_batch,
6597 	.id   = &bond_net_id,
6598 	.size = sizeof(struct bond_net),
6599 };
6600 
6601 static int __init bonding_init(void)
6602 {
6603 	int i;
6604 	int res;
6605 
6606 	res = bond_check_params(&bonding_defaults);
6607 	if (res)
6608 		goto out;
6609 
6610 	bond_create_debugfs();
6611 
6612 	res = register_pernet_subsys(&bond_net_ops);
6613 	if (res)
6614 		goto err_net_ops;
6615 
6616 	res = bond_netlink_init();
6617 	if (res)
6618 		goto err_link;
6619 
6620 	for (i = 0; i < max_bonds; i++) {
6621 		res = bond_create(&init_net, NULL);
6622 		if (res)
6623 			goto err;
6624 	}
6625 
6626 	skb_flow_dissector_init(&flow_keys_bonding,
6627 				flow_keys_bonding_keys,
6628 				ARRAY_SIZE(flow_keys_bonding_keys));
6629 
6630 	register_netdevice_notifier(&bond_netdev_notifier);
6631 out:
6632 	return res;
6633 err:
6634 	bond_netlink_fini();
6635 err_link:
6636 	unregister_pernet_subsys(&bond_net_ops);
6637 err_net_ops:
6638 	bond_destroy_debugfs();
6639 	goto out;
6640 
6641 }
6642 
6643 static void __exit bonding_exit(void)
6644 {
6645 	unregister_netdevice_notifier(&bond_netdev_notifier);
6646 
6647 	bond_netlink_fini();
6648 	unregister_pernet_subsys(&bond_net_ops);
6649 
6650 	bond_destroy_debugfs();
6651 
6652 #ifdef CONFIG_NET_POLL_CONTROLLER
6653 	/* Make sure we don't have an imbalance on our netpoll blocking */
6654 	WARN_ON(atomic_read(&netpoll_block_tx));
6655 #endif
6656 }
6657 
6658 module_init(bonding_init);
6659 module_exit(bonding_exit);
6660 MODULE_LICENSE("GPL");
6661 MODULE_DESCRIPTION(DRV_DESCRIPTION);
6662 MODULE_AUTHOR("Thomas Davis, tadavis@lbl.gov and many others");
6663