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