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