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