Whamcloud - gitweb
88f20e7a7d92255ca42c667eda426dc4a8ae37b0
[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 extern unsigned int lnet_current_net_count;
46
47 static int local_nid_dist_zero = 1;
48 module_param(local_nid_dist_zero, int, 0444);
49 MODULE_PARM_DESC(local_nid_dist_zero, "Reserved");
50
51 struct lnet_send_data {
52         struct lnet_ni *sd_best_ni;
53         struct lnet_peer_ni *sd_best_lpni;
54         struct lnet_peer_ni *sd_final_dst_lpni;
55         struct lnet_peer *sd_peer;
56         struct lnet_peer *sd_gw_peer;
57         struct lnet_peer_ni *sd_gw_lpni;
58         struct lnet_peer_net *sd_peer_net;
59         struct lnet_msg *sd_msg;
60         lnet_nid_t sd_dst_nid;
61         lnet_nid_t sd_src_nid;
62         lnet_nid_t sd_rtr_nid;
63         int sd_cpt;
64         int sd_md_cpt;
65         __u32 sd_send_case;
66 };
67
68 static inline struct lnet_comm_count *
69 get_stats_counts(struct lnet_element_stats *stats,
70                  enum lnet_stats_type stats_type)
71 {
72         switch (stats_type) {
73         case LNET_STATS_TYPE_SEND:
74                 return &stats->el_send_stats;
75         case LNET_STATS_TYPE_RECV:
76                 return &stats->el_recv_stats;
77         case LNET_STATS_TYPE_DROP:
78                 return &stats->el_drop_stats;
79         default:
80                 CERROR("Unknown stats type\n");
81         }
82
83         return NULL;
84 }
85
86 void lnet_incr_stats(struct lnet_element_stats *stats,
87                      enum lnet_msg_type msg_type,
88                      enum lnet_stats_type stats_type)
89 {
90         struct lnet_comm_count *counts = get_stats_counts(stats, stats_type);
91         if (!counts)
92                 return;
93
94         switch (msg_type) {
95         case LNET_MSG_ACK:
96                 atomic_inc(&counts->co_ack_count);
97                 break;
98         case LNET_MSG_PUT:
99                 atomic_inc(&counts->co_put_count);
100                 break;
101         case LNET_MSG_GET:
102                 atomic_inc(&counts->co_get_count);
103                 break;
104         case LNET_MSG_REPLY:
105                 atomic_inc(&counts->co_reply_count);
106                 break;
107         case LNET_MSG_HELLO:
108                 atomic_inc(&counts->co_hello_count);
109                 break;
110         default:
111                 CERROR("There is a BUG in the code. Unknown message type\n");
112                 break;
113         }
114 }
115
116 __u32 lnet_sum_stats(struct lnet_element_stats *stats,
117                      enum lnet_stats_type stats_type)
118 {
119         struct lnet_comm_count *counts = get_stats_counts(stats, stats_type);
120         if (!counts)
121                 return 0;
122
123         return (atomic_read(&counts->co_ack_count) +
124                 atomic_read(&counts->co_put_count) +
125                 atomic_read(&counts->co_get_count) +
126                 atomic_read(&counts->co_reply_count) +
127                 atomic_read(&counts->co_hello_count));
128 }
129
130 static inline void assign_stats(struct lnet_ioctl_comm_count *msg_stats,
131                                 struct lnet_comm_count *counts)
132 {
133         msg_stats->ico_get_count = atomic_read(&counts->co_get_count);
134         msg_stats->ico_put_count = atomic_read(&counts->co_put_count);
135         msg_stats->ico_reply_count = atomic_read(&counts->co_reply_count);
136         msg_stats->ico_ack_count = atomic_read(&counts->co_ack_count);
137         msg_stats->ico_hello_count = atomic_read(&counts->co_hello_count);
138 }
139
140 void lnet_usr_translate_stats(struct lnet_ioctl_element_msg_stats *msg_stats,
141                               struct lnet_element_stats *stats)
142 {
143         struct lnet_comm_count *counts;
144
145         LASSERT(msg_stats);
146         LASSERT(stats);
147
148         counts = get_stats_counts(stats, LNET_STATS_TYPE_SEND);
149         if (!counts)
150                 return;
151         assign_stats(&msg_stats->im_send_stats, counts);
152
153         counts = get_stats_counts(stats, LNET_STATS_TYPE_RECV);
154         if (!counts)
155                 return;
156         assign_stats(&msg_stats->im_recv_stats, counts);
157
158         counts = get_stats_counts(stats, LNET_STATS_TYPE_DROP);
159         if (!counts)
160                 return;
161         assign_stats(&msg_stats->im_drop_stats, counts);
162 }
163
164 int
165 lnet_fail_nid(lnet_nid_t nid, unsigned int threshold)
166 {
167         struct lnet_test_peer *tp;
168         struct list_head *el;
169         struct list_head *next;
170         struct list_head  cull;
171
172         /* NB: use lnet_net_lock(0) to serialize operations on test peers */
173         if (threshold != 0) {
174                 /* Adding a new entry */
175                 LIBCFS_ALLOC(tp, sizeof(*tp));
176                 if (tp == NULL)
177                         return -ENOMEM;
178
179                 tp->tp_nid = nid;
180                 tp->tp_threshold = threshold;
181
182                 lnet_net_lock(0);
183                 list_add_tail(&tp->tp_list, &the_lnet.ln_test_peers);
184                 lnet_net_unlock(0);
185                 return 0;
186         }
187
188         /* removing entries */
189         INIT_LIST_HEAD(&cull);
190
191         lnet_net_lock(0);
192
193         list_for_each_safe(el, next, &the_lnet.ln_test_peers) {
194                 tp = list_entry(el, struct lnet_test_peer, tp_list);
195
196                 if (tp->tp_threshold == 0 ||    /* needs culling anyway */
197                     nid == LNET_NID_ANY ||      /* removing all entries */
198                     tp->tp_nid == nid) {        /* matched this one */
199                         list_del(&tp->tp_list);
200                         list_add(&tp->tp_list, &cull);
201                 }
202         }
203
204         lnet_net_unlock(0);
205
206         while (!list_empty(&cull)) {
207                 tp = list_entry(cull.next, struct lnet_test_peer, tp_list);
208
209                 list_del(&tp->tp_list);
210                 LIBCFS_FREE(tp, sizeof(*tp));
211         }
212         return 0;
213 }
214
215 static int
216 fail_peer (lnet_nid_t nid, int outgoing)
217 {
218         struct lnet_test_peer *tp;
219         struct list_head *el;
220         struct list_head *next;
221         struct list_head  cull;
222         int               fail = 0;
223
224         INIT_LIST_HEAD(&cull);
225
226         /* NB: use lnet_net_lock(0) to serialize operations on test peers */
227         lnet_net_lock(0);
228
229         list_for_each_safe(el, next, &the_lnet.ln_test_peers) {
230                 tp = list_entry(el, struct lnet_test_peer, tp_list);
231
232                 if (tp->tp_threshold == 0) {
233                         /* zombie entry */
234                         if (outgoing) {
235                                 /* only cull zombies on outgoing tests,
236                                  * since we may be at interrupt priority on
237                                  * incoming messages. */
238                                 list_del(&tp->tp_list);
239                                 list_add(&tp->tp_list, &cull);
240                         }
241                         continue;
242                 }
243
244                 if (tp->tp_nid == LNET_NID_ANY ||       /* fail every peer */
245                     nid == tp->tp_nid) {                /* fail this peer */
246                         fail = 1;
247
248                         if (tp->tp_threshold != LNET_MD_THRESH_INF) {
249                                 tp->tp_threshold--;
250                                 if (outgoing &&
251                                     tp->tp_threshold == 0) {
252                                         /* see above */
253                                         list_del(&tp->tp_list);
254                                         list_add(&tp->tp_list, &cull);
255                                 }
256                         }
257                         break;
258                 }
259         }
260
261         lnet_net_unlock(0);
262
263         while (!list_empty(&cull)) {
264                 tp = list_entry(cull.next, struct lnet_test_peer, tp_list);
265                 list_del(&tp->tp_list);
266
267                 LIBCFS_FREE(tp, sizeof(*tp));
268         }
269
270         return fail;
271 }
272
273 unsigned int
274 lnet_iov_nob(unsigned int niov, struct kvec *iov)
275 {
276         unsigned int nob = 0;
277
278         LASSERT(niov == 0 || iov != NULL);
279         while (niov-- > 0)
280                 nob += (iov++)->iov_len;
281
282         return (nob);
283 }
284 EXPORT_SYMBOL(lnet_iov_nob);
285
286 void
287 lnet_copy_iov2iov(unsigned int ndiov, struct kvec *diov, unsigned int doffset,
288                   unsigned int nsiov, struct kvec *siov, unsigned int soffset,
289                   unsigned int nob)
290 {
291         /* NB diov, siov are READ-ONLY */
292         unsigned int  this_nob;
293
294         if (nob == 0)
295                 return;
296
297         /* skip complete frags before 'doffset' */
298         LASSERT(ndiov > 0);
299         while (doffset >= diov->iov_len) {
300                 doffset -= diov->iov_len;
301                 diov++;
302                 ndiov--;
303                 LASSERT(ndiov > 0);
304         }
305
306         /* skip complete frags before 'soffset' */
307         LASSERT(nsiov > 0);
308         while (soffset >= siov->iov_len) {
309                 soffset -= siov->iov_len;
310                 siov++;
311                 nsiov--;
312                 LASSERT(nsiov > 0);
313         }
314
315         do {
316                 LASSERT(ndiov > 0);
317                 LASSERT(nsiov > 0);
318                 this_nob = MIN(diov->iov_len - doffset,
319                                siov->iov_len - soffset);
320                 this_nob = MIN(this_nob, nob);
321
322                 memcpy((char *)diov->iov_base + doffset,
323                        (char *)siov->iov_base + soffset, this_nob);
324                 nob -= this_nob;
325
326                 if (diov->iov_len > doffset + this_nob) {
327                         doffset += this_nob;
328                 } else {
329                         diov++;
330                         ndiov--;
331                         doffset = 0;
332                 }
333
334                 if (siov->iov_len > soffset + this_nob) {
335                         soffset += this_nob;
336                 } else {
337                         siov++;
338                         nsiov--;
339                         soffset = 0;
340                 }
341         } while (nob > 0);
342 }
343 EXPORT_SYMBOL(lnet_copy_iov2iov);
344
345 int
346 lnet_extract_iov(int dst_niov, struct kvec *dst,
347                  int src_niov, struct kvec *src,
348                  unsigned int offset, unsigned int len)
349 {
350         /* Initialise 'dst' to the subset of 'src' starting at 'offset',
351          * for exactly 'len' bytes, and return the number of entries.
352          * NB not destructive to 'src' */
353         unsigned int    frag_len;
354         unsigned int    niov;
355
356         if (len == 0)                           /* no data => */
357                 return (0);                     /* no frags */
358
359         LASSERT(src_niov > 0);
360         while (offset >= src->iov_len) {      /* skip initial frags */
361                 offset -= src->iov_len;
362                 src_niov--;
363                 src++;
364                 LASSERT(src_niov > 0);
365         }
366
367         niov = 1;
368         for (;;) {
369                 LASSERT(src_niov > 0);
370                 LASSERT((int)niov <= dst_niov);
371
372                 frag_len = src->iov_len - offset;
373                 dst->iov_base = ((char *)src->iov_base) + offset;
374
375                 if (len <= frag_len) {
376                         dst->iov_len = len;
377                         return (niov);
378                 }
379
380                 dst->iov_len = frag_len;
381
382                 len -= frag_len;
383                 dst++;
384                 src++;
385                 niov++;
386                 src_niov--;
387                 offset = 0;
388         }
389 }
390 EXPORT_SYMBOL(lnet_extract_iov);
391
392
393 unsigned int
394 lnet_kiov_nob(unsigned int niov, lnet_kiov_t *kiov)
395 {
396         unsigned int  nob = 0;
397
398         LASSERT(niov == 0 || kiov != NULL);
399         while (niov-- > 0)
400                 nob += (kiov++)->kiov_len;
401
402         return (nob);
403 }
404 EXPORT_SYMBOL(lnet_kiov_nob);
405
406 void
407 lnet_copy_kiov2kiov(unsigned int ndiov, lnet_kiov_t *diov, unsigned int doffset,
408                     unsigned int nsiov, lnet_kiov_t *siov, unsigned int soffset,
409                     unsigned int nob)
410 {
411         /* NB diov, siov are READ-ONLY */
412         unsigned int    this_nob;
413         char           *daddr = NULL;
414         char           *saddr = NULL;
415
416         if (nob == 0)
417                 return;
418
419         LASSERT (!in_interrupt ());
420
421         LASSERT (ndiov > 0);
422         while (doffset >= diov->kiov_len) {
423                 doffset -= diov->kiov_len;
424                 diov++;
425                 ndiov--;
426                 LASSERT(ndiov > 0);
427         }
428
429         LASSERT(nsiov > 0);
430         while (soffset >= siov->kiov_len) {
431                 soffset -= siov->kiov_len;
432                 siov++;
433                 nsiov--;
434                 LASSERT(nsiov > 0);
435         }
436
437         do {
438                 LASSERT(ndiov > 0);
439                 LASSERT(nsiov > 0);
440                 this_nob = MIN(diov->kiov_len - doffset,
441                                siov->kiov_len - soffset);
442                 this_nob = MIN(this_nob, nob);
443
444                 if (daddr == NULL)
445                         daddr = ((char *)kmap(diov->kiov_page)) +
446                                 diov->kiov_offset + doffset;
447                 if (saddr == NULL)
448                         saddr = ((char *)kmap(siov->kiov_page)) +
449                                 siov->kiov_offset + soffset;
450
451                 /* Vanishing risk of kmap deadlock when mapping 2 pages.
452                  * However in practice at least one of the kiovs will be mapped
453                  * kernel pages and the map/unmap will be NOOPs */
454
455                 memcpy (daddr, saddr, this_nob);
456                 nob -= this_nob;
457
458                 if (diov->kiov_len > doffset + this_nob) {
459                         daddr += this_nob;
460                         doffset += this_nob;
461                 } else {
462                         kunmap(diov->kiov_page);
463                         daddr = NULL;
464                         diov++;
465                         ndiov--;
466                         doffset = 0;
467                 }
468
469                 if (siov->kiov_len > soffset + this_nob) {
470                         saddr += this_nob;
471                         soffset += this_nob;
472                 } else {
473                         kunmap(siov->kiov_page);
474                         saddr = NULL;
475                         siov++;
476                         nsiov--;
477                         soffset = 0;
478                 }
479         } while (nob > 0);
480
481         if (daddr != NULL)
482                 kunmap(diov->kiov_page);
483         if (saddr != NULL)
484                 kunmap(siov->kiov_page);
485 }
486 EXPORT_SYMBOL(lnet_copy_kiov2kiov);
487
488 void
489 lnet_copy_kiov2iov (unsigned int niov, struct kvec *iov, unsigned int iovoffset,
490                     unsigned int nkiov, lnet_kiov_t *kiov, unsigned int kiovoffset,
491                     unsigned int nob)
492 {
493         /* NB iov, kiov are READ-ONLY */
494         unsigned int    this_nob;
495         char           *addr = NULL;
496
497         if (nob == 0)
498                 return;
499
500         LASSERT (!in_interrupt ());
501
502         LASSERT (niov > 0);
503         while (iovoffset >= iov->iov_len) {
504                 iovoffset -= iov->iov_len;
505                 iov++;
506                 niov--;
507                 LASSERT(niov > 0);
508         }
509
510         LASSERT(nkiov > 0);
511         while (kiovoffset >= kiov->kiov_len) {
512                 kiovoffset -= kiov->kiov_len;
513                 kiov++;
514                 nkiov--;
515                 LASSERT(nkiov > 0);
516         }
517
518         do {
519                 LASSERT(niov > 0);
520                 LASSERT(nkiov > 0);
521                 this_nob = MIN(iov->iov_len - iovoffset,
522                                kiov->kiov_len - kiovoffset);
523                 this_nob = MIN(this_nob, nob);
524
525                 if (addr == NULL)
526                         addr = ((char *)kmap(kiov->kiov_page)) +
527                                 kiov->kiov_offset + kiovoffset;
528
529                 memcpy((char *)iov->iov_base + iovoffset, addr, this_nob);
530                 nob -= this_nob;
531
532                 if (iov->iov_len > iovoffset + this_nob) {
533                         iovoffset += this_nob;
534                 } else {
535                         iov++;
536                         niov--;
537                         iovoffset = 0;
538                 }
539
540                 if (kiov->kiov_len > kiovoffset + this_nob) {
541                         addr += this_nob;
542                         kiovoffset += this_nob;
543                 } else {
544                         kunmap(kiov->kiov_page);
545                         addr = NULL;
546                         kiov++;
547                         nkiov--;
548                         kiovoffset = 0;
549                 }
550
551         } while (nob > 0);
552
553         if (addr != NULL)
554                 kunmap(kiov->kiov_page);
555 }
556 EXPORT_SYMBOL(lnet_copy_kiov2iov);
557
558 void
559 lnet_copy_iov2kiov(unsigned int nkiov, lnet_kiov_t *kiov, unsigned int kiovoffset,
560                    unsigned int niov, struct kvec *iov, unsigned int iovoffset,
561                    unsigned int nob)
562 {
563         /* NB kiov, iov are READ-ONLY */
564         unsigned int    this_nob;
565         char           *addr = NULL;
566
567         if (nob == 0)
568                 return;
569
570         LASSERT (!in_interrupt ());
571
572         LASSERT (nkiov > 0);
573         while (kiovoffset >= kiov->kiov_len) {
574                 kiovoffset -= kiov->kiov_len;
575                 kiov++;
576                 nkiov--;
577                 LASSERT(nkiov > 0);
578         }
579
580         LASSERT(niov > 0);
581         while (iovoffset >= iov->iov_len) {
582                 iovoffset -= iov->iov_len;
583                 iov++;
584                 niov--;
585                 LASSERT(niov > 0);
586         }
587
588         do {
589                 LASSERT(nkiov > 0);
590                 LASSERT(niov > 0);
591                 this_nob = MIN(kiov->kiov_len - kiovoffset,
592                                iov->iov_len - iovoffset);
593                 this_nob = MIN(this_nob, nob);
594
595                 if (addr == NULL)
596                         addr = ((char *)kmap(kiov->kiov_page)) +
597                                 kiov->kiov_offset + kiovoffset;
598
599                 memcpy (addr, (char *)iov->iov_base + iovoffset, this_nob);
600                 nob -= this_nob;
601
602                 if (kiov->kiov_len > kiovoffset + this_nob) {
603                         addr += this_nob;
604                         kiovoffset += this_nob;
605                 } else {
606                         kunmap(kiov->kiov_page);
607                         addr = NULL;
608                         kiov++;
609                         nkiov--;
610                         kiovoffset = 0;
611                 }
612
613                 if (iov->iov_len > iovoffset + this_nob) {
614                         iovoffset += this_nob;
615                 } else {
616                         iov++;
617                         niov--;
618                         iovoffset = 0;
619                 }
620         } while (nob > 0);
621
622         if (addr != NULL)
623                 kunmap(kiov->kiov_page);
624 }
625 EXPORT_SYMBOL(lnet_copy_iov2kiov);
626
627 int
628 lnet_extract_kiov(int dst_niov, lnet_kiov_t *dst,
629                   int src_niov, lnet_kiov_t *src,
630                   unsigned int offset, unsigned int len)
631 {
632         /* Initialise 'dst' to the subset of 'src' starting at 'offset',
633          * for exactly 'len' bytes, and return the number of entries.
634          * NB not destructive to 'src' */
635         unsigned int    frag_len;
636         unsigned int    niov;
637
638         if (len == 0)                           /* no data => */
639                 return (0);                     /* no frags */
640
641         LASSERT(src_niov > 0);
642         while (offset >= src->kiov_len) {      /* skip initial frags */
643                 offset -= src->kiov_len;
644                 src_niov--;
645                 src++;
646                 LASSERT(src_niov > 0);
647         }
648
649         niov = 1;
650         for (;;) {
651                 LASSERT(src_niov > 0);
652                 LASSERT((int)niov <= dst_niov);
653
654                 frag_len = src->kiov_len - offset;
655                 dst->kiov_page = src->kiov_page;
656                 dst->kiov_offset = src->kiov_offset + offset;
657
658                 if (len <= frag_len) {
659                         dst->kiov_len = len;
660                         LASSERT(dst->kiov_offset + dst->kiov_len <= PAGE_SIZE);
661                         return niov;
662                 }
663
664                 dst->kiov_len = frag_len;
665                 LASSERT(dst->kiov_offset + dst->kiov_len <= PAGE_SIZE);
666
667                 len -= frag_len;
668                 dst++;
669                 src++;
670                 niov++;
671                 src_niov--;
672                 offset = 0;
673         }
674 }
675 EXPORT_SYMBOL(lnet_extract_kiov);
676
677 void
678 lnet_ni_recv(struct lnet_ni *ni, void *private, struct lnet_msg *msg,
679              int delayed, unsigned int offset, unsigned int mlen,
680              unsigned int rlen)
681 {
682         unsigned int  niov = 0;
683         struct kvec *iov = NULL;
684         lnet_kiov_t  *kiov = NULL;
685         int           rc;
686
687         LASSERT (!in_interrupt ());
688         LASSERT (mlen == 0 || msg != NULL);
689
690         if (msg != NULL) {
691                 LASSERT(msg->msg_receiving);
692                 LASSERT(!msg->msg_sending);
693                 LASSERT(rlen == msg->msg_len);
694                 LASSERT(mlen <= msg->msg_len);
695                 LASSERT(msg->msg_offset == offset);
696                 LASSERT(msg->msg_wanted == mlen);
697
698                 msg->msg_receiving = 0;
699
700                 if (mlen != 0) {
701                         niov = msg->msg_niov;
702                         iov  = msg->msg_iov;
703                         kiov = msg->msg_kiov;
704
705                         LASSERT (niov > 0);
706                         LASSERT ((iov == NULL) != (kiov == NULL));
707                 }
708         }
709
710         rc = (ni->ni_net->net_lnd->lnd_recv)(ni, private, msg, delayed,
711                                              niov, iov, kiov, offset, mlen,
712                                              rlen);
713         if (rc < 0)
714                 lnet_finalize(msg, rc);
715 }
716
717 static void
718 lnet_setpayloadbuffer(struct lnet_msg *msg)
719 {
720         struct lnet_libmd *md = msg->msg_md;
721
722         LASSERT(msg->msg_len > 0);
723         LASSERT(!msg->msg_routing);
724         LASSERT(md != NULL);
725         LASSERT(msg->msg_niov == 0);
726         LASSERT(msg->msg_iov == NULL);
727         LASSERT(msg->msg_kiov == NULL);
728
729         msg->msg_niov = md->md_niov;
730         if ((md->md_options & LNET_MD_KIOV) != 0)
731                 msg->msg_kiov = md->md_iov.kiov;
732         else
733                 msg->msg_iov = md->md_iov.iov;
734 }
735
736 void
737 lnet_prep_send(struct lnet_msg *msg, int type, struct lnet_process_id target,
738                unsigned int offset, unsigned int len)
739 {
740         msg->msg_type = type;
741         msg->msg_target = target;
742         msg->msg_len = len;
743         msg->msg_offset = offset;
744
745         if (len != 0)
746                 lnet_setpayloadbuffer(msg);
747
748         memset (&msg->msg_hdr, 0, sizeof (msg->msg_hdr));
749         msg->msg_hdr.type           = cpu_to_le32(type);
750         /* dest_nid will be overwritten by lnet_select_pathway() */
751         msg->msg_hdr.dest_nid       = cpu_to_le64(target.nid);
752         msg->msg_hdr.dest_pid       = cpu_to_le32(target.pid);
753         /* src_nid will be set later */
754         msg->msg_hdr.src_pid        = cpu_to_le32(the_lnet.ln_pid);
755         msg->msg_hdr.payload_length = cpu_to_le32(len);
756 }
757
758 static void
759 lnet_ni_send(struct lnet_ni *ni, struct lnet_msg *msg)
760 {
761         void   *priv = msg->msg_private;
762         int rc;
763
764         LASSERT (!in_interrupt ());
765         LASSERT (LNET_NETTYP(LNET_NIDNET(ni->ni_nid)) == LOLND ||
766                  (msg->msg_txcredit && msg->msg_peertxcredit));
767
768         rc = (ni->ni_net->net_lnd->lnd_send)(ni, priv, msg);
769         if (rc < 0) {
770                 msg->msg_no_resend = true;
771                 lnet_finalize(msg, rc);
772         }
773 }
774
775 static int
776 lnet_ni_eager_recv(struct lnet_ni *ni, struct lnet_msg *msg)
777 {
778         int     rc;
779
780         LASSERT(!msg->msg_sending);
781         LASSERT(msg->msg_receiving);
782         LASSERT(!msg->msg_rx_ready_delay);
783         LASSERT(ni->ni_net->net_lnd->lnd_eager_recv != NULL);
784
785         msg->msg_rx_ready_delay = 1;
786         rc = (ni->ni_net->net_lnd->lnd_eager_recv)(ni, msg->msg_private, msg,
787                                                   &msg->msg_private);
788         if (rc != 0) {
789                 CERROR("recv from %s / send to %s aborted: "
790                        "eager_recv failed %d\n",
791                        libcfs_nid2str(msg->msg_rxpeer->lpni_nid),
792                        libcfs_id2str(msg->msg_target), rc);
793                 LASSERT(rc < 0); /* required by my callers */
794         }
795
796         return rc;
797 }
798
799 static bool
800 lnet_is_peer_deadline_passed(struct lnet_peer_ni *lpni, time64_t now)
801 {
802         time64_t deadline;
803
804         deadline = lpni->lpni_last_alive +
805                    lpni->lpni_net->net_tunables.lct_peer_timeout;
806
807         /*
808          * assume peer_ni is alive as long as we're within the configured
809          * peer timeout
810          */
811         if (deadline > now)
812                 return false;
813
814         return true;
815 }
816
817 /* NB: returns 1 when alive, 0 when dead, negative when error;
818  *     may drop the lnet_net_lock */
819 static int
820 lnet_peer_alive_locked(struct lnet_ni *ni, struct lnet_peer_ni *lpni,
821                        struct lnet_msg *msg)
822 {
823         time64_t now = ktime_get_seconds();
824
825         if (!lnet_peer_aliveness_enabled(lpni))
826                 return -ENODEV;
827
828         /*
829          * If we're resending a message, let's attempt to send it even if
830          * the peer is down to fulfill our resend quota on the message
831          */
832         if (msg->msg_retry_count > 0)
833                 return 1;
834
835         /* try and send recovery messages irregardless */
836         if (msg->msg_recovery)
837                 return 1;
838
839         /* always send any responses */
840         if (msg->msg_type == LNET_MSG_ACK ||
841             msg->msg_type == LNET_MSG_REPLY)
842                 return 1;
843
844         if (!lnet_is_peer_deadline_passed(lpni, now))
845                 return true;
846
847         return lnet_is_peer_ni_alive(lpni);
848 }
849
850 /**
851  * \param msg The message to be sent.
852  * \param do_send True if lnet_ni_send() should be called in this function.
853  *        lnet_send() is going to lnet_net_unlock immediately after this, so
854  *        it sets do_send FALSE and I don't do the unlock/send/lock bit.
855  *
856  * \retval LNET_CREDIT_OK If \a msg sent or OK to send.
857  * \retval LNET_CREDIT_WAIT If \a msg blocked for credit.
858  * \retval -EHOSTUNREACH If the next hop of the message appears dead.
859  * \retval -ECANCELED If the MD of the message has been unlinked.
860  */
861 static int
862 lnet_post_send_locked(struct lnet_msg *msg, int do_send)
863 {
864         struct lnet_peer_ni     *lp = msg->msg_txpeer;
865         struct lnet_ni          *ni = msg->msg_txni;
866         int                     cpt = msg->msg_tx_cpt;
867         struct lnet_tx_queue    *tq = ni->ni_tx_queues[cpt];
868
869         /* non-lnet_send() callers have checked before */
870         LASSERT(!do_send || msg->msg_tx_delayed);
871         LASSERT(!msg->msg_receiving);
872         LASSERT(msg->msg_tx_committed);
873         /* can't get here if we're sending to the loopback interface */
874         LASSERT(lp->lpni_nid != the_lnet.ln_loni->ni_nid);
875
876         /* NB 'lp' is always the next hop */
877         if ((msg->msg_target.pid & LNET_PID_USERFLAG) == 0 &&
878             lnet_peer_alive_locked(ni, lp, msg) == 0) {
879                 the_lnet.ln_counters[cpt]->lct_common.lcc_drop_count++;
880                 the_lnet.ln_counters[cpt]->lct_common.lcc_drop_length +=
881                         msg->msg_len;
882                 lnet_net_unlock(cpt);
883                 if (msg->msg_txpeer)
884                         lnet_incr_stats(&msg->msg_txpeer->lpni_stats,
885                                         msg->msg_type,
886                                         LNET_STATS_TYPE_DROP);
887                 if (msg->msg_txni)
888                         lnet_incr_stats(&msg->msg_txni->ni_stats,
889                                         msg->msg_type,
890                                         LNET_STATS_TYPE_DROP);
891
892                 CNETERR("Dropping message for %s: peer not alive\n",
893                         libcfs_id2str(msg->msg_target));
894                 msg->msg_health_status = LNET_MSG_STATUS_REMOTE_DROPPED;
895                 if (do_send)
896                         lnet_finalize(msg, -EHOSTUNREACH);
897
898                 lnet_net_lock(cpt);
899                 return -EHOSTUNREACH;
900         }
901
902         if (msg->msg_md != NULL &&
903             (msg->msg_md->md_flags & LNET_MD_FLAG_ABORTED) != 0) {
904                 lnet_net_unlock(cpt);
905
906                 CNETERR("Aborting message for %s: LNetM[DE]Unlink() already "
907                         "called on the MD/ME.\n",
908                         libcfs_id2str(msg->msg_target));
909                 if (do_send) {
910                         msg->msg_no_resend = true;
911                         CDEBUG(D_NET, "msg %p to %s canceled and will not be resent\n",
912                                msg, libcfs_id2str(msg->msg_target));
913                         lnet_finalize(msg, -ECANCELED);
914                 }
915
916                 lnet_net_lock(cpt);
917                 return -ECANCELED;
918         }
919
920         if (!msg->msg_peertxcredit) {
921                 spin_lock(&lp->lpni_lock);
922                 LASSERT((lp->lpni_txcredits < 0) ==
923                         !list_empty(&lp->lpni_txq));
924
925                 msg->msg_peertxcredit = 1;
926                 lp->lpni_txqnob += msg->msg_len + sizeof(struct lnet_hdr);
927                 lp->lpni_txcredits--;
928
929                 if (lp->lpni_txcredits < lp->lpni_mintxcredits)
930                         lp->lpni_mintxcredits = lp->lpni_txcredits;
931
932                 if (lp->lpni_txcredits < 0) {
933                         msg->msg_tx_delayed = 1;
934                         list_add_tail(&msg->msg_list, &lp->lpni_txq);
935                         spin_unlock(&lp->lpni_lock);
936                         return LNET_CREDIT_WAIT;
937                 }
938                 spin_unlock(&lp->lpni_lock);
939         }
940
941         if (!msg->msg_txcredit) {
942                 LASSERT((tq->tq_credits < 0) ==
943                         !list_empty(&tq->tq_delayed));
944
945                 msg->msg_txcredit = 1;
946                 tq->tq_credits--;
947                 atomic_dec(&ni->ni_tx_credits);
948
949                 if (tq->tq_credits < tq->tq_credits_min)
950                         tq->tq_credits_min = tq->tq_credits;
951
952                 if (tq->tq_credits < 0) {
953                         msg->msg_tx_delayed = 1;
954                         list_add_tail(&msg->msg_list, &tq->tq_delayed);
955                         return LNET_CREDIT_WAIT;
956                 }
957         }
958
959         /* unset the tx_delay flag as we're going to send it now */
960         msg->msg_tx_delayed = 0;
961
962         if (do_send) {
963                 lnet_net_unlock(cpt);
964                 lnet_ni_send(ni, msg);
965                 lnet_net_lock(cpt);
966         }
967         return LNET_CREDIT_OK;
968 }
969
970
971 static struct lnet_rtrbufpool *
972 lnet_msg2bufpool(struct lnet_msg *msg)
973 {
974         struct lnet_rtrbufpool  *rbp;
975         int                     cpt;
976
977         LASSERT(msg->msg_rx_committed);
978
979         cpt = msg->msg_rx_cpt;
980         rbp = &the_lnet.ln_rtrpools[cpt][0];
981
982         LASSERT(msg->msg_len <= LNET_MTU);
983         while (msg->msg_len > (unsigned int)rbp->rbp_npages * PAGE_SIZE) {
984                 rbp++;
985                 LASSERT(rbp < &the_lnet.ln_rtrpools[cpt][LNET_NRBPOOLS]);
986         }
987
988         return rbp;
989 }
990
991 static int
992 lnet_post_routed_recv_locked(struct lnet_msg *msg, int do_recv)
993 {
994         /* lnet_parse is going to lnet_net_unlock immediately after this, so it
995          * sets do_recv FALSE and I don't do the unlock/send/lock bit.
996          * I return LNET_CREDIT_WAIT if msg blocked and LNET_CREDIT_OK if
997          * received or OK to receive */
998         struct lnet_peer_ni *lpni = msg->msg_rxpeer;
999         struct lnet_peer *lp;
1000         struct lnet_rtrbufpool *rbp;
1001         struct lnet_rtrbuf *rb;
1002
1003         LASSERT(msg->msg_iov == NULL);
1004         LASSERT(msg->msg_kiov == NULL);
1005         LASSERT(msg->msg_niov == 0);
1006         LASSERT(msg->msg_routing);
1007         LASSERT(msg->msg_receiving);
1008         LASSERT(!msg->msg_sending);
1009         LASSERT(lpni->lpni_peer_net);
1010         LASSERT(lpni->lpni_peer_net->lpn_peer);
1011
1012         lp = lpni->lpni_peer_net->lpn_peer;
1013
1014         /* non-lnet_parse callers only receive delayed messages */
1015         LASSERT(!do_recv || msg->msg_rx_delayed);
1016
1017         if (!msg->msg_peerrtrcredit) {
1018                 /* lpni_lock protects the credit manipulation */
1019                 spin_lock(&lpni->lpni_lock);
1020                 /* lp_lock protects the lp_rtrq */
1021                 spin_lock(&lp->lp_lock);
1022
1023                 msg->msg_peerrtrcredit = 1;
1024                 lpni->lpni_rtrcredits--;
1025                 if (lpni->lpni_rtrcredits < lpni->lpni_minrtrcredits)
1026                         lpni->lpni_minrtrcredits = lpni->lpni_rtrcredits;
1027
1028                 if (lpni->lpni_rtrcredits < 0) {
1029                         /* must have checked eager_recv before here */
1030                         LASSERT(msg->msg_rx_ready_delay);
1031                         msg->msg_rx_delayed = 1;
1032                         list_add_tail(&msg->msg_list, &lp->lp_rtrq);
1033                         spin_unlock(&lp->lp_lock);
1034                         spin_unlock(&lpni->lpni_lock);
1035                         return LNET_CREDIT_WAIT;
1036                 }
1037                 spin_unlock(&lp->lp_lock);
1038                 spin_unlock(&lpni->lpni_lock);
1039         }
1040
1041         rbp = lnet_msg2bufpool(msg);
1042
1043         if (!msg->msg_rtrcredit) {
1044                 msg->msg_rtrcredit = 1;
1045                 rbp->rbp_credits--;
1046                 if (rbp->rbp_credits < rbp->rbp_mincredits)
1047                         rbp->rbp_mincredits = rbp->rbp_credits;
1048
1049                 if (rbp->rbp_credits < 0) {
1050                         /* must have checked eager_recv before here */
1051                         LASSERT(msg->msg_rx_ready_delay);
1052                         msg->msg_rx_delayed = 1;
1053                         list_add_tail(&msg->msg_list, &rbp->rbp_msgs);
1054                         return LNET_CREDIT_WAIT;
1055                 }
1056         }
1057
1058         LASSERT(!list_empty(&rbp->rbp_bufs));
1059         rb = list_entry(rbp->rbp_bufs.next, struct lnet_rtrbuf, rb_list);
1060         list_del(&rb->rb_list);
1061
1062         msg->msg_niov = rbp->rbp_npages;
1063         msg->msg_kiov = &rb->rb_kiov[0];
1064
1065         /* unset the msg-rx_delayed flag since we're receiving the message */
1066         msg->msg_rx_delayed = 0;
1067
1068         if (do_recv) {
1069                 int cpt = msg->msg_rx_cpt;
1070
1071                 lnet_net_unlock(cpt);
1072                 lnet_ni_recv(msg->msg_rxni, msg->msg_private, msg, 1,
1073                              0, msg->msg_len, msg->msg_len);
1074                 lnet_net_lock(cpt);
1075         }
1076         return LNET_CREDIT_OK;
1077 }
1078
1079 void
1080 lnet_return_tx_credits_locked(struct lnet_msg *msg)
1081 {
1082         struct lnet_peer_ni     *txpeer = msg->msg_txpeer;
1083         struct lnet_ni          *txni = msg->msg_txni;
1084         struct lnet_msg         *msg2;
1085
1086         if (msg->msg_txcredit) {
1087                 struct lnet_ni       *ni = msg->msg_txni;
1088                 struct lnet_tx_queue *tq = ni->ni_tx_queues[msg->msg_tx_cpt];
1089
1090                 /* give back NI txcredits */
1091                 msg->msg_txcredit = 0;
1092
1093                 LASSERT((tq->tq_credits < 0) ==
1094                         !list_empty(&tq->tq_delayed));
1095
1096                 tq->tq_credits++;
1097                 atomic_inc(&ni->ni_tx_credits);
1098                 if (tq->tq_credits <= 0) {
1099                         msg2 = list_entry(tq->tq_delayed.next,
1100                                           struct lnet_msg, msg_list);
1101                         list_del(&msg2->msg_list);
1102
1103                         LASSERT(msg2->msg_txni == ni);
1104                         LASSERT(msg2->msg_tx_delayed);
1105                         LASSERT(msg2->msg_tx_cpt == msg->msg_tx_cpt);
1106
1107                         (void) lnet_post_send_locked(msg2, 1);
1108                 }
1109         }
1110
1111         if (msg->msg_peertxcredit) {
1112                 /* give back peer txcredits */
1113                 msg->msg_peertxcredit = 0;
1114
1115                 spin_lock(&txpeer->lpni_lock);
1116                 LASSERT((txpeer->lpni_txcredits < 0) ==
1117                         !list_empty(&txpeer->lpni_txq));
1118
1119                 txpeer->lpni_txqnob -= msg->msg_len + sizeof(struct lnet_hdr);
1120                 LASSERT(txpeer->lpni_txqnob >= 0);
1121
1122                 txpeer->lpni_txcredits++;
1123                 if (txpeer->lpni_txcredits <= 0) {
1124                         int msg2_cpt;
1125
1126                         msg2 = list_entry(txpeer->lpni_txq.next,
1127                                               struct lnet_msg, msg_list);
1128                         list_del(&msg2->msg_list);
1129                         spin_unlock(&txpeer->lpni_lock);
1130
1131                         LASSERT(msg2->msg_txpeer == txpeer);
1132                         LASSERT(msg2->msg_tx_delayed);
1133
1134                         msg2_cpt = msg2->msg_tx_cpt;
1135
1136                         /*
1137                          * The msg_cpt can be different from the msg2_cpt
1138                          * so we need to make sure we lock the correct cpt
1139                          * for msg2.
1140                          * Once we call lnet_post_send_locked() it is no
1141                          * longer safe to access msg2, since it could've
1142                          * been freed by lnet_finalize(), but we still
1143                          * need to relock the correct cpt, so we cache the
1144                          * msg2_cpt for the purpose of the check that
1145                          * follows the call to lnet_pose_send_locked().
1146                          */
1147                         if (msg2_cpt != msg->msg_tx_cpt) {
1148                                 lnet_net_unlock(msg->msg_tx_cpt);
1149                                 lnet_net_lock(msg2_cpt);
1150                         }
1151                         (void) lnet_post_send_locked(msg2, 1);
1152                         if (msg2_cpt != msg->msg_tx_cpt) {
1153                                 lnet_net_unlock(msg2_cpt);
1154                                 lnet_net_lock(msg->msg_tx_cpt);
1155                         }
1156                 } else {
1157                         spin_unlock(&txpeer->lpni_lock);
1158                 }
1159         }
1160
1161         if (txni != NULL) {
1162                 msg->msg_txni = NULL;
1163                 lnet_ni_decref_locked(txni, msg->msg_tx_cpt);
1164         }
1165
1166         if (txpeer != NULL) {
1167                 msg->msg_txpeer = NULL;
1168                 lnet_peer_ni_decref_locked(txpeer);
1169         }
1170 }
1171
1172 void
1173 lnet_schedule_blocked_locked(struct lnet_rtrbufpool *rbp)
1174 {
1175         struct lnet_msg *msg;
1176
1177         if (list_empty(&rbp->rbp_msgs))
1178                 return;
1179         msg = list_entry(rbp->rbp_msgs.next,
1180                          struct lnet_msg, msg_list);
1181         list_del(&msg->msg_list);
1182
1183         (void)lnet_post_routed_recv_locked(msg, 1);
1184 }
1185
1186 void
1187 lnet_drop_routed_msgs_locked(struct list_head *list, int cpt)
1188 {
1189         struct lnet_msg *msg;
1190         struct lnet_msg *tmp;
1191
1192         lnet_net_unlock(cpt);
1193
1194         list_for_each_entry_safe(msg, tmp, list, msg_list) {
1195                 lnet_ni_recv(msg->msg_rxni, msg->msg_private, NULL,
1196                              0, 0, 0, msg->msg_hdr.payload_length);
1197                 list_del_init(&msg->msg_list);
1198                 msg->msg_no_resend = true;
1199                 msg->msg_health_status = LNET_MSG_STATUS_REMOTE_ERROR;
1200                 lnet_finalize(msg, -ECANCELED);
1201         }
1202
1203         lnet_net_lock(cpt);
1204 }
1205
1206 void
1207 lnet_return_rx_credits_locked(struct lnet_msg *msg)
1208 {
1209         struct lnet_peer_ni *rxpeerni = msg->msg_rxpeer;
1210         struct lnet_peer *lp;
1211         struct lnet_ni *rxni = msg->msg_rxni;
1212         struct lnet_msg *msg2;
1213
1214         if (msg->msg_rtrcredit) {
1215                 /* give back global router credits */
1216                 struct lnet_rtrbuf *rb;
1217                 struct lnet_rtrbufpool *rbp;
1218
1219                 /* NB If a msg ever blocks for a buffer in rbp_msgs, it stays
1220                  * there until it gets one allocated, or aborts the wait
1221                  * itself */
1222                 LASSERT(msg->msg_kiov != NULL);
1223
1224                 rb = list_entry(msg->msg_kiov, struct lnet_rtrbuf, rb_kiov[0]);
1225                 rbp = rb->rb_pool;
1226
1227                 msg->msg_kiov = NULL;
1228                 msg->msg_rtrcredit = 0;
1229
1230                 LASSERT(rbp == lnet_msg2bufpool(msg));
1231
1232                 LASSERT((rbp->rbp_credits > 0) ==
1233                         !list_empty(&rbp->rbp_bufs));
1234
1235                 /* If routing is now turned off, we just drop this buffer and
1236                  * don't bother trying to return credits.  */
1237                 if (!the_lnet.ln_routing) {
1238                         lnet_destroy_rtrbuf(rb, rbp->rbp_npages);
1239                         goto routing_off;
1240                 }
1241
1242                 /* It is possible that a user has lowered the desired number of
1243                  * buffers in this pool.  Make sure we never put back
1244                  * more buffers than the stated number. */
1245                 if (unlikely(rbp->rbp_credits >= rbp->rbp_req_nbuffers)) {
1246                         /* Discard this buffer so we don't have too
1247                          * many. */
1248                         lnet_destroy_rtrbuf(rb, rbp->rbp_npages);
1249                         rbp->rbp_nbuffers--;
1250                 } else {
1251                         list_add(&rb->rb_list, &rbp->rbp_bufs);
1252                         rbp->rbp_credits++;
1253                         if (rbp->rbp_credits <= 0)
1254                                 lnet_schedule_blocked_locked(rbp);
1255                 }
1256         }
1257
1258 routing_off:
1259         if (msg->msg_peerrtrcredit) {
1260                 LASSERT(rxpeerni);
1261                 LASSERT(rxpeerni->lpni_peer_net);
1262                 LASSERT(rxpeerni->lpni_peer_net->lpn_peer);
1263
1264                 lp = rxpeerni->lpni_peer_net->lpn_peer;
1265
1266                 /* give back peer router credits */
1267                 msg->msg_peerrtrcredit = 0;
1268
1269                 spin_lock(&rxpeerni->lpni_lock);
1270                 spin_lock(&lp->lp_lock);
1271
1272                 rxpeerni->lpni_rtrcredits++;
1273
1274                 /* drop all messages which are queued to be routed on that
1275                  * peer. */
1276                 if (!the_lnet.ln_routing) {
1277                         struct list_head drop;
1278                         INIT_LIST_HEAD(&drop);
1279                         list_splice_init(&lp->lp_rtrq, &drop);
1280                         spin_unlock(&lp->lp_lock);
1281                         spin_unlock(&rxpeerni->lpni_lock);
1282                         lnet_drop_routed_msgs_locked(&drop, msg->msg_rx_cpt);
1283                 } else if (!list_empty(&lp->lp_rtrq)) {
1284                         int msg2_cpt;
1285
1286                         msg2 = list_entry(lp->lp_rtrq.next,
1287                                           struct lnet_msg, msg_list);
1288                         list_del(&msg2->msg_list);
1289                         msg2_cpt = msg2->msg_rx_cpt;
1290                         spin_unlock(&lp->lp_lock);
1291                         spin_unlock(&rxpeerni->lpni_lock);
1292                         /*
1293                          * messages on the lp_rtrq can be from any NID in
1294                          * the peer, which means they might have different
1295                          * cpts. We need to make sure we lock the right
1296                          * one.
1297                          */
1298                         if (msg2_cpt != msg->msg_rx_cpt) {
1299                                 lnet_net_unlock(msg->msg_rx_cpt);
1300                                 lnet_net_lock(msg2_cpt);
1301                         }
1302                         (void) lnet_post_routed_recv_locked(msg2, 1);
1303                         if (msg2_cpt != msg->msg_rx_cpt) {
1304                                 lnet_net_unlock(msg2_cpt);
1305                                 lnet_net_lock(msg->msg_rx_cpt);
1306                         }
1307                 } else {
1308                         spin_unlock(&lp->lp_lock);
1309                         spin_unlock(&rxpeerni->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 (rxpeerni != NULL) {
1317                 msg->msg_rxpeer = NULL;
1318                 lnet_peer_ni_decref_locked(rxpeerni);
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 struct lnet_peer_ni *
1341 lnet_select_peer_ni(struct lnet_ni *best_ni, lnet_nid_t dst_nid,
1342                     struct lnet_peer *peer,
1343                     struct lnet_peer_net *peer_net)
1344 {
1345         /*
1346          * Look at the peer NIs for the destination peer that connect
1347          * to the chosen net. If a peer_ni is preferred when using the
1348          * best_ni to communicate, we use that one. If there is no
1349          * preferred peer_ni, or there are multiple preferred peer_ni,
1350          * the available transmit credits are used. If the transmit
1351          * credits are equal, we round-robin over the peer_ni.
1352          */
1353         struct lnet_peer_ni *lpni = NULL;
1354         struct lnet_peer_ni *best_lpni = NULL;
1355         int best_lpni_credits = INT_MIN;
1356         bool preferred = false;
1357         bool ni_is_pref;
1358         int best_lpni_healthv = 0;
1359         int lpni_healthv;
1360
1361         while ((lpni = lnet_get_next_peer_ni_locked(peer, peer_net, lpni))) {
1362                 /*
1363                  * if the best_ni we've chosen aleady has this lpni
1364                  * preferred, then let's use it
1365                  */
1366                 if (best_ni) {
1367                         ni_is_pref = lnet_peer_is_pref_nid_locked(lpni,
1368                                                                 best_ni->ni_nid);
1369                         CDEBUG(D_NET, "%s ni_is_pref = %d\n",
1370                                libcfs_nid2str(best_ni->ni_nid), ni_is_pref);
1371                 } else {
1372                         ni_is_pref = false;
1373                 }
1374
1375                 lpni_healthv = atomic_read(&lpni->lpni_healthv);
1376
1377                 if (best_lpni)
1378                         CDEBUG(D_NET, "%s c:[%d, %d], s:[%d, %d]\n",
1379                                 libcfs_nid2str(lpni->lpni_nid),
1380                                 lpni->lpni_txcredits, best_lpni_credits,
1381                                 lpni->lpni_seq, best_lpni->lpni_seq);
1382
1383                 /* pick the healthiest peer ni */
1384                 if (lpni_healthv < best_lpni_healthv) {
1385                         continue;
1386                 } else if (lpni_healthv > best_lpni_healthv) {
1387                         best_lpni_healthv = lpni_healthv;
1388                 /* if this is a preferred peer use it */
1389                 } else if (!preferred && ni_is_pref) {
1390                         preferred = true;
1391                 } else if (preferred && !ni_is_pref) {
1392                         /*
1393                          * this is not the preferred peer so let's ignore
1394                          * it.
1395                          */
1396                         continue;
1397                 } else if (lpni->lpni_txcredits < best_lpni_credits) {
1398                         /*
1399                          * We already have a peer that has more credits
1400                          * available than this one. No need to consider
1401                          * this peer further.
1402                          */
1403                         continue;
1404                 } else if (lpni->lpni_txcredits == best_lpni_credits) {
1405                         /*
1406                          * The best peer found so far and the current peer
1407                          * have the same number of available credits let's
1408                          * make sure to select between them using Round
1409                          * Robin
1410                          */
1411                         if (best_lpni) {
1412                                 if (best_lpni->lpni_seq <= lpni->lpni_seq)
1413                                         continue;
1414                         }
1415                 }
1416
1417                 best_lpni = lpni;
1418                 best_lpni_credits = lpni->lpni_txcredits;
1419         }
1420
1421         /* if we still can't find a peer ni then we can't reach it */
1422         if (!best_lpni) {
1423                 __u32 net_id = (peer_net) ? peer_net->lpn_net_id :
1424                         LNET_NIDNET(dst_nid);
1425                 CDEBUG(D_NET, "no peer_ni found on peer net %s\n",
1426                                 libcfs_net2str(net_id));
1427                 return NULL;
1428         }
1429
1430         CDEBUG(D_NET, "sd_best_lpni = %s\n",
1431                libcfs_nid2str(best_lpni->lpni_nid));
1432
1433         return best_lpni;
1434 }
1435
1436 /*
1437  * Prerequisite: the best_ni should already be set in the sd
1438  */
1439 static inline struct lnet_peer_ni *
1440 lnet_find_best_lpni_on_net(struct lnet_send_data *sd, struct lnet_peer *peer,
1441                            __u32 net_id)
1442 {
1443         struct lnet_peer_net *peer_net;
1444
1445         /*
1446          * The gateway is Multi-Rail capable so now we must select the
1447          * proper peer_ni
1448          */
1449         peer_net = lnet_peer_get_net_locked(peer, net_id);
1450
1451         if (!peer_net) {
1452                 CERROR("gateway peer %s has no NI on net %s\n",
1453                        libcfs_nid2str(peer->lp_primary_nid),
1454                        libcfs_net2str(net_id));
1455                 return NULL;
1456         }
1457
1458         return lnet_select_peer_ni(sd->sd_best_ni, sd->sd_dst_nid,
1459                                    peer, peer_net);
1460 }
1461
1462 static int
1463 lnet_compare_routes(struct lnet_route *r1, struct lnet_route *r2,
1464                     struct lnet_peer_ni **best_lpni)
1465 {
1466         int r1_hops = (r1->lr_hops == LNET_UNDEFINED_HOPS) ? 1 : r1->lr_hops;
1467         int r2_hops = (r2->lr_hops == LNET_UNDEFINED_HOPS) ? 1 : r2->lr_hops;
1468         struct lnet_peer *lp1 = r1->lr_gateway;
1469         struct lnet_peer *lp2 = r2->lr_gateway;
1470         struct lnet_peer_ni *lpni1;
1471         struct lnet_peer_ni *lpni2;
1472         struct lnet_send_data sd;
1473         int rc;
1474
1475         sd.sd_best_ni = NULL;
1476         sd.sd_dst_nid = LNET_NID_ANY;
1477         lpni1 = lnet_find_best_lpni_on_net(&sd, lp1, r1->lr_lnet);
1478         lpni2 = lnet_find_best_lpni_on_net(&sd, lp2, r2->lr_lnet);
1479         LASSERT(lpni1 && lpni2);
1480
1481         if (r1->lr_priority < r2->lr_priority) {
1482                 *best_lpni = lpni1;
1483                 return 1;
1484         }
1485
1486         if (r1->lr_priority > r2->lr_priority) {
1487                 *best_lpni = lpni2;
1488                 return -1;
1489         }
1490
1491         if (r1_hops < r2_hops) {
1492                 *best_lpni = lpni1;
1493                 return 1;
1494         }
1495
1496         if (r1_hops > r2_hops) {
1497                 *best_lpni = lpni2;
1498                 return -1;
1499         }
1500
1501         rc = lnet_compare_peers(lpni1, lpni2);
1502         if (rc == 1) {
1503                 *best_lpni = lpni1;
1504                 return rc;
1505         } else if (rc == -1) {
1506                 *best_lpni = lpni2;
1507                 return rc;
1508         }
1509
1510         if (r1->lr_seq - r2->lr_seq <= 0) {
1511                 *best_lpni = lpni1;
1512                 return 1;
1513         }
1514
1515         *best_lpni = lpni2;
1516         return -1;
1517 }
1518
1519 static struct lnet_route *
1520 lnet_find_route_locked(struct lnet_net *net, __u32 remote_net,
1521                        lnet_nid_t rtr_nid, struct lnet_route **prev_route,
1522                        struct lnet_peer_ni **gwni)
1523 {
1524         struct lnet_peer_ni *best_gw_ni = NULL;
1525         struct lnet_route *best_route;
1526         struct lnet_route *last_route;
1527         struct lnet_remotenet *rnet;
1528         struct lnet_peer *lp_best;
1529         struct lnet_route *route;
1530         struct lnet_peer *lp;
1531         int rc;
1532
1533         /* If @rtr_nid is not LNET_NID_ANY, return the gateway with
1534          * rtr_nid nid, otherwise find the best gateway I can use */
1535
1536         rnet = lnet_find_rnet_locked(remote_net);
1537         if (rnet == NULL)
1538                 return NULL;
1539
1540         lp_best = NULL;
1541         best_route = last_route = NULL;
1542         list_for_each_entry(route, &rnet->lrn_routes, lr_list) {
1543                 lp = route->lr_gateway;
1544
1545                 if (!lnet_is_route_alive(route))
1546                         continue;
1547
1548                 if (lp_best == NULL) {
1549                         best_route = last_route = route;
1550                         lp_best = lp;
1551                 }
1552
1553                 /* no protection on below fields, but it's harmless */
1554                 if (last_route->lr_seq - route->lr_seq < 0)
1555                         last_route = route;
1556
1557                 rc = lnet_compare_routes(route, best_route, &best_gw_ni);
1558                 if (rc < 0)
1559                         continue;
1560
1561                 best_route = route;
1562                 lp_best = lp;
1563         }
1564
1565         *prev_route = last_route;
1566         *gwni = best_gw_ni;
1567
1568         return best_route;
1569 }
1570
1571 static struct lnet_ni *
1572 lnet_get_best_ni(struct lnet_net *local_net, struct lnet_ni *best_ni,
1573                  struct lnet_peer *peer, struct lnet_peer_net *peer_net,
1574                  int md_cpt)
1575 {
1576         struct lnet_ni *ni = NULL;
1577         unsigned int shortest_distance;
1578         int best_credits;
1579         int best_healthv;
1580
1581         /*
1582          * If there is no peer_ni that we can send to on this network,
1583          * then there is no point in looking for a new best_ni here.
1584         */
1585         if (!lnet_get_next_peer_ni_locked(peer, peer_net, NULL))
1586                 return best_ni;
1587
1588         if (best_ni == NULL) {
1589                 shortest_distance = UINT_MAX;
1590                 best_credits = INT_MIN;
1591                 best_healthv = 0;
1592         } else {
1593                 shortest_distance = cfs_cpt_distance(lnet_cpt_table(), md_cpt,
1594                                                      best_ni->ni_dev_cpt);
1595                 best_credits = atomic_read(&best_ni->ni_tx_credits);
1596                 best_healthv = atomic_read(&best_ni->ni_healthv);
1597         }
1598
1599         while ((ni = lnet_get_next_ni_locked(local_net, ni))) {
1600                 unsigned int distance;
1601                 int ni_credits;
1602                 int ni_healthv;
1603                 int ni_fatal;
1604
1605                 ni_credits = atomic_read(&ni->ni_tx_credits);
1606                 ni_healthv = atomic_read(&ni->ni_healthv);
1607                 ni_fatal = atomic_read(&ni->ni_fatal_error_on);
1608
1609                 /*
1610                  * calculate the distance from the CPT on which
1611                  * the message memory is allocated to the CPT of
1612                  * the NI's physical device
1613                  */
1614                 distance = cfs_cpt_distance(lnet_cpt_table(),
1615                                             md_cpt,
1616                                             ni->ni_dev_cpt);
1617
1618                 CDEBUG(D_NET, "compare ni %s [c:%d, d:%d, s:%d] with best_ni %s [c:%d, d:%d, s:%d]\n",
1619                        libcfs_nid2str(ni->ni_nid), ni_credits, distance,
1620                        ni->ni_seq, (best_ni) ? libcfs_nid2str(best_ni->ni_nid)
1621                         : "not seleced", best_credits, shortest_distance,
1622                         (best_ni) ? best_ni->ni_seq : 0);
1623
1624                 /*
1625                  * All distances smaller than the NUMA range
1626                  * are treated equally.
1627                  */
1628                 if (distance < lnet_numa_range)
1629                         distance = lnet_numa_range;
1630
1631                 /*
1632                  * Select on health, shorter distance, available
1633                  * credits, then round-robin.
1634                  */
1635                 if (ni_fatal) {
1636                         continue;
1637                 } else if (ni_healthv < best_healthv) {
1638                         continue;
1639                 } else if (ni_healthv > best_healthv) {
1640                         best_healthv = ni_healthv;
1641                         /*
1642                          * If we're going to prefer this ni because it's
1643                          * the healthiest, then we should set the
1644                          * shortest_distance in the algorithm in case
1645                          * there are multiple NIs with the same health but
1646                          * different distances.
1647                          */
1648                         if (distance < shortest_distance)
1649                                 shortest_distance = distance;
1650                 } else if (distance > shortest_distance) {
1651                         continue;
1652                 } else if (distance < shortest_distance) {
1653                         shortest_distance = distance;
1654                 } else if (ni_credits < best_credits) {
1655                         continue;
1656                 } else if (ni_credits == best_credits) {
1657                         if (best_ni && best_ni->ni_seq <= ni->ni_seq)
1658                                 continue;
1659                 }
1660                 best_ni = ni;
1661                 best_credits = ni_credits;
1662         }
1663
1664         CDEBUG(D_NET, "selected best_ni %s\n",
1665                (best_ni) ? libcfs_nid2str(best_ni->ni_nid) : "no selection");
1666
1667         return best_ni;
1668 }
1669
1670 /*
1671  * Traffic to the LNET_RESERVED_PORTAL may not trigger peer discovery,
1672  * because such traffic is required to perform discovery. We therefore
1673  * exclude all GET and PUT on that portal. We also exclude all ACK and
1674  * REPLY traffic, but that is because the portal is not tracked in the
1675  * message structure for these message types. We could restrict this
1676  * further by also checking for LNET_PROTO_PING_MATCHBITS.
1677  */
1678 static bool
1679 lnet_msg_discovery(struct lnet_msg *msg)
1680 {
1681         if (msg->msg_type == LNET_MSG_PUT) {
1682                 if (msg->msg_hdr.msg.put.ptl_index != LNET_RESERVED_PORTAL)
1683                         return true;
1684         } else if (msg->msg_type == LNET_MSG_GET) {
1685                 if (msg->msg_hdr.msg.get.ptl_index != LNET_RESERVED_PORTAL)
1686                         return true;
1687         }
1688         return false;
1689 }
1690
1691 #define SRC_SPEC        0x0001
1692 #define SRC_ANY         0x0002
1693 #define LOCAL_DST       0x0004
1694 #define REMOTE_DST      0x0008
1695 #define MR_DST          0x0010
1696 #define NMR_DST         0x0020
1697 #define SND_RESP        0x0040
1698
1699 /* The following to defines are used for return codes */
1700 #define REPEAT_SEND     0x1000
1701 #define PASS_THROUGH    0x2000
1702
1703 /* The different cases lnet_select pathway needs to handle */
1704 #define SRC_SPEC_LOCAL_MR_DST   (SRC_SPEC | LOCAL_DST | MR_DST)
1705 #define SRC_SPEC_ROUTER_MR_DST  (SRC_SPEC | REMOTE_DST | MR_DST)
1706 #define SRC_SPEC_LOCAL_NMR_DST  (SRC_SPEC | LOCAL_DST | NMR_DST)
1707 #define SRC_SPEC_ROUTER_NMR_DST (SRC_SPEC | REMOTE_DST | NMR_DST)
1708 #define SRC_ANY_LOCAL_MR_DST    (SRC_ANY | LOCAL_DST | MR_DST)
1709 #define SRC_ANY_ROUTER_MR_DST   (SRC_ANY | REMOTE_DST | MR_DST)
1710 #define SRC_ANY_LOCAL_NMR_DST   (SRC_ANY | LOCAL_DST | NMR_DST)
1711 #define SRC_ANY_ROUTER_NMR_DST  (SRC_ANY | REMOTE_DST | NMR_DST)
1712
1713 static int
1714 lnet_handle_lo_send(struct lnet_send_data *sd)
1715 {
1716         struct lnet_msg *msg = sd->sd_msg;
1717         int cpt = sd->sd_cpt;
1718
1719         /* No send credit hassles with LOLND */
1720         lnet_ni_addref_locked(the_lnet.ln_loni, cpt);
1721         msg->msg_hdr.dest_nid = cpu_to_le64(the_lnet.ln_loni->ni_nid);
1722         if (!msg->msg_routing)
1723                 msg->msg_hdr.src_nid =
1724                         cpu_to_le64(the_lnet.ln_loni->ni_nid);
1725         msg->msg_target.nid = the_lnet.ln_loni->ni_nid;
1726         lnet_msg_commit(msg, cpt);
1727         msg->msg_txni = the_lnet.ln_loni;
1728
1729         return LNET_CREDIT_OK;
1730 }
1731
1732 static int
1733 lnet_handle_send(struct lnet_send_data *sd)
1734 {
1735         struct lnet_ni *best_ni = sd->sd_best_ni;
1736         struct lnet_peer_ni *best_lpni = sd->sd_best_lpni;
1737         struct lnet_peer_ni *final_dst_lpni = sd->sd_final_dst_lpni;
1738         struct lnet_msg *msg = sd->sd_msg;
1739         int cpt2;
1740         __u32 send_case = sd->sd_send_case;
1741         int rc;
1742         __u32 routing = send_case & REMOTE_DST;
1743          struct lnet_rsp_tracker *rspt;
1744
1745         /*
1746          * Increment sequence number of the selected peer so that we
1747          * pick the next one in Round Robin.
1748          */
1749         best_lpni->lpni_seq++;
1750
1751         /*
1752          * grab a reference on the peer_ni so it sticks around even if
1753          * we need to drop and relock the lnet_net_lock below.
1754          */
1755         lnet_peer_ni_addref_locked(best_lpni);
1756
1757         /*
1758          * Use lnet_cpt_of_nid() to determine the CPT used to commit the
1759          * message. This ensures that we get a CPT that is correct for
1760          * the NI when the NI has been restricted to a subset of all CPTs.
1761          * If the selected CPT differs from the one currently locked, we
1762          * must unlock and relock the lnet_net_lock(), and then check whether
1763          * the configuration has changed. We don't have a hold on the best_ni
1764          * yet, and it may have vanished.
1765          */
1766         cpt2 = lnet_cpt_of_nid_locked(best_lpni->lpni_nid, best_ni);
1767         if (sd->sd_cpt != cpt2) {
1768                 __u32 seq = lnet_get_dlc_seq_locked();
1769                 lnet_net_unlock(sd->sd_cpt);
1770                 sd->sd_cpt = cpt2;
1771                 lnet_net_lock(sd->sd_cpt);
1772                 if (seq != lnet_get_dlc_seq_locked()) {
1773                         lnet_peer_ni_decref_locked(best_lpni);
1774                         return REPEAT_SEND;
1775                 }
1776         }
1777
1778         /*
1779          * store the best_lpni in the message right away to avoid having
1780          * to do the same operation under different conditions
1781          */
1782         msg->msg_txpeer = best_lpni;
1783         msg->msg_txni = best_ni;
1784
1785         /*
1786          * grab a reference for the best_ni since now it's in use in this
1787          * send. The reference will be dropped in lnet_finalize()
1788          */
1789         lnet_ni_addref_locked(msg->msg_txni, sd->sd_cpt);
1790
1791         /*
1792          * Always set the target.nid to the best peer picked. Either the
1793          * NID will be one of the peer NIDs selected, or the same NID as
1794          * what was originally set in the target or it will be the NID of
1795          * a router if this message should be routed
1796          */
1797         msg->msg_target.nid = msg->msg_txpeer->lpni_nid;
1798
1799         /*
1800          * lnet_msg_commit assigns the correct cpt to the message, which
1801          * is used to decrement the correct refcount on the ni when it's
1802          * time to return the credits
1803          */
1804         lnet_msg_commit(msg, sd->sd_cpt);
1805
1806         /*
1807          * If we are routing the message then we keep the src_nid that was
1808          * set by the originator. If we are not routing then we are the
1809          * originator and set it here.
1810          */
1811         if (!msg->msg_routing)
1812                 msg->msg_hdr.src_nid = cpu_to_le64(msg->msg_txni->ni_nid);
1813
1814         if (routing) {
1815                 msg->msg_target_is_router = 1;
1816                 msg->msg_target.pid = LNET_PID_LUSTRE;
1817                 /*
1818                  * since we're routing we want to ensure that the
1819                  * msg_hdr.dest_nid is set to the final destination. When
1820                  * the router receives this message it knows how to route
1821                  * it.
1822                  *
1823                  * final_dst_lpni is set at the beginning of the
1824                  * lnet_select_pathway() function and is never changed.
1825                  * It's safe to use it here.
1826                  */
1827                 msg->msg_hdr.dest_nid = cpu_to_le64(final_dst_lpni->lpni_nid);
1828         } else {
1829                 /*
1830                  * if we're not routing set the dest_nid to the best peer
1831                  * ni NID that we picked earlier in the algorithm.
1832                  */
1833                 msg->msg_hdr.dest_nid = cpu_to_le64(msg->msg_txpeer->lpni_nid);
1834         }
1835
1836         /*
1837          * if we have response tracker block update it with the next hop
1838          * nid
1839          */
1840         if (msg->msg_md) {
1841                 rspt = msg->msg_md->md_rspt_ptr;
1842                 if (rspt) {
1843                         rspt->rspt_next_hop_nid = msg->msg_txpeer->lpni_nid;
1844                         CDEBUG(D_NET, "rspt_next_hop_nid = %s\n",
1845                                libcfs_nid2str(rspt->rspt_next_hop_nid));
1846                 }
1847         }
1848
1849         rc = lnet_post_send_locked(msg, 0);
1850
1851         if (!rc)
1852                 CDEBUG(D_NET, "TRACE: %s(%s:%s) -> %s(%s:%s) : %s try# %d\n",
1853                        libcfs_nid2str(msg->msg_hdr.src_nid),
1854                        libcfs_nid2str(msg->msg_txni->ni_nid),
1855                        libcfs_nid2str(sd->sd_src_nid),
1856                        libcfs_nid2str(msg->msg_hdr.dest_nid),
1857                        libcfs_nid2str(sd->sd_dst_nid),
1858                        libcfs_nid2str(msg->msg_txpeer->lpni_nid),
1859                        lnet_msgtyp2str(msg->msg_type), msg->msg_retry_count);
1860
1861         return rc;
1862 }
1863
1864 static inline void
1865 lnet_set_non_mr_pref_nid(struct lnet_send_data *sd)
1866 {
1867         if (sd->sd_send_case & NMR_DST &&
1868             sd->sd_msg->msg_type != LNET_MSG_REPLY &&
1869             sd->sd_msg->msg_type != LNET_MSG_ACK &&
1870             sd->sd_best_lpni->lpni_pref_nnids == 0) {
1871                 CDEBUG(D_NET, "Setting preferred local NID %s on NMR peer %s\n",
1872                        libcfs_nid2str(sd->sd_best_ni->ni_nid),
1873                        libcfs_nid2str(sd->sd_best_lpni->lpni_nid));
1874                 lnet_peer_ni_set_non_mr_pref_nid(sd->sd_best_lpni,
1875                                                  sd->sd_best_ni->ni_nid);
1876         }
1877 }
1878
1879 /*
1880  * Source Specified
1881  * Local Destination
1882  * non-mr peer
1883  *
1884  * use the source and destination NIDs as the pathway
1885  */
1886 static int
1887 lnet_handle_spec_local_nmr_dst(struct lnet_send_data *sd)
1888 {
1889         /* the destination lpni is set before we get here. */
1890
1891         /* find local NI */
1892         sd->sd_best_ni = lnet_nid2ni_locked(sd->sd_src_nid, sd->sd_cpt);
1893         if (!sd->sd_best_ni) {
1894                 CERROR("Can't send to %s: src %s is not a "
1895                        "local nid\n", libcfs_nid2str(sd->sd_dst_nid),
1896                                 libcfs_nid2str(sd->sd_src_nid));
1897                 return -EINVAL;
1898         }
1899
1900         /*
1901          * the preferred NID will only be set for NMR peers
1902          */
1903         lnet_set_non_mr_pref_nid(sd);
1904
1905         return lnet_handle_send(sd);
1906 }
1907
1908 /*
1909  * Source Specified
1910  * Local Destination
1911  * MR Peer
1912  *
1913  * Run the selection algorithm on the peer NIs unless we're sending
1914  * a response, in this case just send to the destination
1915  */
1916 static int
1917 lnet_handle_spec_local_mr_dst(struct lnet_send_data *sd)
1918 {
1919         sd->sd_best_ni = lnet_nid2ni_locked(sd->sd_src_nid, sd->sd_cpt);
1920         if (!sd->sd_best_ni) {
1921                 CERROR("Can't send to %s: src %s is not a "
1922                        "local nid\n", libcfs_nid2str(sd->sd_dst_nid),
1923                                 libcfs_nid2str(sd->sd_src_nid));
1924                 return -EINVAL;
1925         }
1926
1927         /*
1928          * only run the selection algorithm to pick the peer_ni if we're
1929          * sending a GET or a PUT. Responses are sent to the same
1930          * destination NID provided.
1931          */
1932         if (!(sd->sd_send_case & SND_RESP)) {
1933                 sd->sd_best_lpni =
1934                   lnet_find_best_lpni_on_net(sd, sd->sd_peer,
1935                                              sd->sd_best_ni->ni_net->net_id);
1936         }
1937
1938         if (sd->sd_best_lpni &&
1939             sd->sd_best_lpni->lpni_nid == the_lnet.ln_loni->ni_nid)
1940                 return lnet_handle_lo_send(sd);
1941         else if (sd->sd_best_lpni)
1942                 return lnet_handle_send(sd);
1943
1944         CERROR("can't send to %s. no NI on %s\n",
1945                libcfs_nid2str(sd->sd_dst_nid),
1946                libcfs_net2str(sd->sd_best_ni->ni_net->net_id));
1947
1948         return -EHOSTUNREACH;
1949 }
1950
1951 struct lnet_ni *
1952 lnet_find_best_ni_on_spec_net(struct lnet_ni *cur_best_ni,
1953                               struct lnet_peer *peer,
1954                               struct lnet_peer_net *peer_net,
1955                               int cpt,
1956                               bool incr_seq)
1957 {
1958         struct lnet_net *local_net;
1959         struct lnet_ni *best_ni;
1960
1961         local_net = lnet_get_net_locked(peer_net->lpn_net_id);
1962         if (!local_net)
1963                 return NULL;
1964
1965         /*
1966          * Iterate through the NIs in this local Net and select
1967          * the NI to send from. The selection is determined by
1968          * these 3 criterion in the following priority:
1969          *      1. NUMA
1970          *      2. NI available credits
1971          *      3. Round Robin
1972          */
1973         best_ni = lnet_get_best_ni(local_net, cur_best_ni,
1974                                    peer, peer_net, cpt);
1975
1976         if (incr_seq && best_ni)
1977                 best_ni->ni_seq++;
1978
1979         return best_ni;
1980 }
1981
1982 static int
1983 lnet_initiate_peer_discovery(struct lnet_peer_ni *lpni,
1984                              struct lnet_msg *msg, lnet_nid_t rtr_nid,
1985                              int cpt)
1986 {
1987         struct lnet_peer *peer;
1988         lnet_nid_t primary_nid;
1989         int rc;
1990
1991         lnet_peer_ni_addref_locked(lpni);
1992
1993         peer = lpni->lpni_peer_net->lpn_peer;
1994
1995         if (lnet_peer_gw_discovery(peer)) {
1996                 lnet_peer_ni_decref_locked(lpni);
1997                 return 0;
1998         }
1999
2000         if (!lnet_msg_discovery(msg) || lnet_peer_is_uptodate(peer)) {
2001                 lnet_peer_ni_decref_locked(lpni);
2002                 return 0;
2003         }
2004
2005         rc = lnet_discover_peer_locked(lpni, cpt, false);
2006         if (rc) {
2007                 lnet_peer_ni_decref_locked(lpni);
2008                 return rc;
2009         }
2010         /* The peer may have changed. */
2011         peer = lpni->lpni_peer_net->lpn_peer;
2012         spin_lock(&peer->lp_lock);
2013         if (lnet_peer_is_uptodate_locked(peer)) {
2014                 spin_unlock(&peer->lp_lock);
2015                 lnet_peer_ni_decref_locked(lpni);
2016                 return 0;
2017         }
2018         /* queue message and return */
2019         msg->msg_rtr_nid_param = rtr_nid;
2020         msg->msg_sending = 0;
2021         msg->msg_txpeer = NULL;
2022         list_add_tail(&msg->msg_list, &peer->lp_dc_pendq);
2023         primary_nid = peer->lp_primary_nid;
2024         spin_unlock(&peer->lp_lock);
2025
2026         lnet_peer_ni_decref_locked(lpni);
2027
2028         CDEBUG(D_NET, "msg %p delayed. %s pending discovery\n",
2029                 msg, libcfs_nid2str(primary_nid));
2030
2031         return LNET_DC_WAIT;
2032 }
2033
2034 static int
2035 lnet_handle_find_routed_path(struct lnet_send_data *sd,
2036                              lnet_nid_t dst_nid,
2037                              struct lnet_peer_ni **gw_lpni,
2038                              struct lnet_peer **gw_peer)
2039 {
2040         int rc;
2041         struct lnet_peer *gw;
2042         struct lnet_peer *lp;
2043         struct lnet_peer_net *lpn;
2044         struct lnet_peer_net *best_lpn = NULL;
2045         struct lnet_remotenet *rnet;
2046         struct lnet_route *best_route;
2047         struct lnet_route *last_route;
2048         struct lnet_peer_ni *lpni = NULL;
2049         struct lnet_peer_ni *gwni = NULL;
2050         lnet_nid_t src_nid = sd->sd_src_nid;
2051
2052         /* we've already looked up the initial lpni using dst_nid */
2053         lpni = sd->sd_best_lpni;
2054         /* the peer tree must be in existence */
2055         LASSERT(lpni && lpni->lpni_peer_net && lpni->lpni_peer_net->lpn_peer);
2056         lp = lpni->lpni_peer_net->lpn_peer;
2057
2058         list_for_each_entry(lpn, &lp->lp_peer_nets, lpn_peer_nets) {
2059                 /* is this remote network reachable?  */
2060                 rnet = lnet_find_rnet_locked(lpn->lpn_net_id);
2061                 if (!rnet)
2062                         continue;
2063
2064                 if (!best_lpn)
2065                         best_lpn = lpn;
2066
2067                 if (best_lpn->lpn_seq <= lpn->lpn_seq)
2068                         continue;
2069
2070                 best_lpn = lpn;
2071         }
2072
2073         if (!best_lpn) {
2074                 CERROR("peer %s has no available nets \n",
2075                        libcfs_nid2str(sd->sd_dst_nid));
2076                 return -EHOSTUNREACH;
2077         }
2078
2079         sd->sd_best_lpni = lnet_find_best_lpni_on_net(sd, lp, best_lpn->lpn_net_id);
2080         if (!sd->sd_best_lpni) {
2081                 CERROR("peer %s down\n", libcfs_nid2str(sd->sd_dst_nid));
2082                 return -EHOSTUNREACH;
2083         }
2084
2085         best_route = lnet_find_route_locked(NULL, best_lpn->lpn_net_id,
2086                                             sd->sd_rtr_nid, &last_route,
2087                                             &gwni);
2088         if (!best_route) {
2089                 CERROR("no route to %s from %s\n",
2090                        libcfs_nid2str(dst_nid), libcfs_nid2str(src_nid));
2091                 return -EHOSTUNREACH;
2092         }
2093
2094         if (!gwni) {
2095                 CERROR("Internal Error. Route expected to %s from %s\n",
2096                         libcfs_nid2str(dst_nid),
2097                         libcfs_nid2str(src_nid));
2098                 return -EFAULT;
2099         }
2100
2101         gw = best_route->lr_gateway;
2102         LASSERT(gw == gwni->lpni_peer_net->lpn_peer);
2103
2104         /*
2105          * Discover this gateway if it hasn't already been discovered.
2106          * This means we might delay the message until discovery has
2107          * completed
2108          */
2109         sd->sd_msg->msg_src_nid_param = sd->sd_src_nid;
2110         rc = lnet_initiate_peer_discovery(gwni, sd->sd_msg, sd->sd_rtr_nid,
2111                                           sd->sd_cpt);
2112         if (rc)
2113                 return rc;
2114
2115         if (!sd->sd_best_ni)
2116                 sd->sd_best_ni = lnet_find_best_ni_on_spec_net(NULL, gw,
2117                                         lnet_peer_get_net_locked(gw,
2118                                                 best_route->lr_lnet),
2119                                         sd->sd_md_cpt,
2120                                         true);
2121
2122         if (!sd->sd_best_ni) {
2123                 CERROR("Internal Error. Expected local ni on %s "
2124                        "but non found :%s\n",
2125                        libcfs_net2str(best_route->lr_lnet),
2126                        libcfs_nid2str(sd->sd_src_nid));
2127                 return -EFAULT;
2128         }
2129
2130         *gw_lpni = gwni;
2131         *gw_peer = gw;
2132
2133         /*
2134          * increment the sequence numbers since now we're sure we're
2135          * going to use this path
2136          */
2137         LASSERT(best_route && last_route);
2138         best_route->lr_seq = last_route->lr_seq + 1;
2139         best_lpn->lpn_seq++;
2140
2141         return 0;
2142 }
2143
2144 /*
2145  * Handle two cases:
2146  *
2147  * Case 1:
2148  *  Source specified
2149  *  Remote destination
2150  *  Non-MR destination
2151  *
2152  * Case 2:
2153  *  Source specified
2154  *  Remote destination
2155  *  MR destination
2156  *
2157  * The handling of these two cases is similar. Even though the destination
2158  * can be MR or non-MR, we'll deal directly with the router.
2159  */
2160 static int
2161 lnet_handle_spec_router_dst(struct lnet_send_data *sd)
2162 {
2163         int rc;
2164         struct lnet_peer_ni *gw_lpni = NULL;
2165         struct lnet_peer *gw_peer = NULL;
2166
2167         /* find local NI */
2168         sd->sd_best_ni = lnet_nid2ni_locked(sd->sd_src_nid, sd->sd_cpt);
2169         if (!sd->sd_best_ni) {
2170                 CERROR("Can't send to %s: src %s is not a "
2171                        "local nid\n", libcfs_nid2str(sd->sd_dst_nid),
2172                                 libcfs_nid2str(sd->sd_src_nid));
2173                 return -EINVAL;
2174         }
2175
2176         rc = lnet_handle_find_routed_path(sd, sd->sd_dst_nid, &gw_lpni,
2177                                      &gw_peer);
2178         if (rc)
2179                 return rc;
2180
2181         if (sd->sd_send_case & NMR_DST)
2182                 /*
2183                 * since the final destination is non-MR let's set its preferred
2184                 * NID before we send
2185                 */
2186                 lnet_set_non_mr_pref_nid(sd);
2187
2188         /*
2189          * We're going to send to the gw found so let's set its
2190          * info
2191          */
2192         sd->sd_peer = gw_peer;
2193         sd->sd_best_lpni = gw_lpni;
2194
2195         return lnet_handle_send(sd);
2196 }
2197
2198 struct lnet_ni *
2199 lnet_find_best_ni_on_local_net(struct lnet_peer *peer, int md_cpt,
2200                                bool discovery)
2201 {
2202         struct lnet_peer_net *peer_net = NULL;
2203         struct lnet_ni *best_ni = NULL;
2204
2205         /*
2206          * The peer can have multiple interfaces, some of them can be on
2207          * the local network and others on a routed network. We should
2208          * prefer the local network. However if the local network is not
2209          * available then we need to try the routed network
2210          */
2211
2212         /* go through all the peer nets and find the best_ni */
2213         list_for_each_entry(peer_net, &peer->lp_peer_nets, lpn_peer_nets) {
2214                 /*
2215                  * The peer's list of nets can contain non-local nets. We
2216                  * want to only examine the local ones.
2217                  */
2218                 if (!lnet_get_net_locked(peer_net->lpn_net_id))
2219                         continue;
2220                 best_ni = lnet_find_best_ni_on_spec_net(best_ni, peer,
2221                                                    peer_net, md_cpt, false);
2222
2223                 /*
2224                  * if this is a discovery message and lp_disc_net_id is
2225                  * specified then use that net to send the discovery on.
2226                  */
2227                 if (peer->lp_disc_net_id == peer_net->lpn_net_id &&
2228                     discovery)
2229                         break;
2230         }
2231
2232         if (best_ni)
2233                 /* increment sequence number so we can round robin */
2234                 best_ni->ni_seq++;
2235
2236         return best_ni;
2237 }
2238
2239 static struct lnet_ni *
2240 lnet_find_existing_preferred_best_ni(struct lnet_send_data *sd)
2241 {
2242         struct lnet_ni *best_ni = NULL;
2243         struct lnet_peer_net *peer_net;
2244         struct lnet_peer *peer = sd->sd_peer;
2245         struct lnet_peer_ni *best_lpni = sd->sd_best_lpni;
2246         struct lnet_peer_ni *lpni;
2247         int cpt = sd->sd_cpt;
2248
2249         /*
2250          * We must use a consistent source address when sending to a
2251          * non-MR peer. However, a non-MR peer can have multiple NIDs
2252          * on multiple networks, and we may even need to talk to this
2253          * peer on multiple networks -- certain types of
2254          * load-balancing configuration do this.
2255          *
2256          * So we need to pick the NI the peer prefers for this
2257          * particular network.
2258          */
2259
2260         /* Get the target peer_ni */
2261         peer_net = lnet_peer_get_net_locked(peer,
2262                         LNET_NIDNET(best_lpni->lpni_nid));
2263         LASSERT(peer_net != NULL);
2264         list_for_each_entry(lpni, &peer_net->lpn_peer_nis,
2265                                 lpni_peer_nis) {
2266                 if (lpni->lpni_pref_nnids == 0)
2267                         continue;
2268                 LASSERT(lpni->lpni_pref_nnids == 1);
2269                 best_ni = lnet_nid2ni_locked(
2270                                 lpni->lpni_pref.nid, cpt);
2271                 break;
2272         }
2273
2274         return best_ni;
2275 }
2276
2277 /* Prerequisite: sd->sd_peer and sd->sd_best_lpni should be set */
2278 static int
2279 lnet_select_preferred_best_ni(struct lnet_send_data *sd)
2280 {
2281         struct lnet_ni *best_ni = NULL;
2282         struct lnet_peer_ni *best_lpni = sd->sd_best_lpni;
2283
2284         /*
2285          * We must use a consistent source address when sending to a
2286          * non-MR peer. However, a non-MR peer can have multiple NIDs
2287          * on multiple networks, and we may even need to talk to this
2288          * peer on multiple networks -- certain types of
2289          * load-balancing configuration do this.
2290          *
2291          * So we need to pick the NI the peer prefers for this
2292          * particular network.
2293          */
2294
2295         best_ni = lnet_find_existing_preferred_best_ni(sd);
2296
2297         /* if best_ni is still not set just pick one */
2298         if (!best_ni) {
2299                 best_ni =
2300                   lnet_find_best_ni_on_spec_net(NULL, sd->sd_peer,
2301                                                 sd->sd_best_lpni->lpni_peer_net,
2302                                                 sd->sd_md_cpt, true);
2303                 /* If there is no best_ni we don't have a route */
2304                 if (!best_ni) {
2305                         CERROR("no path to %s from net %s\n",
2306                                 libcfs_nid2str(best_lpni->lpni_nid),
2307                                 libcfs_net2str(best_lpni->lpni_net->net_id));
2308                         return -EHOSTUNREACH;
2309                 }
2310         }
2311
2312         sd->sd_best_ni = best_ni;
2313
2314         /* Set preferred NI if necessary. */
2315         lnet_set_non_mr_pref_nid(sd);
2316
2317         return 0;
2318 }
2319
2320
2321 /*
2322  * Source not specified
2323  * Local destination
2324  * Non-MR Peer
2325  *
2326  * always use the same source NID for NMR peers
2327  * If we've talked to that peer before then we already have a preferred
2328  * source NI associated with it. Otherwise, we select a preferred local NI
2329  * and store it in the peer
2330  */
2331 static int
2332 lnet_handle_any_local_nmr_dst(struct lnet_send_data *sd)
2333 {
2334         int rc;
2335
2336         /* sd->sd_best_lpni is already set to the final destination */
2337
2338         /*
2339          * At this point we should've created the peer ni and peer. If we
2340          * can't find it, then something went wrong. Instead of assert
2341          * output a relevant message and fail the send
2342          */
2343         if (!sd->sd_best_lpni) {
2344                 CERROR("Internal fault. Unable to send msg %s to %s. "
2345                        "NID not known\n",
2346                        lnet_msgtyp2str(sd->sd_msg->msg_type),
2347                        libcfs_nid2str(sd->sd_dst_nid));
2348                 return -EFAULT;
2349         }
2350
2351         rc = lnet_select_preferred_best_ni(sd);
2352         if (!rc)
2353                 rc = lnet_handle_send(sd);
2354
2355         return rc;
2356 }
2357
2358 static int
2359 lnet_handle_any_mr_dsta(struct lnet_send_data *sd)
2360 {
2361         /*
2362          * NOTE we've already handled the remote peer case. So we only
2363          * need to worry about the local case here.
2364          *
2365          * if we're sending a response, ACK or reply, we need to send it
2366          * to the destination NID given to us. At this point we already
2367          * have the peer_ni we're suppose to send to, so just find the
2368          * best_ni on the peer net and use that. Since we're sending to an
2369          * MR peer then we can just run the selection algorithm on our
2370          * local NIs and pick the best one.
2371          */
2372         if (sd->sd_send_case & SND_RESP) {
2373                 sd->sd_best_ni =
2374                   lnet_find_best_ni_on_spec_net(NULL, sd->sd_peer,
2375                                                 sd->sd_best_lpni->lpni_peer_net,
2376                                                 sd->sd_md_cpt, true);
2377
2378                 if (!sd->sd_best_ni) {
2379                         /*
2380                          * We're not going to deal with not able to send
2381                          * a response to the provided final destination
2382                          */
2383                         CERROR("Can't send response to %s. "
2384                                "No local NI available\n",
2385                                 libcfs_nid2str(sd->sd_dst_nid));
2386                         return -EHOSTUNREACH;
2387                 }
2388
2389                 return lnet_handle_send(sd);
2390         }
2391
2392         /*
2393          * If we get here that means we're sending a fresh request, PUT or
2394          * GET, so we need to run our standard selection algorithm.
2395          * First find the best local interface that's on any of the peer's
2396          * networks.
2397          */
2398         sd->sd_best_ni = lnet_find_best_ni_on_local_net(sd->sd_peer,
2399                                         sd->sd_md_cpt,
2400                                         lnet_msg_discovery(sd->sd_msg));
2401         if (sd->sd_best_ni) {
2402                 sd->sd_best_lpni =
2403                   lnet_find_best_lpni_on_net(sd, sd->sd_peer,
2404                                              sd->sd_best_ni->ni_net->net_id);
2405
2406                 /*
2407                  * if we're successful in selecting a peer_ni on the local
2408                  * network, then send to it. Otherwise fall through and
2409                  * try and see if we can reach it over another routed
2410                  * network
2411                  */
2412                 if (sd->sd_best_lpni &&
2413                     sd->sd_best_lpni->lpni_nid == the_lnet.ln_loni->ni_nid) {
2414                         /*
2415                          * in case we initially started with a routed
2416                          * destination, let's reset to local
2417                          */
2418                         sd->sd_send_case &= ~REMOTE_DST;
2419                         sd->sd_send_case |= LOCAL_DST;
2420                         return lnet_handle_lo_send(sd);
2421                 } else if (sd->sd_best_lpni) {
2422                         /*
2423                          * in case we initially started with a routed
2424                          * destination, let's reset to local
2425                          */
2426                         sd->sd_send_case &= ~REMOTE_DST;
2427                         sd->sd_send_case |= LOCAL_DST;
2428                         return lnet_handle_send(sd);
2429                 }
2430
2431                 CERROR("Internal Error. Expected to have a best_lpni: "
2432                        "%s -> %s\n",
2433                        libcfs_nid2str(sd->sd_src_nid),
2434                        libcfs_nid2str(sd->sd_dst_nid));
2435
2436                 return -EFAULT;
2437         }
2438
2439         /*
2440          * Peer doesn't have a local network. Let's see if there is
2441          * a remote network we can reach it on.
2442          */
2443         return PASS_THROUGH;
2444 }
2445
2446 /*
2447  * Case 1:
2448  *      Source NID not specified
2449  *      Local destination
2450  *      MR peer
2451  *
2452  * Case 2:
2453  *      Source NID not speified
2454  *      Remote destination
2455  *      MR peer
2456  *
2457  * In both of these cases if we're sending a response, ACK or REPLY, then
2458  * we need to send to the destination NID provided.
2459  *
2460  * In the remote case let's deal with MR routers.
2461  *
2462  */
2463
2464 static int
2465 lnet_handle_any_mr_dst(struct lnet_send_data *sd)
2466 {
2467         int rc = 0;
2468         struct lnet_peer *gw_peer = NULL;
2469         struct lnet_peer_ni *gw_lpni = NULL;
2470
2471         /*
2472          * handle sending a response to a remote peer here so we don't
2473          * have to worry about it if we hit lnet_handle_any_mr_dsta()
2474          */
2475         if (sd->sd_send_case & REMOTE_DST &&
2476             sd->sd_send_case & SND_RESP) {
2477                 struct lnet_peer_ni *gw;
2478                 struct lnet_peer *gw_peer;
2479
2480                 rc = lnet_handle_find_routed_path(sd, sd->sd_dst_nid, &gw,
2481                                                   &gw_peer);
2482                 if (rc < 0) {
2483                         CERROR("Can't send response to %s. "
2484                                "No route available\n",
2485                                 libcfs_nid2str(sd->sd_dst_nid));
2486                         return -EHOSTUNREACH;
2487                 } else if (rc > 0) {
2488                         return rc;
2489                 }
2490
2491                 sd->sd_best_lpni = gw;
2492                 sd->sd_peer = gw_peer;
2493
2494                 return lnet_handle_send(sd);
2495         }
2496
2497         /*
2498          * Even though the NID for the peer might not be on a local network,
2499          * since the peer is MR there could be other interfaces on the
2500          * local network. In that case we'd still like to prefer the local
2501          * network over the routed network. If we're unable to do that
2502          * then we select the best router among the different routed networks,
2503          * and if the router is MR then we can deal with it as such.
2504          */
2505         rc = lnet_handle_any_mr_dsta(sd);
2506         if (rc != PASS_THROUGH)
2507                 return rc;
2508
2509         /*
2510          * Now that we must route to the destination, we must consider the
2511          * MR case, where the destination has multiple interfaces, some of
2512          * which we can route to and others we do not. For this reason we
2513          * need to select the destination which we can route to and if
2514          * there are multiple, we need to round robin.
2515          */
2516         rc = lnet_handle_find_routed_path(sd, sd->sd_dst_nid, &gw_lpni,
2517                                           &gw_peer);
2518         if (rc)
2519                 return rc;
2520
2521         sd->sd_send_case &= ~LOCAL_DST;
2522         sd->sd_send_case |= REMOTE_DST;
2523
2524         sd->sd_peer = gw_peer;
2525         sd->sd_best_lpni = gw_lpni;
2526
2527         return lnet_handle_send(sd);
2528 }
2529
2530 /*
2531  * Source not specified
2532  * Remote destination
2533  * Non-MR peer
2534  *
2535  * Must send to the specified peer NID using the same source NID that
2536  * we've used before. If it's the first time to talk to that peer then
2537  * find the source NI and assign it as preferred to that peer
2538  */
2539 static int
2540 lnet_handle_any_router_nmr_dst(struct lnet_send_data *sd)
2541 {
2542         int rc;
2543         struct lnet_peer_ni *gw_lpni = NULL;
2544         struct lnet_peer *gw_peer = NULL;
2545
2546         /*
2547          * Let's set if we have a preferred NI to talk to this NMR peer
2548          */
2549         sd->sd_best_ni = lnet_find_existing_preferred_best_ni(sd);
2550
2551         /*
2552          * find the router and that'll find the best NI if we didn't find
2553          * it already.
2554          */
2555         rc = lnet_handle_find_routed_path(sd, sd->sd_dst_nid, &gw_lpni,
2556                                           &gw_peer);
2557         if (rc)
2558                 return rc;
2559
2560         /*
2561          * set the best_ni we've chosen as the preferred one for
2562          * this peer
2563          */
2564         lnet_set_non_mr_pref_nid(sd);
2565
2566         /* we'll be sending to the gw */
2567         sd->sd_best_lpni = gw_lpni;
2568         sd->sd_peer = gw_peer;
2569
2570         return lnet_handle_send(sd);
2571 }
2572
2573 static int
2574 lnet_handle_send_case_locked(struct lnet_send_data *sd)
2575 {
2576         /*
2577          * turn off the SND_RESP bit.
2578          * It will be checked in the case handling
2579          */
2580         __u32 send_case = sd->sd_send_case &= ~SND_RESP ;
2581
2582         CDEBUG(D_NET, "Source %s%s to %s %s %s destination\n",
2583                 (send_case & SRC_SPEC) ? "Specified: " : "ANY",
2584                 (send_case & SRC_SPEC) ? libcfs_nid2str(sd->sd_src_nid) : "",
2585                 (send_case & MR_DST) ? "MR: " : "NMR: ",
2586                 libcfs_nid2str(sd->sd_dst_nid),
2587                 (send_case & LOCAL_DST) ? "local" : "routed");
2588
2589         switch (send_case) {
2590         /*
2591          * For all cases where the source is specified, we should always
2592          * use the destination NID, whether it's an MR destination or not,
2593          * since we're continuing a series of related messages for the
2594          * same RPC
2595          */
2596         case SRC_SPEC_LOCAL_NMR_DST:
2597                 return lnet_handle_spec_local_nmr_dst(sd);
2598         case SRC_SPEC_LOCAL_MR_DST:
2599                 return lnet_handle_spec_local_mr_dst(sd);
2600         case SRC_SPEC_ROUTER_NMR_DST:
2601         case SRC_SPEC_ROUTER_MR_DST:
2602                 return lnet_handle_spec_router_dst(sd);
2603         case SRC_ANY_LOCAL_NMR_DST:
2604                 return lnet_handle_any_local_nmr_dst(sd);
2605         case SRC_ANY_LOCAL_MR_DST:
2606         case SRC_ANY_ROUTER_MR_DST:
2607                 return lnet_handle_any_mr_dst(sd);
2608         case SRC_ANY_ROUTER_NMR_DST:
2609                 return lnet_handle_any_router_nmr_dst(sd);
2610         default:
2611                 CERROR("Unknown send case\n");
2612                 return -1;
2613         }
2614 }
2615
2616 static int
2617 lnet_select_pathway(lnet_nid_t src_nid, lnet_nid_t dst_nid,
2618                     struct lnet_msg *msg, lnet_nid_t rtr_nid)
2619 {
2620         struct lnet_peer_ni     *lpni;
2621         struct lnet_peer        *peer;
2622         struct lnet_send_data   send_data;
2623         int                     cpt, rc;
2624         int                     md_cpt;
2625         __u32                   send_case = 0;
2626
2627         memset(&send_data, 0, sizeof(send_data));
2628
2629         /*
2630          * get an initial CPT to use for locking. The idea here is not to
2631          * serialize the calls to select_pathway, so that as many
2632          * operations can run concurrently as possible. To do that we use
2633          * the CPT where this call is being executed. Later on when we
2634          * determine the CPT to use in lnet_message_commit, we switch the
2635          * lock and check if there was any configuration change.  If none,
2636          * then we proceed, if there is, then we restart the operation.
2637          */
2638         cpt = lnet_net_lock_current();
2639
2640         md_cpt = lnet_cpt_of_md(msg->msg_md, msg->msg_offset);
2641         if (md_cpt == CFS_CPT_ANY)
2642                 md_cpt = cpt;
2643
2644 again:
2645
2646         /*
2647          * If we're being asked to send to the loopback interface, there
2648          * is no need to go through any selection. We can just shortcut
2649          * the entire process and send over lolnd
2650          */
2651         send_data.sd_msg = msg;
2652         send_data.sd_cpt = cpt;
2653         if (LNET_NETTYP(LNET_NIDNET(dst_nid)) == LOLND) {
2654                 rc = lnet_handle_lo_send(&send_data);
2655                 lnet_net_unlock(cpt);
2656                 return rc;
2657         }
2658
2659         /*
2660          * find an existing peer_ni, or create one and mark it as having been
2661          * created due to network traffic. This call will create the
2662          * peer->peer_net->peer_ni tree.
2663          */
2664         lpni = lnet_nid2peerni_locked(dst_nid, LNET_NID_ANY, cpt);
2665         if (IS_ERR(lpni)) {
2666                 lnet_net_unlock(cpt);
2667                 return PTR_ERR(lpni);
2668         }
2669
2670         /*
2671          * Cache the original src_nid. If we need to resend the message
2672          * then we'll need to know whether the src_nid was originally
2673          * specified for this message. If it was originally specified,
2674          * then we need to keep using the same src_nid since it's
2675          * continuing the same sequence of messages.
2676          */
2677         msg->msg_src_nid_param = src_nid;
2678
2679         /*
2680          * If necessary, perform discovery on the peer that owns this peer_ni.
2681          * Note, this can result in the ownership of this peer_ni changing
2682          * to another peer object.
2683          */
2684         rc = lnet_initiate_peer_discovery(lpni, msg, rtr_nid, cpt);
2685         if (rc) {
2686                 lnet_peer_ni_decref_locked(lpni);
2687                 lnet_net_unlock(cpt);
2688                 return rc;
2689         }
2690         lnet_peer_ni_decref_locked(lpni);
2691
2692         peer = lpni->lpni_peer_net->lpn_peer;
2693
2694         /*
2695          * Identify the different send cases
2696          */
2697         if (src_nid == LNET_NID_ANY)
2698                 send_case |= SRC_ANY;
2699         else
2700                 send_case |= SRC_SPEC;
2701
2702         if (lnet_get_net_locked(LNET_NIDNET(dst_nid)))
2703                 send_case |= LOCAL_DST;
2704         else
2705                 send_case |= REMOTE_DST;
2706
2707         /*
2708          * if this is a non-MR peer or if we're recovering a peer ni then
2709          * let's consider this an NMR case so we can hit the destination
2710          * NID.
2711          */
2712         if (!lnet_peer_is_multi_rail(peer) || msg->msg_recovery)
2713                 send_case |= NMR_DST;
2714         else
2715                 send_case |= MR_DST;
2716
2717         if (msg->msg_type == LNET_MSG_REPLY ||
2718             msg->msg_type == LNET_MSG_ACK)
2719                 send_case |= SND_RESP;
2720
2721         /* assign parameters to the send_data */
2722         send_data.sd_rtr_nid = rtr_nid;
2723         send_data.sd_src_nid = src_nid;
2724         send_data.sd_dst_nid = dst_nid;
2725         send_data.sd_best_lpni = lpni;
2726         /*
2727          * keep a pointer to the final destination in case we're going to
2728          * route, so we'll need to access it later
2729          */
2730         send_data.sd_final_dst_lpni = lpni;
2731         send_data.sd_peer = peer;
2732         send_data.sd_md_cpt = md_cpt;
2733         send_data.sd_send_case = send_case;
2734
2735         rc = lnet_handle_send_case_locked(&send_data);
2736
2737         /*
2738          * Update the local cpt since send_data.sd_cpt might've been
2739          * updated as a result of calling lnet_handle_send_case_locked().
2740          */
2741         cpt = send_data.sd_cpt;
2742
2743         if (rc == REPEAT_SEND)
2744                 goto again;
2745
2746         lnet_net_unlock(cpt);
2747
2748         return rc;
2749 }
2750
2751 int
2752 lnet_send(lnet_nid_t src_nid, struct lnet_msg *msg, lnet_nid_t rtr_nid)
2753 {
2754         lnet_nid_t              dst_nid = msg->msg_target.nid;
2755         int                     rc;
2756
2757         /*
2758          * NB: rtr_nid is set to LNET_NID_ANY for all current use-cases,
2759          * but we might want to use pre-determined router for ACK/REPLY
2760          * in the future
2761          */
2762         /* NB: ni != NULL == interface pre-determined (ACK/REPLY) */
2763         LASSERT(msg->msg_txpeer == NULL);
2764         LASSERT(msg->msg_txni == NULL);
2765         LASSERT(!msg->msg_sending);
2766         LASSERT(!msg->msg_target_is_router);
2767         LASSERT(!msg->msg_receiving);
2768
2769         msg->msg_sending = 1;
2770
2771         LASSERT(!msg->msg_tx_committed);
2772
2773         rc = lnet_select_pathway(src_nid, dst_nid, msg, rtr_nid);
2774         if (rc < 0) {
2775                 if (rc == -EHOSTUNREACH)
2776                         msg->msg_health_status = LNET_MSG_STATUS_REMOTE_ERROR;
2777                 else
2778                         msg->msg_health_status = LNET_MSG_STATUS_LOCAL_ERROR;
2779                 return rc;
2780         }
2781
2782         if (rc == LNET_CREDIT_OK)
2783                 lnet_ni_send(msg->msg_txni, msg);
2784
2785         /* rc == LNET_CREDIT_OK or LNET_CREDIT_WAIT or LNET_DC_WAIT */
2786         return 0;
2787 }
2788
2789 enum lnet_mt_event_type {
2790         MT_TYPE_LOCAL_NI = 0,
2791         MT_TYPE_PEER_NI
2792 };
2793
2794 struct lnet_mt_event_info {
2795         enum lnet_mt_event_type mt_type;
2796         lnet_nid_t mt_nid;
2797 };
2798
2799 /* called with res_lock held */
2800 void
2801 lnet_detach_rsp_tracker(struct lnet_libmd *md, int cpt)
2802 {
2803         struct lnet_rsp_tracker *rspt;
2804
2805         /*
2806          * msg has a refcount on the MD so the MD is not going away.
2807          * The rspt queue for the cpt is protected by
2808          * the lnet_net_lock(cpt). cpt is the cpt of the MD cookie.
2809          */
2810         if (!md->md_rspt_ptr)
2811                 return;
2812
2813         rspt = md->md_rspt_ptr;
2814
2815         /* debug code */
2816         LASSERT(rspt->rspt_cpt == cpt);
2817
2818         md->md_rspt_ptr = NULL;
2819
2820         if (LNetMDHandleIsInvalid(rspt->rspt_mdh)) {
2821                 /*
2822                  * The monitor thread has invalidated this handle because the
2823                  * response timed out, but it failed to lookup the MD. That
2824                  * means this response tracker is on the zombie list. We can
2825                  * safely remove it under the resource lock (held by caller) and
2826                  * free the response tracker block.
2827                  */
2828                 list_del(&rspt->rspt_on_list);
2829                 lnet_rspt_free(rspt, cpt);
2830         } else {
2831                 /*
2832                  * invalidate the handle to indicate that a response has been
2833                  * received, which will then lead the monitor thread to clean up
2834                  * the rspt block.
2835                  */
2836                 LNetInvalidateMDHandle(&rspt->rspt_mdh);
2837         }
2838 }
2839
2840 void
2841 lnet_clean_zombie_rstqs(void)
2842 {
2843         struct lnet_rsp_tracker *rspt, *tmp;
2844         int i;
2845
2846         cfs_cpt_for_each(i, lnet_cpt_table()) {
2847                 list_for_each_entry_safe(rspt, tmp,
2848                                          the_lnet.ln_mt_zombie_rstqs[i],
2849                                          rspt_on_list) {
2850                         list_del(&rspt->rspt_on_list);
2851                         lnet_rspt_free(rspt, i);
2852                 }
2853         }
2854
2855         cfs_percpt_free(the_lnet.ln_mt_zombie_rstqs);
2856 }
2857
2858 static void
2859 lnet_finalize_expired_responses(void)
2860 {
2861         struct lnet_libmd *md;
2862         struct list_head local_queue;
2863         struct lnet_rsp_tracker *rspt, *tmp;
2864         ktime_t now;
2865         int i;
2866
2867         if (the_lnet.ln_mt_rstq == NULL)
2868                 return;
2869
2870         cfs_cpt_for_each(i, lnet_cpt_table()) {
2871                 INIT_LIST_HEAD(&local_queue);
2872
2873                 lnet_net_lock(i);
2874                 if (!the_lnet.ln_mt_rstq[i]) {
2875                         lnet_net_unlock(i);
2876                         continue;
2877                 }
2878                 list_splice_init(the_lnet.ln_mt_rstq[i], &local_queue);
2879                 lnet_net_unlock(i);
2880
2881                 now = ktime_get();
2882
2883                 list_for_each_entry_safe(rspt, tmp, &local_queue, rspt_on_list) {
2884                         /*
2885                          * The rspt mdh will be invalidated when a response
2886                          * is received or whenever we want to discard the
2887                          * block the monitor thread will walk the queue
2888                          * and clean up any rsts with an invalid mdh.
2889                          * The monitor thread will walk the queue until
2890                          * the first unexpired rspt block. This means that
2891                          * some rspt blocks which received their
2892                          * corresponding responses will linger in the
2893                          * queue until they are cleaned up eventually.
2894                          */
2895                         lnet_res_lock(i);
2896                         if (LNetMDHandleIsInvalid(rspt->rspt_mdh)) {
2897                                 lnet_res_unlock(i);
2898                                 list_del(&rspt->rspt_on_list);
2899                                 lnet_rspt_free(rspt, i);
2900                                 continue;
2901                         }
2902
2903                         if (ktime_compare(now, rspt->rspt_deadline) >= 0 ||
2904                             the_lnet.ln_mt_state == LNET_MT_STATE_SHUTDOWN) {
2905                                 struct lnet_peer_ni *lpni;
2906                                 lnet_nid_t nid;
2907
2908                                 md = lnet_handle2md(&rspt->rspt_mdh);
2909                                 if (!md) {
2910                                         /* MD has been queued for unlink, but
2911                                          * rspt hasn't been detached (Note we've
2912                                          * checked above that the rspt_mdh is
2913                                          * valid). Since we cannot lookup the MD
2914                                          * we're unable to detach the rspt
2915                                          * ourselves. Thus, move the rspt to the
2916                                          * zombie list where we'll wait for
2917                                          * either:
2918                                          *   1. The remaining operations on the
2919                                          *   MD to complete. In this case the
2920                                          *   final operation will result in
2921                                          *   lnet_msg_detach_md()->
2922                                          *   lnet_detach_rsp_tracker() where
2923                                          *   we will clean up this response
2924                                          *   tracker.
2925                                          *   2. LNet to shutdown. In this case
2926                                          *   we'll wait until after all LND Nets
2927                                          *   have shutdown and then we can
2928                                          *   safely free any remaining response
2929                                          *   tracker blocks on the zombie list.
2930                                          * Note: We need to hold the resource
2931                                          * lock when adding to the zombie list
2932                                          * because we may have concurrent access
2933                                          * with lnet_detach_rsp_tracker().
2934                                          */
2935                                         LNetInvalidateMDHandle(&rspt->rspt_mdh);
2936                                         list_move(&rspt->rspt_on_list,
2937                                                   the_lnet.ln_mt_zombie_rstqs[i]);
2938                                         lnet_res_unlock(i);
2939                                         continue;
2940                                 }
2941                                 LASSERT(md->md_rspt_ptr == rspt);
2942                                 md->md_rspt_ptr = NULL;
2943                                 lnet_res_unlock(i);
2944
2945                                 LNetMDUnlink(rspt->rspt_mdh);
2946
2947                                 nid = rspt->rspt_next_hop_nid;
2948
2949                                 list_del(&rspt->rspt_on_list);
2950                                 lnet_rspt_free(rspt, i);
2951
2952                                 /* If we're shutting down we just want to clean
2953                                  * up the rspt blocks
2954                                  */
2955                                 if (the_lnet.ln_mt_state == LNET_MT_STATE_SHUTDOWN)
2956                                         continue;
2957
2958                                 lnet_net_lock(i);
2959                                 the_lnet.ln_counters[i]->lct_health.lch_response_timeout_count++;
2960                                 lnet_net_unlock(i);
2961
2962                                 CDEBUG(D_NET,
2963                                        "Response timeout: md = %p: nid = %s\n",
2964                                        md, libcfs_nid2str(nid));
2965
2966                                 /*
2967                                  * If there is a timeout on the response
2968                                  * from the next hop decrement its health
2969                                  * value so that we don't use it
2970                                  */
2971                                 lnet_net_lock(0);
2972                                 lpni = lnet_find_peer_ni_locked(nid);
2973                                 if (lpni) {
2974                                         lnet_handle_remote_failure_locked(lpni);
2975                                         lnet_peer_ni_decref_locked(lpni);
2976                                 }
2977                                 lnet_net_unlock(0);
2978                         } else {
2979                                 lnet_res_unlock(i);
2980                                 break;
2981                         }
2982                 }
2983
2984                 if (!list_empty(&local_queue)) {
2985                         lnet_net_lock(i);
2986                         list_splice(&local_queue, the_lnet.ln_mt_rstq[i]);
2987                         lnet_net_unlock(i);
2988                 }
2989         }
2990 }
2991
2992 static void
2993 lnet_resend_pending_msgs_locked(struct list_head *resendq, int cpt)
2994 {
2995         struct lnet_msg *msg;
2996
2997         while (!list_empty(resendq)) {
2998                 struct lnet_peer_ni *lpni;
2999
3000                 msg = list_entry(resendq->next, struct lnet_msg,
3001                                  msg_list);
3002
3003                 list_del_init(&msg->msg_list);
3004
3005                 lpni = lnet_find_peer_ni_locked(msg->msg_hdr.dest_nid);
3006                 if (!lpni) {
3007                         lnet_net_unlock(cpt);
3008                         CERROR("Expected that a peer is already created for %s\n",
3009                                libcfs_nid2str(msg->msg_hdr.dest_nid));
3010                         msg->msg_no_resend = true;
3011                         lnet_finalize(msg, -EFAULT);
3012                         lnet_net_lock(cpt);
3013                 } else {
3014                         struct lnet_peer *peer;
3015                         int rc;
3016                         lnet_nid_t src_nid = LNET_NID_ANY;
3017
3018                         /*
3019                          * if this message is not being routed and the
3020                          * peer is non-MR then we must use the same
3021                          * src_nid that was used in the original send.
3022                          * Otherwise if we're routing the message (IE
3023                          * we're a router) then we can use any of our
3024                          * local interfaces. It doesn't matter to the
3025                          * final destination.
3026                          */
3027                         peer = lpni->lpni_peer_net->lpn_peer;
3028                         if (!msg->msg_routing &&
3029                             !lnet_peer_is_multi_rail(peer))
3030                                 src_nid = le64_to_cpu(msg->msg_hdr.src_nid);
3031
3032                         /*
3033                          * If we originally specified a src NID, then we
3034                          * must attempt to reuse it in the resend as well.
3035                          */
3036                         if (msg->msg_src_nid_param != LNET_NID_ANY)
3037                                 src_nid = msg->msg_src_nid_param;
3038                         lnet_peer_ni_decref_locked(lpni);
3039
3040                         lnet_net_unlock(cpt);
3041                         CDEBUG(D_NET, "resending %s->%s: %s recovery %d try# %d\n",
3042                                libcfs_nid2str(src_nid),
3043                                libcfs_id2str(msg->msg_target),
3044                                lnet_msgtyp2str(msg->msg_type),
3045                                msg->msg_recovery,
3046                                msg->msg_retry_count);
3047                         rc = lnet_send(src_nid, msg, LNET_NID_ANY);
3048                         if (rc) {
3049                                 CERROR("Error sending %s to %s: %d\n",
3050                                        lnet_msgtyp2str(msg->msg_type),
3051                                        libcfs_id2str(msg->msg_target), rc);
3052                                 msg->msg_no_resend = true;
3053                                 lnet_finalize(msg, rc);
3054                         }
3055                         lnet_net_lock(cpt);
3056                         if (!rc)
3057                                 the_lnet.ln_counters[cpt]->lct_health.lch_resend_count++;
3058                 }
3059         }
3060 }
3061
3062 static void
3063 lnet_resend_pending_msgs(void)
3064 {
3065         int i;
3066
3067         cfs_cpt_for_each(i, lnet_cpt_table()) {
3068                 lnet_net_lock(i);
3069                 lnet_resend_pending_msgs_locked(the_lnet.ln_mt_resendqs[i], i);
3070                 lnet_net_unlock(i);
3071         }
3072 }
3073
3074 /* called with cpt and ni_lock held */
3075 static void
3076 lnet_unlink_ni_recovery_mdh_locked(struct lnet_ni *ni, int cpt, bool force)
3077 {
3078         struct lnet_handle_md recovery_mdh;
3079
3080         LNetInvalidateMDHandle(&recovery_mdh);
3081
3082         if (ni->ni_recovery_state & LNET_NI_RECOVERY_PENDING ||
3083             force) {
3084                 recovery_mdh = ni->ni_ping_mdh;
3085                 LNetInvalidateMDHandle(&ni->ni_ping_mdh);
3086         }
3087         lnet_ni_unlock(ni);
3088         lnet_net_unlock(cpt);
3089         if (!LNetMDHandleIsInvalid(recovery_mdh))
3090                 LNetMDUnlink(recovery_mdh);
3091         lnet_net_lock(cpt);
3092         lnet_ni_lock(ni);
3093 }
3094
3095 static void
3096 lnet_recover_local_nis(void)
3097 {
3098         struct lnet_mt_event_info *ev_info;
3099         struct list_head processed_list;
3100         struct list_head local_queue;
3101         struct lnet_handle_md mdh;
3102         struct lnet_ni *tmp;
3103         struct lnet_ni *ni;
3104         lnet_nid_t nid;
3105         int healthv;
3106         int rc;
3107
3108         INIT_LIST_HEAD(&local_queue);
3109         INIT_LIST_HEAD(&processed_list);
3110
3111         /*
3112          * splice the recovery queue on a local queue. We will iterate
3113          * through the local queue and update it as needed. Once we're
3114          * done with the traversal, we'll splice the local queue back on
3115          * the head of the ln_mt_localNIRecovq. Any newly added local NIs
3116          * will be traversed in the next iteration.
3117          */
3118         lnet_net_lock(0);
3119         list_splice_init(&the_lnet.ln_mt_localNIRecovq,
3120                          &local_queue);
3121         lnet_net_unlock(0);
3122
3123         list_for_each_entry_safe(ni, tmp, &local_queue, ni_recovery) {
3124                 /*
3125                  * if an NI is being deleted or it is now healthy, there
3126                  * is no need to keep it around in the recovery queue.
3127                  * The monitor thread is the only thread responsible for
3128                  * removing the NI from the recovery queue.
3129                  * Multiple threads can be adding NIs to the recovery
3130                  * queue.
3131                  */
3132                 healthv = atomic_read(&ni->ni_healthv);
3133
3134                 lnet_net_lock(0);
3135                 lnet_ni_lock(ni);
3136                 if (ni->ni_state != LNET_NI_STATE_ACTIVE ||
3137                     healthv == LNET_MAX_HEALTH_VALUE) {
3138                         list_del_init(&ni->ni_recovery);
3139                         lnet_unlink_ni_recovery_mdh_locked(ni, 0, false);
3140                         lnet_ni_unlock(ni);
3141                         lnet_ni_decref_locked(ni, 0);
3142                         lnet_net_unlock(0);
3143                         continue;
3144                 }
3145
3146                 /*
3147                  * if the local NI failed recovery we must unlink the md.
3148                  * But we want to keep the local_ni on the recovery queue
3149                  * so we can continue the attempts to recover it.
3150                  */
3151                 if (ni->ni_recovery_state & LNET_NI_RECOVERY_FAILED) {
3152                         lnet_unlink_ni_recovery_mdh_locked(ni, 0, true);
3153                         ni->ni_recovery_state &= ~LNET_NI_RECOVERY_FAILED;
3154                 }
3155
3156                 lnet_ni_unlock(ni);
3157                 lnet_net_unlock(0);
3158
3159
3160                 CDEBUG(D_NET, "attempting to recover local ni: %s\n",
3161                        libcfs_nid2str(ni->ni_nid));
3162
3163                 lnet_ni_lock(ni);
3164                 if (!(ni->ni_recovery_state & LNET_NI_RECOVERY_PENDING)) {
3165                         ni->ni_recovery_state |= LNET_NI_RECOVERY_PENDING;
3166                         lnet_ni_unlock(ni);
3167
3168                         LIBCFS_ALLOC(ev_info, sizeof(*ev_info));
3169                         if (!ev_info) {
3170                                 CERROR("out of memory. Can't recover %s\n",
3171                                        libcfs_nid2str(ni->ni_nid));
3172                                 lnet_ni_lock(ni);
3173                                 ni->ni_recovery_state &=
3174                                   ~LNET_NI_RECOVERY_PENDING;
3175                                 lnet_ni_unlock(ni);
3176                                 continue;
3177                         }
3178
3179                         mdh = ni->ni_ping_mdh;
3180                         /*
3181                          * Invalidate the ni mdh in case it's deleted.
3182                          * We'll unlink the mdh in this case below.
3183                          */
3184                         LNetInvalidateMDHandle(&ni->ni_ping_mdh);
3185                         nid = ni->ni_nid;
3186
3187                         /*
3188                          * remove the NI from the local queue and drop the
3189                          * reference count to it while we're recovering
3190                          * it. The reason for that, is that the NI could
3191                          * be deleted, and the way the code is structured
3192                          * is if we don't drop the NI, then the deletion
3193                          * code will enter a loop waiting for the
3194                          * reference count to be removed while holding the
3195                          * ln_mutex_lock(). When we look up the peer to
3196                          * send to in lnet_select_pathway() we will try to
3197                          * lock the ln_mutex_lock() as well, leading to
3198                          * a deadlock. By dropping the refcount and
3199                          * removing it from the list, we allow for the NI
3200                          * to be removed, then we use the cached NID to
3201                          * look it up again. If it's gone, then we just
3202                          * continue examining the rest of the queue.
3203                          */
3204                         lnet_net_lock(0);
3205                         list_del_init(&ni->ni_recovery);
3206                         lnet_ni_decref_locked(ni, 0);
3207                         lnet_net_unlock(0);
3208
3209                         ev_info->mt_type = MT_TYPE_LOCAL_NI;
3210                         ev_info->mt_nid = nid;
3211                         rc = lnet_send_ping(nid, &mdh, LNET_INTERFACES_MIN,
3212                                             ev_info, the_lnet.ln_mt_eqh, true);
3213                         /* lookup the nid again */
3214                         lnet_net_lock(0);
3215                         ni = lnet_nid2ni_locked(nid, 0);
3216                         if (!ni) {
3217                                 /*
3218                                  * the NI has been deleted when we dropped
3219                                  * the ref count
3220                                  */
3221                                 lnet_net_unlock(0);
3222                                 LNetMDUnlink(mdh);
3223                                 continue;
3224                         }
3225                         /*
3226                          * Same note as in lnet_recover_peer_nis(). When
3227                          * we're sending the ping, the NI is free to be
3228                          * deleted or manipulated. By this point it
3229                          * could've been added back on the recovery queue,
3230                          * and a refcount taken on it.
3231                          * So we can't just add it blindly again or we'll
3232                          * corrupt the queue. We must check under lock if
3233                          * it's not on any list and if not then add it
3234                          * to the processed list, which will eventually be
3235                          * spliced back on to the recovery queue.
3236                          */
3237                         ni->ni_ping_mdh = mdh;
3238                         if (list_empty(&ni->ni_recovery)) {
3239                                 list_add_tail(&ni->ni_recovery, &processed_list);
3240                                 lnet_ni_addref_locked(ni, 0);
3241                         }
3242                         lnet_net_unlock(0);
3243
3244                         lnet_ni_lock(ni);
3245                         if (rc)
3246                                 ni->ni_recovery_state &= ~LNET_NI_RECOVERY_PENDING;
3247                 }
3248                 lnet_ni_unlock(ni);
3249         }
3250
3251         /*
3252          * put back the remaining NIs on the ln_mt_localNIRecovq to be
3253          * reexamined in the next iteration.
3254          */
3255         list_splice_init(&processed_list, &local_queue);
3256         lnet_net_lock(0);
3257         list_splice(&local_queue, &the_lnet.ln_mt_localNIRecovq);
3258         lnet_net_unlock(0);
3259 }
3260
3261 static int
3262 lnet_resendqs_create(void)
3263 {
3264         struct list_head **resendqs;
3265         resendqs = lnet_create_array_of_queues();
3266
3267         if (!resendqs)
3268                 return -ENOMEM;
3269
3270         lnet_net_lock(LNET_LOCK_EX);
3271         the_lnet.ln_mt_resendqs = resendqs;
3272         lnet_net_unlock(LNET_LOCK_EX);
3273
3274         return 0;
3275 }
3276
3277 static void
3278 lnet_clean_local_ni_recoveryq(void)
3279 {
3280         struct lnet_ni *ni;
3281
3282         /* This is only called when the monitor thread has stopped */
3283         lnet_net_lock(0);
3284
3285         while (!list_empty(&the_lnet.ln_mt_localNIRecovq)) {
3286                 ni = list_entry(the_lnet.ln_mt_localNIRecovq.next,
3287                                 struct lnet_ni, ni_recovery);
3288                 list_del_init(&ni->ni_recovery);
3289                 lnet_ni_lock(ni);
3290                 lnet_unlink_ni_recovery_mdh_locked(ni, 0, true);
3291                 lnet_ni_unlock(ni);
3292                 lnet_ni_decref_locked(ni, 0);
3293         }
3294
3295         lnet_net_unlock(0);
3296 }
3297
3298 static void
3299 lnet_unlink_lpni_recovery_mdh_locked(struct lnet_peer_ni *lpni, int cpt,
3300                                      bool force)
3301 {
3302         struct lnet_handle_md recovery_mdh;
3303
3304         LNetInvalidateMDHandle(&recovery_mdh);
3305
3306         if (lpni->lpni_state & LNET_PEER_NI_RECOVERY_PENDING || force) {
3307                 recovery_mdh = lpni->lpni_recovery_ping_mdh;
3308                 LNetInvalidateMDHandle(&lpni->lpni_recovery_ping_mdh);
3309         }
3310         spin_unlock(&lpni->lpni_lock);
3311         lnet_net_unlock(cpt);
3312         if (!LNetMDHandleIsInvalid(recovery_mdh))
3313                 LNetMDUnlink(recovery_mdh);
3314         lnet_net_lock(cpt);
3315         spin_lock(&lpni->lpni_lock);
3316 }
3317
3318 static void
3319 lnet_clean_peer_ni_recoveryq(void)
3320 {
3321         struct lnet_peer_ni *lpni, *tmp;
3322
3323         lnet_net_lock(LNET_LOCK_EX);
3324
3325         list_for_each_entry_safe(lpni, tmp, &the_lnet.ln_mt_peerNIRecovq,
3326                                  lpni_recovery) {
3327                 list_del_init(&lpni->lpni_recovery);
3328                 spin_lock(&lpni->lpni_lock);
3329                 lnet_unlink_lpni_recovery_mdh_locked(lpni, LNET_LOCK_EX, true);
3330                 spin_unlock(&lpni->lpni_lock);
3331                 lnet_peer_ni_decref_locked(lpni);
3332         }
3333
3334         lnet_net_unlock(LNET_LOCK_EX);
3335 }
3336
3337 static void
3338 lnet_clean_resendqs(void)
3339 {
3340         struct lnet_msg *msg, *tmp;
3341         struct list_head msgs;
3342         int i;
3343
3344         INIT_LIST_HEAD(&msgs);
3345
3346         cfs_cpt_for_each(i, lnet_cpt_table()) {
3347                 lnet_net_lock(i);
3348                 list_splice_init(the_lnet.ln_mt_resendqs[i], &msgs);
3349                 lnet_net_unlock(i);
3350                 list_for_each_entry_safe(msg, tmp, &msgs, msg_list) {
3351                         list_del_init(&msg->msg_list);
3352                         msg->msg_no_resend = true;
3353                         lnet_finalize(msg, -ESHUTDOWN);
3354                 }
3355         }
3356
3357         cfs_percpt_free(the_lnet.ln_mt_resendqs);
3358 }
3359
3360 static void
3361 lnet_recover_peer_nis(void)
3362 {
3363         struct lnet_mt_event_info *ev_info;
3364         struct list_head processed_list;
3365         struct list_head local_queue;
3366         struct lnet_handle_md mdh;
3367         struct lnet_peer_ni *lpni;
3368         struct lnet_peer_ni *tmp;
3369         lnet_nid_t nid;
3370         int healthv;
3371         int rc;
3372
3373         INIT_LIST_HEAD(&local_queue);
3374         INIT_LIST_HEAD(&processed_list);
3375
3376         /*
3377          * Always use cpt 0 for locking across all interactions with
3378          * ln_mt_peerNIRecovq
3379          */
3380         lnet_net_lock(0);
3381         list_splice_init(&the_lnet.ln_mt_peerNIRecovq,
3382                          &local_queue);
3383         lnet_net_unlock(0);
3384
3385         list_for_each_entry_safe(lpni, tmp, &local_queue,
3386                                  lpni_recovery) {
3387                 /*
3388                  * The same protection strategy is used here as is in the
3389                  * local recovery case.
3390                  */
3391                 lnet_net_lock(0);
3392                 healthv = atomic_read(&lpni->lpni_healthv);
3393                 spin_lock(&lpni->lpni_lock);
3394                 if (lpni->lpni_state & LNET_PEER_NI_DELETING ||
3395                     healthv == LNET_MAX_HEALTH_VALUE) {
3396                         list_del_init(&lpni->lpni_recovery);
3397                         lnet_unlink_lpni_recovery_mdh_locked(lpni, 0, false);
3398                         spin_unlock(&lpni->lpni_lock);
3399                         lnet_peer_ni_decref_locked(lpni);
3400                         lnet_net_unlock(0);
3401                         continue;
3402                 }
3403
3404                 /*
3405                  * If the peer NI has failed recovery we must unlink the
3406                  * md. But we want to keep the peer ni on the recovery
3407                  * queue so we can try to continue recovering it
3408                  */
3409                 if (lpni->lpni_state & LNET_PEER_NI_RECOVERY_FAILED) {
3410                         lnet_unlink_lpni_recovery_mdh_locked(lpni, 0, true);
3411                         lpni->lpni_state &= ~LNET_PEER_NI_RECOVERY_FAILED;
3412                 }
3413
3414                 spin_unlock(&lpni->lpni_lock);
3415                 lnet_net_unlock(0);
3416
3417                 /*
3418                  * NOTE: we're racing with peer deletion from user space.
3419                  * It's possible that a peer is deleted after we check its
3420                  * state. In this case the recovery can create a new peer
3421                  */
3422                 spin_lock(&lpni->lpni_lock);
3423                 if (!(lpni->lpni_state & LNET_PEER_NI_RECOVERY_PENDING) &&
3424                     !(lpni->lpni_state & LNET_PEER_NI_DELETING)) {
3425                         lpni->lpni_state |= LNET_PEER_NI_RECOVERY_PENDING;
3426                         spin_unlock(&lpni->lpni_lock);
3427
3428                         LIBCFS_ALLOC(ev_info, sizeof(*ev_info));
3429                         if (!ev_info) {
3430                                 CERROR("out of memory. Can't recover %s\n",
3431                                        libcfs_nid2str(lpni->lpni_nid));
3432                                 spin_lock(&lpni->lpni_lock);
3433                                 lpni->lpni_state &= ~LNET_PEER_NI_RECOVERY_PENDING;
3434                                 spin_unlock(&lpni->lpni_lock);
3435                                 continue;
3436                         }
3437
3438                         /* look at the comments in lnet_recover_local_nis() */
3439                         mdh = lpni->lpni_recovery_ping_mdh;
3440                         LNetInvalidateMDHandle(&lpni->lpni_recovery_ping_mdh);
3441                         nid = lpni->lpni_nid;
3442                         lnet_net_lock(0);
3443                         list_del_init(&lpni->lpni_recovery);
3444                         lnet_peer_ni_decref_locked(lpni);
3445                         lnet_net_unlock(0);
3446
3447                         ev_info->mt_type = MT_TYPE_PEER_NI;
3448                         ev_info->mt_nid = nid;
3449                         rc = lnet_send_ping(nid, &mdh, LNET_INTERFACES_MIN,
3450                                             ev_info, the_lnet.ln_mt_eqh, true);
3451                         lnet_net_lock(0);
3452                         /*
3453                          * lnet_find_peer_ni_locked() grabs a refcount for
3454                          * us. No need to take it explicitly.
3455                          */
3456                         lpni = lnet_find_peer_ni_locked(nid);
3457                         if (!lpni) {
3458                                 lnet_net_unlock(0);
3459                                 LNetMDUnlink(mdh);
3460                                 continue;
3461                         }
3462
3463                         lpni->lpni_recovery_ping_mdh = mdh;
3464                         /*
3465                          * While we're unlocked the lpni could've been
3466                          * readded on the recovery queue. In this case we
3467                          * don't need to add it to the local queue, since
3468                          * it's already on there and the thread that added
3469                          * it would've incremented the refcount on the
3470                          * peer, which means we need to decref the refcount
3471                          * that was implicitly grabbed by find_peer_ni_locked.
3472                          * Otherwise, if the lpni is still not on
3473                          * the recovery queue, then we'll add it to the
3474                          * processed list.
3475                          */
3476                         if (list_empty(&lpni->lpni_recovery))
3477                                 list_add_tail(&lpni->lpni_recovery, &processed_list);
3478                         else
3479                                 lnet_peer_ni_decref_locked(lpni);
3480                         lnet_net_unlock(0);
3481
3482                         spin_lock(&lpni->lpni_lock);
3483                         if (rc)
3484                                 lpni->lpni_state &= ~LNET_PEER_NI_RECOVERY_PENDING;
3485                 }
3486                 spin_unlock(&lpni->lpni_lock);
3487         }
3488
3489         list_splice_init(&processed_list, &local_queue);
3490         lnet_net_lock(0);
3491         list_splice(&local_queue, &the_lnet.ln_mt_peerNIRecovq);
3492         lnet_net_unlock(0);
3493 }
3494
3495 static int
3496 lnet_monitor_thread(void *arg)
3497 {
3498         time64_t recovery_timeout = 0;
3499         time64_t rsp_timeout = 0;
3500         int interval;
3501         time64_t now;
3502
3503         wait_for_completion(&the_lnet.ln_started);
3504         /*
3505          * The monitor thread takes care of the following:
3506          *  1. Checks the aliveness of routers
3507          *  2. Checks if there are messages on the resend queue to resend
3508          *     them.
3509          *  3. Check if there are any NIs on the local recovery queue and
3510          *     pings them
3511          *  4. Checks if there are any NIs on the remote recovery queue
3512          *     and pings them.
3513          */
3514         cfs_block_allsigs();
3515
3516         while (the_lnet.ln_mt_state == LNET_MT_STATE_RUNNING) {
3517                 now = ktime_get_real_seconds();
3518
3519                 if (lnet_router_checker_active())
3520                         lnet_check_routers();
3521
3522                 lnet_resend_pending_msgs();
3523
3524                 if (now >= rsp_timeout) {
3525                         lnet_finalize_expired_responses();
3526                         rsp_timeout = now + (lnet_transaction_timeout / 2);
3527                 }
3528
3529                 if (now >= recovery_timeout) {
3530                         lnet_recover_local_nis();
3531                         lnet_recover_peer_nis();
3532                         recovery_timeout = now + lnet_recovery_interval;
3533                 }
3534
3535                 /*
3536                  * TODO do we need to check if we should sleep without
3537                  * timeout?  Technically, an active system will always
3538                  * have messages in flight so this check will always
3539                  * evaluate to false. And on an idle system do we care
3540                  * if we wake up every 1 second? Although, we've seen
3541                  * cases where we get a complaint that an idle thread
3542                  * is waking up unnecessarily.
3543                  *
3544                  * Take into account the current net_count when you wake
3545                  * up for alive router checking, since we need to check
3546                  * possibly as many networks as we have configured.
3547                  */
3548                 interval = min(lnet_recovery_interval,
3549                                min((unsigned int) alive_router_check_interval /
3550                                         lnet_current_net_count,
3551                                    lnet_transaction_timeout / 2));
3552                 wait_for_completion_interruptible_timeout(
3553                         &the_lnet.ln_mt_wait_complete,
3554                         cfs_time_seconds(interval));
3555                 /* Must re-init the completion before testing anything,
3556                  * including ln_mt_state.
3557                  */
3558                 reinit_completion(&the_lnet.ln_mt_wait_complete);
3559         }
3560
3561         /* Shutting down */
3562         lnet_net_lock(LNET_LOCK_EX);
3563         the_lnet.ln_mt_state = LNET_MT_STATE_SHUTDOWN;
3564         lnet_net_unlock(LNET_LOCK_EX);
3565
3566         /* signal that the monitor thread is exiting */
3567         up(&the_lnet.ln_mt_signal);
3568
3569         return 0;
3570 }
3571
3572 /*
3573  * lnet_send_ping
3574  * Sends a ping.
3575  * Returns == 0 if success
3576  * Returns > 0 if LNetMDBind or prior fails
3577  * Returns < 0 if LNetGet fails
3578  */
3579 int
3580 lnet_send_ping(lnet_nid_t dest_nid,
3581                struct lnet_handle_md *mdh, int nnis,
3582                void *user_data, struct lnet_handle_eq eqh, bool recovery)
3583 {
3584         struct lnet_md md = { NULL };
3585         struct lnet_process_id id;
3586         struct lnet_ping_buffer *pbuf;
3587         int rc;
3588
3589         if (dest_nid == LNET_NID_ANY) {
3590                 rc = -EHOSTUNREACH;
3591                 goto fail_error;
3592         }
3593
3594         pbuf = lnet_ping_buffer_alloc(nnis, GFP_NOFS);
3595         if (!pbuf) {
3596                 rc = ENOMEM;
3597                 goto fail_error;
3598         }
3599
3600         /* initialize md content */
3601         md.start     = &pbuf->pb_info;
3602         md.length    = LNET_PING_INFO_SIZE(nnis);
3603         md.threshold = 2; /* GET/REPLY */
3604         md.max_size  = 0;
3605         md.options   = LNET_MD_TRUNCATE;
3606         md.user_ptr  = user_data;
3607         md.eq_handle = eqh;
3608
3609         rc = LNetMDBind(md, LNET_UNLINK, mdh);
3610         if (rc) {
3611                 lnet_ping_buffer_decref(pbuf);
3612                 CERROR("Can't bind MD: %d\n", rc);
3613                 rc = -rc; /* change the rc to positive */
3614                 goto fail_error;
3615         }
3616         id.pid = LNET_PID_LUSTRE;
3617         id.nid = dest_nid;
3618
3619         rc = LNetGet(LNET_NID_ANY, *mdh, id,
3620                      LNET_RESERVED_PORTAL,
3621                      LNET_PROTO_PING_MATCHBITS, 0, recovery);
3622
3623         if (rc)
3624                 goto fail_unlink_md;
3625
3626         return 0;
3627
3628 fail_unlink_md:
3629         LNetMDUnlink(*mdh);
3630         LNetInvalidateMDHandle(mdh);
3631 fail_error:
3632         return rc;
3633 }
3634
3635 static void
3636 lnet_handle_recovery_reply(struct lnet_mt_event_info *ev_info,
3637                            int status, bool unlink_event)
3638 {
3639         lnet_nid_t nid = ev_info->mt_nid;
3640
3641         if (ev_info->mt_type == MT_TYPE_LOCAL_NI) {
3642                 struct lnet_ni *ni;
3643
3644                 lnet_net_lock(0);
3645                 ni = lnet_nid2ni_locked(nid, 0);
3646                 if (!ni) {
3647                         lnet_net_unlock(0);
3648                         return;
3649                 }
3650                 lnet_ni_lock(ni);
3651                 ni->ni_recovery_state &= ~LNET_NI_RECOVERY_PENDING;
3652                 if (status)
3653                         ni->ni_recovery_state |= LNET_NI_RECOVERY_FAILED;
3654                 lnet_ni_unlock(ni);
3655                 lnet_net_unlock(0);
3656
3657                 if (status != 0) {
3658                         CERROR("local NI (%s) recovery failed with %d\n",
3659                                libcfs_nid2str(nid), status);
3660                         return;
3661                 }
3662                 /*
3663                  * need to increment healthv for the ni here, because in
3664                  * the lnet_finalize() path we don't have access to this
3665                  * NI. And in order to get access to it, we'll need to
3666                  * carry forward too much information.
3667                  * In the peer case, it'll naturally be incremented
3668                  */
3669                 if (!unlink_event)
3670                         lnet_inc_healthv(&ni->ni_healthv);
3671         } else {
3672                 struct lnet_peer_ni *lpni;
3673                 int cpt;
3674
3675                 cpt = lnet_net_lock_current();
3676                 lpni = lnet_find_peer_ni_locked(nid);
3677                 if (!lpni) {
3678                         lnet_net_unlock(cpt);
3679                         return;
3680                 }
3681                 spin_lock(&lpni->lpni_lock);
3682                 lpni->lpni_state &= ~LNET_PEER_NI_RECOVERY_PENDING;
3683                 if (status)
3684                         lpni->lpni_state |= LNET_PEER_NI_RECOVERY_FAILED;
3685                 spin_unlock(&lpni->lpni_lock);
3686                 lnet_peer_ni_decref_locked(lpni);
3687                 lnet_net_unlock(cpt);
3688
3689                 if (status != 0)
3690                         CERROR("peer NI (%s) recovery failed with %d\n",
3691                                libcfs_nid2str(nid), status);
3692         }
3693 }
3694
3695 void
3696 lnet_mt_event_handler(struct lnet_event *event)
3697 {
3698         struct lnet_mt_event_info *ev_info = event->md.user_ptr;
3699         struct lnet_ping_buffer *pbuf;
3700
3701         /* TODO: remove assert */
3702         LASSERT(event->type == LNET_EVENT_REPLY ||
3703                 event->type == LNET_EVENT_SEND ||
3704                 event->type == LNET_EVENT_UNLINK);
3705
3706         CDEBUG(D_NET, "Received event: %d status: %d\n", event->type,
3707                event->status);
3708
3709         switch (event->type) {
3710         case LNET_EVENT_UNLINK:
3711                 CDEBUG(D_NET, "%s recovery ping unlinked\n",
3712                        libcfs_nid2str(ev_info->mt_nid));
3713                 /* fallthrough */
3714         case LNET_EVENT_REPLY:
3715                 lnet_handle_recovery_reply(ev_info, event->status,
3716                                            event->type == LNET_EVENT_UNLINK);
3717                 break;
3718         case LNET_EVENT_SEND:
3719                 CDEBUG(D_NET, "%s recovery message sent %s:%d\n",
3720                                libcfs_nid2str(ev_info->mt_nid),
3721                                (event->status) ? "unsuccessfully" :
3722                                "successfully", event->status);
3723                 break;
3724         default:
3725                 CERROR("Unexpected event: %d\n", event->type);
3726                 break;
3727         }
3728         if (event->unlinked) {
3729                 LIBCFS_FREE(ev_info, sizeof(*ev_info));
3730                 pbuf = LNET_PING_INFO_TO_BUFFER(event->md.start);
3731                 lnet_ping_buffer_decref(pbuf);
3732         }
3733 }
3734
3735 static int
3736 lnet_rsp_tracker_create(void)
3737 {
3738         struct list_head **rstqs;
3739         rstqs = lnet_create_array_of_queues();
3740
3741         if (!rstqs)
3742                 return -ENOMEM;
3743
3744         the_lnet.ln_mt_rstq = rstqs;
3745
3746         return 0;
3747 }
3748
3749 static void
3750 lnet_rsp_tracker_clean(void)
3751 {
3752         lnet_finalize_expired_responses();
3753
3754         cfs_percpt_free(the_lnet.ln_mt_rstq);
3755         the_lnet.ln_mt_rstq = NULL;
3756 }
3757
3758 int lnet_monitor_thr_start(void)
3759 {
3760         int rc = 0;
3761         struct task_struct *task;
3762
3763         if (the_lnet.ln_mt_state != LNET_MT_STATE_SHUTDOWN)
3764                 return -EALREADY;
3765
3766         rc = lnet_resendqs_create();
3767         if (rc)
3768                 return rc;
3769
3770         rc = lnet_rsp_tracker_create();
3771         if (rc)
3772                 goto clean_queues;
3773
3774         sema_init(&the_lnet.ln_mt_signal, 0);
3775
3776         lnet_net_lock(LNET_LOCK_EX);
3777         the_lnet.ln_mt_state = LNET_MT_STATE_RUNNING;
3778         lnet_net_unlock(LNET_LOCK_EX);
3779         task = kthread_run(lnet_monitor_thread, NULL, "monitor_thread");
3780         if (IS_ERR(task)) {
3781                 rc = PTR_ERR(task);
3782                 CERROR("Can't start monitor thread: %d\n", rc);
3783                 goto clean_thread;
3784         }
3785
3786         return 0;
3787
3788 clean_thread:
3789         lnet_net_lock(LNET_LOCK_EX);
3790         the_lnet.ln_mt_state = LNET_MT_STATE_STOPPING;
3791         lnet_net_unlock(LNET_LOCK_EX);
3792         /* block until event callback signals exit */
3793         down(&the_lnet.ln_mt_signal);
3794         /* clean up */
3795         lnet_net_lock(LNET_LOCK_EX);
3796         the_lnet.ln_mt_state = LNET_MT_STATE_SHUTDOWN;
3797         lnet_net_unlock(LNET_LOCK_EX);
3798         lnet_rsp_tracker_clean();
3799         lnet_clean_local_ni_recoveryq();
3800         lnet_clean_peer_ni_recoveryq();
3801         lnet_clean_resendqs();
3802         LNetInvalidateEQHandle(&the_lnet.ln_mt_eqh);
3803         return rc;
3804 clean_queues:
3805         lnet_rsp_tracker_clean();
3806         lnet_clean_local_ni_recoveryq();
3807         lnet_clean_peer_ni_recoveryq();
3808         lnet_clean_resendqs();
3809         return rc;
3810 }
3811
3812 void lnet_monitor_thr_stop(void)
3813 {
3814         if (the_lnet.ln_mt_state == LNET_MT_STATE_SHUTDOWN)
3815                 return;
3816
3817         LASSERT(the_lnet.ln_mt_state == LNET_MT_STATE_RUNNING);
3818         lnet_net_lock(LNET_LOCK_EX);
3819         the_lnet.ln_mt_state = LNET_MT_STATE_STOPPING;
3820         lnet_net_unlock(LNET_LOCK_EX);
3821
3822         /* tell the monitor thread that we're shutting down */
3823         complete(&the_lnet.ln_mt_wait_complete);
3824
3825         /* block until monitor thread signals that it's done */
3826         down(&the_lnet.ln_mt_signal);
3827         LASSERT(the_lnet.ln_mt_state == LNET_MT_STATE_SHUTDOWN);
3828
3829         /* perform cleanup tasks */
3830         lnet_rsp_tracker_clean();
3831         lnet_clean_local_ni_recoveryq();
3832         lnet_clean_peer_ni_recoveryq();
3833         lnet_clean_resendqs();
3834
3835         return;
3836 }
3837
3838 void
3839 lnet_drop_message(struct lnet_ni *ni, int cpt, void *private, unsigned int nob,
3840                   __u32 msg_type)
3841 {
3842         lnet_net_lock(cpt);
3843         lnet_incr_stats(&ni->ni_stats, msg_type, LNET_STATS_TYPE_DROP);
3844         the_lnet.ln_counters[cpt]->lct_common.lcc_drop_count++;
3845         the_lnet.ln_counters[cpt]->lct_common.lcc_drop_length += nob;
3846         lnet_net_unlock(cpt);
3847
3848         lnet_ni_recv(ni, private, NULL, 0, 0, 0, nob);
3849 }
3850
3851 static void
3852 lnet_recv_put(struct lnet_ni *ni, struct lnet_msg *msg)
3853 {
3854         struct lnet_hdr *hdr = &msg->msg_hdr;
3855
3856         if (msg->msg_wanted != 0)
3857                 lnet_setpayloadbuffer(msg);
3858
3859         lnet_build_msg_event(msg, LNET_EVENT_PUT);
3860
3861         /* Must I ACK?  If so I'll grab the ack_wmd out of the header and put
3862          * it back into the ACK during lnet_finalize() */
3863         msg->msg_ack = (!lnet_is_wire_handle_none(&hdr->msg.put.ack_wmd) &&
3864                         (msg->msg_md->md_options & LNET_MD_ACK_DISABLE) == 0);
3865
3866         lnet_ni_recv(ni, msg->msg_private, msg, msg->msg_rx_delayed,
3867                      msg->msg_offset, msg->msg_wanted, hdr->payload_length);
3868 }
3869
3870 static int
3871 lnet_parse_put(struct lnet_ni *ni, struct lnet_msg *msg)
3872 {
3873         struct lnet_hdr         *hdr = &msg->msg_hdr;
3874         struct lnet_match_info  info;
3875         int                     rc;
3876         bool                    ready_delay;
3877
3878         /* Convert put fields to host byte order */
3879         hdr->msg.put.match_bits = le64_to_cpu(hdr->msg.put.match_bits);
3880         hdr->msg.put.ptl_index  = le32_to_cpu(hdr->msg.put.ptl_index);
3881         hdr->msg.put.offset     = le32_to_cpu(hdr->msg.put.offset);
3882
3883         /* Primary peer NID. */
3884         info.mi_id.nid  = msg->msg_initiator;
3885         info.mi_id.pid  = hdr->src_pid;
3886         info.mi_opc     = LNET_MD_OP_PUT;
3887         info.mi_portal  = hdr->msg.put.ptl_index;
3888         info.mi_rlength = hdr->payload_length;
3889         info.mi_roffset = hdr->msg.put.offset;
3890         info.mi_mbits   = hdr->msg.put.match_bits;
3891         info.mi_cpt     = lnet_cpt_of_nid(msg->msg_initiator, ni);
3892
3893         msg->msg_rx_ready_delay = ni->ni_net->net_lnd->lnd_eager_recv == NULL;
3894         ready_delay = msg->msg_rx_ready_delay;
3895
3896  again:
3897         rc = lnet_ptl_match_md(&info, msg);
3898         switch (rc) {
3899         default:
3900                 LBUG();
3901
3902         case LNET_MATCHMD_OK:
3903                 lnet_recv_put(ni, msg);
3904                 return 0;
3905
3906         case LNET_MATCHMD_NONE:
3907                 if (ready_delay)
3908                         /* no eager_recv or has already called it, should
3909                          * have been attached on delayed list */
3910                         return 0;
3911
3912                 rc = lnet_ni_eager_recv(ni, msg);
3913                 if (rc == 0) {
3914                         ready_delay = true;
3915                         goto again;
3916                 }
3917                 /* fall through */
3918
3919         case LNET_MATCHMD_DROP:
3920                 CNETERR("Dropping PUT from %s portal %d match %llu"
3921                         " offset %d length %d: %d\n",
3922                         libcfs_id2str(info.mi_id), info.mi_portal,
3923                         info.mi_mbits, info.mi_roffset, info.mi_rlength, rc);
3924
3925                 return -ENOENT; /* -ve: OK but no match */
3926         }
3927 }
3928
3929 static int
3930 lnet_parse_get(struct lnet_ni *ni, struct lnet_msg *msg, int rdma_get)
3931 {
3932         struct lnet_match_info info;
3933         struct lnet_hdr *hdr = &msg->msg_hdr;
3934         struct lnet_process_id source_id;
3935         struct lnet_handle_wire reply_wmd;
3936         int rc;
3937
3938         /* Convert get fields to host byte order */
3939         hdr->msg.get.match_bits   = le64_to_cpu(hdr->msg.get.match_bits);
3940         hdr->msg.get.ptl_index    = le32_to_cpu(hdr->msg.get.ptl_index);
3941         hdr->msg.get.sink_length  = le32_to_cpu(hdr->msg.get.sink_length);
3942         hdr->msg.get.src_offset   = le32_to_cpu(hdr->msg.get.src_offset);
3943
3944         source_id.nid = hdr->src_nid;
3945         source_id.pid = hdr->src_pid;
3946         /* Primary peer NID */
3947         info.mi_id.nid  = msg->msg_initiator;
3948         info.mi_id.pid  = hdr->src_pid;
3949         info.mi_opc     = LNET_MD_OP_GET;
3950         info.mi_portal  = hdr->msg.get.ptl_index;
3951         info.mi_rlength = hdr->msg.get.sink_length;
3952         info.mi_roffset = hdr->msg.get.src_offset;
3953         info.mi_mbits   = hdr->msg.get.match_bits;
3954         info.mi_cpt     = lnet_cpt_of_nid(msg->msg_initiator, ni);
3955
3956         rc = lnet_ptl_match_md(&info, msg);
3957         if (rc == LNET_MATCHMD_DROP) {
3958                 CNETERR("Dropping GET from %s portal %d match %llu"
3959                         " offset %d length %d\n",
3960                         libcfs_id2str(info.mi_id), info.mi_portal,
3961                         info.mi_mbits, info.mi_roffset, info.mi_rlength);
3962                 return -ENOENT; /* -ve: OK but no match */
3963         }
3964
3965         LASSERT(rc == LNET_MATCHMD_OK);
3966
3967         lnet_build_msg_event(msg, LNET_EVENT_GET);
3968
3969         reply_wmd = hdr->msg.get.return_wmd;
3970
3971         lnet_prep_send(msg, LNET_MSG_REPLY, source_id,
3972                        msg->msg_offset, msg->msg_wanted);
3973
3974         msg->msg_hdr.msg.reply.dst_wmd = reply_wmd;
3975
3976         if (rdma_get) {
3977                 /* The LND completes the REPLY from her recv procedure */
3978                 lnet_ni_recv(ni, msg->msg_private, msg, 0,
3979                              msg->msg_offset, msg->msg_len, msg->msg_len);
3980                 return 0;
3981         }
3982
3983         lnet_ni_recv(ni, msg->msg_private, NULL, 0, 0, 0, 0);
3984         msg->msg_receiving = 0;
3985
3986         rc = lnet_send(ni->ni_nid, msg, msg->msg_from);
3987         if (rc < 0) {
3988                 /* didn't get as far as lnet_ni_send() */
3989                 CERROR("%s: Unable to send REPLY for GET from %s: %d\n",
3990                        libcfs_nid2str(ni->ni_nid),
3991                        libcfs_id2str(info.mi_id), rc);
3992
3993                 lnet_finalize(msg, rc);
3994         }
3995
3996         return 0;
3997 }
3998
3999 static int
4000 lnet_parse_reply(struct lnet_ni *ni, struct lnet_msg *msg)
4001 {
4002         void *private = msg->msg_private;
4003         struct lnet_hdr *hdr = &msg->msg_hdr;
4004         struct lnet_process_id src = {0};
4005         struct lnet_libmd *md;
4006         int rlength;
4007         int mlength;
4008         int cpt;
4009
4010         cpt = lnet_cpt_of_cookie(hdr->msg.reply.dst_wmd.wh_object_cookie);
4011         lnet_res_lock(cpt);
4012
4013         src.nid = hdr->src_nid;
4014         src.pid = hdr->src_pid;
4015
4016         /* NB handles only looked up by creator (no flips) */
4017         md = lnet_wire_handle2md(&hdr->msg.reply.dst_wmd);
4018         if (md == NULL || md->md_threshold == 0 || md->md_me != NULL) {
4019                 CNETERR("%s: Dropping REPLY from %s for %s "
4020                         "MD %#llx.%#llx\n",
4021                         libcfs_nid2str(ni->ni_nid), libcfs_id2str(src),
4022                         (md == NULL) ? "invalid" : "inactive",
4023                         hdr->msg.reply.dst_wmd.wh_interface_cookie,
4024                         hdr->msg.reply.dst_wmd.wh_object_cookie);
4025                 if (md != NULL && md->md_me != NULL)
4026                         CERROR("REPLY MD also attached to portal %d\n",
4027                                md->md_me->me_portal);
4028
4029                 lnet_res_unlock(cpt);
4030                 return -ENOENT; /* -ve: OK but no match */
4031         }
4032
4033         LASSERT(md->md_offset == 0);
4034
4035         rlength = hdr->payload_length;
4036         mlength = MIN(rlength, (int)md->md_length);
4037
4038         if (mlength < rlength &&
4039             (md->md_options & LNET_MD_TRUNCATE) == 0) {
4040                 CNETERR("%s: Dropping REPLY from %s length %d "
4041                         "for MD %#llx would overflow (%d)\n",
4042                         libcfs_nid2str(ni->ni_nid), libcfs_id2str(src),
4043                         rlength, hdr->msg.reply.dst_wmd.wh_object_cookie,
4044                         mlength);
4045                 lnet_res_unlock(cpt);
4046                 return -ENOENT; /* -ve: OK but no match */
4047         }
4048
4049         CDEBUG(D_NET, "%s: Reply from %s of length %d/%d into md %#llx\n",
4050                libcfs_nid2str(ni->ni_nid), libcfs_id2str(src),
4051                mlength, rlength, hdr->msg.reply.dst_wmd.wh_object_cookie);
4052
4053         lnet_msg_attach_md(msg, md, 0, mlength);
4054
4055         if (mlength != 0)
4056                 lnet_setpayloadbuffer(msg);
4057
4058         lnet_res_unlock(cpt);
4059
4060         lnet_build_msg_event(msg, LNET_EVENT_REPLY);
4061
4062         lnet_ni_recv(ni, private, msg, 0, 0, mlength, rlength);
4063         return 0;
4064 }
4065
4066 static int
4067 lnet_parse_ack(struct lnet_ni *ni, struct lnet_msg *msg)
4068 {
4069         struct lnet_hdr *hdr = &msg->msg_hdr;
4070         struct lnet_process_id src = {0};
4071         struct lnet_libmd *md;
4072         int cpt;
4073
4074         src.nid = hdr->src_nid;
4075         src.pid = hdr->src_pid;
4076
4077         /* Convert ack fields to host byte order */
4078         hdr->msg.ack.match_bits = le64_to_cpu(hdr->msg.ack.match_bits);
4079         hdr->msg.ack.mlength = le32_to_cpu(hdr->msg.ack.mlength);
4080
4081         cpt = lnet_cpt_of_cookie(hdr->msg.ack.dst_wmd.wh_object_cookie);
4082         lnet_res_lock(cpt);
4083
4084         /* NB handles only looked up by creator (no flips) */
4085         md = lnet_wire_handle2md(&hdr->msg.ack.dst_wmd);
4086         if (md == NULL || md->md_threshold == 0 || md->md_me != NULL) {
4087                 /* Don't moan; this is expected */
4088                 CDEBUG(D_NET,
4089                        "%s: Dropping ACK from %s to %s MD %#llx.%#llx\n",
4090                        libcfs_nid2str(ni->ni_nid), libcfs_id2str(src),
4091                        (md == NULL) ? "invalid" : "inactive",
4092                        hdr->msg.ack.dst_wmd.wh_interface_cookie,
4093                        hdr->msg.ack.dst_wmd.wh_object_cookie);
4094                 if (md != NULL && md->md_me != NULL)
4095                         CERROR("Source MD also attached to portal %d\n",
4096                                md->md_me->me_portal);
4097
4098                 lnet_res_unlock(cpt);
4099                 return -ENOENT;                  /* -ve! */
4100         }
4101
4102         CDEBUG(D_NET, "%s: ACK from %s into md %#llx\n",
4103                libcfs_nid2str(ni->ni_nid), libcfs_id2str(src),
4104                hdr->msg.ack.dst_wmd.wh_object_cookie);
4105
4106         lnet_msg_attach_md(msg, md, 0, 0);
4107
4108         lnet_res_unlock(cpt);
4109
4110         lnet_build_msg_event(msg, LNET_EVENT_ACK);
4111
4112         lnet_ni_recv(ni, msg->msg_private, msg, 0, 0, 0, msg->msg_len);
4113         return 0;
4114 }
4115
4116 /**
4117  * \retval LNET_CREDIT_OK       If \a msg is forwarded
4118  * \retval LNET_CREDIT_WAIT     If \a msg is blocked because w/o buffer
4119  * \retval -ve                  error code
4120  */
4121 int
4122 lnet_parse_forward_locked(struct lnet_ni *ni, struct lnet_msg *msg)
4123 {
4124         int     rc = 0;
4125
4126         if (!the_lnet.ln_routing)
4127                 return -ECANCELED;
4128
4129         if (msg->msg_rxpeer->lpni_rtrcredits <= 0 ||
4130             lnet_msg2bufpool(msg)->rbp_credits <= 0) {
4131                 if (ni->ni_net->net_lnd->lnd_eager_recv == NULL) {
4132                         msg->msg_rx_ready_delay = 1;
4133                 } else {
4134                         lnet_net_unlock(msg->msg_rx_cpt);
4135                         rc = lnet_ni_eager_recv(ni, msg);
4136                         lnet_net_lock(msg->msg_rx_cpt);
4137                 }
4138         }
4139
4140         if (rc == 0)
4141                 rc = lnet_post_routed_recv_locked(msg, 0);
4142         return rc;
4143 }
4144
4145 int
4146 lnet_parse_local(struct lnet_ni *ni, struct lnet_msg *msg)
4147 {
4148         int     rc;
4149
4150         switch (msg->msg_type) {
4151         case LNET_MSG_ACK:
4152                 rc = lnet_parse_ack(ni, msg);
4153                 break;
4154         case LNET_MSG_PUT:
4155                 rc = lnet_parse_put(ni, msg);
4156                 break;
4157         case LNET_MSG_GET:
4158                 rc = lnet_parse_get(ni, msg, msg->msg_rdma_get);
4159                 break;
4160         case LNET_MSG_REPLY:
4161                 rc = lnet_parse_reply(ni, msg);
4162                 break;
4163         default: /* prevent an unused label if !kernel */
4164                 LASSERT(0);
4165                 return -EPROTO;
4166         }
4167
4168         LASSERT(rc == 0 || rc == -ENOENT);
4169         return rc;
4170 }
4171
4172 char *
4173 lnet_msgtyp2str (int type)
4174 {
4175         switch (type) {
4176         case LNET_MSG_ACK:
4177                 return ("ACK");
4178         case LNET_MSG_PUT:
4179                 return ("PUT");
4180         case LNET_MSG_GET:
4181                 return ("GET");
4182         case LNET_MSG_REPLY:
4183                 return ("REPLY");
4184         case LNET_MSG_HELLO:
4185                 return ("HELLO");
4186         default:
4187                 return ("<UNKNOWN>");
4188         }
4189 }
4190
4191 void
4192 lnet_print_hdr(struct lnet_hdr *hdr)
4193 {
4194         struct lnet_process_id src = {
4195                 .nid = hdr->src_nid,
4196                 .pid = hdr->src_pid,
4197         };
4198         struct lnet_process_id dst = {
4199                 .nid = hdr->dest_nid,
4200                 .pid = hdr->dest_pid,
4201         };
4202         char *type_str = lnet_msgtyp2str(hdr->type);
4203
4204         CWARN("P3 Header at %p of type %s\n", hdr, type_str);
4205         CWARN("    From %s\n", libcfs_id2str(src));
4206         CWARN("    To   %s\n", libcfs_id2str(dst));
4207
4208         switch (hdr->type) {
4209         default:
4210                 break;
4211
4212         case LNET_MSG_PUT:
4213                 CWARN("    Ptl index %d, ack md %#llx.%#llx, "
4214                       "match bits %llu\n",
4215                       hdr->msg.put.ptl_index,
4216                       hdr->msg.put.ack_wmd.wh_interface_cookie,
4217                       hdr->msg.put.ack_wmd.wh_object_cookie,
4218                       hdr->msg.put.match_bits);
4219                 CWARN("    Length %d, offset %d, hdr data %#llx\n",
4220                       hdr->payload_length, hdr->msg.put.offset,
4221                       hdr->msg.put.hdr_data);
4222                 break;
4223
4224         case LNET_MSG_GET:
4225                 CWARN("    Ptl index %d, return md %#llx.%#llx, "
4226                       "match bits %llu\n", hdr->msg.get.ptl_index,
4227                       hdr->msg.get.return_wmd.wh_interface_cookie,
4228                       hdr->msg.get.return_wmd.wh_object_cookie,
4229                       hdr->msg.get.match_bits);
4230                 CWARN("    Length %d, src offset %d\n",
4231                       hdr->msg.get.sink_length,
4232                       hdr->msg.get.src_offset);
4233                 break;
4234
4235         case LNET_MSG_ACK:
4236                 CWARN("    dst md %#llx.%#llx, "
4237                       "manipulated length %d\n",
4238                       hdr->msg.ack.dst_wmd.wh_interface_cookie,
4239                       hdr->msg.ack.dst_wmd.wh_object_cookie,
4240                       hdr->msg.ack.mlength);
4241                 break;
4242
4243         case LNET_MSG_REPLY:
4244                 CWARN("    dst md %#llx.%#llx, "
4245                       "length %d\n",
4246                       hdr->msg.reply.dst_wmd.wh_interface_cookie,
4247                       hdr->msg.reply.dst_wmd.wh_object_cookie,
4248                       hdr->payload_length);
4249         }
4250
4251 }
4252
4253 int
4254 lnet_parse(struct lnet_ni *ni, struct lnet_hdr *hdr, lnet_nid_t from_nid,
4255            void *private, int rdma_req)
4256 {
4257         struct lnet_peer_ni *lpni;
4258         struct lnet_msg *msg;
4259         __u32 payload_length;
4260         lnet_pid_t dest_pid;
4261         lnet_nid_t dest_nid;
4262         lnet_nid_t src_nid;
4263         bool push = false;
4264         int for_me;
4265         __u32 type;
4266         int rc = 0;
4267         int cpt;
4268
4269         LASSERT (!in_interrupt ());
4270
4271         type = le32_to_cpu(hdr->type);
4272         src_nid = le64_to_cpu(hdr->src_nid);
4273         dest_nid = le64_to_cpu(hdr->dest_nid);
4274         dest_pid = le32_to_cpu(hdr->dest_pid);
4275         payload_length = le32_to_cpu(hdr->payload_length);
4276
4277         for_me = (ni->ni_nid == dest_nid);
4278         cpt = lnet_cpt_of_nid(from_nid, ni);
4279
4280         CDEBUG(D_NET, "TRACE: %s(%s) <- %s : %s - %s\n",
4281                 libcfs_nid2str(dest_nid),
4282                 libcfs_nid2str(ni->ni_nid),
4283                 libcfs_nid2str(src_nid),
4284                 lnet_msgtyp2str(type),
4285                 (for_me) ? "for me" : "routed");
4286
4287         switch (type) {
4288         case LNET_MSG_ACK:
4289         case LNET_MSG_GET:
4290                 if (payload_length > 0) {
4291                         CERROR("%s, src %s: bad %s payload %d (0 expected)\n",
4292                                libcfs_nid2str(from_nid),
4293                                libcfs_nid2str(src_nid),
4294                                lnet_msgtyp2str(type), payload_length);
4295                         return -EPROTO;
4296                 }
4297                 break;
4298
4299         case LNET_MSG_PUT:
4300         case LNET_MSG_REPLY:
4301                 if (payload_length >
4302                     (__u32)(for_me ? LNET_MAX_PAYLOAD : LNET_MTU)) {
4303                         CERROR("%s, src %s: bad %s payload %d "
4304                                "(%d max expected)\n",
4305                                libcfs_nid2str(from_nid),
4306                                libcfs_nid2str(src_nid),
4307                                lnet_msgtyp2str(type),
4308                                payload_length,
4309                                for_me ? LNET_MAX_PAYLOAD : LNET_MTU);
4310                         return -EPROTO;
4311                 }
4312                 break;
4313
4314         default:
4315                 CERROR("%s, src %s: Bad message type 0x%x\n",
4316                        libcfs_nid2str(from_nid),
4317                        libcfs_nid2str(src_nid), type);
4318                 return -EPROTO;
4319         }
4320
4321         if (the_lnet.ln_routing &&
4322             ni->ni_net->net_last_alive != ktime_get_real_seconds()) {
4323                 lnet_ni_lock(ni);
4324                 spin_lock(&ni->ni_net->net_lock);
4325                 ni->ni_net->net_last_alive = ktime_get_real_seconds();
4326                 spin_unlock(&ni->ni_net->net_lock);
4327                 if (ni->ni_status != NULL &&
4328                     ni->ni_status->ns_status == LNET_NI_STATUS_DOWN) {
4329                         ni->ni_status->ns_status = LNET_NI_STATUS_UP;
4330                         push = true;
4331                 }
4332                 lnet_ni_unlock(ni);
4333         }
4334
4335         if (push)
4336                 lnet_push_update_to_peers(1);
4337
4338         /* Regard a bad destination NID as a protocol error.  Senders should
4339          * know what they're doing; if they don't they're misconfigured, buggy
4340          * or malicious so we chop them off at the knees :) */
4341
4342         if (!for_me) {
4343                 if (LNET_NIDNET(dest_nid) == LNET_NIDNET(ni->ni_nid)) {
4344                         /* should have gone direct */
4345                         CERROR("%s, src %s: Bad dest nid %s "
4346                                "(should have been sent direct)\n",
4347                                 libcfs_nid2str(from_nid),
4348                                 libcfs_nid2str(src_nid),
4349                                 libcfs_nid2str(dest_nid));
4350                         return -EPROTO;
4351                 }
4352
4353                 if (lnet_islocalnid(dest_nid)) {
4354                         /* dest is another local NI; sender should have used
4355                          * this node's NID on its own network */
4356                         CERROR("%s, src %s: Bad dest nid %s "
4357                                "(it's my nid but on a different network)\n",
4358                                 libcfs_nid2str(from_nid),
4359                                 libcfs_nid2str(src_nid),
4360                                 libcfs_nid2str(dest_nid));
4361                         return -EPROTO;
4362                 }
4363
4364                 if (rdma_req && type == LNET_MSG_GET) {
4365                         CERROR("%s, src %s: Bad optimized GET for %s "
4366                                "(final destination must be me)\n",
4367                                 libcfs_nid2str(from_nid),
4368                                 libcfs_nid2str(src_nid),
4369                                 libcfs_nid2str(dest_nid));
4370                         return -EPROTO;
4371                 }
4372
4373                 if (!the_lnet.ln_routing) {
4374                         CERROR("%s, src %s: Dropping message for %s "
4375                                "(routing not enabled)\n",
4376                                 libcfs_nid2str(from_nid),
4377                                 libcfs_nid2str(src_nid),
4378                                 libcfs_nid2str(dest_nid));
4379                         goto drop;
4380                 }
4381         }
4382
4383         /* Message looks OK; we're not going to return an error, so we MUST
4384          * call back lnd_recv() come what may... */
4385
4386         if (!list_empty(&the_lnet.ln_test_peers) &&     /* normally we don't */
4387             fail_peer(src_nid, 0)) {                    /* shall we now? */
4388                 CERROR("%s, src %s: Dropping %s to simulate failure\n",
4389                        libcfs_nid2str(from_nid), libcfs_nid2str(src_nid),
4390                        lnet_msgtyp2str(type));
4391                 goto drop;
4392         }
4393
4394         if (!list_empty(&the_lnet.ln_drop_rules) &&
4395             lnet_drop_rule_match(hdr, ni->ni_nid, NULL)) {
4396                 CDEBUG(D_NET, "%s, src %s, dst %s: Dropping %s to simulate"
4397                               "silent message loss\n",
4398                        libcfs_nid2str(from_nid), libcfs_nid2str(src_nid),
4399                        libcfs_nid2str(dest_nid), lnet_msgtyp2str(type));
4400                 goto drop;
4401         }
4402
4403         if (lnet_drop_asym_route && for_me &&
4404             LNET_NIDNET(src_nid) != LNET_NIDNET(from_nid)) {
4405                 struct lnet_net *net;
4406                 struct lnet_remotenet *rnet;
4407                 bool found = true;
4408
4409                 /* we are dealing with a routed message,
4410                  * so see if route to reach src_nid goes through from_nid
4411                  */
4412                 lnet_net_lock(cpt);
4413                 net = lnet_get_net_locked(LNET_NIDNET(ni->ni_nid));
4414                 if (!net) {
4415                         lnet_net_unlock(cpt);
4416                         CERROR("net %s not found\n",
4417                                libcfs_net2str(LNET_NIDNET(ni->ni_nid)));
4418                         return -EPROTO;
4419                 }
4420
4421                 rnet = lnet_find_rnet_locked(LNET_NIDNET(src_nid));
4422                 if (rnet) {
4423                         struct lnet_peer *gw = NULL;
4424                         struct lnet_peer_ni *lpni = NULL;
4425                         struct lnet_route *route;
4426
4427                         list_for_each_entry(route, &rnet->lrn_routes, lr_list) {
4428                                 found = false;
4429                                 gw = route->lr_gateway;
4430                                 if (route->lr_lnet != net->net_id)
4431                                         continue;
4432                                 /*
4433                                  * if the nid is one of the gateway's NIDs
4434                                  * then this is a valid gateway
4435                                  */
4436                                 while ((lpni = lnet_get_next_peer_ni_locked(gw,
4437                                                 NULL, lpni)) != NULL) {
4438                                         if (lpni->lpni_nid == from_nid) {
4439                                                 found = true;
4440                                                 break;
4441                                         }
4442                                 }
4443                         }
4444                 }
4445                 lnet_net_unlock(cpt);
4446                 if (!found) {
4447                         /* we would not use from_nid to route a message to
4448                          * src_nid
4449                          * => asymmetric routing detected but forbidden
4450                          */
4451                         CERROR("%s, src %s: Dropping asymmetrical route %s\n",
4452                                libcfs_nid2str(from_nid),
4453                                libcfs_nid2str(src_nid), lnet_msgtyp2str(type));
4454                         goto drop;
4455                 }
4456         }
4457
4458         msg = lnet_msg_alloc();
4459         if (msg == NULL) {
4460                 CERROR("%s, src %s: Dropping %s (out of memory)\n",
4461                        libcfs_nid2str(from_nid), libcfs_nid2str(src_nid),
4462                        lnet_msgtyp2str(type));
4463                 goto drop;
4464         }
4465
4466         /* msg zeroed in lnet_msg_alloc; i.e. flags all clear,
4467          * pointers NULL etc */
4468
4469         msg->msg_type = type;
4470         msg->msg_private = private;
4471         msg->msg_receiving = 1;
4472         msg->msg_rdma_get = rdma_req;
4473         msg->msg_len = msg->msg_wanted = payload_length;
4474         msg->msg_offset = 0;
4475         msg->msg_hdr = *hdr;
4476         /* for building message event */
4477         msg->msg_from = from_nid;
4478         if (!for_me) {
4479                 msg->msg_target.pid     = dest_pid;
4480                 msg->msg_target.nid     = dest_nid;
4481                 msg->msg_routing        = 1;
4482
4483         } else {
4484                 /* convert common msg->hdr fields to host byteorder */
4485                 msg->msg_hdr.type       = type;
4486                 msg->msg_hdr.src_nid    = src_nid;
4487                 msg->msg_hdr.src_pid    = le32_to_cpu(msg->msg_hdr.src_pid);
4488                 msg->msg_hdr.dest_nid   = dest_nid;
4489                 msg->msg_hdr.dest_pid   = dest_pid;
4490                 msg->msg_hdr.payload_length = payload_length;
4491         }
4492
4493         lnet_net_lock(cpt);
4494         lpni = lnet_nid2peerni_locked(from_nid, ni->ni_nid, cpt);
4495         if (IS_ERR(lpni)) {
4496                 lnet_net_unlock(cpt);
4497                 CERROR("%s, src %s: Dropping %s "
4498                        "(error %ld looking up sender)\n",
4499                        libcfs_nid2str(from_nid), libcfs_nid2str(src_nid),
4500                        lnet_msgtyp2str(type), PTR_ERR(lpni));
4501                 lnet_msg_free(msg);
4502                 if (rc == -ESHUTDOWN)
4503                         /* We are shutting down.  Don't do anything more */
4504                         return 0;
4505                 goto drop;
4506         }
4507
4508         if (the_lnet.ln_routing)
4509                 lpni->lpni_last_alive = ktime_get_seconds();
4510
4511         msg->msg_rxpeer = lpni;
4512         msg->msg_rxni = ni;
4513         lnet_ni_addref_locked(ni, cpt);
4514         /* Multi-Rail: Primary NID of source. */
4515         msg->msg_initiator = lnet_peer_primary_nid_locked(src_nid);
4516
4517         /*
4518          * mark the status of this lpni as UP since we received a message
4519          * from it. The ping response reports back the ns_status which is
4520          * marked on the remote as up or down and we cache it here.
4521          */
4522         msg->msg_rxpeer->lpni_ns_status = LNET_NI_STATUS_UP;
4523
4524         lnet_msg_commit(msg, cpt);
4525
4526         /* message delay simulation */
4527         if (unlikely(!list_empty(&the_lnet.ln_delay_rules) &&
4528                      lnet_delay_rule_match_locked(hdr, msg))) {
4529                 lnet_net_unlock(cpt);
4530                 return 0;
4531         }
4532
4533         if (!for_me) {
4534                 rc = lnet_parse_forward_locked(ni, msg);
4535                 lnet_net_unlock(cpt);
4536
4537                 if (rc < 0)
4538                         goto free_drop;
4539
4540                 if (rc == LNET_CREDIT_OK) {
4541                         lnet_ni_recv(ni, msg->msg_private, msg, 0,
4542                                      0, payload_length, payload_length);
4543                 }
4544                 return 0;
4545         }
4546
4547         lnet_net_unlock(cpt);
4548
4549         rc = lnet_parse_local(ni, msg);
4550         if (rc != 0)
4551                 goto free_drop;
4552         return 0;
4553
4554  free_drop:
4555         LASSERT(msg->msg_md == NULL);
4556         lnet_finalize(msg, rc);
4557
4558  drop:
4559         lnet_drop_message(ni, cpt, private, payload_length, type);
4560         return 0;
4561 }
4562 EXPORT_SYMBOL(lnet_parse);
4563
4564 void
4565 lnet_drop_delayed_msg_list(struct list_head *head, char *reason)
4566 {
4567         while (!list_empty(head)) {
4568                 struct lnet_process_id id = {0};
4569                 struct lnet_msg *msg;
4570
4571                 msg = list_entry(head->next, struct lnet_msg, msg_list);
4572                 list_del(&msg->msg_list);
4573
4574                 id.nid = msg->msg_hdr.src_nid;
4575                 id.pid = msg->msg_hdr.src_pid;
4576
4577                 LASSERT(msg->msg_md == NULL);
4578                 LASSERT(msg->msg_rx_delayed);
4579                 LASSERT(msg->msg_rxpeer != NULL);
4580                 LASSERT(msg->msg_hdr.type == LNET_MSG_PUT);
4581
4582                 CWARN("Dropping delayed PUT from %s portal %d match %llu"
4583                       " offset %d length %d: %s\n",
4584                       libcfs_id2str(id),
4585                       msg->msg_hdr.msg.put.ptl_index,
4586                       msg->msg_hdr.msg.put.match_bits,
4587                       msg->msg_hdr.msg.put.offset,
4588                       msg->msg_hdr.payload_length, reason);
4589
4590                 /* NB I can't drop msg's ref on msg_rxpeer until after I've
4591                  * called lnet_drop_message(), so I just hang onto msg as well
4592                  * until that's done */
4593
4594                 lnet_drop_message(msg->msg_rxni, msg->msg_rx_cpt,
4595                                   msg->msg_private, msg->msg_len,
4596                                   msg->msg_type);
4597
4598                 msg->msg_no_resend = true;
4599                 /*
4600                  * NB: message will not generate event because w/o attached MD,
4601                  * but we still should give error code so lnet_msg_decommit()
4602                  * can skip counters operations and other checks.
4603                  */
4604                 lnet_finalize(msg, -ENOENT);
4605         }
4606 }
4607
4608 void
4609 lnet_recv_delayed_msg_list(struct list_head *head)
4610 {
4611         while (!list_empty(head)) {
4612                 struct lnet_msg *msg;
4613                 struct lnet_process_id id;
4614
4615                 msg = list_entry(head->next, struct lnet_msg, msg_list);
4616                 list_del(&msg->msg_list);
4617
4618                 /* md won't disappear under me, since each msg
4619                  * holds a ref on it */
4620
4621                 id.nid = msg->msg_hdr.src_nid;
4622                 id.pid = msg->msg_hdr.src_pid;
4623
4624                 LASSERT(msg->msg_rx_delayed);
4625                 LASSERT(msg->msg_md != NULL);
4626                 LASSERT(msg->msg_rxpeer != NULL);
4627                 LASSERT(msg->msg_rxni != NULL);
4628                 LASSERT(msg->msg_hdr.type == LNET_MSG_PUT);
4629
4630                 CDEBUG(D_NET, "Resuming delayed PUT from %s portal %d "
4631                        "match %llu offset %d length %d.\n",
4632                         libcfs_id2str(id), msg->msg_hdr.msg.put.ptl_index,
4633                         msg->msg_hdr.msg.put.match_bits,
4634                         msg->msg_hdr.msg.put.offset,
4635                         msg->msg_hdr.payload_length);
4636
4637                 lnet_recv_put(msg->msg_rxni, msg);
4638         }
4639 }
4640
4641 static void
4642 lnet_attach_rsp_tracker(struct lnet_rsp_tracker *rspt, int cpt,
4643                         struct lnet_libmd *md, struct lnet_handle_md mdh)
4644 {
4645         s64 timeout_ns;
4646         bool new_entry = true;
4647         struct lnet_rsp_tracker *local_rspt;
4648
4649         /*
4650          * MD has a refcount taken by message so it's not going away.
4651          * The MD however can be looked up. We need to secure the access
4652          * to the md_rspt_ptr by taking the res_lock.
4653          * The rspt can be accessed without protection up to when it gets
4654          * added to the list.
4655          */
4656
4657         lnet_res_lock(cpt);
4658         local_rspt = md->md_rspt_ptr;
4659         timeout_ns = lnet_transaction_timeout * NSEC_PER_SEC;
4660         if (local_rspt != NULL) {
4661                 /*
4662                  * we already have an rspt attached to the md, so we'll
4663                  * update the deadline on that one.
4664                  */
4665                 LIBCFS_FREE(rspt, sizeof(*rspt));
4666                 new_entry = false;
4667         } else {
4668                 /* new md */
4669                 rspt->rspt_mdh = mdh;
4670                 rspt->rspt_cpt = cpt;
4671                 /* store the rspt so we can access it when we get the REPLY */
4672                 md->md_rspt_ptr = rspt;
4673                 local_rspt = rspt;
4674         }
4675         local_rspt->rspt_deadline = ktime_add_ns(ktime_get(), timeout_ns);
4676
4677         /*
4678          * add to the list of tracked responses. It's added to tail of the
4679          * list in order to expire all the older entries first.
4680          */
4681         lnet_net_lock(cpt);
4682         if (!new_entry && !list_empty(&local_rspt->rspt_on_list))
4683                 list_del_init(&local_rspt->rspt_on_list);
4684         list_add_tail(&local_rspt->rspt_on_list, the_lnet.ln_mt_rstq[cpt]);
4685         lnet_net_unlock(cpt);
4686         lnet_res_unlock(cpt);
4687 }
4688
4689 /**
4690  * Initiate an asynchronous PUT operation.
4691  *
4692  * There are several events associated with a PUT: completion of the send on
4693  * the initiator node (LNET_EVENT_SEND), and when the send completes
4694  * successfully, the receipt of an acknowledgment (LNET_EVENT_ACK) indicating
4695  * that the operation was accepted by the target. The event LNET_EVENT_PUT is
4696  * used at the target node to indicate the completion of incoming data
4697  * delivery.
4698  *
4699  * The local events will be logged in the EQ associated with the MD pointed to
4700  * by \a mdh handle. Using a MD without an associated EQ results in these
4701  * events being discarded. In this case, the caller must have another
4702  * mechanism (e.g., a higher level protocol) for determining when it is safe
4703  * to modify the memory region associated with the MD.
4704  *
4705  * Note that LNet does not guarantee the order of LNET_EVENT_SEND and
4706  * LNET_EVENT_ACK, though intuitively ACK should happen after SEND.
4707  *
4708  * \param self Indicates the NID of a local interface through which to send
4709  * the PUT request. Use LNET_NID_ANY to let LNet choose one by itself.
4710  * \param mdh A handle for the MD that describes the memory to be sent. The MD
4711  * must be "free floating" (See LNetMDBind()).
4712  * \param ack Controls whether an acknowledgment is requested.
4713  * Acknowledgments are only sent when they are requested by the initiating
4714  * process and the target MD enables them.
4715  * \param target A process identifier for the target process.
4716  * \param portal The index in the \a target's portal table.
4717  * \param match_bits The match bits to use for MD selection at the target
4718  * process.
4719  * \param offset The offset into the target MD (only used when the target
4720  * MD has the LNET_MD_MANAGE_REMOTE option set).
4721  * \param hdr_data 64 bits of user data that can be included in the message
4722  * header. This data is written to an event queue entry at the target if an
4723  * EQ is present on the matching MD.
4724  *
4725  * \retval  0      Success, and only in this case events will be generated
4726  * and logged to EQ (if it exists).
4727  * \retval -EIO    Simulated failure.
4728  * \retval -ENOMEM Memory allocation failure.
4729  * \retval -ENOENT Invalid MD object.
4730  *
4731  * \see struct lnet_event::hdr_data and lnet_event_kind_t.
4732  */
4733 int
4734 LNetPut(lnet_nid_t self, struct lnet_handle_md mdh, enum lnet_ack_req ack,
4735         struct lnet_process_id target, unsigned int portal,
4736         __u64 match_bits, unsigned int offset,
4737         __u64 hdr_data)
4738 {
4739         struct lnet_msg *msg;
4740         struct lnet_libmd *md;
4741         int cpt;
4742         int rc;
4743         struct lnet_rsp_tracker *rspt = NULL;
4744
4745         LASSERT(the_lnet.ln_refcount > 0);
4746
4747         if (!list_empty(&the_lnet.ln_test_peers) &&     /* normally we don't */
4748             fail_peer(target.nid, 1)) {                 /* shall we now? */
4749                 CERROR("Dropping PUT to %s: simulated failure\n",
4750                        libcfs_id2str(target));
4751                 return -EIO;
4752         }
4753
4754         msg = lnet_msg_alloc();
4755         if (msg == NULL) {
4756                 CERROR("Dropping PUT to %s: ENOMEM on struct lnet_msg\n",
4757                        libcfs_id2str(target));
4758                 return -ENOMEM;
4759         }
4760         msg->msg_vmflush = !!memory_pressure_get();
4761
4762         cpt = lnet_cpt_of_cookie(mdh.cookie);
4763
4764         if (ack == LNET_ACK_REQ) {
4765                 rspt = lnet_rspt_alloc(cpt);
4766                 if (!rspt) {
4767                         CERROR("Dropping PUT to %s: ENOMEM on response tracker\n",
4768                                 libcfs_id2str(target));
4769                         return -ENOMEM;
4770                 }
4771                 INIT_LIST_HEAD(&rspt->rspt_on_list);
4772         }
4773
4774         lnet_res_lock(cpt);
4775
4776         md = lnet_handle2md(&mdh);
4777         if (md == NULL || md->md_threshold == 0 || md->md_me != NULL) {
4778                 CERROR("Dropping PUT (%llu:%d:%s): MD (%d) invalid\n",
4779                        match_bits, portal, libcfs_id2str(target),
4780                        md == NULL ? -1 : md->md_threshold);
4781                 if (md != NULL && md->md_me != NULL)
4782                         CERROR("Source MD also attached to portal %d\n",
4783                                md->md_me->me_portal);
4784                 lnet_res_unlock(cpt);
4785
4786                 LIBCFS_FREE(rspt, sizeof(*rspt));
4787                 lnet_msg_free(msg);
4788                 return -ENOENT;
4789         }
4790
4791         CDEBUG(D_NET, "LNetPut -> %s\n", libcfs_id2str(target));
4792
4793         lnet_msg_attach_md(msg, md, 0, 0);
4794
4795         lnet_prep_send(msg, LNET_MSG_PUT, target, 0, md->md_length);
4796
4797         msg->msg_hdr.msg.put.match_bits = cpu_to_le64(match_bits);
4798         msg->msg_hdr.msg.put.ptl_index = cpu_to_le32(portal);
4799         msg->msg_hdr.msg.put.offset = cpu_to_le32(offset);
4800         msg->msg_hdr.msg.put.hdr_data = hdr_data;
4801
4802         /* NB handles only looked up by creator (no flips) */
4803         if (ack == LNET_ACK_REQ) {
4804                 msg->msg_hdr.msg.put.ack_wmd.wh_interface_cookie =
4805                         the_lnet.ln_interface_cookie;
4806                 msg->msg_hdr.msg.put.ack_wmd.wh_object_cookie =
4807                         md->md_lh.lh_cookie;
4808         } else {
4809                 msg->msg_hdr.msg.put.ack_wmd.wh_interface_cookie =
4810                         LNET_WIRE_HANDLE_COOKIE_NONE;
4811                 msg->msg_hdr.msg.put.ack_wmd.wh_object_cookie =
4812                         LNET_WIRE_HANDLE_COOKIE_NONE;
4813         }
4814
4815         lnet_res_unlock(cpt);
4816
4817         lnet_build_msg_event(msg, LNET_EVENT_SEND);
4818
4819         if (ack == LNET_ACK_REQ)
4820                 lnet_attach_rsp_tracker(rspt, cpt, md, mdh);
4821
4822         if (CFS_FAIL_CHECK_ORSET(CFS_FAIL_PTLRPC_OST_BULK_CB2,
4823                                  CFS_FAIL_ONCE))
4824                 rc = -EIO;
4825         else
4826                 rc = lnet_send(self, msg, LNET_NID_ANY);
4827
4828         if (rc != 0) {
4829                 CNETERR("Error sending PUT to %s: %d\n",
4830                         libcfs_id2str(target), rc);
4831                 msg->msg_no_resend = true;
4832                 lnet_finalize(msg, rc);
4833         }
4834
4835         /* completion will be signalled by an event */
4836         return 0;
4837 }
4838 EXPORT_SYMBOL(LNetPut);
4839
4840 /*
4841  * The LND can DMA direct to the GET md (i.e. no REPLY msg).  This
4842  * returns a msg for the LND to pass to lnet_finalize() when the sink
4843  * data has been received.
4844  *
4845  * CAVEAT EMPTOR: 'getmsg' is the original GET, which is freed when
4846  * lnet_finalize() is called on it, so the LND must call this first
4847  */
4848 struct lnet_msg *
4849 lnet_create_reply_msg(struct lnet_ni *ni, struct lnet_msg *getmsg)
4850 {
4851         struct lnet_msg *msg = lnet_msg_alloc();
4852         struct lnet_libmd *getmd = getmsg->msg_md;
4853         struct lnet_process_id peer_id = getmsg->msg_target;
4854         int cpt;
4855
4856         LASSERT(!getmsg->msg_target_is_router);
4857         LASSERT(!getmsg->msg_routing);
4858
4859         if (msg == NULL) {
4860                 CERROR("%s: Dropping REPLY from %s: can't allocate msg\n",
4861                        libcfs_nid2str(ni->ni_nid), libcfs_id2str(peer_id));
4862                 goto drop;
4863         }
4864
4865         cpt = lnet_cpt_of_cookie(getmd->md_lh.lh_cookie);
4866         lnet_res_lock(cpt);
4867
4868         LASSERT(getmd->md_refcount > 0);
4869
4870         if (getmd->md_threshold == 0) {
4871                 CERROR("%s: Dropping REPLY from %s for inactive MD %p\n",
4872                         libcfs_nid2str(ni->ni_nid), libcfs_id2str(peer_id),
4873                         getmd);
4874                 lnet_res_unlock(cpt);
4875                 goto drop;
4876         }
4877
4878         LASSERT(getmd->md_offset == 0);
4879
4880         CDEBUG(D_NET, "%s: Reply from %s md %p\n",
4881                libcfs_nid2str(ni->ni_nid), libcfs_id2str(peer_id), getmd);
4882
4883         /* setup information for lnet_build_msg_event */
4884         msg->msg_initiator = getmsg->msg_txpeer->lpni_peer_net->lpn_peer->lp_primary_nid;
4885         msg->msg_from = peer_id.nid;
4886         msg->msg_type = LNET_MSG_GET; /* flag this msg as an "optimized" GET */
4887         msg->msg_hdr.src_nid = peer_id.nid;
4888         msg->msg_hdr.payload_length = getmd->md_length;
4889         msg->msg_receiving = 1; /* required by lnet_msg_attach_md */
4890
4891         lnet_msg_attach_md(msg, getmd, getmd->md_offset, getmd->md_length);
4892         lnet_res_unlock(cpt);
4893
4894         cpt = lnet_cpt_of_nid(peer_id.nid, ni);
4895
4896         lnet_net_lock(cpt);
4897         lnet_msg_commit(msg, cpt);
4898         lnet_net_unlock(cpt);
4899
4900         lnet_build_msg_event(msg, LNET_EVENT_REPLY);
4901
4902         return msg;
4903
4904  drop:
4905         cpt = lnet_cpt_of_nid(peer_id.nid, ni);
4906
4907         lnet_net_lock(cpt);
4908         lnet_incr_stats(&ni->ni_stats, LNET_MSG_GET, LNET_STATS_TYPE_DROP);
4909         the_lnet.ln_counters[cpt]->lct_common.lcc_drop_count++;
4910         the_lnet.ln_counters[cpt]->lct_common.lcc_drop_length +=
4911                 getmd->md_length;
4912         lnet_net_unlock(cpt);
4913
4914         if (msg != NULL)
4915                 lnet_msg_free(msg);
4916
4917         return NULL;
4918 }
4919 EXPORT_SYMBOL(lnet_create_reply_msg);
4920
4921 void
4922 lnet_set_reply_msg_len(struct lnet_ni *ni, struct lnet_msg *reply,
4923                        unsigned int len)
4924 {
4925         /* Set the REPLY length, now the RDMA that elides the REPLY message has
4926          * completed and I know it. */
4927         LASSERT(reply != NULL);
4928         LASSERT(reply->msg_type == LNET_MSG_GET);
4929         LASSERT(reply->msg_ev.type == LNET_EVENT_REPLY);
4930
4931         /* NB I trusted my peer to RDMA.  If she tells me she's written beyond
4932          * the end of my buffer, I might as well be dead. */
4933         LASSERT(len <= reply->msg_ev.mlength);
4934
4935         reply->msg_ev.mlength = len;
4936 }
4937 EXPORT_SYMBOL(lnet_set_reply_msg_len);
4938
4939 /**
4940  * Initiate an asynchronous GET operation.
4941  *
4942  * On the initiator node, an LNET_EVENT_SEND is logged when the GET request
4943  * is sent, and an LNET_EVENT_REPLY is logged when the data returned from
4944  * the target node in the REPLY has been written to local MD.
4945  *
4946  * On the target node, an LNET_EVENT_GET is logged when the GET request
4947  * arrives and is accepted into a MD.
4948  *
4949  * \param self,target,portal,match_bits,offset See the discussion in LNetPut().
4950  * \param mdh A handle for the MD that describes the memory into which the
4951  * requested data will be received. The MD must be "free floating" (See LNetMDBind()).
4952  *
4953  * \retval  0      Success, and only in this case events will be generated
4954  * and logged to EQ (if it exists) of the MD.
4955  * \retval -EIO    Simulated failure.
4956  * \retval -ENOMEM Memory allocation failure.
4957  * \retval -ENOENT Invalid MD object.
4958  */
4959 int
4960 LNetGet(lnet_nid_t self, struct lnet_handle_md mdh,
4961         struct lnet_process_id target, unsigned int portal,
4962         __u64 match_bits, unsigned int offset, bool recovery)
4963 {
4964         struct lnet_msg *msg;
4965         struct lnet_libmd *md;
4966         struct lnet_rsp_tracker *rspt;
4967         int cpt;
4968         int rc;
4969
4970         LASSERT(the_lnet.ln_refcount > 0);
4971
4972         if (!list_empty(&the_lnet.ln_test_peers) &&     /* normally we don't */
4973             fail_peer(target.nid, 1))                   /* shall we now? */
4974         {
4975                 CERROR("Dropping GET to %s: simulated failure\n",
4976                        libcfs_id2str(target));
4977                 return -EIO;
4978         }
4979
4980         msg = lnet_msg_alloc();
4981         if (!msg) {
4982                 CERROR("Dropping GET to %s: ENOMEM on struct lnet_msg\n",
4983                        libcfs_id2str(target));
4984                 return -ENOMEM;
4985         }
4986
4987         cpt = lnet_cpt_of_cookie(mdh.cookie);
4988
4989         rspt = lnet_rspt_alloc(cpt);
4990         if (!rspt) {
4991                 CERROR("Dropping GET to %s: ENOMEM on response tracker\n",
4992                        libcfs_id2str(target));
4993                 return -ENOMEM;
4994         }
4995         INIT_LIST_HEAD(&rspt->rspt_on_list);
4996
4997         msg->msg_recovery = recovery;
4998
4999         lnet_res_lock(cpt);
5000
5001         md = lnet_handle2md(&mdh);
5002         if (md == NULL || md->md_threshold == 0 || md->md_me != NULL) {
5003                 CERROR("Dropping GET (%llu:%d:%s): MD (%d) invalid\n",
5004                        match_bits, portal, libcfs_id2str(target),
5005                        md == NULL ? -1 : md->md_threshold);
5006                 if (md != NULL && md->md_me != NULL)
5007                         CERROR("REPLY MD also attached to portal %d\n",
5008                                md->md_me->me_portal);
5009
5010                 lnet_res_unlock(cpt);
5011
5012                 lnet_msg_free(msg);
5013                 LIBCFS_FREE(rspt, sizeof(*rspt));
5014                 return -ENOENT;
5015         }
5016
5017         CDEBUG(D_NET, "LNetGet -> %s\n", libcfs_id2str(target));
5018
5019         lnet_msg_attach_md(msg, md, 0, 0);
5020
5021         lnet_prep_send(msg, LNET_MSG_GET, target, 0, 0);
5022
5023         msg->msg_hdr.msg.get.match_bits = cpu_to_le64(match_bits);
5024         msg->msg_hdr.msg.get.ptl_index = cpu_to_le32(portal);
5025         msg->msg_hdr.msg.get.src_offset = cpu_to_le32(offset);
5026         msg->msg_hdr.msg.get.sink_length = cpu_to_le32(md->md_length);
5027
5028         /* NB handles only looked up by creator (no flips) */
5029         msg->msg_hdr.msg.get.return_wmd.wh_interface_cookie =
5030                 the_lnet.ln_interface_cookie;
5031         msg->msg_hdr.msg.get.return_wmd.wh_object_cookie =
5032                 md->md_lh.lh_cookie;
5033
5034         lnet_res_unlock(cpt);
5035
5036         lnet_build_msg_event(msg, LNET_EVENT_SEND);
5037
5038         lnet_attach_rsp_tracker(rspt, cpt, md, mdh);
5039
5040         rc = lnet_send(self, msg, LNET_NID_ANY);
5041         if (rc < 0) {
5042                 CNETERR("Error sending GET to %s: %d\n",
5043                         libcfs_id2str(target), rc);
5044                 msg->msg_no_resend = true;
5045                 lnet_finalize(msg, rc);
5046         }
5047
5048         /* completion will be signalled by an event */
5049         return 0;
5050 }
5051 EXPORT_SYMBOL(LNetGet);
5052
5053 /**
5054  * Calculate distance to node at \a dstnid.
5055  *
5056  * \param dstnid Target NID.
5057  * \param srcnidp If not NULL, NID of the local interface to reach \a dstnid
5058  * is saved here.
5059  * \param orderp If not NULL, order of the route to reach \a dstnid is saved
5060  * here.
5061  *
5062  * \retval 0 If \a dstnid belongs to a local interface, and reserved option
5063  * local_nid_dist_zero is set, which is the default.
5064  * \retval positives Distance to target NID, i.e. number of hops plus one.
5065  * \retval -EHOSTUNREACH If \a dstnid is not reachable.
5066  */
5067 int
5068 LNetDist(lnet_nid_t dstnid, lnet_nid_t *srcnidp, __u32 *orderp)
5069 {
5070         struct list_head        *e;
5071         struct lnet_ni *ni = NULL;
5072         struct lnet_remotenet *rnet;
5073         __u32                   dstnet = LNET_NIDNET(dstnid);
5074         int                     hops;
5075         int                     cpt;
5076         __u32                   order = 2;
5077         struct list_head        *rn_list;
5078
5079         /* if !local_nid_dist_zero, I don't return a distance of 0 ever
5080          * (when lustre sees a distance of 0, it substitutes 0@lo), so I
5081          * keep order 0 free for 0@lo and order 1 free for a local NID
5082          * match */
5083
5084         LASSERT(the_lnet.ln_refcount > 0);
5085
5086         cpt = lnet_net_lock_current();
5087
5088         while ((ni = lnet_get_next_ni_locked(NULL, ni))) {
5089                 if (ni->ni_nid == dstnid) {
5090                         if (srcnidp != NULL)
5091                                 *srcnidp = dstnid;
5092                         if (orderp != NULL) {
5093                                 if (LNET_NETTYP(LNET_NIDNET(dstnid)) == LOLND)
5094                                         *orderp = 0;
5095                                 else
5096                                         *orderp = 1;
5097                         }
5098                         lnet_net_unlock(cpt);
5099
5100                         return local_nid_dist_zero ? 0 : 1;
5101                 }
5102
5103                 if (LNET_NIDNET(ni->ni_nid) == dstnet) {
5104                         /* Check if ni was originally created in
5105                          * current net namespace.
5106                          * If not, assign order above 0xffff0000,
5107                          * to make this ni not a priority. */
5108                         if (!net_eq(ni->ni_net_ns, current->nsproxy->net_ns))
5109                                 order += 0xffff0000;
5110
5111                         if (srcnidp != NULL)
5112                                 *srcnidp = ni->ni_nid;
5113                         if (orderp != NULL)
5114                                 *orderp = order;
5115                         lnet_net_unlock(cpt);
5116                         return 1;
5117                 }
5118
5119                 order++;
5120         }
5121
5122         rn_list = lnet_net2rnethash(dstnet);
5123         list_for_each(e, rn_list) {
5124                 rnet = list_entry(e, struct lnet_remotenet, lrn_list);
5125
5126                 if (rnet->lrn_net == dstnet) {
5127                         struct lnet_route *route;
5128                         struct lnet_route *shortest = NULL;
5129                         __u32 shortest_hops = LNET_UNDEFINED_HOPS;
5130                         __u32 route_hops;
5131
5132                         LASSERT(!list_empty(&rnet->lrn_routes));
5133
5134                         list_for_each_entry(route, &rnet->lrn_routes,
5135                                             lr_list) {
5136                                 route_hops = route->lr_hops;
5137                                 if (route_hops == LNET_UNDEFINED_HOPS)
5138                                         route_hops = 1;
5139                                 if (shortest == NULL ||
5140                                     route_hops < shortest_hops) {
5141                                         shortest = route;
5142                                         shortest_hops = route_hops;
5143                                 }
5144                         }
5145
5146                         LASSERT(shortest != NULL);
5147                         hops = shortest_hops;
5148                         if (srcnidp != NULL) {
5149                                 struct lnet_net *net;
5150                                 net = lnet_get_net_locked(shortest->lr_lnet);
5151                                 LASSERT(net);
5152                                 ni = lnet_get_next_ni_locked(net, NULL);
5153                                 *srcnidp = ni->ni_nid;
5154                         }
5155                         if (orderp != NULL)
5156                                 *orderp = order;
5157                         lnet_net_unlock(cpt);
5158                         return hops + 1;
5159                 }
5160                 order++;
5161         }
5162
5163         lnet_net_unlock(cpt);
5164         return -EHOSTUNREACH;
5165 }
5166 EXPORT_SYMBOL(LNetDist);