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