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