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