xref: /linux/fs/ocfs2/move_extents.c (revision 1fd1dc41724319406b0aff221a352a400b0ddfc5)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * move_extents.c
4  *
5  * Copyright (C) 2011 Oracle.  All rights reserved.
6  */
7 #include <linux/fs.h>
8 #include <linux/types.h>
9 #include <linux/mount.h>
10 #include <linux/swap.h>
11 
12 #include <cluster/masklog.h>
13 
14 #include "ocfs2.h"
15 #include "ocfs2_ioctl.h"
16 
17 #include "alloc.h"
18 #include "localalloc.h"
19 #include "aops.h"
20 #include "dlmglue.h"
21 #include "extent_map.h"
22 #include "inode.h"
23 #include "journal.h"
24 #include "suballoc.h"
25 #include "uptodate.h"
26 #include "super.h"
27 #include "dir.h"
28 #include "buffer_head_io.h"
29 #include "sysfile.h"
30 #include "refcounttree.h"
31 #include "move_extents.h"
32 
33 struct ocfs2_move_extents_context {
34 	struct inode *inode;
35 	struct file *file;
36 	int auto_defrag;
37 	int partial;
38 	int credits;
39 	u32 new_phys_cpos;
40 	u32 clusters_moved;
41 	u64 refcount_loc;
42 	struct ocfs2_move_extents *range;
43 	struct ocfs2_extent_tree et;
44 	struct ocfs2_alloc_context *meta_ac;
45 	struct ocfs2_alloc_context *data_ac;
46 	struct ocfs2_cached_dealloc_ctxt dealloc;
47 };
48 
49 static int __ocfs2_move_extent(handle_t *handle,
50 			       struct ocfs2_move_extents_context *context,
51 			       u32 cpos, u32 len, u32 p_cpos, u32 new_p_cpos,
52 			       int ext_flags)
53 {
54 	int ret = 0, index;
55 	struct inode *inode = context->inode;
56 	struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
57 	struct ocfs2_extent_rec *rec, replace_rec;
58 	struct ocfs2_path *path = NULL;
59 	struct ocfs2_extent_list *el;
60 	u64 ino = ocfs2_metadata_cache_owner(context->et.et_ci);
61 	u64 old_blkno = ocfs2_clusters_to_blocks(inode->i_sb, p_cpos);
62 
63 	ret = ocfs2_duplicate_clusters_by_page(handle, inode, cpos,
64 					       p_cpos, new_p_cpos, len);
65 	if (ret) {
66 		mlog_errno(ret);
67 		goto out;
68 	}
69 
70 	memset(&replace_rec, 0, sizeof(replace_rec));
71 	replace_rec.e_cpos = cpu_to_le32(cpos);
72 	replace_rec.e_leaf_clusters = cpu_to_le16(len);
73 	replace_rec.e_blkno = cpu_to_le64(ocfs2_clusters_to_blocks(inode->i_sb,
74 								   new_p_cpos));
75 
76 	path = ocfs2_new_path_from_et(&context->et);
77 	if (!path) {
78 		ret = -ENOMEM;
79 		mlog_errno(ret);
80 		goto out;
81 	}
82 
83 	ret = ocfs2_find_path(INODE_CACHE(inode), path, cpos);
84 	if (ret) {
85 		mlog_errno(ret);
86 		goto out;
87 	}
88 
89 	el = path_leaf_el(path);
90 
91 	index = ocfs2_search_extent_list(el, cpos);
92 	if (index == -1) {
93 		ret = ocfs2_error(inode->i_sb,
94 				  "Inode %llu has an extent at cpos %u which can no longer be found\n",
95 				  (unsigned long long)ino, cpos);
96 		goto out;
97 	}
98 
99 	rec = &el->l_recs[index];
100 
101 	if (ext_flags != rec->e_flags) {
102 		ret = ocfs2_error(inode->i_sb,
103 				  "Inode %llu has corrupted extent %d with flags 0x%x at cpos %u\n",
104 				  (unsigned long long)ino, index, rec->e_flags, cpos);
105 		goto out;
106 	}
107 
108 	/*
109 	 * after moving/defraging to new location, the extent is not going
110 	 * to be refcounted anymore.
111 	 */
112 	replace_rec.e_flags = ext_flags & ~OCFS2_EXT_REFCOUNTED;
113 
114 	ret = ocfs2_split_extent(handle, &context->et, path, index,
115 				 &replace_rec, context->meta_ac,
116 				 &context->dealloc);
117 	if (ret) {
118 		mlog_errno(ret);
119 		goto out;
120 	}
121 
122 	context->new_phys_cpos = new_p_cpos;
123 
124 	/*
125 	 * need I to append truncate log for old clusters?
126 	 */
127 	if (old_blkno) {
128 		if (ext_flags & OCFS2_EXT_REFCOUNTED)
129 			ret = ocfs2_decrease_refcount(inode, handle,
130 					ocfs2_blocks_to_clusters(osb->sb,
131 								 old_blkno),
132 					len, context->meta_ac,
133 					&context->dealloc, 1);
134 		else
135 			ret = ocfs2_truncate_log_append(osb, handle,
136 							old_blkno, len);
137 	}
138 
139 	ocfs2_update_inode_fsync_trans(handle, inode, 0);
140 out:
141 	ocfs2_free_path(path);
142 	return ret;
143 }
144 
145 /*
146  * lock allocator, and reserve appropriate number of bits for
147  * meta blocks.
148  */
149 static int ocfs2_lock_meta_allocator_move_extents(struct inode *inode,
150 					struct ocfs2_extent_tree *et,
151 					u32 clusters_to_move,
152 					u32 extents_to_split,
153 					struct ocfs2_alloc_context **meta_ac,
154 					int extra_blocks,
155 					int *credits)
156 {
157 	int ret, num_free_extents;
158 	unsigned int max_recs_needed = 2 * extents_to_split + clusters_to_move;
159 	struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
160 
161 	num_free_extents = ocfs2_num_free_extents(et);
162 	if (num_free_extents < 0) {
163 		ret = num_free_extents;
164 		mlog_errno(ret);
165 		goto out;
166 	}
167 
168 	if (!num_free_extents ||
169 	    (ocfs2_sparse_alloc(osb) && num_free_extents < max_recs_needed))
170 		extra_blocks += ocfs2_extend_meta_needed(et->et_root_el);
171 
172 	ret = ocfs2_reserve_new_metadata_blocks(osb, extra_blocks, meta_ac);
173 	if (ret) {
174 		mlog_errno(ret);
175 		goto out;
176 	}
177 
178 
179 	*credits += ocfs2_calc_extend_credits(osb->sb, et->et_root_el);
180 
181 	mlog(0, "reserve metadata_blocks: %d, data_clusters: %u, credits: %d\n",
182 	     extra_blocks, clusters_to_move, *credits);
183 out:
184 	if (ret) {
185 		if (*meta_ac) {
186 			ocfs2_free_alloc_context(*meta_ac);
187 			*meta_ac = NULL;
188 		}
189 	}
190 
191 	return ret;
192 }
193 
194 /*
195  * Using one journal handle to guarantee the data consistency in case
196  * crash happens anywhere.
197  *
198  *  XXX: defrag can end up with finishing partial extent as requested,
199  * due to not enough contiguous clusters can be found in allocator.
200  */
201 static int ocfs2_defrag_extent(struct ocfs2_move_extents_context *context,
202 			       u32 cpos, u32 phys_cpos, u32 *len, int ext_flags)
203 {
204 	int ret, credits = 0, extra_blocks = 0, partial = context->partial;
205 	handle_t *handle;
206 	struct inode *inode = context->inode;
207 	struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
208 	struct inode *tl_inode = osb->osb_tl_inode;
209 	struct ocfs2_refcount_tree *ref_tree = NULL;
210 	u32 new_phys_cpos, new_len;
211 	u64 phys_blkno = ocfs2_clusters_to_blocks(inode->i_sb, phys_cpos);
212 	int need_free = 0;
213 
214 	if ((ext_flags & OCFS2_EXT_REFCOUNTED) && *len) {
215 		BUG_ON(!ocfs2_is_refcount_inode(inode));
216 		BUG_ON(!context->refcount_loc);
217 
218 		ret = ocfs2_lock_refcount_tree(osb, context->refcount_loc, 1,
219 					       &ref_tree, NULL);
220 		if (ret) {
221 			mlog_errno(ret);
222 			return ret;
223 		}
224 
225 		ret = ocfs2_prepare_refcount_change_for_del(inode,
226 							context->refcount_loc,
227 							phys_blkno,
228 							*len,
229 							&credits,
230 							&extra_blocks);
231 		if (ret) {
232 			mlog_errno(ret);
233 			goto out;
234 		}
235 	}
236 
237 	ret = ocfs2_lock_meta_allocator_move_extents(inode, &context->et,
238 						*len, 1,
239 						&context->meta_ac,
240 						extra_blocks, &credits);
241 	if (ret) {
242 		mlog_errno(ret);
243 		goto out;
244 	}
245 
246 	/*
247 	 * should be using allocation reservation strategy there?
248 	 *
249 	 * if (context->data_ac)
250 	 *	context->data_ac->ac_resv = &OCFS2_I(inode)->ip_la_data_resv;
251 	 */
252 
253 	inode_lock(tl_inode);
254 
255 	if (ocfs2_truncate_log_needs_flush(osb)) {
256 		ret = __ocfs2_flush_truncate_log(osb);
257 		if (ret < 0) {
258 			mlog_errno(ret);
259 			goto out_unlock_mutex;
260 		}
261 	}
262 
263 	/*
264 	 * Make sure ocfs2_reserve_cluster is called after
265 	 * __ocfs2_flush_truncate_log, otherwise, dead lock may happen.
266 	 *
267 	 * If ocfs2_reserve_cluster is called
268 	 * before __ocfs2_flush_truncate_log, dead lock on global bitmap
269 	 * may happen.
270 	 *
271 	 */
272 	ret = ocfs2_reserve_clusters(osb, *len, &context->data_ac);
273 	if (ret) {
274 		mlog_errno(ret);
275 		goto out_unlock_mutex;
276 	}
277 
278 	handle = ocfs2_start_trans(osb, credits);
279 	if (IS_ERR(handle)) {
280 		ret = PTR_ERR(handle);
281 		mlog_errno(ret);
282 		goto out_unlock_mutex;
283 	}
284 
285 	ret = __ocfs2_claim_clusters(handle, context->data_ac, 1, *len,
286 				     &new_phys_cpos, &new_len);
287 	if (ret) {
288 		mlog_errno(ret);
289 		goto out_commit;
290 	}
291 
292 	/*
293 	 * allowing partial extent moving is kind of 'pros and cons', it makes
294 	 * whole defragmentation less likely to fail, on the contrary, the bad
295 	 * thing is it may make the fs even more fragmented after moving, let
296 	 * userspace make a good decision here.
297 	 */
298 	if (new_len != *len) {
299 		mlog(0, "len_claimed: %u, len: %u\n", new_len, *len);
300 		if (!partial) {
301 			context->range->me_flags &= ~OCFS2_MOVE_EXT_FL_COMPLETE;
302 			ret = -ENOSPC;
303 			need_free = 1;
304 			goto out_commit;
305 		}
306 	}
307 
308 	mlog(0, "cpos: %u, phys_cpos: %u, new_phys_cpos: %u\n", cpos,
309 	     phys_cpos, new_phys_cpos);
310 
311 	ret = __ocfs2_move_extent(handle, context, cpos, new_len, phys_cpos,
312 				  new_phys_cpos, ext_flags);
313 	if (ret)
314 		mlog_errno(ret);
315 
316 	if (partial && (new_len != *len))
317 		*len = new_len;
318 
319 	/*
320 	 * Here we should write the new page out first if we are
321 	 * in write-back mode.
322 	 */
323 	ret = ocfs2_cow_sync_writeback(inode->i_sb, context->inode, cpos, *len);
324 	if (ret)
325 		mlog_errno(ret);
326 
327 out_commit:
328 	if (need_free && context->data_ac) {
329 		struct ocfs2_alloc_context *data_ac = context->data_ac;
330 
331 		if (context->data_ac->ac_which == OCFS2_AC_USE_LOCAL)
332 			ocfs2_free_local_alloc_bits(osb, handle, data_ac,
333 					new_phys_cpos, new_len);
334 		else
335 			ocfs2_free_clusters(handle,
336 					data_ac->ac_inode,
337 					data_ac->ac_bh,
338 					ocfs2_clusters_to_blocks(osb->sb, new_phys_cpos),
339 					new_len);
340 	}
341 
342 	ocfs2_commit_trans(osb, handle);
343 
344 out_unlock_mutex:
345 	inode_unlock(tl_inode);
346 
347 	if (context->data_ac) {
348 		ocfs2_free_alloc_context(context->data_ac);
349 		context->data_ac = NULL;
350 	}
351 
352 	if (context->meta_ac) {
353 		ocfs2_free_alloc_context(context->meta_ac);
354 		context->meta_ac = NULL;
355 	}
356 
357 out:
358 	if (ref_tree)
359 		ocfs2_unlock_refcount_tree(osb, ref_tree, 1);
360 
361 	return ret;
362 }
363 
364 /*
365  * find the victim alloc group, where #blkno fits.
366  */
367 static int ocfs2_find_victim_alloc_group(struct inode *inode,
368 					 u64 vict_blkno,
369 					 int type, int slot,
370 					 int *vict_bit,
371 					 struct buffer_head **ret_bh)
372 {
373 	int ret, i, len, bits_per_unit = 0;
374 	u64 blkno;
375 	char namebuf[40];
376 
377 	struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
378 	struct buffer_head *ac_bh = NULL, *gd_bh = NULL;
379 	struct ocfs2_chain_list *cl;
380 	struct ocfs2_chain_rec *rec;
381 	struct ocfs2_dinode *ac_dinode;
382 	struct ocfs2_group_desc *bg;
383 
384 	len = ocfs2_sprintf_system_inode_name(namebuf, sizeof(namebuf), type, slot);
385 	ret = ocfs2_lookup_ino_from_name(osb->sys_root_inode, namebuf, len, &blkno);
386 
387 	if (ret) {
388 		ret = -ENOENT;
389 		goto out;
390 	}
391 
392 	ret = ocfs2_read_blocks_sync(osb, blkno, 1, &ac_bh);
393 	if (ret) {
394 		mlog_errno(ret);
395 		goto out;
396 	}
397 
398 	ac_dinode = (struct ocfs2_dinode *)ac_bh->b_data;
399 	cl = &(ac_dinode->id2.i_chain);
400 	rec = &(cl->cl_recs[0]);
401 
402 	if (type == GLOBAL_BITMAP_SYSTEM_INODE)
403 		bits_per_unit = osb->s_clustersize_bits -
404 					inode->i_sb->s_blocksize_bits;
405 	/*
406 	 * 'vict_blkno' was out of the valid range.
407 	 */
408 	if ((vict_blkno < le64_to_cpu(rec->c_blkno)) ||
409 	    (vict_blkno >= ((u64)le32_to_cpu(ac_dinode->id1.bitmap1.i_total) <<
410 				bits_per_unit))) {
411 		ret = -EINVAL;
412 		goto out;
413 	}
414 
415 	for (i = 0; i < le16_to_cpu(cl->cl_next_free_rec); i++) {
416 
417 		rec = &(cl->cl_recs[i]);
418 		if (!rec)
419 			continue;
420 
421 		bg = NULL;
422 
423 		do {
424 			if (!bg)
425 				blkno = le64_to_cpu(rec->c_blkno);
426 			else
427 				blkno = le64_to_cpu(bg->bg_next_group);
428 
429 			if (gd_bh) {
430 				brelse(gd_bh);
431 				gd_bh = NULL;
432 			}
433 
434 			ret = ocfs2_read_blocks_sync(osb, blkno, 1, &gd_bh);
435 			if (ret) {
436 				mlog_errno(ret);
437 				goto out;
438 			}
439 
440 			bg = (struct ocfs2_group_desc *)gd_bh->b_data;
441 
442 			if (vict_blkno < (le64_to_cpu(bg->bg_blkno) +
443 						(le16_to_cpu(bg->bg_bits) << bits_per_unit))) {
444 
445 				*ret_bh = gd_bh;
446 				*vict_bit = (vict_blkno - blkno) >>
447 							bits_per_unit;
448 				mlog(0, "find the victim group: #%llu, "
449 				     "total_bits: %u, vict_bit: %u\n",
450 				     blkno, le16_to_cpu(bg->bg_bits),
451 				     *vict_bit);
452 				goto out;
453 			}
454 
455 		} while (le64_to_cpu(bg->bg_next_group));
456 	}
457 
458 	ret = -EINVAL;
459 out:
460 	brelse(ac_bh);
461 
462 	/*
463 	 * caller has to release the gd_bh properly.
464 	 */
465 	return ret;
466 }
467 
468 /*
469  * XXX: helper to validate and adjust moving goal.
470  */
471 static int ocfs2_validate_and_adjust_move_goal(struct inode *inode,
472 					       struct ocfs2_move_extents *range)
473 {
474 	int ret, goal_bit = 0;
475 
476 	struct buffer_head *gd_bh = NULL;
477 	struct ocfs2_group_desc *bg;
478 	struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
479 	int c_to_b = 1 << (osb->s_clustersize_bits -
480 					inode->i_sb->s_blocksize_bits);
481 
482 	/*
483 	 * make goal become cluster aligned.
484 	 */
485 	range->me_goal = ocfs2_block_to_cluster_start(inode->i_sb,
486 						      range->me_goal);
487 	/*
488 	 * validate goal sits within global_bitmap, and return the victim
489 	 * group desc
490 	 */
491 	ret = ocfs2_find_victim_alloc_group(inode, range->me_goal,
492 					    GLOBAL_BITMAP_SYSTEM_INODE,
493 					    OCFS2_INVALID_SLOT,
494 					    &goal_bit, &gd_bh);
495 	if (ret)
496 		goto out;
497 
498 	bg = (struct ocfs2_group_desc *)gd_bh->b_data;
499 
500 	/*
501 	 * moving goal is not allowed to start with a group desc blok(#0 blk)
502 	 * let's compromise to the latter cluster.
503 	 */
504 	if (range->me_goal == le64_to_cpu(bg->bg_blkno))
505 		range->me_goal += c_to_b;
506 
507 	/*
508 	 * movement is not gonna cross two groups.
509 	 */
510 	if ((le16_to_cpu(bg->bg_bits) - goal_bit) * osb->s_clustersize <
511 								range->me_len) {
512 		ret = -EINVAL;
513 		goto out;
514 	}
515 	/*
516 	 * more exact validations/adjustments will be performed later during
517 	 * moving operation for each extent range.
518 	 */
519 	mlog(0, "extents get ready to be moved to #%llu block\n",
520 	     range->me_goal);
521 
522 out:
523 	brelse(gd_bh);
524 
525 	return ret;
526 }
527 
528 static void ocfs2_probe_alloc_group(struct inode *inode, struct buffer_head *bh,
529 				    int *goal_bit, u32 move_len, u32 max_hop,
530 				    u32 *phys_cpos)
531 {
532 	int i, used, last_free_bits = 0, base_bit = *goal_bit;
533 	struct ocfs2_group_desc *gd = (struct ocfs2_group_desc *)bh->b_data;
534 	u32 base_cpos = ocfs2_blocks_to_clusters(inode->i_sb,
535 						 le64_to_cpu(gd->bg_blkno));
536 
537 	for (i = base_bit; i < le16_to_cpu(gd->bg_bits); i++) {
538 
539 		used = ocfs2_test_bit(i, (unsigned long *)gd->bg_bitmap);
540 		if (used) {
541 			/*
542 			 * we even tried searching the free chunk by jumping
543 			 * a 'max_hop' distance, but still failed.
544 			 */
545 			if ((i - base_bit) > max_hop) {
546 				*phys_cpos = 0;
547 				break;
548 			}
549 
550 			if (last_free_bits)
551 				last_free_bits = 0;
552 
553 			continue;
554 		} else
555 			last_free_bits++;
556 
557 		if (last_free_bits == move_len) {
558 			i -= move_len;
559 			*goal_bit = i;
560 			*phys_cpos = base_cpos + i;
561 			break;
562 		}
563 	}
564 
565 	mlog(0, "found phys_cpos: %u to fit the wanted moving.\n", *phys_cpos);
566 }
567 
568 static int ocfs2_move_extent(struct ocfs2_move_extents_context *context,
569 			     u32 cpos, u32 phys_cpos, u32 *new_phys_cpos,
570 			     u32 len, int ext_flags)
571 {
572 	int ret, credits = 0, extra_blocks = 0, goal_bit = 0;
573 	handle_t *handle;
574 	struct inode *inode = context->inode;
575 	struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
576 	struct inode *tl_inode = osb->osb_tl_inode;
577 	struct inode *gb_inode = NULL;
578 	struct buffer_head *gb_bh = NULL;
579 	struct buffer_head *gd_bh = NULL;
580 	struct ocfs2_group_desc *gd;
581 	struct ocfs2_refcount_tree *ref_tree = NULL;
582 	u32 move_max_hop = ocfs2_blocks_to_clusters(inode->i_sb,
583 						    context->range->me_threshold);
584 	u64 phys_blkno, new_phys_blkno;
585 
586 	phys_blkno = ocfs2_clusters_to_blocks(inode->i_sb, phys_cpos);
587 
588 	if ((ext_flags & OCFS2_EXT_REFCOUNTED) && len) {
589 		BUG_ON(!ocfs2_is_refcount_inode(inode));
590 		BUG_ON(!context->refcount_loc);
591 
592 		ret = ocfs2_lock_refcount_tree(osb, context->refcount_loc, 1,
593 					       &ref_tree, NULL);
594 		if (ret) {
595 			mlog_errno(ret);
596 			return ret;
597 		}
598 
599 		ret = ocfs2_prepare_refcount_change_for_del(inode,
600 							context->refcount_loc,
601 							phys_blkno,
602 							len,
603 							&credits,
604 							&extra_blocks);
605 		if (ret) {
606 			mlog_errno(ret);
607 			goto out;
608 		}
609 	}
610 
611 	ret = ocfs2_lock_meta_allocator_move_extents(inode, &context->et,
612 						len, 1,
613 						&context->meta_ac,
614 						extra_blocks, &credits);
615 	if (ret) {
616 		mlog_errno(ret);
617 		goto out;
618 	}
619 
620 	/*
621 	 * need to count 2 extra credits for global_bitmap inode and
622 	 * group descriptor.
623 	 */
624 	credits += OCFS2_INODE_UPDATE_CREDITS + 1;
625 
626 	inode_lock(tl_inode);
627 
628 	/*
629 	 * ocfs2_move_extent() didn't reserve any clusters in lock_allocators()
630 	 * logic, while we still need to lock the global_bitmap.
631 	 */
632 	gb_inode = ocfs2_get_system_file_inode(osb, GLOBAL_BITMAP_SYSTEM_INODE,
633 					       OCFS2_INVALID_SLOT);
634 	if (!gb_inode) {
635 		mlog(ML_ERROR, "unable to get global_bitmap inode\n");
636 		ret = -EIO;
637 		goto out_unlock_tl_inode;
638 	}
639 
640 	inode_lock(gb_inode);
641 
642 	ret = ocfs2_inode_lock(gb_inode, &gb_bh, 1);
643 	if (ret) {
644 		mlog_errno(ret);
645 		goto out_unlock_gb_inode;
646 	}
647 
648 	handle = ocfs2_start_trans(osb, credits);
649 	if (IS_ERR(handle)) {
650 		ret = PTR_ERR(handle);
651 		mlog_errno(ret);
652 		goto out_unlock;
653 	}
654 
655 	new_phys_blkno = ocfs2_clusters_to_blocks(inode->i_sb, *new_phys_cpos);
656 	ret = ocfs2_find_victim_alloc_group(inode, new_phys_blkno,
657 					    GLOBAL_BITMAP_SYSTEM_INODE,
658 					    OCFS2_INVALID_SLOT,
659 					    &goal_bit, &gd_bh);
660 	if (ret) {
661 		mlog_errno(ret);
662 		goto out_commit;
663 	}
664 
665 	gd = (struct ocfs2_group_desc *)gd_bh->b_data;
666 	if (le16_to_cpu(gd->bg_free_bits_count) < len) {
667 		ret = -ENOSPC;
668 		goto out_commit;
669 	}
670 
671 	/*
672 	 * probe the victim cluster group to find a proper
673 	 * region to fit wanted movement, it even will perform
674 	 * a best-effort attempt by compromising to a threshold
675 	 * around the goal.
676 	 */
677 	ocfs2_probe_alloc_group(inode, gd_bh, &goal_bit, len, move_max_hop,
678 				new_phys_cpos);
679 	if (!*new_phys_cpos) {
680 		ret = -ENOSPC;
681 		goto out_commit;
682 	}
683 
684 	ret = __ocfs2_move_extent(handle, context, cpos, len, phys_cpos,
685 				  *new_phys_cpos, ext_flags);
686 	if (ret) {
687 		mlog_errno(ret);
688 		goto out_commit;
689 	}
690 
691 	ret = ocfs2_alloc_dinode_update_counts(gb_inode, handle, gb_bh, len,
692 					       le16_to_cpu(gd->bg_chain));
693 	if (ret) {
694 		mlog_errno(ret);
695 		goto out_commit;
696 	}
697 
698 	ret = ocfs2_block_group_set_bits(handle, gb_inode, gd, gd_bh,
699 					 goal_bit, len, 0, 0);
700 	if (ret) {
701 		ocfs2_rollback_alloc_dinode_counts(gb_inode, gb_bh, len,
702 					       le16_to_cpu(gd->bg_chain));
703 		mlog_errno(ret);
704 	}
705 
706 	/*
707 	 * Here we should write the new page out first if we are
708 	 * in write-back mode.
709 	 */
710 	ret = ocfs2_cow_sync_writeback(inode->i_sb, context->inode, cpos, len);
711 	if (ret)
712 		mlog_errno(ret);
713 
714 out_commit:
715 	ocfs2_commit_trans(osb, handle);
716 	brelse(gd_bh);
717 out_unlock:
718 	ocfs2_inode_unlock(gb_inode, 1);
719 out_unlock_gb_inode:
720 	inode_unlock(gb_inode);
721 	brelse(gb_bh);
722 	iput(gb_inode);
723 out_unlock_tl_inode:
724 	inode_unlock(tl_inode);
725 
726 out:
727 	if (context->meta_ac) {
728 		ocfs2_free_alloc_context(context->meta_ac);
729 		context->meta_ac = NULL;
730 	}
731 
732 	if (ref_tree)
733 		ocfs2_unlock_refcount_tree(osb, ref_tree, 1);
734 
735 	return ret;
736 }
737 
738 /*
739  * Helper to calculate the defraging length in one run according to threshold.
740  */
741 static void ocfs2_calc_extent_defrag_len(u32 *alloc_size, u32 *len_defraged,
742 					 u32 threshold, int *skip)
743 {
744 	if ((*alloc_size + *len_defraged) < threshold) {
745 		/*
746 		 * proceed defragmentation until we meet the thresh
747 		 */
748 		*len_defraged += *alloc_size;
749 	} else if (*len_defraged == 0) {
750 		/*
751 		 * XXX: skip a large extent.
752 		 */
753 		*skip = 1;
754 	} else {
755 		/*
756 		 * split this extent to coalesce with former pieces as
757 		 * to reach the threshold.
758 		 *
759 		 * we're done here with one cycle of defragmentation
760 		 * in a size of 'thresh', resetting 'len_defraged'
761 		 * forces a new defragmentation.
762 		 */
763 		*alloc_size = threshold - *len_defraged;
764 		*len_defraged = 0;
765 	}
766 }
767 
768 static int __ocfs2_move_extents_range(struct buffer_head *di_bh,
769 				struct ocfs2_move_extents_context *context)
770 {
771 	int ret = 0, flags, do_defrag, skip = 0;
772 	u32 cpos, phys_cpos, move_start, len_to_move, alloc_size;
773 	u32 len_defraged = 0, defrag_thresh = 0, new_phys_cpos = 0;
774 
775 	struct inode *inode = context->inode;
776 	struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
777 	struct ocfs2_move_extents *range = context->range;
778 	struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
779 
780 	if ((i_size_read(inode) == 0) || (range->me_len == 0))
781 		return 0;
782 
783 	if (OCFS2_I(inode)->ip_dyn_features & OCFS2_INLINE_DATA_FL)
784 		return 0;
785 
786 	context->refcount_loc = le64_to_cpu(di->i_refcount_loc);
787 
788 	ocfs2_init_dinode_extent_tree(&context->et, INODE_CACHE(inode), di_bh);
789 	ocfs2_init_dealloc_ctxt(&context->dealloc);
790 
791 	/*
792 	 * TO-DO XXX:
793 	 *
794 	 * - xattr extents.
795 	 */
796 
797 	do_defrag = context->auto_defrag;
798 
799 	/*
800 	 * extents moving happens in unit of clusters, for the sake
801 	 * of simplicity, we may ignore two clusters where 'byte_start'
802 	 * and 'byte_start + len' were within.
803 	 */
804 	move_start = ocfs2_clusters_for_bytes(osb->sb, range->me_start);
805 	len_to_move = (range->me_start + range->me_len) >>
806 						osb->s_clustersize_bits;
807 	if (len_to_move >= move_start)
808 		len_to_move -= move_start;
809 	else
810 		len_to_move = 0;
811 
812 	if (do_defrag) {
813 		defrag_thresh = range->me_threshold >> osb->s_clustersize_bits;
814 		if (defrag_thresh <= 1)
815 			goto done;
816 	} else
817 		new_phys_cpos = ocfs2_blocks_to_clusters(inode->i_sb,
818 							 range->me_goal);
819 
820 	mlog(0, "Inode: %llu, start: %llu, len: %llu, cstart: %u, clen: %u, "
821 	     "thresh: %u\n",
822 	     (unsigned long long)OCFS2_I(inode)->ip_blkno,
823 	     (unsigned long long)range->me_start,
824 	     (unsigned long long)range->me_len,
825 	     move_start, len_to_move, defrag_thresh);
826 
827 	cpos = move_start;
828 	while (len_to_move) {
829 		ret = ocfs2_get_clusters(inode, cpos, &phys_cpos, &alloc_size,
830 					 &flags);
831 		if (ret) {
832 			mlog_errno(ret);
833 			goto out;
834 		}
835 
836 		if (alloc_size > len_to_move)
837 			alloc_size = len_to_move;
838 
839 		/*
840 		 * XXX: how to deal with a hole:
841 		 *
842 		 * - skip the hole of course
843 		 * - force a new defragmentation
844 		 */
845 		if (!phys_cpos) {
846 			if (do_defrag)
847 				len_defraged = 0;
848 
849 			goto next;
850 		}
851 
852 		if (do_defrag) {
853 			ocfs2_calc_extent_defrag_len(&alloc_size, &len_defraged,
854 						     defrag_thresh, &skip);
855 			/*
856 			 * skip large extents
857 			 */
858 			if (skip) {
859 				skip = 0;
860 				goto next;
861 			}
862 
863 			mlog(0, "#Defrag: cpos: %u, phys_cpos: %u, "
864 			     "alloc_size: %u, len_defraged: %u\n",
865 			     cpos, phys_cpos, alloc_size, len_defraged);
866 
867 			ret = ocfs2_defrag_extent(context, cpos, phys_cpos,
868 						  &alloc_size, flags);
869 		} else {
870 			ret = ocfs2_move_extent(context, cpos, phys_cpos,
871 						&new_phys_cpos, alloc_size,
872 						flags);
873 
874 			new_phys_cpos += alloc_size;
875 		}
876 
877 		if (ret < 0) {
878 			mlog_errno(ret);
879 			goto out;
880 		}
881 		/*
882 		 * Invalidate extent cache after moving/defragging to prevent
883 		 * stale cached data with outdated extent flags.
884 		 */
885 		ocfs2_extent_map_trunc(inode, cpos);
886 
887 		context->clusters_moved += alloc_size;
888 next:
889 		cpos += alloc_size;
890 		len_to_move -= alloc_size;
891 	}
892 
893 done:
894 	range->me_flags |= OCFS2_MOVE_EXT_FL_COMPLETE;
895 
896 out:
897 	range->me_moved_len = ocfs2_clusters_to_bytes(osb->sb,
898 						      context->clusters_moved);
899 	range->me_new_offset = ocfs2_clusters_to_bytes(osb->sb,
900 						       context->new_phys_cpos);
901 
902 	ocfs2_schedule_truncate_log_flush(osb, 1);
903 	ocfs2_run_deallocs(osb, &context->dealloc);
904 
905 	return ret;
906 }
907 
908 static int ocfs2_move_extents(struct ocfs2_move_extents_context *context)
909 {
910 	int status;
911 	handle_t *handle;
912 	struct inode *inode = context->inode;
913 	struct ocfs2_dinode *di;
914 	struct buffer_head *di_bh = NULL;
915 	struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
916 
917 	if (unlikely(ocfs2_emergency_state(osb)))
918 		return -EROFS;
919 
920 	inode_lock(inode);
921 
922 	/*
923 	 * This prevents concurrent writes from other nodes
924 	 */
925 	status = ocfs2_rw_lock(inode, 1);
926 	if (status) {
927 		mlog_errno(status);
928 		goto out;
929 	}
930 
931 	status = ocfs2_inode_lock(inode, &di_bh, 1);
932 	if (status) {
933 		mlog_errno(status);
934 		goto out_rw_unlock;
935 	}
936 
937 	/*
938 	 * remember ip_xattr_sem also needs to be held if necessary
939 	 */
940 	down_write(&OCFS2_I(inode)->ip_alloc_sem);
941 
942 	status = __ocfs2_move_extents_range(di_bh, context);
943 
944 	up_write(&OCFS2_I(inode)->ip_alloc_sem);
945 	if (status) {
946 		mlog_errno(status);
947 		goto out_inode_unlock;
948 	}
949 
950 	/*
951 	 * We update ctime for these changes
952 	 */
953 	handle = ocfs2_start_trans(osb, OCFS2_INODE_UPDATE_CREDITS);
954 	if (IS_ERR(handle)) {
955 		status = PTR_ERR(handle);
956 		mlog_errno(status);
957 		goto out_inode_unlock;
958 	}
959 
960 	status = ocfs2_journal_access_di(handle, INODE_CACHE(inode), di_bh,
961 					 OCFS2_JOURNAL_ACCESS_WRITE);
962 	if (status) {
963 		mlog_errno(status);
964 		goto out_commit;
965 	}
966 
967 	di = (struct ocfs2_dinode *)di_bh->b_data;
968 	inode_set_ctime_current(inode);
969 	di->i_ctime = cpu_to_le64(inode_get_ctime_sec(inode));
970 	di->i_ctime_nsec = cpu_to_le32(inode_get_ctime_nsec(inode));
971 	ocfs2_update_inode_fsync_trans(handle, inode, 0);
972 
973 	ocfs2_journal_dirty(handle, di_bh);
974 
975 out_commit:
976 	ocfs2_commit_trans(osb, handle);
977 
978 out_inode_unlock:
979 	brelse(di_bh);
980 	ocfs2_inode_unlock(inode, 1);
981 out_rw_unlock:
982 	ocfs2_rw_unlock(inode, 1);
983 out:
984 	inode_unlock(inode);
985 
986 	return status;
987 }
988 
989 int ocfs2_ioctl_move_extents(struct file *filp, void __user *argp)
990 {
991 	int status;
992 
993 	struct inode *inode = file_inode(filp);
994 	struct ocfs2_move_extents range;
995 	struct ocfs2_move_extents_context *context;
996 
997 	if (!argp)
998 		return -EINVAL;
999 
1000 	status = mnt_want_write_file(filp);
1001 	if (status)
1002 		return status;
1003 
1004 	if ((!S_ISREG(inode->i_mode)) || !(filp->f_mode & FMODE_WRITE)) {
1005 		status = -EPERM;
1006 		goto out_drop;
1007 	}
1008 
1009 	if (inode->i_flags & (S_IMMUTABLE|S_APPEND)) {
1010 		status = -EPERM;
1011 		goto out_drop;
1012 	}
1013 
1014 	context = kzalloc_obj(struct ocfs2_move_extents_context, GFP_NOFS);
1015 	if (!context) {
1016 		status = -ENOMEM;
1017 		mlog_errno(status);
1018 		goto out_drop;
1019 	}
1020 
1021 	context->inode = inode;
1022 	context->file = filp;
1023 
1024 	if (copy_from_user(&range, argp, sizeof(range))) {
1025 		status = -EFAULT;
1026 		goto out_free;
1027 	}
1028 
1029 	if (range.me_start > i_size_read(inode)) {
1030 		status = -EINVAL;
1031 		goto out_free;
1032 	}
1033 
1034 	if (range.me_start + range.me_len > i_size_read(inode))
1035 			range.me_len = i_size_read(inode) - range.me_start;
1036 
1037 	context->range = &range;
1038 
1039 	/*
1040 	 * ok, the default threshold for the defragmentation
1041 	 * is 1M, since our maximum clustersize was 1M also.
1042 	 * any thought?
1043 	 */
1044 	if (!range.me_threshold)
1045 		range.me_threshold = 1024 * 1024;
1046 
1047 	if (range.me_threshold > i_size_read(inode))
1048 		range.me_threshold = i_size_read(inode);
1049 
1050 	if (range.me_flags & ~(OCFS2_MOVE_EXT_FL_AUTO_DEFRAG |
1051 			       OCFS2_MOVE_EXT_FL_PART_DEFRAG)) {
1052 		status = -EINVAL;
1053 		goto out_free;
1054 	}
1055 
1056 	if (range.me_flags & OCFS2_MOVE_EXT_FL_AUTO_DEFRAG) {
1057 		context->auto_defrag = 1;
1058 
1059 		if (range.me_flags & OCFS2_MOVE_EXT_FL_PART_DEFRAG)
1060 			context->partial = 1;
1061 	} else {
1062 		/*
1063 		 * first best-effort attempt to validate and adjust the goal
1064 		 * (physical address in block), while it can't guarantee later
1065 		 * operation can succeed all the time since global_bitmap may
1066 		 * change a bit over time.
1067 		 */
1068 
1069 		status = ocfs2_validate_and_adjust_move_goal(inode, &range);
1070 		if (status)
1071 			goto out_copy;
1072 	}
1073 
1074 	status = ocfs2_move_extents(context);
1075 	if (status)
1076 		mlog_errno(status);
1077 out_copy:
1078 	/*
1079 	 * movement/defragmentation may end up being partially completed,
1080 	 * that's the reason why we need to return userspace the finished
1081 	 * length and new_offset even if failure happens somewhere.
1082 	 */
1083 	if (copy_to_user(argp, &range, sizeof(range)))
1084 		status = -EFAULT;
1085 
1086 out_free:
1087 	kfree(context);
1088 out_drop:
1089 	mnt_drop_write_file(filp);
1090 
1091 	return status;
1092 }
1093