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