[XFS] clean up vnode/inode tracing
[linux-2.6] / 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_dmapi.h"
30 #include "xfs_mount.h"
31 #include "xfs_da_btree.h"
32 #include "xfs_bmap_btree.h"
33 #include "xfs_alloc_btree.h"
34 #include "xfs_ialloc_btree.h"
35 #include "xfs_dir2_sf.h"
36 #include "xfs_attr_sf.h"
37 #include "xfs_dinode.h"
38 #include "xfs_inode.h"
39 #include "xfs_inode_item.h"
40 #include "xfs_itable.h"
41 #include "xfs_btree.h"
42 #include "xfs_ialloc.h"
43 #include "xfs_alloc.h"
44 #include "xfs_bmap.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_refcache.h"
52 #include "xfs_trans_space.h"
53 #include "xfs_log_priv.h"
54 #include "xfs_filestream.h"
55 #include "xfs_vnodeops.h"
56
57 int
58 xfs_open(
59         xfs_inode_t     *ip)
60 {
61         int             mode;
62
63         if (XFS_FORCED_SHUTDOWN(ip->i_mount))
64                 return XFS_ERROR(EIO);
65
66         /*
67          * If it's a directory with any blocks, read-ahead block 0
68          * as we're almost certain to have the next operation be a read there.
69          */
70         if (S_ISDIR(ip->i_d.di_mode) && ip->i_d.di_nextents > 0) {
71                 mode = xfs_ilock_map_shared(ip);
72                 if (ip->i_d.di_nextents > 0)
73                         (void)xfs_da_reada_buf(NULL, ip, 0, XFS_DATA_FORK);
74                 xfs_iunlock(ip, mode);
75         }
76         return 0;
77 }
78
79 /*
80  * xfs_getattr
81  */
82 int
83 xfs_getattr(
84         xfs_inode_t     *ip,
85         bhv_vattr_t     *vap,
86         int             flags)
87 {
88         bhv_vnode_t     *vp = XFS_ITOV(ip);
89         xfs_mount_t     *mp = ip->i_mount;
90
91         xfs_itrace_entry(ip);
92
93         if (XFS_FORCED_SHUTDOWN(mp))
94                 return XFS_ERROR(EIO);
95
96         if (!(flags & ATTR_LAZY))
97                 xfs_ilock(ip, XFS_ILOCK_SHARED);
98
99         vap->va_size = XFS_ISIZE(ip);
100         if (vap->va_mask == XFS_AT_SIZE)
101                 goto all_done;
102
103         vap->va_nblocks =
104                 XFS_FSB_TO_BB(mp, ip->i_d.di_nblocks + ip->i_delayed_blks);
105         vap->va_nodeid = ip->i_ino;
106 #if XFS_BIG_INUMS
107         vap->va_nodeid += mp->m_inoadd;
108 #endif
109         vap->va_nlink = ip->i_d.di_nlink;
110
111         /*
112          * Quick exit for non-stat callers
113          */
114         if ((vap->va_mask &
115             ~(XFS_AT_SIZE|XFS_AT_FSID|XFS_AT_NODEID|
116               XFS_AT_NLINK|XFS_AT_BLKSIZE)) == 0)
117                 goto all_done;
118
119         /*
120          * Copy from in-core inode.
121          */
122         vap->va_mode = ip->i_d.di_mode;
123         vap->va_uid = ip->i_d.di_uid;
124         vap->va_gid = ip->i_d.di_gid;
125         vap->va_projid = ip->i_d.di_projid;
126
127         /*
128          * Check vnode type block/char vs. everything else.
129          */
130         switch (ip->i_d.di_mode & S_IFMT) {
131         case S_IFBLK:
132         case S_IFCHR:
133                 vap->va_rdev = ip->i_df.if_u2.if_rdev;
134                 vap->va_blocksize = BLKDEV_IOSIZE;
135                 break;
136         default:
137                 vap->va_rdev = 0;
138
139                 if (!(ip->i_d.di_flags & XFS_DIFLAG_REALTIME)) {
140                         vap->va_blocksize = xfs_preferred_iosize(mp);
141                 } else {
142
143                         /*
144                          * If the file blocks are being allocated from a
145                          * realtime partition, then return the inode's
146                          * realtime extent size or the realtime volume's
147                          * extent size.
148                          */
149                         vap->va_blocksize =
150                                 xfs_get_extsz_hint(ip) << mp->m_sb.sb_blocklog;
151                 }
152                 break;
153         }
154
155         vn_atime_to_timespec(vp, &vap->va_atime);
156         vap->va_mtime.tv_sec = ip->i_d.di_mtime.t_sec;
157         vap->va_mtime.tv_nsec = ip->i_d.di_mtime.t_nsec;
158         vap->va_ctime.tv_sec = ip->i_d.di_ctime.t_sec;
159         vap->va_ctime.tv_nsec = ip->i_d.di_ctime.t_nsec;
160
161         /*
162          * Exit for stat callers.  See if any of the rest of the fields
163          * to be filled in are needed.
164          */
165         if ((vap->va_mask &
166              (XFS_AT_XFLAGS|XFS_AT_EXTSIZE|XFS_AT_NEXTENTS|XFS_AT_ANEXTENTS|
167               XFS_AT_GENCOUNT|XFS_AT_VCODE)) == 0)
168                 goto all_done;
169
170         /*
171          * Convert di_flags to xflags.
172          */
173         vap->va_xflags = xfs_ip2xflags(ip);
174
175         /*
176          * Exit for inode revalidate.  See if any of the rest of
177          * the fields to be filled in are needed.
178          */
179         if ((vap->va_mask &
180              (XFS_AT_EXTSIZE|XFS_AT_NEXTENTS|XFS_AT_ANEXTENTS|
181               XFS_AT_GENCOUNT|XFS_AT_VCODE)) == 0)
182                 goto all_done;
183
184         vap->va_extsize = ip->i_d.di_extsize << mp->m_sb.sb_blocklog;
185         vap->va_nextents =
186                 (ip->i_df.if_flags & XFS_IFEXTENTS) ?
187                         ip->i_df.if_bytes / sizeof(xfs_bmbt_rec_t) :
188                         ip->i_d.di_nextents;
189         if (ip->i_afp)
190                 vap->va_anextents =
191                         (ip->i_afp->if_flags & XFS_IFEXTENTS) ?
192                                 ip->i_afp->if_bytes / sizeof(xfs_bmbt_rec_t) :
193                                  ip->i_d.di_anextents;
194         else
195                 vap->va_anextents = 0;
196         vap->va_gen = ip->i_d.di_gen;
197
198  all_done:
199         if (!(flags & ATTR_LAZY))
200                 xfs_iunlock(ip, XFS_ILOCK_SHARED);
201         return 0;
202 }
203
204
205 /*
206  * xfs_setattr
207  */
208 int
209 xfs_setattr(
210         xfs_inode_t             *ip,
211         bhv_vattr_t             *vap,
212         int                     flags,
213         cred_t                  *credp)
214 {
215         bhv_vnode_t             *vp = XFS_ITOV(ip);
216         xfs_mount_t             *mp = ip->i_mount;
217         xfs_trans_t             *tp;
218         int                     mask;
219         int                     code;
220         uint                    lock_flags;
221         uint                    commit_flags=0;
222         uid_t                   uid=0, iuid=0;
223         gid_t                   gid=0, igid=0;
224         int                     timeflags = 0;
225         xfs_prid_t              projid=0, iprojid=0;
226         int                     mandlock_before, mandlock_after;
227         struct xfs_dquot        *udqp, *gdqp, *olddquot1, *olddquot2;
228         int                     file_owner;
229         int                     need_iolock = 1;
230
231         xfs_itrace_entry(ip);
232
233         if (mp->m_flags & XFS_MOUNT_RDONLY)
234                 return XFS_ERROR(EROFS);
235
236         /*
237          * Cannot set certain attributes.
238          */
239         mask = vap->va_mask;
240         if (mask & XFS_AT_NOSET) {
241                 return XFS_ERROR(EINVAL);
242         }
243
244         if (XFS_FORCED_SHUTDOWN(mp))
245                 return XFS_ERROR(EIO);
246
247         /*
248          * Timestamps do not need to be logged and hence do not
249          * need to be done within a transaction.
250          */
251         if (mask & XFS_AT_UPDTIMES) {
252                 ASSERT((mask & ~XFS_AT_UPDTIMES) == 0);
253                 timeflags = ((mask & XFS_AT_UPDATIME) ? XFS_ICHGTIME_ACC : 0) |
254                             ((mask & XFS_AT_UPDCTIME) ? XFS_ICHGTIME_CHG : 0) |
255                             ((mask & XFS_AT_UPDMTIME) ? XFS_ICHGTIME_MOD : 0);
256                 xfs_ichgtime(ip, timeflags);
257                 return 0;
258         }
259
260         olddquot1 = olddquot2 = NULL;
261         udqp = gdqp = NULL;
262
263         /*
264          * If disk quotas is on, we make sure that the dquots do exist on disk,
265          * before we start any other transactions. Trying to do this later
266          * is messy. We don't care to take a readlock to look at the ids
267          * in inode here, because we can't hold it across the trans_reserve.
268          * If the IDs do change before we take the ilock, we're covered
269          * because the i_*dquot fields will get updated anyway.
270          */
271         if (XFS_IS_QUOTA_ON(mp) &&
272             (mask & (XFS_AT_UID|XFS_AT_GID|XFS_AT_PROJID))) {
273                 uint    qflags = 0;
274
275                 if ((mask & XFS_AT_UID) && XFS_IS_UQUOTA_ON(mp)) {
276                         uid = vap->va_uid;
277                         qflags |= XFS_QMOPT_UQUOTA;
278                 } else {
279                         uid = ip->i_d.di_uid;
280                 }
281                 if ((mask & XFS_AT_GID) && XFS_IS_GQUOTA_ON(mp)) {
282                         gid = vap->va_gid;
283                         qflags |= XFS_QMOPT_GQUOTA;
284                 }  else {
285                         gid = ip->i_d.di_gid;
286                 }
287                 if ((mask & XFS_AT_PROJID) && XFS_IS_PQUOTA_ON(mp)) {
288                         projid = vap->va_projid;
289                         qflags |= XFS_QMOPT_PQUOTA;
290                 }  else {
291                         projid = ip->i_d.di_projid;
292                 }
293                 /*
294                  * We take a reference when we initialize udqp and gdqp,
295                  * so it is important that we never blindly double trip on
296                  * the same variable. See xfs_create() for an example.
297                  */
298                 ASSERT(udqp == NULL);
299                 ASSERT(gdqp == NULL);
300                 code = XFS_QM_DQVOPALLOC(mp, ip, uid, gid, projid, qflags,
301                                          &udqp, &gdqp);
302                 if (code)
303                         return code;
304         }
305
306         /*
307          * For the other attributes, we acquire the inode lock and
308          * first do an error checking pass.
309          */
310         tp = NULL;
311         lock_flags = XFS_ILOCK_EXCL;
312         if (flags & ATTR_NOLOCK)
313                 need_iolock = 0;
314         if (!(mask & XFS_AT_SIZE)) {
315                 if ((mask != (XFS_AT_CTIME|XFS_AT_ATIME|XFS_AT_MTIME)) ||
316                     (mp->m_flags & XFS_MOUNT_WSYNC)) {
317                         tp = xfs_trans_alloc(mp, XFS_TRANS_SETATTR_NOT_SIZE);
318                         commit_flags = 0;
319                         if ((code = xfs_trans_reserve(tp, 0,
320                                                      XFS_ICHANGE_LOG_RES(mp), 0,
321                                                      0, 0))) {
322                                 lock_flags = 0;
323                                 goto error_return;
324                         }
325                 }
326         } else {
327                 if (DM_EVENT_ENABLED(ip, DM_EVENT_TRUNCATE) &&
328                     !(flags & ATTR_DMI)) {
329                         int dmflags = AT_DELAY_FLAG(flags) | DM_SEM_FLAG_WR;
330                         code = XFS_SEND_DATA(mp, DM_EVENT_TRUNCATE, vp,
331                                 vap->va_size, 0, dmflags, NULL);
332                         if (code) {
333                                 lock_flags = 0;
334                                 goto error_return;
335                         }
336                 }
337                 if (need_iolock)
338                         lock_flags |= XFS_IOLOCK_EXCL;
339         }
340
341         xfs_ilock(ip, lock_flags);
342
343         /* boolean: are we the file owner? */
344         file_owner = (current_fsuid(credp) == ip->i_d.di_uid);
345
346         /*
347          * Change various properties of a file.
348          * Only the owner or users with CAP_FOWNER
349          * capability may do these things.
350          */
351         if (mask &
352             (XFS_AT_MODE|XFS_AT_XFLAGS|XFS_AT_EXTSIZE|XFS_AT_UID|
353              XFS_AT_GID|XFS_AT_PROJID)) {
354                 /*
355                  * CAP_FOWNER overrides the following restrictions:
356                  *
357                  * The user ID of the calling process must be equal
358                  * to the file owner ID, except in cases where the
359                  * CAP_FSETID capability is applicable.
360                  */
361                 if (!file_owner && !capable(CAP_FOWNER)) {
362                         code = XFS_ERROR(EPERM);
363                         goto error_return;
364                 }
365
366                 /*
367                  * CAP_FSETID overrides the following restrictions:
368                  *
369                  * The effective user ID of the calling process shall match
370                  * the file owner when setting the set-user-ID and
371                  * set-group-ID bits on that file.
372                  *
373                  * The effective group ID or one of the supplementary group
374                  * IDs of the calling process shall match the group owner of
375                  * the file when setting the set-group-ID bit on that file
376                  */
377                 if (mask & XFS_AT_MODE) {
378                         mode_t m = 0;
379
380                         if ((vap->va_mode & S_ISUID) && !file_owner)
381                                 m |= S_ISUID;
382                         if ((vap->va_mode & S_ISGID) &&
383                             !in_group_p((gid_t)ip->i_d.di_gid))
384                                 m |= S_ISGID;
385 #if 0
386                         /* Linux allows this, Irix doesn't. */
387                         if ((vap->va_mode & S_ISVTX) && !VN_ISDIR(vp))
388                                 m |= S_ISVTX;
389 #endif
390                         if (m && !capable(CAP_FSETID))
391                                 vap->va_mode &= ~m;
392                 }
393         }
394
395         /*
396          * Change file ownership.  Must be the owner or privileged.
397          * If the system was configured with the "restricted_chown"
398          * option, the owner is not permitted to give away the file,
399          * and can change the group id only to a group of which he
400          * or she is a member.
401          */
402         if (mask & (XFS_AT_UID|XFS_AT_GID|XFS_AT_PROJID)) {
403                 /*
404                  * These IDs could have changed since we last looked at them.
405                  * But, we're assured that if the ownership did change
406                  * while we didn't have the inode locked, inode's dquot(s)
407                  * would have changed also.
408                  */
409                 iuid = ip->i_d.di_uid;
410                 iprojid = ip->i_d.di_projid;
411                 igid = ip->i_d.di_gid;
412                 gid = (mask & XFS_AT_GID) ? vap->va_gid : igid;
413                 uid = (mask & XFS_AT_UID) ? vap->va_uid : iuid;
414                 projid = (mask & XFS_AT_PROJID) ? (xfs_prid_t)vap->va_projid :
415                          iprojid;
416
417                 /*
418                  * CAP_CHOWN overrides the following restrictions:
419                  *
420                  * If _POSIX_CHOWN_RESTRICTED is defined, this capability
421                  * shall override the restriction that a process cannot
422                  * change the user ID of a file it owns and the restriction
423                  * that the group ID supplied to the chown() function
424                  * shall be equal to either the group ID or one of the
425                  * supplementary group IDs of the calling process.
426                  */
427                 if (restricted_chown &&
428                     (iuid != uid || (igid != gid &&
429                                      !in_group_p((gid_t)gid))) &&
430                     !capable(CAP_CHOWN)) {
431                         code = XFS_ERROR(EPERM);
432                         goto error_return;
433                 }
434                 /*
435                  * Do a quota reservation only if uid/projid/gid is actually
436                  * going to change.
437                  */
438                 if ((XFS_IS_UQUOTA_ON(mp) && iuid != uid) ||
439                     (XFS_IS_PQUOTA_ON(mp) && iprojid != projid) ||
440                     (XFS_IS_GQUOTA_ON(mp) && igid != gid)) {
441                         ASSERT(tp);
442                         code = XFS_QM_DQVOPCHOWNRESV(mp, tp, ip, udqp, gdqp,
443                                                 capable(CAP_FOWNER) ?
444                                                 XFS_QMOPT_FORCE_RES : 0);
445                         if (code)       /* out of quota */
446                                 goto error_return;
447                 }
448         }
449
450         /*
451          * Truncate file.  Must have write permission and not be a directory.
452          */
453         if (mask & XFS_AT_SIZE) {
454                 /* Short circuit the truncate case for zero length files */
455                 if ((vap->va_size == 0) &&
456                    (ip->i_size == 0) && (ip->i_d.di_nextents == 0)) {
457                         xfs_iunlock(ip, XFS_ILOCK_EXCL);
458                         lock_flags &= ~XFS_ILOCK_EXCL;
459                         if (mask & XFS_AT_CTIME)
460                                 xfs_ichgtime(ip, XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG);
461                         code = 0;
462                         goto error_return;
463                 }
464
465                 if (VN_ISDIR(vp)) {
466                         code = XFS_ERROR(EISDIR);
467                         goto error_return;
468                 } else if (!VN_ISREG(vp)) {
469                         code = XFS_ERROR(EINVAL);
470                         goto error_return;
471                 }
472                 /*
473                  * Make sure that the dquots are attached to the inode.
474                  */
475                 if ((code = XFS_QM_DQATTACH(mp, ip, XFS_QMOPT_ILOCKED)))
476                         goto error_return;
477         }
478
479         /*
480          * Change file access or modified times.
481          */
482         if (mask & (XFS_AT_ATIME|XFS_AT_MTIME)) {
483                 if (!file_owner) {
484                         if ((flags & ATTR_UTIME) &&
485                             !capable(CAP_FOWNER)) {
486                                 code = XFS_ERROR(EPERM);
487                                 goto error_return;
488                         }
489                 }
490         }
491
492         /*
493          * Change extent size or realtime flag.
494          */
495         if (mask & (XFS_AT_EXTSIZE|XFS_AT_XFLAGS)) {
496                 /*
497                  * Can't change extent size if any extents are allocated.
498                  */
499                 if (ip->i_d.di_nextents && (mask & XFS_AT_EXTSIZE) &&
500                     ((ip->i_d.di_extsize << mp->m_sb.sb_blocklog) !=
501                      vap->va_extsize) ) {
502                         code = XFS_ERROR(EINVAL);       /* EFBIG? */
503                         goto error_return;
504                 }
505
506                 /*
507                  * Can't change realtime flag if any extents are allocated.
508                  */
509                 if ((ip->i_d.di_nextents || ip->i_delayed_blks) &&
510                     (mask & XFS_AT_XFLAGS) &&
511                     (ip->i_d.di_flags & XFS_DIFLAG_REALTIME) !=
512                     (vap->va_xflags & XFS_XFLAG_REALTIME)) {
513                         code = XFS_ERROR(EINVAL);       /* EFBIG? */
514                         goto error_return;
515                 }
516                 /*
517                  * Extent size must be a multiple of the appropriate block
518                  * size, if set at all.
519                  */
520                 if ((mask & XFS_AT_EXTSIZE) && vap->va_extsize != 0) {
521                         xfs_extlen_t    size;
522
523                         if ((ip->i_d.di_flags & XFS_DIFLAG_REALTIME) ||
524                             ((mask & XFS_AT_XFLAGS) &&
525                             (vap->va_xflags & XFS_XFLAG_REALTIME))) {
526                                 size = mp->m_sb.sb_rextsize <<
527                                        mp->m_sb.sb_blocklog;
528                         } else {
529                                 size = mp->m_sb.sb_blocksize;
530                         }
531                         if (vap->va_extsize % size) {
532                                 code = XFS_ERROR(EINVAL);
533                                 goto error_return;
534                         }
535                 }
536                 /*
537                  * If realtime flag is set then must have realtime data.
538                  */
539                 if ((mask & XFS_AT_XFLAGS) &&
540                     (vap->va_xflags & XFS_XFLAG_REALTIME)) {
541                         if ((mp->m_sb.sb_rblocks == 0) ||
542                             (mp->m_sb.sb_rextsize == 0) ||
543                             (ip->i_d.di_extsize % mp->m_sb.sb_rextsize)) {
544                                 code = XFS_ERROR(EINVAL);
545                                 goto error_return;
546                         }
547                 }
548
549                 /*
550                  * Can't modify an immutable/append-only file unless
551                  * we have appropriate permission.
552                  */
553                 if ((mask & XFS_AT_XFLAGS) &&
554                     (ip->i_d.di_flags &
555                                 (XFS_DIFLAG_IMMUTABLE|XFS_DIFLAG_APPEND) ||
556                      (vap->va_xflags &
557                                 (XFS_XFLAG_IMMUTABLE | XFS_XFLAG_APPEND))) &&
558                     !capable(CAP_LINUX_IMMUTABLE)) {
559                         code = XFS_ERROR(EPERM);
560                         goto error_return;
561                 }
562         }
563
564         /*
565          * Now we can make the changes.  Before we join the inode
566          * to the transaction, if XFS_AT_SIZE is set then take care of
567          * the part of the truncation that must be done without the
568          * inode lock.  This needs to be done before joining the inode
569          * to the transaction, because the inode cannot be unlocked
570          * once it is a part of the transaction.
571          */
572         if (mask & XFS_AT_SIZE) {
573                 code = 0;
574                 if ((vap->va_size > ip->i_size) &&
575                     (flags & ATTR_NOSIZETOK) == 0) {
576                         code = xfs_igrow_start(ip, vap->va_size, credp);
577                 }
578                 xfs_iunlock(ip, XFS_ILOCK_EXCL);
579
580                 /*
581                  * We are going to log the inode size change in this
582                  * transaction so any previous writes that are beyond the on
583                  * disk EOF and the new EOF that have not been written out need
584                  * to be written here. If we do not write the data out, we
585                  * expose ourselves to the null files problem.
586                  *
587                  * Only flush from the on disk size to the smaller of the in
588                  * memory file size or the new size as that's the range we
589                  * really care about here and prevents waiting for other data
590                  * not within the range we care about here.
591                  */
592                 if (!code &&
593                     (ip->i_size != ip->i_d.di_size) &&
594                     (vap->va_size > ip->i_d.di_size)) {
595                         code = xfs_flush_pages(ip,
596                                         ip->i_d.di_size, vap->va_size,
597                                         XFS_B_ASYNC, FI_NONE);
598                 }
599
600                 /* wait for all I/O to complete */
601                 vn_iowait(ip);
602
603                 if (!code)
604                         code = xfs_itruncate_data(ip, vap->va_size);
605                 if (code) {
606                         ASSERT(tp == NULL);
607                         lock_flags &= ~XFS_ILOCK_EXCL;
608                         ASSERT(lock_flags == XFS_IOLOCK_EXCL);
609                         goto error_return;
610                 }
611                 tp = xfs_trans_alloc(mp, XFS_TRANS_SETATTR_SIZE);
612                 if ((code = xfs_trans_reserve(tp, 0,
613                                              XFS_ITRUNCATE_LOG_RES(mp), 0,
614                                              XFS_TRANS_PERM_LOG_RES,
615                                              XFS_ITRUNCATE_LOG_COUNT))) {
616                         xfs_trans_cancel(tp, 0);
617                         if (need_iolock)
618                                 xfs_iunlock(ip, XFS_IOLOCK_EXCL);
619                         return code;
620                 }
621                 commit_flags = XFS_TRANS_RELEASE_LOG_RES;
622                 xfs_ilock(ip, XFS_ILOCK_EXCL);
623         }
624
625         if (tp) {
626                 xfs_trans_ijoin(tp, ip, lock_flags);
627                 xfs_trans_ihold(tp, ip);
628         }
629
630         /* determine whether mandatory locking mode changes */
631         mandlock_before = MANDLOCK(vp, ip->i_d.di_mode);
632
633         /*
634          * Truncate file.  Must have write permission and not be a directory.
635          */
636         if (mask & XFS_AT_SIZE) {
637                 if (vap->va_size > ip->i_size) {
638                         xfs_igrow_finish(tp, ip, vap->va_size,
639                             !(flags & ATTR_DMI));
640                 } else if ((vap->va_size <= ip->i_size) ||
641                            ((vap->va_size == 0) && ip->i_d.di_nextents)) {
642                         /*
643                          * signal a sync transaction unless
644                          * we're truncating an already unlinked
645                          * file on a wsync filesystem
646                          */
647                         code = xfs_itruncate_finish(&tp, ip,
648                                             (xfs_fsize_t)vap->va_size,
649                                             XFS_DATA_FORK,
650                                             ((ip->i_d.di_nlink != 0 ||
651                                               !(mp->m_flags & XFS_MOUNT_WSYNC))
652                                              ? 1 : 0));
653                         if (code)
654                                 goto abort_return;
655                         /*
656                          * Truncated "down", so we're removing references
657                          * to old data here - if we now delay flushing for
658                          * a long time, we expose ourselves unduly to the
659                          * notorious NULL files problem.  So, we mark this
660                          * vnode and flush it when the file is closed, and
661                          * do not wait the usual (long) time for writeout.
662                          */
663                         xfs_iflags_set(ip, XFS_ITRUNCATED);
664                 }
665                 /*
666                  * Have to do this even if the file's size doesn't change.
667                  */
668                 timeflags |= XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG;
669         }
670
671         /*
672          * Change file access modes.
673          */
674         if (mask & XFS_AT_MODE) {
675                 ip->i_d.di_mode &= S_IFMT;
676                 ip->i_d.di_mode |= vap->va_mode & ~S_IFMT;
677
678                 xfs_trans_log_inode (tp, ip, XFS_ILOG_CORE);
679                 timeflags |= XFS_ICHGTIME_CHG;
680         }
681
682         /*
683          * Change file ownership.  Must be the owner or privileged.
684          * If the system was configured with the "restricted_chown"
685          * option, the owner is not permitted to give away the file,
686          * and can change the group id only to a group of which he
687          * or she is a member.
688          */
689         if (mask & (XFS_AT_UID|XFS_AT_GID|XFS_AT_PROJID)) {
690                 /*
691                  * CAP_FSETID overrides the following restrictions:
692                  *
693                  * The set-user-ID and set-group-ID bits of a file will be
694                  * cleared upon successful return from chown()
695                  */
696                 if ((ip->i_d.di_mode & (S_ISUID|S_ISGID)) &&
697                     !capable(CAP_FSETID)) {
698                         ip->i_d.di_mode &= ~(S_ISUID|S_ISGID);
699                 }
700
701                 /*
702                  * Change the ownerships and register quota modifications
703                  * in the transaction.
704                  */
705                 if (iuid != uid) {
706                         if (XFS_IS_UQUOTA_ON(mp)) {
707                                 ASSERT(mask & XFS_AT_UID);
708                                 ASSERT(udqp);
709                                 olddquot1 = XFS_QM_DQVOPCHOWN(mp, tp, ip,
710                                                         &ip->i_udquot, udqp);
711                         }
712                         ip->i_d.di_uid = uid;
713                 }
714                 if (igid != gid) {
715                         if (XFS_IS_GQUOTA_ON(mp)) {
716                                 ASSERT(!XFS_IS_PQUOTA_ON(mp));
717                                 ASSERT(mask & XFS_AT_GID);
718                                 ASSERT(gdqp);
719                                 olddquot2 = XFS_QM_DQVOPCHOWN(mp, tp, ip,
720                                                         &ip->i_gdquot, gdqp);
721                         }
722                         ip->i_d.di_gid = gid;
723                 }
724                 if (iprojid != projid) {
725                         if (XFS_IS_PQUOTA_ON(mp)) {
726                                 ASSERT(!XFS_IS_GQUOTA_ON(mp));
727                                 ASSERT(mask & XFS_AT_PROJID);
728                                 ASSERT(gdqp);
729                                 olddquot2 = XFS_QM_DQVOPCHOWN(mp, tp, ip,
730                                                         &ip->i_gdquot, gdqp);
731                         }
732                         ip->i_d.di_projid = projid;
733                         /*
734                          * We may have to rev the inode as well as
735                          * the superblock version number since projids didn't
736                          * exist before DINODE_VERSION_2 and SB_VERSION_NLINK.
737                          */
738                         if (ip->i_d.di_version == XFS_DINODE_VERSION_1)
739                                 xfs_bump_ino_vers2(tp, ip);
740                 }
741
742                 xfs_trans_log_inode (tp, ip, XFS_ILOG_CORE);
743                 timeflags |= XFS_ICHGTIME_CHG;
744         }
745
746
747         /*
748          * Change file access or modified times.
749          */
750         if (mask & (XFS_AT_ATIME|XFS_AT_MTIME)) {
751                 if (mask & XFS_AT_ATIME) {
752                         ip->i_d.di_atime.t_sec = vap->va_atime.tv_sec;
753                         ip->i_d.di_atime.t_nsec = vap->va_atime.tv_nsec;
754                         ip->i_update_core = 1;
755                         timeflags &= ~XFS_ICHGTIME_ACC;
756                 }
757                 if (mask & XFS_AT_MTIME) {
758                         ip->i_d.di_mtime.t_sec = vap->va_mtime.tv_sec;
759                         ip->i_d.di_mtime.t_nsec = vap->va_mtime.tv_nsec;
760                         timeflags &= ~XFS_ICHGTIME_MOD;
761                         timeflags |= XFS_ICHGTIME_CHG;
762                 }
763                 if (tp && (flags & ATTR_UTIME))
764                         xfs_trans_log_inode (tp, ip, XFS_ILOG_CORE);
765         }
766
767         /*
768          * Change XFS-added attributes.
769          */
770         if (mask & (XFS_AT_EXTSIZE|XFS_AT_XFLAGS)) {
771                 if (mask & XFS_AT_EXTSIZE) {
772                         /*
773                          * Converting bytes to fs blocks.
774                          */
775                         ip->i_d.di_extsize = vap->va_extsize >>
776                                 mp->m_sb.sb_blocklog;
777                 }
778                 if (mask & XFS_AT_XFLAGS) {
779                         uint    di_flags;
780
781                         /* can't set PREALLOC this way, just preserve it */
782                         di_flags = (ip->i_d.di_flags & XFS_DIFLAG_PREALLOC);
783                         if (vap->va_xflags & XFS_XFLAG_IMMUTABLE)
784                                 di_flags |= XFS_DIFLAG_IMMUTABLE;
785                         if (vap->va_xflags & XFS_XFLAG_APPEND)
786                                 di_flags |= XFS_DIFLAG_APPEND;
787                         if (vap->va_xflags & XFS_XFLAG_SYNC)
788                                 di_flags |= XFS_DIFLAG_SYNC;
789                         if (vap->va_xflags & XFS_XFLAG_NOATIME)
790                                 di_flags |= XFS_DIFLAG_NOATIME;
791                         if (vap->va_xflags & XFS_XFLAG_NODUMP)
792                                 di_flags |= XFS_DIFLAG_NODUMP;
793                         if (vap->va_xflags & XFS_XFLAG_PROJINHERIT)
794                                 di_flags |= XFS_DIFLAG_PROJINHERIT;
795                         if (vap->va_xflags & XFS_XFLAG_NODEFRAG)
796                                 di_flags |= XFS_DIFLAG_NODEFRAG;
797                         if (vap->va_xflags & XFS_XFLAG_FILESTREAM)
798                                 di_flags |= XFS_DIFLAG_FILESTREAM;
799                         if ((ip->i_d.di_mode & S_IFMT) == S_IFDIR) {
800                                 if (vap->va_xflags & XFS_XFLAG_RTINHERIT)
801                                         di_flags |= XFS_DIFLAG_RTINHERIT;
802                                 if (vap->va_xflags & XFS_XFLAG_NOSYMLINKS)
803                                         di_flags |= XFS_DIFLAG_NOSYMLINKS;
804                                 if (vap->va_xflags & XFS_XFLAG_EXTSZINHERIT)
805                                         di_flags |= XFS_DIFLAG_EXTSZINHERIT;
806                         } else if ((ip->i_d.di_mode & S_IFMT) == S_IFREG) {
807                                 if (vap->va_xflags & XFS_XFLAG_REALTIME) {
808                                         di_flags |= XFS_DIFLAG_REALTIME;
809                                         ip->i_iocore.io_flags |= XFS_IOCORE_RT;
810                                 } else {
811                                         ip->i_iocore.io_flags &= ~XFS_IOCORE_RT;
812                                 }
813                                 if (vap->va_xflags & XFS_XFLAG_EXTSIZE)
814                                         di_flags |= XFS_DIFLAG_EXTSIZE;
815                         }
816                         ip->i_d.di_flags = di_flags;
817                 }
818                 xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
819                 timeflags |= XFS_ICHGTIME_CHG;
820         }
821
822         /*
823          * Change file inode change time only if XFS_AT_CTIME set
824          * AND we have been called by a DMI function.
825          */
826
827         if ( (flags & ATTR_DMI) && (mask & XFS_AT_CTIME) ) {
828                 ip->i_d.di_ctime.t_sec = vap->va_ctime.tv_sec;
829                 ip->i_d.di_ctime.t_nsec = vap->va_ctime.tv_nsec;
830                 ip->i_update_core = 1;
831                 timeflags &= ~XFS_ICHGTIME_CHG;
832         }
833
834         /*
835          * Send out timestamp changes that need to be set to the
836          * current time.  Not done when called by a DMI function.
837          */
838         if (timeflags && !(flags & ATTR_DMI))
839                 xfs_ichgtime(ip, timeflags);
840
841         XFS_STATS_INC(xs_ig_attrchg);
842
843         /*
844          * If this is a synchronous mount, make sure that the
845          * transaction goes to disk before returning to the user.
846          * This is slightly sub-optimal in that truncates require
847          * two sync transactions instead of one for wsync filesystems.
848          * One for the truncate and one for the timestamps since we
849          * don't want to change the timestamps unless we're sure the
850          * truncate worked.  Truncates are less than 1% of the laddis
851          * mix so this probably isn't worth the trouble to optimize.
852          */
853         code = 0;
854         if (tp) {
855                 if (mp->m_flags & XFS_MOUNT_WSYNC)
856                         xfs_trans_set_sync(tp);
857
858                 code = xfs_trans_commit(tp, commit_flags);
859         }
860
861         /*
862          * If the (regular) file's mandatory locking mode changed, then
863          * notify the vnode.  We do this under the inode lock to prevent
864          * racing calls to vop_vnode_change.
865          */
866         mandlock_after = MANDLOCK(vp, ip->i_d.di_mode);
867
868         xfs_iunlock(ip, lock_flags);
869
870         /*
871          * Release any dquot(s) the inode had kept before chown.
872          */
873         XFS_QM_DQRELE(mp, olddquot1);
874         XFS_QM_DQRELE(mp, olddquot2);
875         XFS_QM_DQRELE(mp, udqp);
876         XFS_QM_DQRELE(mp, gdqp);
877
878         if (code) {
879                 return code;
880         }
881
882         if (DM_EVENT_ENABLED(ip, DM_EVENT_ATTRIBUTE) &&
883             !(flags & ATTR_DMI)) {
884                 (void) XFS_SEND_NAMESP(mp, DM_EVENT_ATTRIBUTE, vp, DM_RIGHT_NULL,
885                                         NULL, DM_RIGHT_NULL, NULL, NULL,
886                                         0, 0, AT_DELAY_FLAG(flags));
887         }
888         return 0;
889
890  abort_return:
891         commit_flags |= XFS_TRANS_ABORT;
892         /* FALLTHROUGH */
893  error_return:
894         XFS_QM_DQRELE(mp, udqp);
895         XFS_QM_DQRELE(mp, gdqp);
896         if (tp) {
897                 xfs_trans_cancel(tp, commit_flags);
898         }
899         if (lock_flags != 0) {
900                 xfs_iunlock(ip, lock_flags);
901         }
902         return code;
903 }
904
905
906 /*
907  * xfs_access
908  * Null conversion from vnode mode bits to inode mode bits, as in efs.
909  */
910 int
911 xfs_access(
912         xfs_inode_t     *ip,
913         int             mode,
914         cred_t          *credp)
915 {
916         int             error;
917
918         xfs_itrace_entry(ip);
919         xfs_ilock(ip, XFS_ILOCK_SHARED);
920         error = xfs_iaccess(ip, mode, credp);
921         xfs_iunlock(ip, XFS_ILOCK_SHARED);
922         return error;
923 }
924
925
926 /*
927  * The maximum pathlen is 1024 bytes. Since the minimum file system
928  * blocksize is 512 bytes, we can get a max of 2 extents back from
929  * bmapi.
930  */
931 #define SYMLINK_MAPS 2
932
933 STATIC int
934 xfs_readlink_bmap(
935         xfs_inode_t     *ip,
936         char            *link)
937 {
938         xfs_mount_t     *mp = ip->i_mount;
939         int             pathlen = ip->i_d.di_size;
940         int             nmaps = SYMLINK_MAPS;
941         xfs_bmbt_irec_t mval[SYMLINK_MAPS];
942         xfs_daddr_t     d;
943         int             byte_cnt;
944         int             n;
945         xfs_buf_t       *bp;
946         int             error = 0;
947
948         error = xfs_bmapi(NULL, ip, 0, XFS_B_TO_FSB(mp, pathlen), 0, NULL, 0,
949                         mval, &nmaps, NULL, NULL);
950         if (error)
951                 goto out;
952
953         for (n = 0; n < nmaps; n++) {
954                 d = XFS_FSB_TO_DADDR(mp, mval[n].br_startblock);
955                 byte_cnt = XFS_FSB_TO_B(mp, mval[n].br_blockcount);
956
957                 bp = xfs_buf_read(mp->m_ddev_targp, d, BTOBB(byte_cnt), 0);
958                 error = XFS_BUF_GETERROR(bp);
959                 if (error) {
960                         xfs_ioerror_alert("xfs_readlink",
961                                   ip->i_mount, bp, XFS_BUF_ADDR(bp));
962                         xfs_buf_relse(bp);
963                         goto out;
964                 }
965                 if (pathlen < byte_cnt)
966                         byte_cnt = pathlen;
967                 pathlen -= byte_cnt;
968
969                 memcpy(link, XFS_BUF_PTR(bp), byte_cnt);
970                 xfs_buf_relse(bp);
971         }
972
973         link[ip->i_d.di_size] = '\0';
974         error = 0;
975
976  out:
977         return error;
978 }
979
980 int
981 xfs_readlink(
982         xfs_inode_t     *ip,
983         char            *link)
984 {
985         xfs_mount_t     *mp = ip->i_mount;
986         int             pathlen;
987         int             error = 0;
988
989         xfs_itrace_entry(ip);
990
991         if (XFS_FORCED_SHUTDOWN(mp))
992                 return XFS_ERROR(EIO);
993
994         xfs_ilock(ip, XFS_ILOCK_SHARED);
995
996         ASSERT((ip->i_d.di_mode & S_IFMT) == S_IFLNK);
997         ASSERT(ip->i_d.di_size <= MAXPATHLEN);
998
999         pathlen = ip->i_d.di_size;
1000         if (!pathlen)
1001                 goto out;
1002
1003         if (ip->i_df.if_flags & XFS_IFINLINE) {
1004                 memcpy(link, ip->i_df.if_u1.if_data, pathlen);
1005                 link[pathlen] = '\0';
1006         } else {
1007                 error = xfs_readlink_bmap(ip, link);
1008         }
1009
1010  out:
1011         xfs_iunlock(ip, XFS_ILOCK_SHARED);
1012         return error;
1013 }
1014
1015 /*
1016  * xfs_fsync
1017  *
1018  * This is called to sync the inode and its data out to disk.
1019  * We need to hold the I/O lock while flushing the data, and
1020  * the inode lock while flushing the inode.  The inode lock CANNOT
1021  * be held while flushing the data, so acquire after we're done
1022  * with that.
1023  */
1024 int
1025 xfs_fsync(
1026         xfs_inode_t     *ip,
1027         int             flag,
1028         xfs_off_t       start,
1029         xfs_off_t       stop)
1030 {
1031         xfs_trans_t     *tp;
1032         int             error;
1033         int             log_flushed = 0, changed = 1;
1034
1035         xfs_itrace_entry(ip);
1036
1037         ASSERT(start >= 0 && stop >= -1);
1038
1039         if (XFS_FORCED_SHUTDOWN(ip->i_mount))
1040                 return XFS_ERROR(EIO);
1041
1042         if (flag & FSYNC_DATA)
1043                 filemap_fdatawait(vn_to_inode(XFS_ITOV(ip))->i_mapping);
1044
1045         /*
1046          * We always need to make sure that the required inode state
1047          * is safe on disk.  The vnode might be clean but because
1048          * of committed transactions that haven't hit the disk yet.
1049          * Likewise, there could be unflushed non-transactional
1050          * changes to the inode core that have to go to disk.
1051          *
1052          * The following code depends on one assumption:  that
1053          * any transaction that changes an inode logs the core
1054          * because it has to change some field in the inode core
1055          * (typically nextents or nblocks).  That assumption
1056          * implies that any transactions against an inode will
1057          * catch any non-transactional updates.  If inode-altering
1058          * transactions exist that violate this assumption, the
1059          * code breaks.  Right now, it figures that if the involved
1060          * update_* field is clear and the inode is unpinned, the
1061          * inode is clean.  Either it's been flushed or it's been
1062          * committed and the commit has hit the disk unpinning the inode.
1063          * (Note that xfs_inode_item_format() called at commit clears
1064          * the update_* fields.)
1065          */
1066         xfs_ilock(ip, XFS_ILOCK_SHARED);
1067
1068         /* If we are flushing data then we care about update_size
1069          * being set, otherwise we care about update_core
1070          */
1071         if ((flag & FSYNC_DATA) ?
1072                         (ip->i_update_size == 0) :
1073                         (ip->i_update_core == 0)) {
1074                 /*
1075                  * Timestamps/size haven't changed since last inode
1076                  * flush or inode transaction commit.  That means
1077                  * either nothing got written or a transaction
1078                  * committed which caught the updates.  If the
1079                  * latter happened and the transaction hasn't
1080                  * hit the disk yet, the inode will be still
1081                  * be pinned.  If it is, force the log.
1082                  */
1083
1084                 xfs_iunlock(ip, XFS_ILOCK_SHARED);
1085
1086                 if (xfs_ipincount(ip)) {
1087                         _xfs_log_force(ip->i_mount, (xfs_lsn_t)0,
1088                                       XFS_LOG_FORCE |
1089                                       ((flag & FSYNC_WAIT)
1090                                        ? XFS_LOG_SYNC : 0),
1091                                       &log_flushed);
1092                 } else {
1093                         /*
1094                          * If the inode is not pinned and nothing
1095                          * has changed we don't need to flush the
1096                          * cache.
1097                          */
1098                         changed = 0;
1099                 }
1100                 error = 0;
1101         } else  {
1102                 /*
1103                  * Kick off a transaction to log the inode
1104                  * core to get the updates.  Make it
1105                  * sync if FSYNC_WAIT is passed in (which
1106                  * is done by everybody but specfs).  The
1107                  * sync transaction will also force the log.
1108                  */
1109                 xfs_iunlock(ip, XFS_ILOCK_SHARED);
1110                 tp = xfs_trans_alloc(ip->i_mount, XFS_TRANS_FSYNC_TS);
1111                 if ((error = xfs_trans_reserve(tp, 0,
1112                                 XFS_FSYNC_TS_LOG_RES(ip->i_mount),
1113                                 0, 0, 0)))  {
1114                         xfs_trans_cancel(tp, 0);
1115                         return error;
1116                 }
1117                 xfs_ilock(ip, XFS_ILOCK_EXCL);
1118
1119                 /*
1120                  * Note - it's possible that we might have pushed
1121                  * ourselves out of the way during trans_reserve
1122                  * which would flush the inode.  But there's no
1123                  * guarantee that the inode buffer has actually
1124                  * gone out yet (it's delwri).  Plus the buffer
1125                  * could be pinned anyway if it's part of an
1126                  * inode in another recent transaction.  So we
1127                  * play it safe and fire off the transaction anyway.
1128                  */
1129                 xfs_trans_ijoin(tp, ip, XFS_ILOCK_EXCL);
1130                 xfs_trans_ihold(tp, ip);
1131                 xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
1132                 if (flag & FSYNC_WAIT)
1133                         xfs_trans_set_sync(tp);
1134                 error = _xfs_trans_commit(tp, 0, &log_flushed);
1135
1136                 xfs_iunlock(ip, XFS_ILOCK_EXCL);
1137         }
1138
1139         if ((ip->i_mount->m_flags & XFS_MOUNT_BARRIER) && changed) {
1140                 /*
1141                  * If the log write didn't issue an ordered tag we need
1142                  * to flush the disk cache for the data device now.
1143                  */
1144                 if (!log_flushed)
1145                         xfs_blkdev_issue_flush(ip->i_mount->m_ddev_targp);
1146
1147                 /*
1148                  * If this inode is on the RT dev we need to flush that
1149                  * cache as well.
1150                  */
1151                 if (ip->i_d.di_flags & XFS_DIFLAG_REALTIME)
1152                         xfs_blkdev_issue_flush(ip->i_mount->m_rtdev_targp);
1153         }
1154
1155         return error;
1156 }
1157
1158 /*
1159  * This is called by xfs_inactive to free any blocks beyond eof
1160  * when the link count isn't zero and by xfs_dm_punch_hole() when
1161  * punching a hole to EOF.
1162  */
1163 int
1164 xfs_free_eofblocks(
1165         xfs_mount_t     *mp,
1166         xfs_inode_t     *ip,
1167         int             flags)
1168 {
1169         xfs_trans_t     *tp;
1170         int             error;
1171         xfs_fileoff_t   end_fsb;
1172         xfs_fileoff_t   last_fsb;
1173         xfs_filblks_t   map_len;
1174         int             nimaps;
1175         xfs_bmbt_irec_t imap;
1176         int             use_iolock = (flags & XFS_FREE_EOF_LOCK);
1177
1178         /*
1179          * Figure out if there are any blocks beyond the end
1180          * of the file.  If not, then there is nothing to do.
1181          */
1182         end_fsb = XFS_B_TO_FSB(mp, ((xfs_ufsize_t)ip->i_size));
1183         last_fsb = XFS_B_TO_FSB(mp, (xfs_ufsize_t)XFS_MAXIOFFSET(mp));
1184         map_len = last_fsb - end_fsb;
1185         if (map_len <= 0)
1186                 return 0;
1187
1188         nimaps = 1;
1189         xfs_ilock(ip, XFS_ILOCK_SHARED);
1190         error = XFS_BMAPI(mp, NULL, &ip->i_iocore, end_fsb, map_len, 0,
1191                           NULL, 0, &imap, &nimaps, NULL, NULL);
1192         xfs_iunlock(ip, XFS_ILOCK_SHARED);
1193
1194         if (!error && (nimaps != 0) &&
1195             (imap.br_startblock != HOLESTARTBLOCK ||
1196              ip->i_delayed_blks)) {
1197                 /*
1198                  * Attach the dquots to the inode up front.
1199                  */
1200                 if ((error = XFS_QM_DQATTACH(mp, ip, 0)))
1201                         return error;
1202
1203                 /*
1204                  * There are blocks after the end of file.
1205                  * Free them up now by truncating the file to
1206                  * its current size.
1207                  */
1208                 tp = xfs_trans_alloc(mp, XFS_TRANS_INACTIVE);
1209
1210                 /*
1211                  * Do the xfs_itruncate_start() call before
1212                  * reserving any log space because
1213                  * itruncate_start will call into the buffer
1214                  * cache and we can't
1215                  * do that within a transaction.
1216                  */
1217                 if (use_iolock)
1218                         xfs_ilock(ip, XFS_IOLOCK_EXCL);
1219                 error = xfs_itruncate_start(ip, XFS_ITRUNC_DEFINITE,
1220                                     ip->i_size);
1221                 if (error) {
1222                         xfs_trans_cancel(tp, 0);
1223                         if (use_iolock)
1224                                 xfs_iunlock(ip, XFS_IOLOCK_EXCL);
1225                         return error;
1226                 }
1227
1228                 error = xfs_trans_reserve(tp, 0,
1229                                           XFS_ITRUNCATE_LOG_RES(mp),
1230                                           0, XFS_TRANS_PERM_LOG_RES,
1231                                           XFS_ITRUNCATE_LOG_COUNT);
1232                 if (error) {
1233                         ASSERT(XFS_FORCED_SHUTDOWN(mp));
1234                         xfs_trans_cancel(tp, 0);
1235                         xfs_iunlock(ip, XFS_IOLOCK_EXCL);
1236                         return error;
1237                 }
1238
1239                 xfs_ilock(ip, XFS_ILOCK_EXCL);
1240                 xfs_trans_ijoin(tp, ip,
1241                                 XFS_IOLOCK_EXCL |
1242                                 XFS_ILOCK_EXCL);
1243                 xfs_trans_ihold(tp, ip);
1244
1245                 error = xfs_itruncate_finish(&tp, ip,
1246                                              ip->i_size,
1247                                              XFS_DATA_FORK,
1248                                              0);
1249                 /*
1250                  * If we get an error at this point we
1251                  * simply don't bother truncating the file.
1252                  */
1253                 if (error) {
1254                         xfs_trans_cancel(tp,
1255                                          (XFS_TRANS_RELEASE_LOG_RES |
1256                                           XFS_TRANS_ABORT));
1257                 } else {
1258                         error = xfs_trans_commit(tp,
1259                                                 XFS_TRANS_RELEASE_LOG_RES);
1260                 }
1261                 xfs_iunlock(ip, (use_iolock ? (XFS_IOLOCK_EXCL|XFS_ILOCK_EXCL)
1262                                             : XFS_ILOCK_EXCL));
1263         }
1264         return error;
1265 }
1266
1267 /*
1268  * Free a symlink that has blocks associated with it.
1269  */
1270 STATIC int
1271 xfs_inactive_symlink_rmt(
1272         xfs_inode_t     *ip,
1273         xfs_trans_t     **tpp)
1274 {
1275         xfs_buf_t       *bp;
1276         int             committed;
1277         int             done;
1278         int             error;
1279         xfs_fsblock_t   first_block;
1280         xfs_bmap_free_t free_list;
1281         int             i;
1282         xfs_mount_t     *mp;
1283         xfs_bmbt_irec_t mval[SYMLINK_MAPS];
1284         int             nmaps;
1285         xfs_trans_t     *ntp;
1286         int             size;
1287         xfs_trans_t     *tp;
1288
1289         tp = *tpp;
1290         mp = ip->i_mount;
1291         ASSERT(ip->i_d.di_size > XFS_IFORK_DSIZE(ip));
1292         /*
1293          * We're freeing a symlink that has some
1294          * blocks allocated to it.  Free the
1295          * blocks here.  We know that we've got
1296          * either 1 or 2 extents and that we can
1297          * free them all in one bunmapi call.
1298          */
1299         ASSERT(ip->i_d.di_nextents > 0 && ip->i_d.di_nextents <= 2);
1300         if ((error = xfs_trans_reserve(tp, 0, XFS_ITRUNCATE_LOG_RES(mp), 0,
1301                         XFS_TRANS_PERM_LOG_RES, XFS_ITRUNCATE_LOG_COUNT))) {
1302                 ASSERT(XFS_FORCED_SHUTDOWN(mp));
1303                 xfs_trans_cancel(tp, 0);
1304                 *tpp = NULL;
1305                 return error;
1306         }
1307         /*
1308          * Lock the inode, fix the size, and join it to the transaction.
1309          * Hold it so in the normal path, we still have it locked for
1310          * the second transaction.  In the error paths we need it
1311          * held so the cancel won't rele it, see below.
1312          */
1313         xfs_ilock(ip, XFS_IOLOCK_EXCL | XFS_ILOCK_EXCL);
1314         size = (int)ip->i_d.di_size;
1315         ip->i_d.di_size = 0;
1316         xfs_trans_ijoin(tp, ip, XFS_ILOCK_EXCL | XFS_IOLOCK_EXCL);
1317         xfs_trans_ihold(tp, ip);
1318         xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
1319         /*
1320          * Find the block(s) so we can inval and unmap them.
1321          */
1322         done = 0;
1323         XFS_BMAP_INIT(&free_list, &first_block);
1324         nmaps = ARRAY_SIZE(mval);
1325         if ((error = xfs_bmapi(tp, ip, 0, XFS_B_TO_FSB(mp, size),
1326                         XFS_BMAPI_METADATA, &first_block, 0, mval, &nmaps,
1327                         &free_list, NULL)))
1328                 goto error0;
1329         /*
1330          * Invalidate the block(s).
1331          */
1332         for (i = 0; i < nmaps; i++) {
1333                 bp = xfs_trans_get_buf(tp, mp->m_ddev_targp,
1334                         XFS_FSB_TO_DADDR(mp, mval[i].br_startblock),
1335                         XFS_FSB_TO_BB(mp, mval[i].br_blockcount), 0);
1336                 xfs_trans_binval(tp, bp);
1337         }
1338         /*
1339          * Unmap the dead block(s) to the free_list.
1340          */
1341         if ((error = xfs_bunmapi(tp, ip, 0, size, XFS_BMAPI_METADATA, nmaps,
1342                         &first_block, &free_list, NULL, &done)))
1343                 goto error1;
1344         ASSERT(done);
1345         /*
1346          * Commit the first transaction.  This logs the EFI and the inode.
1347          */
1348         if ((error = xfs_bmap_finish(&tp, &free_list, &committed)))
1349                 goto error1;
1350         /*
1351          * The transaction must have been committed, since there were
1352          * actually extents freed by xfs_bunmapi.  See xfs_bmap_finish.
1353          * The new tp has the extent freeing and EFDs.
1354          */
1355         ASSERT(committed);
1356         /*
1357          * The first xact was committed, so add the inode to the new one.
1358          * Mark it dirty so it will be logged and moved forward in the log as
1359          * part of every commit.
1360          */
1361         xfs_trans_ijoin(tp, ip, XFS_ILOCK_EXCL | XFS_IOLOCK_EXCL);
1362         xfs_trans_ihold(tp, ip);
1363         xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
1364         /*
1365          * Get a new, empty transaction to return to our caller.
1366          */
1367         ntp = xfs_trans_dup(tp);
1368         /*
1369          * Commit the transaction containing extent freeing and EFDs.
1370          * If we get an error on the commit here or on the reserve below,
1371          * we need to unlock the inode since the new transaction doesn't
1372          * have the inode attached.
1373          */
1374         error = xfs_trans_commit(tp, 0);
1375         tp = ntp;
1376         if (error) {
1377                 ASSERT(XFS_FORCED_SHUTDOWN(mp));
1378                 goto error0;
1379         }
1380         /*
1381          * Remove the memory for extent descriptions (just bookkeeping).
1382          */
1383         if (ip->i_df.if_bytes)
1384                 xfs_idata_realloc(ip, -ip->i_df.if_bytes, XFS_DATA_FORK);
1385         ASSERT(ip->i_df.if_bytes == 0);
1386         /*
1387          * Put an itruncate log reservation in the new transaction
1388          * for our caller.
1389          */
1390         if ((error = xfs_trans_reserve(tp, 0, XFS_ITRUNCATE_LOG_RES(mp), 0,
1391                         XFS_TRANS_PERM_LOG_RES, XFS_ITRUNCATE_LOG_COUNT))) {
1392                 ASSERT(XFS_FORCED_SHUTDOWN(mp));
1393                 goto error0;
1394         }
1395         /*
1396          * Return with the inode locked but not joined to the transaction.
1397          */
1398         *tpp = tp;
1399         return 0;
1400
1401  error1:
1402         xfs_bmap_cancel(&free_list);
1403  error0:
1404         /*
1405          * Have to come here with the inode locked and either
1406          * (held and in the transaction) or (not in the transaction).
1407          * If the inode isn't held then cancel would iput it, but
1408          * that's wrong since this is inactive and the vnode ref
1409          * count is 0 already.
1410          * Cancel won't do anything to the inode if held, but it still
1411          * needs to be locked until the cancel is done, if it was
1412          * joined to the transaction.
1413          */
1414         xfs_trans_cancel(tp, XFS_TRANS_RELEASE_LOG_RES | XFS_TRANS_ABORT);
1415         xfs_iunlock(ip, XFS_IOLOCK_EXCL | XFS_ILOCK_EXCL);
1416         *tpp = NULL;
1417         return error;
1418
1419 }
1420
1421 STATIC int
1422 xfs_inactive_symlink_local(
1423         xfs_inode_t     *ip,
1424         xfs_trans_t     **tpp)
1425 {
1426         int             error;
1427
1428         ASSERT(ip->i_d.di_size <= XFS_IFORK_DSIZE(ip));
1429         /*
1430          * We're freeing a symlink which fit into
1431          * the inode.  Just free the memory used
1432          * to hold the old symlink.
1433          */
1434         error = xfs_trans_reserve(*tpp, 0,
1435                                   XFS_ITRUNCATE_LOG_RES(ip->i_mount),
1436                                   0, XFS_TRANS_PERM_LOG_RES,
1437                                   XFS_ITRUNCATE_LOG_COUNT);
1438
1439         if (error) {
1440                 xfs_trans_cancel(*tpp, 0);
1441                 *tpp = NULL;
1442                 return error;
1443         }
1444         xfs_ilock(ip, XFS_ILOCK_EXCL | XFS_IOLOCK_EXCL);
1445
1446         /*
1447          * Zero length symlinks _can_ exist.
1448          */
1449         if (ip->i_df.if_bytes > 0) {
1450                 xfs_idata_realloc(ip,
1451                                   -(ip->i_df.if_bytes),
1452                                   XFS_DATA_FORK);
1453                 ASSERT(ip->i_df.if_bytes == 0);
1454         }
1455         return 0;
1456 }
1457
1458 STATIC int
1459 xfs_inactive_attrs(
1460         xfs_inode_t     *ip,
1461         xfs_trans_t     **tpp)
1462 {
1463         xfs_trans_t     *tp;
1464         int             error;
1465         xfs_mount_t     *mp;
1466
1467         ASSERT(ismrlocked(&ip->i_iolock, MR_UPDATE));
1468         tp = *tpp;
1469         mp = ip->i_mount;
1470         ASSERT(ip->i_d.di_forkoff != 0);
1471         xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
1472         xfs_iunlock(ip, XFS_ILOCK_EXCL);
1473
1474         error = xfs_attr_inactive(ip);
1475         if (error) {
1476                 *tpp = NULL;
1477                 xfs_iunlock(ip, XFS_IOLOCK_EXCL);
1478                 return error; /* goto out */
1479         }
1480
1481         tp = xfs_trans_alloc(mp, XFS_TRANS_INACTIVE);
1482         error = xfs_trans_reserve(tp, 0,
1483                                   XFS_IFREE_LOG_RES(mp),
1484                                   0, XFS_TRANS_PERM_LOG_RES,
1485                                   XFS_INACTIVE_LOG_COUNT);
1486         if (error) {
1487                 ASSERT(XFS_FORCED_SHUTDOWN(mp));
1488                 xfs_trans_cancel(tp, 0);
1489                 *tpp = NULL;
1490                 xfs_iunlock(ip, XFS_IOLOCK_EXCL);
1491                 return error;
1492         }
1493
1494         xfs_ilock(ip, XFS_ILOCK_EXCL);
1495         xfs_trans_ijoin(tp, ip, XFS_IOLOCK_EXCL | XFS_ILOCK_EXCL);
1496         xfs_trans_ihold(tp, ip);
1497         xfs_idestroy_fork(ip, XFS_ATTR_FORK);
1498
1499         ASSERT(ip->i_d.di_anextents == 0);
1500
1501         *tpp = tp;
1502         return 0;
1503 }
1504
1505 int
1506 xfs_release(
1507         xfs_inode_t     *ip)
1508 {
1509         bhv_vnode_t     *vp = XFS_ITOV(ip);
1510         xfs_mount_t     *mp = ip->i_mount;
1511         int             error;
1512
1513         if (!VN_ISREG(vp) || (ip->i_d.di_mode == 0))
1514                 return 0;
1515
1516         /* If this is a read-only mount, don't do this (would generate I/O) */
1517         if (mp->m_flags & XFS_MOUNT_RDONLY)
1518                 return 0;
1519
1520         if (!XFS_FORCED_SHUTDOWN(mp)) {
1521                 int truncated;
1522
1523                 /*
1524                  * If we are using filestreams, and we have an unlinked
1525                  * file that we are processing the last close on, then nothing
1526                  * will be able to reopen and write to this file. Purge this
1527                  * inode from the filestreams cache so that it doesn't delay
1528                  * teardown of the inode.
1529                  */
1530                 if ((ip->i_d.di_nlink == 0) && xfs_inode_is_filestream(ip))
1531                         xfs_filestream_deassociate(ip);
1532
1533                 /*
1534                  * If we previously truncated this file and removed old data
1535                  * in the process, we want to initiate "early" writeout on
1536                  * the last close.  This is an attempt to combat the notorious
1537                  * NULL files problem which is particularly noticable from a
1538                  * truncate down, buffered (re-)write (delalloc), followed by
1539                  * a crash.  What we are effectively doing here is
1540                  * significantly reducing the time window where we'd otherwise
1541                  * be exposed to that problem.
1542                  */
1543                 truncated = xfs_iflags_test_and_clear(ip, XFS_ITRUNCATED);
1544                 if (truncated && VN_DIRTY(vp) && ip->i_delayed_blks > 0)
1545                         xfs_flush_pages(ip, 0, -1, XFS_B_ASYNC, FI_NONE);
1546         }
1547
1548 #ifdef HAVE_REFCACHE
1549         /* If we are in the NFS reference cache then don't do this now */
1550         if (ip->i_refcache)
1551                 return 0;
1552 #endif
1553
1554         if (ip->i_d.di_nlink != 0) {
1555                 if ((((ip->i_d.di_mode & S_IFMT) == S_IFREG) &&
1556                      ((ip->i_size > 0) || (VN_CACHED(vp) > 0 ||
1557                        ip->i_delayed_blks > 0)) &&
1558                      (ip->i_df.if_flags & XFS_IFEXTENTS))  &&
1559                     (!(ip->i_d.di_flags &
1560                                 (XFS_DIFLAG_PREALLOC | XFS_DIFLAG_APPEND)))) {
1561                         error = xfs_free_eofblocks(mp, ip, XFS_FREE_EOF_LOCK);
1562                         if (error)
1563                                 return error;
1564                         /* Update linux inode block count after free above */
1565                         vn_to_inode(vp)->i_blocks = XFS_FSB_TO_BB(mp,
1566                                 ip->i_d.di_nblocks + ip->i_delayed_blks);
1567                 }
1568         }
1569
1570         return 0;
1571 }
1572
1573 /*
1574  * xfs_inactive
1575  *
1576  * This is called when the vnode reference count for the vnode
1577  * goes to zero.  If the file has been unlinked, then it must
1578  * now be truncated.  Also, we clear all of the read-ahead state
1579  * kept for the inode here since the file is now closed.
1580  */
1581 int
1582 xfs_inactive(
1583         xfs_inode_t     *ip)
1584 {
1585         bhv_vnode_t     *vp = XFS_ITOV(ip);
1586         xfs_bmap_free_t free_list;
1587         xfs_fsblock_t   first_block;
1588         int             committed;
1589         xfs_trans_t     *tp;
1590         xfs_mount_t     *mp;
1591         int             error;
1592         int             truncate;
1593
1594         xfs_itrace_entry(ip);
1595
1596         /*
1597          * If the inode is already free, then there can be nothing
1598          * to clean up here.
1599          */
1600         if (ip->i_d.di_mode == 0 || VN_BAD(vp)) {
1601                 ASSERT(ip->i_df.if_real_bytes == 0);
1602                 ASSERT(ip->i_df.if_broot_bytes == 0);
1603                 return VN_INACTIVE_CACHE;
1604         }
1605
1606         /*
1607          * Only do a truncate if it's a regular file with
1608          * some actual space in it.  It's OK to look at the
1609          * inode's fields without the lock because we're the
1610          * only one with a reference to the inode.
1611          */
1612         truncate = ((ip->i_d.di_nlink == 0) &&
1613             ((ip->i_d.di_size != 0) || (ip->i_size != 0) ||
1614              (ip->i_d.di_nextents > 0) || (ip->i_delayed_blks > 0)) &&
1615             ((ip->i_d.di_mode & S_IFMT) == S_IFREG));
1616
1617         mp = ip->i_mount;
1618
1619         if (ip->i_d.di_nlink == 0 && DM_EVENT_ENABLED(ip, DM_EVENT_DESTROY)) {
1620                 (void) XFS_SEND_DESTROY(mp, vp, DM_RIGHT_NULL);
1621         }
1622
1623         error = 0;
1624
1625         /* If this is a read-only mount, don't do this (would generate I/O) */
1626         if (mp->m_flags & XFS_MOUNT_RDONLY)
1627                 goto out;
1628
1629         if (ip->i_d.di_nlink != 0) {
1630                 if ((((ip->i_d.di_mode & S_IFMT) == S_IFREG) &&
1631                      ((ip->i_size > 0) || (VN_CACHED(vp) > 0 ||
1632                        ip->i_delayed_blks > 0)) &&
1633                       (ip->i_df.if_flags & XFS_IFEXTENTS) &&
1634                      (!(ip->i_d.di_flags &
1635                                 (XFS_DIFLAG_PREALLOC | XFS_DIFLAG_APPEND)) ||
1636                       (ip->i_delayed_blks != 0)))) {
1637                         error = xfs_free_eofblocks(mp, ip, XFS_FREE_EOF_LOCK);
1638                         if (error)
1639                                 return VN_INACTIVE_CACHE;
1640                         /* Update linux inode block count after free above */
1641                         vn_to_inode(vp)->i_blocks = XFS_FSB_TO_BB(mp,
1642                                 ip->i_d.di_nblocks + ip->i_delayed_blks);
1643                 }
1644                 goto out;
1645         }
1646
1647         ASSERT(ip->i_d.di_nlink == 0);
1648
1649         if ((error = XFS_QM_DQATTACH(mp, ip, 0)))
1650                 return VN_INACTIVE_CACHE;
1651
1652         tp = xfs_trans_alloc(mp, XFS_TRANS_INACTIVE);
1653         if (truncate) {
1654                 /*
1655                  * Do the xfs_itruncate_start() call before
1656                  * reserving any log space because itruncate_start
1657                  * will call into the buffer cache and we can't
1658                  * do that within a transaction.
1659                  */
1660                 xfs_ilock(ip, XFS_IOLOCK_EXCL);
1661
1662                 error = xfs_itruncate_start(ip, XFS_ITRUNC_DEFINITE, 0);
1663                 if (error) {
1664                         xfs_trans_cancel(tp, 0);
1665                         xfs_iunlock(ip, XFS_IOLOCK_EXCL);
1666                         return VN_INACTIVE_CACHE;
1667                 }
1668
1669                 error = xfs_trans_reserve(tp, 0,
1670                                           XFS_ITRUNCATE_LOG_RES(mp),
1671                                           0, XFS_TRANS_PERM_LOG_RES,
1672                                           XFS_ITRUNCATE_LOG_COUNT);
1673                 if (error) {
1674                         /* Don't call itruncate_cleanup */
1675                         ASSERT(XFS_FORCED_SHUTDOWN(mp));
1676                         xfs_trans_cancel(tp, 0);
1677                         xfs_iunlock(ip, XFS_IOLOCK_EXCL);
1678                         return VN_INACTIVE_CACHE;
1679                 }
1680
1681                 xfs_ilock(ip, XFS_ILOCK_EXCL);
1682                 xfs_trans_ijoin(tp, ip, XFS_IOLOCK_EXCL | XFS_ILOCK_EXCL);
1683                 xfs_trans_ihold(tp, ip);
1684
1685                 /*
1686                  * normally, we have to run xfs_itruncate_finish sync.
1687                  * But if filesystem is wsync and we're in the inactive
1688                  * path, then we know that nlink == 0, and that the
1689                  * xaction that made nlink == 0 is permanently committed
1690                  * since xfs_remove runs as a synchronous transaction.
1691                  */
1692                 error = xfs_itruncate_finish(&tp, ip, 0, XFS_DATA_FORK,
1693                                 (!(mp->m_flags & XFS_MOUNT_WSYNC) ? 1 : 0));
1694
1695                 if (error) {
1696                         xfs_trans_cancel(tp,
1697                                 XFS_TRANS_RELEASE_LOG_RES | XFS_TRANS_ABORT);
1698                         xfs_iunlock(ip, XFS_IOLOCK_EXCL | XFS_ILOCK_EXCL);
1699                         return VN_INACTIVE_CACHE;
1700                 }
1701         } else if ((ip->i_d.di_mode & S_IFMT) == S_IFLNK) {
1702
1703                 /*
1704                  * If we get an error while cleaning up a
1705                  * symlink we bail out.
1706                  */
1707                 error = (ip->i_d.di_size > XFS_IFORK_DSIZE(ip)) ?
1708                         xfs_inactive_symlink_rmt(ip, &tp) :
1709                         xfs_inactive_symlink_local(ip, &tp);
1710
1711                 if (error) {
1712                         ASSERT(tp == NULL);
1713                         return VN_INACTIVE_CACHE;
1714                 }
1715
1716                 xfs_trans_ijoin(tp, ip, XFS_IOLOCK_EXCL | XFS_ILOCK_EXCL);
1717                 xfs_trans_ihold(tp, ip);
1718         } else {
1719                 error = xfs_trans_reserve(tp, 0,
1720                                           XFS_IFREE_LOG_RES(mp),
1721                                           0, XFS_TRANS_PERM_LOG_RES,
1722                                           XFS_INACTIVE_LOG_COUNT);
1723                 if (error) {
1724                         ASSERT(XFS_FORCED_SHUTDOWN(mp));
1725                         xfs_trans_cancel(tp, 0);
1726                         return VN_INACTIVE_CACHE;
1727                 }
1728
1729                 xfs_ilock(ip, XFS_ILOCK_EXCL | XFS_IOLOCK_EXCL);
1730                 xfs_trans_ijoin(tp, ip, XFS_IOLOCK_EXCL | XFS_ILOCK_EXCL);
1731                 xfs_trans_ihold(tp, ip);
1732         }
1733
1734         /*
1735          * If there are attributes associated with the file
1736          * then blow them away now.  The code calls a routine
1737          * that recursively deconstructs the attribute fork.
1738          * We need to just commit the current transaction
1739          * because we can't use it for xfs_attr_inactive().
1740          */
1741         if (ip->i_d.di_anextents > 0) {
1742                 error = xfs_inactive_attrs(ip, &tp);
1743                 /*
1744                  * If we got an error, the transaction is already
1745                  * cancelled, and the inode is unlocked. Just get out.
1746                  */
1747                  if (error)
1748                          return VN_INACTIVE_CACHE;
1749         } else if (ip->i_afp) {
1750                 xfs_idestroy_fork(ip, XFS_ATTR_FORK);
1751         }
1752
1753         /*
1754          * Free the inode.
1755          */
1756         XFS_BMAP_INIT(&free_list, &first_block);
1757         error = xfs_ifree(tp, ip, &free_list);
1758         if (error) {
1759                 /*
1760                  * If we fail to free the inode, shut down.  The cancel
1761                  * might do that, we need to make sure.  Otherwise the
1762                  * inode might be lost for a long time or forever.
1763                  */
1764                 if (!XFS_FORCED_SHUTDOWN(mp)) {
1765                         cmn_err(CE_NOTE,
1766                 "xfs_inactive:  xfs_ifree() returned an error = %d on %s",
1767                                 error, mp->m_fsname);
1768                         xfs_force_shutdown(mp, SHUTDOWN_META_IO_ERROR);
1769                 }
1770                 xfs_trans_cancel(tp, XFS_TRANS_RELEASE_LOG_RES|XFS_TRANS_ABORT);
1771         } else {
1772                 /*
1773                  * Credit the quota account(s). The inode is gone.
1774                  */
1775                 XFS_TRANS_MOD_DQUOT_BYINO(mp, tp, ip, XFS_TRANS_DQ_ICOUNT, -1);
1776
1777                 /*
1778                  * Just ignore errors at this point.  There is
1779                  * nothing we can do except to try to keep going.
1780                  */
1781                 (void) xfs_bmap_finish(&tp,  &free_list, &committed);
1782                 (void) xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
1783         }
1784         /*
1785          * Release the dquots held by inode, if any.
1786          */
1787         XFS_QM_DQDETACH(mp, ip);
1788
1789         xfs_iunlock(ip, XFS_IOLOCK_EXCL | XFS_ILOCK_EXCL);
1790
1791  out:
1792         return VN_INACTIVE_CACHE;
1793 }
1794
1795
1796 int
1797 xfs_lookup(
1798         xfs_inode_t             *dp,
1799         bhv_vname_t             *dentry,
1800         bhv_vnode_t             **vpp)
1801 {
1802         xfs_inode_t             *ip;
1803         xfs_ino_t               e_inum;
1804         int                     error;
1805         uint                    lock_mode;
1806
1807         xfs_itrace_entry(dp);
1808
1809         if (XFS_FORCED_SHUTDOWN(dp->i_mount))
1810                 return XFS_ERROR(EIO);
1811
1812         lock_mode = xfs_ilock_map_shared(dp);
1813         error = xfs_dir_lookup_int(dp, lock_mode, dentry, &e_inum, &ip);
1814         if (!error) {
1815                 *vpp = XFS_ITOV(ip);
1816                 xfs_itrace_ref(ip);
1817         }
1818         xfs_iunlock_map_shared(dp, lock_mode);
1819         return error;
1820 }
1821
1822 int
1823 xfs_create(
1824         xfs_inode_t             *dp,
1825         bhv_vname_t             *dentry,
1826         mode_t                  mode,
1827         xfs_dev_t               rdev,
1828         bhv_vnode_t             **vpp,
1829         cred_t                  *credp)
1830 {
1831         char                    *name = VNAME(dentry);
1832         xfs_mount_t             *mp = dp->i_mount;
1833         bhv_vnode_t             *dir_vp = XFS_ITOV(dp);
1834         xfs_inode_t             *ip;
1835         bhv_vnode_t             *vp = NULL;
1836         xfs_trans_t             *tp;
1837         int                     error;
1838         xfs_bmap_free_t         free_list;
1839         xfs_fsblock_t           first_block;
1840         boolean_t               unlock_dp_on_error = B_FALSE;
1841         int                     dm_event_sent = 0;
1842         uint                    cancel_flags;
1843         int                     committed;
1844         xfs_prid_t              prid;
1845         struct xfs_dquot        *udqp, *gdqp;
1846         uint                    resblks;
1847         int                     namelen;
1848
1849         ASSERT(!*vpp);
1850         xfs_itrace_entry(dp);
1851
1852         namelen = VNAMELEN(dentry);
1853
1854         if (DM_EVENT_ENABLED(dp, DM_EVENT_CREATE)) {
1855                 error = XFS_SEND_NAMESP(mp, DM_EVENT_CREATE,
1856                                 dir_vp, DM_RIGHT_NULL, NULL,
1857                                 DM_RIGHT_NULL, name, NULL,
1858                                 mode, 0, 0);
1859
1860                 if (error)
1861                         return error;
1862                 dm_event_sent = 1;
1863         }
1864
1865         if (XFS_FORCED_SHUTDOWN(mp))
1866                 return XFS_ERROR(EIO);
1867
1868         /* Return through std_return after this point. */
1869
1870         udqp = gdqp = NULL;
1871         if (dp->i_d.di_flags & XFS_DIFLAG_PROJINHERIT)
1872                 prid = dp->i_d.di_projid;
1873         else
1874                 prid = (xfs_prid_t)dfltprid;
1875
1876         /*
1877          * Make sure that we have allocated dquot(s) on disk.
1878          */
1879         error = XFS_QM_DQVOPALLOC(mp, dp,
1880                         current_fsuid(credp), current_fsgid(credp), prid,
1881                         XFS_QMOPT_QUOTALL|XFS_QMOPT_INHERIT, &udqp, &gdqp);
1882         if (error)
1883                 goto std_return;
1884
1885         ip = NULL;
1886
1887         tp = xfs_trans_alloc(mp, XFS_TRANS_CREATE);
1888         cancel_flags = XFS_TRANS_RELEASE_LOG_RES;
1889         resblks = XFS_CREATE_SPACE_RES(mp, namelen);
1890         /*
1891          * Initially assume that the file does not exist and
1892          * reserve the resources for that case.  If that is not
1893          * the case we'll drop the one we have and get a more
1894          * appropriate transaction later.
1895          */
1896         error = xfs_trans_reserve(tp, resblks, XFS_CREATE_LOG_RES(mp), 0,
1897                         XFS_TRANS_PERM_LOG_RES, XFS_CREATE_LOG_COUNT);
1898         if (error == ENOSPC) {
1899                 resblks = 0;
1900                 error = xfs_trans_reserve(tp, 0, XFS_CREATE_LOG_RES(mp), 0,
1901                                 XFS_TRANS_PERM_LOG_RES, XFS_CREATE_LOG_COUNT);
1902         }
1903         if (error) {
1904                 cancel_flags = 0;
1905                 goto error_return;
1906         }
1907
1908         xfs_ilock(dp, XFS_ILOCK_EXCL | XFS_ILOCK_PARENT);
1909         unlock_dp_on_error = B_TRUE;
1910
1911         XFS_BMAP_INIT(&free_list, &first_block);
1912
1913         ASSERT(ip == NULL);
1914
1915         /*
1916          * Reserve disk quota and the inode.
1917          */
1918         error = XFS_TRANS_RESERVE_QUOTA(mp, tp, udqp, gdqp, resblks, 1, 0);
1919         if (error)
1920                 goto error_return;
1921
1922         if (resblks == 0 && (error = xfs_dir_canenter(tp, dp, name, namelen)))
1923                 goto error_return;
1924         error = xfs_dir_ialloc(&tp, dp, mode, 1,
1925                         rdev, credp, prid, resblks > 0,
1926                         &ip, &committed);
1927         if (error) {
1928                 if (error == ENOSPC)
1929                         goto error_return;
1930                 goto abort_return;
1931         }
1932         xfs_itrace_ref(ip);
1933
1934         /*
1935          * At this point, we've gotten a newly allocated inode.
1936          * It is locked (and joined to the transaction).
1937          */
1938
1939         ASSERT(ismrlocked (&ip->i_lock, MR_UPDATE));
1940
1941         /*
1942          * Now we join the directory inode to the transaction.  We do not do it
1943          * earlier because xfs_dir_ialloc might commit the previous transaction
1944          * (and release all the locks).  An error from here on will result in
1945          * the transaction cancel unlocking dp so don't do it explicitly in the
1946          * error path.
1947          */
1948         VN_HOLD(dir_vp);
1949         xfs_trans_ijoin(tp, dp, XFS_ILOCK_EXCL);
1950         unlock_dp_on_error = B_FALSE;
1951
1952         error = xfs_dir_createname(tp, dp, name, namelen, ip->i_ino,
1953                                         &first_block, &free_list, resblks ?
1954                                         resblks - XFS_IALLOC_SPACE_RES(mp) : 0);
1955         if (error) {
1956                 ASSERT(error != ENOSPC);
1957                 goto abort_return;
1958         }
1959         xfs_ichgtime(dp, XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG);
1960         xfs_trans_log_inode(tp, dp, XFS_ILOG_CORE);
1961
1962         /*
1963          * If this is a synchronous mount, make sure that the
1964          * create transaction goes to disk before returning to
1965          * the user.
1966          */
1967         if (mp->m_flags & (XFS_MOUNT_WSYNC|XFS_MOUNT_DIRSYNC)) {
1968                 xfs_trans_set_sync(tp);
1969         }
1970
1971         dp->i_gen++;
1972
1973         /*
1974          * Attach the dquot(s) to the inodes and modify them incore.
1975          * These ids of the inode couldn't have changed since the new
1976          * inode has been locked ever since it was created.
1977          */
1978         XFS_QM_DQVOPCREATE(mp, tp, ip, udqp, gdqp);
1979
1980         /*
1981          * xfs_trans_commit normally decrements the vnode ref count
1982          * when it unlocks the inode. Since we want to return the
1983          * vnode to the caller, we bump the vnode ref count now.
1984          */
1985         IHOLD(ip);
1986         vp = XFS_ITOV(ip);
1987
1988         error = xfs_bmap_finish(&tp, &free_list, &committed);
1989         if (error) {
1990                 xfs_bmap_cancel(&free_list);
1991                 goto abort_rele;
1992         }
1993
1994         error = xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
1995         if (error) {
1996                 IRELE(ip);
1997                 tp = NULL;
1998                 goto error_return;
1999         }
2000
2001         XFS_QM_DQRELE(mp, udqp);
2002         XFS_QM_DQRELE(mp, gdqp);
2003
2004         *vpp = vp;
2005
2006         /* Fallthrough to std_return with error = 0  */
2007
2008 std_return:
2009         if ((*vpp || (error != 0 && dm_event_sent != 0)) &&
2010             DM_EVENT_ENABLED(dp, DM_EVENT_POSTCREATE)) {
2011                 (void) XFS_SEND_NAMESP(mp, DM_EVENT_POSTCREATE,
2012                         dir_vp, DM_RIGHT_NULL,
2013                         *vpp ? vp:NULL,
2014                         DM_RIGHT_NULL, name, NULL,
2015                         mode, error, 0);
2016         }
2017         return error;
2018
2019  abort_return:
2020         cancel_flags |= XFS_TRANS_ABORT;
2021         /* FALLTHROUGH */
2022
2023  error_return:
2024         if (tp != NULL)
2025                 xfs_trans_cancel(tp, cancel_flags);
2026
2027         XFS_QM_DQRELE(mp, udqp);
2028         XFS_QM_DQRELE(mp, gdqp);
2029
2030         if (unlock_dp_on_error)
2031                 xfs_iunlock(dp, XFS_ILOCK_EXCL);
2032
2033         goto std_return;
2034
2035  abort_rele:
2036         /*
2037          * Wait until after the current transaction is aborted to
2038          * release the inode.  This prevents recursive transactions
2039          * and deadlocks from xfs_inactive.
2040          */
2041         cancel_flags |= XFS_TRANS_ABORT;
2042         xfs_trans_cancel(tp, cancel_flags);
2043         IRELE(ip);
2044
2045         XFS_QM_DQRELE(mp, udqp);
2046         XFS_QM_DQRELE(mp, gdqp);
2047
2048         goto std_return;
2049 }
2050
2051 #ifdef DEBUG
2052 /*
2053  * Some counters to see if (and how often) we are hitting some deadlock
2054  * prevention code paths.
2055  */
2056
2057 int xfs_rm_locks;
2058 int xfs_rm_lock_delays;
2059 int xfs_rm_attempts;
2060 #endif
2061
2062 /*
2063  * The following routine will lock the inodes associated with the
2064  * directory and the named entry in the directory. The locks are
2065  * acquired in increasing inode number.
2066  *
2067  * If the entry is "..", then only the directory is locked. The
2068  * vnode ref count will still include that from the .. entry in
2069  * this case.
2070  *
2071  * There is a deadlock we need to worry about. If the locked directory is
2072  * in the AIL, it might be blocking up the log. The next inode we lock
2073  * could be already locked by another thread waiting for log space (e.g
2074  * a permanent log reservation with a long running transaction (see
2075  * xfs_itruncate_finish)). To solve this, we must check if the directory
2076  * is in the ail and use lock_nowait. If we can't lock, we need to
2077  * drop the inode lock on the directory and try again. xfs_iunlock will
2078  * potentially push the tail if we were holding up the log.
2079  */
2080 STATIC int
2081 xfs_lock_dir_and_entry(
2082         xfs_inode_t     *dp,
2083         xfs_inode_t     *ip)    /* inode of entry 'name' */
2084 {
2085         int             attempts;
2086         xfs_ino_t       e_inum;
2087         xfs_inode_t     *ips[2];
2088         xfs_log_item_t  *lp;
2089
2090 #ifdef DEBUG
2091         xfs_rm_locks++;
2092 #endif
2093         attempts = 0;
2094
2095 again:
2096         xfs_ilock(dp, XFS_ILOCK_EXCL | XFS_ILOCK_PARENT);
2097
2098         e_inum = ip->i_ino;
2099
2100         xfs_itrace_ref(ip);
2101
2102         /*
2103          * We want to lock in increasing inum. Since we've already
2104          * acquired the lock on the directory, we may need to release
2105          * if if the inum of the entry turns out to be less.
2106          */
2107         if (e_inum > dp->i_ino) {
2108                 /*
2109                  * We are already in the right order, so just
2110                  * lock on the inode of the entry.
2111                  * We need to use nowait if dp is in the AIL.
2112                  */
2113
2114                 lp = (xfs_log_item_t *)dp->i_itemp;
2115                 if (lp && (lp->li_flags & XFS_LI_IN_AIL)) {
2116                         if (!xfs_ilock_nowait(ip, XFS_ILOCK_EXCL)) {
2117                                 attempts++;
2118 #ifdef DEBUG
2119                                 xfs_rm_attempts++;
2120 #endif
2121
2122                                 /*
2123                                  * Unlock dp and try again.
2124                                  * xfs_iunlock will try to push the tail
2125                                  * if the inode is in the AIL.
2126                                  */
2127
2128                                 xfs_iunlock(dp, XFS_ILOCK_EXCL);
2129
2130                                 if ((attempts % 5) == 0) {
2131                                         delay(1); /* Don't just spin the CPU */
2132 #ifdef DEBUG
2133                                         xfs_rm_lock_delays++;
2134 #endif
2135                                 }
2136                                 goto again;
2137                         }
2138                 } else {
2139                         xfs_ilock(ip, XFS_ILOCK_EXCL);
2140                 }
2141         } else if (e_inum < dp->i_ino) {
2142                 xfs_iunlock(dp, XFS_ILOCK_EXCL);
2143
2144                 ips[0] = ip;
2145                 ips[1] = dp;
2146                 xfs_lock_inodes(ips, 2, 0, XFS_ILOCK_EXCL);
2147         }
2148         /* else  e_inum == dp->i_ino */
2149         /*     This can happen if we're asked to lock /x/..
2150          *     the entry is "..", which is also the parent directory.
2151          */
2152
2153         return 0;
2154 }
2155
2156 #ifdef DEBUG
2157 int xfs_locked_n;
2158 int xfs_small_retries;
2159 int xfs_middle_retries;
2160 int xfs_lots_retries;
2161 int xfs_lock_delays;
2162 #endif
2163
2164 /*
2165  * Bump the subclass so xfs_lock_inodes() acquires each lock with
2166  * a different value
2167  */
2168 static inline int
2169 xfs_lock_inumorder(int lock_mode, int subclass)
2170 {
2171         if (lock_mode & (XFS_IOLOCK_SHARED|XFS_IOLOCK_EXCL))
2172                 lock_mode |= (subclass + XFS_LOCK_INUMORDER) << XFS_IOLOCK_SHIFT;
2173         if (lock_mode & (XFS_ILOCK_SHARED|XFS_ILOCK_EXCL))
2174                 lock_mode |= (subclass + XFS_LOCK_INUMORDER) << XFS_ILOCK_SHIFT;
2175
2176         return lock_mode;
2177 }
2178
2179 /*
2180  * The following routine will lock n inodes in exclusive mode.
2181  * We assume the caller calls us with the inodes in i_ino order.
2182  *
2183  * We need to detect deadlock where an inode that we lock
2184  * is in the AIL and we start waiting for another inode that is locked
2185  * by a thread in a long running transaction (such as truncate). This can
2186  * result in deadlock since the long running trans might need to wait
2187  * for the inode we just locked in order to push the tail and free space
2188  * in the log.
2189  */
2190 void
2191 xfs_lock_inodes(
2192         xfs_inode_t     **ips,
2193         int             inodes,
2194         int             first_locked,
2195         uint            lock_mode)
2196 {
2197         int             attempts = 0, i, j, try_lock;
2198         xfs_log_item_t  *lp;
2199
2200         ASSERT(ips && (inodes >= 2)); /* we need at least two */
2201
2202         if (first_locked) {
2203                 try_lock = 1;
2204                 i = 1;
2205         } else {
2206                 try_lock = 0;
2207                 i = 0;
2208         }
2209
2210 again:
2211         for (; i < inodes; i++) {
2212                 ASSERT(ips[i]);
2213
2214                 if (i && (ips[i] == ips[i-1]))  /* Already locked */
2215                         continue;
2216
2217                 /*
2218                  * If try_lock is not set yet, make sure all locked inodes
2219                  * are not in the AIL.
2220                  * If any are, set try_lock to be used later.
2221                  */
2222
2223                 if (!try_lock) {
2224                         for (j = (i - 1); j >= 0 && !try_lock; j--) {
2225                                 lp = (xfs_log_item_t *)ips[j]->i_itemp;
2226                                 if (lp && (lp->li_flags & XFS_LI_IN_AIL)) {
2227                                         try_lock++;
2228                                 }
2229                         }
2230                 }
2231
2232                 /*
2233                  * If any of the previous locks we have locked is in the AIL,
2234                  * we must TRY to get the second and subsequent locks. If
2235                  * we can't get any, we must release all we have
2236                  * and try again.
2237                  */
2238
2239                 if (try_lock) {
2240                         /* try_lock must be 0 if i is 0. */
2241                         /*
2242                          * try_lock means we have an inode locked
2243                          * that is in the AIL.
2244                          */
2245                         ASSERT(i != 0);
2246                         if (!xfs_ilock_nowait(ips[i], xfs_lock_inumorder(lock_mode, i))) {
2247                                 attempts++;
2248
2249                                 /*
2250                                  * Unlock all previous guys and try again.
2251                                  * xfs_iunlock will try to push the tail
2252                                  * if the inode is in the AIL.
2253                                  */
2254
2255                                 for(j = i - 1; j >= 0; j--) {
2256
2257                                         /*
2258                                          * Check to see if we've already
2259                                          * unlocked this one.
2260                                          * Not the first one going back,
2261                                          * and the inode ptr is the same.
2262                                          */
2263                                         if ((j != (i - 1)) && ips[j] ==
2264                                                                 ips[j+1])
2265                                                 continue;
2266
2267                                         xfs_iunlock(ips[j], lock_mode);
2268                                 }
2269
2270                                 if ((attempts % 5) == 0) {
2271                                         delay(1); /* Don't just spin the CPU */
2272 #ifdef DEBUG
2273                                         xfs_lock_delays++;
2274 #endif
2275                                 }
2276                                 i = 0;
2277                                 try_lock = 0;
2278                                 goto again;
2279                         }
2280                 } else {
2281                         xfs_ilock(ips[i], xfs_lock_inumorder(lock_mode, i));
2282                 }
2283         }
2284
2285 #ifdef DEBUG
2286         if (attempts) {
2287                 if (attempts < 5) xfs_small_retries++;
2288                 else if (attempts < 100) xfs_middle_retries++;
2289                 else xfs_lots_retries++;
2290         } else {
2291                 xfs_locked_n++;
2292         }
2293 #endif
2294 }
2295
2296 #ifdef  DEBUG
2297 #define REMOVE_DEBUG_TRACE(x)   {remove_which_error_return = (x);}
2298 int remove_which_error_return = 0;
2299 #else /* ! DEBUG */
2300 #define REMOVE_DEBUG_TRACE(x)
2301 #endif  /* ! DEBUG */
2302
2303 int
2304 xfs_remove(
2305         xfs_inode_t             *dp,
2306         bhv_vname_t             *dentry)
2307 {
2308         bhv_vnode_t             *dir_vp = XFS_ITOV(dp);
2309         char                    *name = VNAME(dentry);
2310         xfs_mount_t             *mp = dp->i_mount;
2311         xfs_inode_t             *ip;
2312         xfs_trans_t             *tp = NULL;
2313         int                     error = 0;
2314         xfs_bmap_free_t         free_list;
2315         xfs_fsblock_t           first_block;
2316         int                     cancel_flags;
2317         int                     committed;
2318         int                     dm_di_mode = 0;
2319         int                     link_zero;
2320         uint                    resblks;
2321         int                     namelen;
2322
2323         xfs_itrace_entry(dp);
2324
2325         if (XFS_FORCED_SHUTDOWN(mp))
2326                 return XFS_ERROR(EIO);
2327
2328         namelen = VNAMELEN(dentry);
2329
2330         if (!xfs_get_dir_entry(dentry, &ip)) {
2331                 dm_di_mode = ip->i_d.di_mode;
2332                 IRELE(ip);
2333         }
2334
2335         if (DM_EVENT_ENABLED(dp, DM_EVENT_REMOVE)) {
2336                 error = XFS_SEND_NAMESP(mp, DM_EVENT_REMOVE, dir_vp,
2337                                         DM_RIGHT_NULL, NULL, DM_RIGHT_NULL,
2338                                         name, NULL, dm_di_mode, 0, 0);
2339                 if (error)
2340                         return error;
2341         }
2342
2343         /* From this point on, return through std_return */
2344         ip = NULL;
2345
2346         /*
2347          * We need to get a reference to ip before we get our log
2348          * reservation. The reason for this is that we cannot call
2349          * xfs_iget for an inode for which we do not have a reference
2350          * once we've acquired a log reservation. This is because the
2351          * inode we are trying to get might be in xfs_inactive going
2352          * for a log reservation. Since we'll have to wait for the
2353          * inactive code to complete before returning from xfs_iget,
2354          * we need to make sure that we don't have log space reserved
2355          * when we call xfs_iget.  Instead we get an unlocked reference
2356          * to the inode before getting our log reservation.
2357          */
2358         error = xfs_get_dir_entry(dentry, &ip);
2359         if (error) {
2360                 REMOVE_DEBUG_TRACE(__LINE__);
2361                 goto std_return;
2362         }
2363
2364         dm_di_mode = ip->i_d.di_mode;
2365
2366         xfs_itrace_entry(ip);
2367         xfs_itrace_ref(ip);
2368
2369         error = XFS_QM_DQATTACH(mp, dp, 0);
2370         if (!error && dp != ip)
2371                 error = XFS_QM_DQATTACH(mp, ip, 0);
2372         if (error) {
2373                 REMOVE_DEBUG_TRACE(__LINE__);
2374                 IRELE(ip);
2375                 goto std_return;
2376         }
2377
2378         tp = xfs_trans_alloc(mp, XFS_TRANS_REMOVE);
2379         cancel_flags = XFS_TRANS_RELEASE_LOG_RES;
2380         /*
2381          * We try to get the real space reservation first,
2382          * allowing for directory btree deletion(s) implying
2383          * possible bmap insert(s).  If we can't get the space
2384          * reservation then we use 0 instead, and avoid the bmap
2385          * btree insert(s) in the directory code by, if the bmap
2386          * insert tries to happen, instead trimming the LAST
2387          * block from the directory.
2388          */
2389         resblks = XFS_REMOVE_SPACE_RES(mp);
2390         error = xfs_trans_reserve(tp, resblks, XFS_REMOVE_LOG_RES(mp), 0,
2391                         XFS_TRANS_PERM_LOG_RES, XFS_REMOVE_LOG_COUNT);
2392         if (error == ENOSPC) {
2393                 resblks = 0;
2394                 error = xfs_trans_reserve(tp, 0, XFS_REMOVE_LOG_RES(mp), 0,
2395                                 XFS_TRANS_PERM_LOG_RES, XFS_REMOVE_LOG_COUNT);
2396         }
2397         if (error) {
2398                 ASSERT(error != ENOSPC);
2399                 REMOVE_DEBUG_TRACE(__LINE__);
2400                 xfs_trans_cancel(tp, 0);
2401                 IRELE(ip);
2402                 return error;
2403         }
2404
2405         error = xfs_lock_dir_and_entry(dp, ip);
2406         if (error) {
2407                 REMOVE_DEBUG_TRACE(__LINE__);
2408                 xfs_trans_cancel(tp, cancel_flags);
2409                 IRELE(ip);
2410                 goto std_return;
2411         }
2412
2413         /*
2414          * At this point, we've gotten both the directory and the entry
2415          * inodes locked.
2416          */
2417         xfs_trans_ijoin(tp, dp, XFS_ILOCK_EXCL);
2418         if (dp != ip) {
2419                 /*
2420                  * Increment vnode ref count only in this case since
2421                  * there's an extra vnode reference in the case where
2422                  * dp == ip.
2423                  */
2424                 IHOLD(dp);
2425                 xfs_trans_ijoin(tp, ip, XFS_ILOCK_EXCL);
2426         }
2427
2428         /*
2429          * Entry must exist since we did a lookup in xfs_lock_dir_and_entry.
2430          */
2431         XFS_BMAP_INIT(&free_list, &first_block);
2432         error = xfs_dir_removename(tp, dp, name, namelen, ip->i_ino,
2433                                         &first_block, &free_list, 0);
2434         if (error) {
2435                 ASSERT(error != ENOENT);
2436                 REMOVE_DEBUG_TRACE(__LINE__);
2437                 goto error1;
2438         }
2439         xfs_ichgtime(dp, XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG);
2440
2441         dp->i_gen++;
2442         xfs_trans_log_inode(tp, dp, XFS_ILOG_CORE);
2443
2444         error = xfs_droplink(tp, ip);
2445         if (error) {
2446                 REMOVE_DEBUG_TRACE(__LINE__);
2447                 goto error1;
2448         }
2449
2450         /* Determine if this is the last link while
2451          * we are in the transaction.
2452          */
2453         link_zero = (ip)->i_d.di_nlink==0;
2454
2455         /*
2456          * Take an extra ref on the inode so that it doesn't
2457          * go to xfs_inactive() from within the commit.
2458          */
2459         IHOLD(ip);
2460
2461         /*
2462          * If this is a synchronous mount, make sure that the
2463          * remove transaction goes to disk before returning to
2464          * the user.
2465          */
2466         if (mp->m_flags & (XFS_MOUNT_WSYNC|XFS_MOUNT_DIRSYNC)) {
2467                 xfs_trans_set_sync(tp);
2468         }
2469
2470         error = xfs_bmap_finish(&tp, &free_list, &committed);
2471         if (error) {
2472                 REMOVE_DEBUG_TRACE(__LINE__);
2473                 goto error_rele;
2474         }
2475
2476         error = xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
2477         if (error) {
2478                 IRELE(ip);
2479                 goto std_return;
2480         }
2481
2482         /*
2483          * Before we drop our extra reference to the inode, purge it
2484          * from the refcache if it is there.  By waiting until afterwards
2485          * to do the IRELE, we ensure that we won't go inactive in the
2486          * xfs_refcache_purge_ip routine (although that would be OK).
2487          */
2488         xfs_refcache_purge_ip(ip);
2489
2490         /*
2491          * If we are using filestreams, kill the stream association.
2492          * If the file is still open it may get a new one but that
2493          * will get killed on last close in xfs_close() so we don't
2494          * have to worry about that.
2495          */
2496         if (link_zero && xfs_inode_is_filestream(ip))
2497                 xfs_filestream_deassociate(ip);
2498
2499         xfs_itrace_exit(ip);
2500         IRELE(ip);
2501
2502 /*      Fall through to std_return with error = 0 */
2503  std_return:
2504         if (DM_EVENT_ENABLED(dp, DM_EVENT_POSTREMOVE)) {
2505                 (void) XFS_SEND_NAMESP(mp, DM_EVENT_POSTREMOVE,
2506                                 dir_vp, DM_RIGHT_NULL,
2507                                 NULL, DM_RIGHT_NULL,
2508                                 name, NULL, dm_di_mode, error, 0);
2509         }
2510         return error;
2511
2512  error1:
2513         xfs_bmap_cancel(&free_list);
2514         cancel_flags |= XFS_TRANS_ABORT;
2515         xfs_trans_cancel(tp, cancel_flags);
2516         goto std_return;
2517
2518  error_rele:
2519         /*
2520          * In this case make sure to not release the inode until after
2521          * the current transaction is aborted.  Releasing it beforehand
2522          * can cause us to go to xfs_inactive and start a recursive
2523          * transaction which can easily deadlock with the current one.
2524          */
2525         xfs_bmap_cancel(&free_list);
2526         cancel_flags |= XFS_TRANS_ABORT;
2527         xfs_trans_cancel(tp, cancel_flags);
2528
2529         /*
2530          * Before we drop our extra reference to the inode, purge it
2531          * from the refcache if it is there.  By waiting until afterwards
2532          * to do the IRELE, we ensure that we won't go inactive in the
2533          * xfs_refcache_purge_ip routine (although that would be OK).
2534          */
2535         xfs_refcache_purge_ip(ip);
2536
2537         IRELE(ip);
2538
2539         goto std_return;
2540 }
2541
2542 int
2543 xfs_link(
2544         xfs_inode_t             *tdp,
2545         bhv_vnode_t             *src_vp,
2546         bhv_vname_t             *dentry)
2547 {
2548         bhv_vnode_t             *target_dir_vp = XFS_ITOV(tdp);
2549         xfs_mount_t             *mp = tdp->i_mount;
2550         xfs_inode_t             *sip = xfs_vtoi(src_vp);
2551         xfs_trans_t             *tp;
2552         xfs_inode_t             *ips[2];
2553         int                     error;
2554         xfs_bmap_free_t         free_list;
2555         xfs_fsblock_t           first_block;
2556         int                     cancel_flags;
2557         int                     committed;
2558         int                     resblks;
2559         char                    *target_name = VNAME(dentry);
2560         int                     target_namelen;
2561
2562         xfs_itrace_entry(tdp);
2563         xfs_itrace_entry(xfs_vtoi(src_vp));
2564
2565         target_namelen = VNAMELEN(dentry);
2566         ASSERT(!VN_ISDIR(src_vp));
2567
2568         if (XFS_FORCED_SHUTDOWN(mp))
2569                 return XFS_ERROR(EIO);
2570
2571         if (DM_EVENT_ENABLED(tdp, DM_EVENT_LINK)) {
2572                 error = XFS_SEND_NAMESP(mp, DM_EVENT_LINK,
2573                                         target_dir_vp, DM_RIGHT_NULL,
2574                                         src_vp, DM_RIGHT_NULL,
2575                                         target_name, NULL, 0, 0, 0);
2576                 if (error)
2577                         return error;
2578         }
2579
2580         /* Return through std_return after this point. */
2581
2582         error = XFS_QM_DQATTACH(mp, sip, 0);
2583         if (!error && sip != tdp)
2584                 error = XFS_QM_DQATTACH(mp, tdp, 0);
2585         if (error)
2586                 goto std_return;
2587
2588         tp = xfs_trans_alloc(mp, XFS_TRANS_LINK);
2589         cancel_flags = XFS_TRANS_RELEASE_LOG_RES;
2590         resblks = XFS_LINK_SPACE_RES(mp, target_namelen);
2591         error = xfs_trans_reserve(tp, resblks, XFS_LINK_LOG_RES(mp), 0,
2592                         XFS_TRANS_PERM_LOG_RES, XFS_LINK_LOG_COUNT);
2593         if (error == ENOSPC) {
2594                 resblks = 0;
2595                 error = xfs_trans_reserve(tp, 0, XFS_LINK_LOG_RES(mp), 0,
2596                                 XFS_TRANS_PERM_LOG_RES, XFS_LINK_LOG_COUNT);
2597         }
2598         if (error) {
2599                 cancel_flags = 0;
2600                 goto error_return;
2601         }
2602
2603         if (sip->i_ino < tdp->i_ino) {
2604                 ips[0] = sip;
2605                 ips[1] = tdp;
2606         } else {
2607                 ips[0] = tdp;
2608                 ips[1] = sip;
2609         }
2610
2611         xfs_lock_inodes(ips, 2, 0, XFS_ILOCK_EXCL);
2612
2613         /*
2614          * Increment vnode ref counts since xfs_trans_commit &
2615          * xfs_trans_cancel will both unlock the inodes and
2616          * decrement the associated ref counts.
2617          */
2618         VN_HOLD(src_vp);
2619         VN_HOLD(target_dir_vp);
2620         xfs_trans_ijoin(tp, sip, XFS_ILOCK_EXCL);
2621         xfs_trans_ijoin(tp, tdp, XFS_ILOCK_EXCL);
2622
2623         /*
2624          * If the source has too many links, we can't make any more to it.
2625          */
2626         if (sip->i_d.di_nlink >= XFS_MAXLINK) {
2627                 error = XFS_ERROR(EMLINK);
2628                 goto error_return;
2629         }
2630
2631         /*
2632          * If we are using project inheritance, we only allow hard link
2633          * creation in our tree when the project IDs are the same; else
2634          * the tree quota mechanism could be circumvented.
2635          */
2636         if (unlikely((tdp->i_d.di_flags & XFS_DIFLAG_PROJINHERIT) &&
2637                      (tdp->i_d.di_projid != sip->i_d.di_projid))) {
2638                 error = XFS_ERROR(EXDEV);
2639                 goto error_return;
2640         }
2641
2642         if (resblks == 0 &&
2643             (error = xfs_dir_canenter(tp, tdp, target_name, target_namelen)))
2644                 goto error_return;
2645
2646         XFS_BMAP_INIT(&free_list, &first_block);
2647
2648         error = xfs_dir_createname(tp, tdp, target_name, target_namelen,
2649                                    sip->i_ino, &first_block, &free_list,
2650                                    resblks);
2651         if (error)
2652                 goto abort_return;
2653         xfs_ichgtime(tdp, XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG);
2654         tdp->i_gen++;
2655         xfs_trans_log_inode(tp, tdp, XFS_ILOG_CORE);
2656
2657         error = xfs_bumplink(tp, sip);
2658         if (error)
2659                 goto abort_return;
2660
2661         /*
2662          * If this is a synchronous mount, make sure that the
2663          * link transaction goes to disk before returning to
2664          * the user.
2665          */
2666         if (mp->m_flags & (XFS_MOUNT_WSYNC|XFS_MOUNT_DIRSYNC)) {
2667                 xfs_trans_set_sync(tp);
2668         }
2669
2670         error = xfs_bmap_finish (&tp, &free_list, &committed);
2671         if (error) {
2672                 xfs_bmap_cancel(&free_list);
2673                 goto abort_return;
2674         }
2675
2676         error = xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
2677         if (error)
2678                 goto std_return;
2679
2680         /* Fall through to std_return with error = 0. */
2681 std_return:
2682         if (DM_EVENT_ENABLED(sip, DM_EVENT_POSTLINK)) {
2683                 (void) XFS_SEND_NAMESP(mp, DM_EVENT_POSTLINK,
2684                                 target_dir_vp, DM_RIGHT_NULL,
2685                                 src_vp, DM_RIGHT_NULL,
2686                                 target_name, NULL, 0, error, 0);
2687         }
2688         return error;
2689
2690  abort_return:
2691         cancel_flags |= XFS_TRANS_ABORT;
2692         /* FALLTHROUGH */
2693
2694  error_return:
2695         xfs_trans_cancel(tp, cancel_flags);
2696         goto std_return;
2697 }
2698
2699
2700 int
2701 xfs_mkdir(
2702         xfs_inode_t             *dp,
2703         bhv_vname_t             *dentry,
2704         mode_t                  mode,
2705         bhv_vnode_t             **vpp,
2706         cred_t                  *credp)
2707 {
2708         bhv_vnode_t             *dir_vp = XFS_ITOV(dp);
2709         char                    *dir_name = VNAME(dentry);
2710         int                     dir_namelen = VNAMELEN(dentry);
2711         xfs_mount_t             *mp = dp->i_mount;
2712         xfs_inode_t             *cdp;   /* inode of created dir */
2713         bhv_vnode_t             *cvp;   /* vnode of created dir */
2714         xfs_trans_t             *tp;
2715         int                     cancel_flags;
2716         int                     error;
2717         int                     committed;
2718         xfs_bmap_free_t         free_list;
2719         xfs_fsblock_t           first_block;
2720         boolean_t               unlock_dp_on_error = B_FALSE;
2721         boolean_t               created = B_FALSE;
2722         int                     dm_event_sent = 0;
2723         xfs_prid_t              prid;
2724         struct xfs_dquot        *udqp, *gdqp;
2725         uint                    resblks;
2726
2727         if (XFS_FORCED_SHUTDOWN(mp))
2728                 return XFS_ERROR(EIO);
2729
2730         tp = NULL;
2731
2732         if (DM_EVENT_ENABLED(dp, DM_EVENT_CREATE)) {
2733                 error = XFS_SEND_NAMESP(mp, DM_EVENT_CREATE,
2734                                         dir_vp, DM_RIGHT_NULL, NULL,
2735                                         DM_RIGHT_NULL, dir_name, NULL,
2736                                         mode, 0, 0);
2737                 if (error)
2738                         return error;
2739                 dm_event_sent = 1;
2740         }
2741
2742         /* Return through std_return after this point. */
2743
2744         xfs_itrace_entry(dp);
2745
2746         mp = dp->i_mount;
2747         udqp = gdqp = NULL;
2748         if (dp->i_d.di_flags & XFS_DIFLAG_PROJINHERIT)
2749                 prid = dp->i_d.di_projid;
2750         else
2751                 prid = (xfs_prid_t)dfltprid;
2752
2753         /*
2754          * Make sure that we have allocated dquot(s) on disk.
2755          */
2756         error = XFS_QM_DQVOPALLOC(mp, dp,
2757                         current_fsuid(credp), current_fsgid(credp), prid,
2758                         XFS_QMOPT_QUOTALL | XFS_QMOPT_INHERIT, &udqp, &gdqp);
2759         if (error)
2760                 goto std_return;
2761
2762         tp = xfs_trans_alloc(mp, XFS_TRANS_MKDIR);
2763         cancel_flags = XFS_TRANS_RELEASE_LOG_RES;
2764         resblks = XFS_MKDIR_SPACE_RES(mp, dir_namelen);
2765         error = xfs_trans_reserve(tp, resblks, XFS_MKDIR_LOG_RES(mp), 0,
2766                                   XFS_TRANS_PERM_LOG_RES, XFS_MKDIR_LOG_COUNT);
2767         if (error == ENOSPC) {
2768                 resblks = 0;
2769                 error = xfs_trans_reserve(tp, 0, XFS_MKDIR_LOG_RES(mp), 0,
2770                                           XFS_TRANS_PERM_LOG_RES,
2771                                           XFS_MKDIR_LOG_COUNT);
2772         }
2773         if (error) {
2774                 cancel_flags = 0;
2775                 goto error_return;
2776         }
2777
2778         xfs_ilock(dp, XFS_ILOCK_EXCL | XFS_ILOCK_PARENT);
2779         unlock_dp_on_error = B_TRUE;
2780
2781         /*
2782          * Check for directory link count overflow.
2783          */
2784         if (dp->i_d.di_nlink >= XFS_MAXLINK) {
2785                 error = XFS_ERROR(EMLINK);
2786                 goto error_return;
2787         }
2788
2789         /*
2790          * Reserve disk quota and the inode.
2791          */
2792         error = XFS_TRANS_RESERVE_QUOTA(mp, tp, udqp, gdqp, resblks, 1, 0);
2793         if (error)
2794                 goto error_return;
2795
2796         if (resblks == 0 &&
2797             (error = xfs_dir_canenter(tp, dp, dir_name, dir_namelen)))
2798                 goto error_return;
2799         /*
2800          * create the directory inode.
2801          */
2802         error = xfs_dir_ialloc(&tp, dp, mode, 2,
2803                         0, credp, prid, resblks > 0,
2804                 &cdp, NULL);
2805         if (error) {
2806                 if (error == ENOSPC)
2807                         goto error_return;
2808                 goto abort_return;
2809         }
2810         xfs_itrace_ref(cdp);
2811
2812         /*
2813          * Now we add the directory inode to the transaction.
2814          * We waited until now since xfs_dir_ialloc might start
2815          * a new transaction.  Had we joined the transaction
2816          * earlier, the locks might have gotten released. An error
2817          * from here on will result in the transaction cancel
2818          * unlocking dp so don't do it explicitly in the error path.
2819          */
2820         VN_HOLD(dir_vp);
2821         xfs_trans_ijoin(tp, dp, XFS_ILOCK_EXCL);
2822         unlock_dp_on_error = B_FALSE;
2823
2824         XFS_BMAP_INIT(&free_list, &first_block);
2825
2826         error = xfs_dir_createname(tp, dp, dir_name, dir_namelen, cdp->i_ino,
2827                                    &first_block, &free_list, resblks ?
2828                                    resblks - XFS_IALLOC_SPACE_RES(mp) : 0);
2829         if (error) {
2830                 ASSERT(error != ENOSPC);
2831                 goto error1;
2832         }
2833         xfs_ichgtime(dp, XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG);
2834
2835         /*
2836          * Bump the in memory version number of the parent directory
2837          * so that other processes accessing it will recognize that
2838          * the directory has changed.
2839          */
2840         dp->i_gen++;
2841
2842         error = xfs_dir_init(tp, cdp, dp);
2843         if (error)
2844                 goto error2;
2845
2846         cdp->i_gen = 1;
2847         error = xfs_bumplink(tp, dp);
2848         if (error)
2849                 goto error2;
2850
2851         cvp = XFS_ITOV(cdp);
2852
2853         created = B_TRUE;
2854
2855         *vpp = cvp;
2856         IHOLD(cdp);
2857
2858         /*
2859          * Attach the dquots to the new inode and modify the icount incore.
2860          */
2861         XFS_QM_DQVOPCREATE(mp, tp, cdp, udqp, gdqp);
2862
2863         /*
2864          * If this is a synchronous mount, make sure that the
2865          * mkdir transaction goes to disk before returning to
2866          * the user.
2867          */
2868         if (mp->m_flags & (XFS_MOUNT_WSYNC|XFS_MOUNT_DIRSYNC)) {
2869                 xfs_trans_set_sync(tp);
2870         }
2871
2872         error = xfs_bmap_finish(&tp, &free_list, &committed);
2873         if (error) {
2874                 IRELE(cdp);
2875                 goto error2;
2876         }
2877
2878         error = xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
2879         XFS_QM_DQRELE(mp, udqp);
2880         XFS_QM_DQRELE(mp, gdqp);
2881         if (error) {
2882                 IRELE(cdp);
2883         }
2884
2885         /* Fall through to std_return with error = 0 or errno from
2886          * xfs_trans_commit. */
2887
2888 std_return:
2889         if ((created || (error != 0 && dm_event_sent != 0)) &&
2890             DM_EVENT_ENABLED(dp, DM_EVENT_POSTCREATE)) {
2891                 (void) XFS_SEND_NAMESP(mp, DM_EVENT_POSTCREATE,
2892                                         dir_vp, DM_RIGHT_NULL,
2893                                         created ? XFS_ITOV(cdp):NULL,
2894                                         DM_RIGHT_NULL,
2895                                         dir_name, NULL,
2896                                         mode, error, 0);
2897         }
2898         return error;
2899
2900  error2:
2901  error1:
2902         xfs_bmap_cancel(&free_list);
2903  abort_return:
2904         cancel_flags |= XFS_TRANS_ABORT;
2905  error_return:
2906         xfs_trans_cancel(tp, cancel_flags);
2907         XFS_QM_DQRELE(mp, udqp);
2908         XFS_QM_DQRELE(mp, gdqp);
2909
2910         if (unlock_dp_on_error)
2911                 xfs_iunlock(dp, XFS_ILOCK_EXCL);
2912
2913         goto std_return;
2914 }
2915
2916 int
2917 xfs_rmdir(
2918         xfs_inode_t             *dp,
2919         bhv_vname_t             *dentry)
2920 {
2921         bhv_vnode_t             *dir_vp = XFS_ITOV(dp);
2922         char                    *name = VNAME(dentry);
2923         int                     namelen = VNAMELEN(dentry);
2924         xfs_mount_t             *mp = dp->i_mount;
2925         xfs_inode_t             *cdp;   /* child directory */
2926         xfs_trans_t             *tp;
2927         int                     error;
2928         xfs_bmap_free_t         free_list;
2929         xfs_fsblock_t           first_block;
2930         int                     cancel_flags;
2931         int                     committed;
2932         int                     dm_di_mode = S_IFDIR;
2933         int                     last_cdp_link;
2934         uint                    resblks;
2935
2936         xfs_itrace_entry(dp);
2937
2938         if (XFS_FORCED_SHUTDOWN(mp))
2939                 return XFS_ERROR(EIO);
2940
2941         if (!xfs_get_dir_entry(dentry, &cdp)) {
2942                 dm_di_mode = cdp->i_d.di_mode;
2943                 IRELE(cdp);
2944         }
2945
2946         if (DM_EVENT_ENABLED(dp, DM_EVENT_REMOVE)) {
2947                 error = XFS_SEND_NAMESP(mp, DM_EVENT_REMOVE,
2948                                         dir_vp, DM_RIGHT_NULL,
2949                                         NULL, DM_RIGHT_NULL,
2950                                         name, NULL, dm_di_mode, 0, 0);
2951                 if (error)
2952                         return XFS_ERROR(error);
2953         }
2954
2955         /* Return through std_return after this point. */
2956
2957         cdp = NULL;
2958
2959         /*
2960          * We need to get a reference to cdp before we get our log
2961          * reservation.  The reason for this is that we cannot call
2962          * xfs_iget for an inode for which we do not have a reference
2963          * once we've acquired a log reservation.  This is because the
2964          * inode we are trying to get might be in xfs_inactive going
2965          * for a log reservation.  Since we'll have to wait for the
2966          * inactive code to complete before returning from xfs_iget,
2967          * we need to make sure that we don't have log space reserved
2968          * when we call xfs_iget.  Instead we get an unlocked reference
2969          * to the inode before getting our log reservation.
2970          */
2971         error = xfs_get_dir_entry(dentry, &cdp);
2972         if (error) {
2973                 REMOVE_DEBUG_TRACE(__LINE__);
2974                 goto std_return;
2975         }
2976         mp = dp->i_mount;
2977         dm_di_mode = cdp->i_d.di_mode;
2978
2979         /*
2980          * Get the dquots for the inodes.
2981          */
2982         error = XFS_QM_DQATTACH(mp, dp, 0);
2983         if (!error && dp != cdp)
2984                 error = XFS_QM_DQATTACH(mp, cdp, 0);
2985         if (error) {
2986                 IRELE(cdp);
2987                 REMOVE_DEBUG_TRACE(__LINE__);
2988                 goto std_return;
2989         }
2990
2991         tp = xfs_trans_alloc(mp, XFS_TRANS_RMDIR);
2992         cancel_flags = XFS_TRANS_RELEASE_LOG_RES;
2993         /*
2994          * We try to get the real space reservation first,
2995          * allowing for directory btree deletion(s) implying
2996          * possible bmap insert(s).  If we can't get the space
2997          * reservation then we use 0 instead, and avoid the bmap
2998          * btree insert(s) in the directory code by, if the bmap
2999          * insert tries to happen, instead trimming the LAST
3000          * block from the directory.
3001          */
3002         resblks = XFS_REMOVE_SPACE_RES(mp);
3003         error = xfs_trans_reserve(tp, resblks, XFS_REMOVE_LOG_RES(mp), 0,
3004                         XFS_TRANS_PERM_LOG_RES, XFS_DEFAULT_LOG_COUNT);
3005         if (error == ENOSPC) {
3006                 resblks = 0;
3007                 error = xfs_trans_reserve(tp, 0, XFS_REMOVE_LOG_RES(mp), 0,
3008                                 XFS_TRANS_PERM_LOG_RES, XFS_DEFAULT_LOG_COUNT);
3009         }
3010         if (error) {
3011                 ASSERT(error != ENOSPC);
3012                 cancel_flags = 0;
3013                 IRELE(cdp);
3014                 goto error_return;
3015         }
3016         XFS_BMAP_INIT(&free_list, &first_block);
3017
3018         /*
3019          * Now lock the child directory inode and the parent directory
3020          * inode in the proper order.  This will take care of validating
3021          * that the directory entry for the child directory inode has
3022          * not changed while we were obtaining a log reservation.
3023          */
3024         error = xfs_lock_dir_and_entry(dp, cdp);
3025         if (error) {
3026                 xfs_trans_cancel(tp, cancel_flags);
3027                 IRELE(cdp);
3028                 goto std_return;
3029         }
3030
3031         xfs_trans_ijoin(tp, dp, XFS_ILOCK_EXCL);
3032         if (dp != cdp) {
3033                 /*
3034                  * Only increment the parent directory vnode count if
3035                  * we didn't bump it in looking up cdp.  The only time
3036                  * we don't bump it is when we're looking up ".".
3037                  */
3038                 VN_HOLD(dir_vp);
3039         }
3040
3041         xfs_itrace_ref(cdp);
3042         xfs_trans_ijoin(tp, cdp, XFS_ILOCK_EXCL);
3043
3044         ASSERT(cdp->i_d.di_nlink >= 2);
3045         if (cdp->i_d.di_nlink != 2) {
3046                 error = XFS_ERROR(ENOTEMPTY);
3047                 goto error_return;
3048         }
3049         if (!xfs_dir_isempty(cdp)) {
3050                 error = XFS_ERROR(ENOTEMPTY);
3051                 goto error_return;
3052         }
3053
3054         error = xfs_dir_removename(tp, dp, name, namelen, cdp->i_ino,
3055                                         &first_block, &free_list, resblks);
3056         if (error)
3057                 goto error1;
3058
3059         xfs_ichgtime(dp, XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG);
3060
3061         /*
3062          * Bump the in memory generation count on the parent
3063          * directory so that other can know that it has changed.
3064          */
3065         dp->i_gen++;
3066
3067         /*
3068          * Drop the link from cdp's "..".
3069          */
3070         error = xfs_droplink(tp, dp);
3071         if (error) {
3072                 goto error1;
3073         }
3074
3075         /*
3076          * Drop the link from dp to cdp.
3077          */
3078         error = xfs_droplink(tp, cdp);
3079         if (error) {
3080                 goto error1;
3081         }
3082
3083         /*
3084          * Drop the "." link from cdp to self.
3085          */
3086         error = xfs_droplink(tp, cdp);
3087         if (error) {
3088                 goto error1;
3089         }
3090
3091         /* Determine these before committing transaction */
3092         last_cdp_link = (cdp)->i_d.di_nlink==0;
3093
3094         /*
3095          * Take an extra ref on the child vnode so that it
3096          * does not go to xfs_inactive() from within the commit.
3097          */
3098         IHOLD(cdp);
3099
3100         /*
3101          * If this is a synchronous mount, make sure that the
3102          * rmdir transaction goes to disk before returning to
3103          * the user.
3104          */
3105         if (mp->m_flags & (XFS_MOUNT_WSYNC|XFS_MOUNT_DIRSYNC)) {
3106                 xfs_trans_set_sync(tp);
3107         }
3108
3109         error = xfs_bmap_finish (&tp, &free_list, &committed);
3110         if (error) {
3111                 xfs_bmap_cancel(&free_list);
3112                 xfs_trans_cancel(tp, (XFS_TRANS_RELEASE_LOG_RES |
3113                                  XFS_TRANS_ABORT));
3114                 IRELE(cdp);
3115                 goto std_return;
3116         }
3117
3118         error = xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
3119         if (error) {
3120                 IRELE(cdp);
3121                 goto std_return;
3122         }
3123
3124
3125         IRELE(cdp);
3126
3127         /* Fall through to std_return with error = 0 or the errno
3128          * from xfs_trans_commit. */
3129  std_return:
3130         if (DM_EVENT_ENABLED(dp, DM_EVENT_POSTREMOVE)) {
3131                 (void) XFS_SEND_NAMESP(mp, DM_EVENT_POSTREMOVE,
3132                                         dir_vp, DM_RIGHT_NULL,
3133                                         NULL, DM_RIGHT_NULL,
3134                                         name, NULL, dm_di_mode,
3135                                         error, 0);
3136         }
3137         return error;
3138
3139  error1:
3140         xfs_bmap_cancel(&free_list);
3141         cancel_flags |= XFS_TRANS_ABORT;
3142         /* FALLTHROUGH */
3143
3144  error_return:
3145         xfs_trans_cancel(tp, cancel_flags);
3146         goto std_return;
3147 }
3148
3149 int
3150 xfs_symlink(
3151         xfs_inode_t             *dp,
3152         bhv_vname_t             *dentry,
3153         char                    *target_path,
3154         mode_t                  mode,
3155         bhv_vnode_t             **vpp,
3156         cred_t                  *credp)
3157 {
3158         bhv_vnode_t             *dir_vp = XFS_ITOV(dp);
3159         xfs_mount_t             *mp = dp->i_mount;
3160         xfs_trans_t             *tp;
3161         xfs_inode_t             *ip;
3162         int                     error;
3163         int                     pathlen;
3164         xfs_bmap_free_t         free_list;
3165         xfs_fsblock_t           first_block;
3166         boolean_t               unlock_dp_on_error = B_FALSE;
3167         uint                    cancel_flags;
3168         int                     committed;
3169         xfs_fileoff_t           first_fsb;
3170         xfs_filblks_t           fs_blocks;
3171         int                     nmaps;
3172         xfs_bmbt_irec_t         mval[SYMLINK_MAPS];
3173         xfs_daddr_t             d;
3174         char                    *cur_chunk;
3175         int                     byte_cnt;
3176         int                     n;
3177         xfs_buf_t               *bp;
3178         xfs_prid_t              prid;
3179         struct xfs_dquot        *udqp, *gdqp;
3180         uint                    resblks;
3181         char                    *link_name = VNAME(dentry);
3182         int                     link_namelen;
3183
3184         *vpp = NULL;
3185         error = 0;
3186         ip = NULL;
3187         tp = NULL;
3188
3189         xfs_itrace_entry(dp);
3190
3191         if (XFS_FORCED_SHUTDOWN(mp))
3192                 return XFS_ERROR(EIO);
3193
3194         link_namelen = VNAMELEN(dentry);
3195
3196         /*
3197          * Check component lengths of the target path name.
3198          */
3199         pathlen = strlen(target_path);
3200         if (pathlen >= MAXPATHLEN)      /* total string too long */
3201                 return XFS_ERROR(ENAMETOOLONG);
3202         if (pathlen >= MAXNAMELEN) {    /* is any component too long? */
3203                 int len, total;
3204                 char *path;
3205
3206                 for (total = 0, path = target_path; total < pathlen;) {
3207                         /*
3208                          * Skip any slashes.
3209                          */
3210                         while(*path == '/') {
3211                                 total++;
3212                                 path++;
3213                         }
3214
3215                         /*
3216                          * Count up to the next slash or end of path.
3217                          * Error out if the component is bigger than MAXNAMELEN.
3218                          */
3219                         for(len = 0; *path != '/' && total < pathlen;total++, path++) {
3220                                 if (++len >= MAXNAMELEN) {
3221                                         error = ENAMETOOLONG;
3222                                         return error;
3223                                 }
3224                         }
3225                 }
3226         }
3227
3228         if (DM_EVENT_ENABLED(dp, DM_EVENT_SYMLINK)) {
3229                 error = XFS_SEND_NAMESP(mp, DM_EVENT_SYMLINK, dir_vp,
3230                                         DM_RIGHT_NULL, NULL, DM_RIGHT_NULL,
3231                                         link_name, target_path, 0, 0, 0);
3232                 if (error)
3233                         return error;
3234         }
3235
3236         /* Return through std_return after this point. */
3237
3238         udqp = gdqp = NULL;
3239         if (dp->i_d.di_flags & XFS_DIFLAG_PROJINHERIT)
3240                 prid = dp->i_d.di_projid;
3241         else
3242                 prid = (xfs_prid_t)dfltprid;
3243
3244         /*
3245          * Make sure that we have allocated dquot(s) on disk.
3246          */
3247         error = XFS_QM_DQVOPALLOC(mp, dp,
3248                         current_fsuid(credp), current_fsgid(credp), prid,
3249                         XFS_QMOPT_QUOTALL | XFS_QMOPT_INHERIT, &udqp, &gdqp);
3250         if (error)
3251                 goto std_return;
3252
3253         tp = xfs_trans_alloc(mp, XFS_TRANS_SYMLINK);
3254         cancel_flags = XFS_TRANS_RELEASE_LOG_RES;
3255         /*
3256          * The symlink will fit into the inode data fork?
3257          * There can't be any attributes so we get the whole variable part.
3258          */
3259         if (pathlen <= XFS_LITINO(mp))
3260                 fs_blocks = 0;
3261         else
3262                 fs_blocks = XFS_B_TO_FSB(mp, pathlen);
3263         resblks = XFS_SYMLINK_SPACE_RES(mp, link_namelen, fs_blocks);
3264         error = xfs_trans_reserve(tp, resblks, XFS_SYMLINK_LOG_RES(mp), 0,
3265                         XFS_TRANS_PERM_LOG_RES, XFS_SYMLINK_LOG_COUNT);
3266         if (error == ENOSPC && fs_blocks == 0) {
3267                 resblks = 0;
3268                 error = xfs_trans_reserve(tp, 0, XFS_SYMLINK_LOG_RES(mp), 0,
3269                                 XFS_TRANS_PERM_LOG_RES, XFS_SYMLINK_LOG_COUNT);
3270         }
3271         if (error) {
3272                 cancel_flags = 0;
3273                 goto error_return;
3274         }
3275
3276         xfs_ilock(dp, XFS_ILOCK_EXCL | XFS_ILOCK_PARENT);
3277         unlock_dp_on_error = B_TRUE;
3278
3279         /*
3280          * Check whether the directory allows new symlinks or not.
3281          */
3282         if (dp->i_d.di_flags & XFS_DIFLAG_NOSYMLINKS) {
3283                 error = XFS_ERROR(EPERM);
3284                 goto error_return;
3285         }
3286
3287         /*
3288          * Reserve disk quota : blocks and inode.
3289          */
3290         error = XFS_TRANS_RESERVE_QUOTA(mp, tp, udqp, gdqp, resblks, 1, 0);
3291         if (error)
3292                 goto error_return;
3293
3294         /*
3295          * Check for ability to enter directory entry, if no space reserved.
3296          */
3297         if (resblks == 0 &&
3298             (error = xfs_dir_canenter(tp, dp, link_name, link_namelen)))
3299                 goto error_return;
3300         /*
3301          * Initialize the bmap freelist prior to calling either
3302          * bmapi or the directory create code.
3303          */
3304         XFS_BMAP_INIT(&free_list, &first_block);
3305
3306         /*
3307          * Allocate an inode for the symlink.
3308          */
3309         error = xfs_dir_ialloc(&tp, dp, S_IFLNK | (mode & ~S_IFMT),
3310                                1, 0, credp, prid, resblks > 0, &ip, NULL);
3311         if (error) {
3312                 if (error == ENOSPC)
3313                         goto error_return;
3314                 goto error1;
3315         }
3316         xfs_itrace_ref(ip);
3317
3318         /*
3319          * An error after we've joined dp to the transaction will result in the
3320          * transaction cancel unlocking dp so don't do it explicitly in the
3321          * error path.
3322          */
3323         VN_HOLD(dir_vp);
3324         xfs_trans_ijoin(tp, dp, XFS_ILOCK_EXCL);
3325         unlock_dp_on_error = B_FALSE;
3326
3327         /*
3328          * Also attach the dquot(s) to it, if applicable.
3329          */
3330         XFS_QM_DQVOPCREATE(mp, tp, ip, udqp, gdqp);
3331
3332         if (resblks)
3333                 resblks -= XFS_IALLOC_SPACE_RES(mp);
3334         /*
3335          * If the symlink will fit into the inode, write it inline.
3336          */
3337         if (pathlen <= XFS_IFORK_DSIZE(ip)) {
3338                 xfs_idata_realloc(ip, pathlen, XFS_DATA_FORK);
3339                 memcpy(ip->i_df.if_u1.if_data, target_path, pathlen);
3340                 ip->i_d.di_size = pathlen;
3341
3342                 /*
3343                  * The inode was initially created in extent format.
3344                  */
3345                 ip->i_df.if_flags &= ~(XFS_IFEXTENTS | XFS_IFBROOT);
3346                 ip->i_df.if_flags |= XFS_IFINLINE;
3347
3348                 ip->i_d.di_format = XFS_DINODE_FMT_LOCAL;
3349                 xfs_trans_log_inode(tp, ip, XFS_ILOG_DDATA | XFS_ILOG_CORE);
3350
3351         } else {
3352                 first_fsb = 0;
3353                 nmaps = SYMLINK_MAPS;
3354
3355                 error = xfs_bmapi(tp, ip, first_fsb, fs_blocks,
3356                                   XFS_BMAPI_WRITE | XFS_BMAPI_METADATA,
3357                                   &first_block, resblks, mval, &nmaps,
3358                                   &free_list, NULL);
3359                 if (error) {
3360                         goto error1;
3361                 }
3362
3363                 if (resblks)
3364                         resblks -= fs_blocks;
3365                 ip->i_d.di_size = pathlen;
3366                 xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
3367
3368                 cur_chunk = target_path;
3369                 for (n = 0; n < nmaps; n++) {
3370                         d = XFS_FSB_TO_DADDR(mp, mval[n].br_startblock);
3371                         byte_cnt = XFS_FSB_TO_B(mp, mval[n].br_blockcount);
3372                         bp = xfs_trans_get_buf(tp, mp->m_ddev_targp, d,
3373                                                BTOBB(byte_cnt), 0);
3374                         ASSERT(bp && !XFS_BUF_GETERROR(bp));
3375                         if (pathlen < byte_cnt) {
3376                                 byte_cnt = pathlen;
3377                         }
3378                         pathlen -= byte_cnt;
3379
3380                         memcpy(XFS_BUF_PTR(bp), cur_chunk, byte_cnt);
3381                         cur_chunk += byte_cnt;
3382
3383                         xfs_trans_log_buf(tp, bp, 0, byte_cnt - 1);
3384                 }
3385         }
3386
3387         /*
3388          * Create the directory entry for the symlink.
3389          */
3390         error = xfs_dir_createname(tp, dp, link_name, link_namelen, ip->i_ino,
3391                                    &first_block, &free_list, resblks);
3392         if (error)
3393                 goto error1;
3394         xfs_ichgtime(dp, XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG);
3395         xfs_trans_log_inode(tp, dp, XFS_ILOG_CORE);
3396
3397         /*
3398          * Bump the in memory version number of the parent directory
3399          * so that other processes accessing it will recognize that
3400          * the directory has changed.
3401          */
3402         dp->i_gen++;
3403
3404         /*
3405          * If this is a synchronous mount, make sure that the
3406          * symlink transaction goes to disk before returning to
3407          * the user.
3408          */
3409         if (mp->m_flags & (XFS_MOUNT_WSYNC|XFS_MOUNT_DIRSYNC)) {
3410                 xfs_trans_set_sync(tp);
3411         }
3412
3413         /*
3414          * xfs_trans_commit normally decrements the vnode ref count
3415          * when it unlocks the inode. Since we want to return the
3416          * vnode to the caller, we bump the vnode ref count now.
3417          */
3418         IHOLD(ip);
3419
3420         error = xfs_bmap_finish(&tp, &free_list, &committed);
3421         if (error) {
3422                 goto error2;
3423         }
3424         error = xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
3425         XFS_QM_DQRELE(mp, udqp);
3426         XFS_QM_DQRELE(mp, gdqp);
3427
3428         /* Fall through to std_return with error = 0 or errno from
3429          * xfs_trans_commit     */
3430 std_return:
3431         if (DM_EVENT_ENABLED(dp, DM_EVENT_POSTSYMLINK)) {
3432                 (void) XFS_SEND_NAMESP(mp, DM_EVENT_POSTSYMLINK,
3433                                         dir_vp, DM_RIGHT_NULL,
3434                                         error ? NULL : XFS_ITOV(ip),
3435                                         DM_RIGHT_NULL, link_name, target_path,
3436                                         0, error, 0);
3437         }
3438
3439         if (!error) {
3440                 bhv_vnode_t *vp;
3441
3442                 ASSERT(ip);
3443                 vp = XFS_ITOV(ip);
3444                 *vpp = vp;
3445         }
3446         return error;
3447
3448  error2:
3449         IRELE(ip);
3450  error1:
3451         xfs_bmap_cancel(&free_list);
3452         cancel_flags |= XFS_TRANS_ABORT;
3453  error_return:
3454         xfs_trans_cancel(tp, cancel_flags);
3455         XFS_QM_DQRELE(mp, udqp);
3456         XFS_QM_DQRELE(mp, gdqp);
3457
3458         if (unlock_dp_on_error)
3459                 xfs_iunlock(dp, XFS_ILOCK_EXCL);
3460
3461         goto std_return;
3462 }
3463
3464
3465 int
3466 xfs_fid2(
3467         xfs_inode_t     *ip,
3468         xfs_fid_t       *xfid)
3469 {
3470         xfs_itrace_entry(ip);
3471
3472         xfid->fid_len = sizeof(xfs_fid_t) - sizeof(xfid->fid_len);
3473         xfid->fid_pad = 0;
3474         /*
3475          * use memcpy because the inode is a long long and there's no
3476          * assurance that xfid->fid_ino is properly aligned.
3477          */
3478         memcpy(&xfid->fid_ino, &ip->i_ino, sizeof(xfid->fid_ino));
3479         xfid->fid_gen = ip->i_d.di_gen;
3480
3481         return 0;
3482 }
3483
3484
3485 int
3486 xfs_rwlock(
3487         xfs_inode_t     *ip,
3488         bhv_vrwlock_t   locktype)
3489 {
3490         if (S_ISDIR(ip->i_d.di_mode))
3491                 return 1;
3492         if (locktype == VRWLOCK_WRITE) {
3493                 xfs_ilock(ip, XFS_IOLOCK_EXCL);
3494         } else if (locktype == VRWLOCK_TRY_READ) {
3495                 return xfs_ilock_nowait(ip, XFS_IOLOCK_SHARED);
3496         } else if (locktype == VRWLOCK_TRY_WRITE) {
3497                 return xfs_ilock_nowait(ip, XFS_IOLOCK_EXCL);
3498         } else {
3499                 ASSERT((locktype == VRWLOCK_READ) ||
3500                        (locktype == VRWLOCK_WRITE_DIRECT));
3501                 xfs_ilock(ip, XFS_IOLOCK_SHARED);
3502         }
3503
3504         return 1;
3505 }
3506
3507
3508 void
3509 xfs_rwunlock(
3510         xfs_inode_t     *ip,
3511         bhv_vrwlock_t   locktype)
3512 {
3513         if (S_ISDIR(ip->i_d.di_mode))
3514                 return;
3515         if (locktype == VRWLOCK_WRITE) {
3516                 /*
3517                  * In the write case, we may have added a new entry to
3518                  * the reference cache.  This might store a pointer to
3519                  * an inode to be released in this inode.  If it is there,
3520                  * clear the pointer and release the inode after unlocking
3521                  * this one.
3522                  */
3523                 xfs_refcache_iunlock(ip, XFS_IOLOCK_EXCL);
3524         } else {
3525                 ASSERT((locktype == VRWLOCK_READ) ||
3526                        (locktype == VRWLOCK_WRITE_DIRECT));
3527                 xfs_iunlock(ip, XFS_IOLOCK_SHARED);
3528         }
3529         return;
3530 }
3531
3532
3533 int
3534 xfs_inode_flush(
3535         xfs_inode_t     *ip,
3536         int             flags)
3537 {
3538         xfs_mount_t     *mp = ip->i_mount;
3539         xfs_inode_log_item_t *iip = ip->i_itemp;
3540         int             error = 0;
3541
3542         if (XFS_FORCED_SHUTDOWN(mp))
3543                 return XFS_ERROR(EIO);
3544
3545         /*
3546          * Bypass inodes which have already been cleaned by
3547          * the inode flush clustering code inside xfs_iflush
3548          */
3549         if ((ip->i_update_core == 0) &&
3550             ((iip == NULL) || !(iip->ili_format.ilf_fields & XFS_ILOG_ALL)))
3551                 return 0;
3552
3553         if (flags & FLUSH_LOG) {
3554                 if (iip && iip->ili_last_lsn) {
3555                         xlog_t          *log = mp->m_log;
3556                         xfs_lsn_t       sync_lsn;
3557                         int             s, log_flags = XFS_LOG_FORCE;
3558
3559                         s = GRANT_LOCK(log);
3560                         sync_lsn = log->l_last_sync_lsn;
3561                         GRANT_UNLOCK(log, s);
3562
3563                         if ((XFS_LSN_CMP(iip->ili_last_lsn, sync_lsn) > 0)) {
3564                                 if (flags & FLUSH_SYNC)
3565                                         log_flags |= XFS_LOG_SYNC;
3566                                 error = xfs_log_force(mp, iip->ili_last_lsn, log_flags);
3567                                 if (error)
3568                                         return error;
3569                         }
3570
3571                         if (ip->i_update_core == 0)
3572                                 return 0;
3573                 }
3574         }
3575
3576         /*
3577          * We make this non-blocking if the inode is contended,
3578          * return EAGAIN to indicate to the caller that they
3579          * did not succeed. This prevents the flush path from
3580          * blocking on inodes inside another operation right
3581          * now, they get caught later by xfs_sync.
3582          */
3583         if (flags & FLUSH_INODE) {
3584                 int     flush_flags;
3585
3586                 if (flags & FLUSH_SYNC) {
3587                         xfs_ilock(ip, XFS_ILOCK_SHARED);
3588                         xfs_iflock(ip);
3589                 } else if (xfs_ilock_nowait(ip, XFS_ILOCK_SHARED)) {
3590                         if (xfs_ipincount(ip) || !xfs_iflock_nowait(ip)) {
3591                                 xfs_iunlock(ip, XFS_ILOCK_SHARED);
3592                                 return EAGAIN;
3593                         }
3594                 } else {
3595                         return EAGAIN;
3596                 }
3597
3598                 if (flags & FLUSH_SYNC)
3599                         flush_flags = XFS_IFLUSH_SYNC;
3600                 else
3601                         flush_flags = XFS_IFLUSH_ASYNC;
3602
3603                 error = xfs_iflush(ip, flush_flags);
3604                 xfs_iunlock(ip, XFS_ILOCK_SHARED);
3605         }
3606
3607         return error;
3608 }
3609
3610
3611 int
3612 xfs_set_dmattrs(
3613         xfs_inode_t     *ip,
3614         u_int           evmask,
3615         u_int16_t       state)
3616 {
3617         xfs_mount_t     *mp = ip->i_mount;
3618         xfs_trans_t     *tp;
3619         int             error;
3620
3621         if (!capable(CAP_SYS_ADMIN))
3622                 return XFS_ERROR(EPERM);
3623
3624         if (XFS_FORCED_SHUTDOWN(mp))
3625                 return XFS_ERROR(EIO);
3626
3627         tp = xfs_trans_alloc(mp, XFS_TRANS_SET_DMATTRS);
3628         error = xfs_trans_reserve(tp, 0, XFS_ICHANGE_LOG_RES (mp), 0, 0, 0);
3629         if (error) {
3630                 xfs_trans_cancel(tp, 0);
3631                 return error;
3632         }
3633         xfs_ilock(ip, XFS_ILOCK_EXCL);
3634         xfs_trans_ijoin(tp, ip, XFS_ILOCK_EXCL);
3635
3636         ip->i_iocore.io_dmevmask = ip->i_d.di_dmevmask = evmask;
3637         ip->i_iocore.io_dmstate  = ip->i_d.di_dmstate  = state;
3638
3639         xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
3640         IHOLD(ip);
3641         error = xfs_trans_commit(tp, 0);
3642
3643         return error;
3644 }
3645
3646 int
3647 xfs_reclaim(
3648         xfs_inode_t     *ip)
3649 {
3650         bhv_vnode_t     *vp = XFS_ITOV(ip);
3651
3652         xfs_itrace_entry(ip);
3653
3654         ASSERT(!VN_MAPPED(vp));
3655
3656         /* bad inode, get out here ASAP */
3657         if (VN_BAD(vp)) {
3658                 xfs_ireclaim(ip);
3659                 return 0;
3660         }
3661
3662         vn_iowait(ip);
3663
3664         ASSERT(XFS_FORCED_SHUTDOWN(ip->i_mount) || ip->i_delayed_blks == 0);
3665
3666         /*
3667          * Make sure the atime in the XFS inode is correct before freeing the
3668          * Linux inode.
3669          */
3670         xfs_synchronize_atime(ip);
3671
3672         /*
3673          * If we have nothing to flush with this inode then complete the
3674          * teardown now, otherwise break the link between the xfs inode and the
3675          * linux inode and clean up the xfs inode later. This avoids flushing
3676          * the inode to disk during the delete operation itself.
3677          *
3678          * When breaking the link, we need to set the XFS_IRECLAIMABLE flag
3679          * first to ensure that xfs_iunpin() will never see an xfs inode
3680          * that has a linux inode being reclaimed. Synchronisation is provided
3681          * by the i_flags_lock.
3682          */
3683         if (!ip->i_update_core && (ip->i_itemp == NULL)) {
3684                 xfs_ilock(ip, XFS_ILOCK_EXCL);
3685                 xfs_iflock(ip);
3686                 return xfs_finish_reclaim(ip, 1, XFS_IFLUSH_DELWRI_ELSE_SYNC);
3687         } else {
3688                 xfs_mount_t     *mp = ip->i_mount;
3689
3690                 /* Protect sync and unpin from us */
3691                 XFS_MOUNT_ILOCK(mp);
3692                 spin_lock(&ip->i_flags_lock);
3693                 __xfs_iflags_set(ip, XFS_IRECLAIMABLE);
3694                 vn_to_inode(vp)->i_private = NULL;
3695                 ip->i_vnode = NULL;
3696                 spin_unlock(&ip->i_flags_lock);
3697                 list_add_tail(&ip->i_reclaim, &mp->m_del_inodes);
3698                 XFS_MOUNT_IUNLOCK(mp);
3699         }
3700         return 0;
3701 }
3702
3703 int
3704 xfs_finish_reclaim(
3705         xfs_inode_t     *ip,
3706         int             locked,
3707         int             sync_mode)
3708 {
3709         xfs_perag_t     *pag = xfs_get_perag(ip->i_mount, ip->i_ino);
3710         bhv_vnode_t     *vp = XFS_ITOV_NULL(ip);
3711         int             error;
3712
3713         if (vp && VN_BAD(vp))
3714                 goto reclaim;
3715
3716         /* The hash lock here protects a thread in xfs_iget_core from
3717          * racing with us on linking the inode back with a vnode.
3718          * Once we have the XFS_IRECLAIM flag set it will not touch
3719          * us.
3720          */
3721         write_lock(&pag->pag_ici_lock);
3722         spin_lock(&ip->i_flags_lock);
3723         if (__xfs_iflags_test(ip, XFS_IRECLAIM) ||
3724             (!__xfs_iflags_test(ip, XFS_IRECLAIMABLE) && vp == NULL)) {
3725                 spin_unlock(&ip->i_flags_lock);
3726                 write_unlock(&pag->pag_ici_lock);
3727                 if (locked) {
3728                         xfs_ifunlock(ip);
3729                         xfs_iunlock(ip, XFS_ILOCK_EXCL);
3730                 }
3731                 return 1;
3732         }
3733         __xfs_iflags_set(ip, XFS_IRECLAIM);
3734         spin_unlock(&ip->i_flags_lock);
3735         write_unlock(&pag->pag_ici_lock);
3736         xfs_put_perag(ip->i_mount, pag);
3737
3738         /*
3739          * If the inode is still dirty, then flush it out.  If the inode
3740          * is not in the AIL, then it will be OK to flush it delwri as
3741          * long as xfs_iflush() does not keep any references to the inode.
3742          * We leave that decision up to xfs_iflush() since it has the
3743          * knowledge of whether it's OK to simply do a delwri flush of
3744          * the inode or whether we need to wait until the inode is
3745          * pulled from the AIL.
3746          * We get the flush lock regardless, though, just to make sure
3747          * we don't free it while it is being flushed.
3748          */
3749         if (!XFS_FORCED_SHUTDOWN(ip->i_mount)) {
3750                 if (!locked) {
3751                         xfs_ilock(ip, XFS_ILOCK_EXCL);
3752                         xfs_iflock(ip);
3753                 }
3754
3755                 if (ip->i_update_core ||
3756                     ((ip->i_itemp != NULL) &&
3757                      (ip->i_itemp->ili_format.ilf_fields != 0))) {
3758                         error = xfs_iflush(ip, sync_mode);
3759                         /*
3760                          * If we hit an error, typically because of filesystem
3761                          * shutdown, we don't need to let vn_reclaim to know
3762                          * because we're gonna reclaim the inode anyway.
3763                          */
3764                         if (error) {
3765                                 xfs_iunlock(ip, XFS_ILOCK_EXCL);
3766                                 goto reclaim;
3767                         }
3768                         xfs_iflock(ip); /* synchronize with xfs_iflush_done */
3769                 }
3770
3771                 ASSERT(ip->i_update_core == 0);
3772                 ASSERT(ip->i_itemp == NULL ||
3773                        ip->i_itemp->ili_format.ilf_fields == 0);
3774                 xfs_iunlock(ip, XFS_ILOCK_EXCL);
3775         } else if (locked) {
3776                 /*
3777                  * We are not interested in doing an iflush if we're
3778                  * in the process of shutting down the filesystem forcibly.
3779                  * So, just reclaim the inode.
3780                  */
3781                 xfs_ifunlock(ip);
3782                 xfs_iunlock(ip, XFS_ILOCK_EXCL);
3783         }
3784
3785  reclaim:
3786         xfs_ireclaim(ip);
3787         return 0;
3788 }
3789
3790 int
3791 xfs_finish_reclaim_all(xfs_mount_t *mp, int noblock)
3792 {
3793         int             purged;
3794         xfs_inode_t     *ip, *n;
3795         int             done = 0;
3796
3797         while (!done) {
3798                 purged = 0;
3799                 XFS_MOUNT_ILOCK(mp);
3800                 list_for_each_entry_safe(ip, n, &mp->m_del_inodes, i_reclaim) {
3801                         if (noblock) {
3802                                 if (xfs_ilock_nowait(ip, XFS_ILOCK_EXCL) == 0)
3803                                         continue;
3804                                 if (xfs_ipincount(ip) ||
3805                                     !xfs_iflock_nowait(ip)) {
3806                                         xfs_iunlock(ip, XFS_ILOCK_EXCL);
3807                                         continue;
3808                                 }
3809                         }
3810                         XFS_MOUNT_IUNLOCK(mp);
3811                         if (xfs_finish_reclaim(ip, noblock,
3812                                         XFS_IFLUSH_DELWRI_ELSE_ASYNC))
3813                                 delay(1);
3814                         purged = 1;
3815                         break;
3816                 }
3817
3818                 done = !purged;
3819         }
3820
3821         XFS_MOUNT_IUNLOCK(mp);
3822         return 0;
3823 }
3824
3825 /*
3826  * xfs_alloc_file_space()
3827  *      This routine allocates disk space for the given file.
3828  *
3829  *      If alloc_type == 0, this request is for an ALLOCSP type
3830  *      request which will change the file size.  In this case, no
3831  *      DMAPI event will be generated by the call.  A TRUNCATE event
3832  *      will be generated later by xfs_setattr.
3833  *
3834  *      If alloc_type != 0, this request is for a RESVSP type
3835  *      request, and a DMAPI DM_EVENT_WRITE will be generated if the
3836  *      lower block boundary byte address is less than the file's
3837  *      length.
3838  *
3839  * RETURNS:
3840  *       0 on success
3841  *      errno on error
3842  *
3843  */
3844 STATIC int
3845 xfs_alloc_file_space(
3846         xfs_inode_t             *ip,
3847         xfs_off_t               offset,
3848         xfs_off_t               len,
3849         int                     alloc_type,
3850         int                     attr_flags)
3851 {
3852         xfs_mount_t             *mp = ip->i_mount;
3853         xfs_off_t               count;
3854         xfs_filblks_t           allocated_fsb;
3855         xfs_filblks_t           allocatesize_fsb;
3856         xfs_extlen_t            extsz, temp;
3857         xfs_fileoff_t           startoffset_fsb;
3858         xfs_fsblock_t           firstfsb;
3859         int                     nimaps;
3860         int                     bmapi_flag;
3861         int                     quota_flag;
3862         int                     rt;
3863         xfs_trans_t             *tp;
3864         xfs_bmbt_irec_t         imaps[1], *imapp;
3865         xfs_bmap_free_t         free_list;
3866         uint                    qblocks, resblks, resrtextents;
3867         int                     committed;
3868         int                     error;
3869
3870         xfs_itrace_entry(ip);
3871
3872         if (XFS_FORCED_SHUTDOWN(mp))
3873                 return XFS_ERROR(EIO);
3874
3875         if ((error = XFS_QM_DQATTACH(mp, ip, 0)))
3876                 return error;
3877
3878         if (len <= 0)
3879                 return XFS_ERROR(EINVAL);
3880
3881         rt = XFS_IS_REALTIME_INODE(ip);
3882         extsz = xfs_get_extsz_hint(ip);
3883
3884         count = len;
3885         imapp = &imaps[0];
3886         nimaps = 1;
3887         bmapi_flag = XFS_BMAPI_WRITE | (alloc_type ? XFS_BMAPI_PREALLOC : 0);
3888         startoffset_fsb = XFS_B_TO_FSBT(mp, offset);
3889         allocatesize_fsb = XFS_B_TO_FSB(mp, count);
3890
3891         /*      Generate a DMAPI event if needed.       */
3892         if (alloc_type != 0 && offset < ip->i_size &&
3893                         (attr_flags&ATTR_DMI) == 0  &&
3894                         DM_EVENT_ENABLED(ip, DM_EVENT_WRITE)) {
3895                 xfs_off_t           end_dmi_offset;
3896
3897                 end_dmi_offset = offset+len;
3898                 if (end_dmi_offset > ip->i_size)
3899                         end_dmi_offset = ip->i_size;
3900                 error = XFS_SEND_DATA(mp, DM_EVENT_WRITE, XFS_ITOV(ip),
3901                         offset, end_dmi_offset - offset,
3902                         0, NULL);
3903                 if (error)
3904                         return error;
3905         }
3906
3907         /*
3908          * Allocate file space until done or until there is an error
3909          */
3910 retry:
3911         while (allocatesize_fsb && !error) {
3912                 xfs_fileoff_t   s, e;
3913
3914                 /*
3915                  * Determine space reservations for data/realtime.
3916                  */
3917                 if (unlikely(extsz)) {
3918                         s = startoffset_fsb;
3919                         do_div(s, extsz);
3920                         s *= extsz;
3921                         e = startoffset_fsb + allocatesize_fsb;
3922                         if ((temp = do_mod(startoffset_fsb, extsz)))
3923                                 e += temp;
3924                         if ((temp = do_mod(e, extsz)))
3925                                 e += extsz - temp;
3926                 } else {
3927                         s = 0;
3928                         e = allocatesize_fsb;
3929                 }
3930
3931                 if (unlikely(rt)) {
3932                         resrtextents = qblocks = (uint)(e - s);
3933                         resrtextents /= mp->m_sb.sb_rextsize;
3934                         resblks = XFS_DIOSTRAT_SPACE_RES(mp, 0);
3935                         quota_flag = XFS_QMOPT_RES_RTBLKS;
3936                 } else {
3937                         resrtextents = 0;
3938                         resblks = qblocks = \
3939                                 XFS_DIOSTRAT_SPACE_RES(mp, (uint)(e - s));
3940                         quota_flag = XFS_QMOPT_RES_REGBLKS;
3941                 }
3942
3943                 /*
3944                  * Allocate and setup the transaction.
3945                  */
3946                 tp = xfs_trans_alloc(mp, XFS_TRANS_DIOSTRAT);
3947                 error = xfs_trans_reserve(tp, resblks,
3948                                           XFS_WRITE_LOG_RES(mp), resrtextents,
3949                                           XFS_TRANS_PERM_LOG_RES,
3950                                           XFS_WRITE_LOG_COUNT);
3951                 /*
3952                  * Check for running out of space
3953                  */
3954                 if (error) {
3955                         /*
3956                          * Free the transaction structure.
3957                          */
3958                         ASSERT(error == ENOSPC || XFS_FORCED_SHUTDOWN(mp));
3959                         xfs_trans_cancel(tp, 0);
3960                         break;
3961                 }
3962                 xfs_ilock(ip, XFS_ILOCK_EXCL);
3963                 error = XFS_TRANS_RESERVE_QUOTA_NBLKS(mp, tp, ip,
3964                                                       qblocks, 0, quota_flag);
3965                 if (error)
3966                         goto error1;
3967
3968                 xfs_trans_ijoin(tp, ip, XFS_ILOCK_EXCL);
3969                 xfs_trans_ihold(tp, ip);
3970
3971                 /*
3972                  * Issue the xfs_bmapi() call to allocate the blocks
3973                  */
3974                 XFS_BMAP_INIT(&free_list, &firstfsb);
3975                 error = XFS_BMAPI(mp, tp, &ip->i_iocore, startoffset_fsb,
3976                                   allocatesize_fsb, bmapi_flag,
3977                                   &firstfsb, 0, imapp, &nimaps,
3978                                   &free_list, NULL);
3979                 if (error) {
3980                         goto error0;
3981                 }
3982
3983                 /*
3984                  * Complete the transaction
3985                  */
3986                 error = xfs_bmap_finish(&tp, &free_list, &committed);
3987                 if (error) {
3988                         goto error0;
3989                 }
3990
3991                 error = xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
3992                 xfs_iunlock(ip, XFS_ILOCK_EXCL);
3993                 if (error) {
3994                         break;
3995                 }
3996
3997                 allocated_fsb = imapp->br_blockcount;
3998
3999                 if (nimaps == 0) {
4000                         error = XFS_ERROR(ENOSPC);
4001                         break;
4002                 }
4003
4004                 startoffset_fsb += allocated_fsb;
4005                 allocatesize_fsb -= allocated_fsb;
4006         }
4007 dmapi_enospc_check:
4008         if (error == ENOSPC && (attr_flags & ATTR_DMI) == 0 &&
4009             DM_EVENT_ENABLED(ip, DM_EVENT_NOSPACE)) {
4010                 error = XFS_SEND_NAMESP(mp, DM_EVENT_NOSPACE,
4011                                 XFS_ITOV(ip), DM_RIGHT_NULL,
4012                                 XFS_ITOV(ip), DM_RIGHT_NULL,
4013                                 NULL, NULL, 0, 0, 0); /* Delay flag intentionally unused */
4014                 if (error == 0)
4015                         goto retry;     /* Maybe DMAPI app. has made space */
4016                 /* else fall through with error from XFS_SEND_DATA */
4017         }
4018
4019         return error;
4020
4021 error0: /* Cancel bmap, unlock inode, unreserve quota blocks, cancel trans */
4022         xfs_bmap_cancel(&free_list);
4023         XFS_TRANS_UNRESERVE_QUOTA_NBLKS(mp, tp, ip, qblocks, 0, quota_flag);
4024
4025 error1: /* Just cancel transaction */
4026         xfs_trans_cancel(tp, XFS_TRANS_RELEASE_LOG_RES | XFS_TRANS_ABORT);
4027         xfs_iunlock(ip, XFS_ILOCK_EXCL);
4028         goto dmapi_enospc_check;
4029 }
4030
4031 /*
4032  * Zero file bytes between startoff and endoff inclusive.
4033  * The iolock is held exclusive and no blocks are buffered.
4034  */
4035 STATIC int
4036 xfs_zero_remaining_bytes(
4037         xfs_inode_t             *ip,
4038         xfs_off_t               startoff,
4039         xfs_off_t               endoff)
4040 {
4041         xfs_bmbt_irec_t         imap;
4042         xfs_fileoff_t           offset_fsb;
4043         xfs_off_t               lastoffset;
4044         xfs_off_t               offset;
4045         xfs_buf_t               *bp;
4046         xfs_mount_t             *mp = ip->i_mount;
4047         int                     nimap;
4048         int                     error = 0;
4049
4050         bp = xfs_buf_get_noaddr(mp->m_sb.sb_blocksize,
4051                                 ip->i_d.di_flags & XFS_DIFLAG_REALTIME ?
4052                                 mp->m_rtdev_targp : mp->m_ddev_targp);
4053
4054         for (offset = startoff; offset <= endoff; offset = lastoffset + 1) {
4055                 offset_fsb = XFS_B_TO_FSBT(mp, offset);
4056                 nimap = 1;
4057                 error = XFS_BMAPI(mp, NULL, &ip->i_iocore, offset_fsb, 1, 0,
4058                         NULL, 0, &imap, &nimap, NULL, NULL);
4059                 if (error || nimap < 1)
4060                         break;
4061                 ASSERT(imap.br_blockcount >= 1);
4062                 ASSERT(imap.br_startoff == offset_fsb);
4063                 lastoffset = XFS_FSB_TO_B(mp, imap.br_startoff + 1) - 1;
4064                 if (lastoffset > endoff)
4065                         lastoffset = endoff;
4066                 if (imap.br_startblock == HOLESTARTBLOCK)
4067                         continue;
4068                 ASSERT(imap.br_startblock != DELAYSTARTBLOCK);
4069                 if (imap.br_state == XFS_EXT_UNWRITTEN)
4070                         continue;
4071                 XFS_BUF_UNDONE(bp);
4072                 XFS_BUF_UNWRITE(bp);
4073                 XFS_BUF_READ(bp);
4074                 XFS_BUF_SET_ADDR(bp, XFS_FSB_TO_DB(ip, imap.br_startblock));
4075                 xfsbdstrat(mp, bp);
4076                 if ((error = xfs_iowait(bp))) {
4077                         xfs_ioerror_alert("xfs_zero_remaining_bytes(read)",
4078                                           mp, bp, XFS_BUF_ADDR(bp));
4079                         break;
4080                 }
4081                 memset(XFS_BUF_PTR(bp) +
4082                         (offset - XFS_FSB_TO_B(mp, imap.br_startoff)),
4083                       0, lastoffset - offset + 1);
4084                 XFS_BUF_UNDONE(bp);
4085                 XFS_BUF_UNREAD(bp);
4086                 XFS_BUF_WRITE(bp);
4087                 xfsbdstrat(mp, bp);
4088                 if ((error = xfs_iowait(bp))) {
4089                         xfs_ioerror_alert("xfs_zero_remaining_bytes(write)",
4090                                           mp, bp, XFS_BUF_ADDR(bp));
4091                         break;
4092                 }
4093         }
4094         xfs_buf_free(bp);
4095         return error;
4096 }
4097
4098 /*
4099  * xfs_free_file_space()
4100  *      This routine frees disk space for the given file.
4101  *
4102  *      This routine is only called by xfs_change_file_space
4103  *      for an UNRESVSP type call.
4104  *
4105  * RETURNS:
4106  *       0 on success
4107  *      errno on error
4108  *
4109  */
4110 STATIC int
4111 xfs_free_file_space(
4112         xfs_inode_t             *ip,
4113         xfs_off_t               offset,
4114         xfs_off_t               len,
4115         int                     attr_flags)
4116 {
4117         bhv_vnode_t             *vp;
4118         int                     committed;
4119         int                     done;
4120         xfs_off_t               end_dmi_offset;
4121         xfs_fileoff_t           endoffset_fsb;
4122         int                     error;
4123         xfs_fsblock_t           firstfsb;
4124         xfs_bmap_free_t         free_list;
4125         xfs_bmbt_irec_t         imap;
4126         xfs_off_t               ioffset;
4127         xfs_extlen_t            mod=0;
4128         xfs_mount_t             *mp;
4129         int                     nimap;
4130         uint                    resblks;
4131         uint                    rounding;
4132         int                     rt;
4133         xfs_fileoff_t           startoffset_fsb;
4134         xfs_trans_t             *tp;
4135         int                     need_iolock = 1;
4136
4137         vp = XFS_ITOV(ip);
4138         mp = ip->i_mount;
4139
4140         xfs_itrace_entry(ip);
4141
4142         if ((error = XFS_QM_DQATTACH(mp, ip, 0)))
4143                 return error;
4144
4145         error = 0;
4146         if (len <= 0)   /* if nothing being freed */
4147                 return error;
4148         rt = (ip->i_d.di_flags & XFS_DIFLAG_REALTIME);
4149         startoffset_fsb = XFS_B_TO_FSB(mp, offset);
4150         end_dmi_offset = offset + len;
4151         endoffset_fsb = XFS_B_TO_FSBT(mp, end_dmi_offset);
4152
4153         if (offset < ip->i_size && (attr_flags & ATTR_DMI) == 0 &&
4154             DM_EVENT_ENABLED(ip, DM_EVENT_WRITE)) {
4155                 if (end_dmi_offset > ip->i_size)
4156                         end_dmi_offset = ip->i_size;
4157                 error = XFS_SEND_DATA(mp, DM_EVENT_WRITE, vp,
4158                                 offset, end_dmi_offset - offset,
4159                                 AT_DELAY_FLAG(attr_flags), NULL);
4160                 if (error)
4161                         return error;
4162         }
4163
4164         if (attr_flags & ATTR_NOLOCK)
4165                 need_iolock = 0;
4166         if (need_iolock) {
4167                 xfs_ilock(ip, XFS_IOLOCK_EXCL);
4168                 vn_iowait(ip);  /* wait for the completion of any pending DIOs */
4169         }
4170
4171         rounding = max_t(uint, 1 << mp->m_sb.sb_blocklog, NBPP);
4172         ioffset = offset & ~(rounding - 1);
4173
4174         if (VN_CACHED(vp) != 0) {
4175                 xfs_inval_cached_trace(&ip->i_iocore, ioffset, -1,
4176                                 ctooff(offtoct(ioffset)), -1);
4177                 error = xfs_flushinval_pages(ip,
4178                                 ctooff(offtoct(ioffset)),
4179                                 -1, FI_REMAPF_LOCKED);
4180                 if (error)
4181                         goto out_unlock_iolock;
4182         }
4183
4184         /*
4185          * Need to zero the stuff we're not freeing, on disk.
4186          * If its a realtime file & can't use unwritten extents then we
4187          * actually need to zero the extent edges.  Otherwise xfs_bunmapi
4188          * will take care of it for us.
4189          */
4190         if (rt && !XFS_SB_VERSION_HASEXTFLGBIT(&mp->m_sb)) {
4191                 nimap = 1;
4192                 error = XFS_BMAPI(mp, NULL, &ip->i_iocore, startoffset_fsb,
4193                         1, 0, NULL, 0, &imap, &nimap, NULL, NULL);
4194                 if (error)
4195                         goto out_unlock_iolock;
4196                 ASSERT(nimap == 0 || nimap == 1);
4197                 if (nimap && imap.br_startblock != HOLESTARTBLOCK) {
4198                         xfs_daddr_t     block;
4199
4200                         ASSERT(imap.br_startblock != DELAYSTARTBLOCK);
4201                         block = imap.br_startblock;
4202                         mod = do_div(block, mp->m_sb.sb_rextsize);
4203                         if (mod)
4204                                 startoffset_fsb += mp->m_sb.sb_rextsize - mod;
4205                 }
4206                 nimap = 1;
4207                 error = XFS_BMAPI(mp, NULL, &ip->i_iocore, endoffset_fsb - 1,
4208                         1, 0, NULL, 0, &imap, &nimap, NULL, NULL);
4209                 if (error)
4210                         goto out_unlock_iolock;
4211                 ASSERT(nimap == 0 || nimap == 1);
4212                 if (nimap && imap.br_startblock != HOLESTARTBLOCK) {
4213                         ASSERT(imap.br_startblock != DELAYSTARTBLOCK);
4214                         mod++;
4215                         if (mod && (mod != mp->m_sb.sb_rextsize))
4216                                 endoffset_fsb -= mod;
4217                 }
4218         }
4219         if ((done = (endoffset_fsb <= startoffset_fsb)))
4220                 /*
4221                  * One contiguous piece to clear
4222                  */
4223                 error = xfs_zero_remaining_bytes(ip, offset, offset + len - 1);
4224         else {
4225                 /*
4226                  * Some full blocks, possibly two pieces to clear
4227                  */
4228                 if (offset < XFS_FSB_TO_B(mp, startoffset_fsb))
4229                         error = xfs_zero_remaining_bytes(ip, offset,
4230                                 XFS_FSB_TO_B(mp, startoffset_fsb) - 1);
4231                 if (!error &&
4232                     XFS_FSB_TO_B(mp, endoffset_fsb) < offset + len)
4233                         error = xfs_zero_remaining_bytes(ip,
4234                                 XFS_FSB_TO_B(mp, endoffset_fsb),
4235                                 offset + len - 1);
4236         }
4237
4238         /*
4239          * free file space until done or until there is an error
4240          */
4241         resblks = XFS_DIOSTRAT_SPACE_RES(mp, 0);
4242         while (!error && !done) {
4243
4244                 /*
4245                  * allocate and setup the transaction. Allow this
4246                  * transaction to dip into the reserve blocks to ensure
4247                  * the freeing of the space succeeds at ENOSPC.
4248                  */
4249                 tp = xfs_trans_alloc(mp, XFS_TRANS_DIOSTRAT);
4250                 tp->t_flags |= XFS_TRANS_RESERVE;
4251                 error = xfs_trans_reserve(tp,
4252                                           resblks,
4253                                           XFS_WRITE_LOG_RES(mp),
4254                                           0,
4255                                           XFS_TRANS_PERM_LOG_RES,
4256                                           XFS_WRITE_LOG_COUNT);
4257
4258                 /*
4259                  * check for running out of space
4260                  */
4261                 if (error) {
4262                         /*
4263                          * Free the transaction structure.
4264                          */
4265                         ASSERT(error == ENOSPC || XFS_FORCED_SHUTDOWN(mp));
4266                         xfs_trans_cancel(tp, 0);
4267                         break;
4268                 }
4269                 xfs_ilock(ip, XFS_ILOCK_EXCL);
4270                 error = XFS_TRANS_RESERVE_QUOTA(mp, tp,
4271                                 ip->i_udquot, ip->i_gdquot, resblks, 0,
4272                                 XFS_QMOPT_RES_REGBLKS);
4273                 if (error)
4274                         goto error1;
4275
4276                 xfs_trans_ijoin(tp, ip, XFS_ILOCK_EXCL);
4277                 xfs_trans_ihold(tp, ip);
4278
4279                 /*
4280                  * issue the bunmapi() call to free the blocks
4281                  */
4282                 XFS_BMAP_INIT(&free_list, &firstfsb);
4283                 error = XFS_BUNMAPI(mp, tp, &ip->i_iocore, startoffset_fsb,
4284                                   endoffset_fsb - startoffset_fsb,
4285                                   0, 2, &firstfsb, &free_list, NULL, &done);
4286                 if (error) {
4287                         goto error0;
4288                 }
4289
4290                 /*
4291                  * complete the transaction
4292                  */
4293                 error = xfs_bmap_finish(&tp, &free_list, &committed);
4294                 if (error) {
4295                         goto error0;
4296                 }
4297
4298                 error = xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
4299                 xfs_iunlock(ip, XFS_ILOCK_EXCL);
4300         }
4301
4302  out_unlock_iolock:
4303         if (need_iolock)
4304                 xfs_iunlock(ip, XFS_IOLOCK_EXCL);
4305         return error;
4306
4307  error0:
4308         xfs_bmap_cancel(&free_list);
4309  error1:
4310         xfs_trans_cancel(tp, XFS_TRANS_RELEASE_LOG_RES | XFS_TRANS_ABORT);
4311         xfs_iunlock(ip, need_iolock ? (XFS_ILOCK_EXCL | XFS_IOLOCK_EXCL) :
4312                     XFS_ILOCK_EXCL);
4313         return error;
4314 }
4315
4316 /*
4317  * xfs_change_file_space()
4318  *      This routine allocates or frees disk space for the given file.
4319  *      The user specified parameters are checked for alignment and size
4320  *      limitations.
4321  *
4322  * RETURNS:
4323  *       0 on success
4324  *      errno on error
4325  *
4326  */
4327 int
4328 xfs_change_file_space(
4329         xfs_inode_t     *ip,
4330         int             cmd,
4331         xfs_flock64_t   *bf,
4332         xfs_off_t       offset,
4333         cred_t          *credp,
4334         int             attr_flags)
4335 {
4336         xfs_mount_t     *mp = ip->i_mount;
4337         int             clrprealloc;
4338         int             error;
4339         xfs_fsize_t     fsize;
4340         int             setprealloc;
4341         xfs_off_t       startoffset;
4342         xfs_off_t       llen;
4343         xfs_trans_t     *tp;
4344         bhv_vattr_t     va;
4345
4346         xfs_itrace_entry(ip);
4347
4348         /*
4349          * must be a regular file and have write permission
4350          */
4351         if (!S_ISREG(ip->i_d.di_mode))
4352                 return XFS_ERROR(EINVAL);
4353
4354         xfs_ilock(ip, XFS_ILOCK_SHARED);
4355
4356         if ((error = xfs_iaccess(ip, S_IWUSR, credp))) {
4357                 xfs_iunlock(ip, XFS_ILOCK_SHARED);
4358                 return error;
4359         }
4360
4361         xfs_iunlock(ip, XFS_ILOCK_SHARED);
4362
4363         switch (bf->l_whence) {
4364         case 0: /*SEEK_SET*/
4365                 break;
4366         case 1: /*SEEK_CUR*/
4367                 bf->l_start += offset;
4368                 break;
4369         case 2: /*SEEK_END*/
4370                 bf->l_start += ip->i_size;
4371                 break;
4372         default:
4373                 return XFS_ERROR(EINVAL);
4374         }
4375
4376         llen = bf->l_len > 0 ? bf->l_len - 1 : bf->l_len;
4377
4378         if (   (bf->l_start < 0)
4379             || (bf->l_start > XFS_MAXIOFFSET(mp))
4380             || (bf->l_start + llen < 0)
4381             || (bf->l_start + llen > XFS_MAXIOFFSET(mp)))
4382                 return XFS_ERROR(EINVAL);
4383
4384         bf->l_whence = 0;
4385
4386         startoffset = bf->l_start;
4387         fsize = ip->i_size;
4388
4389         /*
4390          * XFS_IOC_RESVSP and XFS_IOC_UNRESVSP will reserve or unreserve
4391          * file space.
4392          * These calls do NOT zero the data space allocated to the file,
4393          * nor do they change the file size.
4394          *
4395          * XFS_IOC_ALLOCSP and XFS_IOC_FREESP will allocate and free file
4396          * space.
4397          * These calls cause the new file data to be zeroed and the file
4398          * size to be changed.
4399          */
4400         setprealloc = clrprealloc = 0;
4401
4402         switch (cmd) {
4403         case XFS_IOC_RESVSP:
4404         case XFS_IOC_RESVSP64:
4405                 error = xfs_alloc_file_space(ip, startoffset, bf->l_len,
4406                                                                 1, attr_flags);
4407                 if (error)
4408                         return error;
4409                 setprealloc = 1;
4410                 break;
4411
4412         case XFS_IOC_UNRESVSP:
4413         case XFS_IOC_UNRESVSP64:
4414                 if ((error = xfs_free_file_space(ip, startoffset, bf->l_len,
4415                                                                 attr_flags)))
4416                         return error;
4417                 break;
4418
4419         case XFS_IOC_ALLOCSP:
4420         case XFS_IOC_ALLOCSP64:
4421         case XFS_IOC_FREESP:
4422         case XFS_IOC_FREESP64:
4423                 if (startoffset > fsize) {
4424                         error = xfs_alloc_file_space(ip, fsize,
4425                                         startoffset - fsize, 0, attr_flags);
4426                         if (error)
4427                                 break;
4428                 }
4429
4430                 va.va_mask = XFS_AT_SIZE;
4431                 va.va_size = startoffset;
4432
4433                 error = xfs_setattr(ip, &va, attr_flags, credp);
4434
4435                 if (error)
4436                         return error;
4437
4438                 clrprealloc = 1;
4439                 break;
4440
4441         default:
4442                 ASSERT(0);
4443                 return XFS_ERROR(EINVAL);
4444         }
4445
4446         /*
4447          * update the inode timestamp, mode, and prealloc flag bits
4448          */
4449         tp = xfs_trans_alloc(mp, XFS_TRANS_WRITEID);
4450
4451         if ((error = xfs_trans_reserve(tp, 0, XFS_WRITEID_LOG_RES(mp),
4452                                       0, 0, 0))) {
4453                 /* ASSERT(0); */
4454                 xfs_trans_cancel(tp, 0);
4455                 return error;
4456         }
4457
4458         xfs_ilock(ip, XFS_ILOCK_EXCL);
4459
4460         xfs_trans_ijoin(tp, ip, XFS_ILOCK_EXCL);
4461         xfs_trans_ihold(tp, ip);
4462
4463         if ((attr_flags & ATTR_DMI) == 0) {
4464                 ip->i_d.di_mode &= ~S_ISUID;
4465
4466                 /*
4467                  * Note that we don't have to worry about mandatory
4468                  * file locking being disabled here because we only
4469                  * clear the S_ISGID bit if the Group execute bit is
4470                  * on, but if it was on then mandatory locking wouldn't
4471                  * have been enabled.
4472                  */
4473                 if (ip->i_d.di_mode & S_IXGRP)
4474                         ip->i_d.di_mode &= ~S_ISGID;
4475
4476                 xfs_ichgtime(ip, XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG);
4477         }
4478         if (setprealloc)
4479                 ip->i_d.di_flags |= XFS_DIFLAG_PREALLOC;
4480         else if (clrprealloc)
4481                 ip->i_d.di_flags &= ~XFS_DIFLAG_PREALLOC;
4482
4483         xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
4484         xfs_trans_set_sync(tp);
4485
4486         error = xfs_trans_commit(tp, 0);
4487
4488         xfs_iunlock(ip, XFS_ILOCK_EXCL);
4489
4490         return error;
4491 }