Whamcloud - gitweb
cefc4b6f5671191b1baa4be3e057769d58abacfd
[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 struct lnet_comm_count *
73 get_stats_counts(struct lnet_element_stats *stats,
74                  enum lnet_stats_type stats_type)
75 {
76         switch (stats_type) {
77         case LNET_STATS_TYPE_SEND:
78                 return &stats->el_send_stats;
79         case LNET_STATS_TYPE_RECV:
80                 return &stats->el_recv_stats;
81         case LNET_STATS_TYPE_DROP:
82                 return &stats->el_drop_stats;
83         default:
84                 CERROR("Unknown stats type\n");
85         }
86
87         return NULL;
88 }
89
90 void lnet_incr_stats(struct lnet_element_stats *stats,
91                      enum lnet_msg_type msg_type,
92                      enum lnet_stats_type stats_type)
93 {
94         struct lnet_comm_count *counts = get_stats_counts(stats, stats_type);
95         if (!counts)
96                 return;
97
98         switch (msg_type) {
99         case LNET_MSG_ACK:
100                 atomic_inc(&counts->co_ack_count);
101                 break;
102         case LNET_MSG_PUT:
103                 atomic_inc(&counts->co_put_count);
104                 break;
105         case LNET_MSG_GET:
106                 atomic_inc(&counts->co_get_count);
107                 break;
108         case LNET_MSG_REPLY:
109                 atomic_inc(&counts->co_reply_count);
110                 break;
111         case LNET_MSG_HELLO:
112                 atomic_inc(&counts->co_hello_count);
113                 break;
114         default:
115                 CERROR("There is a BUG in the code. Unknown message type\n");
116                 break;
117         }
118 }
119
120 __u32 lnet_sum_stats(struct lnet_element_stats *stats,
121                      enum lnet_stats_type stats_type)
122 {
123         struct lnet_comm_count *counts = get_stats_counts(stats, stats_type);
124         if (!counts)
125                 return 0;
126
127         return (atomic_read(&counts->co_ack_count) +
128                 atomic_read(&counts->co_put_count) +
129                 atomic_read(&counts->co_get_count) +
130                 atomic_read(&counts->co_reply_count) +
131                 atomic_read(&counts->co_hello_count));
132 }
133
134 static inline void assign_stats(struct lnet_ioctl_comm_count *msg_stats,
135                                 struct lnet_comm_count *counts)
136 {
137         msg_stats->ico_get_count = atomic_read(&counts->co_get_count);
138         msg_stats->ico_put_count = atomic_read(&counts->co_put_count);
139         msg_stats->ico_reply_count = atomic_read(&counts->co_reply_count);
140         msg_stats->ico_ack_count = atomic_read(&counts->co_ack_count);
141         msg_stats->ico_hello_count = atomic_read(&counts->co_hello_count);
142 }
143
144 void lnet_usr_translate_stats(struct lnet_ioctl_element_msg_stats *msg_stats,
145                               struct lnet_element_stats *stats)
146 {
147         struct lnet_comm_count *counts;
148
149         LASSERT(msg_stats);
150         LASSERT(stats);
151
152         counts = get_stats_counts(stats, LNET_STATS_TYPE_SEND);
153         if (!counts)
154                 return;
155         assign_stats(&msg_stats->im_send_stats, counts);
156
157         counts = get_stats_counts(stats, LNET_STATS_TYPE_RECV);
158         if (!counts)
159                 return;
160         assign_stats(&msg_stats->im_recv_stats, counts);
161
162         counts = get_stats_counts(stats, LNET_STATS_TYPE_DROP);
163         if (!counts)
164                 return;
165         assign_stats(&msg_stats->im_drop_stats, counts);
166 }
167
168 int
169 lnet_fail_nid(lnet_nid_t nid, unsigned int threshold)
170 {
171         struct lnet_test_peer *tp;
172         struct list_head *el;
173         struct list_head *next;
174         LIST_HEAD(cull);
175
176         /* NB: use lnet_net_lock(0) to serialize operations on test peers */
177         if (threshold != 0) {
178                 /* Adding a new entry */
179                 LIBCFS_ALLOC(tp, sizeof(*tp));
180                 if (tp == NULL)
181                         return -ENOMEM;
182
183                 tp->tp_nid = nid;
184                 tp->tp_threshold = threshold;
185
186                 lnet_net_lock(0);
187                 list_add_tail(&tp->tp_list, &the_lnet.ln_test_peers);
188                 lnet_net_unlock(0);
189                 return 0;
190         }
191
192         lnet_net_lock(0);
193
194         list_for_each_safe(el, next, &the_lnet.ln_test_peers) {
195                 tp = list_entry(el, struct lnet_test_peer, tp_list);
196
197                 if (tp->tp_threshold == 0 ||    /* needs culling anyway */
198                     nid == LNET_NID_ANY ||      /* removing all entries */
199                     tp->tp_nid == nid) {        /* matched this one */
200                         list_move(&tp->tp_list, &cull);
201                 }
202         }
203
204         lnet_net_unlock(0);
205
206         while (!list_empty(&cull)) {
207                 tp = list_entry(cull.next, struct lnet_test_peer, tp_list);
208
209                 list_del(&tp->tp_list);
210                 LIBCFS_FREE(tp, sizeof(*tp));
211         }
212         return 0;
213 }
214
215 static int
216 fail_peer (lnet_nid_t nid, int outgoing)
217 {
218         struct lnet_test_peer *tp;
219         struct list_head *el;
220         struct list_head *next;
221         LIST_HEAD(cull);
222         int fail = 0;
223
224         /* NB: use lnet_net_lock(0) to serialize operations on test peers */
225         lnet_net_lock(0);
226
227         list_for_each_safe(el, next, &the_lnet.ln_test_peers) {
228                 tp = list_entry(el, struct lnet_test_peer, tp_list);
229
230                 if (tp->tp_threshold == 0) {
231                         /* zombie entry */
232                         if (outgoing) {
233                                 /* only cull zombies on outgoing tests,
234                                  * since we may be at interrupt priority on
235                                  * incoming messages. */
236                                 list_move(&tp->tp_list, &cull);
237                         }
238                         continue;
239                 }
240
241                 if (tp->tp_nid == LNET_NID_ANY ||       /* fail every peer */
242                     nid == tp->tp_nid) {                /* fail this peer */
243                         fail = 1;
244
245                         if (tp->tp_threshold != LNET_MD_THRESH_INF) {
246                                 tp->tp_threshold--;
247                                 if (outgoing &&
248                                     tp->tp_threshold == 0) {
249                                         /* see above */
250                                         list_move(&tp->tp_list, &cull);
251                                 }
252                         }
253                         break;
254                 }
255         }
256
257         lnet_net_unlock(0);
258
259         while (!list_empty(&cull)) {
260                 tp = list_entry(cull.next, struct lnet_test_peer, tp_list);
261                 list_del(&tp->tp_list);
262
263                 LIBCFS_FREE(tp, sizeof(*tp));
264         }
265
266         return fail;
267 }
268
269 unsigned int
270 lnet_iov_nob(unsigned int niov, struct kvec *iov)
271 {
272         unsigned int nob = 0;
273
274         LASSERT(niov == 0 || iov != NULL);
275         while (niov-- > 0)
276                 nob += (iov++)->iov_len;
277
278         return (nob);
279 }
280 EXPORT_SYMBOL(lnet_iov_nob);
281
282 void
283 lnet_copy_iov2iov(unsigned int ndiov, struct kvec *diov, unsigned int doffset,
284                   unsigned int nsiov, struct kvec *siov, unsigned int soffset,
285                   unsigned int nob)
286 {
287         /* NB diov, siov are READ-ONLY */
288         unsigned int this_nob;
289
290         if (nob == 0)
291                 return;
292
293         /* skip complete frags before 'doffset' */
294         LASSERT(ndiov > 0);
295         while (doffset >= diov->iov_len) {
296                 doffset -= diov->iov_len;
297                 diov++;
298                 ndiov--;
299                 LASSERT(ndiov > 0);
300         }
301
302         /* skip complete frags before 'soffset' */
303         LASSERT(nsiov > 0);
304         while (soffset >= siov->iov_len) {
305                 soffset -= siov->iov_len;
306                 siov++;
307                 nsiov--;
308                 LASSERT(nsiov > 0);
309         }
310
311         do {
312                 LASSERT(ndiov > 0);
313                 LASSERT(nsiov > 0);
314                 this_nob = min3((unsigned int)diov->iov_len - doffset,
315                                 (unsigned int)siov->iov_len - soffset,
316                                 nob);
317
318                 memcpy((char *)diov->iov_base + doffset,
319                        (char *)siov->iov_base + soffset, this_nob);
320                 nob -= this_nob;
321
322                 if (diov->iov_len > doffset + this_nob) {
323                         doffset += this_nob;
324                 } else {
325                         diov++;
326                         ndiov--;
327                         doffset = 0;
328                 }
329
330                 if (siov->iov_len > soffset + this_nob) {
331                         soffset += this_nob;
332                 } else {
333                         siov++;
334                         nsiov--;
335                         soffset = 0;
336                 }
337         } while (nob > 0);
338 }
339 EXPORT_SYMBOL(lnet_copy_iov2iov);
340
341 int
342 lnet_extract_iov(int dst_niov, struct kvec *dst,
343                  int src_niov, struct kvec *src,
344                  unsigned int offset, unsigned int len)
345 {
346         /* Initialise 'dst' to the subset of 'src' starting at 'offset',
347          * for exactly 'len' bytes, and return the number of entries.
348          * NB not destructive to 'src' */
349         unsigned int    frag_len;
350         unsigned int    niov;
351
352         if (len == 0)                           /* no data => */
353                 return (0);                     /* no frags */
354
355         LASSERT(src_niov > 0);
356         while (offset >= src->iov_len) {      /* skip initial frags */
357                 offset -= src->iov_len;
358                 src_niov--;
359                 src++;
360                 LASSERT(src_niov > 0);
361         }
362
363         niov = 1;
364         for (;;) {
365                 LASSERT(src_niov > 0);
366                 LASSERT((int)niov <= dst_niov);
367
368                 frag_len = src->iov_len - offset;
369                 dst->iov_base = ((char *)src->iov_base) + offset;
370
371                 if (len <= frag_len) {
372                         dst->iov_len = len;
373                         return (niov);
374                 }
375
376                 dst->iov_len = frag_len;
377
378                 len -= frag_len;
379                 dst++;
380                 src++;
381                 niov++;
382                 src_niov--;
383                 offset = 0;
384         }
385 }
386 EXPORT_SYMBOL(lnet_extract_iov);
387
388
389 unsigned int
390 lnet_kiov_nob(unsigned int niov, struct bio_vec *kiov)
391 {
392         unsigned int  nob = 0;
393
394         LASSERT(niov == 0 || kiov != NULL);
395         while (niov-- > 0)
396                 nob += (kiov++)->bv_len;
397
398         return (nob);
399 }
400 EXPORT_SYMBOL(lnet_kiov_nob);
401
402 void
403 lnet_copy_kiov2kiov(unsigned int ndiov, struct bio_vec *diov,
404                     unsigned int doffset,
405                     unsigned int nsiov, struct bio_vec *siov,
406                     unsigned int soffset,
407                     unsigned int nob)
408 {
409         /* NB diov, siov are READ-ONLY */
410         unsigned int    this_nob;
411         char           *daddr = NULL;
412         char           *saddr = NULL;
413
414         if (nob == 0)
415                 return;
416
417         LASSERT (!in_interrupt ());
418
419         LASSERT (ndiov > 0);
420         while (doffset >= diov->bv_len) {
421                 doffset -= diov->bv_len;
422                 diov++;
423                 ndiov--;
424                 LASSERT(ndiov > 0);
425         }
426
427         LASSERT(nsiov > 0);
428         while (soffset >= siov->bv_len) {
429                 soffset -= siov->bv_len;
430                 siov++;
431                 nsiov--;
432                 LASSERT(nsiov > 0);
433         }
434
435         do {
436                 LASSERT(ndiov > 0);
437                 LASSERT(nsiov > 0);
438                 this_nob = min3(diov->bv_len - doffset,
439                                 siov->bv_len - soffset,
440                                 nob);
441
442                 if (daddr == NULL)
443                         daddr = ((char *)kmap(diov->bv_page)) +
444                                 diov->bv_offset + doffset;
445                 if (saddr == NULL)
446                         saddr = ((char *)kmap(siov->bv_page)) +
447                                 siov->bv_offset + soffset;
448
449                 /* Vanishing risk of kmap deadlock when mapping 2 pages.
450                  * However in practice at least one of the kiovs will be mapped
451                  * kernel pages and the map/unmap will be NOOPs */
452
453                 memcpy (daddr, saddr, this_nob);
454                 nob -= this_nob;
455
456                 if (diov->bv_len > doffset + this_nob) {
457                         daddr += this_nob;
458                         doffset += this_nob;
459                 } else {
460                         kunmap(diov->bv_page);
461                         daddr = NULL;
462                         diov++;
463                         ndiov--;
464                         doffset = 0;
465                 }
466
467                 if (siov->bv_len > soffset + this_nob) {
468                         saddr += this_nob;
469                         soffset += this_nob;
470                 } else {
471                         kunmap(siov->bv_page);
472                         saddr = NULL;
473                         siov++;
474                         nsiov--;
475                         soffset = 0;
476                 }
477         } while (nob > 0);
478
479         if (daddr != NULL)
480                 kunmap(diov->bv_page);
481         if (saddr != NULL)
482                 kunmap(siov->bv_page);
483 }
484 EXPORT_SYMBOL(lnet_copy_kiov2kiov);
485
486 void
487 lnet_copy_kiov2iov (unsigned int niov, struct kvec *iov, unsigned int iovoffset,
488                     unsigned int nkiov, struct bio_vec *kiov,
489                     unsigned int kiovoffset,
490                     unsigned int nob)
491 {
492         /* NB iov, kiov are READ-ONLY */
493         unsigned int    this_nob;
494         char           *addr = NULL;
495
496         if (nob == 0)
497                 return;
498
499         LASSERT (!in_interrupt ());
500
501         LASSERT (niov > 0);
502         while (iovoffset >= iov->iov_len) {
503                 iovoffset -= iov->iov_len;
504                 iov++;
505                 niov--;
506                 LASSERT(niov > 0);
507         }
508
509         LASSERT(nkiov > 0);
510         while (kiovoffset >= kiov->bv_len) {
511                 kiovoffset -= kiov->bv_len;
512                 kiov++;
513                 nkiov--;
514                 LASSERT(nkiov > 0);
515         }
516
517         do {
518                 LASSERT(niov > 0);
519                 LASSERT(nkiov > 0);
520                 this_nob = min3((unsigned int)iov->iov_len - iovoffset,
521                                 (unsigned int)kiov->bv_len - kiovoffset,
522                                 nob);
523
524                 if (addr == NULL)
525                         addr = ((char *)kmap(kiov->bv_page)) +
526                                 kiov->bv_offset + kiovoffset;
527
528                 memcpy((char *)iov->iov_base + iovoffset, addr, this_nob);
529                 nob -= this_nob;
530
531                 if (iov->iov_len > iovoffset + this_nob) {
532                         iovoffset += this_nob;
533                 } else {
534                         iov++;
535                         niov--;
536                         iovoffset = 0;
537                 }
538
539                 if (kiov->bv_len > kiovoffset + this_nob) {
540                         addr += this_nob;
541                         kiovoffset += this_nob;
542                 } else {
543                         kunmap(kiov->bv_page);
544                         addr = NULL;
545                         kiov++;
546                         nkiov--;
547                         kiovoffset = 0;
548                 }
549
550         } while (nob > 0);
551
552         if (addr != NULL)
553                 kunmap(kiov->bv_page);
554 }
555 EXPORT_SYMBOL(lnet_copy_kiov2iov);
556
557 void
558 lnet_copy_iov2kiov(unsigned int nkiov, struct bio_vec *kiov,
559                    unsigned int kiovoffset,
560                    unsigned int niov, struct kvec *iov, unsigned int iovoffset,
561                    unsigned int nob)
562 {
563         /* NB kiov, iov are READ-ONLY */
564         unsigned int    this_nob;
565         char           *addr = NULL;
566
567         if (nob == 0)
568                 return;
569
570         LASSERT (!in_interrupt ());
571
572         LASSERT (nkiov > 0);
573         while (kiovoffset >= kiov->bv_len) {
574                 kiovoffset -= kiov->bv_len;
575                 kiov++;
576                 nkiov--;
577                 LASSERT(nkiov > 0);
578         }
579
580         LASSERT(niov > 0);
581         while (iovoffset >= iov->iov_len) {
582                 iovoffset -= iov->iov_len;
583                 iov++;
584                 niov--;
585                 LASSERT(niov > 0);
586         }
587
588         do {
589                 LASSERT(nkiov > 0);
590                 LASSERT(niov > 0);
591                 this_nob = min3((unsigned int)kiov->bv_len - kiovoffset,
592                                 (unsigned int)iov->iov_len - iovoffset,
593                                 nob);
594
595                 if (addr == NULL)
596                         addr = ((char *)kmap(kiov->bv_page)) +
597                                 kiov->bv_offset + kiovoffset;
598
599                 memcpy (addr, (char *)iov->iov_base + iovoffset, this_nob);
600                 nob -= this_nob;
601
602                 if (kiov->bv_len > kiovoffset + this_nob) {
603                         addr += this_nob;
604                         kiovoffset += this_nob;
605                 } else {
606                         kunmap(kiov->bv_page);
607                         addr = NULL;
608                         kiov++;
609                         nkiov--;
610                         kiovoffset = 0;
611                 }
612
613                 if (iov->iov_len > iovoffset + this_nob) {
614                         iovoffset += this_nob;
615                 } else {
616                         iov++;
617                         niov--;
618                         iovoffset = 0;
619                 }
620         } while (nob > 0);
621
622         if (addr != NULL)
623                 kunmap(kiov->bv_page);
624 }
625 EXPORT_SYMBOL(lnet_copy_iov2kiov);
626
627 int
628 lnet_extract_kiov(int dst_niov, struct bio_vec *dst,
629                   int src_niov, struct bio_vec *src,
630                   unsigned int offset, unsigned int len)
631 {
632         /* Initialise 'dst' to the subset of 'src' starting at 'offset',
633          * for exactly 'len' bytes, and return the number of entries.
634          * NB not destructive to 'src' */
635         unsigned int    frag_len;
636         unsigned int    niov;
637
638         if (len == 0)                           /* no data => */
639                 return (0);                     /* no frags */
640
641         LASSERT(src_niov > 0);
642         while (offset >= src->bv_len) {      /* skip initial frags */
643                 offset -= src->bv_len;
644                 src_niov--;
645                 src++;
646                 LASSERT(src_niov > 0);
647         }
648
649         niov = 1;
650         for (;;) {
651                 LASSERT(src_niov > 0);
652                 LASSERT((int)niov <= dst_niov);
653
654                 frag_len = src->bv_len - offset;
655                 dst->bv_page = src->bv_page;
656                 dst->bv_offset = src->bv_offset + offset;
657
658                 if (len <= frag_len) {
659                         dst->bv_len = len;
660                         LASSERT(dst->bv_offset + dst->bv_len <= PAGE_SIZE);
661                         return niov;
662                 }
663
664                 dst->bv_len = frag_len;
665                 LASSERT(dst->bv_offset + dst->bv_len <= PAGE_SIZE);
666
667                 len -= frag_len;
668                 dst++;
669                 src++;
670                 niov++;
671                 src_niov--;
672                 offset = 0;
673         }
674 }
675 EXPORT_SYMBOL(lnet_extract_kiov);
676
677 void
678 lnet_ni_recv(struct lnet_ni *ni, void *private, struct lnet_msg *msg,
679              int delayed, unsigned int offset, unsigned int mlen,
680              unsigned int rlen)
681 {
682         unsigned int niov = 0;
683         struct kvec *iov = NULL;
684         struct bio_vec  *kiov = NULL;
685         int rc;
686
687         LASSERT (!in_interrupt ());
688         LASSERT (mlen == 0 || msg != NULL);
689
690         if (msg != NULL) {
691                 LASSERT(msg->msg_receiving);
692                 LASSERT(!msg->msg_sending);
693                 LASSERT(rlen == msg->msg_len);
694                 LASSERT(mlen <= msg->msg_len);
695                 LASSERT(msg->msg_offset == offset);
696                 LASSERT(msg->msg_wanted == mlen);
697
698                 msg->msg_receiving = 0;
699
700                 if (mlen != 0) {
701                         niov = msg->msg_niov;
702                         kiov = msg->msg_kiov;
703
704                         LASSERT (niov > 0);
705                         LASSERT ((iov == NULL) != (kiov == NULL));
706                 }
707         }
708
709         rc = (ni->ni_net->net_lnd->lnd_recv)(ni, private, msg, delayed,
710                                              niov, kiov, offset, mlen,
711                                              rlen);
712         if (rc < 0)
713                 lnet_finalize(msg, rc);
714 }
715
716 static void
717 lnet_setpayloadbuffer(struct lnet_msg *msg)
718 {
719         struct lnet_libmd *md = msg->msg_md;
720
721         LASSERT(msg->msg_len > 0);
722         LASSERT(!msg->msg_routing);
723         LASSERT(md != NULL);
724         LASSERT(msg->msg_niov == 0);
725         LASSERT(msg->msg_kiov == NULL);
726
727         msg->msg_niov = md->md_niov;
728         msg->msg_kiov = md->md_kiov;
729 }
730
731 void
732 lnet_prep_send(struct lnet_msg *msg, int type, struct lnet_process_id target,
733                unsigned int offset, unsigned int len)
734 {
735         msg->msg_type = type;
736         msg->msg_target = target;
737         msg->msg_len = len;
738         msg->msg_offset = offset;
739
740         if (len != 0)
741                 lnet_setpayloadbuffer(msg);
742
743         memset (&msg->msg_hdr, 0, sizeof (msg->msg_hdr));
744         msg->msg_hdr.type           = cpu_to_le32(type);
745         /* dest_nid will be overwritten by lnet_select_pathway() */
746         msg->msg_hdr.dest_nid       = cpu_to_le64(target.nid);
747         msg->msg_hdr.dest_pid       = cpu_to_le32(target.pid);
748         /* src_nid will be set later */
749         msg->msg_hdr.src_pid        = cpu_to_le32(the_lnet.ln_pid);
750         msg->msg_hdr.payload_length = cpu_to_le32(len);
751 }
752
753 static void
754 lnet_ni_send(struct lnet_ni *ni, struct lnet_msg *msg)
755 {
756         void *priv = msg->msg_private;
757         int rc;
758
759         LASSERT(!in_interrupt());
760         LASSERT(ni->ni_nid == LNET_NID_LO_0 ||
761                 (msg->msg_txcredit && msg->msg_peertxcredit));
762
763         rc = (ni->ni_net->net_lnd->lnd_send)(ni, priv, msg);
764         if (rc < 0) {
765                 msg->msg_no_resend = true;
766                 lnet_finalize(msg, rc);
767         }
768 }
769
770 static int
771 lnet_ni_eager_recv(struct lnet_ni *ni, struct lnet_msg *msg)
772 {
773         int     rc;
774
775         LASSERT(!msg->msg_sending);
776         LASSERT(msg->msg_receiving);
777         LASSERT(!msg->msg_rx_ready_delay);
778         LASSERT(ni->ni_net->net_lnd->lnd_eager_recv != NULL);
779
780         msg->msg_rx_ready_delay = 1;
781         rc = (ni->ni_net->net_lnd->lnd_eager_recv)(ni, msg->msg_private, msg,
782                                                   &msg->msg_private);
783         if (rc != 0) {
784                 CERROR("recv from %s / send to %s aborted: "
785                        "eager_recv failed %d\n",
786                        libcfs_nid2str(msg->msg_rxpeer->lpni_nid),
787                        libcfs_id2str(msg->msg_target), rc);
788                 LASSERT(rc < 0); /* required by my callers */
789         }
790
791         return rc;
792 }
793
794 static bool
795 lnet_is_peer_deadline_passed(struct lnet_peer_ni *lpni, time64_t now)
796 {
797         time64_t deadline;
798
799         deadline = lpni->lpni_last_alive +
800                    lpni->lpni_net->net_tunables.lct_peer_timeout;
801
802         /*
803          * assume peer_ni is alive as long as we're within the configured
804          * peer timeout
805          */
806         if (deadline > now)
807                 return false;
808
809         return true;
810 }
811
812 /* NB: returns 1 when alive, 0 when dead, negative when error;
813  *     may drop the lnet_net_lock */
814 static int
815 lnet_peer_alive_locked(struct lnet_ni *ni, struct lnet_peer_ni *lpni,
816                        struct lnet_msg *msg)
817 {
818         time64_t now = ktime_get_seconds();
819
820         if (!lnet_peer_aliveness_enabled(lpni))
821                 return -ENODEV;
822
823         /*
824          * If we're resending a message, let's attempt to send it even if
825          * the peer is down to fulfill our resend quota on the message
826          */
827         if (msg->msg_retry_count > 0)
828                 return 1;
829
830         /* try and send recovery messages irregardless */
831         if (msg->msg_recovery)
832                 return 1;
833
834         /* always send any responses */
835         if (lnet_msg_is_response(msg))
836                 return 1;
837
838         if (!lnet_is_peer_deadline_passed(lpni, now))
839                 return true;
840
841         return lnet_is_peer_ni_alive(lpni);
842 }
843
844 /**
845  * \param msg The message to be sent.
846  * \param do_send True if lnet_ni_send() should be called in this function.
847  *        lnet_send() is going to lnet_net_unlock immediately after this, so
848  *        it sets do_send FALSE and I don't do the unlock/send/lock bit.
849  *
850  * \retval LNET_CREDIT_OK If \a msg sent or OK to send.
851  * \retval LNET_CREDIT_WAIT If \a msg blocked for credit.
852  * \retval -EHOSTUNREACH If the next hop of the message appears dead.
853  * \retval -ECANCELED If the MD of the message has been unlinked.
854  */
855 static int
856 lnet_post_send_locked(struct lnet_msg *msg, int do_send)
857 {
858         struct lnet_peer_ni     *lp = msg->msg_txpeer;
859         struct lnet_ni          *ni = msg->msg_txni;
860         int                     cpt = msg->msg_tx_cpt;
861         struct lnet_tx_queue    *tq = ni->ni_tx_queues[cpt];
862
863         /* non-lnet_send() callers have checked before */
864         LASSERT(!do_send || msg->msg_tx_delayed);
865         LASSERT(!msg->msg_receiving);
866         LASSERT(msg->msg_tx_committed);
867         /* can't get here if we're sending to the loopback interface */
868         LASSERT(lp->lpni_nid != the_lnet.ln_loni->ni_nid);
869
870         /* NB 'lp' is always the next hop */
871         if ((msg->msg_target.pid & LNET_PID_USERFLAG) == 0 &&
872             lnet_peer_alive_locked(ni, lp, msg) == 0) {
873                 the_lnet.ln_counters[cpt]->lct_common.lcc_drop_count++;
874                 the_lnet.ln_counters[cpt]->lct_common.lcc_drop_length +=
875                         msg->msg_len;
876                 lnet_net_unlock(cpt);
877                 if (msg->msg_txpeer)
878                         lnet_incr_stats(&msg->msg_txpeer->lpni_stats,
879                                         msg->msg_type,
880                                         LNET_STATS_TYPE_DROP);
881                 if (msg->msg_txni)
882                         lnet_incr_stats(&msg->msg_txni->ni_stats,
883                                         msg->msg_type,
884                                         LNET_STATS_TYPE_DROP);
885
886                 CNETERR("Dropping message for %s: peer not alive\n",
887                         libcfs_id2str(msg->msg_target));
888                 msg->msg_health_status = LNET_MSG_STATUS_REMOTE_DROPPED;
889                 if (do_send)
890                         lnet_finalize(msg, -EHOSTUNREACH);
891
892                 lnet_net_lock(cpt);
893                 return -EHOSTUNREACH;
894         }
895
896         if (msg->msg_md != NULL &&
897             (msg->msg_md->md_flags & LNET_MD_FLAG_ABORTED) != 0) {
898                 lnet_net_unlock(cpt);
899
900                 CNETERR("Aborting message for %s: LNetM[DE]Unlink() already "
901                         "called on the MD/ME.\n",
902                         libcfs_id2str(msg->msg_target));
903                 if (do_send) {
904                         msg->msg_no_resend = true;
905                         CDEBUG(D_NET, "msg %p to %s canceled and will not be resent\n",
906                                msg, libcfs_id2str(msg->msg_target));
907                         lnet_finalize(msg, -ECANCELED);
908                 }
909
910                 lnet_net_lock(cpt);
911                 return -ECANCELED;
912         }
913
914         if (!msg->msg_peertxcredit) {
915                 spin_lock(&lp->lpni_lock);
916                 LASSERT((lp->lpni_txcredits < 0) ==
917                         !list_empty(&lp->lpni_txq));
918
919                 msg->msg_peertxcredit = 1;
920                 lp->lpni_txqnob += msg->msg_len + sizeof(struct lnet_hdr);
921                 lp->lpni_txcredits--;
922
923                 if (lp->lpni_txcredits < lp->lpni_mintxcredits)
924                         lp->lpni_mintxcredits = lp->lpni_txcredits;
925
926                 if (lp->lpni_txcredits < 0) {
927                         msg->msg_tx_delayed = 1;
928                         list_add_tail(&msg->msg_list, &lp->lpni_txq);
929                         spin_unlock(&lp->lpni_lock);
930                         return LNET_CREDIT_WAIT;
931                 }
932                 spin_unlock(&lp->lpni_lock);
933         }
934
935         if (!msg->msg_txcredit) {
936                 LASSERT((tq->tq_credits < 0) ==
937                         !list_empty(&tq->tq_delayed));
938
939                 msg->msg_txcredit = 1;
940                 tq->tq_credits--;
941                 atomic_dec(&ni->ni_tx_credits);
942
943                 if (tq->tq_credits < tq->tq_credits_min)
944                         tq->tq_credits_min = tq->tq_credits;
945
946                 if (tq->tq_credits < 0) {
947                         msg->msg_tx_delayed = 1;
948                         list_add_tail(&msg->msg_list, &tq->tq_delayed);
949                         return LNET_CREDIT_WAIT;
950                 }
951         }
952
953         /* unset the tx_delay flag as we're going to send it now */
954         msg->msg_tx_delayed = 0;
955
956         if (do_send) {
957                 lnet_net_unlock(cpt);
958                 lnet_ni_send(ni, msg);
959                 lnet_net_lock(cpt);
960         }
961         return LNET_CREDIT_OK;
962 }
963
964
965 static struct lnet_rtrbufpool *
966 lnet_msg2bufpool(struct lnet_msg *msg)
967 {
968         struct lnet_rtrbufpool  *rbp;
969         int                     cpt;
970
971         LASSERT(msg->msg_rx_committed);
972
973         cpt = msg->msg_rx_cpt;
974         rbp = &the_lnet.ln_rtrpools[cpt][0];
975
976         LASSERT(msg->msg_len <= LNET_MTU);
977         while (msg->msg_len > (unsigned int)rbp->rbp_npages * PAGE_SIZE) {
978                 rbp++;
979                 LASSERT(rbp < &the_lnet.ln_rtrpools[cpt][LNET_NRBPOOLS]);
980         }
981
982         return rbp;
983 }
984
985 static int
986 lnet_post_routed_recv_locked(struct lnet_msg *msg, int do_recv)
987 {
988         /* lnet_parse is going to lnet_net_unlock immediately after this, so it
989          * sets do_recv FALSE and I don't do the unlock/send/lock bit.
990          * I return LNET_CREDIT_WAIT if msg blocked and LNET_CREDIT_OK if
991          * received or OK to receive */
992         struct lnet_peer_ni *lpni = msg->msg_rxpeer;
993         struct lnet_peer *lp;
994         struct lnet_rtrbufpool *rbp;
995         struct lnet_rtrbuf *rb;
996
997         LASSERT(msg->msg_kiov == NULL);
998         LASSERT(msg->msg_niov == 0);
999         LASSERT(msg->msg_routing);
1000         LASSERT(msg->msg_receiving);
1001         LASSERT(!msg->msg_sending);
1002         LASSERT(lpni->lpni_peer_net);
1003         LASSERT(lpni->lpni_peer_net->lpn_peer);
1004
1005         lp = lpni->lpni_peer_net->lpn_peer;
1006
1007         /* non-lnet_parse callers only receive delayed messages */
1008         LASSERT(!do_recv || msg->msg_rx_delayed);
1009
1010         if (!msg->msg_peerrtrcredit) {
1011                 /* lpni_lock protects the credit manipulation */
1012                 spin_lock(&lpni->lpni_lock);
1013
1014                 msg->msg_peerrtrcredit = 1;
1015                 lpni->lpni_rtrcredits--;
1016                 if (lpni->lpni_rtrcredits < lpni->lpni_minrtrcredits)
1017                         lpni->lpni_minrtrcredits = lpni->lpni_rtrcredits;
1018
1019                 if (lpni->lpni_rtrcredits < 0) {
1020                         spin_unlock(&lpni->lpni_lock);
1021                         /* must have checked eager_recv before here */
1022                         LASSERT(msg->msg_rx_ready_delay);
1023                         msg->msg_rx_delayed = 1;
1024                         /* lp_lock protects the lp_rtrq */
1025                         spin_lock(&lp->lp_lock);
1026                         list_add_tail(&msg->msg_list, &lp->lp_rtrq);
1027                         spin_unlock(&lp->lp_lock);
1028                         return LNET_CREDIT_WAIT;
1029                 }
1030                 spin_unlock(&lpni->lpni_lock);
1031         }
1032
1033         rbp = lnet_msg2bufpool(msg);
1034
1035         if (!msg->msg_rtrcredit) {
1036                 msg->msg_rtrcredit = 1;
1037                 rbp->rbp_credits--;
1038                 if (rbp->rbp_credits < rbp->rbp_mincredits)
1039                         rbp->rbp_mincredits = rbp->rbp_credits;
1040
1041                 if (rbp->rbp_credits < 0) {
1042                         /* must have checked eager_recv before here */
1043                         LASSERT(msg->msg_rx_ready_delay);
1044                         msg->msg_rx_delayed = 1;
1045                         list_add_tail(&msg->msg_list, &rbp->rbp_msgs);
1046                         return LNET_CREDIT_WAIT;
1047                 }
1048         }
1049
1050         LASSERT(!list_empty(&rbp->rbp_bufs));
1051         rb = list_entry(rbp->rbp_bufs.next, struct lnet_rtrbuf, rb_list);
1052         list_del(&rb->rb_list);
1053
1054         msg->msg_niov = rbp->rbp_npages;
1055         msg->msg_kiov = &rb->rb_kiov[0];
1056
1057         /* unset the msg-rx_delayed flag since we're receiving the message */
1058         msg->msg_rx_delayed = 0;
1059
1060         if (do_recv) {
1061                 int cpt = msg->msg_rx_cpt;
1062
1063                 lnet_net_unlock(cpt);
1064                 lnet_ni_recv(msg->msg_rxni, msg->msg_private, msg, 1,
1065                              0, msg->msg_len, msg->msg_len);
1066                 lnet_net_lock(cpt);
1067         }
1068         return LNET_CREDIT_OK;
1069 }
1070
1071 void
1072 lnet_return_tx_credits_locked(struct lnet_msg *msg)
1073 {
1074         struct lnet_peer_ni     *txpeer = msg->msg_txpeer;
1075         struct lnet_ni          *txni = msg->msg_txni;
1076         struct lnet_msg         *msg2;
1077
1078         if (msg->msg_txcredit) {
1079                 struct lnet_ni       *ni = msg->msg_txni;
1080                 struct lnet_tx_queue *tq = ni->ni_tx_queues[msg->msg_tx_cpt];
1081
1082                 /* give back NI txcredits */
1083                 msg->msg_txcredit = 0;
1084
1085                 LASSERT((tq->tq_credits < 0) ==
1086                         !list_empty(&tq->tq_delayed));
1087
1088                 tq->tq_credits++;
1089                 atomic_inc(&ni->ni_tx_credits);
1090                 if (tq->tq_credits <= 0) {
1091                         msg2 = list_entry(tq->tq_delayed.next,
1092                                           struct lnet_msg, msg_list);
1093                         list_del(&msg2->msg_list);
1094
1095                         LASSERT(msg2->msg_txni == ni);
1096                         LASSERT(msg2->msg_tx_delayed);
1097                         LASSERT(msg2->msg_tx_cpt == msg->msg_tx_cpt);
1098
1099                         (void) lnet_post_send_locked(msg2, 1);
1100                 }
1101         }
1102
1103         if (msg->msg_peertxcredit) {
1104                 /* give back peer txcredits */
1105                 msg->msg_peertxcredit = 0;
1106
1107                 spin_lock(&txpeer->lpni_lock);
1108                 LASSERT((txpeer->lpni_txcredits < 0) ==
1109                         !list_empty(&txpeer->lpni_txq));
1110
1111                 txpeer->lpni_txqnob -= msg->msg_len + sizeof(struct lnet_hdr);
1112                 LASSERT(txpeer->lpni_txqnob >= 0);
1113
1114                 txpeer->lpni_txcredits++;
1115                 if (txpeer->lpni_txcredits <= 0) {
1116                         int msg2_cpt;
1117
1118                         msg2 = list_entry(txpeer->lpni_txq.next,
1119                                               struct lnet_msg, msg_list);
1120                         list_del(&msg2->msg_list);
1121                         spin_unlock(&txpeer->lpni_lock);
1122
1123                         LASSERT(msg2->msg_txpeer == txpeer);
1124                         LASSERT(msg2->msg_tx_delayed);
1125
1126                         msg2_cpt = msg2->msg_tx_cpt;
1127
1128                         /*
1129                          * The msg_cpt can be different from the msg2_cpt
1130                          * so we need to make sure we lock the correct cpt
1131                          * for msg2.
1132                          * Once we call lnet_post_send_locked() it is no
1133                          * longer safe to access msg2, since it could've
1134                          * been freed by lnet_finalize(), but we still
1135                          * need to relock the correct cpt, so we cache the
1136                          * msg2_cpt for the purpose of the check that
1137                          * follows the call to lnet_pose_send_locked().
1138                          */
1139                         if (msg2_cpt != msg->msg_tx_cpt) {
1140                                 lnet_net_unlock(msg->msg_tx_cpt);
1141                                 lnet_net_lock(msg2_cpt);
1142                         }
1143                         (void) lnet_post_send_locked(msg2, 1);
1144                         if (msg2_cpt != msg->msg_tx_cpt) {
1145                                 lnet_net_unlock(msg2_cpt);
1146                                 lnet_net_lock(msg->msg_tx_cpt);
1147                         }
1148                 } else {
1149                         spin_unlock(&txpeer->lpni_lock);
1150                 }
1151         }
1152
1153         if (txni != NULL) {
1154                 msg->msg_txni = NULL;
1155                 lnet_ni_decref_locked(txni, msg->msg_tx_cpt);
1156         }
1157
1158         if (txpeer != NULL) {
1159                 msg->msg_txpeer = NULL;
1160                 lnet_peer_ni_decref_locked(txpeer);
1161         }
1162 }
1163
1164 void
1165 lnet_schedule_blocked_locked(struct lnet_rtrbufpool *rbp)
1166 {
1167         struct lnet_msg *msg;
1168
1169         if (list_empty(&rbp->rbp_msgs))
1170                 return;
1171         msg = list_entry(rbp->rbp_msgs.next,
1172                          struct lnet_msg, msg_list);
1173         list_del(&msg->msg_list);
1174
1175         (void)lnet_post_routed_recv_locked(msg, 1);
1176 }
1177
1178 void
1179 lnet_drop_routed_msgs_locked(struct list_head *list, int cpt)
1180 {
1181         struct lnet_msg *msg;
1182         struct lnet_msg *tmp;
1183
1184         lnet_net_unlock(cpt);
1185
1186         list_for_each_entry_safe(msg, tmp, list, msg_list) {
1187                 lnet_ni_recv(msg->msg_rxni, msg->msg_private, NULL,
1188                              0, 0, 0, msg->msg_hdr.payload_length);
1189                 list_del_init(&msg->msg_list);
1190                 msg->msg_no_resend = true;
1191                 msg->msg_health_status = LNET_MSG_STATUS_REMOTE_ERROR;
1192                 lnet_finalize(msg, -ECANCELED);
1193         }
1194
1195         lnet_net_lock(cpt);
1196 }
1197
1198 void
1199 lnet_return_rx_credits_locked(struct lnet_msg *msg)
1200 {
1201         struct lnet_peer_ni *rxpeerni = msg->msg_rxpeer;
1202         struct lnet_peer *lp;
1203         struct lnet_ni *rxni = msg->msg_rxni;
1204         struct lnet_msg *msg2;
1205
1206         if (msg->msg_rtrcredit) {
1207                 /* give back global router credits */
1208                 struct lnet_rtrbuf *rb;
1209                 struct lnet_rtrbufpool *rbp;
1210
1211                 /* NB If a msg ever blocks for a buffer in rbp_msgs, it stays
1212                  * there until it gets one allocated, or aborts the wait
1213                  * itself */
1214                 LASSERT(msg->msg_kiov != NULL);
1215
1216                 rb = list_entry(msg->msg_kiov, struct lnet_rtrbuf, rb_kiov[0]);
1217                 rbp = rb->rb_pool;
1218
1219                 msg->msg_kiov = NULL;
1220                 msg->msg_rtrcredit = 0;
1221
1222                 LASSERT(rbp == lnet_msg2bufpool(msg));
1223
1224                 LASSERT((rbp->rbp_credits > 0) ==
1225                         !list_empty(&rbp->rbp_bufs));
1226
1227                 /* If routing is now turned off, we just drop this buffer and
1228                  * don't bother trying to return credits.  */
1229                 if (!the_lnet.ln_routing) {
1230                         lnet_destroy_rtrbuf(rb, rbp->rbp_npages);
1231                         goto routing_off;
1232                 }
1233
1234                 /* It is possible that a user has lowered the desired number of
1235                  * buffers in this pool.  Make sure we never put back
1236                  * more buffers than the stated number. */
1237                 if (unlikely(rbp->rbp_credits >= rbp->rbp_req_nbuffers)) {
1238                         /* Discard this buffer so we don't have too
1239                          * many. */
1240                         lnet_destroy_rtrbuf(rb, rbp->rbp_npages);
1241                         rbp->rbp_nbuffers--;
1242                 } else {
1243                         list_add(&rb->rb_list, &rbp->rbp_bufs);
1244                         rbp->rbp_credits++;
1245                         if (rbp->rbp_credits <= 0)
1246                                 lnet_schedule_blocked_locked(rbp);
1247                 }
1248         }
1249
1250 routing_off:
1251         if (msg->msg_peerrtrcredit) {
1252                 LASSERT(rxpeerni);
1253                 LASSERT(rxpeerni->lpni_peer_net);
1254                 LASSERT(rxpeerni->lpni_peer_net->lpn_peer);
1255
1256                 /* give back peer router credits */
1257                 msg->msg_peerrtrcredit = 0;
1258
1259                 spin_lock(&rxpeerni->lpni_lock);
1260                 rxpeerni->lpni_rtrcredits++;
1261                 spin_unlock(&rxpeerni->lpni_lock);
1262
1263                 lp = rxpeerni->lpni_peer_net->lpn_peer;
1264                 spin_lock(&lp->lp_lock);
1265
1266                 /* drop all messages which are queued to be routed on that
1267                  * peer. */
1268                 if (!the_lnet.ln_routing) {
1269                         LIST_HEAD(drop);
1270                         list_splice_init(&lp->lp_rtrq, &drop);
1271                         spin_unlock(&lp->lp_lock);
1272                         lnet_drop_routed_msgs_locked(&drop, msg->msg_rx_cpt);
1273                 } else if (!list_empty(&lp->lp_rtrq)) {
1274                         int msg2_cpt;
1275
1276                         msg2 = list_entry(lp->lp_rtrq.next,
1277                                           struct lnet_msg, msg_list);
1278                         list_del(&msg2->msg_list);
1279                         msg2_cpt = msg2->msg_rx_cpt;
1280                         spin_unlock(&lp->lp_lock);
1281                         /*
1282                          * messages on the lp_rtrq can be from any NID in
1283                          * the peer, which means they might have different
1284                          * cpts. We need to make sure we lock the right
1285                          * one.
1286                          */
1287                         if (msg2_cpt != msg->msg_rx_cpt) {
1288                                 lnet_net_unlock(msg->msg_rx_cpt);
1289                                 lnet_net_lock(msg2_cpt);
1290                         }
1291                         (void) lnet_post_routed_recv_locked(msg2, 1);
1292                         if (msg2_cpt != msg->msg_rx_cpt) {
1293                                 lnet_net_unlock(msg2_cpt);
1294                                 lnet_net_lock(msg->msg_rx_cpt);
1295                         }
1296                 } else {
1297                         spin_unlock(&lp->lp_lock);
1298                 }
1299         }
1300         if (rxni != NULL) {
1301                 msg->msg_rxni = NULL;
1302                 lnet_ni_decref_locked(rxni, msg->msg_rx_cpt);
1303         }
1304         if (rxpeerni != NULL) {
1305                 msg->msg_rxpeer = NULL;
1306                 lnet_peer_ni_decref_locked(rxpeerni);
1307         }
1308 }
1309
1310 static int
1311 lnet_compare_gw_lpnis(struct lnet_peer_ni *p1, struct lnet_peer_ni *p2)
1312 {
1313         if (p1->lpni_txqnob < p2->lpni_txqnob)
1314                 return 1;
1315
1316         if (p1->lpni_txqnob > p2->lpni_txqnob)
1317                 return -1;
1318
1319         if (p1->lpni_txcredits > p2->lpni_txcredits)
1320                 return 1;
1321
1322         if (p1->lpni_txcredits < p2->lpni_txcredits)
1323                 return -1;
1324
1325         return 0;
1326 }
1327
1328 static struct lnet_peer_ni *
1329 lnet_select_peer_ni(struct lnet_ni *best_ni, lnet_nid_t dst_nid,
1330                     struct lnet_peer *peer,
1331                     struct lnet_peer_ni *best_lpni,
1332                     struct lnet_peer_net *peer_net)
1333 {
1334         /*
1335          * Look at the peer NIs for the destination peer that connect
1336          * to the chosen net. If a peer_ni is preferred when using the
1337          * best_ni to communicate, we use that one. If there is no
1338          * preferred peer_ni, or there are multiple preferred peer_ni,
1339          * the available transmit credits are used. If the transmit
1340          * credits are equal, we round-robin over the peer_ni.
1341          */
1342         struct lnet_peer_ni *lpni = NULL;
1343         int best_lpni_credits = (best_lpni) ? best_lpni->lpni_txcredits :
1344                 INT_MIN;
1345         int best_lpni_healthv = (best_lpni) ?
1346                 atomic_read(&best_lpni->lpni_healthv) : 0;
1347         bool preferred = false;
1348         bool ni_is_pref;
1349         int lpni_healthv;
1350
1351         while ((lpni = lnet_get_next_peer_ni_locked(peer, peer_net, lpni))) {
1352                 /*
1353                  * if the best_ni we've chosen aleady has this lpni
1354                  * preferred, then let's use it
1355                  */
1356                 if (best_ni) {
1357                         ni_is_pref = lnet_peer_is_pref_nid_locked(lpni,
1358                                                                 best_ni->ni_nid);
1359                         CDEBUG(D_NET, "%s ni_is_pref = %d\n",
1360                                libcfs_nid2str(best_ni->ni_nid), ni_is_pref);
1361                 } else {
1362                         ni_is_pref = false;
1363                 }
1364
1365                 lpni_healthv = atomic_read(&lpni->lpni_healthv);
1366
1367                 if (best_lpni)
1368                         CDEBUG(D_NET, "%s c:[%d, %d], s:[%d, %d]\n",
1369                                 libcfs_nid2str(lpni->lpni_nid),
1370                                 lpni->lpni_txcredits, best_lpni_credits,
1371                                 lpni->lpni_seq, best_lpni->lpni_seq);
1372
1373                 /* pick the healthiest peer ni */
1374                 if (lpni_healthv < best_lpni_healthv) {
1375                         continue;
1376                 } else if (lpni_healthv > best_lpni_healthv) {
1377                         best_lpni_healthv = lpni_healthv;
1378                 /* if this is a preferred peer use it */
1379                 } else if (!preferred && ni_is_pref) {
1380                         preferred = true;
1381                 } else if (preferred && !ni_is_pref) {
1382                         /*
1383                          * this is not the preferred peer so let's ignore
1384                          * it.
1385                          */
1386                         continue;
1387                 } else if (lpni->lpni_txcredits < best_lpni_credits) {
1388                         /*
1389                          * We already have a peer that has more credits
1390                          * available than this one. No need to consider
1391                          * this peer further.
1392                          */
1393                         continue;
1394                 } else if (lpni->lpni_txcredits == best_lpni_credits) {
1395                         /*
1396                          * The best peer found so far and the current peer
1397                          * have the same number of available credits let's
1398                          * make sure to select between them using Round
1399                          * Robin
1400                          */
1401                         if (best_lpni) {
1402                                 if (best_lpni->lpni_seq <= lpni->lpni_seq)
1403                                         continue;
1404                         }
1405                 }
1406
1407                 best_lpni = lpni;
1408                 best_lpni_credits = lpni->lpni_txcredits;
1409         }
1410
1411         /* if we still can't find a peer ni then we can't reach it */
1412         if (!best_lpni) {
1413                 __u32 net_id = (peer_net) ? peer_net->lpn_net_id :
1414                         LNET_NIDNET(dst_nid);
1415                 CDEBUG(D_NET, "no peer_ni found on peer net %s\n",
1416                                 libcfs_net2str(net_id));
1417                 return NULL;
1418         }
1419
1420         CDEBUG(D_NET, "sd_best_lpni = %s\n",
1421                libcfs_nid2str(best_lpni->lpni_nid));
1422
1423         return best_lpni;
1424 }
1425
1426 /*
1427  * Prerequisite: the best_ni should already be set in the sd
1428  * Find the best lpni.
1429  * If the net id is provided then restrict lpni selection on
1430  * that particular net.
1431  * Otherwise find any reachable lpni. When dealing with an MR
1432  * gateway and it has multiple lpnis which we can use
1433  * we want to select the best one from the list of reachable
1434  * ones.
1435  */
1436 static inline struct lnet_peer_ni *
1437 lnet_find_best_lpni(struct lnet_ni *lni, lnet_nid_t dst_nid,
1438                     struct lnet_peer *peer, __u32 net_id)
1439 {
1440         struct lnet_peer_net *peer_net;
1441         __u32 any_net = LNET_NIDNET(LNET_NID_ANY);
1442
1443         /* find the best_lpni on any local network */
1444         if (net_id == any_net) {
1445                 struct lnet_peer_ni *best_lpni = NULL;
1446                 struct lnet_peer_net *lpn;
1447                 list_for_each_entry(lpn, &peer->lp_peer_nets, lpn_peer_nets) {
1448                         /* no net specified find any reachable peer ni */
1449                         if (!lnet_islocalnet_locked(lpn->lpn_net_id))
1450                                 continue;
1451                         best_lpni = lnet_select_peer_ni(lni, dst_nid, peer,
1452                                                         best_lpni, lpn);
1453                 }
1454
1455                 return best_lpni;
1456         }
1457         /* restrict on the specified net */
1458         peer_net = lnet_peer_get_net_locked(peer, net_id);
1459         if (peer_net)
1460                 return lnet_select_peer_ni(lni, dst_nid, peer, NULL, peer_net);
1461
1462         return NULL;
1463 }
1464
1465 /* Compare route priorities and hop counts */
1466 static int
1467 lnet_compare_routes(struct lnet_route *r1, struct lnet_route *r2)
1468 {
1469         int r1_hops = (r1->lr_hops == LNET_UNDEFINED_HOPS) ? 1 : r1->lr_hops;
1470         int r2_hops = (r2->lr_hops == LNET_UNDEFINED_HOPS) ? 1 : r2->lr_hops;
1471
1472         if (r1->lr_priority < r2->lr_priority)
1473                 return 1;
1474
1475         if (r1->lr_priority > r2->lr_priority)
1476                 return -1;
1477
1478         if (r1_hops < r2_hops)
1479                 return 1;
1480
1481         if (r1_hops > r2_hops)
1482                 return -1;
1483
1484         return 0;
1485 }
1486
1487 static struct lnet_route *
1488 lnet_find_route_locked(struct lnet_remotenet *rnet, __u32 src_net,
1489                        struct lnet_route **prev_route,
1490                        struct lnet_peer_ni **gwni)
1491 {
1492         struct lnet_peer_ni *lpni, *best_gw_ni = NULL;
1493         struct lnet_route *best_route;
1494         struct lnet_route *last_route;
1495         struct lnet_route *route;
1496         int rc;
1497
1498         CDEBUG(D_NET, "Looking up a route to %s, from %s\n",
1499                libcfs_net2str(rnet->lrn_net), libcfs_net2str(src_net));
1500
1501         best_route = last_route = NULL;
1502         list_for_each_entry(route, &rnet->lrn_routes, lr_list) {
1503                 if (!lnet_is_route_alive(route))
1504                         continue;
1505
1506                 /*
1507                  * Restrict the selection of the router NI on the src_net
1508                  * provided. If the src_net is LNET_NID_ANY, then select
1509                  * the best interface available.
1510                  */
1511                 if (!best_route) {
1512                         lpni = lnet_find_best_lpni(NULL, LNET_NID_ANY,
1513                                                    route->lr_gateway,
1514                                                    src_net);
1515                         if (lpni) {
1516                                 best_route = last_route = route;
1517                                 best_gw_ni = lpni;
1518                         } else {
1519                                 CDEBUG(D_NET, "Gateway %s does not have a peer NI on net %s\n",
1520                                        libcfs_nid2str(route->lr_gateway->lp_primary_nid),
1521                                        libcfs_net2str(src_net));
1522                         }
1523
1524                         continue;
1525                 }
1526
1527                 /* no protection on below fields, but it's harmless */
1528                 if (last_route->lr_seq - route->lr_seq < 0)
1529                         last_route = route;
1530
1531                 rc = lnet_compare_routes(route, best_route);
1532                 if (rc == -1)
1533                         continue;
1534
1535                 lpni = lnet_find_best_lpni(NULL, LNET_NID_ANY,
1536                                            route->lr_gateway,
1537                                            src_net);
1538                 /* restrict the lpni on the src_net if specified */
1539                 if (!lpni) {
1540                         CDEBUG(D_NET, "Gateway %s does not have a peer NI on net %s\n",
1541                                libcfs_nid2str(route->lr_gateway->lp_primary_nid),
1542                                libcfs_net2str(src_net));
1543                         continue;
1544                 }
1545
1546                 if (rc == 1) {
1547                         best_route = route;
1548                         best_gw_ni = lpni;
1549                         continue;
1550                 }
1551
1552                 rc = lnet_compare_gw_lpnis(lpni, best_gw_ni);
1553                 if (rc == -1)
1554                         continue;
1555
1556                 if (rc == 1 || route->lr_seq <= best_route->lr_seq) {
1557                         best_route = route;
1558                         best_gw_ni = lpni;
1559                         continue;
1560                 }
1561         }
1562
1563         *prev_route = last_route;
1564         *gwni = best_gw_ni;
1565
1566         return best_route;
1567 }
1568
1569 static struct lnet_ni *
1570 lnet_get_best_ni(struct lnet_net *local_net, struct lnet_ni *best_ni,
1571                  struct lnet_peer *peer, struct lnet_peer_net *peer_net,
1572                  int md_cpt)
1573 {
1574         struct lnet_ni *ni = NULL;
1575         unsigned int shortest_distance;
1576         int best_credits;
1577         int best_healthv;
1578
1579         /*
1580          * If there is no peer_ni that we can send to on this network,
1581          * then there is no point in looking for a new best_ni here.
1582         */
1583         if (!lnet_get_next_peer_ni_locked(peer, peer_net, NULL))
1584                 return best_ni;
1585
1586         if (best_ni == NULL) {
1587                 shortest_distance = UINT_MAX;
1588                 best_credits = INT_MIN;
1589                 best_healthv = 0;
1590         } else {
1591                 shortest_distance = cfs_cpt_distance(lnet_cpt_table(), md_cpt,
1592                                                      best_ni->ni_dev_cpt);
1593                 best_credits = atomic_read(&best_ni->ni_tx_credits);
1594                 best_healthv = atomic_read(&best_ni->ni_healthv);
1595         }
1596
1597         while ((ni = lnet_get_next_ni_locked(local_net, ni))) {
1598                 unsigned int distance;
1599                 int ni_credits;
1600                 int ni_healthv;
1601                 int ni_fatal;
1602
1603                 ni_credits = atomic_read(&ni->ni_tx_credits);
1604                 ni_healthv = atomic_read(&ni->ni_healthv);
1605                 ni_fatal = atomic_read(&ni->ni_fatal_error_on);
1606
1607                 /*
1608                  * calculate the distance from the CPT on which
1609                  * the message memory is allocated to the CPT of
1610                  * the NI's physical device
1611                  */
1612                 distance = cfs_cpt_distance(lnet_cpt_table(),
1613                                             md_cpt,
1614                                             ni->ni_dev_cpt);
1615
1616                 CDEBUG(D_NET, "compare ni %s [c:%d, d:%d, s:%d] with best_ni %s [c:%d, d:%d, s:%d]\n",
1617                        libcfs_nid2str(ni->ni_nid), ni_credits, distance,
1618                        ni->ni_seq, (best_ni) ? libcfs_nid2str(best_ni->ni_nid)
1619                         : "not seleced", best_credits, shortest_distance,
1620                         (best_ni) ? best_ni->ni_seq : 0);
1621
1622                 /*
1623                  * All distances smaller than the NUMA range
1624                  * are treated equally.
1625                  */
1626                 if (distance < lnet_numa_range)
1627                         distance = lnet_numa_range;
1628
1629                 /*
1630                  * Select on health, shorter distance, available
1631                  * credits, then round-robin.
1632                  */
1633                 if (ni_fatal) {
1634                         continue;
1635                 } else if (ni_healthv < best_healthv) {
1636                         continue;
1637                 } else if (ni_healthv > best_healthv) {
1638                         best_healthv = ni_healthv;
1639                         /*
1640                          * If we're going to prefer this ni because it's
1641                          * the healthiest, then we should set the
1642                          * shortest_distance in the algorithm in case
1643                          * there are multiple NIs with the same health but
1644                          * different distances.
1645                          */
1646                         if (distance < shortest_distance)
1647                                 shortest_distance = distance;
1648                 } else if (distance > shortest_distance) {
1649                         continue;
1650                 } else if (distance < shortest_distance) {
1651                         shortest_distance = distance;
1652                 } else if (ni_credits < best_credits) {
1653                         continue;
1654                 } else if (ni_credits == best_credits) {
1655                         if (best_ni && best_ni->ni_seq <= ni->ni_seq)
1656                                 continue;
1657                 }
1658                 best_ni = ni;
1659                 best_credits = ni_credits;
1660         }
1661
1662         CDEBUG(D_NET, "selected best_ni %s\n",
1663                (best_ni) ? libcfs_nid2str(best_ni->ni_nid) : "no selection");
1664
1665         return best_ni;
1666 }
1667
1668 /*
1669  * Traffic to the LNET_RESERVED_PORTAL may not trigger peer discovery,
1670  * because such traffic is required to perform discovery. We therefore
1671  * exclude all GET and PUT on that portal. We also exclude all ACK and
1672  * REPLY traffic, but that is because the portal is not tracked in the
1673  * message structure for these message types. We could restrict this
1674  * further by also checking for LNET_PROTO_PING_MATCHBITS.
1675  */
1676 static bool
1677 lnet_msg_discovery(struct lnet_msg *msg)
1678 {
1679         if (msg->msg_type == LNET_MSG_PUT) {
1680                 if (msg->msg_hdr.msg.put.ptl_index != LNET_RESERVED_PORTAL)
1681                         return true;
1682         } else if (msg->msg_type == LNET_MSG_GET) {
1683                 if (msg->msg_hdr.msg.get.ptl_index != LNET_RESERVED_PORTAL)
1684                         return true;
1685         }
1686         return false;
1687 }
1688
1689 #define SRC_SPEC        0x0001
1690 #define SRC_ANY         0x0002
1691 #define LOCAL_DST       0x0004
1692 #define REMOTE_DST      0x0008
1693 #define MR_DST          0x0010
1694 #define NMR_DST         0x0020
1695 #define SND_RESP        0x0040
1696
1697 /* The following to defines are used for return codes */
1698 #define REPEAT_SEND     0x1000
1699 #define PASS_THROUGH    0x2000
1700
1701 /* The different cases lnet_select pathway needs to handle */
1702 #define SRC_SPEC_LOCAL_MR_DST   (SRC_SPEC | LOCAL_DST | MR_DST)
1703 #define SRC_SPEC_ROUTER_MR_DST  (SRC_SPEC | REMOTE_DST | MR_DST)
1704 #define SRC_SPEC_LOCAL_NMR_DST  (SRC_SPEC | LOCAL_DST | NMR_DST)
1705 #define SRC_SPEC_ROUTER_NMR_DST (SRC_SPEC | REMOTE_DST | NMR_DST)
1706 #define SRC_ANY_LOCAL_MR_DST    (SRC_ANY | LOCAL_DST | MR_DST)
1707 #define SRC_ANY_ROUTER_MR_DST   (SRC_ANY | REMOTE_DST | MR_DST)
1708 #define SRC_ANY_LOCAL_NMR_DST   (SRC_ANY | LOCAL_DST | NMR_DST)
1709 #define SRC_ANY_ROUTER_NMR_DST  (SRC_ANY | REMOTE_DST | NMR_DST)
1710
1711 static int
1712 lnet_handle_lo_send(struct lnet_send_data *sd)
1713 {
1714         struct lnet_msg *msg = sd->sd_msg;
1715         int cpt = sd->sd_cpt;
1716
1717         /* No send credit hassles with LOLND */
1718         lnet_ni_addref_locked(the_lnet.ln_loni, cpt);
1719         msg->msg_hdr.dest_nid = cpu_to_le64(the_lnet.ln_loni->ni_nid);
1720         if (!msg->msg_routing)
1721                 msg->msg_hdr.src_nid =
1722                         cpu_to_le64(the_lnet.ln_loni->ni_nid);
1723         msg->msg_target.nid = the_lnet.ln_loni->ni_nid;
1724         lnet_msg_commit(msg, cpt);
1725         msg->msg_txni = the_lnet.ln_loni;
1726
1727         return LNET_CREDIT_OK;
1728 }
1729
1730 static int
1731 lnet_handle_send(struct lnet_send_data *sd)
1732 {
1733         struct lnet_ni *best_ni = sd->sd_best_ni;
1734         struct lnet_peer_ni *best_lpni = sd->sd_best_lpni;
1735         struct lnet_peer_ni *final_dst_lpni = sd->sd_final_dst_lpni;
1736         struct lnet_msg *msg = sd->sd_msg;
1737         int cpt2;
1738         __u32 send_case = sd->sd_send_case;
1739         int rc;
1740         __u32 routing = send_case & REMOTE_DST;
1741          struct lnet_rsp_tracker *rspt;
1742
1743         /*
1744          * Increment sequence number of the selected peer so that we
1745          * pick the next one in Round Robin.
1746          */
1747         best_lpni->lpni_seq++;
1748
1749         /*
1750          * grab a reference on the peer_ni so it sticks around even if
1751          * we need to drop and relock the lnet_net_lock below.
1752          */
1753         lnet_peer_ni_addref_locked(best_lpni);
1754
1755         /*
1756          * Use lnet_cpt_of_nid() to determine the CPT used to commit the
1757          * message. This ensures that we get a CPT that is correct for
1758          * the NI when the NI has been restricted to a subset of all CPTs.
1759          * If the selected CPT differs from the one currently locked, we
1760          * must unlock and relock the lnet_net_lock(), and then check whether
1761          * the configuration has changed. We don't have a hold on the best_ni
1762          * yet, and it may have vanished.
1763          */
1764         cpt2 = lnet_cpt_of_nid_locked(best_lpni->lpni_nid, best_ni);
1765         if (sd->sd_cpt != cpt2) {
1766                 __u32 seq = lnet_get_dlc_seq_locked();
1767                 lnet_net_unlock(sd->sd_cpt);
1768                 sd->sd_cpt = cpt2;
1769                 lnet_net_lock(sd->sd_cpt);
1770                 if (seq != lnet_get_dlc_seq_locked()) {
1771                         lnet_peer_ni_decref_locked(best_lpni);
1772                         return REPEAT_SEND;
1773                 }
1774         }
1775
1776         /*
1777          * store the best_lpni in the message right away to avoid having
1778          * to do the same operation under different conditions
1779          */
1780         msg->msg_txpeer = best_lpni;
1781         msg->msg_txni = best_ni;
1782
1783         /*
1784          * grab a reference for the best_ni since now it's in use in this
1785          * send. The reference will be dropped in lnet_finalize()
1786          */
1787         lnet_ni_addref_locked(msg->msg_txni, sd->sd_cpt);
1788
1789         /*
1790          * Always set the target.nid to the best peer picked. Either the
1791          * NID will be one of the peer NIDs selected, or the same NID as
1792          * what was originally set in the target or it will be the NID of
1793          * a router if this message should be routed
1794          */
1795         msg->msg_target.nid = msg->msg_txpeer->lpni_nid;
1796
1797         /*
1798          * lnet_msg_commit assigns the correct cpt to the message, which
1799          * is used to decrement the correct refcount on the ni when it's
1800          * time to return the credits
1801          */
1802         lnet_msg_commit(msg, sd->sd_cpt);
1803
1804         /*
1805          * If we are routing the message then we keep the src_nid that was
1806          * set by the originator. If we are not routing then we are the
1807          * originator and set it here.
1808          */
1809         if (!msg->msg_routing)
1810                 msg->msg_hdr.src_nid = cpu_to_le64(msg->msg_txni->ni_nid);
1811
1812         if (routing) {
1813                 msg->msg_target_is_router = 1;
1814                 msg->msg_target.pid = LNET_PID_LUSTRE;
1815                 /*
1816                  * since we're routing we want to ensure that the
1817                  * msg_hdr.dest_nid is set to the final destination. When
1818                  * the router receives this message it knows how to route
1819                  * it.
1820                  *
1821                  * final_dst_lpni is set at the beginning of the
1822                  * lnet_select_pathway() function and is never changed.
1823                  * It's safe to use it here.
1824                  */
1825                 msg->msg_hdr.dest_nid = cpu_to_le64(final_dst_lpni->lpni_nid);
1826         } else {
1827                 /*
1828                  * if we're not routing set the dest_nid to the best peer
1829                  * ni NID that we picked earlier in the algorithm.
1830                  */
1831                 msg->msg_hdr.dest_nid = cpu_to_le64(msg->msg_txpeer->lpni_nid);
1832         }
1833
1834         /*
1835          * if we have response tracker block update it with the next hop
1836          * nid
1837          */
1838         if (msg->msg_md) {
1839                 rspt = msg->msg_md->md_rspt_ptr;
1840                 if (rspt) {
1841                         rspt->rspt_next_hop_nid = msg->msg_txpeer->lpni_nid;
1842                         CDEBUG(D_NET, "rspt_next_hop_nid = %s\n",
1843                                libcfs_nid2str(rspt->rspt_next_hop_nid));
1844                 }
1845         }
1846
1847         rc = lnet_post_send_locked(msg, 0);
1848
1849         if (!rc)
1850                 CDEBUG(D_NET, "TRACE: %s(%s:%s) -> %s(%s:%s) %s : %s try# %d\n",
1851                        libcfs_nid2str(msg->msg_hdr.src_nid),
1852                        libcfs_nid2str(msg->msg_txni->ni_nid),
1853                        libcfs_nid2str(sd->sd_src_nid),
1854                        libcfs_nid2str(msg->msg_hdr.dest_nid),
1855                        libcfs_nid2str(sd->sd_dst_nid),
1856                        libcfs_nid2str(msg->msg_txpeer->lpni_nid),
1857                        libcfs_nid2str(sd->sd_rtr_nid),
1858                        lnet_msgtyp2str(msg->msg_type), msg->msg_retry_count);
1859
1860         return rc;
1861 }
1862
1863 static inline void
1864 lnet_set_non_mr_pref_nid(struct lnet_peer_ni *lpni, struct lnet_ni *lni,
1865                          struct lnet_msg *msg)
1866 {
1867         if (!lnet_msg_is_response(msg) && lpni->lpni_pref_nnids == 0) {
1868                 CDEBUG(D_NET, "Setting preferred local NID %s on NMR peer %s\n",
1869                        libcfs_nid2str(lni->ni_nid),
1870                        libcfs_nid2str(lpni->lpni_nid));
1871                 lnet_peer_ni_set_non_mr_pref_nid(lpni, lni->ni_nid);
1872         }
1873 }
1874
1875 /*
1876  * Source Specified
1877  * Local Destination
1878  * non-mr peer
1879  *
1880  * use the source and destination NIDs as the pathway
1881  */
1882 static int
1883 lnet_handle_spec_local_nmr_dst(struct lnet_send_data *sd)
1884 {
1885         /* the destination lpni is set before we get here. */
1886
1887         /* find local NI */
1888         sd->sd_best_ni = lnet_nid2ni_locked(sd->sd_src_nid, sd->sd_cpt);
1889         if (!sd->sd_best_ni) {
1890                 CERROR("Can't send to %s: src %s is not a "
1891                        "local nid\n", libcfs_nid2str(sd->sd_dst_nid),
1892                                 libcfs_nid2str(sd->sd_src_nid));
1893                 return -EINVAL;
1894         }
1895
1896         lnet_set_non_mr_pref_nid(sd->sd_best_lpni, sd->sd_best_ni, sd->sd_msg);
1897
1898         return lnet_handle_send(sd);
1899 }
1900
1901 /*
1902  * Source Specified
1903  * Local Destination
1904  * MR Peer
1905  *
1906  * Don't run the selection algorithm on the peer NIs. By specifying the
1907  * local NID, we're also saying that we should always use the destination NID
1908  * provided. This handles the case where we should be using the same
1909  * destination NID for the all the messages which belong to the same RPC
1910  * request.
1911  */
1912 static int
1913 lnet_handle_spec_local_mr_dst(struct lnet_send_data *sd)
1914 {
1915         sd->sd_best_ni = lnet_nid2ni_locked(sd->sd_src_nid, sd->sd_cpt);
1916         if (!sd->sd_best_ni) {
1917                 CERROR("Can't send to %s: src %s is not a "
1918                        "local nid\n", libcfs_nid2str(sd->sd_dst_nid),
1919                                 libcfs_nid2str(sd->sd_src_nid));
1920                 return -EINVAL;
1921         }
1922
1923         if (sd->sd_best_lpni &&
1924             sd->sd_best_lpni->lpni_nid == the_lnet.ln_loni->ni_nid)
1925                 return lnet_handle_lo_send(sd);
1926         else if (sd->sd_best_lpni)
1927                 return lnet_handle_send(sd);
1928
1929         CERROR("can't send to %s. no NI on %s\n",
1930                libcfs_nid2str(sd->sd_dst_nid),
1931                libcfs_net2str(sd->sd_best_ni->ni_net->net_id));
1932
1933         return -EHOSTUNREACH;
1934 }
1935
1936 struct lnet_ni *
1937 lnet_find_best_ni_on_spec_net(struct lnet_ni *cur_best_ni,
1938                               struct lnet_peer *peer,
1939                               struct lnet_peer_net *peer_net,
1940                               int cpt,
1941                               bool incr_seq)
1942 {
1943         struct lnet_net *local_net;
1944         struct lnet_ni *best_ni;
1945
1946         local_net = lnet_get_net_locked(peer_net->lpn_net_id);
1947         if (!local_net)
1948                 return NULL;
1949
1950         /*
1951          * Iterate through the NIs in this local Net and select
1952          * the NI to send from. The selection is determined by
1953          * these 3 criterion in the following priority:
1954          *      1. NUMA
1955          *      2. NI available credits
1956          *      3. Round Robin
1957          */
1958         best_ni = lnet_get_best_ni(local_net, cur_best_ni,
1959                                    peer, peer_net, cpt);
1960
1961         if (incr_seq && best_ni)
1962                 best_ni->ni_seq++;
1963
1964         return best_ni;
1965 }
1966
1967 static int
1968 lnet_initiate_peer_discovery(struct lnet_peer_ni *lpni, struct lnet_msg *msg,
1969                              int cpt)
1970 {
1971         struct lnet_peer *peer;
1972         int rc;
1973
1974         lnet_peer_ni_addref_locked(lpni);
1975
1976         peer = lpni->lpni_peer_net->lpn_peer;
1977
1978         if (lnet_peer_gw_discovery(peer)) {
1979                 lnet_peer_ni_decref_locked(lpni);
1980                 return 0;
1981         }
1982
1983         if (!lnet_msg_discovery(msg) || lnet_peer_is_uptodate(peer)) {
1984                 lnet_peer_ni_decref_locked(lpni);
1985                 return 0;
1986         }
1987
1988         rc = lnet_discover_peer_locked(lpni, cpt, false);
1989         if (rc) {
1990                 lnet_peer_ni_decref_locked(lpni);
1991                 return rc;
1992         }
1993         /* The peer may have changed. */
1994         peer = lpni->lpni_peer_net->lpn_peer;
1995         spin_lock(&peer->lp_lock);
1996         if (lnet_peer_is_uptodate_locked(peer)) {
1997                 spin_unlock(&peer->lp_lock);
1998                 lnet_peer_ni_decref_locked(lpni);
1999                 return 0;
2000         }
2001         /* queue message and return */
2002         msg->msg_sending = 0;
2003         msg->msg_txpeer = NULL;
2004         list_add_tail(&msg->msg_list, &peer->lp_dc_pendq);
2005         spin_unlock(&peer->lp_lock);
2006
2007         lnet_peer_ni_decref_locked(lpni);
2008
2009         CDEBUG(D_NET, "msg %p delayed. %s pending discovery\n",
2010                msg, libcfs_nid2str(peer->lp_primary_nid));
2011
2012         return LNET_DC_WAIT;
2013 }
2014
2015 static int
2016 lnet_handle_find_routed_path(struct lnet_send_data *sd,
2017                              lnet_nid_t dst_nid,
2018                              struct lnet_peer_ni **gw_lpni,
2019                              struct lnet_peer **gw_peer)
2020 {
2021         int rc;
2022         __u32 local_lnet;
2023         struct lnet_peer *gw;
2024         struct lnet_peer *lp;
2025         struct lnet_peer_net *lpn;
2026         struct lnet_peer_net *best_lpn = NULL;
2027         struct lnet_remotenet *rnet, *best_rnet = NULL;
2028         struct lnet_route *best_route = NULL;
2029         struct lnet_route *last_route = NULL;
2030         struct lnet_peer_ni *lpni = NULL;
2031         struct lnet_peer_ni *gwni = NULL;
2032         lnet_nid_t src_nid = (sd->sd_src_nid != LNET_NID_ANY) ? sd->sd_src_nid :
2033                 (sd->sd_best_ni != NULL) ? sd->sd_best_ni->ni_nid :
2034                 LNET_NID_ANY;
2035
2036         CDEBUG(D_NET, "using src nid %s for route restriction\n",
2037                libcfs_nid2str(src_nid));
2038
2039         /* If a router nid was specified then we are replying to a GET or
2040          * sending an ACK. In this case we use the gateway associated with the
2041          * specified router nid.
2042          */
2043         if (sd->sd_rtr_nid != LNET_NID_ANY) {
2044                 gwni = lnet_find_peer_ni_locked(sd->sd_rtr_nid);
2045                 if (!gwni) {
2046                         CERROR("No peer NI for gateway %s\n",
2047                                libcfs_nid2str(sd->sd_rtr_nid));
2048                         return -EHOSTUNREACH;
2049                 }
2050                 gw = gwni->lpni_peer_net->lpn_peer;
2051                 lnet_peer_ni_decref_locked(gwni);
2052                 local_lnet = LNET_NIDNET(sd->sd_rtr_nid);
2053         } else {
2054                 /* we've already looked up the initial lpni using dst_nid */
2055                 lpni = sd->sd_best_lpni;
2056                 /* the peer tree must be in existence */
2057                 LASSERT(lpni && lpni->lpni_peer_net &&
2058                         lpni->lpni_peer_net->lpn_peer);
2059                 lp = lpni->lpni_peer_net->lpn_peer;
2060
2061                 list_for_each_entry(lpn, &lp->lp_peer_nets, lpn_peer_nets) {
2062                         /* is this remote network reachable?  */
2063                         rnet = lnet_find_rnet_locked(lpn->lpn_net_id);
2064                         if (!rnet)
2065                                 continue;
2066
2067                         if (!best_lpn) {
2068                                 best_lpn = lpn;
2069                                 best_rnet = rnet;
2070                         }
2071
2072                         if (best_lpn->lpn_seq <= lpn->lpn_seq)
2073                                 continue;
2074
2075                         best_lpn = lpn;
2076                         best_rnet = rnet;
2077                 }
2078
2079                 if (!best_lpn) {
2080                         CERROR("peer %s has no available nets\n",
2081                                libcfs_nid2str(sd->sd_dst_nid));
2082                         return -EHOSTUNREACH;
2083                 }
2084
2085                 sd->sd_best_lpni = lnet_find_best_lpni(sd->sd_best_ni,
2086                                                        sd->sd_dst_nid,
2087                                                        lp,
2088                                                        best_lpn->lpn_net_id);
2089                 if (!sd->sd_best_lpni) {
2090                         CERROR("peer %s is unreachable\n",
2091                                libcfs_nid2str(sd->sd_dst_nid));
2092                         return -EHOSTUNREACH;
2093                 }
2094
2095                 /*
2096                  * We're attempting to round robin over the remote peer
2097                  * NI's so update the final destination we selected
2098                  */
2099                 sd->sd_final_dst_lpni = sd->sd_best_lpni;
2100
2101                 /*
2102                  * find the best route. Restrict the selection on the net of the
2103                  * local NI if we've already picked the local NI to send from.
2104                  * Otherwise, let's pick any route we can find and then find
2105                  * a local NI we can reach the route's gateway on. Any route we select
2106                  * will be reachable by virtue of the restriction we have when
2107                  * adding a route.
2108                  */
2109                 best_route = lnet_find_route_locked(best_rnet,
2110                                                     LNET_NIDNET(src_nid),
2111                                                     &last_route, &gwni);
2112
2113                 if (!best_route) {
2114                         CERROR("no route to %s from %s\n",
2115                                libcfs_nid2str(dst_nid),
2116                                libcfs_nid2str(src_nid));
2117                         return -EHOSTUNREACH;
2118                 }
2119
2120                 if (!gwni) {
2121                         CERROR("Internal Error. Route expected to %s from %s\n",
2122                                libcfs_nid2str(dst_nid),
2123                                libcfs_nid2str(src_nid));
2124                         return -EFAULT;
2125                 }
2126
2127                 gw = best_route->lr_gateway;
2128                 LASSERT(gw == gwni->lpni_peer_net->lpn_peer);
2129                 local_lnet = best_route->lr_lnet;
2130
2131                 /*
2132                  * Increment the sequence number of the remote lpni so we
2133                  * can round robin over the different interfaces of the
2134                  * remote lpni
2135                  */
2136                 sd->sd_best_lpni->lpni_seq++;
2137         }
2138
2139         /*
2140          * Discover this gateway if it hasn't already been discovered.
2141          * This means we might delay the message until discovery has
2142          * completed
2143          */
2144         sd->sd_msg->msg_src_nid_param = sd->sd_src_nid;
2145         rc = lnet_initiate_peer_discovery(gwni, sd->sd_msg, sd->sd_cpt);
2146         if (rc)
2147                 return rc;
2148
2149         if (!sd->sd_best_ni)
2150                 sd->sd_best_ni = lnet_find_best_ni_on_spec_net(NULL, gw,
2151                                         lnet_peer_get_net_locked(gw,
2152                                                                  local_lnet),
2153                                         sd->sd_md_cpt,
2154                                         true);
2155
2156         if (!sd->sd_best_ni) {
2157                 CERROR("Internal Error. Expected local ni on %s but non found :%s\n",
2158                        libcfs_net2str(local_lnet),
2159                        libcfs_nid2str(sd->sd_src_nid));
2160                 return -EFAULT;
2161         }
2162
2163         *gw_lpni = gwni;
2164         *gw_peer = gw;
2165
2166         /*
2167          * increment the sequence numbers since now we're sure we're
2168          * going to use this path
2169          */
2170         if (sd->sd_rtr_nid == LNET_NID_ANY) {
2171                 LASSERT(best_route && last_route);
2172                 best_route->lr_seq = last_route->lr_seq + 1;
2173                 best_lpn->lpn_seq++;
2174         }
2175
2176         return 0;
2177 }
2178
2179 /*
2180  * Handle two cases:
2181  *
2182  * Case 1:
2183  *  Source specified
2184  *  Remote destination
2185  *  Non-MR destination
2186  *
2187  * Case 2:
2188  *  Source specified
2189  *  Remote destination
2190  *  MR destination
2191  *
2192  * The handling of these two cases is similar. Even though the destination
2193  * can be MR or non-MR, we'll deal directly with the router.
2194  */
2195 static int
2196 lnet_handle_spec_router_dst(struct lnet_send_data *sd)
2197 {
2198         int rc;
2199         struct lnet_peer_ni *gw_lpni = NULL;
2200         struct lnet_peer *gw_peer = NULL;
2201
2202         /* find local NI */
2203         sd->sd_best_ni = lnet_nid2ni_locked(sd->sd_src_nid, sd->sd_cpt);
2204         if (!sd->sd_best_ni) {
2205                 CERROR("Can't send to %s: src %s is not a "
2206                        "local nid\n", libcfs_nid2str(sd->sd_dst_nid),
2207                                 libcfs_nid2str(sd->sd_src_nid));
2208                 return -EINVAL;
2209         }
2210
2211         rc = lnet_handle_find_routed_path(sd, sd->sd_dst_nid, &gw_lpni,
2212                                      &gw_peer);
2213         if (rc)
2214                 return rc;
2215
2216         if (sd->sd_send_case & NMR_DST)
2217                 /*
2218                  * since the final destination is non-MR let's set its preferred
2219                  * NID before we send
2220                  */
2221                 lnet_set_non_mr_pref_nid(sd->sd_best_lpni, sd->sd_best_ni,
2222                                          sd->sd_msg);
2223
2224         /*
2225          * We're going to send to the gw found so let's set its
2226          * info
2227          */
2228         sd->sd_peer = gw_peer;
2229         sd->sd_best_lpni = gw_lpni;
2230
2231         return lnet_handle_send(sd);
2232 }
2233
2234 struct lnet_ni *
2235 lnet_find_best_ni_on_local_net(struct lnet_peer *peer, int md_cpt,
2236                                bool discovery)
2237 {
2238         struct lnet_peer_net *peer_net = NULL;
2239         struct lnet_ni *best_ni = NULL;
2240         int lpn_healthv = 0;
2241
2242         /*
2243          * The peer can have multiple interfaces, some of them can be on
2244          * the local network and others on a routed network. We should
2245          * prefer the local network. However if the local network is not
2246          * available then we need to try the routed network
2247          */
2248
2249         /* go through all the peer nets and find the best_ni */
2250         list_for_each_entry(peer_net, &peer->lp_peer_nets, lpn_peer_nets) {
2251                 /*
2252                  * The peer's list of nets can contain non-local nets. We
2253                  * want to only examine the local ones.
2254                  */
2255                 if (!lnet_get_net_locked(peer_net->lpn_net_id))
2256                         continue;
2257
2258                 /* always select the lpn with the best health */
2259                 if (lpn_healthv <= peer_net->lpn_healthv)
2260                         lpn_healthv = peer_net->lpn_healthv;
2261                 else
2262                         continue;
2263
2264                 best_ni = lnet_find_best_ni_on_spec_net(best_ni, peer, peer_net,
2265                                                         md_cpt, false);
2266
2267                 /*
2268                  * if this is a discovery message and lp_disc_net_id is
2269                  * specified then use that net to send the discovery on.
2270                  */
2271                 if (peer->lp_disc_net_id == peer_net->lpn_net_id &&
2272                     discovery)
2273                         break;
2274         }
2275
2276         if (best_ni)
2277                 /* increment sequence number so we can round robin */
2278                 best_ni->ni_seq++;
2279
2280         return best_ni;
2281 }
2282
2283 static struct lnet_ni *
2284 lnet_find_existing_preferred_best_ni(struct lnet_peer_ni *lpni, int cpt)
2285 {
2286         struct lnet_ni *best_ni = NULL;
2287         struct lnet_peer_net *peer_net = lpni->lpni_peer_net;
2288         struct lnet_peer_ni *lpni_entry;
2289
2290         /*
2291          * We must use a consistent source address when sending to a
2292          * non-MR peer. However, a non-MR peer can have multiple NIDs
2293          * on multiple networks, and we may even need to talk to this
2294          * peer on multiple networks -- certain types of
2295          * load-balancing configuration do this.
2296          *
2297          * So we need to pick the NI the peer prefers for this
2298          * particular network.
2299          */
2300         LASSERT(peer_net);
2301         list_for_each_entry(lpni_entry, &peer_net->lpn_peer_nis,
2302                             lpni_peer_nis) {
2303                 if (lpni_entry->lpni_pref_nnids == 0)
2304                         continue;
2305                 LASSERT(lpni_entry->lpni_pref_nnids == 1);
2306                 best_ni = lnet_nid2ni_locked(lpni_entry->lpni_pref.nid, cpt);
2307                 break;
2308         }
2309
2310         return best_ni;
2311 }
2312
2313 /* Prerequisite: sd->sd_peer and sd->sd_best_lpni should be set */
2314 static int
2315 lnet_select_preferred_best_ni(struct lnet_send_data *sd)
2316 {
2317         struct lnet_ni *best_ni = NULL;
2318         struct lnet_peer_ni *best_lpni = sd->sd_best_lpni;
2319
2320         /*
2321          * We must use a consistent source address when sending to a
2322          * non-MR peer. However, a non-MR peer can have multiple NIDs
2323          * on multiple networks, and we may even need to talk to this
2324          * peer on multiple networks -- certain types of
2325          * load-balancing configuration do this.
2326          *
2327          * So we need to pick the NI the peer prefers for this
2328          * particular network.
2329          */
2330
2331         best_ni = lnet_find_existing_preferred_best_ni(sd->sd_best_lpni,
2332                                                        sd->sd_cpt);
2333
2334         /* if best_ni is still not set just pick one */
2335         if (!best_ni) {
2336                 best_ni =
2337                   lnet_find_best_ni_on_spec_net(NULL, sd->sd_peer,
2338                                                 sd->sd_best_lpni->lpni_peer_net,
2339                                                 sd->sd_md_cpt, true);
2340                 /* If there is no best_ni we don't have a route */
2341                 if (!best_ni) {
2342                         CERROR("no path to %s from net %s\n",
2343                                 libcfs_nid2str(best_lpni->lpni_nid),
2344                                 libcfs_net2str(best_lpni->lpni_net->net_id));
2345                         return -EHOSTUNREACH;
2346                 }
2347         }
2348
2349         sd->sd_best_ni = best_ni;
2350
2351         /* Set preferred NI if necessary. */
2352         lnet_set_non_mr_pref_nid(sd->sd_best_lpni, sd->sd_best_ni, sd->sd_msg);
2353
2354         return 0;
2355 }
2356
2357
2358 /*
2359  * Source not specified
2360  * Local destination
2361  * Non-MR Peer
2362  *
2363  * always use the same source NID for NMR peers
2364  * If we've talked to that peer before then we already have a preferred
2365  * source NI associated with it. Otherwise, we select a preferred local NI
2366  * and store it in the peer
2367  */
2368 static int
2369 lnet_handle_any_local_nmr_dst(struct lnet_send_data *sd)
2370 {
2371         int rc;
2372
2373         /* sd->sd_best_lpni is already set to the final destination */
2374
2375         /*
2376          * At this point we should've created the peer ni and peer. If we
2377          * can't find it, then something went wrong. Instead of assert
2378          * output a relevant message and fail the send
2379          */
2380         if (!sd->sd_best_lpni) {
2381                 CERROR("Internal fault. Unable to send msg %s to %s. "
2382                        "NID not known\n",
2383                        lnet_msgtyp2str(sd->sd_msg->msg_type),
2384                        libcfs_nid2str(sd->sd_dst_nid));
2385                 return -EFAULT;
2386         }
2387
2388         rc = lnet_select_preferred_best_ni(sd);
2389         if (!rc)
2390                 rc = lnet_handle_send(sd);
2391
2392         return rc;
2393 }
2394
2395 static int
2396 lnet_handle_any_mr_dsta(struct lnet_send_data *sd)
2397 {
2398         /*
2399          * NOTE we've already handled the remote peer case. So we only
2400          * need to worry about the local case here.
2401          *
2402          * if we're sending a response, ACK or reply, we need to send it
2403          * to the destination NID given to us. At this point we already
2404          * have the peer_ni we're suppose to send to, so just find the
2405          * best_ni on the peer net and use that. Since we're sending to an
2406          * MR peer then we can just run the selection algorithm on our
2407          * local NIs and pick the best one.
2408          */
2409         if (sd->sd_send_case & SND_RESP) {
2410                 sd->sd_best_ni =
2411                   lnet_find_best_ni_on_spec_net(NULL, sd->sd_peer,
2412                                                 sd->sd_best_lpni->lpni_peer_net,
2413                                                 sd->sd_md_cpt, true);
2414
2415                 if (!sd->sd_best_ni) {
2416                         /*
2417                          * We're not going to deal with not able to send
2418                          * a response to the provided final destination
2419                          */
2420                         CERROR("Can't send response to %s. "
2421                                "No local NI available\n",
2422                                 libcfs_nid2str(sd->sd_dst_nid));
2423                         return -EHOSTUNREACH;
2424                 }
2425
2426                 return lnet_handle_send(sd);
2427         }
2428
2429         /*
2430          * If we get here that means we're sending a fresh request, PUT or
2431          * GET, so we need to run our standard selection algorithm.
2432          * First find the best local interface that's on any of the peer's
2433          * networks.
2434          */
2435         sd->sd_best_ni = lnet_find_best_ni_on_local_net(sd->sd_peer,
2436                                         sd->sd_md_cpt,
2437                                         lnet_msg_discovery(sd->sd_msg));
2438         if (sd->sd_best_ni) {
2439                 sd->sd_best_lpni =
2440                   lnet_find_best_lpni(sd->sd_best_ni, sd->sd_dst_nid,
2441                                       sd->sd_peer,
2442                                       sd->sd_best_ni->ni_net->net_id);
2443
2444                 /*
2445                  * if we're successful in selecting a peer_ni on the local
2446                  * network, then send to it. Otherwise fall through and
2447                  * try and see if we can reach it over another routed
2448                  * network
2449                  */
2450                 if (sd->sd_best_lpni &&
2451                     sd->sd_best_lpni->lpni_nid == the_lnet.ln_loni->ni_nid) {
2452                         /*
2453                          * in case we initially started with a routed
2454                          * destination, let's reset to local
2455                          */
2456                         sd->sd_send_case &= ~REMOTE_DST;
2457                         sd->sd_send_case |= LOCAL_DST;
2458                         return lnet_handle_lo_send(sd);
2459                 } else if (sd->sd_best_lpni) {
2460                         /*
2461                          * in case we initially started with a routed
2462                          * destination, let's reset to local
2463                          */
2464                         sd->sd_send_case &= ~REMOTE_DST;
2465                         sd->sd_send_case |= LOCAL_DST;
2466                         return lnet_handle_send(sd);
2467                 }
2468
2469                 CERROR("Internal Error. Expected to have a best_lpni: "
2470                        "%s -> %s\n",
2471                        libcfs_nid2str(sd->sd_src_nid),
2472                        libcfs_nid2str(sd->sd_dst_nid));
2473
2474                 return -EFAULT;
2475         }
2476
2477         /*
2478          * Peer doesn't have a local network. Let's see if there is
2479          * a remote network we can reach it on.
2480          */
2481         return PASS_THROUGH;
2482 }
2483
2484 /*
2485  * Case 1:
2486  *      Source NID not specified
2487  *      Local destination
2488  *      MR peer
2489  *
2490  * Case 2:
2491  *      Source NID not speified
2492  *      Remote destination
2493  *      MR peer
2494  *
2495  * In both of these cases if we're sending a response, ACK or REPLY, then
2496  * we need to send to the destination NID provided.
2497  *
2498  * In the remote case let's deal with MR routers.
2499  *
2500  */
2501
2502 static int
2503 lnet_handle_any_mr_dst(struct lnet_send_data *sd)
2504 {
2505         int rc = 0;
2506         struct lnet_peer *gw_peer = NULL;
2507         struct lnet_peer_ni *gw_lpni = NULL;
2508
2509         /*
2510          * handle sending a response to a remote peer here so we don't
2511          * have to worry about it if we hit lnet_handle_any_mr_dsta()
2512          */
2513         if (sd->sd_send_case & REMOTE_DST &&
2514             sd->sd_send_case & SND_RESP) {
2515                 struct lnet_peer_ni *gw;
2516                 struct lnet_peer *gw_peer;
2517
2518                 rc = lnet_handle_find_routed_path(sd, sd->sd_dst_nid, &gw,
2519                                                   &gw_peer);
2520                 if (rc < 0) {
2521                         CERROR("Can't send response to %s. "
2522                                "No route available\n",
2523                                 libcfs_nid2str(sd->sd_dst_nid));
2524                         return -EHOSTUNREACH;
2525                 } else if (rc > 0) {
2526                         return rc;
2527                 }
2528
2529                 sd->sd_best_lpni = gw;
2530                 sd->sd_peer = gw_peer;
2531
2532                 return lnet_handle_send(sd);
2533         }
2534
2535         /*
2536          * Even though the NID for the peer might not be on a local network,
2537          * since the peer is MR there could be other interfaces on the
2538          * local network. In that case we'd still like to prefer the local
2539          * network over the routed network. If we're unable to do that
2540          * then we select the best router among the different routed networks,
2541          * and if the router is MR then we can deal with it as such.
2542          */
2543         rc = lnet_handle_any_mr_dsta(sd);
2544         if (rc != PASS_THROUGH)
2545                 return rc;
2546
2547         /*
2548          * Now that we must route to the destination, we must consider the
2549          * MR case, where the destination has multiple interfaces, some of
2550          * which we can route to and others we do not. For this reason we
2551          * need to select the destination which we can route to and if
2552          * there are multiple, we need to round robin.
2553          */
2554         rc = lnet_handle_find_routed_path(sd, sd->sd_dst_nid, &gw_lpni,
2555                                           &gw_peer);
2556         if (rc)
2557                 return rc;
2558
2559         sd->sd_send_case &= ~LOCAL_DST;
2560         sd->sd_send_case |= REMOTE_DST;
2561
2562         sd->sd_peer = gw_peer;
2563         sd->sd_best_lpni = gw_lpni;
2564
2565         return lnet_handle_send(sd);
2566 }
2567
2568 /*
2569  * Source not specified
2570  * Remote destination
2571  * Non-MR peer
2572  *
2573  * Must send to the specified peer NID using the same source NID that
2574  * we've used before. If it's the first time to talk to that peer then
2575  * find the source NI and assign it as preferred to that peer
2576  */
2577 static int
2578 lnet_handle_any_router_nmr_dst(struct lnet_send_data *sd)
2579 {
2580         int rc;
2581         struct lnet_peer_ni *gw_lpni = NULL;
2582         struct lnet_peer *gw_peer = NULL;
2583
2584         /*
2585          * Let's see if we have a preferred NI to talk to this NMR peer
2586          */
2587         sd->sd_best_ni = lnet_find_existing_preferred_best_ni(sd->sd_best_lpni,
2588                                                               sd->sd_cpt);
2589
2590         /*
2591          * find the router and that'll find the best NI if we didn't find
2592          * it already.
2593          */
2594         rc = lnet_handle_find_routed_path(sd, sd->sd_dst_nid, &gw_lpni,
2595                                           &gw_peer);
2596         if (rc)
2597                 return rc;
2598
2599         /*
2600          * set the best_ni we've chosen as the preferred one for
2601          * this peer
2602          */
2603         lnet_set_non_mr_pref_nid(sd->sd_best_lpni, sd->sd_best_ni, sd->sd_msg);
2604
2605         /* we'll be sending to the gw */
2606         sd->sd_best_lpni = gw_lpni;
2607         sd->sd_peer = gw_peer;
2608
2609         return lnet_handle_send(sd);
2610 }
2611
2612 static int
2613 lnet_handle_send_case_locked(struct lnet_send_data *sd)
2614 {
2615         /*
2616          * turn off the SND_RESP bit.
2617          * It will be checked in the case handling
2618          */
2619         __u32 send_case = sd->sd_send_case &= ~SND_RESP ;
2620
2621         CDEBUG(D_NET, "Source %s%s to %s %s %s destination\n",
2622                 (send_case & SRC_SPEC) ? "Specified: " : "ANY",
2623                 (send_case & SRC_SPEC) ? libcfs_nid2str(sd->sd_src_nid) : "",
2624                 (send_case & MR_DST) ? "MR: " : "NMR: ",
2625                 libcfs_nid2str(sd->sd_dst_nid),
2626                 (send_case & LOCAL_DST) ? "local" : "routed");
2627
2628         switch (send_case) {
2629         /*
2630          * For all cases where the source is specified, we should always
2631          * use the destination NID, whether it's an MR destination or not,
2632          * since we're continuing a series of related messages for the
2633          * same RPC
2634          */
2635         case SRC_SPEC_LOCAL_NMR_DST:
2636                 return lnet_handle_spec_local_nmr_dst(sd);
2637         case SRC_SPEC_LOCAL_MR_DST:
2638                 return lnet_handle_spec_local_mr_dst(sd);
2639         case SRC_SPEC_ROUTER_NMR_DST:
2640         case SRC_SPEC_ROUTER_MR_DST:
2641                 return lnet_handle_spec_router_dst(sd);
2642         case SRC_ANY_LOCAL_NMR_DST:
2643                 return lnet_handle_any_local_nmr_dst(sd);
2644         case SRC_ANY_LOCAL_MR_DST:
2645         case SRC_ANY_ROUTER_MR_DST:
2646                 return lnet_handle_any_mr_dst(sd);
2647         case SRC_ANY_ROUTER_NMR_DST:
2648                 return lnet_handle_any_router_nmr_dst(sd);
2649         default:
2650                 CERROR("Unknown send case\n");
2651                 return -1;
2652         }
2653 }
2654
2655 static int
2656 lnet_select_pathway(lnet_nid_t src_nid, lnet_nid_t dst_nid,
2657                     struct lnet_msg *msg, lnet_nid_t rtr_nid)
2658 {
2659         struct lnet_peer_ni *lpni;
2660         struct lnet_peer *peer;
2661         struct lnet_send_data send_data;
2662         int cpt, rc;
2663         int md_cpt;
2664         __u32 send_case = 0;
2665
2666         memset(&send_data, 0, sizeof(send_data));
2667
2668         /*
2669          * get an initial CPT to use for locking. The idea here is not to
2670          * serialize the calls to select_pathway, so that as many
2671          * operations can run concurrently as possible. To do that we use
2672          * the CPT where this call is being executed. Later on when we
2673          * determine the CPT to use in lnet_message_commit, we switch the
2674          * lock and check if there was any configuration change.  If none,
2675          * then we proceed, if there is, then we restart the operation.
2676          */
2677         cpt = lnet_net_lock_current();
2678
2679         md_cpt = lnet_cpt_of_md(msg->msg_md, msg->msg_offset);
2680         if (md_cpt == CFS_CPT_ANY)
2681                 md_cpt = cpt;
2682
2683 again:
2684
2685         /*
2686          * If we're being asked to send to the loopback interface, there
2687          * is no need to go through any selection. We can just shortcut
2688          * the entire process and send over lolnd
2689          */
2690         send_data.sd_msg = msg;
2691         send_data.sd_cpt = cpt;
2692         if (dst_nid == LNET_NID_LO_0) {
2693                 rc = lnet_handle_lo_send(&send_data);
2694                 lnet_net_unlock(cpt);
2695                 return rc;
2696         }
2697
2698         /*
2699          * find an existing peer_ni, or create one and mark it as having been
2700          * created due to network traffic. This call will create the
2701          * peer->peer_net->peer_ni tree.
2702          */
2703         lpni = lnet_nid2peerni_locked(dst_nid, LNET_NID_ANY, cpt);
2704         if (IS_ERR(lpni)) {
2705                 lnet_net_unlock(cpt);
2706                 return PTR_ERR(lpni);
2707         }
2708
2709         /*
2710          * Cache the original src_nid and rtr_nid. If we need to resend the
2711          * message then we'll need to know whether the src_nid was originally
2712          * specified for this message. If it was originally specified,
2713          * then we need to keep using the same src_nid since it's
2714          * continuing the same sequence of messages. Similarly, rtr_nid will
2715          * affect our choice of next hop.
2716          */
2717         msg->msg_src_nid_param = src_nid;
2718         msg->msg_rtr_nid_param = rtr_nid;
2719
2720         /*
2721          * If necessary, perform discovery on the peer that owns this peer_ni.
2722          * Note, this can result in the ownership of this peer_ni changing
2723          * to another peer object.
2724          */
2725         rc = lnet_initiate_peer_discovery(lpni, msg, cpt);
2726         if (rc) {
2727                 lnet_peer_ni_decref_locked(lpni);
2728                 lnet_net_unlock(cpt);
2729                 return rc;
2730         }
2731         lnet_peer_ni_decref_locked(lpni);
2732
2733         peer = lpni->lpni_peer_net->lpn_peer;
2734
2735         /*
2736          * Identify the different send cases
2737          */
2738         if (src_nid == LNET_NID_ANY)
2739                 send_case |= SRC_ANY;
2740         else
2741                 send_case |= SRC_SPEC;
2742
2743         if (lnet_get_net_locked(LNET_NIDNET(dst_nid)))
2744                 send_case |= LOCAL_DST;
2745         else
2746                 send_case |= REMOTE_DST;
2747
2748         /*
2749          * Deal with the peer as NMR in the following cases:
2750          * 1. the peer is NMR
2751          * 2. We're trying to recover a specific peer NI
2752          * 3. I'm a router sending to the final destination
2753          *    In this case the source of the message would've
2754          *    already selected the final destination so my job
2755          *    is to honor the selection.
2756          */
2757         if (!lnet_peer_is_multi_rail(peer) || msg->msg_recovery ||
2758             (msg->msg_routing && (send_case & LOCAL_DST)))
2759                 send_case |= NMR_DST;
2760         else
2761                 send_case |= MR_DST;
2762
2763         if (lnet_msg_is_response(msg))
2764                 send_case |= SND_RESP;
2765
2766         /* assign parameters to the send_data */
2767         send_data.sd_rtr_nid = rtr_nid;
2768         send_data.sd_src_nid = src_nid;
2769         send_data.sd_dst_nid = dst_nid;
2770         send_data.sd_best_lpni = lpni;
2771         /*
2772          * keep a pointer to the final destination in case we're going to
2773          * route, so we'll need to access it later
2774          */
2775         send_data.sd_final_dst_lpni = lpni;
2776         send_data.sd_peer = peer;
2777         send_data.sd_md_cpt = md_cpt;
2778         send_data.sd_send_case = send_case;
2779
2780         rc = lnet_handle_send_case_locked(&send_data);
2781
2782         /*
2783          * Update the local cpt since send_data.sd_cpt might've been
2784          * updated as a result of calling lnet_handle_send_case_locked().
2785          */
2786         cpt = send_data.sd_cpt;
2787
2788         if (rc == REPEAT_SEND)
2789                 goto again;
2790
2791         lnet_net_unlock(cpt);
2792
2793         return rc;
2794 }
2795
2796 int
2797 lnet_send(lnet_nid_t src_nid, struct lnet_msg *msg, lnet_nid_t rtr_nid)
2798 {
2799         lnet_nid_t              dst_nid = msg->msg_target.nid;
2800         int                     rc;
2801
2802         /*
2803          * NB: rtr_nid is set to LNET_NID_ANY for all current use-cases,
2804          * but we might want to use pre-determined router for ACK/REPLY
2805          * in the future
2806          */
2807         /* NB: ni != NULL == interface pre-determined (ACK/REPLY) */
2808         LASSERT(msg->msg_txpeer == NULL);
2809         LASSERT(msg->msg_txni == NULL);
2810         LASSERT(!msg->msg_sending);
2811         LASSERT(!msg->msg_target_is_router);
2812         LASSERT(!msg->msg_receiving);
2813
2814         msg->msg_sending = 1;
2815
2816         LASSERT(!msg->msg_tx_committed);
2817
2818         rc = lnet_select_pathway(src_nid, dst_nid, msg, rtr_nid);
2819         if (rc < 0) {
2820                 if (rc == -EHOSTUNREACH)
2821                         msg->msg_health_status = LNET_MSG_STATUS_REMOTE_ERROR;
2822                 else
2823                         msg->msg_health_status = LNET_MSG_STATUS_LOCAL_ERROR;
2824                 return rc;
2825         }
2826
2827         if (rc == LNET_CREDIT_OK)
2828                 lnet_ni_send(msg->msg_txni, msg);
2829
2830         /* rc == LNET_CREDIT_OK or LNET_CREDIT_WAIT or LNET_DC_WAIT */
2831         return 0;
2832 }
2833
2834 enum lnet_mt_event_type {
2835         MT_TYPE_LOCAL_NI = 0,
2836         MT_TYPE_PEER_NI
2837 };
2838
2839 struct lnet_mt_event_info {
2840         enum lnet_mt_event_type mt_type;
2841         lnet_nid_t mt_nid;
2842 };
2843
2844 /* called with res_lock held */
2845 void
2846 lnet_detach_rsp_tracker(struct lnet_libmd *md, int cpt)
2847 {
2848         struct lnet_rsp_tracker *rspt;
2849
2850         /*
2851          * msg has a refcount on the MD so the MD is not going away.
2852          * The rspt queue for the cpt is protected by
2853          * the lnet_net_lock(cpt). cpt is the cpt of the MD cookie.
2854          */
2855         if (!md->md_rspt_ptr)
2856                 return;
2857
2858         rspt = md->md_rspt_ptr;
2859
2860         /* debug code */
2861         LASSERT(rspt->rspt_cpt == cpt);
2862
2863         md->md_rspt_ptr = NULL;
2864
2865         if (LNetMDHandleIsInvalid(rspt->rspt_mdh)) {
2866                 /*
2867                  * The monitor thread has invalidated this handle because the
2868                  * response timed out, but it failed to lookup the MD. That
2869                  * means this response tracker is on the zombie list. We can
2870                  * safely remove it under the resource lock (held by caller) and
2871                  * free the response tracker block.
2872                  */
2873                 list_del(&rspt->rspt_on_list);
2874                 lnet_rspt_free(rspt, cpt);
2875         } else {
2876                 /*
2877                  * invalidate the handle to indicate that a response has been
2878                  * received, which will then lead the monitor thread to clean up
2879                  * the rspt block.
2880                  */
2881                 LNetInvalidateMDHandle(&rspt->rspt_mdh);
2882         }
2883 }
2884
2885 void
2886 lnet_clean_zombie_rstqs(void)
2887 {
2888         struct lnet_rsp_tracker *rspt, *tmp;
2889         int i;
2890
2891         cfs_cpt_for_each(i, lnet_cpt_table()) {
2892                 list_for_each_entry_safe(rspt, tmp,
2893                                          the_lnet.ln_mt_zombie_rstqs[i],
2894                                          rspt_on_list) {
2895                         list_del(&rspt->rspt_on_list);
2896                         lnet_rspt_free(rspt, i);
2897                 }
2898         }
2899
2900         cfs_percpt_free(the_lnet.ln_mt_zombie_rstqs);
2901 }
2902
2903 static void
2904 lnet_finalize_expired_responses(void)
2905 {
2906         struct lnet_libmd *md;
2907         struct lnet_rsp_tracker *rspt, *tmp;
2908         ktime_t now;
2909         int i;
2910
2911         if (the_lnet.ln_mt_rstq == NULL)
2912                 return;
2913
2914         cfs_cpt_for_each(i, lnet_cpt_table()) {
2915                 LIST_HEAD(local_queue);
2916
2917                 lnet_net_lock(i);
2918                 if (!the_lnet.ln_mt_rstq[i]) {
2919                         lnet_net_unlock(i);
2920                         continue;
2921                 }
2922                 list_splice_init(the_lnet.ln_mt_rstq[i], &local_queue);
2923                 lnet_net_unlock(i);
2924
2925                 now = ktime_get();
2926
2927                 list_for_each_entry_safe(rspt, tmp, &local_queue, rspt_on_list) {
2928                         /*
2929                          * The rspt mdh will be invalidated when a response
2930                          * is received or whenever we want to discard the
2931                          * block the monitor thread will walk the queue
2932                          * and clean up any rsts with an invalid mdh.
2933                          * The monitor thread will walk the queue until
2934                          * the first unexpired rspt block. This means that
2935                          * some rspt blocks which received their
2936                          * corresponding responses will linger in the
2937                          * queue until they are cleaned up eventually.
2938                          */
2939                         lnet_res_lock(i);
2940                         if (LNetMDHandleIsInvalid(rspt->rspt_mdh)) {
2941                                 lnet_res_unlock(i);
2942                                 list_del(&rspt->rspt_on_list);
2943                                 lnet_rspt_free(rspt, i);
2944                                 continue;
2945                         }
2946
2947                         if (ktime_compare(now, rspt->rspt_deadline) >= 0 ||
2948                             the_lnet.ln_mt_state == LNET_MT_STATE_SHUTDOWN) {
2949                                 struct lnet_peer_ni *lpni;
2950                                 lnet_nid_t nid;
2951
2952                                 md = lnet_handle2md(&rspt->rspt_mdh);
2953                                 if (!md) {
2954                                         /* MD has been queued for unlink, but
2955                                          * rspt hasn't been detached (Note we've
2956                                          * checked above that the rspt_mdh is
2957                                          * valid). Since we cannot lookup the MD
2958                                          * we're unable to detach the rspt
2959                                          * ourselves. Thus, move the rspt to the
2960                                          * zombie list where we'll wait for
2961                                          * either:
2962                                          *   1. The remaining operations on the
2963                                          *   MD to complete. In this case the
2964                                          *   final operation will result in
2965                                          *   lnet_msg_detach_md()->
2966                                          *   lnet_detach_rsp_tracker() where
2967                                          *   we will clean up this response
2968                                          *   tracker.
2969                                          *   2. LNet to shutdown. In this case
2970                                          *   we'll wait until after all LND Nets
2971                                          *   have shutdown and then we can
2972                                          *   safely free any remaining response
2973                                          *   tracker blocks on the zombie list.
2974                                          * Note: We need to hold the resource
2975                                          * lock when adding to the zombie list
2976                                          * because we may have concurrent access
2977                                          * with lnet_detach_rsp_tracker().
2978                                          */
2979                                         LNetInvalidateMDHandle(&rspt->rspt_mdh);
2980                                         list_move(&rspt->rspt_on_list,
2981                                                   the_lnet.ln_mt_zombie_rstqs[i]);
2982                                         lnet_res_unlock(i);
2983                                         continue;
2984                                 }
2985                                 LASSERT(md->md_rspt_ptr == rspt);
2986                                 md->md_rspt_ptr = NULL;
2987                                 lnet_res_unlock(i);
2988
2989                                 LNetMDUnlink(rspt->rspt_mdh);
2990
2991                                 nid = rspt->rspt_next_hop_nid;
2992
2993                                 list_del(&rspt->rspt_on_list);
2994                                 lnet_rspt_free(rspt, i);
2995
2996                                 /* If we're shutting down we just want to clean
2997                                  * up the rspt blocks
2998                                  */
2999                                 if (the_lnet.ln_mt_state == LNET_MT_STATE_SHUTDOWN)
3000                                         continue;
3001
3002                                 lnet_net_lock(i);
3003                                 the_lnet.ln_counters[i]->lct_health.lch_response_timeout_count++;
3004                                 lnet_net_unlock(i);
3005
3006                                 CDEBUG(D_NET,
3007                                        "Response timeout: md = %p: nid = %s\n",
3008                                        md, libcfs_nid2str(nid));
3009
3010                                 /*
3011                                  * If there is a timeout on the response
3012                                  * from the next hop decrement its health
3013                                  * value so that we don't use it
3014                                  */
3015                                 lnet_net_lock(0);
3016                                 lpni = lnet_find_peer_ni_locked(nid);
3017                                 if (lpni) {
3018                                         lnet_handle_remote_failure_locked(lpni);
3019                                         lnet_peer_ni_decref_locked(lpni);
3020                                 }
3021                                 lnet_net_unlock(0);
3022                         } else {
3023                                 lnet_res_unlock(i);
3024                                 break;
3025                         }
3026                 }
3027
3028                 if (!list_empty(&local_queue)) {
3029                         lnet_net_lock(i);
3030                         list_splice(&local_queue, the_lnet.ln_mt_rstq[i]);
3031                         lnet_net_unlock(i);
3032                 }
3033         }
3034 }
3035
3036 static void
3037 lnet_resend_pending_msgs_locked(struct list_head *resendq, int cpt)
3038 {
3039         struct lnet_msg *msg;
3040
3041         while (!list_empty(resendq)) {
3042                 struct lnet_peer_ni *lpni;
3043
3044                 msg = list_entry(resendq->next, struct lnet_msg,
3045                                  msg_list);
3046
3047                 list_del_init(&msg->msg_list);
3048
3049                 lpni = lnet_find_peer_ni_locked(msg->msg_hdr.dest_nid);
3050                 if (!lpni) {
3051                         lnet_net_unlock(cpt);
3052                         CERROR("Expected that a peer is already created for %s\n",
3053                                libcfs_nid2str(msg->msg_hdr.dest_nid));
3054                         msg->msg_no_resend = true;
3055                         lnet_finalize(msg, -EFAULT);
3056                         lnet_net_lock(cpt);
3057                 } else {
3058                         int rc;
3059
3060                         lnet_peer_ni_decref_locked(lpni);
3061
3062                         lnet_net_unlock(cpt);
3063                         CDEBUG(D_NET, "resending %s->%s: %s recovery %d try# %d\n",
3064                                libcfs_nid2str(msg->msg_src_nid_param),
3065                                libcfs_id2str(msg->msg_target),
3066                                lnet_msgtyp2str(msg->msg_type),
3067                                msg->msg_recovery,
3068                                msg->msg_retry_count);
3069                         rc = lnet_send(msg->msg_src_nid_param, msg,
3070                                        msg->msg_rtr_nid_param);
3071                         if (rc) {
3072                                 CERROR("Error sending %s to %s: %d\n",
3073                                        lnet_msgtyp2str(msg->msg_type),
3074                                        libcfs_id2str(msg->msg_target), rc);
3075                                 msg->msg_no_resend = true;
3076                                 lnet_finalize(msg, rc);
3077                         }
3078                         lnet_net_lock(cpt);
3079                         if (!rc)
3080                                 the_lnet.ln_counters[cpt]->lct_health.lch_resend_count++;
3081                 }
3082         }
3083 }
3084
3085 static void
3086 lnet_resend_pending_msgs(void)
3087 {
3088         int i;
3089
3090         cfs_cpt_for_each(i, lnet_cpt_table()) {
3091                 lnet_net_lock(i);
3092                 lnet_resend_pending_msgs_locked(the_lnet.ln_mt_resendqs[i], i);
3093                 lnet_net_unlock(i);
3094         }
3095 }
3096
3097 /* called with cpt and ni_lock held */
3098 static void
3099 lnet_unlink_ni_recovery_mdh_locked(struct lnet_ni *ni, int cpt, bool force)
3100 {
3101         struct lnet_handle_md recovery_mdh;
3102
3103         LNetInvalidateMDHandle(&recovery_mdh);
3104
3105         if (ni->ni_recovery_state & LNET_NI_RECOVERY_PENDING ||
3106             force) {
3107                 recovery_mdh = ni->ni_ping_mdh;
3108                 LNetInvalidateMDHandle(&ni->ni_ping_mdh);
3109         }
3110         lnet_ni_unlock(ni);
3111         lnet_net_unlock(cpt);
3112         if (!LNetMDHandleIsInvalid(recovery_mdh))
3113                 LNetMDUnlink(recovery_mdh);
3114         lnet_net_lock(cpt);
3115         lnet_ni_lock(ni);
3116 }
3117
3118 static void
3119 lnet_recover_local_nis(void)
3120 {
3121         struct lnet_mt_event_info *ev_info;
3122         LIST_HEAD(processed_list);
3123         LIST_HEAD(local_queue);
3124         struct lnet_handle_md mdh;
3125         struct lnet_ni *tmp;
3126         struct lnet_ni *ni;
3127         lnet_nid_t nid;
3128         int healthv;
3129         int rc;
3130
3131         /*
3132          * splice the recovery queue on a local queue. We will iterate
3133          * through the local queue and update it as needed. Once we're
3134          * done with the traversal, we'll splice the local queue back on
3135          * the head of the ln_mt_localNIRecovq. Any newly added local NIs
3136          * will be traversed in the next iteration.
3137          */
3138         lnet_net_lock(0);
3139         list_splice_init(&the_lnet.ln_mt_localNIRecovq,
3140                          &local_queue);
3141         lnet_net_unlock(0);
3142
3143         list_for_each_entry_safe(ni, tmp, &local_queue, ni_recovery) {
3144                 /*
3145                  * if an NI is being deleted or it is now healthy, there
3146                  * is no need to keep it around in the recovery queue.
3147                  * The monitor thread is the only thread responsible for
3148                  * removing the NI from the recovery queue.
3149                  * Multiple threads can be adding NIs to the recovery
3150                  * queue.
3151                  */
3152                 healthv = atomic_read(&ni->ni_healthv);
3153
3154                 lnet_net_lock(0);
3155                 lnet_ni_lock(ni);
3156                 if (ni->ni_state != LNET_NI_STATE_ACTIVE ||
3157                     healthv == LNET_MAX_HEALTH_VALUE) {
3158                         list_del_init(&ni->ni_recovery);
3159                         lnet_unlink_ni_recovery_mdh_locked(ni, 0, false);
3160                         lnet_ni_unlock(ni);
3161                         lnet_ni_decref_locked(ni, 0);
3162                         lnet_net_unlock(0);
3163                         continue;
3164                 }
3165
3166                 /*
3167                  * if the local NI failed recovery we must unlink the md.
3168                  * But we want to keep the local_ni on the recovery queue
3169                  * so we can continue the attempts to recover it.
3170                  */
3171                 if (ni->ni_recovery_state & LNET_NI_RECOVERY_FAILED) {
3172                         lnet_unlink_ni_recovery_mdh_locked(ni, 0, true);
3173                         ni->ni_recovery_state &= ~LNET_NI_RECOVERY_FAILED;
3174                 }
3175
3176                 lnet_ni_unlock(ni);
3177                 lnet_net_unlock(0);
3178
3179
3180                 CDEBUG(D_NET, "attempting to recover local ni: %s\n",
3181                        libcfs_nid2str(ni->ni_nid));
3182
3183                 lnet_ni_lock(ni);
3184                 if (!(ni->ni_recovery_state & LNET_NI_RECOVERY_PENDING)) {
3185                         ni->ni_recovery_state |= LNET_NI_RECOVERY_PENDING;
3186                         lnet_ni_unlock(ni);
3187
3188                         LIBCFS_ALLOC(ev_info, sizeof(*ev_info));
3189                         if (!ev_info) {
3190                                 CERROR("out of memory. Can't recover %s\n",
3191                                        libcfs_nid2str(ni->ni_nid));
3192                                 lnet_ni_lock(ni);
3193                                 ni->ni_recovery_state &=
3194                                   ~LNET_NI_RECOVERY_PENDING;
3195                                 lnet_ni_unlock(ni);
3196                                 continue;
3197                         }
3198
3199                         mdh = ni->ni_ping_mdh;
3200                         /*
3201                          * Invalidate the ni mdh in case it's deleted.
3202                          * We'll unlink the mdh in this case below.
3203                          */
3204                         LNetInvalidateMDHandle(&ni->ni_ping_mdh);
3205                         nid = ni->ni_nid;
3206
3207                         /*
3208                          * remove the NI from the local queue and drop the
3209                          * reference count to it while we're recovering
3210                          * it. The reason for that, is that the NI could
3211                          * be deleted, and the way the code is structured
3212                          * is if we don't drop the NI, then the deletion
3213                          * code will enter a loop waiting for the
3214                          * reference count to be removed while holding the
3215                          * ln_mutex_lock(). When we look up the peer to
3216                          * send to in lnet_select_pathway() we will try to
3217                          * lock the ln_mutex_lock() as well, leading to
3218                          * a deadlock. By dropping the refcount and
3219                          * removing it from the list, we allow for the NI
3220                          * to be removed, then we use the cached NID to
3221                          * look it up again. If it's gone, then we just
3222                          * continue examining the rest of the queue.
3223                          */
3224                         lnet_net_lock(0);
3225                         list_del_init(&ni->ni_recovery);
3226                         lnet_ni_decref_locked(ni, 0);
3227                         lnet_net_unlock(0);
3228
3229                         ev_info->mt_type = MT_TYPE_LOCAL_NI;
3230                         ev_info->mt_nid = nid;
3231                         rc = lnet_send_ping(nid, &mdh, LNET_INTERFACES_MIN,
3232                                             ev_info, the_lnet.ln_mt_handler,
3233                                             true);
3234                         /* lookup the nid again */
3235                         lnet_net_lock(0);
3236                         ni = lnet_nid2ni_locked(nid, 0);
3237                         if (!ni) {
3238                                 /*
3239                                  * the NI has been deleted when we dropped
3240                                  * the ref count
3241                                  */
3242                                 lnet_net_unlock(0);
3243                                 LNetMDUnlink(mdh);
3244                                 continue;
3245                         }
3246                         /*
3247                          * Same note as in lnet_recover_peer_nis(). When
3248                          * we're sending the ping, the NI is free to be
3249                          * deleted or manipulated. By this point it
3250                          * could've been added back on the recovery queue,
3251                          * and a refcount taken on it.
3252                          * So we can't just add it blindly again or we'll
3253                          * corrupt the queue. We must check under lock if
3254                          * it's not on any list and if not then add it
3255                          * to the processed list, which will eventually be
3256                          * spliced back on to the recovery queue.
3257                          */
3258                         ni->ni_ping_mdh = mdh;
3259                         if (list_empty(&ni->ni_recovery)) {
3260                                 list_add_tail(&ni->ni_recovery, &processed_list);
3261                                 lnet_ni_addref_locked(ni, 0);
3262                         }
3263                         lnet_net_unlock(0);
3264
3265                         lnet_ni_lock(ni);
3266                         if (rc)
3267                                 ni->ni_recovery_state &= ~LNET_NI_RECOVERY_PENDING;
3268                 }
3269                 lnet_ni_unlock(ni);
3270         }
3271
3272         /*
3273          * put back the remaining NIs on the ln_mt_localNIRecovq to be
3274          * reexamined in the next iteration.
3275          */
3276         list_splice_init(&processed_list, &local_queue);
3277         lnet_net_lock(0);
3278         list_splice(&local_queue, &the_lnet.ln_mt_localNIRecovq);
3279         lnet_net_unlock(0);
3280 }
3281
3282 static int
3283 lnet_resendqs_create(void)
3284 {
3285         struct list_head **resendqs;
3286         resendqs = lnet_create_array_of_queues();
3287
3288         if (!resendqs)
3289                 return -ENOMEM;
3290
3291         lnet_net_lock(LNET_LOCK_EX);
3292         the_lnet.ln_mt_resendqs = resendqs;
3293         lnet_net_unlock(LNET_LOCK_EX);
3294
3295         return 0;
3296 }
3297
3298 static void
3299 lnet_clean_local_ni_recoveryq(void)
3300 {
3301         struct lnet_ni *ni;
3302
3303         /* This is only called when the monitor thread has stopped */
3304         lnet_net_lock(0);
3305
3306         while (!list_empty(&the_lnet.ln_mt_localNIRecovq)) {
3307                 ni = list_entry(the_lnet.ln_mt_localNIRecovq.next,
3308                                 struct lnet_ni, ni_recovery);
3309                 list_del_init(&ni->ni_recovery);
3310                 lnet_ni_lock(ni);
3311                 lnet_unlink_ni_recovery_mdh_locked(ni, 0, true);
3312                 lnet_ni_unlock(ni);
3313                 lnet_ni_decref_locked(ni, 0);
3314         }
3315
3316         lnet_net_unlock(0);
3317 }
3318
3319 static void
3320 lnet_unlink_lpni_recovery_mdh_locked(struct lnet_peer_ni *lpni, int cpt,
3321                                      bool force)
3322 {
3323         struct lnet_handle_md recovery_mdh;
3324
3325         LNetInvalidateMDHandle(&recovery_mdh);
3326
3327         if (lpni->lpni_state & LNET_PEER_NI_RECOVERY_PENDING || force) {
3328                 recovery_mdh = lpni->lpni_recovery_ping_mdh;
3329                 LNetInvalidateMDHandle(&lpni->lpni_recovery_ping_mdh);
3330         }
3331         spin_unlock(&lpni->lpni_lock);
3332         lnet_net_unlock(cpt);
3333         if (!LNetMDHandleIsInvalid(recovery_mdh))
3334                 LNetMDUnlink(recovery_mdh);
3335         lnet_net_lock(cpt);
3336         spin_lock(&lpni->lpni_lock);
3337 }
3338
3339 static void
3340 lnet_clean_peer_ni_recoveryq(void)
3341 {
3342         struct lnet_peer_ni *lpni, *tmp;
3343
3344         lnet_net_lock(LNET_LOCK_EX);
3345
3346         list_for_each_entry_safe(lpni, tmp, &the_lnet.ln_mt_peerNIRecovq,
3347                                  lpni_recovery) {
3348                 list_del_init(&lpni->lpni_recovery);
3349                 spin_lock(&lpni->lpni_lock);
3350                 lnet_unlink_lpni_recovery_mdh_locked(lpni, LNET_LOCK_EX, true);
3351                 spin_unlock(&lpni->lpni_lock);
3352                 lnet_peer_ni_decref_locked(lpni);
3353         }
3354
3355         lnet_net_unlock(LNET_LOCK_EX);
3356 }
3357
3358 static void
3359 lnet_clean_resendqs(void)
3360 {
3361         struct lnet_msg *msg, *tmp;
3362         LIST_HEAD(msgs);
3363         int i;
3364
3365         cfs_cpt_for_each(i, lnet_cpt_table()) {
3366                 lnet_net_lock(i);
3367                 list_splice_init(the_lnet.ln_mt_resendqs[i], &msgs);
3368                 lnet_net_unlock(i);
3369                 list_for_each_entry_safe(msg, tmp, &msgs, msg_list) {
3370                         list_del_init(&msg->msg_list);
3371                         msg->msg_no_resend = true;
3372                         lnet_finalize(msg, -ESHUTDOWN);
3373                 }
3374         }
3375
3376         cfs_percpt_free(the_lnet.ln_mt_resendqs);
3377 }
3378
3379 static void
3380 lnet_recover_peer_nis(void)
3381 {
3382         struct lnet_mt_event_info *ev_info;
3383         LIST_HEAD(processed_list);
3384         LIST_HEAD(local_queue);
3385         struct lnet_handle_md mdh;
3386         struct lnet_peer_ni *lpni;
3387         struct lnet_peer_ni *tmp;
3388         lnet_nid_t nid;
3389         int healthv;
3390         int rc;
3391
3392         /*
3393          * Always use cpt 0 for locking across all interactions with
3394          * ln_mt_peerNIRecovq
3395          */
3396         lnet_net_lock(0);
3397         list_splice_init(&the_lnet.ln_mt_peerNIRecovq,
3398                          &local_queue);
3399         lnet_net_unlock(0);
3400
3401         list_for_each_entry_safe(lpni, tmp, &local_queue,
3402                                  lpni_recovery) {
3403                 /*
3404                  * The same protection strategy is used here as is in the
3405                  * local recovery case.
3406                  */
3407                 lnet_net_lock(0);
3408                 healthv = atomic_read(&lpni->lpni_healthv);
3409                 spin_lock(&lpni->lpni_lock);
3410                 if (lpni->lpni_state & LNET_PEER_NI_DELETING ||
3411                     healthv == LNET_MAX_HEALTH_VALUE) {
3412                         list_del_init(&lpni->lpni_recovery);
3413                         lnet_unlink_lpni_recovery_mdh_locked(lpni, 0, false);
3414                         spin_unlock(&lpni->lpni_lock);
3415                         lnet_peer_ni_decref_locked(lpni);
3416                         lnet_net_unlock(0);
3417                         continue;
3418                 }
3419
3420                 /*
3421                  * If the peer NI has failed recovery we must unlink the
3422                  * md. But we want to keep the peer ni on the recovery
3423                  * queue so we can try to continue recovering it
3424                  */
3425                 if (lpni->lpni_state & LNET_PEER_NI_RECOVERY_FAILED) {
3426                         lnet_unlink_lpni_recovery_mdh_locked(lpni, 0, true);
3427                         lpni->lpni_state &= ~LNET_PEER_NI_RECOVERY_FAILED;
3428                 }
3429
3430                 spin_unlock(&lpni->lpni_lock);
3431                 lnet_net_unlock(0);
3432
3433                 /*
3434                  * NOTE: we're racing with peer deletion from user space.
3435                  * It's possible that a peer is deleted after we check its
3436                  * state. In this case the recovery can create a new peer
3437                  */
3438                 spin_lock(&lpni->lpni_lock);
3439                 if (!(lpni->lpni_state & LNET_PEER_NI_RECOVERY_PENDING) &&
3440                     !(lpni->lpni_state & LNET_PEER_NI_DELETING)) {
3441                         lpni->lpni_state |= LNET_PEER_NI_RECOVERY_PENDING;
3442                         spin_unlock(&lpni->lpni_lock);
3443
3444                         LIBCFS_ALLOC(ev_info, sizeof(*ev_info));
3445                         if (!ev_info) {
3446                                 CERROR("out of memory. Can't recover %s\n",
3447                                        libcfs_nid2str(lpni->lpni_nid));
3448                                 spin_lock(&lpni->lpni_lock);
3449                                 lpni->lpni_state &= ~LNET_PEER_NI_RECOVERY_PENDING;
3450                                 spin_unlock(&lpni->lpni_lock);
3451                                 continue;
3452                         }
3453
3454                         /* look at the comments in lnet_recover_local_nis() */
3455                         mdh = lpni->lpni_recovery_ping_mdh;
3456                         LNetInvalidateMDHandle(&lpni->lpni_recovery_ping_mdh);
3457                         nid = lpni->lpni_nid;
3458                         lnet_net_lock(0);
3459                         list_del_init(&lpni->lpni_recovery);
3460                         lnet_peer_ni_decref_locked(lpni);
3461                         lnet_net_unlock(0);
3462
3463                         ev_info->mt_type = MT_TYPE_PEER_NI;
3464                         ev_info->mt_nid = nid;
3465                         rc = lnet_send_ping(nid, &mdh, LNET_INTERFACES_MIN,
3466                                             ev_info, the_lnet.ln_mt_handler,
3467                                             true);
3468                         lnet_net_lock(0);
3469                         /*
3470                          * lnet_find_peer_ni_locked() grabs a refcount for
3471                          * us. No need to take it explicitly.
3472                          */
3473                         lpni = lnet_find_peer_ni_locked(nid);
3474                         if (!lpni) {
3475                                 lnet_net_unlock(0);
3476                                 LNetMDUnlink(mdh);
3477                                 continue;
3478                         }
3479
3480                         lpni->lpni_recovery_ping_mdh = mdh;
3481                         /*
3482                          * While we're unlocked the lpni could've been
3483                          * readded on the recovery queue. In this case we
3484                          * don't need to add it to the local queue, since
3485                          * it's already on there and the thread that added
3486                          * it would've incremented the refcount on the
3487                          * peer, which means we need to decref the refcount
3488                          * that was implicitly grabbed by find_peer_ni_locked.
3489                          * Otherwise, if the lpni is still not on
3490                          * the recovery queue, then we'll add it to the
3491                          * processed list.
3492                          */
3493                         if (list_empty(&lpni->lpni_recovery))
3494                                 list_add_tail(&lpni->lpni_recovery, &processed_list);
3495                         else
3496                                 lnet_peer_ni_decref_locked(lpni);
3497                         lnet_net_unlock(0);
3498
3499                         spin_lock(&lpni->lpni_lock);
3500                         if (rc)
3501                                 lpni->lpni_state &= ~LNET_PEER_NI_RECOVERY_PENDING;
3502                 }
3503                 spin_unlock(&lpni->lpni_lock);
3504         }
3505
3506         list_splice_init(&processed_list, &local_queue);
3507         lnet_net_lock(0);
3508         list_splice(&local_queue, &the_lnet.ln_mt_peerNIRecovq);
3509         lnet_net_unlock(0);
3510 }
3511
3512 static int
3513 lnet_monitor_thread(void *arg)
3514 {
3515         time64_t recovery_timeout = 0;
3516         time64_t rsp_timeout = 0;
3517         int interval;
3518         time64_t now;
3519
3520         wait_for_completion(&the_lnet.ln_started);
3521         /*
3522          * The monitor thread takes care of the following:
3523          *  1. Checks the aliveness of routers
3524          *  2. Checks if there are messages on the resend queue to resend
3525          *     them.
3526          *  3. Check if there are any NIs on the local recovery queue and
3527          *     pings them
3528          *  4. Checks if there are any NIs on the remote recovery queue
3529          *     and pings them.
3530          */
3531         while (the_lnet.ln_mt_state == LNET_MT_STATE_RUNNING) {
3532                 now = ktime_get_real_seconds();
3533
3534                 if (lnet_router_checker_active())
3535                         lnet_check_routers();
3536
3537                 lnet_resend_pending_msgs();
3538
3539                 if (now >= rsp_timeout) {
3540                         lnet_finalize_expired_responses();
3541                         rsp_timeout = now + (lnet_transaction_timeout / 2);
3542                 }
3543
3544                 if (now >= recovery_timeout) {
3545                         lnet_recover_local_nis();
3546                         lnet_recover_peer_nis();
3547                         recovery_timeout = now + lnet_recovery_interval;
3548                 }
3549
3550                 /*
3551                  * TODO do we need to check if we should sleep without
3552                  * timeout?  Technically, an active system will always
3553                  * have messages in flight so this check will always
3554                  * evaluate to false. And on an idle system do we care
3555                  * if we wake up every 1 second? Although, we've seen
3556                  * cases where we get a complaint that an idle thread
3557                  * is waking up unnecessarily.
3558                  *
3559                  * Take into account the current net_count when you wake
3560                  * up for alive router checking, since we need to check
3561                  * possibly as many networks as we have configured.
3562                  */
3563                 interval = min(lnet_recovery_interval,
3564                                min((unsigned int) alive_router_check_interval /
3565                                         lnet_current_net_count,
3566                                    lnet_transaction_timeout / 2));
3567                 wait_for_completion_interruptible_timeout(
3568                         &the_lnet.ln_mt_wait_complete,
3569                         cfs_time_seconds(interval));
3570                 /* Must re-init the completion before testing anything,
3571                  * including ln_mt_state.
3572                  */
3573                 reinit_completion(&the_lnet.ln_mt_wait_complete);
3574         }
3575
3576         /* Shutting down */
3577         lnet_net_lock(LNET_LOCK_EX);
3578         the_lnet.ln_mt_state = LNET_MT_STATE_SHUTDOWN;
3579         lnet_net_unlock(LNET_LOCK_EX);
3580
3581         /* signal that the monitor thread is exiting */
3582         up(&the_lnet.ln_mt_signal);
3583
3584         return 0;
3585 }
3586
3587 /*
3588  * lnet_send_ping
3589  * Sends a ping.
3590  * Returns == 0 if success
3591  * Returns > 0 if LNetMDBind or prior fails
3592  * Returns < 0 if LNetGet fails
3593  */
3594 int
3595 lnet_send_ping(lnet_nid_t dest_nid,
3596                struct lnet_handle_md *mdh, int nnis,
3597                void *user_data, lnet_handler_t handler, bool recovery)
3598 {
3599         struct lnet_md md = { NULL };
3600         struct lnet_process_id id;
3601         struct lnet_ping_buffer *pbuf;
3602         int rc;
3603
3604         if (dest_nid == LNET_NID_ANY) {
3605                 rc = -EHOSTUNREACH;
3606                 goto fail_error;
3607         }
3608
3609         pbuf = lnet_ping_buffer_alloc(nnis, GFP_NOFS);
3610         if (!pbuf) {
3611                 rc = ENOMEM;
3612                 goto fail_error;
3613         }
3614
3615         /* initialize md content */
3616         md.start     = &pbuf->pb_info;
3617         md.length    = LNET_PING_INFO_SIZE(nnis);
3618         md.threshold = 2; /* GET/REPLY */
3619         md.max_size  = 0;
3620         md.options   = LNET_MD_TRUNCATE;
3621         md.user_ptr  = user_data;
3622         md.handler   = handler;
3623
3624         rc = LNetMDBind(md, LNET_UNLINK, mdh);
3625         if (rc) {
3626                 lnet_ping_buffer_decref(pbuf);
3627                 CERROR("Can't bind MD: %d\n", rc);
3628                 rc = -rc; /* change the rc to positive */
3629                 goto fail_error;
3630         }
3631         id.pid = LNET_PID_LUSTRE;
3632         id.nid = dest_nid;
3633
3634         rc = LNetGet(LNET_NID_ANY, *mdh, id,
3635                      LNET_RESERVED_PORTAL,
3636                      LNET_PROTO_PING_MATCHBITS, 0, recovery);
3637
3638         if (rc)
3639                 goto fail_unlink_md;
3640
3641         return 0;
3642
3643 fail_unlink_md:
3644         LNetMDUnlink(*mdh);
3645         LNetInvalidateMDHandle(mdh);
3646 fail_error:
3647         return rc;
3648 }
3649
3650 static void
3651 lnet_handle_recovery_reply(struct lnet_mt_event_info *ev_info,
3652                            int status, bool send, bool unlink_event)
3653 {
3654         lnet_nid_t nid = ev_info->mt_nid;
3655
3656         if (ev_info->mt_type == MT_TYPE_LOCAL_NI) {
3657                 struct lnet_ni *ni;
3658
3659                 lnet_net_lock(0);
3660                 ni = lnet_nid2ni_locked(nid, 0);
3661                 if (!ni) {
3662                         lnet_net_unlock(0);
3663                         return;
3664                 }
3665                 lnet_ni_lock(ni);
3666                 if (!send || (send && status != 0))
3667                         ni->ni_recovery_state &= ~LNET_NI_RECOVERY_PENDING;
3668                 if (status)
3669                         ni->ni_recovery_state |= LNET_NI_RECOVERY_FAILED;
3670                 lnet_ni_unlock(ni);
3671                 lnet_net_unlock(0);
3672
3673                 if (status != 0) {
3674                         CERROR("local NI (%s) recovery failed with %d\n",
3675                                libcfs_nid2str(nid), status);
3676                         return;
3677                 }
3678                 /*
3679                  * need to increment healthv for the ni here, because in
3680                  * the lnet_finalize() path we don't have access to this
3681                  * NI. And in order to get access to it, we'll need to
3682                  * carry forward too much information.
3683                  * In the peer case, it'll naturally be incremented
3684                  */
3685                 if (!unlink_event)
3686                         lnet_inc_healthv(&ni->ni_healthv,
3687                                          lnet_health_sensitivity);
3688         } else {
3689                 struct lnet_peer_ni *lpni;
3690                 int cpt;
3691
3692                 cpt = lnet_net_lock_current();
3693                 lpni = lnet_find_peer_ni_locked(nid);
3694                 if (!lpni) {
3695                         lnet_net_unlock(cpt);
3696                         return;
3697                 }
3698                 spin_lock(&lpni->lpni_lock);
3699                 if (!send || (send && status != 0))
3700                         lpni->lpni_state &= ~LNET_PEER_NI_RECOVERY_PENDING;
3701                 if (status)
3702                         lpni->lpni_state |= LNET_PEER_NI_RECOVERY_FAILED;
3703     &