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