Whamcloud - gitweb
Branch HEAD
[fs/lustre-release.git] / lustre / obdfilter / filter_io_26.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  2008 Sun Microsystems, Inc. All rights reserved
30  * Use is subject to license terms.
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/obdfilter/filter_io_26.c
37  *
38  * Author: Peter Braam <braam@clusterfs.com>
39  * Author: Andreas Dilger <adilger@clusterfs.com>
40  * Author: Phil Schwan <phil@clusterfs.com>
41  */
42
43 #ifndef AUTOCONF_INCLUDED
44 #include <linux/config.h>
45 #endif
46 #include <linux/module.h>
47 #include <linux/pagemap.h> // XXX kill me soon
48 #include <linux/version.h>
49 #include <linux/buffer_head.h>
50
51 #define DEBUG_SUBSYSTEM S_FILTER
52
53 #include <obd_class.h>
54 #include <lustre_fsfilt.h>
55 #include <lustre_quota.h>
56 #include "filter_internal.h"
57
58 /* 512byte block min */
59 #define MAX_BLOCKS_PER_PAGE (CFS_PAGE_SIZE / 512)
60 struct filter_iobuf {
61         atomic_t          dr_numreqs;  /* number of reqs being processed */
62         wait_queue_head_t dr_wait;
63         int               dr_max_pages;
64         int               dr_npages;
65         int               dr_error;
66         struct page     **dr_pages;
67         unsigned long    *dr_blocks;
68         spinlock_t        dr_lock;              /* IRQ lock */
69         unsigned int      dr_ignore_quota:1;
70         struct filter_obd *dr_filter;
71 };
72
73 static void record_start_io(struct filter_iobuf *iobuf, int rw, int size,
74                             struct obd_export *exp)
75 {
76         struct filter_obd *filter = iobuf->dr_filter;
77
78         atomic_inc(&iobuf->dr_numreqs);
79
80         if (rw == OBD_BRW_READ) {
81                 atomic_inc(&filter->fo_r_in_flight);
82                 lprocfs_oh_tally(&filter->fo_filter_stats.hist[BRW_R_RPC_HIST],
83                                  atomic_read(&filter->fo_r_in_flight));
84                 lprocfs_oh_tally_log2(&filter->fo_filter_stats.hist[BRW_R_DISK_IOSIZE],
85                                       size);
86                 lprocfs_oh_tally(&exp->exp_filter_data.fed_brw_stats.hist[BRW_R_RPC_HIST],
87                                  atomic_read(&filter->fo_r_in_flight));
88                 lprocfs_oh_tally_log2(&exp->exp_filter_data.fed_brw_stats.hist[BRW_R_DISK_IOSIZE], size);
89         } else {
90                 atomic_inc(&filter->fo_w_in_flight);
91                 lprocfs_oh_tally(&filter->fo_filter_stats.hist[BRW_W_RPC_HIST],
92                                  atomic_read(&filter->fo_w_in_flight));
93                 lprocfs_oh_tally_log2(&filter->fo_filter_stats.hist[BRW_W_DISK_IOSIZE],
94                                       size);
95                 lprocfs_oh_tally(&exp->exp_filter_data.fed_brw_stats.hist[BRW_W_RPC_HIST],
96                                  atomic_read(&filter->fo_w_in_flight));
97                 lprocfs_oh_tally_log2(&exp->exp_filter_data.fed_brw_stats.hist[BRW_W_DISK_IOSIZE], size);
98         }
99 }
100
101 static void record_finish_io(struct filter_iobuf *iobuf, int rw, int rc)
102 {
103         struct filter_obd *filter = iobuf->dr_filter;
104
105         /* CAVEAT EMPTOR: possibly in IRQ context 
106          * DO NOT record procfs stats here!!! */
107
108         if (rw == OBD_BRW_READ)
109                 atomic_dec(&filter->fo_r_in_flight);
110         else
111                 atomic_dec(&filter->fo_w_in_flight);
112
113         if (atomic_dec_and_test(&iobuf->dr_numreqs))
114                 wake_up(&iobuf->dr_wait);
115 }
116
117 static int dio_complete_routine(struct bio *bio, unsigned int done, int error)
118 {
119         struct filter_iobuf *iobuf = bio->bi_private;
120         unsigned long        flags;
121
122 #ifdef HAVE_PAGE_CONSTANT
123         struct bio_vec *bvl;
124         int i;
125 #endif
126
127         /* CAVEAT EMPTOR: possibly in IRQ context 
128          * DO NOT record procfs stats here!!! */
129
130         if (bio->bi_size)                       /* Not complete */
131                 return 1;
132
133         if (iobuf == NULL) {
134                 CERROR("***** bio->bi_private is NULL!  This should never "
135                        "happen.  Normally, I would crash here, but instead I "
136                        "will dump the bio contents to the console.  Please "
137                        "report this to <http://bugzilla.lustre.org/> , along "
138                        "with any interesting messages leading up to this point "
139                        "(like SCSI errors, perhaps).  Because bi_private is "
140                        "NULL, I can't wake up the thread that initiated this "
141                        "I/O -- so you will probably have to reboot this node.\n");
142                 CERROR("bi_next: %p, bi_flags: %lx, bi_rw: %lu, bi_vcnt: %d, "
143                        "bi_idx: %d, bi->size: %d, bi_end_io: %p, bi_cnt: %d, "
144                        "bi_private: %p\n", bio->bi_next, bio->bi_flags,
145                        bio->bi_rw, bio->bi_vcnt, bio->bi_idx, bio->bi_size,
146                        bio->bi_end_io, atomic_read(&bio->bi_cnt),
147                        bio->bi_private);
148                 return 0;
149         }
150
151 #ifdef HAVE_PAGE_CONSTANT
152         bio_for_each_segment(bvl, bio, i)
153                 ClearPageConstant(bvl->bv_page);
154 #endif
155
156         spin_lock_irqsave(&iobuf->dr_lock, flags);
157         if (iobuf->dr_error == 0)
158                 iobuf->dr_error = error;
159         spin_unlock_irqrestore(&iobuf->dr_lock, flags);
160
161         record_finish_io(iobuf, test_bit(BIO_RW, &bio->bi_rw) ?
162                          OBD_BRW_WRITE : OBD_BRW_READ, error);
163
164         /* Completed bios used to be chained off iobuf->dr_bios and freed in
165          * filter_clear_dreq().  It was then possible to exhaust the biovec-256
166          * mempool when serious on-disk fragmentation was encountered,
167          * deadlocking the OST.  The bios are now released as soon as complete
168          * so the pool cannot be exhausted while IOs are competing. bug 10076 */
169         bio_put(bio);
170         return 0;
171 }
172
173 static int can_be_merged(struct bio *bio, sector_t sector)
174 {
175         unsigned int size;
176
177         if (!bio)
178                 return 0;
179
180         size = bio->bi_size >> 9;
181         return bio->bi_sector + size == sector ? 1 : 0;
182 }
183
184 struct filter_iobuf *filter_alloc_iobuf(struct filter_obd *filter,
185                                         int rw, int num_pages)
186 {
187         struct filter_iobuf *iobuf;
188
189         LASSERTF(rw == OBD_BRW_WRITE || rw == OBD_BRW_READ, "%x\n", rw);
190
191         OBD_ALLOC(iobuf, sizeof(*iobuf));
192         if (iobuf == NULL)
193                 goto failed_0;
194
195         OBD_ALLOC(iobuf->dr_pages, num_pages * sizeof(*iobuf->dr_pages));
196         if (iobuf->dr_pages == NULL)
197                 goto failed_1;
198
199         OBD_ALLOC(iobuf->dr_blocks,
200                   MAX_BLOCKS_PER_PAGE * num_pages * sizeof(*iobuf->dr_blocks));
201         if (iobuf->dr_blocks == NULL)
202                 goto failed_2;
203
204         iobuf->dr_filter = filter;
205         init_waitqueue_head(&iobuf->dr_wait);
206         atomic_set(&iobuf->dr_numreqs, 0);
207         spin_lock_init(&iobuf->dr_lock);
208         iobuf->dr_max_pages = num_pages;
209         iobuf->dr_npages = 0;
210         iobuf->dr_error = 0;
211
212         RETURN(iobuf);
213
214  failed_2:
215         OBD_FREE(iobuf->dr_pages,
216                  num_pages * sizeof(*iobuf->dr_pages));
217  failed_1:
218         OBD_FREE(iobuf, sizeof(*iobuf));
219  failed_0:
220         RETURN(ERR_PTR(-ENOMEM));
221 }
222
223 static void filter_clear_iobuf(struct filter_iobuf *iobuf)
224 {
225         iobuf->dr_npages = 0;
226         iobuf->dr_error = 0;
227         atomic_set(&iobuf->dr_numreqs, 0);
228 }
229
230 void filter_free_iobuf(struct filter_iobuf *iobuf)
231 {
232         int num_pages = iobuf->dr_max_pages;
233
234         filter_clear_iobuf(iobuf);
235
236         OBD_FREE(iobuf->dr_blocks,
237                  MAX_BLOCKS_PER_PAGE * num_pages * sizeof(*iobuf->dr_blocks));
238         OBD_FREE(iobuf->dr_pages,
239                  num_pages * sizeof(*iobuf->dr_pages));
240         OBD_FREE_PTR(iobuf);
241 }
242
243 void filter_iobuf_put(struct filter_obd *filter, struct filter_iobuf *iobuf,
244                       struct obd_trans_info *oti)
245 {
246         int thread_id = oti ? oti->oti_thread_id : -1;
247
248         if (unlikely(thread_id < 0)) {
249                 filter_free_iobuf(iobuf);
250                 return;
251         }
252
253         LASSERTF(filter->fo_iobuf_pool[thread_id] == iobuf,
254                  "iobuf mismatch for thread %d: pool %p iobuf %p\n",
255                  thread_id, filter->fo_iobuf_pool[thread_id], iobuf);
256         filter_clear_iobuf(iobuf);
257 }
258
259 int filter_iobuf_add_page(struct obd_device *obd, struct filter_iobuf *iobuf,
260                           struct inode *inode, struct page *page)
261 {
262         LASSERT(iobuf->dr_npages < iobuf->dr_max_pages);
263         iobuf->dr_pages[iobuf->dr_npages++] = page;
264
265         return 0;
266 }
267
268 int filter_do_bio(struct obd_export *exp, struct inode *inode,
269                   struct filter_iobuf *iobuf, int rw)
270 {
271         struct obd_device *obd = exp->exp_obd;
272         int            blocks_per_page = CFS_PAGE_SIZE >> inode->i_blkbits;
273         struct page  **pages = iobuf->dr_pages;
274         int            npages = iobuf->dr_npages;
275         unsigned long *blocks = iobuf->dr_blocks;
276         int            total_blocks = npages * blocks_per_page;
277         int            sector_bits = inode->i_sb->s_blocksize_bits - 9;
278         unsigned int   blocksize = inode->i_sb->s_blocksize;
279         struct bio    *bio = NULL;
280         int            frags = 0;
281         unsigned long  start_time = jiffies;
282         struct page   *page;
283         unsigned int   page_offset;
284         sector_t       sector;
285         int            nblocks;
286         int            block_idx;
287         int            page_idx;
288         int            i;
289         int            rc = 0;
290         ENTRY;
291
292         LASSERT(iobuf->dr_npages == npages);
293         LASSERT(total_blocks <= OBDFILTER_CREATED_SCRATCHPAD_ENTRIES);
294
295         for (page_idx = 0, block_idx = 0;
296              page_idx < npages;
297              page_idx++, block_idx += blocks_per_page) {
298
299                 page = pages[page_idx];
300                 LASSERT (block_idx + blocks_per_page <= total_blocks);
301
302                 for (i = 0, page_offset = 0;
303                      i < blocks_per_page;
304                      i += nblocks, page_offset += blocksize * nblocks) {
305
306                         nblocks = 1;
307
308                         if (blocks[block_idx + i] == 0) {  /* hole */
309                                 LASSERT(rw == OBD_BRW_READ);
310                                 memset(kmap(page) + page_offset, 0, blocksize);
311                                 kunmap(page);
312                                 continue;
313                         }
314
315                         sector = (sector_t)blocks[block_idx + i] << sector_bits;
316
317                         /* Additional contiguous file blocks? */
318                         while (i + nblocks < blocks_per_page &&
319                                (sector + (nblocks << sector_bits)) ==
320                                ((sector_t)blocks[block_idx + i + nblocks] <<
321                                 sector_bits))
322                                 nblocks++;
323
324 #ifdef HAVE_PAGE_CONSTANT
325                         /* I only set the page to be constant only if it 
326                          * is mapped to a contiguous underlying disk block(s). 
327                          * It will then make sure the corresponding device 
328                          * cache of raid5 will be overwritten by this page. 
329                          * - jay */
330                         if ((rw == OBD_BRW_WRITE) && 
331                             (nblocks == blocks_per_page) && 
332                             mapping_cap_page_constant_write(inode->i_mapping))
333                                SetPageConstant(page);
334 #endif
335
336                         if (bio != NULL &&
337                             can_be_merged(bio, sector) &&
338                             bio_add_page(bio, page,
339                                          blocksize * nblocks, page_offset) != 0)
340                                 continue;       /* added this frag OK */
341
342                         if (bio != NULL) {
343                                 request_queue_t *q =
344                                         bdev_get_queue(bio->bi_bdev);
345
346                                 /* Dang! I have to fragment this I/O */
347                                 CDEBUG(D_INODE, "bio++ sz %d vcnt %d(%d) "
348                                        "sectors %d(%d) psg %d(%d) hsg %d(%d)\n",
349                                        bio->bi_size,
350                                        bio->bi_vcnt, bio->bi_max_vecs,
351                                        bio->bi_size >> 9, q->max_sectors,
352                                        bio_phys_segments(q, bio),
353                                        q->max_phys_segments,
354                                        bio_hw_segments(q, bio),
355                                        q->max_hw_segments);
356
357                                 record_start_io(iobuf, rw, bio->bi_size, exp);
358                                 rc = fsfilt_send_bio(rw, obd, inode, bio);
359                                 if (rc < 0) {
360                                         CERROR("Can't send bio: %d\n", rc);
361                                         record_finish_io(iobuf, rw, rc);
362                                         goto out;
363                                 }
364                                 frags++;
365                         }
366
367                         /* allocate new bio */
368                         bio = bio_alloc(GFP_NOIO,
369                                         (npages - page_idx) * blocks_per_page);
370                         if (bio == NULL) {
371                                 CERROR("Can't allocate bio %u*%u = %u pages\n",
372                                        (npages - page_idx), blocks_per_page,
373                                        (npages - page_idx) * blocks_per_page);
374                                 rc = -ENOMEM;
375                                 goto out;
376                         }
377
378                         bio->bi_bdev = inode->i_sb->s_bdev;
379                         bio->bi_sector = sector;
380                         bio->bi_end_io = dio_complete_routine;
381                         bio->bi_private = iobuf;
382
383                         rc = bio_add_page(bio, page,
384                                           blocksize * nblocks, page_offset);
385                         LASSERT (rc != 0);
386                 }
387         }
388
389         if (bio != NULL) {
390                 record_start_io(iobuf, rw, bio->bi_size, exp);
391                 rc = fsfilt_send_bio(rw, obd, inode, bio);
392                 if (rc >= 0) {
393                         frags++;
394                         rc = 0;
395                 } else {
396                         CERROR("Can't send bio: %d\n", rc);
397                         record_finish_io(iobuf, rw, rc);
398                 }
399         }
400
401  out:
402         wait_event(iobuf->dr_wait, atomic_read(&iobuf->dr_numreqs) == 0);
403
404         if (rw == OBD_BRW_READ) {
405                 lprocfs_oh_tally(&obd->u.filter.fo_filter_stats.hist[BRW_R_DIO_FRAGS],
406                                  frags);
407                 lprocfs_oh_tally(&exp->exp_filter_data.fed_brw_stats.hist[BRW_R_DIO_FRAGS],
408                                  frags);
409                 lprocfs_oh_tally_log2(&obd->u.filter.fo_filter_stats.hist[BRW_R_IO_TIME],
410                                       jiffies - start_time);
411                 lprocfs_oh_tally_log2(&exp->exp_filter_data.fed_brw_stats.hist[BRW_R_IO_TIME], jiffies - start_time);
412                 if (exp->exp_nid_stats && exp->exp_nid_stats->nid_brw_stats) {
413                         lprocfs_oh_tally(&exp->exp_nid_stats->nid_brw_stats->hist[BRW_R_DIO_FRAGS],
414                                          frags);
415                         lprocfs_oh_tally_log2(&exp->exp_nid_stats->nid_brw_stats->hist[BRW_R_IO_TIME],
416                                               jiffies - start_time);
417                 }
418         } else {
419                 lprocfs_oh_tally(&obd->u.filter.fo_filter_stats.hist[BRW_W_DIO_FRAGS],
420                                  frags);
421                 lprocfs_oh_tally(&exp->exp_filter_data.fed_brw_stats.hist[BRW_W_DIO_FRAGS],
422                                  frags);
423                 lprocfs_oh_tally_log2(&obd->u.filter.fo_filter_stats.hist[BRW_W_IO_TIME],
424                                       jiffies - start_time);
425                 lprocfs_oh_tally_log2(&exp->exp_filter_data.fed_brw_stats.hist[BRW_W_IO_TIME], jiffies - start_time);
426                 if (exp->exp_nid_stats && exp->exp_nid_stats->nid_brw_stats) {
427                         lprocfs_oh_tally(&exp->exp_nid_stats->nid_brw_stats->hist[BRW_W_DIO_FRAGS],
428                                          frags);
429                         lprocfs_oh_tally_log2(&exp->exp_nid_stats->nid_brw_stats->hist[BRW_W_IO_TIME],
430                                               jiffies - start_time);
431                 }
432         }
433
434         if (rc == 0)
435                 rc = iobuf->dr_error;
436         RETURN(rc);
437 }
438
439 /* These are our hacks to keep our directio/bh IO coherent with ext3's
440  * page cache use.  Most notably ext3 reads file data into the page
441  * cache when it is zeroing the tail of partial-block truncates and
442  * leaves it there, sometimes generating io from it at later truncates.
443  * This removes the partial page and its buffers from the page cache,
444  * so it should only ever cause a wait in rare cases, as otherwise we
445  * always do full-page IO to the OST.
446  *
447  * The call to truncate_complete_page() will call journal_invalidatepage()
448  * to free the buffers and drop the page from cache.  The buffers should
449  * not be dirty, because we already called fdatasync/fdatawait on them.
450  */
451 static int filter_sync_inode_data(struct inode *inode, int locked)
452 {
453         int rc = 0;
454
455         /* This is nearly do_fsync(), without the waiting on the inode */
456         /* XXX: in 2.6.16 (at least) we don't need to hold i_mutex over
457          * filemap_fdatawrite() and filemap_fdatawait(), so we may no longer
458          * need this lock here at all. */
459         if (!locked)
460                 LOCK_INODE_MUTEX(inode);
461         if (inode->i_mapping->nrpages) {
462 #ifdef PF_SYNCWRITE
463                 current->flags |= PF_SYNCWRITE;
464 #endif
465                 rc = filemap_fdatawrite(inode->i_mapping);
466                 if (rc == 0)
467                         rc = filemap_fdatawait(inode->i_mapping);
468 #ifdef PF_SYNCWRITE
469                 current->flags &= ~PF_SYNCWRITE;
470 #endif
471         }
472         if (!locked)
473                 UNLOCK_INODE_MUTEX(inode);
474
475         return rc;
476 }
477 /* Clear pages from the mapping before we do direct IO to that offset.
478  * Now that the only source of such pages in the truncate path flushes
479  * these pages to disk and then discards them, this is error condition.
480  * If add back read cache this will happen again.  This could be disabled
481  * until that time if we never see the below error. */
482 static int filter_clear_page_cache(struct inode *inode,
483                                    struct filter_iobuf *iobuf)
484 {
485         struct page *page;
486         int i, rc;
487
488         rc = filter_sync_inode_data(inode, 0);
489         if (rc != 0)
490                 RETURN(rc);
491
492         /* be careful to call this after fsync_inode_data_buffers has waited
493          * for IO to complete before we evict it from the cache */
494         for (i = 0; i < iobuf->dr_npages; i++) {
495                 page = find_lock_page(inode->i_mapping,
496                                       iobuf->dr_pages[i]->index);
497                 if (page == NULL)
498                         continue;
499                 if (page->mapping != NULL) {
500                         CERROR("page %lu (%d/%d) in page cache during write!\n",
501                                page->index, i, iobuf->dr_npages);
502                         wait_on_page_writeback(page);
503                         ll_truncate_complete_page(page);
504                 }
505
506                 unlock_page(page);
507                 page_cache_release(page);
508         }
509
510         return 0;
511 }
512
513 int filter_clear_truncated_page(struct inode *inode)
514 {
515         struct page *page;
516         int rc;
517
518         /* Truncate on page boundary, so nothing to flush? */
519         if (!(i_size_read(inode) & ~CFS_PAGE_MASK))
520                 return 0;
521
522         rc = filter_sync_inode_data(inode, 1);
523         if (rc != 0)
524                 RETURN(rc);
525
526         /* be careful to call this after fsync_inode_data_buffers has waited
527          * for IO to complete before we evict it from the cache */
528         page = find_lock_page(inode->i_mapping,
529                               i_size_read(inode) >> CFS_PAGE_SHIFT);
530         if (page) {
531                 if (page->mapping != NULL) {
532                         wait_on_page_writeback(page);
533                         ll_truncate_complete_page(page);
534                 }
535                 unlock_page(page);
536                 page_cache_release(page);
537         }
538
539         return 0;
540 }
541
542 /* Must be called with i_mutex taken for writes; this will drop it */
543 int filter_direct_io(int rw, struct dentry *dchild, struct filter_iobuf *iobuf,
544                      struct obd_export *exp, struct iattr *attr,
545                      struct obd_trans_info *oti, void **wait_handle)
546 {
547         struct obd_device *obd = exp->exp_obd;
548         struct inode *inode = dchild->d_inode;
549         int blocks_per_page = CFS_PAGE_SIZE >> inode->i_blkbits;
550         int rc, rc2, create;
551         struct semaphore *sem;
552         ENTRY;
553
554         LASSERTF(iobuf->dr_npages <= iobuf->dr_max_pages, "%d,%d\n",
555                  iobuf->dr_npages, iobuf->dr_max_pages);
556         LASSERT(iobuf->dr_npages <= OBDFILTER_CREATED_SCRATCHPAD_ENTRIES);
557
558         if (rw == OBD_BRW_READ) {
559                 if (iobuf->dr_npages == 0)
560                         RETURN(0);
561                 create = 0;
562                 sem = NULL;
563         } else {
564                 LASSERTF(rw == OBD_BRW_WRITE, "%x\n", rw);
565                 LASSERT(iobuf->dr_npages > 0);
566                 create = 1;
567                 sem = &obd->u.filter.fo_alloc_lock;
568
569                 lquota_enforce(filter_quota_interface_ref, obd, iobuf->dr_ignore_quota);
570         }
571
572         rc = fsfilt_map_inode_pages(obd, inode, iobuf->dr_pages,
573                                     iobuf->dr_npages, iobuf->dr_blocks,
574                                     obdfilter_created_scratchpad, create, sem);
575
576         if (rw == OBD_BRW_WRITE) {
577                 if (rc == 0) {
578                         filter_tally(exp, iobuf->dr_pages,
579                                      iobuf->dr_npages, iobuf->dr_blocks,
580                                      blocks_per_page, 1);
581                         if (attr->ia_size > i_size_read(inode))
582                                 attr->ia_valid |= ATTR_SIZE;
583                         rc = fsfilt_setattr(obd, dchild,
584                                             oti->oti_handle, attr, 0);
585                 }
586
587                 UNLOCK_INODE_MUTEX(inode);
588
589                 rc2 = filter_finish_transno(exp, oti, 0, 0);
590                 if (rc2 != 0) {
591                         CERROR("can't close transaction: %d\n", rc2);
592                         if (rc == 0)
593                                 rc = rc2;
594                 }
595
596                 rc2 = fsfilt_commit_async(obd,inode,oti->oti_handle,
597                                           wait_handle);
598                 if (rc == 0)
599                         rc = rc2;
600                 if (rc != 0)
601                         RETURN(rc);
602         } else if (rc == 0) {
603                 filter_tally(exp, iobuf->dr_pages, iobuf->dr_npages,
604                              iobuf->dr_blocks, blocks_per_page, 0);
605         }
606
607         rc = filter_clear_page_cache(inode, iobuf);
608         if (rc != 0)
609                 RETURN(rc);
610
611         RETURN(filter_do_bio(exp, inode, iobuf, rw));
612 }
613
614 /* See if there are unallocated parts in given file region */
615 static int filter_range_is_mapped(struct inode *inode, obd_size offset, int len)
616 {
617         sector_t (*fs_bmap)(struct address_space *, sector_t) =
618                 inode->i_mapping->a_ops->bmap;
619         int j;
620
621         /* We can't know if we are overwriting or not */
622         if (fs_bmap == NULL)
623                 return 0;
624
625         offset >>= inode->i_blkbits;
626         len >>= inode->i_blkbits;
627
628         for (j = 0; j <= len; j++)
629                 if (fs_bmap(inode->i_mapping, offset + j) == 0)
630                         return 0;
631
632         return 1;
633 }
634
635 int filter_commitrw_write(struct obd_export *exp, struct obdo *oa,
636                           int objcount, struct obd_ioobj *obj, int niocount,
637                           struct niobuf_local *res, struct obd_trans_info *oti,
638                           int rc)
639 {
640         struct niobuf_local *lnb;
641         struct filter_iobuf *iobuf = NULL;
642         struct lvfs_run_ctxt saved;
643         struct fsfilt_objinfo fso;
644         struct iattr iattr = { 0 };
645         struct inode *inode = NULL;
646         unsigned long now = jiffies;
647         int i, err, cleanup_phase = 0;
648         struct obd_device *obd = exp->exp_obd;
649         void *wait_handle;
650         int   total_size = 0, rc2;
651         unsigned int qcids[MAXQUOTAS] = {0, 0};
652         ENTRY;
653
654         LASSERT(oti != NULL);
655         LASSERT(objcount == 1);
656         LASSERT(current->journal_info == NULL);
657
658         if (rc != 0)
659                 GOTO(cleanup, rc);
660
661         /* Unfortunately, if quota master is too busy to handle the
662          * pre-dqacq in time and quota hash on ost is used up, we
663          * have to wait for the completion of in flight dqacq/dqrel,
664          * then try again */
665         if ((rc2 = lquota_chkquota(filter_quota_interface_ref, obd, oa->o_uid,
666                                    oa->o_gid, niocount)) == QUOTA_RET_ACQUOTA) {
667                 OBD_FAIL_TIMEOUT(OBD_FAIL_OST_HOLD_WRITE_RPC, 90);
668                 lquota_acquire(filter_quota_interface_ref, obd, oa->o_uid,
669                                oa->o_gid);
670         }
671
672         if (rc2 < 0) {
673                 rc = rc2;
674                 GOTO(cleanup, rc);
675         }
676
677         iobuf = filter_iobuf_get(&obd->u.filter, oti);
678         if (IS_ERR(iobuf))
679                 GOTO(cleanup, rc = PTR_ERR(iobuf));
680         cleanup_phase = 1;
681
682         fso.fso_dentry = res->dentry;
683         fso.fso_bufcnt = obj->ioo_bufcnt;
684         inode = res->dentry->d_inode;
685
686         iobuf->dr_ignore_quota = 0;
687         for (i = 0, lnb = res; i < obj->ioo_bufcnt; i++, lnb++) {
688                 loff_t this_size;
689
690                 /* If overwriting an existing block, we don't need a grant */
691                 if (!(lnb->flags & OBD_BRW_GRANTED) && lnb->rc == -ENOSPC &&
692                     filter_range_is_mapped(inode, lnb->offset, lnb->len))
693                         lnb->rc = 0;
694
695                 if (lnb->rc) { /* ENOSPC, network RPC error, etc. */
696                         CDEBUG(D_INODE, "Skipping [%d] == %d\n", i, lnb->rc);
697                         continue;
698                 }
699
700                 err = filter_iobuf_add_page(obd, iobuf, inode, lnb->page);
701                 LASSERT (err == 0);
702
703                 total_size += lnb->len;
704
705                 /* we expect these pages to be in offset order, but we'll
706                  * be forgiving */
707                 this_size = lnb->offset + lnb->len;
708                 if (this_size > iattr.ia_size)
709                         iattr.ia_size = this_size;
710
711                 /* if one page is a write-back page from client cache, or it's
712                  * written by root, then mark the whole io request as ignore
713                  * quota request */
714                 if (lnb->flags & (OBD_BRW_FROM_GRANT | OBD_BRW_NOQUOTA))
715                         iobuf->dr_ignore_quota = 1;
716         }
717
718         push_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
719         cleanup_phase = 2;
720
721         DQUOT_INIT(inode);
722
723         LOCK_INODE_MUTEX(inode);
724         fsfilt_check_slow(obd, now, "i_mutex");
725         oti->oti_handle = fsfilt_brw_start(obd, objcount, &fso, niocount, res,
726                                            oti);
727         if (IS_ERR(oti->oti_handle)) {
728                 UNLOCK_INODE_MUTEX(inode);
729                 rc = PTR_ERR(oti->oti_handle);
730                 CDEBUG(rc == -ENOSPC ? D_INODE : D_ERROR,
731                        "error starting transaction: rc = %d\n", rc);
732                 oti->oti_handle = NULL;
733                 GOTO(cleanup, rc);
734         }
735         /* have to call fsfilt_commit() from this point on */
736
737         fsfilt_check_slow(obd, now, "brw_start");
738
739         i = OBD_MD_FLATIME | OBD_MD_FLMTIME | OBD_MD_FLCTIME;
740
741         /* If the inode still has SUID+SGID bits set (see filter_precreate())
742          * then we will accept the UID+GID if sent by the client for
743          * initializing the ownership of this inode.  We only allow this to
744          * happen once (so clear these bits) and later only allow setattr. */
745         if (inode->i_mode & S_ISUID)
746                 i |= OBD_MD_FLUID;
747         if (inode->i_mode & S_ISGID)
748                 i |= OBD_MD_FLGID;
749
750         iattr_from_obdo(&iattr, oa, i);
751         if (iattr.ia_valid & (ATTR_UID | ATTR_GID)) {
752                 unsigned int save;
753
754                 CDEBUG(D_INODE, "update UID/GID to %lu/%lu\n",
755                        (unsigned long)oa->o_uid, (unsigned long)oa->o_gid);
756
757                 cfs_cap_raise(CFS_CAP_SYS_RESOURCE);
758
759                 iattr.ia_valid |= ATTR_MODE;
760                 iattr.ia_mode = inode->i_mode;
761                 if (iattr.ia_valid & ATTR_UID)
762                         iattr.ia_mode &= ~S_ISUID;
763                 if (iattr.ia_valid & ATTR_GID)
764                         iattr.ia_mode &= ~S_ISGID;
765
766                 rc = filter_update_fidea(exp, inode, oti->oti_handle, oa);
767
768                 /* To avoid problems with quotas, UID and GID must be set
769                  * in the inode before filter_direct_io() - see bug 10357. */
770                 save = iattr.ia_valid;
771                 iattr.ia_valid &= (ATTR_UID | ATTR_GID);
772                 rc = fsfilt_setattr(obd, res->dentry, oti->oti_handle, &iattr, 0);
773                 CDEBUG(D_QUOTA, "set uid(%u)/gid(%u) to ino(%lu). rc(%d)\n", 
774                                 iattr.ia_uid, iattr.ia_gid, inode->i_ino, rc);
775                 iattr.ia_valid = save & ~(ATTR_UID | ATTR_GID);
776         }
777
778         /* filter_direct_io drops i_mutex */
779         rc = filter_direct_io(OBD_BRW_WRITE, res->dentry, iobuf, exp, &iattr,
780                               oti, &wait_handle);
781         if (rc == 0)
782                 obdo_from_inode(oa, inode,
783                                 FILTER_VALID_FLAGS |OBD_MD_FLUID |OBD_MD_FLGID);
784         else
785                 obdo_from_inode(oa, inode, OBD_MD_FLUID | OBD_MD_FLGID);
786
787         lquota_getflag(filter_quota_interface_ref, obd, oa);
788
789         fsfilt_check_slow(obd, now, "direct_io");
790
791         err = fsfilt_commit_wait(obd, inode, wait_handle);
792         if (err) {
793                 CERROR("Failure to commit OST transaction (%d)?\n", err);
794                 rc = err;
795         }
796
797         if (obd->obd_replayable && !rc)
798                 LASSERTF(oti->oti_transno <= obd->obd_last_committed,
799                          "oti_transno "LPU64" last_committed "LPU64"\n",
800                          oti->oti_transno, obd->obd_last_committed);
801
802         fsfilt_check_slow(obd, now, "commitrw commit");
803
804 cleanup:
805         filter_grant_commit(exp, niocount, res);
806
807         switch (cleanup_phase) {
808         case 2:
809                 pop_ctxt(&saved, &obd->obd_lvfs_ctxt, NULL);
810                 LASSERT(current->journal_info == NULL);
811         case 1:
812                 filter_iobuf_put(&obd->u.filter, iobuf, oti);
813         case 0:
814                 /*
815                  * lnb->page automatically returns back into per-thread page
816                  * pool (bug 5137)
817                  */
818                 f_dput(res->dentry);
819         }
820
821         /* trigger quota pre-acquire */
822         qcids[USRQUOTA] = oa->o_uid;
823         qcids[GRPQUOTA] = oa->o_gid;
824         err = lquota_adjust(filter_quota_interface_ref, obd, qcids, NULL, rc,
825                             FSFILT_OP_CREATE);
826         CDEBUG(err ? D_ERROR : D_QUOTA,
827                "filter adjust qunit! (rc:%d)\n", err);
828
829         RETURN(rc);
830 }