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