[XFS] Fix double free of log tickets
[linux-2.6.git] / fs / xfs / xfs_vnodeops.c
1 /*
2  * Copyright (c) 2000-2006 Silicon Graphics, Inc.
3  * All Rights Reserved.
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License as
7  * published by the Free Software Foundation.
8  *
9  * This program is distributed in the hope that it would be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write the Free Software Foundation,
16  * Inc.,  51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17  */
18
19 #include "xfs.h"
20 #include "xfs_fs.h"
21 #include "xfs_types.h"
22 #include "xfs_bit.h"
23 #include "xfs_log.h"
24 #include "xfs_inum.h"
25 #include "xfs_trans.h"
26 #include "xfs_sb.h"
27 #include "xfs_ag.h"
28 #include "xfs_dir2.h"
29 #include "xfs_dmapi.h"
30 #include "xfs_mount.h"
31 #include "xfs_da_btree.h"
32 #include "xfs_bmap_btree.h"
33 #include "xfs_alloc_btree.h"
34 #include "xfs_ialloc_btree.h"
35 #include "xfs_dir2_sf.h"
36 #include "xfs_attr_sf.h"
37 #include "xfs_dinode.h"
38 #include "xfs_inode.h"
39 #include "xfs_inode_item.h"
40 #include "xfs_itable.h"
41 #include "xfs_btree.h"
42 #include "xfs_ialloc.h"
43 #include "xfs_alloc.h"
44 #include "xfs_bmap.h"
45 #include "xfs_attr.h"
46 #include "xfs_rw.h"
47 #include "xfs_error.h"
48 #include "xfs_quota.h"
49 #include "xfs_utils.h"
50 #include "xfs_rtalloc.h"
51 #include "xfs_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          * transaction commit worked ok so we can drop the extra ticket
1023          * reference that we gained in xfs_trans_dup()
1024          */
1025         xfs_log_ticket_put(tp->t_ticket);
1026
1027         /*
1028          * Remove the memory for extent descriptions (just bookkeeping).
1029          */
1030         if (ip->i_df.if_bytes)
1031                 xfs_idata_realloc(ip, -ip->i_df.if_bytes, XFS_DATA_FORK);
1032         ASSERT(ip->i_df.if_bytes == 0);
1033         /*
1034          * Put an itruncate log reservation in the new transaction
1035          * for our caller.
1036          */
1037         if ((error = xfs_trans_reserve(tp, 0, XFS_ITRUNCATE_LOG_RES(mp), 0,
1038                         XFS_TRANS_PERM_LOG_RES, XFS_ITRUNCATE_LOG_COUNT))) {
1039                 ASSERT(XFS_FORCED_SHUTDOWN(mp));
1040                 goto error0;
1041         }
1042         /*
1043          * Return with the inode locked but not joined to the transaction.
1044          */
1045         *tpp = tp;
1046         return 0;
1047
1048  error1:
1049         xfs_bmap_cancel(&free_list);
1050  error0:
1051         /*
1052          * Have to come here with the inode locked and either
1053          * (held and in the transaction) or (not in the transaction).
1054          * If the inode isn't held then cancel would iput it, but
1055          * that's wrong since this is inactive and the vnode ref
1056          * count is 0 already.
1057          * Cancel won't do anything to the inode if held, but it still
1058          * needs to be locked until the cancel is done, if it was
1059          * joined to the transaction.
1060          */
1061         xfs_trans_cancel(tp, XFS_TRANS_RELEASE_LOG_RES | XFS_TRANS_ABORT);
1062         xfs_iunlock(ip, XFS_IOLOCK_EXCL | XFS_ILOCK_EXCL);
1063         *tpp = NULL;
1064         return error;
1065
1066 }
1067
1068 STATIC int
1069 xfs_inactive_symlink_local(
1070         xfs_inode_t     *ip,
1071         xfs_trans_t     **tpp)
1072 {
1073         int             error;
1074
1075         ASSERT(ip->i_d.di_size <= XFS_IFORK_DSIZE(ip));
1076         /*
1077          * We're freeing a symlink which fit into
1078          * the inode.  Just free the memory used
1079          * to hold the old symlink.
1080          */
1081         error = xfs_trans_reserve(*tpp, 0,
1082                                   XFS_ITRUNCATE_LOG_RES(ip->i_mount),
1083                                   0, XFS_TRANS_PERM_LOG_RES,
1084                                   XFS_ITRUNCATE_LOG_COUNT);
1085
1086         if (error) {
1087                 xfs_trans_cancel(*tpp, 0);
1088                 *tpp = NULL;
1089                 return error;
1090         }
1091         xfs_ilock(ip, XFS_ILOCK_EXCL | XFS_IOLOCK_EXCL);
1092
1093         /*
1094          * Zero length symlinks _can_ exist.
1095          */
1096         if (ip->i_df.if_bytes > 0) {
1097                 xfs_idata_realloc(ip,
1098                                   -(ip->i_df.if_bytes),
1099                                   XFS_DATA_FORK);
1100                 ASSERT(ip->i_df.if_bytes == 0);
1101         }
1102         return 0;
1103 }
1104
1105 STATIC int
1106 xfs_inactive_attrs(
1107         xfs_inode_t     *ip,
1108         xfs_trans_t     **tpp)
1109 {
1110         xfs_trans_t     *tp;
1111         int             error;
1112         xfs_mount_t     *mp;
1113
1114         ASSERT(xfs_isilocked(ip, XFS_IOLOCK_EXCL));
1115         tp = *tpp;
1116         mp = ip->i_mount;
1117         ASSERT(ip->i_d.di_forkoff != 0);
1118         error = xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
1119         xfs_iunlock(ip, XFS_ILOCK_EXCL);
1120         if (error)
1121                 goto error_unlock;
1122
1123         error = xfs_attr_inactive(ip);
1124         if (error)
1125                 goto error_unlock;
1126
1127         tp = xfs_trans_alloc(mp, XFS_TRANS_INACTIVE);
1128         error = xfs_trans_reserve(tp, 0,
1129                                   XFS_IFREE_LOG_RES(mp),
1130                                   0, XFS_TRANS_PERM_LOG_RES,
1131                                   XFS_INACTIVE_LOG_COUNT);
1132         if (error)
1133                 goto error_cancel;
1134
1135         xfs_ilock(ip, XFS_ILOCK_EXCL);
1136         xfs_trans_ijoin(tp, ip, XFS_IOLOCK_EXCL | XFS_ILOCK_EXCL);
1137         xfs_trans_ihold(tp, ip);
1138         xfs_idestroy_fork(ip, XFS_ATTR_FORK);
1139
1140         ASSERT(ip->i_d.di_anextents == 0);
1141
1142         *tpp = tp;
1143         return 0;
1144
1145 error_cancel:
1146         ASSERT(XFS_FORCED_SHUTDOWN(mp));
1147         xfs_trans_cancel(tp, 0);
1148 error_unlock:
1149         *tpp = NULL;
1150         xfs_iunlock(ip, XFS_IOLOCK_EXCL);
1151         return error;
1152 }
1153
1154 int
1155 xfs_release(
1156         xfs_inode_t     *ip)
1157 {
1158         xfs_mount_t     *mp = ip->i_mount;
1159         int             error;
1160
1161         if (!S_ISREG(ip->i_d.di_mode) || (ip->i_d.di_mode == 0))
1162                 return 0;
1163
1164         /* If this is a read-only mount, don't do this (would generate I/O) */
1165         if (mp->m_flags & XFS_MOUNT_RDONLY)
1166                 return 0;
1167
1168         if (!XFS_FORCED_SHUTDOWN(mp)) {
1169                 int truncated;
1170
1171                 /*
1172                  * If we are using filestreams, and we have an unlinked
1173                  * file that we are processing the last close on, then nothing
1174                  * will be able to reopen and write to this file. Purge this
1175                  * inode from the filestreams cache so that it doesn't delay
1176                  * teardown of the inode.
1177                  */
1178                 if ((ip->i_d.di_nlink == 0) && xfs_inode_is_filestream(ip))
1179                         xfs_filestream_deassociate(ip);
1180
1181                 /*
1182                  * If we previously truncated this file and removed old data
1183                  * in the process, we want to initiate "early" writeout on
1184                  * the last close.  This is an attempt to combat the notorious
1185                  * NULL files problem which is particularly noticable from a
1186                  * truncate down, buffered (re-)write (delalloc), followed by
1187                  * a crash.  What we are effectively doing here is
1188                  * significantly reducing the time window where we'd otherwise
1189                  * be exposed to that problem.
1190                  */
1191                 truncated = xfs_iflags_test_and_clear(ip, XFS_ITRUNCATED);
1192                 if (truncated && VN_DIRTY(VFS_I(ip)) && ip->i_delayed_blks > 0)
1193                         xfs_flush_pages(ip, 0, -1, XFS_B_ASYNC, FI_NONE);
1194         }
1195
1196         if (ip->i_d.di_nlink != 0) {
1197                 if ((((ip->i_d.di_mode & S_IFMT) == S_IFREG) &&
1198                      ((ip->i_size > 0) || (VN_CACHED(VFS_I(ip)) > 0 ||
1199                        ip->i_delayed_blks > 0)) &&
1200                      (ip->i_df.if_flags & XFS_IFEXTENTS))  &&
1201                     (!(ip->i_d.di_flags &
1202                                 (XFS_DIFLAG_PREALLOC | XFS_DIFLAG_APPEND)))) {
1203                         error = xfs_free_eofblocks(mp, ip, XFS_FREE_EOF_LOCK);
1204                         if (error)
1205                                 return error;
1206                 }
1207         }
1208
1209         return 0;
1210 }
1211
1212 /*
1213  * xfs_inactive
1214  *
1215  * This is called when the vnode reference count for the vnode
1216  * goes to zero.  If the file has been unlinked, then it must
1217  * now be truncated.  Also, we clear all of the read-ahead state
1218  * kept for the inode here since the file is now closed.
1219  */
1220 int
1221 xfs_inactive(
1222         xfs_inode_t     *ip)
1223 {
1224         xfs_bmap_free_t free_list;
1225         xfs_fsblock_t   first_block;
1226         int             committed;
1227         xfs_trans_t     *tp;
1228         xfs_mount_t     *mp;
1229         int             error;
1230         int             truncate;
1231
1232         xfs_itrace_entry(ip);
1233
1234         /*
1235          * If the inode is already free, then there can be nothing
1236          * to clean up here.
1237          */
1238         if (ip->i_d.di_mode == 0 || VN_BAD(VFS_I(ip))) {
1239                 ASSERT(ip->i_df.if_real_bytes == 0);
1240                 ASSERT(ip->i_df.if_broot_bytes == 0);
1241                 return VN_INACTIVE_CACHE;
1242         }
1243
1244         /*
1245          * Only do a truncate if it's a regular file with
1246          * some actual space in it.  It's OK to look at the
1247          * inode's fields without the lock because we're the
1248          * only one with a reference to the inode.
1249          */
1250         truncate = ((ip->i_d.di_nlink == 0) &&
1251             ((ip->i_d.di_size != 0) || (ip->i_size != 0) ||
1252              (ip->i_d.di_nextents > 0) || (ip->i_delayed_blks > 0)) &&
1253             ((ip->i_d.di_mode & S_IFMT) == S_IFREG));
1254
1255         mp = ip->i_mount;
1256
1257         if (ip->i_d.di_nlink == 0 && DM_EVENT_ENABLED(ip, DM_EVENT_DESTROY))
1258                 XFS_SEND_DESTROY(mp, ip, DM_RIGHT_NULL);
1259
1260         error = 0;
1261
1262         /* If this is a read-only mount, don't do this (would generate I/O) */
1263         if (mp->m_flags & XFS_MOUNT_RDONLY)
1264                 goto out;
1265
1266         if (ip->i_d.di_nlink != 0) {
1267                 if ((((ip->i_d.di_mode & S_IFMT) == S_IFREG) &&
1268                      ((ip->i_size > 0) || (VN_CACHED(VFS_I(ip)) > 0 ||
1269                        ip->i_delayed_blks > 0)) &&
1270                       (ip->i_df.if_flags & XFS_IFEXTENTS) &&
1271                      (!(ip->i_d.di_flags &
1272                                 (XFS_DIFLAG_PREALLOC | XFS_DIFLAG_APPEND)) ||
1273                       (ip->i_delayed_blks != 0)))) {
1274                         error = xfs_free_eofblocks(mp, ip, XFS_FREE_EOF_LOCK);
1275                         if (error)
1276                                 return VN_INACTIVE_CACHE;
1277                 }
1278                 goto out;
1279         }
1280
1281         ASSERT(ip->i_d.di_nlink == 0);
1282
1283         if ((error = XFS_QM_DQATTACH(mp, ip, 0)))
1284                 return VN_INACTIVE_CACHE;
1285
1286         tp = xfs_trans_alloc(mp, XFS_TRANS_INACTIVE);
1287         if (truncate) {
1288                 /*
1289                  * Do the xfs_itruncate_start() call before
1290                  * reserving any log space because itruncate_start
1291                  * will call into the buffer cache and we can't
1292                  * do that within a transaction.
1293                  */
1294                 xfs_ilock(ip, XFS_IOLOCK_EXCL);
1295
1296                 error = xfs_itruncate_start(ip, XFS_ITRUNC_DEFINITE, 0);
1297                 if (error) {
1298                         xfs_trans_cancel(tp, 0);
1299                         xfs_iunlock(ip, XFS_IOLOCK_EXCL);
1300                         return VN_INACTIVE_CACHE;
1301                 }
1302
1303                 error = xfs_trans_reserve(tp, 0,
1304                                           XFS_ITRUNCATE_LOG_RES(mp),
1305                                           0, XFS_TRANS_PERM_LOG_RES,
1306                                           XFS_ITRUNCATE_LOG_COUNT);
1307                 if (error) {
1308                         /* Don't call itruncate_cleanup */
1309                         ASSERT(XFS_FORCED_SHUTDOWN(mp));
1310                         xfs_trans_cancel(tp, 0);
1311                         xfs_iunlock(ip, XFS_IOLOCK_EXCL);
1312                         return VN_INACTIVE_CACHE;
1313                 }
1314
1315                 xfs_ilock(ip, XFS_ILOCK_EXCL);
1316                 xfs_trans_ijoin(tp, ip, XFS_IOLOCK_EXCL | XFS_ILOCK_EXCL);
1317                 xfs_trans_ihold(tp, ip);
1318
1319                 /*
1320                  * normally, we have to run xfs_itruncate_finish sync.
1321                  * But if filesystem is wsync and we're in the inactive
1322                  * path, then we know that nlink == 0, and that the
1323                  * xaction that made nlink == 0 is permanently committed
1324                  * since xfs_remove runs as a synchronous transaction.
1325                  */
1326                 error = xfs_itruncate_finish(&tp, ip, 0, XFS_DATA_FORK,
1327                                 (!(mp->m_flags & XFS_MOUNT_WSYNC) ? 1 : 0));
1328
1329                 if (error) {
1330                         xfs_trans_cancel(tp,
1331                                 XFS_TRANS_RELEASE_LOG_RES | XFS_TRANS_ABORT);
1332                         xfs_iunlock(ip, XFS_IOLOCK_EXCL | XFS_ILOCK_EXCL);
1333                         return VN_INACTIVE_CACHE;
1334                 }
1335         } else if ((ip->i_d.di_mode & S_IFMT) == S_IFLNK) {
1336
1337                 /*
1338                  * If we get an error while cleaning up a
1339                  * symlink we bail out.
1340                  */
1341                 error = (ip->i_d.di_size > XFS_IFORK_DSIZE(ip)) ?
1342                         xfs_inactive_symlink_rmt(ip, &tp) :
1343                         xfs_inactive_symlink_local(ip, &tp);
1344
1345                 if (error) {
1346                         ASSERT(tp == NULL);
1347                         return VN_INACTIVE_CACHE;
1348                 }
1349
1350                 xfs_trans_ijoin(tp, ip, XFS_IOLOCK_EXCL | XFS_ILOCK_EXCL);
1351                 xfs_trans_ihold(tp, ip);
1352         } else {
1353                 error = xfs_trans_reserve(tp, 0,
1354                                           XFS_IFREE_LOG_RES(mp),
1355                                           0, XFS_TRANS_PERM_LOG_RES,
1356                                           XFS_INACTIVE_LOG_COUNT);
1357                 if (error) {
1358                         ASSERT(XFS_FORCED_SHUTDOWN(mp));
1359                         xfs_trans_cancel(tp, 0);
1360                         return VN_INACTIVE_CACHE;
1361                 }
1362
1363                 xfs_ilock(ip, XFS_ILOCK_EXCL | XFS_IOLOCK_EXCL);
1364                 xfs_trans_ijoin(tp, ip, XFS_IOLOCK_EXCL | XFS_ILOCK_EXCL);
1365                 xfs_trans_ihold(tp, ip);
1366         }
1367
1368         /*
1369          * If there are attributes associated with the file
1370          * then blow them away now.  The code calls a routine
1371          * that recursively deconstructs the attribute fork.
1372          * We need to just commit the current transaction
1373          * because we can't use it for xfs_attr_inactive().
1374          */
1375         if (ip->i_d.di_anextents > 0) {
1376                 error = xfs_inactive_attrs(ip, &tp);
1377                 /*
1378                  * If we got an error, the transaction is already
1379                  * cancelled, and the inode is unlocked. Just get out.
1380                  */
1381                  if (error)
1382                          return VN_INACTIVE_CACHE;
1383         } else if (ip->i_afp) {
1384                 xfs_idestroy_fork(ip, XFS_ATTR_FORK);
1385         }
1386
1387         /*
1388          * Free the inode.
1389          */
1390         XFS_BMAP_INIT(&free_list, &first_block);
1391         error = xfs_ifree(tp, ip, &free_list);
1392         if (error) {
1393                 /*
1394                  * If we fail to free the inode, shut down.  The cancel
1395                  * might do that, we need to make sure.  Otherwise the
1396                  * inode might be lost for a long time or forever.
1397                  */
1398                 if (!XFS_FORCED_SHUTDOWN(mp)) {
1399                         cmn_err(CE_NOTE,
1400                 "xfs_inactive:  xfs_ifree() returned an error = %d on %s",
1401                                 error, mp->m_fsname);
1402                         xfs_force_shutdown(mp, SHUTDOWN_META_IO_ERROR);
1403                 }
1404                 xfs_trans_cancel(tp, XFS_TRANS_RELEASE_LOG_RES|XFS_TRANS_ABORT);
1405         } else {
1406                 /*
1407                  * Credit the quota account(s). The inode is gone.
1408                  */
1409                 XFS_TRANS_MOD_DQUOT_BYINO(mp, tp, ip, XFS_TRANS_DQ_ICOUNT, -1);
1410
1411                 /*
1412                  * Just ignore errors at this point.  There is nothing we can
1413                  * do except to try to keep going. Make sure it's not a silent
1414                  * error.
1415                  */
1416                 error = xfs_bmap_finish(&tp,  &free_list, &committed);
1417                 if (error)
1418                         xfs_fs_cmn_err(CE_NOTE, mp, "xfs_inactive: "
1419                                 "xfs_bmap_finish() returned error %d", error);
1420                 error = xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
1421                 if (error)
1422                         xfs_fs_cmn_err(CE_NOTE, mp, "xfs_inactive: "
1423                                 "xfs_trans_commit() returned error %d", error);
1424         }
1425         /*
1426          * Release the dquots held by inode, if any.
1427          */
1428         XFS_QM_DQDETACH(mp, ip);
1429
1430         xfs_iunlock(ip, XFS_IOLOCK_EXCL | XFS_ILOCK_EXCL);
1431
1432  out:
1433         return VN_INACTIVE_CACHE;
1434 }
1435
1436 /*
1437  * Lookups up an inode from "name". If ci_name is not NULL, then a CI match
1438  * is allowed, otherwise it has to be an exact match. If a CI match is found,
1439  * ci_name->name will point to a the actual name (caller must free) or
1440  * will be set to NULL if an exact match is found.
1441  */
1442 int
1443 xfs_lookup(
1444         xfs_inode_t             *dp,
1445         struct xfs_name         *name,
1446         xfs_inode_t             **ipp,
1447         struct xfs_name         *ci_name)
1448 {
1449         xfs_ino_t               inum;
1450         int                     error;
1451         uint                    lock_mode;
1452
1453         xfs_itrace_entry(dp);
1454
1455         if (XFS_FORCED_SHUTDOWN(dp->i_mount))
1456                 return XFS_ERROR(EIO);
1457
1458         lock_mode = xfs_ilock_map_shared(dp);
1459         error = xfs_dir_lookup(NULL, dp, name, &inum, ci_name);
1460         xfs_iunlock_map_shared(dp, lock_mode);
1461
1462         if (error)
1463                 goto out;
1464
1465         error = xfs_iget(dp->i_mount, NULL, inum, 0, 0, ipp, 0);
1466         if (error)
1467                 goto out_free_name;
1468
1469         xfs_itrace_ref(*ipp);
1470         return 0;
1471
1472 out_free_name:
1473         if (ci_name)
1474                 kmem_free(ci_name->name);
1475 out:
1476         *ipp = NULL;
1477         return error;
1478 }
1479
1480 int
1481 xfs_create(
1482         xfs_inode_t             *dp,
1483         struct xfs_name         *name,
1484         mode_t                  mode,
1485         xfs_dev_t               rdev,
1486         xfs_inode_t             **ipp,
1487         cred_t                  *credp)
1488 {
1489         xfs_mount_t             *mp = dp->i_mount;
1490         xfs_inode_t             *ip;
1491         xfs_trans_t             *tp;
1492         int                     error;
1493         xfs_bmap_free_t         free_list;
1494         xfs_fsblock_t           first_block;
1495         boolean_t               unlock_dp_on_error = B_FALSE;
1496         int                     dm_event_sent = 0;
1497         uint                    cancel_flags;
1498         int                     committed;
1499         xfs_prid_t              prid;
1500         struct xfs_dquot        *udqp, *gdqp;
1501         uint                    resblks;
1502
1503         ASSERT(!*ipp);
1504         xfs_itrace_entry(dp);
1505
1506         if (DM_EVENT_ENABLED(dp, DM_EVENT_CREATE)) {
1507                 error = XFS_SEND_NAMESP(mp, DM_EVENT_CREATE,
1508                                 dp, DM_RIGHT_NULL, NULL,
1509                                 DM_RIGHT_NULL, name->name, NULL,
1510                                 mode, 0, 0);
1511
1512                 if (error)
1513                         return error;
1514                 dm_event_sent = 1;
1515         }
1516
1517         if (XFS_FORCED_SHUTDOWN(mp))
1518                 return XFS_ERROR(EIO);
1519
1520         /* Return through std_return after this point. */
1521
1522         udqp = gdqp = NULL;
1523         if (dp->i_d.di_flags & XFS_DIFLAG_PROJINHERIT)
1524                 prid = dp->i_d.di_projid;
1525         else
1526                 prid = (xfs_prid_t)dfltprid;
1527
1528         /*
1529          * Make sure that we have allocated dquot(s) on disk.
1530          */
1531         error = XFS_QM_DQVOPALLOC(mp, dp,
1532                         current_fsuid(), current_fsgid(), prid,
1533                         XFS_QMOPT_QUOTALL|XFS_QMOPT_INHERIT, &udqp, &gdqp);
1534         if (error)
1535                 goto std_return;
1536
1537         ip = NULL;
1538
1539         tp = xfs_trans_alloc(mp, XFS_TRANS_CREATE);
1540         cancel_flags = XFS_TRANS_RELEASE_LOG_RES;
1541         resblks = XFS_CREATE_SPACE_RES(mp, name->len);
1542         /*
1543          * Initially assume that the file does not exist and
1544          * reserve the resources for that case.  If that is not
1545          * the case we'll drop the one we have and get a more
1546          * appropriate transaction later.
1547          */
1548         error = xfs_trans_reserve(tp, resblks, XFS_CREATE_LOG_RES(mp), 0,
1549                         XFS_TRANS_PERM_LOG_RES, XFS_CREATE_LOG_COUNT);
1550         if (error == ENOSPC) {
1551                 resblks = 0;
1552                 error = xfs_trans_reserve(tp, 0, XFS_CREATE_LOG_RES(mp), 0,
1553                                 XFS_TRANS_PERM_LOG_RES, XFS_CREATE_LOG_COUNT);
1554         }
1555         if (error) {
1556                 cancel_flags = 0;
1557                 goto error_return;
1558         }
1559
1560         xfs_ilock(dp, XFS_ILOCK_EXCL | XFS_ILOCK_PARENT);
1561         unlock_dp_on_error = B_TRUE;
1562
1563         XFS_BMAP_INIT(&free_list, &first_block);
1564
1565         ASSERT(ip == NULL);
1566
1567         /*
1568          * Reserve disk quota and the inode.
1569          */
1570         error = XFS_TRANS_RESERVE_QUOTA(mp, tp, udqp, gdqp, resblks, 1, 0);
1571         if (error)
1572                 goto error_return;
1573
1574         error = xfs_dir_canenter(tp, dp, name, resblks);
1575         if (error)
1576                 goto error_return;
1577         error = xfs_dir_ialloc(&tp, dp, mode, 1,
1578                         rdev, credp, prid, resblks > 0,
1579                         &ip, &committed);
1580         if (error) {
1581                 if (error == ENOSPC)
1582                         goto error_return;
1583                 goto abort_return;
1584         }
1585         xfs_itrace_ref(ip);
1586
1587         /*
1588          * At this point, we've gotten a newly allocated inode.
1589          * It is locked (and joined to the transaction).
1590          */
1591
1592         ASSERT(xfs_isilocked(ip, XFS_ILOCK_EXCL));
1593
1594         /*
1595          * Now we join the directory inode to the transaction.  We do not do it
1596          * earlier because xfs_dir_ialloc might commit the previous transaction
1597          * (and release all the locks).  An error from here on will result in
1598          * the transaction cancel unlocking dp so don't do it explicitly in the
1599          * error path.
1600          */
1601         IHOLD(dp);
1602         xfs_trans_ijoin(tp, dp, XFS_ILOCK_EXCL);
1603         unlock_dp_on_error = B_FALSE;
1604
1605         error = xfs_dir_createname(tp, dp, name, ip->i_ino,
1606                                         &first_block, &free_list, resblks ?
1607                                         resblks - XFS_IALLOC_SPACE_RES(mp) : 0);
1608         if (error) {
1609                 ASSERT(error != ENOSPC);
1610                 goto abort_return;
1611         }
1612         xfs_ichgtime(dp, XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG);
1613         xfs_trans_log_inode(tp, dp, XFS_ILOG_CORE);
1614
1615         /*
1616          * If this is a synchronous mount, make sure that the
1617          * create transaction goes to disk before returning to
1618          * the user.
1619          */
1620         if (mp->m_flags & (XFS_MOUNT_WSYNC|XFS_MOUNT_DIRSYNC)) {
1621                 xfs_trans_set_sync(tp);
1622         }
1623
1624         dp->i_gen++;
1625
1626         /*
1627          * Attach the dquot(s) to the inodes and modify them incore.
1628          * These ids of the inode couldn't have changed since the new
1629          * inode has been locked ever since it was created.
1630          */
1631         XFS_QM_DQVOPCREATE(mp, tp, ip, udqp, gdqp);
1632
1633         /*
1634          * xfs_trans_commit normally decrements the vnode ref count
1635          * when it unlocks the inode. Since we want to return the
1636          * vnode to the caller, we bump the vnode ref count now.
1637          */
1638         IHOLD(ip);
1639
1640         error = xfs_bmap_finish(&tp, &free_list, &committed);
1641         if (error) {
1642                 xfs_bmap_cancel(&free_list);
1643                 goto abort_rele;
1644         }
1645
1646         error = xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
1647         if (error) {
1648                 IRELE(ip);
1649                 tp = NULL;
1650                 goto error_return;
1651         }
1652
1653         XFS_QM_DQRELE(mp, udqp);
1654         XFS_QM_DQRELE(mp, gdqp);
1655
1656         *ipp = ip;
1657
1658         /* Fallthrough to std_return with error = 0  */
1659
1660 std_return:
1661         if ((*ipp || (error != 0 && dm_event_sent != 0)) &&
1662             DM_EVENT_ENABLED(dp, DM_EVENT_POSTCREATE)) {
1663                 (void) XFS_SEND_NAMESP(mp, DM_EVENT_POSTCREATE,
1664                         dp, DM_RIGHT_NULL,
1665                         *ipp ? ip : NULL,
1666                         DM_RIGHT_NULL, name->name, NULL,
1667                         mode, error, 0);
1668         }
1669         return error;
1670
1671  abort_return:
1672         cancel_flags |= XFS_TRANS_ABORT;
1673         /* FALLTHROUGH */
1674
1675  error_return:
1676         if (tp != NULL)
1677                 xfs_trans_cancel(tp, cancel_flags);
1678
1679         XFS_QM_DQRELE(mp, udqp);
1680         XFS_QM_DQRELE(mp, gdqp);
1681
1682         if (unlock_dp_on_error)
1683                 xfs_iunlock(dp, XFS_ILOCK_EXCL);
1684
1685         goto std_return;
1686
1687  abort_rele:
1688         /*
1689          * Wait until after the current transaction is aborted to
1690          * release the inode.  This prevents recursive transactions
1691          * and deadlocks from xfs_inactive.
1692          */
1693         cancel_flags |= XFS_TRANS_ABORT;
1694         xfs_trans_cancel(tp, cancel_flags);
1695         IRELE(ip);
1696
1697         XFS_QM_DQRELE(mp, udqp);
1698         XFS_QM_DQRELE(mp, gdqp);
1699
1700         goto std_return;
1701 }
1702
1703 #ifdef DEBUG
1704 int xfs_locked_n;
1705 int xfs_small_retries;
1706 int xfs_middle_retries;
1707 int xfs_lots_retries;
1708 int xfs_lock_delays;
1709 #endif
1710
1711 /*
1712  * Bump the subclass so xfs_lock_inodes() acquires each lock with
1713  * a different value
1714  */
1715 static inline int
1716 xfs_lock_inumorder(int lock_mode, int subclass)
1717 {
1718         if (lock_mode & (XFS_IOLOCK_SHARED|XFS_IOLOCK_EXCL))
1719                 lock_mode |= (subclass + XFS_LOCK_INUMORDER) << XFS_IOLOCK_SHIFT;
1720         if (lock_mode & (XFS_ILOCK_SHARED|XFS_ILOCK_EXCL))
1721                 lock_mode |= (subclass + XFS_LOCK_INUMORDER) << XFS_ILOCK_SHIFT;
1722
1723         return lock_mode;
1724 }
1725
1726 /*
1727  * The following routine will lock n inodes in exclusive mode.
1728  * We assume the caller calls us with the inodes in i_ino order.
1729  *
1730  * We need to detect deadlock where an inode that we lock
1731  * is in the AIL and we start waiting for another inode that is locked
1732  * by a thread in a long running transaction (such as truncate). This can
1733  * result in deadlock since the long running trans might need to wait
1734  * for the inode we just locked in order to push the tail and free space
1735  * in the log.
1736  */
1737 void
1738 xfs_lock_inodes(
1739         xfs_inode_t     **ips,
1740         int             inodes,
1741         uint            lock_mode)
1742 {
1743         int             attempts = 0, i, j, try_lock;
1744         xfs_log_item_t  *lp;
1745
1746         ASSERT(ips && (inodes >= 2)); /* we need at least two */
1747
1748         try_lock = 0;
1749         i = 0;
1750
1751 again:
1752         for (; i < inodes; i++) {
1753                 ASSERT(ips[i]);
1754
1755                 if (i && (ips[i] == ips[i-1]))  /* Already locked */
1756                         continue;
1757
1758                 /*
1759                  * If try_lock is not set yet, make sure all locked inodes
1760                  * are not in the AIL.
1761                  * If any are, set try_lock to be used later.
1762                  */
1763
1764                 if (!try_lock) {
1765                         for (j = (i - 1); j >= 0 && !try_lock; j--) {
1766                                 lp = (xfs_log_item_t *)ips[j]->i_itemp;
1767                                 if (lp && (lp->li_flags & XFS_LI_IN_AIL)) {
1768                                         try_lock++;
1769                                 }
1770                         }
1771                 }
1772
1773                 /*
1774                  * If any of the previous locks we have locked is in the AIL,
1775                  * we must TRY to get the second and subsequent locks. If
1776                  * we can't get any, we must release all we have
1777                  * and try again.
1778                  */
1779
1780                 if (try_lock) {
1781                         /* try_lock must be 0 if i is 0. */
1782                         /*
1783                          * try_lock means we have an inode locked
1784                          * that is in the AIL.
1785                          */
1786                         ASSERT(i != 0);
1787                         if (!xfs_ilock_nowait(ips[i], xfs_lock_inumorder(lock_mode, i))) {
1788                                 attempts++;
1789
1790                                 /*
1791                                  * Unlock all previous guys and try again.
1792                                  * xfs_iunlock will try to push the tail
1793                                  * if the inode is in the AIL.
1794                                  */
1795
1796                                 for(j = i - 1; j >= 0; j--) {
1797
1798                                         /*
1799                                          * Check to see if we've already
1800                                          * unlocked this one.
1801                                          * Not the first one going back,
1802                                          * and the inode ptr is the same.
1803                                          */
1804                                         if ((j != (i - 1)) && ips[j] ==
1805                                                                 ips[j+1])
1806                                                 continue;
1807
1808                                         xfs_iunlock(ips[j], lock_mode);
1809                                 }
1810
1811                                 if ((attempts % 5) == 0) {
1812                                         delay(1); /* Don't just spin the CPU */
1813 #ifdef DEBUG
1814                                         xfs_lock_delays++;
1815 #endif
1816                                 }
1817                                 i = 0;
1818                                 try_lock = 0;
1819                                 goto again;
1820                         }
1821                 } else {
1822                         xfs_ilock(ips[i], xfs_lock_inumorder(lock_mode, i));
1823                 }
1824         }
1825
1826 #ifdef DEBUG
1827         if (attempts) {
1828                 if (attempts < 5) xfs_small_retries++;
1829                 else if (attempts < 100) xfs_middle_retries++;
1830                 else xfs_lots_retries++;
1831         } else {
1832                 xfs_locked_n++;
1833         }
1834 #endif
1835 }
1836
1837 /*
1838  * xfs_lock_two_inodes() can only be used to lock one type of lock
1839  * at a time - the iolock or the ilock, but not both at once. If
1840  * we lock both at once, lockdep will report false positives saying
1841  * we have violated locking orders.
1842  */
1843 void
1844 xfs_lock_two_inodes(
1845         xfs_inode_t             *ip0,
1846         xfs_inode_t             *ip1,
1847         uint                    lock_mode)
1848 {
1849         xfs_inode_t             *temp;
1850         int                     attempts = 0;
1851         xfs_log_item_t          *lp;
1852
1853         if (lock_mode & (XFS_IOLOCK_SHARED|XFS_IOLOCK_EXCL))
1854                 ASSERT((lock_mode & (XFS_ILOCK_SHARED|XFS_ILOCK_EXCL)) == 0);
1855         ASSERT(ip0->i_ino != ip1->i_ino);
1856
1857         if (ip0->i_ino > ip1->i_ino) {
1858                 temp = ip0;
1859                 ip0 = ip1;
1860                 ip1 = temp;
1861         }
1862
1863  again:
1864         xfs_ilock(ip0, xfs_lock_inumorder(lock_mode, 0));
1865
1866         /*
1867          * If the first lock we have locked is in the AIL, we must TRY to get
1868          * the second lock. If we can't get it, we must release the first one
1869          * and try again.
1870          */
1871         lp = (xfs_log_item_t *)ip0->i_itemp;
1872         if (lp && (lp->li_flags & XFS_LI_IN_AIL)) {
1873                 if (!xfs_ilock_nowait(ip1, xfs_lock_inumorder(lock_mode, 1))) {
1874                         xfs_iunlock(ip0, lock_mode);
1875                         if ((++attempts % 5) == 0)
1876                                 delay(1); /* Don't just spin the CPU */
1877                         goto again;
1878                 }
1879         } else {
1880                 xfs_ilock(ip1, xfs_lock_inumorder(lock_mode, 1));
1881         }
1882 }
1883
1884 int
1885 xfs_remove(
1886         xfs_inode_t             *dp,
1887         struct xfs_name         *name,
1888         xfs_inode_t             *ip)
1889 {
1890         xfs_mount_t             *mp = dp->i_mount;
1891         xfs_trans_t             *tp = NULL;
1892         int                     is_dir = S_ISDIR(ip->i_d.di_mode);
1893         int                     error = 0;
1894         xfs_bmap_free_t         free_list;
1895         xfs_fsblock_t           first_block;
1896         int                     cancel_flags;
1897         int                     committed;
1898         int                     link_zero;
1899         uint                    resblks;
1900         uint                    log_count;
1901
1902         xfs_itrace_entry(dp);
1903         xfs_itrace_entry(ip);
1904
1905         if (XFS_FORCED_SHUTDOWN(mp))
1906                 return XFS_ERROR(EIO);
1907
1908         if (DM_EVENT_ENABLED(dp, DM_EVENT_REMOVE)) {
1909                 error = XFS_SEND_NAMESP(mp, DM_EVENT_REMOVE, dp, DM_RIGHT_NULL,
1910                                         NULL, DM_RIGHT_NULL, name->name, NULL,
1911                                         ip->i_d.di_mode, 0, 0);
1912                 if (error)
1913                         return error;
1914         }
1915
1916         error = XFS_QM_DQATTACH(mp, dp, 0);
1917         if (error)
1918                 goto std_return;
1919
1920         error = XFS_QM_DQATTACH(mp, ip, 0);
1921         if (error)
1922                 goto std_return;
1923
1924         if (is_dir) {
1925                 tp = xfs_trans_alloc(mp, XFS_TRANS_RMDIR);
1926                 log_count = XFS_DEFAULT_LOG_COUNT;
1927         } else {
1928                 tp = xfs_trans_alloc(mp, XFS_TRANS_REMOVE);
1929                 log_count = XFS_REMOVE_LOG_COUNT;
1930         }
1931         cancel_flags = XFS_TRANS_RELEASE_LOG_RES;
1932
1933         /*
1934          * We try to get the real space reservation first,
1935          * allowing for directory btree deletion(s) implying
1936          * possible bmap insert(s).  If we can't get the space
1937          * reservation then we use 0 instead, and avoid the bmap
1938          * btree insert(s) in the directory code by, if the bmap
1939          * insert tries to happen, instead trimming the LAST
1940          * block from the directory.
1941          */
1942         resblks = XFS_REMOVE_SPACE_RES(mp);
1943         error = xfs_trans_reserve(tp, resblks, XFS_REMOVE_LOG_RES(mp), 0,
1944                                   XFS_TRANS_PERM_LOG_RES, log_count);
1945         if (error == ENOSPC) {
1946                 resblks = 0;
1947                 error = xfs_trans_reserve(tp, 0, XFS_REMOVE_LOG_RES(mp), 0,
1948                                           XFS_TRANS_PERM_LOG_RES, log_count);
1949         }
1950         if (error) {
1951                 ASSERT(error != ENOSPC);
1952                 cancel_flags = 0;
1953                 goto out_trans_cancel;
1954         }
1955
1956         xfs_lock_two_inodes(dp, ip, XFS_ILOCK_EXCL);
1957
1958         /*
1959          * At this point, we've gotten both the directory and the entry
1960          * inodes locked.
1961          */
1962         IHOLD(ip);
1963         xfs_trans_ijoin(tp, dp, XFS_ILOCK_EXCL);
1964
1965         IHOLD(dp);
1966         xfs_trans_ijoin(tp, ip, XFS_ILOCK_EXCL);
1967
1968         /*
1969          * If we're removing a directory perform some additional validation.
1970          */
1971         if (is_dir) {
1972                 ASSERT(ip->i_d.di_nlink >= 2);
1973                 if (ip->i_d.di_nlink != 2) {
1974                         error = XFS_ERROR(ENOTEMPTY);
1975                         goto out_trans_cancel;
1976                 }
1977                 if (!xfs_dir_isempty(ip)) {
1978                         error = XFS_ERROR(ENOTEMPTY);
1979                         goto out_trans_cancel;
1980                 }
1981         }
1982
1983         XFS_BMAP_INIT(&free_list, &first_block);
1984         error = xfs_dir_removename(tp, dp, name, ip->i_ino,
1985                                         &first_block, &free_list, resblks);
1986         if (error) {
1987                 ASSERT(error != ENOENT);
1988                 goto out_bmap_cancel;
1989         }
1990         xfs_ichgtime(dp, XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG);
1991
1992         /*
1993          * Bump the in memory generation count on the parent
1994          * directory so that other can know that it has changed.
1995          */
1996         dp->i_gen++;
1997         xfs_trans_log_inode(tp, dp, XFS_ILOG_CORE);
1998
1999         if (is_dir) {
2000                 /*
2001                  * Drop the link from ip's "..".
2002                  */
2003                 error = xfs_droplink(tp, dp);
2004                 if (error)
2005                         goto out_bmap_cancel;
2006
2007                 /*
2008                  * Drop the "." link from ip to self.
2009                  */
2010                 error = xfs_droplink(tp, ip);
2011                 if (error)
2012                         goto out_bmap_cancel;
2013         } else {
2014                 /*
2015                  * When removing a non-directory we need to log the parent
2016                  * inode here for the i_gen update.  For a directory this is
2017                  * done implicitly by the xfs_droplink call for the ".." entry.
2018                  */
2019                 xfs_trans_log_inode(tp, dp, XFS_ILOG_CORE);
2020         }
2021
2022         /*
2023          * Drop the link from dp to ip.
2024          */
2025         error = xfs_droplink(tp, ip);
2026         if (error)
2027                 goto out_bmap_cancel;
2028
2029         /*
2030          * Determine if this is the last link while
2031          * we are in the transaction.
2032          */
2033         link_zero = (ip->i_d.di_nlink == 0);
2034
2035         /*
2036          * If this is a synchronous mount, make sure that the
2037          * remove transaction goes to disk before returning to
2038          * the user.
2039          */
2040         if (mp->m_flags & (XFS_MOUNT_WSYNC|XFS_MOUNT_DIRSYNC))
2041                 xfs_trans_set_sync(tp);
2042
2043         error = xfs_bmap_finish(&tp, &free_list, &committed);
2044         if (error)
2045                 goto out_bmap_cancel;
2046
2047         error = xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
2048         if (error)
2049                 goto std_return;
2050
2051         /*
2052          * If we are using filestreams, kill the stream association.
2053          * If the file is still open it may get a new one but that
2054          * will get killed on last close in xfs_close() so we don't
2055          * have to worry about that.
2056          */
2057         if (!is_dir && link_zero && xfs_inode_is_filestream(ip))
2058                 xfs_filestream_deassociate(ip);
2059
2060         xfs_itrace_exit(ip);
2061         xfs_itrace_exit(dp);
2062
2063  std_return:
2064         if (DM_EVENT_ENABLED(dp, DM_EVENT_POSTREMOVE)) {
2065                 XFS_SEND_NAMESP(mp, DM_EVENT_POSTREMOVE, dp, DM_RIGHT_NULL,
2066                                 NULL, DM_RIGHT_NULL, name->name, NULL,
2067                                 ip->i_d.di_mode, error, 0);
2068         }
2069
2070         return error;
2071
2072  out_bmap_cancel:
2073         xfs_bmap_cancel(&free_list);
2074         cancel_flags |= XFS_TRANS_ABORT;
2075  out_trans_cancel:
2076         xfs_trans_cancel(tp, cancel_flags);
2077         goto std_return;
2078 }
2079
2080 int
2081 xfs_link(
2082         xfs_inode_t             *tdp,
2083         xfs_inode_t             *sip,
2084         struct xfs_name         *target_name)
2085 {
2086         xfs_mount_t             *mp = tdp->i_mount;
2087         xfs_trans_t             *tp;
2088         int                     error;
2089         xfs_bmap_free_t         free_list;
2090         xfs_fsblock_t           first_block;
2091         int                     cancel_flags;
2092         int                     committed;
2093         int                     resblks;
2094
2095         xfs_itrace_entry(tdp);
2096         xfs_itrace_entry(sip);
2097
2098         ASSERT(!S_ISDIR(sip->i_d.di_mode));
2099
2100         if (XFS_FORCED_SHUTDOWN(mp))
2101                 return XFS_ERROR(EIO);
2102
2103         if (DM_EVENT_ENABLED(tdp, DM_EVENT_LINK)) {
2104                 error = XFS_SEND_NAMESP(mp, DM_EVENT_LINK,
2105                                         tdp, DM_RIGHT_NULL,
2106                                         sip, DM_RIGHT_NULL,
2107                                         target_name->name, NULL, 0, 0, 0);
2108                 if (error)
2109                         return error;
2110         }
2111
2112         /* Return through std_return after this point. */
2113
2114         error = XFS_QM_DQATTACH(mp, sip, 0);
2115         if (!error && sip != tdp)
2116                 error = XFS_QM_DQATTACH(mp, tdp, 0);
2117         if (error)
2118                 goto std_return;
2119
2120         tp = xfs_trans_alloc(mp, XFS_TRANS_LINK);
2121         cancel_flags = XFS_TRANS_RELEASE_LOG_RES;
2122         resblks = XFS_LINK_SPACE_RES(mp, target_name->len);
2123         error = xfs_trans_reserve(tp, resblks, XFS_LINK_LOG_RES(mp), 0,
2124                         XFS_TRANS_PERM_LOG_RES, XFS_LINK_LOG_COUNT);
2125         if (error == ENOSPC) {
2126                 resblks = 0;
2127                 error = xfs_trans_reserve(tp, 0, XFS_LINK_LOG_RES(mp), 0,
2128                                 XFS_TRANS_PERM_LOG_RES, XFS_LINK_LOG_COUNT);
2129         }
2130         if (error) {
2131                 cancel_flags = 0;
2132                 goto error_return;
2133         }
2134
2135         xfs_lock_two_inodes(sip, tdp, XFS_ILOCK_EXCL);
2136
2137         /*
2138          * Increment vnode ref counts since xfs_trans_commit &
2139          * xfs_trans_cancel will both unlock the inodes and
2140          * decrement the associated ref counts.
2141          */
2142         IHOLD(sip);
2143         IHOLD(tdp);
2144         xfs_trans_ijoin(tp, sip, XFS_ILOCK_EXCL);
2145         xfs_trans_ijoin(tp, tdp, XFS_ILOCK_EXCL);
2146
2147         /*
2148          * If the source has too many links, we can't make any more to it.
2149          */
2150         if (sip->i_d.di_nlink >= XFS_MAXLINK) {
2151                 error = XFS_ERROR(EMLINK);
2152                 goto error_return;
2153         }
2154
2155         /*
2156          * If we are using project inheritance, we only allow hard link
2157          * creation in our tree when the project IDs are the same; else
2158          * the tree quota mechanism could be circumvented.
2159          */
2160         if (unlikely((tdp->i_d.di_flags & XFS_DIFLAG_PROJINHERIT) &&
2161                      (tdp->i_d.di_projid != sip->i_d.di_projid))) {
2162                 error = XFS_ERROR(EXDEV);
2163                 goto error_return;
2164         }
2165
2166         error = xfs_dir_canenter(tp, tdp, target_name, resblks);
2167         if (error)
2168                 goto error_return;
2169
2170         XFS_BMAP_INIT(&free_list, &first_block);
2171
2172         error = xfs_dir_createname(tp, tdp, target_name, sip->i_ino,
2173                                         &first_block, &free_list, resblks);
2174         if (error)
2175                 goto abort_return;
2176         xfs_ichgtime(tdp, XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG);
2177         tdp->i_gen++;
2178         xfs_trans_log_inode(tp, tdp, XFS_ILOG_CORE);
2179
2180         error = xfs_bumplink(tp, sip);
2181         if (error)
2182                 goto abort_return;
2183
2184         /*
2185          * If this is a synchronous mount, make sure that the
2186          * link transaction goes to disk before returning to
2187          * the user.
2188          */
2189         if (mp->m_flags & (XFS_MOUNT_WSYNC|XFS_MOUNT_DIRSYNC)) {
2190                 xfs_trans_set_sync(tp);
2191         }
2192
2193         error = xfs_bmap_finish (&tp, &free_list, &committed);
2194         if (error) {
2195                 xfs_bmap_cancel(&free_list);
2196                 goto abort_return;
2197         }
2198
2199         error = xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
2200         if (error)
2201                 goto std_return;
2202
2203         /* Fall through to std_return with error = 0. */
2204 std_return:
2205         if (DM_EVENT_ENABLED(sip, DM_EVENT_POSTLINK)) {
2206                 (void) XFS_SEND_NAMESP(mp, DM_EVENT_POSTLINK,
2207                                 tdp, DM_RIGHT_NULL,
2208                                 sip, DM_RIGHT_NULL,
2209                                 target_name->name, NULL, 0, error, 0);
2210         }
2211         return error;
2212
2213  abort_return:
2214         cancel_flags |= XFS_TRANS_ABORT;
2215         /* FALLTHROUGH */
2216
2217  error_return:
2218         xfs_trans_cancel(tp, cancel_flags);
2219         goto std_return;
2220 }
2221
2222
2223 int
2224 xfs_mkdir(
2225         xfs_inode_t             *dp,
2226         struct xfs_name         *dir_name,
2227         mode_t                  mode,
2228         xfs_inode_t             **ipp,
2229         cred_t                  *credp)
2230 {
2231         xfs_mount_t             *mp = dp->i_mount;
2232         xfs_inode_t             *cdp;   /* inode of created dir */
2233         xfs_trans_t             *tp;
2234         int                     cancel_flags;
2235         int                     error;
2236         int                     committed;
2237         xfs_bmap_free_t         free_list;
2238         xfs_fsblock_t           first_block;
2239         boolean_t               unlock_dp_on_error = B_FALSE;
2240         boolean_t               created = B_FALSE;
2241         int                     dm_event_sent = 0;
2242         xfs_prid_t              prid;
2243         struct xfs_dquot        *udqp, *gdqp;
2244         uint                    resblks;
2245
2246         if (XFS_FORCED_SHUTDOWN(mp))
2247                 return XFS_ERROR(EIO);
2248
2249         tp = NULL;
2250
2251         if (DM_EVENT_ENABLED(dp, DM_EVENT_CREATE)) {
2252                 error = XFS_SEND_NAMESP(mp, DM_EVENT_CREATE,
2253                                         dp, DM_RIGHT_NULL, NULL,
2254                                         DM_RIGHT_NULL, dir_name->name, NULL,
2255                                         mode, 0, 0);
2256                 if (error)
2257                         return error;
2258                 dm_event_sent = 1;
2259         }
2260
2261         /* Return through std_return after this point. */
2262
2263         xfs_itrace_entry(dp);
2264
2265         mp = dp->i_mount;
2266         udqp = gdqp = NULL;
2267         if (dp->i_d.di_flags & XFS_DIFLAG_PROJINHERIT)
2268                 prid = dp->i_d.di_projid;
2269         else
2270                 prid = (xfs_prid_t)dfltprid;
2271
2272         /*
2273          * Make sure that we have allocated dquot(s) on disk.
2274          */
2275         error = XFS_QM_DQVOPALLOC(mp, dp,
2276                         current_fsuid(), current_fsgid(), prid,
2277                         XFS_QMOPT_QUOTALL | XFS_QMOPT_INHERIT, &udqp, &gdqp);
2278         if (error)
2279                 goto std_return;
2280
2281         tp = xfs_trans_alloc(mp, XFS_TRANS_MKDIR);
2282         cancel_flags = XFS_TRANS_RELEASE_LOG_RES;
2283         resblks = XFS_MKDIR_SPACE_RES(mp, dir_name->len);
2284         error = xfs_trans_reserve(tp, resblks, XFS_MKDIR_LOG_RES(mp), 0,
2285                                   XFS_TRANS_PERM_LOG_RES, XFS_MKDIR_LOG_COUNT);
2286         if (error == ENOSPC) {
2287                 resblks = 0;
2288                 error = xfs_trans_reserve(tp, 0, XFS_MKDIR_LOG_RES(mp), 0,
2289                                           XFS_TRANS_PERM_LOG_RES,
2290                                           XFS_MKDIR_LOG_COUNT);
2291         }
2292         if (error) {
2293                 cancel_flags = 0;
2294                 goto error_return;
2295         }
2296
2297         xfs_ilock(dp, XFS_ILOCK_EXCL | XFS_ILOCK_PARENT);
2298         unlock_dp_on_error = B_TRUE;
2299
2300         /*
2301          * Check for directory link count overflow.
2302          */
2303         if (dp->i_d.di_nlink >= XFS_MAXLINK) {
2304                 error = XFS_ERROR(EMLINK);
2305                 goto error_return;
2306         }
2307
2308         /*
2309          * Reserve disk quota and the inode.
2310          */
2311         error = XFS_TRANS_RESERVE_QUOTA(mp, tp, udqp, gdqp, resblks, 1, 0);
2312         if (error)
2313                 goto error_return;
2314
2315         error = xfs_dir_canenter(tp, dp, dir_name, resblks);
2316         if (error)
2317                 goto error_return;
2318         /*
2319          * create the directory inode.
2320          */
2321         error = xfs_dir_ialloc(&tp, dp, mode, 2,
2322                         0, credp, prid, resblks > 0,
2323                 &cdp, NULL);
2324         if (error) {
2325                 if (error == ENOSPC)
2326                         goto error_return;
2327                 goto abort_return;
2328         }
2329         xfs_itrace_ref(cdp);
2330
2331         /*
2332          * Now we add the directory inode to the transaction.
2333          * We waited until now since xfs_dir_ialloc might start
2334          * a new transaction.  Had we joined the transaction
2335          * earlier, the locks might have gotten released. An error
2336          * from here on will result in the transaction cancel
2337          * unlocking dp so don't do it explicitly in the error path.
2338          */
2339         IHOLD(dp);
2340         xfs_trans_ijoin(tp, dp, XFS_ILOCK_EXCL);
2341         unlock_dp_on_error = B_FALSE;
2342
2343         XFS_BMAP_INIT(&free_list, &first_block);
2344
2345         error = xfs_dir_createname(tp, dp, dir_name, cdp->i_ino,
2346                                         &first_block, &free_list, resblks ?
2347                                         resblks - XFS_IALLOC_SPACE_RES(mp) : 0);
2348         if (error) {
2349                 ASSERT(error != ENOSPC);
2350                 goto error1;
2351         }
2352         xfs_ichgtime(dp, XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG);
2353
2354         /*
2355          * Bump the in memory version number of the parent directory
2356          * so that other processes accessing it will recognize that
2357          * the directory has changed.
2358          */
2359         dp->i_gen++;
2360
2361         error = xfs_dir_init(tp, cdp, dp);
2362         if (error)
2363                 goto error2;
2364
2365         cdp->i_gen = 1;
2366         error = xfs_bumplink(tp, dp);
2367         if (error)
2368                 goto error2;
2369
2370         created = B_TRUE;
2371
2372         *ipp = cdp;
2373         IHOLD(cdp);
2374
2375         /*
2376          * Attach the dquots to the new inode and modify the icount incore.
2377          */
2378         XFS_QM_DQVOPCREATE(mp, tp, cdp, udqp, gdqp);
2379
2380         /*
2381          * If this is a synchronous mount, make sure that the
2382          * mkdir transaction goes to disk before returning to
2383          * the user.
2384          */
2385         if (mp->m_flags & (XFS_MOUNT_WSYNC|XFS_MOUNT_DIRSYNC)) {
2386                 xfs_trans_set_sync(tp);
2387         }
2388
2389         error = xfs_bmap_finish(&tp, &free_list, &committed);
2390         if (error) {
2391                 IRELE(cdp);
2392                 goto error2;
2393         }
2394
2395         error = xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
2396         XFS_QM_DQRELE(mp, udqp);
2397         XFS_QM_DQRELE(mp, gdqp);
2398         if (error) {
2399                 IRELE(cdp);
2400         }
2401
2402         /* Fall through to std_return with error = 0 or errno from
2403          * xfs_trans_commit. */
2404
2405 std_return:
2406         if ((created || (error != 0 && dm_event_sent != 0)) &&
2407             DM_EVENT_ENABLED(dp, DM_EVENT_POSTCREATE)) {
2408                 (void) XFS_SEND_NAMESP(mp, DM_EVENT_POSTCREATE,
2409                                         dp, DM_RIGHT_NULL,
2410                                         created ? cdp : NULL,
2411                                         DM_RIGHT_NULL,
2412                                         dir_name->name, NULL,
2413                                         mode, error, 0);
2414         }
2415         return error;
2416
2417  error2:
2418  error1:
2419         xfs_bmap_cancel(&free_list);
2420  abort_return:
2421         cancel_flags |= XFS_TRANS_ABORT;
2422  error_return:
2423         xfs_trans_cancel(tp, cancel_flags);
2424         XFS_QM_DQRELE(mp, udqp);
2425         XFS_QM_DQRELE(mp, gdqp);
2426
2427         if (unlock_dp_on_error)
2428                 xfs_iunlock(dp, XFS_ILOCK_EXCL);
2429
2430         goto std_return;
2431 }
2432
2433 int
2434 xfs_symlink(
2435         xfs_inode_t             *dp,
2436         struct xfs_name         *link_name,
2437         const char              *target_path,
2438         mode_t                  mode,
2439         xfs_inode_t             **ipp,
2440         cred_t                  *credp)
2441 {
2442         xfs_mount_t             *mp = dp->i_mount;
2443         xfs_trans_t             *tp;
2444         xfs_inode_t             *ip;
2445         int                     error;
2446         int                     pathlen;
2447         xfs_bmap_free_t         free_list;
2448         xfs_fsblock_t           first_block;
2449         boolean_t               unlock_dp_on_error = B_FALSE;
2450         uint                    cancel_flags;
2451         int                     committed;
2452         xfs_fileoff_t           first_fsb;
2453         xfs_filblks_t           fs_blocks;
2454         int                     nmaps;
2455         xfs_bmbt_irec_t         mval[SYMLINK_MAPS];
2456         xfs_daddr_t             d;
2457         const char              *cur_chunk;
2458         int                     byte_cnt;
2459         int                     n;
2460         xfs_buf_t               *bp;
2461         xfs_prid_t              prid;
2462         struct xfs_dquot        *udqp, *gdqp;
2463         uint                    resblks;
2464
2465         *ipp = NULL;
2466         error = 0;
2467         ip = NULL;
2468         tp = NULL;
2469
2470         xfs_itrace_entry(dp);
2471
2472         if (XFS_FORCED_SHUTDOWN(mp))
2473                 return XFS_ERROR(EIO);
2474
2475         /*
2476          * Check component lengths of the target path name.
2477          */
2478         pathlen = strlen(target_path);
2479         if (pathlen >= MAXPATHLEN)      /* total string too long */
2480                 return XFS_ERROR(ENAMETOOLONG);
2481
2482         if (DM_EVENT_ENABLED(dp, DM_EVENT_SYMLINK)) {
2483                 error = XFS_SEND_NAMESP(mp, DM_EVENT_SYMLINK, dp,
2484                                         DM_RIGHT_NULL, NULL, DM_RIGHT_NULL,
2485                                         link_name->name, target_path, 0, 0, 0);
2486                 if (error)
2487                         return error;
2488         }
2489
2490         /* Return through std_return after this point. */
2491
2492         udqp = gdqp = NULL;
2493         if (dp->i_d.di_flags & XFS_DIFLAG_PROJINHERIT)
2494                 prid = dp->i_d.di_projid;
2495         else
2496                 prid = (xfs_prid_t)dfltprid;
2497
2498         /*
2499          * Make sure that we have allocated dquot(s) on disk.
2500          */
2501         error = XFS_QM_DQVOPALLOC(mp, dp,
2502                         current_fsuid(), current_fsgid(), prid,
2503                         XFS_QMOPT_QUOTALL | XFS_QMOPT_INHERIT, &udqp, &gdqp);
2504         if (error)
2505                 goto std_return;
2506
2507         tp = xfs_trans_alloc(mp, XFS_TRANS_SYMLINK);
2508         cancel_flags = XFS_TRANS_RELEASE_LOG_RES;
2509         /*
2510          * The symlink will fit into the inode data fork?
2511          * There can't be any attributes so we get the whole variable part.
2512          */
2513         if (pathlen <= XFS_LITINO(mp))
2514                 fs_blocks = 0;
2515         else
2516                 fs_blocks = XFS_B_TO_FSB(mp, pathlen);
2517         resblks = XFS_SYMLINK_SPACE_RES(mp, link_name->len, fs_blocks);
2518         error = xfs_trans_reserve(tp, resblks, XFS_SYMLINK_LOG_RES(mp), 0,
2519                         XFS_TRANS_PERM_LOG_RES, XFS_SYMLINK_LOG_COUNT);
2520         if (error == ENOSPC && fs_blocks == 0) {
2521                 resblks = 0;
2522                 error = xfs_trans_reserve(tp, 0, XFS_SYMLINK_LOG_RES(mp), 0,
2523                                 XFS_TRANS_PERM_LOG_RES, XFS_SYMLINK_LOG_COUNT);
2524         }
2525         if (error) {
2526                 cancel_flags = 0;
2527                 goto error_return;
2528         }
2529
2530         xfs_ilock(dp, XFS_ILOCK_EXCL | XFS_ILOCK_PARENT);
2531         unlock_dp_on_error = B_TRUE;
2532
2533         /*
2534          * Check whether the directory allows new symlinks or not.
2535          */
2536         if (dp->i_d.di_flags & XFS_DIFLAG_NOSYMLINKS) {
2537                 error = XFS_ERROR(EPERM);
2538                 goto error_return;
2539         }
2540
2541         /*
2542          * Reserve disk quota : blocks and inode.
2543          */
2544         error = XFS_TRANS_RESERVE_QUOTA(mp, tp, udqp, gdqp, resblks, 1, 0);
2545         if (error)
2546                 goto error_return;
2547
2548         /*
2549          * Check for ability to enter directory entry, if no space reserved.
2550          */
2551         error = xfs_dir_canenter(tp, dp, link_name, resblks);
2552         if (error)
2553                 goto error_return;
2554         /*
2555          * Initialize the bmap freelist prior to calling either
2556          * bmapi or the directory create code.
2557          */
2558         XFS_BMAP_INIT(&free_list, &first_block);
2559
2560         /*
2561          * Allocate an inode for the symlink.
2562          */
2563         error = xfs_dir_ialloc(&tp, dp, S_IFLNK | (mode & ~S_IFMT),
2564                                1, 0, credp, prid, resblks > 0, &ip, NULL);
2565         if (error) {
2566                 if (error == ENOSPC)
2567                         goto error_return;
2568                 goto error1;
2569         }
2570         xfs_itrace_ref(ip);
2571
2572         /*
2573          * An error after we've joined dp to the transaction will result in the
2574          * transaction cancel unlocking dp so don't do it explicitly in the
2575          * error path.
2576          */
2577         IHOLD(dp);
2578         xfs_trans_ijoin(tp, dp, XFS_ILOCK_EXCL);
2579         unlock_dp_on_error = B_FALSE;
2580
2581         /*
2582          * Also attach the dquot(s) to it, if applicable.
2583          */
2584         XFS_QM_DQVOPCREATE(mp, tp, ip, udqp, gdqp);
2585
2586         if (resblks)
2587                 resblks -= XFS_IALLOC_SPACE_RES(mp);
2588         /*
2589          * If the symlink will fit into the inode, write it inline.
2590          */
2591         if (pathlen <= XFS_IFORK_DSIZE(ip)) {
2592                 xfs_idata_realloc(ip, pathlen, XFS_DATA_FORK);
2593                 memcpy(ip->i_df.if_u1.if_data, target_path, pathlen);
2594                 ip->i_d.di_size = pathlen;
2595
2596                 /*
2597                  * The inode was initially created in extent format.
2598                  */
2599                 ip->i_df.if_flags &= ~(XFS_IFEXTENTS | XFS_IFBROOT);
2600                 ip->i_df.if_flags |= XFS_IFINLINE;
2601
2602                 ip->i_d.di_format = XFS_DINODE_FMT_LOCAL;
2603                 xfs_trans_log_inode(tp, ip, XFS_ILOG_DDATA | XFS_ILOG_CORE);
2604
2605         } else {
2606                 first_fsb = 0;
2607                 nmaps = SYMLINK_MAPS;
2608
2609                 error = xfs_bmapi(tp, ip, first_fsb, fs_blocks,
2610                                   XFS_BMAPI_WRITE | XFS_BMAPI_METADATA,
2611                                   &first_block, resblks, mval, &nmaps,
2612                                   &free_list, NULL);
2613                 if (error) {
2614                         goto error1;
2615                 }
2616
2617                 if (resblks)
2618                         resblks -= fs_blocks;
2619                 ip->i_d.di_size = pathlen;
2620                 xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
2621
2622                 cur_chunk = target_path;
2623                 for (n = 0; n < nmaps; n++) {
2624                         d = XFS_FSB_TO_DADDR(mp, mval[n].br_startblock);
2625                         byte_cnt = XFS_FSB_TO_B(mp, mval[n].br_blockcount);
2626                         bp = xfs_trans_get_buf(tp, mp->m_ddev_targp, d,
2627                                                BTOBB(byte_cnt), 0);
2628                         ASSERT(bp && !XFS_BUF_GETERROR(bp));
2629                         if (pathlen < byte_cnt) {
2630                                 byte_cnt = pathlen;
2631                         }
2632                         pathlen -= byte_cnt;
2633
2634                         memcpy(XFS_BUF_PTR(bp), cur_chunk, byte_cnt);
2635                         cur_chunk += byte_cnt;
2636
2637                         xfs_trans_log_buf(tp, bp, 0, byte_cnt - 1);
2638                 }
2639         }
2640
2641         /*
2642          * Create the directory entry for the symlink.
2643          */
2644         error = xfs_dir_createname(tp, dp, link_name, ip->i_ino,
2645                                         &first_block, &free_list, resblks);
2646         if (error)
2647                 goto error1;
2648         xfs_ichgtime(dp, XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG);
2649         xfs_trans_log_inode(tp, dp, XFS_ILOG_CORE);
2650
2651         /*
2652          * Bump the in memory version number of the parent directory
2653          * so that other processes accessing it will recognize that
2654          * the directory has changed.
2655          */
2656         dp->i_gen++;
2657
2658         /*
2659          * If this is a synchronous mount, make sure that the
2660          * symlink transaction goes to disk before returning to
2661          * the user.
2662          */
2663         if (mp->m_flags & (XFS_MOUNT_WSYNC|XFS_MOUNT_DIRSYNC)) {
2664                 xfs_trans_set_sync(tp);
2665         }
2666
2667         /*
2668          * xfs_trans_commit normally decrements the vnode ref count
2669          * when it unlocks the inode. Since we want to return the
2670          * vnode to the caller, we bump the vnode ref count now.
2671          */
2672         IHOLD(ip);
2673
2674         error = xfs_bmap_finish(&tp, &free_list, &committed);
2675         if (error) {
2676                 goto error2;
2677         }
2678         error = xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
2679         XFS_QM_DQRELE(mp, udqp);
2680         XFS_QM_DQRELE(mp, gdqp);
2681
2682         /* Fall through to std_return with error = 0 or errno from
2683          * xfs_trans_commit     */
2684 std_return:
2685         if (DM_EVENT_ENABLED(dp, DM_EVENT_POSTSYMLINK)) {
2686                 (void) XFS_SEND_NAMESP(mp, DM_EVENT_POSTSYMLINK,
2687                                         dp, DM_RIGHT_NULL,
2688                                         error ? NULL : ip,
2689                                         DM_RIGHT_NULL, link_name->name,
2690                                         target_path, 0, error, 0);
2691         }
2692
2693         if (!error)
2694                 *ipp = ip;
2695         return error;
2696
2697  error2:
2698         IRELE(ip);
2699  error1:
2700         xfs_bmap_cancel(&free_list);
2701         cancel_flags |= XFS_TRANS_ABORT;
2702  error_return:
2703         xfs_trans_cancel(tp, cancel_flags);
2704         XFS_QM_DQRELE(mp, udqp);
2705         XFS_QM_DQRELE(mp, gdqp);
2706
2707         if (unlock_dp_on_error)
2708                 xfs_iunlock(dp, XFS_ILOCK_EXCL);
2709
2710         goto std_return;
2711 }
2712
2713 int
2714 xfs_inode_flush(
2715         xfs_inode_t     *ip,
2716         int             flags)
2717 {
2718         xfs_mount_t     *mp = ip->i_mount;
2719         int             error = 0;
2720
2721         if (XFS_FORCED_SHUTDOWN(mp))
2722                 return XFS_ERROR(EIO);
2723
2724         /*
2725          * Bypass inodes which have already been cleaned by
2726          * the inode flush clustering code inside xfs_iflush
2727          */
2728         if (xfs_inode_clean(ip))
2729                 return 0;
2730
2731         /*
2732          * We make this non-blocking if the inode is contended,
2733          * return EAGAIN to indicate to the caller that they
2734          * did not succeed. This prevents the flush path from
2735          * blocking on inodes inside another operation right
2736          * now, they get caught later by xfs_sync.
2737          */
2738         if (flags & FLUSH_SYNC) {
2739                 xfs_ilock(ip, XFS_ILOCK_SHARED);
2740                 xfs_iflock(ip);
2741         } else if (xfs_ilock_nowait(ip, XFS_ILOCK_SHARED)) {
2742                 if (xfs_ipincount(ip) || !xfs_iflock_nowait(ip)) {
2743                         xfs_iunlock(ip, XFS_ILOCK_SHARED);
2744                         return EAGAIN;
2745                 }
2746         } else {
2747                 return EAGAIN;
2748         }
2749
2750         error = xfs_iflush(ip, (flags & FLUSH_SYNC) ? XFS_IFLUSH_SYNC
2751                                                     : XFS_IFLUSH_ASYNC_NOBLOCK);
2752         xfs_iunlock(ip, XFS_ILOCK_SHARED);
2753
2754         return error;
2755 }
2756
2757
2758 int
2759 xfs_set_dmattrs(
2760         xfs_inode_t     *ip,
2761         u_int           evmask,
2762         u_int16_t       state)
2763 {
2764         xfs_mount_t     *mp = ip->i_mount;
2765         xfs_trans_t     *tp;
2766         int             error;
2767
2768         if (!capable(CAP_SYS_ADMIN))
2769                 return XFS_ERROR(EPERM);
2770
2771         if (XFS_FORCED_SHUTDOWN(mp))
2772                 return XFS_ERROR(EIO);
2773
2774         tp = xfs_trans_alloc(mp, XFS_TRANS_SET_DMATTRS);
2775         error = xfs_trans_reserve(tp, 0, XFS_ICHANGE_LOG_RES (mp), 0, 0, 0);
2776         if (error) {
2777                 xfs_trans_cancel(tp, 0);
2778                 return error;
2779         }
2780         xfs_ilock(ip, XFS_ILOCK_EXCL);
2781         xfs_trans_ijoin(tp, ip, XFS_ILOCK_EXCL);
2782
2783         ip->i_d.di_dmevmask = evmask;
2784         ip->i_d.di_dmstate  = state;
2785
2786         xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
2787         IHOLD(ip);
2788         error = xfs_trans_commit(tp, 0);
2789
2790         return error;
2791 }
2792
2793 int
2794 xfs_reclaim(
2795         xfs_inode_t     *ip)
2796 {
2797
2798         xfs_itrace_entry(ip);
2799
2800         ASSERT(!VN_MAPPED(VFS_I(ip)));
2801
2802         /* bad inode, get out here ASAP */
2803         if (VN_BAD(VFS_I(ip))) {
2804                 xfs_ireclaim(ip);
2805                 return 0;
2806         }
2807
2808         vn_iowait(ip);
2809
2810         ASSERT(XFS_FORCED_SHUTDOWN(ip->i_mount) || ip->i_delayed_blks == 0);
2811
2812         /*
2813          * Make sure the atime in the XFS inode is correct before freeing the
2814          * Linux inode.
2815          */
2816         xfs_synchronize_atime(ip);
2817
2818         /*
2819          * If we have nothing to flush with this inode then complete the
2820          * teardown now, otherwise break the link between the xfs inode and the
2821          * linux inode and clean up the xfs inode later. This avoids flushing
2822          * the inode to disk during the delete operation itself.
2823          *
2824          * When breaking the link, we need to set the XFS_IRECLAIMABLE flag
2825          * first to ensure that xfs_iunpin() will never see an xfs inode
2826          * that has a linux inode being reclaimed. Synchronisation is provided
2827          * by the i_flags_lock.
2828          */
2829         if (!ip->i_update_core && (ip->i_itemp == NULL)) {
2830                 xfs_ilock(ip, XFS_ILOCK_EXCL);
2831                 xfs_iflock(ip);
2832                 xfs_iflags_set(ip, XFS_IRECLAIMABLE);
2833                 return xfs_reclaim_inode(ip, 1, XFS_IFLUSH_DELWRI_ELSE_SYNC);
2834         }
2835         xfs_inode_set_reclaim_tag(ip);
2836         return 0;
2837 }
2838
2839 /*
2840  * xfs_alloc_file_space()
2841  *      This routine allocates disk space for the given file.
2842  *
2843  *      If alloc_type == 0, this request is for an ALLOCSP type
2844  *      request which will change the file size.  In this case, no
2845  *      DMAPI event will be generated by the call.  A TRUNCATE event
2846  *      will be generated later by xfs_setattr.
2847  *
2848  *      If alloc_type != 0, this request is for a RESVSP type
2849  *      request, and a DMAPI DM_EVENT_WRITE will be generated if the
2850  *      lower block boundary byte address is less than the file's
2851  *      length.
2852  *
2853  * RETURNS:
2854  *       0 on success
2855  *      errno on error
2856  *
2857  */
2858 STATIC int
2859 xfs_alloc_file_space(
2860         xfs_inode_t             *ip,
2861         xfs_off_t               offset,
2862         xfs_off_t               len,
2863         int                     alloc_type,
2864         int                     attr_flags)
2865 {
2866         xfs_mount_t             *mp = ip->i_mount;
2867         xfs_off_t               count;
2868         xfs_filblks_t           allocated_fsb;
2869         xfs_filblks_t           allocatesize_fsb;
2870         xfs_extlen_t            extsz, temp;
2871         xfs_fileoff_t           startoffset_fsb;
2872         xfs_fsblock_t           firstfsb;
2873         int                     nimaps;
2874         int                     bmapi_flag;
2875         int                     quota_flag;
2876         int                     rt;
2877         xfs_trans_t             *tp;
2878         xfs_bmbt_irec_t         imaps[1], *imapp;
2879         xfs_bmap_free_t         free_list;
2880         uint                    qblocks, resblks, resrtextents;
2881         int                     committed;
2882         int                     error;
2883
2884         xfs_itrace_entry(ip);
2885
2886         if (XFS_FORCED_SHUTDOWN(mp))
2887                 return XFS_ERROR(EIO);
2888
2889         if ((error = XFS_QM_DQATTACH(mp, ip, 0)))
2890                 return error;
2891
2892         if (len <= 0)
2893                 return XFS_ERROR(EINVAL);
2894
2895         rt = XFS_IS_REALTIME_INODE(ip);
2896         extsz = xfs_get_extsz_hint(ip);
2897
2898         count = len;
2899         imapp = &imaps[0];
2900         nimaps = 1;
2901         bmapi_flag = XFS_BMAPI_WRITE | (alloc_type ? XFS_BMAPI_PREALLOC : 0);
2902         startoffset_fsb = XFS_B_TO_FSBT(mp, offset);
2903         allocatesize_fsb = XFS_B_TO_FSB(mp, count);
2904
2905         /*      Generate a DMAPI event if needed.       */
2906         if (alloc_type != 0 && offset < ip->i_size &&
2907                         (attr_flags & XFS_ATTR_DMI) == 0  &&
2908                         DM_EVENT_ENABLED(ip, DM_EVENT_WRITE)) {
2909                 xfs_off_t           end_dmi_offset;
2910
2911                 end_dmi_offset = offset+len;
2912                 if (end_dmi_offset > ip->i_size)
2913                         end_dmi_offset = ip->i_size;
2914                 error = XFS_SEND_DATA(mp, DM_EVENT_WRITE, ip, offset,
2915                                       end_dmi_offset - offset, 0, NULL);
2916                 if (error)
2917                         return error;
2918         }
2919
2920         /*
2921          * Allocate file space until done or until there is an error
2922          */
2923 retry:
2924         while (allocatesize_fsb && !error) {
2925                 xfs_fileoff_t   s, e;
2926
2927                 /*
2928                  * Determine space reservations for data/realtime.
2929                  */
2930                 if (unlikely(extsz)) {
2931                         s = startoffset_fsb;
2932                         do_div(s, extsz);
2933                         s *= extsz;
2934                         e = startoffset_fsb + allocatesize_fsb;
2935                         if ((temp = do_mod(startoffset_fsb, extsz)))
2936                                 e += temp;
2937                         if ((temp = do_mod(e, extsz)))
2938                                 e += extsz - temp;
2939                 } else {
2940                         s = 0;
2941                         e = allocatesize_fsb;
2942                 }
2943
2944                 if (unlikely(rt)) {
2945                         resrtextents = qblocks = (uint)(e - s);
2946                         resrtextents /= mp->m_sb.sb_rextsize;
2947                         resblks = XFS_DIOSTRAT_SPACE_RES(mp, 0);
2948                         quota_flag = XFS_QMOPT_RES_RTBLKS;
2949                 } else {
2950                         resrtextents = 0;
2951                         resblks = qblocks = \
2952                                 XFS_DIOSTRAT_SPACE_RES(mp, (uint)(e - s));
2953                         quota_flag = XFS_QMOPT_RES_REGBLKS;
2954                 }
2955
2956                 /*
2957                  * Allocate and setup the transaction.
2958                  */
2959                 tp = xfs_trans_alloc(mp, XFS_TRANS_DIOSTRAT);
2960                 error = xfs_trans_reserve(tp, resblks,
2961                                           XFS_WRITE_LOG_RES(mp), resrtextents,
2962                                           XFS_TRANS_PERM_LOG_RES,
2963                                           XFS_WRITE_LOG_COUNT);
2964                 /*
2965                  * Check for running out of space
2966                  */
2967                 if (error) {
2968                         /*
2969                          * Free the transaction structure.
2970                          */
2971                         ASSERT(error == ENOSPC || XFS_FORCED_SHUTDOWN(mp));
2972                         xfs_trans_cancel(tp, 0);
2973                         break;
2974                 }
2975                 xfs_ilock(ip, XFS_ILOCK_EXCL);
2976                 error = XFS_TRANS_RESERVE_QUOTA_NBLKS(mp, tp, ip,
2977                                                       qblocks, 0, quota_flag);
2978                 if (error)
2979                         goto error1;
2980
2981                 xfs_trans_ijoin(tp, ip, XFS_ILOCK_EXCL);
2982                 xfs_trans_ihold(tp, ip);
2983
2984                 /*
2985                  * Issue the xfs_bmapi() call to allocate the blocks
2986                  */
2987                 XFS_BMAP_INIT(&free_list, &firstfsb);
2988                 error = xfs_bmapi(tp, ip, startoffset_fsb,
2989                                   allocatesize_fsb, bmapi_flag,
2990                                   &firstfsb, 0, imapp, &nimaps,
2991                                   &free_list, NULL);
2992                 if (error) {
2993                         goto error0;
2994                 }
2995
2996                 /*
2997                  * Complete the transaction
2998                  */
2999                 error = xfs_bmap_finish(&tp, &free_list, &committed);
3000                 if (error) {
3001                         goto error0;
3002                 }
3003
3004                 error = xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
3005                 xfs_iunlock(ip, XFS_ILOCK_EXCL);
3006                 if (error) {
3007                         break;
3008                 }
3009
3010                 allocated_fsb = imapp->br_blockcount;
3011
3012                 if (nimaps == 0) {
3013                         error = XFS_ERROR(ENOSPC);
3014                         break;
3015                 }
3016
3017                 startoffset_fsb += allocated_fsb;
3018                 allocatesize_fsb -= allocated_fsb;
3019         }
3020 dmapi_enospc_check:
3021         if (error == ENOSPC && (attr_flags & XFS_ATTR_DMI) == 0 &&
3022             DM_EVENT_ENABLED(ip, DM_EVENT_NOSPACE)) {
3023                 error = XFS_SEND_NAMESP(mp, DM_EVENT_NOSPACE,
3024                                 ip, DM_RIGHT_NULL,
3025                                 ip, DM_RIGHT_NULL,
3026                                 NULL, NULL, 0, 0, 0); /* Delay flag intentionally unused */
3027                 if (error == 0)
3028                         goto retry;     /* Maybe DMAPI app. has made space */
3029                 /* else fall through with error from XFS_SEND_DATA */
3030         }
3031
3032         return error;
3033
3034 error0: /* Cancel bmap, unlock inode, unreserve quota blocks, cancel trans */
3035         xfs_bmap_cancel(&free_list);
3036         XFS_TRANS_UNRESERVE_QUOTA_NBLKS(mp, tp, ip, qblocks, 0, quota_flag);
3037
3038 error1: /* Just cancel transaction */
3039         xfs_trans_cancel(tp, XFS_TRANS_RELEASE_LOG_RES | XFS_TRANS_ABORT);
3040         xfs_iunlock(ip, XFS_ILOCK_EXCL);
3041         goto dmapi_enospc_check;
3042 }
3043
3044 /*
3045  * Zero file bytes between startoff and endoff inclusive.
3046  * The iolock is held exclusive and no blocks are buffered.
3047  *
3048  * This function is used by xfs_free_file_space() to zero
3049  * partial blocks when the range to free is not block aligned.
3050  * When unreserving space with boundaries that are not block
3051  * aligned we round up the start and round down the end
3052  * boundaries and then use this function to zero the parts of
3053  * the blocks that got dropped during the rounding.
3054  */
3055 STATIC int
3056 xfs_zero_remaining_bytes(
3057         xfs_inode_t             *ip,
3058         xfs_off_t               startoff,
3059         xfs_off_t               endoff)
3060 {
3061         xfs_bmbt_irec_t         imap;
3062         xfs_fileoff_t           offset_fsb;
3063         xfs_off_t               lastoffset;
3064         xfs_off_t               offset;
3065         xfs_buf_t               *bp;
3066         xfs_mount_t             *mp = ip->i_mount;
3067         int                     nimap;
3068         int                     error = 0;
3069
3070         /*
3071          * Avoid doing I/O beyond eof - it's not necessary
3072          * since nothing can read beyond eof.  The space will
3073          * be zeroed when the file is extended anyway.
3074          */
3075         if (startoff >= ip->i_size)
3076                 return 0;
3077
3078         if (endoff > ip->i_size)
3079                 endoff = ip->i_size;
3080
3081         bp = xfs_buf_get_noaddr(mp->m_sb.sb_blocksize,
3082                                 XFS_IS_REALTIME_INODE(ip) ?
3083                                 mp->m_rtdev_targp : mp->m_ddev_targp);
3084
3085         for (offset = startoff; offset <= endoff; offset = lastoffset + 1) {
3086                 offset_fsb = XFS_B_TO_FSBT(mp, offset);
3087                 nimap = 1;
3088                 error = xfs_bmapi(NULL, ip, offset_fsb, 1, 0,
3089                         NULL, 0, &imap, &nimap, NULL, NULL);
3090                 if (error || nimap < 1)
3091                         break;
3092                 ASSERT(imap.br_blockcount >= 1);
3093                 ASSERT(imap.br_startoff == offset_fsb);
3094                 lastoffset = XFS_FSB_TO_B(mp, imap.br_startoff + 1) - 1;
3095                 if (lastoffset > endoff)
3096                         lastoffset = endoff;
3097                 if (imap.br_startblock == HOLESTARTBLOCK)
3098                         continue;
3099                 ASSERT(imap.br_startblock != DELAYSTARTBLOCK);
3100                 if (imap.br_state == XFS_EXT_UNWRITTEN)
3101                         continue;
3102                 XFS_BUF_UNDONE(bp);
3103                 XFS_BUF_UNWRITE(bp);
3104                 XFS_BUF_READ(bp);
3105                 XFS_BUF_SET_ADDR(bp, XFS_FSB_TO_DB(ip, imap.br_startblock));
3106                 xfsbdstrat(mp, bp);
3107                 error = xfs_iowait(bp);
3108                 if (error) {
3109                         xfs_ioerror_alert("xfs_zero_remaining_bytes(read)",
3110                                           mp, bp, XFS_BUF_ADDR(bp));
3111                         break;
3112                 }
3113                 memset(XFS_BUF_PTR(bp) +
3114                         (offset - XFS_FSB_TO_B(mp, imap.br_startoff)),
3115                       0, lastoffset - offset + 1);
3116                 XFS_BUF_UNDONE(bp);
3117                 XFS_BUF_UNREAD(bp);
3118                 XFS_BUF_WRITE(bp);
3119                 xfsbdstrat(mp, bp);
3120                 error = xfs_iowait(bp);
3121                 if (error) {
3122                         xfs_ioerror_alert("xfs_zero_remaining_bytes(write)",
3123                                           mp, bp, XFS_BUF_ADDR(bp));
3124                         break;
3125                 }
3126         }
3127         xfs_buf_free(bp);
3128         return error;
3129 }
3130
3131 /*
3132  * xfs_free_file_space()
3133  *      This routine frees disk space for the given file.
3134  *
3135  *      This routine is only called by xfs_change_file_space
3136  *      for an UNRESVSP type call.
3137  *
3138  * RETURNS:
3139  *       0 on success
3140  *      errno on error
3141  *
3142  */
3143 STATIC int
3144 xfs_free_file_space(
3145         xfs_inode_t             *ip,
3146         xfs_off_t               offset,
3147         xfs_off_t               len,
3148         int                     attr_flags)
3149 {
3150         int                     committed;
3151         int                     done;
3152         xfs_off_t               end_dmi_offset;
3153         xfs_fileoff_t           endoffset_fsb;
3154         int                     error;
3155         xfs_fsblock_t           firstfsb;
3156         xfs_bmap_free_t         free_list;
3157         xfs_bmbt_irec_t         imap;
3158         xfs_off_t               ioffset;
3159         xfs_extlen_t            mod=0;
3160         xfs_mount_t             *mp;
3161         int                     nimap;
3162         uint                    resblks;
3163         uint                    rounding;
3164         int                     rt;
3165         xfs_fileoff_t           startoffset_fsb;
3166         xfs_trans_t             *tp;
3167         int                     need_iolock = 1;
3168
3169         mp = ip->i_mount;
3170
3171         xfs_itrace_entry(ip);
3172
3173         if ((error = XFS_QM_DQATTACH(mp, ip, 0)))
3174                 return error;
3175
3176         error = 0;
3177         if (len <= 0)   /* if nothing being freed */
3178                 return error;
3179         rt = XFS_IS_REALTIME_INODE(ip);
3180         startoffset_fsb = XFS_B_TO_FSB(mp, offset);
3181         end_dmi_offset = offset + len;
3182         endoffset_fsb = XFS_B_TO_FSBT(mp, end_dmi_offset);
3183
3184         if (offset < ip->i_size && (attr_flags & XFS_ATTR_DMI) == 0 &&
3185             DM_EVENT_ENABLED(ip, DM_EVENT_WRITE)) {
3186                 if (end_dmi_offset > ip->i_size)
3187                         end_dmi_offset = ip->i_size;
3188                 error = XFS_SEND_DATA(mp, DM_EVENT_WRITE, ip,
3189                                 offset, end_dmi_offset - offset,
3190                                 AT_DELAY_FLAG(attr_flags), NULL);
3191                 if (error)
3192                         return error;
3193         }
3194
3195         if (attr_flags & XFS_ATTR_NOLOCK)
3196                 need_iolock = 0;
3197         if (need_iolock) {
3198                 xfs_ilock(ip, XFS_IOLOCK_EXCL);
3199                 vn_iowait(ip);  /* wait for the completion of any pending DIOs */
3200         }
3201
3202         rounding = max_t(uint, 1 << mp->m_sb.sb_blocklog, PAGE_CACHE_SIZE);
3203         ioffset = offset & ~(rounding - 1);
3204
3205         if (VN_CACHED(VFS_I(ip)) != 0) {
3206                 xfs_inval_cached_trace(ip, ioffset, -1, ioffset, -1);
3207                 error = xfs_flushinval_pages(ip, ioffset, -1, FI_REMAPF_LOCKED);
3208                 if (error)
3209                         goto out_unlock_iolock;
3210         }
3211
3212         /*
3213          * Need to zero the stuff we're not freeing, on disk.
3214          * If its a realtime file & can't use unwritten extents then we
3215          * actually need to zero the extent edges.  Otherwise xfs_bunmapi
3216          * will take care of it for us.
3217          */
3218         if (rt && !xfs_sb_version_hasextflgbit(&mp->m_sb)) {
3219                 nimap = 1;
3220                 error = xfs_bmapi(NULL, ip, startoffset_fsb,
3221                         1, 0, NULL, 0, &imap, &nimap, NULL, NULL);
3222                 if (error)
3223                         goto out_unlock_iolock;
3224                 ASSERT(nimap == 0 || nimap == 1);
3225                 if (nimap && imap.br_startblock != HOLESTARTBLOCK) {
3226                         xfs_daddr_t     block;
3227
3228                         ASSERT(imap.br_startblock != DELAYSTARTBLOCK);
3229                         block = imap.br_startblock;
3230                         mod = do_div(block, mp->m_sb.sb_rextsize);
3231                         if (mod)
3232                                 startoffset_fsb += mp->m_sb.sb_rextsize - mod;
3233                 }
3234                 nimap = 1;
3235                 error = xfs_bmapi(NULL, ip, endoffset_fsb - 1,
3236                         1, 0, NULL, 0, &imap, &nimap, NULL, NULL);
3237                 if (error)
3238                         goto out_unlock_iolock;
3239                 ASSERT(nimap == 0 || nimap == 1);
3240                 if (nimap && imap.br_startblock != HOLESTARTBLOCK) {
3241                         ASSERT(imap.br_startblock != DELAYSTARTBLOCK);
3242                         mod++;
3243                         if (mod && (mod != mp->m_sb.sb_rextsize))
3244                                 endoffset_fsb -= mod;
3245                 }
3246         }
3247         if ((done = (endoffset_fsb <= startoffset_fsb)))
3248                 /*
3249                  * One contiguous piece to clear
3250                  */
3251                 error = xfs_zero_remaining_bytes(ip, offset, offset + len - 1);
3252         else {
3253                 /*
3254                  * Some full blocks, possibly two pieces to clear
3255                  */
3256                 if (offset < XFS_FSB_TO_B(mp, startoffset_fsb))
3257                         error = xfs_zero_remaining_bytes(ip, offset,
3258                                 XFS_FSB_TO_B(mp, startoffset_fsb) - 1);
3259                 if (!error &&
3260                     XFS_FSB_TO_B(mp, endoffset_fsb) < offset + len)
3261                         error = xfs_zero_remaining_bytes(ip,
3262                                 XFS_FSB_TO_B(mp, endoffset_fsb),
3263                                 offset + len - 1);
3264         }
3265
3266         /*
3267          * free file space until done or until there is an error
3268          */
3269         resblks = XFS_DIOSTRAT_SPACE_RES(mp, 0);
3270         while (!error && !done) {
3271
3272                 /*
3273                  * allocate and setup the transaction. Allow this
3274                  * transaction to dip into the reserve blocks to ensure
3275                  * the freeing of the space succeeds at ENOSPC.
3276                  */
3277                 tp = xfs_trans_alloc(mp, XFS_TRANS_DIOSTRAT);
3278                 tp->t_flags |= XFS_TRANS_RESERVE;
3279                 error = xfs_trans_reserve(tp,
3280                                           resblks,
3281                                           XFS_WRITE_LOG_RES(mp),
3282                                           0,
3283                                           XFS_TRANS_PERM_LOG_RES,
3284                                           XFS_WRITE_LOG_COUNT);
3285
3286                 /*
3287                  * check for running out of space
3288                  */
3289                 if (error) {
3290                         /*
3291                          * Free the transaction structure.
3292                          */
3293                         ASSERT(error == ENOSPC || XFS_FORCED_SHUTDOWN(mp));
3294                         xfs_trans_cancel(tp, 0);
3295                         break;
3296                 }
3297                 xfs_ilock(ip, XFS_ILOCK_EXCL);
3298                 error = XFS_TRANS_RESERVE_QUOTA(mp, tp,
3299                                 ip->i_udquot, ip->i_gdquot, resblks, 0,
3300                                 XFS_QMOPT_RES_REGBLKS);
3301                 if (error)
3302                         goto error1;
3303
3304                 xfs_trans_ijoin(tp, ip, XFS_ILOCK_EXCL);
3305                 xfs_trans_ihold(tp, ip);
3306
3307                 /*
3308                  * issue the bunmapi() call to free the blocks
3309                  */
3310                 XFS_BMAP_INIT(&free_list, &firstfsb);
3311                 error = xfs_bunmapi(tp, ip, startoffset_fsb,
3312                                   endoffset_fsb - startoffset_fsb,
3313                                   0, 2, &firstfsb, &free_list, NULL, &done);
3314                 if (error) {
3315                         goto error0;
3316                 }
3317
3318                 /*
3319                  * complete the transaction
3320                  */
3321                 error = xfs_bmap_finish(&tp, &free_list, &committed);
3322                 if (error) {
3323                         goto error0;
3324                 }
3325
3326                 error = xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
3327                 xfs_iunlock(ip, XFS_ILOCK_EXCL);
3328         }
3329
3330  out_unlock_iolock:
3331         if (need_iolock)
3332                 xfs_iunlock(ip, XFS_IOLOCK_EXCL);
3333         return error;
3334
3335  error0:
3336         xfs_bmap_cancel(&free_list);
3337  error1:
3338         xfs_trans_cancel(tp, XFS_TRANS_RELEASE_LOG_RES | XFS_TRANS_ABORT);
3339         xfs_iunlock(ip, need_iolock ? (XFS_ILOCK_EXCL | XFS_IOLOCK_EXCL) :
3340                     XFS_ILOCK_EXCL);
3341         return error;
3342 }
3343
3344 /*
3345  * xfs_change_file_space()
3346  *      This routine allocates or frees disk space for the given file.
3347  *      The user specified parameters are checked for alignment and size
3348  *      limitations.
3349  *
3350  * RETURNS:
3351  *       0 on success
3352  *      errno on error
3353  *
3354  */
3355 int
3356 xfs_change_file_space(
3357         xfs_inode_t     *ip,
3358         int             cmd,
3359         xfs_flock64_t   *bf,
3360         xfs_off_t       offset,
3361         int             attr_flags)
3362 {
3363         xfs_mount_t     *mp = ip->i_mount;
3364         int             clrprealloc;
3365         int             error;
3366         xfs_fsize_t     fsize;
3367         int             setprealloc;
3368         xfs_off_t       startoffset;
3369         xfs_off_t       llen;
3370         xfs_trans_t     *tp;
3371         struct iattr    iattr;
3372
3373         xfs_itrace_entry(ip);
3374
3375         if (!S_ISREG(ip->i_d.di_mode))
3376                 return XFS_ERROR(EINVAL);
3377
3378         switch (bf->l_whence) {
3379         case 0: /*SEEK_SET*/
3380                 break;
3381         case 1: /*SEEK_CUR*/
3382                 bf->l_start += offset;
3383                 break;
3384         case 2: /*SEEK_END*/
3385                 bf->l_start += ip->i_size;
3386                 break;
3387         default:
3388                 return XFS_ERROR(EINVAL);
3389         }
3390
3391         llen = bf->l_len > 0 ? bf->l_len - 1 : bf->l_len;
3392
3393         if (   (bf->l_start < 0)
3394             || (bf->l_start > XFS_MAXIOFFSET(mp))
3395             || (bf->l_start + llen < 0)
3396             || (bf->l_start + llen > XFS_MAXIOFFSET(mp)))
3397                 return XFS_ERROR(EINVAL);
3398
3399         bf->l_whence = 0;
3400
3401         startoffset = bf->l_start;
3402         fsize = ip->i_size;
3403
3404         /*
3405          * XFS_IOC_RESVSP and XFS_IOC_UNRESVSP will reserve or unreserve
3406          * file space.
3407          * These calls do NOT zero the data space allocated to the file,
3408          * nor do they change the file size.
3409          *
3410          * XFS_IOC_ALLOCSP and XFS_IOC_FREESP will allocate and free file
3411          * space.
3412          * These calls cause the new file data to be zeroed and the file
3413          * size to be changed.
3414          */
3415         setprealloc = clrprealloc = 0;
3416
3417         switch (cmd) {
3418         case XFS_IOC_RESVSP:
3419         case XFS_IOC_RESVSP64:
3420                 error = xfs_alloc_file_space(ip, startoffset, bf->l_len,
3421                                                                 1, attr_flags);
3422                 if (error)
3423                         return error;
3424                 setprealloc = 1;
3425                 break;
3426
3427         case XFS_IOC_UNRESVSP:
3428         case XFS_IOC_UNRESVSP64:
3429                 if ((error = xfs_free_file_space(ip, startoffset, bf->l_len,
3430                                                                 attr_flags)))
3431                         return error;
3432                 break;
3433
3434         case XFS_IOC_ALLOCSP:
3435         case XFS_IOC_ALLOCSP64:
3436         case XFS_IOC_FREESP:
3437         case XFS_IOC_FREESP64:
3438                 if (startoffset > fsize) {
3439                         error = xfs_alloc_file_space(ip, fsize,
3440                                         startoffset - fsize, 0, attr_flags);
3441                         if (error)
3442                                 break;
3443                 }
3444
3445                 iattr.ia_valid = ATTR_SIZE;
3446                 iattr.ia_size = startoffset;
3447
3448                 error = xfs_setattr(ip, &iattr, attr_flags);
3449
3450                 if (error)
3451                         return error;
3452
3453                 clrprealloc = 1;
3454                 break;
3455
3456         default:
3457                 ASSERT(0);
3458                 return XFS_ERROR(EINVAL);
3459         }
3460
3461         /*
3462          * update the inode timestamp, mode, and prealloc flag bits
3463          */
3464         tp = xfs_trans_alloc(mp, XFS_TRANS_WRITEID);
3465
3466         if ((error = xfs_trans_reserve(tp, 0, XFS_WRITEID_LOG_RES(mp),
3467                                       0, 0, 0))) {
3468                 /* ASSERT(0); */
3469                 xfs_trans_cancel(tp, 0);
3470                 return error;
3471         }
3472
3473         xfs_ilock(ip, XFS_ILOCK_EXCL);
3474
3475         xfs_trans_ijoin(tp, ip, XFS_ILOCK_EXCL);
3476         xfs_trans_ihold(tp, ip);
3477
3478         if ((attr_flags & XFS_ATTR_DMI) == 0) {
3479                 ip->i_d.di_mode &= ~S_ISUID;
3480
3481                 /*
3482                  * Note that we don't have to worry about mandatory
3483                  * file locking being disabled here because we only
3484                  * clear the S_ISGID bit if the Group execute bit is
3485                  * on, but if it was on then mandatory locking wouldn't
3486                  * have been enabled.
3487                  */
3488                 if (ip->i_d.di_mode & S_IXGRP)
3489                         ip->i_d.di_mode &= ~S_ISGID;
3490
3491                 xfs_ichgtime(ip, XFS_ICHGTIME_MOD | XFS_ICHGTIME_CHG);
3492         }
3493         if (setprealloc)
3494                 ip->i_d.di_flags |= XFS_DIFLAG_PREALLOC;
3495         else if (clrprealloc)
3496                 ip->i_d.di_flags &= ~XFS_DIFLAG_PREALLOC;
3497
3498         xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
3499         xfs_trans_set_sync(tp);
3500
3501         error = xfs_trans_commit(tp, 0);
3502
3503         xfs_iunlock(ip, XFS_ILOCK_EXCL);
3504
3505         return error;
3506 }