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