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