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