916a35cae5e94d649d6d8d181647ab870ce558d9
[linux-2.6-microblaze.git] / fs / xfs / xfs_file.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (c) 2000-2005 Silicon Graphics, Inc.
4  * All Rights Reserved.
5  */
6 #include "xfs.h"
7 #include "xfs_fs.h"
8 #include "xfs_shared.h"
9 #include "xfs_format.h"
10 #include "xfs_log_format.h"
11 #include "xfs_trans_resv.h"
12 #include "xfs_mount.h"
13 #include "xfs_da_format.h"
14 #include "xfs_da_btree.h"
15 #include "xfs_inode.h"
16 #include "xfs_trans.h"
17 #include "xfs_inode_item.h"
18 #include "xfs_bmap.h"
19 #include "xfs_bmap_util.h"
20 #include "xfs_error.h"
21 #include "xfs_dir2.h"
22 #include "xfs_dir2_priv.h"
23 #include "xfs_ioctl.h"
24 #include "xfs_trace.h"
25 #include "xfs_log.h"
26 #include "xfs_icache.h"
27 #include "xfs_pnfs.h"
28 #include "xfs_iomap.h"
29 #include "xfs_reflink.h"
30
31 #include <linux/dcache.h>
32 #include <linux/falloc.h>
33 #include <linux/pagevec.h>
34 #include <linux/backing-dev.h>
35 #include <linux/mman.h>
36
37 static const struct vm_operations_struct xfs_file_vm_ops;
38
39 int
40 xfs_update_prealloc_flags(
41         struct xfs_inode        *ip,
42         enum xfs_prealloc_flags flags)
43 {
44         struct xfs_trans        *tp;
45         int                     error;
46
47         error = xfs_trans_alloc(ip->i_mount, &M_RES(ip->i_mount)->tr_writeid,
48                         0, 0, 0, &tp);
49         if (error)
50                 return error;
51
52         xfs_ilock(ip, XFS_ILOCK_EXCL);
53         xfs_trans_ijoin(tp, ip, XFS_ILOCK_EXCL);
54
55         if (!(flags & XFS_PREALLOC_INVISIBLE)) {
56                 VFS_I(ip)->i_mode &= ~S_ISUID;
57                 if (VFS_I(ip)->i_mode & S_IXGRP)
58                         VFS_I(ip)->i_mode &= ~S_ISGID;
59                 xfs_trans_ichgtime(tp, ip, XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG);
60         }
61
62         if (flags & XFS_PREALLOC_SET)
63                 ip->i_d.di_flags |= XFS_DIFLAG_PREALLOC;
64         if (flags & XFS_PREALLOC_CLEAR)
65                 ip->i_d.di_flags &= ~XFS_DIFLAG_PREALLOC;
66
67         xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
68         if (flags & XFS_PREALLOC_SYNC)
69                 xfs_trans_set_sync(tp);
70         return xfs_trans_commit(tp);
71 }
72
73 /*
74  * Fsync operations on directories are much simpler than on regular files,
75  * as there is no file data to flush, and thus also no need for explicit
76  * cache flush operations, and there are no non-transaction metadata updates
77  * on directories either.
78  */
79 STATIC int
80 xfs_dir_fsync(
81         struct file             *file,
82         loff_t                  start,
83         loff_t                  end,
84         int                     datasync)
85 {
86         struct xfs_inode        *ip = XFS_I(file->f_mapping->host);
87         struct xfs_mount        *mp = ip->i_mount;
88         xfs_lsn_t               lsn = 0;
89
90         trace_xfs_dir_fsync(ip);
91
92         xfs_ilock(ip, XFS_ILOCK_SHARED);
93         if (xfs_ipincount(ip))
94                 lsn = ip->i_itemp->ili_last_lsn;
95         xfs_iunlock(ip, XFS_ILOCK_SHARED);
96
97         if (!lsn)
98                 return 0;
99         return xfs_log_force_lsn(mp, lsn, XFS_LOG_SYNC, NULL);
100 }
101
102 STATIC int
103 xfs_file_fsync(
104         struct file             *file,
105         loff_t                  start,
106         loff_t                  end,
107         int                     datasync)
108 {
109         struct inode            *inode = file->f_mapping->host;
110         struct xfs_inode        *ip = XFS_I(inode);
111         struct xfs_mount        *mp = ip->i_mount;
112         int                     error = 0;
113         int                     log_flushed = 0;
114         xfs_lsn_t               lsn = 0;
115
116         trace_xfs_file_fsync(ip);
117
118         error = file_write_and_wait_range(file, start, end);
119         if (error)
120                 return error;
121
122         if (XFS_FORCED_SHUTDOWN(mp))
123                 return -EIO;
124
125         xfs_iflags_clear(ip, XFS_ITRUNCATED);
126
127         /*
128          * If we have an RT and/or log subvolume we need to make sure to flush
129          * the write cache the device used for file data first.  This is to
130          * ensure newly written file data make it to disk before logging the new
131          * inode size in case of an extending write.
132          */
133         if (XFS_IS_REALTIME_INODE(ip))
134                 xfs_blkdev_issue_flush(mp->m_rtdev_targp);
135         else if (mp->m_logdev_targp != mp->m_ddev_targp)
136                 xfs_blkdev_issue_flush(mp->m_ddev_targp);
137
138         /*
139          * All metadata updates are logged, which means that we just have to
140          * flush the log up to the latest LSN that touched the inode. If we have
141          * concurrent fsync/fdatasync() calls, we need them to all block on the
142          * log force before we clear the ili_fsync_fields field. This ensures
143          * that we don't get a racing sync operation that does not wait for the
144          * metadata to hit the journal before returning. If we race with
145          * clearing the ili_fsync_fields, then all that will happen is the log
146          * force will do nothing as the lsn will already be on disk. We can't
147          * race with setting ili_fsync_fields because that is done under
148          * XFS_ILOCK_EXCL, and that can't happen because we hold the lock shared
149          * until after the ili_fsync_fields is cleared.
150          */
151         xfs_ilock(ip, XFS_ILOCK_SHARED);
152         if (xfs_ipincount(ip)) {
153                 if (!datasync ||
154                     (ip->i_itemp->ili_fsync_fields & ~XFS_ILOG_TIMESTAMP))
155                         lsn = ip->i_itemp->ili_last_lsn;
156         }
157
158         if (lsn) {
159                 error = xfs_log_force_lsn(mp, lsn, XFS_LOG_SYNC, &log_flushed);
160                 ip->i_itemp->ili_fsync_fields = 0;
161         }
162         xfs_iunlock(ip, XFS_ILOCK_SHARED);
163
164         /*
165          * If we only have a single device, and the log force about was
166          * a no-op we might have to flush the data device cache here.
167          * This can only happen for fdatasync/O_DSYNC if we were overwriting
168          * an already allocated file and thus do not have any metadata to
169          * commit.
170          */
171         if (!log_flushed && !XFS_IS_REALTIME_INODE(ip) &&
172             mp->m_logdev_targp == mp->m_ddev_targp)
173                 xfs_blkdev_issue_flush(mp->m_ddev_targp);
174
175         return error;
176 }
177
178 STATIC ssize_t
179 xfs_file_dio_aio_read(
180         struct kiocb            *iocb,
181         struct iov_iter         *to)
182 {
183         struct xfs_inode        *ip = XFS_I(file_inode(iocb->ki_filp));
184         size_t                  count = iov_iter_count(to);
185         ssize_t                 ret;
186
187         trace_xfs_file_direct_read(ip, count, iocb->ki_pos);
188
189         if (!count)
190                 return 0; /* skip atime */
191
192         file_accessed(iocb->ki_filp);
193
194         xfs_ilock(ip, XFS_IOLOCK_SHARED);
195         ret = iomap_dio_rw(iocb, to, &xfs_iomap_ops, NULL);
196         xfs_iunlock(ip, XFS_IOLOCK_SHARED);
197
198         return ret;
199 }
200
201 static noinline ssize_t
202 xfs_file_dax_read(
203         struct kiocb            *iocb,
204         struct iov_iter         *to)
205 {
206         struct xfs_inode        *ip = XFS_I(iocb->ki_filp->f_mapping->host);
207         size_t                  count = iov_iter_count(to);
208         ssize_t                 ret = 0;
209
210         trace_xfs_file_dax_read(ip, count, iocb->ki_pos);
211
212         if (!count)
213                 return 0; /* skip atime */
214
215         if (iocb->ki_flags & IOCB_NOWAIT) {
216                 if (!xfs_ilock_nowait(ip, XFS_IOLOCK_SHARED))
217                         return -EAGAIN;
218         } else {
219                 xfs_ilock(ip, XFS_IOLOCK_SHARED);
220         }
221
222         ret = dax_iomap_rw(iocb, to, &xfs_iomap_ops);
223         xfs_iunlock(ip, XFS_IOLOCK_SHARED);
224
225         file_accessed(iocb->ki_filp);
226         return ret;
227 }
228
229 STATIC ssize_t
230 xfs_file_buffered_aio_read(
231         struct kiocb            *iocb,
232         struct iov_iter         *to)
233 {
234         struct xfs_inode        *ip = XFS_I(file_inode(iocb->ki_filp));
235         ssize_t                 ret;
236
237         trace_xfs_file_buffered_read(ip, iov_iter_count(to), iocb->ki_pos);
238
239         if (iocb->ki_flags & IOCB_NOWAIT) {
240                 if (!xfs_ilock_nowait(ip, XFS_IOLOCK_SHARED))
241                         return -EAGAIN;
242         } else {
243                 xfs_ilock(ip, XFS_IOLOCK_SHARED);
244         }
245         ret = generic_file_read_iter(iocb, to);
246         xfs_iunlock(ip, XFS_IOLOCK_SHARED);
247
248         return ret;
249 }
250
251 STATIC ssize_t
252 xfs_file_read_iter(
253         struct kiocb            *iocb,
254         struct iov_iter         *to)
255 {
256         struct inode            *inode = file_inode(iocb->ki_filp);
257         struct xfs_mount        *mp = XFS_I(inode)->i_mount;
258         ssize_t                 ret = 0;
259
260         XFS_STATS_INC(mp, xs_read_calls);
261
262         if (XFS_FORCED_SHUTDOWN(mp))
263                 return -EIO;
264
265         if (IS_DAX(inode))
266                 ret = xfs_file_dax_read(iocb, to);
267         else if (iocb->ki_flags & IOCB_DIRECT)
268                 ret = xfs_file_dio_aio_read(iocb, to);
269         else
270                 ret = xfs_file_buffered_aio_read(iocb, to);
271
272         if (ret > 0)
273                 XFS_STATS_ADD(mp, xs_read_bytes, ret);
274         return ret;
275 }
276
277 /*
278  * Common pre-write limit and setup checks.
279  *
280  * Called with the iolocked held either shared and exclusive according to
281  * @iolock, and returns with it held.  Might upgrade the iolock to exclusive
282  * if called for a direct write beyond i_size.
283  */
284 STATIC ssize_t
285 xfs_file_aio_write_checks(
286         struct kiocb            *iocb,
287         struct iov_iter         *from,
288         int                     *iolock)
289 {
290         struct file             *file = iocb->ki_filp;
291         struct inode            *inode = file->f_mapping->host;
292         struct xfs_inode        *ip = XFS_I(inode);
293         ssize_t                 error = 0;
294         size_t                  count = iov_iter_count(from);
295         bool                    drained_dio = false;
296         loff_t                  isize;
297
298 restart:
299         error = generic_write_checks(iocb, from);
300         if (error <= 0)
301                 return error;
302
303         error = xfs_break_layouts(inode, iolock, BREAK_WRITE);
304         if (error)
305                 return error;
306
307         /*
308          * For changing security info in file_remove_privs() we need i_rwsem
309          * exclusively.
310          */
311         if (*iolock == XFS_IOLOCK_SHARED && !IS_NOSEC(inode)) {
312                 xfs_iunlock(ip, *iolock);
313                 *iolock = XFS_IOLOCK_EXCL;
314                 xfs_ilock(ip, *iolock);
315                 goto restart;
316         }
317         /*
318          * If the offset is beyond the size of the file, we need to zero any
319          * blocks that fall between the existing EOF and the start of this
320          * write.  If zeroing is needed and we are currently holding the
321          * iolock shared, we need to update it to exclusive which implies
322          * having to redo all checks before.
323          *
324          * We need to serialise against EOF updates that occur in IO
325          * completions here. We want to make sure that nobody is changing the
326          * size while we do this check until we have placed an IO barrier (i.e.
327          * hold the XFS_IOLOCK_EXCL) that prevents new IO from being dispatched.
328          * The spinlock effectively forms a memory barrier once we have the
329          * XFS_IOLOCK_EXCL so we are guaranteed to see the latest EOF value
330          * and hence be able to correctly determine if we need to run zeroing.
331          */
332         spin_lock(&ip->i_flags_lock);
333         isize = i_size_read(inode);
334         if (iocb->ki_pos > isize) {
335                 spin_unlock(&ip->i_flags_lock);
336                 if (!drained_dio) {
337                         if (*iolock == XFS_IOLOCK_SHARED) {
338                                 xfs_iunlock(ip, *iolock);
339                                 *iolock = XFS_IOLOCK_EXCL;
340                                 xfs_ilock(ip, *iolock);
341                                 iov_iter_reexpand(from, count);
342                         }
343                         /*
344                          * We now have an IO submission barrier in place, but
345                          * AIO can do EOF updates during IO completion and hence
346                          * we now need to wait for all of them to drain. Non-AIO
347                          * DIO will have drained before we are given the
348                          * XFS_IOLOCK_EXCL, and so for most cases this wait is a
349                          * no-op.
350                          */
351                         inode_dio_wait(inode);
352                         drained_dio = true;
353                         goto restart;
354                 }
355         
356                 trace_xfs_zero_eof(ip, isize, iocb->ki_pos - isize);
357                 error = iomap_zero_range(inode, isize, iocb->ki_pos - isize,
358                                 NULL, &xfs_iomap_ops);
359                 if (error)
360                         return error;
361         } else
362                 spin_unlock(&ip->i_flags_lock);
363
364         /*
365          * Updating the timestamps will grab the ilock again from
366          * xfs_fs_dirty_inode, so we have to call it after dropping the
367          * lock above.  Eventually we should look into a way to avoid
368          * the pointless lock roundtrip.
369          */
370         return file_modified(file);
371 }
372
373 static int
374 xfs_dio_write_end_io(
375         struct kiocb            *iocb,
376         ssize_t                 size,
377         unsigned                flags)
378 {
379         struct inode            *inode = file_inode(iocb->ki_filp);
380         struct xfs_inode        *ip = XFS_I(inode);
381         loff_t                  offset = iocb->ki_pos;
382         int                     error = 0;
383
384         trace_xfs_end_io_direct_write(ip, offset, size);
385
386         if (XFS_FORCED_SHUTDOWN(ip->i_mount))
387                 return -EIO;
388
389         if (size <= 0)
390                 return size;
391
392         /*
393          * Capture amount written on completion as we can't reliably account
394          * for it on submission.
395          */
396         XFS_STATS_ADD(ip->i_mount, xs_write_bytes, size);
397
398         if (flags & IOMAP_DIO_COW) {
399                 error = xfs_reflink_end_cow(ip, offset, size);
400                 if (error)
401                         return error;
402         }
403
404         /*
405          * Unwritten conversion updates the in-core isize after extent
406          * conversion but before updating the on-disk size. Updating isize any
407          * earlier allows a racing dio read to find unwritten extents before
408          * they are converted.
409          */
410         if (flags & IOMAP_DIO_UNWRITTEN)
411                 return xfs_iomap_write_unwritten(ip, offset, size, true);
412
413         /*
414          * We need to update the in-core inode size here so that we don't end up
415          * with the on-disk inode size being outside the in-core inode size. We
416          * have no other method of updating EOF for AIO, so always do it here
417          * if necessary.
418          *
419          * We need to lock the test/set EOF update as we can be racing with
420          * other IO completions here to update the EOF. Failing to serialise
421          * here can result in EOF moving backwards and Bad Things Happen when
422          * that occurs.
423          */
424         spin_lock(&ip->i_flags_lock);
425         if (offset + size > i_size_read(inode)) {
426                 i_size_write(inode, offset + size);
427                 spin_unlock(&ip->i_flags_lock);
428                 error = xfs_setfilesize(ip, offset, size);
429         } else {
430                 spin_unlock(&ip->i_flags_lock);
431         }
432
433         return error;
434 }
435
436 /*
437  * xfs_file_dio_aio_write - handle direct IO writes
438  *
439  * Lock the inode appropriately to prepare for and issue a direct IO write.
440  * By separating it from the buffered write path we remove all the tricky to
441  * follow locking changes and looping.
442  *
443  * If there are cached pages or we're extending the file, we need IOLOCK_EXCL
444  * until we're sure the bytes at the new EOF have been zeroed and/or the cached
445  * pages are flushed out.
446  *
447  * In most cases the direct IO writes will be done holding IOLOCK_SHARED
448  * allowing them to be done in parallel with reads and other direct IO writes.
449  * However, if the IO is not aligned to filesystem blocks, the direct IO layer
450  * needs to do sub-block zeroing and that requires serialisation against other
451  * direct IOs to the same block. In this case we need to serialise the
452  * submission of the unaligned IOs so that we don't get racing block zeroing in
453  * the dio layer.  To avoid the problem with aio, we also need to wait for
454  * outstanding IOs to complete so that unwritten extent conversion is completed
455  * before we try to map the overlapping block. This is currently implemented by
456  * hitting it with a big hammer (i.e. inode_dio_wait()).
457  *
458  * Returns with locks held indicated by @iolock and errors indicated by
459  * negative return values.
460  */
461 STATIC ssize_t
462 xfs_file_dio_aio_write(
463         struct kiocb            *iocb,
464         struct iov_iter         *from)
465 {
466         struct file             *file = iocb->ki_filp;
467         struct address_space    *mapping = file->f_mapping;
468         struct inode            *inode = mapping->host;
469         struct xfs_inode        *ip = XFS_I(inode);
470         struct xfs_mount        *mp = ip->i_mount;
471         ssize_t                 ret = 0;
472         int                     unaligned_io = 0;
473         int                     iolock;
474         size_t                  count = iov_iter_count(from);
475         struct xfs_buftarg      *target = XFS_IS_REALTIME_INODE(ip) ?
476                                         mp->m_rtdev_targp : mp->m_ddev_targp;
477
478         /* DIO must be aligned to device logical sector size */
479         if ((iocb->ki_pos | count) & target->bt_logical_sectormask)
480                 return -EINVAL;
481
482         /*
483          * Don't take the exclusive iolock here unless the I/O is unaligned to
484          * the file system block size.  We don't need to consider the EOF
485          * extension case here because xfs_file_aio_write_checks() will relock
486          * the inode as necessary for EOF zeroing cases and fill out the new
487          * inode size as appropriate.
488          */
489         if ((iocb->ki_pos & mp->m_blockmask) ||
490             ((iocb->ki_pos + count) & mp->m_blockmask)) {
491                 unaligned_io = 1;
492
493                 /*
494                  * We can't properly handle unaligned direct I/O to reflink
495                  * files yet, as we can't unshare a partial block.
496                  */
497                 if (xfs_is_cow_inode(ip)) {
498                         trace_xfs_reflink_bounce_dio_write(ip, iocb->ki_pos, count);
499                         return -EREMCHG;
500                 }
501                 iolock = XFS_IOLOCK_EXCL;
502         } else {
503                 iolock = XFS_IOLOCK_SHARED;
504         }
505
506         if (iocb->ki_flags & IOCB_NOWAIT) {
507                 /* unaligned dio always waits, bail */
508                 if (unaligned_io)
509                         return -EAGAIN;
510                 if (!xfs_ilock_nowait(ip, iolock))
511                         return -EAGAIN;
512         } else {
513                 xfs_ilock(ip, iolock);
514         }
515
516         ret = xfs_file_aio_write_checks(iocb, from, &iolock);
517         if (ret)
518                 goto out;
519         count = iov_iter_count(from);
520
521         /*
522          * If we are doing unaligned IO, we can't allow any other overlapping IO
523          * in-flight at the same time or we risk data corruption. Wait for all
524          * other IO to drain before we submit. If the IO is aligned, demote the
525          * iolock if we had to take the exclusive lock in
526          * xfs_file_aio_write_checks() for other reasons.
527          */
528         if (unaligned_io) {
529                 inode_dio_wait(inode);
530         } else if (iolock == XFS_IOLOCK_EXCL) {
531                 xfs_ilock_demote(ip, XFS_IOLOCK_EXCL);
532                 iolock = XFS_IOLOCK_SHARED;
533         }
534
535         trace_xfs_file_direct_write(ip, count, iocb->ki_pos);
536         ret = iomap_dio_rw(iocb, from, &xfs_iomap_ops, xfs_dio_write_end_io);
537
538         /*
539          * If unaligned, this is the only IO in-flight. If it has not yet
540          * completed, wait on it before we release the iolock to prevent
541          * subsequent overlapping IO.
542          */
543         if (ret == -EIOCBQUEUED && unaligned_io)
544                 inode_dio_wait(inode);
545 out:
546         xfs_iunlock(ip, iolock);
547
548         /*
549          * No fallback to buffered IO on errors for XFS, direct IO will either
550          * complete fully or fail.
551          */
552         ASSERT(ret < 0 || ret == count);
553         return ret;
554 }
555
556 static noinline ssize_t
557 xfs_file_dax_write(
558         struct kiocb            *iocb,
559         struct iov_iter         *from)
560 {
561         struct inode            *inode = iocb->ki_filp->f_mapping->host;
562         struct xfs_inode        *ip = XFS_I(inode);
563         int                     iolock = XFS_IOLOCK_EXCL;
564         ssize_t                 ret, error = 0;
565         size_t                  count;
566         loff_t                  pos;
567
568         if (iocb->ki_flags & IOCB_NOWAIT) {
569                 if (!xfs_ilock_nowait(ip, iolock))
570                         return -EAGAIN;
571         } else {
572                 xfs_ilock(ip, iolock);
573         }
574
575         ret = xfs_file_aio_write_checks(iocb, from, &iolock);
576         if (ret)
577                 goto out;
578
579         pos = iocb->ki_pos;
580         count = iov_iter_count(from);
581
582         trace_xfs_file_dax_write(ip, count, pos);
583         ret = dax_iomap_rw(iocb, from, &xfs_iomap_ops);
584         if (ret > 0 && iocb->ki_pos > i_size_read(inode)) {
585                 i_size_write(inode, iocb->ki_pos);
586                 error = xfs_setfilesize(ip, pos, ret);
587         }
588 out:
589         xfs_iunlock(ip, iolock);
590         if (error)
591                 return error;
592
593         if (ret > 0) {
594                 XFS_STATS_ADD(ip->i_mount, xs_write_bytes, ret);
595
596                 /* Handle various SYNC-type writes */
597                 ret = generic_write_sync(iocb, ret);
598         }
599         return ret;
600 }
601
602 STATIC ssize_t
603 xfs_file_buffered_aio_write(
604         struct kiocb            *iocb,
605         struct iov_iter         *from)
606 {
607         struct file             *file = iocb->ki_filp;
608         struct address_space    *mapping = file->f_mapping;
609         struct inode            *inode = mapping->host;
610         struct xfs_inode        *ip = XFS_I(inode);
611         ssize_t                 ret;
612         int                     enospc = 0;
613         int                     iolock;
614
615         if (iocb->ki_flags & IOCB_NOWAIT)
616                 return -EOPNOTSUPP;
617
618 write_retry:
619         iolock = XFS_IOLOCK_EXCL;
620         xfs_ilock(ip, iolock);
621
622         ret = xfs_file_aio_write_checks(iocb, from, &iolock);
623         if (ret)
624                 goto out;
625
626         /* We can write back this queue in page reclaim */
627         current->backing_dev_info = inode_to_bdi(inode);
628
629         trace_xfs_file_buffered_write(ip, iov_iter_count(from), iocb->ki_pos);
630         ret = iomap_file_buffered_write(iocb, from, &xfs_iomap_ops);
631         if (likely(ret >= 0))
632                 iocb->ki_pos += ret;
633
634         /*
635          * If we hit a space limit, try to free up some lingering preallocated
636          * space before returning an error. In the case of ENOSPC, first try to
637          * write back all dirty inodes to free up some of the excess reserved
638          * metadata space. This reduces the chances that the eofblocks scan
639          * waits on dirty mappings. Since xfs_flush_inodes() is serialized, this
640          * also behaves as a filter to prevent too many eofblocks scans from
641          * running at the same time.
642          */
643         if (ret == -EDQUOT && !enospc) {
644                 xfs_iunlock(ip, iolock);
645                 enospc = xfs_inode_free_quota_eofblocks(ip);
646                 if (enospc)
647                         goto write_retry;
648                 enospc = xfs_inode_free_quota_cowblocks(ip);
649                 if (enospc)
650                         goto write_retry;
651                 iolock = 0;
652         } else if (ret == -ENOSPC && !enospc) {
653                 struct xfs_eofblocks eofb = {0};
654
655                 enospc = 1;
656                 xfs_flush_inodes(ip->i_mount);
657
658                 xfs_iunlock(ip, iolock);
659                 eofb.eof_flags = XFS_EOF_FLAGS_SYNC;
660                 xfs_icache_free_eofblocks(ip->i_mount, &eofb);
661                 xfs_icache_free_cowblocks(ip->i_mount, &eofb);
662                 goto write_retry;
663         }
664
665         current->backing_dev_info = NULL;
666 out:
667         if (iolock)
668                 xfs_iunlock(ip, iolock);
669
670         if (ret > 0) {
671                 XFS_STATS_ADD(ip->i_mount, xs_write_bytes, ret);
672                 /* Handle various SYNC-type writes */
673                 ret = generic_write_sync(iocb, ret);
674         }
675         return ret;
676 }
677
678 STATIC ssize_t
679 xfs_file_write_iter(
680         struct kiocb            *iocb,
681         struct iov_iter         *from)
682 {
683         struct file             *file = iocb->ki_filp;
684         struct address_space    *mapping = file->f_mapping;
685         struct inode            *inode = mapping->host;
686         struct xfs_inode        *ip = XFS_I(inode);
687         ssize_t                 ret;
688         size_t                  ocount = iov_iter_count(from);
689
690         XFS_STATS_INC(ip->i_mount, xs_write_calls);
691
692         if (ocount == 0)
693                 return 0;
694
695         if (XFS_FORCED_SHUTDOWN(ip->i_mount))
696                 return -EIO;
697
698         if (IS_DAX(inode))
699                 return xfs_file_dax_write(iocb, from);
700
701         if (iocb->ki_flags & IOCB_DIRECT) {
702                 /*
703                  * Allow a directio write to fall back to a buffered
704                  * write *only* in the case that we're doing a reflink
705                  * CoW.  In all other directio scenarios we do not
706                  * allow an operation to fall back to buffered mode.
707                  */
708                 ret = xfs_file_dio_aio_write(iocb, from);
709                 if (ret != -EREMCHG)
710                         return ret;
711         }
712
713         return xfs_file_buffered_aio_write(iocb, from);
714 }
715
716 static void
717 xfs_wait_dax_page(
718         struct inode            *inode)
719 {
720         struct xfs_inode        *ip = XFS_I(inode);
721
722         xfs_iunlock(ip, XFS_MMAPLOCK_EXCL);
723         schedule();
724         xfs_ilock(ip, XFS_MMAPLOCK_EXCL);
725 }
726
727 static int
728 xfs_break_dax_layouts(
729         struct inode            *inode,
730         bool                    *retry)
731 {
732         struct page             *page;
733
734         ASSERT(xfs_isilocked(XFS_I(inode), XFS_MMAPLOCK_EXCL));
735
736         page = dax_layout_busy_page(inode->i_mapping);
737         if (!page)
738                 return 0;
739
740         *retry = true;
741         return ___wait_var_event(&page->_refcount,
742                         atomic_read(&page->_refcount) == 1, TASK_INTERRUPTIBLE,
743                         0, 0, xfs_wait_dax_page(inode));
744 }
745
746 int
747 xfs_break_layouts(
748         struct inode            *inode,
749         uint                    *iolock,
750         enum layout_break_reason reason)
751 {
752         bool                    retry;
753         int                     error;
754
755         ASSERT(xfs_isilocked(XFS_I(inode), XFS_IOLOCK_SHARED|XFS_IOLOCK_EXCL));
756
757         do {
758                 retry = false;
759                 switch (reason) {
760                 case BREAK_UNMAP:
761                         error = xfs_break_dax_layouts(inode, &retry);
762                         if (error || retry)
763                                 break;
764                         /* fall through */
765                 case BREAK_WRITE:
766                         error = xfs_break_leased_layouts(inode, iolock, &retry);
767                         break;
768                 default:
769                         WARN_ON_ONCE(1);
770                         error = -EINVAL;
771                 }
772         } while (error == 0 && retry);
773
774         return error;
775 }
776
777 #define XFS_FALLOC_FL_SUPPORTED                                         \
778                 (FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE |           \
779                  FALLOC_FL_COLLAPSE_RANGE | FALLOC_FL_ZERO_RANGE |      \
780                  FALLOC_FL_INSERT_RANGE | FALLOC_FL_UNSHARE_RANGE)
781
782 STATIC long
783 xfs_file_fallocate(
784         struct file             *file,
785         int                     mode,
786         loff_t                  offset,
787         loff_t                  len)
788 {
789         struct inode            *inode = file_inode(file);
790         struct xfs_inode        *ip = XFS_I(inode);
791         long                    error;
792         enum xfs_prealloc_flags flags = 0;
793         uint                    iolock = XFS_IOLOCK_EXCL | XFS_MMAPLOCK_EXCL;
794         loff_t                  new_size = 0;
795         bool                    do_file_insert = false;
796
797         if (!S_ISREG(inode->i_mode))
798                 return -EINVAL;
799         if (mode & ~XFS_FALLOC_FL_SUPPORTED)
800                 return -EOPNOTSUPP;
801
802         xfs_ilock(ip, iolock);
803         error = xfs_break_layouts(inode, &iolock, BREAK_UNMAP);
804         if (error)
805                 goto out_unlock;
806
807         if (mode & FALLOC_FL_PUNCH_HOLE) {
808                 error = xfs_free_file_space(ip, offset, len);
809                 if (error)
810                         goto out_unlock;
811         } else if (mode & FALLOC_FL_COLLAPSE_RANGE) {
812                 unsigned int blksize_mask = i_blocksize(inode) - 1;
813
814                 if (offset & blksize_mask || len & blksize_mask) {
815                         error = -EINVAL;
816                         goto out_unlock;
817                 }
818
819                 /*
820                  * There is no need to overlap collapse range with EOF,
821                  * in which case it is effectively a truncate operation
822                  */
823                 if (offset + len >= i_size_read(inode)) {
824                         error = -EINVAL;
825                         goto out_unlock;
826                 }
827
828                 new_size = i_size_read(inode) - len;
829
830                 error = xfs_collapse_file_space(ip, offset, len);
831                 if (error)
832                         goto out_unlock;
833         } else if (mode & FALLOC_FL_INSERT_RANGE) {
834                 unsigned int    blksize_mask = i_blocksize(inode) - 1;
835                 loff_t          isize = i_size_read(inode);
836
837                 if (offset & blksize_mask || len & blksize_mask) {
838                         error = -EINVAL;
839                         goto out_unlock;
840                 }
841
842                 /*
843                  * New inode size must not exceed ->s_maxbytes, accounting for
844                  * possible signed overflow.
845                  */
846                 if (inode->i_sb->s_maxbytes - isize < len) {
847                         error = -EFBIG;
848                         goto out_unlock;
849                 }
850                 new_size = isize + len;
851
852                 /* Offset should be less than i_size */
853                 if (offset >= isize) {
854                         error = -EINVAL;
855                         goto out_unlock;
856                 }
857                 do_file_insert = true;
858         } else {
859                 flags |= XFS_PREALLOC_SET;
860
861                 if (!(mode & FALLOC_FL_KEEP_SIZE) &&
862                     offset + len > i_size_read(inode)) {
863                         new_size = offset + len;
864                         error = inode_newsize_ok(inode, new_size);
865                         if (error)
866                                 goto out_unlock;
867                 }
868
869                 if (mode & FALLOC_FL_ZERO_RANGE) {
870                         error = xfs_zero_file_space(ip, offset, len);
871                 } else if (mode & FALLOC_FL_UNSHARE_RANGE) {
872                         error = xfs_reflink_unshare(ip, offset, len);
873                         if (error)
874                                 goto out_unlock;
875
876                         if (!xfs_is_always_cow_inode(ip)) {
877                                 error = xfs_alloc_file_space(ip, offset, len,
878                                                 XFS_BMAPI_PREALLOC);
879                         }
880                 } else {
881                         /*
882                          * If always_cow mode we can't use preallocations and
883                          * thus should not create them.
884                          */
885                         if (xfs_is_always_cow_inode(ip)) {
886                                 error = -EOPNOTSUPP;
887                                 goto out_unlock;
888                         }
889
890                         error = xfs_alloc_file_space(ip, offset, len,
891                                                      XFS_BMAPI_PREALLOC);
892                 }
893                 if (error)
894                         goto out_unlock;
895         }
896
897         if (file->f_flags & O_DSYNC)
898                 flags |= XFS_PREALLOC_SYNC;
899
900         error = xfs_update_prealloc_flags(ip, flags);
901         if (error)
902                 goto out_unlock;
903
904         /* Change file size if needed */
905         if (new_size) {
906                 struct iattr iattr;
907
908                 iattr.ia_valid = ATTR_SIZE;
909                 iattr.ia_size = new_size;
910                 error = xfs_vn_setattr_size(file_dentry(file), &iattr);
911                 if (error)
912                         goto out_unlock;
913         }
914
915         /*
916          * Perform hole insertion now that the file size has been
917          * updated so that if we crash during the operation we don't
918          * leave shifted extents past EOF and hence losing access to
919          * the data that is contained within them.
920          */
921         if (do_file_insert)
922                 error = xfs_insert_file_space(ip, offset, len);
923
924 out_unlock:
925         xfs_iunlock(ip, iolock);
926         return error;
927 }
928
929
930 STATIC loff_t
931 xfs_file_remap_range(
932         struct file             *file_in,
933         loff_t                  pos_in,
934         struct file             *file_out,
935         loff_t                  pos_out,
936         loff_t                  len,
937         unsigned int            remap_flags)
938 {
939         struct inode            *inode_in = file_inode(file_in);
940         struct xfs_inode        *src = XFS_I(inode_in);
941         struct inode            *inode_out = file_inode(file_out);
942         struct xfs_inode        *dest = XFS_I(inode_out);
943         struct xfs_mount        *mp = src->i_mount;
944         loff_t                  remapped = 0;
945         xfs_extlen_t            cowextsize;
946         int                     ret;
947
948         if (remap_flags & ~(REMAP_FILE_DEDUP | REMAP_FILE_ADVISORY))
949                 return -EINVAL;
950
951         if (!xfs_sb_version_hasreflink(&mp->m_sb))
952                 return -EOPNOTSUPP;
953
954         if (XFS_FORCED_SHUTDOWN(mp))
955                 return -EIO;
956
957         /* Prepare and then clone file data. */
958         ret = xfs_reflink_remap_prep(file_in, pos_in, file_out, pos_out,
959                         &len, remap_flags);
960         if (ret < 0 || len == 0)
961                 return ret;
962
963         trace_xfs_reflink_remap_range(src, pos_in, len, dest, pos_out);
964
965         ret = xfs_reflink_remap_blocks(src, pos_in, dest, pos_out, len,
966                         &remapped);
967         if (ret)
968                 goto out_unlock;
969
970         /*
971          * Carry the cowextsize hint from src to dest if we're sharing the
972          * entire source file to the entire destination file, the source file
973          * has a cowextsize hint, and the destination file does not.
974          */
975         cowextsize = 0;
976         if (pos_in == 0 && len == i_size_read(inode_in) &&
977             (src->i_d.di_flags2 & XFS_DIFLAG2_COWEXTSIZE) &&
978             pos_out == 0 && len >= i_size_read(inode_out) &&
979             !(dest->i_d.di_flags2 & XFS_DIFLAG2_COWEXTSIZE))
980                 cowextsize = src->i_d.di_cowextsize;
981
982         ret = xfs_reflink_update_dest(dest, pos_out + len, cowextsize,
983                         remap_flags);
984
985 out_unlock:
986         xfs_reflink_remap_unlock(file_in, file_out);
987         if (ret)
988                 trace_xfs_reflink_remap_range_error(dest, ret, _RET_IP_);
989         return remapped > 0 ? remapped : ret;
990 }
991
992 STATIC int
993 xfs_file_open(
994         struct inode    *inode,
995         struct file     *file)
996 {
997         if (!(file->f_flags & O_LARGEFILE) && i_size_read(inode) > MAX_NON_LFS)
998                 return -EFBIG;
999         if (XFS_FORCED_SHUTDOWN(XFS_M(inode->i_sb)))
1000                 return -EIO;
1001         file->f_mode |= FMODE_NOWAIT;
1002         return 0;
1003 }
1004
1005 STATIC int
1006 xfs_dir_open(
1007         struct inode    *inode,
1008         struct file     *file)
1009 {
1010         struct xfs_inode *ip = XFS_I(inode);
1011         int             mode;
1012         int             error;
1013
1014         error = xfs_file_open(inode, file);
1015         if (error)
1016                 return error;
1017
1018         /*
1019          * If there are any blocks, read-ahead block 0 as we're almost
1020          * certain to have the next operation be a read there.
1021          */
1022         mode = xfs_ilock_data_map_shared(ip);
1023         if (ip->i_d.di_nextents > 0)
1024                 error = xfs_dir3_data_readahead(ip, 0, -1);
1025         xfs_iunlock(ip, mode);
1026         return error;
1027 }
1028
1029 STATIC int
1030 xfs_file_release(
1031         struct inode    *inode,
1032         struct file     *filp)
1033 {
1034         return xfs_release(XFS_I(inode));
1035 }
1036
1037 STATIC int
1038 xfs_file_readdir(
1039         struct file     *file,
1040         struct dir_context *ctx)
1041 {
1042         struct inode    *inode = file_inode(file);
1043         xfs_inode_t     *ip = XFS_I(inode);
1044         size_t          bufsize;
1045
1046         /*
1047          * The Linux API doesn't pass down the total size of the buffer
1048          * we read into down to the filesystem.  With the filldir concept
1049          * it's not needed for correct information, but the XFS dir2 leaf
1050          * code wants an estimate of the buffer size to calculate it's
1051          * readahead window and size the buffers used for mapping to
1052          * physical blocks.
1053          *
1054          * Try to give it an estimate that's good enough, maybe at some
1055          * point we can change the ->readdir prototype to include the
1056          * buffer size.  For now we use the current glibc buffer size.
1057          */
1058         bufsize = (size_t)min_t(loff_t, XFS_READDIR_BUFSIZE, ip->i_d.di_size);
1059
1060         return xfs_readdir(NULL, ip, ctx, bufsize);
1061 }
1062
1063 STATIC loff_t
1064 xfs_file_llseek(
1065         struct file     *file,
1066         loff_t          offset,
1067         int             whence)
1068 {
1069         struct inode            *inode = file->f_mapping->host;
1070
1071         if (XFS_FORCED_SHUTDOWN(XFS_I(inode)->i_mount))
1072                 return -EIO;
1073
1074         switch (whence) {
1075         default:
1076                 return generic_file_llseek(file, offset, whence);
1077         case SEEK_HOLE:
1078                 offset = iomap_seek_hole(inode, offset, &xfs_seek_iomap_ops);
1079                 break;
1080         case SEEK_DATA:
1081                 offset = iomap_seek_data(inode, offset, &xfs_seek_iomap_ops);
1082                 break;
1083         }
1084
1085         if (offset < 0)
1086                 return offset;
1087         return vfs_setpos(file, offset, inode->i_sb->s_maxbytes);
1088 }
1089
1090 /*
1091  * Locking for serialisation of IO during page faults. This results in a lock
1092  * ordering of:
1093  *
1094  * mmap_sem (MM)
1095  *   sb_start_pagefault(vfs, freeze)
1096  *     i_mmaplock (XFS - truncate serialisation)
1097  *       page_lock (MM)
1098  *         i_lock (XFS - extent map serialisation)
1099  */
1100 static vm_fault_t
1101 __xfs_filemap_fault(
1102         struct vm_fault         *vmf,
1103         enum page_entry_size    pe_size,
1104         bool                    write_fault)
1105 {
1106         struct inode            *inode = file_inode(vmf->vma->vm_file);
1107         struct xfs_inode        *ip = XFS_I(inode);
1108         vm_fault_t              ret;
1109
1110         trace_xfs_filemap_fault(ip, pe_size, write_fault);
1111
1112         if (write_fault) {
1113                 sb_start_pagefault(inode->i_sb);
1114                 file_update_time(vmf->vma->vm_file);
1115         }
1116
1117         xfs_ilock(XFS_I(inode), XFS_MMAPLOCK_SHARED);
1118         if (IS_DAX(inode)) {
1119                 pfn_t pfn;
1120
1121                 ret = dax_iomap_fault(vmf, pe_size, &pfn, NULL, &xfs_iomap_ops);
1122                 if (ret & VM_FAULT_NEEDDSYNC)
1123                         ret = dax_finish_sync_fault(vmf, pe_size, pfn);
1124         } else {
1125                 if (write_fault)
1126                         ret = iomap_page_mkwrite(vmf, &xfs_iomap_ops);
1127                 else
1128                         ret = filemap_fault(vmf);
1129         }
1130         xfs_iunlock(XFS_I(inode), XFS_MMAPLOCK_SHARED);
1131
1132         if (write_fault)
1133                 sb_end_pagefault(inode->i_sb);
1134         return ret;
1135 }
1136
1137 static vm_fault_t
1138 xfs_filemap_fault(
1139         struct vm_fault         *vmf)
1140 {
1141         /* DAX can shortcut the normal fault path on write faults! */
1142         return __xfs_filemap_fault(vmf, PE_SIZE_PTE,
1143                         IS_DAX(file_inode(vmf->vma->vm_file)) &&
1144                         (vmf->flags & FAULT_FLAG_WRITE));
1145 }
1146
1147 static vm_fault_t
1148 xfs_filemap_huge_fault(
1149         struct vm_fault         *vmf,
1150         enum page_entry_size    pe_size)
1151 {
1152         if (!IS_DAX(file_inode(vmf->vma->vm_file)))
1153                 return VM_FAULT_FALLBACK;
1154
1155         /* DAX can shortcut the normal fault path on write faults! */
1156         return __xfs_filemap_fault(vmf, pe_size,
1157                         (vmf->flags & FAULT_FLAG_WRITE));
1158 }
1159
1160 static vm_fault_t
1161 xfs_filemap_page_mkwrite(
1162         struct vm_fault         *vmf)
1163 {
1164         return __xfs_filemap_fault(vmf, PE_SIZE_PTE, true);
1165 }
1166
1167 /*
1168  * pfn_mkwrite was originally intended to ensure we capture time stamp updates
1169  * on write faults. In reality, it needs to serialise against truncate and
1170  * prepare memory for writing so handle is as standard write fault.
1171  */
1172 static vm_fault_t
1173 xfs_filemap_pfn_mkwrite(
1174         struct vm_fault         *vmf)
1175 {
1176
1177         return __xfs_filemap_fault(vmf, PE_SIZE_PTE, true);
1178 }
1179
1180 static const struct vm_operations_struct xfs_file_vm_ops = {
1181         .fault          = xfs_filemap_fault,
1182         .huge_fault     = xfs_filemap_huge_fault,
1183         .map_pages      = filemap_map_pages,
1184         .page_mkwrite   = xfs_filemap_page_mkwrite,
1185         .pfn_mkwrite    = xfs_filemap_pfn_mkwrite,
1186 };
1187
1188 STATIC int
1189 xfs_file_mmap(
1190         struct file     *filp,
1191         struct vm_area_struct *vma)
1192 {
1193         /*
1194          * We don't support synchronous mappings for non-DAX files. At least
1195          * until someone comes with a sensible use case.
1196          */
1197         if (!IS_DAX(file_inode(filp)) && (vma->vm_flags & VM_SYNC))
1198                 return -EOPNOTSUPP;
1199
1200         file_accessed(filp);
1201         vma->vm_ops = &xfs_file_vm_ops;
1202         if (IS_DAX(file_inode(filp)))
1203                 vma->vm_flags |= VM_HUGEPAGE;
1204         return 0;
1205 }
1206
1207 const struct file_operations xfs_file_operations = {
1208         .llseek         = xfs_file_llseek,
1209         .read_iter      = xfs_file_read_iter,
1210         .write_iter     = xfs_file_write_iter,
1211         .splice_read    = generic_file_splice_read,
1212         .splice_write   = iter_file_splice_write,
1213         .iopoll         = iomap_dio_iopoll,
1214         .unlocked_ioctl = xfs_file_ioctl,
1215 #ifdef CONFIG_COMPAT
1216         .compat_ioctl   = xfs_file_compat_ioctl,
1217 #endif
1218         .mmap           = xfs_file_mmap,
1219         .mmap_supported_flags = MAP_SYNC,
1220         .open           = xfs_file_open,
1221         .release        = xfs_file_release,
1222         .fsync          = xfs_file_fsync,
1223         .get_unmapped_area = thp_get_unmapped_area,
1224         .fallocate      = xfs_file_fallocate,
1225         .remap_file_range = xfs_file_remap_range,
1226 };
1227
1228 const struct file_operations xfs_dir_file_operations = {
1229         .open           = xfs_dir_open,
1230         .read           = generic_read_dir,
1231         .iterate_shared = xfs_file_readdir,
1232         .llseek         = generic_file_llseek,
1233         .unlocked_ioctl = xfs_file_ioctl,
1234 #ifdef CONFIG_COMPAT
1235         .compat_ioctl   = xfs_file_compat_ioctl,
1236 #endif
1237         .fsync          = xfs_dir_fsync,
1238 };