Whamcloud - gitweb
8ef55e769f110dae3ddff2b42f7fd1a0d259604f
[fs/lustre-release.git] / lnet / lnet / lib-move.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) 2003, 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  * Lustre is a trademark of Sun Microsystems, Inc.
31  *
32  * lnet/lnet/lib-move.c
33  *
34  * Data movement routines
35  */
36
37 #define DEBUG_SUBSYSTEM S_LNET
38
39 #include <linux/pagemap.h>
40
41 #include <lnet/lib-lnet.h>
42 #include <linux/nsproxy.h>
43 #include <net/net_namespace.h>
44
45 static int local_nid_dist_zero = 1;
46 module_param(local_nid_dist_zero, int, 0444);
47 MODULE_PARM_DESC(local_nid_dist_zero, "Reserved");
48
49 struct lnet_send_data {
50         struct lnet_ni *sd_best_ni;
51         struct lnet_peer_ni *sd_best_lpni;
52         struct lnet_peer_ni *sd_final_dst_lpni;
53         struct lnet_peer *sd_peer;
54         struct lnet_peer *sd_gw_peer;
55         struct lnet_peer_ni *sd_gw_lpni;
56         struct lnet_peer_net *sd_peer_net;
57         struct lnet_msg *sd_msg;
58         lnet_nid_t sd_dst_nid;
59         lnet_nid_t sd_src_nid;
60         lnet_nid_t sd_rtr_nid;
61         int sd_cpt;
62         int sd_md_cpt;
63         __u32 sd_send_case;
64 };
65
66 static inline bool
67 lnet_msg_is_response(struct lnet_msg *msg)
68 {
69         return msg->msg_type == LNET_MSG_ACK || msg->msg_type == LNET_MSG_REPLY;
70 }
71
72 static inline struct lnet_comm_count *
73 get_stats_counts(struct lnet_element_stats *stats,
74                  enum lnet_stats_type stats_type)
75 {
76         switch (stats_type) {
77         case LNET_STATS_TYPE_SEND:
78                 return &stats->el_send_stats;
79         case LNET_STATS_TYPE_RECV:
80                 return &stats->el_recv_stats;
81         case LNET_STATS_TYPE_DROP:
82                 return &stats->el_drop_stats;
83         default:
84                 CERROR("Unknown stats type\n");
85         }
86
87         return NULL;
88 }
89
90 void lnet_incr_stats(struct lnet_element_stats *stats,
91                      enum lnet_msg_type msg_type,
92                      enum lnet_stats_type stats_type)
93 {
94         struct lnet_comm_count *counts = get_stats_counts(stats, stats_type);
95         if (!counts)
96                 return;
97
98         switch (msg_type) {
99         case LNET_MSG_ACK:
100                 atomic_inc(&counts->co_ack_count);
101                 break;
102         case LNET_MSG_PUT:
103                 atomic_inc(&counts->co_put_count);
104                 break;
105         case LNET_MSG_GET:
106                 atomic_inc(&counts->co_get_count);
107                 break;
108         case LNET_MSG_REPLY:
109                 atomic_inc(&counts->co_reply_count);
110                 break;
111         case LNET_MSG_HELLO:
112                 atomic_inc(&counts->co_hello_count);
113                 break;
114         default:
115                 CERROR("There is a BUG in the code. Unknown message type\n");
116                 break;
117         }
118 }
119
120 __u32 lnet_sum_stats(struct lnet_element_stats *stats,
121                      enum lnet_stats_type stats_type)
122 {
123         struct lnet_comm_count *counts = get_stats_counts(stats, stats_type);
124         if (!counts)
125                 return 0;
126
127         return (atomic_read(&counts->co_ack_count) +
128                 atomic_read(&counts->co_put_count) +
129                 atomic_read(&counts->co_get_count) +
130                 atomic_read(&counts->co_reply_count) +
131                 atomic_read(&counts->co_hello_count));
132 }
133
134 static inline void assign_stats(struct lnet_ioctl_comm_count *msg_stats,
135                                 struct lnet_comm_count *counts)
136 {
137         msg_stats->ico_get_count = atomic_read(&counts->co_get_count);
138         msg_stats->ico_put_count = atomic_read(&counts->co_put_count);
139         msg_stats->ico_reply_count = atomic_read(&counts->co_reply_count);
140         msg_stats->ico_ack_count = atomic_read(&counts->co_ack_count);
141         msg_stats->ico_hello_count = atomic_read(&counts->co_hello_count);
142 }
143
144 void lnet_usr_translate_stats(struct lnet_ioctl_element_msg_stats *msg_stats,
145                               struct lnet_element_stats *stats)
146 {
147         struct lnet_comm_count *counts;
148
149         LASSERT(msg_stats);
150         LASSERT(stats);
151
152         counts = get_stats_counts(stats, LNET_STATS_TYPE_SEND);
153         if (!counts)
154                 return;
155         assign_stats(&msg_stats->im_send_stats, counts);
156
157         counts = get_stats_counts(stats, LNET_STATS_TYPE_RECV);
158         if (!counts)
159                 return;
160         assign_stats(&msg_stats->im_recv_stats, counts);
161
162         counts = get_stats_counts(stats, LNET_STATS_TYPE_DROP);
163         if (!counts)
164                 return;
165         assign_stats(&msg_stats->im_drop_stats, counts);
166 }
167
168 int
169 lnet_fail_nid(lnet_nid_t nid, unsigned int threshold)
170 {
171         struct lnet_test_peer *tp;
172         struct list_head *el;
173         struct list_head *next;
174         LIST_HEAD(cull);
175
176         /* NB: use lnet_net_lock(0) to serialize operations on test peers */
177         if (threshold != 0) {
178                 /* Adding a new entry */
179                 LIBCFS_ALLOC(tp, sizeof(*tp));
180                 if (tp == NULL)
181                         return -ENOMEM;
182
183                 tp->tp_nid = nid;
184                 tp->tp_threshold = threshold;
185
186                 lnet_net_lock(0);
187                 list_add_tail(&tp->tp_list, &the_lnet.ln_test_peers);
188                 lnet_net_unlock(0);
189                 return 0;
190         }
191
192         lnet_net_lock(0);
193
194         list_for_each_safe(el, next, &the_lnet.ln_test_peers) {
195                 tp = list_entry(el, struct lnet_test_peer, tp_list);
196
197                 if (tp->tp_threshold == 0 ||    /* needs culling anyway */
198                     nid == LNET_NID_ANY ||      /* removing all entries */
199                     tp->tp_nid == nid) {        /* matched this one */
200                         list_move(&tp->tp_list, &cull);
201                 }
202         }
203
204         lnet_net_unlock(0);
205
206         while (!list_empty(&cull)) {
207                 tp = list_entry(cull.next, struct lnet_test_peer, tp_list);
208
209                 list_del(&tp->tp_list);
210                 LIBCFS_FREE(tp, sizeof(*tp));
211         }
212         return 0;
213 }
214
215 static int
216 fail_peer (lnet_nid_t nid, int outgoing)
217 {
218         struct lnet_test_peer *tp;
219         struct list_head *el;
220         struct list_head *next;
221         LIST_HEAD(cull);
222         int fail = 0;
223
224         /* NB: use lnet_net_lock(0) to serialize operations on test peers */
225         lnet_net_lock(0);
226
227         list_for_each_safe(el, next, &the_lnet.ln_test_peers) {
228                 tp = list_entry(el, struct lnet_test_peer, tp_list);
229
230                 if (tp->tp_threshold == 0) {
231                         /* zombie entry */
232                         if (outgoing) {
233                                 /* only cull zombies on outgoing tests,
234                                  * since we may be at interrupt priority on
235                                  * incoming messages. */
236                                 list_move(&tp->tp_list, &cull);
237                         }
238                         continue;
239                 }
240
241                 if (tp->tp_nid == LNET_NID_ANY ||       /* fail every peer */
242                     nid == tp->tp_nid) {                /* fail this peer */
243                         fail = 1;
244
245                         if (tp->tp_threshold != LNET_MD_THRESH_INF) {
246                                 tp->tp_threshold--;
247                                 if (outgoing &&
248                                     tp->tp_threshold == 0) {
249                                         /* see above */
250                                         list_move(&tp->tp_list, &cull);
251                                 }
252                         }
253                         break;
254                 }
255         }
256
257         lnet_net_unlock(0);
258
259         while (!list_empty(&cull)) {
260                 tp = list_entry(cull.next, struct lnet_test_peer, tp_list);
261                 list_del(&tp->tp_list);
262
263                 LIBCFS_FREE(tp, sizeof(*tp));
264         }
265
266         return fail;
267 }
268
269 unsigned int
270 lnet_iov_nob(unsigned int niov, struct kvec *iov)
271 {
272         unsigned int nob = 0;
273
274         LASSERT(niov == 0 || iov != NULL);
275         while (niov-- > 0)
276                 nob += (iov++)->iov_len;
277
278         return (nob);
279 }
280 EXPORT_SYMBOL(lnet_iov_nob);
281
282 void
283 lnet_copy_iov2iov(unsigned int ndiov, struct kvec *diov, unsigned int doffset,
284                   unsigned int nsiov, struct kvec *siov, unsigned int soffset,
285                   unsigned int nob)
286 {
287         /* NB diov, siov are READ-ONLY */
288         unsigned int this_nob;
289
290         if (nob == 0)
291                 return;
292
293         /* skip complete frags before 'doffset' */
294         LASSERT(ndiov > 0);
295         while (doffset >= diov->iov_len) {
296                 doffset -= diov->iov_len;
297                 diov++;
298                 ndiov--;
299                 LASSERT(ndiov > 0);
300         }
301
302         /* skip complete frags before 'soffset' */
303         LASSERT(nsiov > 0);
304         while (soffset >= siov->iov_len) {
305                 soffset -= siov->iov_len;
306                 siov++;
307                 nsiov--;
308                 LASSERT(nsiov > 0);
309         }
310
311         do {
312                 LASSERT(ndiov > 0);
313                 LASSERT(nsiov > 0);
314                 this_nob = min3((unsigned int)diov->iov_len - doffset,
315                                 (unsigned int)siov->iov_len - soffset,
316                                 nob);
317
318                 memcpy((char *)diov->iov_base + doffset,
319                        (char *)siov->iov_base + soffset, this_nob);
320                 nob -= this_nob;
321
322                 if (diov->iov_len > doffset + this_nob) {
323                         doffset += this_nob;
324                 } else {
325                         diov++;
326                         ndiov--;
327                         doffset = 0;
328                 }
329
330                 if (siov->iov_len > soffset + this_nob) {
331                         soffset += this_nob;
332                 } else {
333                         siov++;
334                         nsiov--;
335                         soffset = 0;
336                 }
337         } while (nob > 0);
338 }
339 EXPORT_SYMBOL(lnet_copy_iov2iov);
340
341 unsigned int
342 lnet_kiov_nob(unsigned int niov, struct bio_vec *kiov)
343 {
344         unsigned int  nob = 0;
345
346         LASSERT(niov == 0 || kiov != NULL);
347         while (niov-- > 0)
348                 nob += (kiov++)->bv_len;
349
350         return (nob);
351 }
352 EXPORT_SYMBOL(lnet_kiov_nob);
353
354 void
355 lnet_copy_kiov2kiov(unsigned int ndiov, struct bio_vec *diov,
356                     unsigned int doffset,
357                     unsigned int nsiov, struct bio_vec *siov,
358                     unsigned int soffset,
359                     unsigned int nob)
360 {
361         /* NB diov, siov are READ-ONLY */
362         unsigned int    this_nob;
363         char           *daddr = NULL;
364         char           *saddr = NULL;
365
366         if (nob == 0)
367                 return;
368
369         LASSERT (!in_interrupt ());
370
371         LASSERT (ndiov > 0);
372         while (doffset >= diov->bv_len) {
373                 doffset -= diov->bv_len;
374                 diov++;
375                 ndiov--;
376                 LASSERT(ndiov > 0);
377         }
378
379         LASSERT(nsiov > 0);
380         while (soffset >= siov->bv_len) {
381                 soffset -= siov->bv_len;
382                 siov++;
383                 nsiov--;
384                 LASSERT(nsiov > 0);
385         }
386
387         do {
388                 LASSERT(ndiov > 0);
389                 LASSERT(nsiov > 0);
390                 this_nob = min3(diov->bv_len - doffset,
391                                 siov->bv_len - soffset,
392                                 nob);
393
394                 if (daddr == NULL)
395                         daddr = ((char *)kmap(diov->bv_page)) +
396                                 diov->bv_offset + doffset;
397                 if (saddr == NULL)
398                         saddr = ((char *)kmap(siov->bv_page)) +
399                                 siov->bv_offset + soffset;
400
401                 /* Vanishing risk of kmap deadlock when mapping 2 pages.
402                  * However in practice at least one of the kiovs will be mapped
403                  * kernel pages and the map/unmap will be NOOPs */
404
405                 memcpy (daddr, saddr, this_nob);
406                 nob -= this_nob;
407
408                 if (diov->bv_len > doffset + this_nob) {
409                         daddr += this_nob;
410                         doffset += this_nob;
411                 } else {
412                         kunmap(diov->bv_page);
413                         daddr = NULL;
414                         diov++;
415                         ndiov--;
416                         doffset = 0;
417                 }
418
419                 if (siov->bv_len > soffset + this_nob) {
420                         saddr += this_nob;
421                         soffset += this_nob;
422                 } else {
423                         kunmap(siov->bv_page);
424                         saddr = NULL;
425                         siov++;
426                         nsiov--;
427                         soffset = 0;
428                 }
429         } while (nob > 0);
430
431         if (daddr != NULL)
432                 kunmap(diov->bv_page);
433         if (saddr != NULL)
434                 kunmap(siov->bv_page);
435 }
436 EXPORT_SYMBOL(lnet_copy_kiov2kiov);
437
438 void
439 lnet_copy_kiov2iov (unsigned int niov, struct kvec *iov, unsigned int iovoffset,
440                     unsigned int nkiov, struct bio_vec *kiov,
441                     unsigned int kiovoffset,
442                     unsigned int nob)
443 {
444         /* NB iov, kiov are READ-ONLY */
445         unsigned int    this_nob;
446         char           *addr = NULL;
447
448         if (nob == 0)
449                 return;
450
451         LASSERT (!in_interrupt ());
452
453         LASSERT (niov > 0);
454         while (iovoffset >= iov->iov_len) {
455                 iovoffset -= iov->iov_len;
456                 iov++;
457                 niov--;
458                 LASSERT(niov > 0);
459         }
460
461         LASSERT(nkiov > 0);
462         while (kiovoffset >= kiov->bv_len) {
463                 kiovoffset -= kiov->bv_len;
464                 kiov++;
465                 nkiov--;
466                 LASSERT(nkiov > 0);
467         }
468
469         do {
470                 LASSERT(niov > 0);
471                 LASSERT(nkiov > 0);
472                 this_nob = min3((unsigned int)iov->iov_len - iovoffset,
473                                 (unsigned int)kiov->bv_len - kiovoffset,
474                                 nob);
475
476                 if (addr == NULL)
477                         addr = ((char *)kmap(kiov->bv_page)) +
478                                 kiov->bv_offset + kiovoffset;
479
480                 memcpy((char *)iov->iov_base + iovoffset, addr, this_nob);
481                 nob -= this_nob;
482
483                 if (iov->iov_len > iovoffset + this_nob) {
484                         iovoffset += this_nob;
485                 } else {
486                         iov++;
487                         niov--;
488                         iovoffset = 0;
489                 }
490
491                 if (kiov->bv_len > kiovoffset + this_nob) {
492                         addr += this_nob;
493                         kiovoffset += this_nob;
494                 } else {
495                         kunmap(kiov->bv_page);
496                         addr = NULL;
497                         kiov++;
498                         nkiov--;
499                         kiovoffset = 0;
500                 }
501
502         } while (nob > 0);
503
504         if (addr != NULL)
505                 kunmap(kiov->bv_page);
506 }
507 EXPORT_SYMBOL(lnet_copy_kiov2iov);
508
509 void
510 lnet_copy_iov2kiov(unsigned int nkiov, struct bio_vec *kiov,
511                    unsigned int kiovoffset,
512                    unsigned int niov, struct kvec *iov, unsigned int iovoffset,
513                    unsigned int nob)
514 {
515         /* NB kiov, iov are READ-ONLY */
516         unsigned int    this_nob;
517         char           *addr = NULL;
518
519         if (nob == 0)
520                 return;
521
522         LASSERT (!in_interrupt ());
523
524         LASSERT (nkiov > 0);
525         while (kiovoffset >= kiov->bv_len) {
526                 kiovoffset -= kiov->bv_len;
527                 kiov++;
528                 nkiov--;
529                 LASSERT(nkiov > 0);
530         }
531
532         LASSERT(niov > 0);
533         while (iovoffset >= iov->iov_len) {
534                 iovoffset -= iov->iov_len;
535                 iov++;
536                 niov--;
537                 LASSERT(niov > 0);
538         }
539
540         do {
541                 LASSERT(nkiov > 0);
542                 LASSERT(niov > 0);
543                 this_nob = min3((unsigned int)kiov->bv_len - kiovoffset,
544                                 (unsigned int)iov->iov_len - iovoffset,
545                                 nob);
546
547                 if (addr == NULL)
548                         addr = ((char *)kmap(kiov->bv_page)) +
549                                 kiov->bv_offset + kiovoffset;
550
551                 memcpy (addr, (char *)iov->iov_base + iovoffset, this_nob);
552                 nob -= this_nob;
553
554                 if (kiov->bv_len > kiovoffset + this_nob) {
555                         addr += this_nob;
556                         kiovoffset += this_nob;
557                 } else {
558                         kunmap(kiov->bv_page);
559                         addr = NULL;
560                         kiov++;
561                         nkiov--;
562                         kiovoffset = 0;
563                 }
564
565                 if (iov->iov_len > iovoffset + this_nob) {
566                         iovoffset += this_nob;
567                 } else {
568                         iov++;
569                         niov--;
570                         iovoffset = 0;
571                 }
572         } while (nob > 0);
573
574         if (addr != NULL)
575                 kunmap(kiov->bv_page);
576 }
577 EXPORT_SYMBOL(lnet_copy_iov2kiov);
578
579 int
580 lnet_extract_kiov(int dst_niov, struct bio_vec *dst,
581                   int src_niov, struct bio_vec *src,
582                   unsigned int offset, unsigned int len)
583 {
584         /* Initialise 'dst' to the subset of 'src' starting at 'offset',
585          * for exactly 'len' bytes, and return the number of entries.
586          * NB not destructive to 'src' */
587         unsigned int    frag_len;
588         unsigned int    niov;
589
590         if (len == 0)                           /* no data => */
591                 return (0);                     /* no frags */
592
593         LASSERT(src_niov > 0);
594         while (offset >= src->bv_len) {      /* skip initial frags */
595                 offset -= src->bv_len;
596                 src_niov--;
597                 src++;
598                 LASSERT(src_niov > 0);
599         }
600
601         niov = 1;
602         for (;;) {
603                 LASSERT(src_niov > 0);
604                 LASSERT((int)niov <= dst_niov);
605
606                 frag_len = src->bv_len - offset;
607                 dst->bv_page = src->bv_page;
608                 dst->bv_offset = src->bv_offset + offset;
609
610                 if (len <= frag_len) {
611                         dst->bv_len = len;
612                         LASSERT(dst->bv_offset + dst->bv_len <= PAGE_SIZE);
613                         return niov;
614                 }
615
616                 dst->bv_len = frag_len;
617                 LASSERT(dst->bv_offset + dst->bv_len <= PAGE_SIZE);
618
619                 len -= frag_len;
620                 dst++;
621                 src++;
622                 niov++;
623                 src_niov--;
624                 offset = 0;
625         }
626 }
627 EXPORT_SYMBOL(lnet_extract_kiov);
628
629 void
630 lnet_ni_recv(struct lnet_ni *ni, void *private, struct lnet_msg *msg,
631              int delayed, unsigned int offset, unsigned int mlen,
632              unsigned int rlen)
633 {
634         unsigned int niov = 0;
635         struct kvec *iov = NULL;
636         struct bio_vec  *kiov = NULL;
637         int rc;
638
639         LASSERT (!in_interrupt ());
640         LASSERT (mlen == 0 || msg != NULL);
641
642         if (msg != NULL) {
643                 LASSERT(msg->msg_receiving);
644                 LASSERT(!msg->msg_sending);
645                 LASSERT(rlen == msg->msg_len);
646                 LASSERT(mlen <= msg->msg_len);
647                 LASSERT(msg->msg_offset == offset);
648                 LASSERT(msg->msg_wanted == mlen);
649
650                 msg->msg_receiving = 0;
651
652                 if (mlen != 0) {
653                         niov = msg->msg_niov;
654                         kiov = msg->msg_kiov;
655
656                         LASSERT (niov > 0);
657                         LASSERT ((iov == NULL) != (kiov == NULL));
658                 }
659         }
660
661         rc = (ni->ni_net->net_lnd->lnd_recv)(ni, private, msg, delayed,
662                                              niov, kiov, offset, mlen,
663                                              rlen);
664         if (rc < 0)
665                 lnet_finalize(msg, rc);
666 }
667
668 static void
669 lnet_setpayloadbuffer(struct lnet_msg *msg)
670 {
671         struct lnet_libmd *md = msg->msg_md;
672
673         LASSERT(msg->msg_len > 0);
674         LASSERT(!msg->msg_routing);
675         LASSERT(md != NULL);
676         LASSERT(msg->msg_niov == 0);
677         LASSERT(msg->msg_kiov == NULL);
678
679         msg->msg_niov = md->md_niov;
680         msg->msg_kiov = md->md_kiov;
681 }
682
683 void
684 lnet_prep_send(struct lnet_msg *msg, int type, struct lnet_process_id target,
685                unsigned int offset, unsigned int len)
686 {
687         msg->msg_type = type;
688         msg->msg_target = target;
689         msg->msg_len = len;
690         msg->msg_offset = offset;
691
692         if (len != 0)
693                 lnet_setpayloadbuffer(msg);
694
695         memset (&msg->msg_hdr, 0, sizeof (msg->msg_hdr));
696         msg->msg_hdr.type           = cpu_to_le32(type);
697         /* dest_nid will be overwritten by lnet_select_pathway() */
698         msg->msg_hdr.dest_nid       = cpu_to_le64(target.nid);
699         msg->msg_hdr.dest_pid       = cpu_to_le32(target.pid);
700         /* src_nid will be set later */
701         msg->msg_hdr.src_pid        = cpu_to_le32(the_lnet.ln_pid);
702         msg->msg_hdr.payload_length = cpu_to_le32(len);
703 }
704
705 static void
706 lnet_ni_send(struct lnet_ni *ni, struct lnet_msg *msg)
707 {
708         void *priv = msg->msg_private;
709         int rc;
710
711         LASSERT(!in_interrupt());
712         LASSERT(ni->ni_nid == LNET_NID_LO_0 ||
713                 (msg->msg_txcredit && msg->msg_peertxcredit));
714
715         rc = (ni->ni_net->net_lnd->lnd_send)(ni, priv, msg);
716         if (rc < 0) {
717                 msg->msg_no_resend = true;
718                 lnet_finalize(msg, rc);
719         }
720 }
721
722 static int
723 lnet_ni_eager_recv(struct lnet_ni *ni, struct lnet_msg *msg)
724 {
725         int     rc;
726
727         LASSERT(!msg->msg_sending);
728         LASSERT(msg->msg_receiving);
729         LASSERT(!msg->msg_rx_ready_delay);
730         LASSERT(ni->ni_net->net_lnd->lnd_eager_recv != NULL);
731
732         msg->msg_rx_ready_delay = 1;
733         rc = (ni->ni_net->net_lnd->lnd_eager_recv)(ni, msg->msg_private, msg,
734                                                   &msg->msg_private);
735         if (rc != 0) {
736                 CERROR("recv from %s / send to %s aborted: "
737                        "eager_recv failed %d\n",
738                        libcfs_nid2str(msg->msg_rxpeer->lpni_nid),
739                        libcfs_id2str(msg->msg_target), rc);
740                 LASSERT(rc < 0); /* required by my callers */
741         }
742
743         return rc;
744 }
745
746 static bool
747 lnet_is_peer_deadline_passed(struct lnet_peer_ni *lpni, time64_t now)
748 {
749         time64_t deadline;
750
751         deadline = lpni->lpni_last_alive +
752                    lpni->lpni_net->net_tunables.lct_peer_timeout;
753
754         /*
755          * assume peer_ni is alive as long as we're within the configured
756          * peer timeout
757          */
758         if (deadline > now)
759                 return false;
760
761         return true;
762 }
763
764 /* NB: returns 1 when alive, 0 when dead, negative when error;
765  *     may drop the lnet_net_lock */
766 static int
767 lnet_peer_alive_locked(struct lnet_ni *ni, struct lnet_peer_ni *lpni,
768                        struct lnet_msg *msg)
769 {
770         time64_t now = ktime_get_seconds();
771
772         if (!lnet_peer_aliveness_enabled(lpni))
773                 return -ENODEV;
774
775         /*
776          * If we're resending a message, let's attempt to send it even if
777          * the peer is down to fulfill our resend quota on the message
778          */
779         if (msg->msg_retry_count > 0)
780                 return 1;
781
782         /* try and send recovery messages irregardless */
783         if (msg->msg_recovery)
784                 return 1;
785
786         /* always send any responses */
787         if (lnet_msg_is_response(msg))
788                 return 1;
789
790         if (!lnet_is_peer_deadline_passed(lpni, now))
791                 return true;
792
793         return lnet_is_peer_ni_alive(lpni);
794 }
795
796 /**
797  * \param msg The message to be sent.
798  * \param do_send True if lnet_ni_send() should be called in this function.
799  *        lnet_send() is going to lnet_net_unlock immediately after this, so
800  *        it sets do_send FALSE and I don't do the unlock/send/lock bit.
801  *
802  * \retval LNET_CREDIT_OK If \a msg sent or OK to send.
803  * \retval LNET_CREDIT_WAIT If \a msg blocked for credit.
804  * \retval -EHOSTUNREACH If the next hop of the message appears dead.
805  * \retval -ECANCELED If the MD of the message has been unlinked.
806  */
807 static int
808 lnet_post_send_locked(struct lnet_msg *msg, int do_send)
809 {
810         struct lnet_peer_ni     *lp = msg->msg_txpeer;
811         struct lnet_ni          *ni = msg->msg_txni;
812         int                     cpt = msg->msg_tx_cpt;
813         struct lnet_tx_queue    *tq = ni->ni_tx_queues[cpt];
814
815         /* non-lnet_send() callers have checked before */
816         LASSERT(!do_send || msg->msg_tx_delayed);
817         LASSERT(!msg->msg_receiving);
818         LASSERT(msg->msg_tx_committed);
819         /* can't get here if we're sending to the loopback interface */
820         LASSERT(lp->lpni_nid != the_lnet.ln_loni->ni_nid);
821
822         /* NB 'lp' is always the next hop */
823         if ((msg->msg_target.pid & LNET_PID_USERFLAG) == 0 &&
824             lnet_peer_alive_locked(ni, lp, msg) == 0) {
825                 the_lnet.ln_counters[cpt]->lct_common.lcc_drop_count++;
826                 the_lnet.ln_counters[cpt]->lct_common.lcc_drop_length +=
827                         msg->msg_len;
828                 lnet_net_unlock(cpt);
829                 if (msg->msg_txpeer)
830                         lnet_incr_stats(&msg->msg_txpeer->lpni_stats,
831                                         msg->msg_type,
832                                         LNET_STATS_TYPE_DROP);
833                 if (msg->msg_txni)
834                         lnet_incr_stats(&msg->msg_txni->ni_stats,
835                                         msg->msg_type,
836                                         LNET_STATS_TYPE_DROP);
837
838                 CNETERR("Dropping message for %s: peer not alive\n",
839                         libcfs_id2str(msg->msg_target));
840                 msg->msg_health_status = LNET_MSG_STATUS_REMOTE_DROPPED;
841                 if (do_send)
842                         lnet_finalize(msg, -EHOSTUNREACH);
843
844                 lnet_net_lock(cpt);
845                 return -EHOSTUNREACH;
846         }
847
848         if (msg->msg_md != NULL &&
849             (msg->msg_md->md_flags & LNET_MD_FLAG_ABORTED) != 0) {
850                 lnet_net_unlock(cpt);
851
852                 CNETERR("Aborting message for %s: LNetM[DE]Unlink() already "
853                         "called on the MD/ME.\n",
854                         libcfs_id2str(msg->msg_target));
855                 if (do_send) {
856                         msg->msg_no_resend = true;
857                         CDEBUG(D_NET, "msg %p to %s canceled and will not be resent\n",
858                                msg, libcfs_id2str(msg->msg_target));
859                         lnet_finalize(msg, -ECANCELED);
860                 }
861
862                 lnet_net_lock(cpt);
863                 return -ECANCELED;
864         }
865
866         if (!msg->msg_peertxcredit) {
867                 spin_lock(&lp->lpni_lock);
868                 LASSERT((lp->lpni_txcredits < 0) ==
869                         !list_empty(&lp->lpni_txq));
870
871                 msg->msg_peertxcredit = 1;
872                 lp->lpni_txqnob += msg->msg_len + sizeof(struct lnet_hdr);
873                 lp->lpni_txcredits--;
874
875                 if (lp->lpni_txcredits < lp->lpni_mintxcredits)
876                         lp->lpni_mintxcredits = lp->lpni_txcredits;
877
878                 if (lp->lpni_txcredits < 0) {
879                         msg->msg_tx_delayed = 1;
880                         list_add_tail(&msg->msg_list, &lp->lpni_txq);
881                         spin_unlock(&lp->lpni_lock);
882                         return LNET_CREDIT_WAIT;
883                 }
884                 spin_unlock(&lp->lpni_lock);
885         }
886
887         if (!msg->msg_txcredit) {
888                 LASSERT((tq->tq_credits < 0) ==
889                         !list_empty(&tq->tq_delayed));
890
891                 msg->msg_txcredit = 1;
892                 tq->tq_credits--;
893                 atomic_dec(&ni->ni_tx_credits);
894
895                 if (tq->tq_credits < tq->tq_credits_min)
896                         tq->tq_credits_min = tq->tq_credits;
897
898                 if (tq->tq_credits < 0) {
899                         msg->msg_tx_delayed = 1;
900                         list_add_tail(&msg->msg_list, &tq->tq_delayed);
901                         return LNET_CREDIT_WAIT;
902                 }
903         }
904
905         /* unset the tx_delay flag as we're going to send it now */
906         msg->msg_tx_delayed = 0;
907
908         if (do_send) {
909                 lnet_net_unlock(cpt);
910                 lnet_ni_send(ni, msg);
911                 lnet_net_lock(cpt);
912         }
913         return LNET_CREDIT_OK;
914 }
915
916
917 static struct lnet_rtrbufpool *
918 lnet_msg2bufpool(struct lnet_msg *msg)
919 {
920         struct lnet_rtrbufpool  *rbp;
921         int                     cpt;
922
923         LASSERT(msg->msg_rx_committed);
924
925         cpt = msg->msg_rx_cpt;
926         rbp = &the_lnet.ln_rtrpools[cpt][0];
927
928         LASSERT(msg->msg_len <= LNET_MTU);
929         while (msg->msg_len > (unsigned int)rbp->rbp_npages * PAGE_SIZE) {
930                 rbp++;
931                 LASSERT(rbp < &the_lnet.ln_rtrpools[cpt][LNET_NRBPOOLS]);
932         }
933
934         return rbp;
935 }
936
937 static int
938 lnet_post_routed_recv_locked(struct lnet_msg *msg, int do_recv)
939 {
940         /* lnet_parse is going to lnet_net_unlock immediately after this, so it
941          * sets do_recv FALSE and I don't do the unlock/send/lock bit.
942          * I return LNET_CREDIT_WAIT if msg blocked and LNET_CREDIT_OK if
943          * received or OK to receive */
944         struct lnet_peer_ni *lpni = msg->msg_rxpeer;
945         struct lnet_peer *lp;
946         struct lnet_rtrbufpool *rbp;
947         struct lnet_rtrbuf *rb;
948
949         LASSERT(msg->msg_kiov == NULL);
950         LASSERT(msg->msg_niov == 0);
951         LASSERT(msg->msg_routing);
952         LASSERT(msg->msg_receiving);
953         LASSERT(!msg->msg_sending);
954         LASSERT(lpni->lpni_peer_net);
955         LASSERT(lpni->lpni_peer_net->lpn_peer);
956
957         lp = lpni->lpni_peer_net->lpn_peer;
958
959         /* non-lnet_parse callers only receive delayed messages */
960         LASSERT(!do_recv || msg->msg_rx_delayed);
961
962         if (!msg->msg_peerrtrcredit) {
963                 /* lpni_lock protects the credit manipulation */
964                 spin_lock(&lpni->lpni_lock);
965
966                 msg->msg_peerrtrcredit = 1;
967                 lpni->lpni_rtrcredits--;
968                 if (lpni->lpni_rtrcredits < lpni->lpni_minrtrcredits)
969                         lpni->lpni_minrtrcredits = lpni->lpni_rtrcredits;
970
971                 if (lpni->lpni_rtrcredits < 0) {
972                         spin_unlock(&lpni->lpni_lock);
973                         /* must have checked eager_recv before here */
974                         LASSERT(msg->msg_rx_ready_delay);
975                         msg->msg_rx_delayed = 1;
976                         /* lp_lock protects the lp_rtrq */
977                         spin_lock(&lp->lp_lock);
978                         list_add_tail(&msg->msg_list, &lp->lp_rtrq);
979                         spin_unlock(&lp->lp_lock);
980                         return LNET_CREDIT_WAIT;
981                 }
982                 spin_unlock(&lpni->lpni_lock);
983         }
984
985         rbp = lnet_msg2bufpool(msg);
986
987         if (!msg->msg_rtrcredit) {
988                 msg->msg_rtrcredit = 1;
989                 rbp->rbp_credits--;
990                 if (rbp->rbp_credits < rbp->rbp_mincredits)
991                         rbp->rbp_mincredits = rbp->rbp_credits;
992
993                 if (rbp->rbp_credits < 0) {
994                         /* must have checked eager_recv before here */
995                         LASSERT(msg->msg_rx_ready_delay);
996                         msg->msg_rx_delayed = 1;
997                         list_add_tail(&msg->msg_list, &rbp->rbp_msgs);
998                         return LNET_CREDIT_WAIT;
999                 }
1000         }
1001
1002         LASSERT(!list_empty(&rbp->rbp_bufs));
1003         rb = list_entry(rbp->rbp_bufs.next, struct lnet_rtrbuf, rb_list);
1004         list_del(&rb->rb_list);
1005
1006         msg->msg_niov = rbp->rbp_npages;
1007         msg->msg_kiov = &rb->rb_kiov[0];
1008
1009         /* unset the msg-rx_delayed flag since we're receiving the message */
1010         msg->msg_rx_delayed = 0;
1011
1012         if (do_recv) {
1013                 int cpt = msg->msg_rx_cpt;
1014
1015                 lnet_net_unlock(cpt);
1016                 lnet_ni_recv(msg->msg_rxni, msg->msg_private, msg, 1,
1017                              0, msg->msg_len, msg->msg_len);
1018                 lnet_net_lock(cpt);
1019         }
1020         return LNET_CREDIT_OK;
1021 }
1022
1023 void
1024 lnet_return_tx_credits_locked(struct lnet_msg *msg)
1025 {
1026         struct lnet_peer_ni     *txpeer = msg->msg_txpeer;
1027         struct lnet_ni          *txni = msg->msg_txni;
1028         struct lnet_msg         *msg2;
1029
1030         if (msg->msg_txcredit) {
1031                 struct lnet_ni       *ni = msg->msg_txni;
1032                 struct lnet_tx_queue *tq = ni->ni_tx_queues[msg->msg_tx_cpt];
1033
1034                 /* give back NI txcredits */
1035                 msg->msg_txcredit = 0;
1036
1037                 LASSERT((tq->tq_credits < 0) ==
1038                         !list_empty(&tq->tq_delayed));
1039
1040                 tq->tq_credits++;
1041                 atomic_inc(&ni->ni_tx_credits);
1042                 if (tq->tq_credits <= 0) {
1043                         msg2 = list_entry(tq->tq_delayed.next,
1044                                           struct lnet_msg, msg_list);
1045                         list_del(&msg2->msg_list);
1046
1047                         LASSERT(msg2->msg_txni == ni);
1048                         LASSERT(msg2->msg_tx_delayed);
1049                         LASSERT(msg2->msg_tx_cpt == msg->msg_tx_cpt);
1050
1051                         (void) lnet_post_send_locked(msg2, 1);
1052                 }
1053         }
1054
1055         if (msg->msg_peertxcredit) {
1056                 /* give back peer txcredits */
1057                 msg->msg_peertxcredit = 0;
1058
1059                 spin_lock(&txpeer->lpni_lock);
1060                 LASSERT((txpeer->lpni_txcredits < 0) ==
1061                         !list_empty(&txpeer->lpni_txq));
1062
1063                 txpeer->lpni_txqnob -= msg->msg_len + sizeof(struct lnet_hdr);
1064                 LASSERT(txpeer->lpni_txqnob >= 0);
1065
1066                 txpeer->lpni_txcredits++;
1067                 if (txpeer->lpni_txcredits <= 0) {
1068                         int msg2_cpt;
1069
1070                         msg2 = list_entry(txpeer->lpni_txq.next,
1071                                               struct lnet_msg, msg_list);
1072                         list_del(&msg2->msg_list);
1073                         spin_unlock(&txpeer->lpni_lock);
1074
1075                         LASSERT(msg2->msg_txpeer == txpeer);
1076                         LASSERT(msg2->msg_tx_delayed);
1077
1078                         msg2_cpt = msg2->msg_tx_cpt;
1079
1080                         /*
1081                          * The msg_cpt can be different from the msg2_cpt
1082                          * so we need to make sure we lock the correct cpt
1083                          * for msg2.
1084                          * Once we call lnet_post_send_locked() it is no
1085                          * longer safe to access msg2, since it could've
1086                          * been freed by lnet_finalize(), but we still
1087                          * need to relock the correct cpt, so we cache the
1088                          * msg2_cpt for the purpose of the check that
1089                          * follows the call to lnet_pose_send_locked().
1090                          */
1091                         if (msg2_cpt != msg->msg_tx_cpt) {
1092                                 lnet_net_unlock(msg->msg_tx_cpt);
1093                                 lnet_net_lock(msg2_cpt);
1094                         }
1095                         (void) lnet_post_send_locked(msg2, 1);
1096                         if (msg2_cpt != msg->msg_tx_cpt) {
1097                                 lnet_net_unlock(msg2_cpt);
1098                                 lnet_net_lock(msg->msg_tx_cpt);
1099                         }
1100                 } else {
1101                         spin_unlock(&txpeer->lpni_lock);
1102                 }
1103         }
1104
1105         if (txni != NULL) {
1106                 msg->msg_txni = NULL;
1107                 lnet_ni_decref_locked(txni, msg->msg_tx_cpt);
1108         }
1109
1110         if (txpeer != NULL) {
1111                 msg->msg_txpeer = NULL;
1112                 lnet_peer_ni_decref_locked(txpeer);
1113         }
1114 }
1115
1116 void
1117 lnet_schedule_blocked_locked(struct lnet_rtrbufpool *rbp)
1118 {
1119         struct lnet_msg *msg;
1120
1121         if (list_empty(&rbp->rbp_msgs))
1122                 return;
1123         msg = list_entry(rbp->rbp_msgs.next,
1124                          struct lnet_msg, msg_list);
1125         list_del(&msg->msg_list);
1126
1127         (void)lnet_post_routed_recv_locked(msg, 1);
1128 }
1129
1130 void
1131 lnet_drop_routed_msgs_locked(struct list_head *list, int cpt)
1132 {
1133         struct lnet_msg *msg;
1134         struct lnet_msg *tmp;
1135
1136         lnet_net_unlock(cpt);
1137
1138         list_for_each_entry_safe(msg, tmp, list, msg_list) {
1139                 lnet_ni_recv(msg->msg_rxni, msg->msg_private, NULL,
1140                              0, 0, 0, msg->msg_hdr.payload_length);
1141                 list_del_init(&msg->msg_list);
1142                 msg->msg_no_resend = true;
1143                 msg->msg_health_status = LNET_MSG_STATUS_REMOTE_ERROR;
1144                 lnet_finalize(msg, -ECANCELED);
1145         }
1146
1147         lnet_net_lock(cpt);
1148 }
1149
1150 void
1151 lnet_return_rx_credits_locked(struct lnet_msg *msg)
1152 {
1153         struct lnet_peer_ni *rxpeerni = msg->msg_rxpeer;
1154         struct lnet_peer *lp;
1155         struct lnet_ni *rxni = msg->msg_rxni;
1156         struct lnet_msg *msg2;
1157
1158         if (msg->msg_rtrcredit) {
1159                 /* give back global router credits */
1160                 struct lnet_rtrbuf *rb;
1161                 struct lnet_rtrbufpool *rbp;
1162
1163                 /* NB If a msg ever blocks for a buffer in rbp_msgs, it stays
1164                  * there until it gets one allocated, or aborts the wait
1165                  * itself */
1166                 LASSERT(msg->msg_kiov != NULL);
1167
1168                 rb = list_entry(msg->msg_kiov, struct lnet_rtrbuf, rb_kiov[0]);
1169                 rbp = rb->rb_pool;
1170
1171                 msg->msg_kiov = NULL;
1172                 msg->msg_rtrcredit = 0;
1173
1174                 LASSERT(rbp == lnet_msg2bufpool(msg));
1175
1176                 LASSERT((rbp->rbp_credits > 0) ==
1177                         !list_empty(&rbp->rbp_bufs));
1178
1179                 /* If routing is now turned off, we just drop this buffer and
1180                  * don't bother trying to return credits.  */
1181                 if (!the_lnet.ln_routing) {
1182                         lnet_destroy_rtrbuf(rb, rbp->rbp_npages);
1183                         goto routing_off;
1184                 }
1185
1186                 /* It is possible that a user has lowered the desired number of
1187                  * buffers in this pool.  Make sure we never put back
1188                  * more buffers than the stated number. */
1189                 if (unlikely(rbp->rbp_credits >= rbp->rbp_req_nbuffers)) {
1190                         /* Discard this buffer so we don't have too
1191                          * many. */
1192                         lnet_destroy_rtrbuf(rb, rbp->rbp_npages);
1193                         rbp->rbp_nbuffers--;
1194                 } else {
1195                         list_add(&rb->rb_list, &rbp->rbp_bufs);
1196                         rbp->rbp_credits++;
1197                         if (rbp->rbp_credits <= 0)
1198                                 lnet_schedule_blocked_locked(rbp);
1199                 }
1200         }
1201
1202 routing_off:
1203         if (msg->msg_peerrtrcredit) {
1204                 LASSERT(rxpeerni);
1205                 LASSERT(rxpeerni->lpni_peer_net);
1206                 LASSERT(rxpeerni->lpni_peer_net->lpn_peer);
1207
1208                 /* give back peer router credits */
1209                 msg->msg_peerrtrcredit = 0;
1210
1211                 spin_lock(&rxpeerni->lpni_lock);
1212                 rxpeerni->lpni_rtrcredits++;
1213                 spin_unlock(&rxpeerni->lpni_lock);
1214
1215                 lp = rxpeerni->lpni_peer_net->lpn_peer;
1216                 spin_lock(&lp->lp_lock);
1217
1218                 /* drop all messages which are queued to be routed on that
1219                  * peer. */
1220                 if (!the_lnet.ln_routing) {
1221                         LIST_HEAD(drop);
1222                         list_splice_init(&lp->lp_rtrq, &drop);
1223                         spin_unlock(&lp->lp_lock);
1224                         lnet_drop_routed_msgs_locked(&drop, msg->msg_rx_cpt);
1225                 } else if (!list_empty(&lp->lp_rtrq)) {
1226                         int msg2_cpt;
1227
1228                         msg2 = list_entry(lp->lp_rtrq.next,
1229                                           struct lnet_msg, msg_list);
1230                         list_del(&msg2->msg_list);
1231                         msg2_cpt = msg2->msg_rx_cpt;
1232                         spin_unlock(&lp->lp_lock);
1233                         /*
1234                          * messages on the lp_rtrq can be from any NID in
1235                          * the peer, which means they might have different
1236                          * cpts. We need to make sure we lock the right
1237                          * one.
1238                          */
1239                         if (msg2_cpt != msg->msg_rx_cpt) {
1240                                 lnet_net_unlock(msg->msg_rx_cpt);
1241                                 lnet_net_lock(msg2_cpt);
1242                         }
1243                         (void) lnet_post_routed_recv_locked(msg2, 1);
1244                         if (msg2_cpt != msg->msg_rx_cpt) {
1245                                 lnet_net_unlock(msg2_cpt);
1246                                 lnet_net_lock(msg->msg_rx_cpt);
1247                         }
1248                 } else {
1249                         spin_unlock(&lp->lp_lock);
1250                 }
1251         }
1252         if (rxni != NULL) {
1253                 msg->msg_rxni = NULL;
1254                 lnet_ni_decref_locked(rxni, msg->msg_rx_cpt);
1255         }
1256         if (rxpeerni != NULL) {
1257                 msg->msg_rxpeer = NULL;
1258                 lnet_peer_ni_decref_locked(rxpeerni);
1259         }
1260 }
1261
1262 static int
1263 lnet_compare_gw_lpnis(struct lnet_peer_ni *p1, struct lnet_peer_ni *p2)
1264 {
1265         if (p1->lpni_txqnob < p2->lpni_txqnob)
1266                 return 1;
1267
1268         if (p1->lpni_txqnob > p2->lpni_txqnob)
1269                 return -1;
1270
1271         if (p1->lpni_txcredits > p2->lpni_txcredits)
1272                 return 1;
1273
1274         if (p1->lpni_txcredits < p2->lpni_txcredits)
1275                 return -1;
1276
1277         return 0;
1278 }
1279
1280 static struct lnet_peer_ni *
1281 lnet_select_peer_ni(struct lnet_ni *best_ni, lnet_nid_t dst_nid,
1282                     struct lnet_peer *peer,
1283                     struct lnet_peer_ni *best_lpni,
1284                     struct lnet_peer_net *peer_net)
1285 {
1286         /*
1287          * Look at the peer NIs for the destination peer that connect
1288          * to the chosen net. If a peer_ni is preferred when using the
1289          * best_ni to communicate, we use that one. If there is no
1290          * preferred peer_ni, or there are multiple preferred peer_ni,
1291          * the available transmit credits are used. If the transmit
1292          * credits are equal, we round-robin over the peer_ni.
1293          */
1294         struct lnet_peer_ni *lpni = NULL;
1295         int best_lpni_credits = (best_lpni) ? best_lpni->lpni_txcredits :
1296                 INT_MIN;
1297         int best_lpni_healthv = (best_lpni) ?
1298                 atomic_read(&best_lpni->lpni_healthv) : 0;
1299         bool preferred = false;
1300         bool ni_is_pref;
1301         int lpni_healthv;
1302
1303         while ((lpni = lnet_get_next_peer_ni_locked(peer, peer_net, lpni))) {
1304                 /*
1305                  * if the best_ni we've chosen aleady has this lpni
1306                  * preferred, then let's use it
1307                  */
1308                 if (best_ni) {
1309                         ni_is_pref = lnet_peer_is_pref_nid_locked(lpni,
1310                                                                 best_ni->ni_nid);
1311                         CDEBUG(D_NET, "%s ni_is_pref = %d\n",
1312                                libcfs_nid2str(best_ni->ni_nid), ni_is_pref);
1313                 } else {
1314                         ni_is_pref = false;
1315                 }
1316
1317                 lpni_healthv = atomic_read(&lpni->lpni_healthv);
1318
1319                 if (best_lpni)
1320                         CDEBUG(D_NET, "%s c:[%d, %d], s:[%d, %d]\n",
1321                                 libcfs_nid2str(lpni->lpni_nid),
1322                                 lpni->lpni_txcredits, best_lpni_credits,
1323                                 lpni->lpni_seq, best_lpni->lpni_seq);
1324
1325                 /* pick the healthiest peer ni */
1326                 if (lpni_healthv < best_lpni_healthv) {
1327                         continue;
1328                 } else if (lpni_healthv > best_lpni_healthv) {
1329                         best_lpni_healthv = lpni_healthv;
1330                 /* if this is a preferred peer use it */
1331                 } else if (!preferred && ni_is_pref) {
1332                         preferred = true;
1333                 } else if (preferred && !ni_is_pref) {
1334                         /*
1335                          * this is not the preferred peer so let's ignore
1336                          * it.
1337                          */
1338                         continue;
1339                 } else if (lpni->lpni_txcredits < best_lpni_credits) {
1340                         /*
1341                          * We already have a peer that has more credits
1342                          * available than this one. No need to consider
1343                          * this peer further.
1344                          */
1345                         continue;
1346                 } else if (lpni->lpni_txcredits == best_lpni_credits) {
1347                         /*
1348                          * The best peer found so far and the current peer
1349                          * have the same number of available credits let's
1350                          * make sure to select between them using Round
1351                          * Robin
1352                          */
1353                         if (best_lpni) {
1354                                 if (best_lpni->lpni_seq <= lpni->lpni_seq)
1355                                         continue;
1356                         }
1357                 }
1358
1359                 best_lpni = lpni;
1360                 best_lpni_credits = lpni->lpni_txcredits;
1361         }
1362
1363         /* if we still can't find a peer ni then we can't reach it */
1364         if (!best_lpni) {
1365                 __u32 net_id = (peer_net) ? peer_net->lpn_net_id :
1366                         LNET_NIDNET(dst_nid);
1367                 CDEBUG(D_NET, "no peer_ni found on peer net %s\n",
1368                                 libcfs_net2str(net_id));
1369                 return NULL;
1370         }
1371
1372         CDEBUG(D_NET, "sd_best_lpni = %s\n",
1373                libcfs_nid2str(best_lpni->lpni_nid));
1374
1375         return best_lpni;
1376 }
1377
1378 /*
1379  * Prerequisite: the best_ni should already be set in the sd
1380  * Find the best lpni.
1381  * If the net id is provided then restrict lpni selection on
1382  * that particular net.
1383  * Otherwise find any reachable lpni. When dealing with an MR
1384  * gateway and it has multiple lpnis which we can use
1385  * we want to select the best one from the list of reachable
1386  * ones.
1387  */
1388 static inline struct lnet_peer_ni *
1389 lnet_find_best_lpni(struct lnet_ni *lni, lnet_nid_t dst_nid,
1390                     struct lnet_peer *peer, __u32 net_id)
1391 {
1392         struct lnet_peer_net *peer_net;
1393         __u32 any_net = LNET_NIDNET(LNET_NID_ANY);
1394
1395         /* find the best_lpni on any local network */
1396         if (net_id == any_net) {
1397                 struct lnet_peer_ni *best_lpni = NULL;
1398                 struct lnet_peer_net *lpn;
1399                 list_for_each_entry(lpn, &peer->lp_peer_nets, lpn_peer_nets) {
1400                         /* no net specified find any reachable peer ni */
1401                         if (!lnet_islocalnet_locked(lpn->lpn_net_id))
1402                                 continue;
1403                         best_lpni = lnet_select_peer_ni(lni, dst_nid, peer,
1404                                                         best_lpni, lpn);
1405                 }
1406
1407                 return best_lpni;
1408         }
1409         /* restrict on the specified net */
1410         peer_net = lnet_peer_get_net_locked(peer, net_id);
1411         if (peer_net)
1412                 return lnet_select_peer_ni(lni, dst_nid, peer, NULL, peer_net);
1413
1414         return NULL;
1415 }
1416
1417 /* Compare route priorities and hop counts */
1418 static int
1419 lnet_compare_routes(struct lnet_route *r1, struct lnet_route *r2)
1420 {
1421         int r1_hops = (r1->lr_hops == LNET_UNDEFINED_HOPS) ? 1 : r1->lr_hops;
1422         int r2_hops = (r2->lr_hops == LNET_UNDEFINED_HOPS) ? 1 : r2->lr_hops;
1423
1424         if (r1->lr_priority < r2->lr_priority)
1425                 return 1;
1426
1427         if (r1->lr_priority > r2->lr_priority)
1428                 return -1;
1429
1430         if (r1_hops < r2_hops)
1431                 return 1;
1432
1433         if (r1_hops > r2_hops)
1434                 return -1;
1435
1436         return 0;
1437 }
1438
1439 static struct lnet_route *
1440 lnet_find_route_locked(struct lnet_remotenet *rnet, __u32 src_net,
1441                        struct lnet_route **prev_route,
1442                        struct lnet_peer_ni **gwni)
1443 {
1444         struct lnet_peer_ni *lpni, *best_gw_ni = NULL;
1445         struct lnet_route *best_route;
1446         struct lnet_route *last_route;
1447         struct lnet_route *route;
1448         int rc;
1449
1450         CDEBUG(D_NET, "Looking up a route to %s, from %s\n",
1451                libcfs_net2str(rnet->lrn_net), libcfs_net2str(src_net));
1452
1453         best_route = last_route = NULL;
1454         list_for_each_entry(route, &rnet->lrn_routes, lr_list) {
1455                 if (!lnet_is_route_alive(route))
1456                         continue;
1457
1458                 /*
1459                  * Restrict the selection of the router NI on the src_net
1460                  * provided. If the src_net is LNET_NID_ANY, then select
1461                  * the best interface available.
1462                  */
1463                 if (!best_route) {
1464                         lpni = lnet_find_best_lpni(NULL, LNET_NID_ANY,
1465                                                    route->lr_gateway,
1466                                                    src_net);
1467                         if (lpni) {
1468                                 best_route = last_route = route;
1469                                 best_gw_ni = lpni;
1470                         } else {
1471                                 CDEBUG(D_NET, "Gateway %s does not have a peer NI on net %s\n",
1472                                        libcfs_nid2str(route->lr_gateway->lp_primary_nid),
1473                                        libcfs_net2str(src_net));
1474                         }
1475
1476                         continue;
1477                 }
1478
1479                 /* no protection on below fields, but it's harmless */
1480                 if (last_route->lr_seq - route->lr_seq < 0)
1481                         last_route = route;
1482
1483                 rc = lnet_compare_routes(route, best_route);
1484                 if (rc == -1)
1485                         continue;
1486
1487                 lpni = lnet_find_best_lpni(NULL, LNET_NID_ANY,
1488                                            route->lr_gateway,
1489                                            src_net);
1490                 /* restrict the lpni on the src_net if specified */
1491                 if (!lpni) {
1492                         CDEBUG(D_NET, "Gateway %s does not have a peer NI on net %s\n",
1493                                libcfs_nid2str(route->lr_gateway->lp_primary_nid),
1494                                libcfs_net2str(src_net));
1495                         continue;
1496                 }
1497
1498                 if (rc == 1) {
1499                         best_route = route;
1500                         best_gw_ni = lpni;
1501                         continue;
1502                 }
1503
1504                 rc = lnet_compare_gw_lpnis(lpni, best_gw_ni);
1505                 if (rc == -1)
1506                         continue;
1507
1508                 if (rc == 1 || route->lr_seq <= best_route->lr_seq) {
1509                         best_route = route;
1510                         best_gw_ni = lpni;
1511                         continue;
1512                 }
1513         }
1514
1515         *prev_route = last_route;
1516         *gwni = best_gw_ni;
1517
1518         return best_route;
1519 }
1520
1521 static struct lnet_ni *
1522 lnet_get_best_ni(struct lnet_net *local_net, struct lnet_ni *best_ni,
1523                  struct lnet_peer *peer, struct lnet_peer_net *peer_net,
1524                  int md_cpt)
1525 {
1526         struct lnet_ni *ni = NULL;
1527         unsigned int shortest_distance;
1528         int best_credits;
1529         int best_healthv;
1530
1531         /*
1532          * If there is no peer_ni that we can send to on this network,
1533          * then there is no point in looking for a new best_ni here.
1534         */
1535         if (!lnet_get_next_peer_ni_locked(peer, peer_net, NULL))
1536                 return best_ni;
1537
1538         if (best_ni == NULL) {
1539                 shortest_distance = UINT_MAX;
1540                 best_credits = INT_MIN;
1541                 best_healthv = 0;
1542         } else {
1543                 shortest_distance = cfs_cpt_distance(lnet_cpt_table(), md_cpt,
1544                                                      best_ni->ni_dev_cpt);
1545                 best_credits = atomic_read(&best_ni->ni_tx_credits);
1546                 best_healthv = atomic_read(&best_ni->ni_healthv);
1547         }
1548
1549         while ((ni = lnet_get_next_ni_locked(local_net, ni))) {
1550                 unsigned int distance;
1551                 int ni_credits;
1552                 int ni_healthv;
1553                 int ni_fatal;
1554
1555                 ni_credits = atomic_read(&ni->ni_tx_credits);
1556                 ni_healthv = atomic_read(&ni->ni_healthv);
1557                 ni_fatal = atomic_read(&ni->ni_fatal_error_on);
1558
1559                 /*
1560                  * calculate the distance from the CPT on which
1561                  * the message memory is allocated to the CPT of
1562                  * the NI's physical device
1563                  */
1564                 distance = cfs_cpt_distance(lnet_cpt_table(),
1565                                             md_cpt,
1566                                             ni->ni_dev_cpt);
1567
1568                 CDEBUG(D_NET, "compare ni %s [c:%d, d:%d, s:%d] with best_ni %s [c:%d, d:%d, s:%d]\n",
1569                        libcfs_nid2str(ni->ni_nid), ni_credits, distance,
1570                        ni->ni_seq, (best_ni) ? libcfs_nid2str(best_ni->ni_nid)
1571                         : "not seleced", best_credits, shortest_distance,
1572                         (best_ni) ? best_ni->ni_seq : 0);
1573
1574                 /*
1575                  * All distances smaller than the NUMA range
1576                  * are treated equally.
1577                  */
1578                 if (distance < lnet_numa_range)
1579                         distance = lnet_numa_range;
1580
1581                 /*
1582                  * Select on health, shorter distance, available
1583                  * credits, then round-robin.
1584                  */
1585                 if (ni_fatal) {
1586                         continue;
1587                 } else if (ni_healthv < best_healthv) {
1588                         continue;
1589                 } else if (ni_healthv > best_healthv) {
1590                         best_healthv = ni_healthv;
1591                         /*
1592                          * If we're going to prefer this ni because it's
1593                          * the healthiest, then we should set the
1594                          * shortest_distance in the algorithm in case
1595                          * there are multiple NIs with the same health but
1596                          * different distances.
1597                          */
1598                         if (distance < shortest_distance)
1599                                 shortest_distance = distance;
1600                 } else if (distance > shortest_distance) {
1601                         continue;
1602                 } else if (distance < shortest_distance) {
1603                         shortest_distance = distance;
1604                 } else if (ni_credits < best_credits) {
1605                         continue;
1606                 } else if (ni_credits == best_credits) {
1607                         if (best_ni && best_ni->ni_seq <= ni->ni_seq)
1608                                 continue;
1609                 }
1610                 best_ni = ni;
1611                 best_credits = ni_credits;
1612         }
1613
1614         CDEBUG(D_NET, "selected best_ni %s\n",
1615                (best_ni) ? libcfs_nid2str(best_ni->ni_nid) : "no selection");
1616
1617         return best_ni;
1618 }
1619
1620 /*
1621  * Traffic to the LNET_RESERVED_PORTAL may not trigger peer discovery,
1622  * because such traffic is required to perform discovery. We therefore
1623  * exclude all GET and PUT on that portal. We also exclude all ACK and
1624  * REPLY traffic, but that is because the portal is not tracked in the
1625  * message structure for these message types. We could restrict this
1626  * further by also checking for LNET_PROTO_PING_MATCHBITS.
1627  */
1628 static bool
1629 lnet_msg_discovery(struct lnet_msg *msg)
1630 {
1631         if (msg->msg_type == LNET_MSG_PUT) {
1632                 if (msg->msg_hdr.msg.put.ptl_index != LNET_RESERVED_PORTAL)
1633                         return true;
1634         } else if (msg->msg_type == LNET_MSG_GET) {
1635                 if (msg->msg_hdr.msg.get.ptl_index != LNET_RESERVED_PORTAL)
1636                         return true;
1637         }
1638         return false;
1639 }
1640
1641 #define SRC_SPEC        0x0001
1642 #define SRC_ANY         0x0002
1643 #define LOCAL_DST       0x0004
1644 #define REMOTE_DST      0x0008
1645 #define MR_DST          0x0010
1646 #define NMR_DST         0x0020
1647 #define SND_RESP        0x0040
1648
1649 /* The following to defines are used for return codes */
1650 #define REPEAT_SEND     0x1000
1651 #define PASS_THROUGH    0x2000
1652
1653 /* The different cases lnet_select pathway needs to handle */
1654 #define SRC_SPEC_LOCAL_MR_DST   (SRC_SPEC | LOCAL_DST | MR_DST)
1655 #define SRC_SPEC_ROUTER_MR_DST  (SRC_SPEC | REMOTE_DST | MR_DST)
1656 #define SRC_SPEC_LOCAL_NMR_DST  (SRC_SPEC | LOCAL_DST | NMR_DST)
1657 #define SRC_SPEC_ROUTER_NMR_DST (SRC_SPEC | REMOTE_DST | NMR_DST)
1658 #define SRC_ANY_LOCAL_MR_DST    (SRC_ANY | LOCAL_DST | MR_DST)
1659 #define SRC_ANY_ROUTER_MR_DST   (SRC_ANY | REMOTE_DST | MR_DST)
1660 #define SRC_ANY_LOCAL_NMR_DST   (SRC_ANY | LOCAL_DST | NMR_DST)
1661 #define SRC_ANY_ROUTER_NMR_DST  (SRC_ANY | REMOTE_DST | NMR_DST)
1662
1663 static int
1664 lnet_handle_lo_send(struct lnet_send_data *sd)
1665 {
1666         struct lnet_msg *msg = sd->sd_msg;
1667         int cpt = sd->sd_cpt;
1668
1669         /* No send credit hassles with LOLND */
1670         lnet_ni_addref_locked(the_lnet.ln_loni, cpt);
1671         msg->msg_hdr.dest_nid = cpu_to_le64(the_lnet.ln_loni->ni_nid);
1672         if (!msg->msg_routing)
1673                 msg->msg_hdr.src_nid =
1674                         cpu_to_le64(the_lnet.ln_loni->ni_nid);
1675         msg->msg_target.nid = the_lnet.ln_loni->ni_nid;
1676         lnet_msg_commit(msg, cpt);
1677         msg->msg_txni = the_lnet.ln_loni;
1678
1679         return LNET_CREDIT_OK;
1680 }
1681
1682 static int
1683 lnet_handle_send(struct lnet_send_data *sd)
1684 {
1685         struct lnet_ni *best_ni = sd->sd_best_ni;
1686         struct lnet_peer_ni *best_lpni = sd->sd_best_lpni;
1687         struct lnet_peer_ni *final_dst_lpni = sd->sd_final_dst_lpni;
1688         struct lnet_msg *msg = sd->sd_msg;
1689         int cpt2;
1690         __u32 send_case = sd->sd_send_case;
1691         int rc;
1692         __u32 routing = send_case & REMOTE_DST;
1693          struct lnet_rsp_tracker *rspt;
1694
1695         /*
1696          * Increment sequence number of the selected peer so that we
1697          * pick the next one in Round Robin.
1698          */
1699         best_lpni->lpni_seq++;
1700
1701         /*
1702          * grab a reference on the peer_ni so it sticks around even if
1703          * we need to drop and relock the lnet_net_lock below.
1704          */
1705         lnet_peer_ni_addref_locked(best_lpni);
1706
1707         /*
1708          * Use lnet_cpt_of_nid() to determine the CPT used to commit the
1709          * message. This ensures that we get a CPT that is correct for
1710          * the NI when the NI has been restricted to a subset of all CPTs.
1711          * If the selected CPT differs from the one currently locked, we
1712          * must unlock and relock the lnet_net_lock(), and then check whether
1713          * the configuration has changed. We don't have a hold on the best_ni
1714          * yet, and it may have vanished.
1715          */
1716         cpt2 = lnet_cpt_of_nid_locked(best_lpni->lpni_nid, best_ni);
1717         if (sd->sd_cpt != cpt2) {
1718                 __u32 seq = lnet_get_dlc_seq_locked();
1719                 lnet_net_unlock(sd->sd_cpt);
1720                 sd->sd_cpt = cpt2;
1721                 lnet_net_lock(sd->sd_cpt);
1722                 if (seq != lnet_get_dlc_seq_locked()) {
1723                         lnet_peer_ni_decref_locked(best_lpni);
1724                         return REPEAT_SEND;
1725                 }
1726         }
1727
1728         /*
1729          * store the best_lpni in the message right away to avoid having
1730          * to do the same operation under different conditions
1731          */
1732         msg->msg_txpeer = best_lpni;
1733         msg->msg_txni = best_ni;
1734
1735         /*
1736          * grab a reference for the best_ni since now it's in use in this
1737          * send. The reference will be dropped in lnet_finalize()
1738          */
1739         lnet_ni_addref_locked(msg->msg_txni, sd->sd_cpt);
1740
1741         /*
1742          * Always set the target.nid to the best peer picked. Either the
1743          * NID will be one of the peer NIDs selected, or the same NID as
1744          * what was originally set in the target or it will be the NID of
1745          * a router if this message should be routed
1746          */
1747         msg->msg_target.nid = msg->msg_txpeer->lpni_nid;
1748
1749         /*
1750          * lnet_msg_commit assigns the correct cpt to the message, which
1751          * is used to decrement the correct refcount on the ni when it's
1752          * time to return the credits
1753          */
1754         lnet_msg_commit(msg, sd->sd_cpt);
1755
1756         /*
1757          * If we are routing the message then we keep the src_nid that was
1758          * set by the originator. If we are not routing then we are the
1759          * originator and set it here.
1760          */
1761         if (!msg->msg_routing)
1762                 msg->msg_hdr.src_nid = cpu_to_le64(msg->msg_txni->ni_nid);
1763
1764         if (routing) {
1765                 msg->msg_target_is_router = 1;
1766                 msg->msg_target.pid = LNET_PID_LUSTRE;
1767                 /*
1768                  * since we're routing we want to ensure that the
1769                  * msg_hdr.dest_nid is set to the final destination. When
1770                  * the router receives this message it knows how to route
1771                  * it.
1772                  *
1773                  * final_dst_lpni is set at the beginning of the
1774                  * lnet_select_pathway() function and is never changed.
1775                  * It's safe to use it here.
1776                  */
1777                 msg->msg_hdr.dest_nid = cpu_to_le64(final_dst_lpni->lpni_nid);
1778         } else {
1779                 /*
1780                  * if we're not routing set the dest_nid to the best peer
1781                  * ni NID that we picked earlier in the algorithm.
1782                  */
1783                 msg->msg_hdr.dest_nid = cpu_to_le64(msg->msg_txpeer->lpni_nid);
1784         }
1785
1786         /*
1787          * if we have response tracker block update it with the next hop
1788          * nid
1789          */
1790         if (msg->msg_md) {
1791                 rspt = msg->msg_md->md_rspt_ptr;
1792                 if (rspt) {
1793                         rspt->rspt_next_hop_nid = msg->msg_txpeer->lpni_nid;
1794                         CDEBUG(D_NET, "rspt_next_hop_nid = %s\n",
1795                                libcfs_nid2str(rspt->rspt_next_hop_nid));
1796                 }
1797         }
1798
1799         rc = lnet_post_send_locked(msg, 0);
1800
1801         if (!rc)
1802                 CDEBUG(D_NET, "TRACE: %s(%s:%s) -> %s(%s:%s) %s : %s try# %d\n",
1803                        libcfs_nid2str(msg->msg_hdr.src_nid),
1804                        libcfs_nid2str(msg->msg_txni->ni_nid),
1805                        libcfs_nid2str(sd->sd_src_nid),
1806                        libcfs_nid2str(msg->msg_hdr.dest_nid),
1807                        libcfs_nid2str(sd->sd_dst_nid),
1808                        libcfs_nid2str(msg->msg_txpeer->lpni_nid),
1809                        libcfs_nid2str(sd->sd_rtr_nid),
1810                        lnet_msgtyp2str(msg->msg_type), msg->msg_retry_count);
1811
1812         return rc;
1813 }
1814
1815 static inline void
1816 lnet_set_non_mr_pref_nid(struct lnet_peer_ni *lpni, struct lnet_ni *lni,
1817                          struct lnet_msg *msg)
1818 {
1819         if (!lnet_peer_is_multi_rail(lpni->lpni_peer_net->lpn_peer) &&
1820             !lnet_msg_is_response(msg) && lpni->lpni_pref_nnids == 0) {
1821                 CDEBUG(D_NET, "Setting preferred local NID %s on NMR peer %s\n",
1822                        libcfs_nid2str(lni->ni_nid),
1823                        libcfs_nid2str(lpni->lpni_nid));
1824                 lnet_peer_ni_set_non_mr_pref_nid(lpni, lni->ni_nid);
1825         }
1826 }
1827
1828 /*
1829  * Source Specified
1830  * Local Destination
1831  * non-mr peer
1832  *
1833  * use the source and destination NIDs as the pathway
1834  */
1835 static int
1836 lnet_handle_spec_local_nmr_dst(struct lnet_send_data *sd)
1837 {
1838         /* the destination lpni is set before we get here. */
1839
1840         /* find local NI */
1841         sd->sd_best_ni = lnet_nid2ni_locked(sd->sd_src_nid, sd->sd_cpt);
1842         if (!sd->sd_best_ni) {
1843                 CERROR("Can't send to %s: src %s is not a "
1844                        "local nid\n", libcfs_nid2str(sd->sd_dst_nid),
1845                                 libcfs_nid2str(sd->sd_src_nid));
1846                 return -EINVAL;
1847         }
1848
1849         lnet_set_non_mr_pref_nid(sd->sd_best_lpni, sd->sd_best_ni, sd->sd_msg);
1850
1851         return lnet_handle_send(sd);
1852 }
1853
1854 /*
1855  * Source Specified
1856  * Local Destination
1857  * MR Peer
1858  *
1859  * Don't run the selection algorithm on the peer NIs. By specifying the
1860  * local NID, we're also saying that we should always use the destination NID
1861  * provided. This handles the case where we should be using the same
1862  * destination NID for the all the messages which belong to the same RPC
1863  * request.
1864  */
1865 static int
1866 lnet_handle_spec_local_mr_dst(struct lnet_send_data *sd)
1867 {
1868         sd->sd_best_ni = lnet_nid2ni_locked(sd->sd_src_nid, sd->sd_cpt);
1869         if (!sd->sd_best_ni) {
1870                 CERROR("Can't send to %s: src %s is not a "
1871                        "local nid\n", libcfs_nid2str(sd->sd_dst_nid),
1872                                 libcfs_nid2str(sd->sd_src_nid));
1873                 return -EINVAL;
1874         }
1875
1876         if (sd->sd_best_lpni &&
1877             sd->sd_best_lpni->lpni_nid == the_lnet.ln_loni->ni_nid)
1878                 return lnet_handle_lo_send(sd);
1879         else if (sd->sd_best_lpni)
1880                 return lnet_handle_send(sd);
1881
1882         CERROR("can't send to %s. no NI on %s\n",
1883                libcfs_nid2str(sd->sd_dst_nid),
1884                libcfs_net2str(sd->sd_best_ni->ni_net->net_id));
1885
1886         return -EHOSTUNREACH;
1887 }
1888
1889 struct lnet_ni *
1890 lnet_find_best_ni_on_spec_net(struct lnet_ni *cur_best_ni,
1891                               struct lnet_peer *peer,
1892                               struct lnet_peer_net *peer_net,
1893                               int cpt,
1894                               bool incr_seq)
1895 {
1896         struct lnet_net *local_net;
1897         struct lnet_ni *best_ni;
1898
1899         local_net = lnet_get_net_locked(peer_net->lpn_net_id);
1900         if (!local_net)
1901                 return NULL;
1902
1903         /*
1904          * Iterate through the NIs in this local Net and select
1905          * the NI to send from. The selection is determined by
1906          * these 3 criterion in the following priority:
1907          *      1. NUMA
1908          *      2. NI available credits
1909          *      3. Round Robin
1910          */
1911         best_ni = lnet_get_best_ni(local_net, cur_best_ni,
1912                                    peer, peer_net, cpt);
1913
1914         if (incr_seq && best_ni)
1915                 best_ni->ni_seq++;
1916
1917         return best_ni;
1918 }
1919
1920 static int
1921 lnet_initiate_peer_discovery(struct lnet_peer_ni *lpni, struct lnet_msg *msg,
1922                              int cpt)
1923 {
1924         struct lnet_peer *peer;
1925         int rc;
1926
1927         lnet_peer_ni_addref_locked(lpni);
1928
1929         peer = lpni->lpni_peer_net->lpn_peer;
1930
1931         if (lnet_peer_gw_discovery(peer)) {
1932                 lnet_peer_ni_decref_locked(lpni);
1933                 return 0;
1934         }
1935
1936         if (!lnet_msg_discovery(msg) || lnet_peer_is_uptodate(peer)) {
1937                 lnet_peer_ni_decref_locked(lpni);
1938                 return 0;
1939         }
1940
1941         rc = lnet_discover_peer_locked(lpni, cpt, false);
1942         if (rc) {
1943                 lnet_peer_ni_decref_locked(lpni);
1944                 return rc;
1945         }
1946         /* The peer may have changed. */
1947         peer = lpni->lpni_peer_net->lpn_peer;
1948         spin_lock(&peer->lp_lock);
1949         if (lnet_peer_is_uptodate_locked(peer)) {
1950                 spin_unlock(&peer->lp_lock);
1951                 lnet_peer_ni_decref_locked(lpni);
1952                 return 0;
1953         }
1954         /* queue message and return */
1955         msg->msg_sending = 0;
1956         msg->msg_txpeer = NULL;
1957         list_add_tail(&msg->msg_list, &peer->lp_dc_pendq);
1958         spin_unlock(&peer->lp_lock);
1959
1960         lnet_peer_ni_decref_locked(lpni);
1961
1962         CDEBUG(D_NET, "msg %p delayed. %s pending discovery\n",
1963                msg, libcfs_nid2str(peer->lp_primary_nid));
1964
1965         return LNET_DC_WAIT;
1966 }
1967
1968 static int
1969 lnet_handle_find_routed_path(struct lnet_send_data *sd,
1970                              lnet_nid_t dst_nid,
1971                              struct lnet_peer_ni **gw_lpni,
1972                              struct lnet_peer **gw_peer)
1973 {
1974         int rc;
1975         __u32 local_lnet;
1976         struct lnet_peer *gw;
1977         struct lnet_peer *lp;
1978         struct lnet_peer_net *lpn;
1979         struct lnet_peer_net *best_lpn = NULL;
1980         struct lnet_remotenet *rnet, *best_rnet = NULL;
1981         struct lnet_route *best_route = NULL;
1982         struct lnet_route *last_route = NULL;
1983         struct lnet_peer_ni *lpni = NULL;
1984         struct lnet_peer_ni *gwni = NULL;
1985         bool route_found = false;
1986         lnet_nid_t src_nid = (sd->sd_src_nid != LNET_NID_ANY) ? sd->sd_src_nid :
1987                 (sd->sd_best_ni != NULL) ? sd->sd_best_ni->ni_nid :
1988                 LNET_NID_ANY;
1989
1990         CDEBUG(D_NET, "using src nid %s for route restriction\n",
1991                libcfs_nid2str(src_nid));
1992
1993         /* If a router nid was specified then we are replying to a GET or
1994          * sending an ACK. In this case we use the gateway associated with the
1995          * specified router nid.
1996          */
1997         if (sd->sd_rtr_nid != LNET_NID_ANY) {
1998                 gwni = lnet_find_peer_ni_locked(sd->sd_rtr_nid);
1999                 if (gwni) {
2000                         gw = gwni->lpni_peer_net->lpn_peer;
2001                         lnet_peer_ni_decref_locked(gwni);
2002                         if (gw->lp_rtr_refcount) {
2003                                 local_lnet = LNET_NIDNET(sd->sd_rtr_nid);
2004                                 route_found = true;
2005                         }
2006                 } else {
2007                         CWARN("No peer NI for gateway %s. Attempting to find an alternative route.\n",
2008                                libcfs_nid2str(sd->sd_rtr_nid));
2009                 }
2010         }
2011
2012         if (!route_found) {
2013                 /* we've already looked up the initial lpni using dst_nid */
2014                 lpni = sd->sd_best_lpni;
2015                 /* the peer tree must be in existence */
2016                 LASSERT(lpni && lpni->lpni_peer_net &&
2017                         lpni->lpni_peer_net->lpn_peer);
2018                 lp = lpni->lpni_peer_net->lpn_peer;
2019
2020                 list_for_each_entry(lpn, &lp->lp_peer_nets, lpn_peer_nets) {
2021                         /* is this remote network reachable?  */
2022                         rnet = lnet_find_rnet_locked(lpn->lpn_net_id);
2023                         if (!rnet)
2024                                 continue;
2025
2026                         if (!best_lpn) {
2027                                 best_lpn = lpn;
2028                                 best_rnet = rnet;
2029                         }
2030
2031                         if (best_lpn->lpn_seq <= lpn->lpn_seq)
2032                                 continue;
2033
2034                         best_lpn = lpn;
2035                         best_rnet = rnet;
2036                 }
2037
2038                 if (!best_lpn) {
2039                         CERROR("peer %s has no available nets\n",
2040                                libcfs_nid2str(sd->sd_dst_nid));
2041                         return -EHOSTUNREACH;
2042                 }
2043
2044                 sd->sd_best_lpni = lnet_find_best_lpni(sd->sd_best_ni,
2045                                                        sd->sd_dst_nid,
2046                                                        lp,
2047                                                        best_lpn->lpn_net_id);
2048                 if (!sd->sd_best_lpni) {
2049                         CERROR("peer %s is unreachable\n",
2050                                libcfs_nid2str(sd->sd_dst_nid));
2051                         return -EHOSTUNREACH;
2052                 }
2053
2054                 /*
2055                  * We're attempting to round robin over the remote peer
2056                  * NI's so update the final destination we selected
2057                  */
2058                 sd->sd_final_dst_lpni = sd->sd_best_lpni;
2059
2060                 /*
2061                  * find the best route. Restrict the selection on the net of the
2062                  * local NI if we've already picked the local NI to send from.
2063                  * Otherwise, let's pick any route we can find and then find
2064                  * a local NI we can reach the route's gateway on. Any route we select
2065                  * will be reachable by virtue of the restriction we have when
2066                  * adding a route.
2067                  */
2068                 best_route = lnet_find_route_locked(best_rnet,
2069                                                     LNET_NIDNET(src_nid),
2070                                                     &last_route, &gwni);
2071
2072                 if (!best_route) {
2073                         CERROR("no route to %s from %s\n",
2074                                libcfs_nid2str(dst_nid),
2075                                libcfs_nid2str(src_nid));
2076                         return -EHOSTUNREACH;
2077                 }
2078
2079                 if (!gwni) {
2080                         CERROR("Internal Error. Route expected to %s from %s\n",
2081                                libcfs_nid2str(dst_nid),
2082                                libcfs_nid2str(src_nid));
2083                         return -EFAULT;
2084                 }
2085
2086                 gw = best_route->lr_gateway;
2087                 LASSERT(gw == gwni->lpni_peer_net->lpn_peer);
2088                 local_lnet = best_route->lr_lnet;
2089
2090                 /*
2091                  * Increment the sequence number of the remote lpni so we
2092                  * can round robin over the different interfaces of the
2093                  * remote lpni
2094                  */
2095                 sd->sd_best_lpni->lpni_seq++;
2096         }
2097
2098         /*
2099          * Discover this gateway if it hasn't already been discovered.
2100          * This means we might delay the message until discovery has
2101          * completed
2102          */
2103         sd->sd_msg->msg_src_nid_param = sd->sd_src_nid;
2104         rc = lnet_initiate_peer_discovery(gwni, sd->sd_msg, sd->sd_cpt);
2105         if (rc)
2106                 return rc;
2107
2108         if (!sd->sd_best_ni)
2109                 sd->sd_best_ni = lnet_find_best_ni_on_spec_net(NULL, gw,
2110                                         lnet_peer_get_net_locked(gw,
2111                                                                  local_lnet),
2112                                         sd->sd_md_cpt,
2113                                         true);
2114
2115         if (!sd->sd_best_ni) {
2116                 CERROR("Internal Error. Expected local ni on %s but non found :%s\n",
2117                        libcfs_net2str(local_lnet),
2118                        libcfs_nid2str(sd->sd_src_nid));
2119                 return -EFAULT;
2120         }
2121
2122         *gw_lpni = gwni;
2123         *gw_peer = gw;
2124
2125         /*
2126          * increment the sequence numbers since now we're sure we're
2127          * going to use this path
2128          */
2129         if (sd->sd_rtr_nid == LNET_NID_ANY) {
2130                 LASSERT(best_route && last_route);
2131                 best_route->lr_seq = last_route->lr_seq + 1;
2132                 best_lpn->lpn_seq++;
2133         }
2134
2135         return 0;
2136 }
2137
2138 /*
2139  * Handle two cases:
2140  *
2141  * Case 1:
2142  *  Source specified
2143  *  Remote destination
2144  *  Non-MR destination
2145  *
2146  * Case 2:
2147  *  Source specified
2148  *  Remote destination
2149  *  MR destination
2150  *
2151  * The handling of these two cases is similar. Even though the destination
2152  * can be MR or non-MR, we'll deal directly with the router.
2153  */
2154 static int
2155 lnet_handle_spec_router_dst(struct lnet_send_data *sd)
2156 {
2157         int rc;
2158         struct lnet_peer_ni *gw_lpni = NULL;
2159         struct lnet_peer *gw_peer = NULL;
2160
2161         /* find local NI */
2162         sd->sd_best_ni = lnet_nid2ni_locked(sd->sd_src_nid, sd->sd_cpt);
2163         if (!sd->sd_best_ni) {
2164                 CERROR("Can't send to %s: src %s is not a "
2165                        "local nid\n", libcfs_nid2str(sd->sd_dst_nid),
2166                                 libcfs_nid2str(sd->sd_src_nid));
2167                 return -EINVAL;
2168         }
2169
2170         rc = lnet_handle_find_routed_path(sd, sd->sd_dst_nid, &gw_lpni,
2171                                      &gw_peer);
2172         if (rc)
2173                 return rc;
2174
2175         if (sd->sd_send_case & NMR_DST)
2176                 /*
2177                  * since the final destination is non-MR let's set its preferred
2178                  * NID before we send
2179                  */
2180                 lnet_set_non_mr_pref_nid(sd->sd_best_lpni, sd->sd_best_ni,
2181                                          sd->sd_msg);
2182
2183         /*
2184          * We're going to send to the gw found so let's set its
2185          * info
2186          */
2187         sd->sd_peer = gw_peer;
2188         sd->sd_best_lpni = gw_lpni;
2189
2190         return lnet_handle_send(sd);
2191 }
2192
2193 struct lnet_ni *
2194 lnet_find_best_ni_on_local_net(struct lnet_peer *peer, int md_cpt,
2195                                bool discovery)
2196 {
2197         struct lnet_peer_net *peer_net = NULL;
2198         struct lnet_ni *best_ni = NULL;
2199         int lpn_healthv = 0;
2200
2201         /*
2202          * The peer can have multiple interfaces, some of them can be on
2203          * the local network and others on a routed network. We should
2204          * prefer the local network. However if the local network is not
2205          * available then we need to try the routed network
2206          */
2207
2208         /* go through all the peer nets and find the best_ni */
2209         list_for_each_entry(peer_net, &peer->lp_peer_nets, lpn_peer_nets) {
2210                 /*
2211                  * The peer's list of nets can contain non-local nets. We
2212                  * want to only examine the local ones.
2213                  */
2214                 if (!lnet_get_net_locked(peer_net->lpn_net_id))
2215                         continue;
2216
2217                 /* always select the lpn with the best health */
2218                 if (lpn_healthv <= peer_net->lpn_healthv)
2219                         lpn_healthv = peer_net->lpn_healthv;
2220                 else
2221                         continue;
2222
2223                 best_ni = lnet_find_best_ni_on_spec_net(best_ni, peer, peer_net,
2224                                                         md_cpt, false);
2225
2226                 /*
2227                  * if this is a discovery message and lp_disc_net_id is
2228                  * specified then use that net to send the discovery on.
2229                  */
2230                 if (peer->lp_disc_net_id == peer_net->lpn_net_id &&
2231                     discovery)
2232                         break;
2233         }
2234
2235         if (best_ni)
2236                 /* increment sequence number so we can round robin */
2237                 best_ni->ni_seq++;
2238
2239         return best_ni;
2240 }
2241
2242 static struct lnet_ni *
2243 lnet_find_existing_preferred_best_ni(struct lnet_peer_ni *lpni, int cpt)
2244 {
2245         struct lnet_ni *best_ni = NULL;
2246         struct lnet_peer_net *peer_net = lpni->lpni_peer_net;
2247         struct lnet_peer_ni *lpni_entry;
2248
2249         /*
2250          * We must use a consistent source address when sending to a
2251          * non-MR peer. However, a non-MR peer can have multiple NIDs
2252          * on multiple networks, and we may even need to talk to this
2253          * peer on multiple networks -- certain types of
2254          * load-balancing configuration do this.
2255          *
2256          * So we need to pick the NI the peer prefers for this
2257          * particular network.
2258          */
2259         LASSERT(peer_net);
2260         list_for_each_entry(lpni_entry, &peer_net->lpn_peer_nis,
2261                             lpni_peer_nis) {
2262                 if (lpni_entry->lpni_pref_nnids == 0)
2263                         continue;
2264                 LASSERT(lpni_entry->lpni_pref_nnids == 1);
2265                 best_ni = lnet_nid2ni_locked(lpni_entry->lpni_pref.nid, cpt);
2266                 break;
2267         }
2268
2269         return best_ni;
2270 }
2271
2272 /* Prerequisite: sd->sd_peer and sd->sd_best_lpni should be set */
2273 static int
2274 lnet_select_preferred_best_ni(struct lnet_send_data *sd)
2275 {
2276         struct lnet_ni *best_ni = NULL;
2277         struct lnet_peer_ni *best_lpni = sd->sd_best_lpni;
2278
2279         /*
2280          * We must use a consistent source address when sending to a
2281          * non-MR peer. However, a non-MR peer can have multiple NIDs
2282          * on multiple networks, and we may even need to talk to this
2283          * peer on multiple networks -- certain types of
2284          * load-balancing configuration do this.
2285          *
2286          * So we need to pick the NI the peer prefers for this
2287          * particular network.
2288          */
2289
2290         best_ni = lnet_find_existing_preferred_best_ni(sd->sd_best_lpni,
2291                                                        sd->sd_cpt);
2292
2293         /* if best_ni is still not set just pick one */
2294         if (!best_ni) {
2295                 best_ni =
2296                   lnet_find_best_ni_on_spec_net(NULL, sd->sd_peer,
2297                                                 sd->sd_best_lpni->lpni_peer_net,
2298                                                 sd->sd_md_cpt, true);
2299                 /* If there is no best_ni we don't have a route */
2300                 if (!best_ni) {
2301                         CERROR("no path to %s from net %s\n",
2302                                 libcfs_nid2str(best_lpni->lpni_nid),
2303                                 libcfs_net2str(best_lpni->lpni_net->net_id));
2304                         return -EHOSTUNREACH;
2305                 }
2306         }
2307
2308         sd->sd_best_ni = best_ni;
2309
2310         /* Set preferred NI if necessary. */
2311         lnet_set_non_mr_pref_nid(sd->sd_best_lpni, sd->sd_best_ni, sd->sd_msg);
2312
2313         return 0;
2314 }
2315
2316
2317 /*
2318  * Source not specified
2319  * Local destination
2320  * Non-MR Peer
2321  *
2322  * always use the same source NID for NMR peers
2323  * If we've talked to that peer before then we already have a preferred
2324  * source NI associated with it. Otherwise, we select a preferred local NI
2325  * and store it in the peer
2326  */
2327 static int
2328 lnet_handle_any_local_nmr_dst(struct lnet_send_data *sd)
2329 {
2330         int rc = 0;
2331
2332         /* sd->sd_best_lpni is already set to the final destination */
2333
2334         /*
2335          * At this point we should've created the peer ni and peer. If we
2336          * can't find it, then something went wrong. Instead of assert
2337          * output a relevant message and fail the send
2338          */
2339         if (!sd->sd_best_lpni) {
2340                 CERROR("Internal fault. Unable to send msg %s to %s. "
2341                        "NID not known\n",
2342                        lnet_msgtyp2str(sd->sd_msg->msg_type),
2343                        libcfs_nid2str(sd->sd_dst_nid));
2344                 return -EFAULT;
2345         }
2346
2347         if (sd->sd_msg->msg_routing) {
2348                 /* If I'm forwarding this message then I can choose any NI
2349                  * on the destination peer net
2350                  */
2351                 sd->sd_best_ni = lnet_find_best_ni_on_spec_net(NULL,
2352                                                                sd->sd_peer,
2353                                                                sd->sd_best_lpni->lpni_peer_net,
2354                                                                sd->sd_md_cpt,
2355                                                                true);
2356                 if (!sd->sd_best_ni) {
2357                         CERROR("Unable to forward message to %s. No local NI available\n",
2358                                libcfs_nid2str(sd->sd_dst_nid));
2359                         rc = -EHOSTUNREACH;
2360                 }
2361         } else
2362                 rc = lnet_select_preferred_best_ni(sd);
2363
2364         if (!rc)
2365                 rc = lnet_handle_send(sd);
2366
2367         return rc;
2368 }
2369
2370 static int
2371 lnet_handle_any_mr_dsta(struct lnet_send_data *sd)
2372 {
2373         /*
2374          * NOTE we've already handled the remote peer case. So we only
2375          * need to worry about the local case here.
2376          *
2377          * if we're sending a response, ACK or reply, we need to send it
2378          * to the destination NID given to us. At this point we already
2379          * have the peer_ni we're suppose to send to, so just find the
2380          * best_ni on the peer net and use that. Since we're sending to an
2381          * MR peer then we can just run the selection algorithm on our
2382          * local NIs and pick the best one.
2383          */
2384         if (sd->sd_send_case & SND_RESP) {
2385                 sd->sd_best_ni =
2386                   lnet_find_best_ni_on_spec_net(NULL, sd->sd_peer,
2387                                                 sd->sd_best_lpni->lpni_peer_net,
2388                                                 sd->sd_md_cpt, true);
2389
2390                 if (!sd->sd_best_ni) {
2391                         /*
2392                          * We're not going to deal with not able to send
2393                          * a response to the provided final destination
2394                          */
2395                         CERROR("Can't send response to %s. "
2396                                "No local NI available\n",
2397                                 libcfs_nid2str(sd->sd_dst_nid));
2398                         return -EHOSTUNREACH;
2399                 }
2400
2401                 return lnet_handle_send(sd);
2402         }
2403
2404         /*
2405          * If we get here that means we're sending a fresh request, PUT or
2406          * GET, so we need to run our standard selection algorithm.
2407          * First find the best local interface that's on any of the peer's
2408          * networks.
2409          */
2410         sd->sd_best_ni = lnet_find_best_ni_on_local_net(sd->sd_peer,
2411                                         sd->sd_md_cpt,
2412                                         lnet_msg_discovery(sd->sd_msg));
2413         if (sd->sd_best_ni) {
2414                 sd->sd_best_lpni =
2415                   lnet_find_best_lpni(sd->sd_best_ni, sd->sd_dst_nid,
2416                                       sd->sd_peer,
2417                                       sd->sd_best_ni->ni_net->net_id);
2418
2419                 /*
2420                  * if we're successful in selecting a peer_ni on the local
2421                  * network, then send to it. Otherwise fall through and
2422                  * try and see if we can reach it over another routed
2423                  * network
2424                  */
2425                 if (sd->sd_best_lpni &&
2426                     sd->sd_best_lpni->lpni_nid == the_lnet.ln_loni->ni_nid) {
2427                         /*
2428                          * in case we initially started with a routed
2429                          * destination, let's reset to local
2430                          */
2431                         sd->sd_send_case &= ~REMOTE_DST;
2432                         sd->sd_send_case |= LOCAL_DST;
2433                         return lnet_handle_lo_send(sd);
2434                 } else if (sd->sd_best_lpni) {
2435                         /*
2436                          * in case we initially started with a routed
2437                          * destination, let's reset to local
2438                          */
2439                         sd->sd_send_case &= ~REMOTE_DST;
2440                         sd->sd_send_case |= LOCAL_DST;
2441                         return lnet_handle_send(sd);
2442                 }
2443
2444                 CERROR("Internal Error. Expected to have a best_lpni: "
2445                        "%s -> %s\n",
2446                        libcfs_nid2str(sd->sd_src_nid),
2447                        libcfs_nid2str(sd->sd_dst_nid));
2448
2449                 return -EFAULT;
2450         }
2451
2452         /*
2453          * Peer doesn't have a local network. Let's see if there is
2454          * a remote network we can reach it on.
2455          */
2456         return PASS_THROUGH;
2457 }
2458
2459 /*
2460  * Case 1:
2461  *      Source NID not specified
2462  *      Local destination
2463  *      MR peer
2464  *
2465  * Case 2:
2466  *      Source NID not speified
2467  *      Remote destination
2468  *      MR peer
2469  *
2470  * In both of these cases if we're sending a response, ACK or REPLY, then
2471  * we need to send to the destination NID provided.
2472  *
2473  * In the remote case let's deal with MR routers.
2474  *
2475  */
2476
2477 static int
2478 lnet_handle_any_mr_dst(struct lnet_send_data *sd)
2479 {
2480         int rc = 0;
2481         struct lnet_peer *gw_peer = NULL;
2482         struct lnet_peer_ni *gw_lpni = NULL;
2483
2484         /*
2485          * handle sending a response to a remote peer here so we don't
2486          * have to worry about it if we hit lnet_handle_any_mr_dsta()
2487          */
2488         if (sd->sd_send_case & REMOTE_DST &&
2489             sd->sd_send_case & SND_RESP) {
2490                 struct lnet_peer_ni *gw;
2491                 struct lnet_peer *gw_peer;
2492
2493                 rc = lnet_handle_find_routed_path(sd, sd->sd_dst_nid, &gw,
2494                                                   &gw_peer);
2495                 if (rc < 0) {
2496                         CERROR("Can't send response to %s. "
2497                                "No route available\n",
2498                                 libcfs_nid2str(sd->sd_dst_nid));
2499                         return -EHOSTUNREACH;
2500                 } else if (rc > 0) {
2501                         return rc;
2502                 }
2503
2504                 sd->sd_best_lpni = gw;
2505                 sd->sd_peer = gw_peer;
2506
2507                 return lnet_handle_send(sd);
2508         }
2509
2510         /*
2511          * Even though the NID for the peer might not be on a local network,
2512          * since the peer is MR there could be other interfaces on the
2513          * local network. In that case we'd still like to prefer the local
2514          * network over the routed network. If we're unable to do that
2515          * then we select the best router among the different routed networks,
2516          * and if the router is MR then we can deal with it as such.
2517          */
2518         rc = lnet_handle_any_mr_dsta(sd);
2519         if (rc != PASS_THROUGH)
2520                 return rc;
2521
2522         /*
2523          * Now that we must route to the destination, we must consider the
2524          * MR case, where the destination has multiple interfaces, some of
2525          * which we can route to and others we do not. For this reason we
2526          * need to select the destination which we can route to and if
2527          * there are multiple, we need to round robin.
2528          */
2529         rc = lnet_handle_find_routed_path(sd, sd->sd_dst_nid, &gw_lpni,
2530                                           &gw_peer);
2531         if (rc)
2532                 return rc;
2533
2534         sd->sd_send_case &= ~LOCAL_DST;
2535         sd->sd_send_case |= REMOTE_DST;
2536
2537         sd->sd_peer = gw_peer;
2538         sd->sd_best_lpni = gw_lpni;
2539
2540         return lnet_handle_send(sd);
2541 }
2542
2543 /*
2544  * Source not specified
2545  * Remote destination
2546  * Non-MR peer
2547  *
2548  * Must send to the specified peer NID using the same source NID that
2549  * we've used before. If it's the first time to talk to that peer then
2550  * find the source NI and assign it as preferred to that peer
2551  */
2552 static int
2553 lnet_handle_any_router_nmr_dst(struct lnet_send_data *sd)
2554 {
2555         int rc;
2556         struct lnet_peer_ni *gw_lpni = NULL;
2557         struct lnet_peer *gw_peer = NULL;
2558
2559         /*
2560          * Let's see if we have a preferred NI to talk to this NMR peer
2561          */
2562         sd->sd_best_ni = lnet_find_existing_preferred_best_ni(sd->sd_best_lpni,
2563                                                               sd->sd_cpt);
2564
2565         /*
2566          * find the router and that'll find the best NI if we didn't find
2567          * it already.
2568          */
2569         rc = lnet_handle_find_routed_path(sd, sd->sd_dst_nid, &gw_lpni,
2570                                           &gw_peer);
2571         if (rc)
2572                 return rc;
2573
2574         /*
2575          * set the best_ni we've chosen as the preferred one for
2576          * this peer
2577          */
2578         lnet_set_non_mr_pref_nid(sd->sd_best_lpni, sd->sd_best_ni, sd->sd_msg);
2579
2580         /* we'll be sending to the gw */
2581         sd->sd_best_lpni = gw_lpni;
2582         sd->sd_peer = gw_peer;
2583
2584         return lnet_handle_send(sd);
2585 }
2586
2587 static int
2588 lnet_handle_send_case_locked(struct lnet_send_data *sd)
2589 {
2590         /*
2591          * turn off the SND_RESP bit.
2592          * It will be checked in the case handling
2593          */
2594         __u32 send_case = sd->sd_send_case &= ~SND_RESP ;
2595
2596         CDEBUG(D_NET, "Source %s%s to %s %s %s destination\n",
2597                 (send_case & SRC_SPEC) ? "Specified: " : "ANY",
2598                 (send_case & SRC_SPEC) ? libcfs_nid2str(sd->sd_src_nid) : "",
2599                 (send_case & MR_DST) ? "MR: " : "NMR: ",
2600                 libcfs_nid2str(sd->sd_dst_nid),
2601                 (send_case & LOCAL_DST) ? "local" : "routed");
2602
2603         switch (send_case) {
2604         /*
2605          * For all cases where the source is specified, we should always
2606          * use the destination NID, whether it's an MR destination or not,
2607          * since we're continuing a series of related messages for the
2608          * same RPC
2609          */
2610         case SRC_SPEC_LOCAL_NMR_DST:
2611                 return lnet_handle_spec_local_nmr_dst(sd);
2612         case SRC_SPEC_LOCAL_MR_DST:
2613                 return lnet_handle_spec_local_mr_dst(sd);
2614         case SRC_SPEC_ROUTER_NMR_DST:
2615         case SRC_SPEC_ROUTER_MR_DST:
2616                 return lnet_handle_spec_router_dst(sd);
2617         case SRC_ANY_LOCAL_NMR_DST:
2618                 return lnet_handle_any_local_nmr_dst(sd);
2619         case SRC_ANY_LOCAL_MR_DST:
2620         case SRC_ANY_ROUTER_MR_DST:
2621                 return lnet_handle_any_mr_dst(sd);
2622         case SRC_ANY_ROUTER_NMR_DST:
2623                 return lnet_handle_any_router_nmr_dst(sd);
2624         default:
2625                 CERROR("Unknown send case\n");
2626                 return -1;
2627         }
2628 }
2629
2630 static int
2631 lnet_select_pathway(lnet_nid_t src_nid, lnet_nid_t dst_nid,
2632                     struct lnet_msg *msg, lnet_nid_t rtr_nid)
2633 {
2634         struct lnet_peer_ni *lpni;
2635         struct lnet_peer *peer;
2636         struct lnet_send_data send_data;
2637         int cpt, rc;
2638         int md_cpt;
2639         __u32 send_case = 0;
2640         bool final_hop;
2641         bool mr_forwarding_allowed;
2642
2643         memset(&send_data, 0, sizeof(send_data));
2644
2645         /*
2646          * get an initial CPT to use for locking. The idea here is not to
2647          * serialize the calls to select_pathway, so that as many
2648          * operations can run concurrently as possible. To do that we use
2649          * the CPT where this call is being executed. Later on when we
2650          * determine the CPT to use in lnet_message_commit, we switch the
2651          * lock and check if there was any configuration change.  If none,
2652          * then we proceed, if there is, then we restart the operation.
2653          */
2654         cpt = lnet_net_lock_current();
2655
2656         md_cpt = lnet_cpt_of_md(msg->msg_md, msg->msg_offset);
2657         if (md_cpt == CFS_CPT_ANY)
2658                 md_cpt = cpt;
2659
2660 again:
2661
2662         /*
2663          * If we're being asked to send to the loopback interface, there
2664          * is no need to go through any selection. We can just shortcut
2665          * the entire process and send over lolnd
2666          */
2667         send_data.sd_msg = msg;
2668         send_data.sd_cpt = cpt;
2669         if (dst_nid == LNET_NID_LO_0) {
2670                 rc = lnet_handle_lo_send(&send_data);
2671                 lnet_net_unlock(cpt);
2672                 return rc;
2673         }
2674
2675         /*
2676          * find an existing peer_ni, or create one and mark it as having been
2677          * created due to network traffic. This call will create the
2678          * peer->peer_net->peer_ni tree.
2679          */
2680         lpni = lnet_nid2peerni_locked(dst_nid, LNET_NID_ANY, cpt);
2681         if (IS_ERR(lpni)) {
2682                 lnet_net_unlock(cpt);
2683                 return PTR_ERR(lpni);
2684         }
2685
2686         /*
2687          * Cache the original src_nid and rtr_nid. If we need to resend the
2688          * message then we'll need to know whether the src_nid was originally
2689          * specified for this message. If it was originally specified,
2690          * then we need to keep using the same src_nid since it's
2691          * continuing the same sequence of messages. Similarly, rtr_nid will
2692          * affect our choice of next hop.
2693          */
2694         msg->msg_src_nid_param = src_nid;
2695         msg->msg_rtr_nid_param = rtr_nid;
2696
2697         /*
2698          * If necessary, perform discovery on the peer that owns this peer_ni.
2699          * Note, this can result in the ownership of this peer_ni changing
2700          * to another peer object.
2701          */
2702         rc = lnet_initiate_peer_discovery(lpni, msg, cpt);
2703         if (rc) {
2704                 lnet_peer_ni_decref_locked(lpni);
2705                 lnet_net_unlock(cpt);
2706                 return rc;
2707         }
2708         lnet_peer_ni_decref_locked(lpni);
2709
2710         peer = lpni->lpni_peer_net->lpn_peer;
2711
2712         /*
2713          * Identify the different send cases
2714          */
2715         if (src_nid == LNET_NID_ANY)
2716                 send_case |= SRC_ANY;
2717         else
2718                 send_case |= SRC_SPEC;
2719
2720         if (lnet_get_net_locked(LNET_NIDNET(dst_nid)))
2721                 send_case |= LOCAL_DST;
2722         else
2723                 send_case |= REMOTE_DST;
2724
2725         final_hop = false;
2726         if (msg->msg_routing && (send_case & LOCAL_DST))
2727                 final_hop = true;
2728
2729         /* Determine whether to allow MR forwarding for this message.
2730          * NB: MR forwarding is allowed if the message originator and the
2731          * destination are both MR capable, and the destination lpni that was
2732          * originally chosen by the originator is unhealthy or down.
2733          * We check the MR capability of the destination further below
2734          */
2735         mr_forwarding_allowed = false;
2736         if (final_hop) {
2737                 struct lnet_peer *src_lp;
2738                 struct lnet_peer_ni *src_lpni;
2739
2740                 src_lpni = lnet_nid2peerni_locked(msg->msg_hdr.src_nid,
2741                                                   LNET_NID_ANY, cpt);
2742                 /* We don't fail the send if we hit any errors here. We'll just
2743                  * try to send it via non-multi-rail criteria
2744                  */
2745                 if (!IS_ERR(src_lpni)) {
2746                         src_lp = lpni->lpni_peer_net->lpn_peer;
2747                         if (lnet_peer_is_multi_rail(src_lp) &&
2748                             !lnet_is_peer_ni_alive(lpni))
2749                                 mr_forwarding_allowed = true;
2750
2751                 }
2752                 CDEBUG(D_NET, "msg %p MR forwarding %s\n", msg,
2753                        mr_forwarding_allowed ? "allowed" : "not allowed");
2754         }
2755
2756         /*
2757          * Deal with the peer as NMR in the following cases:
2758          * 1. the peer is NMR
2759          * 2. We're trying to recover a specific peer NI
2760          * 3. I'm a router sending to the final destination and MR forwarding is
2761          *    not allowed for this message (as determined above).
2762          *    In this case the source of the message would've
2763          *    already selected the final destination so my job
2764          *    is to honor the selection.
2765          */
2766         if (!lnet_peer_is_multi_rail(peer) || msg->msg_recovery ||
2767             (final_hop && !mr_forwarding_allowed))
2768                 send_case |= NMR_DST;
2769         else
2770                 send_case |= MR_DST;
2771
2772         if (lnet_msg_is_response(msg))
2773                 send_case |= SND_RESP;
2774
2775         /* assign parameters to the send_data */
2776         send_data.sd_rtr_nid = rtr_nid;
2777         send_data.sd_src_nid = src_nid;
2778         send_data.sd_dst_nid = dst_nid;
2779         send_data.sd_best_lpni = lpni;
2780         /*
2781          * keep a pointer to the final destination in case we're going to
2782          * route, so we'll need to access it later
2783          */
2784         send_data.sd_final_dst_lpni = lpni;
2785         send_data.sd_peer = peer;
2786         send_data.sd_md_cpt = md_cpt;
2787         send_data.sd_send_case = send_case;
2788
2789         rc = lnet_handle_send_case_locked(&send_data);
2790
2791         /*
2792          * Update the local cpt since send_data.sd_cpt might've been
2793          * updated as a result of calling lnet_handle_send_case_locked().
2794          */
2795         cpt = send_data.sd_cpt;
2796
2797         if (rc == REPEAT_SEND)
2798                 goto again;
2799
2800         lnet_net_unlock(cpt);
2801
2802         return rc;
2803 }
2804
2805 int
2806 lnet_send(lnet_nid_t src_nid, struct lnet_msg *msg, lnet_nid_t rtr_nid)
2807 {
2808         lnet_nid_t              dst_nid = msg->msg_target.nid;
2809         int                     rc;
2810
2811         /*
2812          * NB: rtr_nid is set to LNET_NID_ANY for all current use-cases,
2813          * but we might want to use pre-determined router for ACK/REPLY
2814          * in the future
2815          */
2816         /* NB: ni != NULL == interface pre-determined (ACK/REPLY) */
2817         LASSERT(msg->msg_txpeer == NULL);
2818         LASSERT(msg->msg_txni == NULL);
2819         LASSERT(!msg->msg_sending);
2820         LASSERT(!msg->msg_target_is_router);
2821         LASSERT(!msg->msg_receiving);
2822
2823         msg->msg_sending = 1;
2824
2825         LASSERT(!msg->msg_tx_committed);
2826
2827         rc = lnet_select_pathway(src_nid, dst_nid, msg, rtr_nid);
2828         if (rc < 0) {
2829                 if (rc == -EHOSTUNREACH)
2830                         msg->msg_health_status = LNET_MSG_STATUS_REMOTE_ERROR;
2831                 else
2832                         msg->msg_health_status = LNET_MSG_STATUS_LOCAL_ERROR;
2833                 return rc;
2834         }
2835
2836         if (rc == LNET_CREDIT_OK)
2837                 lnet_ni_send(msg->msg_txni, msg);
2838
2839         /* rc == LNET_CREDIT_OK or LNET_CREDIT_WAIT or LNET_DC_WAIT */
2840         return 0;
2841 }
2842
2843 enum lnet_mt_event_type {
2844         MT_TYPE_LOCAL_NI = 0,
2845         MT_TYPE_PEER_NI
2846 };
2847
2848 struct lnet_mt_event_info {
2849         enum lnet_mt_event_type mt_type;
2850         lnet_nid_t mt_nid;
2851 };
2852
2853 /* called with res_lock held */
2854 void
2855 lnet_detach_rsp_tracker(struct lnet_libmd *md, int cpt)
2856 {
2857         struct lnet_rsp_tracker *rspt;
2858
2859         /*
2860          * msg has a refcount on the MD so the MD is not going away.
2861          * The rspt queue for the cpt is protected by
2862          * the lnet_net_lock(cpt). cpt is the cpt of the MD cookie.
2863          */
2864         if (!md->md_rspt_ptr)
2865                 return;
2866
2867         rspt = md->md_rspt_ptr;
2868
2869         /* debug code */
2870         LASSERT(rspt->rspt_cpt == cpt);
2871
2872         md->md_rspt_ptr = NULL;
2873
2874         if (LNetMDHandleIsInvalid(rspt->rspt_mdh)) {
2875                 /*
2876                  * The monitor thread has invalidated this handle because the
2877                  * response timed out, but it failed to lookup the MD. That
2878                  * means this response tracker is on the zombie list. We can
2879                  * safely remove it under the resource lock (held by caller) and
2880                  * free the response tracker block.
2881                  */
2882                 list_del(&rspt->rspt_on_list);
2883                 lnet_rspt_free(rspt, cpt);
2884         } else {
2885                 /*
2886                  * invalidate the handle to indicate that a response has been
2887                  * received, which will then lead the monitor thread to clean up
2888                  * the rspt block.
2889                  */
2890                 LNetInvalidateMDHandle(&rspt->rspt_mdh);
2891         }
2892 }
2893
2894 void
2895 lnet_clean_zombie_rstqs(void)
2896 {
2897         struct lnet_rsp_tracker *rspt, *tmp;
2898         int i;
2899
2900         cfs_cpt_for_each(i, lnet_cpt_table()) {
2901                 list_for_each_entry_safe(rspt, tmp,
2902                                          the_lnet.ln_mt_zombie_rstqs[i],
2903                                          rspt_on_list) {
2904                         list_del(&rspt->rspt_on_list);
2905                         lnet_rspt_free(rspt, i);
2906                 }
2907         }
2908
2909         cfs_percpt_free(the_lnet.ln_mt_zombie_rstqs);
2910 }
2911
2912 static void
2913 lnet_finalize_expired_responses(void)
2914 {
2915         struct lnet_libmd *md;
2916         struct lnet_rsp_tracker *rspt, *tmp;
2917         ktime_t now;
2918         int i;
2919
2920         if (the_lnet.ln_mt_rstq == NULL)
2921                 return;
2922
2923         cfs_cpt_for_each(i, lnet_cpt_table()) {
2924                 LIST_HEAD(local_queue);
2925
2926                 lnet_net_lock(i);
2927                 if (!the_lnet.ln_mt_rstq[i]) {
2928                         lnet_net_unlock(i);
2929                         continue;
2930                 }
2931                 list_splice_init(the_lnet.ln_mt_rstq[i], &local_queue);
2932                 lnet_net_unlock(i);
2933
2934                 now = ktime_get();
2935
2936                 list_for_each_entry_safe(rspt, tmp, &local_queue, rspt_on_list) {
2937                         /*
2938                          * The rspt mdh will be invalidated when a response
2939                          * is received or whenever we want to discard the
2940                          * block the monitor thread will walk the queue
2941                          * and clean up any rsts with an invalid mdh.
2942                          * The monitor thread will walk the queue until
2943                          * the first unexpired rspt block. This means that
2944                          * some rspt blocks which received their
2945                          * corresponding responses will linger in the
2946                          * queue until they are cleaned up eventually.
2947                          */
2948                         lnet_res_lock(i);
2949                         if (LNetMDHandleIsInvalid(rspt->rspt_mdh)) {
2950                                 lnet_res_unlock(i);
2951                                 list_del(&rspt->rspt_on_list);
2952                                 lnet_rspt_free(rspt, i);
2953                                 continue;
2954                         }
2955
2956                         if (ktime_compare(now, rspt->rspt_deadline) >= 0 ||
2957                             the_lnet.ln_mt_state == LNET_MT_STATE_SHUTDOWN) {
2958                                 struct lnet_peer_ni *lpni;
2959                                 lnet_nid_t nid;
2960
2961                                 md = lnet_handle2md(&rspt->rspt_mdh);
2962                                 if (!md) {
2963                                         /* MD has been queued for unlink, but
2964                                          * rspt hasn't been detached (Note we've
2965                                          * checked above that the rspt_mdh is
2966                                          * valid). Since we cannot lookup the MD
2967                                          * we're unable to detach the rspt
2968                                          * ourselves. Thus, move the rspt to the
2969                                          * zombie list where we'll wait for
2970                                          * either:
2971                                          *   1. The remaining operations on the
2972                                          *   MD to complete. In this case the
2973                                          *   final operation will result in
2974                                          *   lnet_msg_detach_md()->
2975                                          *   lnet_detach_rsp_tracker() where
2976                                          *   we will clean up this response
2977                                          *   tracker.
2978                                          *   2. LNet to shutdown. In this case
2979                                          *   we'll wait until after all LND Nets
2980                                          *   have shutdown and then we can
2981                                          *   safely free any remaining response
2982                                          *   tracker blocks on the zombie list.
2983                                          * Note: We need to hold the resource
2984                                          * lock when adding to the zombie list
2985                                          * because we may have concurrent access
2986                                          * with lnet_detach_rsp_tracker().
2987                                          */
2988                                         LNetInvalidateMDHandle(&rspt->rspt_mdh);
2989                                         list_move(&rspt->rspt_on_list,
2990                                                   the_lnet.ln_mt_zombie_rstqs[i]);
2991                                         lnet_res_unlock(i);
2992                                         continue;
2993                                 }
2994                                 LASSERT(md->md_rspt_ptr == rspt);
2995                                 md->md_rspt_ptr = NULL;
2996                                 lnet_res_unlock(i);
2997
2998                                 LNetMDUnlink(rspt->rspt_mdh);
2999
3000                                 nid = rspt->rspt_next_hop_nid;
3001
3002                                 list_del(&rspt->rspt_on_list);
3003                                 lnet_rspt_free(rspt, i);
3004
3005                                 /* If we're shutting down we just want to clean
3006                                  * up the rspt blocks
3007                                  */
3008                                 if (the_lnet.ln_mt_state == LNET_MT_STATE_SHUTDOWN)
3009                                         continue;
3010
3011                                 lnet_net_lock(i);
3012                                 the_lnet.ln_counters[i]->lct_health.lch_response_timeout_count++;
3013                                 lnet_net_unlock(i);
3014
3015                                 CDEBUG(D_NET,
3016                                        "Response timeout: md = %p: nid = %s\n",
3017                                        md, libcfs_nid2str(nid));
3018
3019                                 /*
3020                                  * If there is a timeout on the response
3021                                  * from the next hop decrement its health
3022                                  * value so that we don't use it
3023                                  */
3024                                 lnet_net_lock(0);
3025                                 lpni = lnet_find_peer_ni_locked(nid);
3026                                 if (lpni) {
3027                                         lnet_handle_remote_failure_locked(lpni);
3028                                         lnet_peer_ni_decref_locked(lpni);
3029                                 }
3030                                 lnet_net_unlock(0);
3031                         } else {
3032                                 lnet_res_unlock(i);
3033                                 break;
3034                         }
3035                 }
3036
3037                 if (!list_empty(&local_queue)) {
3038                         lnet_net_lock(i);
3039                         list_splice(&local_queue, the_lnet.ln_mt_rstq[i]);
3040                         lnet_net_unlock(i);
3041                 }
3042         }
3043 }
3044
3045 static void
3046 lnet_resend_pending_msgs_locked(struct list_head *resendq, int cpt)
3047 {
3048         struct lnet_msg *msg;
3049
3050         while (!list_empty(resendq)) {
3051                 struct lnet_peer_ni *lpni;
3052
3053                 msg = list_entry(resendq->next, struct lnet_msg,
3054                                  msg_list);
3055
3056                 list_del_init(&msg->msg_list);
3057
3058                 lpni = lnet_find_peer_ni_locked(msg->msg_hdr.dest_nid);
3059                 if (!lpni) {
3060                         lnet_net_unlock(cpt);
3061                         CERROR("Expected that a peer is already created for %s\n",
3062                                libcfs_nid2str(msg->msg_hdr.dest_nid));
3063                         msg->msg_no_resend = true;
3064                         lnet_finalize(msg, -EFAULT);
3065                         lnet_net_lock(cpt);
3066                 } else {
3067                         int rc;
3068
3069                         lnet_peer_ni_decref_locked(lpni);
3070
3071                         lnet_net_unlock(cpt);
3072                         CDEBUG(D_NET, "resending %s->%s: %s recovery %d try# %d\n",
3073                                libcfs_nid2str(msg->msg_src_nid_param),
3074                                libcfs_id2str(msg->msg_target),
3075                                lnet_msgtyp2str(msg->msg_type),
3076                                msg->msg_recovery,
3077                                msg->msg_retry_count);
3078                         rc = lnet_send(msg->msg_src_nid_param, msg,
3079                                        msg->msg_rtr_nid_param);
3080                         if (rc) {
3081                                 CERROR("Error sending %s to %s: %d\n",
3082                                        lnet_msgtyp2str(msg->msg_type),
3083                                        libcfs_id2str(msg->msg_target), rc);
3084                                 msg->msg_no_resend = true;
3085                                 lnet_finalize(msg, rc);
3086                         }
3087                         lnet_net_lock(cpt);
3088                         if (!rc)
3089                                 the_lnet.ln_counters[cpt]->lct_health.lch_resend_count++;
3090                 }
3091         }
3092 }
3093
3094 static void
3095 lnet_resend_pending_msgs(void)
3096 {
3097         int i;
3098
3099         cfs_cpt_for_each(i, lnet_cpt_table()) {
3100                 lnet_net_lock(i);
3101                 lnet_resend_pending_msgs_locked(the_lnet.ln_mt_resendqs[i], i);
3102                 lnet_net_unlock(i);
3103         }
3104 }
3105
3106 /* called with cpt and ni_lock held */
3107 static void
3108 lnet_unlink_ni_recovery_mdh_locked(struct lnet_ni *ni, int cpt, bool force)
3109 {
3110         struct lnet_handle_md recovery_mdh;
3111
3112         LNetInvalidateMDHandle(&recovery_mdh);
3113
3114         if (ni->ni_recovery_state & LNET_NI_RECOVERY_PENDING ||
3115             force) {
3116                 recovery_mdh = ni->ni_ping_mdh;
3117                 LNetInvalidateMDHandle(&ni->ni_ping_mdh);
3118         }
3119         lnet_ni_unlock(ni);
3120         lnet_net_unlock(cpt);
3121         if (!LNetMDHandleIsInvalid(recovery_mdh))
3122                 LNetMDUnlink(recovery_mdh);
3123         lnet_net_lock(cpt);
3124         lnet_ni_lock(ni);
3125 }
3126
3127 static void
3128 lnet_recover_local_nis(void)
3129 {
3130         struct lnet_mt_event_info *ev_info;
3131         LIST_HEAD(processed_list);
3132         LIST_HEAD(local_queue);
3133         struct lnet_handle_md mdh;
3134         struct lnet_ni *tmp;
3135         struct lnet_ni *ni;
3136         lnet_nid_t nid;
3137         int healthv;
3138         int rc;
3139
3140         /*
3141          * splice the recovery queue on a local queue. We will iterate
3142          * through the local queue and update it as needed. Once we're
3143          * done with the traversal, we'll splice the local queue back on
3144          * the head of the ln_mt_localNIRecovq. Any newly added local NIs
3145          * will be traversed in the next iteration.
3146          */
3147         lnet_net_lock(0);
3148         list_splice_init(&the_lnet.ln_mt_localNIRecovq,
3149                          &local_queue);
3150         lnet_net_unlock(0);
3151
3152         list_for_each_entry_safe(ni, tmp, &local_queue, ni_recovery) {
3153                 /*
3154                  * if an NI is being deleted or it is now healthy, there
3155                  * is no need to keep it around in the recovery queue.
3156                  * The monitor thread is the only thread responsible for
3157                  * removing the NI from the recovery queue.
3158                  * Multiple threads can be adding NIs to the recovery
3159                  * queue.
3160                  */
3161                 healthv = atomic_read(&ni->ni_healthv);
3162
3163                 lnet_net_lock(0);
3164                 lnet_ni_lock(ni);
3165                 if (ni->ni_state != LNET_NI_STATE_ACTIVE ||
3166                     healthv == LNET_MAX_HEALTH_VALUE) {
3167                         list_del_init(&ni->ni_recovery);
3168                         lnet_unlink_ni_recovery_mdh_locked(ni, 0, false);
3169                         lnet_ni_unlock(ni);
3170                         lnet_ni_decref_locked(ni, 0);
3171                         lnet_net_unlock(0);
3172                         continue;
3173                 }
3174
3175                 /*
3176                  * if the local NI failed recovery we must unlink the md.
3177                  * But we want to keep the local_ni on the recovery queue
3178                  * so we can continue the attempts to recover it.
3179                  */
3180                 if (ni->ni_recovery_state & LNET_NI_RECOVERY_FAILED) {
3181                         lnet_unlink_ni_recovery_mdh_locked(ni, 0, true);
3182                         ni->ni_recovery_state &= ~LNET_NI_RECOVERY_FAILED;
3183                 }
3184
3185                 lnet_ni_unlock(ni);
3186                 lnet_net_unlock(0);
3187
3188
3189                 CDEBUG(D_NET, "attempting to recover local ni: %s\n",
3190                        libcfs_nid2str(ni->ni_nid));
3191
3192                 lnet_ni_lock(ni);
3193                 if (!(ni->ni_recovery_state & LNET_NI_RECOVERY_PENDING)) {
3194                         ni->ni_recovery_state |= LNET_NI_RECOVERY_PENDING;
3195                         lnet_ni_unlock(ni);
3196
3197                         LIBCFS_ALLOC(ev_info, sizeof(*ev_info));
3198                         if (!ev_info) {
3199                                 CERROR("out of memory. Can't recover %s\n",
3200                                        libcfs_nid2str(ni->ni_nid));
3201                                 lnet_ni_lock(ni);
3202                                 ni->ni_recovery_state &=
3203                                   ~LNET_NI_RECOVERY_PENDING;
3204                                 lnet_ni_unlock(ni);
3205                                 continue;
3206                         }
3207
3208                         mdh = ni->ni_ping_mdh;
3209                         /*
3210                          * Invalidate the ni mdh in case it's deleted.
3211                          * We'll unlink the mdh in this case below.
3212                          */
3213                         LNetInvalidateMDHandle(&ni->ni_ping_mdh);
3214                         nid = ni->ni_nid;
3215
3216                         /*
3217                          * remove the NI from the local queue and drop the
3218                          * reference count to it while we're recovering
3219                          * it. The reason for that, is that the NI could
3220                          * be deleted, and the way the code is structured
3221                          * is if we don't drop the NI, then the deletion
3222                          * code will enter a loop waiting for the
3223                          * reference count to be removed while holding the
3224                          * ln_mutex_lock(). When we look up the peer to
3225                          * send to in lnet_select_pathway() we will try to
3226                          * lock the ln_mutex_lock() as well, leading to
3227                          * a deadlock. By dropping the refcount and
3228                          * removing it from the list, we allow for the NI
3229                          * to be removed, then we use the cached NID to
3230                          * look it up again. If it's gone, then we just
3231                          * continue examining the rest of the queue.
3232                          */
3233                         lnet_net_lock(0);
3234                         list_del_init(&ni->ni_recovery);
3235                         lnet_ni_decref_locked(ni, 0);
3236                         lnet_net_unlock(0);
3237
3238                         ev_info->mt_type = MT_TYPE_LOCAL_NI;
3239                         ev_info->mt_nid = nid;
3240                         rc = lnet_send_ping(nid, &mdh, LNET_INTERFACES_MIN,
3241                                             ev_info, the_lnet.ln_mt_handler,
3242                                             true);
3243                         /* lookup the nid again */
3244                         lnet_net_lock(0);
3245                         ni = lnet_nid2ni_locked(nid, 0);
3246                         if (!ni) {
3247                                 /*
3248                                  * the NI has been deleted when we dropped
3249                                  * the ref count
3250                                  */
3251                                 lnet_net_unlock(0);
3252                                 LNetMDUnlink(mdh);
3253                                 continue;
3254                         }
3255                         /*
3256                          * Same note as in lnet_recover_peer_nis(). When
3257                          * we're sending the ping, the NI is free to be
3258                          * deleted or manipulated. By this point it
3259                          * could've been added back on the recovery queue,
3260                          * and a refcount taken on it.
3261                          * So we can't just add it blindly again or we'll
3262                          * corrupt the queue. We must check under lock if
3263                          * it's not on any list and if not then add it
3264                          * to the processed list, which will eventually be
3265                          * spliced back on to the recovery queue.
3266                          */
3267                         ni->ni_ping_mdh = mdh;
3268                         if (list_empty(&ni->ni_recovery)) {
3269                                 list_add_tail(&ni->ni_recovery, &processed_list);
3270                                 lnet_ni_addref_locked(ni, 0);
3271                         }
3272                         lnet_net_unlock(0);
3273
3274                         lnet_ni_lock(ni);
3275                         if (rc)
3276                                 ni->ni_recovery_state &= ~LNET_NI_RECOVERY_PENDING;
3277                 }
3278                 lnet_ni_unlock(ni);
3279         }
3280
3281         /*
3282          * put back the remaining NIs on the ln_mt_localNIRecovq to be
3283          * reexamined in the next iteration.
3284          */
3285         list_splice_init(&processed_list, &local_queue);
3286         lnet_net_lock(0);
3287         list_splice(&local_queue, &the_lnet.ln_mt_localNIRecovq);
3288         lnet_net_unlock(0);
3289 }
3290
3291 static int
3292 lnet_resendqs_create(void)
3293 {
3294         struct list_head **resendqs;
3295         resendqs = lnet_create_array_of_queues();
3296
3297         if (!resendqs)
3298                 return -ENOMEM;
3299
3300         lnet_net_lock(LNET_LOCK_EX);
3301         the_lnet.ln_mt_resendqs = resendqs;
3302         lnet_net_unlock(LNET_LOCK_EX);
3303
3304         return 0;
3305 }
3306
3307 static void
3308 lnet_clean_local_ni_recoveryq(void)
3309 {
3310         struct lnet_ni *ni;
3311
3312         /* This is only called when the monitor thread has stopped */
3313         lnet_net_lock(0);
3314
3315         while (!list_empty(&the_lnet.ln_mt_localNIRecovq)) {
3316                 ni = list_entry(the_lnet.ln_mt_localNIRecovq.next,
3317                                 struct lnet_ni, ni_recovery);
3318                 list_del_init(&ni->ni_recovery);
3319                 lnet_ni_lock(ni);
3320                 lnet_unlink_ni_recovery_mdh_locked(ni, 0, true);
3321                 lnet_ni_unlock(ni);
3322                 lnet_ni_decref_locked(ni, 0);
3323         }
3324
3325         lnet_net_unlock(0);
3326 }
3327
3328 static void
3329 lnet_unlink_lpni_recovery_mdh_locked(struct lnet_peer_ni *lpni, int cpt,
3330                                      bool force)
3331 {
3332         struct lnet_handle_md recovery_mdh;
3333
3334         LNetInvalidateMDHandle(&recovery_mdh);
3335
3336         if (lpni->lpni_state & LNET_PEER_NI_RECOVERY_PENDING || force) {
3337                 recovery_mdh = lpni->lpni_recovery_ping_mdh;
3338                 LNetInvalidateMDHandle(&lpni->lpni_recovery_ping_mdh);
3339         }
3340         spin_unlock(&lpni->lpni_lock);
3341         lnet_net_unlock(cpt);
3342         if (!LNetMDHandleIsInvalid(recovery_mdh))
3343                 LNetMDUnlink(recovery_mdh);
3344         lnet_net_lock(cpt);
3345         spin_lock(&lpni->lpni_lock);
3346 }
3347
3348 static void
3349 lnet_clean_peer_ni_recoveryq(void)
3350 {
3351         struct lnet_peer_ni *lpni, *tmp;
3352
3353         lnet_net_lock(LNET_LOCK_EX);
3354
3355         list_for_each_entry_safe(lpni, tmp, &the_lnet.ln_mt_peerNIRecovq,
3356                                  lpni_recovery) {
3357                 list_del_init(&lpni->lpni_recovery);
3358                 spin_lock(&lpni->lpni_lock);
3359                 lnet_unlink_lpni_recovery_mdh_locked(lpni, LNET_LOCK_EX, true);
3360                 spin_unlock(&lpni->lpni_lock);
3361                 lnet_peer_ni_decref_locked(lpni);
3362         }
3363
3364         lnet_net_unlock(LNET_LOCK_EX);
3365 }
3366
3367 static void
3368 lnet_clean_resendqs(void)
3369 {
3370         struct lnet_msg *msg, *tmp;
3371         LIST_HEAD(msgs);
3372         int i;
3373
3374         cfs_cpt_for_each(i, lnet_cpt_table()) {
3375                 lnet_net_lock(i);
3376                 list_splice_init(the_lnet.ln_mt_resendqs[i], &msgs);
3377                 lnet_net_unlock(i);
3378                 list_for_each_entry_safe(msg, tmp, &msgs, msg_list) {
3379                         list_del_init(&msg->msg_list);
3380                         msg->msg_no_resend = true;
3381                         lnet_finalize(msg, -ESHUTDOWN);
3382                 }
3383         }
3384
3385         cfs_percpt_free(the_lnet.ln_mt_resendqs);
3386 }
3387
3388 static void
3389 lnet_recover_peer_nis(void)
3390 {
3391         struct lnet_mt_event_info *ev_info;
3392         LIST_HEAD(processed_list);
3393         LIST_HEAD(local_queue);
3394         struct lnet_handle_md mdh;
3395         struct lnet_peer_ni *lpni;
3396         struct lnet_peer_ni *tmp;
3397         lnet_nid_t nid;
3398         int healthv;
3399         int rc;
3400
3401         /*
3402          * Always use cpt 0 for locking across all interactions with
3403          * ln_mt_peerNIRecovq
3404          */
3405         lnet_net_lock(0);
3406         list_splice_init(&the_lnet.ln_mt_peerNIRecovq,
3407                          &local_queue);
3408         lnet_net_unlock(0);
3409
3410         list_for_each_entry_safe(lpni, tmp, &local_queue,
3411                                  lpni_recovery) {
3412                 /*
3413                  * The same protection strategy is used here as is in the
3414                  * local recovery case.
3415                  */
3416                 lnet_net_lock(0);
3417                 healthv = atomic_read(&lpni->lpni_healthv);
3418                 spin_lock(&lpni->lpni_lock);
3419                 if (lpni->lpni_state & LNET_PEER_NI_DELETING ||
3420                     healthv == LNET_MAX_HEALTH_VALUE) {
3421                         list_del_init(&lpni->lpni_recovery);
3422                         lnet_unlink_lpni_recovery_mdh_locked(lpni, 0, false);
3423                         spin_unlock(&lpni->lpni_lock);
3424                         lnet_peer_ni_decref_locked(lpni);
3425                         lnet_net_unlock(0);
3426                         continue;
3427                 }
3428
3429                 /*
3430                  * If the peer NI has failed recovery we must unlink the
3431                  * md. But we want to keep the peer ni on the recovery
3432                  * queue so we can try to continue recovering it
3433                  */
3434                 if (lpni->lpni_state & LNET_PEER_NI_RECOVERY_FAILED) {
3435                         lnet_unlink_lpni_recovery_mdh_locked(lpni, 0, true);
3436                         lpni->lpni_state &= ~LNET_PEER_NI_RECOVERY_FAILED;
3437                 }
3438
3439                 spin_unlock(&lpni->lpni_lock);
3440                 lnet_net_unlock(0);
3441
3442                 /*
3443                  * NOTE: we're racing with peer deletion from user space.
3444                  * It's possible that a peer is deleted after we check its
3445                  * state. In this case the recovery can create a new peer
3446                  */
3447                 spin_lock(&lpni->lpni_lock);
3448                 if (!(lpni->lpni_state & LNET_PEER_NI_RECOVERY_PENDING) &&
3449                     !(lpni->lpni_state & LNET_PEER_NI_DELETING)) {
3450                         lpni->lpni_state |= LNET_PEER_NI_RECOVERY_PENDING;
3451                         spin_unlock(&lpni->lpni_lock);
3452
3453                         LIBCFS_ALLOC(ev_info, sizeof(*ev_info));
3454                         if (!ev_info) {
3455                                 CERROR("out of memory. Can't recover %s\n",
3456                                        libcfs_nid2str(lpni->lpni_nid));
3457                                 spin_lock(&lpni->lpni_lock);
3458                                 lpni->lpni_state &= ~LNET_PEER_NI_RECOVERY_PENDING;
3459                                 spin_unlock(&lpni->lpni_lock);
3460                                 continue;
3461                         }
3462
3463                         /* look at the comments in lnet_recover_local_nis() */
3464                         mdh = lpni->lpni_recovery_ping_mdh;
3465                         LNetInvalidateMDHandle(&lpni->lpni_recovery_ping_mdh);
3466                         nid = lpni->lpni_nid;
3467                         lnet_net_lock(0);
3468                         list_del_init(&lpni->lpni_recovery);
3469                         lnet_peer_ni_decref_locked(lpni);
3470                         lnet_net_unlock(0);
3471
3472                         ev_info->mt_type = MT_TYPE_PEER_NI;
3473                         ev_info->mt_nid = nid;
3474                         rc = lnet_send_ping(nid, &mdh, LNET_INTERFACES_MIN,
3475                                             ev_info, the_lnet.ln_mt_handler,
3476                                             true);
3477                         lnet_net_lock(0);
3478                         /*
3479                          * lnet_find_peer_ni_locked() grabs a refcount for
3480                          * us. No need to take it explicitly.
3481                          */
3482                         lpni = lnet_find_peer_ni_locked(nid);
3483                         if (!lpni) {
3484                                 lnet_net_unlock(0);
3485                                 LNetMDUnlink(mdh);
3486                                 continue;
3487                         }
3488
3489                         lpni->lpni_recovery_ping_mdh = mdh;
3490                         /*
3491                          * While we're unlocked the lpni could've been
3492                          * readded on the recovery queue. In this case we
3493                          * don't need to add it to the local queue, since
3494                          * it's already on there and the thread that added
3495                          * it would've incremented the refcount on the
3496                          * peer, which means we need to decref the refcount
3497                          * that was implicitly grabbed by find_peer_ni_locked.
3498                          * Otherwise, if the lpni is still not on
3499                          * the recovery queue, then we'll add it to the
3500                          * processed list.
3501                          */
3502                         if (list_empty(&lpni->lpni_recovery))
3503                                 list_add_tail(&lpni->lpni_recovery, &processed_list);
3504                         else
3505                                 lnet_peer_ni_decref_locked(lpni);
3506                         lnet_net_unlock(0);
3507
3508                         spin_lock(&lpni->lpni_lock);
3509                         if (rc)
3510                                 lpni->lpni_state &= ~LNET_PEER_NI_RECOVERY_PENDING;
3511                 }
3512                 spin_unlock(&lpni->lpni_lock);
3513         }
3514
3515         list_splice_init(&processed_list, &local_queue);
3516         lnet_net_lock(0);
3517         list_splice(&local_queue, &the_lnet.ln_mt_peerNIRecovq);
3518         lnet_net_unlock(0);
3519 }
3520
3521 static int
3522 lnet_monitor_thread(void *arg)
3523 {
3524         time64_t recovery_timeout = 0;
3525         time64_t rsp_timeout = 0;
3526         int interval;
3527         time64_t now;
3528
3529         wait_for_completion(&the_lnet.ln_started);
3530         /*
3531          * The monitor thread takes care of the following:
3532          *  1. Checks the aliveness of routers
3533          *  2. Checks if there are messages on the resend queue to resend
3534          *     them.
3535          *  3. Check if there are any NIs on the local recovery queue and
3536          *     pings them
3537          *  4. Checks if there are any NIs on the remote recovery queue
3538          *     and pings them.
3539          */
3540         while (the_lnet.ln_mt_state == LNET_MT_STATE_RUNNING) {
3541                 now = ktime_get_real_seconds();
3542
3543                 if (lnet_router_checker_active())
3544                         lnet_check_routers();
3545
3546                 lnet_resend_pending_msgs();
3547
3548                 if (now >= rsp_timeout) {
3549                         lnet_finalize_expired_responses();
3550                         rsp_timeout = now + (lnet_transaction_timeout / 2);
3551                 }
3552
3553                 if (now >= recovery_timeout) {
3554                         lnet_recover_local_nis();
3555                         lnet_recover_peer_nis();
3556                         recovery_timeout = now + lnet_recovery_interval;
3557                 }
3558
3559                 /*
3560                  * TODO do we need to check if we should sleep without
3561                  * timeout?  Technically, an active system will always
3562                  * have messages in flight so this check will always
3563                  * evaluate to false. And on an idle system do we care
3564                  * if we wake up every 1 second? Although, we've seen
3565                  * cases where we get a complaint that an idle thread
3566                  * is waking up unnecessarily.
3567                  *
3568                  * Take into account the current net_count when you wake
3569                  * up for alive router checking, since we need to check
3570                  * possibly as many networks as we have configured.
3571                  */
3572                 interval = min(lnet_recovery_interval,
3573                                min((unsigned int) alive_router_check_interval /
3574                                         lnet_current_net_count,
3575                                    lnet_transaction_timeout / 2));
3576                 wait_for_completion_interruptible_timeout(
3577                         &the_lnet.ln_mt_wait_complete,
3578                         cfs_time_seconds(interval));
3579                 /* Must re-init the completion before testing anything,
3580                  * including ln_mt_state.
3581                  */
3582                 reinit_completion(&the_lnet.ln_mt_wait_complete);
3583         }
3584
3585         /* Shutting down */
3586         lnet_net_lock(LNET_LOCK_EX);
3587         the_lnet.ln_mt_state = LNET_MT_STATE_SHUTDOWN;
3588         lnet_net_unlock(LNET_LOCK_EX);
3589
3590         /* signal that the monitor thread is exiting */
3591         up(&the_lnet.ln_mt_signal);
3592
3593         return 0;
3594 }
3595
3596 /*
3597  * lnet_send_ping
3598  * Sends a ping.
3599  * Returns == 0 if success
3600  * Returns > 0 if LNetMDBind or prior fails
3601  * Returns < 0 if LNetGet fails
3602  */
3603 int
3604 lnet_send_ping(lnet_nid_t dest_nid,
3605                struct lnet_handle_md *mdh, int nnis,
3606                void *user_data, lnet_handler_t handler, bool recovery)
3607 {
3608         struct lnet_md md = { NULL };
3609         struct lnet_process_id id;
3610         struct lnet_ping_buffer *pbuf;
3611         int rc;
3612
3613         if (dest_nid == LNET_NID_ANY) {
3614                 rc = -EHOSTUNREACH;
3615                 goto fail_error;
3616         }
3617
3618         pbuf = lnet_ping_buffer_alloc(nnis, GFP_NOFS);
3619         if (!pbuf) {
3620                 rc = ENOMEM;
3621                 goto fail_error;
3622         }
3623
3624         /* initialize md content */
3625         md.start     = &pbuf->pb_info;
3626         md.length    = LNET_PING_INFO_SIZE(nnis);
3627         md.threshold = 2; /* GET/REPLY */
3628         md.max_size  = 0;
3629         md.options   = LNET_MD_TRUNCATE | LNET_MD_TRACK_RESPONSE;
3630         md.user_ptr  = user_data;
3631         md.handler   = handler;
3632
3633         rc = LNetMDBind(&md, LNET_UNLINK, mdh);
3634         if (rc) {
3635                 lnet_ping_buffer_decref(pbuf);
3636                 CERROR("Can't bind MD: %d\n", rc);
3637                 rc = -rc; /* change the rc to positive */
3638                 goto fail_error;
3639         }
3640         id.pid = LNET_PID_LUSTRE;
3641         id.nid = dest_nid;
3642
3643         rc = LNetGet(LNET_NID_ANY, *mdh, id,
3644                      LNET_RESERVED_PORTAL,
3645                      LNET_PROTO_PING_MATCHBITS, 0, recovery);
3646
3647         if (rc)
3648                 goto fail_unlink_md;
3649
3650         return 0;
3651
3652 fail_unlink_md:
3653         LNetMDUnlink(*mdh);
3654         LNetInvalidateMDHandle(mdh);
3655 fail_error:
3656         return rc;
3657 }
3658
3659 static void
3660 lnet_handle_recovery_reply(struct lnet_mt_event_info *ev_info,
3661                            int status, bool send, bool unlink_event)
3662 {
3663         lnet_nid_t nid = ev_info->mt_nid;
3664
3665         if (ev_info->mt_type == MT_TYPE_LOCAL_NI) {
3666                 struct lnet_ni *ni;
3667
3668                 lnet_net_lock(0);
3669                 ni = lnet_nid2ni_locked(nid, 0);
3670                 if (!ni) {
3671                         lnet_net_unlock(0);
3672                         return;
3673                 }
3674                 lnet_ni_lock(ni);
3675                 if (!send || (send && status != 0))
3676                         ni->ni_recovery_state &= ~LNET_NI_RECOVERY_PENDING;
3677                 if (status)
3678                         ni->ni_recovery_state |= LNET_NI_RECOVERY_FAILED;
3679                 lnet_ni_unlock(ni);
3680                 lnet_net_unlock(0);
3681
3682                 if (status != 0) {
3683                         CERROR("local NI (%s) recovery failed with %d\n",
3684                                libcfs_nid2str(nid), status);
3685                         return;
3686                 }
3687                 /*
3688                  * need to increment healthv for the ni here, because in
3689                  * the lnet_finalize() path we don't have access to this
3690                  * NI. And in order to get access to it, we'll need to
3691                  * carry forward too much information.
3692                  * In the peer case, it'll naturally be incremented
3693     &nb