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