Merge remote-tracking branch 'origin/develop-3.0' into develop-3.0-jb
[firefly-linux-kernel-4.4.55.git] / fs / xfs / xfs_vnodeops.c
1 /*
2  * Copyright (c) 2000-2006 Silicon Graphics, Inc.
3  * All Rights Reserved.
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License as
7  * published by the Free Software Foundation.
8  *
9  * This program is distributed in the hope that it would be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write the Free Software Foundation,
16  * Inc.,  51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17  */
18
19 #include "xfs.h"
20 #include "xfs_fs.h"
21 #include "xfs_types.h"
22 #include "xfs_bit.h"
23 #include "xfs_log.h"
24 #include "xfs_inum.h"
25 #include "xfs_trans.h"
26 #include "xfs_sb.h"
27 #include "xfs_ag.h"
28 #include "xfs_dir2.h"
29 #include "xfs_mount.h"
30 #include "xfs_da_btree.h"
31 #include "xfs_bmap_btree.h"
32 #include "xfs_ialloc_btree.h"
33 #include "xfs_dinode.h"
34 #include "xfs_inode.h"
35 #include "xfs_inode_item.h"
36 #include "xfs_itable.h"
37 #include "xfs_ialloc.h"
38 #include "xfs_alloc.h"
39 #include "xfs_bmap.h"
40 #include "xfs_acl.h"
41 #include "xfs_attr.h"
42 #include "xfs_rw.h"
43 #include "xfs_error.h"
44 #include "xfs_quota.h"
45 #include "xfs_utils.h"
46 #include "xfs_rtalloc.h"
47 #include "xfs_trans_space.h"
48 #include "xfs_log_priv.h"
49 #include "xfs_filestream.h"
50 #include "xfs_vnodeops.h"
51 #include "xfs_trace.h"
52
53 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, xfs_get_projid(ip),
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         xfs_fsize_t     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         pathlen = ip->i_d.di_size;
549         if (!pathlen)
550                 goto out;
551
552         if (pathlen < 0 || pathlen > MAXPATHLEN) {
553                 xfs_alert(mp, "%s: inode (%llu) bad symlink length (%lld)",
554                          __func__, (unsigned long long) ip->i_ino,
555                          (long long) pathlen);
556                 ASSERT(0);
557                 error = XFS_ERROR(EFSCORRUPTED);
558                 goto out;
559         }
560
561
562         if (ip->i_df.if_flags & XFS_IFINLINE) {
563                 memcpy(link, ip->i_df.if_u1.if_data, pathlen);
564                 link[pathlen] = '\0';
565         } else {
566                 error = xfs_readlink_bmap(ip, link);
567         }
568
569  out:
570         xfs_iunlock(ip, XFS_ILOCK_SHARED);
571         return error;
572 }
573
574 /*
575  * Flags for xfs_free_eofblocks
576  */
577 #define XFS_FREE_EOF_TRYLOCK    (1<<0)
578
579 /*
580  * This is called by xfs_inactive to free any blocks beyond eof
581  * when the link count isn't zero and by xfs_dm_punch_hole() when
582  * punching a hole to EOF.
583  */
584 STATIC int
585 xfs_free_eofblocks(
586         xfs_mount_t     *mp,
587         xfs_inode_t     *ip,
588         int             flags)
589 {
590         xfs_trans_t     *tp;
591         int             error;
592         xfs_fileoff_t   end_fsb;
593         xfs_fileoff_t   last_fsb;
594         xfs_filblks_t   map_len;
595         int             nimaps;
596         xfs_bmbt_irec_t imap;
597
598         /*
599          * Figure out if there are any blocks beyond the end
600          * of the file.  If not, then there is nothing to do.
601          */
602         end_fsb = XFS_B_TO_FSB(mp, ((xfs_ufsize_t)ip->i_size));
603         last_fsb = XFS_B_TO_FSB(mp, (xfs_ufsize_t)XFS_MAXIOFFSET(mp));
604         if (last_fsb <= end_fsb)
605                 return 0;
606         map_len = last_fsb - end_fsb;
607
608         nimaps = 1;
609         xfs_ilock(ip, XFS_ILOCK_SHARED);
610         error = xfs_bmapi(NULL, ip, end_fsb, map_len, 0,
611                           NULL, 0, &imap, &nimaps, NULL);
612         xfs_iunlock(ip, XFS_ILOCK_SHARED);
613
614         if (!error && (nimaps != 0) &&
615             (imap.br_startblock != HOLESTARTBLOCK ||
616              ip->i_delayed_blks)) {
617                 /*
618                  * Attach the dquots to the inode up front.
619                  */
620                 error = xfs_qm_dqattach(ip, 0);
621                 if (error)
622                         return error;
623
624                 /*
625                  * There are blocks after the end of file.
626                  * Free them up now by truncating the file to
627                  * its current size.
628                  */
629                 tp = xfs_trans_alloc(mp, XFS_TRANS_INACTIVE);
630
631                 /*
632                  * Do the xfs_itruncate_start() call before
633                  * reserving any log space because
634                  * itruncate_start will call into the buffer
635                  * cache and we can't
636                  * do that within a transaction.
637                  */
638                 if (flags & XFS_FREE_EOF_TRYLOCK) {
639                         if (!xfs_ilock_nowait(ip, XFS_IOLOCK_EXCL)) {
640                                 xfs_trans_cancel(tp, 0);
641                                 return 0;
642                         }
643                 } else {
644                         xfs_ilock(ip, XFS_IOLOCK_EXCL);
645                 }
646                 error = xfs_itruncate_start(ip, XFS_ITRUNC_DEFINITE,
647                                     ip->i_size);
648                 if (error) {
649                         xfs_trans_cancel(tp, 0);
650                         xfs_iunlock(ip, XFS_IOLOCK_EXCL);
651                         return error;
652                 }
653
654                 error = xfs_trans_reserve(tp, 0,
655                                           XFS_ITRUNCATE_LOG_RES(mp),
656                                           0, XFS_TRANS_PERM_LOG_RES,
657                                           XFS_ITRUNCATE_LOG_COUNT);
658                 if (error) {
659                         ASSERT(XFS_FORCED_SHUTDOWN(mp));
660                         xfs_trans_cancel(tp, 0);
661                         xfs_iunlock(ip, XFS_IOLOCK_EXCL);
662                         return error;
663                 }
664
665                 xfs_ilock(ip, XFS_ILOCK_EXCL);
666                 xfs_trans_ijoin(tp, ip);
667
668                 error = xfs_itruncate_finish(&tp, ip,
669                                              ip->i_size,
670                                              XFS_DATA_FORK,
671                                              0);
672                 /*
673                  * If we get an error at this point we
674                  * simply don't bother truncating the file.
675                  */
676                 if (error) {
677                         xfs_trans_cancel(tp,
678                                          (XFS_TRANS_RELEASE_LOG_RES |
679                                           XFS_TRANS_ABORT));
680                 } else {
681                         error = xfs_trans_commit(tp,
682                                                 XFS_TRANS_RELEASE_LOG_RES);
683                 }
684                 xfs_iunlock(ip, XFS_IOLOCK_EXCL|XFS_ILOCK_EXCL);
685         }
686         return error;
687 }
688
689 /*
690  * Free a symlink that has blocks associated with it.
691  */
692 STATIC int
693 xfs_inactive_symlink_rmt(
694         xfs_inode_t     *ip,
695         xfs_trans_t     **tpp)
696 {
697         xfs_buf_t       *bp;
698         int             committed;
699         int             done;
700         int             error;
701         xfs_fsblock_t   first_block;
702         xfs_bmap_free_t free_list;
703         int             i;
704         xfs_mount_t     *mp;
705         xfs_bmbt_irec_t mval[SYMLINK_MAPS];
706         int             nmaps;
707         xfs_trans_t     *ntp;
708         int             size;
709         xfs_trans_t     *tp;
710
711         tp = *tpp;
712         mp = ip->i_mount;
713         ASSERT(ip->i_d.di_size > XFS_IFORK_DSIZE(ip));
714         /*
715          * We're freeing a symlink that has some
716          * blocks allocated to it.  Free the
717          * blocks here.  We know that we've got
718          * either 1 or 2 extents and that we can
719          * free them all in one bunmapi call.
720          */
721         ASSERT(ip->i_d.di_nextents > 0 && ip->i_d.di_nextents <= 2);
722         if ((error = xfs_trans_reserve(tp, 0, XFS_ITRUNCATE_LOG_RES(mp), 0,
723                         XFS_TRANS_PERM_LOG_RES, XFS_ITRUNCATE_LOG_COUNT))) {
724                 ASSERT(XFS_FORCED_SHUTDOWN(mp));
725                 xfs_trans_cancel(tp, 0);
726                 *tpp = NULL;
727                 return error;
728         }
729         /*
730          * Lock the inode, fix the size, and join it to the transaction.
731          * Hold it so in the normal path, we still have it locked for
732          * the second transaction.  In the error paths we need it
733          * held so the cancel won't rele it, see below.
734          */
735         xfs_ilock(ip, XFS_IOLOCK_EXCL | XFS_ILOCK_EXCL);
736         size = (int)ip->i_d.di_size;
737         ip->i_d.di_size = 0;
738         xfs_trans_ijoin(tp, ip);
739         xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
740         /*
741          * Find the block(s) so we can inval and unmap them.
742          */
743         done = 0;
744         xfs_bmap_init(&free_list, &first_block);
745         nmaps = ARRAY_SIZE(mval);
746         if ((error = xfs_bmapi(tp, ip, 0, XFS_B_TO_FSB(mp, size),
747                         XFS_BMAPI_METADATA, &first_block, 0, mval, &nmaps,
748                         &free_list)))
749                 goto error0;
750         /*
751          * Invalidate the block(s).
752          */
753         for (i = 0; i < nmaps; i++) {
754                 bp = xfs_trans_get_buf(tp, mp->m_ddev_targp,
755                         XFS_FSB_TO_DADDR(mp, mval[i].br_startblock),
756                         XFS_FSB_TO_BB(mp, mval[i].br_blockcount), 0);
757                 xfs_trans_binval(tp, bp);
758         }
759         /*
760          * Unmap the dead block(s) to the free_list.
761          */
762         if ((error = xfs_bunmapi(tp, ip, 0, size, XFS_BMAPI_METADATA, nmaps,
763                         &first_block, &free_list, &done)))
764                 goto error1;
765         ASSERT(done);
766         /*
767          * Commit the first transaction.  This logs the EFI and the inode.
768          */
769         if ((error = xfs_bmap_finish(&tp, &free_list, &committed)))
770                 goto error1;
771         /*
772          * The transaction must have been committed, since there were
773          * actually extents freed by xfs_bunmapi.  See xfs_bmap_finish.
774          * The new tp has the extent freeing and EFDs.
775          */
776         ASSERT(committed);
777         /*
778          * The first xact was committed, so add the inode to the new one.
779          * Mark it dirty so it will be logged and moved forward in the log as
780          * part of every commit.
781          */
782         xfs_trans_ijoin(tp, ip);
783         xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
784         /*
785          * Get a new, empty transaction to return to our caller.
786          */
787         ntp = xfs_trans_dup(tp);
788         /*
789          * Commit the transaction containing extent freeing and EFDs.
790          * If we get an error on the commit here or on the reserve below,
791          * we need to unlock the inode since the new transaction doesn't
792          * have the inode attached.
793          */
794         error = xfs_trans_commit(tp, 0);
795         tp = ntp;
796         if (error) {
797                 ASSERT(XFS_FORCED_SHUTDOWN(mp));
798                 goto error0;
799         }
800         /*
801          * transaction commit worked ok so we can drop the extra ticket
802          * reference that we gained in xfs_trans_dup()
803          */
804         xfs_log_ticket_put(tp->t_ticket);
805
806         /*
807          * Remove the memory for extent descriptions (just bookkeeping).
808          */
809         if (ip->i_df.if_bytes)
810                 xfs_idata_realloc(ip, -ip->i_df.if_bytes, XFS_DATA_FORK);
811         ASSERT(ip->i_df.if_bytes == 0);
812         /*
813          * Put an itruncate log reservation in the new transaction
814          * for our caller.
815          */
816         if ((error = xfs_trans_reserve(tp, 0, XFS_ITRUNCATE_LOG_RES(mp), 0,
817                         XFS_TRANS_PERM_LOG_RES, XFS_ITRUNCATE_LOG_COUNT))) {
818                 ASSERT(XFS_FORCED_SHUTDOWN(mp));
819                 goto error0;
820         }
821         /*
822          * Return with the inode locked but not joined to the transaction.
823          */
824         *tpp = tp;
825         return 0;
826
827  error1:
828         xfs_bmap_cancel(&free_list);
829  error0:
830         /*
831          * Have to come here with the inode locked and either
832          * (held and in the transaction) or (not in the transaction).
833          * If the inode isn't held then cancel would iput it, but
834          * that's wrong since this is inactive and the vnode ref
835          * count is 0 already.
836          * Cancel won't do anything to the inode if held, but it still
837          * needs to be locked until the cancel is done, if it was
838          * joined to the transaction.
839          */
840         xfs_trans_cancel(tp, XFS_TRANS_RELEASE_LOG_RES | XFS_TRANS_ABORT);
841         xfs_iunlock(ip, XFS_IOLOCK_EXCL | XFS_ILOCK_EXCL);
842         *tpp = NULL;
843         return error;
844
845 }
846
847 STATIC int
848 xfs_inactive_symlink_local(
849         xfs_inode_t     *ip,
850         xfs_trans_t     **tpp)
851 {
852         int             error;
853
854         ASSERT(ip->i_d.di_size <= XFS_IFORK_DSIZE(ip));
855         /*
856          * We're freeing a symlink which fit into
857          * the inode.  Just free the memory used
858          * to hold the old symlink.
859          */
860         error = xfs_trans_reserve(*tpp, 0,
861                                   XFS_ITRUNCATE_LOG_RES(ip->i_mount),
862                                   0, XFS_TRANS_PERM_LOG_RES,
863                                   XFS_ITRUNCATE_LOG_COUNT);
864
865         if (error) {
866                 xfs_trans_cancel(*tpp, 0);
867                 *tpp = NULL;
868                 return error;
869         }
870         xfs_ilock(ip, XFS_ILOCK_EXCL | XFS_IOLOCK_EXCL);
871
872         /*
873          * Zero length symlinks _can_ exist.
874          */
875         if (ip->i_df.if_bytes > 0) {
876                 xfs_idata_realloc(ip,
877                                   -(ip->i_df.if_bytes),
878                                   XFS_DATA_FORK);
879                 ASSERT(ip->i_df.if_bytes == 0);
880         }
881         return 0;
882 }
883
884 STATIC int
885 xfs_inactive_attrs(
886         xfs_inode_t     *ip,
887         xfs_trans_t     **tpp)
888 {
889         xfs_trans_t     *tp;
890         int             error;
891         xfs_mount_t     *mp;
892
893         ASSERT(xfs_isilocked(ip, XFS_IOLOCK_EXCL));
894         tp = *tpp;
895         mp = ip->i_mount;
896         ASSERT(ip->i_d.di_forkoff != 0);
897         error = xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
898         xfs_iunlock(ip, XFS_ILOCK_EXCL);
899         if (error)
900                 goto error_unlock;
901
902         error = xfs_attr_inactive(ip);
903         if (error)
904                 goto error_unlock;
905
906         tp = xfs_trans_alloc(mp, XFS_TRANS_INACTIVE);
907         error = xfs_trans_reserve(tp, 0,
908                                   XFS_IFREE_LOG_RES(mp),
909                                   0, XFS_TRANS_PERM_LOG_RES,
910                                   XFS_INACTIVE_LOG_COUNT);
911         if (error)
912                 goto error_cancel;
913
914         xfs_ilock(ip, XFS_ILOCK_EXCL);
915         xfs_trans_ijoin(tp, ip);
916         xfs_idestroy_fork(ip, XFS_ATTR_FORK);
917
918         ASSERT(ip->i_d.di_anextents == 0);
919
920         *tpp = tp;
921         return 0;
922
923 error_cancel:
924         ASSERT(XFS_FORCED_SHUTDOWN(mp));
925         xfs_trans_cancel(tp, 0);
926 error_unlock:
927         *tpp = NULL;
928         xfs_iunlock(ip, XFS_IOLOCK_EXCL);
929         return error;
930 }
931
932 int
933 xfs_release(
934         xfs_inode_t     *ip)
935 {
936         xfs_mount_t     *mp = ip->i_mount;
937         int             error;
938
939         if (!S_ISREG(ip->i_d.di_mode) || (ip->i_d.di_mode == 0))
940                 return 0;
941
942         /* If this is a read-only mount, don't do this (would generate I/O) */
943         if (mp->m_flags & XFS_MOUNT_RDONLY)
944                 return 0;
945
946         if (!XFS_FORCED_SHUTDOWN(mp)) {
947                 int truncated;
948
949                 /*
950                  * If we are using filestreams, and we have an unlinked
951                  * file that we are processing the last close on, then nothing
952                  * will be able to reopen and write to this file. Purge this
953                  * inode from the filestreams cache so that it doesn't delay
954                  * teardown of the inode.
955                  */
956                 if ((ip->i_d.di_nlink == 0) && xfs_inode_is_filestream(ip))
957                         xfs_filestream_deassociate(ip);
958
959                 /*
960                  * If we previously truncated this file and removed old data
961                  * in the process, we want to initiate "early" writeout on
962                  * the last close.  This is an attempt to combat the notorious
963                  * NULL files problem which is particularly noticeable from a
964                  * truncate down, buffered (re-)write (delalloc), followed by
965                  * a crash.  What we are effectively doing here is
966                  * significantly reducing the time window where we'd otherwise
967                  * be exposed to that problem.
968                  */
969                 truncated = xfs_iflags_test_and_clear(ip, XFS_ITRUNCATED);
970                 if (truncated) {
971                         xfs_iflags_clear(ip, XFS_IDIRTY_RELEASE);
972                         if (VN_DIRTY(VFS_I(ip)) && ip->i_delayed_blks > 0)
973                                 xfs_flush_pages(ip, 0, -1, XBF_ASYNC, FI_NONE);
974                 }
975         }
976
977         if (ip->i_d.di_nlink == 0)
978                 return 0;
979
980         if ((((ip->i_d.di_mode & S_IFMT) == S_IFREG) &&
981              ((ip->i_size > 0) || (VN_CACHED(VFS_I(ip)) > 0 ||
982                ip->i_delayed_blks > 0)) &&
983              (ip->i_df.if_flags & XFS_IFEXTENTS))  &&
984             (!(ip->i_d.di_flags & (XFS_DIFLAG_PREALLOC | XFS_DIFLAG_APPEND)))) {
985
986                 /*
987                  * If we can't get the iolock just skip truncating the blocks
988                  * past EOF because we could deadlock with the mmap_sem
989                  * otherwise.  We'll get another chance to drop them once the
990                  * last reference to the inode is dropped, so we'll never leak
991                  * blocks permanently.
992                  *
993                  * Further, check if the inode is being opened, written and
994                  * closed frequently and we have delayed allocation blocks
995                  * outstanding (e.g. streaming writes from the NFS server),
996                  * truncating the blocks past EOF will cause fragmentation to
997                  * occur.
998                  *
999                  * In this case don't do the truncation, either, but we have to
1000                  * be careful how we detect this case. Blocks beyond EOF show
1001                  * up as i_delayed_blks even when the inode is clean, so we
1002                  * need to truncate them away first before checking for a dirty
1003                  * release. Hence on the first dirty close we will still remove
1004                  * the speculative allocation, but after that we will leave it
1005                  * in place.
1006                  */
1007                 if (xfs_iflags_test(ip, XFS_IDIRTY_RELEASE))
1008                         return 0;
1009
1010                 error = xfs_free_eofblocks(mp, ip,
1011                                            XFS_FREE_EOF_TRYLOCK);
1012                 if (error)
1013                         return error;
1014
1015                 /* delalloc blocks after truncation means it really is dirty */
1016                 if (ip->i_delayed_blks)
1017                         xfs_iflags_set(ip, XFS_IDIRTY_RELEASE);
1018         }
1019         return 0;
1020 }
1021
1022 /*
1023  * xfs_inactive
1024  *
1025  * This is called when the vnode reference count for the vnode
1026  * goes to zero.  If the file has been unlinked, then it must
1027  * now be truncated.  Also, we clear all of the read-ahead state
1028  * kept for the inode here since the file is now closed.
1029  */
1030 int
1031 xfs_inactive(
1032         xfs_inode_t     *ip)
1033 {
1034         xfs_bmap_free_t free_list;
1035         xfs_fsblock_t   first_block;
1036         int             committed;
1037         xfs_trans_t     *tp;
1038         xfs_mount_t     *mp;
1039         int             error;
1040         int             truncate;
1041
1042         /*
1043          * If the inode is already free, then there can be nothing
1044          * to clean up here.
1045          */
1046         if (ip->i_d.di_mode == 0 || is_bad_inode(VFS_I(ip))) {
1047                 ASSERT(ip->i_df.if_real_bytes == 0);
1048                 ASSERT(ip->i_df.if_broot_bytes == 0);
1049                 return VN_INACTIVE_CACHE;
1050         }
1051
1052         /*
1053          * Only do a truncate if it's a regular file with
1054          * some actual space in it.  It's OK to look at the
1055          * inode's fields without the lock because we're the
1056          * only one with a reference to the inode.
1057          */
1058         truncate = ((ip->i_d.di_nlink == 0) &&
1059             ((ip->i_d.di_size != 0) || (ip->i_size != 0) ||
1060              (ip->i_d.di_nextents > 0) || (ip->i_delayed_blks > 0)) &&
1061             ((ip->i_d.di_mode & S_IFMT) == S_IFREG));
1062
1063         mp = ip->i_mount;
1064
1065         error = 0;
1066
1067         /* If this is a read-only mount, don't do this (would generate I/O) */
1068         if (mp->m_flags & XFS_MOUNT_RDONLY)
1069                 goto out;
1070
1071         if (ip->i_d.di_nlink != 0) {
1072                 if ((((ip->i_d.di_mode & S_IFMT) == S_IFREG) &&
1073                      ((ip->i_size > 0) || (VN_CACHED(VFS_I(ip)) > 0 ||
1074                        ip->i_delayed_blks > 0)) &&
1075                       (ip->i_df.if_flags & XFS_IFEXTENTS) &&
1076                      (!(ip->i_d.di_flags &
1077                                 (XFS_DIFLAG_PREALLOC | XFS_DIFLAG_APPEND)) ||
1078                       (ip->i_delayed_blks != 0)))) {
1079                         error = xfs_free_eofblocks(mp, ip, 0);
1080                         if (error)
1081                                 return VN_INACTIVE_CACHE;
1082                 }
1083                 goto out;
1084         }
1085
1086         ASSERT(ip->i_d.di_nlink == 0);
1087
1088         error = xfs_qm_dqattach(ip, 0);
1089         if (error)
1090                 return VN_INACTIVE_CACHE;
1091
1092         tp = xfs_trans_alloc(mp, XFS_TRANS_INACTIVE);
1093         if (truncate) {
1094                 /*
1095                  * Do the xfs_itruncate_start() call before
1096                  * reserving any log space because itruncate_start
1097                  * will call into the buffer cache and we can't
1098                  * do that within a transaction.
1099                  */
1100                 xfs_ilock(ip, XFS_IOLOCK_EXCL);
1101
1102                 error = xfs_itruncate_start(ip, XFS_ITRUNC_DEFINITE, 0);
1103                 if (error) {
1104                         xfs_trans_cancel(tp, 0);
1105                         xfs_iunlock(ip, XFS_IOLOCK_EXCL);
1106                         return VN_INACTIVE_CACHE;
1107                 }
1108
1109                 error = xfs_trans_reserve(tp, 0,
1110                                           XFS_ITRUNCATE_LOG_RES(mp),
1111                                           0, XFS_TRANS_PERM_LOG_RES,
1112                                           XFS_ITRUNCATE_LOG_COUNT);
1113                 if (error) {
1114                         /* Don't call itruncate_cleanup */
1115                         ASSERT(XFS_FORCED_SHUTDOWN(mp));
1116                         xfs_trans_cancel(tp, 0);
1117                         xfs_iunlock(ip, XFS_IOLOCK_EXCL);
1118                         return VN_INACTIVE_CACHE;
1119                 }
1120
1121                 xfs_ilock(ip, XFS_ILOCK_EXCL);
1122                 xfs_trans_ijoin(tp, ip);
1123
1124                 /*
1125                  * normally, we have to run xfs_itruncate_finish sync.
1126                  * But if filesystem is wsync and we're in the inactive
1127                  * path, then we know that nlink == 0, and that the
1128                  * xaction that made nlink == 0 is permanently committed
1129                  * since xfs_remove runs as a synchronous transaction.
1130                  */
1131                 error = xfs_itruncate_finish(&tp, ip, 0, XFS_DATA_FORK,
1132                                 (!(mp->m_flags & XFS_MOUNT_WSYNC) ? 1 : 0));
1133
1134                 if (error) {
1135                         xfs_trans_cancel(tp,
1136                                 XFS_TRANS_RELEASE_LOG_RES | XFS_TRANS_ABORT);
1137                         xfs_iunlock(ip, XFS_IOLOCK_EXCL | XFS_ILOCK_EXCL);
1138                         return VN_INACTIVE_CACHE;
1139                 }
1140         } else if ((ip->i_d.di_mode & S_IFMT) == S_IFLNK) {
1141
1142                 /*
1143                  * If we get an error while cleaning up a
1144                  * symlink we bail out.
1145                  */
1146                 error = (ip->i_d.di_size > XFS_IFORK_DSIZE(ip)) ?
1147                         xfs_inactive_symlink_rmt(ip, &tp) :
1148                         xfs_inactive_symlink_local(ip, &tp);
1149
1150                 if (error) {
1151                         ASSERT(tp == NULL);
1152                         return VN_INACTIVE_CACHE;
1153                 }
1154
1155                 xfs_trans_ijoin(tp, ip);
1156         } else {
1157                 error = xfs_trans_reserve(tp, 0,
1158                                           XFS_IFREE_LOG_RES(mp),
1159                                           0, XFS_TRANS_PERM_LOG_RES,
1160                                           XFS_INACTIVE_LOG_COUNT);
1161                 if (error) {
1162                         ASSERT(XFS_FORCED_SHUTDOWN(mp));
1163                         xfs_trans_cancel(tp, 0);
1164                         return VN_INACTIVE_CACHE;
1165                 }
1166
1167                 xfs_ilock(ip, XFS_ILOCK_EXCL | XFS_IOLOCK_EXCL);
1168                 xfs_trans_ijoin(tp, ip);
1169         }
1170
1171         /*
1172          * If there are attributes associated with the file
1173          * then blow them away now.  The code calls a routine
1174          * that recursively deconstructs the attribute fork.
1175          * We need to just commit the current transaction
1176          * because we can't use it for xfs_attr_inactive().
1177          */
1178         if (ip->i_d.di_anextents > 0) {
1179                 error = xfs_inactive_attrs(ip, &tp);
1180                 /*
1181                  * If we got an error, the transaction is already
1182                  * cancelled, and the inode is unlocked. Just get out.
1183                  */
1184                  if (error)
1185                          return VN_INACTIVE_CACHE;
1186         } else if (ip->i_afp) {
1187                 xfs_idestroy_fork(ip, XFS_ATTR_FORK);
1188         }
1189
1190         /*
1191          * Free the inode.
1192          */
1193         xfs_bmap_init(&free_list, &first_block);
1194         error = xfs_ifree(tp, ip, &free_list);
1195         if (error) {
1196                 /*
1197                  * If we fail to free the inode, shut down.  The cancel
1198                  * might do that, we need to make sure.  Otherwise the
1199                  * inode might be lost for a long time or forever.
1200                  */
1201                 if (!XFS_FORCED_SHUTDOWN(mp)) {
1202                         xfs_notice(mp, "%s: xfs_ifree returned error %d",
1203                                 __func__, error);
1204                         xfs_force_shutdown(mp, SHUTDOWN_META_IO_ERROR);
1205                 }
1206                 xfs_trans_cancel(tp, XFS_TRANS_RELEASE_LOG_RES|XFS_TRANS_ABORT);
1207         } else {
1208                 /*
1209                  * Credit the quota account(s). The inode is gone.
1210                  */
1211                 xfs_trans_mod_dquot_byino(tp, ip, XFS_TRANS_DQ_ICOUNT, -1);
1212
1213                 /*
1214                  * Just ignore errors at this point.  There is nothing we can
1215                  * do except to try to keep going. Make sure it's not a silent
1216                  * error.
1217                  */
1218                 error = xfs_bmap_finish(&tp,  &free_list, &committed);
1219                 if (error)
1220                         xfs_notice(mp, "%s: xfs_bmap_finish returned error %d",
1221                                 __func__, error);
1222                 error = xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
1223                 if (error)
1224                         xfs_notice(mp, "%s: xfs_trans_commit returned error %d",
1225                                 __func__, error);
1226         }
1227
1228         /*
1229          * Release the dquots held by inode, if any.
1230          */
1231         xfs_qm_dqdetach(ip);
1232         xfs_iunlock(ip, XFS_IOLOCK_EXCL | XFS_ILOCK_EXCL);
1233
1234  out:
1235         return VN_INACTIVE_CACHE;
1236 }
1237
1238 /*
1239  * Lookups up an inode from "name". If ci_name is not NULL, then a CI match
1240  * is allowed, otherwise it has to be an exact match. If a CI match is found,
1241  * ci_name->name will point to a the actual name (caller must free) or
1242  * will be set to NULL if an exact match is found.
1243  */
1244 int
1245 xfs_lookup(
1246         xfs_inode_t             *dp,
1247         struct xfs_name         *name,
1248         xfs_inode_t             **ipp,
1249         struct xfs_name         *ci_name)
1250 {
1251         xfs_ino_t               inum;
1252         int                     error;
1253         uint                    lock_mode;
1254
1255         trace_xfs_lookup(dp, name);
1256
1257         if (XFS_FORCED_SHUTDOWN(dp->i_mount))
1258                 return XFS_ERROR(EIO);
1259
1260         lock_mode = xfs_ilock_map_shared(dp);
1261         error = xfs_dir_lookup(NULL, dp, name, &inum, ci_name);
1262         xfs_iunlock_map_shared(dp, lock_mode);
1263
1264         if (error)
1265                 goto out;
1266
1267         error = xfs_iget(dp->i_mount, NULL, inum, 0, 0, ipp);
1268         if (error)
1269                 goto out_free_name;
1270
1271         return 0;
1272
1273 out_free_name:
1274         if (ci_name)
1275                 kmem_free(ci_name->name);
1276 out:
1277         *ipp = NULL;
1278         return error;
1279 }
1280
1281 int
1282 xfs_create(
1283         xfs_inode_t             *dp,
1284         struct xfs_name         *name,
1285         mode_t                  mode,
1286         xfs_dev_t               rdev,
1287         xfs_inode_t             **ipp)
1288 {
1289         int                     is_dir = S_ISDIR(mode);
1290         struct xfs_mount        *mp = dp->i_mount;
1291         struct xfs_inode        *ip = NULL;
1292         struct xfs_trans        *tp = NULL;
1293         int                     error;
1294         xfs_bmap_free_t         free_list;
1295         xfs_fsblock_t           first_block;
1296         boolean_t               unlock_dp_on_error = B_FALSE;
1297         uint                    cancel_flags;
1298         int                     committed;
1299         prid_t                  prid;
1300         struct xfs_dquot        *udqp = NULL;
1301         struct xfs_dquot        *gdqp = NULL;
1302         uint                    resblks;
1303         uint                    log_res;
1304         uint                    log_count;
1305
1306         trace_xfs_create(dp, name);
1307
1308         if (XFS_FORCED_SHUTDOWN(mp))
1309                 return XFS_ERROR(EIO);
1310
1311         if (dp->i_d.di_flags & XFS_DIFLAG_PROJINHERIT)
1312                 prid = xfs_get_projid(dp);
1313         else
1314                 prid = XFS_PROJID_DEFAULT;
1315
1316         /*
1317          * Make sure that we have allocated dquot(s) on disk.
1318          */
1319         error = xfs_qm_vop_dqalloc(dp, current_fsuid(), current_fsgid(), prid,
1320                         XFS_QMOPT_QUOTALL | XFS_QMOPT_INHERIT, &udqp, &gdqp);
1321         if (error)
1322                 return error;
1323
1324         if (is_dir) {
1325                 rdev = 0;
1326                 resblks = XFS_MKDIR_SPACE_RES(mp, name->len);
1327                 log_res = XFS_MKDIR_LOG_RES(mp);
1328                 log_count = XFS_MKDIR_LOG_COUNT;
1329                 tp = xfs_trans_alloc(mp, XFS_TRANS_MKDIR);
1330         } else {
1331                 resblks = XFS_CREATE_SPACE_RES(mp, name->len);
1332                 log_res = XFS_CREATE_LOG_RES(mp);
1333                 log_count = XFS_CREATE_LOG_COUNT;
1334                 tp = xfs_trans_alloc(mp, XFS_TRANS_CREATE);
1335         }
1336
1337         cancel_flags = XFS_TRANS_RELEASE_LOG_RES;
1338
1339         /*
1340          * Initially assume that the file does not exist and
1341          * reserve the resources for that case.  If that is not
1342          * the case we'll drop the one we have and get a more
1343          * appropriate transaction later.
1344          */
1345         error = xfs_trans_reserve(tp, resblks, log_res, 0,
1346                         XFS_TRANS_PERM_LOG_RES, log_count);
1347         if (error == ENOSPC) {
1348                 /* flush outstanding delalloc blocks and retry */
1349                 xfs_flush_inodes(dp);
1350                 error = xfs_trans_reserve(tp, resblks, log_res, 0,
1351                                 XFS_TRANS_PERM_LOG_RES, log_count);
1352         }
1353         if (error == ENOSPC) {
1354                 /* No space at all so try a "no-allocation" reservation */
1355                 resblks = 0;
1356                 error = xfs_trans_reserve(tp, 0, log_res, 0,
1357                                 XFS_TRANS_PERM_LOG_RES, log_count);
1358         }
1359         if (error) {
1360                 cancel_flags = 0;
1361                 goto out_trans_cancel;
1362         }
1363
1364         xfs_ilock(dp, XFS_ILOCK_EXCL | XFS_ILOCK_PARENT);
1365         unlock_dp_on_error = B_TRUE;
1366
1367         /*
1368          * Check for directory link count overflow.
1369          */
1370         if (is_dir && dp->i_d.di_nlink >= XFS_MAXLINK) {
1371                 error = XFS_ERROR(EMLINK);
1372                 goto out_trans_cancel;
1373         }
1374
1375         xfs_bmap_init(&free_list, &first_block);
1376
1377         /*
1378          * Reserve disk quota and the inode.
1379          */
1380         error = xfs_trans_reserve_quota(tp, mp, udqp, gdqp, resblks, 1, 0);
1381         if (error)
1382                 goto out_trans_cancel;
1383
1384         error = xfs_dir_canenter(tp, dp, name, resblks);
1385         if (error)
1386                 goto out_trans_cancel;
1387
1388         /*
1389          * A newly created regular or special file just has one directory
1390          * entry pointing to them, but a directory also the "." entry
1391          * pointing to itself.
1392          */
1393         error = xfs_dir_ialloc(&tp, dp, mode, is_dir ? 2 : 1, rdev,
1394                                prid, resblks > 0, &ip, &committed);
1395         if (error) {
1396                 if (error == ENOSPC)
1397                         goto out_trans_cancel;
1398                 goto out_trans_abort;
1399         }
1400
1401         /*
1402          * Now we join the directory inode to the transaction.  We do not do it
1403          * earlier because xfs_dir_ialloc might commit the previous transaction
1404          * (and release all the locks).  An error from here on will result in
1405          * the transaction cancel unlocking dp so don't do it explicitly in the
1406          * error path.
1407          */
1408         xfs_trans_ijoin_ref(tp, dp, XFS_ILOCK_EXCL);
1409         unlock_dp_on_error = B_FALSE;
1410
1411         error = xfs_dir_createname(tp, dp, name, ip->i_ino,
1412                                         &first_block, &free_list, resblks ?
1413                                         resblks - XFS_IALLOC_SPACE_RES(mp) : 0);
1414         if (error) {
1415                 ASSERT(error != ENOSPC);
1416                 goto out_trans_abort;
1417         }
1418         xfs_trans_ichgtime(tp, dp, XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG);
1419         xfs_trans_log_inode(tp, dp, XFS_ILOG_CORE);
1420
1421         if (is_dir) {
1422                 error = xfs_dir_init(tp, ip, dp);
1423                 if (error)
1424                         goto out_bmap_cancel;
1425
1426                 error = xfs_bumplink(tp, dp);
1427                 if (error)
1428                         goto out_bmap_cancel;
1429         }
1430
1431         /*
1432          * If this is a synchronous mount, make sure that the
1433          * create transaction goes to disk before returning to
1434          * the user.
1435          */
1436         if (mp->m_flags & (XFS_MOUNT_WSYNC|XFS_MOUNT_DIRSYNC))
1437                 xfs_trans_set_sync(tp);
1438
1439         /*
1440          * Attach the dquot(s) to the inodes and modify them incore.
1441          * These ids of the inode couldn't have changed since the new
1442          * inode has been locked ever since it was created.
1443          */
1444         xfs_qm_vop_create_dqattach(tp, ip, udqp, gdqp);
1445
1446         error = xfs_bmap_finish(&tp, &free_list, &committed);
1447         if (error)
1448                 goto out_bmap_cancel;
1449
1450         error = xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
1451         if (error)
1452                 goto out_release_inode;
1453
1454         xfs_qm_dqrele(udqp);
1455         xfs_qm_dqrele(gdqp);
1456
1457         *ipp = ip;
1458         return 0;
1459
1460  out_bmap_cancel:
1461         xfs_bmap_cancel(&free_list);
1462  out_trans_abort:
1463         cancel_flags |= XFS_TRANS_ABORT;
1464  out_trans_cancel:
1465         xfs_trans_cancel(tp, cancel_flags);
1466  out_release_inode:
1467         /*
1468          * Wait until after the current transaction is aborted to
1469          * release the inode.  This prevents recursive transactions
1470          * and deadlocks from xfs_inactive.
1471          */
1472         if (ip)
1473                 IRELE(ip);
1474
1475         xfs_qm_dqrele(udqp);
1476         xfs_qm_dqrele(gdqp);
1477
1478         if (unlock_dp_on_error)
1479                 xfs_iunlock(dp, XFS_ILOCK_EXCL);
1480         return error;
1481 }
1482
1483 #ifdef DEBUG
1484 int xfs_locked_n;
1485 int xfs_small_retries;
1486 int xfs_middle_retries;
1487 int xfs_lots_retries;
1488 int xfs_lock_delays;
1489 #endif
1490
1491 /*
1492  * Bump the subclass so xfs_lock_inodes() acquires each lock with
1493  * a different value
1494  */
1495 static inline int
1496 xfs_lock_inumorder(int lock_mode, int subclass)
1497 {
1498         if (lock_mode & (XFS_IOLOCK_SHARED|XFS_IOLOCK_EXCL))
1499                 lock_mode |= (subclass + XFS_LOCK_INUMORDER) << XFS_IOLOCK_SHIFT;
1500         if (lock_mode & (XFS_ILOCK_SHARED|XFS_ILOCK_EXCL))
1501                 lock_mode |= (subclass + XFS_LOCK_INUMORDER) << XFS_ILOCK_SHIFT;
1502
1503         return lock_mode;
1504 }
1505
1506 /*
1507  * The following routine will lock n inodes in exclusive mode.
1508  * We assume the caller calls us with the inodes in i_ino order.
1509  *
1510  * We need to detect deadlock where an inode that we lock
1511  * is in the AIL and we start waiting for another inode that is locked
1512  * by a thread in a long running transaction (such as truncate). This can
1513  * result in deadlock since the long running trans might need to wait
1514  * for the inode we just locked in order to push the tail and free space
1515  * in the log.
1516  */
1517 void
1518 xfs_lock_inodes(
1519         xfs_inode_t     **ips,
1520         int             inodes,
1521         uint            lock_mode)
1522 {
1523         int             attempts = 0, i, j, try_lock;
1524         xfs_log_item_t  *lp;
1525
1526         ASSERT(ips && (inodes >= 2)); /* we need at least two */
1527
1528         try_lock = 0;
1529         i = 0;
1530
1531 again:
1532         for (; i < inodes; i++) {
1533                 ASSERT(ips[i]);
1534
1535                 if (i && (ips[i] == ips[i-1]))  /* Already locked */
1536                         continue;
1537
1538                 /*
1539                  * If try_lock is not set yet, make sure all locked inodes
1540                  * are not in the AIL.
1541                  * If any are, set try_lock to be used later.
1542                  */
1543
1544                 if (!try_lock) {
1545                         for (j = (i - 1); j >= 0 && !try_lock; j--) {
1546                                 lp = (xfs_log_item_t *)ips[j]->i_itemp;
1547                                 if (lp && (lp->li_flags & XFS_LI_IN_AIL)) {
1548                                         try_lock++;
1549                                 }
1550                         }
1551                 }
1552
1553                 /*
1554                  * If any of the previous locks we have locked is in the AIL,
1555                  * we must TRY to get the second and subsequent locks. If
1556                  * we can't get any, we must release all we have
1557                  * and try again.
1558                  */
1559
1560                 if (try_lock) {
1561                         /* try_lock must be 0 if i is 0. */
1562                         /*
1563                          * try_lock means we have an inode locked
1564                          * that is in the AIL.
1565                          */
1566                         ASSERT(i != 0);
1567                         if (!xfs_ilock_nowait(ips[i], xfs_lock_inumorder(lock_mode, i))) {
1568                                 attempts++;
1569
1570                                 /*
1571                                  * Unlock all previous guys and try again.
1572                                  * xfs_iunlock will try to push the tail
1573                                  * if the inode is in the AIL.
1574                                  */
1575
1576                                 for(j = i - 1; j >= 0; j--) {
1577
1578                                         /*
1579                                          * Check to see if we've already
1580                                          * unlocked this one.
1581                                          * Not the first one going back,
1582                                          * and the inode ptr is the same.
1583                                          */
1584                                         if ((j != (i - 1)) && ips[j] ==
1585                                                                 ips[j+1])
1586                                                 continue;
1587
1588                                         xfs_iunlock(ips[j], lock_mode);
1589                                 }
1590
1591                                 if ((attempts % 5) == 0) {
1592                                         delay(1); /* Don't just spin the CPU */
1593 #ifdef DEBUG
1594                                         xfs_lock_delays++;
1595 #endif
1596                                 }
1597                                 i = 0;
1598                                 try_lock = 0;
1599                                 goto again;
1600                         }
1601                 } else {
1602                         xfs_ilock(ips[i], xfs_lock_inumorder(lock_mode, i));
1603                 }
1604         }
1605
1606 #ifdef DEBUG
1607         if (attempts) {
1608                 if (attempts < 5) xfs_small_retries++;
1609                 else if (attempts < 100) xfs_middle_retries++;
1610                 else xfs_lots_retries++;
1611         } else {
1612                 xfs_locked_n++;
1613         }
1614 #endif
1615 }
1616
1617 /*
1618  * xfs_lock_two_inodes() can only be used to lock one type of lock
1619  * at a time - the iolock or the ilock, but not both at once. If
1620  * we lock both at once, lockdep will report false positives saying
1621  * we have violated locking orders.
1622  */
1623 void
1624 xfs_lock_two_inodes(
1625         xfs_inode_t             *ip0,
1626         xfs_inode_t             *ip1,
1627         uint                    lock_mode)
1628 {
1629         xfs_inode_t             *temp;
1630         int                     attempts = 0;
1631         xfs_log_item_t          *lp;
1632
1633         if (lock_mode & (XFS_IOLOCK_SHARED|XFS_IOLOCK_EXCL))
1634                 ASSERT((lock_mode & (XFS_ILOCK_SHARED|XFS_ILOCK_EXCL)) == 0);
1635         ASSERT(ip0->i_ino != ip1->i_ino);
1636
1637         if (ip0->i_ino > ip1->i_ino) {
1638                 temp = ip0;
1639                 ip0 = ip1;
1640                 ip1 = temp;
1641         }
1642
1643  again:
1644         xfs_ilock(ip0, xfs_lock_inumorder(lock_mode, 0));
1645
1646         /*
1647          * If the first lock we have locked is in the AIL, we must TRY to get
1648          * the second lock. If we can't get it, we must release the first one
1649          * and try again.
1650          */
1651         lp = (xfs_log_item_t *)ip0->i_itemp;
1652         if (lp && (lp->li_flags & XFS_LI_IN_AIL)) {
1653                 if (!xfs_ilock_nowait(ip1, xfs_lock_inumorder(lock_mode, 1))) {
1654                         xfs_iunlock(ip0, lock_mode);
1655                         if ((++attempts % 5) == 0)
1656                                 delay(1); /* Don't just spin the CPU */
1657                         goto again;
1658                 }
1659         } else {
1660                 xfs_ilock(ip1, xfs_lock_inumorder(lock_mode, 1));
1661         }
1662 }
1663
1664 int
1665 xfs_remove(
1666         xfs_inode_t             *dp,
1667         struct xfs_name         *name,
1668         xfs_inode_t             *ip)
1669 {
1670         xfs_mount_t             *mp = dp->i_mount;
1671         xfs_trans_t             *tp = NULL;
1672         int                     is_dir = S_ISDIR(ip->i_d.di_mode);
1673         int                     error = 0;
1674         xfs_bmap_free_t         free_list;
1675         xfs_fsblock_t           first_block;
1676         int                     cancel_flags;
1677         int                     committed;
1678         int                     link_zero;
1679         uint                    resblks;
1680         uint                    log_count;
1681
1682         trace_xfs_remove(dp, name);
1683
1684         if (XFS_FORCED_SHUTDOWN(mp))
1685                 return XFS_ERROR(EIO);
1686
1687         error = xfs_qm_dqattach(dp, 0);
1688         if (error)
1689                 goto std_return;
1690
1691         error = xfs_qm_dqattach(ip, 0);
1692         if (error)
1693                 goto std_return;
1694
1695         if (is_dir) {
1696                 tp = xfs_trans_alloc(mp, XFS_TRANS_RMDIR);
1697                 log_count = XFS_DEFAULT_LOG_COUNT;
1698         } else {
1699                 tp = xfs_trans_alloc(mp, XFS_TRANS_REMOVE);
1700                 log_count = XFS_REMOVE_LOG_COUNT;
1701         }
1702         cancel_flags = XFS_TRANS_RELEASE_LOG_RES;
1703
1704         /*
1705          * We try to get the real space reservation first,
1706          * allowing for directory btree deletion(s) implying
1707          * possible bmap insert(s).  If we can't get the space
1708          * reservation then we use 0 instead, and avoid the bmap
1709          * btree insert(s) in the directory code by, if the bmap
1710          * insert tries to happen, instead trimming the LAST
1711          * block from the directory.
1712          */
1713         resblks = XFS_REMOVE_SPACE_RES(mp);
1714         error = xfs_trans_reserve(tp, resblks, XFS_REMOVE_LOG_RES(mp), 0,
1715                                   XFS_TRANS_PERM_LOG_RES, log_count);
1716         if (error == ENOSPC) {
1717                 resblks = 0;
1718                 error = xfs_trans_reserve(tp, 0, XFS_REMOVE_LOG_RES(mp), 0,
1719                                           XFS_TRANS_PERM_LOG_RES, log_count);
1720         }
1721         if (error) {
1722                 ASSERT(error != ENOSPC);
1723                 cancel_flags = 0;
1724                 goto out_trans_cancel;
1725         }
1726
1727         xfs_lock_two_inodes(dp, ip, XFS_ILOCK_EXCL);
1728
1729         xfs_trans_ijoin_ref(tp, dp, XFS_ILOCK_EXCL);
1730         xfs_trans_ijoin_ref(tp, ip, XFS_ILOCK_EXCL);
1731
1732         /*
1733          * If we're removing a directory perform some additional validation.
1734          */
1735         if (is_dir) {
1736                 ASSERT(ip->i_d.di_nlink >= 2);
1737                 if (ip->i_d.di_nlink != 2) {
1738                         error = XFS_ERROR(ENOTEMPTY);
1739                         goto out_trans_cancel;
1740                 }
1741                 if (!xfs_dir_isempty(ip)) {
1742                         error = XFS_ERROR(ENOTEMPTY);
1743                         goto out_trans_cancel;
1744                 }
1745         }
1746
1747         xfs_bmap_init(&free_list, &first_block);
1748         error = xfs_dir_removename(tp, dp, name, ip->i_ino,
1749                                         &first_block, &free_list, resblks);
1750         if (error) {
1751                 ASSERT(error != ENOENT);
1752                 goto out_bmap_cancel;
1753         }
1754         xfs_trans_ichgtime(tp, dp, XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG);
1755
1756         if (is_dir) {
1757                 /*
1758                  * Drop the link from ip's "..".
1759                  */
1760                 error = xfs_droplink(tp, dp);
1761                 if (error)
1762                         goto out_bmap_cancel;
1763
1764                 /*
1765                  * Drop the "." link from ip to self.
1766                  */
1767                 error = xfs_droplink(tp, ip);
1768                 if (error)
1769                         goto out_bmap_cancel;
1770         } else {
1771                 /*
1772                  * When removing a non-directory we need to log the parent
1773                  * inode here.  For a directory this is done implicitly
1774                  * by the xfs_droplink call for the ".." entry.
1775                  */
1776                 xfs_trans_log_inode(tp, dp, XFS_ILOG_CORE);
1777         }
1778
1779         /*
1780          * Drop the link from dp to ip.
1781          */
1782         error = xfs_droplink(tp, ip);
1783         if (error)
1784                 goto out_bmap_cancel;
1785
1786         /*
1787          * Determine if this is the last link while
1788          * we are in the transaction.
1789          */
1790         link_zero = (ip->i_d.di_nlink == 0);
1791
1792         /*
1793          * If this is a synchronous mount, make sure that the
1794          * remove transaction goes to disk before returning to
1795          * the user.
1796          */
1797         if (mp->m_flags & (XFS_MOUNT_WSYNC|XFS_MOUNT_DIRSYNC))
1798                 xfs_trans_set_sync(tp);
1799
1800         error = xfs_bmap_finish(&tp, &free_list, &committed);
1801         if (error)
1802                 goto out_bmap_cancel;
1803
1804         error = xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
1805         if (error)
1806                 goto std_return;
1807
1808         /*
1809          * If we are using filestreams, kill the stream association.
1810          * If the file is still open it may get a new one but that
1811          * will get killed on last close in xfs_close() so we don't
1812          * have to worry about that.
1813          */
1814         if (!is_dir && link_zero && xfs_inode_is_filestream(ip))
1815                 xfs_filestream_deassociate(ip);
1816
1817         return 0;
1818
1819  out_bmap_cancel:
1820         xfs_bmap_cancel(&free_list);
1821         cancel_flags |= XFS_TRANS_ABORT;
1822  out_trans_cancel:
1823         xfs_trans_cancel(tp, cancel_flags);
1824  std_return:
1825         return error;
1826 }
1827
1828 int
1829 xfs_link(
1830         xfs_inode_t             *tdp,
1831         xfs_inode_t             *sip,
1832         struct xfs_name         *target_name)
1833 {
1834         xfs_mount_t             *mp = tdp->i_mount;
1835         xfs_trans_t             *tp;
1836         int                     error;
1837         xfs_bmap_free_t         free_list;
1838         xfs_fsblock_t           first_block;
1839         int                     cancel_flags;
1840         int                     committed;
1841         int                     resblks;
1842
1843         trace_xfs_link(tdp, target_name);
1844
1845         ASSERT(!S_ISDIR(sip->i_d.di_mode));
1846
1847         if (XFS_FORCED_SHUTDOWN(mp))
1848                 return XFS_ERROR(EIO);
1849
1850         error = xfs_qm_dqattach(sip, 0);
1851         if (error)
1852                 goto std_return;
1853
1854         error = xfs_qm_dqattach(tdp, 0);
1855         if (error)
1856                 goto std_return;
1857
1858         tp = xfs_trans_alloc(mp, XFS_TRANS_LINK);
1859         cancel_flags = XFS_TRANS_RELEASE_LOG_RES;
1860         resblks = XFS_LINK_SPACE_RES(mp, target_name->len);
1861         error = xfs_trans_reserve(tp, resblks, XFS_LINK_LOG_RES(mp), 0,
1862                         XFS_TRANS_PERM_LOG_RES, XFS_LINK_LOG_COUNT);
1863         if (error == ENOSPC) {
1864                 resblks = 0;
1865                 error = xfs_trans_reserve(tp, 0, XFS_LINK_LOG_RES(mp), 0,
1866                                 XFS_TRANS_PERM_LOG_RES, XFS_LINK_LOG_COUNT);
1867         }
1868         if (error) {
1869                 cancel_flags = 0;
1870                 goto error_return;
1871         }
1872
1873         xfs_lock_two_inodes(sip, tdp, XFS_ILOCK_EXCL);
1874
1875         xfs_trans_ijoin_ref(tp, sip, XFS_ILOCK_EXCL);
1876         xfs_trans_ijoin_ref(tp, tdp, XFS_ILOCK_EXCL);
1877
1878         /*
1879          * If the source has too many links, we can't make any more to it.
1880          */
1881         if (sip->i_d.di_nlink >= XFS_MAXLINK) {
1882                 error = XFS_ERROR(EMLINK);
1883                 goto error_return;
1884         }
1885
1886         /*
1887          * If we are using project inheritance, we only allow hard link
1888          * creation in our tree when the project IDs are the same; else
1889          * the tree quota mechanism could be circumvented.
1890          */
1891         if (unlikely((tdp->i_d.di_flags & XFS_DIFLAG_PROJINHERIT) &&
1892                      (xfs_get_projid(tdp) != xfs_get_projid(sip)))) {
1893                 error = XFS_ERROR(EXDEV);
1894                 goto error_return;
1895         }
1896
1897         error = xfs_dir_canenter(tp, tdp, target_name, resblks);
1898         if (error)
1899                 goto error_return;
1900
1901         xfs_bmap_init(&free_list, &first_block);
1902
1903         error = xfs_dir_createname(tp, tdp, target_name, sip->i_ino,
1904                                         &first_block, &free_list, resblks);
1905         if (error)
1906                 goto abort_return;
1907         xfs_trans_ichgtime(tp, tdp, XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG);
1908         xfs_trans_log_inode(tp, tdp, XFS_ILOG_CORE);
1909
1910         error = xfs_bumplink(tp, sip);
1911         if (error)
1912                 goto abort_return;
1913
1914         /*
1915          * If this is a synchronous mount, make sure that the
1916          * link transaction goes to disk before returning to
1917          * the user.
1918          */
1919         if (mp->m_flags & (XFS_MOUNT_WSYNC|XFS_MOUNT_DIRSYNC)) {
1920                 xfs_trans_set_sync(tp);
1921         }
1922
1923         error = xfs_bmap_finish (&tp, &free_list, &committed);
1924         if (error) {
1925                 xfs_bmap_cancel(&free_list);
1926                 goto abort_return;
1927         }
1928
1929         return xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
1930
1931  abort_return:
1932         cancel_flags |= XFS_TRANS_ABORT;
1933  error_return:
1934         xfs_trans_cancel(tp, cancel_flags);
1935  std_return:
1936         return error;
1937 }
1938
1939 int
1940 xfs_symlink(
1941         xfs_inode_t             *dp,
1942         struct xfs_name         *link_name,
1943         const char              *target_path,
1944         mode_t                  mode,
1945         xfs_inode_t             **ipp)
1946 {
1947         xfs_mount_t             *mp = dp->i_mount;
1948         xfs_trans_t             *tp;
1949         xfs_inode_t             *ip;
1950         int                     error;
1951         int                     pathlen;
1952         xfs_bmap_free_t         free_list;
1953         xfs_fsblock_t           first_block;
1954         boolean_t               unlock_dp_on_error = B_FALSE;
1955         uint                    cancel_flags;
1956         int                     committed;
1957         xfs_fileoff_t           first_fsb;
1958         xfs_filblks_t           fs_blocks;
1959         int                     nmaps;
1960         xfs_bmbt_irec_t         mval[SYMLINK_MAPS];
1961         xfs_daddr_t             d;
1962         const char              *cur_chunk;
1963         int                     byte_cnt;
1964         int                     n;
1965         xfs_buf_t               *bp;
1966         prid_t                  prid;
1967         struct xfs_dquot        *udqp, *gdqp;
1968         uint                    resblks;
1969
1970         *ipp = NULL;
1971         error = 0;
1972         ip = NULL;
1973         tp = NULL;
1974
1975         trace_xfs_symlink(dp, link_name);
1976
1977         if (XFS_FORCED_SHUTDOWN(mp))
1978                 return XFS_ERROR(EIO);
1979
1980         /*
1981          * Check component lengths of the target path name.
1982          */
1983         pathlen = strlen(target_path);
1984         if (pathlen >= MAXPATHLEN)      /* total string too long */
1985                 return XFS_ERROR(ENAMETOOLONG);
1986
1987         udqp = gdqp = NULL;
1988         if (dp->i_d.di_flags & XFS_DIFLAG_PROJINHERIT)
1989                 prid = xfs_get_projid(dp);
1990         else
1991                 prid = XFS_PROJID_DEFAULT;
1992
1993         /*
1994          * Make sure that we have allocated dquot(s) on disk.
1995          */
1996         error = xfs_qm_vop_dqalloc(dp, current_fsuid(), current_fsgid(), prid,
1997                         XFS_QMOPT_QUOTALL | XFS_QMOPT_INHERIT, &udqp, &gdqp);
1998         if (error)
1999                 goto std_return;
2000
2001         tp = xfs_trans_alloc(mp, XFS_TRANS_SYMLINK);
2002         cancel_flags = XFS_TRANS_RELEASE_LOG_RES;
2003         /*
2004          * The symlink will fit into the inode data fork?
2005          * There can't be any attributes so we get the whole variable part.
2006          */
2007         if (pathlen <= XFS_LITINO(mp))
2008                 fs_blocks = 0;
2009         else
2010                 fs_blocks = XFS_B_TO_FSB(mp, pathlen);
2011         resblks = XFS_SYMLINK_SPACE_RES(mp, link_name->len, fs_blocks);
2012         error = xfs_trans_reserve(tp, resblks, XFS_SYMLINK_LOG_RES(mp), 0,
2013                         XFS_TRANS_PERM_LOG_RES, XFS_SYMLINK_LOG_COUNT);
2014         if (error == ENOSPC && fs_blocks == 0) {
2015                 resblks = 0;
2016                 error = xfs_trans_reserve(tp, 0, XFS_SYMLINK_LOG_RES(mp), 0,
2017                                 XFS_TRANS_PERM_LOG_RES, XFS_SYMLINK_LOG_COUNT);
2018         }
2019         if (error) {
2020                 cancel_flags = 0;
2021                 goto error_return;
2022         }
2023
2024         xfs_ilock(dp, XFS_ILOCK_EXCL | XFS_ILOCK_PARENT);
2025         unlock_dp_on_error = B_TRUE;
2026
2027         /*
2028          * Check whether the directory allows new symlinks or not.
2029          */
2030         if (dp->i_d.di_flags & XFS_DIFLAG_NOSYMLINKS) {
2031                 error = XFS_ERROR(EPERM);
2032                 goto error_return;
2033         }
2034
2035         /*
2036          * Reserve disk quota : blocks and inode.
2037          */
2038         error = xfs_trans_reserve_quota(tp, mp, udqp, gdqp, resblks, 1, 0);
2039         if (error)
2040                 goto error_return;
2041
2042         /*
2043          * Check for ability to enter directory entry, if no space reserved.
2044          */
2045         error = xfs_dir_canenter(tp, dp, link_name, resblks);
2046         if (error)
2047                 goto error_return;
2048         /*
2049          * Initialize the bmap freelist prior to calling either
2050          * bmapi or the directory create code.
2051          */
2052         xfs_bmap_init(&free_list, &first_block);
2053
2054         /*
2055          * Allocate an inode for the symlink.
2056          */
2057         error = xfs_dir_ialloc(&tp, dp, S_IFLNK | (mode & ~S_IFMT), 1, 0,
2058                                prid, resblks > 0, &ip, NULL);
2059         if (error) {
2060                 if (error == ENOSPC)
2061                         goto error_return;
2062                 goto error1;
2063         }
2064
2065         /*
2066          * An error after we've joined dp to the transaction will result in the
2067          * transaction cancel unlocking dp so don't do it explicitly in the
2068          * error path.
2069          */
2070         xfs_trans_ijoin_ref(tp, dp, XFS_ILOCK_EXCL);
2071         unlock_dp_on_error = B_FALSE;
2072
2073         /*
2074          * Also attach the dquot(s) to it, if applicable.
2075          */
2076         xfs_qm_vop_create_dqattach(tp, ip, udqp, gdqp);
2077
2078         if (resblks)
2079                 resblks -= XFS_IALLOC_SPACE_RES(mp);
2080         /*
2081          * If the symlink will fit into the inode, write it inline.
2082          */
2083         if (pathlen <= XFS_IFORK_DSIZE(ip)) {
2084                 xfs_idata_realloc(ip, pathlen, XFS_DATA_FORK);
2085                 memcpy(ip->i_df.if_u1.if_data, target_path, pathlen);
2086                 ip->i_d.di_size = pathlen;
2087
2088                 /*
2089                  * The inode was initially created in extent format.
2090                  */
2091                 ip->i_df.if_flags &= ~(XFS_IFEXTENTS | XFS_IFBROOT);
2092                 ip->i_df.if_flags |= XFS_IFINLINE;
2093
2094                 ip->i_d.di_format = XFS_DINODE_FMT_LOCAL;
2095                 xfs_trans_log_inode(tp, ip, XFS_ILOG_DDATA | XFS_ILOG_CORE);
2096
2097         } else {
2098                 first_fsb = 0;
2099                 nmaps = SYMLINK_MAPS;
2100
2101                 error = xfs_bmapi(tp, ip, first_fsb, fs_blocks,
2102                                   XFS_BMAPI_WRITE | XFS_BMAPI_METADATA,
2103                                   &first_block, resblks, mval, &nmaps,
2104                                   &free_list);
2105                 if (error)
2106                         goto error2;
2107
2108                 if (resblks)
2109                         resblks -= fs_blocks;
2110                 ip->i_d.di_size = pathlen;
2111                 xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
2112
2113                 cur_chunk = target_path;
2114                 for (n = 0; n < nmaps; n++) {
2115                         d = XFS_FSB_TO_DADDR(mp, mval[n].br_startblock);
2116                         byte_cnt = XFS_FSB_TO_B(mp, mval[n].br_blockcount);
2117                         bp = xfs_trans_get_buf(tp, mp->m_ddev_targp, d,
2118                                                BTOBB(byte_cnt), 0);
2119                         ASSERT(bp && !XFS_BUF_GETERROR(bp));
2120                         if (pathlen < byte_cnt) {
2121                                 byte_cnt = pathlen;
2122                         }
2123                         pathlen -= byte_cnt;
2124
2125                         memcpy(XFS_BUF_PTR(bp), cur_chunk, byte_cnt);
2126                         cur_chunk += byte_cnt;
2127
2128                         xfs_trans_log_buf(tp, bp, 0, byte_cnt - 1);
2129                 }
2130         }
2131
2132         /*
2133          * Create the directory entry for the symlink.
2134          */
2135         error = xfs_dir_createname(tp, dp, link_name, ip->i_ino,
2136                                         &first_block, &free_list, resblks);
2137         if (error)
2138                 goto error2;
2139         xfs_trans_ichgtime(tp, dp, XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG);
2140         xfs_trans_log_inode(tp, dp, XFS_ILOG_CORE);
2141
2142         /*
2143          * If this is a synchronous mount, make sure that the
2144          * symlink transaction goes to disk before returning to
2145          * the user.
2146          */
2147         if (mp->m_flags & (XFS_MOUNT_WSYNC|XFS_MOUNT_DIRSYNC)) {
2148                 xfs_trans_set_sync(tp);
2149         }
2150
2151         error = xfs_bmap_finish(&tp, &free_list, &committed);
2152         if (error) {
2153                 goto error2;
2154         }
2155         error = xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
2156         xfs_qm_dqrele(udqp);
2157         xfs_qm_dqrele(gdqp);
2158
2159         *ipp = ip;
2160         return 0;
2161
2162  error2:
2163         IRELE(ip);
2164  error1:
2165         xfs_bmap_cancel(&free_list);
2166         cancel_flags |= XFS_TRANS_ABORT;
2167  error_return:
2168         xfs_trans_cancel(tp, cancel_flags);
2169         xfs_qm_dqrele(udqp);
2170         xfs_qm_dqrele(gdqp);
2171
2172         if (unlock_dp_on_error)
2173                 xfs_iunlock(dp, XFS_ILOCK_EXCL);
2174  std_return:
2175         return error;
2176 }
2177
2178 int
2179 xfs_set_dmattrs(
2180         xfs_inode_t     *ip,
2181         u_int           evmask,
2182         u_int16_t       state)
2183 {
2184         xfs_mount_t     *mp = ip->i_mount;
2185         xfs_trans_t     *tp;
2186         int             error;
2187
2188         if (!capable(CAP_SYS_ADMIN))
2189                 return XFS_ERROR(EPERM);
2190
2191         if (XFS_FORCED_SHUTDOWN(mp))
2192                 return XFS_ERROR(EIO);
2193
2194         tp = xfs_trans_alloc(mp, XFS_TRANS_SET_DMATTRS);
2195         error = xfs_trans_reserve(tp, 0, XFS_ICHANGE_LOG_RES (mp), 0, 0, 0);
2196         if (error) {
2197                 xfs_trans_cancel(tp, 0);
2198                 return error;
2199         }
2200         xfs_ilock(ip, XFS_ILOCK_EXCL);
2201         xfs_trans_ijoin_ref(tp, ip, XFS_ILOCK_EXCL);
2202
2203         ip->i_d.di_dmevmask = evmask;
2204         ip->i_d.di_dmstate  = state;
2205
2206         xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
2207         error = xfs_trans_commit(tp, 0);
2208
2209         return error;
2210 }
2211
2212 /*
2213  * xfs_alloc_file_space()
2214  *      This routine allocates disk space for the given file.
2215  *
2216  *      If alloc_type == 0, this request is for an ALLOCSP type
2217  *      request which will change the file size.  In this case, no
2218  *      DMAPI event will be generated by the call.  A TRUNCATE event
2219  *      will be generated later by xfs_setattr.
2220  *
2221  *      If alloc_type != 0, this request is for a RESVSP type
2222  *      request, and a DMAPI DM_EVENT_WRITE will be generated if the
2223  *      lower block boundary byte address is less than the file's
2224  *      length.
2225  *
2226  * RETURNS:
2227  *       0 on success
2228  *      errno on error
2229  *
2230  */
2231 STATIC int
2232 xfs_alloc_file_space(
2233         xfs_inode_t             *ip,
2234         xfs_off_t               offset,
2235         xfs_off_t               len,
2236         int                     alloc_type,
2237         int                     attr_flags)
2238 {
2239         xfs_mount_t             *mp = ip->i_mount;
2240         xfs_off_t               count;
2241         xfs_filblks_t           allocated_fsb;
2242         xfs_filblks_t           allocatesize_fsb;
2243         xfs_extlen_t            extsz, temp;
2244         xfs_fileoff_t           startoffset_fsb;
2245         xfs_fsblock_t           firstfsb;
2246         int                     nimaps;
2247         int                     bmapi_flag;
2248         int                     quota_flag;
2249         int                     rt;
2250         xfs_trans_t             *tp;
2251         xfs_bmbt_irec_t         imaps[1], *imapp;
2252         xfs_bmap_free_t         free_list;
2253         uint                    qblocks, resblks, resrtextents;
2254         int                     committed;
2255         int                     error;
2256
2257         trace_xfs_alloc_file_space(ip);
2258
2259         if (XFS_FORCED_SHUTDOWN(mp))
2260                 return XFS_ERROR(EIO);
2261
2262         error = xfs_qm_dqattach(ip, 0);
2263         if (error)
2264                 return error;
2265
2266         if (len <= 0)
2267                 return XFS_ERROR(EINVAL);
2268
2269         rt = XFS_IS_REALTIME_INODE(ip);
2270         extsz = xfs_get_extsz_hint(ip);
2271
2272         count = len;
2273         imapp = &imaps[0];
2274         nimaps = 1;
2275         bmapi_flag = XFS_BMAPI_WRITE | alloc_type;
2276         startoffset_fsb = XFS_B_TO_FSBT(mp, offset);
2277         allocatesize_fsb = XFS_B_TO_FSB(mp, count);
2278
2279         /*
2280          * Allocate file space until done or until there is an error
2281          */
2282         while (allocatesize_fsb && !error) {
2283                 xfs_fileoff_t   s, e;
2284
2285                 /*
2286                  * Determine space reservations for data/realtime.
2287                  */
2288                 if (unlikely(extsz)) {
2289                         s = startoffset_fsb;
2290                         do_div(s, extsz);
2291                         s *= extsz;
2292                         e = startoffset_fsb + allocatesize_fsb;
2293                         if ((temp = do_mod(startoffset_fsb, extsz)))
2294                                 e += temp;
2295                         if ((temp = do_mod(e, extsz)))
2296                                 e += extsz - temp;
2297                 } else {
2298                         s = 0;
2299                         e = allocatesize_fsb;
2300                 }
2301
2302                 /*
2303                  * The transaction reservation is limited to a 32-bit block
2304                  * count, hence we need to limit the number of blocks we are
2305                  * trying to reserve to avoid an overflow. We can't allocate
2306                  * more than @nimaps extents, and an extent is limited on disk
2307                  * to MAXEXTLEN (21 bits), so use that to enforce the limit.
2308                  */
2309                 resblks = min_t(xfs_fileoff_t, (e - s), (MAXEXTLEN * nimaps));
2310                 if (unlikely(rt)) {
2311                         resrtextents = qblocks = resblks;
2312                         resrtextents /= mp->m_sb.sb_rextsize;
2313                         resblks = XFS_DIOSTRAT_SPACE_RES(mp, 0);
2314                         quota_flag = XFS_QMOPT_RES_RTBLKS;
2315                 } else {
2316                         resrtextents = 0;
2317                         resblks = qblocks = XFS_DIOSTRAT_SPACE_RES(mp, resblks);
2318                         quota_flag = XFS_QMOPT_RES_REGBLKS;
2319                 }
2320
2321                 /*
2322                  * Allocate and setup the transaction.
2323                  */
2324                 tp = xfs_trans_alloc(mp, XFS_TRANS_DIOSTRAT);
2325                 error = xfs_trans_reserve(tp, resblks,
2326                                           XFS_WRITE_LOG_RES(mp), resrtextents,
2327                                           XFS_TRANS_PERM_LOG_RES,
2328                                           XFS_WRITE_LOG_COUNT);
2329                 /*
2330                  * Check for running out of space
2331                  */
2332                 if (error) {
2333                         /*
2334                          * Free the transaction structure.
2335                          */
2336                         ASSERT(error == ENOSPC || XFS_FORCED_SHUTDOWN(mp));
2337                         xfs_trans_cancel(tp, 0);
2338                         break;
2339                 }
2340                 xfs_ilock(ip, XFS_ILOCK_EXCL);
2341                 error = xfs_trans_reserve_quota_nblks(tp, ip, qblocks,
2342                                                       0, quota_flag);
2343                 if (error)
2344                         goto error1;
2345
2346                 xfs_trans_ijoin(tp, ip);
2347
2348                 /*
2349                  * Issue the xfs_bmapi() call to allocate the blocks
2350                  */
2351                 xfs_bmap_init(&free_list, &firstfsb);
2352                 error = xfs_bmapi(tp, ip, startoffset_fsb,
2353                                   allocatesize_fsb, bmapi_flag,
2354                                   &firstfsb, 0, imapp, &nimaps,
2355                                   &free_list);
2356                 if (error) {
2357                         goto error0;
2358                 }
2359
2360                 /*
2361                  * Complete the transaction
2362                  */
2363                 error = xfs_bmap_finish(&tp, &free_list, &committed);
2364                 if (error) {
2365                         goto error0;
2366                 }
2367
2368                 error = xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
2369                 xfs_iunlock(ip, XFS_ILOCK_EXCL);
2370                 if (error) {
2371                         break;
2372                 }
2373
2374                 allocated_fsb = imapp->br_blockcount;
2375
2376                 if (nimaps == 0) {
2377                         error = XFS_ERROR(ENOSPC);
2378                         break;
2379                 }
2380
2381                 startoffset_fsb += allocated_fsb;
2382                 allocatesize_fsb -= allocated_fsb;
2383         }
2384
2385         return error;
2386
2387 error0: /* Cancel bmap, unlock inode, unreserve quota blocks, cancel trans */
2388         xfs_bmap_cancel(&free_list);
2389         xfs_trans_unreserve_quota_nblks(tp, ip, qblocks, 0, quota_flag);
2390
2391 error1: /* Just cancel transaction */
2392         xfs_trans_cancel(tp, XFS_TRANS_RELEASE_LOG_RES | XFS_TRANS_ABORT);
2393         xfs_iunlock(ip, XFS_ILOCK_EXCL);
2394         return error;
2395 }
2396
2397 /*
2398  * Zero file bytes between startoff and endoff inclusive.
2399  * The iolock is held exclusive and no blocks are buffered.
2400  *
2401  * This function is used by xfs_free_file_space() to zero
2402  * partial blocks when the range to free is not block aligned.
2403  * When unreserving space with boundaries that are not block
2404  * aligned we round up the start and round down the end
2405  * boundaries and then use this function to zero the parts of
2406  * the blocks that got dropped during the rounding.
2407  */
2408 STATIC int
2409 xfs_zero_remaining_bytes(
2410         xfs_inode_t             *ip,
2411         xfs_off_t               startoff,
2412         xfs_off_t               endoff)
2413 {
2414         xfs_bmbt_irec_t         imap;
2415         xfs_fileoff_t           offset_fsb;
2416         xfs_off_t               lastoffset;
2417         xfs_off_t               offset;
2418         xfs_buf_t               *bp;
2419         xfs_mount_t             *mp = ip->i_mount;
2420         int                     nimap;
2421         int                     error = 0;
2422
2423         /*
2424          * Avoid doing I/O beyond eof - it's not necessary
2425          * since nothing can read beyond eof.  The space will
2426          * be zeroed when the file is extended anyway.
2427          */
2428         if (startoff >= ip->i_size)
2429                 return 0;
2430
2431         if (endoff > ip->i_size)
2432                 endoff = ip->i_size;
2433
2434         bp = xfs_buf_get_uncached(XFS_IS_REALTIME_INODE(ip) ?
2435                                         mp->m_rtdev_targp : mp->m_ddev_targp,
2436                                 mp->m_sb.sb_blocksize, XBF_DONT_BLOCK);
2437         if (!bp)
2438                 return XFS_ERROR(ENOMEM);
2439
2440         for (offset = startoff; offset <= endoff; offset = lastoffset + 1) {
2441                 offset_fsb = XFS_B_TO_FSBT(mp, offset);
2442                 nimap = 1;
2443                 error = xfs_bmapi(NULL, ip, offset_fsb, 1, 0,
2444                         NULL, 0, &imap, &nimap, NULL);
2445                 if (error || nimap < 1)
2446                         break;
2447                 ASSERT(imap.br_blockcount >= 1);
2448                 ASSERT(imap.br_startoff == offset_fsb);
2449                 lastoffset = XFS_FSB_TO_B(mp, imap.br_startoff + 1) - 1;
2450                 if (lastoffset > endoff)
2451                         lastoffset = endoff;
2452                 if (imap.br_startblock == HOLESTARTBLOCK)
2453                         continue;
2454                 ASSERT(imap.br_startblock != DELAYSTARTBLOCK);
2455                 if (imap.br_state == XFS_EXT_UNWRITTEN)
2456                         continue;
2457                 XFS_BUF_UNDONE(bp);
2458                 XFS_BUF_UNWRITE(bp);
2459                 XFS_BUF_READ(bp);
2460                 XFS_BUF_SET_ADDR(bp, xfs_fsb_to_db(ip, imap.br_startblock));
2461                 xfsbdstrat(mp, bp);
2462                 error = xfs_buf_iowait(bp);
2463                 if (error) {
2464                         xfs_ioerror_alert("xfs_zero_remaining_bytes(read)",
2465                                           mp, bp, XFS_BUF_ADDR(bp));
2466                         break;
2467                 }
2468                 memset(XFS_BUF_PTR(bp) +
2469                         (offset - XFS_FSB_TO_B(mp, imap.br_startoff)),
2470                       0, lastoffset - offset + 1);
2471                 XFS_BUF_UNDONE(bp);
2472                 XFS_BUF_UNREAD(bp);
2473                 XFS_BUF_WRITE(bp);
2474                 xfsbdstrat(mp, bp);
2475                 error = xfs_buf_iowait(bp);
2476                 if (error) {
2477                         xfs_ioerror_alert("xfs_zero_remaining_bytes(write)",
2478                                           mp, bp, XFS_BUF_ADDR(bp));
2479                         break;
2480                 }
2481         }
2482         xfs_buf_free(bp);
2483         return error;
2484 }
2485
2486 /*
2487  * xfs_free_file_space()
2488  *      This routine frees disk space for the given file.
2489  *
2490  *      This routine is only called by xfs_change_file_space
2491  *      for an UNRESVSP type call.
2492  *
2493  * RETURNS:
2494  *       0 on success
2495  *      errno on error
2496  *
2497  */
2498 STATIC int
2499 xfs_free_file_space(
2500         xfs_inode_t             *ip,
2501         xfs_off_t               offset,
2502         xfs_off_t               len,
2503         int                     attr_flags)
2504 {
2505         int                     committed;
2506         int                     done;
2507         xfs_fileoff_t           endoffset_fsb;
2508         int                     error;
2509         xfs_fsblock_t           firstfsb;
2510         xfs_bmap_free_t         free_list;
2511         xfs_bmbt_irec_t         imap;
2512         xfs_off_t               ioffset;
2513         xfs_extlen_t            mod=0;
2514         xfs_mount_t             *mp;
2515         int                     nimap;
2516         uint                    resblks;
2517         uint                    rounding;
2518         int                     rt;
2519         xfs_fileoff_t           startoffset_fsb;
2520         xfs_trans_t             *tp;
2521         int                     need_iolock = 1;
2522
2523         mp = ip->i_mount;
2524
2525         trace_xfs_free_file_space(ip);
2526
2527         error = xfs_qm_dqattach(ip, 0);
2528         if (error)
2529                 return error;
2530
2531         error = 0;
2532         if (len <= 0)   /* if nothing being freed */
2533                 return error;
2534         rt = XFS_IS_REALTIME_INODE(ip);
2535         startoffset_fsb = XFS_B_TO_FSB(mp, offset);
2536         endoffset_fsb = XFS_B_TO_FSBT(mp, offset + len);
2537
2538         if (attr_flags & XFS_ATTR_NOLOCK)
2539                 need_iolock = 0;
2540         if (need_iolock) {
2541                 xfs_ilock(ip, XFS_IOLOCK_EXCL);
2542                 /* wait for the completion of any pending DIOs */
2543                 xfs_ioend_wait(ip);
2544         }
2545
2546         rounding = max_t(uint, 1 << mp->m_sb.sb_blocklog, PAGE_CACHE_SIZE);
2547         ioffset = offset & ~(rounding - 1);
2548
2549         if (VN_CACHED(VFS_I(ip)) != 0) {
2550                 error = xfs_flushinval_pages(ip, ioffset, -1, FI_REMAPF_LOCKED);
2551                 if (error)
2552                         goto out_unlock_iolock;
2553         }
2554
2555         /*
2556          * Need to zero the stuff we're not freeing, on disk.
2557          * If it's a realtime file & can't use unwritten extents then we
2558          * actually need to zero the extent edges.  Otherwise xfs_bunmapi
2559          * will take care of it for us.
2560          */
2561         if (rt && !xfs_sb_version_hasextflgbit(&mp->m_sb)) {
2562                 nimap = 1;
2563                 error = xfs_bmapi(NULL, ip, startoffset_fsb,
2564                         1, 0, NULL, 0, &imap, &nimap, NULL);
2565                 if (error)
2566                         goto out_unlock_iolock;
2567                 ASSERT(nimap == 0 || nimap == 1);
2568                 if (nimap && imap.br_startblock != HOLESTARTBLOCK) {
2569                         xfs_daddr_t     block;
2570
2571                         ASSERT(imap.br_startblock != DELAYSTARTBLOCK);
2572                         block = imap.br_startblock;
2573                         mod = do_div(block, mp->m_sb.sb_rextsize);
2574                         if (mod)
2575                                 startoffset_fsb += mp->m_sb.sb_rextsize - mod;
2576                 }
2577                 nimap = 1;
2578                 error = xfs_bmapi(NULL, ip, endoffset_fsb - 1,
2579                         1, 0, NULL, 0, &imap, &nimap, NULL);
2580                 if (error)
2581                         goto out_unlock_iolock;
2582                 ASSERT(nimap == 0 || nimap == 1);
2583                 if (nimap && imap.br_startblock != HOLESTARTBLOCK) {
2584                         ASSERT(imap.br_startblock != DELAYSTARTBLOCK);
2585                         mod++;
2586                         if (mod && (mod != mp->m_sb.sb_rextsize))
2587                                 endoffset_fsb -= mod;
2588                 }
2589         }
2590         if ((done = (endoffset_fsb <= startoffset_fsb)))
2591                 /*
2592                  * One contiguous piece to clear
2593                  */
2594                 error = xfs_zero_remaining_bytes(ip, offset, offset + len - 1);
2595         else {
2596                 /*
2597                  * Some full blocks, possibly two pieces to clear
2598                  */
2599                 if (offset < XFS_FSB_TO_B(mp, startoffset_fsb))
2600                         error = xfs_zero_remaining_bytes(ip, offset,
2601                                 XFS_FSB_TO_B(mp, startoffset_fsb) - 1);
2602                 if (!error &&
2603                     XFS_FSB_TO_B(mp, endoffset_fsb) < offset + len)
2604                         error = xfs_zero_remaining_bytes(ip,
2605                                 XFS_FSB_TO_B(mp, endoffset_fsb),
2606                                 offset + len - 1);
2607         }
2608
2609         /*
2610          * free file space until done or until there is an error
2611          */
2612         resblks = XFS_DIOSTRAT_SPACE_RES(mp, 0);
2613         while (!error && !done) {
2614
2615                 /*
2616                  * allocate and setup the transaction. Allow this
2617                  * transaction to dip into the reserve blocks to ensure
2618                  * the freeing of the space succeeds at ENOSPC.
2619                  */
2620                 tp = xfs_trans_alloc(mp, XFS_TRANS_DIOSTRAT);
2621                 tp->t_flags |= XFS_TRANS_RESERVE;
2622                 error = xfs_trans_reserve(tp,
2623                                           resblks,
2624                                           XFS_WRITE_LOG_RES(mp),
2625                                           0,
2626                                           XFS_TRANS_PERM_LOG_RES,
2627                                           XFS_WRITE_LOG_COUNT);
2628
2629                 /*
2630                  * check for running out of space
2631                  */
2632                 if (error) {
2633                         /*
2634                          * Free the transaction structure.
2635                          */
2636                         ASSERT(error == ENOSPC || XFS_FORCED_SHUTDOWN(mp));
2637                         xfs_trans_cancel(tp, 0);
2638                         break;
2639                 }
2640                 xfs_ilock(ip, XFS_ILOCK_EXCL);
2641                 error = xfs_trans_reserve_quota(tp, mp,
2642                                 ip->i_udquot, ip->i_gdquot,
2643                                 resblks, 0, XFS_QMOPT_RES_REGBLKS);
2644                 if (error)
2645                         goto error1;
2646
2647                 xfs_trans_ijoin(tp, ip);
2648
2649                 /*
2650                  * issue the bunmapi() call to free the blocks
2651                  */
2652                 xfs_bmap_init(&free_list, &firstfsb);
2653                 error = xfs_bunmapi(tp, ip, startoffset_fsb,
2654                                   endoffset_fsb - startoffset_fsb,
2655                                   0, 2, &firstfsb, &free_list, &done);
2656                 if (error) {
2657                         goto error0;
2658                 }
2659
2660                 /*
2661                  * complete the transaction
2662                  */
2663                 error = xfs_bmap_finish(&tp, &free_list, &committed);
2664                 if (error) {
2665                         goto error0;
2666                 }
2667
2668                 error = xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
2669                 xfs_iunlock(ip, XFS_ILOCK_EXCL);
2670         }
2671
2672  out_unlock_iolock:
2673         if (need_iolock)
2674                 xfs_iunlock(ip, XFS_IOLOCK_EXCL);
2675         return error;
2676
2677  error0:
2678         xfs_bmap_cancel(&free_list);
2679  error1:
2680         xfs_trans_cancel(tp, XFS_TRANS_RELEASE_LOG_RES | XFS_TRANS_ABORT);
2681         xfs_iunlock(ip, need_iolock ? (XFS_ILOCK_EXCL | XFS_IOLOCK_EXCL) :
2682                     XFS_ILOCK_EXCL);
2683         return error;
2684 }
2685
2686 /*
2687  * xfs_change_file_space()
2688  *      This routine allocates or frees disk space for the given file.
2689  *      The user specified parameters are checked for alignment and size
2690  *      limitations.
2691  *
2692  * RETURNS:
2693  *       0 on success
2694  *      errno on error
2695  *
2696  */
2697 int
2698 xfs_change_file_space(
2699         xfs_inode_t     *ip,
2700         int             cmd,
2701         xfs_flock64_t   *bf,
2702         xfs_off_t       offset,
2703         int             attr_flags)
2704 {
2705         xfs_mount_t     *mp = ip->i_mount;
2706         int             clrprealloc;
2707         int             error;
2708         xfs_fsize_t     fsize;
2709         int             setprealloc;
2710         xfs_off_t       startoffset;
2711         xfs_off_t       llen;
2712         xfs_trans_t     *tp;
2713         struct iattr    iattr;
2714         int             prealloc_type;
2715
2716         if (!S_ISREG(ip->i_d.di_mode))
2717                 return XFS_ERROR(EINVAL);
2718
2719         switch (bf->l_whence) {
2720         case 0: /*SEEK_SET*/
2721                 break;
2722         case 1: /*SEEK_CUR*/
2723                 bf->l_start += offset;
2724                 break;
2725         case 2: /*SEEK_END*/
2726                 bf->l_start += ip->i_size;
2727                 break;
2728         default:
2729                 return XFS_ERROR(EINVAL);
2730         }
2731
2732         llen = bf->l_len > 0 ? bf->l_len - 1 : bf->l_len;
2733
2734         if (   (bf->l_start < 0)
2735             || (bf->l_start > XFS_MAXIOFFSET(mp))
2736             || (bf->l_start + llen < 0)
2737             || (bf->l_start + llen > XFS_MAXIOFFSET(mp)))
2738                 return XFS_ERROR(EINVAL);
2739
2740         bf->l_whence = 0;
2741
2742         startoffset = bf->l_start;
2743         fsize = ip->i_size;
2744
2745         /*
2746          * XFS_IOC_RESVSP and XFS_IOC_UNRESVSP will reserve or unreserve
2747          * file space.
2748          * These calls do NOT zero the data space allocated to the file,
2749          * nor do they change the file size.
2750          *
2751          * XFS_IOC_ALLOCSP and XFS_IOC_FREESP will allocate and free file
2752          * space.
2753          * These calls cause the new file data to be zeroed and the file
2754          * size to be changed.
2755          */
2756         setprealloc = clrprealloc = 0;
2757         prealloc_type = XFS_BMAPI_PREALLOC;
2758
2759         switch (cmd) {
2760         case XFS_IOC_ZERO_RANGE:
2761                 prealloc_type |= XFS_BMAPI_CONVERT;
2762                 xfs_tosspages(ip, startoffset, startoffset + bf->l_len, 0);
2763                 /* FALLTHRU */
2764         case XFS_IOC_RESVSP:
2765         case XFS_IOC_RESVSP64:
2766                 error = xfs_alloc_file_space(ip, startoffset, bf->l_len,
2767                                                 prealloc_type, attr_flags);
2768                 if (error)
2769                         return error;
2770                 setprealloc = 1;
2771                 break;
2772
2773         case XFS_IOC_UNRESVSP:
2774         case XFS_IOC_UNRESVSP64:
2775                 if ((error = xfs_free_file_space(ip, startoffset, bf->l_len,
2776                                                                 attr_flags)))
2777                         return error;
2778                 break;
2779
2780         case XFS_IOC_ALLOCSP:
2781         case XFS_IOC_ALLOCSP64:
2782         case XFS_IOC_FREESP:
2783         case XFS_IOC_FREESP64:
2784                 if (startoffset > fsize) {
2785                         error = xfs_alloc_file_space(ip, fsize,
2786                                         startoffset - fsize, 0, attr_flags);
2787                         if (error)
2788                                 break;
2789                 }
2790
2791                 iattr.ia_valid = ATTR_SIZE;
2792                 iattr.ia_size = startoffset;
2793
2794                 error = xfs_setattr(ip, &iattr, attr_flags);
2795
2796                 if (error)
2797                         return error;
2798
2799                 clrprealloc = 1;
2800                 break;
2801
2802         default:
2803                 ASSERT(0);
2804                 return XFS_ERROR(EINVAL);
2805         }
2806
2807         /*
2808          * update the inode timestamp, mode, and prealloc flag bits
2809          */
2810         tp = xfs_trans_alloc(mp, XFS_TRANS_WRITEID);
2811
2812         if ((error = xfs_trans_reserve(tp, 0, XFS_WRITEID_LOG_RES(mp),
2813                                       0, 0, 0))) {
2814                 /* ASSERT(0); */
2815                 xfs_trans_cancel(tp, 0);
2816                 return error;
2817         }
2818
2819         xfs_ilock(ip, XFS_ILOCK_EXCL);
2820
2821         xfs_trans_ijoin(tp, ip);
2822
2823         if ((attr_flags & XFS_ATTR_DMI) == 0) {
2824                 ip->i_d.di_mode &= ~S_ISUID;
2825
2826                 /*
2827                  * Note that we don't have to worry about mandatory
2828                  * file locking being disabled here because we only
2829                  * clear the S_ISGID bit if the Group execute bit is
2830                  * on, but if it was on then mandatory locking wouldn't
2831                  * have been enabled.
2832                  */
2833                 if (ip->i_d.di_mode & S_IXGRP)
2834                         ip->i_d.di_mode &= ~S_ISGID;
2835
2836                 xfs_trans_ichgtime(tp, ip, XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG);
2837         }
2838         if (setprealloc)
2839                 ip->i_d.di_flags |= XFS_DIFLAG_PREALLOC;
2840         else if (clrprealloc)
2841                 ip->i_d.di_flags &= ~XFS_DIFLAG_PREALLOC;
2842
2843         xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
2844         if (attr_flags & XFS_ATTR_SYNC)
2845                 xfs_trans_set_sync(tp);
2846
2847         error = xfs_trans_commit(tp, 0);
2848
2849         xfs_iunlock(ip, XFS_ILOCK_EXCL);
2850
2851         return error;
2852 }