ocfs2: Simplify ocfs2_read_block()
[safe/jmp/linux-2.6] / 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
44 #define MLOG_MASK_PREFIX ML_NAMEI
45 #include <cluster/masklog.h>
46
47 #include "ocfs2.h"
48
49 #include "alloc.h"
50 #include "dir.h"
51 #include "dlmglue.h"
52 #include "extent_map.h"
53 #include "file.h"
54 #include "inode.h"
55 #include "journal.h"
56 #include "namei.h"
57 #include "suballoc.h"
58 #include "super.h"
59 #include "uptodate.h"
60
61 #include "buffer_head_io.h"
62
63 #define NAMEI_RA_CHUNKS  2
64 #define NAMEI_RA_BLOCKS  4
65 #define NAMEI_RA_SIZE        (NAMEI_RA_CHUNKS * NAMEI_RA_BLOCKS)
66 #define NAMEI_RA_INDEX(c,b)  (((c) * NAMEI_RA_BLOCKS) + (b))
67
68 static unsigned char ocfs2_filetype_table[] = {
69         DT_UNKNOWN, DT_REG, DT_DIR, DT_CHR, DT_BLK, DT_FIFO, DT_SOCK, DT_LNK
70 };
71
72 static int ocfs2_extend_dir(struct ocfs2_super *osb,
73                             struct inode *dir,
74                             struct buffer_head *parent_fe_bh,
75                             unsigned int blocks_wanted,
76                             struct buffer_head **new_de_bh);
77 static int ocfs2_do_extend_dir(struct super_block *sb,
78                                handle_t *handle,
79                                struct inode *dir,
80                                struct buffer_head *parent_fe_bh,
81                                struct ocfs2_alloc_context *data_ac,
82                                struct ocfs2_alloc_context *meta_ac,
83                                struct buffer_head **new_bh);
84
85 /*
86  * bh passed here can be an inode block or a dir data block, depending
87  * on the inode inline data flag.
88  */
89 static int ocfs2_check_dir_entry(struct inode * dir,
90                                  struct ocfs2_dir_entry * de,
91                                  struct buffer_head * bh,
92                                  unsigned long offset)
93 {
94         const char *error_msg = NULL;
95         const int rlen = le16_to_cpu(de->rec_len);
96
97         if (rlen < OCFS2_DIR_REC_LEN(1))
98                 error_msg = "rec_len is smaller than minimal";
99         else if (rlen % 4 != 0)
100                 error_msg = "rec_len % 4 != 0";
101         else if (rlen < OCFS2_DIR_REC_LEN(de->name_len))
102                 error_msg = "rec_len is too small for name_len";
103         else if (((char *) de - bh->b_data) + rlen > dir->i_sb->s_blocksize)
104                 error_msg = "directory entry across blocks";
105
106         if (error_msg != NULL)
107                 mlog(ML_ERROR, "bad entry in directory #%llu: %s - "
108                      "offset=%lu, inode=%llu, rec_len=%d, name_len=%d\n",
109                      (unsigned long long)OCFS2_I(dir)->ip_blkno, error_msg,
110                      offset, (unsigned long long)le64_to_cpu(de->inode), rlen,
111                      de->name_len);
112         return error_msg == NULL ? 1 : 0;
113 }
114
115 static inline int ocfs2_match(int len,
116                               const char * const name,
117                               struct ocfs2_dir_entry *de)
118 {
119         if (len != de->name_len)
120                 return 0;
121         if (!de->inode)
122                 return 0;
123         return !memcmp(name, de->name, len);
124 }
125
126 /*
127  * Returns 0 if not found, -1 on failure, and 1 on success
128  */
129 static int inline ocfs2_search_dirblock(struct buffer_head *bh,
130                                         struct inode *dir,
131                                         const char *name, int namelen,
132                                         unsigned long offset,
133                                         char *first_de,
134                                         unsigned int bytes,
135                                         struct ocfs2_dir_entry **res_dir)
136 {
137         struct ocfs2_dir_entry *de;
138         char *dlimit, *de_buf;
139         int de_len;
140         int ret = 0;
141
142         mlog_entry_void();
143
144         de_buf = first_de;
145         dlimit = de_buf + bytes;
146
147         while (de_buf < dlimit) {
148                 /* this code is executed quadratically often */
149                 /* do minimal checking `by hand' */
150
151                 de = (struct ocfs2_dir_entry *) de_buf;
152
153                 if (de_buf + namelen <= dlimit &&
154                     ocfs2_match(namelen, name, de)) {
155                         /* found a match - just to be sure, do a full check */
156                         if (!ocfs2_check_dir_entry(dir, de, bh, offset)) {
157                                 ret = -1;
158                                 goto bail;
159                         }
160                         *res_dir = de;
161                         ret = 1;
162                         goto bail;
163                 }
164
165                 /* prevent looping on a bad block */
166                 de_len = le16_to_cpu(de->rec_len);
167                 if (de_len <= 0) {
168                         ret = -1;
169                         goto bail;
170                 }
171
172                 de_buf += de_len;
173                 offset += de_len;
174         }
175
176 bail:
177         mlog_exit(ret);
178         return ret;
179 }
180
181 static struct buffer_head *ocfs2_find_entry_id(const char *name,
182                                                int namelen,
183                                                struct inode *dir,
184                                                struct ocfs2_dir_entry **res_dir)
185 {
186         int ret, found;
187         struct buffer_head *di_bh = NULL;
188         struct ocfs2_dinode *di;
189         struct ocfs2_inline_data *data;
190
191         ret = ocfs2_read_block(dir, OCFS2_I(dir)->ip_blkno, &di_bh);
192         if (ret) {
193                 mlog_errno(ret);
194                 goto out;
195         }
196
197         di = (struct ocfs2_dinode *)di_bh->b_data;
198         data = &di->id2.i_data;
199
200         found = ocfs2_search_dirblock(di_bh, dir, name, namelen, 0,
201                                       data->id_data, i_size_read(dir), res_dir);
202         if (found == 1)
203                 return di_bh;
204
205         brelse(di_bh);
206 out:
207         return NULL;
208 }
209
210 static struct buffer_head *ocfs2_find_entry_el(const char *name, int namelen,
211                                                struct inode *dir,
212                                                struct ocfs2_dir_entry **res_dir)
213 {
214         struct super_block *sb;
215         struct buffer_head *bh_use[NAMEI_RA_SIZE];
216         struct buffer_head *bh, *ret = NULL;
217         unsigned long start, block, b;
218         int ra_max = 0;         /* Number of bh's in the readahead
219                                    buffer, bh_use[] */
220         int ra_ptr = 0;         /* Current index into readahead
221                                    buffer */
222         int num = 0;
223         int nblocks, i, err;
224
225         mlog_entry_void();
226
227         sb = dir->i_sb;
228
229         nblocks = i_size_read(dir) >> sb->s_blocksize_bits;
230         start = OCFS2_I(dir)->ip_dir_start_lookup;
231         if (start >= nblocks)
232                 start = 0;
233         block = start;
234
235 restart:
236         do {
237                 /*
238                  * We deal with the read-ahead logic here.
239                  */
240                 if (ra_ptr >= ra_max) {
241                         /* Refill the readahead buffer */
242                         ra_ptr = 0;
243                         b = block;
244                         for (ra_max = 0; ra_max < NAMEI_RA_SIZE; ra_max++) {
245                                 /*
246                                  * Terminate if we reach the end of the
247                                  * directory and must wrap, or if our
248                                  * search has finished at this block.
249                                  */
250                                 if (b >= nblocks || (num && block == start)) {
251                                         bh_use[ra_max] = NULL;
252                                         break;
253                                 }
254                                 num++;
255
256                                 bh = ocfs2_bread(dir, b++, &err, 1);
257                                 bh_use[ra_max] = bh;
258                         }
259                 }
260                 if ((bh = bh_use[ra_ptr++]) == NULL)
261                         goto next;
262                 wait_on_buffer(bh);
263                 if (!buffer_uptodate(bh)) {
264                         /* read error, skip block & hope for the best */
265                         ocfs2_error(dir->i_sb, "reading directory %llu, "
266                                     "offset %lu\n",
267                                     (unsigned long long)OCFS2_I(dir)->ip_blkno,
268                                     block);
269                         brelse(bh);
270                         goto next;
271                 }
272                 i = ocfs2_search_dirblock(bh, dir, name, namelen,
273                                           block << sb->s_blocksize_bits,
274                                           bh->b_data, sb->s_blocksize,
275                                           res_dir);
276                 if (i == 1) {
277                         OCFS2_I(dir)->ip_dir_start_lookup = block;
278                         ret = bh;
279                         goto cleanup_and_exit;
280                 } else {
281                         brelse(bh);
282                         if (i < 0)
283                                 goto cleanup_and_exit;
284                 }
285         next:
286                 if (++block >= nblocks)
287                         block = 0;
288         } while (block != start);
289
290         /*
291          * If the directory has grown while we were searching, then
292          * search the last part of the directory before giving up.
293          */
294         block = nblocks;
295         nblocks = i_size_read(dir) >> sb->s_blocksize_bits;
296         if (block < nblocks) {
297                 start = 0;
298                 goto restart;
299         }
300
301 cleanup_and_exit:
302         /* Clean up the read-ahead blocks */
303         for (; ra_ptr < ra_max; ra_ptr++)
304                 brelse(bh_use[ra_ptr]);
305
306         mlog_exit_ptr(ret);
307         return ret;
308 }
309
310 /*
311  * Try to find an entry of the provided name within 'dir'.
312  *
313  * If nothing was found, NULL is returned. Otherwise, a buffer_head
314  * and pointer to the dir entry are passed back.
315  *
316  * Caller can NOT assume anything about the contents of the
317  * buffer_head - it is passed back only so that it can be passed into
318  * any one of the manipulation functions (add entry, delete entry,
319  * etc). As an example, bh in the extent directory case is a data
320  * block, in the inline-data case it actually points to an inode.
321  */
322 struct buffer_head *ocfs2_find_entry(const char *name, int namelen,
323                                      struct inode *dir,
324                                      struct ocfs2_dir_entry **res_dir)
325 {
326         *res_dir = NULL;
327
328         if (OCFS2_I(dir)->ip_dyn_features & OCFS2_INLINE_DATA_FL)
329                 return ocfs2_find_entry_id(name, namelen, dir, res_dir);
330
331         return ocfs2_find_entry_el(name, namelen, dir, res_dir);
332 }
333
334 /*
335  * Update inode number and type of a previously found directory entry.
336  */
337 int ocfs2_update_entry(struct inode *dir, handle_t *handle,
338                        struct buffer_head *de_bh, struct ocfs2_dir_entry *de,
339                        struct inode *new_entry_inode)
340 {
341         int ret;
342
343         /*
344          * The same code works fine for both inline-data and extent
345          * based directories, so no need to split this up.
346          */
347
348         ret = ocfs2_journal_access(handle, dir, de_bh,
349                                    OCFS2_JOURNAL_ACCESS_WRITE);
350         if (ret) {
351                 mlog_errno(ret);
352                 goto out;
353         }
354
355         de->inode = cpu_to_le64(OCFS2_I(new_entry_inode)->ip_blkno);
356         ocfs2_set_de_type(de, new_entry_inode->i_mode);
357
358         ocfs2_journal_dirty(handle, de_bh);
359
360 out:
361         return ret;
362 }
363
364 static int __ocfs2_delete_entry(handle_t *handle, struct inode *dir,
365                                 struct ocfs2_dir_entry *de_del,
366                                 struct buffer_head *bh, char *first_de,
367                                 unsigned int bytes)
368 {
369         struct ocfs2_dir_entry *de, *pde;
370         int i, status = -ENOENT;
371
372         mlog_entry("(0x%p, 0x%p, 0x%p, 0x%p)\n", handle, dir, de_del, bh);
373
374         i = 0;
375         pde = NULL;
376         de = (struct ocfs2_dir_entry *) first_de;
377         while (i < bytes) {
378                 if (!ocfs2_check_dir_entry(dir, de, bh, i)) {
379                         status = -EIO;
380                         mlog_errno(status);
381                         goto bail;
382                 }
383                 if (de == de_del)  {
384                         status = ocfs2_journal_access(handle, dir, bh,
385                                                       OCFS2_JOURNAL_ACCESS_WRITE);
386                         if (status < 0) {
387                                 status = -EIO;
388                                 mlog_errno(status);
389                                 goto bail;
390                         }
391                         if (pde)
392                                 le16_add_cpu(&pde->rec_len,
393                                                 le16_to_cpu(de->rec_len));
394                         else
395                                 de->inode = 0;
396                         dir->i_version++;
397                         status = ocfs2_journal_dirty(handle, bh);
398                         goto bail;
399                 }
400                 i += le16_to_cpu(de->rec_len);
401                 pde = de;
402                 de = (struct ocfs2_dir_entry *)((char *)de + le16_to_cpu(de->rec_len));
403         }
404 bail:
405         mlog_exit(status);
406         return status;
407 }
408
409 static inline int ocfs2_delete_entry_id(handle_t *handle,
410                                         struct inode *dir,
411                                         struct ocfs2_dir_entry *de_del,
412                                         struct buffer_head *bh)
413 {
414         int ret;
415         struct buffer_head *di_bh = NULL;
416         struct ocfs2_dinode *di;
417         struct ocfs2_inline_data *data;
418
419         ret = ocfs2_read_block(dir, OCFS2_I(dir)->ip_blkno, &di_bh);
420         if (ret) {
421                 mlog_errno(ret);
422                 goto out;
423         }
424
425         di = (struct ocfs2_dinode *)di_bh->b_data;
426         data = &di->id2.i_data;
427
428         ret = __ocfs2_delete_entry(handle, dir, de_del, bh, data->id_data,
429                                    i_size_read(dir));
430
431         brelse(di_bh);
432 out:
433         return ret;
434 }
435
436 static inline int ocfs2_delete_entry_el(handle_t *handle,
437                                         struct inode *dir,
438                                         struct ocfs2_dir_entry *de_del,
439                                         struct buffer_head *bh)
440 {
441         return __ocfs2_delete_entry(handle, dir, de_del, bh, bh->b_data,
442                                     bh->b_size);
443 }
444
445 /*
446  * ocfs2_delete_entry deletes a directory entry by merging it with the
447  * previous entry
448  */
449 int ocfs2_delete_entry(handle_t *handle,
450                        struct inode *dir,
451                        struct ocfs2_dir_entry *de_del,
452                        struct buffer_head *bh)
453 {
454         if (OCFS2_I(dir)->ip_dyn_features & OCFS2_INLINE_DATA_FL)
455                 return ocfs2_delete_entry_id(handle, dir, de_del, bh);
456
457         return ocfs2_delete_entry_el(handle, dir, de_del, bh);
458 }
459
460 /*
461  * Check whether 'de' has enough room to hold an entry of
462  * 'new_rec_len' bytes.
463  */
464 static inline int ocfs2_dirent_would_fit(struct ocfs2_dir_entry *de,
465                                          unsigned int new_rec_len)
466 {
467         unsigned int de_really_used;
468
469         /* Check whether this is an empty record with enough space */
470         if (le64_to_cpu(de->inode) == 0 &&
471             le16_to_cpu(de->rec_len) >= new_rec_len)
472                 return 1;
473
474         /*
475          * Record might have free space at the end which we can
476          * use.
477          */
478         de_really_used = OCFS2_DIR_REC_LEN(de->name_len);
479         if (le16_to_cpu(de->rec_len) >= (de_really_used + new_rec_len))
480             return 1;
481
482         return 0;
483 }
484
485 /* we don't always have a dentry for what we want to add, so people
486  * like orphan dir can call this instead.
487  *
488  * If you pass me insert_bh, I'll skip the search of the other dir
489  * blocks and put the record in there.
490  */
491 int __ocfs2_add_entry(handle_t *handle,
492                       struct inode *dir,
493                       const char *name, int namelen,
494                       struct inode *inode, u64 blkno,
495                       struct buffer_head *parent_fe_bh,
496                       struct buffer_head *insert_bh)
497 {
498         unsigned long offset;
499         unsigned short rec_len;
500         struct ocfs2_dir_entry *de, *de1;
501         struct ocfs2_dinode *di = (struct ocfs2_dinode *)parent_fe_bh->b_data;
502         struct super_block *sb = dir->i_sb;
503         int retval, status;
504         unsigned int size = sb->s_blocksize;
505         char *data_start = insert_bh->b_data;
506
507         mlog_entry_void();
508
509         if (!namelen)
510                 return -EINVAL;
511
512         if (OCFS2_I(dir)->ip_dyn_features & OCFS2_INLINE_DATA_FL) {
513                 data_start = di->id2.i_data.id_data;
514                 size = i_size_read(dir);
515
516                 BUG_ON(insert_bh != parent_fe_bh);
517         }
518
519         rec_len = OCFS2_DIR_REC_LEN(namelen);
520         offset = 0;
521         de = (struct ocfs2_dir_entry *) data_start;
522         while (1) {
523                 BUG_ON((char *)de >= (size + data_start));
524
525                 /* These checks should've already been passed by the
526                  * prepare function, but I guess we can leave them
527                  * here anyway. */
528                 if (!ocfs2_check_dir_entry(dir, de, insert_bh, offset)) {
529                         retval = -ENOENT;
530                         goto bail;
531                 }
532                 if (ocfs2_match(namelen, name, de)) {
533                         retval = -EEXIST;
534                         goto bail;
535                 }
536
537                 if (ocfs2_dirent_would_fit(de, rec_len)) {
538                         dir->i_mtime = dir->i_ctime = CURRENT_TIME;
539                         retval = ocfs2_mark_inode_dirty(handle, dir, parent_fe_bh);
540                         if (retval < 0) {
541                                 mlog_errno(retval);
542                                 goto bail;
543                         }
544
545                         status = ocfs2_journal_access(handle, dir, insert_bh,
546                                                       OCFS2_JOURNAL_ACCESS_WRITE);
547                         /* By now the buffer is marked for journaling */
548                         offset += le16_to_cpu(de->rec_len);
549                         if (le64_to_cpu(de->inode)) {
550                                 de1 = (struct ocfs2_dir_entry *)((char *) de +
551                                         OCFS2_DIR_REC_LEN(de->name_len));
552                                 de1->rec_len =
553                                         cpu_to_le16(le16_to_cpu(de->rec_len) -
554                                         OCFS2_DIR_REC_LEN(de->name_len));
555                                 de->rec_len = cpu_to_le16(OCFS2_DIR_REC_LEN(de->name_len));
556                                 de = de1;
557                         }
558                         de->file_type = OCFS2_FT_UNKNOWN;
559                         if (blkno) {
560                                 de->inode = cpu_to_le64(blkno);
561                                 ocfs2_set_de_type(de, inode->i_mode);
562                         } else
563                                 de->inode = 0;
564                         de->name_len = namelen;
565                         memcpy(de->name, name, namelen);
566
567                         dir->i_version++;
568                         status = ocfs2_journal_dirty(handle, insert_bh);
569                         retval = 0;
570                         goto bail;
571                 }
572                 offset += le16_to_cpu(de->rec_len);
573                 de = (struct ocfs2_dir_entry *) ((char *) de + le16_to_cpu(de->rec_len));
574         }
575
576         /* when you think about it, the assert above should prevent us
577          * from ever getting here. */
578         retval = -ENOSPC;
579 bail:
580
581         mlog_exit(retval);
582         return retval;
583 }
584
585 static int ocfs2_dir_foreach_blk_id(struct inode *inode,
586                                     u64 *f_version,
587                                     loff_t *f_pos, void *priv,
588                                     filldir_t filldir, int *filldir_err)
589 {
590         int ret, i, filldir_ret;
591         unsigned long offset = *f_pos;
592         struct buffer_head *di_bh = NULL;
593         struct ocfs2_dinode *di;
594         struct ocfs2_inline_data *data;
595         struct ocfs2_dir_entry *de;
596
597         ret = ocfs2_read_block(inode, OCFS2_I(inode)->ip_blkno, &di_bh);
598         if (ret) {
599                 mlog(ML_ERROR, "Unable to read inode block for dir %llu\n",
600                      (unsigned long long)OCFS2_I(inode)->ip_blkno);
601                 goto out;
602         }
603
604         di = (struct ocfs2_dinode *)di_bh->b_data;
605         data = &di->id2.i_data;
606
607         while (*f_pos < i_size_read(inode)) {
608 revalidate:
609                 /* If the dir block has changed since the last call to
610                  * readdir(2), then we might be pointing to an invalid
611                  * dirent right now.  Scan from the start of the block
612                  * to make sure. */
613                 if (*f_version != inode->i_version) {
614                         for (i = 0; i < i_size_read(inode) && i < offset; ) {
615                                 de = (struct ocfs2_dir_entry *)
616                                         (data->id_data + i);
617                                 /* It's too expensive to do a full
618                                  * dirent test each time round this
619                                  * loop, but we do have to test at
620                                  * least that it is non-zero.  A
621                                  * failure will be detected in the
622                                  * dirent test below. */
623                                 if (le16_to_cpu(de->rec_len) <
624                                     OCFS2_DIR_REC_LEN(1))
625                                         break;
626                                 i += le16_to_cpu(de->rec_len);
627                         }
628                         *f_pos = offset = i;
629                         *f_version = inode->i_version;
630                 }
631
632                 de = (struct ocfs2_dir_entry *) (data->id_data + *f_pos);
633                 if (!ocfs2_check_dir_entry(inode, de, di_bh, *f_pos)) {
634                         /* On error, skip the f_pos to the end. */
635                         *f_pos = i_size_read(inode);
636                         goto out;
637                 }
638                 offset += le16_to_cpu(de->rec_len);
639                 if (le64_to_cpu(de->inode)) {
640                         /* We might block in the next section
641                          * if the data destination is
642                          * currently swapped out.  So, use a
643                          * version stamp to detect whether or
644                          * not the directory has been modified
645                          * during the copy operation.
646                          */
647                         u64 version = *f_version;
648                         unsigned char d_type = DT_UNKNOWN;
649
650                         if (de->file_type < OCFS2_FT_MAX)
651                                 d_type = ocfs2_filetype_table[de->file_type];
652
653                         filldir_ret = filldir(priv, de->name,
654                                               de->name_len,
655                                               *f_pos,
656                                               le64_to_cpu(de->inode),
657                                               d_type);
658                         if (filldir_ret) {
659                                 if (filldir_err)
660                                         *filldir_err = filldir_ret;
661                                 break;
662                         }
663                         if (version != *f_version)
664                                 goto revalidate;
665                 }
666                 *f_pos += le16_to_cpu(de->rec_len);
667         }
668
669 out:
670         brelse(di_bh);
671
672         return 0;
673 }
674
675 static int ocfs2_dir_foreach_blk_el(struct inode *inode,
676                                     u64 *f_version,
677                                     loff_t *f_pos, void *priv,
678                                     filldir_t filldir, int *filldir_err)
679 {
680         int error = 0;
681         unsigned long offset, blk, last_ra_blk = 0;
682         int i, stored;
683         struct buffer_head * bh, * tmp;
684         struct ocfs2_dir_entry * de;
685         int err;
686         struct super_block * sb = inode->i_sb;
687         unsigned int ra_sectors = 16;
688
689         stored = 0;
690         bh = NULL;
691
692         offset = (*f_pos) & (sb->s_blocksize - 1);
693
694         while (!error && !stored && *f_pos < i_size_read(inode)) {
695                 blk = (*f_pos) >> sb->s_blocksize_bits;
696                 bh = ocfs2_bread(inode, blk, &err, 0);
697                 if (!bh) {
698                         mlog(ML_ERROR,
699                              "directory #%llu contains a hole at offset %lld\n",
700                              (unsigned long long)OCFS2_I(inode)->ip_blkno,
701                              *f_pos);
702                         *f_pos += sb->s_blocksize - offset;
703                         continue;
704                 }
705
706                 /* The idea here is to begin with 8k read-ahead and to stay
707                  * 4k ahead of our current position.
708                  *
709                  * TODO: Use the pagecache for this. We just need to
710                  * make sure it's cluster-safe... */
711                 if (!last_ra_blk
712                     || (((last_ra_blk - blk) << 9) <= (ra_sectors / 2))) {
713                         for (i = ra_sectors >> (sb->s_blocksize_bits - 9);
714                              i > 0; i--) {
715                                 tmp = ocfs2_bread(inode, ++blk, &err, 1);
716                                 brelse(tmp);
717                         }
718                         last_ra_blk = blk;
719                         ra_sectors = 8;
720                 }
721
722 revalidate:
723                 /* If the dir block has changed since the last call to
724                  * readdir(2), then we might be pointing to an invalid
725                  * dirent right now.  Scan from the start of the block
726                  * to make sure. */
727                 if (*f_version != inode->i_version) {
728                         for (i = 0; i < sb->s_blocksize && i < offset; ) {
729                                 de = (struct ocfs2_dir_entry *) (bh->b_data + i);
730                                 /* It's too expensive to do a full
731                                  * dirent test each time round this
732                                  * loop, but we do have to test at
733                                  * least that it is non-zero.  A
734                                  * failure will be detected in the
735                                  * dirent test below. */
736                                 if (le16_to_cpu(de->rec_len) <
737                                     OCFS2_DIR_REC_LEN(1))
738                                         break;
739                                 i += le16_to_cpu(de->rec_len);
740                         }
741                         offset = i;
742                         *f_pos = ((*f_pos) & ~(sb->s_blocksize - 1))
743                                 | offset;
744                         *f_version = inode->i_version;
745                 }
746
747                 while (!error && *f_pos < i_size_read(inode)
748                        && offset < sb->s_blocksize) {
749                         de = (struct ocfs2_dir_entry *) (bh->b_data + offset);
750                         if (!ocfs2_check_dir_entry(inode, de, bh, offset)) {
751                                 /* On error, skip the f_pos to the
752                                    next block. */
753                                 *f_pos = ((*f_pos) | (sb->s_blocksize - 1)) + 1;
754                                 brelse(bh);
755                                 goto out;
756                         }
757                         offset += le16_to_cpu(de->rec_len);
758                         if (le64_to_cpu(de->inode)) {
759                                 /* We might block in the next section
760                                  * if the data destination is
761                                  * currently swapped out.  So, use a
762                                  * version stamp to detect whether or
763                                  * not the directory has been modified
764                                  * during the copy operation.
765                                  */
766                                 unsigned long version = *f_version;
767                                 unsigned char d_type = DT_UNKNOWN;
768
769                                 if (de->file_type < OCFS2_FT_MAX)
770                                         d_type = ocfs2_filetype_table[de->file_type];
771                                 error = filldir(priv, de->name,
772                                                 de->name_len,
773                                                 *f_pos,
774                                                 le64_to_cpu(de->inode),
775                                                 d_type);
776                                 if (error) {
777                                         if (filldir_err)
778                                                 *filldir_err = error;
779                                         break;
780                                 }
781                                 if (version != *f_version)
782                                         goto revalidate;
783                                 stored ++;
784                         }
785                         *f_pos += le16_to_cpu(de->rec_len);
786                 }
787                 offset = 0;
788                 brelse(bh);
789         }
790
791         stored = 0;
792 out:
793         return stored;
794 }
795
796 static int ocfs2_dir_foreach_blk(struct inode *inode, u64 *f_version,
797                                  loff_t *f_pos, void *priv, filldir_t filldir,
798                                  int *filldir_err)
799 {
800         if (OCFS2_I(inode)->ip_dyn_features & OCFS2_INLINE_DATA_FL)
801                 return ocfs2_dir_foreach_blk_id(inode, f_version, f_pos, priv,
802                                                 filldir, filldir_err);
803
804         return ocfs2_dir_foreach_blk_el(inode, f_version, f_pos, priv, filldir,
805                                         filldir_err);
806 }
807
808 /*
809  * This is intended to be called from inside other kernel functions,
810  * so we fake some arguments.
811  */
812 int ocfs2_dir_foreach(struct inode *inode, loff_t *f_pos, void *priv,
813                       filldir_t filldir)
814 {
815         int ret = 0, filldir_err = 0;
816         u64 version = inode->i_version;
817
818         while (*f_pos < i_size_read(inode)) {
819                 ret = ocfs2_dir_foreach_blk(inode, &version, f_pos, priv,
820                                             filldir, &filldir_err);
821                 if (ret || filldir_err)
822                         break;
823         }
824
825         if (ret > 0)
826                 ret = -EIO;
827
828         return 0;
829 }
830
831 /*
832  * ocfs2_readdir()
833  *
834  */
835 int ocfs2_readdir(struct file * filp, void * dirent, filldir_t filldir)
836 {
837         int error = 0;
838         struct inode *inode = filp->f_path.dentry->d_inode;
839         int lock_level = 0;
840
841         mlog_entry("dirino=%llu\n",
842                    (unsigned long long)OCFS2_I(inode)->ip_blkno);
843
844         error = ocfs2_inode_lock_atime(inode, filp->f_vfsmnt, &lock_level);
845         if (lock_level && error >= 0) {
846                 /* We release EX lock which used to update atime
847                  * and get PR lock again to reduce contention
848                  * on commonly accessed directories. */
849                 ocfs2_inode_unlock(inode, 1);
850                 lock_level = 0;
851                 error = ocfs2_inode_lock(inode, NULL, 0);
852         }
853         if (error < 0) {
854                 if (error != -ENOENT)
855                         mlog_errno(error);
856                 /* we haven't got any yet, so propagate the error. */
857                 goto bail_nolock;
858         }
859
860         error = ocfs2_dir_foreach_blk(inode, &filp->f_version, &filp->f_pos,
861                                       dirent, filldir, NULL);
862
863         ocfs2_inode_unlock(inode, lock_level);
864
865 bail_nolock:
866         mlog_exit(error);
867
868         return error;
869 }
870
871 /*
872  * NOTE: this should always be called with parent dir i_mutex taken.
873  */
874 int ocfs2_find_files_on_disk(const char *name,
875                              int namelen,
876                              u64 *blkno,
877                              struct inode *inode,
878                              struct buffer_head **dirent_bh,
879                              struct ocfs2_dir_entry **dirent)
880 {
881         int status = -ENOENT;
882
883         mlog_entry("(name=%.*s, blkno=%p, inode=%p, dirent_bh=%p, dirent=%p)\n",
884                    namelen, name, blkno, inode, dirent_bh, dirent);
885
886         *dirent_bh = ocfs2_find_entry(name, namelen, inode, dirent);
887         if (!*dirent_bh || !*dirent) {
888                 status = -ENOENT;
889                 goto leave;
890         }
891
892         *blkno = le64_to_cpu((*dirent)->inode);
893
894         status = 0;
895 leave:
896         if (status < 0) {
897                 *dirent = NULL;
898                 brelse(*dirent_bh);
899                 *dirent_bh = NULL;
900         }
901
902         mlog_exit(status);
903         return status;
904 }
905
906 /*
907  * Convenience function for callers which just want the block number
908  * mapped to a name and don't require the full dirent info, etc.
909  */
910 int ocfs2_lookup_ino_from_name(struct inode *dir, const char *name,
911                                int namelen, u64 *blkno)
912 {
913         int ret;
914         struct buffer_head *bh = NULL;
915         struct ocfs2_dir_entry *dirent = NULL;
916
917         ret = ocfs2_find_files_on_disk(name, namelen, blkno, dir, &bh, &dirent);
918         brelse(bh);
919
920         return ret;
921 }
922
923 /* Check for a name within a directory.
924  *
925  * Return 0 if the name does not exist
926  * Return -EEXIST if the directory contains the name
927  *
928  * Callers should have i_mutex + a cluster lock on dir
929  */
930 int ocfs2_check_dir_for_entry(struct inode *dir,
931                               const char *name,
932                               int namelen)
933 {
934         int ret;
935         struct buffer_head *dirent_bh = NULL;
936         struct ocfs2_dir_entry *dirent = NULL;
937
938         mlog_entry("dir %llu, name '%.*s'\n",
939                    (unsigned long long)OCFS2_I(dir)->ip_blkno, namelen, name);
940
941         ret = -EEXIST;
942         dirent_bh = ocfs2_find_entry(name, namelen, dir, &dirent);
943         if (dirent_bh)
944                 goto bail;
945
946         ret = 0;
947 bail:
948         brelse(dirent_bh);
949
950         mlog_exit(ret);
951         return ret;
952 }
953
954 struct ocfs2_empty_dir_priv {
955         unsigned seen_dot;
956         unsigned seen_dot_dot;
957         unsigned seen_other;
958 };
959 static int ocfs2_empty_dir_filldir(void *priv, const char *name, int name_len,
960                                    loff_t pos, u64 ino, unsigned type)
961 {
962         struct ocfs2_empty_dir_priv *p = priv;
963
964         /*
965          * Check the positions of "." and ".." records to be sure
966          * they're in the correct place.
967          */
968         if (name_len == 1 && !strncmp(".", name, 1) && pos == 0) {
969                 p->seen_dot = 1;
970                 return 0;
971         }
972
973         if (name_len == 2 && !strncmp("..", name, 2) &&
974             pos == OCFS2_DIR_REC_LEN(1)) {
975                 p->seen_dot_dot = 1;
976                 return 0;
977         }
978
979         p->seen_other = 1;
980         return 1;
981 }
982 /*
983  * routine to check that the specified directory is empty (for rmdir)
984  *
985  * Returns 1 if dir is empty, zero otherwise.
986  */
987 int ocfs2_empty_dir(struct inode *inode)
988 {
989         int ret;
990         loff_t start = 0;
991         struct ocfs2_empty_dir_priv priv;
992
993         memset(&priv, 0, sizeof(priv));
994
995         ret = ocfs2_dir_foreach(inode, &start, &priv, ocfs2_empty_dir_filldir);
996         if (ret)
997                 mlog_errno(ret);
998
999         if (!priv.seen_dot || !priv.seen_dot_dot) {
1000                 mlog(ML_ERROR, "bad directory (dir #%llu) - no `.' or `..'\n",
1001                      (unsigned long long)OCFS2_I(inode)->ip_blkno);
1002                 /*
1003                  * XXX: Is it really safe to allow an unlink to continue?
1004                  */
1005                 return 1;
1006         }
1007
1008         return !priv.seen_other;
1009 }
1010
1011 static void ocfs2_fill_initial_dirents(struct inode *inode,
1012                                        struct inode *parent,
1013                                        char *start, unsigned int size)
1014 {
1015         struct ocfs2_dir_entry *de = (struct ocfs2_dir_entry *)start;
1016
1017         de->inode = cpu_to_le64(OCFS2_I(inode)->ip_blkno);
1018         de->name_len = 1;
1019         de->rec_len =
1020                 cpu_to_le16(OCFS2_DIR_REC_LEN(de->name_len));
1021         strcpy(de->name, ".");
1022         ocfs2_set_de_type(de, S_IFDIR);
1023
1024         de = (struct ocfs2_dir_entry *) ((char *)de + le16_to_cpu(de->rec_len));
1025         de->inode = cpu_to_le64(OCFS2_I(parent)->ip_blkno);
1026         de->rec_len = cpu_to_le16(size - OCFS2_DIR_REC_LEN(1));
1027         de->name_len = 2;
1028         strcpy(de->name, "..");
1029         ocfs2_set_de_type(de, S_IFDIR);
1030 }
1031
1032 /*
1033  * This works together with code in ocfs2_mknod_locked() which sets
1034  * the inline-data flag and initializes the inline-data section.
1035  */
1036 static int ocfs2_fill_new_dir_id(struct ocfs2_super *osb,
1037                                  handle_t *handle,
1038                                  struct inode *parent,
1039                                  struct inode *inode,
1040                                  struct buffer_head *di_bh)
1041 {
1042         int ret;
1043         struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
1044         struct ocfs2_inline_data *data = &di->id2.i_data;
1045         unsigned int size = le16_to_cpu(data->id_count);
1046
1047         ret = ocfs2_journal_access(handle, inode, di_bh,
1048                                    OCFS2_JOURNAL_ACCESS_WRITE);
1049         if (ret) {
1050                 mlog_errno(ret);
1051                 goto out;
1052         }
1053
1054         ocfs2_fill_initial_dirents(inode, parent, data->id_data, size);
1055
1056         ocfs2_journal_dirty(handle, di_bh);
1057         if (ret) {
1058                 mlog_errno(ret);
1059                 goto out;
1060         }
1061
1062         i_size_write(inode, size);
1063         inode->i_nlink = 2;
1064         inode->i_blocks = ocfs2_inode_sector_count(inode);
1065
1066         ret = ocfs2_mark_inode_dirty(handle, inode, di_bh);
1067         if (ret < 0)
1068                 mlog_errno(ret);
1069
1070 out:
1071         return ret;
1072 }
1073
1074 static int ocfs2_fill_new_dir_el(struct ocfs2_super *osb,
1075                                  handle_t *handle,
1076                                  struct inode *parent,
1077                                  struct inode *inode,
1078                                  struct buffer_head *fe_bh,
1079                                  struct ocfs2_alloc_context *data_ac)
1080 {
1081         int status;
1082         struct buffer_head *new_bh = NULL;
1083
1084         mlog_entry_void();
1085
1086         status = ocfs2_do_extend_dir(osb->sb, handle, inode, fe_bh,
1087                                      data_ac, NULL, &new_bh);
1088         if (status < 0) {
1089                 mlog_errno(status);
1090                 goto bail;
1091         }
1092
1093         ocfs2_set_new_buffer_uptodate(inode, new_bh);
1094
1095         status = ocfs2_journal_access(handle, inode, new_bh,
1096                                       OCFS2_JOURNAL_ACCESS_CREATE);
1097         if (status < 0) {
1098                 mlog_errno(status);
1099                 goto bail;
1100         }
1101         memset(new_bh->b_data, 0, osb->sb->s_blocksize);
1102
1103         ocfs2_fill_initial_dirents(inode, parent, new_bh->b_data,
1104                                    osb->sb->s_blocksize);
1105
1106         status = ocfs2_journal_dirty(handle, new_bh);
1107         if (status < 0) {
1108                 mlog_errno(status);
1109                 goto bail;
1110         }
1111
1112         i_size_write(inode, inode->i_sb->s_blocksize);
1113         inode->i_nlink = 2;
1114         inode->i_blocks = ocfs2_inode_sector_count(inode);
1115         status = ocfs2_mark_inode_dirty(handle, inode, fe_bh);
1116         if (status < 0) {
1117                 mlog_errno(status);
1118                 goto bail;
1119         }
1120
1121         status = 0;
1122 bail:
1123         brelse(new_bh);
1124
1125         mlog_exit(status);
1126         return status;
1127 }
1128
1129 int ocfs2_fill_new_dir(struct ocfs2_super *osb,
1130                        handle_t *handle,
1131                        struct inode *parent,
1132                        struct inode *inode,
1133                        struct buffer_head *fe_bh,
1134                        struct ocfs2_alloc_context *data_ac)
1135 {
1136         BUG_ON(!ocfs2_supports_inline_data(osb) && data_ac == NULL);
1137
1138         if (OCFS2_I(inode)->ip_dyn_features & OCFS2_INLINE_DATA_FL)
1139                 return ocfs2_fill_new_dir_id(osb, handle, parent, inode, fe_bh);
1140
1141         return ocfs2_fill_new_dir_el(osb, handle, parent, inode, fe_bh,
1142                                      data_ac);
1143 }
1144
1145 static void ocfs2_expand_last_dirent(char *start, unsigned int old_size,
1146                                      unsigned int new_size)
1147 {
1148         struct ocfs2_dir_entry *de;
1149         struct ocfs2_dir_entry *prev_de;
1150         char *de_buf, *limit;
1151         unsigned int bytes = new_size - old_size;
1152
1153         limit = start + old_size;
1154         de_buf = start;
1155         de = (struct ocfs2_dir_entry *)de_buf;
1156         do {
1157                 prev_de = de;
1158                 de_buf += le16_to_cpu(de->rec_len);
1159                 de = (struct ocfs2_dir_entry *)de_buf;
1160         } while (de_buf < limit);
1161
1162         le16_add_cpu(&prev_de->rec_len, bytes);
1163 }
1164
1165 /*
1166  * We allocate enough clusters to fulfill "blocks_wanted", but set
1167  * i_size to exactly one block. Ocfs2_extend_dir() will handle the
1168  * rest automatically for us.
1169  *
1170  * *first_block_bh is a pointer to the 1st data block allocated to the
1171  *  directory.
1172  */
1173 static int ocfs2_expand_inline_dir(struct inode *dir, struct buffer_head *di_bh,
1174                                    unsigned int blocks_wanted,
1175                                    struct buffer_head **first_block_bh)
1176 {
1177         int ret, credits = OCFS2_INLINE_TO_EXTENTS_CREDITS;
1178         u32 alloc, bit_off, len;
1179         struct super_block *sb = dir->i_sb;
1180         u64 blkno, bytes = blocks_wanted << sb->s_blocksize_bits;
1181         struct ocfs2_super *osb = OCFS2_SB(dir->i_sb);
1182         struct ocfs2_inode_info *oi = OCFS2_I(dir);
1183         struct ocfs2_alloc_context *data_ac;
1184         struct buffer_head *dirdata_bh = NULL;
1185         struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
1186         handle_t *handle;
1187         struct ocfs2_extent_tree et;
1188
1189         ocfs2_init_dinode_extent_tree(&et, dir, di_bh);
1190
1191         alloc = ocfs2_clusters_for_bytes(sb, bytes);
1192
1193         /*
1194          * We should never need more than 2 clusters for this -
1195          * maximum dirent size is far less than one block. In fact,
1196          * the only time we'd need more than one cluster is if
1197          * blocksize == clustersize and the dirent won't fit in the
1198          * extra space that the expansion to a single block gives. As
1199          * of today, that only happens on 4k/4k file systems.
1200          */
1201         BUG_ON(alloc > 2);
1202
1203         ret = ocfs2_reserve_clusters(osb, alloc, &data_ac);
1204         if (ret) {
1205                 mlog_errno(ret);
1206                 goto out;
1207         }
1208
1209         down_write(&oi->ip_alloc_sem);
1210
1211         /*
1212          * Prepare for worst case allocation scenario of two separate
1213          * extents.
1214          */
1215         if (alloc == 2)
1216                 credits += OCFS2_SUBALLOC_ALLOC;
1217
1218         handle = ocfs2_start_trans(osb, credits);
1219         if (IS_ERR(handle)) {
1220                 ret = PTR_ERR(handle);
1221                 mlog_errno(ret);
1222                 goto out_sem;
1223         }
1224
1225         /*
1226          * Try to claim as many clusters as the bitmap can give though
1227          * if we only get one now, that's enough to continue. The rest
1228          * will be claimed after the conversion to extents.
1229          */
1230         ret = ocfs2_claim_clusters(osb, handle, data_ac, 1, &bit_off, &len);
1231         if (ret) {
1232                 mlog_errno(ret);
1233                 goto out_commit;
1234         }
1235
1236         /*
1237          * Operations are carefully ordered so that we set up the new
1238          * data block first. The conversion from inline data to
1239          * extents follows.
1240          */
1241         blkno = ocfs2_clusters_to_blocks(dir->i_sb, bit_off);
1242         dirdata_bh = sb_getblk(sb, blkno);
1243         if (!dirdata_bh) {
1244                 ret = -EIO;
1245                 mlog_errno(ret);
1246                 goto out_commit;
1247         }
1248
1249         ocfs2_set_new_buffer_uptodate(dir, dirdata_bh);
1250
1251         ret = ocfs2_journal_access(handle, dir, dirdata_bh,
1252                                    OCFS2_JOURNAL_ACCESS_CREATE);
1253         if (ret) {
1254                 mlog_errno(ret);
1255                 goto out_commit;
1256         }
1257
1258         memcpy(dirdata_bh->b_data, di->id2.i_data.id_data, i_size_read(dir));
1259         memset(dirdata_bh->b_data + i_size_read(dir), 0,
1260                sb->s_blocksize - i_size_read(dir));
1261         ocfs2_expand_last_dirent(dirdata_bh->b_data, i_size_read(dir),
1262                                  sb->s_blocksize);
1263
1264         ret = ocfs2_journal_dirty(handle, dirdata_bh);
1265         if (ret) {
1266                 mlog_errno(ret);
1267                 goto out_commit;
1268         }
1269
1270         /*
1271          * Set extent, i_size, etc on the directory. After this, the
1272          * inode should contain the same exact dirents as before and
1273          * be fully accessible from system calls.
1274          *
1275          * We let the later dirent insert modify c/mtime - to the user
1276          * the data hasn't changed.
1277          */
1278         ret = ocfs2_journal_access(handle, dir, di_bh,
1279                                    OCFS2_JOURNAL_ACCESS_CREATE);
1280         if (ret) {
1281                 mlog_errno(ret);
1282                 goto out_commit;
1283         }
1284
1285         spin_lock(&oi->ip_lock);
1286         oi->ip_dyn_features &= ~OCFS2_INLINE_DATA_FL;
1287         di->i_dyn_features = cpu_to_le16(oi->ip_dyn_features);
1288         spin_unlock(&oi->ip_lock);
1289
1290         ocfs2_dinode_new_extent_list(dir, di);
1291
1292         i_size_write(dir, sb->s_blocksize);
1293         dir->i_mtime = dir->i_ctime = CURRENT_TIME;
1294
1295         di->i_size = cpu_to_le64(sb->s_blocksize);
1296         di->i_ctime = di->i_mtime = cpu_to_le64(dir->i_ctime.tv_sec);
1297         di->i_ctime_nsec = di->i_mtime_nsec = cpu_to_le32(dir->i_ctime.tv_nsec);
1298
1299         /*
1300          * This should never fail as our extent list is empty and all
1301          * related blocks have been journaled already.
1302          */
1303         ret = ocfs2_insert_extent(osb, handle, dir, &et, 0, blkno, len,
1304                                   0, NULL);
1305         if (ret) {
1306                 mlog_errno(ret);
1307                 goto out_commit;
1308         }
1309
1310         /*
1311          * Set i_blocks after the extent insert for the most up to
1312          * date ip_clusters value.
1313          */
1314         dir->i_blocks = ocfs2_inode_sector_count(dir);
1315
1316         ret = ocfs2_journal_dirty(handle, di_bh);
1317         if (ret) {
1318                 mlog_errno(ret);
1319                 goto out_commit;
1320         }
1321
1322         /*
1323          * We asked for two clusters, but only got one in the 1st
1324          * pass. Claim the 2nd cluster as a separate extent.
1325          */
1326         if (alloc > len) {
1327                 ret = ocfs2_claim_clusters(osb, handle, data_ac, 1, &bit_off,
1328                                            &len);
1329                 if (ret) {
1330                         mlog_errno(ret);
1331                         goto out_commit;
1332                 }
1333                 blkno = ocfs2_clusters_to_blocks(dir->i_sb, bit_off);
1334
1335                 ret = ocfs2_insert_extent(osb, handle, dir, &et, 1,
1336                                           blkno, len, 0, NULL);
1337                 if (ret) {
1338                         mlog_errno(ret);
1339                         goto out_commit;
1340                 }
1341         }
1342
1343         *first_block_bh = dirdata_bh;
1344         dirdata_bh = NULL;
1345
1346 out_commit:
1347         ocfs2_commit_trans(osb, handle);
1348
1349 out_sem:
1350         up_write(&oi->ip_alloc_sem);
1351
1352 out:
1353         if (data_ac)
1354                 ocfs2_free_alloc_context(data_ac);
1355
1356         brelse(dirdata_bh);
1357
1358         return ret;
1359 }
1360
1361 /* returns a bh of the 1st new block in the allocation. */
1362 static int ocfs2_do_extend_dir(struct super_block *sb,
1363                                handle_t *handle,
1364                                struct inode *dir,
1365                                struct buffer_head *parent_fe_bh,
1366                                struct ocfs2_alloc_context *data_ac,
1367                                struct ocfs2_alloc_context *meta_ac,
1368                                struct buffer_head **new_bh)
1369 {
1370         int status;
1371         int extend;
1372         u64 p_blkno, v_blkno;
1373
1374         spin_lock(&OCFS2_I(dir)->ip_lock);
1375         extend = (i_size_read(dir) == ocfs2_clusters_to_bytes(sb, OCFS2_I(dir)->ip_clusters));
1376         spin_unlock(&OCFS2_I(dir)->ip_lock);
1377
1378         if (extend) {
1379                 u32 offset = OCFS2_I(dir)->ip_clusters;
1380
1381                 status = ocfs2_add_inode_data(OCFS2_SB(sb), dir, &offset,
1382                                               1, 0, parent_fe_bh, handle,
1383                                               data_ac, meta_ac, NULL);
1384                 BUG_ON(status == -EAGAIN);
1385                 if (status < 0) {
1386                         mlog_errno(status);
1387                         goto bail;
1388                 }
1389         }
1390
1391         v_blkno = ocfs2_blocks_for_bytes(sb, i_size_read(dir));
1392         status = ocfs2_extent_map_get_blocks(dir, v_blkno, &p_blkno, NULL, NULL);
1393         if (status < 0) {
1394                 mlog_errno(status);
1395                 goto bail;
1396         }
1397
1398         *new_bh = sb_getblk(sb, p_blkno);
1399         if (!*new_bh) {
1400                 status = -EIO;
1401                 mlog_errno(status);
1402                 goto bail;
1403         }
1404         status = 0;
1405 bail:
1406         mlog_exit(status);
1407         return status;
1408 }
1409
1410 /*
1411  * Assumes you already have a cluster lock on the directory.
1412  *
1413  * 'blocks_wanted' is only used if we have an inline directory which
1414  * is to be turned into an extent based one. The size of the dirent to
1415  * insert might be larger than the space gained by growing to just one
1416  * block, so we may have to grow the inode by two blocks in that case.
1417  */
1418 static int ocfs2_extend_dir(struct ocfs2_super *osb,
1419                             struct inode *dir,
1420                             struct buffer_head *parent_fe_bh,
1421                             unsigned int blocks_wanted,
1422                             struct buffer_head **new_de_bh)
1423 {
1424         int status = 0;
1425         int credits, num_free_extents, drop_alloc_sem = 0;
1426         loff_t dir_i_size;
1427         struct ocfs2_dinode *fe = (struct ocfs2_dinode *) parent_fe_bh->b_data;
1428         struct ocfs2_extent_list *el = &fe->id2.i_list;
1429         struct ocfs2_alloc_context *data_ac = NULL;
1430         struct ocfs2_alloc_context *meta_ac = NULL;
1431         handle_t *handle = NULL;
1432         struct buffer_head *new_bh = NULL;
1433         struct ocfs2_dir_entry * de;
1434         struct super_block *sb = osb->sb;
1435         struct ocfs2_extent_tree et;
1436
1437         mlog_entry_void();
1438
1439         if (OCFS2_I(dir)->ip_dyn_features & OCFS2_INLINE_DATA_FL) {
1440                 status = ocfs2_expand_inline_dir(dir, parent_fe_bh,
1441                                                  blocks_wanted, &new_bh);
1442                 if (status) {
1443                         mlog_errno(status);
1444                         goto bail;
1445                 }
1446
1447                 if (blocks_wanted == 1) {
1448                         /*
1449                          * If the new dirent will fit inside the space
1450                          * created by pushing out to one block, then
1451                          * we can complete the operation
1452                          * here. Otherwise we have to expand i_size
1453                          * and format the 2nd block below.
1454                          */
1455                         BUG_ON(new_bh == NULL);
1456                         goto bail_bh;
1457                 }
1458
1459                 /*
1460                  * Get rid of 'new_bh' - we want to format the 2nd
1461                  * data block and return that instead.
1462                  */
1463                 brelse(new_bh);
1464                 new_bh = NULL;
1465
1466                 dir_i_size = i_size_read(dir);
1467                 credits = OCFS2_SIMPLE_DIR_EXTEND_CREDITS;
1468                 goto do_extend;
1469         }
1470
1471         dir_i_size = i_size_read(dir);
1472         mlog(0, "extending dir %llu (i_size = %lld)\n",
1473              (unsigned long long)OCFS2_I(dir)->ip_blkno, dir_i_size);
1474
1475         /* dir->i_size is always block aligned. */
1476         spin_lock(&OCFS2_I(dir)->ip_lock);
1477         if (dir_i_size == ocfs2_clusters_to_bytes(sb, OCFS2_I(dir)->ip_clusters)) {
1478                 spin_unlock(&OCFS2_I(dir)->ip_lock);
1479                 ocfs2_init_dinode_extent_tree(&et, dir, parent_fe_bh);
1480                 num_free_extents = ocfs2_num_free_extents(osb, dir, &et);
1481                 if (num_free_extents < 0) {
1482                         status = num_free_extents;
1483                         mlog_errno(status);
1484                         goto bail;
1485                 }
1486
1487                 if (!num_free_extents) {
1488                         status = ocfs2_reserve_new_metadata(osb, el, &meta_ac);
1489                         if (status < 0) {
1490                                 if (status != -ENOSPC)
1491                                         mlog_errno(status);
1492                                 goto bail;
1493                         }
1494                 }
1495
1496                 status = ocfs2_reserve_clusters(osb, 1, &data_ac);
1497                 if (status < 0) {
1498                         if (status != -ENOSPC)
1499                                 mlog_errno(status);
1500                         goto bail;
1501                 }
1502
1503                 credits = ocfs2_calc_extend_credits(sb, el, 1);
1504         } else {
1505                 spin_unlock(&OCFS2_I(dir)->ip_lock);
1506                 credits = OCFS2_SIMPLE_DIR_EXTEND_CREDITS;
1507         }
1508
1509 do_extend:
1510         down_write(&OCFS2_I(dir)->ip_alloc_sem);
1511         drop_alloc_sem = 1;
1512
1513         handle = ocfs2_start_trans(osb, credits);
1514         if (IS_ERR(handle)) {
1515                 status = PTR_ERR(handle);
1516                 handle = NULL;
1517                 mlog_errno(status);
1518                 goto bail;
1519         }
1520
1521         status = ocfs2_do_extend_dir(osb->sb, handle, dir, parent_fe_bh,
1522                                      data_ac, meta_ac, &new_bh);
1523         if (status < 0) {
1524                 mlog_errno(status);
1525                 goto bail;
1526         }
1527
1528         ocfs2_set_new_buffer_uptodate(dir, new_bh);
1529
1530         status = ocfs2_journal_access(handle, dir, new_bh,
1531                                       OCFS2_JOURNAL_ACCESS_CREATE);
1532         if (status < 0) {
1533                 mlog_errno(status);
1534                 goto bail;
1535         }
1536         memset(new_bh->b_data, 0, sb->s_blocksize);
1537         de = (struct ocfs2_dir_entry *) new_bh->b_data;
1538         de->inode = 0;
1539         de->rec_len = cpu_to_le16(sb->s_blocksize);
1540         status = ocfs2_journal_dirty(handle, new_bh);
1541         if (status < 0) {
1542                 mlog_errno(status);
1543                 goto bail;
1544         }
1545
1546         dir_i_size += dir->i_sb->s_blocksize;
1547         i_size_write(dir, dir_i_size);
1548         dir->i_blocks = ocfs2_inode_sector_count(dir);
1549         status = ocfs2_mark_inode_dirty(handle, dir, parent_fe_bh);
1550         if (status < 0) {
1551                 mlog_errno(status);
1552                 goto bail;
1553         }
1554
1555 bail_bh:
1556         *new_de_bh = new_bh;
1557         get_bh(*new_de_bh);
1558 bail:
1559         if (drop_alloc_sem)
1560                 up_write(&OCFS2_I(dir)->ip_alloc_sem);
1561         if (handle)
1562                 ocfs2_commit_trans(osb, handle);
1563
1564         if (data_ac)
1565                 ocfs2_free_alloc_context(data_ac);
1566         if (meta_ac)
1567                 ocfs2_free_alloc_context(meta_ac);
1568
1569         brelse(new_bh);
1570
1571         mlog_exit(status);
1572         return status;
1573 }
1574
1575 static int ocfs2_find_dir_space_id(struct inode *dir, struct buffer_head *di_bh,
1576                                    const char *name, int namelen,
1577                                    struct buffer_head **ret_de_bh,
1578                                    unsigned int *blocks_wanted)
1579 {
1580         int ret;
1581         struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
1582         struct ocfs2_dir_entry *de, *last_de = NULL;
1583         char *de_buf, *limit;
1584         unsigned long offset = 0;
1585         unsigned int rec_len, new_rec_len;
1586
1587         de_buf = di->id2.i_data.id_data;
1588         limit = de_buf + i_size_read(dir);
1589         rec_len = OCFS2_DIR_REC_LEN(namelen);
1590
1591         while (de_buf < limit) {
1592                 de = (struct ocfs2_dir_entry *)de_buf;
1593
1594                 if (!ocfs2_check_dir_entry(dir, de, di_bh, offset)) {
1595                         ret = -ENOENT;
1596                         goto out;
1597                 }
1598                 if (ocfs2_match(namelen, name, de)) {
1599                         ret = -EEXIST;
1600                         goto out;
1601                 }
1602                 if (ocfs2_dirent_would_fit(de, rec_len)) {
1603                         /* Ok, we found a spot. Return this bh and let
1604                          * the caller actually fill it in. */
1605                         *ret_de_bh = di_bh;
1606                         get_bh(*ret_de_bh);
1607                         ret = 0;
1608                         goto out;
1609                 }
1610
1611                 last_de = de;
1612                 de_buf += le16_to_cpu(de->rec_len);
1613                 offset += le16_to_cpu(de->rec_len);
1614         }
1615
1616         /*
1617          * We're going to require expansion of the directory - figure
1618          * out how many blocks we'll need so that a place for the
1619          * dirent can be found.
1620          */
1621         *blocks_wanted = 1;
1622         new_rec_len = le16_to_cpu(last_de->rec_len) + (dir->i_sb->s_blocksize - i_size_read(dir));
1623         if (new_rec_len < (rec_len + OCFS2_DIR_REC_LEN(last_de->name_len)))
1624                 *blocks_wanted = 2;
1625
1626         ret = -ENOSPC;
1627 out:
1628         return ret;
1629 }
1630
1631 static int ocfs2_find_dir_space_el(struct inode *dir, const char *name,
1632                                    int namelen, struct buffer_head **ret_de_bh)
1633 {
1634         unsigned long offset;
1635         struct buffer_head *bh = NULL;
1636         unsigned short rec_len;
1637         struct ocfs2_dir_entry *de;
1638         struct super_block *sb = dir->i_sb;
1639         int status;
1640
1641         bh = ocfs2_bread(dir, 0, &status, 0);
1642         if (!bh) {
1643                 mlog_errno(status);
1644                 goto bail;
1645         }
1646
1647         rec_len = OCFS2_DIR_REC_LEN(namelen);
1648         offset = 0;
1649         de = (struct ocfs2_dir_entry *) bh->b_data;
1650         while (1) {
1651                 if ((char *)de >= sb->s_blocksize + bh->b_data) {
1652                         brelse(bh);
1653                         bh = NULL;
1654
1655                         if (i_size_read(dir) <= offset) {
1656                                 /*
1657                                  * Caller will have to expand this
1658                                  * directory.
1659                                  */
1660                                 status = -ENOSPC;
1661                                 goto bail;
1662                         }
1663                         bh = ocfs2_bread(dir,
1664                                          offset >> sb->s_blocksize_bits,
1665                                          &status,
1666                                          0);
1667                         if (!bh) {
1668                                 mlog_errno(status);
1669                                 goto bail;
1670                         }
1671                         /* move to next block */
1672                         de = (struct ocfs2_dir_entry *) bh->b_data;
1673                 }
1674                 if (!ocfs2_check_dir_entry(dir, de, bh, offset)) {
1675                         status = -ENOENT;
1676                         goto bail;
1677                 }
1678                 if (ocfs2_match(namelen, name, de)) {
1679                         status = -EEXIST;
1680                         goto bail;
1681                 }
1682                 if (ocfs2_dirent_would_fit(de, rec_len)) {
1683                         /* Ok, we found a spot. Return this bh and let
1684                          * the caller actually fill it in. */
1685                         *ret_de_bh = bh;
1686                         get_bh(*ret_de_bh);
1687                         status = 0;
1688                         goto bail;
1689                 }
1690                 offset += le16_to_cpu(de->rec_len);
1691                 de = (struct ocfs2_dir_entry *)((char *) de + le16_to_cpu(de->rec_len));
1692         }
1693
1694         status = 0;
1695 bail:
1696         brelse(bh);
1697
1698         mlog_exit(status);
1699         return status;
1700 }
1701
1702 int ocfs2_prepare_dir_for_insert(struct ocfs2_super *osb,
1703                                  struct inode *dir,
1704                                  struct buffer_head *parent_fe_bh,
1705                                  const char *name,
1706                                  int namelen,
1707                                  struct buffer_head **ret_de_bh)
1708 {
1709         int ret;
1710         unsigned int blocks_wanted = 1;
1711         struct buffer_head *bh = NULL;
1712
1713         mlog(0, "getting ready to insert namelen %d into dir %llu\n",
1714              namelen, (unsigned long long)OCFS2_I(dir)->ip_blkno);
1715
1716         *ret_de_bh = NULL;
1717
1718         if (!namelen) {
1719                 ret = -EINVAL;
1720                 mlog_errno(ret);
1721                 goto out;
1722         }
1723
1724         if (OCFS2_I(dir)->ip_dyn_features & OCFS2_INLINE_DATA_FL) {
1725                 ret = ocfs2_find_dir_space_id(dir, parent_fe_bh, name,
1726                                               namelen, &bh, &blocks_wanted);
1727         } else
1728                 ret = ocfs2_find_dir_space_el(dir, name, namelen, &bh);
1729
1730         if (ret && ret != -ENOSPC) {
1731                 mlog_errno(ret);
1732                 goto out;
1733         }
1734
1735         if (ret == -ENOSPC) {
1736                 /*
1737                  * We have to expand the directory to add this name.
1738                  */
1739                 BUG_ON(bh);
1740
1741                 ret = ocfs2_extend_dir(osb, dir, parent_fe_bh, blocks_wanted,
1742                                        &bh);
1743                 if (ret) {
1744                         if (ret != -ENOSPC)
1745                                 mlog_errno(ret);
1746                         goto out;
1747                 }
1748
1749                 BUG_ON(!bh);
1750         }
1751
1752         *ret_de_bh = bh;
1753         bh = NULL;
1754 out:
1755         brelse(bh);
1756         return ret;
1757 }