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