xref: /netbsd-src/sys/fs/tmpfs/tmpfs_subr.c (revision b1c86f5f087524e68db12794ee9c3e3da1ab17a0)
1 /*	$NetBSD: tmpfs_subr.c,v 1.59 2010/07/21 17:52:11 hannken Exp $	*/
2 
3 /*
4  * Copyright (c) 2005, 2006, 2007 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 
37 #include <sys/cdefs.h>
38 __KERNEL_RCSID(0, "$NetBSD: tmpfs_subr.c,v 1.59 2010/07/21 17:52:11 hannken Exp $");
39 
40 #include <sys/param.h>
41 #include <sys/dirent.h>
42 #include <sys/event.h>
43 #include <sys/kmem.h>
44 #include <sys/mount.h>
45 #include <sys/namei.h>
46 #include <sys/time.h>
47 #include <sys/stat.h>
48 #include <sys/systm.h>
49 #include <sys/swap.h>
50 #include <sys/vnode.h>
51 #include <sys/kauth.h>
52 #include <sys/proc.h>
53 #include <sys/atomic.h>
54 
55 #include <uvm/uvm.h>
56 
57 #include <miscfs/specfs/specdev.h>
58 #include <miscfs/genfs/genfs.h>
59 #include <fs/tmpfs/tmpfs.h>
60 #include <fs/tmpfs/tmpfs_fifoops.h>
61 #include <fs/tmpfs/tmpfs_specops.h>
62 #include <fs/tmpfs/tmpfs_vnops.h>
63 
64 /* --------------------------------------------------------------------- */
65 
66 /*
67  * Allocates a new node of type 'type' inside the 'tmp' mount point, with
68  * its owner set to 'uid', its group to 'gid' and its mode set to 'mode',
69  * using the credentials of the process 'p'.
70  *
71  * If the node type is set to 'VDIR', then the parent parameter must point
72  * to the parent directory of the node being created.  It may only be NULL
73  * while allocating the root node.
74  *
75  * If the node type is set to 'VBLK' or 'VCHR', then the rdev parameter
76  * specifies the device the node represents.
77  *
78  * If the node type is set to 'VLNK', then the parameter target specifies
79  * the file name of the target file for the symbolic link that is being
80  * created.
81  *
82  * Note that new nodes are retrieved from the available list if it has
83  * items or, if it is empty, from the node pool as long as there is enough
84  * space to create them.
85  *
86  * Returns zero on success or an appropriate error code on failure.
87  */
88 int
89 tmpfs_alloc_node(struct tmpfs_mount *tmp, enum vtype type,
90     uid_t uid, gid_t gid, mode_t mode, struct tmpfs_node *parent,
91     char *target, dev_t rdev, struct tmpfs_node **node)
92 {
93 	struct tmpfs_node *nnode;
94 
95 	/* If the root directory of the 'tmp' file system is not yet
96 	 * allocated, this must be the request to do it. */
97 	KASSERT(IMPLIES(tmp->tm_root == NULL, parent == NULL && type == VDIR));
98 
99 	KASSERT(IFF(type == VLNK, target != NULL));
100 	KASSERT(IFF(type == VBLK || type == VCHR, rdev != VNOVAL));
101 
102 	KASSERT(uid != VNOVAL && gid != VNOVAL && mode != VNOVAL);
103 
104 	nnode = NULL;
105 	if (atomic_inc_uint_nv(&tmp->tm_nodes_cnt) >= tmp->tm_nodes_max) {
106 		atomic_dec_uint(&tmp->tm_nodes_cnt);
107 		return ENOSPC;
108 	}
109 
110 	nnode = tmpfs_node_get(tmp);
111 	if (nnode == NULL) {
112 		atomic_dec_uint(&tmp->tm_nodes_cnt);
113 		return ENOSPC;
114 	}
115 
116 	/*
117 	 * XXX Where the pool is backed by a map larger than (4GB *
118 	 * sizeof(*nnode)), this may produce duplicate inode numbers
119 	 * for applications that do not understand 64-bit ino_t.
120 	 */
121 	nnode->tn_id = (ino_t)((uintptr_t)nnode / sizeof(*nnode));
122 	nnode->tn_gen = arc4random();
123 
124 	/* Generic initialization. */
125 	nnode->tn_type = type;
126 	nnode->tn_size = 0;
127 	nnode->tn_status = 0;
128 	nnode->tn_flags = 0;
129 	nnode->tn_links = 0;
130 
131 	vfs_timestamp(&nnode->tn_atime);
132 	nnode->tn_birthtime = nnode->tn_atime;
133 	nnode->tn_ctime = nnode->tn_atime;
134 	nnode->tn_mtime = nnode->tn_atime;
135 
136 	nnode->tn_uid = uid;
137 	nnode->tn_gid = gid;
138 	nnode->tn_mode = mode;
139 	nnode->tn_lockf = NULL;
140 	nnode->tn_vnode = NULL;
141 
142 	/* Type-specific initialization. */
143 	switch (nnode->tn_type) {
144 	case VBLK:
145 	case VCHR:
146 		nnode->tn_spec.tn_dev.tn_rdev = rdev;
147 		break;
148 
149 	case VDIR:
150 		TAILQ_INIT(&nnode->tn_spec.tn_dir.tn_dir);
151 		nnode->tn_spec.tn_dir.tn_parent =
152 		    (parent == NULL) ? nnode : parent;
153 		nnode->tn_spec.tn_dir.tn_readdir_lastn = 0;
154 		nnode->tn_spec.tn_dir.tn_readdir_lastp = NULL;
155 		nnode->tn_links++;
156 		break;
157 
158 	case VFIFO:
159 		/* FALLTHROUGH */
160 	case VSOCK:
161 		break;
162 
163 	case VLNK:
164 		KASSERT(strlen(target) < MAXPATHLEN);
165 		nnode->tn_size = strlen(target);
166 		nnode->tn_spec.tn_lnk.tn_link =
167 		    tmpfs_strname_alloc(tmp, nnode->tn_size);
168 		if (nnode->tn_spec.tn_lnk.tn_link == NULL) {
169 			atomic_dec_uint(&tmp->tm_nodes_cnt);
170 			tmpfs_node_put(tmp, nnode);
171 			return ENOSPC;
172 		}
173 		memcpy(nnode->tn_spec.tn_lnk.tn_link, target, nnode->tn_size);
174 		break;
175 
176 	case VREG:
177 		nnode->tn_spec.tn_reg.tn_aobj =
178 		    uao_create(INT32_MAX - PAGE_SIZE, 0);
179 		nnode->tn_spec.tn_reg.tn_aobj_pages = 0;
180 		break;
181 
182 	default:
183 		KASSERT(0);
184 	}
185 
186 	mutex_init(&nnode->tn_vlock, MUTEX_DEFAULT, IPL_NONE);
187 
188 	mutex_enter(&tmp->tm_lock);
189 	LIST_INSERT_HEAD(&tmp->tm_nodes, nnode, tn_entries);
190 	mutex_exit(&tmp->tm_lock);
191 
192 	*node = nnode;
193 	return 0;
194 }
195 
196 /* --------------------------------------------------------------------- */
197 
198 /*
199  * Destroys the node pointed to by node from the file system 'tmp'.
200  * If the node does not belong to the given mount point, the results are
201  * unpredicted.
202  *
203  * If the node references a directory; no entries are allowed because
204  * their removal could need a recursive algorithm, something forbidden in
205  * kernel space.  Furthermore, there is not need to provide such
206  * functionality (recursive removal) because the only primitives offered
207  * to the user are the removal of empty directories and the deletion of
208  * individual files.
209  *
210  * Note that nodes are not really deleted; in fact, when a node has been
211  * allocated, it cannot be deleted during the whole life of the file
212  * system.  Instead, they are moved to the available list and remain there
213  * until reused.
214  */
215 void
216 tmpfs_free_node(struct tmpfs_mount *tmp, struct tmpfs_node *node)
217 {
218 	size_t objsz;
219 
220 	mutex_enter(&tmp->tm_lock);
221 	LIST_REMOVE(node, tn_entries);
222 	mutex_exit(&tmp->tm_lock);
223 	atomic_dec_uint(&tmp->tm_nodes_cnt);
224 
225 	switch (node->tn_type) {
226 	case VLNK:
227 		tmpfs_strname_free(tmp, node->tn_spec.tn_lnk.tn_link,
228 		    node->tn_size);
229 		break;
230 	case VREG:
231 		/*
232 		 * Calculate the size of node data, decrease the used-memory
233 		 * counter, and destroy the memory object (if any).
234 		 */
235 		objsz = PAGE_SIZE * node->tn_spec.tn_reg.tn_aobj_pages;
236 		if (objsz != 0) {
237 			tmpfs_mem_decr(tmp, objsz);
238 		}
239 		if (node->tn_spec.tn_reg.tn_aobj != NULL) {
240 			uao_detach(node->tn_spec.tn_reg.tn_aobj);
241 		}
242 		break;
243 	default:
244 		break;
245 	}
246 
247 	mutex_destroy(&node->tn_vlock);
248 	tmpfs_node_put(tmp, node);
249 }
250 
251 /* --------------------------------------------------------------------- */
252 
253 /*
254  * Allocates a new directory entry for the node node with a name of name.
255  * The new directory entry is returned in *de.
256  *
257  * The link count of node is increased by one to reflect the new object
258  * referencing it.  This takes care of notifying kqueue listeners about
259  * this change.
260  *
261  * Returns zero on success or an appropriate error code on failure.
262  */
263 int
264 tmpfs_alloc_dirent(struct tmpfs_mount *tmp, struct tmpfs_node *node,
265     const char *name, uint16_t len, struct tmpfs_dirent **de)
266 {
267 	struct tmpfs_dirent *nde;
268 
269 	nde = tmpfs_dirent_get(tmp);
270 	if (nde == NULL)
271 		return ENOSPC;
272 
273 	nde->td_name = tmpfs_strname_alloc(tmp, len);
274 	if (nde->td_name == NULL) {
275 		tmpfs_dirent_put(tmp, nde);
276 		return ENOSPC;
277 	}
278 	nde->td_namelen = len;
279 	memcpy(nde->td_name, name, len);
280 	nde->td_node = node;
281 
282 	node->tn_links++;
283 	if (node->tn_links > 1 && node->tn_vnode != NULL)
284 		VN_KNOTE(node->tn_vnode, NOTE_LINK);
285 	*de = nde;
286 
287 	return 0;
288 }
289 
290 /* --------------------------------------------------------------------- */
291 
292 /*
293  * Frees a directory entry.  It is the caller's responsibility to destroy
294  * the node referenced by it if needed.
295  *
296  * The link count of node is decreased by one to reflect the removal of an
297  * object that referenced it.  This only happens if 'node_exists' is true;
298  * otherwise the function will not access the node referred to by the
299  * directory entry, as it may already have been released from the outside.
300  *
301  * Interested parties (kqueue) are notified of the link count change; note
302  * that this can include both the node pointed to by the directory entry
303  * as well as its parent.
304  */
305 void
306 tmpfs_free_dirent(struct tmpfs_mount *tmp, struct tmpfs_dirent *de,
307     bool node_exists)
308 {
309 	if (node_exists) {
310 		struct tmpfs_node *node;
311 
312 		node = de->td_node;
313 
314 		KASSERT(node->tn_links > 0);
315 		node->tn_links--;
316 		if (node->tn_vnode != NULL)
317 			VN_KNOTE(node->tn_vnode, node->tn_links == 0 ?
318 			    NOTE_DELETE : NOTE_LINK);
319 		if (node->tn_type == VDIR)
320 			VN_KNOTE(node->tn_spec.tn_dir.tn_parent->tn_vnode,
321 			    NOTE_LINK);
322 	}
323 
324 	tmpfs_strname_free(tmp, de->td_name, de->td_namelen);
325 	tmpfs_dirent_put(tmp, de);
326 }
327 
328 /* --------------------------------------------------------------------- */
329 
330 /*
331  * Allocates a new vnode for the node node or returns a new reference to
332  * an existing one if the node had already a vnode referencing it.  The
333  * resulting locked vnode is returned in *vpp.
334  *
335  * Returns zero on success or an appropriate error code on failure.
336  */
337 int
338 tmpfs_alloc_vp(struct mount *mp, struct tmpfs_node *node, struct vnode **vpp)
339 {
340 	int error;
341 	struct vnode *vp;
342 
343 	/* If there is already a vnode, then lock it. */
344 	for (;;) {
345 		mutex_enter(&node->tn_vlock);
346 		if ((vp = node->tn_vnode) != NULL) {
347 			mutex_enter(&vp->v_interlock);
348 			mutex_exit(&node->tn_vlock);
349 			error = vget(vp, LK_EXCLUSIVE);
350 			if (error == ENOENT) {
351 				/* vnode was reclaimed. */
352 				continue;
353 			}
354 			*vpp = vp;
355 			return error;
356 		}
357 		break;
358 	}
359 
360 	/* Get a new vnode and associate it with our node. */
361 	error = getnewvnode(VT_TMPFS, mp, tmpfs_vnodeop_p, &vp);
362 	if (error != 0) {
363 		mutex_exit(&node->tn_vlock);
364 		return error;
365 	}
366 
367 	error = vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
368 	if (error != 0) {
369 		mutex_exit(&node->tn_vlock);
370 		ungetnewvnode(vp);
371 		return error;
372 	}
373 
374 	vp->v_type = node->tn_type;
375 
376 	/* Type-specific initialization. */
377 	switch (node->tn_type) {
378 	case VBLK:
379 		/* FALLTHROUGH */
380 	case VCHR:
381 		vp->v_op = tmpfs_specop_p;
382 		spec_node_init(vp, node->tn_spec.tn_dev.tn_rdev);
383 		break;
384 
385 	case VDIR:
386 		vp->v_vflag |= node->tn_spec.tn_dir.tn_parent == node ?
387 		    VV_ROOT : 0;
388 		break;
389 
390 	case VFIFO:
391 		vp->v_op = tmpfs_fifoop_p;
392 		break;
393 
394 	case VLNK:
395 		/* FALLTHROUGH */
396 	case VREG:
397 		/* FALLTHROUGH */
398 	case VSOCK:
399 		break;
400 
401 	default:
402 		KASSERT(0);
403 	}
404 
405 	uvm_vnp_setsize(vp, node->tn_size);
406 	vp->v_data = node;
407 	node->tn_vnode = vp;
408 	mutex_exit(&node->tn_vlock);
409 	*vpp = vp;
410 
411 	KASSERT(IFF(error == 0, *vpp != NULL && VOP_ISLOCKED(*vpp)));
412 	KASSERT(*vpp == node->tn_vnode);
413 
414 	return error;
415 }
416 
417 /* --------------------------------------------------------------------- */
418 
419 /*
420  * Destroys the association between the vnode vp and the node it
421  * references.
422  */
423 void
424 tmpfs_free_vp(struct vnode *vp)
425 {
426 	struct tmpfs_node *node;
427 
428 	node = VP_TO_TMPFS_NODE(vp);
429 
430 	mutex_enter(&node->tn_vlock);
431 	node->tn_vnode = NULL;
432 	mutex_exit(&node->tn_vlock);
433 	vp->v_data = NULL;
434 }
435 
436 /* --------------------------------------------------------------------- */
437 
438 /*
439  * Allocates a new file of type 'type' and adds it to the parent directory
440  * 'dvp'; this addition is done using the component name given in 'cnp'.
441  * The ownership of the new file is automatically assigned based on the
442  * credentials of the caller (through 'cnp'), the group is set based on
443  * the parent directory and the mode is determined from the 'vap' argument.
444  * If successful, *vpp holds a vnode to the newly created file and zero
445  * is returned.  Otherwise *vpp is NULL and the function returns an
446  * appropriate error code.
447  */
448 int
449 tmpfs_alloc_file(struct vnode *dvp, struct vnode **vpp, struct vattr *vap,
450     struct componentname *cnp, char *target)
451 {
452 	int error;
453 	struct tmpfs_dirent *de;
454 	struct tmpfs_mount *tmp;
455 	struct tmpfs_node *dnode;
456 	struct tmpfs_node *node;
457 	struct tmpfs_node *parent;
458 
459 	KASSERT(VOP_ISLOCKED(dvp));
460 	KASSERT(cnp->cn_flags & HASBUF);
461 
462 	tmp = VFS_TO_TMPFS(dvp->v_mount);
463 	dnode = VP_TO_TMPFS_DIR(dvp);
464 	*vpp = NULL;
465 
466 	/* If the entry we are creating is a directory, we cannot overflow
467 	 * the number of links of its parent, because it will get a new
468 	 * link. */
469 	if (vap->va_type == VDIR) {
470 		/* Ensure that we do not overflow the maximum number of links
471 		 * imposed by the system. */
472 		KASSERT(dnode->tn_links <= LINK_MAX);
473 		if (dnode->tn_links == LINK_MAX) {
474 			error = EMLINK;
475 			goto out;
476 		}
477 
478 		parent = dnode;
479 	} else
480 		parent = NULL;
481 
482 	/* Allocate a node that represents the new file. */
483 	error = tmpfs_alloc_node(tmp, vap->va_type, kauth_cred_geteuid(cnp->cn_cred),
484 	    dnode->tn_gid, vap->va_mode, parent, target, vap->va_rdev, &node);
485 	if (error != 0)
486 		goto out;
487 
488 	/* Allocate a directory entry that points to the new file. */
489 	error = tmpfs_alloc_dirent(tmp, node, cnp->cn_nameptr, cnp->cn_namelen,
490 	    &de);
491 	if (error != 0) {
492 		tmpfs_free_node(tmp, node);
493 		goto out;
494 	}
495 
496 	/* Allocate a vnode for the new file. */
497 	error = tmpfs_alloc_vp(dvp->v_mount, node, vpp);
498 	if (error != 0) {
499 		tmpfs_free_dirent(tmp, de, true);
500 		tmpfs_free_node(tmp, node);
501 		goto out;
502 	}
503 
504 	/* Now that all required items are allocated, we can proceed to
505 	 * insert the new node into the directory, an operation that
506 	 * cannot fail. */
507 	tmpfs_dir_attach(dvp, de);
508 	if (vap->va_type == VDIR) {
509 		VN_KNOTE(dvp, NOTE_LINK);
510 		dnode->tn_links++;
511 		KASSERT(dnode->tn_links <= LINK_MAX);
512 	}
513 
514 out:
515 	if (error != 0 || !(cnp->cn_flags & SAVESTART))
516 		PNBUF_PUT(cnp->cn_pnbuf);
517 	vput(dvp);
518 
519 	KASSERT(IFF(error == 0, *vpp != NULL));
520 
521 	return error;
522 }
523 
524 /* --------------------------------------------------------------------- */
525 
526 /*
527  * Attaches the directory entry de to the directory represented by vp.
528  * Note that this does not change the link count of the node pointed by
529  * the directory entry, as this is done by tmpfs_alloc_dirent.
530  *
531  * As the "parent" directory changes, interested parties are notified of
532  * a write to it.
533  */
534 void
535 tmpfs_dir_attach(struct vnode *vp, struct tmpfs_dirent *de)
536 {
537 	struct tmpfs_node *dnode;
538 
539 	KASSERT(VOP_ISLOCKED(vp));
540 	dnode = VP_TO_TMPFS_DIR(vp);
541 
542 	TAILQ_INSERT_TAIL(&dnode->tn_spec.tn_dir.tn_dir, de, td_entries);
543 	dnode->tn_size += sizeof(struct tmpfs_dirent);
544 	dnode->tn_status |= TMPFS_NODE_ACCESSED | TMPFS_NODE_CHANGED | \
545 	    TMPFS_NODE_MODIFIED;
546 	uvm_vnp_setsize(vp, dnode->tn_size);
547 
548 	VN_KNOTE(vp, NOTE_WRITE);
549 }
550 
551 /* --------------------------------------------------------------------- */
552 
553 /*
554  * Detaches the directory entry de from the directory represented by vp.
555  * Note that this does not change the link count of the node pointed by
556  * the directory entry, as this is done by tmpfs_free_dirent.
557  *
558  * As the "parent" directory changes, interested parties are notified of
559  * a write to it.
560  */
561 void
562 tmpfs_dir_detach(struct vnode *vp, struct tmpfs_dirent *de)
563 {
564 	struct tmpfs_node *dnode;
565 
566 	KASSERT(VOP_ISLOCKED(vp));
567 	dnode = VP_TO_TMPFS_DIR(vp);
568 
569 	if (dnode->tn_spec.tn_dir.tn_readdir_lastp == de) {
570 		dnode->tn_spec.tn_dir.tn_readdir_lastn = 0;
571 		dnode->tn_spec.tn_dir.tn_readdir_lastp = NULL;
572 	}
573 
574 	TAILQ_REMOVE(&dnode->tn_spec.tn_dir.tn_dir, de, td_entries);
575 	dnode->tn_size -= sizeof(struct tmpfs_dirent);
576 	dnode->tn_status |= TMPFS_NODE_ACCESSED | TMPFS_NODE_CHANGED | \
577 	    TMPFS_NODE_MODIFIED;
578 	uvm_vnp_setsize(vp, dnode->tn_size);
579 
580 	VN_KNOTE(vp, NOTE_WRITE);
581 }
582 
583 /* --------------------------------------------------------------------- */
584 
585 /*
586  * Looks for a directory entry in the directory represented by node.
587  * 'cnp' describes the name of the entry to look for.  Note that the .
588  * and .. components are not allowed as they do not physically exist
589  * within directories.
590  *
591  * Returns a pointer to the entry when found, otherwise NULL.
592  */
593 struct tmpfs_dirent *
594 tmpfs_dir_lookup(struct tmpfs_node *node, struct componentname *cnp)
595 {
596 	struct tmpfs_dirent *de;
597 
598 	KASSERT(VOP_ISLOCKED(node->tn_vnode));
599 	KASSERT(IMPLIES(cnp->cn_namelen == 1, cnp->cn_nameptr[0] != '.'));
600 	KASSERT(IMPLIES(cnp->cn_namelen == 2, !(cnp->cn_nameptr[0] == '.' &&
601 	    cnp->cn_nameptr[1] == '.')));
602 	TMPFS_VALIDATE_DIR(node);
603 
604 	node->tn_status |= TMPFS_NODE_ACCESSED;
605 
606 	TAILQ_FOREACH(de, &node->tn_spec.tn_dir.tn_dir, td_entries) {
607 		KASSERT(cnp->cn_namelen < 0xffff);
608 		if (de->td_namelen == (uint16_t)cnp->cn_namelen &&
609 		    memcmp(de->td_name, cnp->cn_nameptr, de->td_namelen) == 0) {
610 			break;
611 		}
612 	}
613 
614 	return de;
615 }
616 
617 /* --------------------------------------------------------------------- */
618 
619 /*
620  * Helper function for tmpfs_readdir.  Creates a '.' entry for the given
621  * directory and returns it in the uio space.  The function returns 0
622  * on success, -1 if there was not enough space in the uio structure to
623  * hold the directory entry or an appropriate error code if another
624  * error happens.
625  */
626 int
627 tmpfs_dir_getdotdent(struct tmpfs_node *node, struct uio *uio)
628 {
629 	int error;
630 	struct dirent *dentp;
631 
632 	TMPFS_VALIDATE_DIR(node);
633 	KASSERT(uio->uio_offset == TMPFS_DIRCOOKIE_DOT);
634 
635 	dentp = kmem_alloc(sizeof(struct dirent), KM_SLEEP);
636 
637 	dentp->d_fileno = node->tn_id;
638 	dentp->d_type = DT_DIR;
639 	dentp->d_namlen = 1;
640 	dentp->d_name[0] = '.';
641 	dentp->d_name[1] = '\0';
642 	dentp->d_reclen = _DIRENT_SIZE(dentp);
643 
644 	if (dentp->d_reclen > uio->uio_resid)
645 		error = -1;
646 	else {
647 		error = uiomove(dentp, dentp->d_reclen, uio);
648 		if (error == 0)
649 			uio->uio_offset = TMPFS_DIRCOOKIE_DOTDOT;
650 	}
651 
652 	node->tn_status |= TMPFS_NODE_ACCESSED;
653 
654 	kmem_free(dentp, sizeof(struct dirent));
655 	return error;
656 }
657 
658 /* --------------------------------------------------------------------- */
659 
660 /*
661  * Helper function for tmpfs_readdir.  Creates a '..' entry for the given
662  * directory and returns it in the uio space.  The function returns 0
663  * on success, -1 if there was not enough space in the uio structure to
664  * hold the directory entry or an appropriate error code if another
665  * error happens.
666  */
667 int
668 tmpfs_dir_getdotdotdent(struct tmpfs_node *node, struct uio *uio)
669 {
670 	int error;
671 	struct dirent *dentp;
672 
673 	TMPFS_VALIDATE_DIR(node);
674 	KASSERT(uio->uio_offset == TMPFS_DIRCOOKIE_DOTDOT);
675 
676 	dentp = kmem_alloc(sizeof(struct dirent), KM_SLEEP);
677 
678 	dentp->d_fileno = node->tn_spec.tn_dir.tn_parent->tn_id;
679 	dentp->d_type = DT_DIR;
680 	dentp->d_namlen = 2;
681 	dentp->d_name[0] = '.';
682 	dentp->d_name[1] = '.';
683 	dentp->d_name[2] = '\0';
684 	dentp->d_reclen = _DIRENT_SIZE(dentp);
685 
686 	if (dentp->d_reclen > uio->uio_resid)
687 		error = -1;
688 	else {
689 		error = uiomove(dentp, dentp->d_reclen, uio);
690 		if (error == 0) {
691 			struct tmpfs_dirent *de;
692 
693 			de = TAILQ_FIRST(&node->tn_spec.tn_dir.tn_dir);
694 			if (de == NULL)
695 				uio->uio_offset = TMPFS_DIRCOOKIE_EOF;
696 			else
697 				uio->uio_offset = tmpfs_dircookie(de);
698 		}
699 	}
700 
701 	node->tn_status |= TMPFS_NODE_ACCESSED;
702 
703 	kmem_free(dentp, sizeof(struct dirent));
704 	return error;
705 }
706 
707 /* --------------------------------------------------------------------- */
708 
709 /*
710  * Lookup a directory entry by its associated cookie.
711  */
712 struct tmpfs_dirent *
713 tmpfs_dir_lookupbycookie(struct tmpfs_node *node, off_t cookie)
714 {
715 	struct tmpfs_dirent *de;
716 
717 	KASSERT(VOP_ISLOCKED(node->tn_vnode));
718 
719 	if (cookie == node->tn_spec.tn_dir.tn_readdir_lastn &&
720 	    node->tn_spec.tn_dir.tn_readdir_lastp != NULL) {
721 		return node->tn_spec.tn_dir.tn_readdir_lastp;
722 	}
723 
724 	TAILQ_FOREACH(de, &node->tn_spec.tn_dir.tn_dir, td_entries) {
725 		if (tmpfs_dircookie(de) == cookie) {
726 			break;
727 		}
728 	}
729 
730 	return de;
731 }
732 
733 /* --------------------------------------------------------------------- */
734 
735 /*
736  * Helper function for tmpfs_readdir.  Returns as much directory entries
737  * as can fit in the uio space.  The read starts at uio->uio_offset.
738  * The function returns 0 on success, -1 if there was not enough space
739  * in the uio structure to hold the directory entry or an appropriate
740  * error code if another error happens.
741  */
742 int
743 tmpfs_dir_getdents(struct tmpfs_node *node, struct uio *uio, off_t *cntp)
744 {
745 	int error;
746 	off_t startcookie;
747 	struct dirent *dentp;
748 	struct tmpfs_dirent *de;
749 
750 	KASSERT(VOP_ISLOCKED(node->tn_vnode));
751 	TMPFS_VALIDATE_DIR(node);
752 
753 	/* Locate the first directory entry we have to return.  We have cached
754 	 * the last readdir in the node, so use those values if appropriate.
755 	 * Otherwise do a linear scan to find the requested entry. */
756 	startcookie = uio->uio_offset;
757 	KASSERT(startcookie != TMPFS_DIRCOOKIE_DOT);
758 	KASSERT(startcookie != TMPFS_DIRCOOKIE_DOTDOT);
759 	if (startcookie == TMPFS_DIRCOOKIE_EOF) {
760 		return 0;
761 	} else {
762 		de = tmpfs_dir_lookupbycookie(node, startcookie);
763 	}
764 	if (de == NULL) {
765 		return EINVAL;
766 	}
767 
768 	dentp = kmem_alloc(sizeof(struct dirent), KM_SLEEP);
769 
770 	/* Read as much entries as possible; i.e., until we reach the end of
771 	 * the directory or we exhaust uio space. */
772 	do {
773 		/* Create a dirent structure representing the current
774 		 * tmpfs_node and fill it. */
775 		dentp->d_fileno = de->td_node->tn_id;
776 		switch (de->td_node->tn_type) {
777 		case VBLK:
778 			dentp->d_type = DT_BLK;
779 			break;
780 
781 		case VCHR:
782 			dentp->d_type = DT_CHR;
783 			break;
784 
785 		case VDIR:
786 			dentp->d_type = DT_DIR;
787 			break;
788 
789 		case VFIFO:
790 			dentp->d_type = DT_FIFO;
791 			break;
792 
793 		case VLNK:
794 			dentp->d_type = DT_LNK;
795 			break;
796 
797 		case VREG:
798 			dentp->d_type = DT_REG;
799 			break;
800 
801 		case VSOCK:
802 			dentp->d_type = DT_SOCK;
803 			break;
804 
805 		default:
806 			KASSERT(0);
807 		}
808 		dentp->d_namlen = de->td_namelen;
809 		KASSERT(de->td_namelen < sizeof(dentp->d_name));
810 		(void)memcpy(dentp->d_name, de->td_name, de->td_namelen);
811 		dentp->d_name[de->td_namelen] = '\0';
812 		dentp->d_reclen = _DIRENT_SIZE(dentp);
813 
814 		/* Stop reading if the directory entry we are treating is
815 		 * bigger than the amount of data that can be returned. */
816 		if (dentp->d_reclen > uio->uio_resid) {
817 			error = -1;
818 			break;
819 		}
820 
821 		/* Copy the new dirent structure into the output buffer and
822 		 * advance pointers. */
823 		error = uiomove(dentp, dentp->d_reclen, uio);
824 
825 		(*cntp)++;
826 		de = TAILQ_NEXT(de, td_entries);
827 	} while (error == 0 && uio->uio_resid > 0 && de != NULL);
828 
829 	/* Update the offset and cache. */
830 	if (de == NULL) {
831 		uio->uio_offset = TMPFS_DIRCOOKIE_EOF;
832 		node->tn_spec.tn_dir.tn_readdir_lastn = 0;
833 		node->tn_spec.tn_dir.tn_readdir_lastp = NULL;
834 	} else {
835 		node->tn_spec.tn_dir.tn_readdir_lastn = uio->uio_offset =
836 		    tmpfs_dircookie(de);
837 		node->tn_spec.tn_dir.tn_readdir_lastp = de;
838 	}
839 
840 	node->tn_status |= TMPFS_NODE_ACCESSED;
841 
842 	kmem_free(dentp, sizeof(struct dirent));
843 	return error;
844 }
845 
846 /* --------------------------------------------------------------------- */
847 
848 /*
849  * Resizes the aobj associated to the regular file pointed to by vp to
850  * the size newsize.  'vp' must point to a vnode that represents a regular
851  * file.  'newsize' must be positive.
852  *
853  * If the file is extended, the appropriate kevent is raised.  This does
854  * not rise a write event though because resizing is not the same as
855  * writing.
856  *
857  * Returns zero on success or an appropriate error code on failure.
858  */
859 int
860 tmpfs_reg_resize(struct vnode *vp, off_t newsize)
861 {
862 	size_t newpages, oldpages;
863 	struct tmpfs_mount *tmp;
864 	struct tmpfs_node *node;
865 	off_t oldsize;
866 
867 	KASSERT(vp->v_type == VREG);
868 	KASSERT(newsize >= 0);
869 
870 	node = VP_TO_TMPFS_NODE(vp);
871 	tmp = VFS_TO_TMPFS(vp->v_mount);
872 
873 	oldsize = node->tn_size;
874 	oldpages = round_page(oldsize) >> PAGE_SHIFT;
875 	newpages = round_page(newsize) >> PAGE_SHIFT;
876 	KASSERT(oldpages == node->tn_spec.tn_reg.tn_aobj_pages);
877 
878 	if (newpages > oldpages) {
879 		/* Increase the used-memory counter if getting extra pages. */
880 		if (!tmpfs_mem_incr(tmp, (newpages - oldpages) << PAGE_SHIFT)) {
881 			return ENOSPC;
882 		}
883 	} else if (newsize < oldsize) {
884 		int zerolen = MIN(round_page(newsize), node->tn_size) - newsize;
885 
886 		/* Zero out the truncated part of the last page. */
887 		uvm_vnp_zerorange(vp, newsize, zerolen);
888 	}
889 
890 	node->tn_spec.tn_reg.tn_aobj_pages = newpages;
891 	node->tn_size = newsize;
892 	uvm_vnp_setsize(vp, newsize);
893 
894 	/*
895 	 * Free "backing store".
896 	 */
897 	if (newpages < oldpages) {
898 		struct uvm_object *uobj;
899 
900 		uobj = node->tn_spec.tn_reg.tn_aobj;
901 
902 		mutex_enter(&uobj->vmobjlock);
903 		uao_dropswap_range(uobj, newpages, oldpages);
904 		mutex_exit(&uobj->vmobjlock);
905 
906 		/* Decrease the used-memory counter. */
907 		tmpfs_mem_decr(tmp, (oldpages - newpages) << PAGE_SHIFT);
908 	}
909 
910 	if (newsize > oldsize)
911 		VN_KNOTE(vp, NOTE_EXTEND);
912 
913 	return 0;
914 }
915 
916 /*
917  * Change flags of the given vnode.
918  * Caller should execute tmpfs_update on vp after a successful execution.
919  * The vnode must be locked on entry and remain locked on exit.
920  */
921 int
922 tmpfs_chflags(struct vnode *vp, int flags, kauth_cred_t cred, struct lwp *l)
923 {
924 	int error;
925 	struct tmpfs_node *node;
926 	kauth_action_t action = KAUTH_VNODE_WRITE_FLAGS;
927 	int fs_decision = 0;
928 
929 	KASSERT(VOP_ISLOCKED(vp));
930 
931 	node = VP_TO_TMPFS_NODE(vp);
932 
933 	/* Disallow this operation if the file system is mounted read-only. */
934 	if (vp->v_mount->mnt_flag & MNT_RDONLY)
935 		return EROFS;
936 
937 	if (kauth_cred_geteuid(cred) != node->tn_uid)
938 		fs_decision = EACCES;
939 
940 	/*
941 	 * If the new flags have non-user flags that are different than
942 	 * those on the node, we need special permission to change them.
943 	 */
944 	if ((flags & SF_SETTABLE) != (node->tn_flags & SF_SETTABLE)) {
945 		action |= KAUTH_VNODE_WRITE_SYSFLAGS;
946 		if (!fs_decision)
947 			fs_decision = EPERM;
948 	}
949 
950 	/*
951 	 * Indicate that this node's flags have system attributes in them if
952 	 * that's the case.
953 	 */
954 	if (node->tn_flags & (SF_IMMUTABLE | SF_APPEND)) {
955 		action |= KAUTH_VNODE_HAS_SYSFLAGS;
956 	}
957 
958 	error = kauth_authorize_vnode(cred, action, vp, NULL, fs_decision);
959 	if (error)
960 		return error;
961 
962 	/*
963 	 * Set the flags. If we're not setting non-user flags, be careful not
964 	 * to overwrite them.
965 	 *
966 	 * XXX: Can't we always assign here? if the system flags are different,
967 	 *      the code above should catch attempts to change them without
968 	 *      proper permissions, and if we're here it means it's okay to
969 	 *      change them...
970 	 */
971 	if (action & KAUTH_VNODE_WRITE_SYSFLAGS) {
972 		node->tn_flags = flags;
973 	} else {
974 		/* Clear all user-settable flags and re-set them. */
975 		node->tn_flags &= SF_SETTABLE;
976 		node->tn_flags |= (flags & UF_SETTABLE);
977 	}
978 
979 	node->tn_status |= TMPFS_NODE_CHANGED;
980 	VN_KNOTE(vp, NOTE_ATTRIB);
981 
982 	KASSERT(VOP_ISLOCKED(vp));
983 
984 	return 0;
985 }
986 
987 /* --------------------------------------------------------------------- */
988 
989 /*
990  * Change access mode on the given vnode.
991  * Caller should execute tmpfs_update on vp after a successful execution.
992  * The vnode must be locked on entry and remain locked on exit.
993  */
994 int
995 tmpfs_chmod(struct vnode *vp, mode_t mode, kauth_cred_t cred, struct lwp *l)
996 {
997 	int error;
998 	struct tmpfs_node *node;
999 
1000 	KASSERT(VOP_ISLOCKED(vp));
1001 
1002 	node = VP_TO_TMPFS_NODE(vp);
1003 
1004 	/* Disallow this operation if the file system is mounted read-only. */
1005 	if (vp->v_mount->mnt_flag & MNT_RDONLY)
1006 		return EROFS;
1007 
1008 	/* Immutable or append-only files cannot be modified, either. */
1009 	if (node->tn_flags & (IMMUTABLE | APPEND))
1010 		return EPERM;
1011 
1012 	error = genfs_can_chmod(vp, cred, node->tn_uid, node->tn_gid,
1013 	    mode);
1014 
1015 	error = kauth_authorize_vnode(cred, KAUTH_VNODE_WRITE_SECURITY, vp,
1016 	    NULL, error);
1017 	if (error)
1018 		return (error);
1019 
1020 	node->tn_mode = (mode & ALLPERMS);
1021 
1022 	node->tn_status |= TMPFS_NODE_CHANGED;
1023 	VN_KNOTE(vp, NOTE_ATTRIB);
1024 
1025 	KASSERT(VOP_ISLOCKED(vp));
1026 
1027 	return 0;
1028 }
1029 
1030 /* --------------------------------------------------------------------- */
1031 
1032 /*
1033  * Change ownership of the given vnode.  At least one of uid or gid must
1034  * be different than VNOVAL.  If one is set to that value, the attribute
1035  * is unchanged.
1036  * Caller should execute tmpfs_update on vp after a successful execution.
1037  * The vnode must be locked on entry and remain locked on exit.
1038  */
1039 int
1040 tmpfs_chown(struct vnode *vp, uid_t uid, gid_t gid, kauth_cred_t cred,
1041     struct lwp *l)
1042 {
1043 	int error;
1044 	struct tmpfs_node *node;
1045 
1046 	KASSERT(VOP_ISLOCKED(vp));
1047 
1048 	node = VP_TO_TMPFS_NODE(vp);
1049 
1050 	/* Assign default values if they are unknown. */
1051 	KASSERT(uid != VNOVAL || gid != VNOVAL);
1052 	if (uid == VNOVAL)
1053 		uid = node->tn_uid;
1054 	if (gid == VNOVAL)
1055 		gid = node->tn_gid;
1056 	KASSERT(uid != VNOVAL && gid != VNOVAL);
1057 
1058 	/* Disallow this operation if the file system is mounted read-only. */
1059 	if (vp->v_mount->mnt_flag & MNT_RDONLY)
1060 		return EROFS;
1061 
1062 	/* Immutable or append-only files cannot be modified, either. */
1063 	if (node->tn_flags & (IMMUTABLE | APPEND))
1064 		return EPERM;
1065 
1066 	error = genfs_can_chown(vp, cred, node->tn_uid, node->tn_gid, uid,
1067 	    gid);
1068 
1069 	error = kauth_authorize_vnode(cred, KAUTH_VNODE_CHANGE_OWNERSHIP, vp,
1070 	    NULL, error);
1071 	if (error)
1072 		return (error);
1073 
1074 	node->tn_uid = uid;
1075 	node->tn_gid = gid;
1076 
1077 	node->tn_status |= TMPFS_NODE_CHANGED;
1078 	VN_KNOTE(vp, NOTE_ATTRIB);
1079 
1080 	KASSERT(VOP_ISLOCKED(vp));
1081 
1082 	return 0;
1083 }
1084 
1085 /* --------------------------------------------------------------------- */
1086 
1087 /*
1088  * Change size of the given vnode.
1089  * Caller should execute tmpfs_update on vp after a successful execution.
1090  * The vnode must be locked on entry and remain locked on exit.
1091  */
1092 int
1093 tmpfs_chsize(struct vnode *vp, u_quad_t size, kauth_cred_t cred,
1094     struct lwp *l)
1095 {
1096 	int error;
1097 	struct tmpfs_node *node;
1098 
1099 	KASSERT(VOP_ISLOCKED(vp));
1100 
1101 	node = VP_TO_TMPFS_NODE(vp);
1102 
1103 	/* Decide whether this is a valid operation based on the file type. */
1104 	error = 0;
1105 	switch (vp->v_type) {
1106 	case VDIR:
1107 		return EISDIR;
1108 
1109 	case VREG:
1110 		if (vp->v_mount->mnt_flag & MNT_RDONLY)
1111 			return EROFS;
1112 		break;
1113 
1114 	case VBLK:
1115 		/* FALLTHROUGH */
1116 	case VCHR:
1117 		/* FALLTHROUGH */
1118 	case VFIFO:
1119 		/* Allow modifications of special files even if in the file
1120 		 * system is mounted read-only (we are not modifying the
1121 		 * files themselves, but the objects they represent). */
1122 		return 0;
1123 
1124 	default:
1125 		/* Anything else is unsupported. */
1126 		return EOPNOTSUPP;
1127 	}
1128 
1129 	/* Immutable or append-only files cannot be modified, either. */
1130 	if (node->tn_flags & (IMMUTABLE | APPEND))
1131 		return EPERM;
1132 
1133 	error = tmpfs_truncate(vp, size);
1134 	/* tmpfs_truncate will raise the NOTE_EXTEND and NOTE_ATTRIB kevents
1135 	 * for us, as will update tn_status; no need to do that here. */
1136 
1137 	KASSERT(VOP_ISLOCKED(vp));
1138 
1139 	return error;
1140 }
1141 
1142 /* --------------------------------------------------------------------- */
1143 
1144 /*
1145  * Change access and modification times of the given vnode.
1146  * Caller should execute tmpfs_update on vp after a successful execution.
1147  * The vnode must be locked on entry and remain locked on exit.
1148  */
1149 int
1150 tmpfs_chtimes(struct vnode *vp, const struct timespec *atime,
1151     const struct timespec *mtime, const struct timespec *btime,
1152     int vaflags, kauth_cred_t cred, struct lwp *l)
1153 {
1154 	int error;
1155 	struct tmpfs_node *node;
1156 
1157 	KASSERT(VOP_ISLOCKED(vp));
1158 
1159 	node = VP_TO_TMPFS_NODE(vp);
1160 
1161 	/* Disallow this operation if the file system is mounted read-only. */
1162 	if (vp->v_mount->mnt_flag & MNT_RDONLY)
1163 		return EROFS;
1164 
1165 	/* Immutable or append-only files cannot be modified, either. */
1166 	if (node->tn_flags & (IMMUTABLE | APPEND))
1167 		return EPERM;
1168 
1169 	error = genfs_can_chtimes(vp, vaflags, node->tn_uid, cred);
1170 
1171 	error = kauth_authorize_vnode(cred, KAUTH_VNODE_WRITE_TIMES, vp, NULL,
1172 	    error);
1173 	if (error)
1174 		return (error);
1175 
1176 	if (atime->tv_sec != VNOVAL && atime->tv_nsec != VNOVAL)
1177 		node->tn_status |= TMPFS_NODE_ACCESSED;
1178 
1179 	if (mtime->tv_sec != VNOVAL && mtime->tv_nsec != VNOVAL)
1180 		node->tn_status |= TMPFS_NODE_MODIFIED;
1181 
1182 	if (btime->tv_sec == VNOVAL && btime->tv_nsec == VNOVAL)
1183 		btime = NULL;
1184 
1185 	tmpfs_update(vp, atime, mtime, btime, 0);
1186 	VN_KNOTE(vp, NOTE_ATTRIB);
1187 
1188 	KASSERT(VOP_ISLOCKED(vp));
1189 
1190 	return 0;
1191 }
1192 
1193 /* --------------------------------------------------------------------- */
1194 
1195 /* Sync timestamps */
1196 void
1197 tmpfs_itimes(struct vnode *vp, const struct timespec *acc,
1198     const struct timespec *mod, const struct timespec *birth)
1199 {
1200 	struct tmpfs_node *node;
1201 	struct timespec nowtm;
1202 
1203 	node = VP_TO_TMPFS_NODE(vp);
1204 
1205 	if ((node->tn_status & (TMPFS_NODE_ACCESSED | TMPFS_NODE_MODIFIED |
1206 	    TMPFS_NODE_CHANGED)) == 0)
1207 		return;
1208 
1209 	if (birth != NULL) {
1210 		node->tn_birthtime = *birth;
1211 	}
1212 	vfs_timestamp(&nowtm);
1213 
1214 	if (node->tn_status & TMPFS_NODE_ACCESSED) {
1215 		node->tn_atime = acc ? *acc : nowtm;
1216 	}
1217 	if (node->tn_status & TMPFS_NODE_MODIFIED) {
1218 		node->tn_mtime = mod ? *mod : nowtm;
1219 	}
1220 	if (node->tn_status & TMPFS_NODE_CHANGED) {
1221 		node->tn_ctime = nowtm;
1222 	}
1223 
1224 	node->tn_status &=
1225 	    ~(TMPFS_NODE_ACCESSED | TMPFS_NODE_MODIFIED | TMPFS_NODE_CHANGED);
1226 }
1227 
1228 /* --------------------------------------------------------------------- */
1229 
1230 void
1231 tmpfs_update(struct vnode *vp, const struct timespec *acc,
1232     const struct timespec *mod, const struct timespec *birth, int flags)
1233 {
1234 
1235 	struct tmpfs_node *node;
1236 
1237 	KASSERT(VOP_ISLOCKED(vp));
1238 
1239 	node = VP_TO_TMPFS_NODE(vp);
1240 
1241 #if 0
1242 	if (flags & UPDATE_CLOSE)
1243 		; /* XXX Need to do anything special? */
1244 #endif
1245 
1246 	tmpfs_itimes(vp, acc, mod, birth);
1247 
1248 	KASSERT(VOP_ISLOCKED(vp));
1249 }
1250 
1251 /* --------------------------------------------------------------------- */
1252 
1253 int
1254 tmpfs_truncate(struct vnode *vp, off_t length)
1255 {
1256 	bool extended;
1257 	int error;
1258 	struct tmpfs_node *node;
1259 
1260 	node = VP_TO_TMPFS_NODE(vp);
1261 	extended = length > node->tn_size;
1262 
1263 	if (length < 0) {
1264 		error = EINVAL;
1265 		goto out;
1266 	}
1267 
1268 	if (node->tn_size == length) {
1269 		error = 0;
1270 		goto out;
1271 	}
1272 
1273 	error = tmpfs_reg_resize(vp, length);
1274 	if (error == 0)
1275 		node->tn_status |= TMPFS_NODE_CHANGED | TMPFS_NODE_MODIFIED;
1276 
1277 out:
1278 	tmpfs_update(vp, NULL, NULL, NULL, 0);
1279 
1280 	return error;
1281 }
1282