Whamcloud - gitweb
34090a8556d8a991948163f320172aad0818ffca
[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  * Lustre is a trademark of Sun Microsystems, Inc.
31  *
32  * lustre/osd/osd_io.c
33  *
34  * body operations
35  *
36  * Author: Nikita Danilov <nikita@clusterfs.com>
37  * Author: Alex Zhuravlev <bzzz@whamcloud.com>
38  *
39  */
40
41 /* prerequisite for linux/xattr.h */
42 #include <linux/types.h>
43 /* prerequisite for linux/xattr.h */
44 #include <linux/fs.h>
45 #include <linux/mm.h>
46 #include <linux/pagevec.h>
47
48 /*
49  * struct OBD_{ALLOC,FREE}*()
50  * OBD_FAIL_CHECK
51  */
52 #include <obd_support.h>
53
54 #include "osd_internal.h"
55
56 /* ext_depth() */
57 #include <ldiskfs/ldiskfs_extents.h>
58
59 static inline bool osd_use_page_cache(struct osd_device *d)
60 {
61         /* do not use pagecache if write and read caching are disabled */
62         if (d->od_writethrough_cache + d->od_read_cache == 0)
63                 return false;
64         /* use pagecache by default */
65         return true;
66 }
67
68 static int __osd_init_iobuf(struct osd_device *d, struct osd_iobuf *iobuf,
69                             int rw, int line, int pages)
70 {
71         int blocks, i;
72
73         LASSERTF(iobuf->dr_elapsed_valid == 0,
74                  "iobuf %p, reqs %d, rw %d, line %d\n", iobuf,
75                  atomic_read(&iobuf->dr_numreqs), iobuf->dr_rw,
76                  iobuf->dr_init_at);
77         LASSERT(pages <= PTLRPC_MAX_BRW_PAGES);
78
79         init_waitqueue_head(&iobuf->dr_wait);
80         atomic_set(&iobuf->dr_numreqs, 0);
81         iobuf->dr_npages = 0;
82         iobuf->dr_error = 0;
83         iobuf->dr_dev = d;
84         iobuf->dr_frags = 0;
85         iobuf->dr_elapsed = ktime_set(0, 0);
86         /* must be counted before, so assert */
87         iobuf->dr_rw = rw;
88         iobuf->dr_init_at = line;
89
90         blocks = pages * (PAGE_SIZE >> osd_sb(d)->s_blocksize_bits);
91         if (iobuf->dr_bl_buf.lb_len >= blocks * sizeof(iobuf->dr_blocks[0])) {
92                 LASSERT(iobuf->dr_pg_buf.lb_len >=
93                         pages * sizeof(iobuf->dr_pages[0]));
94                 return 0;
95         }
96
97         /* start with 1MB for 4K blocks */
98         i = 256;
99         while (i <= PTLRPC_MAX_BRW_PAGES && i < pages)
100                 i <<= 1;
101
102         CDEBUG(D_OTHER, "realloc %u for %u (%u) pages\n",
103                (unsigned)(pages * sizeof(iobuf->dr_pages[0])), i, pages);
104         pages = i;
105         blocks = pages * (PAGE_SIZE >> osd_sb(d)->s_blocksize_bits);
106         iobuf->dr_max_pages = 0;
107         CDEBUG(D_OTHER, "realloc %u for %u blocks\n",
108                (unsigned)(blocks * sizeof(iobuf->dr_blocks[0])), blocks);
109
110         lu_buf_realloc(&iobuf->dr_bl_buf, blocks * sizeof(iobuf->dr_blocks[0]));
111         iobuf->dr_blocks = iobuf->dr_bl_buf.lb_buf;
112         if (unlikely(iobuf->dr_blocks == NULL))
113                 return -ENOMEM;
114
115         lu_buf_realloc(&iobuf->dr_pg_buf, pages * sizeof(iobuf->dr_pages[0]));
116         iobuf->dr_pages = iobuf->dr_pg_buf.lb_buf;
117         if (unlikely(iobuf->dr_pages == NULL))
118                 return -ENOMEM;
119
120         lu_buf_realloc(&iobuf->dr_lnb_buf,
121                        pages * sizeof(iobuf->dr_lnbs[0]));
122         iobuf->dr_lnbs = iobuf->dr_lnb_buf.lb_buf;
123         if (unlikely(iobuf->dr_lnbs == NULL))
124                 return -ENOMEM;
125
126         iobuf->dr_max_pages = pages;
127
128         return 0;
129 }
130 #define osd_init_iobuf(dev, iobuf, rw, pages) \
131         __osd_init_iobuf(dev, iobuf, rw, __LINE__, pages)
132
133 static void osd_iobuf_add_page(struct osd_iobuf *iobuf,
134                                struct niobuf_local *lnb)
135 {
136         LASSERT(iobuf->dr_npages < iobuf->dr_max_pages);
137         iobuf->dr_pages[iobuf->dr_npages] = lnb->lnb_page;
138         iobuf->dr_lnbs[iobuf->dr_npages] = lnb;
139         iobuf->dr_npages++;
140 }
141
142 void osd_fini_iobuf(struct osd_device *d, struct osd_iobuf *iobuf)
143 {
144         int rw = iobuf->dr_rw;
145
146         if (iobuf->dr_elapsed_valid) {
147                 iobuf->dr_elapsed_valid = 0;
148                 LASSERT(iobuf->dr_dev == d);
149                 LASSERT(iobuf->dr_frags > 0);
150                 lprocfs_oh_tally(&d->od_brw_stats.
151                                  hist[BRW_R_DIO_FRAGS+rw],
152                                  iobuf->dr_frags);
153                 lprocfs_oh_tally_log2(&d->od_brw_stats.hist[BRW_R_IO_TIME+rw],
154                                       ktime_to_ms(iobuf->dr_elapsed));
155         }
156 }
157
158 #ifdef HAVE_BIO_ENDIO_USES_ONE_ARG
159 static void dio_complete_routine(struct bio *bio)
160 {
161         int error = bio->bi_status;
162 #else
163 static void dio_complete_routine(struct bio *bio, int error)
164 {
165 #endif
166         struct osd_iobuf *iobuf = bio->bi_private;
167         struct bio_vec *bvl;
168
169         /* CAVEAT EMPTOR: possibly in IRQ context
170          * DO NOT record procfs stats here!!! */
171
172         if (unlikely(iobuf == NULL)) {
173                 CERROR("***** bio->bi_private is NULL!  This should never "
174                        "happen.  Normally, I would crash here, but instead I "
175                        "will dump the bio contents to the console.  Please "
176                        "report this to <https://jira.whamcloud.com/> , along "
177                        "with any interesting messages leading up to this point "
178                        "(like SCSI errors, perhaps).  Because bi_private is "
179                        "NULL, I can't wake up the thread that initiated this "
180                        "IO - you will probably have to reboot this node.\n");
181                 CERROR("bi_next: %p, bi_flags: %lx, " __stringify(bi_opf)
182                        ": %x, bi_vcnt: %d, bi_idx: %d, bi->size: %d, bi_end_io: %p, bi_cnt: %d, bi_private: %p\n",
183                        bio->bi_next, (unsigned long)bio->bi_flags,
184                        (unsigned int)bio->bi_opf, bio->bi_vcnt, bio_idx(bio),
185                        bio_sectors(bio) << 9, bio->bi_end_io,
186                        atomic_read(&bio->__bi_cnt),
187                        bio->bi_private);
188                 return;
189         }
190
191         /* the check is outside of the cycle for performance reason -bzzz */
192         if (!bio_data_dir(bio)) {
193                 DECLARE_BVEC_ITER_ALL(iter_all);
194
195                 bio_for_each_segment_all(bvl, bio, iter_all) {
196                         if (likely(error == 0))
197                                 SetPageUptodate(bvl_to_page(bvl));
198                         LASSERT(PageLocked(bvl_to_page(bvl)));
199                 }
200                 atomic_dec(&iobuf->dr_dev->od_r_in_flight);
201         } else {
202                 atomic_dec(&iobuf->dr_dev->od_w_in_flight);
203         }
204
205         /* any real error is good enough -bzzz */
206         if (error != 0 && iobuf->dr_error == 0)
207                 iobuf->dr_error = error;
208
209         /*
210          * set dr_elapsed before dr_numreqs turns to 0, otherwise
211          * it's possible that service thread will see dr_numreqs
212          * is zero, but dr_elapsed is not set yet, leading to lost
213          * data in this processing and an assertion in a subsequent
214          * call to OSD.
215          */
216         if (atomic_read(&iobuf->dr_numreqs) == 1) {
217                 ktime_t now = ktime_get();
218
219                 iobuf->dr_elapsed = ktime_sub(now, iobuf->dr_start_time);
220                 iobuf->dr_elapsed_valid = 1;
221         }
222         if (atomic_dec_and_test(&iobuf->dr_numreqs))
223                 wake_up(&iobuf->dr_wait);
224
225         /* Completed bios used to be chained off iobuf->dr_bios and freed in
226          * filter_clear_dreq().  It was then possible to exhaust the biovec-256
227          * mempool when serious on-disk fragmentation was encountered,
228          * deadlocking the OST.  The bios are now released as soon as complete
229          * so the pool cannot be exhausted while IOs are competing. bug 10076 */
230         bio_put(bio);
231 }
232
233 static void record_start_io(struct osd_iobuf *iobuf, int size)
234 {
235         struct osd_device    *osd = iobuf->dr_dev;
236         struct obd_histogram *h = osd->od_brw_stats.hist;
237
238         iobuf->dr_frags++;
239         atomic_inc(&iobuf->dr_numreqs);
240
241         if (iobuf->dr_rw == 0) {
242                 atomic_inc(&osd->od_r_in_flight);
243                 lprocfs_oh_tally(&h[BRW_R_RPC_HIST],
244                                  atomic_read(&osd->od_r_in_flight));
245                 lprocfs_oh_tally_log2(&h[BRW_R_DISK_IOSIZE], size);
246         } else if (iobuf->dr_rw == 1) {
247                 atomic_inc(&osd->od_w_in_flight);
248                 lprocfs_oh_tally(&h[BRW_W_RPC_HIST],
249                                  atomic_read(&osd->od_w_in_flight));
250                 lprocfs_oh_tally_log2(&h[BRW_W_DISK_IOSIZE], size);
251         } else {
252                 LBUG();
253         }
254 }
255
256 static void osd_submit_bio(int rw, struct bio *bio)
257 {
258         LASSERTF(rw == 0 || rw == 1, "%x\n", rw);
259 #ifdef HAVE_SUBMIT_BIO_2ARGS
260         submit_bio(rw ? WRITE : READ, bio);
261 #else
262         bio->bi_opf |= rw;
263         submit_bio(bio);
264 #endif
265 }
266
267 static int can_be_merged(struct bio *bio, sector_t sector)
268 {
269         if (bio == NULL)
270                 return 0;
271
272         return bio_end_sector(bio) == sector ? 1 : 0;
273 }
274
275 #if IS_ENABLED(CONFIG_BLK_DEV_INTEGRITY)
276 /*
277  * This function will change the data written, thus it should only be
278  * used when checking data integrity feature
279  */
280 static void bio_integrity_fault_inject(struct bio *bio)
281 {
282         struct bio_vec *bvec;
283         DECLARE_BVEC_ITER_ALL(iter_all);
284         void *kaddr;
285         char *addr;
286
287         bio_for_each_segment_all(bvec, bio, iter_all) {
288                 struct page *page = bvec->bv_page;
289
290                 kaddr = kmap(page);
291                 addr = kaddr;
292                 *addr = ~(*addr);
293                 kunmap(page);
294                 break;
295         }
296 }
297
298 static int bio_dif_compare(__u16 *expected_guard_buf, void *bio_prot_buf,
299                            unsigned int sectors, int tuple_size)
300 {
301         __u16 *expected_guard;
302         __u16 *bio_guard;
303         int i;
304
305         expected_guard = expected_guard_buf;
306         for (i = 0; i < sectors; i++) {
307                 bio_guard = (__u16 *)bio_prot_buf;
308                 if (*bio_guard != *expected_guard) {
309                         CERROR("unexpected guard tags on sector %d "
310                                "expected guard %u, bio guard "
311                                "%u, sectors %u, tuple size %d\n",
312                                i, *expected_guard, *bio_guard, sectors,
313                                tuple_size);
314                         return -EIO;
315                 }
316                 expected_guard++;
317                 bio_prot_buf += tuple_size;
318         }
319         return 0;
320 }
321
322 static int osd_bio_integrity_compare(struct bio *bio, struct block_device *bdev,
323                                      struct osd_iobuf *iobuf, int index)
324 {
325         struct blk_integrity *bi = bdev_get_integrity(bdev);
326         struct bio_integrity_payload *bip = bio->bi_integrity;
327         struct niobuf_local *lnb;
328         unsigned short sector_size = blk_integrity_interval(bi);
329         void *bio_prot_buf = page_address(bip->bip_vec->bv_page) +
330                 bip->bip_vec->bv_offset;
331         struct bio_vec *bv;
332         sector_t sector = bio_start_sector(bio);
333         unsigned int sectors, total;
334         DECLARE_BVEC_ITER_ALL(iter_all);
335         __u16 *expected_guard;
336         int rc;
337
338         total = 0;
339         bio_for_each_segment_all(bv, bio, iter_all) {
340                 lnb = iobuf->dr_lnbs[index];
341                 expected_guard = lnb->lnb_guards;
342                 sectors = bv->bv_len / sector_size;
343                 if (lnb->lnb_guard_rpc) {
344                         rc = bio_dif_compare(expected_guard, bio_prot_buf,
345                                              sectors, bi->tuple_size);
346                         if (rc)
347                                 return rc;
348                 }
349
350                 sector += sectors;
351                 bio_prot_buf += sectors * bi->tuple_size;
352                 total += sectors * bi->tuple_size;
353                 LASSERT(total <= bip_size(bio->bi_integrity));
354                 index++;
355         }
356         return 0;
357 }
358
359 static int osd_bio_integrity_handle(struct osd_device *osd, struct bio *bio,
360                                     struct osd_iobuf *iobuf,
361                                     int start_page_idx, bool fault_inject,
362                                     bool integrity_enabled)
363 {
364         struct super_block *sb = osd_sb(osd);
365         integrity_gen_fn *generate_fn = NULL;
366         integrity_vrfy_fn *verify_fn = NULL;
367         int rc;
368
369         ENTRY;
370
371         if (!integrity_enabled)
372                 RETURN(0);
373
374         rc = osd_get_integrity_profile(osd, &generate_fn, &verify_fn);
375         if (rc)
376                 RETURN(rc);
377
378         rc = bio_integrity_prep_fn(bio, generate_fn, verify_fn);
379         if (rc)
380                 RETURN(rc);
381
382         /* Verify and inject fault only when writing */
383         if (iobuf->dr_rw == 1) {
384                 if (unlikely(OBD_FAIL_CHECK(OBD_FAIL_OST_INTEGRITY_CMP))) {
385                         rc = osd_bio_integrity_compare(bio, sb->s_bdev, iobuf,
386                                                        start_page_idx);
387                         if (rc)
388                                 RETURN(rc);
389                 }
390
391                 if (unlikely(fault_inject))
392                         bio_integrity_fault_inject(bio);
393         }
394
395         RETURN(0);
396 }
397
398 #ifdef HAVE_BIO_INTEGRITY_PREP_FN
399 #  ifdef HAVE_BIO_ENDIO_USES_ONE_ARG
400 static void dio_integrity_complete_routine(struct bio *bio)
401 #  else
402 static void dio_integrity_complete_routine(struct bio *bio, int error)
403 #  endif
404 {
405         struct osd_bio_private *bio_private = bio->bi_private;
406
407         bio->bi_private = bio_private->obp_iobuf;
408         osd_dio_complete_routine(bio, error);
409
410         OBD_FREE_PTR(bio_private);
411 }
412 #endif /* HAVE_BIO_INTEGRITY_PREP_FN */
413 #else  /* !CONFIG_BLK_DEV_INTEGRITY */
414 #define osd_bio_integrity_handle(osd, bio, iobuf, start_page_idx, \
415                                  fault_inject, integrity_enabled) 0
416 #endif /* CONFIG_BLK_DEV_INTEGRITY */
417
418 static int osd_bio_init(struct bio *bio, struct osd_iobuf *iobuf,
419                         bool integrity_enabled, int start_page_idx,
420                         struct osd_bio_private **pprivate)
421 {
422         ENTRY;
423
424         *pprivate = NULL;
425
426 #ifdef HAVE_BIO_INTEGRITY_PREP_FN
427         if (integrity_enabled) {
428                 struct osd_bio_private *bio_private = NULL;
429
430                 OBD_ALLOC_GFP(bio_private, sizeof(*bio_private), GFP_NOIO);
431                 if (bio_private == NULL)
432                         RETURN(-ENOMEM);
433                 bio->bi_end_io = dio_integrity_complete_routine;
434                 bio->bi_private = bio_private;
435                 bio_private->obp_start_page_idx = start_page_idx;
436                 bio_private->obp_iobuf = iobuf;
437                 *pprivate = bio_private;
438         } else
439 #endif
440         {
441                 bio->bi_end_io = dio_complete_routine;
442                 bio->bi_private = iobuf;
443         }
444
445         RETURN(0);
446 }
447
448 static int osd_do_bio(struct osd_device *osd, struct inode *inode,
449                       struct osd_iobuf *iobuf)
450 {
451         int blocks_per_page = PAGE_SIZE >> inode->i_blkbits;
452         struct page **pages = iobuf->dr_pages;
453         int npages = iobuf->dr_npages;
454         sector_t *blocks = iobuf->dr_blocks;
455         int total_blocks = npages * blocks_per_page;
456         struct super_block *sb = inode->i_sb;
457         int sector_bits = sb->s_blocksize_bits - 9;
458         unsigned int blocksize = sb->s_blocksize;
459         struct block_device *bdev = sb->s_bdev;
460         struct osd_bio_private *bio_private = NULL;
461         struct bio *bio = NULL;
462         int bio_start_page_idx;
463         struct page *page;
464         unsigned int page_offset;
465         sector_t sector;
466         int nblocks;
467         int block_idx;
468         int page_idx;
469         int i;
470         int rc = 0;
471         bool fault_inject;
472         bool integrity_enabled;
473         struct blk_plug plug;
474         ENTRY;
475
476         fault_inject = OBD_FAIL_CHECK(OBD_FAIL_OST_INTEGRITY_FAULT);
477         LASSERT(iobuf->dr_npages == npages);
478
479         integrity_enabled = bdev_integrity_enabled(bdev, iobuf->dr_rw);
480
481         osd_brw_stats_update(osd, iobuf);
482         iobuf->dr_start_time = ktime_get();
483
484         blk_start_plug(&plug);
485         for (page_idx = 0, block_idx = 0;
486              page_idx < npages;
487              page_idx++, block_idx += blocks_per_page) {
488
489                 page = pages[page_idx];
490                 LASSERT(block_idx + blocks_per_page <= total_blocks);
491
492                 for (i = 0, page_offset = 0;
493                      i < blocks_per_page;
494                      i += nblocks, page_offset += blocksize * nblocks) {
495
496                         nblocks = 1;
497
498                         if (blocks[block_idx + i] == 0) {  /* hole */
499                                 LASSERTF(iobuf->dr_rw == 0,
500                                          "page_idx %u, block_idx %u, i %u\n",
501                                          page_idx, block_idx, i);
502                                 memset(kmap(page) + page_offset, 0, blocksize);
503                                 kunmap(page);
504                                 continue;
505                         }
506
507                         sector = (sector_t)blocks[block_idx + i] << sector_bits;
508
509                         /* Additional contiguous file blocks? */
510                         while (i + nblocks < blocks_per_page &&
511                                (sector + (nblocks << sector_bits)) ==
512                                ((sector_t)blocks[block_idx + i + nblocks] <<
513                                 sector_bits))
514                                 nblocks++;
515
516                         if (bio != NULL &&
517                             can_be_merged(bio, sector) &&
518                             bio_add_page(bio, page,
519                                          blocksize * nblocks, page_offset) != 0)
520                                 continue;       /* added this frag OK */
521
522                         if (bio != NULL) {
523                                 struct request_queue *q = bio_get_queue(bio);
524                                 unsigned int bi_size = bio_sectors(bio) << 9;
525
526                                 /* Dang! I have to fragment this I/O */
527                                 CDEBUG(D_INODE,
528                                        "bio++ sz %d vcnt %d(%d) sectors %d(%d) psg %d(%d)\n",
529                                        bi_size, bio->bi_vcnt, bio->bi_max_vecs,
530                                        bio_sectors(bio),
531                                        queue_max_sectors(q),
532                                        osd_bio_nr_segs(bio),
533                                        queue_max_segments(q));
534                                 rc = osd_bio_integrity_handle(osd, bio,
535                                         iobuf, bio_start_page_idx,
536                                         fault_inject, integrity_enabled);
537                                 if (rc) {
538                                         bio_put(bio);
539                                         goto out;
540                                 }
541
542                                 record_start_io(iobuf, bi_size);
543                                 osd_submit_bio(iobuf->dr_rw, bio);
544                         }
545
546                         bio_start_page_idx = page_idx;
547                         /* allocate new bio */
548                         bio = bio_alloc(GFP_NOIO, min(BIO_MAX_PAGES,
549                                                       (npages - page_idx) *
550                                                       blocks_per_page));
551                         if (bio == NULL) {
552                                 CERROR("Can't allocate bio %u*%u = %u pages\n",
553                                        (npages - page_idx), blocks_per_page,
554                                        (npages - page_idx) * blocks_per_page);
555                                 rc = -ENOMEM;
556                                 goto out;
557                         }
558
559                         bio_set_dev(bio, bdev);
560                         bio_set_sector(bio, sector);
561                         bio->bi_opf = iobuf->dr_rw ? WRITE : READ;
562                         rc = osd_bio_init(bio, iobuf, integrity_enabled,
563                                           bio_start_page_idx, &bio_private);
564                         if (rc) {
565                                 bio_put(bio);
566                                 goto out;
567                         }
568
569                         rc = bio_add_page(bio, page,
570                                           blocksize * nblocks, page_offset);
571                         LASSERT(rc != 0);
572                 }
573         }
574
575         if (bio != NULL) {
576                 rc = osd_bio_integrity_handle(osd, bio, iobuf,
577                                               bio_start_page_idx,
578                                               fault_inject,
579                                               integrity_enabled);
580                 if (rc) {
581                         bio_put(bio);
582                         goto out;
583                 }
584
585                 record_start_io(iobuf, bio_sectors(bio) << 9);
586                 osd_submit_bio(iobuf->dr_rw, bio);
587                 rc = 0;
588         }
589
590 out:
591         blk_finish_plug(&plug);
592
593         /* in order to achieve better IO throughput, we don't wait for writes
594          * completion here. instead we proceed with transaction commit in
595          * parallel and wait for IO completion once transaction is stopped
596          * see osd_trans_stop() for more details -bzzz */
597         if (iobuf->dr_rw == 0 || fault_inject) {
598                 wait_event(iobuf->dr_wait,
599                            atomic_read(&iobuf->dr_numreqs) == 0);
600                 osd_fini_iobuf(osd, iobuf);
601         }
602
603         if (rc == 0) {
604                 rc = iobuf->dr_error;
605         } else {
606                 if (bio_private)
607                         OBD_FREE_PTR(bio_private);
608         }
609
610         RETURN(rc);
611 }
612
613 static int osd_map_remote_to_local(loff_t offset, ssize_t len, int *nrpages,
614                                    struct niobuf_local *lnb, int maxlnb)
615 {
616         int rc = 0;
617         ENTRY;
618
619         *nrpages = 0;
620
621         while (len > 0) {
622                 int poff = offset & (PAGE_SIZE - 1);
623                 int plen = PAGE_SIZE - poff;
624
625                 if (*nrpages >= maxlnb) {
626                         rc = -EOVERFLOW;
627                         break;
628                 }
629
630                 if (plen > len)
631                         plen = len;
632                 lnb->lnb_file_offset = offset;
633                 lnb->lnb_page_offset = poff;
634                 lnb->lnb_len = plen;
635                 /* lnb->lnb_flags = rnb->rnb_flags; */
636                 lnb->lnb_flags = 0;
637                 lnb->lnb_page = NULL;
638                 lnb->lnb_rc = 0;
639                 lnb->lnb_guard_rpc = 0;
640                 lnb->lnb_guard_disk = 0;
641                 lnb->lnb_locked = 0;
642
643                 LASSERTF(plen <= len, "plen %u, len %lld\n", plen,
644                          (long long) len);
645                 offset += plen;
646                 len -= plen;
647                 lnb++;
648                 (*nrpages)++;
649         }
650
651         RETURN(rc);
652 }
653
654 static struct page *osd_get_page(const struct lu_env *env, struct dt_object *dt,
655                                  loff_t offset, gfp_t gfp_mask, bool cache)
656 {
657         struct osd_thread_info *oti = osd_oti_get(env);
658         struct inode *inode = osd_dt_obj(dt)->oo_inode;
659         struct osd_device *d = osd_obj2dev(osd_dt_obj(dt));
660         struct page *page;
661         int cur;
662
663         LASSERT(inode);
664
665         if (cache) {
666                 page = find_or_create_page(inode->i_mapping,
667                                            offset >> PAGE_SHIFT, gfp_mask);
668
669                 if (likely(page))
670                         LASSERT(!test_bit(PG_private_2, &page->flags));
671                 else
672                         lprocfs_counter_add(d->od_stats, LPROC_OSD_NO_PAGE, 1);
673
674                 return page;
675         }
676
677         if (inode->i_mapping->nrpages) {
678                 /* consult with pagecache, but do not create new pages */
679                 /* this is normally used once */
680                 page = find_lock_page(inode->i_mapping, offset >> PAGE_SHIFT);
681                 if (page)
682                         return page;
683         }
684
685         LASSERT(oti->oti_dio_pages);
686         cur = oti->oti_dio_pages_used;
687
688         if (unlikely(!oti->oti_dio_pages[cur])) {
689                 LASSERT(cur < PTLRPC_MAX_BRW_PAGES);
690                 page = alloc_page(gfp_mask);
691                 if (!page)
692                         return NULL;
693                 oti->oti_dio_pages[cur] = page;
694         }
695
696         page = oti->oti_dio_pages[cur];
697         LASSERT(!test_bit(PG_private_2, &page->flags));
698         set_bit(PG_private_2, &page->flags);
699         oti->oti_dio_pages_used++;
700
701         LASSERT(!PageLocked(page));
702         lock_page(page);
703
704         LASSERT(!page->mapping);
705         LASSERT(!PageWriteback(page));
706         ClearPageUptodate(page);
707
708         page->index = offset >> PAGE_SHIFT;
709
710         return page;
711 }
712
713 /*
714  * there are following "locks":
715  * journal_start
716  * i_mutex
717  * page lock
718  *
719  * osd write path:
720  *  - lock page(s)
721  *  - journal_start
722  *  - truncate_sem
723  *
724  * ext4 vmtruncate:
725  *  - lock pages, unlock
726  *  - journal_start
727  *  - lock partial page
728  *  - i_data_sem
729  *
730  */
731
732 /**
733  * Unlock and release pages loaded by osd_bufs_get()
734  *
735  * Unlock \a npages pages from \a lnb and drop the refcount on them.
736  *
737  * \param env           thread execution environment
738  * \param dt            dt object undergoing IO (OSD object + methods)
739  * \param lnb           array of pages undergoing IO
740  * \param npages        number of pages in \a lnb
741  *
742  * \retval 0            always
743  */
744 static int osd_bufs_put(const struct lu_env *env, struct dt_object *dt,
745                         struct niobuf_local *lnb, int npages)
746 {
747         struct osd_thread_info *oti = osd_oti_get(env);
748         struct pagevec pvec;
749         int i;
750
751         ll_pagevec_init(&pvec, 0);
752
753         for (i = 0; i < npages; i++) {
754                 struct page *page = lnb[i].lnb_page;
755
756                 if (page == NULL)
757                         continue;
758
759                 /* if the page isn't cached, then reset uptodate
760                  * to prevent reuse */
761                 if (test_bit(PG_private_2, &page->flags)) {
762                         clear_bit(PG_private_2, &page->flags);
763                         ClearPageUptodate(page);
764                         if (lnb[i].lnb_locked)
765                                 unlock_page(page);
766                         oti->oti_dio_pages_used--;
767                 } else {
768                         if (lnb[i].lnb_locked)
769                                 unlock_page(page);
770                         if (pagevec_add(&pvec, page) == 0)
771                                 pagevec_release(&pvec);
772                 }
773
774                 lnb[i].lnb_page = NULL;
775         }
776
777         LASSERTF(oti->oti_dio_pages_used == 0, "%d\n", oti->oti_dio_pages_used);
778
779         /* Release any partial pagevec */
780         pagevec_release(&pvec);
781
782         RETURN(0);
783 }
784
785 /**
786  * Load and lock pages undergoing IO
787  *
788  * Pages as described in the \a lnb array are fetched (from disk or cache)
789  * and locked for IO by the caller.
790  *
791  * DLM locking protects us from write and truncate competing for same region,
792  * but partial-page truncate can leave dirty pages in the cache for ldiskfs.
793  * It's possible the writeout on a such a page is in progress when we access
794  * it. It's also possible that during this writeout we put new (partial) data
795  * into the page, but won't be able to proceed in filter_commitrw_write().
796  * Therefore, just wait for writeout completion as it should be rare enough.
797  *
798  * \param env           thread execution environment
799  * \param dt            dt object undergoing IO (OSD object + methods)
800  * \param pos           byte offset of IO start
801  * \param len           number of bytes of IO
802  * \param lnb           array of extents undergoing IO
803  * \param rw            read or write operation, and other flags
804  * \param capa          capabilities
805  *
806  * \retval pages        (zero or more) loaded successfully
807  * \retval -ENOMEM      on memory/page allocation error
808  */
809 static int osd_bufs_get(const struct lu_env *env, struct dt_object *dt,
810                         loff_t pos, ssize_t len, struct niobuf_local *lnb,
811                         int maxlnb, enum dt_bufs_type rw)
812 {
813         struct osd_thread_info *oti = osd_oti_get(env);
814         struct osd_object *obj = osd_dt_obj(dt);
815         struct osd_device *osd   = osd_obj2dev(obj);
816         int npages, i, iosize, rc = 0;
817         bool cache, write;
818         loff_t fsize;
819         gfp_t gfp_mask;
820
821         LASSERT(obj->oo_inode);
822
823         rc = osd_map_remote_to_local(pos, len, &npages, lnb, maxlnb);
824         if (rc)
825                 RETURN(rc);
826
827         write = rw & DT_BUFS_TYPE_WRITE;
828
829         fsize = lnb[npages - 1].lnb_file_offset + lnb[npages - 1].lnb_len;
830         iosize = fsize - lnb[0].lnb_file_offset;
831         fsize = max(fsize, i_size_read(obj->oo_inode));
832
833         cache = rw & DT_BUFS_TYPE_READAHEAD;
834         if (cache)
835                 goto bypass_checks;
836
837         cache = osd_use_page_cache(osd);
838         while (cache) {
839                 if (write) {
840                         if (!osd->od_writethrough_cache) {
841                                 cache = false;
842                                 break;
843                         }
844                         if (iosize > osd->od_writethrough_max_iosize) {
845                                 cache = false;
846                                 break;
847                         }
848                 } else {
849                         if (!osd->od_read_cache) {
850                                 cache = false;
851                                 break;
852                         }
853                         if (iosize > osd->od_readcache_max_iosize) {
854                                 cache = false;
855                                 break;
856                         }
857                 }
858                 /* don't use cache on large files */
859                 if (osd->od_readcache_max_filesize &&
860                     fsize > osd->od_readcache_max_filesize)
861                         cache = false;
862                 break;
863         }
864
865 bypass_checks:
866         if (!cache && unlikely(!oti->oti_dio_pages)) {
867                 OBD_ALLOC(oti->oti_dio_pages,
868                           sizeof(struct page *) * PTLRPC_MAX_BRW_PAGES);
869                 if (!oti->oti_dio_pages)
870                         return -ENOMEM;
871         }
872
873         /* this could also try less hard for DT_BUFS_TYPE_READAHEAD pages */
874         gfp_mask = rw & DT_BUFS_TYPE_LOCAL ? (GFP_NOFS | __GFP_HIGHMEM) :
875                                              GFP_HIGHUSER;
876         for (i = 0; i < npages; i++, lnb++) {
877                 lnb->lnb_page = osd_get_page(env, dt, lnb->lnb_file_offset,
878                                              gfp_mask, cache);
879                 if (lnb->lnb_page == NULL)
880                         GOTO(cleanup, rc = -ENOMEM);
881
882                 lnb->lnb_locked = 1;
883                 wait_on_page_writeback(lnb->lnb_page);
884                 BUG_ON(PageWriteback(lnb->lnb_page));
885         }
886
887 #if 0
888         /* XXX: this version doesn't invalidate cached pages, but use them */
889         if (!cache && write && obj->oo_inode->i_mapping->nrpages) {
890                 /* do not allow data aliasing, invalidate pagecache */
891                 /* XXX: can be quite expensive in mixed case */
892                 invalidate_mapping_pages(obj->oo_inode->i_mapping,
893                                 lnb[0].lnb_file_offset >> PAGE_SHIFT,
894                                 lnb[npages - 1].lnb_file_offset >> PAGE_SHIFT);
895         }
896 #endif
897
898         RETURN(i);
899
900 cleanup:
901         if (i > 0)
902                 osd_bufs_put(env, dt, lnb - i, i);
903         return rc;
904 }
905
906 static int osd_ldiskfs_map_inode_pages(struct inode *inode, struct page **page,
907                                        int pages, sector_t *blocks,
908                                        int create)
909 {
910         int blocks_per_page = PAGE_SIZE >> inode->i_blkbits;
911         int rc = 0, i = 0;
912         struct page *fp = NULL;
913         int clen = 0;
914         pgoff_t max_page_index;
915         handle_t *handle = NULL;
916
917         max_page_index = inode->i_sb->s_maxbytes >> PAGE_SHIFT;
918
919         CDEBUG(D_OTHER, "inode %lu: map %d pages from %lu\n",
920                 inode->i_ino, pages, (*page)->index);
921
922         if (create) {
923                 create = LDISKFS_GET_BLOCKS_CREATE;
924                 handle = ldiskfs_journal_current_handle();
925                 LASSERT(handle != NULL);
926                 rc = osd_attach_jinode(inode);
927                 if (rc)
928                         return rc;
929         }
930         /* pages are sorted already. so, we just have to find
931          * contig. space and process them properly */
932         while (i < pages) {
933                 long blen, total = 0;
934                 struct ldiskfs_map_blocks map = { 0 };
935
936                 if (fp == NULL) { /* start new extent */
937                         fp = *page++;
938                         clen = 1;
939                         if (++i != pages)
940                                 continue;
941                 } else if (fp->index + clen == (*page)->index) {
942                         /* continue the extent */
943                         page++;
944                         clen++;
945                         if (++i != pages)
946                                 continue;
947                 }
948                 if (fp->index + clen >= max_page_index)
949                         GOTO(cleanup, rc = -EFBIG);
950                 /* process found extent */
951                 map.m_lblk = fp->index * blocks_per_page;
952                 map.m_len = blen = clen * blocks_per_page;
953 cont_map:
954                 rc = ldiskfs_map_blocks(handle, inode, &map, create);
955                 if (rc >= 0) {
956                         int c = 0;
957                         for (; total < blen && c < map.m_len; c++, total++) {
958                                 if (rc == 0) {
959                                         *(blocks + total) = 0;
960                                         total++;
961                                         break;
962                                 } else {
963                                         *(blocks + total) = map.m_pblk + c;
964                                         /* unmap any possible underlying
965                                          * metadata from the block device
966                                          * mapping.  bug 6998. */
967                                         if ((map.m_flags & LDISKFS_MAP_NEW) &&
968                                             create)
969                                                 clean_bdev_aliases(
970                                                         inode->i_sb->s_bdev,
971                                                         map.m_pblk + c, 1);
972                                 }
973                         }
974                         rc = 0;
975                 }
976                 if (rc == 0 && total < blen) {
977                         map.m_lblk = fp->index * blocks_per_page + total;
978                         map.m_len = blen - total;
979                         goto cont_map;
980                 }
981                 if (rc != 0)
982                         GOTO(cleanup, rc);
983
984                 /* look for next extent */
985                 fp = NULL;
986                 blocks += blocks_per_page * clen;
987         }
988 cleanup:
989         return rc;
990 }
991
992 static int osd_write_prep(const struct lu_env *env, struct dt_object *dt,
993                           struct niobuf_local *lnb, int npages)
994 {
995         struct osd_thread_info *oti   = osd_oti_get(env);
996         struct osd_iobuf       *iobuf = &oti->oti_iobuf;
997         struct inode           *inode = osd_dt_obj(dt)->oo_inode;
998         struct osd_device      *osd   = osd_obj2dev(osd_dt_obj(dt));
999         ktime_t start, end;
1000         s64 timediff;
1001         ssize_t isize;
1002         __s64  maxidx;
1003         int i, rc = 0;
1004
1005         LASSERT(inode);
1006
1007         rc = osd_init_iobuf(osd, iobuf, 0, npages);
1008         if (unlikely(rc != 0))
1009                 RETURN(rc);
1010
1011         isize = i_size_read(inode);
1012         maxidx = ((isize + PAGE_SIZE - 1) >> PAGE_SHIFT) - 1;
1013
1014         start = ktime_get();
1015         for (i = 0; i < npages; i++) {
1016
1017                 /*
1018                  * till commit the content of the page is undefined
1019                  * we'll set it uptodate once bulk is done. otherwise
1020                  * subsequent reads can access non-stable data
1021                  */
1022                 ClearPageUptodate(lnb[i].lnb_page);
1023
1024                 if (lnb[i].lnb_len == PAGE_SIZE)
1025                         continue;
1026
1027                 if (maxidx >= lnb[i].lnb_page->index) {
1028                         osd_iobuf_add_page(iobuf, &lnb[i]);
1029                 } else {
1030                         long off;
1031                         char *p = kmap(lnb[i].lnb_page);
1032
1033                         off = lnb[i].lnb_page_offset;
1034                         if (off)
1035                                 memset(p, 0, off);
1036                         off = (lnb[i].lnb_page_offset + lnb[i].lnb_len) &
1037                               ~PAGE_MASK;
1038                         if (off)
1039                                 memset(p + off, 0, PAGE_SIZE - off);
1040                         kunmap(lnb[i].lnb_page);
1041                 }
1042         }
1043         end = ktime_get();
1044         timediff = ktime_us_delta(end, start);
1045         lprocfs_counter_add(osd->od_stats, LPROC_OSD_GET_PAGE, timediff);
1046
1047         if (iobuf->dr_npages) {
1048                 rc = osd_ldiskfs_map_inode_pages(inode, iobuf->dr_pages,
1049                                                  iobuf->dr_npages,
1050                                                  iobuf->dr_blocks, 0);
1051                 if (likely(rc == 0)) {
1052                         rc = osd_do_bio(osd, inode, iobuf);
1053                         /* do IO stats for preparation reads */
1054                         osd_fini_iobuf(osd, iobuf);
1055                 }
1056         }
1057         RETURN(rc);
1058 }
1059
1060 struct osd_fextent {
1061         sector_t        start;
1062         sector_t        end;
1063         unsigned int    mapped:1;
1064 };
1065
1066 static int osd_is_mapped(struct dt_object *dt, __u64 offset,
1067                          struct osd_fextent *cached_extent)
1068 {
1069         struct inode *inode = osd_dt_obj(dt)->oo_inode;
1070         sector_t block = offset >> inode->i_blkbits;
1071         sector_t start;
1072         struct fiemap_extent_info fei = { 0 };
1073         struct fiemap_extent fe = { 0 };
1074         mm_segment_t saved_fs;
1075         int rc;
1076
1077         if (block >= cached_extent->start && block < cached_extent->end)
1078                 return cached_extent->mapped;
1079
1080         if (i_size_read(inode) == 0)
1081                 return 0;
1082
1083         /* Beyond EOF, must not be mapped */
1084         if (((i_size_read(inode) - 1) >> inode->i_blkbits) < block)
1085                 return 0;
1086
1087         fei.fi_extents_max = 1;
1088         fei.fi_extents_start = &fe;
1089
1090         saved_fs = get_fs();
1091         set_fs(KERNEL_DS);
1092         rc = inode->i_op->fiemap(inode, &fei, offset, FIEMAP_MAX_OFFSET-offset);
1093         set_fs(saved_fs);
1094         if (rc != 0)
1095                 return 0;
1096
1097         start = fe.fe_logical >> inode->i_blkbits;
1098
1099         if (start > block) {
1100                 cached_extent->start = block;
1101                 cached_extent->end = start;
1102                 cached_extent->mapped = 0;
1103         } else {
1104                 cached_extent->start = start;
1105                 cached_extent->end = (fe.fe_logical + fe.fe_length) >>
1106                                       inode->i_blkbits;
1107                 cached_extent->mapped = 1;
1108         }
1109
1110         return cached_extent->mapped;
1111 }
1112
1113 static int osd_declare_write_commit(const struct lu_env *env,
1114                                     struct dt_object *dt,
1115                                     struct niobuf_local *lnb, int npages,
1116                                     struct thandle *handle)
1117 {
1118         const struct osd_device *osd = osd_obj2dev(osd_dt_obj(dt));
1119         struct inode            *inode = osd_dt_obj(dt)->oo_inode;
1120         struct osd_thandle      *oh;
1121         int                     extents = 1;
1122         int                     depth;
1123         int                     i;
1124         int                     newblocks;
1125         int                     rc = 0;
1126         int                     credits = 0;
1127         long long               quota_space = 0;
1128         struct osd_fextent      extent = { 0 };
1129         enum osd_quota_local_flags local_flags = 0;
1130         enum osd_qid_declare_flags declare_flags = OSD_QID_BLK;
1131         ENTRY;
1132
1133         LASSERT(handle != NULL);
1134         oh = container_of0(handle, struct osd_thandle, ot_super);
1135         LASSERT(oh->ot_handle == NULL);
1136
1137         newblocks = npages;
1138
1139         /* calculate number of extents (probably better to pass nb) */
1140         for (i = 0; i < npages; i++) {
1141                 if (i && lnb[i].lnb_file_offset !=
1142                     lnb[i - 1].lnb_file_offset + lnb[i - 1].lnb_len)
1143                         extents++;
1144
1145                 if (osd_is_mapped(dt, lnb[i].lnb_file_offset, &extent))
1146                         lnb[i].lnb_flags |= OBD_BRW_MAPPED;
1147                 else
1148                         quota_space += PAGE_SIZE;
1149
1150                 /* ignore quota for the whole request if any page is from
1151                  * client cache or written by root.
1152                  *
1153                  * XXX once we drop the 1.8 client support, the checking
1154                  * for whether page is from cache can be simplified as:
1155                  * !(lnb[i].flags & OBD_BRW_SYNC)
1156                  *
1157                  * XXX we could handle this on per-lnb basis as done by
1158                  * grant. */
1159                 if ((lnb[i].lnb_flags & OBD_BRW_NOQUOTA) ||
1160                     (lnb[i].lnb_flags & (OBD_BRW_FROM_GRANT | OBD_BRW_SYNC)) ==
1161                     OBD_BRW_FROM_GRANT)
1162                         declare_flags |= OSD_QID_FORCE;
1163         }
1164
1165         /*
1166          * each extent can go into new leaf causing a split
1167          * 5 is max tree depth: inode + 4 index blocks
1168          * with blockmaps, depth is 3 at most
1169          */
1170         if (LDISKFS_I(inode)->i_flags & LDISKFS_EXTENTS_FL) {
1171                 /*
1172                  * many concurrent threads may grow tree by the time
1173                  * our transaction starts. so, consider 2 is a min depth
1174                  */
1175                 depth = ext_depth(inode);
1176                 depth = max(depth, 1) + 1;
1177                 newblocks += depth;
1178                 credits++; /* inode */
1179                 credits += depth * 2 * extents;
1180         } else {
1181                 depth = 3;
1182                 newblocks += depth;
1183                 credits++; /* inode */
1184                 credits += depth * extents;
1185         }
1186
1187         /* quota space for metadata blocks */
1188         quota_space += depth * extents * LDISKFS_BLOCK_SIZE(osd_sb(osd));
1189
1190         /* quota space should be reported in 1K blocks */
1191         quota_space = toqb(quota_space);
1192
1193         /* each new block can go in different group (bitmap + gd) */
1194
1195         /* we can't dirty more bitmap blocks than exist */
1196         if (newblocks > LDISKFS_SB(osd_sb(osd))->s_groups_count)
1197                 credits += LDISKFS_SB(osd_sb(osd))->s_groups_count;
1198         else
1199                 credits += newblocks;
1200
1201         /* we can't dirty more gd blocks than exist */
1202         if (newblocks > LDISKFS_SB(osd_sb(osd))->s_gdb_count)
1203                 credits += LDISKFS_SB(osd_sb(osd))->s_gdb_count;
1204         else
1205                 credits += newblocks;
1206
1207         osd_trans_declare_op(env, oh, OSD_OT_WRITE, credits);
1208
1209         /* make sure the over quota flags were not set */
1210         lnb[0].lnb_flags &= ~OBD_BRW_OVER_ALLQUOTA;
1211
1212         rc = osd_declare_inode_qid(env, i_uid_read(inode), i_gid_read(inode),
1213                                    i_projid_read(inode), quota_space, oh,
1214                                    osd_dt_obj(dt), &local_flags, declare_flags);
1215
1216         /* we need only to store the overquota flags in the first lnb for
1217          * now, once we support multiple objects BRW, this code needs be
1218          * revised. */
1219         if (local_flags & QUOTA_FL_OVER_USRQUOTA)
1220                 lnb[0].lnb_flags |= OBD_BRW_OVER_USRQUOTA;
1221         if (local_flags & QUOTA_FL_OVER_GRPQUOTA)
1222                 lnb[0].lnb_flags |= OBD_BRW_OVER_GRPQUOTA;
1223         if (local_flags & QUOTA_FL_OVER_PRJQUOTA)
1224                 lnb[0].lnb_flags |= OBD_BRW_OVER_PRJQUOTA;
1225
1226         if (rc == 0)
1227                 rc = osd_trunc_lock(osd_dt_obj(dt), oh, true);
1228
1229         RETURN(rc);
1230 }
1231
1232 /* Check if a block is allocated or not */
1233 static int osd_write_commit(const struct lu_env *env, struct dt_object *dt,
1234                             struct niobuf_local *lnb, int npages,
1235                             struct thandle *thandle)
1236 {
1237         struct osd_thread_info *oti = osd_oti_get(env);
1238         struct osd_iobuf *iobuf = &oti->oti_iobuf;
1239         struct inode *inode = osd_dt_obj(dt)->oo_inode;
1240         struct osd_device  *osd = osd_obj2dev(osd_dt_obj(dt));
1241         loff_t isize;
1242         int rc = 0, i;
1243
1244         LASSERT(inode);
1245
1246         rc = osd_init_iobuf(osd, iobuf, 1, npages);
1247         if (unlikely(rc != 0))
1248                 RETURN(rc);
1249
1250         isize = i_size_read(inode);
1251         dquot_initialize(inode);
1252
1253         for (i = 0; i < npages; i++) {
1254                 if (lnb[i].lnb_rc == -ENOSPC &&
1255                     (lnb[i].lnb_flags & OBD_BRW_MAPPED)) {
1256                         /* Allow the write to proceed if overwriting an
1257                          * existing block */
1258                         lnb[i].lnb_rc = 0;
1259                 }
1260
1261                 if (lnb[i].lnb_rc) { /* ENOSPC, network RPC error, etc. */
1262                         CDEBUG(D_INODE, "Skipping [%d] == %d\n", i,
1263                                lnb[i].lnb_rc);
1264                         LASSERT(lnb[i].lnb_page);
1265                         generic_error_remove_page(inode->i_mapping,
1266                                                   lnb[i].lnb_page);
1267                         continue;
1268                 }
1269
1270                 LASSERT(PageLocked(lnb[i].lnb_page));
1271                 LASSERT(!PageWriteback(lnb[i].lnb_page));
1272
1273                 if (lnb[i].lnb_file_offset + lnb[i].lnb_len > isize)
1274                         isize = lnb[i].lnb_file_offset + lnb[i].lnb_len;
1275
1276                 /*
1277                  * Since write and truncate are serialized by oo_sem, even
1278                  * partial-page truncate should not leave dirty pages in the
1279                  * page cache.
1280                  */
1281                 LASSERT(!PageDirty(lnb[i].lnb_page));
1282
1283                 SetPageUptodate(lnb[i].lnb_page);
1284
1285                 osd_iobuf_add_page(iobuf, &lnb[i]);
1286         }
1287
1288         osd_trans_exec_op(env, thandle, OSD_OT_WRITE);
1289
1290         if (OBD_FAIL_CHECK(OBD_FAIL_OST_MAPBLK_ENOSPC)) {
1291                 rc = -ENOSPC;
1292         } else if (iobuf->dr_npages > 0) {
1293                 rc = osd_ldiskfs_map_inode_pages(inode, iobuf->dr_pages,
1294                                                  iobuf->dr_npages,
1295                                                  iobuf->dr_blocks, 1);
1296         } else {
1297                 /* no pages to write, no transno is needed */
1298                 thandle->th_local = 1;
1299         }
1300
1301         if (likely(rc == 0)) {
1302                 spin_lock(&inode->i_lock);
1303                 if (isize > i_size_read(inode)) {
1304                         i_size_write(inode, isize);
1305                         LDISKFS_I(inode)->i_disksize = isize;
1306                         spin_unlock(&inode->i_lock);
1307                         osd_dirty_inode(inode, I_DIRTY_DATASYNC);
1308                 } else {
1309                         spin_unlock(&inode->i_lock);
1310                 }
1311
1312                 rc = osd_do_bio(osd, inode, iobuf);
1313                 /* we don't do stats here as in read path because
1314                  * write is async: we'll do this in osd_put_bufs() */
1315         } else {
1316                 osd_fini_iobuf(osd, iobuf);
1317         }
1318
1319         osd_trans_exec_check(env, thandle, OSD_OT_WRITE);
1320
1321         if (unlikely(rc != 0)) {
1322                 /* if write fails, we should drop pages from the cache */
1323                 for (i = 0; i < npages; i++) {
1324                         if (lnb[i].lnb_page == NULL)
1325                                 continue;
1326                         LASSERT(PageLocked(lnb[i].lnb_page));
1327                         generic_error_remove_page(inode->i_mapping,
1328                                                   lnb[i].lnb_page);
1329                 }
1330         }
1331
1332         RETURN(rc);
1333 }
1334
1335 static int osd_read_prep(const struct lu_env *env, struct dt_object *dt,
1336                          struct niobuf_local *lnb, int npages)
1337 {
1338         struct osd_thread_info *oti = osd_oti_get(env);
1339         struct osd_iobuf *iobuf = &oti->oti_iobuf;
1340         struct inode *inode = osd_dt_obj(dt)->oo_inode;
1341         struct osd_device *osd = osd_obj2dev(osd_dt_obj(dt));
1342         int rc = 0, i, cache_hits = 0, cache_misses = 0;
1343         ktime_t start, end;
1344         s64 timediff;
1345         loff_t isize;
1346
1347         LASSERT(inode);
1348
1349         rc = osd_init_iobuf(osd, iobuf, 0, npages);
1350         if (unlikely(rc != 0))
1351                 RETURN(rc);
1352
1353         isize = i_size_read(inode);
1354
1355         start = ktime_get();
1356         for (i = 0; i < npages; i++) {
1357
1358                 if (isize <= lnb[i].lnb_file_offset)
1359                         /* If there's no more data, abort early.
1360                          * lnb->lnb_rc == 0, so it's easy to detect later. */
1361                         break;
1362
1363                 /* instead of looking if we go beyong isize, send complete
1364                  * pages all the time
1365                  */
1366                 lnb[i].lnb_rc = lnb[i].lnb_len;
1367
1368                 /* Bypass disk read if fail_loc is set properly */
1369                 if (OBD_FAIL_CHECK(OBD_FAIL_OST_FAKE_RW))
1370                         SetPageUptodate(lnb[i].lnb_page);
1371
1372                 if (PageUptodate(lnb[i].lnb_page)) {
1373                         cache_hits++;
1374                         unlock_page(lnb[i].lnb_page);
1375                 } else {
1376                         cache_misses++;
1377                         osd_iobuf_add_page(iobuf, &lnb[i]);
1378                 }
1379                 /* no need to unlock in osd_bufs_put(), the sooner page is
1380                  * unlocked, the earlier another client can access it.
1381                  * notice real unlock_page() can be called few lines
1382                  * below after osd_do_bio(). lnb is a per-thread, so it's
1383                  * fine to have PG_locked and lnb_locked inconsistent here */
1384                 lnb[i].lnb_locked = 0;
1385         }
1386         end = ktime_get();
1387         timediff = ktime_us_delta(end, start);
1388         lprocfs_counter_add(osd->od_stats, LPROC_OSD_GET_PAGE, timediff);
1389
1390         if (cache_hits != 0)
1391                 lprocfs_counter_add(osd->od_stats, LPROC_OSD_CACHE_HIT,
1392                                     cache_hits);
1393         if (cache_misses != 0)
1394                 lprocfs_counter_add(osd->od_stats, LPROC_OSD_CACHE_MISS,
1395                                     cache_misses);
1396         if (cache_hits + cache_misses != 0)
1397                 lprocfs_counter_add(osd->od_stats, LPROC_OSD_CACHE_ACCESS,
1398                                     cache_hits + cache_misses);
1399
1400         if (iobuf->dr_npages) {
1401                 rc = osd_ldiskfs_map_inode_pages(inode, iobuf->dr_pages,
1402                                                  iobuf->dr_npages,
1403                                                  iobuf->dr_blocks, 0);
1404                 rc = osd_do_bio(osd, inode, iobuf);
1405
1406                 /* IO stats will be done in osd_bufs_put() */
1407
1408                 /* early release to let others read data during the bulk */
1409                 for (i = 0; i < iobuf->dr_npages; i++) {
1410                         LASSERT(PageLocked(iobuf->dr_pages[i]));
1411                         unlock_page(iobuf->dr_pages[i]);
1412                 }
1413         }
1414
1415         RETURN(rc);
1416 }
1417
1418 /*
1419  * XXX: Another layering violation for now.
1420  *
1421  * We don't want to use ->f_op->read methods, because generic file write
1422  *
1423  *         - serializes on ->i_sem, and
1424  *
1425  *         - does a lot of extra work like balance_dirty_pages(),
1426  *
1427  * which doesn't work for globally shared files like /last_rcvd.
1428  */
1429 static int osd_ldiskfs_readlink(struct inode *inode, char *buffer, int buflen)
1430 {
1431         struct ldiskfs_inode_info *ei = LDISKFS_I(inode);
1432
1433         memcpy(buffer, (char *)ei->i_data, buflen);
1434
1435         return  buflen;
1436 }
1437
1438 int osd_ldiskfs_read(struct inode *inode, void *buf, int size, loff_t *offs)
1439 {
1440         struct buffer_head *bh;
1441         unsigned long block;
1442         int osize;
1443         int blocksize;
1444         int csize;
1445         int boffs;
1446
1447         /* prevent reading after eof */
1448         spin_lock(&inode->i_lock);
1449         if (i_size_read(inode) < *offs + size) {
1450                 loff_t diff = i_size_read(inode) - *offs;
1451                 spin_unlock(&inode->i_lock);
1452                 if (diff < 0) {
1453                         CDEBUG(D_OTHER,
1454                                "size %llu is too short to read @%llu\n",
1455                                i_size_read(inode), *offs);
1456                         return -EBADR;
1457                 } else if (diff == 0) {
1458                         return 0;
1459                 } else {
1460                         size = diff;
1461                 }
1462         } else {
1463                 spin_unlock(&inode->i_lock);
1464         }
1465
1466         blocksize = 1 << inode->i_blkbits;
1467         osize = size;
1468         while (size > 0) {
1469                 block = *offs >> inode->i_blkbits;
1470                 boffs = *offs & (blocksize - 1);
1471                 csize = min(blocksize - boffs, size);
1472                 bh = __ldiskfs_bread(NULL, inode, block, 0);
1473                 if (IS_ERR(bh)) {
1474                         CERROR("%s: can't read %u@%llu on ino %lu: "
1475                                "rc = %ld\n", osd_ino2name(inode),
1476                                csize, *offs, inode->i_ino,
1477                                PTR_ERR(bh));
1478                         return PTR_ERR(bh);
1479                 }
1480
1481                 if (bh != NULL) {
1482                         memcpy(buf, bh->b_data + boffs, csize);
1483                         brelse(bh);
1484                 } else {
1485                         memset(buf, 0, csize);
1486                 }
1487
1488                 *offs += csize;
1489                 buf += csize;
1490                 size -= csize;
1491         }
1492         return osize;
1493 }
1494
1495 static ssize_t osd_read(const struct lu_env *env, struct dt_object *dt,
1496                         struct lu_buf *buf, loff_t *pos)
1497 {
1498         struct inode *inode = osd_dt_obj(dt)->oo_inode;
1499         int rc;
1500
1501         /* Read small symlink from inode body as we need to maintain correct
1502          * on-disk symlinks for ldiskfs.
1503          */
1504         if (S_ISLNK(dt->do_lu.lo_header->loh_attr)) {
1505                 loff_t size = i_size_read(inode);
1506
1507                 if (buf->lb_len < size)
1508                         return -EOVERFLOW;
1509
1510                 if (size < sizeof(LDISKFS_I(inode)->i_data))
1511                         rc = osd_ldiskfs_readlink(inode, buf->lb_buf, size);
1512                 else
1513                         rc = osd_ldiskfs_read(inode, buf->lb_buf, size, pos);
1514         } else {
1515                 rc = osd_ldiskfs_read(inode, buf->lb_buf, buf->lb_len, pos);
1516         }
1517
1518         return rc;
1519 }
1520
1521 static inline int osd_extents_enabled(struct super_block *sb,
1522                                       struct inode *inode)
1523 {
1524         if (inode != NULL) {
1525                 if (LDISKFS_I(inode)->i_flags & LDISKFS_EXTENTS_FL)
1526                         return 1;
1527         } else if (ldiskfs_has_feature_extents(sb)) {
1528                 return 1;
1529         }
1530         return 0;
1531 }
1532
1533 int osd_calc_bkmap_credits(struct super_block *sb, struct inode *inode,
1534                            const loff_t size, const loff_t pos,
1535                            const int blocks)
1536 {
1537         int credits, bits, bs, i;
1538
1539         bits = sb->s_blocksize_bits;
1540         bs = 1 << bits;
1541
1542         /* legacy blockmap: 3 levels * 3 (bitmap,gd,itself)
1543          * we do not expect blockmaps on the large files,
1544          * so let's shrink it to 2 levels (4GB files) */
1545
1546         /* this is default reservation: 2 levels */
1547         credits = (blocks + 2) * 3;
1548
1549         /* actual offset is unknown, hard to optimize */
1550         if (pos == -1)
1551                 return credits;
1552
1553         /* now check for few specific cases to optimize */
1554         if (pos + size <= LDISKFS_NDIR_BLOCKS * bs) {
1555                 /* no indirects */
1556                 credits = blocks;
1557                 /* allocate if not allocated */
1558                 if (inode == NULL) {
1559                         credits += blocks * 2;
1560                         return credits;
1561                 }
1562                 for (i = (pos >> bits); i < (pos >> bits) + blocks; i++) {
1563                         LASSERT(i < LDISKFS_NDIR_BLOCKS);
1564                         if (LDISKFS_I(inode)->i_data[i] == 0)
1565                                 credits += 2;
1566                 }
1567         } else if (pos + size <= (LDISKFS_NDIR_BLOCKS + 1024) * bs) {
1568                 /* single indirect */
1569                 credits = blocks * 3;
1570                 if (inode == NULL ||
1571                     LDISKFS_I(inode)->i_data[LDISKFS_IND_BLOCK] == 0)
1572                         credits += 3;
1573                 else
1574                         /* The indirect block may be modified. */
1575                         credits += 1;
1576         }
1577
1578         return credits;
1579 }
1580
1581 static ssize_t osd_declare_write(const struct lu_env *env, struct dt_object *dt,
1582                                  const struct lu_buf *buf, loff_t _pos,
1583                                  struct thandle *handle)
1584 {
1585         struct osd_object  *obj  = osd_dt_obj(dt);
1586         struct inode       *inode = obj->oo_inode;
1587         struct super_block *sb = osd_sb(osd_obj2dev(obj));
1588         struct osd_thandle *oh;
1589         int                 rc = 0, est = 0, credits, blocks, allocated = 0;
1590         int                 bits, bs;
1591         int                 depth, size;
1592         loff_t              pos;
1593         ENTRY;
1594
1595         LASSERT(buf != NULL);
1596         LASSERT(handle != NULL);
1597
1598         oh = container_of0(handle, struct osd_thandle, ot_super);
1599         LASSERT(oh->ot_handle == NULL);
1600
1601         size = buf->lb_len;
1602         bits = sb->s_blocksize_bits;
1603         bs = 1 << bits;
1604
1605         if (_pos == -1) {
1606                 /* if this is an append, then we
1607                  * should expect cross-block record */
1608                 pos = 0;
1609         } else {
1610                 pos = _pos;
1611         }
1612
1613         /* blocks to modify */
1614         blocks = ((pos + size + bs - 1) >> bits) - (pos >> bits);
1615         LASSERT(blocks > 0);
1616
1617         if (inode != NULL && _pos != -1) {
1618                 /* object size in blocks */
1619                 est = (i_size_read(inode) + bs - 1) >> bits;
1620                 allocated = inode->i_blocks >> (bits - 9);
1621                 if (pos + size <= i_size_read(inode) && est <= allocated) {
1622                         /* looks like an overwrite, no need to modify tree */
1623                         credits = blocks;
1624                         /* no need to modify i_size */
1625                         goto out;
1626                 }
1627         }
1628
1629         if (osd_extents_enabled(sb, inode)) {
1630                 /*
1631                  * many concurrent threads may grow tree by the time
1632                  * our transaction starts. so, consider 2 is a min depth
1633                  * for every level we may need to allocate a new block
1634                  * and take some entries from the old one. so, 3 blocks
1635                  * to allocate (bitmap, gd, itself) + old block - 4 per
1636                  * level.
1637                  */
1638                 depth = inode != NULL ? ext_depth(inode) : 0;
1639                 depth = max(depth, 1) + 1;
1640                 credits = depth;
1641                 /* if not append, then split may need to modify
1642                  * existing blocks moving entries into the new ones */
1643                 if (_pos != -1)
1644                         credits += depth;
1645                 /* blocks to store data: bitmap,gd,itself */
1646                 credits += blocks * 3;
1647         } else {
1648                 credits = osd_calc_bkmap_credits(sb, inode, size, _pos, blocks);
1649         }
1650         /* if inode is created as part of the transaction,
1651          * then it's counted already by the creation method */
1652         if (inode != NULL)
1653                 credits++;
1654
1655 out:
1656
1657         osd_trans_declare_op(env, oh, OSD_OT_WRITE, credits);
1658
1659         /* dt_declare_write() is usually called for system objects, such
1660          * as llog or last_rcvd files. We needn't enforce quota on those
1661          * objects, so always set the lqi_space as 0. */
1662         if (inode != NULL)
1663                 rc = osd_declare_inode_qid(env, i_uid_read(inode),
1664                                            i_gid_read(inode),
1665                                            i_projid_read(inode), 0,
1666                                            oh, obj, NULL, OSD_QID_BLK);
1667
1668         if (rc == 0)
1669                 rc = osd_trunc_lock(obj, oh, true);
1670
1671         RETURN(rc);
1672 }
1673
1674 static int osd_ldiskfs_writelink(struct inode *inode, char *buffer, int buflen)
1675 {
1676         /* LU-2634: clear the extent format for fast symlink */
1677         ldiskfs_clear_inode_flag(inode, LDISKFS_INODE_EXTENTS);
1678
1679         memcpy((char *)&LDISKFS_I(inode)->i_data, (char *)buffer, buflen);
1680         spin_lock(&inode->i_lock);
1681         LDISKFS_I(inode)->i_disksize = buflen;
1682         i_size_write(inode, buflen);
1683         spin_unlock(&inode->i_lock);
1684         osd_dirty_inode(inode, I_DIRTY_DATASYNC);
1685
1686         return 0;
1687 }
1688
1689 static int osd_ldiskfs_write_record(struct dt_object *dt, void *buf,
1690                                     int bufsize, int write_NUL, loff_t *offs,
1691                                     handle_t *handle)
1692 {
1693         struct inode *inode = osd_dt_obj(dt)->oo_inode;
1694         struct buffer_head *bh        = NULL;
1695         loff_t              offset    = *offs;
1696         loff_t              new_size  = i_size_read(inode);
1697         unsigned long       block;
1698         int                 blocksize = 1 << inode->i_blkbits;
1699         int                 err = 0;
1700         int                 size;
1701         int                 boffs;
1702         int                 dirty_inode = 0;
1703         struct ldiskfs_inode_info *ei = LDISKFS_I(inode);
1704         bool create, sparse, sync = false;
1705
1706         if (write_NUL) {
1707                 /*
1708                  * long symlink write does not count the NUL terminator in
1709                  * bufsize, we write it, and the inode's file size does not
1710                  * count the NUL terminator as well.
1711                  */
1712                 ((char *)buf)[bufsize] = '\0';
1713                 ++bufsize;
1714         }
1715
1716         /* sparse checking is racy, but sparse is very rare case, leave as is */
1717         sparse = (new_size > 0 && (inode->i_blocks >> (inode->i_blkbits - 9)) <
1718                   ((new_size - 1) >> inode->i_blkbits) + 1);
1719
1720         while (bufsize > 0) {
1721                 int credits = handle->h_buffer_credits;
1722                 unsigned long last_block = (new_size == 0) ? 0 :
1723                                            (new_size - 1) >> inode->i_blkbits;
1724
1725                 if (bh)
1726                         brelse(bh);
1727
1728                 block = offset >> inode->i_blkbits;
1729                 boffs = offset & (blocksize - 1);
1730                 size = min(blocksize - boffs, bufsize);
1731                 sync = (block > last_block || new_size == 0 || sparse);
1732
1733                 if (sync)
1734                         down(&ei->i_append_sem);
1735
1736                 bh = __ldiskfs_bread(handle, inode, block, 0);
1737
1738                 if (unlikely(IS_ERR_OR_NULL(bh) && !sync))
1739                         CWARN("%s: adding bh without locking off %llu (block %lu, "
1740                               "size %d, offs %llu)\n", inode->i_sb->s_id,
1741                               offset, block, bufsize, *offs);
1742
1743                 if (IS_ERR_OR_NULL(bh)) {
1744                         struct osd_device *osd = osd_obj2dev(osd_dt_obj(dt));
1745                         int flags = LDISKFS_GET_BLOCKS_CREATE;
1746
1747                         /* while the file system is being mounted, avoid
1748                          * preallocation otherwise mount can take a long
1749                          * time as mballoc cache is cold.
1750                          * XXX: this is a workaround until we have a proper
1751                          *      fix in mballoc
1752                          * XXX: works with extent-based files only */
1753                         if (!osd->od_cl_seq)
1754                                 flags |= LDISKFS_GET_BLOCKS_NO_NORMALIZE;
1755                         bh = __ldiskfs_bread(handle, inode, block, flags);
1756                         create = true;
1757                 } else {
1758                         if (sync) {
1759                                 up(&ei->i_append_sem);
1760                                 sync = false;
1761                         }
1762                         create = false;
1763                 }
1764                 if (IS_ERR_OR_NULL(bh)) {
1765                         if (bh == NULL) {
1766                                 err = -EIO;
1767                         } else {
1768                                 err = PTR_ERR(bh);
1769                                 bh = NULL;
1770                         }
1771
1772                         CERROR("%s: error reading offset %llu (block %lu, "
1773                                "size %d, offs %llu), credits %d/%d: rc = %d\n",
1774                                inode->i_sb->s_id, offset, block, bufsize, *offs,
1775                                credits, handle->h_buffer_credits, err);
1776                         break;
1777                 }
1778
1779                 err = ldiskfs_journal_get_write_access(handle, bh);
1780                 if (err) {
1781                         CERROR("journal_get_write_access() returned error %d\n",
1782                                err);
1783                         break;
1784                 }
1785                 LASSERTF(boffs + size <= bh->b_size,
1786                          "boffs %d size %d bh->b_size %lu\n",
1787                          boffs, size, (unsigned long)bh->b_size);
1788                 if (create) {
1789                         memset(bh->b_data, 0, bh->b_size);
1790                         if (sync) {
1791                                 up(&ei->i_append_sem);
1792                                 sync = false;
1793                         }
1794                 }
1795                 memcpy(bh->b_data + boffs, buf, size);
1796                 err = ldiskfs_handle_dirty_metadata(handle, NULL, bh);
1797                 if (err)
1798                         break;
1799
1800                 if (offset + size > new_size)
1801                         new_size = offset + size;
1802                 offset += size;
1803                 bufsize -= size;
1804                 buf += size;
1805         }
1806         if (sync)
1807                 up(&ei->i_append_sem);
1808
1809         if (bh)
1810                 brelse(bh);
1811
1812         if (write_NUL)
1813                 --new_size;
1814         /* correct in-core and on-disk sizes */
1815         if (new_size > i_size_read(inode)) {
1816                 spin_lock(&inode->i_lock);
1817                 if (new_size > i_size_read(inode))
1818                         i_size_write(inode, new_size);
1819                 if (i_size_read(inode) > LDISKFS_I(inode)->i_disksize) {
1820                         LDISKFS_I(inode)->i_disksize = i_size_read(inode);
1821                         dirty_inode = 1;
1822                 }
1823                 spin_unlock(&inode->i_lock);
1824                 if (dirty_inode)
1825                         osd_dirty_inode(inode, I_DIRTY_DATASYNC);
1826         }
1827
1828         if (err == 0)
1829                 *offs = offset;
1830         return err;
1831 }
1832
1833 static ssize_t osd_write(const struct lu_env *env, struct dt_object *dt,
1834                          const struct lu_buf *buf, loff_t *pos,
1835                          struct thandle *handle)
1836 {
1837         struct inode            *inode = osd_dt_obj(dt)->oo_inode;
1838         struct osd_thandle      *oh;
1839         ssize_t                 result;
1840         int                     is_link;
1841
1842         LASSERT(dt_object_exists(dt));
1843
1844         LASSERT(handle != NULL);
1845         LASSERT(inode != NULL);
1846         dquot_initialize(inode);
1847
1848         /* XXX: don't check: one declared chunk can be used many times */
1849         /* osd_trans_exec_op(env, handle, OSD_OT_WRITE); */
1850
1851         oh = container_of(handle, struct osd_thandle, ot_super);
1852         LASSERT(oh->ot_handle->h_transaction != NULL);
1853         osd_trans_exec_op(env, handle, OSD_OT_WRITE);
1854
1855         /* Write small symlink to inode body as we need to maintain correct
1856          * on-disk symlinks for ldiskfs.
1857          * Note: the buf->lb_buf contains a NUL terminator while buf->lb_len
1858          * does not count it in.
1859          */
1860         is_link = S_ISLNK(dt->do_lu.lo_header->loh_attr);
1861         if (is_link && (buf->lb_len < sizeof(LDISKFS_I(inode)->i_data)))
1862                 result = osd_ldiskfs_writelink(inode, buf->lb_buf, buf->lb_len);
1863         else
1864                 result = osd_ldiskfs_write_record(dt, buf->lb_buf, buf->lb_len,
1865                                                   is_link, pos, oh->ot_handle);
1866         if (result == 0)
1867                 result = buf->lb_len;
1868
1869         osd_trans_exec_check(env, handle, OSD_OT_WRITE);
1870
1871         return result;
1872 }
1873
1874 static int osd_declare_punch(const struct lu_env *env, struct dt_object *dt,
1875                              __u64 start, __u64 end, struct thandle *th)
1876 {
1877         struct osd_thandle *oh;
1878         struct inode       *inode;
1879         int                 rc;
1880         ENTRY;
1881
1882         LASSERT(th);
1883         oh = container_of(th, struct osd_thandle, ot_super);
1884
1885         /*
1886          * we don't need to reserve credits for whole truncate
1887          * it's not possible as truncate may need to free too many
1888          * blocks and that won't fit a single transaction. instead
1889          * we reserve credits to change i_size and put inode onto
1890          * orphan list. if needed truncate will extend or restart
1891          * transaction
1892          */
1893         osd_trans_declare_op(env, oh, OSD_OT_PUNCH,
1894                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE] + 3);
1895
1896         inode = osd_dt_obj(dt)->oo_inode;
1897         LASSERT(inode);
1898
1899         rc = osd_declare_inode_qid(env, i_uid_read(inode), i_gid_read(inode),
1900                                    i_projid_read(inode), 0, oh, osd_dt_obj(dt),
1901                                    NULL, OSD_QID_BLK);
1902
1903         if (rc == 0)
1904                 rc = osd_trunc_lock(osd_dt_obj(dt), oh, false);
1905
1906         RETURN(rc);
1907 }
1908
1909 static int osd_punch(const struct lu_env *env, struct dt_object *dt,
1910                      __u64 start, __u64 end, struct thandle *th)
1911 {
1912         struct osd_object *obj = osd_dt_obj(dt);
1913         struct osd_device *osd = osd_obj2dev(obj);
1914         struct inode *inode = obj->oo_inode;
1915         struct osd_access_lock *al;
1916         struct osd_thandle *oh;
1917         int rc = 0, found = 0;
1918         bool grow = false;
1919         ENTRY;
1920
1921         LASSERT(end == OBD_OBJECT_EOF);
1922         LASSERT(dt_object_exists(dt));
1923         LASSERT(osd_invariant(obj));
1924         LASSERT(inode != NULL);
1925         dquot_initialize(inode);
1926
1927         LASSERT(th);
1928         oh = container_of(th, struct osd_thandle, ot_super);
1929         LASSERT(oh->ot_handle->h_transaction != NULL);
1930
1931         /* we used to skip truncate to current size to
1932          * optimize truncates on OST. with DoM we can
1933          * get attr_set to set specific size (MDS_REINT)
1934          * and then get truncate RPC which essentially
1935          * would be skipped. this is bad.. so, disable
1936          * this optimization on MDS till the client stop
1937          * to sent MDS_REINT (LU-11033) -bzzz */
1938         if (osd->od_is_ost && i_size_read(inode) == start)
1939                 RETURN(0);
1940
1941         osd_trans_exec_op(env, th, OSD_OT_PUNCH);
1942
1943         spin_lock(&inode->i_lock);
1944         if (i_size_read(inode) < start)
1945                 grow = true;
1946         i_size_write(inode, start);
1947         spin_unlock(&inode->i_lock);
1948         ll_truncate_pagecache(inode, start);
1949
1950         /* optimize grow case */
1951         if (grow) {
1952                 osd_execute_truncate(obj);
1953                 GOTO(out, rc);
1954         }
1955
1956         inode_lock(inode);
1957         /* add to orphan list to ensure truncate completion
1958          * if this transaction succeed. ldiskfs_truncate()
1959          * will take the inode out of the list */
1960         rc = ldiskfs_orphan_add(oh->ot_handle, inode);
1961         inode_unlock(inode);
1962         if (rc != 0)
1963                 GOTO(out, rc);
1964
1965         list_for_each_entry(al, &oh->ot_trunc_locks, tl_list) {
1966                 if (obj != al->tl_obj)
1967                         continue;
1968                 LASSERT(al->tl_shared == 0);
1969                 found = 1;
1970                 /* do actual truncate in osd_trans_stop() */
1971                 al->tl_truncate = 1;
1972                 break;
1973         }
1974         LASSERT(found);
1975
1976 out:
1977         RETURN(rc);
1978 }
1979
1980 static int fiemap_check_ranges(struct inode *inode,
1981                                u64 start, u64 len, u64 *new_len)
1982 {
1983         loff_t maxbytes;
1984
1985         *new_len = len;
1986
1987         if (len == 0)
1988                 return -EINVAL;
1989
1990         if (ldiskfs_test_inode_flag(inode, LDISKFS_INODE_EXTENTS))
1991                 maxbytes = inode->i_sb->s_maxbytes;
1992         else
1993                 maxbytes = LDISKFS_SB(inode->i_sb)->s_bitmap_maxbytes;
1994
1995         if (start > maxbytes)
1996                 return -EFBIG;
1997
1998         /*
1999          * Shrink request scope to what the fs can actually handle.
2000          */
2001         if (len > maxbytes || (maxbytes - len) < start)
2002                 *new_len = maxbytes - start;
2003
2004         return 0;
2005 }
2006
2007 /* So that the fiemap access checks can't overflow on 32 bit machines. */
2008 #define FIEMAP_MAX_EXTENTS     (UINT_MAX / sizeof(struct fiemap_extent))
2009
2010 static int osd_fiemap_get(const struct lu_env *env, struct dt_object *dt,
2011                           struct fiemap *fm)
2012 {
2013         struct fiemap_extent_info fieinfo = {0, };
2014         struct inode *inode = osd_dt_obj(dt)->oo_inode;
2015         u64 len;
2016         int rc;
2017         mm_segment_t cur_fs;
2018
2019         LASSERT(inode);
2020         if (inode->i_op->fiemap == NULL)
2021                 return -EOPNOTSUPP;
2022
2023         if (fm->fm_extent_count > FIEMAP_MAX_EXTENTS)
2024                 return -EINVAL;
2025
2026         rc = fiemap_check_ranges(inode, fm->fm_start, fm->fm_length, &len);
2027         if (rc)
2028                 return rc;
2029
2030         fieinfo.fi_flags = fm->fm_flags;
2031         fieinfo.fi_extents_max = fm->fm_extent_count;
2032         fieinfo.fi_extents_start = fm->fm_extents;
2033
2034         if (fieinfo.fi_flags & FIEMAP_FLAG_SYNC)
2035                 filemap_write_and_wait(inode->i_mapping);
2036
2037         /* Save previous value address limit */
2038         cur_fs = get_fs();
2039         /* Set the address limit of the kernel */
2040         set_fs(KERNEL_DS);
2041
2042         rc = inode->i_op->fiemap(inode, &fieinfo, fm->fm_start, len);
2043         fm->fm_flags = fieinfo.fi_flags;
2044         fm->fm_mapped_extents = fieinfo.fi_extents_mapped;
2045
2046         /* Restore the previous address limt */
2047         set_fs(cur_fs);
2048
2049         return rc;
2050 }
2051
2052 static int osd_ladvise(const struct lu_env *env, struct dt_object *dt,
2053                        __u64 start, __u64 end, enum lu_ladvise_type advice)
2054 {
2055         struct osd_object *obj = osd_dt_obj(dt);
2056         int rc = 0;
2057         ENTRY;
2058
2059         switch (advice) {
2060         case LU_LADVISE_DONTNEED:
2061                 if (end)
2062                         invalidate_mapping_pages(obj->oo_inode->i_mapping,
2063                                                  start >> PAGE_SHIFT,
2064                                                  (end - 1) >> PAGE_SHIFT);
2065                 break;
2066         default:
2067                 rc = -ENOTSUPP;
2068                 break;
2069         }
2070
2071         RETURN(rc);
2072 }
2073
2074 /*
2075  * in some cases we may need declare methods for objects being created
2076  * e.g., when we create symlink
2077  */
2078 const struct dt_body_operations osd_body_ops_new = {
2079         .dbo_declare_write = osd_declare_write,
2080 };
2081
2082 const struct dt_body_operations osd_body_ops = {
2083         .dbo_read                       = osd_read,
2084         .dbo_declare_write              = osd_declare_write,
2085         .dbo_write                      = osd_write,
2086         .dbo_bufs_get                   = osd_bufs_get,
2087         .dbo_bufs_put                   = osd_bufs_put,
2088         .dbo_write_prep                 = osd_write_prep,
2089         .dbo_declare_write_commit       = osd_declare_write_commit,
2090         .dbo_write_commit               = osd_write_commit,
2091         .dbo_read_prep                  = osd_read_prep,
2092         .dbo_declare_punch              = osd_declare_punch,
2093         .dbo_punch                      = osd_punch,
2094         .dbo_fiemap_get                 = osd_fiemap_get,
2095         .dbo_ladvise                    = osd_ladvise,
2096 };
2097
2098 /**
2099  * Get a truncate lock
2100  *
2101  * In order to take multi-transaction truncate out of main transaction we let
2102  * the caller grab a lock on the object passed. the lock can be shared (for
2103  * writes) and exclusive (for truncate). It's not allowed to mix truncate
2104  * and write in the same transaction handle (do not confuse with big ldiskfs
2105  * transaction containing lots of handles).
2106  * The lock must be taken at declaration.
2107  *
2108  * \param obj           object to lock
2109  * \oh                  transaction
2110  * \shared              shared or exclusive
2111  *
2112  * \retval 0            lock is granted
2113  * \retval -NOMEM       no memory to allocate lock
2114  */
2115 int osd_trunc_lock(struct osd_object *obj, struct osd_thandle *oh, bool shared)
2116 {
2117         struct osd_access_lock *al, *tmp;
2118
2119         LASSERT(obj);
2120         LASSERT(oh);
2121
2122         list_for_each_entry(tmp, &oh->ot_trunc_locks, tl_list) {
2123                 if (tmp->tl_obj != obj)
2124                         continue;
2125                 LASSERT(tmp->tl_shared == shared);
2126                 /* found same lock */
2127                 return 0;
2128         }
2129
2130         OBD_ALLOC_PTR(al);
2131         if (unlikely(al == NULL))
2132                 return -ENOMEM;
2133         al->tl_obj = obj;
2134         al->tl_truncate = false;
2135         if (shared)
2136                 down_read(&obj->oo_ext_idx_sem);
2137         else
2138                 down_write(&obj->oo_ext_idx_sem);
2139         al->tl_shared = shared;
2140
2141         list_add(&al->tl_list, &oh->ot_trunc_locks);
2142
2143         return 0;
2144 }
2145
2146 void osd_trunc_unlock_all(struct list_head *list)
2147 {
2148         struct osd_access_lock *al, *tmp;
2149         list_for_each_entry_safe(al, tmp, list, tl_list) {
2150                 if (al->tl_shared)
2151                         up_read(&al->tl_obj->oo_ext_idx_sem);
2152                 else
2153                         up_write(&al->tl_obj->oo_ext_idx_sem);
2154                 list_del(&al->tl_list);
2155                 OBD_FREE_PTR(al);
2156         }
2157 }
2158
2159 void osd_execute_truncate(struct osd_object *obj)
2160 {
2161         struct osd_device *d = osd_obj2dev(obj);
2162         struct inode *inode = obj->oo_inode;
2163         __u64 size;
2164
2165         /* simulate crash before (in the middle) of delayed truncate */
2166         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_FAIL_AT_TRUNCATE)) {
2167                 struct ldiskfs_inode_info *ei = LDISKFS_I(inode);
2168                 struct ldiskfs_sb_info *sbi = LDISKFS_SB(inode->i_sb);
2169
2170                 mutex_lock(&sbi->s_orphan_lock);
2171                 list_del_init(&ei->i_orphan);
2172                 mutex_unlock(&sbi->s_orphan_lock);
2173                 return;
2174         }
2175
2176         inode_lock(inode);
2177         ldiskfs_truncate(inode);
2178         inode_unlock(inode);
2179
2180         /*
2181          * For a partial-page truncate, flush the page to disk immediately to
2182          * avoid data corruption during direct disk write.  b=17397
2183          */
2184         size = i_size_read(inode);
2185         if ((size & ~PAGE_MASK) == 0)
2186                 return;
2187         if (osd_use_page_cache(d)) {
2188                 filemap_fdatawrite_range(inode->i_mapping, size, size + 1);
2189         } else {
2190                 /* Notice we use "wait" version to ensure I/O is complete */
2191                 filemap_write_and_wait_range(inode->i_mapping, size, size + 1);
2192                 invalidate_mapping_pages(inode->i_mapping, size >> PAGE_SHIFT,
2193                                          size >> PAGE_SHIFT);
2194         }
2195 }
2196
2197 void osd_process_truncates(struct list_head *list)
2198 {
2199         struct osd_access_lock *al;
2200
2201         LASSERT(journal_current_handle() == NULL);
2202
2203         list_for_each_entry(al, list, tl_list) {
2204                 if (al->tl_shared)
2205                         continue;
2206                 if (!al->tl_truncate)
2207                         continue;
2208                 osd_execute_truncate(al->tl_obj);
2209         }
2210 }