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