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