Whamcloud - gitweb
LU-12043 llite: fix to submit complete read block with ra disabled
[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  * Lustre is a trademark of Sun Microsystems, Inc.
31  *
32  * lustre/llite/rw.c
33  *
34  * Lustre Lite I/O page cache routines shared by different kernel revs
35  */
36
37 #include <linux/kernel.h>
38 #include <linux/mm.h>
39 #include <linux/string.h>
40 #include <linux/stat.h>
41 #include <linux/errno.h>
42 #include <linux/unistd.h>
43 #include <linux/writeback.h>
44 #include <asm/uaccess.h>
45
46 #include <linux/fs.h>
47 #include <linux/file.h>
48 #include <linux/stat.h>
49 #include <asm/uaccess.h>
50 #include <linux/mm.h>
51 #include <linux/pagemap.h>
52 /* current_is_kswapd() */
53 #include <linux/swap.h>
54 #include <linux/task_io_accounting_ops.h>
55
56 #define DEBUG_SUBSYSTEM S_LLITE
57
58 #include <obd_cksum.h>
59 #include "llite_internal.h"
60 #include <lustre_compat.h>
61
62 static void ll_ra_stats_inc_sbi(struct ll_sb_info *sbi, enum ra_stat which);
63
64 /**
65  * Get readahead pages from the filesystem readahead pool of the client for a
66  * thread.
67  *
68  * /param sbi superblock for filesystem readahead state ll_ra_info
69  * /param ria per-thread readahead state
70  * /param pages number of pages requested for readahead for the thread.
71  *
72  * WARNING: This algorithm is used to reduce contention on sbi->ll_lock.
73  * It should work well if the ra_max_pages is much greater than the single
74  * file's read-ahead window, and not too many threads contending for
75  * these readahead pages.
76  *
77  * TODO: There may be a 'global sync problem' if many threads are trying
78  * to get an ra budget that is larger than the remaining readahead pages
79  * and reach here at exactly the same time. They will compute /a ret to
80  * consume the remaining pages, but will fail at atomic_add_return() and
81  * get a zero ra window, although there is still ra space remaining. - Jay */
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         ENTRY;
91
92         /* If read-ahead pages left are less than 1M, do not do read-ahead,
93          * otherwise it will form small read RPC(< 1M), which hurt server
94          * performance a lot. */
95         ret = min(ra->ra_max_pages - atomic_read(&ra->ra_cur_pages),
96                   pages);
97         if (ret < 0 || ret < min_t(long, PTLRPC_MAX_BRW_PAGES, pages))
98                 GOTO(out, ret = 0);
99
100         if (atomic_add_return(ret, &ra->ra_cur_pages) > ra->ra_max_pages) {
101                 atomic_sub(ret, &ra->ra_cur_pages);
102                 ret = 0;
103         }
104
105 out:
106         if (ret < pages_min) {
107                 /* override ra limit for maximum performance */
108                 atomic_add(pages_min - ret, &ra->ra_cur_pages);
109                 ret = pages_min;
110         }
111         RETURN(ret);
112 }
113
114 void ll_ra_count_put(struct ll_sb_info *sbi, unsigned long pages)
115 {
116         struct ll_ra_info *ra = &sbi->ll_ra_info;
117         atomic_sub(pages, &ra->ra_cur_pages);
118 }
119
120 static void ll_ra_stats_inc_sbi(struct ll_sb_info *sbi, enum ra_stat which)
121 {
122         LASSERTF(which < _NR_RA_STAT, "which: %u\n", which);
123         lprocfs_counter_incr(sbi->ll_ra_stats, which);
124 }
125
126 static inline bool ll_readahead_enabled(struct ll_sb_info *sbi)
127 {
128         return sbi->ll_ra_info.ra_max_pages_per_file > 0 &&
129                 sbi->ll_ra_info.ra_max_pages > 0;
130 }
131
132 void ll_ra_stats_inc(struct inode *inode, enum ra_stat which)
133 {
134         struct ll_sb_info *sbi = ll_i2sbi(inode);
135         ll_ra_stats_inc_sbi(sbi, which);
136 }
137
138 #define RAS_CDEBUG(ras) \
139         CDEBUG(D_READA,                                                      \
140                "lre %llu cr %lu cb %llu wsi %lu wp %lu nra %lu rpc %lu "     \
141                "r %lu csr %lu so %llu sb %llu sl %llu lr %lu\n",             \
142                ras->ras_last_read_end_bytes, ras->ras_consecutive_requests,  \
143                ras->ras_consecutive_bytes, ras->ras_window_start_idx,        \
144                ras->ras_window_pages, ras->ras_next_readahead_idx,           \
145                ras->ras_rpc_pages, ras->ras_requests,                        \
146                ras->ras_consecutive_stride_requests, ras->ras_stride_offset, \
147                ras->ras_stride_bytes, ras->ras_stride_length,                \
148                ras->ras_async_last_readpage_idx)
149
150 static bool pos_in_window(loff_t pos, loff_t point,
151                           unsigned long before, unsigned long after)
152 {
153         loff_t start = point - before;
154         loff_t end = point + after;
155
156         if (start > point)
157                 start = 0;
158         if (end < point)
159                 end = ~0;
160
161         return start <= pos && pos <= end;
162 }
163
164 enum ll_ra_page_hint {
165         MAYNEED = 0, /* this page possibly accessed soon */
166         WILLNEED /* this page is gurateed to be needed */
167 };
168
169 /**
170  * Initiates read-ahead of a page with given index.
171  *
172  * \retval +ve: page was already uptodate so it will be skipped
173  *              from being added;
174  * \retval -ve: page wasn't added to \a queue for error;
175  * \retval   0: page was added into \a queue for read ahead.
176  */
177 static int ll_read_ahead_page(const struct lu_env *env, struct cl_io *io,
178                               struct cl_page_list *queue, pgoff_t index,
179                               enum ll_ra_page_hint hint)
180 {
181         struct cl_object *clob  = io->ci_obj;
182         struct inode     *inode = vvp_object_inode(clob);
183         struct page      *vmpage = NULL;
184         struct cl_page   *page;
185         struct vvp_page  *vpg;
186         enum ra_stat      which = _NR_RA_STAT; /* keep gcc happy */
187         int               rc    = 0;
188         const char       *msg   = NULL;
189
190         ENTRY;
191
192         switch (hint) {
193         case MAYNEED:
194                 vmpage = grab_cache_page_nowait(inode->i_mapping, index);
195                 if (vmpage == NULL) {
196                         which = RA_STAT_FAILED_GRAB_PAGE;
197                         msg   = "g_c_p_n failed";
198                         GOTO(out, rc = -EBUSY);
199                 }
200                 break;
201         case WILLNEED:
202                 vmpage = find_or_create_page(inode->i_mapping, index,
203                                              GFP_NOFS);
204                 if (vmpage == NULL)
205                         GOTO(out, rc = -ENOMEM);
206                 break;
207         default:
208                 /* should not come here */
209                 GOTO(out, rc = -EINVAL);
210         }
211  
212         /* Check if vmpage was truncated or reclaimed */
213         if (vmpage->mapping != inode->i_mapping) {
214                 which = RA_STAT_WRONG_GRAB_PAGE;
215                 msg   = "g_c_p_n returned invalid page";
216                 GOTO(out, rc = -EBUSY);
217         }
218
219         page = cl_page_find(env, clob, vmpage->index, vmpage, CPT_CACHEABLE);
220         if (IS_ERR(page)) {
221                 which = RA_STAT_FAILED_GRAB_PAGE;
222                 msg   = "cl_page_find failed";
223                 GOTO(out, rc = PTR_ERR(page));
224         }
225
226         lu_ref_add(&page->cp_reference, "ra", current);
227         cl_page_assume(env, io, page);
228         vpg = cl2vvp_page(cl_object_page_slice(clob, page));
229         if (!vpg->vpg_defer_uptodate && !PageUptodate(vmpage)) {
230                 vpg->vpg_defer_uptodate = 1;
231                 vpg->vpg_ra_used = 0;
232                 cl_page_list_add(queue, page);
233         } else {
234                 /* skip completed pages */
235                 cl_page_unassume(env, io, page);
236                 /* This page is already uptodate, returning a positive number
237                  * to tell the callers about this */
238                 rc = 1;
239         }
240
241         lu_ref_del(&page->cp_reference, "ra", current);
242         cl_page_put(env, page);
243
244 out:
245         if (vmpage != NULL) {
246                 if (rc != 0)
247                         unlock_page(vmpage);
248                 put_page(vmpage);
249         }
250         if (msg != NULL && hint == MAYNEED) {
251                 ll_ra_stats_inc(inode, which);
252                 CDEBUG(D_READA, "%s\n", msg);
253
254         }
255
256         RETURN(rc);
257 }
258
259 #define RIA_DEBUG(ria)                                                  \
260         CDEBUG(D_READA, "rs %lu re %lu ro %llu rl %llu rb %llu\n",      \
261                ria->ria_start_idx, ria->ria_end_idx, ria->ria_stoff,    \
262                ria->ria_length, ria->ria_bytes)
263
264 static inline int stride_io_mode(struct ll_readahead_state *ras)
265 {
266         return ras->ras_consecutive_stride_requests > 1;
267 }
268
269 /* The function calculates how many bytes will be read in
270  * [off, off + length], in such stride IO area,
271  * stride_offset = st_off, stride_lengh = st_len,
272  * stride_bytes = st_bytes
273  *
274  *   |------------------|*****|------------------|*****|------------|*****|....
275  * st_off
276  *   |--- st_bytes     ---|
277  *   |-----     st_len   -----|
278  *
279  *              How many bytes it should read in such pattern
280  *              |-------------------------------------------------------------|
281  *              off
282  *              |<------                  length                      ------->|
283  *
284  *          =   |<----->|  +  |-------------------------------------| +   |---|
285  *             start_left                 st_bytes * i                 end_left
286  */
287 static loff_t stride_byte_count(loff_t st_off, loff_t st_len, loff_t st_bytes,
288                                 loff_t off, loff_t length)
289 {
290         u64 start = off > st_off ? off - st_off : 0;
291         u64 end = off + length > st_off ? off + length - st_off : 0;
292         u64 start_left;
293         u64 end_left;
294         u64 bytes_count;
295
296         if (st_len == 0 || length == 0 || end == 0)
297                 return length;
298
299         start = div64_u64_rem(start, st_len, &start_left);
300         if (start_left < st_bytes)
301                 start_left = st_bytes - start_left;
302         else
303                 start_left = 0;
304
305         end = div64_u64_rem(end, st_len, &end_left);
306         if (end_left > st_bytes)
307                 end_left = st_bytes;
308
309         CDEBUG(D_READA, "start %llu, end %llu start_left %llu end_left %llu\n",
310                start, end, start_left, end_left);
311
312         if (start == end)
313                 bytes_count = end_left - (st_bytes - start_left);
314         else
315                 bytes_count = start_left +
316                         st_bytes * (end - start - 1) + end_left;
317
318         CDEBUG(D_READA,
319                "st_off %llu, st_len %llu st_bytes %llu off %llu length %llu bytescount %llu\n",
320                st_off, st_len, st_bytes, off, length, bytes_count);
321
322         return bytes_count;
323 }
324
325 static unsigned long ria_page_count(struct ra_io_arg *ria)
326 {
327         loff_t length_bytes = ria->ria_end_idx >= ria->ria_start_idx ?
328                 (loff_t)(ria->ria_end_idx -
329                          ria->ria_start_idx + 1) << PAGE_SHIFT : 0;
330         loff_t bytes_count;
331
332         if (ria->ria_length > ria->ria_bytes && ria->ria_bytes &&
333             (ria->ria_length & ~PAGE_MASK || ria->ria_bytes & ~PAGE_MASK ||
334              ria->ria_stoff & ~PAGE_MASK)) {
335                 /* Over-estimate un-aligned page stride read */
336                 unsigned long pg_count = ((ria->ria_bytes +
337                                            PAGE_SIZE - 1) >> PAGE_SHIFT) + 1;
338                 pg_count *= length_bytes / ria->ria_length + 1;
339
340                 return pg_count;
341         }
342         bytes_count = stride_byte_count(ria->ria_stoff, ria->ria_length,
343                                         ria->ria_bytes,
344                                         (loff_t)ria->ria_start_idx<<PAGE_SHIFT,
345                                         length_bytes);
346         return (bytes_count + PAGE_SIZE - 1) >> PAGE_SHIFT;
347 }
348
349 static pgoff_t ras_align(struct ll_readahead_state *ras, pgoff_t index)
350 {
351         return index - (index % ras->ras_rpc_pages);
352 }
353
354 /* Check whether the index is in the defined ra-window */
355 static bool ras_inside_ra_window(pgoff_t idx, struct ra_io_arg *ria)
356 {
357         loff_t pos = (loff_t)idx << PAGE_SHIFT;
358
359         /* If ria_length == ria_bytes, it means non-stride I/O mode,
360          * idx should always inside read-ahead window in this case
361          * For stride I/O mode, just check whether the idx is inside
362          * the ria_bytes.
363          */
364         if (ria->ria_length == 0 || ria->ria_length == ria->ria_bytes)
365                 return true;
366
367         if (pos >= ria->ria_stoff) {
368                 u64 offset;
369
370                 div64_u64_rem(pos - ria->ria_stoff, ria->ria_length, &offset);
371
372                 if (offset < ria->ria_bytes ||
373                     (ria->ria_length - offset) < PAGE_SIZE)
374                         return true;
375         } else if (pos + PAGE_SIZE > ria->ria_stoff) {
376                 return true;
377         }
378
379         return false;
380 }
381
382 static unsigned long
383 ll_read_ahead_pages(const struct lu_env *env, struct cl_io *io,
384                     struct cl_page_list *queue, struct ll_readahead_state *ras,
385                     struct ra_io_arg *ria, pgoff_t *ra_end)
386 {
387         struct cl_read_ahead ra = { 0 };
388         /* busy page count is per stride */
389         int rc = 0, count = 0, busy_page_count = 0;
390         pgoff_t page_idx;
391
392         LASSERT(ria != NULL);
393         RIA_DEBUG(ria);
394
395         for (page_idx = ria->ria_start_idx;
396              page_idx <= ria->ria_end_idx && ria->ria_reserved > 0;
397              page_idx++) {
398                 if (ras_inside_ra_window(page_idx, ria)) {
399                         if (ra.cra_end_idx == 0 || ra.cra_end_idx < page_idx) {
400                                 pgoff_t end_idx;
401
402                                 /*
403                                  * Do not shrink ria_end_idx at any case until
404                                  * the minimum end of current read is covered.
405                                  *
406                                  * Do not extend read lock accross stripe if
407                                  * lock contention detected.
408                                  */
409                                 if (ra.cra_contention &&
410                                     page_idx > ria->ria_end_idx_min) {
411                                         ria->ria_end_idx = *ra_end;
412                                         break;
413                                 }
414
415                                 cl_read_ahead_release(env, &ra);
416
417                                 rc = cl_io_read_ahead(env, io, page_idx, &ra);
418                                 if (rc < 0)
419                                         break;
420
421                                  /*
422                                   * Only shrink ria_end_idx if the matched
423                                   * LDLM lock doesn't cover more.
424                                   */
425                                 if (page_idx > ra.cra_end_idx) {
426                                         ria->ria_end_idx = ra.cra_end_idx;
427                                         break;
428                                 }
429
430                                 CDEBUG(D_READA, "idx: %lu, ra: %lu, rpc: %lu\n",
431                                        page_idx, ra.cra_end_idx,
432                                        ra.cra_rpc_pages);
433                                 LASSERTF(ra.cra_end_idx >= page_idx,
434                                          "object: %p, indcies %lu / %lu\n",
435                                          io->ci_obj, ra.cra_end_idx, page_idx);
436                                 /* update read ahead RPC size.
437                                  * NB: it's racy but doesn't matter */
438                                 if (ras->ras_rpc_pages != ra.cra_rpc_pages &&
439                                     ra.cra_rpc_pages > 0)
440                                         ras->ras_rpc_pages = ra.cra_rpc_pages;
441                                 /* trim it to align with optimal RPC size */
442                                 end_idx = ras_align(ras, ria->ria_end_idx + 1);
443                                 if (end_idx > 0 && !ria->ria_eof)
444                                         ria->ria_end_idx = end_idx - 1;
445                                 if (ria->ria_end_idx < ria->ria_end_idx_min)
446                                         ria->ria_end_idx = ria->ria_end_idx_min;
447                         }
448                         if (page_idx > ria->ria_end_idx)
449                                 break;
450
451                         /* If the page is inside the read-ahead window */
452                         rc = ll_read_ahead_page(env, io, queue, page_idx,
453                                                 MAYNEED);
454                         if (rc < 0 && rc != -EBUSY)
455                                 break;
456                         if (rc == -EBUSY) {
457                                 busy_page_count++;
458                                 CDEBUG(D_READA,
459                                        "skip busy page: %lu\n", page_idx);
460                                 /* For page unaligned readahead the first
461                                  * last pages of each region can be read by
462                                  * another reader on the same node, and so
463                                  * may be busy. So only stop for > 2 busy
464                                  * pages. */
465                                 if (busy_page_count > 2)
466                                         break;
467                         }
468
469                         *ra_end = page_idx;
470                         /* Only subtract from reserve & count the page if we
471                          * really did readahead on that page. */
472                         if (rc == 0) {
473                                 ria->ria_reserved--;
474                                 count++;
475                         }
476                 } else if (stride_io_mode(ras)) {
477                         /* If it is not in the read-ahead window, and it is
478                          * read-ahead mode, then check whether it should skip
479                          * the stride gap.
480                          */
481                         loff_t pos = (loff_t)page_idx << PAGE_SHIFT;
482                         u64 offset;
483
484                         div64_u64_rem(pos - ria->ria_stoff, ria->ria_length,
485                                       &offset);
486                         if (offset >= ria->ria_bytes) {
487                                 pos += (ria->ria_length - offset);
488                                 if ((pos >> PAGE_SHIFT) >= page_idx + 1)
489                                         page_idx = (pos >> PAGE_SHIFT) - 1;
490                                 busy_page_count = 0;
491                                 CDEBUG(D_READA,
492                                        "Stride: jump %llu pages to %lu\n",
493                                        ria->ria_length - offset, page_idx);
494                                 continue;
495                         }
496                 }
497         }
498
499         cl_read_ahead_release(env, &ra);
500
501         return count;
502 }
503
504 static void ll_readahead_work_free(struct ll_readahead_work *work)
505 {
506         fput(work->lrw_file);
507         OBD_FREE_PTR(work);
508 }
509
510 static void ll_readahead_handle_work(struct work_struct *wq);
511 static void ll_readahead_work_add(struct inode *inode,
512                                   struct ll_readahead_work *work)
513 {
514         INIT_WORK(&work->lrw_readahead_work, ll_readahead_handle_work);
515         queue_work(ll_i2sbi(inode)->ll_ra_info.ll_readahead_wq,
516                    &work->lrw_readahead_work);
517 }
518
519 static int ll_readahead_file_kms(const struct lu_env *env,
520                                 struct cl_io *io, __u64 *kms)
521 {
522         struct cl_object *clob;
523         struct inode *inode;
524         struct cl_attr *attr = vvp_env_thread_attr(env);
525         int ret;
526
527         clob = io->ci_obj;
528         inode = vvp_object_inode(clob);
529
530         cl_object_attr_lock(clob);
531         ret = cl_object_attr_get(env, clob, attr);
532         cl_object_attr_unlock(clob);
533
534         if (ret != 0)
535                 RETURN(ret);
536
537         *kms = attr->cat_kms;
538         return 0;
539 }
540
541 static void ll_readahead_handle_work(struct work_struct *wq)
542 {
543         struct ll_readahead_work *work;
544         struct lu_env *env;
545         __u16 refcheck;
546         struct ra_io_arg *ria;
547         struct inode *inode;
548         struct ll_file_data *fd;
549         struct ll_readahead_state *ras;
550         struct cl_io *io;
551         struct cl_2queue *queue;
552         pgoff_t ra_end_idx = 0;
553         unsigned long pages, pages_min = 0;
554         struct file *file;
555         __u64 kms;
556         int rc;
557         pgoff_t eof_index;
558         struct ll_sb_info *sbi;
559
560         work = container_of(wq, struct ll_readahead_work,
561                             lrw_readahead_work);
562         fd = work->lrw_file->private_data;
563         ras = &fd->fd_ras;
564         file = work->lrw_file;
565         inode = file_inode(file);
566         sbi = ll_i2sbi(inode);
567
568         env = cl_env_alloc(&refcheck, LCT_NOREF);
569         if (IS_ERR(env))
570                 GOTO(out_free_work, rc = PTR_ERR(env));
571
572         io = vvp_env_thread_io(env);
573         ll_io_init(io, file, CIT_READ, NULL);
574
575         rc = ll_readahead_file_kms(env, io, &kms);
576         if (rc != 0)
577                 GOTO(out_put_env, rc);
578
579         if (kms == 0) {
580                 ll_ra_stats_inc(inode, RA_STAT_ZERO_LEN);
581                 GOTO(out_put_env, rc = 0);
582         }
583
584         ria = &ll_env_info(env)->lti_ria;
585         memset(ria, 0, sizeof(*ria));
586
587         ria->ria_start_idx = work->lrw_start_idx;
588         /* Truncate RA window to end of file */
589         eof_index = (pgoff_t)(kms - 1) >> PAGE_SHIFT;
590         if (eof_index <= work->lrw_end_idx) {
591                 work->lrw_end_idx = eof_index;
592                 ria->ria_eof = true;
593         }
594         if (work->lrw_end_idx <= work->lrw_start_idx)
595                 GOTO(out_put_env, rc = 0);
596
597         ria->ria_end_idx = work->lrw_end_idx;
598         pages = ria->ria_end_idx - ria->ria_start_idx + 1;
599         ria->ria_reserved = ll_ra_count_get(sbi, ria,
600                                             ria_page_count(ria), pages_min);
601
602         CDEBUG(D_READA,
603                "async reserved pages: %lu/%lu/%lu, ra_cur %d, ra_max %lu\n",
604                ria->ria_reserved, pages, pages_min,
605                atomic_read(&ll_i2sbi(inode)->ll_ra_info.ra_cur_pages),
606                ll_i2sbi(inode)->ll_ra_info.ra_max_pages);
607
608         if (ria->ria_reserved < pages) {
609                 ll_ra_stats_inc(inode, RA_STAT_MAX_IN_FLIGHT);
610                 if (PAGES_TO_MiB(ria->ria_reserved) < 1) {
611                         ll_ra_count_put(ll_i2sbi(inode), ria->ria_reserved);
612                         GOTO(out_put_env, rc = 0);
613                 }
614         }
615
616         rc = cl_io_rw_init(env, io, CIT_READ, ria->ria_start_idx, pages);
617         if (rc)
618                 GOTO(out_put_env, rc);
619
620         vvp_env_io(env)->vui_io_subtype = IO_NORMAL;
621         vvp_env_io(env)->vui_fd = fd;
622         io->ci_state = CIS_LOCKED;
623         io->ci_async_readahead = true;
624         rc = cl_io_start(env, io);
625         if (rc)
626                 GOTO(out_io_fini, rc);
627
628         queue = &io->ci_queue;
629         cl_2queue_init(queue);
630
631         rc = ll_read_ahead_pages(env, io, &queue->c2_qin, ras, ria,
632                                  &ra_end_idx);
633         if (ria->ria_reserved != 0)
634                 ll_ra_count_put(ll_i2sbi(inode), ria->ria_reserved);
635         if (queue->c2_qin.pl_nr > 0) {
636                 int count = queue->c2_qin.pl_nr;
637
638                 rc = cl_io_submit_rw(env, io, CRT_READ, queue);
639                 if (rc == 0)
640                         task_io_account_read(PAGE_SIZE * count);
641         }
642         if (ria->ria_end_idx == ra_end_idx && ra_end_idx == (kms >> PAGE_SHIFT))
643                 ll_ra_stats_inc(inode, RA_STAT_EOF);
644
645         if (ra_end_idx != ria->ria_end_idx)
646                 ll_ra_stats_inc(inode, RA_STAT_FAILED_REACH_END);
647
648         /* TODO: discard all pages until page reinit route is implemented */
649         cl_page_list_discard(env, io, &queue->c2_qin);
650
651         /* Unlock unsent read pages in case of error. */
652         cl_page_list_disown(env, io, &queue->c2_qin);
653
654         cl_2queue_fini(env, queue);
655 out_io_fini:
656         cl_io_end(env, io);
657         cl_io_fini(env, io);
658 out_put_env:
659         cl_env_put(env, &refcheck);
660 out_free_work:
661         if (ra_end_idx > 0)
662                 ll_ra_stats_inc_sbi(ll_i2sbi(inode), RA_STAT_ASYNC);
663         atomic_dec(&sbi->ll_ra_info.ra_async_inflight);
664         ll_readahead_work_free(work);
665 }
666
667 static int ll_readahead(const struct lu_env *env, struct cl_io *io,
668                         struct cl_page_list *queue,
669                         struct ll_readahead_state *ras, bool hit,
670                         struct file *file)
671 {
672         struct vvp_io *vio = vvp_env_io(env);
673         struct ll_thread_info *lti = ll_env_info(env);
674         unsigned long pages, pages_min = 0;
675         pgoff_t ra_end_idx = 0, start_idx = 0, end_idx = 0;
676         struct inode *inode;
677         struct ra_io_arg *ria = &lti->lti_ria;
678         struct cl_object *clob;
679         int ret = 0;
680         __u64 kms;
681         ENTRY;
682
683         clob = io->ci_obj;
684         inode = vvp_object_inode(clob);
685
686         memset(ria, 0, sizeof(*ria));
687         ret = ll_readahead_file_kms(env, io, &kms);
688         if (ret != 0)
689                 RETURN(ret);
690
691         if (kms == 0) {
692                 ll_ra_stats_inc(inode, RA_STAT_ZERO_LEN);
693                 RETURN(0);
694         }
695
696         spin_lock(&ras->ras_lock);
697
698         /**
699          * Note: other thread might rollback the ras_next_readahead_idx,
700          * if it can not get the full size of prepared pages, see the
701          * end of this function. For stride read ahead, it needs to
702          * make sure the offset is no less than ras_stride_offset,
703          * so that stride read ahead can work correctly.
704          */
705         if (stride_io_mode(ras))
706                 start_idx = max_t(pgoff_t, ras->ras_next_readahead_idx,
707                                   ras->ras_stride_offset >> PAGE_SHIFT);
708         else
709                 start_idx = ras->ras_next_readahead_idx;
710
711         if (ras->ras_window_pages > 0)
712                 end_idx = ras->ras_window_start_idx + ras->ras_window_pages - 1;
713
714         /* Enlarge the RA window to encompass the full read */
715         if (vio->vui_ra_valid &&
716             end_idx < vio->vui_ra_start_idx + vio->vui_ra_pages - 1)
717                 end_idx = vio->vui_ra_start_idx + vio->vui_ra_pages - 1;
718
719         if (end_idx != 0) {
720                 pgoff_t eof_index;
721
722                 /* Truncate RA window to end of file */
723                 eof_index = (pgoff_t)((kms - 1) >> PAGE_SHIFT);
724                 if (eof_index <= end_idx) {
725                         end_idx = eof_index;
726                         ria->ria_eof = true;
727                 }
728         }
729         ria->ria_start_idx = start_idx;
730         ria->ria_end_idx = end_idx;
731         /* If stride I/O mode is detected, get stride window*/
732         if (stride_io_mode(ras)) {
733                 ria->ria_stoff = ras->ras_stride_offset;
734                 ria->ria_length = ras->ras_stride_length;
735                 ria->ria_bytes = ras->ras_stride_bytes;
736         }
737         spin_unlock(&ras->ras_lock);
738
739         if (end_idx == 0) {
740                 ll_ra_stats_inc(inode, RA_STAT_ZERO_WINDOW);
741                 RETURN(0);
742         }
743         pages = ria_page_count(ria);
744         if (pages == 0) {
745                 ll_ra_stats_inc(inode, RA_STAT_ZERO_WINDOW);
746                 RETURN(0);
747         }
748
749         RAS_CDEBUG(ras);
750         CDEBUG(D_READA, DFID": ria: %lu/%lu, bead: %lu/%lu, hit: %d\n",
751                PFID(lu_object_fid(&clob->co_lu)),
752                ria->ria_start_idx, ria->ria_end_idx,
753                vio->vui_ra_valid ? vio->vui_ra_start_idx : 0,
754                vio->vui_ra_valid ? vio->vui_ra_pages : 0,
755                hit);
756
757         /* at least to extend the readahead window to cover current read */
758         if (!hit && vio->vui_ra_valid &&
759             vio->vui_ra_start_idx + vio->vui_ra_pages > ria->ria_start_idx) {
760                 ria->ria_end_idx_min =
761                         vio->vui_ra_start_idx + vio->vui_ra_pages - 1;
762                 pages_min = vio->vui_ra_start_idx + vio->vui_ra_pages -
763                                 ria->ria_start_idx;
764         }
765
766         ria->ria_reserved = ll_ra_count_get(ll_i2sbi(inode), ria, pages,
767                                             pages_min);
768         if (ria->ria_reserved < pages)
769                 ll_ra_stats_inc(inode, RA_STAT_MAX_IN_FLIGHT);
770
771         CDEBUG(D_READA, "reserved pages: %lu/%lu/%lu, ra_cur %d, ra_max %lu\n",
772                ria->ria_reserved, pages, pages_min,
773                atomic_read(&ll_i2sbi(inode)->ll_ra_info.ra_cur_pages),
774                ll_i2sbi(inode)->ll_ra_info.ra_max_pages);
775
776         ret = ll_read_ahead_pages(env, io, queue, ras, ria, &ra_end_idx);
777
778         if (ria->ria_reserved != 0)
779                 ll_ra_count_put(ll_i2sbi(inode), ria->ria_reserved);
780
781         if (ra_end_idx == end_idx && ra_end_idx == (kms >> PAGE_SHIFT))
782                 ll_ra_stats_inc(inode, RA_STAT_EOF);
783
784         CDEBUG(D_READA,
785                "ra_end_idx = %lu end_idx = %lu stride end = %lu pages = %d\n",
786                ra_end_idx, end_idx, ria->ria_end_idx, ret);
787
788         if (ra_end_idx != end_idx)
789                 ll_ra_stats_inc(inode, RA_STAT_FAILED_REACH_END);
790         if (ra_end_idx > 0) {
791                 /* update the ras so that the next read-ahead tries from
792                  * where we left off. */
793                 spin_lock(&ras->ras_lock);
794                 ras->ras_next_readahead_idx = ra_end_idx + 1;
795                 spin_unlock(&ras->ras_lock);
796                 RAS_CDEBUG(ras);
797         }
798
799         RETURN(ret);
800 }
801
802 static int ll_readpages(const struct lu_env *env, struct cl_io *io,
803                         struct cl_page_list *queue,
804                         pgoff_t start, pgoff_t end)
805 {
806         int ret = 0;
807         __u64 kms;
808         pgoff_t page_idx;
809         int count = 0;
810
811         ENTRY;
812
813         ret = ll_readahead_file_kms(env, io, &kms);
814         if (ret != 0)
815                 RETURN(ret);
816
817         if (kms == 0)
818                 RETURN(0);
819
820         if (end != 0) {
821                 unsigned long end_index;
822
823                 end_index = (unsigned long)((kms - 1) >> PAGE_SHIFT);
824                 if (end_index <= end)
825                         end = end_index;
826         }
827
828         for (page_idx = start; page_idx <= end; page_idx++) {
829                 ret= ll_read_ahead_page(env, io, queue, page_idx,
830                                         WILLNEED);
831                 if (ret < 0)
832                         break;
833                 else if (ret == 0) /* ret 1 is already uptodate */
834                         count++;
835         }
836
837         RETURN(count > 0 ? count : ret);
838 }
839
840 static void ras_set_start(struct ll_readahead_state *ras, pgoff_t index)
841 {
842         ras->ras_window_start_idx = ras_align(ras, index);
843 }
844
845 /* called with the ras_lock held or from places where it doesn't matter */
846 static void ras_reset(struct ll_readahead_state *ras, pgoff_t index)
847 {
848         ras->ras_consecutive_requests = 0;
849         ras->ras_consecutive_bytes = 0;
850         ras->ras_window_pages = 0;
851         ras_set_start(ras, index);
852         ras->ras_next_readahead_idx = max(ras->ras_window_start_idx, index + 1);
853
854         RAS_CDEBUG(ras);
855 }
856
857 /* called with the ras_lock held or from places where it doesn't matter */
858 static void ras_stride_reset(struct ll_readahead_state *ras)
859 {
860         ras->ras_consecutive_stride_requests = 0;
861         ras->ras_stride_length = 0;
862         ras->ras_stride_bytes = 0;
863         RAS_CDEBUG(ras);
864 }
865
866 void ll_readahead_init(struct inode *inode, struct ll_readahead_state *ras)
867 {
868         spin_lock_init(&ras->ras_lock);
869         ras->ras_rpc_pages = PTLRPC_MAX_BRW_PAGES;
870         ras_reset(ras, 0);
871         ras->ras_last_read_end_bytes = 0;
872         ras->ras_requests = 0;
873 }
874
875 /*
876  * Check whether the read request is in the stride window.
877  * If it is in the stride window, return true, otherwise return false.
878  */
879 static bool read_in_stride_window(struct ll_readahead_state *ras,
880                                   loff_t pos, loff_t count)
881 {
882         loff_t stride_gap;
883
884         if (ras->ras_stride_length == 0 || ras->ras_stride_bytes == 0 ||
885             ras->ras_stride_bytes == ras->ras_stride_length)
886                 return false;
887
888         stride_gap = pos - ras->ras_last_read_end_bytes - 1;
889
890         /* If it is contiguous read */
891         if (stride_gap == 0)
892                 return ras->ras_consecutive_bytes + count <=
893                         ras->ras_stride_bytes;
894
895         /* Otherwise check the stride by itself */
896         return (ras->ras_stride_length - ras->ras_stride_bytes) == stride_gap &&
897                 ras->ras_consecutive_bytes == ras->ras_stride_bytes &&
898                 count <= ras->ras_stride_bytes;
899 }
900
901 static void ras_init_stride_detector(struct ll_readahead_state *ras,
902                                      loff_t pos, loff_t count)
903 {
904         loff_t stride_gap = pos - ras->ras_last_read_end_bytes - 1;
905
906         LASSERT(ras->ras_consecutive_stride_requests == 0);
907
908         if (pos <= ras->ras_last_read_end_bytes) {
909                 /*Reset stride window for forward read*/
910                 ras_stride_reset(ras);
911                 return;
912         }
913
914         ras->ras_stride_bytes = ras->ras_consecutive_bytes;
915         ras->ras_stride_length = stride_gap + ras->ras_consecutive_bytes;
916         ras->ras_consecutive_stride_requests++;
917         ras->ras_stride_offset = pos;
918
919         RAS_CDEBUG(ras);
920 }
921
922 static unsigned long
923 stride_page_count(struct ll_readahead_state *ras, loff_t len)
924 {
925         loff_t bytes_count =
926                 stride_byte_count(ras->ras_stride_offset,
927                                   ras->ras_stride_length, ras->ras_stride_bytes,
928                                   ras->ras_window_start_idx << PAGE_SHIFT, len);
929
930         return (bytes_count + PAGE_SIZE - 1) >> PAGE_SHIFT;
931 }
932
933 /* Stride Read-ahead window will be increased inc_len according to
934  * stride I/O pattern */
935 static void ras_stride_increase_window(struct ll_readahead_state *ras,
936                                        struct ll_ra_info *ra, loff_t inc_bytes)
937 {
938         loff_t window_bytes, stride_bytes;
939         u64 left_bytes;
940         u64 step;
941         loff_t end;
942
943         /* temporarily store in page units to reduce LASSERT() cost below */
944         end = ras->ras_window_start_idx + ras->ras_window_pages;
945
946         LASSERT(ras->ras_stride_length > 0);
947         LASSERTF(end >= (ras->ras_stride_offset >> PAGE_SHIFT),
948                  "window_start_idx %lu, window_pages %lu stride_offset %llu\n",
949                  ras->ras_window_start_idx, ras->ras_window_pages,
950                  ras->ras_stride_offset);
951
952         end <<= PAGE_SHIFT;
953         if (end <= ras->ras_stride_offset)
954                 stride_bytes = 0;
955         else
956                 stride_bytes = end - ras->ras_stride_offset;
957
958         div64_u64_rem(stride_bytes, ras->ras_stride_length, &left_bytes);
959         window_bytes = (ras->ras_window_pages << PAGE_SHIFT);
960         if (left_bytes < ras->ras_stride_bytes) {
961                 if (ras->ras_stride_bytes - left_bytes >= inc_bytes) {
962                         window_bytes += inc_bytes;
963                         goto out;
964                 } else {
965                         window_bytes += (ras->ras_stride_bytes - left_bytes);
966                         inc_bytes -= (ras->ras_stride_bytes - left_bytes);
967                 }
968         } else {
969                 window_bytes += (ras->ras_stride_length - left_bytes);
970         }
971
972         LASSERT(ras->ras_stride_bytes != 0);
973
974         step = div64_u64_rem(inc_bytes, ras->ras_stride_bytes, &left_bytes);
975
976         window_bytes += step * ras->ras_stride_length + left_bytes;
977         LASSERT(window_bytes > 0);
978
979 out:
980         if (stride_page_count(ras, window_bytes) <=
981             ra->ra_max_pages_per_file || ras->ras_window_pages == 0)
982                 ras->ras_window_pages = (window_bytes >> PAGE_SHIFT);
983
984         LASSERT(ras->ras_window_pages > 0);
985
986         RAS_CDEBUG(ras);
987 }
988
989 static void ras_increase_window(struct inode *inode,
990                                 struct ll_readahead_state *ras,
991                                 struct ll_ra_info *ra)
992 {
993         /* The stretch of ra-window should be aligned with max rpc_size
994          * but current clio architecture does not support retrieve such
995          * information from lower layer. FIXME later
996          */
997         if (stride_io_mode(ras)) {
998                 ras_stride_increase_window(ras, ra,
999                                       (loff_t)ras->ras_rpc_pages << PAGE_SHIFT);
1000         } else {
1001                 pgoff_t window_pages;
1002
1003                 window_pages = min(ras->ras_window_pages + ras->ras_rpc_pages,
1004                                    ra->ra_max_pages_per_file);
1005                 if (window_pages < ras->ras_rpc_pages)
1006                         ras->ras_window_pages = window_pages;
1007                 else
1008                         ras->ras_window_pages = ras_align(ras, window_pages);
1009         }
1010 }
1011
1012 /**
1013  * Seek within 8 pages are considered as sequential read for now.
1014  */
1015 static inline bool is_loose_seq_read(struct ll_readahead_state *ras, loff_t pos)
1016 {
1017         return pos_in_window(pos, ras->ras_last_read_end_bytes,
1018                              8UL << PAGE_SHIFT, 8UL << PAGE_SHIFT);
1019 }
1020
1021 static void ras_detect_read_pattern(struct ll_readahead_state *ras,
1022                                     struct ll_sb_info *sbi,
1023                                     loff_t pos, size_t count, bool mmap)
1024 {
1025         bool stride_detect = false;
1026         pgoff_t index = pos >> PAGE_SHIFT;
1027
1028         /*
1029          * Reset the read-ahead window in two cases. First when the app seeks
1030          * or reads to some other part of the file. Secondly if we get a
1031          * read-ahead miss that we think we've previously issued. This can
1032          * be a symptom of there being so many read-ahead pages that the VM
1033          * is reclaiming it before we get to it.
1034          */
1035         if (!is_loose_seq_read(ras, pos)) {
1036                 /* Check whether it is in stride I/O mode */
1037                 if (!read_in_stride_window(ras, pos, count)) {
1038                         if (ras->ras_consecutive_stride_requests == 0)
1039                                 ras_init_stride_detector(ras, pos, count);
1040                         else
1041                                 ras_stride_reset(ras);
1042                         ras->ras_consecutive_bytes = 0;
1043                         ras_reset(ras, index);
1044                 } else {
1045                         ras->ras_consecutive_bytes = 0;
1046                         ras->ras_consecutive_requests = 0;
1047                         if (++ras->ras_consecutive_stride_requests > 1)
1048                                 stride_detect = true;
1049                         RAS_CDEBUG(ras);
1050                 }
1051                 ll_ra_stats_inc_sbi(sbi, RA_STAT_DISTANT_READPAGE);
1052         } else if (stride_io_mode(ras)) {
1053                 /*
1054                  * If this is contiguous read but in stride I/O mode
1055                  * currently, check whether stride step still is valid,
1056                  * if invalid, it will reset the stride ra window to
1057                  * be zero.
1058                  */
1059                 if (!read_in_stride_window(ras, pos, count)) {
1060                         ras_stride_reset(ras);
1061                         ras->ras_window_pages = 0;
1062                         ras->ras_next_readahead_idx = index;
1063                 }
1064         }
1065
1066         ras->ras_consecutive_bytes += count;
1067         if (mmap) {
1068                 pgoff_t idx = ras->ras_consecutive_bytes >> PAGE_SHIFT;
1069
1070                 if ((idx >= 4 && (idx & 3UL) == 0) || stride_detect)
1071                         ras->ras_need_increase_window = true;
1072         } else if ((ras->ras_consecutive_requests > 1 || stride_detect)) {
1073                 ras->ras_need_increase_window = true;
1074         }
1075
1076         ras->ras_last_read_end_bytes = pos + count - 1;
1077 }
1078
1079 void ll_ras_enter(struct file *f, loff_t pos, size_t count)
1080 {
1081         struct ll_file_data *fd = f->private_data;
1082         struct ll_readahead_state *ras = &fd->fd_ras;
1083         struct inode *inode = file_inode(f);
1084         unsigned long index = pos >> PAGE_SHIFT;
1085         struct ll_sb_info *sbi = ll_i2sbi(inode);
1086
1087         spin_lock(&ras->ras_lock);
1088         ras->ras_requests++;
1089         ras->ras_consecutive_requests++;
1090         ras->ras_need_increase_window = false;
1091         ras->ras_no_miss_check = false;
1092         /*
1093          * On the second access to a file smaller than the tunable
1094          * ra_max_read_ahead_whole_pages trigger RA on all pages in the
1095          * file up to ra_max_pages_per_file.  This is simply a best effort
1096          * and only occurs once per open file. Normal RA behavior is reverted
1097          * to for subsequent IO.
1098          */
1099         if (ras->ras_requests >= 2) {
1100                 __u64 kms_pages;
1101                 struct ll_ra_info *ra = &sbi->ll_ra_info;
1102
1103                 kms_pages = (i_size_read(inode) + PAGE_SIZE - 1) >>
1104                             PAGE_SHIFT;
1105
1106                 CDEBUG(D_READA, "kmsp %llu mwp %lu mp %lu\n", kms_pages,
1107                        ra->ra_max_read_ahead_whole_pages,
1108                        ra->ra_max_pages_per_file);
1109
1110                 if (kms_pages &&
1111                     kms_pages <= ra->ra_max_read_ahead_whole_pages) {
1112                         ras->ras_window_start_idx = 0;
1113                         ras->ras_next_readahead_idx = index + 1;
1114                         ras->ras_window_pages = min(ra->ra_max_pages_per_file,
1115                                             ra->ra_max_read_ahead_whole_pages);
1116                         ras->ras_no_miss_check = true;
1117                         GOTO(out_unlock, 0);
1118                 }
1119         }
1120         ras_detect_read_pattern(ras, sbi, pos, count, false);
1121 out_unlock:
1122         spin_unlock(&ras->ras_lock);
1123 }
1124
1125 static bool index_in_stride_window(struct ll_readahead_state *ras,
1126                                    pgoff_t index)
1127 {
1128         loff_t pos = (loff_t)index << PAGE_SHIFT;
1129
1130         if (ras->ras_stride_length == 0 || ras->ras_stride_bytes == 0 ||
1131             ras->ras_stride_bytes == ras->ras_stride_length)
1132                 return false;
1133
1134         if (pos >= ras->ras_stride_offset) {
1135                 u64 offset;
1136
1137                 div64_u64_rem(pos - ras->ras_stride_offset,
1138                               ras->ras_stride_length, &offset);
1139                 if (offset < ras->ras_stride_bytes ||
1140                     ras->ras_stride_length - offset < PAGE_SIZE)
1141                         return true;
1142         } else if (ras->ras_stride_offset - pos < PAGE_SIZE) {
1143                 return true;
1144         }
1145
1146         return false;
1147 }
1148
1149 /*
1150  * ll_ras_enter() is used to detect read pattern according to pos and count.
1151  *
1152  * ras_update() is used to detect cache miss and
1153  * reset window or increase window accordingly
1154  */
1155 static void ras_update(struct ll_sb_info *sbi, struct inode *inode,
1156                        struct ll_readahead_state *ras, pgoff_t index,
1157                        enum ras_update_flags flags)
1158 {
1159         struct ll_ra_info *ra = &sbi->ll_ra_info;
1160         bool hit = flags & LL_RAS_HIT;
1161
1162         ENTRY;
1163         spin_lock(&ras->ras_lock);
1164
1165         if (!hit)
1166                 CDEBUG(D_READA, DFID " pages at %lu miss.\n",
1167                        PFID(ll_inode2fid(inode)), index);
1168         ll_ra_stats_inc_sbi(sbi, hit ? RA_STAT_HIT : RA_STAT_MISS);
1169
1170         /*
1171          * The readahead window has been expanded to cover whole
1172          * file size, we don't care whether ra miss happen or not.
1173          * Because we will read whole file to page cache even if
1174          * some pages missed.
1175          */
1176         if (ras->ras_no_miss_check)
1177                 GOTO(out_unlock, 0);
1178
1179         if (flags & LL_RAS_MMAP)
1180                 ras_detect_read_pattern(ras, sbi, (loff_t)index << PAGE_SHIFT,
1181                                         PAGE_SIZE, true);
1182
1183         if (!hit && ras->ras_window_pages &&
1184             index < ras->ras_next_readahead_idx &&
1185             pos_in_window(index, ras->ras_window_start_idx, 0,
1186                           ras->ras_window_pages)) {
1187                 ll_ra_stats_inc_sbi(sbi, RA_STAT_MISS_IN_WINDOW);
1188                 ras->ras_need_increase_window = false;
1189
1190                 if (index_in_stride_window(ras, index) &&
1191                     stride_io_mode(ras)) {
1192                         /*
1193                          * if (index != ras->ras_last_readpage + 1)
1194                          *      ras->ras_consecutive_pages = 0;
1195                          */
1196                         ras_reset(ras, index);
1197
1198                         /*
1199                          * If stride-RA hit cache miss, the stride
1200                          * detector will not be reset to avoid the
1201                          * overhead of redetecting read-ahead mode,
1202                          * but on the condition that the stride window
1203                          * is still intersect with normal sequential
1204                          * read-ahead window.
1205                          */
1206                         if (ras->ras_window_start_idx < ras->ras_stride_offset)
1207                                 ras_stride_reset(ras);
1208                         RAS_CDEBUG(ras);
1209                 } else {
1210                         /*
1211                          * Reset both stride window and normal RA
1212                          * window.
1213                          */
1214                         ras_reset(ras, index);
1215                         /* ras->ras_consecutive_pages++; */
1216                         ras->ras_consecutive_bytes = 0;
1217                         ras_stride_reset(ras);
1218                         GOTO(out_unlock, 0);
1219                 }
1220         }
1221         ras_set_start(ras, index);
1222
1223         if (stride_io_mode(ras)) {
1224                 /* Since stride readahead is sentivite to the offset
1225                  * of read-ahead, so we use original offset here,
1226                  * instead of ras_window_start_idx, which is RPC aligned.
1227                  */
1228                 ras->ras_next_readahead_idx = max(index + 1,
1229                                                   ras->ras_next_readahead_idx);
1230                 ras->ras_window_start_idx =
1231                                 max_t(pgoff_t, ras->ras_window_start_idx,
1232                                       ras->ras_stride_offset >> PAGE_SHIFT);
1233         } else {
1234                 if (ras->ras_next_readahead_idx < ras->ras_window_start_idx)
1235                         ras->ras_next_readahead_idx = ras->ras_window_start_idx;
1236                 if (!hit)
1237                         ras->ras_next_readahead_idx = index + 1;
1238         }
1239
1240         if (ras->ras_need_increase_window) {
1241                 ras_increase_window(inode, ras, ra);
1242                 ras->ras_need_increase_window = false;
1243         }
1244
1245         EXIT;
1246 out_unlock:
1247         spin_unlock(&ras->ras_lock);
1248 }
1249
1250 int ll_writepage(struct page *vmpage, struct writeback_control *wbc)
1251 {
1252         struct inode           *inode = vmpage->mapping->host;
1253         struct ll_inode_info   *lli   = ll_i2info(inode);
1254         struct lu_env          *env;
1255         struct cl_io           *io;
1256         struct cl_page         *page;
1257         struct cl_object       *clob;
1258         bool redirtied = false;
1259         bool unlocked = false;
1260         int result;
1261         __u16 refcheck;
1262         ENTRY;
1263
1264         LASSERT(PageLocked(vmpage));
1265         LASSERT(!PageWriteback(vmpage));
1266
1267         LASSERT(ll_i2dtexp(inode) != NULL);
1268
1269         env = cl_env_get(&refcheck);
1270         if (IS_ERR(env))
1271                 GOTO(out, result = PTR_ERR(env));
1272
1273         clob  = ll_i2info(inode)->lli_clob;
1274         LASSERT(clob != NULL);
1275
1276         io = vvp_env_thread_io(env);
1277         io->ci_obj = clob;
1278         io->ci_ignore_layout = 1;
1279         result = cl_io_init(env, io, CIT_MISC, clob);
1280         if (result == 0) {
1281                 page = cl_page_find(env, clob, vmpage->index,
1282                                     vmpage, CPT_CACHEABLE);
1283                 if (!IS_ERR(page)) {
1284                         lu_ref_add(&page->cp_reference, "writepage",
1285                                    current);
1286                         cl_page_assume(env, io, page);
1287                         result = cl_page_flush(env, io, page);
1288                         if (result != 0) {
1289                                 /*
1290                                  * Re-dirty page on error so it retries write,
1291                                  * but not in case when IO has actually
1292                                  * occurred and completed with an error.
1293                                  */
1294                                 if (!PageError(vmpage)) {
1295                                         redirty_page_for_writepage(wbc, vmpage);
1296                                         result = 0;
1297                                         redirtied = true;
1298                                 }
1299                         }
1300                         cl_page_disown(env, io, page);
1301                         unlocked = true;
1302                         lu_ref_del(&page->cp_reference,
1303                                    "writepage", current);
1304                         cl_page_put(env, page);
1305                 } else {
1306                         result = PTR_ERR(page);
1307                 }
1308         }
1309         cl_io_fini(env, io);
1310
1311         if (redirtied && wbc->sync_mode == WB_SYNC_ALL) {
1312                 loff_t offset = cl_offset(clob, vmpage->index);
1313
1314                 /* Flush page failed because the extent is being written out.
1315                  * Wait for the write of extent to be finished to avoid
1316                  * breaking kernel which assumes ->writepage should mark
1317                  * PageWriteback or clean the page. */
1318                 result = cl_sync_file_range(inode, offset,
1319                                             offset + PAGE_SIZE - 1,
1320                                             CL_FSYNC_LOCAL, 1);
1321                 if (result > 0) {
1322                         /* actually we may have written more than one page.
1323                          * decreasing this page because the caller will count
1324                          * it. */
1325                         wbc->nr_to_write -= result - 1;
1326                         result = 0;
1327                 }
1328         }
1329
1330         cl_env_put(env, &refcheck);
1331         GOTO(out, result);
1332
1333 out:
1334         if (result < 0) {
1335                 if (!lli->lli_async_rc)
1336                         lli->lli_async_rc = result;
1337                 SetPageError(vmpage);
1338                 if (!unlocked)
1339                         unlock_page(vmpage);
1340         }
1341         return result;
1342 }
1343
1344 int ll_writepages(struct address_space *mapping, struct writeback_control *wbc)
1345 {
1346         struct inode *inode = mapping->host;
1347         loff_t start;
1348         loff_t end;
1349         enum cl_fsync_mode mode;
1350         int range_whole = 0;
1351         int result;
1352         ENTRY;
1353
1354         if (wbc->range_cyclic) {
1355                 start = (loff_t)mapping->writeback_index << PAGE_SHIFT;
1356                 end = OBD_OBJECT_EOF;
1357         } else {
1358                 start = wbc->range_start;
1359                 end = wbc->range_end;
1360                 if (end == LLONG_MAX) {
1361                         end = OBD_OBJECT_EOF;
1362                         range_whole = start == 0;
1363                 }
1364         }
1365
1366         mode = CL_FSYNC_NONE;
1367         if (wbc->sync_mode == WB_SYNC_ALL)
1368                 mode = CL_FSYNC_LOCAL;
1369
1370         if (ll_i2info(inode)->lli_clob == NULL)
1371                 RETURN(0);
1372
1373         /* for directio, it would call writepages() to evict cached pages
1374          * inside the IO context of write, which will cause deadlock at
1375          * layout_conf since it waits for active IOs to complete. */
1376         result = cl_sync_file_range(inode, start, end, mode, 1);
1377         if (result > 0) {
1378                 wbc->nr_to_write -= result;
1379                 result = 0;
1380          }
1381
1382         if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0)) {
1383                 if (end == OBD_OBJECT_EOF)
1384                         mapping->writeback_index = 0;
1385                 else
1386                         mapping->writeback_index = (end >> PAGE_SHIFT) + 1;
1387         }
1388         RETURN(result);
1389 }
1390
1391 struct ll_cl_context *ll_cl_find(struct file *file)
1392 {
1393         struct ll_file_data *fd = file->private_data;
1394         struct ll_cl_context *lcc;
1395         struct ll_cl_context *found = NULL;
1396
1397         read_lock(&fd->fd_lock);
1398         list_for_each_entry(lcc, &fd->fd_lccs, lcc_list) {
1399                 if (lcc->lcc_cookie == current) {
1400                         found = lcc;
1401                         break;
1402                 }
1403         }
1404         read_unlock(&fd->fd_lock);
1405
1406         return found;
1407 }
1408
1409 void ll_cl_add(struct file *file, const struct lu_env *env, struct cl_io *io,
1410                enum lcc_type type)
1411 {
1412         struct ll_file_data *fd = file->private_data;
1413         struct ll_cl_context *lcc = &ll_env_info(env)->lti_io_ctx;
1414
1415         memset(lcc, 0, sizeof(*lcc));
1416         INIT_LIST_HEAD(&lcc->lcc_list);
1417         lcc->lcc_cookie = current;
1418         lcc->lcc_env = env;
1419         lcc->lcc_io = io;
1420         lcc->lcc_type = type;
1421
1422         write_lock(&fd->fd_lock);
1423         list_add(&lcc->lcc_list, &fd->fd_lccs);
1424         write_unlock(&fd->fd_lock);
1425 }
1426
1427 void ll_cl_remove(struct file *file, const struct lu_env *env)
1428 {
1429         struct ll_file_data *fd = file->private_data;
1430         struct ll_cl_context *lcc = &ll_env_info(env)->lti_io_ctx;
1431
1432         write_lock(&fd->fd_lock);
1433         list_del_init(&lcc->lcc_list);
1434         write_unlock(&fd->fd_lock);
1435 }
1436
1437 int ll_io_read_page(const struct lu_env *env, struct cl_io *io,
1438                            struct cl_page *page, struct file *file)
1439 {
1440         struct inode              *inode  = vvp_object_inode(page->cp_obj);
1441         struct ll_sb_info         *sbi    = ll_i2sbi(inode);
1442         struct ll_file_data       *fd     = file->private_data;
1443         struct ll_readahead_state *ras    = &fd->fd_ras;
1444         struct cl_2queue          *queue  = &io->ci_queue;
1445         struct cl_sync_io         *anchor = NULL;
1446         struct vvp_page           *vpg;
1447         int                        rc = 0, rc2 = 0;
1448         bool                       uptodate;
1449         pgoff_t io_start_index;
1450         pgoff_t io_end_index;
1451         ENTRY;
1452
1453         vpg = cl2vvp_page(cl_object_page_slice(page->cp_obj, page));
1454         uptodate = vpg->vpg_defer_uptodate;
1455
1456         if (ll_readahead_enabled(sbi) && !vpg->vpg_ra_updated) {
1457                 struct vvp_io *vio = vvp_env_io(env);
1458                 enum ras_update_flags flags = 0;
1459
1460                 if (uptodate)
1461                         flags |= LL_RAS_HIT;
1462                 if (!vio->vui_ra_valid)
1463                         flags |= LL_RAS_MMAP;
1464                 ras_update(sbi, inode, ras, vvp_index(vpg), flags);
1465         }
1466
1467         cl_2queue_init(queue);
1468         if (uptodate) {
1469                 vpg->vpg_ra_used = 1;
1470                 cl_page_export(env, page, 1);
1471                 cl_page_disown(env, io, page);
1472         } else {
1473                 anchor = &vvp_env_info(env)->vti_anchor;
1474                 cl_sync_io_init(anchor, 1);
1475                 page->cp_sync_io = anchor;
1476
1477                 cl_2queue_add(queue, page);
1478         }
1479
1480         io_start_index = cl_index(io->ci_obj, io->u.ci_rw.crw_pos);
1481         io_end_index = cl_index(io->ci_obj, io->u.ci_rw.crw_pos +
1482                                 io->u.ci_rw.crw_count - 1);
1483         if (ll_readahead_enabled(sbi)) {
1484                 rc2 = ll_readahead(env, io, &queue->c2_qin, ras,
1485                                    uptodate, file);
1486                 CDEBUG(D_READA, DFID " %d pages read ahead at %lu\n",
1487                        PFID(ll_inode2fid(inode)), rc2, vvp_index(vpg));
1488         } else if (vvp_index(vpg) == io_start_index &&
1489                    io_end_index - io_start_index > 0) {
1490                 rc2 = ll_readpages(env, io, &queue->c2_qin, io_start_index + 1,
1491                                    io_end_index);
1492                 CDEBUG(D_READA, DFID " %d pages read at %lu\n",
1493                        PFID(ll_inode2fid(inode)), rc2, vvp_index(vpg));
1494         }
1495
1496         if (queue->c2_qin.pl_nr > 0) {
1497                 int count = queue->c2_qin.pl_nr;
1498                 rc = cl_io_submit_rw(env, io, CRT_READ, queue);
1499                 if (rc == 0)
1500                         task_io_account_read(PAGE_SIZE * count);
1501         }
1502
1503
1504         if (anchor != NULL && !cl_page_is_owned(page, io)) { /* have sent */
1505                 rc = cl_sync_io_wait(env, anchor, 0);
1506
1507                 cl_page_assume(env, io, page);
1508                 cl_page_list_del(env, &queue->c2_qout, page);
1509
1510                 if (!PageUptodate(cl_page_vmpage(page))) {
1511                         /* Failed to read a mirror, discard this page so that
1512                          * new page can be created with new mirror.
1513                          *
1514                          * TODO: this is not needed after page reinit
1515                          * route is implemented */
1516                         cl_page_discard(env, io, page);
1517                 }
1518                 cl_page_disown(env, io, page);
1519         }
1520
1521         /* TODO: discard all pages until page reinit route is implemented */
1522         cl_page_list_discard(env, io, &queue->c2_qin);
1523
1524         /* Unlock unsent read pages in case of error. */
1525         cl_page_list_disown(env, io, &queue->c2_qin);
1526
1527         cl_2queue_fini(env, queue);
1528
1529         RETURN(rc);
1530 }
1531
1532 /*
1533  * Possible return value:
1534  * 0 no async readahead triggered and fast read could not be used.
1535  * 1 no async readahead, but fast read could be used.
1536  * 2 async readahead triggered and fast read could be used too.
1537  * < 0 on error.
1538  */
1539 static int kickoff_async_readahead(struct file *file, unsigned long pages)
1540 {
1541         struct ll_readahead_work *lrw;
1542         struct inode *inode = file_inode(file);
1543         struct ll_sb_info *sbi = ll_i2sbi(inode);
1544         struct ll_file_data *fd = file->private_data;
1545         struct ll_readahead_state *ras = &fd->fd_ras;
1546         struct ll_ra_info *ra = &sbi->ll_ra_info;
1547         unsigned long throttle;
1548         pgoff_t start_idx = ras_align(ras, ras->ras_next_readahead_idx);
1549         pgoff_t end_idx = start_idx + pages - 1;
1550
1551         throttle = min(ra->ra_async_pages_per_file_threshold,
1552                        ra->ra_max_pages_per_file);
1553         /*
1554          * If this is strided i/o or the window is smaller than the
1555          * throttle limit, we do not do async readahead. Otherwise,
1556          * we do async readahead, allowing the user thread to do fast i/o.
1557          */
1558         if (stride_io_mode(ras) || !throttle ||
1559             ras->ras_window_pages < throttle ||
1560             atomic_read(&ra->ra_async_inflight) > ra->ra_async_max_active)
1561                 return 0;
1562
1563         if ((atomic_read(&ra->ra_cur_pages) + pages) > ra->ra_max_pages)
1564                 return 0;
1565
1566         if (ras->ras_async_last_readpage_idx == start_idx)
1567                 return 1;
1568
1569         /* ll_readahead_work_free() free it */
1570         OBD_ALLOC_PTR(lrw);
1571         if (lrw) {
1572                 atomic_inc(&sbi->ll_ra_info.ra_async_inflight);
1573                 lrw->lrw_file = get_file(file);
1574                 lrw->lrw_start_idx = start_idx;
1575                 lrw->lrw_end_idx = end_idx;
1576                 spin_lock(&ras->ras_lock);
1577                 ras->ras_next_readahead_idx = end_idx + 1;
1578                 ras->ras_async_last_readpage_idx = start_idx;
1579                 spin_unlock(&ras->ras_lock);
1580                 ll_readahead_work_add(inode, lrw);
1581         } else {
1582                 return -ENOMEM;
1583         }
1584
1585         return 2;
1586 }
1587
1588 /*
1589  * Check if we can issue a readahead RPC, if that is
1590  * the case, we can't do fast IO because we will need
1591  * a cl_io to issue the RPC.
1592  */
1593 static bool ll_use_fast_io(struct file *file,
1594                            struct ll_readahead_state *ras, pgoff_t index)
1595 {
1596         unsigned long fast_read_pages =
1597                 max(RA_REMAIN_WINDOW_MIN, ras->ras_rpc_pages);
1598         loff_t skip_pages;
1599
1600         if (stride_io_mode(ras)) {
1601                 skip_pages = (ras->ras_stride_length +
1602                         ras->ras_stride_bytes - 1) / ras->ras_stride_bytes;
1603                 skip_pages *= fast_read_pages;
1604         } else {
1605                 skip_pages = fast_read_pages;
1606         }
1607
1608         if (ras->ras_window_start_idx + ras->ras_window_pages <
1609             ras->ras_next_readahead_idx + skip_pages ||
1610             kickoff_async_readahead(file, fast_read_pages) > 0)
1611                 return true;
1612
1613         return false;
1614 }
1615
1616 int ll_readpage(struct file *file, struct page *vmpage)
1617 {
1618         struct inode *inode = file_inode(file);
1619         struct cl_object *clob = ll_i2info(inode)->lli_clob;
1620         struct ll_cl_context *lcc;
1621         const struct lu_env  *env = NULL;
1622         struct cl_io   *io = NULL;
1623         struct cl_page *page;
1624         struct ll_sb_info *sbi = ll_i2sbi(inode);
1625         int result;
1626         ENTRY;
1627
1628         lcc = ll_cl_find(file);
1629         if (lcc != NULL) {
1630                 env = lcc->lcc_env;
1631                 io  = lcc->lcc_io;
1632         }
1633
1634         if (io == NULL) { /* fast read */
1635                 struct inode *inode = file_inode(file);
1636                 struct ll_file_data *fd = file->private_data;
1637                 struct ll_readahead_state *ras = &fd->fd_ras;
1638                 struct lu_env  *local_env = NULL;
1639                 struct vvp_page *vpg;
1640
1641                 result = -ENODATA;
1642
1643                 /* TODO: need to verify the layout version to make sure
1644                  * the page is not invalid due to layout change. */
1645                 page = cl_vmpage_page(vmpage, clob);
1646                 if (page == NULL) {
1647                         unlock_page(vmpage);
1648                         ll_ra_stats_inc_sbi(sbi, RA_STAT_FAILED_FAST_READ);
1649                         RETURN(result);
1650                 }
1651
1652                 vpg = cl2vvp_page(cl_object_page_slice(page->cp_obj, page));
1653                 if (vpg->vpg_defer_uptodate) {
1654                         enum ras_update_flags flags = LL_RAS_HIT;
1655
1656                         if (lcc && lcc->lcc_type == LCC_MMAP)
1657                                 flags |= LL_RAS_MMAP;
1658
1659                         /* For fast read, it updates read ahead state only
1660                          * if the page is hit in cache because non cache page
1661                          * case will be handled by slow read later. */
1662                         ras_update(sbi, inode, ras, vvp_index(vpg), flags);
1663                         /* avoid duplicate ras_update() call */
1664                         vpg->vpg_ra_updated = 1;
1665
1666                         if (ll_use_fast_io(file, ras, vvp_index(vpg)))
1667                                 result = 0;
1668                 }
1669
1670                 if (!env) {
1671                         local_env = cl_env_percpu_get();
1672                         env = local_env;
1673                 }
1674
1675                 /* export the page and skip io stack */
1676                 if (result == 0) {
1677                         vpg->vpg_ra_used = 1;
1678                         cl_page_export(env, page, 1);
1679                 } else {
1680                         ll_ra_stats_inc_sbi(sbi, RA_STAT_FAILED_FAST_READ);
1681                 }
1682                 /* release page refcount before unlocking the page to ensure
1683                  * the object won't be destroyed in the calling path of
1684                  * cl_page_put(). Please see comment in ll_releasepage(). */
1685                 cl_page_put(env, page);
1686                 unlock_page(vmpage);
1687                 if (local_env)
1688                         cl_env_percpu_put(local_env);
1689
1690                 RETURN(result);
1691         }
1692
1693         /**
1694          * Direct read can fall back to buffered read, but DIO is done
1695          * with lockless i/o, and buffered requires LDLM locking, so in
1696          * this case we must restart without lockless.
1697          */
1698         if (file->f_flags & O_DIRECT &&
1699             lcc && lcc->lcc_type == LCC_RW &&
1700             !io->ci_ignore_lockless) {
1701                 unlock_page(vmpage);
1702                 io->ci_ignore_lockless = 1;
1703                 io->ci_need_restart = 1;
1704                 RETURN(-ENOLCK);
1705         }
1706
1707         LASSERT(io->ci_state == CIS_IO_GOING);
1708         page = cl_page_find(env, clob, vmpage->index, vmpage, CPT_CACHEABLE);
1709         if (!IS_ERR(page)) {
1710                 LASSERT(page->cp_type == CPT_CACHEABLE);
1711                 if (likely(!PageUptodate(vmpage))) {
1712                         cl_page_assume(env, io, page);
1713
1714                         result = ll_io_read_page(env, io, page, file);
1715                 } else {
1716                         /* Page from a non-object file. */
1717                         unlock_page(vmpage);
1718                         result = 0;
1719                 }
1720                 cl_page_put(env, page);
1721         } else {
1722                 unlock_page(vmpage);
1723                 result = PTR_ERR(page);
1724         }
1725         RETURN(result);
1726 }