Whamcloud - gitweb
improve handling recoverable errors
[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 #ifndef AUTOCONF_INCLUDED
25 #include <linux/config.h>
26 #endif
27 #include <linux/kernel.h>
28 #include <linux/mm.h>
29 #include <linux/string.h>
30 #include <linux/stat.h>
31 #include <linux/errno.h>
32 #include <linux/smp_lock.h>
33 #include <linux/unistd.h>
34 #include <linux/version.h>
35 #include <asm/system.h>
36 #include <asm/uaccess.h>
37
38 #include <linux/fs.h>
39 #include <linux/stat.h>
40 #include <asm/uaccess.h>
41 #include <asm/segment.h>
42 #include <linux/mm.h>
43 #include <linux/pagemap.h>
44 #include <linux/smp_lock.h>
45
46 #define DEBUG_SUBSYSTEM S_LLITE
47
48 //#include <lustre_mdc.h>
49 #include <lustre_lite.h>
50 #include "llite_internal.h"
51 #include <linux/lustre_compat25.h>
52
53 #ifndef list_for_each_prev_safe
54 #define list_for_each_prev_safe(pos, n, head) \
55         for (pos = (head)->prev, n = pos->prev; pos != (head); \
56                 pos = n, n = pos->prev )
57 #endif
58
59 cfs_mem_cache_t *ll_async_page_slab = NULL;
60 size_t ll_async_page_slab_size = 0;
61
62 /* SYNCHRONOUS I/O to object storage for an inode */
63 static int ll_brw(int cmd, struct inode *inode, struct obdo *oa,
64                   struct page *page, int flags)
65 {
66         struct ll_inode_info *lli = ll_i2info(inode);
67         struct lov_stripe_md *lsm = lli->lli_smd;
68         struct obd_info oinfo = { { { 0 } } };
69         struct brw_page pg;
70         int opc, rc;
71         ENTRY;
72
73         pg.pg = page;
74         pg.off = ((obd_off)page->index) << CFS_PAGE_SHIFT;
75
76         if ((cmd & OBD_BRW_WRITE) && (pg.off+CFS_PAGE_SIZE>i_size_read(inode)))
77                 pg.count = i_size_read(inode) % CFS_PAGE_SIZE;
78         else
79                 pg.count = CFS_PAGE_SIZE;
80
81         LL_CDEBUG_PAGE(D_PAGE, page, "%s %d bytes ino %lu at "LPU64"/"LPX64"\n",
82                        cmd & OBD_BRW_WRITE ? "write" : "read", pg.count,
83                        inode->i_ino, pg.off, pg.off);
84         if (pg.count == 0) {
85                 CERROR("ZERO COUNT: ino %lu: size %p:%Lu(%p:%Lu) idx %lu off "
86                        LPU64"\n", inode->i_ino, inode, i_size_read(inode),
87                        page->mapping->host, i_size_read(page->mapping->host),
88                        page->index, pg.off);
89         }
90
91         pg.flag = flags;
92
93         if (cmd & OBD_BRW_WRITE)
94                 ll_stats_ops_tally(ll_i2sbi(inode), LPROC_LL_BRW_WRITE,
95                                    pg.count);
96         else
97                 ll_stats_ops_tally(ll_i2sbi(inode), LPROC_LL_BRW_READ,
98                                    pg.count);
99         oinfo.oi_oa = oa;
100         oinfo.oi_md = lsm;
101         /* NB partial write, so we might not have CAPA_OPC_OSS_READ capa */
102         opc = cmd & OBD_BRW_WRITE ? CAPA_OPC_OSS_WRITE : CAPA_OPC_OSS_RW;
103         oinfo.oi_capa = ll_osscapa_get(inode, opc);
104         rc = obd_brw(cmd, ll_i2dtexp(inode), &oinfo, 1, &pg, NULL);
105         capa_put(oinfo.oi_capa);
106         if (rc == 0)
107                 obdo_to_inode(inode, oa, OBD_MD_FLBLOCKS);
108         else if (rc != -EIO)
109                 CERROR("error from obd_brw: rc = %d\n", rc);
110         RETURN(rc);
111 }
112
113 /* this isn't where truncate starts.   roughly:
114  * sys_truncate->ll_setattr_raw->vmtruncate->ll_truncate. setattr_raw grabs
115  * DLM lock on [size, EOF], i_mutex, ->lli_size_sem, and WRITE_I_ALLOC_SEM to
116  * avoid races.
117  *
118  * must be called under ->lli_size_sem */
119 void ll_truncate(struct inode *inode)
120 {
121         struct ll_inode_info *lli = ll_i2info(inode);
122         struct obd_info oinfo = { { { 0 } } };
123         struct ost_lvb lvb;
124         struct obdo oa;
125         int rc;
126         ENTRY;
127         CDEBUG(D_VFSTRACE, "VFS Op:inode=%lu/%u(%p) to %Lu=%#Lx\n",inode->i_ino,
128                inode->i_generation, inode, i_size_read(inode),
129                i_size_read(inode));
130
131         ll_stats_ops_tally(ll_i2sbi(inode), LPROC_LL_TRUNC, 1);
132         if (lli->lli_size_sem_owner != current) {
133                 EXIT;
134                 return;
135         }
136
137         if (!lli->lli_smd) {
138                 CDEBUG(D_INODE, "truncate on inode %lu with no objects\n",
139                        inode->i_ino);
140                 GOTO(out_unlock, 0);
141         }
142
143         LASSERT(atomic_read(&lli->lli_size_sem.count) <= 0);
144
145         /* XXX I'm pretty sure this is a hack to paper over a more fundamental
146          * race condition. */
147         lov_stripe_lock(lli->lli_smd);
148         inode_init_lvb(inode, &lvb);
149         obd_merge_lvb(ll_i2dtexp(inode), lli->lli_smd, &lvb, 0);
150         if (lvb.lvb_size == i_size_read(inode)) {
151                 CDEBUG(D_VFSTRACE, "skipping punch for obj "LPX64", %Lu=%#Lx\n",
152                        lli->lli_smd->lsm_object_id, i_size_read(inode),
153                        i_size_read(inode));
154                 lov_stripe_unlock(lli->lli_smd);
155                 GOTO(out_unlock, 0);
156         }
157
158         obd_adjust_kms(ll_i2dtexp(inode), lli->lli_smd, i_size_read(inode), 1);
159         lov_stripe_unlock(lli->lli_smd);
160
161         if (unlikely((ll_i2sbi(inode)->ll_flags & LL_SBI_CHECKSUM) &&
162                      (i_size_read(inode) & ~CFS_PAGE_MASK))) {
163                 /* If the truncate leaves behind a partial page, update its
164                  * checksum. */
165                 struct page *page = find_get_page(inode->i_mapping,
166                                                   i_size_read(inode) >>
167                                                   CFS_PAGE_SHIFT);
168                 if (page != NULL) {
169                         struct ll_async_page *llap = llap_cast_private(page);
170                         if (llap != NULL) {
171                                 llap->llap_checksum =
172                                         crc32_le(0, kmap(page), CFS_PAGE_SIZE);
173                                 kunmap(page);
174                         }
175                         page_cache_release(page);
176                 }
177         }
178
179         CDEBUG(D_INFO, "calling punch for "LPX64" (new size %Lu=%#Lx)\n",
180                lli->lli_smd->lsm_object_id, i_size_read(inode), i_size_read(inode));
181
182         oinfo.oi_md = lli->lli_smd;
183         oinfo.oi_policy.l_extent.start = i_size_read(inode);
184         oinfo.oi_policy.l_extent.end = OBD_OBJECT_EOF;
185         oinfo.oi_oa = &oa;
186         oa.o_id = lli->lli_smd->lsm_object_id;
187         oa.o_gr = lli->lli_smd->lsm_object_gr;
188         oa.o_valid = OBD_MD_FLID | OBD_MD_FLGROUP;
189
190         obdo_from_inode(&oa, inode, OBD_MD_FLTYPE | OBD_MD_FLMODE |
191                         OBD_MD_FLATIME | OBD_MD_FLMTIME | OBD_MD_FLCTIME |
192                         OBD_MD_FLFID | OBD_MD_FLGENER);
193
194         ll_inode_size_unlock(inode, 0);
195
196         oinfo.oi_capa = ll_osscapa_get(inode, CAPA_OPC_OSS_TRUNC);
197         rc = obd_punch_rqset(ll_i2dtexp(inode), &oinfo, NULL);
198         ll_truncate_free_capa(oinfo.oi_capa);
199         if (rc)
200                 CERROR("obd_truncate fails (%d) ino %lu\n", rc, inode->i_ino);
201         else
202                 obdo_to_inode(inode, &oa, OBD_MD_FLSIZE | OBD_MD_FLBLOCKS |
203                               OBD_MD_FLATIME | OBD_MD_FLMTIME | OBD_MD_FLCTIME);
204         EXIT;
205         return;
206
207  out_unlock:
208         ll_inode_size_unlock(inode, 0);
209 } /* ll_truncate */
210
211 int ll_prepare_write(struct file *file, struct page *page, unsigned from,
212                      unsigned to)
213 {
214         struct inode *inode = page->mapping->host;
215         struct ll_inode_info *lli = ll_i2info(inode);
216         struct lov_stripe_md *lsm = lli->lli_smd;
217         obd_off offset = ((obd_off)page->index) << CFS_PAGE_SHIFT;
218         struct obd_info oinfo = { { { 0 } } };
219         struct brw_page pga;
220         struct obdo oa;
221         struct ost_lvb lvb;
222         int rc = 0;
223         ENTRY;
224
225         LASSERT(PageLocked(page));
226         (void)llap_cast_private(page); /* assertion */
227
228         /* Check to see if we should return -EIO right away */
229         pga.pg = page;
230         pga.off = offset;
231         pga.count = CFS_PAGE_SIZE;
232         pga.flag = 0;
233
234         oa.o_mode = inode->i_mode;
235         oa.o_id = lsm->lsm_object_id;
236         oa.o_gr = lsm->lsm_object_gr;
237         oa.o_valid = OBD_MD_FLID | OBD_MD_FLMODE | 
238                      OBD_MD_FLTYPE | OBD_MD_FLGROUP;
239         obdo_from_inode(&oa, inode, OBD_MD_FLFID | OBD_MD_FLGENER);
240
241         oinfo.oi_oa = &oa;
242         oinfo.oi_md = lsm;
243         rc = obd_brw(OBD_BRW_CHECK, ll_i2dtexp(inode), &oinfo, 1, &pga, NULL);
244         if (rc)
245                 RETURN(rc);
246
247         if (PageUptodate(page)) {
248                 LL_CDEBUG_PAGE(D_PAGE, page, "uptodate\n");
249                 RETURN(0);
250         }
251
252         /* We're completely overwriting an existing page, so _don't_ set it up
253          * to date until commit_write */
254         if (from == 0 && to == CFS_PAGE_SIZE) {
255                 LL_CDEBUG_PAGE(D_PAGE, page, "full page write\n");
256                 POISON_PAGE(page, 0x11);
257                 RETURN(0);
258         }
259
260         /* If are writing to a new page, no need to read old data.  The extent
261          * locking will have updated the KMS, and for our purposes here we can
262          * treat it like i_size. */
263         lov_stripe_lock(lsm);
264         inode_init_lvb(inode, &lvb);
265         obd_merge_lvb(ll_i2dtexp(inode), lsm, &lvb, 1);
266         lov_stripe_unlock(lsm);
267         if (lvb.lvb_size <= offset) {
268                 LL_CDEBUG_PAGE(D_PAGE, page, "kms "LPU64" <= offset "LPU64"\n",
269                                lvb.lvb_size, offset);
270                 memset(kmap(page), 0, CFS_PAGE_SIZE);
271                 kunmap(page);
272                 GOTO(prepare_done, rc = 0);
273         }
274
275         /* XXX could be an async ocp read.. read-ahead? */
276         rc = ll_brw(OBD_BRW_READ, inode, &oa, page, 0);
277         if (rc == 0) {
278                 /* bug 1598: don't clobber blksize */
279                 oa.o_valid &= ~(OBD_MD_FLSIZE | OBD_MD_FLBLKSZ);
280                 obdo_refresh_inode(inode, &oa, oa.o_valid);
281         }
282
283         EXIT;
284  prepare_done:
285         if (rc == 0)
286                 SetPageUptodate(page);
287
288         return rc;
289 }
290
291 static int ll_ap_make_ready(void *data, int cmd)
292 {
293         struct ll_async_page *llap;
294         struct page *page;
295         ENTRY;
296
297         llap = LLAP_FROM_COOKIE(data);
298         page = llap->llap_page;
299
300         LASSERTF(!(cmd & OBD_BRW_READ), "cmd %x page %p ino %lu index %lu\n", cmd, page,
301                  page->mapping->host->i_ino, page->index);
302
303         /* we're trying to write, but the page is locked.. come back later */
304         if (TryLockPage(page))
305                 RETURN(-EAGAIN);
306
307         LASSERT(!PageWriteback(page));
308
309         /* if we left PageDirty we might get another writepage call
310          * in the future.  list walkers are bright enough
311          * to check page dirty so we can leave it on whatever list
312          * its on.  XXX also, we're called with the cli list so if
313          * we got the page cache list we'd create a lock inversion
314          * with the removepage path which gets the page lock then the
315          * cli lock */
316 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,0)
317         clear_page_dirty(page);
318 #else
319         LASSERTF(!PageWriteback(page),"cmd %x page %p ino %lu index %lu\n", cmd, page,
320                  page->mapping->host->i_ino, page->index);
321         clear_page_dirty_for_io(page);
322
323         /* This actually clears the dirty bit in the radix tree.*/
324         set_page_writeback(page);
325 #endif
326
327         LL_CDEBUG_PAGE(D_PAGE, page, "made ready\n");
328         page_cache_get(page);
329
330         RETURN(0);
331 }
332
333 /* We have two reasons for giving llite the opportunity to change the
334  * write length of a given queued page as it builds the RPC containing
335  * the page:
336  *
337  * 1) Further extending writes may have landed in the page cache
338  *    since a partial write first queued this page requiring us
339  *    to write more from the page cache.  (No further races are possible, since
340  *    by the time this is called, the page is locked.)
341  * 2) We might have raced with truncate and want to avoid performing
342  *    write RPCs that are just going to be thrown away by the
343  *    truncate's punch on the storage targets.
344  *
345  * The kms serves these purposes as it is set at both truncate and extending
346  * writes.
347  */
348 static int ll_ap_refresh_count(void *data, int cmd)
349 {
350         struct ll_inode_info *lli;
351         struct ll_async_page *llap;
352         struct lov_stripe_md *lsm;
353         struct page *page;
354         struct inode *inode;
355         struct ost_lvb lvb;
356         __u64 kms;
357         ENTRY;
358
359         /* readpage queues with _COUNT_STABLE, shouldn't get here. */
360         LASSERT(cmd != OBD_BRW_READ);
361
362         llap = LLAP_FROM_COOKIE(data);
363         page = llap->llap_page;
364         inode = page->mapping->host;
365         lli = ll_i2info(inode);
366         lsm = lli->lli_smd;
367
368         lov_stripe_lock(lsm);
369         inode_init_lvb(inode, &lvb);
370         obd_merge_lvb(ll_i2dtexp(inode), lsm, &lvb, 1);
371         kms = lvb.lvb_size;
372         lov_stripe_unlock(lsm);
373
374         /* catch race with truncate */
375         if (((__u64)page->index << CFS_PAGE_SHIFT) >= kms)
376                 return 0;
377
378         /* catch sub-page write at end of file */
379         if (((__u64)page->index << CFS_PAGE_SHIFT) + CFS_PAGE_SIZE > kms)
380                 return kms % CFS_PAGE_SIZE;
381
382         return CFS_PAGE_SIZE;
383 }
384
385 void ll_inode_fill_obdo(struct inode *inode, int cmd, struct obdo *oa)
386 {
387         struct lov_stripe_md *lsm;
388         obd_flag valid_flags;
389
390         lsm = ll_i2info(inode)->lli_smd;
391
392         oa->o_id = lsm->lsm_object_id;
393         oa->o_gr = lsm->lsm_object_gr;
394         oa->o_valid = OBD_MD_FLID | OBD_MD_FLGROUP;
395         valid_flags = OBD_MD_FLTYPE | OBD_MD_FLATIME;
396         if (cmd & OBD_BRW_WRITE) {
397                 oa->o_valid |= OBD_MD_FLEPOCH;
398                 oa->o_easize = ll_i2info(inode)->lli_ioepoch;
399
400                 valid_flags |= OBD_MD_FLMTIME | OBD_MD_FLCTIME |
401                         OBD_MD_FLUID | OBD_MD_FLGID |
402                         OBD_MD_FLFID | OBD_MD_FLGENER;
403         }
404
405         obdo_from_inode(oa, inode, valid_flags);
406 }
407
408 static void ll_ap_fill_obdo(void *data, int cmd, struct obdo *oa)
409 {
410         struct ll_async_page *llap;
411         ENTRY;
412
413         llap = LLAP_FROM_COOKIE(data);
414         ll_inode_fill_obdo(llap->llap_page->mapping->host, cmd, oa);
415
416         EXIT;
417 }
418
419 static void ll_ap_update_obdo(void *data, int cmd, struct obdo *oa,
420                               obd_valid valid)
421 {
422         struct ll_async_page *llap;
423         ENTRY;
424
425         llap = LLAP_FROM_COOKIE(data);
426         obdo_from_inode(oa, llap->llap_page->mapping->host, valid);
427
428         EXIT;
429 }
430
431 static struct obd_capa *ll_ap_lookup_capa(void *data, int cmd)
432 {
433         struct ll_async_page *llap = LLAP_FROM_COOKIE(data);
434         int opc = cmd & OBD_BRW_WRITE ? CAPA_OPC_OSS_WRITE : CAPA_OPC_OSS_RW;
435
436         return ll_osscapa_get(llap->llap_page->mapping->host, opc);
437 }
438
439 static struct obd_async_page_ops ll_async_page_ops = {
440         .ap_make_ready =        ll_ap_make_ready,
441         .ap_refresh_count =     ll_ap_refresh_count,
442         .ap_fill_obdo =         ll_ap_fill_obdo,
443         .ap_update_obdo =       ll_ap_update_obdo,
444         .ap_completion =        ll_ap_completion,
445         .ap_lookup_capa =       ll_ap_lookup_capa,
446 };
447
448 struct ll_async_page *llap_cast_private(struct page *page)
449 {
450         struct ll_async_page *llap = (struct ll_async_page *)page_private(page);
451
452         LASSERTF(llap == NULL || llap->llap_magic == LLAP_MAGIC,
453                  "page %p private %lu gave magic %d which != %d\n",
454                  page, page_private(page), llap->llap_magic, LLAP_MAGIC);
455
456         return llap;
457 }
458
459 /* Try to shrink the page cache for the @sbi filesystem by 1/@shrink_fraction.
460  *
461  * There is an llap attached onto every page in lustre, linked off @sbi.
462  * We add an llap to the list so we don't lose our place during list walking.
463  * If llaps in the list are being moved they will only move to the end
464  * of the LRU, and we aren't terribly interested in those pages here (we
465  * start at the beginning of the list where the least-used llaps are.
466  */
467 int llap_shrink_cache(struct ll_sb_info *sbi, int shrink_fraction)
468 {
469         struct ll_async_page *llap, dummy_llap = { .llap_magic = 0xd11ad11a };
470         unsigned long total, want, count = 0;
471
472         total = sbi->ll_async_page_count;
473
474         /* There can be a large number of llaps (600k or more in a large
475          * memory machine) so the VM 1/6 shrink ratio is likely too much.
476          * Since we are freeing pages also, we don't necessarily want to
477          * shrink so much.  Limit to 40MB of pages + llaps per call. */
478         if (shrink_fraction == 0)
479                 want = sbi->ll_async_page_count - sbi->ll_async_page_max + 32;
480         else
481                 want = (total + shrink_fraction - 1) / shrink_fraction;
482
483         if (want > 40 << (20 - CFS_PAGE_SHIFT))
484                 want = 40 << (20 - CFS_PAGE_SHIFT);
485
486         CDEBUG(D_CACHE, "shrinking %lu of %lu pages (1/%d)\n",
487                want, total, shrink_fraction);
488
489         spin_lock(&sbi->ll_lock);
490         list_add(&dummy_llap.llap_pglist_item, &sbi->ll_pglist);
491
492         while (--total >= 0 && count < want) {
493                 struct page *page;
494                 int keep;
495
496                 if (unlikely(need_resched())) {
497                         spin_unlock(&sbi->ll_lock);
498                         cond_resched();
499                         spin_lock(&sbi->ll_lock);
500                 }
501
502                 llap = llite_pglist_next_llap(sbi,&dummy_llap.llap_pglist_item);
503                 list_del_init(&dummy_llap.llap_pglist_item);
504                 if (llap == NULL)
505                         break;
506
507                 page = llap->llap_page;
508                 LASSERT(page != NULL);
509
510                 list_add(&dummy_llap.llap_pglist_item, &llap->llap_pglist_item);
511
512                 /* Page needs/undergoing IO */
513                 if (TryLockPage(page)) {
514                         LL_CDEBUG_PAGE(D_PAGE, page, "can't lock\n");
515                         continue;
516                 }
517
518                keep = (llap->llap_write_queued || PageDirty(page) ||
519                       PageWriteback(page) || (!PageUptodate(page) &&
520                       llap->llap_origin != LLAP_ORIGIN_READAHEAD));
521
522                 LL_CDEBUG_PAGE(D_PAGE, page,"%s LRU page: %s%s%s%s%s origin %s\n",
523                                keep ? "keep" : "drop",
524                                llap->llap_write_queued ? "wq " : "",
525                                PageDirty(page) ? "pd " : "",
526                                PageUptodate(page) ? "" : "!pu ",
527                                PageWriteback(page) ? "wb" : "",
528                                llap->llap_defer_uptodate ? "" : "!du",
529                                llap_origins[llap->llap_origin]);
530
531                 /* If page is dirty or undergoing IO don't discard it */
532                 if (keep) {
533                         unlock_page(page);
534                         continue;
535                 }
536
537                 page_cache_get(page);
538                 spin_unlock(&sbi->ll_lock);
539
540                 if (page->mapping != NULL) {
541                         ll_teardown_mmaps(page->mapping,
542                                          (__u64)page->index << CFS_PAGE_SHIFT,
543                                          ((__u64)page->index << CFS_PAGE_SHIFT)|
544                                           ~CFS_PAGE_MASK);
545                         if (!PageDirty(page) && !page_mapped(page)) {
546                                 ll_ra_accounting(llap, page->mapping);
547                                 ll_truncate_complete_page(page);
548                                 ++count;
549                         } else {
550                                 LL_CDEBUG_PAGE(D_PAGE, page, "Not dropping page"
551                                                              " because it is "
552                                                              "%s\n",
553                                                               PageDirty(page)?
554                                                               "dirty":"mapped");
555                         }
556                 }
557                 unlock_page(page);
558                 page_cache_release(page);
559
560                 spin_lock(&sbi->ll_lock);
561         }
562         list_del(&dummy_llap.llap_pglist_item);
563         spin_unlock(&sbi->ll_lock);
564
565         CDEBUG(D_CACHE, "shrank %lu/%lu and left %lu unscanned\n",
566                count, want, total);
567
568         return count;
569 }
570
571 struct ll_async_page *llap_from_page(struct page *page, unsigned origin)
572 {
573         struct ll_async_page *llap;
574         struct obd_export *exp;
575         struct inode *inode = page->mapping->host;
576         struct ll_sb_info *sbi;
577         int rc;
578         ENTRY;
579
580         if (!inode) {
581                 static int triggered;
582
583                 if (!triggered) {
584                         LL_CDEBUG_PAGE(D_ERROR, page, "Bug 10047. Wrong anon "
585                                        "page received\n");
586                         libcfs_debug_dumpstack(NULL);
587                         triggered = 1;
588                 }
589                 RETURN(ERR_PTR(-EINVAL));
590         }
591         sbi = ll_i2sbi(inode);
592         LASSERT(ll_async_page_slab);
593         LASSERTF(origin < LLAP__ORIGIN_MAX, "%u\n", origin);
594
595         llap = llap_cast_private(page);
596         if (llap != NULL) {
597                 /* move to end of LRU list, except when page is just about to
598                  * die */
599                 if (origin != LLAP_ORIGIN_REMOVEPAGE) {
600                         spin_lock(&sbi->ll_lock);
601                         sbi->ll_pglist_gen++;
602                         list_del_init(&llap->llap_pglist_item);
603                         list_add_tail(&llap->llap_pglist_item, &sbi->ll_pglist);
604                         spin_unlock(&sbi->ll_lock);
605                 }
606                 GOTO(out, llap);
607         }
608
609         exp = ll_i2dtexp(page->mapping->host);
610         if (exp == NULL)
611                 RETURN(ERR_PTR(-EINVAL));
612
613         /* limit the number of lustre-cached pages */
614         if (sbi->ll_async_page_count >= sbi->ll_async_page_max)
615                 llap_shrink_cache(sbi, 0);
616
617         OBD_SLAB_ALLOC(llap, ll_async_page_slab, CFS_ALLOC_STD,
618                        ll_async_page_slab_size);
619         if (llap == NULL)
620                 RETURN(ERR_PTR(-ENOMEM));
621         llap->llap_magic = LLAP_MAGIC;
622         llap->llap_cookie = (void *)llap + size_round(sizeof(*llap));
623
624         rc = obd_prep_async_page(exp, ll_i2info(inode)->lli_smd, NULL, page,
625                                  (obd_off)page->index << CFS_PAGE_SHIFT,
626                                  &ll_async_page_ops, llap, &llap->llap_cookie);
627         if (rc) {
628                 OBD_SLAB_FREE(llap, ll_async_page_slab,
629                               ll_async_page_slab_size);
630                 RETURN(ERR_PTR(rc));
631         }
632
633         CDEBUG(D_CACHE, "llap %p page %p cookie %p obj off "LPU64"\n", llap,
634                page, llap->llap_cookie, (obd_off)page->index << CFS_PAGE_SHIFT);
635         /* also zeroing the PRIVBITS low order bitflags */
636         __set_page_ll_data(page, llap);
637         llap->llap_page = page;
638         spin_lock(&sbi->ll_lock);
639         sbi->ll_pglist_gen++;
640         sbi->ll_async_page_count++;
641         list_add_tail(&llap->llap_pglist_item, &sbi->ll_pglist);
642         INIT_LIST_HEAD(&llap->llap_pending_write);
643         spin_unlock(&sbi->ll_lock);
644
645  out:
646         if (unlikely(sbi->ll_flags & LL_SBI_CHECKSUM)) {
647                 __u32 csum = 0;
648                 csum = crc32_le(csum, kmap(page), CFS_PAGE_SIZE);
649                 kunmap(page);
650                 if (origin == LLAP_ORIGIN_READAHEAD ||
651                     origin == LLAP_ORIGIN_READPAGE) {
652                         llap->llap_checksum = 0;
653                 } else if (origin == LLAP_ORIGIN_COMMIT_WRITE ||
654                            llap->llap_checksum == 0) {
655                         llap->llap_checksum = csum;
656                         CDEBUG(D_PAGE, "page %p cksum %x\n", page, csum);
657                 } else if (llap->llap_checksum == csum) {
658                         /* origin == LLAP_ORIGIN_WRITEPAGE */
659                         CDEBUG(D_PAGE, "page %p cksum %x confirmed\n",
660                                page, csum);
661                 } else {
662                         /* origin == LLAP_ORIGIN_WRITEPAGE */
663                         LL_CDEBUG_PAGE(D_ERROR, page, "old cksum %x != new "
664                                        "%x!\n", llap->llap_checksum, csum);
665                 }
666         }
667
668         llap->llap_origin = origin;
669         RETURN(llap);
670 }
671
672 static int queue_or_sync_write(struct obd_export *exp, struct inode *inode,
673                                struct ll_async_page *llap,
674                                unsigned to, obd_flag async_flags)
675 {
676         unsigned long size_index = i_size_read(inode) >> CFS_PAGE_SHIFT;
677         struct obd_io_group *oig;
678         struct ll_sb_info *sbi = ll_i2sbi(inode);
679         int rc, noquot = llap->llap_ignore_quota ? OBD_BRW_NOQUOTA : 0;
680         ENTRY;
681
682         /* _make_ready only sees llap once we've unlocked the page */
683         llap->llap_write_queued = 1;
684         rc = obd_queue_async_io(exp, ll_i2info(inode)->lli_smd, NULL,
685                                 llap->llap_cookie, OBD_BRW_WRITE | noquot,
686                                 0, 0, 0, async_flags);
687         if (rc == 0) {
688                 LL_CDEBUG_PAGE(D_PAGE, llap->llap_page, "write queued\n");
689                 GOTO(out, 0);
690         }
691
692         llap->llap_write_queued = 0;
693         /* Do not pass llap here as it is sync write. */
694         llap_write_pending(inode, NULL);
695         
696         rc = oig_init(&oig);
697         if (rc)
698                 GOTO(out, rc);
699
700         /* make full-page requests if we are not at EOF (bug 4410) */
701         if (to != CFS_PAGE_SIZE && llap->llap_page->index < size_index) {
702                 LL_CDEBUG_PAGE(D_PAGE, llap->llap_page,
703                                "sync write before EOF: size_index %lu, to %d\n",
704                                size_index, to);
705                 to = CFS_PAGE_SIZE;
706         } else if (to != CFS_PAGE_SIZE && llap->llap_page->index == size_index) {
707                 int size_to = i_size_read(inode) & ~CFS_PAGE_MASK;
708                 LL_CDEBUG_PAGE(D_PAGE, llap->llap_page,
709                                "sync write at EOF: size_index %lu, to %d/%d\n",
710                                size_index, to, size_to);
711                 if (to < size_to)
712                         to = size_to;
713         }
714
715         /* compare the checksum once before the page leaves llite */
716         if (unlikely((sbi->ll_flags & LL_SBI_CHECKSUM) &&
717                      llap->llap_checksum != 0)) {
718                 __u32 csum = 0;
719                 struct page *page = llap->llap_page;
720                 csum = crc32_le(csum, kmap(page), CFS_PAGE_SIZE);
721                 kunmap(page);
722                 if (llap->llap_checksum == csum) {
723                         CDEBUG(D_PAGE, "page %p cksum %x confirmed\n",
724                                page, csum);
725                 } else {
726                         CERROR("page %p old cksum %x != new cksum %x!\n",
727                                page, llap->llap_checksum, csum);
728                 }
729         }
730
731         rc = obd_queue_group_io(exp, ll_i2info(inode)->lli_smd, NULL, oig,
732                                 llap->llap_cookie, OBD_BRW_WRITE | noquot,
733                                 0, to, 0, ASYNC_READY | ASYNC_URGENT |
734                                 ASYNC_COUNT_STABLE | ASYNC_GROUP_SYNC);
735         if (rc)
736                 GOTO(free_oig, rc);
737
738         rc = obd_trigger_group_io(exp, ll_i2info(inode)->lli_smd, NULL, oig);
739         if (rc)
740                 GOTO(free_oig, rc);
741
742         rc = oig_wait(oig);
743
744         if (!rc && async_flags & ASYNC_READY) {
745                 unlock_page(llap->llap_page);
746                 if (PageWriteback(llap->llap_page)) {
747                         end_page_writeback(llap->llap_page);
748                 }
749         }
750
751         if (rc == 0 && llap_write_complete(inode, llap))
752                 ll_queue_done_writing(inode, 0);
753
754         LL_CDEBUG_PAGE(D_PAGE, llap->llap_page, "sync write returned %d\n", rc);
755
756 free_oig:
757         oig_release(oig);
758 out:
759         RETURN(rc);
760 }
761
762 /* update our write count to account for i_size increases that may have
763  * happened since we've queued the page for io. */
764
765 /* be careful not to return success without setting the page Uptodate or
766  * the next pass through prepare_write will read in stale data from disk. */
767 int ll_commit_write(struct file *file, struct page *page, unsigned from,
768                     unsigned to)
769 {
770         struct inode *inode = page->mapping->host;
771         struct ll_inode_info *lli = ll_i2info(inode);
772         struct lov_stripe_md *lsm = lli->lli_smd;
773         struct obd_export *exp;
774         struct ll_async_page *llap;
775         loff_t size;
776         int rc = 0;
777         ENTRY;
778
779         SIGNAL_MASK_ASSERT(); /* XXX BUG 1511 */
780         LASSERT(inode == file->f_dentry->d_inode);
781         LASSERT(PageLocked(page));
782
783         CDEBUG(D_INODE, "inode %p is writing page %p from %d to %d at %lu\n",
784                inode, page, from, to, page->index);
785
786         llap = llap_from_page(page, LLAP_ORIGIN_COMMIT_WRITE);
787         if (IS_ERR(llap))
788                 RETURN(PTR_ERR(llap));
789
790         exp = ll_i2dtexp(inode);
791         if (exp == NULL)
792                 RETURN(-EINVAL);
793
794         llap->llap_ignore_quota = capable(CAP_SYS_RESOURCE);
795
796         /*
797          * queue a write for some time in the future the first time we
798          * dirty the page.
799          *
800          * This is different from what other file systems do: they usually
801          * just mark page (and some of its buffers) dirty and rely on
802          * balance_dirty_pages() to start a write-back. Lustre wants write-back
803          * to be started earlier for the following reasons:
804          *
805          *     (1) with a large number of clients we need to limit the amount
806          *     of cached data on the clients a lot;
807          *
808          *     (2) large compute jobs generally want compute-only then io-only
809          *     and the IO should complete as quickly as possible;
810          *
811          *     (3) IO is batched up to the RPC size and is async until the
812          *     client max cache is hit
813          *     (/proc/fs/lustre/osc/OSC.../max_dirty_mb)
814          *
815          */
816         if (!PageDirty(page)) {
817                 ll_stats_ops_tally(ll_i2sbi(inode), LPROC_LL_DIRTY_MISSES, 1);
818
819                 rc = queue_or_sync_write(exp, inode, llap, to, 0);
820                 if (rc)
821                         GOTO(out, rc);
822         } else {
823                 ll_stats_ops_tally(ll_i2sbi(inode), LPROC_LL_DIRTY_HITS, 1);
824         }
825
826         /* put the page in the page cache, from now on ll_removepage is
827          * responsible for cleaning up the llap.
828          * only set page dirty when it's queued to be write out */
829         if (llap->llap_write_queued)
830                 set_page_dirty(page);
831
832 out:
833         size = (((obd_off)page->index) << CFS_PAGE_SHIFT) + to;
834         ll_inode_size_lock(inode, 0);
835         if (rc == 0) {
836                 lov_stripe_lock(lsm);
837                 obd_adjust_kms(exp, lsm, size, 0);
838                 lov_stripe_unlock(lsm);
839                 if (size > i_size_read(inode))
840                         i_size_write(inode, size);
841                 SetPageUptodate(page);
842         } else if (size > i_size_read(inode)) {
843                 /* this page beyond the pales of i_size, so it can't be
844                  * truncated in ll_p_r_e during lock revoking. we must
845                  * teardown our book-keeping here. */
846                 ll_removepage(page);
847         }
848         ll_inode_size_unlock(inode, 0);
849         RETURN(rc);
850 }
851
852 static unsigned long ll_ra_count_get(struct ll_sb_info *sbi, unsigned long len)
853 {
854         struct ll_ra_info *ra = &sbi->ll_ra_info;
855         unsigned long ret;
856         ENTRY;
857
858         spin_lock(&sbi->ll_lock);
859         ret = min(ra->ra_max_pages - ra->ra_cur_pages, len);
860         ra->ra_cur_pages += ret;
861         spin_unlock(&sbi->ll_lock);
862
863         RETURN(ret);
864 }
865
866 static void ll_ra_count_put(struct ll_sb_info *sbi, unsigned long len)
867 {
868         struct ll_ra_info *ra = &sbi->ll_ra_info;
869         spin_lock(&sbi->ll_lock);
870         LASSERTF(ra->ra_cur_pages >= len, "r_c_p %lu len %lu\n",
871                  ra->ra_cur_pages, len);
872         ra->ra_cur_pages -= len;
873         spin_unlock(&sbi->ll_lock);
874 }
875
876 /* called for each page in a completed rpc.*/
877 int ll_ap_completion(void *data, int cmd, struct obdo *oa, int rc)
878 {
879         struct ll_async_page *llap;
880         struct page *page;
881         int ret = 0;
882         ENTRY;
883
884         llap = LLAP_FROM_COOKIE(data);
885         page = llap->llap_page;
886         LASSERT(PageLocked(page));
887         LASSERT(CheckWriteback(page,cmd));
888         
889         LL_CDEBUG_PAGE(D_PAGE, page, "completing cmd %d with %d\n", cmd, rc);
890
891         if (cmd & OBD_BRW_READ && llap->llap_defer_uptodate)
892                 ll_ra_count_put(ll_i2sbi(page->mapping->host), 1);
893
894         if (rc == 0)  {
895                 if (cmd & OBD_BRW_READ) {
896                         if (!llap->llap_defer_uptodate)
897                                 SetPageUptodate(page);
898                 } else {
899                         llap->llap_write_queued = 0;
900                 }
901                 ClearPageError(page);
902         } else {
903                 if (cmd & OBD_BRW_READ) {
904                         llap->llap_defer_uptodate = 0;
905                 }
906                 SetPageError(page);
907 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
908                 if (rc == -ENOSPC)
909                         set_bit(AS_ENOSPC, &page->mapping->flags);
910                 else
911                         set_bit(AS_EIO, &page->mapping->flags);
912 #else
913                 page->mapping->gfp_mask |= AS_EIO_MASK;
914 #endif
915         }
916
917         unlock_page(page);
918
919         if (cmd & OBD_BRW_WRITE) {
920                 /* Only rc == 0, write succeed, then this page could be deleted
921                  * from the pending_writing list 
922                  */
923                 if (rc == 0 && llap_write_complete(page->mapping->host, llap))
924                         ll_queue_done_writing(page->mapping->host, 0);
925         }
926
927         if (PageWriteback(page)) {
928                 end_page_writeback(page);
929         }
930         page_cache_release(page);
931
932         RETURN(ret);
933 }
934
935 /* the kernel calls us here when a page is unhashed from the page cache.
936  * the page will be locked and the kernel is holding a spinlock, so
937  * we need to be careful.  we're just tearing down our book-keeping
938  * here. */
939 void ll_removepage(struct page *page)
940 {
941         struct inode *inode = page->mapping->host;
942         struct obd_export *exp;
943         struct ll_async_page *llap;
944         struct ll_sb_info *sbi = ll_i2sbi(inode);
945         int rc;
946         ENTRY;
947
948         LASSERT(!in_interrupt());
949
950         /* sync pages or failed read pages can leave pages in the page
951          * cache that don't have our data associated with them anymore */
952         if (page_private(page) == 0) {
953                 EXIT;
954                 return;
955         }
956
957         LL_CDEBUG_PAGE(D_PAGE, page, "being evicted\n");
958
959         exp = ll_i2dtexp(inode);
960         if (exp == NULL) {
961                 CERROR("page %p ind %lu gave null export\n", page, page->index);
962                 EXIT;
963                 return;
964         }
965
966         llap = llap_from_page(page, LLAP_ORIGIN_REMOVEPAGE);
967         if (IS_ERR(llap)) {
968                 CERROR("page %p ind %lu couldn't find llap: %ld\n", page,
969                        page->index, PTR_ERR(llap));
970                 EXIT;
971                 return;
972         }
973
974         if (llap_write_complete(inode, llap))
975                 ll_queue_done_writing(inode, 0);
976
977         rc = obd_teardown_async_page(exp, ll_i2info(inode)->lli_smd, NULL,
978                                      llap->llap_cookie);
979         if (rc != 0)
980                 CERROR("page %p ind %lu failed: %d\n", page, page->index, rc);
981
982         /* this unconditional free is only safe because the page lock
983          * is providing exclusivity to memory pressure/truncate/writeback..*/
984         __clear_page_ll_data(page);
985
986         spin_lock(&sbi->ll_lock);
987         if (!list_empty(&llap->llap_pglist_item))
988                 list_del_init(&llap->llap_pglist_item);
989         sbi->ll_pglist_gen++;
990         sbi->ll_async_page_count--;
991         spin_unlock(&sbi->ll_lock);
992         OBD_SLAB_FREE(llap, ll_async_page_slab, ll_async_page_slab_size);
993         EXIT;
994 }
995
996 static int ll_page_matches(struct page *page, int fd_flags)
997 {
998         struct lustre_handle match_lockh = {0};
999         struct inode *inode = page->mapping->host;
1000         ldlm_policy_data_t page_extent;
1001         int flags, matches;
1002         ENTRY;
1003
1004         if (unlikely(fd_flags & LL_FILE_GROUP_LOCKED))
1005                 RETURN(1);
1006
1007         page_extent.l_extent.start = (__u64)page->index << CFS_PAGE_SHIFT;
1008         page_extent.l_extent.end =
1009                 page_extent.l_extent.start + CFS_PAGE_SIZE - 1;
1010         flags = LDLM_FL_TEST_LOCK | LDLM_FL_BLOCK_GRANTED;
1011         if (!(fd_flags & LL_FILE_READAHEAD))
1012                 flags |= LDLM_FL_CBPENDING;
1013         matches = obd_match(ll_i2sbi(inode)->ll_dt_exp,
1014                             ll_i2info(inode)->lli_smd, LDLM_EXTENT,
1015                             &page_extent, LCK_PR | LCK_PW, &flags, inode,
1016                             &match_lockh);
1017         RETURN(matches);
1018 }
1019
1020 static int ll_issue_page_read(struct obd_export *exp,
1021                               struct ll_async_page *llap,
1022                               struct obd_io_group *oig, int defer)
1023 {
1024         struct page *page = llap->llap_page;
1025         int rc;
1026
1027         page_cache_get(page);
1028         llap->llap_defer_uptodate = defer;
1029         llap->llap_ra_used = 0;
1030         rc = obd_queue_group_io(exp, ll_i2info(page->mapping->host)->lli_smd,
1031                                 NULL, oig, llap->llap_cookie, OBD_BRW_READ, 0,
1032                                 CFS_PAGE_SIZE, 0, ASYNC_COUNT_STABLE |
1033                                                   ASYNC_READY | ASYNC_URGENT);
1034         if (rc) {
1035                 LL_CDEBUG_PAGE(D_ERROR, page, "read queue failed: rc %d\n", rc);
1036                 page_cache_release(page);
1037         }
1038         RETURN(rc);
1039 }
1040
1041 static void ll_ra_stats_inc_unlocked(struct ll_ra_info *ra, enum ra_stat which)
1042 {
1043         LASSERTF(which >= 0 && which < _NR_RA_STAT, "which: %u\n", which);
1044         ra->ra_stats[which]++;
1045 }
1046
1047 static void ll_ra_stats_inc(struct address_space *mapping, enum ra_stat which)
1048 {
1049         struct ll_sb_info *sbi = ll_i2sbi(mapping->host);
1050         struct ll_ra_info *ra = &ll_i2sbi(mapping->host)->ll_ra_info;
1051
1052         spin_lock(&sbi->ll_lock);
1053         ll_ra_stats_inc_unlocked(ra, which);
1054         spin_unlock(&sbi->ll_lock);
1055 }
1056
1057 void ll_ra_accounting(struct ll_async_page *llap, struct address_space *mapping)
1058 {
1059         if (!llap->llap_defer_uptodate || llap->llap_ra_used)
1060                 return;
1061
1062         ll_ra_stats_inc(mapping, RA_STAT_DISCARDED);
1063 }
1064
1065 #define RAS_CDEBUG(ras) \
1066         CDEBUG(D_READA,                                                      \
1067                "lrp %lu cr %lu cp %lu ws %lu wl %lu nra %lu r %lu ri %lu\n", \
1068                ras->ras_last_readpage, ras->ras_consecutive_requests,        \
1069                ras->ras_consecutive_pages, ras->ras_window_start,            \
1070                ras->ras_window_len, ras->ras_next_readahead,                 \
1071                ras->ras_requests, ras->ras_request_index);
1072
1073 static int index_in_window(unsigned long index, unsigned long point,
1074                            unsigned long before, unsigned long after)
1075 {
1076         unsigned long start = point - before, end = point + after;
1077
1078         if (start > point)
1079                start = 0;
1080         if (end < point)
1081                end = ~0;
1082
1083         return start <= index && index <= end;
1084 }
1085
1086 static struct ll_readahead_state *ll_ras_get(struct file *f)
1087 {
1088         struct ll_file_data       *fd;
1089
1090         fd = LUSTRE_FPRIVATE(f);
1091         return &fd->fd_ras;
1092 }
1093
1094 void ll_ra_read_in(struct file *f, struct ll_ra_read *rar)
1095 {
1096         struct ll_readahead_state *ras;
1097
1098         ras = ll_ras_get(f);
1099
1100         spin_lock(&ras->ras_lock);
1101         ras->ras_requests++;
1102         ras->ras_request_index = 0;
1103         ras->ras_consecutive_requests++;
1104         rar->lrr_reader = current;
1105
1106         list_add(&rar->lrr_linkage, &ras->ras_read_beads);
1107         spin_unlock(&ras->ras_lock);
1108 }
1109
1110 void ll_ra_read_ex(struct file *f, struct ll_ra_read *rar)
1111 {
1112         struct ll_readahead_state *ras;
1113
1114         ras = ll_ras_get(f);
1115
1116         spin_lock(&ras->ras_lock);
1117         list_del_init(&rar->lrr_linkage);
1118         spin_unlock(&ras->ras_lock);
1119 }
1120
1121 static struct ll_ra_read *ll_ra_read_get_locked(struct ll_readahead_state *ras)
1122 {
1123         struct ll_ra_read *scan;
1124
1125         list_for_each_entry(scan, &ras->ras_read_beads, lrr_linkage) {
1126                 if (scan->lrr_reader == current)
1127                         return scan;
1128         }
1129         return NULL;
1130 }
1131
1132 struct ll_ra_read *ll_ra_read_get(struct file *f)
1133 {
1134         struct ll_readahead_state *ras;
1135         struct ll_ra_read         *bead;
1136
1137         ras = ll_ras_get(f);
1138
1139         spin_lock(&ras->ras_lock);
1140         bead = ll_ra_read_get_locked(ras);
1141         spin_unlock(&ras->ras_lock);
1142         return bead;
1143 }
1144
1145 static int ll_readahead(struct ll_readahead_state *ras,
1146                          struct obd_export *exp, struct address_space *mapping,
1147                          struct obd_io_group *oig, int flags)
1148 {
1149         unsigned long i, start = 0, end = 0, reserved;
1150         struct ll_async_page *llap;
1151         struct page *page;
1152         int rc, ret = 0, match_failed = 0;
1153         __u64 kms;
1154         unsigned int gfp_mask;
1155         struct inode *inode;
1156         struct lov_stripe_md *lsm;
1157         struct ll_ra_read *bead;
1158         struct ost_lvb lvb;
1159         ENTRY;
1160
1161         inode = mapping->host;
1162         lsm = ll_i2info(inode)->lli_smd;
1163
1164         lov_stripe_lock(lsm);
1165         inode_init_lvb(inode, &lvb);
1166         obd_merge_lvb(ll_i2dtexp(inode), lsm, &lvb, 1);
1167         kms = lvb.lvb_size;
1168         lov_stripe_unlock(lsm);
1169         if (kms == 0) {
1170                 ll_ra_stats_inc(mapping, RA_STAT_ZERO_LEN);
1171                 RETURN(0);
1172         }
1173
1174         spin_lock(&ras->ras_lock);
1175         bead = ll_ra_read_get_locked(ras);
1176         /* Enlarge the RA window to encompass the full read */
1177         if (bead != NULL && ras->ras_window_start + ras->ras_window_len <
1178             bead->lrr_start + bead->lrr_count) {
1179                 ras->ras_window_len = bead->lrr_start + bead->lrr_count -
1180                                       ras->ras_window_start;
1181         }
1182         /* Reserve a part of the read-ahead window that we'll be issuing */
1183         if (ras->ras_window_len) {
1184                 start = ras->ras_next_readahead;
1185                 end = ras->ras_window_start + ras->ras_window_len - 1;
1186         }
1187         if (end != 0) {
1188                 /* Truncate RA window to end of file */
1189                 end = min(end, (unsigned long)((kms - 1) >> CFS_PAGE_SHIFT));
1190                 ras->ras_next_readahead = max(end, end + 1);
1191                 RAS_CDEBUG(ras);
1192         }
1193         spin_unlock(&ras->ras_lock);
1194
1195         if (end == 0) {
1196                 ll_ra_stats_inc(mapping, RA_STAT_ZERO_WINDOW);
1197                 RETURN(0);
1198         }
1199
1200         reserved = ll_ra_count_get(ll_i2sbi(inode), end - start + 1);
1201         if (reserved < end - start + 1)
1202                 ll_ra_stats_inc(mapping, RA_STAT_MAX_IN_FLIGHT);
1203
1204         gfp_mask = GFP_HIGHUSER & ~__GFP_WAIT;
1205 #ifdef __GFP_NOWARN
1206         gfp_mask |= __GFP_NOWARN;
1207 #endif
1208
1209         for (i = start; reserved > 0 && !match_failed && i <= end; i++) {
1210                 /* skip locked pages from previous readpage calls */
1211                 page = grab_cache_page_nowait_gfp(mapping, i, gfp_mask);
1212                 if (page == NULL) {
1213                         ll_ra_stats_inc(mapping, RA_STAT_FAILED_GRAB_PAGE);
1214                         CDEBUG(D_READA, "g_c_p_n failed\n");
1215                         continue;
1216                 }
1217
1218                 /* Check if page was truncated or reclaimed */
1219                 if (page->mapping != mapping) {
1220                         ll_ra_stats_inc(mapping, RA_STAT_WRONG_GRAB_PAGE);
1221                         CDEBUG(D_READA, "g_c_p_n returned invalid page\n");
1222                         goto next_page;
1223                 }
1224
1225                 /* we do this first so that we can see the page in the /proc
1226                  * accounting */
1227                 llap = llap_from_page(page, LLAP_ORIGIN_READAHEAD);
1228                 if (IS_ERR(llap) || llap->llap_defer_uptodate)
1229                         goto next_page;
1230
1231                 /* skip completed pages */
1232                 if (Page_Uptodate(page))
1233                         goto next_page;
1234
1235                 /* bail when we hit the end of the lock. */
1236                 if ((rc = ll_page_matches(page, flags|LL_FILE_READAHEAD)) <= 0){
1237                         LL_CDEBUG_PAGE(D_READA | D_PAGE, page,
1238                                        "lock match failed: rc %d\n", rc);
1239                         ll_ra_stats_inc(mapping, RA_STAT_FAILED_MATCH);
1240                         match_failed = 1;
1241                         goto next_page;
1242                 }
1243
1244                 rc = ll_issue_page_read(exp, llap, oig, 1);
1245                 if (rc == 0) {
1246                         reserved--;
1247                         ret++;
1248                         LL_CDEBUG_PAGE(D_READA| D_PAGE, page,
1249                                        "started read-ahead\n");
1250                 } else {
1251         next_page:
1252                         LL_CDEBUG_PAGE(D_READA | D_PAGE, page,
1253                                        "skipping read-ahead\n");
1254
1255                         unlock_page(page);
1256                 }
1257                 page_cache_release(page);
1258         }
1259
1260         LASSERTF(reserved >= 0, "reserved %lu\n", reserved);
1261         if (reserved != 0)
1262                 ll_ra_count_put(ll_i2sbi(inode), reserved);
1263         if (i == end + 1 && end == (kms >> CFS_PAGE_SHIFT))
1264                 ll_ra_stats_inc(mapping, RA_STAT_EOF);
1265
1266         /* if we didn't get to the end of the region we reserved from
1267          * the ras we need to go back and update the ras so that the
1268          * next read-ahead tries from where we left off.  we only do so
1269          * if the region we failed to issue read-ahead on is still ahead
1270          * of the app and behind the next index to start read-ahead from */
1271         if (i != end + 1) {
1272                 spin_lock(&ras->ras_lock);
1273                 if (i < ras->ras_next_readahead &&
1274                     index_in_window(i, ras->ras_window_start, 0,
1275                                     ras->ras_window_len)) {
1276                         ras->ras_next_readahead = i;
1277                         RAS_CDEBUG(ras);
1278                 }
1279                 spin_unlock(&ras->ras_lock);
1280         }
1281
1282         RETURN(ret);
1283 }
1284
1285 static void ras_set_start(struct ll_readahead_state *ras, unsigned long index)
1286 {
1287         ras->ras_window_start = index & (~((1024 * 1024 >> CFS_PAGE_SHIFT) - 1));
1288 }
1289
1290 /* called with the ras_lock held or from places where it doesn't matter */
1291 static void ras_reset(struct ll_readahead_state *ras, unsigned long index)
1292 {
1293         ras->ras_last_readpage = index;
1294         ras->ras_consecutive_requests = 0;
1295         ras->ras_consecutive_pages = 0;
1296         ras->ras_window_len = 0;
1297         ras_set_start(ras, index);
1298         ras->ras_next_readahead = max(ras->ras_window_start, index);
1299
1300         RAS_CDEBUG(ras);
1301 }
1302
1303 void ll_readahead_init(struct inode *inode, struct ll_readahead_state *ras)
1304 {
1305         spin_lock_init(&ras->ras_lock);
1306         ras_reset(ras, 0);
1307         ras->ras_requests = 0;
1308         INIT_LIST_HEAD(&ras->ras_read_beads);
1309 }
1310
1311 static void ras_update(struct ll_sb_info *sbi, struct inode *inode,
1312                        struct ll_readahead_state *ras, unsigned long index,
1313                        unsigned hit)
1314 {
1315         struct ll_ra_info *ra = &sbi->ll_ra_info;
1316         int zero = 0;
1317         ENTRY;
1318
1319         spin_lock(&sbi->ll_lock);
1320         spin_lock(&ras->ras_lock);
1321
1322         ll_ra_stats_inc_unlocked(ra, hit ? RA_STAT_HIT : RA_STAT_MISS);
1323
1324         /* reset the read-ahead window in two cases.  First when the app seeks
1325          * or reads to some other part of the file.  Secondly if we get a
1326          * read-ahead miss that we think we've previously issued.  This can
1327          * be a symptom of there being so many read-ahead pages that the VM is
1328          * reclaiming it before we get to it. */
1329         if (!index_in_window(index, ras->ras_last_readpage, 8, 8)) {
1330                 zero = 1;
1331                 ll_ra_stats_inc_unlocked(ra, RA_STAT_DISTANT_READPAGE);
1332         } else if (!hit && ras->ras_window_len &&
1333                    index < ras->ras_next_readahead &&
1334                    index_in_window(index, ras->ras_window_start, 0,
1335                                    ras->ras_window_len)) {
1336                 zero = 1;
1337                 ll_ra_stats_inc_unlocked(ra, RA_STAT_MISS_IN_WINDOW);
1338         }
1339
1340         /* On the second access to a file smaller than the tunable
1341          * ra_max_read_ahead_whole_pages trigger RA on all pages in the
1342          * file up to ra_max_pages.  This is simply a best effort and
1343          * only occurs once per open file.  Normal RA behavior is reverted
1344          * to for subsequent IO.  The mmap case does not increment
1345          * ras_requests and thus can never trigger this behavior. */
1346         if (ras->ras_requests == 2 && !ras->ras_request_index) {
1347                 __u64 kms_pages;
1348
1349                 kms_pages = (i_size_read(inode) + CFS_PAGE_SIZE - 1) >>
1350                             CFS_PAGE_SHIFT;
1351
1352                 CDEBUG(D_READA, "kmsp "LPU64" mwp %lu mp %lu\n", kms_pages,
1353                        ra->ra_max_read_ahead_whole_pages, ra->ra_max_pages);
1354
1355                 if (kms_pages &&
1356                     kms_pages <= ra->ra_max_read_ahead_whole_pages) {
1357                         ras->ras_window_start = 0;
1358                         ras->ras_last_readpage = 0;
1359                         ras->ras_next_readahead = 0;
1360                         ras->ras_window_len = min(ra->ra_max_pages,
1361                                 ra->ra_max_read_ahead_whole_pages);
1362                         GOTO(out_unlock, 0);
1363                 }
1364         }
1365
1366         if (zero) {
1367                 ras_reset(ras, index);
1368                 GOTO(out_unlock, 0);
1369         }
1370
1371         ras->ras_last_readpage = index;
1372         ras->ras_consecutive_pages++;
1373         ras_set_start(ras, index);
1374         ras->ras_next_readahead = max(ras->ras_window_start,
1375                                       ras->ras_next_readahead);
1376
1377         /* Trigger RA in the mmap case where ras_consecutive_requests
1378          * is not incremented and thus can't be used to trigger RA */
1379         if (!ras->ras_window_len && ras->ras_consecutive_pages == 3) {
1380                 ras->ras_window_len = 1024 * 1024 >> CFS_PAGE_SHIFT;
1381                 GOTO(out_unlock, 0);
1382         }
1383
1384         /* The initial ras_window_len is set to the request size.  To avoid
1385          * uselessly reading and discarding pages for random IO the window is
1386          * only increased once per consecutive request received. */
1387         if (ras->ras_consecutive_requests > 1 && !ras->ras_request_index) {
1388                 ras->ras_window_len = min(ras->ras_window_len +
1389                                           (1024 * 1024 >> CFS_PAGE_SHIFT),
1390                                           ra->ra_max_pages);
1391         }
1392
1393         EXIT;
1394 out_unlock:
1395         RAS_CDEBUG(ras);
1396         ras->ras_request_index++;
1397         spin_unlock(&ras->ras_lock);
1398         spin_unlock(&sbi->ll_lock);
1399         return;
1400 }
1401
1402 int ll_writepage(struct page *page)
1403 {
1404         struct inode *inode = page->mapping->host;
1405         struct ll_inode_info *lli = ll_i2info(inode);
1406         struct obd_export *exp;
1407         struct ll_async_page *llap;
1408         int rc = 0;
1409         ENTRY;
1410
1411         LASSERT(!PageDirty(page));
1412         LASSERT(PageLocked(page));
1413
1414         exp = ll_i2dtexp(inode);
1415         if (exp == NULL)
1416                 GOTO(out, rc = -EINVAL);
1417
1418         llap = llap_from_page(page, LLAP_ORIGIN_WRITEPAGE);
1419         if (IS_ERR(llap))
1420                 GOTO(out, rc = PTR_ERR(llap));
1421
1422         LASSERT(!PageWriteback(page));
1423         set_page_writeback(page);
1424
1425         page_cache_get(page);
1426         if (llap->llap_write_queued) {
1427                 LL_CDEBUG_PAGE(D_PAGE, page, "marking urgent\n");
1428                 rc = obd_set_async_flags(exp, lli->lli_smd, NULL,
1429                                          llap->llap_cookie,
1430                                          ASYNC_READY | ASYNC_URGENT);
1431         } else {
1432                 rc = queue_or_sync_write(exp, inode, llap, CFS_PAGE_SIZE,
1433                                          ASYNC_READY | ASYNC_URGENT);
1434         }
1435         if (rc)
1436                 page_cache_release(page);
1437 out:
1438         if (rc) {
1439                 if (!lli->lli_async_rc)
1440                         lli->lli_async_rc = rc;
1441                 /* re-dirty page on error so it retries write */
1442                 if (PageWriteback(page)) {
1443                         end_page_writeback(page);
1444                 }
1445                 /* resend page only for not started IO*/
1446                 if (!PageError(page))
1447                         ll_redirty_page(page);
1448                 unlock_page(page);
1449         }
1450         RETURN(rc);
1451 }
1452
1453 /*
1454  * for now we do our readpage the same on both 2.4 and 2.5.  The kernel's
1455  * read-ahead assumes it is valid to issue readpage all the way up to
1456  * i_size, but our dlm locks make that not the case.  We disable the
1457  * kernel's read-ahead and do our own by walking ahead in the page cache
1458  * checking for dlm lock coverage.  the main difference between 2.4 and
1459  * 2.6 is how read-ahead gets batched and issued, but we're using our own,
1460  * so they look the same.
1461  */
1462 int ll_readpage(struct file *filp, struct page *page)
1463 {
1464         struct ll_file_data *fd = LUSTRE_FPRIVATE(filp);
1465         struct inode *inode = page->mapping->host;
1466         struct obd_export *exp;
1467         struct ll_async_page *llap;
1468         struct obd_io_group *oig = NULL;
1469         int rc;
1470         ENTRY;
1471
1472         LASSERT(PageLocked(page));
1473         LASSERT(!PageUptodate(page));
1474         CDEBUG(D_VFSTRACE, "VFS Op:inode=%lu/%u(%p),offset=%Lu=%#Lx\n",
1475                inode->i_ino, inode->i_generation, inode,
1476                (((loff_t)page->index) << CFS_PAGE_SHIFT),
1477                (((loff_t)page->index) << CFS_PAGE_SHIFT));
1478         LASSERT(atomic_read(&filp->f_dentry->d_inode->i_count) > 0);
1479
1480         if (!ll_i2info(inode)->lli_smd) {
1481                 /* File with no objects - one big hole */
1482                 /* We use this just for remove_from_page_cache that is not
1483                  * exported, we'd make page back up to date. */
1484                 ll_truncate_complete_page(page);
1485                 clear_page(kmap(page));
1486                 kunmap(page);
1487                 SetPageUptodate(page);
1488                 unlock_page(page);
1489                 RETURN(0);
1490         }
1491
1492         rc = oig_init(&oig);
1493         if (rc < 0)
1494                 GOTO(out, rc);
1495
1496         exp = ll_i2dtexp(inode);
1497         if (exp == NULL)
1498                 GOTO(out, rc = -EINVAL);
1499
1500         llap = llap_from_page(page, LLAP_ORIGIN_READPAGE);
1501         if (IS_ERR(llap))
1502                 GOTO(out, rc = PTR_ERR(llap));
1503
1504         if (ll_i2sbi(inode)->ll_ra_info.ra_max_pages)
1505                 ras_update(ll_i2sbi(inode), inode, &fd->fd_ras, page->index,
1506                            llap->llap_defer_uptodate);
1507
1508         if (llap->llap_defer_uptodate) {
1509                 llap->llap_ra_used = 1;
1510                 rc = ll_readahead(&fd->fd_ras, exp, page->mapping, oig,
1511                                   fd->fd_flags);
1512                 if (rc > 0)
1513                         obd_trigger_group_io(exp, ll_i2info(inode)->lli_smd,
1514                                              NULL, oig);
1515                 LL_CDEBUG_PAGE(D_PAGE, page, "marking uptodate from defer\n");
1516                 SetPageUptodate(page);
1517                 unlock_page(page);
1518                 GOTO(out_oig, rc = 0);
1519         }
1520
1521         if (likely((fd->fd_flags & LL_FILE_IGNORE_LOCK) == 0)) {
1522                 rc = ll_page_matches(page, fd->fd_flags);
1523                 if (rc < 0) {
1524                         LL_CDEBUG_PAGE(D_ERROR, page, "lock match failed: rc %d\n", rc);
1525                         GOTO(out, rc);
1526                 }
1527
1528                 if (rc == 0) {
1529                         CWARN("ino %lu page %lu (%llu) not covered by "
1530                               "a lock (mmap?).  check debug logs.\n",
1531                               inode->i_ino, page->index,
1532                               (long long)page->index << CFS_PAGE_SHIFT);
1533                 }
1534         }
1535
1536         rc = ll_issue_page_read(exp, llap, oig, 0);
1537         if (rc)
1538                 GOTO(out, rc);
1539
1540         LL_CDEBUG_PAGE(D_PAGE, page, "queued readpage\n");
1541         if (ll_i2sbi(inode)->ll_ra_info.ra_max_pages)
1542                 ll_readahead(&fd->fd_ras, exp, page->mapping, oig,
1543                              fd->fd_flags);
1544
1545         rc = obd_trigger_group_io(exp, ll_i2info(inode)->lli_smd, NULL, oig);
1546
1547 out:
1548         if (rc)
1549                 unlock_page(page);
1550 out_oig:
1551         if (oig != NULL)
1552                 oig_release(oig);
1553         RETURN(rc);
1554 }