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