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