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