ulfs_lookup.c revision 1.10 1 /* $NetBSD: ulfs_lookup.c,v 1.10 2013/06/08 22:05:15 dholland Exp $ */
2 /* from NetBSD: ufs_lookup.c,v 1.122 2013/01/22 09:39:18 dholland Exp */
3
4 /*
5 * Copyright (c) 1989, 1993
6 * The Regents of the University of California. All rights reserved.
7 * (c) UNIX System Laboratories, Inc.
8 * All or some portions of this file are derived from material licensed
9 * to the University of California by American Telephone and Telegraph
10 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
11 * the permission of UNIX System Laboratories, Inc.
12 *
13 * Redistribution and use in source and binary forms, with or without
14 * modification, are permitted provided that the following conditions
15 * are met:
16 * 1. Redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer.
18 * 2. Redistributions in binary form must reproduce the above copyright
19 * notice, this list of conditions and the following disclaimer in the
20 * documentation and/or other materials provided with the distribution.
21 * 3. Neither the name of the University nor the names of its contributors
22 * may be used to endorse or promote products derived from this software
23 * without specific prior written permission.
24 *
25 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 * SUCH DAMAGE.
36 *
37 * @(#)ufs_lookup.c 8.9 (Berkeley) 8/11/94
38 */
39
40 #include <sys/cdefs.h>
41 __KERNEL_RCSID(0, "$NetBSD: ulfs_lookup.c,v 1.10 2013/06/08 22:05:15 dholland Exp $");
42
43 #ifdef _KERNEL_OPT
44 #include "opt_lfs.h"
45 #endif
46
47 #include <sys/param.h>
48 #include <sys/systm.h>
49 #include <sys/namei.h>
50 #include <sys/buf.h>
51 #include <sys/file.h>
52 #include <sys/stat.h>
53 #include <sys/mount.h>
54 #include <sys/vnode.h>
55 #include <sys/kernel.h>
56 #include <sys/kauth.h>
57 #include <sys/wapbl.h>
58 #include <sys/fstrans.h>
59 #include <sys/proc.h>
60 #include <sys/kmem.h>
61
62 #include <ufs/lfs/ulfs_inode.h>
63 #include <ufs/lfs/ulfs_dir.h>
64 #ifdef LFS_DIRHASH
65 #include <ufs/lfs/ulfs_dirhash.h>
66 #endif
67 #include <ufs/lfs/ulfsmount.h>
68 #include <ufs/lfs/ulfs_extern.h>
69 #include <ufs/lfs/ulfs_bswap.h>
70
71 #include <miscfs/genfs/genfs.h>
72
73 #ifdef DIAGNOSTIC
74 int lfs_dirchk = 1;
75 #else
76 int lfs_dirchk = 0;
77 #endif
78
79 /*
80 * Convert a component of a pathname into a pointer to a locked inode.
81 * This is a very central and rather complicated routine.
82 * If the file system is not maintained in a strict tree hierarchy,
83 * this can result in a deadlock situation (see comments in code below).
84 *
85 * The cnp->cn_nameiop argument is LOOKUP, CREATE, RENAME, or DELETE depending
86 * on whether the name is to be looked up, created, renamed, or deleted.
87 * When CREATE, RENAME, or DELETE is specified, information usable in
88 * creating, renaming, or deleting a directory entry may be calculated.
89 * If flag has LOCKPARENT or'ed into it and the target of the pathname
90 * exists, lookup returns both the target and its parent directory locked.
91 * When creating or renaming and LOCKPARENT is specified, the target may
92 * not be ".". When deleting and LOCKPARENT is specified, the target may
93 * be "."., but the caller must check to ensure it does an vrele and vput
94 * instead of two vputs.
95 *
96 * Overall outline of ulfs_lookup:
97 *
98 * check accessibility of directory
99 * look for name in cache, if found, then if at end of path
100 * and deleting or creating, drop it, else return name
101 * search for name in directory, to found or notfound
102 * notfound:
103 * if creating, return locked directory, leaving info on available slots
104 * else return error
105 * found:
106 * if at end of path and deleting, return information to allow delete
107 * if at end of path and rewriting (RENAME and LOCKPARENT), lock target
108 * inode and return info to allow rewrite
109 * if not at end, add name to cache; if at end and neither creating
110 * nor deleting, add name to cache
111 */
112 int
113 ulfs_lookup(void *v)
114 {
115 struct vop_lookup_args /* {
116 struct vnode *a_dvp;
117 struct vnode **a_vpp;
118 struct componentname *a_cnp;
119 } */ *ap = v;
120 struct vnode *vdp = ap->a_dvp; /* vnode for directory being searched */
121 struct inode *dp = VTOI(vdp); /* inode for directory being searched */
122 struct buf *bp; /* a buffer of directory entries */
123 struct lfs_direct *ep; /* the current directory entry */
124 int entryoffsetinblock; /* offset of ep in bp's buffer */
125 enum {
126 NONE, /* need to search a slot for our new entry */
127 COMPACT, /* a compaction can make a slot in the current
128 DIRBLKSIZ block */
129 FOUND, /* found a slot (or no need to search) */
130 } slotstatus;
131 doff_t slotoffset; /* offset of area with free space.
132 a special value -1 for invalid */
133 int slotsize; /* size of area at slotoffset */
134 int slotfreespace; /* accumulated amount of space free in
135 the current DIRBLKSIZ block */
136 int slotneeded; /* size of the entry we're seeking */
137 int numdirpasses; /* strategy for directory search */
138 doff_t endsearch; /* offset to end directory search */
139 doff_t prevoff; /* previous value of ulr_offset */
140 struct vnode *pdp; /* saved dp during symlink work */
141 struct vnode *tdp; /* returned by VFS_VGET */
142 doff_t enduseful; /* pointer past last used dir slot.
143 used for directory truncation. */
144 u_long bmask; /* block offset mask */
145 int error;
146 struct vnode **vpp = ap->a_vpp;
147 struct componentname *cnp = ap->a_cnp;
148 kauth_cred_t cred = cnp->cn_cred;
149 int flags;
150 int nameiop = cnp->cn_nameiop;
151 struct ulfsmount *ump = dp->i_ump;
152 const int needswap = ULFS_MPNEEDSWAP(ump);
153 int dirblksiz = ump->um_dirblksiz;
154 ino_t foundino;
155 struct ulfs_lookup_results *results;
156 int iswhiteout; /* temp result from cache_lookup() */
157
158 flags = cnp->cn_flags;
159
160 bp = NULL;
161 slotoffset = -1;
162 *vpp = NULL;
163 endsearch = 0; /* silence compiler warning */
164
165 /*
166 * Produce the auxiliary lookup results into i_crap. Increment
167 * its serial number so elsewhere we can tell if we're using
168 * stale results. This should not be done this way. XXX.
169 */
170 results = &dp->i_crap;
171 dp->i_crapcounter++;
172
173 /*
174 * Check accessiblity of directory.
175 */
176 if ((error = VOP_ACCESS(vdp, VEXEC, cred)) != 0)
177 return (error);
178
179 if ((flags & ISLASTCN) && (vdp->v_mount->mnt_flag & MNT_RDONLY) &&
180 (nameiop == DELETE || nameiop == RENAME))
181 return (EROFS);
182
183 /*
184 * We now have a segment name to search for, and a directory to search.
185 *
186 * Before tediously performing a linear scan of the directory,
187 * check the name cache to see if the directory/name pair
188 * we are looking for is known already.
189 */
190 if (cache_lookup(vdp, cnp->cn_nameptr, cnp->cn_namelen,
191 cnp->cn_nameiop, cnp->cn_flags, &iswhiteout, vpp)) {
192 if (iswhiteout) {
193 cnp->cn_flags |= ISWHITEOUT;
194 }
195 return *vpp == NULLVP ? ENOENT : 0;
196 }
197 if (iswhiteout) {
198 /*
199 * The namecache set iswhiteout without finding a
200 * cache entry. As of this writing (20121014), this
201 * can happen if there was a whiteout entry that has
202 * been invalidated by the lookup. It is not clear if
203 * it is correct to set ISWHITEOUT in this case or
204 * not; however, doing so retains the prior behavior,
205 * so we'll go with that until some clearer answer
206 * appears. XXX
207 */
208 cnp->cn_flags |= ISWHITEOUT;
209 }
210
211 fstrans_start(vdp->v_mount, FSTRANS_SHARED);
212
213 /*
214 * Suppress search for slots unless creating
215 * file and at end of pathname, in which case
216 * we watch for a place to put the new file in
217 * case it doesn't already exist.
218 */
219 slotstatus = FOUND;
220 slotfreespace = slotsize = slotneeded = 0;
221 if ((nameiop == CREATE || nameiop == RENAME) && (flags & ISLASTCN)) {
222 slotstatus = NONE;
223 slotneeded = LFS_DIRECTSIZ(cnp->cn_namelen);
224 }
225
226 /*
227 * If there is cached information on a previous search of
228 * this directory, pick up where we last left off.
229 * We cache only lookups as these are the most common
230 * and have the greatest payoff. Caching CREATE has little
231 * benefit as it usually must search the entire directory
232 * to determine that the entry does not exist. Caching the
233 * location of the last DELETE or RENAME has not reduced
234 * profiling time and hence has been removed in the interest
235 * of simplicity.
236 */
237 bmask = vdp->v_mount->mnt_stat.f_iosize - 1;
238
239 #ifdef LFS_DIRHASH
240 /*
241 * Use dirhash for fast operations on large directories. The logic
242 * to determine whether to hash the directory is contained within
243 * ulfsdirhash_build(); a zero return means that it decided to hash
244 * this directory and it successfully built up the hash table.
245 */
246 if (ulfsdirhash_build(dp) == 0) {
247 /* Look for a free slot if needed. */
248 enduseful = dp->i_size;
249 if (slotstatus != FOUND) {
250 slotoffset = ulfsdirhash_findfree(dp, slotneeded,
251 &slotsize);
252 if (slotoffset >= 0) {
253 slotstatus = COMPACT;
254 enduseful = ulfsdirhash_enduseful(dp);
255 if (enduseful < 0)
256 enduseful = dp->i_size;
257 }
258 }
259 /* Look up the component. */
260 numdirpasses = 1;
261 entryoffsetinblock = 0; /* silence compiler warning */
262 switch (ulfsdirhash_lookup(dp, cnp->cn_nameptr, cnp->cn_namelen,
263 &results->ulr_offset, &bp, nameiop == DELETE ? &prevoff : NULL)) {
264 case 0:
265 ep = (struct lfs_direct *)((char *)bp->b_data +
266 (results->ulr_offset & bmask));
267 goto foundentry;
268 case ENOENT:
269 results->ulr_offset = roundup(dp->i_size, dirblksiz);
270 goto notfound;
271 default:
272 /* Something failed; just do a linear search. */
273 break;
274 }
275 }
276 #endif /* LFS_DIRHASH */
277
278 if (nameiop != LOOKUP || results->ulr_diroff == 0 ||
279 results->ulr_diroff >= dp->i_size) {
280 entryoffsetinblock = 0;
281 results->ulr_offset = 0;
282 numdirpasses = 1;
283 } else {
284 results->ulr_offset = results->ulr_diroff;
285 if ((entryoffsetinblock = results->ulr_offset & bmask) &&
286 (error = ulfs_blkatoff(vdp, (off_t)results->ulr_offset,
287 NULL, &bp, false)))
288 goto out;
289 numdirpasses = 2;
290 nchstats.ncs_2passes++;
291 }
292 prevoff = results->ulr_offset;
293 endsearch = roundup(dp->i_size, dirblksiz);
294 enduseful = 0;
295
296 searchloop:
297 while (results->ulr_offset < endsearch) {
298 if (curcpu()->ci_schedstate.spc_flags & SPCF_SHOULDYIELD)
299 preempt();
300 /*
301 * If necessary, get the next directory block.
302 */
303 if ((results->ulr_offset & bmask) == 0) {
304 if (bp != NULL)
305 brelse(bp, 0);
306 error = ulfs_blkatoff(vdp, (off_t)results->ulr_offset,
307 NULL, &bp, false);
308 if (error)
309 goto out;
310 entryoffsetinblock = 0;
311 }
312 /*
313 * If still looking for a slot, and at a DIRBLKSIZ
314 * boundary, have to start looking for free space again.
315 */
316 if (slotstatus == NONE &&
317 (entryoffsetinblock & (dirblksiz - 1)) == 0) {
318 slotoffset = -1;
319 slotfreespace = 0;
320 }
321 /*
322 * Get pointer to next entry.
323 * Full validation checks are slow, so we only check
324 * enough to insure forward progress through the
325 * directory. Complete checks can be run by patching
326 * "lfs_dirchk" to be true.
327 */
328 KASSERT(bp != NULL);
329 ep = (struct lfs_direct *)((char *)bp->b_data + entryoffsetinblock);
330 if (ep->d_reclen == 0 ||
331 (lfs_dirchk && ulfs_dirbadentry(vdp, ep, entryoffsetinblock))) {
332 int i;
333
334 ulfs_dirbad(dp, results->ulr_offset, "mangled entry");
335 i = dirblksiz - (entryoffsetinblock & (dirblksiz - 1));
336 results->ulr_offset += i;
337 entryoffsetinblock += i;
338 continue;
339 }
340
341 /*
342 * If an appropriate sized slot has not yet been found,
343 * check to see if one is available. Also accumulate space
344 * in the current block so that we can determine if
345 * compaction is viable.
346 */
347 if (slotstatus != FOUND) {
348 int size = ulfs_rw16(ep->d_reclen, needswap);
349
350 if (ep->d_ino != 0)
351 size -= LFS_DIRSIZ(FSFMT(vdp), ep, needswap);
352 if (size > 0) {
353 if (size >= slotneeded) {
354 slotstatus = FOUND;
355 slotoffset = results->ulr_offset;
356 slotsize = ulfs_rw16(ep->d_reclen,
357 needswap);
358 } else if (slotstatus == NONE) {
359 slotfreespace += size;
360 if (slotoffset == -1)
361 slotoffset = results->ulr_offset;
362 if (slotfreespace >= slotneeded) {
363 slotstatus = COMPACT;
364 slotsize = results->ulr_offset +
365 ulfs_rw16(ep->d_reclen,
366 needswap) -
367 slotoffset;
368 }
369 }
370 }
371 }
372
373 /*
374 * Check for a name match.
375 */
376 if (ep->d_ino) {
377 int namlen;
378
379 #if (BYTE_ORDER == LITTLE_ENDIAN)
380 if (FSFMT(vdp) && needswap == 0)
381 namlen = ep->d_type;
382 else
383 namlen = ep->d_namlen;
384 #else
385 if (FSFMT(vdp) && needswap != 0)
386 namlen = ep->d_type;
387 else
388 namlen = ep->d_namlen;
389 #endif
390 if (namlen == cnp->cn_namelen &&
391 !memcmp(cnp->cn_nameptr, ep->d_name,
392 (unsigned)namlen)) {
393 #ifdef LFS_DIRHASH
394 foundentry:
395 #endif
396 /*
397 * Save directory entry's inode number and
398 * reclen, and release directory buffer.
399 */
400 if (!FSFMT(vdp) && ep->d_type == LFS_DT_WHT) {
401 slotstatus = FOUND;
402 slotoffset = results->ulr_offset;
403 slotsize = ulfs_rw16(ep->d_reclen,
404 needswap);
405 results->ulr_reclen = slotsize;
406 /*
407 * This is used to set
408 * results->ulr_endoff,
409 * which may be used by ulfs_direnter()
410 * as a length to truncate the
411 * directory to. Therefore, it must
412 * point past the end of the last
413 * non-empty directory entry. We don't
414 * know where that is in this case, so
415 * we effectively disable shrinking by
416 * using the existing size of the
417 * directory.
418 *
419 * Note that we wouldn't expect to
420 * shrink the directory while rewriting
421 * an existing entry anyway.
422 */
423 enduseful = endsearch;
424 cnp->cn_flags |= ISWHITEOUT;
425 numdirpasses--;
426 goto notfound;
427 }
428 foundino = ulfs_rw32(ep->d_ino, needswap);
429 results->ulr_reclen =
430 ulfs_rw16(ep->d_reclen, needswap);
431 goto found;
432 }
433 }
434 prevoff = results->ulr_offset;
435 results->ulr_offset += ulfs_rw16(ep->d_reclen, needswap);
436 entryoffsetinblock += ulfs_rw16(ep->d_reclen, needswap);
437 if (ep->d_ino)
438 enduseful = results->ulr_offset;
439 }
440 notfound:
441 /*
442 * If we started in the middle of the directory and failed
443 * to find our target, we must check the beginning as well.
444 */
445 if (numdirpasses == 2) {
446 numdirpasses--;
447 results->ulr_offset = 0;
448 endsearch = results->ulr_diroff;
449 goto searchloop;
450 }
451 if (bp != NULL)
452 brelse(bp, 0);
453 /*
454 * If creating, and at end of pathname and current
455 * directory has not been removed, then can consider
456 * allowing file to be created.
457 */
458 if ((nameiop == CREATE || nameiop == RENAME ||
459 (nameiop == DELETE &&
460 (cnp->cn_flags & DOWHITEOUT) &&
461 (cnp->cn_flags & ISWHITEOUT))) &&
462 (flags & ISLASTCN) && dp->i_nlink != 0) {
463 /*
464 * Access for write is interpreted as allowing
465 * creation of files in the directory.
466 */
467 error = VOP_ACCESS(vdp, VWRITE, cred);
468 if (error)
469 goto out;
470 /*
471 * Return an indication of where the new directory
472 * entry should be put. If we didn't find a slot,
473 * then set results->ulr_count to 0 indicating
474 * that the new slot belongs at the end of the
475 * directory. If we found a slot, then the new entry
476 * can be put in the range from results->ulr_offset to
477 * results->ulr_offset + results->ulr_count.
478 */
479 if (slotstatus == NONE) {
480 results->ulr_offset = roundup(dp->i_size, dirblksiz);
481 results->ulr_count = 0;
482 enduseful = results->ulr_offset;
483 } else if (nameiop == DELETE) {
484 results->ulr_offset = slotoffset;
485 if ((results->ulr_offset & (dirblksiz - 1)) == 0)
486 results->ulr_count = 0;
487 else
488 results->ulr_count =
489 results->ulr_offset - prevoff;
490 } else {
491 results->ulr_offset = slotoffset;
492 results->ulr_count = slotsize;
493 if (enduseful < slotoffset + slotsize)
494 enduseful = slotoffset + slotsize;
495 }
496 results->ulr_endoff = roundup(enduseful, dirblksiz);
497 #if 0 /* commented out by dbj. none of the on disk fields changed */
498 dp->i_flag |= IN_CHANGE | IN_UPDATE;
499 #endif
500 /*
501 * We return with the directory locked, so that
502 * the parameters we set up above will still be
503 * valid if we actually decide to do a direnter().
504 * We return ni_vp == NULL to indicate that the entry
505 * does not currently exist; we leave a pointer to
506 * the (locked) directory inode in ndp->ni_dvp.
507 *
508 * NB - if the directory is unlocked, then this
509 * information cannot be used.
510 */
511 error = EJUSTRETURN;
512 goto out;
513 }
514 /*
515 * Insert name into cache (as non-existent) if appropriate.
516 */
517 if (nameiop != CREATE) {
518 cache_enter(vdp, *vpp, cnp->cn_nameptr, cnp->cn_namelen,
519 cnp->cn_flags);
520 }
521 error = ENOENT;
522 goto out;
523
524 found:
525 if (numdirpasses == 2)
526 nchstats.ncs_pass2++;
527 /*
528 * Check that directory length properly reflects presence
529 * of this entry.
530 */
531 if (results->ulr_offset + LFS_DIRSIZ(FSFMT(vdp), ep, needswap) > dp->i_size) {
532 ulfs_dirbad(dp, results->ulr_offset, "i_size too small");
533 dp->i_size =
534 results->ulr_offset + LFS_DIRSIZ(FSFMT(vdp), ep, needswap);
535 DIP_ASSIGN(dp, size, dp->i_size);
536 dp->i_flag |= IN_CHANGE | IN_UPDATE;
537 }
538 brelse(bp, 0);
539
540 /*
541 * Found component in pathname.
542 * If the final component of path name, save information
543 * in the cache as to where the entry was found.
544 */
545 if ((flags & ISLASTCN) && nameiop == LOOKUP)
546 results->ulr_diroff = results->ulr_offset &~ (dirblksiz - 1);
547
548 /*
549 * If deleting, and at end of pathname, return
550 * parameters which can be used to remove file.
551 * Lock the inode, being careful with ".".
552 */
553 if (nameiop == DELETE && (flags & ISLASTCN)) {
554 /*
555 * Return pointer to current entry in results->ulr_offset,
556 * and distance past previous entry (if there
557 * is a previous entry in this block) in results->ulr_count.
558 * Save directory inode pointer in ndp->ni_dvp for dirremove().
559 */
560 if ((results->ulr_offset & (dirblksiz - 1)) == 0)
561 results->ulr_count = 0;
562 else
563 results->ulr_count = results->ulr_offset - prevoff;
564 if (dp->i_number == foundino) {
565 vref(vdp);
566 tdp = vdp;
567 } else {
568 if (flags & ISDOTDOT)
569 VOP_UNLOCK(vdp); /* race to get the inode */
570 error = VFS_VGET(vdp->v_mount, foundino, &tdp);
571 if (flags & ISDOTDOT)
572 vn_lock(vdp, LK_EXCLUSIVE | LK_RETRY);
573 if (error)
574 goto out;
575 }
576 /*
577 * Write access to directory required to delete files.
578 */
579 error = VOP_ACCESS(vdp, VWRITE, cred);
580 if (error) {
581 if (dp->i_number == foundino)
582 vrele(tdp);
583 else
584 vput(tdp);
585 goto out;
586 }
587 /*
588 * If directory is "sticky", then user must own
589 * the directory, or the file in it, else she
590 * may not delete it (unless she's root). This
591 * implements append-only directories.
592 */
593 if (dp->i_mode & ISVTX) {
594 error = kauth_authorize_vnode(cred, KAUTH_VNODE_DELETE,
595 tdp, vdp, genfs_can_sticky(cred, dp->i_uid,
596 VTOI(tdp)->i_uid));
597 if (error) {
598 if (dp->i_number == foundino)
599 vrele(tdp);
600 else
601 vput(tdp);
602 error = EPERM;
603 goto out;
604 }
605 }
606 *vpp = tdp;
607 error = 0;
608 goto out;
609 }
610
611 /*
612 * If rewriting (RENAME), return the inode and the
613 * information required to rewrite the present directory
614 * Must get inode of directory entry to verify it's a
615 * regular file, or empty directory.
616 */
617 if (nameiop == RENAME && (flags & ISLASTCN)) {
618 error = VOP_ACCESS(vdp, VWRITE, cred);
619 if (error)
620 goto out;
621 /*
622 * Careful about locking second inode.
623 * This can only occur if the target is ".".
624 */
625 if (dp->i_number == foundino) {
626 error = EISDIR;
627 goto out;
628 }
629 if (flags & ISDOTDOT)
630 VOP_UNLOCK(vdp); /* race to get the inode */
631 error = VFS_VGET(vdp->v_mount, foundino, &tdp);
632 if (flags & ISDOTDOT)
633 vn_lock(vdp, LK_EXCLUSIVE | LK_RETRY);
634 if (error)
635 goto out;
636 *vpp = tdp;
637 error = 0;
638 goto out;
639 }
640
641 /*
642 * Step through the translation in the name. We do not `vput' the
643 * directory because we may need it again if a symbolic link
644 * is relative to the current directory. Instead we save it
645 * unlocked as "pdp". We must get the target inode before unlocking
646 * the directory to insure that the inode will not be removed
647 * before we get it. We prevent deadlock by always fetching
648 * inodes from the root, moving down the directory tree. Thus
649 * when following backward pointers ".." we must unlock the
650 * parent directory before getting the requested directory.
651 * There is a potential race condition here if both the current
652 * and parent directories are removed before the VFS_VGET for the
653 * inode associated with ".." returns. We hope that this occurs
654 * infrequently since we cannot avoid this race condition without
655 * implementing a sophisticated deadlock detection algorithm.
656 * Note also that this simple deadlock detection scheme will not
657 * work if the file system has any hard links other than ".."
658 * that point backwards in the directory structure.
659 */
660 pdp = vdp;
661 if (flags & ISDOTDOT) {
662 VOP_UNLOCK(pdp); /* race to get the inode */
663 error = VFS_VGET(vdp->v_mount, foundino, &tdp);
664 vn_lock(pdp, LK_EXCLUSIVE | LK_RETRY);
665 if (error) {
666 goto out;
667 }
668 *vpp = tdp;
669 } else if (dp->i_number == foundino) {
670 vref(vdp); /* we want ourself, ie "." */
671 *vpp = vdp;
672 } else {
673 error = VFS_VGET(vdp->v_mount, foundino, &tdp);
674 if (error)
675 goto out;
676 *vpp = tdp;
677 }
678
679 /*
680 * Insert name into cache if appropriate.
681 */
682 cache_enter(vdp, *vpp, cnp->cn_nameptr, cnp->cn_namelen, cnp->cn_flags);
683 error = 0;
684
685 out:
686 fstrans_done(vdp->v_mount);
687 return error;
688 }
689
690 void
691 ulfs_dirbad(struct inode *ip, doff_t offset, const char *how)
692 {
693 struct mount *mp;
694
695 mp = ITOV(ip)->v_mount;
696 printf("%s: bad dir ino %llu at offset %d: %s\n",
697 mp->mnt_stat.f_mntonname, (unsigned long long)ip->i_number,
698 offset, how);
699 if ((mp->mnt_stat.f_flag & MNT_RDONLY) == 0)
700 panic("bad dir");
701 }
702
703 /*
704 * Do consistency checking on a directory entry:
705 * record length must be multiple of 4
706 * entry must fit in rest of its DIRBLKSIZ block
707 * record must be large enough to contain entry
708 * name is not longer than LFS_MAXNAMLEN
709 * name must be as long as advertised, and null terminated
710 */
711 int
712 ulfs_dirbadentry(struct vnode *dp, struct lfs_direct *ep, int entryoffsetinblock)
713 {
714 int i;
715 int namlen;
716 struct ulfsmount *ump = VFSTOULFS(dp->v_mount);
717 const int needswap = ULFS_MPNEEDSWAP(ump);
718 int dirblksiz = ump->um_dirblksiz;
719
720 #if (BYTE_ORDER == LITTLE_ENDIAN)
721 if (FSFMT(dp) && needswap == 0)
722 namlen = ep->d_type;
723 else
724 namlen = ep->d_namlen;
725 #else
726 if (FSFMT(dp) && needswap != 0)
727 namlen = ep->d_type;
728 else
729 namlen = ep->d_namlen;
730 #endif
731 if ((ulfs_rw16(ep->d_reclen, needswap) & 0x3) != 0 ||
732 ulfs_rw16(ep->d_reclen, needswap) >
733 dirblksiz - (entryoffsetinblock & (dirblksiz - 1)) ||
734 ulfs_rw16(ep->d_reclen, needswap) <
735 LFS_DIRSIZ(FSFMT(dp), ep, needswap) ||
736 namlen > LFS_MAXNAMLEN) {
737 /*return (1); */
738 printf("First bad, reclen=%#x, DIRSIZ=%lu, namlen=%d, "
739 "flags=%#x, entryoffsetinblock=%d, dirblksiz = %d\n",
740 ulfs_rw16(ep->d_reclen, needswap),
741 (u_long)LFS_DIRSIZ(FSFMT(dp), ep, needswap),
742 namlen, dp->v_mount->mnt_flag, entryoffsetinblock,
743 dirblksiz);
744 goto bad;
745 }
746 if (ep->d_ino == 0)
747 return (0);
748 for (i = 0; i < namlen; i++)
749 if (ep->d_name[i] == '\0') {
750 /*return (1); */
751 printf("Second bad\n");
752 goto bad;
753 }
754 if (ep->d_name[i])
755 goto bad;
756 return (0);
757 bad:
758 return (1);
759 }
760
761 /*
762 * Construct a new directory entry after a call to namei, using the
763 * name in the componentname argument cnp. The argument ip is the
764 * inode to which the new directory entry will refer.
765 */
766 void
767 ulfs_makedirentry(struct inode *ip, struct componentname *cnp,
768 struct lfs_direct *newdirp)
769 {
770 newdirp->d_ino = ip->i_number;
771 newdirp->d_namlen = cnp->cn_namelen;
772 memcpy(newdirp->d_name, cnp->cn_nameptr, (size_t)cnp->cn_namelen);
773 newdirp->d_name[cnp->cn_namelen] = '\0';
774 if (FSFMT(ITOV(ip)))
775 newdirp->d_type = 0;
776 else
777 newdirp->d_type = LFS_IFTODT(ip->i_mode);
778 }
779
780 /*
781 * Write a directory entry after a call to namei, using the parameters
782 * that ulfs_lookup left in nameidata and in the ulfs_lookup_results.
783 *
784 * DVP is the directory to be updated. It must be locked.
785 * ULR is the ulfs_lookup_results structure from the final lookup step.
786 * TVP is not used. (XXX: why is it here? remove it)
787 * DIRP is the new directory entry contents.
788 * CNP is the componentname from the final lookup step.
789 * NEWDIRBP is not used and (XXX) should be removed. The previous
790 * comment here said it was used by the now-removed softupdates code.
791 *
792 * The link count of the target inode is *not* incremented; the
793 * caller does that.
794 *
795 * If ulr->ulr_count is 0, ulfs_lookup did not find space to insert the
796 * directory entry. ulr_offset, which is the place to put the entry,
797 * should be on a block boundary (and should be at the end of the
798 * directory AFAIK) and a fresh block is allocated to put the new
799 * directory entry in.
800 *
801 * If ulr->ulr_count is not zero, ulfs_lookup found a slot to insert
802 * the entry into. This slot ranges from ulr_offset to ulr_offset +
803 * ulr_count. However, this slot may already be partially populated
804 * requiring compaction. See notes below.
805 *
806 * Furthermore, if ulr_count is not zero and ulr_endoff is not the
807 * same as i_size, the directory is truncated to size ulr_endoff.
808 */
809 int
810 ulfs_direnter(struct vnode *dvp, const struct ulfs_lookup_results *ulr,
811 struct vnode *tvp, struct lfs_direct *dirp,
812 struct componentname *cnp, struct buf *newdirbp)
813 {
814 kauth_cred_t cr;
815 struct lwp *l;
816 int newentrysize;
817 struct inode *dp;
818 struct buf *bp;
819 u_int dsize;
820 struct lfs_direct *ep, *nep;
821 int error, ret, blkoff, loc, spacefree;
822 char *dirbuf;
823 struct timespec ts;
824 struct ulfsmount *ump = VFSTOULFS(dvp->v_mount);
825 const int needswap = ULFS_MPNEEDSWAP(ump);
826 int dirblksiz = ump->um_dirblksiz;
827
828 error = 0;
829 cr = cnp->cn_cred;
830 l = curlwp;
831
832 dp = VTOI(dvp);
833 newentrysize = LFS_DIRSIZ(0, dirp, 0);
834
835 if (ulr->ulr_count == 0) {
836 /*
837 * If ulr_count is 0, then namei could find no
838 * space in the directory. Here, ulr_offset will
839 * be on a directory block boundary and we will write the
840 * new entry into a fresh block.
841 */
842 if (ulr->ulr_offset & (dirblksiz - 1))
843 panic("ulfs_direnter: newblk");
844 if ((error = ULFS_BALLOC(dvp, (off_t)ulr->ulr_offset, dirblksiz,
845 cr, B_CLRBUF | B_SYNC, &bp)) != 0) {
846 return (error);
847 }
848 dp->i_size = ulr->ulr_offset + dirblksiz;
849 DIP_ASSIGN(dp, size, dp->i_size);
850 dp->i_flag |= IN_CHANGE | IN_UPDATE;
851 uvm_vnp_setsize(dvp, dp->i_size);
852 dirp->d_reclen = ulfs_rw16(dirblksiz, needswap);
853 dirp->d_ino = ulfs_rw32(dirp->d_ino, needswap);
854 if (FSFMT(dvp)) {
855 #if (BYTE_ORDER == LITTLE_ENDIAN)
856 if (needswap == 0) {
857 #else
858 if (needswap != 0) {
859 #endif
860 u_char tmp = dirp->d_namlen;
861 dirp->d_namlen = dirp->d_type;
862 dirp->d_type = tmp;
863 }
864 }
865 blkoff = ulr->ulr_offset & (ump->um_mountp->mnt_stat.f_iosize - 1);
866 memcpy((char *)bp->b_data + blkoff, dirp, newentrysize);
867 #ifdef LFS_DIRHASH
868 if (dp->i_dirhash != NULL) {
869 ulfsdirhash_newblk(dp, ulr->ulr_offset);
870 ulfsdirhash_add(dp, dirp, ulr->ulr_offset);
871 ulfsdirhash_checkblock(dp, (char *)bp->b_data + blkoff,
872 ulr->ulr_offset);
873 }
874 #endif
875 error = VOP_BWRITE(bp->b_vp, bp);
876 vfs_timestamp(&ts);
877 ret = ULFS_UPDATE(dvp, &ts, &ts, UPDATE_DIROP);
878 if (error == 0)
879 return (ret);
880 return (error);
881 }
882
883 /*
884 * If ulr_count is non-zero, then namei found space for the new
885 * entry in the range ulr_offset to ulr_offset + ulr_count
886 * in the directory. To use this space, we may have to compact
887 * the entries located there, by copying them together towards the
888 * beginning of the block, leaving the free space in one usable
889 * chunk at the end.
890 */
891
892 /*
893 * Increase size of directory if entry eats into new space.
894 * This should never push the size past a new multiple of
895 * DIRBLKSIZ.
896 *
897 * N.B. - THIS IS AN ARTIFACT OF 4.2 AND SHOULD NEVER HAPPEN.
898 */
899 if (ulr->ulr_offset + ulr->ulr_count > dp->i_size) {
900 #ifdef DIAGNOSTIC
901 printf("ulfs_direnter: reached 4.2-only block, "
902 "not supposed to happen\n");
903 #endif
904 dp->i_size = ulr->ulr_offset + ulr->ulr_count;
905 DIP_ASSIGN(dp, size, dp->i_size);
906 dp->i_flag |= IN_CHANGE | IN_UPDATE;
907 }
908 /*
909 * Get the block containing the space for the new directory entry.
910 */
911 error = ulfs_blkatoff(dvp, (off_t)ulr->ulr_offset, &dirbuf, &bp, true);
912 if (error) {
913 return (error);
914 }
915 /*
916 * Find space for the new entry. In the simple case, the entry at
917 * offset base will have the space. If it does not, then namei
918 * arranged that compacting the region ulr_offset to
919 * ulr_offset + ulr_count would yield the space.
920 */
921 ep = (struct lfs_direct *)dirbuf;
922 dsize = (ep->d_ino != 0) ? LFS_DIRSIZ(FSFMT(dvp), ep, needswap) : 0;
923 spacefree = ulfs_rw16(ep->d_reclen, needswap) - dsize;
924 for (loc = ulfs_rw16(ep->d_reclen, needswap); loc < ulr->ulr_count; ) {
925 uint16_t reclen;
926
927 nep = (struct lfs_direct *)(dirbuf + loc);
928
929 /* Trim the existing slot (NB: dsize may be zero). */
930 ep->d_reclen = ulfs_rw16(dsize, needswap);
931 ep = (struct lfs_direct *)((char *)ep + dsize);
932
933 reclen = ulfs_rw16(nep->d_reclen, needswap);
934 loc += reclen;
935 if (nep->d_ino == 0) {
936 /*
937 * A mid-block unused entry. Such entries are
938 * never created by the kernel, but fsck_ffs
939 * can create them (and it doesn't fix them).
940 *
941 * Add up the free space, and initialise the
942 * relocated entry since we don't memcpy it.
943 */
944 spacefree += reclen;
945 ep->d_ino = 0;
946 dsize = 0;
947 continue;
948 }
949 dsize = LFS_DIRSIZ(FSFMT(dvp), nep, needswap);
950 spacefree += reclen - dsize;
951 #ifdef LFS_DIRHASH
952 if (dp->i_dirhash != NULL)
953 ulfsdirhash_move(dp, nep,
954 ulr->ulr_offset + ((char *)nep - dirbuf),
955 ulr->ulr_offset + ((char *)ep - dirbuf));
956 #endif
957 memcpy((void *)ep, (void *)nep, dsize);
958 }
959 /*
960 * Here, `ep' points to a directory entry containing `dsize' in-use
961 * bytes followed by `spacefree' unused bytes. If ep->d_ino == 0,
962 * then the entry is completely unused (dsize == 0). The value
963 * of ep->d_reclen is always indeterminate.
964 *
965 * Update the pointer fields in the previous entry (if any),
966 * copy in the new entry, and write out the block.
967 */
968 if (ep->d_ino == 0 ||
969 (ulfs_rw32(ep->d_ino, needswap) == ULFS_WINO &&
970 memcmp(ep->d_name, dirp->d_name, dirp->d_namlen) == 0)) {
971 if (spacefree + dsize < newentrysize)
972 panic("ulfs_direnter: compact1");
973 dirp->d_reclen = spacefree + dsize;
974 } else {
975 if (spacefree < newentrysize)
976 panic("ulfs_direnter: compact2");
977 dirp->d_reclen = spacefree;
978 ep->d_reclen = ulfs_rw16(dsize, needswap);
979 ep = (struct lfs_direct *)((char *)ep + dsize);
980 }
981 dirp->d_reclen = ulfs_rw16(dirp->d_reclen, needswap);
982 dirp->d_ino = ulfs_rw32(dirp->d_ino, needswap);
983 if (FSFMT(dvp)) {
984 #if (BYTE_ORDER == LITTLE_ENDIAN)
985 if (needswap == 0) {
986 #else
987 if (needswap != 0) {
988 #endif
989 u_char tmp = dirp->d_namlen;
990 dirp->d_namlen = dirp->d_type;
991 dirp->d_type = tmp;
992 }
993 }
994 #ifdef LFS_DIRHASH
995 if (dp->i_dirhash != NULL && (ep->d_ino == 0 ||
996 dirp->d_reclen == spacefree))
997 ulfsdirhash_add(dp, dirp, ulr->ulr_offset + ((char *)ep - dirbuf));
998 #endif
999 memcpy((void *)ep, (void *)dirp, (u_int)newentrysize);
1000 #ifdef LFS_DIRHASH
1001 if (dp->i_dirhash != NULL)
1002 ulfsdirhash_checkblock(dp, dirbuf -
1003 (ulr->ulr_offset & (dirblksiz - 1)),
1004 ulr->ulr_offset & ~(dirblksiz - 1));
1005 #endif
1006 error = VOP_BWRITE(bp->b_vp, bp);
1007 dp->i_flag |= IN_CHANGE | IN_UPDATE;
1008 /*
1009 * If all went well, and the directory can be shortened, proceed
1010 * with the truncation. Note that we have to unlock the inode for
1011 * the entry that we just entered, as the truncation may need to
1012 * lock other inodes which can lead to deadlock if we also hold a
1013 * lock on the newly entered node.
1014 */
1015 if (error == 0 && ulr->ulr_endoff && ulr->ulr_endoff < dp->i_size) {
1016 #ifdef LFS_DIRHASH
1017 if (dp->i_dirhash != NULL)
1018 ulfsdirhash_dirtrunc(dp, ulr->ulr_endoff);
1019 #endif
1020 (void) ULFS_TRUNCATE(dvp, (off_t)ulr->ulr_endoff, IO_SYNC, cr);
1021 }
1022 return (error);
1023 }
1024
1025 /*
1026 * Remove a directory entry after a call to namei, using the
1027 * parameters that ulfs_lookup left in nameidata and in the
1028 * ulfs_lookup_results.
1029 *
1030 * DVP is the directory to be updated. It must be locked.
1031 * ULR is the ulfs_lookup_results structure from the final lookup step.
1032 * IP, if not null, is the inode being unlinked.
1033 * FLAGS may contain DOWHITEOUT.
1034 * ISRMDIR is not used and (XXX) should be removed.
1035 *
1036 * If FLAGS contains DOWHITEOUT the entry is replaced with a whiteout
1037 * instead of being cleared.
1038 *
1039 * ulr->ulr_offset contains the position of the directory entry
1040 * to be removed.
1041 *
1042 * ulr->ulr_reclen contains the size of the directory entry to be
1043 * removed.
1044 *
1045 * ulr->ulr_count contains the size of the *previous* directory
1046 * entry. This allows finding it, for free space management. If
1047 * ulr_count is 0, the target entry is at the beginning of the
1048 * directory. (Does this ever happen? The first entry should be ".",
1049 * which should only be removed at rmdir time. Does rmdir come here
1050 * to clear out the "." and ".." entries? Perhaps, but I doubt it.)
1051 *
1052 * The space is marked free by adding it to the record length (not
1053 * name length) of the preceding entry. If the first entry becomes
1054 * free, it is marked free by setting the inode number to 0.
1055 *
1056 * The link count of IP is decremented. Note that this is not the
1057 * inverse behavior of ulfs_direnter, which does not adjust link
1058 * counts. Sigh.
1059 */
1060 int
1061 ulfs_dirremove(struct vnode *dvp, const struct ulfs_lookup_results *ulr,
1062 struct inode *ip, int flags, int isrmdir)
1063 {
1064 struct inode *dp = VTOI(dvp);
1065 struct lfs_direct *ep;
1066 struct buf *bp;
1067 int error;
1068 #ifdef LFS_EI
1069 const int needswap = ULFS_MPNEEDSWAP(dp->i_ump);
1070 #endif
1071
1072 if (flags & DOWHITEOUT) {
1073 /*
1074 * Whiteout entry: set d_ino to ULFS_WINO.
1075 */
1076 error = ulfs_blkatoff(dvp, (off_t)ulr->ulr_offset, (void *)&ep,
1077 &bp, true);
1078 if (error)
1079 return (error);
1080 ep->d_ino = ulfs_rw32(ULFS_WINO, needswap);
1081 ep->d_type = LFS_DT_WHT;
1082 goto out;
1083 }
1084
1085 if ((error = ulfs_blkatoff(dvp,
1086 (off_t)(ulr->ulr_offset - ulr->ulr_count), (void *)&ep, &bp, true)) != 0)
1087 return (error);
1088
1089 #ifdef LFS_DIRHASH
1090 /*
1091 * Remove the dirhash entry. This is complicated by the fact
1092 * that `ep' is the previous entry when ulr_count != 0.
1093 */
1094 if (dp->i_dirhash != NULL)
1095 ulfsdirhash_remove(dp, (ulr->ulr_count == 0) ? ep :
1096 (struct lfs_direct *)((char *)ep +
1097 ulfs_rw16(ep->d_reclen, needswap)), ulr->ulr_offset);
1098 #endif
1099
1100 if (ulr->ulr_count == 0) {
1101 /*
1102 * First entry in block: set d_ino to zero.
1103 */
1104 ep->d_ino = 0;
1105 } else {
1106 /*
1107 * Collapse new free space into previous entry.
1108 */
1109 ep->d_reclen =
1110 ulfs_rw16(ulfs_rw16(ep->d_reclen, needswap) + ulr->ulr_reclen,
1111 needswap);
1112 }
1113
1114 #ifdef LFS_DIRHASH
1115 if (dp->i_dirhash != NULL) {
1116 int dirblksiz = ip->i_ump->um_dirblksiz;
1117 ulfsdirhash_checkblock(dp, (char *)ep -
1118 ((ulr->ulr_offset - ulr->ulr_count) & (dirblksiz - 1)),
1119 ulr->ulr_offset & ~(dirblksiz - 1));
1120 }
1121 #endif
1122
1123 out:
1124 if (ip) {
1125 ip->i_nlink--;
1126 DIP_ASSIGN(ip, nlink, ip->i_nlink);
1127 ip->i_flag |= IN_CHANGE;
1128 }
1129 /*
1130 * XXX did it ever occur to anyone that it might be a good
1131 * idea to restore ip->i_nlink if this fails? Or something?
1132 * Currently on error return from this function the state of
1133 * ip->i_nlink depends on what happened, and callers
1134 * definitely do not take this into account.
1135 */
1136 error = VOP_BWRITE(bp->b_vp, bp);
1137 dp->i_flag |= IN_CHANGE | IN_UPDATE;
1138 /*
1139 * If the last named reference to a snapshot goes away,
1140 * drop its snapshot reference so that it will be reclaimed
1141 * when last open reference goes away.
1142 */
1143 if (ip != 0 && (ip->i_flags & SF_SNAPSHOT) != 0 &&
1144 ip->i_nlink == 0)
1145 ulfs_snapgone(ip);
1146 return (error);
1147 }
1148
1149 /*
1150 * Rewrite an existing directory entry to point at the inode supplied.
1151 *
1152 * DP is the directory to update.
1153 * OFFSET is the position of the entry in question. It may come
1154 * from ulr_offset of a ulfs_lookup_results.
1155 * OIP is the old inode the directory previously pointed to.
1156 * NEWINUM is the number of the new inode.
1157 * NEWTYPE is the new value for the type field of the directory entry.
1158 * (This is ignored if the fs doesn't support that.)
1159 * ISRMDIR is not used and (XXX) should be removed.
1160 * IFLAGS are added to DP's inode flags.
1161 *
1162 * The link count of OIP is decremented. Note that the link count of
1163 * the new inode is *not* incremented. Yay for symmetry.
1164 */
1165 int
1166 ulfs_dirrewrite(struct inode *dp, off_t offset,
1167 struct inode *oip, ino_t newinum, int newtype,
1168 int isrmdir, int iflags)
1169 {
1170 struct buf *bp;
1171 struct lfs_direct *ep;
1172 struct vnode *vdp = ITOV(dp);
1173 int error;
1174
1175 error = ulfs_blkatoff(vdp, offset, (void *)&ep, &bp, true);
1176 if (error)
1177 return (error);
1178 ep->d_ino = ulfs_rw32(newinum, ULFS_MPNEEDSWAP(dp->i_ump));
1179 if (!FSFMT(vdp))
1180 ep->d_type = newtype;
1181 oip->i_nlink--;
1182 DIP_ASSIGN(oip, nlink, oip->i_nlink);
1183 oip->i_flag |= IN_CHANGE;
1184 error = VOP_BWRITE(bp->b_vp, bp);
1185 dp->i_flag |= iflags;
1186 /*
1187 * If the last named reference to a snapshot goes away,
1188 * drop its snapshot reference so that it will be reclaimed
1189 * when last open reference goes away.
1190 */
1191 if ((oip->i_flags & SF_SNAPSHOT) != 0 && oip->i_nlink == 0)
1192 ulfs_snapgone(oip);
1193 return (error);
1194 }
1195
1196 /*
1197 * Check if a directory is empty or not.
1198 * Inode supplied must be locked.
1199 *
1200 * Using a struct lfs_dirtemplate here is not precisely
1201 * what we want, but better than using a struct lfs_direct.
1202 *
1203 * NB: does not handle corrupted directories.
1204 */
1205 int
1206 ulfs_dirempty(struct inode *ip, ino_t parentino, kauth_cred_t cred)
1207 {
1208 doff_t off;
1209 struct lfs_dirtemplate dbuf;
1210 struct lfs_direct *dp = (struct lfs_direct *)&dbuf;
1211 int error, namlen;
1212 size_t count;
1213 const int needswap = ULFS_IPNEEDSWAP(ip);
1214 #define MINDIRSIZ (sizeof (struct lfs_dirtemplate) / 2)
1215
1216 for (off = 0; off < ip->i_size;
1217 off += ulfs_rw16(dp->d_reclen, needswap)) {
1218 error = vn_rdwr(UIO_READ, ITOV(ip), (void *)dp, MINDIRSIZ, off,
1219 UIO_SYSSPACE, IO_NODELOCKED, cred, &count, NULL);
1220 /*
1221 * Since we read MINDIRSIZ, residual must
1222 * be 0 unless we're at end of file.
1223 */
1224 if (error || count != 0)
1225 return (0);
1226 /* avoid infinite loops */
1227 if (dp->d_reclen == 0)
1228 return (0);
1229 /* skip empty entries */
1230 if (dp->d_ino == 0 || ulfs_rw32(dp->d_ino, needswap) == ULFS_WINO)
1231 continue;
1232 /* accept only "." and ".." */
1233 #if (BYTE_ORDER == LITTLE_ENDIAN)
1234 if (FSFMT(ITOV(ip)) && needswap == 0)
1235 namlen = dp->d_type;
1236 else
1237 namlen = dp->d_namlen;
1238 #else
1239 if (FSFMT(ITOV(ip)) && needswap != 0)
1240 namlen = dp->d_type;
1241 else
1242 namlen = dp->d_namlen;
1243 #endif
1244 if (namlen > 2)
1245 return (0);
1246 if (dp->d_name[0] != '.')
1247 return (0);
1248 /*
1249 * At this point namlen must be 1 or 2.
1250 * 1 implies ".", 2 implies ".." if second
1251 * char is also "."
1252 */
1253 if (namlen == 1 &&
1254 ulfs_rw32(dp->d_ino, needswap) == ip->i_number)
1255 continue;
1256 if (dp->d_name[1] == '.' &&
1257 ulfs_rw32(dp->d_ino, needswap) == parentino)
1258 continue;
1259 return (0);
1260 }
1261 return (1);
1262 }
1263
1264 /*
1265 * Check if source directory is in the path of the target directory.
1266 * Target is supplied locked, source is unlocked.
1267 * The target is always vput before returning.
1268 */
1269 int
1270 ulfs_checkpath(struct inode *source, struct inode *target, kauth_cred_t cred)
1271 {
1272 struct vnode *nextvp, *vp;
1273 int error, rootino, namlen;
1274 struct lfs_dirtemplate dirbuf;
1275 const int needswap = ULFS_MPNEEDSWAP(target->i_ump);
1276
1277 vp = ITOV(target);
1278 if (target->i_number == source->i_number) {
1279 error = EEXIST;
1280 goto out;
1281 }
1282 rootino = ULFS_ROOTINO;
1283 error = 0;
1284 if (target->i_number == rootino)
1285 goto out;
1286
1287 for (;;) {
1288 if (vp->v_type != VDIR) {
1289 error = ENOTDIR;
1290 break;
1291 }
1292 error = vn_rdwr(UIO_READ, vp, (void *)&dirbuf,
1293 sizeof (struct lfs_dirtemplate), (off_t)0, UIO_SYSSPACE,
1294 IO_NODELOCKED, cred, NULL, NULL);
1295 if (error != 0)
1296 break;
1297 #if (BYTE_ORDER == LITTLE_ENDIAN)
1298 if (FSFMT(vp) && needswap == 0)
1299 namlen = dirbuf.dotdot_type;
1300 else
1301 namlen = dirbuf.dotdot_namlen;
1302 #else
1303 if (FSFMT(vp) && needswap != 0)
1304 namlen = dirbuf.dotdot_type;
1305 else
1306 namlen = dirbuf.dotdot_namlen;
1307 #endif
1308 if (namlen != 2 ||
1309 dirbuf.dotdot_name[0] != '.' ||
1310 dirbuf.dotdot_name[1] != '.') {
1311 error = ENOTDIR;
1312 break;
1313 }
1314 if (ulfs_rw32(dirbuf.dotdot_ino, needswap) == source->i_number) {
1315 error = EINVAL;
1316 break;
1317 }
1318 if (ulfs_rw32(dirbuf.dotdot_ino, needswap) == rootino)
1319 break;
1320 VOP_UNLOCK(vp);
1321 error = VFS_VGET(vp->v_mount,
1322 ulfs_rw32(dirbuf.dotdot_ino, needswap), &nextvp);
1323 vrele(vp);
1324 if (error) {
1325 vp = NULL;
1326 break;
1327 }
1328 vp = nextvp;
1329 }
1330
1331 out:
1332 if (error == ENOTDIR)
1333 printf("checkpath: .. not a directory\n");
1334 if (vp != NULL)
1335 vput(vp);
1336 return (error);
1337 }
1338
1339 /*
1340 * Extract the inode number of ".." from a directory.
1341 * Helper for ulfs_parentcheck.
1342 */
1343 static int
1344 ulfs_readdotdot(struct vnode *vp, int needswap, kauth_cred_t cred, ino_t *result)
1345 {
1346 struct lfs_dirtemplate dirbuf;
1347 int namlen, error;
1348
1349 error = vn_rdwr(UIO_READ, vp, &dirbuf,
1350 sizeof (struct lfs_dirtemplate), (off_t)0, UIO_SYSSPACE,
1351 IO_NODELOCKED, cred, NULL, NULL);
1352 if (error) {
1353 return error;
1354 }
1355
1356 #if (BYTE_ORDER == LITTLE_ENDIAN)
1357 if (FSFMT(vp) && needswap == 0)
1358 namlen = dirbuf.dotdot_type;
1359 else
1360 namlen = dirbuf.dotdot_namlen;
1361 #else
1362 if (FSFMT(vp) && needswap != 0)
1363 namlen = dirbuf.dotdot_type;
1364 else
1365 namlen = dirbuf.dotdot_namlen;
1366 #endif
1367 if (namlen != 2 ||
1368 dirbuf.dotdot_name[0] != '.' ||
1369 dirbuf.dotdot_name[1] != '.') {
1370 printf("ulfs_readdotdot: directory %llu contains "
1371 "garbage instead of ..\n",
1372 (unsigned long long) VTOI(vp)->i_number);
1373 return ENOTDIR;
1374 }
1375 *result = ulfs_rw32(dirbuf.dotdot_ino, needswap);
1376 return 0;
1377 }
1378
1379 /*
1380 * Check if LOWER is a descendent of UPPER. If we find UPPER, return
1381 * nonzero in FOUND and return a reference to the immediate descendent
1382 * of UPPER in UPPERCHILD. If we don't find UPPER (that is, if we
1383 * reach the volume root and that isn't UPPER), return zero in FOUND
1384 * and null in UPPERCHILD.
1385 *
1386 * Neither UPPER nor LOWER should be locked.
1387 *
1388 * On error (such as a permissions error checking up the directory
1389 * tree) fail entirely.
1390 *
1391 * Note that UPPER and LOWER must be on the same volume, and because
1392 * we inspect only that volume NEEDSWAP can be constant.
1393 */
1394 int
1395 ulfs_parentcheck(struct vnode *upper, struct vnode *lower, kauth_cred_t cred,
1396 int *found_ret, struct vnode **upperchild_ret)
1397 {
1398 const int needswap = ULFS_MPNEEDSWAP(VTOI(lower)->i_ump);
1399 ino_t upper_ino, found_ino;
1400 struct vnode *current, *next;
1401 int error;
1402
1403 if (upper == lower) {
1404 vref(upper);
1405 *found_ret = 1;
1406 *upperchild_ret = upper;
1407 return 0;
1408 }
1409 if (VTOI(lower)->i_number == ULFS_ROOTINO) {
1410 *found_ret = 0;
1411 *upperchild_ret = NULL;
1412 return 0;
1413 }
1414
1415 upper_ino = VTOI(upper)->i_number;
1416
1417 current = lower;
1418 vref(current);
1419 vn_lock(current, LK_EXCLUSIVE | LK_RETRY);
1420
1421 for (;;) {
1422 error = ulfs_readdotdot(current, needswap, cred, &found_ino);
1423 if (error) {
1424 vput(current);
1425 return error;
1426 }
1427 if (found_ino == upper_ino) {
1428 VOP_UNLOCK(current);
1429 *found_ret = 1;
1430 *upperchild_ret = current;
1431 return 0;
1432 }
1433 if (found_ino == ULFS_ROOTINO) {
1434 vput(current);
1435 *found_ret = 0;
1436 *upperchild_ret = NULL;
1437 return 0;
1438 }
1439 VOP_UNLOCK(current);
1440 error = VFS_VGET(current->v_mount, found_ino, &next);
1441 if (error) {
1442 vrele(current);
1443 return error;
1444 }
1445 KASSERT(VOP_ISLOCKED(next));
1446 if (next->v_type != VDIR) {
1447 printf("ulfs_parentcheck: inode %llu reached via .. of "
1448 "inode %llu is not a directory\n",
1449 (unsigned long long)VTOI(next)->i_number,
1450 (unsigned long long)VTOI(current)->i_number);
1451 vput(next);
1452 vrele(current);
1453 return ENOTDIR;
1454 }
1455 vrele(current);
1456 current = next;
1457 }
1458
1459 return 0;
1460 }
1461
1462 #define ULFS_DIRRABLKS 0
1463 int ulfs_dirrablks = ULFS_DIRRABLKS;
1464
1465 /*
1466 * ulfs_blkatoff: Return buffer with the contents of block "offset" from
1467 * the beginning of directory "vp". If "res" is non-NULL, fill it in with
1468 * a pointer to the remaining space in the directory. If the caller intends
1469 * to modify the buffer returned, "modify" must be true.
1470 */
1471
1472 int
1473 ulfs_blkatoff(struct vnode *vp, off_t offset, char **res, struct buf **bpp,
1474 bool modify)
1475 {
1476 struct inode *ip;
1477 struct buf *bp;
1478 daddr_t lbn;
1479 const int dirrablks = ulfs_dirrablks;
1480 daddr_t *blks;
1481 int *blksizes;
1482 int run, error;
1483 struct mount *mp = vp->v_mount;
1484 const int bshift = mp->mnt_fs_bshift;
1485 const int bsize = 1 << bshift;
1486 off_t eof;
1487
1488 blks = kmem_alloc((1 + dirrablks) * sizeof(daddr_t), KM_SLEEP);
1489 blksizes = kmem_alloc((1 + dirrablks) * sizeof(int), KM_SLEEP);
1490 ip = VTOI(vp);
1491 KASSERT(vp->v_size == ip->i_size);
1492 GOP_SIZE(vp, vp->v_size, &eof, 0);
1493 lbn = offset >> bshift;
1494
1495 for (run = 0; run <= dirrablks;) {
1496 const off_t curoff = lbn << bshift;
1497 const int size = MIN(eof - curoff, bsize);
1498
1499 if (size == 0) {
1500 break;
1501 }
1502 KASSERT(curoff < eof);
1503 blks[run] = lbn;
1504 blksizes[run] = size;
1505 lbn++;
1506 run++;
1507 if (size != bsize) {
1508 break;
1509 }
1510 }
1511 KASSERT(run >= 1);
1512 error = breadn(vp, blks[0], blksizes[0], &blks[1], &blksizes[1],
1513 run - 1, NOCRED, (modify ? B_MODIFY : 0), &bp);
1514 if (error != 0) {
1515 *bpp = NULL;
1516 goto out;
1517 }
1518 if (res) {
1519 *res = (char *)bp->b_data + (offset & (bsize - 1));
1520 }
1521 *bpp = bp;
1522
1523 out:
1524 kmem_free(blks, (1 + dirrablks) * sizeof(daddr_t));
1525 kmem_free(blksizes, (1 + dirrablks) * sizeof(int));
1526 return error;
1527 }
1528