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