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