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