Whamcloud - gitweb
05cc13575e941f6e6ddb33a63c9dbac9fe463c90
[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, 2016, 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 <lnet/lib-lnet.h>
40 #include <linux/nsproxy.h>
41 #include <net/net_namespace.h>
42
43 static int local_nid_dist_zero = 1;
44 module_param(local_nid_dist_zero, int, 0444);
45 MODULE_PARM_DESC(local_nid_dist_zero, "Reserved");
46
47 int
48 lnet_fail_nid(lnet_nid_t nid, unsigned int threshold)
49 {
50         lnet_test_peer_t *tp;
51         struct list_head *el;
52         struct list_head *next;
53         struct list_head  cull;
54
55         /* NB: use lnet_net_lock(0) to serialize operations on test peers */
56         if (threshold != 0) {
57                 /* Adding a new entry */
58                 LIBCFS_ALLOC(tp, sizeof(*tp));
59                 if (tp == NULL)
60                         return -ENOMEM;
61
62                 tp->tp_nid = nid;
63                 tp->tp_threshold = threshold;
64
65                 lnet_net_lock(0);
66                 list_add_tail(&tp->tp_list, &the_lnet.ln_test_peers);
67                 lnet_net_unlock(0);
68                 return 0;
69         }
70
71         /* removing entries */
72         INIT_LIST_HEAD(&cull);
73
74         lnet_net_lock(0);
75
76         list_for_each_safe(el, next, &the_lnet.ln_test_peers) {
77                 tp = list_entry(el, lnet_test_peer_t, tp_list);
78
79                 if (tp->tp_threshold == 0 ||    /* needs culling anyway */
80                     nid == LNET_NID_ANY ||      /* removing all entries */
81                     tp->tp_nid == nid) {        /* matched this one */
82                         list_del(&tp->tp_list);
83                         list_add(&tp->tp_list, &cull);
84                 }
85         }
86
87         lnet_net_unlock(0);
88
89         while (!list_empty(&cull)) {
90                 tp = list_entry(cull.next, lnet_test_peer_t, tp_list);
91
92                 list_del(&tp->tp_list);
93                 LIBCFS_FREE(tp, sizeof(*tp));
94         }
95         return 0;
96 }
97
98 static int
99 fail_peer (lnet_nid_t nid, int outgoing)
100 {
101         lnet_test_peer_t *tp;
102         struct list_head *el;
103         struct list_head *next;
104         struct list_head  cull;
105         int               fail = 0;
106
107         INIT_LIST_HEAD(&cull);
108
109         /* NB: use lnet_net_lock(0) to serialize operations on test peers */
110         lnet_net_lock(0);
111
112         list_for_each_safe(el, next, &the_lnet.ln_test_peers) {
113                 tp = list_entry(el, lnet_test_peer_t, tp_list);
114
115                 if (tp->tp_threshold == 0) {
116                         /* zombie entry */
117                         if (outgoing) {
118                                 /* only cull zombies on outgoing tests,
119                                  * since we may be at interrupt priority on
120                                  * incoming messages. */
121                                 list_del(&tp->tp_list);
122                                 list_add(&tp->tp_list, &cull);
123                         }
124                         continue;
125                 }
126
127                 if (tp->tp_nid == LNET_NID_ANY ||       /* fail every peer */
128                     nid == tp->tp_nid) {                /* fail this peer */
129                         fail = 1;
130
131                         if (tp->tp_threshold != LNET_MD_THRESH_INF) {
132                                 tp->tp_threshold--;
133                                 if (outgoing &&
134                                     tp->tp_threshold == 0) {
135                                         /* see above */
136                                         list_del(&tp->tp_list);
137                                         list_add(&tp->tp_list, &cull);
138                                 }
139                         }
140                         break;
141                 }
142         }
143
144         lnet_net_unlock(0);
145
146         while (!list_empty(&cull)) {
147                 tp = list_entry(cull.next, lnet_test_peer_t, tp_list);
148                 list_del(&tp->tp_list);
149
150                 LIBCFS_FREE(tp, sizeof(*tp));
151         }
152
153         return fail;
154 }
155
156 unsigned int
157 lnet_iov_nob(unsigned int niov, struct kvec *iov)
158 {
159         unsigned int nob = 0;
160
161         LASSERT(niov == 0 || iov != NULL);
162         while (niov-- > 0)
163                 nob += (iov++)->iov_len;
164
165         return (nob);
166 }
167 EXPORT_SYMBOL(lnet_iov_nob);
168
169 void
170 lnet_copy_iov2iov(unsigned int ndiov, struct kvec *diov, unsigned int doffset,
171                   unsigned int nsiov, struct kvec *siov, unsigned int soffset,
172                   unsigned int nob)
173 {
174         /* NB diov, siov are READ-ONLY */
175         unsigned int  this_nob;
176
177         if (nob == 0)
178                 return;
179
180         /* skip complete frags before 'doffset' */
181         LASSERT(ndiov > 0);
182         while (doffset >= diov->iov_len) {
183                 doffset -= diov->iov_len;
184                 diov++;
185                 ndiov--;
186                 LASSERT(ndiov > 0);
187         }
188
189         /* skip complete frags before 'soffset' */
190         LASSERT(nsiov > 0);
191         while (soffset >= siov->iov_len) {
192                 soffset -= siov->iov_len;
193                 siov++;
194                 nsiov--;
195                 LASSERT(nsiov > 0);
196         }
197
198         do {
199                 LASSERT(ndiov > 0);
200                 LASSERT(nsiov > 0);
201                 this_nob = MIN(diov->iov_len - doffset,
202                                siov->iov_len - soffset);
203                 this_nob = MIN(this_nob, nob);
204
205                 memcpy((char *)diov->iov_base + doffset,
206                        (char *)siov->iov_base + soffset, this_nob);
207                 nob -= this_nob;
208
209                 if (diov->iov_len > doffset + this_nob) {
210                         doffset += this_nob;
211                 } else {
212                         diov++;
213                         ndiov--;
214                         doffset = 0;
215                 }
216
217                 if (siov->iov_len > soffset + this_nob) {
218                         soffset += this_nob;
219                 } else {
220                         siov++;
221                         nsiov--;
222                         soffset = 0;
223                 }
224         } while (nob > 0);
225 }
226 EXPORT_SYMBOL(lnet_copy_iov2iov);
227
228 int
229 lnet_extract_iov(int dst_niov, struct kvec *dst,
230                  int src_niov, struct kvec *src,
231                  unsigned int offset, unsigned int len)
232 {
233         /* Initialise 'dst' to the subset of 'src' starting at 'offset',
234          * for exactly 'len' bytes, and return the number of entries.
235          * NB not destructive to 'src' */
236         unsigned int    frag_len;
237         unsigned int    niov;
238
239         if (len == 0)                           /* no data => */
240                 return (0);                     /* no frags */
241
242         LASSERT(src_niov > 0);
243         while (offset >= src->iov_len) {      /* skip initial frags */
244                 offset -= src->iov_len;
245                 src_niov--;
246                 src++;
247                 LASSERT(src_niov > 0);
248         }
249
250         niov = 1;
251         for (;;) {
252                 LASSERT(src_niov > 0);
253                 LASSERT((int)niov <= dst_niov);
254
255                 frag_len = src->iov_len - offset;
256                 dst->iov_base = ((char *)src->iov_base) + offset;
257
258                 if (len <= frag_len) {
259                         dst->iov_len = len;
260                         return (niov);
261                 }
262
263                 dst->iov_len = frag_len;
264
265                 len -= frag_len;
266                 dst++;
267                 src++;
268                 niov++;
269                 src_niov--;
270                 offset = 0;
271         }
272 }
273 EXPORT_SYMBOL(lnet_extract_iov);
274
275
276 unsigned int
277 lnet_kiov_nob(unsigned int niov, lnet_kiov_t *kiov)
278 {
279         unsigned int  nob = 0;
280
281         LASSERT(niov == 0 || kiov != NULL);
282         while (niov-- > 0)
283                 nob += (kiov++)->kiov_len;
284
285         return (nob);
286 }
287 EXPORT_SYMBOL(lnet_kiov_nob);
288
289 void
290 lnet_copy_kiov2kiov(unsigned int ndiov, lnet_kiov_t *diov, unsigned int doffset,
291                     unsigned int nsiov, lnet_kiov_t *siov, unsigned int soffset,
292                     unsigned int nob)
293 {
294         /* NB diov, siov are READ-ONLY */
295         unsigned int    this_nob;
296         char           *daddr = NULL;
297         char           *saddr = NULL;
298
299         if (nob == 0)
300                 return;
301
302         LASSERT (!in_interrupt ());
303
304         LASSERT (ndiov > 0);
305         while (doffset >= diov->kiov_len) {
306                 doffset -= diov->kiov_len;
307                 diov++;
308                 ndiov--;
309                 LASSERT(ndiov > 0);
310         }
311
312         LASSERT(nsiov > 0);
313         while (soffset >= siov->kiov_len) {
314                 soffset -= siov->kiov_len;
315                 siov++;
316                 nsiov--;
317                 LASSERT(nsiov > 0);
318         }
319
320         do {
321                 LASSERT(ndiov > 0);
322                 LASSERT(nsiov > 0);
323                 this_nob = MIN(diov->kiov_len - doffset,
324                                siov->kiov_len - soffset);
325                 this_nob = MIN(this_nob, nob);
326
327                 if (daddr == NULL)
328                         daddr = ((char *)kmap(diov->kiov_page)) +
329                                 diov->kiov_offset + doffset;
330                 if (saddr == NULL)
331                         saddr = ((char *)kmap(siov->kiov_page)) +
332                                 siov->kiov_offset + soffset;
333
334                 /* Vanishing risk of kmap deadlock when mapping 2 pages.
335                  * However in practice at least one of the kiovs will be mapped
336                  * kernel pages and the map/unmap will be NOOPs */
337
338                 memcpy (daddr, saddr, this_nob);
339                 nob -= this_nob;
340
341                 if (diov->kiov_len > doffset + this_nob) {
342                         daddr += this_nob;
343                         doffset += this_nob;
344                 } else {
345                         kunmap(diov->kiov_page);
346                         daddr = NULL;
347                         diov++;
348                         ndiov--;
349                         doffset = 0;
350                 }
351
352                 if (siov->kiov_len > soffset + this_nob) {
353                         saddr += this_nob;
354                         soffset += this_nob;
355                 } else {
356                         kunmap(siov->kiov_page);
357                         saddr = NULL;
358                         siov++;
359                         nsiov--;
360                         soffset = 0;
361                 }
362         } while (nob > 0);
363
364         if (daddr != NULL)
365                 kunmap(diov->kiov_page);
366         if (saddr != NULL)
367                 kunmap(siov->kiov_page);
368 }
369 EXPORT_SYMBOL(lnet_copy_kiov2kiov);
370
371 void
372 lnet_copy_kiov2iov (unsigned int niov, struct kvec *iov, unsigned int iovoffset,
373                     unsigned int nkiov, lnet_kiov_t *kiov, unsigned int kiovoffset,
374                     unsigned int nob)
375 {
376         /* NB iov, kiov are READ-ONLY */
377         unsigned int    this_nob;
378         char           *addr = NULL;
379
380         if (nob == 0)
381                 return;
382
383         LASSERT (!in_interrupt ());
384
385         LASSERT (niov > 0);
386         while (iovoffset >= iov->iov_len) {
387                 iovoffset -= iov->iov_len;
388                 iov++;
389                 niov--;
390                 LASSERT(niov > 0);
391         }
392
393         LASSERT(nkiov > 0);
394         while (kiovoffset >= kiov->kiov_len) {
395                 kiovoffset -= kiov->kiov_len;
396                 kiov++;
397                 nkiov--;
398                 LASSERT(nkiov > 0);
399         }
400
401         do {
402                 LASSERT(niov > 0);
403                 LASSERT(nkiov > 0);
404                 this_nob = MIN(iov->iov_len - iovoffset,
405                                kiov->kiov_len - kiovoffset);
406                 this_nob = MIN(this_nob, nob);
407
408                 if (addr == NULL)
409                         addr = ((char *)kmap(kiov->kiov_page)) +
410                                 kiov->kiov_offset + kiovoffset;
411
412                 memcpy((char *)iov->iov_base + iovoffset, addr, this_nob);
413                 nob -= this_nob;
414
415                 if (iov->iov_len > iovoffset + this_nob) {
416                         iovoffset += this_nob;
417                 } else {
418                         iov++;
419                         niov--;
420                         iovoffset = 0;
421                 }
422
423                 if (kiov->kiov_len > kiovoffset + this_nob) {
424                         addr += this_nob;
425                         kiovoffset += this_nob;
426                 } else {
427                         kunmap(kiov->kiov_page);
428                         addr = NULL;
429                         kiov++;
430                         nkiov--;
431                         kiovoffset = 0;
432                 }
433
434         } while (nob > 0);
435
436         if (addr != NULL)
437                 kunmap(kiov->kiov_page);
438 }
439 EXPORT_SYMBOL(lnet_copy_kiov2iov);
440
441 void
442 lnet_copy_iov2kiov(unsigned int nkiov, lnet_kiov_t *kiov, unsigned int kiovoffset,
443                    unsigned int niov, struct kvec *iov, unsigned int iovoffset,
444                    unsigned int nob)
445 {
446         /* NB kiov, iov are READ-ONLY */
447         unsigned int    this_nob;
448         char           *addr = NULL;
449
450         if (nob == 0)
451                 return;
452
453         LASSERT (!in_interrupt ());
454
455         LASSERT (nkiov > 0);
456         while (kiovoffset >= kiov->kiov_len) {
457                 kiovoffset -= kiov->kiov_len;
458                 kiov++;
459                 nkiov--;
460                 LASSERT(nkiov > 0);
461         }
462
463         LASSERT(niov > 0);
464         while (iovoffset >= iov->iov_len) {
465                 iovoffset -= iov->iov_len;
466                 iov++;
467                 niov--;
468                 LASSERT(niov > 0);
469         }
470
471         do {
472                 LASSERT(nkiov > 0);
473                 LASSERT(niov > 0);
474                 this_nob = MIN(kiov->kiov_len - kiovoffset,
475                                iov->iov_len - iovoffset);
476                 this_nob = MIN(this_nob, nob);
477
478                 if (addr == NULL)
479                         addr = ((char *)kmap(kiov->kiov_page)) +
480                                 kiov->kiov_offset + kiovoffset;
481
482                 memcpy (addr, (char *)iov->iov_base + iovoffset, this_nob);
483                 nob -= this_nob;
484
485                 if (kiov->kiov_len > kiovoffset + this_nob) {
486                         addr += this_nob;
487                         kiovoffset += this_nob;
488                 } else {
489                         kunmap(kiov->kiov_page);
490                         addr = NULL;
491                         kiov++;
492                         nkiov--;
493                         kiovoffset = 0;
494                 }
495
496                 if (iov->iov_len > iovoffset + this_nob) {
497                         iovoffset += this_nob;
498                 } else {
499                         iov++;
500                         niov--;
501                         iovoffset = 0;
502                 }
503         } while (nob > 0);
504
505         if (addr != NULL)
506                 kunmap(kiov->kiov_page);
507 }
508 EXPORT_SYMBOL(lnet_copy_iov2kiov);
509
510 int
511 lnet_extract_kiov(int dst_niov, lnet_kiov_t *dst,
512                   int src_niov, lnet_kiov_t *src,
513                   unsigned int offset, unsigned int len)
514 {
515         /* Initialise 'dst' to the subset of 'src' starting at 'offset',
516          * for exactly 'len' bytes, and return the number of entries.
517          * NB not destructive to 'src' */
518         unsigned int    frag_len;
519         unsigned int    niov;
520
521         if (len == 0)                           /* no data => */
522                 return (0);                     /* no frags */
523
524         LASSERT(src_niov > 0);
525         while (offset >= src->kiov_len) {      /* skip initial frags */
526                 offset -= src->kiov_len;
527                 src_niov--;
528                 src++;
529                 LASSERT(src_niov > 0);
530         }
531
532         niov = 1;
533         for (;;) {
534                 LASSERT(src_niov > 0);
535                 LASSERT((int)niov <= dst_niov);
536
537                 frag_len = src->kiov_len - offset;
538                 dst->kiov_page = src->kiov_page;
539                 dst->kiov_offset = src->kiov_offset + offset;
540
541                 if (len <= frag_len) {
542                         dst->kiov_len = len;
543                         LASSERT(dst->kiov_offset + dst->kiov_len <= PAGE_SIZE);
544                         return niov;
545                 }
546
547                 dst->kiov_len = frag_len;
548                 LASSERT(dst->kiov_offset + dst->kiov_len <= PAGE_SIZE);
549
550                 len -= frag_len;
551                 dst++;
552                 src++;
553                 niov++;
554                 src_niov--;
555                 offset = 0;
556         }
557 }
558 EXPORT_SYMBOL(lnet_extract_kiov);
559
560 void
561 lnet_ni_recv(lnet_ni_t *ni, void *private, lnet_msg_t *msg, int delayed,
562              unsigned int offset, unsigned int mlen, unsigned int rlen)
563 {
564         unsigned int  niov = 0;
565         struct kvec *iov = NULL;
566         lnet_kiov_t  *kiov = NULL;
567         int           rc;
568
569         LASSERT (!in_interrupt ());
570         LASSERT (mlen == 0 || msg != NULL);
571
572         if (msg != NULL) {
573                 LASSERT(msg->msg_receiving);
574                 LASSERT(!msg->msg_sending);
575                 LASSERT(rlen == msg->msg_len);
576                 LASSERT(mlen <= msg->msg_len);
577                 LASSERT(msg->msg_offset == offset);
578                 LASSERT(msg->msg_wanted == mlen);
579
580                 msg->msg_receiving = 0;
581
582                 if (mlen != 0) {
583                         niov = msg->msg_niov;
584                         iov  = msg->msg_iov;
585                         kiov = msg->msg_kiov;
586
587                         LASSERT (niov > 0);
588                         LASSERT ((iov == NULL) != (kiov == NULL));
589                 }
590         }
591
592         rc = (ni->ni_net->net_lnd->lnd_recv)(ni, private, msg, delayed,
593                                              niov, iov, kiov, offset, mlen,
594                                              rlen);
595         if (rc < 0)
596                 lnet_finalize(ni, msg, rc);
597 }
598
599 static void
600 lnet_setpayloadbuffer(lnet_msg_t *msg)
601 {
602         lnet_libmd_t *md = msg->msg_md;
603
604         LASSERT(msg->msg_len > 0);
605         LASSERT(!msg->msg_routing);
606         LASSERT(md != NULL);
607         LASSERT(msg->msg_niov == 0);
608         LASSERT(msg->msg_iov == NULL);
609         LASSERT(msg->msg_kiov == NULL);
610
611         msg->msg_niov = md->md_niov;
612         if ((md->md_options & LNET_MD_KIOV) != 0)
613                 msg->msg_kiov = md->md_iov.kiov;
614         else
615                 msg->msg_iov = md->md_iov.iov;
616 }
617
618 void
619 lnet_prep_send(lnet_msg_t *msg, int type, lnet_process_id_t target,
620                unsigned int offset, unsigned int len)
621 {
622         msg->msg_type = type;
623         msg->msg_target = target;
624         msg->msg_len = len;
625         msg->msg_offset = offset;
626
627         if (len != 0)
628                 lnet_setpayloadbuffer(msg);
629
630         memset (&msg->msg_hdr, 0, sizeof (msg->msg_hdr));
631         msg->msg_hdr.type           = cpu_to_le32(type);
632         msg->msg_hdr.dest_pid       = cpu_to_le32(target.pid);
633         /* src_nid will be set later */
634         msg->msg_hdr.src_pid        = cpu_to_le32(the_lnet.ln_pid);
635         msg->msg_hdr.payload_length = cpu_to_le32(len);
636 }
637
638 static void
639 lnet_ni_send(lnet_ni_t *ni, lnet_msg_t *msg)
640 {
641         void   *priv = msg->msg_private;
642         int     rc;
643
644         LASSERT (!in_interrupt ());
645         LASSERT (LNET_NETTYP(LNET_NIDNET(ni->ni_nid)) == LOLND ||
646                  (msg->msg_txcredit && msg->msg_peertxcredit));
647
648         rc = (ni->ni_net->net_lnd->lnd_send)(ni, priv, msg);
649         if (rc < 0)
650                 lnet_finalize(ni, msg, rc);
651 }
652
653 static int
654 lnet_ni_eager_recv(lnet_ni_t *ni, lnet_msg_t *msg)
655 {
656         int     rc;
657
658         LASSERT(!msg->msg_sending);
659         LASSERT(msg->msg_receiving);
660         LASSERT(!msg->msg_rx_ready_delay);
661         LASSERT(ni->ni_net->net_lnd->lnd_eager_recv != NULL);
662
663         msg->msg_rx_ready_delay = 1;
664         rc = (ni->ni_net->net_lnd->lnd_eager_recv)(ni, msg->msg_private, msg,
665                                                   &msg->msg_private);
666         if (rc != 0) {
667                 CERROR("recv from %s / send to %s aborted: "
668                        "eager_recv failed %d\n",
669                        libcfs_nid2str(msg->msg_rxpeer->lpni_nid),
670                        libcfs_id2str(msg->msg_target), rc);
671                 LASSERT(rc < 0); /* required by my callers */
672         }
673
674         return rc;
675 }
676
677 /* NB: caller shall hold a ref on 'lp' as I'd drop lnet_net_lock */
678 static void
679 lnet_ni_query_locked(lnet_ni_t *ni, struct lnet_peer_ni *lp)
680 {
681         cfs_time_t last_alive = 0;
682
683         LASSERT(lnet_peer_aliveness_enabled(lp));
684         LASSERT(ni->ni_net->net_lnd->lnd_query != NULL);
685
686         lnet_net_unlock(lp->lpni_cpt);
687         (ni->ni_net->net_lnd->lnd_query)(ni, lp->lpni_nid, &last_alive);
688         lnet_net_lock(lp->lpni_cpt);
689
690         lp->lpni_last_query = cfs_time_current();
691
692         if (last_alive != 0) /* NI has updated timestamp */
693                 lp->lpni_last_alive = last_alive;
694 }
695
696 /* NB: always called with lnet_net_lock held */
697 static inline int
698 lnet_peer_is_alive (struct lnet_peer_ni *lp, cfs_time_t now)
699 {
700         int        alive;
701         cfs_time_t deadline;
702
703         LASSERT (lnet_peer_aliveness_enabled(lp));
704
705         /*
706          * Trust lnet_notify() if it has more recent aliveness news, but
707          * ignore the initial assumed death (see lnet_peers_start_down()).
708          */
709         if (!lp->lpni_alive && lp->lpni_alive_count > 0 &&
710             cfs_time_aftereq(lp->lpni_timestamp, lp->lpni_last_alive))
711                 return 0;
712
713         deadline =
714           cfs_time_add(lp->lpni_last_alive,
715                        cfs_time_seconds(lp->lpni_net->net_tunables.
716                                         lct_peer_timeout));
717         alive = cfs_time_after(deadline, now);
718
719         /*
720          * Update obsolete lp_alive except for routers assumed to be dead
721          * initially, because router checker would update aliveness in this
722          * case, and moreover lpni_last_alive at peer creation is assumed.
723          */
724         if (alive && !lp->lpni_alive &&
725             !(lnet_isrouter(lp) && lp->lpni_alive_count == 0))
726                 lnet_notify_locked(lp, 0, 1, lp->lpni_last_alive);
727
728         return alive;
729 }
730
731
732 /* NB: returns 1 when alive, 0 when dead, negative when error;
733  *     may drop the lnet_net_lock */
734 static int
735 lnet_peer_alive_locked (struct lnet_ni *ni, struct lnet_peer_ni *lp)
736 {
737         cfs_time_t now = cfs_time_current();
738
739         if (!lnet_peer_aliveness_enabled(lp))
740                 return -ENODEV;
741
742         if (lnet_peer_is_alive(lp, now))
743                 return 1;
744
745         /*
746          * Peer appears dead, but we should avoid frequent NI queries (at
747          * most once per lnet_queryinterval seconds).
748          */
749         if (lp->lpni_last_query != 0) {
750                 static const int lnet_queryinterval = 1;
751
752                 cfs_time_t next_query =
753                            cfs_time_add(lp->lpni_last_query,
754                                         cfs_time_seconds(lnet_queryinterval));
755
756                 if (cfs_time_before(now, next_query)) {
757                         if (lp->lpni_alive)
758                                 CWARN("Unexpected aliveness of peer %s: "
759                                       "%d < %d (%d/%d)\n",
760                                       libcfs_nid2str(lp->lpni_nid),
761                                       (int)now, (int)next_query,
762                                       lnet_queryinterval,
763                                       lp->lpni_net->net_tunables.lct_peer_timeout);
764                         return 0;
765                 }
766         }
767
768         /* query NI for latest aliveness news */
769         lnet_ni_query_locked(ni, lp);
770
771         if (lnet_peer_is_alive(lp, now))
772                 return 1;
773
774         lnet_notify_locked(lp, 0, 0, lp->lpni_last_alive);
775         return 0;
776 }
777
778 /**
779  * \param msg The message to be sent.
780  * \param do_send True if lnet_ni_send() should be called in this function.
781  *        lnet_send() is going to lnet_net_unlock immediately after this, so
782  *        it sets do_send FALSE and I don't do the unlock/send/lock bit.
783  *
784  * \retval LNET_CREDIT_OK If \a msg sent or OK to send.
785  * \retval LNET_CREDIT_WAIT If \a msg blocked for credit.
786  * \retval -EHOSTUNREACH If the next hop of the message appears dead.
787  * \retval -ECANCELED If the MD of the message has been unlinked.
788  */
789 static int
790 lnet_post_send_locked(lnet_msg_t *msg, int do_send)
791 {
792         struct lnet_peer_ni     *lp = msg->msg_txpeer;
793         struct lnet_ni          *ni = msg->msg_txni;
794         int                     cpt = msg->msg_tx_cpt;
795         struct lnet_tx_queue    *tq = ni->ni_tx_queues[cpt];
796
797         /* non-lnet_send() callers have checked before */
798         LASSERT(!do_send || msg->msg_tx_delayed);
799         LASSERT(!msg->msg_receiving);
800         LASSERT(msg->msg_tx_committed);
801
802         /* NB 'lp' is always the next hop */
803         if ((msg->msg_target.pid & LNET_PID_USERFLAG) == 0 &&
804             lnet_peer_alive_locked(ni, lp) == 0) {
805                 the_lnet.ln_counters[cpt]->drop_count++;
806                 the_lnet.ln_counters[cpt]->drop_length += msg->msg_len;
807                 lnet_net_unlock(cpt);
808
809                 CNETERR("Dropping message for %s: peer not alive\n",
810                         libcfs_id2str(msg->msg_target));
811                 if (do_send)
812                         lnet_finalize(ni, msg, -EHOSTUNREACH);
813
814                 lnet_net_lock(cpt);
815                 return -EHOSTUNREACH;
816         }
817
818         if (msg->msg_md != NULL &&
819             (msg->msg_md->md_flags & LNET_MD_FLAG_ABORTED) != 0) {
820                 lnet_net_unlock(cpt);
821
822                 CNETERR("Aborting message for %s: LNetM[DE]Unlink() already "
823                         "called on the MD/ME.\n",
824                         libcfs_id2str(msg->msg_target));
825                 if (do_send)
826                         lnet_finalize(ni, msg, -ECANCELED);
827
828                 lnet_net_lock(cpt);
829                 return -ECANCELED;
830         }
831
832         if (!msg->msg_peertxcredit) {
833                 LASSERT((lp->lpni_txcredits < 0) ==
834                         !list_empty(&lp->lpni_txq));
835
836                 msg->msg_peertxcredit = 1;
837                 lp->lpni_txqnob += msg->msg_len + sizeof(lnet_hdr_t);
838                 lp->lpni_txcredits--;
839
840                 if (lp->lpni_txcredits < lp->lpni_mintxcredits)
841                         lp->lpni_mintxcredits = lp->lpni_txcredits;
842
843                 if (lp->lpni_txcredits < 0) {
844                         msg->msg_tx_delayed = 1;
845                         list_add_tail(&msg->msg_list, &lp->lpni_txq);
846                         return LNET_CREDIT_WAIT;
847                 }
848         }
849
850         if (!msg->msg_txcredit) {
851                 LASSERT((tq->tq_credits < 0) ==
852                         !list_empty(&tq->tq_delayed));
853
854                 msg->msg_txcredit = 1;
855                 tq->tq_credits--;
856
857                 if (tq->tq_credits < tq->tq_credits_min)
858                         tq->tq_credits_min = tq->tq_credits;
859
860                 if (tq->tq_credits < 0) {
861                         msg->msg_tx_delayed = 1;
862                         list_add_tail(&msg->msg_list, &tq->tq_delayed);
863                         return LNET_CREDIT_WAIT;
864                 }
865         }
866
867         if (do_send) {
868                 lnet_net_unlock(cpt);
869                 lnet_ni_send(ni, msg);
870                 lnet_net_lock(cpt);
871         }
872         return LNET_CREDIT_OK;
873 }
874
875
876 static lnet_rtrbufpool_t *
877 lnet_msg2bufpool(lnet_msg_t *msg)
878 {
879         lnet_rtrbufpool_t       *rbp;
880         int                     cpt;
881
882         LASSERT(msg->msg_rx_committed);
883
884         cpt = msg->msg_rx_cpt;
885         rbp = &the_lnet.ln_rtrpools[cpt][0];
886
887         LASSERT(msg->msg_len <= LNET_MTU);
888         while (msg->msg_len > (unsigned int)rbp->rbp_npages * PAGE_SIZE) {
889                 rbp++;
890                 LASSERT(rbp < &the_lnet.ln_rtrpools[cpt][LNET_NRBPOOLS]);
891         }
892
893         return rbp;
894 }
895
896 static int
897 lnet_post_routed_recv_locked (lnet_msg_t *msg, int do_recv)
898 {
899         /* lnet_parse is going to lnet_net_unlock immediately after this, so it
900          * sets do_recv FALSE and I don't do the unlock/send/lock bit.
901          * I return LNET_CREDIT_WAIT if msg blocked and LNET_CREDIT_OK if
902          * received or OK to receive */
903         struct lnet_peer_ni *lp = msg->msg_rxpeer;
904         lnet_rtrbufpool_t   *rbp;
905         lnet_rtrbuf_t       *rb;
906
907         LASSERT (msg->msg_iov == NULL);
908         LASSERT (msg->msg_kiov == NULL);
909         LASSERT (msg->msg_niov == 0);
910         LASSERT (msg->msg_routing);
911         LASSERT (msg->msg_receiving);
912         LASSERT (!msg->msg_sending);
913
914         /* non-lnet_parse callers only receive delayed messages */
915         LASSERT(!do_recv || msg->msg_rx_delayed);
916
917         if (!msg->msg_peerrtrcredit) {
918                 LASSERT((lp->lpni_rtrcredits < 0) ==
919                         !list_empty(&lp->lpni_rtrq));
920
921                 msg->msg_peerrtrcredit = 1;
922                 lp->lpni_rtrcredits--;
923                 if (lp->lpni_rtrcredits < lp->lpni_minrtrcredits)
924                         lp->lpni_minrtrcredits = lp->lpni_rtrcredits;
925
926                 if (lp->lpni_rtrcredits < 0) {
927                         /* must have checked eager_recv before here */
928                         LASSERT(msg->msg_rx_ready_delay);
929                         msg->msg_rx_delayed = 1;
930                         list_add_tail(&msg->msg_list, &lp->lpni_rtrq);
931                         return LNET_CREDIT_WAIT;
932                 }
933         }
934
935         rbp = lnet_msg2bufpool(msg);
936
937         if (!msg->msg_rtrcredit) {
938                 msg->msg_rtrcredit = 1;
939                 rbp->rbp_credits--;
940                 if (rbp->rbp_credits < rbp->rbp_mincredits)
941                         rbp->rbp_mincredits = rbp->rbp_credits;
942
943                 if (rbp->rbp_credits < 0) {
944                         /* must have checked eager_recv before here */
945                         LASSERT(msg->msg_rx_ready_delay);
946                         msg->msg_rx_delayed = 1;
947                         list_add_tail(&msg->msg_list, &rbp->rbp_msgs);
948                         return LNET_CREDIT_WAIT;
949                 }
950         }
951
952         LASSERT(!list_empty(&rbp->rbp_bufs));
953         rb = list_entry(rbp->rbp_bufs.next, lnet_rtrbuf_t, rb_list);
954         list_del(&rb->rb_list);
955
956         msg->msg_niov = rbp->rbp_npages;
957         msg->msg_kiov = &rb->rb_kiov[0];
958
959         if (do_recv) {
960                 int cpt = msg->msg_rx_cpt;
961
962                 lnet_net_unlock(cpt);
963                 lnet_ni_recv(msg->msg_rxni, msg->msg_private, msg, 1,
964                              0, msg->msg_len, msg->msg_len);
965                 lnet_net_lock(cpt);
966         }
967         return LNET_CREDIT_OK;
968 }
969
970 void
971 lnet_return_tx_credits_locked(lnet_msg_t *msg)
972 {
973         struct lnet_peer_ni     *txpeer = msg->msg_txpeer;
974         struct lnet_ni          *txni = msg->msg_txni;
975         lnet_msg_t              *msg2;
976
977         if (msg->msg_txcredit) {
978                 struct lnet_ni       *ni = msg->msg_txni;
979                 struct lnet_tx_queue *tq = ni->ni_tx_queues[msg->msg_tx_cpt];
980
981                 /* give back NI txcredits */
982                 msg->msg_txcredit = 0;
983
984                 LASSERT((tq->tq_credits < 0) ==
985                         !list_empty(&tq->tq_delayed));
986
987                 tq->tq_credits++;
988                 if (tq->tq_credits <= 0) {
989                         msg2 = list_entry(tq->tq_delayed.next,
990                                           lnet_msg_t, msg_list);
991                         list_del(&msg2->msg_list);
992
993                         LASSERT(msg2->msg_txni == ni);
994                         LASSERT(msg2->msg_tx_delayed);
995
996                         (void) lnet_post_send_locked(msg2, 1);
997                 }
998         }
999
1000         if (msg->msg_peertxcredit) {
1001                 /* give back peer txcredits */
1002                 msg->msg_peertxcredit = 0;
1003
1004                 LASSERT((txpeer->lpni_txcredits < 0) ==
1005                         !list_empty(&txpeer->lpni_txq));
1006
1007                 txpeer->lpni_txqnob -= msg->msg_len + sizeof(lnet_hdr_t);
1008                 LASSERT (txpeer->lpni_txqnob >= 0);
1009
1010                 txpeer->lpni_txcredits++;
1011                 if (txpeer->lpni_txcredits <= 0) {
1012                         msg2 = list_entry(txpeer->lpni_txq.next,
1013                                               lnet_msg_t, msg_list);
1014                         list_del(&msg2->msg_list);
1015
1016                         LASSERT(msg2->msg_txpeer == txpeer);
1017                         LASSERT(msg2->msg_tx_delayed);
1018
1019                         (void) lnet_post_send_locked(msg2, 1);
1020                 }
1021         }
1022
1023         if (txni != NULL) {
1024                 msg->msg_txni = NULL;
1025                 lnet_ni_decref_locked(txni, msg->msg_tx_cpt);
1026         }
1027
1028         if (txpeer != NULL) {
1029                 /*
1030                  * TODO:
1031                  * Once the patch for the health comes in we need to set
1032                  * the health of the peer ni to bad when we fail to send
1033                  * a message.
1034                  * int status = msg->msg_ev.status;
1035                  * if (status != 0)
1036                  *      lnet_set_peer_ni_health_locked(txpeer, false)
1037                  */
1038                 msg->msg_txpeer = NULL;
1039                 lnet_peer_ni_decref_locked(txpeer);
1040         }
1041 }
1042
1043 void
1044 lnet_schedule_blocked_locked(lnet_rtrbufpool_t *rbp)
1045 {
1046         lnet_msg_t      *msg;
1047
1048         if (list_empty(&rbp->rbp_msgs))
1049                 return;
1050         msg = list_entry(rbp->rbp_msgs.next,
1051                          lnet_msg_t, msg_list);
1052         list_del(&msg->msg_list);
1053
1054         (void)lnet_post_routed_recv_locked(msg, 1);
1055 }
1056
1057 void
1058 lnet_drop_routed_msgs_locked(struct list_head *list, int cpt)
1059 {
1060         lnet_msg_t       *msg;
1061         lnet_msg_t       *tmp;
1062         struct list_head drop;
1063
1064         INIT_LIST_HEAD(&drop);
1065
1066         list_splice_init(list, &drop);
1067
1068         lnet_net_unlock(cpt);
1069
1070         list_for_each_entry_safe(msg, tmp, &drop, msg_list) {
1071                 lnet_ni_recv(msg->msg_rxni, msg->msg_private, NULL,
1072                              0, 0, 0, msg->msg_hdr.payload_length);
1073                 list_del_init(&msg->msg_list);
1074                 lnet_finalize(NULL, msg, -ECANCELED);
1075         }
1076
1077         lnet_net_lock(cpt);
1078 }
1079
1080 void
1081 lnet_return_rx_credits_locked(lnet_msg_t *msg)
1082 {
1083         struct lnet_peer_ni     *rxpeer = msg->msg_rxpeer;
1084         struct lnet_ni          *rxni = msg->msg_rxni;
1085         lnet_msg_t              *msg2;
1086
1087         if (msg->msg_rtrcredit) {
1088                 /* give back global router credits */
1089                 lnet_rtrbuf_t     *rb;
1090                 lnet_rtrbufpool_t *rbp;
1091
1092                 /* NB If a msg ever blocks for a buffer in rbp_msgs, it stays
1093                  * there until it gets one allocated, or aborts the wait
1094                  * itself */
1095                 LASSERT(msg->msg_kiov != NULL);
1096
1097                 rb = list_entry(msg->msg_kiov, lnet_rtrbuf_t, rb_kiov[0]);
1098                 rbp = rb->rb_pool;
1099
1100                 msg->msg_kiov = NULL;
1101                 msg->msg_rtrcredit = 0;
1102
1103                 LASSERT(rbp == lnet_msg2bufpool(msg));
1104
1105                 LASSERT((rbp->rbp_credits > 0) ==
1106                         !list_empty(&rbp->rbp_bufs));
1107
1108                 /* If routing is now turned off, we just drop this buffer and
1109                  * don't bother trying to return credits.  */
1110                 if (!the_lnet.ln_routing) {
1111                         lnet_destroy_rtrbuf(rb, rbp->rbp_npages);
1112                         goto routing_off;
1113                 }
1114
1115                 /* It is possible that a user has lowered the desired number of
1116                  * buffers in this pool.  Make sure we never put back
1117                  * more buffers than the stated number. */
1118                 if (unlikely(rbp->rbp_credits >= rbp->rbp_req_nbuffers)) {
1119                         /* Discard this buffer so we don't have too
1120                          * many. */
1121                         lnet_destroy_rtrbuf(rb, rbp->rbp_npages);
1122                         rbp->rbp_nbuffers--;
1123                 } else {
1124                         list_add(&rb->rb_list, &rbp->rbp_bufs);
1125                         rbp->rbp_credits++;
1126                         if (rbp->rbp_credits <= 0)
1127                                 lnet_schedule_blocked_locked(rbp);
1128                 }
1129         }
1130
1131 routing_off:
1132         if (msg->msg_peerrtrcredit) {
1133                 /* give back peer router credits */
1134                 msg->msg_peerrtrcredit = 0;
1135
1136                 LASSERT((rxpeer->lpni_rtrcredits < 0) ==
1137                         !list_empty(&rxpeer->lpni_rtrq));
1138
1139                 rxpeer->lpni_rtrcredits++;
1140
1141                 /* drop all messages which are queued to be routed on that
1142                  * peer. */
1143                 if (!the_lnet.ln_routing) {
1144                         lnet_drop_routed_msgs_locked(&rxpeer->lpni_rtrq,
1145                                                      msg->msg_rx_cpt);
1146                 } else if (rxpeer->lpni_rtrcredits <= 0) {
1147                         msg2 = list_entry(rxpeer->lpni_rtrq.next,
1148                                           lnet_msg_t, msg_list);
1149                         list_del(&msg2->msg_list);
1150
1151                         (void) lnet_post_routed_recv_locked(msg2, 1);
1152                 }
1153         }
1154         if (rxni != NULL) {
1155                 msg->msg_rxni = NULL;
1156                 lnet_ni_decref_locked(rxni, msg->msg_rx_cpt);
1157         }
1158         if (rxpeer != NULL) {
1159                 msg->msg_rxpeer = NULL;
1160                 lnet_peer_ni_decref_locked(rxpeer);
1161         }
1162 }
1163
1164 static int
1165 lnet_compare_peers(struct lnet_peer_ni *p1, struct lnet_peer_ni *p2)
1166 {
1167         if (p1->lpni_txqnob < p2->lpni_txqnob)
1168                 return 1;
1169
1170         if (p1->lpni_txqnob > p2->lpni_txqnob)
1171                 return -1;
1172
1173         if (p1->lpni_txcredits > p2->lpni_txcredits)
1174                 return 1;
1175
1176         if (p1->lpni_txcredits < p2->lpni_txcredits)
1177                 return -1;
1178
1179         return 0;
1180 }
1181
1182 static int
1183 lnet_compare_routes(lnet_route_t *r1, lnet_route_t *r2)
1184 {
1185         struct lnet_peer_ni *p1 = r1->lr_gateway;
1186         struct lnet_peer_ni *p2 = r2->lr_gateway;
1187         int r1_hops = (r1->lr_hops == LNET_UNDEFINED_HOPS) ? 1 : r1->lr_hops;
1188         int r2_hops = (r2->lr_hops == LNET_UNDEFINED_HOPS) ? 1 : r2->lr_hops;
1189         int rc;
1190
1191         if (r1->lr_priority < r2->lr_priority)
1192                 return 1;
1193
1194         if (r1->lr_priority > r2->lr_priority)
1195                 return -1;
1196
1197         if (r1_hops < r2_hops)
1198                 return 1;
1199
1200         if (r1_hops > r2_hops)
1201                 return -1;
1202
1203         rc = lnet_compare_peers(p1, p2);
1204         if (rc)
1205                 return rc;
1206
1207         if (r1->lr_seq - r2->lr_seq <= 0)
1208                 return 1;
1209
1210         return -1;
1211 }
1212
1213 static struct lnet_peer_ni *
1214 lnet_find_route_locked(struct lnet_net *net, lnet_nid_t target,
1215                        lnet_nid_t rtr_nid)
1216 {
1217         lnet_remotenet_t        *rnet;
1218         lnet_route_t            *route;
1219         lnet_route_t            *best_route;
1220         lnet_route_t            *last_route;
1221         struct lnet_peer_ni     *lpni_best;
1222         struct lnet_peer_ni     *lp;
1223         int                     rc;
1224
1225         /* If @rtr_nid is not LNET_NID_ANY, return the gateway with
1226          * rtr_nid nid, otherwise find the best gateway I can use */
1227
1228         rnet = lnet_find_rnet_locked(LNET_NIDNET(target));
1229         if (rnet == NULL)
1230                 return NULL;
1231
1232         lpni_best = NULL;
1233         best_route = last_route = NULL;
1234         list_for_each_entry(route, &rnet->lrn_routes, lr_list) {
1235                 lp = route->lr_gateway;
1236
1237                 if (!lnet_is_route_alive(route))
1238                         continue;
1239
1240                 if (net != NULL && lp->lpni_net != net)
1241                         continue;
1242
1243                 if (lp->lpni_nid == rtr_nid) /* it's pre-determined router */
1244                         return lp;
1245
1246                 if (lpni_best == NULL) {
1247                         best_route = last_route = route;
1248                         lpni_best = lp;
1249                         continue;
1250                 }
1251
1252                 /* no protection on below fields, but it's harmless */
1253                 if (last_route->lr_seq - route->lr_seq < 0)
1254                         last_route = route;
1255
1256                 rc = lnet_compare_routes(route, best_route);
1257                 if (rc < 0)
1258                         continue;
1259
1260                 best_route = route;
1261                 lpni_best = lp;
1262         }
1263
1264         /* set sequence number on the best router to the latest sequence + 1
1265          * so we can round-robin all routers, it's race and inaccurate but
1266          * harmless and functional  */
1267         if (best_route != NULL)
1268                 best_route->lr_seq = last_route->lr_seq + 1;
1269         return lpni_best;
1270 }
1271
1272 static int
1273 lnet_select_pathway(lnet_nid_t src_nid, lnet_nid_t dst_nid,
1274                     struct lnet_msg *msg, lnet_nid_t rtr_nid, bool *lo_sent)
1275 {
1276         struct lnet_ni          *best_ni = NULL;
1277         struct lnet_peer_ni     *best_lpni = NULL;
1278         struct lnet_peer_ni     *net_gw = NULL;
1279         struct lnet_peer_ni     *best_gw = NULL;
1280         struct lnet_peer_ni     *lpni;
1281         struct lnet_peer        *peer = NULL;
1282         struct lnet_peer_net    *peer_net;
1283         struct lnet_net         *local_net;
1284         struct lnet_ni          *ni = NULL;
1285         int                     cpt, cpt2, rc;
1286         bool                    routing = false;
1287         bool                    ni_is_pref = false;
1288         bool                    preferred = false;
1289         int                     best_credits = 0;
1290         __u32                   seq, seq2;
1291         int                     best_lpni_credits = INT_MIN;
1292         int                     md_cpt = 0;
1293         int                     shortest_distance = INT_MAX;
1294         int                     distance = 0;
1295         bool                    found_ir = false;
1296
1297 again:
1298         /*
1299          * get an initial CPT to use for locking. The idea here is not to
1300          * serialize the calls to select_pathway, so that as many
1301          * operations can run concurrently as possible. To do that we use
1302          * the CPT where this call is being executed. Later on when we
1303          * determine the CPT to use in lnet_message_commit, we switch the
1304          * lock and check if there was any configuration changes, if none,
1305          * then we proceed, if there is, then we'll need to update the cpt
1306          * and redo the operation.
1307          */
1308         cpt = lnet_net_lock_current();
1309
1310         best_gw = NULL;
1311         routing = false;
1312         local_net = NULL;
1313         best_ni = NULL;
1314         shortest_distance = INT_MAX;
1315         found_ir = false;
1316
1317         if (the_lnet.ln_shutdown) {
1318                 lnet_net_unlock(cpt);
1319                 return -ESHUTDOWN;
1320         }
1321
1322         if (msg->msg_md != NULL)
1323                 /* get the cpt of the MD, used during NUMA based selection */
1324                 md_cpt = lnet_cpt_of_cookie(msg->msg_md->md_lh.lh_cookie);
1325         else
1326                 md_cpt = CFS_CPT_ANY;
1327
1328         /*
1329          * initialize the variables which could be reused if we go to
1330          * again
1331          */
1332         lpni = NULL;
1333         seq = lnet_get_dlc_seq_locked();
1334
1335         rc = lnet_find_or_create_peer_locked(dst_nid, cpt, &peer);
1336         if (rc != 0) {
1337                 lnet_net_unlock(cpt);
1338                 return rc;
1339         }
1340
1341         /* If peer is not healthy then can not send anything to it */
1342         if (!lnet_is_peer_healthy_locked(peer)) {
1343                 lnet_net_unlock(cpt);
1344                 return -EHOSTUNREACH;
1345         }
1346
1347         /*
1348          * STEP 1: first jab at determineing best_ni
1349          * if src_nid is explicitly specified, then best_ni is already
1350          * pre-determiend for us. Otherwise we need to select the best
1351          * one to use later on
1352          */
1353         if (src_nid != LNET_NID_ANY) {
1354                 best_ni = lnet_nid2ni_locked(src_nid, cpt);
1355                 if (!best_ni) {
1356                         lnet_net_unlock(cpt);
1357                         LCONSOLE_WARN("Can't send to %s: src %s is not a "
1358                                       "local nid\n", libcfs_nid2str(dst_nid),
1359                                       libcfs_nid2str(src_nid));
1360                         return -EINVAL;
1361                 }
1362
1363                 if (best_ni->ni_net->net_id != LNET_NIDNET(dst_nid)) {
1364                         lnet_net_unlock(cpt);
1365                         LCONSOLE_WARN("No route to %s via from %s\n",
1366                                       libcfs_nid2str(dst_nid),
1367                                       libcfs_nid2str(src_nid));
1368                         return -EINVAL;
1369                 }
1370         }
1371
1372         if (best_ni)
1373                 goto pick_peer;
1374
1375         /*
1376          * Decide whether we need to route to peer_ni.
1377          * Get the local net that I need to be on to be able to directly
1378          * send to that peer.
1379          *
1380          * a. Find the peer which the dst_nid belongs to.
1381          * b. Iterate through each of the peer_nets/nis to decide
1382          * the best peer/local_ni pair to use
1383          */
1384         list_for_each_entry(peer_net, &peer->lp_peer_nets, lpn_on_peer_list) {
1385                 if (!lnet_is_peer_net_healthy_locked(peer_net))
1386                         continue;
1387
1388                 local_net = lnet_get_net_locked(peer_net->lpn_net_id);
1389                 if (!local_net) {
1390                         /*
1391                          * go through each peer_ni on that peer_net and
1392                          * determine the best possible gw to go through
1393                          */
1394                         list_for_each_entry(lpni, &peer_net->lpn_peer_nis,
1395                                             lpni_on_peer_net_list) {
1396                                 net_gw = lnet_find_route_locked(NULL,
1397                                                                 lpni->lpni_nid,
1398                                                                 rtr_nid);
1399
1400                                 /*
1401                                  * if no route is found for that network then
1402                                  * move onto the next peer_ni in the peer
1403                                  */
1404                                 if (!net_gw)
1405                                         continue;
1406
1407                                 if (!best_gw) {
1408                                         best_gw = net_gw;
1409                                         best_lpni = lpni;
1410                                 } else  {
1411                                         rc = lnet_compare_peers(net_gw,
1412                                                                 best_gw);
1413                                         if (rc > 0) {
1414                                                 best_gw = net_gw;
1415                                                 best_lpni = lpni;
1416                                         }
1417                                 }
1418                         }
1419
1420                         if (!best_gw)
1421                                 continue;
1422
1423                         local_net = lnet_get_net_locked
1424                                         (LNET_NIDNET(best_gw->lpni_nid));
1425                         routing = true;
1426                 } else {
1427                         routing = false;
1428                         best_gw = NULL;
1429                 }
1430
1431                 /* no routable net found go on to a different net */
1432                 if (!local_net)
1433                         continue;
1434
1435                 /*
1436                  * Iterate through the NIs in this local Net and select
1437                  * the NI to send from. The selection is determined by
1438                  * these 3 criterion in the following priority:
1439                  *      1. NUMA
1440                  *      2. NI available credits
1441                  *      3. Round Robin
1442                  */
1443                 while ((ni = lnet_get_next_ni_locked(local_net, ni))) {
1444                         if (!lnet_is_ni_healthy_locked(ni))
1445                                 continue;
1446
1447                         /*
1448                          * calculate the distance from the cpt on which
1449                          * the message memory is allocated to the CPT of
1450                          * the NI's physical device
1451                          */
1452                         distance = cfs_cpt_distance(lnet_cpt_table(),
1453                                                     md_cpt,
1454                                                     ni->dev_cpt);
1455
1456                         /*
1457                          * If we already have a closer NI within the NUMA
1458                          * range provided, then there is no need to
1459                          * consider the current NI. Move on to the next
1460                          * one.
1461                          */
1462                         if (distance > shortest_distance &&
1463                             distance > lnet_get_numa_range())
1464                                 continue;
1465
1466                         if (distance < shortest_distance &&
1467                             distance > lnet_get_numa_range()) {
1468                                 /*
1469                                  * The current NI is the closest one that we
1470                                  * have found, even though it's not in the
1471                                  * NUMA range specified. This occurs if
1472                                  * the NUMA range is less than the least
1473                                  * of the distances in the system.
1474                                  * In effect NUMA range consideration is
1475                                  * turned off.
1476                                  */
1477                                 shortest_distance = distance;
1478                         } else if ((distance <= shortest_distance &&
1479                                     distance < lnet_get_numa_range()) ||
1480                                    distance == shortest_distance) {
1481                                 /*
1482                                  * This NI is either within range or it's
1483                                  * equidistant. In both of these cases we
1484                                  * would want to select the NI based on
1485                                  * its available credits first, and then
1486                                  * via Round Robin.
1487                                  */
1488                                 if (distance <= shortest_distance &&
1489                                     distance < lnet_get_numa_range()) {
1490                                         /*
1491                                          * If this is the first NI that's
1492                                          * within range, then set the
1493                                          * shortest distance to the range
1494                                          * specified by the user. In
1495                                          * effect we're saying that all
1496                                          * NIs that fall within this NUMA
1497                                          * range shall be dealt with as
1498                                          * having equal NUMA weight. Which
1499                                          * will mean that we should select
1500                                          * through that set by their
1501                                          * available credits first
1502                                          * followed by Round Robin.
1503                                          *
1504                                          * And since this is the first NI
1505                                          * in the range, let's just set it
1506                                          * as our best_ni for now. The
1507                                          * following NIs found in the
1508                                          * range will be dealt with as
1509                                          * mentioned previously.
1510                                          */
1511                                         shortest_distance = lnet_get_numa_range();
1512                                         if (!found_ir) {
1513                                                 found_ir = true;
1514                                                 goto set_ni;
1515                                         }
1516                                 }
1517                                 /*
1518                                  * This NI is NUMA equidistant let's
1519                                  * select using credits followed by Round
1520                                  * Robin.
1521                                  */
1522                                 if (ni->ni_tx_queues[cpt]->tq_credits <
1523                                         best_credits) {
1524                                         continue;
1525                                 } else if (ni->ni_tx_queues[cpt]->tq_credits ==
1526                                                 best_credits) {
1527                                         if (best_ni) {
1528                                                 if (best_ni->ni_seq <= ni->ni_seq)
1529                                                         continue;
1530                                         }
1531                                 }
1532                         }
1533 set_ni:
1534                         best_ni = ni;
1535                         best_credits = ni->ni_tx_queues[cpt]->tq_credits;
1536                 }
1537         }
1538         /*
1539          * Now that we selected the NI to use increment its sequence
1540          * number so the Round Robin algorithm will detect that it has
1541          * been used and pick the next NI.
1542          */
1543         best_ni->ni_seq++;
1544
1545         if (!best_ni) {
1546                 lnet_net_unlock(cpt);
1547                 LCONSOLE_WARN("No local ni found to send from to %s\n",
1548                         libcfs_nid2str(dst_nid));
1549                 return -EINVAL;
1550         }
1551
1552         if (routing)
1553                 goto send;
1554
1555 pick_peer:
1556         if (best_ni == the_lnet.ln_loni) {
1557                 /* No send credit hassles with LOLND */
1558                 lnet_ni_addref_locked(best_ni, cpt);
1559                 msg->msg_hdr.dest_nid = cpu_to_le64(best_ni->ni_nid);
1560                 if (!msg->msg_routing)
1561                         msg->msg_hdr.src_nid = cpu_to_le64(best_ni->ni_nid);
1562                 msg->msg_target.nid = best_ni->ni_nid;
1563                 lnet_msg_commit(msg, cpt);
1564
1565                 lnet_net_unlock(cpt);
1566                 msg->msg_txni = best_ni;
1567                 lnet_ni_send(best_ni, msg);
1568
1569                 *lo_sent = true;
1570                 return 0;
1571         }
1572
1573         lpni = NULL;
1574
1575         if (msg->msg_type == LNET_MSG_REPLY ||
1576             msg->msg_type == LNET_MSG_ACK) {
1577                 /*
1578                  * for replies we want to respond on the same peer_ni we
1579                  * received the message on if possible. If not, then pick
1580                  * a peer_ni to send to
1581                  */
1582                 best_lpni = lnet_find_peer_ni_locked(dst_nid);
1583                 if (best_lpni) {
1584                         lnet_peer_ni_decref_locked(best_lpni);
1585                         goto send;
1586                 } else {
1587                         CDEBUG(D_NET, "unable to send msg_type %d to "
1588                               "originating %s\n", msg->msg_type,
1589                               libcfs_nid2str(dst_nid));
1590                 }
1591         }
1592
1593         peer_net = lnet_peer_get_net_locked(peer,
1594                                             best_ni->ni_net->net_id);
1595         /*
1596          * peer_net is not available or the src_nid is explicitly defined
1597          * and the peer_net for that src_nid is unhealthy. find a route to
1598          * the destination nid.
1599          */
1600         if (!peer_net ||
1601             (src_nid != LNET_NID_ANY &&
1602              !lnet_is_peer_net_healthy_locked(peer_net))) {
1603                 best_gw = lnet_find_route_locked(best_ni->ni_net,
1604                                                  dst_nid,
1605                                                  rtr_nid);
1606                 /*
1607                  * if no route is found for that network then
1608                  * move onto the next peer_ni in the peer
1609                  */
1610                 if (!best_gw) {
1611                         lnet_net_unlock(cpt);
1612                         LCONSOLE_WARN("No route to peer from %s\n",
1613                                 libcfs_nid2str(best_ni->ni_nid));
1614                         return -EHOSTUNREACH;
1615                 }
1616
1617                 CDEBUG(D_NET, "Best route to %s via %s for %s %d\n",
1618                         libcfs_nid2str(lpni->lpni_nid),
1619                         libcfs_nid2str(best_gw->lpni_nid),
1620                         lnet_msgtyp2str(msg->msg_type), msg->msg_len);
1621
1622                 best_lpni = lnet_find_peer_ni_locked(dst_nid);
1623                 LASSERT(best_lpni != NULL);
1624                 lnet_peer_ni_decref_locked(best_lpni);
1625
1626                 routing = true;
1627
1628                 goto send;
1629         } else if (!lnet_is_peer_net_healthy_locked(peer_net)) {
1630                 /*
1631                  * this peer_net is unhealthy but we still have an opportunity
1632                  * to find another peer_net that we can use
1633                  */
1634                 __u32 net_id = peer_net->lpn_net_id;
1635                 lnet_net_unlock(cpt);
1636                 if (!best_lpni)
1637                         LCONSOLE_WARN("peer net %s unhealthy\n",
1638                                       libcfs_net2str(net_id));
1639                 goto again;
1640         }
1641
1642         best_lpni = NULL;
1643         while ((lpni = lnet_get_next_peer_ni_locked(peer, peer_net, lpni))) {
1644                 /*
1645                  * if this peer ni is not healthy just skip it, no point in
1646                  * examining it further
1647                  */
1648                 if (!lnet_is_peer_ni_healthy_locked(lpni))
1649                         continue;
1650                 ni_is_pref = lnet_peer_is_ni_pref_locked(lpni, best_ni);
1651
1652                 /* if this is a preferred peer use it */
1653                 if (!preferred && ni_is_pref) {
1654                         preferred = true;
1655                 } else if (preferred && !ni_is_pref) {
1656                         /*
1657                          * this is not the preferred peer so let's ignore
1658                          * it.
1659                          */
1660                         continue;
1661                 } if (lpni->lpni_txcredits < best_lpni_credits)
1662                         /*
1663                          * We already have a peer that has more credits
1664                          * available than this one. No need to consider
1665                          * this peer further.
1666                          */
1667                         continue;
1668                 else if (lpni->lpni_txcredits == best_lpni_credits) {
1669                         /*
1670                          * The best peer found so far and the current peer
1671                          * have the same number of available credits let's
1672                          * make sure to select between them using Round
1673                          * Robin
1674                          */
1675                         if (best_lpni) {
1676                                 if (best_lpni->lpni_seq <= lpni->lpni_seq)
1677                                         continue;
1678                         }
1679                 }
1680
1681                 best_lpni = lpni;
1682                 best_lpni_credits = lpni->lpni_txcredits;
1683         }
1684
1685         /*
1686          * Increment sequence number of the peer selected so that we can
1687          * pick the next one in Round Robin.
1688          */
1689         best_lpni->lpni_seq++;
1690
1691         /* if we still can't find a peer ni then we can't reach it */
1692         if (!best_lpni) {
1693                 __u32 net_id = peer_net->lpn_net_id;
1694                 lnet_net_unlock(cpt);
1695                 LCONSOLE_WARN("no peer_ni found on peer net %s\n",
1696                                 libcfs_net2str(net_id));
1697                 return -EHOSTUNREACH;
1698         }
1699
1700 send:
1701         /*
1702          * determine the cpt to use and if it has changed then
1703          * lock the new cpt and check if the config has changed.
1704          * If it has changed then repeat the algorithm since the
1705          * ni or peer list could have changed and the algorithm
1706          * would endup picking a different ni/peer_ni pair.
1707          */
1708         cpt2 = best_lpni->lpni_cpt;
1709         if (cpt != cpt2) {
1710                 lnet_net_unlock(cpt);
1711                 cpt = cpt2;
1712                 lnet_net_lock(cpt);
1713                 seq2 = lnet_get_dlc_seq_locked();
1714                 if (seq2 != seq) {
1715                         lnet_net_unlock(cpt);
1716                         goto again;
1717                 }
1718         }
1719
1720         /*
1721          * store the best_lpni in the message right away to avoid having
1722          * to do the same operation under different conditions
1723          */
1724         msg->msg_txpeer = (routing) ? best_gw : best_lpni;
1725         msg->msg_txni = best_ni;
1726         /*
1727          * grab a reference for the best_ni since now it's in use in this
1728          * send. the reference will need to be dropped when the message is
1729          * finished in lnet_finalize()
1730          */
1731         lnet_ni_addref_locked(msg->msg_txni, cpt);
1732         lnet_peer_ni_addref_locked(msg->msg_txpeer);
1733
1734         /*
1735          * set the destination nid in the message here because it's
1736          * possible that we'd be sending to a different nid than the one
1737          * originaly given.
1738          */
1739         msg->msg_hdr.dest_nid = cpu_to_le64(msg->msg_txpeer->lpni_nid);
1740
1741         /*
1742          * Always set the target.nid to the best peer picked. Either the
1743          * nid will be one of the preconfigured NIDs, or the same NID as
1744          * what was originaly set in the target or it will be the NID of
1745          * a router if this message should be routed
1746          */
1747         msg->msg_target.nid = msg->msg_txpeer->lpni_nid;
1748
1749         /*
1750          * lnet_msg_commit assigns the correct cpt to the message, which
1751          * is used to decrement the correct refcount on the ni when it's
1752          * time to return the credits
1753          */
1754         lnet_msg_commit(msg, cpt);
1755
1756         /*
1757          * If we are routing the message then we don't need to overwrite
1758          * the src_nid since it would've been set at the origin. Otherwise
1759          * we are the originator so we need to set it.
1760          */
1761         if (!msg->msg_routing)
1762                 msg->msg_hdr.src_nid = cpu_to_le64(msg->msg_txni->ni_nid);
1763
1764         if (routing) {
1765                 msg->msg_target_is_router = 1;
1766                 msg->msg_target.pid = LNET_PID_LUSTRE;
1767         }
1768
1769         rc = lnet_post_send_locked(msg, 0);
1770
1771         lnet_net_unlock(cpt);
1772
1773         return rc;
1774 }
1775
1776 int
1777 lnet_send(lnet_nid_t src_nid, lnet_msg_t *msg, lnet_nid_t rtr_nid)
1778 {
1779         lnet_nid_t              dst_nid = msg->msg_target.nid;
1780         int                     rc;
1781         bool                    lo_sent = false;
1782
1783         /*
1784          * NB: rtr_nid is set to LNET_NID_ANY for all current use-cases,
1785          * but we might want to use pre-determined router for ACK/REPLY
1786          * in the future
1787          */
1788         /* NB: ni != NULL == interface pre-determined (ACK/REPLY) */
1789         LASSERT (msg->msg_txpeer == NULL);
1790         LASSERT (!msg->msg_sending);
1791         LASSERT (!msg->msg_target_is_router);
1792         LASSERT (!msg->msg_receiving);
1793
1794         msg->msg_sending = 1;
1795
1796         LASSERT(!msg->msg_tx_committed);
1797
1798         rc = lnet_select_pathway(src_nid, dst_nid, msg, rtr_nid, &lo_sent);
1799         if (rc < 0 || lo_sent)
1800                 return rc;
1801
1802         if (rc == LNET_CREDIT_OK)
1803                 lnet_ni_send(msg->msg_txni, msg);
1804
1805         /* rc == LNET_CREDIT_OK or LNET_CREDIT_WAIT */
1806         return 0;
1807 }
1808
1809 void
1810 lnet_drop_message(lnet_ni_t *ni, int cpt, void *private, unsigned int nob)
1811 {
1812         lnet_net_lock(cpt);
1813         the_lnet.ln_counters[cpt]->drop_count++;
1814         the_lnet.ln_counters[cpt]->drop_length += nob;
1815         lnet_net_unlock(cpt);
1816
1817         lnet_ni_recv(ni, private, NULL, 0, 0, 0, nob);
1818 }
1819
1820 static void
1821 lnet_recv_put(lnet_ni_t *ni, lnet_msg_t *msg)
1822 {
1823         lnet_hdr_t      *hdr = &msg->msg_hdr;
1824
1825         if (msg->msg_wanted != 0)
1826                 lnet_setpayloadbuffer(msg);
1827
1828         lnet_build_msg_event(msg, LNET_EVENT_PUT);
1829
1830         /* Must I ACK?  If so I'll grab the ack_wmd out of the header and put
1831          * it back into the ACK during lnet_finalize() */
1832         msg->msg_ack = (!lnet_is_wire_handle_none(&hdr->msg.put.ack_wmd) &&
1833                         (msg->msg_md->md_options & LNET_MD_ACK_DISABLE) == 0);
1834
1835         lnet_ni_recv(ni, msg->msg_private, msg, msg->msg_rx_delayed,
1836                      msg->msg_offset, msg->msg_wanted, hdr->payload_length);
1837 }
1838
1839 static int
1840 lnet_parse_put(lnet_ni_t *ni, lnet_msg_t *msg)
1841 {
1842         lnet_hdr_t              *hdr = &msg->msg_hdr;
1843         struct lnet_match_info  info;
1844         int                     rc;
1845         bool                    ready_delay;
1846
1847         /* Convert put fields to host byte order */
1848         hdr->msg.put.match_bits = le64_to_cpu(hdr->msg.put.match_bits);
1849         hdr->msg.put.ptl_index  = le32_to_cpu(hdr->msg.put.ptl_index);
1850         hdr->msg.put.offset     = le32_to_cpu(hdr->msg.put.offset);
1851
1852         /* Primary peer NID. */
1853         info.mi_id.nid  = msg->msg_initiator;
1854         info.mi_id.pid  = hdr->src_pid;
1855         info.mi_opc     = LNET_MD_OP_PUT;
1856         info.mi_portal  = hdr->msg.put.ptl_index;
1857         info.mi_rlength = hdr->payload_length;
1858         info.mi_roffset = hdr->msg.put.offset;
1859         info.mi_mbits   = hdr->msg.put.match_bits;
1860         info.mi_cpt     = msg->msg_rxpeer->lpni_cpt;
1861
1862         msg->msg_rx_ready_delay = ni->ni_net->net_lnd->lnd_eager_recv == NULL;
1863         ready_delay = msg->msg_rx_ready_delay;
1864
1865  again:
1866         rc = lnet_ptl_match_md(&info, msg);
1867         switch (rc) {
1868         default:
1869                 LBUG();
1870
1871         case LNET_MATCHMD_OK:
1872                 lnet_recv_put(ni, msg);
1873                 return 0;
1874
1875         case LNET_MATCHMD_NONE:
1876                 if (ready_delay)
1877                         /* no eager_recv or has already called it, should
1878                          * have been attached on delayed list */
1879                         return 0;
1880
1881                 rc = lnet_ni_eager_recv(ni, msg);
1882                 if (rc == 0) {
1883                         ready_delay = true;
1884                         goto again;
1885                 }
1886                 /* fall through */
1887
1888         case LNET_MATCHMD_DROP:
1889                 CNETERR("Dropping PUT from %s portal %d match %llu"
1890                         " offset %d length %d: %d\n",
1891                         libcfs_id2str(info.mi_id), info.mi_portal,
1892                         info.mi_mbits, info.mi_roffset, info.mi_rlength, rc);
1893
1894                 return -ENOENT; /* -ve: OK but no match */
1895         }
1896 }
1897
1898 static int
1899 lnet_parse_get(lnet_ni_t *ni, lnet_msg_t *msg, int rdma_get)
1900 {
1901         struct lnet_match_info  info;
1902         lnet_hdr_t              *hdr = &msg->msg_hdr;
1903         lnet_process_id_t       source_id;
1904         struct lnet_handle_wire reply_wmd;
1905         int                     rc;
1906
1907         /* Convert get fields to host byte order */
1908         hdr->msg.get.match_bits   = le64_to_cpu(hdr->msg.get.match_bits);
1909         hdr->msg.get.ptl_index    = le32_to_cpu(hdr->msg.get.ptl_index);
1910         hdr->msg.get.sink_length  = le32_to_cpu(hdr->msg.get.sink_length);
1911         hdr->msg.get.src_offset   = le32_to_cpu(hdr->msg.get.src_offset);
1912
1913         source_id.nid = hdr->src_nid;
1914         source_id.pid = hdr->src_pid;
1915         /* Primary peer NID */
1916         info.mi_id.nid  = msg->msg_initiator;
1917         info.mi_id.pid  = hdr->src_pid;
1918         info.mi_opc     = LNET_MD_OP_GET;
1919         info.mi_portal  = hdr->msg.get.ptl_index;
1920         info.mi_rlength = hdr->msg.get.sink_length;
1921         info.mi_roffset = hdr->msg.get.src_offset;
1922         info.mi_mbits   = hdr->msg.get.match_bits;
1923
1924         rc = lnet_ptl_match_md(&info, msg);
1925         if (rc == LNET_MATCHMD_DROP) {
1926                 CNETERR("Dropping GET from %s portal %d match %llu"
1927                         " offset %d length %d\n",
1928                         libcfs_id2str(info.mi_id), info.mi_portal,
1929                         info.mi_mbits, info.mi_roffset, info.mi_rlength);
1930                 return -ENOENT; /* -ve: OK but no match */
1931         }
1932
1933         LASSERT(rc == LNET_MATCHMD_OK);
1934
1935         lnet_build_msg_event(msg, LNET_EVENT_GET);
1936
1937         reply_wmd = hdr->msg.get.return_wmd;
1938
1939         lnet_prep_send(msg, LNET_MSG_REPLY, source_id,
1940                        msg->msg_offset, msg->msg_wanted);
1941
1942         msg->msg_hdr.msg.reply.dst_wmd = reply_wmd;
1943
1944         if (rdma_get) {
1945                 /* The LND completes the REPLY from her recv procedure */
1946                 lnet_ni_recv(ni, msg->msg_private, msg, 0,
1947                              msg->msg_offset, msg->msg_len, msg->msg_len);
1948                 return 0;
1949         }
1950
1951         lnet_ni_recv(ni, msg->msg_private, NULL, 0, 0, 0, 0);
1952         msg->msg_receiving = 0;
1953
1954         rc = lnet_send(ni->ni_nid, msg, LNET_NID_ANY);
1955         if (rc < 0) {
1956                 /* didn't get as far as lnet_ni_send() */
1957                 CERROR("%s: Unable to send REPLY for GET from %s: %d\n",
1958                        libcfs_nid2str(ni->ni_nid),
1959                        libcfs_id2str(info.mi_id), rc);
1960
1961                 lnet_finalize(ni, msg, rc);
1962         }
1963
1964         return 0;
1965 }
1966
1967 static int
1968 lnet_parse_reply(lnet_ni_t *ni, lnet_msg_t *msg)
1969 {
1970         void             *private = msg->msg_private;
1971         lnet_hdr_t       *hdr = &msg->msg_hdr;
1972         lnet_process_id_t src = {0};
1973         lnet_libmd_t     *md;
1974         int               rlength;
1975         int               mlength;
1976         int                     cpt;
1977
1978         cpt = lnet_cpt_of_cookie(hdr->msg.reply.dst_wmd.wh_object_cookie);
1979         lnet_res_lock(cpt);
1980
1981         src.nid = hdr->src_nid;
1982         src.pid = hdr->src_pid;
1983
1984         /* NB handles only looked up by creator (no flips) */
1985         md = lnet_wire_handle2md(&hdr->msg.reply.dst_wmd);
1986         if (md == NULL || md->md_threshold == 0 || md->md_me != NULL) {
1987                 CNETERR("%s: Dropping REPLY from %s for %s "
1988                         "MD %#llx.%#llx\n",
1989                         libcfs_nid2str(ni->ni_nid), libcfs_id2str(src),
1990                         (md == NULL) ? "invalid" : "inactive",
1991                         hdr->msg.reply.dst_wmd.wh_interface_cookie,
1992                         hdr->msg.reply.dst_wmd.wh_object_cookie);
1993                 if (md != NULL && md->md_me != NULL)
1994                         CERROR("REPLY MD also attached to portal %d\n",
1995                                md->md_me->me_portal);
1996
1997                 lnet_res_unlock(cpt);
1998                 return -ENOENT; /* -ve: OK but no match */
1999         }
2000
2001         LASSERT(md->md_offset == 0);
2002
2003         rlength = hdr->payload_length;
2004         mlength = MIN(rlength, (int)md->md_length);
2005
2006         if (mlength < rlength &&
2007             (md->md_options & LNET_MD_TRUNCATE) == 0) {
2008                 CNETERR("%s: Dropping REPLY from %s length %d "
2009                         "for MD %#llx would overflow (%d)\n",
2010                         libcfs_nid2str(ni->ni_nid), libcfs_id2str(src),
2011                         rlength, hdr->msg.reply.dst_wmd.wh_object_cookie,
2012                         mlength);
2013                 lnet_res_unlock(cpt);
2014                 return -ENOENT; /* -ve: OK but no match */
2015         }
2016
2017         CDEBUG(D_NET, "%s: Reply from %s of length %d/%d into md %#llx\n",
2018                libcfs_nid2str(ni->ni_nid), libcfs_id2str(src),
2019                mlength, rlength, hdr->msg.reply.dst_wmd.wh_object_cookie);
2020
2021         lnet_msg_attach_md(msg, md, 0, mlength);
2022
2023         if (mlength != 0)
2024                 lnet_setpayloadbuffer(msg);
2025
2026         lnet_res_unlock(cpt);
2027
2028         lnet_build_msg_event(msg, LNET_EVENT_REPLY);
2029
2030         lnet_ni_recv(ni, private, msg, 0, 0, mlength, rlength);
2031         return 0;
2032 }
2033
2034 static int
2035 lnet_parse_ack(lnet_ni_t *ni, lnet_msg_t *msg)
2036 {
2037         lnet_hdr_t       *hdr = &msg->msg_hdr;
2038         lnet_process_id_t src = {0};
2039         lnet_libmd_t     *md;
2040         int                     cpt;
2041
2042         src.nid = hdr->src_nid;
2043         src.pid = hdr->src_pid;
2044
2045         /* Convert ack fields to host byte order */
2046         hdr->msg.ack.match_bits = le64_to_cpu(hdr->msg.ack.match_bits);
2047         hdr->msg.ack.mlength = le32_to_cpu(hdr->msg.ack.mlength);
2048
2049         cpt = lnet_cpt_of_cookie(hdr->msg.ack.dst_wmd.wh_object_cookie);
2050         lnet_res_lock(cpt);
2051
2052         /* NB handles only looked up by creator (no flips) */
2053         md = lnet_wire_handle2md(&hdr->msg.ack.dst_wmd);
2054         if (md == NULL || md->md_threshold == 0 || md->md_me != NULL) {
2055                 /* Don't moan; this is expected */
2056                 CDEBUG(D_NET,
2057                        "%s: Dropping ACK from %s to %s MD %#llx.%#llx\n",
2058                        libcfs_nid2str(ni->ni_nid), libcfs_id2str(src),
2059                        (md == NULL) ? "invalid" : "inactive",
2060                        hdr->msg.ack.dst_wmd.wh_interface_cookie,
2061                        hdr->msg.ack.dst_wmd.wh_object_cookie);
2062                 if (md != NULL && md->md_me != NULL)
2063                         CERROR("Source MD also attached to portal %d\n",
2064                                md->md_me->me_portal);
2065
2066                 lnet_res_unlock(cpt);
2067                 return -ENOENT;                  /* -ve! */
2068         }
2069
2070         CDEBUG(D_NET, "%s: ACK from %s into md %#llx\n",
2071                libcfs_nid2str(ni->ni_nid), libcfs_id2str(src),
2072                hdr->msg.ack.dst_wmd.wh_object_cookie);
2073
2074         lnet_msg_attach_md(msg, md, 0, 0);
2075
2076         lnet_res_unlock(cpt);
2077
2078         lnet_build_msg_event(msg, LNET_EVENT_ACK);
2079
2080         lnet_ni_recv(ni, msg->msg_private, msg, 0, 0, 0, msg->msg_len);
2081         return 0;
2082 }
2083
2084 /**
2085  * \retval LNET_CREDIT_OK       If \a msg is forwarded
2086  * \retval LNET_CREDIT_WAIT     If \a msg is blocked because w/o buffer
2087  * \retval -ve                  error code
2088  */
2089 int
2090 lnet_parse_forward_locked(lnet_ni_t *ni, lnet_msg_t *msg)
2091 {
2092         int     rc = 0;
2093
2094         if (!the_lnet.ln_routing)
2095                 return -ECANCELED;
2096
2097         if (msg->msg_rxpeer->lpni_rtrcredits <= 0 ||
2098             lnet_msg2bufpool(msg)->rbp_credits <= 0) {
2099                 if (ni->ni_net->net_lnd->lnd_eager_recv == NULL) {
2100                         msg->msg_rx_ready_delay = 1;
2101                 } else {
2102                         lnet_net_unlock(msg->msg_rx_cpt);
2103                         rc = lnet_ni_eager_recv(ni, msg);
2104                         lnet_net_lock(msg->msg_rx_cpt);
2105                 }
2106         }
2107
2108         if (rc == 0)
2109                 rc = lnet_post_routed_recv_locked(msg, 0);
2110         return rc;
2111 }
2112
2113 int
2114 lnet_parse_local(lnet_ni_t *ni, lnet_msg_t *msg)
2115 {
2116         int     rc;
2117
2118         switch (msg->msg_type) {
2119         case LNET_MSG_ACK:
2120                 rc = lnet_parse_ack(ni, msg);
2121                 break;
2122         case LNET_MSG_PUT:
2123                 rc = lnet_parse_put(ni, msg);
2124                 break;
2125         case LNET_MSG_GET:
2126                 rc = lnet_parse_get(ni, msg, msg->msg_rdma_get);
2127                 break;
2128         case LNET_MSG_REPLY:
2129                 rc = lnet_parse_reply(ni, msg);
2130                 break;
2131         default: /* prevent an unused label if !kernel */
2132                 LASSERT(0);
2133                 return -EPROTO;
2134         }
2135
2136         LASSERT(rc == 0 || rc == -ENOENT);
2137         return rc;
2138 }
2139
2140 char *
2141 lnet_msgtyp2str (int type)
2142 {
2143         switch (type) {
2144         case LNET_MSG_ACK:
2145                 return ("ACK");
2146         case LNET_MSG_PUT:
2147                 return ("PUT");
2148         case LNET_MSG_GET:
2149                 return ("GET");
2150         case LNET_MSG_REPLY:
2151                 return ("REPLY");
2152         case LNET_MSG_HELLO:
2153                 return ("HELLO");
2154         default:
2155                 return ("<UNKNOWN>");
2156         }
2157 }
2158
2159 void
2160 lnet_print_hdr(lnet_hdr_t * hdr)
2161 {
2162         lnet_process_id_t src = {0};
2163         lnet_process_id_t dst = {0};
2164         char *type_str = lnet_msgtyp2str(hdr->type);
2165
2166         src.nid = hdr->src_nid;
2167         src.pid = hdr->src_pid;
2168
2169         dst.nid = hdr->dest_nid;
2170         dst.pid = hdr->dest_pid;
2171
2172         CWARN("P3 Header at %p of type %s\n", hdr, type_str);
2173         CWARN("    From %s\n", libcfs_id2str(src));
2174         CWARN("    To   %s\n", libcfs_id2str(dst));
2175
2176         switch (hdr->type) {
2177         default:
2178                 break;
2179
2180         case LNET_MSG_PUT:
2181                 CWARN("    Ptl index %d, ack md %#llx.%#llx, "
2182                       "match bits %llu\n",
2183                       hdr->msg.put.ptl_index,
2184                       hdr->msg.put.ack_wmd.wh_interface_cookie,
2185                       hdr->msg.put.ack_wmd.wh_object_cookie,
2186                       hdr->msg.put.match_bits);
2187                 CWARN("    Length %d, offset %d, hdr data %#llx\n",
2188                       hdr->payload_length, hdr->msg.put.offset,
2189                       hdr->msg.put.hdr_data);
2190                 break;
2191
2192         case LNET_MSG_GET:
2193                 CWARN("    Ptl index %d, return md %#llx.%#llx, "
2194                       "match bits %llu\n", hdr->msg.get.ptl_index,
2195                       hdr->msg.get.return_wmd.wh_interface_cookie,
2196                       hdr->msg.get.return_wmd.wh_object_cookie,
2197                       hdr->msg.get.match_bits);
2198                 CWARN("    Length %d, src offset %d\n",
2199                       hdr->msg.get.sink_length,
2200                       hdr->msg.get.src_offset);
2201                 break;
2202
2203         case LNET_MSG_ACK:
2204                 CWARN("    dst md %#llx.%#llx, "
2205                       "manipulated length %d\n",
2206                       hdr->msg.ack.dst_wmd.wh_interface_cookie,
2207                       hdr->msg.ack.dst_wmd.wh_object_cookie,
2208                       hdr->msg.ack.mlength);
2209                 break;
2210
2211         case LNET_MSG_REPLY:
2212                 CWARN("    dst md %#llx.%#llx, "
2213                       "length %d\n",
2214                       hdr->msg.reply.dst_wmd.wh_interface_cookie,
2215                       hdr->msg.reply.dst_wmd.wh_object_cookie,
2216                       hdr->payload_length);
2217         }
2218
2219 }
2220
2221 int
2222 lnet_parse(lnet_ni_t *ni, lnet_hdr_t *hdr, lnet_nid_t from_nid,
2223            void *private, int rdma_req)
2224 {
2225         int             rc = 0;
2226         int             cpt;
2227         int             for_me;
2228         struct lnet_msg *msg;
2229         lnet_pid_t     dest_pid;
2230         lnet_nid_t     dest_nid;
2231         lnet_nid_t     src_nid;
2232         __u32          payload_length;
2233         __u32          type;
2234
2235         LASSERT (!in_interrupt ());
2236
2237         type = le32_to_cpu(hdr->type);
2238         src_nid = le64_to_cpu(hdr->src_nid);
2239         dest_nid = le64_to_cpu(hdr->dest_nid);
2240         dest_pid = le32_to_cpu(hdr->dest_pid);
2241         payload_length = le32_to_cpu(hdr->payload_length);
2242
2243         for_me = (ni->ni_nid == dest_nid);
2244         cpt = lnet_cpt_of_nid(from_nid, ni);
2245
2246         switch (type) {
2247         case LNET_MSG_ACK:
2248         case LNET_MSG_GET:
2249                 if (payload_length > 0) {
2250                         CERROR("%s, src %s: bad %s payload %d (0 expected)\n",
2251                                libcfs_nid2str(from_nid),
2252                                libcfs_nid2str(src_nid),
2253                                lnet_msgtyp2str(type), payload_length);
2254                         return -EPROTO;
2255                 }
2256                 break;
2257
2258         case LNET_MSG_PUT:
2259         case LNET_MSG_REPLY:
2260                 if (payload_length >
2261                     (__u32)(for_me ? LNET_MAX_PAYLOAD : LNET_MTU)) {
2262                         CERROR("%s, src %s: bad %s payload %d "
2263                                "(%d max expected)\n",
2264                                libcfs_nid2str(from_nid),
2265                                libcfs_nid2str(src_nid),
2266                                lnet_msgtyp2str(type),
2267                                payload_length,
2268                                for_me ? LNET_MAX_PAYLOAD : LNET_MTU);
2269                         return -EPROTO;
2270                 }
2271                 break;
2272
2273         default:
2274                 CERROR("%s, src %s: Bad message type 0x%x\n",
2275                        libcfs_nid2str(from_nid),
2276                        libcfs_nid2str(src_nid), type);
2277                 return -EPROTO;
2278         }
2279
2280         if (the_lnet.ln_routing &&
2281             ni->ni_last_alive != ktime_get_real_seconds()) {
2282                 /* NB: so far here is the only place to set NI status to "up */
2283                 lnet_ni_lock(ni);
2284                 ni->ni_last_alive = ktime_get_real_seconds();
2285                 if (ni->ni_status != NULL &&
2286                     ni->ni_status->ns_status == LNET_NI_STATUS_DOWN)
2287                         ni->ni_status->ns_status = LNET_NI_STATUS_UP;
2288                 lnet_ni_unlock(ni);
2289         }
2290
2291         /* Regard a bad destination NID as a protocol error.  Senders should
2292          * know what they're doing; if they don't they're misconfigured, buggy
2293          * or malicious so we chop them off at the knees :) */
2294
2295         if (!for_me) {
2296                 if (LNET_NIDNET(dest_nid) == LNET_NIDNET(ni->ni_nid)) {
2297                         /* should have gone direct */
2298                         CERROR("%s, src %s: Bad dest nid %s "
2299                                "(should have been sent direct)\n",
2300                                 libcfs_nid2str(from_nid),
2301                                 libcfs_nid2str(src_nid),
2302                                 libcfs_nid2str(dest_nid));
2303                         return -EPROTO;
2304                 }
2305
2306                 if (lnet_islocalnid(dest_nid)) {
2307                         /* dest is another local NI; sender should have used
2308                          * this node's NID on its own network */
2309                         CERROR("%s, src %s: Bad dest nid %s "
2310                                "(it's my nid but on a different network)\n",
2311                                 libcfs_nid2str(from_nid),
2312                                 libcfs_nid2str(src_nid),
2313                                 libcfs_nid2str(dest_nid));
2314                         return -EPROTO;
2315                 }
2316
2317                 if (rdma_req && type == LNET_MSG_GET) {
2318                         CERROR("%s, src %s: Bad optimized GET for %s "
2319                                "(final destination must be me)\n",
2320                                 libcfs_nid2str(from_nid),
2321                                 libcfs_nid2str(src_nid),
2322                                 libcfs_nid2str(dest_nid));
2323                         return -EPROTO;
2324                 }
2325
2326                 if (!the_lnet.ln_routing) {
2327                         CERROR("%s, src %s: Dropping message for %s "
2328                                "(routing not enabled)\n",
2329                                 libcfs_nid2str(from_nid),
2330                                 libcfs_nid2str(src_nid),
2331                                 libcfs_nid2str(dest_nid));
2332                         goto drop;
2333                 }
2334         }
2335
2336         /* Message looks OK; we're not going to return an error, so we MUST
2337          * call back lnd_recv() come what may... */
2338
2339         if (!list_empty(&the_lnet.ln_test_peers) &&     /* normally we don't */
2340             fail_peer(src_nid, 0)) {                    /* shall we now? */
2341                 CERROR("%s, src %s: Dropping %s to simulate failure\n",
2342                        libcfs_nid2str(from_nid), libcfs_nid2str(src_nid),
2343                        lnet_msgtyp2str(type));
2344                 goto drop;
2345         }
2346
2347         if (!list_empty(&the_lnet.ln_drop_rules) &&
2348             lnet_drop_rule_match(hdr)) {
2349                 CDEBUG(D_NET, "%s, src %s, dst %s: Dropping %s to simulate"
2350                               "silent message loss\n",
2351                        libcfs_nid2str(from_nid), libcfs_nid2str(src_nid),
2352                        libcfs_nid2str(dest_nid), lnet_msgtyp2str(type));
2353                 goto drop;
2354         }
2355
2356
2357         msg = lnet_msg_alloc();
2358         if (msg == NULL) {
2359                 CERROR("%s, src %s: Dropping %s (out of memory)\n",
2360                        libcfs_nid2str(from_nid), libcfs_nid2str(src_nid),
2361                        lnet_msgtyp2str(type));
2362                 goto drop;
2363         }
2364
2365         /* msg zeroed in lnet_msg_alloc; i.e. flags all clear,
2366          * pointers NULL etc */
2367
2368         msg->msg_type = type;
2369         msg->msg_private = private;
2370         msg->msg_receiving = 1;
2371         msg->msg_rdma_get = rdma_req;
2372         msg->msg_len = msg->msg_wanted = payload_length;
2373         msg->msg_offset = 0;
2374         msg->msg_hdr = *hdr;
2375         /* for building message event */
2376         msg->msg_from = from_nid;
2377         if (!for_me) {
2378                 msg->msg_target.pid     = dest_pid;
2379                 msg->msg_target.nid     = dest_nid;
2380                 msg->msg_routing        = 1;
2381
2382         } else {
2383                 /* convert common msg->hdr fields to host byteorder */
2384                 msg->msg_hdr.type       = type;
2385                 msg->msg_hdr.src_nid    = src_nid;
2386                 msg->msg_hdr.src_pid    = le32_to_cpu(msg->msg_hdr.src_pid);
2387                 msg->msg_hdr.dest_nid   = dest_nid;
2388                 msg->msg_hdr.dest_pid   = dest_pid;
2389                 msg->msg_hdr.payload_length = payload_length;
2390         }
2391         /* Multi-Rail: Primary NID of source. */
2392         msg->msg_initiator = lnet_peer_primary_nid(src_nid);
2393
2394         lnet_net_lock(cpt);
2395         rc = lnet_nid2peerni_locked(&msg->msg_rxpeer, from_nid, cpt);
2396         if (rc != 0) {
2397                 lnet_net_unlock(cpt);
2398                 CERROR("%s, src %s: Dropping %s "
2399                        "(error %d looking up sender)\n",
2400                        libcfs_nid2str(from_nid), libcfs_nid2str(src_nid),
2401                        lnet_msgtyp2str(type), rc);
2402                 lnet_msg_free(msg);
2403                 if (rc == -ESHUTDOWN)
2404                         /* We are shutting down.  Don't do anything more */
2405                         return 0;
2406                 goto drop;
2407         }
2408         msg->msg_rxni = ni;
2409         lnet_ni_addref_locked(ni, cpt);
2410
2411         if (lnet_isrouter(msg->msg_rxpeer)) {
2412                 lnet_peer_set_alive(msg->msg_rxpeer);
2413                 if (avoid_asym_router_failure &&
2414                     LNET_NIDNET(src_nid) != LNET_NIDNET(from_nid)) {
2415                         /* received a remote message from router, update
2416                          * remote NI status on this router.
2417                          * NB: multi-hop routed message will be ignored.
2418                          */
2419                         lnet_router_ni_update_locked(msg->msg_rxpeer,
2420                                                      LNET_NIDNET(src_nid));
2421                 }
2422         }
2423
2424         lnet_msg_commit(msg, cpt);
2425
2426         /* message delay simulation */
2427         if (unlikely(!list_empty(&the_lnet.ln_delay_rules) &&
2428                      lnet_delay_rule_match_locked(hdr, msg))) {
2429                 lnet_net_unlock(cpt);
2430                 return 0;
2431         }
2432
2433         if (!for_me) {
2434                 rc = lnet_parse_forward_locked(ni, msg);
2435                 lnet_net_unlock(cpt);
2436
2437                 if (rc < 0)
2438                         goto free_drop;
2439
2440                 if (rc == LNET_CREDIT_OK) {
2441                         lnet_ni_recv(ni, msg->msg_private, msg, 0,
2442                                      0, payload_length, payload_length);
2443                 }
2444                 return 0;
2445         }
2446
2447         lnet_net_unlock(cpt);
2448
2449         rc = lnet_parse_local(ni, msg);
2450         if (rc != 0)
2451                 goto free_drop;
2452         return 0;
2453
2454  free_drop:
2455         LASSERT(msg->msg_md == NULL);
2456         lnet_finalize(ni, msg, rc);
2457
2458  drop:
2459         lnet_drop_message(ni, cpt, private, payload_length);
2460         return 0;
2461 }
2462 EXPORT_SYMBOL(lnet_parse);
2463
2464 void
2465 lnet_drop_delayed_msg_list(struct list_head *head, char *reason)
2466 {
2467         while (!list_empty(head)) {
2468                 lnet_process_id_t       id = {0};
2469                 lnet_msg_t              *msg;
2470
2471                 msg = list_entry(head->next, lnet_msg_t, msg_list);
2472                 list_del(&msg->msg_list);
2473
2474                 id.nid = msg->msg_hdr.src_nid;
2475                 id.pid = msg->msg_hdr.src_pid;
2476
2477                 LASSERT(msg->msg_md == NULL);
2478                 LASSERT(msg->msg_rx_delayed);
2479                 LASSERT(msg->msg_rxpeer != NULL);
2480                 LASSERT(msg->msg_hdr.type == LNET_MSG_PUT);
2481
2482                 CWARN("Dropping delayed PUT from %s portal %d match %llu"
2483                       " offset %d length %d: %s\n",
2484                       libcfs_id2str(id),
2485                       msg->msg_hdr.msg.put.ptl_index,
2486                       msg->msg_hdr.msg.put.match_bits,
2487                       msg->msg_hdr.msg.put.offset,
2488                       msg->msg_hdr.payload_length, reason);
2489
2490                 /* NB I can't drop msg's ref on msg_rxpeer until after I've
2491                  * called lnet_drop_message(), so I just hang onto msg as well
2492                  * until that's done */
2493
2494                 lnet_drop_message(msg->msg_rxni,
2495                                   msg->msg_rxpeer->lpni_cpt,
2496                                   msg->msg_private, msg->msg_len);
2497                 /*
2498                  * NB: message will not generate event because w/o attached MD,
2499                  * but we still should give error code so lnet_msg_decommit()
2500                  * can skip counters operations and other checks.
2501                  */
2502                 lnet_finalize(msg->msg_rxni, msg, -ENOENT);
2503         }
2504 }
2505
2506 void
2507 lnet_recv_delayed_msg_list(struct list_head *head)
2508 {
2509         while (!list_empty(head)) {
2510                 lnet_msg_t        *msg;
2511                 lnet_process_id_t  id;
2512
2513                 msg = list_entry(head->next, lnet_msg_t, msg_list);
2514                 list_del(&msg->msg_list);
2515
2516                 /* md won't disappear under me, since each msg
2517                  * holds a ref on it */
2518
2519                 id.nid = msg->msg_hdr.src_nid;
2520                 id.pid = msg->msg_hdr.src_pid;
2521
2522                 LASSERT(msg->msg_rx_delayed);
2523                 LASSERT(msg->msg_md != NULL);
2524                 LASSERT(msg->msg_rxpeer != NULL);
2525                 LASSERT(msg->msg_rxni != NULL);
2526                 LASSERT(msg->msg_hdr.type == LNET_MSG_PUT);
2527
2528                 CDEBUG(D_NET, "Resuming delayed PUT from %s portal %d "
2529                        "match %llu offset %d length %d.\n",
2530                         libcfs_id2str(id), msg->msg_hdr.msg.put.ptl_index,
2531                         msg->msg_hdr.msg.put.match_bits,
2532                         msg->msg_hdr.msg.put.offset,
2533                         msg->msg_hdr.payload_length);
2534
2535                 lnet_recv_put(msg->msg_rxni, msg);
2536         }
2537 }
2538
2539 /**
2540  * Initiate an asynchronous PUT operation.
2541  *
2542  * There are several events associated with a PUT: completion of the send on
2543  * the initiator node (LNET_EVENT_SEND), and when the send completes
2544  * successfully, the receipt of an acknowledgment (LNET_EVENT_ACK) indicating
2545  * that the operation was accepted by the target. The event LNET_EVENT_PUT is
2546  * used at the target node to indicate the completion of incoming data
2547  * delivery.
2548  *
2549  * The local events will be logged in the EQ associated with the MD pointed to
2550  * by \a mdh handle. Using a MD without an associated EQ results in these
2551  * events being discarded. In this case, the caller must have another
2552  * mechanism (e.g., a higher level protocol) for determining when it is safe
2553  * to modify the memory region associated with the MD.
2554  *
2555  * Note that LNet does not guarantee the order of LNET_EVENT_SEND and
2556  * LNET_EVENT_ACK, though intuitively ACK should happen after SEND.
2557  *
2558  * \param self Indicates the NID of a local interface through which to send
2559  * the PUT request. Use LNET_NID_ANY to let LNet choose one by itself.
2560  * \param mdh A handle for the MD that describes the memory to be sent. The MD
2561  * must be "free floating" (See LNetMDBind()).
2562  * \param ack Controls whether an acknowledgment is requested.
2563  * Acknowledgments are only sent when they are requested by the initiating
2564  * process and the target MD enables them.
2565  * \param target A process identifier for the target process.
2566  * \param portal The index in the \a target's portal table.
2567  * \param match_bits The match bits to use for MD selection at the target
2568  * process.
2569  * \param offset The offset into the target MD (only used when the target
2570  * MD has the LNET_MD_MANAGE_REMOTE option set).
2571  * \param hdr_data 64 bits of user data that can be included in the message
2572  * header. This data is written to an event queue entry at the target if an
2573  * EQ is present on the matching MD.
2574  *
2575  * \retval  0      Success, and only in this case events will be generated
2576  * and logged to EQ (if it exists).
2577  * \retval -EIO    Simulated failure.
2578  * \retval -ENOMEM Memory allocation failure.
2579  * \retval -ENOENT Invalid MD object.
2580  *
2581  * \see lnet_event_t::hdr_data and lnet_event_kind_t.
2582  */
2583 int
2584 LNetPut(lnet_nid_t self, lnet_handle_md_t mdh, lnet_ack_req_t ack,
2585         lnet_process_id_t target, unsigned int portal,
2586         __u64 match_bits, unsigned int offset,
2587         __u64 hdr_data)
2588 {
2589         struct lnet_msg         *msg;
2590         struct lnet_libmd       *md;
2591         int                     cpt;
2592         int                     rc;
2593
2594         LASSERT(the_lnet.ln_refcount > 0);
2595
2596         if (!list_empty(&the_lnet.ln_test_peers) &&     /* normally we don't */
2597             fail_peer(target.nid, 1)) {                 /* shall we now? */
2598                 CERROR("Dropping PUT to %s: simulated failure\n",
2599                        libcfs_id2str(target));
2600                 return -EIO;
2601         }
2602
2603         msg = lnet_msg_alloc();
2604         if (msg == NULL) {
2605                 CERROR("Dropping PUT to %s: ENOMEM on lnet_msg_t\n",
2606                        libcfs_id2str(target));
2607                 return -ENOMEM;
2608         }
2609         msg->msg_vmflush = !!memory_pressure_get();
2610
2611         cpt = lnet_cpt_of_cookie(mdh.cookie);
2612         lnet_res_lock(cpt);
2613
2614         md = lnet_handle2md(&mdh);
2615         if (md == NULL || md->md_threshold == 0 || md->md_me != NULL) {
2616                 CERROR("Dropping PUT (%llu:%d:%s): MD (%d) invalid\n",
2617                        match_bits, portal, libcfs_id2str(target),
2618                        md == NULL ? -1 : md->md_threshold);
2619                 if (md != NULL && md->md_me != NULL)
2620                         CERROR("Source MD also attached to portal %d\n",
2621                                md->md_me->me_portal);
2622                 lnet_res_unlock(cpt);
2623
2624                 lnet_msg_free(msg);
2625                 return -ENOENT;
2626         }
2627
2628         CDEBUG(D_NET, "LNetPut -> %s\n", libcfs_id2str(target));
2629
2630         lnet_msg_attach_md(msg, md, 0, 0);
2631
2632         lnet_prep_send(msg, LNET_MSG_PUT, target, 0, md->md_length);
2633
2634         msg->msg_hdr.msg.put.match_bits = cpu_to_le64(match_bits);
2635         msg->msg_hdr.msg.put.ptl_index = cpu_to_le32(portal);
2636         msg->msg_hdr.msg.put.offset = cpu_to_le32(offset);
2637         msg->msg_hdr.msg.put.hdr_data = hdr_data;
2638
2639         /* NB handles only looked up by creator (no flips) */
2640         if (ack == LNET_ACK_REQ) {
2641                 msg->msg_hdr.msg.put.ack_wmd.wh_interface_cookie =
2642                         the_lnet.ln_interface_cookie;
2643                 msg->msg_hdr.msg.put.ack_wmd.wh_object_cookie =
2644                         md->md_lh.lh_cookie;
2645         } else {
2646                 msg->msg_hdr.msg.put.ack_wmd.wh_interface_cookie =
2647                         LNET_WIRE_HANDLE_COOKIE_NONE;
2648                 msg->msg_hdr.msg.put.ack_wmd.wh_object_cookie =
2649                         LNET_WIRE_HANDLE_COOKIE_NONE;
2650         }
2651
2652         lnet_res_unlock(cpt);
2653
2654         lnet_build_msg_event(msg, LNET_EVENT_SEND);
2655
2656         rc = lnet_send(self, msg, LNET_NID_ANY);
2657         if (rc != 0) {
2658                 CNETERR("Error sending PUT to %s: %d\n",
2659                         libcfs_id2str(target), rc);
2660                 lnet_finalize(NULL, msg, rc);
2661         }
2662
2663         /* completion will be signalled by an event */
2664         return 0;
2665 }
2666 EXPORT_SYMBOL(LNetPut);
2667
2668 lnet_msg_t *
2669 lnet_create_reply_msg (lnet_ni_t *ni, lnet_msg_t *getmsg)
2670 {
2671         /* The LND can DMA direct to the GET md (i.e. no REPLY msg).  This
2672          * returns a msg for the LND to pass to lnet_finalize() when the sink
2673          * data has been received.
2674          *
2675          * CAVEAT EMPTOR: 'getmsg' is the original GET, which is freed when
2676          * lnet_finalize() is called on it, so the LND must call this first */
2677
2678         struct lnet_msg         *msg = lnet_msg_alloc();
2679         struct lnet_libmd       *getmd = getmsg->msg_md;
2680         lnet_process_id_t       peer_id = getmsg->msg_target;
2681         int                     cpt;
2682
2683         LASSERT(!getmsg->msg_target_is_router);
2684         LASSERT(!getmsg->msg_routing);
2685
2686         if (msg == NULL) {
2687                 CERROR("%s: Dropping REPLY from %s: can't allocate msg\n",
2688                        libcfs_nid2str(ni->ni_nid), libcfs_id2str(peer_id));
2689                 goto drop;
2690         }
2691
2692         cpt = lnet_cpt_of_cookie(getmd->md_lh.lh_cookie);
2693         lnet_res_lock(cpt);
2694
2695         LASSERT(getmd->md_refcount > 0);
2696
2697         if (getmd->md_threshold == 0) {
2698                 CERROR("%s: Dropping REPLY from %s for inactive MD %p\n",
2699                         libcfs_nid2str(ni->ni_nid), libcfs_id2str(peer_id),
2700                         getmd);
2701                 lnet_res_unlock(cpt);
2702                 goto drop;
2703         }
2704
2705         LASSERT(getmd->md_offset == 0);
2706
2707         CDEBUG(D_NET, "%s: Reply from %s md %p\n",
2708                libcfs_nid2str(ni->ni_nid), libcfs_id2str(peer_id), getmd);
2709
2710         /* setup information for lnet_build_msg_event */
2711         msg->msg_initiator = lnet_peer_primary_nid(peer_id.nid);
2712         /* Cheaper: msg->msg_initiator = getmsg->msg_txpeer->lp_nid; */
2713         msg->msg_from = peer_id.nid;
2714         msg->msg_type = LNET_MSG_GET; /* flag this msg as an "optimized" GET */
2715         msg->msg_hdr.src_nid = peer_id.nid;
2716         msg->msg_hdr.payload_length = getmd->md_length;
2717         msg->msg_receiving = 1; /* required by lnet_msg_attach_md */
2718
2719         lnet_msg_attach_md(msg, getmd, getmd->md_offset, getmd->md_length);
2720         lnet_res_unlock(cpt);
2721
2722         cpt = lnet_cpt_of_nid(peer_id.nid, ni);
2723
2724         lnet_net_lock(cpt);
2725         lnet_msg_commit(msg, cpt);
2726         lnet_net_unlock(cpt);
2727
2728         lnet_build_msg_event(msg, LNET_EVENT_REPLY);
2729
2730         return msg;
2731
2732  drop:
2733         cpt = lnet_cpt_of_nid(peer_id.nid, ni);
2734
2735         lnet_net_lock(cpt);
2736         the_lnet.ln_counters[cpt]->drop_count++;
2737         the_lnet.ln_counters[cpt]->drop_length += getmd->md_length;
2738         lnet_net_unlock(cpt);
2739
2740         if (msg != NULL)
2741                 lnet_msg_free(msg);
2742
2743         return NULL;
2744 }
2745 EXPORT_SYMBOL(lnet_create_reply_msg);
2746
2747 void
2748 lnet_set_reply_msg_len(lnet_ni_t *ni, lnet_msg_t *reply, unsigned int len)
2749 {
2750         /* Set the REPLY length, now the RDMA that elides the REPLY message has
2751          * completed and I know it. */
2752         LASSERT(reply != NULL);
2753         LASSERT(reply->msg_type == LNET_MSG_GET);
2754         LASSERT(reply->msg_ev.type == LNET_EVENT_REPLY);
2755
2756         /* NB I trusted my peer to RDMA.  If she tells me she's written beyond
2757          * the end of my buffer, I might as well be dead. */
2758         LASSERT(len <= reply->msg_ev.mlength);
2759
2760         reply->msg_ev.mlength = len;
2761 }
2762 EXPORT_SYMBOL(lnet_set_reply_msg_len);
2763
2764 /**
2765  * Initiate an asynchronous GET operation.
2766  *
2767  * On the initiator node, an LNET_EVENT_SEND is logged when the GET request
2768  * is sent, and an LNET_EVENT_REPLY is logged when the data returned from
2769  * the target node in the REPLY has been written to local MD.
2770  *
2771  * On the target node, an LNET_EVENT_GET is logged when the GET request
2772  * arrives and is accepted into a MD.
2773  *
2774  * \param self,target,portal,match_bits,offset See the discussion in LNetPut().
2775  * \param mdh A handle for the MD that describes the memory into which the
2776  * requested data will be received. The MD must be "free floating" (See LNetMDBind()).
2777  *
2778  * \retval  0      Success, and only in this case events will be generated
2779  * and logged to EQ (if it exists) of the MD.
2780  * \retval -EIO    Simulated failure.
2781  * \retval -ENOMEM Memory allocation failure.
2782  * \retval -ENOENT Invalid MD object.
2783  */
2784 int
2785 LNetGet(lnet_nid_t self, lnet_handle_md_t mdh,
2786         lnet_process_id_t target, unsigned int portal,
2787         __u64 match_bits, unsigned int offset)
2788 {
2789         struct lnet_msg         *msg;
2790         struct lnet_libmd       *md;
2791         int                     cpt;
2792         int                     rc;
2793
2794         LASSERT(the_lnet.ln_refcount > 0);
2795
2796         if (!list_empty(&the_lnet.ln_test_peers) &&     /* normally we don't */
2797             fail_peer(target.nid, 1))                   /* shall we now? */
2798         {
2799                 CERROR("Dropping GET to %s: simulated failure\n",
2800                        libcfs_id2str(target));
2801                 return -EIO;
2802         }
2803
2804         msg = lnet_msg_alloc();
2805         if (msg == NULL) {
2806                 CERROR("Dropping GET to %s: ENOMEM on lnet_msg_t\n",
2807                        libcfs_id2str(target));
2808                 return -ENOMEM;
2809         }
2810
2811         cpt = lnet_cpt_of_cookie(mdh.cookie);
2812         lnet_res_lock(cpt);
2813
2814         md = lnet_handle2md(&mdh);
2815         if (md == NULL || md->md_threshold == 0 || md->md_me != NULL) {
2816                 CERROR("Dropping GET (%llu:%d:%s): MD (%d) invalid\n",
2817                        match_bits, portal, libcfs_id2str(target),
2818                        md == NULL ? -1 : md->md_threshold);
2819                 if (md != NULL && md->md_me != NULL)
2820                         CERROR("REPLY MD also attached to portal %d\n",
2821                                md->md_me->me_portal);
2822
2823                 lnet_res_unlock(cpt);
2824
2825                 lnet_msg_free(msg);
2826                 return -ENOENT;
2827         }
2828
2829         CDEBUG(D_NET, "LNetGet -> %s\n", libcfs_id2str(target));
2830
2831         lnet_msg_attach_md(msg, md, 0, 0);
2832
2833         lnet_prep_send(msg, LNET_MSG_GET, target, 0, 0);
2834
2835         msg->msg_hdr.msg.get.match_bits = cpu_to_le64(match_bits);
2836         msg->msg_hdr.msg.get.ptl_index = cpu_to_le32(portal);
2837         msg->msg_hdr.msg.get.src_offset = cpu_to_le32(offset);
2838         msg->msg_hdr.msg.get.sink_length = cpu_to_le32(md->md_length);
2839
2840         /* NB handles only looked up by creator (no flips) */
2841         msg->msg_hdr.msg.get.return_wmd.wh_interface_cookie =
2842                 the_lnet.ln_interface_cookie;
2843         msg->msg_hdr.msg.get.return_wmd.wh_object_cookie =
2844                 md->md_lh.lh_cookie;
2845
2846         lnet_res_unlock(cpt);
2847
2848         lnet_build_msg_event(msg, LNET_EVENT_SEND);
2849
2850         rc = lnet_send(self, msg, LNET_NID_ANY);
2851         if (rc < 0) {
2852                 CNETERR("Error sending GET to %s: %d\n",
2853                         libcfs_id2str(target), rc);
2854                 lnet_finalize(NULL, msg, rc);
2855         }
2856
2857         /* completion will be signalled by an event */
2858         return 0;
2859 }
2860 EXPORT_SYMBOL(LNetGet);
2861
2862 /**
2863  * Calculate distance to node at \a dstnid.
2864  *
2865  * \param dstnid Target NID.
2866  * \param srcnidp If not NULL, NID of the local interface to reach \a dstnid
2867  * is saved here.
2868  * \param orderp If not NULL, order of the route to reach \a dstnid is saved
2869  * here.
2870  *
2871  * \retval 0 If \a dstnid belongs to a local interface, and reserved option
2872  * local_nid_dist_zero is set, which is the default.
2873  * \retval positives Distance to target NID, i.e. number of hops plus one.
2874  * \retval -EHOSTUNREACH If \a dstnid is not reachable.
2875  */
2876 int
2877 LNetDist(lnet_nid_t dstnid, lnet_nid_t *srcnidp, __u32 *orderp)
2878 {
2879         struct list_head        *e;
2880         struct lnet_ni          *ni = NULL;
2881         lnet_remotenet_t        *rnet;
2882         __u32                   dstnet = LNET_NIDNET(dstnid);
2883         int                     hops;
2884         int                     cpt;
2885         __u32                   order = 2;
2886         struct list_head        *rn_list;
2887
2888         /* if !local_nid_dist_zero, I don't return a distance of 0 ever
2889          * (when lustre sees a distance of 0, it substitutes 0@lo), so I
2890          * keep order 0 free for 0@lo and order 1 free for a local NID
2891          * match */
2892
2893         LASSERT(the_lnet.ln_refcount > 0);
2894
2895         cpt = lnet_net_lock_current();
2896
2897         while ((ni = lnet_get_next_ni_locked(NULL, ni))) {
2898                 if (ni->ni_nid == dstnid) {
2899                         if (srcnidp != NULL)
2900                                 *srcnidp = dstnid;
2901                         if (orderp != NULL) {
2902                                 if (LNET_NETTYP(LNET_NIDNET(dstnid)) == LOLND)
2903                                         *orderp = 0;
2904                                 else
2905                                         *orderp = 1;
2906                         }
2907                         lnet_net_unlock(cpt);
2908
2909                         return local_nid_dist_zero ? 0 : 1;
2910                 }
2911
2912                 if (LNET_NIDNET(ni->ni_nid) == dstnet) {
2913                         /* Check if ni was originally created in
2914                          * current net namespace.
2915                          * If not, assign order above 0xffff0000,
2916                          * to make this ni not a priority. */
2917                         if (!net_eq(ni->ni_net_ns, current->nsproxy->net_ns))
2918                                 order += 0xffff0000;
2919
2920                         if (srcnidp != NULL)
2921                                 *srcnidp = ni->ni_nid;
2922                         if (orderp != NULL)
2923                                 *orderp = order;
2924                         lnet_net_unlock(cpt);
2925                         return 1;
2926                 }
2927
2928                 order++;
2929         }
2930
2931         rn_list = lnet_net2rnethash(dstnet);
2932         list_for_each(e, rn_list) {
2933                 rnet = list_entry(e, lnet_remotenet_t, lrn_list);
2934
2935                 if (rnet->lrn_net == dstnet) {
2936                         lnet_route_t *route;
2937                         lnet_route_t *shortest = NULL;
2938                         __u32 shortest_hops = LNET_UNDEFINED_HOPS;
2939                         __u32 route_hops;
2940
2941                         LASSERT(!list_empty(&rnet->lrn_routes));
2942
2943                         list_for_each_entry(route, &rnet->lrn_routes,
2944                                             lr_list) {
2945                                 route_hops = route->lr_hops;
2946                                 if (route_hops == LNET_UNDEFINED_HOPS)
2947                                         route_hops = 1;
2948                                 if (shortest == NULL ||
2949                                     route_hops < shortest_hops) {
2950                                         shortest = route;
2951                                         shortest_hops = route_hops;
2952                                 }
2953                         }
2954
2955                         LASSERT(shortest != NULL);
2956                         hops = shortest_hops;
2957                         if (srcnidp != NULL) {
2958                                 ni = lnet_get_next_ni_locked(
2959                                         shortest->lr_gateway->lpni_net,
2960                                         NULL);
2961                                 *srcnidp = ni->ni_nid;
2962                         }
2963                         if (orderp != NULL)
2964                                 *orderp = order;
2965                         lnet_net_unlock(cpt);
2966                         return hops + 1;
2967                 }
2968                 order++;
2969         }
2970
2971         lnet_net_unlock(cpt);
2972         return -EHOSTUNREACH;
2973 }
2974 EXPORT_SYMBOL(LNetDist);