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