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