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