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