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