kernel: Move GPL'd kernel files to sys/gnu to have them all in one place.
[dragonfly.git] / sys / gnu / vfs / ext2fs / ext2_lookup.c
CommitLineData
984263bc
MD
1/*
2 * modified for Lites 1.1
3 *
4 * Aug 1995, Godmar Back (gback@cs.utah.edu)
5 * University of Utah, Department of Computer Science
6 *
7 * $FreeBSD: src/sys/gnu/ext2fs/ext2_lookup.c,v 1.21.2.3 2002/11/17 02:02:42 bde Exp $
8 */
9/*
10 * Copyright (c) 1989, 1993
11 * The Regents of the University of California. All rights reserved.
12 * (c) UNIX System Laboratories, Inc.
13 * All or some portions of this file are derived from material licensed
14 * to the University of California by American Telephone and Telegraph
15 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
16 * the permission of UNIX System Laboratories, Inc.
17 *
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that the following conditions
20 * are met:
21 * 1. Redistributions of source code must retain the above copyright
22 * notice, this list of conditions and the following disclaimer.
23 * 2. Redistributions in binary form must reproduce the above copyright
24 * notice, this list of conditions and the following disclaimer in the
25 * documentation and/or other materials provided with the distribution.
26 * 3. All advertising materials mentioning features or use of this software
27 * must display the following acknowledgement:
28 * This product includes software developed by the University of
29 * California, Berkeley and its contributors.
30 * 4. Neither the name of the University nor the names of its contributors
31 * may be used to endorse or promote products derived from this software
32 * without specific prior written permission.
33 *
34 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
35 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
36 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
37 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
38 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
39 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
40 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
41 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
42 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
43 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
44 * SUCH DAMAGE.
45 *
46 * @(#)ufs_lookup.c 8.6 (Berkeley) 4/1/94
47 */
48
49#include <sys/param.h>
50#include <sys/systm.h>
51#include <sys/namei.h>
52#include <sys/buf.h>
53#include <sys/mount.h>
54#include <sys/vnode.h>
55#include <sys/malloc.h>
56#include <sys/dirent.h>
57
1f1db49f
MD
58#include "quota.h"
59#include "inode.h"
60#include "dir.h"
61#include "ext2mount.h"
1f2de5d4
MD
62#include "ext2_extern.h"
63#include "ext2_fs.h"
64#include "ext2_fs_sb.h"
984263bc 65
b993bb87 66/*
984263bc
MD
67 DIRBLKSIZE in ffs is DEV_BSIZE (in most cases 512)
68 while it is the native blocksize in ext2fs - thus, a #define
69 is no longer appropriate
70*/
71#undef DIRBLKSIZ
72
73extern int dirchk;
74
75static u_char ext2_ft_to_dt[] = {
76 DT_UNKNOWN, /* EXT2_FT_UNKNOWN */
77 DT_REG, /* EXT2_FT_REG_FILE */
78 DT_DIR, /* EXT2_FT_DIR */
79 DT_CHR, /* EXT2_FT_CHRDEV */
80 DT_BLK, /* EXT2_FT_BLKDEV */
81 DT_FIFO, /* EXT2_FT_FIFO */
82 DT_SOCK, /* EXT2_FT_SOCK */
83 DT_LNK, /* EXT2_FT_SYMLINK */
84};
85#define FTTODT(ft) \
c157ff7a 86 ((ft) > NELEM(ext2_ft_to_dt) ? \
984263bc
MD
87 DT_UNKNOWN : ext2_ft_to_dt[(ft)])
88
89static u_char dt_to_ext2_ft[] = {
90 EXT2_FT_UNKNOWN, /* DT_UNKNOWN */
91 EXT2_FT_FIFO, /* DT_FIFO */
92 EXT2_FT_CHRDEV, /* DT_CHR */
93 EXT2_FT_UNKNOWN, /* unused */
94 EXT2_FT_DIR, /* DT_DIR */
95 EXT2_FT_UNKNOWN, /* unused */
96 EXT2_FT_BLKDEV, /* DT_BLK */
97 EXT2_FT_UNKNOWN, /* unused */
98 EXT2_FT_REG_FILE, /* DT_REG */
99 EXT2_FT_UNKNOWN, /* unused */
100 EXT2_FT_SYMLINK, /* DT_LNK */
101 EXT2_FT_UNKNOWN, /* unused */
102 EXT2_FT_SOCK, /* DT_SOCK */
103 EXT2_FT_UNKNOWN, /* unused */
104 EXT2_FT_UNKNOWN, /* DT_WHT */
105};
106#define DTTOFT(dt) \
c157ff7a 107 ((dt) > NELEM(dt_to_ext2_ft) ? \
984263bc
MD
108 EXT2_FT_UNKNOWN : dt_to_ext2_ft[(dt)])
109
a6ee311a 110static int ext2_dirbadentry (struct vnode *dp,
984263bc 111 struct ext2_dir_entry_2 *de,
a6ee311a 112 int entryoffsetinblock);
984263bc
MD
113
114/*
115 * Vnode op for reading directories.
116 *
117 * The routine below assumes that the on-disk format of a directory
118 * is the same as that defined by <sys/dirent.h>. If the on-disk
119 * format changes, then it will be necessary to do a conversion
120 * from the on-disk format that read returns to the format defined
121 * by <sys/dirent.h>.
122 */
123/*
124 * this is exactly what we do here - the problem is that the conversion
125 * will blow up some entries by four bytes, so it can't be done in place.
126 * This is too bad. Right now the conversion is done entry by entry, the
b993bb87 127 * converted entry is sent via uiomove.
984263bc
MD
128 *
129 * XXX allocate a buffer, convert as many entries as possible, then send
130 * the whole buffer to uiomove
0f7f7a49
CP
131 *
132 * ext2_readdir(struct vnode *a_vp, struct uio *a_uio, struct ucred *a_cred)
984263bc
MD
133 */
134int
0f7f7a49 135ext2_readdir(struct vop_readdir_args *ap)
984263bc 136{
f7aae92f 137 struct uio *uio = ap->a_uio;
984263bc 138 int count, error;
984263bc
MD
139 struct ext2_dir_entry_2 *edp, *dp;
140 int ncookies;
984263bc
MD
141 struct uio auio;
142 struct iovec aiov;
143 caddr_t dirbuf;
144 int DIRBLKSIZ = VTOI(ap->a_vp)->i_e2fs->s_blocksize;
a1435edc 145 int readcnt, retval;
984263bc
MD
146 off_t startoffset = uio->uio_offset;
147
885ecb13
MD
148 if ((error = vn_lock(ap->a_vp, LK_EXCLUSIVE | LK_RETRY)) != 0)
149 return(error);
150
984263bc
MD
151 count = uio->uio_resid;
152 /*
153 * Avoid complications for partial directory entries by adjusting
154 * the i/o to end at a block boundary. Don't give up (like ufs
155 * does) if the initial adjustment gives a negative count, since
156 * many callers don't supply a large enough buffer. The correct
157 * size is a little larger than DIRBLKSIZ to allow for expansion
158 * of directory entries, but some callers just use 512.
159 */
160 count -= (uio->uio_offset + count) & (DIRBLKSIZ -1);
161 if (count <= 0)
162 count += DIRBLKSIZ;
fb0466c9
MD
163 if (count > MAXBSIZE) /* limit to a reasonable size */
164 count = MAXBSIZE;
984263bc
MD
165
166#ifdef EXT2FS_DEBUG
b993bb87 167 kprintf("ext2_readdir: uio_offset = %lld, uio_resid = %d, count = %d\n",
984263bc
MD
168 uio->uio_offset, uio->uio_resid, count);
169#endif
170
171 auio = *uio;
172 auio.uio_iov = &aiov;
173 auio.uio_iovcnt = 1;
174 auio.uio_resid = count;
175 auio.uio_segflg = UIO_SYSSPACE;
176 aiov.iov_len = count;
177 MALLOC(dirbuf, caddr_t, count, M_TEMP, M_WAITOK);
178 aiov.iov_base = dirbuf;
179 error = VOP_READ(ap->a_vp, &auio, 0, ap->a_cred);
180 if (error == 0) {
181 readcnt = count - auio.uio_resid;
182 edp = (struct ext2_dir_entry_2 *)&dirbuf[readcnt];
183 ncookies = 0;
b993bb87 184 for (dp = (struct ext2_dir_entry_2 *)dirbuf;
984263bc
MD
185 !error && uio->uio_resid > 0 && dp < edp; ) {
186 /*-
187 * "New" ext2fs directory entries differ in 3 ways
188 * from ufs on-disk ones:
189 * - the name is not necessarily NUL-terminated.
190 * - the file type field always exists and always
191 * follows the name length field.
192 * - the file type is encoded in a different way.
193 *
194 * "Old" ext2fs directory entries need no special
195 * conversions, since they binary compatible with
196 * "new" entries having a file type of 0 (i.e.,
197 * EXT2_FT_UNKNOWN). Splitting the old name length
198 * field didn't make a mess like it did in ufs,
199 * because ext2fs uses a machine-dependent disk
200 * layout.
201 */
a1435edc 202 if (dp->rec_len <= 0) {
984263bc
MD
203 error = EIO;
204 break;
205 }
a1435edc
JS
206 retval = vop_write_dirent(&error, uio, dp->inode,
207 FTTODT(dp->file_type), dp->name_len, dp->name);
208
209 if (retval)
210 break;
211 /* advance dp */
b993bb87 212 dp = (struct ext2_dir_entry_2 *)((char *)dp + dp->rec_len);
a1435edc
JS
213 if (!error)
214 ncookies++;
984263bc
MD
215 }
216 /* we need to correct uio_offset */
217 uio->uio_offset = startoffset + (caddr_t)dp - dirbuf;
218
219 if (!error && ap->a_ncookies != NULL) {
84009d92 220 off_t *cookiep, *cookies, *ecookies;
984263bc
MD
221 off_t off;
222
223 if (uio->uio_segflg != UIO_SYSSPACE || uio->uio_iovcnt != 1)
224 panic("ext2fs_readdir: unexpected uio from NFS server");
fb0466c9 225 if (ncookies) {
84009d92
MD
226 MALLOC(cookies, off_t *,
227 ncookies * sizeof(off_t),
fb0466c9
MD
228 M_TEMP, M_WAITOK);
229 } else {
84009d92
MD
230 MALLOC(cookies, off_t *,
231 sizeof(off_t), M_TEMP, M_WAITOK);
fb0466c9 232 }
984263bc
MD
233 off = startoffset;
234 for (dp = (struct ext2_dir_entry_2 *)dirbuf,
235 cookiep = cookies, ecookies = cookies + ncookies;
236 cookiep < ecookies;
237 dp = (struct ext2_dir_entry_2 *)((caddr_t) dp + dp->rec_len)) {
238 off += dp->rec_len;
84009d92 239 *cookiep++ = off;
984263bc
MD
240 }
241 *ap->a_ncookies = ncookies;
242 *ap->a_cookies = cookies;
243 }
244 }
245 FREE(dirbuf, M_TEMP);
246 if (ap->a_eofflag)
247 *ap->a_eofflag = VTOI(ap->a_vp)->i_size <= uio->uio_offset;
885ecb13 248 vn_unlock(ap->a_vp);
984263bc
MD
249 return (error);
250}
251
252/*
253 * Convert a component of a pathname into a pointer to a locked inode.
254 * This is a very central and rather complicated routine.
255 * If the file system is not maintained in a strict tree hierarchy,
256 * this can result in a deadlock situation (see comments in code below).
257 *
258 * The cnp->cn_nameiop argument is LOOKUP, CREATE, RENAME, or DELETE depending
259 * on whether the name is to be looked up, created, renamed, or deleted.
260 * When CREATE, RENAME, or DELETE is specified, information usable in
261 * creating, renaming, or deleting a directory entry may be calculated.
262 * If flag has LOCKPARENT or'ed into it and the target of the pathname
263 * exists, lookup returns both the target and its parent directory locked.
264 * When creating or renaming and LOCKPARENT is specified, the target may
265 * not be ".". When deleting and LOCKPARENT is specified, the target may
266 * be "."., but the caller must check to ensure it does an vrele and vput
267 * instead of two vputs.
268 *
269 * Overall outline of ufs_lookup:
270 *
271 * search for name in directory, to found or notfound
272 * notfound:
273 * if creating, return locked directory, leaving info on available slots
274 * else return error
275 * found:
276 * if at end of path and deleting, return information to allow delete
277 * if at end of path and rewriting (RENAME and LOCKPARENT), lock target
278 * inode and return info to allow rewrite
279 * if not at end, add name to cache; if at end and neither creating
280 * nor deleting, add name to cache
0f7f7a49
CP
281 *
282 * ext2_lookup(struct vnode *a_dvp, struct vnode **a_vpp,
283 * struct componentname *a_cnp)
984263bc
MD
284 */
285int
e62afb5f 286ext2_lookup(struct vop_old_lookup_args *ap)
984263bc 287{
f7aae92f
RG
288 struct vnode *vdp; /* vnode for directory being searched */
289 struct inode *dp; /* inode for directory being searched */
984263bc 290 struct buf *bp; /* a buffer of directory entries */
f7aae92f 291 struct ext2_dir_entry_2 *ep; /* the current directory entry */
984263bc
MD
292 int entryoffsetinblock; /* offset of ep in bp's buffer */
293 enum {NONE, COMPACT, FOUND} slotstatus;
294 doff_t slotoffset; /* offset of area with free space */
295 int slotsize; /* size of area at slotoffset */
296 int slotfreespace; /* amount of space free in slot */
297 int slotneeded; /* size of the entry we're seeking */
298 int numdirpasses; /* strategy for directory search */
299 doff_t endsearch; /* offset to end directory search */
300 doff_t prevoff; /* prev entry dp->i_offset */
301 struct vnode *pdp; /* saved dp during symlink work */
302 struct vnode *tdp; /* returned by VFS_VGET */
303 doff_t enduseful; /* pointer past last used dir slot */
304 u_long bmask; /* block offset mask */
305 int lockparent; /* 1 => lockparent flag is set */
306 int wantparent; /* 1 => wantparent or lockparent flag */
307 int namlen, error;
308 struct vnode **vpp = ap->a_vpp;
309 struct componentname *cnp = ap->a_cnp;
310 struct ucred *cred = cnp->cn_cred;
311 int flags = cnp->cn_flags;
312 int nameiop = cnp->cn_nameiop;
984263bc
MD
313
314 int DIRBLKSIZ = VTOI(ap->a_dvp)->i_e2fs->s_blocksize;
315
316 bp = NULL;
317 slotoffset = -1;
318 *vpp = NULL;
319 vdp = ap->a_dvp;
320 dp = VTOI(vdp);
2b69e610
MD
321 lockparent = flags & CNP_LOCKPARENT;
322 wantparent = flags & (CNP_LOCKPARENT|CNP_WANTPARENT);
984263bc
MD
323
324 /*
325 * We now have a segment name to search for, and a directory to search.
326 */
327
328 /*
329 * Suppress search for slots unless creating
330 * file and at end of pathname, in which case
331 * we watch for a place to put the new file in
332 * case it doesn't already exist.
333 */
334 slotstatus = FOUND;
335 slotfreespace = slotsize = slotneeded = 0;
fad57d0e 336 if (nameiop == NAMEI_CREATE || nameiop == NAMEI_RENAME) {
984263bc 337 slotstatus = NONE;
b993bb87 338 slotneeded = EXT2_DIR_REC_LEN(cnp->cn_namelen);
984263bc
MD
339 /* was
340 slotneeded = (sizeof(struct direct) - MAXNAMLEN +
341 cnp->cn_namelen + 3) &~ 3; */
342 }
343
344 /*
345 * If there is cached information on a previous search of
346 * this directory, pick up where we last left off.
347 * We cache only lookups as these are the most common
348 * and have the greatest payoff. Caching CREATE has little
349 * benefit as it usually must search the entire directory
350 * to determine that the entry does not exist. Caching the
351 * location of the last DELETE or RENAME has not reduced
352 * profiling time and hence has been removed in the interest
353 * of simplicity.
354 */
1f1db49f 355 bmask = VFSTOEXT2(vdp->v_mount)->um_mountp->mnt_stat.f_iosize - 1;
2b69e610 356 if (nameiop != NAMEI_LOOKUP || dp->i_diroff == 0 ||
984263bc
MD
357 dp->i_diroff > dp->i_size) {
358 entryoffsetinblock = 0;
359 dp->i_offset = 0;
360 numdirpasses = 1;
361 } else {
362 dp->i_offset = dp->i_diroff;
363 if ((entryoffsetinblock = dp->i_offset & bmask) &&
1f1db49f 364 (error = EXT2_BLKATOFF(vdp, (off_t)dp->i_offset, NULL, &bp)))
984263bc
MD
365 return (error);
366 numdirpasses = 2;
984263bc
MD
367 }
368 prevoff = dp->i_offset;
369 endsearch = roundup(dp->i_size, DIRBLKSIZ);
370 enduseful = 0;
371
372searchloop:
373 while (dp->i_offset < endsearch) {
374 /*
375 * If necessary, get the next directory block.
376 */
377 if ((dp->i_offset & bmask) == 0) {
378 if (bp != NULL)
379 brelse(bp);
380 if ((error =
1f1db49f 381 EXT2_BLKATOFF(vdp, (off_t)dp->i_offset, NULL, &bp)) != 0)
984263bc
MD
382 return (error);
383 entryoffsetinblock = 0;
384 }
385 /*
386 * If still looking for a slot, and at a DIRBLKSIZE
387 * boundary, have to start looking for free space again.
388 */
389 if (slotstatus == NONE &&
390 (entryoffsetinblock & (DIRBLKSIZ - 1)) == 0) {
391 slotoffset = -1;
392 slotfreespace = 0;
393 }
394 /*
395 * Get pointer to next entry.
396 * Full validation checks are slow, so we only check
397 * enough to insure forward progress through the
398 * directory. Complete checks can be run by patching
399 * "dirchk" to be true.
400 */
401 ep = (struct ext2_dir_entry_2 *)
402 ((char *)bp->b_data + entryoffsetinblock);
403 if (ep->rec_len == 0 ||
404 (dirchk && ext2_dirbadentry(vdp, ep, entryoffsetinblock))) {
405 int i;
1f1db49f 406 ext2_dirbad(dp, dp->i_offset, "mangled entry");
984263bc
MD
407 i = DIRBLKSIZ - (entryoffsetinblock & (DIRBLKSIZ - 1));
408 dp->i_offset += i;
409 entryoffsetinblock += i;
410 continue;
411 }
412
413 /*
414 * If an appropriate sized slot has not yet been found,
415 * check to see if one is available. Also accumulate space
416 * in the current block so that we can determine if
417 * compaction is viable.
418 */
419 if (slotstatus != FOUND) {
420 int size = ep->rec_len;
421
422 if (ep->inode != 0)
423 size -= EXT2_DIR_REC_LEN(ep->name_len);
424 if (size > 0) {
425 if (size >= slotneeded) {
426 slotstatus = FOUND;
427 slotoffset = dp->i_offset;
428 slotsize = ep->rec_len;
429 } else if (slotstatus == NONE) {
430 slotfreespace += size;
431 if (slotoffset == -1)
432 slotoffset = dp->i_offset;
433 if (slotfreespace >= slotneeded) {
434 slotstatus = COMPACT;
435 slotsize = dp->i_offset +
436 ep->rec_len - slotoffset;
437 }
438 }
439 }
440 }
441
442 /*
443 * Check for a name match.
444 */
445 if (ep->inode) {
446 namlen = ep->name_len;
447 if (namlen == cnp->cn_namelen &&
448 !bcmp(cnp->cn_nameptr, ep->name,
449 (unsigned)namlen)) {
450 /*
451 * Save directory entry's inode number and
452 * reclen in ndp->ni_ufs area, and release
453 * directory buffer.
454 */
455 dp->i_ino = ep->inode;
456 dp->i_reclen = ep->rec_len;
457 goto found;
458 }
459 }
460 prevoff = dp->i_offset;
461 dp->i_offset += ep->rec_len;
462 entryoffsetinblock += ep->rec_len;
463 if (ep->inode)
464 enduseful = dp->i_offset;
465 }
466/* notfound: */
467 /*
468 * If we started in the middle of the directory and failed
469 * to find our target, we must check the beginning as well.
470 */
471 if (numdirpasses == 2) {
472 numdirpasses--;
473 dp->i_offset = 0;
474 endsearch = dp->i_diroff;
475 goto searchloop;
476 }
477 if (bp != NULL)
478 brelse(bp);
479 /*
480 * If creating, and at end of pathname and current
481 * directory has not been removed, then can consider
482 * allowing file to be created.
483 */
2b69e610 484 if ((nameiop == NAMEI_CREATE || nameiop == NAMEI_RENAME) &&
fad57d0e 485 dp->i_nlink != 0) {
984263bc
MD
486 /*
487 * Access for write is interpreted as allowing
488 * creation of files in the directory.
489 */
cb66845a 490 if ((error = VOP_EACCESS(vdp, VWRITE, cred)) != 0)
984263bc
MD
491 return (error);
492 /*
493 * Return an indication of where the new directory
494 * entry should be put. If we didn't find a slot,
495 * then set dp->i_count to 0 indicating
496 * that the new slot belongs at the end of the
497 * directory. If we found a slot, then the new entry
498 * can be put in the range from dp->i_offset to
499 * dp->i_offset + dp->i_count.
500 */
501 if (slotstatus == NONE) {
502 dp->i_offset = roundup(dp->i_size, DIRBLKSIZ);
503 dp->i_count = 0;
504 enduseful = dp->i_offset;
505 } else {
506 dp->i_offset = slotoffset;
507 dp->i_count = slotsize;
508 if (enduseful < slotoffset + slotsize)
509 enduseful = slotoffset + slotsize;
510 }
511 dp->i_endoff = roundup(enduseful, DIRBLKSIZ);
512 dp->i_flag |= IN_CHANGE | IN_UPDATE;
513 /*
514 * We return with the directory locked, so that
515 * the parameters we set up above will still be
516 * valid if we actually decide to do a direnter().
517 * We return ni_vp == NULL to indicate that the entry
518 * does not currently exist; we leave a pointer to
519 * the (locked) directory inode in ndp->ni_dvp.
520 * The pathname buffer is saved so that the name
521 * can be obtained later.
522 *
523 * NB - if the directory is unlocked, then this
524 * information cannot be used.
525 */
984263bc 526 if (!lockparent)
a11aaa81 527 vn_unlock(vdp);
984263bc
MD
528 return (EJUSTRETURN);
529 }
984263bc
MD
530 return (ENOENT);
531
532found:
984263bc
MD
533 /*
534 * Check that directory length properly reflects presence
535 * of this entry.
536 */
537 if (entryoffsetinblock + EXT2_DIR_REC_LEN(ep->name_len)
538 > dp->i_size) {
1f1db49f 539 ext2_dirbad(dp, dp->i_offset, "i_size too small");
984263bc
MD
540 dp->i_size = entryoffsetinblock+EXT2_DIR_REC_LEN(ep->name_len);
541 dp->i_flag |= IN_CHANGE | IN_UPDATE;
542 }
543 brelse(bp);
544
545 /*
546 * Found component in pathname.
547 * If the final component of path name, save information
548 * in the cache as to where the entry was found.
549 */
fad57d0e 550 if (nameiop == NAMEI_LOOKUP)
984263bc
MD
551 dp->i_diroff = dp->i_offset &~ (DIRBLKSIZ - 1);
552
553 /*
554 * If deleting, and at end of pathname, return
555 * parameters which can be used to remove file.
556 * If the wantparent flag isn't set, we return only
557 * the directory (in ndp->ni_dvp), otherwise we go
558 * on and lock the inode, being careful with ".".
559 */
fad57d0e 560 if (nameiop == NAMEI_DELETE) {
984263bc
MD
561 /*
562 * Write access to directory required to delete files.
563 */
cb66845a 564 if ((error = VOP_EACCESS(vdp, VWRITE, cred)) != 0)
984263bc
MD
565 return (error);
566 /*
567 * Return pointer to current entry in dp->i_offset,
568 * and distance past previous entry (if there
569 * is a previous entry in this block) in dp->i_count.
570 * Save directory inode pointer in ndp->ni_dvp for dirremove().
571 */
572 if ((dp->i_offset & (DIRBLKSIZ - 1)) == 0)
573 dp->i_count = 0;
574 else
575 dp->i_count = dp->i_offset - prevoff;
576 if (dp->i_number == dp->i_ino) {
597aea93 577 vref(vdp);
984263bc
MD
578 *vpp = vdp;
579 return (0);
580 }
b9b0a6d0 581 if ((error = VFS_VGET(vdp->v_mount, NULL, dp->i_ino, &tdp)) != 0)
984263bc
MD
582 return (error);
583 /*
584 * If directory is "sticky", then user must own
585 * the directory, or the file in it, else she
586 * may not delete it (unless she's root). This
587 * implements append-only directories.
588 */
589 if ((dp->i_mode & ISVTX) &&
590 cred->cr_uid != 0 &&
591 cred->cr_uid != dp->i_uid &&
592 VTOI(tdp)->i_uid != cred->cr_uid) {
593 vput(tdp);
594 return (EPERM);
595 }
596 *vpp = tdp;
597 if (!lockparent)
a11aaa81 598 vn_unlock(vdp);
984263bc
MD
599 return (0);
600 }
601
602 /*
603 * If rewriting (RENAME), return the inode and the
604 * information required to rewrite the present directory
605 * Must get inode of directory entry to verify it's a
606 * regular file, or empty directory.
607 */
fad57d0e 608 if (nameiop == NAMEI_RENAME && wantparent) {
cb66845a 609 if ((error = VOP_EACCESS(vdp, VWRITE, cred)) != 0)
984263bc
MD
610 return (error);
611 /*
612 * Careful about locking second inode.
613 * This can only occur if the target is ".".
614 */
615 if (dp->i_number == dp->i_ino)
616 return (EISDIR);
b9b0a6d0 617 if ((error = VFS_VGET(vdp->v_mount, NULL, dp->i_ino, &tdp)) != 0)
984263bc
MD
618 return (error);
619 *vpp = tdp;
984263bc 620 if (!lockparent)
a11aaa81 621 vn_unlock(vdp);
984263bc
MD
622 return (0);
623 }
624
625 /*
626 * Step through the translation in the name. We do not `vput' the
627 * directory because we may need it again if a symbolic link
628 * is relative to the current directory. Instead we save it
629 * unlocked as "pdp". We must get the target inode before unlocking
630 * the directory to insure that the inode will not be removed
631 * before we get it. We prevent deadlock by always fetching
632 * inodes from the root, moving down the directory tree. Thus
633 * when following backward pointers ".." we must unlock the
634 * parent directory before getting the requested directory.
635 * There is a potential race condition here if both the current
636 * and parent directories are removed before the VFS_VGET for the
637 * inode associated with ".." returns. We hope that this occurs
638 * infrequently since we cannot avoid this race condition without
639 * implementing a sophisticated deadlock detection algorithm.
640 * Note also that this simple deadlock detection scheme will not
641 * work if the file system has any hard links other than ".."
642 * that point backwards in the directory structure.
643 */
644 pdp = vdp;
2b69e610 645 if (flags & CNP_ISDOTDOT) {
a11aaa81 646 vn_unlock(pdp); /* race to get the inode */
b9b0a6d0 647 if ((error = VFS_VGET(vdp->v_mount, NULL, dp->i_ino, &tdp)) != 0) {
ca466bae 648 vn_lock(pdp, LK_EXCLUSIVE | LK_RETRY);
984263bc
MD
649 return (error);
650 }
ca466bae 651 if (lockparent && (error = vn_lock(pdp, LK_EXCLUSIVE))) {
984263bc
MD
652 vput(tdp);
653 return (error);
654 }
655 *vpp = tdp;
656 } else if (dp->i_number == dp->i_ino) {
597aea93 657 vref(vdp); /* we want ourself, ie "." */
984263bc
MD
658 *vpp = vdp;
659 } else {
b9b0a6d0 660 if ((error = VFS_VGET(vdp->v_mount, NULL, dp->i_ino, &tdp)) != 0)
984263bc 661 return (error);
fad57d0e 662 if (!lockparent)
a11aaa81 663 vn_unlock(pdp);
984263bc
MD
664 *vpp = tdp;
665 }
984263bc
MD
666 return (0);
667}
668
1f1db49f
MD
669void
670ext2_dirbad(struct inode *ip, doff_t offset, char *how)
671{
672 struct mount *mp;
673
674 mp = ITOV(ip)->v_mount;
086c1d7e 675 kprintf("%s: bad dir ino %lu at offset %ld: %s\n",
1f1db49f
MD
676 mp->mnt_stat.f_mntfromname, (u_long)ip->i_number,
677 (long)offset, how);
678 if ((mp->mnt_flag & MNT_RDONLY) == 0)
679 panic("ufs_dirbad: bad dir");
680}
681
984263bc
MD
682/*
683 * Do consistency checking on a directory entry:
684 * record length must be multiple of 4
685 * entry must fit in rest of its DIRBLKSIZ block
686 * record must be large enough to contain entry
687 * name is not longer than MAXNAMLEN
688 * name must be as long as advertised, and null terminated
689 */
690/*
691 * changed so that it confirms to ext2_check_dir_entry
692 */
693static int
0f7f7a49
CP
694ext2_dirbadentry(struct vnode *dp, struct ext2_dir_entry_2 *de,
695 int entryoffsetinblock)
984263bc
MD
696{
697 int DIRBLKSIZ = VTOI(dp)->i_e2fs->s_blocksize;
698
699 char * error_msg = NULL;
700
701 if (de->rec_len < EXT2_DIR_REC_LEN(1))
702 error_msg = "rec_len is smaller than minimal";
703 else if (de->rec_len % 4 != 0)
704 error_msg = "rec_len % 4 != 0";
705 else if (de->rec_len < EXT2_DIR_REC_LEN(de->name_len))
706 error_msg = "reclen is too small for name_len";
707 else if (entryoffsetinblock + de->rec_len > DIRBLKSIZ)
708 error_msg = "directory entry across blocks";
709 /* else LATER
710 if (de->inode > dir->i_sb->u.ext2_sb.s_es->s_inodes_count)
711 error_msg = "inode out of bounds";
712 */
713
714 if (error_msg != NULL) {
086c1d7e
SW
715 kprintf("bad directory entry: %s\n", error_msg);
716 kprintf("offset=%d, inode=%lu, rec_len=%u, name_len=%u\n",
984263bc
MD
717 entryoffsetinblock, (unsigned long)de->inode,
718 de->rec_len, de->name_len);
719 }
720 return error_msg == NULL ? 0 : 1;
721}
722
723/*
724 * Write a directory entry after a call to namei, using the parameters
fad57d0e 725 * that it left in the directory inode. The argument ip is the inode which
b993bb87 726 * the new directory entry will refer to. Dvp is a pointer to the directory
fad57d0e 727 * to be written, which was left locked by namei. Remaining parameters
984263bc
MD
728 * (dp->i_offset, dp->i_count) indicate how the space for the new
729 * entry is to be obtained.
730 */
731int
0f7f7a49 732ext2_direnter(struct inode *ip, struct vnode *dvp, struct componentname *cnp)
984263bc 733{
f7aae92f
RG
734 struct ext2_dir_entry_2 *ep, *nep;
735 struct inode *dp;
984263bc
MD
736 struct buf *bp;
737 struct ext2_dir_entry_2 newdir;
738 struct iovec aiov;
739 struct uio auio;
740 u_int dsize;
741 int error, loc, newentrysize, spacefree;
742 char *dirbuf;
743 int DIRBLKSIZ = ip->i_e2fs->s_blocksize;
744
745
984263bc
MD
746 dp = VTOI(dvp);
747 newdir.inode = ip->i_number;
748 newdir.name_len = cnp->cn_namelen;
749 if (EXT2_HAS_INCOMPAT_FEATURE(ip->i_e2fs->s_es,
750 EXT2_FEATURE_INCOMPAT_FILETYPE))
751 newdir.file_type = DTTOFT(IFTODT(ip->i_mode));
752 else
753 newdir.file_type = EXT2_FT_UNKNOWN;
754 bcopy(cnp->cn_nameptr, newdir.name, (unsigned)cnp->cn_namelen + 1);
755 newentrysize = EXT2_DIR_REC_LEN(newdir.name_len);
756 if (dp->i_count == 0) {
757 /*
758 * If dp->i_count is 0, then namei could find no
759 * space in the directory. Here, dp->i_offset will
760 * be on a directory block boundary and we will write the
761 * new entry into a fresh block.
762 */
763 if (dp->i_offset & (DIRBLKSIZ - 1))
764 panic("ext2_direnter: newblk");
765 auio.uio_offset = dp->i_offset;
766 newdir.rec_len = DIRBLKSIZ;
767 auio.uio_resid = newentrysize;
768 aiov.iov_len = newentrysize;
769 aiov.iov_base = (caddr_t)&newdir;
770 auio.uio_iov = &aiov;
771 auio.uio_iovcnt = 1;
772 auio.uio_rw = UIO_WRITE;
773 auio.uio_segflg = UIO_SYSSPACE;
7b95be2a 774 auio.uio_td = NULL;
984263bc
MD
775 error = VOP_WRITE(dvp, &auio, IO_SYNC, cnp->cn_cred);
776 if (DIRBLKSIZ >
1f1db49f 777 VFSTOEXT2(dvp->v_mount)->um_mountp->mnt_stat.f_bsize)
984263bc
MD
778 /* XXX should grow with balloc() */
779 panic("ext2_direnter: frag size");
780 else if (!error) {
781 dp->i_size = roundup(dp->i_size, DIRBLKSIZ);
782 dp->i_flag |= IN_CHANGE;
783 }
784 return (error);
785 }
786
787 /*
788 * If dp->i_count is non-zero, then namei found space
789 * for the new entry in the range dp->i_offset to
790 * dp->i_offset + dp->i_count in the directory.
791 * To use this space, we may have to compact the entries located
792 * there, by copying them together towards the beginning of the
793 * block, leaving the free space in one usable chunk at the end.
794 */
795
796 /*
797 * Increase size of directory if entry eats into new space.
798 * This should never push the size past a new multiple of
799 * DIRBLKSIZE.
800 *
801 * N.B. - THIS IS AN ARTIFACT OF 4.2 AND SHOULD NEVER HAPPEN.
802 */
803 if (dp->i_offset + dp->i_count > dp->i_size)
804 dp->i_size = dp->i_offset + dp->i_count;
805 /*
806 * Get the block containing the space for the new directory entry.
807 */
1f1db49f 808 if ((error = EXT2_BLKATOFF(dvp, (off_t)dp->i_offset, &dirbuf, &bp)) != 0)
984263bc
MD
809 return (error);
810 /*
811 * Find space for the new entry. In the simple case, the entry at
812 * offset base will have the space. If it does not, then namei
813 * arranged that compacting the region dp->i_offset to
814 * dp->i_offset + dp->i_count would yield the
815 * space.
816 */
817 ep = (struct ext2_dir_entry_2 *)dirbuf;
818 dsize = EXT2_DIR_REC_LEN(ep->name_len);
819 spacefree = ep->rec_len - dsize;
820 for (loc = ep->rec_len; loc < dp->i_count; ) {
821 nep = (struct ext2_dir_entry_2 *)(dirbuf + loc);
822 if (ep->inode) {
823 /* trim the existing slot */
824 ep->rec_len = dsize;
825 ep = (struct ext2_dir_entry_2 *)((char *)ep + dsize);
826 } else {
827 /* overwrite; nothing there; header is ours */
828 spacefree += dsize;
829 }
830 dsize = EXT2_DIR_REC_LEN(nep->name_len);
831 spacefree += nep->rec_len - dsize;
832 loc += nep->rec_len;
833 bcopy((caddr_t)nep, (caddr_t)ep, dsize);
834 }
835 /*
836 * Update the pointer fields in the previous entry (if any),
837 * copy in the new entry, and write out the block.
838 */
839 if (ep->inode == 0) {
840 if (spacefree + dsize < newentrysize)
841 panic("ext2_direnter: compact1");
842 newdir.rec_len = spacefree + dsize;
843 } else {
844 if (spacefree < newentrysize)
845 panic("ext2_direnter: compact2");
846 newdir.rec_len = spacefree;
847 ep->rec_len = dsize;
848 ep = (struct ext2_dir_entry_2 *)((char *)ep + dsize);
849 }
850 bcopy((caddr_t)&newdir, (caddr_t)ep, (u_int)newentrysize);
62cfda27 851 error = bwrite(bp);
984263bc
MD
852 dp->i_flag |= IN_CHANGE | IN_UPDATE;
853 if (!error && dp->i_endoff && dp->i_endoff < dp->i_size)
1f1db49f 854 error = EXT2_TRUNCATE(dvp, (off_t)dp->i_endoff, IO_SYNC,
87de5057 855 cnp->cn_cred);
984263bc
MD
856 return (error);
857}
858
859/*
860 * Remove a directory entry after a call to namei, using
fad57d0e 861 * the parameters which it left in the directory inode. The entry
984263bc
MD
862 * dp->i_offset contains the offset into the directory of the
863 * entry to be eliminated. The dp->i_count field contains the
864 * size of the previous record in the directory. If this
865 * is 0, the first entry is being deleted, so we need only
866 * zero the inode number to mark the entry as free. If the
867 * entry is not the first in the directory, we must reclaim
868 * the space of the now empty record by adding the record size
869 * to the size of the previous entry.
870 */
871int
0f7f7a49 872ext2_dirremove(struct vnode *dvp, struct componentname *cnp)
984263bc 873{
f7aae92f 874 struct inode *dp;
984263bc
MD
875 struct ext2_dir_entry_2 *ep;
876 struct buf *bp;
877 int error;
b993bb87 878
984263bc
MD
879 dp = VTOI(dvp);
880 if (dp->i_count == 0) {
881 /*
882 * First entry in block: set d_ino to zero.
883 */
884 if ((error =
1f1db49f 885 EXT2_BLKATOFF(dvp, (off_t)dp->i_offset, (char **)&ep, &bp)) != 0)
984263bc
MD
886 return (error);
887 ep->inode = 0;
62cfda27 888 error = bwrite(bp);
984263bc
MD
889 dp->i_flag |= IN_CHANGE | IN_UPDATE;
890 return (error);
891 }
892 /*
893 * Collapse new free space into previous entry.
894 */
1f1db49f 895 if ((error = EXT2_BLKATOFF(dvp, (off_t)(dp->i_offset - dp->i_count),
984263bc
MD
896 (char **)&ep, &bp)) != 0)
897 return (error);
898 ep->rec_len += dp->i_reclen;
62cfda27 899 error = bwrite(bp);
984263bc
MD
900 dp->i_flag |= IN_CHANGE | IN_UPDATE;
901 return (error);
902}
903
904/*
905 * Rewrite an existing directory entry to point at the inode
906 * supplied. The parameters describing the directory entry are
907 * set up by a call to namei.
908 */
909int
0f7f7a49 910ext2_dirrewrite(struct inode *dp, struct inode *ip, struct componentname *cnp)
984263bc
MD
911{
912 struct buf *bp;
913 struct ext2_dir_entry_2 *ep;
914 struct vnode *vdp = ITOV(dp);
915 int error;
916
1f1db49f 917 if ((error = EXT2_BLKATOFF(vdp, (off_t)dp->i_offset, (char **)&ep, &bp)) != 0)
984263bc
MD
918 return (error);
919 ep->inode = ip->i_number;
920 if (EXT2_HAS_INCOMPAT_FEATURE(ip->i_e2fs->s_es,
921 EXT2_FEATURE_INCOMPAT_FILETYPE))
922 ep->file_type = DTTOFT(IFTODT(ip->i_mode));
923 else
924 ep->file_type = EXT2_FT_UNKNOWN;
62cfda27 925 error = bwrite(bp);
984263bc
MD
926 dp->i_flag |= IN_CHANGE | IN_UPDATE;
927 return (error);
928}
929
930/*
931 * Check if a directory is empty or not.
932 * Inode supplied must be locked.
933 *
934 * Using a struct dirtemplate here is not precisely
935 * what we want, but better than using a struct direct.
936 *
937 * NB: does not handle corrupted directories.
938 */
939int
0f7f7a49 940ext2_dirempty(struct inode *ip, ino_t parentino, struct ucred *cred)
984263bc 941{
f7aae92f 942 off_t off;
984263bc 943 struct dirtemplate dbuf;
f7aae92f 944 struct ext2_dir_entry_2 *dp = (struct ext2_dir_entry_2 *)&dbuf;
984263bc 945 int error, count, namlen;
b993bb87 946
984263bc
MD
947#define MINDIRSIZ (sizeof (struct dirtemplate) / 2)
948
949 for (off = 0; off < ip->i_size; off += dp->rec_len) {
950 error = vn_rdwr(UIO_READ, ITOV(ip), (caddr_t)dp, MINDIRSIZ, off,
87de5057 951 UIO_SYSSPACE, IO_NODELOCKED, cred, &count);
984263bc
MD
952 /*
953 * Since we read MINDIRSIZ, residual must
954 * be 0 unless we're at end of file.
955 */
956 if (error || count != 0)
957 return (0);
958 /* avoid infinite loops */
959 if (dp->rec_len == 0)
960 return (0);
961 /* skip empty entries */
962 if (dp->inode == 0)
963 continue;
964 /* accept only "." and ".." */
965 namlen = dp->name_len;
966 if (namlen > 2)
967 return (0);
968 if (dp->name[0] != '.')
969 return (0);
970 /*
971 * At this point namlen must be 1 or 2.
972 * 1 implies ".", 2 implies ".." if second
973 * char is also "."
974 */
975 if (namlen == 1)
976 continue;
977 if (dp->name[1] == '.' && dp->inode == parentino)
978 continue;
979 return (0);
980 }
981 return (1);
982}
983
984/*
985 * Check if source directory is in the path of the target directory.
986 * Target is supplied locked, source is unlocked.
987 * The target is always vput before returning.
988 */
989int
0f7f7a49 990ext2_checkpath(struct inode *source, struct inode *target, struct ucred *cred)
984263bc
MD
991{
992 struct vnode *vp;
993 int error, rootino, namlen;
994 struct dirtemplate dirbuf;
995
996 vp = ITOV(target);
997 if (target->i_number == source->i_number) {
998 error = EEXIST;
999 goto out;
1000 }
1001 rootino = ROOTINO;
1002 error = 0;
1003 if (target->i_number == rootino)
1004 goto out;
1005
1006 for (;;) {
1007 if (vp->v_type != VDIR) {
1008 error = ENOTDIR;
1009 break;
1010 }
1011 error = vn_rdwr(UIO_READ, vp, (caddr_t)&dirbuf,
87de5057 1012 sizeof (struct dirtemplate), (off_t)0,
60233e58 1013 UIO_SYSSPACE, IO_NODELOCKED, cred, NULL);
984263bc
MD
1014 if (error != 0)
1015 break;
1016 namlen = dirbuf.dotdot_type; /* like ufs little-endian */
1017 if (namlen != 2 ||
1018 dirbuf.dotdot_name[0] != '.' ||
1019 dirbuf.dotdot_name[1] != '.') {
1020 error = ENOTDIR;
1021 break;
1022 }
1023 if (dirbuf.dotdot_ino == source->i_number) {
1024 error = EINVAL;
1025 break;
1026 }
1027 if (dirbuf.dotdot_ino == rootino)
1028 break;
1029 vput(vp);
b9b0a6d0 1030 if ((error = VFS_VGET(vp->v_mount, NULL, dirbuf.dotdot_ino, &vp)) != 0) {
984263bc
MD
1031 vp = NULL;
1032 break;
1033 }
1034 }
1035
1036out:
1037 if (error == ENOTDIR)
086c1d7e 1038 kprintf("checkpath: .. not a directory\n");
984263bc
MD
1039 if (vp != NULL)
1040 vput(vp);
1041 return (error);
1042}