Whamcloud - gitweb
e23a532e82c231c97cb7f548a36a655461b73c97
[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  *
31  * lnet/lnet/lib-move.c
32  *
33  * Data movement routines
34  */
35
36 #define DEBUG_SUBSYSTEM S_LNET
37
38 #include <linux/pagemap.h>
39
40 #include <lnet/lib-lnet.h>
41 #include <linux/nsproxy.h>
42 #include <lnet/lnet_rdma.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         struct lnet_nid sd_dst_nid;
59         struct lnet_nid sd_src_nid;
60         struct lnet_nid sd_rtr_nid;
61         int sd_cpt;
62         int sd_md_cpt;
63         __u32 sd_send_case;
64 };
65
66 static inline bool
67 lnet_msg_is_response(struct lnet_msg *msg)
68 {
69         return msg->msg_type == LNET_MSG_ACK || msg->msg_type == LNET_MSG_REPLY;
70 }
71
72 static inline bool
73 lnet_response_tracking_enabled(__u32 msg_type, unsigned int md_options)
74 {
75         if (md_options & LNET_MD_NO_TRACK_RESPONSE)
76                 /* Explicitly disabled in MD options */
77                 return false;
78
79         if (md_options & LNET_MD_TRACK_RESPONSE)
80                 /* Explicity enabled in MD options */
81                 return true;
82
83         if (lnet_response_tracking == 3)
84                 /* Enabled for all message types */
85                 return true;
86
87         if (msg_type == LNET_MSG_PUT)
88                 return lnet_response_tracking == 2;
89
90         if (msg_type == LNET_MSG_GET)
91                 return lnet_response_tracking == 1;
92
93         return false;
94 }
95
96 static inline struct lnet_comm_count *
97 get_stats_counts(struct lnet_element_stats *stats,
98                  enum lnet_stats_type stats_type)
99 {
100         switch (stats_type) {
101         case LNET_STATS_TYPE_SEND:
102                 return &stats->el_send_stats;
103         case LNET_STATS_TYPE_RECV:
104                 return &stats->el_recv_stats;
105         case LNET_STATS_TYPE_DROP:
106                 return &stats->el_drop_stats;
107         default:
108                 CERROR("Unknown stats type\n");
109         }
110
111         return NULL;
112 }
113
114 void lnet_incr_stats(struct lnet_element_stats *stats,
115                      enum lnet_msg_type msg_type,
116                      enum lnet_stats_type stats_type)
117 {
118         struct lnet_comm_count *counts = get_stats_counts(stats, stats_type);
119         if (!counts)
120                 return;
121
122         switch (msg_type) {
123         case LNET_MSG_ACK:
124                 atomic_inc(&counts->co_ack_count);
125                 break;
126         case LNET_MSG_PUT:
127                 atomic_inc(&counts->co_put_count);
128                 break;
129         case LNET_MSG_GET:
130                 atomic_inc(&counts->co_get_count);
131                 break;
132         case LNET_MSG_REPLY:
133                 atomic_inc(&counts->co_reply_count);
134                 break;
135         case LNET_MSG_HELLO:
136                 atomic_inc(&counts->co_hello_count);
137                 break;
138         default:
139                 CERROR("There is a BUG in the code. Unknown message type\n");
140                 break;
141         }
142 }
143
144 __u32 lnet_sum_stats(struct lnet_element_stats *stats,
145                      enum lnet_stats_type stats_type)
146 {
147         struct lnet_comm_count *counts = get_stats_counts(stats, stats_type);
148         if (!counts)
149                 return 0;
150
151         return (atomic_read(&counts->co_ack_count) +
152                 atomic_read(&counts->co_put_count) +
153                 atomic_read(&counts->co_get_count) +
154                 atomic_read(&counts->co_reply_count) +
155                 atomic_read(&counts->co_hello_count));
156 }
157
158 static inline void assign_stats(struct lnet_ioctl_comm_count *msg_stats,
159                                 struct lnet_comm_count *counts)
160 {
161         msg_stats->ico_get_count = atomic_read(&counts->co_get_count);
162         msg_stats->ico_put_count = atomic_read(&counts->co_put_count);
163         msg_stats->ico_reply_count = atomic_read(&counts->co_reply_count);
164         msg_stats->ico_ack_count = atomic_read(&counts->co_ack_count);
165         msg_stats->ico_hello_count = atomic_read(&counts->co_hello_count);
166 }
167
168 void lnet_usr_translate_stats(struct lnet_ioctl_element_msg_stats *msg_stats,
169                               struct lnet_element_stats *stats)
170 {
171         struct lnet_comm_count *counts;
172
173         LASSERT(msg_stats);
174         LASSERT(stats);
175
176         counts = get_stats_counts(stats, LNET_STATS_TYPE_SEND);
177         if (!counts)
178                 return;
179         assign_stats(&msg_stats->im_send_stats, counts);
180
181         counts = get_stats_counts(stats, LNET_STATS_TYPE_RECV);
182         if (!counts)
183                 return;
184         assign_stats(&msg_stats->im_recv_stats, counts);
185
186         counts = get_stats_counts(stats, LNET_STATS_TYPE_DROP);
187         if (!counts)
188                 return;
189         assign_stats(&msg_stats->im_drop_stats, counts);
190 }
191
192 int
193 lnet_fail_nid(lnet_nid_t nid4, unsigned int threshold)
194 {
195         struct lnet_test_peer *tp;
196         struct list_head *el;
197         struct list_head *next;
198         struct lnet_nid nid;
199         LIST_HEAD(cull);
200
201         lnet_nid4_to_nid(nid4, &nid);
202         /* NB: use lnet_net_lock(0) to serialize operations on test peers */
203         if (threshold != 0) {
204                 /* Adding a new entry */
205                 LIBCFS_ALLOC(tp, sizeof(*tp));
206                 if (tp == NULL)
207                         return -ENOMEM;
208
209                 tp->tp_nid = nid;
210                 tp->tp_threshold = threshold;
211
212                 lnet_net_lock(0);
213                 list_add_tail(&tp->tp_list, &the_lnet.ln_test_peers);
214                 lnet_net_unlock(0);
215                 return 0;
216         }
217
218         lnet_net_lock(0);
219
220         list_for_each_safe(el, next, &the_lnet.ln_test_peers) {
221                 tp = list_entry(el, struct lnet_test_peer, tp_list);
222
223                 if (tp->tp_threshold == 0 ||    /* needs culling anyway */
224                     LNET_NID_IS_ANY(&nid) ||    /* removing all entries */
225                     nid_same(&tp->tp_nid, &nid)) {      /* matched this one */
226                         list_move(&tp->tp_list, &cull);
227                 }
228         }
229
230         lnet_net_unlock(0);
231
232         while ((tp = list_first_entry_or_null(&cull,
233                                               struct lnet_test_peer,
234                                               tp_list)) != NULL) {
235                 list_del(&tp->tp_list);
236                 LIBCFS_FREE(tp, sizeof(*tp));
237         }
238         return 0;
239 }
240
241 static int
242 fail_peer(struct lnet_nid *nid, int outgoing)
243 {
244         struct lnet_test_peer *tp;
245         struct list_head *el;
246         struct list_head *next;
247         LIST_HEAD(cull);
248         int fail = 0;
249
250         /* NB: use lnet_net_lock(0) to serialize operations on test peers */
251         lnet_net_lock(0);
252
253         list_for_each_safe(el, next, &the_lnet.ln_test_peers) {
254                 tp = list_entry(el, struct lnet_test_peer, tp_list);
255
256                 if (tp->tp_threshold == 0) {
257                         /* zombie entry */
258                         if (outgoing) {
259                                 /* only cull zombies on outgoing tests,
260                                  * since we may be at interrupt priority on
261                                  * incoming messages. */
262                                 list_move(&tp->tp_list, &cull);
263                         }
264                         continue;
265                 }
266
267                 if (LNET_NID_IS_ANY(&tp->tp_nid) ||     /* fail every peer */
268                     nid_same(nid, &tp->tp_nid)) {       /* fail this peer */
269                         fail = 1;
270
271                         if (tp->tp_threshold != LNET_MD_THRESH_INF) {
272                                 tp->tp_threshold--;
273                                 if (outgoing &&
274                                     tp->tp_threshold == 0) {
275                                         /* see above */
276                                         list_move(&tp->tp_list, &cull);
277                                 }
278                         }
279                         break;
280                 }
281         }
282
283         lnet_net_unlock(0);
284
285         while ((tp = list_first_entry_or_null(&cull,
286                                               struct lnet_test_peer,
287                                               tp_list)) != NULL) {
288                 list_del(&tp->tp_list);
289                 LIBCFS_FREE(tp, sizeof(*tp));
290         }
291
292         return fail;
293 }
294
295 unsigned int
296 lnet_iov_nob(unsigned int niov, struct kvec *iov)
297 {
298         unsigned int nob = 0;
299
300         LASSERT(niov == 0 || iov != NULL);
301         while (niov-- > 0)
302                 nob += (iov++)->iov_len;
303
304         return (nob);
305 }
306 EXPORT_SYMBOL(lnet_iov_nob);
307
308 void
309 lnet_copy_iov2iov(unsigned int ndiov, struct kvec *diov, unsigned int doffset,
310                   unsigned int nsiov, struct kvec *siov, unsigned int soffset,
311                   unsigned int nob)
312 {
313         /* NB diov, siov are READ-ONLY */
314         unsigned int this_nob;
315
316         if (nob == 0)
317                 return;
318
319         /* skip complete frags before 'doffset' */
320         LASSERT(ndiov > 0);
321         while (doffset >= diov->iov_len) {
322                 doffset -= diov->iov_len;
323                 diov++;
324                 ndiov--;
325                 LASSERT(ndiov > 0);
326         }
327
328         /* skip complete frags before 'soffset' */
329         LASSERT(nsiov > 0);
330         while (soffset >= siov->iov_len) {
331                 soffset -= siov->iov_len;
332                 siov++;
333                 nsiov--;
334                 LASSERT(nsiov > 0);
335         }
336
337         do {
338                 LASSERT(ndiov > 0);
339                 LASSERT(nsiov > 0);
340                 this_nob = min3((unsigned int)diov->iov_len - doffset,
341                                 (unsigned int)siov->iov_len - soffset,
342                                 nob);
343
344                 memcpy((char *)diov->iov_base + doffset,
345                        (char *)siov->iov_base + soffset, this_nob);
346                 nob -= this_nob;
347
348                 if (diov->iov_len > doffset + this_nob) {
349                         doffset += this_nob;
350                 } else {
351                         diov++;
352                         ndiov--;
353                         doffset = 0;
354                 }
355
356                 if (siov->iov_len > soffset + this_nob) {
357                         soffset += this_nob;
358                 } else {
359                         siov++;
360                         nsiov--;
361                         soffset = 0;
362                 }
363         } while (nob > 0);
364 }
365 EXPORT_SYMBOL(lnet_copy_iov2iov);
366
367 unsigned int
368 lnet_kiov_nob(unsigned int niov, struct bio_vec *kiov)
369 {
370         unsigned int  nob = 0;
371
372         LASSERT(niov == 0 || kiov != NULL);
373         while (niov-- > 0)
374                 nob += (kiov++)->bv_len;
375
376         return (nob);
377 }
378 EXPORT_SYMBOL(lnet_kiov_nob);
379
380 void
381 lnet_copy_kiov2kiov(unsigned int ndiov, struct bio_vec *diov,
382                     unsigned int doffset,
383                     unsigned int nsiov, struct bio_vec *siov,
384                     unsigned int soffset,
385                     unsigned int nob)
386 {
387         /* NB diov, siov are READ-ONLY */
388         unsigned int    this_nob;
389         char           *daddr = NULL;
390         char           *saddr = NULL;
391
392         if (nob == 0)
393                 return;
394
395         LASSERT (!in_interrupt ());
396
397         LASSERT (ndiov > 0);
398         while (doffset >= diov->bv_len) {
399                 doffset -= diov->bv_len;
400                 diov++;
401                 ndiov--;
402                 LASSERT(ndiov > 0);
403         }
404
405         LASSERT(nsiov > 0);
406         while (soffset >= siov->bv_len) {
407                 soffset -= siov->bv_len;
408                 siov++;
409                 nsiov--;
410                 LASSERT(nsiov > 0);
411         }
412
413         do {
414                 LASSERT(ndiov > 0);
415                 LASSERT(nsiov > 0);
416                 this_nob = min3(diov->bv_len - doffset,
417                                 siov->bv_len - soffset,
418                                 nob);
419
420                 if (daddr == NULL)
421                         daddr = ((char *)kmap(diov->bv_page)) +
422                                 diov->bv_offset + doffset;
423                 if (saddr == NULL)
424                         saddr = ((char *)kmap(siov->bv_page)) +
425                                 siov->bv_offset + soffset;
426
427                 /* Vanishing risk of kmap deadlock when mapping 2 pages.
428                  * However in practice at least one of the kiovs will be mapped
429                  * kernel pages and the map/unmap will be NOOPs */
430
431                 memcpy (daddr, saddr, this_nob);
432                 nob -= this_nob;
433
434                 if (diov->bv_len > doffset + this_nob) {
435                         daddr += this_nob;
436                         doffset += this_nob;
437                 } else {
438                         kunmap(diov->bv_page);
439                         daddr = NULL;
440                         diov++;
441                         ndiov--;
442                         doffset = 0;
443                 }
444
445                 if (siov->bv_len > soffset + this_nob) {
446                         saddr += this_nob;
447                         soffset += this_nob;
448                 } else {
449                         kunmap(siov->bv_page);
450                         saddr = NULL;
451                         siov++;
452                         nsiov--;
453                         soffset = 0;
454                 }
455         } while (nob > 0);
456
457         if (daddr != NULL)
458                 kunmap(diov->bv_page);
459         if (saddr != NULL)
460                 kunmap(siov->bv_page);
461 }
462 EXPORT_SYMBOL(lnet_copy_kiov2kiov);
463
464 void
465 lnet_copy_kiov2iov (unsigned int niov, struct kvec *iov, unsigned int iovoffset,
466                     unsigned int nkiov, struct bio_vec *kiov,
467                     unsigned int kiovoffset,
468                     unsigned int nob)
469 {
470         /* NB iov, kiov are READ-ONLY */
471         unsigned int    this_nob;
472         char           *addr = NULL;
473
474         if (nob == 0)
475                 return;
476
477         LASSERT (!in_interrupt ());
478
479         LASSERT (niov > 0);
480         while (iovoffset >= iov->iov_len) {
481                 iovoffset -= iov->iov_len;
482                 iov++;
483                 niov--;
484                 LASSERT(niov > 0);
485         }
486
487         LASSERT(nkiov > 0);
488         while (kiovoffset >= kiov->bv_len) {
489                 kiovoffset -= kiov->bv_len;
490                 kiov++;
491                 nkiov--;
492                 LASSERT(nkiov > 0);
493         }
494
495         do {
496                 LASSERT(niov > 0);
497                 LASSERT(nkiov > 0);
498                 this_nob = min3((unsigned int)iov->iov_len - iovoffset,
499                                 (unsigned int)kiov->bv_len - kiovoffset,
500                                 nob);
501
502                 if (addr == NULL)
503                         addr = ((char *)kmap(kiov->bv_page)) +
504                                 kiov->bv_offset + kiovoffset;
505
506                 memcpy((char *)iov->iov_base + iovoffset, addr, this_nob);
507                 nob -= this_nob;
508
509                 if (iov->iov_len > iovoffset + this_nob) {
510                         iovoffset += this_nob;
511                 } else {
512                         iov++;
513                         niov--;
514                         iovoffset = 0;
515                 }
516
517                 if (kiov->bv_len > kiovoffset + this_nob) {
518                         addr += this_nob;
519                         kiovoffset += this_nob;
520                 } else {
521                         kunmap(kiov->bv_page);
522                         addr = NULL;
523                         kiov++;
524                         nkiov--;
525                         kiovoffset = 0;
526                 }
527
528         } while (nob > 0);
529
530         if (addr != NULL)
531                 kunmap(kiov->bv_page);
532 }
533 EXPORT_SYMBOL(lnet_copy_kiov2iov);
534
535 void
536 lnet_copy_iov2kiov(unsigned int nkiov, struct bio_vec *kiov,
537                    unsigned int kiovoffset,
538                    unsigned int niov, struct kvec *iov, unsigned int iovoffset,
539                    unsigned int nob)
540 {
541         /* NB kiov, iov are READ-ONLY */
542         unsigned int    this_nob;
543         char           *addr = NULL;
544
545         if (nob == 0)
546                 return;
547
548         LASSERT (!in_interrupt ());
549
550         LASSERT (nkiov > 0);
551         while (kiovoffset >= kiov->bv_len) {
552                 kiovoffset -= kiov->bv_len;
553                 kiov++;
554                 nkiov--;
555                 LASSERT(nkiov > 0);
556         }
557
558         LASSERT(niov > 0);
559         while (iovoffset >= iov->iov_len) {
560                 iovoffset -= iov->iov_len;
561                 iov++;
562                 niov--;
563                 LASSERT(niov > 0);
564         }
565
566         do {
567                 LASSERT(nkiov > 0);
568                 LASSERT(niov > 0);
569                 this_nob = min3((unsigned int)kiov->bv_len - kiovoffset,
570                                 (unsigned int)iov->iov_len - iovoffset,
571                                 nob);
572
573                 if (addr == NULL)
574                         addr = ((char *)kmap(kiov->bv_page)) +
575                                 kiov->bv_offset + kiovoffset;
576
577                 memcpy (addr, (char *)iov->iov_base + iovoffset, this_nob);
578                 nob -= this_nob;
579
580                 if (kiov->bv_len > kiovoffset + this_nob) {
581                         addr += this_nob;
582                         kiovoffset += this_nob;
583                 } else {
584                         kunmap(kiov->bv_page);
585                         addr = NULL;
586                         kiov++;
587                         nkiov--;
588                         kiovoffset = 0;
589                 }
590
591                 if (iov->iov_len > iovoffset + this_nob) {
592                         iovoffset += this_nob;
593                 } else {
594                         iov++;
595                         niov--;
596                         iovoffset = 0;
597                 }
598         } while (nob > 0);
599
600         if (addr != NULL)
601                 kunmap(kiov->bv_page);
602 }
603 EXPORT_SYMBOL(lnet_copy_iov2kiov);
604
605 int
606 lnet_extract_kiov(int dst_niov, struct bio_vec *dst,
607                   int src_niov, struct bio_vec *src,
608                   unsigned int offset, unsigned int len)
609 {
610         /* Initialise 'dst' to the subset of 'src' starting at 'offset',
611          * for exactly 'len' bytes, and return the number of entries.
612          * NB not destructive to 'src' */
613         unsigned int    frag_len;
614         unsigned int    niov;
615
616         if (len == 0)                           /* no data => */
617                 return (0);                     /* no frags */
618
619         LASSERT(src_niov > 0);
620         while (offset >= src->bv_len) {      /* skip initial frags */
621                 offset -= src->bv_len;
622                 src_niov--;
623                 src++;
624                 LASSERT(src_niov > 0);
625         }
626
627         niov = 1;
628         for (;;) {
629                 LASSERT(src_niov > 0);
630                 LASSERT((int)niov <= dst_niov);
631
632                 frag_len = src->bv_len - offset;
633                 dst->bv_page = src->bv_page;
634                 dst->bv_offset = src->bv_offset + offset;
635
636                 if (len <= frag_len) {
637                         dst->bv_len = len;
638                         LASSERT(dst->bv_offset + dst->bv_len <= PAGE_SIZE);
639                         return niov;
640                 }
641
642                 dst->bv_len = frag_len;
643                 LASSERT(dst->bv_offset + dst->bv_len <= PAGE_SIZE);
644
645                 len -= frag_len;
646                 dst++;
647                 src++;
648                 niov++;
649                 src_niov--;
650                 offset = 0;
651         }
652 }
653 EXPORT_SYMBOL(lnet_extract_kiov);
654
655 void
656 lnet_ni_recv(struct lnet_ni *ni, void *private, struct lnet_msg *msg,
657              int delayed, unsigned int offset, unsigned int mlen,
658              unsigned int rlen)
659 {
660         unsigned int niov = 0;
661         struct kvec *iov = NULL;
662         struct bio_vec  *kiov = NULL;
663         int rc;
664
665         LASSERT (!in_interrupt ());
666         LASSERT (mlen == 0 || msg != NULL);
667
668         if (msg != NULL) {
669                 LASSERT(msg->msg_receiving);
670                 LASSERT(!msg->msg_sending);
671                 LASSERT(rlen == msg->msg_len);
672                 LASSERT(mlen <= msg->msg_len);
673                 LASSERT(msg->msg_offset == offset);
674                 LASSERT(msg->msg_wanted == mlen);
675
676                 msg->msg_receiving = 0;
677
678                 if (mlen != 0) {
679                         niov = msg->msg_niov;
680                         kiov = msg->msg_kiov;
681
682                         LASSERT (niov > 0);
683                         LASSERT ((iov == NULL) != (kiov == NULL));
684                 }
685         }
686
687         rc = (ni->ni_net->net_lnd->lnd_recv)(ni, private, msg, delayed,
688                                              niov, kiov, offset, mlen,
689                                              rlen);
690         if (rc < 0)
691                 lnet_finalize(msg, rc);
692 }
693
694 static void
695 lnet_setpayloadbuffer(struct lnet_msg *msg)
696 {
697         struct lnet_libmd *md = msg->msg_md;
698
699         LASSERT(msg->msg_len > 0);
700         LASSERT(!msg->msg_routing);
701         LASSERT(md != NULL);
702         LASSERT(msg->msg_niov == 0);
703         LASSERT(msg->msg_kiov == NULL);
704
705         msg->msg_niov = md->md_niov;
706         msg->msg_kiov = md->md_kiov;
707 }
708
709 void
710 lnet_prep_send(struct lnet_msg *msg, int type, struct lnet_processid *target,
711                unsigned int offset, unsigned int len)
712 {
713         msg->msg_type = type;
714         msg->msg_target = *target;
715         msg->msg_len = len;
716         msg->msg_offset = offset;
717
718         if (len != 0)
719                 lnet_setpayloadbuffer(msg);
720
721         memset (&msg->msg_hdr, 0, sizeof (msg->msg_hdr));
722         msg->msg_hdr.type           = type;
723         /* dest_nid will be overwritten by lnet_select_pathway() */
724         msg->msg_hdr.dest_nid = target->nid;
725         msg->msg_hdr.dest_pid = target->pid;
726         /* src_nid will be set later */
727         msg->msg_hdr.src_pid        = the_lnet.ln_pid;
728         msg->msg_hdr.payload_length = len;
729 }
730
731 void
732 lnet_ni_send(struct lnet_ni *ni, struct lnet_msg *msg)
733 {
734         void *priv = msg->msg_private;
735         int rc;
736
737         LASSERT(!in_interrupt());
738         LASSERT(nid_is_lo0(&ni->ni_nid) ||
739                 (msg->msg_txcredit && msg->msg_peertxcredit));
740
741         rc = (ni->ni_net->net_lnd->lnd_send)(ni, priv, msg);
742         if (rc < 0) {
743                 msg->msg_no_resend = true;
744                 lnet_finalize(msg, rc);
745         }
746 }
747
748 static int
749 lnet_ni_eager_recv(struct lnet_ni *ni, struct lnet_msg *msg)
750 {
751         int     rc;
752
753         LASSERT(!msg->msg_sending);
754         LASSERT(msg->msg_receiving);
755         LASSERT(!msg->msg_rx_ready_delay);
756         LASSERT(ni->ni_net->net_lnd->lnd_eager_recv != NULL);
757
758         msg->msg_rx_ready_delay = 1;
759         rc = (ni->ni_net->net_lnd->lnd_eager_recv)(ni, msg->msg_private, msg,
760                                                   &msg->msg_private);
761         if (rc != 0) {
762                 CERROR("recv from %s / send to %s aborted: "
763                        "eager_recv failed %d\n",
764                        libcfs_nidstr(&msg->msg_rxpeer->lpni_nid),
765                        libcfs_idstr(&msg->msg_target), rc);
766                 LASSERT(rc < 0); /* required by my callers */
767         }
768
769         return rc;
770 }
771
772 /* returns true if this message should be dropped */
773 static bool
774 lnet_check_message_drop(struct lnet_ni *ni, struct lnet_peer_ni *lpni,
775                         struct lnet_msg *msg)
776 {
777         if (msg->msg_target.pid & LNET_PID_USERFLAG)
778                 return false;
779
780         if (!lnet_peer_aliveness_enabled(lpni))
781                 return false;
782
783         /* If we're resending a message, let's attempt to send it even if
784          * the peer is down to fulfill our resend quota on the message
785          */
786         if (msg->msg_retry_count > 0)
787                 return false;
788
789         /* try and send recovery messages irregardless */
790         if (msg->msg_recovery)
791                 return false;
792
793         /* always send any responses */
794         if (lnet_msg_is_response(msg))
795                 return false;
796
797         /* assume peer_ni is alive as long as we're within the configured
798          * peer timeout
799          */
800         return ktime_get_seconds() >=
801                 (lpni->lpni_last_alive +
802                  lpni->lpni_net->net_tunables.lct_peer_timeout);
803 }
804
805 /**
806  * \param msg The message to be sent.
807  * \param do_send True if lnet_ni_send() should be called in this function.
808  *        lnet_send() is going to lnet_net_unlock immediately after this, so
809  *        it sets do_send FALSE and I don't do the unlock/send/lock bit.
810  *
811  * \retval LNET_CREDIT_OK If \a msg sent or OK to send.
812  * \retval LNET_CREDIT_WAIT If \a msg blocked for credit.
813  * \retval -EHOSTUNREACH If the next hop of the message appears dead.
814  * \retval -ECANCELED If the MD of the message has been unlinked.
815  */
816 static int
817 lnet_post_send_locked(struct lnet_msg *msg, int do_send)
818 {
819         struct lnet_peer_ni     *lp = msg->msg_txpeer;
820         struct lnet_ni          *ni = msg->msg_txni;
821         int                     cpt = msg->msg_tx_cpt;
822         struct lnet_tx_queue    *tq = ni->ni_tx_queues[cpt];
823
824         /* non-lnet_send() callers have checked before */
825         LASSERT(!do_send || msg->msg_tx_delayed);
826         LASSERT(!msg->msg_receiving);
827         LASSERT(msg->msg_tx_committed);
828
829         /* can't get here if we're sending to the loopback interface */
830         if (the_lnet.ln_loni)
831                 LASSERT(!nid_same(&lp->lpni_nid, &the_lnet.ln_loni->ni_nid));
832
833         /* NB 'lp' is always the next hop */
834         if (lnet_check_message_drop(ni, lp, msg)) {
835                 the_lnet.ln_counters[cpt]->lct_common.lcc_drop_count++;
836                 the_lnet.ln_counters[cpt]->lct_common.lcc_drop_length +=
837                         msg->msg_len;
838                 lnet_net_unlock(cpt);
839                 if (msg->msg_txpeer)
840                         lnet_incr_stats(&msg->msg_txpeer->lpni_stats,
841                                         msg->msg_type,
842                                         LNET_STATS_TYPE_DROP);
843                 if (msg->msg_txni)
844                         lnet_incr_stats(&msg->msg_txni->ni_stats,
845                                         msg->msg_type,
846                                         LNET_STATS_TYPE_DROP);
847
848                 CNETERR("Dropping message for %s: peer not alive\n",
849                         libcfs_idstr(&msg->msg_target));
850                 msg->msg_health_status = LNET_MSG_STATUS_REMOTE_DROPPED;
851                 if (do_send)
852                         lnet_finalize(msg, -EHOSTUNREACH);
853
854                 lnet_net_lock(cpt);
855                 return -EHOSTUNREACH;
856         }
857
858         if (msg->msg_md != NULL &&
859             (msg->msg_md->md_flags & LNET_MD_FLAG_ABORTED) != 0) {
860                 lnet_net_unlock(cpt);
861
862                 CNETERR("Aborting message for %s: LNetM[DE]Unlink() already "
863                         "called on the MD/ME.\n",
864                         libcfs_idstr(&msg->msg_target));
865                 if (do_send) {
866                         msg->msg_no_resend = true;
867                         CDEBUG(D_NET, "msg %p to %s canceled and will not be resent\n",
868                                msg, libcfs_idstr(&msg->msg_target));
869                         lnet_finalize(msg, -ECANCELED);
870                 }
871
872                 lnet_net_lock(cpt);
873                 return -ECANCELED;
874         }
875
876         if (!msg->msg_peertxcredit) {
877                 spin_lock(&lp->lpni_lock);
878                 LASSERT((lp->lpni_txcredits < 0) ==
879                         !list_empty(&lp->lpni_txq));
880
881                 msg->msg_peertxcredit = 1;
882                 lp->lpni_txqnob += msg->msg_len + sizeof(struct lnet_hdr_nid4);
883                 lp->lpni_txcredits--;
884
885                 if (lp->lpni_txcredits < lp->lpni_mintxcredits)
886                         lp->lpni_mintxcredits = lp->lpni_txcredits;
887
888                 if (lp->lpni_txcredits < 0) {
889                         msg->msg_tx_delayed = 1;
890                         list_add_tail(&msg->msg_list, &lp->lpni_txq);
891                         spin_unlock(&lp->lpni_lock);
892                         return LNET_CREDIT_WAIT;
893                 }
894                 spin_unlock(&lp->lpni_lock);
895         }
896
897         if (!msg->msg_txcredit) {
898                 LASSERT((tq->tq_credits < 0) ==
899                         !list_empty(&tq->tq_delayed));
900
901                 msg->msg_txcredit = 1;
902                 tq->tq_credits--;
903                 atomic_dec(&ni->ni_tx_credits);
904
905                 if (tq->tq_credits < tq->tq_credits_min)
906                         tq->tq_credits_min = tq->tq_credits;
907
908                 if (tq->tq_credits < 0) {
909                         msg->msg_tx_delayed = 1;
910                         list_add_tail(&msg->msg_list, &tq->tq_delayed);
911                         return LNET_CREDIT_WAIT;
912                 }
913         }
914
915         if (unlikely(!list_empty(&the_lnet.ln_delay_rules)) &&
916             lnet_delay_rule_match_locked(&msg->msg_hdr, msg)) {
917                 msg->msg_tx_delayed = 1;
918                 return LNET_CREDIT_WAIT;
919         }
920
921         /* unset the tx_delay flag as we're going to send it now */
922         msg->msg_tx_delayed = 0;
923
924         if (do_send) {
925                 lnet_net_unlock(cpt);
926                 lnet_ni_send(ni, msg);
927                 lnet_net_lock(cpt);
928         }
929         return LNET_CREDIT_OK;
930 }
931
932
933 static struct lnet_rtrbufpool *
934 lnet_msg2bufpool(struct lnet_msg *msg)
935 {
936         struct lnet_rtrbufpool  *rbp;
937         int                     cpt;
938
939         LASSERT(msg->msg_rx_committed);
940
941         cpt = msg->msg_rx_cpt;
942         rbp = &the_lnet.ln_rtrpools[cpt][0];
943
944         LASSERT(msg->msg_len <= LNET_MTU);
945         while (msg->msg_len > (unsigned int)rbp->rbp_npages * PAGE_SIZE) {
946                 rbp++;
947                 LASSERT(rbp < &the_lnet.ln_rtrpools[cpt][LNET_NRBPOOLS]);
948         }
949
950         return rbp;
951 }
952
953 static int
954 lnet_post_routed_recv_locked(struct lnet_msg *msg, int do_recv)
955 {
956         /* lnet_parse is going to lnet_net_unlock immediately after this, so it
957          * sets do_recv FALSE and I don't do the unlock/send/lock bit.
958          * I return LNET_CREDIT_WAIT if msg blocked and LNET_CREDIT_OK if
959          * received or OK to receive */
960         struct lnet_peer_ni *lpni = msg->msg_rxpeer;
961         struct lnet_peer *lp;
962         struct lnet_rtrbufpool *rbp;
963         struct lnet_rtrbuf *rb;
964
965         LASSERT(msg->msg_kiov == NULL);
966         LASSERT(msg->msg_niov == 0);
967         LASSERT(msg->msg_routing);
968         LASSERT(msg->msg_receiving);
969         LASSERT(!msg->msg_sending);
970         LASSERT(lpni->lpni_peer_net);
971         LASSERT(lpni->lpni_peer_net->lpn_peer);
972
973         lp = lpni->lpni_peer_net->lpn_peer;
974
975         /* non-lnet_parse callers only receive delayed messages */
976         LASSERT(!do_recv || msg->msg_rx_delayed);
977
978         if (!msg->msg_peerrtrcredit) {
979                 /* lpni_lock protects the credit manipulation */
980                 spin_lock(&lpni->lpni_lock);
981
982                 msg->msg_peerrtrcredit = 1;
983                 lpni->lpni_rtrcredits--;
984                 if (lpni->lpni_rtrcredits < lpni->lpni_minrtrcredits)
985                         lpni->lpni_minrtrcredits = lpni->lpni_rtrcredits;
986
987                 if (lpni->lpni_rtrcredits < 0) {
988                         spin_unlock(&lpni->lpni_lock);
989                         /* must have checked eager_recv before here */
990                         LASSERT(msg->msg_rx_ready_delay);
991                         msg->msg_rx_delayed = 1;
992                         /* lp_lock protects the lp_rtrq */
993                         spin_lock(&lp->lp_lock);
994                         list_add_tail(&msg->msg_list, &lp->lp_rtrq);
995                         spin_unlock(&lp->lp_lock);
996                         return LNET_CREDIT_WAIT;
997                 }
998                 spin_unlock(&lpni->lpni_lock);
999         }
1000
1001         rbp = lnet_msg2bufpool(msg);
1002
1003         if (!msg->msg_rtrcredit) {
1004                 msg->msg_rtrcredit = 1;
1005                 rbp->rbp_credits--;
1006                 if (rbp->rbp_credits < rbp->rbp_mincredits)
1007                         rbp->rbp_mincredits = rbp->rbp_credits;
1008
1009                 if (rbp->rbp_credits < 0) {
1010                         /* must have checked eager_recv before here */
1011                         LASSERT(msg->msg_rx_ready_delay);
1012                         msg->msg_rx_delayed = 1;
1013                         list_add_tail(&msg->msg_list, &rbp->rbp_msgs);
1014                         return LNET_CREDIT_WAIT;
1015                 }
1016         }
1017
1018         LASSERT(!list_empty(&rbp->rbp_bufs));
1019         rb = list_first_entry(&rbp->rbp_bufs, struct lnet_rtrbuf, rb_list);
1020         list_del(&rb->rb_list);
1021
1022         msg->msg_niov = rbp->rbp_npages;
1023         msg->msg_kiov = &rb->rb_kiov[0];
1024
1025         /* unset the msg-rx_delayed flag since we're receiving the message */
1026         msg->msg_rx_delayed = 0;
1027
1028         if (do_recv) {
1029                 int cpt = msg->msg_rx_cpt;
1030
1031                 lnet_net_unlock(cpt);
1032                 lnet_ni_recv(msg->msg_rxni, msg->msg_private, msg, 1,
1033                              0, msg->msg_len, msg->msg_len);
1034                 lnet_net_lock(cpt);
1035         }
1036         return LNET_CREDIT_OK;
1037 }
1038
1039 void
1040 lnet_return_tx_credits_locked(struct lnet_msg *msg)
1041 {
1042         struct lnet_peer_ni     *txpeer = msg->msg_txpeer;
1043         struct lnet_ni          *txni = msg->msg_txni;
1044         struct lnet_msg         *msg2;
1045
1046         if (msg->msg_txcredit) {
1047                 struct lnet_ni       *ni = msg->msg_txni;
1048                 struct lnet_tx_queue *tq = ni->ni_tx_queues[msg->msg_tx_cpt];
1049
1050                 /* give back NI txcredits */
1051                 msg->msg_txcredit = 0;
1052
1053                 LASSERT((tq->tq_credits < 0) ==
1054                         !list_empty(&tq->tq_delayed));
1055
1056                 tq->tq_credits++;
1057                 atomic_inc(&ni->ni_tx_credits);
1058                 if (tq->tq_credits <= 0) {
1059                         msg2 = list_first_entry(&tq->tq_delayed,
1060                                                 struct lnet_msg, msg_list);
1061                         list_del(&msg2->msg_list);
1062
1063                         LASSERT(msg2->msg_txni == ni);
1064                         LASSERT(msg2->msg_tx_delayed);
1065                         LASSERT(msg2->msg_tx_cpt == msg->msg_tx_cpt);
1066
1067                         (void) lnet_post_send_locked(msg2, 1);
1068                 }
1069         }
1070
1071         if (msg->msg_peertxcredit) {
1072                 /* give back peer txcredits */
1073                 msg->msg_peertxcredit = 0;
1074
1075                 spin_lock(&txpeer->lpni_lock);
1076                 LASSERT((txpeer->lpni_txcredits < 0) ==
1077                         !list_empty(&txpeer->lpni_txq));
1078
1079                 txpeer->lpni_txqnob -=  msg->msg_len +
1080                                         sizeof(struct lnet_hdr_nid4);
1081                 LASSERT(txpeer->lpni_txqnob >= 0);
1082
1083                 txpeer->lpni_txcredits++;
1084                 if (txpeer->lpni_txcredits <= 0) {
1085                         int msg2_cpt;
1086
1087                         msg2 = list_first_entry(&txpeer->lpni_txq,
1088                                                 struct lnet_msg, msg_list);
1089                         list_del(&msg2->msg_list);
1090                         spin_unlock(&txpeer->lpni_lock);
1091
1092                         LASSERT(msg2->msg_txpeer == txpeer);
1093                         LASSERT(msg2->msg_tx_delayed);
1094
1095                         msg2_cpt = msg2->msg_tx_cpt;
1096
1097                         /*
1098                          * The msg_cpt can be different from the msg2_cpt
1099                          * so we need to make sure we lock the correct cpt
1100                          * for msg2.
1101                          * Once we call lnet_post_send_locked() it is no
1102                          * longer safe to access msg2, since it could've
1103                          * been freed by lnet_finalize(), but we still
1104                          * need to relock the correct cpt, so we cache the
1105                          * msg2_cpt for the purpose of the check that
1106                          * follows the call to lnet_pose_send_locked().
1107                          */
1108                         if (msg2_cpt != msg->msg_tx_cpt) {
1109                                 lnet_net_unlock(msg->msg_tx_cpt);
1110                                 lnet_net_lock(msg2_cpt);
1111                         }
1112                         (void) lnet_post_send_locked(msg2, 1);
1113                         if (msg2_cpt != msg->msg_tx_cpt) {
1114                                 lnet_net_unlock(msg2_cpt);
1115                                 lnet_net_lock(msg->msg_tx_cpt);
1116                         }
1117                 } else {
1118                         spin_unlock(&txpeer->lpni_lock);
1119                 }
1120         }
1121
1122         if (txni != NULL) {
1123                 msg->msg_txni = NULL;
1124                 lnet_ni_decref_locked(txni, msg->msg_tx_cpt);
1125         }
1126
1127         if (txpeer != NULL) {
1128                 msg->msg_txpeer = NULL;
1129                 lnet_peer_ni_decref_locked(txpeer);
1130         }
1131 }
1132
1133 void
1134 lnet_schedule_blocked_locked(struct lnet_rtrbufpool *rbp)
1135 {
1136         struct lnet_msg *msg;
1137
1138         if (list_empty(&rbp->rbp_msgs))
1139                 return;
1140         msg = list_first_entry(&rbp->rbp_msgs,
1141                                struct lnet_msg, msg_list);
1142         list_del(&msg->msg_list);
1143
1144         (void)lnet_post_routed_recv_locked(msg, 1);
1145 }
1146
1147 void
1148 lnet_drop_routed_msgs_locked(struct list_head *list, int cpt)
1149 {
1150         struct lnet_msg *msg;
1151         struct lnet_msg *tmp;
1152
1153         lnet_net_unlock(cpt);
1154
1155         list_for_each_entry_safe(msg, tmp, list, msg_list) {
1156                 lnet_ni_recv(msg->msg_rxni, msg->msg_private, NULL,
1157                              0, 0, 0, msg->msg_hdr.payload_length);
1158                 list_del_init(&msg->msg_list);
1159                 msg->msg_no_resend = true;
1160                 msg->msg_health_status = LNET_MSG_STATUS_REMOTE_ERROR;
1161                 lnet_finalize(msg, -ECANCELED);
1162         }
1163
1164         lnet_net_lock(cpt);
1165 }
1166
1167 void
1168 lnet_return_rx_credits_locked(struct lnet_msg *msg)
1169 {
1170         struct lnet_peer_ni *rxpeerni = msg->msg_rxpeer;
1171         struct lnet_peer *lp;
1172         struct lnet_ni *rxni = msg->msg_rxni;
1173         struct lnet_msg *msg2;
1174
1175         if (msg->msg_rtrcredit) {
1176                 /* give back global router credits */
1177                 struct lnet_rtrbuf *rb;
1178                 struct lnet_rtrbufpool *rbp;
1179
1180                 /* NB If a msg ever blocks for a buffer in rbp_msgs, it stays
1181                  * there until it gets one allocated, or aborts the wait
1182                  * itself */
1183                 LASSERT(msg->msg_kiov != NULL);
1184
1185                 rb = list_entry(msg->msg_kiov, struct lnet_rtrbuf, rb_kiov[0]);
1186                 rbp = rb->rb_pool;
1187
1188                 msg->msg_kiov = NULL;
1189                 msg->msg_rtrcredit = 0;
1190
1191                 LASSERT(rbp == lnet_msg2bufpool(msg));
1192
1193                 LASSERT((rbp->rbp_credits > 0) ==
1194                         !list_empty(&rbp->rbp_bufs));
1195
1196                 /* If routing is now turned off, we just drop this buffer and
1197                  * don't bother trying to return credits.  */
1198                 if (!the_lnet.ln_routing) {
1199                         lnet_destroy_rtrbuf(rb, rbp->rbp_npages);
1200                         goto routing_off;
1201                 }
1202
1203                 /* It is possible that a user has lowered the desired number of
1204                  * buffers in this pool.  Make sure we never put back
1205                  * more buffers than the stated number. */
1206                 if (unlikely(rbp->rbp_credits >= rbp->rbp_req_nbuffers)) {
1207                         /* Discard this buffer so we don't have too
1208                          * many. */
1209                         lnet_destroy_rtrbuf(rb, rbp->rbp_npages);
1210                         rbp->rbp_nbuffers--;
1211                 } else {
1212                         list_add(&rb->rb_list, &rbp->rbp_bufs);
1213                         rbp->rbp_credits++;
1214                         if (rbp->rbp_credits <= 0)
1215                                 lnet_schedule_blocked_locked(rbp);
1216                 }
1217         }
1218
1219 routing_off:
1220         if (msg->msg_peerrtrcredit) {
1221                 LASSERT(rxpeerni);
1222                 LASSERT(rxpeerni->lpni_peer_net);
1223                 LASSERT(rxpeerni->lpni_peer_net->lpn_peer);
1224
1225                 /* give back peer router credits */
1226                 msg->msg_peerrtrcredit = 0;
1227
1228                 spin_lock(&rxpeerni->lpni_lock);
1229                 rxpeerni->lpni_rtrcredits++;
1230                 spin_unlock(&rxpeerni->lpni_lock);
1231
1232                 lp = rxpeerni->lpni_peer_net->lpn_peer;
1233                 spin_lock(&lp->lp_lock);
1234
1235                 /* drop all messages which are queued to be routed on that
1236                  * peer. */
1237                 if (!the_lnet.ln_routing) {
1238                         LIST_HEAD(drop);
1239                         list_splice_init(&lp->lp_rtrq, &drop);
1240                         spin_unlock(&lp->lp_lock);
1241                         lnet_drop_routed_msgs_locked(&drop, msg->msg_rx_cpt);
1242                 } else if (!list_empty(&lp->lp_rtrq)) {
1243                         int msg2_cpt;
1244
1245                         msg2 = list_first_entry(&lp->lp_rtrq,
1246                                                 struct lnet_msg, msg_list);
1247                         list_del(&msg2->msg_list);
1248                         msg2_cpt = msg2->msg_rx_cpt;
1249                         spin_unlock(&lp->lp_lock);
1250                         /*
1251                          * messages on the lp_rtrq can be from any NID in
1252                          * the peer, which means they might have different
1253                          * cpts. We need to make sure we lock the right
1254                          * one.
1255                          */
1256                         if (msg2_cpt != msg->msg_rx_cpt) {
1257                                 lnet_net_unlock(msg->msg_rx_cpt);
1258                                 lnet_net_lock(msg2_cpt);
1259                         }
1260                         (void) lnet_post_routed_recv_locked(msg2, 1);
1261                         if (msg2_cpt != msg->msg_rx_cpt) {
1262                                 lnet_net_unlock(msg2_cpt);
1263                                 lnet_net_lock(msg->msg_rx_cpt);
1264                         }
1265                 } else {
1266                         spin_unlock(&lp->lp_lock);
1267                 }
1268         }
1269         if (rxni != NULL) {
1270                 msg->msg_rxni = NULL;
1271                 lnet_ni_decref_locked(rxni, msg->msg_rx_cpt);
1272         }
1273         if (rxpeerni != NULL) {
1274                 msg->msg_rxpeer = NULL;
1275                 lnet_peer_ni_decref_locked(rxpeerni);
1276         }
1277 }
1278
1279 static struct lnet_peer_ni *
1280 lnet_select_peer_ni(struct lnet_ni *best_ni, lnet_nid_t dst_nid,
1281                     struct lnet_peer *peer,
1282                     struct lnet_peer_ni *best_lpni,
1283                     struct lnet_peer_net *peer_net)
1284 {
1285         /*
1286          * Look at the peer NIs for the destination peer that connect
1287          * to the chosen net. If a peer_ni is preferred when using the
1288          * best_ni to communicate, we use that one. If there is no
1289          * preferred peer_ni, or there are multiple preferred peer_ni,
1290          * the available transmit credits are used. If the transmit
1291          * credits are equal, we round-robin over the peer_ni.
1292          */
1293         struct lnet_peer_ni *lpni = NULL;
1294         int best_lpni_credits = (best_lpni) ? best_lpni->lpni_txcredits :
1295                 INT_MIN;
1296         int best_lpni_healthv = (best_lpni) ?
1297                 atomic_read(&best_lpni->lpni_healthv) : 0;
1298         bool best_lpni_is_preferred = false;
1299         bool lpni_is_preferred;
1300         int lpni_healthv;
1301         __u32 lpni_sel_prio;
1302         __u32 best_sel_prio = LNET_MAX_SELECTION_PRIORITY;
1303
1304         while ((lpni = lnet_get_next_peer_ni_locked(peer, peer_net, lpni))) {
1305                 /*
1306                  * if the best_ni we've chosen aleady has this lpni
1307                  * preferred, then let's use it
1308                  */
1309                 if (best_ni) {
1310                         lpni_is_preferred = lnet_peer_is_pref_nid_locked(
1311                                 lpni, &best_ni->ni_nid);
1312                         CDEBUG(D_NET, "%s lpni_is_preferred = %d\n",
1313                                libcfs_nidstr(&best_ni->ni_nid),
1314                                lpni_is_preferred);
1315                 } else {
1316                         lpni_is_preferred = false;
1317                 }
1318
1319                 lpni_healthv = atomic_read(&lpni->lpni_healthv);
1320                 lpni_sel_prio = lpni->lpni_sel_priority;
1321
1322                 if (best_lpni)
1323                         CDEBUG(D_NET, "n:[%s, %s] h:[%d, %d] p:[%d, %d] c:[%d, %d] s:[%d, %d]\n",
1324                                 libcfs_nidstr(&lpni->lpni_nid),
1325                                 libcfs_nidstr(&best_lpni->lpni_nid),
1326                                 lpni_healthv, best_lpni_healthv,
1327                                 lpni_sel_prio, best_sel_prio,
1328                                 lpni->lpni_txcredits, best_lpni_credits,
1329                                 lpni->lpni_seq, best_lpni->lpni_seq);
1330                 else
1331                         goto select_lpni;
1332
1333                 /* pick the healthiest peer ni */
1334                 if (lpni_healthv < best_lpni_healthv)
1335                         continue;
1336                 else if (lpni_healthv > best_lpni_healthv) {
1337                         if (best_lpni_is_preferred)
1338                                 best_lpni_is_preferred = false;
1339                         goto select_lpni;
1340                 }
1341
1342                 if (lpni_sel_prio > best_sel_prio)
1343                         continue;
1344                 else if (lpni_sel_prio < best_sel_prio) {
1345                         if (best_lpni_is_preferred)
1346                                 best_lpni_is_preferred = false;
1347                         goto select_lpni;
1348                 }
1349
1350                 /* if this is a preferred peer use it */
1351                 if (!best_lpni_is_preferred && lpni_is_preferred) {
1352                         best_lpni_is_preferred = true;
1353                         goto select_lpni;
1354                 } else if (best_lpni_is_preferred && !lpni_is_preferred) {
1355                         /* this is not the preferred peer so let's ignore
1356                          * it.
1357                          */
1358                         continue;
1359                 }
1360
1361                 if (lpni->lpni_txcredits < best_lpni_credits)
1362                         /* We already have a peer that has more credits
1363                          * available than this one. No need to consider
1364                          * this peer further.
1365                          */
1366                         continue;
1367                 else if (lpni->lpni_txcredits > best_lpni_credits)
1368                         goto select_lpni;
1369
1370                 /* The best peer found so far and the current peer
1371                  * have the same number of available credits let's
1372                  * make sure to select between them using Round Robin
1373                  */
1374                 if (best_lpni && (best_lpni->lpni_seq <= lpni->lpni_seq))
1375                         continue;
1376 select_lpni:
1377                 best_lpni_is_preferred = lpni_is_preferred;
1378                 best_lpni_healthv = lpni_healthv;
1379                 best_sel_prio = lpni_sel_prio;
1380                 best_lpni = lpni;
1381                 best_lpni_credits = lpni->lpni_txcredits;
1382         }
1383
1384         /* if we still can't find a peer ni then we can't reach it */
1385         if (!best_lpni) {
1386                 __u32 net_id = (peer_net) ? peer_net->lpn_net_id :
1387                         LNET_NIDNET(dst_nid);
1388                 CDEBUG(D_NET, "no peer_ni found on peer net %s\n",
1389                                 libcfs_net2str(net_id));
1390                 return NULL;
1391         }
1392
1393         CDEBUG(D_NET, "sd_best_lpni = %s\n",
1394                libcfs_nidstr(&best_lpni->lpni_nid));
1395
1396         return best_lpni;
1397 }
1398
1399 /*
1400  * Prerequisite: the best_ni should already be set in the sd
1401  * Find the best lpni.
1402  * If the net id is provided then restrict lpni selection on
1403  * that particular net.
1404  * Otherwise find any reachable lpni. When dealing with an MR
1405  * gateway and it has multiple lpnis which we can use
1406  * we want to select the best one from the list of reachable
1407  * ones.
1408  */
1409 static inline struct lnet_peer_ni *
1410 lnet_find_best_lpni(struct lnet_ni *lni, lnet_nid_t dst_nid,
1411                     struct lnet_peer *peer, __u32 net_id)
1412 {
1413         struct lnet_peer_net *peer_net;
1414
1415         /* find the best_lpni on any local network */
1416         if (net_id == LNET_NET_ANY) {
1417                 struct lnet_peer_ni *best_lpni = NULL;
1418                 struct lnet_peer_net *lpn;
1419                 list_for_each_entry(lpn, &peer->lp_peer_nets, lpn_peer_nets) {
1420                         /* no net specified find any reachable peer ni */
1421                         if (!lnet_islocalnet_locked(lpn->lpn_net_id))
1422                                 continue;
1423                         best_lpni = lnet_select_peer_ni(lni, dst_nid, peer,
1424                                                         best_lpni, lpn);
1425                 }
1426
1427                 return best_lpni;
1428         }
1429         /* restrict on the specified net */
1430         peer_net = lnet_peer_get_net_locked(peer, net_id);
1431         if (peer_net)
1432                 return lnet_select_peer_ni(lni, dst_nid, peer, NULL, peer_net);
1433
1434         return NULL;
1435 }
1436
1437 static int
1438 lnet_compare_gw_lpnis(struct lnet_peer_ni *lpni1, struct lnet_peer_ni *lpni2)
1439 {
1440         if (lpni1->lpni_txqnob < lpni2->lpni_txqnob)
1441                 return 1;
1442
1443         if (lpni1->lpni_txqnob > lpni2->lpni_txqnob)
1444                 return -1;
1445
1446         if (lpni1->lpni_txcredits > lpni2->lpni_txcredits)
1447                 return 1;
1448
1449         if (lpni1->lpni_txcredits < lpni2->lpni_txcredits)
1450                 return -1;
1451
1452         return 0;
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_peer_ni *remote_lpni,
1480                        struct lnet_route **prev_route,
1481                        struct lnet_peer_ni **gwni)
1482 {
1483         struct lnet_peer_ni *lpni, *best_gw_ni = NULL;
1484         struct lnet_route *best_route;
1485         struct lnet_route *last_route;
1486         struct lnet_route *route;
1487         int rc;
1488         bool best_rte_is_preferred = false;
1489         struct lnet_nid *gw_pnid;
1490
1491         CDEBUG(D_NET, "Looking up a route to %s, from %s\n",
1492                libcfs_net2str(rnet->lrn_net), libcfs_net2str(src_net));
1493
1494         best_route = last_route = NULL;
1495         list_for_each_entry(route, &rnet->lrn_routes, lr_list) {
1496                 if (!lnet_is_route_alive(route))
1497                         continue;
1498                 gw_pnid = &route->lr_gateway->lp_primary_nid;
1499
1500                 /* no protection on below fields, but it's harmless */
1501                 if (last_route && (last_route->lr_seq - route->lr_seq < 0))
1502                         last_route = route;
1503
1504                 /* if the best route found is in the preferred list then
1505                  * tag it as preferred and use it later on. But if we
1506                  * didn't find any routes which are on the preferred list
1507                  * then just use the best route possible.
1508                  */
1509                 rc = lnet_peer_is_pref_rtr_locked(remote_lpni, gw_pnid);
1510
1511                 if (!best_route || (rc && !best_rte_is_preferred)) {
1512                         /* Restrict the selection of the router NI on the
1513                          * src_net provided. If the src_net is LNET_NID_ANY,
1514                          * then select the best interface available.
1515                          */
1516                         lpni = lnet_find_best_lpni(NULL, LNET_NID_ANY,
1517                                                    route->lr_gateway,
1518                                                    src_net);
1519                         if (!lpni) {
1520                                 CDEBUG(D_NET,
1521                                        "Gateway %s does not have a peer NI on net %s\n",
1522                                        libcfs_nidstr(gw_pnid),
1523                                        libcfs_net2str(src_net));
1524                                 continue;
1525                         }
1526                 }
1527
1528                 if (rc && !best_rte_is_preferred) {
1529                         /* This is the first preferred route we found,
1530                          * so it beats any route found previously
1531                          */
1532                         best_route = route;
1533                         if (!last_route)
1534                                 last_route = route;
1535                         best_gw_ni = lpni;
1536                         best_rte_is_preferred = true;
1537                         CDEBUG(D_NET, "preferred gw = %s\n",
1538                                libcfs_nidstr(gw_pnid));
1539                         continue;
1540                 } else if ((!rc) && best_rte_is_preferred)
1541                         /* The best route we found so far is in the preferred
1542                          * list, so it beats any non-preferred route
1543                          */
1544                         continue;
1545
1546                 if (!best_route) {
1547                         best_route = last_route = route;
1548                         best_gw_ni = lpni;
1549                         continue;
1550                 }
1551
1552                 rc = lnet_compare_routes(route, best_route);
1553                 if (rc == -1)
1554                         continue;
1555
1556                 /* Restrict the selection of the router NI on the
1557                  * src_net provided. If the src_net is LNET_NID_ANY,
1558                  * then select the best interface available.
1559                  */
1560                 lpni = lnet_find_best_lpni(NULL, LNET_NID_ANY,
1561                                            route->lr_gateway,
1562                                            src_net);
1563                 if (!lpni) {
1564                         CDEBUG(D_NET,
1565                                "Gateway %s does not have a peer NI on net %s\n",
1566                                libcfs_nidstr(gw_pnid),
1567                                libcfs_net2str(src_net));
1568                         continue;
1569                 }
1570
1571                 if (rc == 1) {
1572                         best_route = route;
1573                         best_gw_ni = lpni;
1574                         continue;
1575                 }
1576
1577                 rc = lnet_compare_gw_lpnis(lpni, best_gw_ni);
1578                 if (rc == -1)
1579                         continue;
1580
1581                 if (rc == 1 || route->lr_seq <= best_route->lr_seq) {
1582                         best_route = route;
1583                         best_gw_ni = lpni;
1584                         continue;
1585                 }
1586         }
1587
1588         *prev_route = last_route;
1589         *gwni = best_gw_ni;
1590
1591         return best_route;
1592 }
1593
1594 static inline unsigned int
1595 lnet_dev_prio_of_md(struct lnet_ni *ni, unsigned int dev_idx)
1596 {
1597         if (dev_idx == UINT_MAX)
1598                 return UINT_MAX;
1599
1600         if (!ni || !ni->ni_net || !ni->ni_net->net_lnd ||
1601             !ni->ni_net->net_lnd->lnd_get_dev_prio)
1602                 return UINT_MAX;
1603
1604         return ni->ni_net->net_lnd->lnd_get_dev_prio(ni, dev_idx);
1605 }
1606
1607 static struct lnet_ni *
1608 lnet_get_best_ni(struct lnet_net *local_net, struct lnet_ni *best_ni,
1609                  struct lnet_peer *peer, struct lnet_peer_net *peer_net,
1610                  struct lnet_msg *msg, int md_cpt)
1611 {
1612         struct lnet_libmd *md = msg->msg_md;
1613         unsigned int offset = msg->msg_offset;
1614         unsigned int shortest_distance;
1615         struct lnet_ni *ni = NULL;
1616         int best_credits;
1617         int best_healthv;
1618         __u32 best_sel_prio;
1619         unsigned int best_dev_prio;
1620         int best_ni_fatal;
1621         unsigned int dev_idx = UINT_MAX;
1622         bool gpu = md ? (md->md_flags & LNET_MD_FLAG_GPU) : false;
1623
1624         if (gpu) {
1625                 struct page *page = lnet_get_first_page(md, offset);
1626
1627                 dev_idx = lnet_get_dev_idx(page);
1628         }
1629
1630         /*
1631          * If there is no peer_ni that we can send to on this network,
1632          * then there is no point in looking for a new best_ni here.
1633         */
1634         if (!lnet_get_next_peer_ni_locked(peer, peer_net, NULL))
1635                 return best_ni;
1636
1637         if (best_ni == NULL) {
1638                 best_sel_prio = LNET_MAX_SELECTION_PRIORITY;
1639                 shortest_distance = UINT_MAX;
1640                 best_dev_prio = UINT_MAX;
1641                 best_credits = INT_MIN;
1642                 best_healthv = 0;
1643                 best_ni_fatal = true;
1644         } else {
1645                 best_dev_prio = lnet_dev_prio_of_md(best_ni, dev_idx);
1646                 shortest_distance = cfs_cpt_distance(lnet_cpt_table(), md_cpt,
1647                                                      best_ni->ni_dev_cpt);
1648                 best_credits = atomic_read(&best_ni->ni_tx_credits);
1649                 best_healthv = atomic_read(&best_ni->ni_healthv);
1650                 best_sel_prio = best_ni->ni_sel_priority;
1651                 best_ni_fatal = atomic_read(&best_ni->ni_fatal_error_on);
1652         }
1653
1654         while ((ni = lnet_get_next_ni_locked(local_net, ni))) {
1655                 unsigned int distance;
1656                 int ni_credits;
1657                 int ni_healthv;
1658                 int ni_fatal;
1659                 __u32 ni_sel_prio;
1660                 unsigned int ni_dev_prio;
1661
1662                 ni_credits = atomic_read(&ni->ni_tx_credits);
1663                 ni_healthv = atomic_read(&ni->ni_healthv);
1664                 ni_fatal = atomic_read(&ni->ni_fatal_error_on);
1665                 ni_sel_prio = ni->ni_sel_priority;
1666
1667                 /*
1668                  * calculate the distance from the CPT on which
1669                  * the message memory is allocated to the CPT of
1670                  * the NI's physical device
1671                  */
1672                 distance = cfs_cpt_distance(lnet_cpt_table(),
1673                                             md_cpt,
1674                                             ni->ni_dev_cpt);
1675
1676                 ni_dev_prio = lnet_dev_prio_of_md(ni, dev_idx);
1677
1678                 /*
1679                  * All distances smaller than the NUMA range
1680                  * are treated equally.
1681                  */
1682                 if (!gpu && distance < lnet_numa_range)
1683                         distance = lnet_numa_range;
1684
1685                 /*
1686                  * Select on health, selection policy, direct dma prio,
1687                  * shorter distance, available credits, then round-robin.
1688                  */
1689                 if (best_ni)
1690                         CDEBUG(D_NET, "compare ni %s [f:%s, c:%d, d:%d, s:%d, p:%u, g:%u, h:%d] with best_ni %s [f:%s, c:%d, d:%d, s:%d, p:%u, g:%u, h:%d]\n",
1691                                libcfs_nidstr(&ni->ni_nid),
1692                                ni_fatal ? "y" : "n", ni_credits, distance,
1693                                ni->ni_seq, ni_sel_prio, ni_dev_prio, ni_healthv,
1694                                (best_ni) ? libcfs_nidstr(&best_ni->ni_nid)
1695                                : "not selected",
1696                                best_ni_fatal ? "y" : "n", best_credits,
1697                                shortest_distance,
1698                                (best_ni) ? best_ni->ni_seq : 0,
1699                                best_sel_prio, best_dev_prio, best_healthv);
1700                 else
1701                         goto select_ni;
1702
1703                 if (ni_fatal && !best_ni_fatal)
1704                         continue;
1705                 else if (!ni_fatal && best_ni_fatal)
1706                         goto select_ni;
1707
1708                 if (ni_healthv < best_healthv)
1709                         continue;
1710                 else if (ni_healthv > best_healthv)
1711                         goto select_ni;
1712
1713                 if (ni_sel_prio > best_sel_prio)
1714                         continue;
1715                 else if (ni_sel_prio < best_sel_prio)
1716                         goto select_ni;
1717
1718                 if (ni_dev_prio > best_dev_prio)
1719                         continue;
1720                 else if (ni_dev_prio < best_dev_prio)
1721                         goto select_ni;
1722
1723                 if (distance > shortest_distance)
1724                         continue;
1725                 else if (distance < shortest_distance)
1726                         goto select_ni;
1727
1728                 if (ni_credits < best_credits)
1729                         continue;
1730                 else if (ni_credits > best_credits)
1731                         goto select_ni;
1732
1733                 if (best_ni && best_ni->ni_seq <= ni->ni_seq)
1734                         continue;
1735
1736 select_ni:
1737                 best_sel_prio = ni_sel_prio;
1738                 best_dev_prio = ni_dev_prio;
1739                 shortest_distance = distance;
1740                 best_healthv = ni_healthv;
1741                 best_ni = ni;
1742                 best_credits = ni_credits;
1743                 best_ni_fatal = ni_fatal;
1744         }
1745
1746         CDEBUG(D_NET, "selected best_ni %s\n",
1747                (best_ni) ? libcfs_nidstr(&best_ni->ni_nid) : "no selection");
1748
1749         return best_ni;
1750 }
1751
1752 static bool
1753 lnet_reserved_msg(struct lnet_msg *msg)
1754 {
1755         if (msg->msg_type == LNET_MSG_PUT) {
1756                 if (msg->msg_hdr.msg.put.ptl_index == LNET_RESERVED_PORTAL)
1757                         return true;
1758         } else if (msg->msg_type == LNET_MSG_GET) {
1759                 if (msg->msg_hdr.msg.get.ptl_index == LNET_RESERVED_PORTAL)
1760                         return true;
1761         }
1762         return false;
1763 }
1764
1765 /* Can the specified message trigger peer discovery?
1766  *
1767  * Traffic to the LNET_RESERVED_PORTAL may not trigger peer discovery,
1768  * because such traffic is required to perform discovery. We therefore
1769  * exclude all GET and PUT on that portal. We also exclude all ACK and
1770  * REPLY traffic, but that is because the portal is not tracked in the
1771  * message structure for these message types. We could restrict this
1772  * further by also checking for LNET_PROTO_PING_MATCHBITS.
1773  */
1774 static bool
1775 lnet_msg_discovery(struct lnet_msg *msg)
1776 {
1777         return !(lnet_reserved_msg(msg) || lnet_msg_is_response(msg));
1778 }
1779
1780 /* Is the specified message an LNet ping?
1781  */
1782 static bool
1783 lnet_msg_is_ping(struct lnet_msg *msg)
1784 {
1785         if (msg->msg_type == LNET_MSG_GET &&
1786             msg->msg_hdr.msg.get.ptl_index == LNET_RESERVED_PORTAL)
1787                 return true;
1788
1789         return false;
1790 }
1791
1792 #define SRC_SPEC        0x0001
1793 #define SRC_ANY         0x0002
1794 #define LOCAL_DST       0x0004
1795 #define REMOTE_DST      0x0008
1796 #define MR_DST          0x0010
1797 #define NMR_DST         0x0020
1798 #define SND_RESP        0x0040
1799
1800 /* The following to defines are used for return codes */
1801 #define REPEAT_SEND     0x1000
1802 #define PASS_THROUGH    0x2000
1803
1804 /* The different cases lnet_select pathway needs to handle */
1805 #define SRC_SPEC_LOCAL_MR_DST   (SRC_SPEC | LOCAL_DST | MR_DST)
1806 #define SRC_SPEC_ROUTER_MR_DST  (SRC_SPEC | REMOTE_DST | MR_DST)
1807 #define SRC_SPEC_LOCAL_NMR_DST  (SRC_SPEC | LOCAL_DST | NMR_DST)
1808 #define SRC_SPEC_ROUTER_NMR_DST (SRC_SPEC | REMOTE_DST | NMR_DST)
1809 #define SRC_ANY_LOCAL_MR_DST    (SRC_ANY | LOCAL_DST | MR_DST)
1810 #define SRC_ANY_ROUTER_MR_DST   (SRC_ANY | REMOTE_DST | MR_DST)
1811 #define SRC_ANY_LOCAL_NMR_DST   (SRC_ANY | LOCAL_DST | NMR_DST)
1812 #define SRC_ANY_ROUTER_NMR_DST  (SRC_ANY | REMOTE_DST | NMR_DST)
1813
1814 static int
1815 lnet_handle_lo_send(struct lnet_send_data *sd)
1816 {
1817         struct lnet_msg *msg = sd->sd_msg;
1818         int cpt = sd->sd_cpt;
1819
1820         if (the_lnet.ln_state != LNET_STATE_RUNNING)
1821                 return -ESHUTDOWN;
1822
1823         /* No send credit hassles with LOLND */
1824         lnet_ni_addref_locked(the_lnet.ln_loni, cpt);
1825         msg->msg_hdr.dest_nid = the_lnet.ln_loni->ni_nid;
1826         if (!msg->msg_routing)
1827                 msg->msg_hdr.src_nid = the_lnet.ln_loni->ni_nid;
1828         msg->msg_target.nid = the_lnet.ln_loni->ni_nid;
1829         lnet_msg_commit(msg, cpt);
1830         msg->msg_txni = the_lnet.ln_loni;
1831
1832         return LNET_CREDIT_OK;
1833 }
1834
1835 static int
1836 lnet_handle_send(struct lnet_send_data *sd)
1837 {
1838         struct lnet_ni *best_ni = sd->sd_best_ni;
1839         struct lnet_peer_ni *best_lpni = sd->sd_best_lpni;
1840         struct lnet_peer_ni *final_dst_lpni = sd->sd_final_dst_lpni;
1841         struct lnet_msg *msg = sd->sd_msg;
1842         int cpt2;
1843         __u32 send_case = sd->sd_send_case;
1844         int rc;
1845         __u32 routing = send_case & REMOTE_DST;
1846         struct lnet_rsp_tracker *rspt;
1847
1848         /* Increment sequence number of the selected peer, peer net,
1849          * local ni and local net so that we pick the next ones
1850          * in Round Robin.
1851          */
1852         best_lpni->lpni_peer_net->lpn_peer->lp_send_seq++;
1853         best_lpni->lpni_peer_net->lpn_seq =
1854                 best_lpni->lpni_peer_net->lpn_peer->lp_send_seq;
1855         best_lpni->lpni_seq = best_lpni->lpni_peer_net->lpn_seq;
1856         the_lnet.ln_net_seq++;
1857         best_ni->ni_net->net_seq = the_lnet.ln_net_seq;
1858         best_ni->ni_seq = best_ni->ni_net->net_seq;
1859
1860         CDEBUG(D_NET, "%s NI seq info: [%d:%d:%d:%u] %s LPNI seq info [%d:%d:%d:%u]\n",
1861                libcfs_nidstr(&best_ni->ni_nid),
1862                best_ni->ni_seq, best_ni->ni_net->net_seq,
1863                atomic_read(&best_ni->ni_tx_credits),
1864                best_ni->ni_sel_priority,
1865                libcfs_nidstr(&best_lpni->lpni_nid),
1866                best_lpni->lpni_seq, best_lpni->lpni_peer_net->lpn_seq,
1867                best_lpni->lpni_txcredits,
1868                best_lpni->lpni_sel_priority);
1869
1870         /*
1871          * grab a reference on the peer_ni so it sticks around even if
1872          * we need to drop and relock the lnet_net_lock below.
1873          */
1874         lnet_peer_ni_addref_locked(best_lpni);
1875
1876         /*
1877          * Use lnet_cpt_of_nid() to determine the CPT used to commit the
1878          * message. This ensures that we get a CPT that is correct for
1879          * the NI when the NI has been restricted to a subset of all CPTs.
1880          * If the selected CPT differs from the one currently locked, we
1881          * must unlock and relock the lnet_net_lock(), and then check whether
1882          * the configuration has changed. We don't have a hold on the best_ni
1883          * yet, and it may have vanished.
1884          */
1885         cpt2 = lnet_cpt_of_nid_locked(&best_lpni->lpni_nid, best_ni);
1886         if (sd->sd_cpt != cpt2) {
1887                 __u32 seq = lnet_get_dlc_seq_locked();
1888                 lnet_net_unlock(sd->sd_cpt);
1889                 sd->sd_cpt = cpt2;
1890                 lnet_net_lock(sd->sd_cpt);
1891                 if (seq != lnet_get_dlc_seq_locked()) {
1892                         lnet_peer_ni_decref_locked(best_lpni);
1893                         return REPEAT_SEND;
1894                 }
1895         }
1896
1897         /*
1898          * store the best_lpni in the message right away to avoid having
1899          * to do the same operation under different conditions
1900          */
1901         msg->msg_txpeer = best_lpni;
1902         msg->msg_txni = best_ni;
1903
1904         /*
1905          * grab a reference for the best_ni since now it's in use in this
1906          * send. The reference will be dropped in lnet_finalize()
1907          */
1908         lnet_ni_addref_locked(msg->msg_txni, sd->sd_cpt);
1909
1910         /*
1911          * Always set the target.nid to the best peer picked. Either the
1912          * NID will be one of the peer NIDs selected, or the same NID as
1913          * what was originally set in the target or it will be the NID of
1914          * a router if this message should be routed
1915          */
1916         msg->msg_target.nid = msg->msg_txpeer->lpni_nid;
1917
1918         /*
1919          * lnet_msg_commit assigns the correct cpt to the message, which
1920          * is used to decrement the correct refcount on the ni when it's
1921          * time to return the credits
1922          */
1923         lnet_msg_commit(msg, sd->sd_cpt);
1924
1925         /*
1926          * If we are routing the message then we keep the src_nid that was
1927          * set by the originator. If we are not routing then we are the
1928          * originator and set it here.
1929          */
1930         if (!msg->msg_routing)
1931                 msg->msg_hdr.src_nid = msg->msg_txni->ni_nid;
1932
1933         if (routing) {
1934                 msg->msg_target_is_router = 1;
1935                 msg->msg_target.pid = LNET_PID_LUSTRE;
1936                 /*
1937                  * since we're routing we want to ensure that the
1938                  * msg_hdr.dest_nid is set to the final destination. When
1939                  * the router receives this message it knows how to route
1940                  * it.
1941                  *
1942                  * final_dst_lpni is set at the beginning of the
1943                  * lnet_select_pathway() function and is never changed.
1944                  * It's safe to use it here.
1945                  */
1946                 final_dst_lpni->lpni_peer_net->lpn_peer->lp_send_seq++;
1947                 final_dst_lpni->lpni_peer_net->lpn_seq =
1948                         final_dst_lpni->lpni_peer_net->lpn_peer->lp_send_seq;
1949                 final_dst_lpni->lpni_seq =
1950                         final_dst_lpni->lpni_peer_net->lpn_seq;
1951                 msg->msg_hdr.dest_nid = final_dst_lpni->lpni_nid;
1952         } else {
1953                 /*
1954                  * if we're not routing set the dest_nid to the best peer
1955                  * ni NID that we picked earlier in the algorithm.
1956                  */
1957                 msg->msg_hdr.dest_nid = msg->msg_txpeer->lpni_nid;
1958         }
1959
1960         /*
1961          * if we have response tracker block update it with the next hop
1962          * nid
1963          */
1964         if (msg->msg_md) {
1965                 rspt = msg->msg_md->md_rspt_ptr;
1966                 if (rspt) {
1967                         rspt->rspt_next_hop_nid =
1968                                 msg->msg_txpeer->lpni_nid;
1969                         CDEBUG(D_NET, "rspt_next_hop_nid = %s\n",
1970                                libcfs_nidstr(&rspt->rspt_next_hop_nid));
1971                 }
1972         }
1973
1974         rc = lnet_post_send_locked(msg, 0);
1975
1976         if (!rc)
1977                 CDEBUG(D_NET, "TRACE: %s(%s:%s) -> %s(%s:%s) %s : %s try# %d\n",
1978                        libcfs_nidstr(&msg->msg_hdr.src_nid),
1979                        libcfs_nidstr(&msg->msg_txni->ni_nid),
1980                        libcfs_nidstr(&sd->sd_src_nid),
1981                        libcfs_nidstr(&msg->msg_hdr.dest_nid),
1982                        libcfs_nidstr(&sd->sd_dst_nid),
1983                        libcfs_nidstr(&msg->msg_txpeer->lpni_nid),
1984                        libcfs_nidstr(&sd->sd_rtr_nid),
1985                        lnet_msgtyp2str(msg->msg_type), msg->msg_retry_count);
1986
1987         return rc;
1988 }
1989
1990 static inline void
1991 lnet_set_non_mr_pref_nid(struct lnet_peer_ni *lpni, struct lnet_ni *lni,
1992                          struct lnet_msg *msg)
1993 {
1994         if (!lnet_peer_is_multi_rail(lpni->lpni_peer_net->lpn_peer) &&
1995             !lnet_msg_is_response(msg) && lpni->lpni_pref_nnids == 0) {
1996                 CDEBUG(D_NET, "Setting preferred local NID %s on NMR peer %s\n",
1997                        libcfs_nidstr(&lni->ni_nid),
1998                        libcfs_nidstr(&lpni->lpni_nid));
1999                 lnet_peer_ni_set_non_mr_pref_nid(lpni, &lni->ni_nid);
2000         }
2001 }
2002
2003 /*
2004  * Source Specified
2005  * Local Destination
2006  * non-mr peer
2007  *
2008  * use the source and destination NIDs as the pathway
2009  */
2010 static int
2011 lnet_handle_spec_local_nmr_dst(struct lnet_send_data *sd)
2012 {
2013         /* the destination lpni is set before we get here. */
2014
2015         /* find local NI */
2016         sd->sd_best_ni = lnet_nid_to_ni_locked(&sd->sd_src_nid, sd->sd_cpt);
2017         if (!sd->sd_best_ni) {
2018                 CERROR("Can't send to %s: src %s is not a local nid\n",
2019                        libcfs_nidstr(&sd->sd_dst_nid),
2020                        libcfs_nidstr(&sd->sd_src_nid));
2021                 return -EINVAL;
2022         }
2023
2024         lnet_set_non_mr_pref_nid(sd->sd_best_lpni, sd->sd_best_ni, sd->sd_msg);
2025
2026         return lnet_handle_send(sd);
2027 }
2028
2029 /*
2030  * Source Specified
2031  * Local Destination
2032  * MR Peer
2033  *
2034  * Don't run the selection algorithm on the peer NIs. By specifying the
2035  * local NID, we're also saying that we should always use the destination NID
2036  * provided. This handles the case where we should be using the same
2037  * destination NID for the all the messages which belong to the same RPC
2038  * request.
2039  */
2040 static int
2041 lnet_handle_spec_local_mr_dst(struct lnet_send_data *sd)
2042 {
2043         sd->sd_best_ni = lnet_nid_to_ni_locked(&sd->sd_src_nid, sd->sd_cpt);
2044         if (!sd->sd_best_ni) {
2045                 CERROR("Can't send to %s: src %s is not a local nid\n",
2046                        libcfs_nidstr(&sd->sd_dst_nid),
2047                        libcfs_nidstr(&sd->sd_src_nid));
2048                 return -EINVAL;
2049         }
2050
2051         if (sd->sd_best_lpni &&
2052             nid_same(&sd->sd_best_lpni->lpni_nid,
2053                       &the_lnet.ln_loni->ni_nid))
2054                 return lnet_handle_lo_send(sd);
2055         else if (sd->sd_best_lpni)
2056                 return lnet_handle_send(sd);
2057
2058         CERROR("can't send to %s. no NI on %s\n",
2059                libcfs_nidstr(&sd->sd_dst_nid),
2060                libcfs_net2str(sd->sd_best_ni->ni_net->net_id));
2061
2062         return -EHOSTUNREACH;
2063 }
2064
2065 struct lnet_ni *
2066 lnet_find_best_ni_on_spec_net(struct lnet_ni *cur_best_ni,
2067                               struct lnet_peer *peer,
2068                               struct lnet_peer_net *peer_net,
2069                               struct lnet_msg *msg,
2070                               int cpt)
2071 {
2072         struct lnet_net *local_net;
2073         struct lnet_ni *best_ni;
2074
2075         local_net = lnet_get_net_locked(peer_net->lpn_net_id);
2076         if (!local_net)
2077                 return NULL;
2078
2079         /*
2080          * Iterate through the NIs in this local Net and select
2081          * the NI to send from. The selection is determined by
2082          * these 3 criterion in the following priority:
2083          *      1. NUMA
2084          *      2. NI available credits
2085          *      3. Round Robin
2086          */
2087         best_ni = lnet_get_best_ni(local_net, cur_best_ni,
2088                                    peer, peer_net, msg, cpt);
2089
2090         return best_ni;
2091 }
2092
2093 static int
2094 lnet_initiate_peer_discovery(struct lnet_peer_ni *lpni, struct lnet_msg *msg,
2095                              int cpt)
2096 {
2097         struct lnet_peer *peer;
2098         struct lnet_peer_ni *new_lpni;
2099         int rc;
2100
2101         lnet_peer_ni_addref_locked(lpni);
2102
2103         peer = lpni->lpni_peer_net->lpn_peer;
2104
2105         if (lnet_peer_gw_discovery(peer)) {
2106                 lnet_peer_ni_decref_locked(lpni);
2107                 return 0;
2108         }
2109
2110         if (!lnet_msg_discovery(msg) || lnet_peer_is_uptodate(peer)) {
2111                 lnet_peer_ni_decref_locked(lpni);
2112                 return 0;
2113         }
2114
2115         rc = lnet_discover_peer_locked(lpni, cpt, false);
2116         if (rc) {
2117                 lnet_peer_ni_decref_locked(lpni);
2118                 return rc;
2119         }
2120
2121         new_lpni = lnet_peer_ni_find_locked(&lpni->lpni_nid);
2122         if (!new_lpni) {
2123                 lnet_peer_ni_decref_locked(lpni);
2124                 return -ENOENT;
2125         }
2126
2127         peer = new_lpni->lpni_peer_net->lpn_peer;
2128         spin_lock(&peer->lp_lock);
2129         if (lpni == new_lpni && lnet_peer_is_uptodate_locked(peer)) {
2130                 /* The peer NI did not change and the peer is up to date.
2131                  * Nothing more to do.
2132                  */
2133                 spin_unlock(&peer->lp_lock);
2134                 lnet_peer_ni_decref_locked(lpni);
2135                 lnet_peer_ni_decref_locked(new_lpni);
2136                 return 0;
2137         }
2138         spin_unlock(&peer->lp_lock);
2139
2140         /* Either the peer NI changed during discovery, or the peer isn't up
2141          * to date. In both cases we want to queue the message on the
2142          * (possibly new) peer's pending queue and queue the peer for discovery
2143          */
2144         msg->msg_sending = 0;
2145         msg->msg_txpeer = NULL;
2146         lnet_net_unlock(cpt);
2147         lnet_peer_queue_message(peer, msg);
2148         lnet_net_lock(cpt);
2149
2150         lnet_peer_ni_decref_locked(lpni);
2151         lnet_peer_ni_decref_locked(new_lpni);
2152
2153         CDEBUG(D_NET, "msg %p delayed. %s pending discovery\n",
2154                msg, libcfs_nidstr(&peer->lp_primary_nid));
2155
2156         return LNET_DC_WAIT;
2157 }
2158
2159 static int
2160 lnet_handle_find_routed_path(struct lnet_send_data *sd,
2161                              struct lnet_nid *dst_nid,
2162                              struct lnet_peer_ni **gw_lpni,
2163                              struct lnet_peer **gw_peer)
2164 {
2165         int rc;
2166         struct lnet_peer *gw;
2167         struct lnet_peer *lp;
2168         struct lnet_peer_net *lpn;
2169         struct lnet_peer_net *best_lpn = NULL;
2170         struct lnet_remotenet *rnet, *best_rnet = NULL;
2171         struct lnet_route *best_route = NULL;
2172         struct lnet_route *last_route = NULL;
2173         struct lnet_peer_ni *lpni = NULL;
2174         struct lnet_peer_ni *gwni = NULL;
2175         bool route_found = false;
2176         struct lnet_nid *src_nid =
2177                 !LNET_NID_IS_ANY(&sd->sd_src_nid) || !sd->sd_best_ni
2178                 ? &sd->sd_src_nid
2179                 : &sd->sd_best_ni->ni_nid;
2180         int best_lpn_healthv = 0;
2181         __u32 best_lpn_sel_prio = LNET_MAX_SELECTION_PRIORITY;
2182
2183         CDEBUG(D_NET, "%s route (%s) from local NI %s to destination %s\n",
2184                LNET_NID_IS_ANY(&sd->sd_rtr_nid) ? "Lookup" : "Specified",
2185                libcfs_nidstr(&sd->sd_rtr_nid), libcfs_nidstr(src_nid),
2186                libcfs_nidstr(&sd->sd_dst_nid));
2187
2188         /* If a router nid was specified then we are replying to a GET or
2189          * sending an ACK. In this case we use the gateway associated with the
2190          * specified router nid.
2191          */
2192         if (!LNET_NID_IS_ANY(&sd->sd_rtr_nid)) {
2193                 gwni = lnet_peer_ni_find_locked(&sd->sd_rtr_nid);
2194                 if (gwni) {
2195                         gw = gwni->lpni_peer_net->lpn_peer;
2196                         lnet_peer_ni_decref_locked(gwni);
2197                         if (gw->lp_rtr_refcount)
2198                                 route_found = true;
2199                 } else {
2200                         CWARN("No peer NI for gateway %s. Attempting to find an alternative route.\n",
2201                               libcfs_nidstr(&sd->sd_rtr_nid));
2202                 }
2203         }
2204
2205         if (!route_found) {
2206                 if (sd->sd_msg->msg_routing || !LNET_NID_IS_ANY(src_nid)) {
2207                         /* If I'm routing this message then I need to find the
2208                          * next hop based on the destination NID
2209                          *
2210                          * We also find next hop based on the destination NID
2211                          * if the source NI was specified
2212                          */
2213                         best_rnet = lnet_find_rnet_locked(LNET_NID_NET(&sd->sd_dst_nid));
2214                         if (!best_rnet) {
2215                                 CERROR("Unable to send message from %s to %s - Route table may be misconfigured\n",
2216                                        (src_nid && LNET_NID_IS_ANY(src_nid)) ?
2217                                                 "any local NI" :
2218                                                 libcfs_nidstr(src_nid),
2219                                        libcfs_nidstr(&sd->sd_dst_nid));
2220                                 return -EHOSTUNREACH;
2221                         }
2222                         CDEBUG(D_NET, "best_rnet %s\n",
2223                                libcfs_net2str(best_rnet->lrn_net));
2224                 } else {
2225                         /* we've already looked up the initial lpni using
2226                          * dst_nid
2227                          */
2228                         lpni = sd->sd_best_lpni;
2229                         /* the peer tree must be in existence */
2230                         LASSERT(lpni && lpni->lpni_peer_net &&
2231                                 lpni->lpni_peer_net->lpn_peer);
2232                         lp = lpni->lpni_peer_net->lpn_peer;
2233
2234                         list_for_each_entry(lpn, &lp->lp_peer_nets, lpn_peer_nets) {
2235                                 /* is this remote network reachable?  */
2236                                 rnet = lnet_find_rnet_locked(lpn->lpn_net_id);
2237                                 if (!rnet)
2238                                         continue;
2239
2240                                 if (!best_lpn)
2241                                         goto use_lpn;
2242                                 else
2243                                         CDEBUG(D_NET, "n[%s, %s] h[%d, %d], p[%u, %u], s[%d, %d]\n",
2244                                                libcfs_net2str(lpn->lpn_net_id),
2245                                                libcfs_net2str(best_lpn->lpn_net_id),
2246                                                lpn->lpn_healthv,
2247                                                best_lpn->lpn_healthv,
2248                                                lpn->lpn_sel_priority,
2249                                                best_lpn->lpn_sel_priority,
2250                                                lpn->lpn_seq,
2251                                                best_lpn->lpn_seq);
2252
2253                                 /* select the preferred peer net */
2254                                 if (best_lpn_healthv > lpn->lpn_healthv)
2255                                         continue;
2256                                 else if (best_lpn_healthv < lpn->lpn_healthv)
2257                                         goto use_lpn;
2258
2259                                 if (best_lpn_sel_prio < lpn->lpn_sel_priority)
2260                                         continue;
2261                                 else if (best_lpn_sel_prio > lpn->lpn_sel_priority)
2262                                         goto use_lpn;
2263
2264                                 if (best_lpn->lpn_seq <= lpn->lpn_seq)
2265                                         continue;
2266 use_lpn:
2267                                 best_lpn_healthv = lpn->lpn_healthv;
2268                                 best_lpn_sel_prio = lpn->lpn_sel_priority;
2269                                 best_lpn = lpn;
2270                                 best_rnet = rnet;
2271                         }
2272
2273                         if (!best_lpn) {
2274                                 CERROR("peer %s has no available nets\n",
2275                                        libcfs_nidstr(&sd->sd_dst_nid));
2276                                 return -EHOSTUNREACH;
2277                         }
2278
2279                         CDEBUG(D_NET, "selected best_lpn %s\n",
2280                                libcfs_net2str(best_lpn->lpn_net_id));
2281
2282                         sd->sd_best_lpni = lnet_find_best_lpni(sd->sd_best_ni,
2283                                                                lnet_nid_to_nid4(&sd->sd_dst_nid),
2284                                                                lp,
2285                                                                best_lpn->lpn_net_id);
2286                         if (!sd->sd_best_lpni) {
2287                                 CERROR("peer %s is unreachable\n",
2288                                        libcfs_nidstr(&sd->sd_dst_nid));
2289                                 return -EHOSTUNREACH;
2290                         }
2291
2292                         /* We're attempting to round robin over the remote peer
2293                          * NI's so update the final destination we selected
2294                          */
2295                         sd->sd_final_dst_lpni = sd->sd_best_lpni;
2296                 }
2297
2298                 /*
2299                  * find the best route. Restrict the selection on the net of the
2300                  * local NI if we've already picked the local NI to send from.
2301                  * Otherwise, let's pick any route we can find and then find
2302                  * a local NI we can reach the route's gateway on. Any route we
2303                  * select will be reachable by virtue of the restriction we have
2304                  * when adding a route.
2305                  */
2306                 best_route = lnet_find_route_locked(best_rnet,
2307                                                     LNET_NID_NET(src_nid),
2308                                                     sd->sd_best_lpni,
2309                                                     &last_route, &gwni);
2310
2311                 if (!best_route) {
2312                         CERROR("no route to %s from %s\n",
2313                                libcfs_nidstr(dst_nid),
2314                                libcfs_nidstr(src_nid));
2315                         return -EHOSTUNREACH;
2316                 }
2317
2318                 if (!gwni) {
2319                         CERROR("Internal Error. Route expected to %s from %s\n",
2320                                libcfs_nidstr(dst_nid),
2321                                libcfs_nidstr(src_nid));
2322                         return -EFAULT;
2323                 }
2324
2325                 gw = best_route->lr_gateway;
2326                 LASSERT(gw == gwni->lpni_peer_net->lpn_peer);
2327         }
2328
2329         /*
2330          * If the router checker is not active then discover the gateway here.
2331          * This ensures we are able to take advantage of multi-rail routing, but
2332          * if the router checker is active then we do not unecessarily delay
2333          * messages while the gateway is being checked by the dedicated monitor
2334          * thread.
2335          *
2336          * NB: We're only checking the alive_router_check_interval here, rather
2337          * than calling lnet_router_checker_active(), because the other
2338          * conditions that are checked by that function are either
2339          * irrelevant (the_lnet.ln_routing) or must be true (list of routers
2340          * is not empty)
2341          */
2342         if (alive_router_check_interval <= 0) {
2343                 rc = lnet_initiate_peer_discovery(gwni, sd->sd_msg, sd->sd_cpt);
2344                 if (rc)
2345                         return rc;
2346         }
2347
2348         if (!sd->sd_best_ni) {
2349                 lpn = gwni->lpni_peer_net;
2350                 sd->sd_best_ni = lnet_find_best_ni_on_spec_net(NULL, gw, lpn,
2351                                                                sd->sd_msg,
2352                                                                sd->sd_md_cpt);
2353                 if (!sd->sd_best_ni) {
2354                         CERROR("Internal Error. Expected local ni on %s but non found: %s\n",
2355                                libcfs_net2str(lpn->lpn_net_id),
2356                                libcfs_nidstr(&sd->sd_src_nid));
2357                         return -EFAULT;
2358                 }
2359         }
2360
2361         *gw_lpni = gwni;
2362         *gw_peer = gw;
2363
2364         /*
2365          * increment the sequence number since now we're sure we're
2366          * going to use this route
2367          */
2368         if (LNET_NID_IS_ANY(&sd->sd_rtr_nid)) {
2369                 LASSERT(best_route && last_route);
2370                 best_route->lr_seq = last_route->lr_seq + 1;
2371         }
2372
2373         return 0;
2374 }
2375
2376 /*
2377  * Handle two cases:
2378  *
2379  * Case 1:
2380  *  Source specified
2381  *  Remote destination
2382  *  Non-MR destination
2383  *
2384  * Case 2:
2385  *  Source specified
2386  *  Remote destination
2387  *  MR destination
2388  *
2389  * The handling of these two cases is similar. Even though the destination
2390  * can be MR or non-MR, we'll deal directly with the router.
2391  */
2392 static int
2393 lnet_handle_spec_router_dst(struct lnet_send_data *sd)
2394 {
2395         int rc;
2396         struct lnet_peer_ni *gw_lpni = NULL;
2397         struct lnet_peer *gw_peer = NULL;
2398
2399         /* find local NI */
2400         sd->sd_best_ni = lnet_nid_to_ni_locked(&sd->sd_src_nid, sd->sd_cpt);
2401         if (!sd->sd_best_ni) {
2402                 CERROR("Can't send to %s: src %s is not a local nid\n",
2403                        libcfs_nidstr(&sd->sd_dst_nid),
2404                        libcfs_nidstr(&sd->sd_src_nid));
2405                 return -EINVAL;
2406         }
2407
2408         rc = lnet_handle_find_routed_path(sd, &sd->sd_dst_nid,
2409                                           &gw_lpni, &gw_peer);
2410         if (rc)
2411                 return rc;
2412
2413         if (sd->sd_send_case & NMR_DST)
2414                 /*
2415                  * since the final destination is non-MR let's set its preferred
2416                  * NID before we send
2417                  */
2418                 lnet_set_non_mr_pref_nid(sd->sd_best_lpni, sd->sd_best_ni,
2419                                          sd->sd_msg);
2420
2421         /*
2422          * We're going to send to the gw found so let's set its
2423          * info
2424          */
2425         sd->sd_peer = gw_peer;
2426         sd->sd_best_lpni = gw_lpni;
2427
2428         return lnet_handle_send(sd);
2429 }
2430
2431 struct lnet_ni *
2432 lnet_find_best_ni_on_local_net(struct lnet_peer *peer, int md_cpt,
2433                                struct lnet_msg *msg, bool discovery)
2434 {
2435         struct lnet_peer_net *lpn = NULL;
2436         struct lnet_peer_net *best_lpn = NULL;
2437         struct lnet_net *net = NULL;
2438         struct lnet_net *best_net = NULL;
2439         struct lnet_ni *best_ni = NULL;
2440         int best_lpn_healthv = 0;
2441         int best_net_healthv = 0;
2442         int net_healthv;
2443         __u32 best_lpn_sel_prio = LNET_MAX_SELECTION_PRIORITY;
2444         __u32 lpn_sel_prio;
2445         __u32 best_net_sel_prio = LNET_MAX_SELECTION_PRIORITY;
2446         __u32 net_sel_prio;
2447
2448         /* If lp_disc_net_id is set, this peer is a router undergoing
2449          * discovery, and this message is an LNet ping, then this may be a
2450          * discovery message and we need to select an NI on the peer net
2451          * specified by lp_disc_net_id
2452          */
2453         if (peer->lp_disc_net_id &&
2454             (peer->lp_state & LNET_PEER_RTR_DISCOVERY) &&
2455             lnet_msg_is_ping(msg)) {
2456                 best_lpn = lnet_peer_get_net_locked(peer, peer->lp_disc_net_id);
2457                 if (best_lpn && lnet_get_net_locked(best_lpn->lpn_net_id))
2458                         goto select_best_ni;
2459         }
2460
2461         /*
2462          * The peer can have multiple interfaces, some of them can be on
2463          * the local network and others on a routed network. We should
2464          * prefer the local network. However if the local network is not
2465          * available then we need to try the routed network
2466          */
2467
2468         /* go through all the peer nets and find the best_ni */
2469         list_for_each_entry(lpn, &peer->lp_peer_nets, lpn_peer_nets) {
2470                 /*
2471                  * The peer's list of nets can contain non-local nets. We
2472                  * want to only examine the local ones.
2473                  */
2474                 net = lnet_get_net_locked(lpn->lpn_net_id);
2475                 if (!net)
2476                         continue;
2477
2478                 lpn_sel_prio = lpn->lpn_sel_priority;
2479                 net_healthv = lnet_get_net_healthv_locked(net);
2480                 net_sel_prio = net->net_sel_priority;
2481
2482                 if (!best_lpn)
2483                         goto select_lpn;
2484                 else
2485                         CDEBUG(D_NET,
2486                                "n[%s, %s] ph[%d, %d], pp[%u, %u], nh[%d, %d], np[%u, %u], ps[%u, %u], ns[%u, %u]\n",
2487                                libcfs_net2str(lpn->lpn_net_id),
2488                                libcfs_net2str(best_lpn->lpn_net_id),
2489                                lpn->lpn_healthv,
2490                                best_lpn_healthv,
2491                                lpn_sel_prio,
2492                                best_lpn_sel_prio,
2493                                net_healthv,
2494                                best_net_healthv,
2495                                net_sel_prio,
2496                                best_net_sel_prio,
2497                                lpn->lpn_seq,
2498                                best_lpn->lpn_seq,
2499                                net->net_seq,
2500                                best_net->net_seq);
2501
2502                 /* always select the lpn with the best health */
2503                 if (best_lpn_healthv > lpn->lpn_healthv)
2504                         continue;
2505                 else if (best_lpn_healthv < lpn->lpn_healthv)
2506                         goto select_lpn;
2507
2508                 /* select the preferred peer and local nets */
2509                 if (best_lpn_sel_prio < lpn_sel_prio)
2510                         continue;
2511                 else if (best_lpn_sel_prio > lpn_sel_prio)
2512                         goto select_lpn;
2513
2514                 if (best_net_healthv > net_healthv)
2515                         continue;
2516                 else if (best_net_healthv < net_healthv)
2517                         goto select_lpn;
2518
2519                 if (best_net_sel_prio < net_sel_prio)
2520                         continue;
2521                 else if (best_net_sel_prio > net_sel_prio)
2522                         goto select_lpn;
2523
2524                 if (best_lpn->lpn_seq < lpn->lpn_seq)
2525                         continue;
2526                 else if (best_lpn->lpn_seq > lpn->lpn_seq)
2527                         goto select_lpn;
2528
2529                 /* round robin over the local networks */
2530                 if (best_net->net_seq <= net->net_seq)
2531                         continue;
2532
2533 select_lpn:
2534                 best_net_healthv = net_healthv;
2535                 best_net_sel_prio = net_sel_prio;
2536                 best_lpn_healthv = lpn->lpn_healthv;
2537                 best_lpn_sel_prio = lpn_sel_prio;
2538                 best_lpn = lpn;
2539                 best_net = net;
2540         }
2541
2542         if (best_lpn) {
2543                 /* Select the best NI on the same net as best_lpn chosen
2544                  * above
2545                  */
2546 select_best_ni:
2547                 CDEBUG(D_NET, "selected best_lpn %s\n",
2548                        libcfs_net2str(best_lpn->lpn_net_id));
2549                 best_ni = lnet_find_best_ni_on_spec_net(NULL, peer, best_lpn,
2550                                                         msg, md_cpt);
2551         }
2552
2553         return best_ni;
2554 }
2555
2556 static struct lnet_ni *
2557 lnet_find_existing_preferred_best_ni(struct lnet_peer_ni *lpni, int cpt)
2558 {
2559         struct lnet_ni *best_ni = NULL;
2560         struct lnet_peer_net *peer_net = lpni->lpni_peer_net;
2561         struct lnet_peer_ni *lpni_entry;
2562
2563         /*
2564          * We must use a consistent source address when sending to a
2565          * non-MR peer. However, a non-MR peer can have multiple NIDs
2566          * on multiple networks, and we may even need to talk to this
2567          * peer on multiple networks -- certain types of
2568          * load-balancing configuration do this.
2569          *
2570          * So we need to pick the NI the peer prefers for this
2571          * particular network.
2572          */
2573         LASSERT(peer_net);
2574         list_for_each_entry(lpni_entry, &peer_net->lpn_peer_nis,
2575                             lpni_peer_nis) {
2576                 if (lpni_entry->lpni_pref_nnids == 0)
2577                         continue;
2578                 LASSERT(lpni_entry->lpni_pref_nnids == 1);
2579                 best_ni = lnet_nid_to_ni_locked(&lpni_entry->lpni_pref.nid,
2580                                                 cpt);
2581                 break;
2582         }
2583
2584         return best_ni;
2585 }
2586
2587 /* Prerequisite: sd->sd_peer and sd->sd_best_lpni should be set */
2588 static int
2589 lnet_select_preferred_best_ni(struct lnet_send_data *sd)
2590 {
2591         struct lnet_ni *best_ni = NULL;
2592
2593         /*
2594          * We must use a consistent source address when sending to a
2595          * non-MR peer. However, a non-MR peer can have multiple NIDs
2596          * on multiple networks, and we may even need to talk to this
2597          * peer on multiple networks -- certain types of
2598          * load-balancing configuration do this.
2599          *
2600          * So we need to pick the NI the peer prefers for this
2601          * particular network.
2602          *
2603          * An exception is traffic on LNET_RESERVED_PORTAL. Internal LNet
2604          * traffic doesn't care which source NI is used, and we don't actually
2605          * want to restrict local recovery pings to a single source NI.
2606          */
2607         if (!lnet_reserved_msg(sd->sd_msg))
2608                 best_ni = lnet_find_existing_preferred_best_ni(sd->sd_best_lpni,
2609                                                                sd->sd_cpt);
2610
2611         if (!best_ni)
2612                 best_ni = lnet_find_best_ni_on_spec_net(NULL, sd->sd_peer,
2613                                                 sd->sd_best_lpni->lpni_peer_net,
2614                                                 sd->sd_msg,
2615                                                 sd->sd_md_cpt);
2616
2617         /* If there is no best_ni we don't have a route */
2618         if (!best_ni) {
2619                 CERROR("no path to %s from net %s\n",
2620                         libcfs_nidstr(&sd->sd_best_lpni->lpni_nid),
2621                         libcfs_net2str(sd->sd_best_lpni->lpni_net->net_id));
2622                 return -EHOSTUNREACH;
2623         }
2624
2625         sd->sd_best_ni = best_ni;
2626
2627         /* Set preferred NI if necessary. */
2628         lnet_set_non_mr_pref_nid(sd->sd_best_lpni, sd->sd_best_ni, sd->sd_msg);
2629
2630         return 0;
2631 }
2632
2633
2634 /*
2635  * Source not specified
2636  * Local destination
2637  * Non-MR Peer
2638  *
2639  * always use the same source NID for NMR peers
2640  * If we've talked to that peer before then we already have a preferred
2641  * source NI associated with it. Otherwise, we select a preferred local NI
2642  * and store it in the peer
2643  */
2644 static int
2645 lnet_handle_any_local_nmr_dst(struct lnet_send_data *sd)
2646 {
2647         int rc = 0;
2648
2649         /* sd->sd_best_lpni is already set to the final destination */
2650
2651         /*
2652          * At this point we should've created the peer ni and peer. If we
2653          * can't find it, then something went wrong. Instead of assert
2654          * output a relevant message and fail the send
2655          */
2656         if (!sd->sd_best_lpni) {
2657                 CERROR("Internal fault. Unable to send msg %s to %s. NID not known\n",
2658                        lnet_msgtyp2str(sd->sd_msg->msg_type),
2659                        libcfs_nidstr(&sd->sd_dst_nid));
2660                 return -EFAULT;
2661         }
2662
2663         if (sd->sd_msg->msg_routing) {
2664                 /* If I'm forwarding this message then I can choose any NI
2665                  * on the destination peer net
2666                  */
2667                 sd->sd_best_ni = lnet_find_best_ni_on_spec_net(NULL,
2668                                                                sd->sd_peer,
2669                                                                sd->sd_best_lpni->lpni_peer_net,
2670                                                                sd->sd_msg,
2671                                                                sd->sd_md_cpt);
2672                 if (!sd->sd_best_ni) {
2673                         CERROR("Unable to forward message to %s. No local NI available\n",
2674                                libcfs_nidstr(&sd->sd_dst_nid));
2675                         rc = -EHOSTUNREACH;
2676                 }
2677         } else
2678                 rc = lnet_select_preferred_best_ni(sd);
2679
2680         if (!rc)
2681                 rc = lnet_handle_send(sd);
2682
2683         return rc;
2684 }
2685
2686 static int
2687 lnet_handle_any_mr_dsta(struct lnet_send_data *sd)
2688 {
2689         /*
2690          * NOTE we've already handled the remote peer case. So we only
2691          * need to worry about the local case here.
2692          *
2693          * if we're sending a response, ACK or reply, we need to send it
2694          * to the destination NID given to us. At this point we already
2695          * have the peer_ni we're suppose to send to, so just find the
2696          * best_ni on the peer net and use that. Since we're sending to an
2697          * MR peer then we can just run the selection algorithm on our
2698          * local NIs and pick the best one.
2699          */
2700         if (sd->sd_send_case & SND_RESP) {
2701                 sd->sd_best_ni =
2702                   lnet_find_best_ni_on_spec_net(NULL, sd->sd_peer,
2703                                                 sd->sd_best_lpni->lpni_peer_net,
2704                                                 sd->sd_msg,
2705                                                 sd->sd_md_cpt);
2706
2707                 if (!sd->sd_best_ni) {
2708                         /*
2709                          * We're not going to deal with not able to send
2710                          * a response to the provided final destination
2711                          */
2712                         CERROR("Can't send response to %s. No local NI available\n",
2713                                 libcfs_nidstr(&sd->sd_dst_nid));
2714                         return -EHOSTUNREACH;
2715                 }
2716
2717                 return lnet_handle_send(sd);
2718         }
2719
2720         /*
2721          * If we get here that means we're sending a fresh request, PUT or
2722          * GET, so we need to run our standard selection algorithm.
2723          * First find the best local interface that's on any of the peer's
2724          * networks.
2725          */
2726         sd->sd_best_ni = lnet_find_best_ni_on_local_net(sd->sd_peer,
2727                                         sd->sd_md_cpt,
2728                                         sd->sd_msg,
2729                                         lnet_msg_discovery(sd->sd_msg));
2730         if (sd->sd_best_ni) {
2731                 sd->sd_best_lpni =
2732                   lnet_find_best_lpni(sd->sd_best_ni,
2733                                              lnet_nid_to_nid4(&sd->sd_dst_nid),
2734                                       sd->sd_peer,
2735                                       sd->sd_best_ni->ni_net->net_id);
2736
2737                 /*
2738                  * if we're successful in selecting a peer_ni on the local
2739                  * network, then send to it. Otherwise fall through and
2740                  * try and see if we can reach it over another routed
2741                  * network
2742                  */
2743                 if (sd->sd_best_lpni &&
2744                     nid_same(&sd->sd_best_lpni->lpni_nid,
2745                              &the_lnet.ln_loni->ni_nid)) {
2746                         /*
2747                          * in case we initially started with a routed
2748                          * destination, let's reset to local
2749                          */
2750                         sd->sd_send_case &= ~REMOTE_DST;
2751                         sd->sd_send_case |= LOCAL_DST;
2752                         return lnet_handle_lo_send(sd);
2753                 } else if (sd->sd_best_lpni) {
2754                         /*
2755                          * in case we initially started with a routed
2756                          * destination, let's reset to local
2757                          */
2758                         sd->sd_send_case &= ~REMOTE_DST;
2759                         sd->sd_send_case |= LOCAL_DST;
2760                         return lnet_handle_send(sd);
2761                 }
2762
2763                 CERROR("Internal Error. Expected to have a best_lpni: "
2764                        "%s -> %s\n",
2765                        libcfs_nidstr(&sd->sd_src_nid),
2766                        libcfs_nidstr(&sd->sd_dst_nid));
2767
2768                 return -EFAULT;
2769         }
2770
2771         /*
2772          * Peer doesn't have a local network. Let's see if there is
2773          * a remote network we can reach it on.
2774          */
2775         return PASS_THROUGH;
2776 }
2777
2778 /*
2779  * Case 1:
2780  *      Source NID not specified
2781  *      Local destination
2782  *      MR peer
2783  *
2784  * Case 2:
2785  *      Source NID not speified
2786  *      Remote destination
2787  *      MR peer
2788  *
2789  * In both of these cases if we're sending a response, ACK or REPLY, then
2790  * we need to send to the destination NID provided.
2791  *
2792  * In the remote case let's deal with MR routers.
2793  *
2794  */
2795
2796 static int
2797 lnet_handle_any_mr_dst(struct lnet_send_data *sd)
2798 {
2799         int rc = 0;
2800         struct lnet_peer *gw_peer = NULL;
2801         struct lnet_peer_ni *gw_lpni = NULL;
2802
2803         /*
2804          * handle sending a response to a remote peer here so we don't
2805          * have to worry about it if we hit lnet_handle_any_mr_dsta()
2806          */
2807         if (sd->sd_send_case & REMOTE_DST &&
2808             sd->sd_send_case & SND_RESP) {
2809                 struct lnet_peer_ni *gw;
2810                 struct lnet_peer *gw_peer;
2811
2812                 rc = lnet_handle_find_routed_path(
2813                         sd, &sd->sd_dst_nid, &gw, &gw_peer);
2814                 if (rc < 0) {
2815                         CERROR("Can't send response to %s. No route available\n",
2816                                libcfs_nidstr(&sd->sd_dst_nid));
2817                         return -EHOSTUNREACH;
2818                 } else if (rc > 0) {
2819                         return rc;
2820                 }
2821
2822                 sd->sd_best_lpni = gw;
2823                 sd->sd_peer = gw_peer;
2824
2825                 return lnet_handle_send(sd);
2826         }
2827
2828         /*
2829          * Even though the NID for the peer might not be on a local network,
2830          * since the peer is MR there could be other interfaces on the
2831          * local network. In that case we'd still like to prefer the local
2832          * network over the routed network. If we're unable to do that
2833          * then we select the best router among the different routed networks,
2834          * and if the router is MR then we can deal with it as such.
2835          */
2836         rc = lnet_handle_any_mr_dsta(sd);
2837         if (rc != PASS_THROUGH)
2838                 return rc;
2839
2840         /*
2841          * Now that we must route to the destination, we must consider the
2842          * MR case, where the destination has multiple interfaces, some of
2843          * which we can route to and others we do not. For this reason we
2844          * need to select the destination which we can route to and if
2845          * there are multiple, we need to round robin.
2846          */
2847         rc = lnet_handle_find_routed_path(sd, &sd->sd_dst_nid,
2848                                           &gw_lpni, &gw_peer);
2849         if (rc)
2850                 return rc;
2851
2852         sd->sd_send_case &= ~LOCAL_DST;
2853         sd->sd_send_case |= REMOTE_DST;
2854
2855         sd->sd_peer = gw_peer;
2856         sd->sd_best_lpni = gw_lpni;
2857
2858         return lnet_handle_send(sd);
2859 }
2860
2861 /*
2862  * Source not specified
2863  * Remote destination
2864  * Non-MR peer
2865  *
2866  * Must send to the specified peer NID using the same source NID that
2867  * we've used before. If it's the first time to talk to that peer then
2868  * find the source NI and assign it as preferred to that peer
2869  */
2870 static int
2871 lnet_handle_any_router_nmr_dst(struct lnet_send_data *sd)
2872 {
2873         int rc;
2874         struct lnet_peer_ni *gw_lpni = NULL;
2875         struct lnet_peer *gw_peer = NULL;
2876
2877         /*
2878          * Let's see if we have a preferred NI to talk to this NMR peer
2879          */
2880         sd->sd_best_ni = lnet_find_existing_preferred_best_ni(sd->sd_best_lpni,
2881                                                               sd->sd_cpt);
2882
2883         /*
2884          * find the router and that'll find the best NI if we didn't find
2885          * it already.
2886          */
2887         rc = lnet_handle_find_routed_path(sd, &sd->sd_dst_nid, &gw_lpni,
2888                                           &gw_peer);
2889         if (rc)
2890                 return rc;
2891
2892         /*
2893          * set the best_ni we've chosen as the preferred one for
2894          * this peer
2895          */
2896         lnet_set_non_mr_pref_nid(sd->sd_best_lpni, sd->sd_best_ni, sd->sd_msg);
2897
2898         /* we'll be sending to the gw */
2899         sd->sd_best_lpni = gw_lpni;
2900         sd->sd_peer = gw_peer;
2901
2902         return lnet_handle_send(sd);
2903 }
2904
2905 static int
2906 lnet_handle_send_case_locked(struct lnet_send_data *sd)
2907 {
2908         /*
2909          * turn off the SND_RESP bit.
2910          * It will be checked in the case handling
2911          */
2912         __u32 send_case = sd->sd_send_case &= ~SND_RESP ;
2913
2914         CDEBUG(D_NET, "Source %s%s to %s %s %s destination\n",
2915                 (send_case & SRC_SPEC) ? "Specified: " : "ANY",
2916                 (send_case & SRC_SPEC) ? libcfs_nidstr(&sd->sd_src_nid) : "",
2917                 (send_case & MR_DST) ? "MR: " : "NMR: ",
2918                 libcfs_nidstr(&sd->sd_dst_nid),
2919                 (send_case & LOCAL_DST) ? "local" : "routed");
2920
2921         switch (send_case) {
2922         /*
2923          * For all cases where the source is specified, we should always
2924          * use the destination NID, whether it's an MR destination or not,
2925          * since we're continuing a series of related messages for the
2926          * same RPC
2927          */
2928         case SRC_SPEC_LOCAL_NMR_DST:
2929                 return lnet_handle_spec_local_nmr_dst(sd);
2930         case SRC_SPEC_LOCAL_MR_DST:
2931                 return lnet_handle_spec_local_mr_dst(sd);
2932         case SRC_SPEC_ROUTER_NMR_DST:
2933         case SRC_SPEC_ROUTER_MR_DST:
2934                 return lnet_handle_spec_router_dst(sd);
2935         case SRC_ANY_LOCAL_NMR_DST:
2936                 return lnet_handle_any_local_nmr_dst(sd);
2937         case SRC_ANY_LOCAL_MR_DST:
2938         case SRC_ANY_ROUTER_MR_DST:
2939                 return lnet_handle_any_mr_dst(sd);
2940         case SRC_ANY_ROUTER_NMR_DST:
2941                 return lnet_handle_any_router_nmr_dst(sd);
2942         default:
2943                 CERROR("Unknown send case\n");
2944                 return -1;
2945         }
2946 }
2947
2948 static int
2949 lnet_select_pathway(struct lnet_nid *src_nid,
2950                     struct lnet_nid *dst_nid,
2951                     struct lnet_msg *msg,
2952                     struct lnet_nid *rtr_nid)
2953 {
2954         struct lnet_peer_ni *lpni;
2955         struct lnet_peer *peer;
2956         struct lnet_send_data send_data;
2957         int cpt, rc;
2958         int md_cpt;
2959         __u32 send_case = 0;
2960         bool final_hop;
2961         bool mr_forwarding_allowed;
2962
2963         memset(&send_data, 0, sizeof(send_data));
2964
2965         /*
2966          * get an initial CPT to use for locking. The idea here is not to
2967          * serialize the calls to select_pathway, so that as many
2968          * operations can run concurrently as possible. To do that we use
2969          * the CPT where this call is being executed. Later on when we
2970          * determine the CPT to use in lnet_message_commit, we switch the
2971          * lock and check if there was any configuration change.  If none,
2972          * then we proceed, if there is, then we restart the operation.
2973          */
2974         cpt = lnet_net_lock_current();
2975
2976         md_cpt = lnet_cpt_of_md(msg->msg_md, msg->msg_offset);
2977         if (md_cpt == CFS_CPT_ANY)
2978                 md_cpt = cpt;
2979
2980 again:
2981
2982         /*
2983          * If we're being asked to send to the loopback interface, there
2984          * is no need to go through any selection. We can just shortcut
2985          * the entire process and send over lolnd
2986          */
2987         send_data.sd_msg = msg;
2988         send_data.sd_cpt = cpt;
2989         if (nid_is_lo0(dst_nid)) {
2990                 rc = lnet_handle_lo_send(&send_data);
2991                 lnet_net_unlock(cpt);
2992                 return rc;
2993         }
2994
2995         /*
2996          * find an existing peer_ni, or create one and mark it as having been
2997          * created due to network traffic. This call will create the
2998          * peer->peer_net->peer_ni tree.
2999          */
3000         lpni = lnet_peerni_by_nid_locked(dst_nid, NULL, cpt);
3001         if (IS_ERR(lpni)) {
3002                 lnet_net_unlock(cpt);
3003                 return PTR_ERR(lpni);
3004         }
3005
3006         /*
3007          * Cache the original src_nid and rtr_nid. If we need to resend the
3008          * message then we'll need to know whether the src_nid was originally
3009          * specified for this message. If it was originally specified,
3010          * then we need to keep using the same src_nid since it's
3011          * continuing the same sequence of messages. Similarly, rtr_nid will
3012          * affect our choice of next hop.
3013          */
3014         if (src_nid)
3015                 msg->msg_src_nid_param = *src_nid;
3016         else
3017                 msg->msg_src_nid_param = LNET_ANY_NID;
3018         if (rtr_nid)
3019                 msg->msg_rtr_nid_param = *rtr_nid;
3020         else
3021                 msg->msg_rtr_nid_param = LNET_ANY_NID;
3022
3023         /*
3024          * If necessary, perform discovery on the peer that owns this peer_ni.
3025          * Note, this can result in the ownership of this peer_ni changing
3026          * to another peer object.
3027          */
3028         rc = lnet_initiate_peer_discovery(lpni, msg, cpt);
3029         if (rc) {
3030                 lnet_peer_ni_decref_locked(lpni);
3031                 lnet_net_unlock(cpt);
3032                 return rc;
3033         }
3034         lnet_peer_ni_decref_locked(lpni);
3035
3036         peer = lpni->lpni_peer_net->lpn_peer;
3037
3038         /*
3039          * Identify the different send cases
3040          */
3041         if (!src_nid || LNET_NID_IS_ANY(src_nid)) {
3042                 send_case |= SRC_ANY;
3043                 if (lnet_get_net_locked(LNET_NID_NET(dst_nid)))
3044                         send_case |= LOCAL_DST;
3045                 else
3046                         send_case |= REMOTE_DST;
3047         } else {
3048                 send_case |= SRC_SPEC;
3049                 if (LNET_NID_NET(src_nid) == LNET_NID_NET(dst_nid))
3050                         send_case |= LOCAL_DST;
3051                 else
3052                         send_case |= REMOTE_DST;
3053         }
3054
3055         final_hop = false;
3056         if (msg->msg_routing && (send_case & LOCAL_DST))
3057                 final_hop = true;
3058
3059         /* Determine whether to allow MR forwarding for this message.
3060          * NB: MR forwarding is allowed if the message originator and the
3061          * destination are both MR capable, and the destination lpni that was
3062          * originally chosen by the originator is unhealthy or down.
3063          * We check the MR capability of the destination further below
3064          */
3065         mr_forwarding_allowed = false;
3066         if (final_hop) {
3067                 struct lnet_peer *src_lp;
3068                 struct lnet_peer_ni *src_lpni;
3069
3070                 src_lpni = lnet_peerni_by_nid_locked(&msg->msg_hdr.src_nid,
3071                                                    NULL, cpt);
3072                 /* We don't fail the send if we hit any errors here. We'll just
3073                  * try to send it via non-multi-rail criteria
3074                  */
3075                 if (!IS_ERR(src_lpni)) {
3076                         /* Drop ref taken by lnet_peerni_by_nid_locked() */
3077                         lnet_peer_ni_decref_locked(src_lpni);
3078                         src_lp = lpni->lpni_peer_net->lpn_peer;
3079                         if (lnet_peer_is_multi_rail(src_lp) &&
3080                             !lnet_is_peer_ni_alive(lpni))
3081                                 mr_forwarding_allowed = true;
3082
3083                 }
3084                 CDEBUG(D_NET, "msg %p MR forwarding %s\n", msg,
3085                        mr_forwarding_allowed ? "allowed" : "not allowed");
3086         }
3087
3088         /*
3089          * Deal with the peer as NMR in the following cases:
3090          * 1. the peer is NMR
3091          * 2. We're trying to recover a specific peer NI
3092          * 3. I'm a router sending to the final destination and MR forwarding is
3093          *    not allowed for this message (as determined above).
3094          *    In this case the source of the message would've
3095          *    already selected the final destination so my job
3096          *    is to honor the selection.
3097          */
3098         if (!lnet_peer_is_multi_rail(peer) || msg->msg_recovery ||
3099             (final_hop && !mr_forwarding_allowed))
3100                 send_case |= NMR_DST;
3101         else
3102                 send_case |= MR_DST;
3103
3104         if (lnet_msg_is_response(msg))
3105                 send_case |= SND_RESP;
3106
3107         /* assign parameters to the send_data */
3108         if (rtr_nid)
3109                 send_data.sd_rtr_nid = *rtr_nid;
3110         else
3111                 send_data.sd_rtr_nid = LNET_ANY_NID;
3112         if (src_nid)
3113                 send_data.sd_src_nid = *src_nid;
3114         else
3115                 send_data.sd_src_nid = LNET_ANY_NID;
3116         send_data.sd_dst_nid = *dst_nid;
3117         send_data.sd_best_lpni = lpni;
3118         /*
3119          * keep a pointer to the final destination in case we're going to
3120          * route, so we'll need to access it later
3121          */
3122         send_data.sd_final_dst_lpni = lpni;
3123         send_data.sd_peer = peer;
3124         send_data.sd_md_cpt = md_cpt;
3125         send_data.sd_send_case = send_case;
3126
3127         rc = lnet_handle_send_case_locked(&send_data);
3128
3129         /*
3130          * Update the local cpt since send_data.sd_cpt might've been
3131          * updated as a result of calling lnet_handle_send_case_locked().
3132          */
3133         cpt = send_data.sd_cpt;
3134
3135         if (rc == REPEAT_SEND)
3136                 goto again;
3137
3138         lnet_net_unlock(cpt);
3139
3140         return rc;
3141 }
3142
3143 int
3144 lnet_send(struct lnet_nid *src_nid, struct lnet_msg *msg,
3145           struct lnet_nid *rtr_nid)
3146 {
3147         struct lnet_nid *dst_nid = &msg->msg_target.nid;
3148         int rc;
3149
3150         /* NB: ni != NULL == interface pre-determined (ACK/REPLY) */
3151         LASSERT(msg->msg_txpeer == NULL);
3152         LASSERT(msg->msg_txni == NULL);
3153         LASSERT(!msg->msg_sending);
3154         LASSERT(!msg->msg_target_is_router);
3155         LASSERT(!msg->msg_receiving);
3156
3157         msg->msg_sending = 1;
3158
3159         LASSERT(!msg->msg_tx_committed);
3160
3161         rc = lnet_select_pathway(src_nid, dst_nid, msg, rtr_nid);
3162         if (rc < 0) {
3163                 if (rc == -EHOSTUNREACH)
3164                         msg->msg_health_status = LNET_MSG_STATUS_REMOTE_ERROR;
3165                 else
3166                         msg->msg_health_status = LNET_MSG_STATUS_LOCAL_ERROR;
3167                 return rc;
3168         }
3169
3170         if (rc == LNET_CREDIT_OK)
3171                 lnet_ni_send(msg->msg_txni, msg);
3172
3173         /* rc == LNET_CREDIT_OK or LNET_CREDIT_WAIT or LNET_DC_WAIT */
3174         return 0;
3175 }
3176
3177 enum lnet_mt_event_type {
3178         MT_TYPE_LOCAL_NI = 0,
3179         MT_TYPE_PEER_NI
3180 };
3181
3182 struct lnet_mt_event_info {
3183         enum lnet_mt_event_type mt_type;
3184         struct lnet_nid mt_nid;
3185 };
3186
3187 /* called with res_lock held */
3188 void
3189 lnet_detach_rsp_tracker(struct lnet_libmd *md, int cpt)
3190 {
3191         struct lnet_rsp_tracker *rspt;
3192
3193         /*
3194          * msg has a refcount on the MD so the MD is not going away.
3195          * The rspt queue for the cpt is protected by
3196          * the lnet_net_lock(cpt). cpt is the cpt of the MD cookie.
3197          */
3198         if (!md->md_rspt_ptr)
3199                 return;
3200
3201         rspt = md->md_rspt_ptr;
3202
3203         /* debug code */
3204         LASSERT(rspt->rspt_cpt == cpt);
3205
3206         md->md_rspt_ptr = NULL;
3207
3208         if (LNetMDHandleIsInvalid(rspt->rspt_mdh)) {
3209                 /*
3210                  * The monitor thread has invalidated this handle because the
3211                  * response timed out, but it failed to lookup the MD. That
3212                  * means this response tracker is on the zombie list. We can
3213                  * safely remove it under the resource lock (held by caller) and
3214                  * free the response tracker block.
3215                  */
3216                 list_del(&rspt->rspt_on_list);
3217                 lnet_rspt_free(rspt, cpt);
3218         } else {
3219                 /*
3220                  * invalidate the handle to indicate that a response has been
3221                  * received, which will then lead the monitor thread to clean up
3222                  * the rspt block.
3223                  */
3224                 LNetInvalidateMDHandle(&rspt->rspt_mdh);
3225         }
3226 }
3227
3228 void
3229 lnet_clean_zombie_rstqs(void)
3230 {
3231         struct lnet_rsp_tracker *rspt, *tmp;
3232         int i;
3233
3234         cfs_cpt_for_each(i, lnet_cpt_table()) {
3235                 list_for_each_entry_safe(rspt, tmp,
3236                                          the_lnet.ln_mt_zombie_rstqs[i],
3237                                          rspt_on_list) {
3238                         list_del(&rspt->rspt_on_list);
3239                         lnet_rspt_free(rspt, i);
3240                 }
3241         }
3242
3243         cfs_percpt_free(the_lnet.ln_mt_zombie_rstqs);
3244 }
3245
3246 static void
3247 lnet_finalize_expired_responses(void)
3248 {
3249         struct lnet_libmd *md;
3250         struct lnet_rsp_tracker *rspt, *tmp;
3251         ktime_t now;
3252         int i;
3253
3254         if (the_lnet.ln_mt_rstq == NULL)
3255                 return;
3256
3257         cfs_cpt_for_each(i, lnet_cpt_table()) {
3258                 LIST_HEAD(local_queue);
3259
3260                 lnet_net_lock(i);
3261                 if (!the_lnet.ln_mt_rstq[i]) {
3262                         lnet_net_unlock(i);
3263                         continue;
3264                 }
3265                 list_splice_init(the_lnet.ln_mt_rstq[i], &local_queue);
3266                 lnet_net_unlock(i);
3267
3268                 now = ktime_get();
3269
3270                 list_for_each_entry_safe(rspt, tmp, &local_queue, rspt_on_list) {
3271                         /*
3272                          * The rspt mdh will be invalidated when a response
3273                          * is received or whenever we want to discard the
3274                          * block the monitor thread will walk the queue
3275                          * and clean up any rsts with an invalid mdh.
3276                          * The monitor thread will walk the queue until
3277                          * the first unexpired rspt block. This means that
3278                          * some rspt blocks which received their
3279                          * corresponding responses will linger in the
3280                          * queue until they are cleaned up eventually.
3281                          */
3282                         lnet_res_lock(i);
3283                         if (LNetMDHandleIsInvalid(rspt->rspt_mdh)) {
3284                                 lnet_res_unlock(i);
3285                                 list_del(&rspt->rspt_on_list);
3286                                 lnet_rspt_free(rspt, i);
3287                                 continue;
3288                         }
3289
3290                         if (ktime_compare(now, rspt->rspt_deadline) >= 0 ||
3291                             the_lnet.ln_mt_state == LNET_MT_STATE_SHUTDOWN) {
3292                                 struct lnet_peer_ni *lpni;
3293                                 struct lnet_nid nid;
3294
3295                                 md = lnet_handle2md(&rspt->rspt_mdh);
3296                                 if (!md) {
3297                                         /* MD has been queued for unlink, but
3298                                          * rspt hasn't been detached (Note we've
3299                                          * checked above that the rspt_mdh is
3300                                          * valid). Since we cannot lookup the MD
3301                                          * we're unable to detach the rspt
3302                                          * ourselves. Thus, move the rspt to the
3303                                          * zombie list where we'll wait for
3304                                          * either:
3305                                          *   1. The remaining operations on the
3306                                          *   MD to complete. In this case the
3307                                          *   final operation will result in
3308                                          *   lnet_msg_detach_md()->
3309                                          *   lnet_detach_rsp_tracker() where
3310                                          *   we will clean up this response
3311                                          *   tracker.
3312                                          *   2. LNet to shutdown. In this case
3313                                          *   we'll wait until after all LND Nets
3314                                          *   have shutdown and then we can
3315                                          *   safely free any remaining response
3316                                          *   tracker blocks on the zombie list.
3317                                          * Note: We need to hold the resource
3318                                          * lock when adding to the zombie list
3319                                          * because we may have concurrent access
3320                                          * with lnet_detach_rsp_tracker().
3321                                          */
3322                                         LNetInvalidateMDHandle(&rspt->rspt_mdh);
3323                                         list_move(&rspt->rspt_on_list,
3324                                                   the_lnet.ln_mt_zombie_rstqs[i]);
3325                                         lnet_res_unlock(i);
3326                                         continue;
3327                                 }
3328                                 LASSERT(md->md_rspt_ptr == rspt);
3329                                 md->md_rspt_ptr = NULL;
3330                                 lnet_res_unlock(i);
3331
3332                                 LNetMDUnlink(rspt->rspt_mdh);
3333
3334                                 nid = rspt->rspt_next_hop_nid;
3335
3336                                 list_del(&rspt->rspt_on_list);
3337                                 lnet_rspt_free(rspt, i);
3338
3339                                 /* If we're shutting down we just want to clean
3340                                  * up the rspt blocks
3341                                  */
3342                                 if (the_lnet.ln_mt_state == LNET_MT_STATE_SHUTDOWN)
3343                                         continue;
3344
3345                                 lnet_net_lock(i);
3346                                 the_lnet.ln_counters[i]->lct_health.lch_response_timeout_count++;
3347                                 lnet_net_unlock(i);
3348
3349                                 CDEBUG(D_NET,
3350                                        "Response timeout: md = %p: nid = %s\n",
3351                                        md, libcfs_nidstr(&nid));
3352
3353                                 /*
3354                                  * If there is a timeout on the response
3355                                  * from the next hop decrement its health
3356                                  * value so that we don't use it
3357                                  */
3358                                 lnet_net_lock(0);
3359                                 lpni = lnet_peer_ni_find_locked(&nid);
3360                                 if (lpni) {
3361                                         lnet_handle_remote_failure_locked(lpni);
3362                                         lnet_peer_ni_decref_locked(lpni);
3363                                 }
3364                                 lnet_net_unlock(0);
3365                         } else {
3366                                 lnet_res_unlock(i);
3367                                 break;
3368                         }
3369                 }
3370
3371                 if (!list_empty(&local_queue)) {
3372                         lnet_net_lock(i);
3373                         list_splice(&local_queue, the_lnet.ln_mt_rstq[i]);
3374                         lnet_net_unlock(i);
3375                 }
3376         }
3377 }
3378
3379 static void
3380 lnet_resend_pending_msgs_locked(struct list_head *resendq, int cpt)
3381 {
3382         struct lnet_msg *msg;
3383
3384         while (!list_empty(resendq)) {
3385                 struct lnet_peer_ni *lpni;
3386
3387                 msg = list_entry(resendq->next, struct lnet_msg,
3388                                  msg_list);
3389
3390                 list_del_init(&msg->msg_list);
3391
3392                 lpni = lnet_peer_ni_find_locked(&msg->msg_hdr.dest_nid);
3393                 if (!lpni) {
3394                         lnet_net_unlock(cpt);
3395                         CERROR("Expected that a peer is already created for %s\n",
3396                                libcfs_nidstr(&msg->msg_hdr.dest_nid));
3397                         msg->msg_no_resend = true;
3398                         lnet_finalize(msg, -EFAULT);
3399                         lnet_net_lock(cpt);
3400                 } else {
3401                         int rc;
3402
3403                         lnet_peer_ni_decref_locked(lpni);
3404
3405                         lnet_net_unlock(cpt);
3406                         CDEBUG(D_NET, "resending %s->%s: %s recovery %d try# %d\n",
3407                                libcfs_nidstr(&msg->msg_src_nid_param),
3408                                libcfs_idstr(&msg->msg_target),
3409                                lnet_msgtyp2str(msg->msg_type),
3410                                msg->msg_recovery,
3411                                msg->msg_retry_count);
3412                         rc = lnet_send(&msg->msg_src_nid_param, msg,
3413                                        &msg->msg_rtr_nid_param);
3414                         if (rc) {
3415                                 CERROR("Error sending %s to %s: %d\n",
3416                                        lnet_msgtyp2str(msg->msg_type),
3417                                        libcfs_idstr(&msg->msg_target), rc);
3418                                 msg->msg_no_resend = true;
3419                                 lnet_finalize(msg, rc);
3420                         }
3421                         lnet_net_lock(cpt);
3422                         if (!rc)
3423                                 the_lnet.ln_counters[cpt]->lct_health.lch_resend_count++;
3424                 }
3425         }
3426 }
3427
3428 static void
3429 lnet_resend_pending_msgs(void)
3430 {
3431         int i;
3432
3433         cfs_cpt_for_each(i, lnet_cpt_table()) {
3434                 lnet_net_lock(i);
3435                 lnet_resend_pending_msgs_locked(the_lnet.ln_mt_resendqs[i], i);
3436                 lnet_net_unlock(i);
3437         }
3438 }
3439
3440 /* called with cpt and ni_lock held */
3441 static void
3442 lnet_unlink_ni_recovery_mdh_locked(struct lnet_ni *ni, int cpt, bool force)
3443 {
3444         struct lnet_handle_md recovery_mdh;
3445
3446         LNetInvalidateMDHandle(&recovery_mdh);
3447
3448         if (ni->ni_recovery_state & LNET_NI_RECOVERY_PENDING ||
3449             force) {
3450                 recovery_mdh = ni->ni_ping_mdh;
3451                 LNetInvalidateMDHandle(&ni->ni_ping_mdh);
3452         }
3453         lnet_ni_unlock(ni);
3454         lnet_net_unlock(cpt);
3455         if (!LNetMDHandleIsInvalid(recovery_mdh))
3456                 LNetMDUnlink(recovery_mdh);
3457         lnet_net_lock(cpt);
3458         lnet_ni_lock(ni);
3459 }
3460
3461 static void
3462 lnet_recover_local_nis(void)
3463 {
3464         struct lnet_mt_event_info *ev_info;
3465         LIST_HEAD(processed_list);
3466         LIST_HEAD(local_queue);
3467         struct lnet_handle_md mdh;
3468         struct lnet_ni *tmp;
3469         struct lnet_ni *ni;
3470         struct lnet_nid nid;
3471         int healthv;
3472         int rc;
3473         time64_t now;
3474
3475         /*
3476          * splice the recovery queue on a local queue. We will iterate
3477          * through the local queue and update it as needed. Once we're
3478          * done with the traversal, we'll splice the local queue back on
3479          * the head of the ln_mt_localNIRecovq. Any newly added local NIs
3480          * will be traversed in the next iteration.
3481          */
3482         lnet_net_lock(0);
3483         list_splice_init(&the_lnet.ln_mt_localNIRecovq,
3484                          &local_queue);
3485         lnet_net_unlock(0);
3486
3487         now = ktime_get_seconds();
3488
3489         list_for_each_entry_safe(ni, tmp, &local_queue, ni_recovery) {
3490                 /*
3491                  * if an NI is being deleted or it is now healthy, there
3492                  * is no need to keep it around in the recovery queue.
3493                  * The monitor thread is the only thread responsible for
3494                  * removing the NI from the recovery queue.
3495                  * Multiple threads can be adding NIs to the recovery
3496                  * queue.
3497                  */
3498                 healthv = atomic_read(&ni->ni_healthv);
3499
3500                 lnet_net_lock(0);
3501                 lnet_ni_lock(ni);
3502                 if (ni->ni_state != LNET_NI_STATE_ACTIVE ||
3503                     healthv == LNET_MAX_HEALTH_VALUE) {
3504                         list_del_init(&ni->ni_recovery);
3505                         lnet_unlink_ni_recovery_mdh_locked(ni, 0, false);
3506                         lnet_ni_unlock(ni);
3507                         lnet_ni_decref_locked(ni, 0);
3508                         lnet_net_unlock(0);
3509                         continue;
3510                 }
3511
3512                 /*
3513                  * if the local NI failed recovery we must unlink the md.
3514                  * But we want to keep the local_ni on the recovery queue
3515                  * so we can continue the attempts to recover it.
3516                  */
3517                 if (ni->ni_recovery_state & LNET_NI_RECOVERY_FAILED) {
3518                         lnet_unlink_ni_recovery_mdh_locked(ni, 0, true);
3519                         ni->ni_recovery_state &= ~LNET_NI_RECOVERY_FAILED;
3520                 }
3521
3522
3523                 lnet_ni_unlock(ni);
3524
3525                 if (now < ni->ni_next_ping) {
3526                         lnet_net_unlock(0);
3527                         continue;
3528                 }
3529
3530                 lnet_net_unlock(0);
3531
3532                 CDEBUG(D_NET, "attempting to recover local ni: %s\n",
3533                        libcfs_nidstr(&ni->ni_nid));
3534
3535                 lnet_ni_lock(ni);
3536                 if (!(ni->ni_recovery_state & LNET_NI_RECOVERY_PENDING)) {
3537                         ni->ni_recovery_state |= LNET_NI_RECOVERY_PENDING;
3538                         lnet_ni_unlock(ni);
3539
3540                         LIBCFS_ALLOC(ev_info, sizeof(*ev_info));
3541                         if (!ev_info) {
3542                                 CERROR("out of memory. Can't recover %s\n",
3543                                        libcfs_nidstr(&ni->ni_nid));
3544                                 lnet_ni_lock(ni);
3545                                 ni->ni_recovery_state &=
3546                                   ~LNET_NI_RECOVERY_PENDING;
3547                                 lnet_ni_unlock(ni);
3548                                 continue;
3549                         }
3550
3551                         mdh = ni->ni_ping_mdh;
3552                         /*
3553                          * Invalidate the ni mdh in case it's deleted.
3554                          * We'll unlink the mdh in this case below.
3555                          */
3556                         LNetInvalidateMDHandle(&ni->ni_ping_mdh);
3557                         nid = ni->ni_nid;
3558
3559                         /*
3560                          * remove the NI from the local queue and drop the
3561                          * reference count to it while we're recovering
3562                          * it. The reason for that, is that the NI could
3563                          * be deleted, and the way the code is structured
3564                          * is if we don't drop the NI, then the deletion
3565                          * code will enter a loop waiting for the
3566                          * reference count to be removed while holding the
3567                          * ln_mutex_lock(). When we look up the peer to
3568                          * send to in lnet_select_pathway() we will try to
3569                          * lock the ln_mutex_lock() as well, leading to
3570                          * a deadlock. By dropping the refcount and
3571                          * removing it from the list, we allow for the NI
3572                          * to be removed, then we use the cached NID to
3573                          * look it up again. If it's gone, then we just
3574                          * continue examining the rest of the queue.
3575                          */
3576                         lnet_net_lock(0);
3577                         list_del_init(&ni->ni_recovery);
3578                         lnet_ni_decref_locked(ni, 0);
3579                         lnet_net_unlock(0);
3580
3581                         ev_info->mt_type = MT_TYPE_LOCAL_NI;
3582                         ev_info->mt_nid = nid;
3583                         rc = lnet_send_ping(&nid, &mdh, LNET_INTERFACES_MIN,
3584                                             ev_info, the_lnet.ln_mt_handler,
3585                                             true);
3586                         /* lookup the nid again */
3587                         lnet_net_lock(0);
3588                         ni = lnet_nid_to_ni_locked(&nid, 0);
3589                         if (!ni) {
3590                                 /*
3591                                  * the NI has been deleted when we dropped
3592                                  * the ref count
3593                                  */
3594                                 lnet_net_unlock(0);
3595                                 LNetMDUnlink(mdh);
3596                                 continue;
3597                         }
3598                         ni->ni_ping_count++;
3599
3600                         ni->ni_ping_mdh = mdh;
3601                         lnet_ni_add_to_recoveryq_locked(ni, &processed_list,
3602                                                         now);
3603
3604                         if (rc) {
3605                                 lnet_ni_lock(ni);
3606                                 ni->ni_recovery_state &= ~LNET_NI_RECOVERY_PENDING;
3607                                 lnet_ni_unlock(ni);
3608                         }
3609                         lnet_net_unlock(0);
3610                 } else
3611                         lnet_ni_unlock(ni);
3612         }
3613
3614         /*
3615          * put back the remaining NIs on the ln_mt_localNIRecovq to be
3616          * reexamined in the next iteration.
3617          */
3618         list_splice_init(&processed_list, &local_queue);
3619         lnet_net_lock(0);
3620         list_splice(&local_queue, &the_lnet.ln_mt_localNIRecovq);
3621         lnet_net_unlock(0);
3622 }
3623
3624 static int
3625 lnet_resendqs_create(void)
3626 {
3627         struct list_head **resendqs;
3628         resendqs = lnet_create_array_of_queues();
3629
3630         if (!resendqs)
3631                 return -ENOMEM;
3632
3633         lnet_net_lock(LNET_LOCK_EX);
3634         the_lnet.ln_mt_resendqs = resendqs;
3635         lnet_net_unlock(LNET_LOCK_EX);
3636
3637         return 0;
3638 }
3639
3640 static void
3641 lnet_clean_local_ni_recoveryq(void)
3642 {
3643         struct lnet_ni *ni;
3644
3645         /* This is only called when the monitor thread has stopped */
3646         lnet_net_lock(0);
3647
3648         while ((ni = list_first_entry_or_null(&the_lnet.ln_mt_localNIRecovq,
3649                                               struct lnet_ni,
3650                                               ni_recovery)) != NULL) {
3651                 list_del_init(&ni->ni_recovery);
3652                 lnet_ni_lock(ni);
3653                 lnet_unlink_ni_recovery_mdh_locked(ni, 0, true);
3654                 lnet_ni_unlock(ni);
3655                 lnet_ni_decref_locked(ni, 0);
3656         }
3657
3658         lnet_net_unlock(0);
3659 }
3660
3661 static void
3662 lnet_unlink_lpni_recovery_mdh_locked(struct lnet_peer_ni *lpni, int cpt,
3663                                      bool force)
3664 {
3665         struct lnet_handle_md recovery_mdh;
3666
3667         LNetInvalidateMDHandle(&recovery_mdh);
3668
3669         if (lpni->lpni_state & LNET_PEER_NI_RECOVERY_PENDING || force) {
3670                 recovery_mdh = lpni->lpni_recovery_ping_mdh;
3671                 LNetInvalidateMDHandle(&lpni->lpni_recovery_ping_mdh);
3672         }
3673         spin_unlock(&lpni->lpni_lock);
3674         lnet_net_unlock(cpt);
3675         if (!LNetMDHandleIsInvalid(recovery_mdh))
3676                 LNetMDUnlink(recovery_mdh);
3677         lnet_net_lock(cpt);
3678         spin_lock(&lpni->lpni_lock);
3679 }
3680
3681 static void
3682 lnet_clean_peer_ni_recoveryq(void)
3683 {
3684         struct lnet_peer_ni *lpni, *tmp;
3685
3686         lnet_net_lock(LNET_LOCK_EX);
3687
3688         list_for_each_entry_safe(lpni, tmp, &the_lnet.ln_mt_peerNIRecovq,
3689                                  lpni_recovery) {
3690                 list_del_init(&lpni->lpni_recovery);
3691                 spin_lock(&lpni->lpni_lock);
3692                 lnet_unlink_lpni_recovery_mdh_locked(lpni, LNET_LOCK_EX, true);
3693                 spin_unlock(&lpni->lpni_lock);
3694                 lnet_peer_ni_decref_locked(lpni);
3695         }
3696
3697         lnet_net_unlock(LNET_LOCK_EX);
3698 }
3699
3700 static void
3701 lnet_clean_resendqs(void)
3702 {
3703         struct lnet_msg *msg, *tmp;
3704         LIST_HEAD(msgs);
3705         int i;
3706
3707         cfs_cpt_for_each(i, lnet_cpt_table()) {
3708                 lnet_net_lock(i);
3709                 list_splice_init(the_lnet.ln_mt_resendqs[i], &msgs);
3710                 lnet_net_unlock(i);
3711                 list_for_each_entry_safe(msg, tmp, &msgs, msg_list) {
3712                         list_del_init(&msg->msg_list);
3713                         msg->msg_no_resend = true;
3714                         lnet_finalize(msg, -ESHUTDOWN);
3715                 }
3716         }
3717
3718         cfs_percpt_free(the_lnet.ln_mt_resendqs);
3719 }
3720
3721 static void
3722 lnet_recover_peer_nis(void)
3723 {
3724         struct lnet_mt_event_info *ev_info;
3725         LIST_HEAD(processed_list);
3726         LIST_HEAD(local_queue);
3727         struct lnet_handle_md mdh;
3728         struct lnet_peer_ni *lpni;
3729         struct lnet_peer_ni *tmp;
3730         struct lnet_nid nid;
3731         int healthv;
3732         int rc;
3733         time64_t now;
3734
3735         /*
3736          * Always use cpt 0 for locking across all interactions with
3737          * ln_mt_peerNIRecovq
3738          */
3739         lnet_net_lock(0);
3740         list_splice_init(&the_lnet.ln_mt_peerNIRecovq,
3741                          &local_queue);
3742         lnet_net_unlock(0);
3743
3744         now = ktime_get_seconds();
3745
3746         list_for_each_entry_safe(lpni, tmp, &local_queue,
3747                                  lpni_recovery) {
3748                 /*
3749                  * The same protection strategy is used here as is in the
3750                  * local recovery case.
3751                  */
3752                 lnet_net_lock(0);
3753                 healthv = atomic_read(&lpni->lpni_healthv);
3754                 spin_lock(&lpni->lpni_lock);
3755                 if (lpni->lpni_state & LNET_PEER_NI_DELETING ||
3756                     healthv == LNET_MAX_HEALTH_VALUE) {
3757                         list_del_init(&lpni->lpni_recovery);
3758                         lnet_unlink_lpni_recovery_mdh_locked(lpni, 0, false);
3759                         spin_unlock(&lpni->lpni_lock);
3760                         lnet_peer_ni_decref_locked(lpni);
3761                         lnet_net_unlock(0);
3762                         continue;
3763                 }
3764
3765                 /*
3766                  * If the peer NI has failed recovery we must unlink the
3767                  * md. But we want to keep the peer ni on the recovery
3768                  * queue so we can try to continue recovering it
3769                  */
3770                 if (lpni->lpni_state & LNET_PEER_NI_RECOVERY_FAILED) {
3771                         lnet_unlink_lpni_recovery_mdh_locked(lpni, 0, true);
3772                         lpni->lpni_state &= ~LNET_PEER_NI_RECOVERY_FAILED;
3773                 }
3774
3775                 spin_unlock(&lpni->lpni_lock);
3776
3777                 if (now < lpni->lpni_next_ping) {
3778                         lnet_net_unlock(0);
3779                         continue;
3780                 }
3781
3782                 lnet_net_unlock(0);
3783
3784                 /*
3785                  * NOTE: we're racing with peer deletion from user space.
3786                  * It's possible that a peer is deleted after we check its
3787                  * state. In this case the recovery can create a new peer
3788                  */
3789                 spin_lock(&lpni->lpni_lock);
3790                 if (!(lpni->lpni_state & LNET_PEER_NI_RECOVERY_PENDING) &&
3791                     !(lpni->lpni_state & LNET_PEER_NI_DELETING)) {
3792                         lpni->lpni_state |= LNET_PEER_NI_RECOVERY_PENDING;
3793                         spin_unlock(&lpni->lpni_lock);
3794
3795                         LIBCFS_ALLOC(ev_info, sizeof(*ev_info));
3796                         if (!ev_info) {
3797                                 CERROR("out of memory. Can't recover %s\n",
3798                                        libcfs_nidstr(&lpni->lpni_nid));
3799                                 spin_lock(&lpni->lpni_lock);
3800                                 lpni->lpni_state &= ~LNET_PEER_NI_RECOVERY_PENDING;
3801                                 spin_unlock(&lpni->lpni_lock);
3802                                 continue;
3803                         }
3804
3805                         /* look at the comments in lnet_recover_local_nis() */
3806                         mdh = lpni->lpni_recovery_ping_mdh;
3807                         nid = lpni->lpni_nid;
3808                         LNetInvalidateMDHandle(&lpni->lpni_recovery_ping_mdh);
3809                         lnet_net_lock(0);
3810                         list_del_init(&lpni->lpni_recovery);
3811                         lnet_peer_ni_decref_locked(lpni);
3812                         lnet_net_unlock(0);
3813
3814                         ev_info->mt_type = MT_TYPE_PEER_NI;
3815                         ev_info->mt_nid = nid;
3816                         rc = lnet_send_ping(&nid, &mdh, LNET_INTERFACES_MIN,
3817                                             ev_info, the_lnet.ln_mt_handler,
3818                                             true);
3819                         lnet_net_lock(0);
3820                         /*
3821                          * lnet_peer_ni_find_locked() grabs a refcount for
3822                          * us. No need to take it explicitly.
3823                          */
3824                         lpni = lnet_peer_ni_find_locked(&nid);
3825                         if (!lpni) {
3826                                 lnet_net_unlock(0);
3827                                 LNetMDUnlink(mdh);
3828                                 continue;
3829                         }
3830
3831                         lpni->lpni_ping_count++;
3832
3833                         lpni->lpni_recovery_ping_mdh = mdh;
3834
3835                         lnet_peer_ni_add_to_recoveryq_locked(lpni,
3836                                                              &processed_list,
3837                                                              now);
3838                         if (rc) {
3839                                 spin_lock(&lpni->lpni_lock);
3840                                 lpni->lpni_state &= ~LNET_PEER_NI_RECOVERY_PENDING;
3841                                 spin_unlock(&lpni->lpni_lock);
3842                         }
3843
3844                         /* Drop the ref taken by lnet_peer_ni_find_locked() */
3845                         lnet_peer_ni_decref_locked(lpni);
3846                         lnet_net_unlock(0);
3847                 } else
3848                         spin_unlock(&lpni->lpni_lock);
3849         }
3850
3851         list_splice_init(&processed_list, &local_queue);
3852         lnet_net_lock(0);
3853         list_splice(&local_queue, &the_lnet.ln_mt_peerNIRecovq);
3854         lnet_net_unlock(0);
3855 }
3856
3857 static int
3858 lnet_monitor_thread(void *arg)
3859 {
3860         time64_t rsp_timeout = 0;
3861         time64_t now;
3862
3863         wait_for_completion(&the_lnet.ln_started);
3864         /*
3865          * The monitor thread takes care of the following:
3866          *  1. Checks the aliveness of routers
3867          *  2. Checks if there are messages on the resend queue to resend
3868          *     them.
3869          *  3. Check if there are any NIs on the local recovery queue and
3870          *     pings them
3871          *  4. Checks if there are any NIs on the remote recovery queue
3872          *     and pings them.
3873          */
3874         while (the_lnet.ln_mt_state == LNET_MT_STATE_RUNNING) {
3875                 now = ktime_get_real_seconds();
3876
3877                 if (lnet_router_checker_active())
3878                         lnet_check_routers();
3879
3880                 lnet_resend_pending_msgs();
3881
3882                 if (now >= rsp_timeout) {
3883                         lnet_finalize_expired_responses();
3884                         rsp_timeout = now + (lnet_transaction_timeout / 2);
3885                 }
3886
3887                 lnet_recover_local_nis();
3888                 lnet_recover_peer_nis();
3889
3890                 /*
3891                  * TODO do we need to check if we should sleep without
3892                  * timeout?  Technically, an active system will always
3893                  * have messages in flight so this check will always
3894                  * evaluate to false. And on an idle system do we care
3895                  * if we wake up every 1 second? Although, we've seen
3896                  * cases where we get a complaint that an idle thread
3897                  * is waking up unnecessarily.
3898                  */
3899                 wait_for_completion_interruptible_timeout(
3900                         &the_lnet.ln_mt_wait_complete,
3901                         cfs_time_seconds(1));
3902                 /* Must re-init the completion before testing anything,
3903                  * including ln_mt_state.
3904                  */
3905                 reinit_completion(&the_lnet.ln_mt_wait_complete);
3906         }
3907
3908         /* Shutting down */
3909         lnet_net_lock(LNET_LOCK_EX);
3910         the_lnet.ln_mt_state = LNET_MT_STATE_SHUTDOWN;
3911         lnet_net_unlock(LNET_LOCK_EX);
3912
3913         /* signal that the monitor thread is exiting */
3914         up(&the_lnet.ln_mt_signal);
3915
3916         return 0;
3917 }
3918
3919 /*
3920  * lnet_send_ping
3921  * Sends a ping.
3922  * Returns == 0 if success
3923  * Returns > 0 if LNetMDBind or prior fails
3924  * Returns < 0 if LNetGet fails
3925  */
3926 int
3927 lnet_send_ping(struct lnet_nid *dest_nid,
3928                struct lnet_handle_md *mdh, int nnis,
3929                void *user_data, lnet_handler_t handler, bool recovery)
3930 {
3931         struct lnet_md md = { NULL };
3932         struct lnet_processid id;
3933         struct lnet_ping_buffer *pbuf;
3934         int rc;
3935
3936         if (LNET_NID_IS_ANY(dest_nid)) {
3937                 rc = -EHOSTUNREACH;
3938                 goto fail_error;
3939         }
3940
3941         pbuf = lnet_ping_buffer_alloc(nnis, GFP_NOFS);
3942         if (!pbuf) {
3943                 rc = ENOMEM;
3944                 goto fail_error;
3945         }
3946
3947         /* initialize md content */
3948         md.start     = &pbuf->pb_info;
3949         md.length    = LNET_PING_INFO_SIZE(nnis);
3950         md.threshold = 2; /* GET/REPLY */
3951         md.max_size  = 0;
3952         md.options   = LNET_MD_TRUNCATE | LNET_MD_TRACK_RESPONSE;
3953         md.user_ptr  = user_data;
3954         md.handler   = handler;
3955
3956         rc = LNetMDBind(&md, LNET_UNLINK, mdh);
3957         if (rc) {
3958                 lnet_ping_buffer_decref(pbuf);
3959                 CERROR("Can't bind MD: %d\n", rc);
3960                 rc = -rc; /* change the rc to positive */
3961                 goto fail_error;
3962         }
3963         id.pid = LNET_PID_LUSTRE;
3964         id.nid = *dest_nid;
3965
3966         rc = LNetGet(NULL, *mdh, &id,
3967                      LNET_RESERVED_PORTAL,
3968                      LNET_PROTO_PING_MATCHBITS, 0, recovery);
3969
3970         if (rc)
3971                 goto fail_unlink_md;
3972
3973         return 0;
3974
3975 fail_unlink_md:
3976         LNetMDUnlink(*mdh);
3977         LNetInvalidateMDHandle(mdh);
3978 fail_error:
3979         return rc;
3980 }
3981
3982 static void
3983 lnet_handle_recovery_reply(struct lnet_mt_event_info *ev_info,
3984                            int status, bool send, bool unlink_event)
3985 {
3986         struct lnet_nid *nid = &ev_info->mt_nid;
3987
3988         if (ev_info->mt_type == MT_TYPE_LOCAL_NI) {
3989                 struct lnet_ni *ni;
3990
3991                 lnet_net_lock(0);
3992                 ni = lnet_nid_to_ni_locked(nid, 0);
3993                 if (!ni) {
3994                         lnet_net_unlock(0);
3995                         return;
3996                 }
3997                 lnet_ni_lock(ni);
3998                 if (!send || (send && status != 0))
3999                         ni->ni_recovery_state &= ~LNET_NI_RECOVERY_PENDING;
4000                 if (status)
4001                         ni->ni_recovery_state |= LNET_NI_RECOVERY_FAILED;
4002                 lnet_ni_unlock(ni);
4003                 lnet_net_unlock(0);
4004
4005                 if (status != 0) {
4006                         CERROR("local NI (%s) recovery failed with %d\n",
4007                                libcfs_nidstr(nid), status);
4008                         return;
4009                 }
4010                 /*
4011                  * need to increment healthv for the ni here, because in
4012                  * the lnet_finalize() path we don't have access to this
4013                  * NI. And in order to get access to it, we'll need to
4014                  * carry forward too much information.
4015                  * In the peer case, it'll naturally be incremented
4016                  */
4017                 if (!unlink_event)
4018                         lnet_inc_healthv(&ni->ni_healthv,
4019                                          lnet_health_sensitivity);
4020         } else {
4021                 struct lnet_peer_ni *lpni;
4022                 int cpt;
4023
4024                 cpt = lnet_net_lock_current();
4025                 lpni = lnet_peer_ni_find_locked(nid);
4026                 if (!lpni) {
4027                         lnet_net_unlock(cpt);
4028                         return;
4029                 }
4030                 spin_lock(&lpni->lpni_lock);
4031                 if (!send || (send && status != 0))
4032                         lpni->lpni_state &= ~LNET_PEER_NI_RECOVERY_PENDING;
4033                 if (status)
4034                         lpni->lpni_state |= LNET_PEER_NI_RECOVERY_FAILED;
4035                 spin_unlock(&lpni->lpni_lock);
4036                 lnet_peer_ni_decref_locked(lpni);
4037                 lnet_net_unlock(cpt);
4038
4039                 if (status != 0)
4040                         CERROR("peer NI (%s) recovery failed with %d\n",
4041                                libcfs_nidstr(nid), status);
4042         }
4043 }
4044
4045 void
4046 lnet_mt_event_handler(struct lnet_event *event)
4047 {
4048         struct lnet_mt_event_info *ev_info = event->md_user_ptr;
4049         struct lnet_ping_buffer *pbuf;
4050
4051         /* TODO: remove assert */
4052         LASSERT(event->type == LNET_EVENT_REPLY ||
4053                 event->type == LNET_EVENT_SEND ||
4054                 event->type == LNET_EVENT_UNLINK);
4055
4056         CDEBUG(D_NET, "Received event: %d status: %d\n", event->type,
4057                event->status);
4058
4059         switch (event->type) {
4060         case LNET_EVENT_UNLINK:
4061                 CDEBUG(D_NET, "%s recovery ping unlinked\n",
4062                        libcfs_nidstr(&ev_info->mt_nid));
4063                 fallthrough;
4064         case LNET_EVENT_REPLY:
4065                 lnet_handle_recovery_reply(ev_info, event->status, false,
4066                                            event->type == LNET_EVENT_UNLINK);
4067                 break;
4068         case LNET_EVENT_SEND:
4069                 CDEBUG(D_NET, "%s recovery message sent %s:%d\n",
4070                                libcfs_nidstr(&ev_info->mt_nid),
4071                                (event->status) ? "unsuccessfully" :
4072                                "successfully", event->status);
4073                 lnet_handle_recovery_reply(ev_info, event->status, true, false);
4074                 break;
4075         default:
4076                 CERROR("Unexpected event: %d\n", event->type);
4077                 break;
4078         }
4079         if (event->unlinked) {
4080                 LIBCFS_FREE(ev_info, sizeof(*ev_info));
4081                 pbuf = LNET_PING_INFO_TO_BUFFER(event->md_start);
4082                 lnet_ping_buffer_decref(pbuf);
4083         }
4084 }
4085
4086 static int
4087 lnet_rsp_tracker_create(void)
4088 {
4089         struct list_head **rstqs;
4090         rstqs = lnet_create_array_of_queues();
4091
4092         if (!rstqs)
4093                 return -ENOMEM;
4094
4095         the_lnet.ln_mt_rstq = rstqs;
4096
4097         return 0;
4098 }
4099
4100 static void
4101 lnet_rsp_tracker_clean(void)
4102 {
4103         lnet_finalize_expired_responses();
4104
4105         cfs_percpt_free(the_lnet.ln_mt_rstq);
4106         the_lnet.ln_mt_rstq = NULL;
4107 }
4108
4109 int lnet_monitor_thr_start(void)
4110 {
4111         int rc = 0;
4112         struct task_struct *task;
4113
4114         if (the_lnet.ln_mt_state != LNET_MT_STATE_SHUTDOWN)
4115                 return -EALREADY;
4116
4117         rc = lnet_resendqs_create();
4118         if (rc)
4119                 return rc;
4120
4121         rc = lnet_rsp_tracker_create();
4122         if (rc)
4123                 goto clean_queues;
4124
4125         sema_init(&the_lnet.ln_mt_signal, 0);
4126
4127         lnet_net_lock(LNET_LOCK_EX);
4128         the_lnet.ln_mt_state = LNET_MT_STATE_RUNNING;
4129         lnet_net_unlock(LNET_LOCK_EX);
4130         task = kthread_run(lnet_monitor_thread, NULL, "monitor_thread");
4131         if (IS_ERR(task)) {
4132                 rc = PTR_ERR(task);
4133                 CERROR("Can't start monitor thread: %d\n", rc);
4134                 goto clean_thread;
4135         }
4136
4137         return 0;
4138
4139 clean_thread:
4140         lnet_net_lock(LNET_LOCK_EX);
4141         the_lnet.ln_mt_state = LNET_MT_STATE_STOPPING;
4142         lnet_net_unlock(LNET_LOCK_EX);
4143         /* block until event callback signals exit */
4144         down(&the_lnet.ln_mt_signal);
4145         /* clean up */
4146         lnet_net_lock(LNET_LOCK_EX);
4147         the_lnet.ln_mt_state = LNET_MT_STATE_SHUTDOWN;
4148         lnet_net_unlock(LNET_LOCK_EX);
4149         lnet_rsp_tracker_clean();
4150         lnet_clean_local_ni_recoveryq();
4151         lnet_clean_peer_ni_recoveryq();
4152         lnet_clean_resendqs();
4153         the_lnet.ln_mt_handler = NULL;
4154         return rc;
4155 clean_queues:
4156         lnet_rsp_tracker_clean();
4157         lnet_clean_local_ni_recoveryq();
4158         lnet_clean_peer_ni_recoveryq();
4159         lnet_clean_resendqs();
4160         return rc;
4161 }
4162
4163 void lnet_monitor_thr_stop(void)
4164 {
4165         if (the_lnet.ln_mt_state == LNET_MT_STATE_SHUTDOWN)
4166                 return;
4167
4168         LASSERT(the_lnet.ln_mt_state == LNET_MT_STATE_RUNNING);
4169         lnet_net_lock(LNET_LOCK_EX);
4170         the_lnet.ln_mt_state = LNET_MT_STATE_STOPPING;
4171         lnet_net_unlock(LNET_LOCK_EX);
4172
4173         /* tell the monitor thread that we're shutting down */
4174         complete(&the_lnet.ln_mt_wait_complete);
4175
4176         /* block until monitor thread signals that it's done */
4177         mutex_unlock(&the_lnet.ln_api_mutex);
4178         down(&the_lnet.ln_mt_signal);
4179         mutex_lock(&the_lnet.ln_api_mutex);
4180         LASSERT(the_lnet.ln_mt_state == LNET_MT_STATE_SHUTDOWN);
4181
4182         /* perform cleanup tasks */
4183         lnet_rsp_tracker_clean();
4184         lnet_clean_local_ni_recoveryq();
4185         lnet_clean_peer_ni_recoveryq();
4186         lnet_clean_resendqs();
4187 }
4188
4189 void
4190 lnet_drop_message(struct lnet_ni *ni, int cpt, void *private, unsigned int nob,
4191                   __u32 msg_type)
4192 {
4193         lnet_net_lock(cpt);
4194         lnet_incr_stats(&ni->ni_stats, msg_type, LNET_STATS_TYPE_DROP);
4195         the_lnet.ln_counters[cpt]->lct_common.lcc_drop_count++;
4196         the_lnet.ln_counters[cpt]->lct_common.lcc_drop_length += nob;
4197         lnet_net_unlock(cpt);
4198
4199         lnet_ni_recv(ni, private, NULL, 0, 0, 0, nob);
4200 }
4201
4202 static void
4203 lnet_recv_put(struct lnet_ni *ni, struct lnet_msg *msg)
4204 {
4205         struct lnet_hdr *hdr = &msg->msg_hdr;
4206
4207         if (msg->msg_wanted != 0)
4208                 lnet_setpayloadbuffer(msg);
4209
4210         lnet_build_msg_event(msg, LNET_EVENT_PUT);
4211
4212         /* Must I ACK?  If so I'll grab the ack_wmd out of the header and put
4213          * it back into the ACK during lnet_finalize() */
4214         msg->msg_ack = (!lnet_is_wire_handle_none(&hdr->msg.put.ack_wmd) &&
4215                         (msg->msg_md->md_options & LNET_MD_ACK_DISABLE) == 0);
4216
4217         lnet_ni_recv(ni, msg->msg_private, msg, msg->msg_rx_delayed,
4218                      msg->msg_offset, msg->msg_wanted, hdr->payload_length);
4219 }
4220
4221 static int
4222 lnet_parse_put(struct lnet_ni *ni, struct lnet_msg *msg)
4223 {
4224         struct lnet_hdr         *hdr = &msg->msg_hdr;
4225         struct lnet_match_info  info;
4226         int                     rc;
4227         bool                    ready_delay;
4228
4229         /* Convert put fields to host byte order */
4230         hdr->msg.put.match_bits = le64_to_cpu(hdr->msg.put.match_bits);
4231         hdr->msg.put.ptl_index  = le32_to_cpu(hdr->msg.put.ptl_index);
4232         hdr->msg.put.offset     = le32_to_cpu(hdr->msg.put.offset);
4233
4234         /* Primary peer NID. */
4235         info.mi_id.nid = msg->msg_initiator;
4236         info.mi_id.pid  = hdr->src_pid;
4237         info.mi_opc     = LNET_MD_OP_PUT;
4238         info.mi_portal  = hdr->msg.put.ptl_index;
4239         info.mi_rlength = hdr->payload_length;
4240         info.mi_roffset = hdr->msg.put.offset;
4241         info.mi_mbits   = hdr->msg.put.match_bits;
4242         info.mi_cpt     = lnet_nid2cpt(&msg->msg_initiator, ni);
4243
4244         msg->msg_rx_ready_delay = ni->ni_net->net_lnd->lnd_eager_recv == NULL;
4245         ready_delay = msg->msg_rx_ready_delay;
4246
4247  again:
4248         rc = lnet_ptl_match_md(&info, msg);
4249         switch (rc) {
4250         default:
4251                 LBUG();
4252
4253         case LNET_MATCHMD_OK:
4254                 lnet_recv_put(ni, msg);
4255                 return 0;
4256
4257         case LNET_MATCHMD_NONE:
4258                 if (ready_delay)
4259                         /* no eager_recv or has already called it, should
4260                          * have been attached on delayed list */
4261                         return 0;
4262
4263                 rc = lnet_ni_eager_recv(ni, msg);
4264                 if (rc == 0) {
4265                         ready_delay = true;
4266                         goto again;
4267                 }
4268                 fallthrough;
4269
4270         case LNET_MATCHMD_DROP:
4271                 CNETERR("Dropping PUT from %s portal %d match %llu"
4272                         " offset %d length %d: %d\n",
4273                         libcfs_idstr(&info.mi_id), info.mi_portal,
4274                         info.mi_mbits, info.mi_roffset, info.mi_rlength, rc);
4275
4276                 return -ENOENT; /* -ve: OK but no match */
4277         }
4278 }
4279
4280 static int
4281 lnet_parse_get(struct lnet_ni *ni, struct lnet_msg *msg, int rdma_get)
4282 {
4283         struct lnet_match_info info;
4284         struct lnet_hdr *hdr = &msg->msg_hdr;
4285         struct lnet_processid source_id;
4286         struct lnet_handle_wire reply_wmd;
4287         int rc;
4288
4289         /* Convert get fields to host byte order */
4290         hdr->msg.get.match_bits   = le64_to_cpu(hdr->msg.get.match_bits);
4291         hdr->msg.get.ptl_index    = le32_to_cpu(hdr->msg.get.ptl_index);
4292         hdr->msg.get.sink_length  = le32_to_cpu(hdr->msg.get.sink_length);
4293         hdr->msg.get.src_offset   = le32_to_cpu(hdr->msg.get.src_offset);
4294
4295         source_id.nid = hdr->src_nid;
4296         source_id.pid = hdr->src_pid;
4297         /* Primary peer NID */
4298         info.mi_id.nid  = msg->msg_initiator;
4299         info.mi_id.pid  = hdr->src_pid;
4300         info.mi_opc     = LNET_MD_OP_GET;
4301         info.mi_portal  = hdr->msg.get.ptl_index;
4302         info.mi_rlength = hdr->msg.get.sink_length;
4303         info.mi_roffset = hdr->msg.get.src_offset;
4304         info.mi_mbits   = hdr->msg.get.match_bits;
4305         info.mi_cpt     = lnet_nid2cpt(&msg->msg_initiator, ni);
4306
4307         rc = lnet_ptl_match_md(&info, msg);
4308         if (rc == LNET_MATCHMD_DROP) {
4309                 CNETERR("Dropping GET from %s portal %d match %llu"
4310                         " offset %d length %d\n",
4311                         libcfs_idstr(&info.mi_id), info.mi_portal,
4312                         info.mi_mbits, info.mi_roffset, info.mi_rlength);
4313                 return -ENOENT; /* -ve: OK but no match */
4314         }
4315
4316         LASSERT(rc == LNET_MATCHMD_OK);
4317
4318         lnet_build_msg_event(msg, LNET_EVENT_GET);
4319
4320         reply_wmd = hdr->msg.get.return_wmd;
4321
4322         lnet_prep_send(msg, LNET_MSG_REPLY, &source_id,
4323                        msg->msg_offset, msg->msg_wanted);
4324
4325         msg->msg_hdr.msg.reply.dst_wmd = reply_wmd;
4326
4327         if (rdma_get) {
4328                 /* The LND completes the REPLY from her recv procedure */
4329                 lnet_ni_recv(ni, msg->msg_private, msg, 0,
4330                              msg->msg_offset, msg->msg_len, msg->msg_len);
4331                 return 0;
4332         }
4333
4334         lnet_ni_recv(ni, msg->msg_private, NULL, 0, 0, 0, 0);
4335         msg->msg_receiving = 0;
4336
4337         rc = lnet_send(&ni->ni_nid, msg, &msg->msg_from);
4338         if (rc < 0) {
4339                 /* didn't get as far as lnet_ni_send() */
4340                 CERROR("%s: Unable to send REPLY for GET from %s: %d\n",
4341                        libcfs_nidstr(&ni->ni_nid),
4342                        libcfs_idstr(&info.mi_id), rc);
4343
4344                 lnet_finalize(msg, rc);
4345         }
4346
4347         return 0;
4348 }
4349
4350 static int
4351 lnet_parse_reply(struct lnet_ni *ni, struct lnet_msg *msg)
4352 {
4353         void *private = msg->msg_private;
4354         struct lnet_hdr *hdr = &msg->msg_hdr;
4355         struct lnet_processid src = {};
4356         struct lnet_libmd *md;
4357         unsigned int rlength;
4358         unsigned int mlength;
4359         int cpt;
4360
4361         cpt = lnet_cpt_of_cookie(hdr->msg.reply.dst_wmd.wh_object_cookie);
4362         lnet_res_lock(cpt);
4363
4364         src.nid = hdr->src_nid;
4365         src.pid = hdr->src_pid;
4366
4367         /* NB handles only looked up by creator (no flips) */
4368         md = lnet_wire_handle2md(&hdr->msg.reply.dst_wmd);
4369         if (md == NULL || md->md_threshold == 0 || md->md_me != NULL) {
4370                 CNETERR("%s: Dropping REPLY from %s for %s "
4371                         "MD %#llx.%#llx\n",
4372                         libcfs_nidstr(&ni->ni_nid), libcfs_idstr(&src),
4373                         (md == NULL) ? "invalid" : "inactive",
4374                         hdr->msg.reply.dst_wmd.wh_interface_cookie,
4375                         hdr->msg.reply.dst_wmd.wh_object_cookie);
4376                 if (md != NULL && md->md_me != NULL)
4377                         CERROR("REPLY MD also attached to portal %d\n",
4378                                md->md_me->me_portal);
4379
4380                 lnet_res_unlock(cpt);
4381                 return -ENOENT; /* -ve: OK but no match */
4382         }
4383
4384         LASSERT(md->md_offset == 0);
4385
4386         rlength = hdr->payload_length;
4387         mlength = min(rlength, md->md_length);
4388
4389         if (mlength < rlength &&
4390             (md->md_options & LNET_MD_TRUNCATE) == 0) {
4391                 CNETERR("%s: Dropping REPLY from %s length %d "
4392                         "for MD %#llx would overflow (%d)\n",
4393                         libcfs_nidstr(&ni->ni_nid), libcfs_idstr(&src),
4394                         rlength, hdr->msg.reply.dst_wmd.wh_object_cookie,
4395                         mlength);
4396                 lnet_res_unlock(cpt);
4397                 return -ENOENT; /* -ve: OK but no match */
4398         }
4399
4400         CDEBUG(D_NET, "%s: Reply from %s of length %d/%d into md %#llx\n",
4401                libcfs_nidstr(&ni->ni_nid), libcfs_idstr(&src),
4402                mlength, rlength, hdr->msg.reply.dst_wmd.wh_object_cookie);
4403
4404         lnet_msg_attach_md(msg, md, 0, mlength);
4405
4406         if (mlength != 0)
4407                 lnet_setpayloadbuffer(msg);
4408
4409         lnet_res_unlock(cpt);
4410
4411         lnet_build_msg_event(msg, LNET_EVENT_REPLY);
4412
4413         lnet_ni_recv(ni, private, msg, 0, 0, mlength, rlength);
4414         return 0;
4415 }
4416
4417 static int
4418 lnet_parse_ack(struct lnet_ni *ni, struct lnet_msg *msg)
4419 {
4420         struct lnet_hdr *hdr = &msg->msg_hdr;
4421         struct lnet_processid src = {};
4422         struct lnet_libmd *md;
4423         int cpt;
4424
4425         src.nid = hdr->src_nid;
4426         src.pid = hdr->src_pid;
4427
4428         /* Convert ack fields to host byte order */
4429         hdr->msg.ack.match_bits = le64_to_cpu(hdr->msg.ack.match_bits);
4430         hdr->msg.ack.mlength = le32_to_cpu(hdr->msg.ack.mlength);
4431
4432         cpt = lnet_cpt_of_cookie(hdr->msg.ack.dst_wmd.wh_object_cookie);
4433         lnet_res_lock(cpt);
4434
4435         /* NB handles only looked up by creator (no flips) */
4436         md = lnet_wire_handle2md(&hdr->msg.ack.dst_wmd);
4437         if (md == NULL || md->md_threshold == 0 || md->md_me != NULL) {
4438                 /* Don't moan; this is expected */
4439                 CDEBUG(D_NET,
4440                        "%s: Dropping ACK from %s to %s MD %#llx.%#llx\n",
4441                        libcfs_nidstr(&ni->ni_nid), libcfs_idstr(&src),
4442                        (md == NULL) ? "invalid" : "inactive",
4443                        hdr->msg.ack.dst_wmd.wh_interface_cookie,
4444                        hdr->msg.ack.dst_wmd.wh_object_cookie);
4445                 if (md != NULL && md->md_me != NULL)
4446                         CERROR("Source MD also attached to portal %d\n",
4447                                md->md_me->me_portal);
4448
4449                 lnet_res_unlock(cpt);
4450                 return -ENOENT;                  /* -ve! */
4451         }
4452
4453         CDEBUG(D_NET, "%s: ACK from %s into md %#llx\n",
4454                libcfs_nidstr(&ni->ni_nid), libcfs_idstr(&src),
4455                hdr->msg.ack.dst_wmd.wh_object_cookie);
4456
4457         lnet_msg_attach_md(msg, md, 0, 0);
4458
4459         lnet_res_unlock(cpt);
4460
4461         lnet_build_msg_event(msg, LNET_EVENT_ACK);
4462
4463         lnet_ni_recv(ni, msg->msg_private, msg, 0, 0, 0, msg->msg_len);
4464         return 0;
4465 }
4466
4467 /**
4468  * \retval LNET_CREDIT_OK       If \a msg is forwarded
4469  * \retval LNET_CREDIT_WAIT     If \a msg is blocked because w/o buffer
4470  * \retval -ve                  error code
4471  */
4472 int
4473 lnet_parse_forward_locked(struct lnet_ni *ni, struct lnet_msg *msg)
4474 {
4475         int     rc = 0;
4476
4477         if (!the_lnet.ln_routing)
4478                 return -ECANCELED;
4479
4480         if (msg->msg_rxpeer->lpni_rtrcredits <= 0 ||
4481             lnet_msg2bufpool(msg)->rbp_credits <= 0) {
4482                 if (ni->ni_net->net_lnd->lnd_eager_recv == NULL) {
4483                         msg->msg_rx_ready_delay = 1;
4484                 } else {
4485                         lnet_net_unlock(msg->msg_rx_cpt);
4486                         rc = lnet_ni_eager_recv(ni, msg);
4487                         lnet_net_lock(msg->msg_rx_cpt);
4488                 }
4489         }
4490
4491         if (rc == 0)
4492                 rc = lnet_post_routed_recv_locked(msg, 0);
4493         return rc;
4494 }
4495
4496 int
4497 lnet_parse_local(struct lnet_ni *ni, struct lnet_msg *msg)
4498 {
4499         int     rc;
4500
4501         switch (msg->msg_type) {
4502         case LNET_MSG_ACK:
4503                 rc = lnet_parse_ack(ni, msg);
4504                 break;
4505         case LNET_MSG_PUT:
4506                 rc = lnet_parse_put(ni, msg);
4507                 break;
4508         case LNET_MSG_GET:
4509                 rc = lnet_parse_get(ni, msg, msg->msg_rdma_get);
4510                 break;
4511         case LNET_MSG_REPLY:
4512                 rc = lnet_parse_reply(ni, msg);
4513                 break;
4514         default: /* prevent an unused label if !kernel */
4515                 LASSERT(0);
4516                 return -EPROTO;
4517         }
4518
4519         LASSERT(rc == 0 || rc == -ENOENT);
4520         return rc;
4521 }
4522
4523 char *
4524 lnet_msgtyp2str (int type)
4525 {
4526         switch (type) {
4527         case LNET_MSG_ACK:
4528                 return ("ACK");
4529         case LNET_MSG_PUT:
4530                 return ("PUT");
4531         case LNET_MSG_GET:
4532                 return ("GET");
4533         case LNET_MSG_REPLY:
4534                 return ("REPLY");
4535         case LNET_MSG_HELLO:
4536                 return ("HELLO");
4537         default:
4538                 return ("<UNKNOWN>");
4539         }
4540 }
4541 EXPORT_SYMBOL(lnet_msgtyp2str);
4542
4543 int
4544 lnet_parse(struct lnet_ni *ni, struct lnet_hdr *hdr,
4545            struct lnet_nid *from_nid, void *private, int rdma_req)
4546 {
4547         struct lnet_peer_ni *lpni;
4548         struct lnet_msg *msg;
4549         __u32 payload_length;
4550         lnet_pid_t dest_pid;
4551         struct lnet_nid dest_nid;
4552         struct lnet_nid src_nid;
4553         bool push = false;
4554         int for_me;
4555         __u32 type;
4556         int rc = 0;
4557         int cpt;
4558         time64_t now = ktime_get_seconds();
4559
4560         LASSERT (!in_interrupt ());
4561
4562         type = hdr->type;
4563         src_nid = hdr->src_nid;
4564         dest_nid = hdr->dest_nid;
4565         dest_pid = hdr->dest_pid;
4566         payload_length = hdr->payload_length;
4567
4568         for_me = nid_same(&ni->ni_nid, &dest_nid);
4569         cpt = lnet_nid2cpt(from_nid, ni);
4570
4571         CDEBUG(D_NET, "TRACE: %s(%s) <- %s : %s - %s\n",
4572                 libcfs_nidstr(&dest_nid),
4573                 libcfs_nidstr(&ni->ni_nid),
4574                 libcfs_nidstr(&src_nid),
4575                 lnet_msgtyp2str(type),
4576                 (for_me) ? "for me" : "routed");
4577
4578         switch (type) {
4579         case LNET_MSG_ACK:
4580         case LNET_MSG_GET:
4581                 if (payload_length > 0) {
4582                         CERROR("%s, src %s: bad %s payload %d (0 expected)\n",
4583                                libcfs_nidstr(from_nid),
4584                                libcfs_nidstr(&src_nid),
4585                                lnet_msgtyp2str(type), payload_length);
4586                         return -EPROTO;
4587                 }
4588                 break;
4589
4590         case LNET_MSG_PUT:
4591         case LNET_MSG_REPLY:
4592                 if (payload_length >
4593                     (__u32)(for_me ? LNET_MAX_PAYLOAD : LNET_MTU)) {
4594                         CERROR("%s, src %s: bad %s payload %d "
4595                                "(%d max expected)\n",
4596                                libcfs_nidstr(from_nid),
4597                                libcfs_nidstr(&src_nid),
4598                                lnet_msgtyp2str(type),
4599                                payload_length,
4600                                for_me ? LNET_MAX_PAYLOAD : LNET_MTU);
4601                         return -EPROTO;
4602                 }
4603                 break;
4604
4605         default:
4606                 CERROR("%s, src %s: Bad message type 0x%x\n",
4607                        libcfs_nidstr(from_nid),
4608                        libcfs_nidstr(&src_nid), type);
4609                 return -EPROTO;
4610         }
4611
4612         /* Only update net_last_alive for incoming GETs on the reserved portal
4613          * (i.e. incoming lnet/discovery pings).
4614          * This avoids situations where the router's own traffic results in NI
4615          * status changes
4616          */
4617         if (the_lnet.ln_routing && type == LNET_MSG_GET &&
4618             hdr->msg.get.ptl_index == LNET_RESERVED_PORTAL &&
4619             !lnet_islocalnid(&src_nid) &&
4620             ni->ni_net->net_last_alive != now) {
4621                 lnet_ni_lock(ni);
4622                 spin_lock(&ni->ni_net->net_lock);
4623                 ni->ni_net->net_last_alive = now;
4624                 spin_unlock(&ni->ni_net->net_lock);
4625                 push = lnet_ni_set_status_locked(ni, LNET_NI_STATUS_UP);
4626                 lnet_ni_unlock(ni);
4627         }
4628
4629         if (push)
4630                 lnet_push_update_to_peers(1);
4631
4632         /* Regard a bad destination NID as a protocol error.  Senders should
4633          * know what they're doing; if they don't they're misconfigured, buggy
4634          * or malicious so we chop them off at the knees :) */
4635
4636         if (!for_me) {
4637                 if (LNET_NID_NET(&dest_nid) == LNET_NID_NET(&ni->ni_nid)) {
4638                         /* should have gone direct */
4639                         CERROR("%s, src %s: Bad dest nid %s "
4640                                "(should have been sent direct)\n",
4641                                 libcfs_nidstr(from_nid),
4642                                 libcfs_nidstr(&src_nid),
4643                                 libcfs_nidstr(&dest_nid));
4644                         return -EPROTO;
4645                 }
4646
4647                 if (lnet_islocalnid(&dest_nid)) {
4648                         /* dest is another local NI; sender should have used
4649                          * this node's NID on its own network */
4650                         CERROR("%s, src %s: Bad dest nid %s "
4651                                "(it's my nid but on a different network)\n",
4652                                 libcfs_nidstr(from_nid),
4653                                 libcfs_nidstr(&src_nid),
4654                                 libcfs_nidstr(&dest_nid));
4655                         return -EPROTO;
4656                 }
4657
4658                 if (rdma_req && type == LNET_MSG_GET) {
4659                         CERROR("%s, src %s: Bad optimized GET for %s "
4660                                "(final destination must be me)\n",
4661                                 libcfs_nidstr(from_nid),
4662                                 libcfs_nidstr(&src_nid),
4663                                 libcfs_nidstr(&dest_nid));
4664                         return -EPROTO;
4665                 }
4666
4667                 if (!the_lnet.ln_routing) {
4668                         CERROR("%s, src %s: Dropping message for %s "
4669                                "(routing not enabled)\n",
4670                                 libcfs_nidstr(from_nid),
4671                                 libcfs_nidstr(&src_nid),
4672                                 libcfs_nidstr(&dest_nid));
4673                         goto drop;
4674                 }
4675         }
4676
4677         /* Message looks OK; we're not going to return an error, so we MUST
4678          * call back lnd_recv() come what may... */
4679
4680         if (!list_empty(&the_lnet.ln_test_peers) &&     /* normally we don't */
4681             fail_peer(&src_nid, 0)) {                   /* shall we now? */
4682                 CERROR("%s, src %s: Dropping %s to simulate failure\n",
4683                        libcfs_nidstr(from_nid), libcfs_nidstr(&src_nid),
4684                        lnet_msgtyp2str(type));
4685                 goto drop;
4686         }
4687
4688         if (!list_empty(&the_lnet.ln_drop_rules) &&
4689             lnet_drop_rule_match(hdr, &ni->ni_nid, NULL)) {
4690                 CDEBUG(D_NET,
4691                        "%s, src %s, dst %s: Dropping %s to simulate silent message loss\n",
4692                        libcfs_nidstr(from_nid), libcfs_nidstr(&src_nid),
4693                        libcfs_nidstr(&dest_nid), lnet_msgtyp2str(type));
4694                 goto drop;
4695         }
4696
4697         msg = lnet_msg_alloc();
4698         if (msg == NULL) {
4699                 CERROR("%s, src %s: Dropping %s (out of memory)\n",
4700                        libcfs_nidstr(from_nid), libcfs_nidstr(&src_nid),
4701                        lnet_msgtyp2str(type));
4702                 goto drop;
4703         }
4704
4705         /* msg zeroed in lnet_msg_alloc; i.e. flags all clear,
4706          * pointers NULL etc */
4707
4708         msg->msg_type = type;
4709         msg->msg_private = private;
4710         msg->msg_receiving = 1;
4711         msg->msg_rdma_get = rdma_req;
4712         msg->msg_len = msg->msg_wanted = payload_length;
4713         msg->msg_offset = 0;
4714         msg->msg_hdr = *hdr;
4715         /* for building message event */
4716         msg->msg_from = *from_nid;
4717         if (!for_me) {
4718                 msg->msg_target.pid = dest_pid;
4719                 msg->msg_target.nid = dest_nid;
4720                 msg->msg_routing = 1;
4721         }
4722
4723         lnet_net_lock(cpt);
4724         lpni = lnet_peerni_by_nid_locked(from_nid, &ni->ni_nid, cpt);
4725         if (IS_ERR(lpni)) {
4726                 lnet_net_unlock(cpt);
4727                 rc = PTR_ERR(lpni);
4728                 CERROR("%s, src %s: Dropping %s (error %d looking up sender)\n",
4729                        libcfs_nidstr(from_nid), libcfs_nidstr(&src_nid),
4730                        lnet_msgtyp2str(type), rc);
4731                 lnet_msg_free(msg);
4732                 if (rc == -ESHUTDOWN)
4733                         /* We are shutting down.  Don't do anything more */
4734                         return rc;
4735                 goto drop;
4736         }
4737
4738         /* If this message was forwarded to us from a router then we may need
4739          * to update router aliveness or check for an asymmetrical route
4740          * (or both)
4741          */
4742         if (((lnet_drop_asym_route && for_me) ||
4743              !lpni->lpni_peer_net->lpn_peer->lp_alive) &&
4744             LNET_NID_NET(&src_nid) != LNET_NID_NET(from_nid)) {
4745                 __u32 src_net_id = LNET_NID_NET(&src_nid);
4746                 struct lnet_peer *gw = lpni->lpni_peer_net->lpn_peer;
4747                 struct lnet_route *route;
4748                 bool found = false;
4749
4750                 list_for_each_entry(route, &gw->lp_routes, lr_gwlist) {
4751                         if (route->lr_net == src_net_id) {
4752                                 found = true;
4753                                 /* If we're transitioning the gateway from
4754                                  * dead -> alive, and discovery is disabled
4755                                  * locally or on the gateway, then we need to
4756                                  * update the cached route aliveness for each
4757                                  * route to the src_nid's net.
4758                                  *
4759                                  * Otherwise, we're only checking for
4760                                  * symmetrical route, and we can break the
4761                                  * loop
4762                                  */
4763                                 if (!gw->lp_alive &&
4764                                     lnet_is_discovery_disabled(gw))
4765                                         lnet_set_route_aliveness(route, true);
4766                                 else
4767                                         break;
4768                         }
4769                 }
4770                 if (lnet_drop_asym_route && for_me && !found) {
4771                         /* Drop ref taken by lnet_nid2peerni_locked() */
4772                         lnet_peer_ni_decref_locked(lpni);
4773                         lnet_net_unlock(cpt);
4774                         /* we would not use from_nid to route a message to
4775                          * src_nid
4776                          * => asymmetric routing detected but forbidden
4777                          */
4778                         CERROR("%s, src %s: Dropping asymmetrical route %s\n",
4779                                libcfs_nidstr(from_nid),
4780                                libcfs_nidstr(&src_nid), lnet_msgtyp2str(type));
4781                         lnet_msg_free(msg);
4782                         goto drop;
4783                 }
4784                 if (!gw->lp_alive) {
4785                         struct lnet_peer_net *lpn;
4786                         struct lnet_peer_ni *lpni2;
4787
4788                         gw->lp_alive = true;
4789                         /* Mark all remote NIs on src_nid's net UP */
4790                         lpn = lnet_peer_get_net_locked(gw, src_net_id);
4791                         if (lpn)
4792                                 list_for_each_entry(lpni2, &lpn->lpn_peer_nis,
4793                                                     lpni_peer_nis)
4794                                         lpni2->lpni_ns_status = LNET_NI_STATUS_UP;
4795                 }
4796         }
4797
4798         lpni->lpni_last_alive = now;
4799
4800         msg->msg_rxpeer = lpni;
4801         msg->msg_rxni = ni;
4802         lnet_ni_addref_locked(ni, cpt);
4803         /* Multi-Rail: Primary NID of source. */
4804         lnet_peer_primary_nid_locked(&src_nid, &msg->msg_initiator);
4805
4806         /*
4807          * mark the status of this lpni as UP since we received a message
4808          * from it. The ping response reports back the ns_status which is
4809          * marked on the remote as up or down and we cache it here.
4810          */
4811         msg->msg_rxpeer->lpni_ns_status = LNET_NI_STATUS_UP;
4812
4813         lnet_msg_commit(msg, cpt);
4814
4815         /* message delay simulation */
4816         if (unlikely(!list_empty(&the_lnet.ln_delay_rules) &&
4817                      lnet_delay_rule_match_locked(hdr, msg))) {
4818                 lnet_net_unlock(cpt);
4819                 return 0;
4820         }
4821
4822         if (!for_me) {
4823                 rc = lnet_parse_forward_locked(ni, msg);
4824                 lnet_net_unlock(cpt);
4825
4826                 if (rc < 0)
4827                         goto free_drop;
4828
4829                 if (rc == LNET_CREDIT_OK) {
4830                         lnet_ni_recv(ni, msg->msg_private, msg, 0,
4831                                      0, payload_length, payload_length);
4832                 }
4833                 return 0;
4834         }
4835
4836         lnet_net_unlock(cpt);
4837
4838         rc = lnet_parse_local(ni, msg);
4839         if (rc != 0)
4840                 goto free_drop;
4841         return 0;
4842
4843  free_drop:
4844         LASSERT(msg->msg_md == NULL);
4845         lnet_finalize(msg, rc);
4846
4847  drop:
4848         lnet_drop_message(ni, cpt, private, payload_length, type);
4849         return 0;
4850 }
4851 EXPORT_SYMBOL(lnet_parse);
4852
4853 void
4854 lnet_drop_delayed_msg_list(struct list_head *head, char *reason)
4855 {
4856         struct lnet_msg *msg;
4857
4858         while ((msg = list_first_entry_or_null(head, struct lnet_msg,
4859                                                msg_list)) != NULL) {
4860                 struct lnet_processid id = {};
4861
4862                 list_del(&msg->msg_list);
4863
4864                 id.nid = msg->msg_hdr.src_nid;
4865                 id.pid = msg->msg_hdr.src_pid;
4866
4867                 LASSERT(msg->msg_md == NULL);
4868                 LASSERT(msg->msg_rx_delayed);
4869                 LASSERT(msg->msg_rxpeer != NULL);
4870                 LASSERT(msg->msg_hdr.type == LNET_MSG_PUT);
4871
4872                 CWARN("Dropping delayed PUT from %s portal %d match %llu"
4873                       " offset %d length %d: %s\n",
4874                       libcfs_idstr(&id),
4875                       msg->msg_hdr.msg.put.ptl_index,
4876                       msg->msg_hdr.msg.put.match_bits,
4877                       msg->msg_hdr.msg.put.offset,
4878                       msg->msg_hdr.payload_length, reason);
4879
4880                 /* NB I can't drop msg's ref on msg_rxpeer until after I've
4881                  * called lnet_drop_message(), so I just hang onto msg as well
4882                  * until that's done */
4883
4884                 lnet_drop_message(msg->msg_rxni, msg->msg_rx_cpt,
4885                                   msg->msg_private, msg->msg_len,
4886                                   msg->msg_type);
4887
4888                 msg->msg_no_resend = true;
4889                 /*
4890                  * NB: message will not generate event because w/o attached MD,
4891                  * but we still should give error code so lnet_msg_decommit()
4892                  * can skip counters operations and other checks.
4893                  */
4894                 lnet_finalize(msg, -ENOENT);
4895         }
4896 }
4897
4898 void
4899 lnet_recv_delayed_msg_list(struct list_head *head)
4900 {
4901         struct lnet_msg *msg;
4902
4903         while ((msg = list_first_entry_or_null(head, struct lnet_msg,
4904                                                msg_list)) != NULL) {
4905                 struct lnet_processid id;
4906
4907                 list_del(&msg->msg_list);
4908
4909                 /* md won't disappear under me, since each msg
4910                  * holds a ref on it */
4911
4912                 id.nid = msg->msg_hdr.src_nid;
4913                 id.pid = msg->msg_hdr.src_pid;
4914
4915                 LASSERT(msg->msg_rx_delayed);
4916                 LASSERT(msg->msg_md != NULL);
4917                 LASSERT(msg->msg_rxpeer != NULL);
4918                 LASSERT(msg->msg_rxni != NULL);
4919                 LASSERT(msg->msg_hdr.type == LNET_MSG_PUT);
4920
4921                 CDEBUG(D_NET, "Resuming delayed PUT from %s portal %d "
4922                        "match %llu offset %d length %d.\n",
4923                         libcfs_idstr(&id), msg->msg_hdr.msg.put.ptl_index,
4924                         msg->msg_hdr.msg.put.match_bits,
4925                         msg->msg_hdr.msg.put.offset,
4926                         msg->msg_hdr.payload_length);
4927
4928                 lnet_recv_put(msg->msg_rxni, msg);
4929         }
4930 }
4931
4932 static void
4933 lnet_attach_rsp_tracker(struct lnet_rsp_tracker *rspt, int cpt,
4934                         struct lnet_libmd *md, struct lnet_handle_md mdh)
4935 {
4936         s64 timeout_ns;
4937         struct lnet_rsp_tracker *local_rspt;
4938
4939         /*
4940          * MD has a refcount taken by message so it's not going away.
4941          * The MD however can be looked up. We need to secure the access
4942          * to the md_rspt_ptr by taking the res_lock.
4943          * The rspt can be accessed without protection up to when it gets
4944          * added to the list.
4945          */
4946
4947         lnet_res_lock(cpt);
4948         local_rspt = md->md_rspt_ptr;
4949         timeout_ns = lnet_transaction_timeout * NSEC_PER_SEC;
4950         if (local_rspt != NULL) {
4951                 /*
4952                  * we already have an rspt attached to the md, so we'll
4953                  * update the deadline on that one.
4954                  */
4955                 lnet_rspt_free(rspt, cpt);
4956         } else {
4957                 /* new md */
4958                 rspt->rspt_mdh = mdh;
4959                 rspt->rspt_cpt = cpt;
4960                 /* store the rspt so we can access it when we get the REPLY */
4961                 md->md_rspt_ptr = rspt;
4962                 local_rspt = rspt;
4963         }
4964         local_rspt->rspt_deadline = ktime_add_ns(ktime_get(), timeout_ns);
4965
4966         /*
4967          * add to the list of tracked responses. It's added to tail of the
4968          * list in order to expire all the older entries first.
4969          */
4970         lnet_net_lock(cpt);
4971         list_move_tail(&local_rspt->rspt_on_list, the_lnet.ln_mt_rstq[cpt]);
4972         lnet_net_unlock(cpt);
4973         lnet_res_unlock(cpt);
4974 }
4975
4976 /**
4977  * Initiate an asynchronous PUT operation.
4978  *
4979  * There are several events associated with a PUT: completion of the send on
4980  * the initiator node (LNET_EVENT_SEND), and when the send completes
4981  * successfully, the receipt of an acknowledgment (LNET_EVENT_ACK) indicating
4982  * that the operation was accepted by the target. The event LNET_EVENT_PUT is
4983  * used at the target node to indicate the completion of incoming data
4984  * delivery.
4985  *
4986  * The local events will be logged in the EQ associated with the MD pointed to
4987  * by \a mdh handle. Using a MD without an associated EQ results in these
4988  * events being discarded. In this case, the caller must have another
4989  * mechanism (e.g., a higher level protocol) for determining when it is safe
4990  * to modify the memory region associated with the MD.
4991  *
4992  * Note that LNet does not guarantee the order of LNET_EVENT_SEND and
4993  * LNET_EVENT_ACK, though intuitively ACK should happen after SEND.
4994  *
4995  * \param self Indicates the NID of a local interface through which to send
4996  * the PUT request. Use LNET_NID_ANY to let LNet choose one by itself.
4997  * \param mdh A handle for the MD that describes the memory to be sent. The MD
4998  * must be "free floating" (See LNetMDBind()).
4999  * \param ack Controls whether an acknowledgment is requested.
5000  * Acknowledgments are only sent when they are requested by the initiating
5001  * process and the target MD enables them.
5002  * \param target A process identifier for the target process.
5003  * \param portal The index in the \a target's portal table.
5004  * \param match_bits The match bits to use for MD selection at the target
5005  * process.
5006  * \param offset The offset into the target MD (only used when the target
5007  * MD has the LNET_MD_MANAGE_REMOTE option set).
5008  * \param hdr_data 64 bits of user data that can be included in the message
5009  * header. This data is written to an event queue entry at the target if an
5010  * EQ is present on the matching MD.
5011  *
5012  * \retval  0      Success, and only in this case events will be generated
5013  * and logged to EQ (if it exists).
5014  * \retval -EIO    Simulated failure.
5015  * \retval -ENOMEM Memory allocation failure.
5016  * \retval -ENOENT Invalid MD object.
5017  *
5018  * \see struct lnet_event::hdr_data and lnet_event_kind_t.
5019  */
5020 int
5021 LNetPut(struct lnet_nid *self, struct lnet_handle_md mdh, enum lnet_ack_req ack,
5022         struct lnet_processid *target, unsigned int portal,
5023         __u64 match_bits, unsigned int offset,
5024         __u64 hdr_data)
5025 {
5026         struct lnet_msg *msg;
5027         struct lnet_libmd *md;
5028         int cpt;
5029         int rc;
5030         struct lnet_rsp_tracker *rspt = NULL;
5031
5032         LASSERT(the_lnet.ln_refcount > 0);
5033
5034         if (!list_empty(&the_lnet.ln_test_peers) &&     /* normally we don't */
5035             fail_peer(&target->nid, 1)) {               /* shall we now? */
5036                 CERROR("Dropping PUT to %s: simulated failure\n",
5037                        libcfs_idstr(target));
5038                 return -EIO;
5039         }
5040
5041         msg = lnet_msg_alloc();
5042         if (msg == NULL) {
5043                 CERROR("Dropping PUT to %s: ENOMEM on struct lnet_msg\n",
5044                        libcfs_idstr(target));
5045                 return -ENOMEM;
5046         }
5047         msg->msg_vmflush = !!(current->flags & PF_MEMALLOC);
5048
5049         cpt = lnet_cpt_of_cookie(mdh.cookie);
5050
5051         if (ack == LNET_ACK_REQ) {
5052                 rspt = lnet_rspt_alloc(cpt);
5053                 if (!rspt) {
5054                         CERROR("Dropping PUT to %s: ENOMEM on response tracker\n",
5055                                 libcfs_idstr(target));
5056                         return -ENOMEM;
5057                 }
5058                 INIT_LIST_HEAD(&rspt->rspt_on_list);
5059         }
5060
5061         lnet_res_lock(cpt);
5062
5063         md = lnet_handle2md(&mdh);
5064         if (md == NULL || md->md_threshold == 0 || md->md_me != NULL) {
5065                 CERROR("Dropping PUT (%llu:%d:%s): MD (%d) invalid\n",
5066                        match_bits, portal, libcfs_idstr(target),
5067                        md == NULL ? -1 : md->md_threshold);
5068                 if (md != NULL && md->md_me != NULL)
5069                         CERROR("Source MD also attached to portal %d\n",
5070                                md->md_me->me_portal);
5071                 lnet_res_unlock(cpt);
5072
5073                 if (rspt)
5074                         lnet_rspt_free(rspt, cpt);
5075
5076                 lnet_msg_free(msg);
5077                 return -ENOENT;
5078         }
5079
5080         CDEBUG(D_NET, "%s -> %s\n", __func__, libcfs_idstr(target));
5081
5082         lnet_msg_attach_md(msg, md, 0, 0);
5083
5084         lnet_prep_send(msg, LNET_MSG_PUT, target, 0, md->md_length);
5085
5086         msg->msg_hdr.msg.put.match_bits = cpu_to_le64(match_bits);
5087         msg->msg_hdr.msg.put.ptl_index = cpu_to_le32(portal);
5088         msg->msg_hdr.msg.put.offset = cpu_to_le32(offset);
5089         msg->msg_hdr.msg.put.hdr_data = hdr_data;
5090
5091         /* NB handles only looked up by creator (no flips) */
5092         if (ack == LNET_ACK_REQ) {
5093                 msg->msg_hdr.msg.put.ack_wmd.wh_interface_cookie =
5094                         the_lnet.ln_interface_cookie;
5095                 msg->msg_hdr.msg.put.ack_wmd.wh_object_cookie =
5096                         md->md_lh.lh_cookie;
5097         } else {
5098                 msg->msg_hdr.msg.put.ack_wmd.wh_interface_cookie =
5099                         LNET_WIRE_HANDLE_COOKIE_NONE;
5100                 msg->msg_hdr.msg.put.ack_wmd.wh_object_cookie =
5101                         LNET_WIRE_HANDLE_COOKIE_NONE;
5102         }
5103
5104         lnet_res_unlock(cpt);
5105
5106         lnet_build_msg_event(msg, LNET_EVENT_SEND);
5107
5108         if (rspt && lnet_response_tracking_enabled(LNET_MSG_PUT,
5109                                                    md->md_options))
5110                 lnet_attach_rsp_tracker(rspt, cpt, md, mdh);
5111         else if (rspt)
5112                 lnet_rspt_free(rspt, cpt);
5113
5114         if (CFS_FAIL_CHECK_ORSET(CFS_FAIL_PTLRPC_OST_BULK_CB2,
5115                                  CFS_FAIL_ONCE))
5116                 rc = -EIO;
5117         else
5118                 rc = lnet_send(self, msg, NULL);
5119
5120         if (rc != 0) {
5121                 CNETERR("Error sending PUT to %s: %d\n",
5122                         libcfs_idstr(target), rc);
5123                 msg->msg_no_resend = true;
5124                 lnet_finalize(msg, rc);
5125         }
5126
5127         /* completion will be signalled by an event */
5128         return 0;
5129 }
5130 EXPORT_SYMBOL(LNetPut);
5131
5132 /*
5133  * The LND can DMA direct to the GET md (i.e. no REPLY msg).  This
5134  * returns a msg for the LND to pass to lnet_finalize() when the sink
5135  * data has been received.
5136  *
5137  * CAVEAT EMPTOR: 'getmsg' is the original GET, which is freed when
5138  * lnet_finalize() is called on it, so the LND must call this first
5139  */
5140 struct lnet_msg *
5141 lnet_create_reply_msg(struct lnet_ni *ni, struct lnet_msg *getmsg)
5142 {
5143         struct lnet_msg *msg = lnet_msg_alloc();
5144         struct lnet_libmd *getmd = getmsg->msg_md;
5145         struct lnet_processid *peer_id = &getmsg->msg_target;
5146         int cpt;
5147
5148         LASSERT(!getmsg->msg_target_is_router);
5149         LASSERT(!getmsg->msg_routing);
5150
5151         if (msg == NULL) {
5152                 CERROR("%s: Dropping REPLY from %s: can't allocate msg\n",
5153                        libcfs_nidstr(&ni->ni_nid), libcfs_idstr(peer_id));
5154                 goto drop;
5155         }
5156
5157         cpt = lnet_cpt_of_cookie(getmd->md_lh.lh_cookie);
5158         lnet_res_lock(cpt);
5159
5160         LASSERT(getmd->md_refcount > 0);
5161
5162         if (getmd->md_threshold == 0) {
5163                 CERROR("%s: Dropping REPLY from %s for inactive MD %p\n",
5164                         libcfs_nidstr(&ni->ni_nid), libcfs_idstr(peer_id),
5165                         getmd);
5166                 lnet_res_unlock(cpt);
5167                 goto drop;
5168         }
5169
5170         LASSERT(getmd->md_offset == 0);
5171
5172         CDEBUG(D_NET, "%s: Reply from %s md %p\n",
5173                libcfs_nidstr(&ni->ni_nid), libcfs_idstr(peer_id), getmd);
5174
5175         /* setup information for lnet_build_msg_event */
5176         msg->msg_initiator =
5177                 getmsg->msg_txpeer->lpni_peer_net->lpn_peer->lp_primary_nid;
5178         msg->msg_from = peer_id->nid;
5179         msg->msg_type = LNET_MSG_GET; /* flag this msg as an "optimized" GET */
5180         msg->msg_hdr.src_nid = peer_id->nid;
5181         msg->msg_hdr.payload_length = getmd->md_length;
5182         msg->msg_receiving = 1; /* required by lnet_msg_attach_md */
5183
5184         lnet_msg_attach_md(msg, getmd, getmd->md_offset, getmd->md_length);
5185         lnet_res_unlock(cpt);
5186
5187         cpt = lnet_nid2cpt(&peer_id->nid, ni);
5188
5189         lnet_net_lock(cpt);
5190         lnet_msg_commit(msg, cpt);
5191         lnet_net_unlock(cpt);
5192
5193         lnet_build_msg_event(msg, LNET_EVENT_REPLY);
5194
5195         return msg;
5196
5197  drop:
5198         cpt = lnet_nid2cpt(&peer_id->nid, ni);
5199
5200         lnet_net_lock(cpt);
5201         lnet_incr_stats(&ni->ni_stats, LNET_MSG_GET, LNET_STATS_TYPE_DROP);
5202         the_lnet.ln_counters[cpt]->lct_common.lcc_drop_count++;
5203         the_lnet.ln_counters[cpt]->lct_common.lcc_drop_length +=
5204                 getmd->md_length;
5205         lnet_net_unlock(cpt);
5206
5207         if (msg != NULL)
5208                 lnet_msg_free(msg);
5209
5210         return NULL;
5211 }
5212 EXPORT_SYMBOL(lnet_create_reply_msg);
5213
5214 void
5215 lnet_set_reply_msg_len(struct lnet_ni *ni, struct lnet_msg *reply,
5216                        unsigned int len)
5217 {
5218         /* Set the REPLY length, now the RDMA that elides the REPLY message has
5219          * completed and I know it. */
5220         LASSERT(reply != NULL);
5221         LASSERT(reply->msg_type == LNET_MSG_GET);
5222         LASSERT(reply->msg_ev.type == LNET_EVENT_REPLY);
5223
5224         /* NB I trusted my peer to RDMA.  If she tells me she's written beyond
5225          * the end of my buffer, I might as well be dead. */
5226         LASSERT(len <= reply->msg_ev.mlength);
5227
5228         reply->msg_ev.mlength = len;
5229 }
5230 EXPORT_SYMBOL(lnet_set_reply_msg_len);
5231
5232 /**
5233  * Initiate an asynchronous GET operation.
5234  *
5235  * On the initiator node, an LNET_EVENT_SEND is logged when the GET request
5236  * is sent, and an LNET_EVENT_REPLY is logged when the data returned from
5237  * the target node in the REPLY has been written to local MD.
5238  *
5239  * On the target node, an LNET_EVENT_GET is logged when the GET request
5240  * arrives and is accepted into a MD.
5241  *
5242  * \param self,target,portal,match_bits,offset See the discussion in LNetPut().
5243  * \param mdh A handle for the MD that describes the memory into which the
5244  * requested data will be received. The MD must be "free floating" (See LNetMDBind()).
5245  *
5246  * \retval  0      Success, and only in this case events will be generated
5247  * and logged to EQ (if it exists) of the MD.
5248  * \retval -EIO    Simulated failure.
5249  * \retval -ENOMEM Memory allocation failure.
5250  * \retval -ENOENT Invalid MD object.
5251  */
5252 int
5253 LNetGet(struct lnet_nid *self, struct lnet_handle_md mdh,
5254         struct lnet_processid *target, unsigned int portal,
5255         __u64 match_bits, unsigned int offset, bool recovery)
5256 {
5257         struct lnet_msg *msg;
5258         struct lnet_libmd *md;
5259         struct lnet_rsp_tracker *rspt;
5260         int cpt;
5261         int rc;
5262
5263         LASSERT(the_lnet.ln_refcount > 0);
5264
5265         if (!list_empty(&the_lnet.ln_test_peers) &&     /* normally we don't */
5266             fail_peer(&target->nid, 1))         /* shall we now? */
5267         {
5268                 CERROR("Dropping GET to %s: simulated failure\n",
5269                        libcfs_idstr(target));
5270                 return -EIO;
5271         }
5272
5273         msg = lnet_msg_alloc();
5274         if (!msg) {
5275                 CERROR("Dropping GET to %s: ENOMEM on struct lnet_msg\n",
5276                        libcfs_idstr(target));
5277                 return -ENOMEM;
5278         }
5279
5280         cpt = lnet_cpt_of_cookie(mdh.cookie);
5281
5282         rspt = lnet_rspt_alloc(cpt);
5283         if (!rspt) {
5284                 CERROR("Dropping GET to %s: ENOMEM on response tracker\n",
5285                        libcfs_idstr(target));
5286                 return -ENOMEM;
5287         }
5288         INIT_LIST_HEAD(&rspt->rspt_on_list);
5289
5290         msg->msg_recovery = recovery;
5291
5292         lnet_res_lock(cpt);
5293
5294         md = lnet_handle2md(&mdh);
5295         if (md == NULL || md->md_threshold == 0 || md->md_me != NULL) {
5296                 CERROR("Dropping GET (%llu:%d:%s): MD (%d) invalid\n",
5297                        match_bits, portal, libcfs_idstr(target),
5298                        md == NULL ? -1 : md->md_threshold);
5299                 if (md != NULL && md->md_me != NULL)
5300                         CERROR("REPLY MD also attached to portal %d\n",
5301                                md->md_me->me_portal);
5302
5303                 lnet_res_unlock(cpt);
5304
5305                 lnet_msg_free(msg);
5306                 lnet_rspt_free(rspt, cpt);
5307                 return -ENOENT;
5308         }
5309
5310         CDEBUG(D_NET, "%s -> %s\n", __func__, libcfs_idstr(target));
5311
5312         lnet_msg_attach_md(msg, md, 0, 0);
5313
5314         lnet_prep_send(msg, LNET_MSG_GET, target, 0, 0);
5315
5316         msg->msg_hdr.msg.get.match_bits = cpu_to_le64(match_bits);
5317         msg->msg_hdr.msg.get.ptl_index = cpu_to_le32(portal);
5318         msg->msg_hdr.msg.get.src_offset = cpu_to_le32(offset);
5319         msg->msg_hdr.msg.get.sink_length = cpu_to_le32(md->md_length);
5320
5321         /* NB handles only looked up by creator (no flips) */
5322         msg->msg_hdr.msg.get.return_wmd.wh_interface_cookie =
5323                 the_lnet.ln_interface_cookie;
5324         msg->msg_hdr.msg.get.return_wmd.wh_object_cookie =
5325                 md->md_lh.lh_cookie;
5326
5327         lnet_res_unlock(cpt);
5328
5329         lnet_build_msg_event(msg, LNET_EVENT_SEND);
5330
5331         if (lnet_response_tracking_enabled(LNET_MSG_GET, md->md_options))
5332                 lnet_attach_rsp_tracker(rspt, cpt, md, mdh);
5333         else
5334                 lnet_rspt_free(rspt, cpt);
5335
5336         rc = lnet_send(self, msg, NULL);
5337         if (rc < 0) {
5338                 CNETERR("Error sending GET to %s: %d\n",
5339                         libcfs_idstr(target), rc);
5340                 msg->msg_no_resend = true;
5341                 lnet_finalize(msg, rc);
5342         }
5343
5344         /* completion will be signalled by an event */
5345         return 0;
5346 }
5347 EXPORT_SYMBOL(LNetGet);
5348
5349 /**
5350  * Calculate distance to node at \a dstnid.
5351  *
5352  * \param dstnid Target NID.
5353  * \param srcnidp If not NULL, NID of the local interface to reach \a dstnid
5354  * is saved here.
5355  * \param orderp If not NULL, order of the route to reach \a dstnid is saved
5356  * here.
5357  *
5358  * \retval 0 If \a dstnid belongs to a local interface, and reserved option
5359  * local_nid_dist_zero is set, which is the default.
5360  * \retval positives Distance to target NID, i.e. number of hops plus one.
5361  * \retval -EHOSTUNREACH If \a dstnid is not reachable.
5362  */
5363 int
5364 LNetDist(struct lnet_nid *dstnid, struct lnet_nid *srcnid, __u32 *orderp)
5365 {
5366         struct lnet_ni *ni = NULL;
5367         struct lnet_remotenet *rnet;
5368         __u32 dstnet = LNET_NID_NET(dstnid);
5369         int hops;
5370         int cpt;
5371         __u32 order = 2;
5372         struct list_head *rn_list;
5373         struct lnet_ni *matched_dstnet = NULL;
5374
5375         /* if !local_nid_dist_zero, I don't return a distance of 0 ever
5376          * (when lustre sees a distance of 0, it substitutes 0@lo), so I
5377          * keep order 0 free for 0@lo and order 1 free for a local NID
5378          * match
5379          * WARNING: dstnid and srcnid might point to same place.
5380          * Don't set *srcnid until late.
5381          */
5382
5383         LASSERT(the_lnet.ln_refcount > 0);
5384
5385         cpt = lnet_net_lock_current();
5386
5387         while ((ni = lnet_get_next_ni_locked(NULL, ni))) {
5388                 if (nid_same(&ni->ni_nid, dstnid)) {
5389                         if (orderp != NULL) {
5390                                 if (nid_is_lo0(dstnid))
5391                                         *orderp = 0;
5392                                 else
5393                                         *orderp = 1;
5394                         }
5395                         if (srcnid)
5396                                 *srcnid = *dstnid;
5397                         lnet_net_unlock(cpt);
5398
5399                         return local_nid_dist_zero ? 0 : 1;
5400                 }
5401
5402                 if (!matched_dstnet && LNET_NID_NET(&ni->ni_nid) == dstnet) {
5403                         matched_dstnet = ni;
5404                         /* We matched the destination net, but we may have
5405                          * additional local NIs to inspect.
5406                          *
5407                          * We record the order as appropriate, but
5408                          * they may be overwritten if we match local NI above.
5409                          */
5410
5411                         if (orderp) {
5412                                 /* Check if ni was originally created in
5413                                  * current net namespace.
5414                                  * If not, assign order above 0xffff0000,
5415                                  * to make this ni not a priority.
5416                                  */
5417                                 if (current->nsproxy &&
5418                                     !net_eq(ni->ni_net_ns,
5419                                             current->nsproxy->net_ns))
5420                                         *orderp = order + 0xffff0000;
5421                                 else
5422                                         *orderp = order;
5423                         }
5424                 }
5425
5426                 order++;
5427         }
5428
5429         if (matched_dstnet) {
5430                 if (srcnid)
5431                         *srcnid = matched_dstnet->ni_nid;
5432                 lnet_net_unlock(cpt);
5433                 return 1;
5434         }
5435
5436         rn_list = lnet_net2rnethash(dstnet);
5437         list_for_each_entry(rnet, rn_list, lrn_list) {
5438                 if (rnet->lrn_net == dstnet) {
5439                         struct lnet_route *route;
5440                         struct lnet_route *shortest = NULL;
5441                         __u32 shortest_hops = LNET_UNDEFINED_HOPS;
5442                         __u32 route_hops;
5443
5444                         LASSERT(!list_empty(&rnet->lrn_routes));
5445
5446                         list_for_each_entry(route, &rnet->lrn_routes,
5447                                             lr_list) {
5448                                 route_hops = route->lr_hops;
5449                                 if (route_hops == LNET_UNDEFINED_HOPS)
5450                                         route_hops = 1;
5451                                 if (shortest == NULL ||
5452                                     route_hops < shortest_hops) {
5453                                         shortest = route;
5454                                         shortest_hops = route_hops;
5455                                 }
5456                         }
5457
5458                         LASSERT(shortest != NULL);
5459                         hops = shortest_hops;
5460                         if (srcnid) {
5461                                 struct lnet_net *net;
5462                                 net = lnet_get_net_locked(shortest->lr_lnet);
5463                                 LASSERT(net);
5464                                 ni = lnet_get_next_ni_locked(net, NULL);
5465                                 *srcnid = ni->ni_nid;
5466                         }
5467                         if (orderp != NULL)
5468                                 *orderp = order;
5469                         lnet_net_unlock(cpt);
5470                         return hops + 1;
5471                 }
5472                 order++;
5473         }
5474
5475         lnet_net_unlock(cpt);
5476         return -EHOSTUNREACH;
5477 }
5478 EXPORT_SYMBOL(LNetDist);