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