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