xfs: merge xfs_dinode.h into xfs_format.h
[firefly-linux-kernel-4.4.55.git] / fs / xfs / xfs_bmap_util.c
1 /*
2  * Copyright (c) 2000-2006 Silicon Graphics, Inc.
3  * Copyright (c) 2012 Red Hat, Inc.
4  * All Rights Reserved.
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License as
8  * published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it would be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write the Free Software Foundation,
17  * Inc.,  51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
18  */
19 #include "xfs.h"
20 #include "xfs_fs.h"
21 #include "xfs_shared.h"
22 #include "xfs_format.h"
23 #include "xfs_log_format.h"
24 #include "xfs_trans_resv.h"
25 #include "xfs_bit.h"
26 #include "xfs_sb.h"
27 #include "xfs_ag.h"
28 #include "xfs_mount.h"
29 #include "xfs_da_format.h"
30 #include "xfs_inode.h"
31 #include "xfs_btree.h"
32 #include "xfs_trans.h"
33 #include "xfs_extfree_item.h"
34 #include "xfs_alloc.h"
35 #include "xfs_bmap.h"
36 #include "xfs_bmap_util.h"
37 #include "xfs_bmap_btree.h"
38 #include "xfs_rtalloc.h"
39 #include "xfs_error.h"
40 #include "xfs_quota.h"
41 #include "xfs_trans_space.h"
42 #include "xfs_trace.h"
43 #include "xfs_icache.h"
44 #include "xfs_log.h"
45
46 /* Kernel only BMAP related definitions and functions */
47
48 /*
49  * Convert the given file system block to a disk block.  We have to treat it
50  * differently based on whether the file is a real time file or not, because the
51  * bmap code does.
52  */
53 xfs_daddr_t
54 xfs_fsb_to_db(struct xfs_inode *ip, xfs_fsblock_t fsb)
55 {
56         return (XFS_IS_REALTIME_INODE(ip) ? \
57                  (xfs_daddr_t)XFS_FSB_TO_BB((ip)->i_mount, (fsb)) : \
58                  XFS_FSB_TO_DADDR((ip)->i_mount, (fsb)));
59 }
60
61 /*
62  * Routine to be called at transaction's end by xfs_bmapi, xfs_bunmapi
63  * caller.  Frees all the extents that need freeing, which must be done
64  * last due to locking considerations.  We never free any extents in
65  * the first transaction.
66  *
67  * Return 1 if the given transaction was committed and a new one
68  * started, and 0 otherwise in the committed parameter.
69  */
70 int                                             /* error */
71 xfs_bmap_finish(
72         xfs_trans_t             **tp,           /* transaction pointer addr */
73         xfs_bmap_free_t         *flist,         /* i/o: list extents to free */
74         int                     *committed)     /* xact committed or not */
75 {
76         xfs_efd_log_item_t      *efd;           /* extent free data */
77         xfs_efi_log_item_t      *efi;           /* extent free intention */
78         int                     error;          /* error return value */
79         xfs_bmap_free_item_t    *free;          /* free extent item */
80         struct xfs_trans_res    tres;           /* new log reservation */
81         xfs_mount_t             *mp;            /* filesystem mount structure */
82         xfs_bmap_free_item_t    *next;          /* next item on free list */
83         xfs_trans_t             *ntp;           /* new transaction pointer */
84
85         ASSERT((*tp)->t_flags & XFS_TRANS_PERM_LOG_RES);
86         if (flist->xbf_count == 0) {
87                 *committed = 0;
88                 return 0;
89         }
90         ntp = *tp;
91         efi = xfs_trans_get_efi(ntp, flist->xbf_count);
92         for (free = flist->xbf_first; free; free = free->xbfi_next)
93                 xfs_trans_log_efi_extent(ntp, efi, free->xbfi_startblock,
94                         free->xbfi_blockcount);
95
96         tres.tr_logres = ntp->t_log_res;
97         tres.tr_logcount = ntp->t_log_count;
98         tres.tr_logflags = XFS_TRANS_PERM_LOG_RES;
99         ntp = xfs_trans_dup(*tp);
100         error = xfs_trans_commit(*tp, 0);
101         *tp = ntp;
102         *committed = 1;
103         /*
104          * We have a new transaction, so we should return committed=1,
105          * even though we're returning an error.
106          */
107         if (error)
108                 return error;
109
110         /*
111          * transaction commit worked ok so we can drop the extra ticket
112          * reference that we gained in xfs_trans_dup()
113          */
114         xfs_log_ticket_put(ntp->t_ticket);
115
116         error = xfs_trans_reserve(ntp, &tres, 0, 0);
117         if (error)
118                 return error;
119         efd = xfs_trans_get_efd(ntp, efi, flist->xbf_count);
120         for (free = flist->xbf_first; free != NULL; free = next) {
121                 next = free->xbfi_next;
122                 if ((error = xfs_free_extent(ntp, free->xbfi_startblock,
123                                 free->xbfi_blockcount))) {
124                         /*
125                          * The bmap free list will be cleaned up at a
126                          * higher level.  The EFI will be canceled when
127                          * this transaction is aborted.
128                          * Need to force shutdown here to make sure it
129                          * happens, since this transaction may not be
130                          * dirty yet.
131                          */
132                         mp = ntp->t_mountp;
133                         if (!XFS_FORCED_SHUTDOWN(mp))
134                                 xfs_force_shutdown(mp,
135                                                    (error == -EFSCORRUPTED) ?
136                                                    SHUTDOWN_CORRUPT_INCORE :
137                                                    SHUTDOWN_META_IO_ERROR);
138                         return error;
139                 }
140                 xfs_trans_log_efd_extent(ntp, efd, free->xbfi_startblock,
141                         free->xbfi_blockcount);
142                 xfs_bmap_del_free(flist, NULL, free);
143         }
144         return 0;
145 }
146
147 int
148 xfs_bmap_rtalloc(
149         struct xfs_bmalloca     *ap)    /* bmap alloc argument struct */
150 {
151         xfs_alloctype_t atype = 0;      /* type for allocation routines */
152         int             error;          /* error return value */
153         xfs_mount_t     *mp;            /* mount point structure */
154         xfs_extlen_t    prod = 0;       /* product factor for allocators */
155         xfs_extlen_t    ralen = 0;      /* realtime allocation length */
156         xfs_extlen_t    align;          /* minimum allocation alignment */
157         xfs_rtblock_t   rtb;
158
159         mp = ap->ip->i_mount;
160         align = xfs_get_extsz_hint(ap->ip);
161         prod = align / mp->m_sb.sb_rextsize;
162         error = xfs_bmap_extsize_align(mp, &ap->got, &ap->prev,
163                                         align, 1, ap->eof, 0,
164                                         ap->conv, &ap->offset, &ap->length);
165         if (error)
166                 return error;
167         ASSERT(ap->length);
168         ASSERT(ap->length % mp->m_sb.sb_rextsize == 0);
169
170         /*
171          * If the offset & length are not perfectly aligned
172          * then kill prod, it will just get us in trouble.
173          */
174         if (do_mod(ap->offset, align) || ap->length % align)
175                 prod = 1;
176         /*
177          * Set ralen to be the actual requested length in rtextents.
178          */
179         ralen = ap->length / mp->m_sb.sb_rextsize;
180         /*
181          * If the old value was close enough to MAXEXTLEN that
182          * we rounded up to it, cut it back so it's valid again.
183          * Note that if it's a really large request (bigger than
184          * MAXEXTLEN), we don't hear about that number, and can't
185          * adjust the starting point to match it.
186          */
187         if (ralen * mp->m_sb.sb_rextsize >= MAXEXTLEN)
188                 ralen = MAXEXTLEN / mp->m_sb.sb_rextsize;
189
190         /*
191          * Lock out other modifications to the RT bitmap inode.
192          */
193         xfs_ilock(mp->m_rbmip, XFS_ILOCK_EXCL);
194         xfs_trans_ijoin(ap->tp, mp->m_rbmip, XFS_ILOCK_EXCL);
195
196         /*
197          * If it's an allocation to an empty file at offset 0,
198          * pick an extent that will space things out in the rt area.
199          */
200         if (ap->eof && ap->offset == 0) {
201                 xfs_rtblock_t uninitialized_var(rtx); /* realtime extent no */
202
203                 error = xfs_rtpick_extent(mp, ap->tp, ralen, &rtx);
204                 if (error)
205                         return error;
206                 ap->blkno = rtx * mp->m_sb.sb_rextsize;
207         } else {
208                 ap->blkno = 0;
209         }
210
211         xfs_bmap_adjacent(ap);
212
213         /*
214          * Realtime allocation, done through xfs_rtallocate_extent.
215          */
216         atype = ap->blkno == 0 ?  XFS_ALLOCTYPE_ANY_AG : XFS_ALLOCTYPE_NEAR_BNO;
217         do_div(ap->blkno, mp->m_sb.sb_rextsize);
218         rtb = ap->blkno;
219         ap->length = ralen;
220         if ((error = xfs_rtallocate_extent(ap->tp, ap->blkno, 1, ap->length,
221                                 &ralen, atype, ap->wasdel, prod, &rtb)))
222                 return error;
223         if (rtb == NULLFSBLOCK && prod > 1 &&
224             (error = xfs_rtallocate_extent(ap->tp, ap->blkno, 1,
225                                            ap->length, &ralen, atype,
226                                            ap->wasdel, 1, &rtb)))
227                 return error;
228         ap->blkno = rtb;
229         if (ap->blkno != NULLFSBLOCK) {
230                 ap->blkno *= mp->m_sb.sb_rextsize;
231                 ralen *= mp->m_sb.sb_rextsize;
232                 ap->length = ralen;
233                 ap->ip->i_d.di_nblocks += ralen;
234                 xfs_trans_log_inode(ap->tp, ap->ip, XFS_ILOG_CORE);
235                 if (ap->wasdel)
236                         ap->ip->i_delayed_blks -= ralen;
237                 /*
238                  * Adjust the disk quota also. This was reserved
239                  * earlier.
240                  */
241                 xfs_trans_mod_dquot_byino(ap->tp, ap->ip,
242                         ap->wasdel ? XFS_TRANS_DQ_DELRTBCOUNT :
243                                         XFS_TRANS_DQ_RTBCOUNT, (long) ralen);
244         } else {
245                 ap->length = 0;
246         }
247         return 0;
248 }
249
250 /*
251  * Check if the endoff is outside the last extent. If so the caller will grow
252  * the allocation to a stripe unit boundary.  All offsets are considered outside
253  * the end of file for an empty fork, so 1 is returned in *eof in that case.
254  */
255 int
256 xfs_bmap_eof(
257         struct xfs_inode        *ip,
258         xfs_fileoff_t           endoff,
259         int                     whichfork,
260         int                     *eof)
261 {
262         struct xfs_bmbt_irec    rec;
263         int                     error;
264
265         error = xfs_bmap_last_extent(NULL, ip, whichfork, &rec, eof);
266         if (error || *eof)
267                 return error;
268
269         *eof = endoff >= rec.br_startoff + rec.br_blockcount;
270         return 0;
271 }
272
273 /*
274  * Extent tree block counting routines.
275  */
276
277 /*
278  * Count leaf blocks given a range of extent records.
279  */
280 STATIC void
281 xfs_bmap_count_leaves(
282         xfs_ifork_t             *ifp,
283         xfs_extnum_t            idx,
284         int                     numrecs,
285         int                     *count)
286 {
287         int             b;
288
289         for (b = 0; b < numrecs; b++) {
290                 xfs_bmbt_rec_host_t *frp = xfs_iext_get_ext(ifp, idx + b);
291                 *count += xfs_bmbt_get_blockcount(frp);
292         }
293 }
294
295 /*
296  * Count leaf blocks given a range of extent records originally
297  * in btree format.
298  */
299 STATIC void
300 xfs_bmap_disk_count_leaves(
301         struct xfs_mount        *mp,
302         struct xfs_btree_block  *block,
303         int                     numrecs,
304         int                     *count)
305 {
306         int             b;
307         xfs_bmbt_rec_t  *frp;
308
309         for (b = 1; b <= numrecs; b++) {
310                 frp = XFS_BMBT_REC_ADDR(mp, block, b);
311                 *count += xfs_bmbt_disk_get_blockcount(frp);
312         }
313 }
314
315 /*
316  * Recursively walks each level of a btree
317  * to count total fsblocks in use.
318  */
319 STATIC int                                     /* error */
320 xfs_bmap_count_tree(
321         xfs_mount_t     *mp,            /* file system mount point */
322         xfs_trans_t     *tp,            /* transaction pointer */
323         xfs_ifork_t     *ifp,           /* inode fork pointer */
324         xfs_fsblock_t   blockno,        /* file system block number */
325         int             levelin,        /* level in btree */
326         int             *count)         /* Count of blocks */
327 {
328         int                     error;
329         xfs_buf_t               *bp, *nbp;
330         int                     level = levelin;
331         __be64                  *pp;
332         xfs_fsblock_t           bno = blockno;
333         xfs_fsblock_t           nextbno;
334         struct xfs_btree_block  *block, *nextblock;
335         int                     numrecs;
336
337         error = xfs_btree_read_bufl(mp, tp, bno, 0, &bp, XFS_BMAP_BTREE_REF,
338                                                 &xfs_bmbt_buf_ops);
339         if (error)
340                 return error;
341         *count += 1;
342         block = XFS_BUF_TO_BLOCK(bp);
343
344         if (--level) {
345                 /* Not at node above leaves, count this level of nodes */
346                 nextbno = be64_to_cpu(block->bb_u.l.bb_rightsib);
347                 while (nextbno != NULLFSBLOCK) {
348                         error = xfs_btree_read_bufl(mp, tp, nextbno, 0, &nbp,
349                                                 XFS_BMAP_BTREE_REF,
350                                                 &xfs_bmbt_buf_ops);
351                         if (error)
352                                 return error;
353                         *count += 1;
354                         nextblock = XFS_BUF_TO_BLOCK(nbp);
355                         nextbno = be64_to_cpu(nextblock->bb_u.l.bb_rightsib);
356                         xfs_trans_brelse(tp, nbp);
357                 }
358
359                 /* Dive to the next level */
360                 pp = XFS_BMBT_PTR_ADDR(mp, block, 1, mp->m_bmap_dmxr[1]);
361                 bno = be64_to_cpu(*pp);
362                 if (unlikely((error =
363                      xfs_bmap_count_tree(mp, tp, ifp, bno, level, count)) < 0)) {
364                         xfs_trans_brelse(tp, bp);
365                         XFS_ERROR_REPORT("xfs_bmap_count_tree(1)",
366                                          XFS_ERRLEVEL_LOW, mp);
367                         return -EFSCORRUPTED;
368                 }
369                 xfs_trans_brelse(tp, bp);
370         } else {
371                 /* count all level 1 nodes and their leaves */
372                 for (;;) {
373                         nextbno = be64_to_cpu(block->bb_u.l.bb_rightsib);
374                         numrecs = be16_to_cpu(block->bb_numrecs);
375                         xfs_bmap_disk_count_leaves(mp, block, numrecs, count);
376                         xfs_trans_brelse(tp, bp);
377                         if (nextbno == NULLFSBLOCK)
378                                 break;
379                         bno = nextbno;
380                         error = xfs_btree_read_bufl(mp, tp, bno, 0, &bp,
381                                                 XFS_BMAP_BTREE_REF,
382                                                 &xfs_bmbt_buf_ops);
383                         if (error)
384                                 return error;
385                         *count += 1;
386                         block = XFS_BUF_TO_BLOCK(bp);
387                 }
388         }
389         return 0;
390 }
391
392 /*
393  * Count fsblocks of the given fork.
394  */
395 int                                             /* error */
396 xfs_bmap_count_blocks(
397         xfs_trans_t             *tp,            /* transaction pointer */
398         xfs_inode_t             *ip,            /* incore inode */
399         int                     whichfork,      /* data or attr fork */
400         int                     *count)         /* out: count of blocks */
401 {
402         struct xfs_btree_block  *block; /* current btree block */
403         xfs_fsblock_t           bno;    /* block # of "block" */
404         xfs_ifork_t             *ifp;   /* fork structure */
405         int                     level;  /* btree level, for checking */
406         xfs_mount_t             *mp;    /* file system mount structure */
407         __be64                  *pp;    /* pointer to block address */
408
409         bno = NULLFSBLOCK;
410         mp = ip->i_mount;
411         ifp = XFS_IFORK_PTR(ip, whichfork);
412         if ( XFS_IFORK_FORMAT(ip, whichfork) == XFS_DINODE_FMT_EXTENTS ) {
413                 xfs_bmap_count_leaves(ifp, 0,
414                         ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t),
415                         count);
416                 return 0;
417         }
418
419         /*
420          * Root level must use BMAP_BROOT_PTR_ADDR macro to get ptr out.
421          */
422         block = ifp->if_broot;
423         level = be16_to_cpu(block->bb_level);
424         ASSERT(level > 0);
425         pp = XFS_BMAP_BROOT_PTR_ADDR(mp, block, 1, ifp->if_broot_bytes);
426         bno = be64_to_cpu(*pp);
427         ASSERT(bno != NULLFSBLOCK);
428         ASSERT(XFS_FSB_TO_AGNO(mp, bno) < mp->m_sb.sb_agcount);
429         ASSERT(XFS_FSB_TO_AGBNO(mp, bno) < mp->m_sb.sb_agblocks);
430
431         if (unlikely(xfs_bmap_count_tree(mp, tp, ifp, bno, level, count) < 0)) {
432                 XFS_ERROR_REPORT("xfs_bmap_count_blocks(2)", XFS_ERRLEVEL_LOW,
433                                  mp);
434                 return -EFSCORRUPTED;
435         }
436
437         return 0;
438 }
439
440 /*
441  * returns 1 for success, 0 if we failed to map the extent.
442  */
443 STATIC int
444 xfs_getbmapx_fix_eof_hole(
445         xfs_inode_t             *ip,            /* xfs incore inode pointer */
446         struct getbmapx         *out,           /* output structure */
447         int                     prealloced,     /* this is a file with
448                                                  * preallocated data space */
449         __int64_t               end,            /* last block requested */
450         xfs_fsblock_t           startblock)
451 {
452         __int64_t               fixlen;
453         xfs_mount_t             *mp;            /* file system mount point */
454         xfs_ifork_t             *ifp;           /* inode fork pointer */
455         xfs_extnum_t            lastx;          /* last extent pointer */
456         xfs_fileoff_t           fileblock;
457
458         if (startblock == HOLESTARTBLOCK) {
459                 mp = ip->i_mount;
460                 out->bmv_block = -1;
461                 fixlen = XFS_FSB_TO_BB(mp, XFS_B_TO_FSB(mp, XFS_ISIZE(ip)));
462                 fixlen -= out->bmv_offset;
463                 if (prealloced && out->bmv_offset + out->bmv_length == end) {
464                         /* Came to hole at EOF. Trim it. */
465                         if (fixlen <= 0)
466                                 return 0;
467                         out->bmv_length = fixlen;
468                 }
469         } else {
470                 if (startblock == DELAYSTARTBLOCK)
471                         out->bmv_block = -2;
472                 else
473                         out->bmv_block = xfs_fsb_to_db(ip, startblock);
474                 fileblock = XFS_BB_TO_FSB(ip->i_mount, out->bmv_offset);
475                 ifp = XFS_IFORK_PTR(ip, XFS_DATA_FORK);
476                 if (xfs_iext_bno_to_ext(ifp, fileblock, &lastx) &&
477                    (lastx == (ifp->if_bytes / (uint)sizeof(xfs_bmbt_rec_t))-1))
478                         out->bmv_oflags |= BMV_OF_LAST;
479         }
480
481         return 1;
482 }
483
484 /*
485  * Get inode's extents as described in bmv, and format for output.
486  * Calls formatter to fill the user's buffer until all extents
487  * are mapped, until the passed-in bmv->bmv_count slots have
488  * been filled, or until the formatter short-circuits the loop,
489  * if it is tracking filled-in extents on its own.
490  */
491 int                                             /* error code */
492 xfs_getbmap(
493         xfs_inode_t             *ip,
494         struct getbmapx         *bmv,           /* user bmap structure */
495         xfs_bmap_format_t       formatter,      /* format to user */
496         void                    *arg)           /* formatter arg */
497 {
498         __int64_t               bmvend;         /* last block requested */
499         int                     error = 0;      /* return value */
500         __int64_t               fixlen;         /* length for -1 case */
501         int                     i;              /* extent number */
502         int                     lock;           /* lock state */
503         xfs_bmbt_irec_t         *map;           /* buffer for user's data */
504         xfs_mount_t             *mp;            /* file system mount point */
505         int                     nex;            /* # of user extents can do */
506         int                     nexleft;        /* # of user extents left */
507         int                     subnex;         /* # of bmapi's can do */
508         int                     nmap;           /* number of map entries */
509         struct getbmapx         *out;           /* output structure */
510         int                     whichfork;      /* data or attr fork */
511         int                     prealloced;     /* this is a file with
512                                                  * preallocated data space */
513         int                     iflags;         /* interface flags */
514         int                     bmapi_flags;    /* flags for xfs_bmapi */
515         int                     cur_ext = 0;
516
517         mp = ip->i_mount;
518         iflags = bmv->bmv_iflags;
519         whichfork = iflags & BMV_IF_ATTRFORK ? XFS_ATTR_FORK : XFS_DATA_FORK;
520
521         if (whichfork == XFS_ATTR_FORK) {
522                 if (XFS_IFORK_Q(ip)) {
523                         if (ip->i_d.di_aformat != XFS_DINODE_FMT_EXTENTS &&
524                             ip->i_d.di_aformat != XFS_DINODE_FMT_BTREE &&
525                             ip->i_d.di_aformat != XFS_DINODE_FMT_LOCAL)
526                                 return -EINVAL;
527                 } else if (unlikely(
528                            ip->i_d.di_aformat != 0 &&
529                            ip->i_d.di_aformat != XFS_DINODE_FMT_EXTENTS)) {
530                         XFS_ERROR_REPORT("xfs_getbmap", XFS_ERRLEVEL_LOW,
531                                          ip->i_mount);
532                         return -EFSCORRUPTED;
533                 }
534
535                 prealloced = 0;
536                 fixlen = 1LL << 32;
537         } else {
538                 if (ip->i_d.di_format != XFS_DINODE_FMT_EXTENTS &&
539                     ip->i_d.di_format != XFS_DINODE_FMT_BTREE &&
540                     ip->i_d.di_format != XFS_DINODE_FMT_LOCAL)
541                         return -EINVAL;
542
543                 if (xfs_get_extsz_hint(ip) ||
544                     ip->i_d.di_flags & (XFS_DIFLAG_PREALLOC|XFS_DIFLAG_APPEND)){
545                         prealloced = 1;
546                         fixlen = mp->m_super->s_maxbytes;
547                 } else {
548                         prealloced = 0;
549                         fixlen = XFS_ISIZE(ip);
550                 }
551         }
552
553         if (bmv->bmv_length == -1) {
554                 fixlen = XFS_FSB_TO_BB(mp, XFS_B_TO_FSB(mp, fixlen));
555                 bmv->bmv_length =
556                         max_t(__int64_t, fixlen - bmv->bmv_offset, 0);
557         } else if (bmv->bmv_length == 0) {
558                 bmv->bmv_entries = 0;
559                 return 0;
560         } else if (bmv->bmv_length < 0) {
561                 return -EINVAL;
562         }
563
564         nex = bmv->bmv_count - 1;
565         if (nex <= 0)
566                 return -EINVAL;
567         bmvend = bmv->bmv_offset + bmv->bmv_length;
568
569
570         if (bmv->bmv_count > ULONG_MAX / sizeof(struct getbmapx))
571                 return -ENOMEM;
572         out = kmem_zalloc_large(bmv->bmv_count * sizeof(struct getbmapx), 0);
573         if (!out)
574                 return -ENOMEM;
575
576         xfs_ilock(ip, XFS_IOLOCK_SHARED);
577         if (whichfork == XFS_DATA_FORK) {
578                 if (!(iflags & BMV_IF_DELALLOC) &&
579                     (ip->i_delayed_blks || XFS_ISIZE(ip) > ip->i_d.di_size)) {
580                         error = filemap_write_and_wait(VFS_I(ip)->i_mapping);
581                         if (error)
582                                 goto out_unlock_iolock;
583
584                         /*
585                          * Even after flushing the inode, there can still be
586                          * delalloc blocks on the inode beyond EOF due to
587                          * speculative preallocation.  These are not removed
588                          * until the release function is called or the inode
589                          * is inactivated.  Hence we cannot assert here that
590                          * ip->i_delayed_blks == 0.
591                          */
592                 }
593
594                 lock = xfs_ilock_data_map_shared(ip);
595         } else {
596                 lock = xfs_ilock_attr_map_shared(ip);
597         }
598
599         /*
600          * Don't let nex be bigger than the number of extents
601          * we can have assuming alternating holes and real extents.
602          */
603         if (nex > XFS_IFORK_NEXTENTS(ip, whichfork) * 2 + 1)
604                 nex = XFS_IFORK_NEXTENTS(ip, whichfork) * 2 + 1;
605
606         bmapi_flags = xfs_bmapi_aflag(whichfork);
607         if (!(iflags & BMV_IF_PREALLOC))
608                 bmapi_flags |= XFS_BMAPI_IGSTATE;
609
610         /*
611          * Allocate enough space to handle "subnex" maps at a time.
612          */
613         error = -ENOMEM;
614         subnex = 16;
615         map = kmem_alloc(subnex * sizeof(*map), KM_MAYFAIL | KM_NOFS);
616         if (!map)
617                 goto out_unlock_ilock;
618
619         bmv->bmv_entries = 0;
620
621         if (XFS_IFORK_NEXTENTS(ip, whichfork) == 0 &&
622             (whichfork == XFS_ATTR_FORK || !(iflags & BMV_IF_DELALLOC))) {
623                 error = 0;
624                 goto out_free_map;
625         }
626
627         nexleft = nex;
628
629         do {
630                 nmap = (nexleft > subnex) ? subnex : nexleft;
631                 error = xfs_bmapi_read(ip, XFS_BB_TO_FSBT(mp, bmv->bmv_offset),
632                                        XFS_BB_TO_FSB(mp, bmv->bmv_length),
633                                        map, &nmap, bmapi_flags);
634                 if (error)
635                         goto out_free_map;
636                 ASSERT(nmap <= subnex);
637
638                 for (i = 0; i < nmap && nexleft && bmv->bmv_length; i++) {
639                         out[cur_ext].bmv_oflags = 0;
640                         if (map[i].br_state == XFS_EXT_UNWRITTEN)
641                                 out[cur_ext].bmv_oflags |= BMV_OF_PREALLOC;
642                         else if (map[i].br_startblock == DELAYSTARTBLOCK)
643                                 out[cur_ext].bmv_oflags |= BMV_OF_DELALLOC;
644                         out[cur_ext].bmv_offset =
645                                 XFS_FSB_TO_BB(mp, map[i].br_startoff);
646                         out[cur_ext].bmv_length =
647                                 XFS_FSB_TO_BB(mp, map[i].br_blockcount);
648                         out[cur_ext].bmv_unused1 = 0;
649                         out[cur_ext].bmv_unused2 = 0;
650
651                         /*
652                          * delayed allocation extents that start beyond EOF can
653                          * occur due to speculative EOF allocation when the
654                          * delalloc extent is larger than the largest freespace
655                          * extent at conversion time. These extents cannot be
656                          * converted by data writeback, so can exist here even
657                          * if we are not supposed to be finding delalloc
658                          * extents.
659                          */
660                         if (map[i].br_startblock == DELAYSTARTBLOCK &&
661                             map[i].br_startoff <= XFS_B_TO_FSB(mp, XFS_ISIZE(ip)))
662                                 ASSERT((iflags & BMV_IF_DELALLOC) != 0);
663
664                         if (map[i].br_startblock == HOLESTARTBLOCK &&
665                             whichfork == XFS_ATTR_FORK) {
666                                 /* came to the end of attribute fork */
667                                 out[cur_ext].bmv_oflags |= BMV_OF_LAST;
668                                 goto out_free_map;
669                         }
670
671                         if (!xfs_getbmapx_fix_eof_hole(ip, &out[cur_ext],
672                                         prealloced, bmvend,
673                                         map[i].br_startblock))
674                                 goto out_free_map;
675
676                         bmv->bmv_offset =
677                                 out[cur_ext].bmv_offset +
678                                 out[cur_ext].bmv_length;
679                         bmv->bmv_length =
680                                 max_t(__int64_t, 0, bmvend - bmv->bmv_offset);
681
682                         /*
683                          * In case we don't want to return the hole,
684                          * don't increase cur_ext so that we can reuse
685                          * it in the next loop.
686                          */
687                         if ((iflags & BMV_IF_NO_HOLES) &&
688                             map[i].br_startblock == HOLESTARTBLOCK) {
689                                 memset(&out[cur_ext], 0, sizeof(out[cur_ext]));
690                                 continue;
691                         }
692
693                         nexleft--;
694                         bmv->bmv_entries++;
695                         cur_ext++;
696                 }
697         } while (nmap && nexleft && bmv->bmv_length);
698
699  out_free_map:
700         kmem_free(map);
701  out_unlock_ilock:
702         xfs_iunlock(ip, lock);
703  out_unlock_iolock:
704         xfs_iunlock(ip, XFS_IOLOCK_SHARED);
705
706         for (i = 0; i < cur_ext; i++) {
707                 int full = 0;   /* user array is full */
708
709                 /* format results & advance arg */
710                 error = formatter(&arg, &out[i], &full);
711                 if (error || full)
712                         break;
713         }
714
715         kmem_free(out);
716         return error;
717 }
718
719 /*
720  * dead simple method of punching delalyed allocation blocks from a range in
721  * the inode. Walks a block at a time so will be slow, but is only executed in
722  * rare error cases so the overhead is not critical. This will always punch out
723  * both the start and end blocks, even if the ranges only partially overlap
724  * them, so it is up to the caller to ensure that partial blocks are not
725  * passed in.
726  */
727 int
728 xfs_bmap_punch_delalloc_range(
729         struct xfs_inode        *ip,
730         xfs_fileoff_t           start_fsb,
731         xfs_fileoff_t           length)
732 {
733         xfs_fileoff_t           remaining = length;
734         int                     error = 0;
735
736         ASSERT(xfs_isilocked(ip, XFS_ILOCK_EXCL));
737
738         do {
739                 int             done;
740                 xfs_bmbt_irec_t imap;
741                 int             nimaps = 1;
742                 xfs_fsblock_t   firstblock;
743                 xfs_bmap_free_t flist;
744
745                 /*
746                  * Map the range first and check that it is a delalloc extent
747                  * before trying to unmap the range. Otherwise we will be
748                  * trying to remove a real extent (which requires a
749                  * transaction) or a hole, which is probably a bad idea...
750                  */
751                 error = xfs_bmapi_read(ip, start_fsb, 1, &imap, &nimaps,
752                                        XFS_BMAPI_ENTIRE);
753
754                 if (error) {
755                         /* something screwed, just bail */
756                         if (!XFS_FORCED_SHUTDOWN(ip->i_mount)) {
757                                 xfs_alert(ip->i_mount,
758                         "Failed delalloc mapping lookup ino %lld fsb %lld.",
759                                                 ip->i_ino, start_fsb);
760                         }
761                         break;
762                 }
763                 if (!nimaps) {
764                         /* nothing there */
765                         goto next_block;
766                 }
767                 if (imap.br_startblock != DELAYSTARTBLOCK) {
768                         /* been converted, ignore */
769                         goto next_block;
770                 }
771                 WARN_ON(imap.br_blockcount == 0);
772
773                 /*
774                  * Note: while we initialise the firstblock/flist pair, they
775                  * should never be used because blocks should never be
776                  * allocated or freed for a delalloc extent and hence we need
777                  * don't cancel or finish them after the xfs_bunmapi() call.
778                  */
779                 xfs_bmap_init(&flist, &firstblock);
780                 error = xfs_bunmapi(NULL, ip, start_fsb, 1, 0, 1, &firstblock,
781                                         &flist, &done);
782                 if (error)
783                         break;
784
785                 ASSERT(!flist.xbf_count && !flist.xbf_first);
786 next_block:
787                 start_fsb++;
788                 remaining--;
789         } while(remaining > 0);
790
791         return error;
792 }
793
794 /*
795  * Test whether it is appropriate to check an inode for and free post EOF
796  * blocks. The 'force' parameter determines whether we should also consider
797  * regular files that are marked preallocated or append-only.
798  */
799 bool
800 xfs_can_free_eofblocks(struct xfs_inode *ip, bool force)
801 {
802         /* prealloc/delalloc exists only on regular files */
803         if (!S_ISREG(ip->i_d.di_mode))
804                 return false;
805
806         /*
807          * Zero sized files with no cached pages and delalloc blocks will not
808          * have speculative prealloc/delalloc blocks to remove.
809          */
810         if (VFS_I(ip)->i_size == 0 &&
811             VFS_I(ip)->i_mapping->nrpages == 0 &&
812             ip->i_delayed_blks == 0)
813                 return false;
814
815         /* If we haven't read in the extent list, then don't do it now. */
816         if (!(ip->i_df.if_flags & XFS_IFEXTENTS))
817                 return false;
818
819         /*
820          * Do not free real preallocated or append-only files unless the file
821          * has delalloc blocks and we are forced to remove them.
822          */
823         if (ip->i_d.di_flags & (XFS_DIFLAG_PREALLOC | XFS_DIFLAG_APPEND))
824                 if (!force || ip->i_delayed_blks == 0)
825                         return false;
826
827         return true;
828 }
829
830 /*
831  * This is called by xfs_inactive to free any blocks beyond eof
832  * when the link count isn't zero and by xfs_dm_punch_hole() when
833  * punching a hole to EOF.
834  */
835 int
836 xfs_free_eofblocks(
837         xfs_mount_t     *mp,
838         xfs_inode_t     *ip,
839         bool            need_iolock)
840 {
841         xfs_trans_t     *tp;
842         int             error;
843         xfs_fileoff_t   end_fsb;
844         xfs_fileoff_t   last_fsb;
845         xfs_filblks_t   map_len;
846         int             nimaps;
847         xfs_bmbt_irec_t imap;
848
849         /*
850          * Figure out if there are any blocks beyond the end
851          * of the file.  If not, then there is nothing to do.
852          */
853         end_fsb = XFS_B_TO_FSB(mp, (xfs_ufsize_t)XFS_ISIZE(ip));
854         last_fsb = XFS_B_TO_FSB(mp, mp->m_super->s_maxbytes);
855         if (last_fsb <= end_fsb)
856                 return 0;
857         map_len = last_fsb - end_fsb;
858
859         nimaps = 1;
860         xfs_ilock(ip, XFS_ILOCK_SHARED);
861         error = xfs_bmapi_read(ip, end_fsb, map_len, &imap, &nimaps, 0);
862         xfs_iunlock(ip, XFS_ILOCK_SHARED);
863
864         if (!error && (nimaps != 0) &&
865             (imap.br_startblock != HOLESTARTBLOCK ||
866              ip->i_delayed_blks)) {
867                 /*
868                  * Attach the dquots to the inode up front.
869                  */
870                 error = xfs_qm_dqattach(ip, 0);
871                 if (error)
872                         return error;
873
874                 /*
875                  * There are blocks after the end of file.
876                  * Free them up now by truncating the file to
877                  * its current size.
878                  */
879                 tp = xfs_trans_alloc(mp, XFS_TRANS_INACTIVE);
880
881                 if (need_iolock) {
882                         if (!xfs_ilock_nowait(ip, XFS_IOLOCK_EXCL)) {
883                                 xfs_trans_cancel(tp, 0);
884                                 return -EAGAIN;
885                         }
886                 }
887
888                 error = xfs_trans_reserve(tp, &M_RES(mp)->tr_itruncate, 0, 0);
889                 if (error) {
890                         ASSERT(XFS_FORCED_SHUTDOWN(mp));
891                         xfs_trans_cancel(tp, 0);
892                         if (need_iolock)
893                                 xfs_iunlock(ip, XFS_IOLOCK_EXCL);
894                         return error;
895                 }
896
897                 xfs_ilock(ip, XFS_ILOCK_EXCL);
898                 xfs_trans_ijoin(tp, ip, 0);
899
900                 /*
901                  * Do not update the on-disk file size.  If we update the
902                  * on-disk file size and then the system crashes before the
903                  * contents of the file are flushed to disk then the files
904                  * may be full of holes (ie NULL files bug).
905                  */
906                 error = xfs_itruncate_extents(&tp, ip, XFS_DATA_FORK,
907                                               XFS_ISIZE(ip));
908                 if (error) {
909                         /*
910                          * If we get an error at this point we simply don't
911                          * bother truncating the file.
912                          */
913                         xfs_trans_cancel(tp,
914                                          (XFS_TRANS_RELEASE_LOG_RES |
915                                           XFS_TRANS_ABORT));
916                 } else {
917                         error = xfs_trans_commit(tp,
918                                                 XFS_TRANS_RELEASE_LOG_RES);
919                         if (!error)
920                                 xfs_inode_clear_eofblocks_tag(ip);
921                 }
922
923                 xfs_iunlock(ip, XFS_ILOCK_EXCL);
924                 if (need_iolock)
925                         xfs_iunlock(ip, XFS_IOLOCK_EXCL);
926         }
927         return error;
928 }
929
930 int
931 xfs_alloc_file_space(
932         struct xfs_inode        *ip,
933         xfs_off_t               offset,
934         xfs_off_t               len,
935         int                     alloc_type)
936 {
937         xfs_mount_t             *mp = ip->i_mount;
938         xfs_off_t               count;
939         xfs_filblks_t           allocated_fsb;
940         xfs_filblks_t           allocatesize_fsb;
941         xfs_extlen_t            extsz, temp;
942         xfs_fileoff_t           startoffset_fsb;
943         xfs_fsblock_t           firstfsb;
944         int                     nimaps;
945         int                     quota_flag;
946         int                     rt;
947         xfs_trans_t             *tp;
948         xfs_bmbt_irec_t         imaps[1], *imapp;
949         xfs_bmap_free_t         free_list;
950         uint                    qblocks, resblks, resrtextents;
951         int                     committed;
952         int                     error;
953
954         trace_xfs_alloc_file_space(ip);
955
956         if (XFS_FORCED_SHUTDOWN(mp))
957                 return -EIO;
958
959         error = xfs_qm_dqattach(ip, 0);
960         if (error)
961                 return error;
962
963         if (len <= 0)
964                 return -EINVAL;
965
966         rt = XFS_IS_REALTIME_INODE(ip);
967         extsz = xfs_get_extsz_hint(ip);
968
969         count = len;
970         imapp = &imaps[0];
971         nimaps = 1;
972         startoffset_fsb = XFS_B_TO_FSBT(mp, offset);
973         allocatesize_fsb = XFS_B_TO_FSB(mp, count);
974
975         /*
976          * Allocate file space until done or until there is an error
977          */
978         while (allocatesize_fsb && !error) {
979                 xfs_fileoff_t   s, e;
980
981                 /*
982                  * Determine space reservations for data/realtime.
983                  */
984                 if (unlikely(extsz)) {
985                         s = startoffset_fsb;
986                         do_div(s, extsz);
987                         s *= extsz;
988                         e = startoffset_fsb + allocatesize_fsb;
989                         if ((temp = do_mod(startoffset_fsb, extsz)))
990                                 e += temp;
991                         if ((temp = do_mod(e, extsz)))
992                                 e += extsz - temp;
993                 } else {
994                         s = 0;
995                         e = allocatesize_fsb;
996                 }
997
998                 /*
999                  * The transaction reservation is limited to a 32-bit block
1000                  * count, hence we need to limit the number of blocks we are
1001                  * trying to reserve to avoid an overflow. We can't allocate
1002                  * more than @nimaps extents, and an extent is limited on disk
1003                  * to MAXEXTLEN (21 bits), so use that to enforce the limit.
1004                  */
1005                 resblks = min_t(xfs_fileoff_t, (e - s), (MAXEXTLEN * nimaps));
1006                 if (unlikely(rt)) {
1007                         resrtextents = qblocks = resblks;
1008                         resrtextents /= mp->m_sb.sb_rextsize;
1009                         resblks = XFS_DIOSTRAT_SPACE_RES(mp, 0);
1010                         quota_flag = XFS_QMOPT_RES_RTBLKS;
1011                 } else {
1012                         resrtextents = 0;
1013                         resblks = qblocks = XFS_DIOSTRAT_SPACE_RES(mp, resblks);
1014                         quota_flag = XFS_QMOPT_RES_REGBLKS;
1015                 }
1016
1017                 /*
1018                  * Allocate and setup the transaction.
1019                  */
1020                 tp = xfs_trans_alloc(mp, XFS_TRANS_DIOSTRAT);
1021                 error = xfs_trans_reserve(tp, &M_RES(mp)->tr_write,
1022                                           resblks, resrtextents);
1023                 /*
1024                  * Check for running out of space
1025                  */
1026                 if (error) {
1027                         /*
1028                          * Free the transaction structure.
1029                          */
1030                         ASSERT(error == -ENOSPC || XFS_FORCED_SHUTDOWN(mp));
1031                         xfs_trans_cancel(tp, 0);
1032                         break;
1033                 }
1034                 xfs_ilock(ip, XFS_ILOCK_EXCL);
1035                 error = xfs_trans_reserve_quota_nblks(tp, ip, qblocks,
1036                                                       0, quota_flag);
1037                 if (error)
1038                         goto error1;
1039
1040                 xfs_trans_ijoin(tp, ip, 0);
1041
1042                 xfs_bmap_init(&free_list, &firstfsb);
1043                 error = xfs_bmapi_write(tp, ip, startoffset_fsb,
1044                                         allocatesize_fsb, alloc_type, &firstfsb,
1045                                         0, imapp, &nimaps, &free_list);
1046                 if (error) {
1047                         goto error0;
1048                 }
1049
1050                 /*
1051                  * Complete the transaction
1052                  */
1053                 error = xfs_bmap_finish(&tp, &free_list, &committed);
1054                 if (error) {
1055                         goto error0;
1056                 }
1057
1058                 error = xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
1059                 xfs_iunlock(ip, XFS_ILOCK_EXCL);
1060                 if (error) {
1061                         break;
1062                 }
1063
1064                 allocated_fsb = imapp->br_blockcount;
1065
1066                 if (nimaps == 0) {
1067                         error = -ENOSPC;
1068                         break;
1069                 }
1070
1071                 startoffset_fsb += allocated_fsb;
1072                 allocatesize_fsb -= allocated_fsb;
1073         }
1074
1075         return error;
1076
1077 error0: /* Cancel bmap, unlock inode, unreserve quota blocks, cancel trans */
1078         xfs_bmap_cancel(&free_list);
1079         xfs_trans_unreserve_quota_nblks(tp, ip, (long)qblocks, 0, quota_flag);
1080
1081 error1: /* Just cancel transaction */
1082         xfs_trans_cancel(tp, XFS_TRANS_RELEASE_LOG_RES | XFS_TRANS_ABORT);
1083         xfs_iunlock(ip, XFS_ILOCK_EXCL);
1084         return error;
1085 }
1086
1087 /*
1088  * Zero file bytes between startoff and endoff inclusive.
1089  * The iolock is held exclusive and no blocks are buffered.
1090  *
1091  * This function is used by xfs_free_file_space() to zero
1092  * partial blocks when the range to free is not block aligned.
1093  * When unreserving space with boundaries that are not block
1094  * aligned we round up the start and round down the end
1095  * boundaries and then use this function to zero the parts of
1096  * the blocks that got dropped during the rounding.
1097  */
1098 STATIC int
1099 xfs_zero_remaining_bytes(
1100         xfs_inode_t             *ip,
1101         xfs_off_t               startoff,
1102         xfs_off_t               endoff)
1103 {
1104         xfs_bmbt_irec_t         imap;
1105         xfs_fileoff_t           offset_fsb;
1106         xfs_off_t               lastoffset;
1107         xfs_off_t               offset;
1108         xfs_buf_t               *bp;
1109         xfs_mount_t             *mp = ip->i_mount;
1110         int                     nimap;
1111         int                     error = 0;
1112
1113         /*
1114          * Avoid doing I/O beyond eof - it's not necessary
1115          * since nothing can read beyond eof.  The space will
1116          * be zeroed when the file is extended anyway.
1117          */
1118         if (startoff >= XFS_ISIZE(ip))
1119                 return 0;
1120
1121         if (endoff > XFS_ISIZE(ip))
1122                 endoff = XFS_ISIZE(ip);
1123
1124         for (offset = startoff; offset <= endoff; offset = lastoffset + 1) {
1125                 uint lock_mode;
1126
1127                 offset_fsb = XFS_B_TO_FSBT(mp, offset);
1128                 nimap = 1;
1129
1130                 lock_mode = xfs_ilock_data_map_shared(ip);
1131                 error = xfs_bmapi_read(ip, offset_fsb, 1, &imap, &nimap, 0);
1132                 xfs_iunlock(ip, lock_mode);
1133
1134                 if (error || nimap < 1)
1135                         break;
1136                 ASSERT(imap.br_blockcount >= 1);
1137                 ASSERT(imap.br_startoff == offset_fsb);
1138                 lastoffset = XFS_FSB_TO_B(mp, imap.br_startoff + 1) - 1;
1139                 if (lastoffset > endoff)
1140                         lastoffset = endoff;
1141                 if (imap.br_startblock == HOLESTARTBLOCK)
1142                         continue;
1143                 ASSERT(imap.br_startblock != DELAYSTARTBLOCK);
1144                 if (imap.br_state == XFS_EXT_UNWRITTEN)
1145                         continue;
1146
1147                 error = xfs_buf_read_uncached(XFS_IS_REALTIME_INODE(ip) ?
1148                                 mp->m_rtdev_targp : mp->m_ddev_targp,
1149                                 xfs_fsb_to_db(ip, imap.br_startblock),
1150                                 BTOBB(mp->m_sb.sb_blocksize),
1151                                 0, &bp, NULL);
1152                 if (error)
1153                         return error;
1154
1155                 memset(bp->b_addr +
1156                                 (offset - XFS_FSB_TO_B(mp, imap.br_startoff)),
1157                        0, lastoffset - offset + 1);
1158
1159                 error = xfs_bwrite(bp);
1160                 xfs_buf_relse(bp);
1161                 if (error)
1162                         return error;
1163         }
1164         return error;
1165 }
1166
1167 int
1168 xfs_free_file_space(
1169         struct xfs_inode        *ip,
1170         xfs_off_t               offset,
1171         xfs_off_t               len)
1172 {
1173         int                     committed;
1174         int                     done;
1175         xfs_fileoff_t           endoffset_fsb;
1176         int                     error;
1177         xfs_fsblock_t           firstfsb;
1178         xfs_bmap_free_t         free_list;
1179         xfs_bmbt_irec_t         imap;
1180         xfs_off_t               ioffset;
1181         xfs_off_t               iendoffset;
1182         xfs_extlen_t            mod=0;
1183         xfs_mount_t             *mp;
1184         int                     nimap;
1185         uint                    resblks;
1186         xfs_off_t               rounding;
1187         int                     rt;
1188         xfs_fileoff_t           startoffset_fsb;
1189         xfs_trans_t             *tp;
1190
1191         mp = ip->i_mount;
1192
1193         trace_xfs_free_file_space(ip);
1194
1195         error = xfs_qm_dqattach(ip, 0);
1196         if (error)
1197                 return error;
1198
1199         error = 0;
1200         if (len <= 0)   /* if nothing being freed */
1201                 return error;
1202         rt = XFS_IS_REALTIME_INODE(ip);
1203         startoffset_fsb = XFS_B_TO_FSB(mp, offset);
1204         endoffset_fsb = XFS_B_TO_FSBT(mp, offset + len);
1205
1206         /* wait for the completion of any pending DIOs */
1207         inode_dio_wait(VFS_I(ip));
1208
1209         rounding = max_t(xfs_off_t, 1 << mp->m_sb.sb_blocklog, PAGE_CACHE_SIZE);
1210         ioffset = round_down(offset, rounding);
1211         iendoffset = round_up(offset + len, rounding) - 1;
1212         error = filemap_write_and_wait_range(VFS_I(ip)->i_mapping, ioffset,
1213                                              iendoffset);
1214         if (error)
1215                 goto out;
1216         truncate_pagecache_range(VFS_I(ip), ioffset, iendoffset);
1217
1218         /*
1219          * Need to zero the stuff we're not freeing, on disk.
1220          * If it's a realtime file & can't use unwritten extents then we
1221          * actually need to zero the extent edges.  Otherwise xfs_bunmapi
1222          * will take care of it for us.
1223          */
1224         if (rt && !xfs_sb_version_hasextflgbit(&mp->m_sb)) {
1225                 nimap = 1;
1226                 error = xfs_bmapi_read(ip, startoffset_fsb, 1,
1227                                         &imap, &nimap, 0);
1228                 if (error)
1229                         goto out;
1230                 ASSERT(nimap == 0 || nimap == 1);
1231                 if (nimap && imap.br_startblock != HOLESTARTBLOCK) {
1232                         xfs_daddr_t     block;
1233
1234                         ASSERT(imap.br_startblock != DELAYSTARTBLOCK);
1235                         block = imap.br_startblock;
1236                         mod = do_div(block, mp->m_sb.sb_rextsize);
1237                         if (mod)
1238                                 startoffset_fsb += mp->m_sb.sb_rextsize - mod;
1239                 }
1240                 nimap = 1;
1241                 error = xfs_bmapi_read(ip, endoffset_fsb - 1, 1,
1242                                         &imap, &nimap, 0);
1243                 if (error)
1244                         goto out;
1245                 ASSERT(nimap == 0 || nimap == 1);
1246                 if (nimap && imap.br_startblock != HOLESTARTBLOCK) {
1247                         ASSERT(imap.br_startblock != DELAYSTARTBLOCK);
1248                         mod++;
1249                         if (mod && (mod != mp->m_sb.sb_rextsize))
1250                                 endoffset_fsb -= mod;
1251                 }
1252         }
1253         if ((done = (endoffset_fsb <= startoffset_fsb)))
1254                 /*
1255                  * One contiguous piece to clear
1256                  */
1257                 error = xfs_zero_remaining_bytes(ip, offset, offset + len - 1);
1258         else {
1259                 /*
1260                  * Some full blocks, possibly two pieces to clear
1261                  */
1262                 if (offset < XFS_FSB_TO_B(mp, startoffset_fsb))
1263                         error = xfs_zero_remaining_bytes(ip, offset,
1264                                 XFS_FSB_TO_B(mp, startoffset_fsb) - 1);
1265                 if (!error &&
1266                     XFS_FSB_TO_B(mp, endoffset_fsb) < offset + len)
1267                         error = xfs_zero_remaining_bytes(ip,
1268                                 XFS_FSB_TO_B(mp, endoffset_fsb),
1269                                 offset + len - 1);
1270         }
1271
1272         /*
1273          * free file space until done or until there is an error
1274          */
1275         resblks = XFS_DIOSTRAT_SPACE_RES(mp, 0);
1276         while (!error && !done) {
1277
1278                 /*
1279                  * allocate and setup the transaction. Allow this
1280                  * transaction to dip into the reserve blocks to ensure
1281                  * the freeing of the space succeeds at ENOSPC.
1282                  */
1283                 tp = xfs_trans_alloc(mp, XFS_TRANS_DIOSTRAT);
1284                 error = xfs_trans_reserve(tp, &M_RES(mp)->tr_write, resblks, 0);
1285
1286                 /*
1287                  * check for running out of space
1288                  */
1289                 if (error) {
1290                         /*
1291                          * Free the transaction structure.
1292                          */
1293                         ASSERT(error == -ENOSPC || XFS_FORCED_SHUTDOWN(mp));
1294                         xfs_trans_cancel(tp, 0);
1295                         break;
1296                 }
1297                 xfs_ilock(ip, XFS_ILOCK_EXCL);
1298                 error = xfs_trans_reserve_quota(tp, mp,
1299                                 ip->i_udquot, ip->i_gdquot, ip->i_pdquot,
1300                                 resblks, 0, XFS_QMOPT_RES_REGBLKS);
1301                 if (error)
1302                         goto error1;
1303
1304                 xfs_trans_ijoin(tp, ip, 0);
1305
1306                 /*
1307                  * issue the bunmapi() call to free the blocks
1308                  */
1309                 xfs_bmap_init(&free_list, &firstfsb);
1310                 error = xfs_bunmapi(tp, ip, startoffset_fsb,
1311                                   endoffset_fsb - startoffset_fsb,
1312                                   0, 2, &firstfsb, &free_list, &done);
1313                 if (error) {
1314                         goto error0;
1315                 }
1316
1317                 /*
1318                  * complete the transaction
1319                  */
1320                 error = xfs_bmap_finish(&tp, &free_list, &committed);
1321                 if (error) {
1322                         goto error0;
1323                 }
1324
1325                 error = xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
1326                 xfs_iunlock(ip, XFS_ILOCK_EXCL);
1327         }
1328
1329  out:
1330         return error;
1331
1332  error0:
1333         xfs_bmap_cancel(&free_list);
1334  error1:
1335         xfs_trans_cancel(tp, XFS_TRANS_RELEASE_LOG_RES | XFS_TRANS_ABORT);
1336         xfs_iunlock(ip, XFS_ILOCK_EXCL);
1337         goto out;
1338 }
1339
1340
1341 int
1342 xfs_zero_file_space(
1343         struct xfs_inode        *ip,
1344         xfs_off_t               offset,
1345         xfs_off_t               len)
1346 {
1347         struct xfs_mount        *mp = ip->i_mount;
1348         uint                    granularity;
1349         xfs_off_t               start_boundary;
1350         xfs_off_t               end_boundary;
1351         int                     error;
1352
1353         trace_xfs_zero_file_space(ip);
1354
1355         granularity = max_t(uint, 1 << mp->m_sb.sb_blocklog, PAGE_CACHE_SIZE);
1356
1357         /*
1358          * Round the range of extents we are going to convert inwards.  If the
1359          * offset is aligned, then it doesn't get changed so we zero from the
1360          * start of the block offset points to.
1361          */
1362         start_boundary = round_up(offset, granularity);
1363         end_boundary = round_down(offset + len, granularity);
1364
1365         ASSERT(start_boundary >= offset);
1366         ASSERT(end_boundary <= offset + len);
1367
1368         if (start_boundary < end_boundary - 1) {
1369                 /*
1370                  * Writeback the range to ensure any inode size updates due to
1371                  * appending writes make it to disk (otherwise we could just
1372                  * punch out the delalloc blocks).
1373                  */
1374                 error = filemap_write_and_wait_range(VFS_I(ip)->i_mapping,
1375                                 start_boundary, end_boundary - 1);
1376                 if (error)
1377                         goto out;
1378                 truncate_pagecache_range(VFS_I(ip), start_boundary,
1379                                          end_boundary - 1);
1380
1381                 /* convert the blocks */
1382                 error = xfs_alloc_file_space(ip, start_boundary,
1383                                         end_boundary - start_boundary - 1,
1384                                         XFS_BMAPI_PREALLOC | XFS_BMAPI_CONVERT);
1385                 if (error)
1386                         goto out;
1387
1388                 /* We've handled the interior of the range, now for the edges */
1389                 if (start_boundary != offset) {
1390                         error = xfs_iozero(ip, offset, start_boundary - offset);
1391                         if (error)
1392                                 goto out;
1393                 }
1394
1395                 if (end_boundary != offset + len)
1396                         error = xfs_iozero(ip, end_boundary,
1397                                            offset + len - end_boundary);
1398
1399         } else {
1400                 /*
1401                  * It's either a sub-granularity range or the range spanned lies
1402                  * partially across two adjacent blocks.
1403                  */
1404                 error = xfs_iozero(ip, offset, len);
1405         }
1406
1407 out:
1408         return error;
1409
1410 }
1411
1412 /*
1413  * xfs_collapse_file_space()
1414  *      This routine frees disk space and shift extent for the given file.
1415  *      The first thing we do is to free data blocks in the specified range
1416  *      by calling xfs_free_file_space(). It would also sync dirty data
1417  *      and invalidate page cache over the region on which collapse range
1418  *      is working. And Shift extent records to the left to cover a hole.
1419  * RETURNS:
1420  *      0 on success
1421  *      errno on error
1422  *
1423  */
1424 int
1425 xfs_collapse_file_space(
1426         struct xfs_inode        *ip,
1427         xfs_off_t               offset,
1428         xfs_off_t               len)
1429 {
1430         int                     done = 0;
1431         struct xfs_mount        *mp = ip->i_mount;
1432         struct xfs_trans        *tp;
1433         int                     error;
1434         struct xfs_bmap_free    free_list;
1435         xfs_fsblock_t           first_block;
1436         int                     committed;
1437         xfs_fileoff_t           start_fsb;
1438         xfs_fileoff_t           next_fsb;
1439         xfs_fileoff_t           shift_fsb;
1440
1441         ASSERT(xfs_isilocked(ip, XFS_IOLOCK_EXCL));
1442
1443         trace_xfs_collapse_file_space(ip);
1444
1445         next_fsb = XFS_B_TO_FSB(mp, offset + len);
1446         shift_fsb = XFS_B_TO_FSB(mp, len);
1447
1448         error = xfs_free_file_space(ip, offset, len);
1449         if (error)
1450                 return error;
1451
1452         /*
1453          * Trim eofblocks to avoid shifting uninitialized post-eof preallocation
1454          * into the accessible region of the file.
1455          */
1456         if (xfs_can_free_eofblocks(ip, true)) {
1457                 error = xfs_free_eofblocks(mp, ip, false);
1458                 if (error)
1459                         return error;
1460         }
1461
1462         /*
1463          * Writeback and invalidate cache for the remainder of the file as we're
1464          * about to shift down every extent from the collapse range to EOF. The
1465          * free of the collapse range above might have already done some of
1466          * this, but we shouldn't rely on it to do anything outside of the range
1467          * that was freed.
1468          */
1469         error = filemap_write_and_wait_range(VFS_I(ip)->i_mapping,
1470                                              offset + len, -1);
1471         if (error)
1472                 return error;
1473         error = invalidate_inode_pages2_range(VFS_I(ip)->i_mapping,
1474                                         (offset + len) >> PAGE_CACHE_SHIFT, -1);
1475         if (error)
1476                 return error;
1477
1478         while (!error && !done) {
1479                 tp = xfs_trans_alloc(mp, XFS_TRANS_DIOSTRAT);
1480                 /*
1481                  * We would need to reserve permanent block for transaction.
1482                  * This will come into picture when after shifting extent into
1483                  * hole we found that adjacent extents can be merged which
1484                  * may lead to freeing of a block during record update.
1485                  */
1486                 error = xfs_trans_reserve(tp, &M_RES(mp)->tr_write,
1487                                 XFS_DIOSTRAT_SPACE_RES(mp, 0), 0);
1488                 if (error) {
1489                         xfs_trans_cancel(tp, 0);
1490                         break;
1491                 }
1492
1493                 xfs_ilock(ip, XFS_ILOCK_EXCL);
1494                 error = xfs_trans_reserve_quota(tp, mp, ip->i_udquot,
1495                                 ip->i_gdquot, ip->i_pdquot,
1496                                 XFS_DIOSTRAT_SPACE_RES(mp, 0), 0,
1497                                 XFS_QMOPT_RES_REGBLKS);
1498                 if (error)
1499                         goto out;
1500
1501                 xfs_trans_ijoin(tp, ip, 0);
1502
1503                 xfs_bmap_init(&free_list, &first_block);
1504
1505                 /*
1506                  * We are using the write transaction in which max 2 bmbt
1507                  * updates are allowed
1508                  */
1509                 start_fsb = next_fsb;
1510                 error = xfs_bmap_shift_extents(tp, ip, start_fsb, shift_fsb,
1511                                 &done, &next_fsb, &first_block, &free_list,
1512                                 XFS_BMAP_MAX_SHIFT_EXTENTS);
1513                 if (error)
1514                         goto out;
1515
1516                 error = xfs_bmap_finish(&tp, &free_list, &committed);
1517                 if (error)
1518                         goto out;
1519
1520                 error = xfs_trans_commit(tp, XFS_TRANS_RELEASE_LOG_RES);
1521                 xfs_iunlock(ip, XFS_ILOCK_EXCL);
1522         }
1523
1524         return error;
1525
1526 out:
1527         xfs_trans_cancel(tp, XFS_TRANS_RELEASE_LOG_RES | XFS_TRANS_ABORT);
1528         xfs_iunlock(ip, XFS_ILOCK_EXCL);
1529         return error;
1530 }
1531
1532 /*
1533  * We need to check that the format of the data fork in the temporary inode is
1534  * valid for the target inode before doing the swap. This is not a problem with
1535  * attr1 because of the fixed fork offset, but attr2 has a dynamically sized
1536  * data fork depending on the space the attribute fork is taking so we can get
1537  * invalid formats on the target inode.
1538  *
1539  * E.g. target has space for 7 extents in extent format, temp inode only has
1540  * space for 6.  If we defragment down to 7 extents, then the tmp format is a
1541  * btree, but when swapped it needs to be in extent format. Hence we can't just
1542  * blindly swap data forks on attr2 filesystems.
1543  *
1544  * Note that we check the swap in both directions so that we don't end up with
1545  * a corrupt temporary inode, either.
1546  *
1547  * Note that fixing the way xfs_fsr sets up the attribute fork in the source
1548  * inode will prevent this situation from occurring, so all we do here is
1549  * reject and log the attempt. basically we are putting the responsibility on
1550  * userspace to get this right.
1551  */
1552 static int
1553 xfs_swap_extents_check_format(
1554         xfs_inode_t     *ip,    /* target inode */
1555         xfs_inode_t     *tip)   /* tmp inode */
1556 {
1557
1558         /* Should never get a local format */
1559         if (ip->i_d.di_format == XFS_DINODE_FMT_LOCAL ||
1560             tip->i_d.di_format == XFS_DINODE_FMT_LOCAL)
1561                 return -EINVAL;
1562
1563         /*
1564          * if the target inode has less extents that then temporary inode then
1565          * why did userspace call us?
1566          */
1567         if (ip->i_d.di_nextents < tip->i_d.di_nextents)
1568                 return -EINVAL;
1569
1570         /*
1571          * if the target inode is in extent form and the temp inode is in btree
1572          * form then we will end up with the target inode in the wrong format
1573          * as we already know there are less extents in the temp inode.
1574          */
1575         if (ip->i_d.di_format == XFS_DINODE_FMT_EXTENTS &&
1576             tip->i_d.di_format == XFS_DINODE_FMT_BTREE)
1577                 return -EINVAL;
1578
1579         /* Check temp in extent form to max in target */
1580         if (tip->i_d.di_format == XFS_DINODE_FMT_EXTENTS &&
1581             XFS_IFORK_NEXTENTS(tip, XFS_DATA_FORK) >
1582                         XFS_IFORK_MAXEXT(ip, XFS_DATA_FORK))
1583                 return -EINVAL;
1584
1585         /* Check target in extent form to max in temp */
1586         if (ip->i_d.di_format == XFS_DINODE_FMT_EXTENTS &&
1587             XFS_IFORK_NEXTENTS(ip, XFS_DATA_FORK) >
1588                         XFS_IFORK_MAXEXT(tip, XFS_DATA_FORK))
1589                 return -EINVAL;
1590
1591         /*
1592          * If we are in a btree format, check that the temp root block will fit
1593          * in the target and that it has enough extents to be in btree format
1594          * in the target.
1595          *
1596          * Note that we have to be careful to allow btree->extent conversions
1597          * (a common defrag case) which will occur when the temp inode is in
1598          * extent format...
1599          */
1600         if (tip->i_d.di_format == XFS_DINODE_FMT_BTREE) {
1601                 if (XFS_IFORK_BOFF(ip) &&
1602                     XFS_BMAP_BMDR_SPACE(tip->i_df.if_broot) > XFS_IFORK_BOFF(ip))
1603                         return -EINVAL;
1604                 if (XFS_IFORK_NEXTENTS(tip, XFS_DATA_FORK) <=
1605                     XFS_IFORK_MAXEXT(ip, XFS_DATA_FORK))
1606                         return -EINVAL;
1607         }
1608
1609         /* Reciprocal target->temp btree format checks */
1610         if (ip->i_d.di_format == XFS_DINODE_FMT_BTREE) {
1611                 if (XFS_IFORK_BOFF(tip) &&
1612                     XFS_BMAP_BMDR_SPACE(ip->i_df.if_broot) > XFS_IFORK_BOFF(tip))
1613                         return -EINVAL;
1614                 if (XFS_IFORK_NEXTENTS(ip, XFS_DATA_FORK) <=
1615                     XFS_IFORK_MAXEXT(tip, XFS_DATA_FORK))
1616                         return -EINVAL;
1617         }
1618
1619         return 0;
1620 }
1621
1622 static int
1623 xfs_swap_extent_flush(
1624         struct xfs_inode        *ip)
1625 {
1626         int     error;
1627
1628         error = filemap_write_and_wait(VFS_I(ip)->i_mapping);
1629         if (error)
1630                 return error;
1631         truncate_pagecache_range(VFS_I(ip), 0, -1);
1632
1633         /* Verify O_DIRECT for ftmp */
1634         if (VFS_I(ip)->i_mapping->nrpages)
1635                 return -EINVAL;
1636
1637         /*
1638          * Don't try to swap extents on mmap()d files because we can't lock
1639          * out races against page faults safely.
1640          */
1641         if (mapping_mapped(VFS_I(ip)->i_mapping))
1642                 return -EBUSY;
1643         return 0;
1644 }
1645
1646 int
1647 xfs_swap_extents(
1648         xfs_inode_t     *ip,    /* target inode */
1649         xfs_inode_t     *tip,   /* tmp inode */
1650         xfs_swapext_t   *sxp)
1651 {
1652         xfs_mount_t     *mp = ip->i_mount;
1653         xfs_trans_t     *tp;
1654         xfs_bstat_t     *sbp = &sxp->sx_stat;
1655         xfs_ifork_t     *tempifp, *ifp, *tifp;
1656         int             src_log_flags, target_log_flags;
1657         int             error = 0;
1658         int             aforkblks = 0;
1659         int             taforkblks = 0;
1660         __uint64_t      tmp;
1661         int             lock_flags;
1662
1663         tempifp = kmem_alloc(sizeof(xfs_ifork_t), KM_MAYFAIL);
1664         if (!tempifp) {
1665                 error = -ENOMEM;
1666                 goto out;
1667         }
1668
1669         /*
1670          * Lock up the inodes against other IO and truncate to begin with.
1671          * Then we can ensure the inodes are flushed and have no page cache
1672          * safely. Once we have done this we can take the ilocks and do the rest
1673          * of the checks.
1674          */
1675         lock_flags = XFS_IOLOCK_EXCL;
1676         xfs_lock_two_inodes(ip, tip, XFS_IOLOCK_EXCL);
1677
1678         /* Verify that both files have the same format */
1679         if ((ip->i_d.di_mode & S_IFMT) != (tip->i_d.di_mode & S_IFMT)) {
1680                 error = -EINVAL;
1681                 goto out_unlock;
1682         }
1683
1684         /* Verify both files are either real-time or non-realtime */
1685         if (XFS_IS_REALTIME_INODE(ip) != XFS_IS_REALTIME_INODE(tip)) {
1686                 error = -EINVAL;
1687                 goto out_unlock;
1688         }
1689
1690         error = xfs_swap_extent_flush(ip);
1691         if (error)
1692                 goto out_unlock;
1693         error = xfs_swap_extent_flush(tip);
1694         if (error)
1695                 goto out_unlock;
1696
1697         tp = xfs_trans_alloc(mp, XFS_TRANS_SWAPEXT);
1698         error = xfs_trans_reserve(tp, &M_RES(mp)->tr_ichange, 0, 0);
1699         if (error) {
1700                 xfs_trans_cancel(tp, 0);
1701                 goto out_unlock;
1702         }
1703         xfs_lock_two_inodes(ip, tip, XFS_ILOCK_EXCL);
1704         lock_flags |= XFS_ILOCK_EXCL;
1705
1706         /* Verify all data are being swapped */
1707         if (sxp->sx_offset != 0 ||
1708             sxp->sx_length != ip->i_d.di_size ||
1709             sxp->sx_length != tip->i_d.di_size) {
1710                 error = -EFAULT;
1711                 goto out_trans_cancel;
1712         }
1713
1714         trace_xfs_swap_extent_before(ip, 0);
1715         trace_xfs_swap_extent_before(tip, 1);
1716
1717         /* check inode formats now that data is flushed */
1718         error = xfs_swap_extents_check_format(ip, tip);
1719         if (error) {
1720                 xfs_notice(mp,
1721                     "%s: inode 0x%llx format is incompatible for exchanging.",
1722                                 __func__, ip->i_ino);
1723                 goto out_trans_cancel;
1724         }
1725
1726         /*
1727          * Compare the current change & modify times with that
1728          * passed in.  If they differ, we abort this swap.
1729          * This is the mechanism used to ensure the calling
1730          * process that the file was not changed out from
1731          * under it.
1732          */
1733         if ((sbp->bs_ctime.tv_sec != VFS_I(ip)->i_ctime.tv_sec) ||
1734             (sbp->bs_ctime.tv_nsec != VFS_I(ip)->i_ctime.tv_nsec) ||
1735             (sbp->bs_mtime.tv_sec != VFS_I(ip)->i_mtime.tv_sec) ||
1736             (sbp->bs_mtime.tv_nsec != VFS_I(ip)->i_mtime.tv_nsec)) {
1737                 error = -EBUSY;
1738                 goto out_trans_cancel;
1739         }
1740         /*
1741          * Count the number of extended attribute blocks
1742          */
1743         if ( ((XFS_IFORK_Q(ip) != 0) && (ip->i_d.di_anextents > 0)) &&
1744              (ip->i_d.di_aformat != XFS_DINODE_FMT_LOCAL)) {
1745                 error = xfs_bmap_count_blocks(tp, ip, XFS_ATTR_FORK, &aforkblks);
1746                 if (error)
1747                         goto out_trans_cancel;
1748         }
1749         if ( ((XFS_IFORK_Q(tip) != 0) && (tip->i_d.di_anextents > 0)) &&
1750              (tip->i_d.di_aformat != XFS_DINODE_FMT_LOCAL)) {
1751                 error = xfs_bmap_count_blocks(tp, tip, XFS_ATTR_FORK,
1752                         &taforkblks);
1753                 if (error)
1754                         goto out_trans_cancel;
1755         }
1756
1757         xfs_trans_ijoin(tp, ip, lock_flags);
1758         xfs_trans_ijoin(tp, tip, lock_flags);
1759
1760         /*
1761          * Before we've swapped the forks, lets set the owners of the forks
1762          * appropriately. We have to do this as we are demand paging the btree
1763          * buffers, and so the validation done on read will expect the owner
1764          * field to be correctly set. Once we change the owners, we can swap the
1765          * inode forks.
1766          *
1767          * Note the trickiness in setting the log flags - we set the owner log
1768          * flag on the opposite inode (i.e. the inode we are setting the new
1769          * owner to be) because once we swap the forks and log that, log
1770          * recovery is going to see the fork as owned by the swapped inode,
1771          * not the pre-swapped inodes.
1772          */
1773         src_log_flags = XFS_ILOG_CORE;
1774         target_log_flags = XFS_ILOG_CORE;
1775         if (ip->i_d.di_version == 3 &&
1776             ip->i_d.di_format == XFS_DINODE_FMT_BTREE) {
1777                 target_log_flags |= XFS_ILOG_DOWNER;
1778                 error = xfs_bmbt_change_owner(tp, ip, XFS_DATA_FORK,
1779                                               tip->i_ino, NULL);
1780                 if (error)
1781                         goto out_trans_cancel;
1782         }
1783
1784         if (tip->i_d.di_version == 3 &&
1785             tip->i_d.di_format == XFS_DINODE_FMT_BTREE) {
1786                 src_log_flags |= XFS_ILOG_DOWNER;
1787                 error = xfs_bmbt_change_owner(tp, tip, XFS_DATA_FORK,
1788                                               ip->i_ino, NULL);
1789                 if (error)
1790                         goto out_trans_cancel;
1791         }
1792
1793         /*
1794          * Swap the data forks of the inodes
1795          */
1796         ifp = &ip->i_df;
1797         tifp = &tip->i_df;
1798         *tempifp = *ifp;        /* struct copy */
1799         *ifp = *tifp;           /* struct copy */
1800         *tifp = *tempifp;       /* struct copy */
1801
1802         /*
1803          * Fix the on-disk inode values
1804          */
1805         tmp = (__uint64_t)ip->i_d.di_nblocks;
1806         ip->i_d.di_nblocks = tip->i_d.di_nblocks - taforkblks + aforkblks;
1807         tip->i_d.di_nblocks = tmp + taforkblks - aforkblks;
1808
1809         tmp = (__uint64_t) ip->i_d.di_nextents;
1810         ip->i_d.di_nextents = tip->i_d.di_nextents;
1811         tip->i_d.di_nextents = tmp;
1812
1813         tmp = (__uint64_t) ip->i_d.di_format;
1814         ip->i_d.di_format = tip->i_d.di_format;
1815         tip->i_d.di_format = tmp;
1816
1817         /*
1818          * The extents in the source inode could still contain speculative
1819          * preallocation beyond EOF (e.g. the file is open but not modified
1820          * while defrag is in progress). In that case, we need to copy over the
1821          * number of delalloc blocks the data fork in the source inode is
1822          * tracking beyond EOF so that when the fork is truncated away when the
1823          * temporary inode is unlinked we don't underrun the i_delayed_blks
1824          * counter on that inode.
1825          */
1826         ASSERT(tip->i_delayed_blks == 0);
1827         tip->i_delayed_blks = ip->i_delayed_blks;
1828         ip->i_delayed_blks = 0;
1829
1830         switch (ip->i_d.di_format) {
1831         case XFS_DINODE_FMT_EXTENTS:
1832                 /* If the extents fit in the inode, fix the
1833                  * pointer.  Otherwise it's already NULL or
1834                  * pointing to the extent.
1835                  */
1836                 if (ip->i_d.di_nextents <= XFS_INLINE_EXTS) {
1837                         ifp->if_u1.if_extents =
1838                                 ifp->if_u2.if_inline_ext;
1839                 }
1840                 src_log_flags |= XFS_ILOG_DEXT;
1841                 break;
1842         case XFS_DINODE_FMT_BTREE:
1843                 ASSERT(ip->i_d.di_version < 3 ||
1844                        (src_log_flags & XFS_ILOG_DOWNER));
1845                 src_log_flags |= XFS_ILOG_DBROOT;
1846                 break;
1847         }
1848
1849         switch (tip->i_d.di_format) {
1850         case XFS_DINODE_FMT_EXTENTS:
1851                 /* If the extents fit in the inode, fix the
1852                  * pointer.  Otherwise it's already NULL or
1853                  * pointing to the extent.
1854                  */
1855                 if (tip->i_d.di_nextents <= XFS_INLINE_EXTS) {
1856                         tifp->if_u1.if_extents =
1857                                 tifp->if_u2.if_inline_ext;
1858                 }
1859                 target_log_flags |= XFS_ILOG_DEXT;
1860                 break;
1861         case XFS_DINODE_FMT_BTREE:
1862                 target_log_flags |= XFS_ILOG_DBROOT;
1863                 ASSERT(tip->i_d.di_version < 3 ||
1864                        (target_log_flags & XFS_ILOG_DOWNER));
1865                 break;
1866         }
1867
1868         xfs_trans_log_inode(tp, ip,  src_log_flags);
1869         xfs_trans_log_inode(tp, tip, target_log_flags);
1870
1871         /*
1872          * If this is a synchronous mount, make sure that the
1873          * transaction goes to disk before returning to the user.
1874          */
1875         if (mp->m_flags & XFS_MOUNT_WSYNC)
1876                 xfs_trans_set_sync(tp);
1877
1878         error = xfs_trans_commit(tp, 0);
1879
1880         trace_xfs_swap_extent_after(ip, 0);
1881         trace_xfs_swap_extent_after(tip, 1);
1882 out:
1883         kmem_free(tempifp);
1884         return error;
1885
1886 out_unlock:
1887         xfs_iunlock(ip, lock_flags);
1888         xfs_iunlock(tip, lock_flags);
1889         goto out;
1890
1891 out_trans_cancel:
1892         xfs_trans_cancel(tp, 0);
1893         goto out_unlock;
1894 }