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