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