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