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