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