Whamcloud - gitweb
comment for ll_readahead_state and assertion in osc_send_oap_request() from b1_4
[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                  * Page submitted for IO has to be locked. Either by
1469                  * ->ap_make_ready() or by higher layers.
1470                  *
1471                  * XXX nikita: this assertion should be adjusted when lustre
1472                  * starts using PG_writeback for pages being written out.
1473                  */
1474                 LASSERT(PageLocked(oap->oap_page));
1475
1476                 /* take the page out of our book-keeping */
1477                 list_del_init(&oap->oap_pending_item);
1478                 lop_update_pending(cli, lop, cmd, -1);
1479                 list_del_init(&oap->oap_urgent_item);
1480
1481                 /* ask the caller for the size of the io as the rpc leaves. */
1482                 if (!(oap->oap_async_flags & ASYNC_COUNT_STABLE))
1483                         oap->oap_count =
1484                                 ops->ap_refresh_count(oap->oap_caller_data,cmd);
1485                 if (oap->oap_count <= 0) {
1486                         CDEBUG(D_CACHE, "oap %p count %d, completing\n", oap,
1487                                oap->oap_count);
1488                         osc_ap_completion(cli, NULL, oap, 0, oap->oap_count);
1489                         continue;
1490                 }
1491
1492                 /* now put the page back in our accounting */
1493                 list_add_tail(&oap->oap_rpc_item, &rpc_list);
1494                 if (++page_count >= cli->cl_max_pages_per_rpc)
1495                         break;
1496         }
1497
1498         osc_wake_cache_waiters(cli);
1499
1500         if (page_count == 0)
1501                 RETURN(0);
1502
1503         loi_list_maint(cli, loi);
1504         spin_unlock(&cli->cl_loi_list_lock);
1505
1506         request = osc_build_req(cli, &rpc_list, page_count, cmd);
1507         if (IS_ERR(request)) {
1508                 /* this should happen rarely and is pretty bad, it makes the
1509                  * pending list not follow the dirty order */
1510                 spin_lock(&cli->cl_loi_list_lock);
1511                 list_for_each_safe(pos, tmp, &rpc_list) {
1512                         oap = list_entry(pos, struct osc_async_page,
1513                                          oap_rpc_item);
1514                         list_del_init(&oap->oap_rpc_item);
1515
1516                         /* queued sync pages can be torn down while the pages
1517                          * were between the pending list and the rpc */
1518                         if (oap->oap_interrupted) {
1519                                 CDEBUG(D_INODE, "oap %p interrupted\n", oap);
1520                                 osc_ap_completion(cli, NULL, oap, 0,
1521                                                   oap->oap_count);
1522                                 continue;
1523                         }
1524
1525                         /* put the page back in the loi/lop lists */
1526                         list_add_tail(&oap->oap_pending_item,
1527                                       &lop->lop_pending);
1528                         lop_update_pending(cli, lop, cmd, 1);
1529                         if (oap->oap_async_flags & ASYNC_URGENT)
1530                                 list_add(&oap->oap_urgent_item,
1531                                          &lop->lop_urgent);
1532                 }
1533                 loi_list_maint(cli, loi);
1534                 RETURN(PTR_ERR(request));
1535         }
1536
1537         LASSERT(sizeof(*aa) <= sizeof(request->rq_async_args));
1538         aa = (struct osc_brw_async_args *)&request->rq_async_args;
1539         INIT_LIST_HEAD(&aa->aa_oaps);
1540         list_splice(&rpc_list, &aa->aa_oaps);
1541         INIT_LIST_HEAD(&rpc_list);
1542
1543 #ifdef __KERNEL__
1544         if (cmd == OBD_BRW_READ) {
1545                 lprocfs_oh_tally_log2(&cli->cl_read_page_hist, page_count);
1546                 lprocfs_oh_tally(&cli->cl_read_rpc_hist, cli->cl_r_in_flight);
1547         } else {
1548                 lprocfs_oh_tally_log2(&cli->cl_write_page_hist, page_count);
1549                 lprocfs_oh_tally(&cli->cl_write_rpc_hist,
1550                                  cli->cl_w_in_flight);
1551         }
1552 #endif
1553
1554         spin_lock(&cli->cl_loi_list_lock);
1555
1556         if (cmd == OBD_BRW_READ)
1557                 cli->cl_r_in_flight++;
1558         else
1559                 cli->cl_w_in_flight++;
1560         /* queued sync pages can be torn down while the pages
1561          * were between the pending list and the rpc */
1562         list_for_each(pos, &aa->aa_oaps) {
1563                 oap = list_entry(pos, struct osc_async_page, oap_rpc_item);
1564                 if (oap->oap_interrupted) {
1565                         CDEBUG(D_INODE, "oap %p in req %p interrupted\n",
1566                                oap, request);
1567                         ptlrpc_mark_interrupted(request);
1568                         break;
1569                 }
1570         }
1571
1572         CDEBUG(D_INODE, "req %p: %d pages, aa %p.  now %dr/%dw in flight\n",
1573                         request, page_count, aa, cli->cl_r_in_flight,
1574                         cli->cl_w_in_flight);
1575
1576         oap->oap_request = ptlrpc_request_addref(request);
1577         request->rq_interpret_reply = brw_interpret_oap;
1578         ptlrpcd_add_req(request);
1579         RETURN(1);
1580 }
1581
1582 static int lop_makes_rpc(struct client_obd *cli, struct loi_oap_pages *lop,
1583                          int cmd)
1584 {
1585         int optimal;
1586         ENTRY;
1587
1588         if (lop->lop_num_pending == 0)
1589                 RETURN(0);
1590
1591         /* if we have an invalid import we want to drain the queued pages
1592          * by forcing them through rpcs that immediately fail and complete
1593          * the pages.  recovery relies on this to empty the queued pages
1594          * before canceling the locks and evicting down the llite pages */
1595         if (cli->cl_import == NULL || cli->cl_import->imp_invalid)
1596                 RETURN(1);
1597
1598         /* stream rpcs in queue order as long as as there is an urgent page
1599          * queued.  this is our cheap solution for good batching in the case
1600          * where writepage marks some random page in the middle of the file as
1601          * urgent because of, say, memory pressure */
1602         if (!list_empty(&lop->lop_urgent))
1603                 RETURN(1);
1604
1605         /* fire off rpcs when we have 'optimal' rpcs as tuned for the wire. */
1606         optimal = cli->cl_max_pages_per_rpc;
1607         if (cmd == OBD_BRW_WRITE) {
1608                 /* trigger a write rpc stream as long as there are dirtiers
1609                  * waiting for space.  as they're waiting, they're not going to
1610                  * create more pages to coallesce with what's waiting.. */
1611                 if (!list_empty(&cli->cl_cache_waiters))
1612                         RETURN(1);
1613
1614                 /* *2 to avoid triggering rpcs that would want to include pages
1615                  * that are being queued but which can't be made ready until
1616                  * the queuer finishes with the page. this is a wart for
1617                  * llite::commit_write() */
1618                 optimal += 16;
1619         }
1620         if (lop->lop_num_pending >= optimal)
1621                 RETURN(1);
1622
1623         RETURN(0);
1624 }
1625
1626 static void on_list(struct list_head *item, struct list_head *list,
1627                     int should_be_on)
1628 {
1629         if (list_empty(item) && should_be_on)
1630                 list_add_tail(item, list);
1631         else if (!list_empty(item) && !should_be_on)
1632                 list_del_init(item);
1633 }
1634
1635 /* maintain the loi's cli list membership invariants so that osc_send_oap_rpc
1636  * can find pages to build into rpcs quickly */
1637 static void loi_list_maint(struct client_obd *cli, struct lov_oinfo *loi)
1638 {
1639         on_list(&loi->loi_cli_item, &cli->cl_loi_ready_list,
1640                 lop_makes_rpc(cli, &loi->loi_write_lop, OBD_BRW_WRITE) ||
1641                 lop_makes_rpc(cli, &loi->loi_read_lop, OBD_BRW_READ));
1642
1643         on_list(&loi->loi_write_item, &cli->cl_loi_write_list,
1644                 loi->loi_write_lop.lop_num_pending);
1645
1646         on_list(&loi->loi_read_item, &cli->cl_loi_read_list,
1647                 loi->loi_read_lop.lop_num_pending);
1648 }
1649
1650 #define LOI_DEBUG(LOI, STR, args...)                                     \
1651         CDEBUG(D_INODE, "loi ready %d wr %d:%d rd %d:%d " STR,           \
1652                !list_empty(&(LOI)->loi_cli_item),                        \
1653                (LOI)->loi_write_lop.lop_num_pending,                     \
1654                !list_empty(&(LOI)->loi_write_lop.lop_urgent),            \
1655                (LOI)->loi_read_lop.lop_num_pending,                      \
1656                !list_empty(&(LOI)->loi_read_lop.lop_urgent),             \
1657                args)                                                     \
1658
1659 struct lov_oinfo *osc_next_loi(struct client_obd *cli)
1660 {
1661         ENTRY;
1662         /* first return all objects which we already know to have
1663          * pages ready to be stuffed into rpcs */
1664         if (!list_empty(&cli->cl_loi_ready_list))
1665                 RETURN(list_entry(cli->cl_loi_ready_list.next,
1666                                   struct lov_oinfo, loi_cli_item));
1667
1668         /* then if we have cache waiters, return all objects with queued
1669          * writes.  This is especially important when many small files
1670          * have filled up the cache and not been fired into rpcs because
1671          * they don't pass the nr_pending/object threshhold */
1672         if (!list_empty(&cli->cl_cache_waiters) &&
1673             !list_empty(&cli->cl_loi_write_list))
1674                 RETURN(list_entry(cli->cl_loi_write_list.next,
1675                                   struct lov_oinfo, loi_write_item));
1676
1677         /* then return all queued objects when we have an invalid import
1678          * so that they get flushed */
1679         if (cli->cl_import == NULL || cli->cl_import->imp_invalid) {
1680                 if (!list_empty(&cli->cl_loi_write_list))
1681                         RETURN(list_entry(cli->cl_loi_write_list.next,
1682                                           struct lov_oinfo, loi_write_item));
1683                 if (!list_empty(&cli->cl_loi_read_list))
1684                         RETURN(list_entry(cli->cl_loi_read_list.next,
1685                                           struct lov_oinfo, loi_read_item));
1686         }
1687         RETURN(NULL);
1688 }
1689
1690 /* called with the loi list lock held */
1691 static void osc_check_rpcs(struct client_obd *cli)
1692 {
1693         struct lov_oinfo *loi;
1694         int rc = 0, race_counter = 0;
1695         ENTRY;
1696
1697         while ((loi = osc_next_loi(cli)) != NULL) {
1698                 LOI_DEBUG(loi, "%lu in flight\n", rpcs_in_flight(cli));
1699
1700                 if (rpcs_in_flight(cli) >= cli->cl_max_rpcs_in_flight)
1701                         break;
1702
1703                 /* attempt some read/write balancing by alternating between
1704                  * reads and writes in an object.  The makes_rpc checks here
1705                  * would be redundant if we were getting read/write work items
1706                  * instead of objects.  we don't want send_oap_rpc to drain a
1707                  * partial read pending queue when we're given this object to
1708                  * do io on writes while there are cache waiters */
1709                 if (lop_makes_rpc(cli, &loi->loi_write_lop, OBD_BRW_WRITE)) {
1710                         rc = osc_send_oap_rpc(cli, loi, OBD_BRW_WRITE,
1711                                               &loi->loi_write_lop);
1712                         if (rc < 0)
1713                                 break;
1714                         if (rc > 0)
1715                                 race_counter = 0;
1716                         else
1717                                 race_counter++;
1718                 }
1719                 if (lop_makes_rpc(cli, &loi->loi_read_lop, OBD_BRW_READ)) {
1720                         rc = osc_send_oap_rpc(cli, loi, OBD_BRW_READ,
1721                                               &loi->loi_read_lop);
1722                         if (rc < 0)
1723                                 break;
1724                         if (rc > 0)
1725                                 race_counter = 0;
1726                         else
1727                                 race_counter++;
1728                 }
1729
1730                 /* attempt some inter-object balancing by issueing rpcs
1731                  * for each object in turn */
1732                 if (!list_empty(&loi->loi_cli_item))
1733                         list_del_init(&loi->loi_cli_item);
1734                 if (!list_empty(&loi->loi_write_item))
1735                         list_del_init(&loi->loi_write_item);
1736                 if (!list_empty(&loi->loi_read_item))
1737                         list_del_init(&loi->loi_read_item);
1738
1739                 loi_list_maint(cli, loi);
1740
1741                 /* send_oap_rpc fails with 0 when make_ready tells it to
1742                  * back off.  llite's make_ready does this when it tries
1743                  * to lock a page queued for write that is already locked.
1744                  * we want to try sending rpcs from many objects, but we
1745                  * don't want to spin failing with 0.  */
1746                 if (race_counter == 10)
1747                         break;
1748         }
1749         EXIT;
1750 }
1751
1752 /* we're trying to queue a page in the osc so we're subject to the
1753  * 'cl_dirty_max' limit on the number of pages that can be queued in the osc.
1754  * If the osc's queued pages are already at that limit, then we want to sleep
1755  * until there is space in the osc's queue for us.  We also may be waiting for
1756  * write credits from the OST if there are RPCs in flight that may return some
1757  * before we fall back to sync writes.
1758  *
1759  * We need this know our allocation was granted in the presence of signals */
1760 static int ocw_granted(struct client_obd *cli, struct osc_cache_waiter *ocw)
1761 {
1762         int rc;
1763         ENTRY;
1764         spin_lock(&cli->cl_loi_list_lock);
1765         rc = list_empty(&ocw->ocw_entry) || rpcs_in_flight(cli) == 0;
1766         spin_unlock(&cli->cl_loi_list_lock);
1767         RETURN(rc);
1768 };
1769
1770 /* Caller must hold loi_list_lock - we drop/regain it if we need to wait for
1771  * grant or cache space. */
1772 static int osc_enter_cache(struct client_obd *cli, struct lov_oinfo *loi,
1773                            struct osc_async_page *oap)
1774 {
1775         struct osc_cache_waiter ocw;
1776         struct l_wait_info lwi = { 0 };
1777         struct timeval start, stop;
1778
1779         CDEBUG(D_CACHE, "dirty: %ld dirty_max: %ld dropped: %lu grant: %lu\n",
1780                cli->cl_dirty, cli->cl_dirty_max, cli->cl_lost_grant,
1781                cli->cl_avail_grant);
1782
1783         if (cli->cl_dirty_max < PAGE_SIZE)
1784                 return(-EDQUOT);
1785
1786         /* Hopefully normal case - cache space and write credits available */
1787         if (cli->cl_dirty + PAGE_SIZE <= cli->cl_dirty_max &&
1788             cli->cl_avail_grant >= PAGE_SIZE) {
1789                 /* account for ourselves */
1790                 osc_consume_write_grant(cli, oap);
1791                 return(0);
1792         }
1793
1794         /* Make sure that there are write rpcs in flight to wait for.  This
1795          * is a little silly as this object may not have any pending but
1796          * other objects sure might. */
1797         if (cli->cl_w_in_flight) {
1798                 list_add_tail(&ocw.ocw_entry, &cli->cl_cache_waiters);
1799                 init_waitqueue_head(&ocw.ocw_waitq);
1800                 ocw.ocw_oap = oap;
1801                 ocw.ocw_rc = 0;
1802
1803                 loi_list_maint(cli, loi);
1804                 osc_check_rpcs(cli);
1805                 spin_unlock(&cli->cl_loi_list_lock);
1806
1807                 CDEBUG(0, "sleeping for cache space\n");
1808                 do_gettimeofday(&start);
1809                 l_wait_event(ocw.ocw_waitq, ocw_granted(cli, &ocw), &lwi);
1810                 do_gettimeofday(&stop);
1811                 spin_lock(&cli->cl_loi_list_lock);
1812                 lprocfs_stime_record(&cli->cl_enter_stime, &stop, &start);
1813                 if (!list_empty(&ocw.ocw_entry)) {
1814                         list_del(&ocw.ocw_entry);
1815                         RETURN(-EINTR);
1816                 }
1817                 RETURN(ocw.ocw_rc);
1818         }
1819
1820         RETURN(-EDQUOT);
1821 }
1822
1823 /* the companion to enter_cache, called when an oap is no longer part of the
1824  * dirty accounting.. so writeback completes or truncate happens before writing
1825  * starts.  must be called with the loi lock held. */
1826 static void osc_exit_cache(struct client_obd *cli, struct osc_async_page *oap,
1827                            int sent)
1828 {
1829         ENTRY;
1830
1831         if (!(oap->oap_brw_flags & OBD_BRW_FROM_GRANT)) {
1832                 EXIT;
1833                 return;
1834         }
1835
1836         oap->oap_brw_flags &= ~OBD_BRW_FROM_GRANT;
1837         cli->cl_dirty -= PAGE_SIZE;
1838         if (!sent) {
1839                 cli->cl_lost_grant += PAGE_SIZE;
1840                 CDEBUG(D_CACHE, "lost grant: %lu avail grant: %lu dirty: %lu\n",
1841                        cli->cl_lost_grant, cli->cl_avail_grant, cli->cl_dirty);
1842         }
1843
1844         EXIT;
1845 }
1846
1847 int osc_prep_async_page(struct obd_export *exp, struct lov_stripe_md *lsm,
1848                         struct lov_oinfo *loi, struct page *page,
1849                         obd_off offset, struct obd_async_page_ops *ops,
1850                         void *data, void **res)
1851 {
1852         struct osc_async_page *oap;
1853         ENTRY;
1854
1855         OBD_ALLOC(oap, sizeof(*oap));
1856         if (oap == NULL)
1857                 return -ENOMEM;
1858
1859         oap->oap_magic = OAP_MAGIC;
1860         oap->oap_cli = &exp->exp_obd->u.cli;
1861         oap->oap_loi = loi;
1862
1863         oap->oap_caller_ops = ops;
1864         oap->oap_caller_data = data;
1865
1866         oap->oap_page = page;
1867         oap->oap_obj_off = offset;
1868
1869         INIT_LIST_HEAD(&oap->oap_pending_item);
1870         INIT_LIST_HEAD(&oap->oap_urgent_item);
1871         INIT_LIST_HEAD(&oap->oap_rpc_item);
1872
1873         oap->oap_occ.occ_interrupted = osc_occ_interrupted;
1874
1875         CDEBUG(D_CACHE, "oap %p page %p obj off "LPU64"\n", oap, page, offset);
1876         *res = oap;
1877         RETURN(0);
1878 }
1879
1880 static int osc_queue_async_io(struct obd_export *exp, struct lov_stripe_md *lsm,
1881                               struct lov_oinfo *loi, void *cookie,
1882                               int cmd, obd_off off, int count,
1883                               obd_flags brw_flags, enum async_flags async_flags)
1884 {
1885         struct client_obd *cli = &exp->exp_obd->u.cli;
1886         struct osc_async_page *oap;
1887         struct loi_oap_pages *lop;
1888         int rc;
1889         ENTRY;
1890
1891         oap = OAP_FROM_COOKIE(cookie);
1892
1893         if (cli->cl_import == NULL || cli->cl_import->imp_invalid)
1894                 RETURN(-EIO);
1895
1896         if (!list_empty(&oap->oap_pending_item) ||
1897             !list_empty(&oap->oap_urgent_item) ||
1898             !list_empty(&oap->oap_rpc_item))
1899                 RETURN(-EBUSY);
1900
1901         if (loi == NULL)
1902                 loi = &lsm->lsm_oinfo[0];
1903
1904         spin_lock(&cli->cl_loi_list_lock);
1905
1906         oap->oap_cmd = cmd;
1907         oap->oap_async_flags = async_flags;
1908         oap->oap_page_off = off;
1909         oap->oap_count = count;
1910         oap->oap_brw_flags = brw_flags;
1911
1912         if (cmd == OBD_BRW_WRITE) {
1913                 rc = osc_enter_cache(cli, loi, oap);
1914                 if (rc) {
1915                         spin_unlock(&cli->cl_loi_list_lock);
1916                         RETURN(rc);
1917                 }
1918                 lop = &loi->loi_write_lop;
1919         } else {
1920                 lop = &loi->loi_read_lop;
1921         }
1922
1923         if (oap->oap_async_flags & ASYNC_URGENT)
1924                 list_add(&oap->oap_urgent_item, &lop->lop_urgent);
1925         list_add_tail(&oap->oap_pending_item, &lop->lop_pending);
1926         lop_update_pending(cli, lop, cmd, 1);
1927
1928         loi_list_maint(cli, loi);
1929
1930         LOI_DEBUG(loi, "oap %p page %p added for cmd %d\n", oap, oap->oap_page,
1931                   cmd);
1932
1933         osc_check_rpcs(cli);
1934         spin_unlock(&cli->cl_loi_list_lock);
1935
1936         RETURN(0);
1937 }
1938
1939 /* aka (~was & now & flag), but this is more clear :) */
1940 #define SETTING(was, now, flag) (!(was & flag) && (now & flag))
1941
1942 static int osc_set_async_flags(struct obd_export *exp,
1943                                struct lov_stripe_md *lsm,
1944                                struct lov_oinfo *loi, void *cookie,
1945                                obd_flags async_flags)
1946 {
1947         struct client_obd *cli = &exp->exp_obd->u.cli;
1948         struct loi_oap_pages *lop;
1949         struct osc_async_page *oap;
1950         int rc = 0;
1951         ENTRY;
1952
1953         oap = OAP_FROM_COOKIE(cookie);
1954
1955         if (cli->cl_import == NULL || cli->cl_import->imp_invalid)
1956                 RETURN(-EIO);
1957
1958         if (loi == NULL)
1959                 loi = &lsm->lsm_oinfo[0];
1960
1961         if (oap->oap_cmd == OBD_BRW_WRITE) {
1962                 lop = &loi->loi_write_lop;
1963         } else {
1964                 lop = &loi->loi_read_lop;
1965         }
1966
1967         spin_lock(&cli->cl_loi_list_lock);
1968
1969         if (list_empty(&oap->oap_pending_item))
1970                 GOTO(out, rc = -EINVAL);
1971
1972         if ((oap->oap_async_flags & async_flags) == async_flags)
1973                 GOTO(out, rc = 0);
1974
1975         if (SETTING(oap->oap_async_flags, async_flags, ASYNC_READY))
1976                 oap->oap_async_flags |= ASYNC_READY;
1977
1978         if (SETTING(oap->oap_async_flags, async_flags, ASYNC_URGENT)) {
1979                 if (list_empty(&oap->oap_rpc_item)) {
1980                         list_add(&oap->oap_urgent_item, &lop->lop_urgent);
1981                         loi_list_maint(cli, loi);
1982                 }
1983         }
1984
1985         LOI_DEBUG(loi, "oap %p page %p has flags %x\n", oap, oap->oap_page,
1986                         oap->oap_async_flags);
1987 out:
1988         osc_check_rpcs(cli);
1989         spin_unlock(&cli->cl_loi_list_lock);
1990         RETURN(rc);
1991 }
1992
1993 static int osc_queue_group_io(struct obd_export *exp, struct lov_stripe_md *lsm,
1994                              struct lov_oinfo *loi,
1995                              struct obd_io_group *oig, void *cookie,
1996                              int cmd, obd_off off, int count,
1997                              obd_flags brw_flags,
1998                              obd_flags async_flags)
1999 {
2000         struct client_obd *cli = &exp->exp_obd->u.cli;
2001         struct osc_async_page *oap;
2002         struct loi_oap_pages *lop;
2003         ENTRY;
2004
2005         oap = OAP_FROM_COOKIE(cookie);
2006
2007         if (cli->cl_import == NULL || cli->cl_import->imp_invalid)
2008                 RETURN(-EIO);
2009
2010         if (!list_empty(&oap->oap_pending_item) ||
2011             !list_empty(&oap->oap_urgent_item) ||
2012             !list_empty(&oap->oap_rpc_item))
2013                 RETURN(-EBUSY);
2014
2015         if (loi == NULL)
2016                 loi = &lsm->lsm_oinfo[0];
2017
2018         spin_lock(&cli->cl_loi_list_lock);
2019
2020         oap->oap_cmd = cmd;
2021         oap->oap_page_off = off;
2022         oap->oap_count = count;
2023         oap->oap_brw_flags = brw_flags;
2024         oap->oap_async_flags = async_flags;
2025
2026         if (cmd == OBD_BRW_WRITE)
2027                 lop = &loi->loi_write_lop;
2028         else
2029                 lop = &loi->loi_read_lop;
2030
2031         list_add_tail(&oap->oap_pending_item, &lop->lop_pending_group);
2032         if (oap->oap_async_flags & ASYNC_GROUP_SYNC) {
2033                 oap->oap_oig = oig;
2034                 oig_add_one(oig, &oap->oap_occ);
2035         }
2036
2037         LOI_DEBUG(loi, "oap %p page %p on group pending\n", oap, oap->oap_page);
2038
2039         spin_unlock(&cli->cl_loi_list_lock);
2040
2041         RETURN(0);
2042 }
2043
2044 static void osc_group_to_pending(struct client_obd *cli, struct lov_oinfo *loi,
2045                                  struct loi_oap_pages *lop, int cmd)
2046 {
2047         struct list_head *pos, *tmp;
2048         struct osc_async_page *oap;
2049
2050         list_for_each_safe(pos, tmp, &lop->lop_pending_group) {
2051                 oap = list_entry(pos, struct osc_async_page, oap_pending_item);
2052                 list_del(&oap->oap_pending_item);
2053                 list_add_tail(&oap->oap_pending_item, &lop->lop_pending);
2054                 list_add(&oap->oap_urgent_item, &lop->lop_urgent);
2055                 lop_update_pending(cli, lop, cmd, 1);
2056         }
2057         loi_list_maint(cli, loi);
2058 }
2059
2060 static int osc_trigger_group_io(struct obd_export *exp,
2061                                 struct lov_stripe_md *lsm,
2062                                 struct lov_oinfo *loi,
2063                                 struct obd_io_group *oig)
2064 {
2065         struct client_obd *cli = &exp->exp_obd->u.cli;
2066         ENTRY;
2067
2068         if (loi == NULL)
2069                 loi = &lsm->lsm_oinfo[0];
2070
2071         spin_lock(&cli->cl_loi_list_lock);
2072
2073         osc_group_to_pending(cli, loi, &loi->loi_write_lop, OBD_BRW_WRITE);
2074         osc_group_to_pending(cli, loi, &loi->loi_read_lop, OBD_BRW_READ);
2075
2076         osc_check_rpcs(cli);
2077         spin_unlock(&cli->cl_loi_list_lock);
2078
2079         RETURN(0);
2080 }
2081
2082 static int osc_teardown_async_page(struct obd_export *exp,
2083                                    struct lov_stripe_md *lsm,
2084                                    struct lov_oinfo *loi, void *cookie)
2085 {
2086         struct client_obd *cli = &exp->exp_obd->u.cli;
2087         struct loi_oap_pages *lop;
2088         struct osc_async_page *oap;
2089         int rc = 0;
2090         ENTRY;
2091
2092         oap = OAP_FROM_COOKIE(cookie);
2093
2094         if (loi == NULL)
2095                 loi = &lsm->lsm_oinfo[0];
2096
2097         if (oap->oap_cmd == OBD_BRW_WRITE) {
2098                 lop = &loi->loi_write_lop;
2099         } else {
2100                 lop = &loi->loi_read_lop;
2101         }
2102
2103         spin_lock(&cli->cl_loi_list_lock);
2104
2105         if (!list_empty(&oap->oap_rpc_item))
2106                 GOTO(out, rc = -EBUSY);
2107
2108         osc_exit_cache(cli, oap, 0);
2109         osc_wake_cache_waiters(cli);
2110
2111         if (!list_empty(&oap->oap_urgent_item)) {
2112                 list_del_init(&oap->oap_urgent_item);
2113                 oap->oap_async_flags &= ~ASYNC_URGENT;
2114         }
2115         if (!list_empty(&oap->oap_pending_item)) {
2116                 list_del_init(&oap->oap_pending_item);
2117                 lop_update_pending(cli, lop, oap->oap_cmd, -1);
2118         }
2119         loi_list_maint(cli, loi);
2120
2121         LOI_DEBUG(loi, "oap %p page %p torn down\n", oap, oap->oap_page);
2122 out:
2123         spin_unlock(&cli->cl_loi_list_lock);
2124         if (rc == 0)
2125                 OBD_FREE(oap, sizeof(*oap));
2126         RETURN(rc);
2127 }
2128
2129 #ifdef __KERNEL__
2130 /* Note: caller will lock/unlock, and set uptodate on the pages */
2131 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0))
2132 static int sanosc_brw_read(struct obd_export *exp, struct obdo *oa,
2133                            struct lov_stripe_md *lsm, obd_count page_count,
2134                            struct brw_page *pga)
2135 {
2136         struct ptlrpc_request *request = NULL;
2137         struct ost_body *body;
2138         struct niobuf_remote *nioptr;
2139         struct obd_ioobj *iooptr;
2140         int rc, size[3] = {sizeof(*body)}, mapped = 0;
2141         int swab;
2142         ENTRY;
2143
2144         /* XXX does not handle 'new' brw protocol */
2145
2146         size[1] = sizeof(struct obd_ioobj);
2147         size[2] = page_count * sizeof(*nioptr);
2148
2149         request = ptlrpc_prep_req(class_exp2cliimp(exp), LUSTRE_OBD_VERSION,
2150                                   OST_SAN_READ, 3, size, NULL);
2151         if (!request)
2152                 RETURN(-ENOMEM);
2153
2154         body = lustre_msg_buf(request->rq_reqmsg, 0, sizeof(*body));
2155         iooptr = lustre_msg_buf(request->rq_reqmsg, 1, sizeof(*iooptr));
2156         nioptr = lustre_msg_buf(request->rq_reqmsg, 2,
2157                                 sizeof(*nioptr) * page_count);
2158
2159         memcpy(&body->oa, oa, sizeof(body->oa));
2160
2161         obdo_to_ioobj(oa, iooptr);
2162         iooptr->ioo_bufcnt = page_count;
2163
2164         for (mapped = 0; mapped < page_count; mapped++, nioptr++) {
2165                 LASSERT(PageLocked(pga[mapped].pg));
2166                 LASSERT(mapped == 0 ||
2167                         pga[mapped].disk_offset > pga[mapped - 1].disk_offset);
2168
2169                 nioptr->offset = pga[mapped].disk_offset;
2170                 nioptr->len    = pga[mapped].count;
2171                 nioptr->flags  = pga[mapped].flag;
2172         }
2173
2174         size[1] = page_count * sizeof(*nioptr);
2175         request->rq_replen = lustre_msg_size(2, size);
2176
2177         rc = ptlrpc_queue_wait(request);
2178         if (rc)
2179                 GOTO(out_req, rc);
2180
2181         body = lustre_swab_repbuf(request, 0, sizeof(*body),
2182                                   lustre_swab_ost_body);
2183         if (body == NULL) {
2184                 CERROR("Can't unpack body\n");
2185                 GOTO(out_req, rc = -EPROTO);
2186         }
2187
2188         memcpy(oa, &body->oa, sizeof(*oa));
2189
2190         swab = lustre_msg_swabbed(request->rq_repmsg);
2191         LASSERT_REPSWAB(request, 1);
2192         nioptr = lustre_msg_buf(request->rq_repmsg, 1, size[1]);
2193         if (!nioptr) {
2194                 /* nioptr missing or short */
2195                 GOTO(out_req, rc = -EPROTO);
2196         }
2197
2198         /* actual read */
2199         for (mapped = 0; mapped < page_count; mapped++, nioptr++) {
2200                 struct page *page = pga[mapped].pg;
2201                 struct buffer_head *bh;
2202                 kdev_t dev;
2203
2204                 if (swab)
2205                         lustre_swab_niobuf_remote (nioptr);
2206
2207                 /* got san device associated */
2208                 LASSERT(exp->exp_obd != NULL);
2209                 dev = exp->exp_obd->u.cli.cl_sandev;
2210
2211                 /* hole */
2212                 if (!nioptr->offset) {
2213                         CDEBUG(D_PAGE, "hole at ino %lu; index %ld\n",
2214                                         page->mapping->host->i_ino,
2215                                         page->index);
2216                         memset(page_address(page), 0, PAGE_SIZE);
2217                         continue;
2218                 }
2219
2220                 if (!page->buffers) {
2221                         create_empty_buffers(page, dev, PAGE_SIZE);
2222                         bh = page->buffers;
2223
2224                         clear_bit(BH_New, &bh->b_state);
2225                         set_bit(BH_Mapped, &bh->b_state);
2226                         bh->b_blocknr = (unsigned long)nioptr->offset;
2227
2228                         clear_bit(BH_Uptodate, &bh->b_state);
2229
2230                         ll_rw_block(READ, 1, &bh);
2231                 } else {
2232                         bh = page->buffers;
2233
2234                         /* if buffer already existed, it must be the
2235                          * one we mapped before, check it */
2236                         LASSERT(!test_bit(BH_New, &bh->b_state));
2237                         LASSERT(test_bit(BH_Mapped, &bh->b_state));
2238                         LASSERT(bh->b_blocknr == (unsigned long)nioptr->offset);
2239
2240                         /* wait it's io completion */
2241                         if (test_bit(BH_Lock, &bh->b_state))
2242                                 wait_on_buffer(bh);
2243
2244                         if (!test_bit(BH_Uptodate, &bh->b_state))
2245                                 ll_rw_block(READ, 1, &bh);
2246                 }
2247
2248
2249                 /* must do syncronous write here */
2250                 wait_on_buffer(bh);
2251                 if (!buffer_uptodate(bh)) {
2252                         /* I/O error */
2253                         rc = -EIO;
2254                         goto out_req;
2255                 }
2256         }
2257
2258 out_req:
2259         ptlrpc_req_finished(request);
2260         RETURN(rc);
2261 }
2262
2263 static int sanosc_brw_write(struct obd_export *exp, struct obdo *oa,
2264                             struct lov_stripe_md *lsm, obd_count page_count,
2265                             struct brw_page *pga)
2266 {
2267         struct ptlrpc_request *request = NULL;
2268         struct ost_body *body;
2269         struct niobuf_remote *nioptr;
2270         struct obd_ioobj *iooptr;
2271         int rc, size[3] = {sizeof(*body)}, mapped = 0;
2272         int swab;
2273         ENTRY;
2274
2275         size[1] = sizeof(struct obd_ioobj);
2276         size[2] = page_count * sizeof(*nioptr);
2277
2278         request = ptlrpc_prep_req(class_exp2cliimp(exp), LUSTRE_OBD_VERSION,
2279                                   OST_SAN_WRITE, 3, size, NULL);
2280         if (!request)
2281                 RETURN(-ENOMEM);
2282
2283         body = lustre_msg_buf(request->rq_reqmsg, 0, sizeof (*body));
2284         iooptr = lustre_msg_buf(request->rq_reqmsg, 1, sizeof (*iooptr));
2285         nioptr = lustre_msg_buf(request->rq_reqmsg, 2,
2286                                 sizeof (*nioptr) * page_count);
2287
2288         memcpy(&body->oa, oa, sizeof(body->oa));
2289
2290         obdo_to_ioobj(oa, iooptr);
2291         iooptr->ioo_bufcnt = page_count;
2292
2293         /* pack request */
2294         for (mapped = 0; mapped < page_count; mapped++, nioptr++) {
2295                 LASSERT(PageLocked(pga[mapped].pg));
2296                 LASSERT(mapped == 0 ||
2297                         pga[mapped].disk_offset > pga[mapped - 1].disk_offset);
2298
2299                 nioptr->offset = pga[mapped].disk_offset;
2300                 nioptr->len    = pga[mapped].count;
2301                 nioptr->flags  = pga[mapped].flag;
2302         }
2303
2304         size[1] = page_count * sizeof(*nioptr);
2305         request->rq_replen = lustre_msg_size(2, size);
2306
2307         rc = ptlrpc_queue_wait(request);
2308         if (rc)
2309                 GOTO(out_req, rc);
2310
2311         swab = lustre_msg_swabbed (request->rq_repmsg);
2312         LASSERT_REPSWAB (request, 1);
2313         nioptr = lustre_msg_buf(request->rq_repmsg, 1, size[1]);
2314         if (!nioptr) {
2315                 CERROR("absent/short niobuf array\n");
2316                 GOTO(out_req, rc = -EPROTO);
2317         }
2318
2319         /* actual write */
2320         for (mapped = 0; mapped < page_count; mapped++, nioptr++) {
2321                 struct page *page = pga[mapped].pg;
2322                 struct buffer_head *bh;
2323                 kdev_t dev;
2324
2325                 if (swab)
2326                         lustre_swab_niobuf_remote (nioptr);
2327
2328                 /* got san device associated */
2329                 LASSERT(exp->exp_obd != NULL);
2330                 dev = exp->exp_obd->u.cli.cl_sandev;
2331
2332                 if (!page->buffers) {
2333                         create_empty_buffers(page, dev, PAGE_SIZE);
2334                 } else {
2335                         /* checking */
2336                         LASSERT(!test_bit(BH_New, &page->buffers->b_state));
2337                         LASSERT(test_bit(BH_Mapped, &page->buffers->b_state));
2338                         LASSERT(page->buffers->b_blocknr ==
2339                                 (unsigned long)nioptr->offset);
2340                 }
2341                 bh = page->buffers;
2342
2343                 LASSERT(bh);
2344
2345                 /* if buffer locked, wait it's io completion */
2346                 if (test_bit(BH_Lock, &bh->b_state))
2347                         wait_on_buffer(bh);
2348
2349                 clear_bit(BH_New, &bh->b_state);
2350                 set_bit(BH_Mapped, &bh->b_state);
2351
2352                 /* override the block nr */
2353                 bh->b_blocknr = (unsigned long)nioptr->offset;
2354
2355                 /* we are about to write it, so set it
2356                  * uptodate/dirty
2357                  * page lock should garentee no race condition here */
2358                 set_bit(BH_Uptodate, &bh->b_state);
2359                 set_bit(BH_Dirty, &bh->b_state);
2360
2361                 ll_rw_block(WRITE, 1, &bh);
2362
2363                 /* must do syncronous write here */
2364                 wait_on_buffer(bh);
2365                 if (!buffer_uptodate(bh) || test_bit(BH_Dirty, &bh->b_state)) {
2366                         /* I/O error */
2367                         rc = -EIO;
2368                         goto out_req;
2369                 }
2370         }
2371
2372 out_req:
2373         ptlrpc_req_finished(request);
2374         RETURN(rc);
2375 }
2376
2377 static int sanosc_brw(int cmd, struct obd_export *exp, struct obdo *oa,
2378                       struct lov_stripe_md *lsm, obd_count page_count,
2379                       struct brw_page *pga, struct obd_trans_info *oti)
2380 {
2381         ENTRY;
2382
2383         while (page_count) {
2384                 obd_count pages_per_brw;
2385                 int rc;
2386
2387                 if (page_count > PTLRPC_MAX_BRW_PAGES)
2388                         pages_per_brw = PTLRPC_MAX_BRW_PAGES;
2389                 else
2390                         pages_per_brw = page_count;
2391
2392                 if (cmd & OBD_BRW_WRITE)
2393                         rc = sanosc_brw_write(exp, oa, lsm, pages_per_brw,pga);
2394                 else
2395                         rc = sanosc_brw_read(exp, oa, lsm, pages_per_brw, pga);
2396
2397                 if (rc != 0)
2398                         RETURN(rc);
2399
2400                 page_count -= pages_per_brw;
2401                 pga += pages_per_brw;
2402         }
2403         RETURN(0);
2404 }
2405 #endif
2406 #endif
2407
2408 static void osc_set_data_with_check(struct lustre_handle *lockh, void *data)
2409 {
2410         struct ldlm_lock *lock = ldlm_handle2lock(lockh);
2411
2412         if (lock == NULL) {
2413                 CERROR("lockh %p, data %p - client evicted?\n", lockh, data);
2414                 return;
2415         }
2416
2417         lock_res_and_lock(lock);
2418 #ifdef __KERNEL__
2419         if (lock->l_ast_data && lock->l_ast_data != data) {
2420                 struct inode *new_inode = data;
2421                 struct inode *old_inode = lock->l_ast_data;
2422                 if (!(old_inode->i_state & I_FREEING))
2423                         LDLM_ERROR(lock, "inconsistent l_ast_data found");
2424                 LASSERTF(old_inode->i_state & I_FREEING,
2425                          "Found existing inode %p/%lu/%u state %lu in lock: "
2426                          "setting data to %p/%lu/%u\n", old_inode,
2427                          old_inode->i_ino, old_inode->i_generation,
2428                          old_inode->i_state,
2429                          new_inode, new_inode->i_ino, new_inode->i_generation);
2430         }
2431 #endif
2432         lock->l_ast_data = data;
2433         unlock_res_and_lock(lock);
2434         LDLM_LOCK_PUT(lock);
2435 }
2436
2437 static int osc_change_cbdata(struct obd_export *exp, struct lov_stripe_md *lsm,
2438                              ldlm_iterator_t replace, void *data)
2439 {
2440         struct ldlm_res_id res_id = { .name = {0} };
2441         struct obd_device *obd = class_exp2obd(exp);
2442
2443         res_id.name[0] = lsm->lsm_object_id;
2444         res_id.name[2] = lsm->lsm_object_gr;
2445         ldlm_change_cbdata(obd->obd_namespace, &res_id, replace, data);
2446         return 0;
2447 }
2448
2449 static int osc_enqueue(struct obd_export *exp, struct lov_stripe_md *lsm,
2450                        __u32 type, ldlm_policy_data_t *policy, __u32 mode,
2451                        int *flags, void *bl_cb, void *cp_cb, void *gl_cb,
2452                        void *data, __u32 lvb_len, void *lvb_swabber,
2453                        struct lustre_handle *lockh)
2454 {
2455         struct obd_device *obd = exp->exp_obd;
2456         struct ldlm_res_id res_id = { .name = {0} };
2457         struct ost_lvb lvb;
2458         struct ldlm_reply *rep;
2459         struct ptlrpc_request *req = NULL;
2460         int rc;
2461         ENTRY;
2462
2463         res_id.name[0] = lsm->lsm_object_id;
2464         res_id.name[2] = lsm->lsm_object_gr;
2465
2466         /* Filesystem lock extents are extended to page boundaries so that
2467          * dealing with the page cache is a little smoother.  */
2468         policy->l_extent.start -= policy->l_extent.start & ~PAGE_MASK;
2469         policy->l_extent.end |= ~PAGE_MASK;
2470
2471         if (lsm->lsm_oinfo->loi_kms_valid == 0)
2472                 goto no_match;
2473
2474         /* Next, search for already existing extent locks that will cover us */
2475         rc = ldlm_lock_match(obd->obd_namespace, 0, &res_id, type, policy, mode,
2476                              lockh);
2477         if (rc == 1) {
2478                 if (ptlrpcs_check_cred(obd->u.cli.cl_import)) {
2479                         /* return immediately if no credential held */
2480                         ldlm_lock_decref(lockh, mode);
2481                         RETURN(-EACCES);
2482                 }
2483
2484                 osc_set_data_with_check(lockh, data);
2485                 if (*flags & LDLM_FL_HAS_INTENT) {
2486                         /* I would like to be able to ASSERT here that rss <=
2487                          * kms, but I can't, for reasons which are explained in
2488                          * lov_enqueue() */
2489                 }
2490                 /* We already have a lock, and it's referenced */
2491                 RETURN(ELDLM_OK);
2492         }
2493
2494         /* If we're trying to read, we also search for an existing PW lock.  The
2495          * VFS and page cache already protect us locally, so lots of readers/
2496          * writers can share a single PW lock.
2497          *
2498          * There are problems with conversion deadlocks, so instead of
2499          * converting a read lock to a write lock, we'll just enqueue a new
2500          * one.
2501          *
2502          * At some point we should cancel the read lock instead of making them
2503          * send us a blocking callback, but there are problems with canceling
2504          * locks out from other users right now, too. */
2505
2506         if (mode == LCK_PR) {
2507                 rc = ldlm_lock_match(obd->obd_namespace, 0, &res_id, type,
2508                                      policy, LCK_PW, lockh);
2509                 if (rc == 1) {
2510                         if (ptlrpcs_check_cred(obd->u.cli.cl_import)) {
2511                                 /* return immediately if no credential held */
2512                                 ldlm_lock_decref(lockh, LCK_PW);
2513                                 RETURN(-EACCES);
2514                         }
2515
2516                         /* FIXME: This is not incredibly elegant, but it might
2517                          * be more elegant than adding another parameter to
2518                          * lock_match.  I want a second opinion. */
2519                         ldlm_lock_addref(lockh, LCK_PR);
2520                         ldlm_lock_decref(lockh, LCK_PW);
2521                         osc_set_data_with_check(lockh, data);
2522                         RETURN(ELDLM_OK);
2523                 }
2524         }
2525         if (mode == LCK_PW) {
2526                 rc = ldlm_lock_match(obd->obd_namespace, 0, &res_id, type,
2527                                      policy, LCK_PR, lockh);
2528                 if (rc == 1) {
2529                         rc = ldlm_cli_convert(lockh, mode, flags);
2530                         if (!rc) {
2531                                 /* Update readers/writers accounting */
2532                                 ldlm_lock_addref(lockh, LCK_PW);
2533                                 ldlm_lock_decref(lockh, LCK_PR);
2534                                 osc_set_data_with_check(lockh, data);
2535                                 RETURN(ELDLM_OK);
2536                         }
2537                         /* If the conversion failed, we need to drop refcount
2538                            on matched lock before we get new one */
2539                         /* XXX Won't it save us some efforts if we cancel PR
2540                            lock here? We are going to take PW lock anyway and it
2541                            will invalidate PR lock */
2542                         ldlm_lock_decref(lockh, LCK_PR);
2543                         if (rc != EDEADLOCK) {
2544                                 RETURN(rc);
2545                         }
2546                 }
2547         }
2548
2549         if (mode == LCK_PW) {
2550                 rc = ldlm_lock_match(obd->obd_namespace, 0, &res_id, type,
2551                                      policy, LCK_PR, lockh);
2552                 if (rc == 1) {
2553                         rc = ldlm_cli_convert(lockh, mode, flags);
2554                         if (!rc) {
2555                                 /* Update readers/writers accounting */
2556                                 ldlm_lock_addref(lockh, LCK_PW);
2557                                 ldlm_lock_decref(lockh, LCK_PR);
2558                                 osc_set_data_with_check(lockh, data);
2559                                 RETURN(ELDLM_OK);
2560                         }
2561                         /* If the conversion failed, we need to drop refcount
2562                            on matched lock before we get new one */
2563                         /* XXX Won't it save us some efforts if we cancel PR
2564                            lock here? We are going to take PW lock anyway and it
2565                            will invalidate PR lock */
2566                         ldlm_lock_decref(lockh, LCK_PR);
2567                         if (rc != EDEADLOCK) {
2568                                 RETURN(rc);
2569                         }
2570                 }
2571         }
2572
2573  no_match:
2574         if (*flags & LDLM_FL_HAS_INTENT) {
2575                 int size[2] = {0, sizeof(struct ldlm_request)};
2576
2577                 req = ptlrpc_prep_req(class_exp2cliimp(exp), LUSTRE_DLM_VERSION,
2578                                       LDLM_ENQUEUE, 2, size, NULL);
2579                 if (req == NULL)
2580                         RETURN(-ENOMEM);
2581
2582                 size[0] = sizeof(*rep);
2583                 size[1] = sizeof(lvb);
2584                 req->rq_replen = lustre_msg_size(2, size);
2585         }
2586         rc = ldlm_cli_enqueue(exp, req, obd->obd_namespace, res_id, type,
2587                               policy, mode, flags, bl_cb, cp_cb, gl_cb, data,
2588                               &lvb, sizeof(lvb), lustre_swab_ost_lvb, lockh);
2589         if (req != NULL) {
2590                 if (rc == ELDLM_LOCK_ABORTED) {
2591                         /* swabbed by ldlm_cli_enqueue() */
2592                         LASSERT_REPSWABBED(req, 0);
2593                         rep = lustre_msg_buf(req->rq_repmsg, 0, sizeof(*rep));
2594                         LASSERT(rep != NULL);
2595                         if (rep->lock_policy_res1)
2596                                 rc = rep->lock_policy_res1;
2597                 }
2598                 ptlrpc_req_finished(req);
2599         }
2600
2601         if ((*flags & LDLM_FL_HAS_INTENT && rc == ELDLM_LOCK_ABORTED) || !rc) {
2602                 CDEBUG(D_INODE, "received kms == "LPU64", blocks == "LPU64"\n",
2603                        lvb.lvb_size, lvb.lvb_blocks);
2604                 lsm->lsm_oinfo->loi_rss = lvb.lvb_size;
2605                 lsm->lsm_oinfo->loi_blocks = lvb.lvb_blocks;
2606         }
2607
2608         RETURN(rc);
2609 }
2610
2611 static int osc_match(struct obd_export *exp, struct lov_stripe_md *lsm,
2612                      __u32 type, ldlm_policy_data_t *policy, __u32 mode,
2613                      int *flags, void *data, struct lustre_handle *lockh)
2614 {
2615         struct ldlm_res_id res_id = { .name = {0} };
2616         struct obd_device *obd = exp->exp_obd;
2617         int rc;
2618         ENTRY;
2619
2620         res_id.name[0] = lsm->lsm_object_id;
2621         res_id.name[2] = lsm->lsm_object_gr;
2622
2623         OBD_FAIL_RETURN(OBD_FAIL_OSC_MATCH, -EIO);
2624
2625         /* Filesystem lock extents are extended to page boundaries so that
2626          * dealing with the page cache is a little smoother */
2627         policy->l_extent.start -= policy->l_extent.start & ~PAGE_MASK;
2628         policy->l_extent.end |= ~PAGE_MASK;
2629
2630         /* Next, search for already existing extent locks that will cover us */
2631         rc = ldlm_lock_match(obd->obd_namespace, *flags, &res_id, type,
2632                              policy, mode, lockh);
2633         if (rc) {
2634                // if (!(*flags & LDLM_FL_TEST_LOCK))
2635                         osc_set_data_with_check(lockh, data);
2636                 RETURN(rc);
2637         }
2638         /* If we're trying to read, we also search for an existing PW lock.  The
2639          * VFS and page cache already protect us locally, so lots of readers/
2640          * writers can share a single PW lock. */
2641         if (mode == LCK_PR) {
2642                 rc = ldlm_lock_match(obd->obd_namespace, *flags, &res_id, type,
2643                                      policy, LCK_PW, lockh);
2644                 if (rc == 1 && !(*flags & LDLM_FL_TEST_LOCK)) {
2645                         /* FIXME: This is not incredibly elegant, but it might
2646                          * be more elegant than adding another parameter to
2647                          * lock_match.  I want a second opinion. */
2648                         osc_set_data_with_check(lockh, data);
2649                         ldlm_lock_addref(lockh, LCK_PR);
2650                         ldlm_lock_decref(lockh, LCK_PW);
2651                 }
2652         }
2653         RETURN(rc);
2654 }
2655
2656 static int osc_cancel(struct obd_export *exp, struct lov_stripe_md *md,
2657                       __u32 mode, struct lustre_handle *lockh)
2658 {
2659         ENTRY;
2660
2661         if (mode == LCK_GROUP)
2662                 ldlm_lock_decref_and_cancel(lockh, mode);
2663         else
2664                 ldlm_lock_decref(lockh, mode);
2665
2666         RETURN(0);
2667 }
2668
2669 static int osc_cancel_unused(struct obd_export *exp,
2670                              struct lov_stripe_md *lsm,
2671                              int flags, void *opaque)
2672 {
2673         struct obd_device *obd = class_exp2obd(exp);
2674         struct ldlm_res_id res_id = { .name = {0} }, *resp = NULL;
2675
2676         if (lsm != NULL) {
2677                 res_id.name[0] = lsm->lsm_object_id;
2678                 res_id.name[2] = lsm->lsm_object_gr;
2679                 resp = &res_id;
2680         }
2681
2682         return ldlm_cli_cancel_unused(obd->obd_namespace, resp, flags, opaque);
2683 }
2684
2685 static int osc_statfs(struct obd_device *obd, struct obd_statfs *osfs,
2686                       unsigned long max_age)
2687 {
2688         struct obd_statfs *msfs;
2689         struct ptlrpc_request *request;
2690         int rc, size = sizeof(*osfs);
2691         ENTRY;
2692
2693         /* We could possibly pass max_age in the request (as an absolute
2694          * timestamp or a "seconds.usec ago") so the target can avoid doing
2695          * extra calls into the filesystem if that isn't necessary (e.g.
2696          * during mount that would help a bit).  Having relative timestamps
2697          * is not so great if request processing is slow, while absolute
2698          * timestamps are not ideal because they need time synchronization. */
2699         request = ptlrpc_prep_req(obd->u.cli.cl_import, LUSTRE_OBD_VERSION,
2700                                   OST_STATFS, 0, NULL, NULL);
2701         if (!request)
2702                 RETURN(-ENOMEM);
2703
2704         request->rq_replen = lustre_msg_size(1, &size);
2705         request->rq_request_portal = OST_CREATE_PORTAL; //XXX FIXME bug 249
2706
2707         rc = ptlrpc_queue_wait(request);
2708         if (rc)
2709                 GOTO(out, rc);
2710
2711         msfs = lustre_swab_repbuf(request, 0, sizeof(*msfs),
2712                                   lustre_swab_obd_statfs);
2713         if (msfs == NULL) {
2714                 CERROR("Can't unpack obd_statfs\n");
2715                 GOTO(out, rc = -EPROTO);
2716         }
2717
2718         memcpy(osfs, msfs, sizeof(*osfs));
2719
2720         EXIT;
2721  out:
2722         ptlrpc_req_finished(request);
2723         return rc;
2724 }
2725
2726 /* Retrieve object striping information.
2727  *
2728  * @lmmu is a pointer to an in-core struct with lmm_ost_count indicating
2729  * the maximum number of OST indices which will fit in the user buffer.
2730  * lmm_magic must be LOV_MAGIC (we only use 1 slot here).
2731  */
2732 static int osc_getstripe(struct lov_stripe_md *lsm, struct lov_user_md *lump)
2733 {
2734         struct lov_user_md lum, *lumk;
2735         int rc, lum_size;
2736         ENTRY;
2737
2738         if (!lsm)
2739                 RETURN(-ENODATA);
2740
2741         rc = copy_from_user(&lum, lump, sizeof(lum));
2742         if (rc)
2743                 RETURN(-EFAULT);
2744
2745         if (lum.lmm_magic != LOV_USER_MAGIC)
2746                 RETURN(-EINVAL);
2747
2748         if (lum.lmm_stripe_count > 0) {
2749                 lum_size = sizeof(lum) + sizeof(lum.lmm_objects[0]);
2750                 OBD_ALLOC(lumk, lum_size);
2751                 if (!lumk)
2752                         RETURN(-ENOMEM);
2753
2754                 lumk->lmm_objects[0].l_object_id = lsm->lsm_object_id;
2755                 lumk->lmm_objects[0].l_object_gr = lsm->lsm_object_gr;
2756         } else {
2757                 lum_size = sizeof(lum);
2758                 lumk = &lum;
2759         }
2760
2761         lumk->lmm_object_id = lsm->lsm_object_id;
2762         lumk->lmm_object_gr = lsm->lsm_object_gr;
2763         lumk->lmm_stripe_count = 1;
2764
2765         if (copy_to_user(lump, lumk, lum_size))
2766                 rc = -EFAULT;
2767
2768         if (lumk != &lum)
2769                 OBD_FREE(lumk, lum_size);
2770
2771         RETURN(rc);
2772 }
2773
2774 static int osc_iocontrol(unsigned int cmd, struct obd_export *exp, int len,
2775                          void *karg, void *uarg)
2776 {
2777         struct obd_device *obd = exp->exp_obd;
2778         struct obd_ioctl_data *data = karg;
2779         int err = 0;
2780         ENTRY;
2781
2782 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0))
2783         MOD_INC_USE_COUNT;
2784 #else
2785         if (!try_module_get(THIS_MODULE)) {
2786                 CERROR("Can't get module. Is it alive?");
2787                 return -EINVAL;
2788         }
2789 #endif
2790         switch (cmd) {
2791         case OBD_IOC_LOV_GET_CONFIG: {
2792                 char *buf;
2793                 struct lov_desc *desc;
2794                 struct obd_uuid uuid;
2795
2796                 buf = NULL;
2797                 len = 0;
2798                 if (obd_ioctl_getdata(&buf, &len, (void *)uarg))
2799                         GOTO(out, err = -EINVAL);
2800
2801                 data = (struct obd_ioctl_data *)buf;
2802
2803                 if (sizeof(*desc) > data->ioc_inllen1) {
2804                         OBD_FREE(buf, len);
2805                         GOTO(out, err = -EINVAL);
2806                 }
2807
2808                 if (data->ioc_inllen2 < sizeof(uuid)) {
2809                         OBD_FREE(buf, len);
2810                         GOTO(out, err = -EINVAL);
2811                 }
2812
2813                 if (data->ioc_inllen3 < sizeof(__u32)) {
2814                         OBD_FREE(buf, len);
2815                         GOTO(out, err = -EINVAL);
2816                 }
2817
2818                 desc = (struct lov_desc *)data->ioc_inlbuf1;
2819                 desc->ld_tgt_count = 1;
2820                 desc->ld_active_tgt_count = 1;
2821                 desc->ld_default_stripe_count = 1;
2822                 desc->ld_default_stripe_size = 0;
2823                 desc->ld_default_stripe_offset = 0;
2824                 desc->ld_pattern = 0;
2825                 memcpy(&desc->ld_uuid, &obd->obd_uuid, sizeof(uuid));
2826                 memcpy(data->ioc_inlbuf2, &obd->obd_uuid, sizeof(uuid));
2827                 *((__u32 *)data->ioc_inlbuf3) = 1;
2828
2829                 err = copy_to_user((void *)uarg, buf, len);
2830                 if (err)
2831                         err = -EFAULT;
2832                 obd_ioctl_freedata(buf, len);
2833                 GOTO(out, err);
2834         }
2835         case LL_IOC_LOV_SETSTRIPE:
2836                 err = obd_alloc_memmd(exp, karg);
2837                 if (err > 0)
2838                         err = 0;
2839                 GOTO(out, err);
2840         case LL_IOC_LOV_GETSTRIPE:
2841                 err = osc_getstripe(karg, uarg);
2842                 GOTO(out, err);
2843         case OBD_IOC_CLIENT_RECOVER:
2844                 err = ptlrpc_recover_import(obd->u.cli.cl_import,
2845                                             data->ioc_inlbuf1);
2846                 if (err > 0)
2847                         err = 0;
2848                 GOTO(out, err);
2849         case IOC_OSC_SET_ACTIVE:
2850                 err = ptlrpc_set_import_active(obd->u.cli.cl_import,
2851                                                data->ioc_offset);
2852                 GOTO(out, err);
2853         case IOC_OSC_CTL_RECOVERY:
2854                 err = ptlrpc_import_control_recovery(obd->u.cli.cl_import,
2855                                                      data->ioc_offset);
2856                 GOTO(out, err);
2857         default:
2858                 CDEBUG(D_INODE, "unrecognised ioctl %#x by %s\n", cmd, current->comm);
2859                 GOTO(out, err = -ENOTTY);
2860         }
2861 out:
2862 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0))
2863         MOD_DEC_USE_COUNT;
2864 #else
2865         module_put(THIS_MODULE);
2866 #endif
2867         return err;
2868 }
2869
2870 static int osc_get_info(struct obd_export *exp, __u32 keylen,
2871                         void *key, __u32 *vallen, void *val)
2872 {
2873         ENTRY;
2874         if (!vallen || !val)
2875                 RETURN(-EFAULT);
2876
2877         if (keylen > strlen("lock_to_stripe") &&
2878             strcmp(key, "lock_to_stripe") == 0) {
2879                 __u32 *stripe = val;
2880                 *vallen = sizeof(*stripe);
2881                 *stripe = 0;
2882                 RETURN(0);
2883         } else if (keylen >= strlen("last_id") && strcmp(key, "last_id") == 0) {
2884                 struct ptlrpc_request *req;
2885                 obd_id *reply;
2886                 char *bufs[1] = {key};
2887                 int rc;
2888                 req = ptlrpc_prep_req(class_exp2cliimp(exp), LUSTRE_OBD_VERSION,
2889                                       OST_GET_INFO, 1, (int *)&keylen, bufs);
2890                 if (req == NULL)
2891                         RETURN(-ENOMEM);
2892
2893                 req->rq_replen = lustre_msg_size(1, (int *)vallen);
2894                 rc = ptlrpc_queue_wait(req);
2895                 if (rc)
2896                         GOTO(out, rc);
2897
2898                 reply = lustre_swab_repbuf(req, 0, sizeof(*reply),
2899                                            lustre_swab_ost_last_id);
2900                 if (reply == NULL) {
2901                         CERROR("Can't unpack OST last ID\n");
2902                         GOTO(out, rc = -EPROTO);
2903                 }
2904                 *((obd_id *)val) = *reply;
2905         out:
2906                 ptlrpc_req_finished(req);
2907                 RETURN(rc);
2908         }
2909         RETURN(-EPROTO);
2910 }
2911
2912 static int osc_set_info(struct obd_export *exp, obd_count keylen,
2913                         void *key, obd_count vallen, void *val)
2914 {
2915         struct obd_device  *obd = exp->exp_obd;
2916         struct obd_import *imp = class_exp2cliimp(exp);
2917         struct llog_ctxt *ctxt;
2918         int rc = 0;
2919         ENTRY;
2920
2921         if (keylen == strlen("unlinked") &&
2922             memcmp(key, "unlinked", keylen) == 0) {
2923                 struct osc_creator *oscc = &obd->u.cli.cl_oscc;
2924                 spin_lock(&oscc->oscc_lock);
2925                 oscc->oscc_flags &= ~OSCC_FLAG_NOSPC;
2926                 spin_unlock(&oscc->oscc_lock);
2927                 RETURN(0);
2928         }
2929         if (keylen == strlen("unrecovery") &&
2930             memcmp(key, "unrecovery", keylen) == 0) {
2931                 struct osc_creator *oscc = &obd->u.cli.cl_oscc;
2932                 spin_lock(&oscc->oscc_lock);
2933                 oscc->oscc_flags &= ~OSCC_FLAG_RECOVERING;
2934                 spin_unlock(&oscc->oscc_lock);
2935                 RETURN(0);
2936         }
2937         if (keylen == strlen("initial_recov") &&
2938             memcmp(key, "initial_recov", strlen("initial_recov")) == 0) {
2939                 struct obd_import *imp = exp->exp_obd->u.cli.cl_import;
2940                 if (vallen != sizeof(int))
2941                         RETURN(-EINVAL);
2942                 imp->imp_initial_recov = *(int *)val;
2943                 CDEBUG(D_HA, "%s: set imp_no_init_recov = %d\n",
2944                        exp->exp_obd->obd_name,
2945                        imp->imp_initial_recov);
2946                 RETURN(0);
2947         }
2948
2949         if (keylen == strlen("async") &&
2950             memcmp(key, "async", keylen) == 0) {
2951                 struct client_obd *cl = &obd->u.cli;
2952                 if (vallen != sizeof(int))
2953                         RETURN(-EINVAL);
2954                 cl->cl_async = *(int *)val;
2955                 CDEBUG(D_HA, "%s: set async = %d\n",
2956                        obd->obd_name, cl->cl_async);
2957                 RETURN(0);
2958         }
2959
2960         if (keylen == strlen("sec") &&
2961             memcmp(key, "sec", keylen) == 0) {
2962                 struct client_obd *cli = &exp->exp_obd->u.cli;
2963
2964                 cli->cl_sec_flavor = ptlrpcs_name2flavor(val);
2965                 if (cli->cl_sec_flavor == PTLRPCS_FLVR_INVALID) {
2966                         CERROR("unrecognized security flavor %s\n", (char*) val);
2967                         RETURN(-EINVAL);
2968                 }
2969
2970                 RETURN(0);
2971         }
2972
2973         if (keylen == strlen("sec_flags") &&
2974             memcmp(key, "sec_flags", keylen) == 0) {
2975                 struct client_obd *cli = &exp->exp_obd->u.cli;
2976
2977                 cli->cl_sec_flags = *((unsigned long *) val);
2978                 RETURN(0);
2979         }
2980
2981         if (keylen == strlen("flush_cred") &&
2982             memcmp(key, "flush_cred", keylen) == 0) {
2983                 struct client_obd *cli = &exp->exp_obd->u.cli;
2984
2985                 if (cli->cl_import)
2986                         ptlrpcs_import_flush_current_creds(cli->cl_import);
2987                 RETURN(0);
2988         }
2989         if (keylen == strlen("crypto_cb") &&
2990             memcmp(key, "crypto_cb", keylen) == 0) {
2991                 LASSERT(vallen == sizeof(crypt_cb_t));
2992                 osc_crypt_cb = (crypt_cb_t)val;
2993                 RETURN(0);
2994         }
2995
2996         if (keylen < strlen("mds_conn") ||
2997             memcmp(key, "mds_conn", keylen) != 0)
2998                 RETURN(-EINVAL);
2999
3000         ctxt = llog_get_context(&exp->exp_obd->obd_llogs,
3001                                 LLOG_UNLINK_ORIG_CTXT);
3002         if (ctxt) {
3003                 if (rc == 0)
3004                         rc = llog_initiator_connect(ctxt);
3005                 else
3006                         CERROR("cannot establish the connect for "
3007                                "ctxt %p: %d\n", ctxt, rc);
3008         }
3009
3010         imp->imp_server_timeout = 1;
3011         CDEBUG(D_HA, "pinging OST %s\n", imp->imp_target_uuid.uuid);
3012         imp->imp_pingable = 1;
3013
3014         RETURN(rc);
3015 }
3016
3017
3018 static struct llog_operations osc_size_repl_logops = {
3019         lop_cancel: llog_obd_repl_cancel
3020 };
3021
3022 static struct llog_operations osc_unlink_orig_logops;
3023
3024 static int osc_llog_init(struct obd_device *obd, struct obd_llogs *llogs,
3025                          struct obd_device *tgt, int count,
3026                          struct llog_catid *catid)
3027 {
3028         int rc;
3029         ENTRY;
3030
3031         osc_unlink_orig_logops = llog_lvfs_ops;
3032         osc_unlink_orig_logops.lop_setup = llog_obd_origin_setup;
3033         osc_unlink_orig_logops.lop_cleanup = llog_catalog_cleanup;
3034         osc_unlink_orig_logops.lop_add = llog_catalog_add;
3035         osc_unlink_orig_logops.lop_connect = llog_origin_connect;
3036
3037         rc = obd_llog_setup(obd, llogs, LLOG_UNLINK_ORIG_CTXT, tgt, count,
3038                             &catid->lci_logid, &osc_unlink_orig_logops);
3039         if (rc)
3040                 RETURN(rc);
3041
3042         rc = obd_llog_setup(obd, llogs, LLOG_SIZE_REPL_CTXT, tgt, count, NULL,
3043                             &osc_size_repl_logops);
3044         RETURN(rc);
3045 }
3046
3047 static int osc_llog_finish(struct obd_device *obd,
3048                            struct obd_llogs *llogs, int count)
3049 {
3050         int rc;
3051         ENTRY;
3052
3053         rc = obd_llog_cleanup(llog_get_context(llogs, LLOG_UNLINK_ORIG_CTXT));
3054         if (rc)
3055                 RETURN(rc);
3056
3057         rc = obd_llog_cleanup(llog_get_context(llogs, LLOG_SIZE_REPL_CTXT));
3058         RETURN(rc);
3059 }
3060
3061 static int osc_connect(struct lustre_handle *exph,
3062                        struct obd_device *obd, struct obd_uuid *cluuid,
3063                        struct obd_connect_data *data,
3064                        unsigned long connect_flags)
3065 {
3066         int rc;
3067         ENTRY;
3068         rc = client_connect_import(exph, obd, cluuid, data, connect_flags);
3069         RETURN(rc);
3070 }
3071
3072 static int osc_disconnect(struct obd_export *exp, unsigned long flags)
3073 {
3074         struct obd_device *obd = class_exp2obd(exp);
3075         struct llog_ctxt *ctxt;
3076         int rc;
3077         ENTRY;
3078
3079         ctxt = llog_get_context(&obd->obd_llogs, LLOG_SIZE_REPL_CTXT);
3080         if (obd->u.cli.cl_conn_count == 1)
3081                 /* flush any remaining cancel messages out to the target */
3082                 llog_sync(ctxt, exp);
3083
3084         rc = client_disconnect_export(exp, flags);
3085         RETURN(rc);
3086 }
3087
3088 static int osc_import_event(struct obd_device *obd,
3089                             struct obd_import *imp,
3090                             enum obd_import_event event)
3091 {
3092         struct client_obd *cli;
3093         int rc = 0;
3094
3095         LASSERT(imp->imp_obd == obd);
3096
3097         switch (event) {
3098         case IMP_EVENT_DISCON: {
3099                 /* Only do this on the MDS OSC's */
3100                 if (imp->imp_server_timeout) {
3101                         struct osc_creator *oscc = &obd->u.cli.cl_oscc;
3102
3103                         spin_lock(&oscc->oscc_lock);
3104                         oscc->oscc_flags |= OSCC_FLAG_RECOVERING;
3105                         spin_unlock(&oscc->oscc_lock);
3106                 }
3107                 break;
3108         }
3109         case IMP_EVENT_INACTIVE: {
3110                 if (obd->obd_observer)
3111                         rc = obd_notify(obd->obd_observer, obd, 0, 0);
3112                 break;
3113         }
3114         case IMP_EVENT_INVALIDATE: {
3115                 struct ldlm_namespace *ns = obd->obd_namespace;
3116
3117                 /* Reset grants */
3118                 cli = &obd->u.cli;
3119                 spin_lock(&cli->cl_loi_list_lock);
3120                 cli->cl_avail_grant = 0;
3121                 cli->cl_lost_grant = 0;
3122                 /* all pages go to failing rpcs due to the invalid import */
3123                 osc_check_rpcs(cli);
3124                 spin_unlock(&cli->cl_loi_list_lock);
3125
3126                 ldlm_namespace_cleanup(ns, LDLM_FL_LOCAL_ONLY);
3127
3128                 break;
3129         }
3130         case IMP_EVENT_ACTIVE: {
3131                 /* Only do this on the MDS OSC's */
3132                 if (imp->imp_server_timeout) {
3133                         struct osc_creator *oscc = &obd->u.cli.cl_oscc;
3134
3135                         spin_lock(&oscc->oscc_lock);
3136                         oscc->oscc_flags &= ~OSCC_FLAG_NOSPC;
3137                         spin_unlock(&oscc->oscc_lock);
3138                 }
3139
3140                 if (obd->obd_observer)
3141                         rc = obd_notify(obd->obd_observer, obd, 1, 0);
3142                 break;
3143         }
3144         default:
3145                 CERROR("Unknown import event %d\n", event);
3146                 LBUG();
3147         }
3148         RETURN(rc);
3149 }
3150
3151 static int osc_attach(struct obd_device *dev, obd_count len, void *data)
3152 {
3153         struct lprocfs_static_vars lvars;
3154         int rc;
3155         ENTRY;
3156
3157         lprocfs_init_vars(osc,&lvars);
3158         rc = lprocfs_obd_attach(dev, lvars.obd_vars);
3159         if (rc < 0)
3160                 RETURN(rc);
3161
3162         rc = lproc_osc_attach_seqstat(dev);
3163         if (rc < 0) {
3164                 lprocfs_obd_detach(dev);
3165                 RETURN(rc);
3166         }
3167
3168         ptlrpc_lprocfs_register_obd(dev);
3169         RETURN(0);
3170 }
3171
3172 static int osc_detach(struct obd_device *dev)
3173 {
3174         ptlrpc_lprocfs_unregister_obd(dev);
3175         return lprocfs_obd_detach(dev);
3176 }
3177
3178 static int osc_setup(struct obd_device *obd, obd_count len, void *buf)
3179 {
3180         int rc;
3181         ENTRY;
3182         rc = ptlrpcd_addref();
3183         if (rc)
3184                 RETURN(rc);
3185
3186         rc = client_obd_setup(obd, len, buf);
3187         if (rc)
3188                 ptlrpcd_decref();
3189         else
3190                 oscc_init(obd);
3191
3192         RETURN(rc);
3193 }
3194
3195 static int osc_cleanup(struct obd_device *obd, int flags)
3196 {
3197         struct osc_creator *oscc = &obd->u.cli.cl_oscc;
3198         int rc;
3199
3200         rc = ldlm_cli_cancel_unused(obd->obd_namespace, NULL,
3201                                     LDLM_FL_CONFIG_CHANGE, NULL);
3202         if (rc)
3203                 RETURN(rc);
3204
3205         spin_lock(&oscc->oscc_lock);
3206         oscc->oscc_flags &= ~OSCC_FLAG_RECOVERING;
3207         oscc->oscc_flags |= OSCC_FLAG_EXITING;
3208         spin_unlock(&oscc->oscc_lock);
3209
3210         rc = client_obd_cleanup(obd, flags);
3211         ptlrpcd_decref();
3212         RETURN(rc);
3213 }
3214
3215 struct obd_ops osc_obd_ops = {
3216         .o_owner                = THIS_MODULE,
3217         .o_attach               = osc_attach,
3218         .o_detach               = osc_detach,
3219         .o_setup                = osc_setup,
3220         .o_cleanup              = osc_cleanup,
3221         .o_add_conn             = client_import_add_conn,
3222         .o_del_conn             = client_import_del_conn,
3223         .o_connect              = osc_connect,
3224         .o_disconnect           = osc_disconnect,
3225         .o_statfs               = osc_statfs,
3226         .o_packmd               = osc_packmd,
3227         .o_unpackmd             = osc_unpackmd,
3228         .o_create               = osc_create,
3229         .o_destroy              = osc_destroy,
3230         .o_getattr              = osc_getattr,
3231         .o_getattr_async        = osc_getattr_async,
3232         .o_setattr              = osc_setattr,
3233         .o_brw                  = osc_brw,
3234         .o_brw_async            = osc_brw_async,
3235         .o_prep_async_page      = osc_prep_async_page,
3236         .o_queue_async_io       = osc_queue_async_io,
3237         .o_set_async_flags      = osc_set_async_flags,
3238         .o_queue_group_io       = osc_queue_group_io,
3239         .o_trigger_group_io     = osc_trigger_group_io,
3240         .o_teardown_async_page  = osc_teardown_async_page,
3241         .o_punch                = osc_punch,
3242         .o_sync                 = osc_sync,
3243         .o_enqueue              = osc_enqueue,
3244         .o_match                = osc_match,
3245         .o_change_cbdata        = osc_change_cbdata,
3246         .o_cancel               = osc_cancel,
3247         .o_cancel_unused        = osc_cancel_unused,
3248         .o_iocontrol            = osc_iocontrol,
3249         .o_get_info             = osc_get_info,
3250         .o_set_info             = osc_set_info,
3251         .o_import_event         = osc_import_event,
3252         .o_llog_init            = osc_llog_init,
3253         .o_llog_finish          = osc_llog_finish,
3254 };
3255
3256 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0))
3257 struct obd_ops sanosc_obd_ops = {
3258         .o_owner                = THIS_MODULE,
3259         .o_attach               = osc_attach,
3260         .o_detach               = osc_detach,
3261         .o_cleanup              = client_obd_cleanup,
3262         .o_add_conn             = client_import_add_conn,
3263         .o_del_conn             = client_import_del_conn,
3264         .o_connect              = osc_connect,
3265         .o_disconnect           = client_disconnect_export,
3266         .o_statfs               = osc_statfs,
3267         .o_packmd               = osc_packmd,
3268         .o_unpackmd             = osc_unpackmd,
3269         .o_create               = osc_real_create,
3270         .o_destroy              = osc_destroy,
3271         .o_getattr              = osc_getattr,
3272         .o_getattr_async        = osc_getattr_async,
3273         .o_setattr              = osc_setattr,
3274         .o_setup                = client_sanobd_setup,
3275         .o_brw                  = sanosc_brw,
3276         .o_punch                = osc_punch,
3277         .o_sync                 = osc_sync,
3278         .o_enqueue              = osc_enqueue,
3279         .o_match                = osc_match,
3280         .o_change_cbdata        = osc_change_cbdata,
3281         .o_cancel               = osc_cancel,
3282         .o_cancel_unused        = osc_cancel_unused,
3283         .o_iocontrol            = osc_iocontrol,
3284         .o_import_event         = osc_import_event,
3285         .o_llog_init            = osc_llog_init,
3286         .o_llog_finish          = osc_llog_finish,
3287 };
3288 #endif
3289
3290 int __init osc_init(void)
3291 {
3292         struct lprocfs_static_vars lvars;
3293 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0))
3294         struct lprocfs_static_vars sanlvars;
3295 #endif
3296         int rc;
3297         ENTRY;
3298
3299         lprocfs_init_vars(osc, &lvars);
3300 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0))
3301         lprocfs_init_vars(osc, &sanlvars);
3302 #endif
3303
3304         rc = class_register_type(&osc_obd_ops, NULL, lvars.module_vars,
3305                                  OBD_OSC_DEVICENAME);
3306         if (rc)
3307                 RETURN(rc);
3308
3309 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0))
3310         rc = class_register_type(&sanosc_obd_ops, NULL, sanlvars.module_vars,
3311                                  OBD_SANOSC_DEVICENAME);
3312         if (rc)
3313                 class_unregister_type(OBD_OSC_DEVICENAME);
3314 #endif
3315
3316         RETURN(rc);
3317 }
3318
3319 #ifdef __KERNEL__
3320 static void /*__exit*/ osc_exit(void)
3321 {
3322 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0))
3323         class_unregister_type(OBD_SANOSC_DEVICENAME);
3324 #endif
3325         class_unregister_type(OBD_OSC_DEVICENAME);
3326 }
3327
3328 MODULE_AUTHOR("Cluster File Systems, Inc. <info@clusterfs.com>");
3329 MODULE_DESCRIPTION("Lustre Object Storage Client (OSC)");
3330 MODULE_LICENSE("GPL");
3331
3332 module_init(osc_init);
3333 module_exit(osc_exit);
3334 #endif