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