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