xref: /netbsd-src/sys/fs/tmpfs/tmpfs_subr.c (revision 6a493d6bc668897c91594964a732d38505b70cbb)
1 /*	$NetBSD: tmpfs_subr.c,v 1.92 2013/11/24 17:16:29 rmind Exp $	*/
2 
3 /*
4  * Copyright (c) 2005-2013 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, and by Mindaugas Rasiukevicius.
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: interfaces for inode and directory entry
35  * construction, destruction and manipulation.
36  *
37  * Reference counting
38  *
39  *	The link count of inode (tmpfs_node_t::tn_links) is used as a
40  *	reference counter.  However, it has slightly different semantics.
41  *
42  *	For directories - link count represents directory entries, which
43  *	refer to the directories.  In other words, it represents the count
44  *	of sub-directories.  It also takes into account the virtual '.'
45  *	entry (which has no real entry in the list).  For files - link count
46  *	represents the hard links.  Since only empty directories can be
47  *	removed - link count aligns the reference counting requirements
48  *	enough.  Note: to check whether directory is not empty, the inode
49  *	size (tmpfs_node_t::tn_size) can be used.
50  *
51  *	The inode itself, as an object, gathers its first reference when
52  *	directory entry is attached via tmpfs_dir_attach(9).  For instance,
53  *	after regular tmpfs_create(), a file would have a link count of 1,
54  *	while directory after tmpfs_mkdir() would have 2 (due to '.').
55  *
56  * Reclamation
57  *
58  *	It should be noted that tmpfs inodes rely on a combination of vnode
59  *	reference counting and link counting.  That is, an inode can only be
60  *	destroyed if its associated vnode is inactive.  The destruction is
61  *	done on vnode reclamation i.e. tmpfs_reclaim().  It should be noted
62  *	that tmpfs_node_t::tn_links being 0 is a destruction criterion.
63  *
64  *	If an inode has references within the file system (tn_links > 0) and
65  *	its inactive vnode gets reclaimed/recycled - then the association is
66  *	broken in tmpfs_reclaim().  In such case, an inode will always pass
67  *	tmpfs_lookup() and thus tmpfs_vnode_get() to associate a new vnode.
68  *
69  * Lock order
70  *
71  *	tmpfs_node_t::tn_vlock ->
72  *		vnode_t::v_vlock ->
73  *			vnode_t::v_interlock
74  */
75 
76 #include <sys/cdefs.h>
77 __KERNEL_RCSID(0, "$NetBSD: tmpfs_subr.c,v 1.92 2013/11/24 17:16:29 rmind Exp $");
78 
79 #include <sys/param.h>
80 #include <sys/cprng.h>
81 #include <sys/dirent.h>
82 #include <sys/event.h>
83 #include <sys/kmem.h>
84 #include <sys/mount.h>
85 #include <sys/namei.h>
86 #include <sys/time.h>
87 #include <sys/stat.h>
88 #include <sys/systm.h>
89 #include <sys/vnode.h>
90 #include <sys/kauth.h>
91 #include <sys/atomic.h>
92 
93 #include <uvm/uvm.h>
94 
95 #include <miscfs/specfs/specdev.h>
96 #include <miscfs/genfs/genfs.h>
97 #include <fs/tmpfs/tmpfs.h>
98 #include <fs/tmpfs/tmpfs_fifoops.h>
99 #include <fs/tmpfs/tmpfs_specops.h>
100 #include <fs/tmpfs/tmpfs_vnops.h>
101 
102 static void	tmpfs_dir_putseq(tmpfs_node_t *, tmpfs_dirent_t *);
103 
104 /*
105  * tmpfs_alloc_node: allocate a new inode of a specified type and
106  * insert it into the list of specified mount point.
107  */
108 int
109 tmpfs_alloc_node(tmpfs_mount_t *tmp, enum vtype type, uid_t uid, gid_t gid,
110     mode_t mode, char *target, dev_t rdev, tmpfs_node_t **node)
111 {
112 	tmpfs_node_t *nnode;
113 
114 	nnode = tmpfs_node_get(tmp);
115 	if (nnode == NULL) {
116 		return ENOSPC;
117 	}
118 
119 	/* Initially, no references and no associations. */
120 	nnode->tn_links = 0;
121 	nnode->tn_vnode = NULL;
122 	nnode->tn_dirent_hint = NULL;
123 
124 	/*
125 	 * XXX Where the pool is backed by a map larger than (4GB *
126 	 * sizeof(*nnode)), this may produce duplicate inode numbers
127 	 * for applications that do not understand 64-bit ino_t.
128 	 */
129 	nnode->tn_id = (ino_t)((uintptr_t)nnode / sizeof(*nnode));
130 	nnode->tn_gen = TMPFS_NODE_GEN_MASK & cprng_fast32();
131 
132 	/* Generic initialization. */
133 	nnode->tn_type = type;
134 	nnode->tn_size = 0;
135 	nnode->tn_flags = 0;
136 	nnode->tn_lockf = NULL;
137 
138 	vfs_timestamp(&nnode->tn_atime);
139 	nnode->tn_birthtime = nnode->tn_atime;
140 	nnode->tn_ctime = nnode->tn_atime;
141 	nnode->tn_mtime = nnode->tn_atime;
142 
143 	KASSERT(uid != VNOVAL && gid != VNOVAL && mode != VNOVAL);
144 	nnode->tn_uid = uid;
145 	nnode->tn_gid = gid;
146 	nnode->tn_mode = mode;
147 
148 	/* Type-specific initialization. */
149 	switch (nnode->tn_type) {
150 	case VBLK:
151 	case VCHR:
152 		/* Character/block special device. */
153 		KASSERT(rdev != VNOVAL);
154 		nnode->tn_spec.tn_dev.tn_rdev = rdev;
155 		break;
156 	case VDIR:
157 		/* Directory. */
158 		TAILQ_INIT(&nnode->tn_spec.tn_dir.tn_dir);
159 		nnode->tn_spec.tn_dir.tn_parent = NULL;
160 		nnode->tn_spec.tn_dir.tn_seq_arena = NULL;
161 		nnode->tn_spec.tn_dir.tn_next_seq = TMPFS_DIRSEQ_START;
162 		nnode->tn_spec.tn_dir.tn_readdir_lastp = NULL;
163 
164 		/* Extra link count for the virtual '.' entry. */
165 		nnode->tn_links++;
166 		break;
167 	case VFIFO:
168 	case VSOCK:
169 		break;
170 	case VLNK:
171 		/* Symbolic link.  Target specifies the file name. */
172 		KASSERT(target != NULL);
173 		nnode->tn_size = strlen(target);
174 
175 		if (nnode->tn_size == 0) {
176 			/* Zero-length targets are supported. */
177 			nnode->tn_spec.tn_lnk.tn_link = NULL;
178 			break;
179 		}
180 
181 		KASSERT(nnode->tn_size < MAXPATHLEN);
182 		nnode->tn_size++; /* include the NUL terminator */
183 
184 		nnode->tn_spec.tn_lnk.tn_link =
185 		    tmpfs_strname_alloc(tmp, nnode->tn_size);
186 		if (nnode->tn_spec.tn_lnk.tn_link == NULL) {
187 			tmpfs_node_put(tmp, nnode);
188 			return ENOSPC;
189 		}
190 		memcpy(nnode->tn_spec.tn_lnk.tn_link, target, nnode->tn_size);
191 		break;
192 	case VREG:
193 		/* Regular file.  Create an underlying UVM object. */
194 		nnode->tn_spec.tn_reg.tn_aobj =
195 		    uao_create(INT32_MAX - PAGE_SIZE, 0);
196 		nnode->tn_spec.tn_reg.tn_aobj_pages = 0;
197 		break;
198 	default:
199 		KASSERT(false);
200 	}
201 
202 	mutex_init(&nnode->tn_vlock, MUTEX_DEFAULT, IPL_NONE);
203 
204 	mutex_enter(&tmp->tm_lock);
205 	LIST_INSERT_HEAD(&tmp->tm_nodes, nnode, tn_entries);
206 	mutex_exit(&tmp->tm_lock);
207 
208 	*node = nnode;
209 	return 0;
210 }
211 
212 /*
213  * tmpfs_free_node: remove the inode from a list in the mount point and
214  * destroy the inode structures.
215  */
216 void
217 tmpfs_free_node(tmpfs_mount_t *tmp, tmpfs_node_t *node)
218 {
219 	size_t objsz;
220 
221 	mutex_enter(&tmp->tm_lock);
222 	LIST_REMOVE(node, tn_entries);
223 	mutex_exit(&tmp->tm_lock);
224 
225 	switch (node->tn_type) {
226 	case VLNK:
227 		if (node->tn_size > 0) {
228 			tmpfs_strname_free(tmp, node->tn_spec.tn_lnk.tn_link,
229 			    node->tn_size);
230 		}
231 		break;
232 	case VREG:
233 		/*
234 		 * Calculate the size of inode data, decrease the used-memory
235 		 * counter, and destroy the unerlying UVM object (if any).
236 		 */
237 		objsz = PAGE_SIZE * node->tn_spec.tn_reg.tn_aobj_pages;
238 		if (objsz != 0) {
239 			tmpfs_mem_decr(tmp, objsz);
240 		}
241 		if (node->tn_spec.tn_reg.tn_aobj != NULL) {
242 			uao_detach(node->tn_spec.tn_reg.tn_aobj);
243 		}
244 		break;
245 	case VDIR:
246 		KASSERT(node->tn_size == 0);
247 		KASSERT(node->tn_spec.tn_dir.tn_seq_arena == NULL);
248 		KASSERT(TAILQ_EMPTY(&node->tn_spec.tn_dir.tn_dir));
249 		KASSERT(node->tn_spec.tn_dir.tn_parent == NULL ||
250 		    node == tmp->tm_root);
251 		break;
252 	default:
253 		break;
254 	}
255 	KASSERT(node->tn_links == 0);
256 
257 	mutex_destroy(&node->tn_vlock);
258 	tmpfs_node_put(tmp, node);
259 }
260 
261 /*
262  * tmpfs_vnode_get: allocate or reclaim a vnode for a specified inode.
263  *
264  * => Must be called with tmpfs_node_t::tn_vlock held.
265  * => Returns vnode (*vpp) locked.
266  */
267 int
268 tmpfs_vnode_get(struct mount *mp, tmpfs_node_t *node, vnode_t **vpp)
269 {
270 	vnode_t *vp;
271 	kmutex_t *slock;
272 	int error;
273 again:
274 	/* If there is already a vnode, try to reclaim it. */
275 	if ((vp = node->tn_vnode) != NULL) {
276 		atomic_or_32(&node->tn_gen, TMPFS_RECLAIMING_BIT);
277 		mutex_enter(vp->v_interlock);
278 		mutex_exit(&node->tn_vlock);
279 		error = vget(vp, LK_EXCLUSIVE);
280 		if (error == ENOENT) {
281 			mutex_enter(&node->tn_vlock);
282 			goto again;
283 		}
284 		atomic_and_32(&node->tn_gen, ~TMPFS_RECLAIMING_BIT);
285 		*vpp = vp;
286 		return error;
287 	}
288 	if (TMPFS_NODE_RECLAIMING(node)) {
289 		atomic_and_32(&node->tn_gen, ~TMPFS_RECLAIMING_BIT);
290 	}
291 
292 	/*
293 	 * Get a new vnode and associate it with our inode.  Share the
294 	 * lock with underlying UVM object, if there is one (VREG case).
295 	 */
296 	if (node->tn_type == VREG) {
297 		struct uvm_object *uobj = node->tn_spec.tn_reg.tn_aobj;
298 		slock = uobj->vmobjlock;
299 	} else {
300 		slock = NULL;
301 	}
302 	error = getnewvnode(VT_TMPFS, mp, tmpfs_vnodeop_p, slock, &vp);
303 	if (error) {
304 		mutex_exit(&node->tn_vlock);
305 		return error;
306 	}
307 
308 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
309 	vp->v_type = node->tn_type;
310 
311 	/* Type-specific initialization. */
312 	switch (node->tn_type) {
313 	case VBLK:
314 	case VCHR:
315 		vp->v_op = tmpfs_specop_p;
316 		spec_node_init(vp, node->tn_spec.tn_dev.tn_rdev);
317 		break;
318 	case VDIR:
319 		vp->v_vflag |= node->tn_spec.tn_dir.tn_parent == node ?
320 		    VV_ROOT : 0;
321 		break;
322 	case VFIFO:
323 		vp->v_op = tmpfs_fifoop_p;
324 		break;
325 	case VLNK:
326 	case VREG:
327 	case VSOCK:
328 		break;
329 	default:
330 		KASSERT(false);
331 	}
332 
333 	uvm_vnp_setsize(vp, node->tn_size);
334 	vp->v_data = node;
335 	node->tn_vnode = vp;
336 	mutex_exit(&node->tn_vlock);
337 
338 	KASSERT(VOP_ISLOCKED(vp));
339 	*vpp = vp;
340 	return 0;
341 }
342 
343 /*
344  * tmpfs_construct_node: allocate a new file of specified type and adds it
345  * into the parent directory.
346  *
347  * => Credentials of the caller are used.
348  */
349 int
350 tmpfs_construct_node(vnode_t *dvp, vnode_t **vpp, struct vattr *vap,
351     struct componentname *cnp, char *target)
352 {
353 	tmpfs_mount_t *tmp = VFS_TO_TMPFS(dvp->v_mount);
354 	tmpfs_node_t *dnode = VP_TO_TMPFS_DIR(dvp), *node;
355 	tmpfs_dirent_t *de, *wde;
356 	int error;
357 
358 	KASSERT(VOP_ISLOCKED(dvp));
359 	*vpp = NULL;
360 
361 	/*
362 	 * If directory was removed, prevent from node creation.  The vnode
363 	 * might still be referenced, but it is about to be reclaimed.
364 	 */
365 	if (dnode->tn_links == 0) {
366 		error = ENOENT;
367 		goto out;
368 	}
369 
370 	/* Check for the maximum number of links limit. */
371 	if (vap->va_type == VDIR) {
372 		/* Check for maximum links limit. */
373 		if (dnode->tn_links == LINK_MAX) {
374 			error = EMLINK;
375 			goto out;
376 		}
377 		KASSERT(dnode->tn_links < LINK_MAX);
378 	}
379 
380 	/* Allocate a node that represents the new file. */
381 	error = tmpfs_alloc_node(tmp, vap->va_type, kauth_cred_geteuid(cnp->cn_cred),
382 	    dnode->tn_gid, vap->va_mode, target, vap->va_rdev, &node);
383 	if (error)
384 		goto out;
385 
386 	/* Allocate a directory entry that points to the new file. */
387 	error = tmpfs_alloc_dirent(tmp, cnp->cn_nameptr, cnp->cn_namelen, &de);
388 	if (error) {
389 		tmpfs_free_node(tmp, node);
390 		goto out;
391 	}
392 
393 	/* Get a vnode for the new file. */
394 	mutex_enter(&node->tn_vlock);
395 	error = tmpfs_vnode_get(dvp->v_mount, node, vpp);
396 	if (error) {
397 		tmpfs_free_dirent(tmp, de);
398 		tmpfs_free_node(tmp, node);
399 		goto out;
400 	}
401 
402 	/* Remove whiteout before adding the new entry. */
403 	if (cnp->cn_flags & ISWHITEOUT) {
404 		wde = tmpfs_dir_lookup(dnode, cnp);
405 		KASSERT(wde != NULL && wde->td_node == TMPFS_NODE_WHITEOUT);
406 		tmpfs_dir_detach(dnode, wde);
407 		tmpfs_free_dirent(tmp, wde);
408 	}
409 
410 	/* Associate inode and attach the entry into the directory. */
411 	tmpfs_dir_attach(dnode, de, node);
412 
413 	/* Make node opaque if requested. */
414 	if (cnp->cn_flags & ISWHITEOUT)
415 		node->tn_flags |= UF_OPAQUE;
416 
417 	/* Update the parent's timestamps. */
418 	tmpfs_update(dvp, TMPFS_UPDATE_MTIME | TMPFS_UPDATE_CTIME);
419 out:
420 	vput(dvp);
421 	return error;
422 }
423 
424 /*
425  * tmpfs_alloc_dirent: allocates a new directory entry for the inode.
426  * The directory entry contains a path name component.
427  */
428 int
429 tmpfs_alloc_dirent(tmpfs_mount_t *tmp, const char *name, uint16_t len,
430     tmpfs_dirent_t **de)
431 {
432 	tmpfs_dirent_t *nde;
433 
434 	nde = tmpfs_dirent_get(tmp);
435 	if (nde == NULL)
436 		return ENOSPC;
437 
438 	nde->td_name = tmpfs_strname_alloc(tmp, len);
439 	if (nde->td_name == NULL) {
440 		tmpfs_dirent_put(tmp, nde);
441 		return ENOSPC;
442 	}
443 	nde->td_namelen = len;
444 	memcpy(nde->td_name, name, len);
445 	nde->td_seq = TMPFS_DIRSEQ_NONE;
446 
447 	*de = nde;
448 	return 0;
449 }
450 
451 /*
452  * tmpfs_free_dirent: free a directory entry.
453  */
454 void
455 tmpfs_free_dirent(tmpfs_mount_t *tmp, tmpfs_dirent_t *de)
456 {
457 	KASSERT(de->td_node == NULL);
458 	KASSERT(de->td_seq == TMPFS_DIRSEQ_NONE);
459 	tmpfs_strname_free(tmp, de->td_name, de->td_namelen);
460 	tmpfs_dirent_put(tmp, de);
461 }
462 
463 /*
464  * tmpfs_dir_attach: associate directory entry with a specified inode,
465  * and attach the entry into the directory, specified by vnode.
466  *
467  * => Increases link count on the associated node.
468  * => Increases link count on directory node if our node is VDIR.
469  * => It is caller's responsibility to check for the LINK_MAX limit.
470  * => Triggers kqueue events here.
471  */
472 void
473 tmpfs_dir_attach(tmpfs_node_t *dnode, tmpfs_dirent_t *de, tmpfs_node_t *node)
474 {
475 	vnode_t *dvp = dnode->tn_vnode;
476 	int events = NOTE_WRITE;
477 
478 	KASSERT(dvp != NULL);
479 	KASSERT(VOP_ISLOCKED(dvp));
480 
481 	/* Get a new sequence number. */
482 	KASSERT(de->td_seq == TMPFS_DIRSEQ_NONE);
483 	de->td_seq = tmpfs_dir_getseq(dnode, de);
484 
485 	/* Associate directory entry and the inode. */
486 	de->td_node = node;
487 	if (node != TMPFS_NODE_WHITEOUT) {
488 		KASSERT(node->tn_links < LINK_MAX);
489 		node->tn_links++;
490 
491 		/* Save the hint (might overwrite). */
492 		node->tn_dirent_hint = de;
493 	} else if ((dnode->tn_gen & TMPFS_WHITEOUT_BIT) == 0) {
494 		/* Flag that there are whiteout entries. */
495 		atomic_or_32(&dnode->tn_gen, TMPFS_WHITEOUT_BIT);
496 	}
497 
498 	/* Insert the entry to the directory (parent of inode). */
499 	TAILQ_INSERT_TAIL(&dnode->tn_spec.tn_dir.tn_dir, de, td_entries);
500 	dnode->tn_size += sizeof(tmpfs_dirent_t);
501 	uvm_vnp_setsize(dvp, dnode->tn_size);
502 
503 	if (node != TMPFS_NODE_WHITEOUT && node->tn_type == VDIR) {
504 		/* Set parent. */
505 		KASSERT(node->tn_spec.tn_dir.tn_parent == NULL);
506 		node->tn_spec.tn_dir.tn_parent = dnode;
507 
508 		/* Increase the link count of parent. */
509 		KASSERT(dnode->tn_links < LINK_MAX);
510 		dnode->tn_links++;
511 		events |= NOTE_LINK;
512 
513 		TMPFS_VALIDATE_DIR(node);
514 	}
515 	VN_KNOTE(dvp, events);
516 }
517 
518 /*
519  * tmpfs_dir_detach: disassociate directory entry and its inode,
520  * and detach the entry from the directory, specified by vnode.
521  *
522  * => Decreases link count on the associated node.
523  * => Decreases the link count on directory node, if our node is VDIR.
524  * => Triggers kqueue events here.
525  *
526  * => Note: dvp and vp may be NULL only if called by tmpfs_unmount().
527  */
528 void
529 tmpfs_dir_detach(tmpfs_node_t *dnode, tmpfs_dirent_t *de)
530 {
531 	tmpfs_node_t *node = de->td_node;
532 	vnode_t *vp, *dvp = dnode->tn_vnode;
533 	int events = NOTE_WRITE;
534 
535 	KASSERT(dvp == NULL || VOP_ISLOCKED(dvp));
536 
537 	if (__predict_true(node != TMPFS_NODE_WHITEOUT)) {
538 		/* Deassociate the inode and entry. */
539 		node->tn_dirent_hint = NULL;
540 
541 		KASSERT(node->tn_links > 0);
542 		node->tn_links--;
543 
544 		if ((vp = node->tn_vnode) != NULL) {
545 			KASSERT(VOP_ISLOCKED(vp));
546 			VN_KNOTE(vp, node->tn_links ? NOTE_LINK : NOTE_DELETE);
547 		}
548 
549 		/* If directory - decrease the link count of parent. */
550 		if (node->tn_type == VDIR) {
551 			KASSERT(node->tn_spec.tn_dir.tn_parent == dnode);
552 			node->tn_spec.tn_dir.tn_parent = NULL;
553 
554 			KASSERT(dnode->tn_links > 0);
555 			dnode->tn_links--;
556 			events |= NOTE_LINK;
557 		}
558 	}
559 	de->td_node = NULL;
560 
561 	/* Remove the entry from the directory. */
562 	if (dnode->tn_spec.tn_dir.tn_readdir_lastp == de) {
563 		dnode->tn_spec.tn_dir.tn_readdir_lastp = NULL;
564 	}
565 	TAILQ_REMOVE(&dnode->tn_spec.tn_dir.tn_dir, de, td_entries);
566 	dnode->tn_size -= sizeof(tmpfs_dirent_t);
567 	tmpfs_dir_putseq(dnode, de);
568 
569 	if (dvp) {
570 		uvm_vnp_setsize(dvp, dnode->tn_size);
571 		VN_KNOTE(dvp, events);
572 	}
573 }
574 
575 /*
576  * tmpfs_dir_lookup: find a directory entry in the specified inode.
577  *
578  * Note that the . and .. components are not allowed as they do not
579  * physically exist within directories.
580  */
581 tmpfs_dirent_t *
582 tmpfs_dir_lookup(tmpfs_node_t *node, struct componentname *cnp)
583 {
584 	const char *name = cnp->cn_nameptr;
585 	const uint16_t nlen = cnp->cn_namelen;
586 	tmpfs_dirent_t *de;
587 
588 	KASSERT(VOP_ISLOCKED(node->tn_vnode));
589 	KASSERT(nlen != 1 || !(name[0] == '.'));
590 	KASSERT(nlen != 2 || !(name[0] == '.' && name[1] == '.'));
591 	TMPFS_VALIDATE_DIR(node);
592 
593 	TAILQ_FOREACH(de, &node->tn_spec.tn_dir.tn_dir, td_entries) {
594 		if (de->td_namelen != nlen)
595 			continue;
596 		if (memcmp(de->td_name, name, nlen) != 0)
597 			continue;
598 		break;
599 	}
600 	return de;
601 }
602 
603 /*
604  * tmpfs_dir_cached: get a cached directory entry if it is valid.  Used to
605  * avoid unnecessary tmpfs_dir_lookup().
606  *
607  * => The vnode must be locked.
608  */
609 tmpfs_dirent_t *
610 tmpfs_dir_cached(tmpfs_node_t *node)
611 {
612 	tmpfs_dirent_t *de = node->tn_dirent_hint;
613 
614 	KASSERT(VOP_ISLOCKED(node->tn_vnode));
615 
616 	if (de == NULL) {
617 		return NULL;
618 	}
619 	KASSERT(de->td_node == node);
620 
621 	/*
622 	 * Directories always have a valid hint.  For files, check if there
623 	 * are any hard links.  If there are - hint might be invalid.
624 	 */
625 	return (node->tn_type != VDIR && node->tn_links > 1) ? NULL : de;
626 }
627 
628 /*
629  * tmpfs_dir_getseq: get a per-directory sequence number for the entry.
630  *
631  * => Shall not be larger than 2^31 for linux32 compatibility.
632  */
633 uint32_t
634 tmpfs_dir_getseq(tmpfs_node_t *dnode, tmpfs_dirent_t *de)
635 {
636 	uint32_t seq = de->td_seq;
637 	vmem_t *seq_arena;
638 	vmem_addr_t off;
639 	int error __diagused;
640 
641 	TMPFS_VALIDATE_DIR(dnode);
642 
643 	if (__predict_true(seq != TMPFS_DIRSEQ_NONE)) {
644 		/* Already set. */
645 		KASSERT(seq >= TMPFS_DIRSEQ_START);
646 		return seq;
647 	}
648 
649 	/*
650 	 * The "." and ".." and the end-of-directory have reserved numbers.
651 	 * The other sequence numbers are allocated as following:
652 	 *
653 	 * - The first half of the 2^31 is assigned incrementally.
654 	 *
655 	 * - If that range is exceeded, then the second half of 2^31
656 	 * is used, but managed by vmem(9).
657 	 */
658 
659 	seq = dnode->tn_spec.tn_dir.tn_next_seq;
660 	KASSERT(seq >= TMPFS_DIRSEQ_START);
661 
662 	if (__predict_true(seq < TMPFS_DIRSEQ_END)) {
663 		/* First half: just increment and return. */
664 		dnode->tn_spec.tn_dir.tn_next_seq++;
665 		return seq;
666 	}
667 
668 	/*
669 	 * First half exceeded, use the second half.  May need to create
670 	 * vmem(9) arena for the directory first.
671 	 */
672 	if ((seq_arena = dnode->tn_spec.tn_dir.tn_seq_arena) == NULL) {
673 		seq_arena = vmem_create("tmpfscoo", 0,
674 		    TMPFS_DIRSEQ_END - 1, 1, NULL, NULL, NULL, 0,
675 		    VM_SLEEP, IPL_NONE);
676 		dnode->tn_spec.tn_dir.tn_seq_arena = seq_arena;
677 		KASSERT(seq_arena != NULL);
678 	}
679 	error = vmem_alloc(seq_arena, 1, VM_SLEEP | VM_BESTFIT, &off);
680 	KASSERT(error == 0);
681 
682 	KASSERT(off < TMPFS_DIRSEQ_END);
683 	seq = off | TMPFS_DIRSEQ_END;
684 	return seq;
685 }
686 
687 static void
688 tmpfs_dir_putseq(tmpfs_node_t *dnode, tmpfs_dirent_t *de)
689 {
690 	vmem_t *seq_arena = dnode->tn_spec.tn_dir.tn_seq_arena;
691 	uint32_t seq = de->td_seq;
692 
693 	TMPFS_VALIDATE_DIR(dnode);
694 
695 	if (seq == TMPFS_DIRSEQ_NONE || seq < TMPFS_DIRSEQ_END) {
696 		/* First half (or no sequence number set yet). */
697 		KASSERT(de->td_seq >= TMPFS_DIRSEQ_START);
698 	} else {
699 		/* Second half. */
700 		KASSERT(seq_arena != NULL);
701 		KASSERT(seq >= TMPFS_DIRSEQ_END);
702 		seq &= ~TMPFS_DIRSEQ_END;
703 		vmem_free(seq_arena, seq, 1);
704 	}
705 	de->td_seq = TMPFS_DIRSEQ_NONE;
706 
707 	/* Empty?  We can reset. */
708 	if (seq_arena && dnode->tn_size == 0) {
709 		dnode->tn_spec.tn_dir.tn_seq_arena = NULL;
710 		dnode->tn_spec.tn_dir.tn_next_seq = TMPFS_DIRSEQ_START;
711 		vmem_destroy(seq_arena);
712 	}
713 }
714 
715 /*
716  * tmpfs_dir_lookupbyseq: lookup a directory entry by the sequence number.
717  */
718 tmpfs_dirent_t *
719 tmpfs_dir_lookupbyseq(tmpfs_node_t *node, off_t seq)
720 {
721 	tmpfs_dirent_t *de = node->tn_spec.tn_dir.tn_readdir_lastp;
722 
723 	TMPFS_VALIDATE_DIR(node);
724 
725 	/*
726 	 * First, check the cache.  If does not match - perform a lookup.
727 	 */
728 	if (de && de->td_seq == seq) {
729 		KASSERT(de->td_seq >= TMPFS_DIRSEQ_START);
730 		KASSERT(de->td_seq != TMPFS_DIRSEQ_NONE);
731 		return de;
732 	}
733 	TAILQ_FOREACH(de, &node->tn_spec.tn_dir.tn_dir, td_entries) {
734 		KASSERT(de->td_seq >= TMPFS_DIRSEQ_START);
735 		KASSERT(de->td_seq != TMPFS_DIRSEQ_NONE);
736 		if (de->td_seq == seq)
737 			return de;
738 	}
739 	return NULL;
740 }
741 
742 /*
743  * tmpfs_dir_getdotents: helper function for tmpfs_readdir() to get the
744  * dot meta entries, that is, "." or "..".  Copy it to the UIO space.
745  */
746 static int
747 tmpfs_dir_getdotents(tmpfs_node_t *node, struct dirent *dp, struct uio *uio)
748 {
749 	tmpfs_dirent_t *de;
750 	off_t next = 0;
751 	int error;
752 
753 	switch (uio->uio_offset) {
754 	case TMPFS_DIRSEQ_DOT:
755 		dp->d_fileno = node->tn_id;
756 		strlcpy(dp->d_name, ".", sizeof(dp->d_name));
757 		next = TMPFS_DIRSEQ_DOTDOT;
758 		break;
759 	case TMPFS_DIRSEQ_DOTDOT:
760 		dp->d_fileno = node->tn_spec.tn_dir.tn_parent->tn_id;
761 		strlcpy(dp->d_name, "..", sizeof(dp->d_name));
762 		de = TAILQ_FIRST(&node->tn_spec.tn_dir.tn_dir);
763 		next = de ? tmpfs_dir_getseq(node, de) : TMPFS_DIRSEQ_EOF;
764 		break;
765 	default:
766 		KASSERT(false);
767 	}
768 	dp->d_type = DT_DIR;
769 	dp->d_namlen = strlen(dp->d_name);
770 	dp->d_reclen = _DIRENT_SIZE(dp);
771 
772 	if (dp->d_reclen > uio->uio_resid) {
773 		return EJUSTRETURN;
774 	}
775 	if ((error = uiomove(dp, dp->d_reclen, uio)) != 0) {
776 		return error;
777 	}
778 
779 	uio->uio_offset = next;
780 	return error;
781 }
782 
783 /*
784  * tmpfs_dir_getdents: helper function for tmpfs_readdir.
785  *
786  * => Returns as much directory entries as can fit in the uio space.
787  * => The read starts at uio->uio_offset.
788  */
789 int
790 tmpfs_dir_getdents(tmpfs_node_t *node, struct uio *uio, off_t *cntp)
791 {
792 	tmpfs_dirent_t *de;
793 	struct dirent *dentp;
794 	int error = 0;
795 
796 	KASSERT(VOP_ISLOCKED(node->tn_vnode));
797 	TMPFS_VALIDATE_DIR(node);
798 
799 	/*
800 	 * Allocate struct dirent and first check for the "." and "..".
801 	 * Note: tmpfs_dir_getdotents() will "seek" for us.
802 	 */
803 	dentp = kmem_zalloc(sizeof(struct dirent), KM_SLEEP);
804 
805 	if (uio->uio_offset == TMPFS_DIRSEQ_DOT) {
806 		if ((error = tmpfs_dir_getdotents(node, dentp, uio)) != 0) {
807 			goto done;
808 		}
809 		(*cntp)++;
810 	}
811 	if (uio->uio_offset == TMPFS_DIRSEQ_DOTDOT) {
812 		if ((error = tmpfs_dir_getdotents(node, dentp, uio)) != 0) {
813 			goto done;
814 		}
815 		(*cntp)++;
816 	}
817 
818 	/* Done if we reached the end. */
819 	if (uio->uio_offset == TMPFS_DIRSEQ_EOF) {
820 		goto done;
821 	}
822 
823 	/* Locate the directory entry given by the given sequence number. */
824 	de = tmpfs_dir_lookupbyseq(node, uio->uio_offset);
825 	if (de == NULL) {
826 		error = EINVAL;
827 		goto done;
828 	}
829 
830 	/*
831 	 * Read as many entries as possible; i.e., until we reach the end
832 	 * of the directory or we exhaust UIO space.
833 	 */
834 	do {
835 		if (de->td_node == TMPFS_NODE_WHITEOUT) {
836 			dentp->d_fileno = 1;
837 			dentp->d_type = DT_WHT;
838 		} else {
839 			dentp->d_fileno = de->td_node->tn_id;
840 			dentp->d_type = vtype2dt(de->td_node->tn_type);
841 		}
842 		dentp->d_namlen = de->td_namelen;
843 		KASSERT(de->td_namelen < sizeof(dentp->d_name));
844 		memcpy(dentp->d_name, de->td_name, de->td_namelen);
845 		dentp->d_name[de->td_namelen] = '\0';
846 		dentp->d_reclen = _DIRENT_SIZE(dentp);
847 
848 		if (dentp->d_reclen > uio->uio_resid) {
849 			/* Exhausted UIO space. */
850 			error = EJUSTRETURN;
851 			break;
852 		}
853 
854 		/* Copy out the directory entry and continue. */
855 		error = uiomove(dentp, dentp->d_reclen, uio);
856 		if (error) {
857 			break;
858 		}
859 		(*cntp)++;
860 		de = TAILQ_NEXT(de, td_entries);
861 
862 	} while (uio->uio_resid > 0 && de);
863 
864 	/* Cache the last entry or clear and mark EOF. */
865 	uio->uio_offset = de ? tmpfs_dir_getseq(node, de) : TMPFS_DIRSEQ_EOF;
866 	node->tn_spec.tn_dir.tn_readdir_lastp = de;
867 done:
868 	tmpfs_update(node->tn_vnode, TMPFS_UPDATE_ATIME);
869 	kmem_free(dentp, sizeof(struct dirent));
870 
871 	if (error == EJUSTRETURN) {
872 		/* Exhausted UIO space - just return. */
873 		error = 0;
874 	}
875 	KASSERT(error >= 0);
876 	return error;
877 }
878 
879 /*
880  * tmpfs_reg_resize: resize the underlying UVM object associated with the
881  * specified regular file.
882  */
883 int
884 tmpfs_reg_resize(struct vnode *vp, off_t newsize)
885 {
886 	tmpfs_mount_t *tmp = VFS_TO_TMPFS(vp->v_mount);
887 	tmpfs_node_t *node = VP_TO_TMPFS_NODE(vp);
888 	struct uvm_object *uobj = node->tn_spec.tn_reg.tn_aobj;
889 	size_t newpages, oldpages;
890 	off_t oldsize;
891 
892 	KASSERT(vp->v_type == VREG);
893 	KASSERT(newsize >= 0);
894 
895 	oldsize = node->tn_size;
896 	oldpages = round_page(oldsize) >> PAGE_SHIFT;
897 	newpages = round_page(newsize) >> PAGE_SHIFT;
898 	KASSERT(oldpages == node->tn_spec.tn_reg.tn_aobj_pages);
899 
900 	if (newpages > oldpages) {
901 		/* Increase the used-memory counter if getting extra pages. */
902 		if (!tmpfs_mem_incr(tmp, (newpages - oldpages) << PAGE_SHIFT)) {
903 			return ENOSPC;
904 		}
905 	} else if (newsize < oldsize) {
906 		size_t zerolen;
907 
908 		zerolen = MIN(round_page(newsize), node->tn_size) - newsize;
909 		ubc_zerorange(uobj, newsize, zerolen, UBC_UNMAP_FLAG(vp));
910 	}
911 
912 	node->tn_spec.tn_reg.tn_aobj_pages = newpages;
913 	node->tn_size = newsize;
914 	uvm_vnp_setsize(vp, newsize);
915 
916 	/*
917 	 * Free "backing store".
918 	 */
919 	if (newpages < oldpages) {
920 		KASSERT(uobj->vmobjlock == vp->v_interlock);
921 
922 		mutex_enter(uobj->vmobjlock);
923 		uao_dropswap_range(uobj, newpages, oldpages);
924 		mutex_exit(uobj->vmobjlock);
925 
926 		/* Decrease the used-memory counter. */
927 		tmpfs_mem_decr(tmp, (oldpages - newpages) << PAGE_SHIFT);
928 	}
929 	if (newsize > oldsize) {
930 		VN_KNOTE(vp, NOTE_EXTEND);
931 	}
932 	return 0;
933 }
934 
935 /*
936  * tmpfs_chflags: change flags of the given vnode.
937  */
938 int
939 tmpfs_chflags(vnode_t *vp, int flags, kauth_cred_t cred, lwp_t *l)
940 {
941 	tmpfs_node_t *node = VP_TO_TMPFS_NODE(vp);
942 	kauth_action_t action = KAUTH_VNODE_WRITE_FLAGS;
943 	int error;
944 	bool changing_sysflags = false;
945 
946 	KASSERT(VOP_ISLOCKED(vp));
947 
948 	/* Disallow this operation if the file system is mounted read-only. */
949 	if (vp->v_mount->mnt_flag & MNT_RDONLY)
950 		return EROFS;
951 
952 	/*
953 	 * If the new flags have non-user flags that are different than
954 	 * those on the node, we need special permission to change them.
955 	 */
956 	if ((flags & SF_SETTABLE) != (node->tn_flags & SF_SETTABLE)) {
957 		action |= KAUTH_VNODE_WRITE_SYSFLAGS;
958 		changing_sysflags = true;
959 	}
960 
961 	/*
962 	 * Indicate that this node's flags have system attributes in them if
963 	 * that's the case.
964 	 */
965 	if (node->tn_flags & (SF_IMMUTABLE | SF_APPEND)) {
966 		action |= KAUTH_VNODE_HAS_SYSFLAGS;
967 	}
968 
969 	error = kauth_authorize_vnode(cred, action, vp, NULL,
970 	    genfs_can_chflags(cred, vp->v_type, node->tn_uid,
971 	    changing_sysflags));
972 	if (error)
973 		return error;
974 
975 	/*
976 	 * Set the flags. If we're not setting non-user flags, be careful not
977 	 * to overwrite them.
978 	 *
979 	 * XXX: Can't we always assign here? if the system flags are different,
980 	 *      the code above should catch attempts to change them without
981 	 *      proper permissions, and if we're here it means it's okay to
982 	 *      change them...
983 	 */
984 	if (!changing_sysflags) {
985 		/* Clear all user-settable flags and re-set them. */
986 		node->tn_flags &= SF_SETTABLE;
987 		node->tn_flags |= (flags & UF_SETTABLE);
988 	} else {
989 		node->tn_flags = flags;
990 	}
991 	tmpfs_update(vp, TMPFS_UPDATE_CTIME);
992 	VN_KNOTE(vp, NOTE_ATTRIB);
993 	return 0;
994 }
995 
996 /*
997  * tmpfs_chmod: change access mode on the given vnode.
998  */
999 int
1000 tmpfs_chmod(vnode_t *vp, mode_t mode, kauth_cred_t cred, lwp_t *l)
1001 {
1002 	tmpfs_node_t *node = VP_TO_TMPFS_NODE(vp);
1003 	int error;
1004 
1005 	KASSERT(VOP_ISLOCKED(vp));
1006 
1007 	/* Disallow this operation if the file system is mounted read-only. */
1008 	if (vp->v_mount->mnt_flag & MNT_RDONLY)
1009 		return EROFS;
1010 
1011 	/* Immutable or append-only files cannot be modified, either. */
1012 	if (node->tn_flags & (IMMUTABLE | APPEND))
1013 		return EPERM;
1014 
1015 	error = kauth_authorize_vnode(cred, KAUTH_VNODE_WRITE_SECURITY, vp,
1016 	    NULL, genfs_can_chmod(vp->v_type, cred, node->tn_uid, node->tn_gid, mode));
1017 	if (error) {
1018 		return error;
1019 	}
1020 	node->tn_mode = (mode & ALLPERMS);
1021 	tmpfs_update(vp, TMPFS_UPDATE_CTIME);
1022 	VN_KNOTE(vp, NOTE_ATTRIB);
1023 	return 0;
1024 }
1025 
1026 /*
1027  * tmpfs_chown: change ownership of the given vnode.
1028  *
1029  * => At least one of uid or gid must be different than VNOVAL.
1030  * => Attribute is unchanged for VNOVAL case.
1031  */
1032 int
1033 tmpfs_chown(vnode_t *vp, uid_t uid, gid_t gid, kauth_cred_t cred, lwp_t *l)
1034 {
1035 	tmpfs_node_t *node = VP_TO_TMPFS_NODE(vp);
1036 	int error;
1037 
1038 	KASSERT(VOP_ISLOCKED(vp));
1039 
1040 	/* Assign default values if they are unknown. */
1041 	KASSERT(uid != VNOVAL || gid != VNOVAL);
1042 	if (uid == VNOVAL) {
1043 		uid = node->tn_uid;
1044 	}
1045 	if (gid == VNOVAL) {
1046 		gid = node->tn_gid;
1047 	}
1048 
1049 	/* Disallow this operation if the file system is mounted read-only. */
1050 	if (vp->v_mount->mnt_flag & MNT_RDONLY)
1051 		return EROFS;
1052 
1053 	/* Immutable or append-only files cannot be modified, either. */
1054 	if (node->tn_flags & (IMMUTABLE | APPEND))
1055 		return EPERM;
1056 
1057 	error = kauth_authorize_vnode(cred, KAUTH_VNODE_CHANGE_OWNERSHIP, vp,
1058 	    NULL, genfs_can_chown(cred, node->tn_uid, node->tn_gid, uid,
1059 	    gid));
1060 	if (error) {
1061 		return error;
1062 	}
1063 	node->tn_uid = uid;
1064 	node->tn_gid = gid;
1065 	tmpfs_update(vp, TMPFS_UPDATE_CTIME);
1066 	VN_KNOTE(vp, NOTE_ATTRIB);
1067 	return 0;
1068 }
1069 
1070 /*
1071  * tmpfs_chsize: change size of the given vnode.
1072  */
1073 int
1074 tmpfs_chsize(vnode_t *vp, u_quad_t size, kauth_cred_t cred, lwp_t *l)
1075 {
1076 	tmpfs_node_t *node = VP_TO_TMPFS_NODE(vp);
1077 	const off_t length = size;
1078 	int error;
1079 
1080 	KASSERT(VOP_ISLOCKED(vp));
1081 
1082 	/* Decide whether this is a valid operation based on the file type. */
1083 	switch (vp->v_type) {
1084 	case VDIR:
1085 		return EISDIR;
1086 	case VREG:
1087 		if (vp->v_mount->mnt_flag & MNT_RDONLY) {
1088 			return EROFS;
1089 		}
1090 		break;
1091 	case VBLK:
1092 	case VCHR:
1093 	case VFIFO:
1094 		/*
1095 		 * Allow modifications of special files even if in the file
1096 		 * system is mounted read-only (we are not modifying the
1097 		 * files themselves, but the objects they represent).
1098 		 */
1099 		return 0;
1100 	default:
1101 		return EOPNOTSUPP;
1102 	}
1103 
1104 	/* Immutable or append-only files cannot be modified, either. */
1105 	if (node->tn_flags & (IMMUTABLE | APPEND)) {
1106 		return EPERM;
1107 	}
1108 
1109 	if (length < 0) {
1110 		return EINVAL;
1111 	}
1112 	if (node->tn_size == length) {
1113 		return 0;
1114 	}
1115 
1116 	/* Note: tmpfs_reg_resize() will raise NOTE_EXTEND and NOTE_ATTRIB. */
1117 	if ((error = tmpfs_reg_resize(vp, length)) != 0) {
1118 		return error;
1119 	}
1120 	tmpfs_update(vp, TMPFS_UPDATE_CTIME | TMPFS_UPDATE_MTIME);
1121 	return 0;
1122 }
1123 
1124 /*
1125  * tmpfs_chtimes: change access and modification times for vnode.
1126  */
1127 int
1128 tmpfs_chtimes(vnode_t *vp, const struct timespec *atime,
1129     const struct timespec *mtime, const struct timespec *btime,
1130     int vaflags, kauth_cred_t cred, lwp_t *l)
1131 {
1132 	tmpfs_node_t *node = VP_TO_TMPFS_NODE(vp);
1133 	int error;
1134 
1135 	KASSERT(VOP_ISLOCKED(vp));
1136 
1137 	/* Disallow this operation if the file system is mounted read-only. */
1138 	if (vp->v_mount->mnt_flag & MNT_RDONLY)
1139 		return EROFS;
1140 
1141 	/* Immutable or append-only files cannot be modified, either. */
1142 	if (node->tn_flags & (IMMUTABLE | APPEND))
1143 		return EPERM;
1144 
1145 	error = kauth_authorize_vnode(cred, KAUTH_VNODE_WRITE_TIMES, vp, NULL,
1146 	    genfs_can_chtimes(vp, vaflags, node->tn_uid, cred));
1147 	if (error)
1148 		return error;
1149 
1150 	if (atime->tv_sec != VNOVAL) {
1151 		node->tn_atime = *atime;
1152 	}
1153 	if (mtime->tv_sec != VNOVAL) {
1154 		node->tn_mtime = *mtime;
1155 	}
1156 	if (btime->tv_sec != VNOVAL) {
1157 		node->tn_birthtime = *btime;
1158 	}
1159 	VN_KNOTE(vp, NOTE_ATTRIB);
1160 	return 0;
1161 }
1162 
1163 /*
1164  * tmpfs_update: update the timestamps as indicated by the flags.
1165  */
1166 void
1167 tmpfs_update(vnode_t *vp, unsigned tflags)
1168 {
1169 	tmpfs_node_t *node = VP_TO_TMPFS_NODE(vp);
1170 	struct timespec nowtm;
1171 
1172 	if (tflags == 0) {
1173 		return;
1174 	}
1175 	vfs_timestamp(&nowtm);
1176 
1177 	if (tflags & TMPFS_UPDATE_ATIME) {
1178 		node->tn_atime = nowtm;
1179 	}
1180 	if (tflags & TMPFS_UPDATE_MTIME) {
1181 		node->tn_mtime = nowtm;
1182 	}
1183 	if (tflags & TMPFS_UPDATE_CTIME) {
1184 		node->tn_ctime = nowtm;
1185 	}
1186 }
1187