Whamcloud - gitweb
Branch: HEAD
[fs/lustre-release.git] / lustre / osc / osc_request.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  *  Copyright (C) 2001-2003 Cluster File Systems, Inc.
5  *   Author Peter Braam <braam@clusterfs.com>
6  *
7  *   This file is part of Lustre, http://www.lustre.org.
8  *
9  *   Lustre is free software; you can redistribute it and/or
10  *   modify it under the terms of version 2 of the GNU General Public
11  *   License as published by the Free Software Foundation.
12  *
13  *   Lustre is distributed in the hope that it will be useful,
14  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  *   GNU General Public License for more details.
17  *
18  *   You should have received a copy of the GNU General Public License
19  *   along with Lustre; if not, write to the Free Software
20  *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21  *
22  *  For testing and management it is treated as an obd_device,
23  *  although * it does not export a full OBD method table (the
24  *  requests are coming * in over the wire, so object target modules
25  *  do not have a full * method table.)
26  *
27  */
28
29 #ifndef EXPORT_SYMTAB
30 # define EXPORT_SYMTAB
31 #endif
32 #define DEBUG_SUBSYSTEM S_OSC
33
34 #ifdef __KERNEL__
35 # include <linux/version.h>
36 # include <linux/module.h>
37 # include <linux/mm.h>
38 # include <linux/highmem.h>
39 # include <linux/ctype.h>
40 # include <linux/init.h>
41 # if (LINUX_VERSION_CODE >= KERNEL_VERSION(2,5,0))
42 #  include <linux/workqueue.h>
43 #  include <linux/smp_lock.h>
44 # else
45 #  include <linux/locks.h>
46 # endif
47 #else /* __KERNEL__ */
48 # include <liblustre.h>
49 #endif
50
51 #include <linux/lustre_dlm.h>
52 #include <libcfs/kp30.h>
53 #include <linux/lustre_net.h>
54 #include <linux/lustre_sec.h>
55 #include <lustre/lustre_user.h>
56 #include <linux/obd_ost.h>
57 #include <linux/obd_lov.h>
58
59 #ifdef  __CYGWIN__
60 # include <ctype.h>
61 #endif
62
63 #include <linux/lustre_ha.h>
64 #include <linux/lprocfs_status.h>
65 #include <linux/lustre_log.h>
66 #include <linux/lustre_gs.h>
67 #include "osc_internal.h"
68
69 /* Pack OSC object metadata for disk storage (LE byte order). */
70 static int osc_packmd(struct obd_export *exp, struct lov_mds_md **lmmp,
71                       struct lov_stripe_md *lsm)
72 {
73         int lmm_size;
74         ENTRY;
75
76         lmm_size = sizeof(**lmmp);
77         if (!lmmp)
78                 RETURN(lmm_size);
79
80         if (*lmmp && !lsm) {
81                 OBD_FREE(*lmmp, lmm_size);
82                 *lmmp = NULL;
83                 RETURN(0);
84         }
85
86         if (!*lmmp) {
87                 OBD_ALLOC(*lmmp, lmm_size);
88                 if (!*lmmp)
89                         RETURN(-ENOMEM);
90         }
91
92         if (lsm) {
93                 LASSERT(lsm->lsm_object_id);
94                 LASSERT(lsm->lsm_object_gr);
95                 (*lmmp)->lmm_object_id = cpu_to_le64(lsm->lsm_object_id);
96                 (*lmmp)->lmm_object_gr = cpu_to_le64(lsm->lsm_object_gr);
97         }
98
99         RETURN(lmm_size);
100 }
101
102 /* Unpack OSC object metadata from disk storage (LE byte order). */
103 static int osc_unpackmd(struct obd_export *exp, struct lov_stripe_md **lsmp,
104                         struct lov_mds_md *lmm, int lmm_bytes)
105 {
106         int lsm_size;
107         ENTRY;
108
109         if (lmm != NULL) {
110                 if (lmm_bytes < sizeof (*lmm)) {
111                         CERROR("lov_mds_md too small: %d, need %d\n",
112                                lmm_bytes, (int)sizeof(*lmm));
113                         RETURN(-EINVAL);
114                 }
115                 /* XXX LOV_MAGIC etc check? */
116
117                 if (lmm->lmm_object_id == 0) {
118                         CERROR("lov_mds_md: zero lmm_object_id\n");
119                         RETURN(-EINVAL);
120                 }
121         }
122
123         lsm_size = lov_stripe_md_size(1);
124         if (lsmp == NULL)
125                 RETURN(lsm_size);
126
127         if (*lsmp != NULL && lmm == NULL) {
128                 OBD_FREE(*lsmp, lsm_size);
129                 *lsmp = NULL;
130                 RETURN(0);
131         }
132
133         if (*lsmp == NULL) {
134                 OBD_ALLOC(*lsmp, lsm_size);
135                 if (*lsmp == NULL)
136                         RETURN(-ENOMEM);
137                 loi_init((*lsmp)->lsm_oinfo);
138         }
139
140         if (lmm != NULL) {
141                 /* XXX zero *lsmp? */
142                 (*lsmp)->lsm_object_id = le64_to_cpu (lmm->lmm_object_id);
143                 (*lsmp)->lsm_object_gr = le64_to_cpu (lmm->lmm_object_gr);
144                 LASSERT((*lsmp)->lsm_object_id);
145                 LASSERT((*lsmp)->lsm_object_gr);
146         }
147
148         (*lsmp)->lsm_maxbytes = LUSTRE_STRIPE_MAXBYTES;
149
150         RETURN(lsm_size);
151 }
152
153 static int osc_getattr_interpret(struct ptlrpc_request *req,
154                                  struct osc_getattr_async_args *aa, int rc)
155 {
156         struct ost_body *body;
157         ENTRY;
158
159         if (rc != 0)
160                 RETURN(rc);
161
162         body = lustre_swab_repbuf(req, 0, sizeof(*body), lustre_swab_ost_body);
163         if (body) {
164                 CDEBUG(D_INODE, "mode: %o\n", body->oa.o_mode);
165                 memcpy(aa->aa_oa, &body->oa, sizeof(*aa->aa_oa));
166
167                 /* This should really be sent by the OST */
168                 aa->aa_oa->o_blksize = PTLRPC_MAX_BRW_SIZE;
169                 aa->aa_oa->o_valid |= OBD_MD_FLBLKSZ;
170         } else {
171                 CERROR("can't unpack ost_body\n");
172                 rc = -EPROTO;
173                 aa->aa_oa->o_valid = 0;
174         }
175
176         RETURN(rc);
177 }
178
179 static int osc_getattr_async(struct obd_export *exp, struct obdo *oa,
180                              struct lov_stripe_md *md,
181                              struct ptlrpc_request_set *set)
182 {
183         struct ptlrpc_request *request;
184         struct ost_body *body;
185         int size = sizeof(*body);
186         struct osc_getattr_async_args *aa;
187         ENTRY;
188
189         request = ptlrpc_prep_req(class_exp2cliimp(exp), LUSTRE_OBD_VERSION,
190                                   OST_GETATTR, 1, &size, NULL);
191         if (!request)
192                 RETURN(-ENOMEM);
193
194         body = lustre_msg_buf(request->rq_reqmsg, 0, sizeof (*body));
195         memcpy(&body->oa, oa, sizeof(*oa));
196
197         request->rq_replen = lustre_msg_size(1, &size);
198         request->rq_interpret_reply = osc_getattr_interpret;
199
200         LASSERT (sizeof (*aa) <= sizeof (request->rq_async_args));
201         aa = (struct osc_getattr_async_args *)&request->rq_async_args;
202         aa->aa_oa = oa;
203
204         ptlrpc_set_add_req (set, request);
205         RETURN (0);
206 }
207
208 static int osc_getattr(struct obd_export *exp, struct obdo *oa,
209                        struct lov_stripe_md *md)
210 {
211         struct ptlrpc_request *request;
212         struct ost_body *body;
213         int rc, size = sizeof(*body);
214         ENTRY;
215
216         request = ptlrpc_prep_req(class_exp2cliimp(exp), LUSTRE_OBD_VERSION,
217                                   OST_GETATTR, 1, &size, NULL);
218         if (!request)
219                 RETURN(-ENOMEM);
220
221         body = lustre_msg_buf(request->rq_reqmsg, 0, sizeof (*body));
222         memcpy(&body->oa, oa, sizeof(*oa));
223
224         request->rq_replen = lustre_msg_size(1, &size);
225
226         rc = ptlrpc_queue_wait(request);
227         if (rc) {
228                 CERROR("%s failed: rc = %d\n", __FUNCTION__, rc);
229                 GOTO(out, rc);
230         }
231
232         body = lustre_swab_repbuf(request, 0, sizeof (*body),
233                                   lustre_swab_ost_body);
234         if (body == NULL) {
235                 CERROR ("can't unpack ost_body\n");
236                 GOTO (out, rc = -EPROTO);
237         }
238
239         CDEBUG(D_INODE, "mode: %o\n", body->oa.o_mode);
240         memcpy(oa, &body->oa, sizeof(*oa));
241
242         /* This should really be sent by the OST */
243         oa->o_blksize = PTLRPC_MAX_BRW_SIZE;
244         oa->o_valid |= OBD_MD_FLBLKSZ;
245
246         EXIT;
247  out:
248         ptlrpc_req_finished(request);
249         return rc;
250 }
251
252 static int osc_setattr(struct obd_export *exp, struct obdo *oa,
253                        struct lov_stripe_md *md, struct obd_trans_info *oti)
254 {
255         struct ptlrpc_request *request;
256         struct ost_body *body;
257         int rc, size = sizeof(*body);
258         ENTRY;
259
260         LASSERT(!(oa->o_valid & OBD_MD_FLGROUP) || oa->o_gr > 0);
261
262         request = ptlrpc_prep_req(class_exp2cliimp(exp), LUSTRE_OBD_VERSION,
263                                   OST_SETATTR, 1, &size, NULL);
264         if (!request)
265                 RETURN(-ENOMEM);
266
267         body = lustre_msg_buf(request->rq_reqmsg, 0, sizeof(*body));
268         memcpy(&body->oa, oa, sizeof(*oa));
269
270         request->rq_replen = lustre_msg_size(1, &size);
271
272         if (oti != NULL && (oti->oti_flags & OBD_MODE_ASYNC)) {
273                 ptlrpcd_add_req(request);
274                 rc = 0;
275         } else {
276                 rc = ptlrpc_queue_wait(request);
277                 if (rc)
278                         GOTO(out, rc);
279
280                 body = lustre_swab_repbuf(request, 0, sizeof(*body),
281                                           lustre_swab_ost_body);
282                 if (body == NULL)
283                         GOTO(out, rc = -EPROTO);
284
285                 memcpy(oa, &body->oa, sizeof(*oa));
286         }
287         EXIT;
288 out:
289         ptlrpc_req_finished(request);
290         RETURN(0);
291 }
292
293 int osc_real_create(struct obd_export *exp, struct obdo *oa,
294                     struct lov_stripe_md **ea, struct obd_trans_info *oti)
295 {
296         struct osc_creator *oscc = &exp->exp_obd->u.cli.cl_oscc;
297         struct ptlrpc_request *request;
298         struct ost_body *body;
299         struct lov_stripe_md *lsm;
300         int rc, size = sizeof(*body);
301         ENTRY;
302
303         LASSERT(oa);
304         LASSERT(ea);
305
306         lsm = *ea;
307         if (!lsm) {
308                 rc = obd_alloc_memmd(exp, &lsm);
309                 if (rc < 0)
310                         RETURN(rc);
311         }
312
313         request = ptlrpc_prep_req(class_exp2cliimp(exp), LUSTRE_OBD_VERSION,
314                                   OST_CREATE, 1, &size, NULL);
315         if (!request)
316                 GOTO(out, rc = -ENOMEM);
317
318         body = lustre_msg_buf(request->rq_reqmsg, 0, sizeof (*body));
319         memcpy(&body->oa, oa, sizeof(body->oa));
320
321         request->rq_replen = lustre_msg_size(1, &size);
322         if (oa->o_valid & OBD_MD_FLINLINE) {
323                 LASSERT((oa->o_valid & OBD_MD_FLFLAGS) &&
324                         oa->o_flags == OBD_FL_DELORPHAN);
325                 DEBUG_REQ(D_HA, request,
326                           "delorphan from OST integration");
327                 /* Don't resend the delorphan request */
328                 request->rq_no_resend = request->rq_no_delay = 1;
329         }
330
331         rc = ptlrpc_queue_wait(request);
332         if (rc)
333                 GOTO(out_req, rc);
334
335         body = lustre_swab_repbuf(request, 0, sizeof(*body),
336                                   lustre_swab_ost_body);
337         if (body == NULL) {
338                 CERROR ("can't unpack ost_body\n");
339                 GOTO (out_req, rc = -EPROTO);
340         }
341
342         if ((oa->o_valid & OBD_MD_FLFLAGS) && oa->o_flags == OBD_FL_DELORPHAN) {
343                 struct obd_import *imp = class_exp2cliimp(exp);
344                 /* MDS declares last known object, OSS responses
345                  * with next possible object -bzzz */
346                 spin_lock(&oscc->oscc_lock);
347                 oscc->oscc_next_id = body->oa.o_id;
348                 spin_unlock(&oscc->oscc_lock);
349                 CDEBUG(D_HA, "%s: set nextid "LPD64" after recovery\n",
350                        imp->imp_target_uuid.uuid, oa->o_id);
351         }
352         memcpy(oa, &body->oa, sizeof(*oa));
353
354         /* This should really be sent by the OST */
355         oa->o_blksize = PTLRPC_MAX_BRW_SIZE;
356         oa->o_valid |= OBD_MD_FLBLKSZ;
357
358         /* XXX LOV STACKING: the lsm that is passed to us from LOV does not
359          * have valid lsm_oinfo data structs, so don't go touching that.
360          * This needs to be fixed in a big way.
361          */
362         lsm->lsm_object_id = oa->o_id;
363         lsm->lsm_object_gr = oa->o_gr;
364         *ea = lsm;
365
366         if (oti != NULL) {
367                 oti->oti_transno = request->rq_repmsg->transno;
368
369                 if (oa->o_valid & OBD_MD_FLCOOKIE) {
370                         if (!oti->oti_logcookies)
371                                 oti_alloc_cookies(oti, 1);
372                         memcpy(oti->oti_logcookies, obdo_logcookie(oa),
373                                sizeof(oti->oti_onecookie));
374                 }
375         }
376
377         CDEBUG(D_HA, "transno: "LPD64"\n", request->rq_repmsg->transno);
378         EXIT;
379 out_req:
380         ptlrpc_req_finished(request);
381 out:
382         if (rc && !*ea)
383                 obd_free_memmd(exp, &lsm);
384         return rc;
385 }
386
387 static int osc_punch(struct obd_export *exp, struct obdo *oa,
388                      struct lov_stripe_md *md, obd_size start,
389                      obd_size end, struct obd_trans_info *oti)
390 {
391         struct ptlrpc_request *request;
392         struct ost_body *body;
393         int rc, size = sizeof(*body);
394         ENTRY;
395
396         if (!oa) {
397                 CERROR("oa NULL\n");
398                 RETURN(-EINVAL);
399         }
400
401         request = ptlrpc_prep_req(class_exp2cliimp(exp), LUSTRE_OBD_VERSION,
402                                   OST_PUNCH, 1, &size, NULL);
403         if (!request)
404                 RETURN(-ENOMEM);
405
406         body = lustre_msg_buf(request->rq_reqmsg, 0, sizeof (*body));
407         memcpy(&body->oa, oa, sizeof(*oa));
408
409         /* overload the size and blocks fields in the oa with start/end */
410         body->oa.o_size = start;
411         body->oa.o_blocks = end;
412         body->oa.o_valid |= (OBD_MD_FLSIZE | OBD_MD_FLBLOCKS);
413
414         request->rq_replen = lustre_msg_size(1, &size);
415
416         rc = ptlrpc_queue_wait(request);
417         if (rc)
418                 GOTO(out, rc);
419
420         body = lustre_swab_repbuf (request, 0, sizeof (*body),
421                                    lustre_swab_ost_body);
422         if (body == NULL) {
423                 CERROR ("can't unpack ost_body\n");
424                 GOTO (out, rc = -EPROTO);
425         }
426
427         memcpy(oa, &body->oa, sizeof(*oa));
428
429         EXIT;
430  out:
431         ptlrpc_req_finished(request);
432         return rc;
433 }
434
435 static int osc_sync(struct obd_export *exp, struct obdo *oa,
436                     struct lov_stripe_md *md, obd_size start,
437                     obd_size end)
438 {
439         struct ptlrpc_request *request;
440         struct ost_body *body;
441         int rc, size = sizeof(*body);
442         ENTRY;
443
444         if (!oa) {
445                 CERROR("oa NULL\n");
446                 RETURN(-EINVAL);
447         }
448
449         request = ptlrpc_prep_req(class_exp2cliimp(exp), LUSTRE_OBD_VERSION,
450                                   OST_SYNC, 1, &size, NULL);
451         if (!request)
452                 RETURN(-ENOMEM);
453
454         body = lustre_msg_buf(request->rq_reqmsg, 0, sizeof (*body));
455         memcpy(&body->oa, oa, sizeof(*oa));
456
457         /* overload the size and blocks fields in the oa with start/end */
458         body->oa.o_size = start;
459         body->oa.o_blocks = end;
460         body->oa.o_valid |= (OBD_MD_FLSIZE | OBD_MD_FLBLOCKS);
461
462         request->rq_replen = lustre_msg_size(1, &size);
463
464         rc = ptlrpc_queue_wait(request);
465         if (rc)
466                 GOTO(out, rc);
467
468         body = lustre_swab_repbuf(request, 0, sizeof(*body),
469                                   lustre_swab_ost_body);
470         if (body == NULL) {
471                 CERROR ("can't unpack ost_body\n");
472                 GOTO (out, rc = -EPROTO);
473         }
474
475         memcpy(oa, &body->oa, sizeof(*oa));
476
477         EXIT;
478  out:
479         ptlrpc_req_finished(request);
480         return rc;
481 }
482
483 static int osc_destroy(struct obd_export *exp, struct obdo *oa,
484                        struct lov_stripe_md *ea, struct obd_trans_info *oti)
485 {
486         struct ptlrpc_request *request;
487         struct ost_body *body;
488         int rc, size = sizeof(*body);
489         ENTRY;
490
491         if (!oa) {
492                 CERROR("oa NULL\n");
493                 RETURN(-EINVAL);
494         }
495
496         request = ptlrpc_prep_req(class_exp2cliimp(exp), LUSTRE_OBD_VERSION,
497                                   OST_DESTROY, 1, &size, NULL);
498         if (!request)
499                 RETURN(-ENOMEM);
500
501         body = lustre_msg_buf(request->rq_reqmsg, 0, sizeof (*body));
502
503         if (oti != NULL && oa->o_valid & OBD_MD_FLCOOKIE) {
504                 memcpy(obdo_logcookie(oa), oti->oti_logcookies,
505                        sizeof(*oti->oti_logcookies));
506                 oti->oti_logcookies++;
507         }
508
509         memcpy(&body->oa, oa, sizeof(*oa));
510         request->rq_replen = lustre_msg_size(1, &size);
511
512         if (oti != NULL && (oti->oti_flags & OBD_MODE_ASYNC)) {
513                 ptlrpcd_add_req(request);
514                 rc = 0;
515         } else {
516                 rc = ptlrpc_queue_wait(request);
517         
518                 if (rc == -ENOENT)
519                         rc = 0;
520
521                 if (rc) {
522                         ptlrpc_req_finished(request);
523                         RETURN(rc);
524                 }
525
526                 body = lustre_swab_repbuf(request, 0, sizeof(*body),
527                                           lustre_swab_ost_body);
528                 if (body == NULL) {
529                         CERROR ("Can't unpack body\n");
530                         ptlrpc_req_finished(request);
531                         RETURN(-EPROTO);
532                 }
533
534                 memcpy(oa, &body->oa, sizeof(*oa));
535                 ptlrpc_req_finished(request);
536         }
537         RETURN(rc);
538 }
539
540 static void osc_announce_cached(struct client_obd *cli, struct obdo *oa,
541                                 long writing_bytes)
542 {
543         obd_valid bits = OBD_MD_FLBLOCKS|OBD_MD_FLGRANT;
544
545         LASSERT(!(oa->o_valid & bits));
546
547         oa->o_valid |= bits;
548         spin_lock(&cli->cl_loi_list_lock);
549         oa->o_dirty = cli->cl_dirty;
550         oa->o_undirty = cli->cl_dirty_max - oa->o_dirty;
551         oa->o_grant = cli->cl_avail_grant;
552         oa->o_dropped = cli->cl_lost_grant;
553         cli->cl_lost_grant = 0;
554         spin_unlock(&cli->cl_loi_list_lock);
555         CDEBUG(D_CACHE,"dirty: "LPU64" undirty: %u dropped %u grant: "LPU64"\n",
556                oa->o_dirty, oa->o_undirty, oa->o_dropped, oa->o_grant);
557 }
558
559 /* caller must hold loi_list_lock */
560 static void osc_consume_write_grant(struct client_obd *cli,
561                                     struct osc_async_page *oap)
562 {
563         cli->cl_dirty += PAGE_SIZE;
564         cli->cl_avail_grant -= PAGE_SIZE;
565         oap->oap_brw_flags |= OBD_BRW_FROM_GRANT;
566         CDEBUG(D_CACHE, "using %lu grant credits for oap %p\n", PAGE_SIZE, oap);
567         LASSERT(cli->cl_avail_grant >= 0);
568 }
569
570 static unsigned long rpcs_in_flight(struct client_obd *cli)
571 {
572         return cli->cl_r_in_flight + cli->cl_w_in_flight;
573 }
574
575 /* caller must hold loi_list_lock */
576 void osc_wake_cache_waiters(struct client_obd *cli)
577 {
578         struct list_head *l, *tmp;
579         struct osc_cache_waiter *ocw;
580
581         list_for_each_safe(l, tmp, &cli->cl_cache_waiters) {
582                 /* if we can't dirty more, we must wait until some is written */
583                 if (cli->cl_dirty + PAGE_SIZE > cli->cl_dirty_max) {
584                         CDEBUG(D_CACHE, "no dirty room: dirty: %ld max %ld\n",
585                                cli->cl_dirty, cli->cl_dirty_max);
586                         return;
587                 }
588
589                 /* if still dirty cache but no grant wait for pending RPCs that
590                  * may yet return us some grant before doing sync writes */
591                 if (cli->cl_w_in_flight && cli->cl_avail_grant < PAGE_SIZE) {
592                         CDEBUG(D_CACHE, "%u BRW writes in flight, no grant\n",
593                                cli->cl_w_in_flight);
594                 }
595                 ocw = list_entry(l, struct osc_cache_waiter, ocw_entry);
596                 list_del_init(&ocw->ocw_entry);
597                 if (cli->cl_avail_grant < PAGE_SIZE) {
598                         /* no more RPCs in flight to return grant, do sync IO */
599                         ocw->ocw_rc = -EDQUOT;
600                         CDEBUG(D_INODE, "wake oap %p for sync\n", ocw->ocw_oap);
601                 } else {
602                         osc_consume_write_grant(cli, ocw->ocw_oap);
603                 }
604
605                 wake_up(&ocw->ocw_waitq);
606         }
607
608         EXIT;
609 }
610
611 static void osc_update_grant(struct client_obd *cli, struct ost_body *body)
612 {
613         spin_lock(&cli->cl_loi_list_lock);
614         CDEBUG(D_CACHE, "got "LPU64" extra grant\n", body->oa.o_grant);
615         cli->cl_avail_grant += body->oa.o_grant;
616         /* waiters are woken in brw_interpret_oap */
617         spin_unlock(&cli->cl_loi_list_lock);
618 }
619
620 /* We assume that the reason this OSC got a short read is because it read
621  * beyond the end of a stripe file; i.e. lustre is reading a sparse file
622  * via the LOV, and it _knows_ it's reading inside the file, it's just that
623  * this stripe never got written at or beyond this stripe offset yet. */
624 static void handle_short_read(int nob_read, obd_count page_count,
625                               struct brw_page *pga)
626 {
627         char *ptr;
628
629         /* skip bytes read OK */
630         while (nob_read > 0) {
631                 LASSERT (page_count > 0);
632
633                 if (pga->count > nob_read) {
634                         /* EOF inside this page */
635                         ptr = kmap(pga->pg) + (pga->page_offset & ~PAGE_MASK);
636                         memset(ptr + nob_read, 0, pga->count - nob_read);
637                         kunmap(pga->pg);
638                         page_count--;
639                         pga++;
640                         break;
641                 }
642
643                 nob_read -= pga->count;
644                 page_count--;
645                 pga++;
646         }
647
648         /* zero remaining pages */
649         while (page_count-- > 0) {
650                 ptr = kmap(pga->pg) + (pga->page_offset & ~PAGE_MASK);
651                 memset(ptr, 0, pga->count);
652                 kunmap(pga->pg);
653                 pga++;
654         }
655 }
656
657 static int check_write_rcs(struct ptlrpc_request *request,
658                            int requested_nob, int niocount,
659                            obd_count page_count, struct brw_page *pga)
660 {
661         int *remote_rcs, i;
662
663         /* return error if any niobuf was in error */
664         remote_rcs = lustre_swab_repbuf(request, 1,
665                                         sizeof(*remote_rcs) * niocount, NULL);
666         if (remote_rcs == NULL) {
667                 CERROR("Missing/short RC vector on BRW_WRITE reply\n");
668                 return(-EPROTO);
669         }
670         if (lustre_msg_swabbed(request->rq_repmsg))
671                 for (i = 0; i < niocount; i++)
672                         __swab32s((__u32 *)&remote_rcs[i]);
673
674         for (i = 0; i < niocount; i++) {
675                 if (remote_rcs[i] < 0)
676                         return(remote_rcs[i]);
677
678                 if (remote_rcs[i] != 0) {
679                         CERROR("rc[%d] invalid (%d) req %p\n",
680                                 i, remote_rcs[i], request);
681                         return(-EPROTO);
682                 }
683         }
684
685         if (request->rq_bulk->bd_nob_transferred != requested_nob) {
686                 CERROR("Unexpected # bytes transferred: %d (requested %d)\n",
687                        requested_nob, request->rq_bulk->bd_nob_transferred);
688                 return(-EPROTO);
689         }
690
691         return (0);
692 }
693
694 static inline int can_merge_pages(struct brw_page *p1, struct brw_page *p2)
695 {
696         if (p1->flag != p2->flag) {
697                 unsigned mask = ~OBD_BRW_FROM_GRANT;
698
699                 /* warn if we try to combine flags that we don't know to be
700                  * safe to combine */
701                 if ((p1->flag & mask) != (p2->flag & mask))
702                         CERROR("is it ok to have flags 0x%x and 0x%x in the "
703                                "same brw?\n", p1->flag, p2->flag);
704                 return 0;
705         }
706
707         return (p1->disk_offset + p1->count == p2->disk_offset);
708 }
709
710 #if CHECKSUM_BULK
711 static obd_count cksum_pages(int nob, obd_count page_count,
712                              struct brw_page *pga)
713 {
714         obd_count cksum = 0;
715         char *ptr;
716
717         while (nob > 0) {
718                 LASSERT (page_count > 0);
719
720                 ptr = kmap(pga->pg);
721                 ost_checksum(&cksum, ptr + (pga->off & (PAGE_SIZE - 1)),
722                              pga->count > nob ? nob : pga->count);
723                 kunmap(pga->pg);
724
725                 nob -= pga->count;
726                 page_count--;
727                 pga++;
728         }
729
730         return (cksum);
731 }
732 #endif
733
734 #define osc_encrypt_page(page, off, count)  \
735         osc_crypt_page(page, off, count, ENCRYPT_DATA)
736 #define osc_decrypt_page(page, off, count)  \
737         osc_crypt_page(page, off, count, DECRYPT_DATA)
738
739 /*Put a global call back var here is Ugly, but put it to client_obd 
740  *also seems not a good idea, WangDi*/ 
741 crypt_cb_t  osc_crypt_cb = NULL;     
742    
743 static int osc_crypt_page(struct page *page, obd_off page_off, obd_off count, 
744                           int flags)
745 {
746         int rc = 0;
747         ENTRY;
748
749         if (osc_crypt_cb != NULL)
750                 rc = osc_crypt_cb(page, page_off, count, flags);
751         if (rc != 0) 
752                 CERROR("crypt page error %d \n", rc);
753         RETURN(rc); 
754 }
755
756 static int osc_brw_prep_request(int cmd, struct obd_import *imp,struct obdo *oa,
757                                 struct lov_stripe_md *lsm, obd_count page_count,
758                                 struct brw_page *pga, int *requested_nobp,
759                                 int *niocountp, struct ptlrpc_request **reqp)
760 {
761         struct ptlrpc_request   *req;
762         struct ptlrpc_bulk_desc *desc;
763         struct client_obd       *cli = &imp->imp_obd->u.cli;
764         struct ost_body         *body;
765         struct obd_ioobj        *ioobj;
766         struct niobuf_remote    *niobuf;
767         int                      niocount;
768         int                      size[3];
769         int                      i;
770         int                      requested_nob;
771         int                      opc;
772         int                      rc;
773
774         opc = ((cmd & OBD_BRW_WRITE) != 0) ? OST_WRITE : OST_READ;
775
776         for (niocount = i = 1; i < page_count; i++)
777                 if (!can_merge_pages(&pga[i - 1], &pga[i]))
778                         niocount++;
779
780         size[0] = sizeof(*body);
781         size[1] = sizeof(*ioobj);
782         size[2] = niocount * sizeof(*niobuf);
783
784         req = ptlrpc_prep_req(imp, LUSTRE_OBD_VERSION, opc, 3, size, NULL);
785         if (req == NULL)
786                 return (-ENOMEM);
787
788         if (opc == OST_WRITE)
789                 desc = ptlrpc_prep_bulk_imp (req, page_count,
790                                              BULK_GET_SOURCE, OST_BULK_PORTAL);
791         else
792                 desc = ptlrpc_prep_bulk_imp (req, page_count,
793                                              BULK_PUT_SINK, OST_BULK_PORTAL);
794         if (desc == NULL)
795                 GOTO(out, rc = -ENOMEM);
796         /* NB request now owns desc and will free it when it gets freed */
797
798         body = lustre_msg_buf(req->rq_reqmsg, 0, sizeof(*body));
799         ioobj = lustre_msg_buf(req->rq_reqmsg, 1, sizeof(*ioobj));
800         niobuf = lustre_msg_buf(req->rq_reqmsg, 2, niocount * sizeof(*niobuf));
801
802         memcpy(&body->oa, oa, sizeof(*oa));
803
804         obdo_to_ioobj(oa, ioobj);
805         ioobj->ioo_bufcnt = niocount;
806
807         LASSERT (page_count > 0);
808
809         for (requested_nob = i = 0; i < page_count; i++, niobuf++) {
810                 struct brw_page *pg = &pga[i];
811                 struct brw_page *pg_prev = pg - 1;
812
813                 LASSERT(pg->count > 0);
814                 LASSERTF((pg->page_offset & ~PAGE_MASK)+ pg->count <= PAGE_SIZE,
815                          "i: %d pg: %p pg_off: "LPU64", count: %u\n", i, pg,
816                          pg->page_offset, pg->count);
817                 LASSERTF(i == 0 || pg->disk_offset > pg_prev->disk_offset,
818                          "i %d p_c %u pg %p [pri %lu ind %lu] off "LPU64
819                          " prev_pg %p [pri %lu ind %lu] off "LPU64"\n",
820                          i, page_count,
821                          pg->pg, pg->pg->private, pg->pg->index, pg->disk_offset,
822                          pg_prev->pg, pg_prev->pg->private, pg_prev->pg->index,
823                          pg_prev->disk_offset);
824                 
825                 if (opc == OST_WRITE) {
826                         osc_encrypt_page(pg->pg, pg->page_offset, pg->count);
827                 } 
828
829                 ptlrpc_prep_bulk_page(desc, pg->pg,
830                                       pg->page_offset & ~PAGE_MASK, pg->count);
831                 requested_nob += pg->count;
832
833                 if (i > 0 && can_merge_pages(pg_prev, pg)) {
834                         niobuf--;
835                         niobuf->len += pg->count;
836                 } else {
837                         niobuf->offset = pg->disk_offset;
838                         niobuf->len    = pg->count;
839                         niobuf->flags  = pg->flag;
840                 }
841         }
842
843         LASSERT((void *)(niobuf - niocount) ==
844                 lustre_msg_buf(req->rq_reqmsg, 2, niocount * sizeof(*niobuf)));
845         osc_announce_cached(cli, &body->oa, opc == OST_WRITE ? requested_nob:0);
846
847         /* size[0] still sizeof (*body) */
848         if (opc == OST_WRITE) {
849 #if CHECKSUM_BULK
850                 body->oa.o_valid |= OBD_MD_FLCKSUM;
851                 body->oa.o_cksum = cksum_pages(requested_nob, page_count, pga);
852 #endif
853                 /* 1 RC per niobuf */
854                 size[1] = sizeof(__u32) * niocount;
855                 req->rq_replen = lustre_msg_size(2, size);
856         } else {
857                 /* 1 RC for the whole I/O */
858                 req->rq_replen = lustre_msg_size(1, size);
859         }
860
861         *niocountp = niocount;
862         *requested_nobp = requested_nob;
863         *reqp = req;
864         return (0);
865
866  out:
867         ptlrpc_req_finished (req);
868         return (rc);
869 }
870
871 static int osc_brw_fini_request(struct ptlrpc_request *req, struct obdo *oa,
872                                 int requested_nob, int niocount,
873                                 obd_count page_count, struct brw_page *pga,
874                                 int rc)
875 {
876         struct client_obd *cli = &req->rq_import->imp_obd->u.cli;
877         struct ost_body *body;
878         ENTRY;
879
880         if (rc < 0)
881                 RETURN(rc);
882
883         body = lustre_swab_repbuf(req, 0, sizeof(*body), lustre_swab_ost_body);
884         if (body == NULL) {
885                 CERROR ("Can't unpack body\n");
886                 RETURN(-EPROTO);
887         }
888
889         osc_update_grant(cli, body);
890         memcpy(oa, &body->oa, sizeof(*oa));
891
892         if (req->rq_reqmsg->opc == OST_WRITE) {
893                 if (rc > 0) {
894                         CERROR ("Unexpected +ve rc %d\n", rc);
895                         RETURN(-EPROTO);
896                 }
897                 LASSERT (req->rq_bulk->bd_nob == requested_nob);
898                 osc_decrypt_page(pga->pg, pga->page_offset, 
899                                  pga->count);
900                 RETURN(check_write_rcs(req, requested_nob, niocount,
901                                        page_count, pga));
902         }
903
904         if (rc > requested_nob) {
905                 CERROR("Unexpected rc %d (%d requested)\n", rc, requested_nob);
906                 RETURN(-EPROTO);
907         }
908
909         if (rc != req->rq_bulk->bd_nob_transferred) {
910                 CERROR ("Unexpected rc %d (%d transferred)\n",
911                         rc, req->rq_bulk->bd_nob_transferred);
912                 return (-EPROTO);
913         }
914
915         if (rc < requested_nob)
916                 handle_short_read(rc, page_count, pga);
917
918 #if CHECKSUM_BULK
919         if (oa->o_valid & OBD_MD_FLCKSUM) {
920                 const struct ptlrpc_peer *peer =
921                         &req->rq_import->imp_connection->c_peer;
922                 static int cksum_counter;
923                 obd_count server_cksum = oa->o_cksum;
924                 obd_count cksum = cksum_pages(rc, page_count, pga);
925                 char str[PTL_NALFMT_SIZE];
926
927                 ptlrpc_peernid2str(peer, str);
928
929                 cksum_counter++;
930                 if (server_cksum != cksum) {
931                         CERROR("Bad checksum: server %x, client %x, server NID "
932                                LPX64" (%s)\n", server_cksum, cksum,
933                                peer->peer_id.nid, str);
934                         cksum_counter = 0;
935                         oa->o_cksum = cksum;
936                 } else if ((cksum_counter & (-cksum_counter)) == cksum_counter){
937                         CWARN("Checksum %u from "LPX64" (%s) OK: %x\n",
938                               cksum_counter, peer->peer_id.nid, str, cksum);
939                 }
940         } else {
941                 static int cksum_missed;
942
943                 cksum_missed++;
944                 if ((cksum_missed & (-cksum_missed)) == cksum_missed)
945                         CERROR("Request checksum %u from "LPX64", no reply\n",
946                                cksum_missed,
947                                req->rq_import->imp_connection->c_peer.peer_id.nid);
948         }
949 #endif
950         osc_decrypt_page(pga->pg, pga->page_offset, pga->count);
951         RETURN(0);
952 }
953
954 static int osc_brw_internal(int cmd, struct obd_export *exp,struct obdo *oa,
955                             struct lov_stripe_md *lsm,
956                             obd_count page_count, struct brw_page *pga)
957 {
958         int                    requested_nob;
959         int                    niocount;
960         struct ptlrpc_request *request;
961         int                    rc;
962         ENTRY;
963
964 restart_bulk:
965         rc = osc_brw_prep_request(cmd, class_exp2cliimp(exp), oa, lsm,
966                                   page_count, pga, &requested_nob, &niocount,
967                                   &request);
968         if (rc != 0)
969                 return (rc);
970
971         rc = ptlrpc_queue_wait(request);
972
973         if (rc == -ETIMEDOUT && request->rq_resend) {
974                 DEBUG_REQ(D_HA, request,  "BULK TIMEOUT");
975                 ptlrpc_req_finished(request);
976                 goto restart_bulk;
977         }
978
979         rc = osc_brw_fini_request(request, oa, requested_nob, niocount,
980                                   page_count, pga, rc);
981
982         ptlrpc_req_finished(request);
983         RETURN (rc);
984 }
985
986 static int brw_interpret(struct ptlrpc_request *request,
987                          struct osc_brw_async_args *aa, int rc)
988 {
989         struct obdo *oa      = aa->aa_oa;
990         int requested_nob    = aa->aa_requested_nob;
991         int niocount         = aa->aa_nio_count;
992         obd_count page_count = aa->aa_page_count;
993         struct brw_page *pga = aa->aa_pga;
994         ENTRY;
995
996         rc = osc_brw_fini_request(request, oa, requested_nob, niocount,
997                                   page_count, pga, rc);
998         RETURN (rc);
999 }
1000
1001 static int async_internal(int cmd, struct obd_export *exp, struct obdo *oa,
1002                           struct lov_stripe_md *lsm, obd_count page_count,
1003                           struct brw_page *pga, struct ptlrpc_request_set *set)
1004 {
1005         struct ptlrpc_request     *request;
1006         int                        requested_nob;
1007         int                        nio_count;
1008         struct osc_brw_async_args *aa;
1009         int                        rc;
1010         ENTRY;
1011
1012         rc = osc_brw_prep_request(cmd, class_exp2cliimp(exp), oa, lsm,
1013                                   page_count, pga, &requested_nob, &nio_count,
1014                                   &request);
1015         if (rc == 0) {
1016                 LASSERT(sizeof(*aa) <= sizeof(request->rq_async_args));
1017                 aa = (struct osc_brw_async_args *)&request->rq_async_args;
1018                 aa->aa_oa = oa;
1019                 aa->aa_requested_nob = requested_nob;
1020                 aa->aa_nio_count = nio_count;
1021                 aa->aa_page_count = page_count;
1022                 aa->aa_pga = pga;
1023
1024                 request->rq_interpret_reply = brw_interpret;
1025                 ptlrpc_set_add_req(set, request);
1026         }
1027         RETURN (rc);
1028 }
1029
1030 #ifndef min_t
1031 #define min_t(type,x,y) \
1032         ({ type __x = (x); type __y = (y); __x < __y ? __x: __y; })
1033 #endif
1034
1035 /*
1036  * ugh, we want disk allocation on the target to happen in offset order.  we'll
1037  * follow sedgewicks advice and stick to the dead simple shellsort -- it'll do
1038  * fine for our small page arrays and doesn't require allocation.  its an
1039  * insertion sort that swaps elements that are strides apart, shrinking the
1040  * stride down until its '1' and the array is sorted.
1041  */
1042 static void sort_brw_pages(struct brw_page *array, int num)
1043 {
1044         int stride, i, j;
1045         struct brw_page tmp;
1046
1047         if (num == 1)
1048                 return;
1049         for (stride = 1; stride < num ; stride = (stride * 3) + 1)
1050                 ;
1051
1052         do {
1053                 stride /= 3;
1054                 for (i = stride ; i < num ; i++) {
1055                         tmp = array[i];
1056                         j = i;
1057                         while (j >= stride && array[j - stride].disk_offset >
1058                                 tmp.disk_offset) {
1059                                 array[j] = array[j - stride];
1060                                 j -= stride;
1061                         }
1062                         array[j] = tmp;
1063                 }
1064         } while (stride > 1);
1065 }
1066
1067 /* make sure we the regions we're passing to elan don't violate its '4
1068  * fragments' constraint.  portal headers are a fragment, all full
1069  * PAGE_SIZE long pages count as 1 fragment, and each partial page
1070  * counts as a fragment.  I think.  see bug 934. */
1071 static obd_count check_elan_limit(struct brw_page *pg, obd_count pages)
1072 {
1073         int frags_left = 3;
1074         int saw_whole_frag = 0;
1075         int i;
1076
1077         for (i = 0 ; frags_left && i < pages ; pg++, i++) {
1078                 if (pg->count == PAGE_SIZE) {
1079                         if (!saw_whole_frag) {
1080                                 saw_whole_frag = 1;
1081                                 frags_left--;
1082                         }
1083                 } else {
1084                         frags_left--;
1085                 }
1086         }
1087         return i;
1088 }
1089
1090 static int osc_brw(int cmd, struct obd_export *exp, struct obdo *oa,
1091                    struct lov_stripe_md *lsm, obd_count page_count,
1092                    struct brw_page *pga, struct obd_trans_info *oti)
1093 {
1094         ENTRY;
1095
1096         if (cmd == OBD_BRW_CHECK) {
1097                 /* The caller just wants to know if there's a chance that this
1098                  * I/O can succeed */
1099                 struct obd_import *imp = class_exp2cliimp(exp);
1100
1101                 if (imp == NULL || imp->imp_invalid)
1102                         RETURN(-EIO);
1103                 RETURN(0);
1104         }
1105
1106         while (page_count) {
1107                 obd_count pages_per_brw;
1108                 int rc;
1109
1110                 if (page_count > PTLRPC_MAX_BRW_PAGES)
1111                         pages_per_brw = PTLRPC_MAX_BRW_PAGES;
1112                 else
1113                         pages_per_brw = page_count;
1114
1115                 sort_brw_pages(pga, pages_per_brw);
1116                 pages_per_brw = check_elan_limit(pga, pages_per_brw);
1117
1118                 rc = osc_brw_internal(cmd, exp, oa, lsm, pages_per_brw, pga);
1119
1120                 if (rc != 0)
1121                         RETURN(rc);
1122
1123                 page_count -= pages_per_brw;
1124                 pga += pages_per_brw;
1125         }
1126         RETURN(0);
1127 }
1128
1129 static int osc_brw_async(int cmd, struct obd_export *exp, struct obdo *oa,
1130                          struct lov_stripe_md *lsm, obd_count page_count,
1131                          struct brw_page *pga, struct ptlrpc_request_set *set,
1132                          struct obd_trans_info *oti)
1133 {
1134         ENTRY;
1135
1136         if (cmd == OBD_BRW_CHECK) {
1137                 /* The caller just wants to know if there's a chance that this
1138                  * I/O can succeed */
1139                 struct obd_import *imp = class_exp2cliimp(exp);
1140
1141                 if (imp == NULL || imp->imp_invalid)
1142                         RETURN(-EIO);
1143                 RETURN(0);
1144         }
1145
1146         while (page_count) {
1147                 obd_count pages_per_brw;
1148                 int rc;
1149
1150                 if (page_count > PTLRPC_MAX_BRW_PAGES)
1151                         pages_per_brw = PTLRPC_MAX_BRW_PAGES;
1152                 else
1153                         pages_per_brw = page_count;
1154
1155                 sort_brw_pages(pga, pages_per_brw);
1156                 pages_per_brw = check_elan_limit(pga, pages_per_brw);
1157
1158                 rc = async_internal(cmd, exp, oa, lsm, pages_per_brw, pga, set);
1159
1160                 if (rc != 0)
1161                         RETURN(rc);
1162
1163                 page_count -= pages_per_brw;
1164                 pga += pages_per_brw;
1165         }
1166         RETURN(0);
1167 }
1168
1169 static void osc_check_rpcs(struct client_obd *cli);
1170 static void osc_exit_cache(struct client_obd *cli, struct osc_async_page *oap,
1171                            int sent);
1172 static void loi_list_maint(struct client_obd *cli, struct lov_oinfo *loi);
1173 static void lop_update_pending(struct client_obd *cli,
1174                                struct loi_oap_pages *lop, int cmd, int delta);
1175
1176 /* this is called when a sync waiter receives an interruption.  Its job is to
1177  * get the caller woken as soon as possible.  If its page hasn't been put in an
1178  * rpc yet it can dequeue immediately.  Otherwise it has to mark the rpc as
1179  * desiring interruption which will forcefully complete the rpc once the rpc
1180  * has timed out */
1181 static void osc_occ_interrupted(struct oig_callback_context *occ)
1182 {
1183         struct osc_async_page *oap;
1184         struct loi_oap_pages *lop;
1185         struct lov_oinfo *loi;
1186         ENTRY;
1187
1188         /* XXX member_of() */
1189         oap = list_entry(occ, struct osc_async_page, oap_occ);
1190
1191         spin_lock(&oap->oap_cli->cl_loi_list_lock);
1192
1193         oap->oap_interrupted = 1;
1194
1195         /* ok, it's been put in an rpc. */
1196         if (oap->oap_request != NULL) {
1197                 ptlrpc_mark_interrupted(oap->oap_request);
1198                 ptlrpcd_wake(oap->oap_request);
1199                 GOTO(unlock, 0);
1200         }
1201
1202         /* we don't get interruption callbacks until osc_trigger_sync_io()
1203          * has been called and put the sync oaps in the pending/urgent lists.*/
1204         if (!list_empty(&oap->oap_pending_item)) {
1205                 list_del_init(&oap->oap_pending_item);
1206                 if (oap->oap_async_flags & ASYNC_URGENT)
1207                         list_del_init(&oap->oap_urgent_item);
1208
1209                 loi = oap->oap_loi;
1210                 lop = (oap->oap_cmd == OBD_BRW_WRITE) ?
1211                         &loi->loi_write_lop : &loi->loi_read_lop;
1212                 lop_update_pending(oap->oap_cli, lop, oap->oap_cmd, -1);
1213                 loi_list_maint(oap->oap_cli, oap->oap_loi);
1214
1215                 oig_complete_one(oap->oap_oig, &oap->oap_occ, 0);
1216                 oap->oap_oig = NULL;
1217         }
1218
1219 unlock:
1220         spin_unlock(&oap->oap_cli->cl_loi_list_lock);
1221 }
1222
1223 /* this must be called holding the loi list lock to give coverage to exit_cache,
1224  * async_flag maintenance, and oap_request */
1225 static void osc_ap_completion(struct client_obd *cli, struct obdo *oa,
1226                               struct osc_async_page *oap, int sent, int rc)
1227 {
1228         osc_exit_cache(cli, oap, sent);
1229         oap->oap_async_flags = 0;
1230         oap->oap_interrupted = 0;
1231
1232         if (oap->oap_request != NULL) {
1233                 ptlrpc_req_finished(oap->oap_request);
1234                 oap->oap_request = NULL;
1235         }
1236
1237         if (rc == 0 && oa != NULL)
1238                 oap->oap_loi->loi_blocks = oa->o_blocks;
1239
1240         if (oap->oap_oig) {
1241                 oig_complete_one(oap->oap_oig, &oap->oap_occ, rc);
1242                 oap->oap_oig = NULL;
1243                 EXIT;
1244                 return;
1245         }
1246
1247         oap->oap_caller_ops->ap_completion(oap->oap_caller_data, oap->oap_cmd,
1248                                            oa, rc);
1249 }
1250
1251 static int brw_interpret_oap(struct ptlrpc_request *request,
1252                              struct osc_brw_async_args *aa, int rc)
1253 {
1254         struct osc_async_page *oap;
1255         struct client_obd *cli;
1256         struct list_head *pos, *n;
1257         struct timeval now;
1258         ENTRY;
1259
1260         do_gettimeofday(&now);
1261         rc = osc_brw_fini_request(request, aa->aa_oa, aa->aa_requested_nob,
1262                                   aa->aa_nio_count, aa->aa_page_count,
1263                                   aa->aa_pga, rc);
1264
1265         CDEBUG(D_INODE, "request %p aa %p rc %d\n", request, aa, rc);
1266
1267         cli = aa->aa_cli;
1268         /* in failout recovery we ignore writeback failure and want
1269          * to just tell llite to unlock the page and continue */
1270         if (request->rq_reqmsg->opc == OST_WRITE && 
1271             (cli->cl_import == NULL || cli->cl_import->imp_invalid)) {
1272                 CDEBUG(D_INODE, "flipping to rc 0 imp %p inv %d\n", 
1273                        cli->cl_import, 
1274                        cli->cl_import ? cli->cl_import->imp_invalid : -1);
1275                 rc = 0;
1276         }
1277
1278         spin_lock(&cli->cl_loi_list_lock);
1279
1280         if (request->rq_reqmsg->opc == OST_WRITE)
1281                 lprocfs_stime_record(&cli->cl_write_stime, &now,
1282                                      &request->rq_rpcd_start);
1283         else
1284                 lprocfs_stime_record(&cli->cl_read_stime, &now,
1285                                      &request->rq_rpcd_start);
1286
1287
1288
1289         /* We need to decrement before osc_ap_completion->osc_wake_cache_waiters
1290          * is called so we know whether to go to sync BRWs or wait for more
1291          * RPCs to complete */
1292         if (request->rq_reqmsg->opc == OST_WRITE)
1293                 cli->cl_w_in_flight--;
1294         else
1295                 cli->cl_r_in_flight--;
1296
1297         /* the caller may re-use the oap after the completion call so
1298          * we need to clean it up a little */
1299         list_for_each_safe(pos, n, &aa->aa_oaps) {
1300                 oap = list_entry(pos, struct osc_async_page, oap_rpc_item);
1301
1302                 //CDEBUG(D_INODE, "page %p index %lu oap %p\n",
1303                        //oap->oap_page, oap->oap_page->index, oap);
1304
1305                 list_del_init(&oap->oap_rpc_item);
1306                 osc_ap_completion(cli, aa->aa_oa, oap, 1, rc);
1307         }
1308
1309         osc_wake_cache_waiters(cli);
1310         osc_check_rpcs(cli);
1311         spin_unlock(&cli->cl_loi_list_lock);
1312
1313         obdo_free(aa->aa_oa);
1314         OBD_FREE(aa->aa_pga, aa->aa_page_count * sizeof(struct brw_page));
1315
1316         RETURN(0);
1317 }
1318
1319 static struct ptlrpc_request *osc_build_req(struct client_obd *cli,
1320                                             struct list_head *rpc_list,
1321                                             int page_count, int cmd)
1322 {
1323         struct ptlrpc_request *req;
1324         struct brw_page *pga = NULL;
1325         int requested_nob, nio_count;
1326         struct osc_brw_async_args *aa;
1327         struct obdo *oa = NULL;
1328         struct obd_async_page_ops *ops = NULL;
1329         void *caller_data = NULL;
1330         struct list_head *pos;
1331         int i, rc;
1332
1333         LASSERT(!list_empty(rpc_list));
1334
1335         OBD_ALLOC(pga, sizeof(*pga) * page_count);
1336         if (pga == NULL)
1337                 RETURN(ERR_PTR(-ENOMEM));
1338
1339         oa = obdo_alloc();
1340         if (oa == NULL)
1341                 GOTO(out, req = ERR_PTR(-ENOMEM));
1342
1343         i = 0;
1344         list_for_each(pos, rpc_list) {
1345                 struct osc_async_page *oap;
1346
1347                 oap = list_entry(pos, struct osc_async_page, oap_rpc_item);
1348                 if (ops == NULL) {
1349                         ops = oap->oap_caller_ops;
1350                         caller_data = oap->oap_caller_data;
1351                 }
1352                 pga[i].disk_offset = oap->oap_obj_off + oap->oap_page_off;
1353                 pga[i].page_offset = pga[i].disk_offset;
1354                 pga[i].pg = oap->oap_page;
1355                 pga[i].count = oap->oap_count;
1356                 pga[i].flag = oap->oap_brw_flags;
1357                 CDEBUG(0, "put page %p index %lu oap %p flg %x to pga\n",
1358                        pga[i].pg, oap->oap_page->index, oap, pga[i].flag);
1359                 i++;
1360         }
1361
1362         /* always get the data for the obdo for the rpc */
1363         LASSERT(ops != NULL);
1364         ops->ap_fill_obdo(caller_data, cmd, oa);
1365
1366         sort_brw_pages(pga, page_count);
1367         rc = osc_brw_prep_request(cmd, cli->cl_import, oa, NULL, page_count,
1368                                   pga, &requested_nob, &nio_count, &req);
1369         if (rc != 0) {
1370                 CERROR("prep_req failed: %d\n", rc);
1371                 GOTO(out, req = ERR_PTR(rc));
1372         }
1373
1374         LASSERT(sizeof(*aa) <= sizeof(req->rq_async_args));
1375         aa = (struct osc_brw_async_args *)&req->rq_async_args;
1376         aa->aa_oa = oa;
1377         aa->aa_requested_nob = requested_nob;
1378         aa->aa_nio_count = nio_count;
1379         aa->aa_page_count = page_count;
1380         aa->aa_pga = pga;
1381         aa->aa_cli = cli;
1382
1383 out:
1384         if (IS_ERR(req)) {
1385                 if (oa)
1386                         obdo_free(oa);
1387                 if (pga)
1388                         OBD_FREE(pga, sizeof(*pga) * page_count);
1389         }
1390         RETURN(req);
1391 }
1392
1393 static void lop_update_pending(struct client_obd *cli,
1394                                struct loi_oap_pages *lop, int cmd, int delta)
1395 {
1396         lop->lop_num_pending += delta;
1397         if (cmd == OBD_BRW_WRITE)
1398                 cli->cl_pending_w_pages += delta;
1399         else
1400                 cli->cl_pending_r_pages += delta;
1401 }
1402
1403 /* the loi lock is held across this function but it's allowed to release
1404  * and reacquire it during its work */
1405 static int osc_send_oap_rpc(struct client_obd *cli, struct lov_oinfo *loi,
1406                             int cmd, struct loi_oap_pages *lop)
1407 {
1408         struct ptlrpc_request *request;
1409         obd_count page_count = 0;
1410         struct list_head *tmp, *pos;
1411         struct osc_async_page *oap = NULL;
1412         struct osc_brw_async_args *aa;
1413         struct obd_async_page_ops *ops;
1414         LIST_HEAD(rpc_list);
1415         ENTRY;
1416
1417         /* first we find the pages we're allowed to work with */
1418         list_for_each_safe(pos, tmp, &lop->lop_pending) {
1419                 oap = list_entry(pos, struct osc_async_page, oap_pending_item);
1420                 ops = oap->oap_caller_ops;
1421
1422                 LASSERT(oap->oap_magic == OAP_MAGIC);
1423
1424                 /* in llite being 'ready' equates to the page being locked
1425                  * until completion unlocks it.  commit_write submits a page
1426                  * as not ready because its unlock will happen unconditionally
1427                  * as the call returns.  if we race with commit_write giving
1428                  * us that page we dont' want to create a hole in the page
1429                  * stream, so we stop and leave the rpc to be fired by
1430                  * another dirtier or kupdated interval (the not ready page
1431                  * will still be on the dirty list).  we could call in
1432                  * at the end of ll_file_write to process the queue again. */
1433                 if (!(oap->oap_async_flags & ASYNC_READY)) {
1434                         int rc = ops->ap_make_ready(oap->oap_caller_data, cmd);
1435                         if (rc < 0)
1436                                 CDEBUG(D_INODE, "oap %p page %p returned %d "
1437                                                 "instead of ready\n", oap,
1438                                                 oap->oap_page, rc);
1439                         switch (rc) {
1440                         case -EAGAIN:
1441                                 /* llite is telling us that the page is still
1442                                  * in commit_write and that we should try
1443                                  * and put it in an rpc again later.  we
1444                                  * break out of the loop so we don't create
1445                                  * a hole in the sequence of pages in the rpc
1446                                  * stream.*/
1447                                 pos = NULL;
1448                                 break;
1449                         case -EINTR:
1450                                 /* the io isn't needed.. tell the checks
1451                                  * below to complete the rpc with EINTR */
1452                                 oap->oap_async_flags |= ASYNC_COUNT_STABLE;
1453                                 oap->oap_count = -EINTR;
1454                                 break;
1455                         case 0:
1456                                 oap->oap_async_flags |= ASYNC_READY;
1457                                 break;
1458                         default:
1459                                 LASSERTF(0, "oap %p page %p returned %d "
1460                                             "from make_ready\n", oap,
1461                                             oap->oap_page, rc);
1462                                 break;
1463                         }
1464                 }
1465                 if (pos == NULL)
1466                         break;
1467
1468                 /* take the page out of our book-keeping */
1469                 list_del_init(&oap->oap_pending_item);
1470                 lop_update_pending(cli, lop, cmd, -1);
1471                 list_del_init(&oap->oap_urgent_item);
1472
1473                 /* ask the caller for the size of the io as the rpc leaves. */
1474                 if (!(oap->oap_async_flags & ASYNC_COUNT_STABLE))
1475                         oap->oap_count =
1476                                 ops->ap_refresh_count(oap->oap_caller_data,cmd);
1477                 if (oap->oap_count <= 0) {
1478                         CDEBUG(D_CACHE, "oap %p count %d, completing\n", oap,
1479                                oap->oap_count);
1480                         osc_ap_completion(cli, NULL, oap, 0, oap->oap_count);
1481                         continue;
1482                 }
1483
1484                 /* now put the page back in our accounting */
1485                 list_add_tail(&oap->oap_rpc_item, &rpc_list);
1486                 if (++page_count >= cli->cl_max_pages_per_rpc)
1487                         break;
1488         }
1489
1490         osc_wake_cache_waiters(cli);
1491
1492         if (page_count == 0)
1493                 RETURN(0);
1494
1495         loi_list_maint(cli, loi);
1496         spin_unlock(&cli->cl_loi_list_lock);
1497
1498         request = osc_build_req(cli, &rpc_list, page_count, cmd);
1499         if (IS_ERR(request)) {
1500                 /* this should happen rarely and is pretty bad, it makes the
1501                  * pending list not follow the dirty order */
1502                 spin_lock(&cli->cl_loi_list_lock);
1503                 list_for_each_safe(pos, tmp, &rpc_list) {
1504                         oap = list_entry(pos, struct osc_async_page,
1505                                          oap_rpc_item);
1506                         list_del_init(&oap->oap_rpc_item);
1507
1508                         /* queued sync pages can be torn down while the pages
1509                          * were between the pending list and the rpc */
1510                         if (oap->oap_interrupted) {
1511                                 CDEBUG(D_INODE, "oap %p interrupted\n", oap);
1512                                 osc_ap_completion(cli, NULL, oap, 0,
1513                                                   oap->oap_count);
1514                                 continue;
1515                         }
1516
1517                         /* put the page back in the loi/lop lists */
1518                         list_add_tail(&oap->oap_pending_item,
1519                                       &lop->lop_pending);
1520                         lop_update_pending(cli, lop, cmd, 1);
1521                         if (oap->oap_async_flags & ASYNC_URGENT)
1522                                 list_add(&oap->oap_urgent_item,
1523                                          &lop->lop_urgent);
1524                 }
1525                 loi_list_maint(cli, loi);
1526                 RETURN(PTR_ERR(request));
1527         }
1528
1529         LASSERT(sizeof(*aa) <= sizeof(request->rq_async_args));
1530         aa = (struct osc_brw_async_args *)&request->rq_async_args;
1531         INIT_LIST_HEAD(&aa->aa_oaps);
1532         list_splice(&rpc_list, &aa->aa_oaps);
1533         INIT_LIST_HEAD(&rpc_list);
1534
1535 #ifdef __KERNEL__
1536         if (cmd == OBD_BRW_READ) {
1537                 lprocfs_oh_tally_log2(&cli->cl_read_page_hist, page_count);
1538                 lprocfs_oh_tally(&cli->cl_read_rpc_hist, cli->cl_r_in_flight);
1539         } else {
1540                 lprocfs_oh_tally_log2(&cli->cl_write_page_hist, page_count);
1541                 lprocfs_oh_tally(&cli->cl_write_rpc_hist,
1542                                  cli->cl_w_in_flight);
1543         }
1544 #endif
1545
1546         spin_lock(&cli->cl_loi_list_lock);
1547
1548         if (cmd == OBD_BRW_READ)
1549                 cli->cl_r_in_flight++;
1550         else
1551                 cli->cl_w_in_flight++;
1552         /* queued sync pages can be torn down while the pages
1553          * were between the pending list and the rpc */
1554         list_for_each(pos, &aa->aa_oaps) {
1555                 oap = list_entry(pos, struct osc_async_page, oap_rpc_item);
1556                 if (oap->oap_interrupted) {
1557                         CDEBUG(D_INODE, "oap %p in req %p interrupted\n",
1558                                oap, request);
1559                         ptlrpc_mark_interrupted(request);
1560                         break;
1561                 }
1562         }
1563
1564         CDEBUG(D_INODE, "req %p: %d pages, aa %p.  now %dr/%dw in flight\n",
1565                         request, page_count, aa, cli->cl_r_in_flight,
1566                         cli->cl_w_in_flight);
1567
1568         oap->oap_request = ptlrpc_request_addref(request);
1569         request->rq_interpret_reply = brw_interpret_oap;
1570         ptlrpcd_add_req(request);
1571         RETURN(1);
1572 }
1573
1574 static int lop_makes_rpc(struct client_obd *cli, struct loi_oap_pages *lop,
1575                          int cmd)
1576 {
1577         int optimal;
1578         ENTRY;
1579
1580         if (lop->lop_num_pending == 0)
1581                 RETURN(0);
1582
1583         /* if we have an invalid import we want to drain the queued pages
1584          * by forcing them through rpcs that immediately fail and complete
1585          * the pages.  recovery relies on this to empty the queued pages
1586          * before canceling the locks and evicting down the llite pages */
1587         if (cli->cl_import == NULL || cli->cl_import->imp_invalid)
1588                 RETURN(1);
1589
1590         /* stream rpcs in queue order as long as as there is an urgent page
1591          * queued.  this is our cheap solution for good batching in the case
1592          * where writepage marks some random page in the middle of the file as
1593          * urgent because of, say, memory pressure */
1594         if (!list_empty(&lop->lop_urgent))
1595                 RETURN(1);
1596
1597         /* fire off rpcs when we have 'optimal' rpcs as tuned for the wire. */
1598         optimal = cli->cl_max_pages_per_rpc;
1599         if (cmd == OBD_BRW_WRITE) {
1600                 /* trigger a write rpc stream as long as there are dirtiers
1601                  * waiting for space.  as they're waiting, they're not going to
1602                  * create more pages to coallesce with what's waiting.. */
1603                 if (!list_empty(&cli->cl_cache_waiters))
1604                         RETURN(1);
1605
1606                 /* *2 to avoid triggering rpcs that would want to include pages
1607                  * that are being queued but which can't be made ready until
1608                  * the queuer finishes with the page. this is a wart for
1609                  * llite::commit_write() */
1610                 optimal += 16;
1611         }
1612         if (lop->lop_num_pending >= optimal)
1613                 RETURN(1);
1614
1615         RETURN(0);
1616 }
1617
1618 static void on_list(struct list_head *item, struct list_head *list,
1619                     int should_be_on)
1620 {
1621         if (list_empty(item) && should_be_on)
1622                 list_add_tail(item, list);
1623         else if (!list_empty(item) && !should_be_on)
1624                 list_del_init(item);
1625 }
1626
1627 /* maintain the loi's cli list membership invariants so that osc_send_oap_rpc
1628  * can find pages to build into rpcs quickly */
1629 static void loi_list_maint(struct client_obd *cli, struct lov_oinfo *loi)
1630 {
1631         on_list(&loi->loi_cli_item, &cli->cl_loi_ready_list,
1632                 lop_makes_rpc(cli, &loi->loi_write_lop, OBD_BRW_WRITE) ||
1633                 lop_makes_rpc(cli, &loi->loi_read_lop, OBD_BRW_READ));
1634
1635         on_list(&loi->loi_write_item, &cli->cl_loi_write_list,
1636                 loi->loi_write_lop.lop_num_pending);
1637
1638         on_list(&loi->loi_read_item, &cli->cl_loi_read_list,
1639                 loi->loi_read_lop.lop_num_pending);
1640 }
1641
1642 #define LOI_DEBUG(LOI, STR, args...)                                     \
1643         CDEBUG(D_INODE, "loi ready %d wr %d:%d rd %d:%d " STR,           \
1644                !list_empty(&(LOI)->loi_cli_item),                        \
1645                (LOI)->loi_write_lop.lop_num_pending,                     \
1646                !list_empty(&(LOI)->loi_write_lop.lop_urgent),            \
1647                (LOI)->loi_read_lop.lop_num_pending,                      \
1648                !list_empty(&(LOI)->loi_read_lop.lop_urgent),             \
1649                args)                                                     \
1650
1651 struct lov_oinfo *osc_next_loi(struct client_obd *cli)
1652 {
1653         ENTRY;
1654         /* first return all objects which we already know to have
1655          * pages ready to be stuffed into rpcs */
1656         if (!list_empty(&cli->cl_loi_ready_list))
1657                 RETURN(list_entry(cli->cl_loi_ready_list.next,
1658                                   struct lov_oinfo, loi_cli_item));
1659
1660         /* then if we have cache waiters, return all objects with queued
1661          * writes.  This is especially important when many small files
1662          * have filled up the cache and not been fired into rpcs because
1663          * they don't pass the nr_pending/object threshhold */
1664         if (!list_empty(&cli->cl_cache_waiters) &&
1665             !list_empty(&cli->cl_loi_write_list))
1666                 RETURN(list_entry(cli->cl_loi_write_list.next,
1667                                   struct lov_oinfo, loi_write_item));
1668
1669         /* then return all queued objects when we have an invalid import
1670          * so that they get flushed */
1671         if (cli->cl_import == NULL || cli->cl_import->imp_invalid) {
1672                 if (!list_empty(&cli->cl_loi_write_list))
1673                         RETURN(list_entry(cli->cl_loi_write_list.next,
1674                                           struct lov_oinfo, loi_write_item));
1675                 if (!list_empty(&cli->cl_loi_read_list))
1676                         RETURN(list_entry(cli->cl_loi_read_list.next,
1677                                           struct lov_oinfo, loi_read_item));
1678         }
1679         RETURN(NULL);
1680 }
1681
1682 /* called with the loi list lock held */
1683 static void osc_check_rpcs(struct client_obd *cli)
1684 {
1685         struct lov_oinfo *loi;
1686         int rc = 0, race_counter = 0;
1687         ENTRY;
1688
1689         while ((loi = osc_next_loi(cli)) != NULL) {
1690                 LOI_DEBUG(loi, "%lu in flight\n", rpcs_in_flight(cli));
1691                 
1692                 if (rpcs_in_flight(cli) >= cli->cl_max_rpcs_in_flight)                        
1693                         break;
1694
1695                 /* attempt some read/write balancing by alternating between
1696                  * reads and writes in an object.  The makes_rpc checks here
1697                  * would be redundant if we were getting read/write work items
1698                  * instead of objects.  we don't want send_oap_rpc to drain a
1699                  * partial read pending queue when we're given this object to
1700                  * do io on writes while there are cache waiters */
1701                 if (lop_makes_rpc(cli, &loi->loi_write_lop, OBD_BRW_WRITE)) {
1702                         rc = osc_send_oap_rpc(cli, loi, OBD_BRW_WRITE,
1703                                               &loi->loi_write_lop);
1704                         if (rc < 0)
1705                                 break;
1706                         if (rc > 0)
1707                                 race_counter = 0;
1708                         else
1709                                 race_counter++;
1710                 }
1711                 if (lop_makes_rpc(cli, &loi->loi_read_lop, OBD_BRW_READ)) {
1712                         rc = osc_send_oap_rpc(cli, loi, OBD_BRW_READ,
1713                                               &loi->loi_read_lop);
1714                         if (rc < 0)
1715                                 break;
1716                         if (rc > 0)
1717                                 race_counter = 0;
1718                         else
1719                                 race_counter++;
1720                 }
1721
1722                 /* attempt some inter-object balancing by issueing rpcs
1723                  * for each object in turn */
1724                 if (!list_empty(&loi->loi_cli_item))
1725                         list_del_init(&loi->loi_cli_item);
1726                 if (!list_empty(&loi->loi_write_item))
1727                         list_del_init(&loi->loi_write_item);
1728                 if (!list_empty(&loi->loi_read_item))
1729                         list_del_init(&loi->loi_read_item);
1730
1731                 loi_list_maint(cli, loi);
1732
1733                 /* send_oap_rpc fails with 0 when make_ready tells it to
1734                  * back off.  llite's make_ready does this when it tries
1735                  * to lock a page queued for write that is already locked.
1736                  * we want to try sending rpcs from many objects, but we
1737                  * don't want to spin failing with 0.  */
1738                 if (race_counter == 10)
1739                         break;
1740         }
1741         EXIT;
1742 }
1743
1744 /* we're trying to queue a page in the osc so we're subject to the
1745  * 'cl_dirty_max' limit on the number of pages that can be queued in the osc.
1746  * If the osc's queued pages are already at that limit, then we want to sleep
1747  * until there is space in the osc's queue for us.  We also may be waiting for
1748  * write credits from the OST if there are RPCs in flight that may return some
1749  * before we fall back to sync writes.
1750  *
1751  * We need this know our allocation was granted in the presence of signals */
1752 static int ocw_granted(struct client_obd *cli, struct osc_cache_waiter *ocw)
1753 {
1754         int rc;
1755         ENTRY;
1756         spin_lock(&cli->cl_loi_list_lock);
1757         rc = list_empty(&ocw->ocw_entry) || rpcs_in_flight(cli) == 0;
1758         spin_unlock(&cli->cl_loi_list_lock);
1759         RETURN(rc);
1760 };
1761
1762 /* Caller must hold loi_list_lock - we drop/regain it if we need to wait for
1763  * grant or cache space. */
1764 static int osc_enter_cache(struct client_obd *cli, struct lov_oinfo *loi,
1765                            struct osc_async_page *oap)
1766 {
1767         struct osc_cache_waiter ocw;
1768         struct l_wait_info lwi = { 0 };
1769         struct timeval start, stop;
1770
1771         CDEBUG(D_CACHE, "dirty: %ld dirty_max: %ld dropped: %lu grant: %lu\n",
1772                cli->cl_dirty, cli->cl_dirty_max, cli->cl_lost_grant,
1773                cli->cl_avail_grant);
1774
1775         if (cli->cl_dirty_max < PAGE_SIZE)
1776                 return(-EDQUOT);
1777
1778         /* Hopefully normal case - cache space and write credits available */
1779         if (cli->cl_dirty + PAGE_SIZE <= cli->cl_dirty_max &&
1780             cli->cl_avail_grant >= PAGE_SIZE) {
1781                 /* account for ourselves */
1782                 osc_consume_write_grant(cli, oap);
1783                 return(0);
1784         }
1785
1786         /* Make sure that there are write rpcs in flight to wait for.  This
1787          * is a little silly as this object may not have any pending but
1788          * other objects sure might. */
1789         if (cli->cl_w_in_flight) {                
1790                 list_add_tail(&ocw.ocw_entry, &cli->cl_cache_waiters);
1791                 init_waitqueue_head(&ocw.ocw_waitq);
1792                 ocw.ocw_oap = oap;
1793                 ocw.ocw_rc = 0;
1794
1795                 loi_list_maint(cli, loi);
1796                 osc_check_rpcs(cli);
1797                 spin_unlock(&cli->cl_loi_list_lock);
1798
1799                 CDEBUG(0, "sleeping for cache space\n");
1800                 do_gettimeofday(&start);
1801                 l_wait_event(ocw.ocw_waitq, ocw_granted(cli, &ocw), &lwi);
1802                 do_gettimeofday(&stop);
1803                 spin_lock(&cli->cl_loi_list_lock);
1804                 lprocfs_stime_record(&cli->cl_enter_stime, &stop, &start);
1805                 if (!list_empty(&ocw.ocw_entry)) {
1806                         list_del(&ocw.ocw_entry);
1807                         RETURN(-EINTR);
1808                 }
1809                 RETURN(ocw.ocw_rc);
1810         }
1811
1812         RETURN(-EDQUOT);
1813 }
1814
1815 /* the companion to enter_cache, called when an oap is no longer part of the
1816  * dirty accounting.. so writeback completes or truncate happens before writing
1817  * starts.  must be called with the loi lock held. */
1818 static void osc_exit_cache(struct client_obd *cli, struct osc_async_page *oap,
1819                            int sent)
1820 {
1821         ENTRY;
1822
1823         if (!(oap->oap_brw_flags & OBD_BRW_FROM_GRANT)) {
1824                 EXIT;
1825                 return;
1826         }
1827
1828         oap->oap_brw_flags &= ~OBD_BRW_FROM_GRANT;
1829         cli->cl_dirty -= PAGE_SIZE;
1830         if (!sent) {
1831                 cli->cl_lost_grant += PAGE_SIZE;
1832                 CDEBUG(D_CACHE, "lost grant: %lu avail grant: %lu dirty: %lu\n",
1833                        cli->cl_lost_grant, cli->cl_avail_grant, cli->cl_dirty);
1834         }
1835
1836         EXIT;
1837 }
1838
1839 int osc_prep_async_page(struct obd_export *exp, struct lov_stripe_md *lsm,
1840                         struct lov_oinfo *loi, struct page *page,
1841                         obd_off offset, struct obd_async_page_ops *ops,
1842                         void *data, void **res)
1843 {
1844         struct osc_async_page *oap;
1845         ENTRY;
1846
1847         OBD_ALLOC(oap, sizeof(*oap));
1848         if (oap == NULL)
1849                 return -ENOMEM;
1850
1851         oap->oap_magic = OAP_MAGIC;
1852         oap->oap_cli = &exp->exp_obd->u.cli;
1853         oap->oap_loi = loi;
1854
1855         oap->oap_caller_ops = ops;
1856         oap->oap_caller_data = data;
1857
1858         oap->oap_page = page;
1859         oap->oap_obj_off = offset;
1860
1861         INIT_LIST_HEAD(&oap->oap_pending_item);
1862         INIT_LIST_HEAD(&oap->oap_urgent_item);
1863         INIT_LIST_HEAD(&oap->oap_rpc_item);
1864
1865         oap->oap_occ.occ_interrupted = osc_occ_interrupted;
1866
1867         CDEBUG(D_CACHE, "oap %p page %p obj off "LPU64"\n", oap, page, offset);
1868         *res = oap;
1869         RETURN(0);
1870 }
1871
1872 static int osc_queue_async_io(struct obd_export *exp, struct lov_stripe_md *lsm,
1873                               struct lov_oinfo *loi, void *cookie,
1874                               int cmd, obd_off off, int count,
1875                               obd_flags brw_flags, enum async_flags async_flags)
1876 {
1877         struct client_obd *cli = &exp->exp_obd->u.cli;
1878         struct osc_async_page *oap;
1879         struct loi_oap_pages *lop;
1880         int rc;
1881         ENTRY;
1882
1883         oap = OAP_FROM_COOKIE(cookie);
1884
1885         if (cli->cl_import == NULL || cli->cl_import->imp_invalid)
1886                 RETURN(-EIO);
1887
1888         if (!list_empty(&oap->oap_pending_item) ||
1889             !list_empty(&oap->oap_urgent_item) ||
1890             !list_empty(&oap->oap_rpc_item))
1891                 RETURN(-EBUSY);
1892
1893         if (loi == NULL)
1894                 loi = &lsm->lsm_oinfo[0];
1895
1896         spin_lock(&cli->cl_loi_list_lock);
1897
1898         oap->oap_cmd = cmd;
1899         oap->oap_async_flags = async_flags;
1900         oap->oap_page_off = off;
1901         oap->oap_count = count;
1902         oap->oap_brw_flags = brw_flags;
1903
1904         if (cmd == OBD_BRW_WRITE) {
1905                 rc = osc_enter_cache(cli, loi, oap);
1906                 if (rc) {
1907                         spin_unlock(&cli->cl_loi_list_lock);
1908                         RETURN(rc);
1909                 }
1910                 lop = &loi->loi_write_lop;
1911         } else {
1912                 lop = &loi->loi_read_lop;
1913         }
1914
1915         if (oap->oap_async_flags & ASYNC_URGENT)
1916                 list_add(&oap->oap_urgent_item, &lop->lop_urgent);
1917         list_add_tail(&oap->oap_pending_item, &lop->lop_pending);
1918         lop_update_pending(cli, lop, cmd, 1);
1919
1920         loi_list_maint(cli, loi);
1921
1922         LOI_DEBUG(loi, "oap %p page %p added for cmd %d\n", oap, oap->oap_page,
1923                   cmd);
1924
1925         osc_check_rpcs(cli);
1926         spin_unlock(&cli->cl_loi_list_lock);
1927
1928         RETURN(0);
1929 }
1930
1931 /* aka (~was & now & flag), but this is more clear :) */
1932 #define SETTING(was, now, flag) (!(was & flag) && (now & flag))
1933
1934 static int osc_set_async_flags(struct obd_export *exp,
1935                                struct lov_stripe_md *lsm,
1936                                struct lov_oinfo *loi, void *cookie,
1937                                obd_flags async_flags)
1938 {
1939         struct client_obd *cli = &exp->exp_obd->u.cli;
1940         struct loi_oap_pages *lop;
1941         struct osc_async_page *oap;
1942         int rc = 0;
1943         ENTRY;
1944
1945         oap = OAP_FROM_COOKIE(cookie);
1946
1947         if (cli->cl_import == NULL || cli->cl_import->imp_invalid)
1948                 RETURN(-EIO);
1949
1950         if (loi == NULL)
1951                 loi = &lsm->lsm_oinfo[0];
1952
1953         if (oap->oap_cmd == OBD_BRW_WRITE) {
1954                 lop = &loi->loi_write_lop;
1955         } else {
1956                 lop = &loi->loi_read_lop;
1957         }
1958
1959         spin_lock(&cli->cl_loi_list_lock);
1960
1961         if (list_empty(&oap->oap_pending_item))
1962                 GOTO(out, rc = -EINVAL);
1963
1964         if ((oap->oap_async_flags & async_flags) == async_flags)
1965                 GOTO(out, rc = 0);
1966
1967         if (SETTING(oap->oap_async_flags, async_flags, ASYNC_READY))
1968                 oap->oap_async_flags |= ASYNC_READY;
1969
1970         if (SETTING(oap->oap_async_flags, async_flags, ASYNC_URGENT)) {
1971                 if (list_empty(&oap->oap_rpc_item)) {
1972                         list_add(&oap->oap_urgent_item, &lop->lop_urgent);
1973                         loi_list_maint(cli, loi);
1974                 }
1975         }
1976
1977         LOI_DEBUG(loi, "oap %p page %p has flags %x\n", oap, oap->oap_page,
1978                         oap->oap_async_flags);
1979 out:
1980         osc_check_rpcs(cli);
1981         spin_unlock(&cli->cl_loi_list_lock);
1982         RETURN(rc);
1983 }
1984
1985 static int osc_queue_group_io(struct obd_export *exp, struct lov_stripe_md *lsm,
1986                              struct lov_oinfo *loi,
1987                              struct obd_io_group *oig, void *cookie,
1988                              int cmd, obd_off off, int count,
1989                              obd_flags brw_flags,
1990                              obd_flags async_flags)
1991 {
1992         struct client_obd *cli = &exp->exp_obd->u.cli;
1993         struct osc_async_page *oap;
1994         struct loi_oap_pages *lop;
1995         ENTRY;
1996
1997         oap = OAP_FROM_COOKIE(cookie);
1998
1999         if (cli->cl_import == NULL || cli->cl_import->imp_invalid)
2000                 RETURN(-EIO);
2001
2002         if (!list_empty(&oap->oap_pending_item) ||
2003             !list_empty(&oap->oap_urgent_item) ||
2004             !list_empty(&oap->oap_rpc_item))
2005                 RETURN(-EBUSY);
2006
2007         if (loi == NULL)
2008                 loi = &lsm->lsm_oinfo[0];
2009
2010         spin_lock(&cli->cl_loi_list_lock);
2011
2012         oap->oap_cmd = cmd;
2013         oap->oap_page_off = off;
2014         oap->oap_count = count;
2015         oap->oap_brw_flags = brw_flags;
2016         oap->oap_async_flags = async_flags;
2017
2018         if (cmd == OBD_BRW_WRITE)
2019                 lop = &loi->loi_write_lop;
2020         else
2021                 lop = &loi->loi_read_lop;
2022
2023         list_add_tail(&oap->oap_pending_item, &lop->lop_pending_group);
2024         if (oap->oap_async_flags & ASYNC_GROUP_SYNC) {
2025                 oap->oap_oig = oig;
2026                 oig_add_one(oig, &oap->oap_occ);
2027         }
2028
2029         LOI_DEBUG(loi, "oap %p page %p on group pending\n", oap, oap->oap_page);
2030
2031         spin_unlock(&cli->cl_loi_list_lock);
2032
2033         RETURN(0);
2034 }
2035
2036 static void osc_group_to_pending(struct client_obd *cli, struct lov_oinfo *loi,
2037                                  struct loi_oap_pages *lop, int cmd)
2038 {
2039         struct list_head *pos, *tmp;
2040         struct osc_async_page *oap;
2041
2042         list_for_each_safe(pos, tmp, &lop->lop_pending_group) {
2043                 oap = list_entry(pos, struct osc_async_page, oap_pending_item);
2044                 list_del(&oap->oap_pending_item);
2045                 list_add_tail(&oap->oap_pending_item, &lop->lop_pending);
2046                 list_add(&oap->oap_urgent_item, &lop->lop_urgent);
2047                 lop_update_pending(cli, lop, cmd, 1);
2048         }
2049         loi_list_maint(cli, loi);
2050 }
2051
2052 static int osc_trigger_group_io(struct obd_export *exp,
2053                                 struct lov_stripe_md *lsm,
2054                                 struct lov_oinfo *loi,
2055                                 struct obd_io_group *oig)
2056 {
2057         struct client_obd *cli = &exp->exp_obd->u.cli;
2058         ENTRY;
2059
2060         if (loi == NULL)
2061                 loi = &lsm->lsm_oinfo[0];
2062
2063         spin_lock(&cli->cl_loi_list_lock);
2064
2065         osc_group_to_pending(cli, loi, &loi->loi_write_lop, OBD_BRW_WRITE);
2066         osc_group_to_pending(cli, loi, &loi->loi_read_lop, OBD_BRW_READ);
2067
2068         osc_check_rpcs(cli);
2069         spin_unlock(&cli->cl_loi_list_lock);
2070
2071         RETURN(0);
2072 }
2073
2074 static int osc_teardown_async_page(struct obd_export *exp,
2075                                    struct lov_stripe_md *lsm,
2076                                    struct lov_oinfo *loi, void *cookie)
2077 {
2078         struct client_obd *cli = &exp->exp_obd->u.cli;
2079         struct loi_oap_pages *lop;
2080         struct osc_async_page *oap;
2081         int rc = 0;
2082         ENTRY;
2083
2084         oap = OAP_FROM_COOKIE(cookie);
2085
2086         if (loi == NULL)
2087                 loi = &lsm->lsm_oinfo[0];
2088
2089         if (oap->oap_cmd == OBD_BRW_WRITE) {
2090                 lop = &loi->loi_write_lop;
2091         } else {
2092                 lop = &loi->loi_read_lop;
2093         }
2094
2095         spin_lock(&cli->cl_loi_list_lock);
2096
2097         if (!list_empty(&oap->oap_rpc_item))
2098                 GOTO(out, rc = -EBUSY);
2099
2100         osc_exit_cache(cli, oap, 0);
2101         osc_wake_cache_waiters(cli);
2102
2103         if (!list_empty(&oap->oap_urgent_item)) {
2104                 list_del_init(&oap->oap_urgent_item);
2105                 oap->oap_async_flags &= ~ASYNC_URGENT;
2106         }
2107         if (!list_empty(&oap->oap_pending_item)) {
2108                 list_del_init(&oap->oap_pending_item);
2109                 lop_update_pending(cli, lop, oap->oap_cmd, -1);
2110         }
2111         loi_list_maint(cli, loi);
2112
2113         LOI_DEBUG(loi, "oap %p page %p torn down\n", oap, oap->oap_page);
2114 out:
2115         spin_unlock(&cli->cl_loi_list_lock);
2116         if (rc == 0)
2117                 OBD_FREE(oap, sizeof(*oap));
2118         RETURN(rc);
2119 }
2120
2121 #ifdef __KERNEL__
2122 /* Note: caller will lock/unlock, and set uptodate on the pages */
2123 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0))
2124 static int sanosc_brw_read(struct obd_export *exp, struct obdo *oa,
2125                            struct lov_stripe_md *lsm, obd_count page_count,
2126                            struct brw_page *pga)
2127 {
2128         struct ptlrpc_request *request = NULL;
2129         struct ost_body *body;
2130         struct niobuf_remote *nioptr;
2131         struct obd_ioobj *iooptr;
2132         int rc, size[3] = {sizeof(*body)}, mapped = 0;
2133         int swab;
2134         ENTRY;
2135
2136         /* XXX does not handle 'new' brw protocol */
2137
2138         size[1] = sizeof(struct obd_ioobj);
2139         size[2] = page_count * sizeof(*nioptr);
2140
2141         request = ptlrpc_prep_req(class_exp2cliimp(exp), LUSTRE_OBD_VERSION,
2142                                   OST_SAN_READ, 3, size, NULL);
2143         if (!request)
2144                 RETURN(-ENOMEM);
2145
2146         body = lustre_msg_buf(request->rq_reqmsg, 0, sizeof(*body));
2147         iooptr = lustre_msg_buf(request->rq_reqmsg, 1, sizeof(*iooptr));
2148         nioptr = lustre_msg_buf(request->rq_reqmsg, 2,
2149                                 sizeof(*nioptr) * page_count);
2150
2151         memcpy(&body->oa, oa, sizeof(body->oa));
2152
2153         obdo_to_ioobj(oa, iooptr);
2154         iooptr->ioo_bufcnt = page_count;
2155
2156         for (mapped = 0; mapped < page_count; mapped++, nioptr++) {
2157                 LASSERT(PageLocked(pga[mapped].pg));
2158                 LASSERT(mapped == 0 ||
2159                         pga[mapped].disk_offset > pga[mapped - 1].disk_offset);
2160
2161                 nioptr->offset = pga[mapped].disk_offset;
2162                 nioptr->len    = pga[mapped].count;
2163                 nioptr->flags  = pga[mapped].flag;
2164         }
2165
2166         size[1] = page_count * sizeof(*nioptr);
2167         request->rq_replen = lustre_msg_size(2, size);
2168
2169         rc = ptlrpc_queue_wait(request);
2170         if (rc)
2171                 GOTO(out_req, rc);
2172
2173         body = lustre_swab_repbuf(request, 0, sizeof(*body),
2174                                   lustre_swab_ost_body);
2175         if (body == NULL) {
2176                 CERROR("Can't unpack body\n");
2177                 GOTO(out_req, rc = -EPROTO);
2178         }
2179
2180         memcpy(oa, &body->oa, sizeof(*oa));
2181
2182         swab = lustre_msg_swabbed(request->rq_repmsg);
2183         LASSERT_REPSWAB(request, 1);
2184         nioptr = lustre_msg_buf(request->rq_repmsg, 1, size[1]);
2185         if (!nioptr) {
2186                 /* nioptr missing or short */
2187                 GOTO(out_req, rc = -EPROTO);
2188         }
2189
2190         /* actual read */
2191         for (mapped = 0; mapped < page_count; mapped++, nioptr++) {
2192                 struct page *page = pga[mapped].pg;
2193                 struct buffer_head *bh;
2194                 kdev_t dev;
2195
2196                 if (swab)
2197                         lustre_swab_niobuf_remote (nioptr);
2198
2199                 /* got san device associated */
2200                 LASSERT(exp->exp_obd != NULL);
2201                 dev = exp->exp_obd->u.cli.cl_sandev;
2202
2203                 /* hole */
2204                 if (!nioptr->offset) {
2205                         CDEBUG(D_PAGE, "hole at ino %lu; index %ld\n",
2206                                         page->mapping->host->i_ino,
2207                                         page->index);
2208                         memset(page_address(page), 0, PAGE_SIZE);
2209                         continue;
2210                 }
2211
2212                 if (!page->buffers) {
2213                         create_empty_buffers(page, dev, PAGE_SIZE);
2214                         bh = page->buffers;
2215
2216                         clear_bit(BH_New, &bh->b_state);
2217                         set_bit(BH_Mapped, &bh->b_state);
2218                         bh->b_blocknr = (unsigned long)nioptr->offset;
2219
2220                         clear_bit(BH_Uptodate, &bh->b_state);
2221
2222                         ll_rw_block(READ, 1, &bh);
2223                 } else {
2224                         bh = page->buffers;
2225
2226                         /* if buffer already existed, it must be the
2227                          * one we mapped before, check it */
2228                         LASSERT(!test_bit(BH_New, &bh->b_state));
2229                         LASSERT(test_bit(BH_Mapped, &bh->b_state));
2230                         LASSERT(bh->b_blocknr == (unsigned long)nioptr->offset);
2231
2232                         /* wait it's io completion */
2233                         if (test_bit(BH_Lock, &bh->b_state))
2234                                 wait_on_buffer(bh);
2235
2236                         if (!test_bit(BH_Uptodate, &bh->b_state))
2237                                 ll_rw_block(READ, 1, &bh);
2238                 }
2239
2240
2241                 /* must do syncronous write here */
2242                 wait_on_buffer(bh);
2243                 if (!buffer_uptodate(bh)) {
2244                         /* I/O error */
2245                         rc = -EIO;
2246                         goto out_req;
2247                 }
2248         }
2249
2250 out_req:
2251         ptlrpc_req_finished(request);
2252         RETURN(rc);
2253 }
2254
2255 static int sanosc_brw_write(struct obd_export *exp, struct obdo *oa,
2256                             struct lov_stripe_md *lsm, obd_count page_count,
2257                             struct brw_page *pga)
2258 {
2259         struct ptlrpc_request *request = NULL;
2260         struct ost_body *body;
2261         struct niobuf_remote *nioptr;
2262         struct obd_ioobj *iooptr;
2263         int rc, size[3] = {sizeof(*body)}, mapped = 0;
2264         int swab;
2265         ENTRY;
2266
2267         size[1] = sizeof(struct obd_ioobj);
2268         size[2] = page_count * sizeof(*nioptr);
2269
2270         request = ptlrpc_prep_req(class_exp2cliimp(exp), LUSTRE_OBD_VERSION,
2271                                   OST_SAN_WRITE, 3, size, NULL);
2272         if (!request)
2273                 RETURN(-ENOMEM);
2274
2275         body = lustre_msg_buf(request->rq_reqmsg, 0, sizeof (*body));
2276         iooptr = lustre_msg_buf(request->rq_reqmsg, 1, sizeof (*iooptr));
2277         nioptr = lustre_msg_buf(request->rq_reqmsg, 2,
2278                                 sizeof (*nioptr) * page_count);
2279
2280         memcpy(&body->oa, oa, sizeof(body->oa));
2281
2282         obdo_to_ioobj(oa, iooptr);
2283         iooptr->ioo_bufcnt = page_count;
2284
2285         /* pack request */
2286         for (mapped = 0; mapped < page_count; mapped++, nioptr++) {
2287                 LASSERT(PageLocked(pga[mapped].pg));
2288                 LASSERT(mapped == 0 ||
2289                         pga[mapped].disk_offset > pga[mapped - 1].disk_offset);
2290
2291                 nioptr->offset = pga[mapped].disk_offset;
2292                 nioptr->len    = pga[mapped].count;
2293                 nioptr->flags  = pga[mapped].flag;
2294         }
2295
2296         size[1] = page_count * sizeof(*nioptr);
2297         request->rq_replen = lustre_msg_size(2, size);
2298
2299         rc = ptlrpc_queue_wait(request);
2300         if (rc)
2301                 GOTO(out_req, rc);
2302
2303         swab = lustre_msg_swabbed (request->rq_repmsg);
2304         LASSERT_REPSWAB (request, 1);
2305         nioptr = lustre_msg_buf(request->rq_repmsg, 1, size[1]);
2306         if (!nioptr) {
2307                 CERROR("absent/short niobuf array\n");
2308                 GOTO(out_req, rc = -EPROTO);
2309         }
2310
2311         /* actual write */
2312         for (mapped = 0; mapped < page_count; mapped++, nioptr++) {
2313                 struct page *page = pga[mapped].pg;
2314                 struct buffer_head *bh;
2315                 kdev_t dev;
2316
2317                 if (swab)
2318                         lustre_swab_niobuf_remote (nioptr);
2319
2320                 /* got san device associated */
2321                 LASSERT(exp->exp_obd != NULL);
2322                 dev = exp->exp_obd->u.cli.cl_sandev;
2323
2324                 if (!page->buffers) {
2325                         create_empty_buffers(page, dev, PAGE_SIZE);
2326                 } else {
2327                         /* checking */
2328                         LASSERT(!test_bit(BH_New, &page->buffers->b_state));
2329                         LASSERT(test_bit(BH_Mapped, &page->buffers->b_state));
2330                         LASSERT(page->buffers->b_blocknr ==
2331                                 (unsigned long)nioptr->offset);
2332                 }
2333                 bh = page->buffers;
2334
2335                 LASSERT(bh);
2336
2337                 /* if buffer locked, wait it's io completion */
2338                 if (test_bit(BH_Lock, &bh->b_state))
2339                         wait_on_buffer(bh);
2340
2341                 clear_bit(BH_New, &bh->b_state);
2342                 set_bit(BH_Mapped, &bh->b_state);
2343
2344                 /* override the block nr */
2345                 bh->b_blocknr = (unsigned long)nioptr->offset;
2346
2347                 /* we are about to write it, so set it
2348                  * uptodate/dirty
2349                  * page lock should garentee no race condition here */
2350                 set_bit(BH_Uptodate, &bh->b_state);
2351                 set_bit(BH_Dirty, &bh->b_state);
2352
2353                 ll_rw_block(WRITE, 1, &bh);
2354
2355                 /* must do syncronous write here */
2356                 wait_on_buffer(bh);
2357                 if (!buffer_uptodate(bh) || test_bit(BH_Dirty, &bh->b_state)) {
2358                         /* I/O error */
2359                         rc = -EIO;
2360                         goto out_req;
2361                 }
2362         }
2363
2364 out_req:
2365         ptlrpc_req_finished(request);
2366         RETURN(rc);
2367 }
2368
2369 static int sanosc_brw(int cmd, struct obd_export *exp, struct obdo *oa,
2370                       struct lov_stripe_md *lsm, obd_count page_count,
2371                       struct brw_page *pga, struct obd_trans_info *oti)
2372 {
2373         ENTRY;
2374
2375         while (page_count) {
2376                 obd_count pages_per_brw;
2377                 int rc;
2378
2379                 if (page_count > PTLRPC_MAX_BRW_PAGES)
2380                         pages_per_brw = PTLRPC_MAX_BRW_PAGES;
2381                 else
2382                         pages_per_brw = page_count;
2383
2384                 if (cmd & OBD_BRW_WRITE)
2385                         rc = sanosc_brw_write(exp, oa, lsm, pages_per_brw,pga);
2386                 else
2387                         rc = sanosc_brw_read(exp, oa, lsm, pages_per_brw, pga);
2388
2389                 if (rc != 0)
2390                         RETURN(rc);
2391
2392                 page_count -= pages_per_brw;
2393                 pga += pages_per_brw;
2394         }
2395         RETURN(0);
2396 }
2397 #endif
2398 #endif
2399
2400 static void osc_set_data_with_check(struct lustre_handle *lockh, void *data)
2401 {
2402         struct ldlm_lock *lock = ldlm_handle2lock(lockh);
2403
2404         if (lock == NULL) {
2405                 CERROR("lockh %p, data %p - client evicted?\n", lockh, data);
2406                 return;
2407         }
2408
2409         lock_res_and_lock(lock);
2410 #ifdef __KERNEL__
2411         if (lock->l_ast_data && lock->l_ast_data != data) {
2412                 struct inode *new_inode = data;
2413                 struct inode *old_inode = lock->l_ast_data;
2414                 if (!(old_inode->i_state & I_FREEING))
2415                         LDLM_ERROR(lock, "inconsistent l_ast_data found");
2416                 LASSERTF(old_inode->i_state & I_FREEING,
2417                          "Found existing inode %p/%lu/%u state %lu in lock: "
2418                          "setting data to %p/%lu/%u\n", old_inode,
2419                          old_inode->i_ino, old_inode->i_generation,
2420                          old_inode->i_state,
2421                          new_inode, new_inode->i_ino, new_inode->i_generation);
2422         }
2423 #endif
2424         lock->l_ast_data = data;
2425         unlock_res_and_lock(lock);
2426         LDLM_LOCK_PUT(lock);
2427 }
2428
2429 static int osc_change_cbdata(struct obd_export *exp, struct lov_stripe_md *lsm,
2430                              ldlm_iterator_t replace, void *data)
2431 {
2432         struct ldlm_res_id res_id = { .name = {0} };
2433         struct obd_device *obd = class_exp2obd(exp);
2434
2435         res_id.name[0] = lsm->lsm_object_id;
2436         res_id.name[2] = lsm->lsm_object_gr;
2437         ldlm_change_cbdata(obd->obd_namespace, &res_id, replace, data);
2438         return 0;
2439 }
2440
2441 static int osc_enqueue(struct obd_export *exp, struct lov_stripe_md *lsm,
2442                        __u32 type, ldlm_policy_data_t *policy, __u32 mode,
2443                        int *flags, void *bl_cb, void *cp_cb, void *gl_cb,
2444                        void *data, __u32 lvb_len, void *lvb_swabber,
2445                        struct lustre_handle *lockh)
2446 {
2447         struct obd_device *obd = exp->exp_obd;
2448         struct ldlm_res_id res_id = { .name = {0} };
2449         struct ost_lvb lvb;
2450         struct ldlm_reply *rep;
2451         struct ptlrpc_request *req = NULL;
2452         int rc;
2453         ENTRY;
2454
2455         res_id.name[0] = lsm->lsm_object_id;
2456         res_id.name[2] = lsm->lsm_object_gr;
2457
2458         /* Filesystem lock extents are extended to page boundaries so that
2459          * dealing with the page cache is a little smoother.  */
2460         policy->l_extent.start -= policy->l_extent.start & ~PAGE_MASK;
2461         policy->l_extent.end |= ~PAGE_MASK;
2462
2463         if (lsm->lsm_oinfo->loi_kms_valid == 0)
2464                 goto no_match;
2465
2466         /* Next, search for already existing extent locks that will cover us */
2467         rc = ldlm_lock_match(obd->obd_namespace, 0, &res_id, type, policy, mode,
2468                              lockh);
2469         if (rc == 1) {
2470                 if (ptlrpcs_check_cred(obd->u.cli.cl_import)) {
2471                         /* return immediately if no credential held */
2472                         ldlm_lock_decref(lockh, mode);
2473                         RETURN(-EACCES);
2474                 }
2475
2476                 osc_set_data_with_check(lockh, data);
2477                 if (*flags & LDLM_FL_HAS_INTENT) {
2478                         /* I would like to be able to ASSERT here that rss <=
2479                          * kms, but I can't, for reasons which are explained in
2480                          * lov_enqueue() */
2481                 }
2482                 /* We already have a lock, and it's referenced */
2483                 RETURN(ELDLM_OK);
2484         }
2485
2486         /* If we're trying to read, we also search for an existing PW lock.  The
2487          * VFS and page cache already protect us locally, so lots of readers/
2488          * writers can share a single PW lock.
2489          *
2490          * There are problems with conversion deadlocks, so instead of
2491          * converting a read lock to a write lock, we'll just enqueue a new
2492          * one.
2493          *
2494          * At some point we should cancel the read lock instead of making them
2495          * send us a blocking callback, but there are problems with canceling
2496          * locks out from other users right now, too. */
2497
2498         if (mode == LCK_PR) {
2499                 rc = ldlm_lock_match(obd->obd_namespace, 0, &res_id, type,
2500                                      policy, LCK_PW, lockh);
2501                 if (rc == 1) {
2502                         if (ptlrpcs_check_cred(obd->u.cli.cl_import)) {
2503                                 /* return immediately if no credential held */
2504                                 ldlm_lock_decref(lockh, LCK_PW);
2505                                 RETURN(-EACCES);
2506                         }
2507
2508                         /* FIXME: This is not incredibly elegant, but it might
2509                          * be more elegant than adding another parameter to
2510                          * lock_match.  I want a second opinion. */
2511                         ldlm_lock_addref(lockh, LCK_PR);
2512                         ldlm_lock_decref(lockh, LCK_PW);
2513                         osc_set_data_with_check(lockh, data);
2514                         RETURN(ELDLM_OK);
2515                 }
2516         }
2517         if (mode == LCK_PW) {
2518                 rc = ldlm_lock_match(obd->obd_namespace, 0, &res_id, type,
2519                                      policy, LCK_PR, lockh);
2520                 if (rc == 1) {
2521                         rc = ldlm_cli_convert(lockh, mode, flags);
2522                         if (!rc) {
2523                                 /* Update readers/writers accounting */
2524                                 ldlm_lock_addref(lockh, LCK_PW);
2525                                 ldlm_lock_decref(lockh, LCK_PR);
2526                                 osc_set_data_with_check(lockh, data);
2527                                 RETURN(ELDLM_OK);
2528                         }
2529                         /* If the conversion failed, we need to drop refcount
2530                            on matched lock before we get new one */
2531                         /* XXX Won't it save us some efforts if we cancel PR
2532                            lock here? We are going to take PW lock anyway and it
2533                            will invalidate PR lock */
2534                         ldlm_lock_decref(lockh, LCK_PR);
2535                         if (rc != EDEADLOCK) {
2536                                 RETURN(rc);
2537                         }
2538                 }
2539         }
2540
2541         if (mode == LCK_PW) {
2542                 rc = ldlm_lock_match(obd->obd_namespace, 0, &res_id, type,
2543                                      policy, LCK_PR, lockh);
2544                 if (rc == 1) {
2545                         rc = ldlm_cli_convert(lockh, mode, flags);
2546                         if (!rc) {
2547                                 /* Update readers/writers accounting */
2548                                 ldlm_lock_addref(lockh, LCK_PW);
2549                                 ldlm_lock_decref(lockh, LCK_PR);
2550                                 osc_set_data_with_check(lockh, data);
2551                                 RETURN(ELDLM_OK);
2552                         }
2553                         /* If the conversion failed, we need to drop refcount
2554                            on matched lock before we get new one */
2555                         /* XXX Won't it save us some efforts if we cancel PR
2556                            lock here? We are going to take PW lock anyway and it
2557                            will invalidate PR lock */
2558                         ldlm_lock_decref(lockh, LCK_PR);
2559                         if (rc != EDEADLOCK) {
2560                                 RETURN(rc);
2561                         }
2562                 }
2563         }
2564
2565  no_match:
2566         if (*flags & LDLM_FL_HAS_INTENT) {
2567                 int size[2] = {0, sizeof(struct ldlm_request)};
2568
2569                 req = ptlrpc_prep_req(class_exp2cliimp(exp), LUSTRE_DLM_VERSION,
2570                                       LDLM_ENQUEUE, 2, size, NULL);
2571                 if (req == NULL)
2572                         RETURN(-ENOMEM);
2573
2574                 size[0] = sizeof(*rep);
2575                 size[1] = sizeof(lvb);
2576                 req->rq_replen = lustre_msg_size(2, size);
2577         }
2578         rc = ldlm_cli_enqueue(exp, req, obd->obd_namespace, res_id, type,
2579                               policy, mode, flags, bl_cb, cp_cb, gl_cb, data,
2580                               &lvb, sizeof(lvb), lustre_swab_ost_lvb, lockh);
2581         if (req != NULL) {
2582                 if (rc == ELDLM_LOCK_ABORTED) {
2583                         /* swabbed by ldlm_cli_enqueue() */
2584                         LASSERT_REPSWABBED(req, 0);
2585                         rep = lustre_msg_buf(req->rq_repmsg, 0, sizeof(*rep));
2586                         LASSERT(rep != NULL);
2587                         if (rep->lock_policy_res1)
2588                                 rc = rep->lock_policy_res1;
2589                 }
2590                 ptlrpc_req_finished(req);
2591         }
2592
2593         if ((*flags & LDLM_FL_HAS_INTENT && rc == ELDLM_LOCK_ABORTED) || !rc) {
2594                 CDEBUG(D_INODE, "received kms == "LPU64", blocks == "LPU64"\n",
2595                        lvb.lvb_size, lvb.lvb_blocks);
2596                 lsm->lsm_oinfo->loi_rss = lvb.lvb_size;
2597                 lsm->lsm_oinfo->loi_blocks = lvb.lvb_blocks;
2598         }
2599
2600         RETURN(rc);
2601 }
2602
2603 static int osc_match(struct obd_export *exp, struct lov_stripe_md *lsm,
2604                      __u32 type, ldlm_policy_data_t *policy, __u32 mode,
2605                      int *flags, void *data, struct lustre_handle *lockh)
2606 {
2607         struct ldlm_res_id res_id = { .name = {0} };
2608         struct obd_device *obd = exp->exp_obd;
2609         int rc;
2610         ENTRY;
2611
2612         res_id.name[0] = lsm->lsm_object_id;
2613         res_id.name[2] = lsm->lsm_object_gr;
2614
2615         OBD_FAIL_RETURN(OBD_FAIL_OSC_MATCH, -EIO);
2616
2617         /* Filesystem lock extents are extended to page boundaries so that
2618          * dealing with the page cache is a little smoother */
2619         policy->l_extent.start -= policy->l_extent.start & ~PAGE_MASK;
2620         policy->l_extent.end |= ~PAGE_MASK;
2621
2622         /* Next, search for already existing extent locks that will cover us */
2623         rc = ldlm_lock_match(obd->obd_namespace, *flags, &res_id, type,
2624                              policy, mode, lockh);
2625         if (rc) {
2626                // if (!(*flags & LDLM_FL_TEST_LOCK))
2627                         osc_set_data_with_check(lockh, data);
2628                 RETURN(rc);
2629         }
2630         /* If we're trying to read, we also search for an existing PW lock.  The
2631          * VFS and page cache already protect us locally, so lots of readers/
2632          * writers can share a single PW lock. */
2633         if (mode == LCK_PR) {
2634                 rc = ldlm_lock_match(obd->obd_namespace, *flags, &res_id, type,
2635                                      policy, LCK_PW, lockh);
2636                 if (rc == 1 && !(*flags & LDLM_FL_TEST_LOCK)) {
2637                         /* FIXME: This is not incredibly elegant, but it might
2638                          * be more elegant than adding another parameter to
2639                          * lock_match.  I want a second opinion. */
2640                         osc_set_data_with_check(lockh, data);
2641                         ldlm_lock_addref(lockh, LCK_PR);
2642                         ldlm_lock_decref(lockh, LCK_PW);
2643                 }
2644         }
2645         RETURN(rc);
2646 }
2647
2648 static int osc_cancel(struct obd_export *exp, struct lov_stripe_md *md,
2649                       __u32 mode, struct lustre_handle *lockh)
2650 {
2651         ENTRY;
2652
2653         if (mode == LCK_GROUP)
2654                 ldlm_lock_decref_and_cancel(lockh, mode);
2655         else
2656                 ldlm_lock_decref(lockh, mode);
2657
2658         RETURN(0);
2659 }
2660
2661 static int osc_cancel_unused(struct obd_export *exp,
2662                              struct lov_stripe_md *lsm,
2663                              int flags, void *opaque)
2664 {
2665         struct obd_device *obd = class_exp2obd(exp);
2666         struct ldlm_res_id res_id = { .name = {0} }, *resp = NULL;
2667
2668         if (lsm != NULL) {
2669                 res_id.name[0] = lsm->lsm_object_id;
2670                 res_id.name[2] = lsm->lsm_object_gr;
2671                 resp = &res_id;
2672         }
2673
2674         return ldlm_cli_cancel_unused(obd->obd_namespace, resp, flags, opaque);
2675 }
2676
2677 static int osc_statfs(struct obd_device *obd, struct obd_statfs *osfs,
2678                       unsigned long max_age)
2679 {
2680         struct obd_statfs *msfs;
2681         struct ptlrpc_request *request;
2682         int rc, size = sizeof(*osfs);
2683         ENTRY;
2684
2685         /* We could possibly pass max_age in the request (as an absolute
2686          * timestamp or a "seconds.usec ago") so the target can avoid doing
2687          * extra calls into the filesystem if that isn't necessary (e.g.
2688          * during mount that would help a bit).  Having relative timestamps
2689          * is not so great if request processing is slow, while absolute
2690          * timestamps are not ideal because they need time synchronization. */
2691         request = ptlrpc_prep_req(obd->u.cli.cl_import, LUSTRE_OBD_VERSION,
2692                                   OST_STATFS, 0, NULL, NULL);
2693         if (!request)
2694                 RETURN(-ENOMEM);
2695
2696         request->rq_replen = lustre_msg_size(1, &size);
2697         request->rq_request_portal = OST_CREATE_PORTAL; //XXX FIXME bug 249
2698
2699         rc = ptlrpc_queue_wait(request);
2700         if (rc)
2701                 GOTO(out, rc);
2702
2703         msfs = lustre_swab_repbuf(request, 0, sizeof(*msfs),
2704                                   lustre_swab_obd_statfs);
2705         if (msfs == NULL) {
2706                 CERROR("Can't unpack obd_statfs\n");
2707                 GOTO(out, rc = -EPROTO);
2708         }
2709
2710         memcpy(osfs, msfs, sizeof(*osfs));
2711
2712         EXIT;
2713  out:
2714         ptlrpc_req_finished(request);
2715         return rc;
2716 }
2717
2718 /* Retrieve object striping information.
2719  *
2720  * @lmmu is a pointer to an in-core struct with lmm_ost_count indicating
2721  * the maximum number of OST indices which will fit in the user buffer.
2722  * lmm_magic must be LOV_MAGIC (we only use 1 slot here).
2723  */
2724 static int osc_getstripe(struct lov_stripe_md *lsm, struct lov_user_md *lump)
2725 {
2726         struct lov_user_md lum, *lumk;
2727         int rc, lum_size;
2728         ENTRY;
2729
2730         if (!lsm)
2731                 RETURN(-ENODATA);
2732
2733         rc = copy_from_user(&lum, lump, sizeof(lum));
2734         if (rc)
2735                 RETURN(-EFAULT);
2736
2737         if (lum.lmm_magic != LOV_USER_MAGIC)
2738                 RETURN(-EINVAL);
2739
2740         if (lum.lmm_stripe_count > 0) {
2741                 lum_size = sizeof(lum) + sizeof(lum.lmm_objects[0]);
2742                 OBD_ALLOC(lumk, lum_size);
2743                 if (!lumk)
2744                         RETURN(-ENOMEM);
2745
2746                 lumk->lmm_objects[0].l_object_id = lsm->lsm_object_id;
2747                 lumk->lmm_objects[0].l_object_gr = lsm->lsm_object_gr;
2748         } else {
2749                 lum_size = sizeof(lum);
2750                 lumk = &lum;
2751         }
2752
2753         lumk->lmm_object_id = lsm->lsm_object_id;
2754         lumk->lmm_object_gr = lsm->lsm_object_gr;
2755         lumk->lmm_stripe_count = 1;
2756
2757         if (copy_to_user(lump, lumk, lum_size))
2758                 rc = -EFAULT;
2759
2760         if (lumk != &lum)
2761                 OBD_FREE(lumk, lum_size);
2762
2763         RETURN(rc);
2764 }
2765
2766 static int osc_iocontrol(unsigned int cmd, struct obd_export *exp, int len,
2767                          void *karg, void *uarg)
2768 {
2769         struct obd_device *obd = exp->exp_obd;
2770         struct obd_ioctl_data *data = karg;
2771         int err = 0;
2772         ENTRY;
2773
2774 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0))
2775         MOD_INC_USE_COUNT;
2776 #else
2777         if (!try_module_get(THIS_MODULE)) {
2778                 CERROR("Can't get module. Is it alive?");
2779                 return -EINVAL;
2780         }
2781 #endif
2782         switch (cmd) {
2783         case OBD_IOC_LOV_GET_CONFIG: {
2784                 char *buf;
2785                 struct lov_desc *desc;
2786                 struct obd_uuid uuid;
2787
2788                 buf = NULL;
2789                 len = 0;
2790                 if (obd_ioctl_getdata(&buf, &len, (void *)uarg))
2791                         GOTO(out, err = -EINVAL);
2792
2793                 data = (struct obd_ioctl_data *)buf;
2794
2795                 if (sizeof(*desc) > data->ioc_inllen1) {
2796                         OBD_FREE(buf, len);
2797                         GOTO(out, err = -EINVAL);
2798                 }
2799
2800                 if (data->ioc_inllen2 < sizeof(uuid)) {
2801                         OBD_FREE(buf, len);
2802                         GOTO(out, err = -EINVAL);
2803                 }
2804
2805                 if (data->ioc_inllen3 < sizeof(__u32)) {
2806                         OBD_FREE(buf, len);
2807                         GOTO(out, err = -EINVAL);
2808                 }
2809
2810                 desc = (struct lov_desc *)data->ioc_inlbuf1;
2811                 desc->ld_tgt_count = 1;
2812                 desc->ld_active_tgt_count = 1;
2813                 desc->ld_default_stripe_count = 1;
2814                 desc->ld_default_stripe_size = 0;
2815                 desc->ld_default_stripe_offset = 0;
2816                 desc->ld_pattern = 0;
2817                 memcpy(&desc->ld_uuid, &obd->obd_uuid, sizeof(uuid));
2818                 memcpy(data->ioc_inlbuf2, &obd->obd_uuid, sizeof(uuid));
2819                 *((__u32 *)data->ioc_inlbuf3) = 1;
2820
2821                 err = copy_to_user((void *)uarg, buf, len);
2822                 if (err)
2823                         err = -EFAULT;
2824                 obd_ioctl_freedata(buf, len);
2825                 GOTO(out, err);
2826         }
2827         case LL_IOC_LOV_SETSTRIPE:
2828                 err = obd_alloc_memmd(exp, karg);
2829                 if (err > 0)
2830                         err = 0;
2831                 GOTO(out, err);
2832         case LL_IOC_LOV_GETSTRIPE:
2833                 err = osc_getstripe(karg, uarg);
2834                 GOTO(out, err);
2835         case OBD_IOC_CLIENT_RECOVER:
2836                 err = ptlrpc_recover_import(obd->u.cli.cl_import,
2837                                             data->ioc_inlbuf1);
2838                 if (err > 0)
2839                         err = 0;
2840                 GOTO(out, err);
2841         case IOC_OSC_SET_ACTIVE:
2842                 err = ptlrpc_set_import_active(obd->u.cli.cl_import,
2843                                                data->ioc_offset);
2844                 GOTO(out, err);
2845         case IOC_OSC_CTL_RECOVERY:
2846                 err = ptlrpc_import_control_recovery(obd->u.cli.cl_import,
2847                                                      data->ioc_offset);
2848                 GOTO(out, err);
2849         default:
2850                 CDEBUG(D_INODE, "unrecognised ioctl %#x by %s\n", cmd, current->comm);
2851                 GOTO(out, err = -ENOTTY);
2852         }
2853 out:
2854 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0))
2855         MOD_DEC_USE_COUNT;
2856 #else
2857         module_put(THIS_MODULE);
2858 #endif
2859         return err;
2860 }
2861
2862 static int osc_get_info(struct obd_export *exp, __u32 keylen,
2863                         void *key, __u32 *vallen, void *val)
2864 {
2865         ENTRY;
2866         if (!vallen || !val)
2867                 RETURN(-EFAULT);
2868
2869         if (keylen > strlen("lock_to_stripe") &&
2870             strcmp(key, "lock_to_stripe") == 0) {
2871                 __u32 *stripe = val;
2872                 *vallen = sizeof(*stripe);
2873                 *stripe = 0;
2874                 RETURN(0);
2875         } else if (keylen >= strlen("last_id") && strcmp(key, "last_id") == 0) {
2876                 struct ptlrpc_request *req;
2877                 obd_id *reply;
2878                 char *bufs[1] = {key};
2879                 int rc;
2880                 req = ptlrpc_prep_req(class_exp2cliimp(exp), LUSTRE_OBD_VERSION,
2881                                       OST_GET_INFO, 1, (int *)&keylen, bufs);
2882                 if (req == NULL)
2883                         RETURN(-ENOMEM);
2884
2885                 req->rq_replen = lustre_msg_size(1, (int *)vallen);
2886                 rc = ptlrpc_queue_wait(req);
2887                 if (rc)
2888                         GOTO(out, rc);
2889
2890                 reply = lustre_swab_repbuf(req, 0, sizeof(*reply),
2891                                            lustre_swab_ost_last_id);
2892                 if (reply == NULL) {
2893                         CERROR("Can't unpack OST last ID\n");
2894                         GOTO(out, rc = -EPROTO);
2895                 }
2896                 *((obd_id *)val) = *reply;
2897         out:
2898                 ptlrpc_req_finished(req);
2899                 RETURN(rc);
2900         }
2901         RETURN(-EPROTO);
2902 }
2903
2904 static int osc_set_info(struct obd_export *exp, obd_count keylen,
2905                         void *key, obd_count vallen, void *val)
2906 {
2907         struct obd_device  *obd = exp->exp_obd;
2908         struct obd_import *imp = class_exp2cliimp(exp);
2909         struct llog_ctxt *ctxt;
2910         int rc = 0;
2911         ENTRY;
2912
2913         if (keylen == strlen("unlinked") &&
2914             memcmp(key, "unlinked", keylen) == 0) {
2915                 struct osc_creator *oscc = &obd->u.cli.cl_oscc;
2916                 spin_lock(&oscc->oscc_lock);
2917                 oscc->oscc_flags &= ~OSCC_FLAG_NOSPC;
2918                 spin_unlock(&oscc->oscc_lock);
2919                 RETURN(0);
2920         }
2921         if (keylen == strlen("unrecovery") &&
2922             memcmp(key, "unrecovery", keylen) == 0) {
2923                 struct osc_creator *oscc = &obd->u.cli.cl_oscc;
2924                 spin_lock(&oscc->oscc_lock);
2925                 oscc->oscc_flags &= ~OSCC_FLAG_RECOVERING;
2926                 spin_unlock(&oscc->oscc_lock);
2927                 RETURN(0);
2928         }
2929         if (keylen == strlen("initial_recov") &&
2930             memcmp(key, "initial_recov", strlen("initial_recov")) == 0) {
2931                 struct obd_import *imp = exp->exp_obd->u.cli.cl_import;
2932                 if (vallen != sizeof(int))
2933                         RETURN(-EINVAL);
2934                 imp->imp_initial_recov = *(int *)val;
2935                 CDEBUG(D_HA, "%s: set imp_no_init_recov = %d\n",
2936                        exp->exp_obd->obd_name,
2937                        imp->imp_initial_recov);
2938                 RETURN(0);
2939         }
2940
2941         if (keylen == strlen("async") &&
2942             memcmp(key, "async", keylen) == 0) {
2943                 struct client_obd *cl = &obd->u.cli;
2944                 if (vallen != sizeof(int))
2945                         RETURN(-EINVAL);
2946                 cl->cl_async = *(int *)val;
2947                 CDEBUG(D_HA, "%s: set async = %d\n",
2948                        obd->obd_name, cl->cl_async);
2949                 RETURN(0);
2950         }
2951
2952         if (keylen == strlen("sec") &&
2953             memcmp(key, "sec", keylen) == 0) {
2954                 struct client_obd *cli = &exp->exp_obd->u.cli;
2955
2956                 cli->cl_sec_flavor = ptlrpcs_name2flavor(val);
2957                 if (cli->cl_sec_flavor == PTLRPCS_FLVR_INVALID) {
2958                         CERROR("unrecognized security flavor %s\n", (char*) val);
2959                         RETURN(-EINVAL);
2960                 }
2961
2962                 RETURN(0);
2963         }
2964
2965         if (keylen == strlen("sec_flags") &&
2966             memcmp(key, "sec_flags", keylen) == 0) {
2967                 struct client_obd *cli = &exp->exp_obd->u.cli;
2968
2969                 cli->cl_sec_flags = *((unsigned long *) val);
2970                 RETURN(0);
2971         }
2972
2973         if (keylen == strlen("flush_cred") &&
2974             memcmp(key, "flush_cred", keylen) == 0) {
2975                 struct client_obd *cli = &exp->exp_obd->u.cli;
2976
2977                 if (cli->cl_import)
2978                         ptlrpcs_import_flush_current_creds(cli->cl_import);
2979                 RETURN(0);
2980         }
2981         if (keylen == strlen("crypto_cb") &&
2982             memcmp(key, "crypto_cb", keylen) == 0) {
2983                 LASSERT(vallen == sizeof(crypt_cb_t));
2984                 osc_crypt_cb = (crypt_cb_t)val; 
2985                 RETURN(0);
2986         }
2987
2988         if (keylen < strlen("mds_conn") ||
2989             memcmp(key, "mds_conn", keylen) != 0)
2990                 RETURN(-EINVAL);
2991
2992         ctxt = llog_get_context(&exp->exp_obd->obd_llogs,
2993                                 LLOG_UNLINK_ORIG_CTXT);
2994         if (ctxt) {
2995                 if (rc == 0)
2996                         rc = llog_initiator_connect(ctxt);
2997                 else
2998                         CERROR("cannot establish the connect for "
2999                                "ctxt %p: %d\n", ctxt, rc);
3000         }
3001
3002         imp->imp_server_timeout = 1;
3003         CDEBUG(D_HA, "pinging OST %s\n", imp->imp_target_uuid.uuid);
3004         imp->imp_pingable = 1;
3005
3006         RETURN(rc);
3007 }
3008
3009
3010 static struct llog_operations osc_size_repl_logops = {
3011         lop_cancel: llog_obd_repl_cancel
3012 };
3013
3014 static struct llog_operations osc_unlink_orig_logops;
3015
3016 static int osc_llog_init(struct obd_device *obd, struct obd_llogs *llogs,
3017                          struct obd_device *tgt, int count,
3018                          struct llog_catid *catid)
3019 {
3020         int rc;
3021         ENTRY;
3022
3023         osc_unlink_orig_logops = llog_lvfs_ops;
3024         osc_unlink_orig_logops.lop_setup = llog_obd_origin_setup;
3025         osc_unlink_orig_logops.lop_cleanup = llog_catalog_cleanup;
3026         osc_unlink_orig_logops.lop_add = llog_catalog_add;
3027         osc_unlink_orig_logops.lop_connect = llog_origin_connect;
3028
3029         rc = obd_llog_setup(obd, llogs, LLOG_UNLINK_ORIG_CTXT, tgt, count,
3030                             &catid->lci_logid, &osc_unlink_orig_logops);
3031         if (rc)
3032                 RETURN(rc);
3033
3034         rc = obd_llog_setup(obd, llogs, LLOG_SIZE_REPL_CTXT, tgt, count, NULL,
3035                             &osc_size_repl_logops);
3036         RETURN(rc);
3037 }
3038
3039 static int osc_llog_finish(struct obd_device *obd,
3040                            struct obd_llogs *llogs, int count)
3041 {
3042         int rc;
3043         ENTRY;
3044
3045         rc = obd_llog_cleanup(llog_get_context(llogs, LLOG_UNLINK_ORIG_CTXT));
3046         if (rc)
3047                 RETURN(rc);
3048
3049         rc = obd_llog_cleanup(llog_get_context(llogs, LLOG_SIZE_REPL_CTXT));
3050         RETURN(rc);
3051 }
3052
3053 static int osc_connect(struct lustre_handle *exph,
3054                        struct obd_device *obd, struct obd_uuid *cluuid,
3055                        struct obd_connect_data *data,
3056                        unsigned long connect_flags)
3057 {
3058         int rc;
3059         ENTRY;
3060         rc = client_connect_import(exph, obd, cluuid, data, connect_flags);
3061         RETURN(rc);
3062 }
3063
3064 static int osc_disconnect(struct obd_export *exp, unsigned long flags)
3065 {
3066         struct obd_device *obd = class_exp2obd(exp);
3067         struct llog_ctxt *ctxt;
3068         int rc;
3069         ENTRY;
3070
3071         ctxt = llog_get_context(&obd->obd_llogs, LLOG_SIZE_REPL_CTXT);
3072         if (obd->u.cli.cl_conn_count == 1)
3073                 /* flush any remaining cancel messages out to the target */
3074                 llog_sync(ctxt, exp);
3075
3076         rc = client_disconnect_export(exp, flags);
3077         RETURN(rc);
3078 }
3079
3080 static int osc_import_event(struct obd_device *obd,
3081                             struct obd_import *imp, 
3082                             enum obd_import_event event)
3083 {
3084         struct client_obd *cli;
3085         int rc = 0;
3086
3087         LASSERT(imp->imp_obd == obd);
3088
3089         switch (event) {
3090         case IMP_EVENT_DISCON: {
3091                 /* Only do this on the MDS OSC's */
3092                 if (imp->imp_server_timeout) {
3093                         struct osc_creator *oscc = &obd->u.cli.cl_oscc;
3094                         
3095                         spin_lock(&oscc->oscc_lock);
3096                         oscc->oscc_flags |= OSCC_FLAG_RECOVERING;
3097                         spin_unlock(&oscc->oscc_lock);
3098                 }
3099                 break;
3100         }
3101         case IMP_EVENT_INACTIVE: {
3102                 if (obd->obd_observer)
3103                         rc = obd_notify(obd->obd_observer, obd, 0, 0);
3104                 break;
3105         }
3106         case IMP_EVENT_INVALIDATE: {
3107                 struct ldlm_namespace *ns = obd->obd_namespace;
3108
3109                 /* Reset grants */
3110                 cli = &obd->u.cli;
3111                 spin_lock(&cli->cl_loi_list_lock);
3112                 cli->cl_avail_grant = 0;
3113                 cli->cl_lost_grant = 0;
3114                 /* all pages go to failing rpcs due to the invalid import */
3115                 osc_check_rpcs(cli);
3116                 spin_unlock(&cli->cl_loi_list_lock);
3117                 
3118                 ldlm_namespace_cleanup(ns, LDLM_FL_LOCAL_ONLY);
3119
3120                 break;
3121         }
3122         case IMP_EVENT_ACTIVE: {
3123                 /* Only do this on the MDS OSC's */
3124                 if (imp->imp_server_timeout) {
3125                         struct osc_creator *oscc = &obd->u.cli.cl_oscc;
3126
3127                         spin_lock(&oscc->oscc_lock);
3128                         oscc->oscc_flags &= ~OSCC_FLAG_NOSPC;
3129                         spin_unlock(&oscc->oscc_lock);
3130                 }
3131
3132                 if (obd->obd_observer)
3133                         rc = obd_notify(obd->obd_observer, obd, 1, 0);
3134                 break;
3135         }
3136         default:
3137                 CERROR("Unknown import event %d\n", event);
3138                 LBUG();
3139         }
3140         RETURN(rc);
3141 }
3142
3143 static int osc_attach(struct obd_device *dev, obd_count len, void *data)
3144 {
3145         struct lprocfs_static_vars lvars;
3146         int rc;
3147         ENTRY;
3148
3149         lprocfs_init_vars(osc,&lvars);
3150         rc = lprocfs_obd_attach(dev, lvars.obd_vars);
3151         if (rc < 0)
3152                 RETURN(rc);
3153
3154         rc = lproc_osc_attach_seqstat(dev);
3155         if (rc < 0) {
3156                 lprocfs_obd_detach(dev);
3157                 RETURN(rc);
3158         }
3159
3160         ptlrpc_lprocfs_register_obd(dev);
3161         RETURN(0);
3162 }
3163
3164 static int osc_detach(struct obd_device *dev)
3165 {
3166         ptlrpc_lprocfs_unregister_obd(dev);
3167         return lprocfs_obd_detach(dev);
3168 }
3169
3170 static int osc_setup(struct obd_device *obd, obd_count len, void *buf)
3171 {
3172         int rc;
3173         ENTRY;
3174         rc = ptlrpcd_addref();
3175         if (rc)
3176                 RETURN(rc);
3177
3178         rc = client_obd_setup(obd, len, buf);
3179         if (rc)
3180                 ptlrpcd_decref();
3181         else
3182                 oscc_init(obd);
3183
3184         RETURN(rc);
3185 }
3186
3187 static int osc_cleanup(struct obd_device *obd, int flags)
3188 {
3189         struct osc_creator *oscc = &obd->u.cli.cl_oscc;
3190         int rc;
3191
3192         rc = ldlm_cli_cancel_unused(obd->obd_namespace, NULL,
3193                                     LDLM_FL_CONFIG_CHANGE, NULL);
3194         if (rc)
3195                 RETURN(rc);
3196
3197         spin_lock(&oscc->oscc_lock);
3198         oscc->oscc_flags &= ~OSCC_FLAG_RECOVERING;
3199         oscc->oscc_flags |= OSCC_FLAG_EXITING;
3200         spin_unlock(&oscc->oscc_lock);
3201
3202         rc = client_obd_cleanup(obd, flags);
3203         ptlrpcd_decref();
3204         RETURN(rc);
3205 }
3206
3207 struct obd_ops osc_obd_ops = {
3208         .o_owner                = THIS_MODULE,
3209         .o_attach               = osc_attach,
3210         .o_detach               = osc_detach,
3211         .o_setup                = osc_setup,
3212         .o_cleanup              = osc_cleanup,
3213         .o_add_conn             = client_import_add_conn,
3214         .o_del_conn             = client_import_del_conn,
3215         .o_connect              = osc_connect,
3216