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