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