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