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