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