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