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