ext2fs_lookup.c revision 1.82 1 /* $NetBSD: ext2fs_lookup.c,v 1.82 2016/08/09 20:18:08 christos Exp $ */
2
3 /*
4 * Modified for NetBSD 1.2E
5 * May 1997, Manuel Bouyer
6 * Laboratoire d'informatique de Paris VI
7 */
8 /*
9 * modified for Lites 1.1
10 *
11 * Aug 1995, Godmar Back (gback (at) cs.utah.edu)
12 * University of Utah, Department of Computer Science
13 */
14 /*
15 * Copyright (c) 1989, 1993
16 * The Regents of the University of California. All rights reserved.
17 * (c) UNIX System Laboratories, Inc.
18 * All or some portions of this file are derived from material licensed
19 * to the University of California by American Telephone and Telegraph
20 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
21 * the permission of UNIX System Laboratories, Inc.
22 *
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
25 * are met:
26 * 1. Redistributions of source code must retain the above copyright
27 * notice, this list of conditions and the following disclaimer.
28 * 2. Redistributions in binary form must reproduce the above copyright
29 * notice, this list of conditions and the following disclaimer in the
30 * documentation and/or other materials provided with the distribution.
31 * 3. Neither the name of the University nor the names of its contributors
32 * may be used to endorse or promote products derived from this software
33 * without specific prior written permission.
34 *
35 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
36 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
37 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
38 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
39 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
40 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
41 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
42 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
43 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
44 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
45 * SUCH DAMAGE.
46 *
47 * @(#)ufs_lookup.c 8.6 (Berkeley) 4/1/94
48 */
49
50 #include <sys/cdefs.h>
51 __KERNEL_RCSID(0, "$NetBSD: ext2fs_lookup.c,v 1.82 2016/08/09 20:18:08 christos Exp $");
52
53 #include <sys/param.h>
54 #include <sys/systm.h>
55 #include <sys/namei.h>
56 #include <sys/buf.h>
57 #include <sys/file.h>
58 #include <sys/mount.h>
59 #include <sys/vnode.h>
60 #include <sys/kmem.h>
61 #include <sys/malloc.h>
62 #include <sys/dirent.h>
63 #include <sys/kauth.h>
64 #include <sys/proc.h>
65
66 #include <ufs/ufs/inode.h>
67 #include <ufs/ufs/ufsmount.h>
68 #include <ufs/ufs/ufs_extern.h>
69
70 #include <ufs/ext2fs/ext2fs_extern.h>
71 #include <ufs/ext2fs/ext2fs_dir.h>
72 #include <ufs/ext2fs/ext2fs.h>
73 #include <ufs/ext2fs/ext2fs_htree.h>
74
75 #include <miscfs/genfs/genfs.h>
76
77 extern int dirchk;
78
79 static void ext2fs_dirconv2ffs(struct ext2fs_direct *e2dir,
80 struct dirent *ffsdir);
81 static int ext2fs_dirbadentry(struct vnode *dp,
82 struct ext2fs_direct *de,
83 int entryoffsetinblock);
84
85 /*
86 * the problem that is tackled below is the fact that FFS
87 * includes the terminating zero on disk while EXT2FS doesn't
88 * this implies that we need to introduce some padding.
89 * For instance, a filename "sbin" has normally a reclen 12
90 * in EXT2, but 16 in FFS.
91 * This reminds me of that Pepsi commercial: 'Kid saved a lousy nine cents...'
92 * If it wasn't for that, the complete ufs code for directories would
93 * have worked w/o changes (except for the difference in DIRBLKSIZ)
94 */
95 static void
96 ext2fs_dirconv2ffs(struct ext2fs_direct *e2dir, struct dirent *ffsdir)
97 {
98 memset(ffsdir, 0, sizeof(struct dirent));
99 ffsdir->d_fileno = fs2h32(e2dir->e2d_ino);
100 ffsdir->d_namlen = e2dir->e2d_namlen;
101
102 ffsdir->d_type = ext2dt2dt(e2dir->e2d_type);
103
104 #ifdef DIAGNOSTIC
105 #if MAXNAMLEN < E2FS_MAXNAMLEN
106 /*
107 * we should handle this more gracefully !
108 */
109 if (e2dir->e2d_namlen > MAXNAMLEN)
110 panic("ext2fs: e2dir->e2d_namlen");
111 #endif
112 #endif
113 strncpy(ffsdir->d_name, e2dir->e2d_name, ffsdir->d_namlen);
114
115 /* Godmar thinks: since e2dir->e2d_reclen can be big and means
116 nothing anyway, we compute our own reclen according to what
117 we think is right
118 */
119 ffsdir->d_reclen = _DIRENT_SIZE(ffsdir);
120 }
121
122 static int
123 ext2fs_is_dot_entry(struct componentname *cnp)
124 {
125 return cnp->cn_namelen <= 2 && cnp->cn_nameptr[0] == '.' &&
126 (cnp->cn_nameptr[1] == '.' || cnp->cn_nameptr[1] == '\0');
127 }
128
129 /*
130 * Vnode op for reading directories.
131 *
132 * Convert the on-disk entries to <sys/dirent.h> entries.
133 * the problem is that the conversion will blow up some entries by four bytes,
134 * so it can't be done in place. This is too bad. Right now the conversion is
135 * done entry by entry, the converted entry is sent via uiomove.
136 *
137 * XXX allocate a buffer, convert as many entries as possible, then send
138 * the whole buffer to uiomove
139 */
140 int
141 ext2fs_readdir(void *v)
142 {
143 struct vop_readdir_args /* {
144 struct vnode *a_vp;
145 struct uio *a_uio;
146 kauth_cred_t a_cred;
147 int **a_eofflag;
148 off_t **a_cookies;
149 int ncookies;
150 } */ *ap = v;
151 struct uio *uio = ap->a_uio;
152 int error;
153 size_t e2fs_count, readcnt;
154 struct vnode *vp = ap->a_vp;
155 struct m_ext2fs *fs = VTOI(vp)->i_e2fs;
156
157 struct ext2fs_direct *dp;
158 struct dirent *dstd;
159 struct uio auio;
160 struct iovec aiov;
161 void *dirbuf;
162 off_t off = uio->uio_offset;
163 off_t *cookies = NULL;
164 int nc = 0, ncookies = 0;
165 int e2d_reclen;
166
167 if (vp->v_type != VDIR)
168 return (ENOTDIR);
169
170 e2fs_count = uio->uio_resid;
171 /* Make sure we don't return partial entries. */
172 e2fs_count -= (uio->uio_offset + e2fs_count) & (fs->e2fs_bsize -1);
173 if (e2fs_count <= 0)
174 return (EINVAL);
175
176 auio = *uio;
177 auio.uio_iov = &aiov;
178 auio.uio_iovcnt = 1;
179 aiov.iov_len = e2fs_count;
180 auio.uio_resid = e2fs_count;
181 UIO_SETUP_SYSSPACE(&auio);
182 dirbuf = kmem_alloc(e2fs_count, KM_SLEEP);
183 dstd = kmem_zalloc(sizeof(struct dirent), KM_SLEEP);
184 if (ap->a_ncookies) {
185 nc = e2fs_count / _DIRENT_MINSIZE((struct dirent *)0);
186 ncookies = nc;
187 cookies = malloc(sizeof (off_t) * ncookies, M_TEMP, M_WAITOK);
188 *ap->a_cookies = cookies;
189 }
190 aiov.iov_base = dirbuf;
191
192 error = UFS_BUFRD(ap->a_vp, &auio, 0, ap->a_cred);
193 if (error == 0) {
194 readcnt = e2fs_count - auio.uio_resid;
195 for (dp = (struct ext2fs_direct *)dirbuf;
196 (char *)dp < (char *)dirbuf + readcnt; ) {
197 e2d_reclen = fs2h16(dp->e2d_reclen);
198 if (e2d_reclen == 0) {
199 error = EIO;
200 break;
201 }
202 ext2fs_dirconv2ffs(dp, dstd);
203 if(dstd->d_reclen > uio->uio_resid) {
204 break;
205 }
206 error = uiomove(dstd, dstd->d_reclen, uio);
207 if (error != 0) {
208 break;
209 }
210 off = off + e2d_reclen;
211 if (cookies != NULL) {
212 *cookies++ = off;
213 if (--ncookies <= 0){
214 break; /* out of cookies */
215 }
216 }
217 /* advance dp */
218 dp = (struct ext2fs_direct *) ((char *)dp + e2d_reclen);
219 }
220 /* we need to correct uio_offset */
221 uio->uio_offset = off;
222 }
223 kmem_free(dirbuf, e2fs_count);
224 kmem_free(dstd, sizeof(*dstd));
225 *ap->a_eofflag = ext2fs_size(VTOI(ap->a_vp)) <= uio->uio_offset;
226 if (ap->a_ncookies) {
227 if (error) {
228 free(*ap->a_cookies, M_TEMP);
229 *ap->a_ncookies = 0;
230 *ap->a_cookies = NULL;
231 } else
232 *ap->a_ncookies = nc - ncookies;
233 }
234 return (error);
235 }
236
237 /*
238 * Convert a component of a pathname into a pointer to a locked inode.
239 * This is a very central and rather complicated routine.
240 * If the file system is not maintained in a strict tree hierarchy,
241 * this can result in a deadlock situation (see comments in code below).
242 *
243 * The cnp->cn_nameiop argument is LOOKUP, CREATE, RENAME, or DELETE depending
244 * on whether the name is to be looked up, created, renamed, or deleted.
245 * When CREATE, RENAME, or DELETE is specified, information usable in
246 * creating, renaming, or deleting a directory entry may be calculated.
247 * If flag has LOCKPARENT or'ed into it and the target of the pathname
248 * exists, lookup returns both the target and its parent directory locked.
249 * When creating or renaming and LOCKPARENT is specified, the target may
250 * not be ".". When deleting and LOCKPARENT is specified, the target may
251 * be "."., but the caller must check to ensure it does an vrele and vput
252 * instead of two vputs.
253 *
254 * Overall outline of ext2fs_lookup:
255 *
256 * check accessibility of directory
257 * look for name in cache, if found, then if at end of path
258 * and deleting or creating, drop it, else return name
259 * search for name in directory, to found or notfound
260 * notfound:
261 * if creating, return locked directory, leaving info on available slots
262 * else return error
263 * found:
264 * if at end of path and deleting, return information to allow delete
265 * if at end of path and rewriting (RENAME and LOCKPARENT), lock target
266 * inode and return info to allow rewrite
267 * if not at end, add name to cache; if at end and neither creating
268 * nor deleting, add name to cache
269 */
270 int
271 ext2fs_lookup(void *v)
272 {
273 struct vop_lookup_v2_args /* {
274 struct vnode *a_dvp;
275 struct vnode **a_vpp;
276 struct componentname *a_cnp;
277 } */ *ap = v;
278 struct vnode *vdp = ap->a_dvp; /* vnode for directory being searched */
279 struct inode *dp = VTOI(vdp); /* inode for directory being searched */
280 struct buf *bp; /* a buffer of directory entries */
281 struct ext2fs_direct *ep; /* the current directory entry */
282 int entryoffsetinblock; /* offset of ep in bp's buffer */
283 enum ext2fs_slotstatus slotstatus;
284 doff_t slotoffset; /* offset of area with free space */
285 int slotsize; /* size of area at slotoffset */
286 int slotfreespace; /* amount of space free in slot */
287 int slotneeded; /* size of the entry we're seeking */
288 int numdirpasses; /* strategy for directory search */
289 doff_t endsearch; /* offset to end directory search */
290 doff_t prevoff; /* prev entry dp->i_offset */
291 struct vnode *tdp; /* returned by vcache_get */
292 doff_t enduseful; /* pointer past last used dir slot */
293 u_long bmask; /* block offset mask */
294 int namlen, error;
295 struct vnode **vpp = ap->a_vpp;
296 struct componentname *cnp = ap->a_cnp;
297 kauth_cred_t cred = cnp->cn_cred;
298 int flags;
299 int nameiop = cnp->cn_nameiop;
300 struct ufsmount *ump = dp->i_ump;
301 int dirblksiz = ump->um_dirblksiz;
302 ino_t foundino;
303 struct ufs_lookup_results *results;
304 doff_t i_offset; /* cached i_offset value */
305 struct ext2fs_searchslot ss;
306
307 flags = cnp->cn_flags;
308
309 bp = NULL;
310 slotoffset = -1;
311 *vpp = NULL;
312
313 /*
314 * Produce the auxiliary lookup results into i_crap. Increment
315 * its serial number so elsewhere we can tell if we're using
316 * stale results. This should not be done this way. XXX.
317 */
318 results = &dp->i_crap;
319 dp->i_crapcounter++;
320
321 /*
322 * Check accessiblity of directory.
323 */
324 if ((error = VOP_ACCESS(vdp, VEXEC, cred)) != 0)
325 return (error);
326
327 if ((flags & ISLASTCN) && (vdp->v_mount->mnt_flag & MNT_RDONLY) &&
328 (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME))
329 return (EROFS);
330
331 /*
332 * We now have a segment name to search for, and a directory to search.
333 *
334 * Before tediously performing a linear scan of the directory,
335 * check the name cache to see if the directory/name pair
336 * we are looking for is known already.
337 */
338 if (cache_lookup(vdp, cnp->cn_nameptr, cnp->cn_namelen,
339 cnp->cn_nameiop, cnp->cn_flags, NULL, vpp)) {
340 return *vpp == NULLVP ? ENOENT : 0;
341 }
342
343 /*
344 * Suppress search for slots unless creating
345 * file and at end of pathname, in which case
346 * we watch for a place to put the new file in
347 * case it doesn't already exist.
348 */
349 slotstatus = FOUND;
350 slotfreespace = slotsize = slotneeded = 0;
351 if ((nameiop == CREATE || nameiop == RENAME) &&
352 (flags & ISLASTCN)) {
353 slotstatus = NONE;
354 slotneeded = EXT2FS_DIRSIZ(cnp->cn_namelen);
355 }
356
357 /*
358 * If there is cached information on a previous search of
359 * this directory, pick up where we last left off.
360 * We cache only lookups as these are the most common
361 * and have the greatest payoff. Caching CREATE has little
362 * benefit as it usually must search the entire directory
363 * to determine that the entry does not exist. Caching the
364 * location of the last DELETE or RENAME has not reduced
365 * profiling time and hence has been removed in the interest
366 * of simplicity.
367 */
368 bmask = vdp->v_mount->mnt_stat.f_iosize - 1;
369 if (nameiop != LOOKUP || results->ulr_diroff == 0 ||
370 results->ulr_diroff >= ext2fs_size(dp)) {
371 entryoffsetinblock = 0;
372 results->ulr_offset = 0;
373 numdirpasses = 1;
374 } else {
375 results->ulr_offset = results->ulr_diroff;
376 if ((entryoffsetinblock = results->ulr_offset & bmask) &&
377 (error = ext2fs_blkatoff(vdp, (off_t)results->ulr_offset, NULL, &bp)))
378 return (error);
379 numdirpasses = 2;
380 namecache_count_2passes();
381 }
382 prevoff = results->ulr_offset;
383 endsearch = roundup(ext2fs_size(dp), dirblksiz);
384 enduseful = 0;
385
386 /*
387 * Try to lookup dir entry using htree directory index.
388 *
389 * If we got an error or we want to find '.' or '..' entry,
390 * we will fall back to linear search.
391 */
392 if (ext2fs_htree_has_idx(dp) && ext2fs_is_dot_entry(cnp)) {
393 numdirpasses = 1;
394 entryoffsetinblock = 0;
395
396 int htree_lookup_ret = ext2fs_htree_lookup(dp, cnp->cn_nameptr,
397 cnp->cn_namelen, &bp, &entryoffsetinblock, &i_offset,
398 &prevoff, &enduseful, &ss);
399 switch (htree_lookup_ret) {
400 case 0:
401 ep = (struct ext2fs_direct*)((char *)bp->b_data +
402 (i_offset & bmask));
403 foundino = ep->e2d_ino;
404 goto found;
405 case ENOENT:
406 i_offset = roundup2(dp->i_size, dp->i_e2fs->e2fs_bsize);
407 goto notfound;
408 default:
409 /*
410 * Something failed; just fallback to do a linear
411 * search.
412 */
413 break;
414 }
415 }
416
417 searchloop:
418 while (results->ulr_offset < endsearch) {
419 if (curcpu()->ci_schedstate.spc_flags & SPCF_SHOULDYIELD)
420 preempt();
421 /*
422 * If necessary, get the next directory block.
423 */
424 if ((results->ulr_offset & bmask) == 0) {
425 if (bp != NULL)
426 brelse(bp, 0);
427 error = ext2fs_blkatoff(vdp, (off_t)results->ulr_offset, NULL,
428 &bp);
429 if (error != 0)
430 return (error);
431 entryoffsetinblock = 0;
432 }
433 /*
434 * If still looking for a slot, and at a dirblksize
435 * boundary, have to start looking for free space again.
436 */
437 if (slotstatus == NONE &&
438 (entryoffsetinblock & (dirblksiz - 1)) == 0) {
439 slotoffset = -1;
440 slotfreespace = 0;
441 }
442 /*
443 * Get pointer to next entry.
444 * Full validation checks are slow, so we only check
445 * enough to insure forward progress through the
446 * directory. Complete checks can be run by patching
447 * "dirchk" to be true.
448 */
449 KASSERT(bp != NULL);
450 ep = (struct ext2fs_direct *)
451 ((char *)bp->b_data + entryoffsetinblock);
452 if (ep->e2d_reclen == 0 ||
453 (dirchk &&
454 ext2fs_dirbadentry(vdp, ep, entryoffsetinblock))) {
455 int i;
456
457 ufs_dirbad(dp, results->ulr_offset, "mangled entry");
458 i = dirblksiz - (entryoffsetinblock & (dirblksiz - 1));
459 results->ulr_offset += i;
460 entryoffsetinblock += i;
461 continue;
462 }
463
464 /*
465 * If an appropriate sized slot has not yet been found,
466 * check to see if one is available. Also accumulate space
467 * in the current block so that we can determine if
468 * compaction is viable.
469 */
470 if (slotstatus != FOUND) {
471 int size = fs2h16(ep->e2d_reclen);
472
473 if (ep->e2d_ino != 0)
474 size -= EXT2FS_DIRSIZ(ep->e2d_namlen);
475 if (size > 0) {
476 if (size >= slotneeded) {
477 slotstatus = FOUND;
478 slotoffset = results->ulr_offset;
479 slotsize = fs2h16(ep->e2d_reclen);
480 } else if (slotstatus == NONE) {
481 slotfreespace += size;
482 if (slotoffset == -1)
483 slotoffset = results->ulr_offset;
484 if (slotfreespace >= slotneeded) {
485 slotstatus = COMPACT;
486 slotsize = results->ulr_offset +
487 fs2h16(ep->e2d_reclen) -
488 slotoffset;
489 }
490 }
491 }
492 }
493
494 /*
495 * Check for a name match.
496 */
497 if (ep->e2d_ino) {
498 namlen = ep->e2d_namlen;
499 if (namlen == cnp->cn_namelen &&
500 !memcmp(cnp->cn_nameptr, ep->e2d_name,
501 (unsigned)namlen)) {
502 /*
503 * Save directory entry's inode number and
504 * reclen in ndp->ni_ufs area, and release
505 * directory buffer.
506 */
507 foundino = fs2h32(ep->e2d_ino);
508 results->ulr_reclen = fs2h16(ep->e2d_reclen);
509 goto found;
510 }
511 }
512 prevoff = results->ulr_offset;
513 results->ulr_offset += fs2h16(ep->e2d_reclen);
514 entryoffsetinblock += fs2h16(ep->e2d_reclen);
515 if (ep->e2d_ino)
516 enduseful = results->ulr_offset;
517 }
518 notfound:
519 /*
520 * If we started in the middle of the directory and failed
521 * to find our target, we must check the beginning as well.
522 */
523 if (numdirpasses == 2) {
524 numdirpasses--;
525 results->ulr_offset = 0;
526 endsearch = results->ulr_diroff;
527 goto searchloop;
528 }
529 if (bp != NULL)
530 brelse(bp, 0);
531 /*
532 * If creating, and at end of pathname and current
533 * directory has not been removed, then can consider
534 * allowing file to be created.
535 */
536 if ((nameiop == CREATE || nameiop == RENAME) &&
537 (flags & ISLASTCN) && dp->i_e2fs_nlink != 0) {
538 /*
539 * Access for write is interpreted as allowing
540 * creation of files in the directory.
541 */
542 error = VOP_ACCESS(vdp, VWRITE, cred);
543 if (error)
544 return (error);
545 /*
546 * Return an indication of where the new directory
547 * entry should be put. If we didn't find a slot,
548 * then set results->ulr_count to 0 indicating
549 * that the new slot belongs at the end of the
550 * directory. If we found a slot, then the new entry
551 * can be put in the range from results->ulr_offset to
552 * results->ulr_offset + results->ulr_count.
553 */
554 if (slotstatus == NONE) {
555 results->ulr_offset = roundup(ext2fs_size(dp), dirblksiz);
556 results->ulr_count = 0;
557 enduseful = results->ulr_offset;
558 } else {
559 results->ulr_offset = slotoffset;
560 results->ulr_count = slotsize;
561 if (enduseful < slotoffset + slotsize)
562 enduseful = slotoffset + slotsize;
563 }
564 results->ulr_endoff = roundup(enduseful, dirblksiz);
565 #if 0
566 dp->i_flag |= IN_CHANGE | IN_UPDATE;
567 #endif
568 /*
569 * We return with the directory locked, so that
570 * the parameters we set up above will still be
571 * valid if we actually decide to do a direnter().
572 * We return ni_vp == NULL to indicate that the entry
573 * does not currently exist; we leave a pointer to
574 * the (locked) directory inode in ndp->ni_dvp.
575 *
576 * NB - if the directory is unlocked, then this
577 * information cannot be used.
578 */
579 return (EJUSTRETURN);
580 }
581 /*
582 * Insert name into cache (as non-existent) if appropriate.
583 */
584 if (nameiop != CREATE) {
585 cache_enter(vdp, *vpp, cnp->cn_nameptr, cnp->cn_namelen,
586 cnp->cn_flags);
587 }
588 return ENOENT;
589
590 found:
591 if (numdirpasses == 2)
592 namecache_count_pass2();
593 /*
594 * Check that directory length properly reflects presence
595 * of this entry.
596 */
597 if (results->ulr_offset + EXT2FS_DIRSIZ(ep->e2d_namlen) > ext2fs_size(dp)) {
598 ufs_dirbad(dp, results->ulr_offset, "i_size too small");
599 error = ext2fs_setsize(dp,
600 results->ulr_offset + EXT2FS_DIRSIZ(ep->e2d_namlen));
601 if (error) {
602 brelse(bp, 0);
603 return (error);
604 }
605 dp->i_flag |= IN_CHANGE | IN_UPDATE;
606 uvm_vnp_setsize(vdp, ext2fs_size(dp));
607 }
608 brelse(bp, 0);
609
610 /*
611 * Found component in pathname.
612 * If the final component of path name, save information
613 * in the cache as to where the entry was found.
614 */
615 if ((flags & ISLASTCN) && nameiop == LOOKUP)
616 results->ulr_diroff = results->ulr_offset &~ (dirblksiz - 1);
617
618 /*
619 * If deleting, and at end of pathname, return
620 * parameters which can be used to remove file.
621 * Lock the inode, being careful with ".".
622 */
623 if (nameiop == DELETE && (flags & ISLASTCN)) {
624 /*
625 * Return pointer to current entry in results->ulr_offset,
626 * and distance past previous entry (if there
627 * is a previous entry in this block) in results->ulr_count.
628 * Save directory inode pointer in ndp->ni_dvp for dirremove().
629 */
630 if ((results->ulr_offset & (dirblksiz - 1)) == 0)
631 results->ulr_count = 0;
632 else
633 results->ulr_count = results->ulr_offset - prevoff;
634 if (dp->i_number == foundino) {
635 vref(vdp);
636 tdp = vdp;
637 } else {
638 error = vcache_get(vdp->v_mount,
639 &foundino, sizeof(foundino), &tdp);
640 if (error)
641 return (error);
642 }
643 /*
644 * Write access to directory required to delete files.
645 */
646 if ((error = VOP_ACCESS(vdp, VWRITE, cred)) != 0) {
647 vrele(tdp);
648 return (error);
649 }
650 /*
651 * If directory is "sticky", then user must own
652 * the directory, or the file in it, else she
653 * may not delete it (unless she's root). This
654 * implements append-only directories.
655 */
656 if (dp->i_e2fs_mode & ISVTX) {
657 error = kauth_authorize_vnode(cred, KAUTH_VNODE_DELETE,
658 tdp, vdp, genfs_can_sticky(cred, dp->i_uid,
659 VTOI(tdp)->i_uid));
660 if (error) {
661 vrele(tdp);
662 return (EPERM);
663 }
664 }
665 *vpp = tdp;
666 return (0);
667 }
668
669 /*
670 * If rewriting (RENAME), return the inode and the
671 * information required to rewrite the present directory
672 * Must get inode of directory entry to verify it's a
673 * regular file, or empty directory.
674 */
675 if (nameiop == RENAME && (flags & ISLASTCN)) {
676 error = VOP_ACCESS(vdp, VWRITE, cred);
677 if (error)
678 return (error);
679 /*
680 * Careful about locking second inode.
681 * This can only occur if the target is ".".
682 */
683 if (dp->i_number == foundino)
684 return (EISDIR);
685 error = vcache_get(vdp->v_mount,
686 &foundino, sizeof(foundino), &tdp);
687 if (error)
688 return (error);
689 *vpp = tdp;
690 return (0);
691 }
692
693 if (dp->i_number == foundino) {
694 vref(vdp); /* we want ourself, ie "." */
695 *vpp = vdp;
696 } else {
697 error = vcache_get(vdp->v_mount,
698 &foundino, sizeof(foundino), &tdp);
699 if (error)
700 return (error);
701 *vpp = tdp;
702 }
703
704 /*
705 * Insert name into cache if appropriate.
706 */
707 cache_enter(vdp, *vpp, cnp->cn_nameptr, cnp->cn_namelen, cnp->cn_flags);
708 return 0;
709 }
710
711 int
712 ext2fs_search_dirblock(struct inode *ip, void *data, int *foundp,
713 const char *name, int namelen, int *entryoffsetinblockp,
714 doff_t *offp, doff_t *prevoffp, doff_t *endusefulp,
715 struct ext2fs_searchslot *ssp)
716 {
717 struct vnode *vdp = ITOV(ip);
718 struct ext2fs_direct *ep, *top;
719 uint32_t bsize = ip->i_e2fs->e2fs_bsize;
720 int offset = *entryoffsetinblockp;
721 int namlen;
722
723 ep = (void *)((char *)data + offset);
724 top = (void *)((char *)data + bsize - EXT2_DIR_REC_LEN(0));
725
726 while (ep < top) {
727 /*
728 * Full validation checks are slow, so we only check
729 * enough to insure forward progress through the
730 * directory. Complete checks can be run by setting
731 * "vfs.e2fs.dirchk" to be true.
732 */
733 if (ep->e2d_reclen == 0 ||
734 (dirchk && ext2fs_dirbadentry(vdp, ep, offset))) {
735 int i;
736 ufs_dirbad(ip, *offp, "mangled entry");
737 i = bsize - (offset & (bsize - 1));
738 *offp += i;
739 offset += i;
740 continue;
741 }
742
743 /*
744 * If an appropriate sized slot has not yet been found,
745 * check to see if one is available. Also accumulate space
746 * in the current block so that we can determine if
747 * compaction is viable.
748 */
749 if (ssp->slotstatus != FOUND) {
750 int size = ep->e2d_reclen;
751
752 if (ep->e2d_ino != 0)
753 size -= EXT2_DIR_REC_LEN(ep->e2d_namlen);
754 if (size >= ssp->slotneeded) {
755 ssp->slotstatus = FOUND;
756 ssp->slotoffset = *offp;
757 ssp->slotsize = ep->e2d_reclen;
758 } else if (size > 0 && ssp->slotstatus == NONE) {
759 ssp->slotfreespace += size;
760 if (ssp->slotoffset == -1)
761 ssp->slotoffset = *offp;
762 if (ssp->slotfreespace >= ssp->slotneeded) {
763 ssp->slotstatus = COMPACT;
764 ssp->slotsize = *offp + ep->e2d_reclen -
765 ssp->slotoffset;
766 }
767 }
768 }
769
770 /*
771 * Check for a name match.
772 */
773 if (ep->e2d_ino) {
774 namlen = ep->e2d_namlen;
775 if (namlen == namelen &&
776 !memcmp(name, ep->e2d_name, (unsigned)namlen)) {
777 /*
778 * Save directory entry's inode number and
779 * reclen in ndp->ni_ufs area, and release
780 * directory buffer.
781 */
782 *foundp = 1;
783 return 0;
784 }
785 }
786 *prevoffp = *offp;
787 *offp += ep->e2d_reclen;
788 offset += ep->e2d_reclen;
789 *entryoffsetinblockp = offset;
790 if (ep->e2d_ino)
791 *endusefulp = *offp;
792 /*
793 * Get pointer to the next entry.
794 */
795 ep = (void *)((char *)data + offset);
796 }
797
798 return 0;
799 }
800
801 /*
802 * Do consistency checking on a directory entry:
803 * record length must be multiple of 4
804 * entry must fit in rest of its dirblksize block
805 * record must be large enough to contain entry
806 * name is not longer than EXT2FS_MAXNAMLEN
807 * name must be as long as advertised, and null terminated
808 */
809 /*
810 * changed so that it confirms to ext2fs_check_dir_entry
811 */
812 static int
813 ext2fs_dirbadentry(struct vnode *dp, struct ext2fs_direct *de,
814 int entryoffsetinblock)
815 {
816 struct ufsmount *ump = VFSTOUFS(dp->v_mount);
817 int dirblksiz = ump->um_dirblksiz;
818
819 const char *error_msg = NULL;
820 int reclen = fs2h16(de->e2d_reclen);
821 int namlen = de->e2d_namlen;
822
823 if (reclen < EXT2FS_DIRSIZ(1)) /* e2d_namlen = 1 */
824 error_msg = "rec_len is smaller than minimal";
825 #if 0
826 else if (reclen % 4 != 0)
827 error_msg = "rec_len % 4 != 0";
828 #endif
829 else if (namlen > EXT2FS_MAXNAMLEN)
830 error_msg = "namlen > EXT2FS_MAXNAMLEN";
831 else if (reclen < EXT2FS_DIRSIZ(namlen))
832 error_msg = "reclen is too small for name_len";
833 else if (entryoffsetinblock + reclen > dirblksiz)
834 error_msg = "directory entry across blocks";
835 else if (fs2h32(de->e2d_ino) >
836 VTOI(dp)->i_e2fs->e2fs.e2fs_icount)
837 error_msg = "inode out of bounds";
838
839 if (error_msg != NULL) {
840 printf( "bad directory entry: %s\n"
841 "offset=%d, inode=%lu, rec_len=%d, name_len=%d \n",
842 error_msg, entryoffsetinblock,
843 (unsigned long) fs2h32(de->e2d_ino),
844 reclen, namlen);
845 panic("ext2fs_dirbadentry");
846 }
847 return error_msg == NULL ? 0 : 1;
848 }
849
850 /*
851 * Write a directory entry after a call to namei, using the parameters
852 * that it left in nameidata. The argument ip is the inode which the new
853 * directory entry will refer to. Dvp is a pointer to the directory to
854 * be written, which was left locked by namei. Remaining parameters
855 * (ulr_offset, ulr_count) indicate how the space for the new
856 * entry is to be obtained.
857 */
858 int
859 ext2fs_direnter(struct inode *ip, struct vnode *dvp,
860 const struct ufs_lookup_results *ulr, struct componentname *cnp)
861 {
862 struct inode *dp;
863 struct ext2fs_direct newdir;
864 struct iovec aiov;
865 struct uio auio;
866 int error, newentrysize;
867 struct ufsmount *ump = VFSTOUFS(dvp->v_mount);
868 int dirblksiz = ump->um_dirblksiz;
869
870 dp = VTOI(dvp);
871
872 newdir.e2d_ino = h2fs32(ip->i_number);
873 newdir.e2d_namlen = cnp->cn_namelen;
874 if (ip->i_e2fs->e2fs.e2fs_rev > E2FS_REV0 &&
875 (ip->i_e2fs->e2fs.e2fs_features_incompat & EXT2F_INCOMPAT_FTYPE)) {
876 newdir.e2d_type = inot2ext2dt(IFTODT(ip->i_e2fs_mode));
877 } else {
878 newdir.e2d_type = 0;
879 }
880 memcpy(newdir.e2d_name, cnp->cn_nameptr, (unsigned)cnp->cn_namelen + 1);
881 newentrysize = EXT2FS_DIRSIZ(cnp->cn_namelen);
882
883 if (ext2fs_htree_has_idx(dp)) {
884 error = ext2fs_htree_add_entry(dvp, &newdir, cnp);
885 if (error) {
886 dp->i_e2fs_flags&= ~EXT2_INDEX;
887 dp->i_flag |= IN_CHANGE | IN_UPDATE;
888 }
889 return error;
890 }
891
892 /*
893 * TODO check if Htree index is not created for the directory then
894 * create one if directory entries get overflew the first dir-block
895 */
896 if (ulr->ulr_count == 0) {
897 /*
898 * If ulr_count is 0, then namei could find no
899 * space in the directory. Here, ulr_offset will
900 * be on a directory block boundary and we will write the
901 * new entry into a fresh block.
902 */
903 if (ulr->ulr_offset & (dirblksiz - 1))
904 panic("ext2fs_direnter: newblk");
905 auio.uio_offset = ulr->ulr_offset;
906 newdir.e2d_reclen = h2fs16(dirblksiz);
907 auio.uio_resid = newentrysize;
908 aiov.iov_len = newentrysize;
909 aiov.iov_base = (void *)&newdir;
910 auio.uio_iov = &aiov;
911 auio.uio_iovcnt = 1;
912 auio.uio_rw = UIO_WRITE;
913 UIO_SETUP_SYSSPACE(&auio);
914 error = ext2fs_bufwr(dvp, &auio, IO_SYNC, cnp->cn_cred);
915 if (dirblksiz > dvp->v_mount->mnt_stat.f_bsize)
916 /* XXX should grow with balloc() */
917 panic("ext2fs_direnter: frag size");
918 else if (!error) {
919 error = ext2fs_setsize(dp,
920 roundup(ext2fs_size(dp), dirblksiz));
921 if (error)
922 return (error);
923 dp->i_flag |= IN_CHANGE;
924 uvm_vnp_setsize(dvp, ext2fs_size(dp));
925 }
926 return error;
927 }
928
929 error = ext2fs_add_entry(dvp, &newdir,ulr);
930
931 if (!error && ulr->ulr_endoff && ulr->ulr_endoff < ext2fs_size(dp))
932 error = ext2fs_truncate(dvp, (off_t)ulr->ulr_endoff, IO_SYNC,
933 cnp->cn_cred);
934 return error;
935 }
936
937 /*
938 * Insert an entry into the directory block.
939 * Compact the contents.
940 */
941
942 int
943 ext2fs_add_entry (struct vnode* dvp, struct ext2fs_direct *entry,
944 const struct ufs_lookup_results *ulr)
945 {
946 struct ext2fs_direct *ep, *nep;
947 struct inode *dp;
948 struct buf *bp;
949 u_int dsize;
950 int error, loc, newentrysize, spacefree;
951 char *dirbuf;
952
953 dp = VTOI(dvp);
954
955 /*
956 * If ulr_count is non-zero, then namei found space
957 * for the new entry in the range ulr_offset to
958 * ulr_offset + ulr_count in the directory.
959 * To use this space, we may have to compact the entries located
960 * there, by copying them together towards the beginning of the
961 * block, leaving the free space in one usable chunk at the end.
962 */
963
964 /*
965 * Get the block containing the space for the new directory entry.
966 */
967 if ((error = ext2fs_blkatoff(dvp, (off_t)ulr->ulr_offset, &dirbuf, &bp)) != 0)
968 return (error);
969 /*
970 * Find space for the new entry. In the simple case, the entry at
971 * offset base will have the space. If it does not, then namei
972 * arranged that compacting the region ulr_offset to
973 * ulr_offset + ulr_count would yield the
974 * space.
975 */
976 ep = (struct ext2fs_direct *)dirbuf;
977 newentrysize = dsize = EXT2FS_DIRSIZ(ep->e2d_namlen);
978 spacefree = fs2h16(ep->e2d_reclen) - dsize;
979 for (loc = fs2h16(ep->e2d_reclen); loc < ulr->ulr_count; ) {
980 nep = (struct ext2fs_direct *)(dirbuf + loc);
981 if (ep->e2d_ino) {
982 /* trim the existing slot */
983 ep->e2d_reclen = h2fs16(dsize);
984 ep = (struct ext2fs_direct *)((char *)ep + dsize);
985 } else {
986 /* overwrite; nothing there; header is ours */
987 spacefree += dsize;
988 }
989 dsize = EXT2FS_DIRSIZ(nep->e2d_namlen);
990 spacefree += fs2h16(nep->e2d_reclen) - dsize;
991 loc += fs2h16(nep->e2d_reclen);
992 memcpy((void *)ep, (void *)nep, dsize);
993 }
994 /*
995 * Update the pointer fields in the previous entry (if any),
996 * copy in the new entry, and write out the block.
997 */
998 if (ep->e2d_ino == 0) {
999 #ifdef DIAGNOSTIC
1000 if (spacefree + dsize < newentrysize)
1001 panic("ext2fs_direnter: compact1");
1002 #endif
1003 entry->e2d_reclen = h2fs16(spacefree + dsize);
1004 } else {
1005 #ifdef DIAGNOSTIC
1006 if (spacefree < newentrysize) {
1007 printf("ext2fs_direnter: compact2 %u %u",
1008 (u_int)spacefree, (u_int)newentrysize);
1009 panic("ext2fs_direnter: compact2");
1010 }
1011 #endif
1012 entry->e2d_reclen = h2fs16(spacefree);
1013 ep->e2d_reclen = h2fs16(dsize);
1014 ep = (struct ext2fs_direct *)((char *)ep + dsize);
1015 }
1016 memcpy(ep, entry, (u_int)newentrysize);
1017 error = VOP_BWRITE(bp->b_vp, bp);
1018 dp->i_flag |= IN_CHANGE | IN_UPDATE;
1019 return error;
1020 }
1021
1022 /*
1023 * Remove a directory entry after a call to namei, using
1024 * the auxiliary results it provided. The entry
1025 * ulr_offset contains the offset into the directory of the
1026 * entry to be eliminated. The ulr_count field contains the
1027 * size of the previous record in the directory. If this
1028 * is 0, the first entry is being deleted, so we need only
1029 * zero the inode number to mark the entry as free. If the
1030 * entry is not the first in the directory, we must reclaim
1031 * the space of the now empty record by adding the record size
1032 * to the size of the previous entry.
1033 */
1034 int
1035 ext2fs_dirremove(struct vnode *dvp, const struct ufs_lookup_results *ulr,
1036 struct componentname *cnp)
1037 {
1038 struct inode *dp;
1039 struct ext2fs_direct *ep;
1040 struct buf *bp;
1041 int error;
1042
1043 dp = VTOI(dvp);
1044
1045 if (ulr->ulr_count == 0) {
1046 /*
1047 * First entry in block: set d_ino to zero.
1048 */
1049 error = ext2fs_blkatoff(dvp, (off_t)ulr->ulr_offset,
1050 (void *)&ep, &bp);
1051 if (error != 0)
1052 return (error);
1053 ep->e2d_ino = 0;
1054 error = VOP_BWRITE(bp->b_vp, bp);
1055 dp->i_flag |= IN_CHANGE | IN_UPDATE;
1056 return (error);
1057 }
1058 /*
1059 * Collapse new free space into previous entry.
1060 */
1061 error = ext2fs_blkatoff(dvp, (off_t)(ulr->ulr_offset - ulr->ulr_count),
1062 (void *)&ep, &bp);
1063 if (error != 0)
1064 return (error);
1065 ep->e2d_reclen = h2fs16(fs2h16(ep->e2d_reclen) + ulr->ulr_reclen);
1066 error = VOP_BWRITE(bp->b_vp, bp);
1067 dp->i_flag |= IN_CHANGE | IN_UPDATE;
1068 return (error);
1069 }
1070
1071 /*
1072 * Rewrite an existing directory entry to point at the inode
1073 * supplied. The parameters describing the directory entry are
1074 * set up by a call to namei.
1075 */
1076 int
1077 ext2fs_dirrewrite(struct inode *dp, const struct ufs_lookup_results *ulr,
1078 struct inode *ip, struct componentname *cnp)
1079 {
1080 struct buf *bp;
1081 struct ext2fs_direct *ep;
1082 struct vnode *vdp = ITOV(dp);
1083 int error;
1084
1085 error = ext2fs_blkatoff(vdp, (off_t)ulr->ulr_offset, (void *)&ep, &bp);
1086 if (error != 0)
1087 return (error);
1088 ep->e2d_ino = h2fs32(ip->i_number);
1089 if (ip->i_e2fs->e2fs.e2fs_rev > E2FS_REV0 &&
1090 (ip->i_e2fs->e2fs.e2fs_features_incompat & EXT2F_INCOMPAT_FTYPE)) {
1091 ep->e2d_type = inot2ext2dt(IFTODT(ip->i_e2fs_mode));
1092 } else {
1093 ep->e2d_type = 0;
1094 }
1095 error = VOP_BWRITE(bp->b_vp, bp);
1096 dp->i_flag |= IN_CHANGE | IN_UPDATE;
1097 return (error);
1098 }
1099
1100 /*
1101 * Check if a directory is empty or not.
1102 * Inode supplied must be locked.
1103 *
1104 * Using a struct dirtemplate here is not precisely
1105 * what we want, but better than using a struct ext2fs_direct.
1106 *
1107 * NB: does not handle corrupted directories.
1108 */
1109 int
1110 ext2fs_dirempty(struct inode *ip, ino_t parentino, kauth_cred_t cred)
1111 {
1112 off_t off;
1113 struct ext2fs_dirtemplate dbuf;
1114 struct ext2fs_direct *dp = (struct ext2fs_direct *)&dbuf;
1115 int error, namlen;
1116 size_t count;
1117
1118 #define MINDIRSIZ (sizeof (struct ext2fs_dirtemplate) / 2)
1119
1120 for (off = 0; off < ext2fs_size(ip); off += fs2h16(dp->e2d_reclen)) {
1121 error = ufs_bufio(UIO_READ, ITOV(ip), (void *)dp, MINDIRSIZ,
1122 off, IO_NODELOCKED, cred, &count, NULL);
1123 /*
1124 * Since we read MINDIRSIZ, residual must
1125 * be 0 unless we're at end of file.
1126 */
1127 if (error || count != 0)
1128 return (0);
1129 /* avoid infinite loops */
1130 if (dp->e2d_reclen == 0)
1131 return (0);
1132 /* skip empty entries */
1133 if (dp->e2d_ino == 0)
1134 continue;
1135 /* accept only "." and ".." */
1136 namlen = dp->e2d_namlen;
1137 if (namlen > 2)
1138 return (0);
1139 if (dp->e2d_name[0] != '.')
1140 return (0);
1141 /*
1142 * At this point namlen must be 1 or 2.
1143 * 1 implies ".", 2 implies ".." if second
1144 * char is also "."
1145 */
1146 if (namlen == 1)
1147 continue;
1148 if (dp->e2d_name[1] == '.' && fs2h32(dp->e2d_ino) == parentino)
1149 continue;
1150 return (0);
1151 }
1152 return (1);
1153 }
1154