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