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