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