Whamcloud - gitweb
LU-3373 osd-ldiskfs: Use ext4_map_blocks for IO map
[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.sun.com/software/products/lustre/docs/GPLv2.pdf
19  *
20  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
21  * CA 95054 USA or visit www.sun.com if you need additional information or
22  * have any questions.
23  *
24  * GPL HEADER END
25  */
26 /*
27  * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  *
30  * Copyright (c) 2012, 2013, Intel Corporation.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * lustre/osd/osd_io.c
37  *
38  * body operations
39  *
40  * Author: Nikita Danilov <nikita@clusterfs.com>
41  * Author: Alex Zhuravlev <bzzz@whamcloud.com>
42  *
43  */
44
45 /* LUSTRE_VERSION_CODE */
46 #include <lustre_ver.h>
47 /* prerequisite for linux/xattr.h */
48 #include <linux/types.h>
49 /* prerequisite for linux/xattr.h */
50 #include <linux/fs.h>
51
52 /*
53  * struct OBD_{ALLOC,FREE}*()
54  * OBD_FAIL_CHECK
55  */
56 #include <obd_support.h>
57
58 #include "osd_internal.h"
59
60 /* ext_depth() */
61 #include <ldiskfs/ldiskfs_extents.h>
62
63 static int __osd_init_iobuf(struct osd_device *d, struct osd_iobuf *iobuf,
64                             int rw, int line, int pages)
65 {
66         int blocks, i;
67
68         LASSERTF(iobuf->dr_elapsed_valid == 0,
69                  "iobuf %p, reqs %d, rw %d, line %d\n", iobuf,
70                  atomic_read(&iobuf->dr_numreqs), iobuf->dr_rw,
71                  iobuf->dr_init_at);
72         LASSERT(pages <= PTLRPC_MAX_BRW_PAGES);
73
74         init_waitqueue_head(&iobuf->dr_wait);
75         atomic_set(&iobuf->dr_numreqs, 0);
76         iobuf->dr_npages = 0;
77         iobuf->dr_error = 0;
78         iobuf->dr_dev = d;
79         iobuf->dr_frags = 0;
80         iobuf->dr_elapsed = 0;
81         /* must be counted before, so assert */
82         iobuf->dr_rw = rw;
83         iobuf->dr_init_at = line;
84
85         blocks = pages * (PAGE_CACHE_SIZE >> osd_sb(d)->s_blocksize_bits);
86         if (iobuf->dr_bl_buf.lb_len >= blocks * sizeof(iobuf->dr_blocks[0])) {
87                 LASSERT(iobuf->dr_pg_buf.lb_len >=
88                         pages * sizeof(iobuf->dr_pages[0]));
89                 return 0;
90         }
91
92         /* start with 1MB for 4K blocks */
93         i = 256;
94         while (i <= PTLRPC_MAX_BRW_PAGES && i < pages)
95                 i <<= 1;
96
97         CDEBUG(D_OTHER, "realloc %u for %u (%u) pages\n",
98                (unsigned)(pages * sizeof(iobuf->dr_pages[0])), i, pages);
99         pages = i;
100         blocks = pages * (PAGE_CACHE_SIZE >> osd_sb(d)->s_blocksize_bits);
101         iobuf->dr_max_pages = 0;
102         CDEBUG(D_OTHER, "realloc %u for %u blocks\n",
103                (unsigned)(blocks * sizeof(iobuf->dr_blocks[0])), blocks);
104
105         lu_buf_realloc(&iobuf->dr_bl_buf, blocks * sizeof(iobuf->dr_blocks[0]));
106         iobuf->dr_blocks = iobuf->dr_bl_buf.lb_buf;
107         if (unlikely(iobuf->dr_blocks == NULL))
108                 return -ENOMEM;
109
110         lu_buf_realloc(&iobuf->dr_pg_buf, pages * sizeof(iobuf->dr_pages[0]));
111         iobuf->dr_pages = iobuf->dr_pg_buf.lb_buf;
112         if (unlikely(iobuf->dr_pages == NULL))
113                 return -ENOMEM;
114
115         iobuf->dr_max_pages = pages;
116
117         return 0;
118 }
119 #define osd_init_iobuf(dev, iobuf, rw, pages) \
120         __osd_init_iobuf(dev, iobuf, rw, __LINE__, pages)
121
122 static void osd_iobuf_add_page(struct osd_iobuf *iobuf, struct page *page)
123 {
124         LASSERT(iobuf->dr_npages < iobuf->dr_max_pages);
125         iobuf->dr_pages[iobuf->dr_npages++] = page;
126 }
127
128 void osd_fini_iobuf(struct osd_device *d, struct osd_iobuf *iobuf)
129 {
130         int rw = iobuf->dr_rw;
131
132         if (iobuf->dr_elapsed_valid) {
133                 iobuf->dr_elapsed_valid = 0;
134                 LASSERT(iobuf->dr_dev == d);
135                 LASSERT(iobuf->dr_frags > 0);
136                 lprocfs_oh_tally(&d->od_brw_stats.
137                                  hist[BRW_R_DIO_FRAGS+rw],
138                                  iobuf->dr_frags);
139                 lprocfs_oh_tally_log2(&d->od_brw_stats.hist[BRW_R_IO_TIME+rw],
140                                       iobuf->dr_elapsed);
141         }
142 }
143
144 #ifndef REQ_WRITE /* pre-2.6.35 */
145 #define __REQ_WRITE BIO_RW
146 #endif
147
148 static void dio_complete_routine(struct bio *bio, int error)
149 {
150         struct osd_iobuf *iobuf = bio->bi_private;
151         struct bio_vec *bvl;
152         int i;
153
154         /* CAVEAT EMPTOR: possibly in IRQ context
155          * DO NOT record procfs stats here!!! */
156
157         if (unlikely(iobuf == NULL)) {
158                 CERROR("***** bio->bi_private is NULL!  This should never "
159                        "happen.  Normally, I would crash here, but instead I "
160                        "will dump the bio contents to the console.  Please "
161                        "report this to <https://jira.hpdd.intel.com/> , along "
162                        "with any interesting messages leading up to this point "
163                        "(like SCSI errors, perhaps).  Because bi_private is "
164                        "NULL, I can't wake up the thread that initiated this "
165                        "IO - you will probably have to reboot this node.\n");
166                 CERROR("bi_next: %p, bi_flags: %lx, bi_rw: %lu, bi_vcnt: %d, "
167                        "bi_idx: %d, bi->size: %d, bi_end_io: %p, bi_cnt: %d, "
168                        "bi_private: %p\n", bio->bi_next, bio->bi_flags,
169                        bio->bi_rw, bio->bi_vcnt, bio->bi_idx, bio->bi_size,
170                        bio->bi_end_io, atomic_read(&bio->bi_cnt),
171                        bio->bi_private);
172                 return;
173         }
174
175         /* the check is outside of the cycle for performance reason -bzzz */
176         if (!test_bit(__REQ_WRITE, &bio->bi_rw)) {
177                 bio_for_each_segment(bvl, bio, i) {
178                         if (likely(error == 0))
179                                 SetPageUptodate(bvl->bv_page);
180                         LASSERT(PageLocked(bvl->bv_page));
181                 }
182                 atomic_dec(&iobuf->dr_dev->od_r_in_flight);
183         } else {
184                 atomic_dec(&iobuf->dr_dev->od_w_in_flight);
185         }
186
187         /* any real error is good enough -bzzz */
188         if (error != 0 && iobuf->dr_error == 0)
189                 iobuf->dr_error = error;
190
191         /*
192          * set dr_elapsed before dr_numreqs turns to 0, otherwise
193          * it's possible that service thread will see dr_numreqs
194          * is zero, but dr_elapsed is not set yet, leading to lost
195          * data in this processing and an assertion in a subsequent
196          * call to OSD.
197          */
198         if (atomic_read(&iobuf->dr_numreqs) == 1) {
199                 iobuf->dr_elapsed = jiffies - iobuf->dr_start_time;
200                 iobuf->dr_elapsed_valid = 1;
201         }
202         if (atomic_dec_and_test(&iobuf->dr_numreqs))
203                 wake_up(&iobuf->dr_wait);
204
205         /* Completed bios used to be chained off iobuf->dr_bios and freed in
206          * filter_clear_dreq().  It was then possible to exhaust the biovec-256
207          * mempool when serious on-disk fragmentation was encountered,
208          * deadlocking the OST.  The bios are now released as soon as complete
209          * so the pool cannot be exhausted while IOs are competing. bug 10076 */
210         bio_put(bio);
211 }
212
213 static void record_start_io(struct osd_iobuf *iobuf, int size)
214 {
215         struct osd_device    *osd = iobuf->dr_dev;
216         struct obd_histogram *h = osd->od_brw_stats.hist;
217
218         iobuf->dr_frags++;
219         atomic_inc(&iobuf->dr_numreqs);
220
221         if (iobuf->dr_rw == 0) {
222                 atomic_inc(&osd->od_r_in_flight);
223                 lprocfs_oh_tally(&h[BRW_R_RPC_HIST],
224                                  atomic_read(&osd->od_r_in_flight));
225                 lprocfs_oh_tally_log2(&h[BRW_R_DISK_IOSIZE], size);
226         } else if (iobuf->dr_rw == 1) {
227                 atomic_inc(&osd->od_w_in_flight);
228                 lprocfs_oh_tally(&h[BRW_W_RPC_HIST],
229                                  atomic_read(&osd->od_w_in_flight));
230                 lprocfs_oh_tally_log2(&h[BRW_W_DISK_IOSIZE], size);
231         } else {
232                 LBUG();
233         }
234 }
235
236 static void osd_submit_bio(int rw, struct bio *bio)
237 {
238         LASSERTF(rw == 0 || rw == 1, "%x\n", rw);
239         if (rw == 0)
240                 submit_bio(READ, bio);
241         else
242                 submit_bio(WRITE, bio);
243 }
244
245 static int can_be_merged(struct bio *bio, sector_t sector)
246 {
247         unsigned int size;
248
249         if (!bio)
250                 return 0;
251
252         size = bio->bi_size >> 9;
253         return bio->bi_sector + size == sector ? 1 : 0;
254 }
255
256 static int osd_do_bio(struct osd_device *osd, struct inode *inode,
257                       struct osd_iobuf *iobuf)
258 {
259         int            blocks_per_page = PAGE_CACHE_SIZE >> inode->i_blkbits;
260         struct page  **pages = iobuf->dr_pages;
261         int            npages = iobuf->dr_npages;
262         unsigned long *blocks = iobuf->dr_blocks;
263         int            total_blocks = npages * blocks_per_page;
264         int            sector_bits = inode->i_sb->s_blocksize_bits - 9;
265         unsigned int   blocksize = inode->i_sb->s_blocksize;
266         struct bio    *bio = NULL;
267         struct page   *page;
268         unsigned int   page_offset;
269         sector_t       sector;
270         int            nblocks;
271         int            block_idx;
272         int            page_idx;
273         int            i;
274         int            rc = 0;
275         ENTRY;
276
277         LASSERT(iobuf->dr_npages == npages);
278
279         osd_brw_stats_update(osd, iobuf);
280         iobuf->dr_start_time = cfs_time_current();
281
282         for (page_idx = 0, block_idx = 0;
283              page_idx < npages;
284              page_idx++, block_idx += blocks_per_page) {
285
286                 page = pages[page_idx];
287                 LASSERT(block_idx + blocks_per_page <= total_blocks);
288
289                 for (i = 0, page_offset = 0;
290                      i < blocks_per_page;
291                      i += nblocks, page_offset += blocksize * nblocks) {
292
293                         nblocks = 1;
294
295                         if (blocks[block_idx + i] == 0) {  /* hole */
296                                 LASSERTF(iobuf->dr_rw == 0,
297                                          "page_idx %u, block_idx %u, i %u\n",
298                                          page_idx, block_idx, i);
299                                 memset(kmap(page) + page_offset, 0, blocksize);
300                                 kunmap(page);
301                                 continue;
302                         }
303
304                         sector = (sector_t)blocks[block_idx + i] << sector_bits;
305
306                         /* Additional contiguous file blocks? */
307                         while (i + nblocks < blocks_per_page &&
308                                (sector + (nblocks << sector_bits)) ==
309                                ((sector_t)blocks[block_idx + i + nblocks] <<
310                                 sector_bits))
311                                 nblocks++;
312
313                         if (bio != NULL &&
314                             can_be_merged(bio, sector) &&
315                             bio_add_page(bio, page,
316                                          blocksize * nblocks, page_offset) != 0)
317                                 continue;       /* added this frag OK */
318
319                         if (bio != NULL) {
320                                 struct request_queue *q =
321                                         bdev_get_queue(bio->bi_bdev);
322
323                                 /* Dang! I have to fragment this I/O */
324                                 CDEBUG(D_INODE, "bio++ sz %d vcnt %d(%d) "
325                                        "sectors %d(%d) psg %d(%d) hsg %d(%d)\n",
326                                        bio->bi_size,
327                                        bio->bi_vcnt, bio->bi_max_vecs,
328                                        bio->bi_size >> 9, queue_max_sectors(q),
329                                        bio_phys_segments(q, bio),
330                                        queue_max_phys_segments(q),
331                                        0, queue_max_hw_segments(q));
332
333                                 record_start_io(iobuf, bio->bi_size);
334                                 osd_submit_bio(iobuf->dr_rw, bio);
335                         }
336
337                         /* allocate new bio */
338                         bio = bio_alloc(GFP_NOIO, min(BIO_MAX_PAGES,
339                                                       (npages - page_idx) *
340                                                       blocks_per_page));
341                         if (bio == NULL) {
342                                 CERROR("Can't allocate bio %u*%u = %u pages\n",
343                                        (npages - page_idx), blocks_per_page,
344                                        (npages - page_idx) * blocks_per_page);
345                                 rc = -ENOMEM;
346                                 goto out;
347                         }
348
349                         bio->bi_bdev = inode->i_sb->s_bdev;
350                         bio->bi_sector = sector;
351                         bio->bi_rw = (iobuf->dr_rw == 0) ? READ : WRITE;
352                         bio->bi_end_io = dio_complete_routine;
353                         bio->bi_private = iobuf;
354
355                         rc = bio_add_page(bio, page,
356                                           blocksize * nblocks, page_offset);
357                         LASSERT(rc != 0);
358                 }
359         }
360
361         if (bio != NULL) {
362                 record_start_io(iobuf, bio->bi_size);
363                 osd_submit_bio(iobuf->dr_rw, bio);
364                 rc = 0;
365         }
366
367 out:
368         /* in order to achieve better IO throughput, we don't wait for writes
369          * completion here. instead we proceed with transaction commit in
370          * parallel and wait for IO completion once transaction is stopped
371          * see osd_trans_stop() for more details -bzzz */
372         if (iobuf->dr_rw == 0) {
373                 wait_event(iobuf->dr_wait,
374                            atomic_read(&iobuf->dr_numreqs) == 0);
375                 osd_fini_iobuf(osd, iobuf);
376         }
377
378         if (rc == 0)
379                 rc = iobuf->dr_error;
380         RETURN(rc);
381 }
382
383 static int osd_map_remote_to_local(loff_t offset, ssize_t len, int *nrpages,
384                                    struct niobuf_local *lnb)
385 {
386         ENTRY;
387
388         *nrpages = 0;
389
390         while (len > 0) {
391                 int poff = offset & (PAGE_CACHE_SIZE - 1);
392                 int plen = PAGE_CACHE_SIZE - poff;
393
394                 if (plen > len)
395                         plen = len;
396                 lnb->lnb_file_offset = offset;
397                 lnb->lnb_page_offset = poff;
398                 lnb->lnb_len = plen;
399                 /* lnb->lnb_flags = rnb->rnb_flags; */
400                 lnb->lnb_flags = 0;
401                 lnb->lnb_page = NULL;
402                 lnb->lnb_rc = 0;
403
404                 LASSERTF(plen <= len, "plen %u, len %lld\n", plen,
405                          (long long) len);
406                 offset += plen;
407                 len -= plen;
408                 lnb++;
409                 (*nrpages)++;
410         }
411
412         RETURN(0);
413 }
414
415 struct page *osd_get_page(struct dt_object *dt, loff_t offset, int rw)
416 {
417         struct inode      *inode = osd_dt_obj(dt)->oo_inode;
418         struct osd_device *d = osd_obj2dev(osd_dt_obj(dt));
419         struct page       *page;
420
421         LASSERT(inode);
422
423         page = find_or_create_page(inode->i_mapping, offset >> PAGE_CACHE_SHIFT,
424                                    GFP_NOFS | __GFP_HIGHMEM);
425         if (unlikely(page == NULL))
426                 lprocfs_counter_add(d->od_stats, LPROC_OSD_NO_PAGE, 1);
427
428         return page;
429 }
430
431 /*
432  * there are following "locks":
433  * journal_start
434  * i_mutex
435  * page lock
436
437  * osd write path
438     * lock page(s)
439     * journal_start
440     * truncate_sem
441
442  * ext4 vmtruncate:
443     * lock pages, unlock
444     * journal_start
445     * lock partial page
446     * i_data_sem
447
448 */
449 int osd_bufs_get(const struct lu_env *env, struct dt_object *d, loff_t pos,
450                  ssize_t len, struct niobuf_local *lnb, int rw,
451                  struct lustre_capa *capa)
452 {
453         struct osd_object   *obj    = osd_dt_obj(d);
454         int npages, i, rc = 0;
455
456         LASSERT(obj->oo_inode);
457
458         osd_map_remote_to_local(pos, len, &npages, lnb);
459
460         for (i = 0; i < npages; i++, lnb++) {
461                 lnb->lnb_page = osd_get_page(d, lnb->lnb_file_offset, rw);
462                 if (lnb->lnb_page == NULL)
463                         GOTO(cleanup, rc = -ENOMEM);
464
465                 /* DLM locking protects us from write and truncate competing
466                  * for same region, but truncate can leave dirty page in the
467                  * cache. it's possible the writeout on a such a page is in
468                  * progress when we access it. it's also possible that during
469                  * this writeout we put new (partial) data, but then won't
470                  * be able to proceed in filter_commitrw_write(). thus let's
471                  * just wait for writeout completion, should be rare enough.
472                  * -bzzz */
473                 wait_on_page_writeback(lnb->lnb_page);
474                 BUG_ON(PageWriteback(lnb->lnb_page));
475
476                 lu_object_get(&d->do_lu);
477         }
478         rc = i;
479
480 cleanup:
481         RETURN(rc);
482 }
483
484 static int osd_bufs_put(const struct lu_env *env, struct dt_object *dt,
485                         struct niobuf_local *lnb, int npages)
486 {
487         int i;
488
489         for (i = 0; i < npages; i++) {
490                 if (lnb[i].lnb_page == NULL)
491                         continue;
492                 LASSERT(PageLocked(lnb[i].lnb_page));
493                 unlock_page(lnb[i].lnb_page);
494                 page_cache_release(lnb[i].lnb_page);
495                 lu_object_put(env, &dt->do_lu);
496                 lnb[i].lnb_page = NULL;
497         }
498
499         RETURN(0);
500 }
501
502 #ifndef HAVE_LDISKFS_MAP_BLOCKS
503
504 #ifdef HAVE_EXT_PBLOCK /* Name changed to ext4_ext_pblock for kernel 2.6.35 */
505 #define ldiskfs_ext_pblock(ex) ext_pblock((ex))
506 #endif
507
508 struct bpointers {
509         unsigned long *blocks;
510         unsigned long start;
511         int num;
512         int init_num;
513         int create;
514 };
515
516 static long ldiskfs_ext_find_goal(struct inode *inode,
517                                   struct ldiskfs_ext_path *path,
518                                   unsigned long block, int *aflags)
519 {
520         struct ldiskfs_inode_info *ei = LDISKFS_I(inode);
521         unsigned long bg_start;
522         unsigned long colour;
523         int depth;
524
525         if (path) {
526                 struct ldiskfs_extent *ex;
527                 depth = path->p_depth;
528
529                 /* try to predict block placement */
530                 if ((ex = path[depth].p_ext))
531                         return ldiskfs_ext_pblock(ex) +
532                                 (block - le32_to_cpu(ex->ee_block));
533
534                 /* it looks index is empty
535                  * try to find starting from index itself */
536                 if (path[depth].p_bh)
537                         return path[depth].p_bh->b_blocknr;
538         }
539
540         /* OK. use inode's group */
541         bg_start = (ei->i_block_group * LDISKFS_BLOCKS_PER_GROUP(inode->i_sb)) +
542                 le32_to_cpu(LDISKFS_SB(inode->i_sb)->s_es->s_first_data_block);
543         colour = (current->pid % 16) *
544                 (LDISKFS_BLOCKS_PER_GROUP(inode->i_sb) / 16);
545         return bg_start + colour + block;
546 }
547
548 static unsigned long new_blocks(handle_t *handle, struct inode *inode,
549                                 struct ldiskfs_ext_path *path,
550                                 unsigned long block, unsigned long *count,
551                                 int *err)
552 {
553         struct ldiskfs_allocation_request ar;
554         unsigned long pblock;
555         int aflags;
556
557         /* find neighbour allocated blocks */
558         ar.lleft = block;
559         *err = ldiskfs_ext_search_left(inode, path, &ar.lleft, &ar.pleft);
560         if (*err)
561                 return 0;
562         ar.lright = block;
563         *err = ldiskfs_ext_search_right(inode, path, &ar.lright, &ar.pright);
564         if (*err)
565                 return 0;
566
567         /* allocate new block */
568         ar.goal = ldiskfs_ext_find_goal(inode, path, block, &aflags);
569         ar.inode = inode;
570         ar.logical = block;
571         ar.len = *count;
572         ar.flags = LDISKFS_MB_HINT_DATA;
573         pblock = ldiskfs_mb_new_blocks(handle, &ar, err);
574         *count = ar.len;
575         return pblock;
576 }
577
578 static int ldiskfs_ext_new_extent_cb(struct inode *inode,
579                                      struct ldiskfs_ext_path *path,
580                                      struct ldiskfs_ext_cache *cex,
581 #ifdef HAVE_EXT_PREPARE_CB_EXTENT
582                                      struct ldiskfs_extent *ex,
583 #endif
584                                      void *cbdata)
585 {
586         struct bpointers *bp = cbdata;
587         struct ldiskfs_extent nex;
588         unsigned long pblock;
589         unsigned long tgen;
590         int err, i;
591         unsigned long count;
592         handle_t *handle;
593
594 #ifdef LDISKFS_EXT_CACHE_EXTENT /* until kernel 2.6.37 */
595         if (cex->ec_type == LDISKFS_EXT_CACHE_EXTENT) {
596 #else
597         if ((cex->ec_len != 0) && (cex->ec_start != 0)) {
598 #endif
599                 err = EXT_CONTINUE;
600                 goto map;
601         }
602
603         if (bp->create == 0) {
604                 i = 0;
605                 if (cex->ec_block < bp->start)
606                         i = bp->start - cex->ec_block;
607                 if (i >= cex->ec_len)
608                         CERROR("nothing to do?! i = %d, e_num = %u\n",
609                                         i, cex->ec_len);
610                 for (; i < cex->ec_len && bp->num; i++) {
611                         *(bp->blocks) = 0;
612                         bp->blocks++;
613                         bp->num--;
614                         bp->start++;
615                 }
616
617                 return EXT_CONTINUE;
618         }
619
620         tgen = LDISKFS_I(inode)->i_ext_generation;
621         count = ldiskfs_ext_calc_credits_for_insert(inode, path);
622
623         handle = osd_journal_start(inode, LDISKFS_HT_MISC,
624                                    count + LDISKFS_ALLOC_NEEDED + 1);
625         if (IS_ERR(handle)) {
626                 return PTR_ERR(handle);
627         }
628
629         if (tgen != LDISKFS_I(inode)->i_ext_generation) {
630                 /* the tree has changed. so path can be invalid at moment */
631                 ldiskfs_journal_stop(handle);
632                 return EXT_REPEAT;
633         }
634
635         /* In 2.6.32 kernel, ldiskfs_ext_walk_space()'s callback func is not
636          * protected by i_data_sem as whole. so we patch it to store
637          * generation to path and now verify the tree hasn't changed */
638         down_write((&LDISKFS_I(inode)->i_data_sem));
639
640         /* validate extent, make sure the extent tree does not changed */
641         if (LDISKFS_I(inode)->i_ext_generation != path[0].p_generation) {
642                 /* cex is invalid, try again */
643                 up_write(&LDISKFS_I(inode)->i_data_sem);
644                 ldiskfs_journal_stop(handle);
645                 return EXT_REPEAT;
646         }
647
648         count = cex->ec_len;
649         pblock = new_blocks(handle, inode, path, cex->ec_block, &count, &err);
650         if (!pblock)
651                 goto out;
652         BUG_ON(count > cex->ec_len);
653
654         /* insert new extent */
655         nex.ee_block = cpu_to_le32(cex->ec_block);
656         ldiskfs_ext_store_pblock(&nex, pblock);
657         nex.ee_len = cpu_to_le16(count);
658         err = ldiskfs_ext_insert_extent(handle, inode, path, &nex, 0);
659         if (err) {
660                 /* free data blocks we just allocated */
661                 /* not a good idea to call discard here directly,
662                  * but otherwise we'd need to call it every free() */
663                 ldiskfs_discard_preallocations(inode);
664 #ifdef HAVE_EXT_FREE_BLOCK_WITH_BUFFER_HEAD /* Introduced in 2.6.32-rc7 */
665                 ldiskfs_free_blocks(handle, inode, NULL,
666                                     ldiskfs_ext_pblock(&nex),
667                                     le16_to_cpu(nex.ee_len), 0);
668 #else
669                 ldiskfs_free_blocks(handle, inode, ldiskfs_ext_pblock(&nex),
670                                     le16_to_cpu(nex.ee_len), 0);
671 #endif
672                 goto out;
673         }
674
675         /*
676          * Putting len of the actual extent we just inserted,
677          * we are asking ldiskfs_ext_walk_space() to continue
678          * scaning after that block
679          */
680         cex->ec_len = le16_to_cpu(nex.ee_len);
681         cex->ec_start = ldiskfs_ext_pblock(&nex);
682         BUG_ON(le16_to_cpu(nex.ee_len) == 0);
683         BUG_ON(le32_to_cpu(nex.ee_block) != cex->ec_block);
684
685 out:
686         up_write((&LDISKFS_I(inode)->i_data_sem));
687         ldiskfs_journal_stop(handle);
688 map:
689         if (err >= 0) {
690                 /* map blocks */
691                 if (bp->num == 0) {
692                         CERROR("hmm. why do we find this extent?\n");
693                         CERROR("initial space: %lu:%u\n",
694                                 bp->start, bp->init_num);
695 #ifdef LDISKFS_EXT_CACHE_EXTENT /* until kernel 2.6.37 */
696                         CERROR("current extent: %u/%u/%llu %d\n",
697                                 cex->ec_block, cex->ec_len,
698                                 (unsigned long long)cex->ec_start,
699                                 cex->ec_type);
700 #else
701                         CERROR("current extent: %u/%u/%llu\n",
702                                 cex->ec_block, cex->ec_len,
703                                 (unsigned long long)cex->ec_start);
704 #endif
705                 }
706                 i = 0;
707                 if (cex->ec_block < bp->start)
708                         i = bp->start - cex->ec_block;
709                 if (i >= cex->ec_len)
710                         CERROR("nothing to do?! i = %d, e_num = %u\n",
711                                         i, cex->ec_len);
712                 for (; i < cex->ec_len && bp->num; i++) {
713                         *(bp->blocks) = cex->ec_start + i;
714 #ifdef LDISKFS_EXT_CACHE_EXTENT /* until kernel 2.6.37 */
715                         if (cex->ec_type != LDISKFS_EXT_CACHE_EXTENT) {
716 #else
717                         if ((cex->ec_len == 0) || (cex->ec_start == 0)) {
718 #endif
719                                 /* unmap any possible underlying metadata from
720                                  * the block device mapping.  bug 6998. */
721                                 unmap_underlying_metadata(inode->i_sb->s_bdev,
722                                                           *(bp->blocks));
723                         }
724                         bp->blocks++;
725                         bp->num--;
726                         bp->start++;
727                 }
728         }
729         return err;
730 }
731
732 int osd_ldiskfs_map_nblocks(struct inode *inode, unsigned long block,
733                             unsigned long num, unsigned long *blocks,
734                             int create)
735 {
736         struct bpointers bp;
737         int err;
738
739         CDEBUG(D_OTHER, "blocks %lu-%lu requested for inode %u\n",
740                block, block + num - 1, (unsigned) inode->i_ino);
741
742         bp.blocks = blocks;
743         bp.start = block;
744         bp.init_num = bp.num = num;
745         bp.create = create;
746
747         err = ldiskfs_ext_walk_space(inode, block, num,
748                                          ldiskfs_ext_new_extent_cb, &bp);
749         ldiskfs_ext_invalidate_cache(inode);
750
751         return err;
752 }
753
754 int osd_ldiskfs_map_bm_inode_pages(struct inode *inode, struct page **page,
755                                    int pages, unsigned long *blocks,
756                                    int create)
757 {
758         int blocks_per_page = PAGE_CACHE_SIZE >> inode->i_blkbits;
759         unsigned long *b;
760         int rc = 0, i;
761
762         for (i = 0, b = blocks; i < pages; i++, page++) {
763                 rc = ldiskfs_map_inode_page(inode, *page, b, create);
764                 if (rc) {
765                         CERROR("ino %lu, blk %lu create %d: rc %d\n",
766                                inode->i_ino, *b, create, rc);
767                         break;
768                 }
769                 b += blocks_per_page;
770         }
771         return rc;
772 }
773
774 int osd_ldiskfs_map_ext_inode_pages(struct inode *inode, struct page **page,
775                                     int pages, unsigned long *blocks,
776                                     int create)
777 {
778         int blocks_per_page = PAGE_CACHE_SIZE >> inode->i_blkbits;
779         int rc = 0, i = 0;
780         struct page *fp = NULL;
781         int clen = 0;
782
783         CDEBUG(D_OTHER, "inode %lu: map %d pages from %lu\n",
784                 inode->i_ino, pages, (*page)->index);
785
786         /* pages are sorted already. so, we just have to find
787          * contig. space and process them properly */
788         while (i < pages) {
789                 if (fp == NULL) {
790                         /* start new extent */
791                         fp = *page++;
792                         clen = 1;
793                         i++;
794                         continue;
795                 } else if (fp->index + clen == (*page)->index) {
796                         /* continue the extent */
797                         page++;
798                         clen++;
799                         i++;
800                         continue;
801                 }
802
803                 /* process found extent */
804                 rc = osd_ldiskfs_map_nblocks(inode, fp->index * blocks_per_page,
805                                              clen * blocks_per_page, blocks,
806                                              create);
807                 if (rc)
808                         GOTO(cleanup, rc);
809
810                 /* look for next extent */
811                 fp = NULL;
812                 blocks += blocks_per_page * clen;
813         }
814
815         if (fp)
816                 rc = osd_ldiskfs_map_nblocks(inode, fp->index * blocks_per_page,
817                                              clen * blocks_per_page, blocks,
818                                              create);
819 cleanup:
820         return rc;
821 }
822
823 static int osd_ldiskfs_map_inode_pages(struct inode *inode, struct page **page,
824                                        int pages, unsigned long *blocks,
825                                        int create)
826 {
827         int rc;
828
829         if (LDISKFS_I(inode)->i_flags & LDISKFS_EXTENTS_FL) {
830                 rc = osd_ldiskfs_map_ext_inode_pages(inode, page, pages,
831                                                      blocks, create);
832                 return rc;
833         }
834         rc = osd_ldiskfs_map_bm_inode_pages(inode, page, pages, blocks, create);
835
836         return rc;
837 }
838 #else
839 static int osd_ldiskfs_map_inode_pages(struct inode *inode, struct page **page,
840                                        int pages, unsigned long *blocks,
841                                        int create)
842 {
843         int blocks_per_page = PAGE_CACHE_SIZE >> inode->i_blkbits;
844         int rc = 0, i = 0;
845         struct page *fp = NULL;
846         int clen = 0;
847
848         CDEBUG(D_OTHER, "inode %lu: map %d pages from %lu\n",
849                 inode->i_ino, pages, (*page)->index);
850
851         /* pages are sorted already. so, we just have to find
852          * contig. space and process them properly */
853         while (i < pages) {
854                 long blen, total = 0;
855                 handle_t *handle = NULL;
856                 struct ldiskfs_map_blocks map = { 0 };
857
858                 if (fp == NULL) { /* start new extent */
859                         fp = *page++;
860                         clen = 1;
861                         if (++i != pages)
862                                 continue;
863                 } else if (fp->index + clen == (*page)->index) {
864                         /* continue the extent */
865                         page++;
866                         clen++;
867                         if (++i != pages)
868                                 continue;
869                 }
870                 /* process found extent */
871                 map.m_lblk = fp->index * blocks_per_page;
872                 map.m_len = blen = clen * blocks_per_page;
873                 if (create) {
874                         create = LDISKFS_GET_BLOCKS_CREATE;
875                         handle = ldiskfs_journal_current_handle();
876                         LASSERT(handle != NULL);
877                 }
878 cont_map:
879                 rc = ldiskfs_map_blocks(handle, inode, &map, create);
880                 if (rc >= 0) {
881                         int c = 0;
882                         for (; total < blen && c < map.m_len; c++, total++) {
883                                 if (rc == 0) {
884                                         *(blocks + total) = 0;
885                                         total++;
886                                         break;
887                                 } else {
888                                         *(blocks + total) = map.m_pblk + c;
889                                         /* unmap any possible underlying
890                                          * metadata from the block device
891                                          * mapping.  bug 6998. */
892                                         if ((map.m_flags & LDISKFS_MAP_NEW) &&
893                                             create)
894                                                 unmap_underlying_metadata(
895                                                         inode->i_sb->s_bdev,
896                                                         map.m_pblk + c);
897                                 }
898                         }
899                         rc = 0;
900                 }
901                 if (rc == 0 && total < blen) {
902                         map.m_lblk = fp->index * blocks_per_page + total;
903                         map.m_len = blen - total;
904                         goto cont_map;
905                 }
906                 if (rc != 0)
907                         GOTO(cleanup, rc);
908
909                 /* look for next extent */
910                 fp = NULL;
911                 blocks += blocks_per_page * clen;
912         }
913 cleanup:
914         return rc;
915 }
916 #endif /* HAVE_LDISKFS_MAP_BLOCKS */
917
918 static int osd_write_prep(const struct lu_env *env, struct dt_object *dt,
919                           struct niobuf_local *lnb, int npages)
920 {
921         struct osd_thread_info *oti   = osd_oti_get(env);
922         struct osd_iobuf       *iobuf = &oti->oti_iobuf;
923         struct inode           *inode = osd_dt_obj(dt)->oo_inode;
924         struct osd_device      *osd   = osd_obj2dev(osd_dt_obj(dt));
925         struct timeval          start;
926         struct timeval          end;
927         unsigned long           timediff;
928         ssize_t                 isize;
929         __s64                   maxidx;
930         int                     rc = 0;
931         int                     i;
932         int                     cache = 0;
933
934         LASSERT(inode);
935
936         rc = osd_init_iobuf(osd, iobuf, 0, npages);
937         if (unlikely(rc != 0))
938                 RETURN(rc);
939
940         isize = i_size_read(inode);
941         maxidx = ((isize + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT) - 1;
942
943         if (osd->od_writethrough_cache)
944                 cache = 1;
945         if (isize > osd->od_readcache_max_filesize)
946                 cache = 0;
947
948         do_gettimeofday(&start);
949         for (i = 0; i < npages; i++) {
950
951                 if (cache == 0)
952                         generic_error_remove_page(inode->i_mapping,
953                                                   lnb[i].lnb_page);
954
955                 /*
956                  * till commit the content of the page is undefined
957                  * we'll set it uptodate once bulk is done. otherwise
958                  * subsequent reads can access non-stable data
959                  */
960                 ClearPageUptodate(lnb[i].lnb_page);
961
962                 if (lnb[i].lnb_len == PAGE_CACHE_SIZE)
963                         continue;
964
965                 if (maxidx >= lnb[i].lnb_page->index) {
966                         osd_iobuf_add_page(iobuf, lnb[i].lnb_page);
967                 } else {
968                         long off;
969                         char *p = kmap(lnb[i].lnb_page);
970
971                         off = lnb[i].lnb_page_offset;
972                         if (off)
973                                 memset(p, 0, off);
974                         off = (lnb[i].lnb_page_offset + lnb[i].lnb_len) &
975                               ~CFS_PAGE_MASK;
976                         if (off)
977                                 memset(p + off, 0, PAGE_CACHE_SIZE - off);
978                         kunmap(lnb[i].lnb_page);
979                 }
980         }
981         do_gettimeofday(&end);
982         timediff = cfs_timeval_sub(&end, &start, NULL);
983         lprocfs_counter_add(osd->od_stats, LPROC_OSD_GET_PAGE, timediff);
984
985         if (iobuf->dr_npages) {
986                 rc = osd_ldiskfs_map_inode_pages(inode, iobuf->dr_pages,
987                                                  iobuf->dr_npages,
988                                                  iobuf->dr_blocks, 0);
989                 if (likely(rc == 0)) {
990                         rc = osd_do_bio(osd, inode, iobuf);
991                         /* do IO stats for preparation reads */
992                         osd_fini_iobuf(osd, iobuf);
993                 }
994         }
995         RETURN(rc);
996 }
997
998 /* Check if a block is allocated or not */
999 static int osd_is_mapped(struct inode *inode, obd_size offset)
1000 {
1001         sector_t (*fs_bmap)(struct address_space *, sector_t);
1002
1003         fs_bmap = inode->i_mapping->a_ops->bmap;
1004
1005         /* We can't know if we are overwriting or not */
1006         if (unlikely(fs_bmap == NULL))
1007                 return 0;
1008
1009         if (i_size_read(inode) == 0)
1010                 return 0;
1011
1012         /* Beyond EOF, must not be mapped */
1013         if (((i_size_read(inode) - 1) >> inode->i_blkbits) <
1014             (offset >> inode->i_blkbits))
1015                 return 0;
1016
1017         if (fs_bmap(inode->i_mapping, offset >> inode->i_blkbits) == 0)
1018                 return 0;
1019
1020         return 1;
1021 }
1022
1023 static int osd_declare_write_commit(const struct lu_env *env,
1024                                     struct dt_object *dt,
1025                                     struct niobuf_local *lnb, int npages,
1026                                     struct thandle *handle)
1027 {
1028         const struct osd_device *osd = osd_obj2dev(osd_dt_obj(dt));
1029         struct inode            *inode = osd_dt_obj(dt)->oo_inode;
1030         struct osd_thandle      *oh;
1031         int                      extents = 1;
1032         int                      depth;
1033         int                      i;
1034         int                      newblocks;
1035         int                      rc = 0;
1036         int                      flags = 0;
1037         bool                     ignore_quota = false;
1038         long long                quota_space = 0;
1039         ENTRY;
1040
1041         LASSERT(handle != NULL);
1042         oh = container_of0(handle, struct osd_thandle, ot_super);
1043         LASSERT(oh->ot_handle == NULL);
1044
1045         newblocks = npages;
1046
1047         /* calculate number of extents (probably better to pass nb) */
1048         for (i = 0; i < npages; i++) {
1049                 if (i && lnb[i].lnb_file_offset !=
1050                     lnb[i - 1].lnb_file_offset + lnb[i - 1].lnb_len)
1051                         extents++;
1052
1053                 if (!osd_is_mapped(inode, lnb[i].lnb_file_offset))
1054                         quota_space += PAGE_CACHE_SIZE;
1055
1056                 /* ignore quota for the whole request if any page is from
1057                  * client cache or written by root.
1058                  *
1059                  * XXX once we drop the 1.8 client support, the checking
1060                  * for whether page is from cache can be simplified as:
1061                  * !(lnb[i].flags & OBD_BRW_SYNC)
1062                  *
1063                  * XXX we could handle this on per-lnb basis as done by
1064                  * grant. */
1065                 if ((lnb[i].lnb_flags & OBD_BRW_NOQUOTA) ||
1066                     (lnb[i].lnb_flags & (OBD_BRW_FROM_GRANT | OBD_BRW_SYNC)) ==
1067                     OBD_BRW_FROM_GRANT)
1068                         ignore_quota = true;
1069         }
1070
1071         /*
1072          * each extent can go into new leaf causing a split
1073          * 5 is max tree depth: inode + 4 index blocks
1074          * with blockmaps, depth is 3 at most
1075          */
1076         if (LDISKFS_I(inode)->i_flags & LDISKFS_EXTENTS_FL) {
1077                 /*
1078                  * many concurrent threads may grow tree by the time
1079                  * our transaction starts. so, consider 2 is a min depth
1080                  */
1081                 depth = ext_depth(inode);
1082                 depth = max(depth, 1) + 1;
1083                 newblocks += depth;
1084                 oh->ot_credits++; /* inode */
1085                 oh->ot_credits += depth * 2 * extents;
1086         } else {
1087                 depth = 3;
1088                 newblocks += depth;
1089                 oh->ot_credits++; /* inode */
1090                 oh->ot_credits += depth * extents;
1091         }
1092
1093         /* quota space for metadata blocks */
1094         quota_space += depth * extents * LDISKFS_BLOCK_SIZE(osd_sb(osd));
1095
1096         /* quota space should be reported in 1K blocks */
1097         quota_space = toqb(quota_space);
1098
1099         /* each new block can go in different group (bitmap + gd) */
1100
1101         /* we can't dirty more bitmap blocks than exist */
1102         if (newblocks > LDISKFS_SB(osd_sb(osd))->s_groups_count)
1103                 oh->ot_credits += LDISKFS_SB(osd_sb(osd))->s_groups_count;
1104         else
1105                 oh->ot_credits += newblocks;
1106
1107         /* we can't dirty more gd blocks than exist */
1108         if (newblocks > LDISKFS_SB(osd_sb(osd))->s_gdb_count)
1109                 oh->ot_credits += LDISKFS_SB(osd_sb(osd))->s_gdb_count;
1110         else
1111                 oh->ot_credits += newblocks;
1112
1113         /* make sure the over quota flags were not set */
1114         lnb[0].lnb_flags &= ~(OBD_BRW_OVER_USRQUOTA | OBD_BRW_OVER_GRPQUOTA);
1115
1116         rc = osd_declare_inode_qid(env, i_uid_read(inode), i_gid_read(inode),
1117                                    quota_space, oh, true, true, &flags,
1118                                    ignore_quota);
1119
1120         /* we need only to store the overquota flags in the first lnb for
1121          * now, once we support multiple objects BRW, this code needs be
1122          * revised. */
1123         if (flags & QUOTA_FL_OVER_USRQUOTA)
1124                 lnb[0].lnb_flags |= OBD_BRW_OVER_USRQUOTA;
1125         if (flags & QUOTA_FL_OVER_GRPQUOTA)
1126                 lnb[0].lnb_flags |= OBD_BRW_OVER_GRPQUOTA;
1127
1128         RETURN(rc);
1129 }
1130
1131 /* Check if a block is allocated or not */
1132 static int osd_write_commit(const struct lu_env *env, struct dt_object *dt,
1133                             struct niobuf_local *lnb, int npages,
1134                             struct thandle *thandle)
1135 {
1136         struct osd_thread_info *oti = osd_oti_get(env);
1137         struct osd_iobuf *iobuf = &oti->oti_iobuf;
1138         struct inode *inode = osd_dt_obj(dt)->oo_inode;
1139         struct osd_device  *osd = osd_obj2dev(osd_dt_obj(dt));
1140         loff_t isize;
1141         int rc = 0, i;
1142
1143         LASSERT(inode);
1144
1145         rc = osd_init_iobuf(osd, iobuf, 1, npages);
1146         if (unlikely(rc != 0))
1147                 RETURN(rc);
1148
1149         isize = i_size_read(inode);
1150         ll_vfs_dq_init(inode);
1151
1152         for (i = 0; i < npages; i++) {
1153                 if (lnb[i].lnb_rc == -ENOSPC &&
1154                     osd_is_mapped(inode, lnb[i].lnb_file_offset)) {
1155                         /* Allow the write to proceed if overwriting an
1156                          * existing block */
1157                         lnb[i].lnb_rc = 0;
1158                 }
1159
1160                 if (lnb[i].lnb_rc) { /* ENOSPC, network RPC error, etc. */
1161                         CDEBUG(D_INODE, "Skipping [%d] == %d\n", i,
1162                                lnb[i].lnb_rc);
1163                         LASSERT(lnb[i].lnb_page);
1164                         generic_error_remove_page(inode->i_mapping,
1165                                                   lnb[i].lnb_page);
1166                         continue;
1167                 }
1168
1169                 LASSERT(PageLocked(lnb[i].lnb_page));
1170                 LASSERT(!PageWriteback(lnb[i].lnb_page));
1171
1172                 if (lnb[i].lnb_file_offset + lnb[i].lnb_len > isize)
1173                         isize = lnb[i].lnb_file_offset + lnb[i].lnb_len;
1174
1175                 /*
1176                  * Since write and truncate are serialized by oo_sem, even
1177                  * partial-page truncate should not leave dirty pages in the
1178                  * page cache.
1179                  */
1180                 LASSERT(!PageDirty(lnb[i].lnb_page));
1181
1182                 SetPageUptodate(lnb[i].lnb_page);
1183
1184                 osd_iobuf_add_page(iobuf, lnb[i].lnb_page);
1185         }
1186
1187         if (OBD_FAIL_CHECK(OBD_FAIL_OST_MAPBLK_ENOSPC)) {
1188                 rc = -ENOSPC;
1189         } else if (iobuf->dr_npages > 0) {
1190                 rc = osd_ldiskfs_map_inode_pages(inode, iobuf->dr_pages,
1191                                                  iobuf->dr_npages,
1192                                                  iobuf->dr_blocks, 1);
1193         } else {
1194                 /* no pages to write, no transno is needed */
1195                 thandle->th_local = 1;
1196         }
1197
1198         if (likely(rc == 0)) {
1199                 if (isize > i_size_read(inode)) {
1200                         i_size_write(inode, isize);
1201                         LDISKFS_I(inode)->i_disksize = isize;
1202                         ll_dirty_inode(inode, I_DIRTY_DATASYNC);
1203                 }
1204
1205                 rc = osd_do_bio(osd, inode, iobuf);
1206                 /* we don't do stats here as in read path because
1207                  * write is async: we'll do this in osd_put_bufs() */
1208         } else {
1209                 osd_fini_iobuf(osd, iobuf);
1210         }
1211
1212         if (unlikely(rc != 0)) {
1213                 /* if write fails, we should drop pages from the cache */
1214                 for (i = 0; i < npages; i++) {
1215                         if (lnb[i].lnb_page == NULL)
1216                                 continue;
1217                         LASSERT(PageLocked(lnb[i].lnb_page));
1218                         generic_error_remove_page(inode->i_mapping,
1219                                                   lnb[i].lnb_page);
1220                 }
1221         }
1222
1223         RETURN(rc);
1224 }
1225
1226 static int osd_read_prep(const struct lu_env *env, struct dt_object *dt,
1227                          struct niobuf_local *lnb, int npages)
1228 {
1229         struct osd_thread_info *oti = osd_oti_get(env);
1230         struct osd_iobuf *iobuf = &oti->oti_iobuf;
1231         struct inode *inode = osd_dt_obj(dt)->oo_inode;
1232         struct osd_device *osd = osd_obj2dev(osd_dt_obj(dt));
1233         struct timeval start, end;
1234         unsigned long timediff;
1235         int rc = 0, i, m = 0, cache = 0, cache_hits = 0, cache_misses = 0;
1236
1237         LASSERT(inode);
1238
1239         rc = osd_init_iobuf(osd, iobuf, 0, npages);
1240         if (unlikely(rc != 0))
1241                 RETURN(rc);
1242
1243         if (osd->od_read_cache)
1244                 cache = 1;
1245         if (i_size_read(inode) > osd->od_readcache_max_filesize)
1246                 cache = 0;
1247
1248         do_gettimeofday(&start);
1249         for (i = 0; i < npages; i++) {
1250
1251                 if (i_size_read(inode) <= lnb[i].lnb_file_offset)
1252                         /* If there's no more data, abort early.
1253                          * lnb->lnb_rc == 0, so it's easy to detect later. */
1254                         break;
1255
1256                 if (i_size_read(inode) <
1257                     lnb[i].lnb_file_offset + lnb[i].lnb_len - 1)
1258                         lnb[i].lnb_rc = i_size_read(inode) -
1259                                 lnb[i].lnb_file_offset;
1260                 else
1261                         lnb[i].lnb_rc = lnb[i].lnb_len;
1262                 m += lnb[i].lnb_len;
1263
1264                 if (PageUptodate(lnb[i].lnb_page)) {
1265                         cache_hits++;
1266                 } else {
1267                         cache_misses++;
1268                         osd_iobuf_add_page(iobuf, lnb[i].lnb_page);
1269                 }
1270
1271                 if (cache == 0)
1272                         generic_error_remove_page(inode->i_mapping,
1273                                                   lnb[i].lnb_page);
1274         }
1275         do_gettimeofday(&end);
1276         timediff = cfs_timeval_sub(&end, &start, NULL);
1277         lprocfs_counter_add(osd->od_stats, LPROC_OSD_GET_PAGE, timediff);
1278
1279         if (cache_hits != 0)
1280                 lprocfs_counter_add(osd->od_stats, LPROC_OSD_CACHE_HIT,
1281                                     cache_hits);
1282         if (cache_misses != 0)
1283                 lprocfs_counter_add(osd->od_stats, LPROC_OSD_CACHE_MISS,
1284                                     cache_misses);
1285         if (cache_hits + cache_misses != 0)
1286                 lprocfs_counter_add(osd->od_stats, LPROC_OSD_CACHE_ACCESS,
1287                                     cache_hits + cache_misses);
1288
1289         if (iobuf->dr_npages) {
1290                 rc = osd_ldiskfs_map_inode_pages(inode, iobuf->dr_pages,
1291                                                  iobuf->dr_npages,
1292                                                  iobuf->dr_blocks, 0);
1293                 rc = osd_do_bio(osd, inode, iobuf);
1294
1295                 /* IO stats will be done in osd_bufs_put() */
1296         }
1297
1298         RETURN(rc);
1299 }
1300
1301 /*
1302  * XXX: Another layering violation for now.
1303  *
1304  * We don't want to use ->f_op->read methods, because generic file write
1305  *
1306  *         - serializes on ->i_sem, and
1307  *
1308  *         - does a lot of extra work like balance_dirty_pages(),
1309  *
1310  * which doesn't work for globally shared files like /last_rcvd.
1311  */
1312 static int osd_ldiskfs_readlink(struct inode *inode, char *buffer, int buflen)
1313 {
1314         struct ldiskfs_inode_info *ei = LDISKFS_I(inode);
1315
1316         memcpy(buffer, (char *)ei->i_data, buflen);
1317
1318         return  buflen;
1319 }
1320
1321 int osd_ldiskfs_read(struct inode *inode, void *buf, int size, loff_t *offs)
1322 {
1323         struct buffer_head *bh;
1324         unsigned long block;
1325         int osize;
1326         int blocksize;
1327         int csize;
1328         int boffs;
1329         int err;
1330
1331         /* prevent reading after eof */
1332         spin_lock(&inode->i_lock);
1333         if (i_size_read(inode) < *offs + size) {
1334                 loff_t diff = i_size_read(inode) - *offs;
1335                 spin_unlock(&inode->i_lock);
1336                 if (diff < 0) {
1337                         CDEBUG(D_EXT2, "size %llu is too short to read @%llu\n",
1338                                i_size_read(inode), *offs);
1339                         return -EBADR;
1340                 } else if (diff == 0) {
1341                         return 0;
1342                 } else {
1343                         size = diff;
1344                 }
1345         } else {
1346                 spin_unlock(&inode->i_lock);
1347         }
1348
1349         blocksize = 1 << inode->i_blkbits;
1350         osize = size;
1351         while (size > 0) {
1352                 block = *offs >> inode->i_blkbits;
1353                 boffs = *offs & (blocksize - 1);
1354                 csize = min(blocksize - boffs, size);
1355                 bh = ldiskfs_bread(NULL, inode, block, 0, &err);
1356                 if (!bh) {
1357                         CERROR("%s: can't read %u@%llu on ino %lu: rc = %d\n",
1358                                LDISKFS_SB(inode->i_sb)->s_es->s_volume_name,
1359                                csize, *offs, inode->i_ino, err);
1360                         return err;
1361                 }
1362
1363                 memcpy(buf, bh->b_data + boffs, csize);
1364                 brelse(bh);
1365
1366                 *offs += csize;
1367                 buf += csize;
1368                 size -= csize;
1369         }
1370         return osize;
1371 }
1372
1373 static ssize_t osd_read(const struct lu_env *env, struct dt_object *dt,
1374                         struct lu_buf *buf, loff_t *pos,
1375                         struct lustre_capa *capa)
1376 {
1377         struct inode *inode = osd_dt_obj(dt)->oo_inode;
1378         int           rc;
1379
1380         if (osd_object_auth(env, dt, capa, CAPA_OPC_BODY_READ))
1381                 RETURN(-EACCES);
1382
1383         /* Read small symlink from inode body as we need to maintain correct
1384          * on-disk symlinks for ldiskfs.
1385          */
1386         if (S_ISLNK(dt->do_lu.lo_header->loh_attr) &&
1387             (buf->lb_len < sizeof(LDISKFS_I(inode)->i_data)))
1388                 rc = osd_ldiskfs_readlink(inode, buf->lb_buf, buf->lb_len);
1389         else
1390                 rc = osd_ldiskfs_read(inode, buf->lb_buf, buf->lb_len, pos);
1391
1392         return rc;
1393 }
1394
1395 static inline int osd_extents_enabled(struct super_block *sb,
1396                                       struct inode *inode)
1397 {
1398         if (inode != NULL) {
1399                 if (LDISKFS_I(inode)->i_flags & LDISKFS_EXTENTS_FL)
1400                         return 1;
1401         } else if (test_opt(sb, EXTENTS)) {
1402                 return 1;
1403         }
1404         return 0;
1405 }
1406
1407 static inline int osd_calc_bkmap_credits(struct super_block *sb,
1408                                          struct inode *inode,
1409                                          const loff_t size,
1410                                          const loff_t pos,
1411                                          const int blocks)
1412 {
1413         int credits, bits, bs, i;
1414
1415         bits = sb->s_blocksize_bits;
1416         bs = 1 << bits;
1417
1418         /* legacy blockmap: 3 levels * 3 (bitmap,gd,itself)
1419          * we do not expect blockmaps on the large files,
1420          * so let's shrink it to 2 levels (4GB files) */
1421
1422         /* this is default reservation: 2 levels */
1423         credits = (blocks + 2) * 3;
1424
1425         /* actual offset is unknown, hard to optimize */
1426         if (pos == -1)
1427                 return credits;
1428
1429         /* now check for few specific cases to optimize */
1430         if (pos + size <= LDISKFS_NDIR_BLOCKS * bs) {
1431                 /* no indirects */
1432                 credits = blocks;
1433                 /* allocate if not allocated */
1434                 if (inode == NULL) {
1435                         credits += blocks * 2;
1436                         return credits;
1437                 }
1438                 for (i = (pos >> bits); i < (pos >> bits) + blocks; i++) {
1439                         LASSERT(i < LDISKFS_NDIR_BLOCKS);
1440                         if (LDISKFS_I(inode)->i_data[i] == 0)
1441                                 credits += 2;
1442                 }
1443         } else if (pos + size <= (LDISKFS_NDIR_BLOCKS + 1024) * bs) {
1444                 /* single indirect */
1445                 credits = blocks * 3;
1446                 /* probably indirect block has been allocated already */
1447                 if (!inode || LDISKFS_I(inode)->i_data[LDISKFS_IND_BLOCK])
1448                         credits += 3;
1449         }
1450
1451         return credits;
1452 }
1453
1454 static ssize_t osd_declare_write(const struct lu_env *env, struct dt_object *dt,
1455                                  const struct lu_buf *buf, loff_t _pos,
1456                                  struct thandle *handle)
1457 {
1458         struct osd_object  *obj  = osd_dt_obj(dt);
1459         struct inode       *inode = obj->oo_inode;
1460         struct super_block *sb = osd_sb(osd_obj2dev(obj));
1461         struct osd_thandle *oh;
1462         int                 rc = 0, est = 0, credits, blocks, allocated = 0;
1463         int                 bits, bs;
1464         int                 depth, size;
1465         loff_t              pos;
1466         ENTRY;
1467
1468         LASSERT(buf != NULL);
1469         LASSERT(handle != NULL);
1470
1471         oh = container_of0(handle, struct osd_thandle, ot_super);
1472         LASSERT(oh->ot_handle == NULL);
1473
1474         size = buf->lb_len;
1475         bits = sb->s_blocksize_bits;
1476         bs = 1 << bits;
1477
1478         if (_pos == -1) {
1479                 /* if this is an append, then we
1480                  * should expect cross-block record */
1481                 pos = 0;
1482         } else {
1483                 pos = _pos;
1484         }
1485
1486         /* blocks to modify */
1487         blocks = ((pos + size + bs - 1) >> bits) - (pos >> bits);
1488         LASSERT(blocks > 0);
1489
1490         if (inode != NULL && _pos != -1) {
1491                 /* object size in blocks */
1492                 est = (i_size_read(inode) + bs - 1) >> bits;
1493                 allocated = inode->i_blocks >> (bits - 9);
1494                 if (pos + size <= i_size_read(inode) && est <= allocated) {
1495                         /* looks like an overwrite, no need to modify tree */
1496                         credits = blocks;
1497                         /* no need to modify i_size */
1498                         goto out;
1499                 }
1500         }
1501
1502         if (osd_extents_enabled(sb, inode)) {
1503                 /*
1504                  * many concurrent threads may grow tree by the time
1505                  * our transaction starts. so, consider 2 is a min depth
1506                  * for every level we may need to allocate a new block
1507                  * and take some entries from the old one. so, 3 blocks
1508                  * to allocate (bitmap, gd, itself) + old block - 4 per
1509                  * level.
1510                  */
1511                 depth = inode != NULL ? ext_depth(inode) : 0;
1512                 depth = max(depth, 1) + 1;
1513                 credits = depth;
1514                 /* if not append, then split may need to modify
1515                  * existing blocks moving entries into the new ones */
1516                 if (_pos == -1)
1517                         credits += depth;
1518                 /* blocks to store data: bitmap,gd,itself */
1519                 credits += blocks * 3;
1520         } else {
1521                 credits = osd_calc_bkmap_credits(sb, inode, size, _pos, blocks);
1522         }
1523         /* if inode is created as part of the transaction,
1524          * then it's counted already by the creation method */
1525         if (inode != NULL)
1526                 credits++;
1527
1528 out:
1529
1530         osd_trans_declare_op(env, oh, OSD_OT_WRITE, credits);
1531
1532         /* dt_declare_write() is usually called for system objects, such
1533          * as llog or last_rcvd files. We needn't enforce quota on those
1534          * objects, so always set the lqi_space as 0. */
1535         if (inode != NULL)
1536                 rc = osd_declare_inode_qid(env, i_uid_read(inode),
1537                                            i_gid_read(inode), 0, oh, true,
1538                                            true, NULL, false);
1539         RETURN(rc);
1540 }
1541
1542 static int osd_ldiskfs_writelink(struct inode *inode, char *buffer, int buflen)
1543 {
1544         /* LU-2634: clear the extent format for fast symlink */
1545         ldiskfs_clear_inode_flag(inode, LDISKFS_INODE_EXTENTS);
1546
1547         memcpy((char *)&LDISKFS_I(inode)->i_data, (char *)buffer, buflen);
1548         LDISKFS_I(inode)->i_disksize = buflen;
1549         i_size_write(inode, buflen);
1550         ll_dirty_inode(inode, I_DIRTY_DATASYNC);
1551
1552         return 0;
1553 }
1554
1555 int osd_ldiskfs_write_record(struct inode *inode, void *buf, int bufsize,
1556                              int write_NUL, loff_t *offs, handle_t *handle)
1557 {
1558         struct buffer_head *bh        = NULL;
1559         loff_t              offset    = *offs;
1560         loff_t              new_size  = i_size_read(inode);
1561         unsigned long       block;
1562         int                 blocksize = 1 << inode->i_blkbits;
1563         int                 err = 0;
1564         int                 size;
1565         int                 boffs;
1566         int                 dirty_inode = 0;
1567
1568         if (write_NUL) {
1569                 /*
1570                  * long symlink write does not count the NUL terminator in
1571                  * bufsize, we write it, and the inode's file size does not
1572                  * count the NUL terminator as well.
1573                  */
1574                 ((char *)buf)[bufsize] = '\0';
1575                 ++bufsize;
1576         }
1577         while (bufsize > 0) {
1578                 if (bh != NULL)
1579                         brelse(bh);
1580
1581                 block = offset >> inode->i_blkbits;
1582                 boffs = offset & (blocksize - 1);
1583                 size = min(blocksize - boffs, bufsize);
1584                 bh = ldiskfs_bread(handle, inode, block, 1, &err);
1585                 if (!bh) {
1586                         CERROR("%s: error reading offset %llu (block %lu): "
1587                                "rc = %d\n",
1588                                inode->i_sb->s_id, offset, block, err);
1589                         break;
1590                 }
1591
1592                 err = ldiskfs_journal_get_write_access(handle, bh);
1593                 if (err) {
1594                         CERROR("journal_get_write_access() returned error %d\n",
1595                                err);
1596                         break;
1597                 }
1598                 LASSERTF(boffs + size <= bh->b_size,
1599                          "boffs %d size %d bh->b_size %lu\n",
1600                          boffs, size, (unsigned long)bh->b_size);
1601                 memcpy(bh->b_data + boffs, buf, size);
1602                 err = ldiskfs_journal_dirty_metadata(handle, bh);
1603                 if (err)
1604                         break;
1605
1606                 if (offset + size > new_size)
1607                         new_size = offset + size;
1608                 offset += size;
1609                 bufsize -= size;
1610                 buf += size;
1611         }
1612         if (bh)
1613                 brelse(bh);
1614
1615         if (write_NUL)
1616                 --new_size;
1617         /* correct in-core and on-disk sizes */
1618         if (new_size > i_size_read(inode)) {
1619                 spin_lock(&inode->i_lock);
1620                 if (new_size > i_size_read(inode))
1621                         i_size_write(inode, new_size);
1622                 if (i_size_read(inode) > LDISKFS_I(inode)->i_disksize) {
1623                         LDISKFS_I(inode)->i_disksize = i_size_read(inode);
1624                         dirty_inode = 1;
1625                 }
1626                 spin_unlock(&inode->i_lock);
1627                 if (dirty_inode)
1628                         ll_dirty_inode(inode, I_DIRTY_DATASYNC);
1629         }
1630
1631         if (err == 0)
1632                 *offs = offset;
1633         return err;
1634 }
1635
1636 static ssize_t osd_write(const struct lu_env *env, struct dt_object *dt,
1637                          const struct lu_buf *buf, loff_t *pos,
1638                          struct thandle *handle, struct lustre_capa *capa,
1639                          int ignore_quota)
1640 {
1641         struct inode            *inode = osd_dt_obj(dt)->oo_inode;
1642         struct osd_thandle      *oh;
1643         ssize_t                 result;
1644         int                     is_link;
1645
1646         LASSERT(dt_object_exists(dt));
1647
1648         if (osd_object_auth(env, dt, capa, CAPA_OPC_BODY_WRITE))
1649                 return -EACCES;
1650
1651         LASSERT(handle != NULL);
1652         LASSERT(inode != NULL);
1653         ll_vfs_dq_init(inode);
1654
1655         /* XXX: don't check: one declared chunk can be used many times */
1656         /* osd_trans_exec_op(env, handle, OSD_OT_WRITE); */
1657
1658         oh = container_of(handle, struct osd_thandle, ot_super);
1659         LASSERT(oh->ot_handle->h_transaction != NULL);
1660         /* Write small symlink to inode body as we need to maintain correct
1661          * on-disk symlinks for ldiskfs.
1662          * Note: the buf->lb_buf contains a NUL terminator while buf->lb_len
1663          * does not count it in.
1664          */
1665         is_link = S_ISLNK(dt->do_lu.lo_header->loh_attr);
1666         if (is_link && (buf->lb_len < sizeof(LDISKFS_I(inode)->i_data)))
1667                 result = osd_ldiskfs_writelink(inode, buf->lb_buf, buf->lb_len);
1668         else
1669                 result = osd_ldiskfs_write_record(inode, buf->lb_buf,
1670                                                   buf->lb_len, is_link, pos,
1671                                                   oh->ot_handle);
1672         if (result == 0)
1673                 result = buf->lb_len;
1674         return result;
1675 }
1676
1677 static int osd_declare_punch(const struct lu_env *env, struct dt_object *dt,
1678                              __u64 start, __u64 end, struct thandle *th)
1679 {
1680         struct osd_thandle *oh;
1681         struct inode       *inode;
1682         int                 rc;
1683         ENTRY;
1684
1685         LASSERT(th);
1686         oh = container_of(th, struct osd_thandle, ot_super);
1687
1688         /*
1689          * we don't need to reserve credits for whole truncate
1690          * it's not possible as truncate may need to free too many
1691          * blocks and that won't fit a single transaction. instead
1692          * we reserve credits to change i_size and put inode onto
1693          * orphan list. if needed truncate will extend or restart
1694          * transaction
1695          */
1696         osd_trans_declare_op(env, oh, OSD_OT_PUNCH,
1697                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE] + 3);
1698
1699         inode = osd_dt_obj(dt)->oo_inode;
1700         LASSERT(inode);
1701
1702         rc = osd_declare_inode_qid(env, i_uid_read(inode), i_gid_read(inode),
1703                                    0, oh, true, true, NULL, false);
1704         RETURN(rc);
1705 }
1706
1707 static int osd_punch(const struct lu_env *env, struct dt_object *dt,
1708                      __u64 start, __u64 end, struct thandle *th,
1709                      struct lustre_capa *capa)
1710 {
1711         struct osd_thandle *oh;
1712         struct osd_object  *obj = osd_dt_obj(dt);
1713         struct inode       *inode = obj->oo_inode;
1714         handle_t           *h;
1715         tid_t               tid;
1716         int                rc = 0, rc2 = 0;
1717         ENTRY;
1718
1719         LASSERT(end == OBD_OBJECT_EOF);
1720         LASSERT(dt_object_exists(dt));
1721         LASSERT(osd_invariant(obj));
1722         LASSERT(inode != NULL);
1723         ll_vfs_dq_init(inode);
1724
1725         LASSERT(th);
1726         oh = container_of(th, struct osd_thandle, ot_super);
1727         LASSERT(oh->ot_handle->h_transaction != NULL);
1728
1729         osd_trans_exec_op(env, th, OSD_OT_PUNCH);
1730
1731         tid = oh->ot_handle->h_transaction->t_tid;
1732
1733         i_size_write(inode, start);
1734         ll_truncate_pagecache(inode, start);
1735 #ifdef HAVE_INODEOPS_TRUNCATE
1736         if (inode->i_op->truncate) {
1737                 inode->i_op->truncate(inode);
1738         } else
1739 #endif
1740                 ldiskfs_truncate(inode);
1741
1742         /*
1743          * For a partial-page truncate, flush the page to disk immediately to
1744          * avoid data corruption during direct disk write.  b=17397
1745          */
1746         if ((start & ~CFS_PAGE_MASK) != 0)
1747                 rc = filemap_fdatawrite_range(inode->i_mapping, start, start+1);
1748
1749         h = journal_current_handle();
1750         LASSERT(h != NULL);
1751         LASSERT(h == oh->ot_handle);
1752
1753         if (tid != h->h_transaction->t_tid) {
1754                 int credits = oh->ot_credits;
1755                 /*
1756                  * transaction has changed during truncate
1757                  * we need to restart the handle with our credits
1758                  */
1759                 if (h->h_buffer_credits < credits) {
1760                         if (ldiskfs_journal_extend(h, credits))
1761                                 rc2 = ldiskfs_journal_restart(h, credits);
1762                 }
1763         }
1764
1765         RETURN(rc == 0 ? rc2 : rc);
1766 }
1767
1768 static int osd_fiemap_get(const struct lu_env *env, struct dt_object *dt,
1769                           struct ll_user_fiemap *fm)
1770 {
1771         struct inode *inode = osd_dt_obj(dt)->oo_inode;
1772         struct osd_thread_info *info   = osd_oti_get(env);
1773         struct dentry          *dentry = &info->oti_obj_dentry;
1774         struct file            *file   = &info->oti_file;
1775         mm_segment_t            saved_fs;
1776         int rc;
1777
1778         LASSERT(inode);
1779         dentry->d_inode = inode;
1780         dentry->d_sb = inode->i_sb;
1781         file->f_dentry = dentry;
1782         file->f_mapping = inode->i_mapping;
1783         file->f_op = inode->i_fop;
1784         set_file_inode(file, inode);
1785
1786         saved_fs = get_fs();
1787         set_fs(get_ds());
1788         /* ldiskfs_ioctl does not have a inode argument */
1789         if (inode->i_fop->unlocked_ioctl)
1790                 rc = inode->i_fop->unlocked_ioctl(file, FSFILT_IOC_FIEMAP,
1791                                                   (long)fm);
1792         else
1793                 rc = -ENOTTY;
1794         set_fs(saved_fs);
1795         return rc;
1796 }
1797
1798 /*
1799  * in some cases we may need declare methods for objects being created
1800  * e.g., when we create symlink
1801  */
1802 const struct dt_body_operations osd_body_ops_new = {
1803         .dbo_declare_write = osd_declare_write,
1804 };
1805
1806 const struct dt_body_operations osd_body_ops = {
1807         .dbo_read                 = osd_read,
1808         .dbo_declare_write        = osd_declare_write,
1809         .dbo_write                = osd_write,
1810         .dbo_bufs_get             = osd_bufs_get,
1811         .dbo_bufs_put             = osd_bufs_put,
1812         .dbo_write_prep           = osd_write_prep,
1813         .dbo_declare_write_commit = osd_declare_write_commit,
1814         .dbo_write_commit         = osd_write_commit,
1815         .dbo_read_prep            = osd_read_prep,
1816         .dbo_declare_punch         = osd_declare_punch,
1817         .dbo_punch                 = osd_punch,
1818         .dbo_fiemap_get           = osd_fiemap_get,
1819 };
1820