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