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