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