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