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