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