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