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