Whamcloud - gitweb
5a304aff3761586c3bd1553de633a2282e0287c5
[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                        struct lnet_msg *msg)
870 {
871         time64_t now = ktime_get_seconds();
872
873         if (!lnet_peer_aliveness_enabled(lp))
874                 return -ENODEV;
875
876         if (lnet_peer_is_alive(lp, now))
877                 return 1;
878
879         /*
880          * If we're resending a message, let's attempt to send it even if
881          * the peer is down to fulfill our resend quota on the message
882          */
883         if (msg->msg_retry_count > 0)
884                 return 1;
885
886         /*
887          * Peer appears dead, but we should avoid frequent NI queries (at
888          * most once per lnet_queryinterval seconds).
889          */
890         if (lp->lpni_last_query != 0) {
891                 static const int lnet_queryinterval = 1;
892                 time64_t next_query;
893
894                 next_query = lp->lpni_last_query + lnet_queryinterval;
895
896                 if (now < next_query) {
897                         if (lp->lpni_alive)
898                                 CWARN("Unexpected aliveness of peer %s: "
899                                       "%lld < %lld (%d/%d)\n",
900                                       libcfs_nid2str(lp->lpni_nid),
901                                       now, next_query,
902                                       lnet_queryinterval,
903                                       lp->lpni_net->net_tunables.lct_peer_timeout);
904                         return 0;
905                 }
906         }
907
908         /* query NI for latest aliveness news */
909         lnet_ni_query_locked(ni, lp);
910
911         if (lnet_peer_is_alive(lp, now))
912                 return 1;
913
914         lnet_notify_locked(lp, 0, 0, lp->lpni_last_alive);
915         return 0;
916 }
917
918 /**
919  * \param msg The message to be sent.
920  * \param do_send True if lnet_ni_send() should be called in this function.
921  *        lnet_send() is going to lnet_net_unlock immediately after this, so
922  *        it sets do_send FALSE and I don't do the unlock/send/lock bit.
923  *
924  * \retval LNET_CREDIT_OK If \a msg sent or OK to send.
925  * \retval LNET_CREDIT_WAIT If \a msg blocked for credit.
926  * \retval -EHOSTUNREACH If the next hop of the message appears dead.
927  * \retval -ECANCELED If the MD of the message has been unlinked.
928  */
929 static int
930 lnet_post_send_locked(struct lnet_msg *msg, int do_send)
931 {
932         struct lnet_peer_ni     *lp = msg->msg_txpeer;
933         struct lnet_ni          *ni = msg->msg_txni;
934         int                     cpt = msg->msg_tx_cpt;
935         struct lnet_tx_queue    *tq = ni->ni_tx_queues[cpt];
936
937         /* non-lnet_send() callers have checked before */
938         LASSERT(!do_send || msg->msg_tx_delayed);
939         LASSERT(!msg->msg_receiving);
940         LASSERT(msg->msg_tx_committed);
941
942         /* NB 'lp' is always the next hop */
943         if ((msg->msg_target.pid & LNET_PID_USERFLAG) == 0 &&
944             lnet_peer_alive_locked(ni, lp, msg) == 0) {
945                 the_lnet.ln_counters[cpt]->lct_common.lcc_drop_count++;
946                 the_lnet.ln_counters[cpt]->lct_common.lcc_drop_length +=
947                         msg->msg_len;
948                 lnet_net_unlock(cpt);
949                 if (msg->msg_txpeer)
950                         lnet_incr_stats(&msg->msg_txpeer->lpni_stats,
951                                         msg->msg_type,
952                                         LNET_STATS_TYPE_DROP);
953                 if (msg->msg_txni)
954                         lnet_incr_stats(&msg->msg_txni->ni_stats,
955                                         msg->msg_type,
956                                         LNET_STATS_TYPE_DROP);
957
958                 CNETERR("Dropping message for %s: peer not alive\n",
959                         libcfs_id2str(msg->msg_target));
960                 msg->msg_health_status = LNET_MSG_STATUS_LOCAL_DROPPED;
961                 if (do_send)
962                         lnet_finalize(msg, -EHOSTUNREACH);
963
964                 lnet_net_lock(cpt);
965                 return -EHOSTUNREACH;
966         }
967
968         if (msg->msg_md != NULL &&
969             (msg->msg_md->md_flags & LNET_MD_FLAG_ABORTED) != 0) {
970                 lnet_net_unlock(cpt);
971
972                 CNETERR("Aborting message for %s: LNetM[DE]Unlink() already "
973                         "called on the MD/ME.\n",
974                         libcfs_id2str(msg->msg_target));
975                 if (do_send) {
976                         msg->msg_no_resend = true;
977                         lnet_finalize(msg, -ECANCELED);
978                 }
979
980                 lnet_net_lock(cpt);
981                 return -ECANCELED;
982         }
983
984         if (!msg->msg_peertxcredit) {
985                 spin_lock(&lp->lpni_lock);
986                 LASSERT((lp->lpni_txcredits < 0) ==
987                         !list_empty(&lp->lpni_txq));
988
989                 msg->msg_peertxcredit = 1;
990                 lp->lpni_txqnob += msg->msg_len + sizeof(struct lnet_hdr);
991                 lp->lpni_txcredits--;
992
993                 if (lp->lpni_txcredits < lp->lpni_mintxcredits)
994                         lp->lpni_mintxcredits = lp->lpni_txcredits;
995
996                 if (lp->lpni_txcredits < 0) {
997                         msg->msg_tx_delayed = 1;
998                         list_add_tail(&msg->msg_list, &lp->lpni_txq);
999                         spin_unlock(&lp->lpni_lock);
1000                         return LNET_CREDIT_WAIT;
1001                 }
1002                 spin_unlock(&lp->lpni_lock);
1003         }
1004
1005         if (!msg->msg_txcredit) {
1006                 LASSERT((tq->tq_credits < 0) ==
1007                         !list_empty(&tq->tq_delayed));
1008
1009                 msg->msg_txcredit = 1;
1010                 tq->tq_credits--;
1011                 atomic_dec(&ni->ni_tx_credits);
1012
1013                 if (tq->tq_credits < tq->tq_credits_min)
1014                         tq->tq_credits_min = tq->tq_credits;
1015
1016                 if (tq->tq_credits < 0) {
1017                         msg->msg_tx_delayed = 1;
1018                         list_add_tail(&msg->msg_list, &tq->tq_delayed);
1019                         return LNET_CREDIT_WAIT;
1020                 }
1021         }
1022
1023         /* unset the tx_delay flag as we're going to send it now */
1024         msg->msg_tx_delayed = 0;
1025
1026         if (do_send) {
1027                 lnet_net_unlock(cpt);
1028                 lnet_ni_send(ni, msg);
1029                 lnet_net_lock(cpt);
1030         }
1031         return LNET_CREDIT_OK;
1032 }
1033
1034
1035 static struct lnet_rtrbufpool *
1036 lnet_msg2bufpool(struct lnet_msg *msg)
1037 {
1038         struct lnet_rtrbufpool  *rbp;
1039         int                     cpt;
1040
1041         LASSERT(msg->msg_rx_committed);
1042
1043         cpt = msg->msg_rx_cpt;
1044         rbp = &the_lnet.ln_rtrpools[cpt][0];
1045
1046         LASSERT(msg->msg_len <= LNET_MTU);
1047         while (msg->msg_len > (unsigned int)rbp->rbp_npages * PAGE_SIZE) {
1048                 rbp++;
1049                 LASSERT(rbp < &the_lnet.ln_rtrpools[cpt][LNET_NRBPOOLS]);
1050         }
1051
1052         return rbp;
1053 }
1054
1055 static int
1056 lnet_post_routed_recv_locked(struct lnet_msg *msg, int do_recv)
1057 {
1058         /* lnet_parse is going to lnet_net_unlock immediately after this, so it
1059          * sets do_recv FALSE and I don't do the unlock/send/lock bit.
1060          * I return LNET_CREDIT_WAIT if msg blocked and LNET_CREDIT_OK if
1061          * received or OK to receive */
1062         struct lnet_peer_ni *lp = msg->msg_rxpeer;
1063         struct lnet_rtrbufpool *rbp;
1064         struct lnet_rtrbuf *rb;
1065
1066         LASSERT (msg->msg_iov == NULL);
1067         LASSERT (msg->msg_kiov == NULL);
1068         LASSERT (msg->msg_niov == 0);
1069         LASSERT (msg->msg_routing);
1070         LASSERT (msg->msg_receiving);
1071         LASSERT (!msg->msg_sending);
1072
1073         /* non-lnet_parse callers only receive delayed messages */
1074         LASSERT(!do_recv || msg->msg_rx_delayed);
1075
1076         if (!msg->msg_peerrtrcredit) {
1077                 spin_lock(&lp->lpni_lock);
1078                 LASSERT((lp->lpni_rtrcredits < 0) ==
1079                         !list_empty(&lp->lpni_rtrq));
1080
1081                 msg->msg_peerrtrcredit = 1;
1082                 lp->lpni_rtrcredits--;
1083                 if (lp->lpni_rtrcredits < lp->lpni_minrtrcredits)
1084                         lp->lpni_minrtrcredits = lp->lpni_rtrcredits;
1085
1086                 if (lp->lpni_rtrcredits < 0) {
1087                         /* must have checked eager_recv before here */
1088                         LASSERT(msg->msg_rx_ready_delay);
1089                         msg->msg_rx_delayed = 1;
1090                         list_add_tail(&msg->msg_list, &lp->lpni_rtrq);
1091                         spin_unlock(&lp->lpni_lock);
1092                         return LNET_CREDIT_WAIT;
1093                 }
1094                 spin_unlock(&lp->lpni_lock);
1095         }
1096
1097         rbp = lnet_msg2bufpool(msg);
1098
1099         if (!msg->msg_rtrcredit) {
1100                 msg->msg_rtrcredit = 1;
1101                 rbp->rbp_credits--;
1102                 if (rbp->rbp_credits < rbp->rbp_mincredits)
1103                         rbp->rbp_mincredits = rbp->rbp_credits;
1104
1105                 if (rbp->rbp_credits < 0) {
1106                         /* must have checked eager_recv before here */
1107                         LASSERT(msg->msg_rx_ready_delay);
1108                         msg->msg_rx_delayed = 1;
1109                         list_add_tail(&msg->msg_list, &rbp->rbp_msgs);
1110                         return LNET_CREDIT_WAIT;
1111                 }
1112         }
1113
1114         LASSERT(!list_empty(&rbp->rbp_bufs));
1115         rb = list_entry(rbp->rbp_bufs.next, struct lnet_rtrbuf, rb_list);
1116         list_del(&rb->rb_list);
1117
1118         msg->msg_niov = rbp->rbp_npages;
1119         msg->msg_kiov = &rb->rb_kiov[0];
1120
1121         /* unset the msg-rx_delayed flag since we're receiving the message */
1122         msg->msg_rx_delayed = 0;
1123
1124         if (do_recv) {
1125                 int cpt = msg->msg_rx_cpt;
1126
1127                 lnet_net_unlock(cpt);
1128                 lnet_ni_recv(msg->msg_rxni, msg->msg_private, msg, 1,
1129                              0, msg->msg_len, msg->msg_len);
1130                 lnet_net_lock(cpt);
1131         }
1132         return LNET_CREDIT_OK;
1133 }
1134
1135 void
1136 lnet_return_tx_credits_locked(struct lnet_msg *msg)
1137 {
1138         struct lnet_peer_ni     *txpeer = msg->msg_txpeer;
1139         struct lnet_ni          *txni = msg->msg_txni;
1140         struct lnet_msg         *msg2;
1141
1142         if (msg->msg_txcredit) {
1143                 struct lnet_ni       *ni = msg->msg_txni;
1144                 struct lnet_tx_queue *tq = ni->ni_tx_queues[msg->msg_tx_cpt];
1145
1146                 /* give back NI txcredits */
1147                 msg->msg_txcredit = 0;
1148
1149                 LASSERT((tq->tq_credits < 0) ==
1150                         !list_empty(&tq->tq_delayed));
1151
1152                 tq->tq_credits++;
1153                 atomic_inc(&ni->ni_tx_credits);
1154                 if (tq->tq_credits <= 0) {
1155                         msg2 = list_entry(tq->tq_delayed.next,
1156                                           struct lnet_msg, msg_list);
1157                         list_del(&msg2->msg_list);
1158
1159                         LASSERT(msg2->msg_txni == ni);
1160                         LASSERT(msg2->msg_tx_delayed);
1161                         LASSERT(msg2->msg_tx_cpt == msg->msg_tx_cpt);
1162
1163                         (void) lnet_post_send_locked(msg2, 1);
1164                 }
1165         }
1166
1167         if (msg->msg_peertxcredit) {
1168                 /* give back peer txcredits */
1169                 msg->msg_peertxcredit = 0;
1170
1171                 spin_lock(&txpeer->lpni_lock);
1172                 LASSERT((txpeer->lpni_txcredits < 0) ==
1173                         !list_empty(&txpeer->lpni_txq));
1174
1175                 txpeer->lpni_txqnob -= msg->msg_len + sizeof(struct lnet_hdr);
1176                 LASSERT(txpeer->lpni_txqnob >= 0);
1177
1178                 txpeer->lpni_txcredits++;
1179                 if (txpeer->lpni_txcredits <= 0) {
1180                         int msg2_cpt;
1181
1182                         msg2 = list_entry(txpeer->lpni_txq.next,
1183                                               struct lnet_msg, msg_list);
1184                         list_del(&msg2->msg_list);
1185                         spin_unlock(&txpeer->lpni_lock);
1186
1187                         LASSERT(msg2->msg_txpeer == txpeer);
1188                         LASSERT(msg2->msg_tx_delayed);
1189
1190                         msg2_cpt = msg2->msg_tx_cpt;
1191
1192                         /*
1193                          * The msg_cpt can be different from the msg2_cpt
1194                          * so we need to make sure we lock the correct cpt
1195                          * for msg2.
1196                          * Once we call lnet_post_send_locked() it is no
1197                          * longer safe to access msg2, since it could've
1198                          * been freed by lnet_finalize(), but we still
1199                          * need to relock the correct cpt, so we cache the
1200                          * msg2_cpt for the purpose of the check that
1201                          * follows the call to lnet_pose_send_locked().
1202                          */
1203                         if (msg2_cpt != msg->msg_tx_cpt) {
1204                                 lnet_net_unlock(msg->msg_tx_cpt);
1205                                 lnet_net_lock(msg2_cpt);
1206                         }
1207                         (void) lnet_post_send_locked(msg2, 1);
1208                         if (msg2_cpt != msg->msg_tx_cpt) {
1209                                 lnet_net_unlock(msg2_cpt);
1210                                 lnet_net_lock(msg->msg_tx_cpt);
1211                         }
1212                 } else {
1213                         spin_unlock(&txpeer->lpni_lock);
1214                 }
1215         }
1216
1217         if (txni != NULL) {
1218                 msg->msg_txni = NULL;
1219                 lnet_ni_decref_locked(txni, msg->msg_tx_cpt);
1220         }
1221
1222         if (txpeer != NULL) {
1223                 msg->msg_txpeer = NULL;
1224                 lnet_peer_ni_decref_locked(txpeer);
1225         }
1226 }
1227
1228 void
1229 lnet_schedule_blocked_locked(struct lnet_rtrbufpool *rbp)
1230 {
1231         struct lnet_msg *msg;
1232
1233         if (list_empty(&rbp->rbp_msgs))
1234                 return;
1235         msg = list_entry(rbp->rbp_msgs.next,
1236                          struct lnet_msg, msg_list);
1237         list_del(&msg->msg_list);
1238
1239         (void)lnet_post_routed_recv_locked(msg, 1);
1240 }
1241
1242 void
1243 lnet_drop_routed_msgs_locked(struct list_head *list, int cpt)
1244 {
1245         struct lnet_msg *msg;
1246         struct lnet_msg *tmp;
1247
1248         lnet_net_unlock(cpt);
1249
1250         list_for_each_entry_safe(msg, tmp, list, msg_list) {
1251                 lnet_ni_recv(msg->msg_rxni, msg->msg_private, NULL,
1252                              0, 0, 0, msg->msg_hdr.payload_length);
1253                 list_del_init(&msg->msg_list);
1254                 msg->msg_no_resend = true;
1255                 lnet_finalize(msg, -ECANCELED);
1256         }
1257
1258         lnet_net_lock(cpt);
1259 }
1260
1261 void
1262 lnet_return_rx_credits_locked(struct lnet_msg *msg)
1263 {
1264         struct lnet_peer_ni *rxpeer = msg->msg_rxpeer;
1265         struct lnet_ni *rxni = msg->msg_rxni;
1266         struct lnet_msg *msg2;
1267
1268         if (msg->msg_rtrcredit) {
1269                 /* give back global router credits */
1270                 struct lnet_rtrbuf *rb;
1271                 struct lnet_rtrbufpool *rbp;
1272
1273                 /* NB If a msg ever blocks for a buffer in rbp_msgs, it stays
1274                  * there until it gets one allocated, or aborts the wait
1275                  * itself */
1276                 LASSERT(msg->msg_kiov != NULL);
1277
1278                 rb = list_entry(msg->msg_kiov, struct lnet_rtrbuf, rb_kiov[0]);
1279                 rbp = rb->rb_pool;
1280
1281                 msg->msg_kiov = NULL;
1282                 msg->msg_rtrcredit = 0;
1283
1284                 LASSERT(rbp == lnet_msg2bufpool(msg));
1285
1286                 LASSERT((rbp->rbp_credits > 0) ==
1287                         !list_empty(&rbp->rbp_bufs));
1288
1289                 /* If routing is now turned off, we just drop this buffer and
1290                  * don't bother trying to return credits.  */
1291                 if (!the_lnet.ln_routing) {
1292                         lnet_destroy_rtrbuf(rb, rbp->rbp_npages);
1293                         goto routing_off;
1294                 }
1295
1296                 /* It is possible that a user has lowered the desired number of
1297                  * buffers in this pool.  Make sure we never put back
1298                  * more buffers than the stated number. */
1299                 if (unlikely(rbp->rbp_credits >= rbp->rbp_req_nbuffers)) {
1300                         /* Discard this buffer so we don't have too
1301                          * many. */
1302                         lnet_destroy_rtrbuf(rb, rbp->rbp_npages);
1303                         rbp->rbp_nbuffers--;
1304                 } else {
1305                         list_add(&rb->rb_list, &rbp->rbp_bufs);
1306                         rbp->rbp_credits++;
1307                         if (rbp->rbp_credits <= 0)
1308                                 lnet_schedule_blocked_locked(rbp);
1309                 }
1310         }
1311
1312 routing_off:
1313         if (msg->msg_peerrtrcredit) {
1314                 /* give back peer router credits */
1315                 msg->msg_peerrtrcredit = 0;
1316
1317                 spin_lock(&rxpeer->lpni_lock);
1318                 LASSERT((rxpeer->lpni_rtrcredits < 0) ==
1319                         !list_empty(&rxpeer->lpni_rtrq));
1320
1321                 rxpeer->lpni_rtrcredits++;
1322
1323                 /* drop all messages which are queued to be routed on that
1324                  * peer. */
1325                 if (!the_lnet.ln_routing) {
1326                         struct list_head drop;
1327                         INIT_LIST_HEAD(&drop);
1328                         list_splice_init(&rxpeer->lpni_rtrq, &drop);
1329                         spin_unlock(&rxpeer->lpni_lock);
1330                         lnet_drop_routed_msgs_locked(&drop, msg->msg_rx_cpt);
1331                 } else if (rxpeer->lpni_rtrcredits <= 0) {
1332                         msg2 = list_entry(rxpeer->lpni_rtrq.next,
1333                                           struct lnet_msg, msg_list);
1334                         list_del(&msg2->msg_list);
1335                         spin_unlock(&rxpeer->lpni_lock);
1336                         (void) lnet_post_routed_recv_locked(msg2, 1);
1337                 } else {
1338                         spin_unlock(&rxpeer->lpni_lock);
1339                 }
1340         }
1341         if (rxni != NULL) {
1342                 msg->msg_rxni = NULL;
1343                 lnet_ni_decref_locked(rxni, msg->msg_rx_cpt);
1344         }
1345         if (rxpeer != NULL) {
1346                 msg->msg_rxpeer = NULL;
1347                 lnet_peer_ni_decref_locked(rxpeer);
1348         }
1349 }
1350
1351 static int
1352 lnet_compare_peers(struct lnet_peer_ni *p1, struct lnet_peer_ni *p2)
1353 {
1354         if (p1->lpni_txqnob < p2->lpni_txqnob)
1355                 return 1;
1356
1357         if (p1->lpni_txqnob > p2->lpni_txqnob)
1358                 return -1;
1359
1360         if (p1->lpni_txcredits > p2->lpni_txcredits)
1361                 return 1;
1362
1363         if (p1->lpni_txcredits < p2->lpni_txcredits)
1364                 return -1;
1365
1366         return 0;
1367 }
1368
1369 static int
1370 lnet_compare_routes(struct lnet_route *r1, struct lnet_route *r2)
1371 {
1372         struct lnet_peer_ni *p1 = r1->lr_gateway;
1373         struct lnet_peer_ni *p2 = r2->lr_gateway;
1374         int r1_hops = (r1->lr_hops == LNET_UNDEFINED_HOPS) ? 1 : r1->lr_hops;
1375         int r2_hops = (r2->lr_hops == LNET_UNDEFINED_HOPS) ? 1 : r2->lr_hops;
1376         int rc;
1377
1378         if (r1->lr_priority < r2->lr_priority)
1379                 return 1;
1380
1381         if (r1->lr_priority > r2->lr_priority)
1382                 return -1;
1383
1384         if (r1_hops < r2_hops)
1385                 return 1;
1386
1387         if (r1_hops > r2_hops)
1388                 return -1;
1389
1390         rc = lnet_compare_peers(p1, p2);
1391         if (rc)
1392                 return rc;
1393
1394         if (r1->lr_seq - r2->lr_seq <= 0)
1395                 return 1;
1396
1397         return -1;
1398 }
1399
1400 static struct lnet_peer_ni *
1401 lnet_find_route_locked(struct lnet_net *net, __u32 remote_net,
1402                        lnet_nid_t rtr_nid)
1403 {
1404         struct lnet_remotenet   *rnet;
1405         struct lnet_route               *route;
1406         struct lnet_route               *best_route;
1407         struct lnet_route               *last_route;
1408         struct lnet_peer_ni     *lpni_best;
1409         struct lnet_peer_ni     *lp;
1410         int                     rc;
1411
1412         /* If @rtr_nid is not LNET_NID_ANY, return the gateway with
1413          * rtr_nid nid, otherwise find the best gateway I can use */
1414
1415         rnet = lnet_find_rnet_locked(remote_net);
1416         if (rnet == NULL)
1417                 return NULL;
1418
1419         lpni_best = NULL;
1420         best_route = last_route = NULL;
1421         list_for_each_entry(route, &rnet->lrn_routes, lr_list) {
1422                 lp = route->lr_gateway;
1423
1424                 if (!lnet_is_route_alive(route))
1425                         continue;
1426
1427                 if (net != NULL && lp->lpni_net != net)
1428                         continue;
1429
1430                 if (lp->lpni_nid == rtr_nid) /* it's pre-determined router */
1431                         return lp;
1432
1433                 if (lpni_best == NULL) {
1434                         best_route = last_route = route;
1435                         lpni_best = lp;
1436                         continue;
1437                 }
1438
1439                 /* no protection on below fields, but it's harmless */
1440                 if (last_route->lr_seq - route->lr_seq < 0)
1441                         last_route = route;
1442
1443                 rc = lnet_compare_routes(route, best_route);
1444                 if (rc < 0)
1445                         continue;
1446
1447                 best_route = route;
1448                 lpni_best = lp;
1449         }
1450
1451         /* set sequence number on the best router to the latest sequence + 1
1452          * so we can round-robin all routers, it's race and inaccurate but
1453          * harmless and functional  */
1454         if (best_route != NULL)
1455                 best_route->lr_seq = last_route->lr_seq + 1;
1456         return lpni_best;
1457 }
1458
1459 static struct lnet_ni *
1460 lnet_get_best_ni(struct lnet_net *local_net, struct lnet_ni *best_ni,
1461                  struct lnet_peer *peer, struct lnet_peer_net *peer_net,
1462                  int md_cpt)
1463 {
1464         struct lnet_ni *ni = NULL;
1465         unsigned int shortest_distance;
1466         int best_credits;
1467         int best_healthv;
1468
1469         /*
1470          * If there is no peer_ni that we can send to on this network,
1471          * then there is no point in looking for a new best_ni here.
1472         */
1473         if (!lnet_get_next_peer_ni_locked(peer, peer_net, NULL))
1474                 return best_ni;
1475
1476         if (best_ni == NULL) {
1477                 shortest_distance = UINT_MAX;
1478                 best_credits = INT_MIN;
1479                 best_healthv = 0;
1480         } else {
1481                 shortest_distance = cfs_cpt_distance(lnet_cpt_table(), md_cpt,
1482                                                      best_ni->ni_dev_cpt);
1483                 best_credits = atomic_read(&best_ni->ni_tx_credits);
1484                 best_healthv = atomic_read(&best_ni->ni_healthv);
1485         }
1486
1487         while ((ni = lnet_get_next_ni_locked(local_net, ni))) {
1488                 unsigned int distance;
1489                 int ni_credits;
1490                 int ni_healthv;
1491                 int ni_fatal;
1492
1493                 ni_credits = atomic_read(&ni->ni_tx_credits);
1494                 ni_healthv = atomic_read(&ni->ni_healthv);
1495                 ni_fatal = atomic_read(&ni->ni_fatal_error_on);
1496
1497                 /*
1498                  * calculate the distance from the CPT on which
1499                  * the message memory is allocated to the CPT of
1500                  * the NI's physical device
1501                  */
1502                 distance = cfs_cpt_distance(lnet_cpt_table(),
1503                                             md_cpt,
1504                                             ni->ni_dev_cpt);
1505
1506                 CDEBUG(D_NET, "compare ni %s [c:%d, d:%d, s:%d] with best_ni %s [c:%d, d:%d, s:%d]\n",
1507                        libcfs_nid2str(ni->ni_nid), ni_credits, distance,
1508                        ni->ni_seq, (best_ni) ? libcfs_nid2str(best_ni->ni_nid)
1509                         : "not seleced", best_credits, shortest_distance,
1510                         (best_ni) ? best_ni->ni_seq : 0);
1511
1512                 /*
1513                  * All distances smaller than the NUMA range
1514                  * are treated equally.
1515                  */
1516                 if (distance < lnet_numa_range)
1517                         distance = lnet_numa_range;
1518
1519                 /*
1520                  * Select on health, shorter distance, available
1521                  * credits, then round-robin.
1522                  */
1523                 if (ni_fatal) {
1524                         continue;
1525                 } else if (ni_healthv < best_healthv) {
1526                         continue;
1527                 } else if (ni_healthv > best_healthv) {
1528                         best_healthv = ni_healthv;
1529                         /*
1530                          * If we're going to prefer this ni because it's
1531                          * the healthiest, then we should set the
1532                          * shortest_distance in the algorithm in case
1533                          * there are multiple NIs with the same health but
1534                          * different distances.
1535                          */
1536                         if (distance < shortest_distance)
1537                                 shortest_distance = distance;
1538                 } else if (distance > shortest_distance) {
1539                         continue;
1540                 } else if (distance < shortest_distance) {
1541                         shortest_distance = distance;
1542                 } else if (ni_credits < best_credits) {
1543                         continue;
1544                 } else if (ni_credits == best_credits) {
1545                         if (best_ni && best_ni->ni_seq <= ni->ni_seq)
1546                                 continue;
1547                 }
1548                 best_ni = ni;
1549                 best_credits = ni_credits;
1550         }
1551
1552         CDEBUG(D_NET, "selected best_ni %s\n",
1553                (best_ni) ? libcfs_nid2str(best_ni->ni_nid) : "no selection");
1554
1555         return best_ni;
1556 }
1557
1558 /*
1559  * Traffic to the LNET_RESERVED_PORTAL may not trigger peer discovery,
1560  * because such traffic is required to perform discovery. We therefore
1561  * exclude all GET and PUT on that portal. We also exclude all ACK and
1562  * REPLY traffic, but that is because the portal is not tracked in the
1563  * message structure for these message types. We could restrict this
1564  * further by also checking for LNET_PROTO_PING_MATCHBITS.
1565  */
1566 static bool
1567 lnet_msg_discovery(struct lnet_msg *msg)
1568 {
1569         if (msg->msg_type == LNET_MSG_PUT) {
1570                 if (msg->msg_hdr.msg.put.ptl_index != LNET_RESERVED_PORTAL)
1571                         return true;
1572         } else if (msg->msg_type == LNET_MSG_GET) {
1573                 if (msg->msg_hdr.msg.get.ptl_index != LNET_RESERVED_PORTAL)
1574                         return true;
1575         }
1576         return false;
1577 }
1578
1579 #define SRC_SPEC        0x0001
1580 #define SRC_ANY         0x0002
1581 #define LOCAL_DST       0x0004
1582 #define REMOTE_DST      0x0008
1583 #define MR_DST          0x0010
1584 #define NMR_DST         0x0020
1585 #define SND_RESP        0x0040
1586
1587 /* The following to defines are used for return codes */
1588 #define REPEAT_SEND     0x1000
1589 #define PASS_THROUGH    0x2000
1590
1591 /* The different cases lnet_select pathway needs to handle */
1592 #define SRC_SPEC_LOCAL_MR_DST   (SRC_SPEC | LOCAL_DST | MR_DST)
1593 #define SRC_SPEC_ROUTER_MR_DST  (SRC_SPEC | REMOTE_DST | MR_DST)
1594 #define SRC_SPEC_LOCAL_NMR_DST  (SRC_SPEC | LOCAL_DST | NMR_DST)
1595 #define SRC_SPEC_ROUTER_NMR_DST (SRC_SPEC | REMOTE_DST | NMR_DST)
1596 #define SRC_ANY_LOCAL_MR_DST    (SRC_ANY | LOCAL_DST | MR_DST)
1597 #define SRC_ANY_ROUTER_MR_DST   (SRC_ANY | REMOTE_DST | MR_DST)
1598 #define SRC_ANY_LOCAL_NMR_DST   (SRC_ANY | LOCAL_DST | NMR_DST)
1599 #define SRC_ANY_ROUTER_NMR_DST  (SRC_ANY | REMOTE_DST | NMR_DST)
1600
1601 static int
1602 lnet_handle_send(struct lnet_send_data *sd)
1603 {
1604         struct lnet_ni *best_ni = sd->sd_best_ni;
1605         struct lnet_peer_ni *best_lpni = sd->sd_best_lpni;
1606         struct lnet_peer_ni *final_dst_lpni = sd->sd_final_dst_lpni;
1607         struct lnet_msg *msg = sd->sd_msg;
1608         int cpt2;
1609         __u32 send_case = sd->sd_send_case;
1610         int rc;
1611         __u32 routing = send_case & REMOTE_DST;
1612
1613         /*
1614          * Increment sequence number of the selected peer so that we
1615          * pick the next one in Round Robin.
1616          */
1617         best_lpni->lpni_seq++;
1618
1619         /*
1620          * grab a reference on the peer_ni so it sticks around even if
1621          * we need to drop and relock the lnet_net_lock below.
1622          */
1623         lnet_peer_ni_addref_locked(best_lpni);
1624
1625         /*
1626          * Use lnet_cpt_of_nid() to determine the CPT used to commit the
1627          * message. This ensures that we get a CPT that is correct for
1628          * the NI when the NI has been restricted to a subset of all CPTs.
1629          * If the selected CPT differs from the one currently locked, we
1630          * must unlock and relock the lnet_net_lock(), and then check whether
1631          * the configuration has changed. We don't have a hold on the best_ni
1632          * yet, and it may have vanished.
1633          */
1634         cpt2 = lnet_cpt_of_nid_locked(best_lpni->lpni_nid, best_ni);
1635         if (sd->sd_cpt != cpt2) {
1636                 __u32 seq = lnet_get_dlc_seq_locked();
1637                 lnet_net_unlock(sd->sd_cpt);
1638                 sd->sd_cpt = cpt2;
1639                 lnet_net_lock(sd->sd_cpt);
1640                 if (seq != lnet_get_dlc_seq_locked()) {
1641                         lnet_peer_ni_decref_locked(best_lpni);
1642                         return REPEAT_SEND;
1643                 }
1644         }
1645
1646         /*
1647          * store the best_lpni in the message right away to avoid having
1648          * to do the same operation under different conditions
1649          */
1650         msg->msg_txpeer = best_lpni;
1651         msg->msg_txni = best_ni;
1652
1653         /*
1654          * grab a reference for the best_ni since now it's in use in this
1655          * send. The reference will be dropped in lnet_finalize()
1656          */
1657         lnet_ni_addref_locked(msg->msg_txni, sd->sd_cpt);
1658
1659         /*
1660          * Always set the target.nid to the best peer picked. Either the
1661          * NID will be one of the peer NIDs selected, or the same NID as
1662          * what was originally set in the target or it will be the NID of
1663          * a router if this message should be routed
1664          */
1665         msg->msg_target.nid = msg->msg_txpeer->lpni_nid;
1666
1667         /*
1668          * lnet_msg_commit assigns the correct cpt to the message, which
1669          * is used to decrement the correct refcount on the ni when it's
1670          * time to return the credits
1671          */
1672         lnet_msg_commit(msg, sd->sd_cpt);
1673
1674         /*
1675          * If we are routing the message then we keep the src_nid that was
1676          * set by the originator. If we are not routing then we are the
1677          * originator and set it here.
1678          */
1679         if (!msg->msg_routing)
1680                 msg->msg_hdr.src_nid = cpu_to_le64(msg->msg_txni->ni_nid);
1681
1682         if (routing) {
1683                 msg->msg_target_is_router = 1;
1684                 msg->msg_target.pid = LNET_PID_LUSTRE;
1685                 /*
1686                  * since we're routing we want to ensure that the
1687                  * msg_hdr.dest_nid is set to the final destination. When
1688                  * the router receives this message it knows how to route
1689                  * it.
1690                  *
1691                  * final_dst_lpni is set at the beginning of the
1692                  * lnet_select_pathway() function and is never changed.
1693                  * It's safe to use it here.
1694                  */
1695                 msg->msg_hdr.dest_nid = cpu_to_le64(final_dst_lpni->lpni_nid);
1696         } else {
1697                 /*
1698                  * if we're not routing set the dest_nid to the best peer
1699                  * ni NID that we picked earlier in the algorithm.
1700                  */
1701                 msg->msg_hdr.dest_nid = cpu_to_le64(msg->msg_txpeer->lpni_nid);
1702         }
1703
1704         rc = lnet_post_send_locked(msg, 0);
1705
1706         if (!rc)
1707                 CDEBUG(D_NET, "TRACE: %s(%s:%s) -> %s(%s:%s) : %s try# %d\n",
1708                        libcfs_nid2str(msg->msg_hdr.src_nid),
1709                        libcfs_nid2str(msg->msg_txni->ni_nid),
1710                        libcfs_nid2str(sd->sd_src_nid),
1711                        libcfs_nid2str(msg->msg_hdr.dest_nid),
1712                        libcfs_nid2str(sd->sd_dst_nid),
1713                        libcfs_nid2str(msg->msg_txpeer->lpni_nid),
1714                        lnet_msgtyp2str(msg->msg_type), msg->msg_retry_count);
1715
1716         return rc;
1717 }
1718
1719 static struct lnet_peer_ni *
1720 lnet_select_peer_ni(struct lnet_send_data *sd, struct lnet_peer *peer,
1721                     struct lnet_peer_net *peer_net)
1722 {
1723         /*
1724          * Look at the peer NIs for the destination peer that connect
1725          * to the chosen net. If a peer_ni is preferred when using the
1726          * best_ni to communicate, we use that one. If there is no
1727          * preferred peer_ni, or there are multiple preferred peer_ni,
1728          * the available transmit credits are used. If the transmit
1729          * credits are equal, we round-robin over the peer_ni.
1730          */
1731         struct lnet_peer_ni *lpni = NULL;
1732         struct lnet_peer_ni *best_lpni = NULL;
1733         struct lnet_ni *best_ni = sd->sd_best_ni;
1734         lnet_nid_t dst_nid = sd->sd_dst_nid;
1735         int best_lpni_credits = INT_MIN;
1736         bool preferred = false;
1737         bool ni_is_pref;
1738         int best_lpni_healthv = 0;
1739         int lpni_healthv;
1740
1741         while ((lpni = lnet_get_next_peer_ni_locked(peer, peer_net, lpni))) {
1742                 /*
1743                  * if the best_ni we've chosen aleady has this lpni
1744                  * preferred, then let's use it
1745                  */
1746                 ni_is_pref = lnet_peer_is_pref_nid_locked(lpni,
1747                                                           best_ni->ni_nid);
1748
1749                 lpni_healthv = atomic_read(&lpni->lpni_healthv);
1750
1751                 CDEBUG(D_NET, "%s ni_is_pref = %d\n",
1752                        libcfs_nid2str(best_ni->ni_nid), ni_is_pref);
1753
1754                 if (best_lpni)
1755                         CDEBUG(D_NET, "%s c:[%d, %d], s:[%d, %d]\n",
1756                                 libcfs_nid2str(lpni->lpni_nid),
1757                                 lpni->lpni_txcredits, best_lpni_credits,
1758                                 lpni->lpni_seq, best_lpni->lpni_seq);
1759
1760                 /* pick the healthiest peer ni */
1761                 if (lpni_healthv < best_lpni_healthv) {
1762                         continue;
1763                 } else if (lpni_healthv > best_lpni_healthv) {
1764                         best_lpni_healthv = lpni_healthv;
1765                 /* if this is a preferred peer use it */
1766                 } else if (!preferred && ni_is_pref) {
1767                         preferred = true;
1768                 } else if (preferred && !ni_is_pref) {
1769                         /*
1770                          * this is not the preferred peer so let's ignore
1771                          * it.
1772                          */
1773                         continue;
1774                 } else if (lpni->lpni_txcredits < best_lpni_credits) {
1775                         /*
1776                          * We already have a peer that has more credits
1777                          * available than this one. No need to consider
1778                          * this peer further.
1779                          */
1780                         continue;
1781                 } else if (lpni->lpni_txcredits == best_lpni_credits) {
1782                         /*
1783                          * The best peer found so far and the current peer
1784                          * have the same number of available credits let's
1785                          * make sure to select between them using Round
1786                          * Robin
1787                          */
1788                         if (best_lpni) {
1789                                 if (best_lpni->lpni_seq <= lpni->lpni_seq)
1790                                         continue;
1791                         }
1792                 }
1793
1794                 best_lpni = lpni;
1795                 best_lpni_credits = lpni->lpni_txcredits;
1796         }
1797
1798         /* if we still can't find a peer ni then we can't reach it */
1799         if (!best_lpni) {
1800                 __u32 net_id = (peer_net) ? peer_net->lpn_net_id :
1801                         LNET_NIDNET(dst_nid);
1802                 CDEBUG(D_NET, "no peer_ni found on peer net %s\n",
1803                                 libcfs_net2str(net_id));
1804                 return NULL;
1805         }
1806
1807         CDEBUG(D_NET, "sd_best_lpni = %s\n",
1808                libcfs_nid2str(best_lpni->lpni_nid));
1809
1810         return best_lpni;
1811 }
1812
1813 /*
1814  * Prerequisite: the best_ni should already be set in the sd
1815  */
1816 static inline struct lnet_peer_ni *
1817 lnet_find_best_lpni_on_net(struct lnet_send_data *sd, struct lnet_peer *peer,
1818                            __u32 net_id)
1819 {
1820         struct lnet_peer_net *peer_net;
1821
1822         /*
1823          * The gateway is Multi-Rail capable so now we must select the
1824          * proper peer_ni
1825          */
1826         peer_net = lnet_peer_get_net_locked(peer, net_id);
1827
1828         if (!peer_net) {
1829                 CERROR("gateway peer %s has no NI on net %s\n",
1830                        libcfs_nid2str(peer->lp_primary_nid),
1831                        libcfs_net2str(net_id));
1832                 return NULL;
1833         }
1834
1835         return lnet_select_peer_ni(sd, peer, peer_net);
1836 }
1837
1838 static inline void
1839 lnet_set_non_mr_pref_nid(struct lnet_send_data *sd)
1840 {
1841         if (sd->sd_send_case & NMR_DST &&
1842             sd->sd_msg->msg_type != LNET_MSG_REPLY &&
1843             sd->sd_msg->msg_type != LNET_MSG_ACK &&
1844             sd->sd_best_lpni->lpni_pref_nnids == 0) {
1845                 CDEBUG(D_NET, "Setting preferred local NID %s on NMR peer %s\n",
1846                        libcfs_nid2str(sd->sd_best_ni->ni_nid),
1847                        libcfs_nid2str(sd->sd_best_lpni->lpni_nid));
1848                 lnet_peer_ni_set_non_mr_pref_nid(sd->sd_best_lpni,
1849                                                  sd->sd_best_ni->ni_nid);
1850         }
1851 }
1852
1853 /*
1854  * Source Specified
1855  * Local Destination
1856  * non-mr peer
1857  *
1858  * use the source and destination NIDs as the pathway
1859  */
1860 static int
1861 lnet_handle_spec_local_nmr_dst(struct lnet_send_data *sd)
1862 {
1863         /* the destination lpni is set before we get here. */
1864
1865         /* find local NI */
1866         sd->sd_best_ni = lnet_nid2ni_locked(sd->sd_src_nid, sd->sd_cpt);
1867         if (!sd->sd_best_ni) {
1868                 CERROR("Can't send to %s: src %s is not a "
1869                        "local nid\n", libcfs_nid2str(sd->sd_dst_nid),
1870                                 libcfs_nid2str(sd->sd_src_nid));
1871                 return -EINVAL;
1872         }
1873
1874         /*
1875          * the preferred NID will only be set for NMR peers
1876          */
1877         lnet_set_non_mr_pref_nid(sd);
1878
1879         return lnet_handle_send(sd);
1880 }
1881
1882 /*
1883  * Source Specified
1884  * Local Destination
1885  * MR Peer
1886  *
1887  * Run the selection algorithm on the peer NIs unless we're sending
1888  * a response, in this case just send to the destination
1889  */
1890 static int
1891 lnet_handle_spec_local_mr_dst(struct lnet_send_data *sd)
1892 {
1893         sd->sd_best_ni = lnet_nid2ni_locked(sd->sd_src_nid, sd->sd_cpt);
1894         if (!sd->sd_best_ni) {
1895                 CERROR("Can't send to %s: src %s is not a "
1896                        "local nid\n", libcfs_nid2str(sd->sd_dst_nid),
1897                                 libcfs_nid2str(sd->sd_src_nid));
1898                 return -EINVAL;
1899         }
1900
1901         /*
1902          * only run the selection algorithm to pick the peer_ni if we're
1903          * sending a GET or a PUT. Responses are sent to the same
1904          * destination NID provided.
1905          */
1906         if (!(sd->sd_send_case & SND_RESP)) {
1907                 sd->sd_best_lpni =
1908                   lnet_find_best_lpni_on_net(sd, sd->sd_peer,
1909                                              sd->sd_best_ni->ni_net->net_id);
1910         }
1911
1912         if (sd->sd_best_lpni)
1913                 return lnet_handle_send(sd);
1914
1915         CERROR("can't send to %s. no NI on %s\n",
1916                libcfs_nid2str(sd->sd_dst_nid),
1917                libcfs_net2str(sd->sd_best_ni->ni_net->net_id));
1918
1919         return -EHOSTUNREACH;
1920 }
1921
1922 struct lnet_ni *
1923 lnet_find_best_ni_on_spec_net(struct lnet_ni *cur_best_ni,
1924                               struct lnet_peer *peer,
1925                               struct lnet_peer_net *peer_net,
1926                               int cpt,
1927                               bool incr_seq)
1928 {
1929         struct lnet_net *local_net;
1930         struct lnet_ni *best_ni;
1931
1932         local_net = lnet_get_net_locked(peer_net->lpn_net_id);
1933         if (!local_net)
1934                 return NULL;
1935
1936         /*
1937          * Iterate through the NIs in this local Net and select
1938          * the NI to send from. The selection is determined by
1939          * these 3 criterion in the following priority:
1940          *      1. NUMA
1941          *      2. NI available credits
1942          *      3. Round Robin
1943          */
1944         best_ni = lnet_get_best_ni(local_net, cur_best_ni,
1945                                    peer, peer_net, cpt);
1946
1947         if (incr_seq && best_ni)
1948                 best_ni->ni_seq++;
1949
1950         return best_ni;
1951 }
1952
1953 static int
1954 lnet_handle_find_routed_path(struct lnet_send_data *sd,
1955                              lnet_nid_t dst_nid,
1956                              struct lnet_peer_ni **gw_lpni,
1957                              struct lnet_peer **gw_peer)
1958 {
1959         struct lnet_peer_ni *gw;
1960         lnet_nid_t src_nid = sd->sd_src_nid;
1961
1962         gw = lnet_find_route_locked(NULL, LNET_NIDNET(dst_nid),
1963                                     sd->sd_rtr_nid);
1964         if (!gw) {
1965                 CERROR("no route to %s from %s\n",
1966                        libcfs_nid2str(dst_nid), libcfs_nid2str(src_nid));
1967                 return -EHOSTUNREACH;
1968         }
1969
1970         /* get the peer of the gw_ni */
1971         LASSERT(gw->lpni_peer_net);
1972         LASSERT(gw->lpni_peer_net->lpn_peer);
1973
1974         *gw_peer = gw->lpni_peer_net->lpn_peer;
1975
1976         if (!sd->sd_best_ni)
1977                 sd->sd_best_ni = lnet_find_best_ni_on_spec_net(NULL, *gw_peer,
1978                                         gw->lpni_peer_net,
1979                                         sd->sd_md_cpt,
1980                                         true);
1981
1982         if (!sd->sd_best_ni) {
1983                 CERROR("Internal Error. Expected local ni on %s "
1984                        "but non found :%s\n",
1985                        libcfs_net2str(gw->lpni_peer_net->lpn_net_id),
1986                        libcfs_nid2str(sd->sd_src_nid));
1987                 return -EFAULT;
1988         }
1989
1990         /*
1991          * if gw is MR let's find its best peer_ni
1992          */
1993         if (lnet_peer_is_multi_rail(*gw_peer)) {
1994                 gw = lnet_find_best_lpni_on_net(sd, *gw_peer,
1995                                                 sd->sd_best_ni->ni_net->net_id);
1996                 /*
1997                  * We've already verified that the gw has an NI on that
1998                  * desired net, but we're not finding it. Something is
1999                  * wrong.
2000                  */
2001                 if (!gw) {
2002                         CERROR("Internal Error. Route expected to %s from %s\n",
2003                                 libcfs_nid2str(dst_nid),
2004                                 libcfs_nid2str(src_nid));
2005                         return -EFAULT;
2006                 }
2007         }
2008
2009         *gw_lpni = gw;
2010
2011         return 0;
2012 }
2013
2014 /*
2015  * Handle two cases:
2016  *
2017  * Case 1:
2018  *  Source specified
2019  *  Remote destination
2020  *  Non-MR destination
2021  *
2022  * Case 2:
2023  *  Source specified
2024  *  Remote destination
2025  *  MR destination
2026  *
2027  * The handling of these two cases is similar. Even though the destination
2028  * can be MR or non-MR, we'll deal directly with the router.
2029  */
2030 static int
2031 lnet_handle_spec_router_dst(struct lnet_send_data *sd)
2032 {
2033         int rc;
2034         struct lnet_peer_ni *gw_lpni = NULL;
2035         struct lnet_peer *gw_peer = NULL;
2036
2037         /* find local NI */
2038         sd->sd_best_ni = lnet_nid2ni_locked(sd->sd_src_nid, sd->sd_cpt);
2039         if (!sd->sd_best_ni) {
2040                 CERROR("Can't send to %s: src %s is not a "
2041                        "local nid\n", libcfs_nid2str(sd->sd_dst_nid),
2042                                 libcfs_nid2str(sd->sd_src_nid));
2043                 return -EINVAL;
2044         }
2045
2046         rc = lnet_handle_find_routed_path(sd, sd->sd_dst_nid, &gw_lpni,
2047                                      &gw_peer);
2048         if (rc < 0)
2049                 return rc;
2050
2051         if (sd->sd_send_case & NMR_DST)
2052                 /*
2053                 * since the final destination is non-MR let's set its preferred
2054                 * NID before we send
2055                 */
2056                 lnet_set_non_mr_pref_nid(sd);
2057
2058         /*
2059          * We're going to send to the gw found so let's set its
2060          * info
2061          */
2062         sd->sd_peer = gw_peer;
2063         sd->sd_best_lpni = gw_lpni;
2064
2065         return lnet_handle_send(sd);
2066 }
2067
2068 struct lnet_ni *
2069 lnet_find_best_ni_on_local_net(struct lnet_peer *peer, int md_cpt)
2070 {
2071         struct lnet_peer_net *peer_net = NULL;
2072         struct lnet_ni *best_ni = NULL;
2073
2074         /*
2075          * The peer can have multiple interfaces, some of them can be on
2076          * the local network and others on a routed network. We should
2077          * prefer the local network. However if the local network is not
2078          * available then we need to try the routed network
2079          */
2080
2081         /* go through all the peer nets and find the best_ni */
2082         list_for_each_entry(peer_net, &peer->lp_peer_nets, lpn_peer_nets) {
2083                 /*
2084                  * The peer's list of nets can contain non-local nets. We
2085                  * want to only examine the local ones.
2086                  */
2087                 if (!lnet_get_net_locked(peer_net->lpn_net_id))
2088                         continue;
2089                 best_ni = lnet_find_best_ni_on_spec_net(best_ni, peer,
2090                                                    peer_net, md_cpt, false);
2091         }
2092
2093         if (best_ni)
2094                 /* increment sequence number so we can round robin */
2095                 best_ni->ni_seq++;
2096
2097         return best_ni;
2098 }
2099
2100 static struct lnet_ni *
2101 lnet_find_existing_preferred_best_ni(struct lnet_send_data *sd)
2102 {
2103         struct lnet_ni *best_ni = NULL;
2104         struct lnet_peer_net *peer_net;
2105         struct lnet_peer *peer = sd->sd_peer;
2106         struct lnet_peer_ni *best_lpni = sd->sd_best_lpni;
2107         struct lnet_peer_ni *lpni;
2108         int cpt = sd->sd_cpt;
2109
2110         /*
2111          * We must use a consistent source address when sending to a
2112          * non-MR peer. However, a non-MR peer can have multiple NIDs
2113          * on multiple networks, and we may even need to talk to this
2114          * peer on multiple networks -- certain types of
2115          * load-balancing configuration do this.
2116          *
2117          * So we need to pick the NI the peer prefers for this
2118          * particular network.
2119          */
2120
2121         /* Get the target peer_ni */
2122         peer_net = lnet_peer_get_net_locked(peer,
2123                         LNET_NIDNET(best_lpni->lpni_nid));
2124         LASSERT(peer_net != NULL);
2125         list_for_each_entry(lpni, &peer_net->lpn_peer_nis,
2126                                 lpni_peer_nis) {
2127                 if (lpni->lpni_pref_nnids == 0)
2128                         continue;
2129                 LASSERT(lpni->lpni_pref_nnids == 1);
2130                 best_ni = lnet_nid2ni_locked(
2131                                 lpni->lpni_pref.nid, cpt);
2132                 break;
2133         }
2134
2135         return best_ni;
2136 }
2137
2138 /* Prerequisite: sd->sd_peer and sd->sd_best_lpni should be set */
2139 static int
2140 lnet_select_preferred_best_ni(struct lnet_send_data *sd)
2141 {
2142         struct lnet_ni *best_ni = NULL;
2143         struct lnet_peer_ni *best_lpni = sd->sd_best_lpni;
2144
2145         /*
2146          * We must use a consistent source address when sending to a
2147          * non-MR peer. However, a non-MR peer can have multiple NIDs
2148          * on multiple networks, and we may even need to talk to this
2149          * peer on multiple networks -- certain types of
2150          * load-balancing configuration do this.
2151          *
2152          * So we need to pick the NI the peer prefers for this
2153          * particular network.
2154          */
2155
2156         best_ni = lnet_find_existing_preferred_best_ni(sd);
2157
2158         /* if best_ni is still not set just pick one */
2159         if (!best_ni) {
2160                 best_ni =
2161                   lnet_find_best_ni_on_spec_net(NULL, sd->sd_peer,
2162                                                 sd->sd_best_lpni->lpni_peer_net,
2163                                                 sd->sd_md_cpt, true);
2164                 /* If there is no best_ni we don't have a route */
2165                 if (!best_ni) {
2166                         CERROR("no path to %s from net %s\n",
2167                                 libcfs_nid2str(best_lpni->lpni_nid),
2168                                 libcfs_net2str(best_lpni->lpni_net->net_id));
2169                         return -EHOSTUNREACH;
2170                 }
2171         }
2172
2173         sd->sd_best_ni = best_ni;
2174
2175         /* Set preferred NI if necessary. */
2176         lnet_set_non_mr_pref_nid(sd);
2177
2178         return 0;
2179 }
2180
2181
2182 /*
2183  * Source not specified
2184  * Local destination
2185  * Non-MR Peer
2186  *
2187  * always use the same source NID for NMR peers
2188  * If we've talked to that peer before then we already have a preferred
2189  * source NI associated with it. Otherwise, we select a preferred local NI
2190  * and store it in the peer
2191  */
2192 static int
2193 lnet_handle_any_local_nmr_dst(struct lnet_send_data *sd)
2194 {
2195         int rc;
2196
2197         /* sd->sd_best_lpni is already set to the final destination */
2198
2199         /*
2200          * At this point we should've created the peer ni and peer. If we
2201          * can't find it, then something went wrong. Instead of assert
2202          * output a relevant message and fail the send
2203          */
2204         if (!sd->sd_best_lpni) {
2205                 CERROR("Internal fault. Unable to send msg %s to %s. "
2206                        "NID not known\n",
2207                        lnet_msgtyp2str(sd->sd_msg->msg_type),
2208                        libcfs_nid2str(sd->sd_dst_nid));
2209                 return -EFAULT;
2210         }
2211
2212         rc = lnet_select_preferred_best_ni(sd);
2213         if (!rc)
2214                 rc = lnet_handle_send(sd);
2215
2216         return rc;
2217 }
2218
2219 static int
2220 lnet_handle_any_mr_dsta(struct lnet_send_data *sd)
2221 {
2222         /*
2223          * NOTE we've already handled the remote peer case. So we only
2224          * need to worry about the local case here.
2225          *
2226          * if we're sending a response, ACK or reply, we need to send it
2227          * to the destination NID given to us. At this point we already
2228          * have the peer_ni we're suppose to send to, so just find the
2229          * best_ni on the peer net and use that. Since we're sending to an
2230          * MR peer then we can just run the selection algorithm on our
2231          * local NIs and pick the best one.
2232          */
2233         if (sd->sd_send_case & SND_RESP) {
2234                 sd->sd_best_ni =
2235                   lnet_find_best_ni_on_spec_net(NULL, sd->sd_peer,
2236                                                 sd->sd_best_lpni->lpni_peer_net,
2237                                                 sd->sd_md_cpt, true);
2238
2239                 if (!sd->sd_best_ni) {
2240                         /*
2241                          * We're not going to deal with not able to send
2242                          * a response to the provided final destination
2243                          */
2244                         CERROR("Can't send response to %s. "
2245                                "No local NI available\n",
2246                                 libcfs_nid2str(sd->sd_dst_nid));
2247                         return -EHOSTUNREACH;
2248                 }
2249
2250                 return lnet_handle_send(sd);
2251         }
2252
2253         /*
2254          * If we get here that means we're sending a fresh request, PUT or
2255          * GET, so we need to run our standard selection algorithm.
2256          * First find the best local interface that's on any of the peer's
2257          * networks.
2258          */
2259         sd->sd_best_ni = lnet_find_best_ni_on_local_net(sd->sd_peer,
2260                                                         sd->sd_md_cpt);
2261         if (sd->sd_best_ni) {
2262                 sd->sd_best_lpni =
2263                   lnet_find_best_lpni_on_net(sd, sd->sd_peer,
2264                                              sd->sd_best_ni->ni_net->net_id);
2265
2266                 /*
2267                  * if we're successful in selecting a peer_ni on the local
2268                  * network, then send to it. Otherwise fall through and
2269                  * try and see if we can reach it over another routed
2270                  * network
2271                  */
2272                 if (sd->sd_best_lpni) {
2273                         /*
2274                          * in case we initially started with a routed
2275                          * destination, let's reset to local
2276                          */
2277                         sd->sd_send_case &= ~REMOTE_DST;
2278                         sd->sd_send_case |= LOCAL_DST;
2279                         return lnet_handle_send(sd);
2280                 }
2281
2282                 CERROR("Internal Error. Expected to have a best_lpni: "
2283                        "%s -> %s\n",
2284                        libcfs_nid2str(sd->sd_src_nid),
2285                        libcfs_nid2str(sd->sd_dst_nid));
2286
2287                 return -EFAULT;
2288         }
2289
2290         /*
2291          * Peer doesn't have a local network. Let's see if there is
2292          * a remote network we can reach it on.
2293          */
2294         return PASS_THROUGH;
2295 }
2296
2297 /*
2298  * Case 1:
2299  *      Source NID not specified
2300  *      Local destination
2301  *      MR peer
2302  *
2303  * Case 2:
2304  *      Source NID not speified
2305  *      Remote destination
2306  *      MR peer
2307  *
2308  * In both of these cases if we're sending a response, ACK or REPLY, then
2309  * we need to send to the destination NID provided.
2310  *
2311  * In the remote case let's deal with MR routers.
2312  *
2313  */
2314
2315 static int
2316 lnet_handle_any_mr_dst(struct lnet_send_data *sd)
2317 {
2318         int rc = 0;
2319         struct lnet_peer *gw_peer = NULL;
2320         struct lnet_peer_ni *gw_lpni = NULL;
2321
2322         /*
2323          * handle sending a response to a remote peer here so we don't
2324          * have to worry about it if we hit lnet_handle_any_mr_dsta()
2325          */
2326         if (sd->sd_send_case & REMOTE_DST &&
2327             sd->sd_send_case & SND_RESP) {
2328                 struct lnet_peer_ni *gw;
2329                 struct lnet_peer *gw_peer;
2330
2331                 rc = lnet_handle_find_routed_path(sd, sd->sd_dst_nid, &gw,
2332                                                   &gw_peer);
2333                 if (rc < 0) {
2334                         CERROR("Can't send response to %s. "
2335                                "No route available\n",
2336                                 libcfs_nid2str(sd->sd_dst_nid));
2337                         return -EHOSTUNREACH;
2338                 }
2339
2340                 sd->sd_best_lpni = gw;
2341                 sd->sd_peer = gw_peer;
2342
2343                 return lnet_handle_send(sd);
2344         }
2345
2346         /*
2347          * Even though the NID for the peer might not be on a local network,
2348          * since the peer is MR there could be other interfaces on the
2349          * local network. In that case we'd still like to prefer the local
2350          * network over the routed network. If we're unable to do that
2351          * then we select the best router among the different routed networks,
2352          * and if the router is MR then we can deal with it as such.
2353          */
2354         rc = lnet_handle_any_mr_dsta(sd);
2355         if (rc != PASS_THROUGH)
2356                 return rc;
2357
2358         /*
2359          * TODO; One possible enhancement is to run the selection
2360          * algorithm on the peer. However for remote peers the credits are
2361          * not decremented, so we'll be basically going over the peer NIs
2362          * in round robin. An MR router will run the selection algorithm
2363          * on the next-hop interfaces.
2364          */
2365         rc = lnet_handle_find_routed_path(sd, sd->sd_dst_nid, &gw_lpni,
2366                                           &gw_peer);
2367         if (rc < 0)
2368                 return rc;
2369
2370         sd->sd_send_case &= ~LOCAL_DST;
2371         sd->sd_send_case |= REMOTE_DST;
2372
2373         sd->sd_peer = gw_peer;
2374         sd->sd_best_lpni = gw_lpni;
2375
2376         return lnet_handle_send(sd);
2377 }
2378
2379 /*
2380  * Source not specified
2381  * Remote destination
2382  * Non-MR peer
2383  *
2384  * Must send to the specified peer NID using the same source NID that
2385  * we've used before. If it's the first time to talk to that peer then
2386  * find the source NI and assign it as preferred to that peer
2387  */
2388 static int
2389 lnet_handle_any_router_nmr_dst(struct lnet_send_data *sd)
2390 {
2391         int rc;
2392         struct lnet_peer_ni *gw_lpni = NULL;
2393         struct lnet_peer *gw_peer = NULL;
2394
2395         /*
2396          * Let's set if we have a preferred NI to talk to this NMR peer
2397          */
2398         sd->sd_best_ni = lnet_find_existing_preferred_best_ni(sd);
2399
2400         /*
2401          * find the router and that'll find the best NI if we didn't find
2402          * it already.
2403          */
2404         rc = lnet_handle_find_routed_path(sd, sd->sd_dst_nid, &gw_lpni,
2405                                           &gw_peer);
2406         if (rc < 0)
2407                 return rc;
2408
2409         /*
2410          * set the best_ni we've chosen as the preferred one for
2411          * this peer
2412          */
2413         lnet_set_non_mr_pref_nid(sd);
2414
2415         /* we'll be sending to the gw */
2416         sd->sd_best_lpni = gw_lpni;
2417         sd->sd_peer = gw_peer;
2418
2419         return lnet_handle_send(sd);
2420 }
2421
2422 static int
2423 lnet_handle_send_case_locked(struct lnet_send_data *sd)
2424 {
2425         /*
2426          * turn off the SND_RESP bit.
2427          * It will be checked in the case handling
2428          */
2429         __u32 send_case = sd->sd_send_case &= ~SND_RESP ;
2430
2431         CDEBUG(D_NET, "Source %s%s to %s %s %s destination\n",
2432                 (send_case & SRC_SPEC) ? "Specified: " : "ANY",
2433                 (send_case & SRC_SPEC) ? libcfs_nid2str(sd->sd_src_nid) : "",
2434                 (send_case & MR_DST) ? "MR: " : "NMR: ",
2435                 libcfs_nid2str(sd->sd_dst_nid),
2436                 (send_case & LOCAL_DST) ? "local" : "routed");
2437
2438         switch (send_case) {
2439         /*
2440          * For all cases where the source is specified, we should always
2441          * use the destination NID, whether it's an MR destination or not,
2442          * since we're continuing a series of related messages for the
2443          * same RPC
2444          */
2445         case SRC_SPEC_LOCAL_NMR_DST:
2446                 return lnet_handle_spec_local_nmr_dst(sd);
2447         case SRC_SPEC_LOCAL_MR_DST:
2448                 return lnet_handle_spec_local_mr_dst(sd);
2449         case SRC_SPEC_ROUTER_NMR_DST:
2450         case SRC_SPEC_ROUTER_MR_DST:
2451                 return lnet_handle_spec_router_dst(sd);
2452         case SRC_ANY_LOCAL_NMR_DST:
2453                 return lnet_handle_any_local_nmr_dst(sd);
2454         case SRC_ANY_LOCAL_MR_DST:
2455         case SRC_ANY_ROUTER_MR_DST:
2456                 return lnet_handle_any_mr_dst(sd);
2457         case SRC_ANY_ROUTER_NMR_DST:
2458                 return lnet_handle_any_router_nmr_dst(sd);
2459         default:
2460                 CERROR("Unknown send case\n");
2461                 return -1;
2462         }
2463 }
2464
2465 static int
2466 lnet_select_pathway(lnet_nid_t src_nid, lnet_nid_t dst_nid,
2467                     struct lnet_msg *msg, lnet_nid_t rtr_nid)
2468 {
2469         struct lnet_peer_ni     *lpni;
2470         struct lnet_peer        *peer;
2471         struct lnet_send_data   send_data;
2472         int                     cpt, rc;
2473         int                     md_cpt;
2474         __u32                   send_case = 0;
2475
2476         memset(&send_data, 0, sizeof(send_data));
2477
2478         /*
2479          * get an initial CPT to use for locking. The idea here is not to
2480          * serialize the calls to select_pathway, so that as many
2481          * operations can run concurrently as possible. To do that we use
2482          * the CPT where this call is being executed. Later on when we
2483          * determine the CPT to use in lnet_message_commit, we switch the
2484          * lock and check if there was any configuration change.  If none,
2485          * then we proceed, if there is, then we restart the operation.
2486          */
2487         cpt = lnet_net_lock_current();
2488
2489         md_cpt = lnet_cpt_of_md(msg->msg_md, msg->msg_offset);
2490         if (md_cpt == CFS_CPT_ANY)
2491                 md_cpt = cpt;
2492
2493 again:
2494
2495         /*
2496          * If we're being asked to send to the loopback interface, there
2497          * is no need to go through any selection. We can just shortcut
2498          * the entire process and send over lolnd
2499          */
2500         if (LNET_NETTYP(LNET_NIDNET(dst_nid)) == LOLND) {
2501                 /* No send credit hassles with LOLND */
2502                 lnet_ni_addref_locked(the_lnet.ln_loni, cpt);
2503                 msg->msg_hdr.dest_nid = cpu_to_le64(the_lnet.ln_loni->ni_nid);
2504                 if (!msg->msg_routing)
2505                         msg->msg_hdr.src_nid =
2506                                 cpu_to_le64(the_lnet.ln_loni->ni_nid);
2507                 msg->msg_target.nid = the_lnet.ln_loni->ni_nid;
2508                 lnet_msg_commit(msg, cpt);
2509                 msg->msg_txni = the_lnet.ln_loni;
2510                 lnet_net_unlock(cpt);
2511
2512                 return LNET_CREDIT_OK;
2513         }
2514
2515         /*
2516          * find an existing peer_ni, or create one and mark it as having been
2517          * created due to network traffic. This call will create the
2518          * peer->peer_net->peer_ni tree.
2519          */
2520         lpni = lnet_nid2peerni_locked(dst_nid, LNET_NID_ANY, cpt);
2521         if (IS_ERR(lpni)) {
2522                 lnet_net_unlock(cpt);
2523                 return PTR_ERR(lpni);
2524         }
2525
2526         /*
2527          * Cache the original src_nid. If we need to resend the message
2528          * then we'll need to know whether the src_nid was originally
2529          * specified for this message. If it was originally specified,
2530          * then we need to keep using the same src_nid since it's
2531          * continuing the same sequence of messages.
2532          */
2533         msg->msg_src_nid_param = src_nid;
2534
2535         /*
2536          * Now that we have a peer_ni, check if we want to discover
2537          * the peer. Traffic to the LNET_RESERVED_PORTAL should not
2538          * trigger discovery.
2539          */
2540         peer = lpni->lpni_peer_net->lpn_peer;
2541         if (lnet_msg_discovery(msg) && !lnet_peer_is_uptodate(peer)) {
2542                 lnet_nid_t primary_nid;
2543                 rc = lnet_discover_peer_locked(lpni, cpt, false);
2544                 if (rc) {
2545                         lnet_peer_ni_decref_locked(lpni);
2546                         lnet_net_unlock(cpt);
2547                         return rc;
2548                 }
2549                 /* The peer may have changed. */
2550                 peer = lpni->lpni_peer_net->lpn_peer;
2551                 /* queue message and return */
2552                 msg->msg_rtr_nid_param = rtr_nid;
2553                 msg->msg_sending = 0;
2554                 list_add_tail(&msg->msg_list, &peer->lp_dc_pendq);
2555                 lnet_peer_ni_decref_locked(lpni);
2556                 primary_nid = peer->lp_primary_nid;
2557                 lnet_net_unlock(cpt);
2558
2559                 CDEBUG(D_NET, "%s pending discovery\n",
2560                        libcfs_nid2str(primary_nid));
2561
2562                 return LNET_DC_WAIT;
2563         }
2564         lnet_peer_ni_decref_locked(lpni);
2565
2566         /*
2567          * Identify the different send cases
2568          */
2569         if (src_nid == LNET_NID_ANY)
2570                 send_case |= SRC_ANY;
2571         else
2572                 send_case |= SRC_SPEC;
2573
2574         if (lnet_get_net_locked(LNET_NIDNET(dst_nid)))
2575                 send_case |= LOCAL_DST;
2576         else
2577                 send_case |= REMOTE_DST;
2578
2579         /*
2580          * if this is a non-MR peer or if we're recovering a peer ni then
2581          * let's consider this an NMR case so we can hit the destination
2582          * NID.
2583          */
2584         if (!lnet_peer_is_multi_rail(peer) || msg->msg_recovery)
2585                 send_case |= NMR_DST;
2586         else
2587                 send_case |= MR_DST;
2588
2589         if (msg->msg_type == LNET_MSG_REPLY ||
2590             msg->msg_type == LNET_MSG_ACK)
2591                 send_case |= SND_RESP;
2592
2593         /* assign parameters to the send_data */
2594         send_data.sd_msg = msg;
2595         send_data.sd_rtr_nid = rtr_nid;
2596         send_data.sd_src_nid = src_nid;
2597         send_data.sd_dst_nid = dst_nid;
2598         send_data.sd_best_lpni = lpni;
2599         /*
2600          * keep a pointer to the final destination in case we're going to
2601          * route, so we'll need to access it later
2602          */
2603         send_data.sd_final_dst_lpni = lpni;
2604         send_data.sd_peer = peer;
2605         send_data.sd_md_cpt = md_cpt;
2606         send_data.sd_cpt = cpt;
2607         send_data.sd_send_case = send_case;
2608
2609         rc = lnet_handle_send_case_locked(&send_data);
2610
2611         if (rc == REPEAT_SEND)
2612                 goto again;
2613
2614         lnet_net_unlock(send_data.sd_cpt);
2615
2616         return rc;
2617 }
2618
2619 int
2620 lnet_send(lnet_nid_t src_nid, struct lnet_msg *msg, lnet_nid_t rtr_nid)
2621 {
2622         lnet_nid_t              dst_nid = msg->msg_target.nid;
2623         int                     rc;
2624
2625         /*
2626          * NB: rtr_nid is set to LNET_NID_ANY for all current use-cases,
2627          * but we might want to use pre-determined router for ACK/REPLY
2628          * in the future
2629          */
2630         /* NB: ni != NULL == interface pre-determined (ACK/REPLY) */
2631         LASSERT(msg->msg_txpeer == NULL);
2632         LASSERT(msg->msg_txni == NULL);
2633         LASSERT(!msg->msg_sending);
2634         LASSERT(!msg->msg_target_is_router);
2635         LASSERT(!msg->msg_receiving);
2636
2637         msg->msg_sending = 1;
2638
2639         LASSERT(!msg->msg_tx_committed);
2640
2641         rc = lnet_select_pathway(src_nid, dst_nid, msg, rtr_nid);
2642         if (rc < 0)
2643                 return rc;
2644
2645         if (rc == LNET_CREDIT_OK)
2646                 lnet_ni_send(msg->msg_txni, msg);
2647
2648         /* rc == LNET_CREDIT_OK or LNET_CREDIT_WAIT or LNET_DC_WAIT */
2649         return 0;
2650 }
2651
2652 enum lnet_mt_event_type {
2653         MT_TYPE_LOCAL_NI = 0,
2654         MT_TYPE_PEER_NI
2655 };
2656
2657 struct lnet_mt_event_info {
2658         enum lnet_mt_event_type mt_type;
2659         lnet_nid_t mt_nid;
2660 };
2661
2662 void
2663 lnet_detach_rsp_tracker(struct lnet_libmd *md, int cpt)
2664 {
2665         struct lnet_rsp_tracker *rspt;
2666
2667         /*
2668          * msg has a refcount on the MD so the MD is not going away.
2669          * The rspt queue for the cpt is protected by
2670          * the lnet_net_lock(cpt). cpt is the cpt of the MD cookie.
2671          */
2672         lnet_res_lock(cpt);
2673         if (!md->md_rspt_ptr) {
2674                 lnet_res_unlock(cpt);
2675                 return;
2676         }
2677         rspt = md->md_rspt_ptr;
2678         md->md_rspt_ptr = NULL;
2679
2680         /* debug code */
2681         LASSERT(rspt->rspt_cpt == cpt);
2682
2683         /*
2684          * invalidate the handle to indicate that a response has been
2685          * received, which will then lead the monitor thread to clean up
2686          * the rspt block.
2687          */
2688         LNetInvalidateMDHandle(&rspt->rspt_mdh);
2689         lnet_res_unlock(cpt);
2690 }
2691
2692 static void
2693 lnet_finalize_expired_responses(bool force)
2694 {
2695         struct lnet_libmd *md;
2696         struct list_head local_queue;
2697         struct lnet_rsp_tracker *rspt, *tmp;
2698         int i;
2699
2700         if (the_lnet.ln_mt_rstq == NULL)
2701                 return;
2702
2703         cfs_cpt_for_each(i, lnet_cpt_table()) {
2704                 INIT_LIST_HEAD(&local_queue);
2705
2706                 lnet_net_lock(i);
2707                 if (!the_lnet.ln_mt_rstq[i]) {
2708                         lnet_net_unlock(i);
2709                         continue;
2710                 }
2711                 list_splice_init(the_lnet.ln_mt_rstq[i], &local_queue);
2712                 lnet_net_unlock(i);
2713
2714                 list_for_each_entry_safe(rspt, tmp, &local_queue, rspt_on_list) {
2715                         /*
2716                          * The rspt mdh will be invalidated when a response
2717                          * is received or whenever we want to discard the
2718                          * block the monitor thread will walk the queue
2719                          * and clean up any rsts with an invalid mdh.
2720                          * The monitor thread will walk the queue until
2721                          * the first unexpired rspt block. This means that
2722                          * some rspt blocks which received their
2723                          * corresponding responses will linger in the
2724                          * queue until they are cleaned up eventually.
2725                          */
2726                         lnet_res_lock(i);
2727                         if (LNetMDHandleIsInvalid(rspt->rspt_mdh)) {
2728                                 lnet_res_unlock(i);
2729                                 list_del_init(&rspt->rspt_on_list);
2730                                 lnet_rspt_free(rspt, i);
2731                                 continue;
2732                         }
2733
2734                         if (ktime_compare(ktime_get(), rspt->rspt_deadline) >= 0 ||
2735                             force) {
2736                                 md = lnet_handle2md(&rspt->rspt_mdh);
2737                                 if (!md) {
2738                                         LNetInvalidateMDHandle(&rspt->rspt_mdh);
2739                                         lnet_res_unlock(i);
2740                                         list_del_init(&rspt->rspt_on_list);
2741                                         lnet_rspt_free(rspt, i);
2742                                         continue;
2743                                 }
2744                                 LASSERT(md->md_rspt_ptr == rspt);
2745                                 md->md_rspt_ptr = NULL;
2746                                 lnet_res_unlock(i);
2747
2748                                 lnet_net_lock(i);
2749                                 the_lnet.ln_counters[i]->lct_health.lch_response_timeout_count++;
2750                                 lnet_net_unlock(i);
2751
2752                                 list_del_init(&rspt->rspt_on_list);
2753
2754                                 CNETERR("Response timed out: md = %p\n", md);
2755                                 LNetMDUnlink(rspt->rspt_mdh);
2756                                 lnet_rspt_free(rspt, i);
2757                         } else {
2758                                 lnet_res_unlock(i);
2759                                 break;
2760                         }
2761                 }
2762
2763                 lnet_net_lock(i);
2764                 if (!list_empty(&local_queue))
2765                         list_splice(&local_queue, the_lnet.ln_mt_rstq[i]);
2766                 lnet_net_unlock(i);
2767         }
2768 }
2769
2770 static void
2771 lnet_resend_pending_msgs_locked(struct list_head *resendq, int cpt)
2772 {
2773         struct lnet_msg *msg;
2774
2775         while (!list_empty(resendq)) {
2776                 struct lnet_peer_ni *lpni;
2777
2778                 msg = list_entry(resendq->next, struct lnet_msg,
2779                                  msg_list);
2780
2781                 list_del_init(&msg->msg_list);
2782
2783                 lpni = lnet_find_peer_ni_locked(msg->msg_hdr.dest_nid);
2784                 if (!lpni) {
2785                         lnet_net_unlock(cpt);
2786                         CERROR("Expected that a peer is already created for %s\n",
2787                                libcfs_nid2str(msg->msg_hdr.dest_nid));
2788                         msg->msg_no_resend = true;
2789                         lnet_finalize(msg, -EFAULT);
2790                         lnet_net_lock(cpt);
2791                 } else {
2792                         struct lnet_peer *peer;
2793                         int rc;
2794                         lnet_nid_t src_nid = LNET_NID_ANY;
2795
2796                         /*
2797                          * if this message is not being routed and the
2798                          * peer is non-MR then we must use the same
2799                          * src_nid that was used in the original send.
2800                          * Otherwise if we're routing the message (IE
2801                          * we're a router) then we can use any of our
2802                          * local interfaces. It doesn't matter to the
2803                          * final destination.
2804                          */
2805                         peer = lpni->lpni_peer_net->lpn_peer;
2806                         if (!msg->msg_routing &&
2807                             !lnet_peer_is_multi_rail(peer))
2808                                 src_nid = le64_to_cpu(msg->msg_hdr.src_nid);
2809
2810                         /*
2811                          * If we originally specified a src NID, then we
2812                          * must attempt to reuse it in the resend as well.
2813                          */
2814                         if (msg->msg_src_nid_param != LNET_NID_ANY)
2815                                 src_nid = msg->msg_src_nid_param;
2816                         lnet_peer_ni_decref_locked(lpni);
2817
2818                         lnet_net_unlock(cpt);
2819                         CDEBUG(D_NET, "resending %s->%s: %s recovery %d try# %d\n",
2820                                libcfs_nid2str(src_nid),
2821                                libcfs_id2str(msg->msg_target),
2822                                lnet_msgtyp2str(msg->msg_type),
2823                                msg->msg_recovery,
2824                                msg->msg_retry_count);
2825                         rc = lnet_send(src_nid, msg, LNET_NID_ANY);
2826                         if (rc) {
2827                                 CERROR("Error sending %s to %s: %d\n",
2828                                        lnet_msgtyp2str(msg->msg_type),
2829                                        libcfs_id2str(msg->msg_target), rc);
2830                                 msg->msg_no_resend = true;
2831                                 lnet_finalize(msg, rc);
2832                         }
2833                         lnet_net_lock(cpt);
2834                         if (!rc)
2835                                 the_lnet.ln_counters[cpt]->lct_health.lch_resend_count++;
2836                 }
2837         }
2838 }
2839
2840 static void
2841 lnet_resend_pending_msgs(void)
2842 {
2843         int i;
2844
2845         cfs_cpt_for_each(i, lnet_cpt_table()) {
2846                 lnet_net_lock(i);
2847                 lnet_resend_pending_msgs_locked(the_lnet.ln_mt_resendqs[i], i);
2848                 lnet_net_unlock(i);
2849         }
2850 }
2851
2852 /* called with cpt and ni_lock held */
2853 static void
2854 lnet_unlink_ni_recovery_mdh_locked(struct lnet_ni *ni, int cpt, bool force)
2855 {
2856         struct lnet_handle_md recovery_mdh;
2857
2858         LNetInvalidateMDHandle(&recovery_mdh);
2859
2860         if (ni->ni_state & LNET_NI_STATE_RECOVERY_PENDING || force) {
2861                 recovery_mdh = ni->ni_ping_mdh;
2862                 LNetInvalidateMDHandle(&ni->ni_ping_mdh);
2863         }
2864         lnet_ni_unlock(ni);
2865         lnet_net_unlock(cpt);
2866         if (!LNetMDHandleIsInvalid(recovery_mdh))
2867                 LNetMDUnlink(recovery_mdh);
2868         lnet_net_lock(cpt);
2869         lnet_ni_lock(ni);
2870 }
2871
2872 static void
2873 lnet_recover_local_nis(void)
2874 {
2875         struct lnet_mt_event_info *ev_info;
2876         struct list_head processed_list;
2877         struct list_head local_queue;
2878         struct lnet_handle_md mdh;
2879         struct lnet_ni *tmp;
2880         struct lnet_ni *ni;
2881         lnet_nid_t nid;
2882         int healthv;
2883         int rc;
2884
2885         INIT_LIST_HEAD(&local_queue);
2886         INIT_LIST_HEAD(&processed_list);
2887
2888         /*
2889          * splice the recovery queue on a local queue. We will iterate
2890          * through the local queue and update it as needed. Once we're
2891          * done with the traversal, we'll splice the local queue back on
2892          * the head of the ln_mt_localNIRecovq. Any newly added local NIs
2893          * will be traversed in the next iteration.
2894          */
2895         lnet_net_lock(0);
2896         list_splice_init(&the_lnet.ln_mt_localNIRecovq,
2897                          &local_queue);
2898         lnet_net_unlock(0);
2899
2900         list_for_each_entry_safe(ni, tmp, &local_queue, ni_recovery) {
2901                 /*
2902                  * if an NI is being deleted or it is now healthy, there
2903                  * is no need to keep it around in the recovery queue.
2904                  * The monitor thread is the only thread responsible for
2905                  * removing the NI from the recovery queue.
2906                  * Multiple threads can be adding NIs to the recovery
2907                  * queue.
2908                  */
2909                 healthv = atomic_read(&ni->ni_healthv);
2910
2911                 lnet_net_lock(0);
2912                 lnet_ni_lock(ni);
2913                 if (!(ni->ni_state & LNET_NI_STATE_ACTIVE) ||
2914                     healthv == LNET_MAX_HEALTH_VALUE) {
2915                         list_del_init(&ni->ni_recovery);
2916                         lnet_unlink_ni_recovery_mdh_locked(ni, 0, false);
2917                         lnet_ni_unlock(ni);
2918                         lnet_ni_decref_locked(ni, 0);
2919                         lnet_net_unlock(0);
2920                         continue;
2921                 }
2922
2923                 /*
2924                  * if the local NI failed recovery we must unlink the md.
2925                  * But we want to keep the local_ni on the recovery queue
2926                  * so we can continue the attempts to recover it.
2927                  */
2928                 if (ni->ni_state & LNET_NI_STATE_RECOVERY_FAILED) {
2929                         lnet_unlink_ni_recovery_mdh_locked(ni, 0, true);
2930                         ni->ni_state &= ~LNET_NI_STATE_RECOVERY_FAILED;
2931                 }
2932
2933                 lnet_ni_unlock(ni);
2934                 lnet_net_unlock(0);
2935
2936
2937                 CDEBUG(D_NET, "attempting to recover local ni: %s\n",
2938                        libcfs_nid2str(ni->ni_nid));
2939
2940                 lnet_ni_lock(ni);
2941                 if (!(ni->ni_state & LNET_NI_STATE_RECOVERY_PENDING)) {
2942                         ni->ni_state |= LNET_NI_STATE_RECOVERY_PENDING;
2943                         lnet_ni_unlock(ni);
2944
2945                         LIBCFS_ALLOC(ev_info, sizeof(*ev_info));
2946                         if (!ev_info) {
2947                                 CERROR("out of memory. Can't recover %s\n",
2948                                        libcfs_nid2str(ni->ni_nid));
2949                                 lnet_ni_lock(ni);
2950                                 ni->ni_state &= ~LNET_NI_STATE_RECOVERY_PENDING;
2951                                 lnet_ni_unlock(ni);
2952                                 continue;
2953                         }
2954
2955                         mdh = ni->ni_ping_mdh;
2956                         /*
2957                          * Invalidate the ni mdh in case it's deleted.
2958                          * We'll unlink the mdh in this case below.
2959                          */
2960                         LNetInvalidateMDHandle(&ni->ni_ping_mdh);
2961                         nid = ni->ni_nid;
2962
2963                         /*
2964                          * remove the NI from the local queue and drop the
2965                          * reference count to it while we're recovering
2966                          * it. The reason for that, is that the NI could
2967                          * be deleted, and the way the code is structured
2968                          * is if we don't drop the NI, then the deletion
2969                          * code will enter a loop waiting for the
2970                          * reference count to be removed while holding the
2971                          * ln_mutex_lock(). When we look up the peer to
2972                          * send to in lnet_select_pathway() we will try to
2973                          * lock the ln_mutex_lock() as well, leading to
2974                          * a deadlock. By dropping the refcount and
2975                          * removing it from the list, we allow for the NI
2976                          * to be removed, then we use the cached NID to
2977                          * look it up again. If it's gone, then we just
2978                          * continue examining the rest of the queue.
2979                          */
2980                         lnet_net_lock(0);
2981                         list_del_init(&ni->ni_recovery);
2982                         lnet_ni_decref_locked(ni, 0);
2983                         lnet_net_unlock(0);
2984
2985                         ev_info->mt_type = MT_TYPE_LOCAL_NI;
2986                         ev_info->mt_nid = nid;
2987                         rc = lnet_send_ping(nid, &mdh, LNET_INTERFACES_MIN,
2988                                             ev_info, the_lnet.ln_mt_eqh, true);
2989                         /* lookup the nid again */
2990                         lnet_net_lock(0);
2991                         ni = lnet_nid2ni_locked(nid, 0);
2992                         if (!ni) {
2993                                 /*
2994                                  * the NI has been deleted when we dropped
2995                                  * the ref count
2996                                  */
2997                                 lnet_net_unlock(0);
2998                                 LNetMDUnlink(mdh);
2999                                 continue;
3000                         }
3001                         /*
3002                          * Same note as in lnet_recover_peer_nis(). When
3003                          * we're sending the ping, the NI is free to be
3004                          * deleted or manipulated. By this point it
3005                          * could've been added back on the recovery queue,
3006                          * and a refcount taken on it.
3007                          * So we can't just add it blindly again or we'll
3008                          * corrupt the queue. We must check under lock if
3009                          * it's not on any list and if not then add it
3010                          * to the processed list, which will eventually be
3011                          * spliced back on to the recovery queue.
3012                          */
3013                         ni->ni_ping_mdh = mdh;
3014                         if (list_empty(&ni->ni_recovery)) {
3015                                 list_add_tail(&ni->ni_recovery, &processed_list);
3016                                 lnet_ni_addref_locked(ni, 0);
3017                         }
3018                         lnet_net_unlock(0);
3019
3020                         lnet_ni_lock(ni);
3021                         if (rc)
3022                                 ni->ni_state &= ~LNET_NI_STATE_RECOVERY_PENDING;
3023                 }
3024                 lnet_ni_unlock(ni);
3025         }
3026
3027         /*
3028          * put back the remaining NIs on the ln_mt_localNIRecovq to be
3029          * reexamined in the next iteration.
3030          */
3031         list_splice_init(&processed_list, &local_queue);
3032         lnet_net_lock(0);
3033         list_splice(&local_queue, &the_lnet.ln_mt_localNIRecovq);
3034         lnet_net_unlock(0);
3035 }
3036
3037 static struct list_head **
3038 lnet_create_array_of_queues(void)
3039 {
3040         struct list_head **qs;
3041         struct list_head *q;
3042         int i;
3043
3044         qs = cfs_percpt_alloc(lnet_cpt_table(),
3045                               sizeof(struct list_head));
3046         if (!qs) {
3047                 CERROR("Failed to allocate queues\n");
3048                 return NULL;
3049         }
3050
3051         cfs_percpt_for_each(q, i, qs)
3052                 INIT_LIST_HEAD(q);
3053
3054         return qs;
3055 }
3056
3057 static int
3058 lnet_resendqs_create(void)
3059 {
3060         struct list_head **resendqs;
3061         resendqs = lnet_create_array_of_queues();
3062
3063         if (!resendqs)
3064                 return -ENOMEM;
3065
3066         lnet_net_lock(LNET_LOCK_EX);
3067         the_lnet.ln_mt_resendqs = resendqs;
3068         lnet_net_unlock(LNET_LOCK_EX);
3069
3070         return 0;
3071 }
3072
3073 static void
3074 lnet_clean_local_ni_recoveryq(void)
3075 {
3076         struct lnet_ni *ni;
3077
3078         /* This is only called when the monitor thread has stopped */
3079         lnet_net_lock(0);
3080
3081         while (!list_empty(&the_lnet.ln_mt_localNIRecovq)) {
3082                 ni = list_entry(the_lnet.ln_mt_localNIRecovq.next,
3083                                 struct lnet_ni, ni_recovery);
3084                 list_del_init(&ni->ni_recovery);
3085                 lnet_ni_lock(ni);
3086                 lnet_unlink_ni_recovery_mdh_locked(ni, 0, true);
3087                 lnet_ni_unlock(ni);
3088                 lnet_ni_decref_locked(ni, 0);
3089         }
3090
3091         lnet_net_unlock(0);
3092 }
3093
3094 static void
3095 lnet_unlink_lpni_recovery_mdh_locked(struct lnet_peer_ni *lpni, int cpt,
3096                                      bool force)
3097 {
3098         struct lnet_handle_md recovery_mdh;
3099
3100         LNetInvalidateMDHandle(&recovery_mdh);
3101
3102         if (lpni->lpni_state & LNET_PEER_NI_RECOVERY_PENDING || force) {
3103                 recovery_mdh = lpni->lpni_recovery_ping_mdh;
3104                 LNetInvalidateMDHandle(&lpni->lpni_recovery_ping_mdh);
3105         }
3106         spin_unlock(&lpni->lpni_lock);
3107         lnet_net_unlock(cpt);
3108         if (!LNetMDHandleIsInvalid(recovery_mdh))
3109                 LNetMDUnlink(recovery_mdh);
3110         lnet_net_lock(cpt);
3111         spin_lock(&lpni->lpni_lock);
3112 }
3113
3114 static void
3115 lnet_clean_peer_ni_recoveryq(void)
3116 {
3117         struct lnet_peer_ni *lpni, *tmp;
3118
3119         lnet_net_lock(LNET_LOCK_EX);
3120
3121         list_for_each_entry_safe(lpni, tmp, &the_lnet.ln_mt_peerNIRecovq,
3122                                  lpni_recovery) {
3123                 list_del_init(&lpni->lpni_recovery);
3124                 spin_lock(&lpni->lpni_lock);
3125                 lnet_unlink_lpni_recovery_mdh_locked(lpni, LNET_LOCK_EX, true);
3126                 spin_unlock(&lpni->lpni_lock);
3127                 lnet_peer_ni_decref_locked(lpni);
3128         }
3129
3130         lnet_net_unlock(LNET_LOCK_EX);
3131 }
3132
3133 static void
3134 lnet_clean_resendqs(void)
3135 {
3136         struct lnet_msg *msg, *tmp;
3137         struct list_head msgs;
3138         int i;
3139
3140         INIT_LIST_HEAD(&msgs);
3141
3142         cfs_cpt_for_each(i, lnet_cpt_table()) {
3143                 lnet_net_lock(i);
3144                 list_splice_init(the_lnet.ln_mt_resendqs[i], &msgs);
3145                 lnet_net_unlock(i);
3146                 list_for_each_entry_safe(msg, tmp, &msgs, msg_list) {
3147                         list_del_init(&msg->msg_list);
3148                         msg->msg_no_resend = true;
3149                         lnet_finalize(msg, -ESHUTDOWN);
3150                 }
3151         }
3152
3153         cfs_percpt_free(the_lnet.ln_mt_resendqs);
3154 }
3155
3156 static void
3157 lnet_recover_peer_nis(void)
3158 {
3159         struct lnet_mt_event_info *ev_info;
3160         struct list_head processed_list;
3161         struct list_head local_queue;
3162         struct lnet_handle_md mdh;
3163         struct lnet_peer_ni *lpni;
3164         struct lnet_peer_ni *tmp;
3165         lnet_nid_t nid;
3166         int healthv;
3167         int rc;
3168
3169         INIT_LIST_HEAD(&local_queue);
3170         INIT_LIST_HEAD(&processed_list);
3171
3172         /*
3173          * Always use cpt 0 for locking across all interactions with
3174          * ln_mt_peerNIRecovq
3175          */
3176         lnet_net_lock(0);
3177         list_splice_init(&the_lnet.ln_mt_peerNIRecovq,
3178                          &local_queue);
3179         lnet_net_unlock(0);
3180
3181         list_for_each_entry_safe(lpni, tmp, &local_queue,
3182                                  lpni_recovery) {
3183                 /*
3184                  * The same protection strategy is used here as is in the
3185                  * local recovery case.
3186                  */
3187                 lnet_net_lock(0);
3188                 healthv = atomic_read(&lpni->lpni_healthv);
3189                 spin_lock(&lpni->lpni_lock);
3190                 if (lpni->lpni_state & LNET_PEER_NI_DELETING ||
3191                     healthv == LNET_MAX_HEALTH_VALUE) {
3192                         list_del_init(&lpni->lpni_recovery);
3193                         lnet_unlink_lpni_recovery_mdh_locked(lpni, 0, false);
3194                         spin_unlock(&lpni->lpni_lock);
3195                         lnet_peer_ni_decref_locked(lpni);
3196                         lnet_net_unlock(0);
3197                         continue;
3198                 }
3199
3200                 /*
3201                  * If the peer NI has failed recovery we must unlink the
3202                  * md. But we want to keep the peer ni on the recovery
3203                  * queue so we can try to continue recovering it
3204                  */
3205                 if (lpni->lpni_state & LNET_PEER_NI_RECOVERY_FAILED) {
3206                         lnet_unlink_lpni_recovery_mdh_locked(lpni, 0, true);
3207                         lpni->lpni_state &= ~LNET_PEER_NI_RECOVERY_FAILED;
3208                 }
3209
3210                 spin_unlock(&lpni->lpni_lock);
3211                 lnet_net_unlock(0);
3212
3213                 /*
3214                  * NOTE: we're racing with peer deletion from user space.
3215                  * It's possible that a peer is deleted after we check its
3216                  * state. In this case the recovery can create a new peer
3217                  */
3218                 spin_lock(&lpni->lpni_lock);
3219                 if (!(lpni->lpni_state & LNET_PEER_NI_RECOVERY_PENDING) &&
3220                     !(lpni->lpni_state & LNET_PEER_NI_DELETING)) {
3221                         lpni->lpni_state |= LNET_PEER_NI_RECOVERY_PENDING;
3222                         spin_unlock(&lpni->lpni_lock);
3223
3224                         LIBCFS_ALLOC(ev_info, sizeof(*ev_info));
3225                         if (!ev_info) {
3226                                 CERROR("out of memory. Can't recover %s\n",
3227                                        libcfs_nid2str(lpni->lpni_nid));
3228                                 spin_lock(&lpni->lpni_lock);
3229                                 lpni->lpni_state &= ~LNET_PEER_NI_RECOVERY_PENDING;
3230                                 spin_unlock(&lpni->lpni_lock);
3231                                 continue;
3232                         }
3233
3234                         /* look at the comments in lnet_recover_local_nis() */
3235                         mdh = lpni->lpni_recovery_ping_mdh;
3236                         LNetInvalidateMDHandle(&lpni->lpni_recovery_ping_mdh);
3237                         nid = lpni->lpni_nid;
3238                         lnet_net_lock(0);
3239                         list_del_init(&lpni->lpni_recovery);
3240                         lnet_peer_ni_decref_locked(lpni);
3241                         lnet_net_unlock(0);
3242
3243                         ev_info->mt_type = MT_TYPE_PEER_NI;
3244                         ev_info->mt_nid = nid;
3245                         rc = lnet_send_ping(nid, &mdh, LNET_INTERFACES_MIN,
3246                                             ev_info, the_lnet.ln_mt_eqh, true);
3247                         lnet_net_lock(0);
3248                         /*
3249                          * lnet_find_peer_ni_locked() grabs a refcount for
3250                          * us. No need to take it explicitly.
3251                          */
3252                         lpni = lnet_find_peer_ni_locked(nid);
3253                         if (!lpni) {
3254                                 lnet_net_unlock(0);
3255                                 LNetMDUnlink(mdh);
3256                                 continue;
3257                         }
3258
3259                         lpni->lpni_recovery_ping_mdh = mdh;
3260                         /*
3261                          * While we're unlocked the lpni could've been
3262                          * readded on the recovery queue. In this case we
3263                          * don't need to add it to the local queue, since
3264                          * it's already on there and the thread that added
3265                          * it would've incremented the refcount on the
3266                          * peer, which means we need to decref the refcount
3267                          * that was implicitly grabbed by find_peer_ni_locked.
3268                          * Otherwise, if the lpni is still not on
3269                          * the recovery queue, then we'll add it to the
3270                          * processed list.
3271                          */
3272                         if (list_empty(&lpni->lpni_recovery))
3273                                 list_add_tail(&lpni->lpni_recovery, &processed_list);
3274                         else
3275                                 lnet_peer_ni_decref_locked(lpni);
3276                         lnet_net_unlock(0);
3277
3278                         spin_lock(&lpni->lpni_lock);
3279                         if (rc)
3280                                 lpni->lpni_state &= ~LNET_PEER_NI_RECOVERY_PENDING;
3281                 }
3282                 spin_unlock(&lpni->lpni_lock);
3283         }
3284
3285         list_splice_init(&processed_list, &local_queue);
3286         lnet_net_lock(0);
3287         list_splice(&local_queue, &the_lnet.ln_mt_peerNIRecovq);
3288         lnet_net_unlock(0);
3289 }
3290
3291 static int
3292 lnet_monitor_thread(void *arg)
3293 {
3294         int wakeup_counter = 0;
3295
3296         /*
3297          * The monitor thread takes care of the following:
3298          *  1. Checks the aliveness of routers
3299          *  2. Checks if there are messages on the resend queue to resend
3300          *     them.
3301          *  3. Check if there are any NIs on the local recovery queue and
3302          *     pings them
3303          *  4. Checks if there are any NIs on the remote recovery queue
3304          *     and pings them.
3305          */
3306         cfs_block_allsigs();
3307
3308         while (the_lnet.ln_mt_state == LNET_MT_STATE_RUNNING) {
3309                 if (lnet_router_checker_active())
3310                         lnet_check_routers();
3311
3312                 lnet_resend_pending_msgs();
3313
3314                 wakeup_counter++;
3315                 if (wakeup_counter >= lnet_transaction_timeout / 2) {
3316                         lnet_finalize_expired_responses(false);
3317                         wakeup_counter = 0;
3318                 }
3319
3320                 lnet_recover_local_nis();
3321
3322                 lnet_recover_peer_nis();
3323
3324                 /*
3325                  * TODO do we need to check if we should sleep without
3326                  * timeout?  Technically, an active system will always
3327                  * have messages in flight so this check will always
3328                  * evaluate to false. And on an idle system do we care
3329                  * if we wake up every 1 second? Although, we've seen
3330                  * cases where we get a complaint that an idle thread
3331                  * is waking up unnecessarily.
3332                  */
3333                 wait_event_interruptible_timeout(the_lnet.ln_mt_waitq,
3334                                                 false,
3335                                                 cfs_time_seconds(1));
3336         }
3337
3338         /* clean up the router checker */
3339         lnet_prune_rc_data(1);
3340
3341         /* Shutting down */
3342         the_lnet.ln_mt_state = LNET_MT_STATE_SHUTDOWN;
3343
3344         /* signal that the monitor thread is exiting */
3345         up(&the_lnet.ln_mt_signal);
3346
3347         return 0;
3348 }
3349
3350 /*
3351  * lnet_send_ping
3352  * Sends a ping.
3353  * Returns == 0 if success
3354  * Returns > 0 if LNetMDBind or prior fails
3355  * Returns < 0 if LNetGet fails
3356  */
3357 int
3358 lnet_send_ping(lnet_nid_t dest_nid,
3359                struct lnet_handle_md *mdh, int nnis,
3360                void *user_data, struct lnet_handle_eq eqh, bool recovery)
3361 {
3362         struct lnet_md md = { NULL };
3363         struct lnet_process_id id;
3364         struct lnet_ping_buffer *pbuf;
3365         int rc;
3366
3367         if (dest_nid == LNET_NID_ANY) {
3368                 rc = -EHOSTUNREACH;
3369                 goto fail_error;
3370         }
3371
3372         pbuf = lnet_ping_buffer_alloc(nnis, GFP_NOFS);
3373         if (!pbuf) {
3374                 rc = ENOMEM;
3375                 goto fail_error;
3376         }
3377
3378         /* initialize md content */
3379         md.start     = &pbuf->pb_info;
3380         md.length    = LNET_PING_INFO_SIZE(nnis);
3381         md.threshold = 2; /* GET/REPLY */
3382         md.max_size  = 0;
3383         md.options   = LNET_MD_TRUNCATE;
3384         md.user_ptr  = user_data;
3385         md.eq_handle = eqh;
3386
3387         rc = LNetMDBind(md, LNET_UNLINK, mdh);
3388         if (rc) {
3389                 lnet_ping_buffer_decref(pbuf);
3390                 CERROR("Can't bind MD: %d\n", rc);
3391                 rc = -rc; /* change the rc to positive */
3392                 goto fail_error;
3393         }
3394         id.pid = LNET_PID_LUSTRE;
3395         id.nid = dest_nid;
3396
3397         rc = LNetGet(LNET_NID_ANY, *mdh, id,
3398                      LNET_RESERVED_PORTAL,
3399                      LNET_PROTO_PING_MATCHBITS, 0, recovery);
3400
3401         if (rc)
3402                 goto fail_unlink_md;
3403
3404         return 0;
3405
3406 fail_unlink_md:
3407         LNetMDUnlink(*mdh);
3408         LNetInvalidateMDHandle(mdh);
3409 fail_error:
3410         return rc;
3411 }
3412
3413 static void
3414 lnet_handle_recovery_reply(struct lnet_mt_event_info *ev_info,
3415                            int status)
3416 {
3417         lnet_nid_t nid = ev_info->mt_nid;
3418
3419         if (ev_info->mt_type == MT_TYPE_LOCAL_NI) {
3420                 struct lnet_ni *ni;
3421
3422                 lnet_net_lock(0);
3423                 ni = lnet_nid2ni_locked(nid, 0);
3424                 if (!ni) {
3425                         lnet_net_unlock(0);
3426                         return;
3427                 }
3428                 lnet_ni_lock(ni);
3429                 ni->ni_state &= ~LNET_NI_STATE_RECOVERY_PENDING;
3430                 if (status)
3431                         ni->ni_state |= LNET_NI_STATE_RECOVERY_FAILED;
3432                 lnet_ni_unlock(ni);
3433                 lnet_net_unlock(0);
3434
3435                 if (status != 0) {
3436                         CERROR("local NI (%s) recovery failed with %d\n",
3437                                libcfs_nid2str(nid), status);
3438                         return;
3439                 }
3440                 /*
3441                  * need to increment healthv for the ni here, because in
3442                  * the lnet_finalize() path we don't have access to this
3443                  * NI. And in order to get access to it, we'll need to
3444                  * carry forward too much information.
3445                  * In the peer case, it'll naturally be incremented
3446                  */
3447                 lnet_inc_healthv(&ni->ni_healthv);
3448         } else {
3449                 struct lnet_peer_ni *lpni;
3450                 int cpt;
3451
3452                 cpt = lnet_net_lock_current();
3453                 lpni = lnet_find_peer_ni_locked(nid);
3454                 if (!lpni) {
3455                         lnet_net_unlock(cpt);
3456                         return;
3457                 }
3458                 spin_lock(&lpni->lpni_lock);
3459                 lpni->lpni_state &= ~LNET_PEER_NI_RECOVERY_PENDING;
3460                 if (status)
3461                         lpni->lpni_state |= LNET_PEER_NI_RECOVERY_FAILED;
3462                 spin_unlock(&lpni->lpni_lock);
3463                 lnet_peer_ni_decref_locked(lpni);
3464                 lnet_net_unlock(cpt);
3465
3466                 if (status != 0)
3467                         CERROR("peer NI (%s) recovery failed with %d\n",
3468                                libcfs_nid2str(nid), status);
3469         }
3470 }
3471
3472 static void
3473 lnet_mt_event_handler(struct lnet_event *event)
3474 {
3475         struct lnet_mt_event_info *ev_info = event->md.user_ptr;
3476         struct lnet_ping_buffer *pbuf;
3477
3478         /* TODO: remove assert */
3479         LASSERT(event->type == LNET_EVENT_REPLY ||
3480                 event->type == LNET_EVENT_SEND ||
3481                 event->type == LNET_EVENT_UNLINK);
3482
3483         CDEBUG(D_NET, "Received event: %d status: %d\n", event->type,
3484                event->status);
3485
3486         switch (event->type) {
3487         case LNET_EVENT_UNLINK:
3488                 CDEBUG(D_NET, "%s recovery ping unlinked\n",
3489                        libcfs_nid2str(ev_info->mt_nid));
3490         case LNET_EVENT_REPLY:
3491                 lnet_handle_recovery_reply(ev_info, event->status);
3492                 break;
3493         case LNET_EVENT_SEND:
3494                 CDEBUG(D_NET, "%s recovery message sent %s:%d\n",
3495                                libcfs_nid2str(ev_info->mt_nid),
3496                                (event->status) ? "unsuccessfully" :
3497                                "successfully", event->status);
3498                 lnet_handle_recovery_reply(ev_info, event->status);
3499                 break;
3500         default:
3501                 CERROR("Unexpected event: %d\n", event->type);
3502                 break;
3503         }
3504         if (event->unlinked) {
3505                 LIBCFS_FREE(ev_info, sizeof(*ev_info));
3506                 pbuf = LNET_PING_INFO_TO_BUFFER(event->md.start);
3507                 lnet_ping_buffer_decref(pbuf);
3508         }
3509 }
3510
3511 static int
3512 lnet_rsp_tracker_create(void)
3513 {
3514         struct list_head **rstqs;
3515         rstqs = lnet_create_array_of_queues();
3516
3517         if (!rstqs)
3518                 return -ENOMEM;
3519
3520         the_lnet.ln_mt_rstq = rstqs;
3521
3522         return 0;
3523 }
3524
3525 static void
3526 lnet_rsp_tracker_clean(void)
3527 {
3528         lnet_finalize_expired_responses(true);
3529
3530         cfs_percpt_free(the_lnet.ln_mt_rstq);
3531         the_lnet.ln_mt_rstq = NULL;
3532 }
3533
3534 int lnet_monitor_thr_start(void)
3535 {
3536         int rc = 0;
3537         struct task_struct *task;
3538
3539         if (the_lnet.ln_mt_state != LNET_MT_STATE_SHUTDOWN)
3540                 return -EALREADY;
3541
3542         rc = lnet_resendqs_create();
3543         if (rc)
3544                 return rc;
3545
3546         rc = lnet_rsp_tracker_create();
3547         if (rc)
3548                 goto clean_queues;
3549
3550         rc = LNetEQAlloc(0, lnet_mt_event_handler, &the_lnet.ln_mt_eqh);
3551         if (rc != 0) {
3552                 CERROR("Can't allocate monitor thread EQ: %d\n", rc);
3553                 goto clean_queues;
3554         }
3555
3556         /* Pre monitor thread start processing */
3557         rc = lnet_router_pre_mt_start();
3558         if (rc)
3559                 goto free_mem;
3560
3561         sema_init(&the_lnet.ln_mt_signal, 0);
3562
3563         the_lnet.ln_mt_state = LNET_MT_STATE_RUNNING;
3564         task = kthread_run(lnet_monitor_thread, NULL, "monitor_thread");
3565         if (IS_ERR(task)) {
3566                 rc = PTR_ERR(task);
3567                 CERROR("Can't start monitor thread: %d\n", rc);
3568                 goto clean_thread;
3569         }
3570
3571         /* post monitor thread start processing */
3572         lnet_router_post_mt_start();
3573
3574         return 0;
3575
3576 clean_thread:
3577         the_lnet.ln_mt_state = LNET_MT_STATE_STOPPING;
3578         /* block until event callback signals exit */
3579         down(&the_lnet.ln_mt_signal);
3580         /* clean up */
3581         lnet_router_cleanup();
3582 free_mem:
3583         the_lnet.ln_mt_state = LNET_MT_STATE_SHUTDOWN;
3584         lnet_rsp_tracker_clean();
3585         lnet_clean_local_ni_recoveryq();
3586         lnet_clean_peer_ni_recoveryq();
3587         lnet_clean_resendqs();
3588         LNetEQFree(the_lnet.ln_mt_eqh);
3589         LNetInvalidateEQHandle(&the_lnet.ln_mt_eqh);
3590         return rc;
3591 clean_queues:
3592         lnet_rsp_tracker_clean();
3593         lnet_clean_local_ni_recoveryq();
3594         lnet_clean_peer_ni_recoveryq();
3595         lnet_clean_resendqs();
3596         return rc;
3597 }
3598
3599 void lnet_monitor_thr_stop(void)
3600 {
3601         int rc;
3602
3603         if (the_lnet.ln_mt_state == LNET_MT_STATE_SHUTDOWN)
3604                 return;
3605
3606         LASSERT(the_lnet.ln_mt_state == LNET_MT_STATE_RUNNING);
3607         the_lnet.ln_mt_state = LNET_MT_STATE_STOPPING;
3608
3609         /* tell the monitor thread that we're shutting down */
3610         wake_up(&the_lnet.ln_mt_waitq);
3611
3612         /* block until monitor thread signals that it's done */
3613         down(&the_lnet.ln_mt_signal);
3614         LASSERT(the_lnet.ln_mt_state == LNET_MT_STATE_SHUTDOWN);
3615
3616         /* perform cleanup tasks */
3617         lnet_router_cleanup();
3618         lnet_rsp_tracker_clean();
3619         lnet_clean_local_ni_recoveryq();
3620         lnet_clean_peer_ni_recoveryq();
3621         lnet_clean_resendqs();
3622         rc = LNetEQFree(the_lnet.ln_mt_eqh);
3623         LASSERT(rc == 0);
3624         return;
3625 }
3626
3627 void
3628 lnet_drop_message(struct lnet_ni *ni, int cpt, void *private, unsigned int nob,
3629                   __u32 msg_type)
3630 {
3631         lnet_net_lock(cpt);
3632         lnet_incr_stats(&ni->ni_stats, msg_type, LNET_STATS_TYPE_DROP);
3633         the_lnet.ln_counters[cpt]->lct_common.lcc_drop_count++;
3634         the_lnet.ln_counters[cpt]->lct_common.lcc_drop_length += nob;
3635         lnet_net_unlock(cpt);
3636
3637         lnet_ni_recv(ni, private, NULL, 0, 0, 0, nob);
3638 }
3639
3640 static void
3641 lnet_recv_put(struct lnet_ni *ni, struct lnet_msg *msg)
3642 {
3643         struct lnet_hdr *hdr = &msg->msg_hdr;
3644
3645         if (msg->msg_wanted != 0)
3646                 lnet_setpayloadbuffer(msg);
3647
3648         lnet_build_msg_event(msg, LNET_EVENT_PUT);
3649
3650         /* Must I ACK?  If so I'll grab the ack_wmd out of the header and put
3651          * it back into the ACK during lnet_finalize() */
3652         msg->msg_ack = (!lnet_is_wire_handle_none(&hdr->msg.put.ack_wmd) &&
3653                         (msg->msg_md->md_options & LNET_MD_ACK_DISABLE) == 0);
3654
3655         lnet_ni_recv(ni, msg->msg_private, msg, msg->msg_rx_delayed,
3656                      msg->msg_offset, msg->msg_wanted, hdr->payload_length);
3657 }
3658
3659 static int
3660 lnet_parse_put(struct lnet_ni *ni, struct lnet_msg *msg)
3661 {
3662         struct lnet_hdr         *hdr = &msg->msg_hdr;
3663         struct lnet_match_info  info;
3664         int                     rc;
3665         bool                    ready_delay;
3666
3667         /* Convert put fields to host byte order */
3668         hdr->msg.put.match_bits = le64_to_cpu(hdr->msg.put.match_bits);
3669         hdr->msg.put.ptl_index  = le32_to_cpu(hdr->msg.put.ptl_index);
3670         hdr->msg.put.offset     = le32_to_cpu(hdr->msg.put.offset);
3671
3672         /* Primary peer NID. */
3673         info.mi_id.nid  = msg->msg_initiator;
3674         info.mi_id.pid  = hdr->src_pid;
3675         info.mi_opc     = LNET_MD_OP_PUT;
3676         info.mi_portal  = hdr->msg.put.ptl_index;
3677         info.mi_rlength = hdr->payload_length;
3678         info.mi_roffset = hdr->msg.put.offset;
3679         info.mi_mbits   = hdr->msg.put.match_bits;
3680         info.mi_cpt     = lnet_cpt_of_nid(msg->msg_rxpeer->lpni_nid, ni);
3681
3682         msg->msg_rx_ready_delay = ni->ni_net->net_lnd->lnd_eager_recv == NULL;
3683         ready_delay = msg->msg_rx_ready_delay;
3684
3685  again:
3686         rc = lnet_ptl_match_md(&info, msg);
3687         switch (rc) {
3688         default:
3689                 LBUG();
3690
3691         case LNET_MATCHMD_OK:
3692                 lnet_recv_put(ni, msg);
3693                 return 0;
3694
3695         case LNET_MATCHMD_NONE:
3696                 if (ready_delay)
3697                         /* no eager_recv or has already called it, should
3698                          * have been attached on delayed list */
3699                         return 0;
3700
3701                 rc = lnet_ni_eager_recv(ni, msg);
3702                 if (rc == 0) {
3703                         ready_delay = true;
3704                         goto again;
3705                 }
3706                 /* fall through */
3707
3708         case LNET_MATCHMD_DROP:
3709                 CNETERR("Dropping PUT from %s portal %d match %llu"
3710                         " offset %d length %d: %d\n",
3711                         libcfs_id2str(info.mi_id), info.mi_portal,
3712                         info.mi_mbits, info.mi_roffset, info.mi_rlength, rc);
3713
3714                 return -ENOENT; /* -ve: OK but no match */
3715         }
3716 }
3717
3718 static int
3719 lnet_parse_get(struct lnet_ni *ni, struct lnet_msg *msg, int rdma_get)
3720 {
3721         struct lnet_match_info info;
3722         struct lnet_hdr *hdr = &msg->msg_hdr;
3723         struct lnet_process_id source_id;
3724         struct lnet_handle_wire reply_wmd;
3725         int rc;
3726
3727         /* Convert get fields to host byte order */
3728         hdr->msg.get.match_bits   = le64_to_cpu(hdr->msg.get.match_bits);
3729         hdr->msg.get.ptl_index    = le32_to_cpu(hdr->msg.get.ptl_index);
3730         hdr->msg.get.sink_length  = le32_to_cpu(hdr->msg.get.sink_length);
3731         hdr->msg.get.src_offset   = le32_to_cpu(hdr->msg.get.src_offset);
3732
3733         source_id.nid = hdr->src_nid;
3734         source_id.pid = hdr->src_pid;
3735         /* Primary peer NID */
3736         info.mi_id.nid  = msg->msg_initiator;
3737         info.mi_id.pid  = hdr->src_pid;
3738         info.mi_opc     = LNET_MD_OP_GET;
3739         info.mi_portal  = hdr->msg.get.ptl_index;
3740         info.mi_rlength = hdr->msg.get.sink_length;
3741         info.mi_roffset = hdr->msg.get.src_offset;
3742         info.mi_mbits   = hdr->msg.get.match_bits;
3743         info.mi_cpt     = lnet_cpt_of_nid(msg->msg_rxpeer->lpni_nid, ni);
3744
3745         rc = lnet_ptl_match_md(&info, msg);
3746         if (rc == LNET_MATCHMD_DROP) {
3747                 CNETERR("Dropping GET from %s portal %d match %llu"
3748                         " offset %d length %d\n",
3749                         libcfs_id2str(info.mi_id), info.mi_portal,
3750                         info.mi_mbits, info.mi_roffset, info.mi_rlength);
3751                 return -ENOENT; /* -ve: OK but no match */
3752         }
3753
3754         LASSERT(rc == LNET_MATCHMD_OK);
3755
3756         lnet_build_msg_event(msg, LNET_EVENT_GET);
3757
3758         reply_wmd = hdr->msg.get.return_wmd;
3759
3760         lnet_prep_send(msg, LNET_MSG_REPLY, source_id,
3761                        msg->msg_offset, msg->msg_wanted);
3762
3763         msg->msg_hdr.msg.reply.dst_wmd = reply_wmd;
3764
3765         if (rdma_get) {
3766                 /* The LND completes the REPLY from her recv procedure */
3767                 lnet_ni_recv(ni, msg->msg_private, msg, 0,
3768                              msg->msg_offset, msg->msg_len, msg->msg_len);
3769                 return 0;
3770         }
3771
3772         lnet_ni_recv(ni, msg->msg_private, NULL, 0, 0, 0, 0);
3773         msg->msg_receiving = 0;
3774
3775         rc = lnet_send(ni->ni_nid, msg, LNET_NID_ANY);
3776         if (rc < 0) {
3777                 /* didn't get as far as lnet_ni_send() */
3778                 CERROR("%s: Unable to send REPLY for GET from %s: %d\n",
3779                        libcfs_nid2str(ni->ni_nid),
3780                        libcfs_id2str(info.mi_id), rc);
3781
3782                 lnet_finalize(msg, rc);
3783         }
3784
3785         return 0;
3786 }
3787
3788 static int
3789 lnet_parse_reply(struct lnet_ni *ni, struct lnet_msg *msg)
3790 {
3791         void *private = msg->msg_private;
3792         struct lnet_hdr *hdr = &msg->msg_hdr;
3793         struct lnet_process_id src = {0};
3794         struct lnet_libmd *md;
3795         int rlength;
3796         int mlength;
3797         int cpt;
3798
3799         cpt = lnet_cpt_of_cookie(hdr->msg.reply.dst_wmd.wh_object_cookie);
3800         lnet_res_lock(cpt);
3801
3802         src.nid = hdr->src_nid;
3803         src.pid = hdr->src_pid;
3804
3805         /* NB handles only looked up by creator (no flips) */
3806         md = lnet_wire_handle2md(&hdr->msg.reply.dst_wmd);
3807         if (md == NULL || md->md_threshold == 0 || md->md_me != NULL) {
3808                 CNETERR("%s: Dropping REPLY from %s for %s "
3809                         "MD %#llx.%#llx\n",
3810                         libcfs_nid2str(ni->ni_nid), libcfs_id2str(src),
3811                         (md == NULL) ? "invalid" : "inactive",
3812                         hdr->msg.reply.dst_wmd.wh_interface_cookie,
3813                         hdr->msg.reply.dst_wmd.wh_object_cookie);
3814                 if (md != NULL && md->md_me != NULL)
3815                         CERROR("REPLY MD also attached to portal %d\n",
3816                                md->md_me->me_portal);
3817
3818                 lnet_res_unlock(cpt);
3819                 return -ENOENT; /* -ve: OK but no match */
3820         }
3821
3822         LASSERT(md->md_offset == 0);
3823
3824         rlength = hdr->payload_length;
3825         mlength = MIN(rlength, (int)md->md_length);
3826
3827         if (mlength < rlength &&
3828             (md->md_options & LNET_MD_TRUNCATE) == 0) {
3829                 CNETERR("%s: Dropping REPLY from %s length %d "
3830                         "for MD %#llx would overflow (%d)\n",
3831                         libcfs_nid2str(ni->ni_nid), libcfs_id2str(src),
3832                         rlength, hdr->msg.reply.dst_wmd.wh_object_cookie,
3833                         mlength);
3834                 lnet_res_unlock(cpt);
3835                 return -ENOENT; /* -ve: OK but no match */
3836         }
3837
3838         CDEBUG(D_NET, "%s: Reply from %s of length %d/%d into md %#llx\n",
3839                libcfs_nid2str(ni->ni_nid), libcfs_id2str(src),
3840                mlength, rlength, hdr->msg.reply.dst_wmd.wh_object_cookie);
3841
3842         lnet_msg_attach_md(msg, md, 0, mlength);
3843
3844         if (mlength != 0)
3845                 lnet_setpayloadbuffer(msg);
3846
3847         lnet_res_unlock(cpt);
3848
3849         lnet_build_msg_event(msg, LNET_EVENT_REPLY);
3850
3851         lnet_ni_recv(ni, private, msg, 0, 0, mlength, rlength);
3852         return 0;
3853 }
3854
3855 static int
3856 lnet_parse_ack(struct lnet_ni *ni, struct lnet_msg *msg)
3857 {
3858         struct lnet_hdr *hdr = &msg->msg_hdr;
3859         struct lnet_process_id src = {0};
3860         struct lnet_libmd *md;
3861         int cpt;
3862
3863         src.nid = hdr->src_nid;
3864         src.pid = hdr->src_pid;
3865
3866         /* Convert ack fields to host byte order */
3867         hdr->msg.ack.match_bits = le64_to_cpu(hdr->msg.ack.match_bits);
3868         hdr->msg.ack.mlength = le32_to_cpu(hdr->msg.ack.mlength);
3869
3870         cpt = lnet_cpt_of_cookie(hdr->msg.ack.dst_wmd.wh_object_cookie);
3871         lnet_res_lock(cpt);
3872
3873         /* NB handles only looked up by creator (no flips) */
3874         md = lnet_wire_handle2md(&hdr->msg.ack.dst_wmd);
3875         if (md == NULL || md->md_threshold == 0 || md->md_me != NULL) {
3876                 /* Don't moan; this is expected */
3877                 CDEBUG(D_NET,
3878                        "%s: Dropping ACK from %s to %s MD %#llx.%#llx\n",
3879                        libcfs_nid2str(ni->ni_nid), libcfs_id2str(src),
3880                        (md == NULL) ? "invalid" : "inactive",
3881                        hdr->msg.ack.dst_wmd.wh_interface_cookie,
3882                        hdr->msg.ack.dst_wmd.wh_object_cookie);
3883                 if (md != NULL && md->md_me != NULL)
3884                         CERROR("Source MD also attached to portal %d\n",
3885                                md->md_me->me_portal);
3886
3887                 lnet_res_unlock(cpt);
3888                 return -ENOENT;                  /* -ve! */
3889         }
3890
3891         CDEBUG(D_NET, "%s: ACK from %s into md %#llx\n",
3892                libcfs_nid2str(ni->ni_nid), libcfs_id2str(src),
3893                hdr->msg.ack.dst_wmd.wh_object_cookie);
3894
3895         lnet_msg_attach_md(msg, md, 0, 0);
3896
3897         lnet_res_unlock(cpt);
3898
3899         lnet_build_msg_event(msg, LNET_EVENT_ACK);
3900
3901         lnet_ni_recv(ni, msg->msg_private, msg, 0, 0, 0, msg->msg_len);
3902         return 0;
3903 }
3904
3905 /**
3906  * \retval LNET_CREDIT_OK       If \a msg is forwarded
3907  * \retval LNET_CREDIT_WAIT     If \a msg is blocked because w/o buffer
3908  * \retval -ve                  error code
3909  */
3910 int
3911 lnet_parse_forward_locked(struct lnet_ni *ni, struct lnet_msg *msg)
3912 {
3913         int     rc = 0;
3914
3915         if (!the_lnet.ln_routing)
3916                 return -ECANCELED;
3917
3918         if (msg->msg_rxpeer->lpni_rtrcredits <= 0 ||
3919             lnet_msg2bufpool(msg)->rbp_credits <= 0) {
3920                 if (ni->ni_net->net_lnd->lnd_eager_recv == NULL) {
3921                         msg->msg_rx_ready_delay = 1;
3922                 } else {
3923                         lnet_net_unlock(msg->msg_rx_cpt);
3924                         rc = lnet_ni_eager_recv(ni, msg);
3925                         lnet_net_lock(msg->msg_rx_cpt);
3926                 }
3927         }
3928
3929         if (rc == 0)
3930                 rc = lnet_post_routed_recv_locked(msg, 0);
3931         return rc;
3932 }
3933
3934 int
3935 lnet_parse_local(struct lnet_ni *ni, struct lnet_msg *msg)
3936 {
3937         int     rc;
3938
3939         switch (msg->msg_type) {
3940         case LNET_MSG_ACK:
3941                 rc = lnet_parse_ack(ni, msg);
3942                 break;
3943         case LNET_MSG_PUT:
3944                 rc = lnet_parse_put(ni, msg);
3945                 break;
3946         case LNET_MSG_GET:
3947                 rc = lnet_parse_get(ni, msg, msg->msg_rdma_get);
3948                 break;
3949         case LNET_MSG_REPLY:
3950                 rc = lnet_parse_reply(ni, msg);
3951                 break;
3952         default: /* prevent an unused label if !kernel */
3953                 LASSERT(0);
3954                 return -EPROTO;
3955         }
3956
3957         LASSERT(rc == 0 || rc == -ENOENT);
3958         return rc;
3959 }
3960
3961 char *
3962 lnet_msgtyp2str (int type)
3963 {
3964         switch (type) {
3965         case LNET_MSG_ACK:
3966                 return ("ACK");
3967         case LNET_MSG_PUT:
3968                 return ("PUT");
3969         case LNET_MSG_GET:
3970                 return ("GET");
3971         case LNET_MSG_REPLY:
3972                 return ("REPLY");
3973         case LNET_MSG_HELLO:
3974                 return ("HELLO");
3975         default:
3976                 return ("<UNKNOWN>");
3977         }
3978 }
3979
3980 void
3981 lnet_print_hdr(struct lnet_hdr *hdr)
3982 {
3983         struct lnet_process_id src = {
3984                 .nid = hdr->src_nid,
3985                 .pid = hdr->src_pid,
3986         };
3987         struct lnet_process_id dst = {
3988                 .nid = hdr->dest_nid,
3989                 .pid = hdr->dest_pid,
3990         };
3991         char *type_str = lnet_msgtyp2str(hdr->type);
3992
3993         CWARN("P3 Header at %p of type %s\n", hdr, type_str);
3994         CWARN("    From %s\n", libcfs_id2str(src));
3995         CWARN("    To   %s\n", libcfs_id2str(dst));
3996
3997         switch (hdr->type) {
3998         default:
3999                 break;
4000
4001         case LNET_MSG_PUT:
4002                 CWARN("    Ptl index %d, ack md %#llx.%#llx, "
4003                       "match bits %llu\n",
4004                       hdr->msg.put.ptl_index,
4005                       hdr->msg.put.ack_wmd.wh_interface_cookie,
4006                       hdr->msg.put.ack_wmd.wh_object_cookie,
4007                       hdr->msg.put.match_bits);
4008                 CWARN("    Length %d, offset %d, hdr data %#llx\n",
4009                       hdr->payload_length, hdr->msg.put.offset,
4010                       hdr->msg.put.hdr_data);
4011                 break;
4012
4013         case LNET_MSG_GET:
4014                 CWARN("    Ptl index %d, return md %#llx.%#llx, "
4015                       "match bits %llu\n", hdr->msg.get.ptl_index,
4016                       hdr->msg.get.return_wmd.wh_interface_cookie,
4017                       hdr->msg.get.return_wmd.wh_object_cookie,
4018                       hdr->msg.get.match_bits);
4019                 CWARN("    Length %d, src offset %d\n",
4020                       hdr->msg.get.sink_length,
4021                       hdr->msg.get.src_offset);
4022                 break;
4023
4024         case LNET_MSG_ACK:
4025                 CWARN("    dst md %#llx.%#llx, "
4026                       "manipulated length %d\n",
4027                       hdr->msg.ack.dst_wmd.wh_interface_cookie,
4028                       hdr->msg.ack.dst_wmd.wh_object_cookie,
4029                       hdr->msg.ack.mlength);
4030                 break;
4031
4032         case LNET_MSG_REPLY:
4033                 CWARN("    dst md %#llx.%#llx, "
4034                       "length %d\n",
4035                       hdr->msg.reply.dst_wmd.wh_interface_cookie,
4036                       hdr->msg.reply.dst_wmd.wh_object_cookie,
4037                       hdr->payload_length);
4038         }
4039
4040 }
4041
4042 int
4043 lnet_parse(struct lnet_ni *ni, struct lnet_hdr *hdr, lnet_nid_t from_nid,
4044            void *private, int rdma_req)
4045 {
4046         int             rc = 0;
4047         int             cpt;
4048         int             for_me;
4049         struct lnet_msg *msg;
4050         lnet_pid_t     dest_pid;
4051         lnet_nid_t     dest_nid;
4052         lnet_nid_t     src_nid;
4053         struct lnet_peer_ni *lpni;
4054         __u32          payload_length;
4055         __u32          type;
4056
4057         LASSERT (!in_interrupt ());
4058
4059         type = le32_to_cpu(hdr->type);
4060         src_nid = le64_to_cpu(hdr->src_nid);
4061         dest_nid = le64_to_cpu(hdr->dest_nid);
4062         dest_pid = le32_to_cpu(hdr->dest_pid);
4063         payload_length = le32_to_cpu(hdr->payload_length);
4064
4065         for_me = (ni->ni_nid == dest_nid);
4066         cpt = lnet_cpt_of_nid(from_nid, ni);
4067
4068         CDEBUG(D_NET, "TRACE: %s(%s) <- %s : %s - %s\n",
4069                 libcfs_nid2str(dest_nid),
4070                 libcfs_nid2str(ni->ni_nid),
4071                 libcfs_nid2str(src_nid),
4072                 lnet_msgtyp2str(type),
4073                 (for_me) ? "for me" : "routed");
4074
4075         switch (type) {
4076         case LNET_MSG_ACK:
4077         case LNET_MSG_GET:
4078                 if (payload_length > 0) {
4079                         CERROR("%s, src %s: bad %s payload %d (0 expected)\n",
4080                                libcfs_nid2str(from_nid),
4081                                libcfs_nid2str(src_nid),
4082                                lnet_msgtyp2str(type), payload_length);
4083                         return -EPROTO;
4084                 }
4085                 break;
4086
4087         case LNET_MSG_PUT:
4088         case LNET_MSG_REPLY:
4089                 if (payload_length >
4090                     (__u32)(for_me ? LNET_MAX_PAYLOAD : LNET_MTU)) {
4091                         CERROR("%s, src %s: bad %s payload %d "
4092                                "(%d max expected)\n",
4093                                libcfs_nid2str(from_nid),
4094                                libcfs_nid2str(src_nid),
4095                                lnet_msgtyp2str(type),
4096                                payload_length,
4097                                for_me ? LNET_MAX_PAYLOAD : LNET_MTU);
4098                         return -EPROTO;
4099                 }
4100                 break;
4101
4102         default:
4103                 CERROR("%s, src %s: Bad message type 0x%x\n",
4104                        libcfs_nid2str(from_nid),
4105                        libcfs_nid2str(src_nid), type);
4106                 return -EPROTO;
4107         }
4108
4109         if (the_lnet.ln_routing &&
4110             ni->ni_last_alive != ktime_get_real_seconds()) {
4111                 /* NB: so far here is the only place to set NI status to "up */
4112                 lnet_ni_lock(ni);
4113                 ni->ni_last_alive = ktime_get_real_seconds();
4114                 if (ni->ni_status != NULL &&
4115                     ni->ni_status->ns_status == LNET_NI_STATUS_DOWN)
4116                         ni->ni_status->ns_status = LNET_NI_STATUS_UP;
4117                 lnet_ni_unlock(ni);
4118         }
4119
4120         /* Regard a bad destination NID as a protocol error.  Senders should
4121          * know what they're doing; if they don't they're misconfigured, buggy
4122          * or malicious so we chop them off at the knees :) */
4123
4124         if (!for_me) {
4125                 if (LNET_NIDNET(dest_nid) == LNET_NIDNET(ni->ni_nid)) {
4126                         /* should have gone direct */
4127                         CERROR("%s, src %s: Bad dest nid %s "
4128                                "(should have been sent direct)\n",
4129                                 libcfs_nid2str(from_nid),
4130                                 libcfs_nid2str(src_nid),
4131                                 libcfs_nid2str(dest_nid));
4132                         return -EPROTO;
4133                 }
4134
4135                 if (lnet_islocalnid(dest_nid)) {
4136                         /* dest is another local NI; sender should have used
4137                          * this node's NID on its own network */
4138                         CERROR("%s, src %s: Bad dest nid %s "
4139                                "(it's my nid but on a different network)\n",
4140                                 libcfs_nid2str(from_nid),
4141                                 libcfs_nid2str(src_nid),
4142                                 libcfs_nid2str(dest_nid));
4143                         return -EPROTO;
4144                 }
4145
4146                 if (rdma_req && type == LNET_MSG_GET) {
4147                         CERROR("%s, src %s: Bad optimized GET for %s "
4148                                "(final destination must be me)\n",
4149                                 libcfs_nid2str(from_nid),
4150                                 libcfs_nid2str(src_nid),
4151                                 libcfs_nid2str(dest_nid));
4152                         return -EPROTO;
4153                 }
4154
4155                 if (!the_lnet.ln_routing) {
4156                         CERROR("%s, src %s: Dropping message for %s "
4157                                "(routing not enabled)\n",
4158                                 libcfs_nid2str(from_nid),
4159                                 libcfs_nid2str(src_nid),
4160                                 libcfs_nid2str(dest_nid));
4161                         goto drop;
4162                 }
4163         }
4164
4165         /* Message looks OK; we're not going to return an error, so we MUST
4166          * call back lnd_recv() come what may... */
4167
4168         if (!list_empty(&the_lnet.ln_test_peers) &&     /* normally we don't */
4169             fail_peer(src_nid, 0)) {                    /* shall we now? */
4170                 CERROR("%s, src %s: Dropping %s to simulate failure\n",
4171                        libcfs_nid2str(from_nid), libcfs_nid2str(src_nid),
4172                        lnet_msgtyp2str(type));
4173                 goto drop;
4174         }
4175
4176         if (!list_empty(&the_lnet.ln_drop_rules) &&
4177             lnet_drop_rule_match(hdr, NULL)) {
4178                 CDEBUG(D_NET, "%s, src %s, dst %s: Dropping %s to simulate"
4179                               "silent message loss\n",
4180                        libcfs_nid2str(from_nid), libcfs_nid2str(src_nid),
4181                        libcfs_nid2str(dest_nid), lnet_msgtyp2str(type));
4182                 goto drop;
4183         }
4184
4185
4186         msg = lnet_msg_alloc();
4187         if (msg == NULL) {
4188                 CERROR("%s, src %s: Dropping %s (out of memory)\n",
4189                        libcfs_nid2str(from_nid), libcfs_nid2str(src_nid),
4190                        lnet_msgtyp2str(type));
4191                 goto drop;
4192         }
4193
4194         /* msg zeroed in lnet_msg_alloc; i.e. flags all clear,
4195          * pointers NULL etc */
4196
4197         msg->msg_type = type;
4198         msg->msg_private = private;
4199         msg->msg_receiving = 1;
4200         msg->msg_rdma_get = rdma_req;
4201         msg->msg_len = msg->msg_wanted = payload_length;
4202         msg->msg_offset = 0;
4203         msg->msg_hdr = *hdr;
4204         /* for building message event */
4205         msg->msg_from = from_nid;
4206         if (!for_me) {
4207                 msg->msg_target.pid     = dest_pid;
4208                 msg->msg_target.nid     = dest_nid;
4209                 msg->msg_routing        = 1;
4210
4211         } else {
4212                 /* convert common msg->hdr fields to host byteorder */
4213                 msg->msg_hdr.type       = type;
4214                 msg->msg_hdr.src_nid    = src_nid;
4215                 msg->msg_hdr.src_pid    = le32_to_cpu(msg->msg_hdr.src_pid);
4216                 msg->msg_hdr.dest_nid   = dest_nid;
4217                 msg->msg_hdr.dest_pid   = dest_pid;
4218                 msg->msg_hdr.payload_length = payload_length;
4219         }
4220
4221         lnet_net_lock(cpt);
4222         lpni = lnet_nid2peerni_locked(from_nid, ni->ni_nid, cpt);
4223         if (IS_ERR(lpni)) {
4224                 lnet_net_unlock(cpt);
4225                 CERROR("%s, src %s: Dropping %s "
4226                        "(error %ld looking up sender)\n",
4227                        libcfs_nid2str(from_nid), libcfs_nid2str(src_nid),
4228                        lnet_msgtyp2str(type), PTR_ERR(lpni));
4229                 lnet_msg_free(msg);
4230                 if (rc == -ESHUTDOWN)
4231                         /* We are shutting down.  Don't do anything more */
4232                         return 0;
4233                 goto drop;
4234         }
4235         msg->msg_rxpeer = lpni;
4236         msg->msg_rxni = ni;
4237         lnet_ni_addref_locked(ni, cpt);
4238         /* Multi-Rail: Primary NID of source. */
4239         msg->msg_initiator = lnet_peer_primary_nid_locked(src_nid);
4240
4241         if (lnet_isrouter(msg->msg_rxpeer)) {
4242                 lnet_peer_set_alive(msg->msg_rxpeer);
4243                 if (avoid_asym_router_failure &&
4244                     LNET_NIDNET(src_nid) != LNET_NIDNET(from_nid)) {
4245                         /* received a remote message from router, update
4246                          * remote NI status on this router.
4247                          * NB: multi-hop routed message will be ignored.
4248                          */
4249                         lnet_router_ni_update_locked(msg->msg_rxpeer,
4250                                                      LNET_NIDNET(src_nid));
4251                 }
4252         }
4253
4254         lnet_msg_commit(msg, cpt);
4255
4256         /* message delay simulation */
4257         if (unlikely(!list_empty(&the_lnet.ln_delay_rules) &&
4258                      lnet_delay_rule_match_locked(hdr, msg))) {
4259                 lnet_net_unlock(cpt);
4260                 return 0;
4261         }
4262
4263         if (!for_me) {
4264                 rc = lnet_parse_forward_locked(ni, msg);
4265                 lnet_net_unlock(cpt);
4266
4267                 if (rc < 0)
4268                         goto free_drop;
4269
4270                 if (rc == LNET_CREDIT_OK) {
4271                         lnet_ni_recv(ni, msg->msg_private, msg, 0,
4272                                      0, payload_length, payload_length);
4273                 }
4274                 return 0;
4275         }
4276
4277         lnet_net_unlock(cpt);
4278
4279         rc = lnet_parse_local(ni, msg);
4280         if (rc != 0)
4281                 goto free_drop;
4282         return 0;
4283
4284  free_drop:
4285         LASSERT(msg->msg_md == NULL);
4286         lnet_finalize(msg, rc);
4287
4288  drop:
4289         lnet_drop_message(ni, cpt, private, payload_length, type);
4290         return 0;
4291 }
4292 EXPORT_SYMBOL(lnet_parse);
4293
4294 void
4295 lnet_drop_delayed_msg_list(struct list_head *head, char *reason)
4296 {
4297         while (!list_empty(head)) {
4298                 struct lnet_process_id id = {0};
4299                 struct lnet_msg *msg;
4300
4301                 msg = list_entry(head->next, struct lnet_msg, msg_list);
4302                 list_del(&msg->msg_list);
4303
4304                 id.nid = msg->msg_hdr.src_nid;
4305                 id.pid = msg->msg_hdr.src_pid;
4306
4307                 LASSERT(msg->msg_md == NULL);
4308                 LASSERT(msg->msg_rx_delayed);
4309                 LASSERT(msg->msg_rxpeer != NULL);
4310                 LASSERT(msg->msg_hdr.type == LNET_MSG_PUT);
4311
4312                 CWARN("Dropping delayed PUT from %s portal %d match %llu"
4313                       " offset %d length %d: %s\n",
4314                       libcfs_id2str(id),
4315                       msg->msg_hdr.msg.put.ptl_index,
4316                       msg->msg_hdr.msg.put.match_bits,
4317                       msg->msg_hdr.msg.put.offset,
4318                       msg->msg_hdr.payload_length, reason);
4319
4320                 /* NB I can't drop msg's ref on msg_rxpeer until after I've
4321                  * called lnet_drop_message(), so I just hang onto msg as well
4322                  * until that's done */
4323
4324                 lnet_drop_message(msg->msg_rxni, msg->msg_rx_cpt,
4325                                   msg->msg_private, msg->msg_len,
4326                                   msg->msg_type);
4327
4328                 msg->msg_no_resend = true;
4329                 /*
4330                  * NB: message will not generate event because w/o attached MD,
4331                  * but we still should give error code so lnet_msg_decommit()
4332                  * can skip counters operations and other checks.
4333                  */
4334                 lnet_finalize(msg, -ENOENT);
4335         }
4336 }
4337
4338 void
4339 lnet_recv_delayed_msg_list(struct list_head *head)
4340 {
4341         while (!list_empty(head)) {
4342                 struct lnet_msg *msg;
4343                 struct lnet_process_id id;
4344
4345                 msg = list_entry(head->next, struct lnet_msg, msg_list);
4346                 list_del(&msg->msg_list);
4347
4348                 /* md won't disappear under me, since each msg
4349                  * holds a ref on it */
4350
4351                 id.nid = msg->msg_hdr.src_nid;
4352                 id.pid = msg->msg_hdr.src_pid;
4353
4354                 LASSERT(msg->msg_rx_delayed);
4355                 LASSERT(msg->msg_md != NULL);
4356                 LASSERT(msg->msg_rxpeer != NULL);
4357                 LASSERT(msg->msg_rxni != NULL);
4358                 LASSERT(msg->msg_hdr.type == LNET_MSG_PUT);
4359
4360                 CDEBUG(D_NET, "Resuming delayed PUT from %s portal %d "
4361                        "match %llu offset %d length %d.\n",
4362                         libcfs_id2str(id), msg->msg_hdr.msg.put.ptl_index,
4363                         msg->msg_hdr.msg.put.match_bits,
4364                         msg->msg_hdr.msg.put.offset,
4365                         msg->msg_hdr.payload_length);
4366
4367                 lnet_recv_put(msg->msg_rxni, msg);
4368         }
4369 }
4370
4371 static void
4372 lnet_attach_rsp_tracker(struct lnet_rsp_tracker *rspt, int cpt,
4373                         struct lnet_libmd *md, struct lnet_handle_md mdh)
4374 {
4375         s64 timeout_ns;
4376
4377         /*
4378          * MD has a refcount taken by message so it's not going away.
4379          * The MD however can be looked up. We need to secure the access
4380          * to the md_rspt_ptr by taking the res_lock.
4381          * The rspt can be accessed without protection up to when it gets
4382          * added to the list.
4383          */
4384
4385         /* debug code */
4386         LASSERT(md->md_rspt_ptr == NULL);
4387
4388         /* we'll use that same event in case we never get a response  */
4389         rspt->rspt_mdh = mdh;
4390         rspt->rspt_cpt = cpt;
4391         timeout_ns = lnet_transaction_timeout * NSEC_PER_SEC;
4392         rspt->rspt_deadline = ktime_add_ns(ktime_get(), timeout_ns);
4393
4394         lnet_res_lock(cpt);
4395         /* store the rspt so we can access it when we get the REPLY */
4396         md->md_rspt_ptr = rspt;
4397         lnet_res_unlock(cpt);
4398
4399         /*
4400          * add to the list of tracked responses. It's added to tail of the
4401          * list in order to expire all the older entries first.
4402          */
4403         lnet_net_lock(cpt);
4404         list_add_tail(&rspt->rspt_on_list, the_lnet.ln_mt_rstq[cpt]);
4405         lnet_net_unlock(cpt);
4406 }
4407
4408 /**
4409  * Initiate an asynchronous PUT operation.
4410  *
4411  * There are several events associated with a PUT: completion of the send on
4412  * the initiator node (LNET_EVENT_SEND), and when the send completes
4413  * successfully, the receipt of an acknowledgment (LNET_EVENT_ACK) indicating
4414  * that the operation was accepted by the target. The event LNET_EVENT_PUT is
4415  * used at the target node to indicate the completion of incoming data
4416  * delivery.
4417  *
4418  * The local events will be logged in the EQ associated with the MD pointed to
4419  * by \a mdh handle. Using a MD without an associated EQ results in these
4420  * events being discarded. In this case, the caller must have another
4421  * mechanism (e.g., a higher level protocol) for determining when it is safe
4422  * to modify the memory region associated with the MD.
4423  *
4424  * Note that LNet does not guarantee the order of LNET_EVENT_SEND and
4425  * LNET_EVENT_ACK, though intuitively ACK should happen after SEND.
4426  *
4427  * \param self Indicates the NID of a local interface through which to send
4428  * the PUT request. Use LNET_NID_ANY to let LNet choose one by itself.
4429  * \param mdh A handle for the MD that describes the memory to be sent. The MD
4430  * must be "free floating" (See LNetMDBind()).
4431  * \param ack Controls whether an acknowledgment is requested.
4432  * Acknowledgments are only sent when they are requested by the initiating
4433  * process and the target MD enables them.
4434  * \param target A process identifier for the target process.
4435  * \param portal The index in the \a target's portal table.
4436  * \param match_bits The match bits to use for MD selection at the target
4437  * process.
4438  * \param offset The offset into the target MD (only used when the target
4439  * MD has the LNET_MD_MANAGE_REMOTE option set).
4440  * \param hdr_data 64 bits of user data that can be included in the message
4441  * header. This data is written to an event queue entry at the target if an
4442  * EQ is present on the matching MD.
4443  *
4444  * \retval  0      Success, and only in this case events will be generated
4445  * and logged to EQ (if it exists).
4446  * \retval -EIO    Simulated failure.
4447  * \retval -ENOMEM Memory allocation failure.
4448  * \retval -ENOENT Invalid MD object.
4449  *
4450  * \see struct lnet_event::hdr_data and lnet_event_kind_t.
4451  */
4452 int
4453 LNetPut(lnet_nid_t self, struct lnet_handle_md mdh, enum lnet_ack_req ack,
4454         struct lnet_process_id target, unsigned int portal,
4455         __u64 match_bits, unsigned int offset,
4456         __u64 hdr_data)
4457 {
4458         struct lnet_msg *msg;
4459         struct lnet_libmd *md;
4460         int cpt;
4461         int rc;
4462         struct lnet_rsp_tracker *rspt = NULL;
4463
4464         LASSERT(the_lnet.ln_refcount > 0);
4465
4466         if (!list_empty(&the_lnet.ln_test_peers) &&     /* normally we don't */
4467             fail_peer(target.nid, 1)) {                 /* shall we now? */
4468                 CERROR("Dropping PUT to %s: simulated failure\n",
4469                        libcfs_id2str(target));
4470                 return -EIO;
4471         }
4472
4473         msg = lnet_msg_alloc();
4474         if (msg == NULL) {
4475                 CERROR("Dropping PUT to %s: ENOMEM on struct lnet_msg\n",
4476                        libcfs_id2str(target));
4477                 return -ENOMEM;
4478         }
4479         msg->msg_vmflush = !!memory_pressure_get();
4480
4481         cpt = lnet_cpt_of_cookie(mdh.cookie);
4482
4483         if (ack == LNET_ACK_REQ) {
4484                 rspt = lnet_rspt_alloc(cpt);
4485                 if (!rspt) {
4486                         CERROR("Dropping PUT to %s: ENOMEM on response tracker\n",
4487                                 libcfs_id2str(target));
4488                         return -ENOMEM;
4489                 }
4490                 INIT_LIST_HEAD(&rspt->rspt_on_list);
4491         }
4492
4493         lnet_res_lock(cpt);
4494
4495         md = lnet_handle2md(&mdh);
4496         if (md == NULL || md->md_threshold == 0 || md->md_me != NULL) {
4497                 CERROR("Dropping PUT (%llu:%d:%s): MD (%d) invalid\n",
4498                        match_bits, portal, libcfs_id2str(target),
4499                        md == NULL ? -1 : md->md_threshold);
4500                 if (md != NULL && md->md_me != NULL)
4501                         CERROR("Source MD also attached to portal %d\n",
4502                                md->md_me->me_portal);
4503                 lnet_res_unlock(cpt);
4504
4505                 LIBCFS_FREE(rspt, sizeof(*rspt));
4506                 lnet_msg_free(msg);
4507                 return -ENOENT;
4508         }
4509
4510         CDEBUG(D_NET, "LNetPut -> %s\n", libcfs_id2str(target));
4511
4512         lnet_msg_attach_md(msg, md, 0, 0);
4513
4514         lnet_prep_send(msg, LNET_MSG_PUT, target, 0, md->md_length);
4515
4516         msg->msg_hdr.msg.put.match_bits = cpu_to_le64(match_bits);
4517         msg->msg_hdr.msg.put.ptl_index = cpu_to_le32(portal);
4518         msg->msg_hdr.msg.put.offset = cpu_to_le32(offset);
4519         msg->msg_hdr.msg.put.hdr_data = hdr_data;
4520
4521         /* NB handles only looked up by creator (no flips) */
4522         if (ack == LNET_ACK_REQ) {
4523                 msg->msg_hdr.msg.put.ack_wmd.wh_interface_cookie =
4524                         the_lnet.ln_interface_cookie;
4525                 msg->msg_hdr.msg.put.ack_wmd.wh_object_cookie =
4526                         md->md_lh.lh_cookie;
4527         } else {
4528                 msg->msg_hdr.msg.put.ack_wmd.wh_interface_cookie =
4529                         LNET_WIRE_HANDLE_COOKIE_NONE;
4530                 msg->msg_hdr.msg.put.ack_wmd.wh_object_cookie =
4531                         LNET_WIRE_HANDLE_COOKIE_NONE;
4532         }
4533
4534         lnet_res_unlock(cpt);
4535
4536         lnet_build_msg_event(msg, LNET_EVENT_SEND);
4537
4538         if (ack == LNET_ACK_REQ)
4539                 lnet_attach_rsp_tracker(rspt, cpt, md, mdh);
4540
4541         rc = lnet_send(self, msg, LNET_NID_ANY);
4542         if (rc != 0) {
4543                 CNETERR("Error sending PUT to %s: %d\n",
4544                         libcfs_id2str(target), rc);
4545                 msg->msg_no_resend = true;
4546                 lnet_detach_rsp_tracker(msg->msg_md, cpt);
4547                 lnet_finalize(msg, rc);
4548         }
4549
4550         /* completion will be signalled by an event */
4551         return 0;
4552 }
4553 EXPORT_SYMBOL(LNetPut);
4554
4555 /*
4556  * The LND can DMA direct to the GET md (i.e. no REPLY msg).  This
4557  * returns a msg for the LND to pass to lnet_finalize() when the sink
4558  * data has been received.
4559  *
4560  * CAVEAT EMPTOR: 'getmsg' is the original GET, which is freed when
4561  * lnet_finalize() is called on it, so the LND must call this first
4562  */
4563 struct lnet_msg *
4564 lnet_create_reply_msg(struct lnet_ni *ni, struct lnet_msg *getmsg)
4565 {
4566         struct lnet_msg *msg = lnet_msg_alloc();
4567         struct lnet_libmd *getmd = getmsg->msg_md;
4568         struct lnet_process_id peer_id = getmsg->msg_target;
4569         int cpt;
4570
4571         LASSERT(!getmsg->msg_target_is_router);
4572         LASSERT(!getmsg->msg_routing);
4573
4574         if (msg == NULL) {
4575                 CERROR("%s: Dropping REPLY from %s: can't allocate msg\n",
4576                        libcfs_nid2str(ni->ni_nid), libcfs_id2str(peer_id));
4577                 goto drop;
4578         }
4579
4580         cpt = lnet_cpt_of_cookie(getmd->md_lh.lh_cookie);
4581         lnet_res_lock(cpt);
4582
4583         LASSERT(getmd->md_refcount > 0);
4584
4585         if (getmd->md_threshold == 0) {
4586                 CERROR("%s: Dropping REPLY from %s for inactive MD %p\n",
4587                         libcfs_nid2str(ni->ni_nid), libcfs_id2str(peer_id),
4588                         getmd);
4589                 lnet_res_unlock(cpt);
4590                 goto drop;
4591         }
4592
4593         LASSERT(getmd->md_offset == 0);
4594
4595         CDEBUG(D_NET, "%s: Reply from %s md %p\n",
4596                libcfs_nid2str(ni->ni_nid), libcfs_id2str(peer_id), getmd);
4597
4598         /* setup information for lnet_build_msg_event */
4599         msg->msg_initiator = getmsg->msg_txpeer->lpni_peer_net->lpn_peer->lp_primary_nid;
4600         msg->msg_from = peer_id.nid;
4601         msg->msg_type = LNET_MSG_GET; /* flag this msg as an "optimized" GET */
4602         msg->msg_hdr.src_nid = peer_id.nid;
4603         msg->msg_hdr.payload_length = getmd->md_length;
4604         msg->msg_receiving = 1; /* required by lnet_msg_attach_md */
4605
4606         lnet_msg_attach_md(msg, getmd, getmd->md_offset, getmd->md_length);
4607         lnet_res_unlock(cpt);
4608
4609         cpt = lnet_cpt_of_nid(peer_id.nid, ni);
4610
4611         lnet_net_lock(cpt);
4612         lnet_msg_commit(msg, cpt);
4613         lnet_net_unlock(cpt);
4614
4615         lnet_build_msg_event(msg, LNET_EVENT_REPLY);
4616
4617         return msg;
4618
4619  drop:
4620         cpt = lnet_cpt_of_nid(peer_id.nid, ni);
4621
4622         lnet_net_lock(cpt);
4623         lnet_incr_stats(&ni->ni_stats, LNET_MSG_GET, LNET_STATS_TYPE_DROP);
4624         the_lnet.ln_counters[cpt]->lct_common.lcc_drop_count++;
4625         the_lnet.ln_counters[cpt]->lct_common.lcc_drop_length +=
4626                 getmd->md_length;
4627         lnet_net_unlock(cpt);
4628
4629         if (msg != NULL)
4630                 lnet_msg_free(msg);
4631
4632         return NULL;
4633 }
4634 EXPORT_SYMBOL(lnet_create_reply_msg);
4635
4636 void
4637 lnet_set_reply_msg_len(struct lnet_ni *ni, struct lnet_msg *reply,
4638                        unsigned int len)
4639 {
4640         /* Set the REPLY length, now the RDMA that elides the REPLY message has
4641          * completed and I know it. */
4642         LASSERT(reply != NULL);
4643         LASSERT(reply->msg_type == LNET_MSG_GET);
4644         LASSERT(reply->msg_ev.type == LNET_EVENT_REPLY);
4645
4646         /* NB I trusted my peer to RDMA.  If she tells me she's written beyond
4647          * the end of my buffer, I might as well be dead. */
4648         LASSERT(len <= reply->msg_ev.mlength);
4649
4650         reply->msg_ev.mlength = len;
4651 }
4652 EXPORT_SYMBOL(lnet_set_reply_msg_len);
4653
4654 /**
4655  * Initiate an asynchronous GET operation.
4656  *
4657  * On the initiator node, an LNET_EVENT_SEND is logged when the GET request
4658  * is sent, and an LNET_EVENT_REPLY is logged when the data returned from
4659  * the target node in the REPLY has been written to local MD.
4660  *
4661  * On the target node, an LNET_EVENT_GET is logged when the GET request
4662  * arrives and is accepted into a MD.
4663  *
4664  * \param self,target,portal,match_bits,offset See the discussion in LNetPut().
4665  * \param mdh A handle for the MD that describes the memory into which the
4666  * requested data will be received. The MD must be "free floating" (See LNetMDBind()).
4667  *
4668  * \retval  0      Success, and only in this case events will be generated
4669  * and logged to EQ (if it exists) of the MD.
4670  * \retval -EIO    Simulated failure.
4671  * \retval -ENOMEM Memory allocation failure.
4672  * \retval -ENOENT Invalid MD object.
4673  */
4674 int
4675 LNetGet(lnet_nid_t self, struct lnet_handle_md mdh,
4676         struct lnet_process_id target, unsigned int portal,
4677         __u64 match_bits, unsigned int offset, bool recovery)
4678 {
4679         struct lnet_msg *msg;
4680         struct lnet_libmd *md;
4681         struct lnet_rsp_tracker *rspt;
4682         int cpt;
4683         int rc;
4684
4685         LASSERT(the_lnet.ln_refcount > 0);
4686
4687         if (!list_empty(&the_lnet.ln_test_peers) &&     /* normally we don't */
4688             fail_peer(target.nid, 1))                   /* shall we now? */
4689         {
4690                 CERROR("Dropping GET to %s: simulated failure\n",
4691                        libcfs_id2str(target));
4692                 return -EIO;
4693         }
4694
4695         msg = lnet_msg_alloc();
4696         if (!msg) {
4697                 CERROR("Dropping GET to %s: ENOMEM on struct lnet_msg\n",
4698                        libcfs_id2str(target));
4699                 return -ENOMEM;
4700         }
4701
4702         cpt = lnet_cpt_of_cookie(mdh.cookie);
4703
4704         rspt = lnet_rspt_alloc(cpt);
4705         if (!rspt) {
4706                 CERROR("Dropping GET to %s: ENOMEM on response tracker\n",
4707                        libcfs_id2str(target));
4708                 return -ENOMEM;
4709         }
4710         INIT_LIST_HEAD(&rspt->rspt_on_list);
4711
4712         msg->msg_recovery = recovery;
4713
4714         lnet_res_lock(cpt);
4715
4716         md = lnet_handle2md(&mdh);
4717         if (md == NULL || md->md_threshold == 0 || md->md_me != NULL) {
4718                 CERROR("Dropping GET (%llu:%d:%s): MD (%d) invalid\n",
4719                        match_bits, portal, libcfs_id2str(target),
4720                        md == NULL ? -1 : md->md_threshold);
4721                 if (md != NULL && md->md_me != NULL)
4722                         CERROR("REPLY MD also attached to portal %d\n",
4723                                md->md_me->me_portal);
4724
4725                 lnet_res_unlock(cpt);
4726
4727                 lnet_msg_free(msg);
4728                 LIBCFS_FREE(rspt, sizeof(*rspt));
4729                 return -ENOENT;
4730         }
4731
4732         CDEBUG(D_NET, "LNetGet -> %s\n", libcfs_id2str(target));
4733
4734         lnet_msg_attach_md(msg, md, 0, 0);
4735
4736         lnet_prep_send(msg, LNET_MSG_GET, target, 0, 0);
4737
4738         msg->msg_hdr.msg.get.match_bits = cpu_to_le64(match_bits);
4739         msg->msg_hdr.msg.get.ptl_index = cpu_to_le32(portal);
4740         msg->msg_hdr.msg.get.src_offset = cpu_to_le32(offset);
4741         msg->msg_hdr.msg.get.sink_length = cpu_to_le32(md->md_length);
4742
4743         /* NB handles only looked up by creator (no flips) */
4744         msg->msg_hdr.msg.get.return_wmd.wh_interface_cookie =
4745                 the_lnet.ln_interface_cookie;
4746         msg->msg_hdr.msg.get.return_wmd.wh_object_cookie =
4747                 md->md_lh.lh_cookie;
4748
4749         lnet_res_unlock(cpt);
4750
4751         lnet_build_msg_event(msg, LNET_EVENT_SEND);
4752
4753         lnet_attach_rsp_tracker(rspt, cpt, md, mdh);
4754
4755         rc = lnet_send(self, msg, LNET_NID_ANY);
4756         if (rc < 0) {
4757                 CNETERR("Error sending GET to %s: %d\n",
4758                         libcfs_id2str(target), rc);
4759                 msg->msg_no_resend = true;
4760                 lnet_detach_rsp_tracker(msg->msg_md, cpt);
4761                 lnet_finalize(msg, rc);
4762         }
4763
4764         /* completion will be signalled by an event */
4765         return 0;
4766 }
4767 EXPORT_SYMBOL(LNetGet);
4768
4769 /**
4770  * Calculate distance to node at \a dstnid.
4771  *
4772  * \param dstnid Target NID.
4773  * \param srcnidp If not NULL, NID of the local interface to reach \a dstnid
4774  * is saved here.
4775  * \param orderp If not NULL, order of the route to reach \a dstnid is saved
4776  * here.
4777  *
4778  * \retval 0 If \a dstnid belongs to a local interface, and reserved option
4779  * local_nid_dist_zero is set, which is the default.
4780  * \retval positives Distance to target NID, i.e. number of hops plus one.
4781  * \retval -EHOSTUNREACH If \a dstnid is not reachable.
4782  */
4783 int
4784 LNetDist(lnet_nid_t dstnid, lnet_nid_t *srcnidp, __u32 *orderp)
4785 {
4786         struct list_head        *e;
4787         struct lnet_ni *ni = NULL;
4788         struct lnet_remotenet *rnet;
4789         __u32                   dstnet = LNET_NIDNET(dstnid);
4790         int                     hops;
4791         int                     cpt;
4792         __u32                   order = 2;
4793         struct list_head        *rn_list;
4794
4795         /* if !local_nid_dist_zero, I don't return a distance of 0 ever
4796          * (when lustre sees a distance of 0, it substitutes 0@lo), so I
4797          * keep order 0 free for 0@lo and order 1 free for a local NID
4798          * match */
4799
4800         LASSERT(the_lnet.ln_refcount > 0);
4801
4802         cpt = lnet_net_lock_current();
4803
4804         while ((ni = lnet_get_next_ni_locked(NULL, ni))) {
4805                 if (ni->ni_nid == dstnid) {
4806                         if (srcnidp != NULL)
4807                                 *srcnidp = dstnid;
4808                         if (orderp != NULL) {
4809                                 if (LNET_NETTYP(LNET_NIDNET(dstnid)) == LOLND)
4810                                         *orderp = 0;
4811                                 else
4812                                         *orderp = 1;
4813                         }
4814                         lnet_net_unlock(cpt);
4815
4816                         return local_nid_dist_zero ? 0 : 1;
4817                 }
4818
4819                 if (LNET_NIDNET(ni->ni_nid) == dstnet) {
4820                         /* Check if ni was originally created in
4821                          * current net namespace.
4822                          * If not, assign order above 0xffff0000,
4823                          * to make this ni not a priority. */
4824                         if (!net_eq(ni->ni_net_ns, current->nsproxy->net_ns))
4825                                 order += 0xffff0000;
4826
4827                         if (srcnidp != NULL)
4828                                 *srcnidp = ni->ni_nid;
4829                         if (orderp != NULL)
4830                                 *orderp = order;
4831                         lnet_net_unlock(cpt);
4832                         return 1;
4833                 }
4834
4835                 order++;
4836         }
4837
4838         rn_list = lnet_net2rnethash(dstnet);
4839         list_for_each(e, rn_list) {
4840                 rnet = list_entry(e, struct lnet_remotenet, lrn_list);
4841
4842                 if (rnet->lrn_net == dstnet) {
4843                         struct lnet_route *route;
4844                         struct lnet_route *shortest = NULL;
4845                         __u32 shortest_hops = LNET_UNDEFINED_HOPS;
4846                         __u32 route_hops;
4847
4848                         LASSERT(!list_empty(&rnet->lrn_routes));
4849
4850                         list_for_each_entry(route, &rnet->lrn_routes,
4851                                             lr_list) {
4852                                 route_hops = route->lr_hops;
4853                                 if (route_hops == LNET_UNDEFINED_HOPS)
4854                                         route_hops = 1;
4855                                 if (shortest == NULL ||
4856                                     route_hops < shortest_hops) {
4857                                         shortest = route;
4858                                         shortest_hops = route_hops;
4859                                 }
4860                         }
4861
4862                         LASSERT(shortest != NULL);
4863                         hops = shortest_hops;
4864                         if (srcnidp != NULL) {
4865                                 ni = lnet_get_next_ni_locked(
4866                                         shortest->lr_gateway->lpni_net,
4867                                         NULL);
4868                                 *srcnidp = ni->ni_nid;
4869                         }
4870                         if (orderp != NULL)
4871                                 *orderp = order;
4872                         lnet_net_unlock(cpt);
4873                         return hops + 1;
4874                 }
4875                 order++;
4876         }
4877
4878         lnet_net_unlock(cpt);
4879         return -EHOSTUNREACH;
4880 }
4881 EXPORT_SYMBOL(LNetDist);