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