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