Whamcloud - gitweb
024734920b4a4c38f74b064fa2b21ed2c8397dbd
[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  * GPL HEADER START
5  *
6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License version 2 only,
10  * as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License version 2 for more details (a copy is included
16  * in the LICENSE file that accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License
19  * version 2 along with this program; If not, see
20  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
21  *
22  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
23  * CA 95054 USA or visit www.sun.com if you need additional information or
24  * have any questions.
25  *
26  * GPL HEADER END
27  */
28 /*
29  * Copyright  2008 Sun Microsystems, Inc. All rights reserved
30  * Use is subject to license terms.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * lustre/llite/rw.c
37  *
38  * Lustre Lite I/O page cache routines shared by different kernel revs
39  */
40
41 #include <linux/autoconf.h>
42 #include <linux/kernel.h>
43 #include <linux/mm.h>
44 #include <linux/string.h>
45 #include <linux/stat.h>
46 #include <linux/errno.h>
47 #include <linux/smp_lock.h>
48 #include <linux/unistd.h>
49 #include <linux/version.h>
50 #include <asm/system.h>
51 #include <asm/uaccess.h>
52
53 #include <linux/fs.h>
54 #include <linux/stat.h>
55 #include <asm/uaccess.h>
56 #include <linux/mm.h>
57 #include <linux/pagemap.h>
58 #include <linux/smp_lock.h>
59 /* current_is_kswapd() */
60 #include <linux/swap.h>
61
62 #define DEBUG_SUBSYSTEM S_LLITE
63
64 //#include <lustre_mdc.h>
65 #include <lustre_lite.h>
66 #include <obd_cksum.h>
67 #include "llite_internal.h"
68 #include <linux/lustre_compat25.h>
69
70 /* this isn't where truncate starts.   roughly:
71  * sys_truncate->ll_setattr_raw->vmtruncate->ll_truncate. setattr_raw grabs
72  * DLM lock on [size, EOF], i_mutex, ->lli_size_sem, and WRITE_I_ALLOC_SEM to
73  * avoid races.
74  *
75  * must be called under ->lli_size_sem */
76 void ll_truncate(struct inode *inode)
77 {
78         struct ll_inode_info *lli = ll_i2info(inode);
79         loff_t new_size;
80         ENTRY;
81         CDEBUG(D_VFSTRACE, "VFS Op:inode=%lu/%u(%p) to %Lu=%#Lx\n",inode->i_ino,
82                inode->i_generation, inode, i_size_read(inode),
83                i_size_read(inode));
84
85         ll_stats_ops_tally(ll_i2sbi(inode), LPROC_LL_TRUNC, 1);
86         if (lli->lli_size_sem_owner != cfs_current()) {
87                 EXIT;
88                 return;
89         }
90
91         if (!lli->lli_smd) {
92                 CDEBUG(D_INODE, "truncate on inode %lu with no objects\n",
93                        inode->i_ino);
94                 GOTO(out_unlock, 0);
95         }
96         LASSERT_SEM_LOCKED(&lli->lli_size_sem);
97
98         if (unlikely((ll_i2sbi(inode)->ll_flags & LL_SBI_CHECKSUM) &&
99                      (i_size_read(inode) & ~CFS_PAGE_MASK))) {
100                 /* If the truncate leaves a partial page, update its checksum */
101                 struct page *page = find_get_page(inode->i_mapping,
102                                                   i_size_read(inode) >>
103                                                   CFS_PAGE_SHIFT);
104                 if (page != NULL) {
105 #if 0 /* XXX */
106                         struct ll_async_page *llap = llap_cast_private(page);
107                         if (llap != NULL) {
108                                 char *kaddr = kmap_atomic(page, KM_USER0);
109                                 llap->llap_checksum =
110                                         init_checksum(OSC_DEFAULT_CKSUM);
111                                 llap->llap_checksum =
112                                         compute_checksum(llap->llap_checksum,
113                                                          kaddr, CFS_PAGE_SIZE,
114                                                          OSC_DEFAULT_CKSUM);
115                                 kunmap_atomic(kaddr, KM_USER0);
116                         }
117                         page_cache_release(page);
118 #endif
119                 }
120         }
121
122         new_size = i_size_read(inode);
123         ll_inode_size_unlock(inode, 0);
124
125         EXIT;
126         return;
127
128  out_unlock:
129         ll_inode_size_unlock(inode, 0);
130 } /* ll_truncate */
131
132 /**
133  * Initializes common cl-data at the typical address_space operation entry
134  * point.
135  */
136 static int ll_cl_init(struct file *file, struct page *vmpage,
137                       struct lu_env **env,
138                       struct cl_io **io, struct cl_page **page, int *refcheck)
139 {
140         struct lu_env    *_env;
141         struct cl_io     *_io;
142         struct cl_page   *_page;
143         struct cl_object *clob;
144
145         int result;
146
147         *env  = NULL;
148         *io   = NULL;
149         *page = NULL;
150
151         clob = ll_i2info(vmpage->mapping->host)->lli_clob;
152         LASSERT(clob != NULL);
153
154         _env = cl_env_get(refcheck);
155         if (!IS_ERR(env)) {
156                 struct ccc_io *cio = ccc_env_io(_env);
157
158                 *env = _env;
159                 *io  = _io = cio->cui_cl.cis_io;
160                 if (_io != NULL) {
161                         LASSERT(_io->ci_state == CIS_IO_GOING);
162                         LASSERT(cio->cui_fd == LUSTRE_FPRIVATE(file));
163                         _page = cl_page_find(_env, clob, vmpage->index, vmpage,
164                                              CPT_CACHEABLE);
165                         if (!IS_ERR(_page)) {
166                                 *page = _page;
167                                 lu_ref_add(&_page->cp_reference, "cl_io", _io);
168                                 result = 0;
169                         } else
170                                 result = PTR_ERR(_page);
171                 } else
172                         /*
173                          * This is for a case where operation can be called
174                          * either with or without cl_io created by the upper
175                          * layer (e.g., ->prepare_write() called directly from
176                          * loop-back driver).
177                          */
178                         result = -EALREADY;
179         } else
180                 result = PTR_ERR(_env);
181         CDEBUG(D_VFSTRACE, "%lu@"DFID" -> %i %p %p %p\n",
182                vmpage->index, PFID(lu_object_fid(&clob->co_lu)), result,
183                *env, *io, *page);
184         return result;
185 }
186
187 /**
188  * Finalizes cl-data before exiting typical address_space operation. Dual to
189  * ll_cl_init().
190  */
191 static void ll_cl_fini(struct lu_env *env,
192                        struct cl_io *io, struct cl_page *page, int *refcheck)
193 {
194         if (page != NULL) {
195                 lu_ref_del(&page->cp_reference, "cl_io", io);
196                 cl_page_put(env, page);
197         }
198         if (env != NULL) {
199                 struct vvp_io *vio;
200
201                 vio = vvp_env_io(env);
202                 LASSERT(vio->cui_oneshot >= 0);
203                 if (vio->cui_oneshot > 0) {
204                         if (--vio->cui_oneshot == 0) {
205                                 cl_io_end(env, io);
206                                 cl_io_unlock(env, io);
207                                 cl_io_iter_fini(env, io);
208                                 cl_io_fini(env, io);
209                                 /* to trigger assertion above, if ll_cl_fini()
210                                  * is called against freed io. */
211                                 vio->cui_oneshot = -1;
212                         }
213                         /* additional reference on env was acquired by io,
214                          * disable refcheck */
215                         refcheck = NULL;
216                 }
217                 cl_env_put(env, refcheck);
218         } else
219                 LASSERT(io == NULL);
220 }
221
222 /**
223  * Initializes one-shot cl_io for the case when loop driver calls
224  * ->{prepare,commit}_write() methods directly.
225  */
226 static int ll_prepare_loop(struct lu_env *env, struct cl_io *io,
227                            struct file *file, struct page *vmpage,
228                            unsigned from, unsigned to)
229 {
230         struct vvp_io *vio;
231         struct ccc_io *cio;
232         int result;
233         loff_t pos;
234
235         vio = vvp_env_io(env);
236         cio = ccc_env_io(env);
237         ll_io_init(io, file, 1);
238         pos = (vmpage->index << CFS_PAGE_SHIFT) + from;
239         /*
240          * Create IO and quickly drive it through CIS_{INIT,IT_STARTED,LOCKED}
241          * states. DLM locks are not taken for vio->cui_oneshot IO---we cannot
242          * take DLM locks here, because page is already locked. With new
243          * ->write_{being,end}() address_space operations lustre might be
244          * luckier.
245          */
246         result = cl_io_rw_init(env, io, CIT_WRITE, pos, from - to);
247         if (result == 0) {
248                 cio->cui_fd = LUSTRE_FPRIVATE(file);
249                 vio->cui_oneshot = 1;
250                 result = cl_io_iter_init(env, io);
251                 if (result == 0) {
252                         result = cl_io_lock(env, io);
253                         if (result == 0)
254                                 result = cl_io_start(env, io);
255                 }
256         } else
257                 result = io->ci_result;
258         return result;
259 }
260
261 /**
262  * ->prepare_write() address space operation called by generic_file_write()
263  * for every page during write.
264  */
265 int ll_prepare_write(struct file *file, struct page *vmpage, unsigned from,
266                      unsigned to)
267 {
268         struct lu_env    *env;
269         struct cl_io     *io;
270         struct cl_page   *page;
271         int result;
272         int refcheck;
273         ENTRY;
274
275         result = ll_cl_init(file, vmpage, &env, &io, &page, &refcheck);
276         /*
277          * Loop-back driver calls ->prepare_write() and ->sendfile() methods
278          * directly, bypassing file system ->write() operation, so cl_io has
279          * to be created here.
280          */
281         if (result == -EALREADY) {
282                 io = &ccc_env_info(env)->cti_io;
283                 result = ll_prepare_loop(env, io, file, vmpage, from, to);
284                 if (result == 0) {
285                         result = ll_cl_init(file, vmpage,
286                                             &env, &io, &page, &refcheck);
287                         cl_env_put(env, NULL);
288                 }
289         }
290         if (result == 0) {
291                 cl_page_assume(env, io, page);
292                 if (cl_io_is_append(io)) {
293                         struct cl_object   *obj   = io->ci_obj;
294                         struct inode       *inode = ccc_object_inode(obj);
295                         /**
296                          * In VFS file->page write loop, for appending, the
297                          * write offset might be reset according to the new
298                          * file size before holding i_mutex. So crw_pos should
299                          * be reset here. BUG:17711.
300                          */
301                         io->u.ci_wr.wr.crw_pos = i_size_read(inode);
302                 }
303                 result = cl_io_prepare_write(env, io, page, from, to);
304                 if (result == 0) {
305                         struct vvp_io *vio;
306
307                         /*
308                          * Add a reference, so that page is not evicted from
309                          * the cache until ->commit_write() is called.
310                          */
311                         cl_page_get(page);
312                         lu_ref_add(&page->cp_reference, "prepare_write",
313                                    cfs_current());
314                         vio = vvp_env_io(env);
315                         if (vio->cui_oneshot > 0)
316                                 vio->cui_oneshot++;
317                 } else
318                         cl_page_unassume(env, io, page);
319         }
320         ll_cl_fini(env, io, page, &refcheck);
321         RETURN(result);
322 }
323
324 int ll_commit_write(struct file *file, struct page *vmpage, unsigned from,
325                     unsigned to)
326 {
327         struct lu_env    *env;
328         struct cl_io     *io;
329         struct cl_page   *page;
330         int result;
331         int refcheck;
332         ENTRY;
333
334         result = ll_cl_init(file, vmpage, &env, &io, &page, &refcheck);
335         LASSERT(result != -EALREADY);
336         if (result == 0) {
337                 LASSERT(cl_page_is_owned(page, io));
338                 result = cl_io_commit_write(env, io, page, from, to);
339                 if (cl_page_is_owned(page, io))
340                         cl_page_unassume(env, io, page);
341                 /*
342                  * Release reference acquired by cl_io_prepare_write().
343                  */
344                 lu_ref_del(&page->cp_reference, "prepare_write", cfs_current());
345                 cl_page_put(env, page);
346         }
347         ll_cl_fini(env, io, page, &refcheck);
348         RETURN(result);
349 }
350
351 struct obd_capa *cl_capa_lookup(struct inode *inode, enum cl_req_type crt)
352 {
353         __u64 opc;
354
355         opc = crt == CRT_WRITE ? CAPA_OPC_OSS_WRITE : CAPA_OPC_OSS_RW;
356         return ll_osscapa_get(inode, opc);
357 }
358
359 static void ll_ra_stats_inc_sbi(struct ll_sb_info *sbi, enum ra_stat which);
360
361 /* WARNING: This algorithm is used to reduce the contention on
362  * sbi->ll_lock. It should work well if the ra_max_pages is much
363  * greater than the single file's read-ahead window.
364  *
365  * TODO: There may exist a `global sync problem' in this implementation.
366  * Considering the global ra window is 100M, and each file's ra window is 10M,
367  * there are over 10 files trying to get its ra budget and reach
368  * ll_ra_count_get at the exactly same time. All of them will get a zero ra
369  * window, although the global window is 100M. -jay
370  */
371 static unsigned long ll_ra_count_get(struct ll_sb_info *sbi, unsigned long len)
372 {
373         struct ll_ra_info *ra = &sbi->ll_ra_info;
374         unsigned long ret;
375         ENTRY;
376
377         /**
378          * If read-ahead pages left are less than 1M, do not do read-ahead,
379          * otherwise it will form small read RPC(< 1M), which hurt server
380          * performance a lot.
381          */
382         ret = min(ra->ra_max_pages - atomic_read(&ra->ra_cur_pages), len);
383         if ((int)ret < 0 || ret < min((unsigned long)PTLRPC_MAX_BRW_PAGES, len))
384                 GOTO(out, ret = 0);
385
386         if (atomic_add_return(ret, &ra->ra_cur_pages) > ra->ra_max_pages) {
387                 atomic_sub(ret, &ra->ra_cur_pages);
388                 ret = 0;
389         }
390 out:
391         RETURN(ret);
392 }
393
394 void ll_ra_count_put(struct ll_sb_info *sbi, unsigned long len)
395 {
396         struct ll_ra_info *ra = &sbi->ll_ra_info;
397         atomic_sub(len, &ra->ra_cur_pages);
398 }
399
400 static void ll_ra_stats_inc_sbi(struct ll_sb_info *sbi, enum ra_stat which)
401 {
402         LASSERTF(which >= 0 && which < _NR_RA_STAT, "which: %u\n", which);
403         lprocfs_counter_incr(sbi->ll_ra_stats, which);
404 }
405
406 void ll_ra_stats_inc(struct address_space *mapping, enum ra_stat which)
407 {
408         struct ll_sb_info *sbi = ll_i2sbi(mapping->host);
409         ll_ra_stats_inc_sbi(sbi, which);
410 }
411
412 #define RAS_CDEBUG(ras) \
413         CDEBUG(D_READA,                                                      \
414                "lrp %lu cr %lu cp %lu ws %lu wl %lu nra %lu r %lu ri %lu"    \
415                "csr %lu sf %lu sp %lu sl %lu \n",                            \
416                ras->ras_last_readpage, ras->ras_consecutive_requests,        \
417                ras->ras_consecutive_pages, ras->ras_window_start,            \
418                ras->ras_window_len, ras->ras_next_readahead,                 \
419                ras->ras_requests, ras->ras_request_index,                    \
420                ras->ras_consecutive_stride_requests, ras->ras_stride_offset, \
421                ras->ras_stride_pages, ras->ras_stride_length)
422
423 static int index_in_window(unsigned long index, unsigned long point,
424                            unsigned long before, unsigned long after)
425 {
426         unsigned long start = point - before, end = point + after;
427
428         if (start > point)
429                start = 0;
430         if (end < point)
431                end = ~0;
432
433         return start <= index && index <= end;
434 }
435
436 static struct ll_readahead_state *ll_ras_get(struct file *f)
437 {
438         struct ll_file_data       *fd;
439
440         fd = LUSTRE_FPRIVATE(f);
441         return &fd->fd_ras;
442 }
443
444 void ll_ra_read_in(struct file *f, struct ll_ra_read *rar)
445 {
446         struct ll_readahead_state *ras;
447
448         ras = ll_ras_get(f);
449
450         spin_lock(&ras->ras_lock);
451         ras->ras_requests++;
452         ras->ras_request_index = 0;
453         ras->ras_consecutive_requests++;
454         rar->lrr_reader = current;
455
456         list_add(&rar->lrr_linkage, &ras->ras_read_beads);
457         spin_unlock(&ras->ras_lock);
458 }
459
460 void ll_ra_read_ex(struct file *f, struct ll_ra_read *rar)
461 {
462         struct ll_readahead_state *ras;
463
464         ras = ll_ras_get(f);
465
466         spin_lock(&ras->ras_lock);
467         list_del_init(&rar->lrr_linkage);
468         spin_unlock(&ras->ras_lock);
469 }
470
471 static struct ll_ra_read *ll_ra_read_get_locked(struct ll_readahead_state *ras)
472 {
473         struct ll_ra_read *scan;
474
475         list_for_each_entry(scan, &ras->ras_read_beads, lrr_linkage) {
476                 if (scan->lrr_reader == current)
477                         return scan;
478         }
479         return NULL;
480 }
481
482 struct ll_ra_read *ll_ra_read_get(struct file *f)
483 {
484         struct ll_readahead_state *ras;
485         struct ll_ra_read         *bead;
486
487         ras = ll_ras_get(f);
488
489         spin_lock(&ras->ras_lock);
490         bead = ll_ra_read_get_locked(ras);
491         spin_unlock(&ras->ras_lock);
492         return bead;
493 }
494
495 static int cl_read_ahead_page(const struct lu_env *env, struct cl_io *io,
496                               struct cl_page_list *queue, struct cl_page *page,
497                               struct page *vmpage)
498 {
499         struct ccc_page *cp;
500         int              rc;
501
502         ENTRY;
503
504         rc = 0;
505         cl_page_assume(env, io, page);
506         lu_ref_add(&page->cp_reference, "ra", cfs_current());
507         cp = cl2ccc_page(cl_page_at(page, &vvp_device_type));
508         if (!cp->cpg_defer_uptodate && !Page_Uptodate(vmpage)) {
509                 rc = cl_page_is_under_lock(env, io, page);
510                 if (rc == -EBUSY) {
511                         cp->cpg_defer_uptodate = 1;
512                         cp->cpg_ra_used = 0;
513                         cl_page_list_add(queue, page);
514                         rc = 1;
515                 } else {
516                         cl_page_delete(env, page);
517                         rc = -ENOLCK;
518                 }
519         } else
520                 /* skip completed pages */
521                 cl_page_unassume(env, io, page);
522         lu_ref_del(&page->cp_reference, "ra", cfs_current());
523         cl_page_put(env, page);
524         RETURN(rc);
525 }
526
527 /**
528  * Initiates read-ahead of a page with given index.
529  *
530  * \retval     +ve: page was added to \a queue.
531  *
532  * \retval -ENOLCK: there is no extent lock for this part of a file, stop
533  *                  read-ahead.
534  *
535  * \retval  -ve, 0: page wasn't added to \a queue for other reason.
536  */
537 static int ll_read_ahead_page(const struct lu_env *env, struct cl_io *io,
538                               struct cl_page_list *queue,
539                               int index, struct address_space *mapping)
540 {
541         struct page      *vmpage;
542         struct cl_object *clob  = ll_i2info(mapping->host)->lli_clob;
543         struct cl_page   *page;
544         enum ra_stat      which = _NR_RA_STAT; /* keep gcc happy */
545         unsigned int      gfp_mask;
546         int               rc    = 0;
547         const char       *msg   = NULL;
548
549         ENTRY;
550
551         gfp_mask = GFP_HIGHUSER & ~__GFP_WAIT;
552 #ifdef __GFP_NOWARN
553         gfp_mask |= __GFP_NOWARN;
554 #endif
555         vmpage = grab_cache_page_nowait_gfp(mapping, index, gfp_mask);
556         if (vmpage != NULL) {
557                 /* Check if vmpage was truncated or reclaimed */
558                 if (vmpage->mapping == mapping) {
559                         page = cl_page_find(env, clob, vmpage->index,
560                                             vmpage, CPT_CACHEABLE);
561                         if (!IS_ERR(page)) {
562                                 rc = cl_read_ahead_page(env, io, queue,
563                                                         page, vmpage);
564                                 if (rc == -ENOLCK) {
565                                         which = RA_STAT_FAILED_MATCH;
566                                         msg   = "lock match failed";
567                                 }
568                         } else {
569                                 which = RA_STAT_FAILED_GRAB_PAGE;
570                                 msg   = "cl_page_find failed";
571                         }
572                 } else {
573                         which = RA_STAT_WRONG_GRAB_PAGE;
574                         msg   = "g_c_p_n returned invalid page";
575                 }
576                 if (rc != 1)
577                         unlock_page(vmpage);
578                 page_cache_release(vmpage);
579         } else {
580                 which = RA_STAT_FAILED_GRAB_PAGE;
581                 msg   = "g_c_p_n failed";
582         }
583         if (msg != NULL) {
584                 ll_ra_stats_inc(mapping, which);
585                 CDEBUG(D_READA, "%s\n", msg);
586         }
587         RETURN(rc);
588 }
589
590 #define RIA_DEBUG(ria)                                                       \
591         CDEBUG(D_READA, "rs %lu re %lu ro %lu rl %lu rp %lu\n",       \
592         ria->ria_start, ria->ria_end, ria->ria_stoff, ria->ria_length,\
593         ria->ria_pages)
594
595 #define RAS_INCREASE_STEP PTLRPC_MAX_BRW_PAGES
596
597 static inline int stride_io_mode(struct ll_readahead_state *ras)
598 {
599         return ras->ras_consecutive_stride_requests > 1;
600 }
601 /* The function calculates how much pages will be read in
602  * [off, off + length], in such stride IO area,
603  * stride_offset = st_off, stride_lengh = st_len,
604  * stride_pages = st_pgs
605  *
606  *   |------------------|*****|------------------|*****|------------|*****|....
607  * st_off
608  *   |--- st_pgs     ---|
609  *   |-----     st_len   -----|
610  *
611  *              How many pages it should read in such pattern
612  *              |-------------------------------------------------------------|
613  *              off
614  *              |<------                  length                      ------->|
615  *
616  *          =   |<----->|  +  |-------------------------------------| +   |---|
617  *             start_left                 st_pgs * i                    end_left
618  */
619 static unsigned long
620 stride_pg_count(pgoff_t st_off, unsigned long st_len, unsigned long st_pgs,
621                 unsigned long off, unsigned long length)
622 {
623         unsigned long start = off > st_off ? off - st_off : 0;
624         unsigned long end = off + length > st_off ? off + length - st_off : 0;
625         unsigned long start_left = 0;
626         unsigned long end_left = 0;
627         unsigned long pg_count;
628
629         if (st_len == 0 || length == 0 || end == 0)
630                 return length;
631
632         start_left = do_div(start, st_len);
633         if (start_left < st_pgs)
634                 start_left = st_pgs - start_left;
635         else
636                 start_left = 0;
637
638         end_left = do_div(end, st_len);
639         if (end_left > st_pgs)
640                 end_left = st_pgs;
641
642         CDEBUG(D_READA, "start %lu, end %lu start_left %lu end_left %lu \n",
643                start, end, start_left, end_left);
644
645         if (start == end)
646                 pg_count = end_left - (st_pgs - start_left);
647         else
648                 pg_count = start_left + st_pgs * (end - start - 1) + end_left;
649
650         CDEBUG(D_READA, "st_off %lu, st_len %lu st_pgs %lu off %lu length %lu"
651                "pgcount %lu\n", st_off, st_len, st_pgs, off, length, pg_count);
652
653         return pg_count;
654 }
655
656 static int ria_page_count(struct ra_io_arg *ria)
657 {
658         __u64 length = ria->ria_end >= ria->ria_start ?
659                        ria->ria_end - ria->ria_start + 1 : 0;
660
661         return stride_pg_count(ria->ria_stoff, ria->ria_length,
662                                ria->ria_pages, ria->ria_start,
663                                length);
664 }
665
666 /*Check whether the index is in the defined ra-window */
667 static int ras_inside_ra_window(unsigned long idx, struct ra_io_arg *ria)
668 {
669         /* If ria_length == ria_pages, it means non-stride I/O mode,
670          * idx should always inside read-ahead window in this case
671          * For stride I/O mode, just check whether the idx is inside
672          * the ria_pages. */
673         return ria->ria_length == 0 || ria->ria_length == ria->ria_pages ||
674                (idx - ria->ria_stoff) % ria->ria_length < ria->ria_pages;
675 }
676
677 static int ll_read_ahead_pages(const struct lu_env *env,
678                                struct cl_io *io, struct cl_page_list *queue,
679                                struct ra_io_arg *ria,
680                                unsigned long *reserved_pages,
681                                struct address_space *mapping,
682                                unsigned long *ra_end)
683 {
684         int rc, count = 0, stride_ria;
685         unsigned long page_idx;
686
687         LASSERT(ria != NULL);
688         RIA_DEBUG(ria);
689
690         stride_ria = ria->ria_length > ria->ria_pages && ria->ria_pages > 0;
691         for (page_idx = ria->ria_start; page_idx <= ria->ria_end &&
692                         *reserved_pages > 0; page_idx++) {
693                 if (ras_inside_ra_window(page_idx, ria)) {
694                         /* If the page is inside the read-ahead window*/
695                         rc = ll_read_ahead_page(env, io, queue,
696                                                 page_idx, mapping);
697                         if (rc == 1) {
698                                 (*reserved_pages)--;
699                                 count ++;
700                         } else if (rc == -ENOLCK)
701                                 break;
702                 } else if (stride_ria) {
703                         /* If it is not in the read-ahead window, and it is
704                          * read-ahead mode, then check whether it should skip
705                          * the stride gap */
706                         pgoff_t offset;
707                         /* FIXME: This assertion only is valid when it is for
708                          * forward read-ahead, it will be fixed when backward
709                          * read-ahead is implemented */
710                         LASSERTF(page_idx > ria->ria_stoff, "since %lu in the"
711                                 " gap of ra window,it should bigger than stride"
712                                 " offset %lu \n", page_idx, ria->ria_stoff);
713
714                         offset = page_idx - ria->ria_stoff;
715                         offset = offset % (ria->ria_length);
716                         if (offset > ria->ria_pages) {
717                                 page_idx += ria->ria_length - offset;
718                                 CDEBUG(D_READA, "i %lu skip %lu \n", page_idx,
719                                        ria->ria_length - offset);
720                                 continue;
721                         }
722                 }
723         }
724         *ra_end = page_idx;
725         return count;
726 }
727
728 int ll_readahead(const struct lu_env *env, struct cl_io *io,
729                  struct ll_readahead_state *ras, struct address_space *mapping,
730                  struct cl_page_list *queue, int flags)
731 {
732         struct vvp_io *vio = vvp_env_io(env);
733         struct vvp_thread_info *vti = vvp_env_info(env);
734         struct cl_attr *attr = ccc_env_thread_attr(env);
735         unsigned long start = 0, end = 0, reserved;
736         unsigned long ra_end, len;
737         struct inode *inode;
738         struct ll_ra_read *bead;
739         struct ra_io_arg *ria = &vti->vti_ria;
740         struct ll_inode_info *lli;
741         struct cl_object *clob;
742         int ret = 0;
743         __u64 kms;
744         ENTRY;
745
746         inode = mapping->host;
747         lli = ll_i2info(inode);
748         clob = lli->lli_clob;
749
750         memset(ria, 0, sizeof *ria);
751
752         cl_object_attr_lock(clob);
753         ret = cl_object_attr_get(env, clob, attr);
754         cl_object_attr_unlock(clob);
755
756         if (ret != 0)
757                 RETURN(ret);
758         kms = attr->cat_kms;
759         if (kms == 0) {
760                 ll_ra_stats_inc(mapping, RA_STAT_ZERO_LEN);
761                 RETURN(0);
762         }
763
764         spin_lock(&ras->ras_lock);
765         if (vio->cui_ra_window_set)
766                 bead = &vio->cui_bead;
767         else
768                 bead = NULL;
769
770         /* Enlarge the RA window to encompass the full read */
771         if (bead != NULL && ras->ras_window_start + ras->ras_window_len <
772             bead->lrr_start + bead->lrr_count) {
773                 ras->ras_window_len = bead->lrr_start + bead->lrr_count -
774                                       ras->ras_window_start;
775         }
776         /* Reserve a part of the read-ahead window that we'll be issuing */
777         if (ras->ras_window_len) {
778                 start = ras->ras_next_readahead;
779                 end = ras->ras_window_start + ras->ras_window_len - 1;
780         }
781         if (end != 0) {
782                 /* Truncate RA window to end of file */
783                 end = min(end, (unsigned long)((kms - 1) >> CFS_PAGE_SHIFT));
784                 ras->ras_next_readahead = max(end, end + 1);
785                 RAS_CDEBUG(ras);
786         }
787         ria->ria_start = start;
788         ria->ria_end = end;
789         /* If stride I/O mode is detected, get stride window*/
790         if (stride_io_mode(ras)) {
791                 ria->ria_stoff = ras->ras_stride_offset;
792                 ria->ria_length = ras->ras_stride_length;
793                 ria->ria_pages = ras->ras_stride_pages;
794         }
795         spin_unlock(&ras->ras_lock);
796
797         if (end == 0) {
798                 ll_ra_stats_inc(mapping, RA_STAT_ZERO_WINDOW);
799                 RETURN(0);
800         }
801         len = ria_page_count(ria);
802         if (len == 0)
803                 RETURN(0);
804
805         reserved = ll_ra_count_get(ll_i2sbi(inode), len);
806
807         if (reserved < len)
808                 ll_ra_stats_inc(mapping, RA_STAT_MAX_IN_FLIGHT);
809
810         CDEBUG(D_READA, "reserved page %lu \n", reserved);
811
812         ret = ll_read_ahead_pages(env, io, queue,
813                                   ria, &reserved, mapping, &ra_end);
814
815         LASSERTF(reserved >= 0, "reserved %lu\n", reserved);
816         if (reserved != 0)
817                 ll_ra_count_put(ll_i2sbi(inode), reserved);
818
819         if (ra_end == end + 1 && ra_end == (kms >> CFS_PAGE_SHIFT))
820                 ll_ra_stats_inc(mapping, RA_STAT_EOF);
821
822         /* if we didn't get to the end of the region we reserved from
823          * the ras we need to go back and update the ras so that the
824          * next read-ahead tries from where we left off.  we only do so
825          * if the region we failed to issue read-ahead on is still ahead
826          * of the app and behind the next index to start read-ahead from */
827         CDEBUG(D_READA, "ra_end %lu end %lu stride end %lu \n",
828                ra_end, end, ria->ria_end);
829
830         if (ra_end != end + 1) {
831                 spin_lock(&ras->ras_lock);
832                 if (ra_end < ras->ras_next_readahead &&
833                     index_in_window(ra_end, ras->ras_window_start, 0,
834                                     ras->ras_window_len)) {
835                         ras->ras_next_readahead = ra_end;
836                                RAS_CDEBUG(ras);
837                 }
838                 spin_unlock(&ras->ras_lock);
839         }
840
841         RETURN(ret);
842 }
843
844 static void ras_set_start(struct ll_readahead_state *ras, unsigned long index)
845 {
846         ras->ras_window_start = index & (~(RAS_INCREASE_STEP - 1));
847 }
848
849 /* called with the ras_lock held or from places where it doesn't matter */
850 static void ras_reset(struct ll_readahead_state *ras, unsigned long index)
851 {
852         ras->ras_last_readpage = index;
853         ras->ras_consecutive_requests = 0;
854         ras->ras_consecutive_pages = 0;
855         ras->ras_window_len = 0;
856         ras_set_start(ras, index);
857         ras->ras_next_readahead = max(ras->ras_window_start, index);
858
859         RAS_CDEBUG(ras);
860 }
861
862 /* called with the ras_lock held or from places where it doesn't matter */
863 static void ras_stride_reset(struct ll_readahead_state *ras)
864 {
865         ras->ras_consecutive_stride_requests = 0;
866         ras->ras_stride_length = 0;
867         ras->ras_stride_pages = 0;
868         RAS_CDEBUG(ras);
869 }
870
871 void ll_readahead_init(struct inode *inode, struct ll_readahead_state *ras)
872 {
873         spin_lock_init(&ras->ras_lock);
874         ras_reset(ras, 0);
875         ras->ras_requests = 0;
876         INIT_LIST_HEAD(&ras->ras_read_beads);
877 }
878
879 /*
880  * Check whether the read request is in the stride window.
881  * If it is in the stride window, return 1, otherwise return 0.
882  */
883 static int index_in_stride_window(unsigned long index,
884                                   struct ll_readahead_state *ras,
885                                   struct inode *inode)
886 {
887         unsigned long stride_gap = index - ras->ras_last_readpage - 1;
888
889         if (ras->ras_stride_length == 0 || ras->ras_stride_pages == 0 ||
890             ras->ras_stride_pages == ras->ras_stride_length)
891                 return 0;
892
893         /* If it is contiguous read */
894         if (stride_gap == 0)
895                 return ras->ras_consecutive_pages + 1 <= ras->ras_stride_pages;
896
897         /*Otherwise check the stride by itself */
898         return (ras->ras_stride_length - ras->ras_stride_pages) == stride_gap &&
899              ras->ras_consecutive_pages == ras->ras_stride_pages;
900 }
901
902 static void ras_update_stride_detector(struct ll_readahead_state *ras,
903                                        unsigned long index)
904 {
905         unsigned long stride_gap = index - ras->ras_last_readpage - 1;
906
907         if (!stride_io_mode(ras) && (stride_gap != 0 ||
908              ras->ras_consecutive_stride_requests == 0)) {
909                 ras->ras_stride_pages = ras->ras_consecutive_pages;
910                 ras->ras_stride_length = stride_gap +ras->ras_consecutive_pages;
911         }
912         LASSERT(ras->ras_request_index == 0);
913         LASSERT(ras->ras_consecutive_stride_requests == 0);
914
915         if (index <= ras->ras_last_readpage) {
916                 /*Reset stride window for forward read*/
917                 ras_stride_reset(ras);
918                 return;
919         }
920
921         ras->ras_stride_pages = ras->ras_consecutive_pages;
922         ras->ras_stride_length = stride_gap +ras->ras_consecutive_pages;
923
924         RAS_CDEBUG(ras);
925         return;
926 }
927
928 static unsigned long
929 stride_page_count(struct ll_readahead_state *ras, unsigned long len)
930 {
931         return stride_pg_count(ras->ras_stride_offset, ras->ras_stride_length,
932                                ras->ras_stride_pages, ras->ras_stride_offset,
933                                len);
934 }
935
936 /* Stride Read-ahead window will be increased inc_len according to
937  * stride I/O pattern */
938 static void ras_stride_increase_window(struct ll_readahead_state *ras,
939                                        struct ll_ra_info *ra,
940                                        unsigned long inc_len)
941 {
942         unsigned long left, step, window_len;
943         unsigned long stride_len;
944
945         LASSERT(ras->ras_stride_length > 0);
946         LASSERTF(ras->ras_window_start + ras->ras_window_len
947                  >= ras->ras_stride_offset, "window_start %lu, window_len %lu"
948                  " stride_offset %lu\n", ras->ras_window_start,
949                  ras->ras_window_len, ras->ras_stride_offset);
950
951         stride_len = ras->ras_window_start + ras->ras_window_len -
952                      ras->ras_stride_offset;
953
954         left = stride_len % ras->ras_stride_length;
955         window_len = ras->ras_window_len - left;
956
957         if (left < ras->ras_stride_pages)
958                 left += inc_len;
959         else
960                 left = ras->ras_stride_pages + inc_len;
961
962         LASSERT(ras->ras_stride_pages != 0);
963
964         step = left / ras->ras_stride_pages;
965         left %= ras->ras_stride_pages;
966
967         window_len += step * ras->ras_stride_length + left;
968
969         if (stride_page_count(ras, window_len) <= ra->ra_max_pages_per_file)
970                 ras->ras_window_len = window_len;
971
972         RAS_CDEBUG(ras);
973 }
974
975 static void ras_increase_window(struct ll_readahead_state *ras,
976                                 struct ll_ra_info *ra, struct inode *inode)
977 {
978         /* The stretch of ra-window should be aligned with max rpc_size
979          * but current clio architecture does not support retrieve such
980          * information from lower layer. FIXME later
981          */
982         if (stride_io_mode(ras))
983                 ras_stride_increase_window(ras, ra, RAS_INCREASE_STEP);
984         else
985                 ras->ras_window_len = min(ras->ras_window_len +
986                                           RAS_INCREASE_STEP,
987                                           ra->ra_max_pages_per_file);
988 }
989
990 void ras_update(struct ll_sb_info *sbi, struct inode *inode,
991                 struct ll_readahead_state *ras, unsigned long index,
992                 unsigned hit)
993 {
994         struct ll_ra_info *ra = &sbi->ll_ra_info;
995         int zero = 0, stride_detect = 0, ra_miss = 0;
996         ENTRY;
997
998         spin_lock(&sbi->ll_lock);
999         spin_lock(&ras->ras_lock);
1000
1001         ll_ra_stats_inc_sbi(sbi, hit ? RA_STAT_HIT : RA_STAT_MISS);
1002
1003         /* reset the read-ahead window in two cases.  First when the app seeks
1004          * or reads to some other part of the file.  Secondly if we get a
1005          * read-ahead miss that we think we've previously issued.  This can
1006          * be a symptom of there being so many read-ahead pages that the VM is
1007          * reclaiming it before we get to it. */
1008         if (!index_in_window(index, ras->ras_last_readpage, 8, 8)) {
1009                 zero = 1;
1010                 ll_ra_stats_inc_sbi(sbi, RA_STAT_DISTANT_READPAGE);
1011         } else if (!hit && ras->ras_window_len &&
1012                    index < ras->ras_next_readahead &&
1013                    index_in_window(index, ras->ras_window_start, 0,
1014                                    ras->ras_window_len)) {
1015                 ra_miss = 1;
1016                 ll_ra_stats_inc_sbi(sbi, RA_STAT_MISS_IN_WINDOW);
1017         }
1018
1019         /* On the second access to a file smaller than the tunable
1020          * ra_max_read_ahead_whole_pages trigger RA on all pages in the
1021          * file up to ra_max_pages_per_file.  This is simply a best effort
1022          * and only occurs once per open file.  Normal RA behavior is reverted
1023          * to for subsequent IO.  The mmap case does not increment
1024          * ras_requests and thus can never trigger this behavior. */
1025         if (ras->ras_requests == 2 && !ras->ras_request_index) {
1026                 __u64 kms_pages;
1027
1028                 kms_pages = (i_size_read(inode) + CFS_PAGE_SIZE - 1) >>
1029                             CFS_PAGE_SHIFT;
1030
1031                 CDEBUG(D_READA, "kmsp "LPU64" mwp %lu mp %lu\n", kms_pages,
1032                        ra->ra_max_read_ahead_whole_pages, ra->ra_max_pages_per_file);
1033
1034                 if (kms_pages &&
1035                     kms_pages <= ra->ra_max_read_ahead_whole_pages) {
1036                         ras->ras_window_start = 0;
1037                         ras->ras_last_readpage = 0;
1038                         ras->ras_next_readahead = 0;
1039                         ras->ras_window_len = min(ra->ra_max_pages_per_file,
1040                                 ra->ra_max_read_ahead_whole_pages);
1041                         GOTO(out_unlock, 0);
1042                 }
1043         }
1044         if (zero) {
1045                 /* check whether it is in stride I/O mode*/
1046                 if (!index_in_stride_window(index, ras, inode)) {
1047                         if (ras->ras_consecutive_stride_requests == 0 &&
1048                             ras->ras_request_index == 0) {
1049                                 ras_update_stride_detector(ras, index);
1050                                 ras->ras_consecutive_stride_requests ++;
1051                         } else {
1052                                 ras_stride_reset(ras);
1053                         }
1054                         ras_reset(ras, index);
1055                         ras->ras_consecutive_pages++;
1056                         GOTO(out_unlock, 0);
1057                 } else {
1058                         ras->ras_consecutive_pages = 0;
1059                         ras->ras_consecutive_requests = 0;
1060                         if (++ras->ras_consecutive_stride_requests > 1)
1061                                 stride_detect = 1;
1062                         RAS_CDEBUG(ras);
1063                 }
1064         } else {
1065                 if (ra_miss) {
1066                         if (index_in_stride_window(index, ras, inode) &&
1067                             stride_io_mode(ras)) {
1068                                 /*If stride-RA hit cache miss, the stride dector
1069                                  *will not be reset to avoid the overhead of
1070                                  *redetecting read-ahead mode */
1071                                 if (index != ras->ras_last_readpage + 1)
1072                                        ras->ras_consecutive_pages = 0;
1073                                 ras_reset(ras, index);
1074                                 RAS_CDEBUG(ras);
1075                         } else {
1076                                 /* Reset both stride window and normal RA
1077                                  * window */
1078                                 ras_reset(ras, index);
1079                                 ras->ras_consecutive_pages++;
1080                                 ras_stride_reset(ras);
1081                                 GOTO(out_unlock, 0);
1082                         }
1083                 } else if (stride_io_mode(ras)) {
1084                         /* If this is contiguous read but in stride I/O mode
1085                          * currently, check whether stride step still is valid,
1086                          * if invalid, it will reset the stride ra window*/
1087                         if (!index_in_stride_window(index, ras, inode)) {
1088                                 /* Shrink stride read-ahead window to be zero */
1089                                 ras_stride_reset(ras);
1090                                 ras->ras_window_len = 0;
1091                                 ras->ras_next_readahead = index;
1092                         }
1093                 }
1094         }
1095         ras->ras_consecutive_pages++;
1096         ras->ras_last_readpage = index;
1097         ras_set_start(ras, index);
1098         ras->ras_next_readahead = max(ras->ras_window_start,
1099                                       ras->ras_next_readahead);
1100         RAS_CDEBUG(ras);
1101
1102         /* Trigger RA in the mmap case where ras_consecutive_requests
1103          * is not incremented and thus can't be used to trigger RA */
1104         if (!ras->ras_window_len && ras->ras_consecutive_pages == 4) {
1105                 ras->ras_window_len = RAS_INCREASE_STEP;
1106                 GOTO(out_unlock, 0);
1107         }
1108
1109         /* Initially reset the stride window offset to next_readahead*/
1110         if (ras->ras_consecutive_stride_requests == 2 && stride_detect) {
1111                 /**
1112                  * Once stride IO mode is detected, next_readahead should be
1113                  * reset to make sure next_readahead > stride offset
1114                  */
1115                 ras->ras_next_readahead = max(index, ras->ras_next_readahead);
1116                 ras->ras_stride_offset = index;
1117                 ras->ras_window_len = RAS_INCREASE_STEP;
1118         }
1119
1120         /* The initial ras_window_len is set to the request size.  To avoid
1121          * uselessly reading and discarding pages for random IO the window is
1122          * only increased once per consecutive request received. */
1123         if ((ras->ras_consecutive_requests > 1 || stride_detect) &&
1124             !ras->ras_request_index)
1125                 ras_increase_window(ras, ra, inode);
1126         EXIT;
1127 out_unlock:
1128         RAS_CDEBUG(ras);
1129         ras->ras_request_index++;
1130         spin_unlock(&ras->ras_lock);
1131         spin_unlock(&sbi->ll_lock);
1132         return;
1133 }
1134
1135 int ll_writepage(struct page *vmpage, struct writeback_control *unused)
1136 {
1137         struct inode           *inode = vmpage->mapping->host;
1138         struct lu_env          *env;
1139         struct cl_io           *io;
1140         struct cl_page         *page;
1141         struct cl_object       *clob;
1142         struct cl_2queue       *queue;
1143         struct cl_env_nest      nest;
1144         int result;
1145         ENTRY;
1146
1147         LASSERT(PageLocked(vmpage));
1148         LASSERT(!PageWriteback(vmpage));
1149
1150         if (ll_i2dtexp(inode) == NULL)
1151                 RETURN(-EINVAL);
1152
1153         env = cl_env_nested_get(&nest);
1154         if (IS_ERR(env))
1155                 RETURN(PTR_ERR(env));
1156
1157         io    = &ccc_env_info(env)->cti_io;
1158         queue = &vvp_env_info(env)->vti_queue;
1159         clob  = ll_i2info(inode)->lli_clob;
1160         LASSERT(clob != NULL);
1161
1162         io->ci_obj = clob;
1163         result = cl_io_init(env, io, CIT_MISC, clob);
1164         if (result == 0) {
1165                 page = cl_page_find(env, clob, vmpage->index,
1166                                     vmpage, CPT_CACHEABLE);
1167                 if (!IS_ERR(page)) {
1168                         lu_ref_add(&page->cp_reference, "writepage",
1169                                    cfs_current());
1170                         cl_page_assume(env, io, page);
1171                         /*
1172                          * Mark page dirty, because this is what
1173                          * ->vio_submit()->cpo_prep_write() assumes.
1174                          *
1175                          * XXX better solution is to detect this from within
1176                          * cl_io_submit_rw() somehow.
1177                          */
1178                         set_page_dirty(vmpage);
1179                         cl_2queue_init_page(queue, page);
1180                         result = cl_io_submit_rw(env, io, CRT_WRITE,
1181                                                  queue, CRP_NORMAL);
1182                         cl_page_list_disown(env, io, &queue->c2_qin);
1183                         if (result != 0) {
1184                                 /*
1185                                  * There is no need to clear PG_writeback, as
1186                                  * cl_io_submit_rw() calls completion callback
1187                                  * on failure.
1188                                  */
1189                                 /*
1190                                  * Re-dirty page on error so it retries write,
1191                                  * but not in case when IO has actually
1192                                  * occurred and completed with an error.
1193                                  */
1194                                 if (!PageError(vmpage))
1195                                         set_page_dirty(vmpage);
1196                         }
1197                         LASSERT(!cl_page_is_owned(page, io));
1198                         lu_ref_del(&page->cp_reference,
1199                                    "writepage", cfs_current());
1200                         cl_page_put(env, page);
1201                         cl_2queue_fini(env, queue);
1202                 }
1203         }
1204         cl_io_fini(env, io);
1205         cl_env_nested_put(&nest, env);
1206         RETURN(result);
1207 }
1208
1209 int ll_readpage(struct file *file, struct page *vmpage)
1210 {
1211         struct lu_env    *env;
1212         struct cl_io     *io;
1213         struct cl_page   *page;
1214         int result;
1215         int refcheck;
1216         ENTRY;
1217
1218         result = ll_cl_init(file, vmpage, &env, &io, &page, &refcheck);
1219         if (result == 0) {
1220                 LASSERT(page->cp_type == CPT_CACHEABLE);
1221                 if (likely(!PageUptodate(vmpage))) {
1222                         cl_page_assume(env, io, page);
1223                         result = cl_io_read_page(env, io, page);
1224                 } else {
1225                         /* Page from a non-object file. */
1226                         LASSERT(!ll_i2info(vmpage->mapping->host)->lli_smd);
1227                         unlock_page(vmpage);
1228                         result = 0;
1229                 }
1230         }
1231         LASSERT(!cl_page_is_owned(page, io));
1232         ll_cl_fini(env, io, page, &refcheck);
1233         RETURN(result);
1234 }
1235