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