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