Whamcloud - gitweb
LU-6142 llite: Fix style issues for rw.c
[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.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2011, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  *
31  * lustre/llite/rw.c
32  *
33  * Lustre Lite I/O page cache routines shared by different kernel revs
34  */
35
36 #include <linux/kernel.h>
37 #include <linux/mm.h>
38 #include <linux/string.h>
39 #include <linux/stat.h>
40 #include <linux/errno.h>
41 #include <linux/unistd.h>
42 #include <linux/writeback.h>
43 #include <asm/uaccess.h>
44
45 #include <linux/fs.h>
46 #include <linux/file.h>
47 #include <linux/stat.h>
48 #include <asm/uaccess.h>
49 #include <linux/mm.h>
50 #include <linux/pagemap.h>
51 /* current_is_kswapd() */
52 #include <linux/swap.h>
53 #include <linux/task_io_accounting_ops.h>
54
55 #define DEBUG_SUBSYSTEM S_LLITE
56
57 #include <obd_cksum.h>
58 #include "llite_internal.h"
59 #include <lustre_compat.h>
60
61 static void ll_ra_stats_inc_sbi(struct ll_sb_info *sbi, enum ra_stat which);
62
63 /*
64  * Get readahead pages from the filesystem readahead pool of the client for a
65  * thread.
66  *
67  * /param sbi superblock for filesystem readahead state ll_ra_info
68  * /param ria per-thread readahead state
69  * /param pages number of pages requested for readahead for the thread.
70  *
71  * WARNING: This algorithm is used to reduce contention on sbi->ll_lock.
72  * It should work well if the ra_max_pages is much greater than the single
73  * file's read-ahead window, and not too many threads contending for
74  * these readahead pages.
75  *
76  * TODO: There may be a 'global sync problem' if many threads are trying
77  * to get an ra budget that is larger than the remaining readahead pages
78  * and reach here at exactly the same time. They will compute /a ret to
79  * consume the remaining pages, but will fail at atomic_add_return() and
80  * get a zero ra window, although there is still ra space remaining. - Jay
81  */
82
83 static unsigned long ll_ra_count_get(struct ll_sb_info *sbi,
84                                      struct ra_io_arg *ria,
85                                      unsigned long pages,
86                                      unsigned long pages_min)
87 {
88         struct ll_ra_info *ra = &sbi->ll_ra_info;
89         long ret;
90
91         ENTRY;
92
93         WARN_ON_ONCE(pages_min > pages);
94         /*
95          * Don't try readahead aggresively if we are limited
96          * LRU pages, otherwise, it could cause deadlock.
97          */
98         pages = min(sbi->ll_cache->ccc_lru_max >> 2, pages);
99         /*
100          * if this happen, we reserve more pages than needed,
101          * this will make us leak @ra_cur_pages, because
102          * ll_ra_count_put() acutally freed @pages.
103          */
104         if (unlikely(pages_min > pages))
105                 pages_min = pages;
106
107         /*
108          * If read-ahead pages left are less than 1M, do not do read-ahead,
109          * otherwise it will form small read RPC(< 1M), which hurt server
110          * performance a lot.
111          */
112         ret = min(ra->ra_max_pages - atomic_read(&ra->ra_cur_pages),
113                   pages);
114         if (ret < 0 || ret < min_t(long, PTLRPC_MAX_BRW_PAGES, pages))
115                 GOTO(out, ret = 0);
116
117         if (atomic_add_return(ret, &ra->ra_cur_pages) > ra->ra_max_pages) {
118                 atomic_sub(ret, &ra->ra_cur_pages);
119                 ret = 0;
120         }
121
122 out:
123         if (ret < pages_min) {
124                 /* override ra limit for maximum performance */
125                 atomic_add(pages_min - ret, &ra->ra_cur_pages);
126                 ret = pages_min;
127         }
128         RETURN(ret);
129 }
130
131 void ll_ra_count_put(struct ll_sb_info *sbi, unsigned long pages)
132 {
133         struct ll_ra_info *ra = &sbi->ll_ra_info;
134
135         atomic_sub(pages, &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 < _NR_RA_STAT, "which: %u\n", which);
141         lprocfs_counter_incr(sbi->ll_ra_stats, which);
142 }
143
144 static inline bool ll_readahead_enabled(struct ll_sb_info *sbi)
145 {
146         return sbi->ll_ra_info.ra_max_pages_per_file > 0 &&
147                 sbi->ll_ra_info.ra_max_pages > 0;
148 }
149
150 void ll_ra_stats_inc(struct inode *inode, enum ra_stat which)
151 {
152         struct ll_sb_info *sbi = ll_i2sbi(inode);
153
154         ll_ra_stats_inc_sbi(sbi, which);
155 }
156
157 static void ll_ra_stats_add(struct inode *inode, enum ra_stat which, long count)
158 {
159         struct ll_sb_info *sbi = ll_i2sbi(inode);
160
161         LASSERTF(which < _NR_RA_STAT, "which: %u\n", which);
162         lprocfs_counter_add(sbi->ll_ra_stats, which, count);
163 }
164
165 #define RAS_CDEBUG(ras) \
166         CDEBUG(D_READA,                                                      \
167                "lre %llu cr %lu cb %llu wsi %lu wp %lu nra %lu rpc %lu "     \
168                "r %lu csr %lu so %llu sb %llu sl %llu lr %lu\n",             \
169                ras->ras_last_read_end_bytes, ras->ras_consecutive_requests,  \
170                ras->ras_consecutive_bytes, ras->ras_window_start_idx,        \
171                ras->ras_window_pages, ras->ras_next_readahead_idx,           \
172                ras->ras_rpc_pages, ras->ras_requests,                        \
173                ras->ras_consecutive_stride_requests, ras->ras_stride_offset, \
174                ras->ras_stride_bytes, ras->ras_stride_length,                \
175                ras->ras_async_last_readpage_idx)
176
177 static bool pos_in_window(loff_t pos, loff_t point,
178                           unsigned long before, unsigned long after)
179 {
180         loff_t start = point - before;
181         loff_t end = point + after;
182
183         if (start > point)
184                 start = 0;
185         if (end < point)
186                 end = ~0;
187
188         return start <= pos && pos <= end;
189 }
190
191 enum ll_ra_page_hint {
192         MAYNEED = 0, /* this page possibly accessed soon */
193         WILLNEED /* this page is gurateed to be needed */
194 };
195
196 /*
197  * Initiates read-ahead of a page with given index.
198  *
199  * \retval +ve: page was already uptodate so it will be skipped
200  *              from being added;
201  * \retval -ve: page wasn't added to \a queue for error;
202  * \retval   0: page was added into \a queue for read ahead.
203  */
204 static int ll_read_ahead_page(const struct lu_env *env, struct cl_io *io,
205                               struct cl_page_list *queue, pgoff_t index,
206                               enum ll_ra_page_hint hint)
207 {
208         struct cl_object *clob  = io->ci_obj;
209         struct inode     *inode = vvp_object_inode(clob);
210         struct page      *vmpage = NULL;
211         struct cl_page   *cp;
212         enum ra_stat      which = _NR_RA_STAT; /* keep gcc happy */
213         int               rc    = 0;
214         const char       *msg   = NULL;
215
216         ENTRY;
217
218         switch (hint) {
219         case MAYNEED:
220                 /*
221                  * We need __GFP_NORETRY here for read-ahead page, otherwise
222                  * the process will fail with OOM killed due to memcg limit.
223                  * See @readahead_gfp_mask for an example.
224                  */
225                 vmpage = pagecache_get_page(inode->i_mapping, index,
226                                             FGP_LOCK | FGP_CREAT |
227                                             FGP_NOFS | FGP_NOWAIT,
228                                             mapping_gfp_mask(inode->i_mapping) |
229                                             __GFP_NORETRY | __GFP_NOWARN);
230                 if (vmpage == NULL) {
231                         which = RA_STAT_FAILED_GRAB_PAGE;
232                         msg   = "g_c_p_n failed";
233                         GOTO(out, rc = -EBUSY);
234                 }
235                 break;
236         case WILLNEED:
237                 vmpage = find_or_create_page(inode->i_mapping, index,
238                                              GFP_NOFS);
239                 if (vmpage == NULL)
240                         GOTO(out, rc = -ENOMEM);
241                 break;
242         default:
243                 /* should not come here */
244                 GOTO(out, rc = -EINVAL);
245         }
246
247         /* Check if vmpage was truncated or reclaimed */
248         if (vmpage->mapping != inode->i_mapping) {
249                 which = RA_STAT_WRONG_GRAB_PAGE;
250                 msg   = "g_c_p_n returned invalid page";
251                 GOTO(out, rc = -EBUSY);
252         }
253
254         cp = cl_page_find(env, clob, vmpage->index, vmpage, CPT_CACHEABLE);
255         if (IS_ERR(cp)) {
256                 which = RA_STAT_FAILED_GRAB_PAGE;
257                 msg   = "cl_page_find failed";
258                 GOTO(out, rc = PTR_ERR(cp));
259         }
260
261         lu_ref_add(&cp->cp_reference, "ra", current);
262         cl_page_assume(env, io, cp);
263
264         if (!cp->cp_defer_uptodate && !PageUptodate(vmpage)) {
265                 if (hint == MAYNEED) {
266                         cp->cp_defer_uptodate = 1;
267                         cp->cp_ra_used = 0;
268                 }
269
270                 cl_page_list_add(queue, cp, true);
271         } else {
272                 /* skip completed pages */
273                 cl_page_unassume(env, io, cp);
274                 /* This page is already uptodate, returning a positive number
275                  * to tell the callers about this
276                  */
277                 rc = 1;
278         }
279
280         lu_ref_del(&cp->cp_reference, "ra", current);
281         cl_page_put(env, cp);
282
283 out:
284         if (vmpage != NULL) {
285                 if (rc != 0)
286                         unlock_page(vmpage);
287                 put_page(vmpage);
288         }
289         if (msg != NULL && hint == MAYNEED) {
290                 ll_ra_stats_inc(inode, which);
291                 CDEBUG(D_READA, "%s\n", msg);
292
293         }
294
295         RETURN(rc);
296 }
297
298 #define RIA_DEBUG(ria)                                                  \
299         CDEBUG(D_READA, "rs %lu re %lu ro %llu rl %llu rb %llu\n",      \
300                ria->ria_start_idx, ria->ria_end_idx, ria->ria_stoff,    \
301                ria->ria_length, ria->ria_bytes)
302
303 static inline int stride_io_mode(struct ll_readahead_state *ras)
304 {
305         return ras->ras_consecutive_stride_requests > 1;
306 }
307
308 /* The function calculates how many bytes will be read in
309  * [off, off + length], in such stride IO area,
310  * stride_offset = st_off, stride_lengh = st_len,
311  * stride_bytes = st_bytes
312  *
313  *   |------------------|*****|------------------|*****|------------|*****|....
314  * st_off
315  *   |--- st_bytes     ---|
316  *   |-----     st_len   -----|
317  *
318  *              How many bytes it should read in such pattern
319  *              |-------------------------------------------------------------|
320  *              off
321  *              |<------                  length                      ------->|
322  *
323  *          =   |<----->|  +  |-------------------------------------| +   |---|
324  *             start_left                 st_bytes * i                 end_left
325  */
326 static loff_t stride_byte_count(loff_t st_off, loff_t st_len, loff_t st_bytes,
327                                 loff_t off, loff_t length)
328 {
329         u64 start = off > st_off ? off - st_off : 0;
330         u64 end = off + length > st_off ? off + length - st_off : 0;
331         u64 start_left;
332         u64 end_left;
333         u64 bytes_count;
334
335         if (st_len == 0 || length == 0 || end == 0)
336                 return length;
337
338         start = div64_u64_rem(start, st_len, &start_left);
339         if (start_left < st_bytes)
340                 start_left = st_bytes - start_left;
341         else
342                 start_left = 0;
343
344         end = div64_u64_rem(end, st_len, &end_left);
345         if (end_left > st_bytes)
346                 end_left = st_bytes;
347
348         CDEBUG(D_READA, "start %llu, end %llu start_left %llu end_left %llu\n",
349                start, end, start_left, end_left);
350
351         if (start == end)
352                 bytes_count = end_left - (st_bytes - start_left);
353         else
354                 bytes_count = start_left +
355                         st_bytes * (end - start - 1) + end_left;
356
357         CDEBUG(D_READA,
358                "st_off %llu, st_len %llu st_bytes %llu off %llu length %llu bytescount %llu\n",
359                st_off, st_len, st_bytes, off, length, bytes_count);
360
361         return bytes_count;
362 }
363
364 static unsigned long ria_page_count(struct ra_io_arg *ria)
365 {
366         loff_t length_bytes = ria->ria_end_idx >= ria->ria_start_idx ?
367                 (loff_t)(ria->ria_end_idx -
368                          ria->ria_start_idx + 1) << PAGE_SHIFT : 0;
369         loff_t bytes_count;
370
371         if (ria->ria_length > ria->ria_bytes && ria->ria_bytes &&
372             (ria->ria_length & ~PAGE_MASK || ria->ria_bytes & ~PAGE_MASK ||
373              ria->ria_stoff & ~PAGE_MASK)) {
374                 /* Over-estimate un-aligned page stride read */
375                 unsigned long pg_count = ((ria->ria_bytes +
376                                            PAGE_SIZE - 1) >> PAGE_SHIFT) + 1;
377                 pg_count *= length_bytes / ria->ria_length + 1;
378
379                 return pg_count;
380         }
381         bytes_count = stride_byte_count(ria->ria_stoff, ria->ria_length,
382                                         ria->ria_bytes,
383                                         (loff_t)ria->ria_start_idx<<PAGE_SHIFT,
384                                         length_bytes);
385         return (bytes_count + PAGE_SIZE - 1) >> PAGE_SHIFT;
386 }
387
388 static pgoff_t ras_align(struct ll_readahead_state *ras, pgoff_t index)
389 {
390         unsigned int opt_size = min(ras->ras_window_pages, ras->ras_rpc_pages);
391
392         if (opt_size == 0)
393                 opt_size = 1;
394         return index - (index % opt_size);
395 }
396
397 /* Check whether the index is in the defined ra-window */
398 static bool ras_inside_ra_window(pgoff_t idx, struct ra_io_arg *ria)
399 {
400         loff_t pos = (loff_t)idx << PAGE_SHIFT;
401
402         /* If ria_length == ria_bytes, it means non-stride I/O mode,
403          * idx should always inside read-ahead window in this case
404          * For stride I/O mode, just check whether the idx is inside
405          * the ria_bytes.
406          */
407         if (ria->ria_length == 0 || ria->ria_length == ria->ria_bytes)
408                 return true;
409
410         if (pos >= ria->ria_stoff) {
411                 u64 offset;
412
413                 div64_u64_rem(pos - ria->ria_stoff, ria->ria_length, &offset);
414
415                 if (offset < ria->ria_bytes ||
416                     (ria->ria_length - offset) < PAGE_SIZE)
417                         return true;
418         } else if (pos + PAGE_SIZE > ria->ria_stoff) {
419                 return true;
420         }
421
422         return false;
423 }
424
425 static unsigned long
426 ll_read_ahead_pages(const struct lu_env *env, struct cl_io *io,
427                     struct cl_page_list *queue, struct ll_readahead_state *ras,
428                     struct ra_io_arg *ria, pgoff_t *ra_end, pgoff_t skip_index)
429 {
430         struct cl_read_ahead ra = { 0 };
431         /* busy page count is per stride */
432         int rc = 0, count = 0, busy_page_count = 0;
433         pgoff_t page_idx;
434
435         LASSERT(ria != NULL);
436         RIA_DEBUG(ria);
437
438         for (page_idx = ria->ria_start_idx;
439              page_idx <= ria->ria_end_idx && ria->ria_reserved > 0;
440              page_idx++) {
441                 if (skip_index && page_idx == skip_index)
442                         continue;
443                 if (ras_inside_ra_window(page_idx, ria)) {
444                         if (ra.cra_end_idx == 0 || ra.cra_end_idx < page_idx) {
445                                 pgoff_t end_idx;
446
447                                 /*
448                                  * Do not shrink ria_end_idx at any case until
449                                  * the minimum end of current read is covered.
450                                  *
451                                  * Do not extend read lock accross stripe if
452                                  * lock contention detected.
453                                  */
454                                 if (ra.cra_contention &&
455                                     page_idx > ria->ria_end_idx_min) {
456                                         ria->ria_end_idx = *ra_end;
457                                         break;
458                                 }
459
460                                 cl_read_ahead_release(env, &ra);
461
462                                 rc = cl_io_read_ahead(env, io, page_idx, &ra);
463                                 if (rc < 0)
464                                         break;
465
466                                  /*
467                                   * Only shrink ria_end_idx if the matched
468                                   * LDLM lock doesn't cover more.
469                                   */
470                                 if (page_idx > ra.cra_end_idx) {
471                                         ria->ria_end_idx = ra.cra_end_idx;
472                                         break;
473                                 }
474
475                                 CDEBUG(D_READA, "idx: %lu, ra: %lu, rpc: %lu\n",
476                                        page_idx, ra.cra_end_idx,
477                                        ra.cra_rpc_pages);
478                                 LASSERTF(ra.cra_end_idx >= page_idx,
479                                          "object: %px, indcies %lu / %lu\n",
480                                          io->ci_obj, ra.cra_end_idx, page_idx);
481                                 /* update read ahead RPC size.
482                                  * NB: it's racy but doesn't matter
483                                  */
484                                 if (ras->ras_rpc_pages != ra.cra_rpc_pages &&
485                                     ra.cra_rpc_pages > 0)
486                                         ras->ras_rpc_pages = ra.cra_rpc_pages;
487                                 if (!skip_index) {
488                                         /* trim (align with optimal RPC size) */
489                                         end_idx = ras_align(ras,
490                                                         ria->ria_end_idx + 1);
491                                         if (end_idx > 0 && !ria->ria_eof)
492                                                 ria->ria_end_idx = end_idx - 1;
493                                 }
494                                 if (ria->ria_end_idx < ria->ria_end_idx_min)
495                                         ria->ria_end_idx = ria->ria_end_idx_min;
496                         }
497                         if (page_idx > ria->ria_end_idx)
498                                 break;
499
500                         /* If the page is inside the read-ahead window */
501                         rc = ll_read_ahead_page(env, io, queue, page_idx,
502                                                 MAYNEED);
503                         if (rc < 0 && rc != -EBUSY)
504                                 break;
505                         if (rc == -EBUSY) {
506                                 busy_page_count++;
507                                 CDEBUG(D_READA,
508                                        "skip busy page: %lu\n", page_idx);
509                                 /* For page unaligned readahead the first
510                                  * last pages of each region can be read by
511                                  * another reader on the same node, and so
512                                  * may be busy. So only stop for > 2 busy
513                                  * pages.
514                                  */
515                                 if (busy_page_count > 2)
516                                         break;
517                         }
518
519                         *ra_end = page_idx;
520                         /* Only subtract from reserve & count the page if we
521                          * really did readahead on that page.
522                          */
523                         if (rc == 0) {
524                                 ria->ria_reserved--;
525                                 count++;
526                         }
527                 } else if (stride_io_mode(ras)) {
528                         /* If it is not in the read-ahead window, and it is
529                          * read-ahead mode, then check whether it should skip
530                          * the stride gap.
531                          */
532                         loff_t pos = (loff_t)page_idx << PAGE_SHIFT;
533                         u64 offset;
534
535                         div64_u64_rem(pos - ria->ria_stoff, ria->ria_length,
536                                       &offset);
537                         if (offset >= ria->ria_bytes) {
538                                 pos += (ria->ria_length - offset);
539                                 if ((pos >> PAGE_SHIFT) >= page_idx + 1)
540                                         page_idx = (pos >> PAGE_SHIFT) - 1;
541                                 busy_page_count = 0;
542                                 CDEBUG(D_READA,
543                                        "Stride: jump %llu pages to %lu\n",
544                                        ria->ria_length - offset, page_idx);
545                                 continue;
546                         }
547                 }
548         }
549
550         cl_read_ahead_release(env, &ra);
551
552         if (count)
553                 ll_ra_stats_add(vvp_object_inode(io->ci_obj),
554                                 RA_STAT_READAHEAD_PAGES, count);
555
556         return count;
557 }
558
559 static void ll_readahead_work_free(struct ll_readahead_work *work)
560 {
561         fput(work->lrw_file);
562         OBD_FREE_PTR(work);
563 }
564
565 static void ll_readahead_handle_work(struct work_struct *wq);
566 static void ll_readahead_work_add(struct inode *inode,
567                                   struct ll_readahead_work *work)
568 {
569         INIT_WORK(&work->lrw_readahead_work, ll_readahead_handle_work);
570         queue_work(ll_i2sbi(inode)->ll_ra_info.ll_readahead_wq,
571                    &work->lrw_readahead_work);
572 }
573
574 static int ll_readahead_file_kms(const struct lu_env *env,
575                                 struct cl_io *io, __u64 *kms)
576 {
577         struct cl_object *clob;
578         struct inode *inode;
579         struct cl_attr *attr = vvp_env_thread_attr(env);
580         int ret;
581
582         clob = io->ci_obj;
583         inode = vvp_object_inode(clob);
584
585         cl_object_attr_lock(clob);
586         ret = cl_object_attr_get(env, clob, attr);
587         cl_object_attr_unlock(clob);
588
589         if (ret != 0)
590                 RETURN(ret);
591
592         *kms = attr->cat_kms;
593         return 0;
594 }
595
596 static void ll_readahead_handle_work(struct work_struct *wq)
597 {
598         struct ll_readahead_work *work;
599         struct lu_env *env;
600         __u16 refcheck;
601         struct ra_io_arg *ria;
602         struct inode *inode;
603         struct ll_file_data *fd;
604         struct ll_readahead_state *ras;
605         struct cl_io *io;
606         struct cl_2queue *queue;
607         pgoff_t ra_end_idx = 0;
608         unsigned long pages, pages_min = 0;
609         struct file *file;
610         __u64 kms;
611         int rc;
612         pgoff_t eof_index;
613         struct ll_sb_info *sbi;
614
615         work = container_of(wq, struct ll_readahead_work,
616                             lrw_readahead_work);
617         fd = work->lrw_file->private_data;
618         ras = &fd->fd_ras;
619         file = work->lrw_file;
620         inode = file_inode(file);
621         sbi = ll_i2sbi(inode);
622
623         CDEBUG(D_READA|D_IOTRACE,
624                "%s:"DFID": async ra from %lu to %lu triggered by user pid %d\n",
625                file_dentry(file)->d_name.name, PFID(ll_inode2fid(inode)),
626                work->lrw_start_idx, work->lrw_end_idx, work->lrw_user_pid);
627
628         env = cl_env_alloc(&refcheck, LCT_NOREF);
629         if (IS_ERR(env))
630                 GOTO(out_free_work, rc = PTR_ERR(env));
631
632         io = vvp_env_thread_io(env);
633         ll_io_init(io, file, CIT_READ, NULL);
634
635         rc = ll_readahead_file_kms(env, io, &kms);
636         if (rc != 0)
637                 GOTO(out_put_env, rc);
638
639         if (kms == 0) {
640                 ll_ra_stats_inc(inode, RA_STAT_ZERO_LEN);
641                 GOTO(out_put_env, rc = 0);
642         }
643
644         ria = &ll_env_info(env)->lti_ria;
645         memset(ria, 0, sizeof(*ria));
646
647         ria->ria_start_idx = work->lrw_start_idx;
648         /* Truncate RA window to end of file */
649         eof_index = (pgoff_t)(kms - 1) >> PAGE_SHIFT;
650         if (eof_index <= work->lrw_end_idx) {
651                 work->lrw_end_idx = eof_index;
652                 ria->ria_eof = true;
653         }
654         if (work->lrw_end_idx <= work->lrw_start_idx)
655                 GOTO(out_put_env, rc = 0);
656
657         ria->ria_end_idx = work->lrw_end_idx;
658         pages = ria->ria_end_idx - ria->ria_start_idx + 1;
659         ria->ria_reserved = ll_ra_count_get(sbi, ria,
660                                             ria_page_count(ria), pages_min);
661
662         CDEBUG(D_READA,
663                "async reserved pages: %lu/%lu/%lu, ra_cur %d, ra_max %lu\n",
664                ria->ria_reserved, pages, pages_min,
665                atomic_read(&ll_i2sbi(inode)->ll_ra_info.ra_cur_pages),
666                ll_i2sbi(inode)->ll_ra_info.ra_max_pages);
667
668         if (ria->ria_reserved < pages) {
669                 ll_ra_stats_inc(inode, RA_STAT_MAX_IN_FLIGHT);
670                 if (PAGES_TO_MiB(ria->ria_reserved) < 1) {
671                         ll_ra_count_put(ll_i2sbi(inode), ria->ria_reserved);
672                         GOTO(out_put_env, rc = 0);
673                 }
674         }
675
676         rc = cl_io_rw_init(env, io, CIT_READ, ria->ria_start_idx, pages);
677         if (rc)
678                 GOTO(out_put_env, rc);
679
680         /* overwrite jobid inited in vvp_io_init() */
681         if (strncmp(ll_i2info(inode)->lli_jobid, work->lrw_jobid,
682                     sizeof(work->lrw_jobid)))
683                 memcpy(ll_i2info(inode)->lli_jobid, work->lrw_jobid,
684                        sizeof(work->lrw_jobid));
685
686         vvp_env_io(env)->vui_fd = fd;
687         io->ci_state = CIS_LOCKED;
688         io->ci_async_readahead = true;
689         rc = cl_io_start(env, io);
690         if (rc)
691                 GOTO(out_io_fini, rc);
692
693         queue = &io->ci_queue;
694         cl_2queue_init(queue);
695
696         rc = ll_read_ahead_pages(env, io, &queue->c2_qin, ras, ria,
697                                  &ra_end_idx, 0);
698         if (ria->ria_reserved != 0)
699                 ll_ra_count_put(ll_i2sbi(inode), ria->ria_reserved);
700         if (queue->c2_qin.pl_nr > 0) {
701                 int count = queue->c2_qin.pl_nr;
702
703                 rc = cl_io_submit_rw(env, io, CRT_READ, queue);
704                 if (rc == 0)
705                         task_io_account_read(PAGE_SIZE * count);
706         }
707         if (ria->ria_end_idx == ra_end_idx && ra_end_idx == (kms >> PAGE_SHIFT))
708                 ll_ra_stats_inc(inode, RA_STAT_EOF);
709
710         if (ra_end_idx != ria->ria_end_idx)
711                 ll_ra_stats_inc(inode, RA_STAT_FAILED_REACH_END);
712
713         /* TODO: discard all pages until page reinit route is implemented */
714         cl_page_list_discard(env, io, &queue->c2_qin);
715
716         /* Unlock unsent read pages in case of error. */
717         cl_page_list_disown(env, &queue->c2_qin);
718
719         cl_2queue_fini(env, queue);
720 out_io_fini:
721         cl_io_end(env, io);
722         cl_io_fini(env, io);
723 out_put_env:
724         cl_env_put(env, &refcheck);
725 out_free_work:
726         if (ra_end_idx > 0)
727                 ll_ra_stats_inc_sbi(ll_i2sbi(inode), RA_STAT_ASYNC);
728         atomic_dec(&sbi->ll_ra_info.ra_async_inflight);
729         ll_readahead_work_free(work);
730 }
731
732 static int ll_readahead(const struct lu_env *env, struct cl_io *io,
733                         struct cl_page_list *queue,
734                         struct ll_readahead_state *ras, bool hit,
735                         struct file *file, pgoff_t skip_index,
736                         pgoff_t *start_idx)
737 {
738         struct vvp_io *vio = vvp_env_io(env);
739         struct ll_thread_info *lti = ll_env_info(env);
740         unsigned long pages, pages_min = 0;
741         pgoff_t ra_end_idx = 0, end_idx = 0;
742         struct inode *inode;
743         struct ra_io_arg *ria = &lti->lti_ria;
744         struct cl_object *clob;
745         int ret = 0;
746         __u64 kms;
747         struct ll_sb_info *sbi;
748         struct ll_ra_info *ra;
749
750         ENTRY;
751
752         clob = io->ci_obj;
753         inode = vvp_object_inode(clob);
754         sbi = ll_i2sbi(inode);
755         ra = &sbi->ll_ra_info;
756
757         /*
758          * In case we have a limited max_cached_mb, readahead
759          * should be stopped if it have run out of all LRU slots.
760          */
761         if (atomic_read(&ra->ra_cur_pages) >= sbi->ll_cache->ccc_lru_max) {
762                 ll_ra_stats_inc(inode, RA_STAT_MAX_IN_FLIGHT);
763                 RETURN(0);
764         }
765
766         memset(ria, 0, sizeof(*ria));
767         ret = ll_readahead_file_kms(env, io, &kms);
768         if (ret != 0)
769                 RETURN(ret);
770
771         if (kms == 0) {
772                 ll_ra_stats_inc(inode, RA_STAT_ZERO_LEN);
773                 RETURN(0);
774         }
775
776         spin_lock(&ras->ras_lock);
777
778         /*
779          * Note: other thread might rollback the ras_next_readahead_idx,
780          * if it can not get the full size of prepared pages, see the
781          * end of this function. For stride read ahead, it needs to
782          * make sure the offset is no less than ras_stride_offset,
783          * so that stride read ahead can work correctly.
784          */
785         if (stride_io_mode(ras))
786                 *start_idx = max_t(pgoff_t, ras->ras_next_readahead_idx,
787                                   ras->ras_stride_offset >> PAGE_SHIFT);
788         else
789                 *start_idx = ras->ras_next_readahead_idx;
790
791         if (ras->ras_window_pages > 0)
792                 end_idx = ras->ras_window_start_idx + ras->ras_window_pages - 1;
793
794         if (skip_index)
795                 end_idx = *start_idx + ras->ras_window_pages - 1;
796
797         /* Enlarge the RA window to encompass the full read */
798         if (vio->vui_ra_valid &&
799             end_idx < vio->vui_ra_start_idx + vio->vui_ra_pages - 1)
800                 end_idx = vio->vui_ra_start_idx + vio->vui_ra_pages - 1;
801
802         if (end_idx != 0) {
803                 pgoff_t eof_index;
804
805                 /* Truncate RA window to end of file */
806                 eof_index = (pgoff_t)((kms - 1) >> PAGE_SHIFT);
807                 if (eof_index <= end_idx) {
808                         end_idx = eof_index;
809                         ria->ria_eof = true;
810                 }
811         }
812         ria->ria_start_idx = *start_idx;
813         ria->ria_end_idx = end_idx;
814         /* If stride I/O mode is detected, get stride window*/
815         if (stride_io_mode(ras)) {
816                 ria->ria_stoff = ras->ras_stride_offset;
817                 ria->ria_length = ras->ras_stride_length;
818                 ria->ria_bytes = ras->ras_stride_bytes;
819         }
820         spin_unlock(&ras->ras_lock);
821
822         pages = ria_page_count(ria);
823
824         RAS_CDEBUG(ras);
825         CDEBUG(D_READA,
826                DFID": ria: %lu/%lu, bead: %lu/%lu, pages %lu, hit: %d\n",
827                PFID(lu_object_fid(&clob->co_lu)),
828                ria->ria_start_idx, ria->ria_end_idx,
829                vio->vui_ra_valid ? vio->vui_ra_start_idx : 0,
830                vio->vui_ra_valid ? vio->vui_ra_pages : 0,
831                pages, hit);
832
833         if (end_idx == 0) {
834                 ll_ra_stats_inc(inode, RA_STAT_ZERO_WINDOW);
835                 RETURN(0);
836         }
837         if (pages == 0) {
838                 ll_ra_stats_inc(inode, RA_STAT_ZERO_WINDOW);
839                 RETURN(0);
840         }
841
842         /* at least to extend the readahead window to cover current read */
843         if (!hit && vio->vui_ra_valid &&
844             vio->vui_ra_start_idx + vio->vui_ra_pages > ria->ria_start_idx) {
845                 ria->ria_end_idx_min =
846                         vio->vui_ra_start_idx + vio->vui_ra_pages - 1;
847                 pages_min = vio->vui_ra_start_idx + vio->vui_ra_pages -
848                                 ria->ria_start_idx;
849                  /*
850                   * For performance reason, exceeding @ra_max_pages
851                   * are allowed, but this should be limited with RPC
852                   * size in case a large block size read issued. Trim
853                   * to RPC boundary.
854                   */
855                 pages_min = min(pages_min, ras->ras_rpc_pages -
856                                 (ria->ria_start_idx % ras->ras_rpc_pages));
857         }
858
859         /* don't over reserved for mmap range read */
860         if (skip_index)
861                 pages_min = 0;
862         if (pages_min > pages)
863                 pages = pages_min;
864         ria->ria_reserved = ll_ra_count_get(ll_i2sbi(inode), ria, pages,
865                                             pages_min);
866         if (ria->ria_reserved < pages)
867                 ll_ra_stats_inc(inode, RA_STAT_MAX_IN_FLIGHT);
868
869         CDEBUG(D_READA, "reserved pages: %lu/%lu/%lu, ra_cur %d, ra_max %lu\n",
870                ria->ria_reserved, pages, pages_min,
871                atomic_read(&ll_i2sbi(inode)->ll_ra_info.ra_cur_pages),
872                ll_i2sbi(inode)->ll_ra_info.ra_max_pages);
873
874         ret = ll_read_ahead_pages(env, io, queue, ras, ria, &ra_end_idx,
875                                   skip_index);
876         if (ria->ria_reserved != 0)
877                 ll_ra_count_put(ll_i2sbi(inode), ria->ria_reserved);
878
879         if (ra_end_idx == end_idx && ra_end_idx == (kms >> PAGE_SHIFT))
880                 ll_ra_stats_inc(inode, RA_STAT_EOF);
881
882         CDEBUG(D_READA,
883                "ra_end_idx = %lu end_idx = %lu stride end = %lu pages = %d\n",
884                ra_end_idx, end_idx, ria->ria_end_idx, ret);
885
886         if (ra_end_idx != end_idx)
887                 ll_ra_stats_inc(inode, RA_STAT_FAILED_REACH_END);
888         if (ra_end_idx > 0) {
889                 /* update the ras so that the next read-ahead tries from
890                  * where we left off.
891                  */
892                 spin_lock(&ras->ras_lock);
893                 ras->ras_next_readahead_idx = ra_end_idx + 1;
894                 spin_unlock(&ras->ras_lock);
895                 RAS_CDEBUG(ras);
896         }
897
898         RETURN(ret);
899 }
900
901 static int ll_readpages(const struct lu_env *env, struct cl_io *io,
902                         struct cl_page_list *queue,
903                         pgoff_t start, pgoff_t end)
904 {
905         int ret = 0;
906         __u64 kms;
907         pgoff_t page_idx;
908         int count = 0;
909
910         ENTRY;
911
912         ret = ll_readahead_file_kms(env, io, &kms);
913         if (ret != 0)
914                 RETURN(ret);
915
916         if (kms == 0)
917                 RETURN(0);
918
919         if (end != 0) {
920                 unsigned long end_index;
921
922                 end_index = (unsigned long)((kms - 1) >> PAGE_SHIFT);
923                 if (end_index <= end)
924                         end = end_index;
925         }
926
927         for (page_idx = start; page_idx <= end; page_idx++) {
928                 ret = ll_read_ahead_page(env, io, queue, page_idx,
929                                         WILLNEED);
930                 if (ret < 0)
931                         break;
932                 else if (ret == 0) /* ret 1 is already uptodate */
933                         count++;
934         }
935
936         RETURN(count > 0 ? count : ret);
937 }
938
939 /* called with the ras_lock held or from places where it doesn't matter */
940 static void ras_reset(struct ll_readahead_state *ras, pgoff_t index)
941 {
942         ras->ras_consecutive_requests = 0;
943         ras->ras_consecutive_bytes = 0;
944         ras->ras_window_pages = 0;
945         ras->ras_window_start_idx = ras_align(ras, index);
946         ras->ras_next_readahead_idx = max(ras->ras_window_start_idx, index + 1);
947
948         RAS_CDEBUG(ras);
949 }
950
951 /* called with the ras_lock held or from places where it doesn't matter */
952 static void ras_stride_reset(struct ll_readahead_state *ras)
953 {
954         ras->ras_consecutive_stride_requests = 0;
955         ras->ras_stride_length = 0;
956         ras->ras_stride_bytes = 0;
957         RAS_CDEBUG(ras);
958 }
959
960 void ll_readahead_init(struct inode *inode, struct ll_readahead_state *ras)
961 {
962         spin_lock_init(&ras->ras_lock);
963         ras->ras_rpc_pages = PTLRPC_MAX_BRW_PAGES;
964         ras_reset(ras, 0);
965         ras->ras_last_read_end_bytes = 0;
966         ras->ras_requests = 0;
967         ras->ras_range_min_start_idx = 0;
968         ras->ras_range_max_end_idx = 0;
969         ras->ras_range_requests = 0;
970         ras->ras_last_range_pages = 0;
971 }
972
973 /*
974  * Check whether the read request is in the stride window.
975  * If it is in the stride window, return true, otherwise return false.
976  */
977 static bool read_in_stride_window(struct ll_readahead_state *ras,
978                                   loff_t pos, loff_t bytes)
979 {
980         loff_t stride_gap;
981
982         if (ras->ras_stride_length == 0 || ras->ras_stride_bytes == 0 ||
983             ras->ras_stride_bytes == ras->ras_stride_length)
984                 return false;
985
986         stride_gap = pos - ras->ras_last_read_end_bytes - 1;
987
988         /* If it is contiguous read */
989         if (stride_gap == 0)
990                 return ras->ras_consecutive_bytes + bytes <=
991                         ras->ras_stride_bytes;
992
993         /* Otherwise check the stride by itself */
994         return (ras->ras_stride_length - ras->ras_stride_bytes) == stride_gap &&
995                 ras->ras_consecutive_bytes == ras->ras_stride_bytes &&
996                 bytes <= ras->ras_stride_bytes;
997 }
998
999 static void ras_init_stride_detector(struct ll_readahead_state *ras,
1000                                      loff_t pos, loff_t bytes)
1001 {
1002         loff_t stride_gap = pos - ras->ras_last_read_end_bytes - 1;
1003
1004         LASSERT(ras->ras_consecutive_stride_requests == 0);
1005
1006         if (pos <= ras->ras_last_read_end_bytes) {
1007                 /* Reset stride window for forward read */
1008                 ras_stride_reset(ras);
1009                 return;
1010         }
1011
1012         ras->ras_stride_bytes = ras->ras_consecutive_bytes;
1013         ras->ras_stride_length = stride_gap + ras->ras_consecutive_bytes;
1014         ras->ras_consecutive_stride_requests++;
1015         ras->ras_stride_offset = pos;
1016
1017         RAS_CDEBUG(ras);
1018 }
1019
1020 static unsigned long
1021 stride_page_count(struct ll_readahead_state *ras, loff_t len)
1022 {
1023         loff_t bytes_count =
1024                 stride_byte_count(ras->ras_stride_offset,
1025                                   ras->ras_stride_length, ras->ras_stride_bytes,
1026                                   ras->ras_window_start_idx << PAGE_SHIFT, len);
1027
1028         return (bytes_count + PAGE_SIZE - 1) >> PAGE_SHIFT;
1029 }
1030
1031 /* Stride Read-ahead window will be increased inc_len according to
1032  * stride I/O pattern
1033  */
1034 static void ras_stride_increase_window(struct ll_readahead_state *ras,
1035                                        struct ll_ra_info *ra, loff_t inc_bytes)
1036 {
1037         loff_t window_bytes, stride_bytes;
1038         u64 left_bytes;
1039         u64 step;
1040         loff_t end;
1041
1042         /* temporarily store in page units to reduce LASSERT() cost below */
1043         end = ras->ras_window_start_idx + ras->ras_window_pages;
1044
1045         LASSERT(ras->ras_stride_length > 0);
1046         LASSERTF(end >= (ras->ras_stride_offset >> PAGE_SHIFT),
1047                  "window_start_idx %lu, window_pages %lu stride_offset %llu\n",
1048                  ras->ras_window_start_idx, ras->ras_window_pages,
1049                  ras->ras_stride_offset);
1050
1051         end <<= PAGE_SHIFT;
1052         if (end <= ras->ras_stride_offset)
1053                 stride_bytes = 0;
1054         else
1055                 stride_bytes = end - ras->ras_stride_offset;
1056
1057         div64_u64_rem(stride_bytes, ras->ras_stride_length, &left_bytes);
1058         window_bytes = (ras->ras_window_pages << PAGE_SHIFT);
1059         if (left_bytes < ras->ras_stride_bytes) {
1060                 if (ras->ras_stride_bytes - left_bytes >= inc_bytes) {
1061                         window_bytes += inc_bytes;
1062                         goto out;
1063                 } else {
1064                         window_bytes += (ras->ras_stride_bytes - left_bytes);
1065                         inc_bytes -= (ras->ras_stride_bytes - left_bytes);
1066                 }
1067         } else {
1068                 window_bytes += (ras->ras_stride_length - left_bytes);
1069         }
1070
1071         LASSERT(ras->ras_stride_bytes != 0);
1072
1073         step = div64_u64_rem(inc_bytes, ras->ras_stride_bytes, &left_bytes);
1074
1075         window_bytes += step * ras->ras_stride_length + left_bytes;
1076         LASSERT(window_bytes > 0);
1077
1078 out:
1079         if (stride_page_count(ras, window_bytes) <=
1080             ra->ra_max_pages_per_file || ras->ras_window_pages == 0)
1081                 ras->ras_window_pages = (window_bytes >> PAGE_SHIFT);
1082
1083         LASSERT(ras->ras_window_pages > 0);
1084
1085         RAS_CDEBUG(ras);
1086 }
1087
1088 static void ras_increase_window(struct inode *inode,
1089                                 struct ll_readahead_state *ras,
1090                                 struct ll_ra_info *ra)
1091 {
1092         /* The stretch of ra-window should be aligned with max rpc_size
1093          * but current clio architecture does not support retrieve such
1094          * information from lower layer. FIXME later
1095          */
1096         if (stride_io_mode(ras)) {
1097                 ras_stride_increase_window(ras, ra,
1098                                       (loff_t)ras->ras_rpc_pages << PAGE_SHIFT);
1099         } else {
1100                 pgoff_t window_pages;
1101
1102                 window_pages = min(ras->ras_window_pages + ras->ras_rpc_pages,
1103                                    ra->ra_max_pages_per_file);
1104                 if (window_pages < ras->ras_rpc_pages)
1105                         ras->ras_window_pages = window_pages;
1106                 else
1107                         ras->ras_window_pages = ras_align(ras, window_pages);
1108         }
1109 }
1110
1111 /*
1112  * Seek within 8 pages are considered as sequential read for now.
1113  */
1114 static inline bool is_loose_seq_read(struct ll_readahead_state *ras, loff_t pos)
1115 {
1116         return pos_in_window(pos, ras->ras_last_read_end_bytes,
1117                              8UL << PAGE_SHIFT, 8UL << PAGE_SHIFT);
1118 }
1119
1120 static inline bool is_loose_mmap_read(struct ll_sb_info *sbi,
1121                                       struct ll_readahead_state *ras,
1122                                       unsigned long pos)
1123 {
1124         unsigned long range_pages = sbi->ll_ra_info.ra_range_pages;
1125
1126         return pos_in_window(pos, ras->ras_last_read_end_bytes,
1127                              range_pages << PAGE_SHIFT,
1128                              range_pages << PAGE_SHIFT);
1129 }
1130
1131 /*
1132  * We have observed slow mmap read performances for some
1133  * applications. The problem is if access pattern is neither
1134  * sequential nor stride, but could be still adjacent in a
1135  * small range and then seek a random position.
1136  *
1137  * So the pattern could be something like this:
1138  *
1139  * [1M data] [hole] [0.5M data] [hole] [0.7M data] [1M data]
1140  *
1141  *
1142  * Every time an application reads mmap data, it may not only
1143  * read a single 4KB page, but aslo a cluster of nearby pages in
1144  * a range(e.g. 1MB) of the first page after a cache miss.
1145  *
1146  * The readahead engine is modified to track the range size of
1147  * a cluster of mmap reads, so that after a seek and/or cache miss,
1148  * the range size is used to efficiently prefetch multiple pages
1149  * in a single RPC rather than many small RPCs.
1150  */
1151 static void ras_detect_cluster_range(struct ll_readahead_state *ras,
1152                                      struct ll_sb_info *sbi,
1153                                      unsigned long pos, unsigned long count)
1154 {
1155         pgoff_t last_pages, pages;
1156         pgoff_t end_idx = (pos + count - 1) >> PAGE_SHIFT;
1157
1158         last_pages = ras->ras_range_max_end_idx -
1159                         ras->ras_range_min_start_idx + 1;
1160         /* First time come here */
1161         if (!ras->ras_range_max_end_idx)
1162                 goto out;
1163
1164         /* Random or Stride read */
1165         if (!is_loose_mmap_read(sbi, ras, pos))
1166                 goto out;
1167
1168         ras->ras_range_requests++;
1169         if (ras->ras_range_max_end_idx < end_idx)
1170                 ras->ras_range_max_end_idx = end_idx;
1171
1172         if (ras->ras_range_min_start_idx > (pos >> PAGE_SHIFT))
1173                 ras->ras_range_min_start_idx = pos >> PAGE_SHIFT;
1174
1175         /* Out of range, consider it as random or stride */
1176         pages = ras->ras_range_max_end_idx -
1177                         ras->ras_range_min_start_idx + 1;
1178         if (pages <= sbi->ll_ra_info.ra_range_pages)
1179                 return;
1180 out:
1181         ras->ras_last_range_pages = last_pages;
1182         ras->ras_range_requests = 0;
1183         ras->ras_range_min_start_idx = pos >> PAGE_SHIFT;
1184         ras->ras_range_max_end_idx = end_idx;
1185 }
1186
1187 static void ras_detect_read_pattern(struct ll_readahead_state *ras,
1188                                     struct ll_sb_info *sbi,
1189                                     loff_t pos, size_t bytes, bool mmap)
1190 {
1191         bool stride_detect = false;
1192         pgoff_t index = pos >> PAGE_SHIFT;
1193
1194         RAS_CDEBUG(ras);
1195         /*
1196          * Reset the read-ahead window in two cases. First when the app seeks
1197          * or reads to some other part of the file. Secondly if we get a
1198          * read-ahead miss that we think we've previously issued. This can
1199          * be a symptom of there being so many read-ahead pages that the VM
1200          * is reclaiming it before we get to it.
1201          */
1202         if (!is_loose_seq_read(ras, pos)) {
1203                 /* Check whether it is in stride I/O mode */
1204                 if (!read_in_stride_window(ras, pos, bytes)) {
1205                         if (ras->ras_consecutive_stride_requests == 0)
1206                                 ras_init_stride_detector(ras, pos, bytes);
1207                         else
1208                                 ras_stride_reset(ras);
1209                         ras->ras_consecutive_bytes = 0;
1210                         ras_reset(ras, index);
1211                 } else {
1212                         ras->ras_consecutive_bytes = 0;
1213                         ras->ras_consecutive_requests = 0;
1214                         if (++ras->ras_consecutive_stride_requests > 1)
1215                                 stride_detect = true;
1216                         RAS_CDEBUG(ras);
1217                 }
1218                 ll_ra_stats_inc_sbi(sbi, RA_STAT_DISTANT_READPAGE);
1219         } else if (stride_io_mode(ras)) {
1220                 /*
1221                  * If this is contiguous read but in stride I/O mode
1222                  * currently, check whether stride step still is valid,
1223                  * if invalid, it will reset the stride ra window to
1224                  * be zero.
1225                  */
1226                 if (!read_in_stride_window(ras, pos, bytes)) {
1227                         ras_stride_reset(ras);
1228                         ras->ras_window_pages = 0;
1229                         ras->ras_next_readahead_idx = index;
1230                 }
1231         }
1232
1233         ras->ras_consecutive_bytes += bytes;
1234         if (mmap) {
1235                 pgoff_t idx = ras->ras_consecutive_bytes >> PAGE_SHIFT;
1236                 unsigned long ra_range_pages =
1237                                 max_t(unsigned long, RA_MIN_MMAP_RANGE_PAGES,
1238                                       sbi->ll_ra_info.ra_range_pages);
1239
1240                 if ((idx >= ra_range_pages &&
1241                      idx % ra_range_pages == 0) || stride_detect)
1242                         ras->ras_need_increase_window = true;
1243         } else if ((ras->ras_consecutive_requests > 1 || stride_detect)) {
1244                 ras->ras_need_increase_window = true;
1245         }
1246
1247         ras->ras_last_read_end_bytes = pos + bytes - 1;
1248         RAS_CDEBUG(ras);
1249 }
1250
1251 void ll_ras_enter(struct file *f, loff_t pos, size_t bytes)
1252 {
1253         struct ll_file_data *fd = f->private_data;
1254         struct ll_readahead_state *ras = &fd->fd_ras;
1255         struct inode *inode = file_inode(f);
1256         struct ll_sb_info *sbi = ll_i2sbi(inode);
1257
1258         spin_lock(&ras->ras_lock);
1259         ras->ras_requests++;
1260         ras->ras_consecutive_requests++;
1261         ras->ras_need_increase_window = false;
1262         ras->ras_whole_file_read = false;
1263         /*
1264          * On the second access to a file smaller than the tunable
1265          * ra_max_read_ahead_whole_pages trigger RA on all pages in the
1266          * file up to ra_max_pages_per_file.  This is simply a best effort
1267          * and only occurs once per open file. Normal RA behavior is reverted
1268          * to for subsequent IO.
1269          */
1270         if (ras->ras_requests >= 2) {
1271                 __u64 kms_pages;
1272                 struct ll_ra_info *ra = &sbi->ll_ra_info;
1273
1274                 kms_pages = (i_size_read(inode) + PAGE_SIZE - 1) >>
1275                             PAGE_SHIFT;
1276
1277                 CDEBUG(D_READA, "kmsp %llu mwp %lu mp %lu\n", kms_pages,
1278                        ra->ra_max_read_ahead_whole_pages,
1279                        ra->ra_max_pages_per_file);
1280
1281                 if (kms_pages &&
1282                     kms_pages <= ra->ra_max_read_ahead_whole_pages) {
1283                         ras->ras_whole_file_read = true;
1284                         ras->ras_window_start_idx = 0;
1285                         ras->ras_next_readahead_idx = 0;
1286                         ras->ras_window_pages = min(ra->ra_max_pages_per_file,
1287                                             ra->ra_max_read_ahead_whole_pages);
1288                         GOTO(out_unlock, 0);
1289                 }
1290         }
1291         ras_detect_read_pattern(ras, sbi, pos, bytes, false);
1292 out_unlock:
1293         spin_unlock(&ras->ras_lock);
1294 }
1295
1296 static bool index_in_stride_window(struct ll_readahead_state *ras,
1297                                    pgoff_t index)
1298 {
1299         loff_t pos = (loff_t)index << PAGE_SHIFT;
1300
1301         if (ras->ras_stride_length == 0 || ras->ras_stride_bytes == 0 ||
1302             ras->ras_stride_bytes == ras->ras_stride_length)
1303                 return false;
1304
1305         if (pos >= ras->ras_stride_offset) {
1306                 u64 offset;
1307
1308                 div64_u64_rem(pos - ras->ras_stride_offset,
1309                               ras->ras_stride_length, &offset);
1310                 if (offset < ras->ras_stride_bytes ||
1311                     ras->ras_stride_length - offset < PAGE_SIZE)
1312                         return true;
1313         } else if (ras->ras_stride_offset - pos < PAGE_SIZE) {
1314                 return true;
1315         }
1316
1317         return false;
1318 }
1319
1320 /*
1321  * ll_ras_enter() is used to detect read pattern according to pos and count.
1322  *
1323  * ras_update() is used to detect cache miss and
1324  * reset window or increase window accordingly
1325  */
1326 static void ras_update(struct ll_sb_info *sbi, struct inode *inode,
1327                        struct ll_readahead_state *ras, pgoff_t index,
1328                        enum ras_update_flags flags, struct cl_io *io)
1329 {
1330         struct ll_ra_info *ra = &sbi->ll_ra_info;
1331         bool hit = flags & LL_RAS_HIT;
1332
1333         ENTRY;
1334         spin_lock(&ras->ras_lock);
1335
1336         RAS_CDEBUG(ras);
1337
1338         if (!hit)
1339                 CDEBUG(D_READA|D_IOTRACE, DFID " pages at %lu miss.\n",
1340                        PFID(ll_inode2fid(inode)), index);
1341         ll_ra_stats_inc_sbi(sbi, hit ? RA_STAT_HIT : RA_STAT_MISS);
1342
1343         /*
1344          * The readahead window has been expanded to cover whole
1345          * file size, we don't care whether ra miss happen or not.
1346          * Because we will read whole file to page cache even if
1347          * some pages missed.
1348          */
1349         if (ras->ras_whole_file_read)
1350                 GOTO(out_unlock, 0);
1351
1352         if (io && io->ci_rand_read)
1353                 GOTO(out_unlock, 0);
1354
1355         if (io && io->ci_seq_read) {
1356                 if (!hit) {
1357                         /* to avoid many small read RPC here */
1358                         ras->ras_window_pages = sbi->ll_ra_info.ra_range_pages;
1359                         ll_ra_stats_inc_sbi(sbi, RA_STAT_MMAP_RANGE_READ);
1360                 }
1361                 goto skip_miss_checking;
1362         }
1363
1364         if (flags & LL_RAS_MMAP) {
1365                 unsigned long ra_pages;
1366
1367                 ras_detect_cluster_range(ras, sbi, index << PAGE_SHIFT,
1368                                          PAGE_SIZE);
1369                 ras_detect_read_pattern(ras, sbi, (loff_t)index << PAGE_SHIFT,
1370                                         PAGE_SIZE, true);
1371
1372                 /* we did not detect anything but we could prefetch */
1373                 if (!ras->ras_need_increase_window &&
1374                     ras->ras_window_pages <= sbi->ll_ra_info.ra_range_pages &&
1375                     ras->ras_range_requests >= 2) {
1376                         if (!hit) {
1377                                 ra_pages = max_t(unsigned long,
1378                                         RA_MIN_MMAP_RANGE_PAGES,
1379                                         ras->ras_last_range_pages);
1380                                 if (index < ra_pages / 2)
1381                                         index = 0;
1382                                 else
1383                                         index -= ra_pages / 2;
1384                                 ras->ras_window_pages = ra_pages;
1385                                 ll_ra_stats_inc_sbi(sbi,
1386                                         RA_STAT_MMAP_RANGE_READ);
1387                         } else {
1388                                 ras->ras_window_pages = 0;
1389                         }
1390                         goto skip_miss_checking;
1391                 }
1392         }
1393
1394         if (!hit && ras->ras_window_pages &&
1395             index < ras->ras_next_readahead_idx &&
1396             pos_in_window(index, ras->ras_window_start_idx, 0,
1397                           ras->ras_window_pages)) {
1398                 ll_ra_stats_inc_sbi(sbi, RA_STAT_MISS_IN_WINDOW);
1399                 ras->ras_need_increase_window = false;
1400
1401                 if (index_in_stride_window(ras, index) &&
1402                     stride_io_mode(ras)) {
1403                         /*
1404                          * if (index != ras->ras_last_readpage + 1)
1405                          *      ras->ras_consecutive_pages = 0;
1406                          */
1407                         ras_reset(ras, index);
1408
1409                         /*
1410                          * If stride-RA hit cache miss, the stride
1411                          * detector will not be reset to avoid the
1412                          * overhead of redetecting read-ahead mode,
1413                          * but on the condition that the stride window
1414                          * is still intersect with normal sequential
1415                          * read-ahead window.
1416                          */
1417                         if (ras->ras_window_start_idx < ras->ras_stride_offset)
1418                                 ras_stride_reset(ras);
1419                         RAS_CDEBUG(ras);
1420                 } else {
1421                         /*
1422                          * Reset both stride window and normal RA
1423                          * window.
1424                          */
1425                         ras_reset(ras, index);
1426                         /* ras->ras_consecutive_pages++; */
1427                         ras->ras_consecutive_bytes = 0;
1428                         ras_stride_reset(ras);
1429                         GOTO(out_unlock, 0);
1430                 }
1431         }
1432
1433 skip_miss_checking:
1434         ras->ras_window_start_idx = ras_align(ras, index);
1435
1436         if (stride_io_mode(ras)) {
1437                 /* Since stride readahead is sentivite to the offset
1438                  * of read-ahead, so we use original offset here,
1439                  * instead of ras_window_start_idx, which is RPC aligned.
1440                  */
1441                 ras->ras_next_readahead_idx = max(index + 1,
1442                                                   ras->ras_next_readahead_idx);
1443                 ras->ras_window_start_idx =
1444                                 max_t(pgoff_t, ras->ras_window_start_idx,
1445                                       ras->ras_stride_offset >> PAGE_SHIFT);
1446         } else {
1447                 if (ras->ras_next_readahead_idx < ras->ras_window_start_idx)
1448                         ras->ras_next_readahead_idx = ras->ras_window_start_idx;
1449                 if (!hit)
1450                         ras->ras_next_readahead_idx = index + 1;
1451         }
1452
1453         if (ras->ras_need_increase_window) {
1454                 ras_increase_window(inode, ras, ra);
1455                 ras->ras_need_increase_window = false;
1456         }
1457
1458         EXIT;
1459 out_unlock:
1460         RAS_CDEBUG(ras);
1461         spin_unlock(&ras->ras_lock);
1462 }
1463
1464 int ll_writepage(struct page *vmpage, struct writeback_control *wbc)
1465 {
1466         struct inode           *inode = vmpage->mapping->host;
1467         struct ll_inode_info   *lli   = ll_i2info(inode);
1468         struct lu_env          *env;
1469         struct cl_io           *io;
1470         struct cl_page         *page;
1471         struct cl_object       *clob;
1472         bool redirtied = false;
1473         bool unlocked = false;
1474         int result;
1475         __u16 refcheck;
1476
1477         ENTRY;
1478
1479         LASSERT(PageLocked(vmpage));
1480         LASSERT(!PageWriteback(vmpage));
1481
1482         LASSERT(ll_i2dtexp(inode) != NULL);
1483
1484         env = cl_env_get(&refcheck);
1485         if (IS_ERR(env))
1486                 GOTO(out, result = PTR_ERR(env));
1487
1488         clob  = ll_i2info(inode)->lli_clob;
1489         LASSERT(clob != NULL);
1490
1491         io = vvp_env_thread_io(env);
1492         io->ci_obj = clob;
1493         io->ci_ignore_layout = 1;
1494         result = cl_io_init(env, io, CIT_MISC, clob);
1495         if (result == 0) {
1496                 page = cl_page_find(env, clob, vmpage->index,
1497                                     vmpage, CPT_CACHEABLE);
1498                 if (!IS_ERR(page)) {
1499                         lu_ref_add(&page->cp_reference, "writepage",
1500                                    current);
1501                         cl_page_assume(env, io, page);
1502                         result = cl_page_flush(env, io, page);
1503                         if (result != 0) {
1504                                 /*
1505                                  * Re-dirty page on error so it retries write,
1506                                  * but not in case when IO has actually
1507                                  * occurred and completed with an error.
1508                                  */
1509                                 if (!PageError(vmpage)) {
1510                                         redirty_page_for_writepage(wbc, vmpage);
1511                                         result = 0;
1512                                         redirtied = true;
1513                                 }
1514                         }
1515                         cl_page_disown(env, io, page);
1516                         unlocked = true;
1517                         lu_ref_del(&page->cp_reference,
1518                                    "writepage", current);
1519                         cl_page_put(env, page);
1520                 } else {
1521                         result = PTR_ERR(page);
1522                 }
1523         }
1524         cl_io_fini(env, io);
1525
1526         if (redirtied && wbc->sync_mode == WB_SYNC_ALL) {
1527                 loff_t offset = vmpage->index << PAGE_SHIFT;
1528
1529                 /* Flush page failed because the extent is being written out.
1530                  * Wait for the write of extent to be finished to avoid
1531                  * breaking kernel which assumes ->writepage should mark
1532                  * PageWriteback or clean the page.
1533                  */
1534                 result = cl_sync_file_range(inode, offset,
1535                                             offset + PAGE_SIZE - 1,
1536                                             CL_FSYNC_LOCAL, 1);
1537                 if (result > 0) {
1538                         /* May have written more than one page. decreasing this
1539                          * page because the caller will count it.
1540                          */
1541                         wbc->nr_to_write -= result - 1;
1542                         result = 0;
1543                 }
1544         }
1545
1546         cl_env_put(env, &refcheck);
1547         GOTO(out, result);
1548
1549 out:
1550         if (result < 0) {
1551                 if (!lli->lli_async_rc)
1552                         lli->lli_async_rc = result;
1553                 SetPageError(vmpage);
1554                 if (!unlocked)
1555                         unlock_page(vmpage);
1556         }
1557         return result;
1558 }
1559
1560 int ll_writepages(struct address_space *mapping, struct writeback_control *wbc)
1561 {
1562         struct inode *inode = mapping->host;
1563         loff_t start;
1564         loff_t end;
1565         enum cl_fsync_mode mode;
1566         int range_whole = 0;
1567         int result;
1568
1569         ENTRY;
1570
1571         if (wbc->range_cyclic) {
1572                 start = (loff_t)mapping->writeback_index << PAGE_SHIFT;
1573                 end = OBD_OBJECT_EOF;
1574         } else {
1575                 start = wbc->range_start;
1576                 end = wbc->range_end;
1577                 if (end == LLONG_MAX) {
1578                         end = OBD_OBJECT_EOF;
1579                         range_whole = start == 0;
1580                 }
1581         }
1582
1583         mode = CL_FSYNC_NONE;
1584         if (wbc->sync_mode == WB_SYNC_ALL)
1585                 mode = CL_FSYNC_LOCAL;
1586
1587         if (wbc->sync_mode == WB_SYNC_NONE) {
1588 #ifdef SB_I_CGROUPWB
1589                 struct bdi_writeback *wb;
1590
1591                 /*
1592                  * As it may break full stripe writes on the inode,
1593                  * disable periodic kupdate writeback (@wbc->for_kupdate)?
1594                  */
1595
1596                 /*
1597                  * The system is under memory pressure and it is now reclaiming
1598                  * cache pages.
1599                  */
1600                 wb = inode_to_wb(inode);
1601                 if (wbc->for_background ||
1602                     (wb->start_all_reason == WB_REASON_VMSCAN &&
1603                      test_bit(WB_start_all, &wb->state)))
1604                         mode = CL_FSYNC_RECLAIM;
1605 #else
1606                 /*
1607                  * We have no idea about writeback reason for memory reclaim
1608                  * WB_REASON_TRY_TO_FREE_PAGES in the old kernel such as rhel7
1609                  * (WB_REASON_VMSCAN in the newer kernel) ...
1610                  * Here set mode with CL_FSYNC_RECLAIM forcely on the old
1611                  * kernel.
1612                  */
1613                 if (!wbc->for_kupdate)
1614                         mode = CL_FSYNC_RECLAIM;
1615 #endif
1616         }
1617
1618         if (ll_i2info(inode)->lli_clob == NULL || (inode->i_state & I_FREEING))
1619                 RETURN(0);
1620
1621         /* for directio, it would call writepages() to evict cached pages
1622          * inside the IO context of write, which will cause deadlock at
1623          * layout_conf since it waits for active IOs to complete.
1624          */
1625         result = cl_sync_file_range(inode, start, end, mode, 1);
1626         if (result > 0) {
1627                 wbc->nr_to_write -= result;
1628                 result = 0;
1629         }
1630
1631         if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0)) {
1632                 if (end == OBD_OBJECT_EOF)
1633                         mapping->writeback_index = 0;
1634                 else
1635                         mapping->writeback_index = (end >> PAGE_SHIFT) + 1;
1636         }
1637         RETURN(result);
1638 }
1639
1640 struct ll_cl_context *ll_cl_find(struct inode *inode)
1641 {
1642         struct ll_inode_info *lli = ll_i2info(inode);
1643         struct ll_cl_context *lcc;
1644         struct ll_cl_context *found = NULL;
1645
1646         read_lock(&lli->lli_lock);
1647         list_for_each_entry(lcc, &lli->lli_lccs, lcc_list) {
1648                 if (lcc->lcc_cookie == current) {
1649                         found = lcc;
1650                         break;
1651                 }
1652         }
1653         read_unlock(&lli->lli_lock);
1654
1655         return found;
1656 }
1657
1658 void ll_cl_add(struct inode *inode, const struct lu_env *env, struct cl_io *io,
1659                enum lcc_type type)
1660 {
1661         struct ll_inode_info *lli = ll_i2info(inode);
1662         struct ll_cl_context *lcc = &ll_env_info(env)->lti_io_ctx;
1663
1664         memset(lcc, 0, sizeof(*lcc));
1665         INIT_LIST_HEAD(&lcc->lcc_list);
1666         lcc->lcc_cookie = current;
1667         lcc->lcc_env = env;
1668         lcc->lcc_io = io;
1669         lcc->lcc_type = type;
1670
1671         write_lock(&lli->lli_lock);
1672         list_add(&lcc->lcc_list, &lli->lli_lccs);
1673         write_unlock(&lli->lli_lock);
1674 }
1675
1676 void ll_cl_remove(struct inode *inode, const struct lu_env *env)
1677 {
1678         struct ll_inode_info *lli = ll_i2info(inode);
1679         struct ll_cl_context *lcc = &ll_env_info(env)->lti_io_ctx;
1680
1681         write_lock(&lli->lli_lock);
1682         list_del_init(&lcc->lcc_list);
1683         write_unlock(&lli->lli_lock);
1684 }
1685
1686 int ll_io_read_page(const struct lu_env *env, struct cl_io *io,
1687                            struct cl_page *page, struct file *file)
1688 {
1689         struct inode              *inode  = vvp_object_inode(page->cp_obj);
1690         struct ll_sb_info         *sbi    = ll_i2sbi(inode);
1691         struct ll_file_data       *fd     = NULL;
1692         struct ll_readahead_state *ras    = NULL;
1693         struct cl_2queue          *queue  = &io->ci_queue;
1694         struct cl_sync_io         *anchor = NULL;
1695         int                        rc = 0, rc2 = 0;
1696         bool                       uptodate;
1697         struct vvp_io *vio = vvp_env_io(env);
1698         bool mmap = !vio->vui_ra_valid;
1699         pgoff_t ra_start_index = 0;
1700         pgoff_t io_start_index;
1701         pgoff_t io_end_index;
1702         bool unlockpage = true;
1703
1704         ENTRY;
1705
1706         if (file) {
1707                 fd = file->private_data;
1708                 ras = &fd->fd_ras;
1709         }
1710
1711         /* PagePrivate2 is set in ll_io_zero_page() to tell us the vmpage
1712          * must not be unlocked after processing.
1713          */
1714         if (page->cp_vmpage && PagePrivate2(page->cp_vmpage))
1715                 unlockpage = false;
1716
1717         uptodate = page->cp_defer_uptodate;
1718
1719         if (ll_readahead_enabled(sbi) && !page->cp_ra_updated && ras) {
1720                 enum ras_update_flags flags = 0;
1721
1722                 if (uptodate)
1723                         flags |= LL_RAS_HIT;
1724                 if (mmap)
1725                         flags |= LL_RAS_MMAP;
1726                 ras_update(sbi, inode, ras, cl_page_index(page), flags, io);
1727         }
1728
1729         cl_2queue_init(queue);
1730         if (uptodate) {
1731                 page->cp_ra_used = 1;
1732                 SetPageUptodate(page->cp_vmpage);
1733                 cl_page_disown(env, io, page);
1734         } else {
1735                 anchor = &vvp_env_info(env)->vti_anchor;
1736                 cl_sync_io_init(anchor, 1);
1737                 page->cp_sync_io = anchor;
1738
1739                 cl_page_list_add(&queue->c2_qin, page, true);
1740         }
1741
1742         /* mmap does not set the ci_rw fields */
1743         if (!mmap) {
1744                 io_start_index = io->u.ci_rw.crw_pos >> PAGE_SHIFT;
1745                 io_end_index = (io->u.ci_rw.crw_pos +
1746                                 io->u.ci_rw.crw_bytes - 1) >> PAGE_SHIFT;
1747         } else {
1748                 io_start_index = cl_page_index(page);
1749                 io_end_index = cl_page_index(page);
1750         }
1751
1752         if (ll_readahead_enabled(sbi) && ras && !io->ci_rand_read) {
1753                 pgoff_t skip_index = 0;
1754
1755                 if (ras->ras_next_readahead_idx < cl_page_index(page))
1756                         skip_index = cl_page_index(page);
1757                 rc2 = ll_readahead(env, io, &queue->c2_qin, ras,
1758                                    uptodate, file, skip_index,
1759                                    &ra_start_index);
1760                 /* Keep iotrace clean. Print only on actual page read */
1761                 CDEBUG(D_READA | (rc2 ? D_IOTRACE : 0),
1762                        DFID " %d pages read ahead at %lu, triggered by user read at %lu, stride offset %lld, stride length %lld, stride bytes %lld\n",
1763                        PFID(ll_inode2fid(inode)), rc2, ra_start_index,
1764                        cl_page_index(page), ras->ras_stride_offset,
1765                        ras->ras_stride_length, ras->ras_stride_bytes);
1766
1767         } else if (cl_page_index(page) == io_start_index &&
1768                    io_end_index - io_start_index > 0) {
1769                 rc2 = ll_readpages(env, io, &queue->c2_qin, io_start_index + 1,
1770                                    io_end_index);
1771                 CDEBUG(D_READA, DFID " %d pages read at %lu\n",
1772                        PFID(ll_inode2fid(inode)), rc2, cl_page_index(page));
1773         }
1774
1775         if (queue->c2_qin.pl_nr > 0) {
1776                 int count = queue->c2_qin.pl_nr;
1777
1778                 rc = cl_io_submit_rw(env, io, CRT_READ, queue);
1779                 if (rc == 0)
1780                         task_io_account_read(PAGE_SIZE * count);
1781         }
1782
1783
1784         if (anchor != NULL && !cl_page_is_owned(page, io)) { /* have sent */
1785                 rc = cl_sync_io_wait(env, anchor, 0);
1786
1787                 cl_page_assume(env, io, page);
1788                 cl_page_list_del(env, &queue->c2_qout, page, true);
1789
1790                 if (!PageUptodate(cl_page_vmpage(page))) {
1791                         /* Failed to read a mirror, discard this page so that
1792                          * new page can be created with new mirror.
1793                          *
1794                          * TODO: this is not needed after page reinit
1795                          * route is implemented
1796                          */
1797                         cl_page_discard(env, io, page);
1798                 }
1799                 if (unlockpage)
1800                         cl_page_disown(env, io, page);
1801         }
1802
1803         /* TODO: discard all pages until page reinit route is implemented */
1804         cl_page_list_discard(env, io, &queue->c2_qin);
1805
1806         /* Unlock unsent read pages in case of error. */
1807         cl_page_list_disown(env, &queue->c2_qin);
1808
1809         cl_2queue_fini(env, queue);
1810
1811         RETURN(rc);
1812 }
1813
1814 /*
1815  * Possible return value:
1816  * 0 no async readahead triggered and fast read could not be used.
1817  * 1 no async readahead, but fast read could be used.
1818  * 2 async readahead triggered and fast read could be used too.
1819  * < 0 on error.
1820  */
1821 static int kickoff_async_readahead(struct file *file, unsigned long pages)
1822 {
1823         struct ll_readahead_work *lrw;
1824         struct inode *inode = file_inode(file);
1825         struct ll_sb_info *sbi = ll_i2sbi(inode);
1826         struct ll_file_data *fd = file->private_data;
1827         struct ll_readahead_state *ras = &fd->fd_ras;
1828         struct ll_ra_info *ra = &sbi->ll_ra_info;
1829         unsigned long throttle;
1830         pgoff_t start_idx = ras_align(ras, ras->ras_next_readahead_idx);
1831         pgoff_t end_idx = start_idx + pages - 1;
1832
1833         /*
1834          * In case we have a limited max_cached_mb, readahead
1835          * should be stopped if it have run out of all LRU slots.
1836          */
1837         if (atomic_read(&ra->ra_cur_pages) >= sbi->ll_cache->ccc_lru_max) {
1838                 ll_ra_stats_inc(inode, RA_STAT_MAX_IN_FLIGHT);
1839                 return 0;
1840         }
1841
1842         throttle = min(ra->ra_async_pages_per_file_threshold,
1843                        ra->ra_max_pages_per_file);
1844         /*
1845          * If this is strided i/o or the window is smaller than the
1846          * throttle limit, we do not do async readahead. Otherwise,
1847          * we do async readahead, allowing the user thread to do fast i/o.
1848          */
1849         if (stride_io_mode(ras) || !throttle ||
1850             ras->ras_window_pages < throttle ||
1851             atomic_read(&ra->ra_async_inflight) > ra->ra_async_max_active)
1852                 return 0;
1853
1854         if ((atomic_read(&ra->ra_cur_pages) + pages) > ra->ra_max_pages)
1855                 return 0;
1856
1857         if (ras->ras_async_last_readpage_idx == start_idx)
1858                 return 1;
1859
1860         /* ll_readahead_work_free() free it */
1861         OBD_ALLOC_PTR(lrw);
1862         if (lrw) {
1863                 atomic_inc(&sbi->ll_ra_info.ra_async_inflight);
1864                 lrw->lrw_file = get_file(file);
1865                 lrw->lrw_start_idx = start_idx;
1866                 lrw->lrw_end_idx = end_idx;
1867                 lrw->lrw_user_pid = current->pid;
1868                 spin_lock(&ras->ras_lock);
1869                 ras->ras_next_readahead_idx = end_idx + 1;
1870                 ras->ras_async_last_readpage_idx = start_idx;
1871                 spin_unlock(&ras->ras_lock);
1872                 memcpy(lrw->lrw_jobid, ll_i2info(inode)->lli_jobid,
1873                        sizeof(lrw->lrw_jobid));
1874                 ll_readahead_work_add(inode, lrw);
1875         } else {
1876                 return -ENOMEM;
1877         }
1878
1879         return 2;
1880 }
1881
1882 /*
1883  * Check if we can issue a readahead RPC, if that is
1884  * the case, we can't do fast IO because we will need
1885  * a cl_io to issue the RPC.
1886  */
1887 static bool ll_use_fast_io(struct file *file,
1888                            struct ll_readahead_state *ras, pgoff_t index)
1889 {
1890         unsigned long fast_read_pages =
1891                 max(RA_REMAIN_WINDOW_MIN, ras->ras_rpc_pages);
1892         loff_t skip_pages;
1893         loff_t stride_bytes = ras->ras_stride_bytes;
1894
1895         RAS_CDEBUG(ras);
1896
1897         if (stride_io_mode(ras) && stride_bytes) {
1898                 skip_pages = (ras->ras_stride_length +
1899                         ras->ras_stride_bytes - 1) / stride_bytes;
1900                 skip_pages *= fast_read_pages;
1901         } else {
1902                 skip_pages = fast_read_pages;
1903         }
1904
1905         RAS_CDEBUG(ras);
1906
1907         if (ras->ras_whole_file_read ||
1908             ras->ras_window_start_idx + ras->ras_window_pages <
1909             ras->ras_next_readahead_idx + skip_pages ||
1910             kickoff_async_readahead(file, fast_read_pages) > 0) {
1911                 return true;
1912         }
1913
1914         return false;
1915 }
1916
1917 int ll_readpage(struct file *file, struct page *vmpage)
1918 {
1919         struct inode *inode = file_inode(file);
1920         struct cl_object *clob = ll_i2info(inode)->lli_clob;
1921         struct ll_sb_info *sbi = ll_i2sbi(inode);
1922         const struct lu_env *env = NULL;
1923         struct cl_read_ahead ra = { 0 };
1924         struct ll_cl_context *lcc;
1925         struct cl_io *io = NULL;
1926         struct cl_page *page;
1927         struct vvp_io *vio;
1928         int result;
1929         int flags;
1930
1931         ENTRY;
1932
1933         if (CFS_FAIL_PRECHECK(OBD_FAIL_LLITE_READPAGE_PAUSE)) {
1934                 unlock_page(vmpage);
1935                 CFS_FAIL_TIMEOUT(OBD_FAIL_LLITE_READPAGE_PAUSE, cfs_fail_val);
1936                 lock_page(vmpage);
1937         }
1938
1939         /*
1940          * The @vmpage got truncated.
1941          * This is a kernel bug introduced since kernel 5.12:
1942          * comment: cbd59c48ae2bcadc4a7599c29cf32fd3f9b78251
1943          * ("mm/filemap: use head pages in generic_file_buffered_read")
1944          *
1945          * The page end offset calculation in filemap_get_read_batch() was off
1946          * by one.  When a read is submitted with end offset 1048575, then it
1947          * calculates the end page for read of 256 where it should be 255. This
1948          * results in the readpage() for the page with index 256 is over stripe
1949          * boundary and may not covered by a DLM extent lock.
1950          *
1951          * This happens in a corner race case: filemap_get_read_batch() adds
1952          * the page with index 256 for read which is not in the current read
1953          * I/O context, and this page is being invalidated and will be removed
1954          * from page cache due to the lock protected it being revoken. This
1955          * results in this page in the read path not covered by any DLM lock.
1956          *
1957          * The solution is simple. Check whether the page was truncated in
1958          * ->readpage(). If so, just return AOP_TRUNCATED_PAGE to the upper
1959          * caller. Then the kernel will retry to batch pages, and it will not
1960          * add the truncated page into batches as it was removed from page
1961          * cache of the file.
1962          */
1963         if (vmpage->mapping != inode->i_mapping) {
1964                 unlock_page(vmpage);
1965                 RETURN(AOP_TRUNCATED_PAGE);
1966         }
1967
1968         lcc = ll_cl_find(inode);
1969         if (lcc != NULL) {
1970                 env = lcc->lcc_env;
1971                 io  = lcc->lcc_io;
1972         }
1973
1974         if (io == NULL) { /* fast read */
1975                 struct inode *inode = file_inode(file);
1976                 struct ll_file_data *fd = file->private_data;
1977                 struct ll_readahead_state *ras = &fd->fd_ras;
1978                 struct lu_env  *local_env = NULL;
1979
1980                 CDEBUG(D_VFSTRACE, "fast read pgno: %ld\n", vmpage->index);
1981
1982                 result = -ENODATA;
1983
1984                 /* TODO: need to verify the layout version to make sure
1985                  * the page is not invalid due to layout change.
1986                  */
1987                 page = cl_vmpage_page(vmpage, clob);
1988                 if (page == NULL) {
1989                         unlock_page(vmpage);
1990                         CDEBUG(D_READA, "fast read: failed to find page %ld\n",
1991                                 vmpage->index);
1992                         ll_ra_stats_inc_sbi(sbi, RA_STAT_FAILED_FAST_READ);
1993                         RETURN(result);
1994                 }
1995
1996                 if (page->cp_defer_uptodate) {
1997                         enum ras_update_flags flags = LL_RAS_HIT;
1998
1999                         if (lcc && lcc->lcc_type == LCC_MMAP)
2000                                 flags |= LL_RAS_MMAP;
2001
2002                         /* For fast read, it updates read ahead state only
2003                          * if the page is hit in cache because non cache page
2004                          * case will be handled by slow read later.
2005                          */
2006                         ras_update(sbi, inode, ras, cl_page_index(page), flags, io);
2007                         /* avoid duplicate ras_update() call */
2008                         page->cp_ra_updated = 1;
2009
2010                         if (ll_use_fast_io(file, ras, cl_page_index(page)))
2011                                 result = 0;
2012                 }
2013
2014                 if (!env) {
2015                         local_env = cl_env_percpu_get();
2016                         env = local_env;
2017                 }
2018
2019                 /* export the page and skip io stack */
2020                 if (result == 0) {
2021                         page->cp_ra_used = 1;
2022                         SetPageUptodate(vmpage);
2023                 } else {
2024                         ll_ra_stats_inc_sbi(sbi, RA_STAT_FAILED_FAST_READ);
2025                 }
2026
2027                 /* release page refcount before unlocking the page to ensure
2028                  * the object won't be destroyed in the calling path of
2029                  * cl_page_put(). Please see comment in ll_releasepage().
2030                  */
2031                 cl_page_put(env, page);
2032                 unlock_page(vmpage);
2033                 if (local_env)
2034                         cl_env_percpu_put(local_env);
2035
2036                 RETURN(result);
2037         }
2038
2039         if (lcc && lcc->lcc_type != LCC_MMAP) {
2040                 /*
2041                  * This handles a kernel bug introduced in kernel 5.12:
2042                  * comment: cbd59c48ae2bcadc4a7599c29cf32fd3f9b78251
2043                  * ("mm/filemap: use head pages in generic_file_buffered_read")
2044                  *
2045                  * See above in this function for a full description of the
2046                  * bug.  Briefly, the kernel will try to read 1 more page than
2047                  * was actually requested *if that page is already in cache*.
2048                  *
2049                  * Because this page is beyond the boundary of the requested
2050                  * read, Lustre does not lock it as part of the read.  This
2051                  * means we must check if there is a valid dlmlock on this
2052                  * this page and reference it before we attempt to read in the
2053                  * page.  If there is not a valid dlmlock, then we are racing
2054                  * with dlmlock cancellation and the page is being removed
2055                  * from the cache.
2056                  *
2057                  * That means we should return AOP_TRUNCATED_PAGE, which will
2058                  * cause the kernel to retry the read, which should allow the
2059                  * page to be removed from cache as the lock is cancelled.
2060                  *
2061                  * This should never occur except in kernels with the bug
2062                  * mentioned above.
2063                  */
2064                 if (vmpage->index >= lcc->lcc_end_index) {
2065                         CDEBUG(D_VFSTRACE,
2066                                "pgno:%ld, beyond read end_index:%ld\n",
2067                                vmpage->index, lcc->lcc_end_index);
2068
2069                         result = cl_io_read_ahead(env, io, vmpage->index, &ra);
2070                         if (result < 0 || vmpage->index > ra.cra_end_idx) {
2071                                 cl_read_ahead_release(env, &ra);
2072                                 unlock_page(vmpage);
2073                                 RETURN(AOP_TRUNCATED_PAGE);
2074                         }
2075                 }
2076         }
2077
2078         vio = vvp_env_io(env);
2079         /*
2080          * Direct read can fall back to buffered read, but DIO is done
2081          * with lockless i/o, and buffered requires LDLM locking, so in
2082          * this case we must restart without lockless.
2083          */
2084         flags = iocb_ki_flags_get(file, vio->vui_iocb);
2085         if (iocb_ki_flags_check(flags, DIRECT) &&
2086             lcc && lcc->lcc_type == LCC_RW &&
2087             !io->ci_dio_lock) {
2088                 unlock_page(vmpage);
2089                 io->ci_dio_lock = 1;
2090                 io->ci_need_restart = 1;
2091                 GOTO(out, result = -ENOLCK);
2092         }
2093
2094         LASSERT(io->ci_state == CIS_IO_GOING);
2095         page = cl_page_find(env, clob, vmpage->index, vmpage, CPT_CACHEABLE);
2096         if (!IS_ERR(page)) {
2097                 LASSERT(page->cp_type == CPT_CACHEABLE);
2098                 if (likely(!PageUptodate(vmpage))) {
2099                         cl_page_assume(env, io, page);
2100
2101                         result = ll_io_read_page(env, io, page, file);
2102                 } else {
2103                         /* Page from a non-object file. */
2104                         unlock_page(vmpage);
2105                         result = 0;
2106                 }
2107                 cl_page_put(env, page);
2108         } else {
2109                 unlock_page(vmpage);
2110                 result = PTR_ERR(page);
2111         }
2112
2113 out:
2114         if (ra.cra_release != NULL)
2115                 cl_read_ahead_release(env, &ra);
2116
2117         /* this delay gives time for the actual read of the page to finish and
2118          * unlock the page in vvp_page_completion_read before we return to our
2119          * caller and the caller tries to use the page, allowing us to test
2120          * races with the page being unlocked after readpage() but before it's
2121          * used by the caller
2122          */
2123         CFS_FAIL_TIMEOUT(OBD_FAIL_LLITE_READPAGE_PAUSE2, cfs_fail_val);
2124
2125         RETURN(result);
2126 }
2127
2128 #ifdef HAVE_AOPS_READ_FOLIO
2129 int ll_read_folio(struct file *file, struct folio *folio)
2130 {
2131         return ll_readpage(file, folio_page(folio, 0));
2132 }
2133 #endif