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