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