Whamcloud - gitweb
b=17682 limit performance impact of rpctrace, dlmtrace & quota (real commit)
[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  * GPL HEADER START
5  *
6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License version 2 only,
10  * as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License version 2 for more details (a copy is included
16  * in the LICENSE file that accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License
19  * version 2 along with this program; If not, see
20  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
21  *
22  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
23  * CA 95054 USA or visit www.sun.com if you need additional information or
24  * have any questions.
25  *
26  * GPL HEADER END
27  */
28 /*
29  * Copyright  2008 Sun Microsystems, Inc. All rights reserved
30  * Use is subject to license terms.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * lustre/llite/rw.c
37  *
38  * Lustre Lite I/O page cache routines shared by different kernel revs
39  */
40
41 #ifndef AUTOCONF_INCLUDED
42 #include <linux/config.h>
43 #endif
44 #include <linux/kernel.h>
45 #include <linux/mm.h>
46 #include <linux/string.h>
47 #include <linux/stat.h>
48 #include <linux/errno.h>
49 #include <linux/smp_lock.h>
50 #include <linux/unistd.h>
51 #include <linux/version.h>
52 #include <asm/system.h>
53 #include <asm/uaccess.h>
54
55 #include <linux/fs.h>
56 #include <linux/stat.h>
57 #include <asm/uaccess.h>
58 #include <linux/mm.h>
59 #include <linux/pagemap.h>
60 #include <linux/smp_lock.h>
61
62 #define DEBUG_SUBSYSTEM S_LLITE
63
64 #include <linux/page-flags.h>
65
66 #include <lustre_lite.h>
67 #include "llite_internal.h"
68 #include <linux/lustre_compat25.h>
69
70 #ifndef list_for_each_prev_safe
71 #define list_for_each_prev_safe(pos, n, head) \
72         for (pos = (head)->prev, n = pos->prev; pos != (head); \
73                 pos = n, n = pos->prev )
74 #endif
75
76 cfs_mem_cache_t *ll_async_page_slab = NULL;
77 size_t ll_async_page_slab_size = 0;
78
79 /* SYNCHRONOUS I/O to object storage for an inode */
80 static int ll_brw(int cmd, struct inode *inode, struct obdo *oa,
81                   struct page *page, int flags)
82 {
83         struct ll_inode_info *lli = ll_i2info(inode);
84         struct lov_stripe_md *lsm = lli->lli_smd;
85         struct obd_info oinfo = { { { 0 } } };
86         struct brw_page pg;
87         int rc;
88         ENTRY;
89
90         pg.pg = page;
91         pg.off = ((obd_off)page->index) << CFS_PAGE_SHIFT;
92
93         if ((cmd & OBD_BRW_WRITE) && (pg.off+CFS_PAGE_SIZE>i_size_read(inode)))
94                 pg.count = i_size_read(inode) % CFS_PAGE_SIZE;
95         else
96                 pg.count = CFS_PAGE_SIZE;
97
98         LL_CDEBUG_PAGE(D_PAGE, page, "%s %d bytes ino %lu at "LPU64"/"LPX64"\n",
99                        cmd & OBD_BRW_WRITE ? "write" : "read", pg.count,
100                        inode->i_ino, pg.off, pg.off);
101         if (pg.count == 0) {
102                 CERROR("ZERO COUNT: ino %lu: size %p:%Lu(%p:%Lu) idx %lu off "
103                        LPU64"\n", inode->i_ino, inode, i_size_read(inode),
104                        page->mapping->host, i_size_read(page->mapping->host),
105                        page->index, pg.off);
106         }
107
108         pg.flag = flags;
109
110         if (cmd & OBD_BRW_WRITE)
111                 ll_stats_ops_tally(ll_i2sbi(inode), LPROC_LL_BRW_WRITE,
112                                    pg.count);
113         else
114                 ll_stats_ops_tally(ll_i2sbi(inode), LPROC_LL_BRW_READ,
115                            pg.count);
116         oinfo.oi_oa = oa;
117         oinfo.oi_md = lsm;
118         rc = obd_brw(cmd, ll_i2obdexp(inode), &oinfo, 1, &pg, NULL);
119         if (rc == 0)
120                 obdo_to_inode(inode, oa, OBD_MD_FLBLOCKS);
121         else if (rc != -EIO)
122                 CERROR("error from obd_brw: rc = %d\n", rc);
123         RETURN(rc);
124 }
125
126 int ll_file_punch(struct inode * inode, loff_t new_size, int srvlock)
127 {
128         struct ll_inode_info *lli = ll_i2info(inode);
129         struct obd_info oinfo = { { { 0 } } };
130         struct obdo oa = { 0 };
131         obd_valid valid;
132         int rc;
133
134         ENTRY;
135         CDEBUG(D_INFO, "calling punch for "LPX64" (new size %Lu=%#Lx)\n",
136                lli->lli_smd->lsm_object_id, new_size, new_size);
137
138         oinfo.oi_md = lli->lli_smd;
139         oinfo.oi_policy.l_extent.start = new_size;
140         oinfo.oi_policy.l_extent.end = OBD_OBJECT_EOF;
141         oinfo.oi_oa = &oa;
142         oa.o_id = lli->lli_smd->lsm_object_id;
143         oa.o_gr = lli->lli_smd->lsm_object_gr;
144         oa.o_valid = OBD_MD_FLID | OBD_MD_FLGROUP;
145
146         valid = OBD_MD_FLTYPE | OBD_MD_FLMODE |OBD_MD_FLFID |
147                 OBD_MD_FLATIME | OBD_MD_FLUID | OBD_MD_FLGID | OBD_MD_FLGENER |
148                 OBD_MD_FLBLOCKS;
149         if (srvlock) {
150                 /* set OBD_MD_FLFLAGS in o_valid, only if we
151                  * set OBD_FL_TRUNCLOCK, otherwise ost_punch
152                  * and filter_setattr get confused, see the comment
153                  * in ost_punch */
154                 oa.o_flags = OBD_FL_TRUNCLOCK;
155                 oa.o_valid |= OBD_MD_FLFLAGS;
156
157                 /* lockless truncate
158                  *
159                  * 1. do not use inode's timestamps because concurrent
160                  * stat might fill the inode with out-of-date times,
161                  * send current instead
162                  *
163                  * 2.do no update lsm, as long as stat (via
164                  * ll_glimpse_size) will bring attributes from osts
165                  * anyway */
166                 oa.o_mtime = oa.o_ctime = LTIME_S(CURRENT_TIME);
167                 oa.o_valid |= OBD_MD_FLMTIME | OBD_MD_FLCTIME;
168         } else {
169                 struct ost_lvb *xtimes;
170                 /* truncate under locks
171                  *
172                  * 1. update inode's mtime and ctime as long as
173                  * concurrent stat (via ll_glimpse_size) might bring
174                  * out-of-date ones
175                  *
176                  * 2. update lsm so that next stat (via
177                  * ll_glimpse_size) could get correct values in lsm */
178                 OBD_ALLOC_PTR(xtimes);
179                 if (NULL == xtimes)
180                         RETURN(-ENOMEM);
181
182                 lov_stripe_lock(lli->lli_smd);
183                 LTIME_S(inode->i_mtime) = LTIME_S(CURRENT_TIME);
184                 LTIME_S(inode->i_ctime) = LTIME_S(CURRENT_TIME);
185                 xtimes->lvb_mtime = LTIME_S(inode->i_mtime);
186                 xtimes->lvb_ctime = LTIME_S(inode->i_ctime);
187                 obd_update_lvb(ll_i2obdexp(inode), lli->lli_smd, xtimes,
188                                OBD_MD_FLMTIME | OBD_MD_FLCTIME);
189                 lov_stripe_unlock(lli->lli_smd);
190                 OBD_FREE_PTR(xtimes);
191
192                 valid |= OBD_MD_FLMTIME | OBD_MD_FLCTIME;
193         }
194         obdo_from_inode(&oa, inode, valid);
195
196         rc = obd_punch_rqset(ll_i2obdexp(inode), &oinfo, NULL);
197         if (rc) {
198                 CERROR("obd_truncate fails (%d) ino %lu\n", rc, inode->i_ino);
199                 RETURN(rc);
200         }
201         obdo_to_inode(inode, &oa, OBD_MD_FLSIZE | OBD_MD_FLBLOCKS |
202                       OBD_MD_FLATIME | OBD_MD_FLMTIME | OBD_MD_FLCTIME);
203         RETURN(0);
204 }
205 /* this isn't where truncate starts.   roughly:
206  * sys_truncate->ll_setattr_raw->vmtruncate->ll_truncate. setattr_raw grabs
207  * DLM lock on [size, EOF], i_mutex, ->lli_size_sem, and WRITE_I_ALLOC_SEM to
208  * avoid races.
209  *
210  * must be called under ->lli_size_sem */
211 void ll_truncate(struct inode *inode)
212 {
213         struct ll_inode_info *lli = ll_i2info(inode);
214         int srvlock = test_bit(LLI_F_SRVLOCK, &lli->lli_flags);
215         loff_t new_size;
216         ENTRY;
217         CDEBUG(D_VFSTRACE, "VFS Op:inode=%lu/%u(%p) to %Lu=%#Lx\n",
218                inode->i_ino, inode->i_generation, inode, i_size_read(inode),
219                i_size_read(inode));
220
221         ll_stats_ops_tally(ll_i2sbi(inode), LPROC_LL_TRUNC, 1);
222         if (lli->lli_size_sem_owner != current) {
223                 EXIT;
224                 return;
225         }
226
227         if (!lli->lli_smd) {
228                 CDEBUG(D_INODE, "truncate on inode %lu with no objects\n",
229                        inode->i_ino);
230                 GOTO(out_unlock, 0);
231         }
232
233         LASSERT(SEM_COUNT(&lli->lli_size_sem) <= 0);
234
235         if (!srvlock) {
236                 struct ost_lvb lvb;
237                 int rc;
238
239                 /* XXX I'm pretty sure this is a hack to paper over a more
240                  * fundamental race condition. */
241                 lov_stripe_lock(lli->lli_smd);
242                 inode_init_lvb(inode, &lvb);
243                 rc = obd_merge_lvb(ll_i2obdexp(inode), lli->lli_smd, &lvb, 0);
244                 inode->i_blocks = lvb.lvb_blocks;
245                 if (lvb.lvb_size == i_size_read(inode) && rc == 0) {
246                         CDEBUG(D_VFSTRACE, "skipping punch for obj "LPX64
247                                ", %Lu=%#Lx\n",
248                                lli->lli_smd->lsm_object_id, i_size_read(inode),
249                                i_size_read(inode));
250                         lov_stripe_unlock(lli->lli_smd);
251                         GOTO(out_unlock, 0);
252                 }
253
254                 obd_adjust_kms(ll_i2obdexp(inode), lli->lli_smd,
255                                i_size_read(inode), 1);
256                 lov_stripe_unlock(lli->lli_smd);
257         }
258
259         if (unlikely((ll_i2sbi(inode)->ll_flags & LL_SBI_LLITE_CHECKSUM) &&
260                      (i_size_read(inode) & ~CFS_PAGE_MASK))) {
261                 /* If the truncate leaves a partial page, update its checksum */
262                 struct page *page = find_get_page(inode->i_mapping,
263                                                   i_size_read(inode) >>
264                                                   CFS_PAGE_SHIFT);
265                 if (page != NULL) {
266                         struct ll_async_page *llap = llap_cast_private(page);
267                         if (llap != NULL) {
268                                 char *kaddr = kmap_atomic(page, KM_USER0);
269                                 llap->llap_checksum =
270                                         init_checksum(OSC_DEFAULT_CKSUM);
271                                 llap->llap_checksum =
272                                         compute_checksum(llap->llap_checksum,
273                                                          kaddr, CFS_PAGE_SIZE,
274                                                          OSC_DEFAULT_CKSUM);
275                                 kunmap_atomic(kaddr, KM_USER0);
276                         }
277                         page_cache_release(page);
278                 }
279         }
280
281         new_size = i_size_read(inode);
282         ll_inode_size_unlock(inode, 0);
283         if (!srvlock)
284                 ll_file_punch(inode, new_size, 0);
285         else
286                 ll_stats_ops_tally(ll_i2sbi(inode), LPROC_LL_LOCKLESS_TRUNC, 1);
287
288         EXIT;
289         return;
290
291  out_unlock:
292         ll_inode_size_unlock(inode, 0);
293 } /* ll_truncate */
294
295 int ll_prepare_write(struct file *file, struct page *page, unsigned from,
296                      unsigned to)
297 {
298         struct inode *inode = page->mapping->host;
299         struct ll_inode_info *lli = ll_i2info(inode);
300         struct lov_stripe_md *lsm = lli->lli_smd;
301         obd_off offset = ((obd_off)page->index) << CFS_PAGE_SHIFT;
302         struct obd_info oinfo = { { { 0 } } };
303         struct brw_page pga;
304         struct obdo oa = { 0 };
305         struct ost_lvb lvb;
306         int rc = 0;
307         ENTRY;
308
309         LASSERT(PageLocked(page));
310         (void)llap_cast_private(page); /* assertion */
311
312         /* Check to see if we should return -EIO right away */
313         pga.pg = page;
314         pga.off = offset;
315         pga.count = CFS_PAGE_SIZE;
316         pga.flag = 0;
317
318         oa.o_mode = inode->i_mode;
319         oa.o_id = lsm->lsm_object_id;
320         oa.o_gr = lsm->lsm_object_gr;
321         oa.o_valid = OBD_MD_FLID   | OBD_MD_FLMODE |
322                      OBD_MD_FLTYPE | OBD_MD_FLGROUP;
323         obdo_from_inode(&oa, inode, OBD_MD_FLFID | OBD_MD_FLGENER);
324
325         oinfo.oi_oa = &oa;
326         oinfo.oi_md = lsm;
327         rc = obd_brw(OBD_BRW_CHECK, ll_i2obdexp(inode), &oinfo, 1, &pga, NULL);
328         if (rc)
329                 RETURN(rc);
330
331         if (PageUptodate(page)) {
332                 LL_CDEBUG_PAGE(D_PAGE, page, "uptodate\n");
333                 RETURN(0);
334         }
335
336         /* We're completely overwriting an existing page, so _don't_ set it up
337          * to date until commit_write */
338         if (from == 0 && to == CFS_PAGE_SIZE) {
339                 LL_CDEBUG_PAGE(D_PAGE, page, "full page write\n");
340                 POISON_PAGE(page, 0x11);
341                 RETURN(0);
342         }
343
344         /* If are writing to a new page, no need to read old data.  The extent
345          * locking will have updated the KMS, and for our purposes here we can
346          * treat it like i_size. */
347         lov_stripe_lock(lsm);
348         inode_init_lvb(inode, &lvb);
349         obd_merge_lvb(ll_i2obdexp(inode), lsm, &lvb, 1);
350         lov_stripe_unlock(lsm);
351         if (lvb.lvb_size <= offset) {
352                 char *kaddr = kmap_atomic(page, KM_USER0);
353                 LL_CDEBUG_PAGE(D_PAGE, page, "kms "LPU64" <= offset "LPU64"\n",
354                                lvb.lvb_size, offset);
355                 memset(kaddr, 0, CFS_PAGE_SIZE);
356                 kunmap_atomic(kaddr, KM_USER0);
357                 GOTO(prepare_done, rc = 0);
358         }
359
360         /* XXX could be an async ocp read.. read-ahead? */
361         rc = ll_brw(OBD_BRW_READ, inode, &oa, page, 0);
362         if (rc == 0) {
363                 /* bug 1598: don't clobber blksize */
364                 oa.o_valid &= ~(OBD_MD_FLSIZE | OBD_MD_FLBLKSZ);
365                 obdo_refresh_inode(inode, &oa, oa.o_valid);
366         }
367
368         EXIT;
369  prepare_done:
370         if (rc == 0)
371                 SetPageUptodate(page);
372
373         return rc;
374 }
375
376 /**
377  * make page ready for ASYNC write
378  * \param data - pointer to llap cookie
379  * \param cmd - is OBD_BRW_* macroses
380  *
381  * \retval 0 is page successfully prepared to send
382  * \retval -EAGAIN is page not need to send
383  */
384 static int ll_ap_make_ready(void *data, int cmd)
385 {
386         struct ll_async_page *llap;
387         struct page *page;
388         ENTRY;
389
390         llap = LLAP_FROM_COOKIE(data);
391         page = llap->llap_page;
392
393         /* we're trying to write, but the page is locked.. come back later */
394         if (TryLockPage(page))
395                 RETURN(-EAGAIN);
396
397         LASSERTF(!(cmd & OBD_BRW_READ) || !PageWriteback(page),
398                 "cmd %x page %p ino %lu index %lu fl %lx\n", cmd, page,
399                  page->mapping->host->i_ino, page->index, (long)page->flags);
400
401         /* if we left PageDirty we might get another writepage call
402          * in the future.  list walkers are bright enough
403          * to check page dirty so we can leave it on whatever list
404          * its on.  XXX also, we're called with the cli list so if
405          * we got the page cache list we'd create a lock inversion
406          * with the removepage path which gets the page lock then the
407          * cli lock */
408         if(!clear_page_dirty_for_io(page)) {
409                 unlock_page(page);
410                 RETURN(-EAGAIN);
411         }
412
413         /* This actually clears the dirty bit in the radix tree.*/
414         set_page_writeback(page);
415
416         LL_CDEBUG_PAGE(D_PAGE, page, "made ready\n");
417         page_cache_get(page);
418
419         RETURN(0);
420 }
421
422 /* We have two reasons for giving llite the opportunity to change the
423  * write length of a given queued page as it builds the RPC containing
424  * the page:
425  *
426  * 1) Further extending writes may have landed in the page cache
427  *    since a partial write first queued this page requiring us
428  *    to write more from the page cache.  (No further races are possible,
429  *    since by the time this is called, the page is locked.)
430  * 2) We might have raced with truncate and want to avoid performing
431  *    write RPCs that are just going to be thrown away by the
432  *    truncate's punch on the storage targets.
433  *
434  * The kms serves these purposes as it is set at both truncate and extending
435  * writes.
436  */
437 static int ll_ap_refresh_count(void *data, int cmd)
438 {
439         struct ll_inode_info *lli;
440         struct ll_async_page *llap;
441         struct lov_stripe_md *lsm;
442         struct page *page;
443         struct inode *inode;
444         struct ost_lvb lvb;
445         __u64 kms;
446         ENTRY;
447
448         /* readpage queues with _COUNT_STABLE, shouldn't get here. */
449         LASSERT(cmd != OBD_BRW_READ);
450
451         llap = LLAP_FROM_COOKIE(data);
452         page = llap->llap_page;
453         inode = page->mapping->host;
454         lli = ll_i2info(inode);
455         lsm = lli->lli_smd;
456
457         lov_stripe_lock(lsm);
458         inode_init_lvb(inode, &lvb);
459         obd_merge_lvb(ll_i2obdexp(inode), lsm, &lvb, 1);
460         kms = lvb.lvb_size;
461         lov_stripe_unlock(lsm);
462
463         /* catch race with truncate */
464         if (((__u64)page->index << CFS_PAGE_SHIFT) >= kms)
465                 return 0;
466
467         /* catch sub-page write at end of file */
468         if (((__u64)page->index << CFS_PAGE_SHIFT) + CFS_PAGE_SIZE > kms)
469                 return kms % CFS_PAGE_SIZE;
470
471         return CFS_PAGE_SIZE;
472 }
473
474 void ll_inode_fill_obdo(struct inode *inode, int cmd, struct obdo *oa)
475 {
476         struct lov_stripe_md *lsm;
477         obd_flag valid_flags;
478
479         lsm = ll_i2info(inode)->lli_smd;
480
481         oa->o_id = lsm->lsm_object_id;
482         oa->o_gr = lsm->lsm_object_gr;
483         oa->o_valid = OBD_MD_FLID | OBD_MD_FLGROUP;
484         valid_flags = OBD_MD_FLTYPE | OBD_MD_FLATIME;
485         if (cmd & OBD_BRW_WRITE) {
486                 oa->o_valid |= OBD_MD_FLEPOCH;
487                 oa->o_easize = ll_i2info(inode)->lli_io_epoch;
488
489                 valid_flags |= OBD_MD_FLMTIME | OBD_MD_FLCTIME |
490                         OBD_MD_FLUID | OBD_MD_FLGID |
491                         OBD_MD_FLFID | OBD_MD_FLGENER;
492         }
493
494         obdo_from_inode(oa, inode, valid_flags);
495 }
496
497 static void ll_ap_fill_obdo(void *data, int cmd, struct obdo *oa)
498 {
499         struct ll_async_page *llap;
500         ENTRY;
501
502         llap = LLAP_FROM_COOKIE(data);
503         ll_inode_fill_obdo(llap->llap_page->mapping->host, cmd, oa);
504
505         EXIT;
506 }
507
508 static void ll_ap_update_obdo(void *data, int cmd, struct obdo *oa,
509                               obd_valid valid)
510 {
511         struct ll_async_page *llap;
512         ENTRY;
513
514         llap = LLAP_FROM_COOKIE(data);
515         obdo_from_inode(oa, llap->llap_page->mapping->host, valid);
516
517         EXIT;
518 }
519
520 static struct obd_async_page_ops ll_async_page_ops = {
521         .ap_make_ready =        ll_ap_make_ready,
522         .ap_refresh_count =     ll_ap_refresh_count,
523         .ap_fill_obdo =         ll_ap_fill_obdo,
524         .ap_update_obdo =       ll_ap_update_obdo,
525         .ap_completion =        ll_ap_completion,
526 };
527
528 struct ll_async_page *llap_cast_private(struct page *page)
529 {
530         struct ll_async_page *llap = (struct ll_async_page *)page_private(page);
531
532         LASSERTF(llap == NULL || llap->llap_magic == LLAP_MAGIC,
533                  "page %p private %lu gave magic %d which != %d\n",
534                  page, page_private(page), llap->llap_magic, LLAP_MAGIC);
535
536         return llap;
537 }
538
539 /* Try to reap @target pages in the specific @cpu's async page list.
540  *
541  * There is an llap attached onto every page in lustre, linked off @sbi.
542  * We add an llap to the list so we don't lose our place during list walking.
543  * If llaps in the list are being moved they will only move to the end
544  * of the LRU, and we aren't terribly interested in those pages here (we
545  * start at the beginning of the list where the least-used llaps are. */
546 static inline int llap_shrink_cache_internal(struct ll_sb_info *sbi,
547         int cpu, int target)
548 {
549         struct ll_async_page *llap, dummy_llap = { .llap_magic = 0xd11ad11a };
550         struct ll_pglist_data *pd;
551         struct list_head *head;
552         int count = 0;
553
554         pd = ll_pglist_cpu_lock(sbi, cpu);
555         head = &pd->llpd_list;
556         list_add(&dummy_llap.llap_pglist_item, head);
557         while (count < target) {
558                 struct page *page;
559                 int keep;
560
561                 if (unlikely(need_resched())) {
562                         list_del(&dummy_llap.llap_pglist_item);
563                         ll_pglist_cpu_unlock(sbi, cpu);
564                         /* vmscan::shrink_slab() have own schedule() */
565                         return count;
566                 }
567
568                 llap = llite_pglist_next_llap(head,
569                         &dummy_llap.llap_pglist_item);
570                 list_del_init(&dummy_llap.llap_pglist_item);
571                 if (llap == NULL)
572                         break;
573
574                 page = llap->llap_page;
575                 LASSERT(page != NULL);
576
577                 list_add(&dummy_llap.llap_pglist_item, &llap->llap_pglist_item);
578
579                 /* Page needs/undergoing IO */
580                 if (TryLockPage(page)) {
581                         LL_CDEBUG_PAGE(D_PAGE, page, "can't lock\n");
582                         continue;
583                 }
584
585                keep = (llap->llap_write_queued || PageDirty(page) ||
586                       PageWriteback(page) || (!PageUptodate(page) &&
587                       llap->llap_origin != LLAP_ORIGIN_READAHEAD));
588
589                 LL_CDEBUG_PAGE(D_PAGE, page,
590                                "%s LRU page: %s%s%s%s%s origin %s\n",
591                                keep ? "keep" : "drop",
592                                llap->llap_write_queued ? "wq " : "",
593                                PageDirty(page) ? "pd " : "",
594                                PageUptodate(page) ? "" : "!pu ",
595                                PageWriteback(page) ? "wb" : "",
596                                llap->llap_defer_uptodate ? "" : "!du",
597                                llap_origins[llap->llap_origin]);
598
599                 /* If page is dirty or undergoing IO don't discard it */
600                 if (keep) {
601                         unlock_page(page);
602                         continue;
603                 }
604
605                 page_cache_get(page);
606                 ll_pglist_cpu_unlock(sbi, cpu);
607
608                 if (page->mapping != NULL) {
609                         ll_teardown_mmaps(page->mapping,
610                                          (__u64)page->index << CFS_PAGE_SHIFT,
611                                          ((__u64)page->index << CFS_PAGE_SHIFT)|
612                                           ~CFS_PAGE_MASK);
613                         if (!PageDirty(page) && !page_mapped(page)) {
614                                 ll_ra_accounting(llap, page->mapping);
615                                 ll_truncate_complete_page(page);
616                                 ++count;
617                         } else {
618                                 LL_CDEBUG_PAGE(D_PAGE, page,
619                                                "Not dropping page because it is"
620                                                " %s\n", PageDirty(page) ?
621                                                "dirty" : "mapped");
622                         }
623                 }
624                 unlock_page(page);
625                 page_cache_release(page);
626
627                 ll_pglist_cpu_lock(sbi, cpu);
628         }
629         list_del(&dummy_llap.llap_pglist_item);
630         ll_pglist_cpu_unlock(sbi, cpu);
631
632         CDEBUG(D_CACHE, "shrank %d, expected %d however. \n", count, target);
633         return count;
634 }
635
636
637 /* Try to shrink the page cache for the @sbi filesystem by 1/@shrink_fraction.
638  *
639  * At first, this code calculates total pages wanted by @shrink_fraction, then
640  * it deduces how many pages should be reaped from each cpu in proportion as
641  * their own # of page count(llpd_count).
642  */
643 int llap_shrink_cache(struct ll_sb_info *sbi, int nr_to_scan)
644 {
645         unsigned long total, want, percpu_want, count = 0;
646         int cpu, nr_cpus;
647
648         total = lcounter_read_positive(&sbi->ll_async_page_count);
649         if (total == 0 || nr_to_scan == 0)
650                 return total;
651
652         want = nr_to_scan;
653
654         /* Since we are freeing pages also, we don't necessarily want to
655          * shrink so much.  Limit to 40MB of pages + llaps per call. */
656         if (want > 40 << (20 - CFS_PAGE_SHIFT))
657                 want = 40 << (20 - CFS_PAGE_SHIFT);
658
659         CDEBUG(D_CACHE, "shrinking %lu of %lu pages (asked for %u)\n",
660                want, total, nr_to_scan);
661
662         nr_cpus = num_possible_cpus();
663         cpu = sbi->ll_async_page_clock_hand;
664         /* we at most do one round */
665         do {
666                 int c;
667
668                 cpu = (cpu + 1) % nr_cpus;
669                 c = LL_PGLIST_DATA_CPU(sbi, cpu)->llpd_count;
670                 if (!cpu_online(cpu))
671                         percpu_want = c;
672                 else
673                         percpu_want = want / ((total / (c + 1)) + 1);
674                 if (percpu_want == 0)
675                         continue;
676
677                 count += llap_shrink_cache_internal(sbi, cpu, percpu_want);
678                 if (count >= want)
679                         sbi->ll_async_page_clock_hand = cpu;
680         } while (cpu != sbi->ll_async_page_clock_hand);
681
682         CDEBUG(D_CACHE, "shrank %lu/%lu and left %lu unscanned\n",
683                count, want, total);
684
685         return lcounter_read_positive(&sbi->ll_async_page_count);
686 }
687
688 /* Rebalance the async page queue len for each cpu. We hope that the cpu
689  * which do much IO job has a relative longer queue len.
690  * This function should be called with preempt disabled.
691  */
692 static inline int llap_async_cache_rebalance(struct ll_sb_info *sbi)
693 {
694         unsigned long sample = 0, *cpu_sample, bias, slice;
695         struct ll_pglist_data *pd;
696         cpumask_t mask;
697         int cpu, surplus;
698         int w1 = 7, w2 = 3, base = (w1 + w2); /* weight value */
699         atomic_t *pcnt;
700
701         if (!spin_trylock(&sbi->ll_async_page_reblnc_lock)) {
702                 /* someone else is doing the job */
703                 return 1;
704         }
705
706         pcnt = &LL_PGLIST_DATA(sbi)->llpd_sample_count;
707         if (!atomic_read(pcnt)) {
708                 /* rare case, somebody else has gotten this job done */
709                 spin_unlock(&sbi->ll_async_page_reblnc_lock);
710                 return 1;
711         }
712
713         sbi->ll_async_page_reblnc_count++;
714         cpu_sample = sbi->ll_async_page_sample;
715         memset(cpu_sample, 0, num_possible_cpus() * sizeof(unsigned long));
716         for_each_online_cpu(cpu) {
717                 pcnt = &LL_PGLIST_DATA_CPU(sbi, cpu)->llpd_sample_count;
718                 cpu_sample[cpu] = atomic_read(pcnt);
719                 atomic_set(pcnt, 0);
720                 sample += cpu_sample[cpu];
721         }
722
723         cpus_clear(mask);
724         surplus = sbi->ll_async_page_max;
725         slice = surplus / sample + 1;
726         sample /= num_online_cpus();
727         bias = sample >> 4;
728         for_each_online_cpu(cpu) {
729                 pd = LL_PGLIST_DATA_CPU(sbi, cpu);
730                 if (labs((long int)sample - cpu_sample[cpu]) > bias) {
731                         unsigned long budget = pd->llpd_budget;
732                         /* weighted original queue length and expected queue
733                          * length to avoid thrashing. */
734                         pd->llpd_budget = (budget * w1) / base +
735                                         (slice * cpu_sample[cpu]) * w2 / base;
736                         cpu_set(cpu, mask);
737                 }
738                 surplus -= min_t(int, pd->llpd_budget, surplus);
739         }
740         surplus /= cpus_weight(mask) ?: 1;
741         for_each_cpu_mask(cpu, mask)
742                 LL_PGLIST_DATA_CPU(sbi, cpu)->llpd_budget += surplus;
743         spin_unlock(&sbi->ll_async_page_reblnc_lock);
744
745         /* We need to call llap_shrink_cache_internal() for every cpu to
746          * ensure the sbi->ll_async_page_max limit is enforced. */
747         for_each_cpu_mask(cpu, mask) {
748                 pd = LL_PGLIST_DATA_CPU(sbi, cpu);
749                 llap_shrink_cache_internal(sbi, cpu, max_t(int, pd->llpd_count-
750                                            pd->llpd_budget, 0) + 32);
751         }
752
753         return 0;
754 }
755
756 static struct ll_async_page *llap_from_page_with_lockh(struct page *page,
757                                                        unsigned origin,
758                                                        struct lustre_handle *lockh,
759                                                        int flags)
760 {
761         struct ll_async_page *llap;
762         struct obd_export *exp;
763         struct inode *inode = page->mapping->host;
764         struct ll_sb_info *sbi;
765         struct ll_pglist_data *pd;
766         int rc, cpu, target;
767         ENTRY;
768
769         if (!inode) {
770                 static int triggered;
771
772                 if (!triggered) {
773                         LL_CDEBUG_PAGE(D_ERROR, page, "Bug 10047. Wrong anon "
774                                        "page received\n");
775                         libcfs_debug_dumpstack(NULL);
776                         triggered = 1;
777                 }
778                 RETURN(ERR_PTR(-EINVAL));
779         }
780         sbi = ll_i2sbi(inode);
781         LASSERT(ll_async_page_slab);
782         LASSERTF(origin < LLAP__ORIGIN_MAX, "%u\n", origin);
783
784         exp = ll_i2obdexp(page->mapping->host);
785         if (exp == NULL)
786                 RETURN(ERR_PTR(-EINVAL));
787
788         llap = llap_cast_private(page);
789         if (llap != NULL) {
790                 if (origin == LLAP_ORIGIN_READAHEAD && lockh) {
791                         /* the page could belong to another lock for which
792                          * we don't hold a reference. We need to check that
793                          * a reference is taken on a lock covering this page.
794                          * For readpage origin, this is fine because
795                          * ll_file_readv() took a reference on lock(s) covering
796                          * the whole read. However, for readhead, we don't have
797                          * this guarantee, so we need to check that the lock
798                          * matched in ll_file_readv() also covers this page */
799                         __u64 offset = ((loff_t)page->index) << CFS_PAGE_SHIFT;
800                         if (!obd_get_lock(exp, ll_i2info(inode)->lli_smd, 
801                                           &llap->llap_cookie, OBD_BRW_READ,
802                                           offset, offset + CFS_PAGE_SIZE - 1,
803                                           lockh, flags))
804                                 RETURN(ERR_PTR(-ENOLCK));
805                 }
806                 /* move to end of LRU list, except when page is just about to
807                  * die */
808                 if (origin != LLAP_ORIGIN_REMOVEPAGE) {
809                         int old_cpu = llap->llap_pglist_cpu;
810                         struct ll_pglist_data *old_pd;
811
812                         pd = ll_pglist_double_lock(sbi, old_cpu, &old_pd);
813                         pd->llpd_hit++;
814                         while (old_cpu != llap->llap_pglist_cpu) {
815                                 /* rarely case, someone else is touching this
816                                  * page too. */
817                                 ll_pglist_double_unlock(sbi, old_cpu);
818                                 old_cpu = llap->llap_pglist_cpu;
819                                 pd=ll_pglist_double_lock(sbi, old_cpu, &old_pd);
820                         }
821
822                         list_move(&llap->llap_pglist_item,
823                                   &pd->llpd_list);
824                         old_pd->llpd_gen++;
825                         if (pd->llpd_cpu != old_cpu) {
826                                 pd->llpd_count++;
827                                 old_pd->llpd_count--;
828                                 old_pd->llpd_gen++;
829                                 llap->llap_pglist_cpu = pd->llpd_cpu;
830                                 pd->llpd_cross++;
831                         }
832                         ll_pglist_double_unlock(sbi, old_cpu);
833                 }
834                 GOTO(out, llap);
835         }
836
837         /* limit the number of lustre-cached pages */
838         cpu = cfs_get_cpu();
839         pd = LL_PGLIST_DATA(sbi);
840         target = pd->llpd_count - pd->llpd_budget;
841         if (target > 0) {
842                 rc = 0;
843                 atomic_inc(&pd->llpd_sample_count);
844                 if (atomic_read(&pd->llpd_sample_count) >
845                     sbi->ll_async_page_sample_max) {
846                         pd->llpd_reblnc_count++;
847                         rc = llap_async_cache_rebalance(sbi);
848                         if (rc == 0)
849                                 target = pd->llpd_count - pd->llpd_budget;
850                 }
851                 /* if rc equals 1, it means other cpu is doing the rebalance
852                  * job, and our budget # would be modified when we read it.
853                  * Furthermore, it is much likely being increased because
854                  * we have already reached the rebalance threshold. In this
855                  * case, we skip to shrink cache here. */
856                 if ((rc == 0) && target > 0)
857                         llap_shrink_cache_internal(sbi, cpu, target + 32);
858         }
859         cfs_put_cpu();
860
861         OBD_SLAB_ALLOC(llap, ll_async_page_slab, CFS_ALLOC_STD,
862                        ll_async_page_slab_size);
863         if (llap == NULL)
864                 RETURN(ERR_PTR(-ENOMEM));
865         llap->llap_magic = LLAP_MAGIC;
866         llap->llap_cookie = (void *)llap + size_round(sizeof(*llap));
867
868         rc = obd_prep_async_page(exp, ll_i2info(inode)->lli_smd, NULL, page,
869                                  (obd_off)page->index << CFS_PAGE_SHIFT,
870                                  &ll_async_page_ops, llap, &llap->llap_cookie,
871                                  flags, lockh);
872         if (rc) {
873                 OBD_SLAB_FREE(llap, ll_async_page_slab,
874                               ll_async_page_slab_size);
875                 RETURN(ERR_PTR(rc));
876         }
877
878         CDEBUG(D_CACHE, "llap %p page %p cookie %p obj off "LPU64"\n", llap,
879                page, llap->llap_cookie, (obd_off)page->index << CFS_PAGE_SHIFT);
880         /* also zeroing the PRIVBITS low order bitflags */
881         __set_page_ll_data(page, llap);
882         llap->llap_page = page;
883
884         lcounter_inc(&sbi->ll_async_page_count);
885         pd = ll_pglist_lock(sbi);
886         list_add_tail(&llap->llap_pglist_item, &pd->llpd_list);
887         pd->llpd_count++;
888         pd->llpd_gen++;
889         pd->llpd_miss++;
890         llap->llap_pglist_cpu = pd->llpd_cpu;
891         ll_pglist_unlock(sbi);
892
893  out:
894         if (unlikely(sbi->ll_flags & LL_SBI_LLITE_CHECKSUM)) {
895                 __u32 csum;
896                 char *kaddr = kmap_atomic(page, KM_USER0);
897                 csum = init_checksum(OSC_DEFAULT_CKSUM);
898                 csum = compute_checksum(csum, kaddr, CFS_PAGE_SIZE,
899                                         OSC_DEFAULT_CKSUM);
900                 kunmap_atomic(kaddr, KM_USER0);
901                 if (origin == LLAP_ORIGIN_READAHEAD ||
902                     origin == LLAP_ORIGIN_READPAGE) {
903                         llap->llap_checksum = 0;
904                 } else if (origin == LLAP_ORIGIN_COMMIT_WRITE ||
905                            llap->llap_checksum == 0) {
906                         llap->llap_checksum = csum;
907                         CDEBUG(D_PAGE, "page %p cksum %x\n", page, csum);
908                 } else if (llap->llap_checksum == csum) {
909                         /* origin == LLAP_ORIGIN_WRITEPAGE */
910                         CDEBUG(D_PAGE, "page %p cksum %x confirmed\n",
911                                page, csum);
912                 } else {
913                         /* origin == LLAP_ORIGIN_WRITEPAGE */
914                         LL_CDEBUG_PAGE(D_ERROR, page, "old cksum %x != new "
915                                        "%x!\n", llap->llap_checksum, csum);
916                 }
917         }
918
919         llap->llap_origin = origin;
920         RETURN(llap);
921 }
922
923 static inline struct ll_async_page *llap_from_page(struct page *page,
924                                                    unsigned origin)
925 {
926         return llap_from_page_with_lockh(page, origin, NULL, 0);
927 }
928
929 static int queue_or_sync_write(struct obd_export *exp, struct inode *inode,
930                                struct ll_async_page *llap,
931                                unsigned to, obd_flag async_flags)
932 {
933         unsigned long size_index = i_size_read(inode) >> CFS_PAGE_SHIFT;
934         struct obd_io_group *oig;
935         struct ll_sb_info *sbi = ll_i2sbi(inode);
936         int rc, noquot = llap->llap_ignore_quota ? OBD_BRW_NOQUOTA : 0;
937         int brwflags = OBD_BRW_ASYNC;
938         ENTRY;
939
940         /* _make_ready only sees llap once we've unlocked the page */
941         llap->llap_write_queued = 1;
942         rc = obd_queue_async_io(exp, ll_i2info(inode)->lli_smd, NULL,
943                                 llap->llap_cookie, OBD_BRW_WRITE | noquot,
944                                 0, 0, brwflags, async_flags);
945         if (rc == 0) {
946                 LL_CDEBUG_PAGE(D_PAGE, llap->llap_page, "write queued\n");
947                 llap_write_pending(inode, llap);
948                 GOTO(out, 0);
949         }
950
951         llap->llap_write_queued = 0;
952
953         rc = oig_init(&oig);
954         if (rc)
955                 GOTO(out, rc);
956
957         /* make full-page requests if we are not at EOF (bug 4410) */
958         if (to != CFS_PAGE_SIZE && llap->llap_page->index < size_index) {
959                 LL_CDEBUG_PAGE(D_PAGE, llap->llap_page,
960                                "sync write before EOF: size_index %lu, to %d\n",
961                                size_index, to);
962                 to = CFS_PAGE_SIZE;
963         } else if (to != CFS_PAGE_SIZE && llap->llap_page->index == size_index){
964                 int size_to = i_size_read(inode) & ~CFS_PAGE_MASK;
965                 LL_CDEBUG_PAGE(D_PAGE, llap->llap_page,
966                                "sync write at EOF: size_index %lu, to %d/%d\n",
967                                size_index, to, size_to);
968                 if (to < size_to)
969                         to = size_to;
970         }
971
972         /* compare the checksum once before the page leaves llite */
973         if (unlikely((sbi->ll_flags & LL_SBI_LLITE_CHECKSUM) &&
974                      llap->llap_checksum != 0)) {
975                 __u32 csum;
976                 struct page *page = llap->llap_page;
977                 char *kaddr = kmap_atomic(page, KM_USER0);
978                 csum = init_checksum(OSC_DEFAULT_CKSUM);
979                 csum = compute_checksum(csum, kaddr, CFS_PAGE_SIZE,
980                                         OSC_DEFAULT_CKSUM);
981                 kunmap_atomic(kaddr, KM_USER0);
982                 if (llap->llap_checksum == csum) {
983                         CDEBUG(D_PAGE, "page %p cksum %x confirmed\n",
984                                page, csum);
985                 } else {
986                         CERROR("page %p old cksum %x != new cksum %x!\n",
987                                page, llap->llap_checksum, csum);
988                 }
989         }
990
991         rc = obd_queue_group_io(exp, ll_i2info(inode)->lli_smd, NULL, oig,
992                                 llap->llap_cookie, OBD_BRW_WRITE | noquot,
993                                 0, to, 0, ASYNC_READY | ASYNC_URGENT |
994                                 ASYNC_COUNT_STABLE | ASYNC_GROUP_SYNC);
995         if (rc)
996                 GOTO(free_oig, rc);
997
998         rc = obd_trigger_group_io(exp, ll_i2info(inode)->lli_smd, NULL, oig);
999         if (rc)
1000                 GOTO(free_oig, rc);
1001
1002         rc = oig_wait(oig);
1003
1004         if (!rc && async_flags & ASYNC_READY) {
1005                 unlock_page(llap->llap_page);
1006                 if (PageWriteback(llap->llap_page))
1007                         end_page_writeback(llap->llap_page);
1008         }
1009
1010         LL_CDEBUG_PAGE(D_PAGE, llap->llap_page, "sync write returned %d\n", rc);
1011
1012 free_oig:
1013         oig_release(oig);
1014 out:
1015         RETURN(rc);
1016 }
1017
1018 /* update our write count to account for i_size increases that may have
1019  * happened since we've queued the page for io. */
1020
1021 /* be careful not to return success without setting the page Uptodate or
1022  * the next pass through prepare_write will read in stale data from disk. */
1023 int ll_commit_write(struct file *file, struct page *page, unsigned from,
1024                     unsigned to)
1025 {
1026         struct ll_file_data *fd = LUSTRE_FPRIVATE(file);
1027         struct inode *inode = page->mapping->host;
1028         struct ll_inode_info *lli = ll_i2info(inode);
1029         struct lov_stripe_md *lsm = lli->lli_smd;
1030         struct obd_export *exp;
1031         struct ll_async_page *llap;
1032         loff_t size;
1033         struct lustre_handle *lockh = NULL;
1034         int rc = 0;
1035         ENTRY;
1036
1037         SIGNAL_MASK_ASSERT(); /* XXX BUG 1511 */
1038         LASSERT(inode == file->f_dentry->d_inode);
1039         LASSERT(PageLocked(page));
1040
1041         CDEBUG(D_INODE, "inode %p is writing page %p from %d to %d at %lu\n",
1042                inode, page, from, to, page->index);
1043
1044         if (fd->fd_flags & LL_FILE_GROUP_LOCKED)
1045                 lockh = &fd->fd_cwlockh;
1046
1047         llap = llap_from_page_with_lockh(page, LLAP_ORIGIN_COMMIT_WRITE, lockh,
1048                                          0);
1049         if (IS_ERR(llap))
1050                 RETURN(PTR_ERR(llap));
1051
1052         exp = ll_i2obdexp(inode);
1053         if (exp == NULL)
1054                 RETURN(-EINVAL);
1055
1056         llap->llap_ignore_quota = cfs_capable(CFS_CAP_SYS_RESOURCE);
1057
1058         /* queue a write for some time in the future the first time we
1059          * dirty the page */
1060         if (!PageDirty(page)) {
1061                 ll_stats_ops_tally(ll_i2sbi(inode), LPROC_LL_DIRTY_MISSES, 1);
1062
1063                 rc = queue_or_sync_write(exp, inode, llap, to, 0);
1064                 if (rc)
1065                         GOTO(out, rc);
1066         } else {
1067                 ll_stats_ops_tally(ll_i2sbi(inode), LPROC_LL_DIRTY_HITS, 1);
1068         }
1069
1070         /* put the page in the page cache, from now on ll_removepage is
1071          * responsible for cleaning up the llap.
1072          * only set page dirty when it's queued to be write out */
1073         if (llap->llap_write_queued)
1074                 set_page_dirty(page);
1075
1076 out:
1077         size = (((obd_off)page->index) << CFS_PAGE_SHIFT) + to;
1078         ll_inode_size_lock(inode, 0);
1079         if (rc == 0) {
1080                 lov_stripe_lock(lsm);
1081                 obd_adjust_kms(exp, lsm, size, 0);
1082                 lov_stripe_unlock(lsm);
1083                 if (size > i_size_read(inode))
1084                         i_size_write(inode, size);
1085                 SetPageUptodate(page);
1086         } else if (size > i_size_read(inode)) {
1087                 /* this page beyond the pales of i_size, so it can't be
1088                  * truncated in ll_p_r_e during lock revoking. we must
1089                  * teardown our book-keeping here. */
1090                 ll_removepage(page);
1091         }
1092         ll_inode_size_unlock(inode, 0);
1093         RETURN(rc);
1094 }
1095
1096 static void ll_ra_stats_inc_sbi(struct ll_sb_info *sbi, enum ra_stat which);
1097
1098 /* WARNING: This algorithm is used to reduce the contention on
1099  * sbi->ll_lock. It should work well if the ra_max_pages is much
1100  * greater than the single file's read-ahead window.
1101  *
1102  * TODO: There may exist a `global sync problem' in this implementation.
1103  * Considering the global ra window is 100M, and each file's ra window is 10M,
1104  * there are over 10 files trying to get its ra budget and reach
1105  * ll_ra_count_get at the exactly same time. All of them will get a zero ra
1106  * window, although the global window is 100M. -jay
1107  */
1108 static unsigned long ll_ra_count_get(struct ll_sb_info *sbi, unsigned long len)
1109 {
1110         struct ll_ra_info *ra = &sbi->ll_ra_info;
1111         unsigned long ret = 0;
1112         ENTRY;
1113
1114         /**
1115          * If read-ahead pages left are less than 1M, do not do read-ahead,
1116          * otherwise it will form small read RPC(< 1M), which hurt server
1117          * performance a lot.
1118          */
1119         ret = min(ra->ra_max_pages - atomic_read(&ra->ra_cur_pages), len);
1120         if ((int)ret < min((unsigned long)PTLRPC_MAX_BRW_PAGES, len))
1121                 GOTO(out, ret = 0);
1122
1123         if (atomic_add_return(ret, &ra->ra_cur_pages) > ra->ra_max_pages) {
1124                 atomic_sub(ret, &ra->ra_cur_pages);
1125                 ret = 0;
1126         }
1127 out:
1128         RETURN(ret);
1129 }
1130
1131 static void ll_ra_count_put(struct ll_sb_info *sbi, unsigned long len)
1132 {
1133         struct ll_ra_info *ra = &sbi->ll_ra_info;
1134         atomic_sub(len, &ra->ra_cur_pages);
1135 }
1136
1137 /* called for each page in a completed rpc.*/
1138 int ll_ap_completion(void *data, int cmd, struct obdo *oa, int rc)
1139 {
1140         struct ll_async_page *llap;
1141         struct page *page;
1142         int ret = 0;
1143         ENTRY;
1144
1145         llap = LLAP_FROM_COOKIE(data);
1146         page = llap->llap_page;
1147         LASSERT(PageLocked(page));
1148         LASSERT(CheckWriteback(page,cmd));
1149
1150         LL_CDEBUG_PAGE(D_PAGE, page, "completing cmd %d with %d\n", cmd, rc);
1151
1152         if (cmd & OBD_BRW_READ && llap->llap_defer_uptodate)
1153                 ll_ra_count_put(ll_i2sbi(page->mapping->host), 1);
1154
1155         if (rc == 0)  {
1156                 if (cmd & OBD_BRW_READ) {
1157                         if (!llap->llap_defer_uptodate)
1158                                 SetPageUptodate(page);
1159                 } else {
1160                         llap->llap_write_queued = 0;
1161                 }
1162                 ClearPageError(page);
1163         } else {
1164                 if (cmd & OBD_BRW_READ) {
1165                         llap->llap_defer_uptodate = 0;
1166                 }
1167                 SetPageError(page);
1168                 if (rc == -ENOSPC)
1169                         set_bit(AS_ENOSPC, &page->mapping->flags);
1170                 else
1171                         set_bit(AS_EIO, &page->mapping->flags);
1172         }
1173
1174         /* be carefull about clear WB.
1175          * if WB will cleared after page lock is released - paralel IO can be
1176          * started before ap_make_ready is finished - so we will be have page
1177          * with PG_Writeback set from ->writepage() and completed READ which
1178          * clear this flag */
1179         if ((cmd & OBD_BRW_WRITE) && PageWriteback(page))
1180                 end_page_writeback(page);
1181
1182         unlock_page(page);
1183
1184         if (cmd & OBD_BRW_WRITE) {
1185                 llap_write_complete(page->mapping->host, llap);
1186                 ll_try_done_writing(page->mapping->host);
1187         }
1188
1189         page_cache_release(page);
1190
1191         RETURN(ret);
1192 }
1193
1194 static void __ll_put_llap(struct page *page)
1195 {
1196         struct inode *inode = page->mapping->host;
1197         struct obd_export *exp;
1198         struct ll_async_page *llap;
1199         struct ll_sb_info *sbi = ll_i2sbi(inode);
1200         struct ll_pglist_data *pd;
1201         int rc, cpu;
1202         ENTRY;
1203
1204         exp = ll_i2obdexp(inode);
1205         if (exp == NULL) {
1206                 CERROR("page %p ind %lu gave null export\n", page, page->index);
1207                 EXIT;
1208                 return;
1209         }
1210
1211         llap = llap_from_page(page, LLAP_ORIGIN_REMOVEPAGE);
1212         if (IS_ERR(llap)) {
1213                 CERROR("page %p ind %lu couldn't find llap: %ld\n", page,
1214                        page->index, PTR_ERR(llap));
1215                 EXIT;
1216                 return;
1217         }
1218
1219         //llap_write_complete(inode, llap);
1220         rc = obd_teardown_async_page(exp, ll_i2info(inode)->lli_smd, NULL,
1221                                      llap->llap_cookie);
1222         if (rc != 0)
1223                 CERROR("page %p ind %lu failed: %d\n", page, page->index, rc);
1224
1225         /* this unconditional free is only safe because the page lock
1226          * is providing exclusivity to memory pressure/truncate/writeback..*/
1227         __clear_page_ll_data(page);
1228
1229         lcounter_dec(&sbi->ll_async_page_count);
1230         cpu = llap->llap_pglist_cpu;
1231         pd = ll_pglist_cpu_lock(sbi, cpu);
1232         pd->llpd_gen++;
1233         pd->llpd_count--;
1234         if (!list_empty(&llap->llap_pglist_item))
1235                 list_del_init(&llap->llap_pglist_item);
1236         ll_pglist_cpu_unlock(sbi, cpu);
1237         OBD_SLAB_FREE(llap, ll_async_page_slab, ll_async_page_slab_size);
1238
1239         EXIT;
1240 }
1241
1242 /* the kernel calls us here when a page is unhashed from the page cache.
1243  * the page will be locked and the kernel is holding a spinlock, so
1244  * we need to be careful.  we're just tearing down our book-keeping
1245  * here. */
1246 void ll_removepage(struct page *page)
1247 {
1248         struct ll_async_page *llap = llap_cast_private(page);
1249         ENTRY;
1250
1251         LASSERT(!in_interrupt());
1252
1253         /* sync pages or failed read pages can leave pages in the page
1254          * cache that don't have our data associated with them anymore */
1255         if (page_private(page) == 0) {
1256                 EXIT;
1257                 return;
1258         }
1259
1260         ll_ra_accounting(llap, page->mapping);
1261         LL_CDEBUG_PAGE(D_PAGE, page, "being evicted\n");
1262         __ll_put_llap(page);
1263
1264         EXIT;
1265 }
1266
1267 static int ll_issue_page_read(struct obd_export *exp,
1268                               struct ll_async_page *llap,
1269                               struct obd_io_group *oig, int defer)
1270 {
1271         struct page *page = llap->llap_page;
1272         int rc;
1273
1274         page_cache_get(page);
1275         llap->llap_defer_uptodate = defer;
1276         llap->llap_ra_used = 0;
1277         rc = obd_queue_group_io(exp, ll_i2info(page->mapping->host)->lli_smd,
1278                                 NULL, oig, llap->llap_cookie, OBD_BRW_READ, 0,
1279                                 CFS_PAGE_SIZE, 0, ASYNC_COUNT_STABLE |
1280                                 ASYNC_READY | ASYNC_URGENT);
1281         if (rc) {
1282                 LL_CDEBUG_PAGE(D_ERROR, page, "read queue failed: rc %d\n", rc);
1283                 page_cache_release(page);
1284         }
1285         RETURN(rc);
1286 }
1287
1288 static void ll_ra_stats_inc_sbi(struct ll_sb_info *sbi, enum ra_stat which)
1289 {
1290         LASSERTF(which >= 0 && which < _NR_RA_STAT, "which: %u\n", which);
1291         lprocfs_counter_incr(sbi->ll_ra_stats, which);
1292 }
1293
1294 static void ll_ra_stats_inc(struct address_space *mapping, enum ra_stat which)
1295 {
1296         struct ll_sb_info *sbi = ll_i2sbi(mapping->host);
1297         ll_ra_stats_inc_sbi(sbi, which);
1298 }
1299
1300 void ll_ra_accounting(struct ll_async_page *llap, struct address_space *mapping)
1301 {
1302         if (!llap->llap_defer_uptodate || llap->llap_ra_used)
1303                 return;
1304
1305         ll_ra_stats_inc(mapping, RA_STAT_DISCARDED);
1306 }
1307
1308 #define RAS_CDEBUG(ras) \
1309         CDEBUG(D_READA,                                                      \
1310                "lrp %lu cr %lu cp %lu ws %lu wl %lu nra %lu r %lu ri %lu"    \
1311                "csr %lu sf %lu sp %lu sl %lu \n",                            \
1312                ras->ras_last_readpage, ras->ras_consecutive_requests,        \
1313                ras->ras_consecutive_pages, ras->ras_window_start,            \
1314                ras->ras_window_len, ras->ras_next_readahead,                 \
1315                ras->ras_requests, ras->ras_request_index,                    \
1316                ras->ras_consecutive_stride_requests, ras->ras_stride_offset, \
1317                ras->ras_stride_pages, ras->ras_stride_length)
1318
1319 static int index_in_window(unsigned long index, unsigned long point,
1320                            unsigned long before, unsigned long after)
1321 {
1322         unsigned long start = point - before, end = point + after;
1323
1324         if (start > point)
1325                start = 0;
1326         if (end < point)
1327                end = ~0;
1328
1329         return start <= index && index <= end;
1330 }
1331
1332 struct ll_thread_data *ll_td_get()
1333 {
1334         struct ll_thread_data *ltd = current->journal_info;
1335
1336         LASSERT(ltd == NULL || ltd->ltd_magic == LTD_MAGIC);
1337         return ltd;
1338 }
1339
1340 void ll_td_set(struct ll_thread_data *ltd)
1341 {
1342         if (ltd == NULL) {
1343                 ltd = current->journal_info;
1344                 LASSERT(ltd == NULL || ltd->ltd_magic == LTD_MAGIC);
1345                 current->journal_info = NULL;
1346                 return;
1347         }
1348
1349         LASSERT(current->journal_info == NULL);
1350         LASSERT(ltd->ltd_magic == LTD_MAGIC);
1351         current->journal_info = ltd;
1352 }
1353
1354 static struct ll_readahead_state *ll_ras_get(struct file *f)
1355 {
1356         struct ll_file_data       *fd;
1357
1358         fd = LUSTRE_FPRIVATE(f);
1359         return &fd->fd_ras;
1360 }
1361
1362 void ll_ra_read_init(struct file *f, struct ll_ra_read *rar,
1363                      loff_t offset, size_t count)
1364 {
1365         struct ll_readahead_state *ras;
1366
1367         ras = ll_ras_get(f);
1368
1369         rar->lrr_start = offset >> CFS_PAGE_SHIFT;
1370         rar->lrr_count = (count + CFS_PAGE_SIZE - 1) >> CFS_PAGE_SHIFT;
1371
1372         spin_lock(&ras->ras_lock);
1373         ras->ras_requests++;
1374         ras->ras_request_index = 0;
1375         ras->ras_consecutive_requests++;
1376         rar->lrr_reader = current;
1377
1378         list_add(&rar->lrr_linkage, &ras->ras_read_beads);
1379         spin_unlock(&ras->ras_lock);
1380 }
1381
1382 void ll_ra_read_ex(struct file *f, struct ll_ra_read *rar)
1383 {
1384         struct ll_readahead_state *ras;
1385
1386         ras = ll_ras_get(f);
1387
1388         spin_lock(&ras->ras_lock);
1389         list_del_init(&rar->lrr_linkage);
1390         spin_unlock(&ras->ras_lock);
1391 }
1392
1393 static struct ll_ra_read *ll_ra_read_get_locked(struct ll_readahead_state *ras)
1394 {
1395         struct ll_ra_read *scan;
1396
1397         list_for_each_entry(scan, &ras->ras_read_beads, lrr_linkage) {
1398                 if (scan->lrr_reader == current)
1399                         return scan;
1400         }
1401         return NULL;
1402 }
1403
1404 struct ll_ra_read *ll_ra_read_get(struct file *f)
1405 {
1406         struct ll_readahead_state *ras;
1407         struct ll_ra_read         *bead;
1408
1409         ras = ll_ras_get(f);
1410
1411         spin_lock(&ras->ras_lock);
1412         bead = ll_ra_read_get_locked(ras);
1413         spin_unlock(&ras->ras_lock);
1414         return bead;
1415 }
1416
1417 static int ll_read_ahead_page(struct obd_export *exp, struct obd_io_group *oig,
1418                               pgoff_t index, struct address_space *mapping)
1419 {
1420         struct ll_async_page *llap;
1421         struct page *page;
1422         unsigned int gfp_mask = 0;
1423         int rc = 0, flags = 0;
1424         struct ll_thread_data *ltd;
1425         struct lustre_handle *lockh = NULL;
1426
1427         gfp_mask = GFP_HIGHUSER & ~__GFP_WAIT;
1428 #ifdef __GFP_NOWARN
1429         gfp_mask |= __GFP_NOWARN;
1430 #endif
1431         page = grab_cache_page_nowait_gfp(mapping, index, gfp_mask);
1432         if (page == NULL) {
1433                 ll_ra_stats_inc(mapping, RA_STAT_FAILED_GRAB_PAGE);
1434                 CDEBUG(D_READA, "g_c_p_n failed\n");
1435                 return 0;
1436         }
1437
1438         /* Check if page was truncated or reclaimed */
1439         if (page->mapping != mapping) {
1440                 ll_ra_stats_inc(mapping, RA_STAT_WRONG_GRAB_PAGE);
1441                 CDEBUG(D_READA, "g_c_p_n returned invalid page\n");
1442                 GOTO(unlock_page, rc = 0);
1443         }
1444
1445         ltd = ll_td_get();
1446         if (ltd && ltd->lock_style > 0) {
1447                 __u64 offset = ((loff_t)page->index) << CFS_PAGE_SHIFT;
1448                 lockh = ltd2lockh(ltd, offset,
1449                                   offset + CFS_PAGE_SIZE - 1);
1450                 if (ltd->lock_style == LL_LOCK_STYLE_FASTLOCK)
1451                         flags = OBD_FAST_LOCK;
1452         }
1453
1454         /* we do this first so that we can see the page in the /proc
1455          * accounting */
1456         llap = llap_from_page_with_lockh(page, LLAP_ORIGIN_READAHEAD, lockh,
1457                                          flags);
1458         if (IS_ERR(llap) || llap->llap_defer_uptodate) {
1459                 if (PTR_ERR(llap) == -ENOLCK) {
1460                         ll_ra_stats_inc(mapping, RA_STAT_FAILED_MATCH);
1461                         CDEBUG(D_READA | D_PAGE,
1462                                "Adding page to cache failed index "
1463                                 "%ld\n", index);
1464                                 CDEBUG(D_READA, "nolock page\n");
1465                                 GOTO(unlock_page, rc = -ENOLCK);
1466                 }
1467                 CDEBUG(D_READA, "read-ahead page\n");
1468                 GOTO(unlock_page, rc = 0);
1469         }
1470
1471         /* skip completed pages */
1472         if (Page_Uptodate(page))
1473                 GOTO(unlock_page, rc = 0);
1474
1475         /* bail out when we hit the end of the lock. */
1476         rc = ll_issue_page_read(exp, llap, oig, 1);
1477         if (rc == 0) {
1478                 LL_CDEBUG_PAGE(D_READA | D_PAGE, page, "started read-ahead\n");
1479                 rc = 1;
1480         } else {
1481 unlock_page:
1482                 unlock_page(page);
1483                 LL_CDEBUG_PAGE(D_READA | D_PAGE, page, "skipping read-ahead\n");
1484         }
1485         page_cache_release(page);
1486         return rc;
1487 }
1488
1489 /* ra_io_arg will be filled in the beginning of ll_readahead with
1490  * ras_lock, then the following ll_read_ahead_pages will read RA
1491  * pages according to this arg, all the items in this structure are
1492  * counted by page index.
1493  */
1494 struct ra_io_arg {
1495         unsigned long ria_start;  /* start offset of read-ahead*/
1496         unsigned long ria_end;    /* end offset of read-ahead*/
1497         /* If stride read pattern is detected, ria_stoff means where
1498          * stride read is started. Note: for normal read-ahead, the
1499          * value here is meaningless, and also it will not be accessed*/
1500         pgoff_t ria_stoff;
1501         /* ria_length and ria_pages are the length and pages length in the
1502          * stride I/O mode. And they will also be used to check whether
1503          * it is stride I/O read-ahead in the read-ahead pages*/
1504         unsigned long ria_length;
1505         unsigned long ria_pages;
1506 };
1507
1508 #define RIA_DEBUG(ria)                                                \
1509         CDEBUG(D_READA, "rs %lu re %lu ro %lu rl %lu rp %lu\n",       \
1510         ria->ria_start, ria->ria_end, ria->ria_stoff, ria->ria_length,\
1511         ria->ria_pages)
1512
1513 #define INIT_RAS_WINDOW_PAGES PTLRPC_MAX_BRW_PAGES
1514
1515 static inline int stride_io_mode(struct ll_readahead_state *ras)
1516 {
1517         return ras->ras_consecutive_stride_requests > 1;
1518 }
1519
1520 /* The function calculates how much pages will be read in
1521  * [off, off + length], in such stride IO area,
1522  * stride_offset = st_off, stride_lengh = st_len,
1523  * stride_pages = st_pgs
1524  *
1525  *   |------------------|*****|------------------|*****|------------|*****|....
1526  * st_off
1527  *   |--- st_pgs     ---|
1528  *   |-----     st_len   -----|
1529  *
1530  *              How many pages it should read in such pattern
1531  *              |-------------------------------------------------------------|
1532  *              off
1533  *              |<------                  length                      ------->|
1534  *
1535  *          =   |<----->|  +  |-------------------------------------| +   |---|
1536  *             start_left                 st_pgs * i                    end_left
1537  */
1538 static unsigned long
1539 stride_pg_count(pgoff_t st_off, unsigned long st_len, unsigned long st_pgs,
1540                 unsigned long off, unsigned long length)
1541 {
1542         unsigned long start = off > st_off ? off - st_off : 0;
1543         unsigned long end = off + length > st_off ? off + length - st_off : 0;
1544         unsigned long start_left = 0;
1545         unsigned long end_left = 0;
1546         unsigned long pg_count;
1547
1548         if (st_len == 0 || length == 0 || end == 0)
1549                 return length;
1550
1551         start_left = do_div(start, st_len);
1552         if (start_left < st_pgs)
1553                 start_left = st_pgs - start_left;
1554         else
1555                 start_left = 0;
1556
1557         end_left = do_div(end, st_len);
1558         if (end_left > st_pgs)
1559                 end_left = st_pgs;
1560
1561         CDEBUG(D_READA, "start %lu, end %lu start_left %lu end_left %lu \n",
1562                start, end, start_left, end_left);
1563
1564         if (start == end)
1565                 pg_count = end_left - (st_pgs - start_left);
1566         else
1567                 pg_count = start_left + st_pgs * (end - start - 1) + end_left;
1568
1569         CDEBUG(D_READA, "st_off %lu, st_len %lu st_pgs %lu off %lu length %lu"
1570                "pgcount %lu\n", st_off, st_len, st_pgs, off, length, pg_count);
1571
1572         return pg_count;
1573 }
1574
1575 static int ria_page_count(struct ra_io_arg *ria)
1576 {
1577         __u64 length = ria->ria_end >= ria->ria_start ?
1578                        ria->ria_end - ria->ria_start + 1 : 0;
1579
1580         return stride_pg_count(ria->ria_stoff, ria->ria_length,
1581                                ria->ria_pages, ria->ria_start,
1582                                length);
1583 }
1584
1585 /*Check whether the index is in the defined ra-window */
1586 static int ras_inside_ra_window(unsigned long idx, struct ra_io_arg *ria)
1587 {
1588         /* If ria_length == ria_pages, it means non-stride I/O mode,
1589          * idx should always inside read-ahead window in this case
1590          * For stride I/O mode, just check whether the idx is inside
1591          * the ria_pages. */
1592         return ria->ria_length == 0 || ria->ria_length == ria->ria_pages ||
1593                (idx - ria->ria_stoff) % ria->ria_length < ria->ria_pages;
1594 }
1595
1596 static int ll_read_ahead_pages(struct obd_export *exp,
1597                                struct obd_io_group *oig,
1598                                struct ra_io_arg *ria,
1599                                unsigned long *reserved_pages,
1600                                struct address_space *mapping,
1601                                unsigned long *ra_end)
1602 {
1603         int rc, count = 0, stride_ria;
1604         unsigned long page_idx;
1605
1606         LASSERT(ria != NULL);
1607         RIA_DEBUG(ria);
1608
1609         stride_ria = ria->ria_length > ria->ria_pages && ria->ria_pages > 0;
1610         for (page_idx = ria->ria_start; page_idx <= ria->ria_end &&
1611                         *reserved_pages > 0; page_idx++) {
1612                 if (ras_inside_ra_window(page_idx, ria)) {
1613                         /* If the page is inside the read-ahead window*/
1614                         rc = ll_read_ahead_page(exp, oig, page_idx, mapping);
1615                         if (rc == 1) {
1616                                 (*reserved_pages)--;
1617                                 count ++;
1618                         } else if (rc == -ENOLCK)
1619                                 break;
1620                 } else if (stride_ria) {
1621                         /* If it is not in the read-ahead window, and it is
1622                          * read-ahead mode, then check whether it should skip
1623                          * the stride gap */
1624                         pgoff_t offset;
1625                         /* FIXME: This assertion only is valid when it is for
1626                          * forward read-ahead, it will be fixed when backward
1627                          * read-ahead is implemented */
1628                         LASSERTF(page_idx > ria->ria_stoff, "since %lu in the"
1629                                 " gap of ra window,it should bigger than stride"
1630                                 " offset %lu \n", page_idx, ria->ria_stoff);
1631
1632                         offset = page_idx - ria->ria_stoff;
1633                         offset = offset % (ria->ria_length);
1634                         if (offset > ria->ria_pages) {
1635                                 page_idx += ria->ria_length - offset;
1636                                 CDEBUG(D_READA, "i %lu skip %lu \n", page_idx,
1637                                        ria->ria_length - offset);
1638                                 continue;
1639                         }
1640                 }
1641         }
1642         *ra_end = page_idx;
1643         return count;
1644 }
1645
1646
1647 /**
1648  * Current readahead process 
1649  *          read_syscall
1650  *              |
1651  *       ll_file_readv (init ll_readahead_state for the open file)
1652  *              |
1653  *              |
1654  *   |---> ll_readpage (read page)
1655  *   |          |
1656  *   |          |
1657  *   |     ras_update  (update read-ahead window according to read pattern) 
1658  *   |          | 
1659  *   |          |
1660  *   |--- ll_readahead  (read_ahead pages)
1661  *
1662  *
1663  *  During this process, ras_update controls how many ahead pages it should
1664  *  read by adjusting read-ahead window(RA window).The window is represented 
1665  *  by following three varibles (all these values are counted by pages)
1666  *        
1667  *      1. ras_window_start: start offset of the read-ahead window. It is 
1668  *                           initialized as the read offset, then as pages
1669  *                           are being read, it will be set as the last 
1670  *                           page(Note: it is 1M aligned, so it actually
1671  *                           is last_page_index & ~index & (~(256 - 1)); 
1672  *      
1673  *      2. ras_window_len: length of the read-ahead window. The read-ahead window
1674  *                         length is decided by two factors
1675  *                         
1676  *                         a. It is at least >= current read syscall length.
1677  *                         b. If continguous read is detected, (Note: it is syscall
1678  *                            continguous, intead of page-read contingous) the
1679  *                            read-ahead window len will be increased by 1M each
1680  *                            time.
1681  *                         c. If stride read pattern is detected, the read-ahead
1682  *                            window will also be increased 1M but by stride pattern.
1683  *                            stride pattern is defined by ras_stride_length, 
1684  *                            ras_stride_pages and ras_stride_gap. (see 
1685  *                            ll_readahead_states comments)
1686  *
1687  *      3. ras_next_readahead: current offset in the read-ahead window, i.e. where
1688  *                             ll_readahead will start in next next-ahead.
1689  * 
1690  *   
1691  *  Cache miss: If memory load is very high, it begins to evicted the page from cache,
1692  *  also includes read-ahead pages, once we found read-ahead page is being evicted before
1693  *  it is "really" accessed, it will reset the read-ahead window to the current read extent 
1694  *  i.e. from current page to the end of this read.
1695  *
1696  *  In flight read-ahead amount is controlled by 2 varible (read-ahead rate)
1697  *       ra_max_pages: how much max in-flight read-ahead pages on the client.
1698  *       ra_max_pages_per_file: how much max in-flight read-ahead pages per file.
1699  **/
1700
1701
1702
1703 static int ll_readahead(struct ll_readahead_state *ras,
1704                         struct obd_export *exp, struct address_space *mapping,
1705                         struct obd_io_group *oig, int flags)
1706 {
1707         unsigned long start = 0, end = 0, reserved;
1708         unsigned long ra_end, len;
1709         struct inode *inode;
1710         struct lov_stripe_md *lsm;
1711         struct ll_ra_read *bead;
1712         struct ost_lvb lvb;
1713         struct ra_io_arg ria = { 0 };
1714         int ret = 0;
1715         __u64 kms;
1716         ENTRY;
1717
1718         inode = mapping->host;
1719         lsm = ll_i2info(inode)->lli_smd;
1720
1721         lov_stripe_lock(lsm);
1722         inode_init_lvb(inode, &lvb);
1723         obd_merge_lvb(ll_i2obdexp(inode), lsm, &lvb, 1);
1724         kms = lvb.lvb_size;
1725         lov_stripe_unlock(lsm);
1726         if (kms == 0) {
1727                 ll_ra_stats_inc(mapping, RA_STAT_ZERO_LEN);
1728                 RETURN(0);
1729         }
1730
1731         spin_lock(&ras->ras_lock);
1732         bead = ll_ra_read_get_locked(ras);
1733         /* Enlarge the RA window to encompass the full read */
1734         if (bead != NULL && ras->ras_window_start + ras->ras_window_len <
1735             bead->lrr_start + bead->lrr_count) {
1736                 obd_off read_end = ((obd_off)(bead->lrr_start +
1737                                               bead->lrr_count))<<CFS_PAGE_SHIFT;
1738                 obd_extent_calc(exp, lsm, OBD_CALC_STRIPE_RPC_END_ALIGN,
1739                                 &read_end);
1740                 ras->ras_window_len = ((read_end + 1) >> CFS_PAGE_SHIFT) -
1741                                       ras->ras_window_start;
1742         }
1743         /* Reserve a part of the read-ahead window that we'll be issuing */
1744         if (ras->ras_window_len) {
1745                 start = ras->ras_next_readahead;
1746                 end = ras->ras_window_start + ras->ras_window_len - 1;
1747         }
1748         if (end != 0) {
1749                 /* Truncate RA window to end of file */
1750                 end = min(end, (unsigned long)((kms - 1) >> CFS_PAGE_SHIFT));
1751                 ras->ras_next_readahead = max(end, end + 1);
1752                 RAS_CDEBUG(ras);
1753         }
1754         ria.ria_start = start;
1755         ria.ria_end = end;
1756         /* If stride I/O mode is detected, get stride window*/
1757         if (stride_io_mode(ras)) {
1758                 ria.ria_stoff = ras->ras_stride_offset;
1759                 ria.ria_length = ras->ras_stride_length;
1760                 ria.ria_pages = ras->ras_stride_pages;
1761         }
1762         spin_unlock(&ras->ras_lock);
1763
1764         if (end == 0) {
1765                 ll_ra_stats_inc(mapping, RA_STAT_ZERO_WINDOW);
1766                 RETURN(0);
1767         }
1768
1769         len = ria_page_count(&ria);
1770         if (len == 0)
1771                 RETURN(0);
1772
1773         reserved = ll_ra_count_get(ll_i2sbi(inode), len);
1774         if (reserved < len)
1775                 ll_ra_stats_inc(mapping, RA_STAT_MAX_IN_FLIGHT);
1776
1777         CDEBUG(D_READA, "reserved page %lu \n", reserved);
1778
1779         ret = ll_read_ahead_pages(exp, oig, &ria, &reserved, mapping, &ra_end);
1780
1781         LASSERTF(reserved >= 0, "reserved %lu\n", reserved);
1782         if (reserved != 0)
1783                 ll_ra_count_put(ll_i2sbi(inode), reserved);
1784
1785         if (ra_end == end + 1 && ra_end == (kms >> CFS_PAGE_SHIFT))
1786                 ll_ra_stats_inc(mapping, RA_STAT_EOF);
1787
1788         /* if we didn't get to the end of the region we reserved from
1789          * the ras we need to go back and update the ras so that the
1790          * next read-ahead tries from where we left off.  we only do so
1791          * if the region we failed to issue read-ahead on is still ahead
1792          * of the app and behind the next index to start read-ahead from */
1793         CDEBUG(D_READA, "ra_end %lu end %lu stride end %lu \n",
1794                ra_end, end, ria.ria_end);
1795
1796         if (ra_end != (end + 1)) {
1797                 spin_lock(&ras->ras_lock);
1798                 if (ra_end < ras->ras_next_readahead &&
1799                     index_in_window(ra_end, ras->ras_window_start, 0,
1800                                     ras->ras_window_len)) {
1801                         ras->ras_next_readahead = ra_end;
1802                         RAS_CDEBUG(ras);
1803                 }
1804                 spin_unlock(&ras->ras_lock);
1805         }
1806
1807         RETURN(ret);
1808 }
1809
1810 static void ras_set_start(struct ll_readahead_state *ras, unsigned long index)
1811 {
1812         ras->ras_window_start = index & (~(INIT_RAS_WINDOW_PAGES - 1));
1813 }
1814
1815 /* called with the ras_lock held or from places where it doesn't matter */
1816 static void ras_reset(struct ll_readahead_state *ras, unsigned long index)
1817 {
1818         ras->ras_last_readpage = index;
1819         ras->ras_consecutive_requests = 0;
1820         ras->ras_consecutive_pages = 0;
1821         ras->ras_window_len = 0;
1822         ras_set_start(ras, index);
1823         ras->ras_next_readahead = max(ras->ras_window_start, index);
1824
1825         RAS_CDEBUG(ras);
1826 }
1827
1828 /* called with the ras_lock held or from places where it doesn't matter */
1829 static void ras_stride_reset(struct ll_readahead_state *ras)
1830 {
1831         ras->ras_consecutive_stride_requests = 0;
1832         ras->ras_stride_length = 0;
1833         ras->ras_stride_pages = 0;
1834         RAS_CDEBUG(ras);
1835 }
1836
1837 void ll_readahead_init(struct inode *inode, struct ll_readahead_state *ras)
1838 {
1839         spin_lock_init(&ras->ras_lock);
1840         ras_reset(ras, 0);
1841         ras->ras_requests = 0;
1842         INIT_LIST_HEAD(&ras->ras_read_beads);
1843 }
1844
1845 /*
1846  * Check whether the read request is in the stride window.
1847  * If it is in the stride window, return 1, otherwise return 0.
1848  */
1849 static int index_in_stride_window(unsigned long index,
1850                                   struct ll_readahead_state *ras,
1851                                   struct inode *inode)
1852 {
1853         unsigned long stride_gap = index - ras->ras_last_readpage - 1;
1854
1855         if (ras->ras_stride_length == 0 || ras->ras_stride_pages == 0 ||
1856             ras->ras_stride_pages == ras->ras_stride_length)
1857                 return 0;
1858
1859         /* If it is contiguous read */
1860         if (stride_gap == 0)
1861                 return ras->ras_consecutive_pages + 1 <= ras->ras_stride_pages;
1862
1863         /*Otherwise check the stride by itself */
1864         return (ras->ras_stride_length - ras->ras_stride_pages) == stride_gap &&
1865              ras->ras_consecutive_pages == ras->ras_stride_pages;
1866 }
1867
1868 static void ras_update_stride_detector(struct ll_readahead_state *ras,
1869                                        unsigned long index)
1870 {
1871         unsigned long stride_gap = index - ras->ras_last_readpage - 1;
1872
1873         if (!stride_io_mode(ras) && (stride_gap != 0 ||
1874              ras->ras_consecutive_stride_requests == 0)) {
1875                 ras->ras_stride_pages = ras->ras_consecutive_pages;
1876                 ras->ras_stride_length = stride_gap +ras->ras_consecutive_pages;
1877         }
1878         LASSERT(ras->ras_request_index == 0);
1879         LASSERT(ras->ras_consecutive_stride_requests == 0);
1880
1881         if (index <= ras->ras_last_readpage) {
1882                 /*Reset stride window for forward read*/
1883                 ras_stride_reset(ras);
1884                 return;
1885         }
1886
1887         ras->ras_stride_pages = ras->ras_consecutive_pages;
1888         ras->ras_stride_length = stride_gap +ras->ras_consecutive_pages;
1889
1890         RAS_CDEBUG(ras);
1891         return;
1892 }
1893
1894 static unsigned long
1895 stride_page_count(struct ll_readahead_state *ras, unsigned long len)
1896 {
1897         return stride_pg_count(ras->ras_stride_offset, ras->ras_stride_length,
1898                                ras->ras_stride_pages, ras->ras_stride_offset,
1899                                len);
1900 }
1901
1902 /* Stride Read-ahead window will be increased inc_len according to
1903  * stride I/O pattern */
1904 static void ras_stride_increase_window(struct ll_readahead_state *ras,
1905                                        struct ll_ra_info *ra,
1906                                        unsigned long inc_len)
1907 {
1908         unsigned long left, step, window_len;
1909         unsigned long stride_len;
1910
1911         LASSERT(ras->ras_stride_length > 0);
1912         LASSERTF(ras->ras_window_start + ras->ras_window_len
1913                  >= ras->ras_stride_offset, "window_start %lu, window_len %lu"
1914                  " stride_offset %lu\n", ras->ras_window_start,
1915                  ras->ras_window_len, ras->ras_stride_offset);
1916
1917         stride_len = ras->ras_window_start + ras->ras_window_len -
1918                      ras->ras_stride_offset;
1919
1920         left = stride_len % ras->ras_stride_length;
1921         window_len = ras->ras_window_len - left;
1922
1923         if (left < ras->ras_stride_pages)
1924                 left += inc_len;
1925         else
1926                 left = ras->ras_stride_pages + inc_len;
1927
1928         LASSERT(ras->ras_stride_pages != 0);
1929
1930         step = left / ras->ras_stride_pages;
1931         left %= ras->ras_stride_pages;
1932
1933         window_len += step * ras->ras_stride_length + left;
1934
1935         if (stride_page_count(ras, window_len) <= ra->ra_max_pages_per_file)
1936                 ras->ras_window_len = window_len;
1937
1938         RAS_CDEBUG(ras);
1939 }
1940
1941 static void ras_increase_window(struct ll_readahead_state *ras,
1942                                 struct ll_ra_info *ra, struct inode *inode)
1943 {
1944         __u64 step;
1945         __u32 size;
1946         int rc;
1947
1948         step = ((loff_t)(ras->ras_window_start +
1949                          ras->ras_window_len)) << CFS_PAGE_SHIFT;
1950         size = sizeof(step);
1951         /*Get rpc_size for this offset (step) */
1952         rc = obd_get_info(ll_i2obdexp(inode), sizeof(KEY_OFF_RPCSIZE),
1953                           KEY_OFF_RPCSIZE, &size, &step,
1954                           ll_i2info(inode)->lli_smd);
1955         if (rc)
1956                 step = INIT_RAS_WINDOW_PAGES;
1957
1958         if (stride_io_mode(ras))
1959                 ras_stride_increase_window(ras, ra, (unsigned long)step);
1960         else
1961                 ras->ras_window_len = min(ras->ras_window_len +
1962                                           (unsigned long)step,
1963                                           ra->ra_max_pages);
1964 }
1965
1966 static void ras_update(struct ll_sb_info *sbi, struct inode *inode,
1967                        struct ll_readahead_state *ras, unsigned long index,
1968                        unsigned hit)
1969 {
1970         struct ll_ra_info *ra = &sbi->ll_ra_info;
1971         int zero = 0, stride_detect = 0, ra_miss = 0;
1972         ENTRY;
1973
1974         spin_lock(&ras->ras_lock);
1975
1976         ll_ra_stats_inc_sbi(sbi, hit ? RA_STAT_HIT : RA_STAT_MISS);
1977
1978         /* reset the read-ahead window in two cases.  First when the app seeks
1979          * or reads to some other part of the file.  Secondly if we get a
1980          * read-ahead miss that we think we've previously issued.  This can
1981          * be a symptom of there being so many read-ahead pages that the VM is
1982          * reclaiming it before we get to it. */
1983         if (!index_in_window(index, ras->ras_last_readpage, 8, 8)) {
1984                 zero = 1;
1985                 ll_ra_stats_inc_sbi(sbi, RA_STAT_DISTANT_READPAGE);
1986         } else if (!hit && ras->ras_window_len &&
1987                    index < ras->ras_next_readahead &&
1988                    index_in_window(index, ras->ras_window_start, 0,
1989                                    ras->ras_window_len)) {
1990                 ra_miss = 1;
1991                 ll_ra_stats_inc_sbi(sbi, RA_STAT_MISS_IN_WINDOW);
1992         }
1993
1994         /* On the second access to a file smaller than the tunable
1995          * ra_max_read_ahead_whole_pages trigger RA on all pages in the
1996          * file up to ra_max_pages_per_file.  This is simply a best effort
1997          * and only occurs once per open file.  Normal RA behavior is reverted
1998          * to for subsequent IO.  The mmap case does not increment
1999          * ras_requests and thus can never trigger this behavior. */
2000         if (ras->ras_requests == 2 && !ras->ras_request_index) {
2001                 __u64 kms_pages;
2002
2003                 kms_pages = (i_size_read(inode) + CFS_PAGE_SIZE - 1) >>
2004                             CFS_PAGE_SHIFT;
2005
2006                 CDEBUG(D_READA, "kmsp "LPU64" mwp %lu mp %lu\n", kms_pages,
2007                        ra->ra_max_read_ahead_whole_pages,
2008                        ra->ra_max_pages_per_file);
2009
2010                 if (kms_pages &&
2011                     kms_pages <= ra->ra_max_read_ahead_whole_pages) {
2012                         ras->ras_window_start = 0;
2013                         ras->ras_last_readpage = 0;
2014                         ras->ras_next_readahead = 0;
2015                         ras->ras_window_len = min(ra->ra_max_pages_per_file,
2016                                 ra->ra_max_read_ahead_whole_pages);
2017                         GOTO(out_unlock, 0);
2018                 }
2019         }
2020         if (zero) {
2021                 /* check whether it is in stride I/O mode*/
2022                 if (!index_in_stride_window(index, ras, inode)) {
2023                         if (ras->ras_consecutive_stride_requests == 0 &&
2024                             ras->ras_request_index == 0) {
2025                                 ras_update_stride_detector(ras, index);
2026                                 ras->ras_consecutive_stride_requests ++;
2027                         } else {
2028                                 ras_stride_reset(ras);
2029                         }
2030                         ras_reset(ras, index);
2031                         ras->ras_consecutive_pages++;
2032                         GOTO(out_unlock, 0);
2033                 } else {
2034                         ras->ras_consecutive_pages = 0;
2035                         ras->ras_consecutive_requests = 0;
2036                         if (++ras->ras_consecutive_stride_requests > 1)
2037                                 stride_detect = 1;
2038                         RAS_CDEBUG(ras);
2039                 }
2040         } else {
2041                 if (ra_miss) {
2042                         if (index_in_stride_window(index, ras, inode) &&
2043                             stride_io_mode(ras)) {
2044                                 /*If stride-RA hit cache miss, the stride dector
2045                                  *will not be reset to avoid the overhead of
2046                                  *redetecting read-ahead mode */
2047                                 if (index != ras->ras_last_readpage + 1)
2048                                        ras->ras_consecutive_pages = 0;
2049                                 ras_reset(ras, index);
2050                                 RAS_CDEBUG(ras);
2051                         } else {
2052                                 /* Reset both stride window and normal RA
2053                                  * window */
2054                                 ras_reset(ras, index);
2055                                 ras->ras_consecutive_pages++;
2056                                 ras_stride_reset(ras);
2057                                 GOTO(out_unlock, 0);
2058                         }
2059                 } else if (stride_io_mode(ras)) {
2060                         /* If this is contiguous read but in stride I/O mode
2061                          * currently, check whether stride step still is valid,
2062                          * if invalid, it will reset the stride ra window*/
2063                         if (!index_in_stride_window(index, ras, inode)) {
2064                                 /* Shrink stride read-ahead window to be zero */
2065                                 ras_stride_reset(ras);
2066                                 ras->ras_window_len = 0;
2067                                 ras->ras_next_readahead = index;
2068                         }
2069                 }
2070         }
2071         ras->ras_consecutive_pages++;
2072         ras->ras_last_readpage = index;
2073         ras_set_start(ras, index);
2074         ras->ras_next_readahead = max(ras->ras_window_start,
2075                                       ras->ras_next_readahead);
2076         RAS_CDEBUG(ras);
2077
2078         /* Trigger RA in the mmap case where ras_consecutive_requests
2079          * is not incremented and thus can't be used to trigger RA */
2080         if (!ras->ras_window_len && ras->ras_consecutive_pages == 4) {
2081                 ras->ras_window_len = INIT_RAS_WINDOW_PAGES;
2082                 GOTO(out_unlock, 0);
2083         }
2084
2085         /* Initially reset the stride window offset to next_readahead*/
2086         if (ras->ras_consecutive_stride_requests == 2 && stride_detect) {
2087                 /**
2088                  * Once stride IO mode is detected, next_readahead should be
2089                  * reset to make sure next_readahead > stride offset
2090                  */
2091                 ras->ras_next_readahead = max(index, ras->ras_next_readahead);
2092                 ras->ras_stride_offset = index;
2093                 ras->ras_window_len = INIT_RAS_WINDOW_PAGES;
2094         }
2095
2096         /* The initial ras_window_len is set to the request size.  To avoid
2097          * uselessly reading and discarding pages for random IO the window is
2098          * only increased once per consecutive request received. */
2099         if ((ras->ras_consecutive_requests > 1 || stride_detect) &&
2100             !ras->ras_request_index)
2101                 ras_increase_window(ras, ra, inode);
2102         EXIT;
2103 out_unlock:
2104         RAS_CDEBUG(ras);
2105         ras->ras_request_index++;
2106         spin_unlock(&ras->ras_lock);
2107         return;
2108 }
2109
2110 int ll_writepage(struct page *page)
2111 {
2112         struct inode *inode = page->mapping->host;
2113         struct ll_inode_info *lli = ll_i2info(inode);
2114         struct obd_export *exp;
2115         struct ll_async_page *llap;
2116         struct ll_thread_data *ltd;
2117         struct lustre_handle *lockh = NULL;
2118         int rc = 0;
2119         ENTRY;
2120
2121         LASSERT(PageLocked(page));
2122
2123         exp = ll_i2obdexp(inode);
2124         if (exp == NULL)
2125                 GOTO(out, rc = -EINVAL);
2126
2127         ltd = ll_td_get();
2128         /* currently, no FAST lock in write path */
2129         if (ltd && ltd->lock_style == LL_LOCK_STYLE_TREELOCK) {
2130                 __u64 offset = ((loff_t)page->index) << CFS_PAGE_SHIFT;
2131                 lockh = ltd2lockh(ltd, offset, offset + CFS_PAGE_SIZE - 1);
2132         }
2133         
2134         llap = llap_from_page_with_lockh(page, LLAP_ORIGIN_WRITEPAGE, lockh, 0);
2135         if (IS_ERR(llap))
2136                 GOTO(out, rc = PTR_ERR(llap));
2137
2138         LASSERT(!PageWriteback(page));
2139         set_page_writeback(page);
2140
2141         page_cache_get(page);
2142         if (llap->llap_write_queued) {
2143                 LL_CDEBUG_PAGE(D_PAGE, page, "marking urgent\n");
2144                 rc = obd_set_async_flags(exp, lli->lli_smd, NULL,
2145                                          llap->llap_cookie,
2146                                          ASYNC_READY | ASYNC_URGENT);
2147         } else {
2148                 rc = queue_or_sync_write(exp, inode, llap, CFS_PAGE_SIZE,
2149                                          ASYNC_READY | ASYNC_URGENT);
2150         }
2151         if (rc) {
2152                 /* re-dirty page on error so it retries write */
2153                 if (PageWriteback(page))
2154                         end_page_writeback(page);
2155
2156                 /* resend page only for not started IO*/
2157                 if (!PageError(page))
2158                         ll_redirty_page(page);
2159
2160                 page_cache_release(page);
2161         }
2162 out:
2163         if (rc) {
2164                 if (!lli->lli_async_rc)
2165                         lli->lli_async_rc = rc;
2166                 /* resend page only for not started IO*/
2167                 unlock_page(page);
2168         }
2169         RETURN(rc);
2170 }
2171
2172 /*
2173  * for now we do our readpage the same on both 2.4 and 2.5.  The kernel's
2174  * read-ahead assumes it is valid to issue readpage all the way up to
2175  * i_size, but our dlm locks make that not the case.  We disable the
2176  * kernel's read-ahead and do our own by walking ahead in the page cache
2177  * checking for dlm lock coverage.  the main difference between 2.4 and
2178  * 2.6 is how read-ahead gets batched and issued, but we're using our own,
2179  * so they look the same.
2180  */
2181 int ll_readpage(struct file *filp, struct page *page)
2182 {
2183         struct ll_file_data *fd = LUSTRE_FPRIVATE(filp);
2184         struct inode *inode = page->mapping->host;
2185         struct obd_export *exp;
2186         struct ll_async_page *llap;
2187         struct obd_io_group *oig = NULL;
2188         struct lustre_handle *lockh = NULL;
2189         int rc, flags = 0;
2190         ENTRY;
2191
2192         LASSERT(PageLocked(page));
2193         LASSERT(!PageUptodate(page));
2194         CDEBUG(D_VFSTRACE, "VFS Op:inode=%lu/%u(%p),offset=%Lu=%#Lx\n",
2195                inode->i_ino, inode->i_generation, inode,
2196                (((loff_t)page->index) << CFS_PAGE_SHIFT),
2197                (((loff_t)page->index) << CFS_PAGE_SHIFT));
2198         LASSERT(atomic_read(&filp->f_dentry->d_inode->i_count) > 0);
2199
2200         if (!ll_i2info(inode)->lli_smd) {
2201                 /* File with no objects - one big hole */
2202                 /* We use this just for remove_from_page_cache that is not
2203                  * exported, we'd make page back up to date. */
2204                 ll_truncate_complete_page(page);
2205                 clear_page(kmap(page));
2206                 kunmap(page);
2207                 SetPageUptodate(page);
2208                 unlock_page(page);
2209                 RETURN(0);
2210         }
2211
2212         rc = oig_init(&oig);
2213         if (rc < 0)
2214                 GOTO(out, rc);
2215
2216         exp = ll_i2obdexp(inode);
2217         if (exp == NULL)
2218                 GOTO(out, rc = -EINVAL);
2219
2220         if (fd->fd_flags & LL_FILE_GROUP_LOCKED) {
2221                 lockh = &fd->fd_cwlockh;
2222         } else {
2223                 struct ll_thread_data *ltd;
2224                 ltd = ll_td_get();
2225                 if (ltd && ltd->lock_style > 0) {
2226                         __u64 offset = ((loff_t)page->index) << CFS_PAGE_SHIFT;
2227                         lockh = ltd2lockh(ltd, offset,
2228                                           offset + CFS_PAGE_SIZE - 1);
2229                         if (ltd->lock_style == LL_LOCK_STYLE_FASTLOCK)
2230                                 flags = OBD_FAST_LOCK;
2231                 }
2232         }
2233
2234         llap = llap_from_page_with_lockh(page, LLAP_ORIGIN_READPAGE, lockh,
2235                                          flags);
2236         if (IS_ERR(llap)) {
2237                 if (PTR_ERR(llap) == -ENOLCK) {
2238                         CWARN("ino %lu page %lu (%llu) not covered by "
2239                               "a lock (mmap?).  check debug logs.\n",
2240                               inode->i_ino, page->index,
2241                               (long long)page->index << PAGE_CACHE_SHIFT);
2242                 }
2243                 GOTO(out, rc = PTR_ERR(llap));
2244         }
2245
2246         if (ll_i2sbi(inode)->ll_ra_info.ra_max_pages_per_file)
2247                 ras_update(ll_i2sbi(inode), inode, &fd->fd_ras, page->index,
2248                            llap->llap_defer_uptodate);
2249
2250
2251         if (llap->llap_defer_uptodate) {
2252                 /* This is the callpath if we got the page from a readahead */
2253                 llap->llap_ra_used = 1;
2254                 rc = ll_readahead(&fd->fd_ras, exp, page->mapping, oig,
2255                                   fd->fd_flags);
2256                 if (rc > 0)
2257                         obd_trigger_group_io(exp, ll_i2info(inode)->lli_smd,
2258                                              NULL, oig);
2259                 LL_CDEBUG_PAGE(D_PAGE, page, "marking uptodate from defer\n");
2260                 SetPageUptodate(page);
2261                 unlock_page(page);
2262                 GOTO(out_oig, rc = 0);
2263         }
2264
2265         rc = ll_issue_page_read(exp, llap, oig, 0);
2266         if (rc)
2267                 GOTO(out, rc);
2268
2269         LL_CDEBUG_PAGE(D_PAGE, page, "queued readpage\n");
2270         /* We have just requested the actual page we want, see if we can tack
2271          * on some readahead to that page's RPC before it is sent. */
2272         if (ll_i2sbi(inode)->ll_ra_info.ra_max_pages_per_file)
2273                 ll_readahead(&fd->fd_ras, exp, page->mapping, oig,
2274                              fd->fd_flags);
2275
2276         rc = obd_trigger_group_io(exp, ll_i2info(inode)->lli_smd, NULL, oig);
2277
2278 out:
2279         if (rc)
2280                 unlock_page(page);
2281 out_oig:
2282         if (oig != NULL)
2283                 oig_release(oig);
2284         RETURN(rc);
2285 }
2286