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