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