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