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