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