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