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