xref: /linux/fs/ocfs2/dir.c (revision 57f3d89691149f11bfb6c4fef9fca4890def8fb1)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * dir.c
4  *
5  * Creates, reads, walks and deletes directory-nodes
6  *
7  * Copyright (C) 2002, 2004 Oracle.  All rights reserved.
8  *
9  *  Portions of this code from linux/fs/ext3/dir.c
10  *
11  *  Copyright (C) 1992, 1993, 1994, 1995
12  *  Remy Card (card@masi.ibp.fr)
13  *  Laboratoire MASI - Institut Blaise pascal
14  *  Universite Pierre et Marie Curie (Paris VI)
15  *
16  *   from
17  *
18  *   linux/fs/minix/dir.c
19  *
20  *   Copyright (C) 1991, 1992 Linus Torvalds
21  */
22 
23 #include <linux/fs.h>
24 #include <linux/types.h>
25 #include <linux/slab.h>
26 #include <linux/highmem.h>
27 #include <linux/quotaops.h>
28 #include <linux/sort.h>
29 #include <linux/iversion.h>
30 
31 #include <cluster/masklog.h>
32 
33 #include "ocfs2.h"
34 
35 #include "alloc.h"
36 #include "blockcheck.h"
37 #include "dir.h"
38 #include "dlmglue.h"
39 #include "extent_map.h"
40 #include "file.h"
41 #include "inode.h"
42 #include "journal.h"
43 #include "namei.h"
44 #include "suballoc.h"
45 #include "super.h"
46 #include "sysfile.h"
47 #include "uptodate.h"
48 #include "ocfs2_trace.h"
49 
50 #include "buffer_head_io.h"
51 
52 #define NAMEI_RA_CHUNKS  2
53 #define NAMEI_RA_BLOCKS  4
54 #define NAMEI_RA_SIZE        (NAMEI_RA_CHUNKS * NAMEI_RA_BLOCKS)
55 
56 static int ocfs2_do_extend_dir(struct super_block *sb,
57 			       handle_t *handle,
58 			       struct inode *dir,
59 			       struct buffer_head *parent_fe_bh,
60 			       struct ocfs2_alloc_context *data_ac,
61 			       struct ocfs2_alloc_context *meta_ac,
62 			       struct buffer_head **new_bh);
63 static int ocfs2_dir_indexed(struct inode *inode);
64 
65 /*
66  * These are distinct checks because future versions of the file system will
67  * want to have a trailing dirent structure independent of indexing.
68  */
69 static int ocfs2_supports_dir_trailer(struct inode *dir)
70 {
71 	struct ocfs2_super *osb = OCFS2_SB(dir->i_sb);
72 
73 	if (OCFS2_I(dir)->ip_dyn_features & OCFS2_INLINE_DATA_FL)
74 		return 0;
75 
76 	return ocfs2_meta_ecc(osb) || ocfs2_dir_indexed(dir);
77 }
78 
79 /*
80  * "new' here refers to the point at which we're creating a new
81  * directory via "mkdir()", but also when we're expanding an inline
82  * directory. In either case, we don't yet have the indexing bit set
83  * on the directory, so the standard checks will fail in when metaecc
84  * is turned off. Only directory-initialization type functions should
85  * use this then. Everything else wants ocfs2_supports_dir_trailer()
86  */
87 static int ocfs2_new_dir_wants_trailer(struct inode *dir)
88 {
89 	struct ocfs2_super *osb = OCFS2_SB(dir->i_sb);
90 
91 	return ocfs2_meta_ecc(osb) ||
92 		ocfs2_supports_indexed_dirs(osb);
93 }
94 
95 static inline unsigned int ocfs2_dir_trailer_blk_off(struct super_block *sb)
96 {
97 	return sb->s_blocksize - sizeof(struct ocfs2_dir_block_trailer);
98 }
99 
100 #define ocfs2_trailer_from_bh(_bh, _sb) ((struct ocfs2_dir_block_trailer *) ((_bh)->b_data + ocfs2_dir_trailer_blk_off((_sb))))
101 
102 /* XXX ocfs2_block_dqtrailer() is similar but not quite - can we make
103  * them more consistent? */
104 struct ocfs2_dir_block_trailer *ocfs2_dir_trailer_from_size(int blocksize,
105 							    void *data)
106 {
107 	char *p = data;
108 
109 	p += blocksize - sizeof(struct ocfs2_dir_block_trailer);
110 	return (struct ocfs2_dir_block_trailer *)p;
111 }
112 
113 /*
114  * XXX: This is executed once on every dirent. We should consider optimizing
115  * it.
116  */
117 static int ocfs2_skip_dir_trailer(struct inode *dir,
118 				  struct ocfs2_dir_entry *de,
119 				  unsigned long offset,
120 				  unsigned long blklen)
121 {
122 	unsigned long toff = blklen - sizeof(struct ocfs2_dir_block_trailer);
123 
124 	if (!ocfs2_supports_dir_trailer(dir))
125 		return 0;
126 
127 	if (offset != toff)
128 		return 0;
129 
130 	return 1;
131 }
132 
133 static void ocfs2_init_dir_trailer(struct inode *inode,
134 				   struct buffer_head *bh, u16 rec_len)
135 {
136 	struct ocfs2_dir_block_trailer *trailer;
137 
138 	trailer = ocfs2_trailer_from_bh(bh, inode->i_sb);
139 	strcpy(trailer->db_signature, OCFS2_DIR_TRAILER_SIGNATURE);
140 	trailer->db_compat_rec_len =
141 			cpu_to_le16(sizeof(struct ocfs2_dir_block_trailer));
142 	trailer->db_parent_dinode = cpu_to_le64(OCFS2_I(inode)->ip_blkno);
143 	trailer->db_blkno = cpu_to_le64(bh->b_blocknr);
144 	trailer->db_free_rec_len = cpu_to_le16(rec_len);
145 }
146 /*
147  * Link an unindexed block with a dir trailer structure into the index free
148  * list. This function will modify dirdata_bh, but assumes you've already
149  * passed it to the journal.
150  */
151 static int ocfs2_dx_dir_link_trailer(struct inode *dir, handle_t *handle,
152 				     struct buffer_head *dx_root_bh,
153 				     struct buffer_head *dirdata_bh)
154 {
155 	int ret;
156 	struct ocfs2_dx_root_block *dx_root;
157 	struct ocfs2_dir_block_trailer *trailer;
158 
159 	ret = ocfs2_journal_access_dr(handle, INODE_CACHE(dir), dx_root_bh,
160 				      OCFS2_JOURNAL_ACCESS_WRITE);
161 	if (ret) {
162 		mlog_errno(ret);
163 		goto out;
164 	}
165 	trailer = ocfs2_trailer_from_bh(dirdata_bh, dir->i_sb);
166 	dx_root = (struct ocfs2_dx_root_block *)dx_root_bh->b_data;
167 
168 	trailer->db_free_next = dx_root->dr_free_blk;
169 	dx_root->dr_free_blk = cpu_to_le64(dirdata_bh->b_blocknr);
170 
171 	ocfs2_journal_dirty(handle, dx_root_bh);
172 
173 out:
174 	return ret;
175 }
176 
177 static int ocfs2_free_list_at_root(struct ocfs2_dir_lookup_result *res)
178 {
179 	return res->dl_prev_leaf_bh == NULL;
180 }
181 
182 void ocfs2_free_dir_lookup_result(struct ocfs2_dir_lookup_result *res)
183 {
184 	brelse(res->dl_dx_root_bh);
185 	brelse(res->dl_leaf_bh);
186 	brelse(res->dl_dx_leaf_bh);
187 	brelse(res->dl_prev_leaf_bh);
188 }
189 
190 static int ocfs2_dir_indexed(struct inode *inode)
191 {
192 	if (OCFS2_I(inode)->ip_dyn_features & OCFS2_INDEXED_DIR_FL)
193 		return 1;
194 	return 0;
195 }
196 
197 static inline int ocfs2_dx_root_inline(struct ocfs2_dx_root_block *dx_root)
198 {
199 	return dx_root->dr_flags & OCFS2_DX_FLAG_INLINE;
200 }
201 
202 /*
203  * Hashing code adapted from ext3
204  */
205 #define DELTA 0x9E3779B9
206 
207 static void TEA_transform(__u32 buf[4], __u32 const in[])
208 {
209 	__u32	sum = 0;
210 	__u32	b0 = buf[0], b1 = buf[1];
211 	__u32	a = in[0], b = in[1], c = in[2], d = in[3];
212 	int	n = 16;
213 
214 	do {
215 		sum += DELTA;
216 		b0 += ((b1 << 4)+a) ^ (b1+sum) ^ ((b1 >> 5)+b);
217 		b1 += ((b0 << 4)+c) ^ (b0+sum) ^ ((b0 >> 5)+d);
218 	} while (--n);
219 
220 	buf[0] += b0;
221 	buf[1] += b1;
222 }
223 
224 static void str2hashbuf(const char *msg, int len, __u32 *buf, int num)
225 {
226 	__u32	pad, val;
227 	int	i;
228 
229 	pad = (__u32)len | ((__u32)len << 8);
230 	pad |= pad << 16;
231 
232 	val = pad;
233 	if (len > num*4)
234 		len = num * 4;
235 	for (i = 0; i < len; i++) {
236 		if ((i % 4) == 0)
237 			val = pad;
238 		val = msg[i] + (val << 8);
239 		if ((i % 4) == 3) {
240 			*buf++ = val;
241 			val = pad;
242 			num--;
243 		}
244 	}
245 	if (--num >= 0)
246 		*buf++ = val;
247 	while (--num >= 0)
248 		*buf++ = pad;
249 }
250 
251 static void ocfs2_dx_dir_name_hash(struct inode *dir, const char *name, int len,
252 				   struct ocfs2_dx_hinfo *hinfo)
253 {
254 	struct ocfs2_super *osb = OCFS2_SB(dir->i_sb);
255 	const char	*p;
256 	__u32		in[8], buf[4];
257 
258 	/*
259 	 * XXX: Is this really necessary, if the index is never looked
260 	 * at by readdir? Is a hash value of '0' a bad idea?
261 	 */
262 	if ((len == 1 && !strncmp(".", name, 1)) ||
263 	    (len == 2 && !strncmp("..", name, 2))) {
264 		buf[0] = buf[1] = 0;
265 		goto out;
266 	}
267 
268 #ifdef OCFS2_DEBUG_DX_DIRS
269 	/*
270 	 * This makes it very easy to debug indexing problems. We
271 	 * should never allow this to be selected without hand editing
272 	 * this file though.
273 	 */
274 	buf[0] = buf[1] = len;
275 	goto out;
276 #endif
277 
278 	memcpy(buf, osb->osb_dx_seed, sizeof(buf));
279 
280 	p = name;
281 	while (len > 0) {
282 		str2hashbuf(p, len, in, 4);
283 		TEA_transform(buf, in);
284 		len -= 16;
285 		p += 16;
286 	}
287 
288 out:
289 	hinfo->major_hash = buf[0];
290 	hinfo->minor_hash = buf[1];
291 }
292 
293 /*
294  * bh passed here can be an inode block or a dir data block, depending
295  * on the inode inline data flag.
296  */
297 static int ocfs2_check_dir_entry(struct inode *dir,
298 				 struct ocfs2_dir_entry *de,
299 				 struct buffer_head *bh,
300 				 char *buf,
301 				 unsigned int size,
302 				 unsigned long offset)
303 {
304 	const char *error_msg = NULL;
305 	const int rlen = le16_to_cpu(de->rec_len);
306 	const unsigned long next_offset = ((char *) de - buf) + rlen;
307 
308 	if (unlikely(rlen < OCFS2_DIR_REC_LEN(1)))
309 		error_msg = "rec_len is smaller than minimal";
310 	else if (unlikely(rlen % 4 != 0))
311 		error_msg = "rec_len % 4 != 0";
312 	else if (unlikely(rlen < OCFS2_DIR_REC_LEN(de->name_len)))
313 		error_msg = "rec_len is too small for name_len";
314 	else if (unlikely(next_offset > size))
315 		error_msg = "directory entry overrun";
316 	else if (unlikely(next_offset > size - OCFS2_DIR_REC_LEN(1)) &&
317 		 next_offset != size)
318 		error_msg = "directory entry too close to end";
319 
320 	if (unlikely(error_msg != NULL))
321 		mlog(ML_ERROR, "bad entry in directory #%llu: %s - "
322 		     "offset=%lu, inode=%llu, rec_len=%d, name_len=%d\n",
323 		     (unsigned long long)OCFS2_I(dir)->ip_blkno, error_msg,
324 		     offset, (unsigned long long)le64_to_cpu(de->inode), rlen,
325 		     de->name_len);
326 
327 	return error_msg == NULL ? 1 : 0;
328 }
329 
330 static inline int ocfs2_match(int len,
331 			      const char * const name,
332 			      struct ocfs2_dir_entry *de)
333 {
334 	if (len != de->name_len)
335 		return 0;
336 	if (!de->inode)
337 		return 0;
338 	return !memcmp(name, de->name, len);
339 }
340 
341 /*
342  * Returns 0 if not found, -1 on failure, and 1 on success
343  */
344 static inline int ocfs2_search_dirblock(struct buffer_head *bh,
345 					struct inode *dir,
346 					const char *name, int namelen,
347 					unsigned long offset,
348 					char *first_de,
349 					unsigned int bytes,
350 					struct ocfs2_dir_entry **res_dir)
351 {
352 	struct ocfs2_dir_entry *de;
353 	char *dlimit, *de_buf;
354 	int de_len;
355 	int ret = 0;
356 
357 	de_buf = first_de;
358 	dlimit = de_buf + bytes;
359 
360 	while (de_buf < dlimit - OCFS2_DIR_MEMBER_LEN) {
361 		/* this code is executed quadratically often */
362 		/* do minimal checking `by hand' */
363 
364 		de = (struct ocfs2_dir_entry *) de_buf;
365 
366 		if (de->name + namelen <= dlimit &&
367 		    ocfs2_match(namelen, name, de)) {
368 			/* found a match - just to be sure, do a full check */
369 			if (!ocfs2_check_dir_entry(dir, de, bh, first_de,
370 						   bytes, offset)) {
371 				ret = -1;
372 				goto bail;
373 			}
374 			*res_dir = de;
375 			ret = 1;
376 			goto bail;
377 		}
378 
379 		/* prevent looping on a bad block */
380 		de_len = le16_to_cpu(de->rec_len);
381 		if (de_len <= 0) {
382 			ret = -1;
383 			goto bail;
384 		}
385 
386 		de_buf += de_len;
387 		offset += de_len;
388 	}
389 
390 bail:
391 	trace_ocfs2_search_dirblock(ret);
392 	return ret;
393 }
394 
395 static struct buffer_head *ocfs2_find_entry_id(const char *name,
396 					       int namelen,
397 					       struct inode *dir,
398 					       struct ocfs2_dir_entry **res_dir)
399 {
400 	int ret, found;
401 	struct buffer_head *di_bh = NULL;
402 	struct ocfs2_dinode *di;
403 	struct ocfs2_inline_data *data;
404 
405 	ret = ocfs2_read_inode_block(dir, &di_bh);
406 	if (ret) {
407 		mlog_errno(ret);
408 		goto out;
409 	}
410 
411 	di = (struct ocfs2_dinode *)di_bh->b_data;
412 	data = &di->id2.i_data;
413 
414 	found = ocfs2_search_dirblock(di_bh, dir, name, namelen, 0,
415 				      data->id_data, i_size_read(dir), res_dir);
416 	if (found == 1)
417 		return di_bh;
418 
419 	brelse(di_bh);
420 out:
421 	return NULL;
422 }
423 
424 static int ocfs2_validate_dir_block(struct super_block *sb,
425 				    struct buffer_head *bh)
426 {
427 	int rc;
428 	struct ocfs2_dir_block_trailer *trailer =
429 		ocfs2_trailer_from_bh(bh, sb);
430 
431 
432 	/*
433 	 * We don't validate dirents here, that's handled
434 	 * in-place when the code walks them.
435 	 */
436 	trace_ocfs2_validate_dir_block((unsigned long long)bh->b_blocknr);
437 
438 	BUG_ON(!buffer_uptodate(bh));
439 
440 	/*
441 	 * If the ecc fails, we return the error but otherwise
442 	 * leave the filesystem running.  We know any error is
443 	 * local to this block.
444 	 *
445 	 * Note that we are safe to call this even if the directory
446 	 * doesn't have a trailer.  Filesystems without metaecc will do
447 	 * nothing, and filesystems with it will have one.
448 	 */
449 	rc = ocfs2_validate_meta_ecc(sb, bh->b_data, &trailer->db_check);
450 	if (rc)
451 		mlog(ML_ERROR, "Checksum failed for dinode %llu\n",
452 		     (unsigned long long)bh->b_blocknr);
453 
454 	return rc;
455 }
456 
457 /*
458  * Validate a directory trailer.
459  *
460  * We check the trailer here rather than in ocfs2_validate_dir_block()
461  * because that function doesn't have the inode to test.
462  */
463 static int ocfs2_check_dir_trailer(struct inode *dir, struct buffer_head *bh)
464 {
465 	int rc = 0;
466 	struct ocfs2_dir_block_trailer *trailer;
467 
468 	trailer = ocfs2_trailer_from_bh(bh, dir->i_sb);
469 	if (!OCFS2_IS_VALID_DIR_TRAILER(trailer)) {
470 		rc = ocfs2_error(dir->i_sb,
471 				 "Invalid dirblock #%llu: signature = %.*s\n",
472 				 (unsigned long long)bh->b_blocknr, 7,
473 				 trailer->db_signature);
474 		goto out;
475 	}
476 	if (le64_to_cpu(trailer->db_blkno) != bh->b_blocknr) {
477 		rc = ocfs2_error(dir->i_sb,
478 				 "Directory block #%llu has an invalid db_blkno of %llu\n",
479 				 (unsigned long long)bh->b_blocknr,
480 				 (unsigned long long)le64_to_cpu(trailer->db_blkno));
481 		goto out;
482 	}
483 	if (le64_to_cpu(trailer->db_parent_dinode) !=
484 	    OCFS2_I(dir)->ip_blkno) {
485 		rc = ocfs2_error(dir->i_sb,
486 				 "Directory block #%llu on dinode #%llu has an invalid parent_dinode of %llu\n",
487 				 (unsigned long long)bh->b_blocknr,
488 				 (unsigned long long)OCFS2_I(dir)->ip_blkno,
489 				 (unsigned long long)le64_to_cpu(trailer->db_blkno));
490 		goto out;
491 	}
492 out:
493 	return rc;
494 }
495 
496 /*
497  * This function forces all errors to -EIO for consistency with its
498  * predecessor, ocfs2_bread().  We haven't audited what returning the
499  * real error codes would do to callers.  We log the real codes with
500  * mlog_errno() before we squash them.
501  */
502 static int ocfs2_read_dir_block(struct inode *inode, u64 v_block,
503 				struct buffer_head **bh, int flags)
504 {
505 	int rc = 0;
506 	struct buffer_head *tmp = *bh;
507 
508 	rc = ocfs2_read_virt_blocks(inode, v_block, 1, &tmp, flags,
509 				    ocfs2_validate_dir_block);
510 	if (rc) {
511 		mlog_errno(rc);
512 		goto out;
513 	}
514 
515 	if (!(flags & OCFS2_BH_READAHEAD) &&
516 	    ocfs2_supports_dir_trailer(inode)) {
517 		rc = ocfs2_check_dir_trailer(inode, tmp);
518 		if (rc) {
519 			if (!*bh)
520 				brelse(tmp);
521 			mlog_errno(rc);
522 			goto out;
523 		}
524 	}
525 
526 	/* If ocfs2_read_virt_blocks() got us a new bh, pass it up. */
527 	if (!*bh)
528 		*bh = tmp;
529 
530 out:
531 	return rc ? -EIO : 0;
532 }
533 
534 /*
535  * Read the block at 'phys' which belongs to this directory
536  * inode. This function does no virtual->physical block translation -
537  * what's passed in is assumed to be a valid directory block.
538  */
539 static int ocfs2_read_dir_block_direct(struct inode *dir, u64 phys,
540 				       struct buffer_head **bh)
541 {
542 	int ret;
543 	struct buffer_head *tmp = *bh;
544 
545 	ret = ocfs2_read_block(INODE_CACHE(dir), phys, &tmp,
546 			       ocfs2_validate_dir_block);
547 	if (ret) {
548 		mlog_errno(ret);
549 		goto out;
550 	}
551 
552 	if (ocfs2_supports_dir_trailer(dir)) {
553 		ret = ocfs2_check_dir_trailer(dir, tmp);
554 		if (ret) {
555 			if (!*bh)
556 				brelse(tmp);
557 			mlog_errno(ret);
558 			goto out;
559 		}
560 	}
561 
562 	if (!ret && !*bh)
563 		*bh = tmp;
564 out:
565 	return ret;
566 }
567 
568 static int ocfs2_validate_dx_root(struct super_block *sb,
569 				  struct buffer_head *bh)
570 {
571 	int ret;
572 	struct ocfs2_dx_root_block *dx_root;
573 
574 	BUG_ON(!buffer_uptodate(bh));
575 
576 	dx_root = (struct ocfs2_dx_root_block *) bh->b_data;
577 
578 	ret = ocfs2_validate_meta_ecc(sb, bh->b_data, &dx_root->dr_check);
579 	if (ret) {
580 		mlog(ML_ERROR,
581 		     "Checksum failed for dir index root block %llu\n",
582 		     (unsigned long long)bh->b_blocknr);
583 		return ret;
584 	}
585 
586 	if (!OCFS2_IS_VALID_DX_ROOT(dx_root)) {
587 		ret = ocfs2_error(sb,
588 				  "Dir Index Root # %llu has bad signature %.*s\n",
589 				  (unsigned long long)le64_to_cpu(dx_root->dr_blkno),
590 				  7, dx_root->dr_signature);
591 	}
592 
593 	return ret;
594 }
595 
596 static int ocfs2_read_dx_root(struct inode *dir, struct ocfs2_dinode *di,
597 			      struct buffer_head **dx_root_bh)
598 {
599 	int ret;
600 	u64 blkno = le64_to_cpu(di->i_dx_root);
601 	struct buffer_head *tmp = *dx_root_bh;
602 
603 	ret = ocfs2_read_block(INODE_CACHE(dir), blkno, &tmp,
604 			       ocfs2_validate_dx_root);
605 
606 	/* If ocfs2_read_block() got us a new bh, pass it up. */
607 	if (!ret && !*dx_root_bh)
608 		*dx_root_bh = tmp;
609 
610 	return ret;
611 }
612 
613 static int ocfs2_validate_dx_leaf(struct super_block *sb,
614 				  struct buffer_head *bh)
615 {
616 	int ret;
617 	struct ocfs2_dx_leaf *dx_leaf = (struct ocfs2_dx_leaf *)bh->b_data;
618 
619 	BUG_ON(!buffer_uptodate(bh));
620 
621 	ret = ocfs2_validate_meta_ecc(sb, bh->b_data, &dx_leaf->dl_check);
622 	if (ret) {
623 		mlog(ML_ERROR,
624 		     "Checksum failed for dir index leaf block %llu\n",
625 		     (unsigned long long)bh->b_blocknr);
626 		return ret;
627 	}
628 
629 	if (!OCFS2_IS_VALID_DX_LEAF(dx_leaf)) {
630 		ret = ocfs2_error(sb, "Dir Index Leaf has bad signature %.*s\n",
631 				  7, dx_leaf->dl_signature);
632 	}
633 
634 	return ret;
635 }
636 
637 static int ocfs2_read_dx_leaf(struct inode *dir, u64 blkno,
638 			      struct buffer_head **dx_leaf_bh)
639 {
640 	int ret;
641 	struct buffer_head *tmp = *dx_leaf_bh;
642 
643 	ret = ocfs2_read_block(INODE_CACHE(dir), blkno, &tmp,
644 			       ocfs2_validate_dx_leaf);
645 
646 	/* If ocfs2_read_block() got us a new bh, pass it up. */
647 	if (!ret && !*dx_leaf_bh)
648 		*dx_leaf_bh = tmp;
649 
650 	return ret;
651 }
652 
653 /*
654  * Read a series of dx_leaf blocks. This expects all buffer_head
655  * pointers to be NULL on function entry.
656  */
657 static int ocfs2_read_dx_leaves(struct inode *dir, u64 start, int num,
658 				struct buffer_head **dx_leaf_bhs)
659 {
660 	int ret;
661 
662 	ret = ocfs2_read_blocks(INODE_CACHE(dir), start, num, dx_leaf_bhs, 0,
663 				ocfs2_validate_dx_leaf);
664 	if (ret)
665 		mlog_errno(ret);
666 
667 	return ret;
668 }
669 
670 static struct buffer_head *ocfs2_find_entry_el(const char *name, int namelen,
671 					       struct inode *dir,
672 					       struct ocfs2_dir_entry **res_dir)
673 {
674 	struct super_block *sb;
675 	struct buffer_head *bh_use[NAMEI_RA_SIZE];
676 	struct buffer_head *bh, *ret = NULL;
677 	unsigned long start, block, b;
678 	int ra_max = 0;		/* Number of bh's in the readahead
679 				   buffer, bh_use[] */
680 	int ra_ptr = 0;		/* Current index into readahead
681 				   buffer */
682 	int num = 0;
683 	int nblocks, i;
684 
685 	sb = dir->i_sb;
686 
687 	nblocks = i_size_read(dir) >> sb->s_blocksize_bits;
688 	start = OCFS2_I(dir)->ip_dir_start_lookup;
689 	if (start >= nblocks)
690 		start = 0;
691 	block = start;
692 
693 restart:
694 	do {
695 		/*
696 		 * We deal with the read-ahead logic here.
697 		 */
698 		if (ra_ptr >= ra_max) {
699 			/* Refill the readahead buffer */
700 			ra_ptr = 0;
701 			b = block;
702 			for (ra_max = 0; ra_max < NAMEI_RA_SIZE; ra_max++) {
703 				/*
704 				 * Terminate if we reach the end of the
705 				 * directory and must wrap, or if our
706 				 * search has finished at this block.
707 				 */
708 				if (b >= nblocks || (num && block == start)) {
709 					bh_use[ra_max] = NULL;
710 					break;
711 				}
712 				num++;
713 
714 				bh = NULL;
715 				ocfs2_read_dir_block(dir, b++, &bh,
716 							   OCFS2_BH_READAHEAD);
717 				bh_use[ra_max] = bh;
718 			}
719 		}
720 		if ((bh = bh_use[ra_ptr++]) == NULL)
721 			goto next;
722 		if (ocfs2_read_dir_block(dir, block, &bh, 0)) {
723 			/* read error, skip block & hope for the best.
724 			 * ocfs2_read_dir_block() has released the bh. */
725 			mlog(ML_ERROR, "reading directory %llu, "
726 				    "offset %lu\n",
727 				    (unsigned long long)OCFS2_I(dir)->ip_blkno,
728 				    block);
729 			goto next;
730 		}
731 		i = ocfs2_search_dirblock(bh, dir, name, namelen,
732 					  block << sb->s_blocksize_bits,
733 					  bh->b_data, sb->s_blocksize,
734 					  res_dir);
735 		if (i == 1) {
736 			OCFS2_I(dir)->ip_dir_start_lookup = block;
737 			ret = bh;
738 			goto cleanup_and_exit;
739 		} else {
740 			brelse(bh);
741 			if (i < 0)
742 				goto cleanup_and_exit;
743 		}
744 	next:
745 		if (++block >= nblocks)
746 			block = 0;
747 	} while (block != start);
748 
749 	/*
750 	 * If the directory has grown while we were searching, then
751 	 * search the last part of the directory before giving up.
752 	 */
753 	block = nblocks;
754 	nblocks = i_size_read(dir) >> sb->s_blocksize_bits;
755 	if (block < nblocks) {
756 		start = 0;
757 		goto restart;
758 	}
759 
760 cleanup_and_exit:
761 	/* Clean up the read-ahead blocks */
762 	for (; ra_ptr < ra_max; ra_ptr++)
763 		brelse(bh_use[ra_ptr]);
764 
765 	trace_ocfs2_find_entry_el(ret);
766 	return ret;
767 }
768 
769 static int ocfs2_dx_dir_lookup_rec(struct inode *inode,
770 				   struct ocfs2_extent_list *el,
771 				   u32 major_hash,
772 				   u32 *ret_cpos,
773 				   u64 *ret_phys_blkno,
774 				   unsigned int *ret_clen)
775 {
776 	int ret = 0, i, found;
777 	struct buffer_head *eb_bh = NULL;
778 	struct ocfs2_extent_block *eb;
779 	struct ocfs2_extent_rec *rec = NULL;
780 
781 	if (le16_to_cpu(el->l_count) !=
782 	    ocfs2_extent_recs_per_dx_root(inode->i_sb)) {
783 		ret = ocfs2_error(inode->i_sb,
784 				  "Inode %lu has invalid extent list length %u\n",
785 				  inode->i_ino, le16_to_cpu(el->l_count));
786 		goto out;
787 	}
788 
789 	if (el->l_tree_depth) {
790 		ret = ocfs2_find_leaf(INODE_CACHE(inode), el, major_hash,
791 				      &eb_bh);
792 		if (ret) {
793 			mlog_errno(ret);
794 			goto out;
795 		}
796 
797 		eb = (struct ocfs2_extent_block *) eb_bh->b_data;
798 		el = &eb->h_list;
799 
800 		if (el->l_tree_depth) {
801 			ret = ocfs2_error(inode->i_sb,
802 					  "Inode %lu has non zero tree depth in btree tree block %llu\n",
803 					  inode->i_ino,
804 					  (unsigned long long)eb_bh->b_blocknr);
805 			goto out;
806 		}
807 	}
808 
809 	if (le16_to_cpu(el->l_next_free_rec) == 0) {
810 		ret = ocfs2_error(inode->i_sb,
811 				  "Inode %lu has empty extent list at depth %u\n",
812 				  inode->i_ino,
813 				  le16_to_cpu(el->l_tree_depth));
814 		goto out;
815 	}
816 
817 	found = 0;
818 	for (i = le16_to_cpu(el->l_next_free_rec) - 1; i >= 0; i--) {
819 		rec = &el->l_recs[i];
820 
821 		if (le32_to_cpu(rec->e_cpos) <= major_hash) {
822 			found = 1;
823 			break;
824 		}
825 	}
826 
827 	if (!found) {
828 		ret = ocfs2_error(inode->i_sb,
829 				  "Inode %lu has bad extent record (%u, %u, 0) in btree\n",
830 				  inode->i_ino,
831 				  le32_to_cpu(rec->e_cpos),
832 				  ocfs2_rec_clusters(el, rec));
833 		goto out;
834 	}
835 
836 	if (ret_phys_blkno)
837 		*ret_phys_blkno = le64_to_cpu(rec->e_blkno);
838 	if (ret_cpos)
839 		*ret_cpos = le32_to_cpu(rec->e_cpos);
840 	if (ret_clen)
841 		*ret_clen = le16_to_cpu(rec->e_leaf_clusters);
842 
843 out:
844 	brelse(eb_bh);
845 	return ret;
846 }
847 
848 /*
849  * Returns the block index, from the start of the cluster which this
850  * hash belongs too.
851  */
852 static inline unsigned int __ocfs2_dx_dir_hash_idx(struct ocfs2_super *osb,
853 						   u32 minor_hash)
854 {
855 	return minor_hash & osb->osb_dx_mask;
856 }
857 
858 static inline unsigned int ocfs2_dx_dir_hash_idx(struct ocfs2_super *osb,
859 					  struct ocfs2_dx_hinfo *hinfo)
860 {
861 	return __ocfs2_dx_dir_hash_idx(osb, hinfo->minor_hash);
862 }
863 
864 static int ocfs2_dx_dir_lookup(struct inode *inode,
865 			       struct ocfs2_extent_list *el,
866 			       struct ocfs2_dx_hinfo *hinfo,
867 			       u32 *ret_cpos,
868 			       u64 *ret_phys_blkno)
869 {
870 	int ret = 0;
871 	unsigned int cend, clen;
872 	u32 cpos;
873 	u64 blkno;
874 	u32 name_hash = hinfo->major_hash;
875 
876 	ret = ocfs2_dx_dir_lookup_rec(inode, el, name_hash, &cpos, &blkno,
877 				      &clen);
878 	if (ret) {
879 		mlog_errno(ret);
880 		goto out;
881 	}
882 
883 	cend = cpos + clen;
884 	if (name_hash >= cend) {
885 		/* We want the last cluster */
886 		blkno += ocfs2_clusters_to_blocks(inode->i_sb, clen - 1);
887 		cpos += clen - 1;
888 	} else {
889 		blkno += ocfs2_clusters_to_blocks(inode->i_sb,
890 						  name_hash - cpos);
891 		cpos = name_hash;
892 	}
893 
894 	/*
895 	 * We now have the cluster which should hold our entry. To
896 	 * find the exact block from the start of the cluster to
897 	 * search, we take the lower bits of the hash.
898 	 */
899 	blkno += ocfs2_dx_dir_hash_idx(OCFS2_SB(inode->i_sb), hinfo);
900 
901 	if (ret_phys_blkno)
902 		*ret_phys_blkno = blkno;
903 	if (ret_cpos)
904 		*ret_cpos = cpos;
905 
906 out:
907 
908 	return ret;
909 }
910 
911 static int ocfs2_dx_dir_search(const char *name, int namelen,
912 			       struct inode *dir,
913 			       struct ocfs2_dx_root_block *dx_root,
914 			       struct ocfs2_dir_lookup_result *res)
915 {
916 	int ret, i, found;
917 	u64 phys;
918 	struct buffer_head *dx_leaf_bh = NULL;
919 	struct ocfs2_dx_leaf *dx_leaf;
920 	struct ocfs2_dx_entry *dx_entry = NULL;
921 	struct buffer_head *dir_ent_bh = NULL;
922 	struct ocfs2_dir_entry *dir_ent = NULL;
923 	struct ocfs2_dx_hinfo *hinfo = &res->dl_hinfo;
924 	struct ocfs2_extent_list *dr_el;
925 	struct ocfs2_dx_entry_list *entry_list;
926 
927 	ocfs2_dx_dir_name_hash(dir, name, namelen, &res->dl_hinfo);
928 
929 	if (ocfs2_dx_root_inline(dx_root)) {
930 		entry_list = &dx_root->dr_entries;
931 		goto search;
932 	}
933 
934 	dr_el = &dx_root->dr_list;
935 
936 	ret = ocfs2_dx_dir_lookup(dir, dr_el, hinfo, NULL, &phys);
937 	if (ret) {
938 		mlog_errno(ret);
939 		goto out;
940 	}
941 
942 	trace_ocfs2_dx_dir_search((unsigned long long)OCFS2_I(dir)->ip_blkno,
943 				  namelen, name, hinfo->major_hash,
944 				  hinfo->minor_hash, (unsigned long long)phys);
945 
946 	ret = ocfs2_read_dx_leaf(dir, phys, &dx_leaf_bh);
947 	if (ret) {
948 		mlog_errno(ret);
949 		goto out;
950 	}
951 
952 	dx_leaf = (struct ocfs2_dx_leaf *) dx_leaf_bh->b_data;
953 
954 	trace_ocfs2_dx_dir_search_leaf_info(
955 			le16_to_cpu(dx_leaf->dl_list.de_num_used),
956 			le16_to_cpu(dx_leaf->dl_list.de_count));
957 
958 	entry_list = &dx_leaf->dl_list;
959 
960 search:
961 	/*
962 	 * Empty leaf is legal, so no need to check for that.
963 	 */
964 	found = 0;
965 	for (i = 0; i < le16_to_cpu(entry_list->de_num_used); i++) {
966 		dx_entry = &entry_list->de_entries[i];
967 
968 		if (hinfo->major_hash != le32_to_cpu(dx_entry->dx_major_hash)
969 		    || hinfo->minor_hash != le32_to_cpu(dx_entry->dx_minor_hash))
970 			continue;
971 
972 		/*
973 		 * Search unindexed leaf block now. We're not
974 		 * guaranteed to find anything.
975 		 */
976 		ret = ocfs2_read_dir_block_direct(dir,
977 					  le64_to_cpu(dx_entry->dx_dirent_blk),
978 					  &dir_ent_bh);
979 		if (ret) {
980 			mlog_errno(ret);
981 			goto out;
982 		}
983 
984 		/*
985 		 * XXX: We should check the unindexed block here,
986 		 * before using it.
987 		 */
988 
989 		found = ocfs2_search_dirblock(dir_ent_bh, dir, name, namelen,
990 					      0, dir_ent_bh->b_data,
991 					      dir->i_sb->s_blocksize, &dir_ent);
992 		if (found == 1)
993 			break;
994 
995 		if (found == -1) {
996 			/* This means we found a bad directory entry. */
997 			ret = -EIO;
998 			mlog_errno(ret);
999 			goto out;
1000 		}
1001 
1002 		brelse(dir_ent_bh);
1003 		dir_ent_bh = NULL;
1004 	}
1005 
1006 	if (found <= 0) {
1007 		ret = -ENOENT;
1008 		goto out;
1009 	}
1010 
1011 	res->dl_leaf_bh = dir_ent_bh;
1012 	res->dl_entry = dir_ent;
1013 	res->dl_dx_leaf_bh = dx_leaf_bh;
1014 	res->dl_dx_entry = dx_entry;
1015 
1016 	ret = 0;
1017 out:
1018 	if (ret) {
1019 		brelse(dx_leaf_bh);
1020 		brelse(dir_ent_bh);
1021 	}
1022 	return ret;
1023 }
1024 
1025 static int ocfs2_find_entry_dx(const char *name, int namelen,
1026 			       struct inode *dir,
1027 			       struct ocfs2_dir_lookup_result *lookup)
1028 {
1029 	int ret;
1030 	struct buffer_head *di_bh = NULL;
1031 	struct ocfs2_dinode *di;
1032 	struct buffer_head *dx_root_bh = NULL;
1033 	struct ocfs2_dx_root_block *dx_root;
1034 
1035 	ret = ocfs2_read_inode_block(dir, &di_bh);
1036 	if (ret) {
1037 		mlog_errno(ret);
1038 		goto out;
1039 	}
1040 
1041 	di = (struct ocfs2_dinode *)di_bh->b_data;
1042 
1043 	ret = ocfs2_read_dx_root(dir, di, &dx_root_bh);
1044 	if (ret) {
1045 		mlog_errno(ret);
1046 		goto out;
1047 	}
1048 	dx_root = (struct ocfs2_dx_root_block *) dx_root_bh->b_data;
1049 
1050 	ret = ocfs2_dx_dir_search(name, namelen, dir, dx_root, lookup);
1051 	if (ret) {
1052 		if (ret != -ENOENT)
1053 			mlog_errno(ret);
1054 		goto out;
1055 	}
1056 
1057 	lookup->dl_dx_root_bh = dx_root_bh;
1058 	dx_root_bh = NULL;
1059 out:
1060 	brelse(di_bh);
1061 	brelse(dx_root_bh);
1062 	return ret;
1063 }
1064 
1065 /*
1066  * Try to find an entry of the provided name within 'dir'.
1067  *
1068  * If nothing was found, -ENOENT is returned. Otherwise, zero is
1069  * returned and the struct 'res' will contain information useful to
1070  * other directory manipulation functions.
1071  *
1072  * Caller can NOT assume anything about the contents of the
1073  * buffer_heads - they are passed back only so that it can be passed
1074  * into any one of the manipulation functions (add entry, delete
1075  * entry, etc). As an example, bh in the extent directory case is a
1076  * data block, in the inline-data case it actually points to an inode,
1077  * in the indexed directory case, multiple buffers are involved.
1078  */
1079 int ocfs2_find_entry(const char *name, int namelen,
1080 		     struct inode *dir, struct ocfs2_dir_lookup_result *lookup)
1081 {
1082 	struct buffer_head *bh;
1083 	struct ocfs2_dir_entry *res_dir = NULL;
1084 	int ret = 0;
1085 
1086 	if (ocfs2_dir_indexed(dir))
1087 		return ocfs2_find_entry_dx(name, namelen, dir, lookup);
1088 
1089 	if (unlikely(i_size_read(dir) <= 0)) {
1090 		ret = -EFSCORRUPTED;
1091 		mlog_errno(ret);
1092 		goto out;
1093 	}
1094 	/*
1095 	 * The unindexed dir code only uses part of the lookup
1096 	 * structure, so there's no reason to push it down further
1097 	 * than this.
1098 	 */
1099 	if (OCFS2_I(dir)->ip_dyn_features & OCFS2_INLINE_DATA_FL) {
1100 		if (unlikely(i_size_read(dir) > dir->i_sb->s_blocksize)) {
1101 			ret = -EFSCORRUPTED;
1102 			mlog_errno(ret);
1103 			goto out;
1104 		}
1105 		bh = ocfs2_find_entry_id(name, namelen, dir, &res_dir);
1106 	} else {
1107 		bh = ocfs2_find_entry_el(name, namelen, dir, &res_dir);
1108 	}
1109 
1110 	if (bh == NULL)
1111 		return -ENOENT;
1112 
1113 	lookup->dl_leaf_bh = bh;
1114 	lookup->dl_entry = res_dir;
1115 out:
1116 	return ret;
1117 }
1118 
1119 /*
1120  * Update inode number and type of a previously found directory entry.
1121  */
1122 int ocfs2_update_entry(struct inode *dir, handle_t *handle,
1123 		       struct ocfs2_dir_lookup_result *res,
1124 		       struct inode *new_entry_inode)
1125 {
1126 	int ret;
1127 	ocfs2_journal_access_func access = ocfs2_journal_access_db;
1128 	struct ocfs2_dir_entry *de = res->dl_entry;
1129 	struct buffer_head *de_bh = res->dl_leaf_bh;
1130 
1131 	/*
1132 	 * The same code works fine for both inline-data and extent
1133 	 * based directories, so no need to split this up.  The only
1134 	 * difference is the journal_access function.
1135 	 */
1136 
1137 	if (OCFS2_I(dir)->ip_dyn_features & OCFS2_INLINE_DATA_FL)
1138 		access = ocfs2_journal_access_di;
1139 
1140 	ret = access(handle, INODE_CACHE(dir), de_bh,
1141 		     OCFS2_JOURNAL_ACCESS_WRITE);
1142 	if (ret) {
1143 		mlog_errno(ret);
1144 		goto out;
1145 	}
1146 
1147 	de->inode = cpu_to_le64(OCFS2_I(new_entry_inode)->ip_blkno);
1148 	ocfs2_set_de_type(de, new_entry_inode->i_mode);
1149 
1150 	ocfs2_journal_dirty(handle, de_bh);
1151 
1152 out:
1153 	return ret;
1154 }
1155 
1156 /*
1157  * __ocfs2_delete_entry deletes a directory entry by merging it with the
1158  * previous entry
1159  */
1160 static int __ocfs2_delete_entry(handle_t *handle, struct inode *dir,
1161 				struct ocfs2_dir_entry *de_del,
1162 				struct buffer_head *bh, char *first_de,
1163 				unsigned int bytes)
1164 {
1165 	struct ocfs2_dir_entry *de, *pde;
1166 	int i, status = -ENOENT;
1167 	ocfs2_journal_access_func access = ocfs2_journal_access_db;
1168 
1169 	if (OCFS2_I(dir)->ip_dyn_features & OCFS2_INLINE_DATA_FL)
1170 		access = ocfs2_journal_access_di;
1171 
1172 	i = 0;
1173 	pde = NULL;
1174 	de = (struct ocfs2_dir_entry *) first_de;
1175 	while (i < bytes) {
1176 		if (!ocfs2_check_dir_entry(dir, de, bh, first_de, bytes, i)) {
1177 			status = -EIO;
1178 			mlog_errno(status);
1179 			goto bail;
1180 		}
1181 		if (de == de_del)  {
1182 			status = access(handle, INODE_CACHE(dir), bh,
1183 					OCFS2_JOURNAL_ACCESS_WRITE);
1184 			if (status < 0) {
1185 				status = -EIO;
1186 				mlog_errno(status);
1187 				goto bail;
1188 			}
1189 			if (pde)
1190 				le16_add_cpu(&pde->rec_len,
1191 						le16_to_cpu(de->rec_len));
1192 			de->inode = 0;
1193 			inode_inc_iversion(dir);
1194 			ocfs2_journal_dirty(handle, bh);
1195 			goto bail;
1196 		}
1197 		i += le16_to_cpu(de->rec_len);
1198 		pde = de;
1199 		de = (struct ocfs2_dir_entry *)((char *)de + le16_to_cpu(de->rec_len));
1200 	}
1201 bail:
1202 	return status;
1203 }
1204 
1205 static unsigned int ocfs2_figure_dirent_hole(struct ocfs2_dir_entry *de)
1206 {
1207 	unsigned int hole;
1208 
1209 	if (le64_to_cpu(de->inode) == 0)
1210 		hole = le16_to_cpu(de->rec_len);
1211 	else
1212 		hole = le16_to_cpu(de->rec_len) -
1213 			OCFS2_DIR_REC_LEN(de->name_len);
1214 
1215 	return hole;
1216 }
1217 
1218 static int ocfs2_find_max_rec_len(struct super_block *sb,
1219 				  struct buffer_head *dirblock_bh)
1220 {
1221 	int size, this_hole, largest_hole = 0;
1222 	char *trailer, *de_buf, *limit, *start = dirblock_bh->b_data;
1223 	struct ocfs2_dir_entry *de;
1224 
1225 	trailer = (char *)ocfs2_trailer_from_bh(dirblock_bh, sb);
1226 	size = ocfs2_dir_trailer_blk_off(sb);
1227 	limit = start + size;
1228 	de_buf = start;
1229 	de = (struct ocfs2_dir_entry *)de_buf;
1230 	do {
1231 		if (de_buf != trailer) {
1232 			this_hole = ocfs2_figure_dirent_hole(de);
1233 			if (this_hole > largest_hole)
1234 				largest_hole = this_hole;
1235 		}
1236 
1237 		de_buf += le16_to_cpu(de->rec_len);
1238 		de = (struct ocfs2_dir_entry *)de_buf;
1239 	} while (de_buf < limit);
1240 
1241 	if (largest_hole >= OCFS2_DIR_MIN_REC_LEN)
1242 		return largest_hole;
1243 	return 0;
1244 }
1245 
1246 static void ocfs2_dx_list_remove_entry(struct ocfs2_dx_entry_list *entry_list,
1247 				       int index)
1248 {
1249 	int num_used = le16_to_cpu(entry_list->de_num_used);
1250 
1251 	if (num_used == 1 || index == (num_used - 1))
1252 		goto clear;
1253 
1254 	memmove(&entry_list->de_entries[index],
1255 		&entry_list->de_entries[index + 1],
1256 		(num_used - index - 1)*sizeof(struct ocfs2_dx_entry));
1257 clear:
1258 	num_used--;
1259 	memset(&entry_list->de_entries[num_used], 0,
1260 	       sizeof(struct ocfs2_dx_entry));
1261 	entry_list->de_num_used = cpu_to_le16(num_used);
1262 }
1263 
1264 static int ocfs2_delete_entry_dx(handle_t *handle, struct inode *dir,
1265 				 struct ocfs2_dir_lookup_result *lookup)
1266 {
1267 	int ret, index, max_rec_len, add_to_free_list = 0;
1268 	struct buffer_head *dx_root_bh = lookup->dl_dx_root_bh;
1269 	struct buffer_head *leaf_bh = lookup->dl_leaf_bh;
1270 	struct ocfs2_dx_leaf *dx_leaf;
1271 	struct ocfs2_dx_entry *dx_entry = lookup->dl_dx_entry;
1272 	struct ocfs2_dir_block_trailer *trailer;
1273 	struct ocfs2_dx_root_block *dx_root;
1274 	struct ocfs2_dx_entry_list *entry_list;
1275 
1276 	/*
1277 	 * This function gets a bit messy because we might have to
1278 	 * modify the root block, regardless of whether the indexed
1279 	 * entries are stored inline.
1280 	 */
1281 
1282 	/*
1283 	 * *Only* set 'entry_list' here, based on where we're looking
1284 	 * for the indexed entries. Later, we might still want to
1285 	 * journal both blocks, based on free list state.
1286 	 */
1287 	dx_root = (struct ocfs2_dx_root_block *)dx_root_bh->b_data;
1288 	if (ocfs2_dx_root_inline(dx_root)) {
1289 		entry_list = &dx_root->dr_entries;
1290 	} else {
1291 		dx_leaf = (struct ocfs2_dx_leaf *) lookup->dl_dx_leaf_bh->b_data;
1292 		entry_list = &dx_leaf->dl_list;
1293 	}
1294 
1295 	/* Neither of these are a disk corruption - that should have
1296 	 * been caught by lookup, before we got here. */
1297 	BUG_ON(le16_to_cpu(entry_list->de_count) <= 0);
1298 	BUG_ON(le16_to_cpu(entry_list->de_num_used) <= 0);
1299 
1300 	index = (char *)dx_entry - (char *)entry_list->de_entries;
1301 	index /= sizeof(*dx_entry);
1302 
1303 	if (index >= le16_to_cpu(entry_list->de_num_used)) {
1304 		mlog(ML_ERROR, "Dir %llu: Bad dx_entry ptr idx %d, (%p, %p)\n",
1305 		     (unsigned long long)OCFS2_I(dir)->ip_blkno, index,
1306 		     entry_list, dx_entry);
1307 		return -EIO;
1308 	}
1309 
1310 	/*
1311 	 * We know that removal of this dirent will leave enough room
1312 	 * for a new one, so add this block to the free list if it
1313 	 * isn't already there.
1314 	 */
1315 	trailer = ocfs2_trailer_from_bh(leaf_bh, dir->i_sb);
1316 	if (trailer->db_free_rec_len == 0)
1317 		add_to_free_list = 1;
1318 
1319 	/*
1320 	 * Add the block holding our index into the journal before
1321 	 * removing the unindexed entry. If we get an error return
1322 	 * from __ocfs2_delete_entry(), then it hasn't removed the
1323 	 * entry yet. Likewise, successful return means we *must*
1324 	 * remove the indexed entry.
1325 	 *
1326 	 * We're also careful to journal the root tree block here as
1327 	 * the entry count needs to be updated. Also, we might be
1328 	 * adding to the start of the free list.
1329 	 */
1330 	ret = ocfs2_journal_access_dr(handle, INODE_CACHE(dir), dx_root_bh,
1331 				      OCFS2_JOURNAL_ACCESS_WRITE);
1332 	if (ret) {
1333 		mlog_errno(ret);
1334 		goto out;
1335 	}
1336 
1337 	if (!ocfs2_dx_root_inline(dx_root)) {
1338 		ret = ocfs2_journal_access_dl(handle, INODE_CACHE(dir),
1339 					      lookup->dl_dx_leaf_bh,
1340 					      OCFS2_JOURNAL_ACCESS_WRITE);
1341 		if (ret) {
1342 			mlog_errno(ret);
1343 			goto out;
1344 		}
1345 	}
1346 
1347 	trace_ocfs2_delete_entry_dx((unsigned long long)OCFS2_I(dir)->ip_blkno,
1348 				    index);
1349 
1350 	ret = __ocfs2_delete_entry(handle, dir, lookup->dl_entry,
1351 				   leaf_bh, leaf_bh->b_data, leaf_bh->b_size);
1352 	if (ret) {
1353 		mlog_errno(ret);
1354 		goto out;
1355 	}
1356 
1357 	max_rec_len = ocfs2_find_max_rec_len(dir->i_sb, leaf_bh);
1358 	trailer->db_free_rec_len = cpu_to_le16(max_rec_len);
1359 	if (add_to_free_list) {
1360 		trailer->db_free_next = dx_root->dr_free_blk;
1361 		dx_root->dr_free_blk = cpu_to_le64(leaf_bh->b_blocknr);
1362 		ocfs2_journal_dirty(handle, dx_root_bh);
1363 	}
1364 
1365 	/* leaf_bh was journal_accessed for us in __ocfs2_delete_entry */
1366 	ocfs2_journal_dirty(handle, leaf_bh);
1367 
1368 	le32_add_cpu(&dx_root->dr_num_entries, -1);
1369 	ocfs2_journal_dirty(handle, dx_root_bh);
1370 
1371 	ocfs2_dx_list_remove_entry(entry_list, index);
1372 
1373 	if (!ocfs2_dx_root_inline(dx_root))
1374 		ocfs2_journal_dirty(handle, lookup->dl_dx_leaf_bh);
1375 
1376 out:
1377 	return ret;
1378 }
1379 
1380 static inline int ocfs2_delete_entry_id(handle_t *handle,
1381 					struct inode *dir,
1382 					struct ocfs2_dir_entry *de_del,
1383 					struct buffer_head *bh)
1384 {
1385 	int ret;
1386 	struct buffer_head *di_bh = NULL;
1387 	struct ocfs2_dinode *di;
1388 	struct ocfs2_inline_data *data;
1389 
1390 	ret = ocfs2_read_inode_block(dir, &di_bh);
1391 	if (ret) {
1392 		mlog_errno(ret);
1393 		goto out;
1394 	}
1395 
1396 	di = (struct ocfs2_dinode *)di_bh->b_data;
1397 	data = &di->id2.i_data;
1398 
1399 	ret = __ocfs2_delete_entry(handle, dir, de_del, bh, data->id_data,
1400 				   i_size_read(dir));
1401 
1402 	brelse(di_bh);
1403 out:
1404 	return ret;
1405 }
1406 
1407 static inline int ocfs2_delete_entry_el(handle_t *handle,
1408 					struct inode *dir,
1409 					struct ocfs2_dir_entry *de_del,
1410 					struct buffer_head *bh)
1411 {
1412 	return __ocfs2_delete_entry(handle, dir, de_del, bh, bh->b_data,
1413 				    bh->b_size);
1414 }
1415 
1416 /*
1417  * Delete a directory entry. Hide the details of directory
1418  * implementation from the caller.
1419  */
1420 int ocfs2_delete_entry(handle_t *handle,
1421 		       struct inode *dir,
1422 		       struct ocfs2_dir_lookup_result *res)
1423 {
1424 	if (ocfs2_dir_indexed(dir))
1425 		return ocfs2_delete_entry_dx(handle, dir, res);
1426 
1427 	if (OCFS2_I(dir)->ip_dyn_features & OCFS2_INLINE_DATA_FL)
1428 		return ocfs2_delete_entry_id(handle, dir, res->dl_entry,
1429 					     res->dl_leaf_bh);
1430 
1431 	return ocfs2_delete_entry_el(handle, dir, res->dl_entry,
1432 				     res->dl_leaf_bh);
1433 }
1434 
1435 /*
1436  * Check whether 'de' has enough room to hold an entry of
1437  * 'new_rec_len' bytes.
1438  */
1439 static inline int ocfs2_dirent_would_fit(struct ocfs2_dir_entry *de,
1440 					 unsigned int new_rec_len)
1441 {
1442 	unsigned int de_really_used;
1443 
1444 	/* Check whether this is an empty record with enough space */
1445 	if (le64_to_cpu(de->inode) == 0 &&
1446 	    le16_to_cpu(de->rec_len) >= new_rec_len)
1447 		return 1;
1448 
1449 	/*
1450 	 * Record might have free space at the end which we can
1451 	 * use.
1452 	 */
1453 	de_really_used = OCFS2_DIR_REC_LEN(de->name_len);
1454 	if (le16_to_cpu(de->rec_len) >= (de_really_used + new_rec_len))
1455 	    return 1;
1456 
1457 	return 0;
1458 }
1459 
1460 static void ocfs2_dx_dir_leaf_insert_tail(struct ocfs2_dx_leaf *dx_leaf,
1461 					  struct ocfs2_dx_entry *dx_new_entry)
1462 {
1463 	int i;
1464 
1465 	i = le16_to_cpu(dx_leaf->dl_list.de_num_used);
1466 	dx_leaf->dl_list.de_entries[i] = *dx_new_entry;
1467 
1468 	le16_add_cpu(&dx_leaf->dl_list.de_num_used, 1);
1469 }
1470 
1471 static void ocfs2_dx_entry_list_insert(struct ocfs2_dx_entry_list *entry_list,
1472 				       struct ocfs2_dx_hinfo *hinfo,
1473 				       u64 dirent_blk)
1474 {
1475 	int i;
1476 	struct ocfs2_dx_entry *dx_entry;
1477 
1478 	i = le16_to_cpu(entry_list->de_num_used);
1479 	dx_entry = &entry_list->de_entries[i];
1480 
1481 	memset(dx_entry, 0, sizeof(*dx_entry));
1482 	dx_entry->dx_major_hash = cpu_to_le32(hinfo->major_hash);
1483 	dx_entry->dx_minor_hash = cpu_to_le32(hinfo->minor_hash);
1484 	dx_entry->dx_dirent_blk = cpu_to_le64(dirent_blk);
1485 
1486 	le16_add_cpu(&entry_list->de_num_used, 1);
1487 }
1488 
1489 static int __ocfs2_dx_dir_leaf_insert(struct inode *dir, handle_t *handle,
1490 				      struct ocfs2_dx_hinfo *hinfo,
1491 				      u64 dirent_blk,
1492 				      struct buffer_head *dx_leaf_bh)
1493 {
1494 	int ret;
1495 	struct ocfs2_dx_leaf *dx_leaf;
1496 
1497 	ret = ocfs2_journal_access_dl(handle, INODE_CACHE(dir), dx_leaf_bh,
1498 				      OCFS2_JOURNAL_ACCESS_WRITE);
1499 	if (ret) {
1500 		mlog_errno(ret);
1501 		goto out;
1502 	}
1503 
1504 	dx_leaf = (struct ocfs2_dx_leaf *)dx_leaf_bh->b_data;
1505 	ocfs2_dx_entry_list_insert(&dx_leaf->dl_list, hinfo, dirent_blk);
1506 	ocfs2_journal_dirty(handle, dx_leaf_bh);
1507 
1508 out:
1509 	return ret;
1510 }
1511 
1512 static void ocfs2_dx_inline_root_insert(struct inode *dir, handle_t *handle,
1513 					struct ocfs2_dx_hinfo *hinfo,
1514 					u64 dirent_blk,
1515 					struct ocfs2_dx_root_block *dx_root)
1516 {
1517 	ocfs2_dx_entry_list_insert(&dx_root->dr_entries, hinfo, dirent_blk);
1518 }
1519 
1520 static int ocfs2_dx_dir_insert(struct inode *dir, handle_t *handle,
1521 			       struct ocfs2_dir_lookup_result *lookup)
1522 {
1523 	int ret = 0;
1524 	struct ocfs2_dx_root_block *dx_root;
1525 	struct buffer_head *dx_root_bh = lookup->dl_dx_root_bh;
1526 
1527 	ret = ocfs2_journal_access_dr(handle, INODE_CACHE(dir), dx_root_bh,
1528 				      OCFS2_JOURNAL_ACCESS_WRITE);
1529 	if (ret) {
1530 		mlog_errno(ret);
1531 		goto out;
1532 	}
1533 
1534 	dx_root = (struct ocfs2_dx_root_block *)lookup->dl_dx_root_bh->b_data;
1535 	if (ocfs2_dx_root_inline(dx_root)) {
1536 		ocfs2_dx_inline_root_insert(dir, handle,
1537 					    &lookup->dl_hinfo,
1538 					    lookup->dl_leaf_bh->b_blocknr,
1539 					    dx_root);
1540 	} else {
1541 		ret = __ocfs2_dx_dir_leaf_insert(dir, handle, &lookup->dl_hinfo,
1542 						 lookup->dl_leaf_bh->b_blocknr,
1543 						 lookup->dl_dx_leaf_bh);
1544 		if (ret)
1545 			goto out;
1546 	}
1547 
1548 	le32_add_cpu(&dx_root->dr_num_entries, 1);
1549 	ocfs2_journal_dirty(handle, dx_root_bh);
1550 
1551 out:
1552 	return ret;
1553 }
1554 
1555 static void ocfs2_remove_block_from_free_list(struct inode *dir,
1556 				       handle_t *handle,
1557 				       struct ocfs2_dir_lookup_result *lookup)
1558 {
1559 	struct ocfs2_dir_block_trailer *trailer, *prev;
1560 	struct ocfs2_dx_root_block *dx_root;
1561 	struct buffer_head *bh;
1562 
1563 	trailer = ocfs2_trailer_from_bh(lookup->dl_leaf_bh, dir->i_sb);
1564 
1565 	if (ocfs2_free_list_at_root(lookup)) {
1566 		bh = lookup->dl_dx_root_bh;
1567 		dx_root = (struct ocfs2_dx_root_block *)bh->b_data;
1568 		dx_root->dr_free_blk = trailer->db_free_next;
1569 	} else {
1570 		bh = lookup->dl_prev_leaf_bh;
1571 		prev = ocfs2_trailer_from_bh(bh, dir->i_sb);
1572 		prev->db_free_next = trailer->db_free_next;
1573 	}
1574 
1575 	trailer->db_free_rec_len = cpu_to_le16(0);
1576 	trailer->db_free_next = cpu_to_le64(0);
1577 
1578 	ocfs2_journal_dirty(handle, bh);
1579 	ocfs2_journal_dirty(handle, lookup->dl_leaf_bh);
1580 }
1581 
1582 /*
1583  * This expects that a journal write has been reserved on
1584  * lookup->dl_prev_leaf_bh or lookup->dl_dx_root_bh
1585  */
1586 static void ocfs2_recalc_free_list(struct inode *dir, handle_t *handle,
1587 				   struct ocfs2_dir_lookup_result *lookup)
1588 {
1589 	int max_rec_len;
1590 	struct ocfs2_dir_block_trailer *trailer;
1591 
1592 	/* Walk dl_leaf_bh to figure out what the new free rec_len is. */
1593 	max_rec_len = ocfs2_find_max_rec_len(dir->i_sb, lookup->dl_leaf_bh);
1594 	if (max_rec_len) {
1595 		/*
1596 		 * There's still room in this block, so no need to remove it
1597 		 * from the free list. In this case, we just want to update
1598 		 * the rec len accounting.
1599 		 */
1600 		trailer = ocfs2_trailer_from_bh(lookup->dl_leaf_bh, dir->i_sb);
1601 		trailer->db_free_rec_len = cpu_to_le16(max_rec_len);
1602 		ocfs2_journal_dirty(handle, lookup->dl_leaf_bh);
1603 	} else {
1604 		ocfs2_remove_block_from_free_list(dir, handle, lookup);
1605 	}
1606 }
1607 
1608 /* we don't always have a dentry for what we want to add, so people
1609  * like orphan dir can call this instead.
1610  *
1611  * The lookup context must have been filled from
1612  * ocfs2_prepare_dir_for_insert.
1613  */
1614 int __ocfs2_add_entry(handle_t *handle,
1615 		      struct inode *dir,
1616 		      const char *name, int namelen,
1617 		      struct inode *inode, u64 blkno,
1618 		      struct buffer_head *parent_fe_bh,
1619 		      struct ocfs2_dir_lookup_result *lookup)
1620 {
1621 	unsigned long offset;
1622 	unsigned short rec_len;
1623 	struct ocfs2_dir_entry *de, *de1;
1624 	struct ocfs2_dinode *di = (struct ocfs2_dinode *)parent_fe_bh->b_data;
1625 	struct super_block *sb = dir->i_sb;
1626 	int retval;
1627 	unsigned int size = sb->s_blocksize;
1628 	struct buffer_head *insert_bh = lookup->dl_leaf_bh;
1629 	char *data_start = insert_bh->b_data;
1630 
1631 	if (ocfs2_dir_indexed(dir)) {
1632 		struct buffer_head *bh;
1633 
1634 		/*
1635 		 * An indexed dir may require that we update the free space
1636 		 * list. Reserve a write to the previous node in the list so
1637 		 * that we don't fail later.
1638 		 *
1639 		 * XXX: This can be either a dx_root_block, or an unindexed
1640 		 * directory tree leaf block.
1641 		 */
1642 		if (ocfs2_free_list_at_root(lookup)) {
1643 			bh = lookup->dl_dx_root_bh;
1644 			retval = ocfs2_journal_access_dr(handle,
1645 						 INODE_CACHE(dir), bh,
1646 						 OCFS2_JOURNAL_ACCESS_WRITE);
1647 		} else {
1648 			bh = lookup->dl_prev_leaf_bh;
1649 			retval = ocfs2_journal_access_db(handle,
1650 						 INODE_CACHE(dir), bh,
1651 						 OCFS2_JOURNAL_ACCESS_WRITE);
1652 		}
1653 		if (retval) {
1654 			mlog_errno(retval);
1655 			return retval;
1656 		}
1657 	} else if (OCFS2_I(dir)->ip_dyn_features & OCFS2_INLINE_DATA_FL) {
1658 		data_start = di->id2.i_data.id_data;
1659 		size = i_size_read(dir);
1660 
1661 		BUG_ON(insert_bh != parent_fe_bh);
1662 	}
1663 
1664 	rec_len = OCFS2_DIR_REC_LEN(namelen);
1665 	offset = 0;
1666 	de = (struct ocfs2_dir_entry *) data_start;
1667 	while (1) {
1668 		BUG_ON((char *)de >= (size + data_start));
1669 
1670 		/* These checks should've already been passed by the
1671 		 * prepare function, but I guess we can leave them
1672 		 * here anyway. */
1673 		if (!ocfs2_check_dir_entry(dir, de, insert_bh, data_start,
1674 					   size, offset)) {
1675 			retval = -ENOENT;
1676 			goto bail;
1677 		}
1678 		if (ocfs2_match(namelen, name, de)) {
1679 			retval = -EEXIST;
1680 			goto bail;
1681 		}
1682 
1683 		/* We're guaranteed that we should have space, so we
1684 		 * can't possibly have hit the trailer...right? */
1685 		mlog_bug_on_msg(ocfs2_skip_dir_trailer(dir, de, offset, size),
1686 				"Hit dir trailer trying to insert %.*s "
1687 			        "(namelen %d) into directory %llu.  "
1688 				"offset is %lu, trailer offset is %d\n",
1689 				namelen, name, namelen,
1690 				(unsigned long long)parent_fe_bh->b_blocknr,
1691 				offset, ocfs2_dir_trailer_blk_off(dir->i_sb));
1692 
1693 		if (ocfs2_dirent_would_fit(de, rec_len)) {
1694 			inode_set_mtime_to_ts(dir,
1695 					      inode_set_ctime_current(dir));
1696 			retval = ocfs2_mark_inode_dirty(handle, dir, parent_fe_bh);
1697 			if (retval < 0) {
1698 				mlog_errno(retval);
1699 				goto bail;
1700 			}
1701 
1702 			if (insert_bh == parent_fe_bh)
1703 				retval = ocfs2_journal_access_di(handle,
1704 								 INODE_CACHE(dir),
1705 								 insert_bh,
1706 								 OCFS2_JOURNAL_ACCESS_WRITE);
1707 			else {
1708 				retval = ocfs2_journal_access_db(handle,
1709 								 INODE_CACHE(dir),
1710 								 insert_bh,
1711 					      OCFS2_JOURNAL_ACCESS_WRITE);
1712 
1713 				if (!retval && ocfs2_dir_indexed(dir))
1714 					retval = ocfs2_dx_dir_insert(dir,
1715 								handle,
1716 								lookup);
1717 			}
1718 
1719 			if (retval) {
1720 				mlog_errno(retval);
1721 				goto bail;
1722 			}
1723 
1724 			/* By now the buffer is marked for journaling */
1725 			offset += le16_to_cpu(de->rec_len);
1726 			if (le64_to_cpu(de->inode)) {
1727 				de1 = (struct ocfs2_dir_entry *)((char *) de +
1728 					OCFS2_DIR_REC_LEN(de->name_len));
1729 				de1->rec_len =
1730 					cpu_to_le16(le16_to_cpu(de->rec_len) -
1731 					OCFS2_DIR_REC_LEN(de->name_len));
1732 				de->rec_len = cpu_to_le16(OCFS2_DIR_REC_LEN(de->name_len));
1733 				de = de1;
1734 			}
1735 			de->file_type = FT_UNKNOWN;
1736 			if (blkno) {
1737 				de->inode = cpu_to_le64(blkno);
1738 				ocfs2_set_de_type(de, inode->i_mode);
1739 			} else
1740 				de->inode = 0;
1741 			de->name_len = namelen;
1742 			memcpy(de->name, name, namelen);
1743 
1744 			if (ocfs2_dir_indexed(dir))
1745 				ocfs2_recalc_free_list(dir, handle, lookup);
1746 
1747 			inode_inc_iversion(dir);
1748 			ocfs2_journal_dirty(handle, insert_bh);
1749 			retval = 0;
1750 			goto bail;
1751 		}
1752 
1753 		offset += le16_to_cpu(de->rec_len);
1754 		de = (struct ocfs2_dir_entry *) ((char *) de + le16_to_cpu(de->rec_len));
1755 	}
1756 
1757 	/* when you think about it, the assert above should prevent us
1758 	 * from ever getting here. */
1759 	retval = -ENOSPC;
1760 bail:
1761 	if (retval)
1762 		mlog_errno(retval);
1763 
1764 	return retval;
1765 }
1766 
1767 static int ocfs2_dir_foreach_blk_id(struct inode *inode,
1768 				    u64 *f_version,
1769 				    struct dir_context *ctx)
1770 {
1771 	int ret, i;
1772 	unsigned long offset = ctx->pos;
1773 	struct buffer_head *di_bh = NULL;
1774 	struct ocfs2_dinode *di;
1775 	struct ocfs2_inline_data *data;
1776 	struct ocfs2_dir_entry *de;
1777 
1778 	ret = ocfs2_read_inode_block(inode, &di_bh);
1779 	if (ret) {
1780 		mlog(ML_ERROR, "Unable to read inode block for dir %llu\n",
1781 		     (unsigned long long)OCFS2_I(inode)->ip_blkno);
1782 		goto out;
1783 	}
1784 
1785 	di = (struct ocfs2_dinode *)di_bh->b_data;
1786 	data = &di->id2.i_data;
1787 
1788 	while (ctx->pos < i_size_read(inode)) {
1789 		/* If the dir block has changed since the last call to
1790 		 * readdir(2), then we might be pointing to an invalid
1791 		 * dirent right now.  Scan from the start of the block
1792 		 * to make sure. */
1793 		if (!inode_eq_iversion(inode, *f_version)) {
1794 			for (i = 0; i < i_size_read(inode) && i < offset; ) {
1795 				de = (struct ocfs2_dir_entry *)
1796 					(data->id_data + i);
1797 				/* It's too expensive to do a full
1798 				 * dirent test each time round this
1799 				 * loop, but we do have to test at
1800 				 * least that it is non-zero.  A
1801 				 * failure will be detected in the
1802 				 * dirent test below. */
1803 				if (le16_to_cpu(de->rec_len) <
1804 				    OCFS2_DIR_REC_LEN(1))
1805 					break;
1806 				i += le16_to_cpu(de->rec_len);
1807 			}
1808 			ctx->pos = offset = i;
1809 			*f_version = inode_query_iversion(inode);
1810 		}
1811 
1812 		de = (struct ocfs2_dir_entry *) (data->id_data + ctx->pos);
1813 		if (!ocfs2_check_dir_entry(inode, de, di_bh, (char *)data->id_data,
1814 					   i_size_read(inode), ctx->pos)) {
1815 			/* On error, skip the f_pos to the end. */
1816 			ctx->pos = i_size_read(inode);
1817 			break;
1818 		}
1819 		offset += le16_to_cpu(de->rec_len);
1820 		if (le64_to_cpu(de->inode)) {
1821 			if (!dir_emit(ctx, de->name, de->name_len,
1822 				      le64_to_cpu(de->inode),
1823 				      fs_ftype_to_dtype(de->file_type)))
1824 				goto out;
1825 		}
1826 		ctx->pos += le16_to_cpu(de->rec_len);
1827 	}
1828 out:
1829 	brelse(di_bh);
1830 	return 0;
1831 }
1832 
1833 /*
1834  * NOTE: This function can be called against unindexed directories,
1835  * and indexed ones.
1836  */
1837 static int ocfs2_dir_foreach_blk_el(struct inode *inode,
1838 				    u64 *f_version,
1839 				    struct dir_context *ctx,
1840 				    bool persist)
1841 {
1842 	unsigned long offset, blk, last_ra_blk = 0;
1843 	int i;
1844 	struct buffer_head * bh, * tmp;
1845 	struct ocfs2_dir_entry * de;
1846 	struct super_block * sb = inode->i_sb;
1847 	unsigned int ra_sectors = 16;
1848 	int stored = 0;
1849 
1850 	bh = NULL;
1851 
1852 	offset = ctx->pos & (sb->s_blocksize - 1);
1853 
1854 	while (ctx->pos < i_size_read(inode)) {
1855 		blk = ctx->pos >> sb->s_blocksize_bits;
1856 		if (ocfs2_read_dir_block(inode, blk, &bh, 0)) {
1857 			/* Skip the corrupt dirblock and keep trying */
1858 			ctx->pos += sb->s_blocksize - offset;
1859 			continue;
1860 		}
1861 
1862 		/* The idea here is to begin with 8k read-ahead and to stay
1863 		 * 4k ahead of our current position.
1864 		 *
1865 		 * TODO: Use the pagecache for this. We just need to
1866 		 * make sure it's cluster-safe... */
1867 		if (!last_ra_blk
1868 		    || (((last_ra_blk - blk) << 9) <= (ra_sectors / 2))) {
1869 			for (i = ra_sectors >> (sb->s_blocksize_bits - 9);
1870 			     i > 0; i--) {
1871 				tmp = NULL;
1872 				if (!ocfs2_read_dir_block(inode, ++blk, &tmp,
1873 							  OCFS2_BH_READAHEAD))
1874 					brelse(tmp);
1875 			}
1876 			last_ra_blk = blk;
1877 			ra_sectors = 8;
1878 		}
1879 
1880 		/* If the dir block has changed since the last call to
1881 		 * readdir(2), then we might be pointing to an invalid
1882 		 * dirent right now.  Scan from the start of the block
1883 		 * to make sure. */
1884 		if (!inode_eq_iversion(inode, *f_version)) {
1885 			for (i = 0; i < sb->s_blocksize && i < offset; ) {
1886 				de = (struct ocfs2_dir_entry *) (bh->b_data + i);
1887 				/* It's too expensive to do a full
1888 				 * dirent test each time round this
1889 				 * loop, but we do have to test at
1890 				 * least that it is non-zero.  A
1891 				 * failure will be detected in the
1892 				 * dirent test below. */
1893 				if (le16_to_cpu(de->rec_len) <
1894 				    OCFS2_DIR_REC_LEN(1))
1895 					break;
1896 				i += le16_to_cpu(de->rec_len);
1897 			}
1898 			offset = i;
1899 			ctx->pos = (ctx->pos & ~(sb->s_blocksize - 1))
1900 				| offset;
1901 			*f_version = inode_query_iversion(inode);
1902 		}
1903 
1904 		while (ctx->pos < i_size_read(inode)
1905 		       && offset < sb->s_blocksize) {
1906 			de = (struct ocfs2_dir_entry *) (bh->b_data + offset);
1907 			if (!ocfs2_check_dir_entry(inode, de, bh, bh->b_data,
1908 						   sb->s_blocksize, offset)) {
1909 				/* On error, skip the f_pos to the
1910 				   next block. */
1911 				ctx->pos = (ctx->pos | (sb->s_blocksize - 1)) + 1;
1912 				break;
1913 			}
1914 			if (le64_to_cpu(de->inode)) {
1915 				if (!dir_emit(ctx, de->name,
1916 						de->name_len,
1917 						le64_to_cpu(de->inode),
1918 					fs_ftype_to_dtype(de->file_type))) {
1919 					brelse(bh);
1920 					return 0;
1921 				}
1922 				stored++;
1923 			}
1924 			offset += le16_to_cpu(de->rec_len);
1925 			ctx->pos += le16_to_cpu(de->rec_len);
1926 		}
1927 		offset = 0;
1928 		brelse(bh);
1929 		bh = NULL;
1930 		if (!persist && stored)
1931 			break;
1932 	}
1933 	return 0;
1934 }
1935 
1936 static int ocfs2_dir_foreach_blk(struct inode *inode, u64 *f_version,
1937 				 struct dir_context *ctx,
1938 				 bool persist)
1939 {
1940 	if (OCFS2_I(inode)->ip_dyn_features & OCFS2_INLINE_DATA_FL)
1941 		return ocfs2_dir_foreach_blk_id(inode, f_version, ctx);
1942 	return ocfs2_dir_foreach_blk_el(inode, f_version, ctx, persist);
1943 }
1944 
1945 /*
1946  * This is intended to be called from inside other kernel functions,
1947  * so we fake some arguments.
1948  */
1949 int ocfs2_dir_foreach(struct inode *inode, struct dir_context *ctx)
1950 {
1951 	u64 version = inode_query_iversion(inode);
1952 	ocfs2_dir_foreach_blk(inode, &version, ctx, true);
1953 	return 0;
1954 }
1955 
1956 /*
1957  * ocfs2_readdir()
1958  *
1959  */
1960 int ocfs2_readdir(struct file *file, struct dir_context *ctx)
1961 {
1962 	int error = 0;
1963 	struct inode *inode = file_inode(file);
1964 	struct ocfs2_file_private *fp = file->private_data;
1965 	int lock_level = 0;
1966 
1967 	trace_ocfs2_readdir((unsigned long long)OCFS2_I(inode)->ip_blkno);
1968 
1969 	error = ocfs2_inode_lock_atime(inode, file->f_path.mnt, &lock_level, 1);
1970 	if (lock_level && error >= 0) {
1971 		/* We release EX lock which used to update atime
1972 		 * and get PR lock again to reduce contention
1973 		 * on commonly accessed directories. */
1974 		ocfs2_inode_unlock(inode, 1);
1975 		lock_level = 0;
1976 		error = ocfs2_inode_lock(inode, NULL, 0);
1977 	}
1978 	if (error < 0) {
1979 		if (error != -ENOENT)
1980 			mlog_errno(error);
1981 		/* we haven't got any yet, so propagate the error. */
1982 		goto bail_nolock;
1983 	}
1984 
1985 	error = ocfs2_dir_foreach_blk(inode, &fp->cookie, ctx, false);
1986 
1987 	ocfs2_inode_unlock(inode, lock_level);
1988 	if (error)
1989 		mlog_errno(error);
1990 
1991 bail_nolock:
1992 
1993 	return error;
1994 }
1995 
1996 /*
1997  * NOTE: this should always be called with parent dir i_rwsem taken.
1998  */
1999 int ocfs2_find_files_on_disk(const char *name,
2000 			     int namelen,
2001 			     u64 *blkno,
2002 			     struct inode *inode,
2003 			     struct ocfs2_dir_lookup_result *lookup)
2004 {
2005 	int status = -ENOENT;
2006 
2007 	trace_ocfs2_find_files_on_disk(namelen, name, blkno,
2008 				(unsigned long long)OCFS2_I(inode)->ip_blkno);
2009 
2010 	status = ocfs2_find_entry(name, namelen, inode, lookup);
2011 	if (status)
2012 		goto leave;
2013 
2014 	*blkno = le64_to_cpu(lookup->dl_entry->inode);
2015 
2016 	status = 0;
2017 leave:
2018 
2019 	return status;
2020 }
2021 
2022 /*
2023  * Convenience function for callers which just want the block number
2024  * mapped to a name and don't require the full dirent info, etc.
2025  */
2026 int ocfs2_lookup_ino_from_name(struct inode *dir, const char *name,
2027 			       int namelen, u64 *blkno)
2028 {
2029 	int ret;
2030 	struct ocfs2_dir_lookup_result lookup = { NULL, };
2031 
2032 	ret = ocfs2_find_files_on_disk(name, namelen, blkno, dir, &lookup);
2033 	ocfs2_free_dir_lookup_result(&lookup);
2034 
2035 	return ret;
2036 }
2037 
2038 /* Check for a name within a directory.
2039  *
2040  * Return 0 if the name does not exist
2041  * Return -EEXIST if the directory contains the name
2042  * Return -EFSCORRUPTED if found corruption
2043  *
2044  * Callers should have i_rwsem + a cluster lock on dir
2045  */
2046 int ocfs2_check_dir_for_entry(struct inode *dir,
2047 			      const char *name,
2048 			      int namelen)
2049 {
2050 	int ret = 0;
2051 	struct ocfs2_dir_lookup_result lookup = { NULL, };
2052 
2053 	trace_ocfs2_check_dir_for_entry(
2054 		(unsigned long long)OCFS2_I(dir)->ip_blkno, namelen, name);
2055 
2056 	ret = ocfs2_find_entry(name, namelen, dir, &lookup);
2057 	if (ret == 0) {
2058 		ret = -EEXIST;
2059 		mlog_errno(ret);
2060 	} else if (ret == -ENOENT) {
2061 		ret = 0;
2062 	}
2063 
2064 	ocfs2_free_dir_lookup_result(&lookup);
2065 
2066 	return ret;
2067 }
2068 
2069 struct ocfs2_empty_dir_priv {
2070 	struct dir_context ctx;
2071 	unsigned seen_dot;
2072 	unsigned seen_dot_dot;
2073 	unsigned seen_other;
2074 	unsigned dx_dir;
2075 };
2076 static bool ocfs2_empty_dir_filldir(struct dir_context *ctx, const char *name,
2077 				   int name_len, loff_t pos, u64 ino,
2078 				   unsigned type)
2079 {
2080 	struct ocfs2_empty_dir_priv *p =
2081 		container_of(ctx, struct ocfs2_empty_dir_priv, ctx);
2082 
2083 	/*
2084 	 * Check the positions of "." and ".." records to be sure
2085 	 * they're in the correct place.
2086 	 *
2087 	 * Indexed directories don't need to proceed past the first
2088 	 * two entries, so we end the scan after seeing '..'. Despite
2089 	 * that, we allow the scan to proceed In the event that we
2090 	 * have a corrupted indexed directory (no dot or dot dot
2091 	 * entries). This allows us to double check for existing
2092 	 * entries which might not have been found in the index.
2093 	 */
2094 	if (name_len == 1 && !strncmp(".", name, 1) && pos == 0) {
2095 		p->seen_dot = 1;
2096 		return true;
2097 	}
2098 
2099 	if (name_len == 2 && !strncmp("..", name, 2) &&
2100 	    pos == OCFS2_DIR_REC_LEN(1)) {
2101 		p->seen_dot_dot = 1;
2102 
2103 		if (p->dx_dir && p->seen_dot)
2104 			return false;
2105 
2106 		return true;
2107 	}
2108 
2109 	p->seen_other = 1;
2110 	return false;
2111 }
2112 
2113 static int ocfs2_empty_dir_dx(struct inode *inode,
2114 			      struct ocfs2_empty_dir_priv *priv)
2115 {
2116 	int ret;
2117 	struct buffer_head *di_bh = NULL;
2118 	struct buffer_head *dx_root_bh = NULL;
2119 	struct ocfs2_dinode *di;
2120 	struct ocfs2_dx_root_block *dx_root;
2121 
2122 	priv->dx_dir = 1;
2123 
2124 	ret = ocfs2_read_inode_block(inode, &di_bh);
2125 	if (ret) {
2126 		mlog_errno(ret);
2127 		goto out;
2128 	}
2129 	di = (struct ocfs2_dinode *)di_bh->b_data;
2130 
2131 	ret = ocfs2_read_dx_root(inode, di, &dx_root_bh);
2132 	if (ret) {
2133 		mlog_errno(ret);
2134 		goto out;
2135 	}
2136 	dx_root = (struct ocfs2_dx_root_block *)dx_root_bh->b_data;
2137 
2138 	if (le32_to_cpu(dx_root->dr_num_entries) != 2)
2139 		priv->seen_other = 1;
2140 
2141 out:
2142 	brelse(di_bh);
2143 	brelse(dx_root_bh);
2144 	return ret;
2145 }
2146 
2147 /*
2148  * routine to check that the specified directory is empty (for rmdir)
2149  *
2150  * Returns 1 if dir is empty, zero otherwise.
2151  *
2152  * XXX: This is a performance problem for unindexed directories.
2153  */
2154 int ocfs2_empty_dir(struct inode *inode)
2155 {
2156 	int ret;
2157 	struct ocfs2_empty_dir_priv priv = {
2158 		.ctx.actor = ocfs2_empty_dir_filldir,
2159 	};
2160 
2161 	if (ocfs2_dir_indexed(inode)) {
2162 		ret = ocfs2_empty_dir_dx(inode, &priv);
2163 		if (ret)
2164 			mlog_errno(ret);
2165 		/*
2166 		 * We still run ocfs2_dir_foreach to get the checks
2167 		 * for "." and "..".
2168 		 */
2169 	}
2170 
2171 	ret = ocfs2_dir_foreach(inode, &priv.ctx);
2172 	if (ret)
2173 		mlog_errno(ret);
2174 
2175 	if (!priv.seen_dot || !priv.seen_dot_dot) {
2176 		mlog(ML_ERROR, "bad directory (dir #%llu) - no `.' or `..'\n",
2177 		     (unsigned long long)OCFS2_I(inode)->ip_blkno);
2178 		/*
2179 		 * XXX: Is it really safe to allow an unlink to continue?
2180 		 */
2181 		return 1;
2182 	}
2183 
2184 	return !priv.seen_other;
2185 }
2186 
2187 /*
2188  * Fills "." and ".." dirents in a new directory block. Returns dirent for
2189  * "..", which might be used during creation of a directory with a trailing
2190  * header. It is otherwise safe to ignore the return code.
2191  */
2192 static struct ocfs2_dir_entry *ocfs2_fill_initial_dirents(struct inode *inode,
2193 							  struct inode *parent,
2194 							  char *start,
2195 							  unsigned int size)
2196 {
2197 	struct ocfs2_dir_entry *de = (struct ocfs2_dir_entry *)start;
2198 
2199 	de->inode = cpu_to_le64(OCFS2_I(inode)->ip_blkno);
2200 	de->name_len = 1;
2201 	de->rec_len =
2202 		cpu_to_le16(OCFS2_DIR_REC_LEN(de->name_len));
2203 	strcpy(de->name, ".");
2204 	ocfs2_set_de_type(de, S_IFDIR);
2205 
2206 	de = (struct ocfs2_dir_entry *) ((char *)de + le16_to_cpu(de->rec_len));
2207 	de->inode = cpu_to_le64(OCFS2_I(parent)->ip_blkno);
2208 	de->rec_len = cpu_to_le16(size - OCFS2_DIR_REC_LEN(1));
2209 	de->name_len = 2;
2210 	strcpy(de->name, "..");
2211 	ocfs2_set_de_type(de, S_IFDIR);
2212 
2213 	return de;
2214 }
2215 
2216 /*
2217  * This works together with code in ocfs2_mknod_locked() which sets
2218  * the inline-data flag and initializes the inline-data section.
2219  */
2220 static int ocfs2_fill_new_dir_id(struct ocfs2_super *osb,
2221 				 handle_t *handle,
2222 				 struct inode *parent,
2223 				 struct inode *inode,
2224 				 struct buffer_head *di_bh)
2225 {
2226 	int ret;
2227 	struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
2228 	struct ocfs2_inline_data *data = &di->id2.i_data;
2229 	unsigned int size = le16_to_cpu(data->id_count);
2230 
2231 	ret = ocfs2_journal_access_di(handle, INODE_CACHE(inode), di_bh,
2232 				      OCFS2_JOURNAL_ACCESS_WRITE);
2233 	if (ret) {
2234 		mlog_errno(ret);
2235 		goto out;
2236 	}
2237 
2238 	ocfs2_fill_initial_dirents(inode, parent, data->id_data, size);
2239 	ocfs2_journal_dirty(handle, di_bh);
2240 
2241 	i_size_write(inode, size);
2242 	set_nlink(inode, 2);
2243 	inode->i_blocks = ocfs2_inode_sector_count(inode);
2244 
2245 	ret = ocfs2_mark_inode_dirty(handle, inode, di_bh);
2246 	if (ret < 0)
2247 		mlog_errno(ret);
2248 
2249 out:
2250 	return ret;
2251 }
2252 
2253 static int ocfs2_fill_new_dir_el(struct ocfs2_super *osb,
2254 				 handle_t *handle,
2255 				 struct inode *parent,
2256 				 struct inode *inode,
2257 				 struct buffer_head *fe_bh,
2258 				 struct ocfs2_alloc_context *data_ac,
2259 				 struct buffer_head **ret_new_bh)
2260 {
2261 	int status;
2262 	unsigned int size = osb->sb->s_blocksize;
2263 	struct buffer_head *new_bh = NULL;
2264 	struct ocfs2_dir_entry *de;
2265 
2266 	if (ocfs2_new_dir_wants_trailer(inode))
2267 		size = ocfs2_dir_trailer_blk_off(parent->i_sb);
2268 
2269 	status = ocfs2_do_extend_dir(osb->sb, handle, inode, fe_bh,
2270 				     data_ac, NULL, &new_bh);
2271 	if (status < 0) {
2272 		mlog_errno(status);
2273 		goto bail;
2274 	}
2275 
2276 	ocfs2_set_new_buffer_uptodate(INODE_CACHE(inode), new_bh);
2277 
2278 	status = ocfs2_journal_access_db(handle, INODE_CACHE(inode), new_bh,
2279 					 OCFS2_JOURNAL_ACCESS_CREATE);
2280 	if (status < 0) {
2281 		mlog_errno(status);
2282 		goto bail;
2283 	}
2284 	memset(new_bh->b_data, 0, osb->sb->s_blocksize);
2285 
2286 	de = ocfs2_fill_initial_dirents(inode, parent, new_bh->b_data, size);
2287 	if (ocfs2_new_dir_wants_trailer(inode)) {
2288 		int size = le16_to_cpu(de->rec_len);
2289 
2290 		/*
2291 		 * Figure out the size of the hole left over after
2292 		 * insertion of '.' and '..'. The trailer wants this
2293 		 * information.
2294 		 */
2295 		size -= OCFS2_DIR_REC_LEN(2);
2296 		size -= sizeof(struct ocfs2_dir_block_trailer);
2297 
2298 		ocfs2_init_dir_trailer(inode, new_bh, size);
2299 	}
2300 
2301 	ocfs2_journal_dirty(handle, new_bh);
2302 
2303 	i_size_write(inode, inode->i_sb->s_blocksize);
2304 	set_nlink(inode, 2);
2305 	inode->i_blocks = ocfs2_inode_sector_count(inode);
2306 	status = ocfs2_mark_inode_dirty(handle, inode, fe_bh);
2307 	if (status < 0) {
2308 		mlog_errno(status);
2309 		goto bail;
2310 	}
2311 
2312 	status = 0;
2313 	if (ret_new_bh) {
2314 		*ret_new_bh = new_bh;
2315 		new_bh = NULL;
2316 	}
2317 bail:
2318 	brelse(new_bh);
2319 
2320 	return status;
2321 }
2322 
2323 static int ocfs2_dx_dir_attach_index(struct ocfs2_super *osb,
2324 				     handle_t *handle, struct inode *dir,
2325 				     struct buffer_head *di_bh,
2326 				     struct buffer_head *dirdata_bh,
2327 				     struct ocfs2_alloc_context *meta_ac,
2328 				     int dx_inline, u32 num_entries,
2329 				     struct buffer_head **ret_dx_root_bh)
2330 {
2331 	int ret;
2332 	struct ocfs2_dinode *di = (struct ocfs2_dinode *) di_bh->b_data;
2333 	u16 dr_suballoc_bit;
2334 	u64 suballoc_loc, dr_blkno;
2335 	unsigned int num_bits;
2336 	struct buffer_head *dx_root_bh = NULL;
2337 	struct ocfs2_dx_root_block *dx_root;
2338 	struct ocfs2_dir_block_trailer *trailer =
2339 		ocfs2_trailer_from_bh(dirdata_bh, dir->i_sb);
2340 
2341 	ret = ocfs2_claim_metadata(handle, meta_ac, 1, &suballoc_loc,
2342 				   &dr_suballoc_bit, &num_bits, &dr_blkno);
2343 	if (ret) {
2344 		mlog_errno(ret);
2345 		goto out;
2346 	}
2347 
2348 	trace_ocfs2_dx_dir_attach_index(
2349 				(unsigned long long)OCFS2_I(dir)->ip_blkno,
2350 				(unsigned long long)dr_blkno);
2351 
2352 	dx_root_bh = sb_getblk(osb->sb, dr_blkno);
2353 	if (dx_root_bh == NULL) {
2354 		ret = -ENOMEM;
2355 		goto out;
2356 	}
2357 	ocfs2_set_new_buffer_uptodate(INODE_CACHE(dir), dx_root_bh);
2358 
2359 	ret = ocfs2_journal_access_dr(handle, INODE_CACHE(dir), dx_root_bh,
2360 				      OCFS2_JOURNAL_ACCESS_CREATE);
2361 	if (ret < 0) {
2362 		mlog_errno(ret);
2363 		goto out;
2364 	}
2365 
2366 	dx_root = (struct ocfs2_dx_root_block *)dx_root_bh->b_data;
2367 	memset(dx_root, 0, osb->sb->s_blocksize);
2368 	strcpy(dx_root->dr_signature, OCFS2_DX_ROOT_SIGNATURE);
2369 	dx_root->dr_suballoc_slot = cpu_to_le16(meta_ac->ac_alloc_slot);
2370 	dx_root->dr_suballoc_loc = cpu_to_le64(suballoc_loc);
2371 	dx_root->dr_suballoc_bit = cpu_to_le16(dr_suballoc_bit);
2372 	dx_root->dr_fs_generation = cpu_to_le32(osb->fs_generation);
2373 	dx_root->dr_blkno = cpu_to_le64(dr_blkno);
2374 	dx_root->dr_dir_blkno = cpu_to_le64(OCFS2_I(dir)->ip_blkno);
2375 	dx_root->dr_num_entries = cpu_to_le32(num_entries);
2376 	if (le16_to_cpu(trailer->db_free_rec_len))
2377 		dx_root->dr_free_blk = cpu_to_le64(dirdata_bh->b_blocknr);
2378 	else
2379 		dx_root->dr_free_blk = cpu_to_le64(0);
2380 
2381 	if (dx_inline) {
2382 		dx_root->dr_flags |= OCFS2_DX_FLAG_INLINE;
2383 		dx_root->dr_entries.de_count =
2384 			cpu_to_le16(ocfs2_dx_entries_per_root(osb->sb));
2385 	} else {
2386 		dx_root->dr_list.l_count =
2387 			cpu_to_le16(ocfs2_extent_recs_per_dx_root(osb->sb));
2388 	}
2389 	ocfs2_journal_dirty(handle, dx_root_bh);
2390 
2391 	ret = ocfs2_journal_access_di(handle, INODE_CACHE(dir), di_bh,
2392 				      OCFS2_JOURNAL_ACCESS_CREATE);
2393 	if (ret) {
2394 		mlog_errno(ret);
2395 		goto out;
2396 	}
2397 
2398 	di->i_dx_root = cpu_to_le64(dr_blkno);
2399 
2400 	spin_lock(&OCFS2_I(dir)->ip_lock);
2401 	OCFS2_I(dir)->ip_dyn_features |= OCFS2_INDEXED_DIR_FL;
2402 	di->i_dyn_features = cpu_to_le16(OCFS2_I(dir)->ip_dyn_features);
2403 	spin_unlock(&OCFS2_I(dir)->ip_lock);
2404 
2405 	ocfs2_journal_dirty(handle, di_bh);
2406 
2407 	*ret_dx_root_bh = dx_root_bh;
2408 	dx_root_bh = NULL;
2409 
2410 out:
2411 	brelse(dx_root_bh);
2412 	return ret;
2413 }
2414 
2415 static int ocfs2_dx_dir_format_cluster(struct ocfs2_super *osb,
2416 				       handle_t *handle, struct inode *dir,
2417 				       struct buffer_head **dx_leaves,
2418 				       int num_dx_leaves, u64 start_blk)
2419 {
2420 	int ret, i;
2421 	struct ocfs2_dx_leaf *dx_leaf;
2422 	struct buffer_head *bh;
2423 
2424 	for (i = 0; i < num_dx_leaves; i++) {
2425 		bh = sb_getblk(osb->sb, start_blk + i);
2426 		if (bh == NULL) {
2427 			ret = -ENOMEM;
2428 			goto out;
2429 		}
2430 		dx_leaves[i] = bh;
2431 
2432 		ocfs2_set_new_buffer_uptodate(INODE_CACHE(dir), bh);
2433 
2434 		ret = ocfs2_journal_access_dl(handle, INODE_CACHE(dir), bh,
2435 					      OCFS2_JOURNAL_ACCESS_CREATE);
2436 		if (ret < 0) {
2437 			mlog_errno(ret);
2438 			goto out;
2439 		}
2440 
2441 		dx_leaf = (struct ocfs2_dx_leaf *) bh->b_data;
2442 
2443 		memset(dx_leaf, 0, osb->sb->s_blocksize);
2444 		strcpy(dx_leaf->dl_signature, OCFS2_DX_LEAF_SIGNATURE);
2445 		dx_leaf->dl_fs_generation = cpu_to_le32(osb->fs_generation);
2446 		dx_leaf->dl_blkno = cpu_to_le64(bh->b_blocknr);
2447 		dx_leaf->dl_list.de_count =
2448 			cpu_to_le16(ocfs2_dx_entries_per_leaf(osb->sb));
2449 
2450 		trace_ocfs2_dx_dir_format_cluster(
2451 				(unsigned long long)OCFS2_I(dir)->ip_blkno,
2452 				(unsigned long long)bh->b_blocknr,
2453 				le16_to_cpu(dx_leaf->dl_list.de_count));
2454 
2455 		ocfs2_journal_dirty(handle, bh);
2456 	}
2457 
2458 	ret = 0;
2459 out:
2460 	return ret;
2461 }
2462 
2463 /*
2464  * Allocates and formats a new cluster for use in an indexed dir
2465  * leaf. This version will not do the extent insert, so that it can be
2466  * used by operations which need careful ordering.
2467  */
2468 static int __ocfs2_dx_dir_new_cluster(struct inode *dir,
2469 				      u32 cpos, handle_t *handle,
2470 				      struct ocfs2_alloc_context *data_ac,
2471 				      struct buffer_head **dx_leaves,
2472 				      int num_dx_leaves, u64 *ret_phys_blkno)
2473 {
2474 	int ret;
2475 	u32 phys, num;
2476 	u64 phys_blkno;
2477 	struct ocfs2_super *osb = OCFS2_SB(dir->i_sb);
2478 
2479 	/*
2480 	 * XXX: For create, this should claim cluster for the index
2481 	 * *before* the unindexed insert so that we have a better
2482 	 * chance of contiguousness as the directory grows in number
2483 	 * of entries.
2484 	 */
2485 	ret = __ocfs2_claim_clusters(handle, data_ac, 1, 1, &phys, &num);
2486 	if (ret) {
2487 		mlog_errno(ret);
2488 		goto out;
2489 	}
2490 
2491 	/*
2492 	 * Format the new cluster first. That way, we're inserting
2493 	 * valid data.
2494 	 */
2495 	phys_blkno = ocfs2_clusters_to_blocks(osb->sb, phys);
2496 	ret = ocfs2_dx_dir_format_cluster(osb, handle, dir, dx_leaves,
2497 					  num_dx_leaves, phys_blkno);
2498 	if (ret) {
2499 		mlog_errno(ret);
2500 		goto out;
2501 	}
2502 
2503 	*ret_phys_blkno = phys_blkno;
2504 out:
2505 	return ret;
2506 }
2507 
2508 static int ocfs2_dx_dir_new_cluster(struct inode *dir,
2509 				    struct ocfs2_extent_tree *et,
2510 				    u32 cpos, handle_t *handle,
2511 				    struct ocfs2_alloc_context *data_ac,
2512 				    struct ocfs2_alloc_context *meta_ac,
2513 				    struct buffer_head **dx_leaves,
2514 				    int num_dx_leaves)
2515 {
2516 	int ret;
2517 	u64 phys_blkno;
2518 
2519 	ret = __ocfs2_dx_dir_new_cluster(dir, cpos, handle, data_ac, dx_leaves,
2520 					 num_dx_leaves, &phys_blkno);
2521 	if (ret) {
2522 		mlog_errno(ret);
2523 		goto out;
2524 	}
2525 
2526 	ret = ocfs2_insert_extent(handle, et, cpos, phys_blkno, 1, 0,
2527 				  meta_ac);
2528 	if (ret)
2529 		mlog_errno(ret);
2530 out:
2531 	return ret;
2532 }
2533 
2534 static struct buffer_head **ocfs2_dx_dir_kmalloc_leaves(struct super_block *sb,
2535 							int *ret_num_leaves)
2536 {
2537 	int num_dx_leaves = ocfs2_clusters_to_blocks(sb, 1);
2538 	struct buffer_head **dx_leaves;
2539 
2540 	dx_leaves = kcalloc(num_dx_leaves, sizeof(struct buffer_head *),
2541 			    GFP_NOFS);
2542 	if (dx_leaves && ret_num_leaves)
2543 		*ret_num_leaves = num_dx_leaves;
2544 
2545 	return dx_leaves;
2546 }
2547 
2548 static int ocfs2_fill_new_dir_dx(struct ocfs2_super *osb,
2549 				 handle_t *handle,
2550 				 struct inode *parent,
2551 				 struct inode *inode,
2552 				 struct buffer_head *di_bh,
2553 				 struct ocfs2_alloc_context *data_ac,
2554 				 struct ocfs2_alloc_context *meta_ac)
2555 {
2556 	int ret;
2557 	struct buffer_head *leaf_bh = NULL;
2558 	struct buffer_head *dx_root_bh = NULL;
2559 	struct ocfs2_dx_hinfo hinfo;
2560 	struct ocfs2_dx_root_block *dx_root;
2561 	struct ocfs2_dx_entry_list *entry_list;
2562 
2563 	/*
2564 	 * Our strategy is to create the directory as though it were
2565 	 * unindexed, then add the index block. This works with very
2566 	 * little complication since the state of a new directory is a
2567 	 * very well known quantity.
2568 	 *
2569 	 * Essentially, we have two dirents ("." and ".."), in the 1st
2570 	 * block which need indexing. These are easily inserted into
2571 	 * the index block.
2572 	 */
2573 
2574 	ret = ocfs2_fill_new_dir_el(osb, handle, parent, inode, di_bh,
2575 				    data_ac, &leaf_bh);
2576 	if (ret) {
2577 		mlog_errno(ret);
2578 		goto out;
2579 	}
2580 
2581 	ret = ocfs2_dx_dir_attach_index(osb, handle, inode, di_bh, leaf_bh,
2582 					meta_ac, 1, 2, &dx_root_bh);
2583 	if (ret) {
2584 		mlog_errno(ret);
2585 		goto out;
2586 	}
2587 	dx_root = (struct ocfs2_dx_root_block *)dx_root_bh->b_data;
2588 	entry_list = &dx_root->dr_entries;
2589 
2590 	/* Buffer has been journaled for us by ocfs2_dx_dir_attach_index */
2591 	ocfs2_dx_dir_name_hash(inode, ".", 1, &hinfo);
2592 	ocfs2_dx_entry_list_insert(entry_list, &hinfo, leaf_bh->b_blocknr);
2593 
2594 	ocfs2_dx_dir_name_hash(inode, "..", 2, &hinfo);
2595 	ocfs2_dx_entry_list_insert(entry_list, &hinfo, leaf_bh->b_blocknr);
2596 
2597 out:
2598 	brelse(dx_root_bh);
2599 	brelse(leaf_bh);
2600 	return ret;
2601 }
2602 
2603 int ocfs2_fill_new_dir(struct ocfs2_super *osb,
2604 		       handle_t *handle,
2605 		       struct inode *parent,
2606 		       struct inode *inode,
2607 		       struct buffer_head *fe_bh,
2608 		       struct ocfs2_alloc_context *data_ac,
2609 		       struct ocfs2_alloc_context *meta_ac)
2610 
2611 {
2612 	BUG_ON(!ocfs2_supports_inline_data(osb) && data_ac == NULL);
2613 
2614 	if (OCFS2_I(inode)->ip_dyn_features & OCFS2_INLINE_DATA_FL)
2615 		return ocfs2_fill_new_dir_id(osb, handle, parent, inode, fe_bh);
2616 
2617 	if (ocfs2_supports_indexed_dirs(osb))
2618 		return ocfs2_fill_new_dir_dx(osb, handle, parent, inode, fe_bh,
2619 					     data_ac, meta_ac);
2620 
2621 	return ocfs2_fill_new_dir_el(osb, handle, parent, inode, fe_bh,
2622 				     data_ac, NULL);
2623 }
2624 
2625 static int ocfs2_dx_dir_index_block(struct inode *dir,
2626 				    handle_t *handle,
2627 				    struct buffer_head **dx_leaves,
2628 				    int num_dx_leaves,
2629 				    u32 *num_dx_entries,
2630 				    struct buffer_head *dirent_bh)
2631 {
2632 	int ret = 0, namelen, i;
2633 	char *de_buf, *limit;
2634 	struct ocfs2_dir_entry *de;
2635 	struct buffer_head *dx_leaf_bh;
2636 	struct ocfs2_dx_hinfo hinfo;
2637 	u64 dirent_blk = dirent_bh->b_blocknr;
2638 
2639 	de_buf = dirent_bh->b_data;
2640 	limit = de_buf + dir->i_sb->s_blocksize;
2641 
2642 	while (de_buf < limit) {
2643 		de = (struct ocfs2_dir_entry *)de_buf;
2644 
2645 		namelen = de->name_len;
2646 		if (!namelen || !de->inode)
2647 			goto inc;
2648 
2649 		ocfs2_dx_dir_name_hash(dir, de->name, namelen, &hinfo);
2650 
2651 		i = ocfs2_dx_dir_hash_idx(OCFS2_SB(dir->i_sb), &hinfo);
2652 		dx_leaf_bh = dx_leaves[i];
2653 
2654 		ret = __ocfs2_dx_dir_leaf_insert(dir, handle, &hinfo,
2655 						 dirent_blk, dx_leaf_bh);
2656 		if (ret) {
2657 			mlog_errno(ret);
2658 			goto out;
2659 		}
2660 
2661 		*num_dx_entries = *num_dx_entries + 1;
2662 
2663 inc:
2664 		de_buf += le16_to_cpu(de->rec_len);
2665 	}
2666 
2667 out:
2668 	return ret;
2669 }
2670 
2671 /*
2672  * XXX: This expects dx_root_bh to already be part of the transaction.
2673  */
2674 static void ocfs2_dx_dir_index_root_block(struct inode *dir,
2675 					 struct buffer_head *dx_root_bh,
2676 					 struct buffer_head *dirent_bh)
2677 {
2678 	char *de_buf, *limit;
2679 	struct ocfs2_dx_root_block *dx_root;
2680 	struct ocfs2_dir_entry *de;
2681 	struct ocfs2_dx_hinfo hinfo;
2682 	u64 dirent_blk = dirent_bh->b_blocknr;
2683 
2684 	dx_root = (struct ocfs2_dx_root_block *)dx_root_bh->b_data;
2685 
2686 	de_buf = dirent_bh->b_data;
2687 	limit = de_buf + dir->i_sb->s_blocksize;
2688 
2689 	while (de_buf < limit) {
2690 		de = (struct ocfs2_dir_entry *)de_buf;
2691 
2692 		if (!de->name_len || !de->inode)
2693 			goto inc;
2694 
2695 		ocfs2_dx_dir_name_hash(dir, de->name, de->name_len, &hinfo);
2696 
2697 		trace_ocfs2_dx_dir_index_root_block(
2698 				(unsigned long long)dir->i_ino,
2699 				hinfo.major_hash, hinfo.minor_hash,
2700 				de->name_len, de->name,
2701 				le16_to_cpu(dx_root->dr_entries.de_num_used));
2702 
2703 		ocfs2_dx_entry_list_insert(&dx_root->dr_entries, &hinfo,
2704 					   dirent_blk);
2705 
2706 		le32_add_cpu(&dx_root->dr_num_entries, 1);
2707 inc:
2708 		de_buf += le16_to_cpu(de->rec_len);
2709 	}
2710 }
2711 
2712 /*
2713  * Count the number of inline directory entries in di_bh and compare
2714  * them against the number of entries we can hold in an inline dx root
2715  * block.
2716  */
2717 static int ocfs2_new_dx_should_be_inline(struct inode *dir,
2718 					 struct buffer_head *di_bh)
2719 {
2720 	int dirent_count = 0;
2721 	char *de_buf, *limit;
2722 	struct ocfs2_dir_entry *de;
2723 	struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
2724 
2725 	de_buf = di->id2.i_data.id_data;
2726 	limit = de_buf + i_size_read(dir);
2727 
2728 	while (de_buf < limit) {
2729 		de = (struct ocfs2_dir_entry *)de_buf;
2730 
2731 		if (de->name_len && de->inode)
2732 			dirent_count++;
2733 
2734 		de_buf += le16_to_cpu(de->rec_len);
2735 	}
2736 
2737 	/* We are careful to leave room for one extra record. */
2738 	return dirent_count < ocfs2_dx_entries_per_root(dir->i_sb);
2739 }
2740 
2741 /*
2742  * Expand rec_len of the rightmost dirent in a directory block so that it
2743  * contains the end of our valid space for dirents. We do this during
2744  * expansion from an inline directory to one with extents. The first dir block
2745  * in that case is taken from the inline data portion of the inode block.
2746  *
2747  * This will also return the largest amount of contiguous space for a dirent
2748  * in the block. That value is *not* necessarily the last dirent, even after
2749  * expansion. The directory indexing code wants this value for free space
2750  * accounting. We do this here since we're already walking the entire dir
2751  * block.
2752  *
2753  * We add the dir trailer if this filesystem wants it.
2754  */
2755 static unsigned int ocfs2_expand_last_dirent(char *start, unsigned int old_size,
2756 					     struct inode *dir)
2757 {
2758 	struct super_block *sb = dir->i_sb;
2759 	struct ocfs2_dir_entry *de;
2760 	struct ocfs2_dir_entry *prev_de;
2761 	char *de_buf, *limit;
2762 	unsigned int new_size = sb->s_blocksize;
2763 	unsigned int bytes, this_hole;
2764 	unsigned int largest_hole = 0;
2765 
2766 	if (ocfs2_new_dir_wants_trailer(dir))
2767 		new_size = ocfs2_dir_trailer_blk_off(sb);
2768 
2769 	bytes = new_size - old_size;
2770 
2771 	limit = start + old_size;
2772 	de_buf = start;
2773 	de = (struct ocfs2_dir_entry *)de_buf;
2774 	do {
2775 		this_hole = ocfs2_figure_dirent_hole(de);
2776 		if (this_hole > largest_hole)
2777 			largest_hole = this_hole;
2778 
2779 		prev_de = de;
2780 		de_buf += le16_to_cpu(de->rec_len);
2781 		de = (struct ocfs2_dir_entry *)de_buf;
2782 	} while (de_buf < limit);
2783 
2784 	le16_add_cpu(&prev_de->rec_len, bytes);
2785 
2786 	/* We need to double check this after modification of the final
2787 	 * dirent. */
2788 	this_hole = ocfs2_figure_dirent_hole(prev_de);
2789 	if (this_hole > largest_hole)
2790 		largest_hole = this_hole;
2791 
2792 	if (largest_hole >= OCFS2_DIR_MIN_REC_LEN)
2793 		return largest_hole;
2794 	return 0;
2795 }
2796 
2797 /*
2798  * We allocate enough clusters to fulfill "blocks_wanted", but set
2799  * i_size to exactly one block. Ocfs2_extend_dir() will handle the
2800  * rest automatically for us.
2801  *
2802  * *first_block_bh is a pointer to the 1st data block allocated to the
2803  *  directory.
2804  */
2805 static int ocfs2_expand_inline_dir(struct inode *dir, struct buffer_head *di_bh,
2806 				   unsigned int blocks_wanted,
2807 				   struct ocfs2_dir_lookup_result *lookup,
2808 				   struct buffer_head **first_block_bh)
2809 {
2810 	u32 alloc, dx_alloc, bit_off, len, num_dx_entries = 0;
2811 	struct super_block *sb = dir->i_sb;
2812 	int ret, i, num_dx_leaves = 0, dx_inline = 0,
2813 		credits = ocfs2_inline_to_extents_credits(sb);
2814 	u64 dx_insert_blkno, blkno,
2815 		bytes = blocks_wanted << sb->s_blocksize_bits;
2816 	struct ocfs2_super *osb = OCFS2_SB(dir->i_sb);
2817 	struct ocfs2_inode_info *oi = OCFS2_I(dir);
2818 	struct ocfs2_alloc_context *data_ac = NULL;
2819 	struct ocfs2_alloc_context *meta_ac = NULL;
2820 	struct buffer_head *dirdata_bh = NULL;
2821 	struct buffer_head *dx_root_bh = NULL;
2822 	struct buffer_head **dx_leaves = NULL;
2823 	struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
2824 	handle_t *handle;
2825 	struct ocfs2_extent_tree et;
2826 	struct ocfs2_extent_tree dx_et;
2827 	int did_quota = 0, bytes_allocated = 0;
2828 
2829 	ocfs2_init_dinode_extent_tree(&et, INODE_CACHE(dir), di_bh);
2830 
2831 	alloc = ocfs2_clusters_for_bytes(sb, bytes);
2832 	dx_alloc = 0;
2833 
2834 	down_write(&oi->ip_alloc_sem);
2835 
2836 	if (ocfs2_supports_indexed_dirs(osb)) {
2837 		credits += ocfs2_add_dir_index_credits(sb);
2838 
2839 		dx_inline = ocfs2_new_dx_should_be_inline(dir, di_bh);
2840 		if (!dx_inline) {
2841 			/* Add one more cluster for an index leaf */
2842 			dx_alloc++;
2843 			dx_leaves = ocfs2_dx_dir_kmalloc_leaves(sb,
2844 								&num_dx_leaves);
2845 			if (!dx_leaves) {
2846 				ret = -ENOMEM;
2847 				mlog_errno(ret);
2848 				goto out;
2849 			}
2850 		}
2851 
2852 		/* This gets us the dx_root */
2853 		ret = ocfs2_reserve_new_metadata_blocks(osb, 1, &meta_ac);
2854 		if (ret) {
2855 			mlog_errno(ret);
2856 			goto out;
2857 		}
2858 	}
2859 
2860 	/*
2861 	 * We should never need more than 2 clusters for the unindexed
2862 	 * tree - maximum dirent size is far less than one block. In
2863 	 * fact, the only time we'd need more than one cluster is if
2864 	 * blocksize == clustersize and the dirent won't fit in the
2865 	 * extra space that the expansion to a single block gives. As
2866 	 * of today, that only happens on 4k/4k file systems.
2867 	 */
2868 	BUG_ON(alloc > 2);
2869 
2870 	ret = ocfs2_reserve_clusters(osb, alloc + dx_alloc, &data_ac);
2871 	if (ret) {
2872 		mlog_errno(ret);
2873 		goto out;
2874 	}
2875 
2876 	/*
2877 	 * Prepare for worst case allocation scenario of two separate
2878 	 * extents in the unindexed tree.
2879 	 */
2880 	if (alloc == 2)
2881 		credits += OCFS2_SUBALLOC_ALLOC;
2882 
2883 	handle = ocfs2_start_trans(osb, credits);
2884 	if (IS_ERR(handle)) {
2885 		ret = PTR_ERR(handle);
2886 		mlog_errno(ret);
2887 		goto out;
2888 	}
2889 
2890 	ret = dquot_alloc_space_nodirty(dir,
2891 		ocfs2_clusters_to_bytes(osb->sb, alloc + dx_alloc));
2892 	if (ret)
2893 		goto out_commit;
2894 	did_quota = 1;
2895 
2896 	if (ocfs2_supports_indexed_dirs(osb) && !dx_inline) {
2897 		/*
2898 		 * Allocate our index cluster first, to maximize the
2899 		 * possibility that unindexed leaves grow
2900 		 * contiguously.
2901 		 */
2902 		ret = __ocfs2_dx_dir_new_cluster(dir, 0, handle, data_ac,
2903 						 dx_leaves, num_dx_leaves,
2904 						 &dx_insert_blkno);
2905 		if (ret) {
2906 			mlog_errno(ret);
2907 			goto out_commit;
2908 		}
2909 		bytes_allocated += ocfs2_clusters_to_bytes(dir->i_sb, 1);
2910 	}
2911 
2912 	/*
2913 	 * Try to claim as many clusters as the bitmap can give though
2914 	 * if we only get one now, that's enough to continue. The rest
2915 	 * will be claimed after the conversion to extents.
2916 	 */
2917 	if (ocfs2_dir_resv_allowed(osb))
2918 		data_ac->ac_resv = &oi->ip_la_data_resv;
2919 	ret = ocfs2_claim_clusters(handle, data_ac, 1, &bit_off, &len);
2920 	if (ret) {
2921 		mlog_errno(ret);
2922 		goto out_commit;
2923 	}
2924 	bytes_allocated += ocfs2_clusters_to_bytes(dir->i_sb, 1);
2925 
2926 	/*
2927 	 * Operations are carefully ordered so that we set up the new
2928 	 * data block first. The conversion from inline data to
2929 	 * extents follows.
2930 	 */
2931 	blkno = ocfs2_clusters_to_blocks(dir->i_sb, bit_off);
2932 	dirdata_bh = sb_getblk(sb, blkno);
2933 	if (!dirdata_bh) {
2934 		ret = -ENOMEM;
2935 		mlog_errno(ret);
2936 		goto out_commit;
2937 	}
2938 
2939 	ocfs2_set_new_buffer_uptodate(INODE_CACHE(dir), dirdata_bh);
2940 
2941 	ret = ocfs2_journal_access_db(handle, INODE_CACHE(dir), dirdata_bh,
2942 				      OCFS2_JOURNAL_ACCESS_CREATE);
2943 	if (ret) {
2944 		mlog_errno(ret);
2945 		goto out_commit;
2946 	}
2947 
2948 	memcpy(dirdata_bh->b_data, di->id2.i_data.id_data, i_size_read(dir));
2949 	memset(dirdata_bh->b_data + i_size_read(dir), 0,
2950 	       sb->s_blocksize - i_size_read(dir));
2951 	i = ocfs2_expand_last_dirent(dirdata_bh->b_data, i_size_read(dir), dir);
2952 	if (ocfs2_new_dir_wants_trailer(dir)) {
2953 		/*
2954 		 * Prepare the dir trailer up front. It will otherwise look
2955 		 * like a valid dirent. Even if inserting the index fails
2956 		 * (unlikely), then all we'll have done is given first dir
2957 		 * block a small amount of fragmentation.
2958 		 */
2959 		ocfs2_init_dir_trailer(dir, dirdata_bh, i);
2960 	}
2961 
2962 	ocfs2_update_inode_fsync_trans(handle, dir, 1);
2963 	ocfs2_journal_dirty(handle, dirdata_bh);
2964 
2965 	if (ocfs2_supports_indexed_dirs(osb) && !dx_inline) {
2966 		/*
2967 		 * Dx dirs with an external cluster need to do this up
2968 		 * front. Inline dx root's get handled later, after
2969 		 * we've allocated our root block. We get passed back
2970 		 * a total number of items so that dr_num_entries can
2971 		 * be correctly set once the dx_root has been
2972 		 * allocated.
2973 		 */
2974 		ret = ocfs2_dx_dir_index_block(dir, handle, dx_leaves,
2975 					       num_dx_leaves, &num_dx_entries,
2976 					       dirdata_bh);
2977 		if (ret) {
2978 			mlog_errno(ret);
2979 			goto out_commit;
2980 		}
2981 	}
2982 
2983 	/*
2984 	 * Set extent, i_size, etc on the directory. After this, the
2985 	 * inode should contain the same exact dirents as before and
2986 	 * be fully accessible from system calls.
2987 	 *
2988 	 * We let the later dirent insert modify c/mtime - to the user
2989 	 * the data hasn't changed.
2990 	 */
2991 	ret = ocfs2_journal_access_di(handle, INODE_CACHE(dir), di_bh,
2992 				      OCFS2_JOURNAL_ACCESS_CREATE);
2993 	if (ret) {
2994 		mlog_errno(ret);
2995 		goto out_commit;
2996 	}
2997 
2998 	spin_lock(&oi->ip_lock);
2999 	oi->ip_dyn_features &= ~OCFS2_INLINE_DATA_FL;
3000 	di->i_dyn_features = cpu_to_le16(oi->ip_dyn_features);
3001 	spin_unlock(&oi->ip_lock);
3002 
3003 	ocfs2_dinode_new_extent_list(dir, di);
3004 
3005 	i_size_write(dir, sb->s_blocksize);
3006 	inode_set_mtime_to_ts(dir, inode_set_ctime_current(dir));
3007 
3008 	di->i_size = cpu_to_le64(sb->s_blocksize);
3009 	di->i_ctime = di->i_mtime = cpu_to_le64(inode_get_ctime_sec(dir));
3010 	di->i_ctime_nsec = di->i_mtime_nsec = cpu_to_le32(inode_get_ctime_nsec(dir));
3011 	ocfs2_update_inode_fsync_trans(handle, dir, 1);
3012 
3013 	/*
3014 	 * This should never fail as our extent list is empty and all
3015 	 * related blocks have been journaled already.
3016 	 */
3017 	ret = ocfs2_insert_extent(handle, &et, 0, blkno, len,
3018 				  0, NULL);
3019 	if (ret) {
3020 		mlog_errno(ret);
3021 		goto out_commit;
3022 	}
3023 
3024 	/*
3025 	 * Set i_blocks after the extent insert for the most up to
3026 	 * date ip_clusters value.
3027 	 */
3028 	dir->i_blocks = ocfs2_inode_sector_count(dir);
3029 
3030 	ocfs2_journal_dirty(handle, di_bh);
3031 
3032 	if (ocfs2_supports_indexed_dirs(osb)) {
3033 		ret = ocfs2_dx_dir_attach_index(osb, handle, dir, di_bh,
3034 						dirdata_bh, meta_ac, dx_inline,
3035 						num_dx_entries, &dx_root_bh);
3036 		if (ret) {
3037 			mlog_errno(ret);
3038 			goto out_commit;
3039 		}
3040 
3041 		if (dx_inline) {
3042 			ocfs2_dx_dir_index_root_block(dir, dx_root_bh,
3043 						      dirdata_bh);
3044 		} else {
3045 			ocfs2_init_dx_root_extent_tree(&dx_et,
3046 						       INODE_CACHE(dir),
3047 						       dx_root_bh);
3048 			ret = ocfs2_insert_extent(handle, &dx_et, 0,
3049 						  dx_insert_blkno, 1, 0, NULL);
3050 			if (ret)
3051 				mlog_errno(ret);
3052 		}
3053 	}
3054 
3055 	/*
3056 	 * We asked for two clusters, but only got one in the 1st
3057 	 * pass. Claim the 2nd cluster as a separate extent.
3058 	 */
3059 	if (alloc > len) {
3060 		ret = ocfs2_claim_clusters(handle, data_ac, 1, &bit_off,
3061 					   &len);
3062 		if (ret) {
3063 			mlog_errno(ret);
3064 			goto out_commit;
3065 		}
3066 		blkno = ocfs2_clusters_to_blocks(dir->i_sb, bit_off);
3067 
3068 		ret = ocfs2_insert_extent(handle, &et, 1,
3069 					  blkno, len, 0, NULL);
3070 		if (ret) {
3071 			mlog_errno(ret);
3072 			goto out_commit;
3073 		}
3074 		bytes_allocated += ocfs2_clusters_to_bytes(dir->i_sb, 1);
3075 	}
3076 
3077 	*first_block_bh = dirdata_bh;
3078 	dirdata_bh = NULL;
3079 	if (ocfs2_supports_indexed_dirs(osb)) {
3080 		unsigned int off;
3081 
3082 		if (!dx_inline) {
3083 			/*
3084 			 * We need to return the correct block within the
3085 			 * cluster which should hold our entry.
3086 			 */
3087 			off = ocfs2_dx_dir_hash_idx(osb,
3088 						    &lookup->dl_hinfo);
3089 			get_bh(dx_leaves[off]);
3090 			lookup->dl_dx_leaf_bh = dx_leaves[off];
3091 		}
3092 		lookup->dl_dx_root_bh = dx_root_bh;
3093 		dx_root_bh = NULL;
3094 	}
3095 
3096 out_commit:
3097 	if (ret < 0 && did_quota)
3098 		dquot_free_space_nodirty(dir, bytes_allocated);
3099 
3100 	ocfs2_commit_trans(osb, handle);
3101 
3102 out:
3103 	up_write(&oi->ip_alloc_sem);
3104 	if (data_ac)
3105 		ocfs2_free_alloc_context(data_ac);
3106 	if (meta_ac)
3107 		ocfs2_free_alloc_context(meta_ac);
3108 
3109 	if (dx_leaves) {
3110 		for (i = 0; i < num_dx_leaves; i++)
3111 			brelse(dx_leaves[i]);
3112 		kfree(dx_leaves);
3113 	}
3114 
3115 	brelse(dirdata_bh);
3116 	brelse(dx_root_bh);
3117 
3118 	return ret;
3119 }
3120 
3121 /* returns a bh of the 1st new block in the allocation. */
3122 static int ocfs2_do_extend_dir(struct super_block *sb,
3123 			       handle_t *handle,
3124 			       struct inode *dir,
3125 			       struct buffer_head *parent_fe_bh,
3126 			       struct ocfs2_alloc_context *data_ac,
3127 			       struct ocfs2_alloc_context *meta_ac,
3128 			       struct buffer_head **new_bh)
3129 {
3130 	int status;
3131 	int extend, did_quota = 0;
3132 	u64 p_blkno, v_blkno;
3133 
3134 	spin_lock(&OCFS2_I(dir)->ip_lock);
3135 	extend = (i_size_read(dir) == ocfs2_clusters_to_bytes(sb, OCFS2_I(dir)->ip_clusters));
3136 	spin_unlock(&OCFS2_I(dir)->ip_lock);
3137 
3138 	if (extend) {
3139 		u32 offset = OCFS2_I(dir)->ip_clusters;
3140 
3141 		status = dquot_alloc_space_nodirty(dir,
3142 					ocfs2_clusters_to_bytes(sb, 1));
3143 		if (status)
3144 			goto bail;
3145 		did_quota = 1;
3146 
3147 		status = ocfs2_add_inode_data(OCFS2_SB(sb), dir, &offset,
3148 					      1, 0, parent_fe_bh, handle,
3149 					      data_ac, meta_ac, NULL);
3150 		BUG_ON(status == -EAGAIN);
3151 		if (status < 0) {
3152 			mlog_errno(status);
3153 			goto bail;
3154 		}
3155 	}
3156 
3157 	v_blkno = ocfs2_blocks_for_bytes(sb, i_size_read(dir));
3158 	status = ocfs2_extent_map_get_blocks(dir, v_blkno, &p_blkno, NULL, NULL);
3159 	if (status < 0) {
3160 		mlog_errno(status);
3161 		goto bail;
3162 	}
3163 
3164 	*new_bh = sb_getblk(sb, p_blkno);
3165 	if (!*new_bh) {
3166 		status = -ENOMEM;
3167 		mlog_errno(status);
3168 		goto bail;
3169 	}
3170 	status = 0;
3171 bail:
3172 	if (did_quota && status < 0)
3173 		dquot_free_space_nodirty(dir, ocfs2_clusters_to_bytes(sb, 1));
3174 	return status;
3175 }
3176 
3177 /*
3178  * Assumes you already have a cluster lock on the directory.
3179  *
3180  * 'blocks_wanted' is only used if we have an inline directory which
3181  * is to be turned into an extent based one. The size of the dirent to
3182  * insert might be larger than the space gained by growing to just one
3183  * block, so we may have to grow the inode by two blocks in that case.
3184  *
3185  * If the directory is already indexed, dx_root_bh must be provided.
3186  */
3187 static int ocfs2_extend_dir(struct ocfs2_super *osb,
3188 			    struct inode *dir,
3189 			    struct buffer_head *parent_fe_bh,
3190 			    unsigned int blocks_wanted,
3191 			    struct ocfs2_dir_lookup_result *lookup,
3192 			    struct buffer_head **new_de_bh)
3193 {
3194 	int status = 0;
3195 	int credits, num_free_extents, drop_alloc_sem = 0;
3196 	loff_t dir_i_size;
3197 	struct ocfs2_dinode *fe = (struct ocfs2_dinode *) parent_fe_bh->b_data;
3198 	struct ocfs2_extent_list *el = &fe->id2.i_list;
3199 	struct ocfs2_alloc_context *data_ac = NULL;
3200 	struct ocfs2_alloc_context *meta_ac = NULL;
3201 	handle_t *handle = NULL;
3202 	struct buffer_head *new_bh = NULL;
3203 	struct ocfs2_dir_entry * de;
3204 	struct super_block *sb = osb->sb;
3205 	struct ocfs2_extent_tree et;
3206 	struct buffer_head *dx_root_bh = lookup->dl_dx_root_bh;
3207 
3208 	if (OCFS2_I(dir)->ip_dyn_features & OCFS2_INLINE_DATA_FL) {
3209 		/*
3210 		 * This would be a code error as an inline directory should
3211 		 * never have an index root.
3212 		 */
3213 		BUG_ON(dx_root_bh);
3214 
3215 		status = ocfs2_expand_inline_dir(dir, parent_fe_bh,
3216 						 blocks_wanted, lookup,
3217 						 &new_bh);
3218 		if (status) {
3219 			mlog_errno(status);
3220 			goto bail;
3221 		}
3222 
3223 		/* Expansion from inline to an indexed directory will
3224 		 * have given us this. */
3225 		dx_root_bh = lookup->dl_dx_root_bh;
3226 
3227 		if (blocks_wanted == 1) {
3228 			/*
3229 			 * If the new dirent will fit inside the space
3230 			 * created by pushing out to one block, then
3231 			 * we can complete the operation
3232 			 * here. Otherwise we have to expand i_size
3233 			 * and format the 2nd block below.
3234 			 */
3235 			BUG_ON(new_bh == NULL);
3236 			goto bail_bh;
3237 		}
3238 
3239 		/*
3240 		 * Get rid of 'new_bh' - we want to format the 2nd
3241 		 * data block and return that instead.
3242 		 */
3243 		brelse(new_bh);
3244 		new_bh = NULL;
3245 
3246 		down_write(&OCFS2_I(dir)->ip_alloc_sem);
3247 		drop_alloc_sem = 1;
3248 		dir_i_size = i_size_read(dir);
3249 		credits = OCFS2_SIMPLE_DIR_EXTEND_CREDITS;
3250 		goto do_extend;
3251 	}
3252 
3253 	down_write(&OCFS2_I(dir)->ip_alloc_sem);
3254 	drop_alloc_sem = 1;
3255 	dir_i_size = i_size_read(dir);
3256 	trace_ocfs2_extend_dir((unsigned long long)OCFS2_I(dir)->ip_blkno,
3257 			       dir_i_size);
3258 
3259 	/* dir->i_size is always block aligned. */
3260 	spin_lock(&OCFS2_I(dir)->ip_lock);
3261 	if (dir_i_size == ocfs2_clusters_to_bytes(sb, OCFS2_I(dir)->ip_clusters)) {
3262 		spin_unlock(&OCFS2_I(dir)->ip_lock);
3263 		ocfs2_init_dinode_extent_tree(&et, INODE_CACHE(dir),
3264 					      parent_fe_bh);
3265 		num_free_extents = ocfs2_num_free_extents(&et);
3266 		if (num_free_extents < 0) {
3267 			status = num_free_extents;
3268 			mlog_errno(status);
3269 			goto bail;
3270 		}
3271 
3272 		if (!num_free_extents) {
3273 			status = ocfs2_reserve_new_metadata(osb, el, &meta_ac);
3274 			if (status < 0) {
3275 				if (status != -ENOSPC)
3276 					mlog_errno(status);
3277 				goto bail;
3278 			}
3279 		}
3280 
3281 		status = ocfs2_reserve_clusters(osb, 1, &data_ac);
3282 		if (status < 0) {
3283 			if (status != -ENOSPC)
3284 				mlog_errno(status);
3285 			goto bail;
3286 		}
3287 
3288 		if (ocfs2_dir_resv_allowed(osb))
3289 			data_ac->ac_resv = &OCFS2_I(dir)->ip_la_data_resv;
3290 
3291 		credits = ocfs2_calc_extend_credits(sb, el);
3292 	} else {
3293 		spin_unlock(&OCFS2_I(dir)->ip_lock);
3294 		credits = OCFS2_SIMPLE_DIR_EXTEND_CREDITS;
3295 	}
3296 
3297 do_extend:
3298 	if (ocfs2_dir_indexed(dir))
3299 		credits++; /* For attaching the new dirent block to the
3300 			    * dx_root */
3301 
3302 	handle = ocfs2_start_trans(osb, credits);
3303 	if (IS_ERR(handle)) {
3304 		status = PTR_ERR(handle);
3305 		handle = NULL;
3306 		mlog_errno(status);
3307 		goto bail;
3308 	}
3309 
3310 	status = ocfs2_do_extend_dir(osb->sb, handle, dir, parent_fe_bh,
3311 				     data_ac, meta_ac, &new_bh);
3312 	if (status < 0) {
3313 		mlog_errno(status);
3314 		goto bail;
3315 	}
3316 
3317 	ocfs2_set_new_buffer_uptodate(INODE_CACHE(dir), new_bh);
3318 
3319 	status = ocfs2_journal_access_db(handle, INODE_CACHE(dir), new_bh,
3320 					 OCFS2_JOURNAL_ACCESS_CREATE);
3321 	if (status < 0) {
3322 		mlog_errno(status);
3323 		goto bail;
3324 	}
3325 	memset(new_bh->b_data, 0, sb->s_blocksize);
3326 
3327 	de = (struct ocfs2_dir_entry *) new_bh->b_data;
3328 	de->inode = 0;
3329 	if (ocfs2_supports_dir_trailer(dir)) {
3330 		de->rec_len = cpu_to_le16(ocfs2_dir_trailer_blk_off(sb));
3331 
3332 		ocfs2_init_dir_trailer(dir, new_bh, le16_to_cpu(de->rec_len));
3333 
3334 		if (ocfs2_dir_indexed(dir)) {
3335 			status = ocfs2_dx_dir_link_trailer(dir, handle,
3336 							   dx_root_bh, new_bh);
3337 			if (status) {
3338 				mlog_errno(status);
3339 				goto bail;
3340 			}
3341 		}
3342 	} else {
3343 		de->rec_len = cpu_to_le16(sb->s_blocksize);
3344 	}
3345 	ocfs2_update_inode_fsync_trans(handle, dir, 1);
3346 	ocfs2_journal_dirty(handle, new_bh);
3347 
3348 	dir_i_size += dir->i_sb->s_blocksize;
3349 	i_size_write(dir, dir_i_size);
3350 	dir->i_blocks = ocfs2_inode_sector_count(dir);
3351 	status = ocfs2_mark_inode_dirty(handle, dir, parent_fe_bh);
3352 	if (status < 0) {
3353 		mlog_errno(status);
3354 		goto bail;
3355 	}
3356 
3357 bail_bh:
3358 	*new_de_bh = new_bh;
3359 	get_bh(*new_de_bh);
3360 bail:
3361 	if (handle)
3362 		ocfs2_commit_trans(osb, handle);
3363 	if (drop_alloc_sem)
3364 		up_write(&OCFS2_I(dir)->ip_alloc_sem);
3365 
3366 	if (data_ac)
3367 		ocfs2_free_alloc_context(data_ac);
3368 	if (meta_ac)
3369 		ocfs2_free_alloc_context(meta_ac);
3370 
3371 	brelse(new_bh);
3372 
3373 	return status;
3374 }
3375 
3376 static int ocfs2_find_dir_space_id(struct inode *dir, struct buffer_head *di_bh,
3377 				   const char *name, int namelen,
3378 				   struct buffer_head **ret_de_bh,
3379 				   unsigned int *blocks_wanted)
3380 {
3381 	int ret;
3382 	struct super_block *sb = dir->i_sb;
3383 	struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
3384 	struct ocfs2_dir_entry *de, *last_de = NULL;
3385 	char *first_de, *de_buf, *limit;
3386 	unsigned long offset = 0;
3387 	unsigned int rec_len, new_rec_len, free_space;
3388 
3389 	/*
3390 	 * This calculates how many free bytes we'd have in block zero, should
3391 	 * this function force expansion to an extent tree.
3392 	 */
3393 	if (ocfs2_new_dir_wants_trailer(dir))
3394 		free_space = ocfs2_dir_trailer_blk_off(sb) - i_size_read(dir);
3395 	else
3396 		free_space = dir->i_sb->s_blocksize - i_size_read(dir);
3397 
3398 	first_de = di->id2.i_data.id_data;
3399 	de_buf = first_de;
3400 	limit = de_buf + i_size_read(dir);
3401 	rec_len = OCFS2_DIR_REC_LEN(namelen);
3402 
3403 	while (de_buf < limit) {
3404 		de = (struct ocfs2_dir_entry *)de_buf;
3405 
3406 		if (!ocfs2_check_dir_entry(dir, de, di_bh, first_de,
3407 					   i_size_read(dir), offset)) {
3408 			ret = -ENOENT;
3409 			goto out;
3410 		}
3411 		if (ocfs2_match(namelen, name, de)) {
3412 			ret = -EEXIST;
3413 			goto out;
3414 		}
3415 		/*
3416 		 * No need to check for a trailing dirent record here as
3417 		 * they're not used for inline dirs.
3418 		 */
3419 
3420 		if (ocfs2_dirent_would_fit(de, rec_len)) {
3421 			/* Ok, we found a spot. Return this bh and let
3422 			 * the caller actually fill it in. */
3423 			*ret_de_bh = di_bh;
3424 			get_bh(*ret_de_bh);
3425 			ret = 0;
3426 			goto out;
3427 		}
3428 
3429 		last_de = de;
3430 		de_buf += le16_to_cpu(de->rec_len);
3431 		offset += le16_to_cpu(de->rec_len);
3432 	}
3433 
3434 	/*
3435 	 * We're going to require expansion of the directory - figure
3436 	 * out how many blocks we'll need so that a place for the
3437 	 * dirent can be found.
3438 	 */
3439 	*blocks_wanted = 1;
3440 	new_rec_len = le16_to_cpu(last_de->rec_len) + free_space;
3441 	if (new_rec_len < (rec_len + OCFS2_DIR_REC_LEN(last_de->name_len)))
3442 		*blocks_wanted = 2;
3443 
3444 	ret = -ENOSPC;
3445 out:
3446 	return ret;
3447 }
3448 
3449 static int ocfs2_find_dir_space_el(struct inode *dir, const char *name,
3450 				   int namelen, struct buffer_head **ret_de_bh)
3451 {
3452 	unsigned long offset;
3453 	struct buffer_head *bh = NULL;
3454 	unsigned short rec_len;
3455 	struct ocfs2_dir_entry *de;
3456 	struct super_block *sb = dir->i_sb;
3457 	int status;
3458 	int blocksize = dir->i_sb->s_blocksize;
3459 
3460 	status = ocfs2_read_dir_block(dir, 0, &bh, 0);
3461 	if (status)
3462 		goto bail;
3463 
3464 	rec_len = OCFS2_DIR_REC_LEN(namelen);
3465 	offset = 0;
3466 	de = (struct ocfs2_dir_entry *) bh->b_data;
3467 	while (1) {
3468 		if ((char *)de >= sb->s_blocksize + bh->b_data) {
3469 			brelse(bh);
3470 			bh = NULL;
3471 
3472 			if (i_size_read(dir) <= offset) {
3473 				/*
3474 				 * Caller will have to expand this
3475 				 * directory.
3476 				 */
3477 				status = -ENOSPC;
3478 				goto bail;
3479 			}
3480 			status = ocfs2_read_dir_block(dir,
3481 					     offset >> sb->s_blocksize_bits,
3482 					     &bh, 0);
3483 			if (status)
3484 				goto bail;
3485 
3486 			/* move to next block */
3487 			de = (struct ocfs2_dir_entry *) bh->b_data;
3488 		}
3489 		if (!ocfs2_check_dir_entry(dir, de, bh, bh->b_data, blocksize,
3490 					   offset)) {
3491 			status = -ENOENT;
3492 			goto bail;
3493 		}
3494 		if (ocfs2_match(namelen, name, de)) {
3495 			status = -EEXIST;
3496 			goto bail;
3497 		}
3498 
3499 		if (ocfs2_skip_dir_trailer(dir, de, offset % blocksize,
3500 					   blocksize))
3501 			goto next;
3502 
3503 		if (ocfs2_dirent_would_fit(de, rec_len)) {
3504 			/* Ok, we found a spot. Return this bh and let
3505 			 * the caller actually fill it in. */
3506 			*ret_de_bh = bh;
3507 			get_bh(*ret_de_bh);
3508 			status = 0;
3509 			goto bail;
3510 		}
3511 next:
3512 		offset += le16_to_cpu(de->rec_len);
3513 		de = (struct ocfs2_dir_entry *)((char *) de + le16_to_cpu(de->rec_len));
3514 	}
3515 
3516 bail:
3517 	brelse(bh);
3518 	if (status)
3519 		mlog_errno(status);
3520 
3521 	return status;
3522 }
3523 
3524 static int dx_leaf_sort_cmp(const void *a, const void *b)
3525 {
3526 	const struct ocfs2_dx_entry *entry1 = a;
3527 	const struct ocfs2_dx_entry *entry2 = b;
3528 	u32 major_hash1 = le32_to_cpu(entry1->dx_major_hash);
3529 	u32 major_hash2 = le32_to_cpu(entry2->dx_major_hash);
3530 	u32 minor_hash1 = le32_to_cpu(entry1->dx_minor_hash);
3531 	u32 minor_hash2 = le32_to_cpu(entry2->dx_minor_hash);
3532 
3533 	if (major_hash1 > major_hash2)
3534 		return 1;
3535 	if (major_hash1 < major_hash2)
3536 		return -1;
3537 
3538 	/*
3539 	 * It is not strictly necessary to sort by minor
3540 	 */
3541 	if (minor_hash1 > minor_hash2)
3542 		return 1;
3543 	if (minor_hash1 < minor_hash2)
3544 		return -1;
3545 	return 0;
3546 }
3547 
3548 static int ocfs2_dx_leaf_same_major(struct ocfs2_dx_leaf *dx_leaf)
3549 {
3550 	struct ocfs2_dx_entry_list *dl_list = &dx_leaf->dl_list;
3551 	int i, num = le16_to_cpu(dl_list->de_num_used);
3552 
3553 	for (i = 0; i < (num - 1); i++) {
3554 		if (le32_to_cpu(dl_list->de_entries[i].dx_major_hash) !=
3555 		    le32_to_cpu(dl_list->de_entries[i + 1].dx_major_hash))
3556 			return 0;
3557 	}
3558 
3559 	return 1;
3560 }
3561 
3562 /*
3563  * Find the optimal value to split this leaf on. This expects the leaf
3564  * entries to be in sorted order.
3565  *
3566  * leaf_cpos is the cpos of the leaf we're splitting. insert_hash is
3567  * the hash we want to insert.
3568  *
3569  * This function is only concerned with the major hash - that which
3570  * determines which cluster an item belongs to.
3571  */
3572 static int ocfs2_dx_dir_find_leaf_split(struct ocfs2_dx_leaf *dx_leaf,
3573 					u32 leaf_cpos, u32 insert_hash,
3574 					u32 *split_hash)
3575 {
3576 	struct ocfs2_dx_entry_list *dl_list = &dx_leaf->dl_list;
3577 	int i, num_used = le16_to_cpu(dl_list->de_num_used);
3578 	int allsame;
3579 
3580 	/*
3581 	 * There's a couple rare, but nasty corner cases we have to
3582 	 * check for here. All of them involve a leaf where all value
3583 	 * have the same hash, which is what we look for first.
3584 	 *
3585 	 * Most of the time, all of the above is false, and we simply
3586 	 * pick the median value for a split.
3587 	 */
3588 	allsame = ocfs2_dx_leaf_same_major(dx_leaf);
3589 	if (allsame) {
3590 		u32 val = le32_to_cpu(dl_list->de_entries[0].dx_major_hash);
3591 
3592 		if (val == insert_hash) {
3593 			/*
3594 			 * No matter where we would choose to split,
3595 			 * the new entry would want to occupy the same
3596 			 * block as these. Since there's no space left
3597 			 * in their existing block, we know there
3598 			 * won't be space after the split.
3599 			 */
3600 			return -ENOSPC;
3601 		}
3602 
3603 		if (val == leaf_cpos) {
3604 			/*
3605 			 * Because val is the same as leaf_cpos (which
3606 			 * is the smallest value this leaf can have),
3607 			 * yet is not equal to insert_hash, then we
3608 			 * know that insert_hash *must* be larger than
3609 			 * val (and leaf_cpos). At least cpos+1 in value.
3610 			 *
3611 			 * We also know then, that there cannot be an
3612 			 * adjacent extent (otherwise we'd be looking
3613 			 * at it). Choosing this value gives us a
3614 			 * chance to get some contiguousness.
3615 			 */
3616 			*split_hash = leaf_cpos + 1;
3617 			return 0;
3618 		}
3619 
3620 		if (val > insert_hash) {
3621 			/*
3622 			 * val can not be the same as insert hash, and
3623 			 * also must be larger than leaf_cpos. Also,
3624 			 * we know that there can't be a leaf between
3625 			 * cpos and val, otherwise the entries with
3626 			 * hash 'val' would be there.
3627 			 */
3628 			*split_hash = val;
3629 			return 0;
3630 		}
3631 
3632 		*split_hash = insert_hash;
3633 		return 0;
3634 	}
3635 
3636 	/*
3637 	 * Since the records are sorted and the checks above
3638 	 * guaranteed that not all records in this block are the same,
3639 	 * we simple travel forward, from the median, and pick the 1st
3640 	 * record whose value is larger than leaf_cpos.
3641 	 */
3642 	for (i = (num_used / 2); i < num_used; i++)
3643 		if (le32_to_cpu(dl_list->de_entries[i].dx_major_hash) >
3644 		    leaf_cpos)
3645 			break;
3646 
3647 	BUG_ON(i == num_used); /* Should be impossible */
3648 	*split_hash = le32_to_cpu(dl_list->de_entries[i].dx_major_hash);
3649 	return 0;
3650 }
3651 
3652 /*
3653  * Transfer all entries in orig_dx_leaves whose major hash is equal to or
3654  * larger than split_hash into new_dx_leaves. We use a temporary
3655  * buffer (tmp_dx_leaf) to make the changes to the original leaf blocks.
3656  *
3657  * Since the block offset inside a leaf (cluster) is a constant mask
3658  * of minor_hash, we can optimize - an item at block offset X within
3659  * the original cluster, will be at offset X within the new cluster.
3660  */
3661 static void ocfs2_dx_dir_transfer_leaf(struct inode *dir, u32 split_hash,
3662 				       handle_t *handle,
3663 				       struct ocfs2_dx_leaf *tmp_dx_leaf,
3664 				       struct buffer_head **orig_dx_leaves,
3665 				       struct buffer_head **new_dx_leaves,
3666 				       int num_dx_leaves)
3667 {
3668 	int i, j, num_used;
3669 	u32 major_hash;
3670 	struct ocfs2_dx_leaf *orig_dx_leaf, *new_dx_leaf;
3671 	struct ocfs2_dx_entry_list *orig_list, *tmp_list;
3672 	struct ocfs2_dx_entry *dx_entry;
3673 
3674 	tmp_list = &tmp_dx_leaf->dl_list;
3675 
3676 	for (i = 0; i < num_dx_leaves; i++) {
3677 		orig_dx_leaf = (struct ocfs2_dx_leaf *) orig_dx_leaves[i]->b_data;
3678 		orig_list = &orig_dx_leaf->dl_list;
3679 		new_dx_leaf = (struct ocfs2_dx_leaf *) new_dx_leaves[i]->b_data;
3680 
3681 		num_used = le16_to_cpu(orig_list->de_num_used);
3682 
3683 		memcpy(tmp_dx_leaf, orig_dx_leaf, dir->i_sb->s_blocksize);
3684 		tmp_list->de_num_used = cpu_to_le16(0);
3685 		memset(&tmp_list->de_entries, 0, sizeof(*dx_entry)*num_used);
3686 
3687 		for (j = 0; j < num_used; j++) {
3688 			dx_entry = &orig_list->de_entries[j];
3689 			major_hash = le32_to_cpu(dx_entry->dx_major_hash);
3690 			if (major_hash >= split_hash)
3691 				ocfs2_dx_dir_leaf_insert_tail(new_dx_leaf,
3692 							      dx_entry);
3693 			else
3694 				ocfs2_dx_dir_leaf_insert_tail(tmp_dx_leaf,
3695 							      dx_entry);
3696 		}
3697 		memcpy(orig_dx_leaf, tmp_dx_leaf, dir->i_sb->s_blocksize);
3698 
3699 		ocfs2_journal_dirty(handle, orig_dx_leaves[i]);
3700 		ocfs2_journal_dirty(handle, new_dx_leaves[i]);
3701 	}
3702 }
3703 
3704 static int ocfs2_dx_dir_rebalance_credits(struct ocfs2_super *osb,
3705 					  struct ocfs2_dx_root_block *dx_root)
3706 {
3707 	int credits = ocfs2_clusters_to_blocks(osb->sb, 3);
3708 
3709 	credits += ocfs2_calc_extend_credits(osb->sb, &dx_root->dr_list);
3710 	credits += ocfs2_quota_trans_credits(osb->sb);
3711 	return credits;
3712 }
3713 
3714 /*
3715  * Find the median value in dx_leaf_bh and allocate a new leaf to move
3716  * half our entries into.
3717  */
3718 static int ocfs2_dx_dir_rebalance(struct ocfs2_super *osb, struct inode *dir,
3719 				  struct buffer_head *dx_root_bh,
3720 				  struct buffer_head *dx_leaf_bh,
3721 				  struct ocfs2_dx_hinfo *hinfo, u32 leaf_cpos,
3722 				  u64 leaf_blkno)
3723 {
3724 	struct ocfs2_dx_leaf *dx_leaf = (struct ocfs2_dx_leaf *)dx_leaf_bh->b_data;
3725 	int credits, ret, i, num_used, did_quota = 0;
3726 	u32 cpos, split_hash, insert_hash = hinfo->major_hash;
3727 	u64 orig_leaves_start;
3728 	int num_dx_leaves;
3729 	struct buffer_head **orig_dx_leaves = NULL;
3730 	struct buffer_head **new_dx_leaves = NULL;
3731 	struct ocfs2_alloc_context *data_ac = NULL, *meta_ac = NULL;
3732 	struct ocfs2_extent_tree et;
3733 	handle_t *handle = NULL;
3734 	struct ocfs2_dx_root_block *dx_root;
3735 	struct ocfs2_dx_leaf *tmp_dx_leaf = NULL;
3736 
3737 	trace_ocfs2_dx_dir_rebalance((unsigned long long)OCFS2_I(dir)->ip_blkno,
3738 				     (unsigned long long)leaf_blkno,
3739 				     insert_hash);
3740 
3741 	ocfs2_init_dx_root_extent_tree(&et, INODE_CACHE(dir), dx_root_bh);
3742 
3743 	dx_root = (struct ocfs2_dx_root_block *)dx_root_bh->b_data;
3744 	/*
3745 	 * XXX: This is a rather large limit. We should use a more
3746 	 * realistic value.
3747 	 */
3748 	if (le32_to_cpu(dx_root->dr_clusters) == UINT_MAX)
3749 		return -ENOSPC;
3750 
3751 	num_used = le16_to_cpu(dx_leaf->dl_list.de_num_used);
3752 	if (num_used < le16_to_cpu(dx_leaf->dl_list.de_count)) {
3753 		mlog(ML_ERROR, "DX Dir: %llu, Asked to rebalance empty leaf: "
3754 		     "%llu, %d\n", (unsigned long long)OCFS2_I(dir)->ip_blkno,
3755 		     (unsigned long long)leaf_blkno, num_used);
3756 		ret = -EIO;
3757 		goto out;
3758 	}
3759 
3760 	orig_dx_leaves = ocfs2_dx_dir_kmalloc_leaves(osb->sb, &num_dx_leaves);
3761 	if (!orig_dx_leaves) {
3762 		ret = -ENOMEM;
3763 		mlog_errno(ret);
3764 		goto out;
3765 	}
3766 
3767 	new_dx_leaves = ocfs2_dx_dir_kmalloc_leaves(osb->sb, NULL);
3768 	if (!new_dx_leaves) {
3769 		ret = -ENOMEM;
3770 		mlog_errno(ret);
3771 		goto out;
3772 	}
3773 
3774 	ret = ocfs2_lock_allocators(dir, &et, 1, 0, &data_ac, &meta_ac);
3775 	if (ret) {
3776 		if (ret != -ENOSPC)
3777 			mlog_errno(ret);
3778 		goto out;
3779 	}
3780 
3781 	credits = ocfs2_dx_dir_rebalance_credits(osb, dx_root);
3782 	handle = ocfs2_start_trans(osb, credits);
3783 	if (IS_ERR(handle)) {
3784 		ret = PTR_ERR(handle);
3785 		handle = NULL;
3786 		mlog_errno(ret);
3787 		goto out;
3788 	}
3789 
3790 	ret = dquot_alloc_space_nodirty(dir,
3791 				       ocfs2_clusters_to_bytes(dir->i_sb, 1));
3792 	if (ret)
3793 		goto out_commit;
3794 	did_quota = 1;
3795 
3796 	ret = ocfs2_journal_access_dl(handle, INODE_CACHE(dir), dx_leaf_bh,
3797 				      OCFS2_JOURNAL_ACCESS_WRITE);
3798 	if (ret) {
3799 		mlog_errno(ret);
3800 		goto out_commit;
3801 	}
3802 
3803 	/*
3804 	 * This block is changing anyway, so we can sort it in place.
3805 	 */
3806 	sort(dx_leaf->dl_list.de_entries, num_used,
3807 	     sizeof(struct ocfs2_dx_entry), dx_leaf_sort_cmp,
3808 	     NULL);
3809 
3810 	ocfs2_journal_dirty(handle, dx_leaf_bh);
3811 
3812 	ret = ocfs2_dx_dir_find_leaf_split(dx_leaf, leaf_cpos, insert_hash,
3813 					   &split_hash);
3814 	if (ret) {
3815 		mlog_errno(ret);
3816 		goto  out_commit;
3817 	}
3818 
3819 	trace_ocfs2_dx_dir_rebalance_split(leaf_cpos, split_hash, insert_hash);
3820 
3821 	/*
3822 	 * We have to carefully order operations here. There are items
3823 	 * which want to be in the new cluster before insert, but in
3824 	 * order to put those items in the new cluster, we alter the
3825 	 * old cluster. A failure to insert gets nasty.
3826 	 *
3827 	 * So, start by reserving writes to the old
3828 	 * cluster. ocfs2_dx_dir_new_cluster will reserve writes on
3829 	 * the new cluster for us, before inserting it. The insert
3830 	 * won't happen if there's an error before that. Once the
3831 	 * insert is done then, we can transfer from one leaf into the
3832 	 * other without fear of hitting any error.
3833 	 */
3834 
3835 	/*
3836 	 * The leaf transfer wants some scratch space so that we don't
3837 	 * wind up doing a bunch of expensive memmove().
3838 	 */
3839 	tmp_dx_leaf = kmalloc(osb->sb->s_blocksize, GFP_NOFS);
3840 	if (!tmp_dx_leaf) {
3841 		ret = -ENOMEM;
3842 		mlog_errno(ret);
3843 		goto out_commit;
3844 	}
3845 
3846 	orig_leaves_start = ocfs2_block_to_cluster_start(dir->i_sb, leaf_blkno);
3847 	ret = ocfs2_read_dx_leaves(dir, orig_leaves_start, num_dx_leaves,
3848 				   orig_dx_leaves);
3849 	if (ret) {
3850 		mlog_errno(ret);
3851 		goto out_commit;
3852 	}
3853 
3854 	cpos = split_hash;
3855 	ret = ocfs2_dx_dir_new_cluster(dir, &et, cpos, handle,
3856 				       data_ac, meta_ac, new_dx_leaves,
3857 				       num_dx_leaves);
3858 	if (ret) {
3859 		mlog_errno(ret);
3860 		goto out_commit;
3861 	}
3862 
3863 	for (i = 0; i < num_dx_leaves; i++) {
3864 		ret = ocfs2_journal_access_dl(handle, INODE_CACHE(dir),
3865 					      orig_dx_leaves[i],
3866 					      OCFS2_JOURNAL_ACCESS_WRITE);
3867 		if (ret) {
3868 			mlog_errno(ret);
3869 			goto out_commit;
3870 		}
3871 
3872 		ret = ocfs2_journal_access_dl(handle, INODE_CACHE(dir),
3873 					      new_dx_leaves[i],
3874 					      OCFS2_JOURNAL_ACCESS_WRITE);
3875 		if (ret) {
3876 			mlog_errno(ret);
3877 			goto out_commit;
3878 		}
3879 	}
3880 
3881 	ocfs2_dx_dir_transfer_leaf(dir, split_hash, handle, tmp_dx_leaf,
3882 				   orig_dx_leaves, new_dx_leaves, num_dx_leaves);
3883 
3884 out_commit:
3885 	if (ret < 0 && did_quota)
3886 		dquot_free_space_nodirty(dir,
3887 				ocfs2_clusters_to_bytes(dir->i_sb, 1));
3888 
3889 	ocfs2_update_inode_fsync_trans(handle, dir, 1);
3890 	ocfs2_commit_trans(osb, handle);
3891 
3892 out:
3893 	if (orig_dx_leaves || new_dx_leaves) {
3894 		for (i = 0; i < num_dx_leaves; i++) {
3895 			if (orig_dx_leaves)
3896 				brelse(orig_dx_leaves[i]);
3897 			if (new_dx_leaves)
3898 				brelse(new_dx_leaves[i]);
3899 		}
3900 		kfree(orig_dx_leaves);
3901 		kfree(new_dx_leaves);
3902 	}
3903 
3904 	if (meta_ac)
3905 		ocfs2_free_alloc_context(meta_ac);
3906 	if (data_ac)
3907 		ocfs2_free_alloc_context(data_ac);
3908 
3909 	kfree(tmp_dx_leaf);
3910 	return ret;
3911 }
3912 
3913 static int ocfs2_find_dir_space_dx(struct ocfs2_super *osb, struct inode *dir,
3914 				   struct buffer_head *di_bh,
3915 				   struct buffer_head *dx_root_bh,
3916 				   const char *name, int namelen,
3917 				   struct ocfs2_dir_lookup_result *lookup)
3918 {
3919 	int ret, rebalanced = 0;
3920 	struct ocfs2_dx_root_block *dx_root;
3921 	struct buffer_head *dx_leaf_bh = NULL;
3922 	struct ocfs2_dx_leaf *dx_leaf;
3923 	u64 blkno;
3924 	u32 leaf_cpos;
3925 
3926 	dx_root = (struct ocfs2_dx_root_block *)dx_root_bh->b_data;
3927 
3928 restart_search:
3929 	ret = ocfs2_dx_dir_lookup(dir, &dx_root->dr_list, &lookup->dl_hinfo,
3930 				  &leaf_cpos, &blkno);
3931 	if (ret) {
3932 		mlog_errno(ret);
3933 		goto out;
3934 	}
3935 
3936 	ret = ocfs2_read_dx_leaf(dir, blkno, &dx_leaf_bh);
3937 	if (ret) {
3938 		mlog_errno(ret);
3939 		goto out;
3940 	}
3941 
3942 	dx_leaf = (struct ocfs2_dx_leaf *)dx_leaf_bh->b_data;
3943 
3944 	if (le16_to_cpu(dx_leaf->dl_list.de_num_used) >=
3945 	    le16_to_cpu(dx_leaf->dl_list.de_count)) {
3946 		if (rebalanced) {
3947 			/*
3948 			 * Rebalancing should have provided us with
3949 			 * space in an appropriate leaf.
3950 			 *
3951 			 * XXX: Is this an abnormal condition then?
3952 			 * Should we print a message here?
3953 			 */
3954 			ret = -ENOSPC;
3955 			goto out;
3956 		}
3957 
3958 		ret = ocfs2_dx_dir_rebalance(osb, dir, dx_root_bh, dx_leaf_bh,
3959 					     &lookup->dl_hinfo, leaf_cpos,
3960 					     blkno);
3961 		if (ret) {
3962 			if (ret != -ENOSPC)
3963 				mlog_errno(ret);
3964 			goto out;
3965 		}
3966 
3967 		/*
3968 		 * Restart the lookup. The rebalance might have
3969 		 * changed which block our item fits into. Mark our
3970 		 * progress, so we only execute this once.
3971 		 */
3972 		brelse(dx_leaf_bh);
3973 		dx_leaf_bh = NULL;
3974 		rebalanced = 1;
3975 		goto restart_search;
3976 	}
3977 
3978 	lookup->dl_dx_leaf_bh = dx_leaf_bh;
3979 	dx_leaf_bh = NULL;
3980 
3981 out:
3982 	brelse(dx_leaf_bh);
3983 	return ret;
3984 }
3985 
3986 static int ocfs2_search_dx_free_list(struct inode *dir,
3987 				     struct buffer_head *dx_root_bh,
3988 				     int namelen,
3989 				     struct ocfs2_dir_lookup_result *lookup)
3990 {
3991 	int ret = -ENOSPC;
3992 	struct buffer_head *leaf_bh = NULL, *prev_leaf_bh = NULL;
3993 	struct ocfs2_dir_block_trailer *db;
3994 	u64 next_block;
3995 	int rec_len = OCFS2_DIR_REC_LEN(namelen);
3996 	struct ocfs2_dx_root_block *dx_root;
3997 
3998 	dx_root = (struct ocfs2_dx_root_block *)dx_root_bh->b_data;
3999 	next_block = le64_to_cpu(dx_root->dr_free_blk);
4000 
4001 	while (next_block) {
4002 		brelse(prev_leaf_bh);
4003 		prev_leaf_bh = leaf_bh;
4004 		leaf_bh = NULL;
4005 
4006 		ret = ocfs2_read_dir_block_direct(dir, next_block, &leaf_bh);
4007 		if (ret) {
4008 			mlog_errno(ret);
4009 			goto out;
4010 		}
4011 
4012 		db = ocfs2_trailer_from_bh(leaf_bh, dir->i_sb);
4013 		if (rec_len <= le16_to_cpu(db->db_free_rec_len)) {
4014 			lookup->dl_leaf_bh = leaf_bh;
4015 			lookup->dl_prev_leaf_bh = prev_leaf_bh;
4016 			leaf_bh = NULL;
4017 			prev_leaf_bh = NULL;
4018 			break;
4019 		}
4020 
4021 		next_block = le64_to_cpu(db->db_free_next);
4022 	}
4023 
4024 	if (!next_block)
4025 		ret = -ENOSPC;
4026 
4027 out:
4028 
4029 	brelse(leaf_bh);
4030 	brelse(prev_leaf_bh);
4031 	return ret;
4032 }
4033 
4034 static int ocfs2_expand_inline_dx_root(struct inode *dir,
4035 				       struct buffer_head *dx_root_bh)
4036 {
4037 	int ret, num_dx_leaves, i, j, did_quota = 0;
4038 	struct buffer_head **dx_leaves = NULL;
4039 	struct ocfs2_extent_tree et;
4040 	u64 insert_blkno;
4041 	struct ocfs2_alloc_context *data_ac = NULL;
4042 	struct ocfs2_super *osb = OCFS2_SB(dir->i_sb);
4043 	handle_t *handle = NULL;
4044 	struct ocfs2_dx_root_block *dx_root;
4045 	struct ocfs2_dx_entry_list *entry_list;
4046 	struct ocfs2_dx_entry *dx_entry;
4047 	struct ocfs2_dx_leaf *target_leaf;
4048 
4049 	ret = ocfs2_reserve_clusters(osb, 1, &data_ac);
4050 	if (ret) {
4051 		mlog_errno(ret);
4052 		goto out;
4053 	}
4054 
4055 	dx_leaves = ocfs2_dx_dir_kmalloc_leaves(osb->sb, &num_dx_leaves);
4056 	if (!dx_leaves) {
4057 		ret = -ENOMEM;
4058 		mlog_errno(ret);
4059 		goto out;
4060 	}
4061 
4062 	handle = ocfs2_start_trans(osb, ocfs2_calc_dxi_expand_credits(osb->sb));
4063 	if (IS_ERR(handle)) {
4064 		ret = PTR_ERR(handle);
4065 		mlog_errno(ret);
4066 		goto out;
4067 	}
4068 
4069 	ret = dquot_alloc_space_nodirty(dir,
4070 				       ocfs2_clusters_to_bytes(osb->sb, 1));
4071 	if (ret)
4072 		goto out_commit;
4073 	did_quota = 1;
4074 
4075 	/*
4076 	 * We do this up front, before the allocation, so that a
4077 	 * failure to add the dx_root_bh to the journal won't result
4078 	 * us losing clusters.
4079 	 */
4080 	ret = ocfs2_journal_access_dr(handle, INODE_CACHE(dir), dx_root_bh,
4081 				      OCFS2_JOURNAL_ACCESS_WRITE);
4082 	if (ret) {
4083 		mlog_errno(ret);
4084 		goto out_commit;
4085 	}
4086 
4087 	ret = __ocfs2_dx_dir_new_cluster(dir, 0, handle, data_ac, dx_leaves,
4088 					 num_dx_leaves, &insert_blkno);
4089 	if (ret) {
4090 		mlog_errno(ret);
4091 		goto out_commit;
4092 	}
4093 
4094 	/*
4095 	 * Transfer the entries from our dx_root into the appropriate
4096 	 * block
4097 	 */
4098 	dx_root = (struct ocfs2_dx_root_block *) dx_root_bh->b_data;
4099 	entry_list = &dx_root->dr_entries;
4100 
4101 	for (i = 0; i < le16_to_cpu(entry_list->de_num_used); i++) {
4102 		dx_entry = &entry_list->de_entries[i];
4103 
4104 		j = __ocfs2_dx_dir_hash_idx(osb,
4105 					    le32_to_cpu(dx_entry->dx_minor_hash));
4106 		target_leaf = (struct ocfs2_dx_leaf *)dx_leaves[j]->b_data;
4107 
4108 		ocfs2_dx_dir_leaf_insert_tail(target_leaf, dx_entry);
4109 
4110 		/* Each leaf has been passed to the journal already
4111 		 * via __ocfs2_dx_dir_new_cluster() */
4112 	}
4113 
4114 	dx_root->dr_flags &= ~OCFS2_DX_FLAG_INLINE;
4115 
4116 	dx_root->dr_list.l_tree_depth = 0;
4117 	dx_root->dr_list.l_count =
4118 		cpu_to_le16(ocfs2_extent_recs_per_dx_root(osb->sb));
4119 	dx_root->dr_list.l_next_free_rec = 0;
4120 	memset(&dx_root->dr_list.l_recs, 0,
4121 	       osb->sb->s_blocksize -
4122 	       (offsetof(struct ocfs2_dx_root_block, dr_list) +
4123 		offsetof(struct ocfs2_extent_list, l_recs)));
4124 
4125 	/* This should never fail considering we start with an empty
4126 	 * dx_root. */
4127 	ocfs2_init_dx_root_extent_tree(&et, INODE_CACHE(dir), dx_root_bh);
4128 	ret = ocfs2_insert_extent(handle, &et, 0, insert_blkno, 1, 0, NULL);
4129 	if (ret)
4130 		mlog_errno(ret);
4131 	did_quota = 0;
4132 
4133 	ocfs2_update_inode_fsync_trans(handle, dir, 1);
4134 	ocfs2_journal_dirty(handle, dx_root_bh);
4135 
4136 out_commit:
4137 	if (ret < 0 && did_quota)
4138 		dquot_free_space_nodirty(dir,
4139 					  ocfs2_clusters_to_bytes(dir->i_sb, 1));
4140 
4141 	ocfs2_commit_trans(osb, handle);
4142 
4143 out:
4144 	if (data_ac)
4145 		ocfs2_free_alloc_context(data_ac);
4146 
4147 	if (dx_leaves) {
4148 		for (i = 0; i < num_dx_leaves; i++)
4149 			brelse(dx_leaves[i]);
4150 		kfree(dx_leaves);
4151 	}
4152 	return ret;
4153 }
4154 
4155 static int ocfs2_inline_dx_has_space(struct buffer_head *dx_root_bh)
4156 {
4157 	struct ocfs2_dx_root_block *dx_root;
4158 	struct ocfs2_dx_entry_list *entry_list;
4159 
4160 	dx_root = (struct ocfs2_dx_root_block *) dx_root_bh->b_data;
4161 	entry_list = &dx_root->dr_entries;
4162 
4163 	if (le16_to_cpu(entry_list->de_num_used) >=
4164 	    le16_to_cpu(entry_list->de_count))
4165 		return -ENOSPC;
4166 
4167 	return 0;
4168 }
4169 
4170 static int ocfs2_prepare_dx_dir_for_insert(struct inode *dir,
4171 					   struct buffer_head *di_bh,
4172 					   const char *name,
4173 					   int namelen,
4174 					   struct ocfs2_dir_lookup_result *lookup)
4175 {
4176 	int ret, free_dx_root = 1;
4177 	struct ocfs2_super *osb = OCFS2_SB(dir->i_sb);
4178 	struct buffer_head *dx_root_bh = NULL;
4179 	struct buffer_head *leaf_bh = NULL;
4180 	struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
4181 	struct ocfs2_dx_root_block *dx_root;
4182 
4183 	ret = ocfs2_read_dx_root(dir, di, &dx_root_bh);
4184 	if (ret) {
4185 		mlog_errno(ret);
4186 		goto out;
4187 	}
4188 
4189 	dx_root = (struct ocfs2_dx_root_block *)dx_root_bh->b_data;
4190 	if (le32_to_cpu(dx_root->dr_num_entries) == OCFS2_DX_ENTRIES_MAX) {
4191 		ret = -ENOSPC;
4192 		mlog_errno(ret);
4193 		goto out;
4194 	}
4195 
4196 	if (ocfs2_dx_root_inline(dx_root)) {
4197 		ret = ocfs2_inline_dx_has_space(dx_root_bh);
4198 
4199 		if (ret == 0)
4200 			goto search_el;
4201 
4202 		/*
4203 		 * We ran out of room in the root block. Expand it to
4204 		 * an extent, then allow ocfs2_find_dir_space_dx to do
4205 		 * the rest.
4206 		 */
4207 		ret = ocfs2_expand_inline_dx_root(dir, dx_root_bh);
4208 		if (ret) {
4209 			mlog_errno(ret);
4210 			goto out;
4211 		}
4212 	}
4213 
4214 	/*
4215 	 * Insert preparation for an indexed directory is split into two
4216 	 * steps. The call to find_dir_space_dx reserves room in the index for
4217 	 * an additional item. If we run out of space there, it's a real error
4218 	 * we can't continue on.
4219 	 */
4220 	ret = ocfs2_find_dir_space_dx(osb, dir, di_bh, dx_root_bh, name,
4221 				      namelen, lookup);
4222 	if (ret) {
4223 		mlog_errno(ret);
4224 		goto out;
4225 	}
4226 
4227 search_el:
4228 	/*
4229 	 * Next, we need to find space in the unindexed tree. This call
4230 	 * searches using the free space linked list. If the unindexed tree
4231 	 * lacks sufficient space, we'll expand it below. The expansion code
4232 	 * is smart enough to add any new blocks to the free space list.
4233 	 */
4234 	ret = ocfs2_search_dx_free_list(dir, dx_root_bh, namelen, lookup);
4235 	if (ret && ret != -ENOSPC) {
4236 		mlog_errno(ret);
4237 		goto out;
4238 	}
4239 
4240 	/* Do this up here - ocfs2_extend_dir might need the dx_root */
4241 	lookup->dl_dx_root_bh = dx_root_bh;
4242 	free_dx_root = 0;
4243 
4244 	if (ret == -ENOSPC) {
4245 		ret = ocfs2_extend_dir(osb, dir, di_bh, 1, lookup, &leaf_bh);
4246 
4247 		if (ret) {
4248 			mlog_errno(ret);
4249 			goto out;
4250 		}
4251 
4252 		/*
4253 		 * We make the assumption here that new leaf blocks are added
4254 		 * to the front of our free list.
4255 		 */
4256 		lookup->dl_prev_leaf_bh = NULL;
4257 		lookup->dl_leaf_bh = leaf_bh;
4258 	}
4259 
4260 out:
4261 	if (free_dx_root)
4262 		brelse(dx_root_bh);
4263 	return ret;
4264 }
4265 
4266 /*
4267  * Get a directory ready for insert. Any directory allocation required
4268  * happens here. Success returns zero, and enough context in the dir
4269  * lookup result that ocfs2_add_entry() will be able complete the task
4270  * with minimal performance impact.
4271  */
4272 int ocfs2_prepare_dir_for_insert(struct ocfs2_super *osb,
4273 				 struct inode *dir,
4274 				 struct buffer_head *parent_fe_bh,
4275 				 const char *name,
4276 				 int namelen,
4277 				 struct ocfs2_dir_lookup_result *lookup)
4278 {
4279 	int ret;
4280 	unsigned int blocks_wanted = 1;
4281 	struct buffer_head *bh = NULL;
4282 
4283 	trace_ocfs2_prepare_dir_for_insert(
4284 		(unsigned long long)OCFS2_I(dir)->ip_blkno, namelen);
4285 
4286 	/*
4287 	 * Do this up front to reduce confusion.
4288 	 *
4289 	 * The directory might start inline, then be turned into an
4290 	 * indexed one, in which case we'd need to hash deep inside
4291 	 * ocfs2_find_dir_space_id(). Since
4292 	 * ocfs2_prepare_dx_dir_for_insert() also needs this hash
4293 	 * done, there seems no point in spreading out the calls. We
4294 	 * can optimize away the case where the file system doesn't
4295 	 * support indexing.
4296 	 */
4297 	if (ocfs2_supports_indexed_dirs(osb))
4298 		ocfs2_dx_dir_name_hash(dir, name, namelen, &lookup->dl_hinfo);
4299 
4300 	if (ocfs2_dir_indexed(dir)) {
4301 		ret = ocfs2_prepare_dx_dir_for_insert(dir, parent_fe_bh,
4302 						      name, namelen, lookup);
4303 		if (ret)
4304 			mlog_errno(ret);
4305 		goto out;
4306 	}
4307 
4308 	if (OCFS2_I(dir)->ip_dyn_features & OCFS2_INLINE_DATA_FL) {
4309 		ret = ocfs2_find_dir_space_id(dir, parent_fe_bh, name,
4310 					      namelen, &bh, &blocks_wanted);
4311 	} else
4312 		ret = ocfs2_find_dir_space_el(dir, name, namelen, &bh);
4313 
4314 	if (ret && ret != -ENOSPC) {
4315 		mlog_errno(ret);
4316 		goto out;
4317 	}
4318 
4319 	if (ret == -ENOSPC) {
4320 		/*
4321 		 * We have to expand the directory to add this name.
4322 		 */
4323 		BUG_ON(bh);
4324 
4325 		ret = ocfs2_extend_dir(osb, dir, parent_fe_bh, blocks_wanted,
4326 				       lookup, &bh);
4327 		if (ret) {
4328 			if (ret != -ENOSPC)
4329 				mlog_errno(ret);
4330 			goto out;
4331 		}
4332 
4333 		BUG_ON(!bh);
4334 	}
4335 
4336 	lookup->dl_leaf_bh = bh;
4337 	bh = NULL;
4338 out:
4339 	brelse(bh);
4340 	return ret;
4341 }
4342 
4343 static int ocfs2_dx_dir_remove_index(struct inode *dir,
4344 				     struct buffer_head *di_bh,
4345 				     struct buffer_head *dx_root_bh)
4346 {
4347 	int ret;
4348 	struct ocfs2_super *osb = OCFS2_SB(dir->i_sb);
4349 	struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
4350 	struct ocfs2_dx_root_block *dx_root;
4351 	struct inode *dx_alloc_inode = NULL;
4352 	struct buffer_head *dx_alloc_bh = NULL;
4353 	handle_t *handle;
4354 	u64 blk;
4355 	u16 bit;
4356 	u64 bg_blkno;
4357 
4358 	dx_root = (struct ocfs2_dx_root_block *) dx_root_bh->b_data;
4359 
4360 	dx_alloc_inode = ocfs2_get_system_file_inode(osb,
4361 					EXTENT_ALLOC_SYSTEM_INODE,
4362 					le16_to_cpu(dx_root->dr_suballoc_slot));
4363 	if (!dx_alloc_inode) {
4364 		ret = -ENOMEM;
4365 		mlog_errno(ret);
4366 		goto out;
4367 	}
4368 	inode_lock(dx_alloc_inode);
4369 
4370 	ret = ocfs2_inode_lock(dx_alloc_inode, &dx_alloc_bh, 1);
4371 	if (ret) {
4372 		mlog_errno(ret);
4373 		goto out_mutex;
4374 	}
4375 
4376 	handle = ocfs2_start_trans(osb, OCFS2_DX_ROOT_REMOVE_CREDITS);
4377 	if (IS_ERR(handle)) {
4378 		ret = PTR_ERR(handle);
4379 		mlog_errno(ret);
4380 		goto out_unlock;
4381 	}
4382 
4383 	ret = ocfs2_journal_access_di(handle, INODE_CACHE(dir), di_bh,
4384 				      OCFS2_JOURNAL_ACCESS_WRITE);
4385 	if (ret) {
4386 		mlog_errno(ret);
4387 		goto out_commit;
4388 	}
4389 
4390 	spin_lock(&OCFS2_I(dir)->ip_lock);
4391 	OCFS2_I(dir)->ip_dyn_features &= ~OCFS2_INDEXED_DIR_FL;
4392 	di->i_dyn_features = cpu_to_le16(OCFS2_I(dir)->ip_dyn_features);
4393 	spin_unlock(&OCFS2_I(dir)->ip_lock);
4394 	di->i_dx_root = cpu_to_le64(0ULL);
4395 	ocfs2_update_inode_fsync_trans(handle, dir, 1);
4396 
4397 	ocfs2_journal_dirty(handle, di_bh);
4398 
4399 	blk = le64_to_cpu(dx_root->dr_blkno);
4400 	bit = le16_to_cpu(dx_root->dr_suballoc_bit);
4401 	if (dx_root->dr_suballoc_loc)
4402 		bg_blkno = le64_to_cpu(dx_root->dr_suballoc_loc);
4403 	else
4404 		bg_blkno = ocfs2_which_suballoc_group(blk, bit);
4405 	ret = ocfs2_free_suballoc_bits(handle, dx_alloc_inode, dx_alloc_bh,
4406 				       bit, bg_blkno, 1);
4407 	if (ret)
4408 		mlog_errno(ret);
4409 
4410 out_commit:
4411 	ocfs2_commit_trans(osb, handle);
4412 
4413 out_unlock:
4414 	ocfs2_inode_unlock(dx_alloc_inode, 1);
4415 
4416 out_mutex:
4417 	inode_unlock(dx_alloc_inode);
4418 	brelse(dx_alloc_bh);
4419 out:
4420 	iput(dx_alloc_inode);
4421 	return ret;
4422 }
4423 
4424 int ocfs2_dx_dir_truncate(struct inode *dir, struct buffer_head *di_bh)
4425 {
4426 	int ret;
4427 	unsigned int clen;
4428 	u32 major_hash = UINT_MAX, p_cpos, cpos;
4429 	u64 blkno;
4430 	struct ocfs2_super *osb = OCFS2_SB(dir->i_sb);
4431 	struct buffer_head *dx_root_bh = NULL;
4432 	struct ocfs2_dx_root_block *dx_root;
4433 	struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
4434 	struct ocfs2_cached_dealloc_ctxt dealloc;
4435 	struct ocfs2_extent_tree et;
4436 
4437 	ocfs2_init_dealloc_ctxt(&dealloc);
4438 
4439 	if (!ocfs2_dir_indexed(dir))
4440 		return 0;
4441 
4442 	ret = ocfs2_read_dx_root(dir, di, &dx_root_bh);
4443 	if (ret) {
4444 		mlog_errno(ret);
4445 		goto out;
4446 	}
4447 	dx_root = (struct ocfs2_dx_root_block *)dx_root_bh->b_data;
4448 
4449 	if (ocfs2_dx_root_inline(dx_root))
4450 		goto remove_index;
4451 
4452 	ocfs2_init_dx_root_extent_tree(&et, INODE_CACHE(dir), dx_root_bh);
4453 
4454 	/* XXX: What if dr_clusters is too large? */
4455 	while (le32_to_cpu(dx_root->dr_clusters)) {
4456 		ret = ocfs2_dx_dir_lookup_rec(dir, &dx_root->dr_list,
4457 					      major_hash, &cpos, &blkno, &clen);
4458 		if (ret) {
4459 			mlog_errno(ret);
4460 			goto out;
4461 		}
4462 
4463 		p_cpos = ocfs2_blocks_to_clusters(dir->i_sb, blkno);
4464 
4465 		ret = ocfs2_remove_btree_range(dir, &et, cpos, p_cpos, clen, 0,
4466 					       &dealloc, 0, false);
4467 		if (ret) {
4468 			mlog_errno(ret);
4469 			goto out;
4470 		}
4471 
4472 		if (cpos == 0)
4473 			break;
4474 
4475 		major_hash = cpos - 1;
4476 	}
4477 
4478 remove_index:
4479 	ret = ocfs2_dx_dir_remove_index(dir, di_bh, dx_root_bh);
4480 	if (ret) {
4481 		mlog_errno(ret);
4482 		goto out;
4483 	}
4484 
4485 	ocfs2_remove_from_cache(INODE_CACHE(dir), dx_root_bh);
4486 out:
4487 	ocfs2_schedule_truncate_log_flush(osb, 1);
4488 	ocfs2_run_deallocs(osb, &dealloc);
4489 
4490 	brelse(dx_root_bh);
4491 	return ret;
4492 }
4493