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