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