microblaze: fix __get_user()
[pandora-kernel.git] / fs / xfs / xfs_file.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_fs.h"
20 #include "xfs_bit.h"
21 #include "xfs_log.h"
22 #include "xfs_inum.h"
23 #include "xfs_sb.h"
24 #include "xfs_ag.h"
25 #include "xfs_trans.h"
26 #include "xfs_mount.h"
27 #include "xfs_bmap_btree.h"
28 #include "xfs_alloc.h"
29 #include "xfs_dinode.h"
30 #include "xfs_inode.h"
31 #include "xfs_inode_item.h"
32 #include "xfs_bmap.h"
33 #include "xfs_error.h"
34 #include "xfs_vnodeops.h"
35 #include "xfs_da_btree.h"
36 #include "xfs_ioctl.h"
37 #include "xfs_trace.h"
38
39 #include <linux/dcache.h>
40 #include <linux/falloc.h>
41
42 static const struct vm_operations_struct xfs_file_vm_ops;
43
44 /*
45  * Locking primitives for read and write IO paths to ensure we consistently use
46  * and order the inode->i_mutex, ip->i_lock and ip->i_iolock.
47  */
48 static inline void
49 xfs_rw_ilock(
50         struct xfs_inode        *ip,
51         int                     type)
52 {
53         if (type & XFS_IOLOCK_EXCL)
54                 mutex_lock(&VFS_I(ip)->i_mutex);
55         xfs_ilock(ip, type);
56 }
57
58 static inline void
59 xfs_rw_iunlock(
60         struct xfs_inode        *ip,
61         int                     type)
62 {
63         xfs_iunlock(ip, type);
64         if (type & XFS_IOLOCK_EXCL)
65                 mutex_unlock(&VFS_I(ip)->i_mutex);
66 }
67
68 static inline void
69 xfs_rw_ilock_demote(
70         struct xfs_inode        *ip,
71         int                     type)
72 {
73         xfs_ilock_demote(ip, type);
74         if (type & XFS_IOLOCK_EXCL)
75                 mutex_unlock(&VFS_I(ip)->i_mutex);
76 }
77
78 /*
79  *      xfs_iozero
80  *
81  *      xfs_iozero clears the specified range of buffer supplied,
82  *      and marks all the affected blocks as valid and modified.  If
83  *      an affected block is not allocated, it will be allocated.  If
84  *      an affected block is not completely overwritten, and is not
85  *      valid before the operation, it will be read from disk before
86  *      being partially zeroed.
87  */
88 STATIC int
89 xfs_iozero(
90         struct xfs_inode        *ip,    /* inode                        */
91         loff_t                  pos,    /* offset in file               */
92         size_t                  count)  /* size of data to zero         */
93 {
94         struct page             *page;
95         struct address_space    *mapping;
96         int                     status;
97
98         mapping = VFS_I(ip)->i_mapping;
99         do {
100                 unsigned offset, bytes;
101                 void *fsdata;
102
103                 offset = (pos & (PAGE_CACHE_SIZE -1)); /* Within page */
104                 bytes = PAGE_CACHE_SIZE - offset;
105                 if (bytes > count)
106                         bytes = count;
107
108                 status = pagecache_write_begin(NULL, mapping, pos, bytes,
109                                         AOP_FLAG_UNINTERRUPTIBLE,
110                                         &page, &fsdata);
111                 if (status)
112                         break;
113
114                 zero_user(page, offset, bytes);
115
116                 status = pagecache_write_end(NULL, mapping, pos, bytes, bytes,
117                                         page, fsdata);
118                 WARN_ON(status <= 0); /* can't return less than zero! */
119                 pos += bytes;
120                 count -= bytes;
121                 status = 0;
122         } while (count);
123
124         return (-status);
125 }
126
127 /*
128  * Fsync operations on directories are much simpler than on regular files,
129  * as there is no file data to flush, and thus also no need for explicit
130  * cache flush operations, and there are no non-transaction metadata updates
131  * on directories either.
132  */
133 STATIC int
134 xfs_dir_fsync(
135         struct file             *file,
136         loff_t                  start,
137         loff_t                  end,
138         int                     datasync)
139 {
140         struct xfs_inode        *ip = XFS_I(file->f_mapping->host);
141         struct xfs_mount        *mp = ip->i_mount;
142         xfs_lsn_t               lsn = 0;
143
144         trace_xfs_dir_fsync(ip);
145
146         xfs_ilock(ip, XFS_ILOCK_SHARED);
147         if (xfs_ipincount(ip))
148                 lsn = ip->i_itemp->ili_last_lsn;
149         xfs_iunlock(ip, XFS_ILOCK_SHARED);
150
151         if (!lsn)
152                 return 0;
153         return _xfs_log_force_lsn(mp, lsn, XFS_LOG_SYNC, NULL);
154 }
155
156 STATIC int
157 xfs_file_fsync(
158         struct file             *file,
159         loff_t                  start,
160         loff_t                  end,
161         int                     datasync)
162 {
163         struct inode            *inode = file->f_mapping->host;
164         struct xfs_inode        *ip = XFS_I(inode);
165         struct xfs_mount        *mp = ip->i_mount;
166         struct xfs_trans        *tp;
167         int                     error = 0;
168         int                     log_flushed = 0;
169         xfs_lsn_t               lsn = 0;
170
171         trace_xfs_file_fsync(ip);
172
173         error = filemap_write_and_wait_range(inode->i_mapping, start, end);
174         if (error)
175                 return error;
176
177         if (XFS_FORCED_SHUTDOWN(mp))
178                 return -XFS_ERROR(EIO);
179
180         xfs_iflags_clear(ip, XFS_ITRUNCATED);
181
182         if (mp->m_flags & XFS_MOUNT_BARRIER) {
183                 /*
184                  * If we have an RT and/or log subvolume we need to make sure
185                  * to flush the write cache the device used for file data
186                  * first.  This is to ensure newly written file data make
187                  * it to disk before logging the new inode size in case of
188                  * an extending write.
189                  */
190                 if (XFS_IS_REALTIME_INODE(ip))
191                         xfs_blkdev_issue_flush(mp->m_rtdev_targp);
192                 else if (mp->m_logdev_targp != mp->m_ddev_targp)
193                         xfs_blkdev_issue_flush(mp->m_ddev_targp);
194         }
195
196         /*
197          * We always need to make sure that the required inode state is safe on
198          * disk.  The inode might be clean but we still might need to force the
199          * log because of committed transactions that haven't hit the disk yet.
200          * Likewise, there could be unflushed non-transactional changes to the
201          * inode core that have to go to disk and this requires us to issue
202          * a synchronous transaction to capture these changes correctly.
203          *
204          * This code relies on the assumption that if the i_update_core field
205          * of the inode is clear and the inode is unpinned then it is clean
206          * and no action is required.
207          */
208         xfs_ilock(ip, XFS_ILOCK_SHARED);
209
210         /*
211          * First check if the VFS inode is marked dirty.  All the dirtying
212          * of non-transactional updates no goes through mark_inode_dirty*,
213          * which allows us to distinguish beteeen pure timestamp updates
214          * and i_size updates which need to be caught for fdatasync.
215          * After that also theck for the dirty state in the XFS inode, which
216          * might gets cleared when the inode gets written out via the AIL
217          * or xfs_iflush_cluster.
218          */
219         if (((inode->i_state & I_DIRTY_DATASYNC) ||
220             ((inode->i_state & I_DIRTY_SYNC) && !datasync)) &&
221             ip->i_update_core) {
222                 /*
223                  * Kick off a transaction to log the inode core to get the
224                  * updates.  The sync transaction will also force the log.
225                  */
226                 xfs_iunlock(ip, XFS_ILOCK_SHARED);
227                 tp = xfs_trans_alloc(mp, XFS_TRANS_FSYNC_TS);
228                 error = xfs_trans_reserve(tp, 0,
229                                 XFS_FSYNC_TS_LOG_RES(mp), 0, 0, 0);
230                 if (error) {
231                         xfs_trans_cancel(tp, 0);
232                         return -error;
233                 }
234                 xfs_ilock(ip, XFS_ILOCK_EXCL);
235
236                 /*
237                  * Note - it's possible that we might have pushed ourselves out
238                  * of the way during trans_reserve which would flush the inode.
239                  * But there's no guarantee that the inode buffer has actually
240                  * gone out yet (it's delwri).  Plus the buffer could be pinned
241                  * anyway if it's part of an inode in another recent
242                  * transaction.  So we play it safe and fire off the
243                  * transaction anyway.
244                  */
245                 xfs_trans_ijoin(tp, ip, 0);
246                 xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
247                 error = xfs_trans_commit(tp, 0);
248
249                 lsn = ip->i_itemp->ili_last_lsn;
250                 xfs_iunlock(ip, XFS_ILOCK_EXCL);
251         } else {
252                 /*
253                  * Timestamps/size haven't changed since last inode flush or
254                  * inode transaction commit.  That means either nothing got
255                  * written or a transaction committed which caught the updates.
256                  * If the latter happened and the transaction hasn't hit the
257                  * disk yet, the inode will be still be pinned.  If it is,
258                  * force the log.
259                  */
260                 if (xfs_ipincount(ip))
261                         lsn = ip->i_itemp->ili_last_lsn;
262                 xfs_iunlock(ip, XFS_ILOCK_SHARED);
263         }
264
265         if (!error && lsn)
266                 error = _xfs_log_force_lsn(mp, lsn, XFS_LOG_SYNC, &log_flushed);
267
268         /*
269          * If we only have a single device, and the log force about was
270          * a no-op we might have to flush the data device cache here.
271          * This can only happen for fdatasync/O_DSYNC if we were overwriting
272          * an already allocated file and thus do not have any metadata to
273          * commit.
274          */
275         if ((mp->m_flags & XFS_MOUNT_BARRIER) &&
276             mp->m_logdev_targp == mp->m_ddev_targp &&
277             !XFS_IS_REALTIME_INODE(ip) &&
278             !log_flushed)
279                 xfs_blkdev_issue_flush(mp->m_ddev_targp);
280
281         return -error;
282 }
283
284 STATIC ssize_t
285 xfs_file_aio_read(
286         struct kiocb            *iocb,
287         const struct iovec      *iovp,
288         unsigned long           nr_segs,
289         loff_t                  pos)
290 {
291         struct file             *file = iocb->ki_filp;
292         struct inode            *inode = file->f_mapping->host;
293         struct xfs_inode        *ip = XFS_I(inode);
294         struct xfs_mount        *mp = ip->i_mount;
295         size_t                  size = 0;
296         ssize_t                 ret = 0;
297         int                     ioflags = 0;
298         xfs_fsize_t             n;
299         unsigned long           seg;
300
301         XFS_STATS_INC(xs_read_calls);
302
303         BUG_ON(iocb->ki_pos != pos);
304
305         if (unlikely(file->f_flags & O_DIRECT))
306                 ioflags |= IO_ISDIRECT;
307         if (file->f_mode & FMODE_NOCMTIME)
308                 ioflags |= IO_INVIS;
309
310         /* START copy & waste from filemap.c */
311         for (seg = 0; seg < nr_segs; seg++) {
312                 const struct iovec *iv = &iovp[seg];
313
314                 /*
315                  * If any segment has a negative length, or the cumulative
316                  * length ever wraps negative then return -EINVAL.
317                  */
318                 size += iv->iov_len;
319                 if (unlikely((ssize_t)(size|iv->iov_len) < 0))
320                         return XFS_ERROR(-EINVAL);
321         }
322         /* END copy & waste from filemap.c */
323
324         if (unlikely(ioflags & IO_ISDIRECT)) {
325                 xfs_buftarg_t   *target =
326                         XFS_IS_REALTIME_INODE(ip) ?
327                                 mp->m_rtdev_targp : mp->m_ddev_targp;
328                 if ((iocb->ki_pos & target->bt_smask) ||
329                     (size & target->bt_smask)) {
330                         if (iocb->ki_pos == ip->i_size)
331                                 return 0;
332                         return -XFS_ERROR(EINVAL);
333                 }
334         }
335
336         n = XFS_MAXIOFFSET(mp) - iocb->ki_pos;
337         if (n <= 0 || size == 0)
338                 return 0;
339
340         if (n < size)
341                 size = n;
342
343         if (XFS_FORCED_SHUTDOWN(mp))
344                 return -EIO;
345
346         /*
347          * Locking is a bit tricky here. If we take an exclusive lock
348          * for direct IO, we effectively serialise all new concurrent
349          * read IO to this file and block it behind IO that is currently in
350          * progress because IO in progress holds the IO lock shared. We only
351          * need to hold the lock exclusive to blow away the page cache, so
352          * only take lock exclusively if the page cache needs invalidation.
353          * This allows the normal direct IO case of no page cache pages to
354          * proceeed concurrently without serialisation.
355          */
356         xfs_rw_ilock(ip, XFS_IOLOCK_SHARED);
357         if ((ioflags & IO_ISDIRECT) && inode->i_mapping->nrpages) {
358                 xfs_rw_iunlock(ip, XFS_IOLOCK_SHARED);
359                 xfs_rw_ilock(ip, XFS_IOLOCK_EXCL);
360
361                 if (inode->i_mapping->nrpages) {
362                         ret = -xfs_flushinval_pages(ip,
363                                         (iocb->ki_pos & PAGE_CACHE_MASK),
364                                         -1, FI_REMAPF_LOCKED);
365                         if (ret) {
366                                 xfs_rw_iunlock(ip, XFS_IOLOCK_EXCL);
367                                 return ret;
368                         }
369                 }
370                 xfs_rw_ilock_demote(ip, XFS_IOLOCK_EXCL);
371         }
372
373         trace_xfs_file_read(ip, size, iocb->ki_pos, ioflags);
374
375         ret = generic_file_aio_read(iocb, iovp, nr_segs, iocb->ki_pos);
376         if (ret > 0)
377                 XFS_STATS_ADD(xs_read_bytes, ret);
378
379         xfs_rw_iunlock(ip, XFS_IOLOCK_SHARED);
380         return ret;
381 }
382
383 STATIC ssize_t
384 xfs_file_splice_read(
385         struct file             *infilp,
386         loff_t                  *ppos,
387         struct pipe_inode_info  *pipe,
388         size_t                  count,
389         unsigned int            flags)
390 {
391         struct xfs_inode        *ip = XFS_I(infilp->f_mapping->host);
392         int                     ioflags = 0;
393         ssize_t                 ret;
394
395         XFS_STATS_INC(xs_read_calls);
396
397         if (infilp->f_mode & FMODE_NOCMTIME)
398                 ioflags |= IO_INVIS;
399
400         if (XFS_FORCED_SHUTDOWN(ip->i_mount))
401                 return -EIO;
402
403         xfs_rw_ilock(ip, XFS_IOLOCK_SHARED);
404
405         trace_xfs_file_splice_read(ip, count, *ppos, ioflags);
406
407         ret = generic_file_splice_read(infilp, ppos, pipe, count, flags);
408         if (ret > 0)
409                 XFS_STATS_ADD(xs_read_bytes, ret);
410
411         xfs_rw_iunlock(ip, XFS_IOLOCK_SHARED);
412         return ret;
413 }
414
415 STATIC void
416 xfs_aio_write_isize_update(
417         struct inode    *inode,
418         loff_t          *ppos,
419         ssize_t         bytes_written)
420 {
421         struct xfs_inode        *ip = XFS_I(inode);
422         xfs_fsize_t             isize = i_size_read(inode);
423
424         if (bytes_written > 0)
425                 XFS_STATS_ADD(xs_write_bytes, bytes_written);
426
427         if (unlikely(bytes_written < 0 && bytes_written != -EFAULT &&
428                                         *ppos > isize))
429                 *ppos = isize;
430
431         if (*ppos > ip->i_size) {
432                 xfs_rw_ilock(ip, XFS_ILOCK_EXCL);
433                 if (*ppos > ip->i_size)
434                         ip->i_size = *ppos;
435                 xfs_rw_iunlock(ip, XFS_ILOCK_EXCL);
436         }
437 }
438
439 /*
440  * If this was a direct or synchronous I/O that failed (such as ENOSPC) then
441  * part of the I/O may have been written to disk before the error occurred.  In
442  * this case the on-disk file size may have been adjusted beyond the in-memory
443  * file size and now needs to be truncated back.
444  */
445 STATIC void
446 xfs_aio_write_newsize_update(
447         struct xfs_inode        *ip,
448         xfs_fsize_t             new_size)
449 {
450         if (new_size == ip->i_new_size) {
451                 xfs_rw_ilock(ip, XFS_ILOCK_EXCL);
452                 if (new_size == ip->i_new_size)
453                         ip->i_new_size = 0;
454                 if (ip->i_d.di_size > ip->i_size)
455                         ip->i_d.di_size = ip->i_size;
456                 xfs_rw_iunlock(ip, XFS_ILOCK_EXCL);
457         }
458 }
459
460 /*
461  * xfs_file_splice_write() does not use xfs_rw_ilock() because
462  * generic_file_splice_write() takes the i_mutex itself. This, in theory,
463  * couuld cause lock inversions between the aio_write path and the splice path
464  * if someone is doing concurrent splice(2) based writes and write(2) based
465  * writes to the same inode. The only real way to fix this is to re-implement
466  * the generic code here with correct locking orders.
467  */
468 STATIC ssize_t
469 xfs_file_splice_write(
470         struct pipe_inode_info  *pipe,
471         struct file             *outfilp,
472         loff_t                  *ppos,
473         size_t                  count,
474         unsigned int            flags)
475 {
476         struct inode            *inode = outfilp->f_mapping->host;
477         struct xfs_inode        *ip = XFS_I(inode);
478         xfs_fsize_t             new_size;
479         int                     ioflags = 0;
480         ssize_t                 ret;
481
482         XFS_STATS_INC(xs_write_calls);
483
484         if (outfilp->f_mode & FMODE_NOCMTIME)
485                 ioflags |= IO_INVIS;
486
487         if (XFS_FORCED_SHUTDOWN(ip->i_mount))
488                 return -EIO;
489
490         xfs_ilock(ip, XFS_IOLOCK_EXCL);
491
492         new_size = *ppos + count;
493
494         xfs_ilock(ip, XFS_ILOCK_EXCL);
495         if (new_size > ip->i_size)
496                 ip->i_new_size = new_size;
497         xfs_iunlock(ip, XFS_ILOCK_EXCL);
498
499         trace_xfs_file_splice_write(ip, count, *ppos, ioflags);
500
501         ret = generic_file_splice_write(pipe, outfilp, ppos, count, flags);
502
503         xfs_aio_write_isize_update(inode, ppos, ret);
504         xfs_aio_write_newsize_update(ip, new_size);
505         xfs_iunlock(ip, XFS_IOLOCK_EXCL);
506         return ret;
507 }
508
509 /*
510  * This routine is called to handle zeroing any space in the last
511  * block of the file that is beyond the EOF.  We do this since the
512  * size is being increased without writing anything to that block
513  * and we don't want anyone to read the garbage on the disk.
514  */
515 STATIC int                              /* error (positive) */
516 xfs_zero_last_block(
517         xfs_inode_t     *ip,
518         xfs_fsize_t     offset,
519         xfs_fsize_t     isize,
520         bool            *did_zeroing)
521 {
522         xfs_fileoff_t   last_fsb;
523         xfs_mount_t     *mp = ip->i_mount;
524         int             nimaps;
525         int             zero_offset;
526         int             zero_len;
527         int             error = 0;
528         xfs_bmbt_irec_t imap;
529
530         ASSERT(xfs_isilocked(ip, XFS_ILOCK_EXCL));
531
532         zero_offset = XFS_B_FSB_OFFSET(mp, isize);
533         if (zero_offset == 0) {
534                 /*
535                  * There are no extra bytes in the last block on disk to
536                  * zero, so return.
537                  */
538                 return 0;
539         }
540
541         last_fsb = XFS_B_TO_FSBT(mp, isize);
542         nimaps = 1;
543         error = xfs_bmapi_read(ip, last_fsb, 1, &imap, &nimaps, 0);
544         if (error)
545                 return error;
546         ASSERT(nimaps > 0);
547         /*
548          * If the block underlying isize is just a hole, then there
549          * is nothing to zero.
550          */
551         if (imap.br_startblock == HOLESTARTBLOCK) {
552                 return 0;
553         }
554         /*
555          * Zero the part of the last block beyond the EOF, and write it
556          * out sync.  We need to drop the ilock while we do this so we
557          * don't deadlock when the buffer cache calls back to us.
558          */
559         xfs_iunlock(ip, XFS_ILOCK_EXCL);
560
561         zero_len = mp->m_sb.sb_blocksize - zero_offset;
562         if (isize + zero_len > offset)
563                 zero_len = offset - isize;
564         *did_zeroing = true;
565         error = xfs_iozero(ip, isize, zero_len);
566
567         xfs_ilock(ip, XFS_ILOCK_EXCL);
568         ASSERT(error >= 0);
569         return error;
570 }
571
572 /*
573  * Zero any on disk space between the current EOF and the new,
574  * larger EOF.  This handles the normal case of zeroing the remainder
575  * of the last block in the file and the unusual case of zeroing blocks
576  * out beyond the size of the file.  This second case only happens
577  * with fixed size extents and when the system crashes before the inode
578  * size was updated but after blocks were allocated.  If fill is set,
579  * then any holes in the range are filled and zeroed.  If not, the holes
580  * are left alone as holes.
581  */
582
583 int                                     /* error (positive) */
584 xfs_zero_eof(
585         xfs_inode_t     *ip,
586         xfs_off_t       offset,         /* starting I/O offset */
587         xfs_fsize_t     isize,          /* current inode size */
588         bool            *did_zeroing)
589 {
590         xfs_mount_t     *mp = ip->i_mount;
591         xfs_fileoff_t   start_zero_fsb;
592         xfs_fileoff_t   end_zero_fsb;
593         xfs_fileoff_t   zero_count_fsb;
594         xfs_fileoff_t   last_fsb;
595         xfs_fileoff_t   zero_off;
596         xfs_fsize_t     zero_len;
597         int             nimaps;
598         int             error = 0;
599         xfs_bmbt_irec_t imap;
600
601         ASSERT(xfs_isilocked(ip, XFS_ILOCK_EXCL|XFS_IOLOCK_EXCL));
602         ASSERT(offset > isize);
603
604         /*
605          * First handle zeroing the block on which isize resides.
606          * We only zero a part of that block so it is handled specially.
607          */
608         error = xfs_zero_last_block(ip, offset, isize, did_zeroing);
609         if (error) {
610                 ASSERT(xfs_isilocked(ip, XFS_ILOCK_EXCL|XFS_IOLOCK_EXCL));
611                 return error;
612         }
613
614         /*
615          * Calculate the range between the new size and the old
616          * where blocks needing to be zeroed may exist.  To get the
617          * block where the last byte in the file currently resides,
618          * we need to subtract one from the size and truncate back
619          * to a block boundary.  We subtract 1 in case the size is
620          * exactly on a block boundary.
621          */
622         last_fsb = isize ? XFS_B_TO_FSBT(mp, isize - 1) : (xfs_fileoff_t)-1;
623         start_zero_fsb = XFS_B_TO_FSB(mp, (xfs_ufsize_t)isize);
624         end_zero_fsb = XFS_B_TO_FSBT(mp, offset - 1);
625         ASSERT((xfs_sfiloff_t)last_fsb < (xfs_sfiloff_t)start_zero_fsb);
626         if (last_fsb == end_zero_fsb) {
627                 /*
628                  * The size was only incremented on its last block.
629                  * We took care of that above, so just return.
630                  */
631                 return 0;
632         }
633
634         ASSERT(start_zero_fsb <= end_zero_fsb);
635         while (start_zero_fsb <= end_zero_fsb) {
636                 nimaps = 1;
637                 zero_count_fsb = end_zero_fsb - start_zero_fsb + 1;
638                 error = xfs_bmapi_read(ip, start_zero_fsb, zero_count_fsb,
639                                           &imap, &nimaps, 0);
640                 if (error) {
641                         ASSERT(xfs_isilocked(ip, XFS_ILOCK_EXCL|XFS_IOLOCK_EXCL));
642                         return error;
643                 }
644                 ASSERT(nimaps > 0);
645
646                 if (imap.br_state == XFS_EXT_UNWRITTEN ||
647                     imap.br_startblock == HOLESTARTBLOCK) {
648                         /*
649                          * This loop handles initializing pages that were
650                          * partially initialized by the code below this
651                          * loop. It basically zeroes the part of the page
652                          * that sits on a hole and sets the page as P_HOLE
653                          * and calls remapf if it is a mapped file.
654                          */
655                         start_zero_fsb = imap.br_startoff + imap.br_blockcount;
656                         ASSERT(start_zero_fsb <= (end_zero_fsb + 1));
657                         continue;
658                 }
659
660                 /*
661                  * There are blocks we need to zero.
662                  * Drop the inode lock while we're doing the I/O.
663                  * We'll still have the iolock to protect us.
664                  */
665                 xfs_iunlock(ip, XFS_ILOCK_EXCL);
666
667                 zero_off = XFS_FSB_TO_B(mp, start_zero_fsb);
668                 zero_len = XFS_FSB_TO_B(mp, imap.br_blockcount);
669
670                 if ((zero_off + zero_len) > offset)
671                         zero_len = offset - zero_off;
672
673                 error = xfs_iozero(ip, zero_off, zero_len);
674                 if (error) {
675                         goto out_lock;
676                 }
677
678                 *did_zeroing = true;
679                 start_zero_fsb = imap.br_startoff + imap.br_blockcount;
680                 ASSERT(start_zero_fsb <= (end_zero_fsb + 1));
681
682                 xfs_ilock(ip, XFS_ILOCK_EXCL);
683         }
684
685         return 0;
686
687 out_lock:
688         xfs_ilock(ip, XFS_ILOCK_EXCL);
689         ASSERT(error >= 0);
690         return error;
691 }
692
693 /*
694  * Common pre-write limit and setup checks.
695  *
696  * Returns with iolock held according to @iolock.
697  */
698 STATIC ssize_t
699 xfs_file_aio_write_checks(
700         struct file             *file,
701         loff_t                  *pos,
702         size_t                  *count,
703         xfs_fsize_t             *new_sizep,
704         int                     *iolock)
705 {
706         struct inode            *inode = file->f_mapping->host;
707         struct xfs_inode        *ip = XFS_I(inode);
708         xfs_fsize_t             new_size;
709         int                     error = 0;
710
711         xfs_rw_ilock(ip, XFS_ILOCK_EXCL);
712         *new_sizep = 0;
713 restart:
714         error = generic_write_checks(file, pos, count, S_ISBLK(inode->i_mode));
715         if (error) {
716                 xfs_rw_iunlock(ip, XFS_ILOCK_EXCL | *iolock);
717                 *iolock = 0;
718                 return error;
719         }
720
721         if (likely(!(file->f_mode & FMODE_NOCMTIME)))
722                 file_update_time(file);
723
724         /*
725          * If the offset is beyond the size of the file, we need to zero any
726          * blocks that fall between the existing EOF and the start of this
727          * write. There is no need to issue zeroing if another in-flght IO ends
728          * at or before this one If zeronig is needed and we are currently
729          * holding the iolock shared, we need to update it to exclusive which
730          * involves dropping all locks and relocking to maintain correct locking
731          * order. If we do this, restart the function to ensure all checks and
732          * values are still valid.
733          */
734         if ((ip->i_new_size && *pos > ip->i_new_size) ||
735             (!ip->i_new_size && *pos > ip->i_size)) {
736                 bool    zero = false;
737
738                 if (*iolock == XFS_IOLOCK_SHARED) {
739                         xfs_rw_iunlock(ip, XFS_ILOCK_EXCL | *iolock);
740                         *iolock = XFS_IOLOCK_EXCL;
741                         xfs_rw_ilock(ip, XFS_ILOCK_EXCL | *iolock);
742                         goto restart;
743                 }
744                 error = -xfs_zero_eof(ip, *pos, ip->i_size, &zero);
745         }
746
747         /*
748          * If this IO extends beyond EOF, we may need to update ip->i_new_size.
749          * We have already zeroed space beyond EOF (if necessary).  Only update
750          * ip->i_new_size if this IO ends beyond any other in-flight writes.
751          */
752         new_size = *pos + *count;
753         if (new_size > ip->i_size) {
754                 if (new_size > ip->i_new_size)
755                         ip->i_new_size = new_size;
756                 *new_sizep = new_size;
757         }
758
759         xfs_rw_iunlock(ip, XFS_ILOCK_EXCL);
760         if (error)
761                 return error;
762
763         /*
764          * If we're writing the file then make sure to clear the setuid and
765          * setgid bits if the process is not being run by root.  This keeps
766          * people from modifying setuid and setgid binaries.
767          */
768         return file_remove_suid(file);
769
770 }
771
772 /*
773  * xfs_file_dio_aio_write - handle direct IO writes
774  *
775  * Lock the inode appropriately to prepare for and issue a direct IO write.
776  * By separating it from the buffered write path we remove all the tricky to
777  * follow locking changes and looping.
778  *
779  * If there are cached pages or we're extending the file, we need IOLOCK_EXCL
780  * until we're sure the bytes at the new EOF have been zeroed and/or the cached
781  * pages are flushed out.
782  *
783  * In most cases the direct IO writes will be done holding IOLOCK_SHARED
784  * allowing them to be done in parallel with reads and other direct IO writes.
785  * However, if the IO is not aligned to filesystem blocks, the direct IO layer
786  * needs to do sub-block zeroing and that requires serialisation against other
787  * direct IOs to the same block. In this case we need to serialise the
788  * submission of the unaligned IOs so that we don't get racing block zeroing in
789  * the dio layer.  To avoid the problem with aio, we also need to wait for
790  * outstanding IOs to complete so that unwritten extent conversion is completed
791  * before we try to map the overlapping block. This is currently implemented by
792  * hitting it with a big hammer (i.e. inode_dio_wait()).
793  *
794  * Returns with locks held indicated by @iolock and errors indicated by
795  * negative return values.
796  */
797 STATIC ssize_t
798 xfs_file_dio_aio_write(
799         struct kiocb            *iocb,
800         const struct iovec      *iovp,
801         unsigned long           nr_segs,
802         loff_t                  pos,
803         size_t                  ocount,
804         xfs_fsize_t             *new_size,
805         int                     *iolock)
806 {
807         struct file             *file = iocb->ki_filp;
808         struct address_space    *mapping = file->f_mapping;
809         struct inode            *inode = mapping->host;
810         struct xfs_inode        *ip = XFS_I(inode);
811         struct xfs_mount        *mp = ip->i_mount;
812         ssize_t                 ret = 0;
813         size_t                  count = ocount;
814         int                     unaligned_io = 0;
815         struct xfs_buftarg      *target = XFS_IS_REALTIME_INODE(ip) ?
816                                         mp->m_rtdev_targp : mp->m_ddev_targp;
817
818         *iolock = 0;
819         if ((pos & target->bt_smask) || (count & target->bt_smask))
820                 return -XFS_ERROR(EINVAL);
821
822         if ((pos & mp->m_blockmask) || ((pos + count) & mp->m_blockmask))
823                 unaligned_io = 1;
824
825         /*
826          * We don't need to take an exclusive lock unless there page cache needs
827          * to be invalidated or unaligned IO is being executed. We don't need to
828          * consider the EOF extension case here because
829          * xfs_file_aio_write_checks() will relock the inode as necessary for
830          * EOF zeroing cases and fill out the new inode size as appropriate.
831          */
832         if (unaligned_io || mapping->nrpages)
833                 *iolock = XFS_IOLOCK_EXCL;
834         else
835                 *iolock = XFS_IOLOCK_SHARED;
836         xfs_rw_ilock(ip, *iolock);
837
838         /*
839          * Recheck if there are cached pages that need invalidate after we got
840          * the iolock to protect against other threads adding new pages while
841          * we were waiting for the iolock.
842          */
843         if (mapping->nrpages && *iolock == XFS_IOLOCK_SHARED) {
844                 xfs_rw_iunlock(ip, *iolock);
845                 *iolock = XFS_IOLOCK_EXCL;
846                 xfs_rw_ilock(ip, *iolock);
847         }
848
849         ret = xfs_file_aio_write_checks(file, &pos, &count, new_size, iolock);
850         if (ret)
851                 return ret;
852
853         if (mapping->nrpages) {
854                 ret = -xfs_flushinval_pages(ip, (pos & PAGE_CACHE_MASK), -1,
855                                                         FI_REMAPF_LOCKED);
856                 if (ret)
857                         return ret;
858         }
859
860         /*
861          * If we are doing unaligned IO, wait for all other IO to drain,
862          * otherwise demote the lock if we had to flush cached pages
863          */
864         if (unaligned_io)
865                 inode_dio_wait(inode);
866         else if (*iolock == XFS_IOLOCK_EXCL) {
867                 xfs_rw_ilock_demote(ip, XFS_IOLOCK_EXCL);
868                 *iolock = XFS_IOLOCK_SHARED;
869         }
870
871         trace_xfs_file_direct_write(ip, count, iocb->ki_pos, 0);
872         ret = generic_file_direct_write(iocb, iovp,
873                         &nr_segs, pos, &iocb->ki_pos, count, ocount);
874
875         /* No fallback to buffered IO on errors for XFS. */
876         ASSERT(ret < 0 || ret == count);
877         return ret;
878 }
879
880 STATIC ssize_t
881 xfs_file_buffered_aio_write(
882         struct kiocb            *iocb,
883         const struct iovec      *iovp,
884         unsigned long           nr_segs,
885         loff_t                  pos,
886         size_t                  ocount,
887         xfs_fsize_t             *new_size,
888         int                     *iolock)
889 {
890         struct file             *file = iocb->ki_filp;
891         struct address_space    *mapping = file->f_mapping;
892         struct inode            *inode = mapping->host;
893         struct xfs_inode        *ip = XFS_I(inode);
894         ssize_t                 ret;
895         int                     enospc = 0;
896         size_t                  count = ocount;
897
898         *iolock = XFS_IOLOCK_EXCL;
899         xfs_rw_ilock(ip, *iolock);
900
901         ret = xfs_file_aio_write_checks(file, &pos, &count, new_size, iolock);
902         if (ret)
903                 return ret;
904
905         /* We can write back this queue in page reclaim */
906         current->backing_dev_info = mapping->backing_dev_info;
907
908 write_retry:
909         trace_xfs_file_buffered_write(ip, count, iocb->ki_pos, 0);
910         ret = generic_file_buffered_write(iocb, iovp, nr_segs,
911                         pos, &iocb->ki_pos, count, ret);
912         /*
913          * if we just got an ENOSPC, flush the inode now we aren't holding any
914          * page locks and retry *once*
915          */
916         if (ret == -ENOSPC && !enospc) {
917                 ret = -xfs_flush_pages(ip, 0, -1, 0, FI_NONE);
918                 if (ret)
919                         return ret;
920                 enospc = 1;
921                 goto write_retry;
922         }
923         current->backing_dev_info = NULL;
924         return ret;
925 }
926
927 STATIC ssize_t
928 xfs_file_aio_write(
929         struct kiocb            *iocb,
930         const struct iovec      *iovp,
931         unsigned long           nr_segs,
932         loff_t                  pos)
933 {
934         struct file             *file = iocb->ki_filp;
935         struct address_space    *mapping = file->f_mapping;
936         struct inode            *inode = mapping->host;
937         struct xfs_inode        *ip = XFS_I(inode);
938         ssize_t                 ret;
939         int                     iolock;
940         size_t                  ocount = 0;
941         xfs_fsize_t             new_size = 0;
942
943         XFS_STATS_INC(xs_write_calls);
944
945         BUG_ON(iocb->ki_pos != pos);
946
947         ret = generic_segment_checks(iovp, &nr_segs, &ocount, VERIFY_READ);
948         if (ret)
949                 return ret;
950
951         if (ocount == 0)
952                 return 0;
953
954         xfs_wait_for_freeze(ip->i_mount, SB_FREEZE_WRITE);
955
956         if (XFS_FORCED_SHUTDOWN(ip->i_mount))
957                 return -EIO;
958
959         if (unlikely(file->f_flags & O_DIRECT))
960                 ret = xfs_file_dio_aio_write(iocb, iovp, nr_segs, pos,
961                                                 ocount, &new_size, &iolock);
962         else
963                 ret = xfs_file_buffered_aio_write(iocb, iovp, nr_segs, pos,
964                                                 ocount, &new_size, &iolock);
965
966         xfs_aio_write_isize_update(inode, &iocb->ki_pos, ret);
967
968         if (ret <= 0)
969                 goto out_unlock;
970
971         /* Handle various SYNC-type writes */
972         if ((file->f_flags & O_DSYNC) || IS_SYNC(inode)) {
973                 loff_t end = pos + ret - 1;
974                 int error;
975
976                 xfs_rw_iunlock(ip, iolock);
977                 error = xfs_file_fsync(file, pos, end,
978                                       (file->f_flags & __O_SYNC) ? 0 : 1);
979                 xfs_rw_ilock(ip, iolock);
980                 if (error)
981                         ret = error;
982         }
983
984 out_unlock:
985         xfs_aio_write_newsize_update(ip, new_size);
986         xfs_rw_iunlock(ip, iolock);
987         return ret;
988 }
989
990 STATIC long
991 xfs_file_fallocate(
992         struct file     *file,
993         int             mode,
994         loff_t          offset,
995         loff_t          len)
996 {
997         struct inode    *inode = file->f_path.dentry->d_inode;
998         long            error;
999         loff_t          new_size = 0;
1000         xfs_flock64_t   bf;
1001         xfs_inode_t     *ip = XFS_I(inode);
1002         int             cmd = XFS_IOC_RESVSP;
1003         int             attr_flags = XFS_ATTR_NOLOCK;
1004
1005         if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE))
1006                 return -EOPNOTSUPP;
1007
1008         bf.l_whence = 0;
1009         bf.l_start = offset;
1010         bf.l_len = len;
1011
1012         xfs_ilock(ip, XFS_IOLOCK_EXCL);
1013
1014         if (mode & FALLOC_FL_PUNCH_HOLE)
1015                 cmd = XFS_IOC_UNRESVSP;
1016
1017         /* check the new inode size is valid before allocating */
1018         if (!(mode & FALLOC_FL_KEEP_SIZE) &&
1019             offset + len > i_size_read(inode)) {
1020                 new_size = offset + len;
1021                 error = inode_newsize_ok(inode, new_size);
1022                 if (error)
1023                         goto out_unlock;
1024         }
1025
1026         if (file->f_flags & O_DSYNC)
1027                 attr_flags |= XFS_ATTR_SYNC;
1028
1029         error = -xfs_change_file_space(ip, cmd, &bf, 0, attr_flags);
1030         if (error)
1031                 goto out_unlock;
1032
1033         /* Change file size if needed */
1034         if (new_size) {
1035                 struct iattr iattr;
1036
1037                 iattr.ia_valid = ATTR_SIZE;
1038                 iattr.ia_size = new_size;
1039                 error = -xfs_setattr_size(ip, &iattr, XFS_ATTR_NOLOCK);
1040         }
1041
1042 out_unlock:
1043         xfs_iunlock(ip, XFS_IOLOCK_EXCL);
1044         return error;
1045 }
1046
1047
1048 STATIC int
1049 xfs_file_open(
1050         struct inode    *inode,
1051         struct file     *file)
1052 {
1053         if (!(file->f_flags & O_LARGEFILE) && i_size_read(inode) > MAX_NON_LFS)
1054                 return -EFBIG;
1055         if (XFS_FORCED_SHUTDOWN(XFS_M(inode->i_sb)))
1056                 return -EIO;
1057         return 0;
1058 }
1059
1060 STATIC int
1061 xfs_dir_open(
1062         struct inode    *inode,
1063         struct file     *file)
1064 {
1065         struct xfs_inode *ip = XFS_I(inode);
1066         int             mode;
1067         int             error;
1068
1069         error = xfs_file_open(inode, file);
1070         if (error)
1071                 return error;
1072
1073         /*
1074          * If there are any blocks, read-ahead block 0 as we're almost
1075          * certain to have the next operation be a read there.
1076          */
1077         mode = xfs_ilock_map_shared(ip);
1078         if (ip->i_d.di_nextents > 0)
1079                 xfs_da_reada_buf(NULL, ip, 0, XFS_DATA_FORK);
1080         xfs_iunlock(ip, mode);
1081         return 0;
1082 }
1083
1084 STATIC int
1085 xfs_file_release(
1086         struct inode    *inode,
1087         struct file     *filp)
1088 {
1089         return -xfs_release(XFS_I(inode));
1090 }
1091
1092 STATIC int
1093 xfs_file_readdir(
1094         struct file     *filp,
1095         void            *dirent,
1096         filldir_t       filldir)
1097 {
1098         struct inode    *inode = filp->f_path.dentry->d_inode;
1099         xfs_inode_t     *ip = XFS_I(inode);
1100         int             error;
1101         size_t          bufsize;
1102
1103         /*
1104          * The Linux API doesn't pass down the total size of the buffer
1105          * we read into down to the filesystem.  With the filldir concept
1106          * it's not needed for correct information, but the XFS dir2 leaf
1107          * code wants an estimate of the buffer size to calculate it's
1108          * readahead window and size the buffers used for mapping to
1109          * physical blocks.
1110          *
1111          * Try to give it an estimate that's good enough, maybe at some
1112          * point we can change the ->readdir prototype to include the
1113          * buffer size.  For now we use the current glibc buffer size.
1114          */
1115         bufsize = (size_t)min_t(loff_t, 32768, ip->i_d.di_size);
1116
1117         error = xfs_readdir(ip, dirent, bufsize,
1118                                 (xfs_off_t *)&filp->f_pos, filldir);
1119         if (error)
1120                 return -error;
1121         return 0;
1122 }
1123
1124 STATIC int
1125 xfs_file_mmap(
1126         struct file     *filp,
1127         struct vm_area_struct *vma)
1128 {
1129         vma->vm_ops = &xfs_file_vm_ops;
1130         vma->vm_flags |= VM_CAN_NONLINEAR;
1131
1132         file_accessed(filp);
1133         return 0;
1134 }
1135
1136 /*
1137  * mmap()d file has taken write protection fault and is being made
1138  * writable. We can set the page state up correctly for a writable
1139  * page, which means we can do correct delalloc accounting (ENOSPC
1140  * checking!) and unwritten extent mapping.
1141  */
1142 STATIC int
1143 xfs_vm_page_mkwrite(
1144         struct vm_area_struct   *vma,
1145         struct vm_fault         *vmf)
1146 {
1147         return block_page_mkwrite(vma, vmf, xfs_get_blocks);
1148 }
1149
1150 const struct file_operations xfs_file_operations = {
1151         .llseek         = generic_file_llseek,
1152         .read           = do_sync_read,
1153         .write          = do_sync_write,
1154         .aio_read       = xfs_file_aio_read,
1155         .aio_write      = xfs_file_aio_write,
1156         .splice_read    = xfs_file_splice_read,
1157         .splice_write   = xfs_file_splice_write,
1158         .unlocked_ioctl = xfs_file_ioctl,
1159 #ifdef CONFIG_COMPAT
1160         .compat_ioctl   = xfs_file_compat_ioctl,
1161 #endif
1162         .mmap           = xfs_file_mmap,
1163         .open           = xfs_file_open,
1164         .release        = xfs_file_release,
1165         .fsync          = xfs_file_fsync,
1166         .fallocate      = xfs_file_fallocate,
1167 };
1168
1169 const struct file_operations xfs_dir_file_operations = {
1170         .open           = xfs_dir_open,
1171         .read           = generic_read_dir,
1172         .readdir        = xfs_file_readdir,
1173         .llseek         = generic_file_llseek,
1174         .unlocked_ioctl = xfs_file_ioctl,
1175 #ifdef CONFIG_COMPAT
1176         .compat_ioctl   = xfs_file_compat_ioctl,
1177 #endif
1178         .fsync          = xfs_dir_fsync,
1179 };
1180
1181 static const struct vm_operations_struct xfs_file_vm_ops = {
1182         .fault          = filemap_fault,
1183         .page_mkwrite   = xfs_vm_page_mkwrite,
1184 };