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