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