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