xref: /openbmc/linux/fs/ocfs2/suballoc.c (revision 0ad53fe3)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * suballoc.c
4  *
5  * metadata alloc and free
6  * Inspired by ext3 block groups.
7  *
8  * Copyright (C) 2002, 2004 Oracle.  All rights reserved.
9  */
10 
11 #include <linux/fs.h>
12 #include <linux/types.h>
13 #include <linux/slab.h>
14 #include <linux/highmem.h>
15 
16 #include <cluster/masklog.h>
17 
18 #include "ocfs2.h"
19 
20 #include "alloc.h"
21 #include "blockcheck.h"
22 #include "dlmglue.h"
23 #include "inode.h"
24 #include "journal.h"
25 #include "localalloc.h"
26 #include "suballoc.h"
27 #include "super.h"
28 #include "sysfile.h"
29 #include "uptodate.h"
30 #include "ocfs2_trace.h"
31 
32 #include "buffer_head_io.h"
33 
34 #define NOT_ALLOC_NEW_GROUP		0
35 #define ALLOC_NEW_GROUP			0x1
36 #define ALLOC_GROUPS_FROM_GLOBAL	0x2
37 
38 #define OCFS2_MAX_TO_STEAL		1024
39 
40 struct ocfs2_suballoc_result {
41 	u64		sr_bg_blkno;	/* The bg we allocated from.  Set
42 					   to 0 when a block group is
43 					   contiguous. */
44 	u64		sr_bg_stable_blkno; /*
45 					     * Doesn't change, always
46 					     * set to target block
47 					     * group descriptor
48 					     * block.
49 					     */
50 	u64		sr_blkno;	/* The first allocated block */
51 	unsigned int	sr_bit_offset;	/* The bit in the bg */
52 	unsigned int	sr_bits;	/* How many bits we claimed */
53 };
54 
55 static u64 ocfs2_group_from_res(struct ocfs2_suballoc_result *res)
56 {
57 	if (res->sr_blkno == 0)
58 		return 0;
59 
60 	if (res->sr_bg_blkno)
61 		return res->sr_bg_blkno;
62 
63 	return ocfs2_which_suballoc_group(res->sr_blkno, res->sr_bit_offset);
64 }
65 
66 static inline u16 ocfs2_find_victim_chain(struct ocfs2_chain_list *cl);
67 static int ocfs2_block_group_fill(handle_t *handle,
68 				  struct inode *alloc_inode,
69 				  struct buffer_head *bg_bh,
70 				  u64 group_blkno,
71 				  unsigned int group_clusters,
72 				  u16 my_chain,
73 				  struct ocfs2_chain_list *cl);
74 static int ocfs2_block_group_alloc(struct ocfs2_super *osb,
75 				   struct inode *alloc_inode,
76 				   struct buffer_head *bh,
77 				   u64 max_block,
78 				   u64 *last_alloc_group,
79 				   int flags);
80 
81 static int ocfs2_cluster_group_search(struct inode *inode,
82 				      struct buffer_head *group_bh,
83 				      u32 bits_wanted, u32 min_bits,
84 				      u64 max_block,
85 				      struct ocfs2_suballoc_result *res);
86 static int ocfs2_block_group_search(struct inode *inode,
87 				    struct buffer_head *group_bh,
88 				    u32 bits_wanted, u32 min_bits,
89 				    u64 max_block,
90 				    struct ocfs2_suballoc_result *res);
91 static int ocfs2_claim_suballoc_bits(struct ocfs2_alloc_context *ac,
92 				     handle_t *handle,
93 				     u32 bits_wanted,
94 				     u32 min_bits,
95 				     struct ocfs2_suballoc_result *res);
96 static int ocfs2_test_bg_bit_allocatable(struct buffer_head *bg_bh,
97 					 int nr);
98 static int ocfs2_relink_block_group(handle_t *handle,
99 				    struct inode *alloc_inode,
100 				    struct buffer_head *fe_bh,
101 				    struct buffer_head *bg_bh,
102 				    struct buffer_head *prev_bg_bh,
103 				    u16 chain);
104 static inline int ocfs2_block_group_reasonably_empty(struct ocfs2_group_desc *bg,
105 						     u32 wanted);
106 static inline u32 ocfs2_desc_bitmap_to_cluster_off(struct inode *inode,
107 						   u64 bg_blkno,
108 						   u16 bg_bit_off);
109 static inline void ocfs2_block_to_cluster_group(struct inode *inode,
110 						u64 data_blkno,
111 						u64 *bg_blkno,
112 						u16 *bg_bit_off);
113 static int ocfs2_reserve_clusters_with_limit(struct ocfs2_super *osb,
114 					     u32 bits_wanted, u64 max_block,
115 					     int flags,
116 					     struct ocfs2_alloc_context **ac);
117 
118 void ocfs2_free_ac_resource(struct ocfs2_alloc_context *ac)
119 {
120 	struct inode *inode = ac->ac_inode;
121 
122 	if (inode) {
123 		if (ac->ac_which != OCFS2_AC_USE_LOCAL)
124 			ocfs2_inode_unlock(inode, 1);
125 
126 		inode_unlock(inode);
127 
128 		iput(inode);
129 		ac->ac_inode = NULL;
130 	}
131 	brelse(ac->ac_bh);
132 	ac->ac_bh = NULL;
133 	ac->ac_resv = NULL;
134 	kfree(ac->ac_find_loc_priv);
135 	ac->ac_find_loc_priv = NULL;
136 }
137 
138 void ocfs2_free_alloc_context(struct ocfs2_alloc_context *ac)
139 {
140 	ocfs2_free_ac_resource(ac);
141 	kfree(ac);
142 }
143 
144 static u32 ocfs2_bits_per_group(struct ocfs2_chain_list *cl)
145 {
146 	return (u32)le16_to_cpu(cl->cl_cpg) * (u32)le16_to_cpu(cl->cl_bpc);
147 }
148 
149 #define do_error(fmt, ...)						\
150 do {									\
151 	if (resize)							\
152 		mlog(ML_ERROR, fmt, ##__VA_ARGS__);			\
153 	else								\
154 		return ocfs2_error(sb, fmt, ##__VA_ARGS__);		\
155 } while (0)
156 
157 static int ocfs2_validate_gd_self(struct super_block *sb,
158 				  struct buffer_head *bh,
159 				  int resize)
160 {
161 	struct ocfs2_group_desc *gd = (struct ocfs2_group_desc *)bh->b_data;
162 
163 	if (!OCFS2_IS_VALID_GROUP_DESC(gd)) {
164 		do_error("Group descriptor #%llu has bad signature %.*s\n",
165 			 (unsigned long long)bh->b_blocknr, 7,
166 			 gd->bg_signature);
167 	}
168 
169 	if (le64_to_cpu(gd->bg_blkno) != bh->b_blocknr) {
170 		do_error("Group descriptor #%llu has an invalid bg_blkno of %llu\n",
171 			 (unsigned long long)bh->b_blocknr,
172 			 (unsigned long long)le64_to_cpu(gd->bg_blkno));
173 	}
174 
175 	if (le32_to_cpu(gd->bg_generation) != OCFS2_SB(sb)->fs_generation) {
176 		do_error("Group descriptor #%llu has an invalid fs_generation of #%u\n",
177 			 (unsigned long long)bh->b_blocknr,
178 			 le32_to_cpu(gd->bg_generation));
179 	}
180 
181 	if (le16_to_cpu(gd->bg_free_bits_count) > le16_to_cpu(gd->bg_bits)) {
182 		do_error("Group descriptor #%llu has bit count %u but claims that %u are free\n",
183 			 (unsigned long long)bh->b_blocknr,
184 			 le16_to_cpu(gd->bg_bits),
185 			 le16_to_cpu(gd->bg_free_bits_count));
186 	}
187 
188 	if (le16_to_cpu(gd->bg_bits) > (8 * le16_to_cpu(gd->bg_size))) {
189 		do_error("Group descriptor #%llu has bit count %u but max bitmap bits of %u\n",
190 			 (unsigned long long)bh->b_blocknr,
191 			 le16_to_cpu(gd->bg_bits),
192 			 8 * le16_to_cpu(gd->bg_size));
193 	}
194 
195 	return 0;
196 }
197 
198 static int ocfs2_validate_gd_parent(struct super_block *sb,
199 				    struct ocfs2_dinode *di,
200 				    struct buffer_head *bh,
201 				    int resize)
202 {
203 	unsigned int max_bits;
204 	struct ocfs2_group_desc *gd = (struct ocfs2_group_desc *)bh->b_data;
205 
206 	if (di->i_blkno != gd->bg_parent_dinode) {
207 		do_error("Group descriptor #%llu has bad parent pointer (%llu, expected %llu)\n",
208 			 (unsigned long long)bh->b_blocknr,
209 			 (unsigned long long)le64_to_cpu(gd->bg_parent_dinode),
210 			 (unsigned long long)le64_to_cpu(di->i_blkno));
211 	}
212 
213 	max_bits = le16_to_cpu(di->id2.i_chain.cl_cpg) * le16_to_cpu(di->id2.i_chain.cl_bpc);
214 	if (le16_to_cpu(gd->bg_bits) > max_bits) {
215 		do_error("Group descriptor #%llu has bit count of %u\n",
216 			 (unsigned long long)bh->b_blocknr,
217 			 le16_to_cpu(gd->bg_bits));
218 	}
219 
220 	/* In resize, we may meet the case bg_chain == cl_next_free_rec. */
221 	if ((le16_to_cpu(gd->bg_chain) >
222 	     le16_to_cpu(di->id2.i_chain.cl_next_free_rec)) ||
223 	    ((le16_to_cpu(gd->bg_chain) ==
224 	     le16_to_cpu(di->id2.i_chain.cl_next_free_rec)) && !resize)) {
225 		do_error("Group descriptor #%llu has bad chain %u\n",
226 			 (unsigned long long)bh->b_blocknr,
227 			 le16_to_cpu(gd->bg_chain));
228 	}
229 
230 	return 0;
231 }
232 
233 #undef do_error
234 
235 /*
236  * This version only prints errors.  It does not fail the filesystem, and
237  * exists only for resize.
238  */
239 int ocfs2_check_group_descriptor(struct super_block *sb,
240 				 struct ocfs2_dinode *di,
241 				 struct buffer_head *bh)
242 {
243 	int rc;
244 	struct ocfs2_group_desc *gd = (struct ocfs2_group_desc *)bh->b_data;
245 
246 	BUG_ON(!buffer_uptodate(bh));
247 
248 	/*
249 	 * If the ecc fails, we return the error but otherwise
250 	 * leave the filesystem running.  We know any error is
251 	 * local to this block.
252 	 */
253 	rc = ocfs2_validate_meta_ecc(sb, bh->b_data, &gd->bg_check);
254 	if (rc) {
255 		mlog(ML_ERROR,
256 		     "Checksum failed for group descriptor %llu\n",
257 		     (unsigned long long)bh->b_blocknr);
258 	} else
259 		rc = ocfs2_validate_gd_self(sb, bh, 1);
260 	if (!rc)
261 		rc = ocfs2_validate_gd_parent(sb, di, bh, 1);
262 
263 	return rc;
264 }
265 
266 static int ocfs2_validate_group_descriptor(struct super_block *sb,
267 					   struct buffer_head *bh)
268 {
269 	int rc;
270 	struct ocfs2_group_desc *gd = (struct ocfs2_group_desc *)bh->b_data;
271 
272 	trace_ocfs2_validate_group_descriptor(
273 					(unsigned long long)bh->b_blocknr);
274 
275 	BUG_ON(!buffer_uptodate(bh));
276 
277 	/*
278 	 * If the ecc fails, we return the error but otherwise
279 	 * leave the filesystem running.  We know any error is
280 	 * local to this block.
281 	 */
282 	rc = ocfs2_validate_meta_ecc(sb, bh->b_data, &gd->bg_check);
283 	if (rc)
284 		return rc;
285 
286 	/*
287 	 * Errors after here are fatal.
288 	 */
289 
290 	return ocfs2_validate_gd_self(sb, bh, 0);
291 }
292 
293 int ocfs2_read_group_descriptor(struct inode *inode, struct ocfs2_dinode *di,
294 				u64 gd_blkno, struct buffer_head **bh)
295 {
296 	int rc;
297 	struct buffer_head *tmp = *bh;
298 
299 	rc = ocfs2_read_block(INODE_CACHE(inode), gd_blkno, &tmp,
300 			      ocfs2_validate_group_descriptor);
301 	if (rc)
302 		goto out;
303 
304 	rc = ocfs2_validate_gd_parent(inode->i_sb, di, tmp, 0);
305 	if (rc) {
306 		brelse(tmp);
307 		goto out;
308 	}
309 
310 	/* If ocfs2_read_block() got us a new bh, pass it up. */
311 	if (!*bh)
312 		*bh = tmp;
313 
314 out:
315 	return rc;
316 }
317 
318 static void ocfs2_bg_discontig_add_extent(struct ocfs2_super *osb,
319 					  struct ocfs2_group_desc *bg,
320 					  struct ocfs2_chain_list *cl,
321 					  u64 p_blkno, unsigned int clusters)
322 {
323 	struct ocfs2_extent_list *el = &bg->bg_list;
324 	struct ocfs2_extent_rec *rec;
325 
326 	BUG_ON(!ocfs2_supports_discontig_bg(osb));
327 	if (!el->l_next_free_rec)
328 		el->l_count = cpu_to_le16(ocfs2_extent_recs_per_gd(osb->sb));
329 	rec = &el->l_recs[le16_to_cpu(el->l_next_free_rec)];
330 	rec->e_blkno = cpu_to_le64(p_blkno);
331 	rec->e_cpos = cpu_to_le32(le16_to_cpu(bg->bg_bits) /
332 				  le16_to_cpu(cl->cl_bpc));
333 	rec->e_leaf_clusters = cpu_to_le16(clusters);
334 	le16_add_cpu(&bg->bg_bits, clusters * le16_to_cpu(cl->cl_bpc));
335 	le16_add_cpu(&bg->bg_free_bits_count,
336 		     clusters * le16_to_cpu(cl->cl_bpc));
337 	le16_add_cpu(&el->l_next_free_rec, 1);
338 }
339 
340 static int ocfs2_block_group_fill(handle_t *handle,
341 				  struct inode *alloc_inode,
342 				  struct buffer_head *bg_bh,
343 				  u64 group_blkno,
344 				  unsigned int group_clusters,
345 				  u16 my_chain,
346 				  struct ocfs2_chain_list *cl)
347 {
348 	int status = 0;
349 	struct ocfs2_super *osb = OCFS2_SB(alloc_inode->i_sb);
350 	struct ocfs2_group_desc *bg = (struct ocfs2_group_desc *) bg_bh->b_data;
351 	struct super_block * sb = alloc_inode->i_sb;
352 
353 	if (((unsigned long long) bg_bh->b_blocknr) != group_blkno) {
354 		status = ocfs2_error(alloc_inode->i_sb,
355 				     "group block (%llu) != b_blocknr (%llu)\n",
356 				     (unsigned long long)group_blkno,
357 				     (unsigned long long) bg_bh->b_blocknr);
358 		goto bail;
359 	}
360 
361 	status = ocfs2_journal_access_gd(handle,
362 					 INODE_CACHE(alloc_inode),
363 					 bg_bh,
364 					 OCFS2_JOURNAL_ACCESS_CREATE);
365 	if (status < 0) {
366 		mlog_errno(status);
367 		goto bail;
368 	}
369 
370 	memset(bg, 0, sb->s_blocksize);
371 	strcpy(bg->bg_signature, OCFS2_GROUP_DESC_SIGNATURE);
372 	bg->bg_generation = cpu_to_le32(osb->fs_generation);
373 	bg->bg_size = cpu_to_le16(ocfs2_group_bitmap_size(sb, 1,
374 						osb->s_feature_incompat));
375 	bg->bg_chain = cpu_to_le16(my_chain);
376 	bg->bg_next_group = cl->cl_recs[my_chain].c_blkno;
377 	bg->bg_parent_dinode = cpu_to_le64(OCFS2_I(alloc_inode)->ip_blkno);
378 	bg->bg_blkno = cpu_to_le64(group_blkno);
379 	if (group_clusters == le16_to_cpu(cl->cl_cpg))
380 		bg->bg_bits = cpu_to_le16(ocfs2_bits_per_group(cl));
381 	else
382 		ocfs2_bg_discontig_add_extent(osb, bg, cl, group_blkno,
383 					      group_clusters);
384 
385 	/* set the 1st bit in the bitmap to account for the descriptor block */
386 	ocfs2_set_bit(0, (unsigned long *)bg->bg_bitmap);
387 	bg->bg_free_bits_count = cpu_to_le16(le16_to_cpu(bg->bg_bits) - 1);
388 
389 	ocfs2_journal_dirty(handle, bg_bh);
390 
391 	/* There is no need to zero out or otherwise initialize the
392 	 * other blocks in a group - All valid FS metadata in a block
393 	 * group stores the superblock fs_generation value at
394 	 * allocation time. */
395 
396 bail:
397 	if (status)
398 		mlog_errno(status);
399 	return status;
400 }
401 
402 static inline u16 ocfs2_find_smallest_chain(struct ocfs2_chain_list *cl)
403 {
404 	u16 curr, best;
405 
406 	best = curr = 0;
407 	while (curr < le16_to_cpu(cl->cl_count)) {
408 		if (le32_to_cpu(cl->cl_recs[best].c_total) >
409 		    le32_to_cpu(cl->cl_recs[curr].c_total))
410 			best = curr;
411 		curr++;
412 	}
413 	return best;
414 }
415 
416 static struct buffer_head *
417 ocfs2_block_group_alloc_contig(struct ocfs2_super *osb, handle_t *handle,
418 			       struct inode *alloc_inode,
419 			       struct ocfs2_alloc_context *ac,
420 			       struct ocfs2_chain_list *cl)
421 {
422 	int status;
423 	u32 bit_off, num_bits;
424 	u64 bg_blkno;
425 	struct buffer_head *bg_bh;
426 	unsigned int alloc_rec = ocfs2_find_smallest_chain(cl);
427 
428 	status = ocfs2_claim_clusters(handle, ac,
429 				      le16_to_cpu(cl->cl_cpg), &bit_off,
430 				      &num_bits);
431 	if (status < 0) {
432 		if (status != -ENOSPC)
433 			mlog_errno(status);
434 		goto bail;
435 	}
436 
437 	/* setup the group */
438 	bg_blkno = ocfs2_clusters_to_blocks(osb->sb, bit_off);
439 	trace_ocfs2_block_group_alloc_contig(
440 	     (unsigned long long)bg_blkno, alloc_rec);
441 
442 	bg_bh = sb_getblk(osb->sb, bg_blkno);
443 	if (!bg_bh) {
444 		status = -ENOMEM;
445 		mlog_errno(status);
446 		goto bail;
447 	}
448 	ocfs2_set_new_buffer_uptodate(INODE_CACHE(alloc_inode), bg_bh);
449 
450 	status = ocfs2_block_group_fill(handle, alloc_inode, bg_bh,
451 					bg_blkno, num_bits, alloc_rec, cl);
452 	if (status < 0) {
453 		brelse(bg_bh);
454 		mlog_errno(status);
455 	}
456 
457 bail:
458 	return status ? ERR_PTR(status) : bg_bh;
459 }
460 
461 static int ocfs2_block_group_claim_bits(struct ocfs2_super *osb,
462 					handle_t *handle,
463 					struct ocfs2_alloc_context *ac,
464 					unsigned int min_bits,
465 					u32 *bit_off, u32 *num_bits)
466 {
467 	int status = 0;
468 
469 	while (min_bits) {
470 		status = ocfs2_claim_clusters(handle, ac, min_bits,
471 					      bit_off, num_bits);
472 		if (status != -ENOSPC)
473 			break;
474 
475 		min_bits >>= 1;
476 	}
477 
478 	return status;
479 }
480 
481 static int ocfs2_block_group_grow_discontig(handle_t *handle,
482 					    struct inode *alloc_inode,
483 					    struct buffer_head *bg_bh,
484 					    struct ocfs2_alloc_context *ac,
485 					    struct ocfs2_chain_list *cl,
486 					    unsigned int min_bits)
487 {
488 	int status;
489 	struct ocfs2_super *osb = OCFS2_SB(alloc_inode->i_sb);
490 	struct ocfs2_group_desc *bg =
491 		(struct ocfs2_group_desc *)bg_bh->b_data;
492 	unsigned int needed = le16_to_cpu(cl->cl_cpg) -
493 			 le16_to_cpu(bg->bg_bits) / le16_to_cpu(cl->cl_bpc);
494 	u32 p_cpos, clusters;
495 	u64 p_blkno;
496 	struct ocfs2_extent_list *el = &bg->bg_list;
497 
498 	status = ocfs2_journal_access_gd(handle,
499 					 INODE_CACHE(alloc_inode),
500 					 bg_bh,
501 					 OCFS2_JOURNAL_ACCESS_CREATE);
502 	if (status < 0) {
503 		mlog_errno(status);
504 		goto bail;
505 	}
506 
507 	while ((needed > 0) && (le16_to_cpu(el->l_next_free_rec) <
508 				le16_to_cpu(el->l_count))) {
509 		if (min_bits > needed)
510 			min_bits = needed;
511 		status = ocfs2_block_group_claim_bits(osb, handle, ac,
512 						      min_bits, &p_cpos,
513 						      &clusters);
514 		if (status < 0) {
515 			if (status != -ENOSPC)
516 				mlog_errno(status);
517 			goto bail;
518 		}
519 		p_blkno = ocfs2_clusters_to_blocks(osb->sb, p_cpos);
520 		ocfs2_bg_discontig_add_extent(osb, bg, cl, p_blkno,
521 					      clusters);
522 
523 		min_bits = clusters;
524 		needed = le16_to_cpu(cl->cl_cpg) -
525 			 le16_to_cpu(bg->bg_bits) / le16_to_cpu(cl->cl_bpc);
526 	}
527 
528 	if (needed > 0) {
529 		/*
530 		 * We have used up all the extent rec but can't fill up
531 		 * the cpg. So bail out.
532 		 */
533 		status = -ENOSPC;
534 		goto bail;
535 	}
536 
537 	ocfs2_journal_dirty(handle, bg_bh);
538 
539 bail:
540 	return status;
541 }
542 
543 static void ocfs2_bg_alloc_cleanup(handle_t *handle,
544 				   struct ocfs2_alloc_context *cluster_ac,
545 				   struct inode *alloc_inode,
546 				   struct buffer_head *bg_bh)
547 {
548 	int i, ret;
549 	struct ocfs2_group_desc *bg;
550 	struct ocfs2_extent_list *el;
551 	struct ocfs2_extent_rec *rec;
552 
553 	if (!bg_bh)
554 		return;
555 
556 	bg = (struct ocfs2_group_desc *)bg_bh->b_data;
557 	el = &bg->bg_list;
558 	for (i = 0; i < le16_to_cpu(el->l_next_free_rec); i++) {
559 		rec = &el->l_recs[i];
560 		ret = ocfs2_free_clusters(handle, cluster_ac->ac_inode,
561 					  cluster_ac->ac_bh,
562 					  le64_to_cpu(rec->e_blkno),
563 					  le16_to_cpu(rec->e_leaf_clusters));
564 		if (ret)
565 			mlog_errno(ret);
566 		/* Try all the clusters to free */
567 	}
568 
569 	ocfs2_remove_from_cache(INODE_CACHE(alloc_inode), bg_bh);
570 	brelse(bg_bh);
571 }
572 
573 static struct buffer_head *
574 ocfs2_block_group_alloc_discontig(handle_t *handle,
575 				  struct inode *alloc_inode,
576 				  struct ocfs2_alloc_context *ac,
577 				  struct ocfs2_chain_list *cl)
578 {
579 	int status;
580 	u32 bit_off, num_bits;
581 	u64 bg_blkno;
582 	unsigned int min_bits = le16_to_cpu(cl->cl_cpg) >> 1;
583 	struct buffer_head *bg_bh = NULL;
584 	unsigned int alloc_rec = ocfs2_find_smallest_chain(cl);
585 	struct ocfs2_super *osb = OCFS2_SB(alloc_inode->i_sb);
586 
587 	if (!ocfs2_supports_discontig_bg(osb)) {
588 		status = -ENOSPC;
589 		goto bail;
590 	}
591 
592 	status = ocfs2_extend_trans(handle,
593 				    ocfs2_calc_bg_discontig_credits(osb->sb));
594 	if (status) {
595 		mlog_errno(status);
596 		goto bail;
597 	}
598 
599 	/*
600 	 * We're going to be grabbing from multiple cluster groups.
601 	 * We don't have enough credits to relink them all, and the
602 	 * cluster groups will be staying in cache for the duration of
603 	 * this operation.
604 	 */
605 	ac->ac_disable_chain_relink = 1;
606 
607 	/* Claim the first region */
608 	status = ocfs2_block_group_claim_bits(osb, handle, ac, min_bits,
609 					      &bit_off, &num_bits);
610 	if (status < 0) {
611 		if (status != -ENOSPC)
612 			mlog_errno(status);
613 		goto bail;
614 	}
615 	min_bits = num_bits;
616 
617 	/* setup the group */
618 	bg_blkno = ocfs2_clusters_to_blocks(osb->sb, bit_off);
619 	trace_ocfs2_block_group_alloc_discontig(
620 				(unsigned long long)bg_blkno, alloc_rec);
621 
622 	bg_bh = sb_getblk(osb->sb, bg_blkno);
623 	if (!bg_bh) {
624 		status = -ENOMEM;
625 		mlog_errno(status);
626 		goto bail;
627 	}
628 	ocfs2_set_new_buffer_uptodate(INODE_CACHE(alloc_inode), bg_bh);
629 
630 	status = ocfs2_block_group_fill(handle, alloc_inode, bg_bh,
631 					bg_blkno, num_bits, alloc_rec, cl);
632 	if (status < 0) {
633 		mlog_errno(status);
634 		goto bail;
635 	}
636 
637 	status = ocfs2_block_group_grow_discontig(handle, alloc_inode,
638 						  bg_bh, ac, cl, min_bits);
639 	if (status)
640 		mlog_errno(status);
641 
642 bail:
643 	if (status)
644 		ocfs2_bg_alloc_cleanup(handle, ac, alloc_inode, bg_bh);
645 	return status ? ERR_PTR(status) : bg_bh;
646 }
647 
648 /*
649  * We expect the block group allocator to already be locked.
650  */
651 static int ocfs2_block_group_alloc(struct ocfs2_super *osb,
652 				   struct inode *alloc_inode,
653 				   struct buffer_head *bh,
654 				   u64 max_block,
655 				   u64 *last_alloc_group,
656 				   int flags)
657 {
658 	int status, credits;
659 	struct ocfs2_dinode *fe = (struct ocfs2_dinode *) bh->b_data;
660 	struct ocfs2_chain_list *cl;
661 	struct ocfs2_alloc_context *ac = NULL;
662 	handle_t *handle = NULL;
663 	u16 alloc_rec;
664 	struct buffer_head *bg_bh = NULL;
665 	struct ocfs2_group_desc *bg;
666 
667 	BUG_ON(ocfs2_is_cluster_bitmap(alloc_inode));
668 
669 	cl = &fe->id2.i_chain;
670 	status = ocfs2_reserve_clusters_with_limit(osb,
671 						   le16_to_cpu(cl->cl_cpg),
672 						   max_block, flags, &ac);
673 	if (status < 0) {
674 		if (status != -ENOSPC)
675 			mlog_errno(status);
676 		goto bail;
677 	}
678 
679 	credits = ocfs2_calc_group_alloc_credits(osb->sb,
680 						 le16_to_cpu(cl->cl_cpg));
681 	handle = ocfs2_start_trans(osb, credits);
682 	if (IS_ERR(handle)) {
683 		status = PTR_ERR(handle);
684 		handle = NULL;
685 		mlog_errno(status);
686 		goto bail;
687 	}
688 
689 	if (last_alloc_group && *last_alloc_group != 0) {
690 		trace_ocfs2_block_group_alloc(
691 				(unsigned long long)*last_alloc_group);
692 		ac->ac_last_group = *last_alloc_group;
693 	}
694 
695 	bg_bh = ocfs2_block_group_alloc_contig(osb, handle, alloc_inode,
696 					       ac, cl);
697 	if (PTR_ERR(bg_bh) == -ENOSPC)
698 		bg_bh = ocfs2_block_group_alloc_discontig(handle,
699 							  alloc_inode,
700 							  ac, cl);
701 	if (IS_ERR(bg_bh)) {
702 		status = PTR_ERR(bg_bh);
703 		bg_bh = NULL;
704 		if (status != -ENOSPC)
705 			mlog_errno(status);
706 		goto bail;
707 	}
708 	bg = (struct ocfs2_group_desc *) bg_bh->b_data;
709 
710 	status = ocfs2_journal_access_di(handle, INODE_CACHE(alloc_inode),
711 					 bh, OCFS2_JOURNAL_ACCESS_WRITE);
712 	if (status < 0) {
713 		mlog_errno(status);
714 		goto bail;
715 	}
716 
717 	alloc_rec = le16_to_cpu(bg->bg_chain);
718 	le32_add_cpu(&cl->cl_recs[alloc_rec].c_free,
719 		     le16_to_cpu(bg->bg_free_bits_count));
720 	le32_add_cpu(&cl->cl_recs[alloc_rec].c_total,
721 		     le16_to_cpu(bg->bg_bits));
722 	cl->cl_recs[alloc_rec].c_blkno = bg->bg_blkno;
723 	if (le16_to_cpu(cl->cl_next_free_rec) < le16_to_cpu(cl->cl_count))
724 		le16_add_cpu(&cl->cl_next_free_rec, 1);
725 
726 	le32_add_cpu(&fe->id1.bitmap1.i_used, le16_to_cpu(bg->bg_bits) -
727 					le16_to_cpu(bg->bg_free_bits_count));
728 	le32_add_cpu(&fe->id1.bitmap1.i_total, le16_to_cpu(bg->bg_bits));
729 	le32_add_cpu(&fe->i_clusters, le16_to_cpu(cl->cl_cpg));
730 
731 	ocfs2_journal_dirty(handle, bh);
732 
733 	spin_lock(&OCFS2_I(alloc_inode)->ip_lock);
734 	OCFS2_I(alloc_inode)->ip_clusters = le32_to_cpu(fe->i_clusters);
735 	fe->i_size = cpu_to_le64(ocfs2_clusters_to_bytes(alloc_inode->i_sb,
736 					     le32_to_cpu(fe->i_clusters)));
737 	spin_unlock(&OCFS2_I(alloc_inode)->ip_lock);
738 	i_size_write(alloc_inode, le64_to_cpu(fe->i_size));
739 	alloc_inode->i_blocks = ocfs2_inode_sector_count(alloc_inode);
740 	ocfs2_update_inode_fsync_trans(handle, alloc_inode, 0);
741 
742 	status = 0;
743 
744 	/* save the new last alloc group so that the caller can cache it. */
745 	if (last_alloc_group)
746 		*last_alloc_group = ac->ac_last_group;
747 
748 bail:
749 	if (handle)
750 		ocfs2_commit_trans(osb, handle);
751 
752 	if (ac)
753 		ocfs2_free_alloc_context(ac);
754 
755 	brelse(bg_bh);
756 
757 	if (status)
758 		mlog_errno(status);
759 	return status;
760 }
761 
762 static int ocfs2_reserve_suballoc_bits(struct ocfs2_super *osb,
763 				       struct ocfs2_alloc_context *ac,
764 				       int type,
765 				       u32 slot,
766 				       u64 *last_alloc_group,
767 				       int flags)
768 {
769 	int status;
770 	u32 bits_wanted = ac->ac_bits_wanted;
771 	struct inode *alloc_inode;
772 	struct buffer_head *bh = NULL;
773 	struct ocfs2_dinode *fe;
774 	u32 free_bits;
775 
776 	alloc_inode = ocfs2_get_system_file_inode(osb, type, slot);
777 	if (!alloc_inode) {
778 		mlog_errno(-EINVAL);
779 		return -EINVAL;
780 	}
781 
782 	inode_lock(alloc_inode);
783 
784 	status = ocfs2_inode_lock(alloc_inode, &bh, 1);
785 	if (status < 0) {
786 		inode_unlock(alloc_inode);
787 		iput(alloc_inode);
788 
789 		mlog_errno(status);
790 		return status;
791 	}
792 
793 	ac->ac_inode = alloc_inode;
794 	ac->ac_alloc_slot = slot;
795 
796 	fe = (struct ocfs2_dinode *) bh->b_data;
797 
798 	/* The bh was validated by the inode read inside
799 	 * ocfs2_inode_lock().  Any corruption is a code bug. */
800 	BUG_ON(!OCFS2_IS_VALID_DINODE(fe));
801 
802 	if (!(fe->i_flags & cpu_to_le32(OCFS2_CHAIN_FL))) {
803 		status = ocfs2_error(alloc_inode->i_sb,
804 				     "Invalid chain allocator %llu\n",
805 				     (unsigned long long)le64_to_cpu(fe->i_blkno));
806 		goto bail;
807 	}
808 
809 	free_bits = le32_to_cpu(fe->id1.bitmap1.i_total) -
810 		le32_to_cpu(fe->id1.bitmap1.i_used);
811 
812 	if (bits_wanted > free_bits) {
813 		/* cluster bitmap never grows */
814 		if (ocfs2_is_cluster_bitmap(alloc_inode)) {
815 			trace_ocfs2_reserve_suballoc_bits_nospc(bits_wanted,
816 								free_bits);
817 			status = -ENOSPC;
818 			goto bail;
819 		}
820 
821 		if (!(flags & ALLOC_NEW_GROUP)) {
822 			trace_ocfs2_reserve_suballoc_bits_no_new_group(
823 						slot, bits_wanted, free_bits);
824 			status = -ENOSPC;
825 			goto bail;
826 		}
827 
828 		status = ocfs2_block_group_alloc(osb, alloc_inode, bh,
829 						 ac->ac_max_block,
830 						 last_alloc_group, flags);
831 		if (status < 0) {
832 			if (status != -ENOSPC)
833 				mlog_errno(status);
834 			goto bail;
835 		}
836 		atomic_inc(&osb->alloc_stats.bg_extends);
837 
838 		/* You should never ask for this much metadata */
839 		BUG_ON(bits_wanted >
840 		       (le32_to_cpu(fe->id1.bitmap1.i_total)
841 			- le32_to_cpu(fe->id1.bitmap1.i_used)));
842 	}
843 
844 	get_bh(bh);
845 	ac->ac_bh = bh;
846 bail:
847 	brelse(bh);
848 
849 	if (status)
850 		mlog_errno(status);
851 	return status;
852 }
853 
854 static void ocfs2_init_inode_steal_slot(struct ocfs2_super *osb)
855 {
856 	spin_lock(&osb->osb_lock);
857 	osb->s_inode_steal_slot = OCFS2_INVALID_SLOT;
858 	spin_unlock(&osb->osb_lock);
859 	atomic_set(&osb->s_num_inodes_stolen, 0);
860 }
861 
862 static void ocfs2_init_meta_steal_slot(struct ocfs2_super *osb)
863 {
864 	spin_lock(&osb->osb_lock);
865 	osb->s_meta_steal_slot = OCFS2_INVALID_SLOT;
866 	spin_unlock(&osb->osb_lock);
867 	atomic_set(&osb->s_num_meta_stolen, 0);
868 }
869 
870 void ocfs2_init_steal_slots(struct ocfs2_super *osb)
871 {
872 	ocfs2_init_inode_steal_slot(osb);
873 	ocfs2_init_meta_steal_slot(osb);
874 }
875 
876 static void __ocfs2_set_steal_slot(struct ocfs2_super *osb, int slot, int type)
877 {
878 	spin_lock(&osb->osb_lock);
879 	if (type == INODE_ALLOC_SYSTEM_INODE)
880 		osb->s_inode_steal_slot = (u16)slot;
881 	else if (type == EXTENT_ALLOC_SYSTEM_INODE)
882 		osb->s_meta_steal_slot = (u16)slot;
883 	spin_unlock(&osb->osb_lock);
884 }
885 
886 static int __ocfs2_get_steal_slot(struct ocfs2_super *osb, int type)
887 {
888 	int slot = OCFS2_INVALID_SLOT;
889 
890 	spin_lock(&osb->osb_lock);
891 	if (type == INODE_ALLOC_SYSTEM_INODE)
892 		slot = osb->s_inode_steal_slot;
893 	else if (type == EXTENT_ALLOC_SYSTEM_INODE)
894 		slot = osb->s_meta_steal_slot;
895 	spin_unlock(&osb->osb_lock);
896 
897 	return slot;
898 }
899 
900 static int ocfs2_get_inode_steal_slot(struct ocfs2_super *osb)
901 {
902 	return __ocfs2_get_steal_slot(osb, INODE_ALLOC_SYSTEM_INODE);
903 }
904 
905 static int ocfs2_get_meta_steal_slot(struct ocfs2_super *osb)
906 {
907 	return __ocfs2_get_steal_slot(osb, EXTENT_ALLOC_SYSTEM_INODE);
908 }
909 
910 static int ocfs2_steal_resource(struct ocfs2_super *osb,
911 				struct ocfs2_alloc_context *ac,
912 				int type)
913 {
914 	int i, status = -ENOSPC;
915 	int slot = __ocfs2_get_steal_slot(osb, type);
916 
917 	/* Start to steal resource from the first slot after ours. */
918 	if (slot == OCFS2_INVALID_SLOT)
919 		slot = osb->slot_num + 1;
920 
921 	for (i = 0; i < osb->max_slots; i++, slot++) {
922 		if (slot == osb->max_slots)
923 			slot = 0;
924 
925 		if (slot == osb->slot_num)
926 			continue;
927 
928 		status = ocfs2_reserve_suballoc_bits(osb, ac,
929 						     type,
930 						     (u32)slot, NULL,
931 						     NOT_ALLOC_NEW_GROUP);
932 		if (status >= 0) {
933 			__ocfs2_set_steal_slot(osb, slot, type);
934 			break;
935 		}
936 
937 		ocfs2_free_ac_resource(ac);
938 	}
939 
940 	return status;
941 }
942 
943 static int ocfs2_steal_inode(struct ocfs2_super *osb,
944 			     struct ocfs2_alloc_context *ac)
945 {
946 	return ocfs2_steal_resource(osb, ac, INODE_ALLOC_SYSTEM_INODE);
947 }
948 
949 static int ocfs2_steal_meta(struct ocfs2_super *osb,
950 			    struct ocfs2_alloc_context *ac)
951 {
952 	return ocfs2_steal_resource(osb, ac, EXTENT_ALLOC_SYSTEM_INODE);
953 }
954 
955 int ocfs2_reserve_new_metadata_blocks(struct ocfs2_super *osb,
956 				      int blocks,
957 				      struct ocfs2_alloc_context **ac)
958 {
959 	int status;
960 	int slot = ocfs2_get_meta_steal_slot(osb);
961 
962 	*ac = kzalloc(sizeof(struct ocfs2_alloc_context), GFP_KERNEL);
963 	if (!(*ac)) {
964 		status = -ENOMEM;
965 		mlog_errno(status);
966 		goto bail;
967 	}
968 
969 	(*ac)->ac_bits_wanted = blocks;
970 	(*ac)->ac_which = OCFS2_AC_USE_META;
971 	(*ac)->ac_group_search = ocfs2_block_group_search;
972 
973 	if (slot != OCFS2_INVALID_SLOT &&
974 		atomic_read(&osb->s_num_meta_stolen) < OCFS2_MAX_TO_STEAL)
975 		goto extent_steal;
976 
977 	atomic_set(&osb->s_num_meta_stolen, 0);
978 	status = ocfs2_reserve_suballoc_bits(osb, (*ac),
979 					     EXTENT_ALLOC_SYSTEM_INODE,
980 					     (u32)osb->slot_num, NULL,
981 					     ALLOC_GROUPS_FROM_GLOBAL|ALLOC_NEW_GROUP);
982 
983 
984 	if (status >= 0) {
985 		status = 0;
986 		if (slot != OCFS2_INVALID_SLOT)
987 			ocfs2_init_meta_steal_slot(osb);
988 		goto bail;
989 	} else if (status < 0 && status != -ENOSPC) {
990 		mlog_errno(status);
991 		goto bail;
992 	}
993 
994 	ocfs2_free_ac_resource(*ac);
995 
996 extent_steal:
997 	status = ocfs2_steal_meta(osb, *ac);
998 	atomic_inc(&osb->s_num_meta_stolen);
999 	if (status < 0) {
1000 		if (status != -ENOSPC)
1001 			mlog_errno(status);
1002 		goto bail;
1003 	}
1004 
1005 	status = 0;
1006 bail:
1007 	if ((status < 0) && *ac) {
1008 		ocfs2_free_alloc_context(*ac);
1009 		*ac = NULL;
1010 	}
1011 
1012 	if (status)
1013 		mlog_errno(status);
1014 	return status;
1015 }
1016 
1017 int ocfs2_reserve_new_metadata(struct ocfs2_super *osb,
1018 			       struct ocfs2_extent_list *root_el,
1019 			       struct ocfs2_alloc_context **ac)
1020 {
1021 	return ocfs2_reserve_new_metadata_blocks(osb,
1022 					ocfs2_extend_meta_needed(root_el),
1023 					ac);
1024 }
1025 
1026 int ocfs2_reserve_new_inode(struct ocfs2_super *osb,
1027 			    struct ocfs2_alloc_context **ac)
1028 {
1029 	int status;
1030 	int slot = ocfs2_get_inode_steal_slot(osb);
1031 	u64 alloc_group;
1032 
1033 	*ac = kzalloc(sizeof(struct ocfs2_alloc_context), GFP_KERNEL);
1034 	if (!(*ac)) {
1035 		status = -ENOMEM;
1036 		mlog_errno(status);
1037 		goto bail;
1038 	}
1039 
1040 	(*ac)->ac_bits_wanted = 1;
1041 	(*ac)->ac_which = OCFS2_AC_USE_INODE;
1042 
1043 	(*ac)->ac_group_search = ocfs2_block_group_search;
1044 
1045 	/*
1046 	 * stat(2) can't handle i_ino > 32bits, so we tell the
1047 	 * lower levels not to allocate us a block group past that
1048 	 * limit.  The 'inode64' mount option avoids this behavior.
1049 	 */
1050 	if (!(osb->s_mount_opt & OCFS2_MOUNT_INODE64))
1051 		(*ac)->ac_max_block = (u32)~0U;
1052 
1053 	/*
1054 	 * slot is set when we successfully steal inode from other nodes.
1055 	 * It is reset in 3 places:
1056 	 * 1. when we flush the truncate log
1057 	 * 2. when we complete local alloc recovery.
1058 	 * 3. when we successfully allocate from our own slot.
1059 	 * After it is set, we will go on stealing inodes until we find the
1060 	 * need to check our slots to see whether there is some space for us.
1061 	 */
1062 	if (slot != OCFS2_INVALID_SLOT &&
1063 	    atomic_read(&osb->s_num_inodes_stolen) < OCFS2_MAX_TO_STEAL)
1064 		goto inode_steal;
1065 
1066 	atomic_set(&osb->s_num_inodes_stolen, 0);
1067 	alloc_group = osb->osb_inode_alloc_group;
1068 	status = ocfs2_reserve_suballoc_bits(osb, *ac,
1069 					     INODE_ALLOC_SYSTEM_INODE,
1070 					     (u32)osb->slot_num,
1071 					     &alloc_group,
1072 					     ALLOC_NEW_GROUP |
1073 					     ALLOC_GROUPS_FROM_GLOBAL);
1074 	if (status >= 0) {
1075 		status = 0;
1076 
1077 		spin_lock(&osb->osb_lock);
1078 		osb->osb_inode_alloc_group = alloc_group;
1079 		spin_unlock(&osb->osb_lock);
1080 		trace_ocfs2_reserve_new_inode_new_group(
1081 			(unsigned long long)alloc_group);
1082 
1083 		/*
1084 		 * Some inodes must be freed by us, so try to allocate
1085 		 * from our own next time.
1086 		 */
1087 		if (slot != OCFS2_INVALID_SLOT)
1088 			ocfs2_init_inode_steal_slot(osb);
1089 		goto bail;
1090 	} else if (status < 0 && status != -ENOSPC) {
1091 		mlog_errno(status);
1092 		goto bail;
1093 	}
1094 
1095 	ocfs2_free_ac_resource(*ac);
1096 
1097 inode_steal:
1098 	status = ocfs2_steal_inode(osb, *ac);
1099 	atomic_inc(&osb->s_num_inodes_stolen);
1100 	if (status < 0) {
1101 		if (status != -ENOSPC)
1102 			mlog_errno(status);
1103 		goto bail;
1104 	}
1105 
1106 	status = 0;
1107 bail:
1108 	if ((status < 0) && *ac) {
1109 		ocfs2_free_alloc_context(*ac);
1110 		*ac = NULL;
1111 	}
1112 
1113 	if (status)
1114 		mlog_errno(status);
1115 	return status;
1116 }
1117 
1118 /* local alloc code has to do the same thing, so rather than do this
1119  * twice.. */
1120 int ocfs2_reserve_cluster_bitmap_bits(struct ocfs2_super *osb,
1121 				      struct ocfs2_alloc_context *ac)
1122 {
1123 	int status;
1124 
1125 	ac->ac_which = OCFS2_AC_USE_MAIN;
1126 	ac->ac_group_search = ocfs2_cluster_group_search;
1127 
1128 	status = ocfs2_reserve_suballoc_bits(osb, ac,
1129 					     GLOBAL_BITMAP_SYSTEM_INODE,
1130 					     OCFS2_INVALID_SLOT, NULL,
1131 					     ALLOC_NEW_GROUP);
1132 	if (status < 0 && status != -ENOSPC)
1133 		mlog_errno(status);
1134 
1135 	return status;
1136 }
1137 
1138 /* Callers don't need to care which bitmap (local alloc or main) to
1139  * use so we figure it out for them, but unfortunately this clutters
1140  * things a bit. */
1141 static int ocfs2_reserve_clusters_with_limit(struct ocfs2_super *osb,
1142 					     u32 bits_wanted, u64 max_block,
1143 					     int flags,
1144 					     struct ocfs2_alloc_context **ac)
1145 {
1146 	int status, ret = 0;
1147 	int retried = 0;
1148 
1149 	*ac = kzalloc(sizeof(struct ocfs2_alloc_context), GFP_KERNEL);
1150 	if (!(*ac)) {
1151 		status = -ENOMEM;
1152 		mlog_errno(status);
1153 		goto bail;
1154 	}
1155 
1156 	(*ac)->ac_bits_wanted = bits_wanted;
1157 	(*ac)->ac_max_block = max_block;
1158 
1159 	status = -ENOSPC;
1160 	if (!(flags & ALLOC_GROUPS_FROM_GLOBAL) &&
1161 	    ocfs2_alloc_should_use_local(osb, bits_wanted)) {
1162 		status = ocfs2_reserve_local_alloc_bits(osb,
1163 							bits_wanted,
1164 							*ac);
1165 		if ((status < 0) && (status != -ENOSPC)) {
1166 			mlog_errno(status);
1167 			goto bail;
1168 		}
1169 	}
1170 
1171 	if (status == -ENOSPC) {
1172 retry:
1173 		status = ocfs2_reserve_cluster_bitmap_bits(osb, *ac);
1174 		/* Retry if there is sufficient space cached in truncate log */
1175 		if (status == -ENOSPC && !retried) {
1176 			retried = 1;
1177 			ocfs2_inode_unlock((*ac)->ac_inode, 1);
1178 			inode_unlock((*ac)->ac_inode);
1179 
1180 			ret = ocfs2_try_to_free_truncate_log(osb, bits_wanted);
1181 			if (ret == 1) {
1182 				iput((*ac)->ac_inode);
1183 				(*ac)->ac_inode = NULL;
1184 				goto retry;
1185 			}
1186 
1187 			if (ret < 0)
1188 				mlog_errno(ret);
1189 
1190 			inode_lock((*ac)->ac_inode);
1191 			ret = ocfs2_inode_lock((*ac)->ac_inode, NULL, 1);
1192 			if (ret < 0) {
1193 				mlog_errno(ret);
1194 				inode_unlock((*ac)->ac_inode);
1195 				iput((*ac)->ac_inode);
1196 				(*ac)->ac_inode = NULL;
1197 				goto bail;
1198 			}
1199 		}
1200 		if (status < 0) {
1201 			if (status != -ENOSPC)
1202 				mlog_errno(status);
1203 			goto bail;
1204 		}
1205 	}
1206 
1207 	status = 0;
1208 bail:
1209 	if ((status < 0) && *ac) {
1210 		ocfs2_free_alloc_context(*ac);
1211 		*ac = NULL;
1212 	}
1213 
1214 	if (status)
1215 		mlog_errno(status);
1216 	return status;
1217 }
1218 
1219 int ocfs2_reserve_clusters(struct ocfs2_super *osb,
1220 			   u32 bits_wanted,
1221 			   struct ocfs2_alloc_context **ac)
1222 {
1223 	return ocfs2_reserve_clusters_with_limit(osb, bits_wanted, 0,
1224 						 ALLOC_NEW_GROUP, ac);
1225 }
1226 
1227 /*
1228  * More or less lifted from ext3. I'll leave their description below:
1229  *
1230  * "For ext3 allocations, we must not reuse any blocks which are
1231  * allocated in the bitmap buffer's "last committed data" copy.  This
1232  * prevents deletes from freeing up the page for reuse until we have
1233  * committed the delete transaction.
1234  *
1235  * If we didn't do this, then deleting something and reallocating it as
1236  * data would allow the old block to be overwritten before the
1237  * transaction committed (because we force data to disk before commit).
1238  * This would lead to corruption if we crashed between overwriting the
1239  * data and committing the delete.
1240  *
1241  * @@@ We may want to make this allocation behaviour conditional on
1242  * data-writes at some point, and disable it for metadata allocations or
1243  * sync-data inodes."
1244  *
1245  * Note: OCFS2 already does this differently for metadata vs data
1246  * allocations, as those bitmaps are separate and undo access is never
1247  * called on a metadata group descriptor.
1248  */
1249 static int ocfs2_test_bg_bit_allocatable(struct buffer_head *bg_bh,
1250 					 int nr)
1251 {
1252 	struct ocfs2_group_desc *bg = (struct ocfs2_group_desc *) bg_bh->b_data;
1253 	struct journal_head *jh;
1254 	int ret;
1255 
1256 	if (ocfs2_test_bit(nr, (unsigned long *)bg->bg_bitmap))
1257 		return 0;
1258 
1259 	if (!buffer_jbd(bg_bh))
1260 		return 1;
1261 
1262 	jh = bh2jh(bg_bh);
1263 	spin_lock(&jh->b_state_lock);
1264 	bg = (struct ocfs2_group_desc *) jh->b_committed_data;
1265 	if (bg)
1266 		ret = !ocfs2_test_bit(nr, (unsigned long *)bg->bg_bitmap);
1267 	else
1268 		ret = 1;
1269 	spin_unlock(&jh->b_state_lock);
1270 
1271 	return ret;
1272 }
1273 
1274 static int ocfs2_block_group_find_clear_bits(struct ocfs2_super *osb,
1275 					     struct buffer_head *bg_bh,
1276 					     unsigned int bits_wanted,
1277 					     unsigned int total_bits,
1278 					     struct ocfs2_suballoc_result *res)
1279 {
1280 	void *bitmap;
1281 	u16 best_offset, best_size;
1282 	int offset, start, found, status = 0;
1283 	struct ocfs2_group_desc *bg = (struct ocfs2_group_desc *) bg_bh->b_data;
1284 
1285 	/* Callers got this descriptor from
1286 	 * ocfs2_read_group_descriptor().  Any corruption is a code bug. */
1287 	BUG_ON(!OCFS2_IS_VALID_GROUP_DESC(bg));
1288 
1289 	found = start = best_offset = best_size = 0;
1290 	bitmap = bg->bg_bitmap;
1291 
1292 	while((offset = ocfs2_find_next_zero_bit(bitmap, total_bits, start)) != -1) {
1293 		if (offset == total_bits)
1294 			break;
1295 
1296 		if (!ocfs2_test_bg_bit_allocatable(bg_bh, offset)) {
1297 			/* We found a zero, but we can't use it as it
1298 			 * hasn't been put to disk yet! */
1299 			found = 0;
1300 			start = offset + 1;
1301 		} else if (offset == start) {
1302 			/* we found a zero */
1303 			found++;
1304 			/* move start to the next bit to test */
1305 			start++;
1306 		} else {
1307 			/* got a zero after some ones */
1308 			found = 1;
1309 			start = offset + 1;
1310 		}
1311 		if (found > best_size) {
1312 			best_size = found;
1313 			best_offset = start - found;
1314 		}
1315 		/* we got everything we needed */
1316 		if (found == bits_wanted) {
1317 			/* mlog(0, "Found it all!\n"); */
1318 			break;
1319 		}
1320 	}
1321 
1322 	if (best_size) {
1323 		res->sr_bit_offset = best_offset;
1324 		res->sr_bits = best_size;
1325 	} else {
1326 		status = -ENOSPC;
1327 		/* No error log here -- see the comment above
1328 		 * ocfs2_test_bg_bit_allocatable */
1329 	}
1330 
1331 	return status;
1332 }
1333 
1334 int ocfs2_block_group_set_bits(handle_t *handle,
1335 					     struct inode *alloc_inode,
1336 					     struct ocfs2_group_desc *bg,
1337 					     struct buffer_head *group_bh,
1338 					     unsigned int bit_off,
1339 					     unsigned int num_bits)
1340 {
1341 	int status;
1342 	void *bitmap = bg->bg_bitmap;
1343 	int journal_type = OCFS2_JOURNAL_ACCESS_WRITE;
1344 
1345 	/* All callers get the descriptor via
1346 	 * ocfs2_read_group_descriptor().  Any corruption is a code bug. */
1347 	BUG_ON(!OCFS2_IS_VALID_GROUP_DESC(bg));
1348 	BUG_ON(le16_to_cpu(bg->bg_free_bits_count) < num_bits);
1349 
1350 	trace_ocfs2_block_group_set_bits(bit_off, num_bits);
1351 
1352 	if (ocfs2_is_cluster_bitmap(alloc_inode))
1353 		journal_type = OCFS2_JOURNAL_ACCESS_UNDO;
1354 
1355 	status = ocfs2_journal_access_gd(handle,
1356 					 INODE_CACHE(alloc_inode),
1357 					 group_bh,
1358 					 journal_type);
1359 	if (status < 0) {
1360 		mlog_errno(status);
1361 		goto bail;
1362 	}
1363 
1364 	le16_add_cpu(&bg->bg_free_bits_count, -num_bits);
1365 	if (le16_to_cpu(bg->bg_free_bits_count) > le16_to_cpu(bg->bg_bits)) {
1366 		return ocfs2_error(alloc_inode->i_sb, "Group descriptor # %llu has bit count %u but claims %u are freed. num_bits %d\n",
1367 				   (unsigned long long)le64_to_cpu(bg->bg_blkno),
1368 				   le16_to_cpu(bg->bg_bits),
1369 				   le16_to_cpu(bg->bg_free_bits_count),
1370 				   num_bits);
1371 	}
1372 	while(num_bits--)
1373 		ocfs2_set_bit(bit_off++, bitmap);
1374 
1375 	ocfs2_journal_dirty(handle, group_bh);
1376 
1377 bail:
1378 	return status;
1379 }
1380 
1381 /* find the one with the most empty bits */
1382 static inline u16 ocfs2_find_victim_chain(struct ocfs2_chain_list *cl)
1383 {
1384 	u16 curr, best;
1385 
1386 	BUG_ON(!cl->cl_next_free_rec);
1387 
1388 	best = curr = 0;
1389 	while (curr < le16_to_cpu(cl->cl_next_free_rec)) {
1390 		if (le32_to_cpu(cl->cl_recs[curr].c_free) >
1391 		    le32_to_cpu(cl->cl_recs[best].c_free))
1392 			best = curr;
1393 		curr++;
1394 	}
1395 
1396 	BUG_ON(best >= le16_to_cpu(cl->cl_next_free_rec));
1397 	return best;
1398 }
1399 
1400 static int ocfs2_relink_block_group(handle_t *handle,
1401 				    struct inode *alloc_inode,
1402 				    struct buffer_head *fe_bh,
1403 				    struct buffer_head *bg_bh,
1404 				    struct buffer_head *prev_bg_bh,
1405 				    u16 chain)
1406 {
1407 	int status;
1408 	/* there is a really tiny chance the journal calls could fail,
1409 	 * but we wouldn't want inconsistent blocks in *any* case. */
1410 	u64 bg_ptr, prev_bg_ptr;
1411 	struct ocfs2_dinode *fe = (struct ocfs2_dinode *) fe_bh->b_data;
1412 	struct ocfs2_group_desc *bg = (struct ocfs2_group_desc *) bg_bh->b_data;
1413 	struct ocfs2_group_desc *prev_bg = (struct ocfs2_group_desc *) prev_bg_bh->b_data;
1414 
1415 	/* The caller got these descriptors from
1416 	 * ocfs2_read_group_descriptor().  Any corruption is a code bug. */
1417 	BUG_ON(!OCFS2_IS_VALID_GROUP_DESC(bg));
1418 	BUG_ON(!OCFS2_IS_VALID_GROUP_DESC(prev_bg));
1419 
1420 	trace_ocfs2_relink_block_group(
1421 		(unsigned long long)le64_to_cpu(fe->i_blkno), chain,
1422 		(unsigned long long)le64_to_cpu(bg->bg_blkno),
1423 		(unsigned long long)le64_to_cpu(prev_bg->bg_blkno));
1424 
1425 	bg_ptr = le64_to_cpu(bg->bg_next_group);
1426 	prev_bg_ptr = le64_to_cpu(prev_bg->bg_next_group);
1427 
1428 	status = ocfs2_journal_access_gd(handle, INODE_CACHE(alloc_inode),
1429 					 prev_bg_bh,
1430 					 OCFS2_JOURNAL_ACCESS_WRITE);
1431 	if (status < 0)
1432 		goto out;
1433 
1434 	prev_bg->bg_next_group = bg->bg_next_group;
1435 	ocfs2_journal_dirty(handle, prev_bg_bh);
1436 
1437 	status = ocfs2_journal_access_gd(handle, INODE_CACHE(alloc_inode),
1438 					 bg_bh, OCFS2_JOURNAL_ACCESS_WRITE);
1439 	if (status < 0)
1440 		goto out_rollback_prev_bg;
1441 
1442 	bg->bg_next_group = fe->id2.i_chain.cl_recs[chain].c_blkno;
1443 	ocfs2_journal_dirty(handle, bg_bh);
1444 
1445 	status = ocfs2_journal_access_di(handle, INODE_CACHE(alloc_inode),
1446 					 fe_bh, OCFS2_JOURNAL_ACCESS_WRITE);
1447 	if (status < 0)
1448 		goto out_rollback_bg;
1449 
1450 	fe->id2.i_chain.cl_recs[chain].c_blkno = bg->bg_blkno;
1451 	ocfs2_journal_dirty(handle, fe_bh);
1452 
1453 out:
1454 	if (status < 0)
1455 		mlog_errno(status);
1456 	return status;
1457 
1458 out_rollback_bg:
1459 	bg->bg_next_group = cpu_to_le64(bg_ptr);
1460 out_rollback_prev_bg:
1461 	prev_bg->bg_next_group = cpu_to_le64(prev_bg_ptr);
1462 	goto out;
1463 }
1464 
1465 static inline int ocfs2_block_group_reasonably_empty(struct ocfs2_group_desc *bg,
1466 						     u32 wanted)
1467 {
1468 	return le16_to_cpu(bg->bg_free_bits_count) > wanted;
1469 }
1470 
1471 /* return 0 on success, -ENOSPC to keep searching and any other < 0
1472  * value on error. */
1473 static int ocfs2_cluster_group_search(struct inode *inode,
1474 				      struct buffer_head *group_bh,
1475 				      u32 bits_wanted, u32 min_bits,
1476 				      u64 max_block,
1477 				      struct ocfs2_suballoc_result *res)
1478 {
1479 	int search = -ENOSPC;
1480 	int ret;
1481 	u64 blkoff;
1482 	struct ocfs2_group_desc *gd = (struct ocfs2_group_desc *) group_bh->b_data;
1483 	struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
1484 	unsigned int max_bits, gd_cluster_off;
1485 
1486 	BUG_ON(!ocfs2_is_cluster_bitmap(inode));
1487 
1488 	if (gd->bg_free_bits_count) {
1489 		max_bits = le16_to_cpu(gd->bg_bits);
1490 
1491 		/* Tail groups in cluster bitmaps which aren't cpg
1492 		 * aligned are prone to partial extension by a failed
1493 		 * fs resize. If the file system resize never got to
1494 		 * update the dinode cluster count, then we don't want
1495 		 * to trust any clusters past it, regardless of what
1496 		 * the group descriptor says. */
1497 		gd_cluster_off = ocfs2_blocks_to_clusters(inode->i_sb,
1498 							  le64_to_cpu(gd->bg_blkno));
1499 		if ((gd_cluster_off + max_bits) >
1500 		    OCFS2_I(inode)->ip_clusters) {
1501 			max_bits = OCFS2_I(inode)->ip_clusters - gd_cluster_off;
1502 			trace_ocfs2_cluster_group_search_wrong_max_bits(
1503 				(unsigned long long)le64_to_cpu(gd->bg_blkno),
1504 				le16_to_cpu(gd->bg_bits),
1505 				OCFS2_I(inode)->ip_clusters, max_bits);
1506 		}
1507 
1508 		ret = ocfs2_block_group_find_clear_bits(osb,
1509 							group_bh, bits_wanted,
1510 							max_bits, res);
1511 		if (ret)
1512 			return ret;
1513 
1514 		if (max_block) {
1515 			blkoff = ocfs2_clusters_to_blocks(inode->i_sb,
1516 							  gd_cluster_off +
1517 							  res->sr_bit_offset +
1518 							  res->sr_bits);
1519 			trace_ocfs2_cluster_group_search_max_block(
1520 				(unsigned long long)blkoff,
1521 				(unsigned long long)max_block);
1522 			if (blkoff > max_block)
1523 				return -ENOSPC;
1524 		}
1525 
1526 		/* ocfs2_block_group_find_clear_bits() might
1527 		 * return success, but we still want to return
1528 		 * -ENOSPC unless it found the minimum number
1529 		 * of bits. */
1530 		if (min_bits <= res->sr_bits)
1531 			search = 0; /* success */
1532 		else if (res->sr_bits) {
1533 			/*
1534 			 * Don't show bits which we'll be returning
1535 			 * for allocation to the local alloc bitmap.
1536 			 */
1537 			ocfs2_local_alloc_seen_free_bits(osb, res->sr_bits);
1538 		}
1539 	}
1540 
1541 	return search;
1542 }
1543 
1544 static int ocfs2_block_group_search(struct inode *inode,
1545 				    struct buffer_head *group_bh,
1546 				    u32 bits_wanted, u32 min_bits,
1547 				    u64 max_block,
1548 				    struct ocfs2_suballoc_result *res)
1549 {
1550 	int ret = -ENOSPC;
1551 	u64 blkoff;
1552 	struct ocfs2_group_desc *bg = (struct ocfs2_group_desc *) group_bh->b_data;
1553 
1554 	BUG_ON(min_bits != 1);
1555 	BUG_ON(ocfs2_is_cluster_bitmap(inode));
1556 
1557 	if (bg->bg_free_bits_count) {
1558 		ret = ocfs2_block_group_find_clear_bits(OCFS2_SB(inode->i_sb),
1559 							group_bh, bits_wanted,
1560 							le16_to_cpu(bg->bg_bits),
1561 							res);
1562 		if (!ret && max_block) {
1563 			blkoff = le64_to_cpu(bg->bg_blkno) +
1564 				res->sr_bit_offset + res->sr_bits;
1565 			trace_ocfs2_block_group_search_max_block(
1566 				(unsigned long long)blkoff,
1567 				(unsigned long long)max_block);
1568 			if (blkoff > max_block)
1569 				ret = -ENOSPC;
1570 		}
1571 	}
1572 
1573 	return ret;
1574 }
1575 
1576 int ocfs2_alloc_dinode_update_counts(struct inode *inode,
1577 				       handle_t *handle,
1578 				       struct buffer_head *di_bh,
1579 				       u32 num_bits,
1580 				       u16 chain)
1581 {
1582 	int ret;
1583 	u32 tmp_used;
1584 	struct ocfs2_dinode *di = (struct ocfs2_dinode *) di_bh->b_data;
1585 	struct ocfs2_chain_list *cl = (struct ocfs2_chain_list *) &di->id2.i_chain;
1586 
1587 	ret = ocfs2_journal_access_di(handle, INODE_CACHE(inode), di_bh,
1588 				      OCFS2_JOURNAL_ACCESS_WRITE);
1589 	if (ret < 0) {
1590 		mlog_errno(ret);
1591 		goto out;
1592 	}
1593 
1594 	tmp_used = le32_to_cpu(di->id1.bitmap1.i_used);
1595 	di->id1.bitmap1.i_used = cpu_to_le32(num_bits + tmp_used);
1596 	le32_add_cpu(&cl->cl_recs[chain].c_free, -num_bits);
1597 	ocfs2_journal_dirty(handle, di_bh);
1598 
1599 out:
1600 	return ret;
1601 }
1602 
1603 void ocfs2_rollback_alloc_dinode_counts(struct inode *inode,
1604 				       struct buffer_head *di_bh,
1605 				       u32 num_bits,
1606 				       u16 chain)
1607 {
1608 	u32 tmp_used;
1609 	struct ocfs2_dinode *di = (struct ocfs2_dinode *) di_bh->b_data;
1610 	struct ocfs2_chain_list *cl;
1611 
1612 	cl = (struct ocfs2_chain_list *)&di->id2.i_chain;
1613 	tmp_used = le32_to_cpu(di->id1.bitmap1.i_used);
1614 	di->id1.bitmap1.i_used = cpu_to_le32(tmp_used - num_bits);
1615 	le32_add_cpu(&cl->cl_recs[chain].c_free, num_bits);
1616 }
1617 
1618 static int ocfs2_bg_discontig_fix_by_rec(struct ocfs2_suballoc_result *res,
1619 					 struct ocfs2_extent_rec *rec,
1620 					 struct ocfs2_chain_list *cl)
1621 {
1622 	unsigned int bpc = le16_to_cpu(cl->cl_bpc);
1623 	unsigned int bitoff = le32_to_cpu(rec->e_cpos) * bpc;
1624 	unsigned int bitcount = le16_to_cpu(rec->e_leaf_clusters) * bpc;
1625 
1626 	if (res->sr_bit_offset < bitoff)
1627 		return 0;
1628 	if (res->sr_bit_offset >= (bitoff + bitcount))
1629 		return 0;
1630 	res->sr_blkno = le64_to_cpu(rec->e_blkno) +
1631 		(res->sr_bit_offset - bitoff);
1632 	if ((res->sr_bit_offset + res->sr_bits) > (bitoff + bitcount))
1633 		res->sr_bits = (bitoff + bitcount) - res->sr_bit_offset;
1634 	return 1;
1635 }
1636 
1637 static void ocfs2_bg_discontig_fix_result(struct ocfs2_alloc_context *ac,
1638 					  struct ocfs2_group_desc *bg,
1639 					  struct ocfs2_suballoc_result *res)
1640 {
1641 	int i;
1642 	u64 bg_blkno = res->sr_bg_blkno;  /* Save off */
1643 	struct ocfs2_extent_rec *rec;
1644 	struct ocfs2_dinode *di = (struct ocfs2_dinode *)ac->ac_bh->b_data;
1645 	struct ocfs2_chain_list *cl = &di->id2.i_chain;
1646 
1647 	if (ocfs2_is_cluster_bitmap(ac->ac_inode)) {
1648 		res->sr_blkno = 0;
1649 		return;
1650 	}
1651 
1652 	res->sr_blkno = res->sr_bg_blkno + res->sr_bit_offset;
1653 	res->sr_bg_blkno = 0;  /* Clear it for contig block groups */
1654 	if (!ocfs2_supports_discontig_bg(OCFS2_SB(ac->ac_inode->i_sb)) ||
1655 	    !bg->bg_list.l_next_free_rec)
1656 		return;
1657 
1658 	for (i = 0; i < le16_to_cpu(bg->bg_list.l_next_free_rec); i++) {
1659 		rec = &bg->bg_list.l_recs[i];
1660 		if (ocfs2_bg_discontig_fix_by_rec(res, rec, cl)) {
1661 			res->sr_bg_blkno = bg_blkno;  /* Restore */
1662 			break;
1663 		}
1664 	}
1665 }
1666 
1667 static int ocfs2_search_one_group(struct ocfs2_alloc_context *ac,
1668 				  handle_t *handle,
1669 				  u32 bits_wanted,
1670 				  u32 min_bits,
1671 				  struct ocfs2_suballoc_result *res,
1672 				  u16 *bits_left)
1673 {
1674 	int ret;
1675 	struct buffer_head *group_bh = NULL;
1676 	struct ocfs2_group_desc *gd;
1677 	struct ocfs2_dinode *di = (struct ocfs2_dinode *)ac->ac_bh->b_data;
1678 	struct inode *alloc_inode = ac->ac_inode;
1679 
1680 	ret = ocfs2_read_group_descriptor(alloc_inode, di,
1681 					  res->sr_bg_blkno, &group_bh);
1682 	if (ret < 0) {
1683 		mlog_errno(ret);
1684 		return ret;
1685 	}
1686 
1687 	gd = (struct ocfs2_group_desc *) group_bh->b_data;
1688 	ret = ac->ac_group_search(alloc_inode, group_bh, bits_wanted, min_bits,
1689 				  ac->ac_max_block, res);
1690 	if (ret < 0) {
1691 		if (ret != -ENOSPC)
1692 			mlog_errno(ret);
1693 		goto out;
1694 	}
1695 
1696 	if (!ret)
1697 		ocfs2_bg_discontig_fix_result(ac, gd, res);
1698 
1699 	/*
1700 	 * sr_bg_blkno might have been changed by
1701 	 * ocfs2_bg_discontig_fix_result
1702 	 */
1703 	res->sr_bg_stable_blkno = group_bh->b_blocknr;
1704 
1705 	if (ac->ac_find_loc_only)
1706 		goto out_loc_only;
1707 
1708 	ret = ocfs2_alloc_dinode_update_counts(alloc_inode, handle, ac->ac_bh,
1709 					       res->sr_bits,
1710 					       le16_to_cpu(gd->bg_chain));
1711 	if (ret < 0) {
1712 		mlog_errno(ret);
1713 		goto out;
1714 	}
1715 
1716 	ret = ocfs2_block_group_set_bits(handle, alloc_inode, gd, group_bh,
1717 					 res->sr_bit_offset, res->sr_bits);
1718 	if (ret < 0) {
1719 		ocfs2_rollback_alloc_dinode_counts(alloc_inode, ac->ac_bh,
1720 					       res->sr_bits,
1721 					       le16_to_cpu(gd->bg_chain));
1722 		mlog_errno(ret);
1723 	}
1724 
1725 out_loc_only:
1726 	*bits_left = le16_to_cpu(gd->bg_free_bits_count);
1727 
1728 out:
1729 	brelse(group_bh);
1730 
1731 	return ret;
1732 }
1733 
1734 static int ocfs2_search_chain(struct ocfs2_alloc_context *ac,
1735 			      handle_t *handle,
1736 			      u32 bits_wanted,
1737 			      u32 min_bits,
1738 			      struct ocfs2_suballoc_result *res,
1739 			      u16 *bits_left)
1740 {
1741 	int status;
1742 	u16 chain;
1743 	u64 next_group;
1744 	struct inode *alloc_inode = ac->ac_inode;
1745 	struct buffer_head *group_bh = NULL;
1746 	struct buffer_head *prev_group_bh = NULL;
1747 	struct ocfs2_dinode *fe = (struct ocfs2_dinode *) ac->ac_bh->b_data;
1748 	struct ocfs2_chain_list *cl = (struct ocfs2_chain_list *) &fe->id2.i_chain;
1749 	struct ocfs2_group_desc *bg;
1750 
1751 	chain = ac->ac_chain;
1752 	trace_ocfs2_search_chain_begin(
1753 		(unsigned long long)OCFS2_I(alloc_inode)->ip_blkno,
1754 		bits_wanted, chain);
1755 
1756 	status = ocfs2_read_group_descriptor(alloc_inode, fe,
1757 					     le64_to_cpu(cl->cl_recs[chain].c_blkno),
1758 					     &group_bh);
1759 	if (status < 0) {
1760 		mlog_errno(status);
1761 		goto bail;
1762 	}
1763 	bg = (struct ocfs2_group_desc *) group_bh->b_data;
1764 
1765 	status = -ENOSPC;
1766 	/* for now, the chain search is a bit simplistic. We just use
1767 	 * the 1st group with any empty bits. */
1768 	while ((status = ac->ac_group_search(alloc_inode, group_bh,
1769 					     bits_wanted, min_bits,
1770 					     ac->ac_max_block,
1771 					     res)) == -ENOSPC) {
1772 		if (!bg->bg_next_group)
1773 			break;
1774 
1775 		brelse(prev_group_bh);
1776 		prev_group_bh = NULL;
1777 
1778 		next_group = le64_to_cpu(bg->bg_next_group);
1779 		prev_group_bh = group_bh;
1780 		group_bh = NULL;
1781 		status = ocfs2_read_group_descriptor(alloc_inode, fe,
1782 						     next_group, &group_bh);
1783 		if (status < 0) {
1784 			mlog_errno(status);
1785 			goto bail;
1786 		}
1787 		bg = (struct ocfs2_group_desc *) group_bh->b_data;
1788 	}
1789 	if (status < 0) {
1790 		if (status != -ENOSPC)
1791 			mlog_errno(status);
1792 		goto bail;
1793 	}
1794 
1795 	trace_ocfs2_search_chain_succ(
1796 		(unsigned long long)le64_to_cpu(bg->bg_blkno), res->sr_bits);
1797 
1798 	res->sr_bg_blkno = le64_to_cpu(bg->bg_blkno);
1799 
1800 	BUG_ON(res->sr_bits == 0);
1801 	if (!status)
1802 		ocfs2_bg_discontig_fix_result(ac, bg, res);
1803 
1804 	/*
1805 	 * sr_bg_blkno might have been changed by
1806 	 * ocfs2_bg_discontig_fix_result
1807 	 */
1808 	res->sr_bg_stable_blkno = group_bh->b_blocknr;
1809 
1810 	/*
1811 	 * Keep track of previous block descriptor read. When
1812 	 * we find a target, if we have read more than X
1813 	 * number of descriptors, and the target is reasonably
1814 	 * empty, relink him to top of his chain.
1815 	 *
1816 	 * We've read 0 extra blocks and only send one more to
1817 	 * the transaction, yet the next guy to search has a
1818 	 * much easier time.
1819 	 *
1820 	 * Do this *after* figuring out how many bits we're taking out
1821 	 * of our target group.
1822 	 */
1823 	if (!ac->ac_disable_chain_relink &&
1824 	    (prev_group_bh) &&
1825 	    (ocfs2_block_group_reasonably_empty(bg, res->sr_bits))) {
1826 		status = ocfs2_relink_block_group(handle, alloc_inode,
1827 						  ac->ac_bh, group_bh,
1828 						  prev_group_bh, chain);
1829 		if (status < 0) {
1830 			mlog_errno(status);
1831 			goto bail;
1832 		}
1833 	}
1834 
1835 	if (ac->ac_find_loc_only)
1836 		goto out_loc_only;
1837 
1838 	status = ocfs2_alloc_dinode_update_counts(alloc_inode, handle,
1839 						  ac->ac_bh, res->sr_bits,
1840 						  chain);
1841 	if (status) {
1842 		mlog_errno(status);
1843 		goto bail;
1844 	}
1845 
1846 	status = ocfs2_block_group_set_bits(handle,
1847 					    alloc_inode,
1848 					    bg,
1849 					    group_bh,
1850 					    res->sr_bit_offset,
1851 					    res->sr_bits);
1852 	if (status < 0) {
1853 		ocfs2_rollback_alloc_dinode_counts(alloc_inode,
1854 					ac->ac_bh, res->sr_bits, chain);
1855 		mlog_errno(status);
1856 		goto bail;
1857 	}
1858 
1859 	trace_ocfs2_search_chain_end(
1860 			(unsigned long long)le64_to_cpu(fe->i_blkno),
1861 			res->sr_bits);
1862 
1863 out_loc_only:
1864 	*bits_left = le16_to_cpu(bg->bg_free_bits_count);
1865 bail:
1866 	brelse(group_bh);
1867 	brelse(prev_group_bh);
1868 
1869 	if (status)
1870 		mlog_errno(status);
1871 	return status;
1872 }
1873 
1874 /* will give out up to bits_wanted contiguous bits. */
1875 static int ocfs2_claim_suballoc_bits(struct ocfs2_alloc_context *ac,
1876 				     handle_t *handle,
1877 				     u32 bits_wanted,
1878 				     u32 min_bits,
1879 				     struct ocfs2_suballoc_result *res)
1880 {
1881 	int status;
1882 	u16 victim, i;
1883 	u16 bits_left = 0;
1884 	u64 hint = ac->ac_last_group;
1885 	struct ocfs2_chain_list *cl;
1886 	struct ocfs2_dinode *fe;
1887 
1888 	BUG_ON(ac->ac_bits_given >= ac->ac_bits_wanted);
1889 	BUG_ON(bits_wanted > (ac->ac_bits_wanted - ac->ac_bits_given));
1890 	BUG_ON(!ac->ac_bh);
1891 
1892 	fe = (struct ocfs2_dinode *) ac->ac_bh->b_data;
1893 
1894 	/* The bh was validated by the inode read during
1895 	 * ocfs2_reserve_suballoc_bits().  Any corruption is a code bug. */
1896 	BUG_ON(!OCFS2_IS_VALID_DINODE(fe));
1897 
1898 	if (le32_to_cpu(fe->id1.bitmap1.i_used) >=
1899 	    le32_to_cpu(fe->id1.bitmap1.i_total)) {
1900 		status = ocfs2_error(ac->ac_inode->i_sb,
1901 				     "Chain allocator dinode %llu has %u used bits but only %u total\n",
1902 				     (unsigned long long)le64_to_cpu(fe->i_blkno),
1903 				     le32_to_cpu(fe->id1.bitmap1.i_used),
1904 				     le32_to_cpu(fe->id1.bitmap1.i_total));
1905 		goto bail;
1906 	}
1907 
1908 	res->sr_bg_blkno = hint;
1909 	if (res->sr_bg_blkno) {
1910 		/* Attempt to short-circuit the usual search mechanism
1911 		 * by jumping straight to the most recently used
1912 		 * allocation group. This helps us maintain some
1913 		 * contiguousness across allocations. */
1914 		status = ocfs2_search_one_group(ac, handle, bits_wanted,
1915 						min_bits, res, &bits_left);
1916 		if (!status)
1917 			goto set_hint;
1918 		if (status < 0 && status != -ENOSPC) {
1919 			mlog_errno(status);
1920 			goto bail;
1921 		}
1922 	}
1923 
1924 	cl = (struct ocfs2_chain_list *) &fe->id2.i_chain;
1925 
1926 	victim = ocfs2_find_victim_chain(cl);
1927 	ac->ac_chain = victim;
1928 
1929 	status = ocfs2_search_chain(ac, handle, bits_wanted, min_bits,
1930 				    res, &bits_left);
1931 	if (!status) {
1932 		if (ocfs2_is_cluster_bitmap(ac->ac_inode))
1933 			hint = res->sr_bg_blkno;
1934 		else
1935 			hint = ocfs2_group_from_res(res);
1936 		goto set_hint;
1937 	}
1938 	if (status < 0 && status != -ENOSPC) {
1939 		mlog_errno(status);
1940 		goto bail;
1941 	}
1942 
1943 	trace_ocfs2_claim_suballoc_bits(victim);
1944 
1945 	/* If we didn't pick a good victim, then just default to
1946 	 * searching each chain in order. Don't allow chain relinking
1947 	 * because we only calculate enough journal credits for one
1948 	 * relink per alloc. */
1949 	ac->ac_disable_chain_relink = 1;
1950 	for (i = 0; i < le16_to_cpu(cl->cl_next_free_rec); i ++) {
1951 		if (i == victim)
1952 			continue;
1953 		if (!cl->cl_recs[i].c_free)
1954 			continue;
1955 
1956 		ac->ac_chain = i;
1957 		status = ocfs2_search_chain(ac, handle, bits_wanted, min_bits,
1958 					    res, &bits_left);
1959 		if (!status) {
1960 			hint = ocfs2_group_from_res(res);
1961 			break;
1962 		}
1963 		if (status < 0 && status != -ENOSPC) {
1964 			mlog_errno(status);
1965 			goto bail;
1966 		}
1967 	}
1968 
1969 set_hint:
1970 	if (status != -ENOSPC) {
1971 		/* If the next search of this group is not likely to
1972 		 * yield a suitable extent, then we reset the last
1973 		 * group hint so as to not waste a disk read */
1974 		if (bits_left < min_bits)
1975 			ac->ac_last_group = 0;
1976 		else
1977 			ac->ac_last_group = hint;
1978 	}
1979 
1980 bail:
1981 	if (status)
1982 		mlog_errno(status);
1983 	return status;
1984 }
1985 
1986 int ocfs2_claim_metadata(handle_t *handle,
1987 			 struct ocfs2_alloc_context *ac,
1988 			 u32 bits_wanted,
1989 			 u64 *suballoc_loc,
1990 			 u16 *suballoc_bit_start,
1991 			 unsigned int *num_bits,
1992 			 u64 *blkno_start)
1993 {
1994 	int status;
1995 	struct ocfs2_suballoc_result res = { .sr_blkno = 0, };
1996 
1997 	BUG_ON(!ac);
1998 	BUG_ON(ac->ac_bits_wanted < (ac->ac_bits_given + bits_wanted));
1999 	BUG_ON(ac->ac_which != OCFS2_AC_USE_META);
2000 
2001 	status = ocfs2_claim_suballoc_bits(ac,
2002 					   handle,
2003 					   bits_wanted,
2004 					   1,
2005 					   &res);
2006 	if (status < 0) {
2007 		mlog_errno(status);
2008 		goto bail;
2009 	}
2010 	atomic_inc(&OCFS2_SB(ac->ac_inode->i_sb)->alloc_stats.bg_allocs);
2011 
2012 	*suballoc_loc = res.sr_bg_blkno;
2013 	*suballoc_bit_start = res.sr_bit_offset;
2014 	*blkno_start = res.sr_blkno;
2015 	ac->ac_bits_given += res.sr_bits;
2016 	*num_bits = res.sr_bits;
2017 	status = 0;
2018 bail:
2019 	if (status)
2020 		mlog_errno(status);
2021 	return status;
2022 }
2023 
2024 static void ocfs2_init_inode_ac_group(struct inode *dir,
2025 				      struct buffer_head *parent_di_bh,
2026 				      struct ocfs2_alloc_context *ac)
2027 {
2028 	struct ocfs2_dinode *di = (struct ocfs2_dinode *)parent_di_bh->b_data;
2029 	/*
2030 	 * Try to allocate inodes from some specific group.
2031 	 *
2032 	 * If the parent dir has recorded the last group used in allocation,
2033 	 * cool, use it. Otherwise if we try to allocate new inode from the
2034 	 * same slot the parent dir belongs to, use the same chunk.
2035 	 *
2036 	 * We are very careful here to avoid the mistake of setting
2037 	 * ac_last_group to a group descriptor from a different (unlocked) slot.
2038 	 */
2039 	if (OCFS2_I(dir)->ip_last_used_group &&
2040 	    OCFS2_I(dir)->ip_last_used_slot == ac->ac_alloc_slot)
2041 		ac->ac_last_group = OCFS2_I(dir)->ip_last_used_group;
2042 	else if (le16_to_cpu(di->i_suballoc_slot) == ac->ac_alloc_slot) {
2043 		if (di->i_suballoc_loc)
2044 			ac->ac_last_group = le64_to_cpu(di->i_suballoc_loc);
2045 		else
2046 			ac->ac_last_group = ocfs2_which_suballoc_group(
2047 					le64_to_cpu(di->i_blkno),
2048 					le16_to_cpu(di->i_suballoc_bit));
2049 	}
2050 }
2051 
2052 static inline void ocfs2_save_inode_ac_group(struct inode *dir,
2053 					     struct ocfs2_alloc_context *ac)
2054 {
2055 	OCFS2_I(dir)->ip_last_used_group = ac->ac_last_group;
2056 	OCFS2_I(dir)->ip_last_used_slot = ac->ac_alloc_slot;
2057 }
2058 
2059 int ocfs2_find_new_inode_loc(struct inode *dir,
2060 			     struct buffer_head *parent_fe_bh,
2061 			     struct ocfs2_alloc_context *ac,
2062 			     u64 *fe_blkno)
2063 {
2064 	int ret;
2065 	handle_t *handle = NULL;
2066 	struct ocfs2_suballoc_result *res;
2067 
2068 	BUG_ON(!ac);
2069 	BUG_ON(ac->ac_bits_given != 0);
2070 	BUG_ON(ac->ac_bits_wanted != 1);
2071 	BUG_ON(ac->ac_which != OCFS2_AC_USE_INODE);
2072 
2073 	res = kzalloc(sizeof(*res), GFP_NOFS);
2074 	if (res == NULL) {
2075 		ret = -ENOMEM;
2076 		mlog_errno(ret);
2077 		goto out;
2078 	}
2079 
2080 	ocfs2_init_inode_ac_group(dir, parent_fe_bh, ac);
2081 
2082 	/*
2083 	 * The handle started here is for chain relink. Alternatively,
2084 	 * we could just disable relink for these calls.
2085 	 */
2086 	handle = ocfs2_start_trans(OCFS2_SB(dir->i_sb), OCFS2_SUBALLOC_ALLOC);
2087 	if (IS_ERR(handle)) {
2088 		ret = PTR_ERR(handle);
2089 		handle = NULL;
2090 		mlog_errno(ret);
2091 		goto out;
2092 	}
2093 
2094 	/*
2095 	 * This will instruct ocfs2_claim_suballoc_bits and
2096 	 * ocfs2_search_one_group to search but save actual allocation
2097 	 * for later.
2098 	 */
2099 	ac->ac_find_loc_only = 1;
2100 
2101 	ret = ocfs2_claim_suballoc_bits(ac, handle, 1, 1, res);
2102 	if (ret < 0) {
2103 		mlog_errno(ret);
2104 		goto out;
2105 	}
2106 
2107 	ac->ac_find_loc_priv = res;
2108 	*fe_blkno = res->sr_blkno;
2109 	ocfs2_update_inode_fsync_trans(handle, dir, 0);
2110 out:
2111 	if (handle)
2112 		ocfs2_commit_trans(OCFS2_SB(dir->i_sb), handle);
2113 
2114 	if (ret)
2115 		kfree(res);
2116 
2117 	return ret;
2118 }
2119 
2120 int ocfs2_claim_new_inode_at_loc(handle_t *handle,
2121 				 struct inode *dir,
2122 				 struct ocfs2_alloc_context *ac,
2123 				 u64 *suballoc_loc,
2124 				 u16 *suballoc_bit,
2125 				 u64 di_blkno)
2126 {
2127 	int ret;
2128 	u16 chain;
2129 	struct ocfs2_suballoc_result *res = ac->ac_find_loc_priv;
2130 	struct buffer_head *bg_bh = NULL;
2131 	struct ocfs2_group_desc *bg;
2132 	struct ocfs2_dinode *di = (struct ocfs2_dinode *) ac->ac_bh->b_data;
2133 
2134 	/*
2135 	 * Since di_blkno is being passed back in, we check for any
2136 	 * inconsistencies which may have happened between
2137 	 * calls. These are code bugs as di_blkno is not expected to
2138 	 * change once returned from ocfs2_find_new_inode_loc()
2139 	 */
2140 	BUG_ON(res->sr_blkno != di_blkno);
2141 
2142 	ret = ocfs2_read_group_descriptor(ac->ac_inode, di,
2143 					  res->sr_bg_stable_blkno, &bg_bh);
2144 	if (ret) {
2145 		mlog_errno(ret);
2146 		goto out;
2147 	}
2148 
2149 	bg = (struct ocfs2_group_desc *) bg_bh->b_data;
2150 	chain = le16_to_cpu(bg->bg_chain);
2151 
2152 	ret = ocfs2_alloc_dinode_update_counts(ac->ac_inode, handle,
2153 					       ac->ac_bh, res->sr_bits,
2154 					       chain);
2155 	if (ret) {
2156 		mlog_errno(ret);
2157 		goto out;
2158 	}
2159 
2160 	ret = ocfs2_block_group_set_bits(handle,
2161 					 ac->ac_inode,
2162 					 bg,
2163 					 bg_bh,
2164 					 res->sr_bit_offset,
2165 					 res->sr_bits);
2166 	if (ret < 0) {
2167 		ocfs2_rollback_alloc_dinode_counts(ac->ac_inode,
2168 					       ac->ac_bh, res->sr_bits, chain);
2169 		mlog_errno(ret);
2170 		goto out;
2171 	}
2172 
2173 	trace_ocfs2_claim_new_inode_at_loc((unsigned long long)di_blkno,
2174 					   res->sr_bits);
2175 
2176 	atomic_inc(&OCFS2_SB(ac->ac_inode->i_sb)->alloc_stats.bg_allocs);
2177 
2178 	BUG_ON(res->sr_bits != 1);
2179 
2180 	*suballoc_loc = res->sr_bg_blkno;
2181 	*suballoc_bit = res->sr_bit_offset;
2182 	ac->ac_bits_given++;
2183 	ocfs2_save_inode_ac_group(dir, ac);
2184 
2185 out:
2186 	brelse(bg_bh);
2187 
2188 	return ret;
2189 }
2190 
2191 int ocfs2_claim_new_inode(handle_t *handle,
2192 			  struct inode *dir,
2193 			  struct buffer_head *parent_fe_bh,
2194 			  struct ocfs2_alloc_context *ac,
2195 			  u64 *suballoc_loc,
2196 			  u16 *suballoc_bit,
2197 			  u64 *fe_blkno)
2198 {
2199 	int status;
2200 	struct ocfs2_suballoc_result res;
2201 
2202 	BUG_ON(!ac);
2203 	BUG_ON(ac->ac_bits_given != 0);
2204 	BUG_ON(ac->ac_bits_wanted != 1);
2205 	BUG_ON(ac->ac_which != OCFS2_AC_USE_INODE);
2206 
2207 	ocfs2_init_inode_ac_group(dir, parent_fe_bh, ac);
2208 
2209 	status = ocfs2_claim_suballoc_bits(ac,
2210 					   handle,
2211 					   1,
2212 					   1,
2213 					   &res);
2214 	if (status < 0) {
2215 		mlog_errno(status);
2216 		goto bail;
2217 	}
2218 	atomic_inc(&OCFS2_SB(ac->ac_inode->i_sb)->alloc_stats.bg_allocs);
2219 
2220 	BUG_ON(res.sr_bits != 1);
2221 
2222 	*suballoc_loc = res.sr_bg_blkno;
2223 	*suballoc_bit = res.sr_bit_offset;
2224 	*fe_blkno = res.sr_blkno;
2225 	ac->ac_bits_given++;
2226 	ocfs2_save_inode_ac_group(dir, ac);
2227 	status = 0;
2228 bail:
2229 	if (status)
2230 		mlog_errno(status);
2231 	return status;
2232 }
2233 
2234 /* translate a group desc. blkno and it's bitmap offset into
2235  * disk cluster offset. */
2236 static inline u32 ocfs2_desc_bitmap_to_cluster_off(struct inode *inode,
2237 						   u64 bg_blkno,
2238 						   u16 bg_bit_off)
2239 {
2240 	struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
2241 	u32 cluster = 0;
2242 
2243 	BUG_ON(!ocfs2_is_cluster_bitmap(inode));
2244 
2245 	if (bg_blkno != osb->first_cluster_group_blkno)
2246 		cluster = ocfs2_blocks_to_clusters(inode->i_sb, bg_blkno);
2247 	cluster += (u32) bg_bit_off;
2248 	return cluster;
2249 }
2250 
2251 /* given a cluster offset, calculate which block group it belongs to
2252  * and return that block offset. */
2253 u64 ocfs2_which_cluster_group(struct inode *inode, u32 cluster)
2254 {
2255 	struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
2256 	u32 group_no;
2257 
2258 	BUG_ON(!ocfs2_is_cluster_bitmap(inode));
2259 
2260 	group_no = cluster / osb->bitmap_cpg;
2261 	if (!group_no)
2262 		return osb->first_cluster_group_blkno;
2263 	return ocfs2_clusters_to_blocks(inode->i_sb,
2264 					group_no * osb->bitmap_cpg);
2265 }
2266 
2267 /* given the block number of a cluster start, calculate which cluster
2268  * group and descriptor bitmap offset that corresponds to. */
2269 static inline void ocfs2_block_to_cluster_group(struct inode *inode,
2270 						u64 data_blkno,
2271 						u64 *bg_blkno,
2272 						u16 *bg_bit_off)
2273 {
2274 	struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
2275 	u32 data_cluster = ocfs2_blocks_to_clusters(osb->sb, data_blkno);
2276 
2277 	BUG_ON(!ocfs2_is_cluster_bitmap(inode));
2278 
2279 	*bg_blkno = ocfs2_which_cluster_group(inode,
2280 					      data_cluster);
2281 
2282 	if (*bg_blkno == osb->first_cluster_group_blkno)
2283 		*bg_bit_off = (u16) data_cluster;
2284 	else
2285 		*bg_bit_off = (u16) ocfs2_blocks_to_clusters(osb->sb,
2286 							     data_blkno - *bg_blkno);
2287 }
2288 
2289 /*
2290  * min_bits - minimum contiguous chunk from this total allocation we
2291  * can handle. set to what we asked for originally for a full
2292  * contig. allocation, set to '1' to indicate we can deal with extents
2293  * of any size.
2294  */
2295 int __ocfs2_claim_clusters(handle_t *handle,
2296 			   struct ocfs2_alloc_context *ac,
2297 			   u32 min_clusters,
2298 			   u32 max_clusters,
2299 			   u32 *cluster_start,
2300 			   u32 *num_clusters)
2301 {
2302 	int status;
2303 	unsigned int bits_wanted = max_clusters;
2304 	struct ocfs2_suballoc_result res = { .sr_blkno = 0, };
2305 	struct ocfs2_super *osb = OCFS2_SB(ac->ac_inode->i_sb);
2306 
2307 	BUG_ON(ac->ac_bits_given >= ac->ac_bits_wanted);
2308 
2309 	BUG_ON(ac->ac_which != OCFS2_AC_USE_LOCAL
2310 	       && ac->ac_which != OCFS2_AC_USE_MAIN);
2311 
2312 	if (ac->ac_which == OCFS2_AC_USE_LOCAL) {
2313 		WARN_ON(min_clusters > 1);
2314 
2315 		status = ocfs2_claim_local_alloc_bits(osb,
2316 						      handle,
2317 						      ac,
2318 						      bits_wanted,
2319 						      cluster_start,
2320 						      num_clusters);
2321 		if (!status)
2322 			atomic_inc(&osb->alloc_stats.local_data);
2323 	} else {
2324 		if (min_clusters > (osb->bitmap_cpg - 1)) {
2325 			/* The only paths asking for contiguousness
2326 			 * should know about this already. */
2327 			mlog(ML_ERROR, "minimum allocation requested %u exceeds "
2328 			     "group bitmap size %u!\n", min_clusters,
2329 			     osb->bitmap_cpg);
2330 			status = -ENOSPC;
2331 			goto bail;
2332 		}
2333 		/* clamp the current request down to a realistic size. */
2334 		if (bits_wanted > (osb->bitmap_cpg - 1))
2335 			bits_wanted = osb->bitmap_cpg - 1;
2336 
2337 		status = ocfs2_claim_suballoc_bits(ac,
2338 						   handle,
2339 						   bits_wanted,
2340 						   min_clusters,
2341 						   &res);
2342 		if (!status) {
2343 			BUG_ON(res.sr_blkno); /* cluster alloc can't set */
2344 			*cluster_start =
2345 				ocfs2_desc_bitmap_to_cluster_off(ac->ac_inode,
2346 								 res.sr_bg_blkno,
2347 								 res.sr_bit_offset);
2348 			atomic_inc(&osb->alloc_stats.bitmap_data);
2349 			*num_clusters = res.sr_bits;
2350 		}
2351 	}
2352 	if (status < 0) {
2353 		if (status != -ENOSPC)
2354 			mlog_errno(status);
2355 		goto bail;
2356 	}
2357 
2358 	ac->ac_bits_given += *num_clusters;
2359 
2360 bail:
2361 	if (status)
2362 		mlog_errno(status);
2363 	return status;
2364 }
2365 
2366 int ocfs2_claim_clusters(handle_t *handle,
2367 			 struct ocfs2_alloc_context *ac,
2368 			 u32 min_clusters,
2369 			 u32 *cluster_start,
2370 			 u32 *num_clusters)
2371 {
2372 	unsigned int bits_wanted = ac->ac_bits_wanted - ac->ac_bits_given;
2373 
2374 	return __ocfs2_claim_clusters(handle, ac, min_clusters,
2375 				      bits_wanted, cluster_start, num_clusters);
2376 }
2377 
2378 static int ocfs2_block_group_clear_bits(handle_t *handle,
2379 					struct inode *alloc_inode,
2380 					struct ocfs2_group_desc *bg,
2381 					struct buffer_head *group_bh,
2382 					unsigned int bit_off,
2383 					unsigned int num_bits,
2384 					void (*undo_fn)(unsigned int bit,
2385 							unsigned long *bmap))
2386 {
2387 	int status;
2388 	unsigned int tmp;
2389 	struct ocfs2_group_desc *undo_bg = NULL;
2390 	struct journal_head *jh;
2391 
2392 	/* The caller got this descriptor from
2393 	 * ocfs2_read_group_descriptor().  Any corruption is a code bug. */
2394 	BUG_ON(!OCFS2_IS_VALID_GROUP_DESC(bg));
2395 
2396 	trace_ocfs2_block_group_clear_bits(bit_off, num_bits);
2397 
2398 	BUG_ON(undo_fn && !ocfs2_is_cluster_bitmap(alloc_inode));
2399 	status = ocfs2_journal_access_gd(handle, INODE_CACHE(alloc_inode),
2400 					 group_bh,
2401 					 undo_fn ?
2402 					 OCFS2_JOURNAL_ACCESS_UNDO :
2403 					 OCFS2_JOURNAL_ACCESS_WRITE);
2404 	if (status < 0) {
2405 		mlog_errno(status);
2406 		goto bail;
2407 	}
2408 
2409 	jh = bh2jh(group_bh);
2410 	if (undo_fn) {
2411 		spin_lock(&jh->b_state_lock);
2412 		undo_bg = (struct ocfs2_group_desc *) jh->b_committed_data;
2413 		BUG_ON(!undo_bg);
2414 	}
2415 
2416 	tmp = num_bits;
2417 	while(tmp--) {
2418 		ocfs2_clear_bit((bit_off + tmp),
2419 				(unsigned long *) bg->bg_bitmap);
2420 		if (undo_fn)
2421 			undo_fn(bit_off + tmp,
2422 				(unsigned long *) undo_bg->bg_bitmap);
2423 	}
2424 	le16_add_cpu(&bg->bg_free_bits_count, num_bits);
2425 	if (le16_to_cpu(bg->bg_free_bits_count) > le16_to_cpu(bg->bg_bits)) {
2426 		if (undo_fn)
2427 			spin_unlock(&jh->b_state_lock);
2428 		return ocfs2_error(alloc_inode->i_sb, "Group descriptor # %llu has bit count %u but claims %u are freed. num_bits %d\n",
2429 				   (unsigned long long)le64_to_cpu(bg->bg_blkno),
2430 				   le16_to_cpu(bg->bg_bits),
2431 				   le16_to_cpu(bg->bg_free_bits_count),
2432 				   num_bits);
2433 	}
2434 
2435 	if (undo_fn)
2436 		spin_unlock(&jh->b_state_lock);
2437 
2438 	ocfs2_journal_dirty(handle, group_bh);
2439 bail:
2440 	return status;
2441 }
2442 
2443 /*
2444  * expects the suballoc inode to already be locked.
2445  */
2446 static int _ocfs2_free_suballoc_bits(handle_t *handle,
2447 				     struct inode *alloc_inode,
2448 				     struct buffer_head *alloc_bh,
2449 				     unsigned int start_bit,
2450 				     u64 bg_blkno,
2451 				     unsigned int count,
2452 				     void (*undo_fn)(unsigned int bit,
2453 						     unsigned long *bitmap))
2454 {
2455 	int status = 0;
2456 	u32 tmp_used;
2457 	struct ocfs2_dinode *fe = (struct ocfs2_dinode *) alloc_bh->b_data;
2458 	struct ocfs2_chain_list *cl = &fe->id2.i_chain;
2459 	struct buffer_head *group_bh = NULL;
2460 	struct ocfs2_group_desc *group;
2461 
2462 	/* The alloc_bh comes from ocfs2_free_dinode() or
2463 	 * ocfs2_free_clusters().  The callers have all locked the
2464 	 * allocator and gotten alloc_bh from the lock call.  This
2465 	 * validates the dinode buffer.  Any corruption that has happened
2466 	 * is a code bug. */
2467 	BUG_ON(!OCFS2_IS_VALID_DINODE(fe));
2468 	BUG_ON((count + start_bit) > ocfs2_bits_per_group(cl));
2469 
2470 	trace_ocfs2_free_suballoc_bits(
2471 		(unsigned long long)OCFS2_I(alloc_inode)->ip_blkno,
2472 		(unsigned long long)bg_blkno,
2473 		start_bit, count);
2474 
2475 	status = ocfs2_read_group_descriptor(alloc_inode, fe, bg_blkno,
2476 					     &group_bh);
2477 	if (status < 0) {
2478 		mlog_errno(status);
2479 		goto bail;
2480 	}
2481 	group = (struct ocfs2_group_desc *) group_bh->b_data;
2482 
2483 	BUG_ON((count + start_bit) > le16_to_cpu(group->bg_bits));
2484 
2485 	status = ocfs2_block_group_clear_bits(handle, alloc_inode,
2486 					      group, group_bh,
2487 					      start_bit, count, undo_fn);
2488 	if (status < 0) {
2489 		mlog_errno(status);
2490 		goto bail;
2491 	}
2492 
2493 	status = ocfs2_journal_access_di(handle, INODE_CACHE(alloc_inode),
2494 					 alloc_bh, OCFS2_JOURNAL_ACCESS_WRITE);
2495 	if (status < 0) {
2496 		mlog_errno(status);
2497 		ocfs2_block_group_set_bits(handle, alloc_inode, group, group_bh,
2498 				start_bit, count);
2499 		goto bail;
2500 	}
2501 
2502 	le32_add_cpu(&cl->cl_recs[le16_to_cpu(group->bg_chain)].c_free,
2503 		     count);
2504 	tmp_used = le32_to_cpu(fe->id1.bitmap1.i_used);
2505 	fe->id1.bitmap1.i_used = cpu_to_le32(tmp_used - count);
2506 	ocfs2_journal_dirty(handle, alloc_bh);
2507 
2508 bail:
2509 	brelse(group_bh);
2510 	return status;
2511 }
2512 
2513 int ocfs2_free_suballoc_bits(handle_t *handle,
2514 			     struct inode *alloc_inode,
2515 			     struct buffer_head *alloc_bh,
2516 			     unsigned int start_bit,
2517 			     u64 bg_blkno,
2518 			     unsigned int count)
2519 {
2520 	return _ocfs2_free_suballoc_bits(handle, alloc_inode, alloc_bh,
2521 					 start_bit, bg_blkno, count, NULL);
2522 }
2523 
2524 int ocfs2_free_dinode(handle_t *handle,
2525 		      struct inode *inode_alloc_inode,
2526 		      struct buffer_head *inode_alloc_bh,
2527 		      struct ocfs2_dinode *di)
2528 {
2529 	u64 blk = le64_to_cpu(di->i_blkno);
2530 	u16 bit = le16_to_cpu(di->i_suballoc_bit);
2531 	u64 bg_blkno = ocfs2_which_suballoc_group(blk, bit);
2532 
2533 	if (di->i_suballoc_loc)
2534 		bg_blkno = le64_to_cpu(di->i_suballoc_loc);
2535 	return ocfs2_free_suballoc_bits(handle, inode_alloc_inode,
2536 					inode_alloc_bh, bit, bg_blkno, 1);
2537 }
2538 
2539 static int _ocfs2_free_clusters(handle_t *handle,
2540 				struct inode *bitmap_inode,
2541 				struct buffer_head *bitmap_bh,
2542 				u64 start_blk,
2543 				unsigned int num_clusters,
2544 				void (*undo_fn)(unsigned int bit,
2545 						unsigned long *bitmap))
2546 {
2547 	int status;
2548 	u16 bg_start_bit;
2549 	u64 bg_blkno;
2550 
2551 	/* You can't ever have a contiguous set of clusters
2552 	 * bigger than a block group bitmap so we never have to worry
2553 	 * about looping on them.
2554 	 * This is expensive. We can safely remove once this stuff has
2555 	 * gotten tested really well. */
2556 	BUG_ON(start_blk != ocfs2_clusters_to_blocks(bitmap_inode->i_sb,
2557 				ocfs2_blocks_to_clusters(bitmap_inode->i_sb,
2558 							 start_blk)));
2559 
2560 
2561 	ocfs2_block_to_cluster_group(bitmap_inode, start_blk, &bg_blkno,
2562 				     &bg_start_bit);
2563 
2564 	trace_ocfs2_free_clusters((unsigned long long)bg_blkno,
2565 			(unsigned long long)start_blk,
2566 			bg_start_bit, num_clusters);
2567 
2568 	status = _ocfs2_free_suballoc_bits(handle, bitmap_inode, bitmap_bh,
2569 					   bg_start_bit, bg_blkno,
2570 					   num_clusters, undo_fn);
2571 	if (status < 0) {
2572 		mlog_errno(status);
2573 		goto out;
2574 	}
2575 
2576 	ocfs2_local_alloc_seen_free_bits(OCFS2_SB(bitmap_inode->i_sb),
2577 					 num_clusters);
2578 
2579 out:
2580 	return status;
2581 }
2582 
2583 int ocfs2_free_clusters(handle_t *handle,
2584 			struct inode *bitmap_inode,
2585 			struct buffer_head *bitmap_bh,
2586 			u64 start_blk,
2587 			unsigned int num_clusters)
2588 {
2589 	return _ocfs2_free_clusters(handle, bitmap_inode, bitmap_bh,
2590 				    start_blk, num_clusters,
2591 				    _ocfs2_set_bit);
2592 }
2593 
2594 /*
2595  * Give never-used clusters back to the global bitmap.  We don't need
2596  * to protect these bits in the undo buffer.
2597  */
2598 int ocfs2_release_clusters(handle_t *handle,
2599 			   struct inode *bitmap_inode,
2600 			   struct buffer_head *bitmap_bh,
2601 			   u64 start_blk,
2602 			   unsigned int num_clusters)
2603 {
2604 	return _ocfs2_free_clusters(handle, bitmap_inode, bitmap_bh,
2605 				    start_blk, num_clusters,
2606 				    _ocfs2_clear_bit);
2607 }
2608 
2609 /*
2610  * For a given allocation, determine which allocators will need to be
2611  * accessed, and lock them, reserving the appropriate number of bits.
2612  *
2613  * Sparse file systems call this from ocfs2_write_begin_nolock()
2614  * and ocfs2_allocate_unwritten_extents().
2615  *
2616  * File systems which don't support holes call this from
2617  * ocfs2_extend_allocation().
2618  */
2619 int ocfs2_lock_allocators(struct inode *inode,
2620 			  struct ocfs2_extent_tree *et,
2621 			  u32 clusters_to_add, u32 extents_to_split,
2622 			  struct ocfs2_alloc_context **data_ac,
2623 			  struct ocfs2_alloc_context **meta_ac)
2624 {
2625 	int ret = 0, num_free_extents;
2626 	unsigned int max_recs_needed = clusters_to_add + 2 * extents_to_split;
2627 	struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
2628 
2629 	*meta_ac = NULL;
2630 	if (data_ac)
2631 		*data_ac = NULL;
2632 
2633 	BUG_ON(clusters_to_add != 0 && data_ac == NULL);
2634 
2635 	num_free_extents = ocfs2_num_free_extents(et);
2636 	if (num_free_extents < 0) {
2637 		ret = num_free_extents;
2638 		mlog_errno(ret);
2639 		goto out;
2640 	}
2641 
2642 	/*
2643 	 * Sparse allocation file systems need to be more conservative
2644 	 * with reserving room for expansion - the actual allocation
2645 	 * happens while we've got a journal handle open so re-taking
2646 	 * a cluster lock (because we ran out of room for another
2647 	 * extent) will violate ordering rules.
2648 	 *
2649 	 * Most of the time we'll only be seeing this 1 cluster at a time
2650 	 * anyway.
2651 	 *
2652 	 * Always lock for any unwritten extents - we might want to
2653 	 * add blocks during a split.
2654 	 */
2655 	if (!num_free_extents ||
2656 	    (ocfs2_sparse_alloc(osb) && num_free_extents < max_recs_needed)) {
2657 		ret = ocfs2_reserve_new_metadata(osb, et->et_root_el, meta_ac);
2658 		if (ret < 0) {
2659 			if (ret != -ENOSPC)
2660 				mlog_errno(ret);
2661 			goto out;
2662 		}
2663 	}
2664 
2665 	if (clusters_to_add == 0)
2666 		goto out;
2667 
2668 	ret = ocfs2_reserve_clusters(osb, clusters_to_add, data_ac);
2669 	if (ret < 0) {
2670 		if (ret != -ENOSPC)
2671 			mlog_errno(ret);
2672 		goto out;
2673 	}
2674 
2675 out:
2676 	if (ret) {
2677 		if (*meta_ac) {
2678 			ocfs2_free_alloc_context(*meta_ac);
2679 			*meta_ac = NULL;
2680 		}
2681 
2682 		/*
2683 		 * We cannot have an error and a non null *data_ac.
2684 		 */
2685 	}
2686 
2687 	return ret;
2688 }
2689 
2690 /*
2691  * Read the inode specified by blkno to get suballoc_slot and
2692  * suballoc_bit.
2693  */
2694 static int ocfs2_get_suballoc_slot_bit(struct ocfs2_super *osb, u64 blkno,
2695 				       u16 *suballoc_slot, u64 *group_blkno,
2696 				       u16 *suballoc_bit)
2697 {
2698 	int status;
2699 	struct buffer_head *inode_bh = NULL;
2700 	struct ocfs2_dinode *inode_fe;
2701 
2702 	trace_ocfs2_get_suballoc_slot_bit((unsigned long long)blkno);
2703 
2704 	/* dirty read disk */
2705 	status = ocfs2_read_blocks_sync(osb, blkno, 1, &inode_bh);
2706 	if (status < 0) {
2707 		mlog(ML_ERROR, "read block %llu failed %d\n",
2708 		     (unsigned long long)blkno, status);
2709 		goto bail;
2710 	}
2711 
2712 	inode_fe = (struct ocfs2_dinode *) inode_bh->b_data;
2713 	if (!OCFS2_IS_VALID_DINODE(inode_fe)) {
2714 		mlog(ML_ERROR, "invalid inode %llu requested\n",
2715 		     (unsigned long long)blkno);
2716 		status = -EINVAL;
2717 		goto bail;
2718 	}
2719 
2720 	if (le16_to_cpu(inode_fe->i_suballoc_slot) != (u16)OCFS2_INVALID_SLOT &&
2721 	    (u32)le16_to_cpu(inode_fe->i_suballoc_slot) > osb->max_slots - 1) {
2722 		mlog(ML_ERROR, "inode %llu has invalid suballoc slot %u\n",
2723 		     (unsigned long long)blkno,
2724 		     (u32)le16_to_cpu(inode_fe->i_suballoc_slot));
2725 		status = -EINVAL;
2726 		goto bail;
2727 	}
2728 
2729 	if (suballoc_slot)
2730 		*suballoc_slot = le16_to_cpu(inode_fe->i_suballoc_slot);
2731 	if (suballoc_bit)
2732 		*suballoc_bit = le16_to_cpu(inode_fe->i_suballoc_bit);
2733 	if (group_blkno)
2734 		*group_blkno = le64_to_cpu(inode_fe->i_suballoc_loc);
2735 
2736 bail:
2737 	brelse(inode_bh);
2738 
2739 	if (status)
2740 		mlog_errno(status);
2741 	return status;
2742 }
2743 
2744 /*
2745  * test whether bit is SET in allocator bitmap or not.  on success, 0
2746  * is returned and *res is 1 for SET; 0 otherwise.  when fails, errno
2747  * is returned and *res is meaningless.  Call this after you have
2748  * cluster locked against suballoc, or you may get a result based on
2749  * non-up2date contents
2750  */
2751 static int ocfs2_test_suballoc_bit(struct ocfs2_super *osb,
2752 				   struct inode *suballoc,
2753 				   struct buffer_head *alloc_bh,
2754 				   u64 group_blkno, u64 blkno,
2755 				   u16 bit, int *res)
2756 {
2757 	struct ocfs2_dinode *alloc_di;
2758 	struct ocfs2_group_desc *group;
2759 	struct buffer_head *group_bh = NULL;
2760 	u64 bg_blkno;
2761 	int status;
2762 
2763 	trace_ocfs2_test_suballoc_bit((unsigned long long)blkno,
2764 				      (unsigned int)bit);
2765 
2766 	alloc_di = (struct ocfs2_dinode *)alloc_bh->b_data;
2767 	if ((bit + 1) > ocfs2_bits_per_group(&alloc_di->id2.i_chain)) {
2768 		mlog(ML_ERROR, "suballoc bit %u out of range of %u\n",
2769 		     (unsigned int)bit,
2770 		     ocfs2_bits_per_group(&alloc_di->id2.i_chain));
2771 		status = -EINVAL;
2772 		goto bail;
2773 	}
2774 
2775 	bg_blkno = group_blkno ? group_blkno :
2776 		   ocfs2_which_suballoc_group(blkno, bit);
2777 	status = ocfs2_read_group_descriptor(suballoc, alloc_di, bg_blkno,
2778 					     &group_bh);
2779 	if (status < 0) {
2780 		mlog(ML_ERROR, "read group %llu failed %d\n",
2781 		     (unsigned long long)bg_blkno, status);
2782 		goto bail;
2783 	}
2784 
2785 	group = (struct ocfs2_group_desc *) group_bh->b_data;
2786 	*res = ocfs2_test_bit(bit, (unsigned long *)group->bg_bitmap);
2787 
2788 bail:
2789 	brelse(group_bh);
2790 
2791 	if (status)
2792 		mlog_errno(status);
2793 	return status;
2794 }
2795 
2796 /*
2797  * Test if the bit representing this inode (blkno) is set in the
2798  * suballocator.
2799  *
2800  * On success, 0 is returned and *res is 1 for SET; 0 otherwise.
2801  *
2802  * In the event of failure, a negative value is returned and *res is
2803  * meaningless.
2804  *
2805  * Callers must make sure to hold nfs_sync_lock to prevent
2806  * ocfs2_delete_inode() on another node from accessing the same
2807  * suballocator concurrently.
2808  */
2809 int ocfs2_test_inode_bit(struct ocfs2_super *osb, u64 blkno, int *res)
2810 {
2811 	int status;
2812 	u64 group_blkno = 0;
2813 	u16 suballoc_bit = 0, suballoc_slot = 0;
2814 	struct inode *inode_alloc_inode;
2815 	struct buffer_head *alloc_bh = NULL;
2816 
2817 	trace_ocfs2_test_inode_bit((unsigned long long)blkno);
2818 
2819 	status = ocfs2_get_suballoc_slot_bit(osb, blkno, &suballoc_slot,
2820 					     &group_blkno, &suballoc_bit);
2821 	if (status < 0) {
2822 		mlog(ML_ERROR, "get alloc slot and bit failed %d\n", status);
2823 		goto bail;
2824 	}
2825 
2826 	if (suballoc_slot == (u16)OCFS2_INVALID_SLOT)
2827 		inode_alloc_inode = ocfs2_get_system_file_inode(osb,
2828 			GLOBAL_INODE_ALLOC_SYSTEM_INODE, suballoc_slot);
2829 	else
2830 		inode_alloc_inode = ocfs2_get_system_file_inode(osb,
2831 			INODE_ALLOC_SYSTEM_INODE, suballoc_slot);
2832 	if (!inode_alloc_inode) {
2833 		/* the error code could be inaccurate, but we are not able to
2834 		 * get the correct one. */
2835 		status = -EINVAL;
2836 		mlog(ML_ERROR, "unable to get alloc inode in slot %u\n",
2837 		     (u32)suballoc_slot);
2838 		goto bail;
2839 	}
2840 
2841 	inode_lock(inode_alloc_inode);
2842 	status = ocfs2_inode_lock(inode_alloc_inode, &alloc_bh, 0);
2843 	if (status < 0) {
2844 		inode_unlock(inode_alloc_inode);
2845 		iput(inode_alloc_inode);
2846 		mlog(ML_ERROR, "lock on alloc inode on slot %u failed %d\n",
2847 		     (u32)suballoc_slot, status);
2848 		goto bail;
2849 	}
2850 
2851 	status = ocfs2_test_suballoc_bit(osb, inode_alloc_inode, alloc_bh,
2852 					 group_blkno, blkno, suballoc_bit, res);
2853 	if (status < 0)
2854 		mlog(ML_ERROR, "test suballoc bit failed %d\n", status);
2855 
2856 	ocfs2_inode_unlock(inode_alloc_inode, 0);
2857 	inode_unlock(inode_alloc_inode);
2858 
2859 	iput(inode_alloc_inode);
2860 	brelse(alloc_bh);
2861 bail:
2862 	if (status)
2863 		mlog_errno(status);
2864 	return status;
2865 }
2866