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