Whamcloud - gitweb
73b463675ade711b1abf4a8529ac6a7d55ce9bc4
[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 bool
67 lnet_msg_is_response(struct lnet_msg *msg)
68 {
69         return msg->msg_type == LNET_MSG_ACK || msg->msg_type == LNET_MSG_REPLY;
70 }
71
72 static inline bool
73 lnet_response_tracking_enabled(__u32 msg_type, unsigned int md_options)
74 {
75         if (md_options & LNET_MD_NO_TRACK_RESPONSE)
76                 /* Explicitly disabled in MD options */
77                 return false;
78
79         if (md_options & LNET_MD_TRACK_RESPONSE)
80                 /* Explicity enabled in MD options */
81                 return true;
82
83         if (lnet_response_tracking == 3)
84                 /* Enabled for all message types */
85                 return true;
86
87         if (msg_type == LNET_MSG_PUT)
88                 return lnet_response_tracking == 2;
89
90         if (msg_type == LNET_MSG_GET)
91                 return lnet_response_tracking == 1;
92
93         return false;
94 }
95
96 static inline struct lnet_comm_count *
97 get_stats_counts(struct lnet_element_stats *stats,
98                  enum lnet_stats_type stats_type)
99 {
100         switch (stats_type) {
101         case LNET_STATS_TYPE_SEND:
102                 return &stats->el_send_stats;
103         case LNET_STATS_TYPE_RECV:
104                 return &stats->el_recv_stats;
105         case LNET_STATS_TYPE_DROP:
106                 return &stats->el_drop_stats;
107         default:
108                 CERROR("Unknown stats type\n");
109         }
110
111         return NULL;
112 }
113
114 void lnet_incr_stats(struct lnet_element_stats *stats,
115                      enum lnet_msg_type msg_type,
116                      enum lnet_stats_type stats_type)
117 {
118         struct lnet_comm_count *counts = get_stats_counts(stats, stats_type);
119         if (!counts)
120                 return;
121
122         switch (msg_type) {
123         case LNET_MSG_ACK:
124                 atomic_inc(&counts->co_ack_count);
125                 break;
126         case LNET_MSG_PUT:
127                 atomic_inc(&counts->co_put_count);
128                 break;
129         case LNET_MSG_GET:
130                 atomic_inc(&counts->co_get_count);
131                 break;
132         case LNET_MSG_REPLY:
133                 atomic_inc(&counts->co_reply_count);
134                 break;
135         case LNET_MSG_HELLO:
136                 atomic_inc(&counts->co_hello_count);
137                 break;
138         default:
139                 CERROR("There is a BUG in the code. Unknown message type\n");
140                 break;
141         }
142 }
143
144 __u32 lnet_sum_stats(struct lnet_element_stats *stats,
145                      enum lnet_stats_type stats_type)
146 {
147         struct lnet_comm_count *counts = get_stats_counts(stats, stats_type);
148         if (!counts)
149                 return 0;
150
151         return (atomic_read(&counts->co_ack_count) +
152                 atomic_read(&counts->co_put_count) +
153                 atomic_read(&counts->co_get_count) +
154                 atomic_read(&counts->co_reply_count) +
155                 atomic_read(&counts->co_hello_count));
156 }
157
158 static inline void assign_stats(struct lnet_ioctl_comm_count *msg_stats,
159                                 struct lnet_comm_count *counts)
160 {
161         msg_stats->ico_get_count = atomic_read(&counts->co_get_count);
162         msg_stats->ico_put_count = atomic_read(&counts->co_put_count);
163         msg_stats->ico_reply_count = atomic_read(&counts->co_reply_count);
164         msg_stats->ico_ack_count = atomic_read(&counts->co_ack_count);
165         msg_stats->ico_hello_count = atomic_read(&counts->co_hello_count);
166 }
167
168 void lnet_usr_translate_stats(struct lnet_ioctl_element_msg_stats *msg_stats,
169                               struct lnet_element_stats *stats)
170 {
171         struct lnet_comm_count *counts;
172
173         LASSERT(msg_stats);
174         LASSERT(stats);
175
176         counts = get_stats_counts(stats, LNET_STATS_TYPE_SEND);
177         if (!counts)
178                 return;
179         assign_stats(&msg_stats->im_send_stats, counts);
180
181         counts = get_stats_counts(stats, LNET_STATS_TYPE_RECV);
182         if (!counts)
183                 return;
184         assign_stats(&msg_stats->im_recv_stats, counts);
185
186         counts = get_stats_counts(stats, LNET_STATS_TYPE_DROP);
187         if (!counts)
188                 return;
189         assign_stats(&msg_stats->im_drop_stats, counts);
190 }
191
192 int
193 lnet_fail_nid(lnet_nid_t nid, unsigned int threshold)
194 {
195         struct lnet_test_peer *tp;
196         struct list_head *el;
197         struct list_head *next;
198         LIST_HEAD(cull);
199
200         /* NB: use lnet_net_lock(0) to serialize operations on test peers */
201         if (threshold != 0) {
202                 /* Adding a new entry */
203                 LIBCFS_ALLOC(tp, sizeof(*tp));
204                 if (tp == NULL)
205                         return -ENOMEM;
206
207                 tp->tp_nid = nid;
208                 tp->tp_threshold = threshold;
209
210                 lnet_net_lock(0);
211                 list_add_tail(&tp->tp_list, &the_lnet.ln_test_peers);
212                 lnet_net_unlock(0);
213                 return 0;
214         }
215
216         lnet_net_lock(0);
217
218         list_for_each_safe(el, next, &the_lnet.ln_test_peers) {
219                 tp = list_entry(el, struct lnet_test_peer, tp_list);
220
221                 if (tp->tp_threshold == 0 ||    /* needs culling anyway */
222                     nid == LNET_NID_ANY ||      /* removing all entries */
223                     tp->tp_nid == nid) {        /* matched this one */
224                         list_move(&tp->tp_list, &cull);
225                 }
226         }
227
228         lnet_net_unlock(0);
229
230         while (!list_empty(&cull)) {
231                 tp = list_entry(cull.next, struct lnet_test_peer, tp_list);
232
233                 list_del(&tp->tp_list);
234                 LIBCFS_FREE(tp, sizeof(*tp));
235         }
236         return 0;
237 }
238
239 static int
240 fail_peer (lnet_nid_t nid, int outgoing)
241 {
242         struct lnet_test_peer *tp;
243         struct list_head *el;
244         struct list_head *next;
245         LIST_HEAD(cull);
246         int fail = 0;
247
248         /* NB: use lnet_net_lock(0) to serialize operations on test peers */
249         lnet_net_lock(0);
250
251         list_for_each_safe(el, next, &the_lnet.ln_test_peers) {
252                 tp = list_entry(el, struct lnet_test_peer, tp_list);
253
254                 if (tp->tp_threshold == 0) {
255                         /* zombie entry */
256                         if (outgoing) {
257                                 /* only cull zombies on outgoing tests,
258                                  * since we may be at interrupt priority on
259                                  * incoming messages. */
260                                 list_move(&tp->tp_list, &cull);
261                         }
262                         continue;
263                 }
264
265                 if (tp->tp_nid == LNET_NID_ANY ||       /* fail every peer */
266                     nid == tp->tp_nid) {                /* fail this peer */
267                         fail = 1;
268
269                         if (tp->tp_threshold != LNET_MD_THRESH_INF) {
270                                 tp->tp_threshold--;
271                                 if (outgoing &&
272                                     tp->tp_threshold == 0) {
273                                         /* see above */
274                                         list_move(&tp->tp_list, &cull);
275                                 }
276                         }
277                         break;
278                 }
279         }
280
281         lnet_net_unlock(0);
282
283         while (!list_empty(&cull)) {
284                 tp = list_entry(cull.next, struct lnet_test_peer, tp_list);
285                 list_del(&tp->tp_list);
286
287                 LIBCFS_FREE(tp, sizeof(*tp));
288         }
289
290         return fail;
291 }
292
293 unsigned int
294 lnet_iov_nob(unsigned int niov, struct kvec *iov)
295 {
296         unsigned int nob = 0;
297
298         LASSERT(niov == 0 || iov != NULL);
299         while (niov-- > 0)
300                 nob += (iov++)->iov_len;
301
302         return (nob);
303 }
304 EXPORT_SYMBOL(lnet_iov_nob);
305
306 void
307 lnet_copy_iov2iov(unsigned int ndiov, struct kvec *diov, unsigned int doffset,
308                   unsigned int nsiov, struct kvec *siov, unsigned int soffset,
309                   unsigned int nob)
310 {
311         /* NB diov, siov are READ-ONLY */
312         unsigned int this_nob;
313
314         if (nob == 0)
315                 return;
316
317         /* skip complete frags before 'doffset' */
318         LASSERT(ndiov > 0);
319         while (doffset >= diov->iov_len) {
320                 doffset -= diov->iov_len;
321                 diov++;
322                 ndiov--;
323                 LASSERT(ndiov > 0);
324         }
325
326         /* skip complete frags before 'soffset' */
327         LASSERT(nsiov > 0);
328         while (soffset >= siov->iov_len) {
329                 soffset -= siov->iov_len;
330                 siov++;
331                 nsiov--;
332                 LASSERT(nsiov > 0);
333         }
334
335         do {
336                 LASSERT(ndiov > 0);
337                 LASSERT(nsiov > 0);
338                 this_nob = min3((unsigned int)diov->iov_len - doffset,
339                                 (unsigned int)siov->iov_len - soffset,
340                                 nob);
341
342                 memcpy((char *)diov->iov_base + doffset,
343                        (char *)siov->iov_base + soffset, this_nob);
344                 nob -= this_nob;
345
346                 if (diov->iov_len > doffset + this_nob) {
347                         doffset += this_nob;
348                 } else {
349                         diov++;
350                         ndiov--;
351                         doffset = 0;
352                 }
353
354                 if (siov->iov_len > soffset + this_nob) {
355                         soffset += this_nob;
356                 } else {
357                         siov++;
358                         nsiov--;
359                         soffset = 0;
360                 }
361         } while (nob > 0);
362 }
363 EXPORT_SYMBOL(lnet_copy_iov2iov);
364
365 unsigned int
366 lnet_kiov_nob(unsigned int niov, struct bio_vec *kiov)
367 {
368         unsigned int  nob = 0;
369
370         LASSERT(niov == 0 || kiov != NULL);
371         while (niov-- > 0)
372                 nob += (kiov++)->bv_len;
373
374         return (nob);
375 }
376 EXPORT_SYMBOL(lnet_kiov_nob);
377
378 void
379 lnet_copy_kiov2kiov(unsigned int ndiov, struct bio_vec *diov,
380                     unsigned int doffset,
381                     unsigned int nsiov, struct bio_vec *siov,
382                     unsigned int soffset,
383                     unsigned int nob)
384 {
385         /* NB diov, siov are READ-ONLY */
386         unsigned int    this_nob;
387         char           *daddr = NULL;
388         char           *saddr = NULL;
389
390         if (nob == 0)
391                 return;
392
393         LASSERT (!in_interrupt ());
394
395         LASSERT (ndiov > 0);
396         while (doffset >= diov->bv_len) {
397                 doffset -= diov->bv_len;
398                 diov++;
399                 ndiov--;
400                 LASSERT(ndiov > 0);
401         }
402
403         LASSERT(nsiov > 0);
404         while (soffset >= siov->bv_len) {
405                 soffset -= siov->bv_len;
406                 siov++;
407                 nsiov--;
408                 LASSERT(nsiov > 0);
409         }
410
411         do {
412                 LASSERT(ndiov > 0);
413                 LASSERT(nsiov > 0);
414                 this_nob = min3(diov->bv_len - doffset,
415                                 siov->bv_len - soffset,
416                                 nob);
417
418                 if (daddr == NULL)
419                         daddr = ((char *)kmap(diov->bv_page)) +
420                                 diov->bv_offset + doffset;
421                 if (saddr == NULL)
422                         saddr = ((char *)kmap(siov->bv_page)) +
423                                 siov->bv_offset + soffset;
424
425                 /* Vanishing risk of kmap deadlock when mapping 2 pages.
426                  * However in practice at least one of the kiovs will be mapped
427                  * kernel pages and the map/unmap will be NOOPs */
428
429                 memcpy (daddr, saddr, this_nob);
430                 nob -= this_nob;
431
432                 if (diov->bv_len > doffset + this_nob) {
433                         daddr += this_nob;
434                         doffset += this_nob;
435                 } else {
436                         kunmap(diov->bv_page);
437                         daddr = NULL;
438                         diov++;
439                         ndiov--;
440                         doffset = 0;
441                 }
442
443                 if (siov->bv_len > soffset + this_nob) {
444                         saddr += this_nob;
445                         soffset += this_nob;
446                 } else {
447                         kunmap(siov->bv_page);
448                         saddr = NULL;
449                         siov++;
450                         nsiov--;
451                         soffset = 0;
452                 }
453         } while (nob > 0);
454
455         if (daddr != NULL)
456                 kunmap(diov->bv_page);
457         if (saddr != NULL)
458                 kunmap(siov->bv_page);
459 }
460 EXPORT_SYMBOL(lnet_copy_kiov2kiov);
461
462 void
463 lnet_copy_kiov2iov (unsigned int niov, struct kvec *iov, unsigned int iovoffset,
464                     unsigned int nkiov, struct bio_vec *kiov,
465                     unsigned int kiovoffset,
466                     unsigned int nob)
467 {
468         /* NB iov, kiov are READ-ONLY */
469         unsigned int    this_nob;
470         char           *addr = NULL;
471
472         if (nob == 0)
473                 return;
474
475         LASSERT (!in_interrupt ());
476
477         LASSERT (niov > 0);
478         while (iovoffset >= iov->iov_len) {
479                 iovoffset -= iov->iov_len;
480                 iov++;
481                 niov--;
482                 LASSERT(niov > 0);
483         }
484
485         LASSERT(nkiov > 0);
486         while (kiovoffset >= kiov->bv_len) {
487                 kiovoffset -= kiov->bv_len;
488                 kiov++;
489                 nkiov--;
490                 LASSERT(nkiov > 0);
491         }
492
493         do {
494                 LASSERT(niov > 0);
495                 LASSERT(nkiov > 0);
496                 this_nob = min3((unsigned int)iov->iov_len - iovoffset,
497                                 (unsigned int)kiov->bv_len - kiovoffset,
498                                 nob);
499
500                 if (addr == NULL)
501                         addr = ((char *)kmap(kiov->bv_page)) +
502                                 kiov->bv_offset + kiovoffset;
503
504                 memcpy((char *)iov->iov_base + iovoffset, addr, this_nob);
505                 nob -= this_nob;
506
507                 if (iov->iov_len > iovoffset + this_nob) {
508                         iovoffset += this_nob;
509                 } else {
510                         iov++;
511                         niov--;
512                         iovoffset = 0;
513                 }
514
515                 if (kiov->bv_len > kiovoffset + this_nob) {
516                         addr += this_nob;
517                         kiovoffset += this_nob;
518                 } else {
519                         kunmap(kiov->bv_page);
520                         addr = NULL;
521                         kiov++;
522                         nkiov--;
523                         kiovoffset = 0;
524                 }
525
526         } while (nob > 0);
527
528         if (addr != NULL)
529                 kunmap(kiov->bv_page);
530 }
531 EXPORT_SYMBOL(lnet_copy_kiov2iov);
532
533 void
534 lnet_copy_iov2kiov(unsigned int nkiov, struct bio_vec *kiov,
535                    unsigned int kiovoffset,
536                    unsigned int niov, struct kvec *iov, unsigned int iovoffset,
537                    unsigned int nob)
538 {
539         /* NB kiov, iov are READ-ONLY */
540         unsigned int    this_nob;
541         char           *addr = NULL;
542
543         if (nob == 0)
544                 return;
545
546         LASSERT (!in_interrupt ());
547
548         LASSERT (nkiov > 0);
549         while (kiovoffset >= kiov->bv_len) {
550                 kiovoffset -= kiov->bv_len;
551                 kiov++;
552                 nkiov--;
553                 LASSERT(nkiov > 0);
554         }
555
556         LASSERT(niov > 0);
557         while (iovoffset >= iov->iov_len) {
558                 iovoffset -= iov->iov_len;
559                 iov++;
560                 niov--;
561                 LASSERT(niov > 0);
562         }
563
564         do {
565                 LASSERT(nkiov > 0);
566                 LASSERT(niov > 0);
567                 this_nob = min3((unsigned int)kiov->bv_len - kiovoffset,
568                                 (unsigned int)iov->iov_len - iovoffset,
569                                 nob);
570
571                 if (addr == NULL)
572                         addr = ((char *)kmap(kiov->bv_page)) +
573                                 kiov->bv_offset + kiovoffset;
574
575                 memcpy (addr, (char *)iov->iov_base + iovoffset, this_nob);
576                 nob -= this_nob;
577
578                 if (kiov->bv_len > kiovoffset + this_nob) {
579                         addr += this_nob;
580                         kiovoffset += this_nob;
581                 } else {
582                         kunmap(kiov->bv_page);
583                         addr = NULL;
584                         kiov++;
585                         nkiov--;
586                         kiovoffset = 0;
587                 }
588
589                 if (iov->iov_len > iovoffset + this_nob) {
590                         iovoffset += this_nob;
591                 } else {
592                         iov++;
593                         niov--;
594                         iovoffset = 0;
595                 }
596         } while (nob > 0);
597
598         if (addr != NULL)
599                 kunmap(kiov->bv_page);
600 }
601 EXPORT_SYMBOL(lnet_copy_iov2kiov);
602
603 int
604 lnet_extract_kiov(int dst_niov, struct bio_vec *dst,
605                   int src_niov, struct bio_vec *src,
606                   unsigned int offset, unsigned int len)
607 {
608         /* Initialise 'dst' to the subset of 'src' starting at 'offset',
609          * for exactly 'len' bytes, and return the number of entries.
610          * NB not destructive to 'src' */
611         unsigned int    frag_len;
612         unsigned int    niov;
613
614         if (len == 0)                           /* no data => */
615                 return (0);                     /* no frags */
616
617         LASSERT(src_niov > 0);
618         while (offset >= src->bv_len) {      /* skip initial frags */
619                 offset -= src->bv_len;
620                 src_niov--;
621                 src++;
622                 LASSERT(src_niov > 0);
623         }
624
625         niov = 1;
626         for (;;) {
627                 LASSERT(src_niov > 0);
628                 LASSERT((int)niov <= dst_niov);
629
630                 frag_len = src->bv_len - offset;
631                 dst->bv_page = src->bv_page;
632                 dst->bv_offset = src->bv_offset + offset;
633
634                 if (len <= frag_len) {
635                         dst->bv_len = len;
636                         LASSERT(dst->bv_offset + dst->bv_len <= PAGE_SIZE);
637                         return niov;
638                 }
639
640                 dst->bv_len = frag_len;
641                 LASSERT(dst->bv_offset + dst->bv_len <= PAGE_SIZE);
642
643                 len -= frag_len;
644                 dst++;
645                 src++;
646                 niov++;
647                 src_niov--;
648                 offset = 0;
649         }
650 }
651 EXPORT_SYMBOL(lnet_extract_kiov);
652
653 void
654 lnet_ni_recv(struct lnet_ni *ni, void *private, struct lnet_msg *msg,
655              int delayed, unsigned int offset, unsigned int mlen,
656              unsigned int rlen)
657 {
658         unsigned int niov = 0;
659         struct kvec *iov = NULL;
660         struct bio_vec  *kiov = NULL;
661         int rc;
662
663         LASSERT (!in_interrupt ());
664         LASSERT (mlen == 0 || msg != NULL);
665
666         if (msg != NULL) {
667                 LASSERT(msg->msg_receiving);
668                 LASSERT(!msg->msg_sending);
669                 LASSERT(rlen == msg->msg_len);
670                 LASSERT(mlen <= msg->msg_len);
671                 LASSERT(msg->msg_offset == offset);
672                 LASSERT(msg->msg_wanted == mlen);
673
674                 msg->msg_receiving = 0;
675
676                 if (mlen != 0) {
677                         niov = msg->msg_niov;
678                         kiov = msg->msg_kiov;
679
680                         LASSERT (niov > 0);
681                         LASSERT ((iov == NULL) != (kiov == NULL));
682                 }
683         }
684
685         rc = (ni->ni_net->net_lnd->lnd_recv)(ni, private, msg, delayed,
686                                              niov, kiov, offset, mlen,
687                                              rlen);
688         if (rc < 0)
689                 lnet_finalize(msg, rc);
690 }
691
692 static void
693 lnet_setpayloadbuffer(struct lnet_msg *msg)
694 {
695         struct lnet_libmd *md = msg->msg_md;
696
697         LASSERT(msg->msg_len > 0);
698         LASSERT(!msg->msg_routing);
699         LASSERT(md != NULL);
700         LASSERT(msg->msg_niov == 0);
701         LASSERT(msg->msg_kiov == NULL);
702
703         msg->msg_niov = md->md_niov;
704         msg->msg_kiov = md->md_kiov;
705 }
706
707 void
708 lnet_prep_send(struct lnet_msg *msg, int type, struct lnet_process_id target,
709                unsigned int offset, unsigned int len)
710 {
711         msg->msg_type = type;
712         msg->msg_target = target;
713         msg->msg_len = len;
714         msg->msg_offset = offset;
715
716         if (len != 0)
717                 lnet_setpayloadbuffer(msg);
718
719         memset (&msg->msg_hdr, 0, sizeof (msg->msg_hdr));
720         msg->msg_hdr.type           = cpu_to_le32(type);
721         /* dest_nid will be overwritten by lnet_select_pathway() */
722         msg->msg_hdr.dest_nid       = cpu_to_le64(target.nid);
723         msg->msg_hdr.dest_pid       = cpu_to_le32(target.pid);
724         /* src_nid will be set later */
725         msg->msg_hdr.src_pid        = cpu_to_le32(the_lnet.ln_pid);
726         msg->msg_hdr.payload_length = cpu_to_le32(len);
727 }
728
729 static void
730 lnet_ni_send(struct lnet_ni *ni, struct lnet_msg *msg)
731 {
732         void *priv = msg->msg_private;
733         int rc;
734
735         LASSERT(!in_interrupt());
736         LASSERT(ni->ni_nid == LNET_NID_LO_0 ||
737                 (msg->msg_txcredit && msg->msg_peertxcredit));
738
739         rc = (ni->ni_net->net_lnd->lnd_send)(ni, priv, msg);
740         if (rc < 0) {
741                 msg->msg_no_resend = true;
742                 lnet_finalize(msg, rc);
743         }
744 }
745
746 static int
747 lnet_ni_eager_recv(struct lnet_ni *ni, struct lnet_msg *msg)
748 {
749         int     rc;
750
751         LASSERT(!msg->msg_sending);
752         LASSERT(msg->msg_receiving);
753         LASSERT(!msg->msg_rx_ready_delay);
754         LASSERT(ni->ni_net->net_lnd->lnd_eager_recv != NULL);
755
756         msg->msg_rx_ready_delay = 1;
757         rc = (ni->ni_net->net_lnd->lnd_eager_recv)(ni, msg->msg_private, msg,
758                                                   &msg->msg_private);
759         if (rc != 0) {
760                 CERROR("recv from %s / send to %s aborted: "
761                        "eager_recv failed %d\n",
762                        libcfs_nid2str(msg->msg_rxpeer->lpni_nid),
763                        libcfs_id2str(msg->msg_target), rc);
764                 LASSERT(rc < 0); /* required by my callers */
765         }
766
767         return rc;
768 }
769
770 static bool
771 lnet_is_peer_deadline_passed(struct lnet_peer_ni *lpni, time64_t now)
772 {
773         time64_t deadline;
774
775         deadline = lpni->lpni_last_alive +
776                    lpni->lpni_net->net_tunables.lct_peer_timeout;
777
778         /*
779          * assume peer_ni is alive as long as we're within the configured
780          * peer timeout
781          */
782         if (deadline > now)
783                 return false;
784
785         return true;
786 }
787
788 /* NB: returns 1 when alive, 0 when dead, negative when error;
789  *     may drop the lnet_net_lock */
790 static int
791 lnet_peer_alive_locked(struct lnet_ni *ni, struct lnet_peer_ni *lpni,
792                        struct lnet_msg *msg)
793 {
794         time64_t now = ktime_get_seconds();
795
796         if (!lnet_peer_aliveness_enabled(lpni))
797                 return -ENODEV;
798
799         /*
800          * If we're resending a message, let's attempt to send it even if
801          * the peer is down to fulfill our resend quota on the message
802          */
803         if (msg->msg_retry_count > 0)
804                 return 1;
805
806         /* try and send recovery messages irregardless */
807         if (msg->msg_recovery)
808                 return 1;
809
810         /* always send any responses */
811         if (lnet_msg_is_response(msg))
812                 return 1;
813
814         if (!lnet_is_peer_deadline_passed(lpni, now))
815                 return true;
816
817         return lnet_is_peer_ni_alive(lpni);
818 }
819
820 /**
821  * \param msg The message to be sent.
822  * \param do_send True if lnet_ni_send() should be called in this function.
823  *        lnet_send() is going to lnet_net_unlock immediately after this, so
824  *        it sets do_send FALSE and I don't do the unlock/send/lock bit.
825  *
826  * \retval LNET_CREDIT_OK If \a msg sent or OK to send.
827  * \retval LNET_CREDIT_WAIT If \a msg blocked for credit.
828  * \retval -EHOSTUNREACH If the next hop of the message appears dead.
829  * \retval -ECANCELED If the MD of the message has been unlinked.
830  */
831 static int
832 lnet_post_send_locked(struct lnet_msg *msg, int do_send)
833 {
834         struct lnet_peer_ni     *lp = msg->msg_txpeer;
835         struct lnet_ni          *ni = msg->msg_txni;
836         int                     cpt = msg->msg_tx_cpt;
837         struct lnet_tx_queue    *tq = ni->ni_tx_queues[cpt];
838
839         /* non-lnet_send() callers have checked before */
840         LASSERT(!do_send || msg->msg_tx_delayed);
841         LASSERT(!msg->msg_receiving);
842         LASSERT(msg->msg_tx_committed);
843
844         /* can't get here if we're sending to the loopback interface */
845         if (the_lnet.ln_loni)
846                 LASSERT(lp->lpni_nid != the_lnet.ln_loni->ni_nid);
847
848         /* NB 'lp' is always the next hop */
849         if ((msg->msg_target.pid & LNET_PID_USERFLAG) == 0 &&
850             lnet_peer_alive_locked(ni, lp, msg) == 0) {
851                 the_lnet.ln_counters[cpt]->lct_common.lcc_drop_count++;
852                 the_lnet.ln_counters[cpt]->lct_common.lcc_drop_length +=
853                         msg->msg_len;
854                 lnet_net_unlock(cpt);
855                 if (msg->msg_txpeer)
856                         lnet_incr_stats(&msg->msg_txpeer->lpni_stats,
857                                         msg->msg_type,
858                                         LNET_STATS_TYPE_DROP);
859                 if (msg->msg_txni)
860                         lnet_incr_stats(&msg->msg_txni->ni_stats,
861                                         msg->msg_type,
862                                         LNET_STATS_TYPE_DROP);
863
864                 CNETERR("Dropping message for %s: peer not alive\n",
865                         libcfs_id2str(msg->msg_target));
866                 msg->msg_health_status = LNET_MSG_STATUS_REMOTE_DROPPED;
867                 if (do_send)
868                         lnet_finalize(msg, -EHOSTUNREACH);
869
870                 lnet_net_lock(cpt);
871                 return -EHOSTUNREACH;
872         }
873
874         if (msg->msg_md != NULL &&
875             (msg->msg_md->md_flags & LNET_MD_FLAG_ABORTED) != 0) {
876                 lnet_net_unlock(cpt);
877
878                 CNETERR("Aborting message for %s: LNetM[DE]Unlink() already "
879                         "called on the MD/ME.\n",
880                         libcfs_id2str(msg->msg_target));
881                 if (do_send) {
882                         msg->msg_no_resend = true;
883                         CDEBUG(D_NET, "msg %p to %s canceled and will not be resent\n",
884                                msg, libcfs_id2str(msg->msg_target));
885                         lnet_finalize(msg, -ECANCELED);
886                 }
887
888                 lnet_net_lock(cpt);
889                 return -ECANCELED;
890         }
891
892         if (!msg->msg_peertxcredit) {
893                 spin_lock(&lp->lpni_lock);
894                 LASSERT((lp->lpni_txcredits < 0) ==
895                         !list_empty(&lp->lpni_txq));
896
897                 msg->msg_peertxcredit = 1;
898                 lp->lpni_txqnob += msg->msg_len + sizeof(struct lnet_hdr);
899                 lp->lpni_txcredits--;
900
901                 if (lp->lpni_txcredits < lp->lpni_mintxcredits)
902                         lp->lpni_mintxcredits = lp->lpni_txcredits;
903
904                 if (lp->lpni_txcredits < 0) {
905                         msg->msg_tx_delayed = 1;
906                         list_add_tail(&msg->msg_list, &lp->lpni_txq);
907                         spin_unlock(&lp->lpni_lock);
908                         return LNET_CREDIT_WAIT;
909                 }
910                 spin_unlock(&lp->lpni_lock);
911         }
912
913         if (!msg->msg_txcredit) {
914                 LASSERT((tq->tq_credits < 0) ==
915                         !list_empty(&tq->tq_delayed));
916
917                 msg->msg_txcredit = 1;
918                 tq->tq_credits--;
919                 atomic_dec(&ni->ni_tx_credits);
920
921                 if (tq->tq_credits < tq->tq_credits_min)
922                         tq->tq_credits_min = tq->tq_credits;
923
924                 if (tq->tq_credits < 0) {
925                         msg->msg_tx_delayed = 1;
926                         list_add_tail(&msg->msg_list, &tq->tq_delayed);
927                         return LNET_CREDIT_WAIT;
928                 }
929         }
930
931         /* unset the tx_delay flag as we're going to send it now */
932         msg->msg_tx_delayed = 0;
933
934         if (do_send) {
935                 lnet_net_unlock(cpt);
936                 lnet_ni_send(ni, msg);
937                 lnet_net_lock(cpt);
938         }
939         return LNET_CREDIT_OK;
940 }
941
942
943 static struct lnet_rtrbufpool *
944 lnet_msg2bufpool(struct lnet_msg *msg)
945 {
946         struct lnet_rtrbufpool  *rbp;
947         int                     cpt;
948
949         LASSERT(msg->msg_rx_committed);
950
951         cpt = msg->msg_rx_cpt;
952         rbp = &the_lnet.ln_rtrpools[cpt][0];
953
954         LASSERT(msg->msg_len <= LNET_MTU);
955         while (msg->msg_len > (unsigned int)rbp->rbp_npages * PAGE_SIZE) {
956                 rbp++;
957                 LASSERT(rbp < &the_lnet.ln_rtrpools[cpt][LNET_NRBPOOLS]);
958         }
959
960         return rbp;
961 }
962
963 static int
964 lnet_post_routed_recv_locked(struct lnet_msg *msg, int do_recv)
965 {
966         /* lnet_parse is going to lnet_net_unlock immediately after this, so it
967          * sets do_recv FALSE and I don't do the unlock/send/lock bit.
968          * I return LNET_CREDIT_WAIT if msg blocked and LNET_CREDIT_OK if
969          * received or OK to receive */
970         struct lnet_peer_ni *lpni = msg->msg_rxpeer;
971         struct lnet_peer *lp;
972         struct lnet_rtrbufpool *rbp;
973         struct lnet_rtrbuf *rb;
974
975         LASSERT(msg->msg_kiov == NULL);
976         LASSERT(msg->msg_niov == 0);
977         LASSERT(msg->msg_routing);
978         LASSERT(msg->msg_receiving);
979         LASSERT(!msg->msg_sending);
980         LASSERT(lpni->lpni_peer_net);
981         LASSERT(lpni->lpni_peer_net->lpn_peer);
982
983         lp = lpni->lpni_peer_net->lpn_peer;
984
985         /* non-lnet_parse callers only receive delayed messages */
986         LASSERT(!do_recv || msg->msg_rx_delayed);
987
988         if (!msg->msg_peerrtrcredit) {
989                 /* lpni_lock protects the credit manipulation */
990                 spin_lock(&lpni->lpni_lock);
991
992                 msg->msg_peerrtrcredit = 1;
993                 lpni->lpni_rtrcredits--;
994                 if (lpni->lpni_rtrcredits < lpni->lpni_minrtrcredits)
995                         lpni->lpni_minrtrcredits = lpni->lpni_rtrcredits;
996
997                 if (lpni->lpni_rtrcredits < 0) {
998                         spin_unlock(&lpni->lpni_lock);
999                         /* must have checked eager_recv before here */
1000                         LASSERT(msg->msg_rx_ready_delay);
1001                         msg->msg_rx_delayed = 1;
1002                         /* lp_lock protects the lp_rtrq */
1003                         spin_lock(&lp->lp_lock);
1004                         list_add_tail(&msg->msg_list, &lp->lp_rtrq);
1005                         spin_unlock(&lp->lp_lock);
1006                         return LNET_CREDIT_WAIT;
1007                 }
1008                 spin_unlock(&lpni->lpni_lock);
1009         }
1010
1011         rbp = lnet_msg2bufpool(msg);
1012
1013         if (!msg->msg_rtrcredit) {
1014                 msg->msg_rtrcredit = 1;
1015                 rbp->rbp_credits--;
1016                 if (rbp->rbp_credits < rbp->rbp_mincredits)
1017                         rbp->rbp_mincredits = rbp->rbp_credits;
1018
1019                 if (rbp->rbp_credits < 0) {
1020                         /* must have checked eager_recv before here */
1021                         LASSERT(msg->msg_rx_ready_delay);
1022                         msg->msg_rx_delayed = 1;
1023                         list_add_tail(&msg->msg_list, &rbp->rbp_msgs);
1024                         return LNET_CREDIT_WAIT;
1025                 }
1026         }
1027
1028         LASSERT(!list_empty(&rbp->rbp_bufs));
1029         rb = list_entry(rbp->rbp_bufs.next, struct lnet_rtrbuf, rb_list);
1030         list_del(&rb->rb_list);
1031
1032         msg->msg_niov = rbp->rbp_npages;
1033         msg->msg_kiov = &rb->rb_kiov[0];
1034
1035         /* unset the msg-rx_delayed flag since we're receiving the message */
1036         msg->msg_rx_delayed = 0;
1037
1038         if (do_recv) {
1039                 int cpt = msg->msg_rx_cpt;
1040
1041                 lnet_net_unlock(cpt);
1042                 lnet_ni_recv(msg->msg_rxni, msg->msg_private, msg, 1,
1043                              0, msg->msg_len, msg->msg_len);
1044                 lnet_net_lock(cpt);
1045         }
1046         return LNET_CREDIT_OK;
1047 }
1048
1049 void
1050 lnet_return_tx_credits_locked(struct lnet_msg *msg)
1051 {
1052         struct lnet_peer_ni     *txpeer = msg->msg_txpeer;
1053         struct lnet_ni          *txni = msg->msg_txni;
1054         struct lnet_msg         *msg2;
1055
1056         if (msg->msg_txcredit) {
1057                 struct lnet_ni       *ni = msg->msg_txni;
1058                 struct lnet_tx_queue *tq = ni->ni_tx_queues[msg->msg_tx_cpt];
1059
1060                 /* give back NI txcredits */
1061                 msg->msg_txcredit = 0;
1062
1063                 LASSERT((tq->tq_credits < 0) ==
1064                         !list_empty(&tq->tq_delayed));
1065
1066                 tq->tq_credits++;
1067                 atomic_inc(&ni->ni_tx_credits);
1068                 if (tq->tq_credits <= 0) {
1069                         msg2 = list_entry(tq->tq_delayed.next,
1070                                           struct lnet_msg, msg_list);
1071                         list_del(&msg2->msg_list);
1072
1073                         LASSERT(msg2->msg_txni == ni);
1074                         LASSERT(msg2->msg_tx_delayed);
1075                         LASSERT(msg2->msg_tx_cpt == msg->msg_tx_cpt);
1076
1077                         (void) lnet_post_send_locked(msg2, 1);
1078                 }
1079         }
1080
1081         if (msg->msg_peertxcredit) {
1082                 /* give back peer txcredits */
1083                 msg->msg_peertxcredit = 0;
1084
1085                 spin_lock(&txpeer->lpni_lock);
1086                 LASSERT((txpeer->lpni_txcredits < 0) ==
1087                         !list_empty(&txpeer->lpni_txq));
1088
1089                 txpeer->lpni_txqnob -= msg->msg_len + sizeof(struct lnet_hdr);
1090                 LASSERT(txpeer->lpni_txqnob >= 0);
1091
1092                 txpeer->lpni_txcredits++;
1093                 if (txpeer->lpni_txcredits <= 0) {
1094                         int msg2_cpt;
1095
1096                         msg2 = list_entry(txpeer->lpni_txq.next,
1097                                               struct lnet_msg, msg_list);
1098                         list_del(&msg2->msg_list);
1099                         spin_unlock(&txpeer->lpni_lock);
1100
1101                         LASSERT(msg2->msg_txpeer == txpeer);
1102                         LASSERT(msg2->msg_tx_delayed);
1103
1104                         msg2_cpt = msg2->msg_tx_cpt;
1105
1106                         /*
1107                          * The msg_cpt can be different from the msg2_cpt
1108                          * so we need to make sure we lock the correct cpt
1109                          * for msg2.
1110                          * Once we call lnet_post_send_locked() it is no
1111                          * longer safe to access msg2, since it could've
1112                          * been freed by lnet_finalize(), but we still
1113                          * need to relock the correct cpt, so we cache the
1114                          * msg2_cpt for the purpose of the check that
1115                          * follows the call to lnet_pose_send_locked().
1116                          */
1117                         if (msg2_cpt != msg->msg_tx_cpt) {
1118                                 lnet_net_unlock(msg->msg_tx_cpt);
1119                                 lnet_net_lock(msg2_cpt);
1120                         }
1121                         (void) lnet_post_send_locked(msg2, 1);
1122                         if (msg2_cpt != msg->msg_tx_cpt) {
1123                                 lnet_net_unlock(msg2_cpt);
1124                                 lnet_net_lock(msg->msg_tx_cpt);
1125                         }
1126                 } else {
1127                         spin_unlock(&txpeer->lpni_lock);
1128                 }
1129         }
1130
1131         if (txni != NULL) {
1132                 msg->msg_txni = NULL;
1133                 lnet_ni_decref_locked(txni, msg->msg_tx_cpt);
1134         }
1135
1136         if (txpeer != NULL) {
1137                 msg->msg_txpeer = NULL;
1138                 lnet_peer_ni_decref_locked(txpeer);
1139         }
1140 }
1141
1142 void
1143 lnet_schedule_blocked_locked(struct lnet_rtrbufpool *rbp)
1144 {
1145         struct lnet_msg *msg;
1146
1147         if (list_empty(&rbp->rbp_msgs))
1148                 return;
1149         msg = list_entry(rbp->rbp_msgs.next,
1150                          struct lnet_msg, msg_list);
1151         list_del(&msg->msg_list);
1152
1153         (void)lnet_post_routed_recv_locked(msg, 1);
1154 }
1155
1156 void
1157 lnet_drop_routed_msgs_locked(struct list_head *list, int cpt)
1158 {
1159         struct lnet_msg *msg;
1160         struct lnet_msg *tmp;
1161
1162         lnet_net_unlock(cpt);
1163
1164         list_for_each_entry_safe(msg, tmp, list, msg_list) {
1165                 lnet_ni_recv(msg->msg_rxni, msg->msg_private, NULL,
1166                              0, 0, 0, msg->msg_hdr.payload_length);
1167                 list_del_init(&msg->msg_list);
1168                 msg->msg_no_resend = true;
1169                 msg->msg_health_status = LNET_MSG_STATUS_REMOTE_ERROR;
1170                 lnet_finalize(msg, -ECANCELED);
1171         }
1172
1173         lnet_net_lock(cpt);
1174 }
1175
1176 void
1177 lnet_return_rx_credits_locked(struct lnet_msg *msg)
1178 {
1179         struct lnet_peer_ni *rxpeerni = msg->msg_rxpeer;
1180         struct lnet_peer *lp;
1181         struct lnet_ni *rxni = msg->msg_rxni;
1182         struct lnet_msg *msg2;
1183
1184         if (msg->msg_rtrcredit) {
1185                 /* give back global router credits */
1186                 struct lnet_rtrbuf *rb;
1187                 struct lnet_rtrbufpool *rbp;
1188
1189                 /* NB If a msg ever blocks for a buffer in rbp_msgs, it stays
1190                  * there until it gets one allocated, or aborts the wait
1191                  * itself */
1192                 LASSERT(msg->msg_kiov != NULL);
1193
1194                 rb = list_entry(msg->msg_kiov, struct lnet_rtrbuf, rb_kiov[0]);
1195                 rbp = rb->rb_pool;
1196
1197                 msg->msg_kiov = NULL;
1198                 msg->msg_rtrcredit = 0;
1199
1200                 LASSERT(rbp == lnet_msg2bufpool(msg));
1201
1202                 LASSERT((rbp->rbp_credits > 0) ==
1203                         !list_empty(&rbp->rbp_bufs));
1204
1205                 /* If routing is now turned off, we just drop this buffer and
1206                  * don't bother trying to return credits.  */
1207                 if (!the_lnet.ln_routing) {
1208                         lnet_destroy_rtrbuf(rb, rbp->rbp_npages);
1209                         goto routing_off;
1210                 }
1211
1212                 /* It is possible that a user has lowered the desired number of
1213                  * buffers in this pool.  Make sure we never put back
1214                  * more buffers than the stated number. */
1215                 if (unlikely(rbp->rbp_credits >= rbp->rbp_req_nbuffers)) {
1216                         /* Discard this buffer so we don't have too
1217                          * many. */
1218                         lnet_destroy_rtrbuf(rb, rbp->rbp_npages);
1219                         rbp->rbp_nbuffers--;
1220                 } else {
1221                         list_add(&rb->rb_list, &rbp->rbp_bufs);
1222                         rbp->rbp_credits++;
1223                         if (rbp->rbp_credits <= 0)
1224                                 lnet_schedule_blocked_locked(rbp);
1225                 }
1226         }
1227
1228 routing_off:
1229         if (msg->msg_peerrtrcredit) {
1230                 LASSERT(rxpeerni);
1231                 LASSERT(rxpeerni->lpni_peer_net);
1232                 LASSERT(rxpeerni->lpni_peer_net->lpn_peer);
1233
1234                 /* give back peer router credits */
1235                 msg->msg_peerrtrcredit = 0;
1236
1237                 spin_lock(&rxpeerni->lpni_lock);
1238                 rxpeerni->lpni_rtrcredits++;
1239                 spin_unlock(&rxpeerni->lpni_lock);
1240
1241                 lp = rxpeerni->lpni_peer_net->lpn_peer;
1242                 spin_lock(&lp->lp_lock);
1243
1244                 /* drop all messages which are queued to be routed on that
1245                  * peer. */
1246                 if (!the_lnet.ln_routing) {
1247                         LIST_HEAD(drop);
1248                         list_splice_init(&lp->lp_rtrq, &drop);
1249                         spin_unlock(&lp->lp_lock);
1250                         lnet_drop_routed_msgs_locked(&drop, msg->msg_rx_cpt);
1251                 } else if (!list_empty(&lp->lp_rtrq)) {
1252                         int msg2_cpt;
1253
1254                         msg2 = list_entry(lp->lp_rtrq.next,
1255                                           struct lnet_msg, msg_list);
1256                         list_del(&msg2->msg_list);
1257                         msg2_cpt = msg2->msg_rx_cpt;
1258                         spin_unlock(&lp->lp_lock);
1259                         /*
1260                          * messages on the lp_rtrq can be from any NID in
1261                          * the peer, which means they might have different
1262                          * cpts. We need to make sure we lock the right
1263                          * one.
1264                          */
1265                         if (msg2_cpt != msg->msg_rx_cpt) {
1266                                 lnet_net_unlock(msg->msg_rx_cpt);
1267                                 lnet_net_lock(msg2_cpt);
1268                         }
1269                         (void) lnet_post_routed_recv_locked(msg2, 1);
1270                         if (msg2_cpt != msg->msg_rx_cpt) {
1271                                 lnet_net_unlock(msg2_cpt);
1272                                 lnet_net_lock(msg->msg_rx_cpt);
1273                         }
1274                 } else {
1275                         spin_unlock(&lp->lp_lock);
1276                 }
1277         }
1278         if (rxni != NULL) {
1279                 msg->msg_rxni = NULL;
1280                 lnet_ni_decref_locked(rxni, msg->msg_rx_cpt);
1281         }
1282         if (rxpeerni != NULL) {
1283                 msg->msg_rxpeer = NULL;
1284                 lnet_peer_ni_decref_locked(rxpeerni);
1285         }
1286 }
1287
1288 static struct lnet_peer_ni *
1289 lnet_select_peer_ni(struct lnet_ni *best_ni, lnet_nid_t dst_nid,
1290                     struct lnet_peer *peer,
1291                     struct lnet_peer_ni *best_lpni,
1292                     struct lnet_peer_net *peer_net)
1293 {
1294         /*
1295          * Look at the peer NIs for the destination peer that connect
1296          * to the chosen net. If a peer_ni is preferred when using the
1297          * best_ni to communicate, we use that one. If there is no
1298          * preferred peer_ni, or there are multiple preferred peer_ni,
1299          * the available transmit credits are used. If the transmit
1300          * credits are equal, we round-robin over the peer_ni.
1301          */
1302         struct lnet_peer_ni *lpni = NULL;
1303         int best_lpni_credits = (best_lpni) ? best_lpni->lpni_txcredits :
1304                 INT_MIN;
1305         int best_lpni_healthv = (best_lpni) ?
1306                 atomic_read(&best_lpni->lpni_healthv) : 0;
1307         bool best_lpni_is_preferred = false;
1308         bool lpni_is_preferred;
1309         int lpni_healthv;
1310         __u32 lpni_sel_prio;
1311         __u32 best_sel_prio = LNET_MAX_SELECTION_PRIORITY;
1312
1313         while ((lpni = lnet_get_next_peer_ni_locked(peer, peer_net, lpni))) {
1314                 /*
1315                  * if the best_ni we've chosen aleady has this lpni
1316                  * preferred, then let's use it
1317                  */
1318                 if (best_ni) {
1319                         lpni_is_preferred = lnet_peer_is_pref_nid_locked(lpni,
1320                                                                 best_ni->ni_nid);
1321                         CDEBUG(D_NET, "%s lpni_is_preferred = %d\n",
1322                                libcfs_nid2str(best_ni->ni_nid),
1323                                lpni_is_preferred);
1324                 } else {
1325                         lpni_is_preferred = false;
1326                 }
1327
1328                 lpni_healthv = atomic_read(&lpni->lpni_healthv);
1329                 lpni_sel_prio = lpni->lpni_sel_priority;
1330
1331                 if (best_lpni)
1332                         CDEBUG(D_NET, "n:[%s, %s] h:[%d, %d] p:[%d, %d] c:[%d, %d] s:[%d, %d]\n",
1333                                 libcfs_nid2str(lpni->lpni_nid),
1334                                 libcfs_nid2str(best_lpni->lpni_nid),
1335                                 lpni_healthv, best_lpni_healthv,
1336                                 lpni_sel_prio, best_sel_prio,
1337                                 lpni->lpni_txcredits, best_lpni_credits,
1338                                 lpni->lpni_seq, best_lpni->lpni_seq);
1339                 else
1340                         goto select_lpni;
1341
1342                 /* pick the healthiest peer ni */
1343                 if (lpni_healthv < best_lpni_healthv)
1344                         continue;
1345                 else if (lpni_healthv > best_lpni_healthv) {
1346                         if (best_lpni_is_preferred)
1347                                 best_lpni_is_preferred = false;
1348                         goto select_lpni;
1349                 }
1350
1351                 if (lpni_sel_prio > best_sel_prio)
1352                         continue;
1353                 else if (lpni_sel_prio < best_sel_prio) {
1354                         if (best_lpni_is_preferred)
1355                                 best_lpni_is_preferred = false;
1356                         goto select_lpni;
1357                 }
1358
1359                 /* if this is a preferred peer use it */
1360                 if (!best_lpni_is_preferred && lpni_is_preferred) {
1361                         best_lpni_is_preferred = true;
1362                         goto select_lpni;
1363                 } else if (best_lpni_is_preferred && !lpni_is_preferred) {
1364                         /* this is not the preferred peer so let's ignore
1365                          * it.
1366                          */
1367                         continue;
1368                 }
1369
1370                 if (lpni->lpni_txcredits < best_lpni_credits)
1371                         /* We already have a peer that has more credits
1372                          * available than this one. No need to consider
1373                          * this peer further.
1374                          */
1375                         continue;
1376                 else if (lpni->lpni_txcredits > best_lpni_credits)
1377                         goto select_lpni;
1378
1379                 /* The best peer found so far and the current peer
1380                  * have the same number of available credits let's
1381                  * make sure to select between them using Round Robin
1382                  */
1383                 if (best_lpni && (best_lpni->lpni_seq <= lpni->lpni_seq))
1384                         continue;
1385 select_lpni:
1386                 best_lpni_is_preferred = lpni_is_preferred;
1387                 best_lpni_healthv = lpni_healthv;
1388                 best_sel_prio = lpni_sel_prio;
1389                 best_lpni = lpni;
1390                 best_lpni_credits = lpni->lpni_txcredits;
1391         }
1392
1393         /* if we still can't find a peer ni then we can't reach it */
1394         if (!best_lpni) {
1395                 __u32 net_id = (peer_net) ? peer_net->lpn_net_id :
1396                         LNET_NIDNET(dst_nid);
1397                 CDEBUG(D_NET, "no peer_ni found on peer net %s\n",
1398                                 libcfs_net2str(net_id));
1399                 return NULL;
1400         }
1401
1402         CDEBUG(D_NET, "sd_best_lpni = %s\n",
1403                libcfs_nid2str(best_lpni->lpni_nid));
1404
1405         return best_lpni;
1406 }
1407
1408 /*
1409  * Prerequisite: the best_ni should already be set in the sd
1410  * Find the best lpni.
1411  * If the net id is provided then restrict lpni selection on
1412  * that particular net.
1413  * Otherwise find any reachable lpni. When dealing with an MR
1414  * gateway and it has multiple lpnis which we can use
1415  * we want to select the best one from the list of reachable
1416  * ones.
1417  */
1418 static inline struct lnet_peer_ni *
1419 lnet_find_best_lpni(struct lnet_ni *lni, lnet_nid_t dst_nid,
1420                     struct lnet_peer *peer, __u32 net_id)
1421 {
1422         struct lnet_peer_net *peer_net;
1423
1424         /* find the best_lpni on any local network */
1425         if (net_id == LNET_NET_ANY) {
1426                 struct lnet_peer_ni *best_lpni = NULL;
1427                 struct lnet_peer_net *lpn;
1428                 list_for_each_entry(lpn, &peer->lp_peer_nets, lpn_peer_nets) {
1429                         /* no net specified find any reachable peer ni */
1430                         if (!lnet_islocalnet_locked(lpn->lpn_net_id))
1431                                 continue;
1432                         best_lpni = lnet_select_peer_ni(lni, dst_nid, peer,
1433                                                         best_lpni, lpn);
1434                 }
1435
1436                 return best_lpni;
1437         }
1438         /* restrict on the specified net */
1439         peer_net = lnet_peer_get_net_locked(peer, net_id);
1440         if (peer_net)
1441                 return lnet_select_peer_ni(lni, dst_nid, peer, NULL, peer_net);
1442
1443         return NULL;
1444 }
1445
1446 static int
1447 lnet_compare_gw_lpnis(struct lnet_peer_ni *lpni1, struct lnet_peer_ni *lpni2)
1448 {
1449         if (lpni1->lpni_txqnob < lpni2->lpni_txqnob)
1450                 return 1;
1451
1452         if (lpni1->lpni_txqnob > lpni2->lpni_txqnob)
1453                 return -1;
1454
1455         if (lpni1->lpni_txcredits > lpni2->lpni_txcredits)
1456                 return 1;
1457
1458         if (lpni1->lpni_txcredits < lpni2->lpni_txcredits)
1459                 return -1;
1460
1461         return 0;
1462 }
1463
1464 /* Compare route priorities and hop counts */
1465 static int
1466 lnet_compare_routes(struct lnet_route *r1, struct lnet_route *r2)
1467 {
1468         int r1_hops = (r1->lr_hops == LNET_UNDEFINED_HOPS) ? 1 : r1->lr_hops;
1469         int r2_hops = (r2->lr_hops == LNET_UNDEFINED_HOPS) ? 1 : r2->lr_hops;
1470
1471         if (r1->lr_priority < r2->lr_priority)
1472                 return 1;
1473
1474         if (r1->lr_priority > r2->lr_priority)
1475                 return -1;
1476
1477         if (r1_hops < r2_hops)
1478                 return 1;
1479
1480         if (r1_hops > r2_hops)
1481                 return -1;
1482
1483         return 0;
1484 }
1485
1486 static struct lnet_route *
1487 lnet_find_route_locked(struct lnet_remotenet *rnet, __u32 src_net,
1488                        struct lnet_peer_ni *remote_lpni,
1489                        struct lnet_route **prev_route,
1490                        struct lnet_peer_ni **gwni)
1491 {
1492         struct lnet_peer_ni *lpni, *best_gw_ni = NULL;
1493         struct lnet_route *best_route;
1494         struct lnet_route *last_route;
1495         struct lnet_route *route;
1496         int rc;
1497         bool best_rte_is_preferred = false;
1498         lnet_nid_t gw_pnid;
1499
1500         CDEBUG(D_NET, "Looking up a route to %s, from %s\n",
1501                libcfs_net2str(rnet->lrn_net), libcfs_net2str(src_net));
1502
1503         best_route = last_route = NULL;
1504         list_for_each_entry(route, &rnet->lrn_routes, lr_list) {
1505                 if (!lnet_is_route_alive(route))
1506                         continue;
1507                 gw_pnid = route->lr_gateway->lp_primary_nid;
1508
1509                 /* no protection on below fields, but it's harmless */
1510                 if (last_route && (last_route->lr_seq - route->lr_seq < 0))
1511                         last_route = route;
1512
1513                 /* if the best route found is in the preferred list then
1514                  * tag it as preferred and use it later on. But if we
1515                  * didn't find any routes which are on the preferred list
1516                  * then just use the best route possible.
1517                  */
1518                 rc = lnet_peer_is_pref_rtr_locked(remote_lpni, gw_pnid);
1519
1520                 if (!best_route || (rc && !best_rte_is_preferred)) {
1521                         /* Restrict the selection of the router NI on the
1522                          * src_net provided. If the src_net is LNET_NID_ANY,
1523                          * then select the best interface available.
1524                          */
1525                         lpni = lnet_find_best_lpni(NULL, LNET_NID_ANY,
1526                                                    route->lr_gateway,
1527                                                    src_net);
1528                         if (!lpni) {
1529                                 CDEBUG(D_NET,
1530                                        "Gateway %s does not have a peer NI on net %s\n",
1531                                        libcfs_nid2str(gw_pnid),
1532                                        libcfs_net2str(src_net));
1533                                 continue;
1534                         }
1535                 }
1536
1537                 if (rc && !best_rte_is_preferred) {
1538                         /* This is the first preferred route we found,
1539                          * so it beats any route found previously
1540                          */
1541                         best_route = route;
1542                         if (!last_route)
1543                                 last_route = route;
1544                         best_gw_ni = lpni;
1545                         best_rte_is_preferred = true;
1546                         CDEBUG(D_NET, "preferred gw = %s\n",
1547                                libcfs_nid2str(gw_pnid));
1548                         continue;
1549                 } else if ((!rc) && best_rte_is_preferred)
1550                         /* The best route we found so far is in the preferred
1551                          * list, so it beats any non-preferred route
1552                          */
1553                         continue;
1554
1555                 if (!best_route) {
1556                         best_route = last_route = route;
1557                         best_gw_ni = lpni;
1558                         continue;
1559                 }
1560
1561                 rc = lnet_compare_routes(route, best_route);
1562                 if (rc == -1)
1563                         continue;
1564
1565                 /* Restrict the selection of the router NI on the
1566                  * src_net provided. If the src_net is LNET_NID_ANY,
1567                  * then select the best interface available.
1568                  */
1569                 lpni = lnet_find_best_lpni(NULL, LNET_NID_ANY,
1570                                            route->lr_gateway,
1571                                            src_net);
1572                 if (!lpni) {
1573                         CDEBUG(D_NET,
1574                                "Gateway %s does not have a peer NI on net %s\n",
1575                                libcfs_nid2str(gw_pnid),
1576                                libcfs_net2str(src_net));
1577                         continue;
1578                 }
1579
1580                 if (rc == 1) {
1581                         best_route = route;
1582                         best_gw_ni = lpni;
1583                         continue;
1584                 }
1585
1586                 rc = lnet_compare_gw_lpnis(lpni, best_gw_ni);
1587                 if (rc == -1)
1588                         continue;
1589
1590                 if (rc == 1 || route->lr_seq <= best_route->lr_seq) {
1591                         best_route = route;
1592                         best_gw_ni = lpni;
1593                         continue;
1594                 }
1595         }
1596
1597         *prev_route = last_route;
1598         *gwni = best_gw_ni;
1599
1600         return best_route;
1601 }
1602
1603 static struct lnet_ni *
1604 lnet_get_best_ni(struct lnet_net *local_net, struct lnet_ni *best_ni,
1605                  struct lnet_peer *peer, struct lnet_peer_net *peer_net,
1606                  int md_cpt)
1607 {
1608         struct lnet_ni *ni = NULL;
1609         unsigned int shortest_distance;
1610         int best_credits;
1611         int best_healthv;
1612         __u32 best_sel_prio;
1613
1614         /*
1615          * If there is no peer_ni that we can send to on this network,
1616          * then there is no point in looking for a new best_ni here.
1617         */
1618         if (!lnet_get_next_peer_ni_locked(peer, peer_net, NULL))
1619                 return best_ni;
1620
1621         if (best_ni == NULL) {
1622                 best_sel_prio = LNET_MAX_SELECTION_PRIORITY;
1623                 shortest_distance = UINT_MAX;
1624                 best_credits = INT_MIN;
1625                 best_healthv = 0;
1626         } else {
1627                 shortest_distance = cfs_cpt_distance(lnet_cpt_table(), md_cpt,
1628                                                      best_ni->ni_dev_cpt);
1629                 best_credits = atomic_read(&best_ni->ni_tx_credits);
1630                 best_healthv = atomic_read(&best_ni->ni_healthv);
1631                 best_sel_prio = best_ni->ni_sel_priority;
1632         }
1633
1634         while ((ni = lnet_get_next_ni_locked(local_net, ni))) {
1635                 unsigned int distance;
1636                 int ni_credits;
1637                 int ni_healthv;
1638                 int ni_fatal;
1639                 __u32 ni_sel_prio;
1640
1641                 ni_credits = atomic_read(&ni->ni_tx_credits);
1642                 ni_healthv = atomic_read(&ni->ni_healthv);
1643                 ni_fatal = atomic_read(&ni->ni_fatal_error_on);
1644                 ni_sel_prio = ni->ni_sel_priority;
1645
1646                 /*
1647                  * calculate the distance from the CPT on which
1648                  * the message memory is allocated to the CPT of
1649                  * the NI's physical device
1650                  */
1651                 distance = cfs_cpt_distance(lnet_cpt_table(),
1652                                             md_cpt,
1653                                             ni->ni_dev_cpt);
1654
1655                 /*
1656                  * All distances smaller than the NUMA range
1657                  * are treated equally.
1658                  */
1659                 if (distance < lnet_numa_range)
1660                         distance = lnet_numa_range;
1661
1662                 /*
1663                  * Select on health, shorter distance, available
1664                  * credits, then round-robin.
1665                  */
1666                 if (ni_fatal)
1667                         continue;
1668
1669                 if (best_ni)
1670                         CDEBUG(D_NET, "compare ni %s [c:%d, d:%d, s:%d, p:%u] with best_ni %s [c:%d, d:%d, s:%d, p:%u]\n",
1671                                libcfs_nid2str(ni->ni_nid), ni_credits, distance,
1672                                ni->ni_seq, ni_sel_prio,
1673                                (best_ni) ? libcfs_nid2str(best_ni->ni_nid)
1674                                : "not selected", best_credits, shortest_distance,
1675                                (best_ni) ? best_ni->ni_seq : 0,
1676                                best_sel_prio);
1677                 else
1678                         goto select_ni;
1679
1680                 if (ni_healthv < best_healthv)
1681                         continue;
1682                 else if (ni_healthv > best_healthv)
1683                         goto select_ni;
1684
1685                 if (ni_sel_prio > best_sel_prio)
1686                         continue;
1687                 else if (ni_sel_prio < best_sel_prio)
1688                         goto select_ni;
1689
1690                 if (distance > shortest_distance)
1691                         continue;
1692                 else if (distance < shortest_distance)
1693                         goto select_ni;
1694
1695                 if (ni_credits < best_credits)
1696                         continue;
1697                 else if (ni_credits > best_credits)
1698                         goto select_ni;
1699
1700                 if (best_ni && best_ni->ni_seq <= ni->ni_seq)
1701                         continue;
1702
1703 select_ni:
1704                 best_sel_prio = ni_sel_prio;
1705                 shortest_distance = distance;
1706                 best_healthv = ni_healthv;
1707                 best_ni = ni;
1708                 best_credits = ni_credits;
1709         }
1710
1711         CDEBUG(D_NET, "selected best_ni %s\n",
1712                (best_ni) ? libcfs_nid2str(best_ni->ni_nid) : "no selection");
1713
1714         return best_ni;
1715 }
1716
1717 /*
1718  * Traffic to the LNET_RESERVED_PORTAL may not trigger peer discovery,
1719  * because such traffic is required to perform discovery. We therefore
1720  * exclude all GET and PUT on that portal. We also exclude all ACK and
1721  * REPLY traffic, but that is because the portal is not tracked in the
1722  * message structure for these message types. We could restrict this
1723  * further by also checking for LNET_PROTO_PING_MATCHBITS.
1724  */
1725 static bool
1726 lnet_msg_discovery(struct lnet_msg *msg)
1727 {
1728         if (msg->msg_type == LNET_MSG_PUT) {
1729                 if (msg->msg_hdr.msg.put.ptl_index != LNET_RESERVED_PORTAL)
1730                         return true;
1731         } else if (msg->msg_type == LNET_MSG_GET) {
1732                 if (msg->msg_hdr.msg.get.ptl_index != LNET_RESERVED_PORTAL)
1733                         return true;
1734         }
1735         return false;
1736 }
1737
1738 #define SRC_SPEC        0x0001
1739 #define SRC_ANY         0x0002
1740 #define LOCAL_DST       0x0004
1741 #define REMOTE_DST      0x0008
1742 #define MR_DST          0x0010
1743 #define NMR_DST         0x0020
1744 #define SND_RESP        0x0040
1745
1746 /* The following to defines are used for return codes */
1747 #define REPEAT_SEND     0x1000
1748 #define PASS_THROUGH    0x2000
1749
1750 /* The different cases lnet_select pathway needs to handle */
1751 #define SRC_SPEC_LOCAL_MR_DST   (SRC_SPEC | LOCAL_DST | MR_DST)
1752 #define SRC_SPEC_ROUTER_MR_DST  (SRC_SPEC | REMOTE_DST | MR_DST)
1753 #define SRC_SPEC_LOCAL_NMR_DST  (SRC_SPEC | LOCAL_DST | NMR_DST)
1754 #define SRC_SPEC_ROUTER_NMR_DST (SRC_SPEC | REMOTE_DST | NMR_DST)
1755 #define SRC_ANY_LOCAL_MR_DST    (SRC_ANY | LOCAL_DST | MR_DST)
1756 #define SRC_ANY_ROUTER_MR_DST   (SRC_ANY | REMOTE_DST | MR_DST)
1757 #define SRC_ANY_LOCAL_NMR_DST   (SRC_ANY | LOCAL_DST | NMR_DST)
1758 #define SRC_ANY_ROUTER_NMR_DST  (SRC_ANY | REMOTE_DST | NMR_DST)
1759
1760 static int
1761 lnet_handle_lo_send(struct lnet_send_data *sd)
1762 {
1763         struct lnet_msg *msg = sd->sd_msg;
1764         int cpt = sd->sd_cpt;
1765
1766         if (the_lnet.ln_state != LNET_STATE_RUNNING)
1767                 return -ESHUTDOWN;
1768
1769         /* No send credit hassles with LOLND */
1770         lnet_ni_addref_locked(the_lnet.ln_loni, cpt);
1771         msg->msg_hdr.dest_nid = cpu_to_le64(the_lnet.ln_loni->ni_nid);
1772         if (!msg->msg_routing)
1773                 msg->msg_hdr.src_nid =
1774                         cpu_to_le64(the_lnet.ln_loni->ni_nid);
1775         msg->msg_target.nid = the_lnet.ln_loni->ni_nid;
1776         lnet_msg_commit(msg, cpt);
1777         msg->msg_txni = the_lnet.ln_loni;
1778
1779         return LNET_CREDIT_OK;
1780 }
1781
1782 static int
1783 lnet_handle_send(struct lnet_send_data *sd)
1784 {
1785         struct lnet_ni *best_ni = sd->sd_best_ni;
1786         struct lnet_peer_ni *best_lpni = sd->sd_best_lpni;
1787         struct lnet_peer_ni *final_dst_lpni = sd->sd_final_dst_lpni;
1788         struct lnet_msg *msg = sd->sd_msg;
1789         int cpt2;
1790         __u32 send_case = sd->sd_send_case;
1791         int rc;
1792         __u32 routing = send_case & REMOTE_DST;
1793          struct lnet_rsp_tracker *rspt;
1794
1795         /* Increment sequence number of the selected peer, peer net,
1796          * local ni and local net so that we pick the next ones
1797          * in Round Robin.
1798          */
1799         best_lpni->lpni_seq++;
1800         best_lpni->lpni_peer_net->lpn_seq++;
1801         best_ni->ni_seq++;
1802         best_ni->ni_net->net_seq++;
1803
1804         CDEBUG(D_NET, "%s NI seq info: [%d:%d:%d:%u] %s LPNI seq info [%d:%d:%d:%u]\n",
1805                libcfs_nid2str(best_ni->ni_nid),
1806                best_ni->ni_seq, best_ni->ni_net->net_seq,
1807                atomic_read(&best_ni->ni_tx_credits),
1808                best_ni->ni_sel_priority,
1809                libcfs_nid2str(best_lpni->lpni_nid),
1810                best_lpni->lpni_seq, best_lpni->lpni_peer_net->lpn_seq,
1811                best_lpni->lpni_txcredits,
1812                best_lpni->lpni_sel_priority);
1813
1814         /*
1815          * grab a reference on the peer_ni so it sticks around even if
1816          * we need to drop and relock the lnet_net_lock below.
1817          */
1818         lnet_peer_ni_addref_locked(best_lpni);
1819
1820         /*
1821          * Use lnet_cpt_of_nid() to determine the CPT used to commit the
1822          * message. This ensures that we get a CPT that is correct for
1823          * the NI when the NI has been restricted to a subset of all CPTs.
1824          * If the selected CPT differs from the one currently locked, we
1825          * must unlock and relock the lnet_net_lock(), and then check whether
1826          * the configuration has changed. We don't have a hold on the best_ni
1827          * yet, and it may have vanished.
1828          */
1829         cpt2 = lnet_cpt_of_nid_locked(best_lpni->lpni_nid, best_ni);
1830         if (sd->sd_cpt != cpt2) {
1831                 __u32 seq = lnet_get_dlc_seq_locked();
1832                 lnet_net_unlock(sd->sd_cpt);
1833                 sd->sd_cpt = cpt2;
1834                 lnet_net_lock(sd->sd_cpt);
1835                 if (seq != lnet_get_dlc_seq_locked()) {
1836                         lnet_peer_ni_decref_locked(best_lpni);
1837                         return REPEAT_SEND;
1838                 }
1839         }
1840
1841         /*
1842          * store the best_lpni in the message right away to avoid having
1843          * to do the same operation under different conditions
1844          */
1845         msg->msg_txpeer = best_lpni;
1846         msg->msg_txni = best_ni;
1847
1848         /*
1849          * grab a reference for the best_ni since now it's in use in this
1850          * send. The reference will be dropped in lnet_finalize()
1851          */
1852         lnet_ni_addref_locked(msg->msg_txni, sd->sd_cpt);
1853
1854         /*
1855          * Always set the target.nid to the best peer picked. Either the
1856          * NID will be one of the peer NIDs selected, or the same NID as
1857          * what was originally set in the target or it will be the NID of
1858          * a router if this message should be routed
1859          */
1860         msg->msg_target.nid = msg->msg_txpeer->lpni_nid;
1861
1862         /*
1863          * lnet_msg_commit assigns the correct cpt to the message, which
1864          * is used to decrement the correct refcount on the ni when it's
1865          * time to return the credits
1866          */
1867         lnet_msg_commit(msg, sd->sd_cpt);
1868
1869         /*
1870          * If we are routing the message then we keep the src_nid that was
1871          * set by the originator. If we are not routing then we are the
1872          * originator and set it here.
1873          */
1874         if (!msg->msg_routing)
1875                 msg->msg_hdr.src_nid = cpu_to_le64(msg->msg_txni->ni_nid);
1876
1877         if (routing) {
1878                 msg->msg_target_is_router = 1;
1879                 msg->msg_target.pid = LNET_PID_LUSTRE;
1880                 /*
1881                  * since we're routing we want to ensure that the
1882                  * msg_hdr.dest_nid is set to the final destination. When
1883                  * the router receives this message it knows how to route
1884                  * it.
1885                  *
1886                  * final_dst_lpni is set at the beginning of the
1887                  * lnet_select_pathway() function and is never changed.
1888                  * It's safe to use it here.
1889                  */
1890                 msg->msg_hdr.dest_nid = cpu_to_le64(final_dst_lpni->lpni_nid);
1891         } else {
1892                 /*
1893                  * if we're not routing set the dest_nid to the best peer
1894                  * ni NID that we picked earlier in the algorithm.
1895                  */
1896                 msg->msg_hdr.dest_nid = cpu_to_le64(msg->msg_txpeer->lpni_nid);
1897         }
1898
1899         /*
1900          * if we have response tracker block update it with the next hop
1901          * nid
1902          */
1903         if (msg->msg_md) {
1904                 rspt = msg->msg_md->md_rspt_ptr;
1905                 if (rspt) {
1906                         rspt->rspt_next_hop_nid = msg->msg_txpeer->lpni_nid;
1907                         CDEBUG(D_NET, "rspt_next_hop_nid = %s\n",
1908                                libcfs_nid2str(rspt->rspt_next_hop_nid));
1909                 }
1910         }
1911
1912         rc = lnet_post_send_locked(msg, 0);
1913
1914         if (!rc)
1915                 CDEBUG(D_NET, "TRACE: %s(%s:%s) -> %s(%s:%s) %s : %s try# %d\n",
1916                        libcfs_nid2str(msg->msg_hdr.src_nid),
1917                        libcfs_nid2str(msg->msg_txni->ni_nid),
1918                        libcfs_nid2str(sd->sd_src_nid),
1919                        libcfs_nid2str(msg->msg_hdr.dest_nid),
1920                        libcfs_nid2str(sd->sd_dst_nid),
1921                        libcfs_nid2str(msg->msg_txpeer->lpni_nid),
1922                        libcfs_nid2str(sd->sd_rtr_nid),
1923                        lnet_msgtyp2str(msg->msg_type), msg->msg_retry_count);
1924
1925         return rc;
1926 }
1927
1928 static inline void
1929 lnet_set_non_mr_pref_nid(struct lnet_peer_ni *lpni, struct lnet_ni *lni,
1930                          struct lnet_msg *msg)
1931 {
1932         if (!lnet_peer_is_multi_rail(lpni->lpni_peer_net->lpn_peer) &&
1933             !lnet_msg_is_response(msg) && lpni->lpni_pref_nnids == 0) {
1934                 CDEBUG(D_NET, "Setting preferred local NID %s on NMR peer %s\n",
1935                        libcfs_nid2str(lni->ni_nid),
1936                        libcfs_nid2str(lpni->lpni_nid));
1937                 lnet_peer_ni_set_non_mr_pref_nid(lpni, lni->ni_nid);
1938         }
1939 }
1940
1941 /*
1942  * Source Specified
1943  * Local Destination
1944  * non-mr peer
1945  *
1946  * use the source and destination NIDs as the pathway
1947  */
1948 static int
1949 lnet_handle_spec_local_nmr_dst(struct lnet_send_data *sd)
1950 {
1951         /* the destination lpni is set before we get here. */
1952
1953         /* find local NI */
1954         sd->sd_best_ni = lnet_nid2ni_locked(sd->sd_src_nid, sd->sd_cpt);
1955         if (!sd->sd_best_ni) {
1956                 CERROR("Can't send to %s: src %s is not a "
1957                        "local nid\n", libcfs_nid2str(sd->sd_dst_nid),
1958                                 libcfs_nid2str(sd->sd_src_nid));
1959                 return -EINVAL;
1960         }
1961
1962         lnet_set_non_mr_pref_nid(sd->sd_best_lpni, sd->sd_best_ni, sd->sd_msg);
1963
1964         return lnet_handle_send(sd);
1965 }
1966
1967 /*
1968  * Source Specified
1969  * Local Destination
1970  * MR Peer
1971  *
1972  * Don't run the selection algorithm on the peer NIs. By specifying the
1973  * local NID, we're also saying that we should always use the destination NID
1974  * provided. This handles the case where we should be using the same
1975  * destination NID for the all the messages which belong to the same RPC
1976  * request.
1977  */
1978 static int
1979 lnet_handle_spec_local_mr_dst(struct lnet_send_data *sd)
1980 {
1981         sd->sd_best_ni = lnet_nid2ni_locked(sd->sd_src_nid, sd->sd_cpt);
1982         if (!sd->sd_best_ni) {
1983                 CERROR("Can't send to %s: src %s is not a "
1984                        "local nid\n", libcfs_nid2str(sd->sd_dst_nid),
1985                                 libcfs_nid2str(sd->sd_src_nid));
1986                 return -EINVAL;
1987         }
1988
1989         if (sd->sd_best_lpni &&
1990             sd->sd_best_lpni->lpni_nid == the_lnet.ln_loni->ni_nid)
1991                 return lnet_handle_lo_send(sd);
1992         else if (sd->sd_best_lpni)
1993                 return lnet_handle_send(sd);
1994
1995         CERROR("can't send to %s. no NI on %s\n",
1996                libcfs_nid2str(sd->sd_dst_nid),
1997                libcfs_net2str(sd->sd_best_ni->ni_net->net_id));
1998
1999         return -EHOSTUNREACH;
2000 }
2001
2002 struct lnet_ni *
2003 lnet_find_best_ni_on_spec_net(struct lnet_ni *cur_best_ni,
2004                               struct lnet_peer *peer,
2005                               struct lnet_peer_net *peer_net,
2006                               int cpt)
2007 {
2008         struct lnet_net *local_net;
2009         struct lnet_ni *best_ni;
2010
2011         local_net = lnet_get_net_locked(peer_net->lpn_net_id);
2012         if (!local_net)
2013                 return NULL;
2014
2015         /*
2016          * Iterate through the NIs in this local Net and select
2017          * the NI to send from. The selection is determined by
2018          * these 3 criterion in the following priority:
2019          *      1. NUMA
2020          *      2. NI available credits
2021          *      3. Round Robin
2022          */
2023         best_ni = lnet_get_best_ni(local_net, cur_best_ni,
2024                                    peer, peer_net, cpt);
2025
2026         return best_ni;
2027 }
2028
2029 static int
2030 lnet_initiate_peer_discovery(struct lnet_peer_ni *lpni, struct lnet_msg *msg,
2031                              int cpt)
2032 {
2033         struct lnet_peer *peer;
2034         struct lnet_peer_ni *new_lpni;
2035         int rc;
2036
2037         lnet_peer_ni_addref_locked(lpni);
2038
2039         peer = lpni->lpni_peer_net->lpn_peer;
2040
2041         if (lnet_peer_gw_discovery(peer)) {
2042                 lnet_peer_ni_decref_locked(lpni);
2043                 return 0;
2044         }
2045
2046         if (!lnet_msg_discovery(msg) || lnet_peer_is_uptodate(peer)) {
2047                 lnet_peer_ni_decref_locked(lpni);
2048                 return 0;
2049         }
2050
2051         rc = lnet_discover_peer_locked(lpni, cpt, false);
2052         if (rc) {
2053                 lnet_peer_ni_decref_locked(lpni);
2054                 return rc;
2055         }
2056
2057         new_lpni = lnet_find_peer_ni_locked(lpni->lpni_nid);
2058         if (!new_lpni) {
2059                 lnet_peer_ni_decref_locked(lpni);
2060                 return -ENOENT;
2061         }
2062
2063         peer = new_lpni->lpni_peer_net->lpn_peer;
2064         spin_lock(&peer->lp_lock);
2065         if (lpni == new_lpni && lnet_peer_is_uptodate_locked(peer)) {
2066                 /* The peer NI did not change and the peer is up to date.
2067                  * Nothing more to do.
2068                  */
2069                 spin_unlock(&peer->lp_lock);
2070                 lnet_peer_ni_decref_locked(lpni);
2071                 lnet_peer_ni_decref_locked(new_lpni);
2072                 return 0;
2073         }
2074         spin_unlock(&peer->lp_lock);
2075
2076         /* Either the peer NI changed during discovery, or the peer isn't up
2077          * to date. In both cases we want to queue the message on the
2078          * (possibly new) peer's pending queue and queue the peer for discovery
2079          */
2080         msg->msg_sending = 0;
2081         msg->msg_txpeer = NULL;
2082         lnet_net_unlock(cpt);
2083         lnet_peer_queue_message(peer, msg);
2084         lnet_net_lock(cpt);
2085
2086         lnet_peer_ni_decref_locked(lpni);
2087         lnet_peer_ni_decref_locked(new_lpni);
2088
2089         CDEBUG(D_NET, "msg %p delayed. %s pending discovery\n",
2090                msg, libcfs_nid2str(peer->lp_primary_nid));
2091
2092         return LNET_DC_WAIT;
2093 }
2094
2095 static int
2096 lnet_handle_find_routed_path(struct lnet_send_data *sd,
2097                              lnet_nid_t dst_nid,
2098                              struct lnet_peer_ni **gw_lpni,
2099                              struct lnet_peer **gw_peer)
2100 {
2101         int rc;
2102         __u32 local_lnet;
2103         struct lnet_peer *gw;
2104         struct lnet_peer *lp;
2105         struct lnet_peer_net *lpn;
2106         struct lnet_peer_net *best_lpn = NULL;
2107         struct lnet_remotenet *rnet, *best_rnet = NULL;
2108         struct lnet_route *best_route = NULL;
2109         struct lnet_route *last_route = NULL;
2110         struct lnet_peer_ni *lpni = NULL;
2111         struct lnet_peer_ni *gwni = NULL;
2112         bool route_found = false;
2113         lnet_nid_t src_nid = (sd->sd_src_nid != LNET_NID_ANY) ? sd->sd_src_nid :
2114                 (sd->sd_best_ni != NULL) ? sd->sd_best_ni->ni_nid :
2115                 LNET_NID_ANY;
2116         int best_lpn_healthv = 0;
2117         __u32 best_lpn_sel_prio = LNET_MAX_SELECTION_PRIORITY;
2118
2119         CDEBUG(D_NET, "using src nid %s for route restriction\n",
2120                libcfs_nid2str(src_nid));
2121
2122         /* If a router nid was specified then we are replying to a GET or
2123          * sending an ACK. In this case we use the gateway associated with the
2124          * specified router nid.
2125          */
2126         if (sd->sd_rtr_nid != LNET_NID_ANY) {
2127                 gwni = lnet_find_peer_ni_locked(sd->sd_rtr_nid);
2128                 if (gwni) {
2129                         gw = gwni->lpni_peer_net->lpn_peer;
2130                         lnet_peer_ni_decref_locked(gwni);
2131                         if (gw->lp_rtr_refcount) {
2132                                 local_lnet = LNET_NIDNET(sd->sd_rtr_nid);
2133                                 route_found = true;
2134                         }
2135                 } else {
2136                         CWARN("No peer NI for gateway %s. Attempting to find an alternative route.\n",
2137                                libcfs_nid2str(sd->sd_rtr_nid));
2138                 }
2139         }
2140
2141         if (!route_found) {
2142                 if (sd->sd_msg->msg_routing) {
2143                         /* If I'm routing this message then I need to find the
2144                          * next hop based on the destination NID
2145                          */
2146                         best_rnet = lnet_find_rnet_locked(LNET_NIDNET(sd->sd_dst_nid));
2147                         if (!best_rnet) {
2148                                 CERROR("Unable to route message to %s - Route table may be misconfigured\n",
2149                                        libcfs_nid2str(sd->sd_dst_nid));
2150                                 return -EHOSTUNREACH;
2151                         }
2152                 } else {
2153                         /* we've already looked up the initial lpni using
2154                          * dst_nid
2155                          */
2156                         lpni = sd->sd_best_lpni;
2157                         /* the peer tree must be in existence */
2158                         LASSERT(lpni && lpni->lpni_peer_net &&
2159                                 lpni->lpni_peer_net->lpn_peer);
2160                         lp = lpni->lpni_peer_net->lpn_peer;
2161
2162                         list_for_each_entry(lpn, &lp->lp_peer_nets, lpn_peer_nets) {
2163                                 /* is this remote network reachable?  */
2164                                 rnet = lnet_find_rnet_locked(lpn->lpn_net_id);
2165                                 if (!rnet)
2166                                         continue;
2167
2168                                 if (!best_lpn) {
2169                                         best_lpn = lpn;
2170                                         best_rnet = rnet;
2171                                 }
2172
2173                                 /* select the preferred peer net */
2174                                 if (best_lpn_healthv > lpn->lpn_healthv)
2175                                         continue;
2176                                 else if (best_lpn_healthv < lpn->lpn_healthv)
2177                                         goto use_lpn;
2178
2179                                 if (best_lpn_sel_prio < lpn->lpn_sel_priority)
2180                                         continue;
2181                                 else if (best_lpn_sel_prio > lpn->lpn_sel_priority)
2182                                         goto use_lpn;
2183
2184                                 if (best_lpn->lpn_seq <= lpn->lpn_seq)
2185                                         continue;
2186 use_lpn:
2187                                 best_lpn_healthv = lpn->lpn_healthv;
2188                                 best_lpn_sel_prio = lpn->lpn_sel_priority;
2189                                 best_lpn = lpn;
2190                                 best_rnet = rnet;
2191                         }
2192
2193                         if (!best_lpn) {
2194                                 CERROR("peer %s has no available nets\n",
2195                                        libcfs_nid2str(sd->sd_dst_nid));
2196                                 return -EHOSTUNREACH;
2197                         }
2198
2199                         sd->sd_best_lpni = lnet_find_best_lpni(sd->sd_best_ni,
2200                                                                sd->sd_dst_nid,
2201                                                                lp,
2202                                                                best_lpn->lpn_net_id);
2203                         if (!sd->sd_best_lpni) {
2204                                 CERROR("peer %s is unreachable\n",
2205                                        libcfs_nid2str(sd->sd_dst_nid));
2206                                 return -EHOSTUNREACH;
2207                         }
2208
2209                         /* We're attempting to round robin over the remote peer
2210                          * NI's so update the final destination we selected
2211                          */
2212                         sd->sd_final_dst_lpni = sd->sd_best_lpni;
2213
2214                         /* Increment the sequence number of the remote lpni so
2215                          * we can round robin over the different interfaces of
2216                          * the remote lpni
2217                          */
2218                         sd->sd_best_lpni->lpni_seq++;
2219                 }
2220
2221                 /*
2222                  * find the best route. Restrict the selection on the net of the
2223                  * local NI if we've already picked the local NI to send from.
2224                  * Otherwise, let's pick any route we can find and then find
2225                  * a local NI we can reach the route's gateway on. Any route we
2226                  * select will be reachable by virtue of the restriction we have
2227                  * when adding a route.
2228                  */
2229                 best_route = lnet_find_route_locked(best_rnet,
2230                                                     LNET_NIDNET(src_nid),
2231                                                     sd->sd_best_lpni,
2232                                                     &last_route, &gwni);
2233
2234                 if (!best_route) {
2235                         CERROR("no route to %s from %s\n",
2236                                libcfs_nid2str(dst_nid),
2237                                libcfs_nid2str(src_nid));
2238                         return -EHOSTUNREACH;
2239                 }
2240
2241                 if (!gwni) {
2242                         CERROR("Internal Error. Route expected to %s from %s\n",
2243                                libcfs_nid2str(dst_nid),
2244                                libcfs_nid2str(src_nid));
2245                         return -EFAULT;
2246                 }
2247
2248                 gw = best_route->lr_gateway;
2249                 LASSERT(gw == gwni->lpni_peer_net->lpn_peer);
2250                 local_lnet = best_route->lr_lnet;
2251         }
2252
2253         /*
2254          * Discover this gateway if it hasn't already been discovered.
2255          * This means we might delay the message until discovery has
2256          * completed
2257          */
2258         sd->sd_msg->msg_src_nid_param = sd->sd_src_nid;
2259         rc = lnet_initiate_peer_discovery(gwni, sd->sd_msg, sd->sd_cpt);
2260         if (rc)
2261                 return rc;
2262
2263         if (!sd->sd_best_ni)
2264                 sd->sd_best_ni = lnet_find_best_ni_on_spec_net(NULL, gw,
2265                                         lnet_peer_get_net_locked(gw,
2266                                                                  local_lnet),
2267                                         sd->sd_md_cpt);
2268
2269         if (!sd->sd_best_ni) {
2270                 CERROR("Internal Error. Expected local ni on %s but non found :%s\n",
2271                        libcfs_net2str(local_lnet),
2272                        libcfs_nid2str(sd->sd_src_nid));
2273                 return -EFAULT;
2274         }
2275
2276         *gw_lpni = gwni;
2277         *gw_peer = gw;
2278
2279         /*
2280          * increment the sequence numbers since now we're sure we're
2281          * going to use this path
2282          */
2283         if (sd->sd_rtr_nid == LNET_NID_ANY) {
2284                 LASSERT(best_route && last_route);
2285                 best_route->lr_seq = last_route->lr_seq + 1;
2286                 if (best_lpn)
2287                         best_lpn->lpn_seq++;
2288         }
2289
2290         return 0;
2291 }
2292
2293 /*
2294  * Handle two cases:
2295  *
2296  * Case 1:
2297  *  Source specified
2298  *  Remote destination
2299  *  Non-MR destination
2300  *
2301  * Case 2:
2302  *  Source specified
2303  *  Remote destination
2304  *  MR destination
2305  *
2306  * The handling of these two cases is similar. Even though the destination
2307  * can be MR or non-MR, we'll deal directly with the router.
2308  */
2309 static int
2310 lnet_handle_spec_router_dst(struct lnet_send_data *sd)
2311 {
2312         int rc;
2313         struct lnet_peer_ni *gw_lpni = NULL;
2314         struct lnet_peer *gw_peer = NULL;
2315
2316         /* find local NI */
2317         sd->sd_best_ni = lnet_nid2ni_locked(sd->sd_src_nid, sd->sd_cpt);
2318         if (!sd->sd_best_ni) {
2319                 CERROR("Can't send to %s: src %s is not a "
2320                        "local nid\n", libcfs_nid2str(sd->sd_dst_nid),
2321                                 libcfs_nid2str(sd->sd_src_nid));
2322                 return -EINVAL;
2323         }
2324
2325         rc = lnet_handle_find_routed_path(sd, sd->sd_dst_nid, &gw_lpni,
2326                                      &gw_peer);
2327         if (rc)
2328                 return rc;
2329
2330         if (sd->sd_send_case & NMR_DST)
2331                 /*
2332                  * since the final destination is non-MR let's set its preferred
2333                  * NID before we send
2334                  */
2335                 lnet_set_non_mr_pref_nid(sd->sd_best_lpni, sd->sd_best_ni,
2336                                          sd->sd_msg);
2337
2338         /*
2339          * We're going to send to the gw found so let's set its
2340          * info
2341          */
2342         sd->sd_peer = gw_peer;
2343         sd->sd_best_lpni = gw_lpni;
2344
2345         return lnet_handle_send(sd);
2346 }
2347
2348 struct lnet_ni *
2349 lnet_find_best_ni_on_local_net(struct lnet_peer *peer, int md_cpt,
2350                                bool discovery)
2351 {
2352         struct lnet_peer_net *lpn = NULL;
2353         struct lnet_peer_net *best_lpn = NULL;
2354         struct lnet_net *net = NULL;
2355         struct lnet_net *best_net = NULL;
2356         struct lnet_ni *best_ni = NULL;
2357         int best_lpn_healthv = 0;
2358         int best_net_healthv = 0;
2359         int net_healthv;
2360         __u32 best_lpn_sel_prio = LNET_MAX_SELECTION_PRIORITY;
2361         __u32 lpn_sel_prio;
2362         __u32 best_net_sel_prio = LNET_MAX_SELECTION_PRIORITY;
2363         __u32 net_sel_prio;
2364         bool exit = false;
2365
2366         /*
2367          * The peer can have multiple interfaces, some of them can be on
2368          * the local network and others on a routed network. We should
2369          * prefer the local network. However if the local network is not
2370          * available then we need to try the routed network
2371          */
2372
2373         /* go through all the peer nets and find the best_ni */
2374         list_for_each_entry(lpn, &peer->lp_peer_nets, lpn_peer_nets) {
2375                 /*
2376                  * The peer's list of nets can contain non-local nets. We
2377                  * want to only examine the local ones.
2378                  */
2379                 net = lnet_get_net_locked(lpn->lpn_net_id);
2380                 if (!net)
2381                         continue;
2382
2383                 lpn_sel_prio = lpn->lpn_sel_priority;
2384                 net_healthv = lnet_get_net_healthv_locked(net);
2385                 net_sel_prio = net->net_sel_priority;
2386
2387                 /*
2388                  * if this is a discovery message and lp_disc_net_id is
2389                  * specified then use that net to send the discovery on.
2390                  */
2391                 if (peer->lp_disc_net_id == lpn->lpn_net_id &&
2392                     discovery) {
2393                         exit = true;
2394                         goto select_lpn;
2395                 }
2396
2397                 if (!best_lpn)
2398                         goto select_lpn;
2399
2400                 /* always select the lpn with the best health */
2401                 if (best_lpn_healthv > lpn->lpn_healthv)
2402                         continue;
2403                 else if (best_lpn_healthv < lpn->lpn_healthv)
2404                         goto select_lpn;
2405
2406                 /* select the preferred peer and local nets */
2407                 if (best_lpn_sel_prio < lpn_sel_prio)
2408                         continue;
2409                 else if (best_lpn_sel_prio > lpn_sel_prio)
2410                         goto select_lpn;
2411
2412                 if (best_net_healthv > net_healthv)
2413                         continue;
2414                 else if (best_net_healthv < net_healthv)
2415                         goto select_lpn;
2416
2417                 if (best_net_sel_prio < net_sel_prio)
2418                         continue;
2419                 else if (best_net_sel_prio > net_sel_prio)
2420                         goto select_lpn;
2421
2422                 if (best_lpn->lpn_seq < lpn->lpn_seq)
2423                         continue;
2424                 else if (best_lpn->lpn_seq > lpn->lpn_seq)
2425                         goto select_lpn;
2426
2427                 /* round robin over the local networks */
2428                 if (best_net->net_seq <= net->net_seq)
2429                         continue;
2430
2431 select_lpn:
2432                 best_net_healthv = net_healthv;
2433                 best_net_sel_prio = net_sel_prio;
2434                 best_lpn_healthv = lpn->lpn_healthv;
2435                 best_lpn_sel_prio = lpn_sel_prio;
2436                 best_lpn = lpn;
2437                 best_net = net;
2438
2439                 if (exit)
2440                         break;
2441         }
2442
2443         if (best_lpn) {
2444                 /* Select the best NI on the same net as best_lpn chosen
2445                  * above
2446                  */
2447                 best_ni = lnet_find_best_ni_on_spec_net(NULL, peer,
2448                                                         best_lpn, md_cpt);
2449         }
2450
2451         return best_ni;
2452 }
2453
2454 static struct lnet_ni *
2455 lnet_find_existing_preferred_best_ni(struct lnet_peer_ni *lpni, int cpt)
2456 {
2457         struct lnet_ni *best_ni = NULL;
2458         struct lnet_peer_net *peer_net = lpni->lpni_peer_net;
2459         struct lnet_peer_ni *lpni_entry;
2460
2461         /*
2462          * We must use a consistent source address when sending to a
2463          * non-MR peer. However, a non-MR peer can have multiple NIDs
2464          * on multiple networks, and we may even need to talk to this
2465          * peer on multiple networks -- certain types of
2466          * load-balancing configuration do this.
2467          *
2468          * So we need to pick the NI the peer prefers for this
2469          * particular network.
2470          */
2471         LASSERT(peer_net);
2472         list_for_each_entry(lpni_entry, &peer_net->lpn_peer_nis,
2473                             lpni_peer_nis) {
2474                 if (lpni_entry->lpni_pref_nnids == 0)
2475                         continue;
2476                 LASSERT(lpni_entry->lpni_pref_nnids == 1);
2477                 best_ni = lnet_nid2ni_locked(lpni_entry->lpni_pref.nid, cpt);
2478                 break;
2479         }
2480
2481         return best_ni;
2482 }
2483
2484 /* Prerequisite: sd->sd_peer and sd->sd_best_lpni should be set */
2485 static int
2486 lnet_select_preferred_best_ni(struct lnet_send_data *sd)
2487 {
2488         struct lnet_ni *best_ni = NULL;
2489         struct lnet_peer_ni *best_lpni = sd->sd_best_lpni;
2490
2491         /*
2492          * We must use a consistent source address when sending to a
2493          * non-MR peer. However, a non-MR peer can have multiple NIDs
2494          * on multiple networks, and we may even need to talk to this
2495          * peer on multiple networks -- certain types of
2496          * load-balancing configuration do this.
2497          *
2498          * So we need to pick the NI the peer prefers for this
2499          * particular network.
2500          */
2501
2502         best_ni = lnet_find_existing_preferred_best_ni(sd->sd_best_lpni,
2503                                                        sd->sd_cpt);
2504
2505         /* if best_ni is still not set just pick one */
2506         if (!best_ni) {
2507                 best_ni =
2508                   lnet_find_best_ni_on_spec_net(NULL, sd->sd_peer,
2509                                                 sd->sd_best_lpni->lpni_peer_net,
2510                                                 sd->sd_md_cpt);
2511                 /* If there is no best_ni we don't have a route */
2512                 if (!best_ni) {
2513                         CERROR("no path to %s from net %s\n",
2514                                 libcfs_nid2str(best_lpni->lpni_nid),
2515                                 libcfs_net2str(best_lpni->lpni_net->net_id));
2516                         return -EHOSTUNREACH;
2517                 }
2518         }
2519
2520         sd->sd_best_ni = best_ni;
2521
2522         /* Set preferred NI if necessary. */
2523         lnet_set_non_mr_pref_nid(sd->sd_best_lpni, sd->sd_best_ni, sd->sd_msg);
2524
2525         return 0;
2526 }
2527
2528
2529 /*
2530  * Source not specified
2531  * Local destination
2532  * Non-MR Peer
2533  *
2534  * always use the same source NID for NMR peers
2535  * If we've talked to that peer before then we already have a preferred
2536  * source NI associated with it. Otherwise, we select a preferred local NI
2537  * and store it in the peer
2538  */
2539 static int
2540 lnet_handle_any_local_nmr_dst(struct lnet_send_data *sd)
2541 {
2542         int rc = 0;
2543
2544         /* sd->sd_best_lpni is already set to the final destination */
2545
2546         /*
2547          * At this point we should've created the peer ni and peer. If we
2548          * can't find it, then something went wrong. Instead of assert
2549          * output a relevant message and fail the send
2550          */
2551         if (!sd->sd_best_lpni) {
2552                 CERROR("Internal fault. Unable to send msg %s to %s. "
2553                        "NID not known\n",
2554                        lnet_msgtyp2str(sd->sd_msg->msg_type),
2555                        libcfs_nid2str(sd->sd_dst_nid));
2556                 return -EFAULT;
2557         }
2558
2559         if (sd->sd_msg->msg_routing) {
2560                 /* If I'm forwarding this message then I can choose any NI
2561                  * on the destination peer net
2562                  */
2563                 sd->sd_best_ni = lnet_find_best_ni_on_spec_net(NULL,
2564                                                                sd->sd_peer,
2565                                                                sd->sd_best_lpni->lpni_peer_net,
2566                                                                sd->sd_md_cpt);
2567                 if (!sd->sd_best_ni) {
2568                         CERROR("Unable to forward message to %s. No local NI available\n",
2569                                libcfs_nid2str(sd->sd_dst_nid));
2570                         rc = -EHOSTUNREACH;
2571                 }
2572         } else
2573                 rc = lnet_select_preferred_best_ni(sd);
2574
2575         if (!rc)
2576                 rc = lnet_handle_send(sd);
2577
2578         return rc;
2579 }
2580
2581 static int
2582 lnet_handle_any_mr_dsta(struct lnet_send_data *sd)
2583 {
2584         /*
2585          * NOTE we've already handled the remote peer case. So we only
2586          * need to worry about the local case here.
2587          *
2588          * if we're sending a response, ACK or reply, we need to send it
2589          * to the destination NID given to us. At this point we already
2590          * have the peer_ni we're suppose to send to, so just find the
2591          * best_ni on the peer net and use that. Since we're sending to an
2592          * MR peer then we can just run the selection algorithm on our
2593          * local NIs and pick the best one.
2594          */
2595         if (sd->sd_send_case & SND_RESP) {
2596                 sd->sd_best_ni =
2597                   lnet_find_best_ni_on_spec_net(NULL, sd->sd_peer,
2598                                                 sd->sd_best_lpni->lpni_peer_net,
2599                                                 sd->sd_md_cpt);
2600
2601                 if (!sd->sd_best_ni) {
2602                         /*
2603                          * We're not going to deal with not able to send
2604                          * a response to the provided final destination
2605                          */
2606                         CERROR("Can't send response to %s. "
2607                                "No local NI available\n",
2608                                 libcfs_nid2str(sd->sd_dst_nid));
2609                         return -EHOSTUNREACH;
2610                 }
2611
2612                 return lnet_handle_send(sd);
2613         }
2614
2615         /*
2616          * If we get here that means we're sending a fresh request, PUT or
2617          * GET, so we need to run our standard selection algorithm.
2618          * First find the best local interface that's on any of the peer's
2619          * networks.
2620          */
2621         sd->sd_best_ni = lnet_find_best_ni_on_local_net(sd->sd_peer,
2622                                         sd->sd_md_cpt,
2623                                         lnet_msg_discovery(sd->sd_msg));
2624         if (sd->sd_best_ni) {
2625                 sd->sd_best_lpni =
2626                   lnet_find_best_lpni(sd->sd_best_ni, sd->sd_dst_nid,
2627                                       sd->sd_peer,
2628                                       sd->sd_best_ni->ni_net->net_id);
2629
2630                 /*
2631                  * if we're successful in selecting a peer_ni on the local
2632                  * network, then send to it. Otherwise fall through and
2633                  * try and see if we can reach it over another routed
2634                  * network
2635                  */
2636                 if (sd->sd_best_lpni &&
2637                     sd->sd_best_lpni->lpni_nid == the_lnet.ln_loni->ni_nid) {
2638                         /*
2639                          * in case we initially started with a routed
2640                          * destination, let's reset to local
2641                          */
2642                         sd->sd_send_case &= ~REMOTE_DST;
2643                         sd->sd_send_case |= LOCAL_DST;
2644                         return lnet_handle_lo_send(sd);
2645                 } else if (sd->sd_best_lpni) {
2646                         /*
2647                          * in case we initially started with a routed
2648                          * destination, let's reset to local
2649                          */
2650                         sd->sd_send_case &= ~REMOTE_DST;
2651                         sd->sd_send_case |= LOCAL_DST;
2652                         return lnet_handle_send(sd);
2653                 }
2654
2655                 CERROR("Internal Error. Expected to have a best_lpni: "
2656                        "%s -> %s\n",
2657                        libcfs_nid2str(sd->sd_src_nid),
2658                        libcfs_nid2str(sd->sd_dst_nid));
2659
2660                 return -EFAULT;
2661         }
2662
2663         /*
2664          * Peer doesn't have a local network. Let's see if there is
2665          * a remote network we can reach it on.
2666          */
2667         return PASS_THROUGH;
2668 }
2669
2670 /*
2671  * Case 1:
2672  *      Source NID not specified
2673  *      Local destination
2674  *      MR peer
2675  *
2676  * Case 2:
2677  *      Source NID not speified
2678  *      Remote destination
2679  *      MR peer
2680  *
2681  * In both of these cases if we're sending a response, ACK or REPLY, then
2682  * we need to send to the destination NID provided.
2683  *
2684  * In the remote case let's deal with MR routers.
2685  *
2686  */
2687
2688 static int
2689 lnet_handle_any_mr_dst(struct lnet_send_data *sd)
2690 {
2691         int rc = 0;
2692         struct lnet_peer *gw_peer = NULL;
2693         struct lnet_peer_ni *gw_lpni = NULL;
2694
2695         /*
2696          * handle sending a response to a remote peer here so we don't
2697          * have to worry about it if we hit lnet_handle_any_mr_dsta()
2698          */
2699         if (sd->sd_send_case & REMOTE_DST &&
2700             sd->sd_send_case & SND_RESP) {
2701                 struct lnet_peer_ni *gw;
2702                 struct lnet_peer *gw_peer;
2703
2704                 rc = lnet_handle_find_routed_path(sd, sd->sd_dst_nid, &gw,
2705                                                   &gw_peer);
2706                 if (rc < 0) {
2707                         CERROR("Can't send response to %s. "
2708                                "No route available\n",
2709                                 libcfs_nid2str(sd->sd_dst_nid));
2710                         return -EHOSTUNREACH;
2711                 } else if (rc > 0) {
2712                         return rc;
2713                 }
2714
2715                 sd->sd_best_lpni = gw;
2716                 sd->sd_peer = gw_peer;
2717
2718                 return lnet_handle_send(sd);
2719         }
2720
2721         /*
2722          * Even though the NID for the peer might not be on a local network,
2723          * since the peer is MR there could be other interfaces on the
2724          * local network. In that case we'd still like to prefer the local
2725          * network over the routed network. If we're unable to do that
2726          * then we select the best router among the different routed networks,
2727          * and if the router is MR then we can deal with it as such.
2728          */
2729         rc = lnet_handle_any_mr_dsta(sd);
2730         if (rc != PASS_THROUGH)
2731                 return rc;
2732
2733         /*
2734          * Now that we must route to the destination, we must consider the
2735          * MR case, where the destination has multiple interfaces, some of
2736          * which we can route to and others we do not. For this reason we
2737          * need to select the destination which we can route to and if
2738          * there are multiple, we need to round robin.
2739          */
2740         rc = lnet_handle_find_routed_path(sd, sd->sd_dst_nid, &gw_lpni,
2741                                           &gw_peer);
2742         if (rc)
2743                 return rc;
2744
2745         sd->sd_send_case &= ~LOCAL_DST;
2746         sd->sd_send_case |= REMOTE_DST;
2747
2748         sd->sd_peer = gw_peer;
2749         sd->sd_best_lpni = gw_lpni;
2750
2751         return lnet_handle_send(sd);
2752 }
2753
2754 /*
2755  * Source not specified
2756  * Remote destination
2757  * Non-MR peer
2758  *
2759  * Must send to the specified peer NID using the same source NID that
2760  * we've used before. If it's the first time to talk to that peer then
2761  * find the source NI and assign it as preferred to that peer
2762  */
2763 static int
2764 lnet_handle_any_router_nmr_dst(struct lnet_send_data *sd)
2765 {
2766         int rc;
2767         struct lnet_peer_ni *gw_lpni = NULL;
2768         struct lnet_peer *gw_peer = NULL;
2769
2770         /*
2771          * Let's see if we have a preferred NI to talk to this NMR peer
2772          */
2773         sd->sd_best_ni = lnet_find_existing_preferred_best_ni(sd->sd_best_lpni,
2774                                                               sd->sd_cpt);
2775
2776         /*
2777          * find the router and that'll find the best NI if we didn't find
2778          * it already.
2779          */
2780         rc = lnet_handle_find_routed_path(sd, sd->sd_dst_nid, &gw_lpni,
2781                                           &gw_peer);
2782         if (rc)
2783                 return rc;
2784
2785         /*
2786          * set the best_ni we've chosen as the preferred one for
2787          * this peer
2788          */
2789         lnet_set_non_mr_pref_nid(sd->sd_best_lpni, sd->sd_best_ni, sd->sd_msg);
2790
2791         /* we'll be sending to the gw */
2792         sd->sd_best_lpni = gw_lpni;
2793         sd->sd_peer = gw_peer;
2794
2795         return lnet_handle_send(sd);
2796 }
2797
2798 static int
2799 lnet_handle_send_case_locked(struct lnet_send_data *sd)
2800 {
2801         /*
2802          * turn off the SND_RESP bit.
2803          * It will be checked in the case handling
2804          */
2805         __u32 send_case = sd->sd_send_case &= ~SND_RESP ;
2806
2807         CDEBUG(D_NET, "Source %s%s to %s %s %s destination\n",
2808                 (send_case & SRC_SPEC) ? "Specified: " : "ANY",
2809                 (send_case & SRC_SPEC) ? libcfs_nid2str(sd->sd_src_nid) : "",
2810                 (send_case & MR_DST) ? "MR: " : "NMR: ",
2811                 libcfs_nid2str(sd->sd_dst_nid),
2812                 (send_case & LOCAL_DST) ? "local" : "routed");
2813
2814         switch (send_case) {
2815         /*
2816          * For all cases where the source is specified, we should always
2817          * use the destination NID, whether it's an MR destination or not,
2818          * since we're continuing a series of related messages for the
2819          * same RPC
2820          */
2821         case SRC_SPEC_LOCAL_NMR_DST:
2822                 return lnet_handle_spec_local_nmr_dst(sd);
2823         case SRC_SPEC_LOCAL_MR_DST:
2824                 return lnet_handle_spec_local_mr_dst(sd);
2825         case SRC_SPEC_ROUTER_NMR_DST:
2826         case SRC_SPEC_ROUTER_MR_DST:
2827                 return lnet_handle_spec_router_dst(sd);
2828         case SRC_ANY_LOCAL_NMR_DST:
2829                 return lnet_handle_any_local_nmr_dst(sd);
2830         case SRC_ANY_LOCAL_MR_DST:
2831         case SRC_ANY_ROUTER_MR_DST:
2832                 return lnet_handle_any_mr_dst(sd);
2833         case SRC_ANY_ROUTER_NMR_DST:
2834                 return lnet_handle_any_router_nmr_dst(sd);
2835         default:
2836                 CERROR("Unknown send case\n");
2837                 return -1;
2838         }
2839 }
2840
2841 static int
2842 lnet_select_pathway(lnet_nid_t src_nid, lnet_nid_t dst_nid,
2843                     struct lnet_msg *msg, lnet_nid_t rtr_nid)
2844 {
2845         struct lnet_peer_ni *lpni;
2846         struct lnet_peer *peer;
2847         struct lnet_send_data send_data;
2848         int cpt, rc;
2849         int md_cpt;
2850         __u32 send_case = 0;
2851         bool final_hop;
2852         bool mr_forwarding_allowed;
2853
2854         memset(&send_data, 0, sizeof(send_data));
2855
2856         /*
2857          * get an initial CPT to use for locking. The idea here is not to
2858          * serialize the calls to select_pathway, so that as many
2859          * operations can run concurrently as possible. To do that we use
2860          * the CPT where this call is being executed. Later on when we
2861          * determine the CPT to use in lnet_message_commit, we switch the
2862          * lock and check if there was any configuration change.  If none,
2863          * then we proceed, if there is, then we restart the operation.
2864          */
2865         cpt = lnet_net_lock_current();
2866
2867         md_cpt = lnet_cpt_of_md(msg->msg_md, msg->msg_offset);
2868         if (md_cpt == CFS_CPT_ANY)
2869                 md_cpt = cpt;
2870
2871 again:
2872
2873         /*
2874          * If we're being asked to send to the loopback interface, there
2875          * is no need to go through any selection. We can just shortcut
2876          * the entire process and send over lolnd
2877          */
2878         send_data.sd_msg = msg;
2879         send_data.sd_cpt = cpt;
2880         if (dst_nid == LNET_NID_LO_0) {
2881                 rc = lnet_handle_lo_send(&send_data);
2882                 lnet_net_unlock(cpt);
2883                 return rc;
2884         }
2885
2886         /*
2887          * find an existing peer_ni, or create one and mark it as having been
2888          * created due to network traffic. This call will create the
2889          * peer->peer_net->peer_ni tree.
2890          */
2891         lpni = lnet_nid2peerni_locked(dst_nid, LNET_NID_ANY, cpt);
2892         if (IS_ERR(lpni)) {
2893                 lnet_net_unlock(cpt);
2894                 return PTR_ERR(lpni);
2895         }
2896
2897         /*
2898          * Cache the original src_nid and rtr_nid. If we need to resend the
2899          * message then we'll need to know whether the src_nid was originally
2900          * specified for this message. If it was originally specified,
2901          * then we need to keep using the same src_nid since it's
2902          * continuing the same sequence of messages. Similarly, rtr_nid will
2903          * affect our choice of next hop.
2904          */
2905         msg->msg_src_nid_param = src_nid;
2906         msg->msg_rtr_nid_param = rtr_nid;
2907
2908         /*
2909          * If necessary, perform discovery on the peer that owns this peer_ni.
2910          * Note, this can result in the ownership of this peer_ni changing
2911          * to another peer object.
2912          */
2913         rc = lnet_initiate_peer_discovery(lpni, msg, cpt);
2914         if (rc) {
2915                 lnet_peer_ni_decref_locked(lpni);
2916                 lnet_net_unlock(cpt);
2917                 return rc;
2918         }
2919         lnet_peer_ni_decref_locked(lpni);
2920
2921         peer = lpni->lpni_peer_net->lpn_peer;
2922
2923         /*
2924          * Identify the different send cases
2925          */
2926         if (src_nid == LNET_NID_ANY)
2927                 send_case |= SRC_ANY;
2928         else
2929                 send_case |= SRC_SPEC;
2930
2931         if (lnet_get_net_locked(LNET_NIDNET(dst_nid)))
2932                 send_case |= LOCAL_DST;
2933         else
2934                 send_case |= REMOTE_DST;
2935
2936         final_hop = false;
2937         if (msg->msg_routing && (send_case & LOCAL_DST))
2938                 final_hop = true;
2939
2940         /* Determine whether to allow MR forwarding for this message.
2941          * NB: MR forwarding is allowed if the message originator and the
2942          * destination are both MR capable, and the destination lpni that was
2943          * originally chosen by the originator is unhealthy or down.
2944          * We check the MR capability of the destination further below
2945          */
2946         mr_forwarding_allowed = false;
2947         if (final_hop) {
2948                 struct lnet_peer *src_lp;
2949                 struct lnet_peer_ni *src_lpni;
2950
2951                 src_lpni = lnet_nid2peerni_locked(msg->msg_hdr.src_nid,
2952                                                   LNET_NID_ANY, cpt);
2953                 /* We don't fail the send if we hit any errors here. We'll just
2954                  * try to send it via non-multi-rail criteria
2955                  */
2956                 if (!IS_ERR(src_lpni)) {
2957                         /* Drop ref taken by lnet_nid2peerni_locked() */
2958                         lnet_peer_ni_decref_locked(src_lpni);
2959                         src_lp = lpni->lpni_peer_net->lpn_peer;
2960                         if (lnet_peer_is_multi_rail(src_lp) &&
2961                             !lnet_is_peer_ni_alive(lpni))
2962                                 mr_forwarding_allowed = true;
2963
2964                 }
2965                 CDEBUG(D_NET, "msg %p MR forwarding %s\n", msg,
2966                        mr_forwarding_allowed ? "allowed" : "not allowed");
2967         }
2968
2969         /*
2970          * Deal with the peer as NMR in the following cases:
2971          * 1. the peer is NMR
2972          * 2. We're trying to recover a specific peer NI
2973          * 3. I'm a router sending to the final destination and MR forwarding is
2974          *    not allowed for this message (as determined above).
2975          *    In this case the source of the message would've
2976          *    already selected the final destination so my job
2977          *    is to honor the selection.
2978          */
2979         if (!lnet_peer_is_multi_rail(peer) || msg->msg_recovery ||
2980             (final_hop && !mr_forwarding_allowed))
2981                 send_case |= NMR_DST;
2982         else
2983                 send_case |= MR_DST;
2984
2985         if (lnet_msg_is_response(msg))
2986                 send_case |= SND_RESP;
2987
2988         /* assign parameters to the send_data */
2989         send_data.sd_rtr_nid = rtr_nid;
2990         send_data.sd_src_nid = src_nid;
2991         send_data.sd_dst_nid = dst_nid;
2992         send_data.sd_best_lpni = lpni;
2993         /*
2994          * keep a pointer to the final destination in case we're going to
2995          * route, so we'll need to access it later
2996          */
2997         send_data.sd_final_dst_lpni = lpni;
2998         send_data.sd_peer = peer;
2999         send_data.sd_md_cpt = md_cpt;
3000         send_data.sd_send_case = send_case;
3001
3002         rc = lnet_handle_send_case_locked(&send_data);
3003
3004         /*
3005          * Update the local cpt since send_data.sd_cpt might've been
3006          * updated as a result of calling lnet_handle_send_case_locked().
3007          */
3008         cpt = send_data.sd_cpt;
3009
3010         if (rc == REPEAT_SEND)
3011                 goto again;
3012
3013         lnet_net_unlock(cpt);
3014
3015         return rc;
3016 }
3017
3018 int
3019 lnet_send(lnet_nid_t src_nid, struct lnet_msg *msg, lnet_nid_t rtr_nid)
3020 {
3021         lnet_nid_t              dst_nid = msg->msg_target.nid;
3022         int                     rc;
3023
3024         /*
3025          * NB: rtr_nid is set to LNET_NID_ANY for all current use-cases,
3026          * but we might want to use pre-determined router for ACK/REPLY
3027          * in the future
3028          */
3029         /* NB: ni != NULL == interface pre-determined (ACK/REPLY) */
3030         LASSERT(msg->msg_txpeer == NULL);
3031         LASSERT(msg->msg_txni == NULL);
3032         LASSERT(!msg->msg_sending);
3033         LASSERT(!msg->msg_target_is_router);
3034         LASSERT(!msg->msg_receiving);
3035
3036         msg->msg_sending = 1;
3037
3038         LASSERT(!msg->msg_tx_committed);
3039
3040         rc = lnet_select_pathway(src_nid, dst_nid, msg, rtr_nid);
3041         if (rc < 0) {
3042                 if (rc == -EHOSTUNREACH)
3043                         msg->msg_health_status = LNET_MSG_STATUS_REMOTE_ERROR;
3044                 else
3045                         msg->msg_health_status = LNET_MSG_STATUS_LOCAL_ERROR;
3046                 return rc;
3047         }
3048
3049         if (rc == LNET_CREDIT_OK)
3050                 lnet_ni_send(msg->msg_txni, msg);
3051
3052         /* rc == LNET_CREDIT_OK or LNET_CREDIT_WAIT or LNET_DC_WAIT */
3053         return 0;
3054 }
3055
3056 enum lnet_mt_event_type {
3057         MT_TYPE_LOCAL_NI = 0,
3058         MT_TYPE_PEER_NI
3059 };
3060
3061 struct lnet_mt_event_info {
3062         enum lnet_mt_event_type mt_type;
3063         lnet_nid_t mt_nid;
3064 };
3065
3066 /* called with res_lock held */
3067 void
3068 lnet_detach_rsp_tracker(struct lnet_libmd *md, int cpt)
3069 {
3070         struct lnet_rsp_tracker *rspt;
3071
3072         /*
3073          * msg has a refcount on the MD so the MD is not going away.
3074          * The rspt queue for the cpt is protected by
3075          * the lnet_net_lock(cpt). cpt is the cpt of the MD cookie.
3076          */
3077         if (!md->md_rspt_ptr)
3078                 return;
3079
3080         rspt = md->md_rspt_ptr;
3081
3082         /* debug code */
3083         LASSERT(rspt->rspt_cpt == cpt);
3084
3085         md->md_rspt_ptr = NULL;
3086
3087         if (LNetMDHandleIsInvalid(rspt->rspt_mdh)) {
3088                 /*
3089                  * The monitor thread has invalidated this handle because the
3090                  * response timed out, but it failed to lookup the MD. That
3091                  * means this response tracker is on the zombie list. We can
3092                  * safely remove it under the resource lock (held by caller) and
3093                  * free the response tracker block.
3094                  */
3095                 list_del(&rspt->rspt_on_list);
3096                 lnet_rspt_free(rspt, cpt);
3097         } else {
3098                 /*
3099                  * invalidate the handle to indicate that a response has been
3100                  * received, which will then lead the monitor thread to clean up
3101                  * the rspt block.
3102                  */
3103                 LNetInvalidateMDHandle(&rspt->rspt_mdh);
3104         }
3105 }
3106
3107 void
3108 lnet_clean_zombie_rstqs(void)
3109 {
3110         struct lnet_rsp_tracker *rspt, *tmp;
3111         int i;
3112
3113         cfs_cpt_for_each(i, lnet_cpt_table()) {
3114                 list_for_each_entry_safe(rspt, tmp,
3115                                          the_lnet.ln_mt_zombie_rstqs[i],
3116                                          rspt_on_list) {
3117                         list_del(&rspt->rspt_on_list);
3118                         lnet_rspt_free(rspt, i);
3119                 }
3120         }
3121
3122         cfs_percpt_free(the_lnet.ln_mt_zombie_rstqs);
3123 }
3124
3125 static void
3126 lnet_finalize_expired_responses(void)
3127 {
3128         struct lnet_libmd *md;
3129         struct lnet_rsp_tracker *rspt, *tmp;
3130         ktime_t now;
3131         int i;
3132
3133         if (the_lnet.ln_mt_rstq == NULL)
3134                 return;
3135
3136         cfs_cpt_for_each(i, lnet_cpt_table()) {
3137                 LIST_HEAD(local_queue);
3138
3139                 lnet_net_lock(i);
3140                 if (!the_lnet.ln_mt_rstq[i]) {
3141                         lnet_net_unlock(i);
3142                         continue;
3143                 }
3144                 list_splice_init(the_lnet.ln_mt_rstq[i], &local_queue);
3145                 lnet_net_unlock(i);
3146
3147                 now = ktime_get();
3148
3149                 list_for_each_entry_safe(rspt, tmp, &local_queue, rspt_on_list) {
3150                         /*
3151                          * The rspt mdh will be invalidated when a response
3152                          * is received or whenever we want to discard the
3153                          * block the monitor thread will walk the queue
3154                          * and clean up any rsts with an invalid mdh.
3155                          * The monitor thread will walk the queue until
3156                          * the first unexpired rspt block. This means that
3157                          * some rspt blocks which received their
3158                          * corresponding responses will linger in the
3159                          * queue until they are cleaned up eventually.
3160                          */
3161                         lnet_res_lock(i);
3162                         if (LNetMDHandleIsInvalid(rspt->rspt_mdh)) {
3163                                 lnet_res_unlock(i);
3164                                 list_del(&rspt->rspt_on_list);
3165                                 lnet_rspt_free(rspt, i);
3166                                 continue;
3167                         }
3168
3169                         if (ktime_compare(now, rspt->rspt_deadline) >= 0 ||
3170                             the_lnet.ln_mt_state == LNET_MT_STATE_SHUTDOWN) {
3171                                 struct lnet_peer_ni *lpni;
3172                                 lnet_nid_t nid;
3173
3174                                 md = lnet_handle2md(&rspt->rspt_mdh);
3175                                 if (!md) {
3176                                         /* MD has been queued for unlink, but
3177                                          * rspt hasn't been detached (Note we've
3178                                          * checked above that the rspt_mdh is
3179                                          * valid). Since we cannot lookup the MD
3180                                          * we're unable to detach the rspt
3181                                          * ourselves. Thus, move the rspt to the
3182                                          * zombie list where we'll wait for
3183                                          * either:
3184                                          *   1. The remaining operations on the
3185                                          *   MD to complete. In this case the
3186                                          *   final operation will result in
3187                                          *   lnet_msg_detach_md()->
3188                                          *   lnet_detach_rsp_tracker() where
3189                                          *   we will clean up this response
3190                                          *   tracker.
3191                                          *   2. LNet to shutdown. In this case
3192                                          *   we'll wait until after all LND Nets
3193                                          *   have shutdown and then we can
3194                                          *   safely free any remaining response
3195                                          *   tracker blocks on the zombie list.
3196                                          * Note: We need to hold the resource
3197                                          * lock when adding to the zombie list
3198                                          * because we may have concurrent access
3199                                          * with lnet_detach_rsp_tracker().
3200                                          */
3201                                         LNetInvalidateMDHandle(&rspt->rspt_mdh);
3202                                         list_move(&rspt->rspt_on_list,
3203                                                   the_lnet.ln_mt_zombie_rstqs[i]);
3204                                         lnet_res_unlock(i);
3205                                         continue;
3206                                 }
3207                                 LASSERT(md->md_rspt_ptr == rspt);
3208                                 md->md_rspt_ptr = NULL;
3209                                 lnet_res_unlock(i);
3210
3211                                 LNetMDUnlink(rspt->rspt_mdh);
3212
3213                                 nid = rspt->rspt_next_hop_nid;
3214
3215                                 list_del(&rspt->rspt_on_list);
3216                                 lnet_rspt_free(rspt, i);
3217
3218                                 /* If we're shutting down we just want to clean
3219                                  * up the rspt blocks
3220                                  */
3221                                 if (the_lnet.ln_mt_state == LNET_MT_STATE_SHUTDOWN)
3222                                         continue;
3223
3224                                 lnet_net_lock(i);
3225                                 the_lnet.ln_counters[i]->lct_health.lch_response_timeout_count++;
3226                                 lnet_net_unlock(i);
3227
3228                                 CDEBUG(D_NET,
3229                                        "Response timeout: md = %p: nid = %s\n",
3230                                        md, libcfs_nid2str(nid));
3231
3232                                 /*
3233                                  * If there is a timeout on the response
3234                                  * from the next hop decrement its health
3235                                  * value so that we don't use it
3236                                  */
3237                                 lnet_net_lock(0);
3238                                 lpni = lnet_find_peer_ni_locked(nid);
3239                                 if (lpni) {
3240                                         lnet_handle_remote_failure_locked(lpni);
3241                                         lnet_peer_ni_decref_locked(lpni);
3242                                 }
3243                                 lnet_net_unlock(0);
3244                         } else {
3245                                 lnet_res_unlock(i);
3246                                 break;
3247                         }
3248                 }
3249
3250                 if (!list_empty(&local_queue)) {
3251                         lnet_net_lock(i);
3252                         list_splice(&local_queue, the_lnet.ln_mt_rstq[i]);
3253                         lnet_net_unlock(i);
3254                 }
3255         }
3256 }
3257
3258 static void
3259 lnet_resend_pending_msgs_locked(struct list_head *resendq, int cpt)
3260 {
3261         struct lnet_msg *msg;
3262
3263         while (!list_empty(resendq)) {
3264                 struct lnet_peer_ni *lpni;
3265
3266                 msg = list_entry(resendq->next, struct lnet_msg,
3267                                  msg_list);
3268
3269                 list_del_init(&msg->msg_list);
3270
3271                 lpni = lnet_find_peer_ni_locked(msg->msg_hdr.dest_nid);
3272                 if (!lpni) {
3273                         lnet_net_unlock(cpt);
3274                         CERROR("Expected that a peer is already created for %s\n",
3275                                libcfs_nid2str(msg->msg_hdr.dest_nid));
3276                         msg->msg_no_resend = true;
3277                         lnet_finalize(msg, -EFAULT);
3278                         lnet_net_lock(cpt);
3279                 } else {
3280                         int rc;
3281
3282                         lnet_peer_ni_decref_locked(lpni);
3283
3284                         lnet_net_unlock(cpt);
3285                         CDEBUG(D_NET, "resending %s->%s: %s recovery %d try# %d\n",
3286                                libcfs_nid2str(msg->msg_src_nid_param),
3287                                libcfs_id2str(msg->msg_target),
3288                                lnet_msgtyp2str(msg->msg_type),
3289                                msg->msg_recovery,
3290                                msg->msg_retry_count);
3291                         rc = lnet_send(msg->msg_src_nid_param, msg,
3292                                        msg->msg_rtr_nid_param);
3293                         if (rc) {
3294                                 CERROR("Error sending %s to %s: %d\n",
3295                                        lnet_msgtyp2str(msg->msg_type),
3296                                        libcfs_id2str(msg->msg_target), rc);
3297                                 msg->msg_no_resend = true;
3298                                 lnet_finalize(msg, rc);
3299                         }
3300                         lnet_net_lock(cpt);
3301                         if (!rc)
3302                                 the_lnet.ln_counters[cpt]->lct_health.lch_resend_count++;
3303                 }
3304         }
3305 }
3306
3307 static void
3308 lnet_resend_pending_msgs(void)
3309 {
3310         int i;
3311
3312         cfs_cpt_for_each(i, lnet_cpt_table()) {
3313                 lnet_net_lock(i);
3314                 lnet_resend_pending_msgs_locked(the_lnet.ln_mt_resendqs[i], i);
3315                 lnet_net_unlock(i);
3316         }
3317 }
3318
3319 /* called with cpt and ni_lock held */
3320 static void
3321 lnet_unlink_ni_recovery_mdh_locked(struct lnet_ni *ni, int cpt, bool force)
3322 {
3323         struct lnet_handle_md recovery_mdh;
3324
3325         LNetInvalidateMDHandle(&recovery_mdh);
3326
3327         if (ni->ni_recovery_state & LNET_NI_RECOVERY_PENDING ||
3328             force) {
3329                 recovery_mdh = ni->ni_ping_mdh;
3330                 LNetInvalidateMDHandle(&ni->ni_ping_mdh);
3331         }
3332         lnet_ni_unlock(ni);
3333         lnet_net_unlock(cpt);
3334         if (!LNetMDHandleIsInvalid(recovery_mdh))
3335                 LNetMDUnlink(recovery_mdh);
3336         lnet_net_lock(cpt);
3337         lnet_ni_lock(ni);
3338 }
3339
3340 static void
3341 lnet_recover_local_nis(void)
3342 {
3343         struct lnet_mt_event_info *ev_info;
3344         LIST_HEAD(processed_list);
3345         LIST_HEAD(local_queue);
3346         struct lnet_handle_md mdh;
3347         struct lnet_ni *tmp;
3348         struct lnet_ni *ni;
3349         lnet_nid_t nid;
3350         int healthv;
3351         int rc;
3352
3353         /*
3354          * splice the recovery queue on a local queue. We will iterate
3355          * through the local queue and update it as needed. Once we're
3356          * done with the traversal, we'll splice the local queue back on
3357          * the head of the ln_mt_localNIRecovq. Any newly added local NIs
3358          * will be traversed in the next iteration.
3359          */
3360         lnet_net_lock(0);
3361         list_splice_init(&the_lnet.ln_mt_localNIRecovq,
3362                          &local_queue);
3363         lnet_net_unlock(0);
3364
3365         list_for_each_entry_safe(ni, tmp, &local_queue, ni_recovery) {
3366                 /*
3367                  * if an NI is being deleted or it is now healthy, there
3368                  * is no need to keep it around in the recovery queue.
3369                  * The monitor thread is the only thread responsible for
3370                  * removing the NI from the recovery queue.
3371                  * Multiple threads can be adding NIs to the recovery
3372                  * queue.
3373                  */
3374                 healthv = atomic_read(&ni->ni_healthv);
3375
3376                 lnet_net_lock(0);
3377                 lnet_ni_lock(ni);
3378                 if (ni->ni_state != LNET_NI_STATE_ACTIVE ||
3379                     healthv == LNET_MAX_HEALTH_VALUE) {
3380                         list_del_init(&ni->ni_recovery);
3381                         lnet_unlink_ni_recovery_mdh_locked(ni, 0, false);
3382                         lnet_ni_unlock(ni);
3383                         lnet_ni_decref_locked(ni, 0);
3384                         lnet_net_unlock(0);
3385                         continue;
3386                 }
3387
3388                 /*
3389                  * if the local NI failed recovery we must unlink the md.
3390                  * But we want to keep the local_ni on the recovery queue
3391                  * so we can continue the attempts to recover it.
3392                  */
3393                 if (ni->ni_recovery_state & LNET_NI_RECOVERY_FAILED) {
3394                         lnet_unlink_ni_recovery_mdh_locked(ni, 0, true);
3395                         ni->ni_recovery_state &= ~LNET_NI_RECOVERY_FAILED;
3396                 }
3397
3398                 lnet_ni_unlock(ni);
3399                 lnet_net_unlock(0);
3400
3401
3402                 CDEBUG(D_NET, "attempting to recover local ni: %s\n",
3403                        libcfs_nid2str(ni->ni_nid));
3404
3405                 lnet_ni_lock(ni);
3406                 if (!(ni->ni_recovery_state & LNET_NI_RECOVERY_PENDING)) {
3407                         ni->ni_recovery_state |= LNET_NI_RECOVERY_PENDING;
3408                         lnet_ni_unlock(ni);
3409
3410                         LIBCFS_ALLOC(ev_info, sizeof(*ev_info));
3411                         if (!ev_info) {
3412                                 CERROR("out of memory. Can't recover %s\n",
3413                                        libcfs_nid2str(ni->ni_nid));
3414                                 lnet_ni_lock(ni);
3415                                 ni->ni_recovery_state &=
3416                                   ~LNET_NI_RECOVERY_PENDING;
3417                                 lnet_ni_unlock(ni);
3418                                 continue;
3419                         }
3420
3421                         mdh = ni->ni_ping_mdh;
3422                         /*
3423                          * Invalidate the ni mdh in case it's deleted.
3424                          * We'll unlink the mdh in this case below.
3425                          */
3426                         LNetInvalidateMDHandle(&ni->ni_ping_mdh);
3427                         nid = ni->ni_nid;
3428
3429                         /*
3430                          * remove the NI from the local queue and drop the
3431                          * reference count to it while we're recovering
3432                          * it. The reason for that, is that the NI could
3433                          * be deleted, and the way the code is structured
3434                          * is if we don't drop the NI, then the deletion
3435                          * code will enter a loop waiting for the
3436                          * reference count to be removed while holding the
3437                          * ln_mutex_lock(). When we look up the peer to
3438                          * send to in lnet_select_pathway() we will try to
3439                          * lock the ln_mutex_lock() as well, leading to
3440                          * a deadlock. By dropping the refcount and
3441                          * removing it from the list, we allow for the NI
3442                          * to be removed, then we use the cached NID to
3443                          * look it up again. If it's gone, then we just
3444                          * continue examining the rest of the queue.
3445                          */
3446                         lnet_net_lock(0);
3447                         list_del_init(&ni->ni_recovery);
3448                         lnet_ni_decref_locked(ni, 0);
3449                         lnet_net_unlock(0);
3450
3451                         ev_info->mt_type = MT_TYPE_LOCAL_NI;
3452                         ev_info->mt_nid = nid;
3453                         rc = lnet_send_ping(nid, &mdh, LNET_INTERFACES_MIN,
3454                                             ev_info, the_lnet.ln_mt_handler,
3455                                             true);
3456                         /* lookup the nid again */
3457                         lnet_net_lock(0);
3458                         ni = lnet_nid2ni_locked(nid, 0);
3459                         if (!ni) {
3460                                 /*
3461                                  * the NI has been deleted when we dropped
3462                                  * the ref count
3463                                  */
3464                                 lnet_net_unlock(0);
3465                                 LNetMDUnlink(mdh);
3466                                 continue;
3467                         }
3468                         /*
3469                          * Same note as in lnet_recover_peer_nis(). When
3470                          * we're sending the ping, the NI is free to be
3471                          * deleted or manipulated. By this point it
3472                          * could've been added back on the recovery queue,
3473                          * and a refcount taken on it.
3474                          * So we can't just add it blindly again or we'll
3475                          * corrupt the queue. We must check under lock if
3476                          * it's not on any list and if not then add it
3477                          * to the processed list, which will eventually be
3478                          * spliced back on to the recovery queue.
3479                          */
3480                         ni->ni_ping_mdh = mdh;
3481                         if (list_empty(&ni->ni_recovery)) {
3482                                 list_add_tail(&ni->ni_recovery, &processed_list);
3483                                 lnet_ni_addref_locked(ni, 0);
3484                         }
3485                         lnet_net_unlock(0);
3486
3487                         lnet_ni_lock(ni);
3488                         if (rc)
3489                                 ni->ni_recovery_state &= ~LNET_NI_RECOVERY_PENDING;
3490                 }
3491                 lnet_ni_unlock(ni);
3492         }
3493
3494         /*
3495          * put back the remaining NIs on the ln_mt_localNIRecovq to be
3496          * reexamined in the next iteration.
3497          */
3498         list_splice_init(&processed_list, &local_queue);
3499         lnet_net_lock(0);
3500         list_splice(&local_queue, &the_lnet.ln_mt_localNIRecovq);
3501         lnet_net_unlock(0);
3502 }
3503
3504 static int
3505 lnet_resendqs_create(void)
3506 {
3507         struct list_head **resendqs;
3508         resendqs = lnet_create_array_of_queues();
3509
3510         if (!resendqs)
3511                 return -ENOMEM;
3512
3513         lnet_net_lock(LNET_LOCK_EX);
3514         the_lnet.ln_mt_resendqs = resendqs;
3515         lnet_net_unlock(LNET_LOCK_EX);
3516
3517         return 0;
3518 }
3519
3520 static void
3521 lnet_clean_local_ni_recoveryq(void)
3522 {
3523         struct lnet_ni *ni;
3524
3525         /* This is only called when the monitor thread has stopped */
3526         lnet_net_lock(0);
3527
3528         while (!list_empty(&the_lnet.ln_mt_localNIRecovq)) {
3529                 ni = list_entry(the_lnet.ln_mt_localNIRecovq.next,
3530                                 struct lnet_ni, ni_recovery);
3531                 list_del_init(&ni->ni_recovery);
3532                 lnet_ni_lock(ni);
3533                 lnet_unlink_ni_recovery_mdh_locked(ni, 0, true);
3534                 lnet_ni_unlock(ni);
3535                 lnet_ni_decref_locked(ni, 0);
3536         }
3537
3538         lnet_net_unlock(0);
3539 }
3540
3541 static void
3542 lnet_unlink_lpni_recovery_mdh_locked(struct lnet_peer_ni *lpni, int cpt,
3543                                      bool force)
3544 {
3545         struct lnet_handle_md recovery_mdh;
3546
3547         LNetInvalidateMDHandle(&recovery_mdh);
3548
3549         if (lpni->lpni_state & LNET_PEER_NI_RECOVERY_PENDING || force) {
3550                 recovery_mdh = lpni->lpni_recovery_ping_mdh;
3551                 LNetInvalidateMDHandle(&lpni->lpni_recovery_ping_mdh);
3552         }
3553         spin_unlock(&lpni->lpni_lock);
3554         lnet_net_unlock(cpt);
3555         if (!LNetMDHandleIsInvalid(recovery_mdh))
3556                 LNetMDUnlink(recovery_mdh);
3557         lnet_net_lock(cpt);
3558         spin_lock(&lpni->lpni_lock);
3559 }
3560
3561 static void
3562 lnet_clean_peer_ni_recoveryq(void)
3563 {
3564         struct lnet_peer_ni *lpni, *tmp;
3565
3566         lnet_net_lock(LNET_LOCK_EX);
3567
3568         list_for_each_entry_safe(lpni, tmp, &the_lnet.ln_mt_peerNIRecovq,
3569                                  lpni_recovery) {
3570                 list_del_init(&lpni->lpni_recovery);
3571                 spin_lock(&lpni->lpni_lock);
3572                 lnet_unlink_lpni_recovery_mdh_locked(lpni, LNET_LOCK_EX, true);
3573                 spin_unlock(&lpni->lpni_lock);
3574                 lnet_peer_ni_decref_locked(lpni);
3575         }
3576
3577         lnet_net_unlock(LNET_LOCK_EX);
3578 }
3579
3580 static void
3581 lnet_clean_resendqs(void)
3582 {
3583         struct lnet_msg *msg, *tmp;
3584         LIST_HEAD(msgs);
3585         int i;
3586
3587         cfs_cpt_for_each(i, lnet_cpt_table()) {
3588                 lnet_net_lock(i);
3589                 list_splice_init(the_lnet.ln_mt_resendqs[i], &msgs);
3590                 lnet_net_unlock(i);
3591                 list_for_each_entry_safe(msg, tmp, &msgs, msg_list) {
3592                         list_del_init(&msg->msg_list);
3593                         msg->msg_no_resend = true;
3594                         lnet_finalize(msg, -ESHUTDOWN);
3595                 }
3596         }
3597
3598         cfs_percpt_free(the_lnet.ln_mt_resendqs);
3599 }
3600
3601 static void
3602 lnet_recover_peer_nis(void)
3603 {
3604         struct lnet_mt_event_info *ev_info;
3605         LIST_HEAD(processed_list);
3606         LIST_HEAD(local_queue);
3607         struct lnet_handle_md mdh;
3608         struct lnet_peer_ni *lpni;
3609         struct lnet_peer_ni *tmp;
3610         lnet_nid_t nid;
3611         int healthv;
3612         int rc;
3613
3614         /*
3615          * Always use cpt 0 for locking across all interactions with
3616          * ln_mt_peerNIRecovq
3617          */
3618         lnet_net_lock(0);
3619         list_splice_init(&the_lnet.ln_mt_peerNIRecovq,
3620                          &local_queue);
3621         lnet_net_unlock(0);
3622
3623         list_for_each_entry_safe(lpni, tmp, &local_queue,
3624                                  lpni_recovery) {
3625                 /*
3626                  * The same protection strategy is used here as is in the
3627                  * local recovery case.
3628                  */
3629                 lnet_net_lock(0);
3630                 healthv = atomic_read(&lpni->lpni_healthv);
3631                 spin_lock(&lpni->lpni_lock);
3632                 if (lpni->lpni_state & LNET_PEER_NI_DELETING ||
3633                     healthv == LNET_MAX_HEALTH_VALUE) {
3634                         list_del_init(&lpni->lpni_recovery);
3635                         lnet_unlink_lpni_recovery_mdh_locked(lpni, 0, false);
3636                         spin_unlock(&lpni->lpni_lock);
3637                         lnet_peer_ni_decref_locked(lpni);
3638                         lnet_net_unlock(0);
3639                         continue;
3640                 }
3641
3642                 /*
3643                  * If the peer NI has failed recovery we must unlink the
3644                  * md. But we want to keep the peer ni on the recovery
3645                  * queue so we can try to continue recovering it
3646                  */
3647                 if (lpni->lpni_state & LNET_PEER_NI_RECOVERY_FAILED) {
3648                         lnet_unlink_lpni_recovery_mdh_locked(lpni, 0, true);
3649                         lpni->lpni_state &= ~LNET_PEER_NI_RECOVERY_FAILED;
3650                 }
3651
3652                 spin_unlock(&lpni->lpni_lock);
3653                 lnet_net_unlock(0);
3654
3655                 /*
3656                  * NOTE: we're racing with peer deletion from user space.
3657                  * It's possible that a peer is deleted after we check its
3658                  * state. In this case the recovery can create a new peer
3659                  */
3660                 spin_lock(&lpni->lpni_lock);
3661                 if (!(lpni->lpni_state & LNET_PEER_NI_RECOVERY_PENDING) &&
3662                     !(lpni->lpni_state & LNET_PEER_NI_DELETING)) {
3663                         lpni->lpni_state |= LNET_PEER_NI_RECOVERY_PENDING;
3664                         spin_unlock(&lpni->lpni_lock);
3665
3666                         LIBCFS_ALLOC(ev_info, sizeof(*ev_info));
3667                         if (!ev_info) {
3668                                 CERROR("out of memory. Can't recover %s\n",
3669                                        libcfs_nid2str(lpni->lpni_nid));
3670                                 spin_lock(&lpni->lpni_lock);
3671                                 lpni->lpni_state &= ~LNET_PEER_NI_RECOVERY_PENDING;
3672                                 spin_unlock(&lpni->lpni_lock);
3673                                 continue;
3674                         }
3675
3676                         /* look at the comments in lnet_recover_local_nis() */
3677                         mdh = lpni->lpni_recovery_ping_mdh;
3678                         LNetInvalidateMDHandle(&lpni->lpni_recovery_ping_mdh);
3679                         nid = lpni->lpni_nid;
3680                         lnet_net_lock(0);