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