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