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