Whamcloud - gitweb
d2b10e6a0d664f95d72fdc5682bb552e2dd42630
[fs/lustre-release.git] / lustre / osd-ldiskfs / osd_io.c
1 /* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
2  * vim:expandtab:shiftwidth=8:tabstop=8:
3  *
4  * GPL HEADER START
5  *
6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License version 2 only,
10  * as published by the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * General Public License version 2 for more details (a copy is included
16  * in the LICENSE file that accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License
19  * version 2 along with this program; If not, see
20  * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
21  *
22  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
23  * CA 95054 USA or visit www.sun.com if you need additional information or
24  * have any questions.
25  *
26  * GPL HEADER END
27  */
28 /*
29  * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
30  * Use is subject to license terms.
31  *
32  * Copyright (c) 2011, 2012, Whamcloud, Inc.
33  */
34 /*
35  * This file is part of Lustre, http://www.lustre.org/
36  * Lustre is a trademark of Sun Microsystems, Inc.
37  *
38  * lustre/osd/osd_io.c
39  *
40  * body operations
41  *
42  * Author: Nikita Danilov <nikita@clusterfs.com>
43  * Author: Alex Zhuravlev <bzzz@whamcloud.com>
44  *
45  */
46
47 /* LUSTRE_VERSION_CODE */
48 #include <lustre_ver.h>
49 /* prerequisite for linux/xattr.h */
50 #include <linux/types.h>
51 /* prerequisite for linux/xattr.h */
52 #include <linux/fs.h>
53
54 /* ext_depth() */
55 #include <ldiskfs/ldiskfs.h>
56 #include <ldiskfs/ldiskfs_jbd2.h>
57 #include <ldiskfs/ldiskfs_extents.h>
58
59 /*
60  * struct OBD_{ALLOC,FREE}*()
61  * OBD_FAIL_CHECK
62  */
63 #include <obd_support.h>
64
65 #include "osd_internal.h"
66
67 #ifndef HAVE_PAGE_CONSTANT
68 #define mapping_cap_page_constant_write(mapping) 0
69 #define SetPageConstant(page) do {} while (0)
70 #define ClearPageConstant(page) do {} while (0)
71 #endif
72
73 #ifndef HAS_GENERIC_ERROR_REMOVE_PAGE
74 int generic_error_remove_page(struct address_space *mapping, struct page *page)
75 {
76         if (mapping == NULL)
77                 return -EINVAL;
78
79         if (mapping != page->mapping)
80                 return -EIO;
81         /*
82          * Only punch for normal data pages for now.
83          * Handling other types like directories would need more auditing.
84          */
85         if (!S_ISREG(mapping->host->i_mode))
86                 return -EIO;
87
88         if (page_mapped(page)) {
89                 unmap_mapping_range(mapping,
90                                     (loff_t)page->index << PAGE_CACHE_SHIFT,
91                                     PAGE_CACHE_SIZE, 0);
92         }
93         truncate_complete_page(mapping, page);
94         return 0;
95 }
96 #endif
97
98 static void osd_init_iobuf(struct osd_device *d, struct osd_iobuf *iobuf,int rw)
99 {
100         cfs_waitq_init(&iobuf->dr_wait);
101         cfs_atomic_set(&iobuf->dr_numreqs, 0);
102         iobuf->dr_max_pages = PTLRPC_MAX_BRW_PAGES;
103         iobuf->dr_npages = 0;
104         iobuf->dr_error = 0;
105         iobuf->dr_dev = d;
106         iobuf->dr_frags = 0;
107         iobuf->dr_elapsed = 0;
108         /* must be counted before, so assert */
109         LASSERT(iobuf->dr_elapsed_valid == 0);
110         iobuf->dr_rw = rw;
111 }
112
113 static void osd_iobuf_add_page(struct osd_iobuf *iobuf, struct page *page)
114 {
115         LASSERT(iobuf->dr_npages < iobuf->dr_max_pages);
116         iobuf->dr_pages[iobuf->dr_npages++] = page;
117 }
118
119 void osd_fini_iobuf(struct osd_device *d, struct osd_iobuf *iobuf)
120 {
121         int rw = iobuf->dr_rw;
122
123         if (iobuf->dr_elapsed_valid) {
124                 iobuf->dr_elapsed_valid = 0;
125                 LASSERT(iobuf->dr_dev == d);
126                 LASSERT(iobuf->dr_frags > 0);
127                 lprocfs_oh_tally(&d->od_brw_stats.
128                                  hist[BRW_R_DIO_FRAGS+rw],
129                                  iobuf->dr_frags);
130                 lprocfs_oh_tally_log2(&d->od_brw_stats.hist[BRW_R_IO_TIME+rw],
131                                       iobuf->dr_elapsed);
132         }
133 }
134
135 #ifdef HAVE_BIO_ENDIO_2ARG
136 #define DIO_RETURN(a)
137 static void dio_complete_routine(struct bio *bio, int error)
138 #else
139 #define DIO_RETURN(a)   return(a)
140 static int dio_complete_routine(struct bio *bio, unsigned int done, int error)
141 #endif
142 {
143         struct osd_iobuf *iobuf = bio->bi_private;
144         struct bio_vec *bvl;
145         int i;
146
147         /* CAVEAT EMPTOR: possibly in IRQ context
148          * DO NOT record procfs stats here!!! */
149
150         if (unlikely(iobuf == NULL)) {
151                 CERROR("***** bio->bi_private is NULL!  This should never "
152                        "happen.  Normally, I would crash here, but instead I "
153                        "will dump the bio contents to the console.  Please "
154                        "report this to <http://jira.whamcloud.com/> , along "
155                        "with any interesting messages leading up to this point "
156                        "(like SCSI errors, perhaps).  Because bi_private is "
157                        "NULL, I can't wake up the thread that initiated this "
158                        "IO - you will probably have to reboot this node.\n");
159                 CERROR("bi_next: %p, bi_flags: %lx, bi_rw: %lu, bi_vcnt: %d, "
160                        "bi_idx: %d, bi->size: %d, bi_end_io: %p, bi_cnt: %d, "
161                        "bi_private: %p\n", bio->bi_next, bio->bi_flags,
162                        bio->bi_rw, bio->bi_vcnt, bio->bi_idx, bio->bi_size,
163                        bio->bi_end_io, cfs_atomic_read(&bio->bi_cnt),
164                        bio->bi_private);
165                 DIO_RETURN(0);
166         }
167
168         /* the check is outside of the cycle for performance reason -bzzz */
169         if (!cfs_test_bit(BIO_RW, &bio->bi_rw)) {
170                 bio_for_each_segment(bvl, bio, i) {
171                         if (likely(error == 0))
172                                 SetPageUptodate(bvl->bv_page);
173                         LASSERT(PageLocked(bvl->bv_page));
174                         ClearPageConstant(bvl->bv_page);
175                 }
176                 cfs_atomic_dec(&iobuf->dr_dev->od_r_in_flight);
177         } else {
178                 struct page *p = iobuf->dr_pages[0];
179                 if (p->mapping) {
180                         if (mapping_cap_page_constant_write(p->mapping)) {
181                                 bio_for_each_segment(bvl, bio, i) {
182                                         ClearPageConstant(bvl->bv_page);
183                                 }
184                         }
185                 }
186                 cfs_atomic_dec(&iobuf->dr_dev->od_w_in_flight);
187         }
188
189         /* any real error is good enough -bzzz */
190         if (error != 0 && iobuf->dr_error == 0)
191                 iobuf->dr_error = error;
192
193         if (cfs_atomic_dec_and_test(&iobuf->dr_numreqs)) {
194                 iobuf->dr_elapsed = jiffies - iobuf->dr_start_time;
195                 iobuf->dr_elapsed_valid = 1;
196                 cfs_waitq_signal(&iobuf->dr_wait);
197         }
198
199         /* Completed bios used to be chained off iobuf->dr_bios and freed in
200          * filter_clear_dreq().  It was then possible to exhaust the biovec-256
201          * mempool when serious on-disk fragmentation was encountered,
202          * deadlocking the OST.  The bios are now released as soon as complete
203          * so the pool cannot be exhausted while IOs are competing. bug 10076 */
204         bio_put(bio);
205         DIO_RETURN(0);
206 }
207
208 static void record_start_io(struct osd_iobuf *iobuf, int size)
209 {
210         struct osd_device    *osd = iobuf->dr_dev;
211         struct obd_histogram *h = osd->od_brw_stats.hist;
212
213         iobuf->dr_frags++;
214         cfs_atomic_inc(&iobuf->dr_numreqs);
215
216         if (iobuf->dr_rw == 0) {
217                 cfs_atomic_inc(&osd->od_r_in_flight);
218                 lprocfs_oh_tally(&h[BRW_R_RPC_HIST],
219                                  cfs_atomic_read(&osd->od_r_in_flight));
220                 lprocfs_oh_tally_log2(&h[BRW_R_DISK_IOSIZE], size);
221         } else if (iobuf->dr_rw == 1) {
222                 cfs_atomic_inc(&osd->od_w_in_flight);
223                 lprocfs_oh_tally(&h[BRW_W_RPC_HIST],
224                                  cfs_atomic_read(&osd->od_w_in_flight));
225                 lprocfs_oh_tally_log2(&h[BRW_W_DISK_IOSIZE], size);
226         } else {
227                 LBUG();
228         }
229 }
230
231 static void osd_submit_bio(int rw, struct bio *bio)
232 {
233         LASSERTF(rw == 0 || rw == 1, "%x\n", rw);
234         if (rw == 0)
235                 submit_bio(READ, bio);
236         else
237                 submit_bio(WRITE, bio);
238 }
239
240 static int can_be_merged(struct bio *bio, sector_t sector)
241 {
242         unsigned int size;
243
244         if (!bio)
245                 return 0;
246
247         size = bio->bi_size >> 9;
248         return bio->bi_sector + size == sector ? 1 : 0;
249 }
250
251 static int osd_do_bio(struct osd_device *osd, struct inode *inode,
252                       struct osd_iobuf *iobuf)
253 {
254         int            blocks_per_page = CFS_PAGE_SIZE >> inode->i_blkbits;
255         struct page  **pages = iobuf->dr_pages;
256         int            npages = iobuf->dr_npages;
257         unsigned long *blocks = iobuf->dr_blocks;
258         int            total_blocks = npages * blocks_per_page;
259         int            sector_bits = inode->i_sb->s_blocksize_bits - 9;
260         unsigned int   blocksize = inode->i_sb->s_blocksize;
261         struct bio    *bio = NULL;
262         struct page   *page;
263         unsigned int   page_offset;
264         sector_t       sector;
265         int            nblocks;
266         int            block_idx;
267         int            page_idx;
268         int            i;
269         int            rc = 0;
270         ENTRY;
271
272         LASSERT(iobuf->dr_npages == npages);
273
274         osd_brw_stats_update(osd, iobuf);
275         iobuf->dr_start_time = cfs_time_current();
276
277         for (page_idx = 0, block_idx = 0;
278              page_idx < npages;
279              page_idx++, block_idx += blocks_per_page) {
280
281                 page = pages[page_idx];
282                 LASSERT(block_idx + blocks_per_page <= total_blocks);
283
284                 for (i = 0, page_offset = 0;
285                      i < blocks_per_page;
286                      i += nblocks, page_offset += blocksize * nblocks) {
287
288                         nblocks = 1;
289
290                         if (blocks[block_idx + i] == 0) {  /* hole */
291                                 LASSERTF(iobuf->dr_rw == 0,
292                                          "page_idx %u, block_idx %u, i %u\n",
293                                          page_idx, block_idx, i);
294                                 memset(kmap(page) + page_offset, 0, blocksize);
295                                 kunmap(page);
296                                 continue;
297                         }
298
299                         sector = (sector_t)blocks[block_idx + i] << sector_bits;
300
301                         /* Additional contiguous file blocks? */
302                         while (i + nblocks < blocks_per_page &&
303                                (sector + (nblocks << sector_bits)) ==
304                                ((sector_t)blocks[block_idx + i + nblocks] <<
305                                 sector_bits))
306                                 nblocks++;
307
308                         /* I only set the page to be constant only if it
309                          * is mapped to a contiguous underlying disk block(s).
310                          * It will then make sure the corresponding device
311                          * cache of raid5 will be overwritten by this page.
312                          * - jay */
313                         if (iobuf->dr_rw && (nblocks == blocks_per_page) &&
314                             mapping_cap_page_constant_write(inode->i_mapping))
315                                 SetPageConstant(page);
316
317                         if (bio != NULL &&
318                             can_be_merged(bio, sector) &&
319                             bio_add_page(bio, page,
320                                          blocksize * nblocks, page_offset) != 0)
321                                 continue;       /* added this frag OK */
322
323                         if (bio != NULL) {
324                                 struct request_queue *q =
325                                         bdev_get_queue(bio->bi_bdev);
326
327                                 /* Dang! I have to fragment this I/O */
328                                 CDEBUG(D_INODE, "bio++ sz %d vcnt %d(%d) "
329                                        "sectors %d(%d) psg %d(%d) hsg %d(%d)\n",
330                                        bio->bi_size,
331                                        bio->bi_vcnt, bio->bi_max_vecs,
332                                        bio->bi_size >> 9, queue_max_sectors(q),
333                                        bio_phys_segments(q, bio),
334                                        queue_max_phys_segments(q),
335                                        bio_hw_segments(q, bio),
336                                        queue_max_hw_segments(q));
337
338                                 record_start_io(iobuf, bio->bi_size);
339                                 osd_submit_bio(iobuf->dr_rw, bio);
340                         }
341
342                         /* allocate new bio, limited by max BIO size, b=9945 */
343                         bio = bio_alloc(GFP_NOIO, max(BIO_MAX_PAGES,
344                                                       (npages - page_idx) *
345                                                       blocks_per_page));
346                         if (bio == NULL) {
347                                 CERROR("Can't allocate bio %u*%u = %u pages\n",
348                                        (npages - page_idx), blocks_per_page,
349                                        (npages - page_idx) * blocks_per_page);
350                                 rc = -ENOMEM;
351                                 goto out;
352                         }
353
354                         bio->bi_bdev = inode->i_sb->s_bdev;
355                         bio->bi_sector = sector;
356                         bio->bi_end_io = dio_complete_routine;
357                         bio->bi_private = iobuf;
358
359                         rc = bio_add_page(bio, page,
360                                           blocksize * nblocks, page_offset);
361                         LASSERT(rc != 0);
362                 }
363         }
364
365         if (bio != NULL) {
366                 record_start_io(iobuf, bio->bi_size);
367                 osd_submit_bio(iobuf->dr_rw, bio);
368                 rc = 0;
369         }
370
371  out:
372         /* in order to achieve better IO throughput, we don't wait for writes
373          * completion here. instead we proceed with transaction commit in
374          * parallel and wait for IO completion once transaction is stopped
375          * see osd_trans_stop() for more details -bzzz */
376         if (iobuf->dr_rw == 0) {
377                 cfs_wait_event(iobuf->dr_wait,
378                                cfs_atomic_read(&iobuf->dr_numreqs) == 0);
379         }
380
381         if (rc == 0)
382                 rc = iobuf->dr_error;
383         RETURN(rc);
384 }
385
386 static int osd_map_remote_to_local(loff_t offset, ssize_t len, int *nrpages,
387                                    struct niobuf_local *lnb)
388 {
389         ENTRY;
390
391         *nrpages = 0;
392
393         while (len > 0) {
394                 int poff = offset & (CFS_PAGE_SIZE - 1);
395                 int plen = CFS_PAGE_SIZE - poff;
396
397                 if (plen > len)
398                         plen = len;
399                 lnb->offset = offset;
400                 /* lnb->lnb_page_offset = poff; */
401                 lnb->len = plen;
402                 /* lb->flags = rnb->flags; */
403                 lnb->flags = 0;
404                 lnb->page = NULL;
405                 lnb->rc = 0;
406
407                 LASSERTF(plen <= len, "plen %u, len %lld\n", plen,
408                          (long long) len);
409                 offset += plen;
410                 len -= plen;
411                 lnb++;
412                 (*nrpages)++;
413         }
414
415         RETURN(0);
416 }
417
418 struct page *osd_get_page(struct dt_object *dt, loff_t offset, int rw)
419 {
420         struct inode      *inode = osd_dt_obj(dt)->oo_inode;
421         struct osd_device *d = osd_obj2dev(osd_dt_obj(dt));
422         struct page       *page;
423
424         LASSERT(inode);
425
426         page = find_or_create_page(inode->i_mapping, offset >> CFS_PAGE_SHIFT,
427                                    GFP_NOFS | __GFP_HIGHMEM);
428         if (unlikely(page == NULL))
429                 lprocfs_counter_add(d->od_stats, LPROC_OSD_NO_PAGE, 1);
430
431         return page;
432 }
433
434 /*
435  * there are following "locks":
436  * journal_start
437  * i_alloc_sem
438  * i_mutex
439  * page lock
440
441  * osd write path
442     * lock page(s)
443     * journal_start
444     * truncate_sem
445
446  * ext4 vmtruncate:
447     * lock pages, unlock
448     * journal_start
449     * lock partial page
450     * i_data_sem
451
452 */
453 int osd_bufs_get(const struct lu_env *env, struct dt_object *d, loff_t pos,
454                  ssize_t len, struct niobuf_local *lnb, int rw,
455                  struct lustre_capa *capa)
456 {
457         struct osd_object   *obj    = osd_dt_obj(d);
458         int npages, i, rc = 0;
459
460         LASSERT(obj->oo_inode);
461
462         osd_map_remote_to_local(pos, len, &npages, lnb);
463
464         for (i = 0; i < npages; i++, lnb++) {
465
466                 /* We still set up for ungranted pages so that granted pages
467                  * can be written to disk as they were promised, and portals
468                  * needs to keep the pages all aligned properly. */
469                 lnb->dentry = (void *) obj;
470
471                 lnb->page = osd_get_page(d, lnb->offset, rw);
472                 if (lnb->page == NULL)
473                         GOTO(cleanup, rc = -ENOMEM);
474
475                 /* DLM locking protects us from write and truncate competing
476                  * for same region, but truncate can leave dirty page in the
477                  * cache. it's possible the writeout on a such a page is in
478                  * progress when we access it. it's also possible that during
479                  * this writeout we put new (partial) data, but then won't
480                  * be able to proceed in filter_commitrw_write(). thus let's
481                  * just wait for writeout completion, should be rare enough.
482                  * -bzzz */
483                 wait_on_page_writeback(lnb->page);
484                 BUG_ON(PageWriteback(lnb->page));
485
486                 lu_object_get(&d->do_lu);
487         }
488         rc = i;
489
490 cleanup:
491         RETURN(rc);
492 }
493
494 static int osd_bufs_put(const struct lu_env *env, struct dt_object *dt,
495                         struct niobuf_local *lnb, int npages)
496 {
497         struct osd_thread_info *oti = osd_oti_get(env);
498         struct osd_iobuf       *iobuf = &oti->oti_iobuf;
499         struct osd_device      *d = osd_obj2dev(osd_dt_obj(dt));
500         int                     i;
501
502         /* to do IO stats, notice we do this here because
503          * osd_do_bio() doesn't wait for write to complete */
504         osd_fini_iobuf(d, iobuf);
505
506         for (i = 0; i < npages; i++) {
507                 if (lnb[i].page == NULL)
508                         continue;
509                 LASSERT(PageLocked(lnb[i].page));
510                 unlock_page(lnb[i].page);
511                 page_cache_release(lnb[i].page);
512                 lu_object_put(env, &dt->do_lu);
513                 lnb[i].page = NULL;
514         }
515         RETURN(0);
516 }
517
518 static int osd_write_prep(const struct lu_env *env, struct dt_object *dt,
519                           struct niobuf_local *lnb, int npages)
520 {
521         struct osd_thread_info *oti   = osd_oti_get(env);
522         struct osd_iobuf       *iobuf = &oti->oti_iobuf;
523         struct inode           *inode = osd_dt_obj(dt)->oo_inode;
524         struct osd_device      *osd   = osd_obj2dev(osd_dt_obj(dt));
525         struct timeval          start;
526         struct timeval          end;
527         unsigned long           timediff;
528         ssize_t                 isize;
529         __s64                   maxidx;
530         int                     rc = 0;
531         int                     i;
532         int                     cache = 0;
533
534         LASSERT(inode);
535
536         osd_init_iobuf(osd, iobuf, 0);
537
538         isize = i_size_read(inode);
539         maxidx = ((isize + CFS_PAGE_SIZE - 1) >> CFS_PAGE_SHIFT) - 1;
540
541         if (osd->od_writethrough_cache)
542                 cache = 1;
543         if (isize > osd->od_readcache_max_filesize)
544                 cache = 0;
545
546         cfs_gettimeofday(&start);
547         for (i = 0; i < npages; i++) {
548
549                 if (cache == 0)
550                         generic_error_remove_page(inode->i_mapping,
551                                                   lnb[i].page);
552
553                 /*
554                  * till commit the content of the page is undefined
555                  * we'll set it uptodate once bulk is done. otherwise
556                  * subsequent reads can access non-stable data
557                  */
558                 ClearPageUptodate(lnb[i].page);
559
560                 if (lnb[i].len == CFS_PAGE_SIZE)
561                         continue;
562
563                 if (maxidx >= lnb[i].page->index) {
564                         osd_iobuf_add_page(iobuf, lnb[i].page);
565                 } else {
566                         long off;
567                         char *p = kmap(lnb[i].page);
568
569                         off = lnb[i].offset;
570                         if (off)
571                                 memset(p, 0, off);
572                         off = lnb[i].offset + lnb[i].len;
573                         off &= ~CFS_PAGE_MASK;
574                         if (off)
575                                 memset(p + off, 0, CFS_PAGE_SIZE - off);
576                         kunmap(lnb[i].page);
577                 }
578         }
579         cfs_gettimeofday(&end);
580         timediff = cfs_timeval_sub(&end, &start, NULL);
581         lprocfs_counter_add(osd->od_stats, LPROC_OSD_GET_PAGE, timediff);
582
583         if (iobuf->dr_npages) {
584                 rc = osd->od_fsops->fs_map_inode_pages(inode, iobuf->dr_pages,
585                                                        iobuf->dr_npages,
586                                                        iobuf->dr_blocks,
587                                                        oti->oti_created,
588                                                        0, NULL);
589                 if (likely(rc == 0)) {
590                         rc = osd_do_bio(osd, inode, iobuf);
591                         /* do IO stats for preparation reads */
592                         osd_fini_iobuf(osd, iobuf);
593                 }
594         }
595         RETURN(rc);
596 }
597
598 static int osd_declare_write_commit(const struct lu_env *env,
599                                     struct dt_object *dt,
600                                     struct niobuf_local *lnb, int npages,
601                                     struct thandle *handle)
602 {
603         const struct osd_device *osd = osd_obj2dev(osd_dt_obj(dt));
604         struct inode            *inode = osd_dt_obj(dt)->oo_inode;
605         struct osd_thandle      *oh;
606         int                      extents = 1;
607         int                      depth;
608         int                      i;
609         int                      newblocks;
610         int                      old;
611
612         LASSERT(handle != NULL);
613         oh = container_of0(handle, struct osd_thandle, ot_super);
614         LASSERT(oh->ot_handle == NULL);
615
616         old = oh->ot_credits;
617         newblocks = npages;
618
619         /* calculate number of extents (probably better to pass nb) */
620         for (i = 1; i < npages; i++)
621                 if (lnb[i].offset !=
622                     lnb[i - 1].offset + lnb[i - 1].len)
623                         extents++;
624
625         /*
626          * each extent can go into new leaf causing a split
627          * 5 is max tree depth: inode + 4 index blocks
628          * with blockmaps, depth is 3 at most
629          */
630         if (LDISKFS_I(inode)->i_flags & LDISKFS_EXTENTS_FL) {
631                 /*
632                  * many concurrent threads may grow tree by the time
633                  * our transaction starts. so, consider 2 is a min depth
634                  */
635                 depth = ext_depth(inode);
636                 depth = max(depth, 1) + 1;
637                 newblocks += depth;
638                 oh->ot_credits++; /* inode */
639                 oh->ot_credits += depth * 2 * extents;
640         } else {
641                 depth = 3;
642                 newblocks += depth;
643                 oh->ot_credits++; /* inode */
644                 oh->ot_credits += depth * extents;
645         }
646
647         /* each new block can go in different group (bitmap + gd) */
648
649         /* we can't dirty more bitmap blocks than exist */
650         if (newblocks > LDISKFS_SB(osd_sb(osd))->s_groups_count)
651                 oh->ot_credits += LDISKFS_SB(osd_sb(osd))->s_groups_count;
652         else
653                 oh->ot_credits += newblocks;
654
655         /* we can't dirty more gd blocks than exist */
656         if (newblocks > LDISKFS_SB(osd_sb(osd))->s_gdb_count)
657                 oh->ot_credits += LDISKFS_SB(osd_sb(osd))->s_gdb_count;
658         else
659                 oh->ot_credits += newblocks;
660
661         RETURN(0);
662 }
663
664 /* Check if a block is allocated or not */
665 static int osd_is_mapped(struct inode *inode, obd_size offset)
666 {
667         sector_t (*fs_bmap)(struct address_space *, sector_t);
668
669         fs_bmap = inode->i_mapping->a_ops->bmap;
670
671         /* We can't know if we are overwriting or not */
672         if (fs_bmap == NULL)
673                 return 0;
674
675         if (fs_bmap(inode->i_mapping, offset >> inode->i_blkbits) == 0)
676                 return 0;
677
678         return 1;
679 }
680
681 static int osd_write_commit(const struct lu_env *env, struct dt_object *dt,
682                             struct niobuf_local *lnb, int npages,
683                             struct thandle *thandle)
684 {
685         struct osd_thread_info *oti = osd_oti_get(env);
686         struct osd_iobuf *iobuf = &oti->oti_iobuf;
687         struct inode *inode = osd_dt_obj(dt)->oo_inode;
688         struct osd_device  *osd = osd_obj2dev(osd_dt_obj(dt));
689         loff_t isize;
690         int rc = 0, i;
691
692         LASSERT(inode);
693
694         osd_init_iobuf(osd, iobuf, 1);
695         isize = i_size_read(inode);
696
697         for (i = 0; i < npages; i++) {
698                 if (lnb[i].rc == -ENOSPC &&
699                     osd_is_mapped(inode, lnb[i].offset)) {
700                         /* Allow the write to proceed if overwriting an
701                          * existing block */
702                         lnb[i].rc = 0;
703                 }
704
705                 if (lnb[i].rc) { /* ENOSPC, network RPC error, etc. */
706                         CDEBUG(D_INODE, "Skipping [%d] == %d\n", i,
707                                lnb[i].rc);
708                         LASSERT(lnb[i].page);
709                         generic_error_remove_page(inode->i_mapping,lnb[i].page);
710                         continue;
711                 }
712
713                 LASSERT(PageLocked(lnb[i].page));
714                 LASSERT(!PageWriteback(lnb[i].page));
715
716                 if (lnb[i].offset + lnb[i].len > isize)
717                         isize = lnb[i].offset + lnb[i].len;
718
719                 /*
720                  * Since write and truncate are serialized by oo_sem, even
721                  * partial-page truncate should not leave dirty pages in the
722                  * page cache.
723                  */
724                 LASSERT(!PageDirty(lnb[i].page));
725
726                 SetPageUptodate(lnb[i].page);
727
728                 osd_iobuf_add_page(iobuf, lnb[i].page);
729         }
730
731         if (OBD_FAIL_CHECK(OBD_FAIL_OST_MAPBLK_ENOSPC)) {
732                 rc = -ENOSPC;
733         } else if (iobuf->dr_npages > 0) {
734                 rc = osd->od_fsops->fs_map_inode_pages(inode, iobuf->dr_pages,
735                                                        iobuf->dr_npages,
736                                                        iobuf->dr_blocks,
737                                                        oti->oti_created,
738                                                        1, NULL);
739         } else {
740                 /* no pages to write, no transno is needed */
741                 thandle->th_local = 1;
742         }
743
744         if (likely(rc == 0)) {
745                 if (isize > i_size_read(inode)) {
746                         i_size_write(inode, isize);
747                         LDISKFS_I(inode)->i_disksize = isize;
748                         inode->i_sb->s_op->dirty_inode(inode);
749                 }
750
751                 rc = osd_do_bio(osd, inode, iobuf);
752                 /* we don't do stats here as in read path because
753                  * write is async: we'll do this in osd_put_bufs() */
754         }
755
756         if (unlikely(rc != 0)) {
757                 /* if write fails, we should drop pages from the cache */
758                 for (i = 0; i < npages; i++) {
759                         if (lnb[i].page == NULL)
760                                 continue;
761                         LASSERT(PageLocked(lnb[i].page));
762                         generic_error_remove_page(inode->i_mapping,lnb[i].page);
763                 }
764         }
765
766         RETURN(rc);
767 }
768
769 static int osd_read_prep(const struct lu_env *env, struct dt_object *dt,
770                          struct niobuf_local *lnb, int npages)
771 {
772         struct osd_thread_info *oti = osd_oti_get(env);
773         struct osd_iobuf *iobuf = &oti->oti_iobuf;
774         struct inode *inode = osd_dt_obj(dt)->oo_inode;
775         struct osd_device *osd = osd_obj2dev(osd_dt_obj(dt));
776         struct timeval start, end;
777         unsigned long timediff;
778         int rc = 0, i, m = 0, cache = 0;
779
780         LASSERT(inode);
781
782         osd_init_iobuf(osd, iobuf, 0);
783
784         if (osd->od_read_cache)
785                 cache = 1;
786         if (i_size_read(inode) > osd->od_readcache_max_filesize)
787                 cache = 0;
788
789         cfs_gettimeofday(&start);
790         for (i = 0; i < npages; i++) {
791
792                 if (i_size_read(inode) <= lnb[i].offset)
793                         /* If there's no more data, abort early.
794                          * lnb->rc == 0, so it's easy to detect later. */
795                         break;
796
797                 if (i_size_read(inode) <
798                     lnb[i].offset + lnb[i].len - 1)
799                         lnb[i].rc = i_size_read(inode) - lnb[i].offset;
800                 else
801                         lnb[i].rc = lnb[i].len;
802                 m += lnb[i].len;
803
804                 lprocfs_counter_add(osd->od_stats, LPROC_OSD_CACHE_ACCESS, 1);
805                 if (PageUptodate(lnb[i].page)) {
806                         lprocfs_counter_add(osd->od_stats,
807                                             LPROC_OSD_CACHE_HIT, 1);
808                 } else {
809                         lprocfs_counter_add(osd->od_stats,
810                                             LPROC_OSD_CACHE_MISS, 1);
811                         osd_iobuf_add_page(iobuf, lnb[i].page);
812                 }
813                 if (cache == 0)
814                         generic_error_remove_page(inode->i_mapping,lnb[i].page);
815         }
816         cfs_gettimeofday(&end);
817         timediff = cfs_timeval_sub(&end, &start, NULL);
818         lprocfs_counter_add(osd->od_stats, LPROC_OSD_GET_PAGE, timediff);
819
820         if (iobuf->dr_npages) {
821                 rc = osd->od_fsops->fs_map_inode_pages(inode, iobuf->dr_pages,
822                                                        iobuf->dr_npages,
823                                                        iobuf->dr_blocks,
824                                                        oti->oti_created,
825                                                        0, NULL);
826                 rc = osd_do_bio(osd, inode, iobuf);
827
828                 /* IO stats will be done in osd_bufs_put() */
829         }
830
831         RETURN(rc);
832 }
833
834 /*
835  * XXX: Another layering violation for now.
836  *
837  * We don't want to use ->f_op->read methods, because generic file write
838  *
839  *         - serializes on ->i_sem, and
840  *
841  *         - does a lot of extra work like balance_dirty_pages(),
842  *
843  * which doesn't work for globally shared files like /last_rcvd.
844  */
845 static int osd_ldiskfs_readlink(struct inode *inode, char *buffer, int buflen)
846 {
847         struct ldiskfs_inode_info *ei = LDISKFS_I(inode);
848
849         memcpy(buffer, (char *)ei->i_data, buflen);
850
851         return  buflen;
852 }
853
854 int osd_ldiskfs_read(struct inode *inode, void *buf, int size, loff_t *offs)
855 {
856         struct buffer_head *bh;
857         unsigned long block;
858         int osize = size;
859         int blocksize;
860         int csize;
861         int boffs;
862         int err;
863
864         /* prevent reading after eof */
865         cfs_spin_lock(&inode->i_lock);
866         if (i_size_read(inode) < *offs + size) {
867                 size = i_size_read(inode) - *offs;
868                 cfs_spin_unlock(&inode->i_lock);
869                 if (size < 0) {
870                         CDEBUG(D_EXT2, "size %llu is too short to read @%llu\n",
871                                i_size_read(inode), *offs);
872                         return -EBADR;
873                 } else if (size == 0) {
874                         return 0;
875                 }
876         } else {
877                 cfs_spin_unlock(&inode->i_lock);
878         }
879
880         blocksize = 1 << inode->i_blkbits;
881         while (size > 0) {
882                 block = *offs >> inode->i_blkbits;
883                 boffs = *offs & (blocksize - 1);
884                 csize = min(blocksize - boffs, size);
885                 bh = ldiskfs_bread(NULL, inode, block, 0, &err);
886                 if (!bh) {
887                         CERROR("%s: error reading offset %llu (block %lu): "
888                                "rc = %d\n",
889                                inode->i_sb->s_id, *offs, block, err);
890                         return err;
891                 }
892
893                 memcpy(buf, bh->b_data + boffs, csize);
894                 brelse(bh);
895
896                 *offs += csize;
897                 buf += csize;
898                 size -= csize;
899         }
900         return osize;
901 }
902
903 static ssize_t osd_read(const struct lu_env *env, struct dt_object *dt,
904                         struct lu_buf *buf, loff_t *pos,
905                         struct lustre_capa *capa)
906 {
907         struct inode *inode = osd_dt_obj(dt)->oo_inode;
908         int           rc;
909
910         if (osd_object_auth(env, dt, capa, CAPA_OPC_BODY_READ))
911                 RETURN(-EACCES);
912
913         /* Read small symlink from inode body as we need to maintain correct
914          * on-disk symlinks for ldiskfs.
915          */
916         if (S_ISLNK(dt->do_lu.lo_header->loh_attr) &&
917             (buf->lb_len <= sizeof(LDISKFS_I(inode)->i_data)))
918                 rc = osd_ldiskfs_readlink(inode, buf->lb_buf, buf->lb_len);
919         else
920                 rc = osd_ldiskfs_read(inode, buf->lb_buf, buf->lb_len, pos);
921
922         return rc;
923 }
924
925 static ssize_t osd_declare_write(const struct lu_env *env, struct dt_object *dt,
926                                  const loff_t size, loff_t pos,
927                                  struct thandle *handle)
928 {
929         struct osd_thandle *oh;
930         int                 credits;
931
932         LASSERT(handle != NULL);
933
934         oh = container_of0(handle, struct osd_thandle, ot_super);
935         LASSERT(oh->ot_handle == NULL);
936
937         /* XXX: size == 0 or INT_MAX indicating a catalog header update or
938          *      llog write, see comment in mdd_declare_llog_record().
939          *
940          *      This hack will be removed with llog over OSD landing
941          */
942         if (size == DECLARE_LLOG_REWRITE)
943                 credits = 2;
944         else if (size == DECLARE_LLOG_WRITE)
945                 credits = 6;
946         else
947                 credits = osd_dto_credits_noquota[DTO_WRITE_BLOCK];
948
949         OSD_DECLARE_OP(oh, write);
950         oh->ot_credits += credits;
951
952         if (osd_dt_obj(dt)->oo_inode == NULL)
953                 return 0;
954
955         osd_declare_qid(dt, oh, USRQUOTA, osd_dt_obj(dt)->oo_inode->i_uid,
956                         osd_dt_obj(dt)->oo_inode);
957         osd_declare_qid(dt, oh, GRPQUOTA, osd_dt_obj(dt)->oo_inode->i_gid,
958                         osd_dt_obj(dt)->oo_inode);
959         return 0;
960 }
961
962 static int osd_ldiskfs_writelink(struct inode *inode, char *buffer, int buflen)
963 {
964
965         memcpy((char *)&LDISKFS_I(inode)->i_data, (char *)buffer, buflen);
966         LDISKFS_I(inode)->i_disksize = buflen;
967         i_size_write(inode, buflen);
968         inode->i_sb->s_op->dirty_inode(inode);
969
970         return 0;
971 }
972
973 static int osd_ldiskfs_write_record(struct inode *inode, void *buf, int bufsize,
974                                     loff_t *offs, handle_t *handle)
975 {
976         struct buffer_head *bh        = NULL;
977         loff_t              offset    = *offs;
978         loff_t              new_size  = i_size_read(inode);
979         unsigned long       block;
980         int                 blocksize = 1 << inode->i_blkbits;
981         int                 err = 0;
982         int                 size;
983         int                 boffs;
984         int                 dirty_inode = 0;
985
986         while (bufsize > 0) {
987                 if (bh != NULL)
988                         brelse(bh);
989
990                 block = offset >> inode->i_blkbits;
991                 boffs = offset & (blocksize - 1);
992                 size = min(blocksize - boffs, bufsize);
993                 bh = ldiskfs_bread(handle, inode, block, 1, &err);
994                 if (!bh) {
995                         CERROR("%s: error reading offset %llu (block %lu): "
996                                "rc = %d\n",
997                                inode->i_sb->s_id, offset, block, err);
998                         break;
999                 }
1000
1001                 err = ldiskfs_journal_get_write_access(handle, bh);
1002                 if (err) {
1003                         CERROR("journal_get_write_access() returned error %d\n",
1004                                err);
1005                         break;
1006                 }
1007                 LASSERTF(boffs + size <= bh->b_size,
1008                          "boffs %d size %d bh->b_size %lu",
1009                          boffs, size, (unsigned long)bh->b_size);
1010                 memcpy(bh->b_data + boffs, buf, size);
1011                 err = ldiskfs_journal_dirty_metadata(handle, bh);
1012                 if (err)
1013                         break;
1014
1015                 if (offset + size > new_size)
1016                         new_size = offset + size;
1017                 offset += size;
1018                 bufsize -= size;
1019                 buf += size;
1020         }
1021         if (bh)
1022                 brelse(bh);
1023
1024         /* correct in-core and on-disk sizes */
1025         if (new_size > i_size_read(inode)) {
1026                 cfs_spin_lock(&inode->i_lock);
1027                 if (new_size > i_size_read(inode))
1028                         i_size_write(inode, new_size);
1029                 if (i_size_read(inode) > LDISKFS_I(inode)->i_disksize) {
1030                         LDISKFS_I(inode)->i_disksize = i_size_read(inode);
1031                         dirty_inode = 1;
1032                 }
1033                 cfs_spin_unlock(&inode->i_lock);
1034                 if (dirty_inode)
1035                         inode->i_sb->s_op->dirty_inode(inode);
1036         }
1037
1038         if (err == 0)
1039                 *offs = offset;
1040         return err;
1041 }
1042
1043 static ssize_t osd_write(const struct lu_env *env, struct dt_object *dt,
1044                          const struct lu_buf *buf, loff_t *pos,
1045                          struct thandle *handle, struct lustre_capa *capa,
1046                          int ignore_quota)
1047 {
1048         struct inode       *inode = osd_dt_obj(dt)->oo_inode;
1049         struct osd_thandle *oh;
1050         ssize_t             result;
1051 #ifdef HAVE_QUOTA_SUPPORT
1052         cfs_cap_t           save = cfs_curproc_cap_pack();
1053 #endif
1054
1055         LASSERT(dt_object_exists(dt));
1056
1057         if (osd_object_auth(env, dt, capa, CAPA_OPC_BODY_WRITE))
1058                 return -EACCES;
1059
1060         LASSERT(handle != NULL);
1061
1062         /* XXX: don't check: one declared chunk can be used many times */
1063         /* OSD_EXEC_OP(handle, write); */
1064
1065         oh = container_of(handle, struct osd_thandle, ot_super);
1066         LASSERT(oh->ot_handle->h_transaction != NULL);
1067 #ifdef HAVE_QUOTA_SUPPORT
1068         if (ignore_quota)
1069                 cfs_cap_raise(CFS_CAP_SYS_RESOURCE);
1070         else
1071                 cfs_cap_lower(CFS_CAP_SYS_RESOURCE);
1072 #endif
1073         /* Write small symlink to inode body as we need to maintain correct
1074          * on-disk symlinks for ldiskfs.
1075          */
1076         if (S_ISLNK(dt->do_lu.lo_header->loh_attr) &&
1077             (buf->lb_len < sizeof(LDISKFS_I(inode)->i_data)))
1078                 result = osd_ldiskfs_writelink(inode, buf->lb_buf, buf->lb_len);
1079         else
1080                 result = osd_ldiskfs_write_record(inode, buf->lb_buf,
1081                                                   buf->lb_len, pos,
1082                                                   oh->ot_handle);
1083 #ifdef HAVE_QUOTA_SUPPORT
1084         cfs_curproc_cap_unpack(save);
1085 #endif
1086         if (result == 0)
1087                 result = buf->lb_len;
1088         return result;
1089 }
1090
1091 static int osd_declare_punch(const struct lu_env *env, struct dt_object *dt,
1092                              __u64 start, __u64 end, struct thandle *th)
1093 {
1094         struct osd_thandle *oh;
1095         ENTRY;
1096
1097         LASSERT(th);
1098         oh = container_of(th, struct osd_thandle, ot_super);
1099
1100         OSD_DECLARE_OP(oh, punch);
1101
1102         /*
1103          * we don't need to reserve credits for whole truncate
1104          * it's not possible as truncate may need to free too many
1105          * blocks and that won't fit a single transaction. instead
1106          * we reserve credits to change i_size and put inode onto
1107          * orphan list. if needed truncate will extend or restart
1108          * transaction
1109          */
1110         oh->ot_credits += osd_dto_credits_noquota[DTO_ATTR_SET_BASE];
1111         oh->ot_credits += 3;
1112
1113         RETURN(0);
1114 }
1115
1116 static int osd_punch(const struct lu_env *env, struct dt_object *dt,
1117                      __u64 start, __u64 end, struct thandle *th,
1118                      struct lustre_capa *capa)
1119 {
1120         struct osd_thandle *oh;
1121         struct osd_object  *obj = osd_dt_obj(dt);
1122         struct inode       *inode = obj->oo_inode;
1123         handle_t           *h;
1124         tid_t               tid;
1125         int                 rc, rc2 = 0;
1126         ENTRY;
1127
1128         LASSERT(end == OBD_OBJECT_EOF);
1129         LASSERT(dt_object_exists(dt));
1130         LASSERT(osd_invariant(obj));
1131
1132         LASSERT(th);
1133         oh = container_of(th, struct osd_thandle, ot_super);
1134         LASSERT(oh->ot_handle->h_transaction != NULL);
1135
1136         OSD_EXEC_OP(th, punch);
1137
1138         tid = oh->ot_handle->h_transaction->t_tid;
1139
1140         rc = vmtruncate(inode, start);
1141
1142         /*
1143          * For a partial-page truncate, flush the page to disk immediately to
1144          * avoid data corruption during direct disk write.  b=17397
1145          */
1146         if (rc == 0 && (start & ~CFS_PAGE_MASK) != 0)
1147                 rc = filemap_fdatawrite_range(inode->i_mapping, start, start+1);
1148
1149         h = journal_current_handle();
1150         LASSERT(h != NULL);
1151         LASSERT(h == oh->ot_handle);
1152
1153         if (tid != h->h_transaction->t_tid) {
1154                 int credits = oh->ot_credits;
1155                 /*
1156                  * transaction has changed during truncate
1157                  * we need to restart the handle with our credits
1158                  */
1159                 if (h->h_buffer_credits < credits) {
1160                         if (ldiskfs_journal_extend(h, credits))
1161                                 rc2 = ldiskfs_journal_restart(h, credits);
1162                 }
1163         }
1164
1165         RETURN(rc == 0 ? rc2 : rc);
1166 }
1167
1168 static int osd_fiemap_get(const struct lu_env *env, struct dt_object *dt,
1169                           struct ll_user_fiemap *fm)
1170 {
1171         struct inode *inode = osd_dt_obj(dt)->oo_inode;
1172         struct osd_thread_info *info   = osd_oti_get(env);
1173         struct dentry          *dentry = &info->oti_obj_dentry;
1174         struct file            *file   = &info->oti_file;
1175         mm_segment_t            saved_fs;
1176         int rc;
1177
1178         LASSERT(inode);
1179         dentry->d_inode = inode;
1180         file->f_dentry = dentry;
1181         file->f_mapping = inode->i_mapping;
1182         file->f_op = inode->i_fop;
1183
1184         saved_fs = get_fs();
1185         set_fs(get_ds());
1186         /* ldiskfs_ioctl does not have a inode argument */
1187         if (inode->i_fop->unlocked_ioctl)
1188                 rc = inode->i_fop->unlocked_ioctl(file, FSFILT_IOC_FIEMAP,
1189                                                   (long)fm);
1190         else
1191                 rc = -ENOTTY;
1192         set_fs(saved_fs);
1193         return rc;
1194 }
1195
1196 /*
1197  * in some cases we may need declare methods for objects being created
1198  * e.g., when we create symlink
1199  */
1200 const struct dt_body_operations osd_body_ops_new = {
1201         .dbo_declare_write = osd_declare_write,
1202 };
1203
1204 const struct dt_body_operations osd_body_ops = {
1205         .dbo_read                 = osd_read,
1206         .dbo_declare_write        = osd_declare_write,
1207         .dbo_write                = osd_write,
1208         .dbo_bufs_get             = osd_bufs_get,
1209         .dbo_bufs_put             = osd_bufs_put,
1210         .dbo_write_prep           = osd_write_prep,
1211         .dbo_declare_write_commit = osd_declare_write_commit,
1212         .dbo_write_commit         = osd_write_commit,
1213         .dbo_read_prep            = osd_read_prep,
1214         .do_declare_punch         = osd_declare_punch,
1215         .do_punch                 = osd_punch,
1216         .dbo_fiemap_get           = osd_fiemap_get,
1217 };
1218