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