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