xref: /freebsd/sys/fs/tmpfs/tmpfs_subr.c (revision 68b2efbd3b74f0d45bbbf07cef5408e455eefbd1)
1 /*	$NetBSD: tmpfs_subr.c,v 1.35 2007/07/09 21:10:50 ad Exp $	*/
2 
3 /*-
4  * Copyright (c) 2005 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Julio M. Merino Vidal, developed as part of Google's Summer of Code
9  * 2005 program.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
24  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30  * POSSIBILITY OF SUCH DAMAGE.
31  */
32 
33 /*
34  * Efficient memory file system supporting functions.
35  */
36 #include <sys/cdefs.h>
37 __FBSDID("$FreeBSD$");
38 
39 #include <sys/param.h>
40 #include <sys/fnv_hash.h>
41 #include <sys/lock.h>
42 #include <sys/namei.h>
43 #include <sys/priv.h>
44 #include <sys/proc.h>
45 #include <sys/random.h>
46 #include <sys/rwlock.h>
47 #include <sys/stat.h>
48 #include <sys/systm.h>
49 #include <sys/sysctl.h>
50 #include <sys/vnode.h>
51 #include <sys/vmmeter.h>
52 
53 #include <vm/vm.h>
54 #include <vm/vm_param.h>
55 #include <vm/vm_object.h>
56 #include <vm/vm_page.h>
57 #include <vm/vm_pageout.h>
58 #include <vm/vm_pager.h>
59 #include <vm/vm_extern.h>
60 
61 #include <fs/tmpfs/tmpfs.h>
62 #include <fs/tmpfs/tmpfs_fifoops.h>
63 #include <fs/tmpfs/tmpfs_vnops.h>
64 
65 SYSCTL_NODE(_vfs, OID_AUTO, tmpfs, CTLFLAG_RW, 0, "tmpfs file system");
66 
67 static long tmpfs_pages_reserved = TMPFS_PAGES_MINRESERVED;
68 
69 static int
70 sysctl_mem_reserved(SYSCTL_HANDLER_ARGS)
71 {
72 	int error;
73 	long pages, bytes;
74 
75 	pages = *(long *)arg1;
76 	bytes = pages * PAGE_SIZE;
77 
78 	error = sysctl_handle_long(oidp, &bytes, 0, req);
79 	if (error || !req->newptr)
80 		return (error);
81 
82 	pages = bytes / PAGE_SIZE;
83 	if (pages < TMPFS_PAGES_MINRESERVED)
84 		return (EINVAL);
85 
86 	*(long *)arg1 = pages;
87 	return (0);
88 }
89 
90 SYSCTL_PROC(_vfs_tmpfs, OID_AUTO, memory_reserved, CTLTYPE_LONG|CTLFLAG_RW,
91     &tmpfs_pages_reserved, 0, sysctl_mem_reserved, "L",
92     "Amount of available memory and swap below which tmpfs growth stops");
93 
94 static __inline int tmpfs_dirtree_cmp(struct tmpfs_dirent *a,
95     struct tmpfs_dirent *b);
96 RB_PROTOTYPE_STATIC(tmpfs_dir, tmpfs_dirent, uh.td_entries, tmpfs_dirtree_cmp);
97 
98 size_t
99 tmpfs_mem_avail(void)
100 {
101 	vm_ooffset_t avail;
102 
103 	avail = swap_pager_avail + vm_cnt.v_free_count - tmpfs_pages_reserved;
104 	if (__predict_false(avail < 0))
105 		avail = 0;
106 	return (avail);
107 }
108 
109 size_t
110 tmpfs_pages_used(struct tmpfs_mount *tmp)
111 {
112 	const size_t node_size = sizeof(struct tmpfs_node) +
113 	    sizeof(struct tmpfs_dirent);
114 	size_t meta_pages;
115 
116 	meta_pages = howmany((uintmax_t)tmp->tm_nodes_inuse * node_size,
117 	    PAGE_SIZE);
118 	return (meta_pages + tmp->tm_pages_used);
119 }
120 
121 static size_t
122 tmpfs_pages_check_avail(struct tmpfs_mount *tmp, size_t req_pages)
123 {
124 	if (tmpfs_mem_avail() < req_pages)
125 		return (0);
126 
127 	if (tmp->tm_pages_max != ULONG_MAX &&
128 	    tmp->tm_pages_max < req_pages + tmpfs_pages_used(tmp))
129 			return (0);
130 
131 	return (1);
132 }
133 
134 void
135 tmpfs_ref_node(struct tmpfs_node *node)
136 {
137 
138 	TMPFS_NODE_LOCK(node);
139 	tmpfs_ref_node_locked(node);
140 	TMPFS_NODE_UNLOCK(node);
141 }
142 
143 void
144 tmpfs_ref_node_locked(struct tmpfs_node *node)
145 {
146 
147 	TMPFS_NODE_ASSERT_LOCKED(node);
148 	KASSERT(node->tn_refcount > 0, ("node %p zero refcount", node));
149 	KASSERT(node->tn_refcount < UINT_MAX, ("node %p refcount %u", node,
150 	    node->tn_refcount));
151 	node->tn_refcount++;
152 }
153 
154 /*
155  * Allocates a new node of type 'type' inside the 'tmp' mount point, with
156  * its owner set to 'uid', its group to 'gid' and its mode set to 'mode',
157  * using the credentials of the process 'p'.
158  *
159  * If the node type is set to 'VDIR', then the parent parameter must point
160  * to the parent directory of the node being created.  It may only be NULL
161  * while allocating the root node.
162  *
163  * If the node type is set to 'VBLK' or 'VCHR', then the rdev parameter
164  * specifies the device the node represents.
165  *
166  * If the node type is set to 'VLNK', then the parameter target specifies
167  * the file name of the target file for the symbolic link that is being
168  * created.
169  *
170  * Note that new nodes are retrieved from the available list if it has
171  * items or, if it is empty, from the node pool as long as there is enough
172  * space to create them.
173  *
174  * Returns zero on success or an appropriate error code on failure.
175  */
176 int
177 tmpfs_alloc_node(struct mount *mp, struct tmpfs_mount *tmp, enum vtype type,
178     uid_t uid, gid_t gid, mode_t mode, struct tmpfs_node *parent,
179     char *target, dev_t rdev, struct tmpfs_node **node)
180 {
181 	struct tmpfs_node *nnode;
182 	vm_object_t obj;
183 
184 	/* If the root directory of the 'tmp' file system is not yet
185 	 * allocated, this must be the request to do it. */
186 	MPASS(IMPLIES(tmp->tm_root == NULL, parent == NULL && type == VDIR));
187 	KASSERT(tmp->tm_root == NULL || mp->mnt_writeopcount > 0,
188 	    ("creating node not under vn_start_write"));
189 
190 	MPASS(IFF(type == VLNK, target != NULL));
191 	MPASS(IFF(type == VBLK || type == VCHR, rdev != VNOVAL));
192 
193 	if (tmp->tm_nodes_inuse >= tmp->tm_nodes_max)
194 		return (ENOSPC);
195 	if (tmpfs_pages_check_avail(tmp, 1) == 0)
196 		return (ENOSPC);
197 
198 	if ((mp->mnt_kern_flag & MNTK_UNMOUNT) != 0) {
199 		/*
200 		 * When a new tmpfs node is created for fully
201 		 * constructed mount point, there must be a parent
202 		 * node, which vnode is locked exclusively.  As
203 		 * consequence, if the unmount is executing in
204 		 * parallel, vflush() cannot reclaim the parent vnode.
205 		 * Due to this, the check for MNTK_UNMOUNT flag is not
206 		 * racy: if we did not see MNTK_UNMOUNT flag, then tmp
207 		 * cannot be destroyed until node construction is
208 		 * finished and the parent vnode unlocked.
209 		 *
210 		 * Tmpfs does not need to instantiate new nodes during
211 		 * unmount.
212 		 */
213 		return (EBUSY);
214 	}
215 
216 	nnode = (struct tmpfs_node *)uma_zalloc_arg(tmp->tm_node_pool, tmp,
217 	    M_WAITOK);
218 
219 	/* Generic initialization. */
220 	nnode->tn_type = type;
221 	vfs_timestamp(&nnode->tn_atime);
222 	nnode->tn_birthtime = nnode->tn_ctime = nnode->tn_mtime =
223 	    nnode->tn_atime;
224 	nnode->tn_uid = uid;
225 	nnode->tn_gid = gid;
226 	nnode->tn_mode = mode;
227 	nnode->tn_id = alloc_unr(tmp->tm_ino_unr);
228 	nnode->tn_refcount = 1;
229 
230 	/* Type-specific initialization. */
231 	switch (nnode->tn_type) {
232 	case VBLK:
233 	case VCHR:
234 		nnode->tn_rdev = rdev;
235 		break;
236 
237 	case VDIR:
238 		RB_INIT(&nnode->tn_dir.tn_dirhead);
239 		LIST_INIT(&nnode->tn_dir.tn_dupindex);
240 		MPASS(parent != nnode);
241 		MPASS(IMPLIES(parent == NULL, tmp->tm_root == NULL));
242 		nnode->tn_dir.tn_parent = (parent == NULL) ? nnode : parent;
243 		nnode->tn_dir.tn_readdir_lastn = 0;
244 		nnode->tn_dir.tn_readdir_lastp = NULL;
245 		nnode->tn_links++;
246 		TMPFS_NODE_LOCK(nnode->tn_dir.tn_parent);
247 		nnode->tn_dir.tn_parent->tn_links++;
248 		TMPFS_NODE_UNLOCK(nnode->tn_dir.tn_parent);
249 		break;
250 
251 	case VFIFO:
252 		/* FALLTHROUGH */
253 	case VSOCK:
254 		break;
255 
256 	case VLNK:
257 		MPASS(strlen(target) < MAXPATHLEN);
258 		nnode->tn_size = strlen(target);
259 		nnode->tn_link = malloc(nnode->tn_size, M_TMPFSNAME,
260 		    M_WAITOK);
261 		memcpy(nnode->tn_link, target, nnode->tn_size);
262 		break;
263 
264 	case VREG:
265 		obj = nnode->tn_reg.tn_aobj =
266 		    vm_pager_allocate(OBJT_SWAP, NULL, 0, VM_PROT_DEFAULT, 0,
267 			NULL /* XXXKIB - tmpfs needs swap reservation */);
268 		VM_OBJECT_WLOCK(obj);
269 		/* OBJ_TMPFS is set together with the setting of vp->v_object */
270 		vm_object_set_flag(obj, OBJ_NOSPLIT | OBJ_TMPFS_NODE);
271 		vm_object_clear_flag(obj, OBJ_ONEMAPPING);
272 		VM_OBJECT_WUNLOCK(obj);
273 		break;
274 
275 	default:
276 		panic("tmpfs_alloc_node: type %p %d", nnode,
277 		    (int)nnode->tn_type);
278 	}
279 
280 	TMPFS_LOCK(tmp);
281 	LIST_INSERT_HEAD(&tmp->tm_nodes_used, nnode, tn_entries);
282 	nnode->tn_attached = true;
283 	tmp->tm_nodes_inuse++;
284 	tmp->tm_refcount++;
285 	TMPFS_UNLOCK(tmp);
286 
287 	*node = nnode;
288 	return (0);
289 }
290 
291 /*
292  * Destroys the node pointed to by node from the file system 'tmp'.
293  * If the node references a directory, no entries are allowed.
294  */
295 void
296 tmpfs_free_node(struct tmpfs_mount *tmp, struct tmpfs_node *node)
297 {
298 
299 	TMPFS_LOCK(tmp);
300 	TMPFS_NODE_LOCK(node);
301 	if (!tmpfs_free_node_locked(tmp, node, false)) {
302 		TMPFS_NODE_UNLOCK(node);
303 		TMPFS_UNLOCK(tmp);
304 	}
305 }
306 
307 bool
308 tmpfs_free_node_locked(struct tmpfs_mount *tmp, struct tmpfs_node *node,
309     bool detach)
310 {
311 	vm_object_t uobj;
312 
313 	TMPFS_MP_ASSERT_LOCKED(tmp);
314 	TMPFS_NODE_ASSERT_LOCKED(node);
315 	KASSERT(node->tn_refcount > 0, ("node %p refcount zero", node));
316 
317 	node->tn_refcount--;
318 	if (node->tn_attached && (detach || node->tn_refcount == 0)) {
319 		MPASS(tmp->tm_nodes_inuse > 0);
320 		tmp->tm_nodes_inuse--;
321 		LIST_REMOVE(node, tn_entries);
322 		node->tn_attached = false;
323 	}
324 	if (node->tn_refcount > 0)
325 		return (false);
326 
327 #ifdef INVARIANTS
328 	MPASS(node->tn_vnode == NULL);
329 	MPASS((node->tn_vpstate & TMPFS_VNODE_ALLOCATING) == 0);
330 #endif
331 	TMPFS_NODE_UNLOCK(node);
332 	TMPFS_UNLOCK(tmp);
333 
334 	switch (node->tn_type) {
335 	case VBLK:
336 		/* FALLTHROUGH */
337 	case VCHR:
338 		/* FALLTHROUGH */
339 	case VDIR:
340 		/* FALLTHROUGH */
341 	case VFIFO:
342 		/* FALLTHROUGH */
343 	case VSOCK:
344 		break;
345 
346 	case VLNK:
347 		free(node->tn_link, M_TMPFSNAME);
348 		break;
349 
350 	case VREG:
351 		uobj = node->tn_reg.tn_aobj;
352 		if (uobj != NULL) {
353 			if (uobj->size != 0)
354 				atomic_subtract_long(&tmp->tm_pages_used, uobj->size);
355 			KASSERT((uobj->flags & OBJ_TMPFS) == 0,
356 			    ("leaked OBJ_TMPFS node %p vm_obj %p", node, uobj));
357 			vm_object_deallocate(uobj);
358 		}
359 		break;
360 
361 	default:
362 		panic("tmpfs_free_node: type %p %d", node, (int)node->tn_type);
363 	}
364 
365 	free_unr(tmp->tm_ino_unr, node->tn_id);
366 	uma_zfree(tmp->tm_node_pool, node);
367 	TMPFS_LOCK(tmp);
368 	tmpfs_free_tmp(tmp);
369 	return (true);
370 }
371 
372 static __inline uint32_t
373 tmpfs_dirent_hash(const char *name, u_int len)
374 {
375 	uint32_t hash;
376 
377 	hash = fnv_32_buf(name, len, FNV1_32_INIT + len) & TMPFS_DIRCOOKIE_MASK;
378 #ifdef TMPFS_DEBUG_DIRCOOKIE_DUP
379 	hash &= 0xf;
380 #endif
381 	if (hash < TMPFS_DIRCOOKIE_MIN)
382 		hash += TMPFS_DIRCOOKIE_MIN;
383 
384 	return (hash);
385 }
386 
387 static __inline off_t
388 tmpfs_dirent_cookie(struct tmpfs_dirent *de)
389 {
390 	if (de == NULL)
391 		return (TMPFS_DIRCOOKIE_EOF);
392 
393 	MPASS(de->td_cookie >= TMPFS_DIRCOOKIE_MIN);
394 
395 	return (de->td_cookie);
396 }
397 
398 static __inline boolean_t
399 tmpfs_dirent_dup(struct tmpfs_dirent *de)
400 {
401 	return ((de->td_cookie & TMPFS_DIRCOOKIE_DUP) != 0);
402 }
403 
404 static __inline boolean_t
405 tmpfs_dirent_duphead(struct tmpfs_dirent *de)
406 {
407 	return ((de->td_cookie & TMPFS_DIRCOOKIE_DUPHEAD) != 0);
408 }
409 
410 void
411 tmpfs_dirent_init(struct tmpfs_dirent *de, const char *name, u_int namelen)
412 {
413 	de->td_hash = de->td_cookie = tmpfs_dirent_hash(name, namelen);
414 	memcpy(de->ud.td_name, name, namelen);
415 	de->td_namelen = namelen;
416 }
417 
418 /*
419  * Allocates a new directory entry for the node node with a name of name.
420  * The new directory entry is returned in *de.
421  *
422  * The link count of node is increased by one to reflect the new object
423  * referencing it.
424  *
425  * Returns zero on success or an appropriate error code on failure.
426  */
427 int
428 tmpfs_alloc_dirent(struct tmpfs_mount *tmp, struct tmpfs_node *node,
429     const char *name, u_int len, struct tmpfs_dirent **de)
430 {
431 	struct tmpfs_dirent *nde;
432 
433 	nde = uma_zalloc(tmp->tm_dirent_pool, M_WAITOK);
434 	nde->td_node = node;
435 	if (name != NULL) {
436 		nde->ud.td_name = malloc(len, M_TMPFSNAME, M_WAITOK);
437 		tmpfs_dirent_init(nde, name, len);
438 	} else
439 		nde->td_namelen = 0;
440 	if (node != NULL)
441 		node->tn_links++;
442 
443 	*de = nde;
444 
445 	return 0;
446 }
447 
448 /*
449  * Frees a directory entry.  It is the caller's responsibility to destroy
450  * the node referenced by it if needed.
451  *
452  * The link count of node is decreased by one to reflect the removal of an
453  * object that referenced it.  This only happens if 'node_exists' is true;
454  * otherwise the function will not access the node referred to by the
455  * directory entry, as it may already have been released from the outside.
456  */
457 void
458 tmpfs_free_dirent(struct tmpfs_mount *tmp, struct tmpfs_dirent *de)
459 {
460 	struct tmpfs_node *node;
461 
462 	node = de->td_node;
463 	if (node != NULL) {
464 		MPASS(node->tn_links > 0);
465 		node->tn_links--;
466 	}
467 	if (!tmpfs_dirent_duphead(de) && de->ud.td_name != NULL)
468 		free(de->ud.td_name, M_TMPFSNAME);
469 	uma_zfree(tmp->tm_dirent_pool, de);
470 }
471 
472 void
473 tmpfs_destroy_vobject(struct vnode *vp, vm_object_t obj)
474 {
475 
476 	ASSERT_VOP_ELOCKED(vp, "tmpfs_destroy_vobject");
477 	if (vp->v_type != VREG || obj == NULL)
478 		return;
479 
480 	VM_OBJECT_WLOCK(obj);
481 	VI_LOCK(vp);
482 	vm_object_clear_flag(obj, OBJ_TMPFS);
483 	obj->un_pager.swp.swp_tmpfs = NULL;
484 	VI_UNLOCK(vp);
485 	VM_OBJECT_WUNLOCK(obj);
486 }
487 
488 /*
489  * Need to clear v_object for insmntque failure.
490  */
491 static void
492 tmpfs_insmntque_dtr(struct vnode *vp, void *dtr_arg)
493 {
494 
495 	tmpfs_destroy_vobject(vp, vp->v_object);
496 	vp->v_object = NULL;
497 	vp->v_data = NULL;
498 	vp->v_op = &dead_vnodeops;
499 	vgone(vp);
500 	vput(vp);
501 }
502 
503 /*
504  * Allocates a new vnode for the node node or returns a new reference to
505  * an existing one if the node had already a vnode referencing it.  The
506  * resulting locked vnode is returned in *vpp.
507  *
508  * Returns zero on success or an appropriate error code on failure.
509  */
510 int
511 tmpfs_alloc_vp(struct mount *mp, struct tmpfs_node *node, int lkflag,
512     struct vnode **vpp)
513 {
514 	struct vnode *vp;
515 	struct tmpfs_mount *tm;
516 	vm_object_t object;
517 	int error;
518 
519 	error = 0;
520 	tm = VFS_TO_TMPFS(mp);
521 	TMPFS_NODE_LOCK(node);
522 	tmpfs_ref_node_locked(node);
523 loop:
524 	TMPFS_NODE_ASSERT_LOCKED(node);
525 	if ((vp = node->tn_vnode) != NULL) {
526 		MPASS((node->tn_vpstate & TMPFS_VNODE_DOOMED) == 0);
527 		VI_LOCK(vp);
528 		if ((node->tn_type == VDIR && node->tn_dir.tn_parent == NULL) ||
529 		    ((vp->v_iflag & VI_DOOMED) != 0 &&
530 		    (lkflag & LK_NOWAIT) != 0)) {
531 			VI_UNLOCK(vp);
532 			TMPFS_NODE_UNLOCK(node);
533 			error = ENOENT;
534 			vp = NULL;
535 			goto out;
536 		}
537 		if ((vp->v_iflag & VI_DOOMED) != 0) {
538 			VI_UNLOCK(vp);
539 			node->tn_vpstate |= TMPFS_VNODE_WRECLAIM;
540 			while ((node->tn_vpstate & TMPFS_VNODE_WRECLAIM) != 0) {
541 				msleep(&node->tn_vnode, TMPFS_NODE_MTX(node),
542 				    0, "tmpfsE", 0);
543 			}
544 			goto loop;
545 		}
546 		TMPFS_NODE_UNLOCK(node);
547 		error = vget(vp, lkflag | LK_INTERLOCK, curthread);
548 		if (error == ENOENT) {
549 			TMPFS_NODE_LOCK(node);
550 			goto loop;
551 		}
552 		if (error != 0) {
553 			vp = NULL;
554 			goto out;
555 		}
556 
557 		/*
558 		 * Make sure the vnode is still there after
559 		 * getting the interlock to avoid racing a free.
560 		 */
561 		if (node->tn_vnode == NULL || node->tn_vnode != vp) {
562 			vput(vp);
563 			TMPFS_NODE_LOCK(node);
564 			goto loop;
565 		}
566 
567 		goto out;
568 	}
569 
570 	if ((node->tn_vpstate & TMPFS_VNODE_DOOMED) ||
571 	    (node->tn_type == VDIR && node->tn_dir.tn_parent == NULL)) {
572 		TMPFS_NODE_UNLOCK(node);
573 		error = ENOENT;
574 		vp = NULL;
575 		goto out;
576 	}
577 
578 	/*
579 	 * otherwise lock the vp list while we call getnewvnode
580 	 * since that can block.
581 	 */
582 	if (node->tn_vpstate & TMPFS_VNODE_ALLOCATING) {
583 		node->tn_vpstate |= TMPFS_VNODE_WANT;
584 		error = msleep((caddr_t) &node->tn_vpstate,
585 		    TMPFS_NODE_MTX(node), 0, "tmpfs_alloc_vp", 0);
586 		if (error != 0)
587 			goto out;
588 		goto loop;
589 	} else
590 		node->tn_vpstate |= TMPFS_VNODE_ALLOCATING;
591 
592 	TMPFS_NODE_UNLOCK(node);
593 
594 	/* Get a new vnode and associate it with our node. */
595 	error = getnewvnode("tmpfs", mp, VFS_TO_TMPFS(mp)->tm_nonc ?
596 	    &tmpfs_vnodeop_nonc_entries : &tmpfs_vnodeop_entries, &vp);
597 	if (error != 0)
598 		goto unlock;
599 	MPASS(vp != NULL);
600 
601 	/* lkflag is ignored, the lock is exclusive */
602 	(void) vn_lock(vp, lkflag | LK_RETRY);
603 
604 	vp->v_data = node;
605 	vp->v_type = node->tn_type;
606 
607 	/* Type-specific initialization. */
608 	switch (node->tn_type) {
609 	case VBLK:
610 		/* FALLTHROUGH */
611 	case VCHR:
612 		/* FALLTHROUGH */
613 	case VLNK:
614 		/* FALLTHROUGH */
615 	case VSOCK:
616 		break;
617 	case VFIFO:
618 		vp->v_op = &tmpfs_fifoop_entries;
619 		break;
620 	case VREG:
621 		object = node->tn_reg.tn_aobj;
622 		VM_OBJECT_WLOCK(object);
623 		VI_LOCK(vp);
624 		KASSERT(vp->v_object == NULL, ("Not NULL v_object in tmpfs"));
625 		vp->v_object = object;
626 		object->un_pager.swp.swp_tmpfs = vp;
627 		vm_object_set_flag(object, OBJ_TMPFS);
628 		VI_UNLOCK(vp);
629 		VM_OBJECT_WUNLOCK(object);
630 		break;
631 	case VDIR:
632 		MPASS(node->tn_dir.tn_parent != NULL);
633 		if (node->tn_dir.tn_parent == node)
634 			vp->v_vflag |= VV_ROOT;
635 		break;
636 
637 	default:
638 		panic("tmpfs_alloc_vp: type %p %d", node, (int)node->tn_type);
639 	}
640 	if (vp->v_type != VFIFO)
641 		VN_LOCK_ASHARE(vp);
642 
643 	error = insmntque1(vp, mp, tmpfs_insmntque_dtr, NULL);
644 	if (error != 0)
645 		vp = NULL;
646 
647 unlock:
648 	TMPFS_NODE_LOCK(node);
649 
650 	MPASS(node->tn_vpstate & TMPFS_VNODE_ALLOCATING);
651 	node->tn_vpstate &= ~TMPFS_VNODE_ALLOCATING;
652 	node->tn_vnode = vp;
653 
654 	if (node->tn_vpstate & TMPFS_VNODE_WANT) {
655 		node->tn_vpstate &= ~TMPFS_VNODE_WANT;
656 		TMPFS_NODE_UNLOCK(node);
657 		wakeup((caddr_t) &node->tn_vpstate);
658 	} else
659 		TMPFS_NODE_UNLOCK(node);
660 
661 out:
662 	if (error == 0) {
663 		*vpp = vp;
664 
665 #ifdef INVARIANTS
666 		MPASS(*vpp != NULL && VOP_ISLOCKED(*vpp));
667 		TMPFS_NODE_LOCK(node);
668 		MPASS(*vpp == node->tn_vnode);
669 		TMPFS_NODE_UNLOCK(node);
670 #endif
671 	}
672 	tmpfs_free_node(tm, node);
673 
674 	return (error);
675 }
676 
677 /*
678  * Destroys the association between the vnode vp and the node it
679  * references.
680  */
681 void
682 tmpfs_free_vp(struct vnode *vp)
683 {
684 	struct tmpfs_node *node;
685 
686 	node = VP_TO_TMPFS_NODE(vp);
687 
688 	TMPFS_NODE_ASSERT_LOCKED(node);
689 	node->tn_vnode = NULL;
690 	if ((node->tn_vpstate & TMPFS_VNODE_WRECLAIM) != 0)
691 		wakeup(&node->tn_vnode);
692 	node->tn_vpstate &= ~TMPFS_VNODE_WRECLAIM;
693 	vp->v_data = NULL;
694 }
695 
696 /*
697  * Allocates a new file of type 'type' and adds it to the parent directory
698  * 'dvp'; this addition is done using the component name given in 'cnp'.
699  * The ownership of the new file is automatically assigned based on the
700  * credentials of the caller (through 'cnp'), the group is set based on
701  * the parent directory and the mode is determined from the 'vap' argument.
702  * If successful, *vpp holds a vnode to the newly created file and zero
703  * is returned.  Otherwise *vpp is NULL and the function returns an
704  * appropriate error code.
705  */
706 int
707 tmpfs_alloc_file(struct vnode *dvp, struct vnode **vpp, struct vattr *vap,
708     struct componentname *cnp, char *target)
709 {
710 	int error;
711 	struct tmpfs_dirent *de;
712 	struct tmpfs_mount *tmp;
713 	struct tmpfs_node *dnode;
714 	struct tmpfs_node *node;
715 	struct tmpfs_node *parent;
716 
717 	ASSERT_VOP_ELOCKED(dvp, "tmpfs_alloc_file");
718 	MPASS(cnp->cn_flags & HASBUF);
719 
720 	tmp = VFS_TO_TMPFS(dvp->v_mount);
721 	dnode = VP_TO_TMPFS_DIR(dvp);
722 	*vpp = NULL;
723 
724 	/* If the entry we are creating is a directory, we cannot overflow
725 	 * the number of links of its parent, because it will get a new
726 	 * link. */
727 	if (vap->va_type == VDIR) {
728 		/* Ensure that we do not overflow the maximum number of links
729 		 * imposed by the system. */
730 		MPASS(dnode->tn_links <= LINK_MAX);
731 		if (dnode->tn_links == LINK_MAX) {
732 			return (EMLINK);
733 		}
734 
735 		parent = dnode;
736 		MPASS(parent != NULL);
737 	} else
738 		parent = NULL;
739 
740 	/* Allocate a node that represents the new file. */
741 	error = tmpfs_alloc_node(dvp->v_mount, tmp, vap->va_type,
742 	    cnp->cn_cred->cr_uid, dnode->tn_gid, vap->va_mode, parent,
743 	    target, vap->va_rdev, &node);
744 	if (error != 0)
745 		return (error);
746 
747 	/* Allocate a directory entry that points to the new file. */
748 	error = tmpfs_alloc_dirent(tmp, node, cnp->cn_nameptr, cnp->cn_namelen,
749 	    &de);
750 	if (error != 0) {
751 		tmpfs_free_node(tmp, node);
752 		return (error);
753 	}
754 
755 	/* Allocate a vnode for the new file. */
756 	error = tmpfs_alloc_vp(dvp->v_mount, node, LK_EXCLUSIVE, vpp);
757 	if (error != 0) {
758 		tmpfs_free_dirent(tmp, de);
759 		tmpfs_free_node(tmp, node);
760 		return (error);
761 	}
762 
763 	/* Now that all required items are allocated, we can proceed to
764 	 * insert the new node into the directory, an operation that
765 	 * cannot fail. */
766 	if (cnp->cn_flags & ISWHITEOUT)
767 		tmpfs_dir_whiteout_remove(dvp, cnp);
768 	tmpfs_dir_attach(dvp, de);
769 	return (0);
770 }
771 
772 struct tmpfs_dirent *
773 tmpfs_dir_first(struct tmpfs_node *dnode, struct tmpfs_dir_cursor *dc)
774 {
775 	struct tmpfs_dirent *de;
776 
777 	de = RB_MIN(tmpfs_dir, &dnode->tn_dir.tn_dirhead);
778 	dc->tdc_tree = de;
779 	if (de != NULL && tmpfs_dirent_duphead(de))
780 		de = LIST_FIRST(&de->ud.td_duphead);
781 	dc->tdc_current = de;
782 
783 	return (dc->tdc_current);
784 }
785 
786 struct tmpfs_dirent *
787 tmpfs_dir_next(struct tmpfs_node *dnode, struct tmpfs_dir_cursor *dc)
788 {
789 	struct tmpfs_dirent *de;
790 
791 	MPASS(dc->tdc_tree != NULL);
792 	if (tmpfs_dirent_dup(dc->tdc_current)) {
793 		dc->tdc_current = LIST_NEXT(dc->tdc_current, uh.td_dup.entries);
794 		if (dc->tdc_current != NULL)
795 			return (dc->tdc_current);
796 	}
797 	dc->tdc_tree = dc->tdc_current = RB_NEXT(tmpfs_dir,
798 	    &dnode->tn_dir.tn_dirhead, dc->tdc_tree);
799 	if ((de = dc->tdc_current) != NULL && tmpfs_dirent_duphead(de)) {
800 		dc->tdc_current = LIST_FIRST(&de->ud.td_duphead);
801 		MPASS(dc->tdc_current != NULL);
802 	}
803 
804 	return (dc->tdc_current);
805 }
806 
807 /* Lookup directory entry in RB-Tree. Function may return duphead entry. */
808 static struct tmpfs_dirent *
809 tmpfs_dir_xlookup_hash(struct tmpfs_node *dnode, uint32_t hash)
810 {
811 	struct tmpfs_dirent *de, dekey;
812 
813 	dekey.td_hash = hash;
814 	de = RB_FIND(tmpfs_dir, &dnode->tn_dir.tn_dirhead, &dekey);
815 	return (de);
816 }
817 
818 /* Lookup directory entry by cookie, initialize directory cursor accordingly. */
819 static struct tmpfs_dirent *
820 tmpfs_dir_lookup_cookie(struct tmpfs_node *node, off_t cookie,
821     struct tmpfs_dir_cursor *dc)
822 {
823 	struct tmpfs_dir *dirhead = &node->tn_dir.tn_dirhead;
824 	struct tmpfs_dirent *de, dekey;
825 
826 	MPASS(cookie >= TMPFS_DIRCOOKIE_MIN);
827 
828 	if (cookie == node->tn_dir.tn_readdir_lastn &&
829 	    (de = node->tn_dir.tn_readdir_lastp) != NULL) {
830 		/* Protect against possible race, tn_readdir_last[pn]
831 		 * may be updated with only shared vnode lock held. */
832 		if (cookie == tmpfs_dirent_cookie(de))
833 			goto out;
834 	}
835 
836 	if ((cookie & TMPFS_DIRCOOKIE_DUP) != 0) {
837 		LIST_FOREACH(de, &node->tn_dir.tn_dupindex,
838 		    uh.td_dup.index_entries) {
839 			MPASS(tmpfs_dirent_dup(de));
840 			if (de->td_cookie == cookie)
841 				goto out;
842 			/* dupindex list is sorted. */
843 			if (de->td_cookie < cookie) {
844 				de = NULL;
845 				goto out;
846 			}
847 		}
848 		MPASS(de == NULL);
849 		goto out;
850 	}
851 
852 	if ((cookie & TMPFS_DIRCOOKIE_MASK) != cookie) {
853 		de = NULL;
854 	} else {
855 		dekey.td_hash = cookie;
856 		/* Recover if direntry for cookie was removed */
857 		de = RB_NFIND(tmpfs_dir, dirhead, &dekey);
858 	}
859 	dc->tdc_tree = de;
860 	dc->tdc_current = de;
861 	if (de != NULL && tmpfs_dirent_duphead(de)) {
862 		dc->tdc_current = LIST_FIRST(&de->ud.td_duphead);
863 		MPASS(dc->tdc_current != NULL);
864 	}
865 	return (dc->tdc_current);
866 
867 out:
868 	dc->tdc_tree = de;
869 	dc->tdc_current = de;
870 	if (de != NULL && tmpfs_dirent_dup(de))
871 		dc->tdc_tree = tmpfs_dir_xlookup_hash(node,
872 		    de->td_hash);
873 	return (dc->tdc_current);
874 }
875 
876 /*
877  * Looks for a directory entry in the directory represented by node.
878  * 'cnp' describes the name of the entry to look for.  Note that the .
879  * and .. components are not allowed as they do not physically exist
880  * within directories.
881  *
882  * Returns a pointer to the entry when found, otherwise NULL.
883  */
884 struct tmpfs_dirent *
885 tmpfs_dir_lookup(struct tmpfs_node *node, struct tmpfs_node *f,
886     struct componentname *cnp)
887 {
888 	struct tmpfs_dir_duphead *duphead;
889 	struct tmpfs_dirent *de;
890 	uint32_t hash;
891 
892 	MPASS(IMPLIES(cnp->cn_namelen == 1, cnp->cn_nameptr[0] != '.'));
893 	MPASS(IMPLIES(cnp->cn_namelen == 2, !(cnp->cn_nameptr[0] == '.' &&
894 	    cnp->cn_nameptr[1] == '.')));
895 	TMPFS_VALIDATE_DIR(node);
896 
897 	hash = tmpfs_dirent_hash(cnp->cn_nameptr, cnp->cn_namelen);
898 	de = tmpfs_dir_xlookup_hash(node, hash);
899 	if (de != NULL && tmpfs_dirent_duphead(de)) {
900 		duphead = &de->ud.td_duphead;
901 		LIST_FOREACH(de, duphead, uh.td_dup.entries) {
902 			if (TMPFS_DIRENT_MATCHES(de, cnp->cn_nameptr,
903 			    cnp->cn_namelen))
904 				break;
905 		}
906 	} else if (de != NULL) {
907 		if (!TMPFS_DIRENT_MATCHES(de, cnp->cn_nameptr,
908 		    cnp->cn_namelen))
909 			de = NULL;
910 	}
911 	if (de != NULL && f != NULL && de->td_node != f)
912 		de = NULL;
913 
914 	return (de);
915 }
916 
917 /*
918  * Attach duplicate-cookie directory entry nde to dnode and insert to dupindex
919  * list, allocate new cookie value.
920  */
921 static void
922 tmpfs_dir_attach_dup(struct tmpfs_node *dnode,
923     struct tmpfs_dir_duphead *duphead, struct tmpfs_dirent *nde)
924 {
925 	struct tmpfs_dir_duphead *dupindex;
926 	struct tmpfs_dirent *de, *pde;
927 
928 	dupindex = &dnode->tn_dir.tn_dupindex;
929 	de = LIST_FIRST(dupindex);
930 	if (de == NULL || de->td_cookie < TMPFS_DIRCOOKIE_DUP_MAX) {
931 		if (de == NULL)
932 			nde->td_cookie = TMPFS_DIRCOOKIE_DUP_MIN;
933 		else
934 			nde->td_cookie = de->td_cookie + 1;
935 		MPASS(tmpfs_dirent_dup(nde));
936 		LIST_INSERT_HEAD(dupindex, nde, uh.td_dup.index_entries);
937 		LIST_INSERT_HEAD(duphead, nde, uh.td_dup.entries);
938 		return;
939 	}
940 
941 	/*
942 	 * Cookie numbers are near exhaustion. Scan dupindex list for unused
943 	 * numbers. dupindex list is sorted in descending order. Keep it so
944 	 * after inserting nde.
945 	 */
946 	while (1) {
947 		pde = de;
948 		de = LIST_NEXT(de, uh.td_dup.index_entries);
949 		if (de == NULL && pde->td_cookie != TMPFS_DIRCOOKIE_DUP_MIN) {
950 			/*
951 			 * Last element of the index doesn't have minimal cookie
952 			 * value, use it.
953 			 */
954 			nde->td_cookie = TMPFS_DIRCOOKIE_DUP_MIN;
955 			LIST_INSERT_AFTER(pde, nde, uh.td_dup.index_entries);
956 			LIST_INSERT_HEAD(duphead, nde, uh.td_dup.entries);
957 			return;
958 		} else if (de == NULL) {
959 			/*
960 			 * We are so lucky have 2^30 hash duplicates in single
961 			 * directory :) Return largest possible cookie value.
962 			 * It should be fine except possible issues with
963 			 * VOP_READDIR restart.
964 			 */
965 			nde->td_cookie = TMPFS_DIRCOOKIE_DUP_MAX;
966 			LIST_INSERT_HEAD(dupindex, nde,
967 			    uh.td_dup.index_entries);
968 			LIST_INSERT_HEAD(duphead, nde, uh.td_dup.entries);
969 			return;
970 		}
971 		if (de->td_cookie + 1 == pde->td_cookie ||
972 		    de->td_cookie >= TMPFS_DIRCOOKIE_DUP_MAX)
973 			continue;	/* No hole or invalid cookie. */
974 		nde->td_cookie = de->td_cookie + 1;
975 		MPASS(tmpfs_dirent_dup(nde));
976 		MPASS(pde->td_cookie > nde->td_cookie);
977 		MPASS(nde->td_cookie > de->td_cookie);
978 		LIST_INSERT_BEFORE(de, nde, uh.td_dup.index_entries);
979 		LIST_INSERT_HEAD(duphead, nde, uh.td_dup.entries);
980 		return;
981 	}
982 }
983 
984 /*
985  * Attaches the directory entry de to the directory represented by vp.
986  * Note that this does not change the link count of the node pointed by
987  * the directory entry, as this is done by tmpfs_alloc_dirent.
988  */
989 void
990 tmpfs_dir_attach(struct vnode *vp, struct tmpfs_dirent *de)
991 {
992 	struct tmpfs_node *dnode;
993 	struct tmpfs_dirent *xde, *nde;
994 
995 	ASSERT_VOP_ELOCKED(vp, __func__);
996 	MPASS(de->td_namelen > 0);
997 	MPASS(de->td_hash >= TMPFS_DIRCOOKIE_MIN);
998 	MPASS(de->td_cookie == de->td_hash);
999 
1000 	dnode = VP_TO_TMPFS_DIR(vp);
1001 	dnode->tn_dir.tn_readdir_lastn = 0;
1002 	dnode->tn_dir.tn_readdir_lastp = NULL;
1003 
1004 	MPASS(!tmpfs_dirent_dup(de));
1005 	xde = RB_INSERT(tmpfs_dir, &dnode->tn_dir.tn_dirhead, de);
1006 	if (xde != NULL && tmpfs_dirent_duphead(xde))
1007 		tmpfs_dir_attach_dup(dnode, &xde->ud.td_duphead, de);
1008 	else if (xde != NULL) {
1009 		/*
1010 		 * Allocate new duphead. Swap xde with duphead to avoid
1011 		 * adding/removing elements with the same hash.
1012 		 */
1013 		MPASS(!tmpfs_dirent_dup(xde));
1014 		tmpfs_alloc_dirent(VFS_TO_TMPFS(vp->v_mount), NULL, NULL, 0,
1015 		    &nde);
1016 		/* *nde = *xde; XXX gcc 4.2.1 may generate invalid code. */
1017 		memcpy(nde, xde, sizeof(*xde));
1018 		xde->td_cookie |= TMPFS_DIRCOOKIE_DUPHEAD;
1019 		LIST_INIT(&xde->ud.td_duphead);
1020 		xde->td_namelen = 0;
1021 		xde->td_node = NULL;
1022 		tmpfs_dir_attach_dup(dnode, &xde->ud.td_duphead, nde);
1023 		tmpfs_dir_attach_dup(dnode, &xde->ud.td_duphead, de);
1024 	}
1025 	dnode->tn_size += sizeof(struct tmpfs_dirent);
1026 	dnode->tn_status |= TMPFS_NODE_ACCESSED | TMPFS_NODE_CHANGED | \
1027 	    TMPFS_NODE_MODIFIED;
1028 	tmpfs_update(vp);
1029 }
1030 
1031 /*
1032  * Detaches the directory entry de from the directory represented by vp.
1033  * Note that this does not change the link count of the node pointed by
1034  * the directory entry, as this is done by tmpfs_free_dirent.
1035  */
1036 void
1037 tmpfs_dir_detach(struct vnode *vp, struct tmpfs_dirent *de)
1038 {
1039 	struct tmpfs_mount *tmp;
1040 	struct tmpfs_dir *head;
1041 	struct tmpfs_node *dnode;
1042 	struct tmpfs_dirent *xde;
1043 
1044 	ASSERT_VOP_ELOCKED(vp, __func__);
1045 
1046 	dnode = VP_TO_TMPFS_DIR(vp);
1047 	head = &dnode->tn_dir.tn_dirhead;
1048 	dnode->tn_dir.tn_readdir_lastn = 0;
1049 	dnode->tn_dir.tn_readdir_lastp = NULL;
1050 
1051 	if (tmpfs_dirent_dup(de)) {
1052 		/* Remove duphead if de was last entry. */
1053 		if (LIST_NEXT(de, uh.td_dup.entries) == NULL) {
1054 			xde = tmpfs_dir_xlookup_hash(dnode, de->td_hash);
1055 			MPASS(tmpfs_dirent_duphead(xde));
1056 		} else
1057 			xde = NULL;
1058 		LIST_REMOVE(de, uh.td_dup.entries);
1059 		LIST_REMOVE(de, uh.td_dup.index_entries);
1060 		if (xde != NULL) {
1061 			if (LIST_EMPTY(&xde->ud.td_duphead)) {
1062 				RB_REMOVE(tmpfs_dir, head, xde);
1063 				tmp = VFS_TO_TMPFS(vp->v_mount);
1064 				MPASS(xde->td_node == NULL);
1065 				tmpfs_free_dirent(tmp, xde);
1066 			}
1067 		}
1068 		de->td_cookie = de->td_hash;
1069 	} else
1070 		RB_REMOVE(tmpfs_dir, head, de);
1071 
1072 	dnode->tn_size -= sizeof(struct tmpfs_dirent);
1073 	dnode->tn_status |= TMPFS_NODE_ACCESSED | TMPFS_NODE_CHANGED | \
1074 	    TMPFS_NODE_MODIFIED;
1075 	tmpfs_update(vp);
1076 }
1077 
1078 void
1079 tmpfs_dir_destroy(struct tmpfs_mount *tmp, struct tmpfs_node *dnode)
1080 {
1081 	struct tmpfs_dirent *de, *dde, *nde;
1082 
1083 	RB_FOREACH_SAFE(de, tmpfs_dir, &dnode->tn_dir.tn_dirhead, nde) {
1084 		RB_REMOVE(tmpfs_dir, &dnode->tn_dir.tn_dirhead, de);
1085 		/* Node may already be destroyed. */
1086 		de->td_node = NULL;
1087 		if (tmpfs_dirent_duphead(de)) {
1088 			while ((dde = LIST_FIRST(&de->ud.td_duphead)) != NULL) {
1089 				LIST_REMOVE(dde, uh.td_dup.entries);
1090 				dde->td_node = NULL;
1091 				tmpfs_free_dirent(tmp, dde);
1092 			}
1093 		}
1094 		tmpfs_free_dirent(tmp, de);
1095 	}
1096 }
1097 
1098 /*
1099  * Helper function for tmpfs_readdir.  Creates a '.' entry for the given
1100  * directory and returns it in the uio space.  The function returns 0
1101  * on success, -1 if there was not enough space in the uio structure to
1102  * hold the directory entry or an appropriate error code if another
1103  * error happens.
1104  */
1105 static int
1106 tmpfs_dir_getdotdent(struct tmpfs_node *node, struct uio *uio)
1107 {
1108 	int error;
1109 	struct dirent dent;
1110 
1111 	TMPFS_VALIDATE_DIR(node);
1112 	MPASS(uio->uio_offset == TMPFS_DIRCOOKIE_DOT);
1113 
1114 	dent.d_fileno = node->tn_id;
1115 	dent.d_type = DT_DIR;
1116 	dent.d_namlen = 1;
1117 	dent.d_name[0] = '.';
1118 	dent.d_name[1] = '\0';
1119 	dent.d_reclen = GENERIC_DIRSIZ(&dent);
1120 
1121 	if (dent.d_reclen > uio->uio_resid)
1122 		error = EJUSTRETURN;
1123 	else
1124 		error = uiomove(&dent, dent.d_reclen, uio);
1125 
1126 	tmpfs_set_status(node, TMPFS_NODE_ACCESSED);
1127 
1128 	return (error);
1129 }
1130 
1131 /*
1132  * Helper function for tmpfs_readdir.  Creates a '..' entry for the given
1133  * directory and returns it in the uio space.  The function returns 0
1134  * on success, -1 if there was not enough space in the uio structure to
1135  * hold the directory entry or an appropriate error code if another
1136  * error happens.
1137  */
1138 static int
1139 tmpfs_dir_getdotdotdent(struct tmpfs_node *node, struct uio *uio)
1140 {
1141 	int error;
1142 	struct dirent dent;
1143 
1144 	TMPFS_VALIDATE_DIR(node);
1145 	MPASS(uio->uio_offset == TMPFS_DIRCOOKIE_DOTDOT);
1146 
1147 	/*
1148 	 * Return ENOENT if the current node is already removed.
1149 	 */
1150 	TMPFS_ASSERT_LOCKED(node);
1151 	if (node->tn_dir.tn_parent == NULL)
1152 		return (ENOENT);
1153 
1154 	TMPFS_NODE_LOCK(node->tn_dir.tn_parent);
1155 	dent.d_fileno = node->tn_dir.tn_parent->tn_id;
1156 	TMPFS_NODE_UNLOCK(node->tn_dir.tn_parent);
1157 
1158 	dent.d_type = DT_DIR;
1159 	dent.d_namlen = 2;
1160 	dent.d_name[0] = '.';
1161 	dent.d_name[1] = '.';
1162 	dent.d_name[2] = '\0';
1163 	dent.d_reclen = GENERIC_DIRSIZ(&dent);
1164 
1165 	if (dent.d_reclen > uio->uio_resid)
1166 		error = EJUSTRETURN;
1167 	else
1168 		error = uiomove(&dent, dent.d_reclen, uio);
1169 
1170 	tmpfs_set_status(node, TMPFS_NODE_ACCESSED);
1171 
1172 	return (error);
1173 }
1174 
1175 /*
1176  * Helper function for tmpfs_readdir.  Returns as much directory entries
1177  * as can fit in the uio space.  The read starts at uio->uio_offset.
1178  * The function returns 0 on success, -1 if there was not enough space
1179  * in the uio structure to hold the directory entry or an appropriate
1180  * error code if another error happens.
1181  */
1182 int
1183 tmpfs_dir_getdents(struct tmpfs_node *node, struct uio *uio, int maxcookies,
1184     u_long *cookies, int *ncookies)
1185 {
1186 	struct tmpfs_dir_cursor dc;
1187 	struct tmpfs_dirent *de;
1188 	off_t off;
1189 	int error;
1190 
1191 	TMPFS_VALIDATE_DIR(node);
1192 
1193 	off = 0;
1194 
1195 	/*
1196 	 * Lookup the node from the current offset.  The starting offset of
1197 	 * 0 will lookup both '.' and '..', and then the first real entry,
1198 	 * or EOF if there are none.  Then find all entries for the dir that
1199 	 * fit into the buffer.  Once no more entries are found (de == NULL),
1200 	 * the offset is set to TMPFS_DIRCOOKIE_EOF, which will cause the next
1201 	 * call to return 0.
1202 	 */
1203 	switch (uio->uio_offset) {
1204 	case TMPFS_DIRCOOKIE_DOT:
1205 		error = tmpfs_dir_getdotdent(node, uio);
1206 		if (error != 0)
1207 			return (error);
1208 		uio->uio_offset = TMPFS_DIRCOOKIE_DOTDOT;
1209 		if (cookies != NULL)
1210 			cookies[(*ncookies)++] = off = uio->uio_offset;
1211 		/* FALLTHROUGH */
1212 	case TMPFS_DIRCOOKIE_DOTDOT:
1213 		error = tmpfs_dir_getdotdotdent(node, uio);
1214 		if (error != 0)
1215 			return (error);
1216 		de = tmpfs_dir_first(node, &dc);
1217 		uio->uio_offset = tmpfs_dirent_cookie(de);
1218 		if (cookies != NULL)
1219 			cookies[(*ncookies)++] = off = uio->uio_offset;
1220 		/* EOF. */
1221 		if (de == NULL)
1222 			return (0);
1223 		break;
1224 	case TMPFS_DIRCOOKIE_EOF:
1225 		return (0);
1226 	default:
1227 		de = tmpfs_dir_lookup_cookie(node, uio->uio_offset, &dc);
1228 		if (de == NULL)
1229 			return (EINVAL);
1230 		if (cookies != NULL)
1231 			off = tmpfs_dirent_cookie(de);
1232 	}
1233 
1234 	/* Read as much entries as possible; i.e., until we reach the end of
1235 	 * the directory or we exhaust uio space. */
1236 	do {
1237 		struct dirent d;
1238 
1239 		/* Create a dirent structure representing the current
1240 		 * tmpfs_node and fill it. */
1241 		if (de->td_node == NULL) {
1242 			d.d_fileno = 1;
1243 			d.d_type = DT_WHT;
1244 		} else {
1245 			d.d_fileno = de->td_node->tn_id;
1246 			switch (de->td_node->tn_type) {
1247 			case VBLK:
1248 				d.d_type = DT_BLK;
1249 				break;
1250 
1251 			case VCHR:
1252 				d.d_type = DT_CHR;
1253 				break;
1254 
1255 			case VDIR:
1256 				d.d_type = DT_DIR;
1257 				break;
1258 
1259 			case VFIFO:
1260 				d.d_type = DT_FIFO;
1261 				break;
1262 
1263 			case VLNK:
1264 				d.d_type = DT_LNK;
1265 				break;
1266 
1267 			case VREG:
1268 				d.d_type = DT_REG;
1269 				break;
1270 
1271 			case VSOCK:
1272 				d.d_type = DT_SOCK;
1273 				break;
1274 
1275 			default:
1276 				panic("tmpfs_dir_getdents: type %p %d",
1277 				    de->td_node, (int)de->td_node->tn_type);
1278 			}
1279 		}
1280 		d.d_namlen = de->td_namelen;
1281 		MPASS(de->td_namelen < sizeof(d.d_name));
1282 		(void)memcpy(d.d_name, de->ud.td_name, de->td_namelen);
1283 		d.d_name[de->td_namelen] = '\0';
1284 		d.d_reclen = GENERIC_DIRSIZ(&d);
1285 
1286 		/* Stop reading if the directory entry we are treating is
1287 		 * bigger than the amount of data that can be returned. */
1288 		if (d.d_reclen > uio->uio_resid) {
1289 			error = EJUSTRETURN;
1290 			break;
1291 		}
1292 
1293 		/* Copy the new dirent structure into the output buffer and
1294 		 * advance pointers. */
1295 		error = uiomove(&d, d.d_reclen, uio);
1296 		if (error == 0) {
1297 			de = tmpfs_dir_next(node, &dc);
1298 			if (cookies != NULL) {
1299 				off = tmpfs_dirent_cookie(de);
1300 				MPASS(*ncookies < maxcookies);
1301 				cookies[(*ncookies)++] = off;
1302 			}
1303 		}
1304 	} while (error == 0 && uio->uio_resid > 0 && de != NULL);
1305 
1306 	/* Skip setting off when using cookies as it is already done above. */
1307 	if (cookies == NULL)
1308 		off = tmpfs_dirent_cookie(de);
1309 
1310 	/* Update the offset and cache. */
1311 	uio->uio_offset = off;
1312 	node->tn_dir.tn_readdir_lastn = off;
1313 	node->tn_dir.tn_readdir_lastp = de;
1314 
1315 	tmpfs_set_status(node, TMPFS_NODE_ACCESSED);
1316 	return error;
1317 }
1318 
1319 int
1320 tmpfs_dir_whiteout_add(struct vnode *dvp, struct componentname *cnp)
1321 {
1322 	struct tmpfs_dirent *de;
1323 	int error;
1324 
1325 	error = tmpfs_alloc_dirent(VFS_TO_TMPFS(dvp->v_mount), NULL,
1326 	    cnp->cn_nameptr, cnp->cn_namelen, &de);
1327 	if (error != 0)
1328 		return (error);
1329 	tmpfs_dir_attach(dvp, de);
1330 	return (0);
1331 }
1332 
1333 void
1334 tmpfs_dir_whiteout_remove(struct vnode *dvp, struct componentname *cnp)
1335 {
1336 	struct tmpfs_dirent *de;
1337 
1338 	de = tmpfs_dir_lookup(VP_TO_TMPFS_DIR(dvp), NULL, cnp);
1339 	MPASS(de != NULL && de->td_node == NULL);
1340 	tmpfs_dir_detach(dvp, de);
1341 	tmpfs_free_dirent(VFS_TO_TMPFS(dvp->v_mount), de);
1342 }
1343 
1344 /*
1345  * Resizes the aobj associated with the regular file pointed to by 'vp' to the
1346  * size 'newsize'.  'vp' must point to a vnode that represents a regular file.
1347  * 'newsize' must be positive.
1348  *
1349  * Returns zero on success or an appropriate error code on failure.
1350  */
1351 int
1352 tmpfs_reg_resize(struct vnode *vp, off_t newsize, boolean_t ignerr)
1353 {
1354 	struct tmpfs_mount *tmp;
1355 	struct tmpfs_node *node;
1356 	vm_object_t uobj;
1357 	vm_page_t m;
1358 	vm_pindex_t idx, newpages, oldpages;
1359 	off_t oldsize;
1360 	int base, rv;
1361 
1362 	MPASS(vp->v_type == VREG);
1363 	MPASS(newsize >= 0);
1364 
1365 	node = VP_TO_TMPFS_NODE(vp);
1366 	uobj = node->tn_reg.tn_aobj;
1367 	tmp = VFS_TO_TMPFS(vp->v_mount);
1368 
1369 	/*
1370 	 * Convert the old and new sizes to the number of pages needed to
1371 	 * store them.  It may happen that we do not need to do anything
1372 	 * because the last allocated page can accommodate the change on
1373 	 * its own.
1374 	 */
1375 	oldsize = node->tn_size;
1376 	oldpages = OFF_TO_IDX(oldsize + PAGE_MASK);
1377 	MPASS(oldpages == uobj->size);
1378 	newpages = OFF_TO_IDX(newsize + PAGE_MASK);
1379 
1380 	if (__predict_true(newpages == oldpages && newsize >= oldsize)) {
1381 		node->tn_size = newsize;
1382 		return (0);
1383 	}
1384 
1385 	if (newpages > oldpages &&
1386 	    tmpfs_pages_check_avail(tmp, newpages - oldpages) == 0)
1387 		return (ENOSPC);
1388 
1389 	VM_OBJECT_WLOCK(uobj);
1390 	if (newsize < oldsize) {
1391 		/*
1392 		 * Zero the truncated part of the last page.
1393 		 */
1394 		base = newsize & PAGE_MASK;
1395 		if (base != 0) {
1396 			idx = OFF_TO_IDX(newsize);
1397 retry:
1398 			m = vm_page_lookup(uobj, idx);
1399 			if (m != NULL) {
1400 				if (vm_page_sleep_if_busy(m, "tmfssz"))
1401 					goto retry;
1402 				MPASS(m->valid == VM_PAGE_BITS_ALL);
1403 			} else if (vm_pager_has_page(uobj, idx, NULL, NULL)) {
1404 				m = vm_page_alloc(uobj, idx, VM_ALLOC_NORMAL);
1405 				if (m == NULL) {
1406 					VM_OBJECT_WUNLOCK(uobj);
1407 					VM_WAIT;
1408 					VM_OBJECT_WLOCK(uobj);
1409 					goto retry;
1410 				}
1411 				rv = vm_pager_get_pages(uobj, &m, 1, NULL,
1412 				    NULL);
1413 				vm_page_lock(m);
1414 				if (rv == VM_PAGER_OK) {
1415 					/*
1416 					 * Since the page was not resident,
1417 					 * and therefore not recently
1418 					 * accessed, immediately enqueue it
1419 					 * for asynchronous laundering.  The
1420 					 * current operation is not regarded
1421 					 * as an access.
1422 					 */
1423 					vm_page_launder(m);
1424 					vm_page_unlock(m);
1425 					vm_page_xunbusy(m);
1426 				} else {
1427 					vm_page_free(m);
1428 					vm_page_unlock(m);
1429 					if (ignerr)
1430 						m = NULL;
1431 					else {
1432 						VM_OBJECT_WUNLOCK(uobj);
1433 						return (EIO);
1434 					}
1435 				}
1436 			}
1437 			if (m != NULL) {
1438 				pmap_zero_page_area(m, base, PAGE_SIZE - base);
1439 				vm_page_dirty(m);
1440 				vm_pager_page_unswapped(m);
1441 			}
1442 		}
1443 
1444 		/*
1445 		 * Release any swap space and free any whole pages.
1446 		 */
1447 		if (newpages < oldpages) {
1448 			swap_pager_freespace(uobj, newpages, oldpages -
1449 			    newpages);
1450 			vm_object_page_remove(uobj, newpages, 0, 0);
1451 		}
1452 	}
1453 	uobj->size = newpages;
1454 	VM_OBJECT_WUNLOCK(uobj);
1455 
1456 	atomic_add_long(&tmp->tm_pages_used, newpages - oldpages);
1457 
1458 	node->tn_size = newsize;
1459 	return (0);
1460 }
1461 
1462 void
1463 tmpfs_check_mtime(struct vnode *vp)
1464 {
1465 	struct tmpfs_node *node;
1466 	struct vm_object *obj;
1467 
1468 	ASSERT_VOP_ELOCKED(vp, "check_mtime");
1469 	if (vp->v_type != VREG)
1470 		return;
1471 	obj = vp->v_object;
1472 	KASSERT((obj->flags & (OBJ_TMPFS_NODE | OBJ_TMPFS)) ==
1473 	    (OBJ_TMPFS_NODE | OBJ_TMPFS), ("non-tmpfs obj"));
1474 	/* unlocked read */
1475 	if ((obj->flags & OBJ_TMPFS_DIRTY) != 0) {
1476 		VM_OBJECT_WLOCK(obj);
1477 		if ((obj->flags & OBJ_TMPFS_DIRTY) != 0) {
1478 			obj->flags &= ~OBJ_TMPFS_DIRTY;
1479 			node = VP_TO_TMPFS_NODE(vp);
1480 			node->tn_status |= TMPFS_NODE_MODIFIED |
1481 			    TMPFS_NODE_CHANGED;
1482 		}
1483 		VM_OBJECT_WUNLOCK(obj);
1484 	}
1485 }
1486 
1487 /*
1488  * Change flags of the given vnode.
1489  * Caller should execute tmpfs_update on vp after a successful execution.
1490  * The vnode must be locked on entry and remain locked on exit.
1491  */
1492 int
1493 tmpfs_chflags(struct vnode *vp, u_long flags, struct ucred *cred,
1494     struct thread *p)
1495 {
1496 	int error;
1497 	struct tmpfs_node *node;
1498 
1499 	ASSERT_VOP_ELOCKED(vp, "chflags");
1500 
1501 	node = VP_TO_TMPFS_NODE(vp);
1502 
1503 	if ((flags & ~(SF_APPEND | SF_ARCHIVED | SF_IMMUTABLE | SF_NOUNLINK |
1504 	    UF_APPEND | UF_ARCHIVE | UF_HIDDEN | UF_IMMUTABLE | UF_NODUMP |
1505 	    UF_NOUNLINK | UF_OFFLINE | UF_OPAQUE | UF_READONLY | UF_REPARSE |
1506 	    UF_SPARSE | UF_SYSTEM)) != 0)
1507 		return (EOPNOTSUPP);
1508 
1509 	/* Disallow this operation if the file system is mounted read-only. */
1510 	if (vp->v_mount->mnt_flag & MNT_RDONLY)
1511 		return EROFS;
1512 
1513 	/*
1514 	 * Callers may only modify the file flags on objects they
1515 	 * have VADMIN rights for.
1516 	 */
1517 	if ((error = VOP_ACCESS(vp, VADMIN, cred, p)))
1518 		return (error);
1519 	/*
1520 	 * Unprivileged processes are not permitted to unset system
1521 	 * flags, or modify flags if any system flags are set.
1522 	 */
1523 	if (!priv_check_cred(cred, PRIV_VFS_SYSFLAGS, 0)) {
1524 		if (node->tn_flags &
1525 		    (SF_NOUNLINK | SF_IMMUTABLE | SF_APPEND)) {
1526 			error = securelevel_gt(cred, 0);
1527 			if (error)
1528 				return (error);
1529 		}
1530 	} else {
1531 		if (node->tn_flags &
1532 		    (SF_NOUNLINK | SF_IMMUTABLE | SF_APPEND) ||
1533 		    ((flags ^ node->tn_flags) & SF_SETTABLE))
1534 			return (EPERM);
1535 	}
1536 	node->tn_flags = flags;
1537 	node->tn_status |= TMPFS_NODE_CHANGED;
1538 
1539 	ASSERT_VOP_ELOCKED(vp, "chflags2");
1540 
1541 	return (0);
1542 }
1543 
1544 /*
1545  * Change access mode on the given vnode.
1546  * Caller should execute tmpfs_update on vp after a successful execution.
1547  * The vnode must be locked on entry and remain locked on exit.
1548  */
1549 int
1550 tmpfs_chmod(struct vnode *vp, mode_t mode, struct ucred *cred, struct thread *p)
1551 {
1552 	int error;
1553 	struct tmpfs_node *node;
1554 
1555 	ASSERT_VOP_ELOCKED(vp, "chmod");
1556 
1557 	node = VP_TO_TMPFS_NODE(vp);
1558 
1559 	/* Disallow this operation if the file system is mounted read-only. */
1560 	if (vp->v_mount->mnt_flag & MNT_RDONLY)
1561 		return EROFS;
1562 
1563 	/* Immutable or append-only files cannot be modified, either. */
1564 	if (node->tn_flags & (IMMUTABLE | APPEND))
1565 		return EPERM;
1566 
1567 	/*
1568 	 * To modify the permissions on a file, must possess VADMIN
1569 	 * for that file.
1570 	 */
1571 	if ((error = VOP_ACCESS(vp, VADMIN, cred, p)))
1572 		return (error);
1573 
1574 	/*
1575 	 * Privileged processes may set the sticky bit on non-directories,
1576 	 * as well as set the setgid bit on a file with a group that the
1577 	 * process is not a member of.
1578 	 */
1579 	if (vp->v_type != VDIR && (mode & S_ISTXT)) {
1580 		if (priv_check_cred(cred, PRIV_VFS_STICKYFILE, 0))
1581 			return (EFTYPE);
1582 	}
1583 	if (!groupmember(node->tn_gid, cred) && (mode & S_ISGID)) {
1584 		error = priv_check_cred(cred, PRIV_VFS_SETGID, 0);
1585 		if (error)
1586 			return (error);
1587 	}
1588 
1589 
1590 	node->tn_mode &= ~ALLPERMS;
1591 	node->tn_mode |= mode & ALLPERMS;
1592 
1593 	node->tn_status |= TMPFS_NODE_CHANGED;
1594 
1595 	ASSERT_VOP_ELOCKED(vp, "chmod2");
1596 
1597 	return (0);
1598 }
1599 
1600 /*
1601  * Change ownership of the given vnode.  At least one of uid or gid must
1602  * be different than VNOVAL.  If one is set to that value, the attribute
1603  * is unchanged.
1604  * Caller should execute tmpfs_update on vp after a successful execution.
1605  * The vnode must be locked on entry and remain locked on exit.
1606  */
1607 int
1608 tmpfs_chown(struct vnode *vp, uid_t uid, gid_t gid, struct ucred *cred,
1609     struct thread *p)
1610 {
1611 	int error;
1612 	struct tmpfs_node *node;
1613 	uid_t ouid;
1614 	gid_t ogid;
1615 
1616 	ASSERT_VOP_ELOCKED(vp, "chown");
1617 
1618 	node = VP_TO_TMPFS_NODE(vp);
1619 
1620 	/* Assign default values if they are unknown. */
1621 	MPASS(uid != VNOVAL || gid != VNOVAL);
1622 	if (uid == VNOVAL)
1623 		uid = node->tn_uid;
1624 	if (gid == VNOVAL)
1625 		gid = node->tn_gid;
1626 	MPASS(uid != VNOVAL && gid != VNOVAL);
1627 
1628 	/* Disallow this operation if the file system is mounted read-only. */
1629 	if (vp->v_mount->mnt_flag & MNT_RDONLY)
1630 		return EROFS;
1631 
1632 	/* Immutable or append-only files cannot be modified, either. */
1633 	if (node->tn_flags & (IMMUTABLE | APPEND))
1634 		return EPERM;
1635 
1636 	/*
1637 	 * To modify the ownership of a file, must possess VADMIN for that
1638 	 * file.
1639 	 */
1640 	if ((error = VOP_ACCESS(vp, VADMIN, cred, p)))
1641 		return (error);
1642 
1643 	/*
1644 	 * To change the owner of a file, or change the group of a file to a
1645 	 * group of which we are not a member, the caller must have
1646 	 * privilege.
1647 	 */
1648 	if ((uid != node->tn_uid ||
1649 	    (gid != node->tn_gid && !groupmember(gid, cred))) &&
1650 	    (error = priv_check_cred(cred, PRIV_VFS_CHOWN, 0)))
1651 		return (error);
1652 
1653 	ogid = node->tn_gid;
1654 	ouid = node->tn_uid;
1655 
1656 	node->tn_uid = uid;
1657 	node->tn_gid = gid;
1658 
1659 	node->tn_status |= TMPFS_NODE_CHANGED;
1660 
1661 	if ((node->tn_mode & (S_ISUID | S_ISGID)) && (ouid != uid || ogid != gid)) {
1662 		if (priv_check_cred(cred, PRIV_VFS_RETAINSUGID, 0))
1663 			node->tn_mode &= ~(S_ISUID | S_ISGID);
1664 	}
1665 
1666 	ASSERT_VOP_ELOCKED(vp, "chown2");
1667 
1668 	return (0);
1669 }
1670 
1671 /*
1672  * Change size of the given vnode.
1673  * Caller should execute tmpfs_update on vp after a successful execution.
1674  * The vnode must be locked on entry and remain locked on exit.
1675  */
1676 int
1677 tmpfs_chsize(struct vnode *vp, u_quad_t size, struct ucred *cred,
1678     struct thread *p)
1679 {
1680 	int error;
1681 	struct tmpfs_node *node;
1682 
1683 	ASSERT_VOP_ELOCKED(vp, "chsize");
1684 
1685 	node = VP_TO_TMPFS_NODE(vp);
1686 
1687 	/* Decide whether this is a valid operation based on the file type. */
1688 	error = 0;
1689 	switch (vp->v_type) {
1690 	case VDIR:
1691 		return EISDIR;
1692 
1693 	case VREG:
1694 		if (vp->v_mount->mnt_flag & MNT_RDONLY)
1695 			return EROFS;
1696 		break;
1697 
1698 	case VBLK:
1699 		/* FALLTHROUGH */
1700 	case VCHR:
1701 		/* FALLTHROUGH */
1702 	case VFIFO:
1703 		/* Allow modifications of special files even if in the file
1704 		 * system is mounted read-only (we are not modifying the
1705 		 * files themselves, but the objects they represent). */
1706 		return 0;
1707 
1708 	default:
1709 		/* Anything else is unsupported. */
1710 		return EOPNOTSUPP;
1711 	}
1712 
1713 	/* Immutable or append-only files cannot be modified, either. */
1714 	if (node->tn_flags & (IMMUTABLE | APPEND))
1715 		return EPERM;
1716 
1717 	error = tmpfs_truncate(vp, size);
1718 	/* tmpfs_truncate will raise the NOTE_EXTEND and NOTE_ATTRIB kevents
1719 	 * for us, as will update tn_status; no need to do that here. */
1720 
1721 	ASSERT_VOP_ELOCKED(vp, "chsize2");
1722 
1723 	return (error);
1724 }
1725 
1726 /*
1727  * Change access and modification times of the given vnode.
1728  * Caller should execute tmpfs_update on vp after a successful execution.
1729  * The vnode must be locked on entry and remain locked on exit.
1730  */
1731 int
1732 tmpfs_chtimes(struct vnode *vp, struct vattr *vap,
1733     struct ucred *cred, struct thread *l)
1734 {
1735 	int error;
1736 	struct tmpfs_node *node;
1737 
1738 	ASSERT_VOP_ELOCKED(vp, "chtimes");
1739 
1740 	node = VP_TO_TMPFS_NODE(vp);
1741 
1742 	/* Disallow this operation if the file system is mounted read-only. */
1743 	if (vp->v_mount->mnt_flag & MNT_RDONLY)
1744 		return EROFS;
1745 
1746 	/* Immutable or append-only files cannot be modified, either. */
1747 	if (node->tn_flags & (IMMUTABLE | APPEND))
1748 		return EPERM;
1749 
1750 	error = vn_utimes_perm(vp, vap, cred, l);
1751 	if (error != 0)
1752 		return (error);
1753 
1754 	if (vap->va_atime.tv_sec != VNOVAL)
1755 		node->tn_status |= TMPFS_NODE_ACCESSED;
1756 
1757 	if (vap->va_mtime.tv_sec != VNOVAL)
1758 		node->tn_status |= TMPFS_NODE_MODIFIED;
1759 
1760 	if (vap->va_birthtime.tv_sec != VNOVAL)
1761 		node->tn_status |= TMPFS_NODE_MODIFIED;
1762 
1763 	tmpfs_itimes(vp, &vap->va_atime, &vap->va_mtime);
1764 
1765 	if (vap->va_birthtime.tv_sec != VNOVAL)
1766 		node->tn_birthtime = vap->va_birthtime;
1767 	ASSERT_VOP_ELOCKED(vp, "chtimes2");
1768 
1769 	return (0);
1770 }
1771 
1772 void
1773 tmpfs_set_status(struct tmpfs_node *node, int status)
1774 {
1775 
1776 	if ((node->tn_status & status) == status)
1777 		return;
1778 	TMPFS_NODE_LOCK(node);
1779 	node->tn_status |= status;
1780 	TMPFS_NODE_UNLOCK(node);
1781 }
1782 
1783 /* Sync timestamps */
1784 void
1785 tmpfs_itimes(struct vnode *vp, const struct timespec *acc,
1786     const struct timespec *mod)
1787 {
1788 	struct tmpfs_node *node;
1789 	struct timespec now;
1790 
1791 	ASSERT_VOP_LOCKED(vp, "tmpfs_itimes");
1792 	node = VP_TO_TMPFS_NODE(vp);
1793 
1794 	if ((node->tn_status & (TMPFS_NODE_ACCESSED | TMPFS_NODE_MODIFIED |
1795 	    TMPFS_NODE_CHANGED)) == 0)
1796 		return;
1797 
1798 	vfs_timestamp(&now);
1799 	TMPFS_NODE_LOCK(node);
1800 	if (node->tn_status & TMPFS_NODE_ACCESSED) {
1801 		if (acc == NULL)
1802 			 acc = &now;
1803 		node->tn_atime = *acc;
1804 	}
1805 	if (node->tn_status & TMPFS_NODE_MODIFIED) {
1806 		if (mod == NULL)
1807 			mod = &now;
1808 		node->tn_mtime = *mod;
1809 	}
1810 	if (node->tn_status & TMPFS_NODE_CHANGED)
1811 		node->tn_ctime = now;
1812 	node->tn_status &= ~(TMPFS_NODE_ACCESSED | TMPFS_NODE_MODIFIED |
1813 	    TMPFS_NODE_CHANGED);
1814 	TMPFS_NODE_UNLOCK(node);
1815 
1816 	/* XXX: FIX? The entropy here is desirable, but the harvesting may be expensive */
1817 	random_harvest_queue(node, sizeof(*node), 1, RANDOM_FS_ATIME);
1818 }
1819 
1820 void
1821 tmpfs_update(struct vnode *vp)
1822 {
1823 
1824 	tmpfs_itimes(vp, NULL, NULL);
1825 }
1826 
1827 int
1828 tmpfs_truncate(struct vnode *vp, off_t length)
1829 {
1830 	int error;
1831 	struct tmpfs_node *node;
1832 
1833 	node = VP_TO_TMPFS_NODE(vp);
1834 
1835 	if (length < 0) {
1836 		error = EINVAL;
1837 		goto out;
1838 	}
1839 
1840 	if (node->tn_size == length) {
1841 		error = 0;
1842 		goto out;
1843 	}
1844 
1845 	if (length > VFS_TO_TMPFS(vp->v_mount)->tm_maxfilesize)
1846 		return (EFBIG);
1847 
1848 	error = tmpfs_reg_resize(vp, length, FALSE);
1849 	if (error == 0)
1850 		node->tn_status |= TMPFS_NODE_CHANGED | TMPFS_NODE_MODIFIED;
1851 
1852 out:
1853 	tmpfs_update(vp);
1854 
1855 	return (error);
1856 }
1857 
1858 static __inline int
1859 tmpfs_dirtree_cmp(struct tmpfs_dirent *a, struct tmpfs_dirent *b)
1860 {
1861 	if (a->td_hash > b->td_hash)
1862 		return (1);
1863 	else if (a->td_hash < b->td_hash)
1864 		return (-1);
1865 	return (0);
1866 }
1867 
1868 RB_GENERATE_STATIC(tmpfs_dir, tmpfs_dirent, uh.td_entries, tmpfs_dirtree_cmp);
1869