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