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