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