Whamcloud - gitweb
LU-5505 clio: revise read ahead algorithm
[fs/lustre-release.git] / lustre / llite / rw.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
19  *
20  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
21  * CA 95054 USA or visit www.sun.com if you need additional information or
22  * have any questions.
23  *
24  * GPL HEADER END
25  */
26 /*
27  * Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  *
30  * Copyright (c) 2011, 2015, Intel Corporation.
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/kernel.h>
42 #include <linux/mm.h>
43 #include <linux/string.h>
44 #include <linux/stat.h>
45 #include <linux/errno.h>
46 #include <linux/unistd.h>
47 #include <linux/writeback.h>
48 #include <asm/uaccess.h>
49
50 #include <linux/fs.h>
51 #include <linux/stat.h>
52 #include <asm/uaccess.h>
53 #include <linux/mm.h>
54 #include <linux/pagemap.h>
55 /* current_is_kswapd() */
56 #include <linux/swap.h>
57
58 #define DEBUG_SUBSYSTEM S_LLITE
59
60 #include <obd_cksum.h>
61 #include "llite_internal.h"
62 #include <lustre_compat.h>
63
64 static void ll_ra_stats_inc_sbi(struct ll_sb_info *sbi, enum ra_stat which);
65
66 /**
67  * Get readahead pages from the filesystem readahead pool of the client for a
68  * thread.
69  *
70  * /param sbi superblock for filesystem readahead state ll_ra_info
71  * /param ria per-thread readahead state
72  * /param pages number of pages requested for readahead for the thread.
73  *
74  * WARNING: This algorithm is used to reduce contention on sbi->ll_lock.
75  * It should work well if the ra_max_pages is much greater than the single
76  * file's read-ahead window, and not too many threads contending for
77  * these readahead pages.
78  *
79  * TODO: There may be a 'global sync problem' if many threads are trying
80  * to get an ra budget that is larger than the remaining readahead pages
81  * and reach here at exactly the same time. They will compute /a ret to
82  * consume the remaining pages, but will fail at atomic_add_return() and
83  * get a zero ra window, although there is still ra space remaining. - Jay */
84
85 static unsigned long ll_ra_count_get(struct ll_sb_info *sbi,
86                                      struct ra_io_arg *ria,
87                                      unsigned long pages, unsigned long min)
88 {
89         struct ll_ra_info *ra = &sbi->ll_ra_info;
90         long ret;
91         ENTRY;
92
93         /* If read-ahead pages left are less than 1M, do not do read-ahead,
94          * otherwise it will form small read RPC(< 1M), which hurt server
95          * performance a lot. */
96         ret = min(ra->ra_max_pages - atomic_read(&ra->ra_cur_pages),
97                   pages);
98         if (ret < 0 || ret < min_t(long, PTLRPC_MAX_BRW_PAGES, pages))
99                 GOTO(out, ret = 0);
100
101         /* If the non-strided (ria_pages == 0) readahead window
102          * (ria_start + ret) has grown across an RPC boundary, then trim
103          * readahead size by the amount beyond the RPC so it ends on an
104          * RPC boundary. If the readahead window is already ending on
105          * an RPC boundary (beyond_rpc == 0), or smaller than a full
106          * RPC (beyond_rpc < ret) the readahead size is unchanged.
107          * The (beyond_rpc != 0) check is skipped since the conditional
108          * branch is more expensive than subtracting zero from the result.
109          *
110          * Strided read is left unaligned to avoid small fragments beyond
111          * the RPC boundary from needing an extra read RPC. */
112         if (ria->ria_pages == 0) {
113                 long beyond_rpc = (ria->ria_start + ret) % PTLRPC_MAX_BRW_PAGES;
114                 if (/* beyond_rpc != 0 && */ beyond_rpc < ret)
115                         ret -= beyond_rpc;
116         }
117
118         if (atomic_add_return(ret, &ra->ra_cur_pages) > ra->ra_max_pages) {
119                 atomic_sub(ret, &ra->ra_cur_pages);
120                 ret = 0;
121         }
122
123 out:
124         if (ret < min) {
125                 /* override ra limit for maximum performance */
126                 atomic_add(min - ret, &ra->ra_cur_pages);
127                 ret = min;
128         }
129         RETURN(ret);
130 }
131
132 void ll_ra_count_put(struct ll_sb_info *sbi, unsigned long len)
133 {
134         struct ll_ra_info *ra = &sbi->ll_ra_info;
135         atomic_sub(len, &ra->ra_cur_pages);
136 }
137
138 static void ll_ra_stats_inc_sbi(struct ll_sb_info *sbi, enum ra_stat which)
139 {
140         LASSERTF(which >= 0 && which < _NR_RA_STAT, "which: %u\n", which);
141         lprocfs_counter_incr(sbi->ll_ra_stats, which);
142 }
143
144 void ll_ra_stats_inc(struct inode *inode, enum ra_stat which)
145 {
146         struct ll_sb_info *sbi = ll_i2sbi(inode);
147         ll_ra_stats_inc_sbi(sbi, which);
148 }
149
150 #define RAS_CDEBUG(ras) \
151         CDEBUG(D_READA,                                                      \
152                "lrp %lu cr %lu cp %lu ws %lu wl %lu nra %lu r %lu ri %lu"    \
153                "csr %lu sf %lu sp %lu sl %lu \n",                            \
154                ras->ras_last_readpage, ras->ras_consecutive_requests,        \
155                ras->ras_consecutive_pages, ras->ras_window_start,            \
156                ras->ras_window_len, ras->ras_next_readahead,                 \
157                ras->ras_requests, ras->ras_request_index,                    \
158                ras->ras_consecutive_stride_requests, ras->ras_stride_offset, \
159                ras->ras_stride_pages, ras->ras_stride_length)
160
161 static int index_in_window(unsigned long index, unsigned long point,
162                            unsigned long before, unsigned long after)
163 {
164         unsigned long start = point - before, end = point + after;
165
166         if (start > point)
167                start = 0;
168         if (end < point)
169                end = ~0;
170
171         return start <= index && index <= end;
172 }
173
174 void ll_ras_enter(struct file *f)
175 {
176         struct ll_file_data *fd = LUSTRE_FPRIVATE(f);
177         struct ll_readahead_state *ras = &fd->fd_ras;
178
179         spin_lock(&ras->ras_lock);
180         ras->ras_requests++;
181         ras->ras_request_index = 0;
182         ras->ras_consecutive_requests++;
183         spin_unlock(&ras->ras_lock);
184 }
185
186 /**
187  * Initiates read-ahead of a page with given index.
188  *
189  * \retval +ve: page was already uptodate so it will be skipped
190  *              from being added;
191  * \retval -ve: page wasn't added to \a queue for error;
192  * \retval   0: page was added into \a queue for read ahead.
193  */
194 static int ll_read_ahead_page(const struct lu_env *env, struct cl_io *io,
195                               struct cl_page_list *queue, pgoff_t index)
196 {
197         struct cl_object *clob  = io->ci_obj;
198         struct inode     *inode = vvp_object_inode(clob);
199         struct page      *vmpage;
200         struct cl_page   *page;
201         struct vvp_page  *vpg;
202         enum ra_stat      which = _NR_RA_STAT; /* keep gcc happy */
203         int               rc    = 0;
204         const char       *msg   = NULL;
205         ENTRY;
206
207         vmpage = grab_cache_page_nowait(inode->i_mapping, index);
208         if (vmpage == NULL) {
209                 which = RA_STAT_FAILED_GRAB_PAGE;
210                 msg   = "g_c_p_n failed";
211                 GOTO(out, rc = -EBUSY);
212         }
213
214         /* Check if vmpage was truncated or reclaimed */
215         if (vmpage->mapping != inode->i_mapping) {
216                 which = RA_STAT_WRONG_GRAB_PAGE;
217                 msg   = "g_c_p_n returned invalid page";
218                 GOTO(out, rc = -EBUSY);
219         }
220
221         page = cl_page_find(env, clob, vmpage->index, vmpage, CPT_CACHEABLE);
222         if (IS_ERR(page)) {
223                 which = RA_STAT_FAILED_GRAB_PAGE;
224                 msg   = "cl_page_find failed";
225                 GOTO(out, rc = PTR_ERR(page));
226         }
227
228         lu_ref_add(&page->cp_reference, "ra", current);
229         cl_page_assume(env, io, page);
230         vpg = cl2vvp_page(cl_object_page_slice(clob, page));
231         if (!vpg->vpg_defer_uptodate && !PageUptodate(vmpage)) {
232                 vpg->vpg_defer_uptodate = 1;
233                 vpg->vpg_ra_used = 0;
234                 cl_page_list_add(queue, page);
235         } else {
236                 /* skip completed pages */
237                 cl_page_unassume(env, io, page);
238                 /* This page is already uptodate, returning a positive number
239                  * to tell the callers about this */
240                 rc = 1;
241         }
242
243         lu_ref_del(&page->cp_reference, "ra", current);
244         cl_page_put(env, page);
245
246 out:
247         if (vmpage != NULL) {
248                 if (rc != 0)
249                         unlock_page(vmpage);
250                 page_cache_release(vmpage);
251         }
252         if (msg != NULL) {
253                 ll_ra_stats_inc(inode, which);
254                 CDEBUG(D_READA, "%s\n", msg);
255
256         }
257
258         RETURN(rc);
259 }
260
261 #define RIA_DEBUG(ria)                                                       \
262         CDEBUG(D_READA, "rs %lu re %lu ro %lu rl %lu rp %lu\n",       \
263         ria->ria_start, ria->ria_end, ria->ria_stoff, ria->ria_length,\
264         ria->ria_pages)
265
266 /* Limit this to the blocksize instead of PTLRPC_BRW_MAX_SIZE, since we don't
267  * know what the actual RPC size is.  If this needs to change, it makes more
268  * sense to tune the i_blkbits value for the file based on the OSTs it is
269  * striped over, rather than having a constant value for all files here. */
270
271 /* RAS_INCREASE_STEP should be (1UL << (inode->i_blkbits - PAGE_CACHE_SHIFT)).
272  * Temprarily set RAS_INCREASE_STEP to 1MB. After 4MB RPC is enabled
273  * by default, this should be adjusted corresponding with max_read_ahead_mb
274  * and max_read_ahead_per_file_mb otherwise the readahead budget can be used
275  * up quickly which will affect read performance siginificantly. See LU-2816 */
276 #define RAS_INCREASE_STEP(inode) (ONE_MB_BRW_SIZE >> PAGE_CACHE_SHIFT)
277
278 static inline int stride_io_mode(struct ll_readahead_state *ras)
279 {
280         return ras->ras_consecutive_stride_requests > 1;
281 }
282 /* The function calculates how much pages will be read in
283  * [off, off + length], in such stride IO area,
284  * stride_offset = st_off, stride_lengh = st_len,
285  * stride_pages = st_pgs
286  *
287  *   |------------------|*****|------------------|*****|------------|*****|....
288  * st_off
289  *   |--- st_pgs     ---|
290  *   |-----     st_len   -----|
291  *
292  *              How many pages it should read in such pattern
293  *              |-------------------------------------------------------------|
294  *              off
295  *              |<------                  length                      ------->|
296  *
297  *          =   |<----->|  +  |-------------------------------------| +   |---|
298  *             start_left                 st_pgs * i                    end_left
299  */
300 static unsigned long
301 stride_pg_count(pgoff_t st_off, unsigned long st_len, unsigned long st_pgs,
302                 unsigned long off, unsigned long length)
303 {
304         __u64 start = off > st_off ? off - st_off : 0;
305         __u64 end = off + length > st_off ? off + length - st_off : 0;
306         unsigned long start_left = 0;
307         unsigned long end_left = 0;
308         unsigned long pg_count;
309
310         if (st_len == 0 || length == 0 || end == 0)
311                 return length;
312
313         start_left = do_div(start, st_len);
314         if (start_left < st_pgs)
315                 start_left = st_pgs - start_left;
316         else
317                 start_left = 0;
318
319         end_left = do_div(end, st_len);
320         if (end_left > st_pgs)
321                 end_left = st_pgs;
322
323         CDEBUG(D_READA, "start "LPU64", end "LPU64" start_left %lu end_left %lu \n",
324                start, end, start_left, end_left);
325
326         if (start == end)
327                 pg_count = end_left - (st_pgs - start_left);
328         else
329                 pg_count = start_left + st_pgs * (end - start - 1) + end_left;
330
331         CDEBUG(D_READA, "st_off %lu, st_len %lu st_pgs %lu off %lu length %lu"
332                "pgcount %lu\n", st_off, st_len, st_pgs, off, length, pg_count);
333
334         return pg_count;
335 }
336
337 static int ria_page_count(struct ra_io_arg *ria)
338 {
339         __u64 length = ria->ria_end >= ria->ria_start ?
340                        ria->ria_end - ria->ria_start + 1 : 0;
341
342         return stride_pg_count(ria->ria_stoff, ria->ria_length,
343                                ria->ria_pages, ria->ria_start,
344                                length);
345 }
346
347 /*Check whether the index is in the defined ra-window */
348 static int ras_inside_ra_window(unsigned long idx, struct ra_io_arg *ria)
349 {
350         /* If ria_length == ria_pages, it means non-stride I/O mode,
351          * idx should always inside read-ahead window in this case
352          * For stride I/O mode, just check whether the idx is inside
353          * the ria_pages. */
354         return ria->ria_length == 0 || ria->ria_length == ria->ria_pages ||
355                (idx >= ria->ria_stoff && (idx - ria->ria_stoff) %
356                 ria->ria_length < ria->ria_pages);
357 }
358
359 static int ll_read_ahead_pages(const struct lu_env *env,
360                                struct cl_io *io, struct cl_page_list *queue,
361                                struct ra_io_arg *ria,
362                                unsigned long *reserved_pages,
363                                pgoff_t *ra_end)
364 {
365         struct cl_read_ahead ra = { 0 };
366         int rc, count = 0;
367         bool stride_ria;
368         pgoff_t page_idx;
369
370         LASSERT(ria != NULL);
371         RIA_DEBUG(ria);
372
373         stride_ria = ria->ria_length > ria->ria_pages && ria->ria_pages > 0;
374         for (page_idx = ria->ria_start;
375              page_idx <= ria->ria_end && *reserved_pages > 0; page_idx++) {
376                 if (ras_inside_ra_window(page_idx, ria)) {
377                         if (ra.cra_end == 0 || ra.cra_end < page_idx) {
378                                 cl_read_ahead_release(env, &ra);
379
380                                 rc = cl_io_read_ahead(env, io, page_idx, &ra);
381                                 if (rc < 0)
382                                         break;
383
384                                 LASSERTF(ra.cra_end >= page_idx,
385                                          "object: %p, indcies %lu / %lu\n",
386                                          io->ci_obj, ra.cra_end, page_idx);
387                         }
388
389                         /* If the page is inside the read-ahead window*/
390                         rc = ll_read_ahead_page(env, io, queue, page_idx);
391                         if (rc == 0) {
392                                 (*reserved_pages)--;
393                                 count++;
394                         }
395                 } else if (stride_ria) {
396                         /* If it is not in the read-ahead window, and it is
397                          * read-ahead mode, then check whether it should skip
398                          * the stride gap */
399                         pgoff_t offset;
400                         /* FIXME: This assertion only is valid when it is for
401                          * forward read-ahead, it will be fixed when backward
402                          * read-ahead is implemented */
403                         LASSERTF(page_idx >= ria->ria_stoff,
404                                 "Invalid page_idx %lu rs %lu re %lu ro %lu "
405                                 "rl %lu rp %lu\n", page_idx,
406                                 ria->ria_start, ria->ria_end, ria->ria_stoff,
407                                 ria->ria_length, ria->ria_pages);
408                         offset = page_idx - ria->ria_stoff;
409                         offset = offset % (ria->ria_length);
410                         if (offset > ria->ria_pages) {
411                                 page_idx += ria->ria_length - offset;
412                                 CDEBUG(D_READA, "i %lu skip %lu \n", page_idx,
413                                        ria->ria_length - offset);
414                                 continue;
415                         }
416                 }
417         }
418
419         cl_read_ahead_release(env, &ra);
420
421         *ra_end = page_idx;
422         return count;
423 }
424
425 static int ll_readahead(const struct lu_env *env, struct cl_io *io,
426                         struct cl_page_list *queue,
427                         struct ll_readahead_state *ras, bool hit)
428 {
429         struct vvp_io *vio = vvp_env_io(env);
430         struct ll_thread_info *lti = ll_env_info(env);
431         struct cl_attr *attr = vvp_env_thread_attr(env);
432         unsigned long len, mlen = 0, reserved;
433         pgoff_t ra_end, start = 0, end = 0;
434         struct inode *inode;
435         struct ra_io_arg *ria = &lti->lti_ria;
436         struct cl_object *clob;
437         int ret = 0;
438         __u64 kms;
439         ENTRY;
440
441         clob = io->ci_obj;
442         inode = vvp_object_inode(clob);
443
444         memset(ria, 0, sizeof *ria);
445
446         cl_object_attr_lock(clob);
447         ret = cl_object_attr_get(env, clob, attr);
448         cl_object_attr_unlock(clob);
449
450         if (ret != 0)
451                 RETURN(ret);
452         kms = attr->cat_kms;
453         if (kms == 0) {
454                 ll_ra_stats_inc(inode, RA_STAT_ZERO_LEN);
455                 RETURN(0);
456         }
457
458         spin_lock(&ras->ras_lock);
459
460         /**
461          * Note: other thread might rollback the ras_next_readahead,
462          * if it can not get the full size of prepared pages, see the
463          * end of this function. For stride read ahead, it needs to
464          * make sure the offset is no less than ras_stride_offset,
465          * so that stride read ahead can work correctly.
466          */
467         if (stride_io_mode(ras))
468                 start = max(ras->ras_next_readahead, ras->ras_stride_offset);
469         else
470                 start = ras->ras_next_readahead;
471
472         if (ras->ras_window_len > 0)
473                 end = ras->ras_window_start + ras->ras_window_len - 1;
474
475         /* Enlarge the RA window to encompass the full read */
476         if (vio->vui_ra_valid &&
477             end < vio->vui_ra_start + vio->vui_ra_count - 1)
478                 end = vio->vui_ra_start + vio->vui_ra_count - 1;
479
480         if (end != 0) {
481                 unsigned long rpc_boundary;
482                 /*
483                  * Align RA window to an optimal boundary.
484                  *
485                  * XXX This would be better to align to cl_max_pages_per_rpc
486                  * instead of PTLRPC_MAX_BRW_PAGES, because the RPC size may
487                  * be aligned to the RAID stripe size in the future and that
488                  * is more important than the RPC size.
489                  */
490                 /* Note: we only trim the RPC, instead of extending the RPC
491                  * to the boundary, so to avoid reading too much pages during
492                  * random reading. */
493                 rpc_boundary = ((end + 1) & (~(PTLRPC_MAX_BRW_PAGES - 1)));
494                 if (rpc_boundary > 0)
495                         rpc_boundary--;
496
497                 if (rpc_boundary  > start)
498                         end = rpc_boundary;
499
500                 /* Truncate RA window to end of file */
501                 end = min(end, (unsigned long)((kms - 1) >> PAGE_CACHE_SHIFT));
502
503                 ras->ras_next_readahead = max(end, end + 1);
504                 RAS_CDEBUG(ras);
505         }
506         ria->ria_start = start;
507         ria->ria_end = end;
508         /* If stride I/O mode is detected, get stride window*/
509         if (stride_io_mode(ras)) {
510                 ria->ria_stoff = ras->ras_stride_offset;
511                 ria->ria_length = ras->ras_stride_length;
512                 ria->ria_pages = ras->ras_stride_pages;
513         }
514         spin_unlock(&ras->ras_lock);
515
516         if (end == 0) {
517                 ll_ra_stats_inc(inode, RA_STAT_ZERO_WINDOW);
518                 RETURN(0);
519         }
520         len = ria_page_count(ria);
521         if (len == 0) {
522                 ll_ra_stats_inc(inode, RA_STAT_ZERO_WINDOW);
523                 RETURN(0);
524         }
525
526         CDEBUG(D_READA, DFID": ria: %lu/%lu, bead: %lu/%lu, hit: %d\n",
527                PFID(lu_object_fid(&clob->co_lu)),
528                ria->ria_start, ria->ria_end,
529                vio->vui_ra_valid ? vio->vui_ra_start : 0,
530                vio->vui_ra_valid ? vio->vui_ra_count : 0,
531                hit);
532
533         /* at least to extend the readahead window to cover current read */
534         if (!hit && vio->vui_ra_valid &&
535             vio->vui_ra_start + vio->vui_ra_count > ria->ria_start) {
536                 /* to the end of current read window. */
537                 mlen = vio->vui_ra_start + vio->vui_ra_count - ria->ria_start;
538                 /* trim to RPC boundary */
539                 start = ria->ria_start & (PTLRPC_MAX_BRW_PAGES - 1);
540                 mlen = min(mlen, PTLRPC_MAX_BRW_PAGES - start);
541         }
542
543         reserved = ll_ra_count_get(ll_i2sbi(inode), ria, len, mlen);
544         if (reserved < len)
545                 ll_ra_stats_inc(inode, RA_STAT_MAX_IN_FLIGHT);
546
547         CDEBUG(D_READA, "reserved pages: %lu/%lu/%lu, ra_cur %d, ra_max %lu\n",
548                reserved, len, mlen,
549                atomic_read(&ll_i2sbi(inode)->ll_ra_info.ra_cur_pages),
550                ll_i2sbi(inode)->ll_ra_info.ra_max_pages);
551
552         ret = ll_read_ahead_pages(env, io, queue, ria, &reserved, &ra_end);
553
554         if (reserved != 0)
555                 ll_ra_count_put(ll_i2sbi(inode), reserved);
556
557         if (ra_end == end + 1 && ra_end == (kms >> PAGE_CACHE_SHIFT))
558                 ll_ra_stats_inc(inode, RA_STAT_EOF);
559
560         /* if we didn't get to the end of the region we reserved from
561          * the ras we need to go back and update the ras so that the
562          * next read-ahead tries from where we left off.  we only do so
563          * if the region we failed to issue read-ahead on is still ahead
564          * of the app and behind the next index to start read-ahead from */
565         CDEBUG(D_READA, "ra_end = %lu end = %lu stride end = %lu pages = %d\n",
566                ra_end, end, ria->ria_end, ret);
567
568         if (ra_end != end + 1) {
569                 ll_ra_stats_inc(inode, RA_STAT_FAILED_REACH_END);
570                 spin_lock(&ras->ras_lock);
571                 if (ra_end < ras->ras_next_readahead &&
572                     index_in_window(ra_end, ras->ras_window_start, 0,
573                                     ras->ras_window_len)) {
574                         ras->ras_next_readahead = ra_end;
575                         RAS_CDEBUG(ras);
576                 }
577                 spin_unlock(&ras->ras_lock);
578         }
579
580         RETURN(ret);
581 }
582
583 static void ras_set_start(struct inode *inode, struct ll_readahead_state *ras,
584                           unsigned long index)
585 {
586         ras->ras_window_start = index & (~(RAS_INCREASE_STEP(inode) - 1));
587 }
588
589 /* called with the ras_lock held or from places where it doesn't matter */
590 static void ras_reset(struct inode *inode, struct ll_readahead_state *ras,
591                       unsigned long index)
592 {
593         ras->ras_last_readpage = index;
594         ras->ras_consecutive_requests = 0;
595         ras->ras_consecutive_pages = 0;
596         ras->ras_window_len = 0;
597         ras_set_start(inode, ras, index);
598         ras->ras_next_readahead = max(ras->ras_window_start, index + 1);
599
600         RAS_CDEBUG(ras);
601 }
602
603 /* called with the ras_lock held or from places where it doesn't matter */
604 static void ras_stride_reset(struct ll_readahead_state *ras)
605 {
606         ras->ras_consecutive_stride_requests = 0;
607         ras->ras_stride_length = 0;
608         ras->ras_stride_pages = 0;
609         RAS_CDEBUG(ras);
610 }
611
612 void ll_readahead_init(struct inode *inode, struct ll_readahead_state *ras)
613 {
614         spin_lock_init(&ras->ras_lock);
615         ras_reset(inode, ras, 0);
616         ras->ras_requests = 0;
617 }
618
619 /*
620  * Check whether the read request is in the stride window.
621  * If it is in the stride window, return 1, otherwise return 0.
622  */
623 static int index_in_stride_window(struct ll_readahead_state *ras,
624                                   unsigned long index)
625 {
626         unsigned long stride_gap;
627
628         if (ras->ras_stride_length == 0 || ras->ras_stride_pages == 0 ||
629             ras->ras_stride_pages == ras->ras_stride_length)
630                 return 0;
631
632         stride_gap = index - ras->ras_last_readpage - 1;
633
634         /* If it is contiguous read */
635         if (stride_gap == 0)
636                 return ras->ras_consecutive_pages + 1 <= ras->ras_stride_pages;
637
638         /* Otherwise check the stride by itself */
639         return (ras->ras_stride_length - ras->ras_stride_pages) == stride_gap &&
640                 ras->ras_consecutive_pages == ras->ras_stride_pages;
641 }
642
643 static void ras_update_stride_detector(struct ll_readahead_state *ras,
644                                        unsigned long index)
645 {
646         unsigned long stride_gap = index - ras->ras_last_readpage - 1;
647
648         if (!stride_io_mode(ras) && (stride_gap != 0 ||
649              ras->ras_consecutive_stride_requests == 0)) {
650                 ras->ras_stride_pages = ras->ras_consecutive_pages;
651                 ras->ras_stride_length = stride_gap +ras->ras_consecutive_pages;
652         }
653         LASSERT(ras->ras_request_index == 0);
654         LASSERT(ras->ras_consecutive_stride_requests == 0);
655
656         if (index <= ras->ras_last_readpage) {
657                 /*Reset stride window for forward read*/
658                 ras_stride_reset(ras);
659                 return;
660         }
661
662         ras->ras_stride_pages = ras->ras_consecutive_pages;
663         ras->ras_stride_length = stride_gap +ras->ras_consecutive_pages;
664
665         RAS_CDEBUG(ras);
666         return;
667 }
668
669 static unsigned long
670 stride_page_count(struct ll_readahead_state *ras, unsigned long len)
671 {
672         return stride_pg_count(ras->ras_stride_offset, ras->ras_stride_length,
673                                ras->ras_stride_pages, ras->ras_stride_offset,
674                                len);
675 }
676
677 /* Stride Read-ahead window will be increased inc_len according to
678  * stride I/O pattern */
679 static void ras_stride_increase_window(struct ll_readahead_state *ras,
680                                        struct ll_ra_info *ra,
681                                        unsigned long inc_len)
682 {
683         unsigned long left, step, window_len;
684         unsigned long stride_len;
685
686         LASSERT(ras->ras_stride_length > 0);
687         LASSERTF(ras->ras_window_start + ras->ras_window_len
688                  >= ras->ras_stride_offset, "window_start %lu, window_len %lu"
689                  " stride_offset %lu\n", ras->ras_window_start,
690                  ras->ras_window_len, ras->ras_stride_offset);
691
692         stride_len = ras->ras_window_start + ras->ras_window_len -
693                      ras->ras_stride_offset;
694
695         left = stride_len % ras->ras_stride_length;
696         window_len = ras->ras_window_len - left;
697
698         if (left < ras->ras_stride_pages)
699                 left += inc_len;
700         else
701                 left = ras->ras_stride_pages + inc_len;
702
703         LASSERT(ras->ras_stride_pages != 0);
704
705         step = left / ras->ras_stride_pages;
706         left %= ras->ras_stride_pages;
707
708         window_len += step * ras->ras_stride_length + left;
709
710         if (stride_page_count(ras, window_len) <= ra->ra_max_pages_per_file)
711                 ras->ras_window_len = window_len;
712
713         RAS_CDEBUG(ras);
714 }
715
716 static void ras_increase_window(struct inode *inode,
717                                 struct ll_readahead_state *ras,
718                                 struct ll_ra_info *ra)
719 {
720         /* The stretch of ra-window should be aligned with max rpc_size
721          * but current clio architecture does not support retrieve such
722          * information from lower layer. FIXME later
723          */
724         if (stride_io_mode(ras))
725                 ras_stride_increase_window(ras, ra, RAS_INCREASE_STEP(inode));
726         else
727                 ras->ras_window_len = min(ras->ras_window_len +
728                                           RAS_INCREASE_STEP(inode),
729                                           ra->ra_max_pages_per_file);
730 }
731
732 static void ras_update(struct ll_sb_info *sbi, struct inode *inode,
733                        struct ll_readahead_state *ras, unsigned long index,
734                        enum ras_update_flags flags)
735 {
736         struct ll_ra_info *ra = &sbi->ll_ra_info;
737         bool hit = flags & LL_RAS_HIT;
738         int zero = 0, stride_detect = 0, ra_miss = 0;
739         ENTRY;
740
741         spin_lock(&ras->ras_lock);
742
743         ll_ra_stats_inc_sbi(sbi, hit ? RA_STAT_HIT : RA_STAT_MISS);
744
745         /* reset the read-ahead window in two cases.  First when the app seeks
746          * or reads to some other part of the file.  Secondly if we get a
747          * read-ahead miss that we think we've previously issued.  This can
748          * be a symptom of there being so many read-ahead pages that the VM is
749          * reclaiming it before we get to it. */
750         if (!index_in_window(index, ras->ras_last_readpage, 8, 8)) {
751                 zero = 1;
752                 ll_ra_stats_inc_sbi(sbi, RA_STAT_DISTANT_READPAGE);
753         } else if (!hit && ras->ras_window_len &&
754                    index < ras->ras_next_readahead &&
755                    index_in_window(index, ras->ras_window_start, 0,
756                                    ras->ras_window_len)) {
757                 ra_miss = 1;
758                 ll_ra_stats_inc_sbi(sbi, RA_STAT_MISS_IN_WINDOW);
759         }
760
761         /* On the second access to a file smaller than the tunable
762          * ra_max_read_ahead_whole_pages trigger RA on all pages in the
763          * file up to ra_max_pages_per_file.  This is simply a best effort
764          * and only occurs once per open file.  Normal RA behavior is reverted
765          * to for subsequent IO.  The mmap case does not increment
766          * ras_requests and thus can never trigger this behavior. */
767         if (ras->ras_requests >= 2 && !ras->ras_request_index) {
768                 __u64 kms_pages;
769
770                 kms_pages = (i_size_read(inode) + PAGE_CACHE_SIZE - 1) >>
771                             PAGE_CACHE_SHIFT;
772
773                 CDEBUG(D_READA, "kmsp "LPU64" mwp %lu mp %lu\n", kms_pages,
774                        ra->ra_max_read_ahead_whole_pages, ra->ra_max_pages_per_file);
775
776                 if (kms_pages &&
777                     kms_pages <= ra->ra_max_read_ahead_whole_pages) {
778                         ras->ras_window_start = 0;
779                         ras->ras_next_readahead = index + 1;
780                         ras->ras_window_len = min(ra->ra_max_pages_per_file,
781                                 ra->ra_max_read_ahead_whole_pages);
782                         GOTO(out_unlock, 0);
783                 }
784         }
785         if (zero) {
786                 /* check whether it is in stride I/O mode*/
787                 if (!index_in_stride_window(ras, index)) {
788                         if (ras->ras_consecutive_stride_requests == 0 &&
789                             ras->ras_request_index == 0) {
790                                 ras_update_stride_detector(ras, index);
791                                 ras->ras_consecutive_stride_requests++;
792                         } else {
793                                 ras_stride_reset(ras);
794                         }
795                         ras_reset(inode, ras, index);
796                         ras->ras_consecutive_pages++;
797                         GOTO(out_unlock, 0);
798                 } else {
799                         ras->ras_consecutive_pages = 0;
800                         ras->ras_consecutive_requests = 0;
801                         if (++ras->ras_consecutive_stride_requests > 1)
802                                 stride_detect = 1;
803                         RAS_CDEBUG(ras);
804                 }
805         } else {
806                 if (ra_miss) {
807                         if (index_in_stride_window(ras, index) &&
808                             stride_io_mode(ras)) {
809                                 /*If stride-RA hit cache miss, the stride dector
810                                  *will not be reset to avoid the overhead of
811                                  *redetecting read-ahead mode */
812                                 if (index != ras->ras_last_readpage + 1)
813                                         ras->ras_consecutive_pages = 0;
814                                 ras_reset(inode, ras, index);
815                                 RAS_CDEBUG(ras);
816                         } else {
817                                 /* Reset both stride window and normal RA
818                                  * window */
819                                 ras_reset(inode, ras, index);
820                                 ras->ras_consecutive_pages++;
821                                 ras_stride_reset(ras);
822                                 GOTO(out_unlock, 0);
823                         }
824                 } else if (stride_io_mode(ras)) {
825                         /* If this is contiguous read but in stride I/O mode
826                          * currently, check whether stride step still is valid,
827                          * if invalid, it will reset the stride ra window*/
828                         if (!index_in_stride_window(ras, index)) {
829                                 /* Shrink stride read-ahead window to be zero */
830                                 ras_stride_reset(ras);
831                                 ras->ras_window_len = 0;
832                                 ras->ras_next_readahead = index;
833                         }
834                 }
835         }
836         ras->ras_consecutive_pages++;
837         ras->ras_last_readpage = index;
838         ras_set_start(inode, ras, index);
839
840         if (stride_io_mode(ras)) {
841                 /* Since stride readahead is sentivite to the offset
842                  * of read-ahead, so we use original offset here,
843                  * instead of ras_window_start, which is RPC aligned */
844                 ras->ras_next_readahead = max(index, ras->ras_next_readahead);
845         } else {
846                 if (ras->ras_next_readahead < ras->ras_window_start)
847                         ras->ras_next_readahead = ras->ras_window_start;
848                 if (!hit)
849                         ras->ras_next_readahead = index + 1;
850         }
851         RAS_CDEBUG(ras);
852
853         /* Trigger RA in the mmap case where ras_consecutive_requests
854          * is not incremented and thus can't be used to trigger RA */
855         if (ras->ras_consecutive_pages >= 4 && flags & LL_RAS_MMAP) {
856                 ras_increase_window(inode, ras, ra);
857                 /* reset consecutive pages so that the readahead window can
858                  * grow gradually. */
859                 ras->ras_consecutive_pages = 0;
860                 GOTO(out_unlock, 0);
861         }
862
863         /* Initially reset the stride window offset to next_readahead*/
864         if (ras->ras_consecutive_stride_requests == 2 && stride_detect) {
865                 /**
866                  * Once stride IO mode is detected, next_readahead should be
867                  * reset to make sure next_readahead > stride offset
868                  */
869                 ras->ras_next_readahead = max(index, ras->ras_next_readahead);
870                 ras->ras_stride_offset = index;
871                 ras->ras_window_len = RAS_INCREASE_STEP(inode);
872         }
873
874         /* The initial ras_window_len is set to the request size.  To avoid
875          * uselessly reading and discarding pages for random IO the window is
876          * only increased once per consecutive request received. */
877         if ((ras->ras_consecutive_requests > 1 || stride_detect) &&
878             !ras->ras_request_index)
879                 ras_increase_window(inode, ras, ra);
880         EXIT;
881 out_unlock:
882         RAS_CDEBUG(ras);
883         ras->ras_request_index++;
884         spin_unlock(&ras->ras_lock);
885         return;
886 }
887
888 int ll_writepage(struct page *vmpage, struct writeback_control *wbc)
889 {
890         struct inode           *inode = vmpage->mapping->host;
891         struct ll_inode_info   *lli   = ll_i2info(inode);
892         struct lu_env          *env;
893         struct cl_io           *io;
894         struct cl_page         *page;
895         struct cl_object       *clob;
896         struct cl_env_nest      nest;
897         bool redirtied = false;
898         bool unlocked = false;
899         int result;
900         ENTRY;
901
902         LASSERT(PageLocked(vmpage));
903         LASSERT(!PageWriteback(vmpage));
904
905         LASSERT(ll_i2dtexp(inode) != NULL);
906
907         env = cl_env_nested_get(&nest);
908         if (IS_ERR(env))
909                 GOTO(out, result = PTR_ERR(env));
910
911         clob  = ll_i2info(inode)->lli_clob;
912         LASSERT(clob != NULL);
913
914         io = vvp_env_thread_io(env);
915         io->ci_obj = clob;
916         io->ci_ignore_layout = 1;
917         result = cl_io_init(env, io, CIT_MISC, clob);
918         if (result == 0) {
919                 page = cl_page_find(env, clob, vmpage->index,
920                                     vmpage, CPT_CACHEABLE);
921                 if (!IS_ERR(page)) {
922                         lu_ref_add(&page->cp_reference, "writepage",
923                                    current);
924                         cl_page_assume(env, io, page);
925                         result = cl_page_flush(env, io, page);
926                         if (result != 0) {
927                                 /*
928                                  * Re-dirty page on error so it retries write,
929                                  * but not in case when IO has actually
930                                  * occurred and completed with an error.
931                                  */
932                                 if (!PageError(vmpage)) {
933                                         redirty_page_for_writepage(wbc, vmpage);
934                                         result = 0;
935                                         redirtied = true;
936                                 }
937                         }
938                         cl_page_disown(env, io, page);
939                         unlocked = true;
940                         lu_ref_del(&page->cp_reference,
941                                    "writepage", current);
942                         cl_page_put(env, page);
943                 } else {
944                         result = PTR_ERR(page);
945                 }
946         }
947         cl_io_fini(env, io);
948
949         if (redirtied && wbc->sync_mode == WB_SYNC_ALL) {
950                 loff_t offset = cl_offset(clob, vmpage->index);
951
952                 /* Flush page failed because the extent is being written out.
953                  * Wait for the write of extent to be finished to avoid
954                  * breaking kernel which assumes ->writepage should mark
955                  * PageWriteback or clean the page. */
956                 result = cl_sync_file_range(inode, offset,
957                                             offset + PAGE_CACHE_SIZE - 1,
958                                             CL_FSYNC_LOCAL, 1);
959                 if (result > 0) {
960                         /* actually we may have written more than one page.
961                          * decreasing this page because the caller will count
962                          * it. */
963                         wbc->nr_to_write -= result - 1;
964                         result = 0;
965                 }
966         }
967
968         cl_env_nested_put(&nest, env);
969         GOTO(out, result);
970
971 out:
972         if (result < 0) {
973                 if (!lli->lli_async_rc)
974                         lli->lli_async_rc = result;
975                 SetPageError(vmpage);
976                 if (!unlocked)
977                         unlock_page(vmpage);
978         }
979         return result;
980 }
981
982 int ll_writepages(struct address_space *mapping, struct writeback_control *wbc)
983 {
984         struct inode *inode = mapping->host;
985         struct ll_sb_info *sbi = ll_i2sbi(inode);
986         loff_t start;
987         loff_t end;
988         enum cl_fsync_mode mode;
989         int range_whole = 0;
990         int result;
991         int ignore_layout = 0;
992         ENTRY;
993
994         if (wbc->range_cyclic) {
995                 start = mapping->writeback_index << PAGE_CACHE_SHIFT;
996                 end = OBD_OBJECT_EOF;
997         } else {
998                 start = wbc->range_start;
999                 end = wbc->range_end;
1000                 if (end == LLONG_MAX) {
1001                         end = OBD_OBJECT_EOF;
1002                         range_whole = start == 0;
1003                 }
1004         }
1005
1006         mode = CL_FSYNC_NONE;
1007         if (wbc->sync_mode == WB_SYNC_ALL)
1008                 mode = CL_FSYNC_LOCAL;
1009
1010         if (sbi->ll_umounting)
1011                 /* if the mountpoint is being umounted, all pages have to be
1012                  * evicted to avoid hitting LBUG when truncate_inode_pages()
1013                  * is called later on. */
1014                 ignore_layout = 1;
1015
1016         if (ll_i2info(inode)->lli_clob == NULL)
1017                 RETURN(0);
1018
1019         result = cl_sync_file_range(inode, start, end, mode, ignore_layout);
1020         if (result > 0) {
1021                 wbc->nr_to_write -= result;
1022                 result = 0;
1023          }
1024
1025         if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0)) {
1026                 if (end == OBD_OBJECT_EOF)
1027                         mapping->writeback_index = 0;
1028                 else
1029                         mapping->writeback_index = (end >> PAGE_CACHE_SHIFT) +1;
1030         }
1031         RETURN(result);
1032 }
1033
1034 struct ll_cl_context *ll_cl_find(struct file *file)
1035 {
1036         struct ll_file_data *fd = LUSTRE_FPRIVATE(file);
1037         struct ll_cl_context *lcc;
1038         struct ll_cl_context *found = NULL;
1039
1040         read_lock(&fd->fd_lock);
1041         list_for_each_entry(lcc, &fd->fd_lccs, lcc_list) {
1042                 if (lcc->lcc_cookie == current) {
1043                         found = lcc;
1044                         break;
1045                 }
1046         }
1047         read_unlock(&fd->fd_lock);
1048
1049         return found;
1050 }
1051
1052 void ll_cl_add(struct file *file, const struct lu_env *env, struct cl_io *io)
1053 {
1054         struct ll_file_data *fd = LUSTRE_FPRIVATE(file);
1055         struct ll_cl_context *lcc = &ll_env_info(env)->lti_io_ctx;
1056
1057         memset(lcc, 0, sizeof(*lcc));
1058         INIT_LIST_HEAD(&lcc->lcc_list);
1059         lcc->lcc_cookie = current;
1060         lcc->lcc_env = env;
1061         lcc->lcc_io = io;
1062
1063         write_lock(&fd->fd_lock);
1064         list_add(&lcc->lcc_list, &fd->fd_lccs);
1065         write_unlock(&fd->fd_lock);
1066 }
1067
1068 void ll_cl_remove(struct file *file, const struct lu_env *env)
1069 {
1070         struct ll_file_data *fd = LUSTRE_FPRIVATE(file);
1071         struct ll_cl_context *lcc = &ll_env_info(env)->lti_io_ctx;
1072
1073         write_lock(&fd->fd_lock);
1074         list_del_init(&lcc->lcc_list);
1075         write_unlock(&fd->fd_lock);
1076 }
1077
1078 static int ll_io_read_page(const struct lu_env *env, struct cl_io *io,
1079                            struct cl_page *page)
1080 {
1081         struct inode              *inode  = vvp_object_inode(page->cp_obj);
1082         struct ll_sb_info         *sbi    = ll_i2sbi(inode);
1083         struct ll_file_data       *fd     = vvp_env_io(env)->vui_fd;
1084         struct ll_readahead_state *ras    = &fd->fd_ras;
1085         struct cl_2queue          *queue  = &io->ci_queue;
1086         struct vvp_page           *vpg;
1087         int                        rc = 0;
1088         ENTRY;
1089
1090         vpg = cl2vvp_page(cl_object_page_slice(page->cp_obj, page));
1091         if (sbi->ll_ra_info.ra_max_pages_per_file > 0 &&
1092             sbi->ll_ra_info.ra_max_pages > 0) {
1093                 struct vvp_io *vio = vvp_env_io(env);
1094                 enum ras_update_flags flags = 0;
1095
1096                 if (vpg->vpg_defer_uptodate)
1097                         flags |= LL_RAS_HIT;
1098                 if (!vio->vui_ra_valid)
1099                         flags |= LL_RAS_MMAP;
1100                 ras_update(sbi, inode, ras, vvp_index(vpg), flags);
1101         }
1102
1103         if (vpg->vpg_defer_uptodate) {
1104                 vpg->vpg_ra_used = 1;
1105                 cl_page_export(env, page, 1);
1106         }
1107
1108         cl_2queue_init(queue);
1109         /*
1110          * Add page into the queue even when it is marked uptodate above.
1111          * this will unlock it automatically as part of cl_page_list_disown().
1112          */
1113         cl_2queue_add(queue, page);
1114         if (sbi->ll_ra_info.ra_max_pages_per_file > 0 &&
1115             sbi->ll_ra_info.ra_max_pages > 0) {
1116                 int rc2;
1117
1118                 rc2 = ll_readahead(env, io, &queue->c2_qin, ras,
1119                                    vpg->vpg_defer_uptodate);
1120                 CDEBUG(D_READA, DFID "%d pages read ahead at %lu\n",
1121                        PFID(ll_inode2fid(inode)), rc2, vvp_index(vpg));
1122         }
1123
1124         if (queue->c2_qin.pl_nr > 0)
1125                 rc = cl_io_submit_rw(env, io, CRT_READ, queue);
1126
1127         /*
1128          * Unlock unsent pages in case of error.
1129          */
1130         cl_page_list_disown(env, io, &queue->c2_qin);
1131         cl_2queue_fini(env, queue);
1132
1133         RETURN(rc);
1134 }
1135
1136 int ll_readpage(struct file *file, struct page *vmpage)
1137 {
1138         struct inode *inode = file->f_path.dentry->d_inode;
1139         struct cl_object *clob = ll_i2info(inode)->lli_clob;
1140         struct ll_cl_context *lcc;
1141         const struct lu_env  *env;
1142         struct cl_io   *io;
1143         struct cl_page *page;
1144         int result;
1145         ENTRY;
1146
1147         lcc = ll_cl_find(file);
1148         if (lcc == NULL) {
1149                 unlock_page(vmpage);
1150                 RETURN(-EIO);
1151         }
1152
1153         env = lcc->lcc_env;
1154         io  = lcc->lcc_io;
1155         LASSERT(io != NULL);
1156         LASSERT(io->ci_state == CIS_IO_GOING);
1157         page = cl_page_find(env, clob, vmpage->index, vmpage, CPT_CACHEABLE);
1158         if (!IS_ERR(page)) {
1159                 LASSERT(page->cp_type == CPT_CACHEABLE);
1160                 if (likely(!PageUptodate(vmpage))) {
1161                         cl_page_assume(env, io, page);
1162                         result = ll_io_read_page(env, io, page);
1163                 } else {
1164                         /* Page from a non-object file. */
1165                         unlock_page(vmpage);
1166                         result = 0;
1167                 }
1168                 cl_page_put(env, page);
1169         } else {
1170                 unlock_page(vmpage);
1171                 result = PTR_ERR(page);
1172         }
1173         RETURN(result);
1174 }
1175
1176 int ll_page_sync_io(const struct lu_env *env, struct cl_io *io,
1177                     struct cl_page *page, enum cl_req_type crt)
1178 {
1179         struct cl_2queue  *queue;
1180         int result;
1181
1182         LASSERT(io->ci_type == CIT_READ || io->ci_type == CIT_WRITE);
1183
1184         queue = &io->ci_queue;
1185         cl_2queue_init_page(queue, page);
1186
1187         result = cl_io_submit_sync(env, io, crt, queue, 0);
1188         LASSERT(cl_page_is_owned(page, io));
1189
1190         if (crt == CRT_READ)
1191                 /*
1192                  * in CRT_WRITE case page is left locked even in case of
1193                  * error.
1194                  */
1195                 cl_page_list_disown(env, io, &queue->c2_qin);
1196         cl_2queue_fini(env, queue);
1197
1198         return result;
1199 }