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