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