Whamcloud - gitweb
LU-14622 osd: mark pages accessed on reads
[fs/lustre-release.git] / lustre / osd-ldiskfs / osd_io.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) 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2012, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  *
31  * lustre/osd/osd_io.c
32  *
33  * body operations
34  *
35  * Author: Nikita Danilov <nikita@clusterfs.com>
36  * Author: Alex Zhuravlev <bzzz@whamcloud.com>
37  *
38  */
39
40 #define DEBUG_SUBSYSTEM S_OSD
41
42 /* prerequisite for linux/xattr.h */
43 #include <linux/types.h>
44 /* prerequisite for linux/xattr.h */
45 #include <linux/fs.h>
46 #include <linux/mm.h>
47 #include <linux/swap.h>
48 #include <linux/pagevec.h>
49
50 /*
51  * struct OBD_{ALLOC,FREE}*()
52  * OBD_FAIL_CHECK
53  */
54 #include <obd_support.h>
55
56 #include "osd_internal.h"
57
58 /* ext_depth() */
59 #include <ldiskfs/ldiskfs_extents.h>
60
61 static inline bool osd_use_page_cache(struct osd_device *d)
62 {
63         /* do not use pagecache if write and read caching are disabled */
64         if (d->od_writethrough_cache + d->od_read_cache == 0)
65                 return false;
66         /* use pagecache by default */
67         return true;
68 }
69
70 static int __osd_init_iobuf(struct osd_device *d, struct osd_iobuf *iobuf,
71                             int rw, int line, int pages)
72 {
73         int blocks, i;
74
75         LASSERTF(iobuf->dr_elapsed_valid == 0,
76                  "iobuf %p, reqs %d, rw %d, line %d\n", iobuf,
77                  atomic_read(&iobuf->dr_numreqs), iobuf->dr_rw,
78                  iobuf->dr_init_at);
79         LASSERT(pages <= PTLRPC_MAX_BRW_PAGES);
80
81         init_waitqueue_head(&iobuf->dr_wait);
82         atomic_set(&iobuf->dr_numreqs, 0);
83         iobuf->dr_npages = 0;
84         iobuf->dr_error = 0;
85         iobuf->dr_dev = d;
86         iobuf->dr_frags = 0;
87         iobuf->dr_elapsed = ktime_set(0, 0);
88         /* must be counted before, so assert */
89         iobuf->dr_rw = rw;
90         iobuf->dr_init_at = line;
91
92         blocks = pages * (PAGE_SIZE >> osd_sb(d)->s_blocksize_bits);
93         if (iobuf->dr_bl_buf.lb_len >= blocks * sizeof(iobuf->dr_blocks[0])) {
94                 LASSERT(iobuf->dr_pg_buf.lb_len >=
95                         pages * sizeof(iobuf->dr_pages[0]));
96                 return 0;
97         }
98
99         /* start with 1MB for 4K blocks */
100         i = 256;
101         while (i <= PTLRPC_MAX_BRW_PAGES && i < pages)
102                 i <<= 1;
103
104         CDEBUG(D_OTHER, "realloc %u for %u (%u) pages\n",
105                (unsigned int)(pages * sizeof(iobuf->dr_pages[0])), i, pages);
106         pages = i;
107         blocks = pages * (PAGE_SIZE >> osd_sb(d)->s_blocksize_bits);
108         iobuf->dr_max_pages = 0;
109         CDEBUG(D_OTHER, "realloc %u for %u blocks\n",
110                (unsigned int)(blocks * sizeof(iobuf->dr_blocks[0])), blocks);
111
112         lu_buf_realloc(&iobuf->dr_bl_buf, blocks * sizeof(iobuf->dr_blocks[0]));
113         iobuf->dr_blocks = iobuf->dr_bl_buf.lb_buf;
114         if (unlikely(iobuf->dr_blocks == NULL))
115                 return -ENOMEM;
116
117         lu_buf_realloc(&iobuf->dr_pg_buf, pages * sizeof(iobuf->dr_pages[0]));
118         iobuf->dr_pages = iobuf->dr_pg_buf.lb_buf;
119         if (unlikely(iobuf->dr_pages == NULL))
120                 return -ENOMEM;
121
122         lu_buf_realloc(&iobuf->dr_lnb_buf,
123                        pages * sizeof(iobuf->dr_lnbs[0]));
124         iobuf->dr_lnbs = iobuf->dr_lnb_buf.lb_buf;
125         if (unlikely(iobuf->dr_lnbs == NULL))
126                 return -ENOMEM;
127
128         iobuf->dr_max_pages = pages;
129
130         return 0;
131 }
132 #define osd_init_iobuf(dev, iobuf, rw, pages) \
133         __osd_init_iobuf(dev, iobuf, rw, __LINE__, pages)
134
135 static void osd_iobuf_add_page(struct osd_iobuf *iobuf,
136                                struct niobuf_local *lnb)
137 {
138         LASSERT(iobuf->dr_npages < iobuf->dr_max_pages);
139         iobuf->dr_pages[iobuf->dr_npages] = lnb->lnb_page;
140         iobuf->dr_lnbs[iobuf->dr_npages] = lnb;
141         iobuf->dr_npages++;
142 }
143
144 void osd_fini_iobuf(struct osd_device *d, struct osd_iobuf *iobuf)
145 {
146         int rw = iobuf->dr_rw;
147
148         if (iobuf->dr_elapsed_valid) {
149                 iobuf->dr_elapsed_valid = 0;
150                 LASSERT(iobuf->dr_dev == d);
151                 LASSERT(iobuf->dr_frags > 0);
152                 lprocfs_oh_tally(&d->od_brw_stats.hist[BRW_R_DIO_FRAGS+rw],
153                                  iobuf->dr_frags);
154                 lprocfs_oh_tally_log2(&d->od_brw_stats.hist[BRW_R_IO_TIME+rw],
155                                       ktime_to_ms(iobuf->dr_elapsed));
156         }
157 }
158
159 #ifdef HAVE_BIO_ENDIO_USES_ONE_ARG
160 static void dio_complete_routine(struct bio *bio)
161 {
162         int error = blk_status_to_errno(bio->bi_status);
163 #else
164 static void dio_complete_routine(struct bio *bio, int error)
165 {
166 #endif
167         struct osd_iobuf *iobuf = bio->bi_private;
168         struct bio_vec *bvl;
169
170         /* CAVEAT EMPTOR: possibly in IRQ context
171          * DO NOT record procfs stats here!!!
172          */
173
174         if (unlikely(iobuf == NULL)) {
175                 CERROR("***** bio->bi_private is NULL!  This should never happen.  Normally, I would crash here, but instead I will dump the bio contents to the console.  Please report this to <https://jira.whamcloud.com/> , along with any interesting messages leading up to this point (like SCSI errors, perhaps).  Because bi_private is NULL, I can't wake up the thread that initiated this IO - you will probably have to reboot this node.\n");
176                 CERROR("bi_next: %p, bi_flags: %lx, " __stringify(bi_opf)
177                        ": %x, bi_vcnt: %d, bi_idx: %d, bi->size: %d, bi_end_io: %p, bi_cnt: %d, bi_private: %p\n",
178                        bio->bi_next, (unsigned long)bio->bi_flags,
179                        (unsigned int)bio->bi_opf, bio->bi_vcnt, bio_idx(bio),
180                        bio_sectors(bio) << 9, bio->bi_end_io,
181                        atomic_read(&bio->__bi_cnt),
182                        bio->bi_private);
183                 return;
184         }
185
186         /* the check is outside of the cycle for performance reason -bzzz */
187         if (!bio_data_dir(bio)) {
188                 DECLARE_BVEC_ITER_ALL(iter_all);
189
190                 bio_for_each_segment_all(bvl, bio, iter_all) {
191                         if (likely(error == 0))
192                                 SetPageUptodate(bvl_to_page(bvl));
193                         LASSERT(PageLocked(bvl_to_page(bvl)));
194                 }
195                 atomic_dec(&iobuf->dr_dev->od_r_in_flight);
196         } else {
197                 atomic_dec(&iobuf->dr_dev->od_w_in_flight);
198         }
199
200         /* any real error is good enough -bzzz */
201         if (error != 0 && iobuf->dr_error == 0)
202                 iobuf->dr_error = error;
203
204         /*
205          * set dr_elapsed before dr_numreqs turns to 0, otherwise
206          * it's possible that service thread will see dr_numreqs
207          * is zero, but dr_elapsed is not set yet, leading to lost
208          * data in this processing and an assertion in a subsequent
209          * call to OSD.
210          */
211         if (atomic_read(&iobuf->dr_numreqs) == 1) {
212                 ktime_t now = ktime_get();
213
214                 iobuf->dr_elapsed = ktime_sub(now, iobuf->dr_start_time);
215                 iobuf->dr_elapsed_valid = 1;
216         }
217         if (atomic_dec_and_test(&iobuf->dr_numreqs))
218                 wake_up(&iobuf->dr_wait);
219
220         /* Completed bios used to be chained off iobuf->dr_bios and freed in
221          * filter_clear_dreq().  It was then possible to exhaust the biovec-256
222          * mempool when serious on-disk fragmentation was encountered,
223          * deadlocking the OST.  The bios are now released as soon as complete
224          * so the pool cannot be exhausted while IOs are competing. b=10076
225          */
226         bio_put(bio);
227 }
228
229 static void record_start_io(struct osd_iobuf *iobuf, int size)
230 {
231         struct osd_device    *osd = iobuf->dr_dev;
232         struct obd_histogram *h = osd->od_brw_stats.hist;
233
234         iobuf->dr_frags++;
235         atomic_inc(&iobuf->dr_numreqs);
236
237         if (iobuf->dr_rw == 0) {
238                 atomic_inc(&osd->od_r_in_flight);
239                 lprocfs_oh_tally(&h[BRW_R_RPC_HIST],
240                                  atomic_read(&osd->od_r_in_flight));
241                 lprocfs_oh_tally_log2(&h[BRW_R_DISK_IOSIZE], size);
242         } else if (iobuf->dr_rw == 1) {
243                 atomic_inc(&osd->od_w_in_flight);
244                 lprocfs_oh_tally(&h[BRW_W_RPC_HIST],
245                                  atomic_read(&osd->od_w_in_flight));
246                 lprocfs_oh_tally_log2(&h[BRW_W_DISK_IOSIZE], size);
247         } else {
248                 LBUG();
249         }
250 }
251
252 static void osd_submit_bio(int rw, struct bio *bio)
253 {
254         LASSERTF(rw == 0 || rw == 1, "%x\n", rw);
255 #ifdef HAVE_SUBMIT_BIO_2ARGS
256         submit_bio(rw ? WRITE : READ, bio);
257 #else
258         bio->bi_opf |= rw;
259         submit_bio(bio);
260 #endif
261 }
262
263 static int can_be_merged(struct bio *bio, sector_t sector)
264 {
265         if (bio == NULL)
266                 return 0;
267
268         return bio_end_sector(bio) == sector ? 1 : 0;
269 }
270
271 #if IS_ENABLED(CONFIG_BLK_DEV_INTEGRITY)
272 /*
273  * This function will change the data written, thus it should only be
274  * used when checking data integrity feature
275  */
276 static void bio_integrity_fault_inject(struct bio *bio)
277 {
278         struct bio_vec *bvec;
279         DECLARE_BVEC_ITER_ALL(iter_all);
280         void *kaddr;
281         char *addr;
282
283         bio_for_each_segment_all(bvec, bio, iter_all) {
284                 struct page *page = bvec->bv_page;
285
286                 kaddr = kmap(page);
287                 addr = kaddr;
288                 *addr = ~(*addr);
289                 kunmap(page);
290                 break;
291         }
292 }
293
294 static int bio_dif_compare(__u16 *expected_guard_buf, void *bio_prot_buf,
295                            unsigned int sectors, int tuple_size)
296 {
297         __u16 *expected_guard;
298         __u16 *bio_guard;
299         int i;
300
301         expected_guard = expected_guard_buf;
302         for (i = 0; i < sectors; i++) {
303                 bio_guard = (__u16 *)bio_prot_buf;
304                 if (*bio_guard != *expected_guard) {
305                         CERROR(
306                                "unexpected guard tags on sector %d expected guard %u, bio guard %u, sectors %u, tuple size %d\n",
307                                i, *expected_guard, *bio_guard, sectors,
308                                tuple_size);
309                         return -EIO;
310                 }
311                 expected_guard++;
312                 bio_prot_buf += tuple_size;
313         }
314         return 0;
315 }
316
317 static int osd_bio_integrity_compare(struct bio *bio, struct block_device *bdev,
318                                      struct osd_iobuf *iobuf, int index)
319 {
320         struct blk_integrity *bi = bdev_get_integrity(bdev);
321         struct bio_integrity_payload *bip = bio->bi_integrity;
322         struct niobuf_local *lnb;
323         unsigned short sector_size = blk_integrity_interval(bi);
324         void *bio_prot_buf = page_address(bip->bip_vec->bv_page) +
325                 bip->bip_vec->bv_offset;
326         struct bio_vec *bv;
327         sector_t sector = bio_start_sector(bio);
328         unsigned int sectors, total;
329         DECLARE_BVEC_ITER_ALL(iter_all);
330         __u16 *expected_guard;
331         int rc;
332
333         total = 0;
334         bio_for_each_segment_all(bv, bio, iter_all) {
335                 lnb = iobuf->dr_lnbs[index];
336                 expected_guard = lnb->lnb_guards;
337                 sectors = bv->bv_len / sector_size;
338                 if (lnb->lnb_guard_rpc) {
339                         rc = bio_dif_compare(expected_guard, bio_prot_buf,
340                                              sectors, bi->tuple_size);
341                         if (rc)
342                                 return rc;
343                 }
344
345                 sector += sectors;
346                 bio_prot_buf += sectors * bi->tuple_size;
347                 total += sectors * bi->tuple_size;
348                 LASSERT(total <= bip_size(bio->bi_integrity));
349                 index++;
350         }
351         return 0;
352 }
353
354 static int osd_bio_integrity_handle(struct osd_device *osd, struct bio *bio,
355                                     struct osd_iobuf *iobuf,
356                                     int start_page_idx, bool fault_inject,
357                                     bool integrity_enabled)
358 {
359         struct super_block *sb = osd_sb(osd);
360         integrity_gen_fn *generate_fn = NULL;
361         integrity_vrfy_fn *verify_fn = NULL;
362         int rc;
363
364         ENTRY;
365
366         if (!integrity_enabled)
367                 RETURN(0);
368
369         rc = osd_get_integrity_profile(osd, &generate_fn, &verify_fn);
370         if (rc)
371                 RETURN(rc);
372
373         rc = bio_integrity_prep_fn(bio, generate_fn, verify_fn);
374         if (rc)
375                 RETURN(rc);
376
377         /* Verify and inject fault only when writing */
378         if (iobuf->dr_rw == 1) {
379                 if (unlikely(OBD_FAIL_CHECK(OBD_FAIL_OST_INTEGRITY_CMP))) {
380                         rc = osd_bio_integrity_compare(bio, sb->s_bdev, iobuf,
381                                                        start_page_idx);
382                         if (rc)
383                                 RETURN(rc);
384                 }
385
386                 if (unlikely(fault_inject))
387                         bio_integrity_fault_inject(bio);
388         }
389
390         RETURN(0);
391 }
392
393 #ifdef HAVE_BIO_INTEGRITY_PREP_FN
394 #  ifdef HAVE_BIO_ENDIO_USES_ONE_ARG
395 static void dio_integrity_complete_routine(struct bio *bio)
396 #  else
397 static void dio_integrity_complete_routine(struct bio *bio, int error)
398 #  endif
399 {
400         struct osd_bio_private *bio_private = bio->bi_private;
401
402         bio->bi_private = bio_private->obp_iobuf;
403         osd_dio_complete_routine(bio, error);
404
405         OBD_FREE_PTR(bio_private);
406 }
407 #endif /* HAVE_BIO_INTEGRITY_PREP_FN */
408 #else  /* !CONFIG_BLK_DEV_INTEGRITY */
409 #define osd_bio_integrity_handle(osd, bio, iobuf, start_page_idx, \
410                                  fault_inject, integrity_enabled) 0
411 #endif /* CONFIG_BLK_DEV_INTEGRITY */
412
413 static int osd_bio_init(struct bio *bio, struct osd_iobuf *iobuf,
414                         bool integrity_enabled, int start_page_idx,
415                         struct osd_bio_private **pprivate)
416 {
417         ENTRY;
418
419         *pprivate = NULL;
420
421 #ifdef HAVE_BIO_INTEGRITY_PREP_FN
422         if (integrity_enabled) {
423                 struct osd_bio_private *bio_private = NULL;
424
425                 OBD_ALLOC_GFP(bio_private, sizeof(*bio_private), GFP_NOIO);
426                 if (bio_private == NULL)
427                         RETURN(-ENOMEM);
428                 bio->bi_end_io = dio_integrity_complete_routine;
429                 bio->bi_private = bio_private;
430                 bio_private->obp_start_page_idx = start_page_idx;
431                 bio_private->obp_iobuf = iobuf;
432                 *pprivate = bio_private;
433         } else
434 #endif
435         {
436                 bio->bi_end_io = dio_complete_routine;
437                 bio->bi_private = iobuf;
438         }
439
440         RETURN(0);
441 }
442
443 static void osd_mark_page_io_done(struct osd_iobuf *iobuf,
444                                   struct inode *inode,
445                                   sector_t start_blocks,
446                                   sector_t count)
447 {
448         struct niobuf_local *lnb;
449         int blocks_per_page = PAGE_SIZE >> inode->i_blkbits;
450         pgoff_t pg_start, pg_end;
451
452         pg_start = start_blocks / blocks_per_page;
453         if (start_blocks % blocks_per_page)
454                 pg_start++;
455         if (count >= blocks_per_page)
456                 pg_end = (start_blocks + count -
457                           blocks_per_page) / blocks_per_page;
458         else
459                 return; /* nothing to mark */
460         for ( ; pg_start <= pg_end; pg_start++) {
461                 lnb = iobuf->dr_lnbs[pg_start];
462                 lnb->lnb_flags |= OBD_BRW_DONE;
463         }
464 }
465
466 static int osd_do_bio(struct osd_device *osd, struct inode *inode,
467                       struct osd_iobuf *iobuf, sector_t start_blocks,
468                       sector_t count)
469 {
470         int blocks_per_page = PAGE_SIZE >> inode->i_blkbits;
471         struct page **pages = iobuf->dr_pages;
472         int npages = iobuf->dr_npages;
473         sector_t *blocks = iobuf->dr_blocks;
474         struct super_block *sb = inode->i_sb;
475         int sector_bits = sb->s_blocksize_bits - 9;
476         unsigned int blocksize = sb->s_blocksize;
477         struct block_device *bdev = sb->s_bdev;
478         struct osd_bio_private *bio_private = NULL;
479         struct bio *bio = NULL;
480         int bio_start_page_idx;
481         struct page *page;
482         unsigned int page_offset;
483         sector_t sector;
484         int nblocks;
485         int block_idx, block_idx_end;
486         int page_idx, page_idx_start;
487         int i;
488         int rc = 0;
489         bool fault_inject;
490         bool integrity_enabled;
491         struct blk_plug plug;
492         int blocks_left_page;
493
494         ENTRY;
495
496         fault_inject = OBD_FAIL_CHECK(OBD_FAIL_OST_INTEGRITY_FAULT);
497         LASSERT(iobuf->dr_npages == npages);
498
499         integrity_enabled = bdev_integrity_enabled(bdev, iobuf->dr_rw);
500
501         osd_brw_stats_update(osd, iobuf);
502         iobuf->dr_start_time = ktime_get();
503
504         if (!count)
505                 count = npages * blocks_per_page;
506         block_idx_end = start_blocks + count;
507
508         blk_start_plug(&plug);
509
510         page_idx_start = start_blocks / blocks_per_page;
511         for (page_idx = page_idx_start, block_idx = start_blocks;
512              block_idx < block_idx_end; page_idx++,
513              block_idx += blocks_left_page) {
514                 page = pages[page_idx];
515                 LASSERT(page_idx < iobuf->dr_npages);
516
517                 i = block_idx % blocks_per_page;
518                 blocks_left_page = blocks_per_page - i;
519                 for (page_offset = i * blocksize; i < blocks_left_page;
520                      i += nblocks, page_offset += blocksize * nblocks) {
521                         nblocks = 1;
522
523                         if (blocks[block_idx + i] == 0) {  /* hole */
524                                 LASSERTF(iobuf->dr_rw == 0,
525                                          "page_idx %u, block_idx %u, i %u,"
526                                          "start_blocks: %llu, count: %llu, npages: %d\n",
527                                          page_idx, block_idx, i,
528                                          (unsigned long long)start_blocks,
529                                          (unsigned long long)count, npages);
530                                 memset(kmap(page) + page_offset, 0, blocksize);
531                                 kunmap(page);
532                                 continue;
533                         }
534
535                         sector = (sector_t)blocks[block_idx + i] << sector_bits;
536
537                         /* Additional contiguous file blocks? */
538                         while (i + nblocks < blocks_left_page &&
539                                (sector + (nblocks << sector_bits)) ==
540                                ((sector_t)blocks[block_idx + i + nblocks] <<
541                                  sector_bits))
542                                 nblocks++;
543
544                         if (bio && can_be_merged(bio, sector) &&
545                             bio_add_page(bio, page, blocksize * nblocks,
546                                          page_offset) != 0)
547                                 continue;       /* added this frag OK */
548
549                         if (bio != NULL) {
550                                 struct request_queue *q = bio_get_queue(bio);
551                                 unsigned int bi_size = bio_sectors(bio) << 9;
552
553                                 /* Dang! I have to fragment this I/O */
554                                 CDEBUG(D_INODE,
555                                        "bio++ sz %d vcnt %d(%d) sectors %d(%d) psg %d(%d)\n",
556                                        bi_size, bio->bi_vcnt, bio->bi_max_vecs,
557                                        bio_sectors(bio),
558                                        queue_max_sectors(q),
559                                        osd_bio_nr_segs(bio),
560                                        queue_max_segments(q));
561                                 rc = osd_bio_integrity_handle(osd, bio,
562                                         iobuf, bio_start_page_idx,
563                                         fault_inject, integrity_enabled);
564                                 if (rc) {
565                                         bio_put(bio);
566                                         goto out;
567                                 }
568
569                                 record_start_io(iobuf, bi_size);
570                                 osd_submit_bio(iobuf->dr_rw, bio);
571                         }
572
573                         bio_start_page_idx = page_idx;
574                         /* allocate new bio */
575                         bio = bio_alloc(GFP_NOIO, min(BIO_MAX_PAGES,
576                                         (block_idx_end - block_idx +
577                                          blocks_left_page - 1)));
578                         if (bio == NULL) {
579                                 CERROR("Can't allocate bio %u pages\n",
580                                        block_idx_end - block_idx +
581                                        blocks_left_page - 1);
582                                 rc = -ENOMEM;
583                                 goto out;
584                         }
585
586                         bio_set_dev(bio, bdev);
587                         bio_set_sector(bio, sector);
588                         bio->bi_opf = iobuf->dr_rw ? WRITE : READ;
589                         rc = osd_bio_init(bio, iobuf, integrity_enabled,
590                                           bio_start_page_idx, &bio_private);
591                         if (rc) {
592                                 bio_put(bio);
593                                 goto out;
594                         }
595
596                         rc = bio_add_page(bio, page,
597                                           blocksize * nblocks, page_offset);
598                         LASSERT(rc != 0);
599                 }
600         }
601
602         if (bio != NULL) {
603                 rc = osd_bio_integrity_handle(osd, bio, iobuf,
604                                               bio_start_page_idx,
605                                               fault_inject,
606                                               integrity_enabled);
607                 if (rc) {
608                         bio_put(bio);
609                         goto out;
610                 }
611
612                 record_start_io(iobuf, bio_sectors(bio) << 9);
613                 osd_submit_bio(iobuf->dr_rw, bio);
614                 rc = 0;
615         }
616
617 out:
618         blk_finish_plug(&plug);
619
620         /* in order to achieve better IO throughput, we don't wait for writes
621          * completion here. instead we proceed with transaction commit in
622          * parallel and wait for IO completion once transaction is stopped
623          * see osd_trans_stop() for more details -bzzz
624          */
625         if (iobuf->dr_rw == 0 || fault_inject) {
626                 wait_event(iobuf->dr_wait,
627                            atomic_read(&iobuf->dr_numreqs) == 0);
628                 osd_fini_iobuf(osd, iobuf);
629         }
630
631         if (rc == 0) {
632                 rc = iobuf->dr_error;
633         } else {
634                 if (bio_private)
635                         OBD_FREE_PTR(bio_private);
636         }
637
638         /* Write only now */
639         if (rc == 0 && iobuf->dr_rw)
640                 osd_mark_page_io_done(iobuf, inode,
641                                       start_blocks, count);
642
643         RETURN(rc);
644 }
645
646 static int osd_map_remote_to_local(loff_t offset, ssize_t len, int *nrpages,
647                                    struct niobuf_local *lnb, int maxlnb)
648 {
649         int rc = 0;
650         ENTRY;
651
652         *nrpages = 0;
653
654         while (len > 0) {
655                 int poff = offset & (PAGE_SIZE - 1);
656                 int plen = PAGE_SIZE - poff;
657
658                 if (*nrpages >= maxlnb) {
659                         rc = -EOVERFLOW;
660                         break;
661                 }
662
663                 if (plen > len)
664                         plen = len;
665                 lnb->lnb_file_offset = offset;
666                 lnb->lnb_page_offset = poff;
667                 lnb->lnb_len = plen;
668                 /* lnb->lnb_flags = rnb->rnb_flags; */
669                 lnb->lnb_flags = 0;
670                 lnb->lnb_page = NULL;
671                 lnb->lnb_rc = 0;
672                 lnb->lnb_guard_rpc = 0;
673                 lnb->lnb_guard_disk = 0;
674                 lnb->lnb_locked = 0;
675
676                 LASSERTF(plen <= len, "plen %u, len %lld\n", plen,
677                          (long long) len);
678                 offset += plen;
679                 len -= plen;
680                 lnb++;
681                 (*nrpages)++;
682         }
683
684         RETURN(rc);
685 }
686
687 static struct page *osd_get_page(const struct lu_env *env, struct dt_object *dt,
688                                  loff_t offset, gfp_t gfp_mask, bool cache)
689 {
690         struct osd_thread_info *oti = osd_oti_get(env);
691         struct inode *inode = osd_dt_obj(dt)->oo_inode;
692         struct osd_device *d = osd_obj2dev(osd_dt_obj(dt));
693         struct page *page;
694         int cur;
695
696         LASSERT(inode);
697
698         if (cache) {
699                 page = find_or_create_page(inode->i_mapping,
700                                            offset >> PAGE_SHIFT, gfp_mask);
701
702                 if (likely(page)) {
703                         LASSERT(!PagePrivate2(page));
704                         wait_on_page_writeback(page);
705                 } else {
706                         lprocfs_counter_add(d->od_stats, LPROC_OSD_NO_PAGE, 1);
707                 }
708
709                 return page;
710         }
711
712         if (inode->i_mapping->nrpages) {
713                 /* consult with pagecache, but do not create new pages */
714                 /* this is normally used once */
715                 page = find_lock_page(inode->i_mapping, offset >> PAGE_SHIFT);
716                 if (page) {
717                         wait_on_page_writeback(page);
718                         return page;
719                 }
720         }
721
722         LASSERT(oti->oti_dio_pages);
723         cur = oti->oti_dio_pages_used;
724         page = oti->oti_dio_pages[cur];
725
726         if (unlikely(!page)) {
727                 LASSERT(cur < PTLRPC_MAX_BRW_PAGES);
728                 page = alloc_page(gfp_mask);
729                 if (!page)
730                         return NULL;
731                 oti->oti_dio_pages[cur] = page;
732                 SetPagePrivate2(page);
733                 lock_page(page);
734         }
735
736         ClearPageUptodate(page);
737         page->index = offset >> PAGE_SHIFT;
738         oti->oti_dio_pages_used++;
739
740         return page;
741 }
742
743 /*
744  * there are following "locks":
745  * journal_start
746  * i_mutex
747  * page lock
748  *
749  * osd write path:
750  *  - lock page(s)
751  *  - journal_start
752  *  - truncate_sem
753  *
754  * ext4 vmtruncate:
755  *  - lock pages, unlock
756  *  - journal_start
757  *  - lock partial page
758  *  - i_data_sem
759  *
760  */
761
762 /**
763  * Unlock and release pages loaded by osd_bufs_get()
764  *
765  * Unlock \a npages pages from \a lnb and drop the refcount on them.
766  *
767  * \param env           thread execution environment
768  * \param dt            dt object undergoing IO (OSD object + methods)
769  * \param lnb           array of pages undergoing IO
770  * \param npages        number of pages in \a lnb
771  *
772  * \retval 0            always
773  */
774 static int osd_bufs_put(const struct lu_env *env, struct dt_object *dt,
775                         struct niobuf_local *lnb, int npages)
776 {
777         struct osd_thread_info *oti = osd_oti_get(env);
778         struct pagevec pvec;
779         int i;
780
781         ll_pagevec_init(&pvec, 0);
782
783         for (i = 0; i < npages; i++) {
784                 struct page *page = lnb[i].lnb_page;
785
786                 if (page == NULL)
787                         continue;
788
789                 /* if the page isn't cached, then reset uptodate
790                  * to prevent reuse
791                  */
792                 if (PagePrivate2(page)) {
793                         oti->oti_dio_pages_used--;
794                 } else {
795                         if (lnb[i].lnb_locked)
796                                 unlock_page(page);
797                         if (pagevec_add(&pvec, page) == 0)
798                                 pagevec_release(&pvec);
799                 }
800
801                 lnb[i].lnb_page = NULL;
802         }
803
804         LASSERTF(oti->oti_dio_pages_used == 0, "%d\n", oti->oti_dio_pages_used);
805
806         /* Release any partial pagevec */
807         pagevec_release(&pvec);
808
809         RETURN(0);
810 }
811
812 /**
813  * Load and lock pages undergoing IO
814  *
815  * Pages as described in the \a lnb array are fetched (from disk or cache)
816  * and locked for IO by the caller.
817  *
818  * DLM locking protects us from write and truncate competing for same region,
819  * but partial-page truncate can leave dirty pages in the cache for ldiskfs.
820  * It's possible the writeout on a such a page is in progress when we access
821  * it. It's also possible that during this writeout we put new (partial) data
822  * into the page, but won't be able to proceed in filter_commitrw_write().
823  * Therefore, just wait for writeout completion as it should be rare enough.
824  *
825  * \param env           thread execution environment
826  * \param dt            dt object undergoing IO (OSD object + methods)
827  * \param pos           byte offset of IO start
828  * \param len           number of bytes of IO
829  * \param lnb           array of extents undergoing IO
830  * \param rw            read or write operation, and other flags
831  * \param capa          capabilities
832  *
833  * \retval pages        (zero or more) loaded successfully
834  * \retval -ENOMEM      on memory/page allocation error
835  */
836 static int osd_bufs_get(const struct lu_env *env, struct dt_object *dt,
837                         loff_t pos, ssize_t len, struct niobuf_local *lnb,
838                         int maxlnb, enum dt_bufs_type rw)
839 {
840         struct osd_thread_info *oti = osd_oti_get(env);
841         struct osd_object *obj = osd_dt_obj(dt);
842         struct osd_device *osd   = osd_obj2dev(obj);
843         int npages, i, iosize, rc = 0;
844         bool cache, write;
845         loff_t fsize;
846         gfp_t gfp_mask;
847
848         LASSERT(obj->oo_inode);
849
850         rc = osd_map_remote_to_local(pos, len, &npages, lnb, maxlnb);
851         if (rc)
852                 RETURN(rc);
853
854         write = rw & DT_BUFS_TYPE_WRITE;
855
856         fsize = lnb[npages - 1].lnb_file_offset + lnb[npages - 1].lnb_len;
857         iosize = fsize - lnb[0].lnb_file_offset;
858         fsize = max(fsize, i_size_read(obj->oo_inode));
859
860         cache = rw & DT_BUFS_TYPE_READAHEAD;
861         if (cache)
862                 goto bypass_checks;
863
864         cache = osd_use_page_cache(osd);
865         while (cache) {
866                 if (write) {
867                         if (!osd->od_writethrough_cache) {
868                                 cache = false;
869                                 break;
870                         }
871                         if (iosize > osd->od_writethrough_max_iosize) {
872                                 cache = false;
873                                 break;
874                         }
875                 } else {
876                         if (!osd->od_read_cache) {
877                                 cache = false;
878                                 break;
879                         }
880                         if (iosize > osd->od_readcache_max_iosize) {
881                                 cache = false;
882                                 break;
883                         }
884                 }
885                 /* don't use cache on large files */
886                 if (osd->od_readcache_max_filesize &&
887                     fsize > osd->od_readcache_max_filesize)
888                         cache = false;
889                 break;
890         }
891
892 bypass_checks:
893         if (!cache && unlikely(!oti->oti_dio_pages)) {
894                 OBD_ALLOC_PTR_ARRAY_LARGE(oti->oti_dio_pages,
895                                           PTLRPC_MAX_BRW_PAGES);
896                 if (!oti->oti_dio_pages)
897                         return -ENOMEM;
898         }
899
900         /* this could also try less hard for DT_BUFS_TYPE_READAHEAD pages */
901         gfp_mask = rw & DT_BUFS_TYPE_LOCAL ? (GFP_NOFS | __GFP_HIGHMEM) :
902                                              GFP_HIGHUSER;
903         for (i = 0; i < npages; i++, lnb++) {
904                 lnb->lnb_page = osd_get_page(env, dt, lnb->lnb_file_offset,
905                                              gfp_mask, cache);
906                 if (lnb->lnb_page == NULL)
907                         GOTO(cleanup, rc = -ENOMEM);
908
909                 lnb->lnb_locked = 1;
910                 if (cache)
911                         mark_page_accessed(lnb->lnb_page);
912         }
913
914 #if 0
915         /* XXX: this version doesn't invalidate cached pages, but use them */
916         if (!cache && write && obj->oo_inode->i_mapping->nrpages) {
917                 /* do not allow data aliasing, invalidate pagecache */
918                 /* XXX: can be quite expensive in mixed case */
919                 invalidate_mapping_pages(obj->oo_inode->i_mapping,
920                                 lnb[0].lnb_file_offset >> PAGE_SHIFT,
921                                 lnb[npages - 1].lnb_file_offset >> PAGE_SHIFT);
922         }
923 #endif
924
925         RETURN(i);
926
927 cleanup:
928         if (i > 0)
929                 osd_bufs_put(env, dt, lnb - i, i);
930         return rc;
931 }
932 /* Borrow @ext4_chunk_trans_blocks */
933 static int osd_chunk_trans_blocks(struct inode *inode, int nrblocks)
934 {
935         ldiskfs_group_t groups;
936         int gdpblocks;
937         int idxblocks;
938         int depth;
939         int ret;
940
941         depth = ext_depth(inode);
942         idxblocks = depth * 2;
943
944         /*
945          * Now let's see how many group bitmaps and group descriptors need
946          * to account.
947          */
948         groups = idxblocks + 1;
949         gdpblocks = groups;
950         if (groups > LDISKFS_SB(inode->i_sb)->s_groups_count)
951                 groups = LDISKFS_SB(inode->i_sb)->s_groups_count;
952         if (gdpblocks > LDISKFS_SB(inode->i_sb)->s_gdb_count)
953                 gdpblocks = LDISKFS_SB(inode->i_sb)->s_gdb_count;
954
955         /* bitmaps and block group descriptor blocks */
956         ret = idxblocks + groups + gdpblocks;
957
958         /* Blocks for super block, inode, quota and xattr blocks */
959         ret += LDISKFS_META_TRANS_BLOCKS(inode->i_sb);
960
961         return ret;
962 }
963
964 #ifdef HAVE_LDISKFS_JOURNAL_ENSURE_CREDITS
965 static int osd_extend_restart_trans(handle_t *handle, int needed,
966                                     struct inode *inode)
967 {
968         int rc;
969
970         rc = ldiskfs_journal_ensure_credits(handle, needed,
971                 ldiskfs_trans_default_revoke_credits(inode->i_sb));
972         /* this means journal has been restarted */
973         if (rc > 0)
974                 rc = 0;
975
976         return rc;
977 }
978 #else
979 static int osd_extend_restart_trans(handle_t *handle, int needed,
980                                     struct inode *inode)
981 {
982         int rc;
983
984         if (ldiskfs_handle_has_enough_credits(handle, needed))
985                 return 0;
986         rc = ldiskfs_journal_extend(handle,
987                                 needed - handle->h_buffer_credits);
988         if (rc <= 0)
989                 return rc;
990
991         return ldiskfs_journal_restart(handle, needed);
992 }
993 #endif /* HAVE_LDISKFS_JOURNAL_ENSURE_CREDITS */
994
995 static int osd_ldiskfs_map_write(struct inode *inode, struct osd_iobuf *iobuf,
996                                  struct osd_device *osd, sector_t start_blocks,
997                                  sector_t count, loff_t *disk_size,
998                                  __u64 user_size)
999 {
1000         /* if file has grown, take user_size into account */
1001         if (user_size && *disk_size > user_size)
1002                 *disk_size = user_size;
1003
1004         spin_lock(&inode->i_lock);
1005         if (*disk_size > i_size_read(inode)) {
1006                 i_size_write(inode, *disk_size);
1007                 LDISKFS_I(inode)->i_disksize = *disk_size;
1008                 spin_unlock(&inode->i_lock);
1009                 osd_dirty_inode(inode, I_DIRTY_DATASYNC);
1010         } else {
1011                 spin_unlock(&inode->i_lock);
1012         }
1013
1014         /*
1015          * We don't do stats here as in read path because
1016          * write is async: we'll do this in osd_put_bufs()
1017          */
1018         return osd_do_bio(osd, inode, iobuf, start_blocks, count);
1019 }
1020
1021 static unsigned int osd_extent_bytes(const struct osd_device *o)
1022 {
1023         unsigned int *extent_bytes_ptr =
1024                         raw_cpu_ptr(o->od_extent_bytes_percpu);
1025
1026         if (likely(*extent_bytes_ptr))
1027                 return *extent_bytes_ptr;
1028
1029         /* initialize on first access or CPU hotplug */
1030         if (!ldiskfs_has_feature_extents(osd_sb(o)))
1031                 *extent_bytes_ptr = 1 << osd_sb(o)->s_blocksize_bits;
1032         else
1033                 *extent_bytes_ptr = OSD_DEFAULT_EXTENT_BYTES;
1034
1035         return *extent_bytes_ptr;
1036 }
1037
1038 #define EXTENT_BYTES_DECAY 64
1039 static void osd_decay_extent_bytes(struct osd_device *osd,
1040                                    unsigned int new_bytes)
1041 {
1042         unsigned int old_bytes;
1043
1044         if (!ldiskfs_has_feature_extents(osd_sb(osd)))
1045                 return;
1046
1047         old_bytes = osd_extent_bytes(osd);
1048         *raw_cpu_ptr(osd->od_extent_bytes_percpu) =
1049                 (old_bytes * (EXTENT_BYTES_DECAY - 1) +
1050                  min(new_bytes, OSD_DEFAULT_EXTENT_BYTES) +
1051                  EXTENT_BYTES_DECAY - 1) / EXTENT_BYTES_DECAY;
1052 }
1053
1054 static int osd_ldiskfs_map_inode_pages(struct inode *inode,
1055                                        struct osd_iobuf *iobuf,
1056                                        struct osd_device *osd,
1057                                        int create, __u64 user_size,
1058                                        int check_credits,
1059                                        struct thandle *thandle)
1060 {
1061         int blocks_per_page = PAGE_SIZE >> inode->i_blkbits;
1062         int rc = 0, i = 0, mapped_index = 0;
1063         struct page *fp = NULL;
1064         int clen = 0;
1065         pgoff_t max_page_index;
1066         handle_t *handle = NULL;
1067         sector_t start_blocks = 0, count = 0;
1068         loff_t disk_size = 0;
1069         struct page **page = iobuf->dr_pages;
1070         int pages = iobuf->dr_npages;
1071         sector_t *blocks = iobuf->dr_blocks;
1072         struct niobuf_local *lnb1, *lnb2;
1073         loff_t size1, size2;
1074
1075         max_page_index = inode->i_sb->s_maxbytes >> PAGE_SHIFT;
1076
1077         CDEBUG(D_OTHER, "inode %lu: map %d pages from %lu\n",
1078                 inode->i_ino, pages, (*page)->index);
1079
1080         if (create) {
1081                 create = LDISKFS_GET_BLOCKS_CREATE;
1082                 handle = ldiskfs_journal_current_handle();
1083                 LASSERT(handle != NULL);
1084                 rc = osd_attach_jinode(inode);
1085                 if (rc)
1086                         return rc;
1087                 disk_size = i_size_read(inode);
1088                 /* if disk_size is already bigger than specified user_size,
1089                  * ignore user_size
1090                  */
1091                 if (disk_size > user_size)
1092                         user_size = 0;
1093         }
1094         /* pages are sorted already. so, we just have to find
1095          * contig. space and process them properly
1096          */
1097         while (i < pages) {
1098                 long blen, total = 0, previous_total = 0;
1099                 struct ldiskfs_map_blocks map = { 0 };
1100
1101                 if (fp == NULL) { /* start new extent */
1102                         fp = *page++;
1103                         clen = 1;
1104                         if (++i != pages)
1105                                 continue;
1106                 } else if (fp->index + clen == (*page)->index) {
1107                         /* continue the extent */
1108                         page++;
1109                         clen++;
1110                         if (++i != pages)
1111                                 continue;
1112                 }
1113                 if (fp->index + clen >= max_page_index)
1114                         GOTO(cleanup, rc = -EFBIG);
1115                 /* process found extent */
1116                 map.m_lblk = fp->index * blocks_per_page;
1117                 map.m_len = blen = clen * blocks_per_page;
1118 cont_map:
1119                 /**
1120                  * We might restart transaction for block allocations,
1121                  * in order to make sure data ordered mode, issue IO, disk
1122                  * size update and block allocations need be within same
1123                  * transaction to make sure consistency.
1124                  */
1125                 if (handle && check_credits) {
1126                         struct osd_thandle *oh;
1127
1128                         LASSERT(thandle != NULL);
1129                         oh = container_of(thandle, struct osd_thandle,
1130                                           ot_super);
1131                         /*
1132                          * only issue IO if restart transaction needed,
1133                          * as update disk size need hold inode lock, we
1134                          * want to avoid that as much as possible.
1135                          */
1136                         if (oh->oh_declared_ext <= 0) {
1137                                 rc = osd_ldiskfs_map_write(inode,
1138                                         iobuf, osd, start_blocks,
1139                                         count, &disk_size, user_size);
1140                                 if (rc)
1141                                         GOTO(cleanup, rc);
1142                                 thandle->th_restart_tran = 1;
1143                                 GOTO(cleanup, rc = -EAGAIN);
1144                         }
1145
1146                         if (OBD_FAIL_CHECK(OBD_FAIL_OST_RESTART_IO))
1147                                 oh->oh_declared_ext = 0;
1148                         else
1149                                 oh->oh_declared_ext--;
1150                 }
1151                 rc = ldiskfs_map_blocks(handle, inode, &map, create);
1152                 if (rc >= 0) {
1153                         int c = 0;
1154
1155                         for (; total < blen && c < map.m_len; c++, total++) {
1156                                 if (rc == 0) {
1157                                         *(blocks + total) = 0;
1158                                         total++;
1159                                         break;
1160                                 }
1161                                 if ((map.m_flags & LDISKFS_MAP_UNWRITTEN) &&
1162                                     !create) {
1163                                         /* don't try to read allocated, but
1164                                          * unwritten blocks, instead fill the
1165                                          * patches with zeros in osd_do_bio() */
1166                                         *(blocks + total) = 0;
1167                                         continue;
1168                                 }
1169                                 *(blocks + total) = map.m_pblk + c;
1170                                 /* unmap any possible underlying
1171                                  * metadata from the block device
1172                                  * mapping.  b=6998.
1173                                  */
1174                                 if ((map.m_flags & LDISKFS_MAP_NEW) &&
1175                                     create)
1176                                         clean_bdev_aliases(inode->i_sb->s_bdev,
1177                                                            map.m_pblk + c, 1);
1178                         }
1179                         rc = 0;
1180                 }
1181
1182                 if (rc == 0 && create) {
1183                         count += (total - previous_total);
1184                         mapped_index = (count + blocks_per_page -
1185                                         1) / blocks_per_page - 1;
1186                         lnb1 = iobuf->dr_lnbs[i - clen];
1187                         lnb2 = iobuf->dr_lnbs[mapped_index];
1188                         size1 = lnb1->lnb_file_offset -
1189                                 (lnb1->lnb_file_offset % PAGE_SIZE) +
1190                                 (total << inode->i_blkbits);
1191                         size2 = lnb2->lnb_file_offset + lnb2->lnb_len;
1192
1193                         if (size1 > size2)
1194                                 size1 = size2;
1195                         if (size1 > disk_size)
1196                                 disk_size = size1;
1197                 }
1198
1199                 if (rc == 0 && total < blen) {
1200                         /*
1201                          * decay extent blocks if we could not
1202                          * allocate extent once.
1203                          */
1204                         osd_decay_extent_bytes(osd,
1205                                 (total - previous_total) << inode->i_blkbits);
1206                         map.m_lblk = fp->index * blocks_per_page + total;
1207                         map.m_len = blen - total;
1208                         previous_total = total;
1209                         goto cont_map;
1210                 }
1211                 if (rc != 0)
1212                         GOTO(cleanup, rc);
1213                 /*
1214                  * decay extent blocks if we could allocate
1215                  * good large extent.
1216                  */
1217                 if (total - previous_total >=
1218                     osd_extent_bytes(osd) >> inode->i_blkbits)
1219                         osd_decay_extent_bytes(osd,
1220                                 (total - previous_total) << inode->i_blkbits);
1221                 /* look for next extent */
1222                 fp = NULL;
1223                 blocks += blocks_per_page * clen;
1224         }
1225 cleanup:
1226         if (rc == 0 && create &&
1227             start_blocks < pages * blocks_per_page) {
1228                 rc = osd_ldiskfs_map_write(inode, iobuf, osd, start_blocks,
1229                                            count, &disk_size, user_size);
1230                 LASSERT(start_blocks + count == pages * blocks_per_page);
1231         }
1232         return rc;
1233 }
1234
1235 static int osd_write_prep(const struct lu_env *env, struct dt_object *dt,
1236                           struct niobuf_local *lnb, int npages)
1237 {
1238         struct osd_thread_info *oti   = osd_oti_get(env);
1239         struct osd_iobuf       *iobuf = &oti->oti_iobuf;
1240         struct inode           *inode = osd_dt_obj(dt)->oo_inode;
1241         struct osd_device      *osd   = osd_obj2dev(osd_dt_obj(dt));
1242         ktime_t start, end;
1243         s64 timediff;
1244         ssize_t isize;
1245         __s64  maxidx;
1246         int i, rc = 0;
1247
1248         LASSERT(inode);
1249
1250         rc = osd_init_iobuf(osd, iobuf, 0, npages);
1251         if (unlikely(rc != 0))
1252                 RETURN(rc);
1253
1254         isize = i_size_read(inode);
1255         maxidx = ((isize + PAGE_SIZE - 1) >> PAGE_SHIFT) - 1;
1256
1257         start = ktime_get();
1258         for (i = 0; i < npages; i++) {
1259
1260                 /*
1261                  * till commit the content of the page is undefined
1262                  * we'll set it uptodate once bulk is done. otherwise
1263                  * subsequent reads can access non-stable data
1264                  */
1265                 ClearPageUptodate(lnb[i].lnb_page);
1266
1267                 if (lnb[i].lnb_len == PAGE_SIZE)
1268                         continue;
1269
1270                 if (maxidx >= lnb[i].lnb_page->index) {
1271                         osd_iobuf_add_page(iobuf, &lnb[i]);
1272                 } else {
1273                         long off;
1274                         char *p = kmap(lnb[i].lnb_page);
1275
1276                         off = lnb[i].lnb_page_offset;
1277                         if (off)
1278                                 memset(p, 0, off);
1279                         off = (lnb[i].lnb_page_offset + lnb[i].lnb_len) &
1280                               ~PAGE_MASK;
1281                         if (off)
1282                                 memset(p + off, 0, PAGE_SIZE - off);
1283                         kunmap(lnb[i].lnb_page);
1284                 }
1285         }
1286         end = ktime_get();
1287         timediff = ktime_us_delta(end, start);
1288         lprocfs_counter_add(osd->od_stats, LPROC_OSD_GET_PAGE, timediff);
1289
1290         if (iobuf->dr_npages) {
1291                 rc = osd_ldiskfs_map_inode_pages(inode, iobuf, osd, 0,
1292                                                  0, 0, NULL);
1293                 if (likely(rc == 0)) {
1294                         rc = osd_do_bio(osd, inode, iobuf, 0, 0);
1295                         /* do IO stats for preparation reads */
1296                         osd_fini_iobuf(osd, iobuf);
1297                 }
1298         }
1299         RETURN(rc);
1300 }
1301
1302 struct osd_fextent {
1303         sector_t        start;
1304         sector_t        end;
1305         unsigned int    mapped:1;
1306 };
1307
1308 static int osd_is_mapped(struct dt_object *dt, __u64 offset,
1309                          struct osd_fextent *cached_extent)
1310 {
1311         struct inode *inode = osd_dt_obj(dt)->oo_inode;
1312         sector_t block = offset >> inode->i_blkbits;
1313         sector_t start;
1314         struct fiemap_extent_info fei = { 0 };
1315         struct fiemap_extent fe = { 0 };
1316         int rc;
1317
1318         if (block >= cached_extent->start && block < cached_extent->end)
1319                 return cached_extent->mapped;
1320
1321         if (i_size_read(inode) == 0)
1322                 return 0;
1323
1324         /* Beyond EOF, must not be mapped */
1325         if (((i_size_read(inode) - 1) >> inode->i_blkbits) < block)
1326                 return 0;
1327
1328         fei.fi_extents_max = 1;
1329         fei.fi_extents_start = &fe;
1330
1331         rc = inode->i_op->fiemap(inode, &fei, offset, FIEMAP_MAX_OFFSET-offset);
1332         if (rc != 0)
1333                 return 0;
1334
1335         start = fe.fe_logical >> inode->i_blkbits;
1336         if (fei.fi_extents_mapped == 0) {
1337                 /* a special case - no extent found at this offset and forward.
1338                  * we can consider this as a hole to EOF. it's safe to cache
1339                  * as other threads can not allocate/punch blocks this thread
1340                  * is working on (LDLM). */
1341                 cached_extent->start = block;
1342                 cached_extent->end = i_size_read(inode) >> inode->i_blkbits;
1343                 cached_extent->mapped = 0;
1344                 return 0;
1345         }
1346
1347         if (start > block) {
1348                 cached_extent->start = block;
1349                 cached_extent->end = start;
1350                 cached_extent->mapped = 0;
1351         } else {
1352                 cached_extent->start = start;
1353                 cached_extent->end = (fe.fe_logical + fe.fe_length) >>
1354                                       inode->i_blkbits;
1355                 cached_extent->mapped = 1;
1356         }
1357
1358         return cached_extent->mapped;
1359 }
1360
1361 #define MAX_EXTENTS_PER_WRITE 100
1362 static int osd_declare_write_commit(const struct lu_env *env,
1363                                     struct dt_object *dt,
1364                                     struct niobuf_local *lnb, int npages,
1365                                     struct thandle *handle)
1366 {
1367         const struct osd_device *osd = osd_obj2dev(osd_dt_obj(dt));
1368         struct inode            *inode = osd_dt_obj(dt)->oo_inode;
1369         struct osd_thandle      *oh;
1370         int                     extents = 0;
1371         int                     depth;
1372         int                     i;
1373         int                     newblocks = 0;
1374         int                     rc = 0;
1375         int                     credits = 0;
1376         long long               quota_space = 0;
1377         struct osd_fextent      mapped = { 0 }, extent = { 0 };
1378         enum osd_quota_local_flags local_flags = 0;
1379         enum osd_qid_declare_flags declare_flags = OSD_QID_BLK;
1380         unsigned int            extent_bytes;
1381         ENTRY;
1382
1383         LASSERT(handle != NULL);
1384         oh = container_of(handle, struct osd_thandle, ot_super);
1385         LASSERT(oh->ot_handle == NULL);
1386
1387         /*
1388          * We track a decaying average extent blocks per filesystem,
1389          * for most of time, it will be 1M, with filesystem becoming
1390          * heavily-fragmented, it will be reduced to 4K at the worst.
1391          */
1392         extent_bytes = osd_extent_bytes(osd);
1393         LASSERT(extent_bytes >= (1 << osd_sb(osd)->s_blocksize));
1394
1395         /* calculate number of extents (probably better to pass nb) */
1396         for (i = 0; i < npages; i++) {
1397                 /* ignore quota for the whole request if any page is from
1398                  * client cache or written by root.
1399                  *
1400                  * XXX once we drop the 1.8 client support, the checking
1401                  * for whether page is from cache can be simplified as:
1402                  * !(lnb[i].flags & OBD_BRW_SYNC)
1403                  *
1404                  * XXX we could handle this on per-lnb basis as done by
1405                  * grant.
1406                  */
1407                 if ((lnb[i].lnb_flags & OBD_BRW_NOQUOTA) ||
1408                     (lnb[i].lnb_flags & (OBD_BRW_FROM_GRANT | OBD_BRW_SYNC)) ==
1409                     OBD_BRW_FROM_GRANT)
1410                         declare_flags |= OSD_QID_FORCE;
1411
1412                 if (osd_is_mapped(dt, lnb[i].lnb_file_offset, &mapped)) {
1413                         lnb[i].lnb_flags |= OBD_BRW_MAPPED;
1414                         continue;
1415                 }
1416
1417                 if (lnb[i].lnb_flags & OBD_BRW_DONE) {
1418                         lnb[i].lnb_flags |= OBD_BRW_MAPPED;
1419                         continue;
1420                 }
1421
1422                 /* count only unmapped changes */
1423                 newblocks++;
1424                 if (lnb[i].lnb_file_offset != extent.end || extent.end == 0) {
1425                         if (extent.end != 0)
1426                                 extents += (extent.end - extent.start +
1427                                             extent_bytes - 1) / extent_bytes;
1428                         extent.start = lnb[i].lnb_file_offset;
1429                         extent.end = lnb[i].lnb_file_offset + lnb[i].lnb_len;
1430                 } else {
1431                         extent.end += lnb[i].lnb_len;
1432                 }
1433
1434                 quota_space += PAGE_SIZE;
1435         }
1436
1437         credits++; /* inode */
1438         /*
1439          * overwrite case, no need to modify tree and
1440          * allocate blocks.
1441          */
1442         if (!newblocks)
1443                 goto out_declare;
1444
1445         extents += (extent.end - extent.start +
1446                     extent_bytes - 1) / extent_bytes;
1447         /**
1448          * with system space usage growing up, mballoc codes won't
1449          * try best to scan block group to align best free extent as
1450          * we can. So extent bytes per extent could be decayed to a
1451          * very small value, this could make us reserve too many credits.
1452          * We could be more optimistic in the credit reservations, even
1453          * in a case where the filesystem is nearly full, it is extremely
1454          * unlikely that the worst case would ever be hit.
1455          */
1456         if (extents > MAX_EXTENTS_PER_WRITE)
1457                 extents = MAX_EXTENTS_PER_WRITE;
1458
1459         /*
1460          * each extent can go into new leaf causing a split
1461          * 5 is max tree depth: inode + 4 index blocks
1462          * with blockmaps, depth is 3 at most
1463          */
1464         if (LDISKFS_I(inode)->i_flags & LDISKFS_EXTENTS_FL) {
1465                 /*
1466                  * many concurrent threads may grow tree by the time
1467                  * our transaction starts. so, consider 2 is a min depth
1468                  */
1469                 depth = ext_depth(inode);
1470                 depth = max(depth, 1) + 1;
1471                 newblocks += depth;
1472                 credits += depth * 2 * extents;
1473         } else {
1474                 depth = 3;
1475                 newblocks += depth;
1476                 credits += depth * extents;
1477         }
1478
1479         oh->oh_declared_ext = extents;
1480
1481         /* quota space for metadata blocks */
1482         quota_space += depth * extents * LDISKFS_BLOCK_SIZE(osd_sb(osd));
1483
1484         /* quota space should be reported in 1K blocks */
1485         quota_space = toqb(quota_space);
1486
1487         /* each new block can go in different group (bitmap + gd) */
1488
1489         /* we can't dirty more bitmap blocks than exist */
1490         if (extents > LDISKFS_SB(osd_sb(osd))->s_groups_count)
1491                 credits += LDISKFS_SB(osd_sb(osd))->s_groups_count;
1492         else
1493                 credits += extents;
1494
1495         /* we can't dirty more gd blocks than exist */
1496         if (extents > LDISKFS_SB(osd_sb(osd))->s_gdb_count)
1497                 credits += LDISKFS_SB(osd_sb(osd))->s_gdb_count;
1498         else
1499                 credits += extents;
1500
1501         CDEBUG(D_INODE,
1502                "%s: inode #%lu extent_bytes %u extents %d credits %d\n",
1503                osd_ino2name(inode), inode->i_ino, extent_bytes, extents,
1504                credits);
1505
1506 out_declare:
1507         osd_trans_declare_op(env, oh, OSD_OT_WRITE, credits);
1508
1509         /* make sure the over quota flags were not set */
1510         lnb[0].lnb_flags &= ~OBD_BRW_OVER_ALLQUOTA;
1511
1512         rc = osd_declare_inode_qid(env, i_uid_read(inode), i_gid_read(inode),
1513                                    i_projid_read(inode), quota_space, oh,
1514                                    osd_dt_obj(dt), &local_flags, declare_flags);
1515
1516         /* we need only to store the overquota flags in the first lnb for
1517          * now, once we support multiple objects BRW, this code needs be
1518          * revised.
1519          */
1520         if (local_flags & QUOTA_FL_OVER_USRQUOTA)
1521                 lnb[0].lnb_flags |= OBD_BRW_OVER_USRQUOTA;
1522         if (local_flags & QUOTA_FL_OVER_GRPQUOTA)
1523                 lnb[0].lnb_flags |= OBD_BRW_OVER_GRPQUOTA;
1524         if (local_flags & QUOTA_FL_OVER_PRJQUOTA)
1525                 lnb[0].lnb_flags |= OBD_BRW_OVER_PRJQUOTA;
1526
1527         if (rc == 0)
1528                 rc = osd_trunc_lock(osd_dt_obj(dt), oh, true);
1529
1530         RETURN(rc);
1531 }
1532
1533 /* Check if a block is allocated or not */
1534 static int osd_write_commit(const struct lu_env *env, struct dt_object *dt,
1535                             struct niobuf_local *lnb, int npages,
1536                             struct thandle *thandle, __u64 user_size)
1537 {
1538         struct osd_thread_info *oti = osd_oti_get(env);
1539         struct osd_iobuf *iobuf = &oti->oti_iobuf;
1540         struct inode *inode = osd_dt_obj(dt)->oo_inode;
1541         struct osd_device  *osd = osd_obj2dev(osd_dt_obj(dt));
1542         int rc = 0, i, check_credits = 0;
1543
1544         LASSERT(inode);
1545
1546         rc = osd_init_iobuf(osd, iobuf, 1, npages);
1547         if (unlikely(rc != 0))
1548                 RETURN(rc);
1549
1550         dquot_initialize(inode);
1551
1552         for (i = 0; i < npages; i++) {
1553                 if (lnb[i].lnb_rc == -ENOSPC &&
1554                     (lnb[i].lnb_flags & OBD_BRW_MAPPED)) {
1555                         /* Allow the write to proceed if overwriting an
1556                          * existing block
1557                          */
1558                         lnb[i].lnb_rc = 0;
1559                 }
1560
1561                 if (lnb[i].lnb_rc) { /* ENOSPC, network RPC error, etc. */
1562                         CDEBUG(D_INODE, "Skipping [%d] == %d\n", i,
1563                                lnb[i].lnb_rc);
1564                         LASSERT(lnb[i].lnb_page);
1565                         generic_error_remove_page(inode->i_mapping,
1566                                                   lnb[i].lnb_page);
1567                         continue;
1568                 }
1569
1570                 if (lnb[i].lnb_flags & OBD_BRW_DONE)
1571                         continue;
1572
1573                 if (!(lnb[i].lnb_flags & OBD_BRW_MAPPED))
1574                         check_credits = 1;
1575
1576                 LASSERT(PageLocked(lnb[i].lnb_page));
1577                 LASSERT(!PageWriteback(lnb[i].lnb_page));
1578
1579                 /*
1580                  * Since write and truncate are serialized by oo_sem, even
1581                  * partial-page truncate should not leave dirty pages in the
1582                  * page cache.
1583                  */
1584                 LASSERT(!PageDirty(lnb[i].lnb_page));
1585
1586                 SetPageUptodate(lnb[i].lnb_page);
1587
1588                 osd_iobuf_add_page(iobuf, &lnb[i]);
1589         }
1590
1591         osd_trans_exec_op(env, thandle, OSD_OT_WRITE);
1592
1593         if (OBD_FAIL_CHECK(OBD_FAIL_OST_MAPBLK_ENOSPC)) {
1594                 rc = -ENOSPC;
1595         } else if (iobuf->dr_npages > 0) {
1596                 rc = osd_ldiskfs_map_inode_pages(inode, iobuf, osd,
1597                                                  1, user_size,
1598                                                  check_credits,
1599                                                  thandle);
1600         } else {
1601                 /* no pages to write, no transno is needed */
1602                 thandle->th_local = 1;
1603         }
1604
1605         if (rc != 0 && !thandle->th_restart_tran)
1606                 osd_fini_iobuf(osd, iobuf);
1607
1608         osd_trans_exec_check(env, thandle, OSD_OT_WRITE);
1609
1610         if (unlikely(rc != 0 && !thandle->th_restart_tran)) {
1611                 /* if write fails, we should drop pages from the cache */
1612                 for (i = 0; i < npages; i++) {
1613                         if (lnb[i].lnb_page == NULL)
1614                                 continue;
1615                         if (!PagePrivate2(lnb[i].lnb_page)) {
1616                                 LASSERT(PageLocked(lnb[i].lnb_page));
1617                                 generic_error_remove_page(inode->i_mapping,
1618                                                           lnb[i].lnb_page);
1619                         }
1620                 }
1621         }
1622
1623         RETURN(rc);
1624 }
1625
1626 static int osd_read_prep(const struct lu_env *env, struct dt_object *dt,
1627                          struct niobuf_local *lnb, int npages)
1628 {
1629         struct osd_thread_info *oti = osd_oti_get(env);
1630         struct osd_iobuf *iobuf = &oti->oti_iobuf;
1631         struct inode *inode = osd_dt_obj(dt)->oo_inode;
1632         struct osd_device *osd = osd_obj2dev(osd_dt_obj(dt));
1633         int rc = 0, i, cache_hits = 0, cache_misses = 0;
1634         ktime_t start, end;
1635         s64 timediff;
1636         loff_t isize;
1637
1638         LASSERT(inode);
1639
1640         rc = osd_init_iobuf(osd, iobuf, 0, npages);
1641         if (unlikely(rc != 0))
1642                 RETURN(rc);
1643
1644         isize = i_size_read(inode);
1645
1646         start = ktime_get();
1647         for (i = 0; i < npages; i++) {
1648
1649                 if (isize <= lnb[i].lnb_file_offset)
1650                         /* If there's no more data, abort early.
1651                          * lnb->lnb_rc == 0, so it's easy to detect later.
1652                          */
1653                         break;
1654
1655                 /* instead of looking if we go beyong isize, send complete
1656                  * pages all the time
1657                  */
1658                 lnb[i].lnb_rc = lnb[i].lnb_len;
1659
1660                 /* Bypass disk read if fail_loc is set properly */
1661                 if (OBD_FAIL_CHECK(OBD_FAIL_OST_FAKE_RW))
1662                         SetPageUptodate(lnb[i].lnb_page);
1663
1664                 if (PageUptodate(lnb[i].lnb_page)) {
1665                         cache_hits++;
1666                         unlock_page(lnb[i].lnb_page);
1667                 } else {
1668                         cache_misses++;
1669                         osd_iobuf_add_page(iobuf, &lnb[i]);
1670                 }
1671                 /* no need to unlock in osd_bufs_put(), the sooner page is
1672                  * unlocked, the earlier another client can access it.
1673                  * notice real unlock_page() can be called few lines
1674                  * below after osd_do_bio(). lnb is a per-thread, so it's
1675                  * fine to have PG_locked and lnb_locked inconsistent here
1676                  */
1677                 lnb[i].lnb_locked = 0;
1678         }
1679         end = ktime_get();
1680         timediff = ktime_us_delta(end, start);
1681         lprocfs_counter_add(osd->od_stats, LPROC_OSD_GET_PAGE, timediff);
1682
1683         if (cache_hits != 0)
1684                 lprocfs_counter_add(osd->od_stats, LPROC_OSD_CACHE_HIT,
1685                                     cache_hits);
1686         if (cache_misses != 0)
1687                 lprocfs_counter_add(osd->od_stats, LPROC_OSD_CACHE_MISS,
1688                                     cache_misses);
1689         if (cache_hits + cache_misses != 0)
1690                 lprocfs_counter_add(osd->od_stats, LPROC_OSD_CACHE_ACCESS,
1691                                     cache_hits + cache_misses);
1692
1693         if (iobuf->dr_npages) {
1694                 rc = osd_ldiskfs_map_inode_pages(inode, iobuf, osd, 0,
1695                                                  0, 0, NULL);
1696                 if (!rc)
1697                         rc = osd_do_bio(osd, inode, iobuf, 0, 0);
1698
1699                 /* IO stats will be done in osd_bufs_put() */
1700
1701                 /* early release to let others read data during the bulk */
1702                 for (i = 0; i < iobuf->dr_npages; i++) {
1703                         LASSERT(PageLocked(iobuf->dr_pages[i]));
1704                         if (!PagePrivate2(iobuf->dr_pages[i]))
1705                                 unlock_page(iobuf->dr_pages[i]);
1706                 }
1707         }
1708
1709         RETURN(rc);
1710 }
1711
1712 /*
1713  * XXX: Another layering violation for now.
1714  *
1715  * We don't want to use ->f_op->read methods, because generic file write
1716  *
1717  *         - serializes on ->i_sem, and
1718  *
1719  *         - does a lot of extra work like balance_dirty_pages(),
1720  *
1721  * which doesn't work for globally shared files like /last_rcvd.
1722  */
1723 static int osd_ldiskfs_readlink(struct inode *inode, char *buffer, int buflen)
1724 {
1725         struct ldiskfs_inode_info *ei = LDISKFS_I(inode);
1726
1727         memcpy(buffer, (char *)ei->i_data, buflen);
1728
1729         return  buflen;
1730 }
1731
1732 int osd_ldiskfs_read(struct inode *inode, void *buf, int size, loff_t *offs)
1733 {
1734         struct buffer_head *bh;
1735         unsigned long block;
1736         int osize;
1737         int blocksize;
1738         int csize;
1739         int boffs;
1740
1741         /* prevent reading after eof */
1742         spin_lock(&inode->i_lock);
1743         if (i_size_read(inode) < *offs + size) {
1744                 loff_t diff = i_size_read(inode) - *offs;
1745
1746                 spin_unlock(&inode->i_lock);
1747                 if (diff < 0) {
1748                         CDEBUG(D_OTHER,
1749                                "size %llu is too short to read @%llu\n",
1750                                i_size_read(inode), *offs);
1751                         return -EBADR;
1752                 } else if (diff == 0) {
1753                         return 0;
1754                 } else {
1755                         size = diff;
1756                 }
1757         } else {
1758                 spin_unlock(&inode->i_lock);
1759         }
1760
1761         blocksize = 1 << inode->i_blkbits;
1762         osize = size;
1763         while (size > 0) {
1764                 block = *offs >> inode->i_blkbits;
1765                 boffs = *offs & (blocksize - 1);
1766                 csize = min(blocksize - boffs, size);
1767                 bh = __ldiskfs_bread(NULL, inode, block, 0);
1768                 if (IS_ERR(bh)) {
1769                         CERROR("%s: can't read %u@%llu on ino %lu: rc = %ld\n",
1770                                osd_ino2name(inode), csize, *offs, inode->i_ino,
1771                                PTR_ERR(bh));
1772                         return PTR_ERR(bh);
1773                 }
1774
1775                 if (bh != NULL) {
1776                         memcpy(buf, bh->b_data + boffs, csize);
1777                         brelse(bh);
1778                 } else {
1779                         memset(buf, 0, csize);
1780                 }
1781
1782                 *offs += csize;
1783                 buf += csize;
1784                 size -= csize;
1785         }
1786         return osize;
1787 }
1788
1789 static ssize_t osd_read(const struct lu_env *env, struct dt_object *dt,
1790                         struct lu_buf *buf, loff_t *pos)
1791 {
1792         struct inode *inode = osd_dt_obj(dt)->oo_inode;
1793         int rc;
1794
1795         /* Read small symlink from inode body as we need to maintain correct
1796          * on-disk symlinks for ldiskfs.
1797          */
1798         if (S_ISLNK(dt->do_lu.lo_header->loh_attr)) {
1799                 loff_t size = i_size_read(inode);
1800
1801                 if (buf->lb_len < size)
1802                         return -EOVERFLOW;
1803
1804                 if (size < sizeof(LDISKFS_I(inode)->i_data))
1805                         rc = osd_ldiskfs_readlink(inode, buf->lb_buf, size);
1806                 else
1807                         rc = osd_ldiskfs_read(inode, buf->lb_buf, size, pos);
1808         } else {
1809                 rc = osd_ldiskfs_read(inode, buf->lb_buf, buf->lb_len, pos);
1810         }
1811
1812         return rc;
1813 }
1814
1815 static inline int osd_extents_enabled(struct super_block *sb,
1816                                       struct inode *inode)
1817 {
1818         if (inode != NULL) {
1819                 if (LDISKFS_I(inode)->i_flags & LDISKFS_EXTENTS_FL)
1820                         return 1;
1821         } else if (ldiskfs_has_feature_extents(sb)) {
1822                 return 1;
1823         }
1824         return 0;
1825 }
1826
1827 int osd_calc_bkmap_credits(struct super_block *sb, struct inode *inode,
1828                            const loff_t size, const loff_t pos,
1829                            const int blocks)
1830 {
1831         int credits, bits, bs, i;
1832
1833         bits = sb->s_blocksize_bits;
1834         bs = 1 << bits;
1835
1836         /* legacy blockmap: 3 levels * 3 (bitmap,gd,itself)
1837          * we do not expect blockmaps on the large files,
1838          * so let's shrink it to 2 levels (4GB files)
1839          */
1840
1841         /* this is default reservation: 2 levels */
1842         credits = (blocks + 2) * 3;
1843
1844         /* actual offset is unknown, hard to optimize */
1845         if (pos == -1)
1846                 return credits;
1847
1848         /* now check for few specific cases to optimize */
1849         if (pos + size <= LDISKFS_NDIR_BLOCKS * bs) {
1850                 /* no indirects */
1851                 credits = blocks;
1852                 /* allocate if not allocated */
1853                 if (inode == NULL) {
1854                         credits += blocks * 2;
1855                         return credits;
1856                 }
1857                 for (i = (pos >> bits); i < (pos >> bits) + blocks; i++) {
1858                         LASSERT(i < LDISKFS_NDIR_BLOCKS);
1859                         if (LDISKFS_I(inode)->i_data[i] == 0)
1860                                 credits += 2;
1861                 }
1862         } else if (pos + size <= (LDISKFS_NDIR_BLOCKS + 1024) * bs) {
1863                 /* single indirect */
1864                 credits = blocks * 3;
1865                 if (inode == NULL ||
1866                     LDISKFS_I(inode)->i_data[LDISKFS_IND_BLOCK] == 0)
1867                         credits += 3;
1868                 else
1869                         /* The indirect block may be modified. */
1870                         credits += 1;
1871         }
1872
1873         return credits;
1874 }
1875
1876 static ssize_t osd_declare_write(const struct lu_env *env, struct dt_object *dt,
1877                                  const struct lu_buf *buf, loff_t _pos,
1878                                  struct thandle *handle)
1879 {
1880         struct osd_object  *obj  = osd_dt_obj(dt);
1881         struct inode       *inode = obj->oo_inode;
1882         struct super_block *sb = osd_sb(osd_obj2dev(obj));
1883         struct osd_thandle *oh;
1884         int                 rc = 0, est = 0, credits, blocks, allocated = 0;
1885         int                 bits, bs;
1886         int                 depth, size;
1887         loff_t              pos;
1888         ENTRY;
1889
1890         LASSERT(buf != NULL);
1891         LASSERT(handle != NULL);
1892
1893         oh = container_of(handle, struct osd_thandle, ot_super);
1894         LASSERT(oh->ot_handle == NULL);
1895
1896         size = buf->lb_len;
1897         bits = sb->s_blocksize_bits;
1898         bs = 1 << bits;
1899
1900         if (_pos == -1) {
1901                 /* if this is an append, then we
1902                  * should expect cross-block record
1903                  */
1904                 pos = 0;
1905         } else {
1906                 pos = _pos;
1907         }
1908
1909         /* blocks to modify */
1910         blocks = ((pos + size + bs - 1) >> bits) - (pos >> bits);
1911         LASSERT(blocks > 0);
1912
1913         if (inode != NULL && _pos != -1) {
1914                 /* object size in blocks */
1915                 est = (i_size_read(inode) + bs - 1) >> bits;
1916                 allocated = inode->i_blocks >> (bits - 9);
1917                 if (pos + size <= i_size_read(inode) && est <= allocated) {
1918                         /* looks like an overwrite, no need to modify tree */
1919                         credits = blocks;
1920                         /* no need to modify i_size */
1921                         goto out;
1922                 }
1923         }
1924
1925         if (osd_extents_enabled(sb, inode)) {
1926                 /*
1927                  * many concurrent threads may grow tree by the time
1928                  * our transaction starts. so, consider 2 is a min depth
1929                  * for every level we may need to allocate a new block
1930                  * and take some entries from the old one. so, 3 blocks
1931                  * to allocate (bitmap, gd, itself) + old block - 4 per
1932                  * level.
1933                  */
1934                 depth = inode != NULL ? ext_depth(inode) : 0;
1935                 depth = max(depth, 1) + 1;
1936                 credits = depth;
1937                 /* if not append, then split may need to modify
1938                  * existing blocks moving entries into the new ones
1939                  */
1940                 if (_pos != -1)
1941                         credits += depth;
1942                 /* blocks to store data: bitmap,gd,itself */
1943                 credits += blocks * 3;
1944         } else {
1945                 credits = osd_calc_bkmap_credits(sb, inode, size, _pos, blocks);
1946         }
1947         /* if inode is created as part of the transaction,
1948          * then it's counted already by the creation method
1949          */
1950         if (inode != NULL)
1951                 credits++;
1952
1953 out:
1954
1955         osd_trans_declare_op(env, oh, OSD_OT_WRITE, credits);
1956
1957         /* dt_declare_write() is usually called for system objects, such
1958          * as llog or last_rcvd files. We needn't enforce quota on those
1959          * objects, so always set the lqi_space as 0.
1960          */
1961         if (inode != NULL)
1962                 rc = osd_declare_inode_qid(env, i_uid_read(inode),
1963                                            i_gid_read(inode),
1964                                            i_projid_read(inode), 0,
1965                                            oh, obj, NULL, OSD_QID_BLK);
1966
1967         if (rc == 0)
1968                 rc = osd_trunc_lock(obj, oh, true);
1969
1970         RETURN(rc);
1971 }
1972
1973 static int osd_ldiskfs_writelink(struct inode *inode, char *buffer, int buflen)
1974 {
1975         /* LU-2634: clear the extent format for fast symlink */
1976         ldiskfs_clear_inode_flag(inode, LDISKFS_INODE_EXTENTS);
1977
1978         memcpy((char *)&LDISKFS_I(inode)->i_data, (char *)buffer, buflen);
1979         spin_lock(&inode->i_lock);
1980         LDISKFS_I(inode)->i_disksize = buflen;
1981         i_size_write(inode, buflen);
1982         spin_unlock(&inode->i_lock);
1983         osd_dirty_inode(inode, I_DIRTY_DATASYNC);
1984
1985         return 0;
1986 }
1987
1988 static int osd_ldiskfs_write_record(struct dt_object *dt, void *buf,
1989                                     int bufsize, int write_NUL, loff_t *offs,
1990                                     handle_t *handle)
1991 {
1992         struct inode *inode = osd_dt_obj(dt)->oo_inode;
1993         struct buffer_head *bh        = NULL;
1994         loff_t              offset    = *offs;
1995         loff_t              new_size  = i_size_read(inode);
1996         unsigned long       block;
1997         int                 blocksize = 1 << inode->i_blkbits;
1998         struct ldiskfs_inode_info *ei = LDISKFS_I(inode);
1999         int                 err = 0;
2000         int                 size;
2001         int                 boffs;
2002         int                 dirty_inode = 0;
2003         bool create, sparse, sync = false;
2004
2005         if (write_NUL) {
2006                 /*
2007                  * long symlink write does not count the NUL terminator in
2008                  * bufsize, we write it, and the inode's file size does not
2009                  * count the NUL terminator as well.
2010                  */
2011                 ((char *)buf)[bufsize] = '\0';
2012                 ++bufsize;
2013         }
2014
2015         /* only the first flag-set matters */
2016         dirty_inode = !test_and_set_bit(LDISKFS_INODE_JOURNAL_DATA,
2017                                        &ei->i_flags);
2018
2019         /* sparse checking is racy, but sparse is very rare case, leave as is */
2020         sparse = (new_size > 0 && (inode->i_blocks >> (inode->i_blkbits - 9)) <
2021                   ((new_size - 1) >> inode->i_blkbits) + 1);
2022
2023         while (bufsize > 0) {
2024                 int credits = handle->h_buffer_credits;
2025                 unsigned long last_block = (new_size == 0) ? 0 :
2026                                            (new_size - 1) >> inode->i_blkbits;
2027
2028                 if (bh)
2029                         brelse(bh);
2030
2031                 block = offset >> inode->i_blkbits;
2032                 boffs = offset & (blocksize - 1);
2033                 size = min(blocksize - boffs, bufsize);
2034                 sync = (block > last_block || new_size == 0 || sparse);
2035
2036                 if (sync)
2037                         down(&ei->i_append_sem);
2038
2039                 bh = __ldiskfs_bread(handle, inode, block, 0);
2040
2041                 if (unlikely(IS_ERR_OR_NULL(bh) && !sync))
2042                         CWARN(
2043                               "%s: adding bh without locking off %llu (block %lu, size %d, offs %llu)\n",
2044                               osd_ino2name(inode),
2045                               offset, block, bufsize, *offs);
2046
2047                 if (IS_ERR_OR_NULL(bh)) {
2048                         struct osd_device *osd = osd_obj2dev(osd_dt_obj(dt));
2049                         int flags = LDISKFS_GET_BLOCKS_CREATE;
2050
2051                         /* while the file system is being mounted, avoid
2052                          * preallocation otherwise mount can take a long
2053                          * time as mballoc cache is cold.
2054                          * XXX: this is a workaround until we have a proper
2055                          *      fix in mballoc
2056                          * XXX: works with extent-based files only */
2057                         if (!osd->od_cl_seq)
2058                                 flags |= LDISKFS_GET_BLOCKS_NO_NORMALIZE;
2059                         bh = __ldiskfs_bread(handle, inode, block, flags);
2060                         create = true;
2061                 } else {
2062                         if (sync) {
2063                                 up(&ei->i_append_sem);
2064                                 sync = false;
2065                         }
2066                         create = false;
2067                 }
2068                 if (IS_ERR_OR_NULL(bh)) {
2069                         if (bh == NULL) {
2070                                 err = -EIO;
2071                         } else {
2072                                 err = PTR_ERR(bh);
2073                                 bh = NULL;
2074                         }
2075
2076                         CERROR(
2077                                "%s: error reading offset %llu (block %lu, size %d, offs %llu), credits %d/%d: rc = %d\n",
2078                                osd_ino2name(inode), offset, block, bufsize,
2079                                *offs, credits, handle->h_buffer_credits, err);
2080                         break;
2081                 }
2082
2083                 err = ldiskfs_journal_get_write_access(handle, bh);
2084                 if (err) {
2085                         CERROR("journal_get_write_access() returned error %d\n",
2086                                err);
2087                         break;
2088                 }
2089                 LASSERTF(boffs + size <= bh->b_size,
2090                          "boffs %d size %d bh->b_size %lu\n",
2091                          boffs, size, (unsigned long)bh->b_size);
2092                 if (create) {
2093                         memset(bh->b_data, 0, bh->b_size);
2094                         if (sync) {
2095                                 up(&ei->i_append_sem);
2096                                 sync = false;
2097                         }
2098                 }
2099                 memcpy(bh->b_data + boffs, buf, size);
2100                 err = ldiskfs_handle_dirty_metadata(handle, NULL, bh);
2101                 if (err)
2102                         break;
2103
2104                 if (offset + size > new_size)
2105                         new_size = offset + size;
2106                 offset += size;
2107                 bufsize -= size;
2108                 buf += size;
2109         }
2110         if (sync)
2111                 up(&ei->i_append_sem);
2112
2113         if (bh)
2114                 brelse(bh);
2115
2116         if (write_NUL)
2117                 --new_size;
2118         /* correct in-core and on-disk sizes */
2119         if (new_size > i_size_read(inode)) {
2120                 spin_lock(&inode->i_lock);
2121                 if (new_size > i_size_read(inode))
2122                         i_size_write(inode, new_size);
2123                 if (i_size_read(inode) > ei->i_disksize) {
2124                         ei->i_disksize = i_size_read(inode);
2125                         dirty_inode = 1;
2126                 }
2127                 spin_unlock(&inode->i_lock);
2128         }
2129         if (dirty_inode)
2130                 osd_dirty_inode(inode, I_DIRTY_DATASYNC);
2131
2132         if (err == 0)
2133                 *offs = offset;
2134         return err;
2135 }
2136
2137 static ssize_t osd_write(const struct lu_env *env, struct dt_object *dt,
2138                          const struct lu_buf *buf, loff_t *pos,
2139                          struct thandle *handle)
2140 {
2141         struct inode            *inode = osd_dt_obj(dt)->oo_inode;
2142         struct osd_thandle      *oh;
2143         ssize_t                 result;
2144         int                     is_link;
2145
2146         LASSERT(dt_object_exists(dt));
2147
2148         LASSERT(handle != NULL);
2149         LASSERT(inode != NULL);
2150         dquot_initialize(inode);
2151
2152         /* XXX: don't check: one declared chunk can be used many times */
2153         /* osd_trans_exec_op(env, handle, OSD_OT_WRITE); */
2154
2155         oh = container_of(handle, struct osd_thandle, ot_super);
2156         LASSERT(oh->ot_handle->h_transaction != NULL);
2157         osd_trans_exec_op(env, handle, OSD_OT_WRITE);
2158
2159         /* Write small symlink to inode body as we need to maintain correct
2160          * on-disk symlinks for ldiskfs.
2161          * Note: the buf->lb_buf contains a NUL terminator while buf->lb_len
2162          * does not count it in.
2163          */
2164         is_link = S_ISLNK(dt->do_lu.lo_header->loh_attr);
2165         if (is_link && (buf->lb_len < sizeof(LDISKFS_I(inode)->i_data)))
2166                 result = osd_ldiskfs_writelink(inode, buf->lb_buf, buf->lb_len);
2167         else
2168                 result = osd_ldiskfs_write_record(dt, buf->lb_buf, buf->lb_len,
2169                                                   is_link, pos, oh->ot_handle);
2170         if (result == 0)
2171                 result = buf->lb_len;
2172
2173         osd_trans_exec_check(env, handle, OSD_OT_WRITE);
2174
2175         return result;
2176 }
2177
2178 static int osd_declare_fallocate(const struct lu_env *env,
2179                                  struct dt_object *dt, __u64 start, __u64 end,
2180                                  int mode, struct thandle *th)
2181 {
2182         struct osd_thandle *oh = container_of(th, struct osd_thandle, ot_super);
2183         struct osd_device *osd = osd_obj2dev(osd_dt_obj(dt));
2184         struct inode *inode = osd_dt_obj(dt)->oo_inode;
2185         long long quota_space = 0;
2186         /* 5 is max tree depth. (inode + 4 index blocks) */
2187         int depth = 5;
2188         int rc;
2189
2190         ENTRY;
2191
2192         /*
2193          * mode == 0 (which is standard prealloc) and PUNCH is supported
2194          * Rest of mode options is not supported yet.
2195          */
2196         if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE))
2197                 RETURN(-EOPNOTSUPP);
2198
2199         /* disable fallocate completely */
2200         if (osd_dev(dt->do_lu.lo_dev)->od_fallocate_zero_blocks < 0)
2201                 RETURN(-EOPNOTSUPP);
2202
2203         LASSERT(th);
2204         LASSERT(inode);
2205
2206         if (mode & FALLOC_FL_PUNCH_HOLE) {
2207                 rc = osd_declare_inode_qid(env, i_uid_read(inode),
2208                                            i_gid_read(inode),
2209                                            i_projid_read(inode), 0, oh,
2210                                            osd_dt_obj(dt), NULL, OSD_QID_BLK);
2211                 if (rc == 0)
2212                         rc = osd_trunc_lock(osd_dt_obj(dt), oh, false);
2213                 RETURN(rc);
2214         }
2215
2216         /* quota space for metadata blocks
2217          * approximate metadata estimate should be good enough.
2218          */
2219         quota_space += PAGE_SIZE;
2220         quota_space += depth * LDISKFS_BLOCK_SIZE(osd_sb(osd));
2221
2222         /* quota space should be reported in 1K blocks */
2223         quota_space = toqb(quota_space) + toqb(end - start) +
2224                       LDISKFS_META_TRANS_BLOCKS(inode->i_sb);
2225
2226         /* We don't need to reserve credits for whole fallocate here.
2227          * We reserve space only for metadata. Fallocate credits are
2228          * extended as required
2229          */
2230         rc = osd_declare_inode_qid(env, i_uid_read(inode), i_gid_read(inode),
2231                                    i_projid_read(inode), quota_space, oh,
2232                                    osd_dt_obj(dt), NULL, OSD_QID_BLK);
2233         RETURN(rc);
2234 }
2235
2236 static int osd_fallocate_preallocate(const struct lu_env *env,
2237                                      struct dt_object *dt,
2238                                      __u64 start, __u64 end, int mode,
2239                                      struct thandle *th)
2240 {
2241         struct osd_thandle *oh = container_of(th, struct osd_thandle, ot_super);
2242         handle_t *handle = ldiskfs_journal_current_handle();
2243         unsigned int save_credits = oh->ot_credits;
2244         struct osd_object *obj = osd_dt_obj(dt);
2245         struct inode *inode = obj->oo_inode;
2246         struct ldiskfs_map_blocks map;
2247         unsigned int credits;
2248         ldiskfs_lblk_t blen;
2249         ldiskfs_lblk_t boff;
2250         loff_t new_size = 0;
2251         int depth = 0;
2252         int flags;
2253         int rc = 0;
2254
2255         ENTRY;
2256
2257         LASSERT(dt_object_exists(dt));
2258         LASSERT(osd_invariant(obj));
2259         LASSERT(inode != NULL);
2260
2261         CDEBUG(D_INODE, "fallocate: inode #%lu: start %llu end %llu mode %d\n",
2262                inode->i_ino, start, end, mode);
2263
2264         dquot_initialize(inode);
2265
2266         LASSERT(th);
2267
2268         boff = start >> inode->i_blkbits;
2269         blen = (ALIGN(end, 1 << inode->i_blkbits) >> inode->i_blkbits) - boff;
2270
2271         /* Create and mark new extents as either zero or unwritten */
2272         flags = osd_dev(dt->do_lu.lo_dev)->od_fallocate_zero_blocks ?
2273                 LDISKFS_GET_BLOCKS_CREATE_ZERO :
2274                 LDISKFS_GET_BLOCKS_CREATE_UNWRIT_EXT;
2275         if (mode & FALLOC_FL_KEEP_SIZE)
2276                 flags |= LDISKFS_GET_BLOCKS_KEEP_SIZE;
2277
2278         inode_lock(inode);
2279
2280         /*
2281          * We only support preallocation for extent-based file only.
2282          */
2283         if (!(ldiskfs_test_inode_flag(inode, LDISKFS_INODE_EXTENTS)))
2284                 GOTO(out, rc = -EOPNOTSUPP);
2285
2286         if (!(mode & FALLOC_FL_KEEP_SIZE) && (end > i_size_read(inode) ||
2287             end > LDISKFS_I(inode)->i_disksize)) {
2288                 new_size = end;
2289                 rc = inode_newsize_ok(inode, new_size);
2290                 if (rc)
2291                         GOTO(out, rc);
2292         }
2293
2294         inode_dio_wait(inode);
2295
2296         map.m_lblk = boff;
2297         map.m_len = blen;
2298
2299         /* Don't normalize the request if it can fit in one extent so
2300          * that it doesn't get unnecessarily split into multiple extents.
2301          */
2302         if (blen <= EXT_UNWRITTEN_MAX_LEN)
2303                 flags |= LDISKFS_GET_BLOCKS_NO_NORMALIZE;
2304
2305         /*
2306          * credits to insert 1 extent into extent tree.
2307          */
2308         credits = osd_chunk_trans_blocks(inode, blen);
2309         depth = ext_depth(inode);
2310
2311         while (rc >= 0 && blen) {
2312                 loff_t epos;
2313
2314                 /*
2315                  * Recalculate credits when extent tree depth changes.
2316                  */
2317                 if (depth != ext_depth(inode)) {
2318                         credits = osd_chunk_trans_blocks(inode, blen);
2319                         depth = ext_depth(inode);
2320                 }
2321
2322                 /* TODO: quota check */
2323                 rc = osd_extend_restart_trans(handle, credits, inode);
2324                 if (rc)
2325                         break;
2326
2327                 rc = ldiskfs_map_blocks(handle, inode, &map, flags);
2328                 if (rc <= 0) {
2329                         CDEBUG(D_INODE,
2330                                "inode #%lu: block %u: len %u: ldiskfs_map_blocks returned %d\n",
2331                                inode->i_ino, map.m_lblk, map.m_len, rc);
2332                         ldiskfs_mark_inode_dirty(handle, inode);
2333                         break;
2334                 }
2335
2336                 map.m_lblk += rc;
2337                 map.m_len = blen = blen - rc;
2338                 epos = (loff_t)map.m_lblk << inode->i_blkbits;
2339                 inode->i_ctime = current_time(inode);
2340                 if (new_size) {
2341                         if (epos > end)
2342                                 epos = end;
2343                         if (ldiskfs_update_inode_size(inode, epos) & 0x1)
2344                                 inode->i_mtime = inode->i_ctime;
2345                 } else {
2346                         if (epos > inode->i_size)
2347                                 ldiskfs_set_inode_flag(inode,
2348                                                        LDISKFS_INODE_EOFBLOCKS);
2349                 }
2350
2351                 ldiskfs_mark_inode_dirty(handle, inode);
2352         }
2353
2354 out:
2355         /* extand credits if needed for operations such as attribute set */
2356         if (rc >= 0)
2357                 rc = osd_extend_restart_trans(handle, save_credits, inode);
2358
2359         inode_unlock(inode);
2360
2361         RETURN(rc);
2362 }
2363
2364 static int osd_fallocate_punch(const struct lu_env *env, struct dt_object *dt,
2365                                __u64 start, __u64 end, int mode,
2366                                struct thandle *th)
2367 {
2368         struct osd_object *obj = osd_dt_obj(dt);
2369         struct inode *inode = obj->oo_inode;
2370         struct osd_access_lock *al;
2371         struct osd_thandle *oh;
2372         int rc = 0, found = 0;
2373
2374         ENTRY;
2375
2376         LASSERT(dt_object_exists(dt));
2377         LASSERT(osd_invariant(obj));
2378         LASSERT(inode != NULL);
2379
2380         dquot_initialize(inode);
2381
2382         LASSERT(th);
2383         oh = container_of(th, struct osd_thandle, ot_super);
2384         LASSERT(oh->ot_handle->h_transaction != NULL);
2385
2386         list_for_each_entry(al, &oh->ot_trunc_locks, tl_list) {
2387                 if (obj != al->tl_obj)
2388                         continue;
2389                 LASSERT(al->tl_shared == 0);
2390                 found = 1;
2391                 /* do actual punch in osd_trans_stop() */
2392                 al->tl_start = start;
2393                 al->tl_end = end;
2394                 al->tl_mode = mode;
2395                 al->tl_punch = true;
2396                 break;
2397         }
2398
2399         RETURN(rc);
2400 }
2401
2402 static int osd_fallocate(const struct lu_env *env, struct dt_object *dt,
2403                          __u64 start, __u64 end, int mode, struct thandle *th)
2404 {
2405         int rc;
2406
2407         ENTRY;
2408
2409         if (mode & FALLOC_FL_PUNCH_HOLE) {
2410                 /* punch */
2411                 rc = osd_fallocate_punch(env, dt, start, end, mode, th);
2412         } else {
2413                 /* standard preallocate */
2414                 rc = osd_fallocate_preallocate(env, dt, start, end, mode, th);
2415         }
2416         RETURN(rc);
2417 }
2418
2419 static int osd_declare_punch(const struct lu_env *env, struct dt_object *dt,
2420                              __u64 start, __u64 end, struct thandle *th)
2421 {
2422         struct osd_thandle *oh;
2423         struct inode       *inode;
2424         int                 rc;
2425         ENTRY;
2426
2427         LASSERT(th);
2428         oh = container_of(th, struct osd_thandle, ot_super);
2429
2430         /*
2431          * we don't need to reserve credits for whole truncate
2432          * it's not possible as truncate may need to free too many
2433          * blocks and that won't fit a single transaction. instead
2434          * we reserve credits to change i_size and put inode onto
2435          * orphan list. if needed truncate will extend or restart
2436          * transaction
2437          */
2438         osd_trans_declare_op(env, oh, OSD_OT_PUNCH,
2439                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE] + 3);
2440
2441         inode = osd_dt_obj(dt)->oo_inode;
2442         LASSERT(inode);
2443
2444         rc = osd_declare_inode_qid(env, i_uid_read(inode), i_gid_read(inode),
2445                                    i_projid_read(inode), 0, oh, osd_dt_obj(dt),
2446                                    NULL, OSD_QID_BLK);
2447
2448         if (rc == 0)
2449                 rc = osd_trunc_lock(osd_dt_obj(dt), oh, false);
2450
2451         RETURN(rc);
2452 }
2453
2454 static int osd_punch(const struct lu_env *env, struct dt_object *dt,
2455                      __u64 start, __u64 end, struct thandle *th)
2456 {
2457         struct osd_object *obj = osd_dt_obj(dt);
2458         struct osd_device *osd = osd_obj2dev(obj);
2459         struct inode *inode = obj->oo_inode;
2460         struct osd_access_lock *al;
2461         struct osd_thandle *oh;
2462         int rc = 0, found = 0;
2463         bool grow = false;
2464         ENTRY;
2465
2466         LASSERT(dt_object_exists(dt));
2467         LASSERT(osd_invariant(obj));
2468         LASSERT(inode != NULL);
2469         dquot_initialize(inode);
2470
2471         LASSERT(th);
2472         oh = container_of(th, struct osd_thandle, ot_super);
2473         LASSERT(oh->ot_handle->h_transaction != NULL);
2474
2475         /* we used to skip truncate to current size to
2476          * optimize truncates on OST. with DoM we can
2477          * get attr_set to set specific size (MDS_REINT)
2478          * and then get truncate RPC which essentially
2479          * would be skipped. this is bad.. so, disable
2480          * this optimization on MDS till the client stop
2481          * to sent MDS_REINT (LU-11033) -bzzz
2482          */
2483         if (osd->od_is_ost && i_size_read(inode) == start)
2484                 RETURN(0);
2485
2486         osd_trans_exec_op(env, th, OSD_OT_PUNCH);
2487
2488         spin_lock(&inode->i_lock);
2489         if (i_size_read(inode) < start)
2490                 grow = true;
2491         i_size_write(inode, start);
2492         spin_unlock(&inode->i_lock);
2493         /* if object holds encrypted content, we need to make sure we truncate
2494          * on an encryption unit boundary, or subsequent reads will get
2495          * corrupted content
2496          */
2497         if (obj->oo_lma_flags & LUSTRE_ENCRYPT_FL &&
2498             start & ~LUSTRE_ENCRYPTION_MASK)
2499                 start = (start & LUSTRE_ENCRYPTION_MASK) +
2500                         LUSTRE_ENCRYPTION_UNIT_SIZE;
2501         ll_truncate_pagecache(inode, start);
2502
2503         /* optimize grow case */
2504         if (grow) {
2505                 osd_execute_truncate(obj);
2506                 GOTO(out, rc);
2507         }
2508
2509         inode_lock(inode);
2510         /* add to orphan list to ensure truncate completion
2511          * if this transaction succeed. ldiskfs_truncate()
2512          * will take the inode out of the list
2513          */
2514         rc = ldiskfs_orphan_add(oh->ot_handle, inode);
2515         inode_unlock(inode);
2516         if (rc != 0)
2517                 GOTO(out, rc);
2518
2519         list_for_each_entry(al, &oh->ot_trunc_locks, tl_list) {
2520                 if (obj != al->tl_obj)
2521                         continue;
2522                 LASSERT(al->tl_shared == 0);
2523                 found = 1;
2524                 /* do actual truncate in osd_trans_stop() */
2525                 al->tl_truncate = 1;
2526                 break;
2527         }
2528         LASSERT(found);
2529
2530 out:
2531         RETURN(rc);
2532 }
2533
2534 static int fiemap_check_ranges(struct inode *inode,
2535                                u64 start, u64 len, u64 *new_len)
2536 {
2537         loff_t maxbytes;
2538
2539         *new_len = len;
2540
2541         if (len == 0)
2542                 return -EINVAL;
2543
2544         if (ldiskfs_test_inode_flag(inode, LDISKFS_INODE_EXTENTS))
2545                 maxbytes = inode->i_sb->s_maxbytes;
2546         else
2547                 maxbytes = LDISKFS_SB(inode->i_sb)->s_bitmap_maxbytes;
2548
2549         if (start > maxbytes)
2550                 return -EFBIG;
2551
2552         /*
2553          * Shrink request scope to what the fs can actually handle.
2554          */
2555         if (len > maxbytes || (maxbytes - len) < start)
2556                 *new_len = maxbytes - start;
2557
2558         return 0;
2559 }
2560
2561 /* So that the fiemap access checks can't overflow on 32 bit machines. */
2562 #define FIEMAP_MAX_EXTENTS     (UINT_MAX / sizeof(struct fiemap_extent))
2563
2564 static int osd_fiemap_get(const struct lu_env *env, struct dt_object *dt,
2565                           struct fiemap *fm)
2566 {
2567         struct fiemap_extent_info fieinfo = {0, };
2568         struct inode *inode = osd_dt_obj(dt)->oo_inode;
2569         u64 len;
2570         int rc;
2571
2572         LASSERT(inode);
2573         if (inode->i_op->fiemap == NULL)
2574                 return -EOPNOTSUPP;
2575
2576         if (fm->fm_extent_count > FIEMAP_MAX_EXTENTS)
2577                 return -EINVAL;
2578
2579         rc = fiemap_check_ranges(inode, fm->fm_start, fm->fm_length, &len);
2580         if (rc)
2581                 return rc;
2582
2583         fieinfo.fi_flags = fm->fm_flags;
2584         fieinfo.fi_extents_max = fm->fm_extent_count;
2585         fieinfo.fi_extents_start = fm->fm_extents;
2586
2587         if (fieinfo.fi_flags & FIEMAP_FLAG_SYNC)
2588                 filemap_write_and_wait(inode->i_mapping);
2589
2590         rc = inode->i_op->fiemap(inode, &fieinfo, fm->fm_start, len);
2591         fm->fm_flags = fieinfo.fi_flags;
2592         fm->fm_mapped_extents = fieinfo.fi_extents_mapped;
2593
2594         return rc;
2595 }
2596
2597 static int osd_ladvise(const struct lu_env *env, struct dt_object *dt,
2598                        __u64 start, __u64 end, enum lu_ladvise_type advice)
2599 {
2600         struct osd_object *obj = osd_dt_obj(dt);
2601         int rc = 0;
2602         ENTRY;
2603
2604         switch (advice) {
2605         case LU_LADVISE_DONTNEED:
2606                 if (end)
2607                         invalidate_mapping_pages(obj->oo_inode->i_mapping,
2608                                                  start >> PAGE_SHIFT,
2609                                                  (end - 1) >> PAGE_SHIFT);
2610                 break;
2611         default:
2612                 rc = -ENOTSUPP;
2613                 break;
2614         }
2615
2616         RETURN(rc);
2617 }
2618
2619 static loff_t osd_lseek(const struct lu_env *env, struct dt_object *dt,
2620                         loff_t offset, int whence)
2621 {
2622         struct osd_object *obj = osd_dt_obj(dt);
2623         struct inode *inode = obj->oo_inode;
2624         struct file *file;
2625         loff_t result;
2626
2627         ENTRY;
2628
2629         LASSERT(dt_object_exists(dt));
2630         LASSERT(osd_invariant(obj));
2631         LASSERT(inode);
2632         LASSERT(offset >= 0);
2633
2634         file = osd_quasi_file(env, inode);
2635         result = file->f_op->llseek(file, offset, whence);
2636
2637         /*
2638          * If 'offset' is beyond end of object file then treat it as not error
2639          * but valid case for SEEK_HOLE and return 'offset' as result.
2640          * LOV will decide if it is beyond real end of file or not.
2641          */
2642         if (whence == SEEK_HOLE && result == -ENXIO)
2643                 result = offset;
2644
2645         CDEBUG(D_INFO, "seek %s from %lld: %lld\n", whence == SEEK_HOLE ?
2646                        "hole" : "data", offset, result);
2647         RETURN(result);
2648 }
2649
2650 /*
2651  * in some cases we may need declare methods for objects being created
2652  * e.g., when we create symlink
2653  */
2654 const struct dt_body_operations osd_body_ops_new = {
2655         .dbo_declare_write = osd_declare_write,
2656 };
2657
2658 const struct dt_body_operations osd_body_ops = {
2659         .dbo_read                       = osd_read,
2660         .dbo_declare_write              = osd_declare_write,
2661         .dbo_write                      = osd_write,
2662         .dbo_bufs_get                   = osd_bufs_get,
2663         .dbo_bufs_put                   = osd_bufs_put,
2664         .dbo_write_prep                 = osd_write_prep,
2665         .dbo_declare_write_commit       = osd_declare_write_commit,
2666         .dbo_write_commit               = osd_write_commit,
2667         .dbo_read_prep                  = osd_read_prep,
2668         .dbo_declare_punch              = osd_declare_punch,
2669         .dbo_punch                      = osd_punch,
2670         .dbo_fiemap_get                 = osd_fiemap_get,
2671         .dbo_ladvise                    = osd_ladvise,
2672         .dbo_declare_fallocate          = osd_declare_fallocate,
2673         .dbo_fallocate                  = osd_fallocate,
2674         .dbo_lseek                      = osd_lseek,
2675 };
2676
2677 /**
2678  * Get a truncate lock
2679  *
2680  * In order to take multi-transaction truncate out of main transaction we let
2681  * the caller grab a lock on the object passed. the lock can be shared (for
2682  * writes) and exclusive (for truncate). It's not allowed to mix truncate
2683  * and write in the same transaction handle (do not confuse with big ldiskfs
2684  * transaction containing lots of handles).
2685  * The lock must be taken at declaration.
2686  *
2687  * \param obj           object to lock
2688  * \oh                  transaction
2689  * \shared              shared or exclusive
2690  *
2691  * \retval 0            lock is granted
2692  * \retval -NOMEM       no memory to allocate lock
2693  */
2694 int osd_trunc_lock(struct osd_object *obj, struct osd_thandle *oh, bool shared)
2695 {
2696         struct osd_access_lock *al, *tmp;
2697
2698         LASSERT(obj);
2699         LASSERT(oh);
2700
2701         list_for_each_entry(tmp, &oh->ot_trunc_locks, tl_list) {
2702                 if (tmp->tl_obj != obj)
2703                         continue;
2704                 LASSERT(tmp->tl_shared == shared);
2705                 /* found same lock */
2706                 return 0;
2707         }
2708
2709         OBD_ALLOC_PTR(al);
2710         if (unlikely(al == NULL))
2711                 return -ENOMEM;
2712         al->tl_obj = obj;
2713         al->tl_truncate = false;
2714         if (shared)
2715                 down_read(&obj->oo_ext_idx_sem);
2716         else
2717                 down_write(&obj->oo_ext_idx_sem);
2718         al->tl_shared = shared;
2719         lu_object_get(&obj->oo_dt.do_lu);
2720
2721         list_add(&al->tl_list, &oh->ot_trunc_locks);
2722
2723         return 0;
2724 }
2725
2726 void osd_trunc_unlock_all(const struct lu_env *env, struct list_head *list)
2727 {
2728         struct osd_access_lock *al, *tmp;
2729
2730         list_for_each_entry_safe(al, tmp, list, tl_list) {
2731                 if (al->tl_shared)
2732                         up_read(&al->tl_obj->oo_ext_idx_sem);
2733                 else
2734                         up_write(&al->tl_obj->oo_ext_idx_sem);
2735                 osd_object_put(env, al->tl_obj);
2736                 list_del(&al->tl_list);
2737                 OBD_FREE_PTR(al);
2738         }
2739 }
2740
2741 /*
2742  * For a partial-page truncate, flush the page to disk immediately to
2743  * avoid data corruption during direct disk write.  b=17397
2744  */
2745 static void osd_partial_page_flush(struct osd_device *d, struct inode *inode,
2746                                    loff_t offset)
2747 {
2748         if (!(offset & ~PAGE_MASK))
2749                 return;
2750
2751         if (osd_use_page_cache(d)) {
2752                 filemap_fdatawrite_range(inode->i_mapping, offset, offset + 1);
2753         } else {
2754                 /* Notice we use "wait" version to ensure I/O is complete */
2755                 filemap_write_and_wait_range(inode->i_mapping, offset,
2756                                              offset + 1);
2757                 invalidate_mapping_pages(inode->i_mapping, offset >> PAGE_SHIFT,
2758                                          offset >> PAGE_SHIFT);
2759         }
2760 }
2761
2762 void osd_execute_truncate(struct osd_object *obj)
2763 {
2764         struct osd_device *d = osd_obj2dev(obj);
2765         struct inode *inode = obj->oo_inode;
2766         __u64 size;
2767
2768         /* simulate crash before (in the middle) of delayed truncate */
2769         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_FAIL_AT_TRUNCATE)) {
2770                 struct ldiskfs_inode_info *ei = LDISKFS_I(inode);
2771                 struct ldiskfs_sb_info *sbi = LDISKFS_SB(inode->i_sb);
2772
2773                 mutex_lock(&sbi->s_orphan_lock);
2774                 list_del_init(&ei->i_orphan);
2775                 mutex_unlock(&sbi->s_orphan_lock);
2776                 return;
2777         }
2778
2779         size = i_size_read(inode);
2780         inode_lock(inode);
2781         /* if object holds encrypted content, we need to make sure we truncate
2782          * on an encryption unit boundary, or block content will get corrupted
2783          */
2784         if (obj->oo_lma_flags & LUSTRE_ENCRYPT_FL &&
2785             size & ~LUSTRE_ENCRYPTION_MASK)
2786                 inode->i_size = (size & LUSTRE_ENCRYPTION_MASK) +
2787                         LUSTRE_ENCRYPTION_UNIT_SIZE;
2788         ldiskfs_truncate(inode);
2789         inode_unlock(inode);
2790         if (inode->i_size != size) {
2791                 spin_lock(&inode->i_lock);
2792                 i_size_write(inode, size);
2793                 LDISKFS_I(inode)->i_disksize = size;
2794                 spin_unlock(&inode->i_lock);
2795                 osd_dirty_inode(inode, I_DIRTY_DATASYNC);
2796         }
2797         osd_partial_page_flush(d, inode, size);
2798 }
2799
2800 void osd_execute_punch(const struct lu_env *env, struct osd_object *obj,
2801                        loff_t start, loff_t end, int mode)
2802 {
2803         struct osd_device *d = osd_obj2dev(obj);
2804         struct inode *inode = obj->oo_inode;
2805         struct file *file = osd_quasi_file(env, inode);
2806
2807         file->f_op->fallocate(file, mode, start, end - start);
2808         osd_partial_page_flush(d, inode, start);
2809         osd_partial_page_flush(d, inode, end - 1);
2810 }
2811
2812 void osd_process_truncates(const struct lu_env *env, struct list_head *list)
2813 {
2814         struct osd_access_lock *al;
2815
2816         LASSERT(journal_current_handle() == NULL);
2817
2818         list_for_each_entry(al, list, tl_list) {
2819                 if (al->tl_shared)
2820                         continue;
2821                 if (al->tl_truncate)
2822                         osd_execute_truncate(al->tl_obj);
2823                 else if (al->tl_punch)
2824                         osd_execute_punch(env, al->tl_obj, al->tl_start,
2825                                           al->tl_end, al->tl_mode);
2826         }
2827 }