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