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