Whamcloud - gitweb
b97abb1defb3a0e16b14f2828f46a22cadc98086
[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                         list_for_each_entry(lpni, &peer_net->lpn_peer_nis,
1614                                             lpni_peer_nis) {
1615                                 if (lpni->lpni_pref_nnids == 0)
1616                                         continue;
1617                                 LASSERT(lpni->lpni_pref_nnids == 1);
1618                                 best_ni = lnet_nid2ni_locked(
1619                                                 lpni->lpni_pref.nid, cpt);
1620                                 break;
1621                         }
1622                 }
1623                 /* if best_ni is still not set just pick one */
1624                 if (!best_ni) {
1625                         best_ni = lnet_net2ni_locked(
1626                                 best_lpni->lpni_net->net_id, cpt);
1627                         /* If there is no best_ni we don't have a route */
1628                         if (!best_ni) {
1629                                 lnet_net_unlock(cpt);
1630                                 CERROR("no path to %s from net %s\n",
1631                                         libcfs_nid2str(best_lpni->lpni_nid),
1632                                         libcfs_net2str(best_lpni->lpni_net->net_id));
1633                                 return -EHOSTUNREACH;
1634                         }
1635                         lpni = list_entry(peer_net->lpn_peer_nis.next,
1636                                         struct lnet_peer_ni,
1637                                         lpni_peer_nis);
1638                 }
1639                 /* Set preferred NI if necessary. */
1640                 if (lpni->lpni_pref_nnids == 0)
1641                         lnet_peer_ni_set_non_mr_pref_nid(lpni, best_ni->ni_nid);
1642         }
1643
1644         /*
1645          * if we already found a best_ni because src_nid is specified and
1646          * best_lpni because we are replying to a message then just send
1647          * the message
1648          */
1649         if (best_ni && best_lpni)
1650                 goto send;
1651
1652         /*
1653          * If we already found a best_ni because src_nid is specified then
1654          * pick the peer then send the message
1655          */
1656         if (best_ni)
1657                 goto pick_peer;
1658
1659         /*
1660          * pick the best_ni by going through all the possible networks of
1661          * that peer and see which local NI is best suited to talk to that
1662          * peer.
1663          *
1664          * Locally connected networks will always be preferred over
1665          * a routed network. If there are only routed paths to the peer,
1666          * then the best route is chosen. If all routes are equal then
1667          * they are used in round robin.
1668          */
1669         list_for_each_entry(peer_net, &peer->lp_peer_nets, lpn_peer_nets) {
1670                 if (!lnet_is_peer_net_healthy_locked(peer_net))
1671                         continue;
1672
1673                 local_net = lnet_get_net_locked(peer_net->lpn_net_id);
1674                 if (!local_net && !routing && !local_found) {
1675                         struct lnet_peer_ni *net_gw;
1676
1677                         lpni = list_entry(peer_net->lpn_peer_nis.next,
1678                                           struct lnet_peer_ni,
1679                                           lpni_peer_nis);
1680
1681                         net_gw = lnet_find_route_locked(NULL,
1682                                                         lpni->lpni_nid,
1683                                                         rtr_nid);
1684                         if (!net_gw)
1685                                 continue;
1686
1687                         if (best_gw) {
1688                                 /*
1689                                  * lnet_find_route_locked() call
1690                                  * will return the best_Gw on the
1691                                  * lpni->lpni_nid network.
1692                                  * However, best_gw and net_gw can
1693                                  * be on different networks.
1694                                  * Therefore need to compare them
1695                                  * to pick the better of either.
1696                                  */
1697                                 if (lnet_compare_peers(best_gw, net_gw) > 0)
1698                                         continue;
1699                                 if (best_gw->lpni_gw_seq <= net_gw->lpni_gw_seq)
1700                                         continue;
1701                         }
1702                         best_gw = net_gw;
1703                         final_dst = lpni;
1704
1705                         routing2 = true;
1706                 } else {
1707                         best_gw = NULL;
1708                         final_dst = NULL;
1709                         routing2 = false;
1710                         local_found = true;
1711                 }
1712
1713                 /*
1714                  * a gw on this network is found, but there could be
1715                  * other better gateways on other networks. So don't pick
1716                  * the best_ni until we determine the best_gw.
1717                  */
1718                 if (best_gw)
1719                         continue;
1720
1721                 /* if no local_net found continue */
1722                 if (!local_net)
1723                         continue;
1724
1725                 /*
1726                  * Iterate through the NIs in this local Net and select
1727                  * the NI to send from. The selection is determined by
1728                  * these 3 criterion in the following priority:
1729                  *      1. NUMA
1730                  *      2. NI available credits
1731                  *      3. Round Robin
1732                  */
1733                 best_ni = lnet_get_best_ni(local_net, best_ni, md_cpt);
1734         }
1735
1736         if (!best_ni && !best_gw) {
1737                 lnet_net_unlock(cpt);
1738                 LCONSOLE_WARN("No local ni found to send from to %s\n",
1739                         libcfs_nid2str(dst_nid));
1740                 return -EINVAL;
1741         }
1742
1743         if (!best_ni) {
1744                 best_ni = lnet_get_best_ni(best_gw->lpni_net, best_ni, md_cpt);
1745                 LASSERT(best_gw && best_ni);
1746
1747                 /*
1748                  * We're going to route the message, so change the peer to
1749                  * the router.
1750                  */
1751                 LASSERT(best_gw->lpni_peer_net);
1752                 LASSERT(best_gw->lpni_peer_net->lpn_peer);
1753                 best_gw->lpni_gw_seq++;
1754                 peer = best_gw->lpni_peer_net->lpn_peer;
1755         }
1756
1757         /*
1758          * Now that we selected the NI to use increment its sequence
1759          * number so the Round Robin algorithm will detect that it has
1760          * been used and pick the next NI.
1761          */
1762         best_ni->ni_seq++;
1763
1764 pick_peer:
1765         /*
1766          * At this point the best_ni is on a local network on which
1767          * the peer has a peer_ni as well
1768          */
1769         peer_net = lnet_peer_get_net_locked(peer,
1770                                             best_ni->ni_net->net_id);
1771         /*
1772          * peer_net is not available or the src_nid is explicitly defined
1773          * and the peer_net for that src_nid is unhealthy. find a route to
1774          * the destination nid.
1775          */
1776         if (!peer_net ||
1777             (src_nid != LNET_NID_ANY &&
1778              !lnet_is_peer_net_healthy_locked(peer_net))) {
1779                 best_gw = lnet_find_route_locked(best_ni->ni_net,
1780                                                  dst_nid,
1781                                                  rtr_nid);
1782                 /*
1783                  * if no route is found for that network then
1784                  * move onto the next peer_ni in the peer
1785                  */
1786                 if (!best_gw) {
1787                         lnet_net_unlock(cpt);
1788                         LCONSOLE_WARN("No route to peer from %s\n",
1789                                 libcfs_nid2str(best_ni->ni_nid));
1790                         return -EHOSTUNREACH;
1791                 }
1792
1793                 CDEBUG(D_NET, "Best route to %s via %s for %s %d\n",
1794                         libcfs_nid2str(dst_nid),
1795                         libcfs_nid2str(best_gw->lpni_nid),
1796                         lnet_msgtyp2str(msg->msg_type), msg->msg_len);
1797
1798                 routing2 = true;
1799                 /*
1800                  * RULE: Each node considers only the next-hop
1801                  *
1802                  * We're going to route the message, so change the peer to
1803                  * the router.
1804                  */
1805                 LASSERT(best_gw->lpni_peer_net);
1806                 LASSERT(best_gw->lpni_peer_net->lpn_peer);
1807                 peer = best_gw->lpni_peer_net->lpn_peer;
1808         } else if (!lnet_is_peer_net_healthy_locked(peer_net)) {
1809                 /*
1810                  * this peer_net is unhealthy but we still have an opportunity
1811                  * to find another peer_net that we can use
1812                  */
1813                 __u32 net_id = peer_net->lpn_net_id;
1814                 LCONSOLE_WARN("peer net %s unhealthy\n",
1815                               libcfs_net2str(net_id));
1816                 goto again;
1817         }
1818
1819         /*
1820          * Look at the peer NIs for the destination peer that connect
1821          * to the chosen net. If a peer_ni is preferred when using the
1822          * best_ni to communicate, we use that one. If there is no
1823          * preferred peer_ni, or there are multiple preferred peer_ni,
1824          * the available transmit credits are used. If the transmit
1825          * credits are equal, we round-robin over the peer_ni.
1826          */
1827         lpni = NULL;
1828         best_lpni_credits = INT_MIN;
1829         preferred = false;
1830         best_lpni = NULL;
1831         while ((lpni = lnet_get_next_peer_ni_locked(peer, peer_net, lpni))) {
1832                 /*
1833                  * if this peer ni is not healthy just skip it, no point in
1834                  * examining it further
1835                  */
1836                 if (!lnet_is_peer_ni_healthy_locked(lpni))
1837                         continue;
1838                 ni_is_pref = lnet_peer_is_pref_nid_locked(lpni,
1839                                                           best_ni->ni_nid);
1840
1841                 /* if this is a preferred peer use it */
1842                 if (!preferred && ni_is_pref) {
1843                         preferred = true;
1844                 } else if (preferred && !ni_is_pref) {
1845                         /*
1846                          * this is not the preferred peer so let's ignore
1847                          * it.
1848                          */
1849                         continue;
1850                 } else if (lpni->lpni_txcredits < best_lpni_credits) {
1851                         /*
1852                          * We already have a peer that has more credits
1853                          * available than this one. No need to consider
1854                          * this peer further.
1855                          */
1856                         continue;
1857                 } else if (lpni->lpni_txcredits == best_lpni_credits) {
1858                         /*
1859                          * The best peer found so far and the current peer
1860                          * have the same number of available credits let's
1861                          * make sure to select between them using Round
1862                          * Robin
1863                          */
1864                         if (best_lpni) {
1865                                 if (best_lpni->lpni_seq <= lpni->lpni_seq)
1866                                         continue;
1867                         }
1868                 }
1869
1870                 best_lpni = lpni;
1871                 best_lpni_credits = lpni->lpni_txcredits;
1872         }
1873
1874         /* if we still can't find a peer ni then we can't reach it */
1875         if (!best_lpni) {
1876                 __u32 net_id = (peer_net) ? peer_net->lpn_net_id :
1877                         LNET_NIDNET(dst_nid);
1878                 lnet_net_unlock(cpt);
1879                 LCONSOLE_WARN("no peer_ni found on peer net %s\n",
1880                                 libcfs_net2str(net_id));
1881                 return -EHOSTUNREACH;
1882         }
1883
1884
1885 send:
1886         /* Shortcut for loopback. */
1887         if (best_ni == the_lnet.ln_loni) {
1888                 /* No send credit hassles with LOLND */
1889                 lnet_ni_addref_locked(best_ni, cpt);
1890                 msg->msg_hdr.dest_nid = cpu_to_le64(best_ni->ni_nid);
1891                 if (!msg->msg_routing)
1892                         msg->msg_hdr.src_nid = cpu_to_le64(best_ni->ni_nid);
1893                 msg->msg_target.nid = best_ni->ni_nid;
1894                 lnet_msg_commit(msg, cpt);
1895                 msg->msg_txni = best_ni;
1896                 lnet_net_unlock(cpt);
1897
1898                 return LNET_CREDIT_OK;
1899         }
1900
1901         routing = routing || routing2;
1902
1903         /*
1904          * Increment sequence number of the peer selected so that we
1905          * pick the next one in Round Robin.
1906          */
1907         best_lpni->lpni_seq++;
1908
1909         /*
1910          * grab a reference on the peer_ni so it sticks around even if
1911          * we need to drop and relock the lnet_net_lock below.
1912          */
1913         lnet_peer_ni_addref_locked(best_lpni);
1914
1915         /*
1916          * Use lnet_cpt_of_nid() to determine the CPT used to commit the
1917          * message. This ensures that we get a CPT that is correct for
1918          * the NI when the NI has been restricted to a subset of all CPTs.
1919          * If the selected CPT differs from the one currently locked, we
1920          * must unlock and relock the lnet_net_lock(), and then check whether
1921          * the configuration has changed. We don't have a hold on the best_ni
1922          * yet, and it may have vanished.
1923          */
1924         cpt2 = lnet_cpt_of_nid_locked(best_lpni->lpni_nid, best_ni);
1925         if (cpt != cpt2) {
1926                 __u32 seq = lnet_get_dlc_seq_locked();
1927                 lnet_net_unlock(cpt);
1928                 cpt = cpt2;
1929                 lnet_net_lock(cpt);
1930                 if (seq != lnet_get_dlc_seq_locked()) {
1931                         lnet_peer_ni_decref_locked(best_lpni);
1932                         goto again;
1933                 }
1934         }
1935
1936         /*
1937          * store the best_lpni in the message right away to avoid having
1938          * to do the same operation under different conditions
1939          */
1940         msg->msg_txpeer = best_lpni;
1941         msg->msg_txni = best_ni;
1942
1943         /*
1944          * grab a reference for the best_ni since now it's in use in this
1945          * send. the reference will need to be dropped when the message is
1946          * finished in lnet_finalize()
1947          */
1948         lnet_ni_addref_locked(msg->msg_txni, cpt);
1949
1950         /*
1951          * Always set the target.nid to the best peer picked. Either the
1952          * nid will be one of the preconfigured NIDs, or the same NID as
1953          * what was originally set in the target or it will be the NID of
1954          * a router if this message should be routed
1955          */
1956         msg->msg_target.nid = msg->msg_txpeer->lpni_nid;
1957
1958         /*
1959          * lnet_msg_commit assigns the correct cpt to the message, which
1960          * is used to decrement the correct refcount on the ni when it's
1961          * time to return the credits
1962          */
1963         lnet_msg_commit(msg, cpt);
1964
1965         /*
1966          * If we are routing the message then we don't need to overwrite
1967          * the src_nid since it would've been set at the origin. Otherwise
1968          * we are the originator so we need to set it.
1969          */
1970         if (!msg->msg_routing)
1971                 msg->msg_hdr.src_nid = cpu_to_le64(msg->msg_txni->ni_nid);
1972
1973         if (routing) {
1974                 msg->msg_target_is_router = 1;
1975                 msg->msg_target.pid = LNET_PID_LUSTRE;
1976                 /*
1977                  * since we're routing we want to ensure that the
1978                  * msg_hdr.dest_nid is set to the final destination. When
1979                  * the router receives this message it knows how to route
1980                  * it.
1981                  */
1982                 msg->msg_hdr.dest_nid =
1983                         cpu_to_le64(final_dst ? final_dst->lpni_nid : dst_nid);
1984         } else {
1985                 /*
1986                  * if we're not routing set the dest_nid to the best peer
1987                  * ni that we picked earlier in the algorithm.
1988                  */
1989                 msg->msg_hdr.dest_nid = cpu_to_le64(msg->msg_txpeer->lpni_nid);
1990         }
1991
1992         rc = lnet_post_send_locked(msg, 0);
1993
1994         if (!rc)
1995                 CDEBUG(D_NET, "TRACE: %s(%s:%s) -> %s(%s:%s) : %s\n",
1996                        libcfs_nid2str(msg->msg_hdr.src_nid),
1997                        libcfs_nid2str(msg->msg_txni->ni_nid),
1998                        libcfs_nid2str(src_nid),
1999                        libcfs_nid2str(msg->msg_hdr.dest_nid),
2000                        libcfs_nid2str(dst_nid),
2001                        libcfs_nid2str(msg->msg_txpeer->lpni_nid),
2002                        lnet_msgtyp2str(msg->msg_type));
2003
2004         lnet_net_unlock(cpt);
2005
2006         return rc;
2007 }
2008
2009 int
2010 lnet_send(lnet_nid_t src_nid, struct lnet_msg *msg, lnet_nid_t rtr_nid)
2011 {
2012         lnet_nid_t              dst_nid = msg->msg_target.nid;
2013         int                     rc;
2014
2015         /*
2016          * NB: rtr_nid is set to LNET_NID_ANY for all current use-cases,
2017          * but we might want to use pre-determined router for ACK/REPLY
2018          * in the future
2019          */
2020         /* NB: ni != NULL == interface pre-determined (ACK/REPLY) */
2021         LASSERT (msg->msg_txpeer == NULL);
2022         LASSERT (!msg->msg_sending);
2023         LASSERT (!msg->msg_target_is_router);
2024         LASSERT (!msg->msg_receiving);
2025
2026         msg->msg_sending = 1;
2027
2028         LASSERT(!msg->msg_tx_committed);
2029
2030         rc = lnet_select_pathway(src_nid, dst_nid, msg, rtr_nid);
2031         if (rc < 0)
2032                 return rc;
2033
2034         if (rc == LNET_CREDIT_OK)
2035                 lnet_ni_send(msg->msg_txni, msg);
2036
2037         /* rc == LNET_CREDIT_OK or LNET_CREDIT_WAIT or LNET_DC_WAIT */
2038         return 0;
2039 }
2040
2041 void
2042 lnet_drop_message(struct lnet_ni *ni, int cpt, void *private, unsigned int nob)
2043 {
2044         lnet_net_lock(cpt);
2045         the_lnet.ln_counters[cpt]->drop_count++;
2046         the_lnet.ln_counters[cpt]->drop_length += nob;
2047         lnet_net_unlock(cpt);
2048
2049         lnet_ni_recv(ni, private, NULL, 0, 0, 0, nob);
2050 }
2051
2052 static void
2053 lnet_recv_put(struct lnet_ni *ni, struct lnet_msg *msg)
2054 {
2055         struct lnet_hdr *hdr = &msg->msg_hdr;
2056
2057         if (msg->msg_wanted != 0)
2058                 lnet_setpayloadbuffer(msg);
2059
2060         lnet_build_msg_event(msg, LNET_EVENT_PUT);
2061
2062         /* Must I ACK?  If so I'll grab the ack_wmd out of the header and put
2063          * it back into the ACK during lnet_finalize() */
2064         msg->msg_ack = (!lnet_is_wire_handle_none(&hdr->msg.put.ack_wmd) &&
2065                         (msg->msg_md->md_options & LNET_MD_ACK_DISABLE) == 0);
2066
2067         lnet_ni_recv(ni, msg->msg_private, msg, msg->msg_rx_delayed,
2068                      msg->msg_offset, msg->msg_wanted, hdr->payload_length);
2069 }
2070
2071 static int
2072 lnet_parse_put(struct lnet_ni *ni, struct lnet_msg *msg)
2073 {
2074         struct lnet_hdr         *hdr = &msg->msg_hdr;
2075         struct lnet_match_info  info;
2076         int                     rc;
2077         bool                    ready_delay;
2078
2079         /* Convert put fields to host byte order */
2080         hdr->msg.put.match_bits = le64_to_cpu(hdr->msg.put.match_bits);
2081         hdr->msg.put.ptl_index  = le32_to_cpu(hdr->msg.put.ptl_index);
2082         hdr->msg.put.offset     = le32_to_cpu(hdr->msg.put.offset);
2083
2084         /* Primary peer NID. */
2085         info.mi_id.nid  = msg->msg_initiator;
2086         info.mi_id.pid  = hdr->src_pid;
2087         info.mi_opc     = LNET_MD_OP_PUT;
2088         info.mi_portal  = hdr->msg.put.ptl_index;
2089         info.mi_rlength = hdr->payload_length;
2090         info.mi_roffset = hdr->msg.put.offset;
2091         info.mi_mbits   = hdr->msg.put.match_bits;
2092         info.mi_cpt     = lnet_cpt_of_nid(msg->msg_rxpeer->lpni_nid, ni);
2093
2094         msg->msg_rx_ready_delay = ni->ni_net->net_lnd->lnd_eager_recv == NULL;
2095         ready_delay = msg->msg_rx_ready_delay;
2096
2097  again:
2098         rc = lnet_ptl_match_md(&info, msg);
2099         switch (rc) {
2100         default:
2101                 LBUG();
2102
2103         case LNET_MATCHMD_OK:
2104                 lnet_recv_put(ni, msg);
2105                 return 0;
2106
2107         case LNET_MATCHMD_NONE:
2108                 if (ready_delay)
2109                         /* no eager_recv or has already called it, should
2110                          * have been attached on delayed list */
2111                         return 0;
2112
2113                 rc = lnet_ni_eager_recv(ni, msg);
2114                 if (rc == 0) {
2115                         ready_delay = true;
2116                         goto again;
2117                 }
2118                 /* fall through */
2119
2120         case LNET_MATCHMD_DROP:
2121                 CNETERR("Dropping PUT from %s portal %d match %llu"
2122                         " offset %d length %d: %d\n",
2123                         libcfs_id2str(info.mi_id), info.mi_portal,
2124                         info.mi_mbits, info.mi_roffset, info.mi_rlength, rc);
2125
2126                 return -ENOENT; /* -ve: OK but no match */
2127         }
2128 }
2129
2130 static int
2131 lnet_parse_get(struct lnet_ni *ni, struct lnet_msg *msg, int rdma_get)
2132 {
2133         struct lnet_match_info info;
2134         struct lnet_hdr *hdr = &msg->msg_hdr;
2135         struct lnet_process_id source_id;
2136         struct lnet_handle_wire reply_wmd;
2137         int rc;
2138
2139         /* Convert get fields to host byte order */
2140         hdr->msg.get.match_bits   = le64_to_cpu(hdr->msg.get.match_bits);
2141         hdr->msg.get.ptl_index    = le32_to_cpu(hdr->msg.get.ptl_index);
2142         hdr->msg.get.sink_length  = le32_to_cpu(hdr->msg.get.sink_length);
2143         hdr->msg.get.src_offset   = le32_to_cpu(hdr->msg.get.src_offset);
2144
2145         source_id.nid = hdr->src_nid;
2146         source_id.pid = hdr->src_pid;
2147         /* Primary peer NID */
2148         info.mi_id.nid  = msg->msg_initiator;
2149         info.mi_id.pid  = hdr->src_pid;
2150         info.mi_opc     = LNET_MD_OP_GET;
2151         info.mi_portal  = hdr->msg.get.ptl_index;
2152         info.mi_rlength = hdr->msg.get.sink_length;
2153         info.mi_roffset = hdr->msg.get.src_offset;
2154         info.mi_mbits   = hdr->msg.get.match_bits;
2155         info.mi_cpt     = lnet_cpt_of_nid(msg->msg_rxpeer->lpni_nid, ni);
2156
2157         rc = lnet_ptl_match_md(&info, msg);
2158         if (rc == LNET_MATCHMD_DROP) {
2159                 CNETERR("Dropping GET from %s portal %d match %llu"
2160                         " offset %d length %d\n",
2161                         libcfs_id2str(info.mi_id), info.mi_portal,
2162                         info.mi_mbits, info.mi_roffset, info.mi_rlength);
2163                 return -ENOENT; /* -ve: OK but no match */
2164         }
2165
2166         LASSERT(rc == LNET_MATCHMD_OK);
2167
2168         lnet_build_msg_event(msg, LNET_EVENT_GET);
2169
2170         reply_wmd = hdr->msg.get.return_wmd;
2171
2172         lnet_prep_send(msg, LNET_MSG_REPLY, source_id,
2173                        msg->msg_offset, msg->msg_wanted);
2174
2175         msg->msg_hdr.msg.reply.dst_wmd = reply_wmd;
2176
2177         if (rdma_get) {
2178                 /* The LND completes the REPLY from her recv procedure */
2179                 lnet_ni_recv(ni, msg->msg_private, msg, 0,
2180                              msg->msg_offset, msg->msg_len, msg->msg_len);
2181                 return 0;
2182         }
2183
2184         lnet_ni_recv(ni, msg->msg_private, NULL, 0, 0, 0, 0);
2185         msg->msg_receiving = 0;
2186
2187         rc = lnet_send(ni->ni_nid, msg, LNET_NID_ANY);
2188         if (rc < 0) {
2189                 /* didn't get as far as lnet_ni_send() */
2190                 CERROR("%s: Unable to send REPLY for GET from %s: %d\n",
2191                        libcfs_nid2str(ni->ni_nid),
2192                        libcfs_id2str(info.mi_id), rc);
2193
2194                 lnet_finalize(msg, rc);
2195         }
2196
2197         return 0;
2198 }
2199
2200 static int
2201 lnet_parse_reply(struct lnet_ni *ni, struct lnet_msg *msg)
2202 {
2203         void             *private = msg->msg_private;
2204         struct lnet_hdr  *hdr = &msg->msg_hdr;
2205         struct lnet_process_id src = {0};
2206         struct lnet_libmd        *md;
2207         int               rlength;
2208         int               mlength;
2209         int                     cpt;
2210
2211         cpt = lnet_cpt_of_cookie(hdr->msg.reply.dst_wmd.wh_object_cookie);
2212         lnet_res_lock(cpt);
2213
2214         src.nid = hdr->src_nid;
2215         src.pid = hdr->src_pid;
2216
2217         /* NB handles only looked up by creator (no flips) */
2218         md = lnet_wire_handle2md(&hdr->msg.reply.dst_wmd);
2219         if (md == NULL || md->md_threshold == 0 || md->md_me != NULL) {
2220                 CNETERR("%s: Dropping REPLY from %s for %s "
2221                         "MD %#llx.%#llx\n",
2222                         libcfs_nid2str(ni->ni_nid), libcfs_id2str(src),
2223                         (md == NULL) ? "invalid" : "inactive",
2224                         hdr->msg.reply.dst_wmd.wh_interface_cookie,
2225                         hdr->msg.reply.dst_wmd.wh_object_cookie);
2226                 if (md != NULL && md->md_me != NULL)
2227                         CERROR("REPLY MD also attached to portal %d\n",
2228                                md->md_me->me_portal);
2229
2230                 lnet_res_unlock(cpt);
2231                 return -ENOENT; /* -ve: OK but no match */
2232         }
2233
2234         LASSERT(md->md_offset == 0);
2235
2236         rlength = hdr->payload_length;
2237         mlength = MIN(rlength, (int)md->md_length);
2238
2239         if (mlength < rlength &&
2240             (md->md_options & LNET_MD_TRUNCATE) == 0) {
2241                 CNETERR("%s: Dropping REPLY from %s length %d "
2242                         "for MD %#llx would overflow (%d)\n",
2243                         libcfs_nid2str(ni->ni_nid), libcfs_id2str(src),
2244                         rlength, hdr->msg.reply.dst_wmd.wh_object_cookie,
2245                         mlength);
2246                 lnet_res_unlock(cpt);
2247                 return -ENOENT; /* -ve: OK but no match */
2248         }
2249
2250         CDEBUG(D_NET, "%s: Reply from %s of length %d/%d into md %#llx\n",
2251                libcfs_nid2str(ni->ni_nid), libcfs_id2str(src),
2252                mlength, rlength, hdr->msg.reply.dst_wmd.wh_object_cookie);
2253
2254         lnet_msg_attach_md(msg, md, 0, mlength);
2255
2256         if (mlength != 0)
2257                 lnet_setpayloadbuffer(msg);
2258
2259         lnet_res_unlock(cpt);
2260
2261         lnet_build_msg_event(msg, LNET_EVENT_REPLY);
2262
2263         lnet_ni_recv(ni, private, msg, 0, 0, mlength, rlength);
2264         return 0;
2265 }
2266
2267 static int
2268 lnet_parse_ack(struct lnet_ni *ni, struct lnet_msg *msg)
2269 {
2270         struct lnet_hdr  *hdr = &msg->msg_hdr;
2271         struct lnet_process_id src = {0};
2272         struct lnet_libmd        *md;
2273         int                     cpt;
2274
2275         src.nid = hdr->src_nid;
2276         src.pid = hdr->src_pid;
2277
2278         /* Convert ack fields to host byte order */
2279         hdr->msg.ack.match_bits = le64_to_cpu(hdr->msg.ack.match_bits);
2280         hdr->msg.ack.mlength = le32_to_cpu(hdr->msg.ack.mlength);
2281
2282         cpt = lnet_cpt_of_cookie(hdr->msg.ack.dst_wmd.wh_object_cookie);
2283         lnet_res_lock(cpt);
2284
2285         /* NB handles only looked up by creator (no flips) */
2286         md = lnet_wire_handle2md(&hdr->msg.ack.dst_wmd);
2287         if (md == NULL || md->md_threshold == 0 || md->md_me != NULL) {
2288                 /* Don't moan; this is expected */
2289                 CDEBUG(D_NET,
2290                        "%s: Dropping ACK from %s to %s MD %#llx.%#llx\n",
2291                        libcfs_nid2str(ni->ni_nid), libcfs_id2str(src),
2292                        (md == NULL) ? "invalid" : "inactive",
2293                        hdr->msg.ack.dst_wmd.wh_interface_cookie,
2294                        hdr->msg.ack.dst_wmd.wh_object_cookie);
2295                 if (md != NULL && md->md_me != NULL)
2296                         CERROR("Source MD also attached to portal %d\n",
2297                                md->md_me->me_portal);
2298
2299                 lnet_res_unlock(cpt);
2300                 return -ENOENT;                  /* -ve! */
2301         }
2302
2303         CDEBUG(D_NET, "%s: ACK from %s into md %#llx\n",
2304                libcfs_nid2str(ni->ni_nid), libcfs_id2str(src),
2305                hdr->msg.ack.dst_wmd.wh_object_cookie);
2306
2307         lnet_msg_attach_md(msg, md, 0, 0);
2308
2309         lnet_res_unlock(cpt);
2310
2311         lnet_build_msg_event(msg, LNET_EVENT_ACK);
2312
2313         lnet_ni_recv(ni, msg->msg_private, msg, 0, 0, 0, msg->msg_len);
2314         return 0;
2315 }
2316
2317 /**
2318  * \retval LNET_CREDIT_OK       If \a msg is forwarded
2319  * \retval LNET_CREDIT_WAIT     If \a msg is blocked because w/o buffer
2320  * \retval -ve                  error code
2321  */
2322 int
2323 lnet_parse_forward_locked(struct lnet_ni *ni, struct lnet_msg *msg)
2324 {
2325         int     rc = 0;
2326
2327         if (!the_lnet.ln_routing)
2328                 return -ECANCELED;
2329
2330         if (msg->msg_rxpeer->lpni_rtrcredits <= 0 ||
2331             lnet_msg2bufpool(msg)->rbp_credits <= 0) {
2332                 if (ni->ni_net->net_lnd->lnd_eager_recv == NULL) {
2333                         msg->msg_rx_ready_delay = 1;
2334                 } else {
2335                         lnet_net_unlock(msg->msg_rx_cpt);
2336                         rc = lnet_ni_eager_recv(ni, msg);
2337                         lnet_net_lock(msg->msg_rx_cpt);
2338                 }
2339         }
2340
2341         if (rc == 0)
2342                 rc = lnet_post_routed_recv_locked(msg, 0);
2343         return rc;
2344 }
2345
2346 int
2347 lnet_parse_local(struct lnet_ni *ni, struct lnet_msg *msg)
2348 {
2349         int     rc;
2350
2351         switch (msg->msg_type) {
2352         case LNET_MSG_ACK:
2353                 rc = lnet_parse_ack(ni, msg);
2354                 break;
2355         case LNET_MSG_PUT:
2356                 rc = lnet_parse_put(ni, msg);
2357                 break;
2358         case LNET_MSG_GET:
2359                 rc = lnet_parse_get(ni, msg, msg->msg_rdma_get);
2360                 break;
2361         case LNET_MSG_REPLY:
2362                 rc = lnet_parse_reply(ni, msg);
2363                 break;
2364         default: /* prevent an unused label if !kernel */
2365                 LASSERT(0);
2366                 return -EPROTO;
2367         }
2368
2369         LASSERT(rc == 0 || rc == -ENOENT);
2370         return rc;
2371 }
2372
2373 char *
2374 lnet_msgtyp2str (int type)
2375 {
2376         switch (type) {
2377         case LNET_MSG_ACK:
2378                 return ("ACK");
2379         case LNET_MSG_PUT:
2380                 return ("PUT");
2381         case LNET_MSG_GET:
2382                 return ("GET");
2383         case LNET_MSG_REPLY:
2384                 return ("REPLY");
2385         case LNET_MSG_HELLO:
2386                 return ("HELLO");
2387         default:
2388                 return ("<UNKNOWN>");
2389         }
2390 }
2391
2392 void
2393 lnet_print_hdr(struct lnet_hdr *hdr)
2394 {
2395         struct lnet_process_id src = {
2396                 .nid = hdr->src_nid,
2397                 .pid = hdr->src_pid,
2398         };
2399         struct lnet_process_id dst = {
2400                 .nid = hdr->dest_nid,
2401                 .pid = hdr->dest_pid,
2402         };
2403         char *type_str = lnet_msgtyp2str(hdr->type);
2404
2405         CWARN("P3 Header at %p of type %s\n", hdr, type_str);
2406         CWARN("    From %s\n", libcfs_id2str(src));
2407         CWARN("    To   %s\n", libcfs_id2str(dst));
2408
2409         switch (hdr->type) {
2410         default:
2411                 break;
2412
2413         case LNET_MSG_PUT:
2414                 CWARN("    Ptl index %d, ack md %#llx.%#llx, "
2415                       "match bits %llu\n",
2416                       hdr->msg.put.ptl_index,
2417                       hdr->msg.put.ack_wmd.wh_interface_cookie,
2418                       hdr->msg.put.ack_wmd.wh_object_cookie,
2419                       hdr->msg.put.match_bits);
2420                 CWARN("    Length %d, offset %d, hdr data %#llx\n",
2421                       hdr->payload_length, hdr->msg.put.offset,
2422                       hdr->msg.put.hdr_data);
2423                 break;
2424
2425         case LNET_MSG_GET:
2426                 CWARN("    Ptl index %d, return md %#llx.%#llx, "
2427                       "match bits %llu\n", hdr->msg.get.ptl_index,
2428                       hdr->msg.get.return_wmd.wh_interface_cookie,
2429                       hdr->msg.get.return_wmd.wh_object_cookie,
2430                       hdr->msg.get.match_bits);
2431                 CWARN("    Length %d, src offset %d\n",
2432                       hdr->msg.get.sink_length,
2433                       hdr->msg.get.src_offset);
2434                 break;
2435
2436         case LNET_MSG_ACK:
2437                 CWARN("    dst md %#llx.%#llx, "
2438                       "manipulated length %d\n",
2439                       hdr->msg.ack.dst_wmd.wh_interface_cookie,
2440                       hdr->msg.ack.dst_wmd.wh_object_cookie,
2441                       hdr->msg.ack.mlength);
2442                 break;
2443
2444         case LNET_MSG_REPLY:
2445                 CWARN("    dst md %#llx.%#llx, "
2446                       "length %d\n",
2447                       hdr->msg.reply.dst_wmd.wh_interface_cookie,
2448                       hdr->msg.reply.dst_wmd.wh_object_cookie,
2449                       hdr->payload_length);
2450         }
2451
2452 }
2453
2454 int
2455 lnet_parse(struct lnet_ni *ni, struct lnet_hdr *hdr, lnet_nid_t from_nid,
2456            void *private, int rdma_req)
2457 {
2458         int             rc = 0;
2459         int             cpt;
2460         int             for_me;
2461         struct lnet_msg *msg;
2462         lnet_pid_t     dest_pid;
2463         lnet_nid_t     dest_nid;
2464         lnet_nid_t     src_nid;
2465         struct lnet_peer_ni *lpni;
2466         __u32          payload_length;
2467         __u32          type;
2468
2469         LASSERT (!in_interrupt ());
2470
2471         type = le32_to_cpu(hdr->type);
2472         src_nid = le64_to_cpu(hdr->src_nid);
2473         dest_nid = le64_to_cpu(hdr->dest_nid);
2474         dest_pid = le32_to_cpu(hdr->dest_pid);
2475         payload_length = le32_to_cpu(hdr->payload_length);
2476
2477         for_me = (ni->ni_nid == dest_nid);
2478         cpt = lnet_cpt_of_nid(from_nid, ni);
2479
2480         CDEBUG(D_NET, "TRACE: %s(%s) <- %s : %s - %s\n",
2481                 libcfs_nid2str(dest_nid),
2482                 libcfs_nid2str(ni->ni_nid),
2483                 libcfs_nid2str(src_nid),
2484                 lnet_msgtyp2str(type),
2485                 (for_me) ? "for me" : "routed");
2486
2487         switch (type) {
2488         case LNET_MSG_ACK:
2489         case LNET_MSG_GET:
2490                 if (payload_length > 0) {
2491                         CERROR("%s, src %s: bad %s payload %d (0 expected)\n",
2492                                libcfs_nid2str(from_nid),
2493                                libcfs_nid2str(src_nid),
2494                                lnet_msgtyp2str(type), payload_length);
2495                         return -EPROTO;
2496                 }
2497                 break;
2498
2499         case LNET_MSG_PUT:
2500         case LNET_MSG_REPLY:
2501                 if (payload_length >
2502                     (__u32)(for_me ? LNET_MAX_PAYLOAD : LNET_MTU)) {
2503                         CERROR("%s, src %s: bad %s payload %d "
2504                                "(%d max expected)\n",
2505                                libcfs_nid2str(from_nid),
2506                                libcfs_nid2str(src_nid),
2507                                lnet_msgtyp2str(type),
2508                                payload_length,
2509                                for_me ? LNET_MAX_PAYLOAD : LNET_MTU);
2510                         return -EPROTO;
2511                 }
2512                 break;
2513
2514         default:
2515                 CERROR("%s, src %s: Bad message type 0x%x\n",
2516                        libcfs_nid2str(from_nid),
2517                        libcfs_nid2str(src_nid), type);
2518                 return -EPROTO;
2519         }
2520
2521         if (the_lnet.ln_routing &&
2522             ni->ni_last_alive != ktime_get_real_seconds()) {
2523                 /* NB: so far here is the only place to set NI status to "up */
2524                 lnet_ni_lock(ni);
2525                 ni->ni_last_alive = ktime_get_real_seconds();
2526                 if (ni->ni_status != NULL &&
2527                     ni->ni_status->ns_status == LNET_NI_STATUS_DOWN)
2528                         ni->ni_status->ns_status = LNET_NI_STATUS_UP;
2529                 lnet_ni_unlock(ni);
2530         }
2531
2532         /* Regard a bad destination NID as a protocol error.  Senders should
2533          * know what they're doing; if they don't they're misconfigured, buggy
2534          * or malicious so we chop them off at the knees :) */
2535
2536         if (!for_me) {
2537                 if (LNET_NIDNET(dest_nid) == LNET_NIDNET(ni->ni_nid)) {
2538                         /* should have gone direct */
2539                         CERROR("%s, src %s: Bad dest nid %s "
2540                                "(should have been sent direct)\n",
2541                                 libcfs_nid2str(from_nid),
2542                                 libcfs_nid2str(src_nid),
2543                                 libcfs_nid2str(dest_nid));
2544                         return -EPROTO;
2545                 }
2546
2547                 if (lnet_islocalnid(dest_nid)) {
2548                         /* dest is another local NI; sender should have used
2549                          * this node's NID on its own network */
2550                         CERROR("%s, src %s: Bad dest nid %s "
2551                                "(it's my nid but on a different network)\n",
2552                                 libcfs_nid2str(from_nid),
2553                                 libcfs_nid2str(src_nid),
2554                                 libcfs_nid2str(dest_nid));
2555                         return -EPROTO;
2556                 }
2557
2558                 if (rdma_req && type == LNET_MSG_GET) {
2559                         CERROR("%s, src %s: Bad optimized GET for %s "
2560                                "(final destination must be me)\n",
2561                                 libcfs_nid2str(from_nid),
2562                                 libcfs_nid2str(src_nid),
2563                                 libcfs_nid2str(dest_nid));
2564                         return -EPROTO;
2565                 }
2566
2567                 if (!the_lnet.ln_routing) {
2568                         CERROR("%s, src %s: Dropping message for %s "
2569                                "(routing not enabled)\n",
2570                                 libcfs_nid2str(from_nid),
2571                                 libcfs_nid2str(src_nid),
2572                                 libcfs_nid2str(dest_nid));
2573                         goto drop;
2574                 }
2575         }
2576
2577         /* Message looks OK; we're not going to return an error, so we MUST
2578          * call back lnd_recv() come what may... */
2579
2580         if (!list_empty(&the_lnet.ln_test_peers) &&     /* normally we don't */
2581             fail_peer(src_nid, 0)) {                    /* shall we now? */
2582                 CERROR("%s, src %s: Dropping %s to simulate failure\n",
2583                        libcfs_nid2str(from_nid), libcfs_nid2str(src_nid),
2584                        lnet_msgtyp2str(type));
2585                 goto drop;
2586         }
2587
2588         if (!list_empty(&the_lnet.ln_drop_rules) &&
2589             lnet_drop_rule_match(hdr)) {
2590                 CDEBUG(D_NET, "%s, src %s, dst %s: Dropping %s to simulate"
2591                               "silent message loss\n",
2592                        libcfs_nid2str(from_nid), libcfs_nid2str(src_nid),
2593                        libcfs_nid2str(dest_nid), lnet_msgtyp2str(type));
2594                 goto drop;
2595         }
2596
2597
2598         msg = lnet_msg_alloc();
2599         if (msg == NULL) {
2600                 CERROR("%s, src %s: Dropping %s (out of memory)\n",
2601                        libcfs_nid2str(from_nid), libcfs_nid2str(src_nid),
2602                        lnet_msgtyp2str(type));
2603                 goto drop;
2604         }
2605
2606         /* msg zeroed in lnet_msg_alloc; i.e. flags all clear,
2607          * pointers NULL etc */
2608
2609         msg->msg_type = type;
2610         msg->msg_private = private;
2611         msg->msg_receiving = 1;
2612         msg->msg_rdma_get = rdma_req;
2613         msg->msg_len = msg->msg_wanted = payload_length;
2614         msg->msg_offset = 0;
2615         msg->msg_hdr = *hdr;
2616         /* for building message event */
2617         msg->msg_from = from_nid;
2618         if (!for_me) {
2619                 msg->msg_target.pid     = dest_pid;
2620                 msg->msg_target.nid     = dest_nid;
2621                 msg->msg_routing        = 1;
2622
2623         } else {
2624                 /* convert common msg->hdr fields to host byteorder */
2625                 msg->msg_hdr.type       = type;
2626                 msg->msg_hdr.src_nid    = src_nid;
2627                 msg->msg_hdr.src_pid    = le32_to_cpu(msg->msg_hdr.src_pid);
2628                 msg->msg_hdr.dest_nid   = dest_nid;
2629                 msg->msg_hdr.dest_pid   = dest_pid;
2630                 msg->msg_hdr.payload_length = payload_length;
2631         }
2632
2633         lnet_net_lock(cpt);
2634         lpni = lnet_nid2peerni_locked(from_nid, ni->ni_nid, cpt);
2635         if (IS_ERR(lpni)) {
2636                 lnet_net_unlock(cpt);
2637                 CERROR("%s, src %s: Dropping %s "
2638                        "(error %ld looking up sender)\n",
2639                        libcfs_nid2str(from_nid), libcfs_nid2str(src_nid),
2640                        lnet_msgtyp2str(type), PTR_ERR(lpni));
2641                 lnet_msg_free(msg);
2642                 if (rc == -ESHUTDOWN)
2643                         /* We are shutting down.  Don't do anything more */
2644                         return 0;
2645                 goto drop;
2646         }
2647         msg->msg_rxpeer = lpni;
2648         msg->msg_rxni = ni;
2649         lnet_ni_addref_locked(ni, cpt);
2650         /* Multi-Rail: Primary NID of source. */
2651         msg->msg_initiator = lnet_peer_primary_nid_locked(src_nid);
2652
2653         if (lnet_isrouter(msg->msg_rxpeer)) {
2654                 lnet_peer_set_alive(msg->msg_rxpeer);
2655                 if (avoid_asym_router_failure &&
2656                     LNET_NIDNET(src_nid) != LNET_NIDNET(from_nid)) {
2657                         /* received a remote message from router, update
2658                          * remote NI status on this router.
2659                          * NB: multi-hop routed message will be ignored.
2660                          */
2661                         lnet_router_ni_update_locked(msg->msg_rxpeer,
2662                                                      LNET_NIDNET(src_nid));
2663                 }
2664         }
2665
2666         lnet_msg_commit(msg, cpt);
2667
2668         /* message delay simulation */
2669         if (unlikely(!list_empty(&the_lnet.ln_delay_rules) &&
2670                      lnet_delay_rule_match_locked(hdr, msg))) {
2671                 lnet_net_unlock(cpt);
2672                 return 0;
2673         }
2674
2675         if (!for_me) {
2676                 rc = lnet_parse_forward_locked(ni, msg);
2677                 lnet_net_unlock(cpt);
2678
2679                 if (rc < 0)
2680                         goto free_drop;
2681
2682                 if (rc == LNET_CREDIT_OK) {
2683                         lnet_ni_recv(ni, msg->msg_private, msg, 0,
2684                                      0, payload_length, payload_length);
2685                 }
2686                 return 0;
2687         }
2688
2689         lnet_net_unlock(cpt);
2690
2691         rc = lnet_parse_local(ni, msg);
2692         if (rc != 0)
2693                 goto free_drop;
2694         return 0;
2695
2696  free_drop:
2697         LASSERT(msg->msg_md == NULL);
2698         lnet_finalize(msg, rc);
2699
2700  drop:
2701         lnet_drop_message(ni, cpt, private, payload_length);
2702         return 0;
2703 }
2704 EXPORT_SYMBOL(lnet_parse);
2705
2706 void
2707 lnet_drop_delayed_msg_list(struct list_head *head, char *reason)
2708 {
2709         while (!list_empty(head)) {
2710                 struct lnet_process_id id = {0};
2711                 struct lnet_msg *msg;
2712
2713                 msg = list_entry(head->next, struct lnet_msg, msg_list);
2714                 list_del(&msg->msg_list);
2715
2716                 id.nid = msg->msg_hdr.src_nid;
2717                 id.pid = msg->msg_hdr.src_pid;
2718
2719                 LASSERT(msg->msg_md == NULL);
2720                 LASSERT(msg->msg_rx_delayed);
2721                 LASSERT(msg->msg_rxpeer != NULL);
2722                 LASSERT(msg->msg_hdr.type == LNET_MSG_PUT);
2723
2724                 CWARN("Dropping delayed PUT from %s portal %d match %llu"
2725                       " offset %d length %d: %s\n",
2726                       libcfs_id2str(id),
2727                       msg->msg_hdr.msg.put.ptl_index,
2728                       msg->msg_hdr.msg.put.match_bits,
2729                       msg->msg_hdr.msg.put.offset,
2730                       msg->msg_hdr.payload_length, reason);
2731
2732                 /* NB I can't drop msg's ref on msg_rxpeer until after I've
2733                  * called lnet_drop_message(), so I just hang onto msg as well
2734                  * until that's done */
2735
2736                 lnet_drop_message(msg->msg_rxni, msg->msg_rx_cpt,
2737                                   msg->msg_private, msg->msg_len);
2738                 /*
2739                  * NB: message will not generate event because w/o attached MD,
2740                  * but we still should give error code so lnet_msg_decommit()
2741                  * can skip counters operations and other checks.
2742                  */
2743                 lnet_finalize(msg, -ENOENT);
2744         }
2745 }
2746
2747 void
2748 lnet_recv_delayed_msg_list(struct list_head *head)
2749 {
2750         while (!list_empty(head)) {
2751                 struct lnet_msg *msg;
2752                 struct lnet_process_id id;
2753
2754                 msg = list_entry(head->next, struct lnet_msg, msg_list);
2755                 list_del(&msg->msg_list);
2756
2757                 /* md won't disappear under me, since each msg
2758                  * holds a ref on it */
2759
2760                 id.nid = msg->msg_hdr.src_nid;
2761                 id.pid = msg->msg_hdr.src_pid;
2762
2763                 LASSERT(msg->msg_rx_delayed);
2764                 LASSERT(msg->msg_md != NULL);
2765                 LASSERT(msg->msg_rxpeer != NULL);
2766                 LASSERT(msg->msg_rxni != NULL);
2767                 LASSERT(msg->msg_hdr.type == LNET_MSG_PUT);
2768
2769                 CDEBUG(D_NET, "Resuming delayed PUT from %s portal %d "
2770                        "match %llu offset %d length %d.\n",
2771                         libcfs_id2str(id), msg->msg_hdr.msg.put.ptl_index,
2772                         msg->msg_hdr.msg.put.match_bits,
2773                         msg->msg_hdr.msg.put.offset,
2774                         msg->msg_hdr.payload_length);
2775
2776                 lnet_recv_put(msg->msg_rxni, msg);
2777         }
2778 }
2779
2780 /**
2781  * Initiate an asynchronous PUT operation.
2782  *
2783  * There are several events associated with a PUT: completion of the send on
2784  * the initiator node (LNET_EVENT_SEND), and when the send completes
2785  * successfully, the receipt of an acknowledgment (LNET_EVENT_ACK) indicating
2786  * that the operation was accepted by the target. The event LNET_EVENT_PUT is
2787  * used at the target node to indicate the completion of incoming data
2788  * delivery.
2789  *
2790  * The local events will be logged in the EQ associated with the MD pointed to
2791  * by \a mdh handle. Using a MD without an associated EQ results in these
2792  * events being discarded. In this case, the caller must have another
2793  * mechanism (e.g., a higher level protocol) for determining when it is safe
2794  * to modify the memory region associated with the MD.
2795  *
2796  * Note that LNet does not guarantee the order of LNET_EVENT_SEND and
2797  * LNET_EVENT_ACK, though intuitively ACK should happen after SEND.
2798  *
2799  * \param self Indicates the NID of a local interface through which to send
2800  * the PUT request. Use LNET_NID_ANY to let LNet choose one by itself.
2801  * \param mdh A handle for the MD that describes the memory to be sent. The MD
2802  * must be "free floating" (See LNetMDBind()).
2803  * \param ack Controls whether an acknowledgment is requested.
2804  * Acknowledgments are only sent when they are requested by the initiating
2805  * process and the target MD enables them.
2806  * \param target A process identifier for the target process.
2807  * \param portal The index in the \a target's portal table.
2808  * \param match_bits The match bits to use for MD selection at the target
2809  * process.
2810  * \param offset The offset into the target MD (only used when the target
2811  * MD has the LNET_MD_MANAGE_REMOTE option set).
2812  * \param hdr_data 64 bits of user data that can be included in the message
2813  * header. This data is written to an event queue entry at the target if an
2814  * EQ is present on the matching MD.
2815  *
2816  * \retval  0      Success, and only in this case events will be generated
2817  * and logged to EQ (if it exists).
2818  * \retval -EIO    Simulated failure.
2819  * \retval -ENOMEM Memory allocation failure.
2820  * \retval -ENOENT Invalid MD object.
2821  *
2822  * \see struct lnet_event::hdr_data and lnet_event_kind_t.
2823  */
2824 int
2825 LNetPut(lnet_nid_t self, struct lnet_handle_md mdh, enum lnet_ack_req ack,
2826         struct lnet_process_id target, unsigned int portal,
2827         __u64 match_bits, unsigned int offset,
2828         __u64 hdr_data)
2829 {
2830         struct lnet_msg         *msg;
2831         struct lnet_libmd       *md;
2832         int                     cpt;
2833         int                     rc;
2834
2835         LASSERT(the_lnet.ln_refcount > 0);
2836
2837         if (!list_empty(&the_lnet.ln_test_peers) &&     /* normally we don't */
2838             fail_peer(target.nid, 1)) {                 /* shall we now? */
2839                 CERROR("Dropping PUT to %s: simulated failure\n",
2840                        libcfs_id2str(target));
2841                 return -EIO;
2842         }
2843
2844         msg = lnet_msg_alloc();
2845         if (msg == NULL) {
2846                 CERROR("Dropping PUT to %s: ENOMEM on struct lnet_msg\n",
2847                        libcfs_id2str(target));
2848                 return -ENOMEM;
2849         }
2850         msg->msg_vmflush = !!memory_pressure_get();
2851
2852         cpt = lnet_cpt_of_cookie(mdh.cookie);
2853         lnet_res_lock(cpt);
2854
2855         md = lnet_handle2md(&mdh);
2856         if (md == NULL || md->md_threshold == 0 || md->md_me != NULL) {
2857                 CERROR("Dropping PUT (%llu:%d:%s): MD (%d) invalid\n",
2858                        match_bits, portal, libcfs_id2str(target),
2859                        md == NULL ? -1 : md->md_threshold);
2860                 if (md != NULL && md->md_me != NULL)
2861                         CERROR("Source MD also attached to portal %d\n",
2862                                md->md_me->me_portal);
2863                 lnet_res_unlock(cpt);
2864
2865                 lnet_msg_free(msg);
2866                 return -ENOENT;
2867         }
2868
2869         CDEBUG(D_NET, "LNetPut -> %s\n", libcfs_id2str(target));
2870
2871         lnet_msg_attach_md(msg, md, 0, 0);
2872
2873         lnet_prep_send(msg, LNET_MSG_PUT, target, 0, md->md_length);
2874
2875         msg->msg_hdr.msg.put.match_bits = cpu_to_le64(match_bits);
2876         msg->msg_hdr.msg.put.ptl_index = cpu_to_le32(portal);
2877         msg->msg_hdr.msg.put.offset = cpu_to_le32(offset);
2878         msg->msg_hdr.msg.put.hdr_data = hdr_data;
2879
2880         /* NB handles only looked up by creator (no flips) */
2881         if (ack == LNET_ACK_REQ) {
2882                 msg->msg_hdr.msg.put.ack_wmd.wh_interface_cookie =
2883                         the_lnet.ln_interface_cookie;
2884                 msg->msg_hdr.msg.put.ack_wmd.wh_object_cookie =
2885                         md->md_lh.lh_cookie;
2886         } else {
2887                 msg->msg_hdr.msg.put.ack_wmd.wh_interface_cookie =
2888                         LNET_WIRE_HANDLE_COOKIE_NONE;
2889                 msg->msg_hdr.msg.put.ack_wmd.wh_object_cookie =
2890                         LNET_WIRE_HANDLE_COOKIE_NONE;
2891         }
2892
2893         lnet_res_unlock(cpt);
2894
2895         lnet_build_msg_event(msg, LNET_EVENT_SEND);
2896
2897         rc = lnet_send(self, msg, LNET_NID_ANY);
2898         if (rc != 0) {
2899                 CNETERR("Error sending PUT to %s: %d\n",
2900                         libcfs_id2str(target), rc);
2901                 lnet_finalize(msg, rc);
2902         }
2903
2904         /* completion will be signalled by an event */
2905         return 0;
2906 }
2907 EXPORT_SYMBOL(LNetPut);
2908
2909 /*
2910  * The LND can DMA direct to the GET md (i.e. no REPLY msg).  This
2911  * returns a msg for the LND to pass to lnet_finalize() when the sink
2912  * data has been received.
2913  *
2914  * CAVEAT EMPTOR: 'getmsg' is the original GET, which is freed when
2915  * lnet_finalize() is called on it, so the LND must call this first
2916  */
2917 struct lnet_msg *
2918 lnet_create_reply_msg(struct lnet_ni *ni, struct lnet_msg *getmsg)
2919 {
2920         struct lnet_msg *msg = lnet_msg_alloc();
2921         struct lnet_libmd *getmd = getmsg->msg_md;
2922         struct lnet_process_id peer_id = getmsg->msg_target;
2923         int cpt;
2924
2925         LASSERT(!getmsg->msg_target_is_router);
2926         LASSERT(!getmsg->msg_routing);
2927
2928         if (msg == NULL) {
2929                 CERROR("%s: Dropping REPLY from %s: can't allocate msg\n",
2930                        libcfs_nid2str(ni->ni_nid), libcfs_id2str(peer_id));
2931                 goto drop;
2932         }
2933
2934         cpt = lnet_cpt_of_cookie(getmd->md_lh.lh_cookie);
2935         lnet_res_lock(cpt);
2936
2937         LASSERT(getmd->md_refcount > 0);
2938
2939         if (getmd->md_threshold == 0) {
2940                 CERROR("%s: Dropping REPLY from %s for inactive MD %p\n",
2941                         libcfs_nid2str(ni->ni_nid), libcfs_id2str(peer_id),
2942                         getmd);
2943                 lnet_res_unlock(cpt);
2944                 goto drop;
2945         }
2946
2947         LASSERT(getmd->md_offset == 0);
2948
2949         CDEBUG(D_NET, "%s: Reply from %s md %p\n",
2950                libcfs_nid2str(ni->ni_nid), libcfs_id2str(peer_id), getmd);
2951
2952         /* setup information for lnet_build_msg_event */
2953         msg->msg_initiator = getmsg->msg_txpeer->lpni_peer_net->lpn_peer->lp_primary_nid;
2954         msg->msg_from = peer_id.nid;
2955         msg->msg_type = LNET_MSG_GET; /* flag this msg as an "optimized" GET */
2956         msg->msg_hdr.src_nid = peer_id.nid;
2957         msg->msg_hdr.payload_length = getmd->md_length;
2958         msg->msg_receiving = 1; /* required by lnet_msg_attach_md */
2959
2960         lnet_msg_attach_md(msg, getmd, getmd->md_offset, getmd->md_length);
2961         lnet_res_unlock(cpt);
2962
2963         cpt = lnet_cpt_of_nid(peer_id.nid, ni);
2964
2965         lnet_net_lock(cpt);
2966         lnet_msg_commit(msg, cpt);
2967         lnet_net_unlock(cpt);
2968
2969         lnet_build_msg_event(msg, LNET_EVENT_REPLY);
2970
2971         return msg;
2972
2973  drop:
2974         cpt = lnet_cpt_of_nid(peer_id.nid, ni);
2975
2976         lnet_net_lock(cpt);
2977         the_lnet.ln_counters[cpt]->drop_count++;
2978         the_lnet.ln_counters[cpt]->drop_length += getmd->md_length;
2979         lnet_net_unlock(cpt);
2980
2981         if (msg != NULL)
2982                 lnet_msg_free(msg);
2983
2984         return NULL;
2985 }
2986 EXPORT_SYMBOL(lnet_create_reply_msg);
2987
2988 void
2989 lnet_set_reply_msg_len(struct lnet_ni *ni, struct lnet_msg *reply,
2990                        unsigned int len)
2991 {
2992         /* Set the REPLY length, now the RDMA that elides the REPLY message has
2993          * completed and I know it. */
2994         LASSERT(reply != NULL);
2995         LASSERT(reply->msg_type == LNET_MSG_GET);
2996         LASSERT(reply->msg_ev.type == LNET_EVENT_REPLY);
2997
2998         /* NB I trusted my peer to RDMA.  If she tells me she's written beyond
2999          * the end of my buffer, I might as well be dead. */
3000         LASSERT(len <= reply->msg_ev.mlength);
3001
3002         reply->msg_ev.mlength = len;
3003 }
3004 EXPORT_SYMBOL(lnet_set_reply_msg_len);
3005
3006 /**
3007  * Initiate an asynchronous GET operation.
3008  *
3009  * On the initiator node, an LNET_EVENT_SEND is logged when the GET request
3010  * is sent, and an LNET_EVENT_REPLY is logged when the data returned from
3011  * the target node in the REPLY has been written to local MD.
3012  *
3013  * On the target node, an LNET_EVENT_GET is logged when the GET request
3014  * arrives and is accepted into a MD.
3015  *
3016  * \param self,target,portal,match_bits,offset See the discussion in LNetPut().
3017  * \param mdh A handle for the MD that describes the memory into which the
3018  * requested data will be received. The MD must be "free floating" (See LNetMDBind()).
3019  *
3020  * \retval  0      Success, and only in this case events will be generated
3021  * and logged to EQ (if it exists) of the MD.
3022  * \retval -EIO    Simulated failure.
3023  * \retval -ENOMEM Memory allocation failure.
3024  * \retval -ENOENT Invalid MD object.
3025  */
3026 int
3027 LNetGet(lnet_nid_t self, struct lnet_handle_md mdh,
3028         struct lnet_process_id target, unsigned int portal,
3029         __u64 match_bits, unsigned int offset)
3030 {
3031         struct lnet_msg         *msg;
3032         struct lnet_libmd       *md;
3033         int                     cpt;
3034         int                     rc;
3035
3036         LASSERT(the_lnet.ln_refcount > 0);
3037
3038         if (!list_empty(&the_lnet.ln_test_peers) &&     /* normally we don't */
3039             fail_peer(target.nid, 1))                   /* shall we now? */
3040         {
3041                 CERROR("Dropping GET to %s: simulated failure\n",
3042                        libcfs_id2str(target));
3043                 return -EIO;
3044         }
3045
3046         msg = lnet_msg_alloc();
3047         if (msg == NULL) {
3048                 CERROR("Dropping GET to %s: ENOMEM on struct lnet_msg\n",
3049                        libcfs_id2str(target));
3050                 return -ENOMEM;
3051         }
3052
3053         cpt = lnet_cpt_of_cookie(mdh.cookie);
3054         lnet_res_lock(cpt);
3055
3056         md = lnet_handle2md(&mdh);
3057         if (md == NULL || md->md_threshold == 0 || md->md_me != NULL) {
3058                 CERROR("Dropping GET (%llu:%d:%s): MD (%d) invalid\n",
3059                        match_bits, portal, libcfs_id2str(target),
3060                        md == NULL ? -1 : md->md_threshold);
3061                 if (md != NULL && md->md_me != NULL)
3062                         CERROR("REPLY MD also attached to portal %d\n",
3063                                md->md_me->me_portal);
3064
3065                 lnet_res_unlock(cpt);
3066
3067                 lnet_msg_free(msg);
3068                 return -ENOENT;
3069         }
3070
3071         CDEBUG(D_NET, "LNetGet -> %s\n", libcfs_id2str(target));
3072
3073         lnet_msg_attach_md(msg, md, 0, 0);
3074
3075         lnet_prep_send(msg, LNET_MSG_GET, target, 0, 0);
3076
3077         msg->msg_hdr.msg.get.match_bits = cpu_to_le64(match_bits);
3078         msg->msg_hdr.msg.get.ptl_index = cpu_to_le32(portal);
3079         msg->msg_hdr.msg.get.src_offset = cpu_to_le32(offset);
3080         msg->msg_hdr.msg.get.sink_length = cpu_to_le32(md->md_length);
3081
3082         /* NB handles only looked up by creator (no flips) */
3083         msg->msg_hdr.msg.get.return_wmd.wh_interface_cookie =
3084                 the_lnet.ln_interface_cookie;
3085         msg->msg_hdr.msg.get.return_wmd.wh_object_cookie =
3086                 md->md_lh.lh_cookie;
3087
3088         lnet_res_unlock(cpt);
3089
3090         lnet_build_msg_event(msg, LNET_EVENT_SEND);
3091
3092         rc = lnet_send(self, msg, LNET_NID_ANY);
3093         if (rc < 0) {
3094                 CNETERR("Error sending GET to %s: %d\n",
3095                         libcfs_id2str(target), rc);
3096                 lnet_finalize(msg, rc);
3097         }
3098
3099         /* completion will be signalled by an event */
3100         return 0;
3101 }
3102 EXPORT_SYMBOL(LNetGet);
3103
3104 /**
3105  * Calculate distance to node at \a dstnid.
3106  *
3107  * \param dstnid Target NID.
3108  * \param srcnidp If not NULL, NID of the local interface to reach \a dstnid
3109  * is saved here.
3110  * \param orderp If not NULL, order of the route to reach \a dstnid is saved
3111  * here.
3112  *
3113  * \retval 0 If \a dstnid belongs to a local interface, and reserved option
3114  * local_nid_dist_zero is set, which is the default.
3115  * \retval positives Distance to target NID, i.e. number of hops plus one.
3116  * \retval -EHOSTUNREACH If \a dstnid is not reachable.
3117  */
3118 int
3119 LNetDist(lnet_nid_t dstnid, lnet_nid_t *srcnidp, __u32 *orderp)
3120 {
3121         struct list_head        *e;
3122         struct lnet_ni *ni = NULL;
3123         struct lnet_remotenet *rnet;
3124         __u32                   dstnet = LNET_NIDNET(dstnid);
3125         int                     hops;
3126         int                     cpt;
3127         __u32                   order = 2;
3128         struct list_head        *rn_list;
3129
3130         /* if !local_nid_dist_zero, I don't return a distance of 0 ever
3131          * (when lustre sees a distance of 0, it substitutes 0@lo), so I
3132          * keep order 0 free for 0@lo and order 1 free for a local NID
3133          * match */
3134
3135         LASSERT(the_lnet.ln_refcount > 0);
3136
3137         cpt = lnet_net_lock_current();
3138
3139         while ((ni = lnet_get_next_ni_locked(NULL, ni))) {
3140                 if (ni->ni_nid == dstnid) {
3141                         if (srcnidp != NULL)
3142                                 *srcnidp = dstnid;
3143                         if (orderp != NULL) {
3144                                 if (LNET_NETTYP(LNET_NIDNET(dstnid)) == LOLND)
3145                                         *orderp = 0;
3146                                 else
3147                                         *orderp = 1;
3148                         }
3149                         lnet_net_unlock(cpt);
3150
3151                         return local_nid_dist_zero ? 0 : 1;
3152                 }
3153
3154                 if (LNET_NIDNET(ni->ni_nid) == dstnet) {
3155                         /* Check if ni was originally created in
3156                          * current net namespace.
3157                          * If not, assign order above 0xffff0000,
3158                          * to make this ni not a priority. */
3159                         if (!net_eq(ni->ni_net_ns, current->nsproxy->net_ns))
3160                                 order += 0xffff0000;
3161
3162                         if (srcnidp != NULL)
3163                                 *srcnidp = ni->ni_nid;
3164                         if (orderp != NULL)
3165                                 *orderp = order;
3166                         lnet_net_unlock(cpt);
3167                         return 1;
3168                 }
3169
3170                 order++;
3171         }
3172
3173         rn_list = lnet_net2rnethash(dstnet);
3174         list_for_each(e, rn_list) {
3175                 rnet = list_entry(e, struct lnet_remotenet, lrn_list);
3176
3177                 if (rnet->lrn_net == dstnet) {
3178                         struct lnet_route *route;
3179                         struct lnet_route *shortest = NULL;
3180                         __u32 shortest_hops = LNET_UNDEFINED_HOPS;
3181                         __u32 route_hops;
3182
3183                         LASSERT(!list_empty(&rnet->lrn_routes));
3184
3185                         list_for_each_entry(route, &rnet->lrn_routes,
3186                                             lr_list) {
3187                                 route_hops = route->lr_hops;
3188                                 if (route_hops == LNET_UNDEFINED_HOPS)
3189                                         route_hops = 1;
3190                                 if (shortest == NULL ||
3191                                     route_hops < shortest_hops) {
3192                                         shortest = route;
3193                                         shortest_hops = route_hops;
3194                                 }
3195                         }
3196
3197                         LASSERT(shortest != NULL);
3198                         hops = shortest_hops;
3199                         if (srcnidp != NULL) {
3200                                 ni = lnet_get_next_ni_locked(
3201                                         shortest->lr_gateway->lpni_net,
3202                                         NULL);
3203                                 *srcnidp = ni->ni_nid;
3204                         }
3205                         if (orderp != NULL)
3206                                 *orderp = order;
3207                         lnet_net_unlock(cpt);
3208                         return hops + 1;
3209                 }
3210                 order++;
3211         }
3212
3213         lnet_net_unlock(cpt);
3214         return -EHOSTUNREACH;
3215 }
3216 EXPORT_SYMBOL(LNetDist);