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