Whamcloud - gitweb
2d8c96720ffcf826259051164b302ec30cb9f09c
[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  *
31  * lnet/lnet/lib-move.c
32  *
33  * Data movement routines
34  */
35
36 #define DEBUG_SUBSYSTEM S_LNET
37
38 #include <linux/pagemap.h>
39
40 #include <lnet/lib-lnet.h>
41 #include <linux/nsproxy.h>
42 #include <lnet/lnet_rdma.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         struct lnet_nid sd_dst_nid;
59         struct lnet_nid sd_src_nid;
60         struct lnet_nid 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 bool
73 lnet_response_tracking_enabled(__u32 msg_type, unsigned int md_options)
74 {
75         if (md_options & LNET_MD_NO_TRACK_RESPONSE)
76                 /* Explicitly disabled in MD options */
77                 return false;
78
79         if (md_options & LNET_MD_TRACK_RESPONSE)
80                 /* Explicity enabled in MD options */
81                 return true;
82
83         if (lnet_response_tracking == 3)
84                 /* Enabled for all message types */
85                 return true;
86
87         if (msg_type == LNET_MSG_PUT)
88                 return lnet_response_tracking == 2;
89
90         if (msg_type == LNET_MSG_GET)
91                 return lnet_response_tracking == 1;
92
93         return false;
94 }
95
96 static inline struct lnet_comm_count *
97 get_stats_counts(struct lnet_element_stats *stats,
98                  enum lnet_stats_type stats_type)
99 {
100         switch (stats_type) {
101         case LNET_STATS_TYPE_SEND:
102                 return &stats->el_send_stats;
103         case LNET_STATS_TYPE_RECV:
104                 return &stats->el_recv_stats;
105         case LNET_STATS_TYPE_DROP:
106                 return &stats->el_drop_stats;
107         default:
108                 CERROR("Unknown stats type\n");
109         }
110
111         return NULL;
112 }
113
114 void lnet_incr_stats(struct lnet_element_stats *stats,
115                      enum lnet_msg_type msg_type,
116                      enum lnet_stats_type stats_type)
117 {
118         struct lnet_comm_count *counts = get_stats_counts(stats, stats_type);
119         if (!counts)
120                 return;
121
122         switch (msg_type) {
123         case LNET_MSG_ACK:
124                 atomic_inc(&counts->co_ack_count);
125                 break;
126         case LNET_MSG_PUT:
127                 atomic_inc(&counts->co_put_count);
128                 break;
129         case LNET_MSG_GET:
130                 atomic_inc(&counts->co_get_count);
131                 break;
132         case LNET_MSG_REPLY:
133                 atomic_inc(&counts->co_reply_count);
134                 break;
135         case LNET_MSG_HELLO:
136                 atomic_inc(&counts->co_hello_count);
137                 break;
138         default:
139                 CERROR("There is a BUG in the code. Unknown message type\n");
140                 break;
141         }
142 }
143
144 __u32 lnet_sum_stats(struct lnet_element_stats *stats,
145                      enum lnet_stats_type stats_type)
146 {
147         struct lnet_comm_count *counts = get_stats_counts(stats, stats_type);
148         if (!counts)
149                 return 0;
150
151         return (atomic_read(&counts->co_ack_count) +
152                 atomic_read(&counts->co_put_count) +
153                 atomic_read(&counts->co_get_count) +
154                 atomic_read(&counts->co_reply_count) +
155                 atomic_read(&counts->co_hello_count));
156 }
157
158 static inline void assign_stats(struct lnet_ioctl_comm_count *msg_stats,
159                                 struct lnet_comm_count *counts)
160 {
161         msg_stats->ico_get_count = atomic_read(&counts->co_get_count);
162         msg_stats->ico_put_count = atomic_read(&counts->co_put_count);
163         msg_stats->ico_reply_count = atomic_read(&counts->co_reply_count);
164         msg_stats->ico_ack_count = atomic_read(&counts->co_ack_count);
165         msg_stats->ico_hello_count = atomic_read(&counts->co_hello_count);
166 }
167
168 void lnet_usr_translate_stats(struct lnet_ioctl_element_msg_stats *msg_stats,
169                               struct lnet_element_stats *stats)
170 {
171         struct lnet_comm_count *counts;
172
173         LASSERT(msg_stats);
174         LASSERT(stats);
175
176         counts = get_stats_counts(stats, LNET_STATS_TYPE_SEND);
177         if (!counts)
178                 return;
179         assign_stats(&msg_stats->im_send_stats, counts);
180
181         counts = get_stats_counts(stats, LNET_STATS_TYPE_RECV);
182         if (!counts)
183                 return;
184         assign_stats(&msg_stats->im_recv_stats, counts);
185
186         counts = get_stats_counts(stats, LNET_STATS_TYPE_DROP);
187         if (!counts)
188                 return;
189         assign_stats(&msg_stats->im_drop_stats, counts);
190 }
191
192 int
193 lnet_fail_nid(lnet_nid_t nid4, unsigned int threshold)
194 {
195         struct lnet_test_peer *tp;
196         struct list_head *el;
197         struct list_head *next;
198         struct lnet_nid nid;
199         LIST_HEAD(cull);
200
201         lnet_nid4_to_nid(nid4, &nid);
202         /* NB: use lnet_net_lock(0) to serialize operations on test peers */
203         if (threshold != 0) {
204                 /* Adding a new entry */
205                 LIBCFS_ALLOC(tp, sizeof(*tp));
206                 if (tp == NULL)
207                         return -ENOMEM;
208
209                 tp->tp_nid = nid;
210                 tp->tp_threshold = threshold;
211
212                 lnet_net_lock(0);
213                 list_add_tail(&tp->tp_list, &the_lnet.ln_test_peers);
214                 lnet_net_unlock(0);
215                 return 0;
216         }
217
218         lnet_net_lock(0);
219
220         list_for_each_safe(el, next, &the_lnet.ln_test_peers) {
221                 tp = list_entry(el, struct lnet_test_peer, tp_list);
222
223                 if (tp->tp_threshold == 0 ||    /* needs culling anyway */
224                     LNET_NID_IS_ANY(&nid) ||    /* removing all entries */
225                     nid_same(&tp->tp_nid, &nid)) {      /* matched this one */
226                         list_move(&tp->tp_list, &cull);
227                 }
228         }
229
230         lnet_net_unlock(0);
231
232         while ((tp = list_first_entry_or_null(&cull,
233                                               struct lnet_test_peer,
234                                               tp_list)) != NULL) {
235                 list_del(&tp->tp_list);
236                 LIBCFS_FREE(tp, sizeof(*tp));
237         }
238         return 0;
239 }
240
241 static int
242 fail_peer(struct lnet_nid *nid, int outgoing)
243 {
244         struct lnet_test_peer *tp;
245         struct list_head *el;
246         struct list_head *next;
247         LIST_HEAD(cull);
248         int fail = 0;
249
250         /* NB: use lnet_net_lock(0) to serialize operations on test peers */
251         lnet_net_lock(0);
252
253         list_for_each_safe(el, next, &the_lnet.ln_test_peers) {
254                 tp = list_entry(el, struct lnet_test_peer, tp_list);
255
256                 if (tp->tp_threshold == 0) {
257                         /* zombie entry */
258                         if (outgoing) {
259                                 /* only cull zombies on outgoing tests,
260                                  * since we may be at interrupt priority on
261                                  * incoming messages. */
262                                 list_move(&tp->tp_list, &cull);
263                         }
264                         continue;
265                 }
266
267                 if (LNET_NID_IS_ANY(&tp->tp_nid) ||     /* fail every peer */
268                     nid_same(nid, &tp->tp_nid)) {       /* fail this peer */
269                         fail = 1;
270
271                         if (tp->tp_threshold != LNET_MD_THRESH_INF) {
272                                 tp->tp_threshold--;
273                                 if (outgoing &&
274                                     tp->tp_threshold == 0) {
275                                         /* see above */
276                                         list_move(&tp->tp_list, &cull);
277                                 }
278                         }
279                         break;
280                 }
281         }
282
283         lnet_net_unlock(0);
284
285         while ((tp = list_first_entry_or_null(&cull,
286                                               struct lnet_test_peer,
287                                               tp_list)) != NULL) {
288                 list_del(&tp->tp_list);
289                 LIBCFS_FREE(tp, sizeof(*tp));
290         }
291
292         return fail;
293 }
294
295 unsigned int
296 lnet_iov_nob(unsigned int niov, struct kvec *iov)
297 {
298         unsigned int nob = 0;
299
300         LASSERT(niov == 0 || iov != NULL);
301         while (niov-- > 0)
302                 nob += (iov++)->iov_len;
303
304         return (nob);
305 }
306 EXPORT_SYMBOL(lnet_iov_nob);
307
308 void
309 lnet_copy_iov2iov(unsigned int ndiov, struct kvec *diov, unsigned int doffset,
310                   unsigned int nsiov, struct kvec *siov, unsigned int soffset,
311                   unsigned int nob)
312 {
313         /* NB diov, siov are READ-ONLY */
314         unsigned int this_nob;
315
316         if (nob == 0)
317                 return;
318
319         /* skip complete frags before 'doffset' */
320         LASSERT(ndiov > 0);
321         while (doffset >= diov->iov_len) {
322                 doffset -= diov->iov_len;
323                 diov++;
324                 ndiov--;
325                 LASSERT(ndiov > 0);
326         }
327
328         /* skip complete frags before 'soffset' */
329         LASSERT(nsiov > 0);
330         while (soffset >= siov->iov_len) {
331                 soffset -= siov->iov_len;
332                 siov++;
333                 nsiov--;
334                 LASSERT(nsiov > 0);
335         }
336
337         do {
338                 LASSERT(ndiov > 0);
339                 LASSERT(nsiov > 0);
340                 this_nob = min3((unsigned int)diov->iov_len - doffset,
341                                 (unsigned int)siov->iov_len - soffset,
342                                 nob);
343
344                 memcpy((char *)diov->iov_base + doffset,
345                        (char *)siov->iov_base + soffset, this_nob);
346                 nob -= this_nob;
347
348                 if (diov->iov_len > doffset + this_nob) {
349                         doffset += this_nob;
350                 } else {
351                         diov++;
352                         ndiov--;
353                         doffset = 0;
354                 }
355
356                 if (siov->iov_len > soffset + this_nob) {
357                         soffset += this_nob;
358                 } else {
359                         siov++;
360                         nsiov--;
361                         soffset = 0;
362                 }
363         } while (nob > 0);
364 }
365 EXPORT_SYMBOL(lnet_copy_iov2iov);
366
367 unsigned int
368 lnet_kiov_nob(unsigned int niov, struct bio_vec *kiov)
369 {
370         unsigned int  nob = 0;
371
372         LASSERT(niov == 0 || kiov != NULL);
373         while (niov-- > 0)
374                 nob += (kiov++)->bv_len;
375
376         return (nob);
377 }
378 EXPORT_SYMBOL(lnet_kiov_nob);
379
380 void
381 lnet_copy_kiov2kiov(unsigned int ndiov, struct bio_vec *diov,
382                     unsigned int doffset,
383                     unsigned int nsiov, struct bio_vec *siov,
384                     unsigned int soffset,
385                     unsigned int nob)
386 {
387         /* NB diov, siov are READ-ONLY */
388         unsigned int    this_nob;
389         char           *daddr = NULL;
390         char           *saddr = NULL;
391
392         if (nob == 0)
393                 return;
394
395         LASSERT (!in_interrupt ());
396
397         LASSERT (ndiov > 0);
398         while (doffset >= diov->bv_len) {
399                 doffset -= diov->bv_len;
400                 diov++;
401                 ndiov--;
402                 LASSERT(ndiov > 0);
403         }
404
405         LASSERT(nsiov > 0);
406         while (soffset >= siov->bv_len) {
407                 soffset -= siov->bv_len;
408                 siov++;
409                 nsiov--;
410                 LASSERT(nsiov > 0);
411         }
412
413         do {
414                 LASSERT(ndiov > 0);
415                 LASSERT(nsiov > 0);
416                 this_nob = min3(diov->bv_len - doffset,
417                                 siov->bv_len - soffset,
418                                 nob);
419
420                 if (daddr == NULL)
421                         daddr = ((char *)kmap(diov->bv_page)) +
422                                 diov->bv_offset + doffset;
423                 if (saddr == NULL)
424                         saddr = ((char *)kmap(siov->bv_page)) +
425                                 siov->bv_offset + soffset;
426
427                 /* Vanishing risk of kmap deadlock when mapping 2 pages.
428                  * However in practice at least one of the kiovs will be mapped
429                  * kernel pages and the map/unmap will be NOOPs */
430
431                 memcpy (daddr, saddr, this_nob);
432                 nob -= this_nob;
433
434                 if (diov->bv_len > doffset + this_nob) {
435                         daddr += this_nob;
436                         doffset += this_nob;
437                 } else {
438                         kunmap(diov->bv_page);
439                         daddr = NULL;
440                         diov++;
441                         ndiov--;
442                         doffset = 0;
443                 }
444
445                 if (siov->bv_len > soffset + this_nob) {
446                         saddr += this_nob;
447                         soffset += this_nob;
448                 } else {
449                         kunmap(siov->bv_page);
450                         saddr = NULL;
451                         siov++;
452                         nsiov--;
453                         soffset = 0;
454                 }
455         } while (nob > 0);
456
457         if (daddr != NULL)
458                 kunmap(diov->bv_page);
459         if (saddr != NULL)
460                 kunmap(siov->bv_page);
461 }
462 EXPORT_SYMBOL(lnet_copy_kiov2kiov);
463
464 void
465 lnet_copy_kiov2iov (unsigned int niov, struct kvec *iov, unsigned int iovoffset,
466                     unsigned int nkiov, struct bio_vec *kiov,
467                     unsigned int kiovoffset,
468                     unsigned int nob)
469 {
470         /* NB iov, kiov are READ-ONLY */
471         unsigned int    this_nob;
472         char           *addr = NULL;
473
474         if (nob == 0)
475                 return;
476
477         LASSERT (!in_interrupt ());
478
479         LASSERT (niov > 0);
480         while (iovoffset >= iov->iov_len) {
481                 iovoffset -= iov->iov_len;
482                 iov++;
483                 niov--;
484                 LASSERT(niov > 0);
485         }
486
487         LASSERT(nkiov > 0);
488         while (kiovoffset >= kiov->bv_len) {
489                 kiovoffset -= kiov->bv_len;
490                 kiov++;
491                 nkiov--;
492                 LASSERT(nkiov > 0);
493         }
494
495         do {
496                 LASSERT(niov > 0);
497                 LASSERT(nkiov > 0);
498                 this_nob = min3((unsigned int)iov->iov_len - iovoffset,
499                                 (unsigned int)kiov->bv_len - kiovoffset,
500                                 nob);
501
502                 if (addr == NULL)
503                         addr = ((char *)kmap(kiov->bv_page)) +
504                                 kiov->bv_offset + kiovoffset;
505
506                 memcpy((char *)iov->iov_base + iovoffset, addr, this_nob);
507                 nob -= this_nob;
508
509                 if (iov->iov_len > iovoffset + this_nob) {
510                         iovoffset += this_nob;
511                 } else {
512                         iov++;
513                         niov--;
514                         iovoffset = 0;
515                 }
516
517                 if (kiov->bv_len > kiovoffset + this_nob) {
518                         addr += this_nob;
519                         kiovoffset += this_nob;
520                 } else {
521                         kunmap(kiov->bv_page);
522                         addr = NULL;
523                         kiov++;
524                         nkiov--;
525                         kiovoffset = 0;
526                 }
527
528         } while (nob > 0);
529
530         if (addr != NULL)
531                 kunmap(kiov->bv_page);
532 }
533 EXPORT_SYMBOL(lnet_copy_kiov2iov);
534
535 void
536 lnet_copy_iov2kiov(unsigned int nkiov, struct bio_vec *kiov,
537                    unsigned int kiovoffset,
538                    unsigned int niov, struct kvec *iov, unsigned int iovoffset,
539                    unsigned int nob)
540 {
541         /* NB kiov, iov are READ-ONLY */
542         unsigned int    this_nob;
543         char           *addr = NULL;
544
545         if (nob == 0)
546                 return;
547
548         LASSERT (!in_interrupt ());
549
550         LASSERT (nkiov > 0);
551         while (kiovoffset >= kiov->bv_len) {
552                 kiovoffset -= kiov->bv_len;
553                 kiov++;
554                 nkiov--;
555                 LASSERT(nkiov > 0);
556         }
557
558         LASSERT(niov > 0);
559         while (iovoffset >= iov->iov_len) {
560                 iovoffset -= iov->iov_len;
561                 iov++;
562                 niov--;
563                 LASSERT(niov > 0);
564         }
565
566         do {
567                 LASSERT(nkiov > 0);
568                 LASSERT(niov > 0);
569                 this_nob = min3((unsigned int)kiov->bv_len - kiovoffset,
570                                 (unsigned int)iov->iov_len - iovoffset,
571                                 nob);
572
573                 if (addr == NULL)
574                         addr = ((char *)kmap(kiov->bv_page)) +
575                                 kiov->bv_offset + kiovoffset;
576
577                 memcpy (addr, (char *)iov->iov_base + iovoffset, this_nob);
578                 nob -= this_nob;
579
580                 if (kiov->bv_len > kiovoffset + this_nob) {
581                         addr += this_nob;
582                         kiovoffset += this_nob;
583                 } else {
584                         kunmap(kiov->bv_page);
585                         addr = NULL;
586                         kiov++;
587                         nkiov--;
588                         kiovoffset = 0;
589                 }
590
591                 if (iov->iov_len > iovoffset + this_nob) {
592                         iovoffset += this_nob;
593                 } else {
594                         iov++;
595                         niov--;
596                         iovoffset = 0;
597                 }
598         } while (nob > 0);
599
600         if (addr != NULL)
601                 kunmap(kiov->bv_page);
602 }
603 EXPORT_SYMBOL(lnet_copy_iov2kiov);
604
605 int
606 lnet_extract_kiov(int dst_niov, struct bio_vec *dst,
607                   int src_niov, struct bio_vec *src,
608                   unsigned int offset, unsigned int len)
609 {
610         /* Initialise 'dst' to the subset of 'src' starting at 'offset',
611          * for exactly 'len' bytes, and return the number of entries.
612          * NB not destructive to 'src' */
613         unsigned int    frag_len;
614         unsigned int    niov;
615
616         if (len == 0)                           /* no data => */
617                 return (0);                     /* no frags */
618
619         LASSERT(src_niov > 0);
620         while (offset >= src->bv_len) {      /* skip initial frags */
621                 offset -= src->bv_len;
622                 src_niov--;
623                 src++;
624                 LASSERT(src_niov > 0);
625         }
626
627         niov = 1;
628         for (;;) {
629                 LASSERT(src_niov > 0);
630                 LASSERT((int)niov <= dst_niov);
631
632                 frag_len = src->bv_len - offset;
633                 dst->bv_page = src->bv_page;
634                 dst->bv_offset = src->bv_offset + offset;
635
636                 if (len <= frag_len) {
637                         dst->bv_len = len;
638                         LASSERT(dst->bv_offset + dst->bv_len <= PAGE_SIZE);
639                         return niov;
640                 }
641
642                 dst->bv_len = frag_len;
643                 LASSERT(dst->bv_offset + dst->bv_len <= PAGE_SIZE);
644
645                 len -= frag_len;
646                 dst++;
647                 src++;
648                 niov++;
649                 src_niov--;
650                 offset = 0;
651         }
652 }
653 EXPORT_SYMBOL(lnet_extract_kiov);
654
655 void
656 lnet_ni_recv(struct lnet_ni *ni, void *private, struct lnet_msg *msg,
657              int delayed, unsigned int offset, unsigned int mlen,
658              unsigned int rlen)
659 {
660         unsigned int niov = 0;
661         struct kvec *iov = NULL;
662         struct bio_vec  *kiov = NULL;
663         int rc;
664
665         LASSERT (!in_interrupt ());
666         LASSERT (mlen == 0 || msg != NULL);
667
668         if (msg != NULL) {
669                 LASSERT(msg->msg_receiving);
670                 LASSERT(!msg->msg_sending);
671                 LASSERT(rlen == msg->msg_len);
672                 LASSERT(mlen <= msg->msg_len);
673                 LASSERT(msg->msg_offset == offset);
674                 LASSERT(msg->msg_wanted == mlen);
675
676                 msg->msg_receiving = 0;
677
678                 if (mlen != 0) {
679                         niov = msg->msg_niov;
680                         kiov = msg->msg_kiov;
681
682                         LASSERT (niov > 0);
683                         LASSERT ((iov == NULL) != (kiov == NULL));
684                 }
685         }
686
687         rc = (ni->ni_net->net_lnd->lnd_recv)(ni, private, msg, delayed,
688                                              niov, kiov, offset, mlen,
689                                              rlen);
690         if (rc < 0)
691                 lnet_finalize(msg, rc);
692 }
693
694 static void
695 lnet_setpayloadbuffer(struct lnet_msg *msg)
696 {
697         struct lnet_libmd *md = msg->msg_md;
698
699         LASSERT(msg->msg_len > 0);
700         LASSERT(!msg->msg_routing);
701         LASSERT(md != NULL);
702         LASSERT(msg->msg_niov == 0);
703         LASSERT(msg->msg_kiov == NULL);
704
705         msg->msg_niov = md->md_niov;
706         msg->msg_kiov = md->md_kiov;
707 }
708
709 void
710 lnet_prep_send(struct lnet_msg *msg, int type, struct lnet_processid *target,
711                unsigned int offset, unsigned int len)
712 {
713         msg->msg_type = type;
714         msg->msg_target = *target;
715         msg->msg_len = len;
716         msg->msg_offset = offset;
717
718         if (len != 0)
719                 lnet_setpayloadbuffer(msg);
720
721         memset (&msg->msg_hdr, 0, sizeof (msg->msg_hdr));
722         msg->msg_hdr.type           = type;
723         /* dest_nid will be overwritten by lnet_select_pathway() */
724         msg->msg_hdr.dest_nid = target->nid;
725         msg->msg_hdr.dest_pid = target->pid;
726         /* src_nid will be set later */
727         msg->msg_hdr.src_pid        = the_lnet.ln_pid;
728         msg->msg_hdr.payload_length = len;
729 }
730
731 void
732 lnet_ni_send(struct lnet_ni *ni, struct lnet_msg *msg)
733 {
734         void *priv = msg->msg_private;
735         int rc;
736
737         LASSERT(!in_interrupt());
738         LASSERT(nid_is_lo0(&ni->ni_nid) ||
739                 (msg->msg_txcredit && msg->msg_peertxcredit));
740
741         rc = (ni->ni_net->net_lnd->lnd_send)(ni, priv, msg);
742         if (rc < 0) {
743                 msg->msg_no_resend = true;
744                 lnet_finalize(msg, rc);
745         }
746 }
747
748 static int
749 lnet_ni_eager_recv(struct lnet_ni *ni, struct lnet_msg *msg)
750 {
751         int     rc;
752
753         LASSERT(!msg->msg_sending);
754         LASSERT(msg->msg_receiving);
755         LASSERT(!msg->msg_rx_ready_delay);
756         LASSERT(ni->ni_net->net_lnd->lnd_eager_recv != NULL);
757
758         msg->msg_rx_ready_delay = 1;
759         rc = (ni->ni_net->net_lnd->lnd_eager_recv)(ni, msg->msg_private, msg,
760                                                   &msg->msg_private);
761         if (rc != 0) {
762                 CERROR("recv from %s / send to %s aborted: "
763                        "eager_recv failed %d\n",
764                        libcfs_nidstr(&msg->msg_rxpeer->lpni_nid),
765                        libcfs_idstr(&msg->msg_target), rc);
766                 LASSERT(rc < 0); /* required by my callers */
767         }
768
769         return rc;
770 }
771
772 /* Returns:
773  *  -ETIMEDOUT if the message deadline has been exceeded
774  *  -EHOSTUNREACH if the peer is down
775  *  0 if this message should not be dropped
776  */
777 static int
778 lnet_check_message_drop(struct lnet_ni *ni, struct lnet_peer_ni *lpni,
779                         struct lnet_msg *msg)
780 {
781         /* Drop message if we've exceeded the message deadline */
782         if (ktime_after(ktime_get(), msg->msg_deadline))
783                 return -ETIMEDOUT;
784
785         if (msg->msg_target.pid & LNET_PID_USERFLAG)
786                 return 0;
787
788         if (!lnet_peer_aliveness_enabled(lpni))
789                 return 0;
790
791         /* If we're resending a message, let's attempt to send it even if
792          * the peer is down to fulfill our resend quota on the message
793          */
794         if (msg->msg_retry_count > 0)
795                 return 0;
796
797         /* try and send recovery messages regardless */
798         if (msg->msg_recovery)
799                 return 0;
800
801         /* always send any responses */
802         if (lnet_msg_is_response(msg))
803                 return 0;
804
805         /* always send non-routed messages */
806         if (!msg->msg_routing)
807                 return 0;
808
809         /* assume peer_ni is alive as long as we're within the configured
810          * peer timeout
811          */
812         if (ktime_get_seconds() <
813             (lpni->lpni_last_alive +
814              lpni->lpni_net->net_tunables.lct_peer_timeout))
815                 return 0;
816
817         if (!lnet_is_peer_ni_alive(lpni))
818                 return -EHOSTUNREACH;
819
820         return 0;
821 }
822
823 /**
824  * \param msg The message to be sent.
825  * \param do_send True if lnet_ni_send() should be called in this function.
826  *        lnet_send() is going to lnet_net_unlock immediately after this, so
827  *        it sets do_send FALSE and I don't do the unlock/send/lock bit.
828  *
829  * \retval LNET_CREDIT_OK If \a msg sent or OK to send.
830  * \retval LNET_CREDIT_WAIT If \a msg blocked for credit.
831  * \retval -EHOSTUNREACH If the next hop of the message appears dead.
832  * \retval -ECANCELED If the MD of the message has been unlinked.
833  */
834 static int
835 lnet_post_send_locked(struct lnet_msg *msg, int do_send)
836 {
837         struct lnet_peer_ni     *lp = msg->msg_txpeer;
838         struct lnet_ni          *ni = msg->msg_txni;
839         int                     cpt = msg->msg_tx_cpt;
840         struct lnet_tx_queue    *tq = ni->ni_tx_queues[cpt];
841         int rc;
842
843         /* non-lnet_send() callers have checked before */
844         LASSERT(!do_send || msg->msg_tx_delayed);
845         LASSERT(!msg->msg_receiving);
846         LASSERT(msg->msg_tx_committed);
847
848         /* can't get here if we're sending to the loopback interface */
849         if (the_lnet.ln_loni)
850                 LASSERT(!nid_same(&lp->lpni_nid, &the_lnet.ln_loni->ni_nid));
851
852         /* NB 'lp' is always the next hop */
853         rc = lnet_check_message_drop(ni, lp, msg);
854         if (rc) {
855                 the_lnet.ln_counters[cpt]->lct_common.lcc_drop_count++;
856                 the_lnet.ln_counters[cpt]->lct_common.lcc_drop_length +=
857                         msg->msg_len;
858                 lnet_net_unlock(cpt);
859                 if (msg->msg_txpeer)
860                         lnet_incr_stats(&msg->msg_txpeer->lpni_stats,
861                                         msg->msg_type,
862                                         LNET_STATS_TYPE_DROP);
863
864                 lnet_incr_stats(&msg->msg_txni->ni_stats,
865                                 msg->msg_type,
866                                 LNET_STATS_TYPE_DROP);
867
868                 if (rc == -EHOSTUNREACH) {
869                         CNETERR("Dropping message for %s: peer not alive\n",
870                                 libcfs_idstr(&msg->msg_target));
871                         msg->msg_health_status = LNET_MSG_STATUS_REMOTE_DROPPED;
872                 } else {
873                         CNETERR("Dropping message for %s: exceeded message deadline\n",
874                                 libcfs_idstr(&msg->msg_target));
875                         msg->msg_health_status =
876                                 LNET_MSG_STATUS_NETWORK_TIMEOUT;
877                 }
878
879                 if (do_send)
880                         lnet_finalize(msg, rc);
881
882                 lnet_net_lock(cpt);
883                 return rc;
884         }
885
886         if (msg->msg_md != NULL &&
887             (msg->msg_md->md_flags & LNET_MD_FLAG_ABORTED) != 0) {
888                 lnet_net_unlock(cpt);
889
890                 CNETERR("Aborting message for %s: LNetM[DE]Unlink() already "
891                         "called on the MD/ME.\n",
892                         libcfs_idstr(&msg->msg_target));
893                 if (do_send) {
894                         msg->msg_no_resend = true;
895                         CDEBUG(D_NET, "msg %p to %s canceled and will not be resent\n",
896                                msg, libcfs_idstr(&msg->msg_target));
897                         lnet_finalize(msg, -ECANCELED);
898                 }
899
900                 lnet_net_lock(cpt);
901                 return -ECANCELED;
902         }
903
904         if (!msg->msg_peertxcredit) {
905                 spin_lock(&lp->lpni_lock);
906                 LASSERT((lp->lpni_txcredits < 0) ==
907                         !list_empty(&lp->lpni_txq));
908
909                 msg->msg_peertxcredit = 1;
910                 lp->lpni_txqnob += msg->msg_len + sizeof(struct lnet_hdr_nid4);
911                 lp->lpni_txcredits--;
912
913                 if (lp->lpni_txcredits < lp->lpni_mintxcredits)
914                         lp->lpni_mintxcredits = lp->lpni_txcredits;
915
916                 if (lp->lpni_txcredits < 0) {
917                         msg->msg_tx_delayed = 1;
918                         list_add_tail(&msg->msg_list, &lp->lpni_txq);
919                         spin_unlock(&lp->lpni_lock);
920                         return LNET_CREDIT_WAIT;
921                 }
922                 spin_unlock(&lp->lpni_lock);
923         }
924
925         if (!msg->msg_txcredit) {
926                 LASSERT((tq->tq_credits < 0) ==
927                         !list_empty(&tq->tq_delayed));
928
929                 msg->msg_txcredit = 1;
930                 tq->tq_credits--;
931                 atomic_dec(&ni->ni_tx_credits);
932
933                 if (tq->tq_credits < tq->tq_credits_min)
934                         tq->tq_credits_min = tq->tq_credits;
935
936                 if (tq->tq_credits < 0) {
937                         msg->msg_tx_delayed = 1;
938                         list_add_tail(&msg->msg_list, &tq->tq_delayed);
939                         return LNET_CREDIT_WAIT;
940                 }
941         }
942
943         if (unlikely(!list_empty(&the_lnet.ln_delay_rules)) &&
944             lnet_delay_rule_match_locked(&msg->msg_hdr, msg)) {
945                 msg->msg_tx_delayed = 1;
946                 return LNET_CREDIT_WAIT;
947         }
948
949         /* unset the tx_delay flag as we're going to send it now */
950         msg->msg_tx_delayed = 0;
951
952         if (do_send) {
953                 lnet_net_unlock(cpt);
954                 lnet_ni_send(ni, msg);
955                 lnet_net_lock(cpt);
956         }
957         return LNET_CREDIT_OK;
958 }
959
960
961 static struct lnet_rtrbufpool *
962 lnet_msg2bufpool(struct lnet_msg *msg)
963 {
964         struct lnet_rtrbufpool  *rbp;
965         int                     cpt;
966
967         LASSERT(msg->msg_rx_committed);
968
969         cpt = msg->msg_rx_cpt;
970         rbp = &the_lnet.ln_rtrpools[cpt][0];
971
972         LASSERT(msg->msg_len <= LNET_MTU);
973         while (msg->msg_len > (unsigned int)rbp->rbp_npages * PAGE_SIZE) {
974                 rbp++;
975                 LASSERT(rbp < &the_lnet.ln_rtrpools[cpt][LNET_NRBPOOLS]);
976         }
977
978         return rbp;
979 }
980
981 static int
982 lnet_post_routed_recv_locked(struct lnet_msg *msg, int do_recv)
983 {
984         /* lnet_parse is going to lnet_net_unlock immediately after this, so it
985          * sets do_recv FALSE and I don't do the unlock/send/lock bit.
986          * I return LNET_CREDIT_WAIT if msg blocked and LNET_CREDIT_OK if
987          * received or OK to receive */
988         struct lnet_peer_ni *lpni = msg->msg_rxpeer;
989         struct lnet_peer *lp;
990         struct lnet_rtrbufpool *rbp;
991         struct lnet_rtrbuf *rb;
992
993         LASSERT(msg->msg_kiov == NULL);
994         LASSERT(msg->msg_niov == 0);
995         LASSERT(msg->msg_routing);
996         LASSERT(msg->msg_receiving);
997         LASSERT(!msg->msg_sending);
998         LASSERT(lpni->lpni_peer_net);
999         LASSERT(lpni->lpni_peer_net->lpn_peer);
1000
1001         lp = lpni->lpni_peer_net->lpn_peer;
1002
1003         /* non-lnet_parse callers only receive delayed messages */
1004         LASSERT(!do_recv || msg->msg_rx_delayed);
1005
1006         if (!msg->msg_peerrtrcredit) {
1007                 /* lpni_lock protects the credit manipulation */
1008                 spin_lock(&lpni->lpni_lock);
1009
1010                 msg->msg_peerrtrcredit = 1;
1011                 lpni->lpni_rtrcredits--;
1012                 if (lpni->lpni_rtrcredits < lpni->lpni_minrtrcredits)
1013                         lpni->lpni_minrtrcredits = lpni->lpni_rtrcredits;
1014
1015                 if (lpni->lpni_rtrcredits < 0) {
1016                         spin_unlock(&lpni->lpni_lock);
1017                         /* must have checked eager_recv before here */
1018                         LASSERT(msg->msg_rx_ready_delay);
1019                         msg->msg_rx_delayed = 1;
1020                         /* lp_lock protects the lp_rtrq */
1021                         spin_lock(&lp->lp_lock);
1022                         list_add_tail(&msg->msg_list, &lp->lp_rtrq);
1023                         spin_unlock(&lp->lp_lock);
1024                         return LNET_CREDIT_WAIT;
1025                 }
1026                 spin_unlock(&lpni->lpni_lock);
1027         }
1028
1029         rbp = lnet_msg2bufpool(msg);
1030
1031         if (!msg->msg_rtrcredit) {
1032                 msg->msg_rtrcredit = 1;
1033                 rbp->rbp_credits--;
1034                 if (rbp->rbp_credits < rbp->rbp_mincredits)
1035                         rbp->rbp_mincredits = rbp->rbp_credits;
1036
1037                 if (rbp->rbp_credits < 0) {
1038                         /* must have checked eager_recv before here */
1039                         LASSERT(msg->msg_rx_ready_delay);
1040                         msg->msg_rx_delayed = 1;
1041                         list_add_tail(&msg->msg_list, &rbp->rbp_msgs);
1042                         return LNET_CREDIT_WAIT;
1043                 }
1044         }
1045
1046         LASSERT(!list_empty(&rbp->rbp_bufs));
1047         rb = list_first_entry(&rbp->rbp_bufs, struct lnet_rtrbuf, rb_list);
1048         list_del(&rb->rb_list);
1049
1050         msg->msg_niov = rbp->rbp_npages;
1051         msg->msg_kiov = &rb->rb_kiov[0];
1052
1053         /* unset the msg-rx_delayed flag since we're receiving the message */
1054         msg->msg_rx_delayed = 0;
1055
1056         if (do_recv) {
1057                 int cpt = msg->msg_rx_cpt;
1058
1059                 lnet_net_unlock(cpt);
1060                 lnet_ni_recv(msg->msg_rxni, msg->msg_private, msg, 1,
1061                              0, msg->msg_len, msg->msg_len);
1062                 lnet_net_lock(cpt);
1063         }
1064         return LNET_CREDIT_OK;
1065 }
1066
1067 void
1068 lnet_return_tx_credits_locked(struct lnet_msg *msg)
1069 {
1070         struct lnet_peer_ni     *txpeer = msg->msg_txpeer;
1071         struct lnet_ni          *txni = msg->msg_txni;
1072         struct lnet_msg         *msg2;
1073
1074         if (msg->msg_txcredit) {
1075                 struct lnet_ni       *ni = msg->msg_txni;
1076                 struct lnet_tx_queue *tq = ni->ni_tx_queues[msg->msg_tx_cpt];
1077
1078                 /* give back NI txcredits */
1079                 msg->msg_txcredit = 0;
1080
1081                 LASSERT((tq->tq_credits < 0) ==
1082                         !list_empty(&tq->tq_delayed));
1083
1084                 tq->tq_credits++;
1085                 atomic_inc(&ni->ni_tx_credits);
1086                 if (tq->tq_credits <= 0) {
1087                         msg2 = list_first_entry(&tq->tq_delayed,
1088                                                 struct lnet_msg, msg_list);
1089                         list_del(&msg2->msg_list);
1090
1091                         LASSERT(msg2->msg_txni == ni);
1092                         LASSERT(msg2->msg_tx_delayed);
1093                         LASSERT(msg2->msg_tx_cpt == msg->msg_tx_cpt);
1094
1095                         (void) lnet_post_send_locked(msg2, 1);
1096                 }
1097         }
1098
1099         if (msg->msg_peertxcredit) {
1100                 /* give back peer txcredits */
1101                 msg->msg_peertxcredit = 0;
1102
1103                 spin_lock(&txpeer->lpni_lock);
1104                 LASSERT((txpeer->lpni_txcredits < 0) ==
1105                         !list_empty(&txpeer->lpni_txq));
1106
1107                 txpeer->lpni_txqnob -=  msg->msg_len +
1108                                         sizeof(struct lnet_hdr_nid4);
1109                 LASSERT(txpeer->lpni_txqnob >= 0);
1110
1111                 txpeer->lpni_txcredits++;
1112                 if (txpeer->lpni_txcredits <= 0) {
1113                         int msg2_cpt;
1114
1115                         msg2 = list_first_entry(&txpeer->lpni_txq,
1116                                                 struct lnet_msg, msg_list);
1117                         list_del(&msg2->msg_list);
1118                         spin_unlock(&txpeer->lpni_lock);
1119
1120                         LASSERT(msg2->msg_txpeer == txpeer);
1121                         LASSERT(msg2->msg_tx_delayed);
1122
1123                         msg2_cpt = msg2->msg_tx_cpt;
1124
1125                         /*
1126                          * The msg_cpt can be different from the msg2_cpt
1127                          * so we need to make sure we lock the correct cpt
1128                          * for msg2.
1129                          * Once we call lnet_post_send_locked() it is no
1130                          * longer safe to access msg2, since it could've
1131                          * been freed by lnet_finalize(), but we still
1132                          * need to relock the correct cpt, so we cache the
1133                          * msg2_cpt for the purpose of the check that
1134                          * follows the call to lnet_pose_send_locked().
1135                          */
1136                         if (msg2_cpt != msg->msg_tx_cpt) {
1137                                 lnet_net_unlock(msg->msg_tx_cpt);
1138                                 lnet_net_lock(msg2_cpt);
1139                         }
1140                         (void) lnet_post_send_locked(msg2, 1);
1141                         if (msg2_cpt != msg->msg_tx_cpt) {
1142                                 lnet_net_unlock(msg2_cpt);
1143                                 lnet_net_lock(msg->msg_tx_cpt);
1144                         }
1145                 } else {
1146                         spin_unlock(&txpeer->lpni_lock);
1147                 }
1148         }
1149
1150         if (txni != NULL) {
1151                 msg->msg_txni = NULL;
1152                 lnet_ni_decref_locked(txni, msg->msg_tx_cpt);
1153         }
1154
1155         if (txpeer != NULL) {
1156                 msg->msg_txpeer = NULL;
1157                 lnet_peer_ni_decref_locked(txpeer);
1158         }
1159 }
1160
1161 void
1162 lnet_schedule_blocked_locked(struct lnet_rtrbufpool *rbp)
1163 {
1164         struct lnet_msg *msg;
1165
1166         if (list_empty(&rbp->rbp_msgs))
1167                 return;
1168         msg = list_first_entry(&rbp->rbp_msgs,
1169                                struct lnet_msg, msg_list);
1170         list_del(&msg->msg_list);
1171
1172         (void)lnet_post_routed_recv_locked(msg, 1);
1173 }
1174
1175 void
1176 lnet_drop_routed_msgs_locked(struct list_head *list, int cpt)
1177 {
1178         struct lnet_msg *msg;
1179         struct lnet_msg *tmp;
1180
1181         lnet_net_unlock(cpt);
1182
1183         list_for_each_entry_safe(msg, tmp, list, msg_list) {
1184                 lnet_ni_recv(msg->msg_rxni, msg->msg_private, NULL,
1185                              0, 0, 0, msg->msg_hdr.payload_length);
1186                 list_del_init(&msg->msg_list);
1187                 msg->msg_no_resend = true;
1188                 msg->msg_health_status = LNET_MSG_STATUS_REMOTE_ERROR;
1189                 lnet_finalize(msg, -ECANCELED);
1190         }
1191
1192         lnet_net_lock(cpt);
1193 }
1194
1195 void
1196 lnet_return_rx_credits_locked(struct lnet_msg *msg)
1197 {
1198         struct lnet_peer_ni *rxpeerni = msg->msg_rxpeer;
1199         struct lnet_peer *lp;
1200         struct lnet_ni *rxni = msg->msg_rxni;
1201         struct lnet_msg *msg2;
1202
1203         if (msg->msg_rtrcredit) {
1204                 /* give back global router credits */
1205                 struct lnet_rtrbuf *rb;
1206                 struct lnet_rtrbufpool *rbp;
1207
1208                 /* NB If a msg ever blocks for a buffer in rbp_msgs, it stays
1209                  * there until it gets one allocated, or aborts the wait
1210                  * itself */
1211                 LASSERT(msg->msg_kiov != NULL);
1212
1213                 rb = list_entry(msg->msg_kiov, struct lnet_rtrbuf, rb_kiov[0]);
1214                 rbp = rb->rb_pool;
1215
1216                 msg->msg_kiov = NULL;
1217                 msg->msg_rtrcredit = 0;
1218
1219                 LASSERT(rbp == lnet_msg2bufpool(msg));
1220
1221                 LASSERT((rbp->rbp_credits > 0) ==
1222                         !list_empty(&rbp->rbp_bufs));
1223
1224                 /* If routing is now turned off, we just drop this buffer and
1225                  * don't bother trying to return credits.  */
1226                 if (!the_lnet.ln_routing) {
1227                         lnet_destroy_rtrbuf(rb, rbp->rbp_npages);
1228                         goto routing_off;
1229                 }
1230
1231                 /* It is possible that a user has lowered the desired number of
1232                  * buffers in this pool.  Make sure we never put back
1233                  * more buffers than the stated number. */
1234                 if (unlikely(rbp->rbp_credits >= rbp->rbp_req_nbuffers)) {
1235                         /* Discard this buffer so we don't have too
1236                          * many. */
1237                         lnet_destroy_rtrbuf(rb, rbp->rbp_npages);
1238                         rbp->rbp_nbuffers--;
1239                 } else {
1240                         list_add(&rb->rb_list, &rbp->rbp_bufs);
1241                         rbp->rbp_credits++;
1242                         if (rbp->rbp_credits <= 0)
1243                                 lnet_schedule_blocked_locked(rbp);
1244                 }
1245         }
1246
1247 routing_off:
1248         if (msg->msg_peerrtrcredit) {
1249                 LASSERT(rxpeerni);
1250                 LASSERT(rxpeerni->lpni_peer_net);
1251                 LASSERT(rxpeerni->lpni_peer_net->lpn_peer);
1252
1253                 spin_lock(&rxpeerni->lpni_lock);
1254                 /* give back peer router credits */
1255                 msg->msg_peerrtrcredit = 0;
1256                 rxpeerni->lpni_rtrcredits++;
1257                 spin_unlock(&rxpeerni->lpni_lock);
1258
1259                 lp = rxpeerni->lpni_peer_net->lpn_peer;
1260                 spin_lock(&lp->lp_lock);
1261
1262                 /* drop all messages which are queued to be routed on that
1263                  * peer. */
1264                 if (!the_lnet.ln_routing) {
1265                         LIST_HEAD(drop);
1266                         list_splice_init(&lp->lp_rtrq, &drop);
1267                         spin_unlock(&lp->lp_lock);
1268                         lnet_drop_routed_msgs_locked(&drop, msg->msg_rx_cpt);
1269                 } else if (!list_empty(&lp->lp_rtrq)) {
1270                         int msg2_cpt;
1271
1272                         msg2 = list_first_entry(&lp->lp_rtrq,
1273                                                 struct lnet_msg, msg_list);
1274                         list_del(&msg2->msg_list);
1275                         msg2_cpt = msg2->msg_rx_cpt;
1276                         spin_unlock(&lp->lp_lock);
1277                         /*
1278                          * messages on the lp_rtrq can be from any NID in
1279                          * the peer, which means they might have different
1280                          * cpts. We need to make sure we lock the right
1281                          * one.
1282                          */
1283                         if (msg2_cpt != msg->msg_rx_cpt) {
1284                                 lnet_net_unlock(msg->msg_rx_cpt);
1285                                 lnet_net_lock(msg2_cpt);
1286                         }
1287                         (void) lnet_post_routed_recv_locked(msg2, 1);
1288                         if (msg2_cpt != msg->msg_rx_cpt) {
1289                                 lnet_net_unlock(msg2_cpt);
1290                                 lnet_net_lock(msg->msg_rx_cpt);
1291                         }
1292                 } else {
1293                         spin_unlock(&lp->lp_lock);
1294                 }
1295         }
1296         if (rxni != NULL) {
1297                 msg->msg_rxni = NULL;
1298                 lnet_ni_decref_locked(rxni, msg->msg_rx_cpt);
1299         }
1300         if (rxpeerni != NULL) {
1301                 msg->msg_rxpeer = NULL;
1302                 lnet_peer_ni_decref_locked(rxpeerni);
1303         }
1304 }
1305
1306 static struct lnet_peer_ni *
1307 lnet_select_peer_ni(struct lnet_ni *best_ni, struct lnet_nid *dst_nid,
1308                     struct lnet_peer *peer,
1309                     struct lnet_peer_ni *best_lpni,
1310                     struct lnet_peer_net *peer_net)
1311 {
1312         /*
1313          * Look at the peer NIs for the destination peer that connect
1314          * to the chosen net. If a peer_ni is preferred when using the
1315          * best_ni to communicate, we use that one. If there is no
1316          * preferred peer_ni, or there are multiple preferred peer_ni,
1317          * the available transmit credits are used. If the transmit
1318          * credits are equal, we round-robin over the peer_ni.
1319          */
1320         struct lnet_peer_ni *lpni = NULL;
1321         int best_lpni_credits = (best_lpni) ? best_lpni->lpni_txcredits :
1322                 INT_MIN;
1323         int best_lpni_healthv = (best_lpni) ?
1324                 atomic_read(&best_lpni->lpni_healthv) : 0;
1325         bool best_lpni_is_preferred = false;
1326         bool lpni_is_preferred;
1327         int lpni_healthv;
1328         __u32 lpni_sel_prio;
1329         __u32 best_sel_prio = LNET_MAX_SELECTION_PRIORITY;
1330
1331         while ((lpni = lnet_get_next_peer_ni_locked(peer, peer_net, lpni))) {
1332                 /*
1333                  * if the best_ni we've chosen aleady has this lpni
1334                  * preferred, then let's use it
1335                  */
1336                 if (best_ni) {
1337                         lpni_is_preferred = lnet_peer_is_pref_nid_locked(
1338                                 lpni, &best_ni->ni_nid);
1339                         CDEBUG(D_NET, "%s lpni_is_preferred = %d\n",
1340                                libcfs_nidstr(&best_ni->ni_nid),
1341                                lpni_is_preferred);
1342                 } else {
1343                         lpni_is_preferred = false;
1344                 }
1345
1346                 lpni_healthv = atomic_read(&lpni->lpni_healthv);
1347                 lpni_sel_prio = lpni->lpni_sel_priority;
1348
1349                 if (best_lpni)
1350                         CDEBUG(D_NET, "n:[%s, %s] h:[%d, %d] p:[%d, %d] c:[%d, %d] s:[%d, %d]\n",
1351                                 libcfs_nidstr(&lpni->lpni_nid),
1352                                 libcfs_nidstr(&best_lpni->lpni_nid),
1353                                 lpni_healthv, best_lpni_healthv,
1354                                 lpni_sel_prio, best_sel_prio,
1355                                 lpni->lpni_txcredits, best_lpni_credits,
1356                                 lpni->lpni_seq, best_lpni->lpni_seq);
1357                 else
1358                         goto select_lpni;
1359
1360                 /* pick the healthiest peer ni */
1361                 if (lpni_healthv < best_lpni_healthv)
1362                         continue;
1363                 else if (lpni_healthv > best_lpni_healthv)
1364                         goto select_lpni;
1365
1366                 if (lpni_sel_prio > best_sel_prio)
1367                         continue;
1368                 else if (lpni_sel_prio < best_sel_prio)
1369                         goto select_lpni;
1370
1371                 /* If this is a preferred peer - use it. Otherwise, ignore it */
1372                 if (!best_lpni_is_preferred && lpni_is_preferred)
1373                         goto select_lpni;
1374                 else if (best_lpni_is_preferred && !lpni_is_preferred)
1375                         continue;
1376
1377                 if (lpni->lpni_txcredits < best_lpni_credits)
1378                         /* We already have a peer that has more credits
1379                          * available than this one. No need to consider
1380                          * this peer further.
1381                          */
1382                         continue;
1383                 else if (lpni->lpni_txcredits > best_lpni_credits)
1384                         goto select_lpni;
1385
1386                 /* The best peer found so far and the current peer
1387                  * have the same number of available credits let's
1388                  * make sure to select between them using Round Robin
1389                  */
1390                 if (best_lpni && (best_lpni->lpni_seq <= lpni->lpni_seq))
1391                         continue;
1392 select_lpni:
1393                 best_lpni_is_preferred = lpni_is_preferred;
1394                 best_lpni_healthv = lpni_healthv;
1395                 best_sel_prio = lpni_sel_prio;
1396                 best_lpni = lpni;
1397                 best_lpni_credits = lpni->lpni_txcredits;
1398         }
1399
1400         /* if we still can't find a peer ni then we can't reach it */
1401         if (!best_lpni) {
1402                 u32 net_id = (peer_net) ? peer_net->lpn_net_id :
1403                              LNET_NID_NET(dst_nid);
1404                 CDEBUG(D_NET, "no peer_ni found on peer net %s\n",
1405                                 libcfs_net2str(net_id));
1406                 return NULL;
1407         }
1408
1409         CDEBUG(D_NET, "sd_best_lpni = %s\n",
1410                libcfs_nidstr(&best_lpni->lpni_nid));
1411
1412         return best_lpni;
1413 }
1414
1415 /*
1416  * Prerequisite: the best_ni should already be set in the sd
1417  * Find the best lpni.
1418  * If the net id is provided then restrict lpni selection on
1419  * that particular net.
1420  * Otherwise find any reachable lpni. When dealing with an MR
1421  * gateway and it has multiple lpnis which we can use
1422  * we want to select the best one from the list of reachable
1423  * ones.
1424  */
1425 static inline struct lnet_peer_ni *
1426 lnet_find_best_lpni(struct lnet_ni *lni, struct lnet_nid *dst_nid,
1427                     struct lnet_peer *peer, u32 net_id)
1428 {
1429         struct lnet_peer_net *peer_net;
1430
1431         /* find the best_lpni on any local network */
1432         if (net_id == LNET_NET_ANY) {
1433                 struct lnet_peer_ni *best_lpni = NULL;
1434                 struct lnet_peer_net *lpn;
1435                 list_for_each_entry(lpn, &peer->lp_peer_nets, lpn_peer_nets) {
1436                         /* no net specified find any reachable peer ni */
1437                         if (!lnet_islocalnet_locked(lpn->lpn_net_id))
1438                                 continue;
1439                         best_lpni = lnet_select_peer_ni(lni, dst_nid, peer,
1440                                                         best_lpni, lpn);
1441                 }
1442
1443                 return best_lpni;
1444         }
1445         /* restrict on the specified net */
1446         peer_net = lnet_peer_get_net_locked(peer, net_id);
1447         if (peer_net)
1448                 return lnet_select_peer_ni(lni, dst_nid, peer, NULL, peer_net);
1449
1450         return NULL;
1451 }
1452
1453 static int
1454 lnet_compare_gw_lpnis(struct lnet_peer_ni *lpni1, struct lnet_peer_ni *lpni2)
1455 {
1456         if (lpni1->lpni_txqnob < lpni2->lpni_txqnob)
1457                 return 1;
1458
1459         if (lpni1->lpni_txqnob > lpni2->lpni_txqnob)
1460                 return -1;
1461
1462         if (lpni1->lpni_txcredits > lpni2->lpni_txcredits)
1463                 return 1;
1464
1465         if (lpni1->lpni_txcredits < lpni2->lpni_txcredits)
1466                 return -1;
1467
1468         return 0;
1469 }
1470
1471 /* Compare route priorities and hop counts */
1472 static int
1473 lnet_compare_routes(struct lnet_route *r1, struct lnet_route *r2)
1474 {
1475         int r1_hops = (r1->lr_hops == LNET_UNDEFINED_HOPS) ? 1 : r1->lr_hops;
1476         int r2_hops = (r2->lr_hops == LNET_UNDEFINED_HOPS) ? 1 : r2->lr_hops;
1477
1478         if (r1->lr_priority < r2->lr_priority)
1479                 return 1;
1480
1481         if (r1->lr_priority > r2->lr_priority)
1482                 return -1;
1483
1484         if (r1_hops < r2_hops)
1485                 return 1;
1486
1487         if (r1_hops > r2_hops)
1488                 return -1;
1489
1490         return 0;
1491 }
1492
1493 static struct lnet_route *
1494 lnet_find_route_locked(struct lnet_remotenet *rnet, __u32 src_net,
1495                        struct lnet_peer_ni *remote_lpni,
1496                        struct lnet_route **prev_route,
1497                        struct lnet_peer_ni **gwni)
1498 {
1499         struct lnet_peer_ni *lpni, *best_gw_ni = NULL;
1500         struct lnet_route *best_route;
1501         struct lnet_route *last_route;
1502         struct lnet_route *route;
1503         int rc;
1504         bool best_rte_is_preferred = false;
1505         struct lnet_nid *gw_pnid;
1506
1507         CDEBUG(D_NET, "Looking up a route to %s, from %s\n",
1508                libcfs_net2str(rnet->lrn_net), libcfs_net2str(src_net));
1509
1510         best_route = last_route = NULL;
1511         list_for_each_entry(route, &rnet->lrn_routes, lr_list) {
1512                 if (!lnet_is_route_alive(route))
1513                         continue;
1514                 gw_pnid = &route->lr_gateway->lp_primary_nid;
1515
1516                 /* no protection on below fields, but it's harmless */
1517                 if (last_route && (last_route->lr_seq - route->lr_seq < 0))
1518                         last_route = route;
1519
1520                 /* if the best route found is in the preferred list then
1521                  * tag it as preferred and use it later on. But if we
1522                  * didn't find any routes which are on the preferred list
1523                  * then just use the best route possible.
1524                  */
1525                 rc = lnet_peer_is_pref_rtr_locked(remote_lpni, gw_pnid);
1526
1527                 if (!best_route || (rc && !best_rte_is_preferred)) {
1528                         /* Restrict the selection of the router NI on the
1529                          * src_net provided. If the src_net is LNET_NID_ANY,
1530                          * then select the best interface available.
1531                          */
1532                         lpni = lnet_find_best_lpni(NULL, NULL,
1533                                                    route->lr_gateway,
1534                                                    src_net);
1535                         if (!lpni) {
1536                                 CDEBUG(D_NET,
1537                                        "Gateway %s does not have a peer NI on net %s\n",
1538                                        libcfs_nidstr(gw_pnid),
1539                                        libcfs_net2str(src_net));
1540                                 continue;
1541                         }
1542                 }
1543
1544                 if (rc && !best_rte_is_preferred) {
1545                         /* This is the first preferred route we found,
1546                          * so it beats any route found previously
1547                          */
1548                         best_route = route;
1549                         if (!last_route)
1550                                 last_route = route;
1551                         best_gw_ni = lpni;
1552                         best_rte_is_preferred = true;
1553                         CDEBUG(D_NET, "preferred gw = %s\n",
1554                                libcfs_nidstr(gw_pnid));
1555                         continue;
1556                 } else if ((!rc) && best_rte_is_preferred)
1557                         /* The best route we found so far is in the preferred
1558                          * list, so it beats any non-preferred route
1559                          */
1560                         continue;
1561
1562                 if (!best_route) {
1563                         best_route = last_route = route;
1564                         best_gw_ni = lpni;
1565                         continue;
1566                 }
1567
1568                 rc = lnet_compare_routes(route, best_route);
1569                 if (rc == -1)
1570                         continue;
1571
1572                 /* Restrict the selection of the router NI on the
1573                  * src_net provided. If the src_net is LNET_NID_ANY,
1574                  * then select the best interface available.
1575                  */
1576                 lpni = lnet_find_best_lpni(NULL, NULL, route->lr_gateway,
1577                                            src_net);
1578                 if (!lpni) {
1579                         CDEBUG(D_NET,
1580                                "Gateway %s does not have a peer NI on net %s\n",
1581                                libcfs_nidstr(gw_pnid),
1582                                libcfs_net2str(src_net));
1583                         continue;
1584                 }
1585
1586                 if (rc == 1) {
1587                         best_route = route;
1588                         best_gw_ni = lpni;
1589                         continue;
1590                 }
1591
1592                 rc = lnet_compare_gw_lpnis(lpni, best_gw_ni);
1593                 if (rc == -1)
1594                         continue;
1595
1596                 if (rc == 1 || route->lr_seq <= best_route->lr_seq) {
1597                         best_route = route;
1598                         best_gw_ni = lpni;
1599                         continue;
1600                 }
1601         }
1602
1603         *prev_route = last_route;
1604         *gwni = best_gw_ni;
1605
1606         return best_route;
1607 }
1608
1609 static inline unsigned int
1610 lnet_dev_prio_of_md(struct lnet_ni *ni, unsigned int dev_idx)
1611 {
1612         if (dev_idx == UINT_MAX)
1613                 return UINT_MAX;
1614
1615         if (!ni || !ni->ni_net || !ni->ni_net->net_lnd ||
1616             !ni->ni_net->net_lnd->lnd_get_dev_prio)
1617                 return UINT_MAX;
1618
1619         return ni->ni_net->net_lnd->lnd_get_dev_prio(ni, dev_idx);
1620 }
1621
1622 static struct lnet_ni *
1623 lnet_get_best_ni(struct lnet_net *local_net, struct lnet_ni *best_ni,
1624                  struct lnet_peer *peer, struct lnet_peer_net *peer_net,
1625                  struct lnet_msg *msg, int md_cpt)
1626 {
1627         struct lnet_libmd *md = msg->msg_md;
1628         unsigned int offset = msg->msg_offset;
1629         unsigned int shortest_distance;
1630         struct lnet_ni *ni = NULL;
1631         int best_credits;
1632         int best_healthv;
1633         __u32 best_sel_prio;
1634         unsigned int best_dev_prio;
1635         int best_ni_fatal;
1636         unsigned int dev_idx = UINT_MAX;
1637         bool gpu = md ? (md->md_flags & LNET_MD_FLAG_GPU) : false;
1638
1639         if (gpu) {
1640                 struct page *page = lnet_get_first_page(md, offset);
1641
1642                 dev_idx = lnet_get_dev_idx(page);
1643         }
1644
1645         /*
1646          * If there is no peer_ni that we can send to on this network,
1647          * then there is no point in looking for a new best_ni here.
1648         */
1649         if (!lnet_get_next_peer_ni_locked(peer, peer_net, NULL))
1650                 return best_ni;
1651
1652         if (best_ni == NULL) {
1653                 best_sel_prio = LNET_MAX_SELECTION_PRIORITY;
1654                 shortest_distance = UINT_MAX;
1655                 best_dev_prio = UINT_MAX;
1656                 best_credits = INT_MIN;
1657                 best_healthv = 0;
1658                 best_ni_fatal = true;
1659         } else {
1660                 best_dev_prio = lnet_dev_prio_of_md(best_ni, dev_idx);
1661                 shortest_distance = cfs_cpt_distance(lnet_cpt_table(), md_cpt,
1662                                                      best_ni->ni_dev_cpt);
1663                 best_credits = atomic_read(&best_ni->ni_tx_credits);
1664                 best_healthv = atomic_read(&best_ni->ni_healthv);
1665                 best_sel_prio = best_ni->ni_sel_priority;
1666                 best_ni_fatal = atomic_read(&best_ni->ni_fatal_error_on);
1667         }
1668
1669         while ((ni = lnet_get_next_ni_locked(local_net, ni))) {
1670                 unsigned int distance;
1671                 int ni_credits;
1672                 int ni_healthv;
1673                 int ni_fatal;
1674                 __u32 ni_sel_prio;
1675                 unsigned int ni_dev_prio;
1676
1677                 ni_credits = atomic_read(&ni->ni_tx_credits);
1678                 ni_healthv = atomic_read(&ni->ni_healthv);
1679                 ni_fatal = atomic_read(&ni->ni_fatal_error_on);
1680                 ni_sel_prio = ni->ni_sel_priority;
1681
1682                 /*
1683                  * calculate the distance from the CPT on which
1684                  * the message memory is allocated to the CPT of
1685                  * the NI's physical device
1686                  */
1687                 distance = cfs_cpt_distance(lnet_cpt_table(),
1688                                             md_cpt,
1689                                             ni->ni_dev_cpt);
1690
1691                 ni_dev_prio = lnet_dev_prio_of_md(ni, dev_idx);
1692
1693                 /*
1694                  * All distances smaller than the NUMA range
1695                  * are treated equally.
1696                  */
1697                 if (!gpu && distance < lnet_numa_range)
1698                         distance = lnet_numa_range;
1699
1700                 /*
1701                  * Select on health, selection policy, direct dma prio,
1702                  * shorter distance, available credits, then round-robin.
1703                  */
1704                 if (best_ni)
1705                         CDEBUG(D_NET, "compare ni %s [f:%s, c:%d, d:%d, s:%d, p:%u, g:%u, h:%d] with best_ni %s [f:%s, c:%d, d:%d, s:%d, p:%u, g:%u, h:%d]\n",
1706                                libcfs_nidstr(&ni->ni_nid),
1707                                ni_fatal ? "y" : "n", ni_credits, distance,
1708                                ni->ni_seq, ni_sel_prio, ni_dev_prio, ni_healthv,
1709                                (best_ni) ? libcfs_nidstr(&best_ni->ni_nid)
1710                                : "not selected",
1711                                best_ni_fatal ? "y" : "n", best_credits,
1712                                shortest_distance,
1713                                (best_ni) ? best_ni->ni_seq : 0,
1714                                best_sel_prio, best_dev_prio, best_healthv);
1715                 else
1716                         goto select_ni;
1717
1718                 if (ni_fatal && !best_ni_fatal)
1719                         continue;
1720                 else if (!ni_fatal && best_ni_fatal)
1721                         goto select_ni;
1722
1723                 if (ni_healthv < best_healthv)
1724                         continue;
1725                 else if (ni_healthv > best_healthv)
1726                         goto select_ni;
1727
1728                 if (ni_sel_prio > best_sel_prio)
1729                         continue;
1730                 else if (ni_sel_prio < best_sel_prio)
1731                         goto select_ni;
1732
1733                 if (ni_dev_prio > best_dev_prio)
1734                         continue;
1735                 else if (ni_dev_prio < best_dev_prio)
1736                         goto select_ni;
1737
1738                 if (distance > shortest_distance)
1739                         continue;
1740                 else if (distance < shortest_distance)
1741                         goto select_ni;
1742
1743                 if (ni_credits < best_credits)
1744                         continue;
1745                 else if (ni_credits > best_credits)
1746                         goto select_ni;
1747
1748                 if (best_ni && best_ni->ni_seq <= ni->ni_seq)
1749                         continue;
1750
1751 select_ni:
1752                 best_sel_prio = ni_sel_prio;
1753                 best_dev_prio = ni_dev_prio;
1754                 shortest_distance = distance;
1755                 best_healthv = ni_healthv;
1756                 best_ni = ni;
1757                 best_credits = ni_credits;
1758                 best_ni_fatal = ni_fatal;
1759         }
1760
1761         CDEBUG(D_NET, "selected best_ni %s\n",
1762                (best_ni) ? libcfs_nidstr(&best_ni->ni_nid) : "no selection");
1763
1764         return best_ni;
1765 }
1766
1767 static bool
1768 lnet_reserved_msg(struct lnet_msg *msg)
1769 {
1770         if (msg->msg_type == LNET_MSG_PUT) {
1771                 if (msg->msg_hdr.msg.put.ptl_index == LNET_RESERVED_PORTAL)
1772                         return true;
1773         } else if (msg->msg_type == LNET_MSG_GET) {
1774                 if (msg->msg_hdr.msg.get.ptl_index == LNET_RESERVED_PORTAL)
1775                         return true;
1776         }
1777         return false;
1778 }
1779
1780 /* Can the specified message trigger peer discovery?
1781  *
1782  * Traffic to the LNET_RESERVED_PORTAL may not trigger peer discovery,
1783  * because such traffic is required to perform discovery. We therefore
1784  * exclude all GET and PUT on that portal. We also exclude all ACK and
1785  * REPLY traffic, but that is because the portal is not tracked in the
1786  * message structure for these message types. We could restrict this
1787  * further by also checking for LNET_PROTO_PING_MATCHBITS.
1788  */
1789 static bool
1790 lnet_msg_discovery(struct lnet_msg *msg)
1791 {
1792         return !(lnet_reserved_msg(msg) || lnet_msg_is_response(msg));
1793 }
1794
1795 /* Is the specified message an LNet ping?
1796  */
1797 static bool
1798 lnet_msg_is_ping(struct lnet_msg *msg)
1799 {
1800         if (msg->msg_type == LNET_MSG_GET &&
1801             msg->msg_hdr.msg.get.ptl_index == LNET_RESERVED_PORTAL)
1802                 return true;
1803
1804         return false;
1805 }
1806
1807 #define SRC_SPEC        0x0001
1808 #define SRC_ANY         0x0002
1809 #define LOCAL_DST       0x0004
1810 #define REMOTE_DST      0x0008
1811 #define MR_DST          0x0010
1812 #define NMR_DST         0x0020
1813 #define SND_RESP        0x0040
1814
1815 /* The following to defines are used for return codes */
1816 #define REPEAT_SEND     0x1000
1817 #define PASS_THROUGH    0x2000
1818
1819 /* The different cases lnet_select pathway needs to handle */
1820 #define SRC_SPEC_LOCAL_MR_DST   (SRC_SPEC | LOCAL_DST | MR_DST)
1821 #define SRC_SPEC_ROUTER_MR_DST  (SRC_SPEC | REMOTE_DST | MR_DST)
1822 #define SRC_SPEC_LOCAL_NMR_DST  (SRC_SPEC | LOCAL_DST | NMR_DST)
1823 #define SRC_SPEC_ROUTER_NMR_DST (SRC_SPEC | REMOTE_DST | NMR_DST)
1824 #define SRC_ANY_LOCAL_MR_DST    (SRC_ANY | LOCAL_DST | MR_DST)
1825 #define SRC_ANY_ROUTER_MR_DST   (SRC_ANY | REMOTE_DST | MR_DST)
1826 #define SRC_ANY_LOCAL_NMR_DST   (SRC_ANY | LOCAL_DST | NMR_DST)
1827 #define SRC_ANY_ROUTER_NMR_DST  (SRC_ANY | REMOTE_DST | NMR_DST)
1828
1829 static int
1830 lnet_handle_lo_send(struct lnet_send_data *sd)
1831 {
1832         struct lnet_msg *msg = sd->sd_msg;
1833         int cpt = sd->sd_cpt;
1834
1835         if (the_lnet.ln_state != LNET_STATE_RUNNING)
1836                 return -ESHUTDOWN;
1837
1838         /* No send credit hassles with LOLND */
1839         lnet_ni_addref_locked(the_lnet.ln_loni, cpt);
1840         msg->msg_hdr.dest_nid = the_lnet.ln_loni->ni_nid;
1841         if (!msg->msg_routing)
1842                 msg->msg_hdr.src_nid = the_lnet.ln_loni->ni_nid;
1843         msg->msg_target.nid = the_lnet.ln_loni->ni_nid;
1844         lnet_msg_commit(msg, cpt);
1845         msg->msg_txni = the_lnet.ln_loni;
1846
1847         return LNET_CREDIT_OK;
1848 }
1849
1850 static int
1851 lnet_handle_send(struct lnet_send_data *sd)
1852 {
1853         struct lnet_ni *best_ni = sd->sd_best_ni;
1854         struct lnet_peer_ni *best_lpni = sd->sd_best_lpni;
1855         struct lnet_peer_ni *final_dst_lpni = sd->sd_final_dst_lpni;
1856         struct lnet_msg *msg = sd->sd_msg;
1857         int cpt2;
1858         __u32 send_case = sd->sd_send_case;
1859         int rc;
1860         __u32 routing = send_case & REMOTE_DST;
1861         struct lnet_rsp_tracker *rspt;
1862
1863         /* Increment sequence number of the selected peer, peer net,
1864          * local ni and local net so that we pick the next ones
1865          * in Round Robin.
1866          */
1867         best_lpni->lpni_peer_net->lpn_peer->lp_send_seq++;
1868         best_lpni->lpni_peer_net->lpn_seq =
1869                 best_lpni->lpni_peer_net->lpn_peer->lp_send_seq;
1870         best_lpni->lpni_seq = best_lpni->lpni_peer_net->lpn_seq;
1871         the_lnet.ln_net_seq++;
1872         best_ni->ni_net->net_seq = the_lnet.ln_net_seq;
1873         best_ni->ni_seq = best_ni->ni_net->net_seq;
1874
1875         CDEBUG(D_NET, "%s NI seq info: [%d:%d:%d:%u] %s LPNI seq info [%d:%d:%d:%u]\n",
1876                libcfs_nidstr(&best_ni->ni_nid),
1877                best_ni->ni_seq, best_ni->ni_net->net_seq,
1878                atomic_read(&best_ni->ni_tx_credits),
1879                best_ni->ni_sel_priority,
1880                libcfs_nidstr(&best_lpni->lpni_nid),
1881                best_lpni->lpni_seq, best_lpni->lpni_peer_net->lpn_seq,
1882                best_lpni->lpni_txcredits,
1883                best_lpni->lpni_sel_priority);
1884
1885         /*
1886          * grab a reference on the peer_ni so it sticks around even if
1887          * we need to drop and relock the lnet_net_lock below.
1888          */
1889         lnet_peer_ni_addref_locked(best_lpni);
1890
1891         /*
1892          * Use lnet_cpt_of_nid() to determine the CPT used to commit the
1893          * message. This ensures that we get a CPT that is correct for
1894          * the NI when the NI has been restricted to a subset of all CPTs.
1895          * If the selected CPT differs from the one currently locked, we
1896          * must unlock and relock the lnet_net_lock(), and then check whether
1897          * the configuration has changed. We don't have a hold on the best_ni
1898          * yet, and it may have vanished.
1899          */
1900         cpt2 = lnet_cpt_of_nid_locked(&best_lpni->lpni_nid, best_ni);
1901         if (sd->sd_cpt != cpt2) {
1902                 __u32 seq = lnet_get_dlc_seq_locked();
1903                 lnet_net_unlock(sd->sd_cpt);
1904                 sd->sd_cpt = cpt2;
1905                 lnet_net_lock(sd->sd_cpt);
1906                 if (seq != lnet_get_dlc_seq_locked()) {
1907                         lnet_peer_ni_decref_locked(best_lpni);
1908                         return REPEAT_SEND;
1909                 }
1910         }
1911
1912         /*
1913          * store the best_lpni in the message right away to avoid having
1914          * to do the same operation under different conditions
1915          */
1916         msg->msg_txpeer = best_lpni;
1917         msg->msg_txni = best_ni;
1918
1919         /*
1920          * grab a reference for the best_ni since now it's in use in this
1921          * send. The reference will be dropped in lnet_finalize()
1922          */
1923         lnet_ni_addref_locked(msg->msg_txni, sd->sd_cpt);
1924
1925         /*
1926          * Always set the target.nid to the best peer picked. Either the
1927          * NID will be one of the peer NIDs selected, or the same NID as
1928          * what was originally set in the target or it will be the NID of
1929          * a router if this message should be routed
1930          */
1931         msg->msg_target.nid = msg->msg_txpeer->lpni_nid;
1932
1933         /*
1934          * lnet_msg_commit assigns the correct cpt to the message, which
1935          * is used to decrement the correct refcount on the ni when it's
1936          * time to return the credits
1937          */
1938         lnet_msg_commit(msg, sd->sd_cpt);
1939
1940         /*
1941          * If we are routing the message then we keep the src_nid that was
1942          * set by the originator. If we are not routing then we are the
1943          * originator and set it here.
1944          */
1945         if (!msg->msg_routing)
1946                 msg->msg_hdr.src_nid = msg->msg_txni->ni_nid;
1947
1948         if (routing) {
1949                 msg->msg_target_is_router = 1;
1950                 msg->msg_target.pid = LNET_PID_LUSTRE;
1951                 /*
1952                  * since we're routing we want to ensure that the
1953                  * msg_hdr.dest_nid is set to the final destination. When
1954                  * the router receives this message it knows how to route
1955                  * it.
1956                  *
1957                  * final_dst_lpni is set at the beginning of the
1958                  * lnet_select_pathway() function and is never changed.
1959                  * It's safe to use it here.
1960                  */
1961                 final_dst_lpni->lpni_peer_net->lpn_peer->lp_send_seq++;
1962                 final_dst_lpni->lpni_peer_net->lpn_seq =
1963                         final_dst_lpni->lpni_peer_net->lpn_peer->lp_send_seq;
1964                 final_dst_lpni->lpni_seq =
1965                         final_dst_lpni->lpni_peer_net->lpn_seq;
1966                 msg->msg_hdr.dest_nid = final_dst_lpni->lpni_nid;
1967         } else {
1968                 /*
1969                  * if we're not routing set the dest_nid to the best peer
1970                  * ni NID that we picked earlier in the algorithm.
1971                  */
1972                 msg->msg_hdr.dest_nid = msg->msg_txpeer->lpni_nid;
1973         }
1974
1975         /*
1976          * if we have response tracker block update it with the next hop
1977          * nid
1978          */
1979         if (msg->msg_md) {
1980                 rspt = msg->msg_md->md_rspt_ptr;
1981                 if (rspt) {
1982                         rspt->rspt_next_hop_nid =
1983                                 msg->msg_txpeer->lpni_nid;
1984                         CDEBUG(D_NET, "rspt_next_hop_nid = %s\n",
1985                                libcfs_nidstr(&rspt->rspt_next_hop_nid));
1986                 }
1987         }
1988
1989         rc = lnet_post_send_locked(msg, 0);
1990
1991         if (!rc)
1992                 CDEBUG(D_NET, "TRACE: %s(%s:%s) -> %s(%s:%s) %s : %s try# %d\n",
1993                        libcfs_nidstr(&msg->msg_hdr.src_nid),
1994                        libcfs_nidstr(&msg->msg_txni->ni_nid),
1995                        libcfs_nidstr(&sd->sd_src_nid),
1996                        libcfs_nidstr(&msg->msg_hdr.dest_nid),
1997                        libcfs_nidstr(&sd->sd_dst_nid),
1998                        libcfs_nidstr(&msg->msg_txpeer->lpni_nid),
1999                        libcfs_nidstr(&sd->sd_rtr_nid),
2000                        lnet_msgtyp2str(msg->msg_type), msg->msg_retry_count);
2001
2002         return rc;
2003 }
2004
2005 static inline void
2006 lnet_set_non_mr_pref_nid(struct lnet_peer_ni *lpni, struct lnet_ni *lni,
2007                          struct lnet_msg *msg)
2008 {
2009         if (!lnet_peer_is_multi_rail(lpni->lpni_peer_net->lpn_peer) &&
2010             !lnet_msg_is_response(msg) && lpni->lpni_pref_nnids == 0) {
2011                 CDEBUG(D_NET, "Setting preferred local NID %s on NMR peer %s\n",
2012                        libcfs_nidstr(&lni->ni_nid),
2013                        libcfs_nidstr(&lpni->lpni_nid));
2014                 lnet_peer_ni_set_non_mr_pref_nid(lpni, &lni->ni_nid);
2015         }
2016 }
2017
2018 /*
2019  * Source Specified
2020  * Local Destination
2021  * non-mr peer
2022  *
2023  * use the source and destination NIDs as the pathway
2024  */
2025 static int
2026 lnet_handle_spec_local_nmr_dst(struct lnet_send_data *sd)
2027 {
2028         /* the destination lpni is set before we get here. */
2029
2030         /* find local NI */
2031         sd->sd_best_ni = lnet_nid_to_ni_locked(&sd->sd_src_nid, sd->sd_cpt);
2032         if (!sd->sd_best_ni) {
2033                 CERROR("Can't send to %s: src %s is not a local nid\n",
2034                        libcfs_nidstr(&sd->sd_dst_nid),
2035                        libcfs_nidstr(&sd->sd_src_nid));
2036                 return -EINVAL;
2037         }
2038
2039         lnet_set_non_mr_pref_nid(sd->sd_best_lpni, sd->sd_best_ni, sd->sd_msg);
2040
2041         return lnet_handle_send(sd);
2042 }
2043
2044 /*
2045  * Source Specified
2046  * Local Destination
2047  * MR Peer
2048  *
2049  * Don't run the selection algorithm on the peer NIs. By specifying the
2050  * local NID, we're also saying that we should always use the destination NID
2051  * provided. This handles the case where we should be using the same
2052  * destination NID for the all the messages which belong to the same RPC
2053  * request.
2054  */
2055 static int
2056 lnet_handle_spec_local_mr_dst(struct lnet_send_data *sd)
2057 {
2058         sd->sd_best_ni = lnet_nid_to_ni_locked(&sd->sd_src_nid, sd->sd_cpt);
2059         if (!sd->sd_best_ni) {
2060                 CERROR("Can't send to %s: src %s is not a local nid\n",
2061                        libcfs_nidstr(&sd->sd_dst_nid),
2062                        libcfs_nidstr(&sd->sd_src_nid));
2063                 return -EINVAL;
2064         }
2065
2066         if (sd->sd_best_lpni &&
2067             nid_same(&sd->sd_best_lpni->lpni_nid,
2068                       &the_lnet.ln_loni->ni_nid))
2069                 return lnet_handle_lo_send(sd);
2070         else if (sd->sd_best_lpni)
2071                 return lnet_handle_send(sd);
2072
2073         CERROR("can't send to %s. no NI on %s\n",
2074                libcfs_nidstr(&sd->sd_dst_nid),
2075                libcfs_net2str(sd->sd_best_ni->ni_net->net_id));
2076
2077         return -EHOSTUNREACH;
2078 }
2079
2080 static struct lnet_ni *
2081 lnet_find_best_ni_on_spec_net(struct lnet_ni *cur_best_ni,
2082                               struct lnet_peer *peer,
2083                               struct lnet_peer_net *peer_net,
2084                               struct lnet_msg *msg,
2085                               int cpt)
2086 {
2087         struct lnet_net *local_net;
2088         struct lnet_ni *best_ni;
2089
2090         local_net = lnet_get_net_locked(peer_net->lpn_net_id);
2091         if (!local_net)
2092                 return NULL;
2093
2094         /*
2095          * Iterate through the NIs in this local Net and select
2096          * the NI to send from. The selection is determined by
2097          * these 3 criterion in the following priority:
2098          *      1. NUMA
2099          *      2. NI available credits
2100          *      3. Round Robin
2101          */
2102         best_ni = lnet_get_best_ni(local_net, cur_best_ni,
2103                                    peer, peer_net, msg, cpt);
2104
2105         return best_ni;
2106 }
2107
2108 static int
2109 lnet_initiate_peer_discovery(struct lnet_peer_ni *lpni, struct lnet_msg *msg,
2110                              int cpt)
2111 {
2112         struct lnet_peer *peer;
2113         struct lnet_peer_ni *new_lpni;
2114         int rc;
2115
2116         lnet_peer_ni_addref_locked(lpni);
2117
2118         peer = lpni->lpni_peer_net->lpn_peer;
2119
2120         if (lnet_peer_gw_discovery(peer)) {
2121                 lnet_peer_ni_decref_locked(lpni);
2122                 return 0;
2123         }
2124
2125         if (!lnet_msg_discovery(msg) || lnet_peer_is_uptodate(peer)) {
2126                 lnet_peer_ni_decref_locked(lpni);
2127                 return 0;
2128         }
2129
2130         rc = lnet_discover_peer_locked(lpni, cpt, false);
2131         if (rc) {
2132                 lnet_peer_ni_decref_locked(lpni);
2133                 return rc;
2134         }
2135
2136         new_lpni = lnet_peer_ni_find_locked(&lpni->lpni_nid);
2137         if (!new_lpni) {
2138                 lnet_peer_ni_decref_locked(lpni);
2139                 return -ENOENT;
2140         }
2141
2142         peer = new_lpni->lpni_peer_net->lpn_peer;
2143         spin_lock(&peer->lp_lock);
2144         if (lpni == new_lpni && lnet_peer_is_uptodate_locked(peer)) {
2145                 /* The peer NI did not change and the peer is up to date.
2146                  * Nothing more to do.
2147                  */
2148                 spin_unlock(&peer->lp_lock);
2149                 lnet_peer_ni_decref_locked(lpni);
2150                 lnet_peer_ni_decref_locked(new_lpni);
2151                 return 0;
2152         }
2153         spin_unlock(&peer->lp_lock);
2154
2155         /* Either the peer NI changed during discovery, or the peer isn't up
2156          * to date. In both cases we want to queue the message on the
2157          * (possibly new) peer's pending queue and queue the peer for discovery
2158          */
2159         msg->msg_sending = 0;
2160         msg->msg_txpeer = NULL;
2161         lnet_net_unlock(cpt);
2162         lnet_peer_queue_message(peer, msg);
2163         lnet_net_lock(cpt);
2164
2165         lnet_peer_ni_decref_locked(lpni);
2166         lnet_peer_ni_decref_locked(new_lpni);
2167
2168         CDEBUG(D_NET, "msg %p delayed. %s pending discovery\n",
2169                msg, libcfs_nidstr(&peer->lp_primary_nid));
2170
2171         return LNET_DC_WAIT;
2172 }
2173
2174 static int
2175 lnet_handle_find_routed_path(struct lnet_send_data *sd,
2176                              struct lnet_nid *dst_nid,
2177                              struct lnet_peer_ni **gw_lpni,
2178                              struct lnet_peer **gw_peer)
2179 {
2180         int rc;
2181         struct lnet_peer *gw;
2182         struct lnet_peer *lp;
2183         struct lnet_peer_net *lpn;
2184         struct lnet_peer_net *best_lpn = NULL;
2185         struct lnet_remotenet *rnet, *best_rnet = NULL;
2186         struct lnet_route *best_route = NULL;
2187         struct lnet_route *last_route = NULL;
2188         struct lnet_peer_ni *lpni = NULL;
2189         struct lnet_peer_ni *gwni = NULL;
2190         bool route_found = false;
2191         struct lnet_nid *src_nid =
2192                 !LNET_NID_IS_ANY(&sd->sd_src_nid) || !sd->sd_best_ni
2193                 ? &sd->sd_src_nid
2194                 : &sd->sd_best_ni->ni_nid;
2195         int best_lpn_healthv = 0;
2196         __u32 best_lpn_sel_prio = LNET_MAX_SELECTION_PRIORITY;
2197
2198         CDEBUG(D_NET, "%s route (%s) from local NI %s to destination %s\n",
2199                LNET_NID_IS_ANY(&sd->sd_rtr_nid) ? "Lookup" : "Specified",
2200                libcfs_nidstr(&sd->sd_rtr_nid), libcfs_nidstr(src_nid),
2201                libcfs_nidstr(&sd->sd_dst_nid));
2202
2203         /* If a router nid was specified then we are replying to a GET or
2204          * sending an ACK. In this case we use the gateway associated with the
2205          * specified router nid.
2206          */
2207         if (!LNET_NID_IS_ANY(&sd->sd_rtr_nid)) {
2208                 gwni = lnet_peer_ni_find_locked(&sd->sd_rtr_nid);
2209                 if (gwni) {
2210                         gw = gwni->lpni_peer_net->lpn_peer;
2211                         lnet_peer_ni_decref_locked(gwni);
2212                         if (gw->lp_rtr_refcount)
2213                                 route_found = true;
2214                 } else {
2215                         CWARN("No peer NI for gateway %s. Attempting to find an alternative route.\n",
2216                               libcfs_nidstr(&sd->sd_rtr_nid));
2217                 }
2218         }
2219
2220         if (!route_found) {
2221                 if (sd->sd_msg->msg_routing || !LNET_NID_IS_ANY(src_nid)) {
2222                         /* If I'm routing this message then I need to find the
2223                          * next hop based on the destination NID
2224                          *
2225                          * We also find next hop based on the destination NID
2226                          * if the source NI was specified
2227                          */
2228                         best_rnet = lnet_find_rnet_locked(LNET_NID_NET(&sd->sd_dst_nid));
2229                         if (!best_rnet) {
2230                                 CERROR("Unable to send message from %s to %s - Route table may be misconfigured\n",
2231                                        (src_nid && LNET_NID_IS_ANY(src_nid)) ?
2232                                                 "any local NI" :
2233                                                 libcfs_nidstr(src_nid),
2234                                        libcfs_nidstr(&sd->sd_dst_nid));
2235                                 return -EHOSTUNREACH;
2236                         }
2237                         CDEBUG(D_NET, "best_rnet %s\n",
2238                                libcfs_net2str(best_rnet->lrn_net));
2239                 } else {
2240                         /* we've already looked up the initial lpni using
2241                          * dst_nid
2242                          */
2243                         lpni = sd->sd_best_lpni;
2244                         /* the peer tree must be in existence */
2245                         LASSERT(lpni && lpni->lpni_peer_net &&
2246                                 lpni->lpni_peer_net->lpn_peer);
2247                         lp = lpni->lpni_peer_net->lpn_peer;
2248
2249                         list_for_each_entry(lpn, &lp->lp_peer_nets, lpn_peer_nets) {
2250                                 /* is this remote network reachable?  */
2251                                 rnet = lnet_find_rnet_locked(lpn->lpn_net_id);
2252                                 if (!rnet)
2253                                         continue;
2254
2255                                 if (!best_lpn)
2256                                         goto use_lpn;
2257                                 else
2258                                         CDEBUG(D_NET, "n[%s, %s] h[%d, %d], p[%u, %u], s[%d, %d]\n",
2259                                                libcfs_net2str(lpn->lpn_net_id),
2260                                                libcfs_net2str(best_lpn->lpn_net_id),
2261                                                lpn->lpn_healthv,
2262                                                best_lpn->lpn_healthv,
2263                                                lpn->lpn_sel_priority,
2264                                                best_lpn->lpn_sel_priority,
2265                                                lpn->lpn_seq,
2266                                                best_lpn->lpn_seq);
2267
2268                                 /* select the preferred peer net */
2269                                 if (best_lpn_healthv > lpn->lpn_healthv)
2270                                         continue;
2271                                 else if (best_lpn_healthv < lpn->lpn_healthv)
2272                                         goto use_lpn;
2273
2274                                 if (best_lpn_sel_prio < lpn->lpn_sel_priority)
2275                                         continue;
2276                                 else if (best_lpn_sel_prio > lpn->lpn_sel_priority)
2277                                         goto use_lpn;
2278
2279                                 if (best_lpn->lpn_seq <= lpn->lpn_seq)
2280                                         continue;
2281 use_lpn:
2282                                 best_lpn_healthv = lpn->lpn_healthv;
2283                                 best_lpn_sel_prio = lpn->lpn_sel_priority;
2284                                 best_lpn = lpn;
2285                                 best_rnet = rnet;
2286                         }
2287
2288                         if (!best_lpn) {
2289                                 CERROR("peer %s has no available nets\n",
2290                                        libcfs_nidstr(&sd->sd_dst_nid));
2291                                 return -EHOSTUNREACH;
2292                         }
2293
2294                         CDEBUG(D_NET, "selected best_lpn %s\n",
2295                                libcfs_net2str(best_lpn->lpn_net_id));
2296
2297                         sd->sd_best_lpni = lnet_find_best_lpni(sd->sd_best_ni,
2298                                                                &sd->sd_dst_nid,
2299                                                                lp,
2300                                                                best_lpn->lpn_net_id);
2301                         if (!sd->sd_best_lpni) {
2302                                 CERROR("peer %s is unreachable\n",
2303                                        libcfs_nidstr(&sd->sd_dst_nid));
2304                                 return -EHOSTUNREACH;
2305                         }
2306
2307                         /* We're attempting to round robin over the remote peer
2308                          * NI's so update the final destination we selected
2309                          */
2310                         sd->sd_final_dst_lpni = sd->sd_best_lpni;
2311                 }
2312
2313                 /*
2314                  * find the best route. Restrict the selection on the net of the
2315                  * local NI if we've already picked the local NI to send from.
2316                  * Otherwise, let's pick any route we can find and then find
2317                  * a local NI we can reach the route's gateway on. Any route we
2318                  * select will be reachable by virtue of the restriction we have
2319                  * when adding a route.
2320                  */
2321                 best_route = lnet_find_route_locked(best_rnet,
2322                                                     LNET_NID_NET(src_nid),
2323                                                     sd->sd_best_lpni,
2324                                                     &last_route, &gwni);
2325
2326                 if (!best_route) {
2327                         CERROR("no route to %s from %s\n",
2328                                libcfs_nidstr(dst_nid),
2329                                libcfs_nidstr(src_nid));
2330                         return -EHOSTUNREACH;
2331                 }
2332
2333                 if (!gwni) {
2334                         CERROR("Internal Error. Route expected to %s from %s\n",
2335                                libcfs_nidstr(dst_nid),
2336                                libcfs_nidstr(src_nid));
2337                         return -EFAULT;
2338                 }
2339
2340                 gw = best_route->lr_gateway;
2341                 LASSERT(gw == gwni->lpni_peer_net->lpn_peer);
2342         }
2343
2344         /*
2345          * If the router checker is not active then discover the gateway here.
2346          * This ensures we are able to take advantage of multi-rail routing, but
2347          * if the router checker is active then we do not unecessarily delay
2348          * messages while the gateway is being checked by the dedicated monitor
2349          * thread.
2350          *
2351          * NB: We're only checking the alive_router_check_interval here, rather
2352          * than calling lnet_router_checker_active(), because the other
2353          * conditions that are checked by that function are either
2354          * irrelevant (the_lnet.ln_routing) or must be true (list of routers
2355          * is not empty)
2356          */
2357         if (alive_router_check_interval <= 0) {
2358                 rc = lnet_initiate_peer_discovery(gwni, sd->sd_msg, sd->sd_cpt);
2359                 if (rc)
2360                         return rc;
2361         }
2362
2363         if (!sd->sd_best_ni) {
2364                 lpn = gwni->lpni_peer_net;
2365                 sd->sd_best_ni = lnet_find_best_ni_on_spec_net(NULL, gw, lpn,
2366                                                                sd->sd_msg,
2367                                                                sd->sd_md_cpt);
2368                 if (!sd->sd_best_ni) {
2369                         CERROR("Internal Error. Expected local ni on %s but non found: %s\n",
2370                                libcfs_net2str(lpn->lpn_net_id),
2371                                libcfs_nidstr(&sd->sd_src_nid));
2372                         return -EFAULT;
2373                 }
2374         }
2375
2376         *gw_lpni = gwni;
2377         *gw_peer = gw;
2378
2379         /*
2380          * increment the sequence number since now we're sure we're
2381          * going to use this route
2382          */
2383         if (LNET_NID_IS_ANY(&sd->sd_rtr_nid)) {
2384                 LASSERT(best_route && last_route);
2385                 best_route->lr_seq = last_route->lr_seq + 1;
2386         }
2387
2388         return 0;
2389 }
2390
2391 /*
2392  * Handle two cases:
2393  *
2394  * Case 1:
2395  *  Source specified
2396  *  Remote destination
2397  *  Non-MR destination
2398  *
2399  * Case 2:
2400  *  Source specified
2401  *  Remote destination
2402  *  MR destination
2403  *
2404  * The handling of these two cases is similar. Even though the destination
2405  * can be MR or non-MR, we'll deal directly with the router.
2406  */
2407 static int
2408 lnet_handle_spec_router_dst(struct lnet_send_data *sd)
2409 {
2410         int rc;
2411         struct lnet_peer_ni *gw_lpni = NULL;
2412         struct lnet_peer *gw_peer = NULL;
2413
2414         /* find local NI */
2415         sd->sd_best_ni = lnet_nid_to_ni_locked(&sd->sd_src_nid, sd->sd_cpt);
2416         if (!sd->sd_best_ni) {
2417                 CERROR("Can't send to %s: src %s is not a local nid\n",
2418                        libcfs_nidstr(&sd->sd_dst_nid),
2419                        libcfs_nidstr(&sd->sd_src_nid));
2420                 return -EINVAL;
2421         }
2422
2423         rc = lnet_handle_find_routed_path(sd, &sd->sd_dst_nid,
2424                                           &gw_lpni, &gw_peer);
2425         if (rc)
2426                 return rc;
2427
2428         if (sd->sd_send_case & NMR_DST)
2429                 /*
2430                  * since the final destination is non-MR let's set its preferred
2431                  * NID before we send
2432                  */
2433                 lnet_set_non_mr_pref_nid(sd->sd_best_lpni, sd->sd_best_ni,
2434                                          sd->sd_msg);
2435
2436         /*
2437          * We're going to send to the gw found so let's set its
2438          * info
2439          */
2440         sd->sd_peer = gw_peer;
2441         sd->sd_best_lpni = gw_lpni;
2442
2443         return lnet_handle_send(sd);
2444 }
2445
2446 static struct lnet_ni *
2447 lnet_find_best_ni_on_local_net(struct lnet_peer *peer, int md_cpt,
2448                                struct lnet_msg *msg, bool discovery)
2449 {
2450         struct lnet_peer_net *lpn = NULL;
2451         struct lnet_peer_net *best_lpn = NULL;
2452         struct lnet_net *net = NULL;
2453         struct lnet_net *best_net = NULL;
2454         struct lnet_ni *best_ni = NULL;
2455         int best_lpn_healthv = 0;
2456         int best_net_healthv = 0;
2457         int net_healthv;
2458         __u32 best_lpn_sel_prio = LNET_MAX_SELECTION_PRIORITY;
2459         __u32 lpn_sel_prio;
2460         __u32 best_net_sel_prio = LNET_MAX_SELECTION_PRIORITY;
2461         __u32 net_sel_prio;
2462
2463         /* If lp_disc_net_id is set, this peer is a router undergoing
2464          * discovery, and this message is an LNet ping, then this may be a
2465          * discovery message and we need to select an NI on the peer net
2466          * specified by lp_disc_net_id
2467          */
2468         if (peer->lp_disc_net_id &&
2469             (peer->lp_state & LNET_PEER_RTR_DISCOVERY) &&
2470             lnet_msg_is_ping(msg)) {
2471                 best_lpn = lnet_peer_get_net_locked(peer, peer->lp_disc_net_id);
2472                 if (best_lpn && lnet_get_net_locked(best_lpn->lpn_net_id))
2473                         goto select_best_ni;
2474         }
2475
2476         /*
2477          * The peer can have multiple interfaces, some of them can be on
2478          * the local network and others on a routed network. We should
2479          * prefer the local network. However if the local network is not
2480          * available then we need to try the routed network
2481          */
2482
2483         /* go through all the peer nets and find the best_ni */
2484         list_for_each_entry(lpn, &peer->lp_peer_nets, lpn_peer_nets) {
2485                 /*
2486                  * The peer's list of nets can contain non-local nets. We
2487                  * want to only examine the local ones.
2488                  */
2489                 net = lnet_get_net_locked(lpn->lpn_net_id);
2490                 if (!net)
2491                         continue;
2492
2493                 lpn_sel_prio = lpn->lpn_sel_priority;
2494                 net_healthv = lnet_get_net_healthv_locked(net);
2495                 net_sel_prio = net->net_sel_priority;
2496
2497                 if (!best_lpn || !best_net)
2498                         goto select_lpn;
2499                 else
2500                         CDEBUG(D_NET,
2501                                "n[%s, %s] ph[%d, %d], pp[%u, %u], nh[%d, %d], np[%u, %u], ps[%u, %u], ns[%u, %u]\n",
2502                                libcfs_net2str(lpn->lpn_net_id),
2503                                libcfs_net2str(best_lpn->lpn_net_id),
2504                                lpn->lpn_healthv,
2505                                best_lpn_healthv,
2506                                lpn_sel_prio,
2507                                best_lpn_sel_prio,
2508                                net_healthv,
2509                                best_net_healthv,
2510                                net_sel_prio,
2511                                best_net_sel_prio,
2512                                lpn->lpn_seq,
2513                                best_lpn->lpn_seq,
2514                                net->net_seq,
2515                                best_net->net_seq);
2516
2517                 /* always select the lpn with the best health */
2518                 if (best_lpn_healthv > lpn->lpn_healthv)
2519                         continue;
2520                 else if (best_lpn_healthv < lpn->lpn_healthv)
2521                         goto select_lpn;
2522
2523                 /* select the preferred peer and local nets */
2524                 if (best_lpn_sel_prio < lpn_sel_prio)
2525                         continue;
2526                 else if (best_lpn_sel_prio > lpn_sel_prio)
2527                         goto select_lpn;
2528
2529                 if (best_net_healthv > net_healthv)
2530                         continue;
2531                 else if (best_net_healthv < net_healthv)
2532                         goto select_lpn;
2533
2534                 if (best_net_sel_prio < net_sel_prio)
2535                         continue;
2536                 else if (best_net_sel_prio > net_sel_prio)
2537                         goto select_lpn;
2538
2539                 if (best_lpn->lpn_seq < lpn->lpn_seq)
2540                         continue;
2541                 else if (best_lpn->lpn_seq > lpn->lpn_seq)
2542                         goto select_lpn;
2543
2544                 /* round robin over the local networks */
2545                 if (best_net->net_seq <= net->net_seq)
2546                         continue;
2547
2548 select_lpn:
2549                 best_net_healthv = net_healthv;
2550                 best_net_sel_prio = net_sel_prio;
2551                 best_lpn_healthv = lpn->lpn_healthv;
2552                 best_lpn_sel_prio = lpn_sel_prio;
2553                 best_lpn = lpn;
2554                 best_net = net;
2555         }
2556
2557         if (best_lpn) {
2558                 /* Select the best NI on the same net as best_lpn chosen
2559                  * above
2560                  */
2561 select_best_ni:
2562                 CDEBUG(D_NET, "selected best_lpn %s\n",
2563                        libcfs_net2str(best_lpn->lpn_net_id));
2564                 best_ni = lnet_find_best_ni_on_spec_net(NULL, peer, best_lpn,
2565                                                         msg, md_cpt);
2566         }
2567
2568         return best_ni;
2569 }
2570
2571 static struct lnet_ni *
2572 lnet_find_existing_preferred_best_ni(struct lnet_peer_ni *lpni, int cpt)
2573 {
2574         struct lnet_ni *best_ni = NULL;
2575         struct lnet_peer_net *peer_net = lpni->lpni_peer_net;
2576         struct lnet_peer_ni *lpni_entry;
2577
2578         /*
2579          * We must use a consistent source address when sending to a
2580          * non-MR peer. However, a non-MR peer can have multiple NIDs
2581          * on multiple networks, and we may even need to talk to this
2582          * peer on multiple networks -- certain types of
2583          * load-balancing configuration do this.
2584          *
2585          * So we need to pick the NI the peer prefers for this
2586          * particular network.
2587          */
2588         LASSERT(peer_net);
2589         list_for_each_entry(lpni_entry, &peer_net->lpn_peer_nis,
2590                             lpni_peer_nis) {
2591                 if (lpni_entry->lpni_pref_nnids == 0)
2592                         continue;
2593                 LASSERT(lpni_entry->lpni_pref_nnids == 1);
2594                 best_ni = lnet_nid_to_ni_locked(&lpni_entry->lpni_pref.nid,
2595                                                 cpt);
2596                 break;
2597         }
2598
2599         return best_ni;
2600 }
2601
2602 /* Prerequisite: sd->sd_peer and sd->sd_best_lpni should be set */
2603 static int
2604 lnet_select_preferred_best_ni(struct lnet_send_data *sd)
2605 {
2606         struct lnet_ni *best_ni = NULL;
2607
2608         /*
2609          * We must use a consistent source address when sending to a
2610          * non-MR peer. However, a non-MR peer can have multiple NIDs
2611          * on multiple networks, and we may even need to talk to this
2612          * peer on multiple networks -- certain types of
2613          * load-balancing configuration do this.
2614          *
2615          * So we need to pick the NI the peer prefers for this
2616          * particular network.
2617          *
2618          * An exception is traffic on LNET_RESERVED_PORTAL. Internal LNet
2619          * traffic doesn't care which source NI is used, and we don't actually
2620          * want to restrict local recovery pings to a single source NI.
2621          */
2622         if (!lnet_reserved_msg(sd->sd_msg))
2623                 best_ni = lnet_find_existing_preferred_best_ni(sd->sd_best_lpni,
2624                                                                sd->sd_cpt);
2625
2626         if (!best_ni)
2627                 best_ni = lnet_find_best_ni_on_spec_net(NULL, sd->sd_peer,
2628                                                 sd->sd_best_lpni->lpni_peer_net,
2629                                                 sd->sd_msg,
2630                                                 sd->sd_md_cpt);
2631
2632         /* If there is no best_ni we don't have a route */
2633         if (!best_ni) {
2634                 CERROR("no path to %s from net %s\n",
2635                         libcfs_nidstr(&sd->sd_best_lpni->lpni_nid),
2636                         libcfs_net2str(sd->sd_best_lpni->lpni_net->net_id));
2637                 return -EHOSTUNREACH;
2638         }
2639
2640         sd->sd_best_ni = best_ni;
2641
2642         /* Set preferred NI if necessary. */
2643         lnet_set_non_mr_pref_nid(sd->sd_best_lpni, sd->sd_best_ni, sd->sd_msg);
2644
2645         return 0;
2646 }
2647
2648
2649 /*
2650  * Source not specified
2651  * Local destination
2652  * Non-MR Peer
2653  *
2654  * always use the same source NID for NMR peers
2655  * If we've talked to that peer before then we already have a preferred
2656  * source NI associated with it. Otherwise, we select a preferred local NI
2657  * and store it in the peer
2658  */
2659 static int
2660 lnet_handle_any_local_nmr_dst(struct lnet_send_data *sd)
2661 {
2662         int rc = 0;
2663
2664         /* sd->sd_best_lpni is already set to the final destination */
2665
2666         /*
2667          * At this point we should've created the peer ni and peer. If we
2668          * can't find it, then something went wrong. Instead of assert
2669          * output a relevant message and fail the send
2670          */
2671         if (!sd->sd_best_lpni) {
2672                 CERROR("Internal fault. Unable to send msg %s to %s. NID not known\n",
2673                        lnet_msgtyp2str(sd->sd_msg->msg_type),
2674                        libcfs_nidstr(&sd->sd_dst_nid));
2675                 return -EFAULT;
2676         }
2677
2678         if (sd->sd_msg->msg_routing) {
2679                 /* If I'm forwarding this message then I can choose any NI
2680                  * on the destination peer net
2681                  */
2682                 sd->sd_best_ni = lnet_find_best_ni_on_spec_net(NULL,
2683                                                                sd->sd_peer,
2684                                                                sd->sd_best_lpni->lpni_peer_net,
2685                                                                sd->sd_msg,
2686                                                                sd->sd_md_cpt);
2687                 if (!sd->sd_best_ni) {
2688                         CERROR("Unable to forward message to %s. No local NI available\n",
2689                                libcfs_nidstr(&sd->sd_dst_nid));
2690                         rc = -EHOSTUNREACH;
2691                 }
2692         } else
2693                 rc = lnet_select_preferred_best_ni(sd);
2694
2695         if (!rc)
2696                 rc = lnet_handle_send(sd);
2697
2698         return rc;
2699 }
2700
2701 static int
2702 lnet_handle_any_mr_dsta(struct lnet_send_data *sd)
2703 {
2704         /*
2705          * NOTE we've already handled the remote peer case. So we only
2706          * need to worry about the local case here.
2707          *
2708          * if we're sending a response, ACK or reply, we need to send it
2709          * to the destination NID given to us. At this point we already
2710          * have the peer_ni we're suppose to send to, so just find the
2711          * best_ni on the peer net and use that. Since we're sending to an
2712          * MR peer then we can just run the selection algorithm on our
2713          * local NIs and pick the best one.
2714          */
2715         if (sd->sd_send_case & SND_RESP) {
2716                 sd->sd_best_ni =
2717                   lnet_find_best_ni_on_spec_net(NULL, sd->sd_peer,
2718                                                 sd->sd_best_lpni->lpni_peer_net,
2719                                                 sd->sd_msg,
2720                                                 sd->sd_md_cpt);
2721
2722                 if (!sd->sd_best_ni) {
2723                         /*
2724                          * We're not going to deal with not able to send
2725                          * a response to the provided final destination
2726                          */
2727                         CERROR("Can't send response to %s. No local NI available\n",
2728                                 libcfs_nidstr(&sd->sd_dst_nid));
2729                         return -EHOSTUNREACH;
2730                 }
2731
2732                 return lnet_handle_send(sd);
2733         }
2734
2735         /*
2736          * If we get here that means we're sending a fresh request, PUT or
2737          * GET, so we need to run our standard selection algorithm.
2738          * First find the best local interface that's on any of the peer's
2739          * networks.
2740          */
2741         sd->sd_best_ni = lnet_find_best_ni_on_local_net(sd->sd_peer,
2742                                         sd->sd_md_cpt,
2743                                         sd->sd_msg,
2744                                         lnet_msg_discovery(sd->sd_msg));
2745         if (sd->sd_best_ni) {
2746                 sd->sd_best_lpni =
2747                   lnet_find_best_lpni(sd->sd_best_ni, &sd->sd_dst_nid,
2748                                       sd->sd_peer,
2749                                       sd->sd_best_ni->ni_net->net_id);
2750
2751                 /*
2752                  * if we're successful in selecting a peer_ni on the local
2753                  * network, then send to it. Otherwise fall through and
2754                  * try and see if we can reach it over another routed
2755                  * network
2756                  */
2757                 if (sd->sd_best_lpni &&
2758                     nid_same(&sd->sd_best_lpni->lpni_nid,
2759                              &the_lnet.ln_loni->ni_nid)) {
2760                         /*
2761                          * in case we initially started with a routed
2762                          * destination, let's reset to local
2763                          */
2764                         sd->sd_send_case &= ~REMOTE_DST;
2765                         sd->sd_send_case |= LOCAL_DST;
2766                         return lnet_handle_lo_send(sd);
2767                 } else if (sd->sd_best_lpni) {
2768                         /*
2769                          * in case we initially started with a routed
2770                          * destination, let's reset to local
2771                          */
2772                         sd->sd_send_case &= ~REMOTE_DST;
2773                         sd->sd_send_case |= LOCAL_DST;
2774                         return lnet_handle_send(sd);
2775                 }
2776
2777                 CERROR("Internal Error. Expected to have a best_lpni: "
2778                        "%s -> %s\n",
2779                        libcfs_nidstr(&sd->sd_src_nid),
2780                        libcfs_nidstr(&sd->sd_dst_nid));
2781
2782                 return -EFAULT;
2783         }
2784
2785         /*
2786          * Peer doesn't have a local network. Let's see if there is
2787          * a remote network we can reach it on.
2788          */
2789         return PASS_THROUGH;
2790 }
2791
2792 /*
2793  * Case 1:
2794  *      Source NID not specified
2795  *      Local destination
2796  *      MR peer
2797  *
2798  * Case 2:
2799  *      Source NID not speified
2800  *      Remote destination
2801  *      MR peer
2802  *
2803  * In both of these cases if we're sending a response, ACK or REPLY, then
2804  * we need to send to the destination NID provided.
2805  *
2806  * In the remote case let's deal with MR routers.
2807  *
2808  */
2809
2810 static int
2811 lnet_handle_any_mr_dst(struct lnet_send_data *sd)
2812 {
2813         int rc = 0;
2814         struct lnet_peer *gw_peer = NULL;
2815         struct lnet_peer_ni *gw_lpni = NULL;
2816
2817         /*
2818          * handle sending a response to a remote peer here so we don't
2819          * have to worry about it if we hit lnet_handle_any_mr_dsta()
2820          */
2821         if (sd->sd_send_case & REMOTE_DST &&
2822             sd->sd_send_case & SND_RESP) {
2823                 struct lnet_peer_ni *gw;
2824                 struct lnet_peer *gw_peer;
2825
2826                 rc = lnet_handle_find_routed_path(
2827                         sd, &sd->sd_dst_nid, &gw, &gw_peer);
2828                 if (rc < 0) {
2829                         CERROR("Can't send response to %s. No route available\n",
2830                                libcfs_nidstr(&sd->sd_dst_nid));
2831                         return -EHOSTUNREACH;
2832                 } else if (rc > 0) {
2833                         return rc;
2834                 }
2835
2836                 sd->sd_best_lpni = gw;
2837                 sd->sd_peer = gw_peer;
2838
2839                 return lnet_handle_send(sd);
2840         }
2841
2842         /*
2843          * Even though the NID for the peer might not be on a local network,
2844          * since the peer is MR there could be other interfaces on the
2845          * local network. In that case we'd still like to prefer the local
2846          * network over the routed network. If we're unable to do that
2847          * then we select the best router among the different routed networks,
2848          * and if the router is MR then we can deal with it as such.
2849          */
2850         rc = lnet_handle_any_mr_dsta(sd);
2851         if (rc != PASS_THROUGH)
2852                 return rc;
2853
2854         /*
2855          * Now that we must route to the destination, we must consider the
2856          * MR case, where the destination has multiple interfaces, some of
2857          * which we can route to and others we do not. For this reason we
2858          * need to select the destination which we can route to and if
2859          * there are multiple, we need to round robin.
2860          */
2861         rc = lnet_handle_find_routed_path(sd, &sd->sd_dst_nid,
2862                                           &gw_lpni, &gw_peer);
2863         if (rc)
2864                 return rc;
2865
2866         sd->sd_send_case &= ~LOCAL_DST;
2867         sd->sd_send_case |= REMOTE_DST;
2868
2869         sd->sd_peer = gw_peer;
2870         sd->sd_best_lpni = gw_lpni;
2871
2872         return lnet_handle_send(sd);
2873 }
2874
2875 /*
2876  * Source not specified
2877  * Remote destination
2878  * Non-MR peer
2879  *
2880  * Must send to the specified peer NID using the same source NID that
2881  * we've used before. If it's the first time to talk to that peer then
2882  * find the source NI and assign it as preferred to that peer
2883  */
2884 static int
2885 lnet_handle_any_router_nmr_dst(struct lnet_send_data *sd)
2886 {
2887         int rc;
2888         struct lnet_peer_ni *gw_lpni = NULL;
2889         struct lnet_peer *gw_peer = NULL;
2890
2891         /*
2892          * Let's see if we have a preferred NI to talk to this NMR peer
2893          */
2894         sd->sd_best_ni = lnet_find_existing_preferred_best_ni(sd->sd_best_lpni,
2895                                                               sd->sd_cpt);
2896
2897         /*
2898          * find the router and that'll find the best NI if we didn't find
2899          * it already.
2900          */
2901         rc = lnet_handle_find_routed_path(sd, &sd->sd_dst_nid, &gw_lpni,
2902                                           &gw_peer);
2903         if (rc)
2904                 return rc;
2905
2906         /*
2907          * set the best_ni we've chosen as the preferred one for
2908          * this peer
2909          */
2910         lnet_set_non_mr_pref_nid(sd->sd_best_lpni, sd->sd_best_ni, sd->sd_msg);
2911
2912         /* we'll be sending to the gw */
2913         sd->sd_best_lpni = gw_lpni;
2914         sd->sd_peer = gw_peer;
2915
2916         return lnet_handle_send(sd);
2917 }
2918
2919 static int
2920 lnet_handle_send_case_locked(struct lnet_send_data *sd)
2921 {
2922         /*
2923          * turn off the SND_RESP bit.
2924          * It will be checked in the case handling
2925          */
2926         __u32 send_case = sd->sd_send_case &= ~SND_RESP ;
2927
2928         CDEBUG(D_NET, "Source %s%s to %s %s %s destination\n",
2929                 (send_case & SRC_SPEC) ? "Specified: " : "ANY",
2930                 (send_case & SRC_SPEC) ? libcfs_nidstr(&sd->sd_src_nid) : "",
2931                 (send_case & MR_DST) ? "MR: " : "NMR: ",
2932                 libcfs_nidstr(&sd->sd_dst_nid),
2933                 (send_case & LOCAL_DST) ? "local" : "routed");
2934
2935         switch (send_case) {
2936         /*
2937          * For all cases where the source is specified, we should always
2938          * use the destination NID, whether it's an MR destination or not,
2939          * since we're continuing a series of related messages for the
2940          * same RPC
2941          */
2942         case SRC_SPEC_LOCAL_NMR_DST:
2943                 return lnet_handle_spec_local_nmr_dst(sd);
2944         case SRC_SPEC_LOCAL_MR_DST:
2945                 return lnet_handle_spec_local_mr_dst(sd);
2946         case SRC_SPEC_ROUTER_NMR_DST:
2947         case SRC_SPEC_ROUTER_MR_DST:
2948                 return lnet_handle_spec_router_dst(sd);
2949         case SRC_ANY_LOCAL_NMR_DST:
2950                 return lnet_handle_any_local_nmr_dst(sd);
2951         case SRC_ANY_LOCAL_MR_DST:
2952         case SRC_ANY_ROUTER_MR_DST:
2953                 return lnet_handle_any_mr_dst(sd);
2954         case SRC_ANY_ROUTER_NMR_DST:
2955                 return lnet_handle_any_router_nmr_dst(sd);
2956         default:
2957                 CERROR("Unknown send case\n");
2958                 return -1;
2959         }
2960 }
2961
2962 static int
2963 lnet_select_pathway(struct lnet_nid *src_nid,
2964                     struct lnet_nid *dst_nid,
2965                     struct lnet_msg *msg,
2966                     struct lnet_nid *rtr_nid)
2967 {
2968         struct lnet_peer_ni *lpni;
2969         struct lnet_peer *peer;
2970         struct lnet_send_data send_data;
2971         int cpt, rc;
2972         int md_cpt;
2973         __u32 send_case = 0;
2974         bool final_hop;
2975         bool mr_forwarding_allowed;
2976
2977         memset(&send_data, 0, sizeof(send_data));
2978
2979         /*
2980          * get an initial CPT to use for locking. The idea here is not to
2981          * serialize the calls to select_pathway, so that as many
2982          * operations can run concurrently as possible. To do that we use
2983          * the CPT where this call is being executed. Later on when we
2984          * determine the CPT to use in lnet_message_commit, we switch the
2985          * lock and check if there was any configuration change.  If none,
2986          * then we proceed, if there is, then we restart the operation.
2987          */
2988         cpt = lnet_net_lock_current();
2989
2990         md_cpt = lnet_cpt_of_md(msg->msg_md, msg->msg_offset);
2991         if (md_cpt == CFS_CPT_ANY)
2992                 md_cpt = cpt;
2993
2994 again:
2995
2996         /*
2997          * If we're being asked to send to the loopback interface, there
2998          * is no need to go through any selection. We can just shortcut
2999          * the entire process and send over lolnd
3000          */
3001         send_data.sd_msg = msg;
3002         send_data.sd_cpt = cpt;
3003         if (nid_is_lo0(dst_nid)) {
3004                 rc = lnet_handle_lo_send(&send_data);
3005                 lnet_net_unlock(cpt);
3006                 return rc;
3007         }
3008
3009         /*
3010          * find an existing peer_ni, or create one and mark it as having been
3011          * created due to network traffic. This call will create the
3012          * peer->peer_net->peer_ni tree.
3013          */
3014         lpni = lnet_peerni_by_nid_locked(dst_nid, NULL, cpt);
3015         if (IS_ERR(lpni)) {
3016                 lnet_net_unlock(cpt);
3017                 return PTR_ERR(lpni);
3018         }
3019
3020         /*
3021          * Cache the original src_nid and rtr_nid. If we need to resend the
3022          * message then we'll need to know whether the src_nid was originally
3023          * specified for this message. If it was originally specified,
3024          * then we need to keep using the same src_nid since it's
3025          * continuing the same sequence of messages. Similarly, rtr_nid will
3026          * affect our choice of next hop.
3027          */
3028         if (src_nid)
3029                 msg->msg_src_nid_param = *src_nid;
3030         else
3031                 msg->msg_src_nid_param = LNET_ANY_NID;
3032         if (rtr_nid)
3033                 msg->msg_rtr_nid_param = *rtr_nid;
3034         else
3035                 msg->msg_rtr_nid_param = LNET_ANY_NID;
3036
3037         /*
3038          * If necessary, perform discovery on the peer that owns this peer_ni.
3039          * Note, this can result in the ownership of this peer_ni changing
3040          * to another peer object.
3041          */
3042         rc = lnet_initiate_peer_discovery(lpni, msg, cpt);
3043         if (rc) {
3044                 lnet_peer_ni_decref_locked(lpni);
3045                 lnet_net_unlock(cpt);
3046                 return rc;
3047         }
3048         lnet_peer_ni_decref_locked(lpni);
3049
3050         peer = lpni->lpni_peer_net->lpn_peer;
3051
3052         /*
3053          * Identify the different send cases
3054          */
3055         if (!src_nid || LNET_NID_IS_ANY(src_nid)) {
3056                 send_case |= SRC_ANY;
3057                 if (lnet_get_net_locked(LNET_NID_NET(dst_nid)))
3058                         send_case |= LOCAL_DST;
3059                 else
3060                         send_case |= REMOTE_DST;
3061         } else {
3062                 send_case |= SRC_SPEC;
3063                 if (LNET_NID_NET(src_nid) == LNET_NID_NET(dst_nid))
3064                         send_case |= LOCAL_DST;
3065                 else
3066                         send_case |= REMOTE_DST;
3067         }
3068
3069         final_hop = false;
3070         if (msg->msg_routing && (send_case & LOCAL_DST))
3071                 final_hop = true;
3072
3073         /* Determine whether to allow MR forwarding for this message.
3074          * NB: MR forwarding is allowed if the message originator and the
3075          * destination are both MR capable, and the destination lpni that was
3076          * originally chosen by the originator is unhealthy or down.
3077          * We check the MR capability of the destination further below
3078          */
3079         mr_forwarding_allowed = false;
3080         if (final_hop) {
3081                 struct lnet_peer *src_lp;
3082                 struct lnet_peer_ni *src_lpni;
3083
3084                 src_lpni = lnet_peerni_by_nid_locked(&msg->msg_hdr.src_nid,
3085                                                    NULL, cpt);
3086                 /* We don't fail the send if we hit any errors here. We'll just
3087                  * try to send it via non-multi-rail criteria
3088                  */
3089                 if (!IS_ERR(src_lpni)) {
3090                         /* Drop ref taken by lnet_peerni_by_nid_locked() */
3091                         lnet_peer_ni_decref_locked(src_lpni);
3092                         src_lp = lpni->lpni_peer_net->lpn_peer;
3093                         if (lnet_peer_is_multi_rail(src_lp) &&
3094                             !lnet_is_peer_ni_alive(lpni))
3095                                 mr_forwarding_allowed = true;
3096
3097                 }
3098                 CDEBUG(D_NET, "msg %p MR forwarding %s\n", msg,
3099                        mr_forwarding_allowed ? "allowed" : "not allowed");
3100         }
3101
3102         /*
3103          * Deal with the peer as NMR in the following cases:
3104          * 1. the peer is NMR
3105          * 2. We're trying to recover a specific peer NI
3106          * 3. I'm a router sending to the final destination and MR forwarding is
3107          *    not allowed for this message (as determined above).
3108          *    In this case the source of the message would've
3109          *    already selected the final destination so my job
3110          *    is to honor the selection.
3111          */
3112         if (!lnet_peer_is_multi_rail(peer) || msg->msg_recovery ||
3113             (final_hop && !mr_forwarding_allowed))
3114                 send_case |= NMR_DST;
3115         else
3116                 send_case |= MR_DST;
3117
3118         if (lnet_msg_is_response(msg))
3119                 send_case |= SND_RESP;
3120
3121         /* assign parameters to the send_data */
3122         if (rtr_nid)
3123                 send_data.sd_rtr_nid = *rtr_nid;
3124         else
3125                 send_data.sd_rtr_nid = LNET_ANY_NID;
3126         if (src_nid)
3127                 send_data.sd_src_nid = *src_nid;
3128         else
3129                 send_data.sd_src_nid = LNET_ANY_NID;
3130         send_data.sd_dst_nid = *dst_nid;
3131         send_data.sd_best_lpni = lpni;
3132         /*
3133          * keep a pointer to the final destination in case we're going to
3134          * route, so we'll need to access it later
3135          */
3136         send_data.sd_final_dst_lpni = lpni;
3137         send_data.sd_peer = peer;
3138         send_data.sd_md_cpt = md_cpt;
3139         send_data.sd_send_case = send_case;
3140
3141         rc = lnet_handle_send_case_locked(&send_data);
3142
3143         /*
3144          * Update the local cpt since send_data.sd_cpt might've been
3145          * updated as a result of calling lnet_handle_send_case_locked().
3146          */
3147         cpt = send_data.sd_cpt;
3148
3149         if (rc == REPEAT_SEND)
3150                 goto again;
3151
3152         lnet_net_unlock(cpt);
3153
3154         return rc;
3155 }
3156
3157 int
3158 lnet_send(struct lnet_nid *src_nid, struct lnet_msg *msg,
3159           struct lnet_nid *rtr_nid)
3160 {
3161         struct lnet_nid *dst_nid = &msg->msg_target.nid;
3162         int rc;
3163
3164         /* NB: ni != NULL == interface pre-determined (ACK/REPLY) */
3165         LASSERT(msg->msg_txpeer == NULL);
3166         LASSERT(msg->msg_txni == NULL);
3167         LASSERT(!msg->msg_sending);
3168         LASSERT(!msg->msg_target_is_router);
3169         LASSERT(!msg->msg_receiving);
3170
3171         msg->msg_sending = 1;
3172
3173         LASSERT(!msg->msg_tx_committed);
3174
3175         rc = lnet_select_pathway(src_nid, dst_nid, msg, rtr_nid);
3176         if (rc < 0) {
3177                 if (rc == -EHOSTUNREACH)
3178                         msg->msg_health_status = LNET_MSG_STATUS_REMOTE_ERROR;
3179                 else
3180                         msg->msg_health_status = LNET_MSG_STATUS_LOCAL_ERROR;
3181                 return rc;
3182         }
3183
3184         if (rc == LNET_CREDIT_OK)
3185                 lnet_ni_send(msg->msg_txni, msg);
3186
3187         /* rc == LNET_CREDIT_OK or LNET_CREDIT_WAIT or LNET_DC_WAIT */
3188         return 0;
3189 }
3190
3191 enum lnet_mt_event_type {
3192         MT_TYPE_LOCAL_NI = 0,
3193         MT_TYPE_PEER_NI
3194 };
3195
3196 struct lnet_mt_event_info {
3197         enum lnet_mt_event_type mt_type;
3198         struct lnet_nid mt_nid;
3199 };
3200
3201 /* called with res_lock held */
3202 void
3203 lnet_detach_rsp_tracker(struct lnet_libmd *md, int cpt)
3204 {
3205         struct lnet_rsp_tracker *rspt;
3206
3207         /*
3208          * msg has a refcount on the MD so the MD is not going away.
3209          * The rspt queue for the cpt is protected by
3210          * the lnet_net_lock(cpt). cpt is the cpt of the MD cookie.
3211          */
3212         if (!md->md_rspt_ptr)
3213                 return;
3214
3215         rspt = md->md_rspt_ptr;
3216
3217         /* debug code */
3218         LASSERT(rspt->rspt_cpt == cpt);
3219
3220         md->md_rspt_ptr = NULL;
3221
3222         if (LNetMDHandleIsInvalid(rspt->rspt_mdh)) {
3223                 /*
3224                  * The monitor thread has invalidated this handle because the
3225                  * response timed out, but it failed to lookup the MD. That
3226                  * means this response tracker is on the zombie list. We can
3227                  * safely remove it under the resource lock (held by caller) and
3228                  * free the response tracker block.
3229                  */
3230                 list_del(&rspt->rspt_on_list);
3231                 lnet_rspt_free(rspt, cpt);
3232         } else {
3233                 /*
3234                  * invalidate the handle to indicate that a response has been
3235                  * received, which will then lead the monitor thread to clean up
3236                  * the rspt block.
3237                  */
3238                 LNetInvalidateMDHandle(&rspt->rspt_mdh);
3239         }
3240 }
3241
3242 void
3243 lnet_clean_zombie_rstqs(void)
3244 {
3245         struct lnet_rsp_tracker *rspt, *tmp;
3246         int i;
3247
3248         cfs_cpt_for_each(i, lnet_cpt_table()) {
3249                 list_for_each_entry_safe(rspt, tmp,
3250                                          the_lnet.ln_mt_zombie_rstqs[i],
3251                                          rspt_on_list) {
3252                         list_del(&rspt->rspt_on_list);
3253                         lnet_rspt_free(rspt, i);
3254                 }
3255         }
3256
3257         cfs_percpt_free(the_lnet.ln_mt_zombie_rstqs);
3258 }
3259
3260 static void
3261 lnet_finalize_expired_responses(void)
3262 {
3263         struct lnet_libmd *md;
3264         struct lnet_rsp_tracker *rspt, *tmp;
3265         ktime_t now;
3266         int i;
3267
3268         if (the_lnet.ln_mt_rstq == NULL)
3269                 return;
3270
3271         cfs_cpt_for_each(i, lnet_cpt_table()) {
3272                 LIST_HEAD(local_queue);
3273
3274                 lnet_net_lock(i);
3275                 if (!the_lnet.ln_mt_rstq[i]) {
3276                         lnet_net_unlock(i);
3277                         continue;
3278                 }
3279                 list_splice_init(the_lnet.ln_mt_rstq[i], &local_queue);
3280                 lnet_net_unlock(i);
3281
3282                 now = ktime_get();
3283
3284                 list_for_each_entry_safe(rspt, tmp, &local_queue, rspt_on_list) {
3285                         /*
3286                          * The rspt mdh will be invalidated when a response
3287                          * is received or whenever we want to discard the
3288                          * block the monitor thread will walk the queue
3289                          * and clean up any rsts with an invalid mdh.
3290                          * The monitor thread will walk the queue until
3291                          * the first unexpired rspt block. This means that
3292                          * some rspt blocks which received their
3293                          * corresponding responses will linger in the
3294                          * queue until they are cleaned up eventually.
3295                          */
3296                         lnet_res_lock(i);
3297                         if (LNetMDHandleIsInvalid(rspt->rspt_mdh)) {
3298                                 lnet_res_unlock(i);
3299                                 list_del(&rspt->rspt_on_list);
3300                                 lnet_rspt_free(rspt, i);
3301                                 continue;
3302                         }
3303
3304                         if (ktime_compare(now, rspt->rspt_deadline) >= 0 ||
3305                             the_lnet.ln_mt_state == LNET_MT_STATE_SHUTDOWN) {
3306                                 struct lnet_peer_ni *lpni;
3307                                 struct lnet_nid nid;
3308
3309                                 md = lnet_handle2md(&rspt->rspt_mdh);
3310                                 if (!md) {
3311                                         /* MD has been queued for unlink, but
3312                                          * rspt hasn't been detached (Note we've
3313                                          * checked above that the rspt_mdh is
3314                                          * valid). Since we cannot lookup the MD
3315                                          * we're unable to detach the rspt
3316                                          * ourselves. Thus, move the rspt to the
3317                                          * zombie list where we'll wait for
3318                                          * either:
3319                                          *   1. The remaining operations on the
3320                                          *   MD to complete. In this case the
3321                                          *   final operation will result in
3322                                          *   lnet_msg_detach_md()->
3323                                          *   lnet_detach_rsp_tracker() where
3324                                          *   we will clean up this response
3325                                          *   tracker.
3326                                          *   2. LNet to shutdown. In this case
3327                                          *   we'll wait until after all LND Nets
3328                                          *   have shutdown and then we can
3329                                          *   safely free any remaining response
3330                                          *   tracker blocks on the zombie list.
3331                                          * Note: We need to hold the resource
3332                                          * lock when adding to the zombie list
3333                                          * because we may have concurrent access
3334                                          * with lnet_detach_rsp_tracker().
3335                                          */
3336                                         LNetInvalidateMDHandle(&rspt->rspt_mdh);
3337                                         list_move(&rspt->rspt_on_list,
3338                                                   the_lnet.ln_mt_zombie_rstqs[i]);
3339                                         lnet_res_unlock(i);
3340                                         continue;
3341                                 }
3342                                 LASSERT(md->md_rspt_ptr == rspt);
3343                                 md->md_rspt_ptr = NULL;
3344                                 lnet_res_unlock(i);
3345
3346                                 LNetMDUnlink(rspt->rspt_mdh);
3347
3348                                 nid = rspt->rspt_next_hop_nid;
3349
3350                                 list_del(&rspt->rspt_on_list);
3351                                 lnet_rspt_free(rspt, i);
3352
3353                                 /* If we're shutting down we just want to clean
3354                                  * up the rspt blocks
3355                                  */
3356                                 if (the_lnet.ln_mt_state == LNET_MT_STATE_SHUTDOWN)
3357                                         continue;
3358
3359                                 lnet_net_lock(i);
3360                                 the_lnet.ln_counters[i]->lct_health.lch_response_timeout_count++;
3361                                 lnet_net_unlock(i);
3362
3363                                 CDEBUG(D_NET,
3364                                        "Response timeout: md = %p: nid = %s\n",
3365                                        md, libcfs_nidstr(&nid));
3366
3367                                 /*
3368                                  * If there is a timeout on the response
3369                                  * from the next hop decrement its health
3370                                  * value so that we don't use it
3371                                  */
3372                                 lnet_net_lock(0);
3373                                 lpni = lnet_peer_ni_find_locked(&nid);
3374                                 if (lpni) {
3375                                         lnet_handle_remote_failure_locked(lpni);
3376                                         lnet_peer_ni_decref_locked(lpni);
3377                                 }
3378                                 lnet_net_unlock(0);
3379                         } else {
3380                                 lnet_res_unlock(i);
3381                                 break;
3382                         }
3383                 }
3384
3385                 if (!list_empty(&local_queue)) {
3386                         lnet_net_lock(i);
3387                         list_splice(&local_queue, the_lnet.ln_mt_rstq[i]);
3388                         lnet_net_unlock(i);
3389                 }
3390         }
3391 }
3392
3393 static void
3394 lnet_resend_pending_msgs_locked(struct list_head *resendq, int cpt)
3395 {
3396         struct lnet_msg *msg;
3397
3398         while (!list_empty(resendq)) {
3399                 struct lnet_peer_ni *lpni;
3400
3401                 msg = list_first_entry(resendq, struct lnet_msg,
3402                                        msg_list);
3403
3404                 list_del_init(&msg->msg_list);
3405
3406                 lpni = lnet_peer_ni_find_locked(&msg->msg_hdr.dest_nid);
3407                 if (!lpni) {
3408                         lnet_net_unlock(cpt);
3409                         CERROR("Expected that a peer is already created for %s\n",
3410                                libcfs_nidstr(&msg->msg_hdr.dest_nid));
3411                         msg->msg_no_resend = true;
3412                         lnet_finalize(msg, -EFAULT);
3413                         lnet_net_lock(cpt);
3414                 } else {
3415                         int rc;
3416
3417                         lnet_peer_ni_decref_locked(lpni);
3418
3419                         lnet_net_unlock(cpt);
3420                         CDEBUG(D_NET, "resending %s->%s: %s recovery %d try# %d\n",
3421                                libcfs_nidstr(&msg->msg_src_nid_param),
3422                                libcfs_idstr(&msg->msg_target),
3423                                lnet_msgtyp2str(msg->msg_type),
3424                                msg->msg_recovery,
3425                                msg->msg_retry_count);
3426                         rc = lnet_send(&msg->msg_src_nid_param, msg,
3427                                        &msg->msg_rtr_nid_param);
3428                         if (rc) {
3429                                 CERROR("Error sending %s to %s: %d\n",
3430                                        lnet_msgtyp2str(msg->msg_type),
3431                                        libcfs_idstr(&msg->msg_target), rc);
3432                                 msg->msg_no_resend = true;
3433                                 lnet_finalize(msg, rc);
3434                         }
3435                         lnet_net_lock(cpt);
3436                         if (!rc)
3437                                 the_lnet.ln_counters[cpt]->lct_health.lch_resend_count++;
3438                 }
3439         }
3440 }
3441
3442 static void
3443 lnet_resend_pending_msgs(void)
3444 {
3445         int i;
3446
3447         cfs_cpt_for_each(i, lnet_cpt_table()) {
3448                 lnet_net_lock(i);
3449                 lnet_resend_pending_msgs_locked(the_lnet.ln_mt_resendqs[i], i);
3450                 lnet_net_unlock(i);
3451         }
3452 }
3453
3454 /* called with cpt and ni_lock held */
3455 static void
3456 lnet_unlink_ni_recovery_mdh_locked(struct lnet_ni *ni, int cpt, bool force)
3457 {
3458         struct lnet_handle_md recovery_mdh;
3459
3460         LNetInvalidateMDHandle(&recovery_mdh);
3461
3462         if (ni->ni_recovery_state & LNET_NI_RECOVERY_PENDING ||
3463             force) {
3464                 recovery_mdh = ni->ni_ping_mdh;
3465                 LNetInvalidateMDHandle(&ni->ni_ping_mdh);
3466         }
3467         lnet_ni_unlock(ni);
3468         lnet_net_unlock(cpt);
3469         if (!LNetMDHandleIsInvalid(recovery_mdh))
3470                 LNetMDUnlink(recovery_mdh);
3471         lnet_net_lock(cpt);
3472         lnet_ni_lock(ni);
3473 }
3474
3475 /* Returns the total number of local NIs in recovery.
3476  * Records up to @arrsz of the associated NIDs in the @nidarr array
3477  */
3478 static int
3479 lnet_recover_local_nis(struct lnet_nid *nidarr, unsigned int arrsz)
3480 {
3481         struct lnet_mt_event_info *ev_info;
3482         LIST_HEAD(processed_list);
3483         LIST_HEAD(local_queue);
3484         struct lnet_handle_md mdh;
3485         struct lnet_ni *tmp;
3486         struct lnet_ni *ni;
3487         struct lnet_nid nid;
3488         int healthv;
3489         int rc;
3490         time64_t now;
3491         unsigned int nnis = 0;
3492
3493         /*
3494          * splice the recovery queue on a local queue. We will iterate
3495          * through the local queue and update it as needed. Once we're
3496          * done with the traversal, we'll splice the local queue back on
3497          * the head of the ln_mt_localNIRecovq. Any newly added local NIs
3498          * will be traversed in the next iteration.
3499          */
3500         lnet_net_lock(0);
3501         list_splice_init(&the_lnet.ln_mt_localNIRecovq,
3502                          &local_queue);
3503         lnet_net_unlock(0);
3504
3505         now = ktime_get_seconds();
3506
3507         list_for_each_entry_safe(ni, tmp, &local_queue, ni_recovery) {
3508                 /*
3509                  * if an NI is being deleted or it is now healthy, there
3510                  * is no need to keep it around in the recovery queue.
3511                  * The monitor thread is the only thread responsible for
3512                  * removing the NI from the recovery queue.
3513                  * Multiple threads can be adding NIs to the recovery
3514                  * queue.
3515                  */
3516                 healthv = atomic_read(&ni->ni_healthv);
3517
3518                 lnet_net_lock(0);
3519                 lnet_ni_lock(ni);
3520                 if (ni->ni_state != LNET_NI_STATE_ACTIVE ||
3521                     healthv == LNET_MAX_HEALTH_VALUE) {
3522                         list_del_init(&ni->ni_recovery);
3523                         lnet_unlink_ni_recovery_mdh_locked(ni, 0, false);
3524                         lnet_ni_unlock(ni);
3525                         lnet_ni_decref_locked(ni, 0);
3526                         lnet_net_unlock(0);
3527                         continue;
3528                 }
3529
3530                 if (nnis < arrsz)
3531                         nidarr[nnis] = ni->ni_nid;
3532                 nnis++;
3533
3534                 /*
3535                  * if the local NI failed recovery we must unlink the md.
3536                  * But we want to keep the local_ni on the recovery queue
3537                  * so we can continue the attempts to recover it.
3538                  */
3539                 if (ni->ni_recovery_state & LNET_NI_RECOVERY_FAILED) {
3540                         lnet_unlink_ni_recovery_mdh_locked(ni, 0, true);
3541                         ni->ni_recovery_state &= ~LNET_NI_RECOVERY_FAILED;
3542                 }
3543
3544
3545                 lnet_ni_unlock(ni);
3546
3547                 if (now < ni->ni_next_ping) {
3548                         lnet_net_unlock(0);
3549                         continue;
3550                 }
3551
3552                 lnet_net_unlock(0);
3553
3554                 CDEBUG(D_NET, "attempting to recover local ni: %s\n",
3555                        libcfs_nidstr(&ni->ni_nid));
3556
3557                 lnet_ni_lock(ni);
3558                 if (!(ni->ni_recovery_state & LNET_NI_RECOVERY_PENDING)) {
3559                         ni->ni_recovery_state |= LNET_NI_RECOVERY_PENDING;
3560                         lnet_ni_unlock(ni);
3561
3562                         LIBCFS_ALLOC(ev_info, sizeof(*ev_info));
3563                         if (!ev_info) {
3564                                 CERROR("out of memory. Can't recover %s\n",
3565                                        libcfs_nidstr(&ni->ni_nid));
3566                                 lnet_ni_lock(ni);
3567                                 ni->ni_recovery_state &=
3568                                   ~LNET_NI_RECOVERY_PENDING;
3569                                 lnet_ni_unlock(ni);
3570                                 continue;
3571                         }
3572
3573                         mdh = ni->ni_ping_mdh;
3574                         /*
3575                          * Invalidate the ni mdh in case it's deleted.
3576                          * We'll unlink the mdh in this case below.
3577                          */
3578                         LNetInvalidateMDHandle(&ni->ni_ping_mdh);
3579                         nid = ni->ni_nid;
3580
3581                         /*
3582                          * remove the NI from the local queue and drop the
3583                          * reference count to it while we're recovering
3584                          * it. The reason for that, is that the NI could
3585                          * be deleted, and the way the code is structured
3586                          * is if we don't drop the NI, then the deletion
3587                          * code will enter a loop waiting for the
3588                          * reference count to be removed while holding the
3589                          * ln_mutex_lock(). When we look up the peer to
3590                          * send to in lnet_select_pathway() we will try to
3591                          * lock the ln_mutex_lock() as well, leading to
3592                          * a deadlock. By dropping the refcount and
3593                          * removing it from the list, we allow for the NI
3594                          * to be removed, then we use the cached NID to
3595                          * look it up again. If it's gone, then we just
3596                          * continue examining the rest of the queue.
3597                          */
3598                         lnet_net_lock(0);
3599                         list_del_init(&ni->ni_recovery);
3600                         lnet_ni_decref_locked(ni, 0);
3601                         lnet_net_unlock(0);
3602
3603                         ev_info->mt_type = MT_TYPE_LOCAL_NI;
3604                         ev_info->mt_nid = nid;
3605                         rc = lnet_send_ping(&nid, &mdh, LNET_PING_INFO_MIN_SIZE,
3606                                             ev_info, the_lnet.ln_mt_handler,
3607                                             true);
3608                         /* lookup the nid again */
3609                         lnet_net_lock(0);
3610                         ni = lnet_nid_to_ni_locked(&nid, 0);
3611                         if (!ni) {
3612                                 /*
3613                                  * the NI has been deleted when we dropped
3614                                  * the ref count
3615                                  */
3616                                 lnet_net_unlock(0);
3617                                 LNetMDUnlink(mdh);
3618                                 continue;
3619                         }
3620                         ni->ni_ping_count++;
3621
3622                         ni->ni_ping_mdh = mdh;
3623                         lnet_ni_add_to_recoveryq_locked(ni, &processed_list,
3624                                                         now);
3625
3626                         if (rc) {
3627                                 lnet_ni_lock(ni);
3628                                 ni->ni_recovery_state &= ~LNET_NI_RECOVERY_PENDING;
3629                                 lnet_ni_unlock(ni);
3630                         }
3631                         lnet_net_unlock(0);
3632                 } else
3633                         lnet_ni_unlock(ni);
3634         }
3635
3636         /*
3637          * put back the remaining NIs on the ln_mt_localNIRecovq to be
3638          * reexamined in the next iteration.
3639          */
3640         list_splice_init(&processed_list, &local_queue);
3641         lnet_net_lock(0);
3642         list_splice(&local_queue, &the_lnet.ln_mt_localNIRecovq);
3643         lnet_net_unlock(0);
3644
3645         return nnis;
3646 }
3647
3648 static int
3649 lnet_resendqs_create(void)
3650 {
3651         struct list_head **resendqs;
3652         resendqs = lnet_create_array_of_queues();
3653
3654         if (!resendqs)
3655                 return -ENOMEM;
3656
3657         lnet_net_lock(LNET_LOCK_EX);
3658         the_lnet.ln_mt_resendqs = resendqs;
3659         lnet_net_unlock(LNET_LOCK_EX);
3660
3661         return 0;
3662 }
3663
3664 static void
3665 lnet_clean_local_ni_recoveryq(void)
3666 {
3667         struct lnet_ni *ni;
3668
3669         /* This is only called when the monitor thread has stopped */
3670         lnet_net_lock(0);
3671
3672         while ((ni = list_first_entry_or_null(&the_lnet.ln_mt_localNIRecovq,
3673                                               struct lnet_ni,
3674                                               ni_recovery)) != NULL) {
3675                 list_del_init(&ni->ni_recovery);
3676                 lnet_ni_lock(ni);
3677                 lnet_unlink_ni_recovery_mdh_locked(ni, 0, true);
3678                 lnet_ni_unlock(ni);
3679                 lnet_ni_decref_locked(ni, 0);
3680         }
3681
3682         lnet_net_unlock(0);
3683 }
3684
3685 static void
3686 lnet_unlink_lpni_recovery_mdh_locked(struct lnet_peer_ni *lpni, int cpt,
3687                                      bool force)
3688 {
3689         struct lnet_handle_md recovery_mdh;
3690
3691         LNetInvalidateMDHandle(&recovery_mdh);
3692
3693         if (lpni->lpni_state & LNET_PEER_NI_RECOVERY_PENDING || force) {
3694                 recovery_mdh = lpni->lpni_recovery_ping_mdh;
3695                 LNetInvalidateMDHandle(&lpni->lpni_recovery_ping_mdh);
3696         }
3697         spin_unlock(&lpni->lpni_lock);
3698         lnet_net_unlock(cpt);
3699         if (!LNetMDHandleIsInvalid(recovery_mdh))
3700                 LNetMDUnlink(recovery_mdh);
3701         lnet_net_lock(cpt);
3702         spin_lock(&lpni->lpni_lock);
3703 }
3704
3705 static void
3706 lnet_clean_peer_ni_recoveryq(void)
3707 {
3708         struct lnet_peer_ni *lpni, *tmp;
3709
3710         lnet_net_lock(LNET_LOCK_EX);
3711
3712         list_for_each_entry_safe(lpni, tmp, &the_lnet.ln_mt_peerNIRecovq,
3713                                  lpni_recovery) {
3714                 list_del_init(&lpni->lpni_recovery);
3715                 spin_lock(&lpni->lpni_lock);
3716                 lnet_unlink_lpni_recovery_mdh_locked(lpni, LNET_LOCK_EX, true);
3717                 spin_unlock(&lpni->lpni_lock);
3718                 lnet_peer_ni_decref_locked(lpni);
3719         }
3720
3721         lnet_net_unlock(LNET_LOCK_EX);
3722 }
3723
3724 static void
3725 lnet_clean_resendqs(void)
3726 {
3727         struct lnet_msg *msg, *tmp;
3728         LIST_HEAD(msgs);
3729         int i;
3730
3731         cfs_cpt_for_each(i, lnet_cpt_table()) {
3732                 lnet_net_lock(i);
3733                 list_splice_init(the_lnet.ln_mt_resendqs[i], &msgs);
3734                 lnet_net_unlock(i);
3735                 list_for_each_entry_safe(msg, tmp, &msgs, msg_list) {
3736                         list_del_init(&msg->msg_list);
3737                         msg->msg_no_resend = true;
3738                         lnet_finalize(msg, -ESHUTDOWN);
3739                 }
3740         }
3741
3742         cfs_percpt_free(the_lnet.ln_mt_resendqs);
3743 }
3744
3745 /* Returns the total number of peer NIs in recovery.
3746  * Records up to @arrsz of the associated NIDs in the @nidarr array
3747  */
3748 static unsigned int
3749 lnet_recover_peer_nis(struct lnet_nid *nidarr, unsigned int arrsz)
3750 {
3751         struct lnet_mt_event_info *ev_info;
3752         LIST_HEAD(processed_list);
3753         LIST_HEAD(local_queue);
3754         struct lnet_handle_md mdh;
3755         struct lnet_peer_ni *lpni;
3756         struct lnet_peer_ni *tmp;
3757         struct lnet_nid nid;
3758         int healthv;
3759         int rc;
3760         time64_t now;
3761         unsigned int nlpnis = 0;
3762
3763         /*
3764          * Always use cpt 0 for locking across all interactions with
3765          * ln_mt_peerNIRecovq
3766          */
3767         lnet_net_lock(0);
3768         list_splice_init(&the_lnet.ln_mt_peerNIRecovq,
3769                          &local_queue);
3770         lnet_net_unlock(0);
3771
3772         now = ktime_get_seconds();
3773
3774         list_for_each_entry_safe(lpni, tmp, &local_queue,
3775                                  lpni_recovery) {
3776                 /*
3777                  * The same protection strategy is used here as is in the
3778                  * local recovery case.
3779                  */
3780                 lnet_net_lock(0);
3781                 healthv = atomic_read(&lpni->lpni_healthv);
3782                 spin_lock(&lpni->lpni_lock);
3783                 if (lpni->lpni_state & LNET_PEER_NI_DELETING ||
3784                     healthv == LNET_MAX_HEALTH_VALUE) {
3785                         list_del_init(&lpni->lpni_recovery);
3786                         lnet_unlink_lpni_recovery_mdh_locked(lpni, 0, false);
3787                         spin_unlock(&lpni->lpni_lock);
3788                         lnet_peer_ni_decref_locked(lpni);
3789                         lnet_net_unlock(0);
3790                         continue;
3791                 }
3792
3793                 if (nlpnis < arrsz)
3794                         nidarr[nlpnis] = lpni->lpni_nid;
3795                 nlpnis++;
3796
3797                 /*
3798                  * If the peer NI has failed recovery we must unlink the
3799                  * md. But we want to keep the peer ni on the recovery
3800                  * queue so we can try to continue recovering it
3801                  */
3802                 if (lpni->lpni_state & LNET_PEER_NI_RECOVERY_FAILED) {
3803                         lnet_unlink_lpni_recovery_mdh_locked(lpni, 0, true);
3804                         lpni->lpni_state &= ~LNET_PEER_NI_RECOVERY_FAILED;
3805                 }
3806
3807                 spin_unlock(&lpni->lpni_lock);
3808
3809                 if (now < lpni->lpni_next_ping) {
3810                         lnet_net_unlock(0);
3811                         continue;
3812                 }
3813
3814                 lnet_net_unlock(0);
3815
3816                 /*
3817                  * NOTE: we're racing with peer deletion from user space.
3818                  * It's possible that a peer is deleted after we check its
3819                  * state. In this case the recovery can create a new peer
3820                  */
3821                 spin_lock(&lpni->lpni_lock);
3822                 if (!(lpni->lpni_state & LNET_PEER_NI_RECOVERY_PENDING) &&
3823                     !(lpni->lpni_state & LNET_PEER_NI_DELETING)) {
3824                         lpni->lpni_state |= LNET_PEER_NI_RECOVERY_PENDING;
3825                         spin_unlock(&lpni->lpni_lock);
3826
3827                         LIBCFS_ALLOC(ev_info, sizeof(*ev_info));
3828                         if (!ev_info) {
3829                                 CERROR("out of memory. Can't recover %s\n",
3830                                        libcfs_nidstr(&lpni->lpni_nid));
3831                                 spin_lock(&lpni->lpni_lock);
3832                                 lpni->lpni_state &= ~LNET_PEER_NI_RECOVERY_PENDING;
3833                                 spin_unlock(&lpni->lpni_lock);
3834                                 continue;
3835                         }
3836
3837                         /* look at the comments in lnet_recover_local_nis() */
3838                         mdh = lpni->lpni_recovery_ping_mdh;
3839                         nid = lpni->lpni_nid;
3840                         LNetInvalidateMDHandle(&lpni->lpni_recovery_ping_mdh);
3841                         lnet_net_lock(0);
3842                         list_del_init(&lpni->lpni_recovery);
3843                         lnet_peer_ni_decref_locked(lpni);
3844                         lnet_net_unlock(0);
3845
3846                         ev_info->mt_type = MT_TYPE_PEER_NI;
3847                         ev_info->mt_nid = nid;
3848                         rc = lnet_send_ping(&nid, &mdh, LNET_PING_INFO_MIN_SIZE,
3849                                             ev_info, the_lnet.ln_mt_handler,
3850                                             true);
3851                         lnet_net_lock(0);
3852                         /*
3853                          * lnet_peer_ni_find_locked() grabs a refcount for
3854                          * us. No need to take it explicitly.
3855                          */
3856                         lpni = lnet_peer_ni_find_locked(&nid);
3857                         if (!lpni) {
3858                                 lnet_net_unlock(0);
3859                                 LNetMDUnlink(mdh);
3860                                 continue;
3861                         }
3862
3863                         lpni->lpni_ping_count++;
3864
3865                         lpni->lpni_recovery_ping_mdh = mdh;
3866
3867                         lnet_peer_ni_add_to_recoveryq_locked(lpni,
3868                                                              &processed_list,
3869                                                              now);
3870                         if (rc) {
3871                                 spin_lock(&lpni->lpni_lock);
3872                                 lpni->lpni_state &= ~LNET_PEER_NI_RECOVERY_PENDING;
3873                                 spin_unlock(&lpni->lpni_lock);
3874                         }
3875
3876                         /* Drop the ref taken by lnet_peer_ni_find_locked() */
3877                         lnet_peer_ni_decref_locked(lpni);
3878                         lnet_net_unlock(0);
3879                 } else {
3880                         spin_unlock(&lpni->lpni_lock);
3881                 }
3882         }
3883
3884         list_splice_init(&processed_list, &local_queue);
3885         lnet_net_lock(0);
3886         list_splice(&local_queue, &the_lnet.ln_mt_peerNIRecovq);
3887         lnet_net_unlock(0);
3888
3889         return nlpnis;
3890 }
3891
3892 #define LNET_MAX_NNIDS 20
3893 /* @nids is array of nids that are in recovery. It has max size of
3894  * LNET_MAX_NNIDS.
3895  * @nnids is the total number of nids that are in recovery. It can be
3896  * larger than LNET_MAX_NNIDS.
3897  * @local tells us whether these are local or peer NIs in recovery.
3898  */
3899 static void
3900 lnet_print_recovery_list(struct lnet_nid *nids, unsigned int nnids,
3901                          bool local)
3902 {
3903         static bool printed;
3904         char *buf = NULL;
3905         char *tmp;
3906         int i;
3907         unsigned int arrsz;
3908         unsigned int bufsz;
3909
3910         if (!nnids)
3911                 return;
3912
3913         arrsz = nnids < LNET_MAX_NNIDS ? nnids : LNET_MAX_NNIDS;
3914
3915         /* Printing arrsz NIDs, each has max size LNET_NIDSTR_SIZE, a comma
3916          * and space for each nid after the first (2 * (arrsz - 1)),
3917          * + 1 for terminating null byte
3918          */
3919         bufsz = (arrsz * LNET_NIDSTR_SIZE) + (2 * (arrsz - 1)) + 1;
3920         LIBCFS_ALLOC(buf, bufsz);
3921         if (!buf) {
3922                 LCONSOLE(D_INFO, "%u %s NIs in recovery\n",
3923                          nnids, local ? "local" : "peer");
3924                 return;
3925         }
3926
3927         tmp = buf;
3928         tmp += sprintf(tmp, "%s", libcfs_nidstr(&nids[0]));
3929         for (i = 1; i < arrsz; i++)
3930                 tmp += sprintf(tmp, ", %s", libcfs_nidstr(&nids[i]));
3931
3932         /* LCONSOLE() used to avoid rate limiting when we have both local
3933          * and peer NIs in recovery
3934          */
3935         LCONSOLE(D_INFO, "%u %s NIs in recovery (showing %u): %s\n",
3936                  nnids, local ? "local" : "peer", arrsz, buf);
3937
3938         LIBCFS_FREE(buf, bufsz);
3939
3940         if (!printed && nnids > LNET_MAX_NNIDS) {
3941                 LCONSOLE(D_INFO, "See full list with 'lnetctl debug recovery -(p|l)'\n");
3942                 printed = true;
3943         }
3944 }
3945
3946 static void
3947 lnet_health_update_console(struct lnet_nid *lnids, unsigned int nnis,
3948                            struct lnet_nid *rnids, unsigned int nlpnis,
3949                            time64_t now)
3950 {
3951         static time64_t next_ni_update;
3952         static time64_t next_lpni_update;
3953         static time64_t next_msg_update;
3954         static unsigned int num_ni_updates;
3955         static unsigned int num_lpni_updates;
3956         static unsigned int num_msg_updates = 1;
3957         int late_count;
3958
3959         if (now >= next_ni_update) {
3960                 if (nnis) {
3961                         lnet_print_recovery_list(lnids, nnis, true);
3962                         if (num_ni_updates < 5)
3963                                 num_ni_updates++;
3964                         next_ni_update = now + (60 * num_ni_updates);
3965                 } else {
3966                         next_ni_update = 0;
3967                         num_ni_updates = 0;
3968                 }
3969         }
3970
3971
3972         if (now >= next_lpni_update) {
3973                 if (nlpnis) {
3974                         lnet_print_recovery_list(rnids, nlpnis, false);
3975                         if (num_lpni_updates < 5)
3976                                 num_lpni_updates++;
3977                         next_lpni_update = now + (60 * num_lpni_updates);
3978                 } else {
3979                         next_lpni_update = 0;
3980                         num_lpni_updates = 0;
3981                 }
3982         }
3983
3984         /* Let late_count accumulate for 60 seconds */
3985         if (unlikely(!next_msg_update))
3986                 next_msg_update = now + 60;
3987
3988         if (now >= next_msg_update) {
3989                 late_count = atomic_read(&the_lnet.ln_late_msg_count);
3990
3991                 if (late_count) {
3992                         s64 avg = atomic64_xchg(&the_lnet.ln_late_msg_nsecs, 0) /
3993                                   atomic_xchg(&the_lnet.ln_late_msg_count, 0);
3994
3995                         if (avg > NSEC_PER_SEC) {
3996                                 unsigned int avg_msec;
3997
3998                                 avg_msec = do_div(avg, NSEC_PER_SEC) /
3999                                                 NSEC_PER_MSEC;
4000                                 LCONSOLE_INFO("%u messages in past %us over their deadline by avg %lld.%03us\n",
4001                                               late_count,
4002                                               (60 * num_msg_updates), avg,
4003                                               avg_msec);
4004
4005                                 if (num_msg_updates < 5)
4006                                         num_msg_updates++;
4007                                 next_msg_update = now + (60 * num_msg_updates);
4008                         }
4009                 } else {
4010                         next_msg_update = now + 60;
4011                         num_msg_updates = 1;
4012                 }
4013         }
4014 }
4015
4016 static int
4017 lnet_monitor_thread(void *arg)
4018 {
4019         time64_t rsp_timeout = 0;
4020         time64_t now;
4021         unsigned int nnis;
4022         unsigned int nlpnis;
4023         struct lnet_nid local_nids[LNET_MAX_NNIDS];
4024         struct lnet_nid peer_nids[LNET_MAX_NNIDS];
4025
4026         wait_for_completion(&the_lnet.ln_started);
4027
4028         /*
4029          * The monitor thread takes care of the following:
4030          *  1. Checks the aliveness of routers
4031          *  2. Checks if there are messages on the resend queue to resend
4032          *     them.
4033          *  3. Checks if there are any NIs on the local recovery queue and
4034          *     pings them
4035          *  4. Checks if there are any NIs on the remote recovery queue
4036          *     and pings them.
4037          *  5. Updates the ping buffer if requested by LNDs upon interface
4038          *     state change
4039          */
4040         while (the_lnet.ln_mt_state == LNET_MT_STATE_RUNNING) {
4041                 now = ktime_get_real_seconds();
4042
4043                 if (lnet_router_checker_active())
4044                         lnet_check_routers();
4045
4046                 lnet_resend_pending_msgs();
4047
4048                 if (now >= rsp_timeout) {
4049                         lnet_finalize_expired_responses();
4050                         rsp_timeout = now + (lnet_transaction_timeout / 2);
4051                 }
4052
4053                 nnis = lnet_recover_local_nis(local_nids, LNET_MAX_NNIDS);
4054                 nlpnis = lnet_recover_peer_nis(peer_nids, LNET_MAX_NNIDS);
4055                 lnet_health_update_console(local_nids, nnis, peer_nids, nlpnis,
4056                                            now);
4057                 lnet_update_ping_buffer();
4058
4059                 /*
4060                  * TODO do we need to check if we should sleep without
4061                  * timeout?  Technically, an active system will always
4062                  * have messages in flight so this check will always
4063                  * evaluate to false. And on an idle system do we care
4064                  * if we wake up every 1 second? Although, we've seen
4065                  * cases where we get a complaint that an idle thread
4066                  * is waking up unnecessarily.
4067                  */
4068                 wait_for_completion_interruptible_timeout(
4069                         &the_lnet.ln_mt_wait_complete,
4070                         cfs_time_seconds(1));
4071                 /* Must re-init the completion before testing anything,
4072                  * including ln_mt_state.
4073                  */
4074                 reinit_completion(&the_lnet.ln_mt_wait_complete);
4075         }
4076
4077         /* Shutting down */
4078         lnet_net_lock(LNET_LOCK_EX);
4079         the_lnet.ln_mt_state = LNET_MT_STATE_SHUTDOWN;
4080         lnet_net_unlock(LNET_LOCK_EX);
4081
4082         /* signal that the monitor thread is exiting */
4083         up(&the_lnet.ln_mt_signal);
4084
4085         return 0;
4086 }
4087
4088 /*
4089  * lnet_send_ping
4090  * Sends a ping.
4091  * Returns == 0 if success
4092  * Returns > 0 if LNetMDBind or prior fails
4093  * Returns < 0 if LNetGet fails
4094  */
4095 int
4096 lnet_send_ping(struct lnet_nid *dest_nid,
4097                struct lnet_handle_md *mdh, int bytes,
4098                void *user_data, lnet_handler_t handler, bool recovery)
4099 {
4100         struct lnet_md md = { NULL };
4101         struct lnet_processid id;
4102         struct lnet_ping_buffer *pbuf;
4103         int rc;
4104
4105         if (LNET_NID_IS_ANY(dest_nid)) {
4106                 rc = -EHOSTUNREACH;
4107                 goto fail_error;
4108         }
4109
4110         pbuf = lnet_ping_buffer_alloc(bytes, GFP_NOFS);
4111         if (!pbuf) {
4112                 rc = ENOMEM;
4113                 goto fail_error;
4114         }
4115
4116         /* initialize md content */
4117         md.start     = &pbuf->pb_info;
4118         md.length    = bytes;
4119         md.threshold = 2; /* GET/REPLY */
4120         md.max_size  = 0;
4121         md.options   = LNET_MD_TRUNCATE | LNET_MD_TRACK_RESPONSE;
4122         md.user_ptr  = user_data;
4123         md.handler   = handler;
4124
4125         rc = LNetMDBind(&md, LNET_UNLINK, mdh);
4126         if (rc) {
4127                 lnet_ping_buffer_decref(pbuf);
4128                 CERROR("Can't bind MD: %d\n", rc);
4129                 rc = -rc; /* change the rc to positive */
4130                 goto fail_error;
4131         }
4132         id.pid = LNET_PID_LUSTRE;
4133         id.nid = *dest_nid;
4134
4135         rc = LNetGet(NULL, *mdh, &id,
4136                      LNET_RESERVED_PORTAL,
4137                      LNET_PROTO_PING_MATCHBITS, 0, recovery);
4138
4139         if (rc)
4140                 goto fail_unlink_md;
4141
4142         return 0;
4143
4144 fail_unlink_md:
4145         LNetMDUnlink(*mdh);
4146         LNetInvalidateMDHandle(mdh);
4147 fail_error:
4148         return rc;
4149 }
4150
4151 static void
4152 lnet_handle_recovery_reply(struct lnet_mt_event_info *ev_info,
4153                            int status, bool send, bool unlink_event)
4154 {
4155         struct lnet_nid *nid = &ev_info->mt_nid;
4156
4157         if (ev_info->mt_type == MT_TYPE_LOCAL_NI) {
4158                 struct lnet_ni *ni;
4159
4160                 lnet_net_lock(0);
4161                 ni = lnet_nid_to_ni_locked(nid, 0);
4162                 if (!ni) {
4163                         lnet_net_unlock(0);
4164                         return;
4165                 }
4166                 lnet_ni_lock(ni);
4167                 if (!send || (send && status != 0))
4168                         ni->ni_recovery_state &= ~LNET_NI_RECOVERY_PENDING;
4169                 if (status)
4170                         ni->ni_recovery_state |= LNET_NI_RECOVERY_FAILED;
4171                 lnet_ni_unlock(ni);
4172                 lnet_net_unlock(0);
4173
4174                 if (status != 0) {
4175                         CDEBUG(D_NET, "local NI (%s) recovery failed with %d\n",
4176                                libcfs_nidstr(nid), status);
4177                         return;
4178                 }
4179                 /*
4180                  * need to increment healthv for the ni here, because in
4181                  * the lnet_finalize() path we don't have access to this
4182                  * NI. And in order to get access to it, we'll need to
4183                  * carry forward too much information.
4184                  * In the peer case, it'll naturally be incremented
4185                  */
4186                 if (!unlink_event)
4187                         lnet_inc_healthv(&ni->ni_healthv,
4188                                          lnet_health_sensitivity);
4189         } else {
4190                 struct lnet_peer_ni *lpni;
4191                 int cpt;
4192
4193                 cpt = lnet_net_lock_current();
4194                 lpni = lnet_peer_ni_find_locked(nid);
4195                 if (!lpni) {
4196                         lnet_net_unlock(cpt);
4197                         return;
4198                 }
4199                 spin_lock(&lpni->lpni_lock);
4200                 if (!send || (send && status != 0))
4201                         lpni->lpni_state &= ~LNET_PEER_NI_RECOVERY_PENDING;
4202                 if (status)
4203                         lpni->lpni_state |= LNET_PEER_NI_RECOVERY_FAILED;
4204                 spin_unlock(&lpni->lpni_lock);
4205                 lnet_peer_ni_decref_locked(lpni);
4206                 lnet_net_unlock(cpt);
4207
4208                 if (status != 0)
4209                         CDEBUG(D_NET, "peer NI (%s) recovery failed with %d\n",
4210                                libcfs_nidstr(nid), status);
4211         }
4212 }
4213
4214 void
4215 lnet_mt_event_handler(struct lnet_event *event)
4216 {
4217         struct lnet_mt_event_info *ev_info = event->md_user_ptr;
4218         struct lnet_ping_buffer *pbuf;
4219
4220         /* TODO: remove assert */
4221         LASSERT(event->type == LNET_EVENT_REPLY ||
4222                 event->type == LNET_EVENT_SEND ||
4223                 event->type == LNET_EVENT_UNLINK);
4224
4225         CDEBUG(D_NET, "Received event: %d status: %d\n", event->type,
4226                event->status);
4227
4228         switch (event->type) {
4229         case LNET_EVENT_UNLINK:
4230                 CDEBUG(D_NET, "%s recovery ping unlinked\n",
4231                        libcfs_nidstr(&ev_info->mt_nid));
4232                 fallthrough;
4233         case LNET_EVENT_REPLY:
4234                 lnet_handle_recovery_reply(ev_info, event->status, false,
4235                                            event->type == LNET_EVENT_UNLINK);
4236                 break;
4237         case LNET_EVENT_SEND:
4238                 CDEBUG(D_NET, "%s recovery message sent %s:%d\n",
4239                                libcfs_nidstr(&ev_info->mt_nid),
4240                                (event->status) ? "unsuccessfully" :
4241                                "successfully", event->status);
4242                 lnet_handle_recovery_reply(ev_info, event->status, true, false);
4243                 break;
4244         default:
4245                 CERROR("Unexpected event: %d\n", event->type);
4246                 break;
4247         }
4248         if (event->unlinked) {
4249                 LIBCFS_FREE(ev_info, sizeof(*ev_info));
4250                 pbuf = LNET_PING_INFO_TO_BUFFER(event->md_start);
4251                 lnet_ping_buffer_decref(pbuf);
4252         }
4253 }
4254
4255 static int
4256 lnet_rsp_tracker_create(void)
4257 {
4258         struct list_head **rstqs;
4259         rstqs = lnet_create_array_of_queues();
4260
4261         if (!rstqs)
4262                 return -ENOMEM;
4263
4264         the_lnet.ln_mt_rstq = rstqs;
4265
4266         return 0;
4267 }
4268
4269 static void
4270 lnet_rsp_tracker_clean(void)
4271 {
4272         lnet_finalize_expired_responses();
4273
4274         cfs_percpt_free(the_lnet.ln_mt_rstq);
4275         the_lnet.ln_mt_rstq = NULL;
4276 }
4277
4278 int lnet_monitor_thr_start(void)
4279 {
4280         int rc = 0;
4281         struct task_struct *task;
4282
4283         if (the_lnet.ln_mt_state != LNET_MT_STATE_SHUTDOWN)
4284                 return -EALREADY;
4285
4286         rc = lnet_resendqs_create();
4287         if (rc)
4288                 return rc;
4289
4290         rc = lnet_rsp_tracker_create();
4291         if (rc)
4292                 goto clean_queues;
4293
4294         sema_init(&the_lnet.ln_mt_signal, 0);
4295
4296         lnet_net_lock(LNET_LOCK_EX);
4297         the_lnet.ln_mt_state = LNET_MT_STATE_RUNNING;
4298         lnet_net_unlock(LNET_LOCK_EX);
4299         task = kthread_run(lnet_monitor_thread, NULL, "monitor_thread");
4300         if (IS_ERR(task)) {
4301                 rc = PTR_ERR(task);
4302                 CERROR("Can't start monitor thread: %d\n", rc);
4303                 goto clean_thread;
4304         }
4305
4306         return 0;
4307
4308 clean_thread:
4309         lnet_net_lock(LNET_LOCK_EX);
4310         the_lnet.ln_mt_state = LNET_MT_STATE_STOPPING;
4311         lnet_net_unlock(LNET_LOCK_EX);
4312         /* block until event callback signals exit */
4313         down(&the_lnet.ln_mt_signal);
4314         /* clean up */
4315         lnet_net_lock(LNET_LOCK_EX);
4316         the_lnet.ln_mt_state = LNET_MT_STATE_SHUTDOWN;
4317         lnet_net_unlock(LNET_LOCK_EX);
4318         lnet_rsp_tracker_clean();
4319         lnet_clean_local_ni_recoveryq();
4320         lnet_clean_peer_ni_recoveryq();
4321         lnet_clean_resendqs();
4322         the_lnet.ln_mt_handler = NULL;
4323         return rc;
4324 clean_queues:
4325         lnet_rsp_tracker_clean();
4326         lnet_clean_local_ni_recoveryq();
4327         lnet_clean_peer_ni_recoveryq();
4328         lnet_clean_resendqs();
4329         return rc;
4330 }
4331
4332 void lnet_monitor_thr_stop(void)
4333 {
4334         if (the_lnet.ln_mt_state == LNET_MT_STATE_SHUTDOWN)
4335                 return;
4336
4337         LASSERT(the_lnet.ln_mt_state == LNET_MT_STATE_RUNNING);
4338         lnet_net_lock(LNET_LOCK_EX);
4339         the_lnet.ln_mt_state = LNET_MT_STATE_STOPPING;
4340         lnet_net_unlock(LNET_LOCK_EX);
4341
4342         /* tell the monitor thread that we're shutting down */
4343         complete(&the_lnet.ln_mt_wait_complete);
4344
4345         /* block until monitor thread signals that it's done */
4346         mutex_unlock(&the_lnet.ln_api_mutex);
4347         down(&the_lnet.ln_mt_signal);
4348         mutex_lock(&the_lnet.ln_api_mutex);
4349         LASSERT(the_lnet.ln_mt_state == LNET_MT_STATE_SHUTDOWN);
4350
4351         /* perform cleanup tasks */
4352         lnet_rsp_tracker_clean();
4353         lnet_clean_local_ni_recoveryq();
4354         lnet_clean_peer_ni_recoveryq();
4355         lnet_clean_resendqs();
4356 }
4357
4358 void
4359 lnet_drop_message(struct lnet_ni *ni, int cpt, void *private, unsigned int nob,
4360                   __u32 msg_type)
4361 {
4362         lnet_net_lock(cpt);
4363         lnet_incr_stats(&ni->ni_stats, msg_type, LNET_STATS_TYPE_DROP);
4364         the_lnet.ln_counters[cpt]->lct_common.lcc_drop_count++;
4365         the_lnet.ln_counters[cpt]->lct_common.lcc_drop_length += nob;
4366         lnet_net_unlock(cpt);
4367
4368         lnet_ni_recv(ni, private, NULL, 0, 0, 0, nob);
4369 }
4370
4371 static void
4372 lnet_recv_put(struct lnet_ni *ni, struct lnet_msg *msg)
4373 {
4374         struct lnet_hdr *hdr = &msg->msg_hdr;
4375
4376         if (msg->msg_wanted != 0)
4377                 lnet_setpayloadbuffer(msg);
4378
4379         lnet_build_msg_event(msg, LNET_EVENT_PUT);
4380
4381         /* Must I ACK?  If so I'll grab the ack_wmd out of the header and put
4382          * it back into the ACK during lnet_finalize() */
4383         msg->msg_ack = (!lnet_is_wire_handle_none(&hdr->msg.put.ack_wmd) &&
4384                         (msg->msg_md->md_options & LNET_MD_ACK_DISABLE) == 0);
4385
4386         lnet_ni_recv(ni, msg->msg_private, msg, msg->msg_rx_delayed,
4387                      msg->msg_offset, msg->msg_wanted, hdr->payload_length);
4388 }
4389
4390 static int
4391 lnet_parse_put(struct lnet_ni *ni, struct lnet_msg *msg)
4392 {
4393         struct lnet_hdr         *hdr = &msg->msg_hdr;
4394         struct lnet_match_info  info;
4395         int                     rc;
4396         bool                    ready_delay;
4397
4398         /* Convert put fields to host byte order */
4399         hdr->msg.put.match_bits = le64_to_cpu(hdr->msg.put.match_bits);
4400         hdr->msg.put.ptl_index  = le32_to_cpu(hdr->msg.put.ptl_index);
4401         hdr->msg.put.offset     = le32_to_cpu(hdr->msg.put.offset);
4402
4403         /* Primary peer NID. */
4404         info.mi_id.nid = msg->msg_initiator;
4405         info.mi_id.pid  = hdr->src_pid;
4406         info.mi_opc     = LNET_MD_OP_PUT;
4407         info.mi_portal  = hdr->msg.put.ptl_index;
4408         info.mi_rlength = hdr->payload_length;
4409         info.mi_roffset = hdr->msg.put.offset;
4410         info.mi_mbits   = hdr->msg.put.match_bits;
4411         info.mi_cpt     = lnet_nid2cpt(&msg->msg_initiator, ni);
4412
4413         msg->msg_rx_ready_delay = ni->ni_net->net_lnd->lnd_eager_recv == NULL;
4414         ready_delay = msg->msg_rx_ready_delay;
4415
4416  again:
4417         rc = lnet_ptl_match_md(&info, msg);
4418         switch (rc) {
4419         default:
4420                 LBUG();
4421
4422         case LNET_MATCHMD_OK:
4423                 lnet_recv_put(ni, msg);
4424                 return 0;
4425
4426         case LNET_MATCHMD_NONE:
4427                 if (ready_delay)
4428                         /* no eager_recv or has already called it, should
4429                          * have been attached on delayed list */
4430                         return 0;
4431
4432                 rc = lnet_ni_eager_recv(ni, msg);
4433                 if (rc == 0) {
4434                         ready_delay = true;
4435                         goto again;
4436                 }
4437                 fallthrough;
4438
4439         case LNET_MATCHMD_DROP:
4440                 CNETERR("Dropping PUT from %s portal %d match %llu"
4441                         " offset %d length %d: %d\n",
4442                         libcfs_idstr(&info.mi_id), info.mi_portal,
4443                         info.mi_mbits, info.mi_roffset, info.mi_rlength, rc);
4444
4445                 return -ENOENT; /* -ve: OK but no match */
4446         }
4447 }
4448
4449 static int
4450 lnet_parse_get(struct lnet_ni *ni, struct lnet_msg *msg, int rdma_get)
4451 {
4452         struct lnet_match_info info;
4453         struct lnet_hdr *hdr = &msg->msg_hdr;
4454         struct lnet_processid source_id;
4455         struct lnet_handle_wire reply_wmd;
4456         int rc;
4457
4458         /* Convert get fields to host byte order */
4459         hdr->msg.get.match_bits   = le64_to_cpu(hdr->msg.get.match_bits);
4460         hdr->msg.get.ptl_index    = le32_to_cpu(hdr->msg.get.ptl_index);
4461         hdr->msg.get.sink_length  = le32_to_cpu(hdr->msg.get.sink_length);
4462         hdr->msg.get.src_offset   = le32_to_cpu(hdr->msg.get.src_offset);
4463
4464         source_id.nid = hdr->src_nid;
4465         source_id.pid = hdr->src_pid;
4466         /* Primary peer NID */
4467         info.mi_id.nid  = msg->msg_initiator;
4468         info.mi_id.pid  = hdr->src_pid;
4469         info.mi_opc     = LNET_MD_OP_GET;
4470         info.mi_portal  = hdr->msg.get.ptl_index;
4471         info.mi_rlength = hdr->msg.get.sink_length;
4472         info.mi_roffset = hdr->msg.get.src_offset;
4473         info.mi_mbits   = hdr->msg.get.match_bits;
4474         info.mi_cpt     = lnet_nid2cpt(&msg->msg_initiator, ni);
4475
4476         rc = lnet_ptl_match_md(&info, msg);
4477         if (rc == LNET_MATCHMD_DROP) {
4478                 CNETERR("Dropping GET from %s portal %d match %llu"
4479                         " offset %d length %d\n",
4480                         libcfs_idstr(&info.mi_id), info.mi_portal,
4481                         info.mi_mbits, info.mi_roffset, info.mi_rlength);
4482                 return -ENOENT; /* -ve: OK but no match */
4483         }
4484
4485         LASSERT(rc == LNET_MATCHMD_OK);
4486
4487         lnet_build_msg_event(msg, LNET_EVENT_GET);
4488
4489         reply_wmd = hdr->msg.get.return_wmd;
4490
4491         lnet_prep_send(msg, LNET_MSG_REPLY, &source_id,
4492                        msg->msg_offset, msg->msg_wanted);
4493
4494         msg->msg_hdr.msg.reply.dst_wmd = reply_wmd;
4495
4496         if (rdma_get) {
4497                 /* The LND completes the REPLY from her recv procedure */
4498                 lnet_ni_recv(ni, msg->msg_private, msg, 0,
4499                              msg->msg_offset, msg->msg_len, msg->msg_len);
4500                 return 0;
4501         }
4502
4503         lnet_ni_recv(ni, msg->msg_private, NULL, 0, 0, 0, 0);
4504         msg->msg_receiving = 0;
4505
4506         rc = lnet_send(&ni->ni_nid, msg, &msg->msg_from);
4507         if (rc < 0) {
4508                 /* didn't get as far as lnet_ni_send() */
4509                 CERROR("%s: Unable to send REPLY for GET from %s: %d\n",
4510                        libcfs_nidstr(&ni->ni_nid),
4511                        libcfs_idstr(&info.mi_id), rc);
4512
4513                 lnet_finalize(msg, rc);
4514         }
4515
4516         return 0;
4517 }
4518
4519 static int
4520 lnet_parse_reply(struct lnet_ni *ni, struct lnet_msg *msg)
4521 {
4522         void *private = msg->msg_private;
4523         struct lnet_hdr *hdr = &msg->msg_hdr;
4524         struct lnet_processid src = {};
4525         struct lnet_libmd *md;
4526         unsigned int rlength;
4527         unsigned int mlength;
4528         int cpt;
4529
4530         cpt = lnet_cpt_of_cookie(hdr->msg.reply.dst_wmd.wh_object_cookie);
4531         lnet_res_lock(cpt);
4532
4533         src.nid = hdr->src_nid;
4534         src.pid = hdr->src_pid;
4535
4536         /* NB handles only looked up by creator (no flips) */
4537         md = lnet_wire_handle2md(&hdr->msg.reply.dst_wmd);
4538         if (md == NULL || md->md_threshold == 0 || md->md_me != NULL) {
4539                 CNETERR("%s: Dropping REPLY from %s for %s "
4540                         "MD %#llx.%#llx\n",
4541                         libcfs_nidstr(&ni->ni_nid), libcfs_idstr(&src),
4542                         (md == NULL) ? "invalid" : "inactive",
4543                         hdr->msg.reply.dst_wmd.wh_interface_cookie,
4544                         hdr->msg.reply.dst_wmd.wh_object_cookie);
4545                 if (md != NULL && md->md_me != NULL)
4546                         CERROR("REPLY MD also attached to portal %d\n",
4547                                md->md_me->me_portal);
4548
4549                 lnet_res_unlock(cpt);
4550                 return -ENOENT; /* -ve: OK but no match */
4551         }
4552
4553         LASSERT(md->md_offset == 0);
4554
4555         rlength = hdr->payload_length;
4556         mlength = min(rlength, md->md_length);
4557
4558         if (mlength < rlength &&
4559             (md->md_options & LNET_MD_TRUNCATE) == 0) {
4560                 CNETERR("%s: Dropping REPLY from %s length %d "
4561                         "for MD %#llx would overflow (%d)\n",
4562                         libcfs_nidstr(&ni->ni_nid), libcfs_idstr(&src),
4563                         rlength, hdr->msg.reply.dst_wmd.wh_object_cookie,
4564                         mlength);
4565                 lnet_res_unlock(cpt);
4566                 return -ENOENT; /* -ve: OK but no match */
4567         }
4568
4569         CDEBUG(D_NET, "%s: Reply from %s of length %d/%d into md %#llx\n",
4570                libcfs_nidstr(&ni->ni_nid), libcfs_idstr(&src),
4571                mlength, rlength, hdr->msg.reply.dst_wmd.wh_object_cookie);
4572
4573         lnet_msg_attach_md(msg, md, 0, mlength);
4574
4575         if (mlength != 0)
4576                 lnet_setpayloadbuffer(msg);
4577
4578         lnet_res_unlock(cpt);
4579
4580         lnet_build_msg_event(msg, LNET_EVENT_REPLY);
4581
4582         lnet_ni_recv(ni, private, msg, 0, 0, mlength, rlength);
4583         return 0;
4584 }
4585
4586 static int
4587 lnet_parse_ack(struct lnet_ni *ni, struct lnet_msg *msg)
4588 {
4589         struct lnet_hdr *hdr = &msg->msg_hdr;
4590         struct lnet_processid src = {};
4591         struct lnet_libmd *md;
4592         int cpt;
4593
4594         src.nid = hdr->src_nid;
4595         src.pid = hdr->src_pid;
4596
4597         /* Convert ack fields to host byte order */
4598         hdr->msg.ack.match_bits = le64_to_cpu(hdr->msg.ack.match_bits);
4599         hdr->msg.ack.mlength = le32_to_cpu(hdr->msg.ack.mlength);
4600
4601         cpt = lnet_cpt_of_cookie(hdr->msg.ack.dst_wmd.wh_object_cookie);
4602         lnet_res_lock(cpt);
4603
4604         /* NB handles only looked up by creator (no flips) */
4605         md = lnet_wire_handle2md(&hdr->msg.ack.dst_wmd);
4606         if (md == NULL || md->md_threshold == 0 || md->md_me != NULL) {
4607                 /* Don't moan; this is expected */
4608                 CDEBUG(D_NET,
4609                        "%s: Dropping ACK from %s to %s MD %#llx.%#llx\n",
4610                        libcfs_nidstr(&ni->ni_nid), libcfs_idstr(&src),
4611                        (md == NULL) ? "invalid" : "inactive",
4612                        hdr->msg.ack.dst_wmd.wh_interface_cookie,
4613                        hdr->msg.ack.dst_wmd.wh_object_cookie);
4614                 if (md != NULL && md->md_me != NULL)
4615                         CERROR("Source MD also attached to portal %d\n",
4616                                md->md_me->me_portal);
4617
4618                 lnet_res_unlock(cpt);
4619                 return -ENOENT;                  /* -ve! */
4620         }
4621
4622         CDEBUG(D_NET, "%s: ACK from %s into md %#llx\n",
4623                libcfs_nidstr(&ni->ni_nid), libcfs_idstr(&src),
4624                hdr->msg.ack.dst_wmd.wh_object_cookie);
4625
4626         lnet_msg_attach_md(msg, md, 0, 0);
4627
4628         lnet_res_unlock(cpt);
4629
4630         lnet_build_msg_event(msg, LNET_EVENT_ACK);
4631
4632         lnet_ni_recv(ni, msg->msg_private, msg, 0, 0, 0, msg->msg_len);
4633         return 0;
4634 }
4635
4636 /**
4637  * \retval LNET_CREDIT_OK       If \a msg is forwarded
4638  * \retval LNET_CREDIT_WAIT     If \a msg is blocked because w/o buffer
4639  * \retval -ve                  error code
4640  */
4641 int
4642 lnet_parse_forward_locked(struct lnet_ni *ni, struct lnet_msg *msg)
4643 {
4644         int     rc = 0;
4645
4646         if (!the_lnet.ln_routing)
4647                 return -ECANCELED;
4648
4649         if (msg->msg_rxpeer->lpni_rtrcredits <= 0 ||
4650             lnet_msg2bufpool(msg)->rbp_credits <= 0) {
4651                 if (ni->ni_net->net_lnd->lnd_eager_recv == NULL) {
4652                         msg->msg_rx_ready_delay = 1;
4653                 } else {
4654                         lnet_net_unlock(msg->msg_rx_cpt);
4655                         rc = lnet_ni_eager_recv(ni, msg);
4656                         lnet_net_lock(msg->msg_rx_cpt);
4657                 }
4658         }
4659
4660         if (rc == 0)
4661                 rc = lnet_post_routed_recv_locked(msg, 0);
4662         return rc;
4663 }
4664
4665 int
4666 lnet_parse_local(struct lnet_ni *ni, struct lnet_msg *msg)
4667 {
4668         int     rc;
4669
4670         switch (msg->msg_type) {
4671         case LNET_MSG_ACK:
4672                 rc = lnet_parse_ack(ni, msg);
4673                 break;
4674         case LNET_MSG_PUT:
4675                 rc = lnet_parse_put(ni, msg);
4676                 break;
4677         case LNET_MSG_GET:
4678                 rc = lnet_parse_get(ni, msg, msg->msg_rdma_get);
4679                 break;
4680         case LNET_MSG_REPLY:
4681                 rc = lnet_parse_reply(ni, msg);
4682                 break;
4683         default: /* prevent an unused label if !kernel */
4684                 LASSERT(0);
4685                 return -EPROTO;
4686         }
4687
4688         LASSERT(rc == 0 || rc == -ENOENT);
4689         return rc;
4690 }
4691
4692 char *
4693 lnet_msgtyp2str (int type)
4694 {
4695         switch (type) {
4696         case LNET_MSG_ACK:
4697                 return ("ACK");
4698         case LNET_MSG_PUT:
4699                 return ("PUT");
4700         case LNET_MSG_GET:
4701                 return ("GET");
4702         case LNET_MSG_REPLY:
4703                 return ("REPLY");
4704         case LNET_MSG_HELLO:
4705                 return ("HELLO");
4706         default:
4707                 return ("<UNKNOWN>");
4708         }
4709 }
4710 EXPORT_SYMBOL(lnet_msgtyp2str);
4711
4712 int
4713 lnet_parse(struct lnet_ni *ni, struct lnet_hdr *hdr,
4714            struct lnet_nid *from_nid, void *private, int rdma_req)
4715 {
4716         struct lnet_peer_ni *lpni;
4717         struct lnet_msg *msg;
4718         __u32 payload_length;
4719         lnet_pid_t dest_pid;
4720         struct lnet_nid dest_nid;
4721         struct lnet_nid src_nid;
4722         bool push = false;
4723         int for_me;
4724         __u32 type;
4725         int rc = 0;
4726         int cpt;
4727         time64_t now = ktime_get_seconds();
4728
4729         LASSERT (!in_interrupt ());
4730
4731         type = hdr->type;
4732         src_nid = hdr->src_nid;
4733         dest_nid = hdr->dest_nid;
4734         dest_pid = hdr->dest_pid;
4735         payload_length = hdr->payload_length;
4736
4737         for_me = nid_same(&ni->ni_nid, &dest_nid);
4738         cpt = lnet_nid2cpt(from_nid, ni);
4739
4740         CDEBUG(D_NET, "TRACE: %s(%s) <- %s : %s - %s\n",
4741                 libcfs_nidstr(&dest_nid),
4742                 libcfs_nidstr(&ni->ni_nid),
4743                 libcfs_nidstr(&src_nid),
4744                 lnet_msgtyp2str(type),
4745                 (for_me) ? "for me" : "routed");
4746
4747         switch (type) {
4748         case LNET_MSG_ACK:
4749         case LNET_MSG_GET:
4750                 if (payload_length > 0) {
4751                         CERROR("%s, src %s: bad %s payload %d (0 expected)\n",
4752                                libcfs_nidstr(from_nid),
4753                                libcfs_nidstr(&src_nid),
4754                                lnet_msgtyp2str(type), payload_length);
4755                         return -EPROTO;
4756                 }
4757                 break;
4758
4759         case LNET_MSG_PUT:
4760         case LNET_MSG_REPLY:
4761                 if (payload_length >
4762                     (__u32)(for_me ? LNET_MAX_PAYLOAD : LNET_MTU)) {
4763                         CERROR("%s, src %s: bad %s payload %d "
4764                                "(%d max expected)\n",
4765                                libcfs_nidstr(from_nid),
4766                                libcfs_nidstr(&src_nid),
4767                                lnet_msgtyp2str(type),
4768                                payload_length,
4769                                for_me ? LNET_MAX_PAYLOAD : LNET_MTU);
4770                         return -EPROTO;
4771                 }
4772                 break;
4773
4774         default:
4775                 CERROR("%s, src %s: Bad message type 0x%x\n",
4776                        libcfs_nidstr(from_nid),
4777                        libcfs_nidstr(&src_nid), type);
4778                 return -EPROTO;
4779         }
4780
4781         /* Only update net_last_alive for incoming GETs on the reserved portal
4782          * (i.e. incoming lnet/discovery pings).
4783          * This avoids situations where the router's own traffic results in NI
4784          * status changes
4785          */
4786         if (the_lnet.ln_routing && type == LNET_MSG_GET &&
4787             hdr->msg.get.ptl_index == LNET_RESERVED_PORTAL &&
4788             !lnet_islocalnid(&src_nid) &&
4789             ni->ni_net->net_last_alive != now) {
4790                 lnet_ni_lock(ni);
4791                 spin_lock(&ni->ni_net->net_lock);
4792                 ni->ni_net->net_last_alive = now;
4793                 spin_unlock(&ni->ni_net->net_lock);
4794                 push = lnet_ni_set_status_locked(ni, LNET_NI_STATUS_UP);
4795                 lnet_ni_unlock(ni);
4796         }
4797
4798         if (push)
4799                 lnet_push_update_to_peers(1);
4800
4801         /* Regard a bad destination NID as a protocol error.  Senders should
4802          * know what they're doing; if they don't they're misconfigured, buggy
4803          * or malicious so we chop them off at the knees :) */
4804
4805         if (!for_me) {
4806                 if (LNET_NID_NET(&dest_nid) == LNET_NID_NET(&ni->ni_nid)) {
4807                         /* should have gone direct */
4808                         CERROR("%s, src %s: Bad dest nid %s "
4809                                "(should have been sent direct)\n",
4810                                 libcfs_nidstr(from_nid),
4811                                 libcfs_nidstr(&src_nid),
4812                                 libcfs_nidstr(&dest_nid));
4813                         return -EPROTO;
4814                 }
4815
4816                 if (lnet_islocalnid(&dest_nid)) {
4817                         /* dest is another local NI; sender should have used
4818                          * this node's NID on its own network */
4819                         CERROR("%s, src %s: Bad dest nid %s "
4820                                "(it's my nid but on a different network)\n",
4821                                 libcfs_nidstr(from_nid),
4822                                 libcfs_nidstr(&src_nid),
4823                                 libcfs_nidstr(&dest_nid));
4824                         return -EPROTO;
4825                 }
4826
4827                 if (rdma_req && type == LNET_MSG_GET) {
4828                         CERROR("%s, src %s: Bad optimized GET for %s "
4829                                "(final destination must be me)\n",
4830                                 libcfs_nidstr(from_nid),
4831                                 libcfs_nidstr(&src_nid),
4832                                 libcfs_nidstr(&dest_nid));
4833                         return -EPROTO;
4834                 }
4835
4836                 if (!the_lnet.ln_routing) {
4837                         CERROR("%s, src %s: Dropping message for %s "
4838                                "(routing not enabled)\n",
4839                                 libcfs_nidstr(from_nid),
4840                                 libcfs_nidstr(&src_nid),
4841                                 libcfs_nidstr(&dest_nid));
4842                         goto drop;
4843                 }
4844         }
4845
4846         /* Message looks OK; we're not going to return an error, so we MUST
4847          * call back lnd_recv() come what may... */
4848
4849         if (!list_empty(&the_lnet.ln_test_peers) &&     /* normally we don't */
4850             fail_peer(&src_nid, 0)) {                   /* shall we now? */
4851                 CERROR("%s, src %s: Dropping %s to simulate failure\n",
4852                        libcfs_nidstr(from_nid), libcfs_nidstr(&src_nid),
4853                        lnet_msgtyp2str(type));
4854                 goto drop;
4855         }
4856
4857         if (!list_empty(&the_lnet.ln_drop_rules) &&
4858             lnet_drop_rule_match(hdr, &ni->ni_nid, NULL)) {
4859                 CDEBUG(D_NET,
4860                        "%s, src %s, dst %s: Dropping %s to simulate silent message loss\n",
4861                        libcfs_nidstr(from_nid), libcfs_nidstr(&src_nid),
4862                        libcfs_nidstr(&dest_nid), lnet_msgtyp2str(type));
4863                 goto drop;
4864         }
4865
4866         msg = lnet_msg_alloc();
4867         if (msg == NULL) {
4868                 CERROR("%s, src %s: Dropping %s (out of memory)\n",
4869                        libcfs_nidstr(from_nid), libcfs_nidstr(&src_nid),
4870                        lnet_msgtyp2str(type));
4871                 goto drop;
4872         }
4873
4874         /* msg zeroed in lnet_msg_alloc; i.e. flags all clear,
4875          * pointers NULL etc */
4876
4877         msg->msg_type = type;
4878         msg->msg_private = private;
4879         msg->msg_receiving = 1;
4880         msg->msg_rdma_get = rdma_req;
4881         msg->msg_len = msg->msg_wanted = payload_length;
4882         msg->msg_offset = 0;
4883         msg->msg_hdr = *hdr;
4884         /* for building message event */
4885         msg->msg_from = *from_nid;
4886         if (!for_me) {
4887                 msg->msg_target.pid = dest_pid;
4888                 msg->msg_target.nid = dest_nid;
4889                 msg->msg_routing = 1;
4890         }
4891
4892         lnet_net_lock(cpt);
4893         lpni = lnet_peerni_by_nid_locked(from_nid, &ni->ni_nid, cpt);
4894         if (IS_ERR(lpni)) {
4895                 lnet_net_unlock(cpt);
4896                 rc = PTR_ERR(lpni);
4897                 CERROR("%s, src %s: Dropping %s (error %d looking up sender)\n",
4898                        libcfs_nidstr(from_nid), libcfs_nidstr(&src_nid),
4899                        lnet_msgtyp2str(type), rc);
4900                 lnet_msg_free(msg);
4901                 if (rc == -ESHUTDOWN)
4902                         /* We are shutting down.  Don't do anything more */
4903                         return rc;
4904                 goto drop;
4905         }
4906
4907         /* If this message was forwarded to us from a router then we may need
4908          * to update router aliveness or check for an asymmetrical route
4909          * (or both)
4910          */
4911         if (((lnet_drop_asym_route && for_me) ||
4912              !lpni->lpni_peer_net->lpn_peer->lp_alive) &&
4913             LNET_NID_NET(&src_nid) != LNET_NID_NET(from_nid)) {
4914                 __u32 src_net_id = LNET_NID_NET(&src_nid);
4915                 struct lnet_peer *gw = lpni->lpni_peer_net->lpn_peer;
4916                 struct lnet_route *route;
4917                 bool found = false;
4918
4919                 list_for_each_entry(route, &gw->lp_routes, lr_gwlist) {
4920                         if (route->lr_net == src_net_id) {
4921                                 found = true;
4922                                 /* If we're transitioning the gateway from
4923                                  * dead -> alive, and discovery is disabled
4924                                  * locally or on the gateway, then we need to
4925                                  * update the cached route aliveness for each
4926                                  * route to the src_nid's net.
4927                                  *
4928                                  * Otherwise, we're only checking for
4929                                  * symmetrical route, and we can break the
4930                                  * loop
4931                                  */
4932                                 if (!gw->lp_alive &&
4933                                     lnet_is_discovery_disabled(gw))
4934                                         lnet_set_route_aliveness(route, true);
4935                                 else
4936                                         break;
4937                         }
4938                 }
4939                 if (lnet_drop_asym_route && for_me && !found) {
4940                         /* Drop ref taken by lnet_nid2peerni_locked() */
4941                         lnet_peer_ni_decref_locked(lpni);
4942                         lnet_net_unlock(cpt);
4943                         /* we would not use from_nid to route a message to
4944                          * src_nid
4945                          * => asymmetric routing detected but forbidden
4946                          */
4947                         CERROR("%s, src %s: Dropping asymmetrical route %s\n",
4948                                libcfs_nidstr(from_nid),
4949                                libcfs_nidstr(&src_nid), lnet_msgtyp2str(type));
4950                         lnet_msg_free(msg);
4951                         goto drop;
4952                 }
4953                 if (!gw->lp_alive) {
4954                         struct lnet_peer_net *lpn;
4955                         struct lnet_peer_ni *lpni2;
4956
4957                         gw->lp_alive = true;
4958                         /* Mark all remote NIs on src_nid's net UP */
4959                         lpn = lnet_peer_get_net_locked(gw, src_net_id);
4960                         if (lpn)
4961                                 list_for_each_entry(lpni2, &lpn->lpn_peer_nis,
4962                                                     lpni_peer_nis)
4963                                         lpni2->lpni_ns_status = LNET_NI_STATUS_UP;
4964                 }
4965         }
4966
4967         lpni->lpni_last_alive = now;
4968
4969         msg->msg_rxpeer = lpni;
4970         msg->msg_rxni = ni;
4971         lnet_ni_addref_locked(ni, cpt);
4972         /* Multi-Rail: Primary NID of source. */
4973         lnet_peer_primary_nid_locked(&src_nid, &msg->msg_initiator);
4974
4975         /*
4976          * mark the status of this lpni as UP since we received a message
4977          * from it. The ping response reports back the ns_status which is
4978          * marked on the remote as up or down and we cache it here.
4979          */
4980         msg->msg_rxpeer->lpni_ns_status = LNET_NI_STATUS_UP;
4981
4982         lnet_msg_commit(msg, cpt);
4983
4984         /* message delay simulation */
4985         if (unlikely(!list_empty(&the_lnet.ln_delay_rules) &&
4986                      lnet_delay_rule_match_locked(hdr, msg))) {
4987                 lnet_net_unlock(cpt);
4988                 return 0;
4989         }
4990
4991         if (!for_me) {
4992                 rc = lnet_parse_forward_locked(ni, msg);
4993                 lnet_net_unlock(cpt);
4994
4995                 if (rc < 0)
4996                         goto free_drop;
4997
4998                 if (rc == LNET_CREDIT_OK) {
4999                         lnet_ni_recv(ni, msg->msg_private, msg, 0,
5000                                      0, payload_length, payload_length);
5001                 }
5002                 return 0;
5003         }
5004
5005         lnet_net_unlock(cpt);
5006
5007         rc = lnet_parse_local(ni, msg);
5008         if (rc != 0)
5009                 goto free_drop;
5010         return 0;
5011
5012  free_drop:
5013         LASSERT(msg->msg_md == NULL);
5014         lnet_finalize(msg, rc);
5015
5016  drop:
5017         lnet_drop_message(ni, cpt, private, payload_length, type);
5018         return 0;
5019 }
5020 EXPORT_SYMBOL(lnet_parse);
5021
5022 void
5023 lnet_drop_delayed_msg_list(struct list_head *head, char *reason)
5024 {
5025         struct lnet_msg *msg;
5026
5027         while ((msg = list_first_entry_or_null(head, struct lnet_msg,
5028                                                msg_list)) != NULL) {
5029                 struct lnet_processid id = {};
5030
5031                 list_del(&msg->msg_list);
5032
5033                 id.nid = msg->msg_hdr.src_nid;
5034                 id.pid = msg->msg_hdr.src_pid;
5035
5036                 LASSERT(msg->msg_md == NULL);
5037                 LASSERT(msg->msg_rx_delayed);
5038                 LASSERT(msg->msg_rxpeer != NULL);
5039                 LASSERT(msg->msg_hdr.type == LNET_MSG_PUT);
5040
5041                 CWARN("Dropping delayed PUT from %s portal %d match %llu"
5042                       " offset %d length %d: %s\n",
5043                       libcfs_idstr(&id),
5044                       msg->msg_hdr.msg.put.ptl_index,
5045                       msg->msg_hdr.msg.put.match_bits,
5046                       msg->msg_hdr.msg.put.offset,
5047                       msg->msg_hdr.payload_length, reason);
5048
5049                 /* NB I can't drop msg's ref on msg_rxpeer until after I've
5050                  * called lnet_drop_message(), so I just hang onto msg as well
5051                  * until that's done */
5052
5053                 lnet_drop_message(msg->msg_rxni, msg->msg_rx_cpt,
5054                                   msg->msg_private, msg->msg_len,
5055                                   msg->msg_type);
5056
5057                 msg->msg_no_resend = true;
5058                 /*
5059                  * NB: message will not generate event because w/o attached MD,
5060                  * but we still should give error code so lnet_msg_decommit()
5061                  * can skip counters operations and other checks.
5062                  */
5063                 lnet_finalize(msg, -ENOENT);
5064         }
5065 }
5066
5067 void
5068 lnet_recv_delayed_msg_list(struct list_head *head)
5069 {
5070         struct lnet_msg *msg;
5071
5072         while ((msg = list_first_entry_or_null(head, struct lnet_msg,
5073                                                msg_list)) != NULL) {
5074                 struct lnet_processid id;
5075
5076                 list_del(&msg->msg_list);
5077
5078                 /* md won't disappear under me, since each msg
5079                  * holds a ref on it */
5080
5081                 id.nid = msg->msg_hdr.src_nid;
5082                 id.pid = msg->msg_hdr.src_pid;
5083
5084                 LASSERT(msg->msg_rx_delayed);
5085                 LASSERT(msg->msg_md != NULL);
5086                 LASSERT(msg->msg_rxpeer != NULL);
5087                 LASSERT(msg->msg_rxni != NULL);
5088                 LASSERT(msg->msg_hdr.type == LNET_MSG_PUT);
5089
5090                 CDEBUG(D_NET, "Resuming delayed PUT from %s portal %d "
5091                        "match %llu offset %d length %d.\n",
5092                         libcfs_idstr(&id), msg->msg_hdr.msg.put.ptl_index,
5093                         msg->msg_hdr.msg.put.match_bits,
5094                         msg->msg_hdr.msg.put.offset,
5095                         msg->msg_hdr.payload_length);
5096
5097                 lnet_recv_put(msg->msg_rxni, msg);
5098         }
5099 }
5100
5101 static void
5102 lnet_attach_rsp_tracker(struct lnet_rsp_tracker *rspt, int cpt,
5103                         struct lnet_libmd *md, struct lnet_handle_md mdh)
5104 {
5105         s64 timeout_ns;
5106         struct lnet_rsp_tracker *local_rspt;
5107
5108         /*
5109          * MD has a refcount taken by message so it's not going away.
5110          * The MD however can be looked up. We need to secure the access
5111          * to the md_rspt_ptr by taking the res_lock.
5112          * The rspt can be accessed without protection up to when it gets
5113          * added to the list.
5114          */
5115
5116         lnet_res_lock(cpt);
5117         local_rspt = md->md_rspt_ptr;
5118         timeout_ns = lnet_transaction_timeout * NSEC_PER_SEC;
5119         if (local_rspt != NULL) {
5120                 /*
5121                  * we already have an rspt attached to the md, so we'll
5122                  * update the deadline on that one.
5123                  */
5124                 lnet_rspt_free(rspt, cpt);
5125         } else {
5126                 /* new md */
5127                 rspt->rspt_mdh = mdh;
5128                 rspt->rspt_cpt = cpt;
5129                 /* store the rspt so we can access it when we get the REPLY */
5130                 md->md_rspt_ptr = rspt;
5131                 local_rspt = rspt;
5132         }
5133         local_rspt->rspt_deadline = ktime_add_ns(ktime_get(), timeout_ns);
5134
5135         /*
5136          * add to the list of tracked responses. It's added to tail of the
5137          * list in order to expire all the older entries first.
5138          */
5139         lnet_net_lock(cpt);
5140         list_move_tail(&local_rspt->rspt_on_list, the_lnet.ln_mt_rstq[cpt]);
5141         lnet_net_unlock(cpt);
5142         lnet_res_unlock(cpt);
5143 }
5144
5145 /**
5146  * Initiate an asynchronous PUT operation.
5147  *
5148  * There are several events associated with a PUT: completion of the send on
5149  * the initiator node (LNET_EVENT_SEND), and when the send completes
5150  * successfully, the receipt of an acknowledgment (LNET_EVENT_ACK) indicating
5151  * that the operation was accepted by the target. The event LNET_EVENT_PUT is
5152  * used at the target node to indicate the completion of incoming data
5153  * delivery.
5154  *
5155  * The local events will be logged in the EQ associated with the MD pointed to
5156  * by \a mdh handle. Using a MD without an associated EQ results in these
5157  * events being discarded. In this case, the caller must have another
5158  * mechanism (e.g., a higher level protocol) for determining when it is safe
5159  * to modify the memory region associated with the MD.
5160  *
5161  * Note that LNet does not guarantee the order of LNET_EVENT_SEND and
5162  * LNET_EVENT_ACK, though intuitively ACK should happen after SEND.
5163  *
5164  * \param self Indicates the NID of a local interface through which to send
5165  * the PUT request. Use LNET_NID_ANY to let LNet choose one by itself.
5166  * \param mdh A handle for the MD that describes the memory to be sent. The MD
5167  * must be "free floating" (See LNetMDBind()).
5168  * \param ack Controls whether an acknowledgment is requested.
5169  * Acknowledgments are only sent when they are requested by the initiating
5170  * process and the target MD enables them.
5171  * \param target A process identifier for the target process.
5172  * \param portal The index in the \a target's portal table.
5173  * \param match_bits The match bits to use for MD selection at the target
5174  * process.
5175  * \param offset The offset into the target MD (only used when the target
5176  * MD has the LNET_MD_MANAGE_REMOTE option set).
5177  * \param hdr_data 64 bits of user data that can be included in the message
5178  * header. This data is written to an event queue entry at the target if an
5179  * EQ is present on the matching MD.
5180  *
5181  * \retval  0      Success, and only in this case events will be generated
5182  * and logged to EQ (if it exists).
5183  * \retval -EIO    Simulated failure.
5184  * \retval -ENOMEM Memory allocation failure.
5185  * \retval -ENOENT Invalid MD object.
5186  *
5187  * \see struct lnet_event::hdr_data and lnet_event_kind_t.
5188  */
5189 int
5190 LNetPut(struct lnet_nid *self, struct lnet_handle_md mdh, enum lnet_ack_req ack,
5191         struct lnet_processid *target, unsigned int portal,
5192         __u64 match_bits, unsigned int offset,
5193         __u64 hdr_data)
5194 {
5195         struct lnet_msg *msg;
5196         struct lnet_libmd *md;
5197         int cpt;
5198         int rc;
5199         struct lnet_rsp_tracker *rspt = NULL;
5200
5201         LASSERT(the_lnet.ln_refcount > 0);
5202
5203         if (!list_empty(&the_lnet.ln_test_peers) &&     /* normally we don't */
5204             fail_peer(&target->nid, 1)) {               /* shall we now? */
5205                 CERROR("Dropping PUT to %s: simulated failure\n",
5206                        libcfs_idstr(target));
5207                 return -EIO;
5208         }
5209
5210         msg = lnet_msg_alloc();
5211         if (msg == NULL) {
5212                 CERROR("Dropping PUT to %s: ENOMEM on struct lnet_msg\n",
5213                        libcfs_idstr(target));
5214                 return -ENOMEM;
5215         }
5216         msg->msg_vmflush = !!(current->flags & PF_MEMALLOC);
5217
5218         cpt = lnet_cpt_of_cookie(mdh.cookie);
5219
5220         if (ack == LNET_ACK_REQ) {
5221                 rspt = lnet_rspt_alloc(cpt);
5222                 if (!rspt) {
5223                         CERROR("Dropping PUT to %s: ENOMEM on response tracker\n",
5224                                 libcfs_idstr(target));
5225                         lnet_msg_free(msg);
5226                         return -ENOMEM;
5227                 }
5228                 INIT_LIST_HEAD(&rspt->rspt_on_list);
5229         }
5230
5231         lnet_res_lock(cpt);
5232
5233         md = lnet_handle2md(&mdh);
5234         if (md == NULL || md->md_threshold == 0 || md->md_me != NULL) {
5235                 CERROR("Dropping PUT (%llu:%d:%s): MD (%d) invalid\n",
5236                        match_bits, portal, libcfs_idstr(target),
5237                        md == NULL ? -1 : md->md_threshold);
5238                 if (md != NULL && md->md_me != NULL)
5239                         CERROR("Source MD also attached to portal %d\n",
5240                                md->md_me->me_portal);
5241                 lnet_res_unlock(cpt);
5242
5243                 if (rspt)
5244                         lnet_rspt_free(rspt, cpt);
5245
5246                 lnet_msg_free(msg);
5247                 return -ENOENT;
5248         }
5249
5250         CDEBUG(D_NET, "%s -> %s\n", __func__, libcfs_idstr(target));
5251
5252         lnet_msg_attach_md(msg, md, 0, 0);
5253
5254         lnet_prep_send(msg, LNET_MSG_PUT, target, 0, md->md_length);
5255
5256         msg->msg_hdr.msg.put.match_bits = cpu_to_le64(match_bits);
5257         msg->msg_hdr.msg.put.ptl_index = cpu_to_le32(portal);
5258         msg->msg_hdr.msg.put.offset = cpu_to_le32(offset);
5259         msg->msg_hdr.msg.put.hdr_data = hdr_data;
5260
5261         /* NB handles only looked up by creator (no flips) */
5262         if (ack == LNET_ACK_REQ) {
5263                 msg->msg_hdr.msg.put.ack_wmd.wh_interface_cookie =
5264                         the_lnet.ln_interface_cookie;
5265                 msg->msg_hdr.msg.put.ack_wmd.wh_object_cookie =
5266                         md->md_lh.lh_cookie;
5267         } else {
5268                 msg->msg_hdr.msg.put.ack_wmd.wh_interface_cookie =
5269                         LNET_WIRE_HANDLE_COOKIE_NONE;
5270                 msg->msg_hdr.msg.put.ack_wmd.wh_object_cookie =
5271                         LNET_WIRE_HANDLE_COOKIE_NONE;
5272         }
5273
5274         lnet_res_unlock(cpt);
5275
5276         lnet_build_msg_event(msg, LNET_EVENT_SEND);
5277
5278         if (rspt && lnet_response_tracking_enabled(LNET_MSG_PUT,
5279                                                    md->md_options))
5280                 lnet_attach_rsp_tracker(rspt, cpt, md, mdh);
5281         else if (rspt)
5282                 lnet_rspt_free(rspt, cpt);
5283
5284         if (CFS_FAIL_CHECK_ORSET(CFS_FAIL_PTLRPC_OST_BULK_CB2,
5285                                  CFS_FAIL_ONCE))
5286                 rc = -EIO;
5287         else
5288                 rc = lnet_send(self, msg, NULL);
5289
5290         if (rc != 0) {
5291                 CNETERR("Error sending PUT to %s: %d\n",
5292                         libcfs_idstr(target), rc);
5293                 msg->msg_no_resend = true;
5294                 lnet_finalize(msg, rc);
5295         }
5296
5297         /* completion will be signalled by an event */
5298         return 0;
5299 }
5300 EXPORT_SYMBOL(LNetPut);
5301
5302 /*
5303  * The LND can DMA direct to the GET md (i.e. no REPLY msg).  This
5304  * returns a msg for the LND to pass to lnet_finalize() when the sink
5305  * data has been received.
5306  *
5307  * CAVEAT EMPTOR: 'getmsg' is the original GET, which is freed when
5308  * lnet_finalize() is called on it, so the LND must call this first
5309  */
5310 struct lnet_msg *
5311 lnet_create_reply_msg(struct lnet_ni *ni, struct lnet_msg *getmsg)
5312 {
5313         struct lnet_msg *msg = lnet_msg_alloc();
5314         struct lnet_libmd *getmd = getmsg->msg_md;
5315         struct lnet_processid *peer_id = &getmsg->msg_target;
5316         int cpt;
5317
5318         LASSERT(!getmsg->msg_target_is_router);
5319         LASSERT(!getmsg->msg_routing);
5320
5321         if (msg == NULL) {
5322                 CERROR("%s: Dropping REPLY from %s: can't allocate msg\n",
5323                        libcfs_nidstr(&ni->ni_nid), libcfs_idstr(peer_id));
5324                 goto drop;
5325         }
5326
5327         cpt = lnet_cpt_of_cookie(getmd->md_lh.lh_cookie);
5328         lnet_res_lock(cpt);
5329
5330         LASSERT(getmd->md_refcount > 0);
5331
5332         if (getmd->md_threshold == 0) {
5333                 CERROR("%s: Dropping REPLY from %s for inactive MD %p\n",
5334                         libcfs_nidstr(&ni->ni_nid), libcfs_idstr(peer_id),
5335                         getmd);
5336                 lnet_res_unlock(cpt);
5337                 goto drop;
5338         }
5339
5340         LASSERT(getmd->md_offset == 0);
5341
5342         CDEBUG(D_NET, "%s: Reply from %s md %p\n",
5343                libcfs_nidstr(&ni->ni_nid), libcfs_idstr(peer_id), getmd);
5344
5345         /* setup information for lnet_build_msg_event */
5346         msg->msg_initiator =
5347                 getmsg->msg_txpeer->lpni_peer_net->lpn_peer->lp_primary_nid;
5348         msg->msg_from = peer_id->nid;
5349         msg->msg_type = LNET_MSG_GET; /* flag this msg as an "optimized" GET */
5350         msg->msg_hdr.src_nid = peer_id->nid;
5351         msg->msg_hdr.payload_length = getmd->md_length;
5352         msg->msg_receiving = 1; /* required by lnet_msg_attach_md */
5353
5354         lnet_msg_attach_md(msg, getmd, getmd->md_offset, getmd->md_length);
5355         lnet_res_unlock(cpt);
5356
5357         cpt = lnet_nid2cpt(&peer_id->nid, ni);
5358
5359         lnet_net_lock(cpt);
5360         lnet_msg_commit(msg, cpt);
5361         lnet_net_unlock(cpt);
5362
5363         lnet_build_msg_event(msg, LNET_EVENT_REPLY);
5364
5365         return msg;
5366
5367  drop:
5368         cpt = lnet_nid2cpt(&peer_id->nid, ni);
5369
5370         lnet_net_lock(cpt);
5371         lnet_incr_stats(&ni->ni_stats, LNET_MSG_GET, LNET_STATS_TYPE_DROP);
5372         the_lnet.ln_counters[cpt]->lct_common.lcc_drop_count++;
5373         the_lnet.ln_counters[cpt]->lct_common.lcc_drop_length +=
5374                 getmd->md_length;
5375         lnet_net_unlock(cpt);
5376
5377         if (msg != NULL)
5378                 lnet_msg_free(msg);
5379
5380         return NULL;
5381 }
5382 EXPORT_SYMBOL(lnet_create_reply_msg);
5383
5384 void
5385 lnet_set_reply_msg_len(struct lnet_ni *ni, struct lnet_msg *reply,
5386                        unsigned int len)
5387 {
5388         /* Set the REPLY length, now the RDMA that elides the REPLY message has
5389          * completed and I know it. */
5390         LASSERT(reply != NULL);
5391         LASSERT(reply->msg_type == LNET_MSG_GET);
5392         LASSERT(reply->msg_ev.type == LNET_EVENT_REPLY);
5393
5394         /* NB I trusted my peer to RDMA.  If she tells me she's written beyond
5395          * the end of my buffer, I might as well be dead. */
5396         LASSERT(len <= reply->msg_ev.mlength);
5397
5398         reply->msg_ev.mlength = len;
5399 }
5400 EXPORT_SYMBOL(lnet_set_reply_msg_len);
5401
5402 /**
5403  * Initiate an asynchronous GET operation.
5404  *
5405  * On the initiator node, an LNET_EVENT_SEND is logged when the GET request
5406  * is sent, and an LNET_EVENT_REPLY is logged when the data returned from
5407  * the target node in the REPLY has been written to local MD.
5408  *
5409  * On the target node, an LNET_EVENT_GET is logged when the GET request
5410  * arrives and is accepted into a MD.
5411  *
5412  * \param self,target,portal,match_bits,offset See the discussion in LNetPut().
5413  * \param mdh A handle for the MD that describes the memory into which the
5414  * requested data will be received. The MD must be "free floating" (See LNetMDBind()).
5415  *
5416  * \retval  0      Success, and only in this case events will be generated
5417  * and logged to EQ (if it exists) of the MD.
5418  * \retval -EIO    Simulated failure.
5419  * \retval -ENOMEM Memory allocation failure.
5420  * \retval -ENOENT Invalid MD object.
5421  */
5422 int
5423 LNetGet(struct lnet_nid *self, struct lnet_handle_md mdh,
5424         struct lnet_processid *target, unsigned int portal,
5425         __u64 match_bits, unsigned int offset, bool recovery)
5426 {
5427         struct lnet_msg *msg;
5428         struct lnet_libmd *md;
5429         struct lnet_rsp_tracker *rspt;
5430         int cpt;
5431         int rc;
5432
5433         LASSERT(the_lnet.ln_refcount > 0);
5434
5435         if (!list_empty(&the_lnet.ln_test_peers) &&     /* normally we don't */
5436             fail_peer(&target->nid, 1))         /* shall we now? */
5437         {
5438                 CERROR("Dropping GET to %s: simulated failure\n",
5439                        libcfs_idstr(target));
5440                 return -EIO;
5441         }
5442
5443         msg = lnet_msg_alloc();
5444         if (!msg) {
5445                 CERROR("Dropping GET to %s: ENOMEM on struct lnet_msg\n",
5446                        libcfs_idstr(target));
5447                 return -ENOMEM;
5448         }
5449
5450         cpt = lnet_cpt_of_cookie(mdh.cookie);
5451
5452         rspt = lnet_rspt_alloc(cpt);
5453         if (!rspt) {
5454                 CERROR("Dropping GET to %s: ENOMEM on response tracker\n",
5455                        libcfs_idstr(target));
5456                 lnet_msg_free(msg);
5457                 return -ENOMEM;
5458         }
5459         INIT_LIST_HEAD(&rspt->rspt_on_list);
5460
5461         msg->msg_recovery = recovery;
5462
5463         lnet_res_lock(cpt);
5464
5465         md = lnet_handle2md(&mdh);
5466         if (md == NULL || md->md_threshold == 0 || md->md_me != NULL) {
5467                 CERROR("Dropping GET (%llu:%d:%s): MD (%d) invalid\n",
5468                        match_bits, portal, libcfs_idstr(target),
5469                        md == NULL ? -1 : md->md_threshold);
5470                 if (md != NULL && md->md_me != NULL)
5471                         CERROR("REPLY MD also attached to portal %d\n",
5472                                md->md_me->me_portal);
5473
5474                 lnet_res_unlock(cpt);
5475
5476                 lnet_msg_free(msg);
5477                 lnet_rspt_free(rspt, cpt);
5478                 return -ENOENT;
5479         }
5480
5481         CDEBUG(D_NET, "%s -> %s\n", __func__, libcfs_idstr(target));
5482
5483         lnet_msg_attach_md(msg, md, 0, 0);
5484
5485         lnet_prep_send(msg, LNET_MSG_GET, target, 0, 0);
5486
5487         msg->msg_hdr.msg.get.match_bits = cpu_to_le64(match_bits);
5488         msg->msg_hdr.msg.get.ptl_index = cpu_to_le32(portal);
5489         msg->msg_hdr.msg.get.src_offset = cpu_to_le32(offset);
5490         msg->msg_hdr.msg.get.sink_length = cpu_to_le32(md->md_length);
5491
5492         /* NB handles only looked up by creator (no flips) */
5493         msg->msg_hdr.msg.get.return_wmd.wh_interface_cookie =
5494                 the_lnet.ln_interface_cookie;
5495         msg->msg_hdr.msg.get.return_wmd.wh_object_cookie =
5496                 md->md_lh.lh_cookie;
5497
5498         lnet_res_unlock(cpt);
5499
5500         lnet_build_msg_event(msg, LNET_EVENT_SEND);
5501
5502         if (lnet_response_tracking_enabled(LNET_MSG_GET, md->md_options))
5503                 lnet_attach_rsp_tracker(rspt, cpt, md, mdh);
5504         else
5505                 lnet_rspt_free(rspt, cpt);
5506
5507         rc = lnet_send(self, msg, NULL);
5508         if (rc < 0) {
5509                 CNETERR("Error sending GET to %s: %d\n",
5510                         libcfs_idstr(target), rc);
5511                 msg->msg_no_resend = true;
5512                 lnet_finalize(msg, rc);
5513         }
5514
5515         /* completion will be signalled by an event */
5516         return 0;
5517 }
5518 EXPORT_SYMBOL(LNetGet);
5519
5520 /**
5521  * Calculate distance to node at \a dstnid.
5522  *
5523  * \param dstnid Target NID.
5524  * \param srcnidp If not NULL, NID of the local interface to reach \a dstnid
5525  * is saved here.
5526  * \param orderp If not NULL, order of the route to reach \a dstnid is saved
5527  * here.
5528  *
5529  * \retval 0 If \a dstnid belongs to a local interface, and reserved option
5530  * local_nid_dist_zero is set, which is the default.
5531  * \retval positives Distance to target NID, i.e. number of hops plus one.
5532  * \retval -EHOSTUNREACH If \a dstnid is not reachable.
5533  */
5534 int
5535 LNetDist(struct lnet_nid *dstnid, struct lnet_nid *srcnid, __u32 *orderp)
5536 {
5537         struct lnet_ni *ni = NULL;
5538         struct lnet_remotenet *rnet;
5539         __u32 dstnet = LNET_NID_NET(dstnid);
5540         int hops;
5541         int cpt;
5542         __u32 order = 2;
5543         struct list_head *rn_list;
5544         struct lnet_ni *matched_dstnet = NULL;
5545
5546         /* if !local_nid_dist_zero, I don't return a distance of 0 ever
5547          * (when lustre sees a distance of 0, it substitutes 0@lo), so I
5548          * keep order 0 free for 0@lo and order 1 free for a local NID
5549          * match
5550          * WARNING: dstnid and srcnid might point to same place.
5551          * Don't set *srcnid until late.
5552          */
5553
5554         LASSERT(the_lnet.ln_refcount > 0);
5555
5556         cpt = lnet_net_lock_current();
5557
5558         while ((ni = lnet_get_next_ni_locked(NULL, ni))) {
5559                 if (nid_same(&ni->ni_nid, dstnid)) {
5560                         if (orderp != NULL) {
5561                                 if (nid_is_lo0(dstnid))
5562                                         *orderp = 0;
5563                                 else
5564                                         *orderp = 1;
5565                         }
5566                         if (srcnid)
5567                                 *srcnid = *dstnid;
5568                         lnet_net_unlock(cpt);
5569
5570                         return local_nid_dist_zero ? 0 : 1;
5571                 }
5572
5573                 if (!matched_dstnet && LNET_NID_NET(&ni->ni_nid) == dstnet) {
5574                         matched_dstnet = ni;
5575                         /* We matched the destination net, but we may have
5576                          * additional local NIs to inspect.
5577                          *
5578                          * We record the order as appropriate, but
5579                          * they may be overwritten if we match local NI above.
5580                          */
5581
5582                         if (orderp) {
5583                                 /* Check if ni was originally created in
5584                                  * current net namespace.
5585                                  * If not, assign order above 0xffff0000,
5586                                  * to make this ni not a priority.
5587                                  */
5588                                 if (current->nsproxy &&
5589                                     !net_eq(ni->ni_net_ns,
5590                                             current->nsproxy->net_ns))
5591                                         *orderp = order + 0xffff0000;
5592                                 else
5593                                         *orderp = order;
5594                         }
5595                 }
5596
5597                 order++;
5598         }
5599
5600         if (matched_dstnet) {
5601                 if (srcnid)
5602                         *srcnid = matched_dstnet->ni_nid;
5603                 lnet_net_unlock(cpt);
5604                 return 1;
5605         }
5606
5607         rn_list = lnet_net2rnethash(dstnet);
5608         list_for_each_entry(rnet, rn_list, lrn_list) {
5609                 if (rnet->lrn_net == dstnet) {
5610                         struct lnet_route *route;
5611                         struct lnet_route *shortest = NULL;
5612                         __u32 shortest_hops = LNET_UNDEFINED_HOPS;
5613                         __u32 route_hops;
5614
5615                         LASSERT(!list_empty(&rnet->lrn_routes));
5616
5617                         list_for_each_entry(route, &rnet->lrn_routes,
5618                                             lr_list) {
5619                                 route_hops = route->lr_hops;
5620                                 if (route_hops == LNET_UNDEFINED_HOPS)
5621                                         route_hops = 1;
5622                                 if (shortest == NULL ||
5623                                     route_hops < shortest_hops) {
5624                                         shortest = route;
5625                                         shortest_hops = route_hops;
5626                                 }
5627                         }
5628
5629                         LASSERT(shortest != NULL);
5630                         hops = shortest_hops;
5631                         if (srcnid) {
5632                                 struct lnet_net *net;
5633                                 net = lnet_get_net_locked(shortest->lr_lnet);
5634                                 LASSERT(net);
5635                                 ni = lnet_get_next_ni_locked(net, NULL);
5636                                 *srcnid = ni->ni_nid;
5637                         }
5638                         if (orderp != NULL)
5639                                 *orderp = order;
5640                         lnet_net_unlock(cpt);
5641                         return hops + 1;
5642                 }
5643                 order++;
5644         }
5645
5646         lnet_net_unlock(cpt);
5647         return -EHOSTUNREACH;
5648 }
5649 EXPORT_SYMBOL(LNetDist);