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