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