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