f75c7c99cb630912dc596ef628a782c5fdec4fa4
[platform/kernel/linux-rpi.git] / fs / xfs / 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_shared.h"
20 #include "xfs_format.h"
21 #include "xfs_log_format.h"
22 #include "xfs_trans_resv.h"
23 #include "xfs_mount.h"
24 #include "xfs_inode.h"
25 #include "xfs_trans.h"
26 #include "xfs_inode_item.h"
27 #include "xfs_alloc.h"
28 #include "xfs_error.h"
29 #include "xfs_iomap.h"
30 #include "xfs_trace.h"
31 #include "xfs_bmap.h"
32 #include "xfs_bmap_util.h"
33 #include "xfs_bmap_btree.h"
34 #include <linux/gfp.h>
35 #include <linux/mpage.h>
36 #include <linux/pagevec.h>
37 #include <linux/writeback.h>
38
39 /*
40  * structure owned by writepages passed to individual writepage calls
41  */
42 struct xfs_writepage_ctx {
43         struct xfs_bmbt_irec    imap;
44         bool                    imap_valid;
45         unsigned int            io_type;
46         struct xfs_ioend        *iohead;
47         struct xfs_ioend        *ioend;
48         sector_t                last_block;
49 };
50
51 void
52 xfs_count_page_state(
53         struct page             *page,
54         int                     *delalloc,
55         int                     *unwritten)
56 {
57         struct buffer_head      *bh, *head;
58
59         *delalloc = *unwritten = 0;
60
61         bh = head = page_buffers(page);
62         do {
63                 if (buffer_unwritten(bh))
64                         (*unwritten) = 1;
65                 else if (buffer_delay(bh))
66                         (*delalloc) = 1;
67         } while ((bh = bh->b_this_page) != head);
68 }
69
70 STATIC struct block_device *
71 xfs_find_bdev_for_inode(
72         struct inode            *inode)
73 {
74         struct xfs_inode        *ip = XFS_I(inode);
75         struct xfs_mount        *mp = ip->i_mount;
76
77         if (XFS_IS_REALTIME_INODE(ip))
78                 return mp->m_rtdev_targp->bt_bdev;
79         else
80                 return mp->m_ddev_targp->bt_bdev;
81 }
82
83 /*
84  * We're now finished for good with this ioend structure.
85  * Update the page state via the associated buffer_heads,
86  * release holds on the inode and bio, and finally free
87  * up memory.  Do not use the ioend after this.
88  */
89 STATIC void
90 xfs_destroy_ioend(
91         xfs_ioend_t             *ioend)
92 {
93         struct buffer_head      *bh, *next;
94
95         for (bh = ioend->io_buffer_head; bh; bh = next) {
96                 next = bh->b_private;
97                 bh->b_end_io(bh, !ioend->io_error);
98         }
99
100         mempool_free(ioend, xfs_ioend_pool);
101 }
102
103 /*
104  * Fast and loose check if this write could update the on-disk inode size.
105  */
106 static inline bool xfs_ioend_is_append(struct xfs_ioend *ioend)
107 {
108         return ioend->io_offset + ioend->io_size >
109                 XFS_I(ioend->io_inode)->i_d.di_size;
110 }
111
112 STATIC int
113 xfs_setfilesize_trans_alloc(
114         struct xfs_ioend        *ioend)
115 {
116         struct xfs_mount        *mp = XFS_I(ioend->io_inode)->i_mount;
117         struct xfs_trans        *tp;
118         int                     error;
119
120         tp = xfs_trans_alloc(mp, XFS_TRANS_FSYNC_TS);
121
122         error = xfs_trans_reserve(tp, &M_RES(mp)->tr_fsyncts, 0, 0);
123         if (error) {
124                 xfs_trans_cancel(tp);
125                 return error;
126         }
127
128         ioend->io_append_trans = tp;
129
130         /*
131          * We may pass freeze protection with a transaction.  So tell lockdep
132          * we released it.
133          */
134         __sb_writers_release(ioend->io_inode->i_sb, SB_FREEZE_FS);
135         /*
136          * We hand off the transaction to the completion thread now, so
137          * clear the flag here.
138          */
139         current_restore_flags_nested(&tp->t_pflags, PF_FSTRANS);
140         return 0;
141 }
142
143 /*
144  * Update on-disk file size now that data has been written to disk.
145  */
146 STATIC int
147 xfs_setfilesize(
148         struct xfs_inode        *ip,
149         struct xfs_trans        *tp,
150         xfs_off_t               offset,
151         size_t                  size)
152 {
153         xfs_fsize_t             isize;
154
155         xfs_ilock(ip, XFS_ILOCK_EXCL);
156         isize = xfs_new_eof(ip, offset + size);
157         if (!isize) {
158                 xfs_iunlock(ip, XFS_ILOCK_EXCL);
159                 xfs_trans_cancel(tp);
160                 return 0;
161         }
162
163         trace_xfs_setfilesize(ip, offset, size);
164
165         ip->i_d.di_size = isize;
166         xfs_trans_ijoin(tp, ip, XFS_ILOCK_EXCL);
167         xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
168
169         return xfs_trans_commit(tp);
170 }
171
172 STATIC int
173 xfs_setfilesize_ioend(
174         struct xfs_ioend        *ioend)
175 {
176         struct xfs_inode        *ip = XFS_I(ioend->io_inode);
177         struct xfs_trans        *tp = ioend->io_append_trans;
178
179         /*
180          * The transaction may have been allocated in the I/O submission thread,
181          * thus we need to mark ourselves as being in a transaction manually.
182          * Similarly for freeze protection.
183          */
184         current_set_flags_nested(&tp->t_pflags, PF_FSTRANS);
185         __sb_writers_acquired(VFS_I(ip)->i_sb, SB_FREEZE_FS);
186
187         /* we abort the update if there was an IO error */
188         if (ioend->io_error) {
189                 xfs_trans_cancel(tp);
190                 return ioend->io_error;
191         }
192
193         return xfs_setfilesize(ip, tp, ioend->io_offset, ioend->io_size);
194 }
195
196 /*
197  * Schedule IO completion handling on the final put of an ioend.
198  *
199  * If there is no work to do we might as well call it a day and free the
200  * ioend right now.
201  */
202 STATIC void
203 xfs_finish_ioend(
204         struct xfs_ioend        *ioend)
205 {
206         if (atomic_dec_and_test(&ioend->io_remaining)) {
207                 struct xfs_mount        *mp = XFS_I(ioend->io_inode)->i_mount;
208
209                 if (ioend->io_type == XFS_IO_UNWRITTEN)
210                         queue_work(mp->m_unwritten_workqueue, &ioend->io_work);
211                 else if (ioend->io_append_trans)
212                         queue_work(mp->m_data_workqueue, &ioend->io_work);
213                 else
214                         xfs_destroy_ioend(ioend);
215         }
216 }
217
218 /*
219  * IO write completion.
220  */
221 STATIC void
222 xfs_end_io(
223         struct work_struct *work)
224 {
225         xfs_ioend_t     *ioend = container_of(work, xfs_ioend_t, io_work);
226         struct xfs_inode *ip = XFS_I(ioend->io_inode);
227         int             error = 0;
228
229         if (XFS_FORCED_SHUTDOWN(ip->i_mount)) {
230                 ioend->io_error = -EIO;
231                 goto done;
232         }
233
234         /*
235          * For unwritten extents we need to issue transactions to convert a
236          * range to normal written extens after the data I/O has finished.
237          * Detecting and handling completion IO errors is done individually
238          * for each case as different cleanup operations need to be performed
239          * on error.
240          */
241         if (ioend->io_type == XFS_IO_UNWRITTEN) {
242                 if (ioend->io_error)
243                         goto done;
244                 error = xfs_iomap_write_unwritten(ip, ioend->io_offset,
245                                                   ioend->io_size);
246         } else if (ioend->io_append_trans) {
247                 error = xfs_setfilesize_ioend(ioend);
248         } else {
249                 ASSERT(!xfs_ioend_is_append(ioend));
250         }
251
252 done:
253         if (error)
254                 ioend->io_error = error;
255         xfs_destroy_ioend(ioend);
256 }
257
258 /*
259  * Allocate and initialise an IO completion structure.
260  * We need to track unwritten extent write completion here initially.
261  * We'll need to extend this for updating the ondisk inode size later
262  * (vs. incore size).
263  */
264 STATIC xfs_ioend_t *
265 xfs_alloc_ioend(
266         struct inode            *inode,
267         unsigned int            type)
268 {
269         xfs_ioend_t             *ioend;
270
271         ioend = mempool_alloc(xfs_ioend_pool, GFP_NOFS);
272
273         /*
274          * Set the count to 1 initially, which will prevent an I/O
275          * completion callback from happening before we have started
276          * all the I/O from calling the completion routine too early.
277          */
278         atomic_set(&ioend->io_remaining, 1);
279         ioend->io_error = 0;
280         ioend->io_list = NULL;
281         ioend->io_type = type;
282         ioend->io_inode = inode;
283         ioend->io_buffer_head = NULL;
284         ioend->io_buffer_tail = NULL;
285         ioend->io_offset = 0;
286         ioend->io_size = 0;
287         ioend->io_append_trans = NULL;
288
289         INIT_WORK(&ioend->io_work, xfs_end_io);
290         return ioend;
291 }
292
293 STATIC int
294 xfs_map_blocks(
295         struct inode            *inode,
296         loff_t                  offset,
297         struct xfs_bmbt_irec    *imap,
298         int                     type)
299 {
300         struct xfs_inode        *ip = XFS_I(inode);
301         struct xfs_mount        *mp = ip->i_mount;
302         ssize_t                 count = 1 << inode->i_blkbits;
303         xfs_fileoff_t           offset_fsb, end_fsb;
304         int                     error = 0;
305         int                     bmapi_flags = XFS_BMAPI_ENTIRE;
306         int                     nimaps = 1;
307
308         if (XFS_FORCED_SHUTDOWN(mp))
309                 return -EIO;
310
311         if (type == XFS_IO_UNWRITTEN)
312                 bmapi_flags |= XFS_BMAPI_IGSTATE;
313
314         xfs_ilock(ip, XFS_ILOCK_SHARED);
315         ASSERT(ip->i_d.di_format != XFS_DINODE_FMT_BTREE ||
316                (ip->i_df.if_flags & XFS_IFEXTENTS));
317         ASSERT(offset <= mp->m_super->s_maxbytes);
318
319         if (offset + count > mp->m_super->s_maxbytes)
320                 count = mp->m_super->s_maxbytes - offset;
321         end_fsb = XFS_B_TO_FSB(mp, (xfs_ufsize_t)offset + count);
322         offset_fsb = XFS_B_TO_FSBT(mp, offset);
323         error = xfs_bmapi_read(ip, offset_fsb, end_fsb - offset_fsb,
324                                 imap, &nimaps, bmapi_flags);
325         xfs_iunlock(ip, XFS_ILOCK_SHARED);
326
327         if (error)
328                 return error;
329
330         if (type == XFS_IO_DELALLOC &&
331             (!nimaps || isnullstartblock(imap->br_startblock))) {
332                 error = xfs_iomap_write_allocate(ip, offset, imap);
333                 if (!error)
334                         trace_xfs_map_blocks_alloc(ip, offset, count, type, imap);
335                 return error;
336         }
337
338 #ifdef DEBUG
339         if (type == XFS_IO_UNWRITTEN) {
340                 ASSERT(nimaps);
341                 ASSERT(imap->br_startblock != HOLESTARTBLOCK);
342                 ASSERT(imap->br_startblock != DELAYSTARTBLOCK);
343         }
344 #endif
345         if (nimaps)
346                 trace_xfs_map_blocks_found(ip, offset, count, type, imap);
347         return 0;
348 }
349
350 STATIC bool
351 xfs_imap_valid(
352         struct inode            *inode,
353         struct xfs_bmbt_irec    *imap,
354         xfs_off_t               offset)
355 {
356         offset >>= inode->i_blkbits;
357
358         return offset >= imap->br_startoff &&
359                 offset < imap->br_startoff + imap->br_blockcount;
360 }
361
362 /*
363  * BIO completion handler for buffered IO.
364  */
365 STATIC void
366 xfs_end_bio(
367         struct bio              *bio)
368 {
369         xfs_ioend_t             *ioend = bio->bi_private;
370
371         if (!ioend->io_error)
372                 ioend->io_error = bio->bi_error;
373
374         /* Toss bio and pass work off to an xfsdatad thread */
375         bio->bi_private = NULL;
376         bio->bi_end_io = NULL;
377         bio_put(bio);
378
379         xfs_finish_ioend(ioend);
380 }
381
382 STATIC void
383 xfs_submit_ioend_bio(
384         struct writeback_control *wbc,
385         xfs_ioend_t             *ioend,
386         struct bio              *bio)
387 {
388         atomic_inc(&ioend->io_remaining);
389         bio->bi_private = ioend;
390         bio->bi_end_io = xfs_end_bio;
391         submit_bio(wbc->sync_mode == WB_SYNC_ALL ? WRITE_SYNC : WRITE, bio);
392 }
393
394 STATIC struct bio *
395 xfs_alloc_ioend_bio(
396         struct buffer_head      *bh)
397 {
398         struct bio              *bio = bio_alloc(GFP_NOIO, BIO_MAX_PAGES);
399
400         ASSERT(bio->bi_private == NULL);
401         bio->bi_iter.bi_sector = bh->b_blocknr * (bh->b_size >> 9);
402         bio->bi_bdev = bh->b_bdev;
403         return bio;
404 }
405
406 STATIC void
407 xfs_start_buffer_writeback(
408         struct buffer_head      *bh)
409 {
410         ASSERT(buffer_mapped(bh));
411         ASSERT(buffer_locked(bh));
412         ASSERT(!buffer_delay(bh));
413         ASSERT(!buffer_unwritten(bh));
414
415         mark_buffer_async_write(bh);
416         set_buffer_uptodate(bh);
417         clear_buffer_dirty(bh);
418 }
419
420 STATIC void
421 xfs_start_page_writeback(
422         struct page             *page,
423         int                     clear_dirty,
424         int                     buffers)
425 {
426         ASSERT(PageLocked(page));
427         ASSERT(!PageWriteback(page));
428
429         /*
430          * if the page was not fully cleaned, we need to ensure that the higher
431          * layers come back to it correctly. That means we need to keep the page
432          * dirty, and for WB_SYNC_ALL writeback we need to ensure the
433          * PAGECACHE_TAG_TOWRITE index mark is not removed so another attempt to
434          * write this page in this writeback sweep will be made.
435          */
436         if (clear_dirty) {
437                 clear_page_dirty_for_io(page);
438                 set_page_writeback(page);
439         } else
440                 set_page_writeback_keepwrite(page);
441
442         unlock_page(page);
443
444         /* If no buffers on the page are to be written, finish it here */
445         if (!buffers)
446                 end_page_writeback(page);
447 }
448
449 static inline int xfs_bio_add_buffer(struct bio *bio, struct buffer_head *bh)
450 {
451         return bio_add_page(bio, bh->b_page, bh->b_size, bh_offset(bh));
452 }
453
454 /*
455  * Submit all of the bios for all of the ioends we have saved up, covering the
456  * initial writepage page and also any probed pages.
457  *
458  * Because we may have multiple ioends spanning a page, we need to start
459  * writeback on all the buffers before we submit them for I/O. If we mark the
460  * buffers as we got, then we can end up with a page that only has buffers
461  * marked async write and I/O complete on can occur before we mark the other
462  * buffers async write.
463  *
464  * The end result of this is that we trip a bug in end_page_writeback() because
465  * we call it twice for the one page as the code in end_buffer_async_write()
466  * assumes that all buffers on the page are started at the same time.
467  *
468  * The fix is two passes across the ioend list - one to start writeback on the
469  * buffer_heads, and then submit them for I/O on the second pass.
470  *
471  * If @fail is non-zero, it means that we have a situation where some part of
472  * the submission process has failed after we have marked paged for writeback
473  * and unlocked them. In this situation, we need to fail the ioend chain rather
474  * than submit it to IO. This typically only happens on a filesystem shutdown.
475  */
476 STATIC void
477 xfs_submit_ioend(
478         struct writeback_control *wbc,
479         xfs_ioend_t             *ioend,
480         int                     fail)
481 {
482         xfs_ioend_t             *head = ioend;
483         xfs_ioend_t             *next;
484         struct buffer_head      *bh;
485         struct bio              *bio;
486         sector_t                lastblock = 0;
487
488         /* Pass 1 - start writeback */
489         do {
490                 next = ioend->io_list;
491                 for (bh = ioend->io_buffer_head; bh; bh = bh->b_private)
492                         xfs_start_buffer_writeback(bh);
493         } while ((ioend = next) != NULL);
494
495         /* Pass 2 - submit I/O */
496         ioend = head;
497         do {
498                 next = ioend->io_list;
499                 bio = NULL;
500
501                 /*
502                  * If we are failing the IO now, just mark the ioend with an
503                  * error and finish it. This will run IO completion immediately
504                  * as there is only one reference to the ioend at this point in
505                  * time.
506                  */
507                 if (fail) {
508                         ioend->io_error = fail;
509                         xfs_finish_ioend(ioend);
510                         continue;
511                 }
512
513                 for (bh = ioend->io_buffer_head; bh; bh = bh->b_private) {
514
515                         if (!bio) {
516  retry:
517                                 bio = xfs_alloc_ioend_bio(bh);
518                         } else if (bh->b_blocknr != lastblock + 1) {
519                                 xfs_submit_ioend_bio(wbc, ioend, bio);
520                                 goto retry;
521                         }
522
523                         if (xfs_bio_add_buffer(bio, bh) != bh->b_size) {
524                                 xfs_submit_ioend_bio(wbc, ioend, bio);
525                                 goto retry;
526                         }
527
528                         lastblock = bh->b_blocknr;
529                 }
530                 if (bio)
531                         xfs_submit_ioend_bio(wbc, ioend, bio);
532                 xfs_finish_ioend(ioend);
533         } while ((ioend = next) != NULL);
534 }
535
536 /*
537  * Test to see if we've been building up a completion structure for
538  * earlier buffers -- if so, we try to append to this ioend if we
539  * can, otherwise we finish off any current ioend and start another.
540  * Return true if we've finished the given ioend.
541  */
542 STATIC void
543 xfs_add_to_ioend(
544         struct inode            *inode,
545         struct buffer_head      *bh,
546         xfs_off_t               offset,
547         struct xfs_writepage_ctx *wpc)
548 {
549         if (!wpc->ioend || wpc->io_type != wpc->ioend->io_type ||
550             bh->b_blocknr != wpc->last_block + 1) {
551                 struct xfs_ioend        *new;
552
553                 new = xfs_alloc_ioend(inode, wpc->io_type);
554                 new->io_offset = offset;
555                 new->io_buffer_head = bh;
556                 new->io_buffer_tail = bh;
557                 if (wpc->ioend)
558                         wpc->ioend->io_list = new;
559                 wpc->ioend = new;
560         } else {
561                 wpc->ioend->io_buffer_tail->b_private = bh;
562                 wpc->ioend->io_buffer_tail = bh;
563         }
564
565         bh->b_private = NULL;
566         wpc->ioend->io_size += bh->b_size;
567         wpc->last_block = bh->b_blocknr;
568 }
569
570 STATIC void
571 xfs_map_buffer(
572         struct inode            *inode,
573         struct buffer_head      *bh,
574         struct xfs_bmbt_irec    *imap,
575         xfs_off_t               offset)
576 {
577         sector_t                bn;
578         struct xfs_mount        *m = XFS_I(inode)->i_mount;
579         xfs_off_t               iomap_offset = XFS_FSB_TO_B(m, imap->br_startoff);
580         xfs_daddr_t             iomap_bn = xfs_fsb_to_db(XFS_I(inode), imap->br_startblock);
581
582         ASSERT(imap->br_startblock != HOLESTARTBLOCK);
583         ASSERT(imap->br_startblock != DELAYSTARTBLOCK);
584
585         bn = (iomap_bn >> (inode->i_blkbits - BBSHIFT)) +
586               ((offset - iomap_offset) >> inode->i_blkbits);
587
588         ASSERT(bn || XFS_IS_REALTIME_INODE(XFS_I(inode)));
589
590         bh->b_blocknr = bn;
591         set_buffer_mapped(bh);
592 }
593
594 STATIC void
595 xfs_map_at_offset(
596         struct inode            *inode,
597         struct buffer_head      *bh,
598         struct xfs_bmbt_irec    *imap,
599         xfs_off_t               offset)
600 {
601         ASSERT(imap->br_startblock != HOLESTARTBLOCK);
602         ASSERT(imap->br_startblock != DELAYSTARTBLOCK);
603
604         xfs_map_buffer(inode, bh, imap, offset);
605         set_buffer_mapped(bh);
606         clear_buffer_delay(bh);
607         clear_buffer_unwritten(bh);
608 }
609
610 /*
611  * Test if a given page contains at least one buffer of a given @type.
612  * If @check_all_buffers is true, then we walk all the buffers in the page to
613  * try to find one of the type passed in. If it is not set, then the caller only
614  * needs to check the first buffer on the page for a match.
615  */
616 STATIC bool
617 xfs_check_page_type(
618         struct page             *page,
619         unsigned int            type,
620         bool                    check_all_buffers)
621 {
622         struct buffer_head      *bh;
623         struct buffer_head      *head;
624
625         if (PageWriteback(page))
626                 return false;
627         if (!page->mapping)
628                 return false;
629         if (!page_has_buffers(page))
630                 return false;
631
632         bh = head = page_buffers(page);
633         do {
634                 if (buffer_unwritten(bh)) {
635                         if (type == XFS_IO_UNWRITTEN)
636                                 return true;
637                 } else if (buffer_delay(bh)) {
638                         if (type == XFS_IO_DELALLOC)
639                                 return true;
640                 } else if (buffer_dirty(bh) && buffer_mapped(bh)) {
641                         if (type == XFS_IO_OVERWRITE)
642                                 return true;
643                 }
644
645                 /* If we are only checking the first buffer, we are done now. */
646                 if (!check_all_buffers)
647                         break;
648         } while ((bh = bh->b_this_page) != head);
649
650         return false;
651 }
652
653 STATIC void
654 xfs_vm_invalidatepage(
655         struct page             *page,
656         unsigned int            offset,
657         unsigned int            length)
658 {
659         trace_xfs_invalidatepage(page->mapping->host, page, offset,
660                                  length);
661         block_invalidatepage(page, offset, length);
662 }
663
664 /*
665  * If the page has delalloc buffers on it, we need to punch them out before we
666  * invalidate the page. If we don't, we leave a stale delalloc mapping on the
667  * inode that can trip a BUG() in xfs_get_blocks() later on if a direct IO read
668  * is done on that same region - the delalloc extent is returned when none is
669  * supposed to be there.
670  *
671  * We prevent this by truncating away the delalloc regions on the page before
672  * invalidating it. Because they are delalloc, we can do this without needing a
673  * transaction. Indeed - if we get ENOSPC errors, we have to be able to do this
674  * truncation without a transaction as there is no space left for block
675  * reservation (typically why we see a ENOSPC in writeback).
676  *
677  * This is not a performance critical path, so for now just do the punching a
678  * buffer head at a time.
679  */
680 STATIC void
681 xfs_aops_discard_page(
682         struct page             *page)
683 {
684         struct inode            *inode = page->mapping->host;
685         struct xfs_inode        *ip = XFS_I(inode);
686         struct buffer_head      *bh, *head;
687         loff_t                  offset = page_offset(page);
688
689         if (!xfs_check_page_type(page, XFS_IO_DELALLOC, true))
690                 goto out_invalidate;
691
692         if (XFS_FORCED_SHUTDOWN(ip->i_mount))
693                 goto out_invalidate;
694
695         xfs_alert(ip->i_mount,
696                 "page discard on page %p, inode 0x%llx, offset %llu.",
697                         page, ip->i_ino, offset);
698
699         xfs_ilock(ip, XFS_ILOCK_EXCL);
700         bh = head = page_buffers(page);
701         do {
702                 int             error;
703                 xfs_fileoff_t   start_fsb;
704
705                 if (!buffer_delay(bh))
706                         goto next_buffer;
707
708                 start_fsb = XFS_B_TO_FSBT(ip->i_mount, offset);
709                 error = xfs_bmap_punch_delalloc_range(ip, start_fsb, 1);
710                 if (error) {
711                         /* something screwed, just bail */
712                         if (!XFS_FORCED_SHUTDOWN(ip->i_mount)) {
713                                 xfs_alert(ip->i_mount,
714                         "page discard unable to remove delalloc mapping.");
715                         }
716                         break;
717                 }
718 next_buffer:
719                 offset += 1 << inode->i_blkbits;
720
721         } while ((bh = bh->b_this_page) != head);
722
723         xfs_iunlock(ip, XFS_ILOCK_EXCL);
724 out_invalidate:
725         xfs_vm_invalidatepage(page, 0, PAGE_CACHE_SIZE);
726         return;
727 }
728
729 static int
730 xfs_writepage_submit(
731         struct xfs_writepage_ctx *wpc,
732         struct writeback_control *wbc,
733         int                     status)
734 {
735         struct blk_plug         plug;
736
737         /* Reserve log space if we might write beyond the on-disk inode size. */
738         if (!status && wpc->ioend && wpc->ioend->io_type != XFS_IO_UNWRITTEN &&
739             xfs_ioend_is_append(wpc->ioend))
740                 status = xfs_setfilesize_trans_alloc(wpc->ioend);
741
742         if (wpc->iohead) {
743                 blk_start_plug(&plug);
744                 xfs_submit_ioend(wbc, wpc->iohead, status);
745                 blk_finish_plug(&plug);
746         }
747         return status;
748 }
749
750 /*
751  * Write out a dirty page.
752  *
753  * For delalloc space on the page we need to allocate space and flush it.
754  * For unwritten space on the page we need to start the conversion to
755  * regular allocated space.
756  * For any other dirty buffer heads on the page we should flush them.
757  */
758 STATIC int
759 xfs_do_writepage(
760         struct page             *page,
761         struct writeback_control *wbc,
762         void                    *data)
763 {
764         struct xfs_writepage_ctx *wpc = data;
765         struct inode            *inode = page->mapping->host;
766         struct buffer_head      *bh, *head;
767         loff_t                  offset;
768         __uint64_t              end_offset;
769         pgoff_t                 end_index;
770         ssize_t                 len;
771         int                     err, uptodate = 1;
772         int                     count = 0;
773
774         trace_xfs_writepage(inode, page, 0, 0);
775
776         ASSERT(page_has_buffers(page));
777
778         /*
779          * Refuse to write the page out if we are called from reclaim context.
780          *
781          * This avoids stack overflows when called from deeply used stacks in
782          * random callers for direct reclaim or memcg reclaim.  We explicitly
783          * allow reclaim from kswapd as the stack usage there is relatively low.
784          *
785          * This should never happen except in the case of a VM regression so
786          * warn about it.
787          */
788         if (WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD)) ==
789                         PF_MEMALLOC))
790                 goto redirty;
791
792         /*
793          * Given that we do not allow direct reclaim to call us, we should
794          * never be called while in a filesystem transaction.
795          */
796         if (WARN_ON_ONCE(current->flags & PF_FSTRANS))
797                 goto redirty;
798
799         /*
800          * Is this page beyond the end of the file?
801          *
802          * The page index is less than the end_index, adjust the end_offset
803          * to the highest offset that this page should represent.
804          * -----------------------------------------------------
805          * |                    file mapping           | <EOF> |
806          * -----------------------------------------------------
807          * | Page ... | Page N-2 | Page N-1 |  Page N  |       |
808          * ^--------------------------------^----------|--------
809          * |     desired writeback range    |      see else    |
810          * ---------------------------------^------------------|
811          */
812         offset = i_size_read(inode);
813         end_index = offset >> PAGE_CACHE_SHIFT;
814         if (page->index < end_index)
815                 end_offset = (xfs_off_t)(page->index + 1) << PAGE_CACHE_SHIFT;
816         else {
817                 /*
818                  * Check whether the page to write out is beyond or straddles
819                  * i_size or not.
820                  * -------------------------------------------------------
821                  * |            file mapping                    | <EOF>  |
822                  * -------------------------------------------------------
823                  * | Page ... | Page N-2 | Page N-1 |  Page N   | Beyond |
824                  * ^--------------------------------^-----------|---------
825                  * |                                |      Straddles     |
826                  * ---------------------------------^-----------|--------|
827                  */
828                 unsigned offset_into_page = offset & (PAGE_CACHE_SIZE - 1);
829
830                 /*
831                  * Skip the page if it is fully outside i_size, e.g. due to a
832                  * truncate operation that is in progress. We must redirty the
833                  * page so that reclaim stops reclaiming it. Otherwise
834                  * xfs_vm_releasepage() is called on it and gets confused.
835                  *
836                  * Note that the end_index is unsigned long, it would overflow
837                  * if the given offset is greater than 16TB on 32-bit system
838                  * and if we do check the page is fully outside i_size or not
839                  * via "if (page->index >= end_index + 1)" as "end_index + 1"
840                  * will be evaluated to 0.  Hence this page will be redirtied
841                  * and be written out repeatedly which would result in an
842                  * infinite loop, the user program that perform this operation
843                  * will hang.  Instead, we can verify this situation by checking
844                  * if the page to write is totally beyond the i_size or if it's
845                  * offset is just equal to the EOF.
846                  */
847                 if (page->index > end_index ||
848                     (page->index == end_index && offset_into_page == 0))
849                         goto redirty;
850
851                 /*
852                  * The page straddles i_size.  It must be zeroed out on each
853                  * and every writepage invocation because it may be mmapped.
854                  * "A file is mapped in multiples of the page size.  For a file
855                  * that is not a multiple of the page size, the remaining
856                  * memory is zeroed when mapped, and writes to that region are
857                  * not written out to the file."
858                  */
859                 zero_user_segment(page, offset_into_page, PAGE_CACHE_SIZE);
860
861                 /* Adjust the end_offset to the end of file */
862                 end_offset = offset;
863         }
864
865         len = 1 << inode->i_blkbits;
866
867         bh = head = page_buffers(page);
868         offset = page_offset(page);
869
870         do {
871                 if (offset >= end_offset)
872                         break;
873                 if (!buffer_uptodate(bh))
874                         uptodate = 0;
875
876                 /*
877                  * set_page_dirty dirties all buffers in a page, independent
878                  * of their state.  The dirty state however is entirely
879                  * meaningless for holes (!mapped && uptodate), so skip
880                  * buffers covering holes here.
881                  */
882                 if (!buffer_mapped(bh) && buffer_uptodate(bh)) {
883                         wpc->imap_valid = false;
884                         continue;
885                 }
886
887                 if (buffer_unwritten(bh)) {
888                         if (wpc->io_type != XFS_IO_UNWRITTEN) {
889                                 wpc->io_type = XFS_IO_UNWRITTEN;
890                                 wpc->imap_valid = false;
891                         }
892                 } else if (buffer_delay(bh)) {
893                         if (wpc->io_type != XFS_IO_DELALLOC) {
894                                 wpc->io_type = XFS_IO_DELALLOC;
895                                 wpc->imap_valid = false;
896                         }
897                 } else if (buffer_uptodate(bh)) {
898                         if (wpc->io_type != XFS_IO_OVERWRITE) {
899                                 wpc->io_type = XFS_IO_OVERWRITE;
900                                 wpc->imap_valid = false;
901                         }
902                 } else {
903                         if (PageUptodate(page))
904                                 ASSERT(buffer_mapped(bh));
905                         /*
906                          * This buffer is not uptodate and will not be
907                          * written to disk.  Ensure that we will put any
908                          * subsequent writeable buffers into a new
909                          * ioend.
910                          */
911                         wpc->imap_valid = 0;
912                         continue;
913                 }
914
915                 if (wpc->imap_valid)
916                         wpc->imap_valid = xfs_imap_valid(inode, &wpc->imap, offset);
917                 if (!wpc->imap_valid) {
918                         err = xfs_map_blocks(inode, offset, &wpc->imap,
919                                              wpc->io_type);
920                         if (err)
921                                 goto error;
922                         wpc->imap_valid = xfs_imap_valid(inode, &wpc->imap, offset);
923                 }
924                 if (wpc->imap_valid) {
925                         lock_buffer(bh);
926                         if (wpc->io_type != XFS_IO_OVERWRITE)
927                                 xfs_map_at_offset(inode, bh, &wpc->imap, offset);
928                         xfs_add_to_ioend(inode, bh, offset, wpc);
929                         count++;
930                 }
931
932                 if (!wpc->iohead)
933                         wpc->iohead = wpc->ioend;
934
935         } while (offset += len, ((bh = bh->b_this_page) != head));
936
937         if (uptodate && bh == head)
938                 SetPageUptodate(page);
939
940         xfs_start_page_writeback(page, 1, count);
941
942         ASSERT(wpc->iohead || !count);
943         return 0;
944
945 error:
946         /*
947          * On error, we have to fail the iohead here because we buffers locked
948          * in the ioend chain. If we don't do this, we'll deadlock invalidating
949          * the page as that tries to lock the buffers on the page. Also, because
950          * we may have set pages under writeback, we have to make sure we run
951          * IO completion to mark the error state of the IO appropriately, so we
952          * can't cancel the ioend directly here. That means we have to mark this
953          * page as under writeback if we included any buffers from it in the
954          * ioend chain so that completion treats it correctly.
955          *
956          * If we didn't include the page in the ioend, then we can simply
957          * discard and unlock it as there are no other users of the page or it's
958          * buffers right now. The caller will still need to trigger submission
959          * of outstanding ioends on the writepage context so they are treated
960          * correctly on error.
961          */
962         if (count)
963                 xfs_start_page_writeback(page, 0, count);
964         else {
965                 xfs_aops_discard_page(page);
966                 ClearPageUptodate(page);
967                 unlock_page(page);
968         }
969         mapping_set_error(page->mapping, err);
970         return err;
971
972 redirty:
973         redirty_page_for_writepage(wbc, page);
974         unlock_page(page);
975         return 0;
976 }
977
978 STATIC int
979 xfs_vm_writepage(
980         struct page             *page,
981         struct writeback_control *wbc)
982 {
983         struct xfs_writepage_ctx wpc = {
984                 .io_type = XFS_IO_INVALID,
985         };
986         int                     ret;
987
988         ret = xfs_do_writepage(page, wbc, &wpc);
989         return xfs_writepage_submit(&wpc, wbc, ret);
990 }
991
992 STATIC int
993 xfs_vm_writepages(
994         struct address_space    *mapping,
995         struct writeback_control *wbc)
996 {
997         struct xfs_writepage_ctx wpc = {
998                 .io_type = XFS_IO_INVALID,
999         };
1000         int                     ret;
1001
1002         xfs_iflags_clear(XFS_I(mapping->host), XFS_ITRUNCATED);
1003         ret = write_cache_pages(mapping, wbc, xfs_do_writepage, &wpc);
1004         return xfs_writepage_submit(&wpc, wbc, ret);
1005 }
1006
1007 /*
1008  * Called to move a page into cleanable state - and from there
1009  * to be released. The page should already be clean. We always
1010  * have buffer heads in this call.
1011  *
1012  * Returns 1 if the page is ok to release, 0 otherwise.
1013  */
1014 STATIC int
1015 xfs_vm_releasepage(
1016         struct page             *page,
1017         gfp_t                   gfp_mask)
1018 {
1019         int                     delalloc, unwritten;
1020
1021         trace_xfs_releasepage(page->mapping->host, page, 0, 0);
1022
1023         xfs_count_page_state(page, &delalloc, &unwritten);
1024
1025         if (WARN_ON_ONCE(delalloc))
1026                 return 0;
1027         if (WARN_ON_ONCE(unwritten))
1028                 return 0;
1029
1030         return try_to_free_buffers(page);
1031 }
1032
1033 /*
1034  * When we map a DIO buffer, we may need to attach an ioend that describes the
1035  * type of write IO we are doing. This passes to the completion function the
1036  * operations it needs to perform. If the mapping is for an overwrite wholly
1037  * within the EOF then we don't need an ioend and so we don't allocate one.
1038  * This avoids the unnecessary overhead of allocating and freeing ioends for
1039  * workloads that don't require transactions on IO completion.
1040  *
1041  * If we get multiple mappings in a single IO, we might be mapping different
1042  * types. But because the direct IO can only have a single private pointer, we
1043  * need to ensure that:
1044  *
1045  * a) i) the ioend spans the entire region of unwritten mappings; or
1046  *    ii) the ioend spans all the mappings that cross or are beyond EOF; and
1047  * b) if it contains unwritten extents, it is *permanently* marked as such
1048  *
1049  * We could do this by chaining ioends like buffered IO does, but we only
1050  * actually get one IO completion callback from the direct IO, and that spans
1051  * the entire IO regardless of how many mappings and IOs are needed to complete
1052  * the DIO. There is only going to be one reference to the ioend and its life
1053  * cycle is constrained by the DIO completion code. hence we don't need
1054  * reference counting here.
1055  *
1056  * Note that for DIO, an IO to the highest supported file block offset (i.e.
1057  * 2^63 - 1FSB bytes) will result in the offset + count overflowing a signed 64
1058  * bit variable. Hence if we see this overflow, we have to assume that the IO is
1059  * extending the file size. We won't know for sure until IO completion is run
1060  * and the actual max write offset is communicated to the IO completion
1061  * routine.
1062  *
1063  * For DAX page faults, we are preparing to never see unwritten extents here,
1064  * nor should we ever extend the inode size. Hence we will soon have nothing to
1065  * do here for this case, ensuring we don't have to provide an IO completion
1066  * callback to free an ioend that we don't actually need for a fault into the
1067  * page at offset (2^63 - 1FSB) bytes.
1068  */
1069
1070 static void
1071 xfs_map_direct(
1072         struct inode            *inode,
1073         struct buffer_head      *bh_result,
1074         struct xfs_bmbt_irec    *imap,
1075         xfs_off_t               offset,
1076         bool                    dax_fault)
1077 {
1078         struct xfs_ioend        *ioend;
1079         xfs_off_t               size = bh_result->b_size;
1080         int                     type;
1081
1082         if (ISUNWRITTEN(imap))
1083                 type = XFS_IO_UNWRITTEN;
1084         else
1085                 type = XFS_IO_OVERWRITE;
1086
1087         trace_xfs_gbmap_direct(XFS_I(inode), offset, size, type, imap);
1088
1089         if (dax_fault) {
1090                 ASSERT(type == XFS_IO_OVERWRITE);
1091                 trace_xfs_gbmap_direct_none(XFS_I(inode), offset, size, type,
1092                                             imap);
1093                 return;
1094         }
1095
1096         if (bh_result->b_private) {
1097                 ioend = bh_result->b_private;
1098                 ASSERT(ioend->io_size > 0);
1099                 ASSERT(offset >= ioend->io_offset);
1100                 if (offset + size > ioend->io_offset + ioend->io_size)
1101                         ioend->io_size = offset - ioend->io_offset + size;
1102
1103                 if (type == XFS_IO_UNWRITTEN && type != ioend->io_type)
1104                         ioend->io_type = XFS_IO_UNWRITTEN;
1105
1106                 trace_xfs_gbmap_direct_update(XFS_I(inode), ioend->io_offset,
1107                                               ioend->io_size, ioend->io_type,
1108                                               imap);
1109         } else if (type == XFS_IO_UNWRITTEN ||
1110                    offset + size > i_size_read(inode) ||
1111                    offset + size < 0) {
1112                 ioend = xfs_alloc_ioend(inode, type);
1113                 ioend->io_offset = offset;
1114                 ioend->io_size = size;
1115
1116                 bh_result->b_private = ioend;
1117                 set_buffer_defer_completion(bh_result);
1118
1119                 trace_xfs_gbmap_direct_new(XFS_I(inode), offset, size, type,
1120                                            imap);
1121         } else {
1122                 trace_xfs_gbmap_direct_none(XFS_I(inode), offset, size, type,
1123                                             imap);
1124         }
1125 }
1126
1127 /*
1128  * If this is O_DIRECT or the mpage code calling tell them how large the mapping
1129  * is, so that we can avoid repeated get_blocks calls.
1130  *
1131  * If the mapping spans EOF, then we have to break the mapping up as the mapping
1132  * for blocks beyond EOF must be marked new so that sub block regions can be
1133  * correctly zeroed. We can't do this for mappings within EOF unless the mapping
1134  * was just allocated or is unwritten, otherwise the callers would overwrite
1135  * existing data with zeros. Hence we have to split the mapping into a range up
1136  * to and including EOF, and a second mapping for beyond EOF.
1137  */
1138 static void
1139 xfs_map_trim_size(
1140         struct inode            *inode,
1141         sector_t                iblock,
1142         struct buffer_head      *bh_result,
1143         struct xfs_bmbt_irec    *imap,
1144         xfs_off_t               offset,
1145         ssize_t                 size)
1146 {
1147         xfs_off_t               mapping_size;
1148
1149         mapping_size = imap->br_startoff + imap->br_blockcount - iblock;
1150         mapping_size <<= inode->i_blkbits;
1151
1152         ASSERT(mapping_size > 0);
1153         if (mapping_size > size)
1154                 mapping_size = size;
1155         if (offset < i_size_read(inode) &&
1156             offset + mapping_size >= i_size_read(inode)) {
1157                 /* limit mapping to block that spans EOF */
1158                 mapping_size = roundup_64(i_size_read(inode) - offset,
1159                                           1 << inode->i_blkbits);
1160         }
1161         if (mapping_size > LONG_MAX)
1162                 mapping_size = LONG_MAX;
1163
1164         bh_result->b_size = mapping_size;
1165 }
1166
1167 STATIC int
1168 __xfs_get_blocks(
1169         struct inode            *inode,
1170         sector_t                iblock,
1171         struct buffer_head      *bh_result,
1172         int                     create,
1173         bool                    direct,
1174         bool                    dax_fault)
1175 {
1176         struct xfs_inode        *ip = XFS_I(inode);
1177         struct xfs_mount        *mp = ip->i_mount;
1178         xfs_fileoff_t           offset_fsb, end_fsb;
1179         int                     error = 0;
1180         int                     lockmode = 0;
1181         struct xfs_bmbt_irec    imap;
1182         int                     nimaps = 1;
1183         xfs_off_t               offset;
1184         ssize_t                 size;
1185         int                     new = 0;
1186
1187         if (XFS_FORCED_SHUTDOWN(mp))
1188                 return -EIO;
1189
1190         offset = (xfs_off_t)iblock << inode->i_blkbits;
1191         ASSERT(bh_result->b_size >= (1 << inode->i_blkbits));
1192         size = bh_result->b_size;
1193
1194         if (!create && direct && offset >= i_size_read(inode))
1195                 return 0;
1196
1197         /*
1198          * Direct I/O is usually done on preallocated files, so try getting
1199          * a block mapping without an exclusive lock first.  For buffered
1200          * writes we already have the exclusive iolock anyway, so avoiding
1201          * a lock roundtrip here by taking the ilock exclusive from the
1202          * beginning is a useful micro optimization.
1203          */
1204         if (create && !direct) {
1205                 lockmode = XFS_ILOCK_EXCL;
1206                 xfs_ilock(ip, lockmode);
1207         } else {
1208                 lockmode = xfs_ilock_data_map_shared(ip);
1209         }
1210
1211         ASSERT(offset <= mp->m_super->s_maxbytes);
1212         if (offset + size > mp->m_super->s_maxbytes)
1213                 size = mp->m_super->s_maxbytes - offset;
1214         end_fsb = XFS_B_TO_FSB(mp, (xfs_ufsize_t)offset + size);
1215         offset_fsb = XFS_B_TO_FSBT(mp, offset);
1216
1217         error = xfs_bmapi_read(ip, offset_fsb, end_fsb - offset_fsb,
1218                                 &imap, &nimaps, XFS_BMAPI_ENTIRE);
1219         if (error)
1220                 goto out_unlock;
1221
1222         /* for DAX, we convert unwritten extents directly */
1223         if (create &&
1224             (!nimaps ||
1225              (imap.br_startblock == HOLESTARTBLOCK ||
1226               imap.br_startblock == DELAYSTARTBLOCK) ||
1227              (IS_DAX(inode) && ISUNWRITTEN(&imap)))) {
1228                 if (direct || xfs_get_extsz_hint(ip)) {
1229                         /*
1230                          * xfs_iomap_write_direct() expects the shared lock. It
1231                          * is unlocked on return.
1232                          */
1233                         if (lockmode == XFS_ILOCK_EXCL)
1234                                 xfs_ilock_demote(ip, lockmode);
1235
1236                         error = xfs_iomap_write_direct(ip, offset, size,
1237                                                        &imap, nimaps);
1238                         if (error)
1239                                 return error;
1240                         new = 1;
1241
1242                 } else {
1243                         /*
1244                          * Delalloc reservations do not require a transaction,
1245                          * we can go on without dropping the lock here. If we
1246                          * are allocating a new delalloc block, make sure that
1247                          * we set the new flag so that we mark the buffer new so
1248                          * that we know that it is newly allocated if the write
1249                          * fails.
1250                          */
1251                         if (nimaps && imap.br_startblock == HOLESTARTBLOCK)
1252                                 new = 1;
1253                         error = xfs_iomap_write_delay(ip, offset, size, &imap);
1254                         if (error)
1255                                 goto out_unlock;
1256
1257                         xfs_iunlock(ip, lockmode);
1258                 }
1259                 trace_xfs_get_blocks_alloc(ip, offset, size,
1260                                 ISUNWRITTEN(&imap) ? XFS_IO_UNWRITTEN
1261                                                    : XFS_IO_DELALLOC, &imap);
1262         } else if (nimaps) {
1263                 trace_xfs_get_blocks_found(ip, offset, size,
1264                                 ISUNWRITTEN(&imap) ? XFS_IO_UNWRITTEN
1265                                                    : XFS_IO_OVERWRITE, &imap);
1266                 xfs_iunlock(ip, lockmode);
1267         } else {
1268                 trace_xfs_get_blocks_notfound(ip, offset, size);
1269                 goto out_unlock;
1270         }
1271
1272         if (IS_DAX(inode) && create) {
1273                 ASSERT(!ISUNWRITTEN(&imap));
1274                 /* zeroing is not needed at a higher layer */
1275                 new = 0;
1276         }
1277
1278         /* trim mapping down to size requested */
1279         if (direct || size > (1 << inode->i_blkbits))
1280                 xfs_map_trim_size(inode, iblock, bh_result,
1281                                   &imap, offset, size);
1282
1283         /*
1284          * For unwritten extents do not report a disk address in the buffered
1285          * read case (treat as if we're reading into a hole).
1286          */
1287         if (imap.br_startblock != HOLESTARTBLOCK &&
1288             imap.br_startblock != DELAYSTARTBLOCK &&
1289             (create || !ISUNWRITTEN(&imap))) {
1290                 xfs_map_buffer(inode, bh_result, &imap, offset);
1291                 if (ISUNWRITTEN(&imap))
1292                         set_buffer_unwritten(bh_result);
1293                 /* direct IO needs special help */
1294                 if (create && direct)
1295                         xfs_map_direct(inode, bh_result, &imap, offset,
1296                                        dax_fault);
1297         }
1298
1299         /*
1300          * If this is a realtime file, data may be on a different device.
1301          * to that pointed to from the buffer_head b_bdev currently.
1302          */
1303         bh_result->b_bdev = xfs_find_bdev_for_inode(inode);
1304
1305         /*
1306          * If we previously allocated a block out beyond eof and we are now
1307          * coming back to use it then we will need to flag it as new even if it
1308          * has a disk address.
1309          *
1310          * With sub-block writes into unwritten extents we also need to mark
1311          * the buffer as new so that the unwritten parts of the buffer gets
1312          * correctly zeroed.
1313          */
1314         if (create &&
1315             ((!buffer_mapped(bh_result) && !buffer_uptodate(bh_result)) ||
1316              (offset >= i_size_read(inode)) ||
1317              (new || ISUNWRITTEN(&imap))))
1318                 set_buffer_new(bh_result);
1319
1320         if (imap.br_startblock == DELAYSTARTBLOCK) {
1321                 BUG_ON(direct);
1322                 if (create) {
1323                         set_buffer_uptodate(bh_result);
1324                         set_buffer_mapped(bh_result);
1325                         set_buffer_delay(bh_result);
1326                 }
1327         }
1328
1329         return 0;
1330
1331 out_unlock:
1332         xfs_iunlock(ip, lockmode);
1333         return error;
1334 }
1335
1336 int
1337 xfs_get_blocks(
1338         struct inode            *inode,
1339         sector_t                iblock,
1340         struct buffer_head      *bh_result,
1341         int                     create)
1342 {
1343         return __xfs_get_blocks(inode, iblock, bh_result, create, false, false);
1344 }
1345
1346 int
1347 xfs_get_blocks_direct(
1348         struct inode            *inode,
1349         sector_t                iblock,
1350         struct buffer_head      *bh_result,
1351         int                     create)
1352 {
1353         return __xfs_get_blocks(inode, iblock, bh_result, create, true, false);
1354 }
1355
1356 int
1357 xfs_get_blocks_dax_fault(
1358         struct inode            *inode,
1359         sector_t                iblock,
1360         struct buffer_head      *bh_result,
1361         int                     create)
1362 {
1363         return __xfs_get_blocks(inode, iblock, bh_result, create, true, true);
1364 }
1365
1366 static void
1367 __xfs_end_io_direct_write(
1368         struct inode            *inode,
1369         struct xfs_ioend        *ioend,
1370         loff_t                  offset,
1371         ssize_t                 size)
1372 {
1373         struct xfs_mount        *mp = XFS_I(inode)->i_mount;
1374
1375         if (XFS_FORCED_SHUTDOWN(mp) || ioend->io_error)
1376                 goto out_end_io;
1377
1378         /*
1379          * dio completion end_io functions are only called on writes if more
1380          * than 0 bytes was written.
1381          */
1382         ASSERT(size > 0);
1383
1384         /*
1385          * The ioend only maps whole blocks, while the IO may be sector aligned.
1386          * Hence the ioend offset/size may not match the IO offset/size exactly.
1387          * Because we don't map overwrites within EOF into the ioend, the offset
1388          * may not match, but only if the endio spans EOF.  Either way, write
1389          * the IO sizes into the ioend so that completion processing does the
1390          * right thing.
1391          */
1392         ASSERT(offset + size <= ioend->io_offset + ioend->io_size);
1393         ioend->io_size = size;
1394         ioend->io_offset = offset;
1395
1396         /*
1397          * The ioend tells us whether we are doing unwritten extent conversion
1398          * or an append transaction that updates the on-disk file size. These
1399          * cases are the only cases where we should *potentially* be needing
1400          * to update the VFS inode size.
1401          *
1402          * We need to update the in-core inode size here so that we don't end up
1403          * with the on-disk inode size being outside the in-core inode size. We
1404          * have no other method of updating EOF for AIO, so always do it here
1405          * if necessary.
1406          *
1407          * We need to lock the test/set EOF update as we can be racing with
1408          * other IO completions here to update the EOF. Failing to serialise
1409          * here can result in EOF moving backwards and Bad Things Happen when
1410          * that occurs.
1411          */
1412         spin_lock(&XFS_I(inode)->i_flags_lock);
1413         if (offset + size > i_size_read(inode))
1414                 i_size_write(inode, offset + size);
1415         spin_unlock(&XFS_I(inode)->i_flags_lock);
1416
1417         /*
1418          * If we are doing an append IO that needs to update the EOF on disk,
1419          * do the transaction reserve now so we can use common end io
1420          * processing. Stashing the error (if there is one) in the ioend will
1421          * result in the ioend processing passing on the error if it is
1422          * possible as we can't return it from here.
1423          */
1424         if (ioend->io_type == XFS_IO_OVERWRITE)
1425                 ioend->io_error = xfs_setfilesize_trans_alloc(ioend);
1426
1427 out_end_io:
1428         xfs_end_io(&ioend->io_work);
1429         return;
1430 }
1431
1432 /*
1433  * Complete a direct I/O write request.
1434  *
1435  * The ioend structure is passed from __xfs_get_blocks() to tell us what to do.
1436  * If no ioend exists (i.e. @private == NULL) then the write IO is an overwrite
1437  * wholly within the EOF and so there is nothing for us to do. Note that in this
1438  * case the completion can be called in interrupt context, whereas if we have an
1439  * ioend we will always be called in task context (i.e. from a workqueue).
1440  */
1441 STATIC void
1442 xfs_end_io_direct_write(
1443         struct kiocb            *iocb,
1444         loff_t                  offset,
1445         ssize_t                 size,
1446         void                    *private)
1447 {
1448         struct inode            *inode = file_inode(iocb->ki_filp);
1449         struct xfs_ioend        *ioend = private;
1450
1451         trace_xfs_gbmap_direct_endio(XFS_I(inode), offset, size,
1452                                      ioend ? ioend->io_type : 0, NULL);
1453
1454         if (!ioend) {
1455                 ASSERT(offset + size <= i_size_read(inode));
1456                 return;
1457         }
1458
1459         __xfs_end_io_direct_write(inode, ioend, offset, size);
1460 }
1461
1462 static inline ssize_t
1463 xfs_vm_do_dio(
1464         struct inode            *inode,
1465         struct kiocb            *iocb,
1466         struct iov_iter         *iter,
1467         loff_t                  offset,
1468         void                    (*endio)(struct kiocb   *iocb,
1469                                          loff_t         offset,
1470                                          ssize_t        size,
1471                                          void           *private),
1472         int                     flags)
1473 {
1474         struct block_device     *bdev;
1475
1476         if (IS_DAX(inode))
1477                 return dax_do_io(iocb, inode, iter, offset,
1478                                  xfs_get_blocks_direct, endio, 0);
1479
1480         bdev = xfs_find_bdev_for_inode(inode);
1481         return  __blockdev_direct_IO(iocb, inode, bdev, iter, offset,
1482                                      xfs_get_blocks_direct, endio, NULL, flags);
1483 }
1484
1485 STATIC ssize_t
1486 xfs_vm_direct_IO(
1487         struct kiocb            *iocb,
1488         struct iov_iter         *iter,
1489         loff_t                  offset)
1490 {
1491         struct inode            *inode = iocb->ki_filp->f_mapping->host;
1492
1493         if (iov_iter_rw(iter) == WRITE)
1494                 return xfs_vm_do_dio(inode, iocb, iter, offset,
1495                                      xfs_end_io_direct_write, DIO_ASYNC_EXTEND);
1496         return xfs_vm_do_dio(inode, iocb, iter, offset, NULL, 0);
1497 }
1498
1499 /*
1500  * Punch out the delalloc blocks we have already allocated.
1501  *
1502  * Don't bother with xfs_setattr given that nothing can have made it to disk yet
1503  * as the page is still locked at this point.
1504  */
1505 STATIC void
1506 xfs_vm_kill_delalloc_range(
1507         struct inode            *inode,
1508         loff_t                  start,
1509         loff_t                  end)
1510 {
1511         struct xfs_inode        *ip = XFS_I(inode);
1512         xfs_fileoff_t           start_fsb;
1513         xfs_fileoff_t           end_fsb;
1514         int                     error;
1515
1516         start_fsb = XFS_B_TO_FSB(ip->i_mount, start);
1517         end_fsb = XFS_B_TO_FSB(ip->i_mount, end);
1518         if (end_fsb <= start_fsb)
1519                 return;
1520
1521         xfs_ilock(ip, XFS_ILOCK_EXCL);
1522         error = xfs_bmap_punch_delalloc_range(ip, start_fsb,
1523                                                 end_fsb - start_fsb);
1524         if (error) {
1525                 /* something screwed, just bail */
1526                 if (!XFS_FORCED_SHUTDOWN(ip->i_mount)) {
1527                         xfs_alert(ip->i_mount,
1528                 "xfs_vm_write_failed: unable to clean up ino %lld",
1529                                         ip->i_ino);
1530                 }
1531         }
1532         xfs_iunlock(ip, XFS_ILOCK_EXCL);
1533 }
1534
1535 STATIC void
1536 xfs_vm_write_failed(
1537         struct inode            *inode,
1538         struct page             *page,
1539         loff_t                  pos,
1540         unsigned                len)
1541 {
1542         loff_t                  block_offset;
1543         loff_t                  block_start;
1544         loff_t                  block_end;
1545         loff_t                  from = pos & (PAGE_CACHE_SIZE - 1);
1546         loff_t                  to = from + len;
1547         struct buffer_head      *bh, *head;
1548
1549         /*
1550          * The request pos offset might be 32 or 64 bit, this is all fine
1551          * on 64-bit platform.  However, for 64-bit pos request on 32-bit
1552          * platform, the high 32-bit will be masked off if we evaluate the
1553          * block_offset via (pos & PAGE_MASK) because the PAGE_MASK is
1554          * 0xfffff000 as an unsigned long, hence the result is incorrect
1555          * which could cause the following ASSERT failed in most cases.
1556          * In order to avoid this, we can evaluate the block_offset of the
1557          * start of the page by using shifts rather than masks the mismatch
1558          * problem.
1559          */
1560         block_offset = (pos >> PAGE_CACHE_SHIFT) << PAGE_CACHE_SHIFT;
1561
1562         ASSERT(block_offset + from == pos);
1563
1564         head = page_buffers(page);
1565         block_start = 0;
1566         for (bh = head; bh != head || !block_start;
1567              bh = bh->b_this_page, block_start = block_end,
1568                                    block_offset += bh->b_size) {
1569                 block_end = block_start + bh->b_size;
1570
1571                 /* skip buffers before the write */
1572                 if (block_end <= from)
1573                         continue;
1574
1575                 /* if the buffer is after the write, we're done */
1576                 if (block_start >= to)
1577                         break;
1578
1579                 if (!buffer_delay(bh))
1580                         continue;
1581
1582                 if (!buffer_new(bh) && block_offset < i_size_read(inode))
1583                         continue;
1584
1585                 xfs_vm_kill_delalloc_range(inode, block_offset,
1586                                            block_offset + bh->b_size);
1587
1588                 /*
1589                  * This buffer does not contain data anymore. make sure anyone
1590                  * who finds it knows that for certain.
1591                  */
1592                 clear_buffer_delay(bh);
1593                 clear_buffer_uptodate(bh);
1594                 clear_buffer_mapped(bh);
1595                 clear_buffer_new(bh);
1596                 clear_buffer_dirty(bh);
1597         }
1598
1599 }
1600
1601 /*
1602  * This used to call block_write_begin(), but it unlocks and releases the page
1603  * on error, and we need that page to be able to punch stale delalloc blocks out
1604  * on failure. hence we copy-n-waste it here and call xfs_vm_write_failed() at
1605  * the appropriate point.
1606  */
1607 STATIC int
1608 xfs_vm_write_begin(
1609         struct file             *file,
1610         struct address_space    *mapping,
1611         loff_t                  pos,
1612         unsigned                len,
1613         unsigned                flags,
1614         struct page             **pagep,
1615         void                    **fsdata)
1616 {
1617         pgoff_t                 index = pos >> PAGE_CACHE_SHIFT;
1618         struct page             *page;
1619         int                     status;
1620
1621         ASSERT(len <= PAGE_CACHE_SIZE);
1622
1623         page = grab_cache_page_write_begin(mapping, index, flags);
1624         if (!page)
1625                 return -ENOMEM;
1626
1627         status = __block_write_begin(page, pos, len, xfs_get_blocks);
1628         if (unlikely(status)) {
1629                 struct inode    *inode = mapping->host;
1630                 size_t          isize = i_size_read(inode);
1631
1632                 xfs_vm_write_failed(inode, page, pos, len);
1633                 unlock_page(page);
1634
1635                 /*
1636                  * If the write is beyond EOF, we only want to kill blocks
1637                  * allocated in this write, not blocks that were previously
1638                  * written successfully.
1639                  */
1640                 if (pos + len > isize) {
1641                         ssize_t start = max_t(ssize_t, pos, isize);
1642
1643                         truncate_pagecache_range(inode, start, pos + len);
1644                 }
1645
1646                 page_cache_release(page);
1647                 page = NULL;
1648         }
1649
1650         *pagep = page;
1651         return status;
1652 }
1653
1654 /*
1655  * On failure, we only need to kill delalloc blocks beyond EOF in the range of
1656  * this specific write because they will never be written. Previous writes
1657  * beyond EOF where block allocation succeeded do not need to be trashed, so
1658  * only new blocks from this write should be trashed. For blocks within
1659  * EOF, generic_write_end() zeros them so they are safe to leave alone and be
1660  * written with all the other valid data.
1661  */
1662 STATIC int
1663 xfs_vm_write_end(
1664         struct file             *file,
1665         struct address_space    *mapping,
1666         loff_t                  pos,
1667         unsigned                len,
1668         unsigned                copied,
1669         struct page             *page,
1670         void                    *fsdata)
1671 {
1672         int                     ret;
1673
1674         ASSERT(len <= PAGE_CACHE_SIZE);
1675
1676         ret = generic_write_end(file, mapping, pos, len, copied, page, fsdata);
1677         if (unlikely(ret < len)) {
1678                 struct inode    *inode = mapping->host;
1679                 size_t          isize = i_size_read(inode);
1680                 loff_t          to = pos + len;
1681
1682                 if (to > isize) {
1683                         /* only kill blocks in this write beyond EOF */
1684                         if (pos > isize)
1685                                 isize = pos;
1686                         xfs_vm_kill_delalloc_range(inode, isize, to);
1687                         truncate_pagecache_range(inode, isize, to);
1688                 }
1689         }
1690         return ret;
1691 }
1692
1693 STATIC sector_t
1694 xfs_vm_bmap(
1695         struct address_space    *mapping,
1696         sector_t                block)
1697 {
1698         struct inode            *inode = (struct inode *)mapping->host;
1699         struct xfs_inode        *ip = XFS_I(inode);
1700
1701         trace_xfs_vm_bmap(XFS_I(inode));
1702         xfs_ilock(ip, XFS_IOLOCK_SHARED);
1703         filemap_write_and_wait(mapping);
1704         xfs_iunlock(ip, XFS_IOLOCK_SHARED);
1705         return generic_block_bmap(mapping, block, xfs_get_blocks);
1706 }
1707
1708 STATIC int
1709 xfs_vm_readpage(
1710         struct file             *unused,
1711         struct page             *page)
1712 {
1713         trace_xfs_vm_readpage(page->mapping->host, 1);
1714         return mpage_readpage(page, xfs_get_blocks);
1715 }
1716
1717 STATIC int
1718 xfs_vm_readpages(
1719         struct file             *unused,
1720         struct address_space    *mapping,
1721         struct list_head        *pages,
1722         unsigned                nr_pages)
1723 {
1724         trace_xfs_vm_readpages(mapping->host, nr_pages);
1725         return mpage_readpages(mapping, pages, nr_pages, xfs_get_blocks);
1726 }
1727
1728 /*
1729  * This is basically a copy of __set_page_dirty_buffers() with one
1730  * small tweak: buffers beyond EOF do not get marked dirty. If we mark them
1731  * dirty, we'll never be able to clean them because we don't write buffers
1732  * beyond EOF, and that means we can't invalidate pages that span EOF
1733  * that have been marked dirty. Further, the dirty state can leak into
1734  * the file interior if the file is extended, resulting in all sorts of
1735  * bad things happening as the state does not match the underlying data.
1736  *
1737  * XXX: this really indicates that bufferheads in XFS need to die. Warts like
1738  * this only exist because of bufferheads and how the generic code manages them.
1739  */
1740 STATIC int
1741 xfs_vm_set_page_dirty(
1742         struct page             *page)
1743 {
1744         struct address_space    *mapping = page->mapping;
1745         struct inode            *inode = mapping->host;
1746         loff_t                  end_offset;
1747         loff_t                  offset;
1748         int                     newly_dirty;
1749         struct mem_cgroup       *memcg;
1750
1751         if (unlikely(!mapping))
1752                 return !TestSetPageDirty(page);
1753
1754         end_offset = i_size_read(inode);
1755         offset = page_offset(page);
1756
1757         spin_lock(&mapping->private_lock);
1758         if (page_has_buffers(page)) {
1759                 struct buffer_head *head = page_buffers(page);
1760                 struct buffer_head *bh = head;
1761
1762                 do {
1763                         if (offset < end_offset)
1764                                 set_buffer_dirty(bh);
1765                         bh = bh->b_this_page;
1766                         offset += 1 << inode->i_blkbits;
1767                 } while (bh != head);
1768         }
1769         /*
1770          * Use mem_group_begin_page_stat() to keep PageDirty synchronized with
1771          * per-memcg dirty page counters.
1772          */
1773         memcg = mem_cgroup_begin_page_stat(page);
1774         newly_dirty = !TestSetPageDirty(page);
1775         spin_unlock(&mapping->private_lock);
1776
1777         if (newly_dirty) {
1778                 /* sigh - __set_page_dirty() is static, so copy it here, too */
1779                 unsigned long flags;
1780
1781                 spin_lock_irqsave(&mapping->tree_lock, flags);
1782                 if (page->mapping) {    /* Race with truncate? */
1783                         WARN_ON_ONCE(!PageUptodate(page));
1784                         account_page_dirtied(page, mapping, memcg);
1785                         radix_tree_tag_set(&mapping->page_tree,
1786                                         page_index(page), PAGECACHE_TAG_DIRTY);
1787                 }
1788                 spin_unlock_irqrestore(&mapping->tree_lock, flags);
1789         }
1790         mem_cgroup_end_page_stat(memcg);
1791         if (newly_dirty)
1792                 __mark_inode_dirty(mapping->host, I_DIRTY_PAGES);
1793         return newly_dirty;
1794 }
1795
1796 const struct address_space_operations xfs_address_space_operations = {
1797         .readpage               = xfs_vm_readpage,
1798         .readpages              = xfs_vm_readpages,
1799         .writepage              = xfs_vm_writepage,
1800         .writepages             = xfs_vm_writepages,
1801         .set_page_dirty         = xfs_vm_set_page_dirty,
1802         .releasepage            = xfs_vm_releasepage,
1803         .invalidatepage         = xfs_vm_invalidatepage,
1804         .write_begin            = xfs_vm_write_begin,
1805         .write_end              = xfs_vm_write_end,
1806         .bmap                   = xfs_vm_bmap,
1807         .direct_IO              = xfs_vm_direct_IO,
1808         .migratepage            = buffer_migrate_page,
1809         .is_partially_uptodate  = block_is_partially_uptodate,
1810         .error_remove_page      = generic_error_remove_page,
1811 };