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