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