1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * Copyright (c) 2000-2006 Silicon Graphics, Inc.
4 * Copyright (c) 2012 Red Hat, Inc.
5 * All Rights Reserved.
6 */
7 #include "xfs_platform.h"
8 #include "xfs_fs.h"
9 #include "xfs_shared.h"
10 #include "xfs_format.h"
11 #include "xfs_log_format.h"
12 #include "xfs_trans_resv.h"
13 #include "xfs_bit.h"
14 #include "xfs_mount.h"
15 #include "xfs_defer.h"
16 #include "xfs_inode.h"
17 #include "xfs_btree.h"
18 #include "xfs_trans.h"
19 #include "xfs_alloc.h"
20 #include "xfs_bmap.h"
21 #include "xfs_bmap_util.h"
22 #include "xfs_bmap_btree.h"
23 #include "xfs_rtalloc.h"
24 #include "xfs_error.h"
25 #include "xfs_quota.h"
26 #include "xfs_trans_space.h"
27 #include "xfs_trace.h"
28 #include "xfs_icache.h"
29 #include "xfs_iomap.h"
30 #include "xfs_reflink.h"
31 #include "xfs_rtbitmap.h"
32 #include "xfs_rtgroup.h"
33 #include "xfs_zone_alloc.h"
34
35 /* Kernel only BMAP related definitions and functions */
36
37 /*
38 * Convert the given file system block to a disk block. We have to treat it
39 * differently based on whether the file is a real time file or not, because the
40 * bmap code does.
41 */
42 xfs_daddr_t
xfs_fsb_to_db(struct xfs_inode * ip,xfs_fsblock_t fsb)43 xfs_fsb_to_db(struct xfs_inode *ip, xfs_fsblock_t fsb)
44 {
45 if (XFS_IS_REALTIME_INODE(ip))
46 return xfs_rtb_to_daddr(ip->i_mount, fsb);
47 return XFS_FSB_TO_DADDR(ip->i_mount, fsb);
48 }
49
50 /*
51 * Routine to zero an extent on disk allocated to the specific inode.
52 */
53 int
xfs_zero_extent(struct xfs_inode * ip,xfs_fsblock_t start_fsb,xfs_off_t count_fsb)54 xfs_zero_extent(
55 struct xfs_inode *ip,
56 xfs_fsblock_t start_fsb,
57 xfs_off_t count_fsb)
58 {
59 return blkdev_issue_zeroout(xfs_inode_buftarg(ip)->bt_bdev,
60 xfs_fsb_to_db(ip, start_fsb),
61 XFS_FSB_TO_BB(ip->i_mount, count_fsb),
62 GFP_KERNEL, 0);
63 }
64
65 /*
66 * Extent tree block counting routines.
67 */
68
69 /*
70 * Count leaf blocks given a range of extent records. Delayed allocation
71 * extents are not counted towards the totals.
72 */
73 xfs_extnum_t
xfs_bmap_count_leaves(struct xfs_ifork * ifp,xfs_filblks_t * count)74 xfs_bmap_count_leaves(
75 struct xfs_ifork *ifp,
76 xfs_filblks_t *count)
77 {
78 struct xfs_iext_cursor icur;
79 struct xfs_bmbt_irec got;
80 xfs_extnum_t numrecs = 0;
81
82 for_each_xfs_iext(ifp, &icur, &got) {
83 if (!isnullstartblock(got.br_startblock)) {
84 *count += got.br_blockcount;
85 numrecs++;
86 }
87 }
88
89 return numrecs;
90 }
91
92 /*
93 * Count fsblocks of the given fork. Delayed allocation extents are
94 * not counted towards the totals.
95 */
96 int
xfs_bmap_count_blocks(struct xfs_trans * tp,struct xfs_inode * ip,int whichfork,xfs_extnum_t * nextents,xfs_filblks_t * count)97 xfs_bmap_count_blocks(
98 struct xfs_trans *tp,
99 struct xfs_inode *ip,
100 int whichfork,
101 xfs_extnum_t *nextents,
102 xfs_filblks_t *count)
103 {
104 struct xfs_mount *mp = ip->i_mount;
105 struct xfs_ifork *ifp = xfs_ifork_ptr(ip, whichfork);
106 struct xfs_btree_cur *cur;
107 xfs_filblks_t btblocks = 0;
108 int error;
109
110 *nextents = 0;
111 *count = 0;
112
113 if (!ifp)
114 return 0;
115
116 switch (ifp->if_format) {
117 case XFS_DINODE_FMT_BTREE:
118 error = xfs_iread_extents(tp, ip, whichfork);
119 if (error)
120 return error;
121
122 cur = xfs_bmbt_init_cursor(mp, tp, ip, whichfork);
123 error = xfs_btree_count_blocks(cur, &btblocks);
124 xfs_btree_del_cursor(cur, error);
125 if (error)
126 return error;
127
128 /*
129 * xfs_btree_count_blocks includes the root block contained in
130 * the inode fork in @btblocks, so subtract one because we're
131 * only interested in allocated disk blocks.
132 */
133 *count += btblocks - 1;
134
135 fallthrough;
136 case XFS_DINODE_FMT_EXTENTS:
137 *nextents = xfs_bmap_count_leaves(ifp, count);
138 break;
139 }
140
141 return 0;
142 }
143
144 static int
xfs_getbmap_report_one(struct xfs_inode * ip,struct getbmapx * bmv,struct kgetbmap * out,int64_t bmv_end,struct xfs_bmbt_irec * got)145 xfs_getbmap_report_one(
146 struct xfs_inode *ip,
147 struct getbmapx *bmv,
148 struct kgetbmap *out,
149 int64_t bmv_end,
150 struct xfs_bmbt_irec *got)
151 {
152 struct kgetbmap *p = out + bmv->bmv_entries;
153 bool shared = false;
154 int error;
155
156 error = xfs_reflink_trim_around_shared(ip, got, &shared);
157 if (error)
158 return error;
159
160 if (isnullstartblock(got->br_startblock) ||
161 got->br_startblock == DELAYSTARTBLOCK) {
162 /*
163 * Take the flush completion as being a point-in-time snapshot
164 * where there are no delalloc extents, and if any new ones
165 * have been created racily, just skip them as being 'after'
166 * the flush and so don't get reported.
167 */
168 if (!(bmv->bmv_iflags & BMV_IF_DELALLOC))
169 return 0;
170
171 p->bmv_oflags |= BMV_OF_DELALLOC;
172 p->bmv_block = -2;
173 } else {
174 p->bmv_block = xfs_fsb_to_db(ip, got->br_startblock);
175 }
176
177 if (got->br_state == XFS_EXT_UNWRITTEN &&
178 (bmv->bmv_iflags & BMV_IF_PREALLOC))
179 p->bmv_oflags |= BMV_OF_PREALLOC;
180
181 if (shared)
182 p->bmv_oflags |= BMV_OF_SHARED;
183
184 p->bmv_offset = XFS_FSB_TO_BB(ip->i_mount, got->br_startoff);
185 p->bmv_length = XFS_FSB_TO_BB(ip->i_mount, got->br_blockcount);
186
187 bmv->bmv_offset = p->bmv_offset + p->bmv_length;
188 bmv->bmv_length = max(0LL, bmv_end - bmv->bmv_offset);
189 bmv->bmv_entries++;
190 return 0;
191 }
192
193 static void
xfs_getbmap_report_hole(struct xfs_inode * ip,struct getbmapx * bmv,struct kgetbmap * out,int64_t bmv_end,xfs_fileoff_t bno,xfs_fileoff_t end)194 xfs_getbmap_report_hole(
195 struct xfs_inode *ip,
196 struct getbmapx *bmv,
197 struct kgetbmap *out,
198 int64_t bmv_end,
199 xfs_fileoff_t bno,
200 xfs_fileoff_t end)
201 {
202 struct kgetbmap *p = out + bmv->bmv_entries;
203
204 if (bmv->bmv_iflags & BMV_IF_NO_HOLES)
205 return;
206
207 p->bmv_block = -1;
208 p->bmv_offset = XFS_FSB_TO_BB(ip->i_mount, bno);
209 p->bmv_length = XFS_FSB_TO_BB(ip->i_mount, end - bno);
210
211 bmv->bmv_offset = p->bmv_offset + p->bmv_length;
212 bmv->bmv_length = max(0LL, bmv_end - bmv->bmv_offset);
213 bmv->bmv_entries++;
214 }
215
216 static inline bool
xfs_getbmap_full(struct getbmapx * bmv)217 xfs_getbmap_full(
218 struct getbmapx *bmv)
219 {
220 return bmv->bmv_length == 0 || bmv->bmv_entries >= bmv->bmv_count - 1;
221 }
222
223 static bool
xfs_getbmap_next_rec(struct xfs_bmbt_irec * rec,xfs_fileoff_t total_end)224 xfs_getbmap_next_rec(
225 struct xfs_bmbt_irec *rec,
226 xfs_fileoff_t total_end)
227 {
228 xfs_fileoff_t end = rec->br_startoff + rec->br_blockcount;
229
230 if (end == total_end)
231 return false;
232
233 rec->br_startoff += rec->br_blockcount;
234 if (!isnullstartblock(rec->br_startblock) &&
235 rec->br_startblock != DELAYSTARTBLOCK)
236 rec->br_startblock += rec->br_blockcount;
237 rec->br_blockcount = total_end - end;
238 return true;
239 }
240
241 /*
242 * Get inode's extents as described in bmv, and format for output.
243 * Calls formatter to fill the user's buffer until all extents
244 * are mapped, until the passed-in bmv->bmv_count slots have
245 * been filled, or until the formatter short-circuits the loop,
246 * if it is tracking filled-in extents on its own.
247 */
248 int /* error code */
xfs_getbmap(struct xfs_inode * ip,struct getbmapx * bmv,struct kgetbmap * out)249 xfs_getbmap(
250 struct xfs_inode *ip,
251 struct getbmapx *bmv, /* user bmap structure */
252 struct kgetbmap *out)
253 {
254 struct xfs_mount *mp = ip->i_mount;
255 int iflags = bmv->bmv_iflags;
256 int whichfork, lock, error = 0;
257 int64_t bmv_end, max_len;
258 xfs_fileoff_t bno, first_bno;
259 struct xfs_ifork *ifp;
260 struct xfs_bmbt_irec got, rec;
261 xfs_filblks_t len;
262 struct xfs_iext_cursor icur;
263
264 if (bmv->bmv_iflags & ~BMV_IF_VALID)
265 return -EINVAL;
266 #ifndef DEBUG
267 /* Only allow CoW fork queries if we're debugging. */
268 if (iflags & BMV_IF_COWFORK)
269 return -EINVAL;
270 #endif
271 if ((iflags & BMV_IF_ATTRFORK) && (iflags & BMV_IF_COWFORK))
272 return -EINVAL;
273
274 if (bmv->bmv_length < -1)
275 return -EINVAL;
276 bmv->bmv_entries = 0;
277 if (bmv->bmv_length == 0)
278 return 0;
279
280 if (iflags & BMV_IF_ATTRFORK)
281 whichfork = XFS_ATTR_FORK;
282 else if (iflags & BMV_IF_COWFORK)
283 whichfork = XFS_COW_FORK;
284 else
285 whichfork = XFS_DATA_FORK;
286
287 xfs_ilock(ip, XFS_IOLOCK_SHARED);
288 switch (whichfork) {
289 case XFS_ATTR_FORK:
290 lock = xfs_ilock_attr_map_shared(ip);
291 if (!xfs_inode_has_attr_fork(ip))
292 goto out_unlock_ilock;
293
294 max_len = 1LL << 32;
295 break;
296 case XFS_COW_FORK:
297 lock = XFS_ILOCK_SHARED;
298 xfs_ilock(ip, lock);
299
300 /* No CoW fork? Just return */
301 if (!xfs_ifork_ptr(ip, whichfork))
302 goto out_unlock_ilock;
303
304 if (xfs_get_cowextsz_hint(ip))
305 max_len = mp->m_super->s_maxbytes;
306 else
307 max_len = XFS_ISIZE(ip);
308 break;
309 case XFS_DATA_FORK:
310 if (!(iflags & BMV_IF_DELALLOC) &&
311 (ip->i_delayed_blks || XFS_ISIZE(ip) > ip->i_disk_size)) {
312 error = filemap_write_and_wait(VFS_I(ip)->i_mapping);
313 if (error)
314 goto out_unlock_iolock;
315
316 /*
317 * Even after flushing the inode, there can still be
318 * delalloc blocks on the inode beyond EOF due to
319 * speculative preallocation. These are not removed
320 * until the release function is called or the inode
321 * is inactivated. Hence we cannot assert here that
322 * ip->i_delayed_blks == 0.
323 */
324 }
325
326 if (xfs_get_extsz_hint(ip) ||
327 (ip->i_diflags & XFS_DIFLAG_PREALLOC))
328 max_len = mp->m_super->s_maxbytes;
329 else
330 max_len = XFS_ISIZE(ip);
331
332 lock = xfs_ilock_data_map_shared(ip);
333 break;
334 }
335
336 ifp = xfs_ifork_ptr(ip, whichfork);
337
338 switch (ifp->if_format) {
339 case XFS_DINODE_FMT_EXTENTS:
340 case XFS_DINODE_FMT_BTREE:
341 break;
342 case XFS_DINODE_FMT_LOCAL:
343 /* Local format inode forks report no extents. */
344 goto out_unlock_ilock;
345 default:
346 error = -EINVAL;
347 goto out_unlock_ilock;
348 }
349
350 if (bmv->bmv_length == -1) {
351 max_len = XFS_FSB_TO_BB(mp, XFS_B_TO_FSB(mp, max_len));
352 bmv->bmv_length = max(0LL, max_len - bmv->bmv_offset);
353 }
354
355 bmv_end = bmv->bmv_offset + bmv->bmv_length;
356
357 first_bno = bno = XFS_BB_TO_FSBT(mp, bmv->bmv_offset);
358 len = XFS_BB_TO_FSB(mp, bmv->bmv_length);
359
360 error = xfs_iread_extents(NULL, ip, whichfork);
361 if (error)
362 goto out_unlock_ilock;
363
364 if (!xfs_iext_lookup_extent(ip, ifp, bno, &icur, &got)) {
365 /*
366 * Report a whole-file hole if the delalloc flag is set to
367 * stay compatible with the old implementation.
368 */
369 if (iflags & BMV_IF_DELALLOC)
370 xfs_getbmap_report_hole(ip, bmv, out, bmv_end, bno,
371 XFS_B_TO_FSB(mp, XFS_ISIZE(ip)));
372 goto out_unlock_ilock;
373 }
374
375 while (!xfs_getbmap_full(bmv)) {
376 xfs_trim_extent(&got, first_bno, len);
377
378 /*
379 * Report an entry for a hole if this extent doesn't directly
380 * follow the previous one.
381 */
382 if (got.br_startoff > bno) {
383 xfs_getbmap_report_hole(ip, bmv, out, bmv_end, bno,
384 got.br_startoff);
385 if (xfs_getbmap_full(bmv))
386 break;
387 }
388
389 /*
390 * In order to report shared extents accurately, we report each
391 * distinct shared / unshared part of a single bmbt record with
392 * an individual getbmapx record.
393 */
394 bno = got.br_startoff + got.br_blockcount;
395 rec = got;
396 do {
397 error = xfs_getbmap_report_one(ip, bmv, out, bmv_end,
398 &rec);
399 if (error || xfs_getbmap_full(bmv))
400 goto out_unlock_ilock;
401 } while (xfs_getbmap_next_rec(&rec, bno));
402
403 if (!xfs_iext_next_extent(ifp, &icur, &got)) {
404 xfs_fileoff_t end = XFS_B_TO_FSB(mp, XFS_ISIZE(ip));
405
406 if (bmv->bmv_entries > 0)
407 out[bmv->bmv_entries - 1].bmv_oflags |=
408 BMV_OF_LAST;
409
410 if (whichfork != XFS_ATTR_FORK && bno < end &&
411 !xfs_getbmap_full(bmv)) {
412 xfs_getbmap_report_hole(ip, bmv, out, bmv_end,
413 bno, end);
414 }
415 break;
416 }
417
418 if (bno >= first_bno + len)
419 break;
420 }
421
422 out_unlock_ilock:
423 xfs_iunlock(ip, lock);
424 out_unlock_iolock:
425 xfs_iunlock(ip, XFS_IOLOCK_SHARED);
426 return error;
427 }
428
429 /*
430 * Dead simple method of punching delalyed allocation blocks from a range in
431 * the inode. This will always punch out both the start and end blocks, even
432 * if the ranges only partially overlap them, so it is up to the caller to
433 * ensure that partial blocks are not passed in.
434 */
435 void
xfs_bmap_punch_delalloc_range(struct xfs_inode * ip,int whichfork,xfs_off_t start_byte,xfs_off_t end_byte,struct xfs_zone_alloc_ctx * ac)436 xfs_bmap_punch_delalloc_range(
437 struct xfs_inode *ip,
438 int whichfork,
439 xfs_off_t start_byte,
440 xfs_off_t end_byte,
441 struct xfs_zone_alloc_ctx *ac)
442 {
443 struct xfs_mount *mp = ip->i_mount;
444 struct xfs_ifork *ifp = xfs_ifork_ptr(ip, whichfork);
445 xfs_fileoff_t start_fsb = XFS_B_TO_FSBT(mp, start_byte);
446 xfs_fileoff_t end_fsb = XFS_B_TO_FSB(mp, end_byte);
447 struct xfs_bmbt_irec got, del;
448 struct xfs_iext_cursor icur;
449
450 ASSERT(!xfs_need_iread_extents(ifp));
451
452 xfs_ilock(ip, XFS_ILOCK_EXCL);
453 if (!xfs_iext_lookup_extent_before(ip, ifp, &end_fsb, &icur, &got))
454 goto out_unlock;
455
456 while (got.br_startoff + got.br_blockcount > start_fsb) {
457 del = got;
458 xfs_trim_extent(&del, start_fsb, end_fsb - start_fsb);
459
460 /*
461 * A delete can push the cursor forward. Step back to the
462 * previous extent on non-delalloc or extents outside the
463 * target range.
464 */
465 if (!del.br_blockcount ||
466 !isnullstartblock(del.br_startblock)) {
467 if (!xfs_iext_prev_extent(ifp, &icur, &got))
468 break;
469 continue;
470 }
471
472 if (xfs_is_zoned_inode(ip) && ac) {
473 /*
474 * In a zoned buffered write context we need to return
475 * the punched delalloc allocations to the allocation
476 * context. This allows reusing them in the following
477 * iomap iterations.
478 */
479 xfs_bmap_del_extent_delay(ip, whichfork, &icur, &got,
480 &del, XFS_BMAPI_REMAP);
481 ac->reserved_blocks += del.br_blockcount;
482 } else {
483 xfs_bmap_del_extent_delay(ip, whichfork, &icur, &got,
484 &del, 0);
485 }
486
487 if (!xfs_iext_get_extent(ifp, &icur, &got))
488 break;
489 }
490
491 if (whichfork == XFS_COW_FORK && !ifp->if_bytes)
492 xfs_inode_clear_cowblocks_tag(ip);
493
494 out_unlock:
495 xfs_iunlock(ip, XFS_ILOCK_EXCL);
496 }
497
498 /*
499 * Test whether it is appropriate to check an inode for and free post EOF
500 * blocks.
501 */
502 bool
xfs_can_free_eofblocks(struct xfs_inode * ip)503 xfs_can_free_eofblocks(
504 struct xfs_inode *ip)
505 {
506 struct xfs_mount *mp = ip->i_mount;
507 bool found_blocks = false;
508 xfs_fileoff_t end_fsb;
509 xfs_fileoff_t last_fsb;
510 struct xfs_bmbt_irec imap;
511 struct xfs_iext_cursor icur;
512
513 /*
514 * Caller must either hold the exclusive io lock; or be inactivating
515 * the inode, which guarantees there are no other users of the inode.
516 */
517 if (!(inode_state_read_once(VFS_I(ip)) & I_FREEING))
518 xfs_assert_ilocked(ip, XFS_IOLOCK_EXCL);
519
520 /* prealloc/delalloc exists only on regular files */
521 if (!S_ISREG(VFS_I(ip)->i_mode))
522 return false;
523
524 /*
525 * Zero sized files with no cached pages and delalloc blocks will not
526 * have speculative prealloc/delalloc blocks to remove.
527 */
528 if (VFS_I(ip)->i_size == 0 &&
529 VFS_I(ip)->i_mapping->nrpages == 0 &&
530 ip->i_delayed_blks == 0)
531 return false;
532
533 /* If we haven't read in the extent list, then don't do it now. */
534 if (xfs_need_iread_extents(&ip->i_df))
535 return false;
536
537 /*
538 * Do not free real extents in preallocated files unless the file has
539 * delalloc blocks and we are forced to remove them.
540 */
541 if ((ip->i_diflags & XFS_DIFLAG_PREALLOC) && !ip->i_delayed_blks)
542 return false;
543
544 /*
545 * Do not try to free post-EOF blocks if EOF is beyond the end of the
546 * range supported by the page cache, because the truncation will loop
547 * forever.
548 */
549 end_fsb = XFS_B_TO_FSB(mp, (xfs_ufsize_t)XFS_ISIZE(ip));
550 if (xfs_inode_has_bigrtalloc(ip))
551 end_fsb = xfs_fileoff_roundup_rtx(mp, end_fsb);
552 last_fsb = XFS_B_TO_FSB(mp, mp->m_super->s_maxbytes);
553 if (last_fsb <= end_fsb)
554 return false;
555
556 /*
557 * Check if there is an post-EOF extent to free. If there are any
558 * delalloc blocks attached to the inode (data fork delalloc
559 * reservations or CoW extents of any kind), we need to free them so
560 * that inactivation doesn't fail to erase them.
561 */
562 xfs_ilock(ip, XFS_ILOCK_SHARED);
563 if (ip->i_delayed_blks ||
564 xfs_iext_lookup_extent(ip, &ip->i_df, end_fsb, &icur, &imap))
565 found_blocks = true;
566 xfs_iunlock(ip, XFS_ILOCK_SHARED);
567 return found_blocks;
568 }
569
570 /*
571 * This is called to free any blocks beyond eof. The caller must hold
572 * IOLOCK_EXCL unless we are in the inode reclaim path and have the only
573 * reference to the inode.
574 */
575 int
xfs_free_eofblocks(struct xfs_inode * ip)576 xfs_free_eofblocks(
577 struct xfs_inode *ip)
578 {
579 struct xfs_trans *tp;
580 struct xfs_mount *mp = ip->i_mount;
581 int error;
582
583 /* Attach the dquots to the inode up front. */
584 error = xfs_qm_dqattach(ip);
585 if (error)
586 return error;
587
588 /* Wait on dio to ensure i_size has settled. */
589 inode_dio_wait(VFS_I(ip));
590
591 /*
592 * For preallocated files only free delayed allocations.
593 *
594 * Note that this means we also leave speculative preallocations in
595 * place for preallocated files.
596 */
597 if (ip->i_diflags & (XFS_DIFLAG_PREALLOC | XFS_DIFLAG_APPEND)) {
598 if (ip->i_delayed_blks) {
599 xfs_bmap_punch_delalloc_range(ip, XFS_DATA_FORK,
600 round_up(XFS_ISIZE(ip), mp->m_sb.sb_blocksize),
601 LLONG_MAX, NULL);
602 }
603 xfs_inode_clear_eofblocks_tag(ip);
604 return 0;
605 }
606
607 error = xfs_trans_alloc(mp, &M_RES(mp)->tr_itruncate, 0, 0, 0, &tp);
608 if (error) {
609 ASSERT(xfs_is_shutdown(mp));
610 return error;
611 }
612
613 xfs_ilock(ip, XFS_ILOCK_EXCL);
614 xfs_trans_ijoin(tp, ip, 0);
615
616 /*
617 * Do not update the on-disk file size. If we update the on-disk file
618 * size and then the system crashes before the contents of the file are
619 * flushed to disk then the files may be full of holes (ie NULL files
620 * bug).
621 */
622 error = xfs_itruncate_extents_flags(&tp, ip, XFS_DATA_FORK,
623 XFS_ISIZE(ip), XFS_BMAPI_NODISCARD);
624 if (error)
625 goto err_cancel;
626
627 error = xfs_trans_commit(tp);
628 if (error)
629 goto out_unlock;
630
631 xfs_inode_clear_eofblocks_tag(ip);
632 goto out_unlock;
633
634 err_cancel:
635 /*
636 * If we get an error at this point we simply don't
637 * bother truncating the file.
638 */
639 xfs_trans_cancel(tp);
640 out_unlock:
641 xfs_iunlock(ip, XFS_ILOCK_EXCL);
642 return error;
643 }
644
645 /*
646 * Allocate space or convert extents for a file according to @mode:
647 *
648 * XFS_ALLOC_FILE_SPACE_PREALLOC:
649 * Preallocate unwritten extents over holes across the range and mark the inode
650 * as preallocated.
651 *
652 * XFS_ALLOC_FILE_SPACE_WRITE_ZEROES:
653 * Allocate written extents over holes and convert unwritten extents in the
654 * range to written extents, initialising both to contain zeroes.
655 *
656 * This function does not update the file size; callers that extend the file
657 * are responsible for updating it once the extents are allocated.
658 */
659 int
xfs_alloc_file_space(struct xfs_inode * ip,xfs_off_t offset,xfs_off_t len,enum xfs_alloc_file_space_mode mode)660 xfs_alloc_file_space(
661 struct xfs_inode *ip,
662 xfs_off_t offset,
663 xfs_off_t len,
664 enum xfs_alloc_file_space_mode mode)
665 {
666 xfs_mount_t *mp = ip->i_mount;
667 xfs_off_t count;
668 xfs_filblks_t allocatesize_fsb;
669 xfs_extlen_t extsz, temp;
670 xfs_fileoff_t startoffset_fsb;
671 xfs_fileoff_t endoffset_fsb;
672 int rt;
673 xfs_trans_t *tp;
674 xfs_bmbt_irec_t imaps[1], *imapp;
675 uint32_t bmapi_flags, nr_exts;
676 int error;
677
678 if (xfs_is_always_cow_inode(ip))
679 return 0;
680
681 trace_xfs_alloc_file_space(ip);
682
683 if (xfs_is_shutdown(mp))
684 return -EIO;
685
686 error = xfs_qm_dqattach(ip);
687 if (error)
688 return error;
689
690 if (len <= 0)
691 return -EINVAL;
692
693 switch (mode) {
694 case XFS_ALLOC_FILE_SPACE_PREALLOC:
695 bmapi_flags = XFS_BMAPI_PREALLOC;
696 nr_exts = XFS_IEXT_ADD_NOSPLIT_CNT;
697 break;
698 case XFS_ALLOC_FILE_SPACE_WRITE_ZEROES:
699 bmapi_flags = XFS_BMAPI_CONVERT | XFS_BMAPI_ZERO;
700 nr_exts = XFS_IEXT_WRITE_UNWRITTEN_CNT;
701 break;
702 default:
703 return -EINVAL;
704 }
705
706 rt = XFS_IS_REALTIME_INODE(ip);
707 extsz = xfs_get_extsz_hint(ip);
708
709 count = len;
710 imapp = &imaps[0];
711 startoffset_fsb = XFS_B_TO_FSBT(mp, offset);
712 endoffset_fsb = XFS_B_TO_FSB(mp, offset + count);
713 allocatesize_fsb = endoffset_fsb - startoffset_fsb;
714
715 /*
716 * Allocate file space until done or until there is an error
717 */
718 while (allocatesize_fsb && !error) {
719 xfs_fileoff_t s, e;
720 unsigned int dblocks, rblocks, resblks;
721 int nimaps = 1;
722
723 /*
724 * Determine space reservations for data/realtime.
725 */
726 if (unlikely(extsz)) {
727 s = startoffset_fsb;
728 do_div(s, extsz);
729 s *= extsz;
730 e = startoffset_fsb + allocatesize_fsb;
731 div_u64_rem(startoffset_fsb, extsz, &temp);
732 if (temp)
733 e += temp;
734 div_u64_rem(e, extsz, &temp);
735 if (temp)
736 e += extsz - temp;
737 } else {
738 s = 0;
739 e = allocatesize_fsb;
740 }
741
742 /*
743 * The transaction reservation is limited to a 32-bit block
744 * count, hence we need to limit the number of blocks we are
745 * trying to reserve to avoid an overflow. We can't allocate
746 * more than @nimaps extents, and an extent is limited on disk
747 * to XFS_BMBT_MAX_EXTLEN (21 bits), so use that to enforce the
748 * limit.
749 */
750 resblks = min_t(xfs_fileoff_t, (e - s),
751 (XFS_MAX_BMBT_EXTLEN * nimaps));
752 if (unlikely(rt)) {
753 dblocks = XFS_DIOSTRAT_SPACE_RES(mp, 0);
754 rblocks = resblks;
755 } else {
756 dblocks = XFS_DIOSTRAT_SPACE_RES(mp, resblks);
757 rblocks = 0;
758 }
759
760 error = xfs_trans_alloc_inode(ip, &M_RES(mp)->tr_write,
761 dblocks, rblocks, false, &tp);
762 if (error)
763 break;
764
765 error = xfs_iext_count_extend(tp, ip, XFS_DATA_FORK, nr_exts);
766 if (error)
767 goto error;
768
769 /*
770 * If the allocator cannot find a single free extent large
771 * enough to cover the start block of the requested range,
772 * xfs_bmapi_write will return -ENOSR.
773 *
774 * In that case we simply need to keep looping with the same
775 * startoffset_fsb so that one of the following allocations
776 * will eventually reach the requested range.
777 */
778 error = xfs_bmapi_write(tp, ip, startoffset_fsb,
779 allocatesize_fsb, bmapi_flags, 0, imapp,
780 &nimaps);
781 if (error) {
782 if (error != -ENOSR)
783 goto error;
784 error = 0;
785 } else {
786 startoffset_fsb += imapp->br_blockcount;
787 allocatesize_fsb -= imapp->br_blockcount;
788 }
789
790 if (mode == XFS_ALLOC_FILE_SPACE_PREALLOC) {
791 ip->i_diflags |= XFS_DIFLAG_PREALLOC;
792 xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
793 }
794
795 error = xfs_trans_commit(tp);
796 xfs_iunlock(ip, XFS_ILOCK_EXCL);
797 }
798
799 return error;
800
801 error:
802 xfs_trans_cancel(tp);
803 xfs_iunlock(ip, XFS_ILOCK_EXCL);
804 return error;
805 }
806
807 static int
xfs_unmap_extent(struct xfs_inode * ip,xfs_fileoff_t startoffset_fsb,xfs_filblks_t len_fsb,int * done)808 xfs_unmap_extent(
809 struct xfs_inode *ip,
810 xfs_fileoff_t startoffset_fsb,
811 xfs_filblks_t len_fsb,
812 int *done)
813 {
814 struct xfs_mount *mp = ip->i_mount;
815 struct xfs_trans *tp;
816 uint resblks = XFS_DIOSTRAT_SPACE_RES(mp, 0);
817 int error;
818
819 error = xfs_trans_alloc_inode(ip, &M_RES(mp)->tr_write, resblks, 0,
820 false, &tp);
821 if (error)
822 return error;
823
824 error = xfs_iext_count_extend(tp, ip, XFS_DATA_FORK,
825 XFS_IEXT_PUNCH_HOLE_CNT);
826 if (error)
827 goto out_trans_cancel;
828
829 error = xfs_bunmapi(tp, ip, startoffset_fsb, len_fsb, 0, 2, done);
830 if (error)
831 goto out_trans_cancel;
832
833 error = xfs_trans_commit(tp);
834 out_unlock:
835 xfs_iunlock(ip, XFS_ILOCK_EXCL);
836 return error;
837
838 out_trans_cancel:
839 xfs_trans_cancel(tp);
840 goto out_unlock;
841 }
842
843 /* Caller must first wait for the completion of any pending DIOs if required. */
844 int
xfs_flush_unmap_range(struct xfs_inode * ip,xfs_off_t offset,xfs_off_t len)845 xfs_flush_unmap_range(
846 struct xfs_inode *ip,
847 xfs_off_t offset,
848 xfs_off_t len)
849 {
850 struct inode *inode = VFS_I(ip);
851 xfs_off_t rounding, start, end;
852 int error;
853
854 /*
855 * Make sure we extend the flush out to extent alignment
856 * boundaries so any extent range overlapping the start/end
857 * of the modification we are about to do is clean and idle.
858 */
859 rounding = max_t(xfs_off_t, xfs_inode_alloc_unitsize(ip), PAGE_SIZE);
860 start = rounddown_64(offset, rounding);
861 end = roundup_64(offset + len, rounding) - 1;
862
863 error = filemap_write_and_wait_range(inode->i_mapping, start, end);
864 if (error)
865 return error;
866 truncate_pagecache_range(inode, start, end);
867 return 0;
868 }
869
870 int
xfs_free_file_space(struct xfs_inode * ip,xfs_off_t offset,xfs_off_t len,struct xfs_zone_alloc_ctx * ac)871 xfs_free_file_space(
872 struct xfs_inode *ip,
873 xfs_off_t offset,
874 xfs_off_t len,
875 struct xfs_zone_alloc_ctx *ac)
876 {
877 struct xfs_mount *mp = ip->i_mount;
878 xfs_fileoff_t startoffset_fsb;
879 xfs_fileoff_t endoffset_fsb;
880 int done = 0, error;
881
882 trace_xfs_free_file_space(ip);
883
884 error = xfs_qm_dqattach(ip);
885 if (error)
886 return error;
887
888 if (len <= 0) /* if nothing being freed */
889 return 0;
890
891 /*
892 * Now AIO and DIO has drained we flush and (if necessary) invalidate
893 * the cached range over the first operation we are about to run.
894 */
895 error = xfs_flush_unmap_range(ip, offset, len);
896 if (error)
897 return error;
898
899 startoffset_fsb = XFS_B_TO_FSB(mp, offset);
900 endoffset_fsb = XFS_B_TO_FSBT(mp, offset + len);
901
902 /* We can only free complete realtime extents. */
903 if (xfs_inode_has_bigrtalloc(ip)) {
904 startoffset_fsb = xfs_fileoff_roundup_rtx(mp, startoffset_fsb);
905 endoffset_fsb = xfs_fileoff_rounddown_rtx(mp, endoffset_fsb);
906 }
907
908 /*
909 * Need to zero the stuff we're not freeing, on disk.
910 */
911 if (endoffset_fsb > startoffset_fsb) {
912 while (!done) {
913 error = xfs_unmap_extent(ip, startoffset_fsb,
914 endoffset_fsb - startoffset_fsb, &done);
915 if (error)
916 return error;
917 }
918 }
919
920 /*
921 * Now that we've unmap all full blocks we'll have to zero out any
922 * partial block at the beginning and/or end. xfs_zero_range is smart
923 * enough to skip any holes, including those we just created, but we
924 * must take care not to zero beyond EOF and enlarge i_size.
925 */
926 if (offset >= XFS_ISIZE(ip))
927 return 0;
928 if (offset + len > XFS_ISIZE(ip))
929 len = XFS_ISIZE(ip) - offset;
930 error = xfs_zero_range(ip, offset, len, ac, NULL);
931 if (error)
932 return error;
933
934 /*
935 * If we zeroed right up to EOF and EOF straddles a page boundary we
936 * must make sure that the post-EOF area is also zeroed because the
937 * page could be mmap'd and xfs_zero_range doesn't do that for us.
938 * Writeback of the eof page will do this, albeit clumsily.
939 */
940 if (offset + len >= XFS_ISIZE(ip) && offset_in_page(offset + len) > 0) {
941 error = filemap_write_and_wait_range(VFS_I(ip)->i_mapping,
942 round_down(offset + len, PAGE_SIZE), LLONG_MAX);
943 }
944
945 return error;
946 }
947
948 static int
xfs_prepare_shift(struct xfs_inode * ip,loff_t offset)949 xfs_prepare_shift(
950 struct xfs_inode *ip,
951 loff_t offset)
952 {
953 unsigned int rounding;
954 int error;
955
956 /*
957 * Trim eofblocks to avoid shifting uninitialized post-eof preallocation
958 * into the accessible region of the file.
959 */
960 if (xfs_can_free_eofblocks(ip)) {
961 error = xfs_free_eofblocks(ip);
962 if (error)
963 return error;
964 }
965
966 /*
967 * Shift operations must stabilize the start block offset boundary along
968 * with the full range of the operation. If we don't, a COW writeback
969 * completion could race with an insert, front merge with the start
970 * extent (after split) during the shift and corrupt the file. Start
971 * with the allocation unit just prior to the start to stabilize the
972 * boundary.
973 */
974 rounding = xfs_inode_alloc_unitsize(ip);
975 offset = rounddown_64(offset, rounding);
976 if (offset)
977 offset -= rounding;
978
979 /*
980 * Writeback and invalidate cache for the remainder of the file as we're
981 * about to shift down every extent from offset to EOF.
982 */
983 error = xfs_flush_unmap_range(ip, offset, XFS_ISIZE(ip));
984 if (error)
985 return error;
986
987 /*
988 * Clean out anything hanging around in the cow fork now that
989 * we've flushed all the dirty data out to disk to avoid having
990 * CoW extents at the wrong offsets.
991 */
992 if (xfs_inode_has_cow_data(ip)) {
993 error = xfs_reflink_cancel_cow_range(ip, offset, NULLFILEOFF,
994 true);
995 if (error)
996 return error;
997 }
998
999 return 0;
1000 }
1001
1002 /*
1003 * xfs_collapse_file_space()
1004 * This routine frees disk space and shift extent for the given file.
1005 * The first thing we do is to free data blocks in the specified range
1006 * by calling xfs_free_file_space(). It would also sync dirty data
1007 * and invalidate page cache over the region on which collapse range
1008 * is working. And Shift extent records to the left to cover a hole.
1009 * RETURNS:
1010 * 0 on success
1011 * errno on error
1012 *
1013 */
1014 int
xfs_collapse_file_space(struct xfs_inode * ip,xfs_off_t offset,xfs_off_t len,struct xfs_zone_alloc_ctx * ac)1015 xfs_collapse_file_space(
1016 struct xfs_inode *ip,
1017 xfs_off_t offset,
1018 xfs_off_t len,
1019 struct xfs_zone_alloc_ctx *ac)
1020 {
1021 struct xfs_mount *mp = ip->i_mount;
1022 struct xfs_trans *tp;
1023 int error;
1024 xfs_fileoff_t next_fsb = XFS_B_TO_FSB(mp, offset + len);
1025 xfs_fileoff_t shift_fsb = XFS_B_TO_FSB(mp, len);
1026 bool done = false;
1027
1028 xfs_assert_ilocked(ip, XFS_IOLOCK_EXCL | XFS_MMAPLOCK_EXCL);
1029
1030 trace_xfs_collapse_file_space(ip);
1031
1032 error = xfs_free_file_space(ip, offset, len, ac);
1033 if (error)
1034 return error;
1035
1036 error = xfs_prepare_shift(ip, offset);
1037 if (error)
1038 return error;
1039
1040 error = xfs_trans_alloc(mp, &M_RES(mp)->tr_write, 0, 0, 0, &tp);
1041 if (error)
1042 return error;
1043
1044 xfs_ilock(ip, XFS_ILOCK_EXCL);
1045 xfs_trans_ijoin(tp, ip, 0);
1046
1047 while (!done) {
1048 error = xfs_bmap_collapse_extents(tp, ip, &next_fsb, shift_fsb,
1049 &done);
1050 if (error)
1051 goto out_trans_cancel;
1052 if (done)
1053 break;
1054
1055 /* finish any deferred frees and roll the transaction */
1056 error = xfs_defer_finish(&tp);
1057 if (error)
1058 goto out_trans_cancel;
1059 }
1060
1061 error = xfs_trans_commit(tp);
1062 xfs_iunlock(ip, XFS_ILOCK_EXCL);
1063 return error;
1064
1065 out_trans_cancel:
1066 xfs_trans_cancel(tp);
1067 xfs_iunlock(ip, XFS_ILOCK_EXCL);
1068 return error;
1069 }
1070
1071 /*
1072 * xfs_insert_file_space()
1073 * This routine create hole space by shifting extents for the given file.
1074 * The first thing we do is to sync dirty data and invalidate page cache
1075 * over the region on which insert range is working. And split an extent
1076 * to two extents at given offset by calling xfs_bmap_split_extent.
1077 * And shift all extent records which are laying between [offset,
1078 * last allocated extent] to the right to reserve hole range.
1079 * RETURNS:
1080 * 0 on success
1081 * errno on error
1082 */
1083 int
xfs_insert_file_space(struct xfs_inode * ip,loff_t offset,loff_t len)1084 xfs_insert_file_space(
1085 struct xfs_inode *ip,
1086 loff_t offset,
1087 loff_t len)
1088 {
1089 struct xfs_mount *mp = ip->i_mount;
1090 struct xfs_trans *tp;
1091 int error;
1092 xfs_fileoff_t stop_fsb = XFS_B_TO_FSB(mp, offset);
1093 xfs_fileoff_t next_fsb = NULLFSBLOCK;
1094 xfs_fileoff_t shift_fsb = XFS_B_TO_FSB(mp, len);
1095 bool done = false;
1096
1097 xfs_assert_ilocked(ip, XFS_IOLOCK_EXCL | XFS_MMAPLOCK_EXCL);
1098
1099 trace_xfs_insert_file_space(ip);
1100
1101 error = xfs_bmap_can_insert_extents(ip, stop_fsb, shift_fsb);
1102 if (error)
1103 return error;
1104
1105 error = xfs_prepare_shift(ip, offset);
1106 if (error)
1107 return error;
1108
1109 error = xfs_trans_alloc(mp, &M_RES(mp)->tr_write,
1110 XFS_DIOSTRAT_SPACE_RES(mp, 0), 0, 0, &tp);
1111 if (error)
1112 return error;
1113
1114 xfs_ilock(ip, XFS_ILOCK_EXCL);
1115 xfs_trans_ijoin(tp, ip, 0);
1116
1117 error = xfs_iext_count_extend(tp, ip, XFS_DATA_FORK,
1118 XFS_IEXT_PUNCH_HOLE_CNT);
1119 if (error)
1120 goto out_trans_cancel;
1121
1122 /*
1123 * The extent shifting code works on extent granularity. So, if stop_fsb
1124 * is not the starting block of extent, we need to split the extent at
1125 * stop_fsb.
1126 */
1127 error = xfs_bmap_split_extent(tp, ip, stop_fsb);
1128 if (error)
1129 goto out_trans_cancel;
1130
1131 do {
1132 error = xfs_defer_finish(&tp);
1133 if (error)
1134 goto out_trans_cancel;
1135
1136 error = xfs_bmap_insert_extents(tp, ip, &next_fsb, shift_fsb,
1137 &done, stop_fsb);
1138 if (error)
1139 goto out_trans_cancel;
1140 } while (!done);
1141
1142 error = xfs_trans_commit(tp);
1143 xfs_iunlock(ip, XFS_ILOCK_EXCL);
1144 return error;
1145
1146 out_trans_cancel:
1147 xfs_trans_cancel(tp);
1148 xfs_iunlock(ip, XFS_ILOCK_EXCL);
1149 return error;
1150 }
1151
1152 /*
1153 * We need to check that the format of the data fork in the temporary inode is
1154 * valid for the target inode before doing the swap. This is not a problem with
1155 * attr1 because of the fixed fork offset, but attr2 has a dynamically sized
1156 * data fork depending on the space the attribute fork is taking so we can get
1157 * invalid formats on the target inode.
1158 *
1159 * E.g. target has space for 7 extents in extent format, temp inode only has
1160 * space for 6. If we defragment down to 7 extents, then the tmp format is a
1161 * btree, but when swapped it needs to be in extent format. Hence we can't just
1162 * blindly swap data forks on attr2 filesystems.
1163 *
1164 * Note that we check the swap in both directions so that we don't end up with
1165 * a corrupt temporary inode, either.
1166 *
1167 * Note that fixing the way xfs_fsr sets up the attribute fork in the source
1168 * inode will prevent this situation from occurring, so all we do here is
1169 * reject and log the attempt. basically we are putting the responsibility on
1170 * userspace to get this right.
1171 */
1172 static int
xfs_swap_extents_check_format(struct xfs_inode * ip,struct xfs_inode * tip)1173 xfs_swap_extents_check_format(
1174 struct xfs_inode *ip, /* target inode */
1175 struct xfs_inode *tip) /* tmp inode */
1176 {
1177 struct xfs_ifork *ifp = &ip->i_df;
1178 struct xfs_ifork *tifp = &tip->i_df;
1179
1180 /* User/group/project quota ids must match if quotas are enforced. */
1181 if (XFS_IS_QUOTA_ON(ip->i_mount) &&
1182 (!uid_eq(VFS_I(ip)->i_uid, VFS_I(tip)->i_uid) ||
1183 !gid_eq(VFS_I(ip)->i_gid, VFS_I(tip)->i_gid) ||
1184 ip->i_projid != tip->i_projid))
1185 return -EINVAL;
1186
1187 /* Should never get a local format */
1188 if (ifp->if_format == XFS_DINODE_FMT_LOCAL ||
1189 tifp->if_format == XFS_DINODE_FMT_LOCAL)
1190 return -EINVAL;
1191
1192 /*
1193 * if the target inode has less extents that then temporary inode then
1194 * why did userspace call us?
1195 */
1196 if (ifp->if_nextents < tifp->if_nextents)
1197 return -EINVAL;
1198
1199 /*
1200 * If we have to use the (expensive) rmap swap method, we can
1201 * handle any number of extents and any format.
1202 */
1203 if (xfs_has_rmapbt(ip->i_mount))
1204 return 0;
1205
1206 /*
1207 * if the target inode is in extent form and the temp inode is in btree
1208 * form then we will end up with the target inode in the wrong format
1209 * as we already know there are less extents in the temp inode.
1210 */
1211 if (ifp->if_format == XFS_DINODE_FMT_EXTENTS &&
1212 tifp->if_format == XFS_DINODE_FMT_BTREE)
1213 return -EINVAL;
1214
1215 /* Check temp in extent form to max in target */
1216 if (tifp->if_format == XFS_DINODE_FMT_EXTENTS &&
1217 tifp->if_nextents > XFS_IFORK_MAXEXT(ip, XFS_DATA_FORK))
1218 return -EINVAL;
1219
1220 /* Check target in extent form to max in temp */
1221 if (ifp->if_format == XFS_DINODE_FMT_EXTENTS &&
1222 ifp->if_nextents > XFS_IFORK_MAXEXT(tip, XFS_DATA_FORK))
1223 return -EINVAL;
1224
1225 /*
1226 * If we are in a btree format, check that the temp root block will fit
1227 * in the target and that it has enough extents to be in btree format
1228 * in the target.
1229 *
1230 * Note that we have to be careful to allow btree->extent conversions
1231 * (a common defrag case) which will occur when the temp inode is in
1232 * extent format...
1233 */
1234 if (tifp->if_format == XFS_DINODE_FMT_BTREE) {
1235 if (xfs_inode_has_attr_fork(ip) &&
1236 xfs_bmap_bmdr_space(tifp->if_broot) > xfs_inode_fork_boff(ip))
1237 return -EINVAL;
1238 if (tifp->if_nextents <= XFS_IFORK_MAXEXT(ip, XFS_DATA_FORK))
1239 return -EINVAL;
1240 }
1241
1242 /* Reciprocal target->temp btree format checks */
1243 if (ifp->if_format == XFS_DINODE_FMT_BTREE) {
1244 if (xfs_inode_has_attr_fork(tip) &&
1245 xfs_bmap_bmdr_space(ip->i_df.if_broot) > xfs_inode_fork_boff(tip))
1246 return -EINVAL;
1247 if (ifp->if_nextents <= XFS_IFORK_MAXEXT(tip, XFS_DATA_FORK))
1248 return -EINVAL;
1249 }
1250
1251 return 0;
1252 }
1253
1254 static int
xfs_swap_extent_flush(struct xfs_inode * ip)1255 xfs_swap_extent_flush(
1256 struct xfs_inode *ip)
1257 {
1258 int error;
1259
1260 error = filemap_write_and_wait(VFS_I(ip)->i_mapping);
1261 if (error)
1262 return error;
1263 truncate_pagecache_range(VFS_I(ip), 0, -1);
1264
1265 /* Verify O_DIRECT for ftmp */
1266 if (VFS_I(ip)->i_mapping->nrpages)
1267 return -EINVAL;
1268 return 0;
1269 }
1270
1271 /*
1272 * Move extents from one file to another, when rmap is enabled.
1273 */
1274 STATIC int
xfs_swap_extent_rmap(struct xfs_trans ** tpp,struct xfs_inode * ip,struct xfs_inode * tip)1275 xfs_swap_extent_rmap(
1276 struct xfs_trans **tpp,
1277 struct xfs_inode *ip,
1278 struct xfs_inode *tip)
1279 {
1280 struct xfs_trans *tp = *tpp;
1281 struct xfs_bmbt_irec irec;
1282 struct xfs_bmbt_irec uirec;
1283 struct xfs_bmbt_irec tirec;
1284 xfs_fileoff_t offset_fsb;
1285 xfs_fileoff_t end_fsb;
1286 xfs_filblks_t count_fsb;
1287 int error;
1288 xfs_filblks_t ilen;
1289 xfs_filblks_t rlen;
1290 int nimaps;
1291 uint64_t tip_flags2;
1292
1293 /*
1294 * If the source file has shared blocks, we must flag the donor
1295 * file as having shared blocks so that we get the shared-block
1296 * rmap functions when we go to fix up the rmaps. The flags
1297 * will be switch for reals later.
1298 */
1299 tip_flags2 = tip->i_diflags2;
1300 if (ip->i_diflags2 & XFS_DIFLAG2_REFLINK)
1301 tip->i_diflags2 |= XFS_DIFLAG2_REFLINK;
1302
1303 offset_fsb = 0;
1304 end_fsb = XFS_B_TO_FSB(ip->i_mount, i_size_read(VFS_I(ip)));
1305 count_fsb = (xfs_filblks_t)(end_fsb - offset_fsb);
1306
1307 while (count_fsb) {
1308 /* Read extent from the donor file */
1309 nimaps = 1;
1310 error = xfs_bmapi_read(tip, offset_fsb, count_fsb, &tirec,
1311 &nimaps, 0);
1312 if (error)
1313 goto out;
1314 ASSERT(nimaps == 1);
1315 ASSERT(tirec.br_startblock != DELAYSTARTBLOCK);
1316
1317 trace_xfs_swap_extent_rmap_remap(tip, &tirec);
1318 ilen = tirec.br_blockcount;
1319
1320 /* Unmap the old blocks in the source file. */
1321 while (tirec.br_blockcount) {
1322 ASSERT(tp->t_highest_agno == NULLAGNUMBER);
1323 trace_xfs_swap_extent_rmap_remap_piece(tip, &tirec);
1324
1325 /* Read extent from the source file */
1326 nimaps = 1;
1327 error = xfs_bmapi_read(ip, tirec.br_startoff,
1328 tirec.br_blockcount, &irec,
1329 &nimaps, 0);
1330 if (error)
1331 goto out;
1332 ASSERT(nimaps == 1);
1333 ASSERT(tirec.br_startoff == irec.br_startoff);
1334 trace_xfs_swap_extent_rmap_remap_piece(ip, &irec);
1335
1336 /* Trim the extent. */
1337 uirec = tirec;
1338 uirec.br_blockcount = rlen = min_t(xfs_filblks_t,
1339 tirec.br_blockcount,
1340 irec.br_blockcount);
1341 trace_xfs_swap_extent_rmap_remap_piece(tip, &uirec);
1342
1343 if (xfs_bmap_is_real_extent(&uirec)) {
1344 error = xfs_iext_count_extend(tp, ip,
1345 XFS_DATA_FORK,
1346 XFS_IEXT_SWAP_RMAP_CNT);
1347 if (error)
1348 goto out;
1349 }
1350
1351 if (xfs_bmap_is_real_extent(&irec)) {
1352 error = xfs_iext_count_extend(tp, tip,
1353 XFS_DATA_FORK,
1354 XFS_IEXT_SWAP_RMAP_CNT);
1355 if (error)
1356 goto out;
1357 }
1358
1359 /* Remove the mapping from the donor file. */
1360 xfs_bmap_unmap_extent(tp, tip, XFS_DATA_FORK, &uirec);
1361
1362 /* Remove the mapping from the source file. */
1363 xfs_bmap_unmap_extent(tp, ip, XFS_DATA_FORK, &irec);
1364
1365 /* Map the donor file's blocks into the source file. */
1366 xfs_bmap_map_extent(tp, ip, XFS_DATA_FORK, &uirec);
1367
1368 /* Map the source file's blocks into the donor file. */
1369 xfs_bmap_map_extent(tp, tip, XFS_DATA_FORK, &irec);
1370
1371 error = xfs_defer_finish(tpp);
1372 tp = *tpp;
1373 if (error)
1374 goto out;
1375
1376 tirec.br_startoff += rlen;
1377 if (tirec.br_startblock != HOLESTARTBLOCK &&
1378 tirec.br_startblock != DELAYSTARTBLOCK)
1379 tirec.br_startblock += rlen;
1380 tirec.br_blockcount -= rlen;
1381 }
1382
1383 /* Roll on... */
1384 count_fsb -= ilen;
1385 offset_fsb += ilen;
1386 }
1387
1388 tip->i_diflags2 = tip_flags2;
1389 return 0;
1390
1391 out:
1392 trace_xfs_swap_extent_rmap_error(ip, error, _RET_IP_);
1393 tip->i_diflags2 = tip_flags2;
1394 return error;
1395 }
1396
1397 /* Swap the extents of two files by swapping data forks. */
1398 STATIC int
xfs_swap_extent_forks(struct xfs_trans * tp,struct xfs_inode * ip,struct xfs_inode * tip,int * src_log_flags,int * target_log_flags)1399 xfs_swap_extent_forks(
1400 struct xfs_trans *tp,
1401 struct xfs_inode *ip,
1402 struct xfs_inode *tip,
1403 int *src_log_flags,
1404 int *target_log_flags)
1405 {
1406 xfs_filblks_t aforkblks = 0;
1407 xfs_filblks_t taforkblks = 0;
1408 xfs_extnum_t junk;
1409 uint64_t tmp;
1410 int error;
1411
1412 /*
1413 * Count the number of extended attribute blocks
1414 */
1415 if (xfs_inode_has_attr_fork(ip) && ip->i_af.if_nextents > 0 &&
1416 ip->i_af.if_format != XFS_DINODE_FMT_LOCAL) {
1417 error = xfs_bmap_count_blocks(tp, ip, XFS_ATTR_FORK, &junk,
1418 &aforkblks);
1419 if (error)
1420 return error;
1421 }
1422 if (xfs_inode_has_attr_fork(tip) && tip->i_af.if_nextents > 0 &&
1423 tip->i_af.if_format != XFS_DINODE_FMT_LOCAL) {
1424 error = xfs_bmap_count_blocks(tp, tip, XFS_ATTR_FORK, &junk,
1425 &taforkblks);
1426 if (error)
1427 return error;
1428 }
1429
1430 /*
1431 * Btree format (v3) inodes have the inode number stamped in the bmbt
1432 * block headers. We can't start changing the bmbt blocks until the
1433 * inode owner change is logged so recovery does the right thing in the
1434 * event of a crash. Set the owner change log flags now and leave the
1435 * bmbt scan as the last step.
1436 */
1437 if (xfs_has_v3inodes(ip->i_mount)) {
1438 if (ip->i_df.if_format == XFS_DINODE_FMT_BTREE)
1439 (*target_log_flags) |= XFS_ILOG_DOWNER;
1440 if (tip->i_df.if_format == XFS_DINODE_FMT_BTREE)
1441 (*src_log_flags) |= XFS_ILOG_DOWNER;
1442 }
1443
1444 /*
1445 * Swap the data forks of the inodes
1446 */
1447 swap(ip->i_df, tip->i_df);
1448
1449 /*
1450 * Fix the on-disk inode values
1451 */
1452 tmp = (uint64_t)ip->i_nblocks;
1453 ip->i_nblocks = tip->i_nblocks - taforkblks + aforkblks;
1454 tip->i_nblocks = tmp + taforkblks - aforkblks;
1455
1456 /*
1457 * The extents in the source inode could still contain speculative
1458 * preallocation beyond EOF (e.g. the file is open but not modified
1459 * while defrag is in progress). In that case, we need to copy over the
1460 * number of delalloc blocks the data fork in the source inode is
1461 * tracking beyond EOF so that when the fork is truncated away when the
1462 * temporary inode is unlinked we don't underrun the i_delayed_blks
1463 * counter on that inode.
1464 */
1465 ASSERT(tip->i_delayed_blks == 0);
1466 tip->i_delayed_blks = ip->i_delayed_blks;
1467 ip->i_delayed_blks = 0;
1468
1469 switch (ip->i_df.if_format) {
1470 case XFS_DINODE_FMT_EXTENTS:
1471 (*src_log_flags) |= XFS_ILOG_DEXT;
1472 break;
1473 case XFS_DINODE_FMT_BTREE:
1474 ASSERT(!xfs_has_v3inodes(ip->i_mount) ||
1475 (*src_log_flags & XFS_ILOG_DOWNER));
1476 (*src_log_flags) |= XFS_ILOG_DBROOT;
1477 break;
1478 }
1479
1480 switch (tip->i_df.if_format) {
1481 case XFS_DINODE_FMT_EXTENTS:
1482 (*target_log_flags) |= XFS_ILOG_DEXT;
1483 break;
1484 case XFS_DINODE_FMT_BTREE:
1485 (*target_log_flags) |= XFS_ILOG_DBROOT;
1486 ASSERT(!xfs_has_v3inodes(ip->i_mount) ||
1487 (*target_log_flags & XFS_ILOG_DOWNER));
1488 break;
1489 }
1490
1491 return 0;
1492 }
1493
1494 /*
1495 * Fix up the owners of the bmbt blocks to refer to the current inode. The
1496 * change owner scan attempts to order all modified buffers in the current
1497 * transaction. In the event of ordered buffer failure, the offending buffer is
1498 * physically logged as a fallback and the scan returns -EAGAIN. We must roll
1499 * the transaction in this case to replenish the fallback log reservation and
1500 * restart the scan. This process repeats until the scan completes.
1501 */
1502 static int
xfs_swap_change_owner(struct xfs_trans ** tpp,struct xfs_inode * ip,struct xfs_inode * tmpip)1503 xfs_swap_change_owner(
1504 struct xfs_trans **tpp,
1505 struct xfs_inode *ip,
1506 struct xfs_inode *tmpip)
1507 {
1508 int error;
1509 struct xfs_trans *tp = *tpp;
1510
1511 do {
1512 error = xfs_bmbt_change_owner(tp, ip, XFS_DATA_FORK, I_INO(ip),
1513 NULL);
1514 /* success or fatal error */
1515 if (error != -EAGAIN)
1516 break;
1517
1518 error = xfs_trans_roll(tpp);
1519 if (error)
1520 break;
1521 tp = *tpp;
1522
1523 /*
1524 * Redirty both inodes so they can relog and keep the log tail
1525 * moving forward.
1526 */
1527 xfs_trans_ijoin(tp, ip, 0);
1528 xfs_trans_ijoin(tp, tmpip, 0);
1529 xfs_trans_log_inode(tp, ip, XFS_ILOG_CORE);
1530 xfs_trans_log_inode(tp, tmpip, XFS_ILOG_CORE);
1531 } while (true);
1532
1533 return error;
1534 }
1535
1536 int
xfs_swap_extents(struct xfs_inode * ip,struct xfs_inode * tip,struct xfs_swapext * sxp)1537 xfs_swap_extents(
1538 struct xfs_inode *ip, /* target inode */
1539 struct xfs_inode *tip, /* tmp inode */
1540 struct xfs_swapext *sxp)
1541 {
1542 struct xfs_mount *mp = ip->i_mount;
1543 struct xfs_trans *tp;
1544 struct xfs_bstat *sbp = &sxp->sx_stat;
1545 int src_log_flags, target_log_flags;
1546 int error = 0;
1547 uint64_t f;
1548 int resblks = 0;
1549 unsigned int flags = 0;
1550 struct timespec64 ctime, mtime;
1551
1552 /*
1553 * Lock the inodes against other IO, page faults and truncate to
1554 * begin with. Then we can ensure the inodes are flushed and have no
1555 * page cache safely. Once we have done this we can take the ilocks and
1556 * do the rest of the checks.
1557 */
1558 lock_two_nondirectories(VFS_I(ip), VFS_I(tip));
1559 filemap_invalidate_lock_two(VFS_I(ip)->i_mapping,
1560 VFS_I(tip)->i_mapping);
1561
1562 /* Verify that both files have the same format */
1563 if ((VFS_I(ip)->i_mode & S_IFMT) != (VFS_I(tip)->i_mode & S_IFMT)) {
1564 error = -EINVAL;
1565 goto out_unlock;
1566 }
1567
1568 /* Verify both files are either real-time or non-realtime */
1569 if (XFS_IS_REALTIME_INODE(ip) != XFS_IS_REALTIME_INODE(tip)) {
1570 error = -EINVAL;
1571 goto out_unlock;
1572 }
1573
1574 /*
1575 * The rmapbt implementation is unable to resume a swapext operation
1576 * after a crash if the allocation unit size is larger than a block.
1577 * This (deprecated) interface will not be upgraded to handle this
1578 * situation. Defragmentation must be performed with the commit range
1579 * ioctl.
1580 */
1581 if (XFS_IS_REALTIME_INODE(ip) && xfs_has_rtgroups(ip->i_mount)) {
1582 error = -EOPNOTSUPP;
1583 goto out_unlock;
1584 }
1585
1586 error = xfs_qm_dqattach(ip);
1587 if (error)
1588 goto out_unlock;
1589
1590 error = xfs_qm_dqattach(tip);
1591 if (error)
1592 goto out_unlock;
1593
1594 error = xfs_swap_extent_flush(ip);
1595 if (error)
1596 goto out_unlock;
1597 error = xfs_swap_extent_flush(tip);
1598 if (error)
1599 goto out_unlock;
1600
1601 if (xfs_inode_has_cow_data(tip)) {
1602 error = xfs_reflink_cancel_cow_range(tip, 0, NULLFILEOFF, true);
1603 if (error)
1604 goto out_unlock;
1605 }
1606
1607 /*
1608 * Extent "swapping" with rmap requires a permanent reservation and
1609 * a block reservation because it's really just a remap operation
1610 * performed with log redo items!
1611 */
1612 if (xfs_has_rmapbt(mp)) {
1613 int w = XFS_DATA_FORK;
1614 uint32_t ipnext = ip->i_df.if_nextents;
1615 uint32_t tipnext = tip->i_df.if_nextents;
1616
1617 /*
1618 * Conceptually this shouldn't affect the shape of either bmbt,
1619 * but since we atomically move extents one by one, we reserve
1620 * enough space to rebuild both trees.
1621 */
1622 resblks = XFS_SWAP_RMAP_SPACE_RES(mp, ipnext, w);
1623 resblks += XFS_SWAP_RMAP_SPACE_RES(mp, tipnext, w);
1624
1625 /*
1626 * If either inode straddles a bmapbt block allocation boundary,
1627 * the rmapbt algorithm triggers repeated allocs and frees as
1628 * extents are remapped. This can exhaust the block reservation
1629 * prematurely and cause shutdown. Return freed blocks to the
1630 * transaction reservation to counter this behavior.
1631 */
1632 flags |= XFS_TRANS_RES_FDBLKS;
1633 }
1634 error = xfs_trans_alloc(mp, &M_RES(mp)->tr_write, resblks, 0, flags,
1635 &tp);
1636 if (error)
1637 goto out_unlock;
1638
1639 /*
1640 * Lock and join the inodes to the tansaction so that transaction commit
1641 * or cancel will unlock the inodes from this point onwards.
1642 */
1643 xfs_lock_two_inodes(ip, XFS_ILOCK_EXCL, tip, XFS_ILOCK_EXCL);
1644 xfs_trans_ijoin(tp, ip, 0);
1645 xfs_trans_ijoin(tp, tip, 0);
1646
1647
1648 /* Verify all data are being swapped */
1649 if (sxp->sx_offset != 0 ||
1650 sxp->sx_length != ip->i_disk_size ||
1651 sxp->sx_length != tip->i_disk_size) {
1652 error = -EFAULT;
1653 goto out_trans_cancel;
1654 }
1655
1656 trace_xfs_swap_extent_before(ip, 0);
1657 trace_xfs_swap_extent_before(tip, 1);
1658
1659 /* check inode formats now that data is flushed */
1660 error = xfs_swap_extents_check_format(ip, tip);
1661 if (error) {
1662 xfs_notice(mp,
1663 "%s: inode 0x%llx format is incompatible for exchanging.",
1664 __func__, I_INO(ip));
1665 goto out_trans_cancel;
1666 }
1667
1668 /*
1669 * Compare the current change & modify times with that
1670 * passed in. If they differ, we abort this swap.
1671 * This is the mechanism used to ensure the calling
1672 * process that the file was not changed out from
1673 * under it.
1674 */
1675 ctime = inode_get_ctime(VFS_I(ip));
1676 mtime = inode_get_mtime(VFS_I(ip));
1677 if ((sbp->bs_ctime.tv_sec != ctime.tv_sec) ||
1678 (sbp->bs_ctime.tv_nsec != ctime.tv_nsec) ||
1679 (sbp->bs_mtime.tv_sec != mtime.tv_sec) ||
1680 (sbp->bs_mtime.tv_nsec != mtime.tv_nsec)) {
1681 error = -EBUSY;
1682 goto out_trans_cancel;
1683 }
1684
1685 /*
1686 * Note the trickiness in setting the log flags - we set the owner log
1687 * flag on the opposite inode (i.e. the inode we are setting the new
1688 * owner to be) because once we swap the forks and log that, log
1689 * recovery is going to see the fork as owned by the swapped inode,
1690 * not the pre-swapped inodes.
1691 */
1692 src_log_flags = XFS_ILOG_CORE;
1693 target_log_flags = XFS_ILOG_CORE;
1694
1695 if (xfs_has_rmapbt(mp))
1696 error = xfs_swap_extent_rmap(&tp, ip, tip);
1697 else
1698 error = xfs_swap_extent_forks(tp, ip, tip, &src_log_flags,
1699 &target_log_flags);
1700 if (error)
1701 goto out_trans_cancel;
1702
1703 /* Do we have to swap reflink flags? */
1704 if ((ip->i_diflags2 & XFS_DIFLAG2_REFLINK) ^
1705 (tip->i_diflags2 & XFS_DIFLAG2_REFLINK)) {
1706 f = ip->i_diflags2 & XFS_DIFLAG2_REFLINK;
1707 ip->i_diflags2 &= ~XFS_DIFLAG2_REFLINK;
1708 ip->i_diflags2 |= tip->i_diflags2 & XFS_DIFLAG2_REFLINK;
1709 tip->i_diflags2 &= ~XFS_DIFLAG2_REFLINK;
1710 tip->i_diflags2 |= f & XFS_DIFLAG2_REFLINK;
1711 }
1712
1713 /* Swap the cow forks. */
1714 if (xfs_has_reflink(mp)) {
1715 ASSERT(!ip->i_cowfp ||
1716 ip->i_cowfp->if_format == XFS_DINODE_FMT_EXTENTS);
1717 ASSERT(!tip->i_cowfp ||
1718 tip->i_cowfp->if_format == XFS_DINODE_FMT_EXTENTS);
1719
1720 swap(ip->i_cowfp, tip->i_cowfp);
1721
1722 if (ip->i_cowfp && ip->i_cowfp->if_bytes)
1723 xfs_inode_set_cowblocks_tag(ip);
1724 else
1725 xfs_inode_clear_cowblocks_tag(ip);
1726 if (tip->i_cowfp && tip->i_cowfp->if_bytes)
1727 xfs_inode_set_cowblocks_tag(tip);
1728 else
1729 xfs_inode_clear_cowblocks_tag(tip);
1730 }
1731
1732 xfs_trans_log_inode(tp, ip, src_log_flags);
1733 xfs_trans_log_inode(tp, tip, target_log_flags);
1734
1735 /*
1736 * The extent forks have been swapped, but crc=1,rmapbt=0 filesystems
1737 * have inode number owner values in the bmbt blocks that still refer to
1738 * the old inode. Scan each bmbt to fix up the owner values with the
1739 * inode number of the current inode.
1740 */
1741 if (src_log_flags & XFS_ILOG_DOWNER) {
1742 error = xfs_swap_change_owner(&tp, ip, tip);
1743 if (error)
1744 goto out_trans_cancel;
1745 }
1746 if (target_log_flags & XFS_ILOG_DOWNER) {
1747 error = xfs_swap_change_owner(&tp, tip, ip);
1748 if (error)
1749 goto out_trans_cancel;
1750 }
1751
1752 /*
1753 * If this is a synchronous mount, make sure that the
1754 * transaction goes to disk before returning to the user.
1755 */
1756 if (xfs_has_wsync(mp))
1757 xfs_trans_set_sync(tp);
1758
1759 error = xfs_trans_commit(tp);
1760
1761 trace_xfs_swap_extent_after(ip, 0);
1762 trace_xfs_swap_extent_after(tip, 1);
1763
1764 out_unlock_ilock:
1765 xfs_iunlock(ip, XFS_ILOCK_EXCL);
1766 xfs_iunlock(tip, XFS_ILOCK_EXCL);
1767 out_unlock:
1768 filemap_invalidate_unlock_two(VFS_I(ip)->i_mapping,
1769 VFS_I(tip)->i_mapping);
1770 unlock_two_nondirectories(VFS_I(ip), VFS_I(tip));
1771 return error;
1772
1773 out_trans_cancel:
1774 xfs_trans_cancel(tp);
1775 goto out_unlock_ilock;
1776 }
1777
1778 /*
1779 * Given a CoW fork mapping @got and a replacement mapping @rep, map the space
1780 * described by @rep into the cow fork, pushing aside @got as necessary. @icur
1781 * must point to iext tree leaf containing @got.
1782 */
1783 void
xfs_bmap_replace_cow_mapping(struct xfs_inode * ip,struct xfs_iext_cursor * icur,struct xfs_bmbt_irec * got,struct xfs_bmbt_irec * rep)1784 xfs_bmap_replace_cow_mapping(
1785 struct xfs_inode *ip,
1786 struct xfs_iext_cursor *icur,
1787 struct xfs_bmbt_irec *got,
1788 struct xfs_bmbt_irec *rep)
1789 {
1790 struct xfs_ifork *ifp = xfs_ifork_ptr(ip, XFS_COW_FORK);
1791 xfs_fileoff_t rep_endoff =
1792 rep->br_startoff + rep->br_blockcount;
1793 xfs_fileoff_t got_endoff =
1794 got->br_startoff + got->br_blockcount;
1795 uint32_t state = BMAP_COWFORK;
1796
1797 ASSERT(rep->br_blockcount > 0);
1798 ASSERT(!isnullstartblock(got->br_startblock));
1799 ASSERT(got->br_startoff <= rep->br_startoff);
1800 ASSERT(got_endoff >= rep_endoff);
1801
1802 trace_xfs_bmap_replace_cow_mapping(ip, got, rep);
1803
1804 if (got->br_startoff == rep->br_startoff)
1805 state |= BMAP_LEFT_FILLING;
1806 if (got_endoff == rep_endoff)
1807 state |= BMAP_RIGHT_FILLING;
1808
1809 switch (state & (BMAP_LEFT_FILLING | BMAP_RIGHT_FILLING)) {
1810 case BMAP_LEFT_FILLING | BMAP_RIGHT_FILLING:
1811 /*
1812 * Replacement matches the whole mapping, update the record.
1813 */
1814 xfs_iext_update_extent(ip, state, icur, rep);
1815 break;
1816 case BMAP_LEFT_FILLING:
1817 /*
1818 * Replace the first part of the mapping: Update the cursor
1819 * position with the new mapping, then add a record with the
1820 * tail of the old mapping.
1821 */
1822 got->br_startoff = rep_endoff;
1823 got->br_blockcount -= rep->br_blockcount;
1824 got->br_startblock += rep->br_blockcount;
1825
1826 xfs_iext_update_extent(ip, state, icur, rep);
1827 xfs_iext_next(ifp, icur);
1828 xfs_iext_insert(ip, icur, got, state);
1829 break;
1830 case BMAP_RIGHT_FILLING:
1831 /*
1832 * Replacing the last part of the mapping. Shorten the current
1833 * mapping then add a record with the new mapping.
1834 */
1835 got->br_blockcount -= rep->br_blockcount;
1836
1837 xfs_iext_update_extent(ip, state, icur, got);
1838 xfs_iext_next(ifp, icur);
1839 xfs_iext_insert(ip, icur, rep, state);
1840 break;
1841 case 0:
1842 /*
1843 * Replacing the middle of the extent. Shorten the current
1844 * mapping, add a new record with the new mapping, and add a
1845 * second new record with the tail of the old mapping.
1846 */
1847 got->br_blockcount = rep->br_startoff - got->br_startoff;
1848
1849 struct xfs_bmbt_irec new = {
1850 .br_startoff = rep_endoff,
1851 .br_blockcount = got_endoff - rep_endoff,
1852 .br_state = got->br_state,
1853 .br_startblock = got->br_startblock +
1854 rep->br_blockcount +
1855 got->br_blockcount,
1856 };
1857
1858 xfs_iext_update_extent(ip, state, icur, got);
1859 xfs_iext_next(ifp, icur);
1860 xfs_iext_insert(ip, icur, rep, state);
1861 xfs_iext_next(ifp, icur);
1862 xfs_iext_insert(ip, icur, &new, state);
1863 break;
1864 }
1865 }
1866