tmpfs_subr.c revision 269170
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 269170 2014-07-28 01:08:43Z 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);
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	(void) vn_lock(vp, lkflag | LK_RETRY);
552
553	vp->v_data = node;
554	vp->v_type = node->tn_type;
555
556	/* Type-specific initialization. */
557	switch (node->tn_type) {
558	case VBLK:
559		/* FALLTHROUGH */
560	case VCHR:
561		/* FALLTHROUGH */
562	case VLNK:
563		/* FALLTHROUGH */
564	case VSOCK:
565		break;
566	case VFIFO:
567		vp->v_op = &tmpfs_fifoop_entries;
568		break;
569	case VREG:
570		object = node->tn_reg.tn_aobj;
571		VM_OBJECT_WLOCK(object);
572		VI_LOCK(vp);
573		KASSERT(vp->v_object == NULL, ("Not NULL v_object in tmpfs"));
574		vp->v_object = object;
575		object->un_pager.swp.swp_tmpfs = vp;
576		vm_object_set_flag(object, OBJ_TMPFS);
577		VI_UNLOCK(vp);
578		VM_OBJECT_WUNLOCK(object);
579		break;
580	case VDIR:
581		MPASS(node->tn_dir.tn_parent != NULL);
582		if (node->tn_dir.tn_parent == node)
583			vp->v_vflag |= VV_ROOT;
584		break;
585
586	default:
587		panic("tmpfs_alloc_vp: type %p %d", node, (int)node->tn_type);
588	}
589	if (vp->v_type != VFIFO)
590		VN_LOCK_ASHARE(vp);
591
592	error = insmntque1(vp, mp, tmpfs_insmntque_dtr, NULL);
593	if (error)
594		vp = NULL;
595
596unlock:
597	TMPFS_NODE_LOCK(node);
598
599	MPASS(node->tn_vpstate & TMPFS_VNODE_ALLOCATING);
600	node->tn_vpstate &= ~TMPFS_VNODE_ALLOCATING;
601	node->tn_vnode = vp;
602
603	if (node->tn_vpstate & TMPFS_VNODE_WANT) {
604		node->tn_vpstate &= ~TMPFS_VNODE_WANT;
605		TMPFS_NODE_UNLOCK(node);
606		wakeup((caddr_t) &node->tn_vpstate);
607	} else
608		TMPFS_NODE_UNLOCK(node);
609
610out:
611	*vpp = vp;
612
613#ifdef INVARIANTS
614	if (error == 0) {
615		MPASS(*vpp != NULL && VOP_ISLOCKED(*vpp));
616		TMPFS_NODE_LOCK(node);
617		MPASS(*vpp == node->tn_vnode);
618		TMPFS_NODE_UNLOCK(node);
619	}
620#endif
621
622	return error;
623}
624
625/*
626 * Destroys the association between the vnode vp and the node it
627 * references.
628 */
629void
630tmpfs_free_vp(struct vnode *vp)
631{
632	struct tmpfs_node *node;
633
634	node = VP_TO_TMPFS_NODE(vp);
635
636	TMPFS_NODE_ASSERT_LOCKED(node);
637	node->tn_vnode = NULL;
638	if ((node->tn_vpstate & TMPFS_VNODE_WRECLAIM) != 0)
639		wakeup(&node->tn_vnode);
640	node->tn_vpstate &= ~TMPFS_VNODE_WRECLAIM;
641	vp->v_data = NULL;
642}
643
644/*
645 * Allocates a new file of type 'type' and adds it to the parent directory
646 * 'dvp'; this addition is done using the component name given in 'cnp'.
647 * The ownership of the new file is automatically assigned based on the
648 * credentials of the caller (through 'cnp'), the group is set based on
649 * the parent directory and the mode is determined from the 'vap' argument.
650 * If successful, *vpp holds a vnode to the newly created file and zero
651 * is returned.  Otherwise *vpp is NULL and the function returns an
652 * appropriate error code.
653 */
654int
655tmpfs_alloc_file(struct vnode *dvp, struct vnode **vpp, struct vattr *vap,
656    struct componentname *cnp, char *target)
657{
658	int error;
659	struct tmpfs_dirent *de;
660	struct tmpfs_mount *tmp;
661	struct tmpfs_node *dnode;
662	struct tmpfs_node *node;
663	struct tmpfs_node *parent;
664
665	MPASS(VOP_ISLOCKED(dvp));
666	MPASS(cnp->cn_flags & HASBUF);
667
668	tmp = VFS_TO_TMPFS(dvp->v_mount);
669	dnode = VP_TO_TMPFS_DIR(dvp);
670	*vpp = NULL;
671
672	/* If the entry we are creating is a directory, we cannot overflow
673	 * the number of links of its parent, because it will get a new
674	 * link. */
675	if (vap->va_type == VDIR) {
676		/* Ensure that we do not overflow the maximum number of links
677		 * imposed by the system. */
678		MPASS(dnode->tn_links <= LINK_MAX);
679		if (dnode->tn_links == LINK_MAX) {
680			return (EMLINK);
681		}
682
683		parent = dnode;
684		MPASS(parent != NULL);
685	} else
686		parent = NULL;
687
688	/* Allocate a node that represents the new file. */
689	error = tmpfs_alloc_node(tmp, vap->va_type, cnp->cn_cred->cr_uid,
690	    dnode->tn_gid, vap->va_mode, parent, target, vap->va_rdev, &node);
691	if (error != 0)
692		return (error);
693
694	/* Allocate a directory entry that points to the new file. */
695	error = tmpfs_alloc_dirent(tmp, node, cnp->cn_nameptr, cnp->cn_namelen,
696	    &de);
697	if (error != 0) {
698		tmpfs_free_node(tmp, node);
699		return (error);
700	}
701
702	/* Allocate a vnode for the new file. */
703	error = tmpfs_alloc_vp(dvp->v_mount, node, LK_EXCLUSIVE, vpp);
704	if (error != 0) {
705		tmpfs_free_dirent(tmp, de);
706		tmpfs_free_node(tmp, node);
707		return (error);
708	}
709
710	/* Now that all required items are allocated, we can proceed to
711	 * insert the new node into the directory, an operation that
712	 * cannot fail. */
713	if (cnp->cn_flags & ISWHITEOUT)
714		tmpfs_dir_whiteout_remove(dvp, cnp);
715	tmpfs_dir_attach(dvp, de);
716	return (0);
717}
718
719static struct tmpfs_dirent *
720tmpfs_dir_first(struct tmpfs_node *dnode, struct tmpfs_dir_cursor *dc)
721{
722	struct tmpfs_dirent *de;
723
724	de = RB_MIN(tmpfs_dir, &dnode->tn_dir.tn_dirhead);
725	dc->tdc_tree = de;
726	if (de != NULL && tmpfs_dirent_duphead(de))
727		de = LIST_FIRST(&de->ud.td_duphead);
728	dc->tdc_current = de;
729
730	return (dc->tdc_current);
731}
732
733static struct tmpfs_dirent *
734tmpfs_dir_next(struct tmpfs_node *dnode, struct tmpfs_dir_cursor *dc)
735{
736	struct tmpfs_dirent *de;
737
738	MPASS(dc->tdc_tree != NULL);
739	if (tmpfs_dirent_dup(dc->tdc_current)) {
740		dc->tdc_current = LIST_NEXT(dc->tdc_current, uh.td_dup.entries);
741		if (dc->tdc_current != NULL)
742			return (dc->tdc_current);
743	}
744	dc->tdc_tree = dc->tdc_current = RB_NEXT(tmpfs_dir,
745	    &dnode->tn_dir.tn_dirhead, dc->tdc_tree);
746	if ((de = dc->tdc_current) != NULL && tmpfs_dirent_duphead(de)) {
747		dc->tdc_current = LIST_FIRST(&de->ud.td_duphead);
748		MPASS(dc->tdc_current != NULL);
749	}
750
751	return (dc->tdc_current);
752}
753
754/* Lookup directory entry in RB-Tree. Function may return duphead entry. */
755static struct tmpfs_dirent *
756tmpfs_dir_xlookup_hash(struct tmpfs_node *dnode, uint32_t hash)
757{
758	struct tmpfs_dirent *de, dekey;
759
760	dekey.td_hash = hash;
761	de = RB_FIND(tmpfs_dir, &dnode->tn_dir.tn_dirhead, &dekey);
762	return (de);
763}
764
765/* Lookup directory entry by cookie, initialize directory cursor accordingly. */
766static struct tmpfs_dirent *
767tmpfs_dir_lookup_cookie(struct tmpfs_node *node, off_t cookie,
768    struct tmpfs_dir_cursor *dc)
769{
770	struct tmpfs_dir *dirhead = &node->tn_dir.tn_dirhead;
771	struct tmpfs_dirent *de, dekey;
772
773	MPASS(cookie >= TMPFS_DIRCOOKIE_MIN);
774
775	if (cookie == node->tn_dir.tn_readdir_lastn &&
776	    (de = node->tn_dir.tn_readdir_lastp) != NULL) {
777		/* Protect against possible race, tn_readdir_last[pn]
778		 * may be updated with only shared vnode lock held. */
779		if (cookie == tmpfs_dirent_cookie(de))
780			goto out;
781	}
782
783	if ((cookie & TMPFS_DIRCOOKIE_DUP) != 0) {
784		LIST_FOREACH(de, &node->tn_dir.tn_dupindex,
785		    uh.td_dup.index_entries) {
786			MPASS(tmpfs_dirent_dup(de));
787			if (de->td_cookie == cookie)
788				goto out;
789			/* dupindex list is sorted. */
790			if (de->td_cookie < cookie) {
791				de = NULL;
792				goto out;
793			}
794		}
795		MPASS(de == NULL);
796		goto out;
797	}
798
799	MPASS((cookie & TMPFS_DIRCOOKIE_MASK) == cookie);
800	dekey.td_hash = cookie;
801	/* Recover if direntry for cookie was removed */
802	de = RB_NFIND(tmpfs_dir, dirhead, &dekey);
803	dc->tdc_tree = de;
804	dc->tdc_current = de;
805	if (de != NULL && tmpfs_dirent_duphead(de)) {
806		dc->tdc_current = LIST_FIRST(&de->ud.td_duphead);
807		MPASS(dc->tdc_current != NULL);
808	}
809	return (dc->tdc_current);
810
811out:
812	dc->tdc_tree = de;
813	dc->tdc_current = de;
814	if (de != NULL && tmpfs_dirent_dup(de))
815		dc->tdc_tree = tmpfs_dir_xlookup_hash(node,
816		    de->td_hash);
817	return (dc->tdc_current);
818}
819
820/*
821 * Looks for a directory entry in the directory represented by node.
822 * 'cnp' describes the name of the entry to look for.  Note that the .
823 * and .. components are not allowed as they do not physically exist
824 * within directories.
825 *
826 * Returns a pointer to the entry when found, otherwise NULL.
827 */
828struct tmpfs_dirent *
829tmpfs_dir_lookup(struct tmpfs_node *node, struct tmpfs_node *f,
830    struct componentname *cnp)
831{
832	struct tmpfs_dir_duphead *duphead;
833	struct tmpfs_dirent *de;
834	uint32_t hash;
835
836	MPASS(IMPLIES(cnp->cn_namelen == 1, cnp->cn_nameptr[0] != '.'));
837	MPASS(IMPLIES(cnp->cn_namelen == 2, !(cnp->cn_nameptr[0] == '.' &&
838	    cnp->cn_nameptr[1] == '.')));
839	TMPFS_VALIDATE_DIR(node);
840
841	hash = tmpfs_dirent_hash(cnp->cn_nameptr, cnp->cn_namelen);
842	de = tmpfs_dir_xlookup_hash(node, hash);
843	if (de != NULL && tmpfs_dirent_duphead(de)) {
844		duphead = &de->ud.td_duphead;
845		LIST_FOREACH(de, duphead, uh.td_dup.entries) {
846			if (TMPFS_DIRENT_MATCHES(de, cnp->cn_nameptr,
847			    cnp->cn_namelen))
848				break;
849		}
850	} else if (de != NULL) {
851		if (!TMPFS_DIRENT_MATCHES(de, cnp->cn_nameptr,
852		    cnp->cn_namelen))
853			de = NULL;
854	}
855	if (de != NULL && f != NULL && de->td_node != f)
856		de = NULL;
857
858	return (de);
859}
860
861/*
862 * Attach duplicate-cookie directory entry nde to dnode and insert to dupindex
863 * list, allocate new cookie value.
864 */
865static void
866tmpfs_dir_attach_dup(struct tmpfs_node *dnode,
867    struct tmpfs_dir_duphead *duphead, struct tmpfs_dirent *nde)
868{
869	struct tmpfs_dir_duphead *dupindex;
870	struct tmpfs_dirent *de, *pde;
871
872	dupindex = &dnode->tn_dir.tn_dupindex;
873	de = LIST_FIRST(dupindex);
874	if (de == NULL || de->td_cookie < TMPFS_DIRCOOKIE_DUP_MAX) {
875		if (de == NULL)
876			nde->td_cookie = TMPFS_DIRCOOKIE_DUP_MIN;
877		else
878			nde->td_cookie = de->td_cookie + 1;
879		MPASS(tmpfs_dirent_dup(nde));
880		LIST_INSERT_HEAD(dupindex, nde, uh.td_dup.index_entries);
881		LIST_INSERT_HEAD(duphead, nde, uh.td_dup.entries);
882		return;
883	}
884
885	/*
886	 * Cookie numbers are near exhaustion. Scan dupindex list for unused
887	 * numbers. dupindex list is sorted in descending order. Keep it so
888	 * after inserting nde.
889	 */
890	while (1) {
891		pde = de;
892		de = LIST_NEXT(de, uh.td_dup.index_entries);
893		if (de == NULL && pde->td_cookie != TMPFS_DIRCOOKIE_DUP_MIN) {
894			/*
895			 * Last element of the index doesn't have minimal cookie
896			 * value, use it.
897			 */
898			nde->td_cookie = TMPFS_DIRCOOKIE_DUP_MIN;
899			LIST_INSERT_AFTER(pde, nde, uh.td_dup.index_entries);
900			LIST_INSERT_HEAD(duphead, nde, uh.td_dup.entries);
901			return;
902		} else if (de == NULL) {
903			/*
904			 * We are so lucky have 2^30 hash duplicates in single
905			 * directory :) Return largest possible cookie value.
906			 * It should be fine except possible issues with
907			 * VOP_READDIR restart.
908			 */
909			nde->td_cookie = TMPFS_DIRCOOKIE_DUP_MAX;
910			LIST_INSERT_HEAD(dupindex, nde,
911			    uh.td_dup.index_entries);
912			LIST_INSERT_HEAD(duphead, nde, uh.td_dup.entries);
913			return;
914		}
915		if (de->td_cookie + 1 == pde->td_cookie ||
916		    de->td_cookie >= TMPFS_DIRCOOKIE_DUP_MAX)
917			continue;	/* No hole or invalid cookie. */
918		nde->td_cookie = de->td_cookie + 1;
919		MPASS(tmpfs_dirent_dup(nde));
920		MPASS(pde->td_cookie > nde->td_cookie);
921		MPASS(nde->td_cookie > de->td_cookie);
922		LIST_INSERT_BEFORE(de, nde, uh.td_dup.index_entries);
923		LIST_INSERT_HEAD(duphead, nde, uh.td_dup.entries);
924		return;
925	};
926}
927
928/*
929 * Attaches the directory entry de to the directory represented by vp.
930 * Note that this does not change the link count of the node pointed by
931 * the directory entry, as this is done by tmpfs_alloc_dirent.
932 */
933void
934tmpfs_dir_attach(struct vnode *vp, struct tmpfs_dirent *de)
935{
936	struct tmpfs_node *dnode;
937	struct tmpfs_dirent *xde, *nde;
938
939	ASSERT_VOP_ELOCKED(vp, __func__);
940	MPASS(de->td_namelen > 0);
941	MPASS(de->td_hash >= TMPFS_DIRCOOKIE_MIN);
942	MPASS(de->td_cookie == de->td_hash);
943
944	dnode = VP_TO_TMPFS_DIR(vp);
945	dnode->tn_dir.tn_readdir_lastn = 0;
946	dnode->tn_dir.tn_readdir_lastp = NULL;
947
948	MPASS(!tmpfs_dirent_dup(de));
949	xde = RB_INSERT(tmpfs_dir, &dnode->tn_dir.tn_dirhead, de);
950	if (xde != NULL && tmpfs_dirent_duphead(xde))
951		tmpfs_dir_attach_dup(dnode, &xde->ud.td_duphead, de);
952	else if (xde != NULL) {
953		/*
954		 * Allocate new duphead. Swap xde with duphead to avoid
955		 * adding/removing elements with the same hash.
956		 */
957		MPASS(!tmpfs_dirent_dup(xde));
958		tmpfs_alloc_dirent(VFS_TO_TMPFS(vp->v_mount), NULL, NULL, 0,
959		    &nde);
960		/* *nde = *xde; XXX gcc 4.2.1 may generate invalid code. */
961		memcpy(nde, xde, sizeof(*xde));
962		xde->td_cookie |= TMPFS_DIRCOOKIE_DUPHEAD;
963		LIST_INIT(&xde->ud.td_duphead);
964		xde->td_namelen = 0;
965		xde->td_node = NULL;
966		tmpfs_dir_attach_dup(dnode, &xde->ud.td_duphead, nde);
967		tmpfs_dir_attach_dup(dnode, &xde->ud.td_duphead, de);
968	}
969	dnode->tn_size += sizeof(struct tmpfs_dirent);
970	dnode->tn_status |= TMPFS_NODE_ACCESSED | TMPFS_NODE_CHANGED | \
971	    TMPFS_NODE_MODIFIED;
972}
973
974/*
975 * Detaches the directory entry de from the directory represented by vp.
976 * Note that this does not change the link count of the node pointed by
977 * the directory entry, as this is done by tmpfs_free_dirent.
978 */
979void
980tmpfs_dir_detach(struct vnode *vp, struct tmpfs_dirent *de)
981{
982	struct tmpfs_mount *tmp;
983	struct tmpfs_dir *head;
984	struct tmpfs_node *dnode;
985	struct tmpfs_dirent *xde;
986
987	ASSERT_VOP_ELOCKED(vp, __func__);
988
989	dnode = VP_TO_TMPFS_DIR(vp);
990	head = &dnode->tn_dir.tn_dirhead;
991	dnode->tn_dir.tn_readdir_lastn = 0;
992	dnode->tn_dir.tn_readdir_lastp = NULL;
993
994	if (tmpfs_dirent_dup(de)) {
995		/* Remove duphead if de was last entry. */
996		if (LIST_NEXT(de, uh.td_dup.entries) == NULL) {
997			xde = tmpfs_dir_xlookup_hash(dnode, de->td_hash);
998			MPASS(tmpfs_dirent_duphead(xde));
999		} else
1000			xde = NULL;
1001		LIST_REMOVE(de, uh.td_dup.entries);
1002		LIST_REMOVE(de, uh.td_dup.index_entries);
1003		if (xde != NULL) {
1004			if (LIST_EMPTY(&xde->ud.td_duphead)) {
1005				RB_REMOVE(tmpfs_dir, head, xde);
1006				tmp = VFS_TO_TMPFS(vp->v_mount);
1007				MPASS(xde->td_node == NULL);
1008				tmpfs_free_dirent(tmp, xde);
1009			}
1010		}
1011	} else
1012		RB_REMOVE(tmpfs_dir, head, de);
1013
1014	dnode->tn_size -= sizeof(struct tmpfs_dirent);
1015	dnode->tn_status |= TMPFS_NODE_ACCESSED | TMPFS_NODE_CHANGED | \
1016	    TMPFS_NODE_MODIFIED;
1017}
1018
1019void
1020tmpfs_dir_destroy(struct tmpfs_mount *tmp, struct tmpfs_node *dnode)
1021{
1022	struct tmpfs_dirent *de, *dde, *nde;
1023
1024	RB_FOREACH_SAFE(de, tmpfs_dir, &dnode->tn_dir.tn_dirhead, nde) {
1025		RB_REMOVE(tmpfs_dir, &dnode->tn_dir.tn_dirhead, de);
1026		/* Node may already be destroyed. */
1027		de->td_node = NULL;
1028		if (tmpfs_dirent_duphead(de)) {
1029			while ((dde = LIST_FIRST(&de->ud.td_duphead)) != NULL) {
1030				LIST_REMOVE(dde, uh.td_dup.entries);
1031				dde->td_node = NULL;
1032				tmpfs_free_dirent(tmp, dde);
1033			}
1034		}
1035		tmpfs_free_dirent(tmp, de);
1036	}
1037}
1038
1039/*
1040 * Helper function for tmpfs_readdir.  Creates a '.' entry for the given
1041 * directory and returns it in the uio space.  The function returns 0
1042 * on success, -1 if there was not enough space in the uio structure to
1043 * hold the directory entry or an appropriate error code if another
1044 * error happens.
1045 */
1046static int
1047tmpfs_dir_getdotdent(struct tmpfs_node *node, struct uio *uio)
1048{
1049	int error;
1050	struct dirent dent;
1051
1052	TMPFS_VALIDATE_DIR(node);
1053	MPASS(uio->uio_offset == TMPFS_DIRCOOKIE_DOT);
1054
1055	dent.d_fileno = node->tn_id;
1056	dent.d_type = DT_DIR;
1057	dent.d_namlen = 1;
1058	dent.d_name[0] = '.';
1059	dent.d_name[1] = '\0';
1060	dent.d_reclen = GENERIC_DIRSIZ(&dent);
1061
1062	if (dent.d_reclen > uio->uio_resid)
1063		error = EJUSTRETURN;
1064	else
1065		error = uiomove(&dent, dent.d_reclen, uio);
1066
1067	node->tn_status |= TMPFS_NODE_ACCESSED;
1068
1069	return error;
1070}
1071
1072/*
1073 * Helper function for tmpfs_readdir.  Creates a '..' entry for the given
1074 * directory and returns it in the uio space.  The function returns 0
1075 * on success, -1 if there was not enough space in the uio structure to
1076 * hold the directory entry or an appropriate error code if another
1077 * error happens.
1078 */
1079static int
1080tmpfs_dir_getdotdotdent(struct tmpfs_node *node, struct uio *uio)
1081{
1082	int error;
1083	struct dirent dent;
1084
1085	TMPFS_VALIDATE_DIR(node);
1086	MPASS(uio->uio_offset == TMPFS_DIRCOOKIE_DOTDOT);
1087
1088	/*
1089	 * Return ENOENT if the current node is already removed.
1090	 */
1091	TMPFS_ASSERT_LOCKED(node);
1092	if (node->tn_dir.tn_parent == NULL) {
1093		return (ENOENT);
1094	}
1095
1096	TMPFS_NODE_LOCK(node->tn_dir.tn_parent);
1097	dent.d_fileno = node->tn_dir.tn_parent->tn_id;
1098	TMPFS_NODE_UNLOCK(node->tn_dir.tn_parent);
1099
1100	dent.d_type = DT_DIR;
1101	dent.d_namlen = 2;
1102	dent.d_name[0] = '.';
1103	dent.d_name[1] = '.';
1104	dent.d_name[2] = '\0';
1105	dent.d_reclen = GENERIC_DIRSIZ(&dent);
1106
1107	if (dent.d_reclen > uio->uio_resid)
1108		error = EJUSTRETURN;
1109	else
1110		error = uiomove(&dent, dent.d_reclen, uio);
1111
1112	node->tn_status |= TMPFS_NODE_ACCESSED;
1113
1114	return error;
1115}
1116
1117/*
1118 * Helper function for tmpfs_readdir.  Returns as much directory entries
1119 * as can fit in the uio space.  The read starts at uio->uio_offset.
1120 * The function returns 0 on success, -1 if there was not enough space
1121 * in the uio structure to hold the directory entry or an appropriate
1122 * error code if another error happens.
1123 */
1124int
1125tmpfs_dir_getdents(struct tmpfs_node *node, struct uio *uio, int maxcookies,
1126    u_long *cookies, int *ncookies)
1127{
1128	struct tmpfs_dir_cursor dc;
1129	struct tmpfs_dirent *de;
1130	off_t off;
1131	int error;
1132
1133	TMPFS_VALIDATE_DIR(node);
1134
1135	off = 0;
1136
1137	/*
1138	 * Lookup the node from the current offset.  The starting offset of
1139	 * 0 will lookup both '.' and '..', and then the first real entry,
1140	 * or EOF if there are none.  Then find all entries for the dir that
1141	 * fit into the buffer.  Once no more entries are found (de == NULL),
1142	 * the offset is set to TMPFS_DIRCOOKIE_EOF, which will cause the next
1143	 * call to return 0.
1144	 */
1145	switch (uio->uio_offset) {
1146	case TMPFS_DIRCOOKIE_DOT:
1147		error = tmpfs_dir_getdotdent(node, uio);
1148		if (error != 0)
1149			return (error);
1150		uio->uio_offset = TMPFS_DIRCOOKIE_DOTDOT;
1151		if (cookies != NULL)
1152			cookies[(*ncookies)++] = off = uio->uio_offset;
1153		/* FALLTHROUGH */
1154	case TMPFS_DIRCOOKIE_DOTDOT:
1155		error = tmpfs_dir_getdotdotdent(node, uio);
1156		if (error != 0)
1157			return (error);
1158		de = tmpfs_dir_first(node, &dc);
1159		uio->uio_offset = tmpfs_dirent_cookie(de);
1160		if (cookies != NULL)
1161			cookies[(*ncookies)++] = off = uio->uio_offset;
1162		/* EOF. */
1163		if (de == NULL)
1164			return (0);
1165		break;
1166	case TMPFS_DIRCOOKIE_EOF:
1167		return (0);
1168	default:
1169		de = tmpfs_dir_lookup_cookie(node, uio->uio_offset, &dc);
1170		if (de == NULL)
1171			return (EINVAL);
1172		if (cookies != NULL)
1173			off = tmpfs_dirent_cookie(de);
1174	}
1175
1176	/* Read as much entries as possible; i.e., until we reach the end of
1177	 * the directory or we exhaust uio space. */
1178	do {
1179		struct dirent d;
1180
1181		/* Create a dirent structure representing the current
1182		 * tmpfs_node and fill it. */
1183		if (de->td_node == NULL) {
1184			d.d_fileno = 1;
1185			d.d_type = DT_WHT;
1186		} else {
1187			d.d_fileno = de->td_node->tn_id;
1188			switch (de->td_node->tn_type) {
1189			case VBLK:
1190				d.d_type = DT_BLK;
1191				break;
1192
1193			case VCHR:
1194				d.d_type = DT_CHR;
1195				break;
1196
1197			case VDIR:
1198				d.d_type = DT_DIR;
1199				break;
1200
1201			case VFIFO:
1202				d.d_type = DT_FIFO;
1203				break;
1204
1205			case VLNK:
1206				d.d_type = DT_LNK;
1207				break;
1208
1209			case VREG:
1210				d.d_type = DT_REG;
1211				break;
1212
1213			case VSOCK:
1214				d.d_type = DT_SOCK;
1215				break;
1216
1217			default:
1218				panic("tmpfs_dir_getdents: type %p %d",
1219				    de->td_node, (int)de->td_node->tn_type);
1220			}
1221		}
1222		d.d_namlen = de->td_namelen;
1223		MPASS(de->td_namelen < sizeof(d.d_name));
1224		(void)memcpy(d.d_name, de->ud.td_name, de->td_namelen);
1225		d.d_name[de->td_namelen] = '\0';
1226		d.d_reclen = GENERIC_DIRSIZ(&d);
1227
1228		/* Stop reading if the directory entry we are treating is
1229		 * bigger than the amount of data that can be returned. */
1230		if (d.d_reclen > uio->uio_resid) {
1231			error = EJUSTRETURN;
1232			break;
1233		}
1234
1235		/* Copy the new dirent structure into the output buffer and
1236		 * advance pointers. */
1237		error = uiomove(&d, d.d_reclen, uio);
1238		if (error == 0) {
1239			de = tmpfs_dir_next(node, &dc);
1240			if (cookies != NULL) {
1241				off = tmpfs_dirent_cookie(de);
1242				MPASS(*ncookies < maxcookies);
1243				cookies[(*ncookies)++] = off;
1244			}
1245		}
1246	} while (error == 0 && uio->uio_resid > 0 && de != NULL);
1247
1248	/* Skip setting off when using cookies as it is already done above. */
1249	if (cookies == NULL)
1250		off = tmpfs_dirent_cookie(de);
1251
1252	/* Update the offset and cache. */
1253	uio->uio_offset = off;
1254	node->tn_dir.tn_readdir_lastn = off;
1255	node->tn_dir.tn_readdir_lastp = de;
1256
1257	node->tn_status |= TMPFS_NODE_ACCESSED;
1258	return error;
1259}
1260
1261int
1262tmpfs_dir_whiteout_add(struct vnode *dvp, struct componentname *cnp)
1263{
1264	struct tmpfs_dirent *de;
1265	int error;
1266
1267	error = tmpfs_alloc_dirent(VFS_TO_TMPFS(dvp->v_mount), NULL,
1268	    cnp->cn_nameptr, cnp->cn_namelen, &de);
1269	if (error != 0)
1270		return (error);
1271	tmpfs_dir_attach(dvp, de);
1272	return (0);
1273}
1274
1275void
1276tmpfs_dir_whiteout_remove(struct vnode *dvp, struct componentname *cnp)
1277{
1278	struct tmpfs_dirent *de;
1279
1280	de = tmpfs_dir_lookup(VP_TO_TMPFS_DIR(dvp), NULL, cnp);
1281	MPASS(de != NULL && de->td_node == NULL);
1282	tmpfs_dir_detach(dvp, de);
1283	tmpfs_free_dirent(VFS_TO_TMPFS(dvp->v_mount), de);
1284}
1285
1286/*
1287 * Resizes the aobj associated with the regular file pointed to by 'vp' to the
1288 * size 'newsize'.  'vp' must point to a vnode that represents a regular file.
1289 * 'newsize' must be positive.
1290 *
1291 * Returns zero on success or an appropriate error code on failure.
1292 */
1293int
1294tmpfs_reg_resize(struct vnode *vp, off_t newsize, boolean_t ignerr)
1295{
1296	struct tmpfs_mount *tmp;
1297	struct tmpfs_node *node;
1298	vm_object_t uobj;
1299	vm_page_t m, ma[1];
1300	vm_pindex_t idx, newpages, oldpages;
1301	off_t oldsize;
1302	int base, rv;
1303
1304	MPASS(vp->v_type == VREG);
1305	MPASS(newsize >= 0);
1306
1307	node = VP_TO_TMPFS_NODE(vp);
1308	uobj = node->tn_reg.tn_aobj;
1309	tmp = VFS_TO_TMPFS(vp->v_mount);
1310
1311	/*
1312	 * Convert the old and new sizes to the number of pages needed to
1313	 * store them.  It may happen that we do not need to do anything
1314	 * because the last allocated page can accommodate the change on
1315	 * its own.
1316	 */
1317	oldsize = node->tn_size;
1318	oldpages = OFF_TO_IDX(oldsize + PAGE_MASK);
1319	MPASS(oldpages == uobj->size);
1320	newpages = OFF_TO_IDX(newsize + PAGE_MASK);
1321	if (newpages > oldpages &&
1322	    tmpfs_pages_check_avail(tmp, newpages - oldpages) == 0)
1323		return (ENOSPC);
1324
1325	VM_OBJECT_WLOCK(uobj);
1326	if (newsize < oldsize) {
1327		/*
1328		 * Zero the truncated part of the last page.
1329		 */
1330		base = newsize & PAGE_MASK;
1331		if (base != 0) {
1332			idx = OFF_TO_IDX(newsize);
1333retry:
1334			m = vm_page_lookup(uobj, idx);
1335			if (m != NULL) {
1336				if (vm_page_sleep_if_busy(m, "tmfssz"))
1337					goto retry;
1338				MPASS(m->valid == VM_PAGE_BITS_ALL);
1339			} else if (vm_pager_has_page(uobj, idx, NULL, NULL)) {
1340				m = vm_page_alloc(uobj, idx, VM_ALLOC_NORMAL);
1341				if (m == NULL) {
1342					VM_OBJECT_WUNLOCK(uobj);
1343					VM_WAIT;
1344					VM_OBJECT_WLOCK(uobj);
1345					goto retry;
1346				} else if (m->valid != VM_PAGE_BITS_ALL) {
1347					ma[0] = m;
1348					rv = vm_pager_get_pages(uobj, ma, 1, 0);
1349					m = vm_page_lookup(uobj, idx);
1350				} else
1351					/* A cached page was reactivated. */
1352					rv = VM_PAGER_OK;
1353				vm_page_lock(m);
1354				if (rv == VM_PAGER_OK) {
1355					vm_page_deactivate(m);
1356					vm_page_unlock(m);
1357					vm_page_xunbusy(m);
1358				} else {
1359					vm_page_free(m);
1360					vm_page_unlock(m);
1361					if (ignerr)
1362						m = NULL;
1363					else {
1364						VM_OBJECT_WUNLOCK(uobj);
1365						return (EIO);
1366					}
1367				}
1368			}
1369			if (m != NULL) {
1370				pmap_zero_page_area(m, base, PAGE_SIZE - base);
1371				vm_page_dirty(m);
1372				vm_pager_page_unswapped(m);
1373			}
1374		}
1375
1376		/*
1377		 * Release any swap space and free any whole pages.
1378		 */
1379		if (newpages < oldpages) {
1380			swap_pager_freespace(uobj, newpages, oldpages -
1381			    newpages);
1382			vm_object_page_remove(uobj, newpages, 0, 0);
1383		}
1384	}
1385	uobj->size = newpages;
1386	VM_OBJECT_WUNLOCK(uobj);
1387
1388	TMPFS_LOCK(tmp);
1389	tmp->tm_pages_used += (newpages - oldpages);
1390	TMPFS_UNLOCK(tmp);
1391
1392	node->tn_size = newsize;
1393	return (0);
1394}
1395
1396/*
1397 * Change flags of the given vnode.
1398 * Caller should execute tmpfs_update on vp after a successful execution.
1399 * The vnode must be locked on entry and remain locked on exit.
1400 */
1401int
1402tmpfs_chflags(struct vnode *vp, u_long flags, struct ucred *cred,
1403    struct thread *p)
1404{
1405	int error;
1406	struct tmpfs_node *node;
1407
1408	MPASS(VOP_ISLOCKED(vp));
1409
1410	node = VP_TO_TMPFS_NODE(vp);
1411
1412	if ((flags & ~(SF_APPEND | SF_ARCHIVED | SF_IMMUTABLE | SF_NOUNLINK |
1413	    UF_APPEND | UF_ARCHIVE | UF_HIDDEN | UF_IMMUTABLE | UF_NODUMP |
1414	    UF_NOUNLINK | UF_OFFLINE | UF_OPAQUE | UF_READONLY | UF_REPARSE |
1415	    UF_SPARSE | UF_SYSTEM)) != 0)
1416		return (EOPNOTSUPP);
1417
1418	/* Disallow this operation if the file system is mounted read-only. */
1419	if (vp->v_mount->mnt_flag & MNT_RDONLY)
1420		return EROFS;
1421
1422	/*
1423	 * Callers may only modify the file flags on objects they
1424	 * have VADMIN rights for.
1425	 */
1426	if ((error = VOP_ACCESS(vp, VADMIN, cred, p)))
1427		return (error);
1428	/*
1429	 * Unprivileged processes are not permitted to unset system
1430	 * flags, or modify flags if any system flags are set.
1431	 */
1432	if (!priv_check_cred(cred, PRIV_VFS_SYSFLAGS, 0)) {
1433		if (node->tn_flags &
1434		    (SF_NOUNLINK | SF_IMMUTABLE | SF_APPEND)) {
1435			error = securelevel_gt(cred, 0);
1436			if (error)
1437				return (error);
1438		}
1439	} else {
1440		if (node->tn_flags &
1441		    (SF_NOUNLINK | SF_IMMUTABLE | SF_APPEND) ||
1442		    ((flags ^ node->tn_flags) & SF_SETTABLE))
1443			return (EPERM);
1444	}
1445	node->tn_flags = flags;
1446	node->tn_status |= TMPFS_NODE_CHANGED;
1447
1448	MPASS(VOP_ISLOCKED(vp));
1449
1450	return 0;
1451}
1452
1453/*
1454 * Change access mode on the given vnode.
1455 * Caller should execute tmpfs_update on vp after a successful execution.
1456 * The vnode must be locked on entry and remain locked on exit.
1457 */
1458int
1459tmpfs_chmod(struct vnode *vp, mode_t mode, struct ucred *cred, struct thread *p)
1460{
1461	int error;
1462	struct tmpfs_node *node;
1463
1464	MPASS(VOP_ISLOCKED(vp));
1465
1466	node = VP_TO_TMPFS_NODE(vp);
1467
1468	/* Disallow this operation if the file system is mounted read-only. */
1469	if (vp->v_mount->mnt_flag & MNT_RDONLY)
1470		return EROFS;
1471
1472	/* Immutable or append-only files cannot be modified, either. */
1473	if (node->tn_flags & (IMMUTABLE | APPEND))
1474		return EPERM;
1475
1476	/*
1477	 * To modify the permissions on a file, must possess VADMIN
1478	 * for that file.
1479	 */
1480	if ((error = VOP_ACCESS(vp, VADMIN, cred, p)))
1481		return (error);
1482
1483	/*
1484	 * Privileged processes may set the sticky bit on non-directories,
1485	 * as well as set the setgid bit on a file with a group that the
1486	 * process is not a member of.
1487	 */
1488	if (vp->v_type != VDIR && (mode & S_ISTXT)) {
1489		if (priv_check_cred(cred, PRIV_VFS_STICKYFILE, 0))
1490			return (EFTYPE);
1491	}
1492	if (!groupmember(node->tn_gid, cred) && (mode & S_ISGID)) {
1493		error = priv_check_cred(cred, PRIV_VFS_SETGID, 0);
1494		if (error)
1495			return (error);
1496	}
1497
1498
1499	node->tn_mode &= ~ALLPERMS;
1500	node->tn_mode |= mode & ALLPERMS;
1501
1502	node->tn_status |= TMPFS_NODE_CHANGED;
1503
1504	MPASS(VOP_ISLOCKED(vp));
1505
1506	return 0;
1507}
1508
1509/*
1510 * Change ownership of the given vnode.  At least one of uid or gid must
1511 * be different than VNOVAL.  If one is set to that value, the attribute
1512 * is unchanged.
1513 * Caller should execute tmpfs_update on vp after a successful execution.
1514 * The vnode must be locked on entry and remain locked on exit.
1515 */
1516int
1517tmpfs_chown(struct vnode *vp, uid_t uid, gid_t gid, struct ucred *cred,
1518    struct thread *p)
1519{
1520	int error;
1521	struct tmpfs_node *node;
1522	uid_t ouid;
1523	gid_t ogid;
1524
1525	MPASS(VOP_ISLOCKED(vp));
1526
1527	node = VP_TO_TMPFS_NODE(vp);
1528
1529	/* Assign default values if they are unknown. */
1530	MPASS(uid != VNOVAL || gid != VNOVAL);
1531	if (uid == VNOVAL)
1532		uid = node->tn_uid;
1533	if (gid == VNOVAL)
1534		gid = node->tn_gid;
1535	MPASS(uid != VNOVAL && gid != VNOVAL);
1536
1537	/* Disallow this operation if the file system is mounted read-only. */
1538	if (vp->v_mount->mnt_flag & MNT_RDONLY)
1539		return EROFS;
1540
1541	/* Immutable or append-only files cannot be modified, either. */
1542	if (node->tn_flags & (IMMUTABLE | APPEND))
1543		return EPERM;
1544
1545	/*
1546	 * To modify the ownership of a file, must possess VADMIN for that
1547	 * file.
1548	 */
1549	if ((error = VOP_ACCESS(vp, VADMIN, cred, p)))
1550		return (error);
1551
1552	/*
1553	 * To change the owner of a file, or change the group of a file to a
1554	 * group of which we are not a member, the caller must have
1555	 * privilege.
1556	 */
1557	if ((uid != node->tn_uid ||
1558	    (gid != node->tn_gid && !groupmember(gid, cred))) &&
1559	    (error = priv_check_cred(cred, PRIV_VFS_CHOWN, 0)))
1560		return (error);
1561
1562	ogid = node->tn_gid;
1563	ouid = node->tn_uid;
1564
1565	node->tn_uid = uid;
1566	node->tn_gid = gid;
1567
1568	node->tn_status |= TMPFS_NODE_CHANGED;
1569
1570	if ((node->tn_mode & (S_ISUID | S_ISGID)) && (ouid != uid || ogid != gid)) {
1571		if (priv_check_cred(cred, PRIV_VFS_RETAINSUGID, 0))
1572			node->tn_mode &= ~(S_ISUID | S_ISGID);
1573	}
1574
1575	MPASS(VOP_ISLOCKED(vp));
1576
1577	return 0;
1578}
1579
1580/*
1581 * Change size of the given vnode.
1582 * Caller should execute tmpfs_update on vp after a successful execution.
1583 * The vnode must be locked on entry and remain locked on exit.
1584 */
1585int
1586tmpfs_chsize(struct vnode *vp, u_quad_t size, struct ucred *cred,
1587    struct thread *p)
1588{
1589	int error;
1590	struct tmpfs_node *node;
1591
1592	MPASS(VOP_ISLOCKED(vp));
1593
1594	node = VP_TO_TMPFS_NODE(vp);
1595
1596	/* Decide whether this is a valid operation based on the file type. */
1597	error = 0;
1598	switch (vp->v_type) {
1599	case VDIR:
1600		return EISDIR;
1601
1602	case VREG:
1603		if (vp->v_mount->mnt_flag & MNT_RDONLY)
1604			return EROFS;
1605		break;
1606
1607	case VBLK:
1608		/* FALLTHROUGH */
1609	case VCHR:
1610		/* FALLTHROUGH */
1611	case VFIFO:
1612		/* Allow modifications of special files even if in the file
1613		 * system is mounted read-only (we are not modifying the
1614		 * files themselves, but the objects they represent). */
1615		return 0;
1616
1617	default:
1618		/* Anything else is unsupported. */
1619		return EOPNOTSUPP;
1620	}
1621
1622	/* Immutable or append-only files cannot be modified, either. */
1623	if (node->tn_flags & (IMMUTABLE | APPEND))
1624		return EPERM;
1625
1626	error = tmpfs_truncate(vp, size);
1627	/* tmpfs_truncate will raise the NOTE_EXTEND and NOTE_ATTRIB kevents
1628	 * for us, as will update tn_status; no need to do that here. */
1629
1630	MPASS(VOP_ISLOCKED(vp));
1631
1632	return error;
1633}
1634
1635/*
1636 * Change access and modification times of the given vnode.
1637 * Caller should execute tmpfs_update on vp after a successful execution.
1638 * The vnode must be locked on entry and remain locked on exit.
1639 */
1640int
1641tmpfs_chtimes(struct vnode *vp, struct vattr *vap,
1642    struct ucred *cred, struct thread *l)
1643{
1644	int error;
1645	struct tmpfs_node *node;
1646
1647	MPASS(VOP_ISLOCKED(vp));
1648
1649	node = VP_TO_TMPFS_NODE(vp);
1650
1651	/* Disallow this operation if the file system is mounted read-only. */
1652	if (vp->v_mount->mnt_flag & MNT_RDONLY)
1653		return EROFS;
1654
1655	/* Immutable or append-only files cannot be modified, either. */
1656	if (node->tn_flags & (IMMUTABLE | APPEND))
1657		return EPERM;
1658
1659	error = vn_utimes_perm(vp, vap, cred, l);
1660	if (error != 0)
1661		return (error);
1662
1663	if (vap->va_atime.tv_sec != VNOVAL && vap->va_atime.tv_nsec != VNOVAL)
1664		node->tn_status |= TMPFS_NODE_ACCESSED;
1665
1666	if (vap->va_mtime.tv_sec != VNOVAL && vap->va_mtime.tv_nsec != VNOVAL)
1667		node->tn_status |= TMPFS_NODE_MODIFIED;
1668
1669	if (vap->va_birthtime.tv_nsec != VNOVAL &&
1670	    vap->va_birthtime.tv_nsec != VNOVAL)
1671		node->tn_status |= TMPFS_NODE_MODIFIED;
1672
1673	tmpfs_itimes(vp, &vap->va_atime, &vap->va_mtime);
1674
1675	if (vap->va_birthtime.tv_nsec != VNOVAL &&
1676	    vap->va_birthtime.tv_nsec != VNOVAL)
1677		node->tn_birthtime = vap->va_birthtime;
1678	MPASS(VOP_ISLOCKED(vp));
1679
1680	return 0;
1681}
1682
1683/* Sync timestamps */
1684void
1685tmpfs_itimes(struct vnode *vp, const struct timespec *acc,
1686    const struct timespec *mod)
1687{
1688	struct tmpfs_node *node;
1689	struct timespec now;
1690
1691	node = VP_TO_TMPFS_NODE(vp);
1692
1693	if ((node->tn_status & (TMPFS_NODE_ACCESSED | TMPFS_NODE_MODIFIED |
1694	    TMPFS_NODE_CHANGED)) == 0)
1695		return;
1696
1697	vfs_timestamp(&now);
1698	if (node->tn_status & TMPFS_NODE_ACCESSED) {
1699		if (acc == NULL)
1700			 acc = &now;
1701		node->tn_atime = *acc;
1702	}
1703	if (node->tn_status & TMPFS_NODE_MODIFIED) {
1704		if (mod == NULL)
1705			mod = &now;
1706		node->tn_mtime = *mod;
1707	}
1708	if (node->tn_status & TMPFS_NODE_CHANGED) {
1709		node->tn_ctime = now;
1710	}
1711	node->tn_status &=
1712	    ~(TMPFS_NODE_ACCESSED | TMPFS_NODE_MODIFIED | TMPFS_NODE_CHANGED);
1713}
1714
1715void
1716tmpfs_update(struct vnode *vp)
1717{
1718
1719	tmpfs_itimes(vp, NULL, NULL);
1720}
1721
1722int
1723tmpfs_truncate(struct vnode *vp, off_t length)
1724{
1725	int error;
1726	struct tmpfs_node *node;
1727
1728	node = VP_TO_TMPFS_NODE(vp);
1729
1730	if (length < 0) {
1731		error = EINVAL;
1732		goto out;
1733	}
1734
1735	if (node->tn_size == length) {
1736		error = 0;
1737		goto out;
1738	}
1739
1740	if (length > VFS_TO_TMPFS(vp->v_mount)->tm_maxfilesize)
1741		return (EFBIG);
1742
1743	error = tmpfs_reg_resize(vp, length, FALSE);
1744	if (error == 0) {
1745		node->tn_status |= TMPFS_NODE_CHANGED | TMPFS_NODE_MODIFIED;
1746	}
1747
1748out:
1749	tmpfs_update(vp);
1750
1751	return error;
1752}
1753
1754static __inline int
1755tmpfs_dirtree_cmp(struct tmpfs_dirent *a, struct tmpfs_dirent *b)
1756{
1757	if (a->td_hash > b->td_hash)
1758		return (1);
1759	else if (a->td_hash < b->td_hash)
1760		return (-1);
1761	return (0);
1762}
1763
1764RB_GENERATE_STATIC(tmpfs_dir, tmpfs_dirent, uh.td_entries, tmpfs_dirtree_cmp);
1765