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