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