Whamcloud - gitweb
Land b_hd_capa onto HEAD (20050809_1942)
[fs/lustre-release.git] / lustre / llite / rw.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  * Lustre Lite I/O page cache routines shared by different kernel revs
5  *
6  *  Copyright (c) 2001-2003 Cluster File Systems, Inc.
7  *
8  *   This file is part of Lustre, http://www.lustre.org.
9  *
10  *   Lustre is free software; you can redistribute it and/or
11  *   modify it under the terms of version 2 of the GNU General Public
12  *   License as published by the Free Software Foundation.
13  *
14  *   Lustre is distributed in the hope that it will be useful,
15  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
16  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  *   GNU General Public License for more details.
18  *
19  *   You should have received a copy of the GNU General Public License
20  *   along with Lustre; if not, write to the Free Software
21  *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22  */
23
24 #include <linux/config.h>
25 #include <linux/kernel.h>
26 #include <linux/mm.h>
27 #include <linux/string.h>
28 #include <linux/stat.h>
29 #include <linux/errno.h>
30 #include <linux/smp_lock.h>
31 #include <linux/unistd.h>
32 #include <linux/version.h>
33 #include <asm/system.h>
34 #include <asm/uaccess.h>
35
36 #include <linux/fs.h>
37 #include <linux/stat.h>
38 #include <asm/uaccess.h>
39 #include <asm/segment.h>
40 #include <linux/mm.h>
41 #include <linux/pagemap.h>
42 #include <linux/smp_lock.h>
43
44 #define DEBUG_SUBSYSTEM S_LLITE
45
46 #include <linux/lustre_mds.h>
47 #include <linux/lustre_lite.h>
48 #include "llite_internal.h"
49 #include <linux/lustre_compat25.h>
50
51 #ifndef list_for_each_prev_safe
52 #define list_for_each_prev_safe(pos, n, head) \
53         for (pos = (head)->prev, n = pos->prev; pos != (head); \
54                 pos = n, n = pos->prev )
55 #endif
56
57 /* SYNCHRONOUS I/O to object storage for an inode */
58 static int ll_brw(int cmd, struct inode *inode, struct obdo *oa,
59                   struct page *page, int flags)
60 {
61         struct ll_inode_info *lli = ll_i2info(inode);
62         struct lov_stripe_md *lsm = lli->lli_smd;
63         struct timeval start;
64         struct brw_page pg;
65         int rc;
66         ENTRY;
67
68         do_gettimeofday(&start);
69
70         pg.pg = page;
71         pg.disk_offset = pg.page_offset = ((obd_off)page->index) << PAGE_SHIFT;
72
73         if (cmd == OBD_BRW_WRITE &&
74             (pg.disk_offset + PAGE_SIZE > inode->i_size))
75                 pg.count = inode->i_size % PAGE_SIZE;
76         else
77                 pg.count = PAGE_SIZE;
78
79         CDEBUG(D_PAGE, "%s %d bytes ino %lu at "LPU64"/"LPX64"\n",
80                cmd & OBD_BRW_WRITE ? "write" : "read", pg.count, inode->i_ino,
81                pg.disk_offset, pg.disk_offset);
82         if (pg.count == 0) {
83                 CERROR("ZERO COUNT: ino %lu: size %p:%Lu(%p:%Lu) idx %lu off "
84                        LPU64"\n", inode->i_ino, inode, inode->i_size,
85                        page->mapping->host, page->mapping->host->i_size,
86                        page->index, pg.disk_offset);
87         }
88
89         pg.flag = flags;
90
91         if (cmd == OBD_BRW_WRITE)
92                 lprocfs_counter_add(ll_i2sbi(inode)->ll_stats,
93                                     LPROC_LL_BRW_WRITE, pg.count);
94         else
95                 lprocfs_counter_add(ll_i2sbi(inode)->ll_stats,
96                                     LPROC_LL_BRW_READ, pg.count);
97         rc = obd_brw(cmd, ll_i2dtexp(inode), oa, lsm, 1, &pg, NULL);
98         if (rc == 0)
99                 obdo_to_inode(inode, oa, OBD_MD_FLBLOCKS);
100         else if (rc != -EIO)
101                 CERROR("error from obd_brw: rc = %d\n", rc);
102         ll_stime_record(ll_i2sbi(inode), &start,
103                         &ll_i2sbi(inode)->ll_brw_stime);
104         RETURN(rc);
105 }
106
107 __u64 lov_merge_size(struct lov_stripe_md *lsm, int kms);
108
109 /*
110  * this isn't where truncate starts.   roughly:
111  * sys_truncate->ll_setattr_raw->vmtruncate->ll_truncate
112  * we grab the lock back in setattr_raw to avoid races.
113  *
114  * must be called with lli_size_sem held.
115  */
116 void ll_truncate(struct inode *inode)
117 {
118         struct lov_stripe_md *lsm = ll_i2info(inode)->lli_smd;
119         struct ll_inode_info *lli = ll_i2info(inode);
120         struct obdo *oa = NULL;
121         int rc;
122         ENTRY;
123
124         CDEBUG(D_VFSTRACE, "VFS Op:inode=%lu/%u(%p) to %llu\n", inode->i_ino,
125                inode->i_generation, inode, inode->i_size);
126
127         if (lli->lli_size_pid != current->pid) {
128                 EXIT;
129                 return;
130         }
131
132         if (!lsm) {
133                 CDEBUG(D_INODE, "truncate on inode %lu with no objects\n",
134                        inode->i_ino);
135                 GOTO(out_unlock, 0);
136         }
137
138         LASSERT(atomic_read(&lli->lli_size_sem.count) <= 0);
139         
140         if (lov_merge_size(lsm, 0) == inode->i_size) {
141                 CDEBUG(D_VFSTRACE, "skipping punch for "LPX64" (size = %llu)\n",
142                        lsm->lsm_object_id, inode->i_size);
143                 GOTO(out_unlock, 0);
144         }
145         
146         CDEBUG(D_INFO, "calling punch for "LPX64" (new size %llu)\n",
147                lsm->lsm_object_id, inode->i_size);
148                 
149         oa = obdo_alloc();
150         if (oa == NULL) {
151                 CERROR("cannot alloc oa, error %d\n",
152                        -ENOMEM);
153                 EXIT;
154                 return;
155         }
156
157         oa->o_id = lsm->lsm_object_id;
158         oa->o_gr = lsm->lsm_object_gr;
159         oa->o_valid = OBD_MD_FLID | OBD_MD_FLGROUP | OBD_MD_FLIFID;
160         obdo_from_inode(oa, inode, OBD_MD_FLTYPE | OBD_MD_FLMODE |
161                         OBD_MD_FLATIME | OBD_MD_FLMTIME | OBD_MD_FLCTIME);
162         memcpy(obdo_id(oa), &lli->lli_id, sizeof(lli->lli_id));
163
164         obd_adjust_kms(ll_i2dtexp(inode), lsm, inode->i_size, 1);
165
166         lli->lli_size_pid = 0;
167         up(&lli->lli_size_sem);
168         
169         rc = obd_punch(ll_i2dtexp(inode), oa, lsm, inode->i_size,
170                        OBD_OBJECT_EOF, NULL, lli->lli_trunc_capa);
171         if (rc)
172                 CERROR("obd_truncate fails (%d) ino %lu\n", rc, inode->i_ino);
173         else
174                 obdo_to_inode(inode, oa, OBD_MD_FLSIZE | OBD_MD_FLBLOCKS |
175                               OBD_MD_FLATIME | OBD_MD_FLMTIME | OBD_MD_FLCTIME);
176
177         obdo_free(oa);
178         
179         EXIT;
180         return;
181         
182 out_unlock:
183         LASSERT(atomic_read(&lli->lli_size_sem.count) <= 0);
184         up(&lli->lli_size_sem);
185 } /* ll_truncate */
186
187 struct ll_async_page *llap_cast_private(struct page *page)
188 {
189         struct ll_async_page *llap = (struct ll_async_page *)page->private;
190
191         LASSERTF(llap == NULL || llap->llap_magic == LLAP_MAGIC, 
192                  "page %p private %lu gave magic %d which != %d\n",
193                  page, page->private, llap->llap_magic, LLAP_MAGIC);
194         return llap;
195 }
196
197 int ll_prepare_write(struct file *file, struct page *page,
198                      unsigned from, unsigned to)
199 {
200         struct inode *inode = page->mapping->host;
201         struct ll_inode_info *lli = ll_i2info(inode);
202         struct lov_stripe_md *lsm = lli->lli_smd;
203         obd_off offset = ((obd_off)page->index) << PAGE_SHIFT;
204         struct obdo *oa = NULL;
205         struct brw_page pga;
206         __u64 kms;
207         int rc = 0;
208         ENTRY;
209
210         LASSERT(LLI_DIRTY_HANDLE(inode));
211         LASSERT(PageLocked(page));
212         (void)llap_cast_private(page); /* assertion */
213
214         /* Check to see if we should return -EIO right away */
215         pga.pg = page;
216         pga.disk_offset = pga.page_offset = offset;
217         pga.count = PAGE_SIZE;
218         pga.flag = 0;
219
220         oa = obdo_alloc();
221         if (oa == NULL)
222                 RETURN(-ENOMEM);
223
224         oa->o_id = lsm->lsm_object_id;
225         oa->o_gr = lsm->lsm_object_gr;
226         oa->o_mode = inode->i_mode;
227
228         oa->o_valid = OBD_MD_FLID | OBD_MD_FLMODE |
229                 OBD_MD_FLTYPE | OBD_MD_FLGROUP;
230
231         oa->o_fsuid = current->fsuid;
232         oa->o_valid |= OBD_MD_FLFSUID;
233
234         rc = obd_brw(OBD_BRW_CHECK, ll_i2dtexp(inode),
235                      oa, lsm, 1, &pga, NULL);
236         if (rc)
237                 GOTO(out_free_oa, rc);
238
239         if (PageUptodate(page))
240                 GOTO(out_free_oa, 0);
241
242         /* We're completely overwriting an existing page, so _don't_ set it up
243          * to date until commit_write */
244         if (from == 0 && to == PAGE_SIZE) {
245                 POISON_PAGE(page, 0x11);
246                 GOTO(out_free_oa, 0);
247         }
248
249         /* If are writing to a new page, no need to read old data.  The extent
250          * locking will have updated the KMS, and for our purposes here we can
251          * treat it like i_size. */
252         down(&lli->lli_size_sem);
253         kms = lov_merge_size(lsm, 1);
254         up(&lli->lli_size_sem);
255         if (kms <= offset) {
256                 memset(kmap(page), 0, PAGE_SIZE);
257                 kunmap(page);
258                 GOTO(prepare_done, rc = 0);
259         }
260
261         /* XXX could be an async ocp read.. read-ahead? */
262         rc = ll_brw(OBD_BRW_READ, inode, oa, page, 0);
263         if (rc == 0) {
264                 /* bug 1598: don't clobber blksize */
265                 oa->o_valid &= ~(OBD_MD_FLSIZE | OBD_MD_FLBLKSZ);
266                 obdo_refresh_inode(inode, oa, oa->o_valid);
267         } else if (rc == -ENOENT) {
268                 /* tolerate no entry error here, cause the objects might
269                  * not be created yet */
270                 rc = 0;
271         }
272
273         EXIT;
274 prepare_done:
275         if (rc == 0)
276                 SetPageUptodate(page);
277 out_free_oa:
278         obdo_free(oa);
279         return rc;
280 }
281
282 static int ll_ap_make_ready(void *data, int cmd)
283 {
284         struct ll_async_page *llap;
285         struct page *page;
286         ENTRY;
287
288         llap = LLAP_FROM_COOKIE(data);
289         page = llap->llap_page;
290
291         LASSERT(cmd != OBD_BRW_READ);
292
293         /* we're trying to write, but the page is locked.. come back later */
294         if (TryLockPage(page))
295                 RETURN(-EAGAIN);
296
297         LL_CDEBUG_PAGE(D_PAGE, page, "made ready\n");
298         page_cache_get(page);
299
300         /* if we left PageDirty we might get another writepage call
301          * in the future.  list walkers are bright enough
302          * to check page dirty so we can leave it on whatever list
303          * its on.  XXX also, we're called with the cli list so if
304          * we got the page cache list we'd create a lock inversion
305          * with the removepage path which gets the page lock then the
306          * cli lock */
307         clear_page_dirty(page);
308         RETURN(0);
309 }
310
311 /* We have two reasons for giving llite the opportunity to change the 
312  * write length of a given queued page as it builds the RPC containing
313  * the page: 
314  *
315  * 1) Further extending writes may have landed in the page cache
316  *    since a partial write first queued this page requiring us
317  *    to write more from the page cache. (No further races are possible, since
318  *    by the time this is called, the page is locked.)
319  * 2) We might have raced with truncate and want to avoid performing
320  *    write RPCs that are just going to be thrown away by the 
321  *    truncate's punch on the storage targets.
322  *
323  * The kms serves these purposes as it is set at both truncate and extending
324  * writes.
325  */
326 static int ll_ap_refresh_count(void *data, int cmd)
327 {
328         struct ll_inode_info *lli;
329         struct ll_async_page *llap;
330         struct lov_stripe_md *lsm;
331         struct page *page;
332         __u64 kms;
333         ENTRY;
334
335         /* readpage queues with _COUNT_STABLE, shouldn't get here. */
336         LASSERT(cmd != OBD_BRW_READ);
337
338         llap = LLAP_FROM_COOKIE(data);
339         page = llap->llap_page;
340         lli = ll_i2info(page->mapping->host);
341         lsm = lli->lli_smd;
342
343         /*
344          * this callback is called with client lock taken, thus, it should not
345          * sleep or deadlock is possible. --umka
346          */
347 //        down(&lli->lli_size_sem);
348         kms = lov_merge_size(lsm, 1);
349 //        up(&lli->lli_size_sem);
350
351         /* catch race with truncate */
352         if (((__u64)page->index << PAGE_SHIFT) >= kms)
353                 return 0;
354
355         /* catch sub-page write at end of file */
356         if (((__u64)page->index << PAGE_SHIFT) + PAGE_SIZE > kms)
357                 return kms % PAGE_SIZE;
358
359         return PAGE_SIZE;
360 }
361
362 void ll_inode_fill_obdo(struct inode *inode, int cmd, struct obdo *oa)
363 {
364         struct lov_stripe_md *lsm;
365         obd_valid valid_flags;
366
367         lsm = ll_i2info(inode)->lli_smd;
368
369         oa->o_id = lsm->lsm_object_id;
370         oa->o_gr = lsm->lsm_object_gr;
371         oa->o_valid = OBD_MD_FLID | OBD_MD_FLGROUP;
372         valid_flags = OBD_MD_FLTYPE | OBD_MD_FLATIME;
373         if (cmd == OBD_BRW_WRITE || cmd == OBD_BRW_READ) {
374                 oa->o_valid |= OBD_MD_FLIFID | OBD_MD_FLEPOCH;
375                 *(obdo_id(oa)) = ll_i2info(inode)->lli_id;
376                 oa->o_easize = ll_i2info(inode)->lli_io_epoch;
377                 valid_flags |= OBD_MD_FLMTIME | OBD_MD_FLCTIME;
378         }
379
380         obdo_from_inode(oa, inode, valid_flags);
381 }
382
383 static void ll_ap_fill_obdo(void *data, int cmd, struct obdo *oa)
384 {
385         struct ll_async_page *llap;
386         ENTRY;
387
388         llap = LLAP_FROM_COOKIE(data);
389         ll_inode_fill_obdo(llap->llap_page->mapping->host, cmd, oa);
390         oa->o_fsuid = llap->llap_fsuid;
391         EXIT;
392 }
393
394 static struct obd_async_page_ops ll_async_page_ops = {
395         .ap_make_ready =        ll_ap_make_ready,
396         .ap_refresh_count =     ll_ap_refresh_count,
397         .ap_fill_obdo =         ll_ap_fill_obdo,
398         .ap_completion =        ll_ap_completion,
399 };
400
401
402 /* XXX have the exp be an argument? */
403 struct ll_async_page *llap_from_page(struct page *page, unsigned origin)
404 {
405         struct ll_async_page *llap;
406         struct obd_export *exp;
407         struct inode *inode = page->mapping->host;
408         struct ll_sb_info *sbi = ll_i2sbi(inode);
409         int rc;
410         ENTRY;
411
412         LASSERTF(origin < LLAP__ORIGIN_MAX, "%u\n", origin);
413
414         llap = llap_cast_private(page);
415         if (llap != NULL) {
416                 GOTO(out, llap);
417         }
418         exp = ll_i2dtexp(page->mapping->host);
419         if (exp == NULL)
420                 RETURN(ERR_PTR(-EINVAL));
421         
422         OBD_ALLOC(llap, sizeof(*llap));
423         if (llap == NULL) {
424                 RETURN(ERR_PTR(-ENOMEM));
425         }
426         llap->llap_magic = LLAP_MAGIC;
427         INIT_LIST_HEAD(&llap->llap_pending_write);
428         rc = obd_prep_async_page(exp, ll_i2info(inode)->lli_smd, NULL, page,
429                                  (obd_off)page->index << PAGE_SHIFT,
430                                  &ll_async_page_ops, llap, &llap->llap_cookie);
431         if (rc) {
432                 OBD_FREE(llap, sizeof(*llap));
433                 RETURN(ERR_PTR(rc));
434         }
435
436         CDEBUG(D_CACHE, "llap %p page %p cookie %p obj off "LPU64"\n", llap,
437                page, llap->llap_cookie, (obd_off)page->index << PAGE_SHIFT);
438        
439         __set_page_ll_data(page, llap);
440        
441          /* also zeroing the PRIVBITS low order bitflags */
442         llap->llap_page = page;
443
444         spin_lock(&sbi->ll_lock);
445         sbi->ll_pglist_gen++;
446         list_add_tail(&llap->llap_proc_item, &sbi->ll_pglist);
447         spin_unlock(&sbi->ll_lock);
448
449 out:
450         llap->llap_origin = origin;
451         RETURN(llap);
452 }
453
454 static int queue_or_sync_write(struct obd_export *exp,
455                                struct lov_stripe_md *lsm,
456                                struct ll_async_page *llap,
457                                unsigned to,
458                                obd_flags async_flags)
459 {
460         struct obd_io_group *oig;
461         int rc;
462         ENTRY;
463
464         /* _make_ready only sees llap once we've unlocked the page */
465         llap->llap_write_queued = 1;
466         rc = obd_queue_async_io(exp, lsm, NULL, llap->llap_cookie,
467                                 OBD_BRW_WRITE, 0, 0, 0, async_flags);
468         if (rc == 0) {
469                 LL_CDEBUG_PAGE(D_PAGE, llap->llap_page, "write queued\n");
470                 llap_write_pending(llap->llap_page->mapping->host, llap);
471                 GOTO(out, 0);
472         }
473
474         llap->llap_write_queued = 0;
475
476         rc = oig_init(&oig);
477         if (rc)
478                 GOTO(out, rc);
479         rc = obd_queue_group_io(exp, lsm, NULL, oig, llap->llap_cookie,
480                                 OBD_BRW_WRITE, 0, to, 0, ASYNC_READY |
481                                 ASYNC_URGENT | ASYNC_COUNT_STABLE |
482                                 ASYNC_GROUP_SYNC);
483         if (rc)
484                 GOTO(free_oig, rc);
485
486         rc = obd_trigger_group_io(exp, lsm, NULL, oig);
487         if (rc)
488                 GOTO(free_oig, rc);
489
490         rc = oig_wait(oig);
491
492         if (!rc && async_flags & ASYNC_READY)
493                 unlock_page(llap->llap_page);
494
495         LL_CDEBUG_PAGE(D_PAGE, llap->llap_page,
496                        "sync write returned %d\n", rc);
497
498         EXIT;
499 free_oig:
500         oig_release(oig);
501 out:
502         return rc;
503 }
504
505 /* be careful not to return success without setting the page Uptodate or
506  * the next pass through prepare_write will read in stale data from disk. */
507 int ll_commit_write(struct file *file, struct page *page, unsigned from,
508                     unsigned to)
509 {
510         struct inode *inode = page->mapping->host;
511         struct ll_inode_info *lli = ll_i2info(inode);
512         struct lov_stripe_md *lsm = lli->lli_smd;
513         struct obd_export *exp = NULL;
514         struct ll_async_page *llap;
515         loff_t size;
516         int rc = 0;
517         ENTRY;
518
519         SIGNAL_MASK_ASSERT(); /* XXX BUG 1511 */
520         LASSERT(inode == file->f_dentry->d_inode);
521         LASSERT(PageLocked(page));
522         LASSERT(LLI_DIRTY_HANDLE(inode));
523
524         CDEBUG(D_INODE, "inode %p is writing page %p from %d to %d at %lu\n",
525                inode, page, from, to, page->index);
526
527         llap = llap_from_page(page, LLAP_ORIGIN_COMMIT_WRITE);
528         if (IS_ERR(llap))
529                 RETURN(PTR_ERR(llap));
530
531         exp = ll_i2dtexp(inode);
532         if (exp == NULL)
533                 RETURN(-EINVAL);
534
535         llap->llap_fsuid = current->fsuid;
536
537         /* queue a write for some time in the future the first time we
538          * dirty the page */
539         if (!PageDirty(page)) {
540                 lprocfs_counter_incr(ll_i2sbi(inode)->ll_stats,
541                                      LPROC_LL_DIRTY_MISSES);
542
543                 rc = queue_or_sync_write(exp, ll_i2info(inode)->lli_smd, 
544                                          llap, to, 0);
545                 if (rc)
546                         GOTO(out, rc);
547         } else {
548                 lprocfs_counter_incr(ll_i2sbi(inode)->ll_stats,
549                                      LPROC_LL_DIRTY_HITS);
550         }
551
552         /* put the page in the page cache, from now on ll_removepage is
553          * responsible for cleaning up the llap.
554          * don't dirty the page if it has been write out in q_o_s_w */
555         if (llap->llap_write_queued)
556                 set_page_dirty(page);
557         EXIT;
558 out:
559         size = (((obd_off)page->index) << PAGE_SHIFT) + to;
560         down(&lli->lli_size_sem);
561         if (rc == 0) {
562                 obd_adjust_kms(exp, lsm, size, 0);
563                 if (size > inode->i_size)
564                         inode->i_size = size;
565                 SetPageUptodate(page);
566         } else if (size > inode->i_size) {
567                 /* this page beyond the pales of i_size, so it can't be
568                  * truncated in ll_p_r_e during lock revoking. we must
569                  * teardown our book-keeping here. */
570                 ll_removepage(page);
571         }
572         up(&lli->lli_size_sem);
573         return rc;
574 }
575
576 static unsigned long ll_ra_count_get(struct ll_sb_info *sbi, unsigned long len)
577 {
578         struct ll_ra_info *ra = &sbi->ll_ra_info;
579         unsigned long ret;
580         ENTRY;
581
582         spin_lock(&sbi->ll_lock);
583         ret = min(ra->ra_max_pages - ra->ra_cur_pages, len);
584         ra->ra_cur_pages += ret;
585         spin_unlock(&sbi->ll_lock);
586
587         RETURN(ret);
588 }
589
590 static void ll_ra_count_put(struct ll_sb_info *sbi, unsigned long len)
591 {
592         struct ll_ra_info *ra = &sbi->ll_ra_info;
593         spin_lock(&sbi->ll_lock);
594         LASSERTF(ra->ra_cur_pages >= len, "r_c_p %lu len %lu\n",
595                  ra->ra_cur_pages, len);
596         ra->ra_cur_pages -= len;
597         spin_unlock(&sbi->ll_lock);
598 }
599
600 int ll_writepage(struct page *page)
601 {
602         struct inode *inode = page->mapping->host;
603         struct obd_export *exp;
604         struct ll_async_page *llap;
605         int rc = 0;
606         ENTRY;
607
608         LASSERT(!PageDirty(page));
609         LASSERT(PageLocked(page));
610         LASSERT(LLI_DIRTY_HANDLE(inode));
611
612         exp = ll_i2dtexp(inode);
613         if (exp == NULL)
614                 GOTO(out, rc = -EINVAL);
615
616         llap = llap_from_page(page, LLAP_ORIGIN_WRITEPAGE);
617         if (IS_ERR(llap))
618                 GOTO(out, rc = PTR_ERR(llap));
619
620         page_cache_get(page);
621         if (llap->llap_write_queued) {
622                 LL_CDEBUG_PAGE(D_PAGE, page, "marking urgent\n");
623                 rc = obd_set_async_flags(exp, ll_i2info(inode)->lli_smd, NULL,
624                                          llap->llap_cookie,
625                                          ASYNC_READY | ASYNC_URGENT);
626         } else {
627                 rc = queue_or_sync_write(exp, ll_i2info(inode)->lli_smd, llap,
628                                          PAGE_SIZE, ASYNC_READY |
629                                          ASYNC_URGENT);
630         }
631         if (rc)
632                 page_cache_release(page);
633         EXIT;
634 out:
635         if (rc)
636                 unlock_page(page);
637         return rc;
638 }
639
640 /* called for each page in a completed rpc.*/
641 void ll_ap_completion(void *data, int cmd, struct obdo *oa, int rc)
642 {
643         struct ll_async_page *llap;
644         struct page *page;
645         ENTRY;
646
647         llap = LLAP_FROM_COOKIE(data);
648         page = llap->llap_page;
649         LASSERT(PageLocked(page));
650
651         LL_CDEBUG_PAGE(D_PAGE, page, "completing cmd %d with %d\n", cmd, rc);
652
653         if (cmd == OBD_BRW_READ && llap->llap_defer_uptodate)
654                 ll_ra_count_put(ll_i2sbi(page->mapping->host), 1);
655
656         if (rc == 0)  {
657                 if (cmd == OBD_BRW_READ) {
658                         if (!llap->llap_defer_uptodate)
659                                 SetPageUptodate(page);
660                 } else {
661                         llap->llap_write_queued = 0;
662                 }
663                 ClearPageError(page);
664         } else {
665                 if (cmd == OBD_BRW_READ)
666                         llap->llap_defer_uptodate = 0;
667                 SetPageError(page);
668         }
669
670         unlock_page(page);
671
672         if (cmd == OBD_BRW_WRITE) {
673                 llap_write_complete(page->mapping->host, llap);
674                 ll_try_done_writing(page->mapping->host);
675         }
676         
677         if (PageWriteback(page)) {
678                 end_page_writeback(page);
679         }
680         page_cache_release(page);
681         EXIT;
682 }
683
684 /* the kernel calls us here when a page is unhashed from the page cache.
685  * the page will be locked and the kernel is holding a spinlock, so
686  * we need to be careful.  we're just tearing down our book-keeping
687  * here. */
688 void ll_removepage(struct page *page)
689 {
690         struct inode *inode = page->mapping->host;
691         struct obd_export *exp;
692         struct ll_async_page *llap;
693         struct ll_sb_info *sbi = ll_i2sbi(inode);
694         int rc;
695         ENTRY;
696
697         LASSERT(!in_interrupt());
698
699         /* sync pages or failed read pages can leave pages in the page
700          * cache that don't have our data associated with them anymore */
701         if (page->private == 0) {
702                 EXIT;
703                 return;
704         }
705
706         LL_CDEBUG_PAGE(D_PAGE, page, "being evicted\n");
707
708         exp = ll_i2dtexp(inode);
709         if (exp == NULL) {
710                 CERROR("page %p ind %lu gave null export\n", page, page->index);
711                 EXIT;
712                 return;
713         }
714         llap = llap_from_page(page, 0);
715         if (IS_ERR(llap)) {
716                 CERROR("page %p ind %lu couldn't find llap: %ld\n", page,
717                        page->index, PTR_ERR(llap));
718                 EXIT;
719                 return;
720         }
721
722         llap_write_complete(inode, llap);
723         rc = obd_teardown_async_page(exp, ll_i2info(inode)->lli_smd, NULL,
724                                      llap->llap_cookie);
725         if (rc != 0)
726                 CERROR("page %p ind %lu failed: %d\n", page, page->index, rc);
727
728         /* this unconditional free is only safe because the page lock
729          * is providing exclusivity to memory pressure/truncate/writeback..*/
730         __clear_page_ll_data(page);
731
732         spin_lock(&sbi->ll_lock);
733         if (!list_empty(&llap->llap_proc_item))
734                 list_del_init(&llap->llap_proc_item);
735         sbi->ll_pglist_gen++;
736         spin_unlock(&sbi->ll_lock);
737         OBD_FREE(llap, sizeof(*llap));
738         EXIT;
739 }
740
741 static int ll_page_matches(struct page *page, int fd_flags, int readahead)
742 {
743         struct lustre_handle match_lockh = {0};
744         struct inode *inode = page->mapping->host;
745         ldlm_policy_data_t page_extent;
746         int flags, matches;
747         ENTRY;
748
749         if (fd_flags & LL_FILE_GROUP_LOCKED)
750                 RETURN(1);
751
752         page_extent.l_extent.start = (__u64)page->index << PAGE_CACHE_SHIFT;
753         page_extent.l_extent.end =
754                 page_extent.l_extent.start + PAGE_CACHE_SIZE - 1;
755         flags = LDLM_FL_TEST_LOCK;
756         if (!readahead)
757                 flags |= LDLM_FL_CBPENDING | LDLM_FL_BLOCK_GRANTED;
758         matches = obd_match(ll_i2sbi(inode)->ll_dt_exp,
759                             ll_i2info(inode)->lli_smd, LDLM_EXTENT,
760                             &page_extent, LCK_PR | LCK_PW, &flags, inode,
761                             &match_lockh);
762         RETURN(matches);
763 }
764
765 static int ll_issue_page_read(struct obd_export *exp,
766                               struct ll_async_page *llap,
767                               struct obd_io_group *oig, int defer)
768 {
769         struct page *page = llap->llap_page;
770         int rc;
771
772         page_cache_get(page);
773         llap->llap_defer_uptodate = defer;
774         llap->llap_ra_used = 0;
775         
776         rc = obd_queue_group_io(exp, ll_i2info(page->mapping->host)->lli_smd,
777                                 NULL, oig, llap->llap_cookie, OBD_BRW_READ, 0,
778                                 PAGE_SIZE, 0, ASYNC_COUNT_STABLE | ASYNC_READY
779                                 | ASYNC_URGENT);
780         if (rc) {
781                 LL_CDEBUG_PAGE(D_ERROR, page, "read queue failed: rc %d\n", rc);
782                 page_cache_release(page);
783         }
784         RETURN(rc);
785 }
786
787 static void ll_ra_stats_inc_unlocked(struct ll_ra_info *ra, enum ra_stat which)
788 {
789         LASSERTF(which >= 0 && which < _NR_RA_STAT, "which: %u\n", which);
790         ra->ra_stats[which]++;
791 }
792
793 static void ll_ra_stats_inc(struct address_space *mapping, enum ra_stat which)
794 {
795         struct ll_sb_info *sbi = ll_i2sbi(mapping->host);
796         struct ll_ra_info *ra = &ll_i2sbi(mapping->host)->ll_ra_info;
797
798         spin_lock(&sbi->ll_lock);
799         ll_ra_stats_inc_unlocked(ra, which);
800         spin_unlock(&sbi->ll_lock);
801 }
802
803 void ll_ra_accounting(struct page *page, struct address_space *mapping)
804 {
805         struct ll_async_page *llap;
806
807         llap = llap_from_page(page, LLAP_ORIGIN_WRITEPAGE);
808         if (IS_ERR(llap))
809                 return;
810
811         if (!llap->llap_defer_uptodate || llap->llap_ra_used)
812                 return;
813
814         ll_ra_stats_inc(mapping, RA_STAT_DISCARDED);
815 }
816
817 #define RAS_CDEBUG(ras) \
818         CDEBUG(D_READA, "lrp %lu c %lu ws %lu wl %lu nra %lu\n",        \
819                ras->ras_last_readpage, ras->ras_consecutive,            \
820                ras->ras_window_start, ras->ras_window_len,              \
821                ras->ras_next_readahead);
822
823 static int index_in_window(unsigned long index, unsigned long point,
824                            unsigned long before, unsigned long after)
825 {
826         unsigned long start = point - before, end = point + after;
827
828         if (start > point)
829                start = 0;
830         if (end < point)
831                end = ~0;
832
833         return start <= index && index <= end;
834 }
835
836 static int ll_readahead(struct ll_readahead_state *ras,
837                          struct obd_export *exp, struct address_space *mapping,
838                          struct obd_io_group *oig, int flags)
839 {
840         unsigned long i, start = 0, end = 0, reserved;
841         struct ll_async_page *llap;
842         struct page *page;
843         int rc, ret = 0, match_failed = 0;
844         __u64 kms;
845         ENTRY;
846
847         kms = lov_merge_size(ll_i2info(mapping->host)->lli_smd, 1);
848         if (kms == 0) {
849                 ll_ra_stats_inc(mapping, RA_STAT_ZERO_LEN);
850                 RETURN(0);
851         }
852         spin_lock(&ras->ras_lock);
853
854         /* reserve a part of the read-ahead window that we'll be issuing */
855         if (ras->ras_window_len) {
856                 start = ras->ras_next_readahead;
857                 end = ras->ras_window_start + ras->ras_window_len - 1;
858                 end = min(end, (unsigned long)(kms >> PAGE_CACHE_SHIFT));
859                 ras->ras_next_readahead = max(end, end + 1);
860
861                 RAS_CDEBUG(ras);
862         }
863
864         spin_unlock(&ras->ras_lock);
865
866         if (end == 0) {
867                 ll_ra_stats_inc(mapping, RA_STAT_ZERO_WINDOW);
868                 RETURN(0);
869         }
870
871         reserved = ll_ra_count_get(ll_i2sbi(mapping->host), end - start + 1);
872         if (reserved < end - start + 1)
873                 ll_ra_stats_inc(mapping, RA_STAT_MAX_IN_FLIGHT);
874
875         for (i = start; reserved > 0 && !match_failed && i <= end; i++) {
876                 /* skip locked pages from previous readpage calls */
877                 page = grab_cache_page_nowait(mapping, i);
878                 if (page == NULL) {
879                         CDEBUG(D_READA, "g_c_p_n failed\n");
880                         continue;
881                 }
882                 
883                 /* we do this first so that we can see the page in the /proc
884                  * accounting */
885                 llap = llap_from_page(page, LLAP_ORIGIN_READAHEAD);
886                 if (IS_ERR(llap) || llap->llap_defer_uptodate)
887                         goto next_page;
888
889                 /* skip completed pages */
890                 if (Page_Uptodate(page))
891                         goto next_page;
892
893                 /* bail when we hit the end of the lock. */
894                 if ((rc = ll_page_matches(page, flags, 1)) <= 0) {
895                         LL_CDEBUG_PAGE(D_READA | D_PAGE, page,
896                                        "lock match failed: rc %d\n", rc);
897                         ll_ra_stats_inc(mapping, RA_STAT_FAILED_MATCH);
898                         match_failed = 1;
899                         goto next_page;
900                 }
901
902                 rc = ll_issue_page_read(exp, llap, oig, 1);
903                 if (rc == 0) {
904                         reserved--;
905                         ret++;
906                         LL_CDEBUG_PAGE(D_READA| D_PAGE, page, 
907                                        "started read-ahead\n");
908                 }
909                 if (rc) {
910         next_page:
911                         LL_CDEBUG_PAGE(D_READA | D_PAGE, page, 
912                                        "skipping read-ahead\n");
913
914                         unlock_page(page);
915                 }
916                 page_cache_release(page);
917         }
918
919         LASSERTF(reserved >= 0, "reserved %lu\n", reserved);
920         if (reserved != 0)
921                 ll_ra_count_put(ll_i2sbi(mapping->host), reserved);
922
923         if (i == end + 1 && end == (kms >> PAGE_CACHE_SHIFT))
924                 ll_ra_stats_inc(mapping, RA_STAT_EOF);
925
926         /* if we didn't get to the end of the region we reserved from
927          * the ras we need to go back and update the ras so that the
928          * next read-ahead tries from where we left off.  we only do so
929          * if the region we failed to issue read-ahead on is still ahead
930          * of the app and behind the next index to start read-ahead from */
931         if (i != end + 1) {
932                 spin_lock(&ras->ras_lock);
933                 if (i < ras->ras_next_readahead &&
934                     index_in_window(i, ras->ras_window_start, 0,
935                                     ras->ras_window_len)) {
936                         ras->ras_next_readahead = i;
937                         RAS_CDEBUG(ras);
938                 }
939                 spin_unlock(&ras->ras_lock);
940         }
941
942         RETURN(ret);
943 }
944
945 static void ras_set_start(struct ll_readahead_state *ras, unsigned long index)
946 {
947         ras->ras_window_start = index & (~(PTLRPC_MAX_BRW_PAGES - 1));
948 }
949
950 /* called with the ras_lock held or from places where it doesn't matter */
951 static void ras_reset(struct ll_readahead_state *ras, unsigned long index)
952 {
953         ras->ras_last_readpage = index;
954         ras->ras_consecutive = 1;
955         ras->ras_window_len = 0;
956         ras_set_start(ras, index);
957         ras->ras_next_readahead = ras->ras_window_start;
958
959         RAS_CDEBUG(ras);
960 }
961
962 void ll_readahead_init(struct inode *inode, struct ll_readahead_state *ras)
963 {
964         spin_lock_init(&ras->ras_lock);
965         ras_reset(ras, 0);
966 }
967
968 static void ras_update(struct ll_sb_info *sbi, struct ll_readahead_state *ras,
969                        unsigned long index, unsigned hit)
970 {
971         struct ll_ra_info *ra = &sbi->ll_ra_info;
972         int zero = 0;
973         ENTRY;
974
975         spin_lock(&sbi->ll_lock);
976         spin_lock(&ras->ras_lock);
977         
978         ll_ra_stats_inc_unlocked(ra, hit ? RA_STAT_HIT : RA_STAT_MISS);
979
980         /* reset the read-ahead window in two cases.  First when the app seeks
981          * or reads to some other part of the file.  Secondly if we get a
982          * read-ahead miss that we think we've previously issued.  This can
983          * be a symptom of there being so many read-ahead pages that the VM is
984          * reclaiming it before we get to it. */
985         if (!index_in_window(index, ras->ras_last_readpage, 8, 8)) {
986                 zero = 1;
987                 ll_ra_stats_inc_unlocked(ra, RA_STAT_DISTANT_READPAGE);
988         } else if (!hit && ras->ras_window_len &&
989                    index < ras->ras_next_readahead &&
990                    index_in_window(index, ras->ras_window_start, 0,
991                                    ras->ras_window_len)) {
992                 zero = 1;
993                 ll_ra_stats_inc_unlocked(ra, RA_STAT_MISS_IN_WINDOW);
994         }
995
996         if (zero) {
997                 ras_reset(ras, index);
998                 GOTO(out_unlock, 0);
999         }
1000
1001         ras->ras_last_readpage = index;
1002         ras->ras_consecutive++;
1003         ras_set_start(ras, index);
1004         ras->ras_next_readahead = max(ras->ras_window_start,
1005                                       ras->ras_next_readahead);
1006
1007         /* wait for a few pages to arrive before issuing readahead to avoid
1008          * the worst overutilization */
1009         if (ras->ras_consecutive == 3) {
1010                 ras->ras_window_len = PTLRPC_MAX_BRW_PAGES;
1011                 GOTO(out_unlock, 0);
1012         }
1013
1014         /* we need to increase the window sometimes.  we'll arbitrarily
1015          * do it half-way through the pages in an rpc */
1016         if ((index & (PTLRPC_MAX_BRW_PAGES - 1)) == 
1017             (PTLRPC_MAX_BRW_PAGES >> 1)) {
1018                 ras->ras_window_len += PTLRPC_MAX_BRW_PAGES;
1019                 ras->ras_window_len = min(ras->ras_window_len,
1020                                           ra->ra_max_pages);
1021
1022         }
1023
1024         EXIT;
1025 out_unlock:
1026         RAS_CDEBUG(ras);
1027         spin_unlock(&ras->ras_lock);
1028         spin_unlock(&sbi->ll_lock);
1029 }
1030
1031 /*
1032  * for now we do our readpage the same on both 2.4 and 2.5.  The kernel's
1033  * read-ahead assumes it is valid to issue readpage all the way up to
1034  * i_size, but our dlm locks make that not the case.  We disable the
1035  * kernel's read-ahead and do our own by walking ahead in the page cache
1036  * checking for dlm lock coverage.  the main difference between 2.4 and
1037  * 2.6 is how read-ahead gets batched and issued, but we're using our own,
1038  * so they look the same.
1039  */
1040 int ll_readpage(struct file *filp, struct page *page)
1041 {
1042         struct ll_file_data *fd = filp->private_data;
1043         struct inode *inode = page->mapping->host;
1044         struct obd_export *exp;
1045         struct ll_async_page *llap;
1046         struct obd_io_group *oig = NULL;
1047         int rc;
1048         ENTRY;
1049
1050         LASSERT(PageLocked(page));
1051         LASSERT(!PageUptodate(page));
1052         CDEBUG(D_VFSTRACE, "VFS Op:inode=%lu/%u(%p),offset="LPX64"\n",
1053                inode->i_ino, inode->i_generation, inode,
1054                (((obd_off)page->index) << PAGE_SHIFT));
1055         LASSERT(atomic_read(&filp->f_dentry->d_inode->i_count) > 0);
1056
1057         rc = oig_init(&oig);
1058         if (rc < 0)
1059                 GOTO(out, rc);
1060
1061         exp = ll_i2dtexp(inode);
1062         if (exp == NULL)
1063                 GOTO(out, rc = -EINVAL);
1064
1065         llap = llap_from_page(page, LLAP_ORIGIN_READPAGE);
1066         if (IS_ERR(llap))
1067                 GOTO(out, rc = PTR_ERR(llap));
1068         
1069         if (ll_i2sbi(inode)->ll_flags & LL_SBI_READAHEAD)
1070                 ras_update(ll_i2sbi(inode), &fd->fd_ras, page->index,
1071                            llap->llap_defer_uptodate);
1072         
1073         if (llap->llap_defer_uptodate) {
1074                 llap->llap_ra_used = 1;
1075                 rc = ll_readahead(&fd->fd_ras, exp, page->mapping, oig,
1076                                   fd->fd_flags);
1077                 if (rc > 0)
1078                         obd_trigger_group_io(exp, ll_i2info(inode)->lli_smd, 
1079                                              NULL, oig);
1080                 LL_CDEBUG_PAGE(D_PAGE, page, "marking uptodate from defer\n");
1081                 SetPageUptodate(page);
1082                 unlock_page(page);
1083                 GOTO(out_oig, rc = 0);
1084         }
1085
1086         rc = ll_page_matches(page, fd->fd_flags, 0);
1087         if (rc < 0) {
1088                 LL_CDEBUG_PAGE(D_ERROR, page, "lock match failed: rc %d\n", rc);
1089                 GOTO(out, rc);
1090         }
1091
1092         if (rc == 0) {
1093                 CWARN("ino %lu page %lu (%llu) not covered by "
1094                       "a lock (mmap?).  check debug logs.\n",
1095                       inode->i_ino, page->index,
1096                       (long long)page->index << PAGE_CACHE_SHIFT);
1097         }
1098
1099         rc = ll_issue_page_read(exp, llap, oig, 0);
1100         if (rc)
1101                 GOTO(out, rc);
1102
1103         LL_CDEBUG_PAGE(D_PAGE, page, "queued readpage\n");
1104         if (ll_i2sbi(inode)->ll_flags & LL_SBI_READAHEAD)
1105                 ll_readahead(&fd->fd_ras, exp, page->mapping, oig,
1106                              fd->fd_flags);
1107
1108         rc = obd_trigger_group_io(exp, ll_i2info(inode)->lli_smd, NULL, oig);
1109         EXIT;
1110 out:
1111         if (rc)
1112                 unlock_page(page);
1113 out_oig:
1114         if (oig != NULL)
1115                 oig_release(oig);
1116         return rc;
1117 }