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