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