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