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