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