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