f1dd70e201cfa08ba2cab5870fee698860156d0f
[pandora-kernel.git] / fs / xfs / linux-2.6 / xfs_aops.c
1 /*
2  * Copyright (c) 2000-2005 Silicon Graphics, Inc.
3  * All Rights Reserved.
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License as
7  * published by the Free Software Foundation.
8  *
9  * This program is distributed in the hope that it would be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write the Free Software Foundation,
16  * Inc.,  51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17  */
18 #include "xfs.h"
19 #include "xfs_bit.h"
20 #include "xfs_log.h"
21 #include "xfs_inum.h"
22 #include "xfs_sb.h"
23 #include "xfs_ag.h"
24 #include "xfs_dir2.h"
25 #include "xfs_trans.h"
26 #include "xfs_dmapi.h"
27 #include "xfs_mount.h"
28 #include "xfs_bmap_btree.h"
29 #include "xfs_alloc_btree.h"
30 #include "xfs_ialloc_btree.h"
31 #include "xfs_dir2_sf.h"
32 #include "xfs_attr_sf.h"
33 #include "xfs_dinode.h"
34 #include "xfs_inode.h"
35 #include "xfs_alloc.h"
36 #include "xfs_btree.h"
37 #include "xfs_error.h"
38 #include "xfs_rw.h"
39 #include "xfs_iomap.h"
40 #include "xfs_vnodeops.h"
41 #include "xfs_trace.h"
42 #include "xfs_bmap.h"
43 #include <linux/gfp.h>
44 #include <linux/mpage.h>
45 #include <linux/pagevec.h>
46 #include <linux/writeback.h>
47
48 /*
49  * Types of I/O for bmap clustering and I/O completion tracking.
50  */
51 enum {
52         IO_READ,        /* mapping for a read */
53         IO_DELAY,       /* mapping covers delalloc region */
54         IO_UNWRITTEN,   /* mapping covers allocated but uninitialized data */
55         IO_NEW          /* just allocated */
56 };
57
58 /*
59  * Prime number of hash buckets since address is used as the key.
60  */
61 #define NVSYNC          37
62 #define to_ioend_wq(v)  (&xfs_ioend_wq[((unsigned long)v) % NVSYNC])
63 static wait_queue_head_t xfs_ioend_wq[NVSYNC];
64
65 void __init
66 xfs_ioend_init(void)
67 {
68         int i;
69
70         for (i = 0; i < NVSYNC; i++)
71                 init_waitqueue_head(&xfs_ioend_wq[i]);
72 }
73
74 void
75 xfs_ioend_wait(
76         xfs_inode_t     *ip)
77 {
78         wait_queue_head_t *wq = to_ioend_wq(ip);
79
80         wait_event(*wq, (atomic_read(&ip->i_iocount) == 0));
81 }
82
83 STATIC void
84 xfs_ioend_wake(
85         xfs_inode_t     *ip)
86 {
87         if (atomic_dec_and_test(&ip->i_iocount))
88                 wake_up(to_ioend_wq(ip));
89 }
90
91 void
92 xfs_count_page_state(
93         struct page             *page,
94         int                     *delalloc,
95         int                     *unmapped,
96         int                     *unwritten)
97 {
98         struct buffer_head      *bh, *head;
99
100         *delalloc = *unmapped = *unwritten = 0;
101
102         bh = head = page_buffers(page);
103         do {
104                 if (buffer_uptodate(bh) && !buffer_mapped(bh))
105                         (*unmapped) = 1;
106                 else if (buffer_unwritten(bh))
107                         (*unwritten) = 1;
108                 else if (buffer_delay(bh))
109                         (*delalloc) = 1;
110         } while ((bh = bh->b_this_page) != head);
111 }
112
113 STATIC struct block_device *
114 xfs_find_bdev_for_inode(
115         struct inode            *inode)
116 {
117         struct xfs_inode        *ip = XFS_I(inode);
118         struct xfs_mount        *mp = ip->i_mount;
119
120         if (XFS_IS_REALTIME_INODE(ip))
121                 return mp->m_rtdev_targp->bt_bdev;
122         else
123                 return mp->m_ddev_targp->bt_bdev;
124 }
125
126 /*
127  * We're now finished for good with this ioend structure.
128  * Update the page state via the associated buffer_heads,
129  * release holds on the inode and bio, and finally free
130  * up memory.  Do not use the ioend after this.
131  */
132 STATIC void
133 xfs_destroy_ioend(
134         xfs_ioend_t             *ioend)
135 {
136         struct buffer_head      *bh, *next;
137         struct xfs_inode        *ip = XFS_I(ioend->io_inode);
138
139         for (bh = ioend->io_buffer_head; bh; bh = next) {
140                 next = bh->b_private;
141                 bh->b_end_io(bh, !ioend->io_error);
142         }
143
144         /*
145          * Volume managers supporting multiple paths can send back ENODEV
146          * when the final path disappears.  In this case continuing to fill
147          * the page cache with dirty data which cannot be written out is
148          * evil, so prevent that.
149          */
150         if (unlikely(ioend->io_error == -ENODEV)) {
151                 xfs_do_force_shutdown(ip->i_mount, SHUTDOWN_DEVICE_REQ,
152                                       __FILE__, __LINE__);
153         }
154
155         xfs_ioend_wake(ip);
156         mempool_free(ioend, xfs_ioend_pool);
157 }
158
159 /*
160  * If the end of the current ioend is beyond the current EOF,
161  * return the new EOF value, otherwise zero.
162  */
163 STATIC xfs_fsize_t
164 xfs_ioend_new_eof(
165         xfs_ioend_t             *ioend)
166 {
167         xfs_inode_t             *ip = XFS_I(ioend->io_inode);
168         xfs_fsize_t             isize;
169         xfs_fsize_t             bsize;
170
171         bsize = ioend->io_offset + ioend->io_size;
172         isize = MAX(ip->i_size, ip->i_new_size);
173         isize = MIN(isize, bsize);
174         return isize > ip->i_d.di_size ? isize : 0;
175 }
176
177 /*
178  * Update on-disk file size now that data has been written to disk.  The
179  * current in-memory file size is i_size.  If a write is beyond eof i_new_size
180  * will be the intended file size until i_size is updated.  If this write does
181  * not extend all the way to the valid file size then restrict this update to
182  * the end of the write.
183  *
184  * This function does not block as blocking on the inode lock in IO completion
185  * can lead to IO completion order dependency deadlocks.. If it can't get the
186  * inode ilock it will return EAGAIN. Callers must handle this.
187  */
188 STATIC int
189 xfs_setfilesize(
190         xfs_ioend_t             *ioend)
191 {
192         xfs_inode_t             *ip = XFS_I(ioend->io_inode);
193         xfs_fsize_t             isize;
194
195         ASSERT((ip->i_d.di_mode & S_IFMT) == S_IFREG);
196         ASSERT(ioend->io_type != IO_READ);
197
198         if (unlikely(ioend->io_error))
199                 return 0;
200
201         if (!xfs_ilock_nowait(ip, XFS_ILOCK_EXCL))
202                 return EAGAIN;
203
204         isize = xfs_ioend_new_eof(ioend);
205         if (isize) {
206                 ip->i_d.di_size = isize;
207                 xfs_mark_inode_dirty(ip);
208         }
209
210         xfs_iunlock(ip, XFS_ILOCK_EXCL);
211         return 0;
212 }
213
214 /*
215  * Schedule IO completion handling on a xfsdatad if this was
216  * the final hold on this ioend. If we are asked to wait,
217  * flush the workqueue.
218  */
219 STATIC void
220 xfs_finish_ioend(
221         xfs_ioend_t     *ioend,
222         int             wait)
223 {
224         if (atomic_dec_and_test(&ioend->io_remaining)) {
225                 struct workqueue_struct *wq;
226
227                 wq = (ioend->io_type == IO_UNWRITTEN) ?
228                         xfsconvertd_workqueue : xfsdatad_workqueue;
229                 queue_work(wq, &ioend->io_work);
230                 if (wait)
231                         flush_workqueue(wq);
232         }
233 }
234
235 /*
236  * IO write completion.
237  */
238 STATIC void
239 xfs_end_io(
240         struct work_struct *work)
241 {
242         xfs_ioend_t     *ioend = container_of(work, xfs_ioend_t, io_work);
243         struct xfs_inode *ip = XFS_I(ioend->io_inode);
244         int             error = 0;
245
246         /*
247          * For unwritten extents we need to issue transactions to convert a
248          * range to normal written extens after the data I/O has finished.
249          */
250         if (ioend->io_type == IO_UNWRITTEN &&
251             likely(!ioend->io_error && !XFS_FORCED_SHUTDOWN(ip->i_mount))) {
252
253                 error = xfs_iomap_write_unwritten(ip, ioend->io_offset,
254                                                  ioend->io_size);
255                 if (error)
256                         ioend->io_error = error;
257         }
258
259         /*
260          * We might have to update the on-disk file size after extending
261          * writes.
262          */
263         if (ioend->io_type != IO_READ) {
264                 error = xfs_setfilesize(ioend);
265                 ASSERT(!error || error == EAGAIN);
266         }
267
268         /*
269          * If we didn't complete processing of the ioend, requeue it to the
270          * tail of the workqueue for another attempt later. Otherwise destroy
271          * it.
272          */
273         if (error == EAGAIN) {
274                 atomic_inc(&ioend->io_remaining);
275                 xfs_finish_ioend(ioend, 0);
276                 /* ensure we don't spin on blocked ioends */
277                 delay(1);
278         } else
279                 xfs_destroy_ioend(ioend);
280 }
281
282 /*
283  * Allocate and initialise an IO completion structure.
284  * We need to track unwritten extent write completion here initially.
285  * We'll need to extend this for updating the ondisk inode size later
286  * (vs. incore size).
287  */
288 STATIC xfs_ioend_t *
289 xfs_alloc_ioend(
290         struct inode            *inode,
291         unsigned int            type)
292 {
293         xfs_ioend_t             *ioend;
294
295         ioend = mempool_alloc(xfs_ioend_pool, GFP_NOFS);
296
297         /*
298          * Set the count to 1 initially, which will prevent an I/O
299          * completion callback from happening before we have started
300          * all the I/O from calling the completion routine too early.
301          */
302         atomic_set(&ioend->io_remaining, 1);
303         ioend->io_error = 0;
304         ioend->io_list = NULL;
305         ioend->io_type = type;
306         ioend->io_inode = inode;
307         ioend->io_buffer_head = NULL;
308         ioend->io_buffer_tail = NULL;
309         atomic_inc(&XFS_I(ioend->io_inode)->i_iocount);
310         ioend->io_offset = 0;
311         ioend->io_size = 0;
312
313         INIT_WORK(&ioend->io_work, xfs_end_io);
314         return ioend;
315 }
316
317 STATIC int
318 xfs_map_blocks(
319         struct inode            *inode,
320         loff_t                  offset,
321         ssize_t                 count,
322         struct xfs_bmbt_irec    *imap,
323         int                     flags)
324 {
325         int                     nmaps = 1;
326         int                     new = 0;
327
328         return -xfs_iomap(XFS_I(inode), offset, count, flags, imap, &nmaps, &new);
329 }
330
331 STATIC int
332 xfs_iomap_valid(
333         struct inode            *inode,
334         struct xfs_bmbt_irec    *imap,
335         loff_t                  offset)
336 {
337         struct xfs_mount        *mp = XFS_I(inode)->i_mount;
338         xfs_off_t               iomap_offset = XFS_FSB_TO_B(mp, imap->br_startoff);
339         xfs_off_t               iomap_bsize = XFS_FSB_TO_B(mp, imap->br_blockcount);
340
341         return offset >= iomap_offset &&
342                 offset < iomap_offset + iomap_bsize;
343 }
344
345 /*
346  * BIO completion handler for buffered IO.
347  */
348 STATIC void
349 xfs_end_bio(
350         struct bio              *bio,
351         int                     error)
352 {
353         xfs_ioend_t             *ioend = bio->bi_private;
354
355         ASSERT(atomic_read(&bio->bi_cnt) >= 1);
356         ioend->io_error = test_bit(BIO_UPTODATE, &bio->bi_flags) ? 0 : error;
357
358         /* Toss bio and pass work off to an xfsdatad thread */
359         bio->bi_private = NULL;
360         bio->bi_end_io = NULL;
361         bio_put(bio);
362
363         xfs_finish_ioend(ioend, 0);
364 }
365
366 STATIC void
367 xfs_submit_ioend_bio(
368         struct writeback_control *wbc,
369         xfs_ioend_t             *ioend,
370         struct bio              *bio)
371 {
372         atomic_inc(&ioend->io_remaining);
373         bio->bi_private = ioend;
374         bio->bi_end_io = xfs_end_bio;
375
376         /*
377          * If the I/O is beyond EOF we mark the inode dirty immediately
378          * but don't update the inode size until I/O completion.
379          */
380         if (xfs_ioend_new_eof(ioend))
381                 xfs_mark_inode_dirty(XFS_I(ioend->io_inode));
382
383         submit_bio(wbc->sync_mode == WB_SYNC_ALL ?
384                    WRITE_SYNC_PLUG : WRITE, bio);
385         ASSERT(!bio_flagged(bio, BIO_EOPNOTSUPP));
386         bio_put(bio);
387 }
388
389 STATIC struct bio *
390 xfs_alloc_ioend_bio(
391         struct buffer_head      *bh)
392 {
393         struct bio              *bio;
394         int                     nvecs = bio_get_nr_vecs(bh->b_bdev);
395
396         do {
397                 bio = bio_alloc(GFP_NOIO, nvecs);
398                 nvecs >>= 1;
399         } while (!bio);
400
401         ASSERT(bio->bi_private == NULL);
402         bio->bi_sector = bh->b_blocknr * (bh->b_size >> 9);
403         bio->bi_bdev = bh->b_bdev;
404         bio_get(bio);
405         return bio;
406 }
407
408 STATIC void
409 xfs_start_buffer_writeback(
410         struct buffer_head      *bh)
411 {
412         ASSERT(buffer_mapped(bh));
413         ASSERT(buffer_locked(bh));
414         ASSERT(!buffer_delay(bh));
415         ASSERT(!buffer_unwritten(bh));
416
417         mark_buffer_async_write(bh);
418         set_buffer_uptodate(bh);
419         clear_buffer_dirty(bh);
420 }
421
422 STATIC void
423 xfs_start_page_writeback(
424         struct page             *page,
425         int                     clear_dirty,
426         int                     buffers)
427 {
428         ASSERT(PageLocked(page));
429         ASSERT(!PageWriteback(page));
430         if (clear_dirty)
431                 clear_page_dirty_for_io(page);
432         set_page_writeback(page);
433         unlock_page(page);
434         /* If no buffers on the page are to be written, finish it here */
435         if (!buffers)
436                 end_page_writeback(page);
437 }
438
439 static inline int bio_add_buffer(struct bio *bio, struct buffer_head *bh)
440 {
441         return bio_add_page(bio, bh->b_page, bh->b_size, bh_offset(bh));
442 }
443
444 /*
445  * Submit all of the bios for all of the ioends we have saved up, covering the
446  * initial writepage page and also any probed pages.
447  *
448  * Because we may have multiple ioends spanning a page, we need to start
449  * writeback on all the buffers before we submit them for I/O. If we mark the
450  * buffers as we got, then we can end up with a page that only has buffers
451  * marked async write and I/O complete on can occur before we mark the other
452  * buffers async write.
453  *
454  * The end result of this is that we trip a bug in end_page_writeback() because
455  * we call it twice for the one page as the code in end_buffer_async_write()
456  * assumes that all buffers on the page are started at the same time.
457  *
458  * The fix is two passes across the ioend list - one to start writeback on the
459  * buffer_heads, and then submit them for I/O on the second pass.
460  */
461 STATIC void
462 xfs_submit_ioend(
463         struct writeback_control *wbc,
464         xfs_ioend_t             *ioend)
465 {
466         xfs_ioend_t             *head = ioend;
467         xfs_ioend_t             *next;
468         struct buffer_head      *bh;
469         struct bio              *bio;
470         sector_t                lastblock = 0;
471
472         /* Pass 1 - start writeback */
473         do {
474                 next = ioend->io_list;
475                 for (bh = ioend->io_buffer_head; bh; bh = bh->b_private) {
476                         xfs_start_buffer_writeback(bh);
477                 }
478         } while ((ioend = next) != NULL);
479
480         /* Pass 2 - submit I/O */
481         ioend = head;
482         do {
483                 next = ioend->io_list;
484                 bio = NULL;
485
486                 for (bh = ioend->io_buffer_head; bh; bh = bh->b_private) {
487
488                         if (!bio) {
489  retry:
490                                 bio = xfs_alloc_ioend_bio(bh);
491                         } else if (bh->b_blocknr != lastblock + 1) {
492                                 xfs_submit_ioend_bio(wbc, ioend, bio);
493                                 goto retry;
494                         }
495
496                         if (bio_add_buffer(bio, bh) != bh->b_size) {
497                                 xfs_submit_ioend_bio(wbc, ioend, bio);
498                                 goto retry;
499                         }
500
501                         lastblock = bh->b_blocknr;
502                 }
503                 if (bio)
504                         xfs_submit_ioend_bio(wbc, ioend, bio);
505                 xfs_finish_ioend(ioend, 0);
506         } while ((ioend = next) != NULL);
507 }
508
509 /*
510  * Cancel submission of all buffer_heads so far in this endio.
511  * Toss the endio too.  Only ever called for the initial page
512  * in a writepage request, so only ever one page.
513  */
514 STATIC void
515 xfs_cancel_ioend(
516         xfs_ioend_t             *ioend)
517 {
518         xfs_ioend_t             *next;
519         struct buffer_head      *bh, *next_bh;
520
521         do {
522                 next = ioend->io_list;
523                 bh = ioend->io_buffer_head;
524                 do {
525                         next_bh = bh->b_private;
526                         clear_buffer_async_write(bh);
527                         unlock_buffer(bh);
528                 } while ((bh = next_bh) != NULL);
529
530                 xfs_ioend_wake(XFS_I(ioend->io_inode));
531                 mempool_free(ioend, xfs_ioend_pool);
532         } while ((ioend = next) != NULL);
533 }
534
535 /*
536  * Test to see if we've been building up a completion structure for
537  * earlier buffers -- if so, we try to append to this ioend if we
538  * can, otherwise we finish off any current ioend and start another.
539  * Return true if we've finished the given ioend.
540  */
541 STATIC void
542 xfs_add_to_ioend(
543         struct inode            *inode,
544         struct buffer_head      *bh,
545         xfs_off_t               offset,
546         unsigned int            type,
547         xfs_ioend_t             **result,
548         int                     need_ioend)
549 {
550         xfs_ioend_t             *ioend = *result;
551
552         if (!ioend || need_ioend || type != ioend->io_type) {
553                 xfs_ioend_t     *previous = *result;
554
555                 ioend = xfs_alloc_ioend(inode, type);
556                 ioend->io_offset = offset;
557                 ioend->io_buffer_head = bh;
558                 ioend->io_buffer_tail = bh;
559                 if (previous)
560                         previous->io_list = ioend;
561                 *result = ioend;
562         } else {
563                 ioend->io_buffer_tail->b_private = bh;
564                 ioend->io_buffer_tail = bh;
565         }
566
567         bh->b_private = NULL;
568         ioend->io_size += bh->b_size;
569 }
570
571 STATIC void
572 xfs_map_buffer(
573         struct inode            *inode,
574         struct buffer_head      *bh,
575         struct xfs_bmbt_irec    *imap,
576         xfs_off_t               offset)
577 {
578         sector_t                bn;
579         struct xfs_mount        *m = XFS_I(inode)->i_mount;
580         xfs_off_t               iomap_offset = XFS_FSB_TO_B(m, imap->br_startoff);
581         xfs_daddr_t             iomap_bn = xfs_fsb_to_db(XFS_I(inode), imap->br_startblock);
582
583         ASSERT(imap->br_startblock != HOLESTARTBLOCK);
584         ASSERT(imap->br_startblock != DELAYSTARTBLOCK);
585
586         bn = (iomap_bn >> (inode->i_blkbits - BBSHIFT)) +
587               ((offset - iomap_offset) >> inode->i_blkbits);
588
589         ASSERT(bn || XFS_IS_REALTIME_INODE(XFS_I(inode)));
590
591         bh->b_blocknr = bn;
592         set_buffer_mapped(bh);
593 }
594
595 STATIC void
596 xfs_map_at_offset(
597         struct inode            *inode,
598         struct buffer_head      *bh,
599         struct xfs_bmbt_irec    *imap,
600         xfs_off_t               offset)
601 {
602         ASSERT(imap->br_startblock != HOLESTARTBLOCK);
603         ASSERT(imap->br_startblock != DELAYSTARTBLOCK);
604
605         lock_buffer(bh);
606         xfs_map_buffer(inode, bh, imap, offset);
607         bh->b_bdev = xfs_find_bdev_for_inode(inode);
608         set_buffer_mapped(bh);
609         clear_buffer_delay(bh);
610         clear_buffer_unwritten(bh);
611 }
612
613 /*
614  * Look for a page at index that is suitable for clustering.
615  */
616 STATIC unsigned int
617 xfs_probe_page(
618         struct page             *page,
619         unsigned int            pg_offset,
620         int                     mapped)
621 {
622         int                     ret = 0;
623
624         if (PageWriteback(page))
625                 return 0;
626
627         if (page->mapping && PageDirty(page)) {
628                 if (page_has_buffers(page)) {
629                         struct buffer_head      *bh, *head;
630
631                         bh = head = page_buffers(page);
632                         do {
633                                 if (!buffer_uptodate(bh))
634                                         break;
635                                 if (mapped != buffer_mapped(bh))
636                                         break;
637                                 ret += bh->b_size;
638                                 if (ret >= pg_offset)
639                                         break;
640                         } while ((bh = bh->b_this_page) != head);
641                 } else
642                         ret = mapped ? 0 : PAGE_CACHE_SIZE;
643         }
644
645         return ret;
646 }
647
648 STATIC size_t
649 xfs_probe_cluster(
650         struct inode            *inode,
651         struct page             *startpage,
652         struct buffer_head      *bh,
653         struct buffer_head      *head,
654         int                     mapped)
655 {
656         struct pagevec          pvec;
657         pgoff_t                 tindex, tlast, tloff;
658         size_t                  total = 0;
659         int                     done = 0, i;
660
661         /* First sum forwards in this page */
662         do {
663                 if (!buffer_uptodate(bh) || (mapped != buffer_mapped(bh)))
664                         return total;
665                 total += bh->b_size;
666         } while ((bh = bh->b_this_page) != head);
667
668         /* if we reached the end of the page, sum forwards in following pages */
669         tlast = i_size_read(inode) >> PAGE_CACHE_SHIFT;
670         tindex = startpage->index + 1;
671
672         /* Prune this back to avoid pathological behavior */
673         tloff = min(tlast, startpage->index + 64);
674
675         pagevec_init(&pvec, 0);
676         while (!done && tindex <= tloff) {
677                 unsigned len = min_t(pgoff_t, PAGEVEC_SIZE, tlast - tindex + 1);
678
679                 if (!pagevec_lookup(&pvec, inode->i_mapping, tindex, len))
680                         break;
681
682                 for (i = 0; i < pagevec_count(&pvec); i++) {
683                         struct page *page = pvec.pages[i];
684                         size_t pg_offset, pg_len = 0;
685
686                         if (tindex == tlast) {
687                                 pg_offset =
688                                     i_size_read(inode) & (PAGE_CACHE_SIZE - 1);
689                                 if (!pg_offset) {
690                                         done = 1;
691                                         break;
692                                 }
693                         } else
694                                 pg_offset = PAGE_CACHE_SIZE;
695
696                         if (page->index == tindex && trylock_page(page)) {
697                                 pg_len = xfs_probe_page(page, pg_offset, mapped);
698                                 unlock_page(page);
699                         }
700
701                         if (!pg_len) {
702                                 done = 1;
703                                 break;
704                         }
705
706                         total += pg_len;
707                         tindex++;
708                 }
709
710                 pagevec_release(&pvec);
711                 cond_resched();
712         }
713
714         return total;
715 }
716
717 /*
718  * Test if a given page is suitable for writing as part of an unwritten
719  * or delayed allocate extent.
720  */
721 STATIC int
722 xfs_is_delayed_page(
723         struct page             *page,
724         unsigned int            type)
725 {
726         if (PageWriteback(page))
727                 return 0;
728
729         if (page->mapping && page_has_buffers(page)) {
730                 struct buffer_head      *bh, *head;
731                 int                     acceptable = 0;
732
733                 bh = head = page_buffers(page);
734                 do {
735                         if (buffer_unwritten(bh))
736                                 acceptable = (type == IO_UNWRITTEN);
737                         else if (buffer_delay(bh))
738                                 acceptable = (type == IO_DELAY);
739                         else if (buffer_dirty(bh) && buffer_mapped(bh))
740                                 acceptable = (type == IO_NEW);
741                         else
742                                 break;
743                 } while ((bh = bh->b_this_page) != head);
744
745                 if (acceptable)
746                         return 1;
747         }
748
749         return 0;
750 }
751
752 /*
753  * Allocate & map buffers for page given the extent map. Write it out.
754  * except for the original page of a writepage, this is called on
755  * delalloc/unwritten pages only, for the original page it is possible
756  * that the page has no mapping at all.
757  */
758 STATIC int
759 xfs_convert_page(
760         struct inode            *inode,
761         struct page             *page,
762         loff_t                  tindex,
763         struct xfs_bmbt_irec    *imap,
764         xfs_ioend_t             **ioendp,
765         struct writeback_control *wbc,
766         int                     startio,
767         int                     all_bh)
768 {
769         struct buffer_head      *bh, *head;
770         xfs_off_t               end_offset;
771         unsigned long           p_offset;
772         unsigned int            type;
773         int                     len, page_dirty;
774         int                     count = 0, done = 0, uptodate = 1;
775         xfs_off_t               offset = page_offset(page);
776
777         if (page->index != tindex)
778                 goto fail;
779         if (!trylock_page(page))
780                 goto fail;
781         if (PageWriteback(page))
782                 goto fail_unlock_page;
783         if (page->mapping != inode->i_mapping)
784                 goto fail_unlock_page;
785         if (!xfs_is_delayed_page(page, (*ioendp)->io_type))
786                 goto fail_unlock_page;
787
788         /*
789          * page_dirty is initially a count of buffers on the page before
790          * EOF and is decremented as we move each into a cleanable state.
791          *
792          * Derivation:
793          *
794          * End offset is the highest offset that this page should represent.
795          * If we are on the last page, (end_offset & (PAGE_CACHE_SIZE - 1))
796          * will evaluate non-zero and be less than PAGE_CACHE_SIZE and
797          * hence give us the correct page_dirty count. On any other page,
798          * it will be zero and in that case we need page_dirty to be the
799          * count of buffers on the page.
800          */
801         end_offset = min_t(unsigned long long,
802                         (xfs_off_t)(page->index + 1) << PAGE_CACHE_SHIFT,
803                         i_size_read(inode));
804
805         len = 1 << inode->i_blkbits;
806         p_offset = min_t(unsigned long, end_offset & (PAGE_CACHE_SIZE - 1),
807                                         PAGE_CACHE_SIZE);
808         p_offset = p_offset ? roundup(p_offset, len) : PAGE_CACHE_SIZE;
809         page_dirty = p_offset / len;
810
811         bh = head = page_buffers(page);
812         do {
813                 if (offset >= end_offset)
814                         break;
815                 if (!buffer_uptodate(bh))
816                         uptodate = 0;
817                 if (!(PageUptodate(page) || buffer_uptodate(bh))) {
818                         done = 1;
819                         continue;
820                 }
821
822                 if (buffer_unwritten(bh) || buffer_delay(bh)) {
823                         if (buffer_unwritten(bh))
824                                 type = IO_UNWRITTEN;
825                         else
826                                 type = IO_DELAY;
827
828                         if (!xfs_iomap_valid(inode, imap, offset)) {
829                                 done = 1;
830                                 continue;
831                         }
832
833                         ASSERT(imap->br_startblock != HOLESTARTBLOCK);
834                         ASSERT(imap->br_startblock != DELAYSTARTBLOCK);
835
836                         xfs_map_at_offset(inode, bh, imap, offset);
837                         if (startio) {
838                                 xfs_add_to_ioend(inode, bh, offset,
839                                                 type, ioendp, done);
840                         } else {
841                                 set_buffer_dirty(bh);
842                                 unlock_buffer(bh);
843                                 mark_buffer_dirty(bh);
844                         }
845                         page_dirty--;
846                         count++;
847                 } else {
848                         type = IO_NEW;
849                         if (buffer_mapped(bh) && all_bh && startio) {
850                                 lock_buffer(bh);
851                                 xfs_add_to_ioend(inode, bh, offset,
852                                                 type, ioendp, done);
853                                 count++;
854                                 page_dirty--;
855                         } else {
856                                 done = 1;
857                         }
858                 }
859         } while (offset += len, (bh = bh->b_this_page) != head);
860
861         if (uptodate && bh == head)
862                 SetPageUptodate(page);
863
864         if (startio) {
865                 if (count) {
866                         wbc->nr_to_write--;
867                         if (wbc->nr_to_write <= 0)
868                                 done = 1;
869                 }
870                 xfs_start_page_writeback(page, !page_dirty, count);
871         }
872
873         return done;
874  fail_unlock_page:
875         unlock_page(page);
876  fail:
877         return 1;
878 }
879
880 /*
881  * Convert & write out a cluster of pages in the same extent as defined
882  * by mp and following the start page.
883  */
884 STATIC void
885 xfs_cluster_write(
886         struct inode            *inode,
887         pgoff_t                 tindex,
888         struct xfs_bmbt_irec    *imap,
889         xfs_ioend_t             **ioendp,
890         struct writeback_control *wbc,
891         int                     startio,
892         int                     all_bh,
893         pgoff_t                 tlast)
894 {
895         struct pagevec          pvec;
896         int                     done = 0, i;
897
898         pagevec_init(&pvec, 0);
899         while (!done && tindex <= tlast) {
900                 unsigned len = min_t(pgoff_t, PAGEVEC_SIZE, tlast - tindex + 1);
901
902                 if (!pagevec_lookup(&pvec, inode->i_mapping, tindex, len))
903                         break;
904
905                 for (i = 0; i < pagevec_count(&pvec); i++) {
906                         done = xfs_convert_page(inode, pvec.pages[i], tindex++,
907                                         imap, ioendp, wbc, startio, all_bh);
908                         if (done)
909                                 break;
910                 }
911
912                 pagevec_release(&pvec);
913                 cond_resched();
914         }
915 }
916
917 STATIC void
918 xfs_vm_invalidatepage(
919         struct page             *page,
920         unsigned long           offset)
921 {
922         trace_xfs_invalidatepage(page->mapping->host, page, offset);
923         block_invalidatepage(page, offset);
924 }
925
926 /*
927  * If the page has delalloc buffers on it, we need to punch them out before we
928  * invalidate the page. If we don't, we leave a stale delalloc mapping on the
929  * inode that can trip a BUG() in xfs_get_blocks() later on if a direct IO read
930  * is done on that same region - the delalloc extent is returned when none is
931  * supposed to be there.
932  *
933  * We prevent this by truncating away the delalloc regions on the page before
934  * invalidating it. Because they are delalloc, we can do this without needing a
935  * transaction. Indeed - if we get ENOSPC errors, we have to be able to do this
936  * truncation without a transaction as there is no space left for block
937  * reservation (typically why we see a ENOSPC in writeback).
938  *
939  * This is not a performance critical path, so for now just do the punching a
940  * buffer head at a time.
941  */
942 STATIC void
943 xfs_aops_discard_page(
944         struct page             *page)
945 {
946         struct inode            *inode = page->mapping->host;
947         struct xfs_inode        *ip = XFS_I(inode);
948         struct buffer_head      *bh, *head;
949         loff_t                  offset = page_offset(page);
950         ssize_t                 len = 1 << inode->i_blkbits;
951
952         if (!xfs_is_delayed_page(page, IO_DELAY))
953                 goto out_invalidate;
954
955         if (XFS_FORCED_SHUTDOWN(ip->i_mount))
956                 goto out_invalidate;
957
958         xfs_fs_cmn_err(CE_ALERT, ip->i_mount,
959                 "page discard on page %p, inode 0x%llx, offset %llu.",
960                         page, ip->i_ino, offset);
961
962         xfs_ilock(ip, XFS_ILOCK_EXCL);
963         bh = head = page_buffers(page);
964         do {
965                 int             done;
966                 xfs_fileoff_t   offset_fsb;
967                 xfs_bmbt_irec_t imap;
968                 int             nimaps = 1;
969                 int             error;
970                 xfs_fsblock_t   firstblock;
971                 xfs_bmap_free_t flist;
972
973                 if (!buffer_delay(bh))
974                         goto next_buffer;
975
976                 offset_fsb = XFS_B_TO_FSBT(ip->i_mount, offset);
977
978                 /*
979                  * Map the range first and check that it is a delalloc extent
980                  * before trying to unmap the range. Otherwise we will be
981                  * trying to remove a real extent (which requires a
982                  * transaction) or a hole, which is probably a bad idea...
983                  */
984                 error = xfs_bmapi(NULL, ip, offset_fsb, 1,
985                                 XFS_BMAPI_ENTIRE,  NULL, 0, &imap,
986                                 &nimaps, NULL, NULL);
987
988                 if (error) {
989                         /* something screwed, just bail */
990                         if (!XFS_FORCED_SHUTDOWN(ip->i_mount)) {
991                                 xfs_fs_cmn_err(CE_ALERT, ip->i_mount,
992                                 "page discard failed delalloc mapping lookup.");
993                         }
994                         break;
995                 }
996                 if (!nimaps) {
997                         /* nothing there */
998                         goto next_buffer;
999                 }
1000                 if (imap.br_startblock != DELAYSTARTBLOCK) {
1001                         /* been converted, ignore */
1002                         goto next_buffer;
1003                 }
1004                 WARN_ON(imap.br_blockcount == 0);
1005
1006                 /*
1007                  * Note: while we initialise the firstblock/flist pair, they
1008                  * should never be used because blocks should never be
1009                  * allocated or freed for a delalloc extent and hence we need
1010                  * don't cancel or finish them after the xfs_bunmapi() call.
1011                  */
1012                 xfs_bmap_init(&flist, &firstblock);
1013                 error = xfs_bunmapi(NULL, ip, offset_fsb, 1, 0, 1, &firstblock,
1014                                         &flist, NULL, &done);
1015
1016                 ASSERT(!flist.xbf_count && !flist.xbf_first);
1017                 if (error) {
1018                         /* something screwed, just bail */
1019                         if (!XFS_FORCED_SHUTDOWN(ip->i_mount)) {
1020                                 xfs_fs_cmn_err(CE_ALERT, ip->i_mount,
1021                         "page discard unable to remove delalloc mapping.");
1022                         }
1023                         break;
1024                 }
1025 next_buffer:
1026                 offset += len;
1027
1028         } while ((bh = bh->b_this_page) != head);
1029
1030         xfs_iunlock(ip, XFS_ILOCK_EXCL);
1031 out_invalidate:
1032         xfs_vm_invalidatepage(page, 0);
1033         return;
1034 }
1035
1036 /*
1037  * Calling this without startio set means we are being asked to make a dirty
1038  * page ready for freeing it's buffers.  When called with startio set then
1039  * we are coming from writepage.
1040  *
1041  * When called with startio set it is important that we write the WHOLE
1042  * page if possible.
1043  * The bh->b_state's cannot know if any of the blocks or which block for
1044  * that matter are dirty due to mmap writes, and therefore bh uptodate is
1045  * only valid if the page itself isn't completely uptodate.  Some layers
1046  * may clear the page dirty flag prior to calling write page, under the
1047  * assumption the entire page will be written out; by not writing out the
1048  * whole page the page can be reused before all valid dirty data is
1049  * written out.  Note: in the case of a page that has been dirty'd by
1050  * mapwrite and but partially setup by block_prepare_write the
1051  * bh->b_states's will not agree and only ones setup by BPW/BCW will have
1052  * valid state, thus the whole page must be written out thing.
1053  */
1054
1055 STATIC int
1056 xfs_page_state_convert(
1057         struct inode    *inode,
1058         struct page     *page,
1059         struct writeback_control *wbc,
1060         int             startio,
1061         int             unmapped) /* also implies page uptodate */
1062 {
1063         struct buffer_head      *bh, *head;
1064         struct xfs_bmbt_irec    imap;
1065         xfs_ioend_t             *ioend = NULL, *iohead = NULL;
1066         loff_t                  offset;
1067         unsigned long           p_offset = 0;
1068         unsigned int            type;
1069         __uint64_t              end_offset;
1070         pgoff_t                 end_index, last_index, tlast;
1071         ssize_t                 size, len;
1072         int                     flags, err, iomap_valid = 0, uptodate = 1;
1073         int                     page_dirty, count = 0;
1074         int                     trylock = 0;
1075         int                     all_bh = unmapped;
1076
1077         if (startio) {
1078                 if (wbc->sync_mode == WB_SYNC_NONE && wbc->nonblocking)
1079                         trylock |= BMAPI_TRYLOCK;
1080         }
1081
1082         /* Is this page beyond the end of the file? */
1083         offset = i_size_read(inode);
1084         end_index = offset >> PAGE_CACHE_SHIFT;
1085         last_index = (offset - 1) >> PAGE_CACHE_SHIFT;
1086         if (page->index >= end_index) {
1087                 if ((page->index >= end_index + 1) ||
1088                     !(i_size_read(inode) & (PAGE_CACHE_SIZE - 1))) {
1089                         if (startio)
1090                                 unlock_page(page);
1091                         return 0;
1092                 }
1093         }
1094
1095         /*
1096          * page_dirty is initially a count of buffers on the page before
1097          * EOF and is decremented as we move each into a cleanable state.
1098          *
1099          * Derivation:
1100          *
1101          * End offset is the highest offset that this page should represent.
1102          * If we are on the last page, (end_offset & (PAGE_CACHE_SIZE - 1))
1103          * will evaluate non-zero and be less than PAGE_CACHE_SIZE and
1104          * hence give us the correct page_dirty count. On any other page,
1105          * it will be zero and in that case we need page_dirty to be the
1106          * count of buffers on the page.
1107          */
1108         end_offset = min_t(unsigned long long,
1109                         (xfs_off_t)(page->index + 1) << PAGE_CACHE_SHIFT, offset);
1110         len = 1 << inode->i_blkbits;
1111         p_offset = min_t(unsigned long, end_offset & (PAGE_CACHE_SIZE - 1),
1112                                         PAGE_CACHE_SIZE);
1113         p_offset = p_offset ? roundup(p_offset, len) : PAGE_CACHE_SIZE;
1114         page_dirty = p_offset / len;
1115
1116         bh = head = page_buffers(page);
1117         offset = page_offset(page);
1118         flags = BMAPI_READ;
1119         type = IO_NEW;
1120
1121         /* TODO: cleanup count and page_dirty */
1122
1123         do {
1124                 if (offset >= end_offset)
1125                         break;
1126                 if (!buffer_uptodate(bh))
1127                         uptodate = 0;
1128                 if (!(PageUptodate(page) || buffer_uptodate(bh)) && !startio) {
1129                         /*
1130                          * the iomap is actually still valid, but the ioend
1131                          * isn't.  shouldn't happen too often.
1132                          */
1133                         iomap_valid = 0;
1134                         continue;
1135                 }
1136
1137                 if (iomap_valid)
1138                         iomap_valid = xfs_iomap_valid(inode, &imap, offset);
1139
1140                 /*
1141                  * First case, map an unwritten extent and prepare for
1142                  * extent state conversion transaction on completion.
1143                  *
1144                  * Second case, allocate space for a delalloc buffer.
1145                  * We can return EAGAIN here in the release page case.
1146                  *
1147                  * Third case, an unmapped buffer was found, and we are
1148                  * in a path where we need to write the whole page out.
1149                  */
1150                 if (buffer_unwritten(bh) || buffer_delay(bh) ||
1151                     ((buffer_uptodate(bh) || PageUptodate(page)) &&
1152                      !buffer_mapped(bh) && (unmapped || startio))) {
1153                         int new_ioend = 0;
1154
1155                         /*
1156                          * Make sure we don't use a read-only iomap
1157                          */
1158                         if (flags == BMAPI_READ)
1159                                 iomap_valid = 0;
1160
1161                         if (buffer_unwritten(bh)) {
1162                                 type = IO_UNWRITTEN;
1163                                 flags = BMAPI_WRITE | BMAPI_IGNSTATE;
1164                         } else if (buffer_delay(bh)) {
1165                                 type = IO_DELAY;
1166                                 flags = BMAPI_ALLOCATE | trylock;
1167                         } else {
1168                                 type = IO_NEW;
1169                                 flags = BMAPI_WRITE | BMAPI_MMAP;
1170                         }
1171
1172                         if (!iomap_valid) {
1173                                 /*
1174                                  * if we didn't have a valid mapping then we
1175                                  * need to ensure that we put the new mapping
1176                                  * in a new ioend structure. This needs to be
1177                                  * done to ensure that the ioends correctly
1178                                  * reflect the block mappings at io completion
1179                                  * for unwritten extent conversion.
1180                                  */
1181                                 new_ioend = 1;
1182                                 if (type == IO_NEW) {
1183                                         size = xfs_probe_cluster(inode,
1184                                                         page, bh, head, 0);
1185                                 } else {
1186                                         size = len;
1187                                 }
1188
1189                                 err = xfs_map_blocks(inode, offset, size,
1190                                                 &imap, flags);
1191                                 if (err)
1192                                         goto error;
1193                                 iomap_valid = xfs_iomap_valid(inode, &imap, offset);
1194                         }
1195                         if (iomap_valid) {
1196                                 xfs_map_at_offset(inode, bh, &imap, offset);
1197                                 if (startio) {
1198                                         xfs_add_to_ioend(inode, bh, offset,
1199                                                         type, &ioend,
1200                                                         new_ioend);
1201                                 } else {
1202                                         set_buffer_dirty(bh);
1203                                         unlock_buffer(bh);
1204                                         mark_buffer_dirty(bh);
1205                                 }
1206                                 page_dirty--;
1207                                 count++;
1208                         }
1209                 } else if (buffer_uptodate(bh) && startio) {
1210                         /*
1211                          * we got here because the buffer is already mapped.
1212                          * That means it must already have extents allocated
1213                          * underneath it. Map the extent by reading it.
1214                          */
1215                         if (!iomap_valid || flags != BMAPI_READ) {
1216                                 flags = BMAPI_READ;
1217                                 size = xfs_probe_cluster(inode, page, bh,
1218                                                                 head, 1);
1219                                 err = xfs_map_blocks(inode, offset, size,
1220                                                 &imap, flags);
1221                                 if (err)
1222                                         goto error;
1223                                 iomap_valid = xfs_iomap_valid(inode, &imap, offset);
1224                         }
1225
1226                         /*
1227                          * We set the type to IO_NEW in case we are doing a
1228                          * small write at EOF that is extending the file but
1229                          * without needing an allocation. We need to update the
1230                          * file size on I/O completion in this case so it is
1231                          * the same case as having just allocated a new extent
1232                          * that we are writing into for the first time.
1233                          */
1234                         type = IO_NEW;
1235                         if (trylock_buffer(bh)) {
1236                                 ASSERT(buffer_mapped(bh));
1237                                 if (iomap_valid)
1238                                         all_bh = 1;
1239                                 xfs_add_to_ioend(inode, bh, offset, type,
1240                                                 &ioend, !iomap_valid);
1241                                 page_dirty--;
1242                                 count++;
1243                         } else {
1244                                 iomap_valid = 0;
1245                         }
1246                 } else if ((buffer_uptodate(bh) || PageUptodate(page)) &&
1247                            (unmapped || startio)) {
1248                         iomap_valid = 0;
1249                 }
1250
1251                 if (!iohead)
1252                         iohead = ioend;
1253
1254         } while (offset += len, ((bh = bh->b_this_page) != head));
1255
1256         if (uptodate && bh == head)
1257                 SetPageUptodate(page);
1258
1259         if (startio)
1260                 xfs_start_page_writeback(page, 1, count);
1261
1262         if (ioend && iomap_valid) {
1263                 struct xfs_mount        *m = XFS_I(inode)->i_mount;
1264                 xfs_off_t               iomap_offset = XFS_FSB_TO_B(m, imap.br_startoff);
1265                 xfs_off_t               iomap_bsize = XFS_FSB_TO_B(m, imap.br_blockcount);
1266
1267                 offset = (iomap_offset + iomap_bsize - 1) >>
1268                                         PAGE_CACHE_SHIFT;
1269                 tlast = min_t(pgoff_t, offset, last_index);
1270                 xfs_cluster_write(inode, page->index + 1, &imap, &ioend,
1271                                         wbc, startio, all_bh, tlast);
1272         }
1273
1274         if (iohead)
1275                 xfs_submit_ioend(wbc, iohead);
1276
1277         return page_dirty;
1278
1279 error:
1280         if (iohead)
1281                 xfs_cancel_ioend(iohead);
1282
1283         /*
1284          * If it's delalloc and we have nowhere to put it,
1285          * throw it away, unless the lower layers told
1286          * us to try again.
1287          */
1288         if (err != -EAGAIN) {
1289                 if (!unmapped)
1290                         xfs_aops_discard_page(page);
1291                 ClearPageUptodate(page);
1292         }
1293         return err;
1294 }
1295
1296 /*
1297  * writepage: Called from one of two places:
1298  *
1299  * 1. we are flushing a delalloc buffer head.
1300  *
1301  * 2. we are writing out a dirty page. Typically the page dirty
1302  *    state is cleared before we get here. In this case is it
1303  *    conceivable we have no buffer heads.
1304  *
1305  * For delalloc space on the page we need to allocate space and
1306  * flush it. For unmapped buffer heads on the page we should
1307  * allocate space if the page is uptodate. For any other dirty
1308  * buffer heads on the page we should flush them.
1309  *
1310  * If we detect that a transaction would be required to flush
1311  * the page, we have to check the process flags first, if we
1312  * are already in a transaction or disk I/O during allocations
1313  * is off, we need to fail the writepage and redirty the page.
1314  */
1315
1316 STATIC int
1317 xfs_vm_writepage(
1318         struct page             *page,
1319         struct writeback_control *wbc)
1320 {
1321         int                     error;
1322         int                     need_trans;
1323         int                     delalloc, unmapped, unwritten;
1324         struct inode            *inode = page->mapping->host;
1325
1326         trace_xfs_writepage(inode, page, 0);
1327
1328         /*
1329          * We need a transaction if:
1330          *  1. There are delalloc buffers on the page
1331          *  2. The page is uptodate and we have unmapped buffers
1332          *  3. The page is uptodate and we have no buffers
1333          *  4. There are unwritten buffers on the page
1334          */
1335
1336         if (!page_has_buffers(page)) {
1337                 unmapped = 1;
1338                 need_trans = 1;
1339         } else {
1340                 xfs_count_page_state(page, &delalloc, &unmapped, &unwritten);
1341                 if (!PageUptodate(page))
1342                         unmapped = 0;
1343                 need_trans = delalloc + unmapped + unwritten;
1344         }
1345
1346         /*
1347          * If we need a transaction and the process flags say
1348          * we are already in a transaction, or no IO is allowed
1349          * then mark the page dirty again and leave the page
1350          * as is.
1351          */
1352         if (current_test_flags(PF_FSTRANS) && need_trans)
1353                 goto out_fail;
1354
1355         /*
1356          * Delay hooking up buffer heads until we have
1357          * made our go/no-go decision.
1358          */
1359         if (!page_has_buffers(page))
1360                 create_empty_buffers(page, 1 << inode->i_blkbits, 0);
1361
1362
1363         /*
1364          *  VM calculation for nr_to_write seems off.  Bump it way
1365          *  up, this gets simple streaming writes zippy again.
1366          *  To be reviewed again after Jens' writeback changes.
1367          */
1368         wbc->nr_to_write *= 4;
1369
1370         /*
1371          * Convert delayed allocate, unwritten or unmapped space
1372          * to real space and flush out to disk.
1373          */
1374         error = xfs_page_state_convert(inode, page, wbc, 1, unmapped);
1375         if (error == -EAGAIN)
1376                 goto out_fail;
1377         if (unlikely(error < 0))
1378                 goto out_unlock;
1379
1380         return 0;
1381
1382 out_fail:
1383         redirty_page_for_writepage(wbc, page);
1384         unlock_page(page);
1385         return 0;
1386 out_unlock:
1387         unlock_page(page);
1388         return error;
1389 }
1390
1391 STATIC int
1392 xfs_vm_writepages(
1393         struct address_space    *mapping,
1394         struct writeback_control *wbc)
1395 {
1396         xfs_iflags_clear(XFS_I(mapping->host), XFS_ITRUNCATED);
1397         return generic_writepages(mapping, wbc);
1398 }
1399
1400 /*
1401  * Called to move a page into cleanable state - and from there
1402  * to be released. Possibly the page is already clean. We always
1403  * have buffer heads in this call.
1404  *
1405  * Returns 0 if the page is ok to release, 1 otherwise.
1406  *
1407  * Possible scenarios are:
1408  *
1409  * 1. We are being called to release a page which has been written
1410  *    to via regular I/O. buffer heads will be dirty and possibly
1411  *    delalloc. If no delalloc buffer heads in this case then we
1412  *    can just return zero.
1413  *
1414  * 2. We are called to release a page which has been written via
1415  *    mmap, all we need to do is ensure there is no delalloc
1416  *    state in the buffer heads, if not we can let the caller
1417  *    free them and we should come back later via writepage.
1418  */
1419 STATIC int
1420 xfs_vm_releasepage(
1421         struct page             *page,
1422         gfp_t                   gfp_mask)
1423 {
1424         struct inode            *inode = page->mapping->host;
1425         int                     dirty, delalloc, unmapped, unwritten;
1426         struct writeback_control wbc = {
1427                 .sync_mode = WB_SYNC_ALL,
1428                 .nr_to_write = 1,
1429         };
1430
1431         trace_xfs_releasepage(inode, page, 0);
1432
1433         if (!page_has_buffers(page))
1434                 return 0;
1435
1436         xfs_count_page_state(page, &delalloc, &unmapped, &unwritten);
1437         if (!delalloc && !unwritten)
1438                 goto free_buffers;
1439
1440         if (!(gfp_mask & __GFP_FS))
1441                 return 0;
1442
1443         /* If we are already inside a transaction or the thread cannot
1444          * do I/O, we cannot release this page.
1445          */
1446         if (current_test_flags(PF_FSTRANS))
1447                 return 0;
1448
1449         /*
1450          * Convert delalloc space to real space, do not flush the
1451          * data out to disk, that will be done by the caller.
1452          * Never need to allocate space here - we will always
1453          * come back to writepage in that case.
1454          */
1455         dirty = xfs_page_state_convert(inode, page, &wbc, 0, 0);
1456         if (dirty == 0 && !unwritten)
1457                 goto free_buffers;
1458         return 0;
1459
1460 free_buffers:
1461         return try_to_free_buffers(page);
1462 }
1463
1464 STATIC int
1465 __xfs_get_blocks(
1466         struct inode            *inode,
1467         sector_t                iblock,
1468         struct buffer_head      *bh_result,
1469         int                     create,
1470         int                     direct,
1471         bmapi_flags_t           flags)
1472 {
1473         struct xfs_bmbt_irec    imap;
1474         xfs_off_t               offset;
1475         ssize_t                 size;
1476         int                     nimap = 1;
1477         int                     new = 0;
1478         int                     error;
1479
1480         offset = (xfs_off_t)iblock << inode->i_blkbits;
1481         ASSERT(bh_result->b_size >= (1 << inode->i_blkbits));
1482         size = bh_result->b_size;
1483
1484         if (!create && direct && offset >= i_size_read(inode))
1485                 return 0;
1486
1487         error = xfs_iomap(XFS_I(inode), offset, size,
1488                              create ? flags : BMAPI_READ, &imap, &nimap, &new);
1489         if (error)
1490                 return -error;
1491         if (nimap == 0)
1492                 return 0;
1493
1494         if (imap.br_startblock != HOLESTARTBLOCK &&
1495             imap.br_startblock != DELAYSTARTBLOCK) {
1496                 /*
1497                  * For unwritten extents do not report a disk address on
1498                  * the read case (treat as if we're reading into a hole).
1499                  */
1500                 if (create || !ISUNWRITTEN(&imap))
1501                         xfs_map_buffer(inode, bh_result, &imap, offset);
1502                 if (create && ISUNWRITTEN(&imap)) {
1503                         if (direct)
1504                                 bh_result->b_private = inode;
1505                         set_buffer_unwritten(bh_result);
1506                 }
1507         }
1508
1509         /*
1510          * If this is a realtime file, data may be on a different device.
1511          * to that pointed to from the buffer_head b_bdev currently.
1512          */
1513         bh_result->b_bdev = xfs_find_bdev_for_inode(inode);
1514
1515         /*
1516          * If we previously allocated a block out beyond eof and we are now
1517          * coming back to use it then we will need to flag it as new even if it
1518          * has a disk address.
1519          *
1520          * With sub-block writes into unwritten extents we also need to mark
1521          * the buffer as new so that the unwritten parts of the buffer gets
1522          * correctly zeroed.
1523          */
1524         if (create &&
1525             ((!buffer_mapped(bh_result) && !buffer_uptodate(bh_result)) ||
1526              (offset >= i_size_read(inode)) ||
1527              (new || ISUNWRITTEN(&imap))))
1528                 set_buffer_new(bh_result);
1529
1530         if (imap.br_startblock == DELAYSTARTBLOCK) {
1531                 BUG_ON(direct);
1532                 if (create) {
1533                         set_buffer_uptodate(bh_result);
1534                         set_buffer_mapped(bh_result);
1535                         set_buffer_delay(bh_result);
1536                 }
1537         }
1538
1539         if (direct || size > (1 << inode->i_blkbits)) {
1540                 struct xfs_mount        *mp = XFS_I(inode)->i_mount;
1541                 xfs_off_t               iomap_offset = XFS_FSB_TO_B(mp, imap.br_startoff);
1542                 xfs_off_t               iomap_delta = offset - iomap_offset;
1543                 xfs_off_t               iomap_bsize = XFS_FSB_TO_B(mp, imap.br_blockcount);
1544
1545                 ASSERT(iomap_bsize - iomap_delta > 0);
1546                 offset = min_t(xfs_off_t,
1547                                 iomap_bsize - iomap_delta, size);
1548                 bh_result->b_size = (ssize_t)min_t(xfs_off_t, LONG_MAX, offset);
1549         }
1550
1551         return 0;
1552 }
1553
1554 int
1555 xfs_get_blocks(
1556         struct inode            *inode,
1557         sector_t                iblock,
1558         struct buffer_head      *bh_result,
1559         int                     create)
1560 {
1561         return __xfs_get_blocks(inode, iblock,
1562                                 bh_result, create, 0, BMAPI_WRITE);
1563 }
1564
1565 STATIC int
1566 xfs_get_blocks_direct(
1567         struct inode            *inode,
1568         sector_t                iblock,
1569         struct buffer_head      *bh_result,
1570         int                     create)
1571 {
1572         return __xfs_get_blocks(inode, iblock,
1573                                 bh_result, create, 1, BMAPI_WRITE|BMAPI_DIRECT);
1574 }
1575
1576 STATIC void
1577 xfs_end_io_direct(
1578         struct kiocb    *iocb,
1579         loff_t          offset,
1580         ssize_t         size,
1581         void            *private)
1582 {
1583         xfs_ioend_t     *ioend = iocb->private;
1584
1585         /*
1586          * Non-NULL private data means we need to issue a transaction to
1587          * convert a range from unwritten to written extents.  This needs
1588          * to happen from process context but aio+dio I/O completion
1589          * happens from irq context so we need to defer it to a workqueue.
1590          * This is not necessary for synchronous direct I/O, but we do
1591          * it anyway to keep the code uniform and simpler.
1592          *
1593          * Well, if only it were that simple. Because synchronous direct I/O
1594          * requires extent conversion to occur *before* we return to userspace,
1595          * we have to wait for extent conversion to complete. Look at the
1596          * iocb that has been passed to us to determine if this is AIO or
1597          * not. If it is synchronous, tell xfs_finish_ioend() to kick the
1598          * workqueue and wait for it to complete.
1599          *
1600          * The core direct I/O code might be changed to always call the
1601          * completion handler in the future, in which case all this can
1602          * go away.
1603          */
1604         ioend->io_offset = offset;
1605         ioend->io_size = size;
1606         if (ioend->io_type == IO_READ) {
1607                 xfs_finish_ioend(ioend, 0);
1608         } else if (private && size > 0) {
1609                 xfs_finish_ioend(ioend, is_sync_kiocb(iocb));
1610         } else {
1611                 /*
1612                  * A direct I/O write ioend starts it's life in unwritten
1613                  * state in case they map an unwritten extent.  This write
1614                  * didn't map an unwritten extent so switch it's completion
1615                  * handler.
1616                  */
1617                 ioend->io_type = IO_NEW;
1618                 xfs_finish_ioend(ioend, 0);
1619         }
1620
1621         /*
1622          * blockdev_direct_IO can return an error even after the I/O
1623          * completion handler was called.  Thus we need to protect
1624          * against double-freeing.
1625          */
1626         iocb->private = NULL;
1627 }
1628
1629 STATIC ssize_t
1630 xfs_vm_direct_IO(
1631         int                     rw,
1632         struct kiocb            *iocb,
1633         const struct iovec      *iov,
1634         loff_t                  offset,
1635         unsigned long           nr_segs)
1636 {
1637         struct file     *file = iocb->ki_filp;
1638         struct inode    *inode = file->f_mapping->host;
1639         struct block_device *bdev;
1640         ssize_t         ret;
1641
1642         bdev = xfs_find_bdev_for_inode(inode);
1643
1644         iocb->private = xfs_alloc_ioend(inode, rw == WRITE ?
1645                                         IO_UNWRITTEN : IO_READ);
1646
1647         ret = blockdev_direct_IO_no_locking(rw, iocb, inode, bdev, iov,
1648                                             offset, nr_segs,
1649                                             xfs_get_blocks_direct,
1650                                             xfs_end_io_direct);
1651
1652         if (unlikely(ret != -EIOCBQUEUED && iocb->private))
1653                 xfs_destroy_ioend(iocb->private);
1654         return ret;
1655 }
1656
1657 STATIC int
1658 xfs_vm_write_begin(
1659         struct file             *file,
1660         struct address_space    *mapping,
1661         loff_t                  pos,
1662         unsigned                len,
1663         unsigned                flags,
1664         struct page             **pagep,
1665         void                    **fsdata)
1666 {
1667         *pagep = NULL;
1668         return block_write_begin(file, mapping, pos, len, flags, pagep, fsdata,
1669                                                                 xfs_get_blocks);
1670 }
1671
1672 STATIC sector_t
1673 xfs_vm_bmap(
1674         struct address_space    *mapping,
1675         sector_t                block)
1676 {
1677         struct inode            *inode = (struct inode *)mapping->host;
1678         struct xfs_inode        *ip = XFS_I(inode);
1679
1680         xfs_itrace_entry(XFS_I(inode));
1681         xfs_ilock(ip, XFS_IOLOCK_SHARED);
1682         xfs_flush_pages(ip, (xfs_off_t)0, -1, 0, FI_REMAPF);
1683         xfs_iunlock(ip, XFS_IOLOCK_SHARED);
1684         return generic_block_bmap(mapping, block, xfs_get_blocks);
1685 }
1686
1687 STATIC int
1688 xfs_vm_readpage(
1689         struct file             *unused,
1690         struct page             *page)
1691 {
1692         return mpage_readpage(page, xfs_get_blocks);
1693 }
1694
1695 STATIC int
1696 xfs_vm_readpages(
1697         struct file             *unused,
1698         struct address_space    *mapping,
1699         struct list_head        *pages,
1700         unsigned                nr_pages)
1701 {
1702         return mpage_readpages(mapping, pages, nr_pages, xfs_get_blocks);
1703 }
1704
1705 const struct address_space_operations xfs_address_space_operations = {
1706         .readpage               = xfs_vm_readpage,
1707         .readpages              = xfs_vm_readpages,
1708         .writepage              = xfs_vm_writepage,
1709         .writepages             = xfs_vm_writepages,
1710         .sync_page              = block_sync_page,
1711         .releasepage            = xfs_vm_releasepage,
1712         .invalidatepage         = xfs_vm_invalidatepage,
1713         .write_begin            = xfs_vm_write_begin,
1714         .write_end              = generic_write_end,
1715         .bmap                   = xfs_vm_bmap,
1716         .direct_IO              = xfs_vm_direct_IO,
1717         .migratepage            = buffer_migrate_page,
1718         .is_partially_uptodate  = block_is_partially_uptodate,
1719         .error_remove_page      = generic_error_remove_page,
1720 };