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