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