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