Whamcloud - gitweb
LU-16202 build: bio_alloc takes struct block_device
[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
1659         if (rc == 0)
1660                 rc = osd_trunc_lock(osd_dt_obj(dt), oh, true);
1661
1662         RETURN(rc);
1663 }
1664
1665 /* Check if a block is allocated or not */
1666 static int osd_write_commit(const struct lu_env *env, struct dt_object *dt,
1667                             struct niobuf_local *lnb, int npages,
1668                             struct thandle *thandle, __u64 user_size)
1669 {
1670         struct osd_thread_info *oti = osd_oti_get(env);
1671         struct osd_iobuf *iobuf = &oti->oti_iobuf;
1672         struct inode *inode = osd_dt_obj(dt)->oo_inode;
1673         struct osd_device  *osd = osd_obj2dev(osd_dt_obj(dt));
1674         int rc = 0, i, check_credits = 0;
1675
1676         LASSERT(inode);
1677
1678         rc = osd_init_iobuf(osd, iobuf, 1, npages);
1679         if (unlikely(rc != 0))
1680                 RETURN(rc);
1681
1682         dquot_initialize(inode);
1683
1684         for (i = 0; i < npages; i++) {
1685                 if (lnb[i].lnb_rc == -ENOSPC &&
1686                     (lnb[i].lnb_flags & OBD_BRW_MAPPED)) {
1687                         /* Allow the write to proceed if overwriting an
1688                          * existing block
1689                          */
1690                         lnb[i].lnb_rc = 0;
1691                 }
1692
1693                 if (lnb[i].lnb_rc) { /* ENOSPC, network RPC error, etc. */
1694                         CDEBUG(D_INODE, "Skipping [%d] == %d\n", i,
1695                                lnb[i].lnb_rc);
1696                         LASSERT(lnb[i].lnb_page);
1697                         generic_error_remove_page(inode->i_mapping,
1698                                                   lnb[i].lnb_page);
1699                         continue;
1700                 }
1701
1702                 if (lnb[i].lnb_flags & OBD_BRW_DONE)
1703                         continue;
1704
1705                 if (!(lnb[i].lnb_flags & OBD_BRW_MAPPED))
1706                         check_credits = 1;
1707
1708                 LASSERT(PageLocked(lnb[i].lnb_page));
1709                 LASSERT(!PageWriteback(lnb[i].lnb_page));
1710
1711                 /*
1712                  * Since write and truncate are serialized by oo_sem, even
1713                  * partial-page truncate should not leave dirty pages in the
1714                  * page cache.
1715                  */
1716                 LASSERT(!PageDirty(lnb[i].lnb_page));
1717
1718                 SetPageUptodate(lnb[i].lnb_page);
1719
1720                 osd_iobuf_add_page(iobuf, &lnb[i]);
1721         }
1722
1723         osd_trans_exec_op(env, thandle, OSD_OT_WRITE);
1724
1725         if (OBD_FAIL_CHECK(OBD_FAIL_OST_MAPBLK_ENOSPC)) {
1726                 rc = -ENOSPC;
1727         } else if (iobuf->dr_npages > 0) {
1728                 rc = osd_ldiskfs_map_inode_pages(inode, iobuf, osd,
1729                                                  1, user_size,
1730                                                  check_credits,
1731                                                  thandle);
1732         } else {
1733                 /* no pages to write, no transno is needed */
1734                 thandle->th_local = 1;
1735         }
1736
1737         if (rc != 0 && !thandle->th_restart_tran)
1738                 osd_fini_iobuf(osd, iobuf);
1739
1740         osd_trans_exec_check(env, thandle, OSD_OT_WRITE);
1741
1742         if (unlikely(rc != 0 && !thandle->th_restart_tran)) {
1743                 /* if write fails, we should drop pages from the cache */
1744                 for (i = 0; i < npages; i++) {
1745                         if (lnb[i].lnb_page == NULL)
1746                                 continue;
1747                         if (!PagePrivate2(lnb[i].lnb_page)) {
1748                                 LASSERT(PageLocked(lnb[i].lnb_page));
1749                                 generic_error_remove_page(inode->i_mapping,
1750                                                           lnb[i].lnb_page);
1751                         }
1752                 }
1753         }
1754
1755         RETURN(rc);
1756 }
1757
1758 static int osd_read_prep(const struct lu_env *env, struct dt_object *dt,
1759                          struct niobuf_local *lnb, int npages)
1760 {
1761         struct osd_thread_info *oti = osd_oti_get(env);
1762         struct osd_iobuf *iobuf = &oti->oti_iobuf;
1763         struct inode *inode = osd_dt_obj(dt)->oo_inode;
1764         struct osd_device *osd = osd_obj2dev(osd_dt_obj(dt));
1765         int rc = 0, i, cache_hits = 0, cache_misses = 0;
1766         ktime_t start, end;
1767         s64 timediff;
1768         loff_t isize;
1769
1770         LASSERT(inode);
1771
1772         rc = osd_init_iobuf(osd, iobuf, 0, npages);
1773         if (unlikely(rc != 0))
1774                 RETURN(rc);
1775
1776         isize = i_size_read(inode);
1777
1778         start = ktime_get();
1779         for (i = 0; i < npages; i++) {
1780
1781                 if (isize <= lnb[i].lnb_file_offset)
1782                         /* If there's no more data, abort early.
1783                          * lnb->lnb_rc == 0, so it's easy to detect later.
1784                          */
1785                         break;
1786
1787                 /* instead of looking if we go beyong isize, send complete
1788                  * pages all the time
1789                  */
1790                 lnb[i].lnb_rc = lnb[i].lnb_len;
1791
1792                 /* Bypass disk read if fail_loc is set properly */
1793                 if (OBD_FAIL_CHECK_QUIET(OBD_FAIL_OST_FAKE_RW))
1794                         SetPageUptodate(lnb[i].lnb_page);
1795
1796                 if (PageUptodate(lnb[i].lnb_page)) {
1797                         cache_hits++;
1798                         unlock_page(lnb[i].lnb_page);
1799                 } else {
1800                         cache_misses++;
1801                         osd_iobuf_add_page(iobuf, &lnb[i]);
1802                 }
1803                 /* no need to unlock in osd_bufs_put(), the sooner page is
1804                  * unlocked, the earlier another client can access it.
1805                  * notice real unlock_page() can be called few lines
1806                  * below after osd_do_bio(). lnb is a per-thread, so it's
1807                  * fine to have PG_locked and lnb_locked inconsistent here
1808                  */
1809                 lnb[i].lnb_locked = 0;
1810         }
1811         end = ktime_get();
1812         timediff = ktime_us_delta(end, start);
1813         lprocfs_counter_add(osd->od_stats, LPROC_OSD_GET_PAGE, timediff);
1814
1815         if (cache_hits != 0)
1816                 lprocfs_counter_add(osd->od_stats, LPROC_OSD_CACHE_HIT,
1817                                     cache_hits);
1818         if (cache_misses != 0)
1819                 lprocfs_counter_add(osd->od_stats, LPROC_OSD_CACHE_MISS,
1820                                     cache_misses);
1821         if (cache_hits + cache_misses != 0)
1822                 lprocfs_counter_add(osd->od_stats, LPROC_OSD_CACHE_ACCESS,
1823                                     cache_hits + cache_misses);
1824
1825         if (iobuf->dr_npages) {
1826                 rc = osd_ldiskfs_map_inode_pages(inode, iobuf, osd, 0,
1827                                                  0, 0, NULL);
1828                 if (!rc)
1829                         rc = osd_do_bio(osd, inode, iobuf, 0, 0);
1830
1831                 /* IO stats will be done in osd_bufs_put() */
1832
1833                 /* early release to let others read data during the bulk */
1834                 for (i = 0; i < iobuf->dr_npages; i++) {
1835                         LASSERT(PageLocked(iobuf->dr_pages[i]));
1836                         if (!PagePrivate2(iobuf->dr_pages[i]))
1837                                 unlock_page(iobuf->dr_pages[i]);
1838                 }
1839         }
1840
1841         RETURN(rc);
1842 }
1843
1844 /*
1845  * XXX: Another layering violation for now.
1846  *
1847  * We don't want to use ->f_op->read methods, because generic file write
1848  *
1849  *         - serializes on ->i_sem, and
1850  *
1851  *         - does a lot of extra work like balance_dirty_pages(),
1852  *
1853  * which doesn't work for globally shared files like /last_rcvd.
1854  */
1855 static int osd_ldiskfs_readlink(struct inode *inode, char *buffer, int buflen)
1856 {
1857         struct ldiskfs_inode_info *ei = LDISKFS_I(inode);
1858
1859         memcpy(buffer, (char *)ei->i_data, buflen);
1860
1861         return  buflen;
1862 }
1863
1864 int osd_ldiskfs_read(struct inode *inode, void *buf, int size, loff_t *offs)
1865 {
1866         struct buffer_head *bh;
1867         unsigned long block;
1868         int osize;
1869         int blocksize;
1870         int csize;
1871         int boffs;
1872
1873         /* prevent reading after eof */
1874         spin_lock(&inode->i_lock);
1875         if (i_size_read(inode) < *offs + size) {
1876                 loff_t diff = i_size_read(inode) - *offs;
1877
1878                 spin_unlock(&inode->i_lock);
1879                 if (diff < 0) {
1880                         CDEBUG(D_OTHER,
1881                                "size %llu is too short to read @%llu\n",
1882                                i_size_read(inode), *offs);
1883                         return -EBADR;
1884                 } else if (diff == 0) {
1885                         return 0;
1886                 } else {
1887                         size = diff;
1888                 }
1889         } else {
1890                 spin_unlock(&inode->i_lock);
1891         }
1892
1893         blocksize = 1 << inode->i_blkbits;
1894         osize = size;
1895         while (size > 0) {
1896                 block = *offs >> inode->i_blkbits;
1897                 boffs = *offs & (blocksize - 1);
1898                 csize = min(blocksize - boffs, size);
1899                 bh = __ldiskfs_bread(NULL, inode, block, 0);
1900                 if (IS_ERR(bh)) {
1901                         CERROR("%s: can't read %u@%llu on ino %lu: rc = %ld\n",
1902                                osd_ino2name(inode), csize, *offs, inode->i_ino,
1903                                PTR_ERR(bh));
1904                         return PTR_ERR(bh);
1905                 }
1906
1907                 if (bh != NULL) {
1908                         memcpy(buf, bh->b_data + boffs, csize);
1909                         brelse(bh);
1910                 } else {
1911                         memset(buf, 0, csize);
1912                 }
1913
1914                 *offs += csize;
1915                 buf += csize;
1916                 size -= csize;
1917         }
1918         return osize;
1919 }
1920
1921 static ssize_t osd_read(const struct lu_env *env, struct dt_object *dt,
1922                         struct lu_buf *buf, loff_t *pos)
1923 {
1924         struct inode *inode = osd_dt_obj(dt)->oo_inode;
1925         int rc;
1926
1927         /* Read small symlink from inode body as we need to maintain correct
1928          * on-disk symlinks for ldiskfs.
1929          */
1930         if (S_ISLNK(dt->do_lu.lo_header->loh_attr)) {
1931                 loff_t size = i_size_read(inode);
1932
1933                 if (buf->lb_len < size)
1934                         return -EOVERFLOW;
1935
1936                 if (size < sizeof(LDISKFS_I(inode)->i_data))
1937                         rc = osd_ldiskfs_readlink(inode, buf->lb_buf, size);
1938                 else
1939                         rc = osd_ldiskfs_read(inode, buf->lb_buf, size, pos);
1940         } else {
1941                 rc = osd_ldiskfs_read(inode, buf->lb_buf, buf->lb_len, pos);
1942         }
1943
1944         return rc;
1945 }
1946
1947 static inline int osd_extents_enabled(struct super_block *sb,
1948                                       struct inode *inode)
1949 {
1950         if (inode != NULL) {
1951                 if (LDISKFS_I(inode)->i_flags & LDISKFS_EXTENTS_FL)
1952                         return 1;
1953         } else if (ldiskfs_has_feature_extents(sb)) {
1954                 return 1;
1955         }
1956         return 0;
1957 }
1958
1959 int osd_calc_bkmap_credits(struct super_block *sb, struct inode *inode,
1960                            const loff_t size, const loff_t pos,
1961                            const int blocks)
1962 {
1963         int credits, bits, bs, i;
1964
1965         bits = sb->s_blocksize_bits;
1966         bs = 1 << bits;
1967
1968         /* legacy blockmap: 3 levels * 3 (bitmap,gd,itself)
1969          * we do not expect blockmaps on the large files,
1970          * so let's shrink it to 2 levels (4GB files)
1971          */
1972
1973         /* this is default reservation: 2 levels */
1974         credits = (blocks + 2) * 3;
1975
1976         /* actual offset is unknown, hard to optimize */
1977         if (pos == -1)
1978                 return credits;
1979
1980         /* now check for few specific cases to optimize */
1981         if (pos + size <= LDISKFS_NDIR_BLOCKS * bs) {
1982                 /* no indirects */
1983                 credits = blocks;
1984                 /* allocate if not allocated */
1985                 if (inode == NULL) {
1986                         credits += blocks * 2;
1987                         return credits;
1988                 }
1989                 for (i = (pos >> bits); i < (pos >> bits) + blocks; i++) {
1990                         LASSERT(i < LDISKFS_NDIR_BLOCKS);
1991                         if (LDISKFS_I(inode)->i_data[i] == 0)
1992                                 credits += 2;
1993                 }
1994         } else if (pos + size <= (LDISKFS_NDIR_BLOCKS + 1024) * bs) {
1995                 /* single indirect */
1996                 credits = blocks * 3;
1997                 if (inode == NULL ||
1998                     LDISKFS_I(inode)->i_data[LDISKFS_IND_BLOCK] == 0)
1999                         credits += 3;
2000                 else
2001                         /* The indirect block may be modified. */
2002                         credits += 1;
2003         }
2004
2005         return credits;
2006 }
2007
2008 static ssize_t osd_declare_write(const struct lu_env *env, struct dt_object *dt,
2009                                  const struct lu_buf *buf, loff_t _pos,
2010                                  struct thandle *handle)
2011 {
2012         struct osd_object  *obj  = osd_dt_obj(dt);
2013         struct inode       *inode = obj->oo_inode;
2014         struct super_block *sb = osd_sb(osd_obj2dev(obj));
2015         struct osd_thandle *oh;
2016         int                 rc = 0, est = 0, credits, blocks, allocated = 0;
2017         int                 bits, bs;
2018         int                 depth, size;
2019         loff_t              pos;
2020         ENTRY;
2021
2022         LASSERT(buf != NULL);
2023         LASSERT(handle != NULL);
2024
2025         oh = container_of(handle, struct osd_thandle, ot_super);
2026         LASSERT(oh->ot_handle == NULL);
2027
2028         size = buf->lb_len;
2029         bits = sb->s_blocksize_bits;
2030         bs = 1 << bits;
2031
2032         if (_pos == -1) {
2033                 /* if this is an append, then we
2034                  * should expect cross-block record
2035                  */
2036                 pos = 0;
2037         } else {
2038                 pos = _pos;
2039         }
2040
2041         /* blocks to modify */
2042         blocks = ((pos + size + bs - 1) >> bits) - (pos >> bits);
2043         LASSERT(blocks > 0);
2044
2045         if (inode != NULL && _pos != -1) {
2046                 /* object size in blocks */
2047                 est = (i_size_read(inode) + bs - 1) >> bits;
2048                 allocated = inode->i_blocks >> (bits - 9);
2049                 if (pos + size <= i_size_read(inode) && est <= allocated) {
2050                         /* looks like an overwrite, no need to modify tree */
2051                         credits = blocks;
2052                         /* no need to modify i_size */
2053                         goto out;
2054                 }
2055         }
2056
2057         if (osd_extents_enabled(sb, inode)) {
2058                 /*
2059                  * many concurrent threads may grow tree by the time
2060                  * our transaction starts. so, consider 2 is a min depth
2061                  * for every level we may need to allocate a new block
2062                  * and take some entries from the old one. so, 3 blocks
2063                  * to allocate (bitmap, gd, itself) + old block - 4 per
2064                  * level.
2065                  */
2066                 depth = inode != NULL ? ext_depth(inode) : 0;
2067                 depth = min(max(depth, 1) + 3, LDISKFS_MAX_EXTENT_DEPTH);
2068                 credits = depth;
2069                 /* if not append, then split may need to modify
2070                  * existing blocks moving entries into the new ones
2071                  */
2072                 if (_pos != -1)
2073                         credits += depth;
2074                 /* blocks to store data: bitmap,gd,itself */
2075                 credits += blocks * 3;
2076         } else {
2077                 credits = osd_calc_bkmap_credits(sb, inode, size, _pos, blocks);
2078         }
2079         /* if inode is created as part of the transaction,
2080          * then it's counted already by the creation method
2081          */
2082         if (inode != NULL)
2083                 credits++;
2084
2085 out:
2086
2087         osd_trans_declare_op(env, oh, OSD_OT_WRITE, credits);
2088
2089         /* dt_declare_write() is usually called for system objects, such
2090          * as llog or last_rcvd files. We needn't enforce quota on those
2091          * objects, so always set the lqi_space as 0.
2092          */
2093         if (inode != NULL)
2094                 rc = osd_declare_inode_qid(env, i_uid_read(inode),
2095                                            i_gid_read(inode),
2096                                            i_projid_read(inode), 0,
2097                                            oh, obj, NULL, OSD_QID_BLK);
2098
2099         if (rc == 0)
2100                 rc = osd_trunc_lock(obj, oh, true);
2101
2102         RETURN(rc);
2103 }
2104
2105 static int osd_ldiskfs_writelink(struct inode *inode, char *buffer, int buflen)
2106 {
2107         /* LU-2634: clear the extent format for fast symlink */
2108         ldiskfs_clear_inode_flag(inode, LDISKFS_INODE_EXTENTS);
2109
2110         /* Copying the NUL byte terminating the link target as well */
2111         memcpy((char *)&LDISKFS_I(inode)->i_data, (char *)buffer, buflen + 1);
2112         spin_lock(&inode->i_lock);
2113         LDISKFS_I(inode)->i_disksize = buflen;
2114         i_size_write(inode, buflen);
2115         spin_unlock(&inode->i_lock);
2116         osd_dirty_inode(inode, I_DIRTY_DATASYNC);
2117
2118         return 0;
2119 }
2120
2121 static int osd_ldiskfs_write_record(struct dt_object *dt, void *buf,
2122                                     int bufsize, int write_NUL, loff_t *offs,
2123                                     handle_t *handle)
2124 {
2125         struct inode *inode = osd_dt_obj(dt)->oo_inode;
2126         struct buffer_head *bh        = NULL;
2127         loff_t              offset    = *offs;
2128         loff_t              new_size  = i_size_read(inode);
2129         unsigned long       block;
2130         int                 blocksize = 1 << inode->i_blkbits;
2131         struct ldiskfs_inode_info *ei = LDISKFS_I(inode);
2132         int                 err = 0;
2133         int                 size;
2134         int                 boffs;
2135         int                 dirty_inode = 0;
2136         bool create, sparse, sync = false;
2137
2138         if (write_NUL) {
2139                 /*
2140                  * long symlink write does not count the NUL terminator in
2141                  * bufsize, we write it, and the inode's file size does not
2142                  * count the NUL terminator as well.
2143                  */
2144                 ((char *)buf)[bufsize] = '\0';
2145                 ++bufsize;
2146         }
2147
2148         /* only the first flag-set matters */
2149         dirty_inode = !test_and_set_bit(LDISKFS_INODE_JOURNAL_DATA,
2150                                        &ei->i_flags);
2151
2152         /* sparse checking is racy, but sparse is very rare case, leave as is */
2153         sparse = (new_size > 0 && (inode->i_blocks >> (inode->i_blkbits - 9)) <
2154                   ((new_size - 1) >> inode->i_blkbits) + 1);
2155
2156         while (bufsize > 0) {
2157                 int credits = handle->h_buffer_credits;
2158                 unsigned long last_block = (new_size == 0) ? 0 :
2159                                            (new_size - 1) >> inode->i_blkbits;
2160
2161                 if (bh)
2162                         brelse(bh);
2163
2164                 block = offset >> inode->i_blkbits;
2165                 boffs = offset & (blocksize - 1);
2166                 size = min(blocksize - boffs, bufsize);
2167                 sync = (block > last_block || new_size == 0 || sparse);
2168
2169                 if (sync)
2170                         down(&ei->i_append_sem);
2171
2172                 bh = __ldiskfs_bread(handle, inode, block, 0);
2173
2174                 if (unlikely(IS_ERR_OR_NULL(bh) && !sync))
2175                         CWARN(
2176                               "%s: adding bh without locking off %llu (block %lu, size %d, offs %llu)\n",
2177                               osd_ino2name(inode),
2178                               offset, block, bufsize, *offs);
2179
2180                 if (IS_ERR_OR_NULL(bh)) {
2181                         struct osd_device *osd = osd_obj2dev(osd_dt_obj(dt));
2182                         int flags = LDISKFS_GET_BLOCKS_CREATE;
2183
2184                         /* while the file system is being mounted, avoid
2185                          * preallocation otherwise mount can take a long
2186                          * time as mballoc cache is cold.
2187                          * XXX: this is a workaround until we have a proper
2188                          *      fix in mballoc
2189                          * XXX: works with extent-based files only */
2190                         if (!osd->od_cl_seq)
2191                                 flags |= LDISKFS_GET_BLOCKS_NO_NORMALIZE;
2192                         bh = __ldiskfs_bread(handle, inode, block, flags);
2193                         create = true;
2194                 } else {
2195                         if (sync) {
2196                                 up(&ei->i_append_sem);
2197                                 sync = false;
2198                         }
2199                         create = false;
2200                 }
2201                 if (IS_ERR_OR_NULL(bh)) {
2202                         if (bh == NULL) {
2203                                 err = -EIO;
2204                         } else {
2205                                 err = PTR_ERR(bh);
2206                                 bh = NULL;
2207                         }
2208
2209                         CERROR(
2210                                "%s: error reading offset %llu (block %lu, size %d, offs %llu), credits %d/%d: rc = %d\n",
2211                                osd_ino2name(inode), offset, block, bufsize,
2212                                *offs, credits, handle->h_buffer_credits, err);
2213                         break;
2214                 }
2215
2216                 err = osd_ldiskfs_journal_get_write_access(handle, inode->i_sb,
2217                                                            bh,
2218                                                            LDISKFS_JTR_NONE);
2219                 if (err) {
2220                         CERROR("journal_get_write_access() returned error %d\n",
2221                                err);
2222                         break;
2223                 }
2224                 LASSERTF(boffs + size <= bh->b_size,
2225                          "boffs %d size %d bh->b_size %lu\n",
2226                          boffs, size, (unsigned long)bh->b_size);
2227                 if (create) {
2228                         memset(bh->b_data, 0, bh->b_size);
2229                         if (sync) {
2230                                 up(&ei->i_append_sem);
2231                                 sync = false;
2232                         }
2233                 }
2234                 memcpy(bh->b_data + boffs, buf, size);
2235                 err = ldiskfs_handle_dirty_metadata(handle, NULL, bh);
2236                 if (err)
2237                         break;
2238
2239                 if (offset + size > new_size)
2240                         new_size = offset + size;
2241                 offset += size;
2242                 bufsize -= size;
2243                 buf += size;
2244         }
2245         if (sync)
2246                 up(&ei->i_append_sem);
2247
2248         if (bh)
2249                 brelse(bh);
2250
2251         if (write_NUL)
2252                 --new_size;
2253         /* correct in-core and on-disk sizes */
2254         if (new_size > i_size_read(inode)) {
2255                 spin_lock(&inode->i_lock);
2256                 if (new_size > i_size_read(inode))
2257                         i_size_write(inode, new_size);
2258                 if (i_size_read(inode) > ei->i_disksize) {
2259                         ei->i_disksize = i_size_read(inode);
2260                         dirty_inode = 1;
2261                 }
2262                 spin_unlock(&inode->i_lock);
2263         }
2264         if (dirty_inode)
2265                 osd_dirty_inode(inode, I_DIRTY_DATASYNC);
2266
2267         if (err == 0)
2268                 *offs = offset;
2269         return err;
2270 }
2271
2272 static ssize_t osd_write(const struct lu_env *env, struct dt_object *dt,
2273                          const struct lu_buf *buf, loff_t *pos,
2274                          struct thandle *handle)
2275 {
2276         struct inode            *inode = osd_dt_obj(dt)->oo_inode;
2277         struct osd_thandle      *oh;
2278         ssize_t                 result;
2279         int                     is_link;
2280
2281         LASSERT(dt_object_exists(dt));
2282
2283         LASSERT(handle != NULL);
2284         LASSERT(inode != NULL);
2285         dquot_initialize(inode);
2286
2287         /* XXX: don't check: one declared chunk can be used many times */
2288         /* osd_trans_exec_op(env, handle, OSD_OT_WRITE); */
2289
2290         oh = container_of(handle, struct osd_thandle, ot_super);
2291         LASSERT(oh->ot_handle->h_transaction != NULL);
2292         osd_trans_exec_op(env, handle, OSD_OT_WRITE);
2293
2294         /* Write small symlink to inode body as we need to maintain correct
2295          * on-disk symlinks for ldiskfs.
2296          * Note: the buf->lb_buf contains a NUL terminator while buf->lb_len
2297          * does not count it in.
2298          */
2299         is_link = S_ISLNK(dt->do_lu.lo_header->loh_attr);
2300         if (is_link && (buf->lb_len < sizeof(LDISKFS_I(inode)->i_data)))
2301                 result = osd_ldiskfs_writelink(inode, buf->lb_buf, buf->lb_len);
2302         else
2303                 result = osd_ldiskfs_write_record(dt, buf->lb_buf, buf->lb_len,
2304                                                   is_link, pos, oh->ot_handle);
2305         if (result == 0)
2306                 result = buf->lb_len;
2307
2308         osd_trans_exec_check(env, handle, OSD_OT_WRITE);
2309
2310         return result;
2311 }
2312
2313 static int osd_declare_fallocate(const struct lu_env *env,
2314                                  struct dt_object *dt, __u64 start, __u64 end,
2315                                  int mode, struct thandle *th)
2316 {
2317         struct osd_thandle *oh = container_of(th, struct osd_thandle, ot_super);
2318         struct osd_device *osd = osd_obj2dev(osd_dt_obj(dt));
2319         struct inode *inode = osd_dt_obj(dt)->oo_inode;
2320         long long quota_space = 0;
2321         /* 5 is max tree depth. (inode + 4 index blocks) */
2322         int depth = 5;
2323         int rc;
2324
2325         ENTRY;
2326
2327         /*
2328          * mode == 0 (which is standard prealloc) and PUNCH is supported
2329          * Rest of mode options is not supported yet.
2330          */
2331         if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE))
2332                 RETURN(-EOPNOTSUPP);
2333
2334         /* disable fallocate completely */
2335         if (osd_dev(dt->do_lu.lo_dev)->od_fallocate_zero_blocks < 0)
2336                 RETURN(-EOPNOTSUPP);
2337
2338         LASSERT(th);
2339         LASSERT(inode);
2340
2341         if (mode & FALLOC_FL_PUNCH_HOLE) {
2342                 rc = osd_declare_inode_qid(env, i_uid_read(inode),
2343                                            i_gid_read(inode),
2344                                            i_projid_read(inode), 0, oh,
2345                                            osd_dt_obj(dt), NULL, OSD_QID_BLK);
2346                 if (rc == 0)
2347                         rc = osd_trunc_lock(osd_dt_obj(dt), oh, false);
2348                 RETURN(rc);
2349         }
2350
2351         /* quota space for metadata blocks
2352          * approximate metadata estimate should be good enough.
2353          */
2354         quota_space += PAGE_SIZE;
2355         quota_space += depth * LDISKFS_BLOCK_SIZE(osd_sb(osd));
2356
2357         /* quota space should be reported in 1K blocks */
2358         quota_space = toqb(quota_space) + toqb(end - start) +
2359                       LDISKFS_META_TRANS_BLOCKS(inode->i_sb);
2360
2361         /* We don't need to reserve credits for whole fallocate here.
2362          * We reserve space only for metadata. Fallocate credits are
2363          * extended as required
2364          */
2365         rc = osd_declare_inode_qid(env, i_uid_read(inode), i_gid_read(inode),
2366                                    i_projid_read(inode), quota_space, oh,
2367                                    osd_dt_obj(dt), NULL, OSD_QID_BLK);
2368         RETURN(rc);
2369 }
2370
2371 static int osd_fallocate_preallocate(const struct lu_env *env,
2372                                      struct dt_object *dt,
2373                                      __u64 start, __u64 end, int mode,
2374                                      struct thandle *th)
2375 {
2376         struct osd_thandle *oh = container_of(th, struct osd_thandle, ot_super);
2377         handle_t *handle = ldiskfs_journal_current_handle();
2378         unsigned int save_credits = oh->ot_credits;
2379         struct osd_object *obj = osd_dt_obj(dt);
2380         struct inode *inode = obj->oo_inode;
2381         struct ldiskfs_map_blocks map;
2382         unsigned int credits;
2383         ldiskfs_lblk_t blen;
2384         ldiskfs_lblk_t boff;
2385         loff_t new_size = 0;
2386         int depth = 0;
2387         int flags;
2388         int rc = 0;
2389
2390         ENTRY;
2391
2392         LASSERT(dt_object_exists(dt));
2393         LASSERT(osd_invariant(obj));
2394         LASSERT(inode != NULL);
2395
2396         CDEBUG(D_INODE, "fallocate: inode #%lu: start %llu end %llu mode %d\n",
2397                inode->i_ino, start, end, mode);
2398
2399         dquot_initialize(inode);
2400
2401         LASSERT(th);
2402
2403         boff = start >> inode->i_blkbits;
2404         blen = (ALIGN(end, 1 << inode->i_blkbits) >> inode->i_blkbits) - boff;
2405
2406         /* Create and mark new extents as either zero or unwritten */
2407         flags = (osd_dev(dt->do_lu.lo_dev)->od_fallocate_zero_blocks ||
2408                  !ldiskfs_test_inode_flag(inode, LDISKFS_INODE_EXTENTS)) ?
2409                 LDISKFS_GET_BLOCKS_CREATE_ZERO :
2410                 LDISKFS_GET_BLOCKS_CREATE_UNWRIT_EXT;
2411 #ifdef LDISKFS_GET_BLOCKS_KEEP_SIZE
2412         if (mode & FALLOC_FL_KEEP_SIZE)
2413                 flags |= LDISKFS_GET_BLOCKS_KEEP_SIZE;
2414 #endif
2415         inode_lock(inode);
2416
2417         if (!(mode & FALLOC_FL_KEEP_SIZE) && (end > i_size_read(inode) ||
2418             end > LDISKFS_I(inode)->i_disksize)) {
2419                 new_size = end;
2420                 rc = inode_newsize_ok(inode, new_size);
2421                 if (rc)
2422                         GOTO(out, rc);
2423         }
2424
2425         inode_dio_wait(inode);
2426
2427         map.m_lblk = boff;
2428         map.m_len = blen;
2429
2430         /* Don't normalize the request if it can fit in one extent so
2431          * that it doesn't get unnecessarily split into multiple extents.
2432          */
2433         if (blen <= EXT_UNWRITTEN_MAX_LEN)
2434                 flags |= LDISKFS_GET_BLOCKS_NO_NORMALIZE;
2435
2436         /*
2437          * credits to insert 1 extent into extent tree.
2438          */
2439         credits = osd_chunk_trans_blocks(inode, blen);
2440         depth = ext_depth(inode);
2441
2442         while (rc >= 0 && blen) {
2443                 loff_t epos;
2444
2445                 /*
2446                  * Recalculate credits when extent tree depth changes.
2447                  */
2448                 if (depth != ext_depth(inode)) {
2449                         credits = osd_chunk_trans_blocks(inode, blen);
2450                         depth = ext_depth(inode);
2451                 }
2452
2453                 /* TODO: quota check */
2454                 rc = osd_extend_restart_trans(handle, credits, inode);
2455                 if (rc)
2456                         break;
2457
2458                 rc = ldiskfs_map_blocks(handle, inode, &map, flags);
2459                 if (rc <= 0) {
2460                         CDEBUG(D_INODE,
2461                                "inode #%lu: block %u: len %u: ldiskfs_map_blocks returned %d\n",
2462                                inode->i_ino, map.m_lblk, map.m_len, rc);
2463                         ldiskfs_mark_inode_dirty(handle, inode);
2464                         break;
2465                 }
2466
2467                 map.m_lblk += rc;
2468                 map.m_len = blen = blen - rc;
2469                 epos = (loff_t)map.m_lblk << inode->i_blkbits;
2470                 inode->i_ctime = current_time(inode);
2471                 if (new_size) {
2472                         if (epos > end)
2473                                 epos = end;
2474                         if (ldiskfs_update_inode_size(inode, epos) & 0x1)
2475                                 inode->i_mtime = inode->i_ctime;
2476 #ifdef LDISKFS_EOFBLOCKS_FL
2477                 } else {
2478                         if (epos > inode->i_size)
2479                                 ldiskfs_set_inode_flag(inode,
2480                                                        LDISKFS_INODE_EOFBLOCKS);
2481 #endif
2482                 }
2483
2484                 ldiskfs_mark_inode_dirty(handle, inode);
2485         }
2486
2487 out:
2488         /* extand credits if needed for operations such as attribute set */
2489         if (rc >= 0)
2490                 rc = osd_extend_restart_trans(handle, save_credits, inode);
2491
2492         inode_unlock(inode);
2493
2494         RETURN(rc);
2495 }
2496
2497 static int osd_fallocate_punch(const struct lu_env *env, struct dt_object *dt,
2498                                __u64 start, __u64 end, int mode,
2499                                struct thandle *th)
2500 {
2501         struct osd_object *obj = osd_dt_obj(dt);
2502         struct inode *inode = obj->oo_inode;
2503         struct osd_access_lock *al;
2504         struct osd_thandle *oh;
2505         int rc = 0, found = 0;
2506
2507         ENTRY;
2508
2509         LASSERT(dt_object_exists(dt));
2510         LASSERT(osd_invariant(obj));
2511         LASSERT(inode != NULL);
2512
2513         dquot_initialize(inode);
2514
2515         LASSERT(th);
2516         oh = container_of(th, struct osd_thandle, ot_super);
2517         LASSERT(oh->ot_handle->h_transaction != NULL);
2518
2519         list_for_each_entry(al, &oh->ot_trunc_locks, tl_list) {
2520                 if (obj != al->tl_obj)
2521                         continue;
2522                 LASSERT(al->tl_shared == 0);
2523                 found = 1;
2524                 /* do actual punch in osd_trans_stop() */
2525                 al->tl_start = start;
2526                 al->tl_end = end;
2527                 al->tl_mode = mode;
2528                 al->tl_punch = true;
2529                 break;
2530         }
2531
2532         RETURN(rc);
2533 }
2534
2535 static int osd_fallocate(const struct lu_env *env, struct dt_object *dt,
2536                          __u64 start, __u64 end, int mode, struct thandle *th)
2537 {
2538         int rc;
2539
2540         ENTRY;
2541
2542         if (mode & FALLOC_FL_PUNCH_HOLE) {
2543                 /* punch */
2544                 rc = osd_fallocate_punch(env, dt, start, end, mode, th);
2545         } else {
2546                 /* standard preallocate */
2547                 rc = osd_fallocate_preallocate(env, dt, start, end, mode, th);
2548         }
2549         RETURN(rc);
2550 }
2551
2552 static int osd_declare_punch(const struct lu_env *env, struct dt_object *dt,
2553                              __u64 start, __u64 end, struct thandle *th)
2554 {
2555         struct osd_thandle *oh;
2556         struct osd_object  *obj = osd_dt_obj(dt);
2557         struct inode       *inode;
2558         int                 rc;
2559         ENTRY;
2560
2561         LASSERT(th);
2562         oh = container_of(th, struct osd_thandle, ot_super);
2563
2564         /*
2565          * we don't need to reserve credits for whole truncate
2566          * it's not possible as truncate may need to free too many
2567          * blocks and that won't fit a single transaction. instead
2568          * we reserve credits to change i_size and put inode onto
2569          * orphan list. if needed truncate will extend or restart
2570          * transaction
2571          */
2572         osd_trans_declare_op(env, oh, OSD_OT_PUNCH,
2573                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE] + 3);
2574
2575         inode = obj->oo_inode;
2576         LASSERT(inode);
2577
2578         rc = osd_declare_inode_qid(env, i_uid_read(inode), i_gid_read(inode),
2579                                    i_projid_read(inode), 0, oh, obj,
2580                                    NULL, OSD_QID_BLK);
2581
2582         /* if object holds encrypted content, we need to make sure we truncate
2583          * on an encryption unit boundary, or subsequent reads will get
2584          * corrupted content
2585          */
2586         if (rc == 0) {
2587                 if (obj->oo_lma_flags & LUSTRE_ENCRYPT_FL &&
2588                     start & ~LUSTRE_ENCRYPTION_MASK)
2589                         start = (start & LUSTRE_ENCRYPTION_MASK) +
2590                                 LUSTRE_ENCRYPTION_UNIT_SIZE;
2591                 ll_truncate_pagecache(inode, start);
2592                 rc = osd_trunc_lock(obj, oh, false);
2593         }
2594
2595         RETURN(rc);
2596 }
2597
2598 static int osd_punch(const struct lu_env *env, struct dt_object *dt,
2599                      __u64 start, __u64 end, struct thandle *th)
2600 {
2601         struct osd_object *obj = osd_dt_obj(dt);
2602         struct osd_device *osd = osd_obj2dev(obj);
2603         struct inode *inode = obj->oo_inode;
2604         struct osd_access_lock *al;
2605         struct osd_thandle *oh;
2606         int rc = 0, found = 0;
2607         bool grow = false;
2608         ENTRY;
2609
2610         LASSERT(dt_object_exists(dt));
2611         LASSERT(osd_invariant(obj));
2612         LASSERT(inode != NULL);
2613         dquot_initialize(inode);
2614
2615         LASSERT(th);
2616         oh = container_of(th, struct osd_thandle, ot_super);
2617         LASSERT(oh->ot_handle->h_transaction != NULL);
2618
2619         /* we used to skip truncate to current size to
2620          * optimize truncates on OST. with DoM we can
2621          * get attr_set to set specific size (MDS_REINT)
2622          * and then get truncate RPC which essentially
2623          * would be skipped. this is bad.. so, disable
2624          * this optimization on MDS till the client stop
2625          * to sent MDS_REINT (LU-11033) -bzzz
2626          */
2627         if (osd->od_is_ost && i_size_read(inode) == start)
2628                 RETURN(0);
2629
2630         osd_trans_exec_op(env, th, OSD_OT_PUNCH);
2631
2632         spin_lock(&inode->i_lock);
2633         if (i_size_read(inode) < start)
2634                 grow = true;
2635         i_size_write(inode, start);
2636         spin_unlock(&inode->i_lock);
2637
2638         /* optimize grow case */
2639         if (grow) {
2640                 osd_execute_truncate(obj);
2641                 GOTO(out, rc);
2642         }
2643
2644         inode_lock(inode);
2645         /* add to orphan list to ensure truncate completion
2646          * if this transaction succeed. ldiskfs_truncate()
2647          * will take the inode out of the list
2648          */
2649         rc = ldiskfs_orphan_add(oh->ot_handle, inode);
2650         inode_unlock(inode);
2651         if (rc != 0)
2652                 GOTO(out, rc);
2653
2654         list_for_each_entry(al, &oh->ot_trunc_locks, tl_list) {
2655                 if (obj != al->tl_obj)
2656                         continue;
2657                 LASSERT(al->tl_shared == 0);
2658                 found = 1;
2659                 /* do actual truncate in osd_trans_stop() */
2660                 al->tl_truncate = 1;
2661                 break;
2662         }
2663         LASSERT(found);
2664
2665 out:
2666         RETURN(rc);
2667 }
2668
2669 static int fiemap_check_ranges(struct inode *inode,
2670                                u64 start, u64 len, u64 *new_len)
2671 {
2672         loff_t maxbytes;
2673
2674         *new_len = len;
2675
2676         if (len == 0)
2677                 return -EINVAL;
2678
2679         if (ldiskfs_test_inode_flag(inode, LDISKFS_INODE_EXTENTS))
2680                 maxbytes = inode->i_sb->s_maxbytes;
2681         else
2682                 maxbytes = LDISKFS_SB(inode->i_sb)->s_bitmap_maxbytes;
2683
2684         if (start > maxbytes)
2685                 return -EFBIG;
2686
2687         /*
2688          * Shrink request scope to what the fs can actually handle.
2689          */
2690         if (len > maxbytes || (maxbytes - len) < start)
2691                 *new_len = maxbytes - start;
2692
2693         return 0;
2694 }
2695
2696 /* So that the fiemap access checks can't overflow on 32 bit machines. */
2697 #define FIEMAP_MAX_EXTENTS     (UINT_MAX / sizeof(struct fiemap_extent))
2698
2699 static int osd_fiemap_get(const struct lu_env *env, struct dt_object *dt,
2700                           struct fiemap *fm)
2701 {
2702         struct fiemap_extent_info fieinfo = {0, };
2703         struct inode *inode = osd_dt_obj(dt)->oo_inode;
2704         u64 len;
2705         int rc;
2706         DECLARE_MM_SEGMENT_T(saved_fs);
2707
2708         LASSERT(inode);
2709         if (inode->i_op->fiemap == NULL)
2710                 return -EOPNOTSUPP;
2711
2712         if (fm->fm_extent_count > FIEMAP_MAX_EXTENTS)
2713                 return -EINVAL;
2714
2715         rc = fiemap_check_ranges(inode, fm->fm_start, fm->fm_length, &len);
2716         if (rc)
2717                 return rc;
2718
2719         fieinfo.fi_flags = fm->fm_flags;
2720         fieinfo.fi_extents_max = fm->fm_extent_count;
2721         fieinfo.fi_extents_start = fm->fm_extents;
2722
2723         if (fieinfo.fi_flags & FIEMAP_FLAG_SYNC)
2724                 filemap_write_and_wait(inode->i_mapping);
2725
2726         access_set_kernel(saved_fs, &fieinfo);
2727         rc = inode->i_op->fiemap(inode, &fieinfo, fm->fm_start, len);
2728         access_unset_kernel(saved_fs, &fieinfo);
2729         fm->fm_flags = fieinfo.fi_flags;
2730         fm->fm_mapped_extents = fieinfo.fi_extents_mapped;
2731
2732         return rc;
2733 }
2734
2735 static int osd_ladvise(const struct lu_env *env, struct dt_object *dt,
2736                        __u64 start, __u64 end, enum lu_ladvise_type advice)
2737 {
2738         struct osd_object *obj = osd_dt_obj(dt);
2739         int rc = 0;
2740         ENTRY;
2741
2742         switch (advice) {
2743         case LU_LADVISE_DONTNEED:
2744                 if (end)
2745                         invalidate_mapping_pages(obj->oo_inode->i_mapping,
2746                                                  start >> PAGE_SHIFT,
2747                                                  (end - 1) >> PAGE_SHIFT);
2748                 break;
2749         default:
2750                 rc = -ENOTSUPP;
2751                 break;
2752         }
2753
2754         RETURN(rc);
2755 }
2756
2757 static loff_t osd_lseek(const struct lu_env *env, struct dt_object *dt,
2758                         loff_t offset, int whence)
2759 {
2760         struct osd_object *obj = osd_dt_obj(dt);
2761         struct osd_device *dev = osd_obj2dev(obj);
2762         struct inode *inode = obj->oo_inode;
2763         struct file *file;
2764         loff_t result;
2765
2766         ENTRY;
2767         LASSERT(dt_object_exists(dt));
2768         LASSERT(osd_invariant(obj));
2769         LASSERT(inode);
2770         LASSERT(offset >= 0);
2771
2772         file = alloc_file_pseudo(inode, dev->od_mnt, "/", O_NOATIME,
2773                                  inode->i_fop);
2774         if (IS_ERR(file))
2775                 RETURN(PTR_ERR(file));
2776
2777         file->f_mode |= FMODE_64BITHASH;
2778         result = file->f_op->llseek(file, offset, whence);
2779         ihold(inode);
2780         fput(file);
2781         /*
2782          * If 'offset' is beyond end of object file then treat it as not error
2783          * but valid case for SEEK_HOLE and return 'offset' as result.
2784          * LOV will decide if it is beyond real end of file or not.
2785          */
2786         if (whence == SEEK_HOLE && result == -ENXIO)
2787                 result = offset;
2788
2789         CDEBUG(D_INFO, "seek %s from %lld: %lld\n", whence == SEEK_HOLE ?
2790                        "hole" : "data", offset, result);
2791         RETURN(result);
2792 }
2793
2794 /*
2795  * in some cases we may need declare methods for objects being created
2796  * e.g., when we create symlink
2797  */
2798 const struct dt_body_operations osd_body_ops_new = {
2799         .dbo_declare_write = osd_declare_write,
2800 };
2801
2802 const struct dt_body_operations osd_body_ops = {
2803         .dbo_read                       = osd_read,
2804         .dbo_declare_write              = osd_declare_write,
2805         .dbo_write                      = osd_write,
2806         .dbo_bufs_get                   = osd_bufs_get,
2807         .dbo_bufs_put                   = osd_bufs_put,
2808         .dbo_write_prep                 = osd_write_prep,
2809         .dbo_declare_write_commit       = osd_declare_write_commit,
2810         .dbo_write_commit               = osd_write_commit,
2811         .dbo_read_prep                  = osd_read_prep,
2812         .dbo_declare_punch              = osd_declare_punch,
2813         .dbo_punch                      = osd_punch,
2814         .dbo_fiemap_get                 = osd_fiemap_get,
2815         .dbo_ladvise                    = osd_ladvise,
2816         .dbo_declare_fallocate          = osd_declare_fallocate,
2817         .dbo_fallocate                  = osd_fallocate,
2818         .dbo_lseek                      = osd_lseek,
2819 };
2820
2821 /**
2822  * Get a truncate lock
2823  *
2824  * In order to take multi-transaction truncate out of main transaction we let
2825  * the caller grab a lock on the object passed. the lock can be shared (for
2826  * writes) and exclusive (for truncate). It's not allowed to mix truncate
2827  * and write in the same transaction handle (do not confuse with big ldiskfs
2828  * transaction containing lots of handles).
2829  * The lock must be taken at declaration.
2830  *
2831  * \param obj           object to lock
2832  * \oh                  transaction
2833  * \shared              shared or exclusive
2834  *
2835  * \retval 0            lock is granted
2836  * \retval -NOMEM       no memory to allocate lock
2837  */
2838 int osd_trunc_lock(struct osd_object *obj, struct osd_thandle *oh, bool shared)
2839 {
2840         struct osd_access_lock *al, *tmp;
2841
2842         LASSERT(obj);
2843         LASSERT(oh);
2844
2845         list_for_each_entry(tmp, &oh->ot_trunc_locks, tl_list) {
2846                 if (tmp->tl_obj != obj)
2847                         continue;
2848                 LASSERT(tmp->tl_shared == shared);
2849                 /* found same lock */
2850                 return 0;
2851         }
2852
2853         OBD_ALLOC_PTR(al);
2854         if (unlikely(al == NULL))
2855                 return -ENOMEM;
2856         al->tl_obj = obj;
2857         al->tl_truncate = false;
2858         if (shared)
2859                 down_read(&obj->oo_ext_idx_sem);
2860         else
2861                 down_write(&obj->oo_ext_idx_sem);
2862         al->tl_shared = shared;
2863         lu_object_get(&obj->oo_dt.do_lu);
2864
2865         list_add(&al->tl_list, &oh->ot_trunc_locks);
2866
2867         return 0;
2868 }
2869
2870 void osd_trunc_unlock_all(const struct lu_env *env, struct list_head *list)
2871 {
2872         struct osd_access_lock *al, *tmp;
2873
2874         list_for_each_entry_safe(al, tmp, list, tl_list) {
2875                 if (al->tl_shared)
2876                         up_read(&al->tl_obj->oo_ext_idx_sem);
2877                 else
2878                         up_write(&al->tl_obj->oo_ext_idx_sem);
2879                 osd_object_put(env, al->tl_obj);
2880                 list_del(&al->tl_list);
2881                 OBD_FREE_PTR(al);
2882         }
2883 }
2884
2885 /* For a partial-page punch, flush punch range to disk immediately */
2886 static void osd_partial_page_flush_punch(struct osd_device *d,
2887                                          struct inode *inode, loff_t start,
2888                                          loff_t end)
2889 {
2890         if (osd_use_page_cache(d)) {
2891                 filemap_fdatawrite_range(inode->i_mapping, start, end);
2892         } else {
2893                 /* Notice we use "wait" version to ensure I/O is complete */
2894                 filemap_write_and_wait_range(inode->i_mapping, start,
2895                                              end);
2896                 invalidate_mapping_pages(inode->i_mapping, start >> PAGE_SHIFT,
2897                                          end >> PAGE_SHIFT);
2898         }
2899 }
2900
2901 /*
2902  * For a partial-page truncate, flush the page to disk immediately to
2903  * avoid data corruption during direct disk write.  b=17397
2904  */
2905 static void osd_partial_page_flush(struct osd_device *d, struct inode *inode,
2906                                    loff_t offset)
2907 {
2908         if (!(offset & ~PAGE_MASK))
2909                 return;
2910
2911         if (osd_use_page_cache(d)) {
2912                 filemap_fdatawrite_range(inode->i_mapping, offset, offset + 1);
2913         } else {
2914                 /* Notice we use "wait" version to ensure I/O is complete */
2915                 filemap_write_and_wait_range(inode->i_mapping, offset,
2916                                              offset + 1);
2917                 invalidate_mapping_pages(inode->i_mapping, offset >> PAGE_SHIFT,
2918                                          offset >> PAGE_SHIFT);
2919         }
2920 }
2921
2922 void osd_execute_truncate(struct osd_object *obj)
2923 {
2924         struct osd_device *d = osd_obj2dev(obj);
2925         struct inode *inode = obj->oo_inode;
2926         __u64 size;
2927
2928         /* simulate crash before (in the middle) of delayed truncate */
2929         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_FAIL_AT_TRUNCATE)) {
2930                 struct ldiskfs_inode_info *ei = LDISKFS_I(inode);
2931                 struct ldiskfs_sb_info *sbi = LDISKFS_SB(inode->i_sb);
2932
2933                 mutex_lock(&sbi->s_orphan_lock);
2934                 list_del_init(&ei->i_orphan);
2935                 mutex_unlock(&sbi->s_orphan_lock);
2936                 return;
2937         }
2938
2939         size = i_size_read(inode);
2940         inode_lock(inode);
2941         /* if object holds encrypted content, we need to make sure we truncate
2942          * on an encryption unit boundary, or block content will get corrupted
2943          */
2944         if (obj->oo_lma_flags & LUSTRE_ENCRYPT_FL &&
2945             size & ~LUSTRE_ENCRYPTION_MASK)
2946                 inode->i_size = (size & LUSTRE_ENCRYPTION_MASK) +
2947                         LUSTRE_ENCRYPTION_UNIT_SIZE;
2948         ldiskfs_truncate(inode);
2949         inode_unlock(inode);
2950         if (inode->i_size != size) {
2951                 spin_lock(&inode->i_lock);
2952                 i_size_write(inode, size);
2953                 LDISKFS_I(inode)->i_disksize = size;
2954                 spin_unlock(&inode->i_lock);
2955                 osd_dirty_inode(inode, I_DIRTY_DATASYNC);
2956         }
2957         osd_partial_page_flush(d, inode, size);
2958 }
2959
2960 static int osd_execute_punch(const struct lu_env *env, struct osd_object *obj,
2961                              loff_t start, loff_t end, int mode)
2962 {
2963         struct osd_device *d = osd_obj2dev(obj);
2964         struct inode *inode = obj->oo_inode;
2965         struct file *file;
2966         int rc;
2967
2968         file = alloc_file_pseudo(inode, d->od_mnt, "/", O_NOATIME,
2969                                  inode->i_fop);
2970         if (IS_ERR(file))
2971                 RETURN(PTR_ERR(file));
2972
2973         file->f_mode |= FMODE_64BITHASH;
2974         rc = file->f_op->fallocate(file, mode, start, end - start);
2975         ihold(inode);
2976         fput(file);
2977         if (rc == 0)
2978                 osd_partial_page_flush_punch(d, inode, start, end - 1);
2979         return rc;
2980 }
2981
2982 int osd_process_truncates(const struct lu_env *env, struct list_head *list)
2983 {
2984         struct osd_access_lock *al;
2985         int rc = 0;
2986
2987         LASSERT(!journal_current_handle());
2988
2989         list_for_each_entry(al, list, tl_list) {
2990                 if (al->tl_shared)
2991                         continue;
2992                 if (al->tl_truncate)
2993                         osd_execute_truncate(al->tl_obj);
2994                 else if (al->tl_punch)
2995                         rc = osd_execute_punch(env, al->tl_obj, al->tl_start,
2996                                                al->tl_end, al->tl_mode);
2997         }
2998
2999         return rc;
3000 }