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