xref: /minix3/sys/ufs/ufs/ufs_lookup.c (revision 0a6a1f1d05b60e214de2f05a7310ddd1f0e590e7)
1 /*	$NetBSD: ufs_lookup.c,v 1.135 2015/07/11 11:04:48 mlelstv Exp $	*/
2 
3 /*
4  * Copyright (c) 1989, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  * (c) UNIX System Laboratories, Inc.
7  * All or some portions of this file are derived from material licensed
8  * to the University of California by American Telephone and Telegraph
9  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10  * the permission of UNIX System Laboratories, Inc.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  *	@(#)ufs_lookup.c	8.9 (Berkeley) 8/11/94
37  */
38 
39 #include <sys/cdefs.h>
40 __KERNEL_RCSID(0, "$NetBSD: ufs_lookup.c,v 1.135 2015/07/11 11:04:48 mlelstv Exp $");
41 
42 #ifdef _KERNEL_OPT
43 #include "opt_ffs.h"
44 #endif
45 
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/namei.h>
49 #include <sys/buf.h>
50 #include <sys/file.h>
51 #include <sys/stat.h>
52 #include <sys/mount.h>
53 #include <sys/vnode.h>
54 #include <sys/kernel.h>
55 #include <sys/kauth.h>
56 #include <sys/wapbl.h>
57 #include <sys/fstrans.h>
58 #include <sys/proc.h>
59 #include <sys/kmem.h>
60 
61 #include <ufs/ufs/inode.h>
62 #include <ufs/ufs/dir.h>
63 #ifdef UFS_DIRHASH
64 #include <ufs/ufs/dirhash.h>
65 #endif
66 #include <ufs/ufs/ufsmount.h>
67 #include <ufs/ufs/ufs_extern.h>
68 #include <ufs/ufs/ufs_bswap.h>
69 #include <ufs/ufs/ufs_wapbl.h>
70 
71 #include <miscfs/genfs/genfs.h>
72 
73 #ifdef DIAGNOSTIC
74 int	dirchk = 1;
75 #else
76 int	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 ufs_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
ufs_lookup(void * v)113 ufs_lookup(void *v)
114 {
115 	struct vop_lookup_v2_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 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 *tdp;		/* returned by vcache_get */
141 	doff_t enduseful;		/* pointer past last used dir slot.
142 					   used for directory truncation. */
143 	u_long bmask;			/* block offset mask */
144 	int error;
145 	struct vnode **vpp = ap->a_vpp;
146 	struct componentname *cnp = ap->a_cnp;
147 	kauth_cred_t cred = cnp->cn_cred;
148 	int flags;
149 	int nameiop = cnp->cn_nameiop;
150 	struct ufsmount *ump = dp->i_ump;
151 	const int needswap = UFS_MPNEEDSWAP(ump);
152 	int dirblksiz = ump->um_dirblksiz;
153 	ino_t foundino;
154 	struct ufs_lookup_results *results;
155 	int iswhiteout;			/* temp result from cache_lookup() */
156 
157 	flags = cnp->cn_flags;
158 
159 	bp = NULL;
160 	slotoffset = -1;
161 	*vpp = NULL;
162 	endsearch = 0; /* silence compiler warning */
163 
164 	/*
165 	 * Produce the auxiliary lookup results into i_crap. Increment
166 	 * its serial number so elsewhere we can tell if we're using
167 	 * stale results. This should not be done this way. XXX.
168 	 */
169 	results = &dp->i_crap;
170 	dp->i_crapcounter++;
171 
172 	/*
173 	 * Check accessiblity of directory.
174 	 */
175 	if ((error = VOP_ACCESS(vdp, VEXEC, cred)) != 0)
176 		return (error);
177 
178 	if ((flags & ISLASTCN) && (vdp->v_mount->mnt_flag & MNT_RDONLY) &&
179 	    (nameiop == DELETE || nameiop == RENAME))
180 		return (EROFS);
181 
182 	/*
183 	 * We now have a segment name to search for, and a directory to search.
184 	 *
185 	 * Before tediously performing a linear scan of the directory,
186 	 * check the name cache to see if the directory/name pair
187 	 * we are looking for is known already.
188 	 */
189 	if (cache_lookup(vdp, cnp->cn_nameptr, cnp->cn_namelen,
190 			 cnp->cn_nameiop, cnp->cn_flags, &iswhiteout, vpp)) {
191 		if (iswhiteout) {
192 			cnp->cn_flags |= ISWHITEOUT;
193 		}
194 		return *vpp == NULLVP ? ENOENT : 0;
195 	}
196 	if (iswhiteout) {
197 		/*
198 		 * The namecache set iswhiteout without finding a
199 		 * cache entry. As of this writing (20121014), this
200 		 * can happen if there was a whiteout entry that has
201 		 * been invalidated by the lookup. It is not clear if
202 		 * it is correct to set ISWHITEOUT in this case or
203 		 * not; however, doing so retains the prior behavior,
204 		 * so we'll go with that until some clearer answer
205 		 * appears. XXX
206 		 */
207 		cnp->cn_flags |= ISWHITEOUT;
208 	}
209 
210 	fstrans_start(vdp->v_mount, FSTRANS_SHARED);
211 
212 	/*
213 	 * Suppress search for slots unless creating
214 	 * file and at end of pathname, in which case
215 	 * we watch for a place to put the new file in
216 	 * case it doesn't already exist.
217 	 */
218 	slotstatus = FOUND;
219 	slotfreespace = slotsize = slotneeded = 0;
220 	if ((nameiop == CREATE || nameiop == RENAME) && (flags & ISLASTCN)) {
221 		slotstatus = NONE;
222 		slotneeded = UFS_DIRECTSIZ(cnp->cn_namelen);
223 	}
224 
225 	/*
226 	 * If there is cached information on a previous search of
227 	 * this directory, pick up where we last left off.
228 	 * We cache only lookups as these are the most common
229 	 * and have the greatest payoff. Caching CREATE has little
230 	 * benefit as it usually must search the entire directory
231 	 * to determine that the entry does not exist. Caching the
232 	 * location of the last DELETE or RENAME has not reduced
233 	 * profiling time and hence has been removed in the interest
234 	 * of simplicity.
235 	 */
236 	bmask = vdp->v_mount->mnt_stat.f_iosize - 1;
237 
238 #ifdef UFS_DIRHASH
239 	/*
240 	 * Use dirhash for fast operations on large directories. The logic
241 	 * to determine whether to hash the directory is contained within
242 	 * ufsdirhash_build(); a zero return means that it decided to hash
243 	 * this directory and it successfully built up the hash table.
244 	 */
245 	if (ufsdirhash_build(dp) == 0) {
246 		/* Look for a free slot if needed. */
247 		enduseful = dp->i_size;
248 		if (slotstatus != FOUND) {
249 			slotoffset = ufsdirhash_findfree(dp, slotneeded,
250 			    &slotsize);
251 			if (slotoffset >= 0) {
252 				slotstatus = COMPACT;
253 				enduseful = ufsdirhash_enduseful(dp);
254 				if (enduseful < 0)
255 					enduseful = dp->i_size;
256 			}
257 		}
258 		/* Look up the component. */
259 		numdirpasses = 1;
260 		entryoffsetinblock = 0; /* silence compiler warning */
261 		switch (ufsdirhash_lookup(dp, cnp->cn_nameptr, cnp->cn_namelen,
262 		    &results->ulr_offset, &bp, nameiop == DELETE ? &prevoff : NULL)) {
263 		case 0:
264 			ep = (struct direct *)((char *)bp->b_data +
265 			    (results->ulr_offset & bmask));
266 			goto foundentry;
267 		case ENOENT:
268 			results->ulr_offset = roundup(dp->i_size, dirblksiz);
269 			goto notfound;
270 		default:
271 			/* Something failed; just do a linear search. */
272 			break;
273 		}
274 	}
275 #endif /* UFS_DIRHASH */
276 
277 	if (nameiop != LOOKUP || results->ulr_diroff == 0 ||
278 	    results->ulr_diroff >= dp->i_size) {
279 		entryoffsetinblock = 0;
280 		results->ulr_offset = 0;
281 		numdirpasses = 1;
282 	} else {
283 		results->ulr_offset = results->ulr_diroff;
284 		if ((entryoffsetinblock = results->ulr_offset & bmask) &&
285 		    (error = ufs_blkatoff(vdp, (off_t)results->ulr_offset,
286 		    NULL, &bp, false)))
287 			goto out;
288 		numdirpasses = 2;
289 		namecache_count_2passes();
290 	}
291 	prevoff = results->ulr_offset;
292 	endsearch = roundup(dp->i_size, dirblksiz);
293 	enduseful = 0;
294 
295 searchloop:
296 	while (results->ulr_offset < endsearch) {
297 		if (curcpu()->ci_schedstate.spc_flags & SPCF_SHOULDYIELD)
298 			preempt();
299 		/*
300 		 * If necessary, get the next directory block.
301 		 */
302 		if ((results->ulr_offset & bmask) == 0) {
303 			if (bp != NULL)
304 				brelse(bp, 0);
305 			error = ufs_blkatoff(vdp, (off_t)results->ulr_offset,
306 			    NULL, &bp, false);
307 			if (error)
308 				goto out;
309 			entryoffsetinblock = 0;
310 		}
311 		/*
312 		 * If still looking for a slot, and at a DIRBLKSIZ
313 		 * boundary, have to start looking for free space again.
314 		 */
315 		if (slotstatus == NONE &&
316 		    (entryoffsetinblock & (dirblksiz - 1)) == 0) {
317 			slotoffset = -1;
318 			slotfreespace = 0;
319 		}
320 		/*
321 		 * Get pointer to next entry.
322 		 * Full validation checks are slow, so we only check
323 		 * enough to insure forward progress through the
324 		 * directory. Complete checks can be run by patching
325 		 * "dirchk" to be true.
326 		 */
327 		KASSERT(bp != NULL);
328 		ep = (struct direct *)((char *)bp->b_data + entryoffsetinblock);
329 		if (ep->d_reclen == 0 ||
330 		    (dirchk && ufs_dirbadentry(vdp, ep, entryoffsetinblock))) {
331 			int i;
332 
333 			ufs_dirbad(dp, results->ulr_offset, "mangled entry");
334 			i = dirblksiz - (entryoffsetinblock & (dirblksiz - 1));
335 			results->ulr_offset += i;
336 			entryoffsetinblock += i;
337 			continue;
338 		}
339 
340 		/*
341 		 * If an appropriate sized slot has not yet been found,
342 		 * check to see if one is available. Also accumulate space
343 		 * in the current block so that we can determine if
344 		 * compaction is viable.
345 		 */
346 		if (slotstatus != FOUND) {
347 			int size = ufs_rw16(ep->d_reclen, needswap);
348 
349 			if (ep->d_ino != 0)
350 				size -= UFS_DIRSIZ(FSFMT(vdp), ep, needswap);
351 			if (size > 0) {
352 				if (size >= slotneeded) {
353 					slotstatus = FOUND;
354 					slotoffset = results->ulr_offset;
355 					slotsize = ufs_rw16(ep->d_reclen,
356 					    needswap);
357 				} else if (slotstatus == NONE) {
358 					slotfreespace += size;
359 					if (slotoffset == -1)
360 						slotoffset = results->ulr_offset;
361 					if (slotfreespace >= slotneeded) {
362 						slotstatus = COMPACT;
363 						slotsize = results->ulr_offset +
364 						    ufs_rw16(ep->d_reclen,
365 							     needswap) -
366 						    slotoffset;
367 					}
368 				}
369 			}
370 		}
371 
372 		/*
373 		 * Check for a name match.
374 		 */
375 		if (ep->d_ino) {
376 			int namlen;
377 
378 #if (BYTE_ORDER == LITTLE_ENDIAN)
379 			if (FSFMT(vdp) && needswap == 0)
380 				namlen = ep->d_type;
381 			else
382 				namlen = ep->d_namlen;
383 #else
384 			if (FSFMT(vdp) && needswap != 0)
385 				namlen = ep->d_type;
386 			else
387 				namlen = ep->d_namlen;
388 #endif
389 			if (namlen == cnp->cn_namelen &&
390 			    !memcmp(cnp->cn_nameptr, ep->d_name,
391 			    (unsigned)namlen)) {
392 #ifdef UFS_DIRHASH
393 foundentry:
394 #endif
395 				/*
396 				 * Save directory entry's inode number and
397 				 * reclen, and release directory buffer.
398 				 */
399 				if (!FSFMT(vdp) && ep->d_type == DT_WHT) {
400 					slotstatus = FOUND;
401 					slotoffset = results->ulr_offset;
402 					slotsize = ufs_rw16(ep->d_reclen,
403 					    needswap);
404 					results->ulr_reclen = slotsize;
405 					/*
406 					 * This is used to set
407 					 * results->ulr_endoff,
408 					 * which may be used by ufs_direnter()
409 					 * as a length to truncate the
410 					 * directory to.  Therefore, it must
411 					 * point past the end of the last
412 					 * non-empty directory entry.  We don't
413 					 * know where that is in this case, so
414 					 * we effectively disable shrinking by
415 					 * using the existing size of the
416 					 * directory.
417 					 *
418 					 * Note that we wouldn't expect to
419 					 * shrink the directory while rewriting
420 					 * an existing entry anyway.
421 					 */
422 					enduseful = endsearch;
423 					cnp->cn_flags |= ISWHITEOUT;
424 					numdirpasses--;
425 					goto notfound;
426 				}
427 				foundino = ufs_rw32(ep->d_ino, needswap);
428 				results->ulr_reclen =
429 				    ufs_rw16(ep->d_reclen, needswap);
430 				goto found;
431 			}
432 		}
433 		prevoff = results->ulr_offset;
434 		results->ulr_offset += ufs_rw16(ep->d_reclen, needswap);
435 		entryoffsetinblock += ufs_rw16(ep->d_reclen, needswap);
436 		if (ep->d_ino)
437 			enduseful = results->ulr_offset;
438 	}
439 notfound:
440 	/*
441 	 * If we started in the middle of the directory and failed
442 	 * to find our target, we must check the beginning as well.
443 	 */
444 	if (numdirpasses == 2) {
445 		numdirpasses--;
446 		results->ulr_offset = 0;
447 		endsearch = results->ulr_diroff;
448 		goto searchloop;
449 	}
450 	if (bp != NULL)
451 		brelse(bp, 0);
452 	/*
453 	 * If creating, and at end of pathname and current
454 	 * directory has not been removed, then can consider
455 	 * allowing file to be created.
456 	 */
457 	if ((nameiop == CREATE || nameiop == RENAME ||
458 	     (nameiop == DELETE &&
459 	      (cnp->cn_flags & DOWHITEOUT) &&
460 	      (cnp->cn_flags & ISWHITEOUT))) &&
461 	    (flags & ISLASTCN) && dp->i_nlink != 0) {
462 		/*
463 		 * Access for write is interpreted as allowing
464 		 * creation of files in the directory.
465 		 */
466 		error = VOP_ACCESS(vdp, VWRITE, cred);
467 		if (error)
468 			goto out;
469 		/*
470 		 * Return an indication of where the new directory
471 		 * entry should be put.  If we didn't find a slot,
472 		 * then set results->ulr_count to 0 indicating
473 		 * that the new slot belongs at the end of the
474 		 * directory. If we found a slot, then the new entry
475 		 * can be put in the range from results->ulr_offset to
476 		 * results->ulr_offset + results->ulr_count.
477 		 */
478 		if (slotstatus == NONE) {
479 			results->ulr_offset = roundup(dp->i_size, dirblksiz);
480 			results->ulr_count = 0;
481 			enduseful = results->ulr_offset;
482 		} else if (nameiop == DELETE) {
483 			results->ulr_offset = slotoffset;
484 			if ((results->ulr_offset & (dirblksiz - 1)) == 0)
485 				results->ulr_count = 0;
486 			else
487 				results->ulr_count =
488 				    results->ulr_offset - prevoff;
489 		} else {
490 			results->ulr_offset = slotoffset;
491 			results->ulr_count = slotsize;
492 			if (enduseful < slotoffset + slotsize)
493 				enduseful = slotoffset + slotsize;
494 		}
495 		results->ulr_endoff = roundup(enduseful, dirblksiz);
496 #if 0 /* commented out by dbj. none of the on disk fields changed */
497 		dp->i_flag |= IN_CHANGE | IN_UPDATE;
498 #endif
499 		/*
500 		 * We return with the directory locked, so that
501 		 * the parameters we set up above will still be
502 		 * valid if we actually decide to do a direnter().
503 		 * We return ni_vp == NULL to indicate that the entry
504 		 * does not currently exist; we leave a pointer to
505 		 * the (locked) directory inode in ndp->ni_dvp.
506 		 *
507 		 * NB - if the directory is unlocked, then this
508 		 * information cannot be used.
509 		 */
510 		error = EJUSTRETURN;
511 		goto out;
512 	}
513 	/*
514 	 * Insert name into cache (as non-existent) if appropriate.
515 	 */
516 	if (nameiop != CREATE) {
517 		cache_enter(vdp, *vpp, cnp->cn_nameptr, cnp->cn_namelen,
518 			    cnp->cn_flags);
519 	}
520 	error = ENOENT;
521 	goto out;
522 
523 found:
524 	if (numdirpasses == 2)
525 		namecache_count_pass2();
526 	/*
527 	 * Check that directory length properly reflects presence
528 	 * of this entry.
529 	 */
530 	if (results->ulr_offset + UFS_DIRSIZ(FSFMT(vdp), ep, needswap) > dp->i_size) {
531 		ufs_dirbad(dp, results->ulr_offset, "i_size too small");
532 		dp->i_size =
533 		    results->ulr_offset + UFS_DIRSIZ(FSFMT(vdp), ep, needswap);
534 		DIP_ASSIGN(dp, size, dp->i_size);
535 		dp->i_flag |= IN_CHANGE | IN_UPDATE;
536 		UFS_WAPBL_UPDATE(vdp, NULL, NULL, UPDATE_DIROP);
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 			error = vcache_get(vdp->v_mount,
569 			    &foundino, sizeof(foundino), &tdp);
570 			if (error)
571 				goto out;
572 		}
573 		/*
574 		 * Write access to directory required to delete files.
575 		 */
576 		error = VOP_ACCESS(vdp, VWRITE, cred);
577 		if (error) {
578 			vrele(tdp);
579 			goto out;
580 		}
581 		/*
582 		 * If directory is "sticky", then user must own
583 		 * the directory, or the file in it, else she
584 		 * may not delete it (unless she's root). This
585 		 * implements append-only directories.
586 		 */
587 		if (dp->i_mode & ISVTX) {
588 			error = kauth_authorize_vnode(cred, KAUTH_VNODE_DELETE,
589 			    tdp, vdp, genfs_can_sticky(cred, dp->i_uid,
590 			    VTOI(tdp)->i_uid));
591 			if (error) {
592 				vrele(tdp);
593 				error = EPERM;
594 				goto out;
595 			}
596 		}
597 		*vpp = tdp;
598 		error = 0;
599 		goto out;
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 	 */
608 	if (nameiop == RENAME && (flags & ISLASTCN)) {
609 		error = VOP_ACCESS(vdp, VWRITE, cred);
610 		if (error)
611 			goto out;
612 		/*
613 		 * Careful about locking second inode.
614 		 * This can only occur if the target is ".".
615 		 */
616 		if (dp->i_number == foundino) {
617 			error = EISDIR;
618 			goto out;
619 		}
620 		error = vcache_get(vdp->v_mount,
621 		    &foundino, sizeof(foundino), &tdp);
622 		if (error)
623 			goto out;
624 		*vpp = tdp;
625 		error = 0;
626 		goto out;
627 	}
628 
629 	if (dp->i_number == foundino) {
630 		vref(vdp);	/* we want ourself, ie "." */
631 		*vpp = vdp;
632 	} else {
633 		error = vcache_get(vdp->v_mount,
634 		    &foundino, sizeof(foundino), &tdp);
635 		if (error)
636 			goto out;
637 		*vpp = tdp;
638 	}
639 
640 	/*
641 	 * Insert name into cache if appropriate.
642 	 */
643 	cache_enter(vdp, *vpp, cnp->cn_nameptr, cnp->cn_namelen, cnp->cn_flags);
644 	error = 0;
645 
646 out:
647 	fstrans_done(vdp->v_mount);
648 	return error;
649 }
650 
651 void
ufs_dirbad(struct inode * ip,doff_t offset,const char * how)652 ufs_dirbad(struct inode *ip, doff_t offset, const char *how)
653 {
654 	struct mount *mp;
655 
656 	mp = ITOV(ip)->v_mount;
657 	printf("%s: bad dir ino %llu at offset %d: %s\n",
658 	    mp->mnt_stat.f_mntonname, (unsigned long long)ip->i_number,
659 	    offset, how);
660 	if ((mp->mnt_flag & MNT_RDONLY) == 0)
661 		panic("bad dir");
662 }
663 
664 /*
665  * Do consistency checking on a directory entry:
666  *	record length must be multiple of 4
667  *	entry must fit in rest of its DIRBLKSIZ block
668  *	record must be large enough to contain entry
669  *	name is not longer than FFS_MAXNAMLEN
670  *	name must be as long as advertised, and null terminated
671  */
672 int
ufs_dirbadentry(struct vnode * dp,struct direct * ep,int entryoffsetinblock)673 ufs_dirbadentry(struct vnode *dp, struct direct *ep, int entryoffsetinblock)
674 {
675 	int i;
676 	int namlen;
677 	struct ufsmount *ump = VFSTOUFS(dp->v_mount);
678 	const int needswap = UFS_MPNEEDSWAP(ump);
679 	int dirblksiz = ump->um_dirblksiz;
680 
681 #if (BYTE_ORDER == LITTLE_ENDIAN)
682 	if (FSFMT(dp) && needswap == 0)
683 		namlen = ep->d_type;
684 	else
685 		namlen = ep->d_namlen;
686 #else
687 	if (FSFMT(dp) && needswap != 0)
688 		namlen = ep->d_type;
689 	else
690 		namlen = ep->d_namlen;
691 #endif
692 	if ((ufs_rw16(ep->d_reclen, needswap) & 0x3) != 0 ||
693 	    ufs_rw16(ep->d_reclen, needswap) >
694 		dirblksiz - (entryoffsetinblock & (dirblksiz - 1)) ||
695 	    ufs_rw16(ep->d_reclen, needswap) <
696 		UFS_DIRSIZ(FSFMT(dp), ep, needswap) ||
697 	    namlen > FFS_MAXNAMLEN) {
698 		/*return (1); */
699 		printf("First bad, reclen=%#x, DIRSIZ=%lu, namlen=%d, "
700 			"flags=%#x, entryoffsetinblock=%d, dirblksiz = %d\n",
701 			ufs_rw16(ep->d_reclen, needswap),
702 			(u_long)UFS_DIRSIZ(FSFMT(dp), ep, needswap),
703 			namlen, dp->v_mount->mnt_flag, entryoffsetinblock,
704 			dirblksiz);
705 		goto bad;
706 	}
707 	if (ep->d_ino == 0)
708 		return (0);
709 	for (i = 0; i < namlen; i++)
710 		if (ep->d_name[i] == '\0') {
711 			/*return (1); */
712 			printf("Second bad\n");
713 			goto bad;
714 	}
715 	if (ep->d_name[i])
716 		goto bad;
717 	return (0);
718 bad:
719 	return (1);
720 }
721 
722 /*
723  * Construct a new directory entry after a call to namei, using the
724  * name in the componentname argument cnp. The argument ip is the
725  * inode to which the new directory entry will refer.
726  */
727 void
ufs_makedirentry(struct inode * ip,struct componentname * cnp,struct direct * newdirp)728 ufs_makedirentry(struct inode *ip, struct componentname *cnp,
729     struct direct *newdirp)
730 {
731 	newdirp->d_ino = ip->i_number;
732 	newdirp->d_namlen = cnp->cn_namelen;
733 	memcpy(newdirp->d_name, cnp->cn_nameptr, (size_t)cnp->cn_namelen);
734 	newdirp->d_name[cnp->cn_namelen] = '\0';
735 	if (FSFMT(ITOV(ip)))
736 		newdirp->d_type = 0;
737 	else
738 		newdirp->d_type = IFTODT(ip->i_mode);
739 }
740 
741 /*
742  * Write a directory entry after a call to namei, using the parameters
743  * that ufs_lookup left in nameidata and in the ufs_lookup_results.
744  *
745  * DVP is the directory to be updated. It must be locked.
746  * ULR is the ufs_lookup_results structure from the final lookup step.
747  * TVP is not used. (XXX: why is it here? remove it)
748  * DIRP is the new directory entry contents.
749  * CNP is the componentname from the final lookup step.
750  * NEWDIRBP is not used and (XXX) should be removed. The previous
751  * comment here said it was used by the now-removed softupdates code.
752  *
753  * The link count of the target inode is *not* incremented; the
754  * caller does that.
755  *
756  * If ulr->ulr_count is 0, ufs_lookup did not find space to insert the
757  * directory entry. ulr_offset, which is the place to put the entry,
758  * should be on a block boundary (and should be at the end of the
759  * directory AFAIK) and a fresh block is allocated to put the new
760  * directory entry in.
761  *
762  * If ulr->ulr_count is not zero, ufs_lookup found a slot to insert
763  * the entry into. This slot ranges from ulr_offset to ulr_offset +
764  * ulr_count. However, this slot may already be partially populated
765  * requiring compaction. See notes below.
766  *
767  * Furthermore, if ulr_count is not zero and ulr_endoff is not the
768  * same as i_size, the directory is truncated to size ulr_endoff.
769  */
770 int
ufs_direnter(struct vnode * dvp,const struct ufs_lookup_results * ulr,struct vnode * tvp,struct direct * dirp,struct componentname * cnp,struct buf * newdirbp)771 ufs_direnter(struct vnode *dvp, const struct ufs_lookup_results *ulr,
772     struct vnode *tvp, struct direct *dirp,
773     struct componentname *cnp, struct buf *newdirbp)
774 {
775 	kauth_cred_t cr;
776 	int newentrysize;
777 	struct inode *dp;
778 	struct buf *bp;
779 	u_int dsize;
780 	struct direct *ep, *nep;
781 	int error, ret, blkoff, loc, spacefree;
782 	char *dirbuf;
783 	struct timespec ts;
784 	struct ufsmount *ump = VFSTOUFS(dvp->v_mount);
785 	const int needswap = UFS_MPNEEDSWAP(ump);
786 	int dirblksiz = ump->um_dirblksiz;
787 
788 	UFS_WAPBL_JLOCK_ASSERT(dvp->v_mount);
789 
790 	error = 0;
791 	cr = cnp->cn_cred;
792 
793 	dp = VTOI(dvp);
794 	newentrysize = UFS_DIRSIZ(0, dirp, 0);
795 
796 	if (ulr->ulr_count == 0) {
797 		/*
798 		 * If ulr_count is 0, then namei could find no
799 		 * space in the directory. Here, ulr_offset will
800 		 * be on a directory block boundary and we will write the
801 		 * new entry into a fresh block.
802 		 */
803 		if (ulr->ulr_offset & (dirblksiz - 1))
804 			panic("ufs_direnter: newblk");
805 		if ((error = UFS_BALLOC(dvp, (off_t)ulr->ulr_offset, dirblksiz,
806 		    cr, B_CLRBUF | B_SYNC, &bp)) != 0) {
807 			return (error);
808 		}
809 		dp->i_size = ulr->ulr_offset + dirblksiz;
810 		DIP_ASSIGN(dp, size, dp->i_size);
811 		dp->i_flag |= IN_CHANGE | IN_UPDATE;
812 		uvm_vnp_setsize(dvp, dp->i_size);
813 		dirp->d_reclen = ufs_rw16(dirblksiz, needswap);
814 		dirp->d_ino = ufs_rw32(dirp->d_ino, needswap);
815 		if (FSFMT(dvp)) {
816 #if (BYTE_ORDER == LITTLE_ENDIAN)
817 			if (needswap == 0) {
818 #else
819 			if (needswap != 0) {
820 #endif
821 				u_char tmp = dirp->d_namlen;
822 				dirp->d_namlen = dirp->d_type;
823 				dirp->d_type = tmp;
824 			}
825 		}
826 		blkoff = ulr->ulr_offset & (ump->um_mountp->mnt_stat.f_iosize - 1);
827 		memcpy((char *)bp->b_data + blkoff, dirp, newentrysize);
828 #ifdef UFS_DIRHASH
829 		if (dp->i_dirhash != NULL) {
830 			ufsdirhash_newblk(dp, ulr->ulr_offset);
831 			ufsdirhash_add(dp, dirp, ulr->ulr_offset);
832 			ufsdirhash_checkblock(dp, (char *)bp->b_data + blkoff,
833 			    ulr->ulr_offset);
834 		}
835 #endif
836 		error = VOP_BWRITE(bp->b_vp, bp);
837 		vfs_timestamp(&ts);
838 		ret = UFS_UPDATE(dvp, &ts, &ts, UPDATE_DIROP);
839 		if (error == 0)
840 			return (ret);
841 		return (error);
842 	}
843 
844 	/*
845 	 * If ulr_count is non-zero, then namei found space for the new
846 	 * entry in the range ulr_offset to ulr_offset + ulr_count
847 	 * in the directory. To use this space, we may have to compact
848 	 * the entries located there, by copying them together towards the
849 	 * beginning of the block, leaving the free space in one usable
850 	 * chunk at the end.
851 	 */
852 
853 	/*
854 	 * Increase size of directory if entry eats into new space.
855 	 * This should never push the size past a new multiple of
856 	 * DIRBLKSIZ.
857 	 *
858 	 * N.B. - THIS IS AN ARTIFACT OF 4.2 AND SHOULD NEVER HAPPEN.
859 	 */
860 	if (ulr->ulr_offset + ulr->ulr_count > dp->i_size) {
861 #ifdef DIAGNOSTIC
862 		printf("ufs_direnter: reached 4.2-only block, "
863 		       "not supposed to happen\n");
864 #endif
865 		dp->i_size = ulr->ulr_offset + ulr->ulr_count;
866 		DIP_ASSIGN(dp, size, dp->i_size);
867 		dp->i_flag |= IN_CHANGE | IN_UPDATE;
868 		UFS_WAPBL_UPDATE(dvp, NULL, NULL, UPDATE_DIROP);
869 	}
870 	/*
871 	 * Get the block containing the space for the new directory entry.
872 	 */
873 	error = ufs_blkatoff(dvp, (off_t)ulr->ulr_offset, &dirbuf, &bp, true);
874 	if (error) {
875 		return (error);
876 	}
877 	/*
878 	 * Find space for the new entry. In the simple case, the entry at
879 	 * offset base will have the space. If it does not, then namei
880 	 * arranged that compacting the region ulr_offset to
881 	 * ulr_offset + ulr_count would yield the space.
882 	 */
883 	ep = (struct direct *)dirbuf;
884 	dsize = (ep->d_ino != 0) ? UFS_DIRSIZ(FSFMT(dvp), ep, needswap) : 0;
885 	spacefree = ufs_rw16(ep->d_reclen, needswap) - dsize;
886 	for (loc = ufs_rw16(ep->d_reclen, needswap); loc < ulr->ulr_count; ) {
887 		uint16_t reclen;
888 
889 		nep = (struct direct *)(dirbuf + loc);
890 
891 		/* Trim the existing slot (NB: dsize may be zero). */
892 		ep->d_reclen = ufs_rw16(dsize, needswap);
893 		ep = (struct direct *)((char *)ep + dsize);
894 
895 		reclen = ufs_rw16(nep->d_reclen, needswap);
896 		loc += reclen;
897 		if (nep->d_ino == 0) {
898 			/*
899 			 * A mid-block unused entry. Such entries are
900 			 * never created by the kernel, but fsck_ffs
901 			 * can create them (and it doesn't fix them).
902 			 *
903 			 * Add up the free space, and initialise the
904 			 * relocated entry since we don't memcpy it.
905 			 */
906 			spacefree += reclen;
907 			ep->d_ino = 0;
908 			dsize = 0;
909 			continue;
910 		}
911 		dsize = UFS_DIRSIZ(FSFMT(dvp), nep, needswap);
912 		spacefree += reclen - dsize;
913 #ifdef UFS_DIRHASH
914 		if (dp->i_dirhash != NULL)
915 			ufsdirhash_move(dp, nep,
916 			    ulr->ulr_offset + ((char *)nep - dirbuf),
917 			    ulr->ulr_offset + ((char *)ep - dirbuf));
918 #endif
919 		memcpy((void *)ep, (void *)nep, dsize);
920 	}
921 	/*
922 	 * Here, `ep' points to a directory entry containing `dsize' in-use
923 	 * bytes followed by `spacefree' unused bytes. If ep->d_ino == 0,
924 	 * then the entry is completely unused (dsize == 0). The value
925 	 * of ep->d_reclen is always indeterminate.
926 	 *
927 	 * Update the pointer fields in the previous entry (if any),
928 	 * copy in the new entry, and write out the block.
929 	 */
930 	if (ep->d_ino == 0 ||
931 	    (ufs_rw32(ep->d_ino, needswap) == UFS_WINO &&
932 	     memcmp(ep->d_name, dirp->d_name, dirp->d_namlen) == 0)) {
933 		if (spacefree + dsize < newentrysize)
934 			panic("ufs_direnter: compact1");
935 		dirp->d_reclen = spacefree + dsize;
936 	} else {
937 		if (spacefree < newentrysize)
938 			panic("ufs_direnter: compact2");
939 		dirp->d_reclen = spacefree;
940 		ep->d_reclen = ufs_rw16(dsize, needswap);
941 		ep = (struct direct *)((char *)ep + dsize);
942 	}
943 	dirp->d_reclen = ufs_rw16(dirp->d_reclen, needswap);
944 	dirp->d_ino = ufs_rw32(dirp->d_ino, needswap);
945 	if (FSFMT(dvp)) {
946 #if (BYTE_ORDER == LITTLE_ENDIAN)
947 		if (needswap == 0) {
948 #else
949 		if (needswap != 0) {
950 #endif
951 			u_char tmp = dirp->d_namlen;
952 			dirp->d_namlen = dirp->d_type;
953 			dirp->d_type = tmp;
954 		}
955 	}
956 #ifdef UFS_DIRHASH
957 	if (dp->i_dirhash != NULL && (ep->d_ino == 0 ||
958 	    dirp->d_reclen == spacefree))
959 		ufsdirhash_add(dp, dirp, ulr->ulr_offset + ((char *)ep - dirbuf));
960 #endif
961 	memcpy((void *)ep, (void *)dirp, (u_int)newentrysize);
962 #ifdef UFS_DIRHASH
963 	if (dp->i_dirhash != NULL)
964 		ufsdirhash_checkblock(dp, dirbuf -
965 		    (ulr->ulr_offset & (dirblksiz - 1)),
966 		    ulr->ulr_offset & ~(dirblksiz - 1));
967 #endif
968 	error = VOP_BWRITE(bp->b_vp, bp);
969 	dp->i_flag |= IN_CHANGE | IN_UPDATE;
970 	/*
971 	 * If all went well, and the directory can be shortened, proceed
972 	 * with the truncation. Note that we have to unlock the inode for
973 	 * the entry that we just entered, as the truncation may need to
974 	 * lock other inodes which can lead to deadlock if we also hold a
975 	 * lock on the newly entered node.
976 	 */
977 	if (error == 0 && ulr->ulr_endoff && ulr->ulr_endoff < dp->i_size) {
978 #ifdef UFS_DIRHASH
979 		if (dp->i_dirhash != NULL)
980 			ufsdirhash_dirtrunc(dp, ulr->ulr_endoff);
981 #endif
982 		(void) UFS_TRUNCATE(dvp, (off_t)ulr->ulr_endoff, IO_SYNC, cr);
983 	}
984 	UFS_WAPBL_UPDATE(dvp, NULL, NULL, UPDATE_DIROP);
985 	return (error);
986 }
987 
988 /*
989  * Remove a directory entry after a call to namei, using the
990  * parameters that ufs_lookup left in nameidata and in the
991  * ufs_lookup_results.
992  *
993  * DVP is the directory to be updated. It must be locked.
994  * ULR is the ufs_lookup_results structure from the final lookup step.
995  * IP, if not null, is the inode being unlinked.
996  * FLAGS may contain DOWHITEOUT.
997  * ISRMDIR is not used and (XXX) should be removed.
998  *
999  * If FLAGS contains DOWHITEOUT the entry is replaced with a whiteout
1000  * instead of being cleared.
1001  *
1002  * ulr->ulr_offset contains the position of the directory entry
1003  * to be removed.
1004  *
1005  * ulr->ulr_reclen contains the size of the directory entry to be
1006  * removed.
1007  *
1008  * ulr->ulr_count contains the size of the *previous* directory
1009  * entry. This allows finding it, for free space management. If
1010  * ulr_count is 0, the target entry is at the beginning of the
1011  * directory. (Does this ever happen? The first entry should be ".",
1012  * which should only be removed at rmdir time. Does rmdir come here
1013  * to clear out the "." and ".." entries? Perhaps, but I doubt it.)
1014  *
1015  * The space is marked free by adding it to the record length (not
1016  * name length) of the preceding entry. If the first entry becomes
1017  * free, it is marked free by setting the inode number to 0.
1018  *
1019  * The link count of IP is decremented. Note that this is not the
1020  * inverse behavior of ufs_direnter, which does not adjust link
1021  * counts. Sigh.
1022  */
1023 int
1024 ufs_dirremove(struct vnode *dvp, const struct ufs_lookup_results *ulr,
1025 	      struct inode *ip, int flags, int isrmdir)
1026 {
1027 	struct inode *dp = VTOI(dvp);
1028 	struct direct *ep;
1029 	struct buf *bp;
1030 	int error;
1031 	const int needswap = UFS_MPNEEDSWAP(dp->i_ump);
1032 
1033 	UFS_WAPBL_JLOCK_ASSERT(dvp->v_mount);
1034 
1035 	if (flags & DOWHITEOUT) {
1036 		/*
1037 		 * Whiteout entry: set d_ino to UFS_WINO.
1038 		 */
1039 		error = ufs_blkatoff(dvp, (off_t)ulr->ulr_offset, (void *)&ep,
1040 				     &bp, true);
1041 		if (error)
1042 			return (error);
1043 		ep->d_ino = ufs_rw32(UFS_WINO, needswap);
1044 		ep->d_type = DT_WHT;
1045 		goto out;
1046 	}
1047 
1048 	if ((error = ufs_blkatoff(dvp,
1049 	    (off_t)(ulr->ulr_offset - ulr->ulr_count), (void *)&ep, &bp, true)) != 0)
1050 		return (error);
1051 
1052 #ifdef UFS_DIRHASH
1053 	/*
1054 	 * Remove the dirhash entry. This is complicated by the fact
1055 	 * that `ep' is the previous entry when ulr_count != 0.
1056 	 */
1057 	if (dp->i_dirhash != NULL)
1058 		ufsdirhash_remove(dp, (ulr->ulr_count == 0) ? ep :
1059 		   (struct direct *)((char *)ep +
1060 		   ufs_rw16(ep->d_reclen, needswap)), ulr->ulr_offset);
1061 #endif
1062 
1063 	if (ulr->ulr_count == 0) {
1064 		/*
1065 		 * First entry in block: set d_ino to zero.
1066 		 */
1067 		ep->d_ino = 0;
1068 	} else {
1069 		/*
1070 		 * Collapse new free space into previous entry.
1071 		 */
1072 		ep->d_reclen =
1073 		    ufs_rw16(ufs_rw16(ep->d_reclen, needswap) + ulr->ulr_reclen,
1074 			needswap);
1075 	}
1076 
1077 #ifdef UFS_DIRHASH
1078 	if (dp->i_dirhash != NULL) {
1079 		int dirblksiz = ip->i_ump->um_dirblksiz;
1080 		ufsdirhash_checkblock(dp, (char *)ep -
1081 		    ((ulr->ulr_offset - ulr->ulr_count) & (dirblksiz - 1)),
1082 		    ulr->ulr_offset & ~(dirblksiz - 1));
1083 	}
1084 #endif
1085 
1086 out:
1087 	if (ip) {
1088 		ip->i_nlink--;
1089 		DIP_ASSIGN(ip, nlink, ip->i_nlink);
1090 		ip->i_flag |= IN_CHANGE;
1091 		UFS_WAPBL_UPDATE(ITOV(ip), NULL, NULL, 0);
1092 	}
1093 	/*
1094 	 * XXX did it ever occur to anyone that it might be a good
1095 	 * idea to restore ip->i_nlink if this fails? Or something?
1096 	 * Currently on error return from this function the state of
1097 	 * ip->i_nlink depends on what happened, and callers
1098 	 * definitely do not take this into account.
1099 	 */
1100 	error = VOP_BWRITE(bp->b_vp, bp);
1101 	dp->i_flag |= IN_CHANGE | IN_UPDATE;
1102 	/*
1103 	 * If the last named reference to a snapshot goes away,
1104 	 * drop its snapshot reference so that it will be reclaimed
1105 	 * when last open reference goes away.
1106 	 */
1107 	if (ip != 0 && (ip->i_flags & SF_SNAPSHOT) != 0 &&
1108 	    ip->i_nlink == 0)
1109 		UFS_SNAPGONE(ITOV(ip));
1110 	UFS_WAPBL_UPDATE(dvp, NULL, NULL, 0);
1111 	return (error);
1112 }
1113 
1114 /*
1115  * Rewrite an existing directory entry to point at the inode supplied.
1116  *
1117  * DP is the directory to update.
1118  * OFFSET is the position of the entry in question. It may come
1119  * from ulr_offset of a ufs_lookup_results.
1120  * OIP is the old inode the directory previously pointed to.
1121  * NEWINUM is the number of the new inode.
1122  * NEWTYPE is the new value for the type field of the directory entry.
1123  * (This is ignored if the fs doesn't support that.)
1124  * ISRMDIR is not used and (XXX) should be removed.
1125  * IFLAGS are added to DP's inode flags.
1126  *
1127  * The link count of OIP is decremented. Note that the link count of
1128  * the new inode is *not* incremented. Yay for symmetry.
1129  */
1130 int
1131 ufs_dirrewrite(struct inode *dp, off_t offset,
1132     struct inode *oip, ino_t newinum, int newtype,
1133     int isrmdir, int iflags)
1134 {
1135 	struct buf *bp;
1136 	struct direct *ep;
1137 	struct vnode *vdp = ITOV(dp);
1138 	int error;
1139 
1140 	error = ufs_blkatoff(vdp, offset, (void *)&ep, &bp, true);
1141 	if (error)
1142 		return (error);
1143 	ep->d_ino = ufs_rw32(newinum, UFS_MPNEEDSWAP(dp->i_ump));
1144 	if (!FSFMT(vdp))
1145 		ep->d_type = newtype;
1146 	oip->i_nlink--;
1147 	DIP_ASSIGN(oip, nlink, oip->i_nlink);
1148 	oip->i_flag |= IN_CHANGE;
1149 	UFS_WAPBL_UPDATE(ITOV(oip), NULL, NULL, UPDATE_DIROP);
1150 	error = VOP_BWRITE(bp->b_vp, bp);
1151 	dp->i_flag |= iflags;
1152 	/*
1153 	 * If the last named reference to a snapshot goes away,
1154 	 * drop its snapshot reference so that it will be reclaimed
1155 	 * when last open reference goes away.
1156 	 */
1157 	if ((oip->i_flags & SF_SNAPSHOT) != 0 && oip->i_nlink == 0)
1158 		UFS_SNAPGONE(ITOV(oip));
1159 	UFS_WAPBL_UPDATE(vdp, NULL, NULL, UPDATE_DIROP);
1160 	return (error);
1161 }
1162 
1163 /*
1164  * Check if a directory is empty or not.
1165  * Inode supplied must be locked.
1166  *
1167  * Using a struct dirtemplate here is not precisely
1168  * what we want, but better than using a struct direct.
1169  *
1170  * NB: does not handle corrupted directories.
1171  */
1172 int
1173 ufs_dirempty(struct inode *ip, ino_t parentino, kauth_cred_t cred)
1174 {
1175 	doff_t off;
1176 	struct dirtemplate dbuf;
1177 	struct direct *dp = (struct direct *)&dbuf;
1178 	int error, namlen;
1179 	size_t count;
1180 	const int needswap = UFS_IPNEEDSWAP(ip);
1181 #define	MINDIRSIZ (sizeof (struct dirtemplate) / 2)
1182 
1183 	for (off = 0; off < ip->i_size;
1184 	    off += ufs_rw16(dp->d_reclen, needswap)) {
1185 		error = ufs_bufio(UIO_READ, ITOV(ip), (void *)dp, MINDIRSIZ,
1186 		    off, IO_NODELOCKED, cred, &count, NULL);
1187 		/*
1188 		 * Since we read MINDIRSIZ, residual must
1189 		 * be 0 unless we're at end of file.
1190 		 */
1191 		if (error || count != 0)
1192 			return (0);
1193 		/* avoid infinite loops */
1194 		if (dp->d_reclen == 0)
1195 			return (0);
1196 		/* skip empty entries */
1197 		if (dp->d_ino == 0 || ufs_rw32(dp->d_ino, needswap) == UFS_WINO)
1198 			continue;
1199 		/* accept only "." and ".." */
1200 #if (BYTE_ORDER == LITTLE_ENDIAN)
1201 		if (FSFMT(ITOV(ip)) && needswap == 0)
1202 			namlen = dp->d_type;
1203 		else
1204 			namlen = dp->d_namlen;
1205 #else
1206 		if (FSFMT(ITOV(ip)) && needswap != 0)
1207 			namlen = dp->d_type;
1208 		else
1209 			namlen = dp->d_namlen;
1210 #endif
1211 		if (namlen > 2)
1212 			return (0);
1213 		if (dp->d_name[0] != '.')
1214 			return (0);
1215 		/*
1216 		 * At this point namlen must be 1 or 2.
1217 		 * 1 implies ".", 2 implies ".." if second
1218 		 * char is also "."
1219 		 */
1220 		if (namlen == 1 &&
1221 		    ufs_rw32(dp->d_ino, needswap) == ip->i_number)
1222 			continue;
1223 		if (dp->d_name[1] == '.' &&
1224 		    ufs_rw32(dp->d_ino, needswap) == parentino)
1225 			continue;
1226 		return (0);
1227 	}
1228 	return (1);
1229 }
1230 
1231 #define	UFS_DIRRABLKS 0
1232 int ufs_dirrablks = UFS_DIRRABLKS;
1233 
1234 /*
1235  * ufs_blkatoff: Return buffer with the contents of block "offset" from
1236  * the beginning of directory "vp".  If "res" is non-NULL, fill it in with
1237  * a pointer to the remaining space in the directory.  If the caller intends
1238  * to modify the buffer returned, "modify" must be true.
1239  */
1240 
1241 int
1242 ufs_blkatoff(struct vnode *vp, off_t offset, char **res, struct buf **bpp,
1243     bool modify)
1244 {
1245 	struct inode *ip __diagused;
1246 	struct buf *bp;
1247 	daddr_t lbn;
1248 	const int dirrablks = ufs_dirrablks;
1249 	daddr_t *blks;
1250 	int *blksizes;
1251 	int run, error;
1252 	struct mount *mp = vp->v_mount;
1253 	const int bshift = mp->mnt_fs_bshift;
1254 	const int bsize = 1 << bshift;
1255 	off_t eof;
1256 
1257 	blks = kmem_alloc((1 + dirrablks) * sizeof(daddr_t), KM_SLEEP);
1258 	blksizes = kmem_alloc((1 + dirrablks) * sizeof(int), KM_SLEEP);
1259 	ip = VTOI(vp);
1260 	KASSERT(vp->v_size == ip->i_size);
1261 	GOP_SIZE(vp, vp->v_size, &eof, 0);
1262 	lbn = offset >> bshift;
1263 
1264 	for (run = 0; run <= dirrablks;) {
1265 		const off_t curoff = lbn << bshift;
1266 		const int size = MIN(eof - curoff, bsize);
1267 
1268 		if (size == 0) {
1269 			break;
1270 		}
1271 		KASSERT(curoff < eof);
1272 		blks[run] = lbn;
1273 		blksizes[run] = size;
1274 		lbn++;
1275 		run++;
1276 		if (size != bsize) {
1277 			break;
1278 		}
1279 	}
1280 	KASSERT(run >= 1);
1281 	error = breadn(vp, blks[0], blksizes[0], &blks[1], &blksizes[1],
1282 	    run - 1, (modify ? B_MODIFY : 0), &bp);
1283 	if (error != 0) {
1284 		*bpp = NULL;
1285 		goto out;
1286 	}
1287 	if (res) {
1288 		*res = (char *)bp->b_data + (offset & (bsize - 1));
1289 	}
1290 	*bpp = bp;
1291 
1292  out:
1293 	kmem_free(blks, (1 + dirrablks) * sizeof(daddr_t));
1294 	kmem_free(blksizes, (1 + dirrablks) * sizeof(int));
1295 	return error;
1296 }
1297