Whamcloud - gitweb
LU-9913 lnet: balance references in lnet_discover_peer_locked()
[fs/lustre-release.git] / lnet / lnet / peer.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2012, 2014, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  * Lustre is a trademark of Sun Microsystems, Inc.
31  *
32  * lnet/lnet/peer.c
33  */
34
35 #define DEBUG_SUBSYSTEM S_LNET
36
37 #include <lnet/lib-lnet.h>
38 #include <uapi/linux/lnet/lnet-dlc.h>
39
40 /* Value indicating that recovery needs to re-check a peer immediately. */
41 #define LNET_REDISCOVER_PEER    (1)
42
43 static int lnet_peer_queue_for_discovery(struct lnet_peer *lp);
44
45 static void
46 lnet_peer_remove_from_remote_list(struct lnet_peer_ni *lpni)
47 {
48         if (!list_empty(&lpni->lpni_on_remote_peer_ni_list)) {
49                 list_del_init(&lpni->lpni_on_remote_peer_ni_list);
50                 lnet_peer_ni_decref_locked(lpni);
51         }
52 }
53
54 void
55 lnet_peer_net_added(struct lnet_net *net)
56 {
57         struct lnet_peer_ni *lpni, *tmp;
58
59         list_for_each_entry_safe(lpni, tmp, &the_lnet.ln_remote_peer_ni_list,
60                                  lpni_on_remote_peer_ni_list) {
61
62                 if (LNET_NIDNET(lpni->lpni_nid) == net->net_id) {
63                         lpni->lpni_net = net;
64
65                         spin_lock(&lpni->lpni_lock);
66                         lpni->lpni_txcredits =
67                                 lpni->lpni_net->net_tunables.lct_peer_tx_credits;
68                         lpni->lpni_mintxcredits = lpni->lpni_txcredits;
69                         lpni->lpni_rtrcredits =
70                                 lnet_peer_buffer_credits(lpni->lpni_net);
71                         lpni->lpni_minrtrcredits = lpni->lpni_rtrcredits;
72                         spin_unlock(&lpni->lpni_lock);
73
74                         lnet_peer_remove_from_remote_list(lpni);
75                 }
76         }
77 }
78
79 static void
80 lnet_peer_tables_destroy(void)
81 {
82         struct lnet_peer_table  *ptable;
83         struct list_head        *hash;
84         int                     i;
85         int                     j;
86
87         if (!the_lnet.ln_peer_tables)
88                 return;
89
90         cfs_percpt_for_each(ptable, i, the_lnet.ln_peer_tables) {
91                 hash = ptable->pt_hash;
92                 if (!hash) /* not intialized */
93                         break;
94
95                 LASSERT(list_empty(&ptable->pt_zombie_list));
96
97                 ptable->pt_hash = NULL;
98                 for (j = 0; j < LNET_PEER_HASH_SIZE; j++)
99                         LASSERT(list_empty(&hash[j]));
100
101                 LIBCFS_FREE(hash, LNET_PEER_HASH_SIZE * sizeof(*hash));
102         }
103
104         cfs_percpt_free(the_lnet.ln_peer_tables);
105         the_lnet.ln_peer_tables = NULL;
106 }
107
108 int
109 lnet_peer_tables_create(void)
110 {
111         struct lnet_peer_table  *ptable;
112         struct list_head        *hash;
113         int                     i;
114         int                     j;
115
116         the_lnet.ln_peer_tables = cfs_percpt_alloc(lnet_cpt_table(),
117                                                    sizeof(*ptable));
118         if (the_lnet.ln_peer_tables == NULL) {
119                 CERROR("Failed to allocate cpu-partition peer tables\n");
120                 return -ENOMEM;
121         }
122
123         cfs_percpt_for_each(ptable, i, the_lnet.ln_peer_tables) {
124                 LIBCFS_CPT_ALLOC(hash, lnet_cpt_table(), i,
125                                  LNET_PEER_HASH_SIZE * sizeof(*hash));
126                 if (hash == NULL) {
127                         CERROR("Failed to create peer hash table\n");
128                         lnet_peer_tables_destroy();
129                         return -ENOMEM;
130                 }
131
132                 spin_lock_init(&ptable->pt_zombie_lock);
133                 INIT_LIST_HEAD(&ptable->pt_zombie_list);
134
135                 INIT_LIST_HEAD(&ptable->pt_peer_list);
136
137                 for (j = 0; j < LNET_PEER_HASH_SIZE; j++)
138                         INIT_LIST_HEAD(&hash[j]);
139                 ptable->pt_hash = hash; /* sign of initialization */
140         }
141
142         return 0;
143 }
144
145 static struct lnet_peer_ni *
146 lnet_peer_ni_alloc(lnet_nid_t nid)
147 {
148         struct lnet_peer_ni *lpni;
149         struct lnet_net *net;
150         int cpt;
151
152         cpt = lnet_nid_cpt_hash(nid, LNET_CPT_NUMBER);
153
154         LIBCFS_CPT_ALLOC(lpni, lnet_cpt_table(), cpt, sizeof(*lpni));
155         if (!lpni)
156                 return NULL;
157
158         INIT_LIST_HEAD(&lpni->lpni_txq);
159         INIT_LIST_HEAD(&lpni->lpni_rtrq);
160         INIT_LIST_HEAD(&lpni->lpni_routes);
161         INIT_LIST_HEAD(&lpni->lpni_hashlist);
162         INIT_LIST_HEAD(&lpni->lpni_peer_nis);
163         INIT_LIST_HEAD(&lpni->lpni_on_remote_peer_ni_list);
164
165         spin_lock_init(&lpni->lpni_lock);
166
167         lpni->lpni_alive = !lnet_peers_start_down(); /* 1 bit!! */
168         lpni->lpni_last_alive = cfs_time_current(); /* assumes alive */
169         lpni->lpni_ping_feats = LNET_PING_FEAT_INVAL;
170         lpni->lpni_nid = nid;
171         lpni->lpni_cpt = cpt;
172         lnet_set_peer_ni_health_locked(lpni, true);
173
174         net = lnet_get_net_locked(LNET_NIDNET(nid));
175         lpni->lpni_net = net;
176         if (net) {
177                 lpni->lpni_txcredits = net->net_tunables.lct_peer_tx_credits;
178                 lpni->lpni_mintxcredits = lpni->lpni_txcredits;
179                 lpni->lpni_rtrcredits = lnet_peer_buffer_credits(net);
180                 lpni->lpni_minrtrcredits = lpni->lpni_rtrcredits;
181         } else {
182                 /*
183                  * This peer_ni is not on a local network, so we
184                  * cannot add the credits here. In case the net is
185                  * added later, add the peer_ni to the remote peer ni
186                  * list so it can be easily found and revisited.
187                  */
188                 /* FIXME: per-net implementation instead? */
189                 atomic_inc(&lpni->lpni_refcount);
190                 list_add_tail(&lpni->lpni_on_remote_peer_ni_list,
191                               &the_lnet.ln_remote_peer_ni_list);
192         }
193
194         CDEBUG(D_NET, "%p nid %s\n", lpni, libcfs_nid2str(lpni->lpni_nid));
195
196         return lpni;
197 }
198
199 static struct lnet_peer_net *
200 lnet_peer_net_alloc(__u32 net_id)
201 {
202         struct lnet_peer_net *lpn;
203
204         LIBCFS_CPT_ALLOC(lpn, lnet_cpt_table(), CFS_CPT_ANY, sizeof(*lpn));
205         if (!lpn)
206                 return NULL;
207
208         INIT_LIST_HEAD(&lpn->lpn_peer_nets);
209         INIT_LIST_HEAD(&lpn->lpn_peer_nis);
210         lpn->lpn_net_id = net_id;
211
212         CDEBUG(D_NET, "%p net %s\n", lpn, libcfs_net2str(lpn->lpn_net_id));
213
214         return lpn;
215 }
216
217 void
218 lnet_destroy_peer_net_locked(struct lnet_peer_net *lpn)
219 {
220         struct lnet_peer *lp;
221
222         CDEBUG(D_NET, "%p net %s\n", lpn, libcfs_net2str(lpn->lpn_net_id));
223
224         LASSERT(atomic_read(&lpn->lpn_refcount) == 0);
225         LASSERT(list_empty(&lpn->lpn_peer_nis));
226         LASSERT(list_empty(&lpn->lpn_peer_nets));
227         lp = lpn->lpn_peer;
228         lpn->lpn_peer = NULL;
229         LIBCFS_FREE(lpn, sizeof(*lpn));
230
231         lnet_peer_decref_locked(lp);
232 }
233
234 static struct lnet_peer *
235 lnet_peer_alloc(lnet_nid_t nid)
236 {
237         struct lnet_peer *lp;
238
239         LIBCFS_CPT_ALLOC(lp, lnet_cpt_table(), CFS_CPT_ANY, sizeof(*lp));
240         if (!lp)
241                 return NULL;
242
243         INIT_LIST_HEAD(&lp->lp_peer_list);
244         INIT_LIST_HEAD(&lp->lp_peer_nets);
245         INIT_LIST_HEAD(&lp->lp_dc_list);
246         INIT_LIST_HEAD(&lp->lp_dc_pendq);
247         init_waitqueue_head(&lp->lp_dc_waitq);
248         spin_lock_init(&lp->lp_lock);
249         lp->lp_primary_nid = nid;
250         lp->lp_cpt = lnet_nid_cpt_hash(nid, LNET_CPT_NUMBER);
251
252         CDEBUG(D_NET, "%p nid %s\n", lp, libcfs_nid2str(lp->lp_primary_nid));
253
254         return lp;
255 }
256
257 void
258 lnet_destroy_peer_locked(struct lnet_peer *lp)
259 {
260         CDEBUG(D_NET, "%p nid %s\n", lp, libcfs_nid2str(lp->lp_primary_nid));
261
262         LASSERT(atomic_read(&lp->lp_refcount) == 0);
263         LASSERT(list_empty(&lp->lp_peer_nets));
264         LASSERT(list_empty(&lp->lp_peer_list));
265         LASSERT(list_empty(&lp->lp_dc_list));
266
267         if (lp->lp_data)
268                 lnet_ping_buffer_decref(lp->lp_data);
269
270         LIBCFS_FREE(lp, sizeof(*lp));
271 }
272
273 /*
274  * Detach a peer_ni from its peer_net. If this was the last peer_ni on
275  * that peer_net, detach the peer_net from the peer.
276  *
277  * Call with lnet_net_lock/EX held
278  */
279 static void
280 lnet_peer_detach_peer_ni_locked(struct lnet_peer_ni *lpni)
281 {
282         struct lnet_peer_table *ptable;
283         struct lnet_peer_net *lpn;
284         struct lnet_peer *lp;
285
286         /*
287          * Belts and suspenders: gracefully handle teardown of a
288          * partially connected peer_ni.
289          */
290         lpn = lpni->lpni_peer_net;
291
292         list_del_init(&lpni->lpni_peer_nis);
293         /*
294          * If there are no lpni's left, we detach lpn from
295          * lp_peer_nets, so it cannot be found anymore.
296          */
297         if (list_empty(&lpn->lpn_peer_nis))
298                 list_del_init(&lpn->lpn_peer_nets);
299
300         /* Update peer NID count. */
301         lp = lpn->lpn_peer;
302         lp->lp_nnis--;
303
304         /*
305          * If there are no more peer nets, make the peer unfindable
306          * via the peer_tables.
307          *
308          * Otherwise, if the peer is DISCOVERED, tell discovery to
309          * take another look at it. This is a no-op if discovery for
310          * this peer did the detaching.
311          */
312         if (list_empty(&lp->lp_peer_nets)) {
313                 list_del_init(&lp->lp_peer_list);
314                 ptable = the_lnet.ln_peer_tables[lp->lp_cpt];
315                 ptable->pt_peers--;
316         } else if (the_lnet.ln_dc_state != LNET_DC_STATE_RUNNING) {
317                 /* Discovery isn't running, nothing to do here. */
318         } else if (lp->lp_state & LNET_PEER_DISCOVERED) {
319                 lnet_peer_queue_for_discovery(lp);
320                 wake_up(&the_lnet.ln_dc_waitq);
321         }
322         CDEBUG(D_NET, "peer %s NID %s\n",
323                 libcfs_nid2str(lp->lp_primary_nid),
324                 libcfs_nid2str(lpni->lpni_nid));
325 }
326
327 /* called with lnet_net_lock LNET_LOCK_EX held */
328 static int
329 lnet_peer_ni_del_locked(struct lnet_peer_ni *lpni)
330 {
331         struct lnet_peer_table *ptable = NULL;
332
333         /* don't remove a peer_ni if it's also a gateway */
334         if (lpni->lpni_rtr_refcount > 0) {
335                 CERROR("Peer NI %s is a gateway. Can not delete it\n",
336                        libcfs_nid2str(lpni->lpni_nid));
337                 return -EBUSY;
338         }
339
340         lnet_peer_remove_from_remote_list(lpni);
341
342         /* remove peer ni from the hash list. */
343         list_del_init(&lpni->lpni_hashlist);
344
345         /* decrement the ref count on the peer table */
346         ptable = the_lnet.ln_peer_tables[lpni->lpni_cpt];
347         LASSERT(ptable->pt_number > 0);
348         ptable->pt_number--;
349
350         /*
351          * The peer_ni can no longer be found with a lookup. But there
352          * can be current users, so keep track of it on the zombie
353          * list until the reference count has gone to zero.
354          *
355          * The last reference may be lost in a place where the
356          * lnet_net_lock locks only a single cpt, and that cpt may not
357          * be lpni->lpni_cpt. So the zombie list of lnet_peer_table
358          * has its own lock.
359          */
360         spin_lock(&ptable->pt_zombie_lock);
361         list_add(&lpni->lpni_hashlist, &ptable->pt_zombie_list);
362         ptable->pt_zombies++;
363         spin_unlock(&ptable->pt_zombie_lock);
364
365         /* no need to keep this peer_ni on the hierarchy anymore */
366         lnet_peer_detach_peer_ni_locked(lpni);
367
368         /* remove hashlist reference on peer_ni */
369         lnet_peer_ni_decref_locked(lpni);
370
371         return 0;
372 }
373
374 void lnet_peer_uninit(void)
375 {
376         struct lnet_peer_ni *lpni, *tmp;
377
378         lnet_net_lock(LNET_LOCK_EX);
379
380         /* remove all peer_nis from the remote peer and the hash list */
381         list_for_each_entry_safe(lpni, tmp, &the_lnet.ln_remote_peer_ni_list,
382                                  lpni_on_remote_peer_ni_list)
383                 lnet_peer_ni_del_locked(lpni);
384
385         lnet_peer_tables_destroy();
386
387         lnet_net_unlock(LNET_LOCK_EX);
388 }
389
390 static int
391 lnet_peer_del_locked(struct lnet_peer *peer)
392 {
393         struct lnet_peer_ni *lpni = NULL, *lpni2;
394         int rc = 0, rc2 = 0;
395
396         CDEBUG(D_NET, "peer %s\n", libcfs_nid2str(peer->lp_primary_nid));
397
398         lpni = lnet_get_next_peer_ni_locked(peer, NULL, lpni);
399         while (lpni != NULL) {
400                 lpni2 = lnet_get_next_peer_ni_locked(peer, NULL, lpni);
401                 rc = lnet_peer_ni_del_locked(lpni);
402                 if (rc != 0)
403                         rc2 = rc;
404                 lpni = lpni2;
405         }
406
407         return rc2;
408 }
409
410 static int
411 lnet_peer_del(struct lnet_peer *peer)
412 {
413         lnet_net_lock(LNET_LOCK_EX);
414         lnet_peer_del_locked(peer);
415         lnet_net_unlock(LNET_LOCK_EX);
416
417         return 0;
418 }
419
420 /*
421  * Delete a NID from a peer. Call with ln_api_mutex held.
422  *
423  * Error codes:
424  *  -EPERM:  Non-DLC deletion from DLC-configured peer.
425  *  -ENOENT: No lnet_peer_ni corresponding to the nid.
426  *  -ECHILD: The lnet_peer_ni isn't connected to the peer.
427  *  -EBUSY:  The lnet_peer_ni is the primary, and not the only peer_ni.
428  */
429 static int
430 lnet_peer_del_nid(struct lnet_peer *lp, lnet_nid_t nid, unsigned flags)
431 {
432         struct lnet_peer_ni *lpni;
433         lnet_nid_t primary_nid = lp->lp_primary_nid;
434         int rc = 0;
435
436         if (!(flags & LNET_PEER_CONFIGURED)) {
437                 if (lp->lp_state & LNET_PEER_CONFIGURED) {
438                         rc = -EPERM;
439                         goto out;
440                 }
441         }
442         lpni = lnet_find_peer_ni_locked(nid);
443         if (!lpni) {
444                 rc = -ENOENT;
445                 goto out;
446         }
447         lnet_peer_ni_decref_locked(lpni);
448         if (lp != lpni->lpni_peer_net->lpn_peer) {
449                 rc = -ECHILD;
450                 goto out;
451         }
452
453         /*
454          * This function only allows deletion of the primary NID if it
455          * is the only NID.
456          */
457         if (nid == lp->lp_primary_nid && lp->lp_nnis != 1) {
458                 rc = -EBUSY;
459                 goto out;
460         }
461
462         lnet_net_lock(LNET_LOCK_EX);
463         lnet_peer_ni_del_locked(lpni);
464         lnet_net_unlock(LNET_LOCK_EX);
465
466 out:
467         CDEBUG(D_NET, "peer %s NID %s flags %#x: %d\n",
468                libcfs_nid2str(primary_nid), libcfs_nid2str(nid), flags, rc);
469
470         return rc;
471 }
472
473 static void
474 lnet_peer_table_cleanup_locked(struct lnet_net *net,
475                                struct lnet_peer_table *ptable)
476 {
477         int                      i;
478         struct lnet_peer_ni     *next;
479         struct lnet_peer_ni     *lpni;
480         struct lnet_peer        *peer;
481
482         for (i = 0; i < LNET_PEER_HASH_SIZE; i++) {
483                 list_for_each_entry_safe(lpni, next, &ptable->pt_hash[i],
484                                          lpni_hashlist) {
485                         if (net != NULL && net != lpni->lpni_net)
486                                 continue;
487
488                         peer = lpni->lpni_peer_net->lpn_peer;
489                         if (peer->lp_primary_nid != lpni->lpni_nid) {
490                                 lnet_peer_ni_del_locked(lpni);
491                                 continue;
492                         }
493                         /*
494                          * Removing the primary NID implies removing
495                          * the entire peer. Advance next beyond any
496                          * peer_ni that belongs to the same peer.
497                          */
498                         list_for_each_entry_from(next, &ptable->pt_hash[i],
499                                                  lpni_hashlist) {
500                                 if (next->lpni_peer_net->lpn_peer != peer)
501                                         break;
502                         }
503                         lnet_peer_del_locked(peer);
504                 }
505         }
506 }
507
508 static void
509 lnet_peer_ni_finalize_wait(struct lnet_peer_table *ptable)
510 {
511         int     i = 3;
512
513         spin_lock(&ptable->pt_zombie_lock);
514         while (ptable->pt_zombies) {
515                 spin_unlock(&ptable->pt_zombie_lock);
516
517                 if (is_power_of_2(i)) {
518                         CDEBUG(D_WARNING,
519                                "Waiting for %d zombies on peer table\n",
520                                ptable->pt_zombies);
521                 }
522                 set_current_state(TASK_UNINTERRUPTIBLE);
523                 schedule_timeout(cfs_time_seconds(1) >> 1);
524                 spin_lock(&ptable->pt_zombie_lock);
525         }
526         spin_unlock(&ptable->pt_zombie_lock);
527 }
528
529 static void
530 lnet_peer_table_del_rtrs_locked(struct lnet_net *net,
531                                 struct lnet_peer_table *ptable)
532 {
533         struct lnet_peer_ni     *lp;
534         struct lnet_peer_ni     *tmp;
535         lnet_nid_t              lpni_nid;
536         int                     i;
537
538         for (i = 0; i < LNET_PEER_HASH_SIZE; i++) {
539                 list_for_each_entry_safe(lp, tmp, &ptable->pt_hash[i],
540                                          lpni_hashlist) {
541                         if (net != lp->lpni_net)
542                                 continue;
543
544                         if (lp->lpni_rtr_refcount == 0)
545                                 continue;
546
547                         lpni_nid = lp->lpni_nid;
548
549                         lnet_net_unlock(LNET_LOCK_EX);
550                         lnet_del_route(LNET_NIDNET(LNET_NID_ANY), lpni_nid);
551                         lnet_net_lock(LNET_LOCK_EX);
552                 }
553         }
554 }
555
556 void
557 lnet_peer_tables_cleanup(struct lnet_net *net)
558 {
559         int                             i;
560         struct lnet_peer_table          *ptable;
561
562         LASSERT(the_lnet.ln_state != LNET_STATE_SHUTDOWN || net != NULL);
563         /* If just deleting the peers for a NI, get rid of any routes these
564          * peers are gateways for. */
565         cfs_percpt_for_each(ptable, i, the_lnet.ln_peer_tables) {
566                 lnet_net_lock(LNET_LOCK_EX);
567                 lnet_peer_table_del_rtrs_locked(net, ptable);
568                 lnet_net_unlock(LNET_LOCK_EX);
569         }
570
571         /* Start the cleanup process */
572         cfs_percpt_for_each(ptable, i, the_lnet.ln_peer_tables) {
573                 lnet_net_lock(LNET_LOCK_EX);
574                 lnet_peer_table_cleanup_locked(net, ptable);
575                 lnet_net_unlock(LNET_LOCK_EX);
576         }
577
578         cfs_percpt_for_each(ptable, i, the_lnet.ln_peer_tables)
579                 lnet_peer_ni_finalize_wait(ptable);
580 }
581
582 static struct lnet_peer_ni *
583 lnet_get_peer_ni_locked(struct lnet_peer_table *ptable, lnet_nid_t nid)
584 {
585         struct list_head        *peers;
586         struct lnet_peer_ni     *lp;
587
588         LASSERT(the_lnet.ln_state == LNET_STATE_RUNNING);
589
590         peers = &ptable->pt_hash[lnet_nid2peerhash(nid)];
591         list_for_each_entry(lp, peers, lpni_hashlist) {
592                 if (lp->lpni_nid == nid) {
593                         lnet_peer_ni_addref_locked(lp);
594                         return lp;
595                 }
596         }
597
598         return NULL;
599 }
600
601 struct lnet_peer_ni *
602 lnet_find_peer_ni_locked(lnet_nid_t nid)
603 {
604         struct lnet_peer_ni *lpni;
605         struct lnet_peer_table *ptable;
606         int cpt;
607
608         cpt = lnet_nid_cpt_hash(nid, LNET_CPT_NUMBER);
609
610         ptable = the_lnet.ln_peer_tables[cpt];
611         lpni = lnet_get_peer_ni_locked(ptable, nid);
612
613         return lpni;
614 }
615
616 struct lnet_peer *
617 lnet_find_peer(lnet_nid_t nid)
618 {
619         struct lnet_peer_ni *lpni;
620         struct lnet_peer *lp = NULL;
621         int cpt;
622
623         cpt = lnet_net_lock_current();
624         lpni = lnet_find_peer_ni_locked(nid);
625         if (lpni) {
626                 lp = lpni->lpni_peer_net->lpn_peer;
627                 lnet_peer_addref_locked(lp);
628                 lnet_peer_ni_decref_locked(lpni);
629         }
630         lnet_net_unlock(cpt);
631
632         return lp;
633 }
634
635 struct lnet_peer_ni *
636 lnet_get_next_peer_ni_locked(struct lnet_peer *peer,
637                              struct lnet_peer_net *peer_net,
638                              struct lnet_peer_ni *prev)
639 {
640         struct lnet_peer_ni *lpni;
641         struct lnet_peer_net *net = peer_net;
642
643         if (!prev) {
644                 if (!net) {
645                         if (list_empty(&peer->lp_peer_nets))
646                                 return NULL;
647
648                         net = list_entry(peer->lp_peer_nets.next,
649                                          struct lnet_peer_net,
650                                          lpn_peer_nets);
651                 }
652                 lpni = list_entry(net->lpn_peer_nis.next, struct lnet_peer_ni,
653                                   lpni_peer_nis);
654
655                 return lpni;
656         }
657
658         if (prev->lpni_peer_nis.next == &prev->lpni_peer_net->lpn_peer_nis) {
659                 /*
660                  * if you reached the end of the peer ni list and the peer
661                  * net is specified then there are no more peer nis in that
662                  * net.
663                  */
664                 if (net)
665                         return NULL;
666
667                 /*
668                  * we reached the end of this net ni list. move to the
669                  * next net
670                  */
671                 if (prev->lpni_peer_net->lpn_peer_nets.next ==
672                     &peer->lp_peer_nets)
673                         /* no more nets and no more NIs. */
674                         return NULL;
675
676                 /* get the next net */
677                 net = list_entry(prev->lpni_peer_net->lpn_peer_nets.next,
678                                  struct lnet_peer_net,
679                                  lpn_peer_nets);
680                 /* get the ni on it */
681                 lpni = list_entry(net->lpn_peer_nis.next, struct lnet_peer_ni,
682                                   lpni_peer_nis);
683
684                 return lpni;
685         }
686
687         /* there are more nis left */
688         lpni = list_entry(prev->lpni_peer_nis.next,
689                           struct lnet_peer_ni, lpni_peer_nis);
690
691         return lpni;
692 }
693
694 /* Call with the ln_api_mutex held */
695 int
696 lnet_get_peer_list(__u32 *countp, __u32 *sizep, lnet_process_id_t __user *ids)
697 {
698         lnet_process_id_t id;
699         struct lnet_peer_table *ptable;
700         struct lnet_peer *lp;
701         __u32 count = 0;
702         __u32 size = 0;
703         int lncpt;
704         int cpt;
705         __u32 i;
706         int rc;
707
708         rc = -ESHUTDOWN;
709         if (the_lnet.ln_state != LNET_STATE_RUNNING)
710                 goto done;
711
712         lncpt = cfs_percpt_number(the_lnet.ln_peer_tables);
713
714         /*
715          * Count the number of peers, and return E2BIG if the buffer
716          * is too small. We'll also return the desired size.
717          */
718         rc = -E2BIG;
719         for (cpt = 0; cpt < lncpt; cpt++) {
720                 ptable = the_lnet.ln_peer_tables[cpt];
721                 count += ptable->pt_peers;
722         }
723         size = count * sizeof(*ids);
724         if (size > *sizep)
725                 goto done;
726
727         /*
728          * Walk the peer lists and copy out the primary nids.
729          * This is safe because the peer lists are only modified
730          * while the ln_api_mutex is held. So we don't need to
731          * hold the lnet_net_lock as well, and can therefore
732          * directly call copy_to_user().
733          */
734         rc = -EFAULT;
735         memset(&id, 0, sizeof(id));
736         id.pid = LNET_PID_LUSTRE;
737         i = 0;
738         for (cpt = 0; cpt < lncpt; cpt++) {
739                 ptable = the_lnet.ln_peer_tables[cpt];
740                 list_for_each_entry(lp, &ptable->pt_peer_list, lp_peer_list) {
741                         if (i >= count)
742                                 goto done;
743                         id.nid = lp->lp_primary_nid;
744                         if (copy_to_user(&ids[i], &id, sizeof(id)))
745                                 goto done;
746                         i++;
747                 }
748         }
749         rc = 0;
750 done:
751         *countp = count;
752         *sizep = size;
753         return rc;
754 }
755
756 /*
757  * Start pushes to peers that need to be updated for a configuration
758  * change on this node.
759  */
760 void
761 lnet_push_update_to_peers(int force)
762 {
763         struct lnet_peer_table *ptable;
764         struct lnet_peer *lp;
765         int lncpt;
766         int cpt;
767
768         lnet_net_lock(LNET_LOCK_EX);
769         lncpt = cfs_percpt_number(the_lnet.ln_peer_tables);
770         for (cpt = 0; cpt < lncpt; cpt++) {
771                 ptable = the_lnet.ln_peer_tables[cpt];
772                 list_for_each_entry(lp, &ptable->pt_peer_list, lp_peer_list) {
773                         if (force) {
774                                 spin_lock(&lp->lp_lock);
775                                 if (lp->lp_state & LNET_PEER_MULTI_RAIL)
776                                         lp->lp_state |= LNET_PEER_FORCE_PUSH;
777                                 spin_unlock(&lp->lp_lock);
778                         }
779                         if (lnet_peer_needs_push(lp))
780                                 lnet_peer_queue_for_discovery(lp);
781                 }
782         }
783         lnet_net_unlock(LNET_LOCK_EX);
784         wake_up(&the_lnet.ln_dc_waitq);
785 }
786
787 /*
788  * Test whether a ni is a preferred ni for this peer_ni, e.g, whether
789  * this is a preferred point-to-point path. Call with lnet_net_lock in
790  * shared mmode.
791  */
792 bool
793 lnet_peer_is_pref_nid_locked(struct lnet_peer_ni *lpni, lnet_nid_t nid)
794 {
795         int i;
796
797         if (lpni->lpni_pref_nnids == 0)
798                 return false;
799         if (lpni->lpni_pref_nnids == 1)
800                 return lpni->lpni_pref.nid == nid;
801         for (i = 0; i < lpni->lpni_pref_nnids; i++) {
802                 if (lpni->lpni_pref.nids[i] == nid)
803                         return true;
804         }
805         return false;
806 }
807
808 /*
809  * Set a single ni as preferred, provided no preferred ni is already
810  * defined. Only to be used for non-multi-rail peer_ni.
811  */
812 int
813 lnet_peer_ni_set_non_mr_pref_nid(struct lnet_peer_ni *lpni, lnet_nid_t nid)
814 {
815         int rc = 0;
816
817         spin_lock(&lpni->lpni_lock);
818         if (nid == LNET_NID_ANY) {
819                 rc = -EINVAL;
820         } else if (lpni->lpni_pref_nnids > 0) {
821                 rc = -EPERM;
822         } else if (lpni->lpni_pref_nnids == 0) {
823                 lpni->lpni_pref.nid = nid;
824                 lpni->lpni_pref_nnids = 1;
825                 lpni->lpni_state |= LNET_PEER_NI_NON_MR_PREF;
826         }
827         spin_unlock(&lpni->lpni_lock);
828
829         CDEBUG(D_NET, "peer %s nid %s: %d\n",
830                libcfs_nid2str(lpni->lpni_nid), libcfs_nid2str(nid), rc);
831         return rc;
832 }
833
834 /*
835  * Clear the preferred NID from a non-multi-rail peer_ni, provided
836  * this preference was set by lnet_peer_ni_set_non_mr_pref_nid().
837  */
838 int
839 lnet_peer_ni_clr_non_mr_pref_nid(struct lnet_peer_ni *lpni)
840 {
841         int rc = 0;
842
843         spin_lock(&lpni->lpni_lock);
844         if (lpni->lpni_state & LNET_PEER_NI_NON_MR_PREF) {
845                 lpni->lpni_pref_nnids = 0;
846                 lpni->lpni_state &= ~LNET_PEER_NI_NON_MR_PREF;
847         } else if (lpni->lpni_pref_nnids == 0) {
848                 rc = -ENOENT;
849         } else {
850                 rc = -EPERM;
851         }
852         spin_unlock(&lpni->lpni_lock);
853
854         CDEBUG(D_NET, "peer %s: %d\n",
855                libcfs_nid2str(lpni->lpni_nid), rc);
856         return rc;
857 }
858
859 /*
860  * Clear the preferred NIDs from a non-multi-rail peer.
861  */
862 void
863 lnet_peer_clr_non_mr_pref_nids(struct lnet_peer *lp)
864 {
865         struct lnet_peer_ni *lpni = NULL;
866
867         while ((lpni = lnet_get_next_peer_ni_locked(lp, NULL, lpni)) != NULL)
868                 lnet_peer_ni_clr_non_mr_pref_nid(lpni);
869 }
870
871 int
872 lnet_peer_add_pref_nid(struct lnet_peer_ni *lpni, lnet_nid_t nid)
873 {
874         lnet_nid_t *nids = NULL;
875         lnet_nid_t *oldnids = NULL;
876         struct lnet_peer *lp = lpni->lpni_peer_net->lpn_peer;
877         int size;
878         int i;
879         int rc = 0;
880
881         if (nid == LNET_NID_ANY) {
882                 rc = -EINVAL;
883                 goto out;
884         }
885
886         if (lpni->lpni_pref_nnids == 1 && lpni->lpni_pref.nid == nid) {
887                 rc = -EEXIST;
888                 goto out;
889         }
890
891         /* A non-MR node may have only one preferred NI per peer_ni */
892         if (lpni->lpni_pref_nnids > 0) {
893                 if (!(lp->lp_state & LNET_PEER_MULTI_RAIL)) {
894                         rc = -EPERM;
895                         goto out;
896                 }
897         }
898
899         if (lpni->lpni_pref_nnids != 0) {
900                 size = sizeof(*nids) * (lpni->lpni_pref_nnids + 1);
901                 LIBCFS_CPT_ALLOC(nids, lnet_cpt_table(), lpni->lpni_cpt, size);
902                 if (!nids) {
903                         rc = -ENOMEM;
904                         goto out;
905                 }
906                 for (i = 0; i < lpni->lpni_pref_nnids; i++) {
907                         if (lpni->lpni_pref.nids[i] == nid) {
908                                 LIBCFS_FREE(nids, size);
909                                 rc = -EEXIST;
910                                 goto out;
911                         }
912                         nids[i] = lpni->lpni_pref.nids[i];
913                 }
914                 nids[i] = nid;
915         }
916
917         lnet_net_lock(LNET_LOCK_EX);
918         spin_lock(&lpni->lpni_lock);
919         if (lpni->lpni_pref_nnids == 0) {
920                 lpni->lpni_pref.nid = nid;
921         } else {
922                 oldnids = lpni->lpni_pref.nids;
923                 lpni->lpni_pref.nids = nids;
924         }
925         lpni->lpni_pref_nnids++;
926         lpni->lpni_state &= ~LNET_PEER_NI_NON_MR_PREF;
927         spin_unlock(&lpni->lpni_lock);
928         lnet_net_unlock(LNET_LOCK_EX);
929
930         if (oldnids) {
931                 size = sizeof(*nids) * (lpni->lpni_pref_nnids - 1);
932                 LIBCFS_FREE(oldnids, sizeof(*oldnids) * size);
933         }
934 out:
935         if (rc == -EEXIST && (lpni->lpni_state & LNET_PEER_NI_NON_MR_PREF)) {
936                 spin_lock(&lpni->lpni_lock);
937                 lpni->lpni_state &= ~LNET_PEER_NI_NON_MR_PREF;
938                 spin_unlock(&lpni->lpni_lock);
939         }
940         CDEBUG(D_NET, "peer %s nid %s: %d\n",
941                libcfs_nid2str(lp->lp_primary_nid), libcfs_nid2str(nid), rc);
942         return rc;
943 }
944
945 int
946 lnet_peer_del_pref_nid(struct lnet_peer_ni *lpni, lnet_nid_t nid)
947 {
948         lnet_nid_t *nids = NULL;
949         lnet_nid_t *oldnids = NULL;
950         struct lnet_peer *lp = lpni->lpni_peer_net->lpn_peer;
951         int size;
952         int i, j;
953         int rc = 0;
954
955         if (lpni->lpni_pref_nnids == 0) {
956                 rc = -ENOENT;
957                 goto out;
958         }
959
960         if (lpni->lpni_pref_nnids == 1) {
961                 if (lpni->lpni_pref.nid != nid) {
962                         rc = -ENOENT;
963                         goto out;
964                 }
965         } else if (lpni->lpni_pref_nnids == 2) {
966                 if (lpni->lpni_pref.nids[0] != nid &&
967                     lpni->lpni_pref.nids[1] != nid) {
968                         rc = -ENOENT;
969                         goto out;
970                 }
971         } else {
972                 size = sizeof(*nids) * (lpni->lpni_pref_nnids - 1);
973                 LIBCFS_CPT_ALLOC(nids, lnet_cpt_table(), lpni->lpni_cpt, size);
974                 if (!nids) {
975                         rc = -ENOMEM;
976                         goto out;
977                 }
978                 for (i = 0, j = 0; i < lpni->lpni_pref_nnids; i++) {
979                         if (lpni->lpni_pref.nids[i] != nid)
980                                 continue;
981                         nids[j++] = lpni->lpni_pref.nids[i];
982                 }
983                 /* Check if we actually removed a nid. */
984                 if (j == lpni->lpni_pref_nnids) {
985                         LIBCFS_FREE(nids, size);
986                         rc = -ENOENT;
987                         goto out;
988                 }
989         }
990
991         lnet_net_lock(LNET_LOCK_EX);
992         spin_lock(&lpni->lpni_lock);
993         if (lpni->lpni_pref_nnids == 1) {
994                 lpni->lpni_pref.nid = LNET_NID_ANY;
995         } else if (lpni->lpni_pref_nnids == 2) {
996                 oldnids = lpni->lpni_pref.nids;
997                 if (oldnids[0] == nid)
998                         lpni->lpni_pref.nid = oldnids[1];
999                 else
1000                         lpni->lpni_pref.nid = oldnids[2];
1001         } else {
1002                 oldnids = lpni->lpni_pref.nids;
1003                 lpni->lpni_pref.nids = nids;
1004         }
1005         lpni->lpni_pref_nnids--;
1006         lpni->lpni_state &= ~LNET_PEER_NI_NON_MR_PREF;
1007         spin_unlock(&lpni->lpni_lock);
1008         lnet_net_unlock(LNET_LOCK_EX);
1009
1010         if (oldnids) {
1011                 size = sizeof(*nids) * (lpni->lpni_pref_nnids + 1);
1012                 LIBCFS_FREE(oldnids, sizeof(*oldnids) * size);
1013         }
1014 out:
1015         CDEBUG(D_NET, "peer %s nid %s: %d\n",
1016                libcfs_nid2str(lp->lp_primary_nid), libcfs_nid2str(nid), rc);
1017         return rc;
1018 }
1019
1020 lnet_nid_t
1021 lnet_peer_primary_nid_locked(lnet_nid_t nid)
1022 {
1023         struct lnet_peer_ni *lpni;
1024         lnet_nid_t primary_nid = nid;
1025
1026         lpni = lnet_find_peer_ni_locked(nid);
1027         if (lpni) {
1028                 primary_nid = lpni->lpni_peer_net->lpn_peer->lp_primary_nid;
1029                 lnet_peer_ni_decref_locked(lpni);
1030         }
1031
1032         return primary_nid;
1033 }
1034
1035 lnet_nid_t
1036 LNetPrimaryNID(lnet_nid_t nid)
1037 {
1038         struct lnet_peer *lp;
1039         struct lnet_peer_ni *lpni;
1040         lnet_nid_t primary_nid = nid;
1041         int rc = 0;
1042         int cpt;
1043
1044         cpt = lnet_net_lock_current();
1045         lpni = lnet_nid2peerni_locked(nid, LNET_NID_ANY, cpt);
1046         if (IS_ERR(lpni)) {
1047                 rc = PTR_ERR(lpni);
1048                 goto out_unlock;
1049         }
1050         lp = lpni->lpni_peer_net->lpn_peer;
1051         while (!lnet_peer_is_uptodate(lp)) {
1052                 rc = lnet_discover_peer_locked(lpni, cpt, true);
1053                 if (rc)
1054                         goto out_decref;
1055                 lp = lpni->lpni_peer_net->lpn_peer;
1056         }
1057         primary_nid = lp->lp_primary_nid;
1058 out_decref:
1059         lnet_peer_ni_decref_locked(lpni);
1060 out_unlock:
1061         lnet_net_unlock(cpt);
1062
1063         CDEBUG(D_NET, "NID %s primary NID %s rc %d\n", libcfs_nid2str(nid),
1064                libcfs_nid2str(primary_nid), rc);
1065         return primary_nid;
1066 }
1067 EXPORT_SYMBOL(LNetPrimaryNID);
1068
1069 struct lnet_peer_net *
1070 lnet_peer_get_net_locked(struct lnet_peer *peer, __u32 net_id)
1071 {
1072         struct lnet_peer_net *peer_net;
1073         list_for_each_entry(peer_net, &peer->lp_peer_nets, lpn_peer_nets) {
1074                 if (peer_net->lpn_net_id == net_id)
1075                         return peer_net;
1076         }
1077         return NULL;
1078 }
1079
1080 /*
1081  * Attach a peer_ni to a peer_net and peer. This function assumes
1082  * peer_ni is not already attached to the peer_net/peer. The peer_ni
1083  * may be attached to a different peer, in which case it will be
1084  * properly detached first. The whole operation is done atomically.
1085  *
1086  * Always returns 0.  This is the last function called from functions
1087  * that do return an int, so returning 0 here allows the compiler to
1088  * do a tail call.
1089  */
1090 static int
1091 lnet_peer_attach_peer_ni(struct lnet_peer *lp,
1092                                 struct lnet_peer_net *lpn,
1093                                 struct lnet_peer_ni *lpni,
1094                                 unsigned flags)
1095 {
1096         struct lnet_peer_table *ptable;
1097
1098         /* Install the new peer_ni */
1099         lnet_net_lock(LNET_LOCK_EX);
1100         /* Add peer_ni to global peer table hash, if necessary. */
1101         if (list_empty(&lpni->lpni_hashlist)) {
1102                 int hash = lnet_nid2peerhash(lpni->lpni_nid);
1103
1104                 ptable = the_lnet.ln_peer_tables[lpni->lpni_cpt];
1105                 list_add_tail(&lpni->lpni_hashlist, &ptable->pt_hash[hash]);
1106                 ptable->pt_version++;
1107                 ptable->pt_number++;
1108                 /* This is the 1st refcount on lpni. */
1109                 atomic_inc(&lpni->lpni_refcount);
1110         }
1111
1112         /* Detach the peer_ni from an existing peer, if necessary. */
1113         if (lpni->lpni_peer_net) {
1114                 LASSERT(lpni->lpni_peer_net != lpn);
1115                 LASSERT(lpni->lpni_peer_net->lpn_peer != lp);
1116                 lnet_peer_detach_peer_ni_locked(lpni);
1117                 lnet_peer_net_decref_locked(lpni->lpni_peer_net);
1118                 lpni->lpni_peer_net = NULL;
1119         }
1120
1121         /* Add peer_ni to peer_net */
1122         lpni->lpni_peer_net = lpn;
1123         list_add_tail(&lpni->lpni_peer_nis, &lpn->lpn_peer_nis);
1124         lnet_peer_net_addref_locked(lpn);
1125
1126         /* Add peer_net to peer */
1127         if (!lpn->lpn_peer) {
1128                 lpn->lpn_peer = lp;
1129                 list_add_tail(&lpn->lpn_peer_nets, &lp->lp_peer_nets);
1130                 lnet_peer_addref_locked(lp);
1131         }
1132
1133         /* Add peer to global peer list, if necessary */
1134         ptable = the_lnet.ln_peer_tables[lp->lp_cpt];
1135         if (list_empty(&lp->lp_peer_list)) {
1136                 list_add_tail(&lp->lp_peer_list, &ptable->pt_peer_list);
1137                 ptable->pt_peers++;
1138         }
1139
1140
1141         /* Update peer state */
1142         spin_lock(&lp->lp_lock);
1143         if (flags & LNET_PEER_CONFIGURED) {
1144                 if (!(lp->lp_state & LNET_PEER_CONFIGURED))
1145                         lp->lp_state |= LNET_PEER_CONFIGURED;
1146         }
1147         if (flags & LNET_PEER_MULTI_RAIL) {
1148                 if (!(lp->lp_state & LNET_PEER_MULTI_RAIL)) {
1149                         lp->lp_state |= LNET_PEER_MULTI_RAIL;
1150                         lnet_peer_clr_non_mr_pref_nids(lp);
1151                 }
1152         }
1153         spin_unlock(&lp->lp_lock);
1154
1155         lp->lp_nnis++;
1156         lnet_net_unlock(LNET_LOCK_EX);
1157
1158         CDEBUG(D_NET, "peer %s NID %s flags %#x\n",
1159                libcfs_nid2str(lp->lp_primary_nid),
1160                libcfs_nid2str(lpni->lpni_nid), flags);
1161
1162         return 0;
1163 }
1164
1165 /*
1166  * Create a new peer, with nid as its primary nid.
1167  *
1168  * Call with the lnet_api_mutex held.
1169  */
1170 static int
1171 lnet_peer_add(lnet_nid_t nid, unsigned flags)
1172 {
1173         struct lnet_peer *lp;
1174         struct lnet_peer_net *lpn;
1175         struct lnet_peer_ni *lpni;
1176         int rc = 0;
1177
1178         LASSERT(nid != LNET_NID_ANY);
1179
1180         /*
1181          * No need for the lnet_net_lock here, because the
1182          * lnet_api_mutex is held.
1183          */
1184         lpni = lnet_find_peer_ni_locked(nid);
1185         if (lpni) {
1186                 /* A peer with this NID already exists. */
1187                 lp = lpni->lpni_peer_net->lpn_peer;
1188                 lnet_peer_ni_decref_locked(lpni);
1189                 /*
1190                  * This is an error if the peer was configured and the
1191                  * primary NID differs or an attempt is made to change
1192                  * the Multi-Rail flag. Otherwise the assumption is
1193                  * that an existing peer is being modified.
1194                  */
1195                 if (lp->lp_state & LNET_PEER_CONFIGURED) {
1196                         if (lp->lp_primary_nid != nid)
1197                                 rc = -EEXIST;
1198                         else if ((lp->lp_state ^ flags) & LNET_PEER_MULTI_RAIL)
1199                                 rc = -EPERM;
1200                         goto out;
1201                 }
1202                 /* Delete and recreate as a configured peer. */
1203                 lnet_peer_del(lp);
1204         }
1205
1206         /* Create peer, peer_net, and peer_ni. */
1207         rc = -ENOMEM;
1208         lp = lnet_peer_alloc(nid);
1209         if (!lp)
1210                 goto out;
1211         lpn = lnet_peer_net_alloc(LNET_NIDNET(nid));
1212         if (!lpn)
1213                 goto out_free_lp;
1214         lpni = lnet_peer_ni_alloc(nid);
1215         if (!lpni)
1216                 goto out_free_lpn;
1217
1218         return lnet_peer_attach_peer_ni(lp, lpn, lpni, flags);
1219
1220 out_free_lpn:
1221         LIBCFS_FREE(lpn, sizeof(*lpn));
1222 out_free_lp:
1223         LIBCFS_FREE(lp, sizeof(*lp));
1224 out:
1225         CDEBUG(D_NET, "peer %s NID flags %#x: %d\n",
1226                libcfs_nid2str(nid), flags, rc);
1227         return rc;
1228 }
1229
1230 /*
1231  * Add a NID to a peer. Call with ln_api_mutex held.
1232  *
1233  * Error codes:
1234  *  -EPERM:    Non-DLC addition to a DLC-configured peer.
1235  *  -EEXIST:   The NID was configured by DLC for a different peer.
1236  *  -ENOMEM:   Out of memory.
1237  *  -ENOTUNIQ: Adding a second peer NID on a single network on a
1238  *             non-multi-rail peer.
1239  */
1240 static int
1241 lnet_peer_add_nid(struct lnet_peer *lp, lnet_nid_t nid, unsigned flags)
1242 {
1243         struct lnet_peer_net *lpn;
1244         struct lnet_peer_ni *lpni;
1245         int rc = 0;
1246
1247         LASSERT(lp);
1248         LASSERT(nid != LNET_NID_ANY);
1249
1250         /* A configured peer can only be updated through configuration. */
1251         if (!(flags & LNET_PEER_CONFIGURED)) {
1252                 if (lp->lp_state & LNET_PEER_CONFIGURED) {
1253                         rc = -EPERM;
1254                         goto out;
1255                 }
1256         }
1257
1258         /*
1259          * The MULTI_RAIL flag can be set but not cleared, because
1260          * that would leave the peer struct in an invalid state.
1261          */
1262         if (flags & LNET_PEER_MULTI_RAIL) {
1263                 spin_lock(&lp->lp_lock);
1264                 if (!(lp->lp_state & LNET_PEER_MULTI_RAIL)) {
1265                         lp->lp_state |= LNET_PEER_MULTI_RAIL;
1266                         lnet_peer_clr_non_mr_pref_nids(lp);
1267                 }
1268                 spin_unlock(&lp->lp_lock);
1269         } else if (lp->lp_state & LNET_PEER_MULTI_RAIL) {
1270                 rc = -EPERM;
1271                 goto out;
1272         }
1273
1274         lpni = lnet_find_peer_ni_locked(nid);
1275         if (lpni) {
1276                 /*
1277                  * A peer_ni already exists. This is only a problem if
1278                  * it is not connected to this peer and was configured
1279                  * by DLC.
1280                  */
1281                 lnet_peer_ni_decref_locked(lpni);
1282                 if (lpni->lpni_peer_net->lpn_peer == lp)
1283                         goto out;
1284                 if (lnet_peer_ni_is_configured(lpni)) {
1285                         rc = -EEXIST;
1286                         goto out;
1287                 }
1288                 /* If this is the primary NID, destroy the peer. */
1289                 if (lnet_peer_ni_is_primary(lpni)) {
1290                         lnet_peer_del(lpni->lpni_peer_net->lpn_peer);
1291                         lpni = lnet_peer_ni_alloc(nid);
1292                         if (!lpni) {
1293                                 rc = -ENOMEM;
1294                                 goto out;
1295                         }
1296                 }
1297         } else {
1298                 lpni = lnet_peer_ni_alloc(nid);
1299                 if (!lpni) {
1300                         rc = -ENOMEM;
1301                         goto out;
1302                 }
1303         }
1304
1305         /*
1306          * Get the peer_net. Check that we're not adding a second
1307          * peer_ni on a peer_net of a non-multi-rail peer.
1308          */
1309         lpn = lnet_peer_get_net_locked(lp, LNET_NIDNET(nid));
1310         if (!lpn) {
1311                 lpn = lnet_peer_net_alloc(LNET_NIDNET(nid));
1312                 if (!lpn) {
1313                         rc = -ENOMEM;
1314                         goto out_free_lpni;
1315                 }
1316         } else if (!(lp->lp_state & LNET_PEER_MULTI_RAIL)) {
1317                 rc = -ENOTUNIQ;
1318                 goto out_free_lpni;
1319         }
1320
1321         return lnet_peer_attach_peer_ni(lp, lpn, lpni, flags);
1322
1323 out_free_lpni:
1324         /* If the peer_ni was allocated above its peer_net pointer is NULL */
1325         if (!lpni->lpni_peer_net)
1326                 LIBCFS_FREE(lpni, sizeof(*lpni));
1327 out:
1328         CDEBUG(D_NET, "peer %s NID %s flags %#x: %d\n",
1329                libcfs_nid2str(lp->lp_primary_nid), libcfs_nid2str(nid),
1330                flags, rc);
1331         return rc;
1332 }
1333
1334 /*
1335  * Update the primary NID of a peer, if possible.
1336  *
1337  * Call with the lnet_api_mutex held.
1338  */
1339 static int
1340 lnet_peer_set_primary_nid(struct lnet_peer *lp, lnet_nid_t nid, unsigned flags)
1341 {
1342         lnet_nid_t old = lp->lp_primary_nid;
1343         int rc = 0;
1344
1345         if (lp->lp_primary_nid == nid)
1346                 goto out;
1347         rc = lnet_peer_add_nid(lp, nid, flags);
1348         if (rc)
1349                 goto out;
1350         lp->lp_primary_nid = nid;
1351 out:
1352         CDEBUG(D_NET, "peer %s NID %s: %d\n",
1353                libcfs_nid2str(old), libcfs_nid2str(nid), rc);
1354         return rc;
1355 }
1356
1357 /*
1358  * lpni creation initiated due to traffic either sending or receiving.
1359  */
1360 static int
1361 lnet_peer_ni_traffic_add(lnet_nid_t nid, lnet_nid_t pref)
1362 {
1363         struct lnet_peer *lp;
1364         struct lnet_peer_net *lpn;
1365         struct lnet_peer_ni *lpni;
1366         unsigned flags = 0;
1367         int rc = 0;
1368
1369         if (nid == LNET_NID_ANY) {
1370                 rc = -EINVAL;
1371                 goto out;
1372         }
1373
1374         /* lnet_net_lock is not needed here because ln_api_lock is held */
1375         lpni = lnet_find_peer_ni_locked(nid);
1376         if (lpni) {
1377                 /*
1378                  * We must have raced with another thread. Since we
1379                  * know next to nothing about a peer_ni created by
1380                  * traffic, we just assume everything is ok and
1381                  * return.
1382                  */
1383                 lnet_peer_ni_decref_locked(lpni);
1384                 goto out;
1385         }
1386
1387         /* Create peer, peer_net, and peer_ni. */
1388         rc = -ENOMEM;
1389         lp = lnet_peer_alloc(nid);
1390         if (!lp)
1391                 goto out;
1392         lpn = lnet_peer_net_alloc(LNET_NIDNET(nid));
1393         if (!lpn)
1394                 goto out_free_lp;
1395         lpni = lnet_peer_ni_alloc(nid);
1396         if (!lpni)
1397                 goto out_free_lpn;
1398         if (pref != LNET_NID_ANY)
1399                 lnet_peer_ni_set_non_mr_pref_nid(lpni, pref);
1400
1401         return lnet_peer_attach_peer_ni(lp, lpn, lpni, flags);
1402
1403 out_free_lpn:
1404         LIBCFS_FREE(lpn, sizeof(*lpn));
1405 out_free_lp:
1406         LIBCFS_FREE(lp, sizeof(*lp));
1407 out:
1408         CDEBUG(D_NET, "peer %s: %d\n", libcfs_nid2str(nid), rc);
1409         return rc;
1410 }
1411
1412 /*
1413  * Implementation of IOC_LIBCFS_ADD_PEER_NI.
1414  *
1415  * This API handles the following combinations:
1416  *   Create a peer with its primary NI if only the prim_nid is provided
1417  *   Add a NID to a peer identified by the prim_nid. The peer identified
1418  *   by the prim_nid must already exist.
1419  *   The peer being created may be non-MR.
1420  *
1421  * The caller must hold ln_api_mutex. This prevents the peer from
1422  * being created/modified/deleted by a different thread.
1423  */
1424 int
1425 lnet_add_peer_ni(lnet_nid_t prim_nid, lnet_nid_t nid, bool mr)
1426 {
1427         struct lnet_peer *lp = NULL;
1428         struct lnet_peer_ni *lpni;
1429         unsigned flags;
1430
1431         /* The prim_nid must always be specified */
1432         if (prim_nid == LNET_NID_ANY)
1433                 return -EINVAL;
1434
1435         flags = LNET_PEER_CONFIGURED;
1436         if (mr)
1437                 flags |= LNET_PEER_MULTI_RAIL;
1438
1439         /*
1440          * If nid isn't specified, we must create a new peer with
1441          * prim_nid as its primary nid.
1442          */
1443         if (nid == LNET_NID_ANY)
1444                 return lnet_peer_add(prim_nid, flags);
1445
1446         /* Look up the prim_nid, which must exist. */
1447         lpni = lnet_find_peer_ni_locked(prim_nid);
1448         if (!lpni)
1449                 return -ENOENT;
1450         lnet_peer_ni_decref_locked(lpni);
1451         lp = lpni->lpni_peer_net->lpn_peer;
1452
1453         /* Peer must have been configured. */
1454         if (!(lp->lp_state & LNET_PEER_CONFIGURED)) {
1455                 CDEBUG(D_NET, "peer %s was not configured\n",
1456                        libcfs_nid2str(prim_nid));
1457                 return -ENOENT;
1458         }
1459
1460         /* Primary NID must match */
1461         if (lp->lp_primary_nid != prim_nid) {
1462                 CDEBUG(D_NET, "prim_nid %s is not primary for peer %s\n",
1463                        libcfs_nid2str(prim_nid),
1464                        libcfs_nid2str(lp->lp_primary_nid));
1465                 return -ENODEV;
1466         }
1467
1468         /* Multi-Rail flag must match. */
1469         if ((lp->lp_state ^ flags) & LNET_PEER_MULTI_RAIL) {
1470                 CDEBUG(D_NET, "multi-rail state mismatch for peer %s\n",
1471                        libcfs_nid2str(prim_nid));
1472                 return -EPERM;
1473         }
1474
1475         return lnet_peer_add_nid(lp, nid, flags);
1476 }
1477
1478 /*
1479  * Implementation of IOC_LIBCFS_DEL_PEER_NI.
1480  *
1481  * This API handles the following combinations:
1482  *   Delete a NI from a peer if both prim_nid and nid are provided.
1483  *   Delete a peer if only prim_nid is provided.
1484  *   Delete a peer if its primary nid is provided.
1485  *
1486  * The caller must hold ln_api_mutex. This prevents the peer from
1487  * being modified/deleted by a different thread.
1488  */
1489 int
1490 lnet_del_peer_ni(lnet_nid_t prim_nid, lnet_nid_t nid)
1491 {
1492         struct lnet_peer *lp;
1493         struct lnet_peer_ni *lpni;
1494         unsigned flags;
1495
1496         if (prim_nid == LNET_NID_ANY)
1497                 return -EINVAL;
1498
1499         lpni = lnet_find_peer_ni_locked(prim_nid);
1500         if (!lpni)
1501                 return -ENOENT;
1502         lnet_peer_ni_decref_locked(lpni);
1503         lp = lpni->lpni_peer_net->lpn_peer;
1504
1505         if (prim_nid != lp->lp_primary_nid) {
1506                 CDEBUG(D_NET, "prim_nid %s is not primary for peer %s\n",
1507                        libcfs_nid2str(prim_nid),
1508                        libcfs_nid2str(lp->lp_primary_nid));
1509                 return -ENODEV;
1510         }
1511
1512         if (nid == LNET_NID_ANY || nid == lp->lp_primary_nid)
1513                 return lnet_peer_del(lp);
1514
1515         flags = LNET_PEER_CONFIGURED;
1516         if (lp->lp_state & LNET_PEER_MULTI_RAIL)
1517                 flags |= LNET_PEER_MULTI_RAIL;
1518
1519         return lnet_peer_del_nid(lp, nid, flags);
1520 }
1521
1522 void
1523 lnet_destroy_peer_ni_locked(struct lnet_peer_ni *lpni)
1524 {
1525         struct lnet_peer_table *ptable;
1526         struct lnet_peer_net *lpn;
1527
1528         CDEBUG(D_NET, "%p nid %s\n", lpni, libcfs_nid2str(lpni->lpni_nid));
1529
1530         LASSERT(atomic_read(&lpni->lpni_refcount) == 0);
1531         LASSERT(lpni->lpni_rtr_refcount == 0);
1532         LASSERT(list_empty(&lpni->lpni_txq));
1533         LASSERT(lpni->lpni_txqnob == 0);
1534
1535         lpn = lpni->lpni_peer_net;
1536         lpni->lpni_peer_net = NULL;
1537         lpni->lpni_net = NULL;
1538
1539         /* remove the peer ni from the zombie list */
1540         ptable = the_lnet.ln_peer_tables[lpni->lpni_cpt];
1541         spin_lock(&ptable->pt_zombie_lock);
1542         list_del_init(&lpni->lpni_hashlist);
1543         ptable->pt_zombies--;
1544         spin_unlock(&ptable->pt_zombie_lock);
1545
1546         if (lpni->lpni_pref_nnids > 1) {
1547                 LIBCFS_FREE(lpni->lpni_pref.nids,
1548                         sizeof(*lpni->lpni_pref.nids) * lpni->lpni_pref_nnids);
1549         }
1550         LIBCFS_FREE(lpni, sizeof(*lpni));
1551
1552         lnet_peer_net_decref_locked(lpn);
1553 }
1554
1555 struct lnet_peer_ni *
1556 lnet_nid2peerni_ex(lnet_nid_t nid, int cpt)
1557 {
1558         struct lnet_peer_ni *lpni = NULL;
1559         int rc;
1560
1561         if (the_lnet.ln_state != LNET_STATE_RUNNING)
1562                 return ERR_PTR(-ESHUTDOWN);
1563
1564         /*
1565          * find if a peer_ni already exists.
1566          * If so then just return that.
1567          */
1568         lpni = lnet_find_peer_ni_locked(nid);
1569         if (lpni)
1570                 return lpni;
1571
1572         lnet_net_unlock(cpt);
1573
1574         rc = lnet_peer_ni_traffic_add(nid, LNET_NID_ANY);
1575         if (rc) {
1576                 lpni = ERR_PTR(rc);
1577                 goto out_net_relock;
1578         }
1579
1580         lpni = lnet_find_peer_ni_locked(nid);
1581         LASSERT(lpni);
1582
1583 out_net_relock:
1584         lnet_net_lock(cpt);
1585
1586         return lpni;
1587 }
1588
1589 /*
1590  * Get a peer_ni for the given nid, create it if necessary. Takes a
1591  * hold on the peer_ni.
1592  */
1593 struct lnet_peer_ni *
1594 lnet_nid2peerni_locked(lnet_nid_t nid, lnet_nid_t pref, int cpt)
1595 {
1596         struct lnet_peer_ni *lpni = NULL;
1597         int rc;
1598
1599         if (the_lnet.ln_state != LNET_STATE_RUNNING)
1600                 return ERR_PTR(-ESHUTDOWN);
1601
1602         /*
1603          * find if a peer_ni already exists.
1604          * If so then just return that.
1605          */
1606         lpni = lnet_find_peer_ni_locked(nid);
1607         if (lpni)
1608                 return lpni;
1609
1610         /*
1611          * Slow path:
1612          * use the lnet_api_mutex to serialize the creation of the peer_ni
1613          * and the creation/deletion of the local ni/net. When a local ni is
1614          * created, if there exists a set of peer_nis on that network,
1615          * they need to be traversed and updated. When a local NI is
1616          * deleted, which could result in a network being deleted, then
1617          * all peer nis on that network need to be removed as well.
1618          *
1619          * Creation through traffic should also be serialized with
1620          * creation through DLC.
1621          */
1622         lnet_net_unlock(cpt);
1623         mutex_lock(&the_lnet.ln_api_mutex);
1624         /*
1625          * Shutdown is only set under the ln_api_lock, so a single
1626          * check here is sufficent.
1627          */
1628         if (the_lnet.ln_state != LNET_STATE_RUNNING) {
1629                 lpni = ERR_PTR(-ESHUTDOWN);
1630                 goto out_mutex_unlock;
1631         }
1632
1633         rc = lnet_peer_ni_traffic_add(nid, pref);
1634         if (rc) {
1635                 lpni = ERR_PTR(rc);
1636                 goto out_mutex_unlock;
1637         }
1638
1639         lpni = lnet_find_peer_ni_locked(nid);
1640         LASSERT(lpni);
1641
1642 out_mutex_unlock:
1643         mutex_unlock(&the_lnet.ln_api_mutex);
1644         lnet_net_lock(cpt);
1645
1646         /* Lock has been dropped, check again for shutdown. */
1647         if (the_lnet.ln_state != LNET_STATE_RUNNING) {
1648                 if (!IS_ERR(lpni))
1649                         lnet_peer_ni_decref_locked(lpni);
1650                 lpni = ERR_PTR(-ESHUTDOWN);
1651         }
1652
1653         return lpni;
1654 }
1655
1656 /*
1657  * Peer Discovery
1658  */
1659
1660 /*
1661  * Is a peer uptodate from the point of view of discovery?
1662  *
1663  * If it is currently being processed, obviously not.
1664  * A forced Ping or Push is also handled by the discovery thread.
1665  *
1666  * Otherwise look at whether the peer needs rediscovering.
1667  */
1668 bool
1669 lnet_peer_is_uptodate(struct lnet_peer *lp)
1670 {
1671         bool rc;
1672
1673         spin_lock(&lp->lp_lock);
1674         if (lp->lp_state & (LNET_PEER_DISCOVERING |
1675                             LNET_PEER_FORCE_PING |
1676                             LNET_PEER_FORCE_PUSH)) {
1677                 rc = false;
1678         } else if (lp->lp_state & LNET_PEER_NO_DISCOVERY) {
1679                 rc = true;
1680         } else if (lp->lp_state & LNET_PEER_REDISCOVER) {
1681                 if (lnet_peer_discovery_disabled)
1682                         rc = true;
1683                 else
1684                         rc = false;
1685         } else if (lnet_peer_needs_push(lp)) {
1686                 rc = false;
1687         } else if (lp->lp_state & LNET_PEER_DISCOVERED) {
1688                 if (lp->lp_state & LNET_PEER_NIDS_UPTODATE)
1689                         rc = true;
1690                 else
1691                         rc = false;
1692         } else {
1693                 rc = false;
1694         }
1695         spin_unlock(&lp->lp_lock);
1696
1697         return rc;
1698 }
1699
1700 /*
1701  * Queue a peer for the attention of the discovery thread.  Call with
1702  * lnet_net_lock/EX held. Returns 0 if the peer was queued, and
1703  * -EALREADY if the peer was already queued.
1704  */
1705 static int lnet_peer_queue_for_discovery(struct lnet_peer *lp)
1706 {
1707         int rc;
1708
1709         spin_lock(&lp->lp_lock);
1710         if (!(lp->lp_state & LNET_PEER_DISCOVERING))
1711                 lp->lp_state |= LNET_PEER_DISCOVERING;
1712         spin_unlock(&lp->lp_lock);
1713         if (list_empty(&lp->lp_dc_list)) {
1714                 lnet_peer_addref_locked(lp);
1715                 list_add_tail(&lp->lp_dc_list, &the_lnet.ln_dc_request);
1716                 wake_up(&the_lnet.ln_dc_waitq);
1717                 rc = 0;
1718         } else {
1719                 rc = -EALREADY;
1720         }
1721
1722         CDEBUG(D_NET, "Queue peer %s: %d\n",
1723                libcfs_nid2str(lp->lp_primary_nid), rc);
1724
1725         return rc;
1726 }
1727
1728 /*
1729  * Discovery of a peer is complete. Wake all waiters on the peer.
1730  * Call with lnet_net_lock/EX held.
1731  */
1732 static void lnet_peer_discovery_complete(struct lnet_peer *lp)
1733 {
1734         struct lnet_msg *msg = NULL;
1735         int rc = 0;
1736         struct list_head pending_msgs;
1737
1738         INIT_LIST_HEAD(&pending_msgs);
1739
1740         CDEBUG(D_NET, "Discovery complete. Dequeue peer %s\n",
1741                libcfs_nid2str(lp->lp_primary_nid));
1742
1743         list_del_init(&lp->lp_dc_list);
1744         list_splice_init(&lp->lp_dc_pendq, &pending_msgs);
1745         wake_up_all(&lp->lp_dc_waitq);
1746
1747         lnet_net_unlock(LNET_LOCK_EX);
1748
1749         /* iterate through all pending messages and send them again */
1750         list_for_each_entry(msg, &pending_msgs, msg_list) {
1751                 if (lp->lp_dc_error) {
1752                         lnet_finalize(msg, lp->lp_dc_error);
1753                         continue;
1754                 }
1755
1756                 CDEBUG(D_NET, "sending pending message %s to target %s\n",
1757                        lnet_msgtyp2str(msg->msg_type),
1758                        libcfs_id2str(msg->msg_target));
1759                 rc = lnet_send(msg->msg_src_nid_param, msg,
1760                                msg->msg_rtr_nid_param);
1761                 if (rc < 0) {
1762                         CNETERR("Error sending %s to %s: %d\n",
1763                                lnet_msgtyp2str(msg->msg_type),
1764                                libcfs_id2str(msg->msg_target), rc);
1765                         lnet_finalize(msg, rc);
1766                 }
1767         }
1768         lnet_net_lock(LNET_LOCK_EX);
1769         lnet_peer_decref_locked(lp);
1770 }
1771
1772 /*
1773  * Handle inbound push.
1774  * Like any event handler, called with lnet_res_lock/CPT held.
1775  */
1776 void lnet_peer_push_event(struct lnet_event *ev)
1777 {
1778         struct lnet_ping_buffer *pbuf = ev->md.user_ptr;
1779         struct lnet_peer *lp;
1780
1781         /* lnet_find_peer() adds a refcount */
1782         lp = lnet_find_peer(ev->source.nid);
1783         if (!lp) {
1784                 CERROR("Push Put from unknown %s (source %s)\n",
1785                        libcfs_nid2str(ev->initiator.nid),
1786                        libcfs_nid2str(ev->source.nid));
1787                 return;
1788         }
1789
1790         /* Ensure peer state remains consistent while we modify it. */
1791         spin_lock(&lp->lp_lock);
1792
1793         /*
1794          * If some kind of error happened the contents of the message
1795          * cannot be used. Clear the NIDS_UPTODATE and set the
1796          * FORCE_PING flag to trigger a ping.
1797          */
1798         if (ev->status) {
1799                 lp->lp_state &= ~LNET_PEER_NIDS_UPTODATE;
1800                 lp->lp_state |= LNET_PEER_FORCE_PING;
1801                 CDEBUG(D_NET, "Push Put error %d from %s (source %s)\n",
1802                        ev->status,
1803                        libcfs_nid2str(lp->lp_primary_nid),
1804                        libcfs_nid2str(ev->source.nid));
1805                 goto out;
1806         }
1807
1808         /*
1809          * A push with invalid or corrupted info. Clear the UPTODATE
1810          * flag to trigger a ping.
1811          */
1812         if (lnet_ping_info_validate(&pbuf->pb_info)) {
1813                 lp->lp_state &= ~LNET_PEER_NIDS_UPTODATE;
1814                 lp->lp_state |= LNET_PEER_FORCE_PING;
1815                 CDEBUG(D_NET, "Corrupted Push from %s\n",
1816                        libcfs_nid2str(lp->lp_primary_nid));
1817                 goto out;
1818         }
1819
1820         /*
1821          * Make sure we'll allocate the correct size ping buffer when
1822          * pinging the peer.
1823          */
1824         if (lp->lp_data_nnis < pbuf->pb_info.pi_nnis)
1825                 lp->lp_data_nnis = pbuf->pb_info.pi_nnis;
1826
1827         /*
1828          * A non-Multi-Rail peer is not supposed to be capable of
1829          * sending a push.
1830          */
1831         if (!(pbuf->pb_info.pi_features & LNET_PING_FEAT_MULTI_RAIL)) {
1832                 CERROR("Push from non-Multi-Rail peer %s dropped\n",
1833                        libcfs_nid2str(lp->lp_primary_nid));
1834                 goto out;
1835         }
1836
1837         /*
1838          * Check the MULTIRAIL flag. Complain if the peer was DLC
1839          * configured without it.
1840          */
1841         if (!(lp->lp_state & LNET_PEER_MULTI_RAIL)) {
1842                 if (lp->lp_state & LNET_PEER_CONFIGURED) {
1843                         CERROR("Push says %s is Multi-Rail, DLC says not\n",
1844                                libcfs_nid2str(lp->lp_primary_nid));
1845                 } else {
1846                         lp->lp_state |= LNET_PEER_MULTI_RAIL;
1847                         lnet_peer_clr_non_mr_pref_nids(lp);
1848                 }
1849         }
1850
1851         /*
1852          * The peer may have discovery disabled at its end. Set
1853          * NO_DISCOVERY as appropriate.
1854          */
1855         if (!(pbuf->pb_info.pi_features & LNET_PING_FEAT_DISCOVERY)) {
1856                 CDEBUG(D_NET, "Peer %s has discovery disabled\n",
1857                        libcfs_nid2str(lp->lp_primary_nid));
1858                 lp->lp_state |= LNET_PEER_NO_DISCOVERY;
1859         } else if (lp->lp_state & LNET_PEER_NO_DISCOVERY) {
1860                 CDEBUG(D_NET, "Peer %s has discovery enabled\n",
1861                        libcfs_nid2str(lp->lp_primary_nid));
1862                 lp->lp_state &= ~LNET_PEER_NO_DISCOVERY;
1863         }
1864
1865         /*
1866          * Check for truncation of the Put message. Clear the
1867          * NIDS_UPTODATE flag and set FORCE_PING to trigger a ping,
1868          * and tell discovery to allocate a bigger buffer.
1869          */
1870         if (pbuf->pb_nnis < pbuf->pb_info.pi_nnis) {
1871                 if (the_lnet.ln_push_target_nnis < pbuf->pb_info.pi_nnis)
1872                         the_lnet.ln_push_target_nnis = pbuf->pb_info.pi_nnis;
1873                 lp->lp_state &= ~LNET_PEER_NIDS_UPTODATE;
1874                 lp->lp_state |= LNET_PEER_FORCE_PING;
1875                 CDEBUG(D_NET, "Truncated Push from %s (%d nids)\n",
1876                        libcfs_nid2str(lp->lp_primary_nid),
1877                        pbuf->pb_info.pi_nnis);
1878                 goto out;
1879         }
1880
1881         /*
1882          * Check whether the Put data is stale. Stale data can just be
1883          * dropped.
1884          */
1885         if (pbuf->pb_info.pi_nnis > 1 &&
1886             lp->lp_primary_nid == pbuf->pb_info.pi_ni[1].ns_nid &&
1887             LNET_PING_BUFFER_SEQNO(pbuf) < lp->lp_peer_seqno) {
1888                 CDEBUG(D_NET, "Stale Push from %s: got %u have %u\n",
1889                        libcfs_nid2str(lp->lp_primary_nid),
1890                        LNET_PING_BUFFER_SEQNO(pbuf),
1891                        lp->lp_peer_seqno);
1892                 goto out;
1893         }
1894
1895         /*
1896          * Check whether the Put data is new, in which case we clear
1897          * the UPTODATE flag and prepare to process it.
1898          *
1899          * If the Put data is current, and the peer is UPTODATE then
1900          * we assome everything is all right and drop the data as
1901          * stale.
1902          */
1903         if (LNET_PING_BUFFER_SEQNO(pbuf) > lp->lp_peer_seqno) {
1904                 lp->lp_peer_seqno = LNET_PING_BUFFER_SEQNO(pbuf);
1905                 lp->lp_state &= ~LNET_PEER_NIDS_UPTODATE;
1906         } else if (lp->lp_state & LNET_PEER_NIDS_UPTODATE) {
1907                 CDEBUG(D_NET, "Stale Push from %s: got %u have %u\n",
1908                        libcfs_nid2str(lp->lp_primary_nid),
1909                        LNET_PING_BUFFER_SEQNO(pbuf),
1910                        lp->lp_peer_seqno);
1911                 goto out;
1912         }
1913
1914         /*
1915          * If there is data present that hasn't been processed yet,
1916          * we'll replace it if the Put contained newer data and it
1917          * fits. We're racing with a Ping or earlier Push in this
1918          * case.
1919          */
1920         if (lp->lp_state & LNET_PEER_DATA_PRESENT) {
1921                 if (LNET_PING_BUFFER_SEQNO(pbuf) >
1922                         LNET_PING_BUFFER_SEQNO(lp->lp_data) &&
1923                     pbuf->pb_info.pi_nnis <= lp->lp_data->pb_nnis) {
1924                         memcpy(&lp->lp_data->pb_info, &pbuf->pb_info,
1925                                LNET_PING_INFO_SIZE(pbuf->pb_info.pi_nnis));
1926                         CDEBUG(D_NET, "Ping/Push race from %s: %u vs %u\n",
1927                               libcfs_nid2str(lp->lp_primary_nid),
1928                               LNET_PING_BUFFER_SEQNO(pbuf),
1929                               LNET_PING_BUFFER_SEQNO(lp->lp_data));
1930                 }
1931                 goto out;
1932         }
1933
1934         /*
1935          * Allocate a buffer to copy the data. On a failure we drop
1936          * the Push and set FORCE_PING to force the discovery
1937          * thread to fix the problem by pinging the peer.
1938          */
1939         lp->lp_data = lnet_ping_buffer_alloc(lp->lp_data_nnis, GFP_ATOMIC);
1940         if (!lp->lp_data) {
1941                 lp->lp_state |= LNET_PEER_FORCE_PING;
1942                 CDEBUG(D_NET, "Cannot allocate Push buffer for %s %u\n",
1943                        libcfs_nid2str(lp->lp_primary_nid),
1944                        LNET_PING_BUFFER_SEQNO(pbuf));
1945                 goto out;
1946         }
1947
1948         /* Success */
1949         memcpy(&lp->lp_data->pb_info, &pbuf->pb_info,
1950                LNET_PING_INFO_SIZE(pbuf->pb_info.pi_nnis));
1951         lp->lp_state |= LNET_PEER_DATA_PRESENT;
1952         CDEBUG(D_NET, "Received Push %s %u\n",
1953                libcfs_nid2str(lp->lp_primary_nid),
1954                LNET_PING_BUFFER_SEQNO(pbuf));
1955
1956 out:
1957         /*
1958          * Queue the peer for discovery, and wake the discovery thread
1959          * if the peer was already queued, because its status changed.
1960          */
1961         spin_unlock(&lp->lp_lock);
1962         lnet_net_lock(LNET_LOCK_EX);
1963         if (lnet_peer_queue_for_discovery(lp))
1964                 wake_up(&the_lnet.ln_dc_waitq);
1965         /* Drop refcount from lookup */
1966         lnet_peer_decref_locked(lp);
1967         lnet_net_unlock(LNET_LOCK_EX);
1968 }
1969
1970 /*
1971  * Clear the discovery error state, unless we're already discovering
1972  * this peer, in which case the error is current.
1973  */
1974 static void lnet_peer_clear_discovery_error(struct lnet_peer *lp)
1975 {
1976         spin_lock(&lp->lp_lock);
1977         if (!(lp->lp_state & LNET_PEER_DISCOVERING))
1978                 lp->lp_dc_error = 0;
1979         spin_unlock(&lp->lp_lock);
1980 }
1981
1982 /*
1983  * Peer discovery slow path. The ln_api_mutex is held on entry, and
1984  * dropped/retaken within this function. An lnet_peer_ni is passed in
1985  * because discovery could tear down an lnet_peer.
1986  */
1987 int
1988 lnet_discover_peer_locked(struct lnet_peer_ni *lpni, int cpt, bool block)
1989 {
1990         DEFINE_WAIT(wait);
1991         struct lnet_peer *lp;
1992         int rc = 0;
1993
1994 again:
1995         lnet_net_unlock(cpt);
1996         lnet_net_lock(LNET_LOCK_EX);
1997         lp = lpni->lpni_peer_net->lpn_peer;
1998         lnet_peer_clear_discovery_error(lp);
1999
2000         /*
2001          * We're willing to be interrupted. The lpni can become a
2002          * zombie if we race with DLC, so we must check for that.
2003          */
2004         for (;;) {
2005                 prepare_to_wait(&lp->lp_dc_waitq, &wait, TASK_INTERRUPTIBLE);
2006                 if (signal_pending(current))
2007                         break;
2008                 if (the_lnet.ln_dc_state != LNET_DC_STATE_RUNNING)
2009                         break;
2010                 if (lp->lp_dc_error)
2011                         break;
2012                 if (lnet_peer_is_uptodate(lp))
2013                         break;
2014                 lnet_peer_queue_for_discovery(lp);
2015                 /*
2016                  * if caller requested a non-blocking operation then
2017                  * return immediately. Once discovery is complete then the
2018                  * peer ref will be decremented and any pending messages
2019                  * that were stopped due to discovery will be transmitted.
2020                  */
2021                 if (!block)
2022                         break;
2023
2024                 lnet_peer_addref_locked(lp);
2025                 lnet_net_unlock(LNET_LOCK_EX);
2026                 schedule();
2027                 finish_wait(&lp->lp_dc_waitq, &wait);
2028                 lnet_net_lock(LNET_LOCK_EX);
2029                 lnet_peer_decref_locked(lp);
2030                 /* Peer may have changed */
2031                 lp = lpni->lpni_peer_net->lpn_peer;
2032         }
2033         finish_wait(&lp->lp_dc_waitq, &wait);
2034
2035         lnet_net_unlock(LNET_LOCK_EX);
2036         lnet_net_lock(cpt);
2037
2038         if (signal_pending(current))
2039                 rc = -EINTR;
2040         else if (the_lnet.ln_dc_state != LNET_DC_STATE_RUNNING)
2041                 rc = -ESHUTDOWN;
2042         else if (lp->lp_dc_error)
2043                 rc = lp->lp_dc_error;
2044         else if (!block)
2045                 CDEBUG(D_NET, "non-blocking discovery\n");
2046         else if (!lnet_peer_is_uptodate(lp))
2047                 goto again;
2048
2049         CDEBUG(D_NET, "peer %s NID %s: %d. %s\n",
2050                (lp ? libcfs_nid2str(lp->lp_primary_nid) : "(none)"),
2051                libcfs_nid2str(lpni->lpni_nid), rc,
2052                (!block) ? "pending discovery" : "discovery complete");
2053
2054         return rc;
2055 }
2056
2057 /* Handle an incoming ack for a push. */
2058 static void
2059 lnet_discovery_event_ack(struct lnet_peer *lp, struct lnet_event *ev)
2060 {
2061         struct lnet_ping_buffer *pbuf;
2062
2063         pbuf = LNET_PING_INFO_TO_BUFFER(ev->md.start);
2064         spin_lock(&lp->lp_lock);
2065         lp->lp_state &= ~LNET_PEER_PUSH_SENT;
2066         lp->lp_push_error = ev->status;
2067         if (ev->status)
2068                 lp->lp_state |= LNET_PEER_PUSH_FAILED;
2069         else
2070                 lp->lp_node_seqno = LNET_PING_BUFFER_SEQNO(pbuf);
2071         spin_unlock(&lp->lp_lock);
2072
2073         CDEBUG(D_NET, "peer %s ev->status %d\n",
2074                libcfs_nid2str(lp->lp_primary_nid), ev->status);
2075 }
2076
2077 /* Handle a Reply message. This is the reply to a Ping message. */
2078 static void
2079 lnet_discovery_event_reply(struct lnet_peer *lp, struct lnet_event *ev)
2080 {
2081         struct lnet_ping_buffer *pbuf;
2082         int rc;
2083
2084         spin_lock(&lp->lp_lock);
2085
2086         /*
2087          * If some kind of error happened the contents of message
2088          * cannot be used. Set PING_FAILED to trigger a retry.
2089          */
2090         if (ev->status) {
2091                 lp->lp_state |= LNET_PEER_PING_FAILED;
2092                 lp->lp_ping_error = ev->status;
2093                 CDEBUG(D_NET, "Ping Reply error %d from %s (source %s)\n",
2094                        ev->status,
2095                        libcfs_nid2str(lp->lp_primary_nid),
2096                        libcfs_nid2str(ev->source.nid));
2097                 goto out;
2098         }
2099
2100         pbuf = LNET_PING_INFO_TO_BUFFER(ev->md.start);
2101         if (pbuf->pb_info.pi_magic == __swab32(LNET_PROTO_PING_MAGIC))
2102                 lnet_swap_pinginfo(pbuf);
2103
2104         /*
2105          * A reply with invalid or corrupted info. Set PING_FAILED to
2106          * trigger a retry.
2107          */
2108         rc = lnet_ping_info_validate(&pbuf->pb_info);
2109         if (rc) {
2110                 lp->lp_state |= LNET_PEER_PING_FAILED;
2111                 lp->lp_ping_error = 0;
2112                 CDEBUG(D_NET, "Corrupted Ping Reply from %s: %d\n",
2113                        libcfs_nid2str(lp->lp_primary_nid), rc);
2114                 goto out;
2115         }
2116
2117         /*
2118          * Update the MULTI_RAIL flag based on the reply. If the peer
2119          * was configured with DLC then the setting should match what
2120          * DLC put in.
2121          */
2122         if (pbuf->pb_info.pi_features & LNET_PING_FEAT_MULTI_RAIL) {
2123                 if (lp->lp_state & LNET_PEER_MULTI_RAIL) {
2124                         /* Everything's fine */
2125                 } else if (lp->lp_state & LNET_PEER_CONFIGURED) {
2126                         CWARN("Reply says %s is Multi-Rail, DLC says not\n",
2127                               libcfs_nid2str(lp->lp_primary_nid));
2128                 } else {
2129                         lp->lp_state |= LNET_PEER_MULTI_RAIL;
2130                         lnet_peer_clr_non_mr_pref_nids(lp);
2131                 }
2132         } else if (lp->lp_state & LNET_PEER_MULTI_RAIL) {
2133                 if (lp->lp_state & LNET_PEER_CONFIGURED) {
2134                         CWARN("DLC says %s is Multi-Rail, Reply says not\n",
2135                               libcfs_nid2str(lp->lp_primary_nid));
2136                 } else {
2137                         CERROR("Multi-Rail state vanished from %s\n",
2138                                libcfs_nid2str(lp->lp_primary_nid));
2139                         lp->lp_state &= ~LNET_PEER_MULTI_RAIL;
2140                 }
2141         }
2142
2143         /*
2144          * Make sure we'll allocate the correct size ping buffer when
2145          * pinging the peer.
2146          */
2147         if (lp->lp_data_nnis < pbuf->pb_info.pi_nnis)
2148                 lp->lp_data_nnis = pbuf->pb_info.pi_nnis;
2149
2150         /*
2151          * The peer may have discovery disabled at its end. Set
2152          * NO_DISCOVERY as appropriate.
2153          */
2154         if (!(pbuf->pb_info.pi_features & LNET_PING_FEAT_DISCOVERY)) {
2155                 CDEBUG(D_NET, "Peer %s has discovery disabled\n",
2156                        libcfs_nid2str(lp->lp_primary_nid));
2157                 lp->lp_state |= LNET_PEER_NO_DISCOVERY;
2158         } else if (lp->lp_state & LNET_PEER_NO_DISCOVERY) {
2159                 CDEBUG(D_NET, "Peer %s has discovery enabled\n",
2160                        libcfs_nid2str(lp->lp_primary_nid));
2161                 lp->lp_state &= ~LNET_PEER_NO_DISCOVERY;
2162         }
2163
2164         /*
2165          * Check for truncation of the Reply. Clear PING_SENT and set
2166          * PING_FAILED to trigger a retry.
2167          */
2168         if (pbuf->pb_nnis < pbuf->pb_info.pi_nnis) {
2169                 if (the_lnet.ln_push_target_nnis < pbuf->pb_info.pi_nnis)
2170                         the_lnet.ln_push_target_nnis = pbuf->pb_info.pi_nnis;
2171                 lp->lp_state |= LNET_PEER_PING_FAILED;
2172                 lp->lp_ping_error = 0;
2173                 CDEBUG(D_NET, "Truncated Reply from %s (%d nids)\n",
2174                        libcfs_nid2str(lp->lp_primary_nid),
2175                        pbuf->pb_info.pi_nnis);
2176                 goto out;
2177         }
2178
2179         /*
2180          * Check the sequence numbers in the reply. These are only
2181          * available if the reply came from a Multi-Rail peer.
2182          */
2183         if (pbuf->pb_info.pi_features & LNET_PING_FEAT_MULTI_RAIL &&
2184             pbuf->pb_info.pi_nnis > 1 &&
2185             lp->lp_primary_nid == pbuf->pb_info.pi_ni[1].ns_nid) {
2186                 if (LNET_PING_BUFFER_SEQNO(pbuf) < lp->lp_peer_seqno) {
2187                         CDEBUG(D_NET, "Stale Reply from %s: got %u have %u\n",
2188                                 libcfs_nid2str(lp->lp_primary_nid),
2189                                 LNET_PING_BUFFER_SEQNO(pbuf),
2190                                 lp->lp_peer_seqno);
2191                         goto out;
2192                 }
2193
2194                 if (LNET_PING_BUFFER_SEQNO(pbuf) > lp->lp_peer_seqno)
2195                         lp->lp_peer_seqno = LNET_PING_BUFFER_SEQNO(pbuf);
2196         }
2197
2198         /* We're happy with the state of the data in the buffer. */
2199         CDEBUG(D_NET, "peer %s data present %u\n",
2200                libcfs_nid2str(lp->lp_primary_nid), lp->lp_peer_seqno);
2201         if (lp->lp_state & LNET_PEER_DATA_PRESENT)
2202                 lnet_ping_buffer_decref(lp->lp_data);
2203         else
2204                 lp->lp_state |= LNET_PEER_DATA_PRESENT;
2205         lnet_ping_buffer_addref(pbuf);
2206         lp->lp_data = pbuf;
2207 out:
2208         lp->lp_state &= ~LNET_PEER_PING_SENT;
2209         spin_unlock(&lp->lp_lock);
2210 }
2211
2212 /*
2213  * Send event handling. Only matters for error cases, where we clean
2214  * up state on the peer and peer_ni that would otherwise be updated in
2215  * the REPLY event handler for a successful Ping, and the ACK event
2216  * handler for a successful Push.
2217  */
2218 static int
2219 lnet_discovery_event_send(struct lnet_peer *lp, struct lnet_event *ev)
2220 {
2221         int rc = 0;
2222
2223         if (!ev->status)
2224                 goto out;
2225
2226         spin_lock(&lp->lp_lock);
2227         if (ev->msg_type == LNET_MSG_GET) {
2228                 lp->lp_state &= ~LNET_PEER_PING_SENT;
2229                 lp->lp_state |= LNET_PEER_PING_FAILED;
2230                 lp->lp_ping_error = ev->status;
2231         } else { /* ev->msg_type == LNET_MSG_PUT */
2232                 lp->lp_state &= ~LNET_PEER_PUSH_SENT;
2233                 lp->lp_state |= LNET_PEER_PUSH_FAILED;
2234                 lp->lp_push_error = ev->status;
2235         }
2236         spin_unlock(&lp->lp_lock);
2237         rc = LNET_REDISCOVER_PEER;
2238 out:
2239         CDEBUG(D_NET, "%s Send to %s: %d\n",
2240                 (ev->msg_type == LNET_MSG_GET ? "Ping" : "Push"),
2241                 libcfs_nid2str(ev->target.nid), rc);
2242         return rc;
2243 }
2244
2245 /*
2246  * Unlink event handling. This event is only seen if a call to
2247  * LNetMDUnlink() caused the event to be unlinked. If this call was
2248  * made after the event was set up in LNetGet() or LNetPut() then we
2249  * assume the Ping or Push timed out.
2250  */
2251 static void
2252 lnet_discovery_event_unlink(struct lnet_peer *lp, struct lnet_event *ev)
2253 {
2254         spin_lock(&lp->lp_lock);
2255         /* We've passed through LNetGet() */
2256         if (lp->lp_state & LNET_PEER_PING_SENT) {
2257                 lp->lp_state &= ~LNET_PEER_PING_SENT;
2258                 lp->lp_state |= LNET_PEER_PING_FAILED;
2259                 lp->lp_ping_error = -ETIMEDOUT;
2260                 CDEBUG(D_NET, "Ping Unlink for message to peer %s\n",
2261                         libcfs_nid2str(lp->lp_primary_nid));
2262         }
2263         /* We've passed through LNetPut() */
2264         if (lp->lp_state & LNET_PEER_PUSH_SENT) {
2265                 lp->lp_state &= ~LNET_PEER_PUSH_SENT;
2266                 lp->lp_state |= LNET_PEER_PUSH_FAILED;
2267                 lp->lp_push_error = -ETIMEDOUT;
2268                 CDEBUG(D_NET, "Push Unlink for message to peer %s\n",
2269                         libcfs_nid2str(lp->lp_primary_nid));
2270         }
2271         spin_unlock(&lp->lp_lock);
2272 }
2273
2274 /*
2275  * Event handler for the discovery EQ.
2276  *
2277  * Called with lnet_res_lock(cpt) held. The cpt is the
2278  * lnet_cpt_of_cookie() of the md handle cookie.
2279  */
2280 static void lnet_discovery_event_handler(lnet_event_t *event)
2281 {
2282         struct lnet_peer *lp = event->md.user_ptr;
2283         struct lnet_ping_buffer *pbuf;
2284         int rc;
2285
2286         /* discovery needs to take another look */
2287         rc = LNET_REDISCOVER_PEER;
2288
2289         CDEBUG(D_NET, "Received event: %d\n", event->type);
2290
2291         switch (event->type) {
2292         case LNET_EVENT_ACK:
2293                 lnet_discovery_event_ack(lp, event);
2294                 break;
2295         case LNET_EVENT_REPLY:
2296                 lnet_discovery_event_reply(lp, event);
2297                 break;
2298         case LNET_EVENT_SEND:
2299                 /* Only send failure triggers a retry. */
2300                 rc = lnet_discovery_event_send(lp, event);
2301                 break;
2302         case LNET_EVENT_UNLINK:
2303                 /* LNetMDUnlink() was called */
2304                 lnet_discovery_event_unlink(lp, event);
2305                 break;
2306         default:
2307                 /* Invalid events. */
2308                 LBUG();
2309         }
2310         lnet_net_lock(LNET_LOCK_EX);
2311         if (event->unlinked) {
2312                 pbuf = LNET_PING_INFO_TO_BUFFER(event->md.start);
2313                 lnet_ping_buffer_decref(pbuf);
2314                 lnet_peer_decref_locked(lp);
2315         }
2316         if (rc == LNET_REDISCOVER_PEER) {
2317                 list_move_tail(&lp->lp_dc_list, &the_lnet.ln_dc_request);
2318                 wake_up(&the_lnet.ln_dc_waitq);
2319         }
2320         lnet_net_unlock(LNET_LOCK_EX);
2321 }
2322
2323 /*
2324  * Build a peer from incoming data.
2325  *
2326  * The NIDs in the incoming data are supposed to be structured as follows:
2327  *  - loopback
2328  *  - primary NID
2329  *  - other NIDs in same net
2330  *  - NIDs in second net
2331  *  - NIDs in third net
2332  *  - ...
2333  * This due to the way the list of NIDs in the data is created.
2334  *
2335  * Note that this function will mark the peer uptodate unless an
2336  * ENOMEM is encontered. All other errors are due to a conflict
2337  * between the DLC configuration and what discovery sees. We treat DLC
2338  * as binding, and therefore set the NIDS_UPTODATE flag to prevent the
2339  * peer from becoming stuck in discovery.
2340  */
2341 static int lnet_peer_merge_data(struct lnet_peer *lp,
2342                                 struct lnet_ping_buffer *pbuf)
2343 {
2344         struct lnet_peer_ni *lpni;
2345         lnet_nid_t *curnis = NULL;
2346         lnet_nid_t *addnis = NULL;
2347         lnet_nid_t *delnis = NULL;
2348         unsigned flags;
2349         int ncurnis;
2350         int naddnis;
2351         int ndelnis;
2352         int nnis = 0;
2353         int i;
2354         int j;
2355         int rc;
2356
2357         flags = LNET_PEER_DISCOVERED;
2358         if (pbuf->pb_info.pi_features & LNET_PING_FEAT_MULTI_RAIL)
2359                 flags |= LNET_PEER_MULTI_RAIL;
2360
2361         nnis = MAX(lp->lp_nnis, pbuf->pb_info.pi_nnis);
2362         LIBCFS_ALLOC(curnis, nnis * sizeof(lnet_nid_t));
2363         LIBCFS_ALLOC(addnis, nnis * sizeof(lnet_nid_t));
2364         LIBCFS_ALLOC(delnis, nnis * sizeof(lnet_nid_t));
2365         if (!curnis || !addnis || !delnis) {
2366                 rc = -ENOMEM;
2367                 goto out;
2368         }
2369         ncurnis = 0;
2370         naddnis = 0;
2371         ndelnis = 0;
2372
2373         /* Construct the list of NIDs present in peer. */
2374         lpni = NULL;
2375         while ((lpni = lnet_get_next_peer_ni_locked(lp, NULL, lpni)) != NULL)
2376                 curnis[ncurnis++] = lpni->lpni_nid;
2377
2378         /*
2379          * Check for NIDs in pbuf not present in curnis[].
2380          * The loop starts at 1 to skip the loopback NID.
2381          */
2382         for (i = 1; i < pbuf->pb_info.pi_nnis; i++) {
2383                 for (j = 0; j < ncurnis; j++)
2384                         if (pbuf->pb_info.pi_ni[i].ns_nid == curnis[j])
2385                                 break;
2386                 if (j == ncurnis)
2387                         addnis[naddnis++] = pbuf->pb_info.pi_ni[i].ns_nid;
2388         }
2389         /*
2390          * Check for NIDs in curnis[] not present in pbuf.
2391          * The nested loop starts at 1 to skip the loopback NID.
2392          *
2393          * But never add the loopback NID to delnis[]: if it is
2394          * present in curnis[] then this peer is for this node.
2395          */
2396         for (i = 0; i < ncurnis; i++) {
2397                 if (LNET_NETTYP(LNET_NIDNET(curnis[i])) == LOLND)
2398                         continue;
2399                 for (j = 1; j < pbuf->pb_info.pi_nnis; j++)
2400                         if (curnis[i] == pbuf->pb_info.pi_ni[j].ns_nid)
2401                                 break;
2402                 if (j == pbuf->pb_info.pi_nnis)
2403                         delnis[ndelnis++] = curnis[i];
2404         }
2405
2406         for (i = 0; i < naddnis; i++) {
2407                 rc = lnet_peer_add_nid(lp, addnis[i], flags);
2408                 if (rc) {
2409                         CERROR("Error adding NID %s to peer %s: %d\n",
2410                                libcfs_nid2str(addnis[i]),
2411                                libcfs_nid2str(lp->lp_primary_nid), rc);
2412                         if (rc == -ENOMEM)
2413                                 goto out;
2414                 }
2415         }
2416         for (i = 0; i < ndelnis; i++) {
2417                 rc = lnet_peer_del_nid(lp, delnis[i], flags);
2418                 if (rc) {
2419                         CERROR("Error deleting NID %s from peer %s: %d\n",
2420                                libcfs_nid2str(delnis[i]),
2421                                libcfs_nid2str(lp->lp_primary_nid), rc);
2422                         if (rc == -ENOMEM)
2423                                 goto out;
2424                 }
2425         }
2426         /*
2427          * Errors other than -ENOMEM are due to peers having been
2428          * configured with DLC. Ignore these because DLC overrides
2429          * Discovery.
2430          */
2431         rc = 0;
2432 out:
2433         LIBCFS_FREE(curnis, nnis * sizeof(lnet_nid_t));
2434         LIBCFS_FREE(addnis, nnis * sizeof(lnet_nid_t));
2435         LIBCFS_FREE(delnis, nnis * sizeof(lnet_nid_t));
2436         lnet_ping_buffer_decref(pbuf);
2437         CDEBUG(D_NET, "peer %s: %d\n", libcfs_nid2str(lp->lp_primary_nid), rc);
2438
2439         if (rc) {
2440                 spin_lock(&lp->lp_lock);
2441                 lp->lp_state &= ~LNET_PEER_NIDS_UPTODATE;
2442                 lp->lp_state |= LNET_PEER_FORCE_PING;
2443                 spin_unlock(&lp->lp_lock);
2444         }
2445         return rc;
2446 }
2447
2448 /*
2449  * The data in pbuf says lp is its primary peer, but the data was
2450  * received by a different peer. Try to update lp with the data.
2451  */
2452 static int
2453 lnet_peer_set_primary_data(struct lnet_peer *lp, struct lnet_ping_buffer *pbuf)
2454 {
2455         lnet_handle_md_t mdh;
2456
2457         /* Queue lp for discovery, and force it on the request queue. */
2458         lnet_net_lock(LNET_LOCK_EX);
2459         if (lnet_peer_queue_for_discovery(lp))
2460                 list_move(&lp->lp_dc_list, &the_lnet.ln_dc_request);
2461         lnet_net_unlock(LNET_LOCK_EX);
2462
2463         LNetInvalidateMDHandle(&mdh);
2464
2465         /*
2466          * Decide whether we can move the peer to the DATA_PRESENT state.
2467          *
2468          * We replace stale data for a multi-rail peer, repair PING_FAILED
2469          * status, and preempt FORCE_PING.
2470          *
2471          * If after that we have DATA_PRESENT, we merge it into this peer.
2472          */
2473         spin_lock(&lp->lp_lock);
2474         if (lp->lp_state & LNET_PEER_MULTI_RAIL) {
2475                 if (lp->lp_peer_seqno < LNET_PING_BUFFER_SEQNO(pbuf)) {
2476                         lp->lp_peer_seqno = LNET_PING_BUFFER_SEQNO(pbuf);
2477                 } else if (lp->lp_state & LNET_PEER_DATA_PRESENT) {
2478                         lp->lp_state &= ~LNET_PEER_DATA_PRESENT;
2479                         lnet_ping_buffer_decref(pbuf);
2480                         pbuf = lp->lp_data;
2481                         lp->lp_data = NULL;
2482                 }
2483         }
2484         if (lp->lp_state & LNET_PEER_DATA_PRESENT) {
2485                 lnet_ping_buffer_decref(lp->lp_data);
2486                 lp->lp_data = NULL;
2487                 lp->lp_state &= ~LNET_PEER_DATA_PRESENT;
2488         }
2489         if (lp->lp_state & LNET_PEER_PING_FAILED) {
2490                 mdh = lp->lp_ping_mdh;
2491                 LNetInvalidateMDHandle(&lp->lp_ping_mdh);
2492                 lp->lp_state &= ~LNET_PEER_PING_FAILED;
2493                 lp->lp_ping_error = 0;
2494         }
2495         if (lp->lp_state & LNET_PEER_FORCE_PING)
2496                 lp->lp_state &= ~LNET_PEER_FORCE_PING;
2497         lp->lp_state |= LNET_PEER_NIDS_UPTODATE;
2498         spin_unlock(&lp->lp_lock);
2499
2500         if (!LNetMDHandleIsInvalid(mdh))
2501                 LNetMDUnlink(mdh);
2502
2503         if (pbuf)
2504                 return lnet_peer_merge_data(lp, pbuf);
2505
2506         CDEBUG(D_NET, "peer %s\n", libcfs_nid2str(lp->lp_primary_nid));
2507         return 0;
2508 }
2509
2510 /*
2511  * Update a peer using the data received.
2512  */
2513 static int lnet_peer_data_present(struct lnet_peer *lp)
2514 __must_hold(&lp->lp_lock)
2515 {
2516         struct lnet_ping_buffer *pbuf;
2517         struct lnet_peer_ni *lpni;
2518         lnet_nid_t nid = LNET_NID_ANY;
2519         unsigned flags;
2520         int rc = 0;
2521
2522         pbuf = lp->lp_data;
2523         lp->lp_data = NULL;
2524         lp->lp_state &= ~LNET_PEER_DATA_PRESENT;
2525         lp->lp_state |= LNET_PEER_NIDS_UPTODATE;
2526         spin_unlock(&lp->lp_lock);
2527
2528         /*
2529          * Modifications of peer structures are done while holding the
2530          * ln_api_mutex. A global lock is required because we may be
2531          * modifying multiple peer structures, and a mutex greatly
2532          * simplifies memory management.
2533          *
2534          * The actual changes to the data structures must also protect
2535          * against concurrent lookups, for which the lnet_net_lock in
2536          * LNET_LOCK_EX mode is used.
2537          */
2538         mutex_lock(&the_lnet.ln_api_mutex);
2539         if (the_lnet.ln_state != LNET_STATE_RUNNING) {
2540                 rc = -ESHUTDOWN;
2541                 goto out;
2542         }
2543
2544         /*
2545          * If this peer is not on the peer list then it is being torn
2546          * down, and our reference count may be all that is keeping it
2547          * alive. Don't do any work on it.
2548          */
2549         if (list_empty(&lp->lp_peer_list))
2550                 goto out;
2551
2552         flags = LNET_PEER_DISCOVERED;
2553         if (pbuf->pb_info.pi_features & LNET_PING_FEAT_MULTI_RAIL)
2554                 flags |= LNET_PEER_MULTI_RAIL;
2555
2556         /*
2557          * Check whether the primary NID in the message matches the
2558          * primary NID of the peer. If it does, update the peer, if
2559          * it it does not, check whether there is already a peer with
2560          * that primary NID. If no such peer exists, try to update
2561          * the primary NID of the current peer (allowed if it was
2562          * created due to message traffic) and complete the update.
2563          * If the peer did exist, hand off the data to it.
2564          *
2565          * The peer for the loopback interface is a special case: this
2566          * is the peer for the local node, and we want to set its
2567          * primary NID to the correct value here.
2568          */
2569         if (pbuf->pb_info.pi_nnis > 1)
2570                 nid = pbuf->pb_info.pi_ni[1].ns_nid;
2571         if (LNET_NETTYP(LNET_NIDNET(lp->lp_primary_nid)) == LOLND) {
2572                 rc = lnet_peer_set_primary_nid(lp, nid, flags);
2573                 if (!rc)
2574                         rc = lnet_peer_merge_data(lp, pbuf);
2575         } else if (lp->lp_primary_nid == nid) {
2576                 rc = lnet_peer_merge_data(lp, pbuf);
2577         } else {
2578                 lpni = lnet_find_peer_ni_locked(nid);
2579                 if (!lpni) {
2580                         rc = lnet_peer_set_primary_nid(lp, nid, flags);
2581                         if (rc) {
2582                                 CERROR("Primary NID error %s versus %s: %d\n",
2583                                        libcfs_nid2str(lp->lp_primary_nid),
2584                                        libcfs_nid2str(nid), rc);
2585                         } else {
2586                                 rc = lnet_peer_merge_data(lp, pbuf);
2587                         }
2588                 } else {
2589                         rc = lnet_peer_set_primary_data(
2590                                 lpni->lpni_peer_net->lpn_peer, pbuf);
2591                         lnet_peer_ni_decref_locked(lpni);
2592                 }
2593         }
2594 out:
2595         CDEBUG(D_NET, "peer %s: %d\n", libcfs_nid2str(lp->lp_primary_nid), rc);
2596         mutex_unlock(&the_lnet.ln_api_mutex);
2597
2598         spin_lock(&lp->lp_lock);
2599         /* Tell discovery to re-check the peer immediately. */
2600         if (!rc)
2601                 rc = LNET_REDISCOVER_PEER;
2602         return rc;
2603 }
2604
2605 /*
2606  * A ping failed. Clear the PING_FAILED state and set the
2607  * FORCE_PING state, to ensure a retry even if discovery is
2608  * disabled. This avoids being left with incorrect state.
2609  */
2610 static int lnet_peer_ping_failed(struct lnet_peer *lp)
2611 __must_hold(&lp->lp_lock)
2612 {
2613         lnet_handle_md_t mdh;
2614         int rc;
2615
2616         mdh = lp->lp_ping_mdh;
2617         LNetInvalidateMDHandle(&lp->lp_ping_mdh);
2618         lp->lp_state &= ~LNET_PEER_PING_FAILED;
2619         lp->lp_state |= LNET_PEER_FORCE_PING;
2620         rc = lp->lp_ping_error;
2621         lp->lp_ping_error = 0;
2622         spin_unlock(&lp->lp_lock);
2623
2624         if (!LNetMDHandleIsInvalid(mdh))
2625                 LNetMDUnlink(mdh);
2626
2627         CDEBUG(D_NET, "peer %s:%d\n",
2628                libcfs_nid2str(lp->lp_primary_nid), rc);
2629
2630         spin_lock(&lp->lp_lock);
2631         return rc ? rc : LNET_REDISCOVER_PEER;
2632 }
2633
2634 /*
2635  * Select NID to send a Ping or Push to.
2636  */
2637 static lnet_nid_t lnet_peer_select_nid(struct lnet_peer *lp)
2638 {
2639         struct lnet_peer_ni *lpni;
2640
2641         /* Look for a direct-connected NID for this peer. */
2642         lpni = NULL;
2643         while ((lpni = lnet_get_next_peer_ni_locked(lp, NULL, lpni)) != NULL) {
2644                 if (!lnet_is_peer_ni_healthy_locked(lpni))
2645                         continue;
2646                 if (!lnet_get_net_locked(lpni->lpni_peer_net->lpn_net_id))
2647                         continue;
2648                 break;
2649         }
2650         if (lpni)
2651                 return lpni->lpni_nid;
2652
2653         /* Look for a routed-connected NID for this peer. */
2654         lpni = NULL;
2655         while ((lpni = lnet_get_next_peer_ni_locked(lp, NULL, lpni)) != NULL) {
2656                 if (!lnet_is_peer_ni_healthy_locked(lpni))
2657                         continue;
2658                 if (!lnet_find_rnet_locked(lpni->lpni_peer_net->lpn_net_id))
2659                         continue;
2660                 break;
2661         }
2662         if (lpni)
2663                 return lpni->lpni_nid;
2664
2665         return LNET_NID_ANY;
2666 }
2667
2668 /* Active side of ping. */
2669 static int lnet_peer_send_ping(struct lnet_peer *lp)
2670 __must_hold(&lp->lp_lock)
2671 {
2672         lnet_md_t md = { NULL };
2673         lnet_process_id_t id;
2674         struct lnet_ping_buffer *pbuf;
2675         int nnis;
2676         int rc;
2677         int cpt;
2678
2679         lp->lp_state |= LNET_PEER_PING_SENT;
2680         lp->lp_state &= ~LNET_PEER_FORCE_PING;
2681         spin_unlock(&lp->lp_lock);
2682
2683         nnis = MAX(lp->lp_data_nnis, LNET_INTERFACES_MIN);
2684         pbuf = lnet_ping_buffer_alloc(nnis, GFP_NOFS);
2685         if (!pbuf) {
2686                 rc = -ENOMEM;
2687                 goto fail_error;
2688         }
2689
2690         /* initialize md content */
2691         md.start     = &pbuf->pb_info;
2692         md.length    = LNET_PING_INFO_SIZE(nnis);
2693         md.threshold = 2; /* GET/REPLY */
2694         md.max_size  = 0;
2695         md.options   = LNET_MD_TRUNCATE;
2696         md.user_ptr  = lp;
2697         md.eq_handle = the_lnet.ln_dc_eqh;
2698
2699         rc = LNetMDBind(md, LNET_UNLINK, &lp->lp_ping_mdh);
2700         if (rc != 0) {
2701                 lnet_ping_buffer_decref(pbuf);
2702                 CERROR("Can't bind MD: %d\n", rc);
2703                 goto fail_error;
2704         }
2705         cpt = lnet_net_lock_current();
2706         /* Refcount for MD. */
2707         lnet_peer_addref_locked(lp);
2708         id.pid = LNET_PID_LUSTRE;
2709         id.nid = lnet_peer_select_nid(lp);
2710         lnet_net_unlock(cpt);
2711
2712         if (id.nid == LNET_NID_ANY) {
2713                 rc = -EHOSTUNREACH;
2714                 goto fail_unlink_md;
2715         }
2716
2717         rc = LNetGet(LNET_NID_ANY, lp->lp_ping_mdh, id,
2718                      LNET_RESERVED_PORTAL,
2719                      LNET_PROTO_PING_MATCHBITS, 0);
2720
2721         if (rc)
2722                 goto fail_unlink_md;
2723
2724         CDEBUG(D_NET, "peer %s\n", libcfs_nid2str(lp->lp_primary_nid));
2725
2726         spin_lock(&lp->lp_lock);
2727         return 0;
2728
2729 fail_unlink_md:
2730         LNetMDUnlink(lp->lp_ping_mdh);
2731         LNetInvalidateMDHandle(&lp->lp_ping_mdh);
2732 fail_error:
2733         CDEBUG(D_NET, "peer %s: %d\n", libcfs_nid2str(lp->lp_primary_nid), rc);
2734         /*
2735          * The errors that get us here are considered hard errors and
2736          * cause Discovery to terminate. So we clear PING_SENT, but do
2737          * not set either PING_FAILED or FORCE_PING. In fact we need
2738          * to clear PING_FAILED, because the unlink event handler will
2739          * have set it if we called LNetMDUnlink() above.
2740          */
2741         spin_lock(&lp->lp_lock);
2742         lp->lp_state &= ~(LNET_PEER_PING_SENT | LNET_PEER_PING_FAILED);
2743         return rc;
2744 }
2745
2746 /*
2747  * This function exists because you cannot call LNetMDUnlink() from an
2748  * event handler.
2749  */
2750 static int lnet_peer_push_failed(struct lnet_peer *lp)
2751 __must_hold(&lp->lp_lock)
2752 {
2753         lnet_handle_md_t mdh;
2754         int rc;
2755
2756         mdh = lp->lp_push_mdh;
2757         LNetInvalidateMDHandle(&lp->lp_push_mdh);
2758         lp->lp_state &= ~LNET_PEER_PUSH_FAILED;
2759         rc = lp->lp_push_error;
2760         lp->lp_push_error = 0;
2761         spin_unlock(&lp->lp_lock);
2762
2763         if (!LNetMDHandleIsInvalid(mdh))
2764                 LNetMDUnlink(mdh);
2765
2766         CDEBUG(D_NET, "peer %s\n", libcfs_nid2str(lp->lp_primary_nid));
2767         spin_lock(&lp->lp_lock);
2768         return rc ? rc : LNET_REDISCOVER_PEER;
2769 }
2770
2771 /* Active side of push. */
2772 static int lnet_peer_send_push(struct lnet_peer *lp)
2773 __must_hold(&lp->lp_lock)
2774 {
2775         struct lnet_ping_buffer *pbuf;
2776         lnet_process_id_t id;
2777         lnet_md_t md;
2778         int cpt;
2779         int rc;
2780
2781         /* Don't push to a non-multi-rail peer. */
2782         if (!(lp->lp_state & LNET_PEER_MULTI_RAIL)) {
2783                 lp->lp_state &= ~LNET_PEER_FORCE_PUSH;
2784                 return 0;
2785         }
2786
2787         lp->lp_state |= LNET_PEER_PUSH_SENT;
2788         lp->lp_state &= ~LNET_PEER_FORCE_PUSH;
2789         spin_unlock(&lp->lp_lock);
2790
2791         cpt = lnet_net_lock_current();
2792         pbuf = the_lnet.ln_ping_target;
2793         lnet_ping_buffer_addref(pbuf);
2794         lnet_net_unlock(cpt);
2795
2796         /* Push source MD */
2797         md.start     = &pbuf->pb_info;
2798         md.length    = LNET_PING_INFO_SIZE(pbuf->pb_nnis);
2799         md.threshold = 2; /* Put/Ack */
2800         md.max_size  = 0;
2801         md.options   = 0;
2802         md.eq_handle = the_lnet.ln_dc_eqh;
2803         md.user_ptr  = lp;
2804
2805         rc = LNetMDBind(md, LNET_UNLINK, &lp->lp_push_mdh);
2806         if (rc) {
2807                 lnet_ping_buffer_decref(pbuf);
2808                 CERROR("Can't bind push source MD: %d\n", rc);
2809                 goto fail_error;
2810         }
2811         cpt = lnet_net_lock_current();
2812         /* Refcount for MD. */
2813         lnet_peer_addref_locked(lp);
2814         id.pid = LNET_PID_LUSTRE;
2815         id.nid = lnet_peer_select_nid(lp);
2816         lnet_net_unlock(cpt);
2817
2818         if (id.nid == LNET_NID_ANY) {
2819                 rc = -EHOSTUNREACH;
2820                 goto fail_unlink;
2821         }
2822
2823         rc = LNetPut(LNET_NID_ANY, lp->lp_push_mdh,
2824                      LNET_ACK_REQ, id, LNET_RESERVED_PORTAL,
2825                      LNET_PROTO_PING_MATCHBITS, 0, 0);
2826
2827         if (rc)
2828                 goto fail_unlink;
2829
2830         CDEBUG(D_NET, "peer %s\n", libcfs_nid2str(lp->lp_primary_nid));
2831
2832         spin_lock(&lp->lp_lock);
2833         return 0;
2834
2835 fail_unlink:
2836         LNetMDUnlink(lp->lp_push_mdh);
2837         LNetInvalidateMDHandle(&lp->lp_push_mdh);
2838 fail_error:
2839         CDEBUG(D_NET, "peer %s: %d\n", libcfs_nid2str(lp->lp_primary_nid), rc);
2840         /*
2841          * The errors that get us here are considered hard errors and
2842          * cause Discovery to terminate. So we clear PUSH_SENT, but do
2843          * not set PUSH_FAILED. In fact we need to clear PUSH_FAILED,
2844          * because the unlink event handler will have set it if we
2845          * called LNetMDUnlink() above.
2846          */
2847         spin_lock(&lp->lp_lock);
2848         lp->lp_state &= ~(LNET_PEER_PUSH_SENT | LNET_PEER_PUSH_FAILED);
2849         return rc;
2850 }
2851
2852 /*
2853  * An unrecoverable error was encountered during discovery.
2854  * Set error status in peer and abort discovery.
2855  */
2856 static void lnet_peer_discovery_error(struct lnet_peer *lp, int error)
2857 {
2858         CDEBUG(D_NET, "Discovery error %s: %d\n",
2859                libcfs_nid2str(lp->lp_primary_nid), error);
2860
2861         spin_lock(&lp->lp_lock);
2862         lp->lp_dc_error = error;
2863         lp->lp_state &= ~LNET_PEER_DISCOVERING;
2864         lp->lp_state |= LNET_PEER_REDISCOVER;
2865         spin_unlock(&lp->lp_lock);
2866 }
2867
2868 /*
2869  * Mark the peer as discovered.
2870  */
2871 static int lnet_peer_discovered(struct lnet_peer *lp)
2872 __must_hold(&lp->lp_lock)
2873 {
2874         lp->lp_state |= LNET_PEER_DISCOVERED;
2875         lp->lp_state &= ~(LNET_PEER_DISCOVERING |
2876                           LNET_PEER_REDISCOVER);
2877
2878         CDEBUG(D_NET, "peer %s\n", libcfs_nid2str(lp->lp_primary_nid));
2879
2880         return 0;
2881 }
2882
2883 /*
2884  * Mark the peer as to be rediscovered.
2885  */
2886 static int lnet_peer_rediscover(struct lnet_peer *lp)
2887 __must_hold(&lp->lp_lock)
2888 {
2889         lp->lp_state |= LNET_PEER_REDISCOVER;
2890         lp->lp_state &= ~LNET_PEER_DISCOVERING;
2891
2892         CDEBUG(D_NET, "peer %s\n", libcfs_nid2str(lp->lp_primary_nid));
2893
2894         return 0;
2895 }
2896
2897 /*
2898  * Returns the first peer on the ln_dc_working queue if its timeout
2899  * has expired. Takes the current time as an argument so as to not
2900  * obsessively re-check the clock. The oldest discovery request will
2901  * be at the head of the queue.
2902  */
2903 static struct lnet_peer *lnet_peer_dc_timed_out(time64_t now)
2904 {
2905         struct lnet_peer *lp;
2906
2907         if (list_empty(&the_lnet.ln_dc_working))
2908                 return NULL;
2909         lp = list_first_entry(&the_lnet.ln_dc_working,
2910                               struct lnet_peer, lp_dc_list);
2911         if (now < lp->lp_last_queued + DEFAULT_PEER_TIMEOUT)
2912                 return NULL;
2913         return lp;
2914 }
2915
2916 /*
2917  * Discovering this peer is taking too long. Cancel any Ping or Push
2918  * that discovery is waiting on by unlinking the relevant MDs. The
2919  * lnet_discovery_event_handler() will proceed from here and complete
2920  * the cleanup.
2921  */
2922 static void lnet_peer_discovery_timeout(struct lnet_peer *lp)
2923 {
2924         struct lnet_handle_md ping_mdh;
2925         struct lnet_handle_md push_mdh;
2926
2927         LNetInvalidateMDHandle(&ping_mdh);
2928         LNetInvalidateMDHandle(&push_mdh);
2929
2930         spin_lock(&lp->lp_lock);
2931         if (lp->lp_state & LNET_PEER_PING_SENT) {
2932                 ping_mdh = lp->lp_ping_mdh;
2933                 LNetInvalidateMDHandle(&lp->lp_ping_mdh);
2934         }
2935         if (lp->lp_state & LNET_PEER_PUSH_SENT) {
2936                 push_mdh = lp->lp_push_mdh;
2937                 LNetInvalidateMDHandle(&lp->lp_push_mdh);
2938         }
2939         spin_unlock(&lp->lp_lock);
2940
2941         if (!LNetMDHandleIsInvalid(ping_mdh))
2942                 LNetMDUnlink(ping_mdh);
2943         if (!LNetMDHandleIsInvalid(push_mdh))
2944                 LNetMDUnlink(push_mdh);
2945 }
2946
2947 /*
2948  * Wait for work to be queued or some other change that must be
2949  * attended to. Returns non-zero if the discovery thread should shut
2950  * down.
2951  */
2952 static int lnet_peer_discovery_wait_for_work(void)
2953 {
2954         int cpt;
2955         int rc = 0;
2956
2957         DEFINE_WAIT(wait);
2958
2959         cpt = lnet_net_lock_current();
2960         for (;;) {
2961                 prepare_to_wait(&the_lnet.ln_dc_waitq, &wait,
2962                                 TASK_INTERRUPTIBLE);
2963                 if (the_lnet.ln_dc_state == LNET_DC_STATE_STOPPING)
2964                         break;
2965                 if (lnet_push_target_resize_needed())
2966                         break;
2967                 if (!list_empty(&the_lnet.ln_dc_request))
2968                         break;
2969                 if (lnet_peer_dc_timed_out(ktime_get_real_seconds()))
2970                         break;
2971                 lnet_net_unlock(cpt);
2972
2973                 /*
2974                  * wakeup max every second to check if there are peers that
2975                  * have been stuck on the working queue for greater than
2976                  * the peer timeout.
2977                  */
2978                 schedule_timeout(cfs_time_seconds(1));
2979                 finish_wait(&the_lnet.ln_dc_waitq, &wait);
2980                 cpt = lnet_net_lock_current();
2981         }
2982         finish_wait(&the_lnet.ln_dc_waitq, &wait);
2983
2984         if (the_lnet.ln_dc_state == LNET_DC_STATE_STOPPING)
2985                 rc = -ESHUTDOWN;
2986
2987         lnet_net_unlock(cpt);
2988
2989         CDEBUG(D_NET, "woken: %d\n", rc);
2990
2991         return rc;
2992 }
2993
2994 /* The discovery thread. */
2995 static int lnet_peer_discovery(void *arg)
2996 {
2997         struct lnet_peer *lp;
2998         time64_t now;
2999         int rc;
3000
3001         CDEBUG(D_NET, "started\n");
3002         cfs_block_allsigs();
3003
3004         for (;;) {
3005                 if (lnet_peer_discovery_wait_for_work())
3006                         break;
3007
3008                 if (lnet_push_target_resize_needed())
3009                         lnet_push_target_resize();
3010
3011                 lnet_net_lock(LNET_LOCK_EX);
3012                 if (the_lnet.ln_dc_state == LNET_DC_STATE_STOPPING)
3013                         break;
3014
3015                 /*
3016                  * Process all incoming discovery work requests.  When
3017                  * discovery must wait on a peer to change state, it
3018                  * is added to the tail of the ln_dc_working queue. A
3019                  * timestamp keeps track of when the peer was added,
3020                  * so we can time out discovery requests that take too
3021                  * long.
3022                  */
3023                 while (!list_empty(&the_lnet.ln_dc_request)) {
3024                         lp = list_first_entry(&the_lnet.ln_dc_request,
3025                                               struct lnet_peer, lp_dc_list);
3026                         list_move(&lp->lp_dc_list, &the_lnet.ln_dc_working);
3027                         /*
3028                          * set the time the peer was put on the dc_working
3029                          * queue. It shouldn't remain on the queue
3030                          * forever, in case the GET message (for ping)
3031                          * doesn't get a REPLY or the PUT message (for
3032                          * push) doesn't get an ACK.
3033                          *
3034                          * TODO: LNet Health will deal with this scenario
3035                          * in a generic way.
3036                          */
3037                         lp->lp_last_queued = ktime_get_real_seconds();
3038                         lnet_net_unlock(LNET_LOCK_EX);
3039
3040                         /*
3041                          * Select an action depending on the state of
3042                          * the peer and whether discovery is disabled.
3043                          * The check whether discovery is disabled is
3044                          * done after the code that handles processing
3045                          * for arrived data, cleanup for failures, and
3046                          * forcing a Ping or Push.
3047                          */
3048                         spin_lock(&lp->lp_lock);
3049                         CDEBUG(D_NET, "peer %s state %#x\n",
3050                                 libcfs_nid2str(lp->lp_primary_nid),
3051                                 lp->lp_state);
3052                         if (lp->lp_state & LNET_PEER_DATA_PRESENT)
3053                                 rc = lnet_peer_data_present(lp);
3054                         else if (lp->lp_state & LNET_PEER_PING_FAILED)
3055                                 rc = lnet_peer_ping_failed(lp);
3056                         else if (lp->lp_state & LNET_PEER_PUSH_FAILED)
3057                                 rc = lnet_peer_push_failed(lp);
3058                         else if (lp->lp_state & LNET_PEER_FORCE_PING)
3059                                 rc = lnet_peer_send_ping(lp);
3060                         else if (lp->lp_state & LNET_PEER_FORCE_PUSH)
3061                                 rc = lnet_peer_send_push(lp);
3062                         else if (lnet_peer_discovery_disabled)
3063                                 rc = lnet_peer_rediscover(lp);
3064                         else if (!(lp->lp_state & LNET_PEER_NIDS_UPTODATE))
3065                                 rc = lnet_peer_send_ping(lp);
3066                         else if (lnet_peer_needs_push(lp))
3067                                 rc = lnet_peer_send_push(lp);
3068                         else
3069                                 rc = lnet_peer_discovered(lp);
3070                         CDEBUG(D_NET, "peer %s state %#x rc %d\n",
3071                                 libcfs_nid2str(lp->lp_primary_nid),
3072                                 lp->lp_state, rc);
3073                         spin_unlock(&lp->lp_lock);
3074
3075                         lnet_net_lock(LNET_LOCK_EX);
3076                         if (rc == LNET_REDISCOVER_PEER) {
3077                                 list_move(&lp->lp_dc_list,
3078                                           &the_lnet.ln_dc_request);
3079                         } else if (rc) {
3080                                 lnet_peer_discovery_error(lp, rc);
3081                         }
3082                         if (!(lp->lp_state & LNET_PEER_DISCOVERING))
3083                                 lnet_peer_discovery_complete(lp);
3084                         if (the_lnet.ln_dc_state == LNET_DC_STATE_STOPPING)
3085                                 break;
3086                 }
3087
3088                 /*
3089                  * Now that the ln_dc_request queue has been emptied
3090                  * check the ln_dc_working queue for peers that are
3091                  * taking too long. Move all that are found to the
3092                  * ln_dc_expired queue and time out any pending
3093                  * Ping or Push. We have to drop the lnet_net_lock
3094                  * in the loop because lnet_peer_discovery_timeout()
3095                  * calls LNetMDUnlink().
3096                  */
3097                 now = ktime_get_real_seconds();
3098                 while ((lp = lnet_peer_dc_timed_out(now)) != NULL) {
3099                         list_move(&lp->lp_dc_list, &the_lnet.ln_dc_expired);
3100                         lnet_net_unlock(LNET_LOCK_EX);
3101                         lnet_peer_discovery_timeout(lp);
3102                         lnet_net_lock(LNET_LOCK_EX);
3103                 }
3104
3105                 lnet_net_unlock(LNET_LOCK_EX);
3106         }
3107
3108         CDEBUG(D_NET, "stopping\n");
3109         /*
3110          * Clean up before telling lnet_peer_discovery_stop() that
3111          * we're done. Use wake_up() below to somewhat reduce the
3112          * size of the thundering herd if there are multiple threads
3113          * waiting on discovery of a single peer.
3114          */
3115         LNetEQFree(the_lnet.ln_dc_eqh);
3116         LNetInvalidateEQHandle(&the_lnet.ln_dc_eqh);
3117
3118         /* Queue cleanup 1: stop all pending pings and pushes. */
3119         lnet_net_lock(LNET_LOCK_EX);
3120         while (!list_empty(&the_lnet.ln_dc_working)) {
3121                 lp = list_first_entry(&the_lnet.ln_dc_working,
3122                                       struct lnet_peer, lp_dc_list);
3123                 list_move(&lp->lp_dc_list, &the_lnet.ln_dc_expired);
3124                 lnet_net_unlock(LNET_LOCK_EX);
3125                 lnet_peer_discovery_timeout(lp);
3126                 lnet_net_lock(LNET_LOCK_EX);
3127         }
3128         lnet_net_unlock(LNET_LOCK_EX);
3129
3130         /* Queue cleanup 2: wait for the expired queue to clear. */
3131         while (!list_empty(&the_lnet.ln_dc_expired))
3132                 schedule_timeout(cfs_time_seconds(1));
3133
3134         /* Queue cleanup 3: clear the request queue. */
3135         lnet_net_lock(LNET_LOCK_EX);
3136         while (!list_empty(&the_lnet.ln_dc_request)) {
3137                 lp = list_first_entry(&the_lnet.ln_dc_request,
3138                                       struct lnet_peer, lp_dc_list);
3139                 lnet_peer_discovery_error(lp, -ESHUTDOWN);
3140                 lnet_peer_discovery_complete(lp);
3141         }
3142         lnet_net_unlock(LNET_LOCK_EX);
3143
3144         the_lnet.ln_dc_state = LNET_DC_STATE_SHUTDOWN;
3145         wake_up(&the_lnet.ln_dc_waitq);
3146
3147         CDEBUG(D_NET, "stopped\n");
3148
3149         return 0;
3150 }
3151
3152 /* ln_api_mutex is held on entry. */
3153 int lnet_peer_discovery_start(void)
3154 {
3155         struct task_struct *task;
3156         int rc;
3157
3158         if (the_lnet.ln_dc_state != LNET_DC_STATE_SHUTDOWN)
3159                 return -EALREADY;
3160
3161         rc = LNetEQAlloc(0, lnet_discovery_event_handler, &the_lnet.ln_dc_eqh);
3162         if (rc != 0) {
3163                 CERROR("Can't allocate discovery EQ: %d\n", rc);
3164                 return rc;
3165         }
3166
3167         the_lnet.ln_dc_state = LNET_DC_STATE_RUNNING;
3168         task = kthread_run(lnet_peer_discovery, NULL, "lnet_discovery");
3169         if (IS_ERR(task)) {
3170                 rc = PTR_ERR(task);
3171                 CERROR("Can't start peer discovery thread: %d\n", rc);
3172
3173                 LNetEQFree(the_lnet.ln_dc_eqh);
3174                 LNetInvalidateEQHandle(&the_lnet.ln_dc_eqh);
3175
3176                 the_lnet.ln_dc_state = LNET_DC_STATE_SHUTDOWN;
3177         }
3178
3179         CDEBUG(D_NET, "discovery start: %d\n", rc);
3180
3181         return rc;
3182 }
3183
3184 /* ln_api_mutex is held on entry. */
3185 void lnet_peer_discovery_stop(void)
3186 {
3187         if (the_lnet.ln_dc_state == LNET_DC_STATE_SHUTDOWN)
3188                 return;
3189
3190         LASSERT(the_lnet.ln_dc_state == LNET_DC_STATE_RUNNING);
3191         the_lnet.ln_dc_state = LNET_DC_STATE_STOPPING;
3192         wake_up(&the_lnet.ln_dc_waitq);
3193
3194         wait_event(the_lnet.ln_dc_waitq,
3195                    the_lnet.ln_dc_state == LNET_DC_STATE_SHUTDOWN);
3196
3197         LASSERT(list_empty(&the_lnet.ln_dc_request));
3198         LASSERT(list_empty(&the_lnet.ln_dc_working));
3199         LASSERT(list_empty(&the_lnet.ln_dc_expired));
3200
3201         CDEBUG(D_NET, "discovery stopped\n");
3202 }
3203
3204 /* Debugging */
3205
3206 void
3207 lnet_debug_peer(lnet_nid_t nid)
3208 {
3209         char                    *aliveness = "NA";
3210         struct lnet_peer_ni     *lp;
3211         int                     cpt;
3212
3213         cpt = lnet_cpt_of_nid(nid, NULL);
3214         lnet_net_lock(cpt);
3215
3216         lp = lnet_nid2peerni_locked(nid, LNET_NID_ANY, cpt);
3217         if (IS_ERR(lp)) {
3218                 lnet_net_unlock(cpt);
3219                 CDEBUG(D_WARNING, "No peer %s\n", libcfs_nid2str(nid));
3220                 return;
3221         }
3222
3223         if (lnet_isrouter(lp) || lnet_peer_aliveness_enabled(lp))
3224                 aliveness = lp->lpni_alive ? "up" : "down";
3225
3226         CDEBUG(D_WARNING, "%-24s %4d %5s %5d %5d %5d %5d %5d %ld\n",
3227                libcfs_nid2str(lp->lpni_nid), atomic_read(&lp->lpni_refcount),
3228                aliveness, lp->lpni_net->net_tunables.lct_peer_tx_credits,
3229                lp->lpni_rtrcredits, lp->lpni_minrtrcredits,
3230                lp->lpni_txcredits, lp->lpni_mintxcredits, lp->lpni_txqnob);
3231
3232         lnet_peer_ni_decref_locked(lp);
3233
3234         lnet_net_unlock(cpt);
3235 }
3236
3237 /* Gathering information for userspace. */
3238
3239 int lnet_get_peer_ni_info(__u32 peer_index, __u64 *nid,
3240                           char aliveness[LNET_MAX_STR_LEN],
3241                           __u32 *cpt_iter, __u32 *refcount,
3242                           __u32 *ni_peer_tx_credits, __u32 *peer_tx_credits,
3243                           __u32 *peer_rtr_credits, __u32 *peer_min_rtr_credits,
3244                           __u32 *peer_tx_qnob)
3245 {
3246         struct lnet_peer_table          *peer_table;
3247         struct lnet_peer_ni             *lp;
3248         int                             j;
3249         int                             lncpt;
3250         bool                            found = false;
3251
3252         /* get the number of CPTs */
3253         lncpt = cfs_percpt_number(the_lnet.ln_peer_tables);
3254
3255         /* if the cpt number to be examined is >= the number of cpts in
3256          * the system then indicate that there are no more cpts to examin
3257          */
3258         if (*cpt_iter >= lncpt)
3259                 return -ENOENT;
3260
3261         /* get the current table */
3262         peer_table = the_lnet.ln_peer_tables[*cpt_iter];
3263         /* if the ptable is NULL then there are no more cpts to examine */
3264         if (peer_table == NULL)
3265                 return -ENOENT;
3266
3267         lnet_net_lock(*cpt_iter);
3268
3269         for (j = 0; j < LNET_PEER_HASH_SIZE && !found; j++) {
3270                 struct list_head *peers = &peer_table->pt_hash[j];
3271
3272                 list_for_each_entry(lp, peers, lpni_hashlist) {
3273                         if (peer_index-- > 0)
3274                                 continue;
3275
3276                         snprintf(aliveness, LNET_MAX_STR_LEN, "NA");
3277                         if (lnet_isrouter(lp) ||
3278                                 lnet_peer_aliveness_enabled(lp))
3279                                 snprintf(aliveness, LNET_MAX_STR_LEN,
3280                                          lp->lpni_alive ? "up" : "down");
3281
3282                         *nid = lp->lpni_nid;
3283                         *refcount = atomic_read(&lp->lpni_refcount);
3284                         *ni_peer_tx_credits =
3285                                 lp->lpni_net->net_tunables.lct_peer_tx_credits;
3286                         *peer_tx_credits = lp->lpni_txcredits;
3287                         *peer_rtr_credits = lp->lpni_rtrcredits;
3288                         *peer_min_rtr_credits = lp->lpni_mintxcredits;
3289                         *peer_tx_qnob = lp->lpni_txqnob;
3290
3291                         found = true;
3292                 }
3293
3294         }
3295         lnet_net_unlock(*cpt_iter);
3296
3297         *cpt_iter = lncpt;
3298
3299         return found ? 0 : -ENOENT;
3300 }
3301
3302 /* ln_api_mutex is held, which keeps the peer list stable */
3303 int lnet_get_peer_info(struct lnet_ioctl_peer_cfg *cfg, void __user *bulk)
3304 {
3305         struct lnet_ioctl_element_stats *lpni_stats;
3306         struct lnet_ioctl_element_msg_stats *lpni_msg_stats;
3307         struct lnet_peer_ni_credit_info *lpni_info;
3308         struct lnet_peer_ni *lpni;
3309         struct lnet_peer *lp;
3310         lnet_nid_t nid;
3311         __u32 size;
3312         int rc;
3313
3314         lp = lnet_find_peer(cfg->prcfg_prim_nid);
3315
3316         if (!lp) {
3317                 rc = -ENOENT;
3318                 goto out;
3319         }
3320
3321         size = sizeof(nid) + sizeof(*lpni_info) + sizeof(*lpni_stats)
3322                 + sizeof(*lpni_msg_stats);
3323         size *= lp->lp_nnis;
3324         if (size > cfg->prcfg_size) {
3325                 cfg->prcfg_size = size;
3326                 rc = -E2BIG;
3327                 goto out_lp_decref;
3328         }
3329
3330         cfg->prcfg_prim_nid = lp->lp_primary_nid;
3331         cfg->prcfg_mr = lnet_peer_is_multi_rail(lp);
3332         cfg->prcfg_cfg_nid = lp->lp_primary_nid;
3333         cfg->prcfg_count = lp->lp_nnis;
3334         cfg->prcfg_size = size;
3335         cfg->prcfg_state = lp->lp_state;
3336
3337         /* Allocate helper buffers. */
3338         rc = -ENOMEM;
3339         LIBCFS_ALLOC(lpni_info, sizeof(*lpni_info));
3340         if (!lpni_info)
3341                 goto out_lp_decref;
3342         LIBCFS_ALLOC(lpni_stats, sizeof(*lpni_stats));
3343         if (!lpni_stats)
3344                 goto out_free_info;
3345         LIBCFS_ALLOC(lpni_msg_stats, sizeof(*lpni_msg_stats));
3346         if (!lpni_msg_stats)
3347                 goto out_free_stats;
3348
3349
3350         lpni = NULL;
3351         rc = -EFAULT;
3352         while ((lpni = lnet_get_next_peer_ni_locked(lp, NULL, lpni)) != NULL) {
3353                 nid = lpni->lpni_nid;
3354                 if (copy_to_user(bulk, &nid, sizeof(nid)))
3355                         goto out_free_msg_stats;
3356                 bulk += sizeof(nid);
3357
3358                 memset(lpni_info, 0, sizeof(*lpni_info));
3359                 snprintf(lpni_info->cr_aliveness, LNET_MAX_STR_LEN, "NA");
3360                 if (lnet_isrouter(lpni) ||
3361                         lnet_peer_aliveness_enabled(lpni))
3362                         snprintf(lpni_info->cr_aliveness, LNET_MAX_STR_LEN,
3363                                 lpni->lpni_alive ? "up" : "down");
3364
3365                 lpni_info->cr_refcount = atomic_read(&lpni->lpni_refcount);
3366                 lpni_info->cr_ni_peer_tx_credits = (lpni->lpni_net != NULL) ?
3367                         lpni->lpni_net->net_tunables.lct_peer_tx_credits : 0;
3368                 lpni_info->cr_peer_tx_credits = lpni->lpni_txcredits;
3369                 lpni_info->cr_peer_rtr_credits = lpni->lpni_rtrcredits;
3370                 lpni_info->cr_peer_min_rtr_credits = lpni->lpni_minrtrcredits;
3371                 lpni_info->cr_peer_min_tx_credits = lpni->lpni_mintxcredits;
3372                 lpni_info->cr_peer_tx_qnob = lpni->lpni_txqnob;
3373                 if (copy_to_user(bulk, lpni_info, sizeof(*lpni_info)))
3374                         goto out_free_msg_stats;
3375                 bulk += sizeof(*lpni_info);
3376
3377                 memset(lpni_stats, 0, sizeof(*lpni_stats));
3378                 lpni_stats->iel_send_count = lnet_sum_stats(&lpni->lpni_stats,
3379                                                             LNET_STATS_TYPE_SEND);
3380                 lpni_stats->iel_recv_count = lnet_sum_stats(&lpni->lpni_stats,
3381                                                             LNET_STATS_TYPE_RECV);
3382                 lpni_stats->iel_drop_count = lnet_sum_stats(&lpni->lpni_stats,
3383                                                             LNET_STATS_TYPE_DROP);
3384                 if (copy_to_user(bulk, lpni_stats, sizeof(*lpni_stats)))
3385                         goto out_free_msg_stats;
3386                 bulk += sizeof(*lpni_stats);
3387                 lnet_usr_translate_stats(lpni_msg_stats, &lpni->lpni_stats);
3388                 if (copy_to_user(bulk, lpni_msg_stats, sizeof(*lpni_msg_stats)))
3389                         goto out_free_msg_stats;
3390                 bulk += sizeof(*lpni_msg_stats);
3391         }
3392         rc = 0;
3393
3394 out_free_msg_stats:
3395         LIBCFS_FREE(lpni_msg_stats, sizeof(*lpni_msg_stats));
3396 out_free_stats:
3397         LIBCFS_FREE(lpni_stats, sizeof(*lpni_stats));
3398 out_free_info:
3399         LIBCFS_FREE(lpni_info, sizeof(*lpni_info));
3400 out_lp_decref:
3401         lnet_peer_decref_locked(lp);
3402 out:
3403         return rc;
3404 }