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