Whamcloud - gitweb
LU-9679 modules: use list_move were appropriate.
[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 sending to ourselves then there is no need to go through
2656          * any selection. We can shortcut the entire process and send over
2657          * lolnd.
2658          *
2659          * However, we make two exceptions to this rule:
2660          * 1. If the src_nid is specified then our API defines that we must send
2661          *    via that interface.
2662          * 2. Recovery messages must be sent to the lnet_ni that is being
2663          *    recovered.
2664          */
2665         send_data.sd_msg = msg;
2666         send_data.sd_cpt = cpt;
2667         if (src_nid == LNET_NID_ANY && !msg->msg_recovery &&
2668             lnet_nid2ni_locked(dst_nid, cpt)) {
2669                 rc = lnet_handle_lo_send(&send_data);
2670                 lnet_net_unlock(cpt);
2671                 return rc;
2672         }
2673
2674         /*
2675          * find an existing peer_ni, or create one and mark it as having been
2676          * created due to network traffic. This call will create the
2677          * peer->peer_net->peer_ni tree.
2678          */
2679         lpni = lnet_nid2peerni_locked(dst_nid, LNET_NID_ANY, cpt);
2680         if (IS_ERR(lpni)) {
2681                 lnet_net_unlock(cpt);
2682                 return PTR_ERR(lpni);
2683         }
2684
2685         /*
2686          * Cache the original src_nid. If we need to resend the message
2687          * then we'll need to know whether the src_nid was originally
2688          * specified for this message. If it was originally specified,
2689          * then we need to keep using the same src_nid since it's
2690          * continuing the same sequence of messages.
2691          */
2692         msg->msg_src_nid_param = src_nid;
2693
2694         /*
2695          * If necessary, perform discovery on the peer that owns this peer_ni.
2696          * Note, this can result in the ownership of this peer_ni changing
2697          * to another peer object.
2698          */
2699         rc = lnet_initiate_peer_discovery(lpni, msg, rtr_nid, cpt);
2700         if (rc) {
2701                 lnet_peer_ni_decref_locked(lpni);
2702                 lnet_net_unlock(cpt);
2703                 return rc;
2704         }
2705         lnet_peer_ni_decref_locked(lpni);
2706
2707         peer = lpni->lpni_peer_net->lpn_peer;
2708
2709         /*
2710          * Identify the different send cases
2711          */
2712         if (src_nid == LNET_NID_ANY)
2713                 send_case |= SRC_ANY;
2714         else
2715                 send_case |= SRC_SPEC;
2716
2717         if (lnet_get_net_locked(LNET_NIDNET(dst_nid)))
2718                 send_case |= LOCAL_DST;
2719         else
2720                 send_case |= REMOTE_DST;
2721
2722         /*
2723          * if this is a non-MR peer or if we're recovering a peer ni then
2724          * let's consider this an NMR case so we can hit the destination
2725          * NID.
2726          */
2727         if (!lnet_peer_is_multi_rail(peer) || msg->msg_recovery)
2728                 send_case |= NMR_DST;
2729         else
2730                 send_case |= MR_DST;
2731
2732         if (msg->msg_type == LNET_MSG_REPLY ||
2733             msg->msg_type == LNET_MSG_ACK)
2734                 send_case |= SND_RESP;
2735
2736         /* assign parameters to the send_data */
2737         send_data.sd_rtr_nid = rtr_nid;
2738         send_data.sd_src_nid = src_nid;
2739         send_data.sd_dst_nid = dst_nid;
2740         send_data.sd_best_lpni = lpni;
2741         /*
2742          * keep a pointer to the final destination in case we're going to
2743          * route, so we'll need to access it later
2744          */
2745         send_data.sd_final_dst_lpni = lpni;
2746         send_data.sd_peer = peer;
2747         send_data.sd_md_cpt = md_cpt;
2748         send_data.sd_send_case = send_case;
2749
2750         rc = lnet_handle_send_case_locked(&send_data);
2751
2752         /*
2753          * Update the local cpt since send_data.sd_cpt might've been
2754          * updated as a result of calling lnet_handle_send_case_locked().
2755          */
2756         cpt = send_data.sd_cpt;
2757
2758         if (rc == REPEAT_SEND)
2759                 goto again;
2760
2761         lnet_net_unlock(cpt);
2762
2763         return rc;
2764 }
2765
2766 int
2767 lnet_send(lnet_nid_t src_nid, struct lnet_msg *msg, lnet_nid_t rtr_nid)
2768 {
2769         lnet_nid_t              dst_nid = msg->msg_target.nid;
2770         int                     rc;
2771
2772         /*
2773          * NB: rtr_nid is set to LNET_NID_ANY for all current use-cases,
2774          * but we might want to use pre-determined router for ACK/REPLY
2775          * in the future
2776          */
2777         /* NB: ni != NULL == interface pre-determined (ACK/REPLY) */
2778         LASSERT(msg->msg_txpeer == NULL);
2779         LASSERT(msg->msg_txni == NULL);
2780         LASSERT(!msg->msg_sending);
2781         LASSERT(!msg->msg_target_is_router);
2782         LASSERT(!msg->msg_receiving);
2783
2784         msg->msg_sending = 1;
2785
2786         LASSERT(!msg->msg_tx_committed);
2787
2788         rc = lnet_select_pathway(src_nid, dst_nid, msg, rtr_nid);
2789         if (rc < 0) {
2790                 if (rc == -EHOSTUNREACH)
2791                         msg->msg_health_status = LNET_MSG_STATUS_REMOTE_ERROR;
2792                 else
2793                         msg->msg_health_status = LNET_MSG_STATUS_LOCAL_ERROR;
2794                 return rc;
2795         }
2796
2797         if (rc == LNET_CREDIT_OK)
2798                 lnet_ni_send(msg->msg_txni, msg);
2799
2800         /* rc == LNET_CREDIT_OK or LNET_CREDIT_WAIT or LNET_DC_WAIT */
2801         return 0;
2802 }
2803
2804 enum lnet_mt_event_type {
2805         MT_TYPE_LOCAL_NI = 0,
2806         MT_TYPE_PEER_NI
2807 };
2808
2809 struct lnet_mt_event_info {
2810         enum lnet_mt_event_type mt_type;
2811         lnet_nid_t mt_nid;
2812 };
2813
2814 /* called with res_lock held */
2815 void
2816 lnet_detach_rsp_tracker(struct lnet_libmd *md, int cpt)
2817 {
2818         struct lnet_rsp_tracker *rspt;
2819
2820         /*
2821          * msg has a refcount on the MD so the MD is not going away.
2822          * The rspt queue for the cpt is protected by
2823          * the lnet_net_lock(cpt). cpt is the cpt of the MD cookie.
2824          */
2825         if (!md->md_rspt_ptr)
2826                 return;
2827
2828         rspt = md->md_rspt_ptr;
2829
2830         /* debug code */
2831         LASSERT(rspt->rspt_cpt == cpt);
2832
2833         md->md_rspt_ptr = NULL;
2834
2835         if (LNetMDHandleIsInvalid(rspt->rspt_mdh)) {
2836                 /*
2837                  * The monitor thread has invalidated this handle because the
2838                  * response timed out, but it failed to lookup the MD. That
2839                  * means this response tracker is on the zombie list. We can
2840                  * safely remove it under the resource lock (held by caller) and
2841                  * free the response tracker block.
2842                  */
2843                 list_del(&rspt->rspt_on_list);
2844                 lnet_rspt_free(rspt, cpt);
2845         } else {
2846                 /*
2847                  * invalidate the handle to indicate that a response has been
2848                  * received, which will then lead the monitor thread to clean up
2849                  * the rspt block.
2850                  */
2851                 LNetInvalidateMDHandle(&rspt->rspt_mdh);
2852         }
2853 }
2854
2855 void
2856 lnet_clean_zombie_rstqs(void)
2857 {
2858         struct lnet_rsp_tracker *rspt, *tmp;
2859         int i;
2860
2861         cfs_cpt_for_each(i, lnet_cpt_table()) {
2862                 list_for_each_entry_safe(rspt, tmp,
2863                                          the_lnet.ln_mt_zombie_rstqs[i],
2864                                          rspt_on_list) {
2865                         list_del(&rspt->rspt_on_list);
2866                         lnet_rspt_free(rspt, i);
2867                 }
2868         }
2869
2870         cfs_percpt_free(the_lnet.ln_mt_zombie_rstqs);
2871 }
2872
2873 static void
2874 lnet_finalize_expired_responses(void)
2875 {
2876         struct lnet_libmd *md;
2877         struct list_head local_queue;
2878         struct lnet_rsp_tracker *rspt, *tmp;
2879         ktime_t now;
2880         int i;
2881
2882         if (the_lnet.ln_mt_rstq == NULL)
2883                 return;
2884
2885         cfs_cpt_for_each(i, lnet_cpt_table()) {
2886                 INIT_LIST_HEAD(&local_queue);
2887
2888                 lnet_net_lock(i);
2889                 if (!the_lnet.ln_mt_rstq[i]) {
2890                         lnet_net_unlock(i);
2891                         continue;
2892                 }
2893                 list_splice_init(the_lnet.ln_mt_rstq[i], &local_queue);
2894                 lnet_net_unlock(i);
2895
2896                 now = ktime_get();
2897
2898                 list_for_each_entry_safe(rspt, tmp, &local_queue, rspt_on_list) {
2899                         /*
2900                          * The rspt mdh will be invalidated when a response
2901                          * is received or whenever we want to discard the
2902                          * block the monitor thread will walk the queue
2903                          * and clean up any rsts with an invalid mdh.
2904                          * The monitor thread will walk the queue until
2905                          * the first unexpired rspt block. This means that
2906                          * some rspt blocks which received their
2907                          * corresponding responses will linger in the
2908                          * queue until they are cleaned up eventually.
2909                          */
2910                         lnet_res_lock(i);
2911                         if (LNetMDHandleIsInvalid(rspt->rspt_mdh)) {
2912                                 lnet_res_unlock(i);
2913                                 list_del(&rspt->rspt_on_list);
2914                                 lnet_rspt_free(rspt, i);
2915                                 continue;
2916                         }
2917
2918                         if (ktime_compare(now, rspt->rspt_deadline) >= 0 ||
2919                             the_lnet.ln_mt_state == LNET_MT_STATE_SHUTDOWN) {
2920                                 struct lnet_peer_ni *lpni;
2921                                 lnet_nid_t nid;
2922
2923                                 md = lnet_handle2md(&rspt->rspt_mdh);
2924                                 if (!md) {
2925                                         /* MD has been queued for unlink, but
2926                                          * rspt hasn't been detached (Note we've
2927                                          * checked above that the rspt_mdh is
2928                                          * valid). Since we cannot lookup the MD
2929                                          * we're unable to detach the rspt
2930                                          * ourselves. Thus, move the rspt to the
2931                                          * zombie list where we'll wait for
2932                                          * either:
2933                                          *   1. The remaining operations on the
2934                                          *   MD to complete. In this case the
2935                                          *   final operation will result in
2936                                          *   lnet_msg_detach_md()->
2937                                          *   lnet_detach_rsp_tracker() where
2938                                          *   we will clean up this response
2939                                          *   tracker.
2940                                          *   2. LNet to shutdown. In this case
2941                                          *   we'll wait until after all LND Nets
2942                                          *   have shutdown and then we can
2943                                          *   safely free any remaining response
2944                                          *   tracker blocks on the zombie list.
2945                                          * Note: We need to hold the resource
2946                                          * lock when adding to the zombie list
2947                                          * because we may have concurrent access
2948                                          * with lnet_detach_rsp_tracker().
2949                                          */
2950                                         LNetInvalidateMDHandle(&rspt->rspt_mdh);
2951                                         list_move(&rspt->rspt_on_list,
2952                                                   the_lnet.ln_mt_zombie_rstqs[i]);
2953                                         lnet_res_unlock(i);
2954                                         continue;
2955                                 }
2956                                 LASSERT(md->md_rspt_ptr == rspt);
2957                                 md->md_rspt_ptr = NULL;
2958                                 lnet_res_unlock(i);
2959
2960                                 LNetMDUnlink(rspt->rspt_mdh);
2961
2962                                 nid = rspt->rspt_next_hop_nid;
2963
2964                                 list_del(&rspt->rspt_on_list);
2965                                 lnet_rspt_free(rspt, i);
2966
2967                                 /* If we're shutting down we just want to clean
2968                                  * up the rspt blocks
2969                                  */
2970                                 if (the_lnet.ln_mt_state == LNET_MT_STATE_SHUTDOWN)
2971                                         continue;
2972
2973                                 lnet_net_lock(i);
2974                                 the_lnet.ln_counters[i]->lct_health.lch_response_timeout_count++;
2975                                 lnet_net_unlock(i);
2976
2977                                 CDEBUG(D_NET,
2978                                        "Response timeout: md = %p: nid = %s\n",
2979                                        md, libcfs_nid2str(nid));
2980
2981                                 /*
2982                                  * If there is a timeout on the response
2983                                  * from the next hop decrement its health
2984                                  * value so that we don't use it
2985                                  */
2986                                 lnet_net_lock(0);
2987                                 lpni = lnet_find_peer_ni_locked(nid);
2988                                 if (lpni) {
2989                                         lnet_handle_remote_failure_locked(lpni);
2990                                         lnet_peer_ni_decref_locked(lpni);
2991                                 }
2992                                 lnet_net_unlock(0);
2993                         } else {
2994                                 lnet_res_unlock(i);
2995                                 break;
2996                         }
2997                 }
2998
2999                 if (!list_empty(&local_queue)) {
3000                         lnet_net_lock(i);
3001                         list_splice(&local_queue, the_lnet.ln_mt_rstq[i]);
3002                         lnet_net_unlock(i);
3003                 }
3004         }
3005 }
3006
3007 static void
3008 lnet_resend_pending_msgs_locked(struct list_head *resendq, int cpt)
3009 {
3010         struct lnet_msg *msg;
3011
3012         while (!list_empty(resendq)) {
3013                 struct lnet_peer_ni *lpni;
3014
3015                 msg = list_entry(resendq->next, struct lnet_msg,
3016                                  msg_list);
3017
3018                 list_del_init(&msg->msg_list);
3019
3020                 lpni = lnet_find_peer_ni_locked(msg->msg_hdr.dest_nid);
3021                 if (!lpni) {
3022                         lnet_net_unlock(cpt);
3023                         CERROR("Expected that a peer is already created for %s\n",
3024                                libcfs_nid2str(msg->msg_hdr.dest_nid));
3025                         msg->msg_no_resend = true;
3026                         lnet_finalize(msg, -EFAULT);
3027                         lnet_net_lock(cpt);
3028                 } else {
3029                         struct lnet_peer *peer;
3030                         int rc;
3031                         lnet_nid_t src_nid = LNET_NID_ANY;
3032
3033                         /*
3034                          * if this message is not being routed and the
3035                          * peer is non-MR then we must use the same
3036                          * src_nid that was used in the original send.
3037                          * Otherwise if we're routing the message (IE
3038                          * we're a router) then we can use any of our
3039                          * local interfaces. It doesn't matter to the
3040                          * final destination.
3041                          */
3042                         peer = lpni->lpni_peer_net->lpn_peer;
3043                         if (!msg->msg_routing &&
3044                             !lnet_peer_is_multi_rail(peer))
3045                                 src_nid = le64_to_cpu(msg->msg_hdr.src_nid);
3046
3047                         /*
3048                          * If we originally specified a src NID, then we
3049                          * must attempt to reuse it in the resend as well.
3050                          */
3051                         if (msg->msg_src_nid_param != LNET_NID_ANY)
3052                                 src_nid = msg->msg_src_nid_param;
3053                         lnet_peer_ni_decref_locked(lpni);
3054
3055                         lnet_net_unlock(cpt);
3056                         CDEBUG(D_NET, "resending %s->%s: %s recovery %d try# %d\n",
3057                                libcfs_nid2str(src_nid),
3058                                libcfs_id2str(msg->msg_target),
3059                                lnet_msgtyp2str(msg->msg_type),
3060                                msg->msg_recovery,
3061                                msg->msg_retry_count);
3062                         rc = lnet_send(src_nid, msg, LNET_NID_ANY);
3063                         if (rc) {
3064                                 CERROR("Error sending %s to %s: %d\n",
3065                                        lnet_msgtyp2str(msg->msg_type),
3066                                        libcfs_id2str(msg->msg_target), rc);
3067                                 msg->msg_no_resend = true;
3068                                 lnet_finalize(msg, rc);
3069                         }
3070                         lnet_net_lock(cpt);
3071                         if (!rc)
3072                                 the_lnet.ln_counters[cpt]->lct_health.lch_resend_count++;
3073                 }
3074         }
3075 }
3076
3077 static void
3078 lnet_resend_pending_msgs(void)
3079 {
3080         int i;
3081
3082         cfs_cpt_for_each(i, lnet_cpt_table()) {
3083                 lnet_net_lock(i);
3084                 lnet_resend_pending_msgs_locked(the_lnet.ln_mt_resendqs[i], i);
3085                 lnet_net_unlock(i);
3086         }
3087 }
3088
3089 /* called with cpt and ni_lock held */
3090 static void
3091 lnet_unlink_ni_recovery_mdh_locked(struct lnet_ni *ni, int cpt, bool force)
3092 {
3093         struct lnet_handle_md recovery_mdh;
3094
3095         LNetInvalidateMDHandle(&recovery_mdh);
3096
3097         if (ni->ni_recovery_state & LNET_NI_RECOVERY_PENDING ||
3098             force) {
3099                 recovery_mdh = ni->ni_ping_mdh;
3100                 LNetInvalidateMDHandle(&ni->ni_ping_mdh);
3101         }
3102         lnet_ni_unlock(ni);
3103         lnet_net_unlock(cpt);
3104         if (!LNetMDHandleIsInvalid(recovery_mdh))
3105                 LNetMDUnlink(recovery_mdh);
3106         lnet_net_lock(cpt);
3107         lnet_ni_lock(ni);
3108 }
3109
3110 static void
3111 lnet_recover_local_nis(void)
3112 {
3113         struct lnet_mt_event_info *ev_info;
3114         struct list_head processed_list;
3115         struct list_head local_queue;
3116         struct lnet_handle_md mdh;
3117         struct lnet_ni *tmp;
3118         struct lnet_ni *ni;
3119         lnet_nid_t nid;
3120         int healthv;
3121         int rc;
3122
3123         INIT_LIST_HEAD(&local_queue);
3124         INIT_LIST_HEAD(&processed_list);
3125
3126         /*
3127          * splice the recovery queue on a local queue. We will iterate
3128          * through the local queue and update it as needed. Once we're
3129          * done with the traversal, we'll splice the local queue back on
3130          * the head of the ln_mt_localNIRecovq. Any newly added local NIs
3131          * will be traversed in the next iteration.
3132          */
3133         lnet_net_lock(0);
3134         list_splice_init(&the_lnet.ln_mt_localNIRecovq,
3135                          &local_queue);
3136         lnet_net_unlock(0);
3137
3138         list_for_each_entry_safe(ni, tmp, &local_queue, ni_recovery) {
3139                 /*
3140                  * if an NI is being deleted or it is now healthy, there
3141                  * is no need to keep it around in the recovery queue.
3142                  * The monitor thread is the only thread responsible for
3143                  * removing the NI from the recovery queue.
3144                  * Multiple threads can be adding NIs to the recovery
3145                  * queue.
3146                  */
3147                 healthv = atomic_read(&ni->ni_healthv);
3148
3149                 lnet_net_lock(0);
3150                 lnet_ni_lock(ni);
3151                 if (ni->ni_state != LNET_NI_STATE_ACTIVE ||
3152                     healthv == LNET_MAX_HEALTH_VALUE) {
3153                         list_del_init(&ni->ni_recovery);
3154                         lnet_unlink_ni_recovery_mdh_locked(ni, 0, false);
3155                         lnet_ni_unlock(ni);
3156                         lnet_ni_decref_locked(ni, 0);
3157                         lnet_net_unlock(0);
3158                         continue;
3159                 }
3160
3161                 /*
3162                  * if the local NI failed recovery we must unlink the md.
3163                  * But we want to keep the local_ni on the recovery queue
3164                  * so we can continue the attempts to recover it.
3165                  */
3166                 if (ni->ni_recovery_state & LNET_NI_RECOVERY_FAILED) {
3167                         lnet_unlink_ni_recovery_mdh_locked(ni, 0, true);
3168                         ni->ni_recovery_state &= ~LNET_NI_RECOVERY_FAILED;
3169                 }
3170
3171                 lnet_ni_unlock(ni);
3172                 lnet_net_unlock(0);
3173
3174
3175                 CDEBUG(D_NET, "attempting to recover local ni: %s\n",
3176                        libcfs_nid2str(ni->ni_nid));
3177
3178                 lnet_ni_lock(ni);
3179                 if (!(ni->ni_recovery_state & LNET_NI_RECOVERY_PENDING)) {
3180                         ni->ni_recovery_state |= LNET_NI_RECOVERY_PENDING;
3181                         lnet_ni_unlock(ni);
3182
3183                         LIBCFS_ALLOC(ev_info, sizeof(*ev_info));
3184                         if (!ev_info) {
3185                                 CERROR("out of memory. Can't recover %s\n",
3186                                        libcfs_nid2str(ni->ni_nid));
3187                                 lnet_ni_lock(ni);
3188                                 ni->ni_recovery_state &=
3189                                   ~LNET_NI_RECOVERY_PENDING;
3190                                 lnet_ni_unlock(ni);
3191                                 continue;
3192                         }
3193
3194                         mdh = ni->ni_ping_mdh;
3195                         /*
3196                          * Invalidate the ni mdh in case it's deleted.
3197                          * We'll unlink the mdh in this case below.
3198                          */
3199                         LNetInvalidateMDHandle(&ni->ni_ping_mdh);
3200                         nid = ni->ni_nid;
3201
3202                         /*
3203                          * remove the NI from the local queue and drop the
3204                          * reference count to it while we're recovering
3205                          * it. The reason for that, is that the NI could
3206                          * be deleted, and the way the code is structured
3207                          * is if we don't drop the NI, then the deletion
3208                          * code will enter a loop waiting for the
3209                          * reference count to be removed while holding the
3210                          * ln_mutex_lock(). When we look up the peer to
3211                          * send to in lnet_select_pathway() we will try to
3212                          * lock the ln_mutex_lock() as well, leading to
3213                          * a deadlock. By dropping the refcount and
3214                          * removing it from the list, we allow for the NI
3215                          * to be removed, then we use the cached NID to
3216                          * look it up again. If it's gone, then we just
3217                          * continue examining the rest of the queue.
3218                          */
3219                         lnet_net_lock(0);
3220                         list_del_init(&ni->ni_recovery);
3221                         lnet_ni_decref_locked(ni, 0);
3222                         lnet_net_unlock(0);
3223
3224                         ev_info->mt_type = MT_TYPE_LOCAL_NI;
3225                         ev_info->mt_nid = nid;
3226                         rc = lnet_send_ping(nid, &mdh, LNET_INTERFACES_MIN,
3227                                             ev_info, the_lnet.ln_mt_eqh, true);
3228                         /* lookup the nid again */
3229                         lnet_net_lock(0);
3230                         ni = lnet_nid2ni_locked(nid, 0);
3231                         if (!ni) {
3232                                 /*
3233                                  * the NI has been deleted when we dropped
3234                                  * the ref count
3235                                  */
3236                                 lnet_net_unlock(0);
3237                                 LNetMDUnlink(mdh);
3238                                 continue;
3239                         }
3240                         /*
3241                          * Same note as in lnet_recover_peer_nis(). When
3242                          * we're sending the ping, the NI is free to be
3243                          * deleted or manipulated. By this point it
3244                          * could've been added back on the recovery queue,
3245                          * and a refcount taken on it.
3246                          * So we can't just add it blindly again or we'll
3247                          * corrupt the queue. We must check under lock if
3248                          * it's not on any list and if not then add it
3249                          * to the processed list, which will eventually be
3250                          * spliced back on to the recovery queue.
3251                          */
3252                         ni->ni_ping_mdh = mdh;
3253                         if (list_empty(&ni->ni_recovery)) {
3254                                 list_add_tail(&ni->ni_recovery, &processed_list);
3255                                 lnet_ni_addref_locked(ni, 0);
3256                         }
3257                         lnet_net_unlock(0);
3258
3259                         lnet_ni_lock(ni);
3260                         if (rc)
3261                                 ni->ni_recovery_state &= ~LNET_NI_RECOVERY_PENDING;
3262                 }
3263                 lnet_ni_unlock(ni);
3264         }
3265
3266         /*
3267          * put back the remaining NIs on the ln_mt_localNIRecovq to be
3268          * reexamined in the next iteration.
3269          */
3270         list_splice_init(&processed_list, &local_queue);
3271         lnet_net_lock(0);
3272         list_splice(&local_queue, &the_lnet.ln_mt_localNIRecovq);
3273         lnet_net_unlock(0);
3274 }
3275
3276 static int
3277 lnet_resendqs_create(void)
3278 {
3279         struct list_head **resendqs;
3280         resendqs = lnet_create_array_of_queues();
3281
3282         if (!resendqs)
3283                 return -ENOMEM;
3284
3285         lnet_net_lock(LNET_LOCK_EX);
3286         the_lnet.ln_mt_resendqs = resendqs;
3287         lnet_net_unlock(LNET_LOCK_EX);
3288
3289         return 0;
3290 }
3291
3292 static void
3293 lnet_clean_local_ni_recoveryq(void)
3294 {
3295         struct lnet_ni *ni;
3296
3297         /* This is only called when the monitor thread has stopped */
3298         lnet_net_lock(0);
3299
3300         while (!list_empty(&the_lnet.ln_mt_localNIRecovq)) {
3301                 ni = list_entry(the_lnet.ln_mt_localNIRecovq.next,
3302                                 struct lnet_ni, ni_recovery);
3303                 list_del_init(&ni->ni_recovery);
3304                 lnet_ni_lock(ni);
3305                 lnet_unlink_ni_recovery_mdh_locked(ni, 0, true);
3306                 lnet_ni_unlock(ni);
3307                 lnet_ni_decref_locked(ni, 0);
3308         }
3309
3310         lnet_net_unlock(0);
3311 }
3312
3313 static void
3314 lnet_unlink_lpni_recovery_mdh_locked(struct lnet_peer_ni *lpni, int cpt,
3315                                      bool force)
3316 {
3317         struct lnet_handle_md recovery_mdh;
3318
3319         LNetInvalidateMDHandle(&recovery_mdh);
3320
3321         if (lpni->lpni_state & LNET_PEER_NI_RECOVERY_PENDING || force) {
3322                 recovery_mdh = lpni->lpni_recovery_ping_mdh;
3323                 LNetInvalidateMDHandle(&lpni->lpni_recovery_ping_mdh);
3324         }
3325         spin_unlock(&lpni->lpni_lock);
3326         lnet_net_unlock(cpt);
3327         if (!LNetMDHandleIsInvalid(recovery_mdh))
3328                 LNetMDUnlink(recovery_mdh);
3329         lnet_net_lock(cpt);
3330         spin_lock(&lpni->lpni_lock);
3331 }
3332
3333 static void
3334 lnet_clean_peer_ni_recoveryq(void)
3335 {
3336         struct lnet_peer_ni *lpni, *tmp;
3337
3338         lnet_net_lock(LNET_LOCK_EX);
3339
3340         list_for_each_entry_safe(lpni, tmp, &the_lnet.ln_mt_peerNIRecovq,
3341                                  lpni_recovery) {
3342                 list_del_init(&lpni->lpni_recovery);
3343                 spin_lock(&lpni->lpni_lock);
3344                 lnet_unlink_lpni_recovery_mdh_locked(lpni, LNET_LOCK_EX, true);
3345                 spin_unlock(&lpni->lpni_lock);
3346                 lnet_peer_ni_decref_locked(lpni);
3347         }
3348
3349         lnet_net_unlock(LNET_LOCK_EX);
3350 }
3351
3352 static void
3353 lnet_clean_resendqs(void)
3354 {
3355         struct lnet_msg *msg, *tmp;
3356         struct list_head msgs;
3357         int i;
3358
3359         INIT_LIST_HEAD(&msgs);
3360
3361         cfs_cpt_for_each(i, lnet_cpt_table()) {
3362                 lnet_net_lock(i);
3363                 list_splice_init(the_lnet.ln_mt_resendqs[i], &msgs);
3364                 lnet_net_unlock(i);
3365                 list_for_each_entry_safe(msg, tmp, &msgs, msg_list) {
3366                         list_del_init(&msg->msg_list);
3367                         msg->msg_no_resend = true;
3368                         lnet_finalize(msg, -ESHUTDOWN);
3369                 }
3370         }
3371
3372         cfs_percpt_free(the_lnet.ln_mt_resendqs);
3373 }
3374
3375 static void
3376 lnet_recover_peer_nis(void)
3377 {
3378         struct lnet_mt_event_info *ev_info;
3379         struct list_head processed_list;
3380         struct list_head local_queue;
3381         struct lnet_handle_md mdh;
3382         struct lnet_peer_ni *lpni;
3383         struct lnet_peer_ni *tmp;
3384         lnet_nid_t nid;
3385         int healthv;
3386         int rc;
3387
3388         INIT_LIST_HEAD(&local_queue);
3389         INIT_LIST_HEAD(&processed_list);
3390
3391         /*
3392          * Always use cpt 0 for locking across all interactions with
3393          * ln_mt_peerNIRecovq
3394          */
3395         lnet_net_lock(0);
3396         list_splice_init(&the_lnet.ln_mt_peerNIRecovq,
3397                          &local_queue);
3398         lnet_net_unlock(0);
3399
3400         list_for_each_entry_safe(lpni, tmp, &local_queue,
3401                                  lpni_recovery) {
3402                 /*
3403                  * The same protection strategy is used here as is in the
3404                  * local recovery case.
3405                  */
3406                 lnet_net_lock(0);
3407                 healthv = atomic_read(&lpni->lpni_healthv);
3408                 spin_lock(&lpni->lpni_lock);
3409                 if (lpni->lpni_state & LNET_PEER_NI_DELETING ||
3410                     healthv == LNET_MAX_HEALTH_VALUE) {
3411                         list_del_init(&lpni->lpni_recovery);
3412                         lnet_unlink_lpni_recovery_mdh_locked(lpni, 0, false);
3413                         spin_unlock(&lpni->lpni_lock);
3414                         lnet_peer_ni_decref_locked(lpni);
3415                         lnet_net_unlock(0);
3416                         continue;
3417                 }
3418
3419                 /*
3420                  * If the peer NI has failed recovery we must unlink the
3421                  * md. But we want to keep the peer ni on the recovery
3422                  * queue so we can try to continue recovering it
3423                  */
3424                 if (lpni->lpni_state & LNET_PEER_NI_RECOVERY_FAILED) {
3425                         lnet_unlink_lpni_recovery_mdh_locked(lpni, 0, true);
3426                         lpni->lpni_state &= ~LNET_PEER_NI_RECOVERY_FAILED;
3427                 }
3428
3429                 spin_unlock(&lpni->lpni_lock);
3430                 lnet_net_unlock(0);
3431
3432                 /*
3433                  * NOTE: we're racing with peer deletion from user space.
3434                  * It's possible that a peer is deleted after we check its
3435                  * state. In this case the recovery can create a new peer
3436                  */
3437                 spin_lock(&lpni->lpni_lock);
3438                 if (!(lpni->lpni_state & LNET_PEER_NI_RECOVERY_PENDING) &&
3439                     !(lpni->lpni_state & LNET_PEER_NI_DELETING)) {
3440                         lpni->lpni_state |= LNET_PEER_NI_RECOVERY_PENDING;
3441                         spin_unlock(&lpni->lpni_lock);
3442
3443                         LIBCFS_ALLOC(ev_info, sizeof(*ev_info));
3444                         if (!ev_info) {
3445                                 CERROR("out of memory. Can't recover %s\n",
3446                                        libcfs_nid2str(lpni->lpni_nid));
3447                                 spin_lock(&lpni->lpni_lock);
3448                                 lpni->lpni_state &= ~LNET_PEER_NI_RECOVERY_PENDING;
3449                                 spin_unlock(&lpni->lpni_lock);
3450                                 continue;
3451                         }
3452
3453                         /* look at the comments in lnet_recover_local_nis() */
3454                         mdh = lpni->lpni_recovery_ping_mdh;
3455                         LNetInvalidateMDHandle(&lpni->lpni_recovery_ping_mdh);
3456                         nid = lpni->lpni_nid;
3457                         lnet_net_lock(0);
3458                         list_del_init(&lpni->lpni_recovery);
3459                         lnet_peer_ni_decref_locked(lpni);
3460                         lnet_net_unlock(0);
3461
3462                         ev_info->mt_type = MT_TYPE_PEER_NI;
3463                         ev_info->mt_nid = nid;
3464                         rc = lnet_send_ping(nid, &mdh, LNET_INTERFACES_MIN,
3465                                             ev_info, the_lnet.ln_mt_eqh, true);
3466                         lnet_net_lock(0);
3467                         /*
3468                          * lnet_find_peer_ni_locked() grabs a refcount for
3469                          * us. No need to take it explicitly.
3470                          */
3471                         lpni = lnet_find_peer_ni_locked(nid);
3472                         if (!lpni) {
3473                                 lnet_net_unlock(0);
3474                                 LNetMDUnlink(mdh);
3475                                 continue;
3476                         }
3477
3478                         lpni->lpni_recovery_ping_mdh = mdh;
3479                         /*
3480                          * While we're unlocked the lpni could've been
3481                          * readded on the recovery queue. In this case we
3482                          * don't need to add it to the local queue, since
3483                          * it's already on there and the thread that added
3484                          * it would've incremented the refcount on the
3485                          * peer, which means we need to decref the refcount
3486                          * that was implicitly grabbed by find_peer_ni_locked.
3487                          * Otherwise, if the lpni is still not on
3488                          * the recovery queue, then we'll add it to the
3489                          * processed list.
3490                          */
3491                         if (list_empty(&lpni->lpni_recovery))
3492                                 list_add_tail(&lpni->lpni_recovery, &processed_list);
3493                         else
3494                                 lnet_peer_ni_decref_locked(lpni);
3495                         lnet_net_unlock(0);
3496
3497                         spin_lock(&lpni->lpni_lock);
3498                         if (rc)
3499                                 lpni->lpni_state &= ~LNET_PEER_NI_RECOVERY_PENDING;
3500                 }
3501                 spin_unlock(&lpni->lpni_lock);
3502         }
3503
3504         list_splice_init(&processed_list, &local_queue);
3505         lnet_net_lock(0);
3506         list_splice(&local_queue, &the_lnet.ln_mt_peerNIRecovq);
3507         lnet_net_unlock(0);
3508 }
3509
3510 static int
3511 lnet_monitor_thread(void *arg)
3512 {
3513         time64_t recovery_timeout = 0;
3514         time64_t rsp_timeout = 0;
3515         int interval;
3516         time64_t now;
3517
3518         wait_for_completion(&the_lnet.ln_started);
3519         /*
3520          * The monitor thread takes care of the following:
3521          *  1. Checks the aliveness of routers
3522          *  2. Checks if there are messages on the resend queue to resend
3523          *     them.
3524          *  3. Check if there are any NIs on the local recovery queue and
3525          *     pings them
3526          *  4. Checks if there are any NIs on the remote recovery queue
3527          *     and pings them.
3528          */
3529         cfs_block_allsigs();
3530
3531         while (the_lnet.ln_mt_state == LNET_MT_STATE_RUNNING) {
3532                 now = ktime_get_real_seconds();
3533
3534                 if (lnet_router_checker_active())
3535                         lnet_check_routers();
3536
3537                 lnet_resend_pending_msgs();
3538
3539                 if (now >= rsp_timeout) {
3540                         lnet_finalize_expired_responses();
3541                         rsp_timeout = now + (lnet_transaction_timeout / 2);
3542                 }
3543
3544                 if (now >= recovery_timeout) {
3545                         lnet_recover_local_nis();
3546                         lnet_recover_peer_nis();
3547                         recovery_timeout = now + lnet_recovery_interval;
3548                 }
3549
3550                 /*
3551                  * TODO do we need to check if we should sleep without
3552                  * timeout?  Technically, an active system will always
3553                  * have messages in flight so this check will always
3554                  * evaluate to false. And on an idle system do we care
3555                  * if we wake up every 1 second? Although, we've seen
3556                  * cases where we get a complaint that an idle thread
3557                  * is waking up unnecessarily.
3558                  *
3559                  * Take into account the current net_count when you wake
3560                  * up for alive router checking, since we need to check
3561                  * possibly as many networks as we have configured.
3562                  */
3563                 interval = min(lnet_recovery_interval,
3564                                min((unsigned int) alive_router_check_interval /
3565                                         lnet_current_net_count,
3566                                    lnet_transaction_timeout / 2));
3567                 wait_for_completion_interruptible_timeout(
3568                         &the_lnet.ln_mt_wait_complete,
3569                         cfs_time_seconds(interval));
3570                 /* Must re-init the completion before testing anything,
3571                  * including ln_mt_state.
3572                  */
3573                 reinit_completion(&the_lnet.ln_mt_wait_complete);
3574         }
3575
3576         /* Shutting down */
3577         lnet_net_lock(LNET_LOCK_EX);
3578         the_lnet.ln_mt_state = LNET_MT_STATE_SHUTDOWN;
3579         lnet_net_unlock(LNET_LOCK_EX);
3580
3581         /* signal that the monitor thread is exiting */
3582         up(&the_lnet.ln_mt_signal);
3583
3584         return 0;
3585 }
3586
3587 /*
3588  * lnet_send_ping
3589  * Sends a ping.
3590  * Returns == 0 if success
3591  * Returns > 0 if LNetMDBind or prior fails
3592  * Returns < 0 if LNetGet fails
3593  */
3594 int
3595 lnet_send_ping(lnet_nid_t dest_nid,
3596                struct lnet_handle_md *mdh, int nnis,
3597                void *user_data, struct lnet_handle_eq eqh, bool recovery)
3598 {
3599         struct lnet_md md = { NULL };
3600         struct lnet_process_id id;
3601         struct lnet_ping_buffer *pbuf;
3602         int rc;
3603
3604         if (dest_nid == LNET_NID_ANY) {
3605                 rc = -EHOSTUNREACH;
3606                 goto fail_error;
3607         }
3608
3609         pbuf = lnet_ping_buffer_alloc(nnis, GFP_NOFS);
3610         if (!pbuf) {
3611                 rc = ENOMEM;
3612                 goto fail_error;
3613         }
3614
3615         /* initialize md content */
3616         md.start     = &pbuf->pb_info;
3617         md.length    = LNET_PING_INFO_SIZE(nnis);
3618         md.threshold = 2; /* GET/REPLY */
3619         md.max_size  = 0;
3620         md.options   = LNET_MD_TRUNCATE;
3621         md.user_ptr  = user_data;
3622         md.eq_handle = eqh;
3623
3624         rc = LNetMDBind(md, LNET_UNLINK, mdh);
3625         if (rc) {
3626                 lnet_ping_buffer_decref(pbuf);
3627                 CERROR("Can't bind MD: %d\n", rc);
3628                 rc = -rc; /* change the rc to positive */
3629                 goto fail_error;
3630         }
3631         id.pid = LNET_PID_LUSTRE;
3632         id.nid = dest_nid;
3633
3634         rc = LNetGet(LNET_NID_ANY, *mdh, id,
3635                      LNET_RESERVED_PORTAL,
3636                      LNET_PROTO_PING_MATCHBITS, 0, recovery);
3637
3638         if (rc)
3639                 goto fail_unlink_md;
3640
3641         return 0;
3642
3643 fail_unlink_md:
3644         LNetMDUnlink(*mdh);
3645         LNetInvalidateMDHandle(mdh);
3646 fail_error:
3647         return rc;
3648 }
3649
3650 static void
3651 lnet_handle_recovery_reply(struct lnet_mt_event_info *ev_info,
3652                            int status, bool unlink_event)
3653 {
3654         lnet_nid_t nid = ev_info->mt_nid;
3655
3656         if (ev_info->mt_type == MT_TYPE_LOCAL_NI) {
3657                 struct lnet_ni *ni;
3658
3659                 lnet_net_lock(0);
3660                 ni = lnet_nid2ni_locked(nid, 0);
3661                 if (!ni) {
3662                         lnet_net_unlock(0);
3663                         return;
3664                 }
3665                 lnet_ni_lock(ni);
3666                 ni->ni_recovery_state &= ~LNET_NI_RECOVERY_PENDING;
3667                 if (status)
3668                         ni->ni_recovery_state |= LNET_NI_RECOVERY_FAILED;
3669                 lnet_ni_unlock(ni);
3670                 lnet_net_unlock(0);
3671
3672                 if (status != 0) {
3673                         CERROR("local NI (%s) recovery failed with %d\n",
3674                                libcfs_nid2str(nid), status);
3675                         return;
3676                 }
3677                 /*
3678                  * need to increment healthv for the ni here, because in
3679                  * the lnet_finalize() path we don't have access to this
3680                  * NI. And in order to get access to it, we'll need to
3681                  * carry forward too much information.
3682                  * In the peer case, it'll naturally be incremented
3683                  */
3684                 if (!unlink_event)
3685                         lnet_inc_healthv(&ni->ni_healthv);
3686         } else {
3687                 struct lnet_peer_ni *lpni;
3688                 int cpt;
3689
3690                 cpt = lnet_net_lock_current();
3691                 lpni = lnet_find_peer_ni_locked(nid);
3692                 if (!lpni) {
3693                         lnet_net_unlock(cpt);
3694                         return;
3695                 }
3696                 spin_lock(&lpni->lpni_lock);
3697                 lpni->lpni_state &= ~LNET_PEER_NI_RECOVERY_PENDING;
3698                 if (status)
3699                         lpni->lpni_state |= LNET_PEER_NI_RECOVERY_FAILED;
3700                 spin_unlock(&lpni->lpni_lock);
3701                 lnet_peer_ni_decref_locked(lpni);
3702                 lnet_net_unlock(cpt);
3703
3704                 if (status != 0)
3705                         CERROR("peer NI (%s) recovery failed with %d\n",
3706                                libcfs_nid2str(nid), status);
3707         }
3708 }
3709
3710 void
3711 lnet_mt_event_handler(struct lnet_event *event)
3712 {
3713         struct lnet_mt_event_info *ev_info = event->md.user_ptr;
3714         struct lnet_ping_buffer *pbuf;
3715
3716         /* TODO: remove assert */
3717         LASSERT(event->type == LNET_EVENT_REPLY ||
3718                 event->type == LNET_EVENT_SEND ||
3719                 event->type == LNET_EVENT_UNLINK);
3720
3721         CDEBUG(D_NET, "Received event: %d status: %d\n", event->type,
3722                event->status);
3723
3724         switch (event->type) {
3725         case LNET_EVENT_UNLINK:
3726                 CDEBUG(D_NET, "%s recovery ping unlinked\n",
3727                        libcfs_nid2str(ev_info->mt_nid));
3728                 /* fallthrough */
3729         case LNET_EVENT_REPLY:
3730                 lnet_handle_recovery_reply(ev_info, event->status,
3731                                            event->type == LNET_EVENT_UNLINK);
3732                 break;
3733         case LNET_EVENT_SEND:
3734                 CDEBUG(D_NET, "%s recovery message sent %s:%d\n",
3735                                libcfs_nid2str(ev_info->mt_nid),
3736                                (event->status) ? "unsuccessfully" :
3737                                "successfully", event->status);
3738                 break;
3739         default:
3740                 CERROR("Unexpected event: %d\n", event->type);
3741                 break;
3742         }
3743         if (event->unlinked) {
3744                 LIBCFS_FREE(ev_info, sizeof(*ev_info));
3745                 pbuf = LNET_PING_INFO_TO_BUFFER(event->md.start);
3746                 lnet_ping_buffer_decref(pbuf);
3747         }
3748 }
3749
3750 static int
3751 lnet_rsp_tracker_create(void)
3752 {
3753         struct list_head **rstqs;
3754         rstqs = lnet_create_array_of_queues();
3755
3756         if (!rstqs)
3757                 return -ENOMEM;
3758
3759         the_lnet.ln_mt_rstq = rstqs;
3760
3761         return 0;
3762 }
3763
3764 static void
3765 lnet_rsp_tracker_clean(void)
3766 {
3767         lnet_finalize_expired_responses();
3768
3769         cfs_percpt_free(the_lnet.ln_mt_rstq);
3770         the_lnet.ln_mt_rstq = NULL;
3771 }
3772
3773 int lnet_monitor_thr_start(void)
3774 {
3775         int rc = 0;
3776         struct task_struct *task;
3777
3778         if (the_lnet.ln_mt_state != LNET_MT_STATE_SHUTDOWN)
3779                 return -EALREADY;
3780
3781         rc = lnet_resendqs_create();
3782         if (rc)
3783                 return rc;
3784
3785         rc = lnet_rsp_tracker_create();
3786         if (rc)
3787                 goto clean_queues;
3788
3789         sema_init(&the_lnet.ln_mt_signal, 0);
3790
3791         lnet_net_lock(LNET_LOCK_EX);
3792         the_lnet.ln_mt_state = LNET_MT_STATE_RUNNING;
3793         lnet_net_unlock(LNET_LOCK_EX);
3794         task = kthread_run(lnet_monitor_thread, NULL, "monitor_thread");
3795         if (IS_ERR(task)) {
3796                 rc = PTR_ERR(task);
3797                 CERROR("Can't start monitor thread: %d\n", rc);
3798                 goto clean_thread;
3799         }
3800
3801         return 0;
3802
3803 clean_thread:
3804         lnet_net_lock(LNET_LOCK_EX);
3805         the_lnet.ln_mt_state = LNET_MT_STATE_STOPPING;
3806         lnet_net_unlock(LNET_LOCK_EX);
3807         /* block until event callback signals exit */
3808         down(&the_lnet.ln_mt_signal);
3809         /* clean up */
3810         lnet_net_lock(LNET_LOCK_EX);
3811         the_lnet.ln_mt_state = LNET_MT_STATE_SHUTDOWN;
3812         lnet_net_unlock(LNET_LOCK_EX);
3813         lnet_rsp_tracker_clean();
3814         lnet_clean_local_ni_recoveryq();
3815         lnet_clean_peer_ni_recoveryq();
3816         lnet_clean_resendqs();
3817         LNetInvalidateEQHandle(&the_lnet.ln_mt_eqh);
3818         return rc;
3819 clean_queues:
3820         lnet_rsp_tracker_clean();
3821         lnet_clean_local_ni_recoveryq();
3822         lnet_clean_peer_ni_recoveryq();
3823         lnet_clean_resendqs();
3824         return rc;
3825 }
3826
3827 void lnet_monitor_thr_stop(void)
3828 {
3829         if (the_lnet.ln_mt_state == LNET_MT_STATE_SHUTDOWN)
3830                 return;
3831
3832         LASSERT(the_lnet.ln_mt_state == LNET_MT_STATE_RUNNING);
3833         lnet_net_lock(LNET_LOCK_EX);
3834         the_lnet.ln_mt_state = LNET_MT_STATE_STOPPING;
3835         lnet_net_unlock(LNET_LOCK_EX);
3836
3837         /* tell the monitor thread that we're shutting down */
3838         complete(&the_lnet.ln_mt_wait_complete);
3839
3840         /* block until monitor thread signals that it's done */
3841         down(&the_lnet.ln_mt_signal);
3842         LASSERT(the_lnet.ln_mt_state == LNET_MT_STATE_SHUTDOWN);
3843
3844         /* perform cleanup tasks */
3845         lnet_rsp_tracker_clean();
3846         lnet_clean_local_ni_recoveryq();
3847         lnet_clean_peer_ni_recoveryq();
3848         lnet_clean_resendqs();
3849 }
3850
3851 void
3852 lnet_drop_message(struct lnet_ni *ni, int cpt, void *private, unsigned int nob,
3853                   __u32 msg_type)
3854 {
3855         lnet_net_lock(cpt);
3856         lnet_incr_stats(&ni->ni_stats, msg_type, LNET_STATS_TYPE_DROP);
3857         the_lnet.ln_counters[cpt]->lct_common.lcc_drop_count++;
3858         the_lnet.ln_counters[cpt]->lct_common.lcc_drop_length += nob;
3859         lnet_net_unlock(cpt);
3860
3861         lnet_ni_recv(ni, private, NULL, 0, 0, 0, nob);
3862 }
3863
3864 static void
3865 lnet_recv_put(struct lnet_ni *ni, struct lnet_msg *msg)
3866 {
3867         struct lnet_hdr *hdr = &msg->msg_hdr;
3868
3869         if (msg->msg_wanted != 0)
3870                 lnet_setpayloadbuffer(msg);
3871
3872         lnet_build_msg_event(msg, LNET_EVENT_PUT);
3873
3874         /* Must I ACK?  If so I'll grab the ack_wmd out of the header and put
3875          * it back into the ACK during lnet_finalize() */
3876         msg->msg_ack = (!lnet_is_wire_handle_none(&hdr->msg.put.ack_wmd) &&
3877                         (msg->msg_md->md_options & LNET_MD_ACK_DISABLE) == 0);
3878
3879         lnet_ni_recv(ni, msg->msg_private, msg, msg->msg_rx_delayed,
3880                      msg->msg_offset, msg->msg_wanted, hdr->payload_length);
3881 }
3882
3883 static int
3884 lnet_parse_put(struct lnet_ni *ni, struct lnet_msg *msg)
3885 {
3886         struct lnet_hdr         *hdr = &msg->msg_hdr;
3887         struct lnet_match_info  info;
3888         int                     rc;
3889         bool                    ready_delay;
3890
3891         /* Convert put fields to host byte order */
3892         hdr->msg.put.match_bits = le64_to_cpu(hdr->msg.put.match_bits);
3893         hdr->msg.put.ptl_index  = le32_to_cpu(hdr->msg.put.ptl_index);
3894         hdr->msg.put.offset     = le32_to_cpu(hdr->msg.put.offset);
3895
3896         /* Primary peer NID. */
3897         info.mi_id.nid  = msg->msg_initiator;
3898         info.mi_id.pid  = hdr->src_pid;
3899         info.mi_opc     = LNET_MD_OP_PUT;
3900         info.mi_portal  = hdr->msg.put.ptl_index;
3901         info.mi_rlength = hdr->payload_length;
3902         info.mi_roffset = hdr->msg.put.offset;
3903         info.mi_mbits   = hdr->msg.put.match_bits;
3904         info.mi_cpt     = lnet_cpt_of_nid(msg->msg_initiator, ni);
3905
3906         msg->msg_rx_ready_delay = ni->ni_net->net_lnd->lnd_eager_recv == NULL;
3907         ready_delay = msg->msg_rx_ready_delay;
3908
3909  again:
3910         rc = lnet_ptl_match_md(&info, msg);
3911         switch (rc) {
3912         default:
3913                 LBUG();
3914
3915         case LNET_MATCHMD_OK:
3916                 lnet_recv_put(ni, msg);
3917                 return 0;
3918
3919         case LNET_MATCHMD_NONE:
3920                 if (ready_delay)
3921                         /* no eager_recv or has already called it, should
3922                          * have been attached on delayed list */
3923                         return 0;
3924
3925                 rc = lnet_ni_eager_recv(ni, msg);
3926                 if (rc == 0) {
3927                         ready_delay = true;
3928                         goto again;
3929                 }
3930                 /* fall through */
3931
3932         case LNET_MATCHMD_DROP:
3933                 CNETERR("Dropping PUT from %s portal %d match %llu"
3934                         " offset %d length %d: %d\n",
3935                         libcfs_id2str(info.mi_id), info.mi_portal,
3936                         info.mi_mbits, info.mi_roffset, info.mi_rlength, rc);
3937
3938                 return -ENOENT; /* -ve: OK but no match */
3939         }
3940 }
3941
3942 static int
3943 lnet_parse_get(struct lnet_ni *ni, struct lnet_msg *msg, int rdma_get)
3944 {
3945         struct lnet_match_info info;
3946         struct lnet_hdr *hdr = &msg->msg_hdr;
3947         struct lnet_process_id source_id;
3948         struct lnet_handle_wire reply_wmd;
3949         int rc;
3950
3951         /* Convert get fields to host byte order */
3952         hdr->msg.get.match_bits   = le64_to_cpu(hdr->msg.get.match_bits);
3953         hdr->msg.get.ptl_index    = le32_to_cpu(hdr->msg.get.ptl_index);
3954         hdr->msg.get.sink_length  = le32_to_cpu(hdr->msg.get.sink_length);
3955         hdr->msg.get.src_offset   = le32_to_cpu(hdr->msg.get.src_offset);
3956
3957         source_id.nid = hdr->src_nid;
3958         source_id.pid = hdr->src_pid;
3959         /* Primary peer NID */
3960         info.mi_id.nid  = msg->msg_initiator;
3961         info.mi_id.pid  = hdr->src_pid;
3962         info.mi_opc     = LNET_MD_OP_GET;
3963         info.mi_portal  = hdr->msg.get.ptl_index;
3964         info.mi_rlength = hdr->msg.get.sink_length;
3965         info.mi_roffset = hdr->msg.get.src_offset;
3966         info.mi_mbits   = hdr->msg.get.match_bits;
3967         info.mi_cpt     = lnet_cpt_of_nid(msg->msg_initiator, ni);
3968
3969         rc = lnet_ptl_match_md(&info, msg);
3970         if (rc == LNET_MATCHMD_DROP) {
3971                 CNETERR("Dropping GET from %s portal %d match %llu"
3972                         " offset %d length %d\n",
3973                         libcfs_id2str(info.mi_id), info.mi_portal,
3974                         info.mi_mbits, info.mi_roffset, info.mi_rlength);
3975                 return -ENOENT; /* -ve: OK but no match */
3976         }
3977
3978         LASSERT(rc == LNET_MATCHMD_OK);
3979
3980         lnet_build_msg_event(msg, LNET_EVENT_GET);
3981
3982         reply_wmd = hdr->msg.get.return_wmd;
3983
3984         lnet_prep_send(msg, LNET_MSG_REPLY, source_id,
3985                        msg->msg_offset, msg->msg_wanted);
3986
3987         msg->msg_hdr.msg.reply.dst_wmd = reply_wmd;
3988
3989         if (rdma_get) {
3990                 /* The LND completes the REPLY from her recv procedure */
3991                 lnet_ni_recv(ni, msg->msg_private, msg, 0,
3992                              msg->msg_offset, msg->msg_len, msg->msg_len);
3993                 return 0;
3994         }
3995
3996         lnet_ni_recv(ni, msg->msg_private, NULL, 0, 0, 0, 0);
3997         msg->msg_receiving = 0;
3998
3999         rc = lnet_send(ni->ni_nid, msg, msg->msg_from);
4000         if (rc < 0) {
4001                 /* didn't get as far as lnet_ni_send() */
4002                 CERROR("%s: Unable to send REPLY for GET from %s: %d\n",
4003                        libcfs_nid2str(ni->ni_nid),
4004                        libcfs_id2str(info.mi_id), rc);
4005
4006                 lnet_finalize(msg, rc);
4007         }
4008
4009         return 0;
4010 }
4011
4012 static int
4013 lnet_parse_reply(struct lnet_ni *ni, struct lnet_msg *msg)
4014 {
4015         void *private = msg->msg_private;
4016         struct lnet_hdr *hdr = &msg->msg_hdr;
4017         struct lnet_process_id src = {0};
4018         struct lnet_libmd *md;
4019         int rlength;
4020         int mlength;
4021         int cpt;
4022
4023         cpt = lnet_cpt_of_cookie(hdr->msg.reply.dst_wmd.wh_object_cookie);
4024         lnet_res_lock(cpt);
4025
4026         src.nid = hdr->src_nid;
4027         src.pid = hdr->src_pid;
4028
4029         /* NB handles only looked up by creator (no flips) */
4030         md = lnet_wire_handle2md(&hdr->msg.reply.dst_wmd);
4031         if (md == NULL || md->md_threshold == 0 || md->md_me != NULL) {
4032                 CNETERR("%s: Dropping REPLY from %s for %s "
4033                         "MD %#llx.%#llx\n",
4034                         libcfs_nid2str(ni->ni_nid), libcfs_id2str(src),
4035                         (md == NULL) ? "invalid" : "inactive",
4036                         hdr->msg.reply.dst_wmd.wh_interface_cookie,
4037                         hdr->msg.reply.dst_wmd.wh_object_cookie);
4038                 if (md != NULL && md->md_me != NULL)
4039                         CERROR("REPLY MD also attached to portal %d\n",
4040                                md->md_me->me_portal);
4041
4042                 lnet_res_unlock(cpt);
4043                 return -ENOENT; /* -ve: OK but no match */
4044         }
4045
4046         LASSERT(md->md_offset == 0);
4047
4048         rlength = hdr->payload_length;
4049         mlength = MIN(rlength, (int)md->md_length);
4050
4051         if (mlength < rlength &&
4052             (md->md_options & LNET_MD_TRUNCATE) == 0) {
4053                 CNETERR("%s: Dropping REPLY from %s length %d "
4054                         "for MD %#llx would overflow (%d)\n",
4055                         libcfs_nid2str(ni->ni_nid), libcfs_id2str(src),
4056                         rlength, hdr->msg.reply.dst_wmd.wh_object_cookie,
4057                         mlength);
4058                 lnet_res_unlock(cpt);
4059                 return -ENOENT; /* -ve: OK but no match */
4060         }
4061
4062         CDEBUG(D_NET, "%s: Reply from %s of length %d/%d into md %#llx\n",
4063                libcfs_nid2str(ni->ni_nid), libcfs_id2str(src),
4064                mlength, rlength, hdr->msg.reply.dst_wmd.wh_object_cookie);
4065
4066         lnet_msg_attach_md(msg, md, 0, mlength);
4067
4068         if (mlength != 0)
4069                 lnet_setpayloadbuffer(msg);
4070
4071         lnet_res_unlock(cpt);
4072
4073         lnet_build_msg_event(msg, LNET_EVENT_REPLY);
4074
4075         lnet_ni_recv(ni, private, msg, 0, 0, mlength, rlength);
4076         return 0;
4077 }
4078
4079 static int
4080 lnet_parse_ack(struct lnet_ni *ni, struct lnet_msg *msg)
4081 {
4082         struct lnet_hdr *hdr = &msg->msg_hdr;
4083         struct lnet_process_id src = {0};
4084         struct lnet_libmd *md;
4085         int cpt;
4086
4087         src.nid = hdr->src_nid;
4088         src.pid = hdr->src_pid;
4089
4090         /* Convert ack fields to host byte order */
4091         hdr->msg.ack.match_bits = le64_to_cpu(hdr->msg.ack.match_bits);
4092         hdr->msg.ack.mlength = le32_to_cpu(hdr->msg.ack.mlength);
4093
4094         cpt = lnet_cpt_of_cookie(hdr->msg.ack.dst_wmd.wh_object_cookie);
4095         lnet_res_lock(cpt);
4096
4097         /* NB handles only looked up by creator (no flips) */
4098         md = lnet_wire_handle2md(&hdr->msg.ack.dst_wmd);
4099         if (md == NULL || md->md_threshold == 0 || md->md_me != NULL) {
4100                 /* Don't moan; this is expected */
4101                 CDEBUG(D_NET,
4102                        "%s: Dropping ACK from %s to %s MD %#llx.%#llx\n",
4103                        libcfs_nid2str(ni->ni_nid), libcfs_id2str(src),
4104                        (md == NULL) ? "invalid" : "inactive",
4105                        hdr->msg.ack.dst_wmd.wh_interface_cookie,
4106                        hdr->msg.ack.dst_wmd.wh_object_cookie);
4107                 if (md != NULL && md->md_me != NULL)
4108                         CERROR("Source MD also attached to portal %d\n",
4109                                md->md_me->me_portal);
4110
4111                 lnet_res_unlock(cpt);
4112                 return -ENOENT;                  /* -ve! */
4113         }
4114
4115         CDEBUG(D_NET, "%s: ACK from %s into md %#llx\n",
4116                libcfs_nid2str(ni->ni_nid), libcfs_id2str(src),
4117                hdr->msg.ack.dst_wmd.wh_object_cookie);
4118
4119         lnet_msg_attach_md(msg, md, 0, 0);
4120
4121         lnet_res_unlock(cpt);
4122
4123         lnet_build_msg_event(msg, LNET_EVENT_ACK);
4124
4125         lnet_ni_recv(ni, msg->msg_private, msg, 0, 0, 0, msg->msg_len);
4126         return 0;
4127 }
4128
4129 /**
4130  * \retval LNET_CREDIT_OK       If \a msg is forwarded
4131  * \retval LNET_CREDIT_WAIT     If \a msg is blocked because w/o buffer
4132  * \retval -ve                  error code
4133  */
4134 int
4135 lnet_parse_forward_locked(struct lnet_ni *ni, struct lnet_msg *msg)
4136 {
4137         int     rc = 0;
4138
4139         if (!the_lnet.ln_routing)
4140                 return -ECANCELED;
4141
4142         if (msg->msg_rxpeer->lpni_rtrcredits <= 0 ||
4143             lnet_msg2bufpool(msg)->rbp_credits <= 0) {
4144                 if (ni->ni_net->net_lnd->lnd_eager_recv == NULL) {
4145                         msg->msg_rx_ready_delay = 1;
4146                 } else {
4147                         lnet_net_unlock(msg->msg_rx_cpt);
4148                         rc = lnet_ni_eager_recv(ni, msg);
4149                         lnet_net_lock(msg->msg_rx_cpt);
4150                 }
4151         }
4152
4153         if (rc == 0)
4154                 rc = lnet_post_routed_recv_locked(msg, 0);
4155         return rc;
4156 }
4157
4158 int
4159 lnet_parse_local(struct lnet_ni *ni, struct lnet_msg *msg)
4160 {
4161         int     rc;
4162
4163         switch (msg->msg_type) {
4164         case LNET_MSG_ACK:
4165                 rc = lnet_parse_ack(ni, msg);
4166                 break;
4167         case LNET_MSG_PUT:
4168                 rc = lnet_parse_put(ni, msg);
4169                 break;
4170         case LNET_MSG_GET:
4171                 rc = lnet_parse_get(ni, msg, msg->msg_rdma_get);
4172                 break;
4173         case LNET_MSG_REPLY:
4174                 rc = lnet_parse_reply(ni, msg);
4175                 break;
4176         default: /* prevent an unused label if !kernel */
4177                 LASSERT(0);
4178                 return -EPROTO;
4179         }
4180
4181         LASSERT(rc == 0 || rc == -ENOENT);
4182         return rc;
4183 }
4184
4185 char *
4186 lnet_msgtyp2str (int type)
4187 {
4188         switch (type) {
4189         case LNET_MSG_ACK:
4190                 return ("ACK");
4191         case LNET_MSG_PUT:
4192                 return ("PUT");
4193         case LNET_MSG_GET:
4194                 return ("GET");
4195         case LNET_MSG_REPLY:
4196                 return ("REPLY");
4197         case LNET_MSG_HELLO:
4198                 return ("HELLO");
4199         default:
4200                 return ("<UNKNOWN>");
4201         }
4202 }
4203
4204 void
4205 lnet_print_hdr(struct lnet_hdr *hdr)
4206 {
4207         struct lnet_process_id src = {
4208                 .nid = hdr->src_nid,
4209                 .pid = hdr->src_pid,
4210         };
4211         struct lnet_process_id dst = {
4212                 .nid = hdr->dest_nid,
4213                 .pid = hdr->dest_pid,
4214         };
4215         char *type_str = lnet_msgtyp2str(hdr->type);
4216
4217         CWARN("P3 Header at %p of type %s\n", hdr, type_str);
4218         CWARN("    From %s\n", libcfs_id2str(src));
4219         CWARN("    To   %s\n", libcfs_id2str(dst));
4220
4221         switch (hdr->type) {
4222         default:
4223                 break;
4224
4225         case LNET_MSG_PUT:
4226                 CWARN("    Ptl index %d, ack md %#llx.%#llx, "
4227                       "match bits %llu\n",
4228                       hdr->msg.put.ptl_index,
4229                       hdr->msg.put.ack_wmd.wh_interface_cookie,
4230                       hdr->msg.put.ack_wmd.wh_object_cookie,
4231                       hdr->msg.put.match_bits);
4232                 CWARN("    Length %d, offset %d, hdr data %#llx\n",
4233                       hdr->payload_length, hdr->msg.put.offset,
4234                       hdr->msg.put.hdr_data);
4235                 break;
4236
4237         case LNET_MSG_GET:
4238                 CWARN("    Ptl index %d, return md %#llx.%#llx, "
4239                       "match bits %llu\n", hdr->msg.get.ptl_index,
4240                       hdr->msg.get.return_wmd.wh_interface_cookie,
4241                       hdr->msg.get.return_wmd.wh_object_cookie,
4242                       hdr->msg.get.match_bits);
4243                 CWARN("    Length %d, src offset %d\n",
4244                       hdr->msg.get.sink_length,
4245                       hdr->msg.get.src_offset);
4246                 break;
4247
4248         case LNET_MSG_ACK:
4249                 CWARN("    dst md %#llx.%#llx, "
4250                       "manipulated length %d\n",
4251                       hdr->msg.ack.dst_wmd.wh_interface_cookie,
4252                       hdr->msg.ack.dst_wmd.wh_object_cookie,
4253                       hdr->msg.ack.mlength);
4254                 break;
4255
4256         case LNET_MSG_REPLY:
4257                 CWARN("    dst md %#llx.%#llx, "
4258                       "length %d\n",
4259                       hdr->msg.reply.dst_wmd.wh_interface_cookie,
4260                       hdr->msg.reply.dst_wmd.wh_object_cookie,
4261                       hdr->payload_length);
4262         }
4263
4264 }
4265
4266 int
4267 lnet_parse(struct lnet_ni *ni, struct lnet_hdr *hdr, lnet_nid_t from_nid,
4268            void *private, int rdma_req)
4269 {
4270         struct lnet_peer_ni *lpni;
4271         struct lnet_msg *msg;
4272         __u32 payload_length;
4273         lnet_pid_t dest_pid;
4274         lnet_nid_t dest_nid;
4275         lnet_nid_t src_nid;
4276         bool push = false;
4277         int for_me;
4278         __u32 type;
4279         int rc = 0;
4280         int cpt;
4281
4282         LASSERT (!in_interrupt ());
4283
4284         type = le32_to_cpu(hdr->type);
4285         src_nid = le64_to_cpu(hdr->src_nid);
4286         dest_nid = le64_to_cpu(hdr->dest_nid);
4287         dest_pid = le32_to_cpu(hdr->dest_pid);
4288         payload_length = le32_to_cpu(hdr->payload_length);
4289
4290         for_me = (ni->ni_nid == dest_nid);
4291         cpt = lnet_cpt_of_nid(from_nid, ni);
4292
4293         CDEBUG(D_NET, "TRACE: %s(%s) <- %s : %s - %s\n",
4294                 libcfs_nid2str(dest_nid),
4295                 libcfs_nid2str(ni->ni_nid),
4296                 libcfs_nid2str(src_nid),
4297                 lnet_msgtyp2str(type),
4298                 (for_me) ? "for me" : "routed");
4299
4300         switch (type) {
4301         case LNET_MSG_ACK:
4302         case LNET_MSG_GET:
4303                 if (payload_length > 0) {
4304                         CERROR("%s, src %s: bad %s payload %d (0 expected)\n",
4305                                libcfs_nid2str(from_nid),
4306                                libcfs_nid2str(src_nid),
4307                                lnet_msgtyp2str(type), payload_length);
4308                         return -EPROTO;
4309                 }
4310                 break;
4311
4312         case LNET_MSG_PUT:
4313         case LNET_MSG_REPLY:
4314                 if (payload_length >
4315                     (__u32)(for_me ? LNET_MAX_PAYLOAD : LNET_MTU)) {
4316                         CERROR("%s, src %s: bad %s payload %d "
4317                                "(%d max expected)\n",
4318                                libcfs_nid2str(from_nid),
4319                                libcfs_nid2str(src_nid),
4320                                lnet_msgtyp2str(type),
4321                                payload_length,
4322                                for_me ? LNET_MAX_PAYLOAD : LNET_MTU);
4323                         return -EPROTO;
4324                 }
4325                 break;
4326
4327         default:
4328                 CERROR("%s, src %s: Bad message type 0x%x\n",
4329                        libcfs_nid2str(from_nid),
4330                        libcfs_nid2str(src_nid), type);
4331                 return -EPROTO;
4332         }
4333
4334         if (the_lnet.ln_routing &&
4335             ni->ni_net->net_last_alive != ktime_get_real_seconds()) {
4336                 lnet_ni_lock(ni);
4337                 spin_lock(&ni->ni_net->net_lock);
4338                 ni->ni_net->net_last_alive = ktime_get_real_seconds();
4339                 spin_unlock(&ni->ni_net->net_lock);
4340                 if (ni->ni_status != NULL &&
4341                     ni->ni_status->ns_status == LNET_NI_STATUS_DOWN) {
4342                         ni->ni_status->ns_status = LNET_NI_STATUS_UP;
4343                         push = true;
4344                 }
4345                 lnet_ni_unlock(ni);
4346         }
4347
4348         if (push)
4349                 lnet_push_update_to_peers(1);
4350
4351         /* Regard a bad destination NID as a protocol error.  Senders should
4352          * know what they're doing; if they don't they're misconfigured, buggy
4353          * or malicious so we chop them off at the knees :) */
4354
4355         if (!for_me) {
4356                 if (LNET_NIDNET(dest_nid) == LNET_NIDNET(ni->ni_nid)) {
4357                         /* should have gone direct */
4358                         CERROR("%s, src %s: Bad dest nid %s "
4359                                "(should have been sent direct)\n",
4360                                 libcfs_nid2str(from_nid),
4361                                 libcfs_nid2str(src_nid),
4362                                 libcfs_nid2str(dest_nid));
4363                         return -EPROTO;
4364                 }
4365
4366                 if (lnet_islocalnid(dest_nid)) {
4367                         /* dest is another local NI; sender should have used
4368                          * this node's NID on its own network */
4369                         CERROR("%s, src %s: Bad dest nid %s "
4370                                "(it's my nid but on a different network)\n",
4371                                 libcfs_nid2str(from_nid),
4372                                 libcfs_nid2str(src_nid),
4373                                 libcfs_nid2str(dest_nid));
4374                         return -EPROTO;
4375                 }
4376
4377                 if (rdma_req && type == LNET_MSG_GET) {
4378                         CERROR("%s, src %s: Bad optimized GET for %s "
4379                                "(final destination must be me)\n",
4380                                 libcfs_nid2str(from_nid),
4381                                 libcfs_nid2str(src_nid),
4382                                 libcfs_nid2str(dest_nid));
4383                         return -EPROTO;
4384                 }
4385
4386                 if (!the_lnet.ln_routing) {
4387                         CERROR("%s, src %s: Dropping message for %s "
4388                                "(routing not enabled)\n",
4389                                 libcfs_nid2str(from_nid),
4390                                 libcfs_nid2str(src_nid),
4391                                 libcfs_nid2str(dest_nid));
4392                         goto drop;
4393                 }
4394         }
4395
4396         /* Message looks OK; we're not going to return an error, so we MUST
4397          * call back lnd_recv() come what may... */
4398
4399         if (!list_empty(&the_lnet.ln_test_peers) &&     /* normally we don't */
4400             fail_peer(src_nid, 0)) {                    /* shall we now? */
4401                 CERROR("%s, src %s: Dropping %s to simulate failure\n",
4402                        libcfs_nid2str(from_nid), libcfs_nid2str(src_nid),
4403                        lnet_msgtyp2str(type));
4404                 goto drop;
4405         }
4406
4407         if (!list_empty(&the_lnet.ln_drop_rules) &&
4408             lnet_drop_rule_match(hdr, ni->ni_nid, NULL)) {
4409                 CDEBUG(D_NET, "%s, src %s, dst %s: Dropping %s to simulate"
4410                               "silent message loss\n",
4411                        libcfs_nid2str(from_nid), libcfs_nid2str(src_nid),
4412                        libcfs_nid2str(dest_nid), lnet_msgtyp2str(type));
4413                 goto drop;
4414         }
4415
4416         if (lnet_drop_asym_route && for_me &&
4417             LNET_NIDNET(src_nid) != LNET_NIDNET(from_nid)) {
4418                 struct lnet_net *net;
4419                 struct lnet_remotenet *rnet;
4420                 bool found = true;
4421
4422                 /* we are dealing with a routed message,
4423                  * so see if route to reach src_nid goes through from_nid
4424                  */
4425                 lnet_net_lock(cpt);
4426                 net = lnet_get_net_locked(LNET_NIDNET(ni->ni_nid));
4427                 if (!net) {
4428                         lnet_net_unlock(cpt);
4429                         CERROR("net %s not found\n",
4430                                libcfs_net2str(LNET_NIDNET(ni->ni_nid)));
4431                         return -EPROTO;
4432                 }
4433
4434                 rnet = lnet_find_rnet_locked(LNET_NIDNET(src_nid));
4435                 if (rnet) {
4436                         struct lnet_peer *gw = NULL;
4437                         struct lnet_peer_ni *lpni = NULL;
4438                         struct lnet_route *route;
4439
4440                         list_for_each_entry(route, &rnet->lrn_routes, lr_list) {
4441                                 found = false;
4442                                 gw = route->lr_gateway;
4443                                 if (route->lr_lnet != net->net_id)
4444                                         continue;
4445                                 /*
4446                                  * if the nid is one of the gateway's NIDs
4447                                  * then this is a valid gateway
4448                                  */
4449                                 while ((lpni = lnet_get_next_peer_ni_locked(gw,
4450                                                 NULL, lpni)) != NULL) {
4451                                         if (lpni->lpni_nid == from_nid) {
4452                                                 found = true;
4453                                                 break;
4454                                         }
4455                                 }
4456                         }
4457                 }
4458                 lnet_net_unlock(cpt);
4459                 if (!found) {
4460                         /* we would not use from_nid to route a message to
4461                          * src_nid
4462                          * => asymmetric routing detected but forbidden
4463                          */
4464                         CERROR("%s, src %s: Dropping asymmetrical route %s\n",
4465                                libcfs_nid2str(from_nid),
4466                                libcfs_nid2str(src_nid), lnet_msgtyp2str(type));
4467                         goto drop;
4468                 }
4469         }
4470
4471         msg = lnet_msg_alloc();
4472         if (msg == NULL) {
4473                 CERROR("%s, src %s: Dropping %s (out of memory)\n",
4474                        libcfs_nid2str(from_nid), libcfs_nid2str(src_nid),
4475                        lnet_msgtyp2str(type));
4476                 goto drop;
4477         }
4478
4479         /* msg zeroed in lnet_msg_alloc; i.e. flags all clear,
4480          * pointers NULL etc */
4481
4482         msg->msg_type = type;
4483         msg->msg_private = private;
4484         msg->msg_receiving = 1;
4485         msg->msg_rdma_get = rdma_req;
4486         msg->msg_len = msg->msg_wanted = payload_length;
4487         msg->msg_offset = 0;
4488         msg->msg_hdr = *hdr;
4489         /* for building message event */
4490         msg->msg_from = from_nid;
4491         if (!for_me) {
4492                 msg->msg_target.pid     = dest_pid;
4493                 msg->msg_target.nid     = dest_nid;
4494                 msg->msg_routing        = 1;
4495
4496         } else {
4497                 /* convert common msg->hdr fields to host byteorder */
4498                 msg->msg_hdr.type       = type;
4499                 msg->msg_hdr.src_nid    = src_nid;
4500                 msg->msg_hdr.src_pid    = le32_to_cpu(msg->msg_hdr.src_pid);
4501                 msg->msg_hdr.dest_nid   = dest_nid;
4502                 msg->msg_hdr.dest_pid   = dest_pid;
4503                 msg->msg_hdr.payload_length = payload_length;
4504         }
4505
4506         lnet_net_lock(cpt);
4507         lpni = lnet_nid2peerni_locked(from_nid, ni->ni_nid, cpt);
4508         if (IS_ERR(lpni)) {
4509                 lnet_net_unlock(cpt);
4510                 CERROR("%s, src %s: Dropping %s "
4511                        "(error %ld looking up sender)\n",
4512                        libcfs_nid2str(from_nid), libcfs_nid2str(src_nid),
4513                        lnet_msgtyp2str(type), PTR_ERR(lpni));
4514                 lnet_msg_free(msg);
4515                 if (rc == -ESHUTDOWN)
4516                         /* We are shutting down.  Don't do anything more */
4517                         return 0;
4518                 goto drop;
4519         }
4520
4521         if (the_lnet.ln_routing)
4522                 lpni->lpni_last_alive = ktime_get_seconds();
4523
4524         msg->msg_rxpeer = lpni;
4525         msg->msg_rxni = ni;
4526         lnet_ni_addref_locked(ni, cpt);
4527         /* Multi-Rail: Primary NID of source. */
4528         msg->msg_initiator = lnet_peer_primary_nid_locked(src_nid);
4529
4530         /*
4531          * mark the status of this lpni as UP since we received a message
4532          * from it. The ping response reports back the ns_status which is
4533          * marked on the remote as up or down and we cache it here.
4534          */
4535         msg->msg_rxpeer->lpni_ns_status = LNET_NI_STATUS_UP;
4536
4537         lnet_msg_commit(msg, cpt);
4538
4539         /* message delay simulation */
4540         if (unlikely(!list_empty(&the_lnet.ln_delay_rules) &&
4541                      lnet_delay_rule_match_locked(hdr, msg))) {
4542                 lnet_net_unlock(cpt);
4543                 return 0;
4544         }
4545
4546         if (!for_me) {
4547                 rc = lnet_parse_forward_locked(ni, msg);
4548                 lnet_net_unlock(cpt);
4549
4550                 if (rc < 0)
4551                         goto free_drop;
4552
4553                 if (rc == LNET_CREDIT_OK) {
4554                         lnet_ni_recv(ni, msg->msg_private, msg, 0,
4555                                      0, payload_length, payload_length);
4556                 }
4557                 return 0;
4558         }
4559
4560         lnet_net_unlock(cpt);
4561
4562         rc = lnet_parse_local(ni, msg);
4563         if (rc != 0)
4564                 goto free_drop;
4565         return 0;
4566
4567  free_drop:
4568         LASSERT(msg->msg_md == NULL);
4569         lnet_finalize(msg, rc);
4570
4571  drop:
4572         lnet_drop_message(ni, cpt, private, payload_length, type);
4573         return 0;
4574 }
4575 EXPORT_SYMBOL(lnet_parse);
4576
4577 void
4578 lnet_drop_delayed_msg_list(struct list_head *head, char *reason)
4579 {
4580         while (!list_empty(head)) {
4581                 struct lnet_process_id id = {0};
4582                 struct lnet_msg *msg;
4583
4584                 msg = list_entry(head->next, struct lnet_msg, msg_list);
4585                 list_del(&msg->msg_list);
4586
4587                 id.nid = msg->msg_hdr.src_nid;
4588                 id.pid = msg->msg_hdr.src_pid;
4589
4590                 LASSERT(msg->msg_md == NULL);
4591                 LASSERT(msg->msg_rx_delayed);
4592                 LASSERT(msg->msg_rxpeer != NULL);
4593                 LASSERT(msg->msg_hdr.type == LNET_MSG_PUT);
4594
4595                 CWARN("Dropping delayed PUT from %s portal %d match %llu"
4596                       " offset %d length %d: %s\n",
4597                       libcfs_id2str(id),
4598                       msg->msg_hdr.msg.put.ptl_index,
4599                       msg->msg_hdr.msg.put.match_bits,
4600                       msg->msg_hdr.msg.put.offset,
4601                       msg->msg_hdr.payload_length, reason);
4602
4603                 /* NB I can't drop msg's ref on msg_rxpeer until after I've
4604                  * called lnet_drop_message(), so I just hang onto msg as well
4605                  * until that's done */
4606
4607                 lnet_drop_message(msg->msg_rxni, msg->msg_rx_cpt,
4608                                   msg->msg_private, msg->msg_len,
4609                                   msg->msg_type);
4610
4611                 msg->msg_no_resend = true;
4612                 /*
4613                  * NB: message will not generate event because w/o attached MD,
4614                  * but we still should give error code so lnet_msg_decommit()
4615                  * can skip counters operations and other checks.
4616                  */
4617                 lnet_finalize(msg, -ENOENT);
4618         }
4619 }
4620
4621 void
4622 lnet_recv_delayed_msg_list(struct list_head *head)
4623 {
4624         while (!list_empty(head)) {
4625                 struct lnet_msg *msg;
4626                 struct lnet_process_id id;
4627
4628                 msg = list_entry(head->next, struct lnet_msg, msg_list);
4629                 list_del(&msg->msg_list);
4630
4631                 /* md won't disappear under me, since each msg
4632                  * holds a ref on it */
4633
4634                 id.nid = msg->msg_hdr.src_nid;
4635                 id.pid = msg->msg_hdr.src_pid;
4636
4637                 LASSERT(msg->msg_rx_delayed);
4638                 LASSERT(msg->msg_md != NULL);
4639                 LASSERT(msg->msg_rxpeer != NULL);
4640                 LASSERT(msg->msg_rxni != NULL);
4641                 LASSERT(msg->msg_hdr.type == LNET_MSG_PUT);
4642
4643                 CDEBUG(D_NET, "Resuming delayed PUT from %s portal %d "
4644                        "match %llu offset %d length %d.\n",
4645                         libcfs_id2str(id), msg->msg_hdr.msg.put.ptl_index,
4646                         msg->msg_hdr.msg.put.match_bits,
4647                         msg->msg_hdr.msg.put.offset,
4648                         msg->msg_hdr.payload_length);
4649
4650                 lnet_recv_put(msg->msg_rxni, msg);
4651         }
4652 }
4653
4654 static void
4655 lnet_attach_rsp_tracker(struct lnet_rsp_tracker *rspt, int cpt,
4656                         struct lnet_libmd *md, struct lnet_handle_md mdh)
4657 {
4658         s64 timeout_ns;
4659         struct lnet_rsp_tracker *local_rspt;
4660
4661         /*
4662          * MD has a refcount taken by message so it's not going away.
4663          * The MD however can be looked up. We need to secure the access
4664          * to the md_rspt_ptr by taking the res_lock.
4665          * The rspt can be accessed without protection up to when it gets
4666          * added to the list.
4667          */
4668
4669         lnet_res_lock(cpt);
4670         local_rspt = md->md_rspt_ptr;
4671         timeout_ns = lnet_transaction_timeout * NSEC_PER_SEC;
4672         if (local_rspt != NULL) {
4673                 /*
4674                  * we already have an rspt attached to the md, so we'll
4675                  * update the deadline on that one.
4676                  */
4677                 lnet_rspt_free(rspt, cpt);
4678         } else {
4679                 /* new md */
4680                 rspt->rspt_mdh = mdh;
4681                 rspt->rspt_cpt = cpt;
4682                 /* store the rspt so we can access it when we get the REPLY */
4683                 md->md_rspt_ptr = rspt;
4684                 local_rspt = rspt;
4685         }
4686         local_rspt->rspt_deadline = ktime_add_ns(ktime_get(), timeout_ns);
4687
4688         /*
4689          * add to the list of tracked responses. It's added to tail of the
4690          * list in order to expire all the older entries first.
4691          */
4692         lnet_net_lock(cpt);
4693         list_move_tail(&local_rspt->rspt_on_list, the_lnet.ln_mt_rstq[cpt]);
4694         lnet_net_unlock(cpt);
4695         lnet_res_unlock(cpt);
4696 }
4697
4698 /**
4699  * Initiate an asynchronous PUT operation.
4700  *
4701  * There are several events associated with a PUT: completion of the send on
4702  * the initiator node (LNET_EVENT_SEND), and when the send completes
4703  * successfully, the receipt of an acknowledgment (LNET_EVENT_ACK) indicating
4704  * that the operation was accepted by the target. The event LNET_EVENT_PUT is
4705  * used at the target node to indicate the completion of incoming data
4706  * delivery.
4707  *
4708  * The local events will be logged in the EQ associated with the MD pointed to
4709  * by \a mdh handle. Using a MD without an associated EQ results in these
4710  * events being discarded. In this case, the caller must have another
4711  * mechanism (e.g., a higher level protocol) for determining when it is safe
4712  * to modify the memory region associated with the MD.
4713  *
4714  * Note that LNet does not guarantee the order of LNET_EVENT_SEND and
4715  * LNET_EVENT_ACK, though intuitively ACK should happen after SEND.
4716  *
4717  * \param self Indicates the NID of a local interface through which to send
4718  * the PUT request. Use LNET_NID_ANY to let LNet choose one by itself.
4719  * \param mdh A handle for the MD that describes the memory to be sent. The MD
4720  * must be "free floating" (See LNetMDBind()).
4721  * \param ack Controls whether an acknowledgment is requested.
4722  * Acknowledgments are only sent when they are requested by the initiating
4723  * process and the target MD enables them.
4724  * \param target A process identifier for the target process.
4725  * \param portal The index in the \a target's portal table.
4726  * \param match_bits The match bits to use for MD selection at the target
4727  * process.
4728  * \param offset The offset into the target MD (only used when the target
4729  * MD has the LNET_MD_MANAGE_REMOTE option set).
4730  * \param hdr_data 64 bits of user data that can be included in the message
4731  * header. This data is written to an event queue entry at the target if an
4732  * EQ is present on the matching MD.
4733  *
4734  * \retval  0      Success, and only in this case events will be generated
4735  * and logged to EQ (if it exists).
4736  * \retval -EIO    Simulated failure.
4737  * \retval -ENOMEM Memory allocation failure.
4738  * \retval -ENOENT Invalid MD object.
4739  *
4740  * \see struct lnet_event::hdr_data and lnet_event_kind_t.
4741  */
4742 int
4743 LNetPut(lnet_nid_t self, struct lnet_handle_md mdh, enum lnet_ack_req ack,
4744         struct lnet_process_id target, unsigned int portal,
4745         __u64 match_bits, unsigned int offset,
4746         __u64 hdr_data)
4747 {
4748         struct lnet_msg *msg;
4749         struct lnet_libmd *md;
4750         int cpt;
4751         int rc;
4752         struct lnet_rsp_tracker *rspt = NULL;
4753
4754         LASSERT(the_lnet.ln_refcount > 0);
4755
4756         if (!list_empty(&the_lnet.ln_test_peers) &&     /* normally we don't */
4757             fail_peer(target.nid, 1)) {                 /* shall we now? */
4758                 CERROR("Dropping PUT to %s: simulated failure\n",
4759                        libcfs_id2str(target));
4760                 return -EIO;
4761         }
4762
4763         msg = lnet_msg_alloc();
4764         if (msg == NULL) {
4765                 CERROR("Dropping PUT to %s: ENOMEM on struct lnet_msg\n",
4766                        libcfs_id2str(target));
4767                 return -ENOMEM;
4768         }
4769         msg->msg_vmflush = !!memory_pressure_get();
4770
4771         cpt = lnet_cpt_of_cookie(mdh.cookie);
4772
4773         if (ack == LNET_ACK_REQ) {
4774                 rspt = lnet_rspt_alloc(cpt);
4775                 if (!rspt) {
4776                         CERROR("Dropping PUT to %s: ENOMEM on response tracker\n",
4777                                 libcfs_id2str(target));
4778                         return -ENOMEM;
4779                 }
4780                 INIT_LIST_HEAD(&rspt->rspt_on_list);
4781         }
4782
4783         lnet_res_lock(cpt);
4784
4785         md = lnet_handle2md(&mdh);
4786         if (md == NULL || md->md_threshold == 0 || md->md_me != NULL) {
4787                 CERROR("Dropping PUT (%llu:%d:%s): MD (%d) invalid\n",
4788                        match_bits, portal, libcfs_id2str(target),
4789                        md == NULL ? -1 : md->md_threshold);
4790                 if (md != NULL && md->md_me != NULL)
4791                         CERROR("Source MD also attached to portal %d\n",
4792                                md->md_me->me_portal);
4793                 lnet_res_unlock(cpt);
4794
4795                 lnet_rspt_free(rspt, cpt);
4796                 lnet_msg_free(msg);
4797                 return -ENOENT;
4798         }
4799
4800         CDEBUG(D_NET, "LNetPut -> %s\n", libcfs_id2str(target));
4801
4802         lnet_msg_attach_md(msg, md, 0, 0);
4803
4804         lnet_prep_send(msg, LNET_MSG_PUT, target, 0, md->md_length);
4805
4806         msg->msg_hdr.msg.put.match_bits = cpu_to_le64(match_bits);
4807         msg->msg_hdr.msg.put.ptl_index = cpu_to_le32(portal);
4808         msg->msg_hdr.msg.put.offset = cpu_to_le32(offset);
4809         msg->msg_hdr.msg.put.hdr_data = hdr_data;
4810
4811         /* NB handles only looked up by creator (no flips) */
4812         if (ack == LNET_ACK_REQ) {
4813                 msg->msg_hdr.msg.put.ack_wmd.wh_interface_cookie =
4814                         the_lnet.ln_interface_cookie;
4815                 msg->msg_hdr.msg.put.ack_wmd.wh_object_cookie =
4816                         md->md_lh.lh_cookie;
4817         } else {
4818                 msg->msg_hdr.msg.put.ack_wmd.wh_interface_cookie =
4819                         LNET_WIRE_HANDLE_COOKIE_NONE;
4820                 msg->msg_hdr.msg.put.ack_wmd.wh_object_cookie =
4821                         LNET_WIRE_HANDLE_COOKIE_NONE;
4822         }
4823
4824         lnet_res_unlock(cpt);
4825
4826         lnet_build_msg_event(msg, LNET_EVENT_SEND);
4827
4828         if (ack == LNET_ACK_REQ)
4829                 lnet_attach_rsp_tracker(rspt, cpt, md, mdh);
4830
4831         if (CFS_FAIL_CHECK_ORSET(CFS_FAIL_PTLRPC_OST_BULK_CB2,
4832                                  CFS_FAIL_ONCE))
4833                 rc = -EIO;
4834         else
4835                 rc = lnet_send(self, msg, LNET_NID_ANY);
4836
4837         if (rc != 0) {
4838                 CNETERR("Error sending PUT to %s: %d\n",
4839                         libcfs_id2str(target), rc);
4840                 msg->msg_no_resend = true;
4841                 lnet_finalize(msg, rc);
4842         }
4843
4844         /* completion will be signalled by an event */
4845         return 0;
4846 }
4847 EXPORT_SYMBOL(LNetPut);
4848
4849 /*
4850  * The LND can DMA direct to the GET md (i.e. no REPLY msg).  This
4851  * returns a msg for the LND to pass to lnet_finalize() when the sink
4852  * data has been received.
4853  *
4854  * CAVEAT EMPTOR: 'getmsg' is the original GET, which is freed when
4855  * lnet_finalize() is called on it, so the LND must call this first
4856  */
4857 struct lnet_msg *
4858 lnet_create_reply_msg(struct lnet_ni *ni, struct lnet_msg *getmsg)
4859 {
4860         struct lnet_msg *msg = lnet_msg_alloc();
4861         struct lnet_libmd *getmd = getmsg->msg_md;
4862         struct lnet_process_id peer_id = getmsg->msg_target;
4863         int cpt;
4864
4865         LASSERT(!getmsg->msg_target_is_router);
4866         LASSERT(!getmsg->msg_routing);
4867
4868         if (msg == NULL) {
4869                 CERROR("%s: Dropping REPLY from %s: can't allocate msg\n",
4870                        libcfs_nid2str(ni->ni_nid), libcfs_id2str(peer_id));
4871                 goto drop;
4872         }
4873
4874         cpt = lnet_cpt_of_cookie(getmd->md_lh.lh_cookie);
4875         lnet_res_lock(cpt);
4876
4877         LASSERT(getmd->md_refcount > 0);
4878
4879         if (getmd->md_threshold == 0) {
4880                 CERROR("%s: Dropping REPLY from %s for inactive MD %p\n",
4881                         libcfs_nid2str(ni->ni_nid), libcfs_id2str(peer_id),
4882                         getmd);
4883                 lnet_res_unlock(cpt);
4884                 goto drop;
4885         }
4886
4887         LASSERT(getmd->md_offset == 0);
4888
4889         CDEBUG(D_NET, "%s: Reply from %s md %p\n",
4890                libcfs_nid2str(ni->ni_nid), libcfs_id2str(peer_id), getmd);
4891
4892         /* setup information for lnet_build_msg_event */
4893         msg->msg_initiator = getmsg->msg_txpeer->lpni_peer_net->lpn_peer->lp_primary_nid;
4894         msg->msg_from = peer_id.nid;
4895         msg->msg_type = LNET_MSG_GET; /* flag this msg as an "optimized" GET */
4896         msg->msg_hdr.src_nid = peer_id.nid;
4897         msg->msg_hdr.payload_length = getmd->md_length;
4898         msg->msg_receiving = 1; /* required by lnet_msg_attach_md */
4899
4900         lnet_msg_attach_md(msg, getmd, getmd->md_offset, getmd->md_length);
4901         lnet_res_unlock(cpt);
4902
4903         cpt = lnet_cpt_of_nid(peer_id.nid, ni);
4904
4905         lnet_net_lock(cpt);
4906         lnet_msg_commit(msg, cpt);
4907         lnet_net_unlock(cpt);
4908
4909         lnet_build_msg_event(msg, LNET_EVENT_REPLY);
4910
4911         return msg;
4912
4913  drop:
4914         cpt = lnet_cpt_of_nid(peer_id.nid, ni);
4915
4916         lnet_net_lock(cpt);
4917         lnet_incr_stats(&ni->ni_stats, LNET_MSG_GET, LNET_STATS_TYPE_DROP);
4918         the_lnet.ln_counters[cpt]->lct_common.lcc_drop_count++;
4919         the_lnet.ln_counters[cpt]->lct_common.lcc_drop_length +=
4920                 getmd->md_length;
4921         lnet_net_unlock(cpt);
4922
4923         if (msg != NULL)
4924                 lnet_msg_free(msg);
4925
4926         return NULL;
4927 }
4928 EXPORT_SYMBOL(lnet_create_reply_msg);
4929
4930 void
4931 lnet_set_reply_msg_len(struct lnet_ni *ni, struct lnet_msg *reply,
4932                        unsigned int len)
4933 {
4934         /* Set the REPLY length, now the RDMA that elides the REPLY message has
4935          * completed and I know it. */
4936         LASSERT(reply != NULL);
4937         LASSERT(reply->msg_type == LNET_MSG_GET);
4938         LASSERT(reply->msg_ev.type == LNET_EVENT_REPLY);
4939
4940         /* NB I trusted my peer to RDMA.  If she tells me she's written beyond
4941          * the end of my buffer, I might as well be dead. */
4942         LASSERT(len <= reply->msg_ev.mlength);
4943
4944         reply->msg_ev.mlength = len;
4945 }
4946 EXPORT_SYMBOL(lnet_set_reply_msg_len);
4947
4948 /**
4949  * Initiate an asynchronous GET operation.
4950  *
4951  * On the initiator node, an LNET_EVENT_SEND is logged when the GET request
4952  * is sent, and an LNET_EVENT_REPLY is logged when the data returned from
4953  * the target node in the REPLY has been written to local MD.
4954  *
4955  * On the target node, an LNET_EVENT_GET is logged when the GET request
4956  * arrives and is accepted into a MD.
4957  *
4958  * \param self,target,portal,match_bits,offset See the discussion in LNetPut().
4959  * \param mdh A handle for the MD that describes the memory into which the
4960  * requested data will be received. The MD must be "free floating" (See LNetMDBind()).
4961  *
4962  * \retval  0      Success, and only in this case events will be generated
4963  * and logged to EQ (if it exists) of the MD.
4964  * \retval -EIO    Simulated failure.
4965  * \retval -ENOMEM Memory allocation failure.
4966  * \retval -ENOENT Invalid MD object.
4967  */
4968 int
4969 LNetGet(lnet_nid_t self, struct lnet_handle_md mdh,
4970         struct lnet_process_id target, unsigned int portal,
4971         __u64 match_bits, unsigned int offset, bool recovery)
4972 {
4973         struct lnet_msg *msg;
4974         struct lnet_libmd *md;
4975         struct lnet_rsp_tracker *rspt;
4976         int cpt;
4977         int rc;
4978
4979         LASSERT(the_lnet.ln_refcount > 0);
4980
4981         if (!list_empty(&the_lnet.ln_test_peers) &&     /* normally we don't */
4982             fail_peer(target.nid, 1))                   /* shall we now? */
4983         {
4984                 CERROR("Dropping GET to %s: simulated failure\n",
4985                        libcfs_id2str(target));
4986                 return -EIO;
4987         }
4988
4989         msg = lnet_msg_alloc();
4990         if (!msg) {
4991                 CERROR("Dropping GET to %s: ENOMEM on struct lnet_msg\n",
4992                        libcfs_id2str(target));
4993                 return -ENOMEM;
4994         }
4995
4996         cpt = lnet_cpt_of_cookie(mdh.cookie);
4997
4998         rspt = lnet_rspt_alloc(cpt);
4999         if (!rspt) {
5000                 CERROR("Dropping GET to %s: ENOMEM on response tracker\n",
5001                        libcfs_id2str(target));
5002                 return -ENOMEM;
5003         }
5004         INIT_LIST_HEAD(&rspt->rspt_on_list);
5005
5006         msg->msg_recovery = recovery;
5007
5008         lnet_res_lock(cpt);
5009
5010         md = lnet_handle2md(&mdh);
5011         if (md == NULL || md->md_threshold == 0 || md->md_me != NULL) {
5012                 CERROR("Dropping GET (%llu:%d:%s): MD (%d) invalid\n",
5013                        match_bits, portal, libcfs_id2str(target),
5014                        md == NULL ? -1 : md->md_threshold);
5015                 if (md != NULL && md->md_me != NULL)
5016                         CERROR("REPLY MD also attached to portal %d\n",
5017                                md->md_me->me_portal);
5018
5019                 lnet_res_unlock(cpt);
5020
5021                 lnet_msg_free(msg);
5022                 lnet_rspt_free(rspt, cpt);
5023                 return -ENOENT;
5024         }
5025
5026         CDEBUG(D_NET, "LNetGet -> %s\n", libcfs_id2str(target));
5027
5028         lnet_msg_attach_md(msg, md, 0, 0);
5029
5030         lnet_prep_send(msg, LNET_MSG_GET, target, 0, 0);
5031
5032         msg->msg_hdr.msg.get.match_bits = cpu_to_le64(match_bits);
5033         msg->msg_hdr.msg.get.ptl_index = cpu_to_le32(portal);
5034         msg->msg_hdr.msg.get.src_offset = cpu_to_le32(offset);
5035         msg->msg_hdr.msg.get.sink_length = cpu_to_le32(md->md_length);
5036
5037         /* NB handles only looked up by creator (no flips) */
5038         msg->msg_hdr.msg.get.return_wmd.wh_interface_cookie =
5039                 the_lnet.ln_interface_cookie;
5040         msg->msg_hdr.msg.get.return_wmd.wh_object_cookie =
5041                 md->md_lh.lh_cookie;
5042
5043         lnet_res_unlock(cpt);
5044
5045         lnet_build_msg_event(msg, LNET_EVENT_SEND);
5046
5047         lnet_attach_rsp_tracker(rspt, cpt, md, mdh);
5048
5049         rc = lnet_send(self, msg, LNET_NID_ANY);
5050         if (rc < 0) {
5051                 CNETERR("Error sending GET to %s: %d\n",
5052                         libcfs_id2str(target), rc);
5053                 msg->msg_no_resend = true;
5054                 lnet_finalize(msg, rc);
5055         }
5056
5057         /* completion will be signalled by an event */
5058         return 0;
5059 }
5060 EXPORT_SYMBOL(LNetGet);
5061
5062 /**
5063  * Calculate distance to node at \a dstnid.
5064  *
5065  * \param dstnid Target NID.
5066  * \param srcnidp If not NULL, NID of the local interface to reach \a dstnid
5067  * is saved here.
5068  * \param orderp If not NULL, order of the route to reach \a dstnid is saved
5069  * here.
5070  *
5071  * \retval 0 If \a dstnid belongs to a local interface, and reserved option
5072  * local_nid_dist_zero is set, which is the default.
5073  * \retval positives Distance to target NID, i.e. number of hops plus one.
5074  * \retval -EHOSTUNREACH If \a dstnid is not reachable.
5075  */
5076 int
5077 LNetDist(lnet_nid_t dstnid, lnet_nid_t *srcnidp, __u32 *orderp)
5078 {
5079         struct list_head        *e;
5080         struct lnet_ni *ni = NULL;
5081         struct lnet_remotenet *rnet;
5082         __u32                   dstnet = LNET_NIDNET(dstnid);
5083         int                     hops;
5084         int                     cpt;
5085         __u32                   order = 2;
5086         struct list_head        *rn_list;
5087
5088         /* if !local_nid_dist_zero, I don't return a distance of 0 ever
5089          * (when lustre sees a distance of 0, it substitutes 0@lo), so I
5090          * keep order 0 free for 0@lo and order 1 free for a local NID
5091          * match */
5092
5093         LASSERT(the_lnet.ln_refcount > 0);
5094
5095         cpt = lnet_net_lock_current();
5096
5097         while ((ni = lnet_get_next_ni_locked(NULL, ni))) {
5098                 if (ni->ni_nid == dstnid) {
5099                         if (srcnidp != NULL)
5100                                 *srcnidp = dstnid;
5101                         if (orderp != NULL) {
5102                                 if (LNET_NETTYP(LNET_NIDNET(dstnid)) == LOLND)
5103                                         *orderp = 0;
5104                                 else
5105                                         *orderp = 1;
5106                         }
5107                         lnet_net_unlock(cpt);
5108
5109                         return local_nid_dist_zero ? 0 : 1;
5110                 }
5111
5112                 if (LNET_NIDNET(ni->ni_nid) == dstnet) {
5113                         /* Check if ni was originally created in
5114                          * current net namespace.
5115                          * If not, assign order above 0xffff0000,
5116                          * to make this ni not a priority. */
5117                         if (current->nsproxy &&
5118                             !net_eq(ni->ni_net_ns, current->nsproxy->net_ns))
5119                                         order += 0xffff0000;
5120                         if (srcnidp != NULL)
5121                                 *srcnidp = ni->ni_nid;
5122                         if (orderp != NULL)
5123                                 *orderp = order;
5124                         lnet_net_unlock(cpt);
5125                         return 1;
5126                 }
5127
5128                 order++;
5129         }
5130
5131         rn_list = lnet_net2rnethash(dstnet);
5132         list_for_each(e, rn_list) {
5133                 rnet = list_entry(e, struct lnet_remotenet, lrn_list);
5134
5135                 if (rnet->lrn_net == dstnet) {
5136                         struct lnet_route *route;
5137                         struct lnet_route *shortest = NULL;
5138                         __u32 shortest_hops = LNET_UNDEFINED_HOPS;
5139                         __u32 route_hops;
5140
5141                         LASSERT(!list_empty(&rnet->lrn_routes));
5142
5143                         list_for_each_entry(route, &rnet->lrn_routes,
5144                                             lr_list) {
5145                                 route_hops = route->lr_hops;
5146                                 if (route_hops == LNET_UNDEFINED_HOPS)
5147                                         route_hops = 1;
5148                                 if (shortest == NULL ||
5149                                     route_hops < shortest_hops) {
5150                                         shortest = route;
5151                                         shortest_hops = route_hops;
5152                                 }
5153                         }
5154
5155                         LASSERT(shortest != NULL);
5156                         hops = shortest_hops;
5157                         if (srcnidp != NULL) {
5158                                 struct lnet_net *net;
5159                                 net = lnet_get_net_locked(shortest->lr_lnet);
5160                                 LASSERT(net);
5161                                 ni = lnet_get_next_ni_locked(net, NULL);
5162                                 *srcnidp = ni->ni_nid;
5163                         }
5164                         if (orderp != NULL)
5165                                 *orderp = order;
5166                         lnet_net_unlock(cpt);
5167                         return hops + 1;
5168                 }
5169                 order++;
5170         }
5171
5172         lnet_net_unlock(cpt);
5173         return -EHOSTUNREACH;
5174 }
5175 EXPORT_SYMBOL(LNetDist);