Whamcloud - gitweb
LU-5435 lnet: lustre network latency simulation
[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.sun.com/software/products/lustre/docs/GPLv2.pdf
19  *
20  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
21  * CA 95054 USA or visit www.sun.com if you need additional information or
22  * have any questions.
23  *
24  * GPL HEADER END
25  */
26 /*
27  * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  *
30  * Copyright (c) 2012, 2013, Intel Corporation.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * lnet/lnet/lib-move.c
37  *
38  * Data movement routines
39  */
40
41 #define DEBUG_SUBSYSTEM S_LNET
42
43 #include <lnet/lib-lnet.h>
44
45 static int local_nid_dist_zero = 1;
46 CFS_MODULE_PARM(local_nid_dist_zero, "i", int, 0444,
47                 "Reserved");
48
49 int
50 lnet_fail_nid(lnet_nid_t nid, unsigned int threshold)
51 {
52         lnet_test_peer_t *tp;
53         struct list_head *el;
54         struct list_head *next;
55         struct list_head  cull;
56
57         LASSERT(the_lnet.ln_init);
58
59         /* NB: use lnet_net_lock(0) to serialize operations on test peers */
60         if (threshold != 0) {
61                 /* Adding a new entry */
62                 LIBCFS_ALLOC(tp, sizeof(*tp));
63                 if (tp == NULL)
64                         return -ENOMEM;
65
66                 tp->tp_nid = nid;
67                 tp->tp_threshold = threshold;
68
69                 lnet_net_lock(0);
70                 list_add_tail(&tp->tp_list, &the_lnet.ln_test_peers);
71                 lnet_net_unlock(0);
72                 return 0;
73         }
74
75         /* removing entries */
76         INIT_LIST_HEAD(&cull);
77
78         lnet_net_lock(0);
79
80         list_for_each_safe(el, next, &the_lnet.ln_test_peers) {
81                 tp = list_entry(el, lnet_test_peer_t, tp_list);
82
83                 if (tp->tp_threshold == 0 ||    /* needs culling anyway */
84                     nid == LNET_NID_ANY ||      /* removing all entries */
85                     tp->tp_nid == nid) {        /* matched this one */
86                         list_del(&tp->tp_list);
87                         list_add(&tp->tp_list, &cull);
88                 }
89         }
90
91         lnet_net_unlock(0);
92
93         while (!list_empty(&cull)) {
94                 tp = list_entry(cull.next, lnet_test_peer_t, tp_list);
95
96                 list_del(&tp->tp_list);
97                 LIBCFS_FREE(tp, sizeof(*tp));
98         }
99         return 0;
100 }
101
102 static int
103 fail_peer (lnet_nid_t nid, int outgoing)
104 {
105         lnet_test_peer_t *tp;
106         struct list_head *el;
107         struct list_head *next;
108         struct list_head  cull;
109         int               fail = 0;
110
111         INIT_LIST_HEAD(&cull);
112
113         /* NB: use lnet_net_lock(0) to serialize operations on test peers */
114         lnet_net_lock(0);
115
116         list_for_each_safe(el, next, &the_lnet.ln_test_peers) {
117                 tp = list_entry(el, lnet_test_peer_t, tp_list);
118
119                 if (tp->tp_threshold == 0) {
120                         /* zombie entry */
121                         if (outgoing) {
122                                 /* only cull zombies on outgoing tests,
123                                  * since we may be at interrupt priority on
124                                  * incoming messages. */
125                                 list_del(&tp->tp_list);
126                                 list_add(&tp->tp_list, &cull);
127                         }
128                         continue;
129                 }
130
131                 if (tp->tp_nid == LNET_NID_ANY ||       /* fail every peer */
132                     nid == tp->tp_nid) {                /* fail this peer */
133                         fail = 1;
134
135                         if (tp->tp_threshold != LNET_MD_THRESH_INF) {
136                                 tp->tp_threshold--;
137                                 if (outgoing &&
138                                     tp->tp_threshold == 0) {
139                                         /* see above */
140                                         list_del(&tp->tp_list);
141                                         list_add(&tp->tp_list, &cull);
142                                 }
143                         }
144                         break;
145                 }
146         }
147
148         lnet_net_unlock(0);
149
150         while (!list_empty(&cull)) {
151                 tp = list_entry(cull.next, lnet_test_peer_t, tp_list);
152                 list_del(&tp->tp_list);
153
154                 LIBCFS_FREE(tp, sizeof(*tp));
155         }
156
157         return fail;
158 }
159
160 unsigned int
161 lnet_iov_nob (unsigned int niov, struct iovec *iov)
162 {
163         unsigned int nob = 0;
164
165         LASSERT(niov == 0 || iov != NULL);
166         while (niov-- > 0)
167                 nob += (iov++)->iov_len;
168
169         return (nob);
170 }
171 EXPORT_SYMBOL(lnet_iov_nob);
172
173 void
174 lnet_copy_iov2iov (unsigned int ndiov, struct iovec *diov, unsigned int doffset,
175                    unsigned int nsiov, struct iovec *siov, unsigned int soffset,
176                    unsigned int nob)
177 {
178         /* NB diov, siov are READ-ONLY */
179         unsigned int  this_nob;
180
181         if (nob == 0)
182                 return;
183
184         /* skip complete frags before 'doffset' */
185         LASSERT (ndiov > 0);
186         while (doffset >= diov->iov_len) {
187                 doffset -= diov->iov_len;
188                 diov++;
189                 ndiov--;
190                 LASSERT (ndiov > 0);
191         }
192
193         /* skip complete frags before 'soffset' */
194         LASSERT (nsiov > 0);
195         while (soffset >= siov->iov_len) {
196                 soffset -= siov->iov_len;
197                 siov++;
198                 nsiov--;
199                 LASSERT (nsiov > 0);
200         }
201
202         do {
203                 LASSERT (ndiov > 0);
204                 LASSERT (nsiov > 0);
205                 this_nob = MIN(diov->iov_len - doffset,
206                                siov->iov_len - soffset);
207                 this_nob = MIN(this_nob, nob);
208
209                 memcpy ((char *)diov->iov_base + doffset,
210                         (char *)siov->iov_base + soffset, this_nob);
211                 nob -= this_nob;
212
213                 if (diov->iov_len > doffset + this_nob) {
214                         doffset += this_nob;
215                 } else {
216                         diov++;
217                         ndiov--;
218                         doffset = 0;
219                 }
220
221                 if (siov->iov_len > soffset + this_nob) {
222                         soffset += this_nob;
223                 } else {
224                         siov++;
225                         nsiov--;
226                         soffset = 0;
227                 }
228         } while (nob > 0);
229 }
230 EXPORT_SYMBOL(lnet_copy_iov2iov);
231
232 int
233 lnet_extract_iov (int dst_niov, struct iovec *dst,
234                   int src_niov, struct iovec *src,
235                   unsigned int offset, unsigned int len)
236 {
237         /* Initialise 'dst' to the subset of 'src' starting at 'offset',
238          * for exactly 'len' bytes, and return the number of entries.
239          * NB not destructive to 'src' */
240         unsigned int    frag_len;
241         unsigned int    niov;
242
243         if (len == 0)                           /* no data => */
244                 return (0);                     /* no frags */
245
246         LASSERT (src_niov > 0);
247         while (offset >= src->iov_len) {      /* skip initial frags */
248                 offset -= src->iov_len;
249                 src_niov--;
250                 src++;
251                 LASSERT (src_niov > 0);
252         }
253
254         niov = 1;
255         for (;;) {
256                 LASSERT (src_niov > 0);
257                 LASSERT ((int)niov <= dst_niov);
258
259                 frag_len = src->iov_len - offset;
260                 dst->iov_base = ((char *)src->iov_base) + offset;
261
262                 if (len <= frag_len) {
263                         dst->iov_len = len;
264                         return (niov);
265                 }
266
267                 dst->iov_len = frag_len;
268
269                 len -= frag_len;
270                 dst++;
271                 src++;
272                 niov++;
273                 src_niov--;
274                 offset = 0;
275         }
276 }
277 EXPORT_SYMBOL(lnet_extract_iov);
278
279 #ifndef __KERNEL__
280 unsigned int
281 lnet_kiov_nob (unsigned int niov, lnet_kiov_t *kiov)
282 {
283         LASSERT (0);
284         return (0);
285 }
286
287 void
288 lnet_copy_kiov2kiov (unsigned int ndkiov, lnet_kiov_t *dkiov, unsigned int doffset,
289                      unsigned int nskiov, lnet_kiov_t *skiov, unsigned int soffset,
290                      unsigned int nob)
291 {
292         LASSERT (0);
293 }
294
295 void
296 lnet_copy_kiov2iov (unsigned int niov, struct iovec *iov, unsigned int iovoffset,
297                     unsigned int nkiov, lnet_kiov_t *kiov, unsigned int kiovoffset,
298                     unsigned int nob)
299 {
300         LASSERT (0);
301 }
302
303 void
304 lnet_copy_iov2kiov (unsigned int nkiov, lnet_kiov_t *kiov, unsigned int kiovoffset,
305                     unsigned int niov, struct iovec *iov, unsigned int iovoffset,
306                     unsigned int nob)
307 {
308         LASSERT (0);
309 }
310
311 int
312 lnet_extract_kiov (int dst_niov, lnet_kiov_t *dst,
313                    int src_niov, lnet_kiov_t *src,
314                    unsigned int offset, unsigned int len)
315 {
316         LASSERT (0);
317 }
318
319 #else /* __KERNEL__ */
320
321 unsigned int
322 lnet_kiov_nob (unsigned int niov, lnet_kiov_t *kiov)
323 {
324         unsigned int  nob = 0;
325
326         LASSERT(niov == 0 || kiov != NULL);
327         while (niov-- > 0)
328                 nob += (kiov++)->kiov_len;
329
330         return (nob);
331 }
332 EXPORT_SYMBOL(lnet_kiov_nob);
333
334 void
335 lnet_copy_kiov2kiov (unsigned int ndiov, lnet_kiov_t *diov, unsigned int doffset,
336                      unsigned int nsiov, lnet_kiov_t *siov, unsigned int soffset,
337                      unsigned int nob)
338 {
339         /* NB diov, siov are READ-ONLY */
340         unsigned int    this_nob;
341         char           *daddr = NULL;
342         char           *saddr = NULL;
343
344         if (nob == 0)
345                 return;
346
347         LASSERT (!in_interrupt ());
348
349         LASSERT (ndiov > 0);
350         while (doffset >= diov->kiov_len) {
351                 doffset -= diov->kiov_len;
352                 diov++;
353                 ndiov--;
354                 LASSERT (ndiov > 0);
355         }
356
357         LASSERT (nsiov > 0);
358         while (soffset >= siov->kiov_len) {
359                 soffset -= siov->kiov_len;
360                 siov++;
361                 nsiov--;
362                 LASSERT (nsiov > 0);
363         }
364
365         do {
366                 LASSERT (ndiov > 0);
367                 LASSERT (nsiov > 0);
368                 this_nob = MIN(diov->kiov_len - doffset,
369                                siov->kiov_len - soffset);
370                 this_nob = MIN(this_nob, nob);
371
372                 if (daddr == NULL)
373                         daddr = ((char *)kmap(diov->kiov_page)) +
374                                 diov->kiov_offset + doffset;
375                 if (saddr == NULL)
376                         saddr = ((char *)kmap(siov->kiov_page)) +
377                                 siov->kiov_offset + soffset;
378
379                 /* Vanishing risk of kmap deadlock when mapping 2 pages.
380                  * However in practice at least one of the kiovs will be mapped
381                  * kernel pages and the map/unmap will be NOOPs */
382
383                 memcpy (daddr, saddr, this_nob);
384                 nob -= this_nob;
385
386                 if (diov->kiov_len > doffset + this_nob) {
387                         daddr += this_nob;
388                         doffset += this_nob;
389                 } else {
390                         kunmap(diov->kiov_page);
391                         daddr = NULL;
392                         diov++;
393                         ndiov--;
394                         doffset = 0;
395                 }
396
397                 if (siov->kiov_len > soffset + this_nob) {
398                         saddr += this_nob;
399                         soffset += this_nob;
400                 } else {
401                         kunmap(siov->kiov_page);
402                         saddr = NULL;
403                         siov++;
404                         nsiov--;
405                         soffset = 0;
406                 }
407         } while (nob > 0);
408
409         if (daddr != NULL)
410                 kunmap(diov->kiov_page);
411         if (saddr != NULL)
412                 kunmap(siov->kiov_page);
413 }
414 EXPORT_SYMBOL(lnet_copy_kiov2kiov);
415
416 void
417 lnet_copy_kiov2iov (unsigned int niov, struct iovec *iov, unsigned int iovoffset,
418                     unsigned int nkiov, lnet_kiov_t *kiov, unsigned int kiovoffset,
419                     unsigned int nob)
420 {
421         /* NB iov, kiov are READ-ONLY */
422         unsigned int    this_nob;
423         char           *addr = NULL;
424
425         if (nob == 0)
426                 return;
427
428         LASSERT (!in_interrupt ());
429
430         LASSERT (niov > 0);
431         while (iovoffset >= iov->iov_len) {
432                 iovoffset -= iov->iov_len;
433                 iov++;
434                 niov--;
435                 LASSERT (niov > 0);
436         }
437
438         LASSERT (nkiov > 0);
439         while (kiovoffset >= kiov->kiov_len) {
440                 kiovoffset -= kiov->kiov_len;
441                 kiov++;
442                 nkiov--;
443                 LASSERT (nkiov > 0);
444         }
445
446         do {
447                 LASSERT (niov > 0);
448                 LASSERT (nkiov > 0);
449                 this_nob = MIN(iov->iov_len - iovoffset,
450                                kiov->kiov_len - kiovoffset);
451                 this_nob = MIN(this_nob, nob);
452
453                 if (addr == NULL)
454                         addr = ((char *)kmap(kiov->kiov_page)) +
455                                 kiov->kiov_offset + kiovoffset;
456
457                 memcpy ((char *)iov->iov_base + iovoffset, addr, this_nob);
458                 nob -= this_nob;
459
460                 if (iov->iov_len > iovoffset + this_nob) {
461                         iovoffset += this_nob;
462                 } else {
463                         iov++;
464                         niov--;
465                         iovoffset = 0;
466                 }
467
468                 if (kiov->kiov_len > kiovoffset + this_nob) {
469                         addr += this_nob;
470                         kiovoffset += this_nob;
471                 } else {
472                         kunmap(kiov->kiov_page);
473                         addr = NULL;
474                         kiov++;
475                         nkiov--;
476                         kiovoffset = 0;
477                 }
478
479         } while (nob > 0);
480
481         if (addr != NULL)
482                 kunmap(kiov->kiov_page);
483 }
484 EXPORT_SYMBOL(lnet_copy_kiov2iov);
485
486 void
487 lnet_copy_iov2kiov (unsigned int nkiov, lnet_kiov_t *kiov, unsigned int kiovoffset,
488                     unsigned int niov, struct iovec *iov, unsigned int iovoffset,
489                     unsigned int nob)
490 {
491         /* NB kiov, iov 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 (nkiov > 0);
501         while (kiovoffset >= kiov->kiov_len) {
502                 kiovoffset -= kiov->kiov_len;
503                 kiov++;
504                 nkiov--;
505                 LASSERT (nkiov > 0);
506         }
507
508         LASSERT (niov > 0);
509         while (iovoffset >= iov->iov_len) {
510                 iovoffset -= iov->iov_len;
511                 iov++;
512                 niov--;
513                 LASSERT (niov > 0);
514         }
515
516         do {
517                 LASSERT (nkiov > 0);
518                 LASSERT (niov > 0);
519                 this_nob = MIN(kiov->kiov_len - kiovoffset,
520                                iov->iov_len - iovoffset);
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 (addr, (char *)iov->iov_base + iovoffset, this_nob);
528                 nob -= this_nob;
529
530                 if (kiov->kiov_len > kiovoffset + this_nob) {
531                         addr += this_nob;
532                         kiovoffset += this_nob;
533                 } else {
534                         kunmap(kiov->kiov_page);
535                         addr = NULL;
536                         kiov++;
537                         nkiov--;
538                         kiovoffset = 0;
539                 }
540
541                 if (iov->iov_len > iovoffset + this_nob) {
542                         iovoffset += this_nob;
543                 } else {
544                         iov++;
545                         niov--;
546                         iovoffset = 0;
547                 }
548         } while (nob > 0);
549
550         if (addr != NULL)
551                 kunmap(kiov->kiov_page);
552 }
553 EXPORT_SYMBOL(lnet_copy_iov2kiov);
554
555 int
556 lnet_extract_kiov (int dst_niov, lnet_kiov_t *dst,
557                    int src_niov, lnet_kiov_t *src,
558                    unsigned int offset, unsigned int len)
559 {
560         /* Initialise 'dst' to the subset of 'src' starting at 'offset',
561          * for exactly 'len' bytes, and return the number of entries.
562          * NB not destructive to 'src' */
563         unsigned int    frag_len;
564         unsigned int    niov;
565
566         if (len == 0)                           /* no data => */
567                 return (0);                     /* no frags */
568
569         LASSERT (src_niov > 0);
570         while (offset >= src->kiov_len) {      /* skip initial frags */
571                 offset -= src->kiov_len;
572                 src_niov--;
573                 src++;
574                 LASSERT (src_niov > 0);
575         }
576
577         niov = 1;
578         for (;;) {
579                 LASSERT (src_niov > 0);
580                 LASSERT ((int)niov <= dst_niov);
581
582                 frag_len = src->kiov_len - offset;
583                 dst->kiov_page = src->kiov_page;
584                 dst->kiov_offset = src->kiov_offset + offset;
585
586                 if (len <= frag_len) {
587                         dst->kiov_len = len;
588                         LASSERT (dst->kiov_offset + dst->kiov_len <= PAGE_CACHE_SIZE);
589                         return niov;
590                 }
591
592                 dst->kiov_len = frag_len;
593                 LASSERT (dst->kiov_offset + dst->kiov_len <= PAGE_CACHE_SIZE);
594
595                 len -= frag_len;
596                 dst++;
597                 src++;
598                 niov++;
599                 src_niov--;
600                 offset = 0;
601         }
602 }
603 EXPORT_SYMBOL(lnet_extract_kiov);
604 #endif
605
606 void
607 lnet_ni_recv(lnet_ni_t *ni, void *private, lnet_msg_t *msg, int delayed,
608              unsigned int offset, unsigned int mlen, unsigned int rlen)
609 {
610         unsigned int  niov = 0;
611         struct iovec *iov = NULL;
612         lnet_kiov_t  *kiov = NULL;
613         int           rc;
614
615         LASSERT (!in_interrupt ());
616         LASSERT (mlen == 0 || msg != NULL);
617
618         if (msg != NULL) {
619                 LASSERT(msg->msg_receiving);
620                 LASSERT(!msg->msg_sending);
621                 LASSERT(rlen == msg->msg_len);
622                 LASSERT(mlen <= msg->msg_len);
623                 LASSERT(msg->msg_offset == offset);
624                 LASSERT(msg->msg_wanted == mlen);
625
626                 msg->msg_receiving = 0;
627
628                 if (mlen != 0) {
629                         niov = msg->msg_niov;
630                         iov  = msg->msg_iov;
631                         kiov = msg->msg_kiov;
632
633                         LASSERT (niov > 0);
634                         LASSERT ((iov == NULL) != (kiov == NULL));
635                 }
636         }
637
638         rc = (ni->ni_lnd->lnd_recv)(ni, private, msg, delayed,
639                                     niov, iov, kiov, offset, mlen, rlen);
640         if (rc < 0)
641                 lnet_finalize(ni, msg, rc);
642 }
643
644 void
645 lnet_setpayloadbuffer(lnet_msg_t *msg)
646 {
647         lnet_libmd_t *md = msg->msg_md;
648
649         LASSERT (msg->msg_len > 0);
650         LASSERT (!msg->msg_routing);
651         LASSERT (md != NULL);
652         LASSERT (msg->msg_niov == 0);
653         LASSERT (msg->msg_iov == NULL);
654         LASSERT (msg->msg_kiov == NULL);
655
656         msg->msg_niov = md->md_niov;
657         if ((md->md_options & LNET_MD_KIOV) != 0)
658                 msg->msg_kiov = md->md_iov.kiov;
659         else
660                 msg->msg_iov = md->md_iov.iov;
661 }
662
663 void
664 lnet_prep_send(lnet_msg_t *msg, int type, lnet_process_id_t target,
665                unsigned int offset, unsigned int len) 
666 {
667         msg->msg_type = type;
668         msg->msg_target = target;
669         msg->msg_len = len;
670         msg->msg_offset = offset;
671
672         if (len != 0)
673                 lnet_setpayloadbuffer(msg);
674
675         memset (&msg->msg_hdr, 0, sizeof (msg->msg_hdr));
676         msg->msg_hdr.type           = cpu_to_le32(type);
677         msg->msg_hdr.dest_nid       = cpu_to_le64(target.nid);
678         msg->msg_hdr.dest_pid       = cpu_to_le32(target.pid);
679         /* src_nid will be set later */
680         msg->msg_hdr.src_pid        = cpu_to_le32(the_lnet.ln_pid);
681         msg->msg_hdr.payload_length = cpu_to_le32(len);
682 }
683
684 void
685 lnet_ni_send(lnet_ni_t *ni, lnet_msg_t *msg)
686 {
687         void   *priv = msg->msg_private;
688         int     rc;
689
690         LASSERT (!in_interrupt ());
691         LASSERT (LNET_NETTYP(LNET_NIDNET(ni->ni_nid)) == LOLND ||
692                  (msg->msg_txcredit && msg->msg_peertxcredit));
693
694         rc = (ni->ni_lnd->lnd_send)(ni, priv, msg);
695         if (rc < 0)
696                 lnet_finalize(ni, msg, rc);
697 }
698
699 int
700 lnet_ni_eager_recv(lnet_ni_t *ni, lnet_msg_t *msg)
701 {
702         int     rc;
703
704         LASSERT(!msg->msg_sending);
705         LASSERT(msg->msg_receiving);
706         LASSERT(!msg->msg_rx_ready_delay);
707         LASSERT(ni->ni_lnd->lnd_eager_recv != NULL);
708
709         msg->msg_rx_ready_delay = 1;
710         rc = (ni->ni_lnd->lnd_eager_recv)(ni, msg->msg_private, msg,
711                                           &msg->msg_private);
712         if (rc != 0) {
713                 CERROR("recv from %s / send to %s aborted: "
714                        "eager_recv failed %d\n",
715                        libcfs_nid2str(msg->msg_rxpeer->lp_nid),
716                        libcfs_id2str(msg->msg_target), rc);
717                 LASSERT(rc < 0); /* required by my callers */
718         }
719
720         return rc;
721 }
722
723 /* NB: caller shall hold a ref on 'lp' as I'd drop lnet_net_lock */
724 void
725 lnet_ni_query_locked(lnet_ni_t *ni, lnet_peer_t *lp)
726 {
727         cfs_time_t last_alive = 0;
728
729         LASSERT(lnet_peer_aliveness_enabled(lp));
730         LASSERT(ni->ni_lnd->lnd_query != NULL);
731
732         lnet_net_unlock(lp->lp_cpt);
733         (ni->ni_lnd->lnd_query)(ni, lp->lp_nid, &last_alive);
734         lnet_net_lock(lp->lp_cpt);
735
736         lp->lp_last_query = cfs_time_current();
737
738         if (last_alive != 0) /* NI has updated timestamp */
739                 lp->lp_last_alive = last_alive;
740 }
741
742 /* NB: always called with lnet_net_lock held */
743 static inline int
744 lnet_peer_is_alive (lnet_peer_t *lp, cfs_time_t now)
745 {
746         int        alive;
747         cfs_time_t deadline;
748
749         LASSERT (lnet_peer_aliveness_enabled(lp));
750
751         /* Trust lnet_notify() if it has more recent aliveness news, but
752          * ignore the initial assumed death (see lnet_peers_start_down()).
753          */
754         if (!lp->lp_alive && lp->lp_alive_count > 0 &&
755             cfs_time_aftereq(lp->lp_timestamp, lp->lp_last_alive))
756                 return 0;
757
758         deadline = cfs_time_add(lp->lp_last_alive,
759                                 cfs_time_seconds(lp->lp_ni->ni_peertimeout));
760         alive = cfs_time_after(deadline, now);
761
762         /* Update obsolete lp_alive except for routers assumed to be dead
763          * initially, because router checker would update aliveness in this
764          * case, and moreover lp_last_alive at peer creation is assumed.
765          */
766         if (alive && !lp->lp_alive &&
767             !(lnet_isrouter(lp) && lp->lp_alive_count == 0))
768                 lnet_notify_locked(lp, 0, 1, lp->lp_last_alive);
769
770         return alive;
771 }
772
773
774 /* NB: returns 1 when alive, 0 when dead, negative when error;
775  *     may drop the lnet_net_lock */
776 int
777 lnet_peer_alive_locked (lnet_peer_t *lp)
778 {
779         cfs_time_t now = cfs_time_current();
780
781         if (!lnet_peer_aliveness_enabled(lp))
782                 return -ENODEV;
783
784         if (lnet_peer_is_alive(lp, now))
785                 return 1;
786
787         /* Peer appears dead, but we should avoid frequent NI queries (at
788          * most once per lnet_queryinterval seconds). */
789         if (lp->lp_last_query != 0) {
790                 static const int lnet_queryinterval = 1;
791
792                 cfs_time_t next_query =
793                            cfs_time_add(lp->lp_last_query,
794                                         cfs_time_seconds(lnet_queryinterval));
795
796                 if (cfs_time_before(now, next_query)) {
797                         if (lp->lp_alive)
798                                 CWARN("Unexpected aliveness of peer %s: "
799                                       "%d < %d (%d/%d)\n",
800                                       libcfs_nid2str(lp->lp_nid),
801                                       (int)now, (int)next_query,
802                                       lnet_queryinterval,
803                                       lp->lp_ni->ni_peertimeout);
804                         return 0;
805                 }
806         }
807
808         /* query NI for latest aliveness news */
809         lnet_ni_query_locked(lp->lp_ni, lp);
810
811         if (lnet_peer_is_alive(lp, now))
812                 return 1;
813
814         lnet_notify_locked(lp, 0, 0, lp->lp_last_alive);
815         return 0;
816 }
817
818 /**
819  * \param msg The message to be sent.
820  * \param do_send True if lnet_ni_send() should be called in this function.
821  *        lnet_send() is going to lnet_net_unlock immediately after this, so
822  *        it sets do_send FALSE and I don't do the unlock/send/lock bit.
823  *
824  * \retval LNET_CREDIT_OK If \a msg sent or OK to send.
825  * \retval LNET_CREDIT_WAIT If \a msg blocked for credit.
826  * \retval -EHOSTUNREACH If the next hop of the message appears dead.
827  * \retval -ECANCELED If the MD of the message has been unlinked.
828  */
829 static int
830 lnet_post_send_locked(lnet_msg_t *msg, int do_send)
831 {
832         lnet_peer_t             *lp = msg->msg_txpeer;
833         lnet_ni_t               *ni = lp->lp_ni;
834         int                     cpt = msg->msg_tx_cpt;
835         struct lnet_tx_queue    *tq = ni->ni_tx_queues[cpt];
836
837         /* non-lnet_send() callers have checked before */
838         LASSERT(!do_send || msg->msg_tx_delayed);
839         LASSERT(!msg->msg_receiving);
840         LASSERT(msg->msg_tx_committed);
841
842         /* NB 'lp' is always the next hop */
843         if ((msg->msg_target.pid & LNET_PID_USERFLAG) == 0 &&
844             lnet_peer_alive_locked(lp) == 0) {
845                 the_lnet.ln_counters[cpt]->drop_count++;
846                 the_lnet.ln_counters[cpt]->drop_length += msg->msg_len;
847                 lnet_net_unlock(cpt);
848
849                 CNETERR("Dropping message for %s: peer not alive\n",
850                         libcfs_id2str(msg->msg_target));
851                 if (do_send)
852                         lnet_finalize(ni, msg, -EHOSTUNREACH);
853
854                 lnet_net_lock(cpt);
855                 return -EHOSTUNREACH;
856         }
857
858         if (msg->msg_md != NULL &&
859             (msg->msg_md->md_flags & LNET_MD_FLAG_ABORTED) != 0) {
860                 lnet_net_unlock(cpt);
861
862                 CNETERR("Aborting message for %s: LNetM[DE]Unlink() already "
863                         "called on the MD/ME.\n",
864                         libcfs_id2str(msg->msg_target));
865                 if (do_send)
866                         lnet_finalize(ni, msg, -ECANCELED);
867
868                 lnet_net_lock(cpt);
869                 return -ECANCELED;
870         }
871
872         if (!msg->msg_peertxcredit) {
873                 LASSERT((lp->lp_txcredits < 0) ==
874                         !list_empty(&lp->lp_txq));
875
876                 msg->msg_peertxcredit = 1;
877                 lp->lp_txqnob += msg->msg_len + sizeof(lnet_hdr_t);
878                 lp->lp_txcredits--;
879
880                 if (lp->lp_txcredits < lp->lp_mintxcredits)
881                         lp->lp_mintxcredits = lp->lp_txcredits;
882
883                 if (lp->lp_txcredits < 0) {
884                         msg->msg_tx_delayed = 1;
885                         list_add_tail(&msg->msg_list, &lp->lp_txq);
886                         return LNET_CREDIT_WAIT;
887                 }
888         }
889
890         if (!msg->msg_txcredit) {
891                 LASSERT((tq->tq_credits < 0) ==
892                         !list_empty(&tq->tq_delayed));
893
894                 msg->msg_txcredit = 1;
895                 tq->tq_credits--;
896
897                 if (tq->tq_credits < tq->tq_credits_min)
898                         tq->tq_credits_min = tq->tq_credits;
899
900                 if (tq->tq_credits < 0) {
901                         msg->msg_tx_delayed = 1;
902                         list_add_tail(&msg->msg_list, &tq->tq_delayed);
903                         return LNET_CREDIT_WAIT;
904                 }
905         }
906
907         if (do_send) {
908                 lnet_net_unlock(cpt);
909                 lnet_ni_send(ni, msg);
910                 lnet_net_lock(cpt);
911         }
912         return LNET_CREDIT_OK;
913 }
914
915 #ifdef __KERNEL__
916
917 lnet_rtrbufpool_t *
918 lnet_msg2bufpool(lnet_msg_t *msg)
919 {
920         lnet_rtrbufpool_t       *rbp;
921         int                     cpt;
922
923         LASSERT(msg->msg_rx_committed);
924
925         cpt = msg->msg_rx_cpt;
926         rbp = &the_lnet.ln_rtrpools[cpt][0];
927
928         LASSERT(msg->msg_len <= LNET_MTU);
929         while (msg->msg_len > (unsigned int)rbp->rbp_npages * PAGE_CACHE_SIZE) {
930                 rbp++;
931                 LASSERT(rbp < &the_lnet.ln_rtrpools[cpt][LNET_NRBPOOLS]);
932         }
933
934         return rbp;
935 }
936
937 int
938 lnet_post_routed_recv_locked (lnet_msg_t *msg, int do_recv)
939 {
940         /* lnet_parse is going to lnet_net_unlock immediately after this, so it
941          * sets do_recv FALSE and I don't do the unlock/send/lock bit.
942          * I return LNET_CREDIT_WAIT if msg blocked and LNET_CREDIT_OK if
943          * received or OK to receive */
944         lnet_peer_t         *lp = msg->msg_rxpeer;
945         lnet_rtrbufpool_t   *rbp;
946         lnet_rtrbuf_t       *rb;
947
948         LASSERT (msg->msg_iov == NULL);
949         LASSERT (msg->msg_kiov == NULL);
950         LASSERT (msg->msg_niov == 0);
951         LASSERT (msg->msg_routing);
952         LASSERT (msg->msg_receiving);
953         LASSERT (!msg->msg_sending);
954
955         /* non-lnet_parse callers only receive delayed messages */
956         LASSERT(!do_recv || msg->msg_rx_delayed);
957
958         if (!msg->msg_peerrtrcredit) {
959                 LASSERT((lp->lp_rtrcredits < 0) ==
960                         !list_empty(&lp->lp_rtrq));
961
962                 msg->msg_peerrtrcredit = 1;
963                 lp->lp_rtrcredits--;
964                 if (lp->lp_rtrcredits < lp->lp_minrtrcredits)
965                         lp->lp_minrtrcredits = lp->lp_rtrcredits;
966
967                 if (lp->lp_rtrcredits < 0) {
968                         /* must have checked eager_recv before here */
969                         LASSERT(msg->msg_rx_ready_delay);
970                         msg->msg_rx_delayed = 1;
971                         list_add_tail(&msg->msg_list, &lp->lp_rtrq);
972                         return LNET_CREDIT_WAIT;
973                 }
974         }
975
976         rbp = lnet_msg2bufpool(msg);
977
978         if (!msg->msg_rtrcredit) {
979                 msg->msg_rtrcredit = 1;
980                 rbp->rbp_credits--;
981                 if (rbp->rbp_credits < rbp->rbp_mincredits)
982                         rbp->rbp_mincredits = rbp->rbp_credits;
983
984                 if (rbp->rbp_credits < 0) {
985                         /* must have checked eager_recv before here */
986                         LASSERT(msg->msg_rx_ready_delay);
987                         msg->msg_rx_delayed = 1;
988                         list_add_tail(&msg->msg_list, &rbp->rbp_msgs);
989                         return LNET_CREDIT_WAIT;
990                 }
991         }
992
993         LASSERT(!list_empty(&rbp->rbp_bufs));
994         rb = list_entry(rbp->rbp_bufs.next, lnet_rtrbuf_t, rb_list);
995         list_del(&rb->rb_list);
996
997         msg->msg_niov = rbp->rbp_npages;
998         msg->msg_kiov = &rb->rb_kiov[0];
999
1000         if (do_recv) {
1001                 int cpt = msg->msg_rx_cpt;
1002
1003                 lnet_net_unlock(cpt);
1004                 lnet_ni_recv(lp->lp_ni, msg->msg_private, msg, 1,
1005                              0, msg->msg_len, msg->msg_len);
1006                 lnet_net_lock(cpt);
1007         }
1008         return LNET_CREDIT_OK;
1009 }
1010 #endif
1011
1012 void
1013 lnet_return_tx_credits_locked(lnet_msg_t *msg)
1014 {
1015         lnet_peer_t     *txpeer = msg->msg_txpeer;
1016         lnet_msg_t      *msg2;
1017
1018         if (msg->msg_txcredit) {
1019                 struct lnet_ni       *ni = txpeer->lp_ni;
1020                 struct lnet_tx_queue *tq = ni->ni_tx_queues[msg->msg_tx_cpt];
1021
1022                 /* give back NI txcredits */
1023                 msg->msg_txcredit = 0;
1024
1025                 LASSERT((tq->tq_credits < 0) ==
1026                         !list_empty(&tq->tq_delayed));
1027
1028                 tq->tq_credits++;
1029                 if (tq->tq_credits <= 0) {
1030                         msg2 = list_entry(tq->tq_delayed.next,
1031                                           lnet_msg_t, msg_list);
1032                         list_del(&msg2->msg_list);
1033
1034                         LASSERT(msg2->msg_txpeer->lp_ni == ni);
1035                         LASSERT(msg2->msg_tx_delayed);
1036
1037                         (void) lnet_post_send_locked(msg2, 1);
1038                 }
1039         }
1040
1041         if (msg->msg_peertxcredit) {
1042                 /* give back peer txcredits */
1043                 msg->msg_peertxcredit = 0;
1044
1045                 LASSERT((txpeer->lp_txcredits < 0) ==
1046                         !list_empty(&txpeer->lp_txq));
1047
1048                 txpeer->lp_txqnob -= msg->msg_len + sizeof(lnet_hdr_t);
1049                 LASSERT (txpeer->lp_txqnob >= 0);
1050
1051                 txpeer->lp_txcredits++;
1052                 if (txpeer->lp_txcredits <= 0) {
1053                         msg2 = list_entry(txpeer->lp_txq.next,
1054                                               lnet_msg_t, msg_list);
1055                         list_del(&msg2->msg_list);
1056
1057                         LASSERT(msg2->msg_txpeer == txpeer);
1058                         LASSERT(msg2->msg_tx_delayed);
1059
1060                         (void) lnet_post_send_locked(msg2, 1);
1061                 }
1062         }
1063
1064         if (txpeer != NULL) {
1065                 msg->msg_txpeer = NULL;
1066                 lnet_peer_decref_locked(txpeer);
1067         }
1068 }
1069
1070 #ifdef __KERNEL__
1071 void
1072 lnet_schedule_blocked_locked(lnet_rtrbufpool_t *rbp)
1073 {
1074         lnet_msg_t      *msg;
1075
1076         if (list_empty(&rbp->rbp_msgs))
1077                 return;
1078         msg = list_entry(rbp->rbp_msgs.next,
1079                          lnet_msg_t, msg_list);
1080         list_del(&msg->msg_list);
1081
1082         (void)lnet_post_routed_recv_locked(msg, 1);
1083 }
1084 #endif
1085
1086 void
1087 lnet_drop_routed_msgs_locked(struct list_head *list, int cpt)
1088 {
1089         lnet_msg_t       *msg;
1090         lnet_msg_t       *tmp;
1091         struct list_head drop;
1092
1093         INIT_LIST_HEAD(&drop);
1094
1095         list_splice_init(list, &drop);
1096
1097         lnet_net_unlock(cpt);
1098
1099         list_for_each_entry_safe(msg, tmp, &drop, msg_list) {
1100                 lnet_ni_recv(msg->msg_rxpeer->lp_ni, msg->msg_private, NULL,
1101                              0, 0, 0, msg->msg_hdr.payload_length);
1102                 list_del_init(&msg->msg_list);
1103                 lnet_finalize(NULL, msg, -ECANCELED);
1104         }
1105
1106         lnet_net_lock(cpt);
1107 }
1108
1109 void
1110 lnet_return_rx_credits_locked(lnet_msg_t *msg)
1111 {
1112         lnet_peer_t     *rxpeer = msg->msg_rxpeer;
1113 #ifdef __KERNEL__
1114         lnet_msg_t      *msg2;
1115
1116         if (msg->msg_rtrcredit) {
1117                 /* give back global router credits */
1118                 lnet_rtrbuf_t     *rb;
1119                 lnet_rtrbufpool_t *rbp;
1120
1121                 /* NB If a msg ever blocks for a buffer in rbp_msgs, it stays
1122                  * there until it gets one allocated, or aborts the wait
1123                  * itself */
1124                 LASSERT(msg->msg_kiov != NULL);
1125
1126                 rb = list_entry(msg->msg_kiov, lnet_rtrbuf_t, rb_kiov[0]);
1127                 rbp = rb->rb_pool;
1128
1129                 msg->msg_kiov = NULL;
1130                 msg->msg_rtrcredit = 0;
1131
1132                 LASSERT(rbp == lnet_msg2bufpool(msg));
1133
1134                 LASSERT((rbp->rbp_credits > 0) ==
1135                         !list_empty(&rbp->rbp_bufs));
1136
1137                 /* If routing is now turned off, we just drop this buffer and
1138                  * don't bother trying to return credits.  */
1139                 if (!the_lnet.ln_routing) {
1140                         lnet_destroy_rtrbuf(rb, rbp->rbp_npages);
1141                         goto routing_off;
1142                 }
1143
1144                 /* It is possible that a user has lowered the desired number of
1145                  * buffers in this pool.  Make sure we never put back
1146                  * more buffers than the stated number. */
1147                 if (rbp->rbp_credits >= rbp->rbp_nbuffers) {
1148                         /* Discard this buffer so we don't have too many. */
1149                         lnet_destroy_rtrbuf(rb, rbp->rbp_npages);
1150                 } else {
1151                         list_add(&rb->rb_list, &rbp->rbp_bufs);
1152                         rbp->rbp_credits++;
1153                         if (rbp->rbp_credits <= 0)
1154                                 lnet_schedule_blocked_locked(rbp);
1155                 }
1156         }
1157
1158 routing_off:
1159         if (msg->msg_peerrtrcredit) {
1160                 /* give back peer router credits */
1161                 msg->msg_peerrtrcredit = 0;
1162
1163                 LASSERT((rxpeer->lp_rtrcredits < 0) ==
1164                         !list_empty(&rxpeer->lp_rtrq));
1165
1166                 rxpeer->lp_rtrcredits++;
1167
1168                 /* drop all messages which are queued to be routed on that
1169                  * peer. */
1170                 if (!the_lnet.ln_routing) {
1171                         lnet_drop_routed_msgs_locked(&rxpeer->lp_rtrq,
1172                                                      msg->msg_rx_cpt);
1173                 } else if (rxpeer->lp_rtrcredits <= 0) {
1174                         msg2 = list_entry(rxpeer->lp_rtrq.next,
1175                                           lnet_msg_t, msg_list);
1176                         list_del(&msg2->msg_list);
1177
1178                         (void) lnet_post_routed_recv_locked(msg2, 1);
1179                 }
1180         }
1181 #else
1182         LASSERT(!msg->msg_rtrcredit);
1183         LASSERT(!msg->msg_peerrtrcredit);
1184 #endif
1185         if (rxpeer != NULL) {
1186                 msg->msg_rxpeer = NULL;
1187                 lnet_peer_decref_locked(rxpeer);
1188         }
1189 }
1190
1191 static int
1192 lnet_compare_routes(lnet_route_t *r1, lnet_route_t *r2)
1193 {
1194         lnet_peer_t *p1 = r1->lr_gateway;
1195         lnet_peer_t *p2 = r2->lr_gateway;
1196
1197         if (r1->lr_priority < r2->lr_priority)
1198                 return 1;
1199
1200         if (r1->lr_priority > r2->lr_priority)
1201                 return -1;
1202
1203         if (r1->lr_hops < r2->lr_hops)
1204                 return 1;
1205
1206         if (r1->lr_hops > r2->lr_hops)
1207                 return -1;
1208
1209         if (p1->lp_txqnob < p2->lp_txqnob)
1210                 return 1;
1211
1212         if (p1->lp_txqnob > p2->lp_txqnob)
1213                 return -1;
1214
1215         if (p1->lp_txcredits > p2->lp_txcredits)
1216                 return 1;
1217
1218         if (p1->lp_txcredits < p2->lp_txcredits)
1219                 return -1;
1220
1221         if (r1->lr_seq - r2->lr_seq <= 0)
1222                 return 1;
1223
1224         return -1;
1225 }
1226
1227 static lnet_peer_t *
1228 lnet_find_route_locked(lnet_ni_t *ni, lnet_nid_t target, lnet_nid_t rtr_nid)
1229 {
1230         lnet_remotenet_t        *rnet;
1231         lnet_route_t            *route;
1232         lnet_route_t            *best_route;
1233         lnet_route_t            *last_route;
1234         struct lnet_peer        *lp_best;
1235         struct lnet_peer        *lp;
1236         int                     rc;
1237
1238         /* If @rtr_nid is not LNET_NID_ANY, return the gateway with
1239          * rtr_nid nid, otherwise find the best gateway I can use */
1240
1241         rnet = lnet_find_net_locked(LNET_NIDNET(target));
1242         if (rnet == NULL)
1243                 return NULL;
1244
1245         lp_best = NULL;
1246         best_route = last_route = NULL;
1247         list_for_each_entry(route, &rnet->lrn_routes, lr_list) {
1248                 lp = route->lr_gateway;
1249
1250                 if (!lnet_is_route_alive(route))
1251                         continue;
1252
1253                 if (ni != NULL && lp->lp_ni != ni)
1254                         continue;
1255
1256                 if (lp->lp_nid == rtr_nid) /* it's pre-determined router */
1257                         return lp;
1258
1259                 if (lp_best == NULL) {
1260                         best_route = last_route = route;
1261                         lp_best = lp;
1262                         continue;
1263                 }
1264
1265                 /* no protection on below fields, but it's harmless */
1266                 if (last_route->lr_seq - route->lr_seq < 0)
1267                         last_route = route;
1268
1269                 rc = lnet_compare_routes(route, best_route);
1270                 if (rc < 0)
1271                         continue;
1272
1273                 best_route = route;
1274                 lp_best = lp;
1275         }
1276
1277         /* set sequence number on the best router to the latest sequence + 1
1278          * so we can round-robin all routers, it's race and inaccurate but
1279          * harmless and functional  */
1280         if (best_route != NULL)
1281                 best_route->lr_seq = last_route->lr_seq + 1;
1282         return lp_best;
1283 }
1284
1285 int
1286 lnet_send(lnet_nid_t src_nid, lnet_msg_t *msg, lnet_nid_t rtr_nid)
1287 {
1288         lnet_nid_t              dst_nid = msg->msg_target.nid;
1289         struct lnet_ni          *src_ni;
1290         struct lnet_ni          *local_ni;
1291         struct lnet_peer        *lp;
1292         int                     cpt;
1293         int                     cpt2;
1294         int                     rc;
1295
1296         /* NB: rtr_nid is set to LNET_NID_ANY for all current use-cases,
1297          * but we might want to use pre-determined router for ACK/REPLY
1298          * in the future */
1299         /* NB: ni != NULL == interface pre-determined (ACK/REPLY) */
1300         LASSERT (msg->msg_txpeer == NULL);
1301         LASSERT (!msg->msg_sending);
1302         LASSERT (!msg->msg_target_is_router);
1303         LASSERT (!msg->msg_receiving);
1304
1305         msg->msg_sending = 1;
1306
1307         LASSERT(!msg->msg_tx_committed);
1308         cpt = lnet_cpt_of_nid(rtr_nid == LNET_NID_ANY ? dst_nid : rtr_nid);
1309  again:
1310         lnet_net_lock(cpt);
1311
1312         if (the_lnet.ln_shutdown) {
1313                 lnet_net_unlock(cpt);
1314                 return -ESHUTDOWN;
1315         }
1316
1317         if (src_nid == LNET_NID_ANY) {
1318                 src_ni = NULL;
1319         } else {
1320                 src_ni = lnet_nid2ni_locked(src_nid, cpt);
1321                 if (src_ni == NULL) {
1322                         lnet_net_unlock(cpt);
1323                         LCONSOLE_WARN("Can't send to %s: src %s is not a "
1324                                       "local nid\n", libcfs_nid2str(dst_nid),
1325                                       libcfs_nid2str(src_nid));
1326                         return -EINVAL;
1327                 }
1328                 LASSERT (!msg->msg_routing);
1329         }
1330
1331         /* Is this for someone on a local network? */
1332         local_ni = lnet_net2ni_locked(LNET_NIDNET(dst_nid), cpt);
1333
1334         if (local_ni != NULL) {
1335                 if (src_ni == NULL) {
1336                         src_ni = local_ni;
1337                         src_nid = src_ni->ni_nid;
1338                 } else if (src_ni == local_ni) {
1339                         lnet_ni_decref_locked(local_ni, cpt);
1340                 } else {
1341                         lnet_ni_decref_locked(local_ni, cpt);
1342                         lnet_ni_decref_locked(src_ni, cpt);
1343                         lnet_net_unlock(cpt);
1344                         LCONSOLE_WARN("No route to %s via from %s\n",
1345                                       libcfs_nid2str(dst_nid),
1346                                       libcfs_nid2str(src_nid));
1347                         return -EINVAL;
1348                 }
1349
1350                 LASSERT(src_nid != LNET_NID_ANY);
1351                 lnet_msg_commit(msg, cpt);
1352
1353                 if (!msg->msg_routing)
1354                         msg->msg_hdr.src_nid = cpu_to_le64(src_nid);
1355
1356                 if (src_ni == the_lnet.ln_loni) {
1357                         /* No send credit hassles with LOLND */
1358                         lnet_net_unlock(cpt);
1359                         lnet_ni_send(src_ni, msg);
1360
1361                         lnet_net_lock(cpt);
1362                         lnet_ni_decref_locked(src_ni, cpt);
1363                         lnet_net_unlock(cpt);
1364                         return 0;
1365                 }
1366
1367                 rc = lnet_nid2peer_locked(&lp, dst_nid, cpt);
1368                 /* lp has ref on src_ni; lose mine */
1369                 lnet_ni_decref_locked(src_ni, cpt);
1370                 if (rc != 0) {
1371                         lnet_net_unlock(cpt);
1372                         LCONSOLE_WARN("Error %d finding peer %s\n", rc,
1373                                       libcfs_nid2str(dst_nid));
1374                         /* ENOMEM or shutting down */
1375                         return rc;
1376                 }
1377                 LASSERT (lp->lp_ni == src_ni);
1378         } else {
1379 #ifndef __KERNEL__
1380                 lnet_net_unlock(cpt);
1381
1382                 /* NB
1383                  * - once application finishes computation, check here to update
1384                  *   router states before it waits for pending IO in LNetEQPoll
1385                  * - recursion breaker: router checker sends no message
1386                  *   to remote networks */
1387                 if (the_lnet.ln_rc_state == LNET_RC_STATE_RUNNING)
1388                         lnet_router_checker();
1389
1390                 lnet_net_lock(cpt);
1391 #endif
1392                 /* sending to a remote network */
1393                 lp = lnet_find_route_locked(src_ni, dst_nid, rtr_nid);
1394                 if (lp == NULL) {
1395                         if (src_ni != NULL)
1396                                 lnet_ni_decref_locked(src_ni, cpt);
1397                         lnet_net_unlock(cpt);
1398
1399                         LCONSOLE_WARN("No route to %s via %s "
1400                                       "(all routers down)\n",
1401                                       libcfs_id2str(msg->msg_target),
1402                                       libcfs_nid2str(src_nid));
1403                         return -EHOSTUNREACH;
1404                 }
1405
1406                 /* rtr_nid is LNET_NID_ANY or NID of pre-determined router,
1407                  * it's possible that rtr_nid isn't LNET_NID_ANY and lp isn't
1408                  * pre-determined router, this can happen if router table
1409                  * was changed when we release the lock */
1410                 if (rtr_nid != lp->lp_nid) {
1411                         cpt2 = lnet_cpt_of_nid_locked(lp->lp_nid);
1412                         if (cpt2 != cpt) {
1413                                 if (src_ni != NULL)
1414                                         lnet_ni_decref_locked(src_ni, cpt);
1415                                 lnet_net_unlock(cpt);
1416
1417                                 rtr_nid = lp->lp_nid;
1418                                 cpt = cpt2;
1419                                 goto again;
1420                         }
1421                 }
1422
1423                 CDEBUG(D_NET, "Best route to %s via %s for %s %d\n",
1424                        libcfs_nid2str(dst_nid), libcfs_nid2str(lp->lp_nid),
1425                        lnet_msgtyp2str(msg->msg_type), msg->msg_len);
1426
1427                 if (src_ni == NULL) {
1428                         src_ni = lp->lp_ni;
1429                         src_nid = src_ni->ni_nid;
1430                 } else {
1431                         LASSERT (src_ni == lp->lp_ni);
1432                         lnet_ni_decref_locked(src_ni, cpt);
1433                 }
1434
1435                 lnet_peer_addref_locked(lp);
1436
1437                 LASSERT(src_nid != LNET_NID_ANY);
1438                 lnet_msg_commit(msg, cpt);
1439
1440                 if (!msg->msg_routing) {
1441                         /* I'm the source and now I know which NI to send on */
1442                         msg->msg_hdr.src_nid = cpu_to_le64(src_nid);
1443                 }
1444
1445                 msg->msg_target_is_router = 1;
1446                 msg->msg_target.nid = lp->lp_nid;
1447                 msg->msg_target.pid = LNET_PID_LUSTRE;
1448         }
1449
1450         /* 'lp' is our best choice of peer */
1451
1452         LASSERT (!msg->msg_peertxcredit);
1453         LASSERT (!msg->msg_txcredit);
1454         LASSERT (msg->msg_txpeer == NULL);
1455
1456         msg->msg_txpeer = lp;                   /* msg takes my ref on lp */
1457
1458         rc = lnet_post_send_locked(msg, 0);
1459         lnet_net_unlock(cpt);
1460
1461         if (rc < 0)
1462                 return rc;
1463
1464         if (rc == LNET_CREDIT_OK)
1465                 lnet_ni_send(src_ni, msg);
1466
1467         return 0; /* rc == LNET_CREDIT_OK or LNET_CREDIT_WAIT */
1468 }
1469
1470 void
1471 lnet_drop_message(lnet_ni_t *ni, int cpt, void *private, unsigned int nob)
1472 {
1473         lnet_net_lock(cpt);
1474         the_lnet.ln_counters[cpt]->drop_count++;
1475         the_lnet.ln_counters[cpt]->drop_length += nob;
1476         lnet_net_unlock(cpt);
1477
1478         lnet_ni_recv(ni, private, NULL, 0, 0, 0, nob);
1479 }
1480
1481 static void
1482 lnet_recv_put(lnet_ni_t *ni, lnet_msg_t *msg)
1483 {
1484         lnet_hdr_t      *hdr = &msg->msg_hdr;
1485
1486         if (msg->msg_wanted != 0)
1487                 lnet_setpayloadbuffer(msg);
1488
1489         lnet_build_msg_event(msg, LNET_EVENT_PUT);
1490
1491         /* Must I ACK?  If so I'll grab the ack_wmd out of the header and put
1492          * it back into the ACK during lnet_finalize() */
1493         msg->msg_ack = (!lnet_is_wire_handle_none(&hdr->msg.put.ack_wmd) &&
1494                         (msg->msg_md->md_options & LNET_MD_ACK_DISABLE) == 0);
1495
1496         lnet_ni_recv(ni, msg->msg_private, msg, msg->msg_rx_delayed,
1497                      msg->msg_offset, msg->msg_wanted, hdr->payload_length);
1498 }
1499
1500 static int
1501 lnet_parse_put(lnet_ni_t *ni, lnet_msg_t *msg)
1502 {
1503         lnet_hdr_t              *hdr = &msg->msg_hdr;
1504         struct lnet_match_info  info;
1505         int                     rc;
1506
1507         /* Convert put fields to host byte order */
1508         hdr->msg.put.match_bits = le64_to_cpu(hdr->msg.put.match_bits);
1509         hdr->msg.put.ptl_index  = le32_to_cpu(hdr->msg.put.ptl_index);
1510         hdr->msg.put.offset     = le32_to_cpu(hdr->msg.put.offset);
1511
1512         info.mi_id.nid  = hdr->src_nid;
1513         info.mi_id.pid  = hdr->src_pid;
1514         info.mi_opc     = LNET_MD_OP_PUT;
1515         info.mi_portal  = hdr->msg.put.ptl_index;
1516         info.mi_rlength = hdr->payload_length;
1517         info.mi_roffset = hdr->msg.put.offset;
1518         info.mi_mbits   = hdr->msg.put.match_bits;
1519
1520         msg->msg_rx_ready_delay = ni->ni_lnd->lnd_eager_recv == NULL;
1521
1522  again:
1523         rc = lnet_ptl_match_md(&info, msg);
1524         switch (rc) {
1525         default:
1526                 LBUG();
1527
1528         case LNET_MATCHMD_OK:
1529                 lnet_recv_put(ni, msg);
1530                 return 0;
1531
1532         case LNET_MATCHMD_NONE:
1533                 if (msg->msg_rx_delayed) /* attached on delayed list */
1534                         return 0;
1535
1536                 rc = lnet_ni_eager_recv(ni, msg);
1537                 if (rc == 0)
1538                         goto again;
1539                 /* fall through */
1540
1541         case LNET_MATCHMD_DROP:
1542                 CNETERR("Dropping PUT from %s portal %d match "LPU64
1543                         " offset %d length %d: %d\n",
1544                         libcfs_id2str(info.mi_id), info.mi_portal,
1545                         info.mi_mbits, info.mi_roffset, info.mi_rlength, rc);
1546
1547                 return ENOENT;  /* +ve: OK but no match */
1548         }
1549 }
1550
1551 static int
1552 lnet_parse_get(lnet_ni_t *ni, lnet_msg_t *msg, int rdma_get)
1553 {
1554         struct lnet_match_info  info;
1555         lnet_hdr_t              *hdr = &msg->msg_hdr;
1556         lnet_handle_wire_t      reply_wmd;
1557         int                     rc;
1558
1559         /* Convert get fields to host byte order */
1560         hdr->msg.get.match_bits   = le64_to_cpu(hdr->msg.get.match_bits);
1561         hdr->msg.get.ptl_index    = le32_to_cpu(hdr->msg.get.ptl_index);
1562         hdr->msg.get.sink_length  = le32_to_cpu(hdr->msg.get.sink_length);
1563         hdr->msg.get.src_offset   = le32_to_cpu(hdr->msg.get.src_offset);
1564
1565         info.mi_id.nid  = hdr->src_nid;
1566         info.mi_id.pid  = hdr->src_pid;
1567         info.mi_opc     = LNET_MD_OP_GET;
1568         info.mi_portal  = hdr->msg.get.ptl_index;
1569         info.mi_rlength = hdr->msg.get.sink_length;
1570         info.mi_roffset = hdr->msg.get.src_offset;
1571         info.mi_mbits   = hdr->msg.get.match_bits;
1572
1573         rc = lnet_ptl_match_md(&info, msg);
1574         if (rc == LNET_MATCHMD_DROP) {
1575                 CNETERR("Dropping GET from %s portal %d match "LPU64
1576                         " offset %d length %d\n",
1577                         libcfs_id2str(info.mi_id), info.mi_portal,
1578                         info.mi_mbits, info.mi_roffset, info.mi_rlength);
1579                 return ENOENT;  /* +ve: OK but no match */
1580         }
1581
1582         LASSERT(rc == LNET_MATCHMD_OK);
1583
1584         lnet_build_msg_event(msg, LNET_EVENT_GET);
1585
1586         reply_wmd = hdr->msg.get.return_wmd;
1587
1588         lnet_prep_send(msg, LNET_MSG_REPLY, info.mi_id,
1589                        msg->msg_offset, msg->msg_wanted);
1590
1591         msg->msg_hdr.msg.reply.dst_wmd = reply_wmd;
1592
1593         if (rdma_get) {
1594                 /* The LND completes the REPLY from her recv procedure */
1595                 lnet_ni_recv(ni, msg->msg_private, msg, 0,
1596                              msg->msg_offset, msg->msg_len, msg->msg_len);
1597                 return 0;
1598         }
1599
1600         lnet_ni_recv(ni, msg->msg_private, NULL, 0, 0, 0, 0);
1601         msg->msg_receiving = 0;
1602
1603         rc = lnet_send(ni->ni_nid, msg, LNET_NID_ANY);
1604         if (rc < 0) {
1605                 /* didn't get as far as lnet_ni_send() */
1606                 CERROR("%s: Unable to send REPLY for GET from %s: %d\n",
1607                        libcfs_nid2str(ni->ni_nid),
1608                        libcfs_id2str(info.mi_id), rc);
1609
1610                 lnet_finalize(ni, msg, rc);
1611         }
1612
1613         return 0;
1614 }
1615
1616 static int
1617 lnet_parse_reply(lnet_ni_t *ni, lnet_msg_t *msg)
1618 {
1619         void             *private = msg->msg_private;
1620         lnet_hdr_t       *hdr = &msg->msg_hdr;
1621         lnet_process_id_t src = {0};
1622         lnet_libmd_t     *md;
1623         int               rlength;
1624         int               mlength;
1625         int                     cpt;
1626
1627         cpt = lnet_cpt_of_cookie(hdr->msg.reply.dst_wmd.wh_object_cookie);
1628         lnet_res_lock(cpt);
1629
1630         src.nid = hdr->src_nid;
1631         src.pid = hdr->src_pid;
1632
1633         /* NB handles only looked up by creator (no flips) */
1634         md = lnet_wire_handle2md(&hdr->msg.reply.dst_wmd);
1635         if (md == NULL || md->md_threshold == 0 || md->md_me != NULL) {
1636                 CNETERR("%s: Dropping REPLY from %s for %s "
1637                         "MD "LPX64"."LPX64"\n",
1638                         libcfs_nid2str(ni->ni_nid), libcfs_id2str(src),
1639                         (md == NULL) ? "invalid" : "inactive",
1640                         hdr->msg.reply.dst_wmd.wh_interface_cookie,
1641                         hdr->msg.reply.dst_wmd.wh_object_cookie);
1642                 if (md != NULL && md->md_me != NULL)
1643                         CERROR("REPLY MD also attached to portal %d\n",
1644                                md->md_me->me_portal);
1645
1646                 lnet_res_unlock(cpt);
1647                 return ENOENT;                  /* +ve: OK but no match */
1648         }
1649
1650         LASSERT (md->md_offset == 0);
1651
1652         rlength = hdr->payload_length;
1653         mlength = MIN(rlength, (int)md->md_length);
1654
1655         if (mlength < rlength &&
1656             (md->md_options & LNET_MD_TRUNCATE) == 0) {
1657                 CNETERR("%s: Dropping REPLY from %s length %d "
1658                         "for MD "LPX64" would overflow (%d)\n",
1659                         libcfs_nid2str(ni->ni_nid), libcfs_id2str(src),
1660                         rlength, hdr->msg.reply.dst_wmd.wh_object_cookie,
1661                         mlength);
1662                 lnet_res_unlock(cpt);
1663                 return ENOENT;          /* +ve: OK but no match */
1664         }
1665
1666         CDEBUG(D_NET, "%s: Reply from %s of length %d/%d into md "LPX64"\n",
1667                libcfs_nid2str(ni->ni_nid), libcfs_id2str(src), 
1668                mlength, rlength, hdr->msg.reply.dst_wmd.wh_object_cookie);
1669
1670         lnet_msg_attach_md(msg, md, 0, mlength);
1671
1672         if (mlength != 0)
1673                 lnet_setpayloadbuffer(msg);
1674
1675         lnet_res_unlock(cpt);
1676
1677         lnet_build_msg_event(msg, LNET_EVENT_REPLY);
1678
1679         lnet_ni_recv(ni, private, msg, 0, 0, mlength, rlength);
1680         return 0;
1681 }
1682
1683 static int
1684 lnet_parse_ack(lnet_ni_t *ni, lnet_msg_t *msg)
1685 {
1686         lnet_hdr_t       *hdr = &msg->msg_hdr;
1687         lnet_process_id_t src = {0};
1688         lnet_libmd_t     *md;
1689         int                     cpt;
1690
1691         src.nid = hdr->src_nid;
1692         src.pid = hdr->src_pid;
1693
1694         /* Convert ack fields to host byte order */
1695         hdr->msg.ack.match_bits = le64_to_cpu(hdr->msg.ack.match_bits);
1696         hdr->msg.ack.mlength = le32_to_cpu(hdr->msg.ack.mlength);
1697
1698         cpt = lnet_cpt_of_cookie(hdr->msg.ack.dst_wmd.wh_object_cookie);
1699         lnet_res_lock(cpt);
1700
1701         /* NB handles only looked up by creator (no flips) */
1702         md = lnet_wire_handle2md(&hdr->msg.ack.dst_wmd);
1703         if (md == NULL || md->md_threshold == 0 || md->md_me != NULL) {
1704                 /* Don't moan; this is expected */
1705                 CDEBUG(D_NET,
1706                        "%s: Dropping ACK from %s to %s MD "LPX64"."LPX64"\n",
1707                        libcfs_nid2str(ni->ni_nid), libcfs_id2str(src),
1708                        (md == NULL) ? "invalid" : "inactive",
1709                        hdr->msg.ack.dst_wmd.wh_interface_cookie,
1710                        hdr->msg.ack.dst_wmd.wh_object_cookie);
1711                 if (md != NULL && md->md_me != NULL)
1712                         CERROR("Source MD also attached to portal %d\n",
1713                                md->md_me->me_portal);
1714
1715                 lnet_res_unlock(cpt);
1716                 return ENOENT;                  /* +ve! */
1717         }
1718
1719         CDEBUG(D_NET, "%s: ACK from %s into md "LPX64"\n",
1720                libcfs_nid2str(ni->ni_nid), libcfs_id2str(src), 
1721                hdr->msg.ack.dst_wmd.wh_object_cookie);
1722
1723         lnet_msg_attach_md(msg, md, 0, 0);
1724
1725         lnet_res_unlock(cpt);
1726
1727         lnet_build_msg_event(msg, LNET_EVENT_ACK);
1728
1729         lnet_ni_recv(ni, msg->msg_private, msg, 0, 0, 0, msg->msg_len);
1730         return 0;
1731 }
1732
1733 /**
1734  * \retval LNET_CREDIT_OK       If \a msg is forwarded
1735  * \retval LNET_CREDIT_WAIT     If \a msg is blocked because w/o buffer
1736  * \retval -ve                  error code
1737  */
1738 int
1739 lnet_parse_forward_locked(lnet_ni_t *ni, lnet_msg_t *msg)
1740 {
1741         int     rc = 0;
1742
1743 #ifdef __KERNEL__
1744         if (!the_lnet.ln_routing)
1745                 return -ECANCELED;
1746
1747         if (msg->msg_rxpeer->lp_rtrcredits <= 0 ||
1748             lnet_msg2bufpool(msg)->rbp_credits <= 0) {
1749                 if (ni->ni_lnd->lnd_eager_recv == NULL) {
1750                         msg->msg_rx_ready_delay = 1;
1751                 } else {
1752                         lnet_net_unlock(msg->msg_rx_cpt);
1753                         rc = lnet_ni_eager_recv(ni, msg);
1754                         lnet_net_lock(msg->msg_rx_cpt);
1755                 }
1756         }
1757
1758         if (rc == 0)
1759                 rc = lnet_post_routed_recv_locked(msg, 0);
1760 #else
1761         LBUG();
1762 #endif
1763         return rc;
1764 }
1765
1766 int
1767 lnet_parse_local(lnet_ni_t *ni, lnet_msg_t *msg)
1768 {
1769         int     rc;
1770
1771         switch (msg->msg_type) {
1772         case LNET_MSG_ACK:
1773                 rc = lnet_parse_ack(ni, msg);
1774                 break;
1775         case LNET_MSG_PUT:
1776                 rc = lnet_parse_put(ni, msg);
1777                 break;
1778         case LNET_MSG_GET:
1779                 rc = lnet_parse_get(ni, msg, msg->msg_rdma_get);
1780                 break;
1781         case LNET_MSG_REPLY:
1782                 rc = lnet_parse_reply(ni, msg);
1783                 break;
1784         default: /* prevent an unused label if !kernel */
1785                 LASSERT(0);
1786                 return -EPROTO;
1787         }
1788
1789         LASSERT(rc == 0 || rc == ENOENT);
1790         return rc;
1791 }
1792
1793 char *
1794 lnet_msgtyp2str (int type)
1795 {
1796         switch (type) {
1797         case LNET_MSG_ACK:
1798                 return ("ACK");
1799         case LNET_MSG_PUT:
1800                 return ("PUT");
1801         case LNET_MSG_GET:
1802                 return ("GET");
1803         case LNET_MSG_REPLY:
1804                 return ("REPLY");
1805         case LNET_MSG_HELLO:
1806                 return ("HELLO");
1807         default:
1808                 return ("<UNKNOWN>");
1809         }
1810 }
1811 EXPORT_SYMBOL(lnet_msgtyp2str);
1812
1813 void
1814 lnet_print_hdr(lnet_hdr_t * hdr)
1815 {
1816         lnet_process_id_t src = {0};
1817         lnet_process_id_t dst = {0};
1818         char *type_str = lnet_msgtyp2str (hdr->type);
1819
1820         src.nid = hdr->src_nid;
1821         src.pid = hdr->src_pid;
1822
1823         dst.nid = hdr->dest_nid;
1824         dst.pid = hdr->dest_pid;
1825
1826         CWARN("P3 Header at %p of type %s\n", hdr, type_str);
1827         CWARN("    From %s\n", libcfs_id2str(src));
1828         CWARN("    To   %s\n", libcfs_id2str(dst));
1829
1830         switch (hdr->type) {
1831         default:
1832                 break;
1833
1834         case LNET_MSG_PUT:
1835                 CWARN("    Ptl index %d, ack md "LPX64"."LPX64", "
1836                       "match bits "LPU64"\n",
1837                       hdr->msg.put.ptl_index,
1838                       hdr->msg.put.ack_wmd.wh_interface_cookie,
1839                       hdr->msg.put.ack_wmd.wh_object_cookie,
1840                       hdr->msg.put.match_bits);
1841                 CWARN("    Length %d, offset %d, hdr data "LPX64"\n",
1842                       hdr->payload_length, hdr->msg.put.offset,
1843                       hdr->msg.put.hdr_data);
1844                 break;
1845
1846         case LNET_MSG_GET:
1847                 CWARN("    Ptl index %d, return md "LPX64"."LPX64", "
1848                       "match bits "LPU64"\n", hdr->msg.get.ptl_index,
1849                       hdr->msg.get.return_wmd.wh_interface_cookie,
1850                       hdr->msg.get.return_wmd.wh_object_cookie,
1851                       hdr->msg.get.match_bits);
1852                 CWARN("    Length %d, src offset %d\n",
1853                       hdr->msg.get.sink_length,
1854                       hdr->msg.get.src_offset);
1855                 break;
1856
1857         case LNET_MSG_ACK:
1858                 CWARN("    dst md "LPX64"."LPX64", "
1859                       "manipulated length %d\n",
1860                       hdr->msg.ack.dst_wmd.wh_interface_cookie,
1861                       hdr->msg.ack.dst_wmd.wh_object_cookie,
1862                       hdr->msg.ack.mlength);
1863                 break;
1864
1865         case LNET_MSG_REPLY:
1866                 CWARN("    dst md "LPX64"."LPX64", "
1867                       "length %d\n",
1868                       hdr->msg.reply.dst_wmd.wh_interface_cookie,
1869                       hdr->msg.reply.dst_wmd.wh_object_cookie,
1870                       hdr->payload_length);
1871         }
1872
1873 }
1874
1875 int
1876 lnet_parse(lnet_ni_t *ni, lnet_hdr_t *hdr, lnet_nid_t from_nid,
1877            void *private, int rdma_req)
1878 {
1879         int             rc = 0;
1880         int             cpt;
1881         int             for_me;
1882         struct lnet_msg *msg;
1883         lnet_pid_t     dest_pid;
1884         lnet_nid_t     dest_nid;
1885         lnet_nid_t     src_nid;
1886         __u32          payload_length;
1887         __u32          type;
1888
1889         LASSERT (!in_interrupt ());
1890
1891         type = le32_to_cpu(hdr->type);
1892         src_nid = le64_to_cpu(hdr->src_nid);
1893         dest_nid = le64_to_cpu(hdr->dest_nid);
1894         dest_pid = le32_to_cpu(hdr->dest_pid);
1895         payload_length = le32_to_cpu(hdr->payload_length);
1896
1897         for_me = (ni->ni_nid == dest_nid);
1898         cpt = lnet_cpt_of_nid(from_nid);
1899
1900         switch (type) {
1901         case LNET_MSG_ACK:
1902         case LNET_MSG_GET:
1903                 if (payload_length > 0) {
1904                         CERROR("%s, src %s: bad %s payload %d (0 expected)\n",
1905                                libcfs_nid2str(from_nid),
1906                                libcfs_nid2str(src_nid),
1907                                lnet_msgtyp2str(type), payload_length);
1908                         return -EPROTO;
1909                 }
1910                 break;
1911
1912         case LNET_MSG_PUT:
1913         case LNET_MSG_REPLY:
1914                 if (payload_length >
1915                     (__u32)(for_me ? LNET_MAX_PAYLOAD : LNET_MTU)) {
1916                         CERROR("%s, src %s: bad %s payload %d "
1917                                "(%d max expected)\n",
1918                                libcfs_nid2str(from_nid),
1919                                libcfs_nid2str(src_nid),
1920                                lnet_msgtyp2str(type),
1921                                payload_length,
1922                                for_me ? LNET_MAX_PAYLOAD : LNET_MTU);
1923                         return -EPROTO;
1924                 }
1925                 break;
1926
1927         default:
1928                 CERROR("%s, src %s: Bad message type 0x%x\n",
1929                        libcfs_nid2str(from_nid),
1930                        libcfs_nid2str(src_nid), type);
1931                 return -EPROTO;
1932         }
1933
1934         if (the_lnet.ln_routing &&
1935             ni->ni_last_alive != cfs_time_current_sec()) {
1936                 /* NB: so far here is the only place to set NI status to "up */
1937                 lnet_ni_lock(ni);
1938                 ni->ni_last_alive = cfs_time_current_sec();
1939                 if (ni->ni_status != NULL &&
1940                     ni->ni_status->ns_status == LNET_NI_STATUS_DOWN)
1941                         ni->ni_status->ns_status = LNET_NI_STATUS_UP;
1942                 lnet_ni_unlock(ni);
1943         }
1944
1945         /* Regard a bad destination NID as a protocol error.  Senders should
1946          * know what they're doing; if they don't they're misconfigured, buggy
1947          * or malicious so we chop them off at the knees :) */
1948
1949         if (!for_me) {
1950                 if (LNET_NIDNET(dest_nid) == LNET_NIDNET(ni->ni_nid)) {
1951                         /* should have gone direct */
1952                         CERROR("%s, src %s: Bad dest nid %s "
1953                                "(should have been sent direct)\n",
1954                                 libcfs_nid2str(from_nid),
1955                                 libcfs_nid2str(src_nid),
1956                                 libcfs_nid2str(dest_nid));
1957                         return -EPROTO;
1958                 }
1959
1960                 if (lnet_islocalnid(dest_nid)) {
1961                         /* dest is another local NI; sender should have used
1962                          * this node's NID on its own network */
1963                         CERROR("%s, src %s: Bad dest nid %s "
1964                                "(it's my nid but on a different network)\n",
1965                                 libcfs_nid2str(from_nid),
1966                                 libcfs_nid2str(src_nid),
1967                                 libcfs_nid2str(dest_nid));
1968                         return -EPROTO;
1969                 }
1970
1971                 if (rdma_req && type == LNET_MSG_GET) {
1972                         CERROR("%s, src %s: Bad optimized GET for %s "
1973                                "(final destination must be me)\n",
1974                                 libcfs_nid2str(from_nid),
1975                                 libcfs_nid2str(src_nid),
1976                                 libcfs_nid2str(dest_nid));
1977                         return -EPROTO;
1978                 }
1979
1980                 if (!the_lnet.ln_routing) {
1981                         CERROR("%s, src %s: Dropping message for %s "
1982                                "(routing not enabled)\n",
1983                                 libcfs_nid2str(from_nid),
1984                                 libcfs_nid2str(src_nid),
1985                                 libcfs_nid2str(dest_nid));
1986                         goto drop;
1987                 }
1988         }
1989
1990         /* Message looks OK; we're not going to return an error, so we MUST
1991          * call back lnd_recv() come what may... */
1992
1993         if (!list_empty(&the_lnet.ln_test_peers) &&     /* normally we don't */
1994             fail_peer(src_nid, 0)) {                    /* shall we now? */
1995                 CERROR("%s, src %s: Dropping %s to simulate failure\n",
1996                        libcfs_nid2str(from_nid), libcfs_nid2str(src_nid),
1997                        lnet_msgtyp2str(type));
1998                 goto drop;
1999         }
2000
2001         if (!list_empty(&the_lnet.ln_drop_rules) &&
2002             lnet_drop_rule_match(hdr)) {
2003                 CDEBUG(D_NET, "%s, src %s, dst %s: Dropping %s to simulate"
2004                               "silent message loss\n",
2005                        libcfs_nid2str(from_nid), libcfs_nid2str(src_nid),
2006                        libcfs_nid2str(dest_nid), lnet_msgtyp2str(type));
2007                 goto drop;
2008         }
2009
2010
2011         msg = lnet_msg_alloc();
2012         if (msg == NULL) {
2013                 CERROR("%s, src %s: Dropping %s (out of memory)\n",
2014                        libcfs_nid2str(from_nid), libcfs_nid2str(src_nid),
2015                        lnet_msgtyp2str(type));
2016                 goto drop;
2017         }
2018
2019         /* msg zeroed in lnet_msg_alloc; i.e. flags all clear,
2020          * pointers NULL etc */
2021
2022         msg->msg_type = type;
2023         msg->msg_private = private;
2024         msg->msg_receiving = 1;
2025         msg->msg_rdma_get = rdma_req;
2026         msg->msg_len = msg->msg_wanted = payload_length;
2027         msg->msg_offset = 0;
2028         msg->msg_hdr = *hdr;
2029         /* for building message event */
2030         msg->msg_from = from_nid;
2031         if (!for_me) {
2032                 msg->msg_target.pid     = dest_pid;
2033                 msg->msg_target.nid     = dest_nid;
2034                 msg->msg_routing        = 1;
2035
2036         } else {
2037                 /* convert common msg->hdr fields to host byteorder */
2038                 msg->msg_hdr.type       = type;
2039                 msg->msg_hdr.src_nid    = src_nid;
2040                 msg->msg_hdr.src_pid    = le32_to_cpu(msg->msg_hdr.src_pid);
2041                 msg->msg_hdr.dest_nid   = dest_nid;
2042                 msg->msg_hdr.dest_pid   = dest_pid;
2043                 msg->msg_hdr.payload_length = payload_length;
2044         }
2045
2046         lnet_net_lock(cpt);
2047         rc = lnet_nid2peer_locked(&msg->msg_rxpeer, from_nid, cpt);
2048         if (rc != 0) {
2049                 lnet_net_unlock(cpt);
2050                 CERROR("%s, src %s: Dropping %s "
2051                        "(error %d looking up sender)\n",
2052                        libcfs_nid2str(from_nid), libcfs_nid2str(src_nid),
2053                        lnet_msgtyp2str(type), rc);
2054                 lnet_msg_free(msg);
2055                 goto drop;
2056         }
2057
2058         lnet_msg_commit(msg, cpt);
2059
2060         /* message delay simulation */
2061         if (unlikely(!list_empty(&the_lnet.ln_delay_rules) &&
2062                      lnet_delay_rule_match_locked(hdr, msg))) {
2063                 lnet_net_unlock(cpt);
2064                 return 0;
2065         }
2066
2067         if (!for_me) {
2068                 rc = lnet_parse_forward_locked(ni, msg);
2069                 lnet_net_unlock(cpt);
2070
2071                 if (rc < 0)
2072                         goto free_drop;
2073
2074                 if (rc == LNET_CREDIT_OK) {
2075                         lnet_ni_recv(ni, msg->msg_private, msg, 0,
2076                                      0, payload_length, payload_length);
2077                 }
2078                 return 0;
2079         }
2080
2081         lnet_net_unlock(cpt);
2082
2083         rc = lnet_parse_local(ni, msg);
2084         if (rc != 0)
2085                 goto free_drop;
2086         return 0;
2087
2088  free_drop:
2089         LASSERT(msg->msg_md == NULL);
2090         lnet_finalize(ni, msg, rc);
2091
2092  drop:
2093         lnet_drop_message(ni, cpt, private, payload_length);
2094         return 0;
2095 }
2096 EXPORT_SYMBOL(lnet_parse);
2097
2098 void
2099 lnet_drop_delayed_msg_list(struct list_head *head, char *reason)
2100 {
2101         while (!list_empty(head)) {
2102                 lnet_process_id_t       id = {0};
2103                 lnet_msg_t              *msg;
2104
2105                 msg = list_entry(head->next, lnet_msg_t, msg_list);
2106                 list_del(&msg->msg_list);
2107
2108                 id.nid = msg->msg_hdr.src_nid;
2109                 id.pid = msg->msg_hdr.src_pid;
2110
2111                 LASSERT(msg->msg_md == NULL);
2112                 LASSERT(msg->msg_rx_delayed);
2113                 LASSERT(msg->msg_rxpeer != NULL);
2114                 LASSERT(msg->msg_hdr.type == LNET_MSG_PUT);
2115
2116                 CWARN("Dropping delayed PUT from %s portal %d match "LPU64
2117                       " offset %d length %d: %s\n",
2118                       libcfs_id2str(id),
2119                       msg->msg_hdr.msg.put.ptl_index,
2120                       msg->msg_hdr.msg.put.match_bits,
2121                       msg->msg_hdr.msg.put.offset,
2122                       msg->msg_hdr.payload_length, reason);
2123
2124                 /* NB I can't drop msg's ref on msg_rxpeer until after I've
2125                  * called lnet_drop_message(), so I just hang onto msg as well
2126                  * until that's done */
2127
2128                 lnet_drop_message(msg->msg_rxpeer->lp_ni,
2129                                   msg->msg_rxpeer->lp_cpt,
2130                                   msg->msg_private, msg->msg_len);
2131                 /*
2132                  * NB: message will not generate event because w/o attached MD,
2133                  * but we still should give error code so lnet_msg_decommit()
2134                  * can skip counters operations and other checks.
2135                  */
2136                 lnet_finalize(msg->msg_rxpeer->lp_ni, msg, -ENOENT);
2137         }
2138 }
2139
2140 void
2141 lnet_recv_delayed_msg_list(struct list_head *head)
2142 {
2143         while (!list_empty(head)) {
2144                 lnet_msg_t        *msg;
2145                 lnet_process_id_t  id;
2146
2147                 msg = list_entry(head->next, lnet_msg_t, msg_list);
2148                 list_del(&msg->msg_list);
2149
2150                 /* md won't disappear under me, since each msg
2151                  * holds a ref on it */
2152
2153                 id.nid = msg->msg_hdr.src_nid;
2154                 id.pid = msg->msg_hdr.src_pid;
2155
2156                 LASSERT(msg->msg_rx_delayed);
2157                 LASSERT(msg->msg_md != NULL);
2158                 LASSERT(msg->msg_rxpeer != NULL);
2159                 LASSERT(msg->msg_hdr.type == LNET_MSG_PUT);
2160
2161                 CDEBUG(D_NET, "Resuming delayed PUT from %s portal %d "
2162                        "match "LPU64" offset %d length %d.\n",
2163                         libcfs_id2str(id), msg->msg_hdr.msg.put.ptl_index,
2164                         msg->msg_hdr.msg.put.match_bits,
2165                         msg->msg_hdr.msg.put.offset,
2166                         msg->msg_hdr.payload_length);
2167
2168                 lnet_recv_put(msg->msg_rxpeer->lp_ni, msg);
2169         }
2170 }
2171
2172 /**
2173  * Initiate an asynchronous PUT operation.
2174  *
2175  * There are several events associated with a PUT: completion of the send on
2176  * the initiator node (LNET_EVENT_SEND), and when the send completes
2177  * successfully, the receipt of an acknowledgment (LNET_EVENT_ACK) indicating
2178  * that the operation was accepted by the target. The event LNET_EVENT_PUT is
2179  * used at the target node to indicate the completion of incoming data
2180  * delivery.
2181  *
2182  * The local events will be logged in the EQ associated with the MD pointed to
2183  * by \a mdh handle. Using a MD without an associated EQ results in these
2184  * events being discarded. In this case, the caller must have another
2185  * mechanism (e.g., a higher level protocol) for determining when it is safe
2186  * to modify the memory region associated with the MD.
2187  *
2188  * Note that LNet does not guarantee the order of LNET_EVENT_SEND and
2189  * LNET_EVENT_ACK, though intuitively ACK should happen after SEND.
2190  *
2191  * \param self Indicates the NID of a local interface through which to send
2192  * the PUT request. Use LNET_NID_ANY to let LNet choose one by itself.
2193  * \param mdh A handle for the MD that describes the memory to be sent. The MD
2194  * must be "free floating" (See LNetMDBind()).
2195  * \param ack Controls whether an acknowledgment is requested.
2196  * Acknowledgments are only sent when they are requested by the initiating
2197  * process and the target MD enables them.
2198  * \param target A process identifier for the target process.
2199  * \param portal The index in the \a target's portal table.
2200  * \param match_bits The match bits to use for MD selection at the target
2201  * process.
2202  * \param offset The offset into the target MD (only used when the target
2203  * MD has the LNET_MD_MANAGE_REMOTE option set).
2204  * \param hdr_data 64 bits of user data that can be included in the message
2205  * header. This data is written to an event queue entry at the target if an
2206  * EQ is present on the matching MD.
2207  *
2208  * \retval  0      Success, and only in this case events will be generated
2209  * and logged to EQ (if it exists).
2210  * \retval -EIO    Simulated failure.
2211  * \retval -ENOMEM Memory allocation failure.
2212  * \retval -ENOENT Invalid MD object.
2213  *
2214  * \see lnet_event_t::hdr_data and lnet_event_kind_t.
2215  */
2216 int
2217 LNetPut(lnet_nid_t self, lnet_handle_md_t mdh, lnet_ack_req_t ack,
2218         lnet_process_id_t target, unsigned int portal,
2219         __u64 match_bits, unsigned int offset,
2220         __u64 hdr_data)
2221 {
2222         struct lnet_msg         *msg;
2223         struct lnet_libmd       *md;
2224         int                     cpt;
2225         int                     rc;
2226
2227         LASSERT(the_lnet.ln_init);
2228         LASSERT(the_lnet.ln_refcount > 0);
2229
2230         if (!list_empty(&the_lnet.ln_test_peers) &&     /* normally we don't */
2231             fail_peer(target.nid, 1)) {                 /* shall we now? */
2232                 CERROR("Dropping PUT to %s: simulated failure\n",
2233                        libcfs_id2str(target));
2234                 return -EIO;
2235         }
2236
2237         msg = lnet_msg_alloc();
2238         if (msg == NULL) {
2239                 CERROR("Dropping PUT to %s: ENOMEM on lnet_msg_t\n",
2240                        libcfs_id2str(target));
2241                 return -ENOMEM;
2242         }
2243         msg->msg_vmflush = !!memory_pressure_get();
2244
2245         cpt = lnet_cpt_of_cookie(mdh.cookie);
2246         lnet_res_lock(cpt);
2247
2248         md = lnet_handle2md(&mdh);
2249         if (md == NULL || md->md_threshold == 0 || md->md_me != NULL) {
2250                 CERROR("Dropping PUT ("LPU64":%d:%s): MD (%d) invalid\n",
2251                        match_bits, portal, libcfs_id2str(target),
2252                        md == NULL ? -1 : md->md_threshold);
2253                 if (md != NULL && md->md_me != NULL)
2254                         CERROR("Source MD also attached to portal %d\n",
2255                                md->md_me->me_portal);
2256                 lnet_res_unlock(cpt);
2257
2258                 lnet_msg_free(msg);
2259                 return -ENOENT;
2260         }
2261
2262         CDEBUG(D_NET, "LNetPut -> %s\n", libcfs_id2str(target));
2263
2264         lnet_msg_attach_md(msg, md, 0, 0);
2265
2266         lnet_prep_send(msg, LNET_MSG_PUT, target, 0, md->md_length);
2267
2268         msg->msg_hdr.msg.put.match_bits = cpu_to_le64(match_bits);
2269         msg->msg_hdr.msg.put.ptl_index = cpu_to_le32(portal);
2270         msg->msg_hdr.msg.put.offset = cpu_to_le32(offset);
2271         msg->msg_hdr.msg.put.hdr_data = hdr_data;
2272
2273         /* NB handles only looked up by creator (no flips) */
2274         if (ack == LNET_ACK_REQ) {
2275                 msg->msg_hdr.msg.put.ack_wmd.wh_interface_cookie = 
2276                         the_lnet.ln_interface_cookie;
2277                 msg->msg_hdr.msg.put.ack_wmd.wh_object_cookie = 
2278                         md->md_lh.lh_cookie;
2279         } else {
2280                 msg->msg_hdr.msg.put.ack_wmd.wh_interface_cookie = 
2281                         LNET_WIRE_HANDLE_COOKIE_NONE;
2282                 msg->msg_hdr.msg.put.ack_wmd.wh_object_cookie = 
2283                         LNET_WIRE_HANDLE_COOKIE_NONE;
2284         }
2285
2286         lnet_res_unlock(cpt);
2287
2288         lnet_build_msg_event(msg, LNET_EVENT_SEND);
2289
2290         rc = lnet_send(self, msg, LNET_NID_ANY);
2291         if (rc != 0) {
2292                 CNETERR( "Error sending PUT to %s: %d\n",
2293                        libcfs_id2str(target), rc);
2294                 lnet_finalize (NULL, msg, rc);
2295         }
2296
2297         /* completion will be signalled by an event */
2298         return 0;
2299 }
2300 EXPORT_SYMBOL(LNetPut);
2301
2302 lnet_msg_t *
2303 lnet_create_reply_msg (lnet_ni_t *ni, lnet_msg_t *getmsg)
2304 {
2305         /* The LND can DMA direct to the GET md (i.e. no REPLY msg).  This
2306          * returns a msg for the LND to pass to lnet_finalize() when the sink
2307          * data has been received.
2308          *
2309          * CAVEAT EMPTOR: 'getmsg' is the original GET, which is freed when
2310          * lnet_finalize() is called on it, so the LND must call this first */
2311
2312         struct lnet_msg         *msg = lnet_msg_alloc();
2313         struct lnet_libmd       *getmd = getmsg->msg_md;
2314         lnet_process_id_t       peer_id = getmsg->msg_target;
2315         int                     cpt;
2316
2317         LASSERT(!getmsg->msg_target_is_router);
2318         LASSERT(!getmsg->msg_routing);
2319
2320         if (msg == NULL) {
2321                 CERROR("%s: Dropping REPLY from %s: can't allocate msg\n",
2322                        libcfs_nid2str(ni->ni_nid), libcfs_id2str(peer_id));
2323                 goto drop;
2324         }
2325
2326         cpt = lnet_cpt_of_cookie(getmd->md_lh.lh_cookie);
2327         lnet_res_lock(cpt);
2328
2329         LASSERT(getmd->md_refcount > 0);
2330
2331         if (getmd->md_threshold == 0) {
2332                 CERROR ("%s: Dropping REPLY from %s for inactive MD %p\n",
2333                         libcfs_nid2str(ni->ni_nid), libcfs_id2str(peer_id), 
2334                         getmd);
2335                 lnet_res_unlock(cpt);
2336                 goto drop;
2337         }
2338
2339         LASSERT(getmd->md_offset == 0);
2340
2341         CDEBUG(D_NET, "%s: Reply from %s md %p\n",
2342                libcfs_nid2str(ni->ni_nid), libcfs_id2str(peer_id), getmd);
2343
2344         /* setup information for lnet_build_msg_event */
2345         msg->msg_from = peer_id.nid;
2346         msg->msg_type = LNET_MSG_GET; /* flag this msg as an "optimized" GET */
2347         msg->msg_hdr.src_nid = peer_id.nid;
2348         msg->msg_hdr.payload_length = getmd->md_length;
2349         msg->msg_receiving = 1; /* required by lnet_msg_attach_md */
2350
2351         lnet_msg_attach_md(msg, getmd, getmd->md_offset, getmd->md_length);
2352         lnet_res_unlock(cpt);
2353
2354         cpt = lnet_cpt_of_nid(peer_id.nid);
2355
2356         lnet_net_lock(cpt);
2357         lnet_msg_commit(msg, cpt);
2358         lnet_net_unlock(cpt);
2359
2360         lnet_build_msg_event(msg, LNET_EVENT_REPLY);
2361
2362         return msg;
2363
2364  drop:
2365         cpt = lnet_cpt_of_nid(peer_id.nid);
2366
2367         lnet_net_lock(cpt);
2368         the_lnet.ln_counters[cpt]->drop_count++;
2369         the_lnet.ln_counters[cpt]->drop_length += getmd->md_length;
2370         lnet_net_unlock(cpt);
2371
2372         if (msg != NULL)
2373                 lnet_msg_free(msg);
2374
2375         return NULL;
2376 }
2377 EXPORT_SYMBOL(lnet_create_reply_msg);
2378
2379 void
2380 lnet_set_reply_msg_len(lnet_ni_t *ni, lnet_msg_t *reply, unsigned int len)
2381 {
2382         /* Set the REPLY length, now the RDMA that elides the REPLY message has
2383          * completed and I know it. */
2384         LASSERT (reply != NULL);
2385         LASSERT (reply->msg_type == LNET_MSG_GET);
2386         LASSERT (reply->msg_ev.type == LNET_EVENT_REPLY);
2387
2388         /* NB I trusted my peer to RDMA.  If she tells me she's written beyond
2389          * the end of my buffer, I might as well be dead. */
2390         LASSERT (len <= reply->msg_ev.mlength);
2391
2392         reply->msg_ev.mlength = len;
2393 }
2394 EXPORT_SYMBOL(lnet_set_reply_msg_len);
2395
2396 /**
2397  * Initiate an asynchronous GET operation.
2398  *
2399  * On the initiator node, an LNET_EVENT_SEND is logged when the GET request
2400  * is sent, and an LNET_EVENT_REPLY is logged when the data returned from
2401  * the target node in the REPLY has been written to local MD.
2402  *
2403  * On the target node, an LNET_EVENT_GET is logged when the GET request
2404  * arrives and is accepted into a MD.
2405  *
2406  * \param self,target,portal,match_bits,offset See the discussion in LNetPut().
2407  * \param mdh A handle for the MD that describes the memory into which the
2408  * requested data will be received. The MD must be "free floating" (See LNetMDBind()).
2409  *
2410  * \retval  0      Success, and only in this case events will be generated
2411  * and logged to EQ (if it exists) of the MD.
2412  * \retval -EIO    Simulated failure.
2413  * \retval -ENOMEM Memory allocation failure.
2414  * \retval -ENOENT Invalid MD object.
2415  */
2416 int
2417 LNetGet(lnet_nid_t self, lnet_handle_md_t mdh,
2418         lnet_process_id_t target, unsigned int portal,
2419         __u64 match_bits, unsigned int offset)
2420 {
2421         struct lnet_msg         *msg;
2422         struct lnet_libmd       *md;
2423         int                     cpt;
2424         int                     rc;
2425
2426         LASSERT (the_lnet.ln_init);
2427         LASSERT (the_lnet.ln_refcount > 0);
2428
2429         if (!list_empty(&the_lnet.ln_test_peers) &&     /* normally we don't */
2430             fail_peer(target.nid, 1))                   /* shall we now? */
2431         {
2432                 CERROR("Dropping GET to %s: simulated failure\n",
2433                        libcfs_id2str(target));
2434                 return -EIO;
2435         }
2436
2437         msg = lnet_msg_alloc();
2438         if (msg == NULL) {
2439                 CERROR("Dropping GET to %s: ENOMEM on lnet_msg_t\n",
2440                        libcfs_id2str(target));
2441                 return -ENOMEM;
2442         }
2443
2444         cpt = lnet_cpt_of_cookie(mdh.cookie);
2445         lnet_res_lock(cpt);
2446
2447         md = lnet_handle2md(&mdh);
2448         if (md == NULL || md->md_threshold == 0 || md->md_me != NULL) {
2449                 CERROR("Dropping GET ("LPU64":%d:%s): MD (%d) invalid\n",
2450                        match_bits, portal, libcfs_id2str(target),
2451                        md == NULL ? -1 : md->md_threshold);
2452                 if (md != NULL && md->md_me != NULL)
2453                         CERROR("REPLY MD also attached to portal %d\n",
2454                                md->md_me->me_portal);
2455
2456                 lnet_res_unlock(cpt);
2457
2458                 lnet_msg_free(msg);
2459                 return -ENOENT;
2460         }
2461
2462         CDEBUG(D_NET, "LNetGet -> %s\n", libcfs_id2str(target));
2463
2464         lnet_msg_attach_md(msg, md, 0, 0);
2465
2466         lnet_prep_send(msg, LNET_MSG_GET, target, 0, 0);
2467
2468         msg->msg_hdr.msg.get.match_bits = cpu_to_le64(match_bits);
2469         msg->msg_hdr.msg.get.ptl_index = cpu_to_le32(portal);
2470         msg->msg_hdr.msg.get.src_offset = cpu_to_le32(offset);
2471         msg->msg_hdr.msg.get.sink_length = cpu_to_le32(md->md_length);
2472
2473         /* NB handles only looked up by creator (no flips) */
2474         msg->msg_hdr.msg.get.return_wmd.wh_interface_cookie =
2475                 the_lnet.ln_interface_cookie;
2476         msg->msg_hdr.msg.get.return_wmd.wh_object_cookie =
2477                 md->md_lh.lh_cookie;
2478
2479         lnet_res_unlock(cpt);
2480
2481         lnet_build_msg_event(msg, LNET_EVENT_SEND);
2482
2483         rc = lnet_send(self, msg, LNET_NID_ANY);
2484         if (rc < 0) {
2485                 CNETERR("Error sending GET to %s: %d\n",
2486                         libcfs_id2str(target), rc);
2487                 lnet_finalize(NULL, msg, rc);
2488         }
2489
2490         /* completion will be signalled by an event */
2491         return 0;
2492 }
2493 EXPORT_SYMBOL(LNetGet);
2494
2495 /**
2496  * Calculate distance to node at \a dstnid.
2497  *
2498  * \param dstnid Target NID.
2499  * \param srcnidp If not NULL, NID of the local interface to reach \a dstnid
2500  * is saved here.
2501  * \param orderp If not NULL, order of the route to reach \a dstnid is saved
2502  * here.
2503  *
2504  * \retval 0 If \a dstnid belongs to a local interface, and reserved option
2505  * local_nid_dist_zero is set, which is the default.
2506  * \retval positives Distance to target NID, i.e. number of hops plus one.
2507  * \retval -EHOSTUNREACH If \a dstnid is not reachable.
2508  */
2509 int
2510 LNetDist(lnet_nid_t dstnid, lnet_nid_t *srcnidp, __u32 *orderp)
2511 {
2512         struct list_head        *e;
2513         struct lnet_ni          *ni;
2514         lnet_remotenet_t        *rnet;
2515         __u32                   dstnet = LNET_NIDNET(dstnid);
2516         int                     hops;
2517         int                     cpt;
2518         __u32                   order = 2;
2519         struct list_head        *rn_list;
2520
2521         /* if !local_nid_dist_zero, I don't return a distance of 0 ever
2522          * (when lustre sees a distance of 0, it substitutes 0@lo), so I
2523          * keep order 0 free for 0@lo and order 1 free for a local NID
2524          * match */
2525
2526         LASSERT (the_lnet.ln_init);
2527         LASSERT (the_lnet.ln_refcount > 0);
2528
2529         cpt = lnet_net_lock_current();
2530
2531         list_for_each(e, &the_lnet.ln_nis) {
2532                 ni = list_entry(e, lnet_ni_t, ni_list);
2533
2534                 if (ni->ni_nid == dstnid) {
2535                         if (srcnidp != NULL)
2536                                 *srcnidp = dstnid;
2537                         if (orderp != NULL) {
2538                                 if (LNET_NETTYP(LNET_NIDNET(dstnid)) == LOLND)
2539                                         *orderp = 0;
2540                                 else
2541                                         *orderp = 1;
2542                         }
2543                         lnet_net_unlock(cpt);
2544
2545                         return local_nid_dist_zero ? 0 : 1;
2546                 }
2547
2548                 if (LNET_NIDNET(ni->ni_nid) == dstnet) {
2549                         if (srcnidp != NULL)
2550                                 *srcnidp = ni->ni_nid;
2551                         if (orderp != NULL)
2552                                 *orderp = order;
2553                         lnet_net_unlock(cpt);
2554                         return 1;
2555                 }
2556
2557                 order++;
2558         }
2559
2560         rn_list = lnet_net2rnethash(dstnet);
2561         list_for_each(e, rn_list) {
2562                 rnet = list_entry(e, lnet_remotenet_t, lrn_list);
2563
2564                 if (rnet->lrn_net == dstnet) {
2565                         lnet_route_t *route;
2566                         lnet_route_t *shortest = NULL;
2567
2568                         LASSERT(!list_empty(&rnet->lrn_routes));
2569
2570                         list_for_each_entry(route, &rnet->lrn_routes,
2571                                             lr_list) {
2572                                 if (shortest == NULL ||
2573                                     route->lr_hops < shortest->lr_hops)
2574                                         shortest = route;
2575                         }
2576
2577                         LASSERT (shortest != NULL);
2578                         hops = shortest->lr_hops;
2579                         if (srcnidp != NULL)
2580                                 *srcnidp = shortest->lr_gateway->lp_ni->ni_nid;
2581                         if (orderp != NULL)
2582                                 *orderp = order;
2583                         lnet_net_unlock(cpt);
2584                         return hops + 1;
2585                 }
2586                 order++;
2587         }
2588
2589         lnet_net_unlock(cpt);
2590         return -EHOSTUNREACH;
2591 }
2592 EXPORT_SYMBOL(LNetDist);
2593
2594 /**
2595  * Set the number of asynchronous messages expected from a target process.
2596  *
2597  * This function is only meaningful for userspace callers. It's a no-op when
2598  * called from kernel.
2599  *
2600  * Asynchronous messages are those that can come from a target when the
2601  * userspace process is not waiting for IO to complete; e.g., AST callbacks
2602  * from Lustre servers. Specifying the expected number of such messages
2603  * allows them to be eagerly received when user process is not running in
2604  * LNet; otherwise network errors may occur.
2605  *
2606  * \param id Process ID of the target process.
2607  * \param nasync Number of asynchronous messages expected from the target.
2608  *
2609  * \return 0 on success, and an error code otherwise.
2610  */
2611 int
2612 LNetSetAsync(lnet_process_id_t id, int nasync)
2613 {
2614 #ifdef __KERNEL__
2615         return 0;
2616 #else
2617         lnet_ni_t        *ni;
2618         lnet_remotenet_t *rnet;
2619         struct list_head *tmp;
2620         lnet_route_t     *route;
2621         lnet_nid_t       *nids;
2622         int               nnids;
2623         int               maxnids = 256;
2624         int               rc = 0;
2625         int               rc2;
2626         int                     cpt;
2627
2628         /* Target on a local network? */
2629         ni = lnet_net2ni(LNET_NIDNET(id.nid));
2630         if (ni != NULL) {
2631                 if (ni->ni_lnd->lnd_setasync != NULL) 
2632                         rc = (ni->ni_lnd->lnd_setasync)(ni, id, nasync);
2633                 lnet_ni_decref(ni);
2634                 return rc;
2635         }
2636
2637         /* Target on a remote network: apply to routers */
2638  again:
2639         LIBCFS_ALLOC(nids, maxnids * sizeof(*nids));
2640         if (nids == NULL)
2641                 return -ENOMEM;
2642         nnids = 0;
2643
2644         /* Snapshot all the router NIDs */
2645         cpt = lnet_net_lock_current();
2646         rnet = lnet_find_net_locked(LNET_NIDNET(id.nid));
2647         if (rnet != NULL) {
2648                 list_for_each(tmp, &rnet->lrn_routes) {
2649                         if (nnids == maxnids) {
2650                                 lnet_net_unlock(cpt);
2651                                 LIBCFS_FREE(nids, maxnids * sizeof(*nids));
2652                                 maxnids *= 2;
2653                                 goto again;
2654                         }
2655
2656                         route = list_entry(tmp, lnet_route_t, lr_list);
2657                         nids[nnids++] = route->lr_gateway->lp_nid;
2658                 }
2659         }
2660         lnet_net_unlock(cpt);
2661
2662         /* set async on all the routers */
2663         while (nnids-- > 0) {
2664                 id.pid = LNET_PID_LUSTRE;
2665                 id.nid = nids[nnids];
2666
2667                 ni = lnet_net2ni(LNET_NIDNET(id.nid));
2668                 if (ni == NULL)
2669                         continue;
2670
2671                 if (ni->ni_lnd->lnd_setasync != NULL) {
2672                         rc2 = (ni->ni_lnd->lnd_setasync)(ni, id, nasync);
2673                         if (rc2 != 0)
2674                                 rc = rc2;
2675                 }
2676                 lnet_ni_decref(ni);
2677         }
2678
2679         LIBCFS_FREE(nids, maxnids * sizeof(*nids));
2680         return rc;
2681 #endif
2682 }
2683 EXPORT_SYMBOL(LNetSetAsync);