ee98d0bf0f6a4fe12f857c69793d44e36a34d384
[pandora-kernel.git] / fs / xfs / xfs_vnodeops.c
1 /*
2  * Copyright (c) 2000-2006 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
19 #include "xfs.h"
20 #include "xfs_fs.h"
21 #include "xfs_types.h"
22 #include "xfs_bit.h"
23 #include "xfs_log.h"
24 #include "xfs_inum.h"
25 #include "xfs_trans.h"
26 #include "xfs_sb.h"
27 #include "xfs_ag.h"
28 #include "xfs_dir2.h"
29 #include "xfs_mount.h"
30 #include "xfs_da_btree.h"
31 #include "xfs_bmap_btree.h"
32 #include "xfs_ialloc_btree.h"
33 #include "xfs_dinode.h"
34 #include "xfs_inode.h"
35 #include "xfs_inode_item.h"
36 #include "xfs_itable.h"
37 #include "xfs_ialloc.h"
38 #include "xfs_alloc.h"
39 #include "xfs_bmap.h"
40 #include "xfs_acl.h"
41 #include "xfs_attr.h"
42 #include "xfs_rw.h"
43 #include "xfs_error.h"
44 #include "xfs_quota.h"
45 #include "xfs_utils.h"
46 #include "xfs_rtalloc.h"
47 #include "xfs_trans_space.h"
48 #include "xfs_log_priv.h"
49 #include "xfs_filestream.h"
50 #include "xfs_vnodeops.h"
51 #include "xfs_trace.h"
52
53 /*
54  * The maximum pathlen is 1024 bytes. Since the minimum file system
55  * blocksize is 512 bytes, we can get a max of 2 extents back from
56  * bmapi.
57  */
58 #define SYMLINK_MAPS 2
59
60 STATIC int
61 xfs_readlink_bmap(
62         xfs_inode_t     *ip,
63         char            *link)
64 {
65         xfs_mount_t     *mp = ip->i_mount;
66         int             pathlen = ip->i_d.di_size;
67         int             nmaps = SYMLINK_MAPS;
68         xfs_bmbt_irec_t mval[SYMLINK_MAPS];
69         xfs_daddr_t     d;
70         int             byte_cnt;
71         int             n;
72         xfs_buf_t       *bp;
73         int             error = 0;
74
75         error = xfs_bmapi_read(ip, 0, XFS_B_TO_FSB(mp, pathlen), mval, &nmaps,
76                                0);
77         if (error)
78                 goto out;
79
80         for (n = 0; n < nmaps; n++) {
81                 d = XFS_FSB_TO_DADDR(mp, mval[n].br_startblock);
82                 byte_cnt = XFS_FSB_TO_B(mp, mval[n].br_blockcount);
83
84                 bp = xfs_buf_read(mp->m_ddev_targp, d, BTOBB(byte_cnt),
85                                   XBF_LOCK | XBF_MAPPED | XBF_DONT_BLOCK);
86                 if (!bp)
87                         return XFS_ERROR(ENOMEM);
88                 error = bp->b_error;
89                 if (error) {
90                         xfs_buf_ioerror_alert(bp, __func__);
91                         xfs_buf_relse(bp);
92                         goto out;
93                 }
94                 if (pathlen < byte_cnt)
95                         byte_cnt = pathlen;
96                 pathlen -= byte_cnt;
97
98                 memcpy(link, bp->b_addr, byte_cnt);
99                 xfs_buf_relse(bp);
100         }
101
102         link[ip->i_d.di_size] = '\0';
103         error = 0;
104
105  out:
106         return error;
107 }
108
109 int
110 xfs_readlink(
111         xfs_inode_t     *ip,
112         char            *link)
113 {
114         xfs_mount_t     *mp = ip->i_mount;
115         xfs_fsize_t     pathlen;
116         int             error = 0;
117
118         trace_xfs_readlink(ip);
119
120         if (XFS_FORCED_SHUTDOWN(mp))
121                 return XFS_ERROR(EIO);
122
123         xfs_ilock(ip, XFS_ILOCK_SHARED);
124
125         pathlen = ip->i_d.di_size;
126         if (!pathlen)
127                 goto out;
128
129         if (pathlen < 0 || pathlen > MAXPATHLEN) {
130                 xfs_alert(mp, "%s: inode (%llu) bad symlink length (%lld)",
131                          __func__, (unsigned long long) ip->i_ino,
132                          (long long) pathlen);
133                 ASSERT(0);
134                 error = XFS_ERROR(EFSCORRUPTED);
135                 goto out;
136         }
137
138
139         if (ip->i_df.if_flags & XFS_IFINLINE) {
140                 memcpy(link, ip->i_df.if_u1.if_data, pathlen);
141                 link[pathlen] = '\0';
142         } else {
143                 error = xfs_readlink_bmap(ip, link);
144         }
145
146  out:
147         xfs_iunlock(ip, XFS_ILOCK_SHARED);
148         return error;
149 }
150
151 /*
152  * Flags for xfs_free_eofblocks
153  */
154 #define XFS_FREE_EOF_TRYLOCK    (1<<0)
155
156 /*
157  * This is called by xfs_inactive to free any blocks beyond eof
158  * when the link count isn't zero and by xfs_dm_punch_hole() when
159  * punching a hole to EOF.
160  */
161 STATIC int
162 xfs_free_eofblocks(
163         xfs_mount_t     *mp,
164         xfs_inode_t     *ip,
165         int             flags)
166 {
167         xfs_trans_t     *tp;
168         int             error;
169         xfs_fileoff_t   end_fsb;
170         xfs_fileoff_t   last_fsb;
171         xfs_filblks_t   map_len;
172         int             nimaps;
173         xfs_bmbt_irec_t imap;
174
175         /*
176          * Figure out if there are any blocks beyond the end
177          * of the file.  If not, then there is nothing to do.
178          */
179         end_fsb = XFS_B_TO_FSB(mp, ((xfs_ufsize_t)ip->i_size));
180         last_fsb = XFS_B_TO_FSB(mp, (xfs_ufsize_t)XFS_MAXIOFFSET(mp));
181         if (last_fsb <= end_fsb)
182                 return 0;
183         map_len = last_fsb - end_fsb;
184
185         nimaps = 1;
186         xfs_ilock(ip, XFS_ILOCK_SHARED);
187         error = xfs_bmapi_read(ip, end_fsb, map_len, &imap, &nimaps, 0);
188         xfs_iunlock(ip, XFS_ILOCK_SHARED);
189
190         if (!error && (nimaps != 0) &&
191             (imap.br_startblock != HOLESTARTBLOCK ||
192              ip->i_delayed_blks)) {
193                 /*
194                  * Attach the dquots to the inode up front.
195                  */
196                 error = xfs_qm_dqattach(ip, 0);
197                 if (error)
198                         return error;
199
200                 /*
201                  * There are blocks after the end of file.
202                  * Free them up now by truncating the file to
203                  * its current size.
204                  */
205                 tp = xfs_trans_alloc(mp, XFS_TRANS_INACTIVE);
206
207                 if (flags & XFS_FREE_EOF_TRYLOCK) {
208                         if (!xfs_ilock_nowait(ip, XFS_IOLOCK_EXCL)) {
209                                 xfs_trans_cancel(tp, 0);
210                                 return 0;
211                         }
212                 } else {
213                         xfs_ilock(ip, XFS_IOLOCK_EXCL);
214                 }
215
216                 error = xfs_trans_reserve(tp, 0,
217                                           XFS_ITRUNCATE_LOG_RES(mp),
218                                           0, XFS_TRANS_PERM_LOG_RES,
219                                           XFS_ITRUNCATE_LOG_COUNT);
220                 if (error) {
221                         ASSERT(XFS_FORCED_SHUTDOWN(mp));
222                         xfs_trans_cancel(tp, 0);
223                         xfs_iunlock(ip, XFS_IOLOCK_EXCL);
224                         return error;
225                 }
226
227                 xfs_ilock(ip, XFS_ILOCK_EXCL);
228                 xfs_trans_ijoin(tp, ip, 0);
229
230                 error = xfs_itruncate_data(&tp, ip, ip->i_size);
231                 if (error) {
232                         /*
233                          * If we get an error at this point we simply don't
234                          * bother truncating the file.
235                          */
236                         xfs_trans_cancel(tp,
237                                          (XFS_TRANS_RELEASE_LOG_RES |
238                                           XFS_TRANS_ABORT));
239                 } else {
240                         error = xfs_trans_commit(tp,
241                                                 XFS_TRANS_RELEASE_LOG_RES);
242                 }
243                 xfs_iunlock(ip, XFS_IOLOCK_EXCL|XFS_ILOCK_EXCL);
244         }
245         return error;
246 }
247
248 /*
249  * Free a symlink that has blocks associated with it.
250  */
251 STATIC int
252 xfs_inactive_symlink_rmt(
253         xfs_inode_t     *ip,
254         xfs_trans_t     **tpp)
255 {
256         xfs_buf_t       *bp;
257         int             committed;
258         int             done;
259         int             error;
260         xfs_fsblock_t   first_block;
261         xfs_bmap_free_t free_list;
262         int             i;
263         xfs_mount_t     *mp;
264         xfs_bmbt_irec_t mval[SYMLINK_MAPS];
265         int             nmaps;
266         xfs_trans_t     *ntp;
267         int             size;
268         xfs_trans_t     *tp;
269
270         tp = *tpp;
271         mp = ip->i_mount;
272         ASSERT(ip->i_d.di_size > XFS_IFORK_DSIZE(ip));
273         /*
274          * We're freeing a symlink that has some
275          * blocks allocated to it.  Free the
276          * blocks here.  We know that we've got
277          * either 1 or 2 extents and that we can
278          * free them all in one bunmapi call.
279          */
280         ASSERT(ip->i_d.di_nextents > 0 && ip->i_d.di_nextents <= 2);
281         if ((error = xfs_trans_reserve(tp, 0, XFS_ITRUNCATE_LOG_RES(mp), 0,
282                         XFS_TRANS_PERM_LOG_RES, XFS_ITRUNCATE_LOG_COUNT))) {
283                 ASSERT(XFS_FORCED_SHUTDOWN(mp));
284                 xfs_trans_cancel(tp, 0);
285                 *tpp = NULL;
286                 return error;
287         }
288         /*
289          * Lock the inode, fix the size, and join it to the transaction.
290          * Hold it so in the normal path, we still have it locked for
291          * the second transaction.  In the error paths we need it
292          * held so the cancel won't rele it, see below.
293          */
294         xfs_ilock(ip, XFS_IOLOCK_EXCL | XFS_ILOCK_EXCL);
295         size = (int)ip->i_d.di_size;
296         ip->i_d.di_size = 0;
297         xfs_trans_ijoin(tp, ip, 0);
298         xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
299         /*
300          * Find the block(s) so we can inval and unmap them.
301          */
302         done = 0;
303         xfs_bmap_init(&free_list, &first_block);
304         nmaps = ARRAY_SIZE(mval);
305         error = xfs_bmapi_read(ip, 0, XFS_B_TO_FSB(mp, size),
306                                 mval, &nmaps, 0);
307         if (error)
308                 goto error0;
309         /*
310          * Invalidate the block(s).
311          */
312         for (i = 0; i < nmaps; i++) {
313                 bp = xfs_trans_get_buf(tp, mp->m_ddev_targp,
314                         XFS_FSB_TO_DADDR(mp, mval[i].br_startblock),
315                         XFS_FSB_TO_BB(mp, mval[i].br_blockcount), 0);
316                 if (!bp) {
317                         error = ENOMEM;
318                         goto error1;
319                 }
320                 xfs_trans_binval(tp, bp);
321         }
322         /*
323          * Unmap the dead block(s) to the free_list.
324          */
325         if ((error = xfs_bunmapi(tp, ip, 0, size, XFS_BMAPI_METADATA, nmaps,
326                         &first_block, &free_list, &done)))
327                 goto error1;
328         ASSERT(done);
329         /*
330          * Commit the first transaction.  This logs the EFI and the inode.
331          */
332         if ((error = xfs_bmap_finish(&tp, &free_list, &committed)))
333                 goto error1;
334         /*
335          * The transaction must have been committed, since there were
336          * actually extents freed by xfs_bunmapi.  See xfs_bmap_finish.
337          * The new tp has the extent freeing and EFDs.
338          */
339         ASSERT(committed);
340         /*
341          * The first xact was committed, so add the inode to the new one.
342          * Mark it dirty so it will be logged and moved forward in the log as
343          * part of every commit.
344          */
345         xfs_trans_ijoin(tp, ip, 0);
346         xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
347         /*
348          * Get a new, empty transaction to return to our caller.
349          */
350         ntp = xfs_trans_dup(tp);
351         /*
352          * Commit the transaction containing extent freeing and EFDs.
353          * If we get an error on the commit here or on the reserve below,
354          * we need to unlock the inode since the new transaction doesn't
355          * have the inode attached.
356          */
357         error = xfs_trans_commit(tp, 0);
358         tp = ntp;
359         if (error) {
360                 ASSERT(XFS_FORCED_SHUTDOWN(mp));
361                 goto error0;
362         }
363         /*
364          * transaction commit worked ok so we can drop the extra ticket
365          * reference that we gained in xfs_trans_dup()
366          */
367         xfs_log_ticket_put(tp->t_ticket);
368
369         /*
370          * Remove the memory for extent descriptions (just bookkeeping).
371          */
372         if (ip->i_df.if_bytes)
373                 xfs_idata_realloc(ip, -ip->i_df.if_bytes, XFS_DATA_FORK);
374         ASSERT(ip->i_df.if_bytes == 0);
375         /*
376          * Put an itruncate log reservation in the new transaction
377          * for our caller.
378          */
379         if ((error = xfs_trans_reserve(tp, 0, XFS_ITRUNCATE_LOG_RES(mp), 0,
380                         XFS_TRANS_PERM_LOG_RES, XFS_ITRUNCATE_LOG_COUNT))) {
381                 ASSERT(XFS_FORCED_SHUTDOWN(mp));
382                 goto error0;
383         }
384         /*
385          * Return with the inode locked but not joined to the transaction.
386          */
387         *tpp = tp;
388         return 0;
389
390  error1:
391         xfs_bmap_cancel(&free_list);
392  error0:
393         /*
394          * Have to come here with the inode locked and either
395          * (held and in the transaction) or (not in the transaction).
396          * If the inode isn't held then cancel would iput it, but
397          * that's wrong since this is inactive and the vnode ref
398          * count is 0 already.
399          * Cancel won't do anything to the inode if held, but it still
400          * needs to be locked until the cancel is done, if it was
401          * joined to the transaction.
402          */
403         xfs_trans_cancel(tp, XFS_TRANS_RELEASE_LOG_RES | XFS_TRANS_ABORT);
404         xfs_iunlock(ip, XFS_IOLOCK_EXCL | XFS_ILOCK_EXCL);
405         *tpp = NULL;
406         return error;
407
408 }
409
410 STATIC int
411 xfs_inactive_symlink_local(
412         xfs_inode_t     *ip,
413         xfs_trans_t     **tpp)
414 {
415         int             error;
416
417         ASSERT(ip->i_d.di_size <= XFS_IFORK_DSIZE(ip));
418         /*
419          * We're freeing a symlink which fit into
420          * the inode.  Just free the memory used
421          * to hold the old symlink.
422          */
423         error = xfs_trans_reserve(*tpp, 0,
424                                   XFS_ITRUNCATE_LOG_RES(ip->i_mount),
425                                   0, XFS_TRANS_PERM_LOG_RES,
426                                   XFS_ITRUNCATE_LOG_COUNT);
427
428         if (error) {
429                 xfs_trans_cancel(*tpp, 0);
430                 *tpp = NULL;
431                 return error;
432         }
433         xfs_ilock(ip, XFS_ILOCK_EXCL | XFS_IOLOCK_EXCL);
434
435         /*
436          * Zero length symlinks _can_ exist.
437          */
438         if (ip->i_df.if_bytes > 0) {
439                 xfs_idata_realloc(ip,
440                                   -(ip->i_df.if_bytes),
441                                   XFS_DATA_FORK);
442                 ASSERT(ip->i_df.if_bytes == 0);
443         }
444         return 0;
445 }
446
447 STATIC int
448 xfs_inactive_attrs(
449         xfs_inode_t     *ip,
450         xfs_trans_t     **tpp)
451 {
452         xfs_trans_t     *tp;
453         int             error;
454         xfs_mount_t     *mp;
455
456         ASSERT(xfs_isilocked(ip, XFS_IOLOCK_EXCL));
457         tp = *tpp;
458         mp = ip->i_mount;
459         ASSERT(ip->i_d.di_forkoff != 0);
460         error = xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
461         xfs_iunlock(ip, XFS_ILOCK_EXCL);
462         if (error)
463                 goto error_unlock;
464
465         error = xfs_attr_inactive(ip);
466         if (error)
467                 goto error_unlock;
468
469         tp = xfs_trans_alloc(mp, XFS_TRANS_INACTIVE);
470         error = xfs_trans_reserve(tp, 0,
471                                   XFS_IFREE_LOG_RES(mp),
472                                   0, XFS_TRANS_PERM_LOG_RES,
473                                   XFS_INACTIVE_LOG_COUNT);
474         if (error)
475                 goto error_cancel;
476
477         xfs_ilock(ip, XFS_ILOCK_EXCL);
478         xfs_trans_ijoin(tp, ip, 0);
479         xfs_idestroy_fork(ip, XFS_ATTR_FORK);
480
481         ASSERT(ip->i_d.di_anextents == 0);
482
483         *tpp = tp;
484         return 0;
485
486 error_cancel:
487         ASSERT(XFS_FORCED_SHUTDOWN(mp));
488         xfs_trans_cancel(tp, 0);
489 error_unlock:
490         *tpp = NULL;
491         xfs_iunlock(ip, XFS_IOLOCK_EXCL);
492         return error;
493 }
494
495 int
496 xfs_release(
497         xfs_inode_t     *ip)
498 {
499         xfs_mount_t     *mp = ip->i_mount;
500         int             error;
501
502         if (!S_ISREG(ip->i_d.di_mode) || (ip->i_d.di_mode == 0))
503                 return 0;
504
505         /* If this is a read-only mount, don't do this (would generate I/O) */
506         if (mp->m_flags & XFS_MOUNT_RDONLY)
507                 return 0;
508
509         if (!XFS_FORCED_SHUTDOWN(mp)) {
510                 int truncated;
511
512                 /*
513                  * If we are using filestreams, and we have an unlinked
514                  * file that we are processing the last close on, then nothing
515                  * will be able to reopen and write to this file. Purge this
516                  * inode from the filestreams cache so that it doesn't delay
517                  * teardown of the inode.
518                  */
519                 if ((ip->i_d.di_nlink == 0) && xfs_inode_is_filestream(ip))
520                         xfs_filestream_deassociate(ip);
521
522                 /*
523                  * If we previously truncated this file and removed old data
524                  * in the process, we want to initiate "early" writeout on
525                  * the last close.  This is an attempt to combat the notorious
526                  * NULL files problem which is particularly noticeable from a
527                  * truncate down, buffered (re-)write (delalloc), followed by
528                  * a crash.  What we are effectively doing here is
529                  * significantly reducing the time window where we'd otherwise
530                  * be exposed to that problem.
531                  */
532                 truncated = xfs_iflags_test_and_clear(ip, XFS_ITRUNCATED);
533                 if (truncated) {
534                         xfs_iflags_clear(ip, XFS_IDIRTY_RELEASE);
535                         if (VN_DIRTY(VFS_I(ip)) && ip->i_delayed_blks > 0)
536                                 xfs_flush_pages(ip, 0, -1, XBF_ASYNC, FI_NONE);
537                 }
538         }
539
540         if (ip->i_d.di_nlink == 0)
541                 return 0;
542
543         if ((S_ISREG(ip->i_d.di_mode) &&
544              ((ip->i_size > 0) || (VN_CACHED(VFS_I(ip)) > 0 ||
545                ip->i_delayed_blks > 0)) &&
546              (ip->i_df.if_flags & XFS_IFEXTENTS))  &&
547             (!(ip->i_d.di_flags & (XFS_DIFLAG_PREALLOC | XFS_DIFLAG_APPEND)))) {
548
549                 /*
550                  * If we can't get the iolock just skip truncating the blocks
551                  * past EOF because we could deadlock with the mmap_sem
552                  * otherwise.  We'll get another chance to drop them once the
553                  * last reference to the inode is dropped, so we'll never leak
554                  * blocks permanently.
555                  *
556                  * Further, check if the inode is being opened, written and
557                  * closed frequently and we have delayed allocation blocks
558                  * outstanding (e.g. streaming writes from the NFS server),
559                  * truncating the blocks past EOF will cause fragmentation to
560                  * occur.
561                  *
562                  * In this case don't do the truncation, either, but we have to
563                  * be careful how we detect this case. Blocks beyond EOF show
564                  * up as i_delayed_blks even when the inode is clean, so we
565                  * need to truncate them away first before checking for a dirty
566                  * release. Hence on the first dirty close we will still remove
567                  * the speculative allocation, but after that we will leave it
568                  * in place.
569                  */
570                 if (xfs_iflags_test(ip, XFS_IDIRTY_RELEASE))
571                         return 0;
572
573                 error = xfs_free_eofblocks(mp, ip,
574                                            XFS_FREE_EOF_TRYLOCK);
575                 if (error)
576                         return error;
577
578                 /* delalloc blocks after truncation means it really is dirty */
579                 if (ip->i_delayed_blks)
580                         xfs_iflags_set(ip, XFS_IDIRTY_RELEASE);
581         }
582         return 0;
583 }
584
585 /*
586  * xfs_inactive
587  *
588  * This is called when the vnode reference count for the vnode
589  * goes to zero.  If the file has been unlinked, then it must
590  * now be truncated.  Also, we clear all of the read-ahead state
591  * kept for the inode here since the file is now closed.
592  */
593 int
594 xfs_inactive(
595         xfs_inode_t     *ip)
596 {
597         xfs_bmap_free_t free_list;
598         xfs_fsblock_t   first_block;
599         int             committed;
600         xfs_trans_t     *tp;
601         xfs_mount_t     *mp;
602         int             error;
603         int             truncate;
604
605         /*
606          * If the inode is already free, then there can be nothing
607          * to clean up here.
608          */
609         if (ip->i_d.di_mode == 0 || is_bad_inode(VFS_I(ip))) {
610                 ASSERT(ip->i_df.if_real_bytes == 0);
611                 ASSERT(ip->i_df.if_broot_bytes == 0);
612                 return VN_INACTIVE_CACHE;
613         }
614
615         /*
616          * Only do a truncate if it's a regular file with
617          * some actual space in it.  It's OK to look at the
618          * inode's fields without the lock because we're the
619          * only one with a reference to the inode.
620          */
621         truncate = ((ip->i_d.di_nlink == 0) &&
622             ((ip->i_d.di_size != 0) || (ip->i_size != 0) ||
623              (ip->i_d.di_nextents > 0) || (ip->i_delayed_blks > 0)) &&
624             S_ISREG(ip->i_d.di_mode));
625
626         mp = ip->i_mount;
627
628         error = 0;
629
630         /* If this is a read-only mount, don't do this (would generate I/O) */
631         if (mp->m_flags & XFS_MOUNT_RDONLY)
632                 goto out;
633
634         if (ip->i_d.di_nlink != 0) {
635                 if ((S_ISREG(ip->i_d.di_mode) &&
636                      ((ip->i_size > 0) || (VN_CACHED(VFS_I(ip)) > 0 ||
637                        ip->i_delayed_blks > 0)) &&
638                       (ip->i_df.if_flags & XFS_IFEXTENTS) &&
639                      (!(ip->i_d.di_flags &
640                                 (XFS_DIFLAG_PREALLOC | XFS_DIFLAG_APPEND)) ||
641                       (ip->i_delayed_blks != 0)))) {
642                         error = xfs_free_eofblocks(mp, ip, 0);
643                         if (error)
644                                 return VN_INACTIVE_CACHE;
645                 }
646                 goto out;
647         }
648
649         ASSERT(ip->i_d.di_nlink == 0);
650
651         error = xfs_qm_dqattach(ip, 0);
652         if (error)
653                 return VN_INACTIVE_CACHE;
654
655         tp = xfs_trans_alloc(mp, XFS_TRANS_INACTIVE);
656         if (truncate) {
657                 xfs_ilock(ip, XFS_IOLOCK_EXCL);
658
659                 error = xfs_trans_reserve(tp, 0,
660                                           XFS_ITRUNCATE_LOG_RES(mp),
661                                           0, XFS_TRANS_PERM_LOG_RES,
662                                           XFS_ITRUNCATE_LOG_COUNT);
663                 if (error) {
664                         /* Don't call itruncate_cleanup */
665                         ASSERT(XFS_FORCED_SHUTDOWN(mp));
666                         xfs_trans_cancel(tp, 0);
667                         xfs_iunlock(ip, XFS_IOLOCK_EXCL);
668                         return VN_INACTIVE_CACHE;
669                 }
670
671                 xfs_ilock(ip, XFS_ILOCK_EXCL);
672                 xfs_trans_ijoin(tp, ip, 0);
673
674                 error = xfs_itruncate_data(&tp, ip, 0);
675                 if (error) {
676                         xfs_trans_cancel(tp,
677                                 XFS_TRANS_RELEASE_LOG_RES | XFS_TRANS_ABORT);
678                         xfs_iunlock(ip, XFS_IOLOCK_EXCL | XFS_ILOCK_EXCL);
679                         return VN_INACTIVE_CACHE;
680                 }
681         } else if (S_ISLNK(ip->i_d.di_mode)) {
682
683                 /*
684                  * If we get an error while cleaning up a
685                  * symlink we bail out.
686                  */
687                 error = (ip->i_d.di_size > XFS_IFORK_DSIZE(ip)) ?
688                         xfs_inactive_symlink_rmt(ip, &tp) :
689                         xfs_inactive_symlink_local(ip, &tp);
690
691                 if (error) {
692                         ASSERT(tp == NULL);
693                         return VN_INACTIVE_CACHE;
694                 }
695
696                 xfs_trans_ijoin(tp, ip, 0);
697         } else {
698                 error = xfs_trans_reserve(tp, 0,
699                                           XFS_IFREE_LOG_RES(mp),
700                                           0, XFS_TRANS_PERM_LOG_RES,
701                                           XFS_INACTIVE_LOG_COUNT);
702                 if (error) {
703                         ASSERT(XFS_FORCED_SHUTDOWN(mp));
704                         xfs_trans_cancel(tp, 0);
705                         return VN_INACTIVE_CACHE;
706                 }
707
708                 xfs_ilock(ip, XFS_ILOCK_EXCL | XFS_IOLOCK_EXCL);
709                 xfs_trans_ijoin(tp, ip, 0);
710         }
711
712         /*
713          * If there are attributes associated with the file
714          * then blow them away now.  The code calls a routine
715          * that recursively deconstructs the attribute fork.
716          * We need to just commit the current transaction
717          * because we can't use it for xfs_attr_inactive().
718          */
719         if (ip->i_d.di_anextents > 0) {
720                 error = xfs_inactive_attrs(ip, &tp);
721                 /*
722                  * If we got an error, the transaction is already
723                  * cancelled, and the inode is unlocked. Just get out.
724                  */
725                  if (error)
726                          return VN_INACTIVE_CACHE;
727         } else if (ip->i_afp) {
728                 xfs_idestroy_fork(ip, XFS_ATTR_FORK);
729         }
730
731         /*
732          * Free the inode.
733          */
734         xfs_bmap_init(&free_list, &first_block);
735         error = xfs_ifree(tp, ip, &free_list);
736         if (error) {
737                 /*
738                  * If we fail to free the inode, shut down.  The cancel
739                  * might do that, we need to make sure.  Otherwise the
740                  * inode might be lost for a long time or forever.
741                  */
742                 if (!XFS_FORCED_SHUTDOWN(mp)) {
743                         xfs_notice(mp, "%s: xfs_ifree returned error %d",
744                                 __func__, error);
745                         xfs_force_shutdown(mp, SHUTDOWN_META_IO_ERROR);
746                 }
747                 xfs_trans_cancel(tp, XFS_TRANS_RELEASE_LOG_RES|XFS_TRANS_ABORT);
748         } else {
749                 /*
750                  * Credit the quota account(s). The inode is gone.
751                  */
752                 xfs_trans_mod_dquot_byino(tp, ip, XFS_TRANS_DQ_ICOUNT, -1);
753
754                 /*
755                  * Just ignore errors at this point.  There is nothing we can
756                  * do except to try to keep going. Make sure it's not a silent
757                  * error.
758                  */
759                 error = xfs_bmap_finish(&tp,  &free_list, &committed);
760                 if (error)
761                         xfs_notice(mp, "%s: xfs_bmap_finish returned error %d",
762                                 __func__, error);
763                 error = xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
764                 if (error)
765                         xfs_notice(mp, "%s: xfs_trans_commit returned error %d",
766                                 __func__, error);
767         }
768
769         /*
770          * Release the dquots held by inode, if any.
771          */
772         xfs_qm_dqdetach(ip);
773         xfs_iunlock(ip, XFS_IOLOCK_EXCL | XFS_ILOCK_EXCL);
774
775  out:
776         return VN_INACTIVE_CACHE;
777 }
778
779 /*
780  * Lookups up an inode from "name". If ci_name is not NULL, then a CI match
781  * is allowed, otherwise it has to be an exact match. If a CI match is found,
782  * ci_name->name will point to a the actual name (caller must free) or
783  * will be set to NULL if an exact match is found.
784  */
785 int
786 xfs_lookup(
787         xfs_inode_t             *dp,
788         struct xfs_name         *name,
789         xfs_inode_t             **ipp,
790         struct xfs_name         *ci_name)
791 {
792         xfs_ino_t               inum;
793         int                     error;
794         uint                    lock_mode;
795
796         trace_xfs_lookup(dp, name);
797
798         if (XFS_FORCED_SHUTDOWN(dp->i_mount))
799                 return XFS_ERROR(EIO);
800
801         lock_mode = xfs_ilock_map_shared(dp);
802         error = xfs_dir_lookup(NULL, dp, name, &inum, ci_name);
803         xfs_iunlock_map_shared(dp, lock_mode);
804
805         if (error)
806                 goto out;
807
808         error = xfs_iget(dp->i_mount, NULL, inum, 0, 0, ipp);
809         if (error)
810                 goto out_free_name;
811
812         return 0;
813
814 out_free_name:
815         if (ci_name)
816                 kmem_free(ci_name->name);
817 out:
818         *ipp = NULL;
819         return error;
820 }
821
822 int
823 xfs_create(
824         xfs_inode_t             *dp,
825         struct xfs_name         *name,
826         mode_t                  mode,
827         xfs_dev_t               rdev,
828         xfs_inode_t             **ipp)
829 {
830         int                     is_dir = S_ISDIR(mode);
831         struct xfs_mount        *mp = dp->i_mount;
832         struct xfs_inode        *ip = NULL;
833         struct xfs_trans        *tp = NULL;
834         int                     error;
835         xfs_bmap_free_t         free_list;
836         xfs_fsblock_t           first_block;
837         boolean_t               unlock_dp_on_error = B_FALSE;
838         uint                    cancel_flags;
839         int                     committed;
840         prid_t                  prid;
841         struct xfs_dquot        *udqp = NULL;
842         struct xfs_dquot        *gdqp = NULL;
843         uint                    resblks;
844         uint                    log_res;
845         uint                    log_count;
846
847         trace_xfs_create(dp, name);
848
849         if (XFS_FORCED_SHUTDOWN(mp))
850                 return XFS_ERROR(EIO);
851
852         if (dp->i_d.di_flags & XFS_DIFLAG_PROJINHERIT)
853                 prid = xfs_get_projid(dp);
854         else
855                 prid = XFS_PROJID_DEFAULT;
856
857         /*
858          * Make sure that we have allocated dquot(s) on disk.
859          */
860         error = xfs_qm_vop_dqalloc(dp, current_fsuid(), current_fsgid(), prid,
861                         XFS_QMOPT_QUOTALL | XFS_QMOPT_INHERIT, &udqp, &gdqp);
862         if (error)
863                 return error;
864
865         if (is_dir) {
866                 rdev = 0;
867                 resblks = XFS_MKDIR_SPACE_RES(mp, name->len);
868                 log_res = XFS_MKDIR_LOG_RES(mp);
869                 log_count = XFS_MKDIR_LOG_COUNT;
870                 tp = xfs_trans_alloc(mp, XFS_TRANS_MKDIR);
871         } else {
872                 resblks = XFS_CREATE_SPACE_RES(mp, name->len);
873                 log_res = XFS_CREATE_LOG_RES(mp);
874                 log_count = XFS_CREATE_LOG_COUNT;
875                 tp = xfs_trans_alloc(mp, XFS_TRANS_CREATE);
876         }
877
878         cancel_flags = XFS_TRANS_RELEASE_LOG_RES;
879
880         /*
881          * Initially assume that the file does not exist and
882          * reserve the resources for that case.  If that is not
883          * the case we'll drop the one we have and get a more
884          * appropriate transaction later.
885          */
886         error = xfs_trans_reserve(tp, resblks, log_res, 0,
887                         XFS_TRANS_PERM_LOG_RES, log_count);
888         if (error == ENOSPC) {
889                 /* flush outstanding delalloc blocks and retry */
890                 xfs_flush_inodes(dp);
891                 error = xfs_trans_reserve(tp, resblks, log_res, 0,
892                                 XFS_TRANS_PERM_LOG_RES, log_count);
893         }
894         if (error == ENOSPC) {
895                 /* No space at all so try a "no-allocation" reservation */
896                 resblks = 0;
897                 error = xfs_trans_reserve(tp, 0, log_res, 0,
898                                 XFS_TRANS_PERM_LOG_RES, log_count);
899         }
900         if (error) {
901                 cancel_flags = 0;
902                 goto out_trans_cancel;
903         }
904
905         xfs_ilock(dp, XFS_ILOCK_EXCL | XFS_ILOCK_PARENT);
906         unlock_dp_on_error = B_TRUE;
907
908         /*
909          * Check for directory link count overflow.
910          */
911         if (is_dir && dp->i_d.di_nlink >= XFS_MAXLINK) {
912                 error = XFS_ERROR(EMLINK);
913                 goto out_trans_cancel;
914         }
915
916         xfs_bmap_init(&free_list, &first_block);
917
918         /*
919          * Reserve disk quota and the inode.
920          */
921         error = xfs_trans_reserve_quota(tp, mp, udqp, gdqp, resblks, 1, 0);
922         if (error)
923                 goto out_trans_cancel;
924
925         error = xfs_dir_canenter(tp, dp, name, resblks);
926         if (error)
927                 goto out_trans_cancel;
928
929         /*
930          * A newly created regular or special file just has one directory
931          * entry pointing to them, but a directory also the "." entry
932          * pointing to itself.
933          */
934         error = xfs_dir_ialloc(&tp, dp, mode, is_dir ? 2 : 1, rdev,
935                                prid, resblks > 0, &ip, &committed);
936         if (error) {
937                 if (error == ENOSPC)
938                         goto out_trans_cancel;
939                 goto out_trans_abort;
940         }
941
942         /*
943          * Now we join the directory inode to the transaction.  We do not do it
944          * earlier because xfs_dir_ialloc might commit the previous transaction
945          * (and release all the locks).  An error from here on will result in
946          * the transaction cancel unlocking dp so don't do it explicitly in the
947          * error path.
948          */
949         xfs_trans_ijoin(tp, dp, XFS_ILOCK_EXCL);
950         unlock_dp_on_error = B_FALSE;
951
952         error = xfs_dir_createname(tp, dp, name, ip->i_ino,
953                                         &first_block, &free_list, resblks ?
954                                         resblks - XFS_IALLOC_SPACE_RES(mp) : 0);
955         if (error) {
956                 ASSERT(error != ENOSPC);
957                 goto out_trans_abort;
958         }
959         xfs_trans_ichgtime(tp, dp, XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG);
960         xfs_trans_log_inode(tp, dp, XFS_ILOG_CORE);
961
962         if (is_dir) {
963                 error = xfs_dir_init(tp, ip, dp);
964                 if (error)
965                         goto out_bmap_cancel;
966
967                 error = xfs_bumplink(tp, dp);
968                 if (error)
969                         goto out_bmap_cancel;
970         }
971
972         /*
973          * If this is a synchronous mount, make sure that the
974          * create transaction goes to disk before returning to
975          * the user.
976          */
977         if (mp->m_flags & (XFS_MOUNT_WSYNC|XFS_MOUNT_DIRSYNC))
978                 xfs_trans_set_sync(tp);
979
980         /*
981          * Attach the dquot(s) to the inodes and modify them incore.
982          * These ids of the inode couldn't have changed since the new
983          * inode has been locked ever since it was created.
984          */
985         xfs_qm_vop_create_dqattach(tp, ip, udqp, gdqp);
986
987         error = xfs_bmap_finish(&tp, &free_list, &committed);
988         if (error)
989                 goto out_bmap_cancel;
990
991         error = xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
992         if (error)
993                 goto out_release_inode;
994
995         xfs_qm_dqrele(udqp);
996         xfs_qm_dqrele(gdqp);
997
998         *ipp = ip;
999         return 0;
1000
1001  out_bmap_cancel:
1002         xfs_bmap_cancel(&free_list);
1003  out_trans_abort:
1004         cancel_flags |= XFS_TRANS_ABORT;
1005  out_trans_cancel:
1006         xfs_trans_cancel(tp, cancel_flags);
1007  out_release_inode:
1008         /*
1009          * Wait until after the current transaction is aborted to
1010          * release the inode.  This prevents recursive transactions
1011          * and deadlocks from xfs_inactive.
1012          */
1013         if (ip)
1014                 IRELE(ip);
1015
1016         xfs_qm_dqrele(udqp);
1017         xfs_qm_dqrele(gdqp);
1018
1019         if (unlock_dp_on_error)
1020                 xfs_iunlock(dp, XFS_ILOCK_EXCL);
1021         return error;
1022 }
1023
1024 #ifdef DEBUG
1025 int xfs_locked_n;
1026 int xfs_small_retries;
1027 int xfs_middle_retries;
1028 int xfs_lots_retries;
1029 int xfs_lock_delays;
1030 #endif
1031
1032 /*
1033  * Bump the subclass so xfs_lock_inodes() acquires each lock with
1034  * a different value
1035  */
1036 static inline int
1037 xfs_lock_inumorder(int lock_mode, int subclass)
1038 {
1039         if (lock_mode & (XFS_IOLOCK_SHARED|XFS_IOLOCK_EXCL))
1040                 lock_mode |= (subclass + XFS_LOCK_INUMORDER) << XFS_IOLOCK_SHIFT;
1041         if (lock_mode & (XFS_ILOCK_SHARED|XFS_ILOCK_EXCL))
1042                 lock_mode |= (subclass + XFS_LOCK_INUMORDER) << XFS_ILOCK_SHIFT;
1043
1044         return lock_mode;
1045 }
1046
1047 /*
1048  * The following routine will lock n inodes in exclusive mode.
1049  * We assume the caller calls us with the inodes in i_ino order.
1050  *
1051  * We need to detect deadlock where an inode that we lock
1052  * is in the AIL and we start waiting for another inode that is locked
1053  * by a thread in a long running transaction (such as truncate). This can
1054  * result in deadlock since the long running trans might need to wait
1055  * for the inode we just locked in order to push the tail and free space
1056  * in the log.
1057  */
1058 void
1059 xfs_lock_inodes(
1060         xfs_inode_t     **ips,
1061         int             inodes,
1062         uint            lock_mode)
1063 {
1064         int             attempts = 0, i, j, try_lock;
1065         xfs_log_item_t  *lp;
1066
1067         ASSERT(ips && (inodes >= 2)); /* we need at least two */
1068
1069         try_lock = 0;
1070         i = 0;
1071
1072 again:
1073         for (; i < inodes; i++) {
1074                 ASSERT(ips[i]);
1075
1076                 if (i && (ips[i] == ips[i-1]))  /* Already locked */
1077                         continue;
1078
1079                 /*
1080                  * If try_lock is not set yet, make sure all locked inodes
1081                  * are not in the AIL.
1082                  * If any are, set try_lock to be used later.
1083                  */
1084
1085                 if (!try_lock) {
1086                         for (j = (i - 1); j >= 0 && !try_lock; j--) {
1087                                 lp = (xfs_log_item_t *)ips[j]->i_itemp;
1088                                 if (lp && (lp->li_flags & XFS_LI_IN_AIL)) {
1089                                         try_lock++;
1090                                 }
1091                         }
1092                 }
1093
1094                 /*
1095                  * If any of the previous locks we have locked is in the AIL,
1096                  * we must TRY to get the second and subsequent locks. If
1097                  * we can't get any, we must release all we have
1098                  * and try again.
1099                  */
1100
1101                 if (try_lock) {
1102                         /* try_lock must be 0 if i is 0. */
1103                         /*
1104                          * try_lock means we have an inode locked
1105                          * that is in the AIL.
1106                          */
1107                         ASSERT(i != 0);
1108                         if (!xfs_ilock_nowait(ips[i], xfs_lock_inumorder(lock_mode, i))) {
1109                                 attempts++;
1110
1111                                 /*
1112                                  * Unlock all previous guys and try again.
1113                                  * xfs_iunlock will try to push the tail
1114                                  * if the inode is in the AIL.
1115                                  */
1116
1117                                 for(j = i - 1; j >= 0; j--) {
1118
1119                                         /*
1120                                          * Check to see if we've already
1121                                          * unlocked this one.
1122                                          * Not the first one going back,
1123                                          * and the inode ptr is the same.
1124                                          */
1125                                         if ((j != (i - 1)) && ips[j] ==
1126                                                                 ips[j+1])
1127                                                 continue;
1128
1129                                         xfs_iunlock(ips[j], lock_mode);
1130                                 }
1131
1132                                 if ((attempts % 5) == 0) {
1133                                         delay(1); /* Don't just spin the CPU */
1134 #ifdef DEBUG
1135                                         xfs_lock_delays++;
1136 #endif
1137                                 }
1138                                 i = 0;
1139                                 try_lock = 0;
1140                                 goto again;
1141                         }
1142                 } else {
1143                         xfs_ilock(ips[i], xfs_lock_inumorder(lock_mode, i));
1144                 }
1145         }
1146
1147 #ifdef DEBUG
1148         if (attempts) {
1149                 if (attempts < 5) xfs_small_retries++;
1150                 else if (attempts < 100) xfs_middle_retries++;
1151                 else xfs_lots_retries++;
1152         } else {
1153                 xfs_locked_n++;
1154         }
1155 #endif
1156 }
1157
1158 /*
1159  * xfs_lock_two_inodes() can only be used to lock one type of lock
1160  * at a time - the iolock or the ilock, but not both at once. If
1161  * we lock both at once, lockdep will report false positives saying
1162  * we have violated locking orders.
1163  */
1164 void
1165 xfs_lock_two_inodes(
1166         xfs_inode_t             *ip0,
1167         xfs_inode_t             *ip1,
1168         uint                    lock_mode)
1169 {
1170         xfs_inode_t             *temp;
1171         int                     attempts = 0;
1172         xfs_log_item_t          *lp;
1173
1174         if (lock_mode & (XFS_IOLOCK_SHARED|XFS_IOLOCK_EXCL))
1175                 ASSERT((lock_mode & (XFS_ILOCK_SHARED|XFS_ILOCK_EXCL)) == 0);
1176         ASSERT(ip0->i_ino != ip1->i_ino);
1177
1178         if (ip0->i_ino > ip1->i_ino) {
1179                 temp = ip0;
1180                 ip0 = ip1;
1181                 ip1 = temp;
1182         }
1183
1184  again:
1185         xfs_ilock(ip0, xfs_lock_inumorder(lock_mode, 0));
1186
1187         /*
1188          * If the first lock we have locked is in the AIL, we must TRY to get
1189          * the second lock. If we can't get it, we must release the first one
1190          * and try again.
1191          */
1192         lp = (xfs_log_item_t *)ip0->i_itemp;
1193         if (lp && (lp->li_flags & XFS_LI_IN_AIL)) {
1194                 if (!xfs_ilock_nowait(ip1, xfs_lock_inumorder(lock_mode, 1))) {
1195                         xfs_iunlock(ip0, lock_mode);
1196                         if ((++attempts % 5) == 0)
1197                                 delay(1); /* Don't just spin the CPU */
1198                         goto again;
1199                 }
1200         } else {
1201                 xfs_ilock(ip1, xfs_lock_inumorder(lock_mode, 1));
1202         }
1203 }
1204
1205 int
1206 xfs_remove(
1207         xfs_inode_t             *dp,
1208         struct xfs_name         *name,
1209         xfs_inode_t             *ip)
1210 {
1211         xfs_mount_t             *mp = dp->i_mount;
1212         xfs_trans_t             *tp = NULL;
1213         int                     is_dir = S_ISDIR(ip->i_d.di_mode);
1214         int                     error = 0;
1215         xfs_bmap_free_t         free_list;
1216         xfs_fsblock_t           first_block;
1217         int                     cancel_flags;
1218         int                     committed;
1219         int                     link_zero;
1220         uint                    resblks;
1221         uint                    log_count;
1222
1223         trace_xfs_remove(dp, name);
1224
1225         if (XFS_FORCED_SHUTDOWN(mp))
1226                 return XFS_ERROR(EIO);
1227
1228         error = xfs_qm_dqattach(dp, 0);
1229         if (error)
1230                 goto std_return;
1231
1232         error = xfs_qm_dqattach(ip, 0);
1233         if (error)
1234                 goto std_return;
1235
1236         if (is_dir) {
1237                 tp = xfs_trans_alloc(mp, XFS_TRANS_RMDIR);
1238                 log_count = XFS_DEFAULT_LOG_COUNT;
1239         } else {
1240                 tp = xfs_trans_alloc(mp, XFS_TRANS_REMOVE);
1241                 log_count = XFS_REMOVE_LOG_COUNT;
1242         }
1243         cancel_flags = XFS_TRANS_RELEASE_LOG_RES;
1244
1245         /*
1246          * We try to get the real space reservation first,
1247          * allowing for directory btree deletion(s) implying
1248          * possible bmap insert(s).  If we can't get the space
1249          * reservation then we use 0 instead, and avoid the bmap
1250          * btree insert(s) in the directory code by, if the bmap
1251          * insert tries to happen, instead trimming the LAST
1252          * block from the directory.
1253          */
1254         resblks = XFS_REMOVE_SPACE_RES(mp);
1255         error = xfs_trans_reserve(tp, resblks, XFS_REMOVE_LOG_RES(mp), 0,
1256                                   XFS_TRANS_PERM_LOG_RES, log_count);
1257         if (error == ENOSPC) {
1258                 resblks = 0;
1259                 error = xfs_trans_reserve(tp, 0, XFS_REMOVE_LOG_RES(mp), 0,
1260                                           XFS_TRANS_PERM_LOG_RES, log_count);
1261         }
1262         if (error) {
1263                 ASSERT(error != ENOSPC);
1264                 cancel_flags = 0;
1265                 goto out_trans_cancel;
1266         }
1267
1268         xfs_lock_two_inodes(dp, ip, XFS_ILOCK_EXCL);
1269
1270         xfs_trans_ijoin(tp, dp, XFS_ILOCK_EXCL);
1271         xfs_trans_ijoin(tp, ip, XFS_ILOCK_EXCL);
1272
1273         /*
1274          * If we're removing a directory perform some additional validation.
1275          */
1276         if (is_dir) {
1277                 ASSERT(ip->i_d.di_nlink >= 2);
1278                 if (ip->i_d.di_nlink != 2) {
1279                         error = XFS_ERROR(ENOTEMPTY);
1280                         goto out_trans_cancel;
1281                 }
1282                 if (!xfs_dir_isempty(ip)) {
1283                         error = XFS_ERROR(ENOTEMPTY);
1284                         goto out_trans_cancel;
1285                 }
1286         }
1287
1288         xfs_bmap_init(&free_list, &first_block);
1289         error = xfs_dir_removename(tp, dp, name, ip->i_ino,
1290                                         &first_block, &free_list, resblks);
1291         if (error) {
1292                 ASSERT(error != ENOENT);
1293                 goto out_bmap_cancel;
1294         }
1295         xfs_trans_ichgtime(tp, dp, XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG);
1296
1297         if (is_dir) {
1298                 /*
1299                  * Drop the link from ip's "..".
1300                  */
1301                 error = xfs_droplink(tp, dp);
1302                 if (error)
1303                         goto out_bmap_cancel;
1304
1305                 /*
1306                  * Drop the "." link from ip to self.
1307                  */
1308                 error = xfs_droplink(tp, ip);
1309                 if (error)
1310                         goto out_bmap_cancel;
1311         } else {
1312                 /*
1313                  * When removing a non-directory we need to log the parent
1314                  * inode here.  For a directory this is done implicitly
1315                  * by the xfs_droplink call for the ".." entry.
1316                  */
1317                 xfs_trans_log_inode(tp, dp, XFS_ILOG_CORE);
1318         }
1319
1320         /*
1321          * Drop the link from dp to ip.
1322          */
1323         error = xfs_droplink(tp, ip);
1324         if (error)
1325                 goto out_bmap_cancel;
1326
1327         /*
1328          * Determine if this is the last link while
1329          * we are in the transaction.
1330          */
1331         link_zero = (ip->i_d.di_nlink == 0);
1332
1333         /*
1334          * If this is a synchronous mount, make sure that the
1335          * remove transaction goes to disk before returning to
1336          * the user.
1337          */
1338         if (mp->m_flags & (XFS_MOUNT_WSYNC|XFS_MOUNT_DIRSYNC))
1339                 xfs_trans_set_sync(tp);
1340
1341         error = xfs_bmap_finish(&tp, &free_list, &committed);
1342         if (error)
1343                 goto out_bmap_cancel;
1344
1345         error = xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
1346         if (error)
1347                 goto std_return;
1348
1349         /*
1350          * If we are using filestreams, kill the stream association.
1351          * If the file is still open it may get a new one but that
1352          * will get killed on last close in xfs_close() so we don't
1353          * have to worry about that.
1354          */
1355         if (!is_dir && link_zero && xfs_inode_is_filestream(ip))
1356                 xfs_filestream_deassociate(ip);
1357
1358         return 0;
1359
1360  out_bmap_cancel:
1361         xfs_bmap_cancel(&free_list);
1362         cancel_flags |= XFS_TRANS_ABORT;
1363  out_trans_cancel:
1364         xfs_trans_cancel(tp, cancel_flags);
1365  std_return:
1366         return error;
1367 }
1368
1369 int
1370 xfs_link(
1371         xfs_inode_t             *tdp,
1372         xfs_inode_t             *sip,
1373         struct xfs_name         *target_name)
1374 {
1375         xfs_mount_t             *mp = tdp->i_mount;
1376         xfs_trans_t             *tp;
1377         int                     error;
1378         xfs_bmap_free_t         free_list;
1379         xfs_fsblock_t           first_block;
1380         int                     cancel_flags;
1381         int                     committed;
1382         int                     resblks;
1383
1384         trace_xfs_link(tdp, target_name);
1385
1386         ASSERT(!S_ISDIR(sip->i_d.di_mode));
1387
1388         if (XFS_FORCED_SHUTDOWN(mp))
1389                 return XFS_ERROR(EIO);
1390
1391         error = xfs_qm_dqattach(sip, 0);
1392         if (error)
1393                 goto std_return;
1394
1395         error = xfs_qm_dqattach(tdp, 0);
1396         if (error)
1397                 goto std_return;
1398
1399         tp = xfs_trans_alloc(mp, XFS_TRANS_LINK);
1400         cancel_flags = XFS_TRANS_RELEASE_LOG_RES;
1401         resblks = XFS_LINK_SPACE_RES(mp, target_name->len);
1402         error = xfs_trans_reserve(tp, resblks, XFS_LINK_LOG_RES(mp), 0,
1403                         XFS_TRANS_PERM_LOG_RES, XFS_LINK_LOG_COUNT);
1404         if (error == ENOSPC) {
1405                 resblks = 0;
1406                 error = xfs_trans_reserve(tp, 0, XFS_LINK_LOG_RES(mp), 0,
1407                                 XFS_TRANS_PERM_LOG_RES, XFS_LINK_LOG_COUNT);
1408         }
1409         if (error) {
1410                 cancel_flags = 0;
1411                 goto error_return;
1412         }
1413
1414         xfs_lock_two_inodes(sip, tdp, XFS_ILOCK_EXCL);
1415
1416         xfs_trans_ijoin(tp, sip, XFS_ILOCK_EXCL);
1417         xfs_trans_ijoin(tp, tdp, XFS_ILOCK_EXCL);
1418
1419         /*
1420          * If the source has too many links, we can't make any more to it.
1421          */
1422         if (sip->i_d.di_nlink >= XFS_MAXLINK) {
1423                 error = XFS_ERROR(EMLINK);
1424                 goto error_return;
1425         }
1426
1427         /*
1428          * If we are using project inheritance, we only allow hard link
1429          * creation in our tree when the project IDs are the same; else
1430          * the tree quota mechanism could be circumvented.
1431          */
1432         if (unlikely((tdp->i_d.di_flags & XFS_DIFLAG_PROJINHERIT) &&
1433                      (xfs_get_projid(tdp) != xfs_get_projid(sip)))) {
1434                 error = XFS_ERROR(EXDEV);
1435                 goto error_return;
1436         }
1437
1438         error = xfs_dir_canenter(tp, tdp, target_name, resblks);
1439         if (error)
1440                 goto error_return;
1441
1442         xfs_bmap_init(&free_list, &first_block);
1443
1444         error = xfs_dir_createname(tp, tdp, target_name, sip->i_ino,
1445                                         &first_block, &free_list, resblks);
1446         if (error)
1447                 goto abort_return;
1448         xfs_trans_ichgtime(tp, tdp, XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG);
1449         xfs_trans_log_inode(tp, tdp, XFS_ILOG_CORE);
1450
1451         error = xfs_bumplink(tp, sip);
1452         if (error)
1453                 goto abort_return;
1454
1455         /*
1456          * If this is a synchronous mount, make sure that the
1457          * link transaction goes to disk before returning to
1458          * the user.
1459          */
1460         if (mp->m_flags & (XFS_MOUNT_WSYNC|XFS_MOUNT_DIRSYNC)) {
1461                 xfs_trans_set_sync(tp);
1462         }
1463
1464         error = xfs_bmap_finish (&tp, &free_list, &committed);
1465         if (error) {
1466                 xfs_bmap_cancel(&free_list);
1467                 goto abort_return;
1468         }
1469
1470         return xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
1471
1472  abort_return:
1473         cancel_flags |= XFS_TRANS_ABORT;
1474  error_return:
1475         xfs_trans_cancel(tp, cancel_flags);
1476  std_return:
1477         return error;
1478 }
1479
1480 int
1481 xfs_symlink(
1482         xfs_inode_t             *dp,
1483         struct xfs_name         *link_name,
1484         const char              *target_path,
1485         mode_t                  mode,
1486         xfs_inode_t             **ipp)
1487 {
1488         xfs_mount_t             *mp = dp->i_mount;
1489         xfs_trans_t             *tp;
1490         xfs_inode_t             *ip;
1491         int                     error;
1492         int                     pathlen;
1493         xfs_bmap_free_t         free_list;
1494         xfs_fsblock_t           first_block;
1495         boolean_t               unlock_dp_on_error = B_FALSE;
1496         uint                    cancel_flags;
1497         int                     committed;
1498         xfs_fileoff_t           first_fsb;
1499         xfs_filblks_t           fs_blocks;
1500         int                     nmaps;
1501         xfs_bmbt_irec_t         mval[SYMLINK_MAPS];
1502         xfs_daddr_t             d;
1503         const char              *cur_chunk;
1504         int                     byte_cnt;
1505         int                     n;
1506         xfs_buf_t               *bp;
1507         prid_t                  prid;
1508         struct xfs_dquot        *udqp, *gdqp;
1509         uint                    resblks;
1510
1511         *ipp = NULL;
1512         error = 0;
1513         ip = NULL;
1514         tp = NULL;
1515
1516         trace_xfs_symlink(dp, link_name);
1517
1518         if (XFS_FORCED_SHUTDOWN(mp))
1519                 return XFS_ERROR(EIO);
1520
1521         /*
1522          * Check component lengths of the target path name.
1523          */
1524         pathlen = strlen(target_path);
1525         if (pathlen >= MAXPATHLEN)      /* total string too long */
1526                 return XFS_ERROR(ENAMETOOLONG);
1527
1528         udqp = gdqp = NULL;
1529         if (dp->i_d.di_flags & XFS_DIFLAG_PROJINHERIT)
1530                 prid = xfs_get_projid(dp);
1531         else
1532                 prid = XFS_PROJID_DEFAULT;
1533
1534         /*
1535          * Make sure that we have allocated dquot(s) on disk.
1536          */
1537         error = xfs_qm_vop_dqalloc(dp, current_fsuid(), current_fsgid(), prid,
1538                         XFS_QMOPT_QUOTALL | XFS_QMOPT_INHERIT, &udqp, &gdqp);
1539         if (error)
1540                 goto std_return;
1541
1542         tp = xfs_trans_alloc(mp, XFS_TRANS_SYMLINK);
1543         cancel_flags = XFS_TRANS_RELEASE_LOG_RES;
1544         /*
1545          * The symlink will fit into the inode data fork?
1546          * There can't be any attributes so we get the whole variable part.
1547          */
1548         if (pathlen <= XFS_LITINO(mp))
1549                 fs_blocks = 0;
1550         else
1551                 fs_blocks = XFS_B_TO_FSB(mp, pathlen);
1552         resblks = XFS_SYMLINK_SPACE_RES(mp, link_name->len, fs_blocks);
1553         error = xfs_trans_reserve(tp, resblks, XFS_SYMLINK_LOG_RES(mp), 0,
1554                         XFS_TRANS_PERM_LOG_RES, XFS_SYMLINK_LOG_COUNT);
1555         if (error == ENOSPC && fs_blocks == 0) {
1556                 resblks = 0;
1557                 error = xfs_trans_reserve(tp, 0, XFS_SYMLINK_LOG_RES(mp), 0,
1558                                 XFS_TRANS_PERM_LOG_RES, XFS_SYMLINK_LOG_COUNT);
1559         }
1560         if (error) {
1561                 cancel_flags = 0;
1562                 goto error_return;
1563         }
1564
1565         xfs_ilock(dp, XFS_ILOCK_EXCL | XFS_ILOCK_PARENT);
1566         unlock_dp_on_error = B_TRUE;
1567
1568         /*
1569          * Check whether the directory allows new symlinks or not.
1570          */
1571         if (dp->i_d.di_flags & XFS_DIFLAG_NOSYMLINKS) {
1572                 error = XFS_ERROR(EPERM);
1573                 goto error_return;
1574         }
1575
1576         /*
1577          * Reserve disk quota : blocks and inode.
1578          */
1579         error = xfs_trans_reserve_quota(tp, mp, udqp, gdqp, resblks, 1, 0);
1580         if (error)
1581                 goto error_return;
1582
1583         /*
1584          * Check for ability to enter directory entry, if no space reserved.
1585          */
1586         error = xfs_dir_canenter(tp, dp, link_name, resblks);
1587         if (error)
1588                 goto error_return;
1589         /*
1590          * Initialize the bmap freelist prior to calling either
1591          * bmapi or the directory create code.
1592          */
1593         xfs_bmap_init(&free_list, &first_block);
1594
1595         /*
1596          * Allocate an inode for the symlink.
1597          */
1598         error = xfs_dir_ialloc(&tp, dp, S_IFLNK | (mode & ~S_IFMT), 1, 0,
1599                                prid, resblks > 0, &ip, NULL);
1600         if (error) {
1601                 if (error == ENOSPC)
1602                         goto error_return;
1603                 goto error1;
1604         }
1605
1606         /*
1607          * An error after we've joined dp to the transaction will result in the
1608          * transaction cancel unlocking dp so don't do it explicitly in the
1609          * error path.
1610          */
1611         xfs_trans_ijoin(tp, dp, XFS_ILOCK_EXCL);
1612         unlock_dp_on_error = B_FALSE;
1613
1614         /*
1615          * Also attach the dquot(s) to it, if applicable.
1616          */
1617         xfs_qm_vop_create_dqattach(tp, ip, udqp, gdqp);
1618
1619         if (resblks)
1620                 resblks -= XFS_IALLOC_SPACE_RES(mp);
1621         /*
1622          * If the symlink will fit into the inode, write it inline.
1623          */
1624         if (pathlen <= XFS_IFORK_DSIZE(ip)) {
1625                 xfs_idata_realloc(ip, pathlen, XFS_DATA_FORK);
1626                 memcpy(ip->i_df.if_u1.if_data, target_path, pathlen);
1627                 ip->i_d.di_size = pathlen;
1628
1629                 /*
1630                  * The inode was initially created in extent format.
1631                  */
1632                 ip->i_df.if_flags &= ~(XFS_IFEXTENTS | XFS_IFBROOT);
1633                 ip->i_df.if_flags |= XFS_IFINLINE;
1634
1635                 ip->i_d.di_format = XFS_DINODE_FMT_LOCAL;
1636                 xfs_trans_log_inode(tp, ip, XFS_ILOG_DDATA | XFS_ILOG_CORE);
1637
1638         } else {
1639                 first_fsb = 0;
1640                 nmaps = SYMLINK_MAPS;
1641
1642                 error = xfs_bmapi_write(tp, ip, first_fsb, fs_blocks,
1643                                   XFS_BMAPI_METADATA, &first_block, resblks,
1644                                   mval, &nmaps, &free_list);
1645                 if (error)
1646                         goto error2;
1647
1648                 if (resblks)
1649                         resblks -= fs_blocks;
1650                 ip->i_d.di_size = pathlen;
1651                 xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
1652
1653                 cur_chunk = target_path;
1654                 for (n = 0; n < nmaps; n++) {
1655                         d = XFS_FSB_TO_DADDR(mp, mval[n].br_startblock);
1656                         byte_cnt = XFS_FSB_TO_B(mp, mval[n].br_blockcount);
1657                         bp = xfs_trans_get_buf(tp, mp->m_ddev_targp, d,
1658                                                BTOBB(byte_cnt), 0);
1659                         if (!bp) {
1660                                 error = ENOMEM;
1661                                 goto error2;
1662                         }
1663                         if (pathlen < byte_cnt) {
1664                                 byte_cnt = pathlen;
1665                         }
1666                         pathlen -= byte_cnt;
1667
1668                         memcpy(bp->b_addr, cur_chunk, byte_cnt);
1669                         cur_chunk += byte_cnt;
1670
1671                         xfs_trans_log_buf(tp, bp, 0, byte_cnt - 1);
1672                 }
1673         }
1674
1675         /*
1676          * Create the directory entry for the symlink.
1677          */
1678         error = xfs_dir_createname(tp, dp, link_name, ip->i_ino,
1679                                         &first_block, &free_list, resblks);
1680         if (error)
1681                 goto error2;
1682         xfs_trans_ichgtime(tp, dp, XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG);
1683         xfs_trans_log_inode(tp, dp, XFS_ILOG_CORE);
1684
1685         /*
1686          * If this is a synchronous mount, make sure that the
1687          * symlink transaction goes to disk before returning to
1688          * the user.
1689          */
1690         if (mp->m_flags & (XFS_MOUNT_WSYNC|XFS_MOUNT_DIRSYNC)) {
1691                 xfs_trans_set_sync(tp);
1692         }
1693
1694         error = xfs_bmap_finish(&tp, &free_list, &committed);
1695         if (error) {
1696                 goto error2;
1697         }
1698         error = xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
1699         xfs_qm_dqrele(udqp);
1700         xfs_qm_dqrele(gdqp);
1701
1702         *ipp = ip;
1703         return 0;
1704
1705  error2:
1706         IRELE(ip);
1707  error1:
1708         xfs_bmap_cancel(&free_list);
1709         cancel_flags |= XFS_TRANS_ABORT;
1710  error_return:
1711         xfs_trans_cancel(tp, cancel_flags);
1712         xfs_qm_dqrele(udqp);
1713         xfs_qm_dqrele(gdqp);
1714
1715         if (unlock_dp_on_error)
1716                 xfs_iunlock(dp, XFS_ILOCK_EXCL);
1717  std_return:
1718         return error;
1719 }
1720
1721 int
1722 xfs_set_dmattrs(
1723         xfs_inode_t     *ip,
1724         u_int           evmask,
1725         u_int16_t       state)
1726 {
1727         xfs_mount_t     *mp = ip->i_mount;
1728         xfs_trans_t     *tp;
1729         int             error;
1730
1731         if (!capable(CAP_SYS_ADMIN))
1732                 return XFS_ERROR(EPERM);
1733
1734         if (XFS_FORCED_SHUTDOWN(mp))
1735                 return XFS_ERROR(EIO);
1736
1737         tp = xfs_trans_alloc(mp, XFS_TRANS_SET_DMATTRS);
1738         error = xfs_trans_reserve(tp, 0, XFS_ICHANGE_LOG_RES (mp), 0, 0, 0);
1739         if (error) {
1740                 xfs_trans_cancel(tp, 0);
1741                 return error;
1742         }
1743         xfs_ilock(ip, XFS_ILOCK_EXCL);
1744         xfs_trans_ijoin(tp, ip, XFS_ILOCK_EXCL);
1745
1746         ip->i_d.di_dmevmask = evmask;
1747         ip->i_d.di_dmstate  = state;
1748
1749         xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
1750         error = xfs_trans_commit(tp, 0);
1751
1752         return error;
1753 }
1754
1755 /*
1756  * xfs_alloc_file_space()
1757  *      This routine allocates disk space for the given file.
1758  *
1759  *      If alloc_type == 0, this request is for an ALLOCSP type
1760  *      request which will change the file size.  In this case, no
1761  *      DMAPI event will be generated by the call.  A TRUNCATE event
1762  *      will be generated later by xfs_setattr.
1763  *
1764  *      If alloc_type != 0, this request is for a RESVSP type
1765  *      request, and a DMAPI DM_EVENT_WRITE will be generated if the
1766  *      lower block boundary byte address is less than the file's
1767  *      length.
1768  *
1769  * RETURNS:
1770  *       0 on success
1771  *      errno on error
1772  *
1773  */
1774 STATIC int
1775 xfs_alloc_file_space(
1776         xfs_inode_t             *ip,
1777         xfs_off_t               offset,
1778         xfs_off_t               len,
1779         int                     alloc_type,
1780         int                     attr_flags)
1781 {
1782         xfs_mount_t             *mp = ip->i_mount;
1783         xfs_off_t               count;
1784         xfs_filblks_t           allocated_fsb;
1785         xfs_filblks_t           allocatesize_fsb;
1786         xfs_extlen_t            extsz, temp;
1787         xfs_fileoff_t           startoffset_fsb;
1788         xfs_fsblock_t           firstfsb;
1789         int                     nimaps;
1790         int                     quota_flag;
1791         int                     rt;
1792         xfs_trans_t             *tp;
1793         xfs_bmbt_irec_t         imaps[1], *imapp;
1794         xfs_bmap_free_t         free_list;
1795         uint                    qblocks, resblks, resrtextents;
1796         int                     committed;
1797         int                     error;
1798
1799         trace_xfs_alloc_file_space(ip);
1800
1801         if (XFS_FORCED_SHUTDOWN(mp))
1802                 return XFS_ERROR(EIO);
1803
1804         error = xfs_qm_dqattach(ip, 0);
1805         if (error)
1806                 return error;
1807
1808         if (len <= 0)
1809                 return XFS_ERROR(EINVAL);
1810
1811         rt = XFS_IS_REALTIME_INODE(ip);
1812         extsz = xfs_get_extsz_hint(ip);
1813
1814         count = len;
1815         imapp = &imaps[0];
1816         nimaps = 1;
1817         startoffset_fsb = XFS_B_TO_FSBT(mp, offset);
1818         allocatesize_fsb = XFS_B_TO_FSB(mp, count);
1819
1820         /*
1821          * Allocate file space until done or until there is an error
1822          */
1823         while (allocatesize_fsb && !error) {
1824                 xfs_fileoff_t   s, e;
1825
1826                 /*
1827                  * Determine space reservations for data/realtime.
1828                  */
1829                 if (unlikely(extsz)) {
1830                         s = startoffset_fsb;
1831                         do_div(s, extsz);
1832                         s *= extsz;
1833                         e = startoffset_fsb + allocatesize_fsb;
1834                         if ((temp = do_mod(startoffset_fsb, extsz)))
1835                                 e += temp;
1836                         if ((temp = do_mod(e, extsz)))
1837                                 e += extsz - temp;
1838                 } else {
1839                         s = 0;
1840                         e = allocatesize_fsb;
1841                 }
1842
1843                 /*
1844                  * The transaction reservation is limited to a 32-bit block
1845                  * count, hence we need to limit the number of blocks we are
1846                  * trying to reserve to avoid an overflow. We can't allocate
1847                  * more than @nimaps extents, and an extent is limited on disk
1848                  * to MAXEXTLEN (21 bits), so use that to enforce the limit.
1849                  */
1850                 resblks = min_t(xfs_fileoff_t, (e - s), (MAXEXTLEN * nimaps));
1851                 if (unlikely(rt)) {
1852                         resrtextents = qblocks = resblks;
1853                         resrtextents /= mp->m_sb.sb_rextsize;
1854                         resblks = XFS_DIOSTRAT_SPACE_RES(mp, 0);
1855                         quota_flag = XFS_QMOPT_RES_RTBLKS;
1856                 } else {
1857                         resrtextents = 0;
1858                         resblks = qblocks = XFS_DIOSTRAT_SPACE_RES(mp, resblks);
1859                         quota_flag = XFS_QMOPT_RES_REGBLKS;
1860                 }
1861
1862                 /*
1863                  * Allocate and setup the transaction.
1864                  */
1865                 tp = xfs_trans_alloc(mp, XFS_TRANS_DIOSTRAT);
1866                 error = xfs_trans_reserve(tp, resblks,
1867                                           XFS_WRITE_LOG_RES(mp), resrtextents,
1868                                           XFS_TRANS_PERM_LOG_RES,
1869                                           XFS_WRITE_LOG_COUNT);
1870                 /*
1871                  * Check for running out of space
1872                  */
1873                 if (error) {
1874                         /*
1875                          * Free the transaction structure.
1876                          */
1877                         ASSERT(error == ENOSPC || XFS_FORCED_SHUTDOWN(mp));
1878                         xfs_trans_cancel(tp, 0);
1879                         break;
1880                 }
1881                 xfs_ilock(ip, XFS_ILOCK_EXCL);
1882                 error = xfs_trans_reserve_quota_nblks(tp, ip, qblocks,
1883                                                       0, quota_flag);
1884                 if (error)
1885                         goto error1;
1886
1887                 xfs_trans_ijoin(tp, ip, 0);
1888
1889                 xfs_bmap_init(&free_list, &firstfsb);
1890                 error = xfs_bmapi_write(tp, ip, startoffset_fsb,
1891                                         allocatesize_fsb, alloc_type, &firstfsb,
1892                                         0, imapp, &nimaps, &free_list);
1893                 if (error) {
1894                         goto error0;
1895                 }
1896
1897                 /*
1898                  * Complete the transaction
1899                  */
1900                 error = xfs_bmap_finish(&tp, &free_list, &committed);
1901                 if (error) {
1902                         goto error0;
1903                 }
1904
1905                 error = xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
1906                 xfs_iunlock(ip, XFS_ILOCK_EXCL);
1907                 if (error) {
1908                         break;
1909                 }
1910
1911                 allocated_fsb = imapp->br_blockcount;
1912
1913                 if (nimaps == 0) {
1914                         error = XFS_ERROR(ENOSPC);
1915                         break;
1916                 }
1917
1918                 startoffset_fsb += allocated_fsb;
1919                 allocatesize_fsb -= allocated_fsb;
1920         }
1921
1922         return error;
1923
1924 error0: /* Cancel bmap, unlock inode, unreserve quota blocks, cancel trans */
1925         xfs_bmap_cancel(&free_list);
1926         xfs_trans_unreserve_quota_nblks(tp, ip, qblocks, 0, quota_flag);
1927
1928 error1: /* Just cancel transaction */
1929         xfs_trans_cancel(tp, XFS_TRANS_RELEASE_LOG_RES | XFS_TRANS_ABORT);
1930         xfs_iunlock(ip, XFS_ILOCK_EXCL);
1931         return error;
1932 }
1933
1934 /*
1935  * Zero file bytes between startoff and endoff inclusive.
1936  * The iolock is held exclusive and no blocks are buffered.
1937  *
1938  * This function is used by xfs_free_file_space() to zero
1939  * partial blocks when the range to free is not block aligned.
1940  * When unreserving space with boundaries that are not block
1941  * aligned we round up the start and round down the end
1942  * boundaries and then use this function to zero the parts of
1943  * the blocks that got dropped during the rounding.
1944  */
1945 STATIC int
1946 xfs_zero_remaining_bytes(
1947         xfs_inode_t             *ip,
1948         xfs_off_t               startoff,
1949         xfs_off_t               endoff)
1950 {
1951         xfs_bmbt_irec_t         imap;
1952         xfs_fileoff_t           offset_fsb;
1953         xfs_off_t               lastoffset;
1954         xfs_off_t               offset;
1955         xfs_buf_t               *bp;
1956         xfs_mount_t             *mp = ip->i_mount;
1957         int                     nimap;
1958         int                     error = 0;
1959
1960         /*
1961          * Avoid doing I/O beyond eof - it's not necessary
1962          * since nothing can read beyond eof.  The space will
1963          * be zeroed when the file is extended anyway.
1964          */
1965         if (startoff >= ip->i_size)
1966                 return 0;
1967
1968         if (endoff > ip->i_size)
1969                 endoff = ip->i_size;
1970
1971         bp = xfs_buf_get_uncached(XFS_IS_REALTIME_INODE(ip) ?
1972                                         mp->m_rtdev_targp : mp->m_ddev_targp,
1973                                 mp->m_sb.sb_blocksize, XBF_DONT_BLOCK);
1974         if (!bp)
1975                 return XFS_ERROR(ENOMEM);
1976
1977         xfs_buf_unlock(bp);
1978
1979         for (offset = startoff; offset <= endoff; offset = lastoffset + 1) {
1980                 offset_fsb = XFS_B_TO_FSBT(mp, offset);
1981                 nimap = 1;
1982                 error = xfs_bmapi_read(ip, offset_fsb, 1, &imap, &nimap, 0);
1983                 if (error || nimap < 1)
1984                         break;
1985                 ASSERT(imap.br_blockcount >= 1);
1986                 ASSERT(imap.br_startoff == offset_fsb);
1987                 lastoffset = XFS_FSB_TO_B(mp, imap.br_startoff + 1) - 1;
1988                 if (lastoffset > endoff)
1989                         lastoffset = endoff;
1990                 if (imap.br_startblock == HOLESTARTBLOCK)
1991                         continue;
1992                 ASSERT(imap.br_startblock != DELAYSTARTBLOCK);
1993                 if (imap.br_state == XFS_EXT_UNWRITTEN)
1994                         continue;
1995                 XFS_BUF_UNDONE(bp);
1996                 XFS_BUF_UNWRITE(bp);
1997                 XFS_BUF_READ(bp);
1998                 XFS_BUF_SET_ADDR(bp, xfs_fsb_to_db(ip, imap.br_startblock));
1999                 xfsbdstrat(mp, bp);
2000                 error = xfs_buf_iowait(bp);
2001                 if (error) {
2002                         xfs_buf_ioerror_alert(bp,
2003                                         "xfs_zero_remaining_bytes(read)");
2004                         break;
2005                 }
2006                 memset(bp->b_addr +
2007                         (offset - XFS_FSB_TO_B(mp, imap.br_startoff)),
2008                       0, lastoffset - offset + 1);
2009                 XFS_BUF_UNDONE(bp);
2010                 XFS_BUF_UNREAD(bp);
2011                 XFS_BUF_WRITE(bp);
2012                 xfsbdstrat(mp, bp);
2013                 error = xfs_buf_iowait(bp);
2014                 if (error) {
2015                         xfs_buf_ioerror_alert(bp,
2016                                         "xfs_zero_remaining_bytes(write)");
2017                         break;
2018                 }
2019         }
2020         xfs_buf_free(bp);
2021         return error;
2022 }
2023
2024 /*
2025  * xfs_free_file_space()
2026  *      This routine frees disk space for the given file.
2027  *
2028  *      This routine is only called by xfs_change_file_space
2029  *      for an UNRESVSP type call.
2030  *
2031  * RETURNS:
2032  *       0 on success
2033  *      errno on error
2034  *
2035  */
2036 STATIC int
2037 xfs_free_file_space(
2038         xfs_inode_t             *ip,
2039         xfs_off_t               offset,
2040         xfs_off_t               len,
2041         int                     attr_flags)
2042 {
2043         int                     committed;
2044         int                     done;
2045         xfs_fileoff_t           endoffset_fsb;
2046         int                     error;
2047         xfs_fsblock_t           firstfsb;
2048         xfs_bmap_free_t         free_list;
2049         xfs_bmbt_irec_t         imap;
2050         xfs_off_t               ioffset;
2051         xfs_extlen_t            mod=0;
2052         xfs_mount_t             *mp;
2053         int                     nimap;
2054         uint                    resblks;
2055         uint                    rounding;
2056         int                     rt;
2057         xfs_fileoff_t           startoffset_fsb;
2058         xfs_trans_t             *tp;
2059         int                     need_iolock = 1;
2060
2061         mp = ip->i_mount;
2062
2063         trace_xfs_free_file_space(ip);
2064
2065         error = xfs_qm_dqattach(ip, 0);
2066         if (error)
2067                 return error;
2068
2069         error = 0;
2070         if (len <= 0)   /* if nothing being freed */
2071                 return error;
2072         rt = XFS_IS_REALTIME_INODE(ip);
2073         startoffset_fsb = XFS_B_TO_FSB(mp, offset);
2074         endoffset_fsb = XFS_B_TO_FSBT(mp, offset + len);
2075
2076         if (attr_flags & XFS_ATTR_NOLOCK)
2077                 need_iolock = 0;
2078         if (need_iolock) {
2079                 xfs_ilock(ip, XFS_IOLOCK_EXCL);
2080                 /* wait for the completion of any pending DIOs */
2081                 inode_dio_wait(VFS_I(ip));
2082         }
2083
2084         rounding = max_t(uint, 1 << mp->m_sb.sb_blocklog, PAGE_CACHE_SIZE);
2085         ioffset = offset & ~(rounding - 1);
2086
2087         if (VN_CACHED(VFS_I(ip)) != 0) {
2088                 error = xfs_flushinval_pages(ip, ioffset, -1, FI_REMAPF_LOCKED);
2089                 if (error)
2090                         goto out_unlock_iolock;
2091         }
2092
2093         /*
2094          * Need to zero the stuff we're not freeing, on disk.
2095          * If it's a realtime file & can't use unwritten extents then we
2096          * actually need to zero the extent edges.  Otherwise xfs_bunmapi
2097          * will take care of it for us.
2098          */
2099         if (rt && !xfs_sb_version_hasextflgbit(&mp->m_sb)) {
2100                 nimap = 1;
2101                 error = xfs_bmapi_read(ip, startoffset_fsb, 1,
2102                                         &imap, &nimap, 0);
2103                 if (error)
2104                         goto out_unlock_iolock;
2105                 ASSERT(nimap == 0 || nimap == 1);
2106                 if (nimap && imap.br_startblock != HOLESTARTBLOCK) {
2107                         xfs_daddr_t     block;
2108
2109                         ASSERT(imap.br_startblock != DELAYSTARTBLOCK);
2110                         block = imap.br_startblock;
2111                         mod = do_div(block, mp->m_sb.sb_rextsize);
2112                         if (mod)
2113                                 startoffset_fsb += mp->m_sb.sb_rextsize - mod;
2114                 }
2115                 nimap = 1;
2116                 error = xfs_bmapi_read(ip, endoffset_fsb - 1, 1,
2117                                         &imap, &nimap, 0);
2118                 if (error)
2119                         goto out_unlock_iolock;
2120                 ASSERT(nimap == 0 || nimap == 1);
2121                 if (nimap && imap.br_startblock != HOLESTARTBLOCK) {
2122                         ASSERT(imap.br_startblock != DELAYSTARTBLOCK);
2123                         mod++;
2124                         if (mod && (mod != mp->m_sb.sb_rextsize))
2125                                 endoffset_fsb -= mod;
2126                 }
2127         }
2128         if ((done = (endoffset_fsb <= startoffset_fsb)))
2129                 /*
2130                  * One contiguous piece to clear
2131                  */
2132                 error = xfs_zero_remaining_bytes(ip, offset, offset + len - 1);
2133         else {
2134                 /*
2135                  * Some full blocks, possibly two pieces to clear
2136                  */
2137                 if (offset < XFS_FSB_TO_B(mp, startoffset_fsb))
2138                         error = xfs_zero_remaining_bytes(ip, offset,
2139                                 XFS_FSB_TO_B(mp, startoffset_fsb) - 1);
2140                 if (!error &&
2141                     XFS_FSB_TO_B(mp, endoffset_fsb) < offset + len)
2142                         error = xfs_zero_remaining_bytes(ip,
2143                                 XFS_FSB_TO_B(mp, endoffset_fsb),
2144                                 offset + len - 1);
2145         }
2146
2147         /*
2148          * free file space until done or until there is an error
2149          */
2150         resblks = XFS_DIOSTRAT_SPACE_RES(mp, 0);
2151         while (!error && !done) {
2152
2153                 /*
2154                  * allocate and setup the transaction. Allow this
2155                  * transaction to dip into the reserve blocks to ensure
2156                  * the freeing of the space succeeds at ENOSPC.
2157                  */
2158                 tp = xfs_trans_alloc(mp, XFS_TRANS_DIOSTRAT);
2159                 tp->t_flags |= XFS_TRANS_RESERVE;
2160                 error = xfs_trans_reserve(tp,
2161                                           resblks,
2162                                           XFS_WRITE_LOG_RES(mp),
2163                                           0,
2164                                           XFS_TRANS_PERM_LOG_RES,
2165                                           XFS_WRITE_LOG_COUNT);
2166
2167                 /*
2168                  * check for running out of space
2169                  */
2170                 if (error) {
2171                         /*
2172                          * Free the transaction structure.
2173                          */
2174                         ASSERT(error == ENOSPC || XFS_FORCED_SHUTDOWN(mp));
2175                         xfs_trans_cancel(tp, 0);
2176                         break;
2177                 }
2178                 xfs_ilock(ip, XFS_ILOCK_EXCL);
2179                 error = xfs_trans_reserve_quota(tp, mp,
2180                                 ip->i_udquot, ip->i_gdquot,
2181                                 resblks, 0, XFS_QMOPT_RES_REGBLKS);
2182                 if (error)
2183                         goto error1;
2184
2185                 xfs_trans_ijoin(tp, ip, 0);
2186
2187                 /*
2188                  * issue the bunmapi() call to free the blocks
2189                  */
2190                 xfs_bmap_init(&free_list, &firstfsb);
2191                 error = xfs_bunmapi(tp, ip, startoffset_fsb,
2192                                   endoffset_fsb - startoffset_fsb,
2193                                   0, 2, &firstfsb, &free_list, &done);
2194                 if (error) {
2195                         goto error0;
2196                 }
2197
2198                 /*
2199                  * complete the transaction
2200                  */
2201                 error = xfs_bmap_finish(&tp, &free_list, &committed);
2202                 if (error) {
2203                         goto error0;
2204                 }
2205
2206                 error = xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
2207                 xfs_iunlock(ip, XFS_ILOCK_EXCL);
2208         }
2209
2210  out_unlock_iolock:
2211         if (need_iolock)
2212                 xfs_iunlock(ip, XFS_IOLOCK_EXCL);
2213         return error;
2214
2215  error0:
2216         xfs_bmap_cancel(&free_list);
2217  error1:
2218         xfs_trans_cancel(tp, XFS_TRANS_RELEASE_LOG_RES | XFS_TRANS_ABORT);
2219         xfs_iunlock(ip, need_iolock ? (XFS_ILOCK_EXCL | XFS_IOLOCK_EXCL) :
2220                     XFS_ILOCK_EXCL);
2221         return error;
2222 }
2223
2224 /*
2225  * xfs_change_file_space()
2226  *      This routine allocates or frees disk space for the given file.
2227  *      The user specified parameters are checked for alignment and size
2228  *      limitations.
2229  *
2230  * RETURNS:
2231  *       0 on success
2232  *      errno on error
2233  *
2234  */
2235 int
2236 xfs_change_file_space(
2237         xfs_inode_t     *ip,
2238         int             cmd,
2239         xfs_flock64_t   *bf,
2240         xfs_off_t       offset,
2241         int             attr_flags)
2242 {
2243         xfs_mount_t     *mp = ip->i_mount;
2244         int             clrprealloc;
2245         int             error;
2246         xfs_fsize_t     fsize;
2247         int             setprealloc;
2248         xfs_off_t       startoffset;
2249         xfs_off_t       llen;
2250         xfs_trans_t     *tp;
2251         struct iattr    iattr;
2252         int             prealloc_type;
2253
2254         if (!S_ISREG(ip->i_d.di_mode))
2255                 return XFS_ERROR(EINVAL);
2256
2257         switch (bf->l_whence) {
2258         case 0: /*SEEK_SET*/
2259                 break;
2260         case 1: /*SEEK_CUR*/
2261                 bf->l_start += offset;
2262                 break;
2263         case 2: /*SEEK_END*/
2264                 bf->l_start += ip->i_size;
2265                 break;
2266         default:
2267                 return XFS_ERROR(EINVAL);
2268         }
2269
2270         llen = bf->l_len > 0 ? bf->l_len - 1 : bf->l_len;
2271
2272         if (   (bf->l_start < 0)
2273             || (bf->l_start > XFS_MAXIOFFSET(mp))
2274             || (bf->l_start + llen < 0)
2275             || (bf->l_start + llen > XFS_MAXIOFFSET(mp)))
2276                 return XFS_ERROR(EINVAL);
2277
2278         bf->l_whence = 0;
2279
2280         startoffset = bf->l_start;
2281         fsize = ip->i_size;
2282
2283         /*
2284          * XFS_IOC_RESVSP and XFS_IOC_UNRESVSP will reserve or unreserve
2285          * file space.
2286          * These calls do NOT zero the data space allocated to the file,
2287          * nor do they change the file size.
2288          *
2289          * XFS_IOC_ALLOCSP and XFS_IOC_FREESP will allocate and free file
2290          * space.
2291          * These calls cause the new file data to be zeroed and the file
2292          * size to be changed.
2293          */
2294         setprealloc = clrprealloc = 0;
2295         prealloc_type = XFS_BMAPI_PREALLOC;
2296
2297         switch (cmd) {
2298         case XFS_IOC_ZERO_RANGE:
2299                 prealloc_type |= XFS_BMAPI_CONVERT;
2300                 xfs_tosspages(ip, startoffset, startoffset + bf->l_len, 0);
2301                 /* FALLTHRU */
2302         case XFS_IOC_RESVSP:
2303         case XFS_IOC_RESVSP64:
2304                 error = xfs_alloc_file_space(ip, startoffset, bf->l_len,
2305                                                 prealloc_type, attr_flags);
2306                 if (error)
2307                         return error;
2308                 setprealloc = 1;
2309                 break;
2310
2311         case XFS_IOC_UNRESVSP:
2312         case XFS_IOC_UNRESVSP64:
2313                 if ((error = xfs_free_file_space(ip, startoffset, bf->l_len,
2314                                                                 attr_flags)))
2315                         return error;
2316                 break;
2317
2318         case XFS_IOC_ALLOCSP:
2319         case XFS_IOC_ALLOCSP64:
2320         case XFS_IOC_FREESP:
2321         case XFS_IOC_FREESP64:
2322                 if (startoffset > fsize) {
2323                         error = xfs_alloc_file_space(ip, fsize,
2324                                         startoffset - fsize, 0, attr_flags);
2325                         if (error)
2326                                 break;
2327                 }
2328
2329                 iattr.ia_valid = ATTR_SIZE;
2330                 iattr.ia_size = startoffset;
2331
2332                 error = xfs_setattr_size(ip, &iattr, attr_flags);
2333
2334                 if (error)
2335                         return error;
2336
2337                 clrprealloc = 1;
2338                 break;
2339
2340         default:
2341                 ASSERT(0);
2342                 return XFS_ERROR(EINVAL);
2343         }
2344
2345         /*
2346          * update the inode timestamp, mode, and prealloc flag bits
2347          */
2348         tp = xfs_trans_alloc(mp, XFS_TRANS_WRITEID);
2349
2350         if ((error = xfs_trans_reserve(tp, 0, XFS_WRITEID_LOG_RES(mp),
2351                                       0, 0, 0))) {
2352                 /* ASSERT(0); */
2353                 xfs_trans_cancel(tp, 0);
2354                 return error;
2355         }
2356
2357         xfs_ilock(ip, XFS_ILOCK_EXCL);
2358         xfs_trans_ijoin(tp, ip, XFS_ILOCK_EXCL);
2359
2360         if ((attr_flags & XFS_ATTR_DMI) == 0) {
2361                 ip->i_d.di_mode &= ~S_ISUID;
2362
2363                 /*
2364                  * Note that we don't have to worry about mandatory
2365                  * file locking being disabled here because we only
2366                  * clear the S_ISGID bit if the Group execute bit is
2367                  * on, but if it was on then mandatory locking wouldn't
2368                  * have been enabled.
2369                  */
2370                 if (ip->i_d.di_mode & S_IXGRP)
2371                         ip->i_d.di_mode &= ~S_ISGID;
2372
2373                 xfs_trans_ichgtime(tp, ip, XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG);
2374         }
2375         if (setprealloc)
2376                 ip->i_d.di_flags |= XFS_DIFLAG_PREALLOC;
2377         else if (clrprealloc)
2378                 ip->i_d.di_flags &= ~XFS_DIFLAG_PREALLOC;
2379
2380         xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
2381         if (attr_flags & XFS_ATTR_SYNC)
2382                 xfs_trans_set_sync(tp);
2383         return xfs_trans_commit(tp, 0);
2384 }