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