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