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