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