Whamcloud - gitweb
LU-9120 lnet: add lnet_health_sensitivity
[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                 lnet_finalize(msg, rc);
769 }
770
771 static int
772 lnet_ni_eager_recv(struct lnet_ni *ni, struct lnet_msg *msg)
773 {
774         int     rc;
775
776         LASSERT(!msg->msg_sending);
777         LASSERT(msg->msg_receiving);
778         LASSERT(!msg->msg_rx_ready_delay);
779         LASSERT(ni->ni_net->net_lnd->lnd_eager_recv != NULL);
780
781         msg->msg_rx_ready_delay = 1;
782         rc = (ni->ni_net->net_lnd->lnd_eager_recv)(ni, msg->msg_private, msg,
783                                                   &msg->msg_private);
784         if (rc != 0) {
785                 CERROR("recv from %s / send to %s aborted: "
786                        "eager_recv failed %d\n",
787                        libcfs_nid2str(msg->msg_rxpeer->lpni_nid),
788                        libcfs_id2str(msg->msg_target), rc);
789                 LASSERT(rc < 0); /* required by my callers */
790         }
791
792         return rc;
793 }
794
795 /*
796  * This function can be called from two paths:
797  *      1. when sending a message
798  *      2. when decommiting a message (lnet_msg_decommit_tx())
799  * In both these cases the peer_ni should have it's reference count
800  * acquired by the caller and therefore it is safe to drop the spin
801  * lock before calling lnd_query()
802  */
803 static void
804 lnet_ni_query_locked(struct lnet_ni *ni, struct lnet_peer_ni *lp)
805 {
806         time64_t last_alive = 0;
807         int cpt = lnet_cpt_of_nid_locked(lp->lpni_nid, ni);
808
809         LASSERT(lnet_peer_aliveness_enabled(lp));
810         LASSERT(ni->ni_net->net_lnd->lnd_query != NULL);
811
812         lnet_net_unlock(cpt);
813         (ni->ni_net->net_lnd->lnd_query)(ni, lp->lpni_nid, &last_alive);
814         lnet_net_lock(cpt);
815
816         lp->lpni_last_query = ktime_get_seconds();
817
818         if (last_alive != 0) /* NI has updated timestamp */
819                 lp->lpni_last_alive = last_alive;
820 }
821
822 /* NB: always called with lnet_net_lock held */
823 static inline int
824 lnet_peer_is_alive(struct lnet_peer_ni *lp, time64_t now)
825 {
826         int alive;
827         time64_t deadline;
828
829         LASSERT (lnet_peer_aliveness_enabled(lp));
830
831         /*
832          * Trust lnet_notify() if it has more recent aliveness news, but
833          * ignore the initial assumed death (see lnet_peers_start_down()).
834          */
835         spin_lock(&lp->lpni_lock);
836         if (!lp->lpni_alive && lp->lpni_alive_count > 0 &&
837             lp->lpni_timestamp >= lp->lpni_last_alive) {
838                 spin_unlock(&lp->lpni_lock);
839                 return 0;
840         }
841
842         deadline = lp->lpni_last_alive +
843                    lp->lpni_net->net_tunables.lct_peer_timeout;
844         alive = deadline > now;
845
846         /*
847          * Update obsolete lp_alive except for routers assumed to be dead
848          * initially, because router checker would update aliveness in this
849          * case, and moreover lpni_last_alive at peer creation is assumed.
850          */
851         if (alive && !lp->lpni_alive &&
852             !(lnet_isrouter(lp) && lp->lpni_alive_count == 0)) {
853                 spin_unlock(&lp->lpni_lock);
854                 lnet_notify_locked(lp, 0, 1, lp->lpni_last_alive);
855         } else {
856                 spin_unlock(&lp->lpni_lock);
857         }
858
859         return alive;
860 }
861
862
863 /* NB: returns 1 when alive, 0 when dead, negative when error;
864  *     may drop the lnet_net_lock */
865 static int
866 lnet_peer_alive_locked(struct lnet_ni *ni, struct lnet_peer_ni *lp)
867 {
868         time64_t now = ktime_get_seconds();
869
870         if (!lnet_peer_aliveness_enabled(lp))
871                 return -ENODEV;
872
873         if (lnet_peer_is_alive(lp, now))
874                 return 1;
875
876         /*
877          * Peer appears dead, but we should avoid frequent NI queries (at
878          * most once per lnet_queryinterval seconds).
879          */
880         if (lp->lpni_last_query != 0) {
881                 static const int lnet_queryinterval = 1;
882                 time64_t next_query;
883
884                 next_query = lp->lpni_last_query + lnet_queryinterval;
885
886                 if (now < next_query) {
887                         if (lp->lpni_alive)
888                                 CWARN("Unexpected aliveness of peer %s: "
889                                       "%lld < %lld (%d/%d)\n",
890                                       libcfs_nid2str(lp->lpni_nid),
891                                       now, next_query,
892                                       lnet_queryinterval,
893                                       lp->lpni_net->net_tunables.lct_peer_timeout);
894                         return 0;
895                 }
896         }
897
898         /* query NI for latest aliveness news */
899         lnet_ni_query_locked(ni, lp);
900
901         if (lnet_peer_is_alive(lp, now))
902                 return 1;
903
904         lnet_notify_locked(lp, 0, 0, lp->lpni_last_alive);
905         return 0;
906 }
907
908 /**
909  * \param msg The message to be sent.
910  * \param do_send True if lnet_ni_send() should be called in this function.
911  *        lnet_send() is going to lnet_net_unlock immediately after this, so
912  *        it sets do_send FALSE and I don't do the unlock/send/lock bit.
913  *
914  * \retval LNET_CREDIT_OK If \a msg sent or OK to send.
915  * \retval LNET_CREDIT_WAIT If \a msg blocked for credit.
916  * \retval -EHOSTUNREACH If the next hop of the message appears dead.
917  * \retval -ECANCELED If the MD of the message has been unlinked.
918  */
919 static int
920 lnet_post_send_locked(struct lnet_msg *msg, int do_send)
921 {
922         struct lnet_peer_ni     *lp = msg->msg_txpeer;
923         struct lnet_ni          *ni = msg->msg_txni;
924         int                     cpt = msg->msg_tx_cpt;
925         struct lnet_tx_queue    *tq = ni->ni_tx_queues[cpt];
926
927         /* non-lnet_send() callers have checked before */
928         LASSERT(!do_send || msg->msg_tx_delayed);
929         LASSERT(!msg->msg_receiving);
930         LASSERT(msg->msg_tx_committed);
931
932         /* NB 'lp' is always the next hop */
933         if ((msg->msg_target.pid & LNET_PID_USERFLAG) == 0 &&
934             lnet_peer_alive_locked(ni, lp) == 0) {
935                 the_lnet.ln_counters[cpt]->drop_count++;
936                 the_lnet.ln_counters[cpt]->drop_length += msg->msg_len;
937                 lnet_net_unlock(cpt);
938                 if (msg->msg_txpeer)
939                         lnet_incr_stats(&msg->msg_txpeer->lpni_stats,
940                                         msg->msg_type,
941                                         LNET_STATS_TYPE_DROP);
942                 if (msg->msg_txni)
943                         lnet_incr_stats(&msg->msg_txni->ni_stats,
944                                         msg->msg_type,
945                                         LNET_STATS_TYPE_DROP);
946
947                 CNETERR("Dropping message for %s: peer not alive\n",
948                         libcfs_id2str(msg->msg_target));
949                 if (do_send)
950                         lnet_finalize(msg, -EHOSTUNREACH);
951
952                 lnet_net_lock(cpt);
953                 return -EHOSTUNREACH;
954         }
955
956         if (msg->msg_md != NULL &&
957             (msg->msg_md->md_flags & LNET_MD_FLAG_ABORTED) != 0) {
958                 lnet_net_unlock(cpt);
959
960                 CNETERR("Aborting message for %s: LNetM[DE]Unlink() already "
961                         "called on the MD/ME.\n",
962                         libcfs_id2str(msg->msg_target));
963                 if (do_send)
964                         lnet_finalize(msg, -ECANCELED);
965
966                 lnet_net_lock(cpt);
967                 return -ECANCELED;
968         }
969
970         if (!msg->msg_peertxcredit) {
971                 spin_lock(&lp->lpni_lock);
972                 LASSERT((lp->lpni_txcredits < 0) ==
973                         !list_empty(&lp->lpni_txq));
974
975                 msg->msg_peertxcredit = 1;
976                 lp->lpni_txqnob += msg->msg_len + sizeof(struct lnet_hdr);
977                 lp->lpni_txcredits--;
978
979                 if (lp->lpni_txcredits < lp->lpni_mintxcredits)
980                         lp->lpni_mintxcredits = lp->lpni_txcredits;
981
982                 if (lp->lpni_txcredits < 0) {
983                         msg->msg_tx_delayed = 1;
984                         list_add_tail(&msg->msg_list, &lp->lpni_txq);
985                         spin_unlock(&lp->lpni_lock);
986                         return LNET_CREDIT_WAIT;
987                 }
988                 spin_unlock(&lp->lpni_lock);
989         }
990
991         if (!msg->msg_txcredit) {
992                 LASSERT((tq->tq_credits < 0) ==
993                         !list_empty(&tq->tq_delayed));
994
995                 msg->msg_txcredit = 1;
996                 tq->tq_credits--;
997                 atomic_dec(&ni->ni_tx_credits);
998
999                 if (tq->tq_credits < tq->tq_credits_min)
1000                         tq->tq_credits_min = tq->tq_credits;
1001
1002                 if (tq->tq_credits < 0) {
1003                         msg->msg_tx_delayed = 1;
1004                         list_add_tail(&msg->msg_list, &tq->tq_delayed);
1005                         return LNET_CREDIT_WAIT;
1006                 }
1007         }
1008
1009         if (do_send) {
1010                 lnet_net_unlock(cpt);
1011                 lnet_ni_send(ni, msg);
1012                 lnet_net_lock(cpt);
1013         }
1014         return LNET_CREDIT_OK;
1015 }
1016
1017
1018 static struct lnet_rtrbufpool *
1019 lnet_msg2bufpool(struct lnet_msg *msg)
1020 {
1021         struct lnet_rtrbufpool  *rbp;
1022         int                     cpt;
1023
1024         LASSERT(msg->msg_rx_committed);
1025
1026         cpt = msg->msg_rx_cpt;
1027         rbp = &the_lnet.ln_rtrpools[cpt][0];
1028
1029         LASSERT(msg->msg_len <= LNET_MTU);
1030         while (msg->msg_len > (unsigned int)rbp->rbp_npages * PAGE_SIZE) {
1031                 rbp++;
1032                 LASSERT(rbp < &the_lnet.ln_rtrpools[cpt][LNET_NRBPOOLS]);
1033         }
1034
1035         return rbp;
1036 }
1037
1038 static int
1039 lnet_post_routed_recv_locked(struct lnet_msg *msg, int do_recv)
1040 {
1041         /* lnet_parse is going to lnet_net_unlock immediately after this, so it
1042          * sets do_recv FALSE and I don't do the unlock/send/lock bit.
1043          * I return LNET_CREDIT_WAIT if msg blocked and LNET_CREDIT_OK if
1044          * received or OK to receive */
1045         struct lnet_peer_ni *lp = msg->msg_rxpeer;
1046         struct lnet_rtrbufpool *rbp;
1047         struct lnet_rtrbuf *rb;
1048
1049         LASSERT (msg->msg_iov == NULL);
1050         LASSERT (msg->msg_kiov == NULL);
1051         LASSERT (msg->msg_niov == 0);
1052         LASSERT (msg->msg_routing);
1053         LASSERT (msg->msg_receiving);
1054         LASSERT (!msg->msg_sending);
1055
1056         /* non-lnet_parse callers only receive delayed messages */
1057         LASSERT(!do_recv || msg->msg_rx_delayed);
1058
1059         if (!msg->msg_peerrtrcredit) {
1060                 spin_lock(&lp->lpni_lock);
1061                 LASSERT((lp->lpni_rtrcredits < 0) ==
1062                         !list_empty(&lp->lpni_rtrq));
1063
1064                 msg->msg_peerrtrcredit = 1;
1065                 lp->lpni_rtrcredits--;
1066                 if (lp->lpni_rtrcredits < lp->lpni_minrtrcredits)
1067                         lp->lpni_minrtrcredits = lp->lpni_rtrcredits;
1068
1069                 if (lp->lpni_rtrcredits < 0) {
1070                         /* must have checked eager_recv before here */
1071                         LASSERT(msg->msg_rx_ready_delay);
1072                         msg->msg_rx_delayed = 1;
1073                         list_add_tail(&msg->msg_list, &lp->lpni_rtrq);
1074                         spin_unlock(&lp->lpni_lock);
1075                         return LNET_CREDIT_WAIT;
1076                 }
1077                 spin_unlock(&lp->lpni_lock);
1078         }
1079
1080         rbp = lnet_msg2bufpool(msg);
1081
1082         if (!msg->msg_rtrcredit) {
1083                 msg->msg_rtrcredit = 1;
1084                 rbp->rbp_credits--;
1085                 if (rbp->rbp_credits < rbp->rbp_mincredits)
1086                         rbp->rbp_mincredits = rbp->rbp_credits;
1087
1088                 if (rbp->rbp_credits < 0) {
1089                         /* must have checked eager_recv before here */
1090                         LASSERT(msg->msg_rx_ready_delay);
1091                         msg->msg_rx_delayed = 1;
1092                         list_add_tail(&msg->msg_list, &rbp->rbp_msgs);
1093                         return LNET_CREDIT_WAIT;
1094                 }
1095         }
1096
1097         LASSERT(!list_empty(&rbp->rbp_bufs));
1098         rb = list_entry(rbp->rbp_bufs.next, struct lnet_rtrbuf, rb_list);
1099         list_del(&rb->rb_list);
1100
1101         msg->msg_niov = rbp->rbp_npages;
1102         msg->msg_kiov = &rb->rb_kiov[0];
1103
1104         if (do_recv) {
1105                 int cpt = msg->msg_rx_cpt;
1106
1107                 lnet_net_unlock(cpt);
1108                 lnet_ni_recv(msg->msg_rxni, msg->msg_private, msg, 1,
1109                              0, msg->msg_len, msg->msg_len);
1110                 lnet_net_lock(cpt);
1111         }
1112         return LNET_CREDIT_OK;
1113 }
1114
1115 void
1116 lnet_return_tx_credits_locked(struct lnet_msg *msg)
1117 {
1118         struct lnet_peer_ni     *txpeer = msg->msg_txpeer;
1119         struct lnet_ni          *txni = msg->msg_txni;
1120         struct lnet_msg         *msg2;
1121
1122         if (msg->msg_txcredit) {
1123                 struct lnet_ni       *ni = msg->msg_txni;
1124                 struct lnet_tx_queue *tq = ni->ni_tx_queues[msg->msg_tx_cpt];
1125
1126                 /* give back NI txcredits */
1127                 msg->msg_txcredit = 0;
1128
1129                 LASSERT((tq->tq_credits < 0) ==
1130                         !list_empty(&tq->tq_delayed));
1131
1132                 tq->tq_credits++;
1133                 atomic_inc(&ni->ni_tx_credits);
1134                 if (tq->tq_credits <= 0) {
1135                         msg2 = list_entry(tq->tq_delayed.next,
1136                                           struct lnet_msg, msg_list);
1137                         list_del(&msg2->msg_list);
1138
1139                         LASSERT(msg2->msg_txni == ni);
1140                         LASSERT(msg2->msg_tx_delayed);
1141                         LASSERT(msg2->msg_tx_cpt == msg->msg_tx_cpt);
1142
1143                         (void) lnet_post_send_locked(msg2, 1);
1144                 }
1145         }
1146
1147         if (msg->msg_peertxcredit) {
1148                 /* give back peer txcredits */
1149                 msg->msg_peertxcredit = 0;
1150
1151                 spin_lock(&txpeer->lpni_lock);
1152                 LASSERT((txpeer->lpni_txcredits < 0) ==
1153                         !list_empty(&txpeer->lpni_txq));
1154
1155                 txpeer->lpni_txqnob -= msg->msg_len + sizeof(struct lnet_hdr);
1156                 LASSERT(txpeer->lpni_txqnob >= 0);
1157
1158                 txpeer->lpni_txcredits++;
1159                 if (txpeer->lpni_txcredits <= 0) {
1160                         int msg2_cpt;
1161
1162                         msg2 = list_entry(txpeer->lpni_txq.next,
1163                                               struct lnet_msg, msg_list);
1164                         list_del(&msg2->msg_list);
1165                         spin_unlock(&txpeer->lpni_lock);
1166
1167                         LASSERT(msg2->msg_txpeer == txpeer);
1168                         LASSERT(msg2->msg_tx_delayed);
1169
1170                         msg2_cpt = msg2->msg_tx_cpt;
1171
1172                         /*
1173                          * The msg_cpt can be different from the msg2_cpt
1174                          * so we need to make sure we lock the correct cpt
1175                          * for msg2.
1176                          * Once we call lnet_post_send_locked() it is no
1177                          * longer safe to access msg2, since it could've
1178                          * been freed by lnet_finalize(), but we still
1179                          * need to relock the correct cpt, so we cache the
1180                          * msg2_cpt for the purpose of the check that
1181                          * follows the call to lnet_pose_send_locked().
1182                          */
1183                         if (msg2_cpt != msg->msg_tx_cpt) {
1184                                 lnet_net_unlock(msg->msg_tx_cpt);
1185                                 lnet_net_lock(msg2_cpt);
1186                         }
1187                         (void) lnet_post_send_locked(msg2, 1);
1188                         if (msg2_cpt != msg->msg_tx_cpt) {
1189                                 lnet_net_unlock(msg2_cpt);
1190                                 lnet_net_lock(msg->msg_tx_cpt);
1191                         }
1192                 } else {
1193                         spin_unlock(&txpeer->lpni_lock);
1194                 }
1195         }
1196
1197         if (txni != NULL) {
1198                 msg->msg_txni = NULL;
1199                 lnet_ni_decref_locked(txni, msg->msg_tx_cpt);
1200         }
1201
1202         if (txpeer != NULL) {
1203                 /*
1204                  * TODO:
1205                  * Once the patch for the health comes in we need to set
1206                  * the health of the peer ni to bad when we fail to send
1207                  * a message.
1208                  * int status = msg->msg_ev.status;
1209                  * if (status != 0)
1210                  *      lnet_set_peer_ni_health_locked(txpeer, false)
1211                  */
1212                 msg->msg_txpeer = NULL;
1213                 lnet_peer_ni_decref_locked(txpeer);
1214         }
1215 }
1216
1217 void
1218 lnet_schedule_blocked_locked(struct lnet_rtrbufpool *rbp)
1219 {
1220         struct lnet_msg *msg;
1221
1222         if (list_empty(&rbp->rbp_msgs))
1223                 return;
1224         msg = list_entry(rbp->rbp_msgs.next,
1225                          struct lnet_msg, msg_list);
1226         list_del(&msg->msg_list);
1227
1228         (void)lnet_post_routed_recv_locked(msg, 1);
1229 }
1230
1231 void
1232 lnet_drop_routed_msgs_locked(struct list_head *list, int cpt)
1233 {
1234         struct lnet_msg *msg;
1235         struct lnet_msg *tmp;
1236
1237         lnet_net_unlock(cpt);
1238
1239         list_for_each_entry_safe(msg, tmp, list, msg_list) {
1240                 lnet_ni_recv(msg->msg_rxni, msg->msg_private, NULL,
1241                              0, 0, 0, msg->msg_hdr.payload_length);
1242                 list_del_init(&msg->msg_list);
1243                 lnet_finalize(msg, -ECANCELED);
1244         }
1245
1246         lnet_net_lock(cpt);
1247 }
1248
1249 void
1250 lnet_return_rx_credits_locked(struct lnet_msg *msg)
1251 {
1252         struct lnet_peer_ni *rxpeer = msg->msg_rxpeer;
1253         struct lnet_ni *rxni = msg->msg_rxni;
1254         struct lnet_msg *msg2;
1255
1256         if (msg->msg_rtrcredit) {
1257                 /* give back global router credits */
1258                 struct lnet_rtrbuf *rb;
1259                 struct lnet_rtrbufpool *rbp;
1260
1261                 /* NB If a msg ever blocks for a buffer in rbp_msgs, it stays
1262                  * there until it gets one allocated, or aborts the wait
1263                  * itself */
1264                 LASSERT(msg->msg_kiov != NULL);
1265
1266                 rb = list_entry(msg->msg_kiov, struct lnet_rtrbuf, rb_kiov[0]);
1267                 rbp = rb->rb_pool;
1268
1269                 msg->msg_kiov = NULL;
1270                 msg->msg_rtrcredit = 0;
1271
1272                 LASSERT(rbp == lnet_msg2bufpool(msg));
1273
1274                 LASSERT((rbp->rbp_credits > 0) ==
1275                         !list_empty(&rbp->rbp_bufs));
1276
1277                 /* If routing is now turned off, we just drop this buffer and
1278                  * don't bother trying to return credits.  */
1279                 if (!the_lnet.ln_routing) {
1280                         lnet_destroy_rtrbuf(rb, rbp->rbp_npages);
1281                         goto routing_off;
1282                 }
1283
1284                 /* It is possible that a user has lowered the desired number of
1285                  * buffers in this pool.  Make sure we never put back
1286                  * more buffers than the stated number. */
1287                 if (unlikely(rbp->rbp_credits >= rbp->rbp_req_nbuffers)) {
1288                         /* Discard this buffer so we don't have too
1289                          * many. */
1290                         lnet_destroy_rtrbuf(rb, rbp->rbp_npages);
1291                         rbp->rbp_nbuffers--;
1292                 } else {
1293                         list_add(&rb->rb_list, &rbp->rbp_bufs);
1294                         rbp->rbp_credits++;
1295                         if (rbp->rbp_credits <= 0)
1296                                 lnet_schedule_blocked_locked(rbp);
1297                 }
1298         }
1299
1300 routing_off:
1301         if (msg->msg_peerrtrcredit) {
1302                 /* give back peer router credits */
1303                 msg->msg_peerrtrcredit = 0;
1304
1305                 spin_lock(&rxpeer->lpni_lock);
1306                 LASSERT((rxpeer->lpni_rtrcredits < 0) ==
1307                         !list_empty(&rxpeer->lpni_rtrq));
1308
1309                 rxpeer->lpni_rtrcredits++;
1310
1311                 /* drop all messages which are queued to be routed on that
1312                  * peer. */
1313                 if (!the_lnet.ln_routing) {
1314                         struct list_head drop;
1315                         INIT_LIST_HEAD(&drop);
1316                         list_splice_init(&rxpeer->lpni_rtrq, &drop);
1317                         spin_unlock(&rxpeer->lpni_lock);
1318                         lnet_drop_routed_msgs_locked(&drop, msg->msg_rx_cpt);
1319                 } else if (rxpeer->lpni_rtrcredits <= 0) {
1320                         msg2 = list_entry(rxpeer->lpni_rtrq.next,
1321                                           struct lnet_msg, msg_list);
1322                         list_del(&msg2->msg_list);
1323                         spin_unlock(&rxpeer->lpni_lock);
1324                         (void) lnet_post_routed_recv_locked(msg2, 1);
1325                 } else {
1326                         spin_unlock(&rxpeer->lpni_lock);
1327                 }
1328         }
1329         if (rxni != NULL) {
1330                 msg->msg_rxni = NULL;
1331                 lnet_ni_decref_locked(rxni, msg->msg_rx_cpt);
1332         }
1333         if (rxpeer != NULL) {
1334                 msg->msg_rxpeer = NULL;
1335                 lnet_peer_ni_decref_locked(rxpeer);
1336         }
1337 }
1338
1339 static int
1340 lnet_compare_peers(struct lnet_peer_ni *p1, struct lnet_peer_ni *p2)
1341 {
1342         if (p1->lpni_txqnob < p2->lpni_txqnob)
1343                 return 1;
1344
1345         if (p1->lpni_txqnob > p2->lpni_txqnob)
1346                 return -1;
1347
1348         if (p1->lpni_txcredits > p2->lpni_txcredits)
1349                 return 1;
1350
1351         if (p1->lpni_txcredits < p2->lpni_txcredits)
1352                 return -1;
1353
1354         return 0;
1355 }
1356
1357 static int
1358 lnet_compare_routes(struct lnet_route *r1, struct lnet_route *r2)
1359 {
1360         struct lnet_peer_ni *p1 = r1->lr_gateway;
1361         struct lnet_peer_ni *p2 = r2->lr_gateway;
1362         int r1_hops = (r1->lr_hops == LNET_UNDEFINED_HOPS) ? 1 : r1->lr_hops;
1363         int r2_hops = (r2->lr_hops == LNET_UNDEFINED_HOPS) ? 1 : r2->lr_hops;
1364         int rc;
1365
1366         if (r1->lr_priority < r2->lr_priority)
1367                 return 1;
1368
1369         if (r1->lr_priority > r2->lr_priority)
1370                 return -1;
1371
1372         if (r1_hops < r2_hops)
1373                 return 1;
1374
1375         if (r1_hops > r2_hops)
1376                 return -1;
1377
1378         rc = lnet_compare_peers(p1, p2);
1379         if (rc)
1380                 return rc;
1381
1382         if (r1->lr_seq - r2->lr_seq <= 0)
1383                 return 1;
1384
1385         return -1;
1386 }
1387
1388 static struct lnet_peer_ni *
1389 lnet_find_route_locked(struct lnet_net *net, __u32 remote_net,
1390                        lnet_nid_t rtr_nid)
1391 {
1392         struct lnet_remotenet   *rnet;
1393         struct lnet_route               *route;
1394         struct lnet_route               *best_route;
1395         struct lnet_route               *last_route;
1396         struct lnet_peer_ni     *lpni_best;
1397         struct lnet_peer_ni     *lp;
1398         int                     rc;
1399
1400         /* If @rtr_nid is not LNET_NID_ANY, return the gateway with
1401          * rtr_nid nid, otherwise find the best gateway I can use */
1402
1403         rnet = lnet_find_rnet_locked(remote_net);
1404         if (rnet == NULL)
1405                 return NULL;
1406
1407         lpni_best = NULL;
1408         best_route = last_route = NULL;
1409         list_for_each_entry(route, &rnet->lrn_routes, lr_list) {
1410                 lp = route->lr_gateway;
1411
1412                 if (!lnet_is_route_alive(route))
1413                         continue;
1414
1415                 if (net != NULL && lp->lpni_net != net)
1416                         continue;
1417
1418                 if (lp->lpni_nid == rtr_nid) /* it's pre-determined router */
1419                         return lp;
1420
1421                 if (lpni_best == NULL) {
1422                         best_route = last_route = route;
1423                         lpni_best = lp;
1424                         continue;
1425                 }
1426
1427                 /* no protection on below fields, but it's harmless */
1428                 if (last_route->lr_seq - route->lr_seq < 0)
1429                         last_route = route;
1430
1431                 rc = lnet_compare_routes(route, best_route);
1432                 if (rc < 0)
1433                         continue;
1434
1435                 best_route = route;
1436                 lpni_best = lp;
1437         }
1438
1439         /* set sequence number on the best router to the latest sequence + 1
1440          * so we can round-robin all routers, it's race and inaccurate but
1441          * harmless and functional  */
1442         if (best_route != NULL)
1443                 best_route->lr_seq = last_route->lr_seq + 1;
1444         return lpni_best;
1445 }
1446
1447 static struct lnet_ni *
1448 lnet_get_best_ni(struct lnet_net *local_net, struct lnet_ni *best_ni,
1449                  struct lnet_peer *peer, struct lnet_peer_net *peer_net,
1450                  int md_cpt)
1451 {
1452         struct lnet_ni *ni = NULL;
1453         unsigned int shortest_distance;
1454         int best_credits;
1455         int best_healthv;
1456
1457         /*
1458          * If there is no peer_ni that we can send to on this network,
1459          * then there is no point in looking for a new best_ni here.
1460         */
1461         if (!lnet_get_next_peer_ni_locked(peer, peer_net, NULL))
1462                 return best_ni;
1463
1464         if (best_ni == NULL) {
1465                 shortest_distance = UINT_MAX;
1466                 best_credits = INT_MIN;
1467                 best_healthv = 0;
1468         } else {
1469                 shortest_distance = cfs_cpt_distance(lnet_cpt_table(), md_cpt,
1470                                                      best_ni->ni_dev_cpt);
1471                 best_credits = atomic_read(&best_ni->ni_tx_credits);
1472                 best_healthv = atomic_read(&best_ni->ni_healthv);
1473         }
1474
1475         while ((ni = lnet_get_next_ni_locked(local_net, ni))) {
1476                 unsigned int distance;
1477                 int ni_credits;
1478                 int ni_healthv;
1479
1480                 ni_credits = atomic_read(&ni->ni_tx_credits);
1481                 ni_healthv = atomic_read(&ni->ni_healthv);
1482
1483                 /*
1484                  * calculate the distance from the CPT on which
1485                  * the message memory is allocated to the CPT of
1486                  * the NI's physical device
1487                  */
1488                 distance = cfs_cpt_distance(lnet_cpt_table(),
1489                                             md_cpt,
1490                                             ni->ni_dev_cpt);
1491
1492                 CDEBUG(D_NET, "compare ni %s [c:%d, d:%d, s:%d] with best_ni %s [c:%d, d:%d, s:%d]\n",
1493                        libcfs_nid2str(ni->ni_nid), ni_credits, distance,
1494                        ni->ni_seq, (best_ni) ? libcfs_nid2str(best_ni->ni_nid)
1495                         : "not seleced", best_credits, shortest_distance,
1496                         (best_ni) ? best_ni->ni_seq : 0);
1497
1498                 /*
1499                  * All distances smaller than the NUMA range
1500                  * are treated equally.
1501                  */
1502                 if (distance < lnet_numa_range)
1503                         distance = lnet_numa_range;
1504
1505                 /*
1506                  * Select on health, shorter distance, available
1507                  * credits, then round-robin.
1508                  */
1509                 if (ni_healthv < best_healthv) {
1510                         continue;
1511                 } else if (ni_healthv > best_healthv) {
1512                         best_healthv = ni_healthv;
1513                         /*
1514                          * If we're going to prefer this ni because it's
1515                          * the healthiest, then we should set the
1516                          * shortest_distance in the algorithm in case
1517                          * there are multiple NIs with the same health but
1518                          * different distances.
1519                          */
1520                         if (distance < shortest_distance)
1521                                 shortest_distance = distance;
1522                 } else if (distance > shortest_distance) {
1523                         continue;
1524                 } else if (distance < shortest_distance) {
1525                         shortest_distance = distance;
1526                 } else if (ni_credits < best_credits) {
1527                         continue;
1528                 } else if (ni_credits == best_credits) {
1529                         if (best_ni && best_ni->ni_seq <= ni->ni_seq)
1530                                 continue;
1531                 }
1532                 best_ni = ni;
1533                 best_credits = ni_credits;
1534         }
1535
1536         CDEBUG(D_NET, "selected best_ni %s\n",
1537                (best_ni) ? libcfs_nid2str(best_ni->ni_nid) : "no selection");
1538
1539         return best_ni;
1540 }
1541
1542 /*
1543  * Traffic to the LNET_RESERVED_PORTAL may not trigger peer discovery,
1544  * because such traffic is required to perform discovery. We therefore
1545  * exclude all GET and PUT on that portal. We also exclude all ACK and
1546  * REPLY traffic, but that is because the portal is not tracked in the
1547  * message structure for these message types. We could restrict this
1548  * further by also checking for LNET_PROTO_PING_MATCHBITS.
1549  */
1550 static bool
1551 lnet_msg_discovery(struct lnet_msg *msg)
1552 {
1553         if (msg->msg_type == LNET_MSG_PUT) {
1554                 if (msg->msg_hdr.msg.put.ptl_index != LNET_RESERVED_PORTAL)
1555                         return true;
1556         } else if (msg->msg_type == LNET_MSG_GET) {
1557                 if (msg->msg_hdr.msg.get.ptl_index != LNET_RESERVED_PORTAL)
1558                         return true;
1559         }
1560         return false;
1561 }
1562
1563 #define SRC_SPEC        0x0001
1564 #define SRC_ANY         0x0002
1565 #define LOCAL_DST       0x0004
1566 #define REMOTE_DST      0x0008
1567 #define MR_DST          0x0010
1568 #define NMR_DST         0x0020
1569 #define SND_RESP        0x0040
1570
1571 /* The following to defines are used for return codes */
1572 #define REPEAT_SEND     0x1000
1573 #define PASS_THROUGH    0x2000
1574
1575 /* The different cases lnet_select pathway needs to handle */
1576 #define SRC_SPEC_LOCAL_MR_DST   (SRC_SPEC | LOCAL_DST | MR_DST)
1577 #define SRC_SPEC_ROUTER_MR_DST  (SRC_SPEC | REMOTE_DST | MR_DST)
1578 #define SRC_SPEC_LOCAL_NMR_DST  (SRC_SPEC | LOCAL_DST | NMR_DST)
1579 #define SRC_SPEC_ROUTER_NMR_DST (SRC_SPEC | REMOTE_DST | NMR_DST)
1580 #define SRC_ANY_LOCAL_MR_DST    (SRC_ANY | LOCAL_DST | MR_DST)
1581 #define SRC_ANY_ROUTER_MR_DST   (SRC_ANY | REMOTE_DST | MR_DST)
1582 #define SRC_ANY_LOCAL_NMR_DST   (SRC_ANY | LOCAL_DST | NMR_DST)
1583 #define SRC_ANY_ROUTER_NMR_DST  (SRC_ANY | REMOTE_DST | NMR_DST)
1584
1585 static int
1586 lnet_handle_send(struct lnet_send_data *sd)
1587 {
1588         struct lnet_ni *best_ni = sd->sd_best_ni;
1589         struct lnet_peer_ni *best_lpni = sd->sd_best_lpni;
1590         struct lnet_peer_ni *final_dst_lpni = sd->sd_final_dst_lpni;
1591         struct lnet_msg *msg = sd->sd_msg;
1592         int cpt2;
1593         __u32 send_case = sd->sd_send_case;
1594         int rc;
1595         __u32 routing = send_case & REMOTE_DST;
1596
1597         /*
1598          * Increment sequence number of the selected peer so that we
1599          * pick the next one in Round Robin.
1600          */
1601         best_lpni->lpni_seq++;
1602
1603         /*
1604          * grab a reference on the peer_ni so it sticks around even if
1605          * we need to drop and relock the lnet_net_lock below.
1606          */
1607         lnet_peer_ni_addref_locked(best_lpni);
1608
1609         /*
1610          * Use lnet_cpt_of_nid() to determine the CPT used to commit the
1611          * message. This ensures that we get a CPT that is correct for
1612          * the NI when the NI has been restricted to a subset of all CPTs.
1613          * If the selected CPT differs from the one currently locked, we
1614          * must unlock and relock the lnet_net_lock(), and then check whether
1615          * the configuration has changed. We don't have a hold on the best_ni
1616          * yet, and it may have vanished.
1617          */
1618         cpt2 = lnet_cpt_of_nid_locked(best_lpni->lpni_nid, best_ni);
1619         if (sd->sd_cpt != cpt2) {
1620                 __u32 seq = lnet_get_dlc_seq_locked();
1621                 lnet_net_unlock(sd->sd_cpt);
1622                 sd->sd_cpt = cpt2;
1623                 lnet_net_lock(sd->sd_cpt);
1624                 if (seq != lnet_get_dlc_seq_locked()) {
1625                         lnet_peer_ni_decref_locked(best_lpni);
1626                         return REPEAT_SEND;
1627                 }
1628         }
1629
1630         /*
1631          * store the best_lpni in the message right away to avoid having
1632          * to do the same operation under different conditions
1633          */
1634         msg->msg_txpeer = best_lpni;
1635         msg->msg_txni = best_ni;
1636
1637         /*
1638          * grab a reference for the best_ni since now it's in use in this
1639          * send. The reference will be dropped in lnet_finalize()
1640          */
1641         lnet_ni_addref_locked(msg->msg_txni, sd->sd_cpt);
1642
1643         /*
1644          * Always set the target.nid to the best peer picked. Either the
1645          * NID will be one of the peer NIDs selected, or the same NID as
1646          * what was originally set in the target or it will be the NID of
1647          * a router if this message should be routed
1648          */
1649         msg->msg_target.nid = msg->msg_txpeer->lpni_nid;
1650
1651         /*
1652          * lnet_msg_commit assigns the correct cpt to the message, which
1653          * is used to decrement the correct refcount on the ni when it's
1654          * time to return the credits
1655          */
1656         lnet_msg_commit(msg, sd->sd_cpt);
1657
1658         /*
1659          * If we are routing the message then we keep the src_nid that was
1660          * set by the originator. If we are not routing then we are the
1661          * originator and set it here.
1662          */
1663         if (!msg->msg_routing)
1664                 msg->msg_hdr.src_nid = cpu_to_le64(msg->msg_txni->ni_nid);
1665
1666         if (routing) {
1667                 msg->msg_target_is_router = 1;
1668                 msg->msg_target.pid = LNET_PID_LUSTRE;
1669                 /*
1670                  * since we're routing we want to ensure that the
1671                  * msg_hdr.dest_nid is set to the final destination. When
1672                  * the router receives this message it knows how to route
1673                  * it.
1674                  *
1675                  * final_dst_lpni is set at the beginning of the
1676                  * lnet_select_pathway() function and is never changed.
1677                  * It's safe to use it here.
1678                  */
1679                 msg->msg_hdr.dest_nid = cpu_to_le64(final_dst_lpni->lpni_nid);
1680         } else {
1681                 /*
1682                  * if we're not routing set the dest_nid to the best peer
1683                  * ni NID that we picked earlier in the algorithm.
1684                  */
1685                 msg->msg_hdr.dest_nid = cpu_to_le64(msg->msg_txpeer->lpni_nid);
1686         }
1687
1688         rc = lnet_post_send_locked(msg, 0);
1689
1690         if (!rc)
1691                 CDEBUG(D_NET, "TRACE: %s(%s:%s) -> %s(%s:%s) : %s\n",
1692                        libcfs_nid2str(msg->msg_hdr.src_nid),
1693                        libcfs_nid2str(msg->msg_txni->ni_nid),
1694                        libcfs_nid2str(sd->sd_src_nid),
1695                        libcfs_nid2str(msg->msg_hdr.dest_nid),
1696                        libcfs_nid2str(sd->sd_dst_nid),
1697                        libcfs_nid2str(msg->msg_txpeer->lpni_nid),
1698                        lnet_msgtyp2str(msg->msg_type));
1699
1700         return rc;
1701 }
1702
1703 static struct lnet_peer_ni *
1704 lnet_select_peer_ni(struct lnet_send_data *sd, struct lnet_peer *peer,
1705                     struct lnet_peer_net *peer_net)
1706 {
1707         /*
1708          * Look at the peer NIs for the destination peer that connect
1709          * to the chosen net. If a peer_ni is preferred when using the
1710          * best_ni to communicate, we use that one. If there is no
1711          * preferred peer_ni, or there are multiple preferred peer_ni,
1712          * the available transmit credits are used. If the transmit
1713          * credits are equal, we round-robin over the peer_ni.
1714          */
1715         struct lnet_peer_ni *lpni = NULL;
1716         struct lnet_peer_ni *best_lpni = NULL;
1717         struct lnet_ni *best_ni = sd->sd_best_ni;
1718         lnet_nid_t dst_nid = sd->sd_dst_nid;
1719         int best_lpni_credits = INT_MIN;
1720         bool preferred = false;
1721         bool ni_is_pref;
1722
1723         while ((lpni = lnet_get_next_peer_ni_locked(peer, peer_net, lpni))) {
1724                 /*
1725                  * if the best_ni we've chosen aleady has this lpni
1726                  * preferred, then let's use it
1727                  */
1728                 ni_is_pref = lnet_peer_is_pref_nid_locked(lpni,
1729                                                           best_ni->ni_nid);
1730
1731                 CDEBUG(D_NET, "%s ni_is_pref = %d\n",
1732                        libcfs_nid2str(best_ni->ni_nid), ni_is_pref);
1733
1734                 if (best_lpni)
1735                         CDEBUG(D_NET, "%s c:[%d, %d], s:[%d, %d]\n",
1736                                 libcfs_nid2str(lpni->lpni_nid),
1737                                 lpni->lpni_txcredits, best_lpni_credits,
1738                                 lpni->lpni_seq, best_lpni->lpni_seq);
1739
1740                 /* if this is a preferred peer use it */
1741                 if (!preferred && ni_is_pref) {
1742                         preferred = true;
1743                 } else if (preferred && !ni_is_pref) {
1744                         /*
1745                          * this is not the preferred peer so let's ignore
1746                          * it.
1747                          */
1748                         continue;
1749                 } else if (lpni->lpni_txcredits < best_lpni_credits) {
1750                         /*
1751                          * We already have a peer that has more credits
1752                          * available than this one. No need to consider
1753                          * this peer further.
1754                          */
1755                         continue;
1756                 } else if (lpni->lpni_txcredits == best_lpni_credits) {
1757                         /*
1758                          * The best peer found so far and the current peer
1759                          * have the same number of available credits let's
1760                          * make sure to select between them using Round
1761                          * Robin
1762                          */
1763                         if (best_lpni) {
1764                                 if (best_lpni->lpni_seq <= lpni->lpni_seq)
1765                                         continue;
1766                         }
1767                 }
1768
1769                 best_lpni = lpni;
1770                 best_lpni_credits = lpni->lpni_txcredits;
1771         }
1772
1773         /* if we still can't find a peer ni then we can't reach it */
1774         if (!best_lpni) {
1775                 __u32 net_id = (peer_net) ? peer_net->lpn_net_id :
1776                         LNET_NIDNET(dst_nid);
1777                 CDEBUG(D_NET, "no peer_ni found on peer net %s\n",
1778                                 libcfs_net2str(net_id));
1779                 return NULL;
1780         }
1781
1782         CDEBUG(D_NET, "sd_best_lpni = %s\n",
1783                libcfs_nid2str(best_lpni->lpni_nid));
1784
1785         return best_lpni;
1786 }
1787
1788 /*
1789  * Prerequisite: the best_ni should already be set in the sd
1790  */
1791 static inline struct lnet_peer_ni *
1792 lnet_find_best_lpni_on_net(struct lnet_send_data *sd, struct lnet_peer *peer,
1793                            __u32 net_id)
1794 {
1795         struct lnet_peer_net *peer_net;
1796
1797         /*
1798          * The gateway is Multi-Rail capable so now we must select the
1799          * proper peer_ni
1800          */
1801         peer_net = lnet_peer_get_net_locked(peer, net_id);
1802
1803         if (!peer_net) {
1804                 CERROR("gateway peer %s has no NI on net %s\n",
1805                        libcfs_nid2str(peer->lp_primary_nid),
1806                        libcfs_net2str(net_id));
1807                 return NULL;
1808         }
1809
1810         return lnet_select_peer_ni(sd, peer, peer_net);
1811 }
1812
1813 static inline void
1814 lnet_set_non_mr_pref_nid(struct lnet_send_data *sd)
1815 {
1816         if (sd->sd_send_case & NMR_DST &&
1817             sd->sd_msg->msg_type != LNET_MSG_REPLY &&
1818             sd->sd_msg->msg_type != LNET_MSG_ACK &&
1819             sd->sd_best_lpni->lpni_pref_nnids == 0) {
1820                 CDEBUG(D_NET, "Setting preferred local NID %s on NMR peer %s\n",
1821                        libcfs_nid2str(sd->sd_best_ni->ni_nid),
1822                        libcfs_nid2str(sd->sd_best_lpni->lpni_nid));
1823                 lnet_peer_ni_set_non_mr_pref_nid(sd->sd_best_lpni,
1824                                                  sd->sd_best_ni->ni_nid);
1825         }
1826 }
1827
1828 /*
1829  * Source Specified
1830  * Local Destination
1831  * non-mr peer
1832  *
1833  * use the source and destination NIDs as the pathway
1834  */
1835 static int
1836 lnet_handle_spec_local_nmr_dst(struct lnet_send_data *sd)
1837 {
1838         /* the destination lpni is set before we get here. */
1839
1840         /* find local NI */
1841         sd->sd_best_ni = lnet_nid2ni_locked(sd->sd_src_nid, sd->sd_cpt);
1842         if (!sd->sd_best_ni) {
1843                 CERROR("Can't send to %s: src %s is not a "
1844                        "local nid\n", libcfs_nid2str(sd->sd_dst_nid),
1845                                 libcfs_nid2str(sd->sd_src_nid));
1846                 return -EINVAL;
1847         }
1848
1849         /*
1850          * the preferred NID will only be set for NMR peers
1851          */
1852         lnet_set_non_mr_pref_nid(sd);
1853
1854         return lnet_handle_send(sd);
1855 }
1856
1857 /*
1858  * Source Specified
1859  * Local Destination
1860  * MR Peer
1861  *
1862  * Run the selection algorithm on the peer NIs unless we're sending
1863  * a response, in this case just send to the destination
1864  */
1865 static int
1866 lnet_handle_spec_local_mr_dst(struct lnet_send_data *sd)
1867 {
1868         sd->sd_best_ni = lnet_nid2ni_locked(sd->sd_src_nid, sd->sd_cpt);
1869         if (!sd->sd_best_ni) {
1870                 CERROR("Can't send to %s: src %s is not a "
1871                        "local nid\n", libcfs_nid2str(sd->sd_dst_nid),
1872                                 libcfs_nid2str(sd->sd_src_nid));
1873                 return -EINVAL;
1874         }
1875
1876         /*
1877          * only run the selection algorithm to pick the peer_ni if we're
1878          * sending a GET or a PUT. Responses are sent to the same
1879          * destination NID provided.
1880          */
1881         if (!(sd->sd_send_case & SND_RESP)) {
1882                 sd->sd_best_lpni =
1883                   lnet_find_best_lpni_on_net(sd, sd->sd_peer,
1884                                              sd->sd_best_ni->ni_net->net_id);
1885         }
1886
1887         if (sd->sd_best_lpni)
1888                 return lnet_handle_send(sd);
1889
1890         CERROR("can't send to %s. no NI on %s\n",
1891                libcfs_nid2str(sd->sd_dst_nid),
1892                libcfs_net2str(sd->sd_best_ni->ni_net->net_id));
1893
1894         return -EHOSTUNREACH;
1895 }
1896
1897 struct lnet_ni *
1898 lnet_find_best_ni_on_spec_net(struct lnet_ni *cur_best_ni,
1899                               struct lnet_peer *peer,
1900                               struct lnet_peer_net *peer_net,
1901                               int cpt,
1902                               bool incr_seq)
1903 {
1904         struct lnet_net *local_net;
1905         struct lnet_ni *best_ni;
1906
1907         local_net = lnet_get_net_locked(peer_net->lpn_net_id);
1908         if (!local_net)
1909                 return NULL;
1910
1911         /*
1912          * Iterate through the NIs in this local Net and select
1913          * the NI to send from. The selection is determined by
1914          * these 3 criterion in the following priority:
1915          *      1. NUMA
1916          *      2. NI available credits
1917          *      3. Round Robin
1918          */
1919         best_ni = lnet_get_best_ni(local_net, cur_best_ni,
1920                                    peer, peer_net, cpt);
1921
1922         if (incr_seq && best_ni)
1923                 best_ni->ni_seq++;
1924
1925         return best_ni;
1926 }
1927
1928 static int
1929 lnet_handle_find_routed_path(struct lnet_send_data *sd,
1930                              lnet_nid_t dst_nid,
1931                              struct lnet_peer_ni **gw_lpni,
1932                              struct lnet_peer **gw_peer)
1933 {
1934         struct lnet_peer_ni *gw;
1935         lnet_nid_t src_nid = sd->sd_src_nid;
1936
1937         gw = lnet_find_route_locked(NULL, LNET_NIDNET(dst_nid),
1938                                     sd->sd_rtr_nid);
1939         if (!gw) {
1940                 CERROR("no route to %s from %s\n",
1941                        libcfs_nid2str(dst_nid), libcfs_nid2str(src_nid));
1942                 return -EHOSTUNREACH;
1943         }
1944
1945         /* get the peer of the gw_ni */
1946         LASSERT(gw->lpni_peer_net);
1947         LASSERT(gw->lpni_peer_net->lpn_peer);
1948
1949         *gw_peer = gw->lpni_peer_net->lpn_peer;
1950
1951         if (!sd->sd_best_ni)
1952                 sd->sd_best_ni = lnet_find_best_ni_on_spec_net(NULL, *gw_peer,
1953                                         gw->lpni_peer_net,
1954                                         sd->sd_md_cpt,
1955                                         true);
1956
1957         if (!sd->sd_best_ni) {
1958                 CERROR("Internal Error. Expected local ni on %s "
1959                        "but non found :%s\n",
1960                        libcfs_net2str(gw->lpni_peer_net->lpn_net_id),
1961                        libcfs_nid2str(sd->sd_src_nid));
1962                 return -EFAULT;
1963         }
1964
1965         /*
1966          * if gw is MR let's find its best peer_ni
1967          */
1968         if (lnet_peer_is_multi_rail(*gw_peer)) {
1969                 gw = lnet_find_best_lpni_on_net(sd, *gw_peer,
1970                                                 sd->sd_best_ni->ni_net->net_id);
1971                 /*
1972                  * We've already verified that the gw has an NI on that
1973                  * desired net, but we're not finding it. Something is
1974                  * wrong.
1975                  */
1976                 if (!gw) {
1977                         CERROR("Internal Error. Route expected to %s from %s\n",
1978                                 libcfs_nid2str(dst_nid),
1979                                 libcfs_nid2str(src_nid));
1980                         return -EFAULT;
1981                 }
1982         }
1983
1984         *gw_lpni = gw;
1985
1986         return 0;
1987 }
1988
1989 /*
1990  * Handle two cases:
1991  *
1992  * Case 1:
1993  *  Source specified
1994  *  Remote destination
1995  *  Non-MR destination
1996  *
1997  * Case 2:
1998  *  Source specified
1999  *  Remote destination
2000  *  MR destination
2001  *
2002  * The handling of these two cases is similar. Even though the destination
2003  * can be MR or non-MR, we'll deal directly with the router.
2004  */
2005 static int
2006 lnet_handle_spec_router_dst(struct lnet_send_data *sd)
2007 {
2008         int rc;
2009         struct lnet_peer_ni *gw_lpni = NULL;
2010         struct lnet_peer *gw_peer = NULL;
2011
2012         /* find local NI */
2013         sd->sd_best_ni = lnet_nid2ni_locked(sd->sd_src_nid, sd->sd_cpt);
2014         if (!sd->sd_best_ni) {
2015                 CERROR("Can't send to %s: src %s is not a "
2016                        "local nid\n", libcfs_nid2str(sd->sd_dst_nid),
2017                                 libcfs_nid2str(sd->sd_src_nid));
2018                 return -EINVAL;
2019         }
2020
2021         rc = lnet_handle_find_routed_path(sd, sd->sd_dst_nid, &gw_lpni,
2022                                      &gw_peer);
2023         if (rc < 0)
2024                 return rc;
2025
2026         if (sd->sd_send_case & NMR_DST)
2027                 /*
2028                 * since the final destination is non-MR let's set its preferred
2029                 * NID before we send
2030                 */
2031                 lnet_set_non_mr_pref_nid(sd);
2032
2033         /*
2034          * We're going to send to the gw found so let's set its
2035          * info
2036          */
2037         sd->sd_peer = gw_peer;
2038         sd->sd_best_lpni = gw_lpni;
2039
2040         return lnet_handle_send(sd);
2041 }
2042
2043 struct lnet_ni *
2044 lnet_find_best_ni_on_local_net(struct lnet_peer *peer, int md_cpt)
2045 {
2046         struct lnet_peer_net *peer_net = NULL;
2047         struct lnet_ni *best_ni = NULL;
2048
2049         /*
2050          * The peer can have multiple interfaces, some of them can be on
2051          * the local network and others on a routed network. We should
2052          * prefer the local network. However if the local network is not
2053          * available then we need to try the routed network
2054          */
2055
2056         /* go through all the peer nets and find the best_ni */
2057         list_for_each_entry(peer_net, &peer->lp_peer_nets, lpn_peer_nets) {
2058                 /*
2059                  * The peer's list of nets can contain non-local nets. We
2060                  * want to only examine the local ones.
2061                  */
2062                 if (!lnet_get_net_locked(peer_net->lpn_net_id))
2063                         continue;
2064                 best_ni = lnet_find_best_ni_on_spec_net(best_ni, peer,
2065                                                    peer_net, md_cpt, false);
2066         }
2067
2068         if (best_ni)
2069                 /* increment sequence number so we can round robin */
2070                 best_ni->ni_seq++;
2071
2072         return best_ni;
2073 }
2074
2075 static struct lnet_ni *
2076 lnet_find_existing_preferred_best_ni(struct lnet_send_data *sd)
2077 {
2078         struct lnet_ni *best_ni = NULL;
2079         struct lnet_peer_net *peer_net;
2080         struct lnet_peer *peer = sd->sd_peer;
2081         struct lnet_peer_ni *best_lpni = sd->sd_best_lpni;
2082         struct lnet_peer_ni *lpni;
2083         int cpt = sd->sd_cpt;
2084
2085         /*
2086          * We must use a consistent source address when sending to a
2087          * non-MR peer. However, a non-MR peer can have multiple NIDs
2088          * on multiple networks, and we may even need to talk to this
2089          * peer on multiple networks -- certain types of
2090          * load-balancing configuration do this.
2091          *
2092          * So we need to pick the NI the peer prefers for this
2093          * particular network.
2094          */
2095
2096         /* Get the target peer_ni */
2097         peer_net = lnet_peer_get_net_locked(peer,
2098                         LNET_NIDNET(best_lpni->lpni_nid));
2099         LASSERT(peer_net != NULL);
2100         list_for_each_entry(lpni, &peer_net->lpn_peer_nis,
2101                                 lpni_peer_nis) {
2102                 if (lpni->lpni_pref_nnids == 0)
2103                         continue;
2104                 LASSERT(lpni->lpni_pref_nnids == 1);
2105                 best_ni = lnet_nid2ni_locked(
2106                                 lpni->lpni_pref.nid, cpt);
2107                 break;
2108         }
2109
2110         return best_ni;
2111 }
2112
2113 /* Prerequisite: sd->sd_peer and sd->sd_best_lpni should be set */
2114 static int
2115 lnet_select_preferred_best_ni(struct lnet_send_data *sd)
2116 {
2117         struct lnet_ni *best_ni = NULL;
2118         struct lnet_peer_ni *best_lpni = sd->sd_best_lpni;
2119
2120         /*
2121          * We must use a consistent source address when sending to a
2122          * non-MR peer. However, a non-MR peer can have multiple NIDs
2123          * on multiple networks, and we may even need to talk to this
2124          * peer on multiple networks -- certain types of
2125          * load-balancing configuration do this.
2126          *
2127          * So we need to pick the NI the peer prefers for this
2128          * particular network.
2129          */
2130
2131         best_ni = lnet_find_existing_preferred_best_ni(sd);
2132
2133         /* if best_ni is still not set just pick one */
2134         if (!best_ni) {
2135                 best_ni =
2136                   lnet_find_best_ni_on_spec_net(NULL, sd->sd_peer,
2137                                                 sd->sd_best_lpni->lpni_peer_net,
2138                                                 sd->sd_md_cpt, true);
2139                 /* If there is no best_ni we don't have a route */
2140                 if (!best_ni) {
2141                         CERROR("no path to %s from net %s\n",
2142                                 libcfs_nid2str(best_lpni->lpni_nid),
2143                                 libcfs_net2str(best_lpni->lpni_net->net_id));
2144                         return -EHOSTUNREACH;
2145                 }
2146         }
2147
2148         sd->sd_best_ni = best_ni;
2149
2150         /* Set preferred NI if necessary. */
2151         lnet_set_non_mr_pref_nid(sd);
2152
2153         return 0;
2154 }
2155
2156
2157 /*
2158  * Source not specified
2159  * Local destination
2160  * Non-MR Peer
2161  *
2162  * always use the same source NID for NMR peers
2163  * If we've talked to that peer before then we already have a preferred
2164  * source NI associated with it. Otherwise, we select a preferred local NI
2165  * and store it in the peer
2166  */
2167 static int
2168 lnet_handle_any_local_nmr_dst(struct lnet_send_data *sd)
2169 {
2170         int rc;
2171
2172         /* sd->sd_best_lpni is already set to the final destination */
2173
2174         /*
2175          * At this point we should've created the peer ni and peer. If we
2176          * can't find it, then something went wrong. Instead of assert
2177          * output a relevant message and fail the send
2178          */
2179         if (!sd->sd_best_lpni) {
2180                 CERROR("Internal fault. Unable to send msg %s to %s. "
2181                        "NID not known\n",
2182                        lnet_msgtyp2str(sd->sd_msg->msg_type),
2183                        libcfs_nid2str(sd->sd_dst_nid));
2184                 return -EFAULT;
2185         }
2186
2187         rc = lnet_select_preferred_best_ni(sd);
2188         if (!rc)
2189                 rc = lnet_handle_send(sd);
2190
2191         return rc;
2192 }
2193
2194 static int
2195 lnet_handle_any_mr_dsta(struct lnet_send_data *sd)
2196 {
2197         /*
2198          * NOTE we've already handled the remote peer case. So we only
2199          * need to worry about the local case here.
2200          *
2201          * if we're sending a response, ACK or reply, we need to send it
2202          * to the destination NID given to us. At this point we already
2203          * have the peer_ni we're suppose to send to, so just find the
2204          * best_ni on the peer net and use that. Since we're sending to an
2205          * MR peer then we can just run the selection algorithm on our
2206          * local NIs and pick the best one.
2207          */
2208         if (sd->sd_send_case & SND_RESP) {
2209                 sd->sd_best_ni =
2210                   lnet_find_best_ni_on_spec_net(NULL, sd->sd_peer,
2211                                                 sd->sd_best_lpni->lpni_peer_net,
2212                                                 sd->sd_md_cpt, true);
2213
2214                 if (!sd->sd_best_ni) {
2215                         /*
2216                          * We're not going to deal with not able to send
2217                          * a response to the provided final destination
2218                          */
2219                         CERROR("Can't send response to %s. "
2220                                "No local NI available\n",
2221                                 libcfs_nid2str(sd->sd_dst_nid));
2222                         return -EHOSTUNREACH;
2223                 }
2224
2225                 return lnet_handle_send(sd);
2226         }
2227
2228         /*
2229          * If we get here that means we're sending a fresh request, PUT or
2230          * GET, so we need to run our standard selection algorithm.
2231          * First find the best local interface that's on any of the peer's
2232          * networks.
2233          */
2234         sd->sd_best_ni = lnet_find_best_ni_on_local_net(sd->sd_peer,
2235                                                         sd->sd_md_cpt);
2236         if (sd->sd_best_ni) {
2237                 sd->sd_best_lpni =
2238                   lnet_find_best_lpni_on_net(sd, sd->sd_peer,
2239                                              sd->sd_best_ni->ni_net->net_id);
2240
2241                 /*
2242                  * if we're successful in selecting a peer_ni on the local
2243                  * network, then send to it. Otherwise fall through and
2244                  * try and see if we can reach it over another routed
2245                  * network
2246                  */
2247                 if (sd->sd_best_lpni) {
2248                         /*
2249                          * in case we initially started with a routed
2250                          * destination, let's reset to local
2251                          */
2252                         sd->sd_send_case &= ~REMOTE_DST;
2253                         sd->sd_send_case |= LOCAL_DST;
2254                         return lnet_handle_send(sd);
2255                 }
2256
2257                 CERROR("Internal Error. Expected to have a best_lpni: "
2258                        "%s -> %s\n",
2259                        libcfs_nid2str(sd->sd_src_nid),
2260                        libcfs_nid2str(sd->sd_dst_nid));
2261
2262                 return -EFAULT;
2263         }
2264
2265         /*
2266          * Peer doesn't have a local network. Let's see if there is
2267          * a remote network we can reach it on.
2268          */
2269         return PASS_THROUGH;
2270 }
2271
2272 /*
2273  * Case 1:
2274  *      Source NID not specified
2275  *      Local destination
2276  *      MR peer
2277  *
2278  * Case 2:
2279  *      Source NID not speified
2280  *      Remote destination
2281  *      MR peer
2282  *
2283  * In both of these cases if we're sending a response, ACK or REPLY, then
2284  * we need to send to the destination NID provided.
2285  *
2286  * In the remote case let's deal with MR routers.
2287  *
2288  */
2289
2290 static int
2291 lnet_handle_any_mr_dst(struct lnet_send_data *sd)
2292 {
2293         int rc = 0;
2294         struct lnet_peer *gw_peer = NULL;
2295         struct lnet_peer_ni *gw_lpni = NULL;
2296
2297         /*
2298          * handle sending a response to a remote peer here so we don't
2299          * have to worry about it if we hit lnet_handle_any_mr_dsta()
2300          */
2301         if (sd->sd_send_case & REMOTE_DST &&
2302             sd->sd_send_case & SND_RESP) {
2303                 struct lnet_peer_ni *gw;
2304                 struct lnet_peer *gw_peer;
2305
2306                 rc = lnet_handle_find_routed_path(sd, sd->sd_dst_nid, &gw,
2307                                                   &gw_peer);
2308                 if (rc < 0) {
2309                         CERROR("Can't send response to %s. "
2310                                "No route available\n",
2311                                 libcfs_nid2str(sd->sd_dst_nid));
2312                         return -EHOSTUNREACH;
2313                 }
2314
2315                 sd->sd_best_lpni = gw;
2316                 sd->sd_peer = gw_peer;
2317
2318                 return lnet_handle_send(sd);
2319         }
2320
2321         /*
2322          * Even though the NID for the peer might not be on a local network,
2323          * since the peer is MR there could be other interfaces on the
2324          * local network. In that case we'd still like to prefer the local
2325          * network over the routed network. If we're unable to do that
2326          * then we select the best router among the different routed networks,
2327          * and if the router is MR then we can deal with it as such.
2328          */
2329         rc = lnet_handle_any_mr_dsta(sd);
2330         if (rc != PASS_THROUGH)
2331                 return rc;
2332
2333         /*
2334          * TODO; One possible enhancement is to run the selection
2335          * algorithm on the peer. However for remote peers the credits are
2336          * not decremented, so we'll be basically going over the peer NIs
2337          * in round robin. An MR router will run the selection algorithm
2338          * on the next-hop interfaces.
2339          */
2340         rc = lnet_handle_find_routed_path(sd, sd->sd_dst_nid, &gw_lpni,
2341                                           &gw_peer);
2342         if (rc < 0)
2343                 return rc;
2344
2345         sd->sd_send_case &= ~LOCAL_DST;
2346         sd->sd_send_case |= REMOTE_DST;
2347
2348         sd->sd_peer = gw_peer;
2349         sd->sd_best_lpni = gw_lpni;
2350
2351         return lnet_handle_send(sd);
2352 }
2353
2354 /*
2355  * Source not specified
2356  * Remote destination
2357  * Non-MR peer
2358  *
2359  * Must send to the specified peer NID using the same source NID that
2360  * we've used before. If it's the first time to talk to that peer then
2361  * find the source NI and assign it as preferred to that peer
2362  */
2363 static int
2364 lnet_handle_any_router_nmr_dst(struct lnet_send_data *sd)
2365 {
2366         int rc;
2367         struct lnet_peer_ni *gw_lpni = NULL;
2368         struct lnet_peer *gw_peer = NULL;
2369
2370         /*
2371          * Let's set if we have a preferred NI to talk to this NMR peer
2372          */
2373         sd->sd_best_ni = lnet_find_existing_preferred_best_ni(sd);
2374
2375         /*
2376          * find the router and that'll find the best NI if we didn't find
2377          * it already.
2378          */
2379         rc = lnet_handle_find_routed_path(sd, sd->sd_dst_nid, &gw_lpni,
2380                                           &gw_peer);
2381         if (rc < 0)
2382                 return rc;
2383
2384         /*
2385          * set the best_ni we've chosen as the preferred one for
2386          * this peer
2387          */
2388         lnet_set_non_mr_pref_nid(sd);
2389
2390         /* we'll be sending to the gw */
2391         sd->sd_best_lpni = gw_lpni;
2392         sd->sd_peer = gw_peer;
2393
2394         return lnet_handle_send(sd);
2395 }
2396
2397 static int
2398 lnet_handle_send_case_locked(struct lnet_send_data *sd)
2399 {
2400         /*
2401          * turn off the SND_RESP bit.
2402          * It will be checked in the case handling
2403          */
2404         __u32 send_case = sd->sd_send_case &= ~SND_RESP ;
2405
2406         CDEBUG(D_NET, "Source %s%s to %s %s %s destination\n",
2407                 (send_case & SRC_SPEC) ? "Specified: " : "ANY",
2408                 (send_case & SRC_SPEC) ? libcfs_nid2str(sd->sd_src_nid) : "",
2409                 (send_case & MR_DST) ? "MR: " : "NMR: ",
2410                 libcfs_nid2str(sd->sd_dst_nid),
2411                 (send_case & LOCAL_DST) ? "local" : "routed");
2412
2413         switch (send_case) {
2414         /*
2415          * For all cases where the source is specified, we should always
2416          * use the destination NID, whether it's an MR destination or not,
2417          * since we're continuing a series of related messages for the
2418          * same RPC
2419          */
2420         case SRC_SPEC_LOCAL_NMR_DST:
2421                 return lnet_handle_spec_local_nmr_dst(sd);
2422         case SRC_SPEC_LOCAL_MR_DST:
2423                 return lnet_handle_spec_local_mr_dst(sd);
2424         case SRC_SPEC_ROUTER_NMR_DST:
2425         case SRC_SPEC_ROUTER_MR_DST:
2426                 return lnet_handle_spec_router_dst(sd);
2427         case SRC_ANY_LOCAL_NMR_DST:
2428                 return lnet_handle_any_local_nmr_dst(sd);
2429         case SRC_ANY_LOCAL_MR_DST:
2430         case SRC_ANY_ROUTER_MR_DST:
2431                 return lnet_handle_any_mr_dst(sd);
2432         case SRC_ANY_ROUTER_NMR_DST:
2433                 return lnet_handle_any_router_nmr_dst(sd);
2434         default:
2435                 CERROR("Unknown send case\n");
2436                 return -1;
2437         }
2438 }
2439
2440 static int
2441 lnet_select_pathway(lnet_nid_t src_nid, lnet_nid_t dst_nid,
2442                     struct lnet_msg *msg, lnet_nid_t rtr_nid)
2443 {
2444         struct lnet_peer_ni     *lpni;
2445         struct lnet_peer        *peer;
2446         struct lnet_send_data   send_data;
2447         int                     cpt, rc;
2448         int                     md_cpt;
2449         __u32                   send_case = 0;
2450
2451         memset(&send_data, 0, sizeof(send_data));
2452
2453         /*
2454          * get an initial CPT to use for locking. The idea here is not to
2455          * serialize the calls to select_pathway, so that as many
2456          * operations can run concurrently as possible. To do that we use
2457          * the CPT where this call is being executed. Later on when we
2458          * determine the CPT to use in lnet_message_commit, we switch the
2459          * lock and check if there was any configuration change.  If none,
2460          * then we proceed, if there is, then we restart the operation.
2461          */
2462         cpt = lnet_net_lock_current();
2463
2464         md_cpt = lnet_cpt_of_md(msg->msg_md, msg->msg_offset);
2465         if (md_cpt == CFS_CPT_ANY)
2466                 md_cpt = cpt;
2467
2468 again:
2469
2470         /*
2471          * If we're being asked to send to the loopback interface, there
2472          * is no need to go through any selection. We can just shortcut
2473          * the entire process and send over lolnd
2474          */
2475         if (LNET_NETTYP(LNET_NIDNET(dst_nid)) == LOLND) {
2476                 /* No send credit hassles with LOLND */
2477                 lnet_ni_addref_locked(the_lnet.ln_loni, cpt);
2478                 msg->msg_hdr.dest_nid = cpu_to_le64(the_lnet.ln_loni->ni_nid);
2479                 if (!msg->msg_routing)
2480                         msg->msg_hdr.src_nid =
2481                                 cpu_to_le64(the_lnet.ln_loni->ni_nid);
2482                 msg->msg_target.nid = the_lnet.ln_loni->ni_nid;
2483                 lnet_msg_commit(msg, cpt);
2484                 msg->msg_txni = the_lnet.ln_loni;
2485                 lnet_net_unlock(cpt);
2486
2487                 return LNET_CREDIT_OK;
2488         }
2489
2490         /*
2491          * find an existing peer_ni, or create one and mark it as having been
2492          * created due to network traffic. This call will create the
2493          * peer->peer_net->peer_ni tree.
2494          */
2495         lpni = lnet_nid2peerni_locked(dst_nid, LNET_NID_ANY, cpt);
2496         if (IS_ERR(lpni)) {
2497                 lnet_net_unlock(cpt);
2498                 return PTR_ERR(lpni);
2499         }
2500
2501         /*
2502          * Now that we have a peer_ni, check if we want to discover
2503          * the peer. Traffic to the LNET_RESERVED_PORTAL should not
2504          * trigger discovery.
2505          */
2506         peer = lpni->lpni_peer_net->lpn_peer;
2507         if (lnet_msg_discovery(msg) && !lnet_peer_is_uptodate(peer)) {
2508                 lnet_nid_t primary_nid;
2509                 rc = lnet_discover_peer_locked(lpni, cpt, false);
2510                 if (rc) {
2511                         lnet_peer_ni_decref_locked(lpni);
2512                         lnet_net_unlock(cpt);
2513                         return rc;
2514                 }
2515                 /* The peer may have changed. */
2516                 peer = lpni->lpni_peer_net->lpn_peer;
2517                 /* queue message and return */
2518                 msg->msg_src_nid_param = src_nid;
2519                 msg->msg_rtr_nid_param = rtr_nid;
2520                 msg->msg_sending = 0;
2521                 list_add_tail(&msg->msg_list, &peer->lp_dc_pendq);
2522                 lnet_peer_ni_decref_locked(lpni);
2523                 primary_nid = peer->lp_primary_nid;
2524                 lnet_net_unlock(cpt);
2525
2526                 CDEBUG(D_NET, "%s pending discovery\n",
2527                        libcfs_nid2str(primary_nid));
2528
2529                 return LNET_DC_WAIT;
2530         }
2531         lnet_peer_ni_decref_locked(lpni);
2532
2533         /* If peer is not healthy then can not send anything to it */
2534         if (!lnet_is_peer_healthy_locked(peer)) {
2535                 lnet_net_unlock(cpt);
2536                 return -EHOSTUNREACH;
2537         }
2538
2539         /*
2540          * Identify the different send cases
2541          */
2542         if (src_nid == LNET_NID_ANY)
2543                 send_case |= SRC_ANY;
2544         else
2545                 send_case |= SRC_SPEC;
2546
2547         if (lnet_get_net_locked(LNET_NIDNET(dst_nid)))
2548                 send_case |= LOCAL_DST;
2549         else
2550                 send_case |= REMOTE_DST;
2551
2552         if (!lnet_peer_is_multi_rail(peer))
2553                 send_case |= NMR_DST;
2554         else
2555                 send_case |= MR_DST;
2556
2557         if (msg->msg_type == LNET_MSG_REPLY ||
2558             msg->msg_type == LNET_MSG_ACK)
2559                 send_case |= SND_RESP;
2560
2561         /* assign parameters to the send_data */
2562         send_data.sd_msg = msg;
2563         send_data.sd_rtr_nid = rtr_nid;
2564         send_data.sd_src_nid = src_nid;
2565         send_data.sd_dst_nid = dst_nid;
2566         send_data.sd_best_lpni = lpni;
2567         /*
2568          * keep a pointer to the final destination in case we're going to
2569          * route, so we'll need to access it later
2570          */
2571         send_data.sd_final_dst_lpni = lpni;
2572         send_data.sd_peer = peer;
2573         send_data.sd_md_cpt = md_cpt;
2574         send_data.sd_cpt = cpt;
2575         send_data.sd_send_case = send_case;
2576
2577         rc = lnet_handle_send_case_locked(&send_data);
2578
2579         if (rc == REPEAT_SEND)
2580                 goto again;
2581
2582         lnet_net_unlock(send_data.sd_cpt);
2583
2584         return rc;
2585 }
2586
2587 int
2588 lnet_send(lnet_nid_t src_nid, struct lnet_msg *msg, lnet_nid_t rtr_nid)
2589 {
2590         lnet_nid_t              dst_nid = msg->msg_target.nid;
2591         int                     rc;
2592
2593         /*
2594          * NB: rtr_nid is set to LNET_NID_ANY for all current use-cases,
2595          * but we might want to use pre-determined router for ACK/REPLY
2596          * in the future
2597          */
2598         /* NB: ni != NULL == interface pre-determined (ACK/REPLY) */
2599         LASSERT (msg->msg_txpeer == NULL);
2600         LASSERT (!msg->msg_sending);
2601         LASSERT (!msg->msg_target_is_router);
2602         LASSERT (!msg->msg_receiving);
2603
2604         msg->msg_sending = 1;
2605
2606         LASSERT(!msg->msg_tx_committed);
2607
2608         rc = lnet_select_pathway(src_nid, dst_nid, msg, rtr_nid);
2609         if (rc < 0)
2610                 return rc;
2611
2612         if (rc == LNET_CREDIT_OK)
2613                 lnet_ni_send(msg->msg_txni, msg);
2614
2615         /* rc == LNET_CREDIT_OK or LNET_CREDIT_WAIT or LNET_DC_WAIT */
2616         return 0;
2617 }
2618
2619 void
2620 lnet_drop_message(struct lnet_ni *ni, int cpt, void *private, unsigned int nob,
2621                   __u32 msg_type)
2622 {
2623         lnet_net_lock(cpt);
2624         lnet_incr_stats(&ni->ni_stats, msg_type, LNET_STATS_TYPE_DROP);
2625         the_lnet.ln_counters[cpt]->drop_count++;
2626         the_lnet.ln_counters[cpt]->drop_length += nob;
2627         lnet_net_unlock(cpt);
2628
2629         lnet_ni_recv(ni, private, NULL, 0, 0, 0, nob);
2630 }
2631
2632 static void
2633 lnet_recv_put(struct lnet_ni *ni, struct lnet_msg *msg)
2634 {
2635         struct lnet_hdr *hdr = &msg->msg_hdr;
2636
2637         if (msg->msg_wanted != 0)
2638                 lnet_setpayloadbuffer(msg);
2639
2640         lnet_build_msg_event(msg, LNET_EVENT_PUT);
2641
2642         /* Must I ACK?  If so I'll grab the ack_wmd out of the header and put
2643          * it back into the ACK during lnet_finalize() */
2644         msg->msg_ack = (!lnet_is_wire_handle_none(&hdr->msg.put.ack_wmd) &&
2645                         (msg->msg_md->md_options & LNET_MD_ACK_DISABLE) == 0);
2646
2647         lnet_ni_recv(ni, msg->msg_private, msg, msg->msg_rx_delayed,
2648                      msg->msg_offset, msg->msg_wanted, hdr->payload_length);
2649 }
2650
2651 static int
2652 lnet_parse_put(struct lnet_ni *ni, struct lnet_msg *msg)
2653 {
2654         struct lnet_hdr         *hdr = &msg->msg_hdr;
2655         struct lnet_match_info  info;
2656         int                     rc;
2657         bool                    ready_delay;
2658
2659         /* Convert put fields to host byte order */
2660         hdr->msg.put.match_bits = le64_to_cpu(hdr->msg.put.match_bits);
2661         hdr->msg.put.ptl_index  = le32_to_cpu(hdr->msg.put.ptl_index);
2662         hdr->msg.put.offset     = le32_to_cpu(hdr->msg.put.offset);
2663
2664         /* Primary peer NID. */
2665         info.mi_id.nid  = msg->msg_initiator;
2666         info.mi_id.pid  = hdr->src_pid;
2667         info.mi_opc     = LNET_MD_OP_PUT;
2668         info.mi_portal  = hdr->msg.put.ptl_index;
2669         info.mi_rlength = hdr->payload_length;
2670         info.mi_roffset = hdr->msg.put.offset;
2671         info.mi_mbits   = hdr->msg.put.match_bits;
2672         info.mi_cpt     = lnet_cpt_of_nid(msg->msg_rxpeer->lpni_nid, ni);
2673
2674         msg->msg_rx_ready_delay = ni->ni_net->net_lnd->lnd_eager_recv == NULL;
2675         ready_delay = msg->msg_rx_ready_delay;
2676
2677  again:
2678         rc = lnet_ptl_match_md(&info, msg);
2679         switch (rc) {
2680         default:
2681                 LBUG();
2682
2683         case LNET_MATCHMD_OK:
2684                 lnet_recv_put(ni, msg);
2685                 return 0;
2686
2687         case LNET_MATCHMD_NONE:
2688                 if (ready_delay)
2689                         /* no eager_recv or has already called it, should
2690                          * have been attached on delayed list */
2691                         return 0;
2692
2693                 rc = lnet_ni_eager_recv(ni, msg);
2694                 if (rc == 0) {
2695                         ready_delay = true;
2696                         goto again;
2697                 }
2698                 /* fall through */
2699
2700         case LNET_MATCHMD_DROP:
2701                 CNETERR("Dropping PUT from %s portal %d match %llu"
2702                         " offset %d length %d: %d\n",
2703                         libcfs_id2str(info.mi_id), info.mi_portal,
2704                         info.mi_mbits, info.mi_roffset, info.mi_rlength, rc);
2705
2706                 return -ENOENT; /* -ve: OK but no match */
2707         }
2708 }
2709
2710 static int
2711 lnet_parse_get(struct lnet_ni *ni, struct lnet_msg *msg, int rdma_get)
2712 {
2713         struct lnet_match_info info;
2714         struct lnet_hdr *hdr = &msg->msg_hdr;
2715         struct lnet_process_id source_id;
2716         struct lnet_handle_wire reply_wmd;
2717         int rc;
2718
2719         /* Convert get fields to host byte order */
2720         hdr->msg.get.match_bits   = le64_to_cpu(hdr->msg.get.match_bits);
2721         hdr->msg.get.ptl_index    = le32_to_cpu(hdr->msg.get.ptl_index);
2722         hdr->msg.get.sink_length  = le32_to_cpu(hdr->msg.get.sink_length);
2723         hdr->msg.get.src_offset   = le32_to_cpu(hdr->msg.get.src_offset);
2724
2725         source_id.nid = hdr->src_nid;
2726         source_id.pid = hdr->src_pid;
2727         /* Primary peer NID */
2728         info.mi_id.nid  = msg->msg_initiator;
2729         info.mi_id.pid  = hdr->src_pid;
2730         info.mi_opc     = LNET_MD_OP_GET;
2731         info.mi_portal  = hdr->msg.get.ptl_index;
2732         info.mi_rlength = hdr->msg.get.sink_length;
2733         info.mi_roffset = hdr->msg.get.src_offset;
2734         info.mi_mbits   = hdr->msg.get.match_bits;
2735         info.mi_cpt     = lnet_cpt_of_nid(msg->msg_rxpeer->lpni_nid, ni);
2736
2737         rc = lnet_ptl_match_md(&info, msg);
2738         if (rc == LNET_MATCHMD_DROP) {
2739                 CNETERR("Dropping GET from %s portal %d match %llu"
2740                         " offset %d length %d\n",
2741                         libcfs_id2str(info.mi_id), info.mi_portal,
2742                         info.mi_mbits, info.mi_roffset, info.mi_rlength);
2743                 return -ENOENT; /* -ve: OK but no match */
2744         }
2745
2746         LASSERT(rc == LNET_MATCHMD_OK);
2747
2748         lnet_build_msg_event(msg, LNET_EVENT_GET);
2749
2750         reply_wmd = hdr->msg.get.return_wmd;
2751
2752         lnet_prep_send(msg, LNET_MSG_REPLY, source_id,
2753                        msg->msg_offset, msg->msg_wanted);
2754
2755         msg->msg_hdr.msg.reply.dst_wmd = reply_wmd;
2756
2757         if (rdma_get) {
2758                 /* The LND completes the REPLY from her recv procedure */
2759                 lnet_ni_recv(ni, msg->msg_private, msg, 0,
2760                              msg->msg_offset, msg->msg_len, msg->msg_len);
2761                 return 0;
2762         }
2763
2764         lnet_ni_recv(ni, msg->msg_private, NULL, 0, 0, 0, 0);
2765         msg->msg_receiving = 0;
2766
2767         rc = lnet_send(ni->ni_nid, msg, LNET_NID_ANY);
2768         if (rc < 0) {
2769                 /* didn't get as far as lnet_ni_send() */
2770                 CERROR("%s: Unable to send REPLY for GET from %s: %d\n",
2771                        libcfs_nid2str(ni->ni_nid),
2772                        libcfs_id2str(info.mi_id), rc);
2773
2774                 lnet_finalize(msg, rc);
2775         }
2776
2777         return 0;
2778 }
2779
2780 static int
2781 lnet_parse_reply(struct lnet_ni *ni, struct lnet_msg *msg)
2782 {
2783         void             *private = msg->msg_private;
2784         struct lnet_hdr  *hdr = &msg->msg_hdr;
2785         struct lnet_process_id src = {0};
2786         struct lnet_libmd        *md;
2787         int               rlength;
2788         int               mlength;
2789         int                     cpt;
2790
2791         cpt = lnet_cpt_of_cookie(hdr->msg.reply.dst_wmd.wh_object_cookie);
2792         lnet_res_lock(cpt);
2793
2794         src.nid = hdr->src_nid;
2795         src.pid = hdr->src_pid;
2796
2797         /* NB handles only looked up by creator (no flips) */
2798         md = lnet_wire_handle2md(&hdr->msg.reply.dst_wmd);
2799         if (md == NULL || md->md_threshold == 0 || md->md_me != NULL) {
2800                 CNETERR("%s: Dropping REPLY from %s for %s "
2801                         "MD %#llx.%#llx\n",
2802                         libcfs_nid2str(ni->ni_nid), libcfs_id2str(src),
2803                         (md == NULL) ? "invalid" : "inactive",
2804                         hdr->msg.reply.dst_wmd.wh_interface_cookie,
2805                         hdr->msg.reply.dst_wmd.wh_object_cookie);
2806                 if (md != NULL && md->md_me != NULL)
2807                         CERROR("REPLY MD also attached to portal %d\n",
2808                                md->md_me->me_portal);
2809
2810                 lnet_res_unlock(cpt);
2811                 return -ENOENT; /* -ve: OK but no match */
2812         }
2813
2814         LASSERT(md->md_offset == 0);
2815
2816         rlength = hdr->payload_length;
2817         mlength = MIN(rlength, (int)md->md_length);
2818
2819         if (mlength < rlength &&
2820             (md->md_options & LNET_MD_TRUNCATE) == 0) {
2821                 CNETERR("%s: Dropping REPLY from %s length %d "
2822                         "for MD %#llx would overflow (%d)\n",
2823                         libcfs_nid2str(ni->ni_nid), libcfs_id2str(src),
2824                         rlength, hdr->msg.reply.dst_wmd.wh_object_cookie,
2825                         mlength);
2826                 lnet_res_unlock(cpt);
2827                 return -ENOENT; /* -ve: OK but no match */
2828         }
2829
2830         CDEBUG(D_NET, "%s: Reply from %s of length %d/%d into md %#llx\n",
2831                libcfs_nid2str(ni->ni_nid), libcfs_id2str(src),
2832                mlength, rlength, hdr->msg.reply.dst_wmd.wh_object_cookie);
2833
2834         lnet_msg_attach_md(msg, md, 0, mlength);
2835
2836         if (mlength != 0)
2837                 lnet_setpayloadbuffer(msg);
2838
2839         lnet_res_unlock(cpt);
2840
2841         lnet_build_msg_event(msg, LNET_EVENT_REPLY);
2842
2843         lnet_ni_recv(ni, private, msg, 0, 0, mlength, rlength);
2844         return 0;
2845 }
2846
2847 static int
2848 lnet_parse_ack(struct lnet_ni *ni, struct lnet_msg *msg)
2849 {
2850         struct lnet_hdr  *hdr = &msg->msg_hdr;
2851         struct lnet_process_id src = {0};
2852         struct lnet_libmd        *md;
2853         int                     cpt;
2854
2855         src.nid = hdr->src_nid;
2856         src.pid = hdr->src_pid;
2857
2858         /* Convert ack fields to host byte order */
2859         hdr->msg.ack.match_bits = le64_to_cpu(hdr->msg.ack.match_bits);
2860         hdr->msg.ack.mlength = le32_to_cpu(hdr->msg.ack.mlength);
2861
2862         cpt = lnet_cpt_of_cookie(hdr->msg.ack.dst_wmd.wh_object_cookie);
2863         lnet_res_lock(cpt);
2864
2865         /* NB handles only looked up by creator (no flips) */
2866         md = lnet_wire_handle2md(&hdr->msg.ack.dst_wmd);
2867         if (md == NULL || md->md_threshold == 0 || md->md_me != NULL) {
2868                 /* Don't moan; this is expected */
2869                 CDEBUG(D_NET,
2870                        "%s: Dropping ACK from %s to %s MD %#llx.%#llx\n",
2871                        libcfs_nid2str(ni->ni_nid), libcfs_id2str(src),
2872                        (md == NULL) ? "invalid" : "inactive",
2873                        hdr->msg.ack.dst_wmd.wh_interface_cookie,
2874                        hdr->msg.ack.dst_wmd.wh_object_cookie);
2875                 if (md != NULL && md->md_me != NULL)
2876                         CERROR("Source MD also attached to portal %d\n",
2877                                md->md_me->me_portal);
2878
2879                 lnet_res_unlock(cpt);
2880                 return -ENOENT;                  /* -ve! */
2881         }
2882
2883         CDEBUG(D_NET, "%s: ACK from %s into md %#llx\n",
2884                libcfs_nid2str(ni->ni_nid), libcfs_id2str(src),
2885                hdr->msg.ack.dst_wmd.wh_object_cookie);
2886
2887         lnet_msg_attach_md(msg, md, 0, 0);
2888
2889         lnet_res_unlock(cpt);
2890
2891         lnet_build_msg_event(msg, LNET_EVENT_ACK);
2892
2893         lnet_ni_recv(ni, msg->msg_private, msg, 0, 0, 0, msg->msg_len);
2894         return 0;
2895 }
2896
2897 /**
2898  * \retval LNET_CREDIT_OK       If \a msg is forwarded
2899  * \retval LNET_CREDIT_WAIT     If \a msg is blocked because w/o buffer
2900  * \retval -ve                  error code
2901  */
2902 int
2903 lnet_parse_forward_locked(struct lnet_ni *ni, struct lnet_msg *msg)
2904 {
2905         int     rc = 0;
2906
2907         if (!the_lnet.ln_routing)
2908                 return -ECANCELED;
2909
2910         if (msg->msg_rxpeer->lpni_rtrcredits <= 0 ||
2911             lnet_msg2bufpool(msg)->rbp_credits <= 0) {
2912                 if (ni->ni_net->net_lnd->lnd_eager_recv == NULL) {
2913                         msg->msg_rx_ready_delay = 1;
2914                 } else {
2915                         lnet_net_unlock(msg->msg_rx_cpt);
2916                         rc = lnet_ni_eager_recv(ni, msg);
2917                         lnet_net_lock(msg->msg_rx_cpt);
2918                 }
2919         }
2920
2921         if (rc == 0)
2922                 rc = lnet_post_routed_recv_locked(msg, 0);
2923         return rc;
2924 }
2925
2926 int
2927 lnet_parse_local(struct lnet_ni *ni, struct lnet_msg *msg)
2928 {
2929         int     rc;
2930
2931         switch (msg->msg_type) {
2932         case LNET_MSG_ACK:
2933                 rc = lnet_parse_ack(ni, msg);
2934                 break;
2935         case LNET_MSG_PUT:
2936                 rc = lnet_parse_put(ni, msg);
2937                 break;
2938         case LNET_MSG_GET:
2939                 rc = lnet_parse_get(ni, msg, msg->msg_rdma_get);
2940                 break;
2941         case LNET_MSG_REPLY:
2942                 rc = lnet_parse_reply(ni, msg);
2943                 break;
2944         default: /* prevent an unused label if !kernel */
2945                 LASSERT(0);
2946                 return -EPROTO;
2947         }
2948
2949         LASSERT(rc == 0 || rc == -ENOENT);
2950         return rc;
2951 }
2952
2953 char *
2954 lnet_msgtyp2str (int type)
2955 {
2956         switch (type) {
2957         case LNET_MSG_ACK:
2958                 return ("ACK");
2959         case LNET_MSG_PUT:
2960                 return ("PUT");
2961         case LNET_MSG_GET:
2962                 return ("GET");
2963         case LNET_MSG_REPLY:
2964                 return ("REPLY");
2965         case LNET_MSG_HELLO:
2966                 return ("HELLO");
2967         default:
2968                 return ("<UNKNOWN>");
2969         }
2970 }
2971
2972 void
2973 lnet_print_hdr(struct lnet_hdr *hdr)
2974 {
2975         struct lnet_process_id src = {
2976                 .nid = hdr->src_nid,
2977                 .pid = hdr->src_pid,
2978         };
2979         struct lnet_process_id dst = {
2980                 .nid = hdr->dest_nid,
2981                 .pid = hdr->dest_pid,
2982         };
2983         char *type_str = lnet_msgtyp2str(hdr->type);
2984
2985         CWARN("P3 Header at %p of type %s\n", hdr, type_str);
2986         CWARN("    From %s\n", libcfs_id2str(src));
2987         CWARN("    To   %s\n", libcfs_id2str(dst));
2988
2989         switch (hdr->type) {
2990         default:
2991                 break;
2992
2993         case LNET_MSG_PUT:
2994                 CWARN("    Ptl index %d, ack md %#llx.%#llx, "
2995                       "match bits %llu\n",
2996                       hdr->msg.put.ptl_index,
2997                       hdr->msg.put.ack_wmd.wh_interface_cookie,
2998                       hdr->msg.put.ack_wmd.wh_object_cookie,
2999                       hdr->msg.put.match_bits);
3000                 CWARN("    Length %d, offset %d, hdr data %#llx\n",
3001                       hdr->payload_length, hdr->msg.put.offset,
3002                       hdr->msg.put.hdr_data);
3003                 break;
3004
3005         case LNET_MSG_GET:
3006                 CWARN("    Ptl index %d, return md %#llx.%#llx, "
3007                       "match bits %llu\n", hdr->msg.get.ptl_index,
3008                       hdr->msg.get.return_wmd.wh_interface_cookie,
3009                       hdr->msg.get.return_wmd.wh_object_cookie,
3010                       hdr->msg.get.match_bits);
3011                 CWARN("    Length %d, src offset %d\n",
3012                       hdr->msg.get.sink_length,
3013                       hdr->msg.get.src_offset);
3014                 break;
3015
3016         case LNET_MSG_ACK:
3017                 CWARN("    dst md %#llx.%#llx, "
3018                       "manipulated length %d\n",
3019                       hdr->msg.ack.dst_wmd.wh_interface_cookie,
3020                       hdr->msg.ack.dst_wmd.wh_object_cookie,
3021                       hdr->msg.ack.mlength);
3022                 break;
3023
3024         case LNET_MSG_REPLY:
3025                 CWARN("    dst md %#llx.%#llx, "
3026                       "length %d\n",
3027                       hdr->msg.reply.dst_wmd.wh_interface_cookie,
3028                       hdr->msg.reply.dst_wmd.wh_object_cookie,
3029                       hdr->payload_length);
3030         }
3031
3032 }
3033
3034 int
3035 lnet_parse(struct lnet_ni *ni, struct lnet_hdr *hdr, lnet_nid_t from_nid,
3036            void *private, int rdma_req)
3037 {
3038         int             rc = 0;
3039         int             cpt;
3040         int             for_me;
3041         struct lnet_msg *msg;
3042         lnet_pid_t     dest_pid;
3043         lnet_nid_t     dest_nid;
3044         lnet_nid_t     src_nid;
3045         struct lnet_peer_ni *lpni;
3046         __u32          payload_length;
3047         __u32          type;
3048
3049         LASSERT (!in_interrupt ());
3050
3051         type = le32_to_cpu(hdr->type);
3052         src_nid = le64_to_cpu(hdr->src_nid);
3053         dest_nid = le64_to_cpu(hdr->dest_nid);
3054         dest_pid = le32_to_cpu(hdr->dest_pid);
3055         payload_length = le32_to_cpu(hdr->payload_length);
3056
3057         for_me = (ni->ni_nid == dest_nid);
3058         cpt = lnet_cpt_of_nid(from_nid, ni);
3059
3060         CDEBUG(D_NET, "TRACE: %s(%s) <- %s : %s - %s\n",
3061                 libcfs_nid2str(dest_nid),
3062                 libcfs_nid2str(ni->ni_nid),
3063                 libcfs_nid2str(src_nid),
3064                 lnet_msgtyp2str(type),
3065                 (for_me) ? "for me" : "routed");
3066
3067         switch (type) {
3068         case LNET_MSG_ACK:
3069         case LNET_MSG_GET:
3070                 if (payload_length > 0) {
3071                         CERROR("%s, src %s: bad %s payload %d (0 expected)\n",
3072                                libcfs_nid2str(from_nid),
3073                                libcfs_nid2str(src_nid),
3074                                lnet_msgtyp2str(type), payload_length);
3075                         return -EPROTO;
3076                 }
3077                 break;
3078
3079         case LNET_MSG_PUT:
3080         case LNET_MSG_REPLY:
3081                 if (payload_length >
3082                     (__u32)(for_me ? LNET_MAX_PAYLOAD : LNET_MTU)) {
3083                         CERROR("%s, src %s: bad %s payload %d "
3084                                "(%d max expected)\n",
3085                                libcfs_nid2str(from_nid),
3086                                libcfs_nid2str(src_nid),
3087                                lnet_msgtyp2str(type),
3088                                payload_length,
3089                                for_me ? LNET_MAX_PAYLOAD : LNET_MTU);
3090                         return -EPROTO;
3091                 }
3092                 break;
3093
3094         default:
3095                 CERROR("%s, src %s: Bad message type 0x%x\n",
3096                        libcfs_nid2str(from_nid),
3097                        libcfs_nid2str(src_nid), type);
3098                 return -EPROTO;
3099         }
3100
3101         if (the_lnet.ln_routing &&
3102             ni->ni_last_alive != ktime_get_real_seconds()) {
3103                 /* NB: so far here is the only place to set NI status to "up */
3104                 lnet_ni_lock(ni);
3105                 ni->ni_last_alive = ktime_get_real_seconds();
3106                 if (ni->ni_status != NULL &&
3107                     ni->ni_status->ns_status == LNET_NI_STATUS_DOWN)
3108                         ni->ni_status->ns_status = LNET_NI_STATUS_UP;
3109                 lnet_ni_unlock(ni);
3110         }
3111
3112         /* Regard a bad destination NID as a protocol error.  Senders should
3113          * know what they're doing; if they don't they're misconfigured, buggy
3114          * or malicious so we chop them off at the knees :) */
3115
3116         if (!for_me) {
3117                 if (LNET_NIDNET(dest_nid) == LNET_NIDNET(ni->ni_nid)) {
3118                         /* should have gone direct */
3119                         CERROR("%s, src %s: Bad dest nid %s "
3120                                "(should have been sent direct)\n",
3121                                 libcfs_nid2str(from_nid),
3122                                 libcfs_nid2str(src_nid),
3123                                 libcfs_nid2str(dest_nid));
3124                         return -EPROTO;
3125                 }
3126
3127                 if (lnet_islocalnid(dest_nid)) {
3128                         /* dest is another local NI; sender should have used
3129                          * this node's NID on its own network */
3130                         CERROR("%s, src %s: Bad dest nid %s "
3131                                "(it's my nid but on a different network)\n",
3132                                 libcfs_nid2str(from_nid),
3133                                 libcfs_nid2str(src_nid),
3134                                 libcfs_nid2str(dest_nid));
3135                         return -EPROTO;
3136                 }
3137
3138                 if (rdma_req && type == LNET_MSG_GET) {
3139                         CERROR("%s, src %s: Bad optimized GET for %s "
3140                                "(final destination must be me)\n",
3141                                 libcfs_nid2str(from_nid),
3142                                 libcfs_nid2str(src_nid),
3143                                 libcfs_nid2str(dest_nid));
3144                         return -EPROTO;
3145                 }
3146
3147                 if (!the_lnet.ln_routing) {
3148                         CERROR("%s, src %s: Dropping message for %s "
3149                                "(routing not enabled)\n",
3150                                 libcfs_nid2str(from_nid),
3151                                 libcfs_nid2str(src_nid),
3152                                 libcfs_nid2str(dest_nid));
3153                         goto drop;
3154                 }
3155         }
3156
3157         /* Message looks OK; we're not going to return an error, so we MUST
3158          * call back lnd_recv() come what may... */
3159
3160         if (!list_empty(&the_lnet.ln_test_peers) &&     /* normally we don't */
3161             fail_peer(src_nid, 0)) {                    /* shall we now? */
3162                 CERROR("%s, src %s: Dropping %s to simulate failure\n",
3163                        libcfs_nid2str(from_nid), libcfs_nid2str(src_nid),
3164                        lnet_msgtyp2str(type));
3165                 goto drop;
3166         }
3167
3168         if (!list_empty(&the_lnet.ln_drop_rules) &&
3169             lnet_drop_rule_match(hdr)) {
3170                 CDEBUG(D_NET, "%s, src %s, dst %s: Dropping %s to simulate"
3171                               "silent message loss\n",
3172                        libcfs_nid2str(from_nid), libcfs_nid2str(src_nid),
3173                        libcfs_nid2str(dest_nid), lnet_msgtyp2str(type));
3174                 goto drop;
3175         }
3176
3177
3178         msg = lnet_msg_alloc();
3179         if (msg == NULL) {
3180                 CERROR("%s, src %s: Dropping %s (out of memory)\n",
3181                        libcfs_nid2str(from_nid), libcfs_nid2str(src_nid),
3182                        lnet_msgtyp2str(type));
3183                 goto drop;
3184         }
3185
3186         /* msg zeroed in lnet_msg_alloc; i.e. flags all clear,
3187          * pointers NULL etc */
3188
3189         msg->msg_type = type;
3190         msg->msg_private = private;
3191         msg->msg_receiving = 1;
3192         msg->msg_rdma_get = rdma_req;
3193         msg->msg_len = msg->msg_wanted = payload_length;
3194         msg->msg_offset = 0;
3195         msg->msg_hdr = *hdr;
3196         /* for building message event */
3197         msg->msg_from = from_nid;
3198         if (!for_me) {
3199                 msg->msg_target.pid     = dest_pid;
3200                 msg->msg_target.nid     = dest_nid;
3201                 msg->msg_routing        = 1;
3202
3203         } else {
3204                 /* convert common msg->hdr fields to host byteorder */
3205                 msg->msg_hdr.type       = type;
3206                 msg->msg_hdr.src_nid    = src_nid;
3207                 msg->msg_hdr.src_pid    = le32_to_cpu(msg->msg_hdr.src_pid);
3208                 msg->msg_hdr.dest_nid   = dest_nid;
3209                 msg->msg_hdr.dest_pid   = dest_pid;
3210                 msg->msg_hdr.payload_length = payload_length;
3211         }
3212
3213         lnet_net_lock(cpt);
3214         lpni = lnet_nid2peerni_locked(from_nid, ni->ni_nid, cpt);
3215         if (IS_ERR(lpni)) {
3216                 lnet_net_unlock(cpt);
3217                 CERROR("%s, src %s: Dropping %s "
3218                        "(error %ld looking up sender)\n",
3219                        libcfs_nid2str(from_nid), libcfs_nid2str(src_nid),
3220                        lnet_msgtyp2str(type), PTR_ERR(lpni));
3221                 lnet_msg_free(msg);
3222                 if (rc == -ESHUTDOWN)
3223                         /* We are shutting down.  Don't do anything more */
3224                         return 0;
3225                 goto drop;
3226         }
3227         msg->msg_rxpeer = lpni;
3228         msg->msg_rxni = ni;
3229         lnet_ni_addref_locked(ni, cpt);
3230         /* Multi-Rail: Primary NID of source. */
3231         msg->msg_initiator = lnet_peer_primary_nid_locked(src_nid);
3232
3233         if (lnet_isrouter(msg->msg_rxpeer)) {
3234                 lnet_peer_set_alive(msg->msg_rxpeer);
3235                 if (avoid_asym_router_failure &&
3236                     LNET_NIDNET(src_nid) != LNET_NIDNET(from_nid)) {
3237                         /* received a remote message from router, update
3238                          * remote NI status on this router.
3239                          * NB: multi-hop routed message will be ignored.
3240                          */
3241                         lnet_router_ni_update_locked(msg->msg_rxpeer,
3242                                                      LNET_NIDNET(src_nid));
3243                 }
3244         }
3245
3246         lnet_msg_commit(msg, cpt);
3247
3248         /* message delay simulation */
3249         if (unlikely(!list_empty(&the_lnet.ln_delay_rules) &&
3250                      lnet_delay_rule_match_locked(hdr, msg))) {
3251                 lnet_net_unlock(cpt);
3252                 return 0;
3253         }
3254
3255         if (!for_me) {
3256                 rc = lnet_parse_forward_locked(ni, msg);
3257                 lnet_net_unlock(cpt);
3258
3259                 if (rc < 0)
3260                         goto free_drop;
3261
3262                 if (rc == LNET_CREDIT_OK) {
3263                         lnet_ni_recv(ni, msg->msg_private, msg, 0,
3264                                      0, payload_length, payload_length);
3265                 }
3266                 return 0;
3267         }
3268
3269         lnet_net_unlock(cpt);
3270
3271         rc = lnet_parse_local(ni, msg);
3272         if (rc != 0)
3273                 goto free_drop;
3274         return 0;
3275
3276  free_drop:
3277         LASSERT(msg->msg_md == NULL);
3278         lnet_finalize(msg, rc);
3279
3280  drop:
3281         lnet_drop_message(ni, cpt, private, payload_length, type);
3282         return 0;
3283 }
3284 EXPORT_SYMBOL(lnet_parse);
3285
3286 void
3287 lnet_drop_delayed_msg_list(struct list_head *head, char *reason)
3288 {
3289         while (!list_empty(head)) {
3290                 struct lnet_process_id id = {0};
3291                 struct lnet_msg *msg;
3292
3293                 msg = list_entry(head->next, struct lnet_msg, msg_list);
3294                 list_del(&msg->msg_list);
3295
3296                 id.nid = msg->msg_hdr.src_nid;
3297                 id.pid = msg->msg_hdr.src_pid;
3298
3299                 LASSERT(msg->msg_md == NULL);
3300                 LASSERT(msg->msg_rx_delayed);
3301                 LASSERT(msg->msg_rxpeer != NULL);
3302                 LASSERT(msg->msg_hdr.type == LNET_MSG_PUT);
3303
3304                 CWARN("Dropping delayed PUT from %s portal %d match %llu"
3305                       " offset %d length %d: %s\n",
3306                       libcfs_id2str(id),
3307                       msg->msg_hdr.msg.put.ptl_index,
3308                       msg->msg_hdr.msg.put.match_bits,
3309                       msg->msg_hdr.msg.put.offset,
3310                       msg->msg_hdr.payload_length, reason);
3311
3312                 /* NB I can't drop msg's ref on msg_rxpeer until after I've
3313                  * called lnet_drop_message(), so I just hang onto msg as well
3314                  * until that's done */
3315
3316                 lnet_drop_message(msg->msg_rxni, msg->msg_rx_cpt,
3317                                   msg->msg_private, msg->msg_len,
3318                                   msg->msg_type);
3319                 /*
3320                  * NB: message will not generate event because w/o attached MD,
3321                  * but we still should give error code so lnet_msg_decommit()
3322                  * can skip counters operations and other checks.
3323                  */
3324                 lnet_finalize(msg, -ENOENT);
3325         }
3326 }
3327
3328 void
3329 lnet_recv_delayed_msg_list(struct list_head *head)
3330 {
3331         while (!list_empty(head)) {
3332                 struct lnet_msg *msg;
3333                 struct lnet_process_id id;
3334
3335                 msg = list_entry(head->next, struct lnet_msg, msg_list);
3336                 list_del(&msg->msg_list);
3337
3338                 /* md won't disappear under me, since each msg
3339                  * holds a ref on it */
3340
3341                 id.nid = msg->msg_hdr.src_nid;
3342                 id.pid = msg->msg_hdr.src_pid;
3343
3344                 LASSERT(msg->msg_rx_delayed);
3345                 LASSERT(msg->msg_md != NULL);
3346                 LASSERT(msg->msg_rxpeer != NULL);
3347                 LASSERT(msg->msg_rxni != NULL);
3348                 LASSERT(msg->msg_hdr.type == LNET_MSG_PUT);
3349
3350                 CDEBUG(D_NET, "Resuming delayed PUT from %s portal %d "
3351                        "match %llu offset %d length %d.\n",
3352                         libcfs_id2str(id), msg->msg_hdr.msg.put.ptl_index,
3353                         msg->msg_hdr.msg.put.match_bits,
3354                         msg->msg_hdr.msg.put.offset,
3355                         msg->msg_hdr.payload_length);
3356
3357                 lnet_recv_put(msg->msg_rxni, msg);
3358         }
3359 }
3360
3361 /**
3362  * Initiate an asynchronous PUT operation.
3363  *
3364  * There are several events associated with a PUT: completion of the send on
3365  * the initiator node (LNET_EVENT_SEND), and when the send completes
3366  * successfully, the receipt of an acknowledgment (LNET_EVENT_ACK) indicating
3367  * that the operation was accepted by the target. The event LNET_EVENT_PUT is
3368  * used at the target node to indicate the completion of incoming data
3369  * delivery.
3370  *
3371  * The local events will be logged in the EQ associated with the MD pointed to
3372  * by \a mdh handle. Using a MD without an associated EQ results in these
3373  * events being discarded. In this case, the caller must have another
3374  * mechanism (e.g., a higher level protocol) for determining when it is safe
3375  * to modify the memory region associated with the MD.
3376  *
3377  * Note that LNet does not guarantee the order of LNET_EVENT_SEND and
3378  * LNET_EVENT_ACK, though intuitively ACK should happen after SEND.
3379  *
3380  * \param self Indicates the NID of a local interface through which to send
3381  * the PUT request. Use LNET_NID_ANY to let LNet choose one by itself.
3382  * \param mdh A handle for the MD that describes the memory to be sent. The MD
3383  * must be "free floating" (See LNetMDBind()).
3384  * \param ack Controls whether an acknowledgment is requested.
3385  * Acknowledgments are only sent when they are requested by the initiating
3386  * process and the target MD enables them.
3387  * \param target A process identifier for the target process.
3388  * \param portal The index in the \a target's portal table.
3389  * \param match_bits The match bits to use for MD selection at the target
3390  * process.
3391  * \param offset The offset into the target MD (only used when the target
3392  * MD has the LNET_MD_MANAGE_REMOTE option set).
3393  * \param hdr_data 64 bits of user data that can be included in the message
3394  * header. This data is written to an event queue entry at the target if an
3395  * EQ is present on the matching MD.
3396  *
3397  * \retval  0      Success, and only in this case events will be generated
3398  * and logged to EQ (if it exists).
3399  * \retval -EIO    Simulated failure.
3400  * \retval -ENOMEM Memory allocation failure.
3401  * \retval -ENOENT Invalid MD object.
3402  *
3403  * \see struct lnet_event::hdr_data and lnet_event_kind_t.
3404  */
3405 int
3406 LNetPut(lnet_nid_t self, struct lnet_handle_md mdh, enum lnet_ack_req ack,
3407         struct lnet_process_id target, unsigned int portal,
3408         __u64 match_bits, unsigned int offset,
3409         __u64 hdr_data)
3410 {
3411         struct lnet_msg         *msg;
3412         struct lnet_libmd       *md;
3413         int                     cpt;
3414         int                     rc;
3415
3416         LASSERT(the_lnet.ln_refcount > 0);
3417
3418         if (!list_empty(&the_lnet.ln_test_peers) &&     /* normally we don't */
3419             fail_peer(target.nid, 1)) {                 /* shall we now? */
3420                 CERROR("Dropping PUT to %s: simulated failure\n",
3421                        libcfs_id2str(target));
3422                 return -EIO;
3423         }
3424
3425         msg = lnet_msg_alloc();
3426         if (msg == NULL) {
3427                 CERROR("Dropping PUT to %s: ENOMEM on struct lnet_msg\n",
3428                        libcfs_id2str(target));
3429                 return -ENOMEM;
3430         }
3431         msg->msg_vmflush = !!memory_pressure_get();
3432
3433         cpt = lnet_cpt_of_cookie(mdh.cookie);
3434         lnet_res_lock(cpt);
3435
3436         md = lnet_handle2md(&mdh);
3437         if (md == NULL || md->md_threshold == 0 || md->md_me != NULL) {
3438                 CERROR("Dropping PUT (%llu:%d:%s): MD (%d) invalid\n",
3439                        match_bits, portal, libcfs_id2str(target),
3440                        md == NULL ? -1 : md->md_threshold);
3441                 if (md != NULL && md->md_me != NULL)
3442                         CERROR("Source MD also attached to portal %d\n",
3443                                md->md_me->me_portal);
3444                 lnet_res_unlock(cpt);
3445
3446                 lnet_msg_free(msg);
3447                 return -ENOENT;
3448         }
3449
3450         CDEBUG(D_NET, "LNetPut -> %s\n", libcfs_id2str(target));
3451
3452         lnet_msg_attach_md(msg, md, 0, 0);
3453
3454         lnet_prep_send(msg, LNET_MSG_PUT, target, 0, md->md_length);
3455
3456         msg->msg_hdr.msg.put.match_bits = cpu_to_le64(match_bits);
3457         msg->msg_hdr.msg.put.ptl_index = cpu_to_le32(portal);
3458         msg->msg_hdr.msg.put.offset = cpu_to_le32(offset);
3459         msg->msg_hdr.msg.put.hdr_data = hdr_data;
3460
3461         /* NB handles only looked up by creator (no flips) */
3462         if (ack == LNET_ACK_REQ) {
3463                 msg->msg_hdr.msg.put.ack_wmd.wh_interface_cookie =
3464                         the_lnet.ln_interface_cookie;
3465                 msg->msg_hdr.msg.put.ack_wmd.wh_object_cookie =
3466                         md->md_lh.lh_cookie;
3467         } else {
3468                 msg->msg_hdr.msg.put.ack_wmd.wh_interface_cookie =
3469                         LNET_WIRE_HANDLE_COOKIE_NONE;
3470                 msg->msg_hdr.msg.put.ack_wmd.wh_object_cookie =
3471                         LNET_WIRE_HANDLE_COOKIE_NONE;
3472         }
3473
3474         lnet_res_unlock(cpt);
3475
3476         lnet_build_msg_event(msg, LNET_EVENT_SEND);
3477
3478         rc = lnet_send(self, msg, LNET_NID_ANY);
3479         if (rc != 0) {
3480                 CNETERR("Error sending PUT to %s: %d\n",
3481                         libcfs_id2str(target), rc);
3482                 lnet_finalize(msg, rc);
3483         }
3484
3485         /* completion will be signalled by an event */
3486         return 0;
3487 }
3488 EXPORT_SYMBOL(LNetPut);
3489
3490 /*
3491  * The LND can DMA direct to the GET md (i.e. no REPLY msg).  This
3492  * returns a msg for the LND to pass to lnet_finalize() when the sink
3493  * data has been received.
3494  *
3495  * CAVEAT EMPTOR: 'getmsg' is the original GET, which is freed when
3496  * lnet_finalize() is called on it, so the LND must call this first
3497  */
3498 struct lnet_msg *
3499 lnet_create_reply_msg(struct lnet_ni *ni, struct lnet_msg *getmsg)
3500 {
3501         struct lnet_msg *msg = lnet_msg_alloc();
3502         struct lnet_libmd *getmd = getmsg->msg_md;
3503         struct lnet_process_id peer_id = getmsg->msg_target;
3504         int cpt;
3505
3506         LASSERT(!getmsg->msg_target_is_router);
3507         LASSERT(!getmsg->msg_routing);
3508
3509         if (msg == NULL) {
3510                 CERROR("%s: Dropping REPLY from %s: can't allocate msg\n",
3511                        libcfs_nid2str(ni->ni_nid), libcfs_id2str(peer_id));
3512                 goto drop;
3513         }
3514
3515         cpt = lnet_cpt_of_cookie(getmd->md_lh.lh_cookie);
3516         lnet_res_lock(cpt);
3517
3518         LASSERT(getmd->md_refcount > 0);
3519
3520         if (getmd->md_threshold == 0) {
3521                 CERROR("%s: Dropping REPLY from %s for inactive MD %p\n",
3522                         libcfs_nid2str(ni->ni_nid), libcfs_id2str(peer_id),
3523                         getmd);
3524                 lnet_res_unlock(cpt);
3525                 goto drop;
3526         }
3527
3528         LASSERT(getmd->md_offset == 0);
3529
3530         CDEBUG(D_NET, "%s: Reply from %s md %p\n",
3531                libcfs_nid2str(ni->ni_nid), libcfs_id2str(peer_id), getmd);
3532
3533         /* setup information for lnet_build_msg_event */
3534         msg->msg_initiator = getmsg->msg_txpeer->lpni_peer_net->lpn_peer->lp_primary_nid;
3535         msg->msg_from = peer_id.nid;
3536         msg->msg_type = LNET_MSG_GET; /* flag this msg as an "optimized" GET */
3537         msg->msg_hdr.src_nid = peer_id.nid;
3538         msg->msg_hdr.payload_length = getmd->md_length;
3539         msg->msg_receiving = 1; /* required by lnet_msg_attach_md */
3540
3541         lnet_msg_attach_md(msg, getmd, getmd->md_offset, getmd->md_length);
3542         lnet_res_unlock(cpt);
3543
3544         cpt = lnet_cpt_of_nid(peer_id.nid, ni);
3545
3546         lnet_net_lock(cpt);
3547         lnet_msg_commit(msg, cpt);
3548         lnet_net_unlock(cpt);
3549
3550         lnet_build_msg_event(msg, LNET_EVENT_REPLY);
3551
3552         return msg;
3553
3554  drop:
3555         cpt = lnet_cpt_of_nid(peer_id.nid, ni);
3556
3557         lnet_net_lock(cpt);
3558         lnet_incr_stats(&ni->ni_stats, LNET_MSG_GET, LNET_STATS_TYPE_DROP);
3559         the_lnet.ln_counters[cpt]->drop_count++;
3560         the_lnet.ln_counters[cpt]->drop_length += getmd->md_length;
3561         lnet_net_unlock(cpt);
3562
3563         if (msg != NULL)
3564                 lnet_msg_free(msg);
3565
3566         return NULL;
3567 }
3568 EXPORT_SYMBOL(lnet_create_reply_msg);
3569
3570 void
3571 lnet_set_reply_msg_len(struct lnet_ni *ni, struct lnet_msg *reply,
3572                        unsigned int len)
3573 {
3574         /* Set the REPLY length, now the RDMA that elides the REPLY message has
3575          * completed and I know it. */
3576         LASSERT(reply != NULL);
3577         LASSERT(reply->msg_type == LNET_MSG_GET);
3578         LASSERT(reply->msg_ev.type == LNET_EVENT_REPLY);
3579
3580         /* NB I trusted my peer to RDMA.  If she tells me she's written beyond
3581          * the end of my buffer, I might as well be dead. */
3582         LASSERT(len <= reply->msg_ev.mlength);
3583
3584         reply->msg_ev.mlength = len;
3585 }
3586 EXPORT_SYMBOL(lnet_set_reply_msg_len);
3587
3588 /**
3589  * Initiate an asynchronous GET operation.
3590  *
3591  * On the initiator node, an LNET_EVENT_SEND is logged when the GET request
3592  * is sent, and an LNET_EVENT_REPLY is logged when the data returned from
3593  * the target node in the REPLY has been written to local MD.
3594  *
3595  * On the target node, an LNET_EVENT_GET is logged when the GET request
3596  * arrives and is accepted into a MD.
3597  *
3598  * \param self,target,portal,match_bits,offset See the discussion in LNetPut().
3599  * \param mdh A handle for the MD that describes the memory into which the
3600  * requested data will be received. The MD must be "free floating" (See LNetMDBind()).
3601  *
3602  * \retval  0      Success, and only in this case events will be generated
3603  * and logged to EQ (if it exists) of the MD.
3604  * \retval -EIO    Simulated failure.
3605  * \retval -ENOMEM Memory allocation failure.
3606  * \retval -ENOENT Invalid MD object.
3607  */
3608 int
3609 LNetGet(lnet_nid_t self, struct lnet_handle_md mdh,
3610         struct lnet_process_id target, unsigned int portal,
3611         __u64 match_bits, unsigned int offset)
3612 {
3613         struct lnet_msg         *msg;
3614         struct lnet_libmd       *md;
3615         int                     cpt;
3616         int                     rc;
3617
3618         LASSERT(the_lnet.ln_refcount > 0);
3619
3620         if (!list_empty(&the_lnet.ln_test_peers) &&     /* normally we don't */
3621             fail_peer(target.nid, 1))                   /* shall we now? */
3622         {
3623                 CERROR("Dropping GET to %s: simulated failure\n",
3624                        libcfs_id2str(target));
3625                 return -EIO;
3626         }
3627
3628         msg = lnet_msg_alloc();
3629         if (msg == NULL) {
3630                 CERROR("Dropping GET to %s: ENOMEM on struct lnet_msg\n",
3631                        libcfs_id2str(target));
3632                 return -ENOMEM;
3633         }
3634
3635         cpt = lnet_cpt_of_cookie(mdh.cookie);
3636         lnet_res_lock(cpt);
3637
3638         md = lnet_handle2md(&mdh);
3639         if (md == NULL || md->md_threshold == 0 || md->md_me != NULL) {
3640                 CERROR("Dropping GET (%llu:%d:%s): MD (%d) invalid\n",
3641                        match_bits, portal, libcfs_id2str(target),
3642                        md == NULL ? -1 : md->md_threshold);
3643                 if (md != NULL && md->md_me != NULL)
3644                         CERROR("REPLY MD also attached to portal %d\n",
3645                                md->md_me->me_portal);
3646
3647                 lnet_res_unlock(cpt);
3648
3649                 lnet_msg_free(msg);
3650                 return -ENOENT;
3651         }
3652
3653         CDEBUG(D_NET, "LNetGet -> %s\n", libcfs_id2str(target));
3654
3655         lnet_msg_attach_md(msg, md, 0, 0);
3656
3657         lnet_prep_send(msg, LNET_MSG_GET, target, 0, 0);
3658
3659         msg->msg_hdr.msg.get.match_bits = cpu_to_le64(match_bits);
3660         msg->msg_hdr.msg.get.ptl_index = cpu_to_le32(portal);
3661         msg->msg_hdr.msg.get.src_offset = cpu_to_le32(offset);
3662         msg->msg_hdr.msg.get.sink_length = cpu_to_le32(md->md_length);
3663
3664         /* NB handles only looked up by creator (no flips) */
3665         msg->msg_hdr.msg.get.return_wmd.wh_interface_cookie =
3666                 the_lnet.ln_interface_cookie;
3667         msg->msg_hdr.msg.get.return_wmd.wh_object_cookie =
3668                 md->md_lh.lh_cookie;
3669
3670         lnet_res_unlock(cpt);
3671
3672         lnet_build_msg_event(msg, LNET_EVENT_SEND);
3673
3674         rc = lnet_send(self, msg, LNET_NID_ANY);
3675         if (rc < 0) {
3676                 CNETERR("Error sending GET to %s: %d\n",
3677                         libcfs_id2str(target), rc);
3678                 lnet_finalize(msg, rc);
3679         }
3680
3681         /* completion will be signalled by an event */
3682         return 0;
3683 }
3684 EXPORT_SYMBOL(LNetGet);
3685
3686 /**
3687  * Calculate distance to node at \a dstnid.
3688  *
3689  * \param dstnid Target NID.
3690  * \param srcnidp If not NULL, NID of the local interface to reach \a dstnid
3691  * is saved here.
3692  * \param orderp If not NULL, order of the route to reach \a dstnid is saved
3693  * here.
3694  *
3695  * \retval 0 If \a dstnid belongs to a local interface, and reserved option
3696  * local_nid_dist_zero is set, which is the default.
3697  * \retval positives Distance to target NID, i.e. number of hops plus one.
3698  * \retval -EHOSTUNREACH If \a dstnid is not reachable.
3699  */
3700 int
3701 LNetDist(lnet_nid_t dstnid, lnet_nid_t *srcnidp, __u32 *orderp)
3702 {
3703         struct list_head        *e;
3704         struct lnet_ni *ni = NULL;
3705         struct lnet_remotenet *rnet;
3706         __u32                   dstnet = LNET_NIDNET(dstnid);
3707         int                     hops;
3708         int                     cpt;
3709         __u32                   order = 2;
3710         struct list_head        *rn_list;
3711
3712         /* if !local_nid_dist_zero, I don't return a distance of 0 ever
3713          * (when lustre sees a distance of 0, it substitutes 0@lo), so I
3714          * keep order 0 free for 0@lo and order 1 free for a local NID
3715          * match */
3716
3717         LASSERT(the_lnet.ln_refcount > 0);
3718
3719         cpt = lnet_net_lock_current();
3720
3721         while ((ni = lnet_get_next_ni_locked(NULL, ni))) {
3722                 if (ni->ni_nid == dstnid) {
3723                         if (srcnidp != NULL)
3724                                 *srcnidp = dstnid;
3725                         if (orderp != NULL) {
3726                                 if (LNET_NETTYP(LNET_NIDNET(dstnid)) == LOLND)
3727                                         *orderp = 0;
3728                                 else
3729                                         *orderp = 1;
3730                         }
3731                         lnet_net_unlock(cpt);
3732
3733                         return local_nid_dist_zero ? 0 : 1;
3734                 }
3735
3736                 if (LNET_NIDNET(ni->ni_nid) == dstnet) {
3737                         /* Check if ni was originally created in
3738                          * current net namespace.
3739                          * If not, assign order above 0xffff0000,
3740                          * to make this ni not a priority. */
3741                         if (!net_eq(ni->ni_net_ns, current->nsproxy->net_ns))
3742                                 order += 0xffff0000;
3743
3744                         if (srcnidp != NULL)
3745                                 *srcnidp = ni->ni_nid;
3746                         if (orderp != NULL)
3747                                 *orderp = order;
3748                         lnet_net_unlock(cpt);
3749                         return 1;
3750                 }
3751
3752                 order++;
3753         }
3754
3755         rn_list = lnet_net2rnethash(dstnet);
3756         list_for_each(e, rn_list) {
3757                 rnet = list_entry(e, struct lnet_remotenet, lrn_list);
3758
3759                 if (rnet->lrn_net == dstnet) {
3760                         struct lnet_route *route;
3761                         struct lnet_route *shortest = NULL;
3762                         __u32 shortest_hops = LNET_UNDEFINED_HOPS;
3763                         __u32 route_hops;
3764
3765                         LASSERT(!list_empty(&rnet->lrn_routes));
3766
3767                         list_for_each_entry(route, &rnet->lrn_routes,
3768                                             lr_list) {
3769                                 route_hops = route->lr_hops;
3770                                 if (route_hops == LNET_UNDEFINED_HOPS)
3771                                         route_hops = 1;
3772                                 if (shortest == NULL ||
3773                                     route_hops < shortest_hops) {
3774                                         shortest = route;
3775                                         shortest_hops = route_hops;
3776                                 }
3777                         }
3778
3779                         LASSERT(shortest != NULL);
3780                         hops = shortest_hops;
3781                         if (srcnidp != NULL) {
3782                                 ni = lnet_get_next_ni_locked(
3783                                         shortest->lr_gateway->lpni_net,
3784                                         NULL);
3785                                 *srcnidp = ni->ni_nid;
3786                         }
3787                         if (orderp != NULL)
3788                                 *orderp = order;
3789                         lnet_net_unlock(cpt);
3790                         return hops + 1;
3791                 }
3792                 order++;
3793         }
3794
3795         lnet_net_unlock(cpt);
3796         return -EHOSTUNREACH;
3797 }
3798 EXPORT_SYMBOL(LNetDist);