Whamcloud - gitweb
LU-9480 lnet: add "lnetctl discover"
[fs/lustre-release.git] / lnet / lnet / lib-move.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2012, 2016, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  * Lustre is a trademark of Sun Microsystems, Inc.
31  *
32  * lnet/lnet/lib-move.c
33  *
34  * Data movement routines
35  */
36
37 #define DEBUG_SUBSYSTEM S_LNET
38
39 #include <lnet/lib-lnet.h>
40 #include <linux/nsproxy.h>
41 #include <net/net_namespace.h>
42
43 static int local_nid_dist_zero = 1;
44 module_param(local_nid_dist_zero, int, 0444);
45 MODULE_PARM_DESC(local_nid_dist_zero, "Reserved");
46
47 int
48 lnet_fail_nid(lnet_nid_t nid, unsigned int threshold)
49 {
50         struct lnet_test_peer *tp;
51         struct list_head *el;
52         struct list_head *next;
53         struct list_head  cull;
54
55         /* NB: use lnet_net_lock(0) to serialize operations on test peers */
56         if (threshold != 0) {
57                 /* Adding a new entry */
58                 LIBCFS_ALLOC(tp, sizeof(*tp));
59                 if (tp == NULL)
60                         return -ENOMEM;
61
62                 tp->tp_nid = nid;
63                 tp->tp_threshold = threshold;
64
65                 lnet_net_lock(0);
66                 list_add_tail(&tp->tp_list, &the_lnet.ln_test_peers);
67                 lnet_net_unlock(0);
68                 return 0;
69         }
70
71         /* removing entries */
72         INIT_LIST_HEAD(&cull);
73
74         lnet_net_lock(0);
75
76         list_for_each_safe(el, next, &the_lnet.ln_test_peers) {
77                 tp = list_entry(el, struct lnet_test_peer, tp_list);
78
79                 if (tp->tp_threshold == 0 ||    /* needs culling anyway */
80                     nid == LNET_NID_ANY ||      /* removing all entries */
81                     tp->tp_nid == nid) {        /* matched this one */
82                         list_del(&tp->tp_list);
83                         list_add(&tp->tp_list, &cull);
84                 }
85         }
86
87         lnet_net_unlock(0);
88
89         while (!list_empty(&cull)) {
90                 tp = list_entry(cull.next, struct lnet_test_peer, tp_list);
91
92                 list_del(&tp->tp_list);
93                 LIBCFS_FREE(tp, sizeof(*tp));
94         }
95         return 0;
96 }
97
98 static int
99 fail_peer (lnet_nid_t nid, int outgoing)
100 {
101         struct lnet_test_peer *tp;
102         struct list_head *el;
103         struct list_head *next;
104         struct list_head  cull;
105         int               fail = 0;
106
107         INIT_LIST_HEAD(&cull);
108
109         /* NB: use lnet_net_lock(0) to serialize operations on test peers */
110         lnet_net_lock(0);
111
112         list_for_each_safe(el, next, &the_lnet.ln_test_peers) {
113                 tp = list_entry(el, struct lnet_test_peer, tp_list);
114
115                 if (tp->tp_threshold == 0) {
116                         /* zombie entry */
117                         if (outgoing) {
118                                 /* only cull zombies on outgoing tests,
119                                  * since we may be at interrupt priority on
120                                  * incoming messages. */
121                                 list_del(&tp->tp_list);
122                                 list_add(&tp->tp_list, &cull);
123                         }
124                         continue;
125                 }
126
127                 if (tp->tp_nid == LNET_NID_ANY ||       /* fail every peer */
128                     nid == tp->tp_nid) {                /* fail this peer */
129                         fail = 1;
130
131                         if (tp->tp_threshold != LNET_MD_THRESH_INF) {
132                                 tp->tp_threshold--;
133                                 if (outgoing &&
134                                     tp->tp_threshold == 0) {
135                                         /* see above */
136                                         list_del(&tp->tp_list);
137                                         list_add(&tp->tp_list, &cull);
138                                 }
139                         }
140                         break;
141                 }
142         }
143
144         lnet_net_unlock(0);
145
146         while (!list_empty(&cull)) {
147                 tp = list_entry(cull.next, struct lnet_test_peer, tp_list);
148                 list_del(&tp->tp_list);
149
150                 LIBCFS_FREE(tp, sizeof(*tp));
151         }
152
153         return fail;
154 }
155
156 unsigned int
157 lnet_iov_nob(unsigned int niov, struct kvec *iov)
158 {
159         unsigned int nob = 0;
160
161         LASSERT(niov == 0 || iov != NULL);
162         while (niov-- > 0)
163                 nob += (iov++)->iov_len;
164
165         return (nob);
166 }
167 EXPORT_SYMBOL(lnet_iov_nob);
168
169 void
170 lnet_copy_iov2iov(unsigned int ndiov, struct kvec *diov, unsigned int doffset,
171                   unsigned int nsiov, struct kvec *siov, unsigned int soffset,
172                   unsigned int nob)
173 {
174         /* NB diov, siov are READ-ONLY */
175         unsigned int  this_nob;
176
177         if (nob == 0)
178                 return;
179
180         /* skip complete frags before 'doffset' */
181         LASSERT(ndiov > 0);
182         while (doffset >= diov->iov_len) {
183                 doffset -= diov->iov_len;
184                 diov++;
185                 ndiov--;
186                 LASSERT(ndiov > 0);
187         }
188
189         /* skip complete frags before 'soffset' */
190         LASSERT(nsiov > 0);
191         while (soffset >= siov->iov_len) {
192                 soffset -= siov->iov_len;
193                 siov++;
194                 nsiov--;
195                 LASSERT(nsiov > 0);
196         }
197
198         do {
199                 LASSERT(ndiov > 0);
200                 LASSERT(nsiov > 0);
201                 this_nob = MIN(diov->iov_len - doffset,
202                                siov->iov_len - soffset);
203                 this_nob = MIN(this_nob, nob);
204
205                 memcpy((char *)diov->iov_base + doffset,
206                        (char *)siov->iov_base + soffset, this_nob);
207                 nob -= this_nob;
208
209                 if (diov->iov_len > doffset + this_nob) {
210                         doffset += this_nob;
211                 } else {
212                         diov++;
213                         ndiov--;
214                         doffset = 0;
215                 }
216
217                 if (siov->iov_len > soffset + this_nob) {
218                         soffset += this_nob;
219                 } else {
220                         siov++;
221                         nsiov--;
222                         soffset = 0;
223                 }
224         } while (nob > 0);
225 }
226 EXPORT_SYMBOL(lnet_copy_iov2iov);
227
228 int
229 lnet_extract_iov(int dst_niov, struct kvec *dst,
230                  int src_niov, struct kvec *src,
231                  unsigned int offset, unsigned int len)
232 {
233         /* Initialise 'dst' to the subset of 'src' starting at 'offset',
234          * for exactly 'len' bytes, and return the number of entries.
235          * NB not destructive to 'src' */
236         unsigned int    frag_len;
237         unsigned int    niov;
238
239         if (len == 0)                           /* no data => */
240                 return (0);                     /* no frags */
241
242         LASSERT(src_niov > 0);
243         while (offset >= src->iov_len) {      /* skip initial frags */
244                 offset -= src->iov_len;
245                 src_niov--;
246                 src++;
247                 LASSERT(src_niov > 0);
248         }
249
250         niov = 1;
251         for (;;) {
252                 LASSERT(src_niov > 0);
253                 LASSERT((int)niov <= dst_niov);
254
255                 frag_len = src->iov_len - offset;
256                 dst->iov_base = ((char *)src->iov_base) + offset;
257
258                 if (len <= frag_len) {
259                         dst->iov_len = len;
260                         return (niov);
261                 }
262
263                 dst->iov_len = frag_len;
264
265                 len -= frag_len;
266                 dst++;
267                 src++;
268                 niov++;
269                 src_niov--;
270                 offset = 0;
271         }
272 }
273 EXPORT_SYMBOL(lnet_extract_iov);
274
275
276 unsigned int
277 lnet_kiov_nob(unsigned int niov, lnet_kiov_t *kiov)
278 {
279         unsigned int  nob = 0;
280
281         LASSERT(niov == 0 || kiov != NULL);
282         while (niov-- > 0)
283                 nob += (kiov++)->kiov_len;
284
285         return (nob);
286 }
287 EXPORT_SYMBOL(lnet_kiov_nob);
288
289 void
290 lnet_copy_kiov2kiov(unsigned int ndiov, lnet_kiov_t *diov, unsigned int doffset,
291                     unsigned int nsiov, lnet_kiov_t *siov, unsigned int soffset,
292                     unsigned int nob)
293 {
294         /* NB diov, siov are READ-ONLY */
295         unsigned int    this_nob;
296         char           *daddr = NULL;
297         char           *saddr = NULL;
298
299         if (nob == 0)
300                 return;
301
302         LASSERT (!in_interrupt ());
303
304         LASSERT (ndiov > 0);
305         while (doffset >= diov->kiov_len) {
306                 doffset -= diov->kiov_len;
307                 diov++;
308                 ndiov--;
309                 LASSERT(ndiov > 0);
310         }
311
312         LASSERT(nsiov > 0);
313         while (soffset >= siov->kiov_len) {
314                 soffset -= siov->kiov_len;
315                 siov++;
316                 nsiov--;
317                 LASSERT(nsiov > 0);
318         }
319
320         do {
321                 LASSERT(ndiov > 0);
322                 LASSERT(nsiov > 0);
323                 this_nob = MIN(diov->kiov_len - doffset,
324                                siov->kiov_len - soffset);
325                 this_nob = MIN(this_nob, nob);
326
327                 if (daddr == NULL)
328                         daddr = ((char *)kmap(diov->kiov_page)) +
329                                 diov->kiov_offset + doffset;
330                 if (saddr == NULL)
331                         saddr = ((char *)kmap(siov->kiov_page)) +
332                                 siov->kiov_offset + soffset;
333
334                 /* Vanishing risk of kmap deadlock when mapping 2 pages.
335                  * However in practice at least one of the kiovs will be mapped
336                  * kernel pages and the map/unmap will be NOOPs */
337
338                 memcpy (daddr, saddr, this_nob);
339                 nob -= this_nob;
340
341                 if (diov->kiov_len > doffset + this_nob) {
342                         daddr += this_nob;
343                         doffset += this_nob;
344                 } else {
345                         kunmap(diov->kiov_page);
346                         daddr = NULL;
347                         diov++;
348                         ndiov--;
349                         doffset = 0;
350                 }
351
352                 if (siov->kiov_len > soffset + this_nob) {
353                         saddr += this_nob;
354                         soffset += this_nob;
355                 } else {
356                         kunmap(siov->kiov_page);
357                         saddr = NULL;
358                         siov++;
359                         nsiov--;
360                         soffset = 0;
361                 }
362         } while (nob > 0);
363
364         if (daddr != NULL)
365                 kunmap(diov->kiov_page);
366         if (saddr != NULL)
367                 kunmap(siov->kiov_page);
368 }
369 EXPORT_SYMBOL(lnet_copy_kiov2kiov);
370
371 void
372 lnet_copy_kiov2iov (unsigned int niov, struct kvec *iov, unsigned int iovoffset,
373                     unsigned int nkiov, lnet_kiov_t *kiov, unsigned int kiovoffset,
374                     unsigned int nob)
375 {
376         /* NB iov, kiov are READ-ONLY */
377         unsigned int    this_nob;
378         char           *addr = NULL;
379
380         if (nob == 0)
381                 return;
382
383         LASSERT (!in_interrupt ());
384
385         LASSERT (niov > 0);
386         while (iovoffset >= iov->iov_len) {
387                 iovoffset -= iov->iov_len;
388                 iov++;
389                 niov--;
390                 LASSERT(niov > 0);
391         }
392
393         LASSERT(nkiov > 0);
394         while (kiovoffset >= kiov->kiov_len) {
395                 kiovoffset -= kiov->kiov_len;
396                 kiov++;
397                 nkiov--;
398                 LASSERT(nkiov > 0);
399         }
400
401         do {
402                 LASSERT(niov > 0);
403                 LASSERT(nkiov > 0);
404                 this_nob = MIN(iov->iov_len - iovoffset,
405                                kiov->kiov_len - kiovoffset);
406                 this_nob = MIN(this_nob, nob);
407
408                 if (addr == NULL)
409                         addr = ((char *)kmap(kiov->kiov_page)) +
410                                 kiov->kiov_offset + kiovoffset;
411
412                 memcpy((char *)iov->iov_base + iovoffset, addr, this_nob);
413                 nob -= this_nob;
414
415                 if (iov->iov_len > iovoffset + this_nob) {
416                         iovoffset += this_nob;
417                 } else {
418                         iov++;
419                         niov--;
420                         iovoffset = 0;
421                 }
422
423                 if (kiov->kiov_len > kiovoffset + this_nob) {
424                         addr += this_nob;
425                         kiovoffset += this_nob;
426                 } else {
427                         kunmap(kiov->kiov_page);
428                         addr = NULL;
429                         kiov++;
430                         nkiov--;
431                         kiovoffset = 0;
432                 }
433
434         } while (nob > 0);
435
436         if (addr != NULL)
437                 kunmap(kiov->kiov_page);
438 }
439 EXPORT_SYMBOL(lnet_copy_kiov2iov);
440
441 void
442 lnet_copy_iov2kiov(unsigned int nkiov, lnet_kiov_t *kiov, unsigned int kiovoffset,
443                    unsigned int niov, struct kvec *iov, unsigned int iovoffset,
444                    unsigned int nob)
445 {
446         /* NB kiov, iov are READ-ONLY */
447         unsigned int    this_nob;
448         char           *addr = NULL;
449
450         if (nob == 0)
451                 return;
452
453         LASSERT (!in_interrupt ());
454
455         LASSERT (nkiov > 0);
456         while (kiovoffset >= kiov->kiov_len) {
457                 kiovoffset -= kiov->kiov_len;
458                 kiov++;
459                 nkiov--;
460                 LASSERT(nkiov > 0);
461         }
462
463         LASSERT(niov > 0);
464         while (iovoffset >= iov->iov_len) {
465                 iovoffset -= iov->iov_len;
466                 iov++;
467                 niov--;
468                 LASSERT(niov > 0);
469         }
470
471         do {
472                 LASSERT(nkiov > 0);
473                 LASSERT(niov > 0);
474                 this_nob = MIN(kiov->kiov_len - kiovoffset,
475                                iov->iov_len - iovoffset);
476                 this_nob = MIN(this_nob, nob);
477
478                 if (addr == NULL)
479                         addr = ((char *)kmap(kiov->kiov_page)) +
480                                 kiov->kiov_offset + kiovoffset;
481
482                 memcpy (addr, (char *)iov->iov_base + iovoffset, this_nob);
483                 nob -= this_nob;
484
485                 if (kiov->kiov_len > kiovoffset + this_nob) {
486                         addr += this_nob;
487                         kiovoffset += this_nob;
488                 } else {
489                         kunmap(kiov->kiov_page);
490                         addr = NULL;
491                         kiov++;
492                         nkiov--;
493                         kiovoffset = 0;
494                 }
495
496                 if (iov->iov_len > iovoffset + this_nob) {
497                         iovoffset += this_nob;
498                 } else {
499                         iov++;
500                         niov--;
501                         iovoffset = 0;
502                 }
503         } while (nob > 0);
504
505         if (addr != NULL)
506                 kunmap(kiov->kiov_page);
507 }
508 EXPORT_SYMBOL(lnet_copy_iov2kiov);
509
510 int
511 lnet_extract_kiov(int dst_niov, lnet_kiov_t *dst,
512                   int src_niov, lnet_kiov_t *src,
513                   unsigned int offset, unsigned int len)
514 {
515         /* Initialise 'dst' to the subset of 'src' starting at 'offset',
516          * for exactly 'len' bytes, and return the number of entries.
517          * NB not destructive to 'src' */
518         unsigned int    frag_len;
519         unsigned int    niov;
520
521         if (len == 0)                           /* no data => */
522                 return (0);                     /* no frags */
523
524         LASSERT(src_niov > 0);
525         while (offset >= src->kiov_len) {      /* skip initial frags */
526                 offset -= src->kiov_len;
527                 src_niov--;
528                 src++;
529                 LASSERT(src_niov > 0);
530         }
531
532         niov = 1;
533         for (;;) {
534                 LASSERT(src_niov > 0);
535                 LASSERT((int)niov <= dst_niov);
536
537                 frag_len = src->kiov_len - offset;
538                 dst->kiov_page = src->kiov_page;
539                 dst->kiov_offset = src->kiov_offset + offset;
540
541                 if (len <= frag_len) {
542                         dst->kiov_len = len;
543                         LASSERT(dst->kiov_offset + dst->kiov_len <= PAGE_SIZE);
544                         return niov;
545                 }
546
547                 dst->kiov_len = frag_len;
548                 LASSERT(dst->kiov_offset + dst->kiov_len <= PAGE_SIZE);
549
550                 len -= frag_len;
551                 dst++;
552                 src++;
553                 niov++;
554                 src_niov--;
555                 offset = 0;
556         }
557 }
558 EXPORT_SYMBOL(lnet_extract_kiov);
559
560 void
561 lnet_ni_recv(struct lnet_ni *ni, void *private, struct lnet_msg *msg,
562              int delayed, unsigned int offset, unsigned int mlen,
563              unsigned int rlen)
564 {
565         unsigned int  niov = 0;
566         struct kvec *iov = NULL;
567         lnet_kiov_t  *kiov = NULL;
568         int           rc;
569
570         LASSERT (!in_interrupt ());
571         LASSERT (mlen == 0 || msg != NULL);
572
573         if (msg != NULL) {
574                 LASSERT(msg->msg_receiving);
575                 LASSERT(!msg->msg_sending);
576                 LASSERT(rlen == msg->msg_len);
577                 LASSERT(mlen <= msg->msg_len);
578                 LASSERT(msg->msg_offset == offset);
579                 LASSERT(msg->msg_wanted == mlen);
580
581                 msg->msg_receiving = 0;
582
583                 if (mlen != 0) {
584                         niov = msg->msg_niov;
585                         iov  = msg->msg_iov;
586                         kiov = msg->msg_kiov;
587
588                         LASSERT (niov > 0);
589                         LASSERT ((iov == NULL) != (kiov == NULL));
590                 }
591         }
592
593         rc = (ni->ni_net->net_lnd->lnd_recv)(ni, private, msg, delayed,
594                                              niov, iov, kiov, offset, mlen,
595                                              rlen);
596         if (rc < 0)
597                 lnet_finalize(msg, rc);
598 }
599
600 static void
601 lnet_setpayloadbuffer(struct lnet_msg *msg)
602 {
603         struct lnet_libmd *md = msg->msg_md;
604
605         LASSERT(msg->msg_len > 0);
606         LASSERT(!msg->msg_routing);
607         LASSERT(md != NULL);
608         LASSERT(msg->msg_niov == 0);
609         LASSERT(msg->msg_iov == NULL);
610         LASSERT(msg->msg_kiov == NULL);
611
612         msg->msg_niov = md->md_niov;
613         if ((md->md_options & LNET_MD_KIOV) != 0)
614                 msg->msg_kiov = md->md_iov.kiov;
615         else
616                 msg->msg_iov = md->md_iov.iov;
617 }
618
619 void
620 lnet_prep_send(struct lnet_msg *msg, int type, struct lnet_process_id target,
621                unsigned int offset, unsigned int len)
622 {
623         msg->msg_type = type;
624         msg->msg_target = target;
625         msg->msg_len = len;
626         msg->msg_offset = offset;
627
628         if (len != 0)
629                 lnet_setpayloadbuffer(msg);
630
631         memset (&msg->msg_hdr, 0, sizeof (msg->msg_hdr));
632         msg->msg_hdr.type           = cpu_to_le32(type);
633         /* dest_nid will be overwritten by lnet_select_pathway() */
634         msg->msg_hdr.dest_nid       = cpu_to_le64(target.nid);
635         msg->msg_hdr.dest_pid       = cpu_to_le32(target.pid);
636         /* src_nid will be set later */
637         msg->msg_hdr.src_pid        = cpu_to_le32(the_lnet.ln_pid);
638         msg->msg_hdr.payload_length = cpu_to_le32(len);
639 }
640
641 static void
642 lnet_ni_send(struct lnet_ni *ni, struct lnet_msg *msg)
643 {
644         void   *priv = msg->msg_private;
645         int     rc;
646
647         LASSERT (!in_interrupt ());
648         LASSERT (LNET_NETTYP(LNET_NIDNET(ni->ni_nid)) == LOLND ||
649                  (msg->msg_txcredit && msg->msg_peertxcredit));
650
651         rc = (ni->ni_net->net_lnd->lnd_send)(ni, priv, msg);
652         if (rc < 0)
653                 lnet_finalize(msg, rc);
654 }
655
656 static int
657 lnet_ni_eager_recv(struct lnet_ni *ni, struct lnet_msg *msg)
658 {
659         int     rc;
660
661         LASSERT(!msg->msg_sending);
662         LASSERT(msg->msg_receiving);
663         LASSERT(!msg->msg_rx_ready_delay);
664         LASSERT(ni->ni_net->net_lnd->lnd_eager_recv != NULL);
665
666         msg->msg_rx_ready_delay = 1;
667         rc = (ni->ni_net->net_lnd->lnd_eager_recv)(ni, msg->msg_private, msg,
668                                                   &msg->msg_private);
669         if (rc != 0) {
670                 CERROR("recv from %s / send to %s aborted: "
671                        "eager_recv failed %d\n",
672                        libcfs_nid2str(msg->msg_rxpeer->lpni_nid),
673                        libcfs_id2str(msg->msg_target), rc);
674                 LASSERT(rc < 0); /* required by my callers */
675         }
676
677         return rc;
678 }
679
680 /*
681  * This function can be called from two paths:
682  *      1. when sending a message
683  *      2. when decommiting a message (lnet_msg_decommit_tx())
684  * In both these cases the peer_ni should have it's reference count
685  * acquired by the caller and therefore it is safe to drop the spin
686  * lock before calling lnd_query()
687  */
688 static void
689 lnet_ni_query_locked(struct lnet_ni *ni, struct lnet_peer_ni *lp)
690 {
691         cfs_time_t last_alive = 0;
692         int cpt = lnet_cpt_of_nid_locked(lp->lpni_nid, ni);
693
694         LASSERT(lnet_peer_aliveness_enabled(lp));
695         LASSERT(ni->ni_net->net_lnd->lnd_query != NULL);
696
697         lnet_net_unlock(cpt);
698         (ni->ni_net->net_lnd->lnd_query)(ni, lp->lpni_nid, &last_alive);
699         lnet_net_lock(cpt);
700
701         lp->lpni_last_query = cfs_time_current();
702
703         if (last_alive != 0) /* NI has updated timestamp */
704                 lp->lpni_last_alive = last_alive;
705 }
706
707 /* NB: always called with lnet_net_lock held */
708 static inline int
709 lnet_peer_is_alive (struct lnet_peer_ni *lp, cfs_time_t now)
710 {
711         int        alive;
712         cfs_time_t deadline;
713
714         LASSERT (lnet_peer_aliveness_enabled(lp));
715
716         /*
717          * Trust lnet_notify() if it has more recent aliveness news, but
718          * ignore the initial assumed death (see lnet_peers_start_down()).
719          */
720         spin_lock(&lp->lpni_lock);
721         if (!lp->lpni_alive && lp->lpni_alive_count > 0 &&
722             cfs_time_aftereq(lp->lpni_timestamp, lp->lpni_last_alive)) {
723                 spin_unlock(&lp->lpni_lock);
724                 return 0;
725         }
726
727         deadline =
728           cfs_time_add(lp->lpni_last_alive,
729                        cfs_time_seconds(lp->lpni_net->net_tunables.
730                                         lct_peer_timeout));
731         alive = cfs_time_after(deadline, now);
732
733         /*
734          * Update obsolete lp_alive except for routers assumed to be dead
735          * initially, because router checker would update aliveness in this
736          * case, and moreover lpni_last_alive at peer creation is assumed.
737          */
738         if (alive && !lp->lpni_alive &&
739             !(lnet_isrouter(lp) && lp->lpni_alive_count == 0)) {
740                 spin_unlock(&lp->lpni_lock);
741                 lnet_notify_locked(lp, 0, 1, lp->lpni_last_alive);
742         } else {
743                 spin_unlock(&lp->lpni_lock);
744         }
745
746         return alive;
747 }
748
749
750 /* NB: returns 1 when alive, 0 when dead, negative when error;
751  *     may drop the lnet_net_lock */
752 static int
753 lnet_peer_alive_locked (struct lnet_ni *ni, struct lnet_peer_ni *lp)
754 {
755         cfs_time_t now = cfs_time_current();
756
757         if (!lnet_peer_aliveness_enabled(lp))
758                 return -ENODEV;
759
760         if (lnet_peer_is_alive(lp, now))
761                 return 1;
762
763         /*
764          * Peer appears dead, but we should avoid frequent NI queries (at
765          * most once per lnet_queryinterval seconds).
766          */
767         if (lp->lpni_last_query != 0) {
768                 static const int lnet_queryinterval = 1;
769
770                 cfs_time_t next_query =
771                            cfs_time_add(lp->lpni_last_query,
772                                         cfs_time_seconds(lnet_queryinterval));
773
774                 if (cfs_time_before(now, next_query)) {
775                         if (lp->lpni_alive)
776                                 CWARN("Unexpected aliveness of peer %s: "
777                                       "%d < %d (%d/%d)\n",
778                                       libcfs_nid2str(lp->lpni_nid),
779                                       (int)now, (int)next_query,
780                                       lnet_queryinterval,
781                                       lp->lpni_net->net_tunables.lct_peer_timeout);
782                         return 0;
783                 }
784         }
785
786         /* query NI for latest aliveness news */
787         lnet_ni_query_locked(ni, lp);
788
789         if (lnet_peer_is_alive(lp, now))
790                 return 1;
791
792         lnet_notify_locked(lp, 0, 0, lp->lpni_last_alive);
793         return 0;
794 }
795
796 /**
797  * \param msg The message to be sent.
798  * \param do_send True if lnet_ni_send() should be called in this function.
799  *        lnet_send() is going to lnet_net_unlock immediately after this, so
800  *        it sets do_send FALSE and I don't do the unlock/send/lock bit.
801  *
802  * \retval LNET_CREDIT_OK If \a msg sent or OK to send.
803  * \retval LNET_CREDIT_WAIT If \a msg blocked for credit.
804  * \retval -EHOSTUNREACH If the next hop of the message appears dead.
805  * \retval -ECANCELED If the MD of the message has been unlinked.
806  */
807 static int
808 lnet_post_send_locked(struct lnet_msg *msg, int do_send)
809 {
810         struct lnet_peer_ni     *lp = msg->msg_txpeer;
811         struct lnet_ni          *ni = msg->msg_txni;
812         int                     cpt = msg->msg_tx_cpt;
813         struct lnet_tx_queue    *tq = ni->ni_tx_queues[cpt];
814
815         /* non-lnet_send() callers have checked before */
816         LASSERT(!do_send || msg->msg_tx_delayed);
817         LASSERT(!msg->msg_receiving);
818         LASSERT(msg->msg_tx_committed);
819
820         /* NB 'lp' is always the next hop */
821         if ((msg->msg_target.pid & LNET_PID_USERFLAG) == 0 &&
822             lnet_peer_alive_locked(ni, lp) == 0) {
823                 the_lnet.ln_counters[cpt]->drop_count++;
824                 the_lnet.ln_counters[cpt]->drop_length += msg->msg_len;
825                 lnet_net_unlock(cpt);
826                 if (msg->msg_txpeer)
827                         atomic_inc(&msg->msg_txpeer->lpni_stats.drop_count);
828                 if (msg->msg_txni)
829                         atomic_inc(&msg->msg_txni->ni_stats.drop_count);
830
831                 CNETERR("Dropping message for %s: peer not alive\n",
832                         libcfs_id2str(msg->msg_target));
833                 if (do_send)
834                         lnet_finalize(msg, -EHOSTUNREACH);
835
836                 lnet_net_lock(cpt);
837                 return -EHOSTUNREACH;
838         }
839
840         if (msg->msg_md != NULL &&
841             (msg->msg_md->md_flags & LNET_MD_FLAG_ABORTED) != 0) {
842                 lnet_net_unlock(cpt);
843
844                 CNETERR("Aborting message for %s: LNetM[DE]Unlink() already "
845                         "called on the MD/ME.\n",
846                         libcfs_id2str(msg->msg_target));
847                 if (do_send)
848                         lnet_finalize(msg, -ECANCELED);
849
850                 lnet_net_lock(cpt);
851                 return -ECANCELED;
852         }
853
854         if (!msg->msg_peertxcredit) {
855                 spin_lock(&lp->lpni_lock);
856                 LASSERT((lp->lpni_txcredits < 0) ==
857                         !list_empty(&lp->lpni_txq));
858
859                 msg->msg_peertxcredit = 1;
860                 lp->lpni_txqnob += msg->msg_len + sizeof(struct lnet_hdr);
861                 lp->lpni_txcredits--;
862
863                 if (lp->lpni_txcredits < lp->lpni_mintxcredits)
864                         lp->lpni_mintxcredits = lp->lpni_txcredits;
865
866                 if (lp->lpni_txcredits < 0) {
867                         msg->msg_tx_delayed = 1;
868                         list_add_tail(&msg->msg_list, &lp->lpni_txq);
869                         spin_unlock(&lp->lpni_lock);
870                         return LNET_CREDIT_WAIT;
871                 }
872                 spin_unlock(&lp->lpni_lock);
873         }
874
875         if (!msg->msg_txcredit) {
876                 LASSERT((tq->tq_credits < 0) ==
877                         !list_empty(&tq->tq_delayed));
878
879                 msg->msg_txcredit = 1;
880                 tq->tq_credits--;
881                 atomic_dec(&ni->ni_tx_credits);
882
883                 if (tq->tq_credits < tq->tq_credits_min)
884                         tq->tq_credits_min = tq->tq_credits;
885
886                 if (tq->tq_credits < 0) {
887                         msg->msg_tx_delayed = 1;
888                         list_add_tail(&msg->msg_list, &tq->tq_delayed);
889                         return LNET_CREDIT_WAIT;
890                 }
891         }
892
893         if (do_send) {
894                 lnet_net_unlock(cpt);
895                 lnet_ni_send(ni, msg);
896                 lnet_net_lock(cpt);
897         }
898         return LNET_CREDIT_OK;
899 }
900
901
902 static struct lnet_rtrbufpool *
903 lnet_msg2bufpool(struct lnet_msg *msg)
904 {
905         struct lnet_rtrbufpool  *rbp;
906         int                     cpt;
907
908         LASSERT(msg->msg_rx_committed);
909
910         cpt = msg->msg_rx_cpt;
911         rbp = &the_lnet.ln_rtrpools[cpt][0];
912
913         LASSERT(msg->msg_len <= LNET_MTU);
914         while (msg->msg_len > (unsigned int)rbp->rbp_npages * PAGE_SIZE) {
915                 rbp++;
916                 LASSERT(rbp < &the_lnet.ln_rtrpools[cpt][LNET_NRBPOOLS]);
917         }
918
919         return rbp;
920 }
921
922 static int
923 lnet_post_routed_recv_locked(struct lnet_msg *msg, int do_recv)
924 {
925         /* lnet_parse is going to lnet_net_unlock immediately after this, so it
926          * sets do_recv FALSE and I don't do the unlock/send/lock bit.
927          * I return LNET_CREDIT_WAIT if msg blocked and LNET_CREDIT_OK if
928          * received or OK to receive */
929         struct lnet_peer_ni *lp = msg->msg_rxpeer;
930         struct lnet_rtrbufpool *rbp;
931         struct lnet_rtrbuf *rb;
932
933         LASSERT (msg->msg_iov == NULL);
934         LASSERT (msg->msg_kiov == NULL);
935         LASSERT (msg->msg_niov == 0);
936         LASSERT (msg->msg_routing);
937         LASSERT (msg->msg_receiving);
938         LASSERT (!msg->msg_sending);
939
940         /* non-lnet_parse callers only receive delayed messages */
941         LASSERT(!do_recv || msg->msg_rx_delayed);
942
943         if (!msg->msg_peerrtrcredit) {
944                 spin_lock(&lp->lpni_lock);
945                 LASSERT((lp->lpni_rtrcredits < 0) ==
946                         !list_empty(&lp->lpni_rtrq));
947
948                 msg->msg_peerrtrcredit = 1;
949                 lp->lpni_rtrcredits--;
950                 if (lp->lpni_rtrcredits < lp->lpni_minrtrcredits)
951                         lp->lpni_minrtrcredits = lp->lpni_rtrcredits;
952
953                 if (lp->lpni_rtrcredits < 0) {
954                         /* must have checked eager_recv before here */
955                         LASSERT(msg->msg_rx_ready_delay);
956                         msg->msg_rx_delayed = 1;
957                         list_add_tail(&msg->msg_list, &lp->lpni_rtrq);
958                         spin_unlock(&lp->lpni_lock);
959                         return LNET_CREDIT_WAIT;
960                 }
961                 spin_unlock(&lp->lpni_lock);
962         }
963
964         rbp = lnet_msg2bufpool(msg);
965
966         if (!msg->msg_rtrcredit) {
967                 msg->msg_rtrcredit = 1;
968                 rbp->rbp_credits--;
969                 if (rbp->rbp_credits < rbp->rbp_mincredits)
970                         rbp->rbp_mincredits = rbp->rbp_credits;
971
972                 if (rbp->rbp_credits < 0) {
973                         /* must have checked eager_recv before here */
974                         LASSERT(msg->msg_rx_ready_delay);
975                         msg->msg_rx_delayed = 1;
976                         list_add_tail(&msg->msg_list, &rbp->rbp_msgs);
977                         return LNET_CREDIT_WAIT;
978                 }
979         }
980
981         LASSERT(!list_empty(&rbp->rbp_bufs));
982         rb = list_entry(rbp->rbp_bufs.next, struct lnet_rtrbuf, rb_list);
983         list_del(&rb->rb_list);
984
985         msg->msg_niov = rbp->rbp_npages;
986         msg->msg_kiov = &rb->rb_kiov[0];
987
988         if (do_recv) {
989                 int cpt = msg->msg_rx_cpt;
990
991                 lnet_net_unlock(cpt);
992                 lnet_ni_recv(msg->msg_rxni, msg->msg_private, msg, 1,
993                              0, msg->msg_len, msg->msg_len);
994                 lnet_net_lock(cpt);
995         }
996         return LNET_CREDIT_OK;
997 }
998
999 void
1000 lnet_return_tx_credits_locked(struct lnet_msg *msg)
1001 {
1002         struct lnet_peer_ni     *txpeer = msg->msg_txpeer;
1003         struct lnet_ni          *txni = msg->msg_txni;
1004         struct lnet_msg         *msg2;
1005
1006         if (msg->msg_txcredit) {
1007                 struct lnet_ni       *ni = msg->msg_txni;
1008                 struct lnet_tx_queue *tq = ni->ni_tx_queues[msg->msg_tx_cpt];
1009
1010                 /* give back NI txcredits */
1011                 msg->msg_txcredit = 0;
1012
1013                 LASSERT((tq->tq_credits < 0) ==
1014                         !list_empty(&tq->tq_delayed));
1015
1016                 tq->tq_credits++;
1017                 atomic_inc(&ni->ni_tx_credits);
1018                 if (tq->tq_credits <= 0) {
1019                         msg2 = list_entry(tq->tq_delayed.next,
1020                                           struct lnet_msg, msg_list);
1021                         list_del(&msg2->msg_list);
1022
1023                         LASSERT(msg2->msg_txni == ni);
1024                         LASSERT(msg2->msg_tx_delayed);
1025                         LASSERT(msg2->msg_tx_cpt == msg->msg_tx_cpt);
1026
1027                         (void) lnet_post_send_locked(msg2, 1);
1028                 }
1029         }
1030
1031         if (msg->msg_peertxcredit) {
1032                 /* give back peer txcredits */
1033                 msg->msg_peertxcredit = 0;
1034
1035                 spin_lock(&txpeer->lpni_lock);
1036                 LASSERT((txpeer->lpni_txcredits < 0) ==
1037                         !list_empty(&txpeer->lpni_txq));
1038
1039                 txpeer->lpni_txqnob -= msg->msg_len + sizeof(struct lnet_hdr);
1040                 LASSERT(txpeer->lpni_txqnob >= 0);
1041
1042                 txpeer->lpni_txcredits++;
1043                 if (txpeer->lpni_txcredits <= 0) {
1044                         int msg2_cpt;
1045
1046                         msg2 = list_entry(txpeer->lpni_txq.next,
1047                                               struct lnet_msg, msg_list);
1048                         list_del(&msg2->msg_list);
1049                         spin_unlock(&txpeer->lpni_lock);
1050
1051                         LASSERT(msg2->msg_txpeer == txpeer);
1052                         LASSERT(msg2->msg_tx_delayed);
1053
1054                         msg2_cpt = msg2->msg_tx_cpt;
1055
1056                         /*
1057                          * The msg_cpt can be different from the msg2_cpt
1058                          * so we need to make sure we lock the correct cpt
1059                          * for msg2.
1060                          * Once we call lnet_post_send_locked() it is no
1061                          * longer safe to access msg2, since it could've
1062                          * been freed by lnet_finalize(), but we still
1063                          * need to relock the correct cpt, so we cache the
1064                          * msg2_cpt for the purpose of the check that
1065                          * follows the call to lnet_pose_send_locked().
1066                          */
1067                         if (msg2_cpt != msg->msg_tx_cpt) {
1068                                 lnet_net_unlock(msg->msg_tx_cpt);
1069                                 lnet_net_lock(msg2_cpt);
1070                         }
1071                         (void) lnet_post_send_locked(msg2, 1);
1072                         if (msg2_cpt != msg->msg_tx_cpt) {
1073                                 lnet_net_unlock(msg2_cpt);
1074                                 lnet_net_lock(msg->msg_tx_cpt);
1075                         }
1076                 } else {
1077                         spin_unlock(&txpeer->lpni_lock);
1078                 }
1079         }
1080
1081         if (txni != NULL) {
1082                 msg->msg_txni = NULL;
1083                 lnet_ni_decref_locked(txni, msg->msg_tx_cpt);
1084         }
1085
1086         if (txpeer != NULL) {
1087                 /*
1088                  * TODO:
1089                  * Once the patch for the health comes in we need to set
1090                  * the health of the peer ni to bad when we fail to send
1091                  * a message.
1092                  * int status = msg->msg_ev.status;
1093                  * if (status != 0)
1094                  *      lnet_set_peer_ni_health_locked(txpeer, false)
1095                  */
1096                 msg->msg_txpeer = NULL;
1097                 lnet_peer_ni_decref_locked(txpeer);
1098         }
1099 }
1100
1101 void
1102 lnet_schedule_blocked_locked(struct lnet_rtrbufpool *rbp)
1103 {
1104         struct lnet_msg *msg;
1105
1106         if (list_empty(&rbp->rbp_msgs))
1107                 return;
1108         msg = list_entry(rbp->rbp_msgs.next,
1109                          struct lnet_msg, msg_list);
1110         list_del(&msg->msg_list);
1111
1112         (void)lnet_post_routed_recv_locked(msg, 1);
1113 }
1114
1115 void
1116 lnet_drop_routed_msgs_locked(struct list_head *list, int cpt)
1117 {
1118         struct lnet_msg *msg;
1119         struct lnet_msg *tmp;
1120
1121         lnet_net_unlock(cpt);
1122
1123         list_for_each_entry_safe(msg, tmp, list, msg_list) {
1124                 lnet_ni_recv(msg->msg_rxni, msg->msg_private, NULL,
1125                              0, 0, 0, msg->msg_hdr.payload_length);
1126                 list_del_init(&msg->msg_list);
1127                 lnet_finalize(msg, -ECANCELED);
1128         }
1129
1130         lnet_net_lock(cpt);
1131 }
1132
1133 void
1134 lnet_return_rx_credits_locked(struct lnet_msg *msg)
1135 {
1136         struct lnet_peer_ni *rxpeer = msg->msg_rxpeer;
1137         struct lnet_ni *rxni = msg->msg_rxni;
1138         struct lnet_msg *msg2;
1139
1140         if (msg->msg_rtrcredit) {
1141                 /* give back global router credits */
1142                 struct lnet_rtrbuf *rb;
1143                 struct lnet_rtrbufpool *rbp;
1144
1145                 /* NB If a msg ever blocks for a buffer in rbp_msgs, it stays
1146                  * there until it gets one allocated, or aborts the wait
1147                  * itself */
1148                 LASSERT(msg->msg_kiov != NULL);
1149
1150                 rb = list_entry(msg->msg_kiov, struct lnet_rtrbuf, rb_kiov[0]);
1151                 rbp = rb->rb_pool;
1152
1153                 msg->msg_kiov = NULL;
1154                 msg->msg_rtrcredit = 0;
1155
1156                 LASSERT(rbp == lnet_msg2bufpool(msg));
1157
1158                 LASSERT((rbp->rbp_credits > 0) ==
1159                         !list_empty(&rbp->rbp_bufs));
1160
1161                 /* If routing is now turned off, we just drop this buffer and
1162                  * don't bother trying to return credits.  */
1163                 if (!the_lnet.ln_routing) {
1164                         lnet_destroy_rtrbuf(rb, rbp->rbp_npages);
1165                         goto routing_off;
1166                 }
1167
1168                 /* It is possible that a user has lowered the desired number of
1169                  * buffers in this pool.  Make sure we never put back
1170                  * more buffers than the stated number. */
1171                 if (unlikely(rbp->rbp_credits >= rbp->rbp_req_nbuffers)) {
1172                         /* Discard this buffer so we don't have too
1173                          * many. */
1174                         lnet_destroy_rtrbuf(rb, rbp->rbp_npages);
1175                         rbp->rbp_nbuffers--;
1176                 } else {
1177                         list_add(&rb->rb_list, &rbp->rbp_bufs);
1178                         rbp->rbp_credits++;
1179                         if (rbp->rbp_credits <= 0)
1180                                 lnet_schedule_blocked_locked(rbp);
1181                 }
1182         }
1183
1184 routing_off:
1185         if (msg->msg_peerrtrcredit) {
1186                 /* give back peer router credits */
1187                 msg->msg_peerrtrcredit = 0;
1188
1189                 spin_lock(&rxpeer->lpni_lock);
1190                 LASSERT((rxpeer->lpni_rtrcredits < 0) ==
1191                         !list_empty(&rxpeer->lpni_rtrq));
1192
1193                 rxpeer->lpni_rtrcredits++;
1194
1195                 /* drop all messages which are queued to be routed on that
1196                  * peer. */
1197                 if (!the_lnet.ln_routing) {
1198                         struct list_head drop;
1199                         INIT_LIST_HEAD(&drop);
1200                         list_splice_init(&rxpeer->lpni_rtrq, &drop);
1201                         spin_unlock(&rxpeer->lpni_lock);
1202                         lnet_drop_routed_msgs_locked(&drop, msg->msg_rx_cpt);
1203                 } else if (rxpeer->lpni_rtrcredits <= 0) {
1204                         msg2 = list_entry(rxpeer->lpni_rtrq.next,
1205                                           struct lnet_msg, msg_list);
1206                         list_del(&msg2->msg_list);
1207                         spin_unlock(&rxpeer->lpni_lock);
1208                         (void) lnet_post_routed_recv_locked(msg2, 1);
1209                 } else {
1210                         spin_unlock(&rxpeer->lpni_lock);
1211                 }
1212         }
1213         if (rxni != NULL) {
1214                 msg->msg_rxni = NULL;
1215                 lnet_ni_decref_locked(rxni, msg->msg_rx_cpt);
1216         }
1217         if (rxpeer != NULL) {
1218                 msg->msg_rxpeer = NULL;
1219                 lnet_peer_ni_decref_locked(rxpeer);
1220         }
1221 }
1222
1223 static int
1224 lnet_compare_peers(struct lnet_peer_ni *p1, struct lnet_peer_ni *p2)
1225 {
1226         if (p1->lpni_txqnob < p2->lpni_txqnob)
1227                 return 1;
1228
1229         if (p1->lpni_txqnob > p2->lpni_txqnob)
1230                 return -1;
1231
1232         if (p1->lpni_txcredits > p2->lpni_txcredits)
1233                 return 1;
1234
1235         if (p1->lpni_txcredits < p2->lpni_txcredits)
1236                 return -1;
1237
1238         return 0;
1239 }
1240
1241 static int
1242 lnet_compare_routes(struct lnet_route *r1, struct lnet_route *r2)
1243 {
1244         struct lnet_peer_ni *p1 = r1->lr_gateway;
1245         struct lnet_peer_ni *p2 = r2->lr_gateway;
1246         int r1_hops = (r1->lr_hops == LNET_UNDEFINED_HOPS) ? 1 : r1->lr_hops;
1247         int r2_hops = (r2->lr_hops == LNET_UNDEFINED_HOPS) ? 1 : r2->lr_hops;
1248         int rc;
1249
1250         if (r1->lr_priority < r2->lr_priority)
1251                 return 1;
1252
1253         if (r1->lr_priority > r2->lr_priority)
1254                 return -1;
1255
1256         if (r1_hops < r2_hops)
1257                 return 1;
1258
1259         if (r1_hops > r2_hops)
1260                 return -1;
1261
1262         rc = lnet_compare_peers(p1, p2);
1263         if (rc)
1264                 return rc;
1265
1266         if (r1->lr_seq - r2->lr_seq <= 0)
1267                 return 1;
1268
1269         return -1;
1270 }
1271
1272 static struct lnet_peer_ni *
1273 lnet_find_route_locked(struct lnet_net *net, lnet_nid_t target,
1274                        lnet_nid_t rtr_nid)
1275 {
1276         struct lnet_remotenet   *rnet;
1277         struct lnet_route               *route;
1278         struct lnet_route               *best_route;
1279         struct lnet_route               *last_route;
1280         struct lnet_peer_ni     *lpni_best;
1281         struct lnet_peer_ni     *lp;
1282         int                     rc;
1283
1284         /* If @rtr_nid is not LNET_NID_ANY, return the gateway with
1285          * rtr_nid nid, otherwise find the best gateway I can use */
1286
1287         rnet = lnet_find_rnet_locked(LNET_NIDNET(target));
1288         if (rnet == NULL)
1289                 return NULL;
1290
1291         lpni_best = NULL;
1292         best_route = last_route = NULL;
1293         list_for_each_entry(route, &rnet->lrn_routes, lr_list) {
1294                 lp = route->lr_gateway;
1295
1296                 if (!lnet_is_route_alive(route))
1297                         continue;
1298
1299                 if (net != NULL && lp->lpni_net != net)
1300                         continue;
1301
1302                 if (lp->lpni_nid == rtr_nid) /* it's pre-determined router */
1303                         return lp;
1304
1305                 if (lpni_best == NULL) {
1306                         best_route = last_route = route;
1307                         lpni_best = lp;
1308                         continue;
1309                 }
1310
1311                 /* no protection on below fields, but it's harmless */
1312                 if (last_route->lr_seq - route->lr_seq < 0)
1313                         last_route = route;
1314
1315                 rc = lnet_compare_routes(route, best_route);
1316                 if (rc < 0)
1317                         continue;
1318
1319                 best_route = route;
1320                 lpni_best = lp;
1321         }
1322
1323         /* set sequence number on the best router to the latest sequence + 1
1324          * so we can round-robin all routers, it's race and inaccurate but
1325          * harmless and functional  */
1326         if (best_route != NULL)
1327                 best_route->lr_seq = last_route->lr_seq + 1;
1328         return lpni_best;
1329 }
1330
1331 static struct lnet_ni *
1332 lnet_get_best_ni(struct lnet_net *local_net, struct lnet_ni *cur_ni,
1333                  int md_cpt)
1334 {
1335         struct lnet_ni *ni = NULL, *best_ni = cur_ni;
1336         unsigned int shortest_distance;
1337         int best_credits;
1338
1339         if (best_ni == NULL) {
1340                 shortest_distance = UINT_MAX;
1341                 best_credits = INT_MIN;
1342         } else {
1343                 shortest_distance = cfs_cpt_distance(lnet_cpt_table(), md_cpt,
1344                                                      best_ni->ni_dev_cpt);
1345                 best_credits = atomic_read(&best_ni->ni_tx_credits);
1346         }
1347
1348         while ((ni = lnet_get_next_ni_locked(local_net, ni))) {
1349                 unsigned int distance;
1350                 int ni_credits;
1351
1352                 if (!lnet_is_ni_healthy_locked(ni))
1353                         continue;
1354
1355                 ni_credits = atomic_read(&ni->ni_tx_credits);
1356
1357                 /*
1358                  * calculate the distance from the CPT on which
1359                  * the message memory is allocated to the CPT of
1360                  * the NI's physical device
1361                  */
1362                 distance = cfs_cpt_distance(lnet_cpt_table(),
1363                                             md_cpt,
1364                                             ni->ni_dev_cpt);
1365
1366                 /*
1367                  * All distances smaller than the NUMA range
1368                  * are treated equally.
1369                  */
1370                 if (distance < lnet_numa_range)
1371                         distance = lnet_numa_range;
1372
1373                 /*
1374                  * Select on shorter distance, then available
1375                  * credits, then round-robin.
1376                  */
1377                 if (distance > shortest_distance) {
1378                         continue;
1379                 } else if (distance < shortest_distance) {
1380                         shortest_distance = distance;
1381                 } else if (ni_credits < best_credits) {
1382                         continue;
1383                 } else if (ni_credits == best_credits) {
1384                         if (best_ni && (best_ni)->ni_seq <= ni->ni_seq)
1385                                 continue;
1386                 }
1387                 best_ni = ni;
1388                 best_credits = ni_credits;
1389         }
1390
1391         return best_ni;
1392 }
1393
1394 /*
1395  * Traffic to the LNET_RESERVED_PORTAL may not trigger peer discovery,
1396  * because such traffic is required to perform discovery. We therefore
1397  * exclude all GET and PUT on that portal. We also exclude all ACK and
1398  * REPLY traffic, but that is because the portal is not tracked in the
1399  * message structure for these message types. We could restrict this
1400  * further by also checking for LNET_PROTO_PING_MATCHBITS.
1401  */
1402 static bool
1403 lnet_msg_discovery(struct lnet_msg *msg)
1404 {
1405         if (msg->msg_type == LNET_MSG_PUT) {
1406                 if (msg->msg_hdr.msg.put.ptl_index != LNET_RESERVED_PORTAL)
1407                         return true;
1408         } else if (msg->msg_type == LNET_MSG_GET) {
1409                 if (msg->msg_hdr.msg.get.ptl_index != LNET_RESERVED_PORTAL)
1410                         return true;
1411         }
1412         return false;
1413 }
1414
1415 static int
1416 lnet_select_pathway(lnet_nid_t src_nid, lnet_nid_t dst_nid,
1417                     struct lnet_msg *msg, lnet_nid_t rtr_nid)
1418 {
1419         struct lnet_ni          *best_ni;
1420         struct lnet_peer_ni     *best_lpni;
1421         struct lnet_peer_ni     *best_gw;
1422         struct lnet_peer_ni     *lpni;
1423         struct lnet_peer_ni     *final_dst;
1424         struct lnet_peer        *peer;
1425         struct lnet_peer_net    *peer_net;
1426         struct lnet_net         *local_net;
1427         int                     cpt, cpt2, rc;
1428         bool                    routing;
1429         bool                    routing2;
1430         bool                    ni_is_pref;
1431         bool                    preferred;
1432         bool                    local_found;
1433         int                     best_lpni_credits;
1434         int                     md_cpt;
1435
1436         /*
1437          * get an initial CPT to use for locking. The idea here is not to
1438          * serialize the calls to select_pathway, so that as many
1439          * operations can run concurrently as possible. To do that we use
1440          * the CPT where this call is being executed. Later on when we
1441          * determine the CPT to use in lnet_message_commit, we switch the
1442          * lock and check if there was any configuration change.  If none,
1443          * then we proceed, if there is, then we restart the operation.
1444          */
1445         cpt = lnet_net_lock_current();
1446
1447         md_cpt = lnet_cpt_of_md(msg->msg_md, msg->msg_offset);
1448         if (md_cpt == CFS_CPT_ANY)
1449                 md_cpt = cpt;
1450
1451 again:
1452         best_ni = NULL;
1453         best_lpni = NULL;
1454         best_gw = NULL;
1455         final_dst = NULL;
1456         local_net = NULL;
1457         routing = false;
1458         routing2 = false;
1459         local_found = false;
1460
1461         /*
1462          * lnet_nid2peerni_locked() is the path that will find an
1463          * existing peer_ni, or create one and mark it as having been
1464          * created due to network traffic.
1465          */
1466         lpni = lnet_nid2peerni_locked(dst_nid, LNET_NID_ANY, cpt);
1467         if (IS_ERR(lpni)) {
1468                 lnet_net_unlock(cpt);
1469                 return PTR_ERR(lpni);
1470         }
1471         /*
1472          * Now that we have a peer_ni, check if we want to discover
1473          * the peer. Traffic to the LNET_RESERVED_PORTAL should not
1474          * trigger discovery.
1475          */
1476         peer = lpni->lpni_peer_net->lpn_peer;
1477         if (lnet_msg_discovery(msg) && !lnet_peer_is_uptodate(peer)) {
1478                 rc = lnet_discover_peer_locked(lpni, cpt, false);
1479                 if (rc) {
1480                         lnet_peer_ni_decref_locked(lpni);
1481                         lnet_net_unlock(cpt);
1482                         return rc;
1483                 }
1484                 /* The peer may have changed. */
1485                 peer = lpni->lpni_peer_net->lpn_peer;
1486                 /* queue message and return */
1487                 msg->msg_src_nid_param = src_nid;
1488                 msg->msg_rtr_nid_param = rtr_nid;
1489                 msg->msg_sending = 0;
1490                 list_add_tail(&msg->msg_list, &peer->lp_dc_pendq);
1491                 lnet_peer_ni_decref_locked(lpni);
1492                 lnet_net_unlock(cpt);
1493
1494                 CDEBUG(D_NET, "%s pending discovery\n",
1495                        libcfs_nid2str(peer->lp_primary_nid));
1496
1497                 return LNET_DC_WAIT;
1498         }
1499         lnet_peer_ni_decref_locked(lpni);
1500
1501         /* If peer is not healthy then can not send anything to it */
1502         if (!lnet_is_peer_healthy_locked(peer)) {
1503                 lnet_net_unlock(cpt);
1504                 return -EHOSTUNREACH;
1505         }
1506
1507         /*
1508          * STEP 1: first jab at determining best_ni
1509          * if src_nid is explicitly specified, then best_ni is already
1510          * pre-determiend for us. Otherwise we need to select the best
1511          * one to use later on
1512          */
1513         if (src_nid != LNET_NID_ANY) {
1514                 best_ni = lnet_nid2ni_locked(src_nid, cpt);
1515                 if (!best_ni) {
1516                         lnet_net_unlock(cpt);
1517                         LCONSOLE_WARN("Can't send to %s: src %s is not a "
1518                                       "local nid\n", libcfs_nid2str(dst_nid),
1519                                       libcfs_nid2str(src_nid));
1520                         return -EINVAL;
1521                 }
1522         }
1523
1524         if (msg->msg_type == LNET_MSG_REPLY ||
1525             msg->msg_type == LNET_MSG_ACK ||
1526             !lnet_peer_is_multi_rail(peer) ||
1527             best_ni) {
1528                 /*
1529                  * for replies we want to respond on the same peer_ni we
1530                  * received the message on if possible. If not, then pick
1531                  * a peer_ni to send to
1532                  *
1533                  * if the peer is non-multi-rail then you want to send to
1534                  * the dst_nid provided as well.
1535                  *
1536                  * If the best_ni has already been determined, IE the
1537                  * src_nid has been specified, then use the
1538                  * destination_nid provided as well, since we're
1539                  * continuing a series of related messages for the same
1540                  * RPC.
1541                  *
1542                  * It is expected to find the lpni using dst_nid, since we
1543                  * created it earlier.
1544                  */
1545                 best_lpni = lnet_find_peer_ni_locked(dst_nid);
1546                 if (best_lpni)
1547                         lnet_peer_ni_decref_locked(best_lpni);
1548
1549                 if (best_lpni && !lnet_get_net_locked(LNET_NIDNET(dst_nid))) {
1550                         /*
1551                          * this lpni is not on a local network so we need
1552                          * to route this reply.
1553                          */
1554                         best_gw = lnet_find_route_locked(NULL,
1555                                                          best_lpni->lpni_nid,
1556                                                          rtr_nid);
1557                         if (best_gw) {
1558                                 /*
1559                                 * RULE: Each node considers only the next-hop
1560                                 *
1561                                 * We're going to route the message, so change the peer to
1562                                 * the router.
1563                                 */
1564                                 LASSERT(best_gw->lpni_peer_net);
1565                                 LASSERT(best_gw->lpni_peer_net->lpn_peer);
1566                                 peer = best_gw->lpni_peer_net->lpn_peer;
1567
1568                                 /*
1569                                 * if the router is not multi-rail then use the best_gw
1570                                 * found to send the message to
1571                                 */
1572                                 if (!lnet_peer_is_multi_rail(peer))
1573                                         best_lpni = best_gw;
1574                                 else
1575                                         best_lpni = NULL;
1576
1577                                 routing = true;
1578                         } else {
1579                                 best_lpni = NULL;
1580                         }
1581                 } else if (!best_lpni) {
1582                         lnet_net_unlock(cpt);
1583                         CERROR("unable to send msg_type %d to "
1584                               "originating %s. Destination NID not in DB\n",
1585                               msg->msg_type, libcfs_nid2str(dst_nid));
1586                         return -EINVAL;
1587                 }
1588         }
1589
1590         /*
1591          * We must use a consistent source address when sending to a
1592          * non-MR peer. However, a non-MR peer can have multiple NIDs
1593          * on multiple networks, and we may even need to talk to this
1594          * peer on multiple networks -- certain types of
1595          * load-balancing configuration do this.
1596          *
1597          * So we need to pick the NI the peer prefers for this
1598          * particular network.
1599          */
1600         if (!lnet_peer_is_multi_rail(peer)) {
1601                 if (!best_lpni) {
1602                         lnet_net_unlock(cpt);
1603                         CERROR("no route to %s\n",
1604                                libcfs_nid2str(dst_nid));
1605                         return -EHOSTUNREACH;
1606                 }
1607
1608                 /* best ni is already set if src_nid was provided */
1609                 if (!best_ni) {
1610                         /* Get the target peer_ni */
1611                         peer_net = lnet_peer_get_net_locked(peer,
1612                                         LNET_NIDNET(best_lpni->lpni_nid));
1613                         LASSERT(peer_net != NULL);
1614                         list_for_each_entry(lpni, &peer_net->lpn_peer_nis,
1615                                             lpni_peer_nis) {
1616                                 if (lpni->lpni_pref_nnids == 0)
1617                                         continue;
1618                                 LASSERT(lpni->lpni_pref_nnids == 1);
1619                                 best_ni = lnet_nid2ni_locked(
1620                                                 lpni->lpni_pref.nid, cpt);
1621                                 break;
1622                         }
1623                 }
1624                 /* if best_ni is still not set just pick one */
1625                 if (!best_ni) {
1626                         best_ni = lnet_net2ni_locked(
1627                                 best_lpni->lpni_net->net_id, cpt);
1628                         /* If there is no best_ni we don't have a route */
1629                         if (!best_ni) {
1630                                 lnet_net_unlock(cpt);
1631                                 CERROR("no path to %s from net %s\n",
1632                                         libcfs_nid2str(best_lpni->lpni_nid),
1633                                         libcfs_net2str(best_lpni->lpni_net->net_id));
1634                                 return -EHOSTUNREACH;
1635                         }
1636                         lpni = list_entry(peer_net->lpn_peer_nis.next,
1637                                         struct lnet_peer_ni,
1638                                         lpni_peer_nis);
1639                 }
1640                 /* Set preferred NI if necessary. */
1641                 if (lpni->lpni_pref_nnids == 0)
1642                         lnet_peer_ni_set_non_mr_pref_nid(lpni, best_ni->ni_nid);
1643         }
1644
1645         /*
1646          * if we already found a best_ni because src_nid is specified and
1647          * best_lpni because we are replying to a message then just send
1648          * the message
1649          */
1650         if (best_ni && best_lpni)
1651                 goto send;
1652
1653         /*
1654          * If we already found a best_ni because src_nid is specified then
1655          * pick the peer then send the message
1656          */
1657         if (best_ni)
1658                 goto pick_peer;
1659
1660         /*
1661          * pick the best_ni by going through all the possible networks of
1662          * that peer and see which local NI is best suited to talk to that
1663          * peer.
1664          *
1665          * Locally connected networks will always be preferred over
1666          * a routed network. If there are only routed paths to the peer,
1667          * then the best route is chosen. If all routes are equal then
1668          * they are used in round robin.
1669          */
1670         list_for_each_entry(peer_net, &peer->lp_peer_nets, lpn_peer_nets) {
1671                 if (!lnet_is_peer_net_healthy_locked(peer_net))
1672                         continue;
1673
1674                 local_net = lnet_get_net_locked(peer_net->lpn_net_id);
1675                 if (!local_net && !routing && !local_found) {
1676                         struct lnet_peer_ni *net_gw;
1677
1678                         lpni = list_entry(peer_net->lpn_peer_nis.next,
1679                                           struct lnet_peer_ni,
1680                                           lpni_peer_nis);
1681
1682                         net_gw = lnet_find_route_locked(NULL,
1683                                                         lpni->lpni_nid,
1684                                                         rtr_nid);
1685                         if (!net_gw)
1686                                 continue;
1687
1688                         if (best_gw) {
1689                                 /*
1690                                  * lnet_find_route_locked() call
1691                                  * will return the best_Gw on the
1692                                  * lpni->lpni_nid network.
1693                                  * However, best_gw and net_gw can
1694                                  * be on different networks.
1695                                  * Therefore need to compare them
1696                                  * to pick the better of either.
1697                                  */
1698                                 if (lnet_compare_peers(best_gw, net_gw) > 0)
1699                                         continue;
1700                                 if (best_gw->lpni_gw_seq <= net_gw->lpni_gw_seq)
1701                                         continue;
1702                         }
1703                         best_gw = net_gw;
1704                         final_dst = lpni;
1705
1706                         routing2 = true;
1707                 } else {
1708                         best_gw = NULL;
1709                         final_dst = NULL;
1710                         routing2 = false;
1711                         local_found = true;
1712                 }
1713
1714                 /*
1715                  * a gw on this network is found, but there could be
1716                  * other better gateways on other networks. So don't pick
1717                  * the best_ni until we determine the best_gw.
1718                  */
1719                 if (best_gw)
1720                         continue;
1721
1722                 /* if no local_net found continue */
1723                 if (!local_net)
1724                         continue;
1725
1726                 /*
1727                  * Iterate through the NIs in this local Net and select
1728                  * the NI to send from. The selection is determined by
1729                  * these 3 criterion in the following priority:
1730                  *      1. NUMA
1731                  *      2. NI available credits
1732                  *      3. Round Robin
1733                  */
1734                 best_ni = lnet_get_best_ni(local_net, best_ni, md_cpt);
1735         }
1736
1737         if (!best_ni && !best_gw) {
1738                 lnet_net_unlock(cpt);
1739                 LCONSOLE_WARN("No local ni found to send from to %s\n",
1740                         libcfs_nid2str(dst_nid));
1741                 return -EINVAL;
1742         }
1743
1744         if (!best_ni) {
1745                 best_ni = lnet_get_best_ni(best_gw->lpni_net, best_ni, md_cpt);
1746                 LASSERT(best_gw && best_ni);
1747
1748                 /*
1749                  * We're going to route the message, so change the peer to
1750                  * the router.
1751                  */
1752                 LASSERT(best_gw->lpni_peer_net);
1753                 LASSERT(best_gw->lpni_peer_net->lpn_peer);
1754                 best_gw->lpni_gw_seq++;
1755                 peer = best_gw->lpni_peer_net->lpn_peer;
1756         }
1757
1758         /*
1759          * Now that we selected the NI to use increment its sequence
1760          * number so the Round Robin algorithm will detect that it has
1761          * been used and pick the next NI.
1762          */
1763         best_ni->ni_seq++;
1764
1765 pick_peer:
1766         /*
1767          * At this point the best_ni is on a local network on which
1768          * the peer has a peer_ni as well
1769          */
1770         peer_net = lnet_peer_get_net_locked(peer,
1771                                             best_ni->ni_net->net_id);
1772         /*
1773          * peer_net is not available or the src_nid is explicitly defined
1774          * and the peer_net for that src_nid is unhealthy. find a route to
1775          * the destination nid.
1776          */
1777         if (!peer_net ||
1778             (src_nid != LNET_NID_ANY &&
1779              !lnet_is_peer_net_healthy_locked(peer_net))) {
1780                 best_gw = lnet_find_route_locked(best_ni->ni_net,
1781                                                  dst_nid,
1782                                                  rtr_nid);
1783                 /*
1784                  * if no route is found for that network then
1785                  * move onto the next peer_ni in the peer
1786                  */
1787                 if (!best_gw) {
1788                         lnet_net_unlock(cpt);
1789                         LCONSOLE_WARN("No route to peer from %s\n",
1790                                 libcfs_nid2str(best_ni->ni_nid));
1791                         return -EHOSTUNREACH;
1792                 }
1793
1794                 CDEBUG(D_NET, "Best route to %s via %s for %s %d\n",
1795                         libcfs_nid2str(dst_nid),
1796                         libcfs_nid2str(best_gw->lpni_nid),
1797                         lnet_msgtyp2str(msg->msg_type), msg->msg_len);
1798
1799                 routing2 = true;
1800                 /*
1801                  * RULE: Each node considers only the next-hop
1802                  *
1803                  * We're going to route the message, so change the peer to
1804                  * the router.
1805                  */
1806                 LASSERT(best_gw->lpni_peer_net);
1807                 LASSERT(best_gw->lpni_peer_net->lpn_peer);
1808                 peer = best_gw->lpni_peer_net->lpn_peer;
1809         } else if (!lnet_is_peer_net_healthy_locked(peer_net)) {
1810                 /*
1811                  * this peer_net is unhealthy but we still have an opportunity
1812                  * to find another peer_net that we can use
1813                  */
1814                 __u32 net_id = peer_net->lpn_net_id;
1815                 LCONSOLE_WARN("peer net %s unhealthy\n",
1816                               libcfs_net2str(net_id));
1817                 goto again;
1818         }
1819
1820         /*
1821          * Look at the peer NIs for the destination peer that connect
1822          * to the chosen net. If a peer_ni is preferred when using the
1823          * best_ni to communicate, we use that one. If there is no
1824          * preferred peer_ni, or there are multiple preferred peer_ni,
1825          * the available transmit credits are used. If the transmit
1826          * credits are equal, we round-robin over the peer_ni.
1827          */
1828         lpni = NULL;
1829         best_lpni_credits = INT_MIN;
1830         preferred = false;
1831         best_lpni = NULL;
1832         while ((lpni = lnet_get_next_peer_ni_locked(peer, peer_net, lpni))) {
1833                 /*
1834                  * if this peer ni is not healthy just skip it, no point in
1835                  * examining it further
1836                  */
1837                 if (!lnet_is_peer_ni_healthy_locked(lpni))
1838                         continue;
1839                 ni_is_pref = lnet_peer_is_pref_nid_locked(lpni,
1840                                                           best_ni->ni_nid);
1841
1842                 /* if this is a preferred peer use it */
1843                 if (!preferred && ni_is_pref) {
1844                         preferred = true;
1845                 } else if (preferred && !ni_is_pref) {
1846                         /*
1847                          * this is not the preferred peer so let's ignore
1848                          * it.
1849                          */
1850                         continue;
1851                 } else if (lpni->lpni_txcredits < best_lpni_credits) {
1852                         /*
1853                          * We already have a peer that has more credits
1854                          * available than this one. No need to consider
1855                          * this peer further.
1856                          */
1857                         continue;
1858                 } else if (lpni->lpni_txcredits == best_lpni_credits) {
1859                         /*
1860                          * The best peer found so far and the current peer
1861                          * have the same number of available credits let's
1862                          * make sure to select between them using Round
1863                          * Robin
1864                          */
1865                         if (best_lpni) {
1866                                 if (best_lpni->lpni_seq <= lpni->lpni_seq)
1867                                         continue;
1868                         }
1869                 }
1870
1871                 best_lpni = lpni;
1872                 best_lpni_credits = lpni->lpni_txcredits;
1873         }
1874
1875         /* if we still can't find a peer ni then we can't reach it */
1876         if (!best_lpni) {
1877                 __u32 net_id = (peer_net) ? peer_net->lpn_net_id :
1878                         LNET_NIDNET(dst_nid);
1879                 lnet_net_unlock(cpt);
1880                 LCONSOLE_WARN("no peer_ni found on peer net %s\n",
1881                                 libcfs_net2str(net_id));
1882                 return -EHOSTUNREACH;
1883         }
1884
1885
1886 send:
1887         /* Shortcut for loopback. */
1888         if (best_ni == the_lnet.ln_loni) {
1889                 /* No send credit hassles with LOLND */
1890                 lnet_ni_addref_locked(best_ni, cpt);
1891                 msg->msg_hdr.dest_nid = cpu_to_le64(best_ni->ni_nid);
1892                 if (!msg->msg_routing)
1893                         msg->msg_hdr.src_nid = cpu_to_le64(best_ni->ni_nid);
1894                 msg->msg_target.nid = best_ni->ni_nid;
1895                 lnet_msg_commit(msg, cpt);
1896                 msg->msg_txni = best_ni;
1897                 lnet_net_unlock(cpt);
1898
1899                 return LNET_CREDIT_OK;
1900         }
1901
1902         routing = routing || routing2;
1903
1904         /*
1905          * Increment sequence number of the peer selected so that we
1906          * pick the next one in Round Robin.
1907          */
1908         best_lpni->lpni_seq++;
1909
1910         /*
1911          * grab a reference on the peer_ni so it sticks around even if
1912          * we need to drop and relock the lnet_net_lock below.
1913          */
1914         lnet_peer_ni_addref_locked(best_lpni);
1915
1916         /*
1917          * Use lnet_cpt_of_nid() to determine the CPT used to commit the
1918          * message. This ensures that we get a CPT that is correct for
1919          * the NI when the NI has been restricted to a subset of all CPTs.
1920          * If the selected CPT differs from the one currently locked, we
1921          * must unlock and relock the lnet_net_lock(), and then check whether
1922          * the configuration has changed. We don't have a hold on the best_ni
1923          * yet, and it may have vanished.
1924          */
1925         cpt2 = lnet_cpt_of_nid_locked(best_lpni->lpni_nid, best_ni);
1926         if (cpt != cpt2) {
1927                 __u32 seq = lnet_get_dlc_seq_locked();
1928                 lnet_net_unlock(cpt);
1929                 cpt = cpt2;
1930                 lnet_net_lock(cpt);
1931                 if (seq != lnet_get_dlc_seq_locked()) {
1932                         lnet_peer_ni_decref_locked(best_lpni);
1933                         goto again;
1934                 }
1935         }
1936
1937         /*
1938          * store the best_lpni in the message right away to avoid having
1939          * to do the same operation under different conditions
1940          */
1941         msg->msg_txpeer = best_lpni;
1942         msg->msg_txni = best_ni;
1943
1944         /*
1945          * grab a reference for the best_ni since now it's in use in this
1946          * send. the reference will need to be dropped when the message is
1947          * finished in lnet_finalize()
1948          */
1949         lnet_ni_addref_locked(msg->msg_txni, cpt);
1950
1951         /*
1952          * Always set the target.nid to the best peer picked. Either the
1953          * nid will be one of the preconfigured NIDs, or the same NID as
1954          * what was originally set in the target or it will be the NID of
1955          * a router if this message should be routed
1956          */
1957         msg->msg_target.nid = msg->msg_txpeer->lpni_nid;
1958
1959         /*
1960          * lnet_msg_commit assigns the correct cpt to the message, which
1961          * is used to decrement the correct refcount on the ni when it's
1962          * time to return the credits
1963          */
1964         lnet_msg_commit(msg, cpt);
1965
1966         /*
1967          * If we are routing the message then we don't need to overwrite
1968          * the src_nid since it would've been set at the origin. Otherwise
1969          * we are the originator so we need to set it.
1970          */
1971         if (!msg->msg_routing)
1972                 msg->msg_hdr.src_nid = cpu_to_le64(msg->msg_txni->ni_nid);
1973
1974         if (routing) {
1975                 msg->msg_target_is_router = 1;
1976                 msg->msg_target.pid = LNET_PID_LUSTRE;
1977                 /*
1978                  * since we're routing we want to ensure that the
1979                  * msg_hdr.dest_nid is set to the final destination. When
1980                  * the router receives this message it knows how to route
1981                  * it.
1982                  */
1983                 msg->msg_hdr.dest_nid =
1984                         cpu_to_le64(final_dst ? final_dst->lpni_nid : dst_nid);
1985         } else {
1986                 /*
1987                  * if we're not routing set the dest_nid to the best peer
1988                  * ni that we picked earlier in the algorithm.
1989                  */
1990                 msg->msg_hdr.dest_nid = cpu_to_le64(msg->msg_txpeer->lpni_nid);
1991         }
1992
1993         rc = lnet_post_send_locked(msg, 0);
1994
1995         if (!rc)
1996                 CDEBUG(D_NET, "TRACE: %s(%s:%s) -> %s(%s:%s) : %s\n",
1997                        libcfs_nid2str(msg->msg_hdr.src_nid),
1998                        libcfs_nid2str(msg->msg_txni->ni_nid),
1999                        libcfs_nid2str(src_nid),
2000                        libcfs_nid2str(msg->msg_hdr.dest_nid),
2001                        libcfs_nid2str(dst_nid),
2002                        libcfs_nid2str(msg->msg_txpeer->lpni_nid),
2003                        lnet_msgtyp2str(msg->msg_type));
2004
2005         lnet_net_unlock(cpt);
2006
2007         return rc;
2008 }
2009
2010 int
2011 lnet_send(lnet_nid_t src_nid, struct lnet_msg *msg, lnet_nid_t rtr_nid)
2012 {
2013         lnet_nid_t              dst_nid = msg->msg_target.nid;
2014         int                     rc;
2015
2016         /*
2017          * NB: rtr_nid is set to LNET_NID_ANY for all current use-cases,
2018          * but we might want to use pre-determined router for ACK/REPLY
2019          * in the future
2020          */
2021         /* NB: ni != NULL == interface pre-determined (ACK/REPLY) */
2022         LASSERT (msg->msg_txpeer == NULL);
2023         LASSERT (!msg->msg_sending);
2024         LASSERT (!msg->msg_target_is_router);
2025         LASSERT (!msg->msg_receiving);
2026
2027         msg->msg_sending = 1;
2028
2029         LASSERT(!msg->msg_tx_committed);
2030
2031         rc = lnet_select_pathway(src_nid, dst_nid, msg, rtr_nid);
2032         if (rc < 0)
2033                 return rc;
2034
2035         if (rc == LNET_CREDIT_OK)
2036                 lnet_ni_send(msg->msg_txni, msg);
2037
2038         /* rc == LNET_CREDIT_OK or LNET_CREDIT_WAIT or LNET_DC_WAIT */
2039         return 0;
2040 }
2041
2042 void
2043 lnet_drop_message(struct lnet_ni *ni, int cpt, void *private, unsigned int nob)
2044 {
2045         lnet_net_lock(cpt);
2046         the_lnet.ln_counters[cpt]->drop_count++;
2047         the_lnet.ln_counters[cpt]->drop_length += nob;
2048         lnet_net_unlock(cpt);
2049
2050         lnet_ni_recv(ni, private, NULL, 0, 0, 0, nob);
2051 }
2052
2053 static void
2054 lnet_recv_put(struct lnet_ni *ni, struct lnet_msg *msg)
2055 {
2056         struct lnet_hdr *hdr = &msg->msg_hdr;
2057
2058         if (msg->msg_wanted != 0)
2059                 lnet_setpayloadbuffer(msg);
2060
2061         lnet_build_msg_event(msg, LNET_EVENT_PUT);
2062
2063         /* Must I ACK?  If so I'll grab the ack_wmd out of the header and put
2064          * it back into the ACK during lnet_finalize() */
2065         msg->msg_ack = (!lnet_is_wire_handle_none(&hdr->msg.put.ack_wmd) &&
2066                         (msg->msg_md->md_options & LNET_MD_ACK_DISABLE) == 0);
2067
2068         lnet_ni_recv(ni, msg->msg_private, msg, msg->msg_rx_delayed,
2069                      msg->msg_offset, msg->msg_wanted, hdr->payload_length);
2070 }
2071
2072 static int
2073 lnet_parse_put(struct lnet_ni *ni, struct lnet_msg *msg)
2074 {
2075         struct lnet_hdr         *hdr = &msg->msg_hdr;
2076         struct lnet_match_info  info;
2077         int                     rc;
2078         bool                    ready_delay;
2079
2080         /* Convert put fields to host byte order */
2081         hdr->msg.put.match_bits = le64_to_cpu(hdr->msg.put.match_bits);
2082         hdr->msg.put.ptl_index  = le32_to_cpu(hdr->msg.put.ptl_index);
2083         hdr->msg.put.offset     = le32_to_cpu(hdr->msg.put.offset);
2084
2085         /* Primary peer NID. */
2086         info.mi_id.nid  = msg->msg_initiator;
2087         info.mi_id.pid  = hdr->src_pid;
2088         info.mi_opc     = LNET_MD_OP_PUT;
2089         info.mi_portal  = hdr->msg.put.ptl_index;
2090         info.mi_rlength = hdr->payload_length;
2091         info.mi_roffset = hdr->msg.put.offset;
2092         info.mi_mbits   = hdr->msg.put.match_bits;
2093         info.mi_cpt     = lnet_cpt_of_nid(msg->msg_rxpeer->lpni_nid, ni);
2094
2095         msg->msg_rx_ready_delay = ni->ni_net->net_lnd->lnd_eager_recv == NULL;
2096         ready_delay = msg->msg_rx_ready_delay;
2097
2098  again:
2099         rc = lnet_ptl_match_md(&info, msg);
2100         switch (rc) {
2101         default:
2102                 LBUG();
2103
2104         case LNET_MATCHMD_OK:
2105                 lnet_recv_put(ni, msg);
2106                 return 0;
2107
2108         case LNET_MATCHMD_NONE:
2109                 if (ready_delay)
2110                         /* no eager_recv or has already called it, should
2111                          * have been attached on delayed list */
2112                         return 0;
2113
2114                 rc = lnet_ni_eager_recv(ni, msg);
2115                 if (rc == 0) {
2116                         ready_delay = true;
2117                         goto again;
2118                 }
2119                 /* fall through */
2120
2121         case LNET_MATCHMD_DROP:
2122                 CNETERR("Dropping PUT from %s portal %d match %llu"
2123                         " offset %d length %d: %d\n",
2124                         libcfs_id2str(info.mi_id), info.mi_portal,
2125                         info.mi_mbits, info.mi_roffset, info.mi_rlength, rc);
2126
2127                 return -ENOENT; /* -ve: OK but no match */
2128         }
2129 }
2130
2131 static int
2132 lnet_parse_get(struct lnet_ni *ni, struct lnet_msg *msg, int rdma_get)
2133 {
2134         struct lnet_match_info info;
2135         struct lnet_hdr *hdr = &msg->msg_hdr;
2136         struct lnet_process_id source_id;
2137         struct lnet_handle_wire reply_wmd;
2138         int rc;
2139
2140         /* Convert get fields to host byte order */
2141         hdr->msg.get.match_bits   = le64_to_cpu(hdr->msg.get.match_bits);
2142         hdr->msg.get.ptl_index    = le32_to_cpu(hdr->msg.get.ptl_index);
2143         hdr->msg.get.sink_length  = le32_to_cpu(hdr->msg.get.sink_length);
2144         hdr->msg.get.src_offset   = le32_to_cpu(hdr->msg.get.src_offset);
2145
2146         source_id.nid = hdr->src_nid;
2147         source_id.pid = hdr->src_pid;
2148         /* Primary peer NID */
2149         info.mi_id.nid  = msg->msg_initiator;
2150         info.mi_id.pid  = hdr->src_pid;
2151         info.mi_opc     = LNET_MD_OP_GET;
2152         info.mi_portal  = hdr->msg.get.ptl_index;
2153         info.mi_rlength = hdr->msg.get.sink_length;
2154         info.mi_roffset = hdr->msg.get.src_offset;
2155         info.mi_mbits   = hdr->msg.get.match_bits;
2156         info.mi_cpt     = lnet_cpt_of_nid(msg->msg_rxpeer->lpni_nid, ni);
2157
2158         rc = lnet_ptl_match_md(&info, msg);
2159         if (rc == LNET_MATCHMD_DROP) {
2160                 CNETERR("Dropping GET from %s portal %d match %llu"
2161                         " offset %d length %d\n",
2162                         libcfs_id2str(info.mi_id), info.mi_portal,
2163                         info.mi_mbits, info.mi_roffset, info.mi_rlength);
2164                 return -ENOENT; /* -ve: OK but no match */
2165         }
2166
2167         LASSERT(rc == LNET_MATCHMD_OK);
2168
2169         lnet_build_msg_event(msg, LNET_EVENT_GET);
2170
2171         reply_wmd = hdr->msg.get.return_wmd;
2172
2173         lnet_prep_send(msg, LNET_MSG_REPLY, source_id,
2174                        msg->msg_offset, msg->msg_wanted);
2175
2176         msg->msg_hdr.msg.reply.dst_wmd = reply_wmd;
2177
2178         if (rdma_get) {
2179                 /* The LND completes the REPLY from her recv procedure */
2180                 lnet_ni_recv(ni, msg->msg_private, msg, 0,
2181                              msg->msg_offset, msg->msg_len, msg->msg_len);
2182                 return 0;
2183         }
2184
2185         lnet_ni_recv(ni, msg->msg_private, NULL, 0, 0, 0, 0);
2186         msg->msg_receiving = 0;
2187
2188         rc = lnet_send(ni->ni_nid, msg, LNET_NID_ANY);
2189         if (rc < 0) {
2190                 /* didn't get as far as lnet_ni_send() */
2191                 CERROR("%s: Unable to send REPLY for GET from %s: %d\n",
2192                        libcfs_nid2str(ni->ni_nid),
2193                        libcfs_id2str(info.mi_id), rc);
2194
2195                 lnet_finalize(msg, rc);
2196         }
2197
2198         return 0;
2199 }
2200
2201 static int
2202 lnet_parse_reply(struct lnet_ni *ni, struct lnet_msg *msg)
2203 {
2204         void             *private = msg->msg_private;
2205         struct lnet_hdr  *hdr = &msg->msg_hdr;
2206         struct lnet_process_id src = {0};
2207         struct lnet_libmd        *md;
2208         int               rlength;
2209         int               mlength;
2210         int                     cpt;
2211
2212         cpt = lnet_cpt_of_cookie(hdr->msg.reply.dst_wmd.wh_object_cookie);
2213         lnet_res_lock(cpt);
2214
2215         src.nid = hdr->src_nid;
2216         src.pid = hdr->src_pid;
2217
2218         /* NB handles only looked up by creator (no flips) */
2219         md = lnet_wire_handle2md(&hdr->msg.reply.dst_wmd);
2220         if (md == NULL || md->md_threshold == 0 || md->md_me != NULL) {
2221                 CNETERR("%s: Dropping REPLY from %s for %s "
2222                         "MD %#llx.%#llx\n",
2223                         libcfs_nid2str(ni->ni_nid), libcfs_id2str(src),
2224                         (md == NULL) ? "invalid" : "inactive",
2225                         hdr->msg.reply.dst_wmd.wh_interface_cookie,
2226                         hdr->msg.reply.dst_wmd.wh_object_cookie);
2227                 if (md != NULL && md->md_me != NULL)
2228                         CERROR("REPLY MD also attached to portal %d\n",
2229                                md->md_me->me_portal);
2230
2231                 lnet_res_unlock(cpt);
2232                 return -ENOENT; /* -ve: OK but no match */
2233         }
2234
2235         LASSERT(md->md_offset == 0);
2236
2237         rlength = hdr->payload_length;
2238         mlength = MIN(rlength, (int)md->md_length);
2239
2240         if (mlength < rlength &&
2241             (md->md_options & LNET_MD_TRUNCATE) == 0) {
2242                 CNETERR("%s: Dropping REPLY from %s length %d "
2243                         "for MD %#llx would overflow (%d)\n",
2244                         libcfs_nid2str(ni->ni_nid), libcfs_id2str(src),
2245                         rlength, hdr->msg.reply.dst_wmd.wh_object_cookie,
2246                         mlength);
2247                 lnet_res_unlock(cpt);
2248                 return -ENOENT; /* -ve: OK but no match */
2249         }
2250
2251         CDEBUG(D_NET, "%s: Reply from %s of length %d/%d into md %#llx\n",
2252                libcfs_nid2str(ni->ni_nid), libcfs_id2str(src),
2253                mlength, rlength, hdr->msg.reply.dst_wmd.wh_object_cookie);
2254
2255         lnet_msg_attach_md(msg, md, 0, mlength);
2256
2257         if (mlength != 0)
2258                 lnet_setpayloadbuffer(msg);
2259
2260         lnet_res_unlock(cpt);
2261
2262         lnet_build_msg_event(msg, LNET_EVENT_REPLY);
2263
2264         lnet_ni_recv(ni, private, msg, 0, 0, mlength, rlength);
2265         return 0;
2266 }
2267
2268 static int
2269 lnet_parse_ack(struct lnet_ni *ni, struct lnet_msg *msg)
2270 {
2271         struct lnet_hdr  *hdr = &msg->msg_hdr;
2272         struct lnet_process_id src = {0};
2273         struct lnet_libmd        *md;
2274         int                     cpt;
2275
2276         src.nid = hdr->src_nid;
2277         src.pid = hdr->src_pid;
2278
2279         /* Convert ack fields to host byte order */
2280         hdr->msg.ack.match_bits = le64_to_cpu(hdr->msg.ack.match_bits);
2281         hdr->msg.ack.mlength = le32_to_cpu(hdr->msg.ack.mlength);
2282
2283         cpt = lnet_cpt_of_cookie(hdr->msg.ack.dst_wmd.wh_object_cookie);
2284         lnet_res_lock(cpt);
2285
2286         /* NB handles only looked up by creator (no flips) */
2287         md = lnet_wire_handle2md(&hdr->msg.ack.dst_wmd);
2288         if (md == NULL || md->md_threshold == 0 || md->md_me != NULL) {
2289                 /* Don't moan; this is expected */
2290                 CDEBUG(D_NET,
2291                        "%s: Dropping ACK from %s to %s MD %#llx.%#llx\n",
2292                        libcfs_nid2str(ni->ni_nid), libcfs_id2str(src),
2293                        (md == NULL) ? "invalid" : "inactive",
2294                        hdr->msg.ack.dst_wmd.wh_interface_cookie,
2295                        hdr->msg.ack.dst_wmd.wh_object_cookie);
2296                 if (md != NULL && md->md_me != NULL)
2297                         CERROR("Source MD also attached to portal %d\n",
2298                                md->md_me->me_portal);
2299
2300                 lnet_res_unlock(cpt);
2301                 return -ENOENT;                  /* -ve! */
2302         }
2303
2304         CDEBUG(D_NET, "%s: ACK from %s into md %#llx\n",
2305                libcfs_nid2str(ni->ni_nid), libcfs_id2str(src),
2306                hdr->msg.ack.dst_wmd.wh_object_cookie);
2307
2308         lnet_msg_attach_md(msg, md, 0, 0);
2309
2310         lnet_res_unlock(cpt);
2311
2312         lnet_build_msg_event(msg, LNET_EVENT_ACK);
2313
2314         lnet_ni_recv(ni, msg->msg_private, msg, 0, 0, 0, msg->msg_len);
2315         return 0;
2316 }
2317
2318 /**
2319  * \retval LNET_CREDIT_OK       If \a msg is forwarded
2320  * \retval LNET_CREDIT_WAIT     If \a msg is blocked because w/o buffer
2321  * \retval -ve                  error code
2322  */
2323 int
2324 lnet_parse_forward_locked(struct lnet_ni *ni, struct lnet_msg *msg)
2325 {
2326         int     rc = 0;
2327
2328         if (!the_lnet.ln_routing)
2329                 return -ECANCELED;
2330
2331         if (msg->msg_rxpeer->lpni_rtrcredits <= 0 ||
2332             lnet_msg2bufpool(msg)->rbp_credits <= 0) {
2333                 if (ni->ni_net->net_lnd->lnd_eager_recv == NULL) {
2334                         msg->msg_rx_ready_delay = 1;
2335                 } else {
2336                         lnet_net_unlock(msg->msg_rx_cpt);
2337                         rc = lnet_ni_eager_recv(ni, msg);
2338                         lnet_net_lock(msg->msg_rx_cpt);
2339                 }
2340         }
2341
2342         if (rc == 0)
2343                 rc = lnet_post_routed_recv_locked(msg, 0);
2344         return rc;
2345 }
2346
2347 int
2348 lnet_parse_local(struct lnet_ni *ni, struct lnet_msg *msg)
2349 {
2350         int     rc;
2351
2352         switch (msg->msg_type) {
2353         case LNET_MSG_ACK:
2354                 rc = lnet_parse_ack(ni, msg);
2355                 break;
2356         case LNET_MSG_PUT:
2357                 rc = lnet_parse_put(ni, msg);
2358                 break;
2359         case LNET_MSG_GET:
2360                 rc = lnet_parse_get(ni, msg, msg->msg_rdma_get);
2361                 break;
2362         case LNET_MSG_REPLY:
2363                 rc = lnet_parse_reply(ni, msg);
2364                 break;
2365         default: /* prevent an unused label if !kernel */
2366                 LASSERT(0);
2367                 return -EPROTO;
2368         }
2369
2370         LASSERT(rc == 0 || rc == -ENOENT);
2371         return rc;
2372 }
2373
2374 char *
2375 lnet_msgtyp2str (int type)
2376 {
2377         switch (type) {
2378         case LNET_MSG_ACK:
2379                 return ("ACK");
2380         case LNET_MSG_PUT:
2381                 return ("PUT");
2382         case LNET_MSG_GET:
2383                 return ("GET");
2384         case LNET_MSG_REPLY:
2385                 return ("REPLY");
2386         case LNET_MSG_HELLO:
2387                 return ("HELLO");
2388         default:
2389                 return ("<UNKNOWN>");
2390         }
2391 }
2392
2393 void
2394 lnet_print_hdr(struct lnet_hdr *hdr)
2395 {
2396         struct lnet_process_id src = {
2397                 .nid = hdr->src_nid,
2398                 .pid = hdr->src_pid,
2399         };
2400         struct lnet_process_id dst = {
2401                 .nid = hdr->dest_nid,
2402                 .pid = hdr->dest_pid,
2403         };
2404         char *type_str = lnet_msgtyp2str(hdr->type);
2405
2406         CWARN("P3 Header at %p of type %s\n", hdr, type_str);
2407         CWARN("    From %s\n", libcfs_id2str(src));
2408         CWARN("    To   %s\n", libcfs_id2str(dst));
2409
2410         switch (hdr->type) {
2411         default:
2412                 break;
2413
2414         case LNET_MSG_PUT:
2415                 CWARN("    Ptl index %d, ack md %#llx.%#llx, "
2416                       "match bits %llu\n",
2417                       hdr->msg.put.ptl_index,
2418                       hdr->msg.put.ack_wmd.wh_interface_cookie,
2419                       hdr->msg.put.ack_wmd.wh_object_cookie,
2420                       hdr->msg.put.match_bits);
2421                 CWARN("    Length %d, offset %d, hdr data %#llx\n",
2422                       hdr->payload_length, hdr->msg.put.offset,
2423                       hdr->msg.put.hdr_data);
2424                 break;
2425
2426         case LNET_MSG_GET:
2427                 CWARN("    Ptl index %d, return md %#llx.%#llx, "
2428                       "match bits %llu\n", hdr->msg.get.ptl_index,
2429                       hdr->msg.get.return_wmd.wh_interface_cookie,
2430                       hdr->msg.get.return_wmd.wh_object_cookie,
2431                       hdr->msg.get.match_bits);
2432                 CWARN("    Length %d, src offset %d\n",
2433                       hdr->msg.get.sink_length,
2434                       hdr->msg.get.src_offset);
2435                 break;
2436
2437         case LNET_MSG_ACK:
2438                 CWARN("    dst md %#llx.%#llx, "
2439                       "manipulated length %d\n",
2440                       hdr->msg.ack.dst_wmd.wh_interface_cookie,
2441                       hdr->msg.ack.dst_wmd.wh_object_cookie,
2442                       hdr->msg.ack.mlength);
2443                 break;
2444
2445         case LNET_MSG_REPLY:
2446                 CWARN("    dst md %#llx.%#llx, "
2447                       "length %d\n",
2448                       hdr->msg.reply.dst_wmd.wh_interface_cookie,
2449                       hdr->msg.reply.dst_wmd.wh_object_cookie,
2450                       hdr->payload_length);
2451         }
2452
2453 }
2454
2455 int
2456 lnet_parse(struct lnet_ni *ni, struct lnet_hdr *hdr, lnet_nid_t from_nid,
2457            void *private, int rdma_req)
2458 {
2459         int             rc = 0;
2460         int             cpt;
2461         int             for_me;
2462         struct lnet_msg *msg;
2463         lnet_pid_t     dest_pid;
2464         lnet_nid_t     dest_nid;
2465         lnet_nid_t     src_nid;
2466         struct lnet_peer_ni *lpni;
2467         __u32          payload_length;
2468         __u32          type;
2469
2470         LASSERT (!in_interrupt ());
2471
2472         type = le32_to_cpu(hdr->type);
2473         src_nid = le64_to_cpu(hdr->src_nid);
2474         dest_nid = le64_to_cpu(hdr->dest_nid);
2475         dest_pid = le32_to_cpu(hdr->dest_pid);
2476         payload_length = le32_to_cpu(hdr->payload_length);
2477
2478         for_me = (ni->ni_nid == dest_nid);
2479         cpt = lnet_cpt_of_nid(from_nid, ni);
2480
2481         CDEBUG(D_NET, "TRACE: %s(%s) <- %s : %s - %s\n",
2482                 libcfs_nid2str(dest_nid),
2483                 libcfs_nid2str(ni->ni_nid),
2484                 libcfs_nid2str(src_nid),
2485                 lnet_msgtyp2str(type),
2486                 (for_me) ? "for me" : "routed");
2487
2488         switch (type) {
2489         case LNET_MSG_ACK:
2490         case LNET_MSG_GET:
2491                 if (payload_length > 0) {
2492                         CERROR("%s, src %s: bad %s payload %d (0 expected)\n",
2493                                libcfs_nid2str(from_nid),
2494                                libcfs_nid2str(src_nid),
2495                                lnet_msgtyp2str(type), payload_length);
2496                         return -EPROTO;
2497                 }
2498                 break;
2499
2500         case LNET_MSG_PUT:
2501         case LNET_MSG_REPLY:
2502                 if (payload_length >
2503                     (__u32)(for_me ? LNET_MAX_PAYLOAD : LNET_MTU)) {
2504                         CERROR("%s, src %s: bad %s payload %d "
2505                                "(%d max expected)\n",
2506                                libcfs_nid2str(from_nid),
2507                                libcfs_nid2str(src_nid),
2508                                lnet_msgtyp2str(type),
2509                                payload_length,
2510                                for_me ? LNET_MAX_PAYLOAD : LNET_MTU);
2511                         return -EPROTO;
2512                 }
2513                 break;
2514
2515         default:
2516                 CERROR("%s, src %s: Bad message type 0x%x\n",
2517                        libcfs_nid2str(from_nid),
2518                        libcfs_nid2str(src_nid), type);
2519                 return -EPROTO;
2520         }
2521
2522         if (the_lnet.ln_routing &&
2523             ni->ni_last_alive != ktime_get_real_seconds()) {
2524                 /* NB: so far here is the only place to set NI status to "up */
2525                 lnet_ni_lock(ni);
2526                 ni->ni_last_alive = ktime_get_real_seconds();
2527                 if (ni->ni_status != NULL &&
2528                     ni->ni_status->ns_status == LNET_NI_STATUS_DOWN)
2529                         ni->ni_status->ns_status = LNET_NI_STATUS_UP;
2530                 lnet_ni_unlock(ni);
2531         }
2532
2533         /* Regard a bad destination NID as a protocol error.  Senders should
2534          * know what they're doing; if they don't they're misconfigured, buggy
2535          * or malicious so we chop them off at the knees :) */
2536
2537         if (!for_me) {
2538                 if (LNET_NIDNET(dest_nid) == LNET_NIDNET(ni->ni_nid)) {
2539                         /* should have gone direct */
2540                         CERROR("%s, src %s: Bad dest nid %s "
2541                                "(should have been sent direct)\n",
2542                                 libcfs_nid2str(from_nid),
2543                                 libcfs_nid2str(src_nid),
2544                                 libcfs_nid2str(dest_nid));
2545                         return -EPROTO;
2546                 }
2547
2548                 if (lnet_islocalnid(dest_nid)) {
2549                         /* dest is another local NI; sender should have used
2550                          * this node's NID on its own network */
2551                         CERROR("%s, src %s: Bad dest nid %s "
2552                                "(it's my nid but on a different network)\n",
2553                                 libcfs_nid2str(from_nid),
2554                                 libcfs_nid2str(src_nid),
2555                                 libcfs_nid2str(dest_nid));
2556                         return -EPROTO;
2557                 }
2558
2559                 if (rdma_req && type == LNET_MSG_GET) {
2560                         CERROR("%s, src %s: Bad optimized GET for %s "
2561                                "(final destination must be me)\n",
2562                                 libcfs_nid2str(from_nid),
2563                                 libcfs_nid2str(src_nid),
2564                                 libcfs_nid2str(dest_nid));
2565                         return -EPROTO;
2566                 }
2567
2568                 if (!the_lnet.ln_routing) {
2569                         CERROR("%s, src %s: Dropping message for %s "
2570                                "(routing not enabled)\n",
2571                                 libcfs_nid2str(from_nid),
2572                                 libcfs_nid2str(src_nid),
2573                                 libcfs_nid2str(dest_nid));
2574                         goto drop;
2575                 }
2576         }
2577
2578         /* Message looks OK; we're not going to return an error, so we MUST
2579          * call back lnd_recv() come what may... */
2580
2581         if (!list_empty(&the_lnet.ln_test_peers) &&     /* normally we don't */
2582             fail_peer(src_nid, 0)) {                    /* shall we now? */
2583                 CERROR("%s, src %s: Dropping %s to simulate failure\n",
2584                        libcfs_nid2str(from_nid), libcfs_nid2str(src_nid),
2585                        lnet_msgtyp2str(type));
2586                 goto drop;
2587         }
2588
2589         if (!list_empty(&the_lnet.ln_drop_rules) &&
2590             lnet_drop_rule_match(hdr)) {
2591                 CDEBUG(D_NET, "%s, src %s, dst %s: Dropping %s to simulate"
2592                               "silent message loss\n",
2593                        libcfs_nid2str(from_nid), libcfs_nid2str(src_nid),
2594                        libcfs_nid2str(dest_nid), lnet_msgtyp2str(type));
2595                 goto drop;
2596         }
2597
2598
2599         msg = lnet_msg_alloc();
2600         if (msg == NULL) {
2601                 CERROR("%s, src %s: Dropping %s (out of memory)\n",
2602                        libcfs_nid2str(from_nid), libcfs_nid2str(src_nid),
2603                        lnet_msgtyp2str(type));
2604                 goto drop;
2605         }
2606
2607         /* msg zeroed in lnet_msg_alloc; i.e. flags all clear,
2608          * pointers NULL etc */
2609
2610         msg->msg_type = type;
2611         msg->msg_private = private;
2612         msg->msg_receiving = 1;
2613         msg->msg_rdma_get = rdma_req;
2614         msg->msg_len = msg->msg_wanted = payload_length;
2615         msg->msg_offset = 0;
2616         msg->msg_hdr = *hdr;
2617         /* for building message event */
2618         msg->msg_from = from_nid;
2619         if (!for_me) {
2620                 msg->msg_target.pid     = dest_pid;
2621                 msg->msg_target.nid     = dest_nid;
2622                 msg->msg_routing        = 1;
2623
2624         } else {
2625                 /* convert common msg->hdr fields to host byteorder */
2626                 msg->msg_hdr.type       = type;
2627                 msg->msg_hdr.src_nid    = src_nid;
2628                 msg->msg_hdr.src_pid    = le32_to_cpu(msg->msg_hdr.src_pid);
2629                 msg->msg_hdr.dest_nid   = dest_nid;
2630                 msg->msg_hdr.dest_pid   = dest_pid;
2631                 msg->msg_hdr.payload_length = payload_length;
2632         }
2633
2634         lnet_net_lock(cpt);
2635         lpni = lnet_nid2peerni_locked(from_nid, ni->ni_nid, cpt);
2636         if (IS_ERR(lpni)) {
2637                 lnet_net_unlock(cpt);
2638                 CERROR("%s, src %s: Dropping %s "
2639                        "(error %ld looking up sender)\n",
2640                        libcfs_nid2str(from_nid), libcfs_nid2str(src_nid),
2641                        lnet_msgtyp2str(type), PTR_ERR(lpni));
2642                 lnet_msg_free(msg);
2643                 if (rc == -ESHUTDOWN)
2644                         /* We are shutting down.  Don't do anything more */
2645                         return 0;
2646                 goto drop;
2647         }
2648         msg->msg_rxpeer = lpni;
2649         msg->msg_rxni = ni;
2650         lnet_ni_addref_locked(ni, cpt);
2651         /* Multi-Rail: Primary NID of source. */
2652         msg->msg_initiator = lnet_peer_primary_nid_locked(src_nid);
2653
2654         if (lnet_isrouter(msg->msg_rxpeer)) {
2655                 lnet_peer_set_alive(msg->msg_rxpeer);
2656                 if (avoid_asym_router_failure &&
2657                     LNET_NIDNET(src_nid) != LNET_NIDNET(from_nid)) {
2658                         /* received a remote message from router, update
2659                          * remote NI status on this router.
2660                          * NB: multi-hop routed message will be ignored.
2661                          */
2662                         lnet_router_ni_update_locked(msg->msg_rxpeer,
2663                                                      LNET_NIDNET(src_nid));
2664                 }
2665         }
2666
2667         lnet_msg_commit(msg, cpt);
2668
2669         /* message delay simulation */
2670         if (unlikely(!list_empty(&the_lnet.ln_delay_rules) &&
2671                      lnet_delay_rule_match_locked(hdr, msg))) {
2672                 lnet_net_unlock(cpt);
2673                 return 0;
2674         }
2675
2676         if (!for_me) {
2677                 rc = lnet_parse_forward_locked(ni, msg);
2678                 lnet_net_unlock(cpt);
2679
2680                 if (rc < 0)
2681                         goto free_drop;
2682
2683                 if (rc == LNET_CREDIT_OK) {
2684                         lnet_ni_recv(ni, msg->msg_private, msg, 0,
2685                                      0, payload_length, payload_length);
2686                 }
2687                 return 0;
2688         }
2689
2690         lnet_net_unlock(cpt);
2691
2692         rc = lnet_parse_local(ni, msg);
2693         if (rc != 0)
2694                 goto free_drop;
2695         return 0;
2696
2697  free_drop:
2698         LASSERT(msg->msg_md == NULL);
2699         lnet_finalize(msg, rc);
2700
2701  drop:
2702         lnet_drop_message(ni, cpt, private, payload_length);
2703         return 0;
2704 }
2705 EXPORT_SYMBOL(lnet_parse);
2706
2707 void
2708 lnet_drop_delayed_msg_list(struct list_head *head, char *reason)
2709 {
2710         while (!list_empty(head)) {
2711                 struct lnet_process_id id = {0};
2712                 struct lnet_msg *msg;
2713
2714                 msg = list_entry(head->next, struct lnet_msg, msg_list);
2715                 list_del(&msg->msg_list);
2716
2717                 id.nid = msg->msg_hdr.src_nid;
2718                 id.pid = msg->msg_hdr.src_pid;
2719
2720                 LASSERT(msg->msg_md == NULL);
2721                 LASSERT(msg->msg_rx_delayed);
2722                 LASSERT(msg->msg_rxpeer != NULL);
2723                 LASSERT(msg->msg_hdr.type == LNET_MSG_PUT);
2724
2725                 CWARN("Dropping delayed PUT from %s portal %d match %llu"
2726                       " offset %d length %d: %s\n",
2727                       libcfs_id2str(id),
2728                       msg->msg_hdr.msg.put.ptl_index,
2729                       msg->msg_hdr.msg.put.match_bits,
2730                       msg->msg_hdr.msg.put.offset,
2731                       msg->msg_hdr.payload_length, reason);
2732
2733                 /* NB I can't drop msg's ref on msg_rxpeer until after I've
2734                  * called lnet_drop_message(), so I just hang onto msg as well
2735                  * until that's done */
2736
2737                 lnet_drop_message(msg->msg_rxni, msg->msg_rx_cpt,
2738                                   msg->msg_private, msg->msg_len);
2739                 /*
2740                  * NB: message will not generate event because w/o attached MD,
2741                  * but we still should give error code so lnet_msg_decommit()
2742                  * can skip counters operations and other checks.
2743                  */
2744                 lnet_finalize(msg, -ENOENT);
2745         }
2746 }
2747
2748 void
2749 lnet_recv_delayed_msg_list(struct list_head *head)
2750 {
2751         while (!list_empty(head)) {
2752                 struct lnet_msg *msg;
2753                 struct lnet_process_id id;
2754
2755                 msg = list_entry(head->next, struct lnet_msg, msg_list);
2756                 list_del(&msg->msg_list);
2757
2758                 /* md won't disappear under me, since each msg
2759                  * holds a ref on it */
2760
2761                 id.nid = msg->msg_hdr.src_nid;
2762                 id.pid = msg->msg_hdr.src_pid;
2763
2764                 LASSERT(msg->msg_rx_delayed);
2765                 LASSERT(msg->msg_md != NULL);
2766                 LASSERT(msg->msg_rxpeer != NULL);
2767                 LASSERT(msg->msg_rxni != NULL);
2768                 LASSERT(msg->msg_hdr.type == LNET_MSG_PUT);
2769
2770                 CDEBUG(D_NET, "Resuming delayed PUT from %s portal %d "
2771                        "match %llu offset %d length %d.\n",
2772                         libcfs_id2str(id), msg->msg_hdr.msg.put.ptl_index,
2773                         msg->msg_hdr.msg.put.match_bits,
2774                         msg->msg_hdr.msg.put.offset,
2775                         msg->msg_hdr.payload_length);
2776
2777                 lnet_recv_put(msg->msg_rxni, msg);
2778         }
2779 }
2780
2781 /**
2782  * Initiate an asynchronous PUT operation.
2783  *
2784  * There are several events associated with a PUT: completion of the send on
2785  * the initiator node (LNET_EVENT_SEND), and when the send completes
2786  * successfully, the receipt of an acknowledgment (LNET_EVENT_ACK) indicating
2787  * that the operation was accepted by the target. The event LNET_EVENT_PUT is
2788  * used at the target node to indicate the completion of incoming data
2789  * delivery.
2790  *
2791  * The local events will be logged in the EQ associated with the MD pointed to
2792  * by \a mdh handle. Using a MD without an associated EQ results in these
2793  * events being discarded. In this case, the caller must have another
2794  * mechanism (e.g., a higher level protocol) for determining when it is safe
2795  * to modify the memory region associated with the MD.
2796  *
2797  * Note that LNet does not guarantee the order of LNET_EVENT_SEND and
2798  * LNET_EVENT_ACK, though intuitively ACK should happen after SEND.
2799  *
2800  * \param self Indicates the NID of a local interface through which to send
2801  * the PUT request. Use LNET_NID_ANY to let LNet choose one by itself.
2802  * \param mdh A handle for the MD that describes the memory to be sent. The MD
2803  * must be "free floating" (See LNetMDBind()).
2804  * \param ack Controls whether an acknowledgment is requested.
2805  * Acknowledgments are only sent when they are requested by the initiating
2806  * process and the target MD enables them.
2807  * \param target A process identifier for the target process.
2808  * \param portal The index in the \a target's portal table.
2809  * \param match_bits The match bits to use for MD selection at the target
2810  * process.
2811  * \param offset The offset into the target MD (only used when the target
2812  * MD has the LNET_MD_MANAGE_REMOTE option set).
2813  * \param hdr_data 64 bits of user data that can be included in the message
2814  * header. This data is written to an event queue entry at the target if an
2815  * EQ is present on the matching MD.
2816  *
2817  * \retval  0      Success, and only in this case events will be generated
2818  * and logged to EQ (if it exists).
2819  * \retval -EIO    Simulated failure.
2820  * \retval -ENOMEM Memory allocation failure.
2821  * \retval -ENOENT Invalid MD object.
2822  *
2823  * \see struct lnet_event::hdr_data and lnet_event_kind_t.
2824  */
2825 int
2826 LNetPut(lnet_nid_t self, struct lnet_handle_md mdh, enum lnet_ack_req ack,
2827         struct lnet_process_id target, unsigned int portal,
2828         __u64 match_bits, unsigned int offset,
2829         __u64 hdr_data)
2830 {
2831         struct lnet_msg         *msg;
2832         struct lnet_libmd       *md;
2833         int                     cpt;
2834         int                     rc;
2835
2836         LASSERT(the_lnet.ln_refcount > 0);
2837
2838         if (!list_empty(&the_lnet.ln_test_peers) &&     /* normally we don't */
2839             fail_peer(target.nid, 1)) {                 /* shall we now? */
2840                 CERROR("Dropping PUT to %s: simulated failure\n",
2841                        libcfs_id2str(target));
2842                 return -EIO;
2843         }
2844
2845         msg = lnet_msg_alloc();
2846         if (msg == NULL) {
2847                 CERROR("Dropping PUT to %s: ENOMEM on struct lnet_msg\n",
2848                        libcfs_id2str(target));
2849                 return -ENOMEM;
2850         }
2851         msg->msg_vmflush = !!memory_pressure_get();
2852
2853         cpt = lnet_cpt_of_cookie(mdh.cookie);
2854         lnet_res_lock(cpt);
2855
2856         md = lnet_handle2md(&mdh);
2857         if (md == NULL || md->md_threshold == 0 || md->md_me != NULL) {
2858                 CERROR("Dropping PUT (%llu:%d:%s): MD (%d) invalid\n",
2859                        match_bits, portal, libcfs_id2str(target),
2860                        md == NULL ? -1 : md->md_threshold);
2861                 if (md != NULL && md->md_me != NULL)
2862                         CERROR("Source MD also attached to portal %d\n",
2863                                md->md_me->me_portal);
2864                 lnet_res_unlock(cpt);
2865
2866                 lnet_msg_free(msg);
2867                 return -ENOENT;
2868         }
2869
2870         CDEBUG(D_NET, "LNetPut -> %s\n", libcfs_id2str(target));
2871
2872         lnet_msg_attach_md(msg, md, 0, 0);
2873
2874         lnet_prep_send(msg, LNET_MSG_PUT, target, 0, md->md_length);
2875
2876         msg->msg_hdr.msg.put.match_bits = cpu_to_le64(match_bits);
2877         msg->msg_hdr.msg.put.ptl_index = cpu_to_le32(portal);
2878         msg->msg_hdr.msg.put.offset = cpu_to_le32(offset);
2879         msg->msg_hdr.msg.put.hdr_data = hdr_data;
2880
2881         /* NB handles only looked up by creator (no flips) */
2882         if (ack == LNET_ACK_REQ) {
2883                 msg->msg_hdr.msg.put.ack_wmd.wh_interface_cookie =
2884                         the_lnet.ln_interface_cookie;
2885                 msg->msg_hdr.msg.put.ack_wmd.wh_object_cookie =
2886                         md->md_lh.lh_cookie;
2887         } else {
2888                 msg->msg_hdr.msg.put.ack_wmd.wh_interface_cookie =
2889                         LNET_WIRE_HANDLE_COOKIE_NONE;
2890                 msg->msg_hdr.msg.put.ack_wmd.wh_object_cookie =
2891                         LNET_WIRE_HANDLE_COOKIE_NONE;
2892         }
2893
2894         lnet_res_unlock(cpt);
2895
2896         lnet_build_msg_event(msg, LNET_EVENT_SEND);
2897
2898         rc = lnet_send(self, msg, LNET_NID_ANY);
2899         if (rc != 0) {
2900                 CNETERR("Error sending PUT to %s: %d\n",
2901                         libcfs_id2str(target), rc);
2902                 lnet_finalize(msg, rc);
2903         }
2904
2905         /* completion will be signalled by an event */
2906         return 0;
2907 }
2908 EXPORT_SYMBOL(LNetPut);
2909
2910 /*
2911  * The LND can DMA direct to the GET md (i.e. no REPLY msg).  This
2912  * returns a msg for the LND to pass to lnet_finalize() when the sink
2913  * data has been received.
2914  *
2915  * CAVEAT EMPTOR: 'getmsg' is the original GET, which is freed when
2916  * lnet_finalize() is called on it, so the LND must call this first
2917  */
2918 struct lnet_msg *
2919 lnet_create_reply_msg(struct lnet_ni *ni, struct lnet_msg *getmsg)
2920 {
2921         struct lnet_msg *msg = lnet_msg_alloc();
2922         struct lnet_libmd *getmd = getmsg->msg_md;
2923         struct lnet_process_id peer_id = getmsg->msg_target;
2924         int cpt;
2925
2926         LASSERT(!getmsg->msg_target_is_router);
2927         LASSERT(!getmsg->msg_routing);
2928
2929         if (msg == NULL) {
2930                 CERROR("%s: Dropping REPLY from %s: can't allocate msg\n",
2931                        libcfs_nid2str(ni->ni_nid), libcfs_id2str(peer_id));
2932                 goto drop;
2933         }
2934
2935         cpt = lnet_cpt_of_cookie(getmd->md_lh.lh_cookie);
2936         lnet_res_lock(cpt);
2937
2938         LASSERT(getmd->md_refcount > 0);
2939
2940         if (getmd->md_threshold == 0) {
2941                 CERROR("%s: Dropping REPLY from %s for inactive MD %p\n",
2942                         libcfs_nid2str(ni->ni_nid), libcfs_id2str(peer_id),
2943                         getmd);
2944                 lnet_res_unlock(cpt);
2945                 goto drop;
2946         }
2947
2948         LASSERT(getmd->md_offset == 0);
2949
2950         CDEBUG(D_NET, "%s: Reply from %s md %p\n",
2951                libcfs_nid2str(ni->ni_nid), libcfs_id2str(peer_id), getmd);
2952
2953         /* setup information for lnet_build_msg_event */
2954         msg->msg_initiator = getmsg->msg_txpeer->lpni_peer_net->lpn_peer->lp_primary_nid;
2955         msg->msg_from = peer_id.nid;
2956         msg->msg_type = LNET_MSG_GET; /* flag this msg as an "optimized" GET */
2957         msg->msg_hdr.src_nid = peer_id.nid;
2958         msg->msg_hdr.payload_length = getmd->md_length;
2959         msg->msg_receiving = 1; /* required by lnet_msg_attach_md */
2960
2961         lnet_msg_attach_md(msg, getmd, getmd->md_offset, getmd->md_length);
2962         lnet_res_unlock(cpt);
2963
2964         cpt = lnet_cpt_of_nid(peer_id.nid, ni);
2965
2966         lnet_net_lock(cpt);
2967         lnet_msg_commit(msg, cpt);
2968         lnet_net_unlock(cpt);
2969
2970         lnet_build_msg_event(msg, LNET_EVENT_REPLY);
2971
2972         return msg;
2973
2974  drop:
2975         cpt = lnet_cpt_of_nid(peer_id.nid, ni);
2976
2977         lnet_net_lock(cpt);
2978         the_lnet.ln_counters[cpt]->drop_count++;
2979         the_lnet.ln_counters[cpt]->drop_length += getmd->md_length;
2980         lnet_net_unlock(cpt);
2981
2982         if (msg != NULL)
2983                 lnet_msg_free(msg);
2984
2985         return NULL;
2986 }
2987 EXPORT_SYMBOL(lnet_create_reply_msg);
2988
2989 void
2990 lnet_set_reply_msg_len(struct lnet_ni *ni, struct lnet_msg *reply,
2991                        unsigned int len)
2992 {
2993         /* Set the REPLY length, now the RDMA that elides the REPLY message has
2994          * completed and I know it. */
2995         LASSERT(reply != NULL);
2996         LASSERT(reply->msg_type == LNET_MSG_GET);
2997         LASSERT(reply->msg_ev.type == LNET_EVENT_REPLY);
2998
2999         /* NB I trusted my peer to RDMA.  If she tells me she's written beyond
3000          * the end of my buffer, I might as well be dead. */
3001         LASSERT(len <= reply->msg_ev.mlength);
3002
3003         reply->msg_ev.mlength = len;
3004 }
3005 EXPORT_SYMBOL(lnet_set_reply_msg_len);
3006
3007 /**
3008  * Initiate an asynchronous GET operation.
3009  *
3010  * On the initiator node, an LNET_EVENT_SEND is logged when the GET request
3011  * is sent, and an LNET_EVENT_REPLY is logged when the data returned from
3012  * the target node in the REPLY has been written to local MD.
3013  *
3014  * On the target node, an LNET_EVENT_GET is logged when the GET request
3015  * arrives and is accepted into a MD.
3016  *
3017  * \param self,target,portal,match_bits,offset See the discussion in LNetPut().
3018  * \param mdh A handle for the MD that describes the memory into which the
3019  * requested data will be received. The MD must be "free floating" (See LNetMDBind()).
3020  *
3021  * \retval  0      Success, and only in this case events will be generated
3022  * and logged to EQ (if it exists) of the MD.
3023  * \retval -EIO    Simulated failure.
3024  * \retval -ENOMEM Memory allocation failure.
3025  * \retval -ENOENT Invalid MD object.
3026  */
3027 int
3028 LNetGet(lnet_nid_t self, struct lnet_handle_md mdh,
3029         struct lnet_process_id target, unsigned int portal,
3030         __u64 match_bits, unsigned int offset)
3031 {
3032         struct lnet_msg         *msg;
3033         struct lnet_libmd       *md;
3034         int                     cpt;
3035         int                     rc;
3036
3037         LASSERT(the_lnet.ln_refcount > 0);
3038
3039         if (!list_empty(&the_lnet.ln_test_peers) &&     /* normally we don't */
3040             fail_peer(target.nid, 1))                   /* shall we now? */
3041         {
3042                 CERROR("Dropping GET to %s: simulated failure\n",
3043                        libcfs_id2str(target));
3044                 return -EIO;
3045         }
3046
3047         msg = lnet_msg_alloc();
3048         if (msg == NULL) {
3049                 CERROR("Dropping GET to %s: ENOMEM on struct lnet_msg\n",
3050                        libcfs_id2str(target));
3051                 return -ENOMEM;
3052         }
3053
3054         cpt = lnet_cpt_of_cookie(mdh.cookie);
3055         lnet_res_lock(cpt);
3056
3057         md = lnet_handle2md(&mdh);
3058         if (md == NULL || md->md_threshold == 0 || md->md_me != NULL) {
3059                 CERROR("Dropping GET (%llu:%d:%s): MD (%d) invalid\n",
3060                        match_bits, portal, libcfs_id2str(target),
3061                        md == NULL ? -1 : md->md_threshold);
3062                 if (md != NULL && md->md_me != NULL)
3063                         CERROR("REPLY MD also attached to portal %d\n",
3064                                md->md_me->me_portal);
3065
3066                 lnet_res_unlock(cpt);
3067
3068                 lnet_msg_free(msg);
3069                 return -ENOENT;
3070         }
3071
3072         CDEBUG(D_NET, "LNetGet -> %s\n", libcfs_id2str(target));
3073
3074         lnet_msg_attach_md(msg, md, 0, 0);
3075
3076         lnet_prep_send(msg, LNET_MSG_GET, target, 0, 0);
3077
3078         msg->msg_hdr.msg.get.match_bits = cpu_to_le64(match_bits);
3079         msg->msg_hdr.msg.get.ptl_index = cpu_to_le32(portal);
3080         msg->msg_hdr.msg.get.src_offset = cpu_to_le32(offset);
3081         msg->msg_hdr.msg.get.sink_length = cpu_to_le32(md->md_length);
3082
3083         /* NB handles only looked up by creator (no flips) */
3084         msg->msg_hdr.msg.get.return_wmd.wh_interface_cookie =
3085                 the_lnet.ln_interface_cookie;
3086         msg->msg_hdr.msg.get.return_wmd.wh_object_cookie =
3087                 md->md_lh.lh_cookie;
3088
3089         lnet_res_unlock(cpt);
3090
3091         lnet_build_msg_event(msg, LNET_EVENT_SEND);
3092
3093         rc = lnet_send(self, msg, LNET_NID_ANY);
3094         if (rc < 0) {
3095                 CNETERR("Error sending GET to %s: %d\n",
3096                         libcfs_id2str(target), rc);
3097                 lnet_finalize(msg, rc);
3098         }
3099
3100         /* completion will be signalled by an event */
3101         return 0;
3102 }
3103 EXPORT_SYMBOL(LNetGet);
3104
3105 /**
3106  * Calculate distance to node at \a dstnid.
3107  *
3108  * \param dstnid Target NID.
3109  * \param srcnidp If not NULL, NID of the local interface to reach \a dstnid
3110  * is saved here.
3111  * \param orderp If not NULL, order of the route to reach \a dstnid is saved
3112  * here.
3113  *
3114  * \retval 0 If \a dstnid belongs to a local interface, and reserved option
3115  * local_nid_dist_zero is set, which is the default.
3116  * \retval positives Distance to target NID, i.e. number of hops plus one.
3117  * \retval -EHOSTUNREACH If \a dstnid is not reachable.
3118  */
3119 int
3120 LNetDist(lnet_nid_t dstnid, lnet_nid_t *srcnidp, __u32 *orderp)
3121 {
3122         struct list_head        *e;
3123         struct lnet_ni *ni = NULL;
3124         struct lnet_remotenet *rnet;
3125         __u32                   dstnet = LNET_NIDNET(dstnid);
3126         int                     hops;
3127         int                     cpt;
3128         __u32                   order = 2;
3129         struct list_head        *rn_list;
3130
3131         /* if !local_nid_dist_zero, I don't return a distance of 0 ever
3132          * (when lustre sees a distance of 0, it substitutes 0@lo), so I
3133          * keep order 0 free for 0@lo and order 1 free for a local NID
3134          * match */
3135
3136         LASSERT(the_lnet.ln_refcount > 0);
3137
3138         cpt = lnet_net_lock_current();
3139
3140         while ((ni = lnet_get_next_ni_locked(NULL, ni))) {
3141                 if (ni->ni_nid == dstnid) {
3142                         if (srcnidp != NULL)
3143                                 *srcnidp = dstnid;
3144                         if (orderp != NULL) {
3145                                 if (LNET_NETTYP(LNET_NIDNET(dstnid)) == LOLND)
3146                                         *orderp = 0;
3147                                 else
3148                                         *orderp = 1;
3149                         }
3150                         lnet_net_unlock(cpt);
3151
3152                         return local_nid_dist_zero ? 0 : 1;
3153                 }
3154
3155                 if (LNET_NIDNET(ni->ni_nid) == dstnet) {
3156                         /* Check if ni was originally created in
3157                          * current net namespace.
3158                          * If not, assign order above 0xffff0000,
3159                          * to make this ni not a priority. */
3160                         if (!net_eq(ni->ni_net_ns, current->nsproxy->net_ns))
3161                                 order += 0xffff0000;
3162
3163                         if (srcnidp != NULL)
3164                                 *srcnidp = ni->ni_nid;
3165                         if (orderp != NULL)
3166                                 *orderp = order;
3167                         lnet_net_unlock(cpt);
3168                         return 1;
3169                 }
3170
3171                 order++;
3172         }
3173
3174         rn_list = lnet_net2rnethash(dstnet);
3175         list_for_each(e, rn_list) {
3176                 rnet = list_entry(e, struct lnet_remotenet, lrn_list);
3177
3178                 if (rnet->lrn_net == dstnet) {
3179                         struct lnet_route *route;
3180                         struct lnet_route *shortest = NULL;
3181                         __u32 shortest_hops = LNET_UNDEFINED_HOPS;
3182                         __u32 route_hops;
3183
3184                         LASSERT(!list_empty(&rnet->lrn_routes));
3185
3186                         list_for_each_entry(route, &rnet->lrn_routes,
3187                                             lr_list) {
3188                                 route_hops = route->lr_hops;
3189                                 if (route_hops == LNET_UNDEFINED_HOPS)
3190                                         route_hops = 1;
3191                                 if (shortest == NULL ||
3192                                     route_hops < shortest_hops) {
3193                                         shortest = route;
3194                                         shortest_hops = route_hops;
3195                                 }
3196                         }
3197
3198                         LASSERT(shortest != NULL);
3199                         hops = shortest_hops;
3200                         if (srcnidp != NULL) {
3201                                 ni = lnet_get_next_ni_locked(
3202                                         shortest->lr_gateway->lpni_net,
3203                                         NULL);
3204                                 *srcnidp = ni->ni_nid;
3205                         }
3206                         if (orderp != NULL)
3207                                 *orderp = order;
3208                         lnet_net_unlock(cpt);
3209                         return hops + 1;
3210                 }
3211                 order++;
3212         }
3213
3214         lnet_net_unlock(cpt);
3215         return -EHOSTUNREACH;
3216 }
3217 EXPORT_SYMBOL(LNetDist);