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