Whamcloud - gitweb
15c8b75d742bfc3c70c86a7109ebaf4e0e9be498
[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, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  *
31  * lnet/lnet/peer.c
32  */
33
34 #define DEBUG_SUBSYSTEM S_LNET
35
36 #include <linux/sched.h>
37 #ifdef HAVE_SCHED_HEADERS
38 #include <linux/sched/signal.h>
39 #endif
40 #include <linux/uaccess.h>
41
42 #include <lnet/udsp.h>
43 #include <lnet/lib-lnet.h>
44 #include <uapi/linux/lnet/lnet-dlc.h>
45
46 /* Value indicating that recovery needs to re-check a peer immediately. */
47 #define LNET_REDISCOVER_PEER    (1)
48
49 static int lnet_peer_queue_for_discovery(struct lnet_peer *lp);
50 static int lnet_add_peer_ni(struct lnet_nid *prim_nid, struct lnet_nid *nid, bool mr,
51                             unsigned int flags);
52
53 static void
54 lnet_peer_remove_from_remote_list(struct lnet_peer_ni *lpni)
55 {
56         if (!list_empty(&lpni->lpni_on_remote_peer_ni_list)) {
57                 list_del_init(&lpni->lpni_on_remote_peer_ni_list);
58                 lnet_peer_ni_decref_locked(lpni);
59         }
60 }
61
62 void
63 lnet_peer_net_added(struct lnet_net *net)
64 {
65         struct lnet_peer_ni *lpni, *tmp;
66
67         list_for_each_entry_safe(lpni, tmp, &the_lnet.ln_remote_peer_ni_list,
68                                  lpni_on_remote_peer_ni_list) {
69
70                 if (LNET_NID_NET(&lpni->lpni_nid) == net->net_id) {
71                         lpni->lpni_net = net;
72
73                         spin_lock(&lpni->lpni_lock);
74                         lpni->lpni_txcredits =
75                                 lpni->lpni_net->net_tunables.lct_peer_tx_credits;
76                         lpni->lpni_mintxcredits = lpni->lpni_txcredits;
77                         lpni->lpni_rtrcredits =
78                                 lnet_peer_buffer_credits(lpni->lpni_net);
79                         lpni->lpni_minrtrcredits = lpni->lpni_rtrcredits;
80                         spin_unlock(&lpni->lpni_lock);
81
82                         lnet_peer_remove_from_remote_list(lpni);
83                 }
84         }
85 }
86
87 static void
88 lnet_peer_tables_destroy(void)
89 {
90         struct lnet_peer_table  *ptable;
91         struct list_head        *hash;
92         int                     i;
93         int                     j;
94
95         if (!the_lnet.ln_peer_tables)
96                 return;
97
98         cfs_percpt_for_each(ptable, i, the_lnet.ln_peer_tables) {
99                 hash = ptable->pt_hash;
100                 if (!hash) /* not intialized */
101                         break;
102
103                 LASSERT(list_empty(&ptable->pt_zombie_list));
104
105                 ptable->pt_hash = NULL;
106                 for (j = 0; j < LNET_PEER_HASH_SIZE; j++)
107                         LASSERT(list_empty(&hash[j]));
108
109                 CFS_FREE_PTR_ARRAY(hash, LNET_PEER_HASH_SIZE);
110         }
111
112         cfs_percpt_free(the_lnet.ln_peer_tables);
113         the_lnet.ln_peer_tables = NULL;
114 }
115
116 int
117 lnet_peer_tables_create(void)
118 {
119         struct lnet_peer_table  *ptable;
120         struct list_head        *hash;
121         int                     i;
122         int                     j;
123
124         the_lnet.ln_peer_tables = cfs_percpt_alloc(lnet_cpt_table(),
125                                                    sizeof(*ptable));
126         if (the_lnet.ln_peer_tables == NULL) {
127                 CERROR("Failed to allocate cpu-partition peer tables\n");
128                 return -ENOMEM;
129         }
130
131         cfs_percpt_for_each(ptable, i, the_lnet.ln_peer_tables) {
132                 LIBCFS_CPT_ALLOC(hash, lnet_cpt_table(), i,
133                                  LNET_PEER_HASH_SIZE * sizeof(*hash));
134                 if (hash == NULL) {
135                         CERROR("Failed to create peer hash table\n");
136                         lnet_peer_tables_destroy();
137                         return -ENOMEM;
138                 }
139
140                 spin_lock_init(&ptable->pt_zombie_lock);
141                 INIT_LIST_HEAD(&ptable->pt_zombie_list);
142
143                 INIT_LIST_HEAD(&ptable->pt_peer_list);
144
145                 for (j = 0; j < LNET_PEER_HASH_SIZE; j++)
146                         INIT_LIST_HEAD(&hash[j]);
147                 ptable->pt_hash = hash; /* sign of initialization */
148         }
149
150         return 0;
151 }
152
153 static struct lnet_peer_ni *
154 lnet_peer_ni_alloc(struct lnet_nid *nid)
155 {
156         struct lnet_peer_ni *lpni;
157         struct lnet_net *net;
158         int cpt;
159
160         cpt = lnet_nid_cpt_hash(nid, LNET_CPT_NUMBER);
161
162         LIBCFS_CPT_ALLOC(lpni, lnet_cpt_table(), cpt, sizeof(*lpni));
163         if (!lpni)
164                 return NULL;
165
166         INIT_LIST_HEAD(&lpni->lpni_txq);
167         INIT_LIST_HEAD(&lpni->lpni_hashlist);
168         INIT_LIST_HEAD(&lpni->lpni_peer_nis);
169         INIT_LIST_HEAD(&lpni->lpni_recovery);
170         INIT_LIST_HEAD(&lpni->lpni_on_remote_peer_ni_list);
171         INIT_LIST_HEAD(&lpni->lpni_rtr_pref_nids);
172         LNetInvalidateMDHandle(&lpni->lpni_recovery_ping_mdh);
173         kref_init(&lpni->lpni_kref);
174         lpni->lpni_sel_priority = LNET_MAX_SELECTION_PRIORITY;
175
176         spin_lock_init(&lpni->lpni_lock);
177
178         if (lnet_peers_start_down())
179                 lpni->lpni_ns_status = LNET_NI_STATUS_DOWN;
180         else
181                 lpni->lpni_ns_status = LNET_NI_STATUS_UP;
182         lpni->lpni_ping_feats = LNET_PING_FEAT_INVAL;
183         lpni->lpni_nid = *nid;
184         lpni->lpni_cpt = cpt;
185         atomic_set(&lpni->lpni_healthv, LNET_MAX_HEALTH_VALUE);
186
187         net = lnet_get_net_locked(LNET_NID_NET(nid));
188         lpni->lpni_net = net;
189         if (net) {
190                 lpni->lpni_txcredits = net->net_tunables.lct_peer_tx_credits;
191                 lpni->lpni_mintxcredits = lpni->lpni_txcredits;
192                 lpni->lpni_rtrcredits = lnet_peer_buffer_credits(net);
193                 lpni->lpni_minrtrcredits = lpni->lpni_rtrcredits;
194         } else {
195                 /*
196                  * This peer_ni is not on a local network, so we
197                  * cannot add the credits here. In case the net is
198                  * added later, add the peer_ni to the remote peer ni
199                  * list so it can be easily found and revisited.
200                  */
201                 /* FIXME: per-net implementation instead? */
202                 lnet_peer_ni_addref_locked(lpni);
203                 list_add_tail(&lpni->lpni_on_remote_peer_ni_list,
204                               &the_lnet.ln_remote_peer_ni_list);
205         }
206
207         CDEBUG(D_NET, "%p nid %s\n", lpni, libcfs_nidstr(&lpni->lpni_nid));
208
209         return lpni;
210 }
211
212 static struct lnet_peer_net *
213 lnet_peer_net_alloc(__u32 net_id)
214 {
215         struct lnet_peer_net *lpn;
216
217         LIBCFS_CPT_ALLOC(lpn, lnet_cpt_table(), CFS_CPT_ANY, sizeof(*lpn));
218         if (!lpn)
219                 return NULL;
220
221         INIT_LIST_HEAD(&lpn->lpn_peer_nets);
222         INIT_LIST_HEAD(&lpn->lpn_peer_nis);
223         lpn->lpn_net_id = net_id;
224         lpn->lpn_sel_priority = LNET_MAX_SELECTION_PRIORITY;
225
226         CDEBUG(D_NET, "%p net %s\n", lpn, libcfs_net2str(lpn->lpn_net_id));
227
228         return lpn;
229 }
230
231 void
232 lnet_destroy_peer_net_locked(struct lnet_peer_net *lpn)
233 {
234         struct lnet_peer *lp;
235
236         CDEBUG(D_NET, "%p net %s\n", lpn, libcfs_net2str(lpn->lpn_net_id));
237
238         LASSERT(atomic_read(&lpn->lpn_refcount) == 0);
239         LASSERT(list_empty(&lpn->lpn_peer_nis));
240         LASSERT(list_empty(&lpn->lpn_peer_nets));
241         lp = lpn->lpn_peer;
242         lpn->lpn_peer = NULL;
243         LIBCFS_FREE(lpn, sizeof(*lpn));
244
245         lnet_peer_decref_locked(lp);
246 }
247
248 static struct lnet_peer *
249 lnet_peer_alloc(struct lnet_nid *nid)
250 {
251         struct lnet_peer *lp;
252
253         LIBCFS_CPT_ALLOC(lp, lnet_cpt_table(), CFS_CPT_ANY, sizeof(*lp));
254         if (!lp)
255                 return NULL;
256
257         INIT_LIST_HEAD(&lp->lp_rtrq);
258         INIT_LIST_HEAD(&lp->lp_routes);
259         INIT_LIST_HEAD(&lp->lp_peer_list);
260         INIT_LIST_HEAD(&lp->lp_peer_nets);
261         INIT_LIST_HEAD(&lp->lp_dc_list);
262         INIT_LIST_HEAD(&lp->lp_dc_pendq);
263         INIT_LIST_HEAD(&lp->lp_rtr_list);
264         init_waitqueue_head(&lp->lp_dc_waitq);
265         spin_lock_init(&lp->lp_lock);
266         lp->lp_primary_nid = *nid;
267         lp->lp_disc_src_nid = LNET_ANY_NID;
268         lp->lp_disc_dst_nid = LNET_ANY_NID;
269         if (lnet_peers_start_down())
270                 lp->lp_alive = false;
271         else
272                 lp->lp_alive = true;
273
274         /*
275          * all peers created on a router should have health on
276          * if it's not already on.
277          */
278         if (the_lnet.ln_routing && !lnet_health_sensitivity)
279                 lp->lp_health_sensitivity = 1;
280
281         /*
282          * Turn off discovery for loopback peer. If you're creating a peer
283          * for the loopback interface then that was initiated when we
284          * attempted to send a message over the loopback. There is no need
285          * to ever use a different interface when sending messages to
286          * myself.
287          */
288         if (nid_is_lo0(nid))
289                 lp->lp_state = LNET_PEER_NO_DISCOVERY;
290         lp->lp_cpt = lnet_nid_cpt_hash(nid, LNET_CPT_NUMBER);
291
292         CDEBUG(D_NET, "%p nid %s\n", lp, libcfs_nidstr(&lp->lp_primary_nid));
293
294         return lp;
295 }
296
297 void
298 lnet_destroy_peer_locked(struct lnet_peer *lp)
299 {
300         CDEBUG(D_NET, "%p nid %s\n", lp, libcfs_nidstr(&lp->lp_primary_nid));
301
302         LASSERT(atomic_read(&lp->lp_refcount) == 0);
303         LASSERT(lp->lp_rtr_refcount == 0);
304         LASSERT(list_empty(&lp->lp_peer_nets));
305         LASSERT(list_empty(&lp->lp_peer_list));
306         LASSERT(list_empty(&lp->lp_dc_list));
307
308         if (lp->lp_data)
309                 lnet_ping_buffer_decref(lp->lp_data);
310
311         /*
312          * if there are messages still on the pending queue, then make
313          * sure to queue them on the ln_msg_resend list so they can be
314          * resent at a later point if the discovery thread is still
315          * running.
316          * If the discovery thread has stopped, then the wakeup will be a
317          * no-op, and it is expected the lnet_shutdown_lndnets() will
318          * eventually be called, which will traverse this list and
319          * finalize the messages on the list.
320          * We can not resend them now because we're holding the cpt lock.
321          * Releasing the lock can cause an inconsistent state
322          */
323         spin_lock(&the_lnet.ln_msg_resend_lock);
324         spin_lock(&lp->lp_lock);
325         list_splice(&lp->lp_dc_pendq, &the_lnet.ln_msg_resend);
326         spin_unlock(&lp->lp_lock);
327         spin_unlock(&the_lnet.ln_msg_resend_lock);
328         wake_up(&the_lnet.ln_dc_waitq);
329
330         LIBCFS_FREE(lp, sizeof(*lp));
331 }
332
333 /*
334  * Detach a peer_ni from its peer_net. If this was the last peer_ni on
335  * that peer_net, detach the peer_net from the peer.
336  *
337  * Call with lnet_net_lock/EX held
338  */
339 static void
340 lnet_peer_detach_peer_ni_locked(struct lnet_peer_ni *lpni)
341 {
342         struct lnet_peer_table *ptable;
343         struct lnet_peer_net *lpn;
344         struct lnet_peer *lp;
345
346         /*
347          * Belts and suspenders: gracefully handle teardown of a
348          * partially connected peer_ni.
349          */
350         lpn = lpni->lpni_peer_net;
351
352         list_del_init(&lpni->lpni_peer_nis);
353         /*
354          * If there are no lpni's left, we detach lpn from
355          * lp_peer_nets, so it cannot be found anymore.
356          */
357         if (list_empty(&lpn->lpn_peer_nis))
358                 list_del_init(&lpn->lpn_peer_nets);
359
360         /* Update peer NID count. */
361         lp = lpn->lpn_peer;
362         lp->lp_nnis--;
363
364         /*
365          * If there are no more peer nets, make the peer unfindable
366          * via the peer_tables.
367          *
368          * Otherwise, if the peer is DISCOVERED, tell discovery to
369          * take another look at it. This is a no-op if discovery for
370          * this peer did the detaching.
371          */
372         if (list_empty(&lp->lp_peer_nets)) {
373                 list_del_init(&lp->lp_peer_list);
374                 ptable = the_lnet.ln_peer_tables[lp->lp_cpt];
375                 ptable->pt_peers--;
376         } else if (the_lnet.ln_dc_state != LNET_DC_STATE_RUNNING) {
377                 /* Discovery isn't running, nothing to do here. */
378         } else if (lp->lp_state & LNET_PEER_DISCOVERED) {
379                 lnet_peer_queue_for_discovery(lp);
380                 wake_up(&the_lnet.ln_dc_waitq);
381         }
382         CDEBUG(D_NET, "peer %s NID %s\n",
383                 libcfs_nidstr(&lp->lp_primary_nid),
384                 libcfs_nidstr(&lpni->lpni_nid));
385 }
386
387 /* called with lnet_net_lock LNET_LOCK_EX held */
388 static int
389 lnet_peer_ni_del_locked(struct lnet_peer_ni *lpni, bool force)
390 {
391         struct lnet_peer_table *ptable = NULL;
392
393         /* don't remove a peer_ni if it's also a gateway */
394         if (lnet_isrouter(lpni) && !force) {
395                 CERROR("Peer NI %s is a gateway. Can not delete it\n",
396                        libcfs_nidstr(&lpni->lpni_nid));
397                 return -EBUSY;
398         }
399
400         lnet_peer_remove_from_remote_list(lpni);
401
402         /* remove peer ni from the hash list. */
403         list_del_init(&lpni->lpni_hashlist);
404
405         /*
406          * indicate the peer is being deleted so the monitor thread can
407          * remove it from the recovery queue.
408          */
409         spin_lock(&lpni->lpni_lock);
410         lpni->lpni_state |= LNET_PEER_NI_DELETING;
411         spin_unlock(&lpni->lpni_lock);
412
413         /* decrement the ref count on the peer table */
414         ptable = the_lnet.ln_peer_tables[lpni->lpni_cpt];
415
416         /*
417          * The peer_ni can no longer be found with a lookup. But there
418          * can be current users, so keep track of it on the zombie
419          * list until the reference count has gone to zero.
420          *
421          * The last reference may be lost in a place where the
422          * lnet_net_lock locks only a single cpt, and that cpt may not
423          * be lpni->lpni_cpt. So the zombie list of lnet_peer_table
424          * has its own lock.
425          */
426         spin_lock(&ptable->pt_zombie_lock);
427         list_add(&lpni->lpni_hashlist, &ptable->pt_zombie_list);
428         ptable->pt_zombies++;
429         spin_unlock(&ptable->pt_zombie_lock);
430
431         /* no need to keep this peer_ni on the hierarchy anymore */
432         lnet_peer_detach_peer_ni_locked(lpni);
433
434         /* remove hashlist reference on peer_ni */
435         lnet_peer_ni_decref_locked(lpni);
436
437         return 0;
438 }
439
440 void lnet_peer_uninit(void)
441 {
442         struct lnet_peer_ni *lpni, *tmp;
443
444         lnet_net_lock(LNET_LOCK_EX);
445
446         /* remove all peer_nis from the remote peer and the hash list */
447         list_for_each_entry_safe(lpni, tmp, &the_lnet.ln_remote_peer_ni_list,
448                                  lpni_on_remote_peer_ni_list)
449                 lnet_peer_ni_del_locked(lpni, false);
450
451         lnet_peer_tables_destroy();
452
453         lnet_net_unlock(LNET_LOCK_EX);
454 }
455
456 static int
457 lnet_peer_del_locked(struct lnet_peer *peer)
458 {
459         struct lnet_peer_ni *lpni = NULL, *lpni2;
460         int rc = 0, rc2 = 0;
461
462         CDEBUG(D_NET, "peer %s\n", libcfs_nidstr(&peer->lp_primary_nid));
463
464         spin_lock(&peer->lp_lock);
465         peer->lp_state |= LNET_PEER_MARK_DELETED;
466         spin_unlock(&peer->lp_lock);
467
468         lpni = lnet_get_next_peer_ni_locked(peer, NULL, lpni);
469         while (lpni != NULL) {
470                 lpni2 = lnet_get_next_peer_ni_locked(peer, NULL, lpni);
471                 rc = lnet_peer_ni_del_locked(lpni, false);
472                 if (rc != 0)
473                         rc2 = rc;
474                 lpni = lpni2;
475         }
476
477         return rc2;
478 }
479
480 /*
481  * Discovering this peer is taking too long. Cancel any Ping or Push
482  * that discovery is waiting on by unlinking the relevant MDs. The
483  * lnet_discovery_event_handler() will proceed from here and complete
484  * the cleanup.
485  */
486 static void lnet_peer_cancel_discovery(struct lnet_peer *lp)
487 {
488         struct lnet_handle_md ping_mdh;
489         struct lnet_handle_md push_mdh;
490
491         LNetInvalidateMDHandle(&ping_mdh);
492         LNetInvalidateMDHandle(&push_mdh);
493
494         spin_lock(&lp->lp_lock);
495         if (lp->lp_state & LNET_PEER_PING_SENT) {
496                 ping_mdh = lp->lp_ping_mdh;
497                 LNetInvalidateMDHandle(&lp->lp_ping_mdh);
498         }
499         if (lp->lp_state & LNET_PEER_PUSH_SENT) {
500                 push_mdh = lp->lp_push_mdh;
501                 LNetInvalidateMDHandle(&lp->lp_push_mdh);
502         }
503         spin_unlock(&lp->lp_lock);
504
505         if (!LNetMDHandleIsInvalid(ping_mdh))
506                 LNetMDUnlink(ping_mdh);
507         if (!LNetMDHandleIsInvalid(push_mdh))
508                 LNetMDUnlink(push_mdh);
509 }
510
511 static int
512 lnet_peer_del(struct lnet_peer *peer)
513 {
514         int rc;
515
516         lnet_peer_cancel_discovery(peer);
517         lnet_net_lock(LNET_LOCK_EX);
518         rc = lnet_peer_del_locked(peer);
519         lnet_net_unlock(LNET_LOCK_EX);
520
521         return rc;
522 }
523
524 /*
525  * Delete a NID from a peer. Call with ln_api_mutex held.
526  *
527  * Error codes:
528  *  -EPERM:  Non-DLC deletion from DLC-configured peer.
529  *  -ENOENT: No lnet_peer_ni corresponding to the nid.
530  *  -ECHILD: The lnet_peer_ni isn't connected to the peer.
531  *  -EBUSY:  The lnet_peer_ni is the primary, and not the only peer_ni.
532  */
533 static int
534 lnet_peer_del_nid(struct lnet_peer *lp, struct lnet_nid *nid,
535                   unsigned int flags)
536 {
537         struct lnet_peer_ni *lpni;
538         struct lnet_nid primary_nid = lp->lp_primary_nid;
539         int rc = 0;
540         bool force = (flags & LNET_PEER_RTR_NI_FORCE_DEL) ? true : false;
541
542         if (!(flags & LNET_PEER_CONFIGURED)) {
543                 if (lp->lp_state & LNET_PEER_CONFIGURED) {
544                         rc = -EPERM;
545                         goto out;
546                 }
547         }
548
549         /* If we're asked to lock down the primary NID we shouldn't be
550          * deleting it
551          */
552         if (lp->lp_state & LNET_PEER_LOCK_PRIMARY &&
553             nid_same(&primary_nid, nid)) {
554                 rc = -EPERM;
555                 goto out;
556         }
557
558         lpni = lnet_peer_ni_find_locked(nid);
559         if (!lpni) {
560                 rc = -ENOENT;
561                 goto out;
562         }
563         lnet_peer_ni_decref_locked(lpni);
564         if (lp != lpni->lpni_peer_net->lpn_peer) {
565                 rc = -ECHILD;
566                 goto out;
567         }
568
569         /*
570          * This function only allows deletion of the primary NID if it
571          * is the only NID.
572          */
573         if (nid_same(nid, &lp->lp_primary_nid) && lp->lp_nnis != 1 && !force) {
574                 rc = -EBUSY;
575                 goto out;
576         }
577
578         lnet_net_lock(LNET_LOCK_EX);
579
580         if (nid_same(nid, &lp->lp_primary_nid) && lp->lp_nnis != 1 && force) {
581                 struct lnet_peer_ni *lpni2;
582                 /* assign the next peer_ni to be the primary */
583                 lpni2 = lnet_get_next_peer_ni_locked(lp, NULL, lpni);
584                 LASSERT(lpni2);
585                 lp->lp_primary_nid = lpni2->lpni_nid;
586         }
587         rc = lnet_peer_ni_del_locked(lpni, force);
588
589         lnet_net_unlock(LNET_LOCK_EX);
590
591 out:
592         CDEBUG(D_NET, "peer %s NID %s flags %#x: %d\n",
593                libcfs_nidstr(&primary_nid), libcfs_nidstr(nid),
594                flags, rc);
595
596         return rc;
597 }
598
599 static void
600 lnet_peer_table_cleanup_locked(struct lnet_net *net,
601                                struct lnet_peer_table *ptable)
602 {
603         int                      i;
604         struct lnet_peer_ni     *next;
605         struct lnet_peer_ni     *lpni;
606         struct lnet_peer        *peer;
607
608         for (i = 0; i < LNET_PEER_HASH_SIZE; i++) {
609                 list_for_each_entry_safe(lpni, next, &ptable->pt_hash[i],
610                                          lpni_hashlist) {
611                         if (net != NULL && net != lpni->lpni_net)
612                                 continue;
613
614                         peer = lpni->lpni_peer_net->lpn_peer;
615                         if (!nid_same(&peer->lp_primary_nid,
616                                        &lpni->lpni_nid)) {
617                                 lnet_peer_ni_del_locked(lpni, false);
618                                 continue;
619                         }
620                         /*
621                          * Removing the primary NID implies removing
622                          * the entire peer. Advance next beyond any
623                          * peer_ni that belongs to the same peer.
624                          */
625                         list_for_each_entry_from(next, &ptable->pt_hash[i],
626                                                  lpni_hashlist) {
627                                 if (next->lpni_peer_net->lpn_peer != peer)
628                                         break;
629                         }
630                         lnet_peer_del_locked(peer);
631                 }
632         }
633 }
634
635 static void
636 lnet_peer_ni_finalize_wait(struct lnet_peer_table *ptable)
637 {
638         wait_var_event_warning(&ptable->pt_zombies,
639                                ptable->pt_zombies == 0,
640                                "Waiting for %d zombies on peer table\n",
641                                ptable->pt_zombies);
642 }
643
644 static void
645 lnet_peer_table_del_rtrs_locked(struct lnet_net *net,
646                                 struct lnet_peer_table *ptable)
647 {
648         struct lnet_peer_ni     *lp;
649         struct lnet_peer_ni     *tmp;
650         struct lnet_nid         gw_nid;
651         int                     i;
652
653         for (i = 0; i < LNET_PEER_HASH_SIZE; i++) {
654                 list_for_each_entry_safe(lp, tmp, &ptable->pt_hash[i],
655                                          lpni_hashlist) {
656                         if (net != lp->lpni_net)
657                                 continue;
658
659                         if (!lnet_isrouter(lp))
660                                 continue;
661
662                         gw_nid = lp->lpni_peer_net->lpn_peer->lp_primary_nid;
663
664                         lnet_net_unlock(LNET_LOCK_EX);
665                         lnet_del_route(LNET_NET_ANY, &gw_nid);
666                         lnet_net_lock(LNET_LOCK_EX);
667                 }
668         }
669 }
670
671 void
672 lnet_peer_tables_cleanup(struct lnet_net *net)
673 {
674         int i;
675         struct lnet_peer_table *ptable;
676
677         LASSERT(the_lnet.ln_state != LNET_STATE_SHUTDOWN || net != NULL);
678         /* If just deleting the peers for a NI, get rid of any routes these
679          * peers are gateways for. */
680         cfs_percpt_for_each(ptable, i, the_lnet.ln_peer_tables) {
681                 lnet_net_lock(LNET_LOCK_EX);
682                 lnet_peer_table_del_rtrs_locked(net, ptable);
683                 lnet_net_unlock(LNET_LOCK_EX);
684         }
685
686         /* Start the cleanup process */
687         cfs_percpt_for_each(ptable, i, the_lnet.ln_peer_tables) {
688                 lnet_net_lock(LNET_LOCK_EX);
689                 lnet_peer_table_cleanup_locked(net, ptable);
690                 lnet_net_unlock(LNET_LOCK_EX);
691         }
692
693         cfs_percpt_for_each(ptable, i, the_lnet.ln_peer_tables)
694                 lnet_peer_ni_finalize_wait(ptable);
695 }
696
697 static struct lnet_peer_ni *
698 lnet_get_peer_ni_locked(struct lnet_peer_table *ptable, struct lnet_nid *nid)
699 {
700         struct list_head        *peers;
701         struct lnet_peer_ni     *lp;
702
703         if (the_lnet.ln_state != LNET_STATE_RUNNING)
704                 return NULL;
705
706         peers = &ptable->pt_hash[lnet_nid2peerhash(nid)];
707         list_for_each_entry(lp, peers, lpni_hashlist) {
708                 if (nid_same(&lp->lpni_nid, nid)) {
709                         lnet_peer_ni_addref_locked(lp);
710                         return lp;
711                 }
712         }
713
714         return NULL;
715 }
716
717 struct lnet_peer_ni *
718 lnet_peer_ni_find_locked(struct lnet_nid *nid)
719 {
720         struct lnet_peer_ni *lpni;
721         struct lnet_peer_table *ptable;
722         int cpt;
723
724         cpt = lnet_nid_cpt_hash(nid, LNET_CPT_NUMBER);
725
726         ptable = the_lnet.ln_peer_tables[cpt];
727         lpni = lnet_get_peer_ni_locked(ptable, nid);
728
729         return lpni;
730 }
731
732 struct lnet_peer_ni *
733 lnet_peer_ni_get_locked(struct lnet_peer *lp, struct lnet_nid *nid)
734 {
735         struct lnet_peer_net *lpn;
736         struct lnet_peer_ni *lpni;
737
738         lpn = lnet_peer_get_net_locked(lp, LNET_NID_NET(nid));
739         if (!lpn)
740                 return NULL;
741
742         list_for_each_entry(lpni, &lpn->lpn_peer_nis, lpni_peer_nis) {
743                 if (nid_same(&lpni->lpni_nid, nid))
744                         return lpni;
745         }
746
747         return NULL;
748 }
749
750 struct lnet_peer *
751 lnet_find_peer(struct lnet_nid *nid)
752 {
753         struct lnet_peer_ni *lpni;
754         struct lnet_peer *lp = NULL;
755         int cpt;
756
757         cpt = lnet_net_lock_current();
758         lpni = lnet_peer_ni_find_locked(nid);
759         if (lpni) {
760                 lp = lpni->lpni_peer_net->lpn_peer;
761                 lnet_peer_addref_locked(lp);
762                 lnet_peer_ni_decref_locked(lpni);
763         }
764         lnet_net_unlock(cpt);
765
766         return lp;
767 }
768
769 struct lnet_peer_net *
770 lnet_get_next_peer_net_locked(struct lnet_peer *lp, __u32 prev_lpn_id)
771 {
772         struct lnet_peer_net *net;
773
774         if (!prev_lpn_id) {
775                 /* no net id provided return the first net */
776                 net = list_first_entry_or_null(&lp->lp_peer_nets,
777                                                struct lnet_peer_net,
778                                                lpn_peer_nets);
779
780                 return net;
781         }
782
783         /* find the net after the one provided */
784         list_for_each_entry(net, &lp->lp_peer_nets, lpn_peer_nets) {
785                 if (net->lpn_net_id == prev_lpn_id) {
786                         /*
787                          * if we reached the end of the list loop to the
788                          * beginning.
789                          */
790                         if (net->lpn_peer_nets.next == &lp->lp_peer_nets)
791                                 return list_first_entry_or_null(&lp->lp_peer_nets,
792                                                                 struct lnet_peer_net,
793                                                                 lpn_peer_nets);
794                         else
795                                 return list_next_entry(net, lpn_peer_nets);
796                 }
797         }
798
799         return NULL;
800 }
801
802 struct lnet_peer_ni *
803 lnet_get_next_peer_ni_locked(struct lnet_peer *peer,
804                              struct lnet_peer_net *peer_net,
805                              struct lnet_peer_ni *prev)
806 {
807         struct lnet_peer_ni *lpni;
808         struct lnet_peer_net *net = peer_net;
809
810         if (!prev) {
811                 if (!net) {
812                         if (list_empty(&peer->lp_peer_nets))
813                                 return NULL;
814
815                         net = list_first_entry(&peer->lp_peer_nets,
816                                                struct lnet_peer_net,
817                                                lpn_peer_nets);
818                 }
819                 lpni = list_first_entry(&net->lpn_peer_nis, struct lnet_peer_ni,
820                                         lpni_peer_nis);
821
822                 return lpni;
823         }
824
825         if (prev->lpni_peer_nis.next == &prev->lpni_peer_net->lpn_peer_nis) {
826                 /*
827                  * if you reached the end of the peer ni list and the peer
828                  * net is specified then there are no more peer nis in that
829                  * net.
830                  */
831                 if (net)
832                         return NULL;
833
834                 /*
835                  * we reached the end of this net ni list. move to the
836                  * next net
837                  */
838                 if (prev->lpni_peer_net->lpn_peer_nets.next ==
839                     &peer->lp_peer_nets)
840                         /* no more nets and no more NIs. */
841                         return NULL;
842
843                 /* get the next net */
844                 net = list_first_entry(&prev->lpni_peer_net->lpn_peer_nets,
845                                        struct lnet_peer_net,
846                                        lpn_peer_nets);
847                 /* get the ni on it */
848                 lpni = list_first_entry(&net->lpn_peer_nis, struct lnet_peer_ni,
849                                         lpni_peer_nis);
850
851                 return lpni;
852         }
853
854         /* there are more nis left */
855         lpni = list_first_entry(&prev->lpni_peer_nis,
856                                 struct lnet_peer_ni, lpni_peer_nis);
857
858         return lpni;
859 }
860
861 /* Call with the ln_api_mutex held */
862 int lnet_get_peer_list(u32 *countp, u32 *sizep, struct lnet_process_id __user *ids)
863 {
864         struct lnet_process_id id;
865         struct lnet_peer_table *ptable;
866         struct lnet_peer *lp;
867         __u32 count = 0;
868         __u32 size = 0;
869         int lncpt;
870         int cpt;
871         __u32 i;
872         int rc;
873
874         rc = -ESHUTDOWN;
875         if (the_lnet.ln_state != LNET_STATE_RUNNING)
876                 goto done;
877
878         lncpt = cfs_percpt_number(the_lnet.ln_peer_tables);
879
880         /*
881          * Count the number of peers, and return E2BIG if the buffer
882          * is too small. We'll also return the desired size.
883          */
884         rc = -E2BIG;
885         for (cpt = 0; cpt < lncpt; cpt++) {
886                 ptable = the_lnet.ln_peer_tables[cpt];
887                 count += ptable->pt_peers;
888         }
889         size = count * sizeof(*ids);
890         if (size > *sizep)
891                 goto done;
892
893         /*
894          * Walk the peer lists and copy out the primary nids.
895          * This is safe because the peer lists are only modified
896          * while the ln_api_mutex is held. So we don't need to
897          * hold the lnet_net_lock as well, and can therefore
898          * directly call copy_to_user().
899          */
900         rc = -EFAULT;
901         memset(&id, 0, sizeof(id));
902         id.pid = LNET_PID_LUSTRE;
903         i = 0;
904         for (cpt = 0; cpt < lncpt; cpt++) {
905                 ptable = the_lnet.ln_peer_tables[cpt];
906                 list_for_each_entry(lp, &ptable->pt_peer_list, lp_peer_list) {
907                         if (!nid_is_nid4(&lp->lp_primary_nid))
908                                 continue;
909                         if (i >= count)
910                                 goto done;
911                         id.nid = lnet_nid_to_nid4(&lp->lp_primary_nid);
912                         if (copy_to_user(&ids[i], &id, sizeof(id)))
913                                 goto done;
914                         i++;
915                 }
916         }
917         rc = 0;
918 done:
919         *countp = count;
920         *sizep = size;
921         return rc;
922 }
923
924 /*
925  * Start pushes to peers that need to be updated for a configuration
926  * change on this node.
927  */
928 void
929 lnet_push_update_to_peers(int force)
930 {
931         struct lnet_peer_table *ptable;
932         struct lnet_peer *lp;
933         int lncpt;
934         int cpt;
935
936         lnet_net_lock(LNET_LOCK_EX);
937         if (lnet_peer_discovery_disabled)
938                 force = 0;
939         lncpt = cfs_percpt_number(the_lnet.ln_peer_tables);
940         for (cpt = 0; cpt < lncpt; cpt++) {
941                 ptable = the_lnet.ln_peer_tables[cpt];
942                 list_for_each_entry(lp, &ptable->pt_peer_list, lp_peer_list) {
943                         if (force) {
944                                 spin_lock(&lp->lp_lock);
945                                 if (lp->lp_state & LNET_PEER_MULTI_RAIL)
946                                         lp->lp_state |= LNET_PEER_FORCE_PUSH;
947                                 spin_unlock(&lp->lp_lock);
948                         }
949                         if (lnet_peer_needs_push(lp))
950                                 lnet_peer_queue_for_discovery(lp);
951                 }
952         }
953         lnet_net_unlock(LNET_LOCK_EX);
954         wake_up(&the_lnet.ln_dc_waitq);
955 }
956
957 /* find the NID in the preferred gateways for the remote peer
958  * return:
959  *      false: list is not empty and NID is not preferred
960  *      false: list is empty
961  *      true: nid is found in the list
962  */
963 bool
964 lnet_peer_is_pref_rtr_locked(struct lnet_peer_ni *lpni,
965                              struct lnet_nid *gw_nid)
966 {
967         struct lnet_nid_list *ne;
968
969         CDEBUG(D_NET, "%s: rtr pref emtpy: %d\n",
970                libcfs_nidstr(&lpni->lpni_nid),
971                list_empty(&lpni->lpni_rtr_pref_nids));
972
973         if (list_empty(&lpni->lpni_rtr_pref_nids))
974                 return false;
975
976         /* iterate through all the preferred NIDs and see if any of them
977          * matches the provided gw_nid
978          */
979         list_for_each_entry(ne, &lpni->lpni_rtr_pref_nids, nl_list) {
980                 CDEBUG(D_NET, "Comparing pref %s with gw %s\n",
981                        libcfs_nidstr(&ne->nl_nid),
982                        libcfs_nidstr(gw_nid));
983                 if (nid_same(&ne->nl_nid, gw_nid))
984                         return true;
985         }
986
987         return false;
988 }
989
990 void
991 lnet_peer_clr_pref_rtrs(struct lnet_peer_ni *lpni)
992 {
993         struct list_head zombies;
994         struct lnet_nid_list *ne;
995         struct lnet_nid_list *tmp;
996         int cpt = lpni->lpni_cpt;
997
998         INIT_LIST_HEAD(&zombies);
999
1000         lnet_net_lock(cpt);
1001         list_splice_init(&lpni->lpni_rtr_pref_nids, &zombies);
1002         lnet_net_unlock(cpt);
1003
1004         list_for_each_entry_safe(ne, tmp, &zombies, nl_list) {
1005                 list_del(&ne->nl_list);
1006                 LIBCFS_FREE(ne, sizeof(*ne));
1007         }
1008 }
1009
1010 int
1011 lnet_peer_add_pref_rtr(struct lnet_peer_ni *lpni,
1012                        struct lnet_nid *gw_nid)
1013 {
1014         int cpt = lpni->lpni_cpt;
1015         struct lnet_nid_list *ne = NULL;
1016
1017         /* This function is called with api_mutex held. When the api_mutex
1018          * is held the list can not be modified, as it is only modified as
1019          * a result of applying a UDSP and that happens under api_mutex
1020          * lock.
1021          */
1022         __must_hold(&the_lnet.ln_api_mutex);
1023
1024         list_for_each_entry(ne, &lpni->lpni_rtr_pref_nids, nl_list) {
1025                 if (nid_same(&ne->nl_nid, gw_nid))
1026                         return -EEXIST;
1027         }
1028
1029         LIBCFS_CPT_ALLOC(ne, lnet_cpt_table(), cpt, sizeof(*ne));
1030         if (!ne)
1031                 return -ENOMEM;
1032
1033         ne->nl_nid = *gw_nid;
1034
1035         /* Lock the cpt to protect against addition and checks in the
1036          * selection algorithm
1037          */
1038         lnet_net_lock(cpt);
1039         list_add(&ne->nl_list, &lpni->lpni_rtr_pref_nids);
1040         lnet_net_unlock(cpt);
1041
1042         return 0;
1043 }
1044
1045 /*
1046  * Test whether a ni is a preferred ni for this peer_ni, e.g, whether
1047  * this is a preferred point-to-point path. Call with lnet_net_lock in
1048  * shared mmode.
1049  */
1050 bool
1051 lnet_peer_is_pref_nid_locked(struct lnet_peer_ni *lpni, struct lnet_nid *nid)
1052 {
1053         struct lnet_nid_list *ne;
1054
1055         if (lpni->lpni_pref_nnids == 0)
1056                 return false;
1057         if (lpni->lpni_pref_nnids == 1)
1058                 return nid_same(&lpni->lpni_pref.nid, nid);
1059         list_for_each_entry(ne, &lpni->lpni_pref.nids, nl_list) {
1060                 if (nid_same(&ne->nl_nid, nid))
1061                         return true;
1062         }
1063         return false;
1064 }
1065
1066 /*
1067  * Set a single ni as preferred, provided no preferred ni is already
1068  * defined. Only to be used for non-multi-rail peer_ni.
1069  */
1070 int
1071 lnet_peer_ni_set_non_mr_pref_nid(struct lnet_peer_ni *lpni,
1072                                   struct lnet_nid *nid)
1073 {
1074         int rc = 0;
1075
1076         if (!nid)
1077                 return -EINVAL;
1078         spin_lock(&lpni->lpni_lock);
1079         if (LNET_NID_IS_ANY(nid)) {
1080                 rc = -EINVAL;
1081         } else if (lpni->lpni_pref_nnids > 0) {
1082                 rc = -EPERM;
1083         } else if (lpni->lpni_pref_nnids == 0) {
1084                 lpni->lpni_pref.nid = *nid;
1085                 lpni->lpni_pref_nnids = 1;
1086                 lpni->lpni_state |= LNET_PEER_NI_NON_MR_PREF;
1087         }
1088         spin_unlock(&lpni->lpni_lock);
1089
1090         CDEBUG(D_NET, "peer %s nid %s: %d\n",
1091                libcfs_nidstr(&lpni->lpni_nid), libcfs_nidstr(nid), rc);
1092         return rc;
1093 }
1094
1095 /*
1096  * Clear the preferred NID from a non-multi-rail peer_ni, provided
1097  * this preference was set by lnet_peer_ni_set_non_mr_pref_nid().
1098  */
1099 int
1100 lnet_peer_ni_clr_non_mr_pref_nid(struct lnet_peer_ni *lpni)
1101 {
1102         int rc = 0;
1103
1104         spin_lock(&lpni->lpni_lock);
1105         if (lpni->lpni_state & LNET_PEER_NI_NON_MR_PREF) {
1106                 lpni->lpni_pref_nnids = 0;
1107                 lpni->lpni_state &= ~LNET_PEER_NI_NON_MR_PREF;
1108         } else if (lpni->lpni_pref_nnids == 0) {
1109                 rc = -ENOENT;
1110         } else {
1111                 rc = -EPERM;
1112         }
1113         spin_unlock(&lpni->lpni_lock);
1114
1115         CDEBUG(D_NET, "peer %s: %d\n",
1116                libcfs_nidstr(&lpni->lpni_nid), rc);
1117         return rc;
1118 }
1119
1120 void
1121 lnet_peer_ni_set_selection_priority(struct lnet_peer_ni *lpni, __u32 priority)
1122 {
1123         lpni->lpni_sel_priority = priority;
1124 }
1125
1126 /*
1127  * Clear the preferred NIDs from a non-multi-rail peer.
1128  */
1129 void
1130 lnet_peer_clr_non_mr_pref_nids(struct lnet_peer *lp)
1131 {
1132         struct lnet_peer_ni *lpni = NULL;
1133
1134         while ((lpni = lnet_get_next_peer_ni_locked(lp, NULL, lpni)) != NULL)
1135                 lnet_peer_ni_clr_non_mr_pref_nid(lpni);
1136 }
1137
1138 int
1139 lnet_peer_add_pref_nid(struct lnet_peer_ni *lpni, struct lnet_nid *nid)
1140 {
1141         struct lnet_peer *lp = lpni->lpni_peer_net->lpn_peer;
1142         struct lnet_nid_list *ne1 = NULL;
1143         struct lnet_nid_list *ne2 = NULL;
1144         struct lnet_nid *tmp_nid = NULL;
1145         int rc = 0;
1146
1147         if (LNET_NID_IS_ANY(nid)) {
1148                 rc = -EINVAL;
1149                 goto out;
1150         }
1151
1152         if (lpni->lpni_pref_nnids == 1 &&
1153             nid_same(&lpni->lpni_pref.nid, nid)) {
1154                 rc = -EEXIST;
1155                 goto out;
1156         }
1157
1158         /* A non-MR node may have only one preferred NI per peer_ni */
1159         if (lpni->lpni_pref_nnids > 0 &&
1160             !(lp->lp_state & LNET_PEER_MULTI_RAIL)) {
1161                 rc = -EPERM;
1162                 goto out;
1163         }
1164
1165         /* add the new preferred nid to the list of preferred nids */
1166         if (lpni->lpni_pref_nnids != 0) {
1167                 size_t alloc_size = sizeof(*ne1);
1168
1169                 if (lpni->lpni_pref_nnids == 1) {
1170                         tmp_nid = &lpni->lpni_pref.nid;
1171                         INIT_LIST_HEAD(&lpni->lpni_pref.nids);
1172                 }
1173
1174                 list_for_each_entry(ne1, &lpni->lpni_pref.nids, nl_list) {
1175                         if (nid_same(&ne1->nl_nid, nid)) {
1176                                 rc = -EEXIST;
1177                                 goto out;
1178                         }
1179                 }
1180
1181                 LIBCFS_CPT_ALLOC(ne1, lnet_cpt_table(), lpni->lpni_cpt,
1182                                  alloc_size);
1183                 if (!ne1) {
1184                         rc = -ENOMEM;
1185                         goto out;
1186                 }
1187
1188                 /* move the originally stored nid to the list */
1189                 if (lpni->lpni_pref_nnids == 1) {
1190                         LIBCFS_CPT_ALLOC(ne2, lnet_cpt_table(),
1191                                 lpni->lpni_cpt, alloc_size);
1192                         if (!ne2) {
1193                                 rc = -ENOMEM;
1194                                 goto out;
1195                         }
1196                         INIT_LIST_HEAD(&ne2->nl_list);
1197                         ne2->nl_nid = *tmp_nid;
1198                 }
1199                 ne1->nl_nid = *nid;
1200         }
1201
1202         lnet_net_lock(LNET_LOCK_EX);
1203         spin_lock(&lpni->lpni_lock);
1204         if (lpni->lpni_pref_nnids == 0) {
1205                 lpni->lpni_pref.nid = *nid;
1206         } else {
1207                 if (ne2)
1208                         list_add_tail(&ne2->nl_list, &lpni->lpni_pref.nids);
1209                 list_add_tail(&ne1->nl_list, &lpni->lpni_pref.nids);
1210         }
1211         lpni->lpni_pref_nnids++;
1212         lpni->lpni_state &= ~LNET_PEER_NI_NON_MR_PREF;
1213         spin_unlock(&lpni->lpni_lock);
1214         lnet_net_unlock(LNET_LOCK_EX);
1215
1216 out:
1217         if (rc == -EEXIST && (lpni->lpni_state & LNET_PEER_NI_NON_MR_PREF)) {
1218                 spin_lock(&lpni->lpni_lock);
1219                 lpni->lpni_state &= ~LNET_PEER_NI_NON_MR_PREF;
1220                 spin_unlock(&lpni->lpni_lock);
1221         }
1222         CDEBUG(D_NET, "peer %s nid %s: %d\n",
1223                libcfs_nidstr(&lp->lp_primary_nid), libcfs_nidstr(nid), rc);
1224         return rc;
1225 }
1226
1227 int
1228 lnet_peer_del_pref_nid(struct lnet_peer_ni *lpni, struct lnet_nid *nid)
1229 {
1230         struct lnet_peer *lp = lpni->lpni_peer_net->lpn_peer;
1231         struct lnet_nid_list *ne = NULL;
1232         int rc = 0;
1233
1234         if (lpni->lpni_pref_nnids == 0) {
1235                 rc = -ENOENT;
1236                 goto out;
1237         }
1238
1239         if (lpni->lpni_pref_nnids == 1) {
1240                 if (!nid_same(&lpni->lpni_pref.nid, nid)) {
1241                         rc = -ENOENT;
1242                         goto out;
1243                 }
1244         } else {
1245                 list_for_each_entry(ne, &lpni->lpni_pref.nids, nl_list) {
1246                         if (nid_same(&ne->nl_nid, nid))
1247                                 goto remove_nid_entry;
1248                 }
1249                 rc = -ENOENT;
1250                 ne = NULL;
1251                 goto out;
1252         }
1253
1254 remove_nid_entry:
1255         lnet_net_lock(LNET_LOCK_EX);
1256         spin_lock(&lpni->lpni_lock);
1257         if (lpni->lpni_pref_nnids == 1)
1258                 lpni->lpni_pref.nid = LNET_ANY_NID;
1259         else {
1260                 list_del_init(&ne->nl_list);
1261                 if (lpni->lpni_pref_nnids == 2) {
1262                         struct lnet_nid_list *ne, *tmp;
1263
1264                         list_for_each_entry_safe(ne, tmp,
1265                                                  &lpni->lpni_pref.nids,
1266                                                  nl_list) {
1267                                 lpni->lpni_pref.nid = ne->nl_nid;
1268                                 list_del_init(&ne->nl_list);
1269                                 LIBCFS_FREE(ne, sizeof(*ne));
1270                         }
1271                 }
1272         }
1273         lpni->lpni_pref_nnids--;
1274         lpni->lpni_state &= ~LNET_PEER_NI_NON_MR_PREF;
1275         spin_unlock(&lpni->lpni_lock);
1276         lnet_net_unlock(LNET_LOCK_EX);
1277
1278         if (ne)
1279                 LIBCFS_FREE(ne, sizeof(*ne));
1280 out:
1281         CDEBUG(D_NET, "peer %s nid %s: %d\n",
1282                libcfs_nidstr(&lp->lp_primary_nid), libcfs_nidstr(nid), rc);
1283         return rc;
1284 }
1285
1286 void
1287 lnet_peer_clr_pref_nids(struct lnet_peer_ni *lpni)
1288 {
1289         struct list_head zombies;
1290         struct lnet_nid_list *ne;
1291         struct lnet_nid_list *tmp;
1292
1293         INIT_LIST_HEAD(&zombies);
1294
1295         lnet_net_lock(LNET_LOCK_EX);
1296         if (lpni->lpni_pref_nnids == 1)
1297                 lpni->lpni_pref.nid = LNET_ANY_NID;
1298         else if (lpni->lpni_pref_nnids > 1)
1299                 list_splice_init(&lpni->lpni_pref.nids, &zombies);
1300         lpni->lpni_pref_nnids = 0;
1301         lnet_net_unlock(LNET_LOCK_EX);
1302
1303         list_for_each_entry_safe(ne, tmp, &zombies, nl_list) {
1304                 list_del_init(&ne->nl_list);
1305                 LIBCFS_FREE(ne, sizeof(*ne));
1306         }
1307 }
1308
1309 void
1310 lnet_peer_primary_nid_locked(struct lnet_nid *nid, struct lnet_nid *result)
1311 {
1312         struct lnet_peer_ni *lpni;
1313
1314         *result = *nid;
1315         lpni = lnet_peer_ni_find_locked(nid);
1316         if (lpni) {
1317                 *result = lpni->lpni_peer_net->lpn_peer->lp_primary_nid;
1318                 lnet_peer_ni_decref_locked(lpni);
1319         }
1320 }
1321
1322 bool
1323 lnet_is_discovery_disabled_locked(struct lnet_peer *lp)
1324 __must_hold(&lp->lp_lock)
1325 {
1326         if (lnet_peer_discovery_disabled)
1327                 return true;
1328
1329         if (!(lp->lp_state & LNET_PEER_MULTI_RAIL) ||
1330             (lp->lp_state & LNET_PEER_NO_DISCOVERY)) {
1331                 return true;
1332         }
1333
1334         return false;
1335 }
1336
1337 /*
1338  * Peer Discovery
1339  */
1340 bool
1341 lnet_is_discovery_disabled(struct lnet_peer *lp)
1342 {
1343         bool rc = false;
1344
1345         spin_lock(&lp->lp_lock);
1346         rc = lnet_is_discovery_disabled_locked(lp);
1347         spin_unlock(&lp->lp_lock);
1348
1349         return rc;
1350 }
1351
1352 int
1353 LNetAddPeer(struct lnet_nid *nids, u32 num_nids)
1354 {
1355         struct lnet_nid pnid = LNET_ANY_NID;
1356         bool mr;
1357         int i, rc;
1358         int flags = lock_prim_nid ? LNET_PEER_LOCK_PRIMARY : 0;
1359
1360         if (!nids || num_nids < 1)
1361                 return -EINVAL;
1362
1363         rc = LNetNIInit(LNET_PID_ANY);
1364         if (rc < 0)
1365                 return rc;
1366
1367         mutex_lock(&the_lnet.ln_api_mutex);
1368
1369         mr = lnet_peer_discovery_disabled == 0;
1370
1371         rc = 0;
1372         for (i = 0; i < num_nids; i++) {
1373                 if (nid_is_lo0(&nids[i]))
1374                         continue;
1375
1376                 if (LNET_NID_IS_ANY(&pnid)) {
1377                         pnid = nids[i];
1378                         rc = lnet_add_peer_ni(&pnid, &LNET_ANY_NID, mr, flags);
1379                         if (rc == -EALREADY) {
1380                                 struct lnet_peer *lp;
1381
1382                                 CDEBUG(D_NET, "A peer exists for NID %s\n",
1383                                        libcfs_nidstr(&pnid));
1384                                 rc = 0;
1385                                 /* Adds a refcount */
1386                                 lp = lnet_find_peer(&pnid);
1387                                 LASSERT(lp);
1388                                 pnid = lp->lp_primary_nid;
1389                                 /* Drop refcount from lookup */
1390                                 lnet_peer_decref_locked(lp);
1391                         }
1392                 } else if (lnet_peer_discovery_disabled) {
1393                         rc = lnet_add_peer_ni(&nids[i], &LNET_ANY_NID, mr,
1394                                               flags);
1395                 } else {
1396                         rc = lnet_add_peer_ni(&pnid, &nids[i], mr,
1397                                               flags);
1398                 }
1399
1400                 if (rc && rc != -EEXIST)
1401                         goto unlock;
1402         }
1403
1404 unlock:
1405         mutex_unlock(&the_lnet.ln_api_mutex);
1406
1407         LNetNIFini();
1408
1409         return rc == -EEXIST ? 0 : rc;
1410 }
1411 EXPORT_SYMBOL(LNetAddPeer);
1412
1413 void LNetPrimaryNID(struct lnet_nid *nid)
1414 {
1415         struct lnet_peer *lp;
1416         struct lnet_peer_ni *lpni;
1417         struct lnet_nid orig;
1418         int rc = 0;
1419         int cpt;
1420
1421         if (!nid || nid_is_lo0(nid))
1422                 return;
1423         orig = *nid;
1424
1425         cpt = lnet_net_lock_current();
1426         lpni = lnet_peerni_by_nid_locked(nid, NULL, cpt);
1427         if (IS_ERR(lpni)) {
1428                 rc = PTR_ERR(lpni);
1429                 goto out_unlock;
1430         }
1431         lp = lpni->lpni_peer_net->lpn_peer;
1432
1433         /* If discovery is disabled locally then we needn't bother running
1434          * discovery here because discovery will not modify whatever
1435          * primary NID is currently set for this peer. If the specified peer is
1436          * down then this discovery can introduce long delays into the mount
1437          * process, so skip it if it isn't necessary.
1438          */
1439 again:
1440         spin_lock(&lp->lp_lock);
1441         if (!(lp->lp_state & LNET_PEER_LOCK_PRIMARY) && lock_prim_nid)
1442                 lp->lp_state |= LNET_PEER_LOCK_PRIMARY;
1443
1444         /* DD disabled, nothing to do */
1445         if (lnet_peer_discovery_disabled) {
1446                 *nid = lp->lp_primary_nid;
1447                 spin_unlock(&lp->lp_lock);
1448                 goto out_decref;
1449         }
1450
1451         /* Peer already up to date, nothing to do */
1452         if (lnet_peer_is_uptodate_locked(lp)) {
1453                 *nid = lp->lp_primary_nid;
1454                 spin_unlock(&lp->lp_lock);
1455                 goto out_decref;
1456         }
1457         spin_unlock(&lp->lp_lock);
1458
1459         /* If primary nid locking is enabled, discovery is performed
1460          * in the background.
1461          * If primary nid locking is disabled, discovery blocks here.
1462          * Messages to the peer will not go through until the discovery is
1463          * complete.
1464          */
1465         if (lock_prim_nid)
1466                 rc = lnet_discover_peer_locked(lpni, cpt, false);
1467         else
1468                 rc = lnet_discover_peer_locked(lpni, cpt, true);
1469         if (rc)
1470                 goto out_decref;
1471
1472         /* The lpni (or lp) for this NID may have changed and our ref is
1473          * the only thing keeping the old one around. Release the ref
1474          * and lookup the lpni again
1475          */
1476         lnet_peer_ni_decref_locked(lpni);
1477         lpni = lnet_peer_ni_find_locked(nid);
1478         if (!lpni) {
1479                 rc = -ENOENT;
1480                 goto out_unlock;
1481         }
1482         lp = lpni->lpni_peer_net->lpn_peer;
1483
1484         if (!lock_prim_nid && !lnet_is_discovery_disabled(lp))
1485                 goto again;
1486         *nid = lp->lp_primary_nid;
1487 out_decref:
1488         lnet_peer_ni_decref_locked(lpni);
1489 out_unlock:
1490         lnet_net_unlock(cpt);
1491
1492         CDEBUG(D_NET, "NID %s primary NID %s rc %d\n", libcfs_nidstr(&orig),
1493                libcfs_nidstr(nid), rc);
1494 }
1495 EXPORT_SYMBOL(LNetPrimaryNID);
1496
1497 struct lnet_peer_net *
1498 lnet_peer_get_net_locked(struct lnet_peer *peer, __u32 net_id)
1499 {
1500         struct lnet_peer_net *peer_net;
1501         list_for_each_entry(peer_net, &peer->lp_peer_nets, lpn_peer_nets) {
1502                 if (peer_net->lpn_net_id == net_id)
1503                         return peer_net;
1504         }
1505         return NULL;
1506 }
1507
1508 /*
1509  * Attach a peer_ni to a peer_net and peer. This function assumes
1510  * peer_ni is not already attached to the peer_net/peer. The peer_ni
1511  * may be attached to a different peer, in which case it will be
1512  * properly detached first. The whole operation is done atomically.
1513  *
1514  * This function consumes the reference on lpni and Always returns 0.
1515  * This is the last function called from functions that do return an
1516  * int, so returning 0 here allows the compiler to do a tail call.
1517  */
1518 static int
1519 lnet_peer_attach_peer_ni(struct lnet_peer *lp,
1520                          struct lnet_peer_net *lpn,
1521                          struct lnet_peer_ni *lpni,
1522                          unsigned flags)
1523 {
1524         struct lnet_peer_table *ptable;
1525         bool new_lpn = false;
1526         int rc;
1527
1528         /* Install the new peer_ni */
1529         lnet_net_lock(LNET_LOCK_EX);
1530         /* Add peer_ni to global peer table hash, if necessary. */
1531         if (list_empty(&lpni->lpni_hashlist)) {
1532                 int hash = lnet_nid2peerhash(&lpni->lpni_nid);
1533
1534                 ptable = the_lnet.ln_peer_tables[lpni->lpni_cpt];
1535                 list_add_tail(&lpni->lpni_hashlist, &ptable->pt_hash[hash]);
1536                 ptable->pt_version++;
1537                 lnet_peer_ni_addref_locked(lpni);
1538         }
1539
1540         /* Detach the peer_ni from an existing peer, if necessary. */
1541         if (lpni->lpni_peer_net) {
1542                 LASSERT(lpni->lpni_peer_net != lpn);
1543                 LASSERT(lpni->lpni_peer_net->lpn_peer != lp);
1544                 lnet_peer_detach_peer_ni_locked(lpni);
1545                 lnet_peer_net_decref_locked(lpni->lpni_peer_net);
1546                 lpni->lpni_peer_net = NULL;
1547         }
1548
1549         /* Add peer_ni to peer_net */
1550         lpni->lpni_peer_net = lpn;
1551         if (nid_same(&lp->lp_primary_nid, &lpni->lpni_nid))
1552                 list_add(&lpni->lpni_peer_nis, &lpn->lpn_peer_nis);
1553         else
1554                 list_add_tail(&lpni->lpni_peer_nis, &lpn->lpn_peer_nis);
1555         lnet_update_peer_net_healthv(lpni);
1556         lnet_peer_net_addref_locked(lpn);
1557
1558         /* Add peer_net to peer */
1559         if (!lpn->lpn_peer) {
1560                 new_lpn = true;
1561                 lpn->lpn_peer = lp;
1562                 if (nid_same(&lp->lp_primary_nid, &lpni->lpni_nid))
1563                         list_add(&lpn->lpn_peer_nets, &lp->lp_peer_nets);
1564                 else
1565                         list_add_tail(&lpn->lpn_peer_nets, &lp->lp_peer_nets);
1566                 lnet_peer_addref_locked(lp);
1567         }
1568
1569         /* Add peer to global peer list, if necessary */
1570         ptable = the_lnet.ln_peer_tables[lp->lp_cpt];
1571         if (list_empty(&lp->lp_peer_list)) {
1572                 list_add_tail(&lp->lp_peer_list, &ptable->pt_peer_list);
1573                 ptable->pt_peers++;
1574         }
1575
1576         /* Update peer state */
1577         spin_lock(&lp->lp_lock);
1578         if (flags & LNET_PEER_CONFIGURED) {
1579                 if (!(lp->lp_state & LNET_PEER_CONFIGURED))
1580                         lp->lp_state |= LNET_PEER_CONFIGURED;
1581         }
1582         if (flags & LNET_PEER_MULTI_RAIL) {
1583                 if (!(lp->lp_state & LNET_PEER_MULTI_RAIL)) {
1584                         lp->lp_state |= LNET_PEER_MULTI_RAIL;
1585                         lnet_peer_clr_non_mr_pref_nids(lp);
1586                 }
1587         }
1588         if (flags & LNET_PEER_LOCK_PRIMARY)
1589                 lp->lp_state |= LNET_PEER_LOCK_PRIMARY;
1590         spin_unlock(&lp->lp_lock);
1591
1592         lp->lp_nnis++;
1593
1594         /* apply UDSPs */
1595         if (new_lpn) {
1596                 rc = lnet_udsp_apply_policies_on_lpn(lpn);
1597                 if (rc)
1598                         CERROR("Failed to apply UDSPs on lpn %s\n",
1599                                libcfs_net2str(lpn->lpn_net_id));
1600         }
1601         rc = lnet_udsp_apply_policies_on_lpni(lpni);
1602         if (rc)
1603                 CERROR("Failed to apply UDSPs on lpni %s\n",
1604                        libcfs_nidstr(&lpni->lpni_nid));
1605
1606         CDEBUG(D_NET, "peer %s NID %s flags %#x\n",
1607                libcfs_nidstr(&lp->lp_primary_nid),
1608                libcfs_nidstr(&lpni->lpni_nid), flags);
1609         lnet_peer_ni_decref_locked(lpni);
1610         lnet_net_unlock(LNET_LOCK_EX);
1611
1612         return 0;
1613 }
1614
1615 /*
1616  * Create a new peer, with nid as its primary nid.
1617  *
1618  * Call with the lnet_api_mutex held.
1619  */
1620 static int
1621 lnet_peer_add(struct lnet_nid *nid, unsigned int flags)
1622 {
1623         struct lnet_peer *lp;
1624         struct lnet_peer_net *lpn;
1625         struct lnet_peer_ni *lpni;
1626         int rc = 0;
1627
1628         LASSERT(nid);
1629
1630         /*
1631          * No need for the lnet_net_lock here, because the
1632          * lnet_api_mutex is held.
1633          */
1634         lpni = lnet_peer_ni_find_locked(nid);
1635         if (lpni) {
1636                 /* A peer with this NID already exists. */
1637                 lp = lpni->lpni_peer_net->lpn_peer;
1638                 lnet_peer_ni_decref_locked(lpni);
1639                 /*
1640                  * This is an error if the peer was configured and the
1641                  * primary NID differs or an attempt is made to change
1642                  * the Multi-Rail flag. Otherwise the assumption is
1643                  * that an existing peer is being modified.
1644                  */
1645                 if (lp->lp_state & LNET_PEER_CONFIGURED) {
1646                         if (!nid_same(&lp->lp_primary_nid, nid))
1647                                 rc = -EEXIST;
1648                         else if ((lp->lp_state ^ flags) & LNET_PEER_MULTI_RAIL)
1649                                 rc = -EPERM;
1650                         goto out;
1651                 } else if (lp->lp_state & LNET_PEER_LOCK_PRIMARY) {
1652                         if (nid_same(&lp->lp_primary_nid, nid))
1653                                 rc = -EEXIST;
1654                         /* we're trying to recreate an existing peer which
1655                          * has already been created and its primary
1656                          * locked. This is likely due to two servers
1657                          * existing on the same node. So we'll just refer
1658                          * to that node with the primary NID which was
1659                          * first added by Lustre
1660                          */
1661                         else
1662                                 rc = -EALREADY;
1663                         goto out;
1664                 } else if (!(flags & (LNET_PEER_LOCK_PRIMARY | LNET_PEER_CONFIGURED))) {
1665                         /* if not recreating peer as configured and
1666                          * not locking primary nid, no need to
1667                          * do anything if primary nid is not being changed
1668                          */
1669                         if (nid_same(&lp->lp_primary_nid, nid)) {
1670                                 rc = -EEXIST;
1671                                 goto out;
1672                         }
1673                 }
1674                 /* Delete and recreate the peer.
1675                  * We can get here:
1676                  * 1. If the peer is being recreated as a configured NID
1677                  * 2. if there already exists a peer which
1678                  *    was discovered manually, but is recreated via Lustre
1679                  *    with PRIMARY_lock
1680                  */
1681                 rc = lnet_peer_del(lp);
1682                 if (rc)
1683                         goto out;
1684         }
1685
1686         /* Create peer, peer_net, and peer_ni. */
1687         rc = -ENOMEM;
1688         lp = lnet_peer_alloc(nid);
1689         if (!lp)
1690                 goto out;
1691         lpn = lnet_peer_net_alloc(LNET_NID_NET(nid));
1692         if (!lpn)
1693                 goto out_free_lp;
1694         lpni = lnet_peer_ni_alloc(nid);
1695         if (!lpni)
1696                 goto out_free_lpn;
1697
1698         return lnet_peer_attach_peer_ni(lp, lpn, lpni, flags);
1699
1700 out_free_lpn:
1701         LIBCFS_FREE(lpn, sizeof(*lpn));
1702 out_free_lp:
1703         LIBCFS_FREE(lp, sizeof(*lp));
1704 out:
1705         CDEBUG(D_NET, "peer %s NID flags %#x: %d\n",
1706                libcfs_nidstr(nid), flags, rc);
1707         return rc;
1708 }
1709
1710 /*
1711  * Add a NID to a peer. Call with ln_api_mutex held.
1712  *
1713  * Error codes:
1714  *  -EPERM:    Non-DLC addition to a DLC-configured peer.
1715  *  -EEXIST:   The NID was configured by DLC for a different peer.
1716  *  -ENOMEM:   Out of memory.
1717  *  -ENOTUNIQ: Adding a second peer NID on a single network on a
1718  *             non-multi-rail peer.
1719  */
1720 static int
1721 lnet_peer_add_nid(struct lnet_peer *lp, struct lnet_nid *nid,
1722                   unsigned int flags)
1723 {
1724         struct lnet_peer_net *lpn;
1725         struct lnet_peer_ni *lpni;
1726         int rc = 0;
1727
1728         LASSERT(lp);
1729         LASSERT(nid);
1730
1731         /* A configured peer can only be updated through configuration. */
1732         if (!(flags & LNET_PEER_CONFIGURED)) {
1733                 if (lp->lp_state & LNET_PEER_CONFIGURED) {
1734                         rc = -EPERM;
1735                         goto out;
1736                 }
1737         }
1738
1739         /*
1740          * The MULTI_RAIL flag can be set but not cleared, because
1741          * that would leave the peer struct in an invalid state.
1742          */
1743         if (flags & LNET_PEER_MULTI_RAIL) {
1744                 spin_lock(&lp->lp_lock);
1745                 if (!(lp->lp_state & LNET_PEER_MULTI_RAIL)) {
1746                         lp->lp_state |= LNET_PEER_MULTI_RAIL;
1747                         lnet_peer_clr_non_mr_pref_nids(lp);
1748                 }
1749                 spin_unlock(&lp->lp_lock);
1750         } else if (lp->lp_state & LNET_PEER_MULTI_RAIL) {
1751                 rc = -EPERM;
1752                 goto out;
1753         }
1754
1755         lpni = lnet_peer_ni_find_locked(nid);
1756         if (lpni) {
1757                 /*
1758                  * A peer_ni already exists. This is only a problem if
1759                  * it is not connected to this peer and was configured
1760                  * by DLC.
1761                  */
1762                 if (lpni->lpni_peer_net->lpn_peer == lp)
1763                         goto out_free_lpni;
1764                 if (lnet_peer_ni_is_configured(lpni)) {
1765                         rc = -EEXIST;
1766                         goto out_free_lpni;
1767                 }
1768                 /* If this is the primary NID, destroy the peer. */
1769                 if (lnet_peer_ni_is_primary(lpni)) {
1770                         struct lnet_peer *lp2 =
1771                                 lpni->lpni_peer_net->lpn_peer;
1772                         int rtr_refcount = lp2->lp_rtr_refcount;
1773
1774                         /* If the new peer that this NID belongs to is
1775                          * a primary NID for another peer which we're
1776                          * suppose to preserve the Primary for then we
1777                          * don't want to mess with it. But the
1778                          * configuration is wrong at this point, so we
1779                          * should flag both of these peers as in a bad
1780                          * state
1781                          */
1782                         if (lp2->lp_state & LNET_PEER_LOCK_PRIMARY) {
1783                                 spin_lock(&lp->lp_lock);
1784                                 lp->lp_state |= LNET_PEER_BAD_CONFIG;
1785                                 spin_unlock(&lp->lp_lock);
1786                                 spin_lock(&lp2->lp_lock);
1787                                 lp2->lp_state |= LNET_PEER_BAD_CONFIG;
1788                                 spin_unlock(&lp2->lp_lock);
1789                                 goto out_free_lpni;
1790                         }
1791                         /*
1792                          * if we're trying to delete a router it means
1793                          * we're moving this peer NI to a new peer so must
1794                          * transfer router properties to the new peer
1795                          */
1796                         if (rtr_refcount > 0) {
1797                                 flags |= LNET_PEER_RTR_NI_FORCE_DEL;
1798                                 lnet_rtr_transfer_to_peer(lp2, lp);
1799                         }
1800                         lnet_peer_del(lp2);
1801                         lnet_peer_ni_decref_locked(lpni);
1802                         lpni = lnet_peer_ni_alloc(nid);
1803                         if (!lpni) {
1804                                 rc = -ENOMEM;
1805                                 goto out_free_lpni;
1806                         }
1807                 }
1808         } else {
1809                 lpni = lnet_peer_ni_alloc(nid);
1810                 if (!lpni) {
1811                         rc = -ENOMEM;
1812                         goto out_free_lpni;
1813                 }
1814         }
1815
1816         /*
1817          * Get the peer_net. Check that we're not adding a second
1818          * peer_ni on a peer_net of a non-multi-rail peer.
1819          */
1820         lpn = lnet_peer_get_net_locked(lp, LNET_NID_NET(nid));
1821         if (!lpn) {
1822                 lpn = lnet_peer_net_alloc(LNET_NID_NET(nid));
1823                 if (!lpn) {
1824                         rc = -ENOMEM;
1825                         goto out_free_lpni;
1826                 }
1827         } else if (!(lp->lp_state & LNET_PEER_MULTI_RAIL)) {
1828                 rc = -ENOTUNIQ;
1829                 goto out_free_lpni;
1830         }
1831
1832         return lnet_peer_attach_peer_ni(lp, lpn, lpni, flags);
1833
1834 out_free_lpni:
1835         lnet_peer_ni_decref_locked(lpni);
1836 out:
1837         CDEBUG(D_NET, "peer %s NID %s flags %#x: %d\n",
1838                libcfs_nidstr(&lp->lp_primary_nid), libcfs_nidstr(nid),
1839                flags, rc);
1840         return rc;
1841 }
1842
1843 /*
1844  * Update the primary NID of a peer, if possible.
1845  *
1846  * Call with the lnet_api_mutex held.
1847  */
1848 static int
1849 lnet_peer_set_primary_nid(struct lnet_peer *lp, struct lnet_nid *nid,
1850                           unsigned int flags)
1851 {
1852         struct lnet_nid old = lp->lp_primary_nid;
1853         int rc = 0;
1854
1855         if (nid_same(&lp->lp_primary_nid, nid))
1856                 goto out;
1857
1858         if (!(lp->lp_state & LNET_PEER_LOCK_PRIMARY))
1859                 lp->lp_primary_nid = *nid;
1860
1861         rc = lnet_peer_add_nid(lp, nid, flags);
1862         if (rc) {
1863                 lp->lp_primary_nid = old;
1864                 goto out;
1865         }
1866 out:
1867         /* if this is a configured peer or the primary for that peer has
1868          * been locked, then we don't want to flag this scenario as
1869          * a failure
1870          */
1871         if (lp->lp_state & LNET_PEER_CONFIGURED ||
1872             lp->lp_state & LNET_PEER_LOCK_PRIMARY)
1873                 return 0;
1874
1875         CDEBUG(D_NET, "peer %s NID %s: %d\n",
1876                libcfs_nidstr(&old), libcfs_nidstr(nid), rc);
1877
1878         return rc;
1879 }
1880
1881 /*
1882  * lpni creation initiated due to traffic either sending or receiving.
1883  * Callers must hold ln_api_mutex
1884  * Ref taken on lnet_peer_ni returned by this function
1885  */
1886 static struct lnet_peer_ni *
1887 lnet_peer_ni_traffic_add(struct lnet_nid *nid, struct lnet_nid *pref)
1888 __must_hold(&the_lnet.ln_api_mutex)
1889 {
1890         struct lnet_peer *lp = NULL;
1891         struct lnet_peer_net *lpn = NULL;
1892         struct lnet_peer_ni *lpni;
1893         unsigned flags = 0;
1894         int rc = 0;
1895
1896         if (LNET_NID_IS_ANY(nid)) {
1897                 rc = -EINVAL;
1898                 goto out_err;
1899         }
1900
1901         /* lnet_net_lock is not needed here because ln_api_lock is held */
1902         lpni = lnet_peer_ni_find_locked(nid);
1903         if (lpni) {
1904                 /*
1905                  * We must have raced with another thread. Since we
1906                  * know next to nothing about a peer_ni created by
1907                  * traffic, we just assume everything is ok and
1908                  * return.
1909                  */
1910                 goto out;
1911         }
1912
1913         /* Create peer, peer_net, and peer_ni. */
1914         rc = -ENOMEM;
1915         lp = lnet_peer_alloc(nid);
1916         if (!lp)
1917                 goto out_err;
1918         lpn = lnet_peer_net_alloc(LNET_NID_NET(nid));
1919         if (!lpn)
1920                 goto out_err;
1921         lpni = lnet_peer_ni_alloc(nid);
1922         if (!lpni)
1923                 goto out_err;
1924         lnet_peer_ni_set_non_mr_pref_nid(lpni, pref);
1925
1926         /* lnet_peer_attach_peer_ni() always returns 0 */
1927         rc = lnet_peer_attach_peer_ni(lp, lpn, lpni, flags);
1928
1929         lnet_peer_ni_addref_locked(lpni);
1930
1931 out_err:
1932         if (rc) {
1933                 if (lpn)
1934                         LIBCFS_FREE(lpn, sizeof(*lpn));
1935                 if (lp)
1936                         LIBCFS_FREE(lp, sizeof(*lp));
1937                 lpni = ERR_PTR(rc);
1938         }
1939 out:
1940         CDEBUG(D_NET, "peer %s: %d\n", libcfs_nidstr(nid), rc);
1941         return lpni;
1942 }
1943
1944 /*
1945  * Implementation of IOC_LIBCFS_ADD_PEER_NI.
1946  *
1947  * This API handles the following combinations:
1948  *   Create a peer with its primary NI if only the prim_nid is provided
1949  *   Add a NID to a peer identified by the prim_nid. The peer identified
1950  *   by the prim_nid must already exist.
1951  *   The peer being created may be non-MR.
1952  *
1953  * The caller must hold ln_api_mutex. This prevents the peer from
1954  * being created/modified/deleted by a different thread.
1955  */
1956 static int
1957 lnet_add_peer_ni(struct lnet_nid *prim_nid, struct lnet_nid *nid, bool mr,
1958                  unsigned int flags)
1959 __must_hold(&the_lnet.ln_api_mutex)
1960 {
1961         struct lnet_peer *lp = NULL;
1962         struct lnet_peer_ni *lpni;
1963
1964         /* The prim_nid must always be specified */
1965         if (LNET_NID_IS_ANY(prim_nid))
1966                 return -EINVAL;
1967
1968         if (mr)
1969                 flags |= LNET_PEER_MULTI_RAIL;
1970
1971         /*
1972          * If nid isn't specified, we must create a new peer with
1973          * prim_nid as its primary nid.
1974          */
1975         if (LNET_NID_IS_ANY(nid))
1976                 return lnet_peer_add(prim_nid, flags);
1977
1978         /* Look up the prim_nid, which must exist. */
1979         lpni = lnet_peer_ni_find_locked(prim_nid);
1980         if (!lpni)
1981                 return -ENOENT;
1982         lnet_peer_ni_decref_locked(lpni);
1983         lp = lpni->lpni_peer_net->lpn_peer;
1984
1985         /* Peer must have been configured. */
1986         if ((flags & LNET_PEER_CONFIGURED) &&
1987             !(lp->lp_state & LNET_PEER_CONFIGURED)) {
1988                 CDEBUG(D_NET, "peer %s was not configured\n",
1989                        libcfs_nidstr(prim_nid));
1990                 return -ENOENT;
1991         }
1992
1993         /* Primary NID must match */
1994         if (!nid_same(&lp->lp_primary_nid, prim_nid)) {
1995                 CDEBUG(D_NET, "prim_nid %s is not primary for peer %s\n",
1996                        libcfs_nidstr(prim_nid),
1997                        libcfs_nidstr(&lp->lp_primary_nid));
1998                 return -ENODEV;
1999         }
2000
2001         /* Multi-Rail flag must match. */
2002         if ((lp->lp_state ^ flags) & LNET_PEER_MULTI_RAIL) {
2003                 CDEBUG(D_NET, "multi-rail state mismatch for peer %s\n",
2004                        libcfs_nidstr(prim_nid));
2005                 return -EPERM;
2006         }
2007
2008         if (lnet_peer_is_uptodate(lp) && !(flags & LNET_PEER_CONFIGURED)) {
2009                 CDEBUG(D_NET,
2010                        "Don't add temporary peer NI for uptodate peer %s\n",
2011                        libcfs_nidstr(&lp->lp_primary_nid));
2012                 return -EINVAL;
2013         }
2014
2015         return lnet_peer_add_nid(lp, nid, flags);
2016 }
2017
2018 int lnet_user_add_peer_ni(struct lnet_nid *prim_nid, struct lnet_nid *nid,
2019                           bool mr, bool lock_prim)
2020 {
2021         int fl = LNET_PEER_CONFIGURED | (LNET_PEER_LOCK_PRIMARY * lock_prim);
2022
2023         return lnet_add_peer_ni(prim_nid, nid, mr, fl);
2024 }
2025
2026 static int
2027 lnet_reset_peer(struct lnet_peer *lp)
2028 {
2029         struct lnet_peer_net *lpn, *lpntmp;
2030         struct lnet_peer_ni *lpni, *lpnitmp;
2031         unsigned int flags;
2032         int rc;
2033
2034         lnet_peer_cancel_discovery(lp);
2035
2036         flags = LNET_PEER_CONFIGURED;
2037         if (lp->lp_state & LNET_PEER_MULTI_RAIL)
2038                 flags |= LNET_PEER_MULTI_RAIL;
2039
2040         list_for_each_entry_safe(lpn, lpntmp, &lp->lp_peer_nets, lpn_peer_nets) {
2041                 list_for_each_entry_safe(lpni, lpnitmp, &lpn->lpn_peer_nis,
2042                                          lpni_peer_nis) {
2043                         if (nid_same(&lpni->lpni_nid, &lp->lp_primary_nid))
2044                                 continue;
2045
2046                         rc = lnet_peer_del_nid(lp, &lpni->lpni_nid, flags);
2047                         if (rc) {
2048                                 CERROR("Failed to delete %s from peer %s\n",
2049                                        libcfs_nidstr(&lpni->lpni_nid),
2050                                        libcfs_nidstr(&lp->lp_primary_nid));
2051                         }
2052                 }
2053         }
2054
2055         /* mark it for discovery the next time we use it */
2056         lp->lp_state &= ~LNET_PEER_NIDS_UPTODATE;
2057         return 0;
2058 }
2059
2060 /*
2061  * Implementation of IOC_LIBCFS_DEL_PEER_NI.
2062  *
2063  * This API handles the following combinations:
2064  *   Delete a NI from a peer if both prim_nid and nid are provided.
2065  *   Delete a peer if only prim_nid is provided.
2066  *   Delete a peer if its primary nid is provided.
2067  *
2068  * The caller must hold ln_api_mutex. This prevents the peer from
2069  * being modified/deleted by a different thread.
2070  */
2071 int
2072 lnet_del_peer_ni(struct lnet_nid *prim_nid, struct lnet_nid *nid,
2073                  int force)
2074 {
2075         struct lnet_peer *lp;
2076         struct lnet_peer_ni *lpni;
2077         unsigned int flags;
2078
2079         if (!prim_nid || LNET_NID_IS_ANY(prim_nid))
2080                 return -EINVAL;
2081
2082         lpni = lnet_peer_ni_find_locked(prim_nid);
2083         if (!lpni)
2084                 return -ENOENT;
2085         lnet_peer_ni_decref_locked(lpni);
2086         lp = lpni->lpni_peer_net->lpn_peer;
2087
2088         if (!nid_same(prim_nid, &lp->lp_primary_nid)) {
2089                 CDEBUG(D_NET, "prim_nid %s is not primary for peer %s\n",
2090                        libcfs_nidstr(prim_nid),
2091                        libcfs_nidstr(&lp->lp_primary_nid));
2092                 return -ENODEV;
2093         }
2094
2095         lnet_net_lock(LNET_LOCK_EX);
2096         if (lp->lp_rtr_refcount > 0) {
2097                 lnet_net_unlock(LNET_LOCK_EX);
2098                 CERROR("%s is a router. Can not be deleted\n",
2099                        libcfs_nidstr(prim_nid));
2100                 return -EBUSY;
2101         }
2102         lnet_net_unlock(LNET_LOCK_EX);
2103
2104         if (LNET_NID_IS_ANY(nid) || nid_same(nid, &lp->lp_primary_nid)) {
2105                 if (!force && lp->lp_state & LNET_PEER_LOCK_PRIMARY) {
2106                         CERROR("peer %s created by Lustre. Must preserve primary NID, but will remove other NIDs\n",
2107                                libcfs_nidstr(&lp->lp_primary_nid));
2108                         return lnet_reset_peer(lp);
2109                 } else {
2110                         return lnet_peer_del(lp);
2111                 }
2112         }
2113
2114         flags = LNET_PEER_CONFIGURED;
2115         if (lp->lp_state & LNET_PEER_MULTI_RAIL)
2116                 flags |= LNET_PEER_MULTI_RAIL;
2117
2118         return lnet_peer_del_nid(lp, nid, flags);
2119 }
2120
2121 void
2122 lnet_destroy_peer_ni_locked(struct kref *ref)
2123 {
2124         struct lnet_peer_ni *lpni = container_of(ref, struct lnet_peer_ni,
2125                                                  lpni_kref);
2126         struct lnet_peer_table *ptable;
2127         struct lnet_peer_net *lpn;
2128
2129         CDEBUG(D_NET, "%p nid %s\n", lpni, libcfs_nidstr(&lpni->lpni_nid));
2130
2131         LASSERT(kref_read(&lpni->lpni_kref) == 0);
2132         LASSERT(list_empty(&lpni->lpni_txq));
2133         LASSERT(lpni->lpni_txqnob == 0);
2134         LASSERT(list_empty(&lpni->lpni_peer_nis));
2135         LASSERT(list_empty(&lpni->lpni_on_remote_peer_ni_list));
2136
2137         lpn = lpni->lpni_peer_net;
2138         lpni->lpni_peer_net = NULL;
2139         lpni->lpni_net = NULL;
2140
2141         if (!list_empty(&lpni->lpni_hashlist)) {
2142                 /* remove the peer ni from the zombie list */
2143                 ptable = the_lnet.ln_peer_tables[lpni->lpni_cpt];
2144                 spin_lock(&ptable->pt_zombie_lock);
2145                 list_del_init(&lpni->lpni_hashlist);
2146                 ptable->pt_zombies--;
2147                 spin_unlock(&ptable->pt_zombie_lock);
2148         }
2149
2150         if (lpni->lpni_pref_nnids > 1) {
2151                 struct lnet_nid_list *ne, *tmp;
2152
2153                 list_for_each_entry_safe(ne, tmp, &lpni->lpni_pref.nids,
2154                                          nl_list) {
2155                         list_del_init(&ne->nl_list);
2156                         LIBCFS_FREE(ne, sizeof(*ne));
2157                 }
2158         }
2159         LIBCFS_FREE(lpni, sizeof(*lpni));
2160
2161         if (lpn)
2162                 lnet_peer_net_decref_locked(lpn);
2163 }
2164
2165 struct lnet_peer_ni *
2166 lnet_nid2peerni_ex(struct lnet_nid *nid)
2167 __must_hold(&the_lnet.ln_api_mutex)
2168 {
2169         struct lnet_peer_ni *lpni = NULL;
2170
2171         if (the_lnet.ln_state != LNET_STATE_RUNNING)
2172                 return ERR_PTR(-ESHUTDOWN);
2173
2174         /*
2175          * find if a peer_ni already exists.
2176          * If so then just return that.
2177          */
2178         lpni = lnet_peer_ni_find_locked(nid);
2179         if (lpni)
2180                 return lpni;
2181
2182         lnet_net_unlock(LNET_LOCK_EX);
2183
2184         lpni = lnet_peer_ni_traffic_add(nid, NULL);
2185
2186         lnet_net_lock(LNET_LOCK_EX);
2187
2188         return lpni;
2189 }
2190
2191 /*
2192  * Get a peer_ni for the given nid, create it if necessary. Takes a
2193  * hold on the peer_ni.
2194  */
2195 struct lnet_peer_ni *
2196 lnet_peerni_by_nid_locked(struct lnet_nid *nid,
2197                         struct lnet_nid *pref, int cpt)
2198 {
2199         struct lnet_peer_ni *lpni = NULL;
2200
2201         if (the_lnet.ln_state != LNET_STATE_RUNNING)
2202                 return ERR_PTR(-ESHUTDOWN);
2203
2204         /*
2205          * find if a peer_ni already exists.
2206          * If so then just return that.
2207          */
2208         lpni = lnet_peer_ni_find_locked(nid);
2209         if (lpni)
2210                 return lpni;
2211
2212         /*
2213          * Slow path:
2214          * use the lnet_api_mutex to serialize the creation of the peer_ni
2215          * and the creation/deletion of the local ni/net. When a local ni is
2216          * created, if there exists a set of peer_nis on that network,
2217          * they need to be traversed and updated. When a local NI is
2218          * deleted, which could result in a network being deleted, then
2219          * all peer nis on that network need to be removed as well.
2220          *
2221          * Creation through traffic should also be serialized with
2222          * creation through DLC.
2223          */
2224         lnet_net_unlock(cpt);
2225         mutex_lock(&the_lnet.ln_api_mutex);
2226         /*
2227          * the_lnet.ln_state is only modified under the ln_api_lock, so a single
2228          * check here is sufficent.
2229          */
2230         if (the_lnet.ln_state == LNET_STATE_RUNNING)
2231                 lpni = lnet_peer_ni_traffic_add(nid, pref);
2232
2233         mutex_unlock(&the_lnet.ln_api_mutex);
2234         lnet_net_lock(cpt);
2235
2236         /* Lock has been dropped, check again for shutdown. */
2237         if (the_lnet.ln_state != LNET_STATE_RUNNING) {
2238                 if (!IS_ERR_OR_NULL(lpni))
2239                         lnet_peer_ni_decref_locked(lpni);
2240                 lpni = ERR_PTR(-ESHUTDOWN);
2241         }
2242
2243         return lpni;
2244 }
2245
2246 bool
2247 lnet_peer_gw_discovery(struct lnet_peer *lp)
2248 {
2249         bool rc = false;
2250
2251         spin_lock(&lp->lp_lock);
2252         if (lp->lp_state & LNET_PEER_RTR_DISCOVERY)
2253                 rc = true;
2254         spin_unlock(&lp->lp_lock);
2255
2256         return rc;
2257 }
2258
2259 bool
2260 lnet_peer_is_uptodate(struct lnet_peer *lp)
2261 {
2262         bool rc;
2263
2264         spin_lock(&lp->lp_lock);
2265         rc = lnet_peer_is_uptodate_locked(lp);
2266         spin_unlock(&lp->lp_lock);
2267         return rc;
2268 }
2269
2270 /*
2271  * Is a peer uptodate from the point of view of discovery?
2272  *
2273  * If it is currently being processed, obviously not.
2274  * A forced Ping or Push is also handled by the discovery thread.
2275  *
2276  * Otherwise look at whether the peer needs rediscovering.
2277  */
2278 bool
2279 lnet_peer_is_uptodate_locked(struct lnet_peer *lp)
2280 __must_hold(&lp->lp_lock)
2281 {
2282         bool rc;
2283
2284         if (lp->lp_state & (LNET_PEER_DISCOVERING |
2285                             LNET_PEER_FORCE_PING |
2286                             LNET_PEER_FORCE_PUSH)) {
2287                 rc = false;
2288         } else if (lp->lp_state & LNET_PEER_REDISCOVER) {
2289                 rc = false;
2290         } else if (lnet_peer_needs_push(lp)) {
2291                 rc = false;
2292         } else if (lp->lp_state & LNET_PEER_DISCOVERED) {
2293                 if (lp->lp_state & LNET_PEER_NIDS_UPTODATE)
2294                         rc = true;
2295                 else
2296                         rc = false;
2297         } else {
2298                 rc = false;
2299         }
2300
2301         return rc;
2302 }
2303
2304 /* Add the message to the peer's lp_dc_pendq and queue the peer for discovery */
2305 void
2306 lnet_peer_queue_message(struct lnet_peer *lp, struct lnet_msg *msg)
2307 {
2308         /* The discovery thread holds net_lock/EX and lp_lock when it splices
2309          * the lp_dc_pendq onto a local list for resending. Thus, we do the same
2310          * when adding to the list and queuing the peer to ensure that we do not
2311          * strand any messages on the lp_dc_pendq. This scheme ensures the
2312          * message will be resent even if the peer is already being discovered.
2313          * Therefore we needn't check the return value of
2314          * lnet_peer_queue_for_discovery(lp).
2315          */
2316         lnet_net_lock(LNET_LOCK_EX);
2317         spin_lock(&lp->lp_lock);
2318         list_add_tail(&msg->msg_list, &lp->lp_dc_pendq);
2319         spin_unlock(&lp->lp_lock);
2320         lnet_peer_queue_for_discovery(lp);
2321         lnet_net_unlock(LNET_LOCK_EX);
2322 }
2323
2324 /*
2325  * Queue a peer for the attention of the discovery thread.  Call with
2326  * lnet_net_lock/EX held. Returns 0 if the peer was queued, and
2327  * -EALREADY if the peer was already queued.
2328  */
2329 static int lnet_peer_queue_for_discovery(struct lnet_peer *lp)
2330 {
2331         int rc;
2332
2333         spin_lock(&lp->lp_lock);
2334         if (!(lp->lp_state & LNET_PEER_DISCOVERING))
2335                 lp->lp_state |= LNET_PEER_DISCOVERING;
2336         spin_unlock(&lp->lp_lock);
2337         if (list_empty(&lp->lp_dc_list)) {
2338                 lnet_peer_addref_locked(lp);
2339                 list_add_tail(&lp->lp_dc_list, &the_lnet.ln_dc_request);
2340                 wake_up(&the_lnet.ln_dc_waitq);
2341                 rc = 0;
2342         } else {
2343                 rc = -EALREADY;
2344         }
2345
2346         CDEBUG(D_NET, "Queue peer %s: %d\n",
2347                libcfs_nidstr(&lp->lp_primary_nid), rc);
2348
2349         return rc;
2350 }
2351
2352 /*
2353  * Discovery of a peer is complete. Wake all waiters on the peer.
2354  * Call with lnet_net_lock/EX held.
2355  */
2356 static void lnet_peer_discovery_complete(struct lnet_peer *lp, int dc_error)
2357 {
2358         struct lnet_msg *msg, *tmp;
2359         int rc = 0;
2360         LIST_HEAD(pending_msgs);
2361
2362         CDEBUG(D_NET, "Discovery complete. Dequeue peer %s\n",
2363                libcfs_nidstr(&lp->lp_primary_nid));
2364
2365         spin_lock(&lp->lp_lock);
2366         /* Our caller dropped lp_lock which may have allowed another thread to
2367          * set LNET_PEER_DISCOVERING, or it may be set if dc_error is non-zero.
2368          * Ensure it is cleared.
2369          */
2370         lp->lp_state &= ~LNET_PEER_DISCOVERING;
2371         if (dc_error) {
2372                 lp->lp_dc_error = dc_error;
2373                 lp->lp_state |= LNET_PEER_REDISCOVER;
2374         }
2375         list_splice_init(&lp->lp_dc_pendq, &pending_msgs);
2376         spin_unlock(&lp->lp_lock);
2377         list_del_init(&lp->lp_dc_list);
2378         wake_up(&lp->lp_dc_waitq);
2379
2380         if (lp->lp_rtr_refcount > 0)
2381                 lnet_router_discovery_complete(lp);
2382
2383         lnet_net_unlock(LNET_LOCK_EX);
2384
2385         /* iterate through all pending messages and send them again */
2386         list_for_each_entry_safe(msg, tmp, &pending_msgs, msg_list) {
2387                 list_del_init(&msg->msg_list);
2388                 if (dc_error) {
2389                         lnet_finalize(msg, dc_error);
2390                         continue;
2391                 }
2392
2393                 CDEBUG(D_NET, "sending pending message %s to target %s\n",
2394                        lnet_msgtyp2str(msg->msg_type),
2395                        libcfs_idstr(&msg->msg_target));
2396                 rc = lnet_send(&msg->msg_src_nid_param, msg,
2397                                &msg->msg_rtr_nid_param);
2398                 if (rc < 0) {
2399                         CNETERR("Error sending %s to %s: %d\n",
2400                                lnet_msgtyp2str(msg->msg_type),
2401                                libcfs_idstr(&msg->msg_target), rc);
2402                         lnet_finalize(msg, rc);
2403                 }
2404         }
2405         lnet_net_lock(LNET_LOCK_EX);
2406         lnet_peer_decref_locked(lp);
2407 }
2408
2409 /*
2410  * Handle inbound push.
2411  * Like any event handler, called with lnet_res_lock/CPT held.
2412  */
2413 void lnet_peer_push_event(struct lnet_event *ev)
2414 {
2415         struct lnet_ping_buffer *pbuf;
2416         struct lnet_peer *lp;
2417         int infobytes;
2418
2419         pbuf = LNET_PING_INFO_TO_BUFFER(ev->md_start + ev->offset);
2420
2421         /* lnet_find_peer() adds a refcount */
2422         lp = lnet_find_peer(&ev->source.nid);
2423         if (!lp) {
2424                 CDEBUG(D_NET, "Push Put from unknown %s (source %s). Ignoring...\n",
2425                        libcfs_nidstr(&ev->initiator.nid),
2426                        libcfs_nidstr(&ev->source.nid));
2427                 pbuf->pb_needs_post = true;
2428                 return;
2429         }
2430
2431         /* Ensure peer state remains consistent while we modify it. */
2432         spin_lock(&lp->lp_lock);
2433
2434         /*
2435          * If some kind of error happened the contents of the message
2436          * cannot be used. Clear the NIDS_UPTODATE and set the
2437          * FORCE_PING flag to trigger a ping.
2438          */
2439         if (ev->status) {
2440                 lp->lp_state &= ~LNET_PEER_NIDS_UPTODATE;
2441                 lp->lp_state |= LNET_PEER_FORCE_PING;
2442                 CDEBUG(D_NET, "Push Put error %d from %s (source %s)\n",
2443                        ev->status,
2444                        libcfs_nidstr(&lp->lp_primary_nid),
2445                        libcfs_nidstr(&ev->source.nid));
2446                 goto out;
2447         }
2448
2449         /*
2450          * A push with invalid or corrupted info. Clear the UPTODATE
2451          * flag to trigger a ping.
2452          */
2453         if (lnet_ping_info_validate(&pbuf->pb_info)) {
2454                 lp->lp_state &= ~LNET_PEER_NIDS_UPTODATE;
2455                 lp->lp_state |= LNET_PEER_FORCE_PING;
2456                 CDEBUG(D_NET, "Corrupted Push from %s\n",
2457                        libcfs_nidstr(&lp->lp_primary_nid));
2458                 goto out;
2459         }
2460
2461         /* Make sure we'll allocate the correct size ping buffer when
2462          * pinging the peer.
2463          */
2464         infobytes = lnet_ping_info_size(&pbuf->pb_info);
2465         if (lp->lp_data_bytes < infobytes)
2466                 lp->lp_data_bytes = infobytes;
2467
2468         /*
2469          * A non-Multi-Rail peer is not supposed to be capable of
2470          * sending a push.
2471          */
2472         if (!(pbuf->pb_info.pi_features & LNET_PING_FEAT_MULTI_RAIL)) {
2473                 CERROR("Push from non-Multi-Rail peer %s dropped\n",
2474                        libcfs_nidstr(&lp->lp_primary_nid));
2475                 goto out;
2476         }
2477
2478         /*
2479          * The peer may have discovery disabled at its end. Set
2480          * NO_DISCOVERY as appropriate.
2481          */
2482         if (!(pbuf->pb_info.pi_features & LNET_PING_FEAT_DISCOVERY)) {
2483                 CDEBUG(D_NET, "Peer %s has discovery disabled\n",
2484                        libcfs_nidstr(&lp->lp_primary_nid));
2485                 /*
2486                  * Mark the peer for deletion if we already know about it
2487                  * and it's going from discovery set to no discovery set
2488                  */
2489                 if (!(lp->lp_state & (LNET_PEER_NO_DISCOVERY |
2490                                       LNET_PEER_DISCOVERING)) &&
2491                      lp->lp_state & LNET_PEER_DISCOVERED) {
2492                         CDEBUG(D_NET, "Marking %s:0x%x for deletion\n",
2493                                libcfs_nidstr(&lp->lp_primary_nid),
2494                                lp->lp_state);
2495                         lp->lp_state |= LNET_PEER_MARK_DELETION;
2496                 }
2497                 lp->lp_state |= LNET_PEER_NO_DISCOVERY;
2498         } else if (lp->lp_state & LNET_PEER_NO_DISCOVERY) {
2499                 CDEBUG(D_NET, "Peer %s has discovery enabled\n",
2500                        libcfs_nidstr(&lp->lp_primary_nid));
2501                 lp->lp_state &= ~LNET_PEER_NO_DISCOVERY;
2502         }
2503
2504         /*
2505          * Update the MULTI_RAIL flag based on the push. If the peer
2506          * was configured with DLC then the setting should match what
2507          * DLC put in.
2508          * NB: We verified above that the MR feature bit is set in pi_features
2509          */
2510         if (lp->lp_state & LNET_PEER_MULTI_RAIL) {
2511                 CDEBUG(D_NET, "peer %s(%p) is MR\n",
2512                        libcfs_nidstr(&lp->lp_primary_nid), lp);
2513         } else if (lp->lp_state & LNET_PEER_CONFIGURED) {
2514                 CWARN("Push says %s is Multi-Rail, DLC says not\n",
2515                       libcfs_nidstr(&lp->lp_primary_nid));
2516         } else if (lnet_peer_discovery_disabled) {
2517                 CDEBUG(D_NET, "peer %s(%p) not MR: DD disabled locally\n",
2518                        libcfs_nidstr(&lp->lp_primary_nid), lp);
2519         } else if (lp->lp_state & LNET_PEER_NO_DISCOVERY) {
2520                 CDEBUG(D_NET, "peer %s(%p) not MR: DD disabled remotely\n",
2521                        libcfs_nidstr(&lp->lp_primary_nid), lp);
2522         } else {
2523                 CDEBUG(D_NET, "peer %s(%p) is MR capable\n",
2524                        libcfs_nidstr(&lp->lp_primary_nid), lp);
2525                 lp->lp_state |= LNET_PEER_MULTI_RAIL;
2526                 lnet_peer_clr_non_mr_pref_nids(lp);
2527         }
2528
2529         /* Check for truncation of the Put message. Clear the
2530          * NIDS_UPTODATE flag and set FORCE_PING to trigger a ping,
2531          * and tell discovery to allocate a bigger buffer.
2532          */
2533         if (ev->mlength < ev->rlength) {
2534                 if (the_lnet.ln_push_target_nbytes < infobytes)
2535                         the_lnet.ln_push_target_nbytes = infobytes;
2536                 lp->lp_state &= ~LNET_PEER_NIDS_UPTODATE;
2537                 lp->lp_state |= LNET_PEER_FORCE_PING;
2538                 CDEBUG(D_NET, "Truncated Push from %s (%d bytes)\n",
2539                        libcfs_nidstr(&lp->lp_primary_nid), infobytes);
2540                 goto out;
2541         }
2542
2543         /* always assume new data */
2544         lp->lp_peer_seqno = LNET_PING_BUFFER_SEQNO(pbuf);
2545         lp->lp_state &= ~LNET_PEER_NIDS_UPTODATE;
2546
2547         /* If there is data present that hasn't been processed yet,
2548          * we'll replace it if the Put contained newer data and it
2549          * fits. We're racing with a Ping or earlier Push in this
2550          * case.
2551          */
2552         if (lp->lp_state & LNET_PEER_DATA_PRESENT) {
2553                 if (LNET_PING_BUFFER_SEQNO(pbuf) >
2554                         LNET_PING_BUFFER_SEQNO(lp->lp_data) &&
2555                     infobytes <= lp->lp_data->pb_nbytes) {
2556                         memcpy(&lp->lp_data->pb_info, &pbuf->pb_info,
2557                                infobytes);
2558                         CDEBUG(D_NET, "Ping/Push race from %s: %u vs %u\n",
2559                               libcfs_nidstr(&lp->lp_primary_nid),
2560                               LNET_PING_BUFFER_SEQNO(pbuf),
2561                               LNET_PING_BUFFER_SEQNO(lp->lp_data));
2562                 }
2563                 goto out;
2564         }
2565
2566         /*
2567          * Allocate a buffer to copy the data. On a failure we drop
2568          * the Push and set FORCE_PING to force the discovery
2569          * thread to fix the problem by pinging the peer.
2570          */
2571         lp->lp_data = lnet_ping_buffer_alloc(lp->lp_data_bytes, GFP_ATOMIC);
2572         if (!lp->lp_data) {
2573                 lp->lp_state |= LNET_PEER_FORCE_PING;
2574                 CDEBUG(D_NET, "Cannot allocate Push buffer for %s %u\n",
2575                        libcfs_nidstr(&lp->lp_primary_nid),
2576                        LNET_PING_BUFFER_SEQNO(pbuf));
2577                 goto out;
2578         }
2579
2580         /* Success */
2581         unsafe_memcpy(&lp->lp_data->pb_info, &pbuf->pb_info, infobytes,
2582                       FLEXIBLE_OBJECT);
2583         lp->lp_state |= LNET_PEER_DATA_PRESENT;
2584         CDEBUG(D_NET, "Received Push %s %u\n",
2585                libcfs_nidstr(&lp->lp_primary_nid),
2586                LNET_PING_BUFFER_SEQNO(pbuf));
2587
2588 out:
2589         /* We've processed this buffer. It can be reposted */
2590         pbuf->pb_needs_post = true;
2591
2592         /*
2593          * Queue the peer for discovery if not done, force it on the request
2594          * queue and wake the discovery thread if the peer was already queued,
2595          * because its status changed.
2596          */
2597         spin_unlock(&lp->lp_lock);
2598         lnet_net_lock(LNET_LOCK_EX);
2599         if (!lnet_peer_is_uptodate(lp) && lnet_peer_queue_for_discovery(lp)) {
2600                 list_move(&lp->lp_dc_list, &the_lnet.ln_dc_request);
2601                 wake_up(&the_lnet.ln_dc_waitq);
2602         }
2603         /* Drop refcount from lookup */
2604         lnet_peer_decref_locked(lp);
2605         lnet_net_unlock(LNET_LOCK_EX);
2606 }
2607
2608 /*
2609  * Clear the discovery error state, unless we're already discovering
2610  * this peer, in which case the error is current.
2611  */
2612 static void lnet_peer_clear_discovery_error(struct lnet_peer *lp)
2613 {
2614         spin_lock(&lp->lp_lock);
2615         if (!(lp->lp_state & LNET_PEER_DISCOVERING))
2616                 lp->lp_dc_error = 0;
2617         spin_unlock(&lp->lp_lock);
2618 }
2619
2620 /*
2621  * Peer discovery slow path. The ln_api_mutex is held on entry, and
2622  * dropped/retaken within this function. An lnet_peer_ni is passed in
2623  * because discovery could tear down an lnet_peer.
2624  */
2625 int
2626 lnet_discover_peer_locked(struct lnet_peer_ni *lpni, int cpt, bool block)
2627 {
2628         DEFINE_WAIT(wait);
2629         struct lnet_peer *lp;
2630         int rc = 0;
2631         int count = 0;
2632
2633 again:
2634         lnet_net_unlock(cpt);
2635         lnet_net_lock(LNET_LOCK_EX);
2636         lp = lpni->lpni_peer_net->lpn_peer;
2637         lnet_peer_clear_discovery_error(lp);
2638
2639         /*
2640          * We're willing to be interrupted. The lpni can become a
2641          * zombie if we race with DLC, so we must check for that.
2642          */
2643         for (;;) {
2644                 /* Keep lp alive when the lnet_net_lock is unlocked */
2645                 lnet_peer_addref_locked(lp);
2646                 prepare_to_wait(&lp->lp_dc_waitq, &wait, TASK_INTERRUPTIBLE);
2647                 if (signal_pending(current))
2648                         break;
2649                 if (the_lnet.ln_dc_state != LNET_DC_STATE_RUNNING)
2650                         break;
2651                 /*
2652                  * Don't repeat discovery if discovery is disabled. This is
2653                  * done to ensure we can use discovery as a standard ping as
2654                  * well for backwards compatibility with routers which do not
2655                  * have discovery or have discovery disabled
2656                  */
2657                 if (lnet_is_discovery_disabled(lp) && count > 0)
2658                         break;
2659                 if (lp->lp_dc_error)
2660                         break;
2661                 if (lnet_peer_is_uptodate(lp))
2662                         break;
2663                 if (lp->lp_state & LNET_PEER_MARK_DELETED)
2664                         break;
2665                 lnet_peer_queue_for_discovery(lp);
2666                 count++;
2667                 CDEBUG(D_NET, "Discovery attempt # %d\n", count);
2668
2669                 /*
2670                  * If caller requested a non-blocking operation then
2671                  * return immediately. Once discovery is complete any
2672                  * pending messages that were stopped due to discovery
2673                  * will be transmitted.
2674                  */
2675                 if (!block)
2676                         break;
2677
2678                 lnet_net_unlock(LNET_LOCK_EX);
2679                 schedule();
2680                 finish_wait(&lp->lp_dc_waitq, &wait);
2681                 lnet_net_lock(LNET_LOCK_EX);
2682                 lnet_peer_decref_locked(lp);
2683                 /* Peer may have changed */
2684                 lp = lpni->lpni_peer_net->lpn_peer;
2685         }
2686         finish_wait(&lp->lp_dc_waitq, &wait);
2687
2688         lnet_net_unlock(LNET_LOCK_EX);
2689         lnet_net_lock(cpt);
2690         lnet_peer_decref_locked(lp);
2691         /*
2692          * The peer may have changed, so re-check and rediscover if that turns
2693          * out to have been the case. The reference count on lp ensured that
2694          * even if it was unlinked from lpni the memory could not be recycled.
2695          * Thus the check below is sufficient to determine whether the peer
2696          * changed. If the peer changed, then lp must not be dereferenced.
2697          */
2698         if (lp != lpni->lpni_peer_net->lpn_peer)
2699                 goto again;
2700
2701         if (signal_pending(current))
2702                 rc = -EINTR;
2703         else if (the_lnet.ln_dc_state != LNET_DC_STATE_RUNNING)
2704                 rc = -ESHUTDOWN;
2705         else if (lp->lp_dc_error)
2706                 rc = lp->lp_dc_error;
2707         else if (!block)
2708                 CDEBUG(D_NET, "non-blocking discovery\n");
2709         else if (!lnet_peer_is_uptodate(lp) &&
2710                  !(lnet_is_discovery_disabled(lp) ||
2711                    (lp->lp_state & LNET_PEER_MARK_DELETED)))
2712                 goto again;
2713
2714         CDEBUG(D_NET, "peer %s NID %s: %d. %s\n",
2715                (lp ? libcfs_nidstr(&lp->lp_primary_nid) : "(none)"),
2716                libcfs_nidstr(&lpni->lpni_nid), rc,
2717                (!block) ? "pending discovery" : "discovery complete");
2718
2719         return rc;
2720 }
2721
2722 /* Handle an incoming ack for a push. */
2723 static void
2724 lnet_discovery_event_ack(struct lnet_peer *lp, struct lnet_event *ev)
2725 {
2726         struct lnet_ping_buffer *pbuf;
2727
2728         pbuf = LNET_PING_INFO_TO_BUFFER(ev->md_start);
2729         spin_lock(&lp->lp_lock);
2730         lp->lp_state &= ~LNET_PEER_PUSH_SENT;
2731         lp->lp_push_error = ev->status;
2732         if (ev->status)
2733                 lp->lp_state |= LNET_PEER_PUSH_FAILED;
2734         else
2735                 lp->lp_node_seqno = LNET_PING_BUFFER_SEQNO(pbuf);
2736         spin_unlock(&lp->lp_lock);
2737
2738         CDEBUG(D_NET, "peer %s ev->status %d\n",
2739                libcfs_nidstr(&lp->lp_primary_nid), ev->status);
2740 }
2741
2742 static bool find_primary(struct lnet_nid *nid,
2743                          struct lnet_ping_buffer *pbuf)
2744 {
2745         struct lnet_ping_info *pi = &pbuf->pb_info;
2746         struct lnet_ping_iter piter;
2747         __u32 *stp;
2748
2749         if (pi->pi_features & LNET_PING_FEAT_PRIMARY_LARGE) {
2750                 /* First large nid is primary */
2751                 for (stp = ping_iter_first(&piter, pbuf, nid);
2752                      stp;
2753                      stp = ping_iter_next(&piter, nid)) {
2754                         if (nid_is_nid4(nid))
2755                                 continue;
2756                         /* nid has already been copied in */
2757                         return true;
2758                 }
2759                 /* no large nids ... weird ... ignore the flag
2760                  * and use first nid.
2761                  */
2762         }
2763         /* pi_nids[1] is primary */
2764         if (pi->pi_nnis < 2)
2765                 return false;
2766         lnet_nid4_to_nid(pbuf->pb_info.pi_ni[1].ns_nid, nid);
2767         return true;
2768 }
2769
2770 /* Handle a Reply message. This is the reply to a Ping message. */
2771 static void
2772 lnet_discovery_event_reply(struct lnet_peer *lp, struct lnet_event *ev)
2773 {
2774         struct lnet_ping_buffer *pbuf;
2775         struct lnet_nid primary;
2776         int infobytes;
2777         int rc;
2778         bool ping_feat_disc;
2779
2780         spin_lock(&lp->lp_lock);
2781
2782         lp->lp_disc_src_nid = ev->target.nid;
2783         lp->lp_disc_dst_nid = ev->source.nid;
2784
2785         /*
2786          * If some kind of error happened the contents of message
2787          * cannot be used. Set PING_FAILED to trigger a retry.
2788          */
2789         if (ev->status) {
2790                 lp->lp_state |= LNET_PEER_PING_FAILED;
2791                 lp->lp_ping_error = ev->status;
2792                 CDEBUG(D_NET, "Ping Reply error %d from %s (source %s)\n",
2793                        ev->status,
2794                        libcfs_nidstr(&lp->lp_primary_nid),
2795                        libcfs_nidstr(&ev->source.nid));
2796                 goto out;
2797         }
2798
2799         pbuf = LNET_PING_INFO_TO_BUFFER(ev->md_start);
2800         if (pbuf->pb_info.pi_magic == __swab32(LNET_PROTO_PING_MAGIC))
2801                 lnet_swap_pinginfo(pbuf);
2802
2803         /*
2804          * A reply with invalid or corrupted info. Set PING_FAILED to
2805          * trigger a retry.
2806          */
2807         rc = lnet_ping_info_validate(&pbuf->pb_info);
2808         if (rc) {
2809                 lp->lp_state |= LNET_PEER_PING_FAILED;
2810                 lp->lp_ping_error = 0;
2811                 CDEBUG(D_NET, "Corrupted Ping Reply from %s: %d\n",
2812                        libcfs_nidstr(&lp->lp_primary_nid), rc);
2813                 goto out;
2814         }
2815
2816         /*
2817          * The peer may have discovery disabled at its end. Set
2818          * NO_DISCOVERY as appropriate.
2819          */
2820         ping_feat_disc = pbuf->pb_info.pi_features & LNET_PING_FEAT_DISCOVERY;
2821         if (!ping_feat_disc || lnet_peer_discovery_disabled) {
2822                 CDEBUG(D_NET, "Peer %s has discovery %s, local discovery %s\n",
2823                        libcfs_nidstr(&lp->lp_primary_nid),
2824                        ping_feat_disc ? "enabled" : "disabled",
2825                        lnet_peer_discovery_disabled ? "disabled" : "enabled");
2826
2827                 /* Detect whether this peer has toggled discovery from on to
2828                  * off and whether we can delete and re-create the peer. Peers
2829                  * that were manually configured cannot be deleted by discovery.
2830                  * We need to delete this peer and re-create it if the peer was
2831                  * not configured manually, is currently considered DD capable,
2832                  * and either:
2833                  * 1. We've already discovered the peer (the peer has toggled
2834                  *    the discovery feature from on to off), or
2835                  * 2. The peer is considered MR, but it was not user configured
2836                  *    (this was a "temporary" peer created via the kernel APIs
2837                  *     that we're discovering for the first time)
2838                  */
2839                 if (!(lp->lp_state & (LNET_PEER_CONFIGURED |
2840                                       LNET_PEER_NO_DISCOVERY)) &&
2841                     (lp->lp_state & (LNET_PEER_DISCOVERED |
2842                                      LNET_PEER_MULTI_RAIL))) {
2843                         CDEBUG(D_NET, "Marking %s:0x%x for deletion\n",
2844                                libcfs_nidstr(&lp->lp_primary_nid),
2845                                lp->lp_state);
2846                         lp->lp_state |= LNET_PEER_MARK_DELETION;
2847                 }
2848                 lp->lp_state |= LNET_PEER_NO_DISCOVERY;
2849         } else {
2850                 CDEBUG(D_NET, "Peer %s has discovery enabled\n",
2851                        libcfs_nidstr(&lp->lp_primary_nid));
2852                 lp->lp_state &= ~LNET_PEER_NO_DISCOVERY;
2853         }
2854
2855         /*
2856          * Update the MULTI_RAIL flag based on the reply. If the peer
2857          * was configured with DLC then the setting should match what
2858          * DLC put in.
2859          */
2860         if (pbuf->pb_info.pi_features & LNET_PING_FEAT_MULTI_RAIL) {
2861                 if (lp->lp_state & LNET_PEER_MULTI_RAIL) {
2862                         CDEBUG(D_NET, "peer %s(%p) is MR\n",
2863                                libcfs_nidstr(&lp->lp_primary_nid), lp);
2864                 } else if (lp->lp_state & LNET_PEER_CONFIGURED) {
2865                         CWARN("Reply says %s is Multi-Rail, DLC says not\n",
2866                               libcfs_nidstr(&lp->lp_primary_nid));
2867                 } else if (lnet_peer_discovery_disabled) {
2868                         CDEBUG(D_NET,
2869                                "peer %s(%p) not MR: DD disabled locally\n",
2870                                libcfs_nidstr(&lp->lp_primary_nid), lp);
2871                 } else if (lp->lp_state & LNET_PEER_NO_DISCOVERY) {
2872                         CDEBUG(D_NET,
2873                                "peer %s(%p) not MR: DD disabled remotely\n",
2874                                libcfs_nidstr(&lp->lp_primary_nid), lp);
2875                 } else {
2876                         CDEBUG(D_NET, "peer %s(%p) is MR capable\n",
2877                                libcfs_nidstr(&lp->lp_primary_nid), lp);
2878                         lp->lp_state |= LNET_PEER_MULTI_RAIL;
2879                         lnet_peer_clr_non_mr_pref_nids(lp);
2880                 }
2881         } else if (lp->lp_state & LNET_PEER_MULTI_RAIL) {
2882                 if (lp->lp_state & LNET_PEER_CONFIGURED) {
2883                         CWARN("DLC says %s is Multi-Rail, Reply says not\n",
2884                               libcfs_nidstr(&lp->lp_primary_nid));
2885                 } else {
2886                         CERROR("Multi-Rail state vanished from %s\n",
2887                                libcfs_nidstr(&lp->lp_primary_nid));
2888                         lp->lp_state &= ~LNET_PEER_MULTI_RAIL;
2889                 }
2890         }
2891
2892         infobytes = lnet_ping_info_size(&pbuf->pb_info);
2893         /*
2894          * Make sure we'll allocate the correct size ping buffer when
2895          * pinging the peer.
2896          */
2897         if (lp->lp_data_bytes < infobytes)
2898                 lp->lp_data_bytes = infobytes;
2899
2900         /* Check for truncation of the Reply. Clear PING_SENT and set
2901          * PING_FAILED to trigger a retry.
2902          */
2903         if (pbuf->pb_nbytes < infobytes) {
2904                 if (the_lnet.ln_push_target_nbytes < infobytes)
2905                         the_lnet.ln_push_target_nbytes = infobytes;
2906                 lp->lp_state |= LNET_PEER_PING_FAILED;
2907                 lp->lp_ping_error = 0;
2908                 CDEBUG(D_NET, "Truncated Reply from %s (%d bytes)\n",
2909                        libcfs_nidstr(&lp->lp_primary_nid), infobytes);
2910                 goto out;
2911         }
2912
2913         /*
2914          * Check the sequence numbers in the reply. These are only
2915          * available if the reply came from a Multi-Rail peer.
2916          */
2917         if (pbuf->pb_info.pi_features & LNET_PING_FEAT_MULTI_RAIL &&
2918             find_primary(&primary, pbuf) &&
2919             nid_same(&lp->lp_primary_nid, &primary)) {
2920                 if (LNET_PING_BUFFER_SEQNO(pbuf) < lp->lp_peer_seqno)
2921                         CDEBUG(D_NET, "peer %s: seq# got %u have %u. peer rebooted?\n",
2922                                 libcfs_nidstr(&lp->lp_primary_nid),
2923                                 LNET_PING_BUFFER_SEQNO(pbuf),
2924                                 lp->lp_peer_seqno);
2925
2926                 lp->lp_peer_seqno = LNET_PING_BUFFER_SEQNO(pbuf);
2927         }
2928
2929         /* We're happy with the state of the data in the buffer. */
2930         CDEBUG(D_NET, "peer %s data present %u. state = 0x%x\n",
2931                libcfs_nidstr(&lp->lp_primary_nid), lp->lp_peer_seqno,
2932                lp->lp_state);
2933         if (lp->lp_state & LNET_PEER_DATA_PRESENT)
2934                 lnet_ping_buffer_decref(lp->lp_data);
2935         else
2936                 lp->lp_state |= LNET_PEER_DATA_PRESENT;
2937         lnet_ping_buffer_addref(pbuf);
2938         lp->lp_data = pbuf;
2939 out:
2940         lp->lp_state &= ~LNET_PEER_PING_SENT;
2941         spin_unlock(&lp->lp_lock);
2942 }
2943
2944 /*
2945  * Send event handling. Only matters for error cases, where we clean
2946  * up state on the peer and peer_ni that would otherwise be updated in
2947  * the REPLY event handler for a successful Ping, and the ACK event
2948  * handler for a successful Push.
2949  */
2950 static int
2951 lnet_discovery_event_send(struct lnet_peer *lp, struct lnet_event *ev)
2952 {
2953         int rc = 0;
2954
2955         if (!ev->status)
2956                 goto out;
2957
2958         spin_lock(&lp->lp_lock);
2959         if (ev->msg_type == LNET_MSG_GET) {
2960                 lp->lp_state &= ~LNET_PEER_PING_SENT;
2961                 lp->lp_state |= LNET_PEER_PING_FAILED;
2962                 lp->lp_ping_error = ev->status;
2963         } else { /* ev->msg_type == LNET_MSG_PUT */
2964                 lp->lp_state &= ~LNET_PEER_PUSH_SENT;
2965                 lp->lp_state |= LNET_PEER_PUSH_FAILED;
2966                 lp->lp_push_error = ev->status;
2967         }
2968         spin_unlock(&lp->lp_lock);
2969         rc = LNET_REDISCOVER_PEER;
2970 out:
2971         CDEBUG(D_NET, "%s Send to %s: %d\n",
2972                 (ev->msg_type == LNET_MSG_GET ? "Ping" : "Push"),
2973                 libcfs_nidstr(&ev->target.nid), rc);
2974         return rc;
2975 }
2976
2977 /*
2978  * Unlink event handling. This event is only seen if a call to
2979  * LNetMDUnlink() caused the event to be unlinked. If this call was
2980  * made after the event was set up in LNetGet() or LNetPut() then we
2981  * assume the Ping or Push timed out.
2982  */
2983 static void
2984 lnet_discovery_event_unlink(struct lnet_peer *lp, struct lnet_event *ev)
2985 {
2986         spin_lock(&lp->lp_lock);
2987         /* We've passed through LNetGet() */
2988         if (lp->lp_state & LNET_PEER_PING_SENT) {
2989                 lp->lp_state &= ~LNET_PEER_PING_SENT;
2990                 lp->lp_state |= LNET_PEER_PING_FAILED;
2991                 lp->lp_ping_error = -ETIMEDOUT;
2992                 CDEBUG(D_NET, "Ping Unlink for message to peer %s\n",
2993                         libcfs_nidstr(&lp->lp_primary_nid));
2994         }
2995         /* We've passed through LNetPut() */
2996         if (lp->lp_state & LNET_PEER_PUSH_SENT) {
2997                 lp->lp_state &= ~LNET_PEER_PUSH_SENT;
2998                 lp->lp_state |= LNET_PEER_PUSH_FAILED;
2999                 lp->lp_push_error = -ETIMEDOUT;
3000                 CDEBUG(D_NET, "Push Unlink for message to peer %s\n",
3001                         libcfs_nidstr(&lp->lp_primary_nid));
3002         }
3003         spin_unlock(&lp->lp_lock);
3004 }
3005
3006 /*
3007  * Event handler for the discovery EQ.
3008  *
3009  * Called with lnet_res_lock(cpt) held. The cpt is the
3010  * lnet_cpt_of_cookie() of the md handle cookie.
3011  */
3012 static void lnet_discovery_event_handler(struct lnet_event *event)
3013 {
3014         struct lnet_peer *lp = event->md_user_ptr;
3015         struct lnet_ping_buffer *pbuf;
3016         int rc;
3017
3018         /* discovery needs to take another look */
3019         rc = LNET_REDISCOVER_PEER;
3020
3021         CDEBUG(D_NET, "Received event: %d\n", event->type);
3022
3023         switch (event->type) {
3024         case LNET_EVENT_ACK:
3025                 lnet_discovery_event_ack(lp, event);
3026                 break;
3027         case LNET_EVENT_REPLY:
3028                 lnet_discovery_event_reply(lp, event);
3029                 break;
3030         case LNET_EVENT_SEND:
3031                 /* Only send failure triggers a retry. */
3032                 rc = lnet_discovery_event_send(lp, event);
3033                 break;
3034         case LNET_EVENT_UNLINK:
3035                 /* LNetMDUnlink() was called */
3036                 lnet_discovery_event_unlink(lp, event);
3037                 break;
3038         default:
3039                 /* Invalid events. */
3040                 LBUG();
3041         }
3042         lnet_net_lock(LNET_LOCK_EX);
3043         if (event->unlinked) {
3044                 pbuf = LNET_PING_INFO_TO_BUFFER(event->md_start);
3045                 lnet_ping_buffer_decref(pbuf);
3046                 lnet_peer_decref_locked(lp);
3047         }
3048
3049         /* put peer back at end of request queue, if discovery not already
3050          * done */
3051         if (rc == LNET_REDISCOVER_PEER && !lnet_peer_is_uptodate(lp) &&
3052             lnet_peer_queue_for_discovery(lp)) {
3053                 list_move_tail(&lp->lp_dc_list, &the_lnet.ln_dc_request);
3054                 wake_up(&the_lnet.ln_dc_waitq);
3055         }
3056         lnet_net_unlock(LNET_LOCK_EX);
3057 }
3058
3059 u32 *ping_iter_first(struct lnet_ping_iter *pi,
3060                      struct lnet_ping_buffer *pbuf,
3061                      struct lnet_nid *nid)
3062 {
3063         pi->pinfo = &pbuf->pb_info;
3064         pi->pos = &pbuf->pb_info.pi_ni;
3065         pi->end = (void *)pi->pinfo +
3066                   min_t(int, pbuf->pb_nbytes,
3067                         lnet_ping_info_size(pi->pinfo));
3068         /* lnet_ping_info_validiate ensures there will be one
3069          * lnet_ni_status at the start
3070          */
3071         if (nid)
3072                 lnet_nid4_to_nid(pbuf->pb_info.pi_ni[0].ns_nid, nid);
3073
3074         pi->pos += sizeof(struct lnet_ni_status);
3075         return &pbuf->pb_info.pi_ni[0].ns_status;
3076 }
3077
3078 u32 *ping_iter_next(struct lnet_ping_iter *pi, struct lnet_nid *nid)
3079 {
3080         int off = offsetof(struct lnet_ping_info, pi_ni[pi->pinfo->pi_nnis]);
3081
3082         if (pi->pos < ((void *)pi->pinfo + off)) {
3083                 struct lnet_ni_status *ns = pi->pos;
3084
3085                 pi->pos = ns + 1;
3086                 if (pi->pos > pi->end)
3087                         return NULL;
3088                 if (nid)
3089                         lnet_nid4_to_nid(ns->ns_nid, nid);
3090                 return &ns->ns_status;
3091         }
3092
3093         while (pi->pinfo->pi_features & LNET_PING_FEAT_LARGE_ADDR) {
3094                 struct lnet_ni_large_status *lns = pi->pos;
3095
3096                 if (pi->pos + 8 > pi->end)
3097                         /* Not safe to examine next */
3098                         return NULL;
3099                 pi->pos = lnet_ping_sts_next(lns);
3100                 if (pi->pos > pi->end)
3101                         return NULL;
3102                 if (NID_BYTES(&lns->ns_nid) > sizeof(struct lnet_nid))
3103                         continue;
3104                 if (nid)
3105                         *nid = lns->ns_nid;
3106                 return &lns->ns_status;
3107         }
3108         return NULL;
3109 }
3110
3111 int ping_info_count_entries(struct lnet_ping_buffer *pbuf)
3112 {
3113         struct lnet_ping_iter pi;
3114         u32 *st;
3115         int nnis = 0;
3116
3117         for (st = ping_iter_first(&pi, pbuf, NULL); st;
3118              st = ping_iter_next(&pi, NULL))
3119                 nnis += 1;
3120
3121         return nnis;
3122 }
3123
3124 static inline void handle_disc_lpni_health(struct lnet_peer_ni *lpni)
3125 {
3126         if (lpni->lpni_ns_status == LNET_NI_STATUS_DOWN)
3127                 lnet_handle_remote_failure_locked(lpni);
3128         else if (lpni->lpni_ns_status == LNET_NI_STATUS_UP &&
3129                  !lpni->lpni_last_alive)
3130                 atomic_set(&lpni->lpni_healthv, LNET_MAX_HEALTH_VALUE);
3131 }
3132
3133 /*
3134  * Build a peer from incoming data.
3135  *
3136  * The NIDs in the incoming data are supposed to be structured as follows:
3137  *  - loopback
3138  *  - primary NID
3139  *  - other NIDs in same net
3140  *  - NIDs in second net
3141  *  - NIDs in third net
3142  *  - ...
3143  * This due to the way the list of NIDs in the data is created.
3144  *
3145  * Note that this function will mark the peer uptodate unless an
3146  * ENOMEM is encontered. All other errors are due to a conflict
3147  * between the DLC configuration and what discovery sees. We treat DLC
3148  * as binding, and therefore set the NIDS_UPTODATE flag to prevent the
3149  * peer from becoming stuck in discovery.
3150  */
3151 static int lnet_peer_merge_data(struct lnet_peer *lp,
3152                                 struct lnet_ping_buffer *pbuf)
3153 {
3154         struct lnet_peer_net *lpn;
3155         struct lnet_peer_ni *lpni;
3156         struct lnet_nid *curnis = NULL;
3157         struct lnet_ni_large_status *addnis = NULL;
3158         struct lnet_nid *delnis = NULL;
3159         struct lnet_ping_iter pi;
3160         struct lnet_nid nid;
3161         u32 *stp;
3162         struct lnet_nid primary = {};
3163         bool want_large_primary;
3164         unsigned int flags;
3165         int ncurnis;
3166         int naddnis;
3167         int ndelnis;
3168         int nnis = 0;
3169         int i;
3170         int j;
3171         int rc;
3172         __u32 old_st;
3173
3174         flags = LNET_PEER_DISCOVERED;
3175         if (pbuf->pb_info.pi_features & LNET_PING_FEAT_MULTI_RAIL)
3176                 flags |= LNET_PEER_MULTI_RAIL;
3177
3178         /*
3179          * Cache the routing feature for the peer; whether it is enabled
3180          * for disabled as reported by the remote peer.
3181          */
3182         spin_lock(&lp->lp_lock);
3183         if (!(pbuf->pb_info.pi_features & LNET_PING_FEAT_RTE_DISABLED))
3184                 lp->lp_state |= LNET_PEER_ROUTER_ENABLED;
3185         else
3186                 lp->lp_state &= ~LNET_PEER_ROUTER_ENABLED;
3187         spin_unlock(&lp->lp_lock);
3188
3189         nnis = ping_info_count_entries(pbuf);
3190         nnis = max_t(int, lp->lp_nnis, nnis);
3191         CFS_ALLOC_PTR_ARRAY(curnis, nnis);
3192         CFS_ALLOC_PTR_ARRAY(addnis, nnis);
3193         CFS_ALLOC_PTR_ARRAY(delnis, nnis);
3194         if (!curnis || !addnis || !delnis) {
3195                 rc = -ENOMEM;
3196                 goto out;
3197         }
3198         ncurnis = 0;
3199         naddnis = 0;
3200         ndelnis = 0;
3201
3202         /* Construct the list of NIDs present in peer. */
3203         lpni = NULL;
3204         while ((lpni = lnet_get_next_peer_ni_locked(lp, NULL, lpni)) != NULL)
3205                 curnis[ncurnis++] = lpni->lpni_nid;
3206
3207         /* Check for NIDs in pbuf not present in curnis[].
3208          * Skip the first, which is loop-back.  Take second as
3209          * primary, unless a large primary is found.
3210          */
3211         ping_iter_first(&pi, pbuf, NULL);
3212         stp = ping_iter_next(&pi, &nid);
3213         if (stp)
3214                 primary = nid;
3215         want_large_primary = (pbuf->pb_info.pi_features &
3216                               LNET_PING_FEAT_PRIMARY_LARGE);
3217         for (; stp; stp = ping_iter_next(&pi, &nid)) {
3218                 for (j = 0; j < ncurnis; j++)
3219                         if (nid_same(&nid, &curnis[j]))
3220                                 break;
3221                 if (j == ncurnis) {
3222                         addnis[naddnis].ns_nid = nid;
3223                         addnis[naddnis].ns_status = *stp;
3224                         naddnis += 1;
3225                 }
3226                 if (want_large_primary && nid.nid_size) {
3227                         primary = nid;
3228                         want_large_primary = false;
3229                 }
3230         }
3231         /*
3232          * Check for NIDs in curnis[] not present in pbuf.
3233          * The nested loop starts at 1 to skip the loopback NID.
3234          *
3235          * But never add the loopback NID to delnis[]: if it is
3236          * present in curnis[] then this peer is for this node.
3237          */
3238         for (i = 0; i < ncurnis; i++) {
3239                 if (nid_is_lo0(&curnis[i]))
3240                         continue;
3241                 ping_iter_first(&pi, pbuf, NULL);
3242                 while ((stp = ping_iter_next(&pi, &nid)) != NULL) {
3243                         if (nid_same(&curnis[i], &nid)) {
3244                                 /*
3245                                  * update the information we cache for the
3246                                  * peer with the latest information we
3247                                  * received
3248                                  */
3249                                 lpni = lnet_peer_ni_find_locked(&curnis[i]);
3250                                 if (lpni) {
3251                                         old_st = lpni->lpni_ns_status;
3252                                         lpni->lpni_ns_status = *stp;
3253                                         if (old_st != lpni->lpni_ns_status)
3254                                                 handle_disc_lpni_health(lpni);
3255                                         lnet_peer_ni_decref_locked(lpni);
3256                                 }
3257                                 break;
3258                         }
3259                 }
3260                 if (!stp)
3261                         delnis[ndelnis++] = curnis[i];
3262         }
3263
3264         /*
3265          * If we get here and the discovery is disabled then we don't want
3266          * to add or delete any NIs. We just updated the ones we have some
3267          * information on, and call it a day
3268          */
3269         rc = 0;
3270         if (lnet_is_discovery_disabled(lp))
3271                 goto out;
3272
3273         for (i = 0; i < naddnis; i++) {
3274                 rc = lnet_peer_add_nid(lp, &addnis[i].ns_nid, flags);
3275                 if (rc) {
3276                         CERROR("Error adding NID %s to peer %s: %d\n",
3277                                libcfs_nidstr(&addnis[i].ns_nid),
3278                                libcfs_nidstr(&lp->lp_primary_nid), rc);
3279                         if (rc == -ENOMEM)
3280                                 goto out;
3281                 }
3282                 lpni = lnet_peer_ni_find_locked(&addnis[i].ns_nid);
3283                 if (lpni) {
3284                         lpni->lpni_ns_status = addnis[i].ns_status;
3285                         handle_disc_lpni_health(lpni);
3286                         lnet_peer_ni_decref_locked(lpni);
3287                 }
3288         }
3289
3290         for (i = 0; i < ndelnis; i++) {
3291                 /*
3292                  * for routers it's okay to delete the primary_nid because
3293                  * the upper layers don't really rely on it. So if we're
3294                  * being told that the router changed its primary_nid
3295                  * then it's okay to delete it.
3296                  */
3297                 if (lp->lp_rtr_refcount > 0)
3298                         flags |= LNET_PEER_RTR_NI_FORCE_DEL;
3299                 rc = lnet_peer_del_nid(lp, &delnis[i], flags);
3300                 if (rc) {
3301                         CERROR("Error deleting NID %s from peer %s: %d\n",
3302                                libcfs_nidstr(&delnis[i]),
3303                                libcfs_nidstr(&lp->lp_primary_nid), rc);
3304                         if (rc == -ENOMEM)
3305                                 goto out;
3306                 }
3307         }
3308
3309         /* The peer net for the primary NID should be the first entry in the
3310          * peer's lp_peer_nets list, and the peer NI for the primary NID should
3311          * be the first entry in its peer net's lpn_peer_nis list.
3312          */
3313         find_primary(&nid, pbuf);
3314         lpni = lnet_peer_ni_find_locked(&nid);
3315         if (!lpni) {
3316                 CERROR("Internal error: Failed to lookup peer NI for primary NID: %s\n",
3317                        libcfs_nidstr(&nid));
3318                 goto out;
3319         }
3320
3321         lnet_peer_ni_decref_locked(lpni);
3322
3323         lpn = lpni->lpni_peer_net;
3324         if (lpn->lpn_peer_nets.prev != &lp->lp_peer_nets)
3325                 list_move(&lpn->lpn_peer_nets, &lp->lp_peer_nets);
3326
3327         if (lpni->lpni_peer_nis.prev != &lpni->lpni_peer_net->lpn_peer_nis)
3328                 list_move(&lpni->lpni_peer_nis,
3329                           &lpni->lpni_peer_net->lpn_peer_nis);
3330
3331         /*
3332          * Errors other than -ENOMEM are due to peers having been
3333          * configured with DLC. Ignore these because DLC overrides
3334          * Discovery.
3335          */
3336         rc = 0;
3337 out:
3338         /* If this peer is a gateway, invoke the routing callback to update
3339          * the associated route status
3340          */
3341         if (lp->lp_rtr_refcount > 0)
3342                 lnet_router_discovery_ping_reply(lp, pbuf);
3343
3344         CFS_FREE_PTR_ARRAY(curnis, nnis);
3345         CFS_FREE_PTR_ARRAY(addnis, nnis);
3346         CFS_FREE_PTR_ARRAY(delnis, nnis);
3347         lnet_ping_buffer_decref(pbuf);
3348         CDEBUG(D_NET, "peer %s (%p): %d\n",
3349                libcfs_nidstr(&lp->lp_primary_nid), lp, rc);
3350
3351         if (rc) {
3352                 spin_lock(&lp->lp_lock);
3353                 lp->lp_state &= ~LNET_PEER_NIDS_UPTODATE;
3354                 lp->lp_state |= LNET_PEER_FORCE_PING;
3355                 spin_unlock(&lp->lp_lock);
3356         }
3357         return rc;
3358 }
3359
3360 /*
3361  * The data in pbuf says lp is its primary peer, but the data was
3362  * received by a different peer. Try to update lp with the data.
3363  */
3364 static int
3365 lnet_peer_set_primary_data(struct lnet_peer *lp, struct lnet_ping_buffer *pbuf)
3366 {
3367         struct lnet_handle_md mdh;
3368
3369         /* Queue lp for discovery, and force it on the request queue. */
3370         lnet_net_lock(LNET_LOCK_EX);
3371         if (lnet_peer_queue_for_discovery(lp))
3372                 list_move(&lp->lp_dc_list, &the_lnet.ln_dc_request);
3373         lnet_net_unlock(LNET_LOCK_EX);
3374
3375         LNetInvalidateMDHandle(&mdh);
3376
3377         /*
3378          * Decide whether we can move the peer to the DATA_PRESENT state.
3379          *
3380          * We replace stale data for a multi-rail peer, repair PING_FAILED
3381          * status, and preempt FORCE_PING.
3382          *
3383          * If after that we have DATA_PRESENT, we merge it into this peer.
3384          */
3385         spin_lock(&lp->lp_lock);
3386         if (lp->lp_state & LNET_PEER_MULTI_RAIL) {
3387                 if (lp->lp_peer_seqno < LNET_PING_BUFFER_SEQNO(pbuf)) {
3388                         lp->lp_peer_seqno = LNET_PING_BUFFER_SEQNO(pbuf);
3389                 } else if (lp->lp_state & LNET_PEER_DATA_PRESENT) {
3390                         lp->lp_state &= ~LNET_PEER_DATA_PRESENT;
3391                         lnet_ping_buffer_decref(pbuf);
3392                         pbuf = lp->lp_data;
3393                         lp->lp_data = NULL;
3394                 }
3395         }
3396         if (lp->lp_state & LNET_PEER_DATA_PRESENT) {
3397                 lnet_ping_buffer_decref(lp->lp_data);
3398                 lp->lp_data = NULL;
3399                 lp->lp_state &= ~LNET_PEER_DATA_PRESENT;
3400         }
3401         if (lp->lp_state & LNET_PEER_PING_FAILED) {
3402                 mdh = lp->lp_ping_mdh;
3403                 LNetInvalidateMDHandle(&lp->lp_ping_mdh);
3404                 lp->lp_state &= ~LNET_PEER_PING_FAILED;
3405                 lp->lp_ping_error = 0;
3406         }
3407         if (lp->lp_state & LNET_PEER_FORCE_PING)
3408                 lp->lp_state &= ~LNET_PEER_FORCE_PING;
3409         lp->lp_state |= LNET_PEER_NIDS_UPTODATE;
3410         spin_unlock(&lp->lp_lock);
3411
3412         if (!LNetMDHandleIsInvalid(mdh))
3413                 LNetMDUnlink(mdh);
3414
3415         if (pbuf)
3416                 return lnet_peer_merge_data(lp, pbuf);
3417
3418         CDEBUG(D_NET, "peer %s\n", libcfs_nidstr(&lp->lp_primary_nid));
3419         return 0;
3420 }
3421
3422 static bool lnet_is_nid_in_ping_info(struct lnet_nid *nid,
3423                                      struct lnet_ping_buffer *pbuf)
3424 {
3425         struct lnet_ping_iter pi;
3426         struct lnet_nid pnid;
3427         u32 *st;
3428
3429         for (st = ping_iter_first(&pi, pbuf, &pnid);
3430              st;
3431              st = ping_iter_next(&pi, &pnid))
3432                 if (nid_same(nid, &pnid))
3433                         return true;
3434         return false;
3435 }
3436
3437 /* Delete a peer that has been marked for deletion. NB: when this peer was added
3438  * to the discovery queue a reference was taken that will prevent the peer from
3439  * actually being freed by this function. After this function exits the
3440  * discovery thread should call lnet_peer_discovery_complete() which will
3441  * drop that reference as well as wake any waiters that may also be holding a
3442  * ref on the peer
3443  */
3444 static int lnet_peer_deletion(struct lnet_peer *lp)
3445 __must_hold(&lp->lp_lock)
3446 {
3447         struct list_head rlist;
3448         struct lnet_route *route, *tmp;
3449         int sensitivity = lp->lp_health_sensitivity;
3450         int rc = 0;
3451
3452         INIT_LIST_HEAD(&rlist);
3453
3454         CDEBUG(D_NET, "peer %s(%p) state %#x\n",
3455                libcfs_nidstr(&lp->lp_primary_nid), lp, lp->lp_state);
3456
3457         /* no-op if lnet_peer_del() has already been called on this peer */
3458         if (lp->lp_state & LNET_PEER_MARK_DELETED)
3459                 goto clear_discovering;
3460
3461         spin_unlock(&lp->lp_lock);
3462
3463         mutex_lock(&the_lnet.ln_api_mutex);
3464         if (the_lnet.ln_state != LNET_STATE_RUNNING ||
3465             the_lnet.ln_dc_state != LNET_DC_STATE_RUNNING) {
3466                 mutex_unlock(&the_lnet.ln_api_mutex);
3467                 spin_lock(&lp->lp_lock);
3468                 rc = -ESHUTDOWN;
3469                 goto clear_discovering;
3470         }
3471
3472         lnet_peer_cancel_discovery(lp);
3473         lnet_net_lock(LNET_LOCK_EX);
3474         list_for_each_entry_safe(route, tmp,
3475                                  &lp->lp_routes,
3476                                  lr_gwlist)
3477                 lnet_move_route(route, NULL, &rlist);
3478
3479         /* lnet_peer_del_locked() deletes all the peer NIs owned by this peer */
3480         rc = lnet_peer_del_locked(lp);
3481         if (rc)
3482                 CNETERR("Internal error: Unable to delete peer %s rc %d\n",
3483                         libcfs_nidstr(&lp->lp_primary_nid), rc);
3484
3485         lnet_net_unlock(LNET_LOCK_EX);
3486
3487         list_for_each_entry_safe(route, tmp,
3488                                  &rlist, lr_list) {
3489                 /* re-add these routes */
3490                 lnet_add_route(route->lr_net,
3491                                route->lr_hops,
3492                                &route->lr_nid,
3493                                route->lr_priority,
3494                                sensitivity);
3495                 LIBCFS_FREE(route, sizeof(*route));
3496         }
3497
3498         mutex_unlock(&the_lnet.ln_api_mutex);
3499
3500         spin_lock(&lp->lp_lock);
3501
3502         rc = 0;
3503
3504 clear_discovering:
3505         lp->lp_state &= ~(LNET_PEER_DISCOVERING | LNET_PEER_FORCE_PING |
3506                           LNET_PEER_FORCE_PUSH);
3507
3508         return rc;
3509 }
3510
3511 /*
3512  * Update a peer using the data received.
3513  */
3514 static int lnet_peer_data_present(struct lnet_peer *lp)
3515 __must_hold(&lp->lp_lock)
3516 {
3517         struct lnet_ping_buffer *pbuf;
3518         struct lnet_peer_ni *lpni;
3519         struct lnet_nid nid;
3520         unsigned int flags;
3521         int rc = 0;
3522
3523         pbuf = lp->lp_data;
3524         lp->lp_data = NULL;
3525         lp->lp_state &= ~LNET_PEER_DATA_PRESENT;
3526         lp->lp_state |= LNET_PEER_NIDS_UPTODATE;
3527         spin_unlock(&lp->lp_lock);
3528
3529         /*
3530          * Modifications of peer structures are done while holding the
3531          * ln_api_mutex. A global lock is required because we may be
3532          * modifying multiple peer structures, and a mutex greatly
3533          * simplifies memory management.
3534          *
3535          * The actual changes to the data structures must also protect
3536          * against concurrent lookups, for which the lnet_net_lock in
3537          * LNET_LOCK_EX mode is used.
3538          */
3539         mutex_lock(&the_lnet.ln_api_mutex);
3540         if (the_lnet.ln_state != LNET_STATE_RUNNING) {
3541                 rc = -ESHUTDOWN;
3542                 goto out;
3543         }
3544
3545         /*
3546          * If this peer is not on the peer list then it is being torn
3547          * down, and our reference count may be all that is keeping it
3548          * alive. Don't do any work on it.
3549          */
3550         if (list_empty(&lp->lp_peer_list)) {
3551                 lnet_ping_buffer_decref(pbuf);
3552                 goto out;
3553         }
3554
3555         flags = LNET_PEER_DISCOVERED;
3556         if (pbuf->pb_info.pi_features & LNET_PING_FEAT_MULTI_RAIL)
3557                 flags |= LNET_PEER_MULTI_RAIL;
3558
3559         /*
3560          * Check whether the primary NID in the message matches the
3561          * primary NID of the peer. If it does, update the peer, if
3562          * it it does not, check whether there is already a peer with
3563          * that primary NID. If no such peer exists, try to update
3564          * the primary NID of the current peer (allowed if it was
3565          * created due to message traffic) and complete the update.
3566          * If the peer did exist, hand off the data to it.
3567          *
3568          * The peer for the loopback interface is a special case: this
3569          * is the peer for the local node, and we want to set its
3570          * primary NID to the correct value here. Moreover, this peer
3571          * can show up with only the loopback NID in the ping buffer.
3572          */
3573         if (!find_primary(&nid, pbuf)) {
3574                 lnet_ping_buffer_decref(pbuf);
3575                 goto out;
3576         }
3577         if (nid_is_lo0(&lp->lp_primary_nid)) {
3578                 rc = lnet_peer_set_primary_nid(lp, &nid, flags);
3579                 if (rc)
3580                         lnet_ping_buffer_decref(pbuf);
3581                 else
3582                         rc = lnet_peer_merge_data(lp, pbuf);
3583         /*
3584          * if the primary nid of the peer is present in the ping info returned
3585          * from the peer, but it's not the local primary peer we have
3586          * cached and discovery is disabled, then we don't want to update
3587          * our local peer info, by adding or removing NIDs, we just want
3588          * to update the status of the nids that we currently have
3589          * recorded in that peer.
3590          */
3591         } else if (nid_same(&lp->lp_primary_nid, &nid) ||
3592                    (lnet_is_nid_in_ping_info(&lp->lp_primary_nid, pbuf) &&
3593                     lnet_is_discovery_disabled(lp))) {
3594                 rc = lnet_peer_merge_data(lp, pbuf);
3595         } else {
3596                 lpni = lnet_peer_ni_find_locked(&nid);
3597                 if (!lpni || lp == lpni->lpni_peer_net->lpn_peer) {
3598                         rc = lnet_peer_set_primary_nid(lp, &nid, flags);
3599                         if (rc) {
3600                                 CERROR("Primary NID error %s versus %s: %d\n",
3601                                        libcfs_nidstr(&lp->lp_primary_nid),
3602                                        libcfs_nidstr(&nid), rc);
3603                                 lnet_ping_buffer_decref(pbuf);
3604                         } else {
3605                                 rc = lnet_peer_merge_data(lp, pbuf);
3606                         }
3607                         if (lpni)
3608                                 lnet_peer_ni_decref_locked(lpni);
3609                 } else {
3610                         struct lnet_peer *new_lp;
3611                         new_lp = lpni->lpni_peer_net->lpn_peer;
3612                         /*
3613                          * if lp has discovery/MR enabled that means new_lp
3614                          * should have discovery/MR enabled as well, since
3615                          * it's the same peer, which we're about to merge
3616                          */
3617                         spin_lock(&lp->lp_lock);
3618                         spin_lock(&new_lp->lp_lock);
3619                         if (!(lp->lp_state & LNET_PEER_NO_DISCOVERY))
3620                                 new_lp->lp_state &= ~LNET_PEER_NO_DISCOVERY;
3621                         if (lp->lp_state & LNET_PEER_MULTI_RAIL)
3622                                 new_lp->lp_state |= LNET_PEER_MULTI_RAIL;
3623                         /* If we're processing a ping reply then we may be
3624                          * about to send a push to the peer that we ping'd.
3625                          * Since the ping reply that we're processing was
3626                          * received by lp, we need to set the discovery source
3627                          * NID for new_lp to the NID stored in lp.
3628                          */
3629                         if (!LNET_NID_IS_ANY(&lp->lp_disc_src_nid)) {
3630                                 new_lp->lp_disc_src_nid = lp->lp_disc_src_nid;
3631                                 new_lp->lp_disc_dst_nid = lp->lp_disc_dst_nid;
3632                         }
3633                         spin_unlock(&new_lp->lp_lock);
3634                         spin_unlock(&lp->lp_lock);
3635
3636                         rc = lnet_peer_set_primary_data(new_lp, pbuf);
3637                         lnet_consolidate_routes_locked(lp, new_lp);
3638                         lnet_peer_ni_decref_locked(lpni);
3639                 }
3640         }
3641 out:
3642         CDEBUG(D_NET, "peer %s(%p): %d. state = 0x%x\n",
3643                libcfs_nidstr(&lp->lp_primary_nid), lp, rc,
3644                lp->lp_state);
3645         mutex_unlock(&the_lnet.ln_api_mutex);
3646
3647         spin_lock(&lp->lp_lock);
3648         /* Tell discovery to re-check the peer immediately. */
3649         if (!rc)
3650                 rc = LNET_REDISCOVER_PEER;
3651         return rc;
3652 }
3653
3654 /*
3655  * A ping failed. Clear the PING_FAILED state and set the
3656  * FORCE_PING state, to ensure a retry even if discovery is
3657  * disabled. This avoids being left with incorrect state.
3658  */
3659 static int lnet_peer_ping_failed(struct lnet_peer *lp)
3660 __must_hold(&lp->lp_lock)
3661 {
3662         struct lnet_handle_md mdh;
3663         int rc;
3664
3665         mdh = lp->lp_ping_mdh;
3666         LNetInvalidateMDHandle(&lp->lp_ping_mdh);
3667         lp->lp_state &= ~LNET_PEER_PING_FAILED;
3668         lp->lp_state |= LNET_PEER_FORCE_PING;
3669         rc = lp->lp_ping_error;
3670         lp->lp_ping_error = 0;
3671         spin_unlock(&lp->lp_lock);
3672
3673         if (!LNetMDHandleIsInvalid(mdh))
3674                 LNetMDUnlink(mdh);
3675
3676         CDEBUG(D_NET, "peer %s:%d\n",
3677                libcfs_nidstr(&lp->lp_primary_nid), rc);
3678
3679         spin_lock(&lp->lp_lock);
3680         return rc ? rc : LNET_REDISCOVER_PEER;
3681 }
3682
3683 /* Active side of ping. */
3684 static int lnet_peer_send_ping(struct lnet_peer *lp)
3685 __must_hold(&lp->lp_lock)
3686 {
3687         int bytes;
3688         int rc;
3689         int cpt;
3690
3691         lp->lp_state |= LNET_PEER_PING_SENT;
3692         lp->lp_state &= ~LNET_PEER_FORCE_PING;
3693         spin_unlock(&lp->lp_lock);
3694
3695         cpt = lnet_net_lock_current();
3696         /* Refcount for MD. */
3697         lnet_peer_addref_locked(lp);
3698         lnet_net_unlock(cpt);
3699
3700         bytes = max_t(int, lp->lp_data_bytes, LNET_PING_INFO_MIN_SIZE);
3701
3702         rc = lnet_send_ping(&lp->lp_primary_nid, &lp->lp_ping_mdh, bytes, lp,
3703                             the_lnet.ln_dc_handler, false);
3704         /* if LNetMDBind in lnet_send_ping fails we need to decrement the
3705          * refcount on the peer, otherwise LNetMDUnlink will be called
3706          * which will eventually do that.
3707          */
3708         if (rc > 0) {
3709                 lnet_net_lock(cpt);
3710                 lnet_peer_decref_locked(lp);
3711                 lnet_net_unlock(cpt);
3712                 rc = -rc; /* change the rc to negative value */
3713                 goto fail_error;
3714         } else if (rc < 0) {
3715                 goto fail_error;
3716         }
3717
3718         CDEBUG(D_NET, "peer %s\n", libcfs_nidstr(&lp->lp_primary_nid));
3719
3720         spin_lock(&lp->lp_lock);
3721         return 0;
3722
3723 fail_error:
3724         CDEBUG(D_NET, "peer %s: %d\n", libcfs_nidstr(&lp->lp_primary_nid), rc);
3725         /*
3726          * The errors that get us here are considered hard errors and
3727          * cause Discovery to terminate. So we clear PING_SENT, but do
3728          * not set either PING_FAILED or FORCE_PING. In fact we need
3729          * to clear PING_FAILED, because the unlink event handler will
3730          * have set it if we called LNetMDUnlink() above.
3731          */
3732         spin_lock(&lp->lp_lock);
3733         lp->lp_state &= ~(LNET_PEER_PING_SENT | LNET_PEER_PING_FAILED);
3734         return rc;
3735 }
3736
3737 /*
3738  * This function exists because you cannot call LNetMDUnlink() from an
3739  * event handler.
3740  */
3741 static int lnet_peer_push_failed(struct lnet_peer *lp)
3742 __must_hold(&lp->lp_lock)
3743 {
3744         struct lnet_handle_md mdh;
3745         int rc;
3746
3747         mdh = lp->lp_push_mdh;
3748         LNetInvalidateMDHandle(&lp->lp_push_mdh);
3749         lp->lp_state &= ~LNET_PEER_PUSH_FAILED;
3750         rc = lp->lp_push_error;
3751         lp->lp_push_error = 0;
3752         spin_unlock(&lp->lp_lock);
3753
3754         if (!LNetMDHandleIsInvalid(mdh))
3755                 LNetMDUnlink(mdh);
3756
3757         CDEBUG(D_NET, "peer %s\n", libcfs_nidstr(&lp->lp_primary_nid));
3758         spin_lock(&lp->lp_lock);
3759         return rc ? rc : LNET_REDISCOVER_PEER;
3760 }
3761
3762 /*
3763  * Mark the peer as discovered.
3764  */
3765 static int lnet_peer_discovered(struct lnet_peer *lp)
3766 __must_hold(&lp->lp_lock)
3767 {
3768         lp->lp_state |= LNET_PEER_DISCOVERED;
3769         lp->lp_state &= ~(LNET_PEER_DISCOVERING |
3770                           LNET_PEER_REDISCOVER);
3771
3772         lp->lp_dc_error = 0;
3773
3774         CDEBUG(D_NET, "peer %s\n", libcfs_nidstr(&lp->lp_primary_nid));
3775
3776         return 0;
3777 }
3778
3779 /* Active side of push. */
3780 static int lnet_peer_send_push(struct lnet_peer *lp)
3781 __must_hold(&lp->lp_lock)
3782 {
3783         struct lnet_ping_buffer *pbuf;
3784         struct lnet_processid id;
3785         struct lnet_md md;
3786         int cpt;
3787         int rc;
3788
3789         /* Don't push to a non-multi-rail peer. */
3790         if (!(lp->lp_state & LNET_PEER_MULTI_RAIL)) {
3791                 lp->lp_state &= ~LNET_PEER_FORCE_PUSH;
3792                 /* if peer's NIDs are uptodate then peer is discovered */
3793                 if (lp->lp_state & LNET_PEER_NIDS_UPTODATE) {
3794                         rc = lnet_peer_discovered(lp);
3795                         return rc;
3796                 }
3797
3798                 return 0;
3799         }
3800
3801         lp->lp_state |= LNET_PEER_PUSH_SENT;
3802         lp->lp_state &= ~LNET_PEER_FORCE_PUSH;
3803         spin_unlock(&lp->lp_lock);
3804
3805         cpt = lnet_net_lock_current();
3806         pbuf = the_lnet.ln_ping_target;
3807         lnet_ping_buffer_addref(pbuf);
3808         lnet_net_unlock(cpt);
3809
3810         /* Push source MD */
3811         md.start     = &pbuf->pb_info;
3812         md.length    = pbuf->pb_nbytes;
3813         md.threshold = 2; /* Put/Ack */
3814         md.max_size  = 0;
3815         md.options   = LNET_MD_TRACK_RESPONSE;
3816         md.handler   = the_lnet.ln_dc_handler;
3817         md.user_ptr  = lp;
3818
3819         rc = LNetMDBind(&md, LNET_UNLINK, &lp->lp_push_mdh);
3820         if (rc) {
3821                 lnet_ping_buffer_decref(pbuf);
3822                 CERROR("Can't bind push source MD: %d\n", rc);
3823                 goto fail_error;
3824         }
3825
3826         cpt = lnet_net_lock_current();
3827         /* Refcount for MD. */
3828         lnet_peer_addref_locked(lp);
3829         id.pid = LNET_PID_LUSTRE;
3830         if (!LNET_NID_IS_ANY(&lp->lp_disc_dst_nid))
3831                 id.nid = lp->lp_disc_dst_nid;
3832         else
3833                 id.nid = lp->lp_primary_nid;
3834         lnet_net_unlock(cpt);
3835
3836         rc = LNetPut(&lp->lp_disc_src_nid, lp->lp_push_mdh,
3837                      LNET_ACK_REQ, &id, LNET_RESERVED_PORTAL,
3838                      LNET_PROTO_PING_MATCHBITS, 0, 0);
3839
3840         /*
3841          * reset the discovery nid. There is no need to restrict sending
3842          * from that source, if we call lnet_push_update_to_peers(). It'll
3843          * get set to a specific NID, if we initiate discovery from the
3844          * scratch
3845          */
3846         lp->lp_disc_src_nid = LNET_ANY_NID;
3847         lp->lp_disc_dst_nid = LNET_ANY_NID;
3848
3849         if (rc)
3850                 goto fail_unlink;
3851
3852         CDEBUG(D_NET, "peer %s\n", libcfs_nidstr(&lp->lp_primary_nid));
3853
3854         spin_lock(&lp->lp_lock);
3855         return 0;
3856
3857 fail_unlink:
3858         LNetMDUnlink(lp->lp_push_mdh);
3859         LNetInvalidateMDHandle(&lp->lp_push_mdh);
3860 fail_error:
3861         CDEBUG(D_NET, "peer %s(%p): %d\n", libcfs_nidstr(&lp->lp_primary_nid),
3862                lp, rc);
3863         /*
3864          * The errors that get us here are considered hard errors and
3865          * cause Discovery to terminate. So we clear PUSH_SENT, but do
3866          * not set PUSH_FAILED. In fact we need to clear PUSH_FAILED,
3867          * because the unlink event handler will have set it if we
3868          * called LNetMDUnlink() above.
3869          */
3870         spin_lock(&lp->lp_lock);
3871         lp->lp_state &= ~(LNET_PEER_PUSH_SENT | LNET_PEER_PUSH_FAILED);
3872         return rc;
3873 }
3874
3875 /*
3876  * Wait for work to be queued or some other change that must be
3877  * attended to. Returns non-zero if the discovery thread should shut
3878  * down.
3879  */
3880 static int lnet_peer_discovery_wait_for_work(void)
3881 {
3882         int cpt;
3883         int rc = 0;
3884
3885         DEFINE_WAIT(wait);
3886
3887         cpt = lnet_net_lock_current();
3888         for (;;) {
3889                 prepare_to_wait(&the_lnet.ln_dc_waitq, &wait,
3890                                 TASK_INTERRUPTIBLE);
3891                 if (the_lnet.ln_dc_state == LNET_DC_STATE_STOPPING)
3892                         break;
3893                 if (lnet_push_target_resize_needed() ||
3894                     the_lnet.ln_push_target->pb_needs_post)
3895                         break;
3896                 if (!list_empty(&the_lnet.ln_dc_request))
3897                         break;
3898                 if (!list_empty(&the_lnet.ln_msg_resend))
3899                         break;
3900                 lnet_net_unlock(cpt);
3901
3902                 /*
3903                  * wakeup max every second to check if there are peers that
3904                  * have been stuck on the working queue for greater than
3905                  * the peer timeout.
3906                  */
3907                 schedule_timeout(cfs_time_seconds(1));
3908                 finish_wait(&the_lnet.ln_dc_waitq, &wait);
3909                 cpt = lnet_net_lock_current();
3910         }
3911         finish_wait(&the_lnet.ln_dc_waitq, &wait);
3912
3913         if (the_lnet.ln_dc_state == LNET_DC_STATE_STOPPING)
3914                 rc = -ESHUTDOWN;
3915
3916         lnet_net_unlock(cpt);
3917
3918         CDEBUG(D_NET, "woken: %d\n", rc);
3919
3920         return rc;
3921 }
3922
3923 /*
3924  * Messages that were pending on a destroyed peer will be put on a global
3925  * resend list. The message resend list will be checked by
3926  * the discovery thread when it wakes up, and will resend messages. These
3927  * messages can still be sendable in the case the lpni which was the initial
3928  * cause of the message re-queue was transfered to another peer.
3929  *
3930  * It is possible that LNet could be shutdown while we're iterating
3931  * through the list. lnet_shudown_lndnets() will attempt to access the
3932  * resend list, but will have to wait until the spinlock is released, by
3933  * which time there shouldn't be any more messages on the resend list.
3934  * During shutdown lnet_send() will fail and lnet_finalize() will be called
3935  * for the messages so they can be released. The other case is that
3936  * lnet_shudown_lndnets() can finalize all the messages before this
3937  * function can visit the resend list, in which case this function will be
3938  * a no-op.
3939  */
3940 static void lnet_resend_msgs(void)
3941 {
3942         struct lnet_msg *msg, *tmp;
3943         LIST_HEAD(resend);
3944         int rc;
3945
3946         spin_lock(&the_lnet.ln_msg_resend_lock);
3947         list_splice(&the_lnet.ln_msg_resend, &resend);
3948         spin_unlock(&the_lnet.ln_msg_resend_lock);
3949
3950         list_for_each_entry_safe(msg, tmp, &resend, msg_list) {
3951                 list_del_init(&msg->msg_list);
3952                 rc = lnet_send(&msg->msg_src_nid_param, msg,
3953                                &msg->msg_rtr_nid_param);
3954                 if (rc < 0) {
3955                         CNETERR("Error sending %s to %s: %d\n",
3956                                lnet_msgtyp2str(msg->msg_type),
3957                                libcfs_idstr(&msg->msg_target), rc);
3958                         lnet_finalize(msg, rc);
3959                 }
3960         }
3961 }
3962
3963 /* The discovery thread. */
3964 static int lnet_peer_discovery(void *arg)
3965 {
3966         struct lnet_peer *lp;
3967         int rc;
3968
3969         wait_for_completion(&the_lnet.ln_started);
3970
3971         CDEBUG(D_NET, "started\n");
3972
3973         for (;;) {
3974                 if (lnet_peer_discovery_wait_for_work())
3975                         break;
3976
3977                 if (lnet_push_target_resize_needed())
3978                         lnet_push_target_resize();
3979                 else if (the_lnet.ln_push_target->pb_needs_post)
3980                         lnet_push_target_post(the_lnet.ln_push_target,
3981                                               &the_lnet.ln_push_target_md);
3982
3983                 lnet_resend_msgs();
3984
3985                 lnet_net_lock(LNET_LOCK_EX);
3986                 if (the_lnet.ln_dc_state == LNET_DC_STATE_STOPPING) {
3987                         lnet_net_unlock(LNET_LOCK_EX);
3988                         break;
3989                 }
3990
3991                 /*
3992                  * Process all incoming discovery work requests.  When
3993                  * discovery must wait on a peer to change state, it
3994                  * is added to the tail of the ln_dc_working queue. A
3995                  * timestamp keeps track of when the peer was added,
3996                  * so we can time out discovery requests that take too
3997                  * long.
3998                  */
3999                 while (!list_empty(&the_lnet.ln_dc_request)) {
4000                         lp = list_first_entry(&the_lnet.ln_dc_request,
4001                                               struct lnet_peer, lp_dc_list);
4002                         list_move(&lp->lp_dc_list, &the_lnet.ln_dc_working);
4003                         /*
4004                          * set the time the peer was put on the dc_working
4005                          * queue. It shouldn't remain on the queue
4006                          * forever, in case the GET message (for ping)
4007                          * doesn't get a REPLY or the PUT message (for
4008                          * push) doesn't get an ACK.
4009                          */
4010                         lp->lp_last_queued = ktime_get_real_seconds();
4011                         lnet_net_unlock(LNET_LOCK_EX);
4012
4013                         if (lnet_push_target_resize_needed())
4014                                 lnet_push_target_resize();
4015                         else if (the_lnet.ln_push_target->pb_needs_post)
4016                                 lnet_push_target_post(the_lnet.ln_push_target,
4017                                                       &the_lnet.ln_push_target_md);
4018
4019                         /*
4020                          * Select an action depending on the state of
4021                          * the peer and whether discovery is disabled.
4022                          * The check whether discovery is disabled is
4023                          * done after the code that handles processing
4024                          * for arrived data, cleanup for failures, and
4025                          * forcing a Ping or Push.
4026                          */
4027                         spin_lock(&lp->lp_lock);
4028                         CDEBUG(D_NET, "peer %s(%p) state %#x\n",
4029                                 libcfs_nidstr(&lp->lp_primary_nid), lp,
4030                                 lp->lp_state);
4031                         if (lp->lp_state & (LNET_PEER_MARK_DELETION |
4032                                             LNET_PEER_MARK_DELETED))
4033                                 rc = lnet_peer_deletion(lp);
4034                         else if (lp->lp_state & LNET_PEER_DATA_PRESENT)
4035                                 rc = lnet_peer_data_present(lp);
4036                         else if (lp->lp_state & LNET_PEER_PING_FAILED)
4037                                 rc = lnet_peer_ping_failed(lp);
4038                         else if (lp->lp_state & LNET_PEER_PUSH_FAILED)
4039                                 rc = lnet_peer_push_failed(lp);
4040                         else if (lp->lp_state & LNET_PEER_FORCE_PING)
4041                                 rc = lnet_peer_send_ping(lp);
4042                         else if (lp->lp_state & LNET_PEER_FORCE_PUSH)
4043                                 rc = lnet_peer_send_push(lp);
4044                         else if (!(lp->lp_state & LNET_PEER_NIDS_UPTODATE))
4045                                 rc = lnet_peer_send_ping(lp);
4046                         else if (lnet_peer_needs_push(lp))
4047                                 rc = lnet_peer_send_push(lp);
4048                         else
4049                                 rc = lnet_peer_discovered(lp);
4050                         CDEBUG(D_NET, "peer %s(%p) state %#x rc %d\n",
4051                                 libcfs_nidstr(&lp->lp_primary_nid), lp,
4052                                 lp->lp_state, rc);
4053
4054                         if (rc == LNET_REDISCOVER_PEER) {
4055                                 spin_unlock(&lp->lp_lock);
4056                                 lnet_net_lock(LNET_LOCK_EX);
4057                                 list_move(&lp->lp_dc_list,
4058                                           &the_lnet.ln_dc_request);
4059                         } else if (rc ||
4060                                    !(lp->lp_state & LNET_PEER_DISCOVERING)) {
4061                                 spin_unlock(&lp->lp_lock);
4062                                 lnet_net_lock(LNET_LOCK_EX);
4063                                 lnet_peer_discovery_complete(lp, rc);
4064                         } else {
4065                                 spin_unlock(&lp->lp_lock);
4066                                 lnet_net_lock(LNET_LOCK_EX);
4067                         }
4068
4069                         if (the_lnet.ln_dc_state == LNET_DC_STATE_STOPPING)
4070                                 break;
4071
4072                 }
4073
4074                 lnet_net_unlock(LNET_LOCK_EX);
4075         }
4076
4077         CDEBUG(D_NET, "stopping\n");
4078         /*
4079          * Clean up before telling lnet_peer_discovery_stop() that
4080          * we're done. Use wake_up() below to somewhat reduce the
4081          * size of the thundering herd if there are multiple threads
4082          * waiting on discovery of a single peer.
4083          */
4084
4085         /* Queue cleanup 1: stop all pending pings and pushes. */
4086         lnet_net_lock(LNET_LOCK_EX);
4087         while (!list_empty(&the_lnet.ln_dc_working)) {
4088                 lp = list_first_entry(&the_lnet.ln_dc_working,
4089                                       struct lnet_peer, lp_dc_list);
4090                 list_move(&lp->lp_dc_list, &the_lnet.ln_dc_expired);
4091                 lnet_net_unlock(LNET_LOCK_EX);
4092                 lnet_peer_cancel_discovery(lp);
4093                 lnet_net_lock(LNET_LOCK_EX);
4094         }
4095         lnet_net_unlock(LNET_LOCK_EX);
4096
4097         /* Queue cleanup 2: wait for the expired queue to clear. */
4098         while (!list_empty(&the_lnet.ln_dc_expired))
4099                 schedule_timeout_uninterruptible(cfs_time_seconds(1));
4100
4101         /* Queue cleanup 3: clear the request queue. */
4102         lnet_net_lock(LNET_LOCK_EX);
4103         while (!list_empty(&the_lnet.ln_dc_request)) {
4104                 lp = list_first_entry(&the_lnet.ln_dc_request,
4105                                       struct lnet_peer, lp_dc_list);
4106                 lnet_peer_discovery_complete(lp, -ESHUTDOWN);
4107         }
4108         lnet_net_unlock(LNET_LOCK_EX);
4109
4110         lnet_assert_handler_unused(the_lnet.ln_dc_handler);
4111         the_lnet.ln_dc_handler = NULL;
4112
4113         the_lnet.ln_dc_state = LNET_DC_STATE_SHUTDOWN;
4114         wake_up(&the_lnet.ln_dc_waitq);
4115
4116         CDEBUG(D_NET, "stopped\n");
4117
4118         return 0;
4119 }
4120
4121 /* ln_api_mutex is held on entry. */
4122 int lnet_peer_discovery_start(void)
4123 {
4124         struct task_struct *task;
4125         int rc = 0;
4126
4127         if (the_lnet.ln_dc_state != LNET_DC_STATE_SHUTDOWN)
4128                 return -EALREADY;
4129
4130         the_lnet.ln_dc_handler = lnet_discovery_event_handler;
4131         the_lnet.ln_dc_state = LNET_DC_STATE_RUNNING;
4132         task = kthread_run(lnet_peer_discovery, NULL, "lnet_discovery");
4133         if (IS_ERR(task)) {
4134                 rc = PTR_ERR(task);
4135                 CERROR("Can't start peer discovery thread: %d\n", rc);
4136
4137                 the_lnet.ln_dc_handler = NULL;
4138
4139                 the_lnet.ln_dc_state = LNET_DC_STATE_SHUTDOWN;
4140         }
4141
4142         CDEBUG(D_NET, "discovery start: %d\n", rc);
4143
4144         return rc;
4145 }
4146
4147 /* ln_api_mutex is held on entry. */
4148 void lnet_peer_discovery_stop(void)
4149 {
4150         if (the_lnet.ln_dc_state == LNET_DC_STATE_SHUTDOWN)
4151                 return;
4152
4153         LASSERT(the_lnet.ln_dc_state == LNET_DC_STATE_RUNNING);
4154         the_lnet.ln_dc_state = LNET_DC_STATE_STOPPING;
4155
4156         /* In the LNetNIInit() path we may be stopping discovery before it
4157          * entered its work loop
4158          */
4159         if (!completion_done(&the_lnet.ln_started))
4160                 complete(&the_lnet.ln_started);
4161         else
4162                 wake_up(&the_lnet.ln_dc_waitq);
4163
4164         mutex_unlock(&the_lnet.ln_api_mutex);
4165         wait_event(the_lnet.ln_dc_waitq,
4166                    the_lnet.ln_dc_state == LNET_DC_STATE_SHUTDOWN);
4167         mutex_lock(&the_lnet.ln_api_mutex);
4168
4169         LASSERT(list_empty(&the_lnet.ln_dc_request));
4170         LASSERT(list_empty(&the_lnet.ln_dc_working));
4171         LASSERT(list_empty(&the_lnet.ln_dc_expired));
4172
4173         CDEBUG(D_NET, "discovery stopped\n");
4174 }
4175
4176 /* Debugging */
4177
4178 void
4179 lnet_debug_peer(struct lnet_nid *nid)
4180 {
4181         char                    *aliveness = "NA";
4182         struct lnet_peer_ni     *lp;
4183         int                     cpt;
4184
4185         cpt = lnet_nid2cpt(nid, NULL);
4186         lnet_net_lock(cpt);
4187
4188         lp = lnet_peerni_by_nid_locked(nid, NULL, cpt);
4189         if (IS_ERR(lp)) {
4190                 lnet_net_unlock(cpt);
4191                 CDEBUG(D_WARNING, "No peer %s\n", libcfs_nidstr(nid));
4192                 return;
4193         }
4194
4195         if (lnet_isrouter(lp) || lnet_peer_aliveness_enabled(lp))
4196                 aliveness = (lnet_is_peer_ni_alive(lp)) ? "up" : "down";
4197
4198         CDEBUG(D_WARNING, "%-24s %4d %5s %5d %5d %5d %5d %5d %ld\n",
4199                libcfs_nidstr(&lp->lpni_nid), kref_read(&lp->lpni_kref),
4200                aliveness, lp->lpni_net->net_tunables.lct_peer_tx_credits,
4201                lp->lpni_rtrcredits, lp->lpni_minrtrcredits,
4202                lp->lpni_txcredits, lp->lpni_mintxcredits, lp->lpni_txqnob);
4203
4204         lnet_peer_ni_decref_locked(lp);
4205
4206         lnet_net_unlock(cpt);
4207 }
4208
4209 /* Gathering information for userspace. */
4210
4211 int lnet_get_peer_ni_info(__u32 peer_index, __u64 *nid,
4212                           char aliveness[LNET_MAX_STR_LEN],
4213                           __u32 *cpt_iter, __u32 *refcount,
4214                           __u32 *ni_peer_tx_credits, __u32 *peer_tx_credits,
4215                           __u32 *peer_rtr_credits, __u32 *peer_min_rtr_credits,
4216                           __u32 *peer_tx_qnob)
4217 {
4218         struct lnet_peer_table          *peer_table;
4219         struct lnet_peer_ni             *lp;
4220         int                             j;
4221         int                             lncpt;
4222         bool                            found = false;
4223
4224         /* get the number of CPTs */
4225         lncpt = cfs_percpt_number(the_lnet.ln_peer_tables);
4226
4227         /* if the cpt number to be examined is >= the number of cpts in
4228          * the system then indicate that there are no more cpts to examin
4229          */
4230         if (*cpt_iter >= lncpt)
4231                 return -ENOENT;
4232
4233         /* get the current table */
4234         peer_table = the_lnet.ln_peer_tables[*cpt_iter];
4235         /* if the ptable is NULL then there are no more cpts to examine */
4236         if (peer_table == NULL)
4237                 return -ENOENT;
4238
4239         lnet_net_lock(*cpt_iter);
4240
4241         for (j = 0; j < LNET_PEER_HASH_SIZE && !found; j++) {
4242                 struct list_head *peers = &peer_table->pt_hash[j];
4243
4244                 list_for_each_entry(lp, peers, lpni_hashlist) {
4245                         if (!nid_is_nid4(&lp->lpni_nid))
4246                                 continue;
4247                         if (peer_index-- > 0)
4248                                 continue;
4249
4250                         snprintf(aliveness, LNET_MAX_STR_LEN, "NA");
4251                         if (lnet_isrouter(lp) ||
4252                                 lnet_peer_aliveness_enabled(lp))
4253                                 snprintf(aliveness, LNET_MAX_STR_LEN,
4254                                          lnet_is_peer_ni_alive(lp) ? "up" : "down");
4255
4256                         *nid = lnet_nid_to_nid4(&lp->lpni_nid);
4257                         *refcount = kref_read(&lp->lpni_kref);
4258                         *ni_peer_tx_credits =
4259                                 lp->lpni_net->net_tunables.lct_peer_tx_credits;
4260                         *peer_tx_credits = lp->lpni_txcredits;
4261                         *peer_rtr_credits = lp->lpni_rtrcredits;
4262                         *peer_min_rtr_credits = lp->lpni_mintxcredits;
4263                         *peer_tx_qnob = lp->lpni_txqnob;
4264
4265                         found = true;
4266                 }
4267
4268         }
4269         lnet_net_unlock(*cpt_iter);
4270
4271         *cpt_iter = lncpt;
4272
4273         return found ? 0 : -ENOENT;
4274 }
4275
4276 /* ln_api_mutex is held, which keeps the peer list stable */
4277 int lnet_get_peer_info(struct lnet_ioctl_peer_cfg *cfg, void __user *bulk)
4278 {
4279         struct lnet_ioctl_element_stats *lpni_stats;
4280         struct lnet_ioctl_element_msg_stats *lpni_msg_stats;
4281         struct lnet_ioctl_peer_ni_hstats *lpni_hstats;
4282         struct lnet_peer_ni_credit_info *lpni_info;
4283         struct lnet_peer_ni *lpni;
4284         struct lnet_peer *lp;
4285         lnet_nid_t nid4;
4286         struct lnet_nid nid;
4287         __u32 size;
4288         int rc;
4289
4290         lnet_nid4_to_nid(cfg->prcfg_prim_nid, &nid);
4291         lp = lnet_find_peer(&nid);
4292
4293         if (!lp) {
4294                 rc = -ENOENT;
4295                 goto out;
4296         }
4297
4298         size = sizeof(nid4) + sizeof(*lpni_info) + sizeof(*lpni_stats)
4299                 + sizeof(*lpni_msg_stats) + sizeof(*lpni_hstats);
4300         size *= lp->lp_nnis;
4301         if (size > cfg->prcfg_size) {
4302                 cfg->prcfg_size = size;
4303                 rc = -E2BIG;
4304                 goto out_lp_decref;
4305         }
4306
4307         cfg->prcfg_prim_nid = lnet_nid_to_nid4(&lp->lp_primary_nid);
4308         cfg->prcfg_mr = lnet_peer_is_multi_rail(lp);
4309         cfg->prcfg_cfg_nid = lnet_nid_to_nid4(&lp->lp_primary_nid);
4310         cfg->prcfg_count = lp->lp_nnis;
4311         cfg->prcfg_size = size;
4312         cfg->prcfg_state = lp->lp_state;
4313
4314         /* Allocate helper buffers. */
4315         rc = -ENOMEM;
4316         LIBCFS_ALLOC(lpni_info, sizeof(*lpni_info));
4317         if (!lpni_info)
4318                 goto out_lp_decref;
4319         LIBCFS_ALLOC(lpni_stats, sizeof(*lpni_stats));
4320         if (!lpni_stats)
4321                 goto out_free_info;
4322         LIBCFS_ALLOC(lpni_msg_stats, sizeof(*lpni_msg_stats));
4323         if (!lpni_msg_stats)
4324                 goto out_free_stats;
4325         LIBCFS_ALLOC(lpni_hstats, sizeof(*lpni_hstats));
4326         if (!lpni_hstats)
4327                 goto out_free_msg_stats;
4328
4329
4330         lpni = NULL;
4331         rc = -EFAULT;
4332         while ((lpni = lnet_get_next_peer_ni_locked(lp, NULL, lpni)) != NULL) {
4333                 if (!nid_is_nid4(&lpni->lpni_nid))
4334                         continue;
4335                 nid4 = lnet_nid_to_nid4(&lpni->lpni_nid);
4336                 if (copy_to_user(bulk, &nid4, sizeof(nid4)))
4337                         goto out_free_hstats;
4338                 bulk += sizeof(nid4);
4339
4340                 memset(lpni_info, 0, sizeof(*lpni_info));
4341                 snprintf(lpni_info->cr_aliveness, LNET_MAX_STR_LEN, "NA");
4342                 if (lnet_isrouter(lpni) ||
4343                         lnet_peer_aliveness_enabled(lpni))
4344                         snprintf(lpni_info->cr_aliveness, LNET_MAX_STR_LEN,
4345                                 lnet_is_peer_ni_alive(lpni) ? "up" : "down");
4346
4347                 lpni_info->cr_refcount = kref_read(&lpni->lpni_kref);
4348                 lpni_info->cr_ni_peer_tx_credits = (lpni->lpni_net != NULL) ?
4349                         lpni->lpni_net->net_tunables.lct_peer_tx_credits : 0;
4350                 lpni_info->cr_peer_tx_credits = lpni->lpni_txcredits;
4351                 lpni_info->cr_peer_rtr_credits = lpni->lpni_rtrcredits;
4352                 lpni_info->cr_peer_min_rtr_credits = lpni->lpni_minrtrcredits;
4353                 lpni_info->cr_peer_min_tx_credits = lpni->lpni_mintxcredits;
4354                 lpni_info->cr_peer_tx_qnob = lpni->lpni_txqnob;
4355                 if (copy_to_user(bulk, lpni_info, sizeof(*lpni_info)))
4356                         goto out_free_hstats;
4357                 bulk += sizeof(*lpni_info);
4358
4359                 memset(lpni_stats, 0, sizeof(*lpni_stats));
4360                 lpni_stats->iel_send_count = lnet_sum_stats(&lpni->lpni_stats,
4361                                                             LNET_STATS_TYPE_SEND);
4362                 lpni_stats->iel_recv_count = lnet_sum_stats(&lpni->lpni_stats,
4363                                                             LNET_STATS_TYPE_RECV);
4364                 lpni_stats->iel_drop_count = lnet_sum_stats(&lpni->lpni_stats,
4365                                                             LNET_STATS_TYPE_DROP);
4366                 if (copy_to_user(bulk, lpni_stats, sizeof(*lpni_stats)))
4367                         goto out_free_hstats;
4368                 bulk += sizeof(*lpni_stats);
4369                 lnet_usr_translate_stats(lpni_msg_stats, &lpni->lpni_stats);
4370                 if (copy_to_user(bulk, lpni_msg_stats, sizeof(*lpni_msg_stats)))
4371                         goto out_free_hstats;
4372                 bulk += sizeof(*lpni_msg_stats);
4373                 lpni_hstats->hlpni_network_timeout =
4374                   atomic_read(&lpni->lpni_hstats.hlt_network_timeout);
4375                 lpni_hstats->hlpni_remote_dropped =
4376                   atomic_read(&lpni->lpni_hstats.hlt_remote_dropped);
4377                 lpni_hstats->hlpni_remote_timeout =
4378                   atomic_read(&lpni->lpni_hstats.hlt_remote_timeout);
4379                 lpni_hstats->hlpni_remote_error =
4380                   atomic_read(&lpni->lpni_hstats.hlt_remote_error);
4381                 lpni_hstats->hlpni_health_value =
4382                   atomic_read(&lpni->lpni_healthv);
4383                 lpni_hstats->hlpni_ping_count = lpni->lpni_ping_count;
4384                 lpni_hstats->hlpni_next_ping = lpni->lpni_next_ping;
4385                 if (copy_to_user(bulk, lpni_hstats, sizeof(*lpni_hstats)))
4386                         goto out_free_hstats;
4387                 bulk += sizeof(*lpni_hstats);
4388         }
4389         rc = 0;
4390
4391 out_free_hstats:
4392         LIBCFS_FREE(lpni_hstats, sizeof(*lpni_hstats));
4393 out_free_msg_stats:
4394         LIBCFS_FREE(lpni_msg_stats, sizeof(*lpni_msg_stats));
4395 out_free_stats:
4396         LIBCFS_FREE(lpni_stats, sizeof(*lpni_stats));
4397 out_free_info:
4398         LIBCFS_FREE(lpni_info, sizeof(*lpni_info));
4399 out_lp_decref:
4400         lnet_peer_decref_locked(lp);
4401 out:
4402         return rc;
4403 }
4404
4405 /* must hold net_lock/0 */
4406 void
4407 lnet_peer_ni_add_to_recoveryq_locked(struct lnet_peer_ni *lpni,
4408                                      struct list_head *recovery_queue,
4409                                      time64_t now)
4410 {
4411         /* the mt could've shutdown and cleaned up the queues */
4412         if (the_lnet.ln_mt_state != LNET_MT_STATE_RUNNING)
4413                 return;
4414
4415         if (!list_empty(&lpni->lpni_recovery))
4416                 return;
4417
4418         if (atomic_read(&lpni->lpni_healthv) == LNET_MAX_HEALTH_VALUE)
4419                 return;
4420
4421         if (!lpni->lpni_last_alive) {
4422                 CDEBUG(D_NET,
4423                        "lpni %s(%p) not eligible for recovery last alive %lld\n",
4424                        libcfs_nidstr(&lpni->lpni_nid), lpni,
4425                        lpni->lpni_last_alive);
4426                 return;
4427         }
4428
4429         if (lnet_recovery_limit &&
4430             now > lpni->lpni_last_alive + lnet_recovery_limit) {
4431                 CDEBUG(D_NET, "lpni %s aged out last alive %lld\n",
4432                        libcfs_nidstr(&lpni->lpni_nid),
4433                        lpni->lpni_last_alive);
4434                 /* Reset the ping count so that if this peer NI is added back to
4435                  * the recovery queue we will send the first ping right away.
4436                  */
4437                 lpni->lpni_ping_count = 0;
4438                 return;
4439         }
4440
4441         /* This peer NI is going on the recovery queue, so take a ref on it */
4442         lnet_peer_ni_addref_locked(lpni);
4443
4444         lnet_peer_ni_set_next_ping(lpni, now);
4445
4446         CDEBUG(D_NET, "%s added to recovery queue. ping count: %u next ping: %lld last alive: %lld health: %d\n",
4447                libcfs_nidstr(&lpni->lpni_nid),
4448                lpni->lpni_ping_count,
4449                lpni->lpni_next_ping,
4450                lpni->lpni_last_alive,
4451                atomic_read(&lpni->lpni_healthv));
4452
4453         list_add_tail(&lpni->lpni_recovery, recovery_queue);
4454 }
4455
4456 /* Call with the ln_api_mutex held */
4457 void
4458 lnet_peer_ni_set_healthv(lnet_nid_t nid4, int value, bool all)
4459 {
4460         struct lnet_peer_table *ptable;
4461         struct lnet_peer *lp;
4462         struct lnet_peer_net *lpn;
4463         struct lnet_peer_ni *lpni;
4464         struct lnet_nid nid;
4465         int lncpt;
4466         int cpt;
4467         time64_t now;
4468
4469         if (the_lnet.ln_state != LNET_STATE_RUNNING)
4470                 return;
4471
4472         lnet_nid4_to_nid(nid4, &nid);
4473         now = ktime_get_seconds();
4474
4475         if (!all) {
4476                 lnet_net_lock(LNET_LOCK_EX);
4477                 lpni = lnet_peer_ni_find_locked(&nid);
4478                 if (!lpni) {
4479                         lnet_net_unlock(LNET_LOCK_EX);
4480                         return;
4481                 }
4482                 lnet_set_lpni_healthv_locked(lpni, value);
4483                 lnet_peer_ni_add_to_recoveryq_locked(lpni,
4484                                              &the_lnet.ln_mt_peerNIRecovq, now);
4485                 lnet_peer_ni_decref_locked(lpni);
4486                 lnet_net_unlock(LNET_LOCK_EX);
4487                 return;
4488         }
4489
4490         lncpt = cfs_percpt_number(the_lnet.ln_peer_tables);
4491
4492         /*
4493          * Walk all the peers and reset the health value for each one to the
4494          * specified value.
4495          */
4496         lnet_net_lock(LNET_LOCK_EX);
4497         for (cpt = 0; cpt < lncpt; cpt++) {
4498                 ptable = the_lnet.ln_peer_tables[cpt];
4499                 list_for_each_entry(lp, &ptable->pt_peer_list, lp_peer_list) {
4500                         list_for_each_entry(lpn, &lp->lp_peer_nets, lpn_peer_nets) {
4501                                 list_for_each_entry(lpni, &lpn->lpn_peer_nis,
4502                                                     lpni_peer_nis) {
4503                                         lnet_set_lpni_healthv_locked(lpni,
4504                                                                      value);
4505                                         lnet_peer_ni_add_to_recoveryq_locked(lpni,
4506                                              &the_lnet.ln_mt_peerNIRecovq, now);
4507                                 }
4508                         }
4509                 }
4510         }
4511         lnet_net_unlock(LNET_LOCK_EX);
4512 }
4513