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