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