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