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