]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/fs/tmpfs/tmpfs_subr.c
Merge llvm, clang, compiler-rt, libc++, libunwind, lld, lldb and openmp
[FreeBSD/FreeBSD.git] / sys / fs / tmpfs / tmpfs_subr.c
1 /*      $NetBSD: tmpfs_subr.c,v 1.35 2007/07/09 21:10:50 ad Exp $       */
2
3 /*-
4  * SPDX-License-Identifier: BSD-2-Clause-NetBSD
5  *
6  * Copyright (c) 2005 The NetBSD Foundation, Inc.
7  * All rights reserved.
8  *
9  * This code is derived from software contributed to The NetBSD Foundation
10  * by Julio M. Merino Vidal, developed as part of Google's Summer of Code
11  * 2005 program.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
23  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
24  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
25  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
26  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
27  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
28  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
29  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
30  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
31  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32  * POSSIBILITY OF SUCH DAMAGE.
33  */
34
35 /*
36  * Efficient memory file system supporting functions.
37  */
38 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD$");
40
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/dirent.h>
44 #include <sys/fnv_hash.h>
45 #include <sys/lock.h>
46 #include <sys/limits.h>
47 #include <sys/mount.h>
48 #include <sys/namei.h>
49 #include <sys/priv.h>
50 #include <sys/proc.h>
51 #include <sys/random.h>
52 #include <sys/refcount.h>
53 #include <sys/rwlock.h>
54 #include <sys/smr.h>
55 #include <sys/stat.h>
56 #include <sys/sysctl.h>
57 #include <sys/vnode.h>
58 #include <sys/vmmeter.h>
59
60 #include <vm/vm.h>
61 #include <vm/vm_param.h>
62 #include <vm/vm_object.h>
63 #include <vm/vm_page.h>
64 #include <vm/vm_pageout.h>
65 #include <vm/vm_pager.h>
66 #include <vm/vm_extern.h>
67 #include <vm/swap_pager.h>
68
69 #include <fs/tmpfs/tmpfs.h>
70 #include <fs/tmpfs/tmpfs_fifoops.h>
71 #include <fs/tmpfs/tmpfs_vnops.h>
72
73 SYSCTL_NODE(_vfs, OID_AUTO, tmpfs, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
74     "tmpfs file system");
75
76 static long tmpfs_pages_reserved = TMPFS_PAGES_MINRESERVED;
77
78 static uma_zone_t tmpfs_dirent_pool;
79 static uma_zone_t tmpfs_node_pool;
80 VFS_SMR_DECLARE;
81
82 static int
83 tmpfs_node_ctor(void *mem, int size, void *arg, int flags)
84 {
85         struct tmpfs_node *node;
86
87         node = mem;
88         node->tn_gen++;
89         node->tn_size = 0;
90         node->tn_status = 0;
91         node->tn_flags = 0;
92         node->tn_links = 0;
93         node->tn_vnode = NULL;
94         node->tn_vpstate = 0;
95         return (0);
96 }
97
98 static void
99 tmpfs_node_dtor(void *mem, int size, void *arg)
100 {
101         struct tmpfs_node *node;
102
103         node = mem;
104         node->tn_type = VNON;
105 }
106
107 static int
108 tmpfs_node_init(void *mem, int size, int flags)
109 {
110         struct tmpfs_node *node;
111
112         node = mem;
113         node->tn_id = 0;
114         mtx_init(&node->tn_interlock, "tmpfsni", NULL, MTX_DEF);
115         node->tn_gen = arc4random();
116         return (0);
117 }
118
119 static void
120 tmpfs_node_fini(void *mem, int size)
121 {
122         struct tmpfs_node *node;
123
124         node = mem;
125         mtx_destroy(&node->tn_interlock);
126 }
127
128 void
129 tmpfs_subr_init(void)
130 {
131         tmpfs_dirent_pool = uma_zcreate("TMPFS dirent",
132             sizeof(struct tmpfs_dirent), NULL, NULL, NULL, NULL,
133             UMA_ALIGN_PTR, 0);
134         tmpfs_node_pool = uma_zcreate("TMPFS node",
135             sizeof(struct tmpfs_node), tmpfs_node_ctor, tmpfs_node_dtor,
136             tmpfs_node_init, tmpfs_node_fini, UMA_ALIGN_PTR, 0);
137         VFS_SMR_ZONE_SET(tmpfs_node_pool);
138 }
139
140 void
141 tmpfs_subr_uninit(void)
142 {
143         uma_zdestroy(tmpfs_node_pool);
144         uma_zdestroy(tmpfs_dirent_pool);
145 }
146
147 static int
148 sysctl_mem_reserved(SYSCTL_HANDLER_ARGS)
149 {
150         int error;
151         long pages, bytes;
152
153         pages = *(long *)arg1;
154         bytes = pages * PAGE_SIZE;
155
156         error = sysctl_handle_long(oidp, &bytes, 0, req);
157         if (error || !req->newptr)
158                 return (error);
159
160         pages = bytes / PAGE_SIZE;
161         if (pages < TMPFS_PAGES_MINRESERVED)
162                 return (EINVAL);
163
164         *(long *)arg1 = pages;
165         return (0);
166 }
167
168 SYSCTL_PROC(_vfs_tmpfs, OID_AUTO, memory_reserved,
169     CTLTYPE_LONG|CTLFLAG_MPSAFE|CTLFLAG_RW, &tmpfs_pages_reserved, 0,
170     sysctl_mem_reserved, "L",
171     "Amount of available memory and swap below which tmpfs growth stops");
172
173 static __inline int tmpfs_dirtree_cmp(struct tmpfs_dirent *a,
174     struct tmpfs_dirent *b);
175 RB_PROTOTYPE_STATIC(tmpfs_dir, tmpfs_dirent, uh.td_entries, tmpfs_dirtree_cmp);
176
177 size_t
178 tmpfs_mem_avail(void)
179 {
180         vm_ooffset_t avail;
181
182         avail = swap_pager_avail + vm_free_count() - tmpfs_pages_reserved;
183         if (__predict_false(avail < 0))
184                 avail = 0;
185         return (avail);
186 }
187
188 size_t
189 tmpfs_pages_used(struct tmpfs_mount *tmp)
190 {
191         const size_t node_size = sizeof(struct tmpfs_node) +
192             sizeof(struct tmpfs_dirent);
193         size_t meta_pages;
194
195         meta_pages = howmany((uintmax_t)tmp->tm_nodes_inuse * node_size,
196             PAGE_SIZE);
197         return (meta_pages + tmp->tm_pages_used);
198 }
199
200 static size_t
201 tmpfs_pages_check_avail(struct tmpfs_mount *tmp, size_t req_pages)
202 {
203         if (tmpfs_mem_avail() < req_pages)
204                 return (0);
205
206         if (tmp->tm_pages_max != ULONG_MAX &&
207             tmp->tm_pages_max < req_pages + tmpfs_pages_used(tmp))
208                         return (0);
209
210         return (1);
211 }
212
213 void
214 tmpfs_ref_node(struct tmpfs_node *node)
215 {
216 #ifdef INVARIANTS
217         u_int old;
218
219         old =
220 #endif
221         refcount_acquire(&node->tn_refcount);
222 #ifdef INVARIANTS
223         KASSERT(old > 0, ("node %p zero refcount", node));
224 #endif
225 }
226
227 /*
228  * Allocates a new node of type 'type' inside the 'tmp' mount point, with
229  * its owner set to 'uid', its group to 'gid' and its mode set to 'mode',
230  * using the credentials of the process 'p'.
231  *
232  * If the node type is set to 'VDIR', then the parent parameter must point
233  * to the parent directory of the node being created.  It may only be NULL
234  * while allocating the root node.
235  *
236  * If the node type is set to 'VBLK' or 'VCHR', then the rdev parameter
237  * specifies the device the node represents.
238  *
239  * If the node type is set to 'VLNK', then the parameter target specifies
240  * the file name of the target file for the symbolic link that is being
241  * created.
242  *
243  * Note that new nodes are retrieved from the available list if it has
244  * items or, if it is empty, from the node pool as long as there is enough
245  * space to create them.
246  *
247  * Returns zero on success or an appropriate error code on failure.
248  */
249 int
250 tmpfs_alloc_node(struct mount *mp, struct tmpfs_mount *tmp, enum vtype type,
251     uid_t uid, gid_t gid, mode_t mode, struct tmpfs_node *parent,
252     const char *target, dev_t rdev, struct tmpfs_node **node)
253 {
254         struct tmpfs_node *nnode;
255         vm_object_t obj;
256
257         /* If the root directory of the 'tmp' file system is not yet
258          * allocated, this must be the request to do it. */
259         MPASS(IMPLIES(tmp->tm_root == NULL, parent == NULL && type == VDIR));
260
261         MPASS(IFF(type == VLNK, target != NULL));
262         MPASS(IFF(type == VBLK || type == VCHR, rdev != VNOVAL));
263
264         if (tmp->tm_nodes_inuse >= tmp->tm_nodes_max)
265                 return (ENOSPC);
266         if (tmpfs_pages_check_avail(tmp, 1) == 0)
267                 return (ENOSPC);
268
269         if ((mp->mnt_kern_flag & MNTK_UNMOUNT) != 0) {
270                 /*
271                  * When a new tmpfs node is created for fully
272                  * constructed mount point, there must be a parent
273                  * node, which vnode is locked exclusively.  As
274                  * consequence, if the unmount is executing in
275                  * parallel, vflush() cannot reclaim the parent vnode.
276                  * Due to this, the check for MNTK_UNMOUNT flag is not
277                  * racy: if we did not see MNTK_UNMOUNT flag, then tmp
278                  * cannot be destroyed until node construction is
279                  * finished and the parent vnode unlocked.
280                  *
281                  * Tmpfs does not need to instantiate new nodes during
282                  * unmount.
283                  */
284                 return (EBUSY);
285         }
286         if ((mp->mnt_kern_flag & MNT_RDONLY) != 0)
287                 return (EROFS);
288
289         nnode = uma_zalloc_smr(tmpfs_node_pool, M_WAITOK);
290
291         /* Generic initialization. */
292         nnode->tn_type = type;
293         vfs_timestamp(&nnode->tn_atime);
294         nnode->tn_birthtime = nnode->tn_ctime = nnode->tn_mtime =
295             nnode->tn_atime;
296         nnode->tn_uid = uid;
297         nnode->tn_gid = gid;
298         nnode->tn_mode = mode;
299         nnode->tn_id = alloc_unr64(&tmp->tm_ino_unr);
300         nnode->tn_refcount = 1;
301
302         /* Type-specific initialization. */
303         switch (nnode->tn_type) {
304         case VBLK:
305         case VCHR:
306                 nnode->tn_rdev = rdev;
307                 break;
308
309         case VDIR:
310                 RB_INIT(&nnode->tn_dir.tn_dirhead);
311                 LIST_INIT(&nnode->tn_dir.tn_dupindex);
312                 MPASS(parent != nnode);
313                 MPASS(IMPLIES(parent == NULL, tmp->tm_root == NULL));
314                 nnode->tn_dir.tn_parent = (parent == NULL) ? nnode : parent;
315                 nnode->tn_dir.tn_readdir_lastn = 0;
316                 nnode->tn_dir.tn_readdir_lastp = NULL;
317                 nnode->tn_links++;
318                 TMPFS_NODE_LOCK(nnode->tn_dir.tn_parent);
319                 nnode->tn_dir.tn_parent->tn_links++;
320                 TMPFS_NODE_UNLOCK(nnode->tn_dir.tn_parent);
321                 break;
322
323         case VFIFO:
324                 /* FALLTHROUGH */
325         case VSOCK:
326                 break;
327
328         case VLNK:
329                 MPASS(strlen(target) < MAXPATHLEN);
330                 nnode->tn_size = strlen(target);
331                 nnode->tn_link = malloc(nnode->tn_size, M_TMPFSNAME,
332                     M_WAITOK);
333                 memcpy(nnode->tn_link, target, nnode->tn_size);
334                 break;
335
336         case VREG:
337                 obj = nnode->tn_reg.tn_aobj =
338                     vm_pager_allocate(OBJT_SWAP, NULL, 0, VM_PROT_DEFAULT, 0,
339                         NULL /* XXXKIB - tmpfs needs swap reservation */);
340                 VM_OBJECT_WLOCK(obj);
341                 /* OBJ_TMPFS is set together with the setting of vp->v_object */
342                 vm_object_set_flag(obj, OBJ_TMPFS_NODE);
343                 VM_OBJECT_WUNLOCK(obj);
344                 nnode->tn_reg.tn_tmp = tmp;
345                 break;
346
347         default:
348                 panic("tmpfs_alloc_node: type %p %d", nnode,
349                     (int)nnode->tn_type);
350         }
351
352         TMPFS_LOCK(tmp);
353         LIST_INSERT_HEAD(&tmp->tm_nodes_used, nnode, tn_entries);
354         nnode->tn_attached = true;
355         tmp->tm_nodes_inuse++;
356         tmp->tm_refcount++;
357         TMPFS_UNLOCK(tmp);
358
359         *node = nnode;
360         return (0);
361 }
362
363 /*
364  * Destroys the node pointed to by node from the file system 'tmp'.
365  * If the node references a directory, no entries are allowed.
366  */
367 void
368 tmpfs_free_node(struct tmpfs_mount *tmp, struct tmpfs_node *node)
369 {
370         if (refcount_release_if_not_last(&node->tn_refcount))
371                 return;
372
373         TMPFS_LOCK(tmp);
374         TMPFS_NODE_LOCK(node);
375         if (!tmpfs_free_node_locked(tmp, node, false)) {
376                 TMPFS_NODE_UNLOCK(node);
377                 TMPFS_UNLOCK(tmp);
378         }
379 }
380
381 bool
382 tmpfs_free_node_locked(struct tmpfs_mount *tmp, struct tmpfs_node *node,
383     bool detach)
384 {
385         vm_object_t uobj;
386         bool last;
387
388         TMPFS_MP_ASSERT_LOCKED(tmp);
389         TMPFS_NODE_ASSERT_LOCKED(node);
390
391         last = refcount_release(&node->tn_refcount);
392         if (node->tn_attached && (detach || last)) {
393                 MPASS(tmp->tm_nodes_inuse > 0);
394                 tmp->tm_nodes_inuse--;
395                 LIST_REMOVE(node, tn_entries);
396                 node->tn_attached = false;
397         }
398         if (!last)
399                 return (false);
400
401 #ifdef INVARIANTS
402         MPASS(node->tn_vnode == NULL);
403         MPASS((node->tn_vpstate & TMPFS_VNODE_ALLOCATING) == 0);
404 #endif
405         TMPFS_NODE_UNLOCK(node);
406         TMPFS_UNLOCK(tmp);
407
408         switch (node->tn_type) {
409         case VBLK:
410                 /* FALLTHROUGH */
411         case VCHR:
412                 /* FALLTHROUGH */
413         case VDIR:
414                 /* FALLTHROUGH */
415         case VFIFO:
416                 /* FALLTHROUGH */
417         case VSOCK:
418                 break;
419
420         case VLNK:
421                 free(node->tn_link, M_TMPFSNAME);
422                 break;
423
424         case VREG:
425                 uobj = node->tn_reg.tn_aobj;
426                 if (uobj != NULL) {
427                         if (uobj->size != 0)
428                                 atomic_subtract_long(&tmp->tm_pages_used, uobj->size);
429                         KASSERT((uobj->flags & OBJ_TMPFS) == 0,
430                             ("leaked OBJ_TMPFS node %p vm_obj %p", node, uobj));
431                         vm_object_deallocate(uobj);
432                 }
433                 break;
434
435         default:
436                 panic("tmpfs_free_node: type %p %d", node, (int)node->tn_type);
437         }
438
439         uma_zfree_smr(tmpfs_node_pool, node);
440         TMPFS_LOCK(tmp);
441         tmpfs_free_tmp(tmp);
442         return (true);
443 }
444
445 static __inline uint32_t
446 tmpfs_dirent_hash(const char *name, u_int len)
447 {
448         uint32_t hash;
449
450         hash = fnv_32_buf(name, len, FNV1_32_INIT + len) & TMPFS_DIRCOOKIE_MASK;
451 #ifdef TMPFS_DEBUG_DIRCOOKIE_DUP
452         hash &= 0xf;
453 #endif
454         if (hash < TMPFS_DIRCOOKIE_MIN)
455                 hash += TMPFS_DIRCOOKIE_MIN;
456
457         return (hash);
458 }
459
460 static __inline off_t
461 tmpfs_dirent_cookie(struct tmpfs_dirent *de)
462 {
463         if (de == NULL)
464                 return (TMPFS_DIRCOOKIE_EOF);
465
466         MPASS(de->td_cookie >= TMPFS_DIRCOOKIE_MIN);
467
468         return (de->td_cookie);
469 }
470
471 static __inline boolean_t
472 tmpfs_dirent_dup(struct tmpfs_dirent *de)
473 {
474         return ((de->td_cookie & TMPFS_DIRCOOKIE_DUP) != 0);
475 }
476
477 static __inline boolean_t
478 tmpfs_dirent_duphead(struct tmpfs_dirent *de)
479 {
480         return ((de->td_cookie & TMPFS_DIRCOOKIE_DUPHEAD) != 0);
481 }
482
483 void
484 tmpfs_dirent_init(struct tmpfs_dirent *de, const char *name, u_int namelen)
485 {
486         de->td_hash = de->td_cookie = tmpfs_dirent_hash(name, namelen);
487         memcpy(de->ud.td_name, name, namelen);
488         de->td_namelen = namelen;
489 }
490
491 /*
492  * Allocates a new directory entry for the node node with a name of name.
493  * The new directory entry is returned in *de.
494  *
495  * The link count of node is increased by one to reflect the new object
496  * referencing it.
497  *
498  * Returns zero on success or an appropriate error code on failure.
499  */
500 int
501 tmpfs_alloc_dirent(struct tmpfs_mount *tmp, struct tmpfs_node *node,
502     const char *name, u_int len, struct tmpfs_dirent **de)
503 {
504         struct tmpfs_dirent *nde;
505
506         nde = uma_zalloc(tmpfs_dirent_pool, M_WAITOK);
507         nde->td_node = node;
508         if (name != NULL) {
509                 nde->ud.td_name = malloc(len, M_TMPFSNAME, M_WAITOK);
510                 tmpfs_dirent_init(nde, name, len);
511         } else
512                 nde->td_namelen = 0;
513         if (node != NULL)
514                 node->tn_links++;
515
516         *de = nde;
517
518         return 0;
519 }
520
521 /*
522  * Frees a directory entry.  It is the caller's responsibility to destroy
523  * the node referenced by it if needed.
524  *
525  * The link count of node is decreased by one to reflect the removal of an
526  * object that referenced it.  This only happens if 'node_exists' is true;
527  * otherwise the function will not access the node referred to by the
528  * directory entry, as it may already have been released from the outside.
529  */
530 void
531 tmpfs_free_dirent(struct tmpfs_mount *tmp, struct tmpfs_dirent *de)
532 {
533         struct tmpfs_node *node;
534
535         node = de->td_node;
536         if (node != NULL) {
537                 MPASS(node->tn_links > 0);
538                 node->tn_links--;
539         }
540         if (!tmpfs_dirent_duphead(de) && de->ud.td_name != NULL)
541                 free(de->ud.td_name, M_TMPFSNAME);
542         uma_zfree(tmpfs_dirent_pool, de);
543 }
544
545 void
546 tmpfs_destroy_vobject(struct vnode *vp, vm_object_t obj)
547 {
548
549         ASSERT_VOP_ELOCKED(vp, "tmpfs_destroy_vobject");
550         if (vp->v_type != VREG || obj == NULL)
551                 return;
552
553         VM_OBJECT_WLOCK(obj);
554         VI_LOCK(vp);
555         vm_object_clear_flag(obj, OBJ_TMPFS);
556         obj->un_pager.swp.swp_tmpfs = NULL;
557         if (vp->v_writecount < 0)
558                 vp->v_writecount = 0;
559         VI_UNLOCK(vp);
560         VM_OBJECT_WUNLOCK(obj);
561 }
562
563 /*
564  * Need to clear v_object for insmntque failure.
565  */
566 static void
567 tmpfs_insmntque_dtr(struct vnode *vp, void *dtr_arg)
568 {
569
570         tmpfs_destroy_vobject(vp, vp->v_object);
571         vp->v_object = NULL;
572         vp->v_data = NULL;
573         vp->v_op = &dead_vnodeops;
574         vgone(vp);
575         vput(vp);
576 }
577
578 /*
579  * Allocates a new vnode for the node node or returns a new reference to
580  * an existing one if the node had already a vnode referencing it.  The
581  * resulting locked vnode is returned in *vpp.
582  *
583  * Returns zero on success or an appropriate error code on failure.
584  */
585 int
586 tmpfs_alloc_vp(struct mount *mp, struct tmpfs_node *node, int lkflag,
587     struct vnode **vpp)
588 {
589         struct vnode *vp;
590         enum vgetstate vs;
591         struct tmpfs_mount *tm;
592         vm_object_t object;
593         int error;
594
595         error = 0;
596         tm = VFS_TO_TMPFS(mp);
597         TMPFS_NODE_LOCK(node);
598         tmpfs_ref_node(node);
599 loop:
600         TMPFS_NODE_ASSERT_LOCKED(node);
601         if ((vp = node->tn_vnode) != NULL) {
602                 MPASS((node->tn_vpstate & TMPFS_VNODE_DOOMED) == 0);
603                 if ((node->tn_type == VDIR && node->tn_dir.tn_parent == NULL) ||
604                     (VN_IS_DOOMED(vp) &&
605                      (lkflag & LK_NOWAIT) != 0)) {
606                         TMPFS_NODE_UNLOCK(node);
607                         error = ENOENT;
608                         vp = NULL;
609                         goto out;
610                 }
611                 if (VN_IS_DOOMED(vp)) {
612                         node->tn_vpstate |= TMPFS_VNODE_WRECLAIM;
613                         while ((node->tn_vpstate & TMPFS_VNODE_WRECLAIM) != 0) {
614                                 msleep(&node->tn_vnode, TMPFS_NODE_MTX(node),
615                                     0, "tmpfsE", 0);
616                         }
617                         goto loop;
618                 }
619                 vs = vget_prep(vp);
620                 TMPFS_NODE_UNLOCK(node);
621                 error = vget_finish(vp, lkflag, vs);
622                 if (error == ENOENT) {
623                         TMPFS_NODE_LOCK(node);
624                         goto loop;
625                 }
626                 if (error != 0) {
627                         vp = NULL;
628                         goto out;
629                 }
630
631                 /*
632                  * Make sure the vnode is still there after
633                  * getting the interlock to avoid racing a free.
634                  */
635                 if (node->tn_vnode == NULL || node->tn_vnode != vp) {
636                         vput(vp);
637                         TMPFS_NODE_LOCK(node);
638                         goto loop;
639                 }
640
641                 goto out;
642         }
643
644         if ((node->tn_vpstate & TMPFS_VNODE_DOOMED) ||
645             (node->tn_type == VDIR && node->tn_dir.tn_parent == NULL)) {
646                 TMPFS_NODE_UNLOCK(node);
647                 error = ENOENT;
648                 vp = NULL;
649                 goto out;
650         }
651
652         /*
653          * otherwise lock the vp list while we call getnewvnode
654          * since that can block.
655          */
656         if (node->tn_vpstate & TMPFS_VNODE_ALLOCATING) {
657                 node->tn_vpstate |= TMPFS_VNODE_WANT;
658                 error = msleep((caddr_t) &node->tn_vpstate,
659                     TMPFS_NODE_MTX(node), 0, "tmpfs_alloc_vp", 0);
660                 if (error != 0)
661                         goto out;
662                 goto loop;
663         } else
664                 node->tn_vpstate |= TMPFS_VNODE_ALLOCATING;
665
666         TMPFS_NODE_UNLOCK(node);
667
668         /* Get a new vnode and associate it with our node. */
669         error = getnewvnode("tmpfs", mp, VFS_TO_TMPFS(mp)->tm_nonc ?
670             &tmpfs_vnodeop_nonc_entries : &tmpfs_vnodeop_entries, &vp);
671         if (error != 0)
672                 goto unlock;
673         MPASS(vp != NULL);
674
675         /* lkflag is ignored, the lock is exclusive */
676         (void) vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
677
678         vp->v_data = node;
679         vp->v_type = node->tn_type;
680
681         /* Type-specific initialization. */
682         switch (node->tn_type) {
683         case VBLK:
684                 /* FALLTHROUGH */
685         case VCHR:
686                 /* FALLTHROUGH */
687         case VLNK:
688                 /* FALLTHROUGH */
689         case VSOCK:
690                 break;
691         case VFIFO:
692                 vp->v_op = &tmpfs_fifoop_entries;
693                 break;
694         case VREG:
695                 object = node->tn_reg.tn_aobj;
696                 VM_OBJECT_WLOCK(object);
697                 VI_LOCK(vp);
698                 KASSERT(vp->v_object == NULL, ("Not NULL v_object in tmpfs"));
699                 vp->v_object = object;
700                 object->un_pager.swp.swp_tmpfs = vp;
701                 vm_object_set_flag(object, OBJ_TMPFS);
702                 vp->v_irflag |= VIRF_PGREAD;
703                 VI_UNLOCK(vp);
704                 VM_OBJECT_WUNLOCK(object);
705                 break;
706         case VDIR:
707                 MPASS(node->tn_dir.tn_parent != NULL);
708                 if (node->tn_dir.tn_parent == node)
709                         vp->v_vflag |= VV_ROOT;
710                 break;
711
712         default:
713                 panic("tmpfs_alloc_vp: type %p %d", node, (int)node->tn_type);
714         }
715         if (vp->v_type != VFIFO)
716                 VN_LOCK_ASHARE(vp);
717
718         error = insmntque1(vp, mp, tmpfs_insmntque_dtr, NULL);
719         if (error != 0)
720                 vp = NULL;
721
722 unlock:
723         TMPFS_NODE_LOCK(node);
724
725         MPASS(node->tn_vpstate & TMPFS_VNODE_ALLOCATING);
726         node->tn_vpstate &= ~TMPFS_VNODE_ALLOCATING;
727         node->tn_vnode = vp;
728
729         if (node->tn_vpstate & TMPFS_VNODE_WANT) {
730                 node->tn_vpstate &= ~TMPFS_VNODE_WANT;
731                 TMPFS_NODE_UNLOCK(node);
732                 wakeup((caddr_t) &node->tn_vpstate);
733         } else
734                 TMPFS_NODE_UNLOCK(node);
735
736 out:
737         if (error == 0) {
738                 *vpp = vp;
739
740 #ifdef INVARIANTS
741                 MPASS(*vpp != NULL && VOP_ISLOCKED(*vpp));
742                 TMPFS_NODE_LOCK(node);
743                 MPASS(*vpp == node->tn_vnode);
744                 TMPFS_NODE_UNLOCK(node);
745 #endif
746         }
747         tmpfs_free_node(tm, node);
748
749         return (error);
750 }
751
752 /*
753  * Destroys the association between the vnode vp and the node it
754  * references.
755  */
756 void
757 tmpfs_free_vp(struct vnode *vp)
758 {
759         struct tmpfs_node *node;
760
761         node = VP_TO_TMPFS_NODE(vp);
762
763         TMPFS_NODE_ASSERT_LOCKED(node);
764         node->tn_vnode = NULL;
765         if ((node->tn_vpstate & TMPFS_VNODE_WRECLAIM) != 0)
766                 wakeup(&node->tn_vnode);
767         node->tn_vpstate &= ~TMPFS_VNODE_WRECLAIM;
768         vp->v_data = NULL;
769 }
770
771 /*
772  * Allocates a new file of type 'type' and adds it to the parent directory
773  * 'dvp'; this addition is done using the component name given in 'cnp'.
774  * The ownership of the new file is automatically assigned based on the
775  * credentials of the caller (through 'cnp'), the group is set based on
776  * the parent directory and the mode is determined from the 'vap' argument.
777  * If successful, *vpp holds a vnode to the newly created file and zero
778  * is returned.  Otherwise *vpp is NULL and the function returns an
779  * appropriate error code.
780  */
781 int
782 tmpfs_alloc_file(struct vnode *dvp, struct vnode **vpp, struct vattr *vap,
783     struct componentname *cnp, const char *target)
784 {
785         int error;
786         struct tmpfs_dirent *de;
787         struct tmpfs_mount *tmp;
788         struct tmpfs_node *dnode;
789         struct tmpfs_node *node;
790         struct tmpfs_node *parent;
791
792         ASSERT_VOP_ELOCKED(dvp, "tmpfs_alloc_file");
793         MPASS(cnp->cn_flags & HASBUF);
794
795         tmp = VFS_TO_TMPFS(dvp->v_mount);
796         dnode = VP_TO_TMPFS_DIR(dvp);
797         *vpp = NULL;
798
799         /* If the entry we are creating is a directory, we cannot overflow
800          * the number of links of its parent, because it will get a new
801          * link. */
802         if (vap->va_type == VDIR) {
803                 /* Ensure that we do not overflow the maximum number of links
804                  * imposed by the system. */
805                 MPASS(dnode->tn_links <= TMPFS_LINK_MAX);
806                 if (dnode->tn_links == TMPFS_LINK_MAX) {
807                         return (EMLINK);
808                 }
809
810                 parent = dnode;
811                 MPASS(parent != NULL);
812         } else
813                 parent = NULL;
814
815         /* Allocate a node that represents the new file. */
816         error = tmpfs_alloc_node(dvp->v_mount, tmp, vap->va_type,
817             cnp->cn_cred->cr_uid, dnode->tn_gid, vap->va_mode, parent,
818             target, vap->va_rdev, &node);
819         if (error != 0)
820                 return (error);
821
822         /* Allocate a directory entry that points to the new file. */
823         error = tmpfs_alloc_dirent(tmp, node, cnp->cn_nameptr, cnp->cn_namelen,
824             &de);
825         if (error != 0) {
826                 tmpfs_free_node(tmp, node);
827                 return (error);
828         }
829
830         /* Allocate a vnode for the new file. */
831         error = tmpfs_alloc_vp(dvp->v_mount, node, LK_EXCLUSIVE, vpp);
832         if (error != 0) {
833                 tmpfs_free_dirent(tmp, de);
834                 tmpfs_free_node(tmp, node);
835                 return (error);
836         }
837
838         /* Now that all required items are allocated, we can proceed to
839          * insert the new node into the directory, an operation that
840          * cannot fail. */
841         if (cnp->cn_flags & ISWHITEOUT)
842                 tmpfs_dir_whiteout_remove(dvp, cnp);
843         tmpfs_dir_attach(dvp, de);
844         return (0);
845 }
846
847 struct tmpfs_dirent *
848 tmpfs_dir_first(struct tmpfs_node *dnode, struct tmpfs_dir_cursor *dc)
849 {
850         struct tmpfs_dirent *de;
851
852         de = RB_MIN(tmpfs_dir, &dnode->tn_dir.tn_dirhead);
853         dc->tdc_tree = de;
854         if (de != NULL && tmpfs_dirent_duphead(de))
855                 de = LIST_FIRST(&de->ud.td_duphead);
856         dc->tdc_current = de;
857
858         return (dc->tdc_current);
859 }
860
861 struct tmpfs_dirent *
862 tmpfs_dir_next(struct tmpfs_node *dnode, struct tmpfs_dir_cursor *dc)
863 {
864         struct tmpfs_dirent *de;
865
866         MPASS(dc->tdc_tree != NULL);
867         if (tmpfs_dirent_dup(dc->tdc_current)) {
868                 dc->tdc_current = LIST_NEXT(dc->tdc_current, uh.td_dup.entries);
869                 if (dc->tdc_current != NULL)
870                         return (dc->tdc_current);
871         }
872         dc->tdc_tree = dc->tdc_current = RB_NEXT(tmpfs_dir,
873             &dnode->tn_dir.tn_dirhead, dc->tdc_tree);
874         if ((de = dc->tdc_current) != NULL && tmpfs_dirent_duphead(de)) {
875                 dc->tdc_current = LIST_FIRST(&de->ud.td_duphead);
876                 MPASS(dc->tdc_current != NULL);
877         }
878
879         return (dc->tdc_current);
880 }
881
882 /* Lookup directory entry in RB-Tree. Function may return duphead entry. */
883 static struct tmpfs_dirent *
884 tmpfs_dir_xlookup_hash(struct tmpfs_node *dnode, uint32_t hash)
885 {
886         struct tmpfs_dirent *de, dekey;
887
888         dekey.td_hash = hash;
889         de = RB_FIND(tmpfs_dir, &dnode->tn_dir.tn_dirhead, &dekey);
890         return (de);
891 }
892
893 /* Lookup directory entry by cookie, initialize directory cursor accordingly. */
894 static struct tmpfs_dirent *
895 tmpfs_dir_lookup_cookie(struct tmpfs_node *node, off_t cookie,
896     struct tmpfs_dir_cursor *dc)
897 {
898         struct tmpfs_dir *dirhead = &node->tn_dir.tn_dirhead;
899         struct tmpfs_dirent *de, dekey;
900
901         MPASS(cookie >= TMPFS_DIRCOOKIE_MIN);
902
903         if (cookie == node->tn_dir.tn_readdir_lastn &&
904             (de = node->tn_dir.tn_readdir_lastp) != NULL) {
905                 /* Protect against possible race, tn_readdir_last[pn]
906                  * may be updated with only shared vnode lock held. */
907                 if (cookie == tmpfs_dirent_cookie(de))
908                         goto out;
909         }
910
911         if ((cookie & TMPFS_DIRCOOKIE_DUP) != 0) {
912                 LIST_FOREACH(de, &node->tn_dir.tn_dupindex,
913                     uh.td_dup.index_entries) {
914                         MPASS(tmpfs_dirent_dup(de));
915                         if (de->td_cookie == cookie)
916                                 goto out;
917                         /* dupindex list is sorted. */
918                         if (de->td_cookie < cookie) {
919                                 de = NULL;
920                                 goto out;
921                         }
922                 }
923                 MPASS(de == NULL);
924                 goto out;
925         }
926
927         if ((cookie & TMPFS_DIRCOOKIE_MASK) != cookie) {
928                 de = NULL;
929         } else {
930                 dekey.td_hash = cookie;
931                 /* Recover if direntry for cookie was removed */
932                 de = RB_NFIND(tmpfs_dir, dirhead, &dekey);
933         }
934         dc->tdc_tree = de;
935         dc->tdc_current = de;
936         if (de != NULL && tmpfs_dirent_duphead(de)) {
937                 dc->tdc_current = LIST_FIRST(&de->ud.td_duphead);
938                 MPASS(dc->tdc_current != NULL);
939         }
940         return (dc->tdc_current);
941
942 out:
943         dc->tdc_tree = de;
944         dc->tdc_current = de;
945         if (de != NULL && tmpfs_dirent_dup(de))
946                 dc->tdc_tree = tmpfs_dir_xlookup_hash(node,
947                     de->td_hash);
948         return (dc->tdc_current);
949 }
950
951 /*
952  * Looks for a directory entry in the directory represented by node.
953  * 'cnp' describes the name of the entry to look for.  Note that the .
954  * and .. components are not allowed as they do not physically exist
955  * within directories.
956  *
957  * Returns a pointer to the entry when found, otherwise NULL.
958  */
959 struct tmpfs_dirent *
960 tmpfs_dir_lookup(struct tmpfs_node *node, struct tmpfs_node *f,
961     struct componentname *cnp)
962 {
963         struct tmpfs_dir_duphead *duphead;
964         struct tmpfs_dirent *de;
965         uint32_t hash;
966
967         MPASS(IMPLIES(cnp->cn_namelen == 1, cnp->cn_nameptr[0] != '.'));
968         MPASS(IMPLIES(cnp->cn_namelen == 2, !(cnp->cn_nameptr[0] == '.' &&
969             cnp->cn_nameptr[1] == '.')));
970         TMPFS_VALIDATE_DIR(node);
971
972         hash = tmpfs_dirent_hash(cnp->cn_nameptr, cnp->cn_namelen);
973         de = tmpfs_dir_xlookup_hash(node, hash);
974         if (de != NULL && tmpfs_dirent_duphead(de)) {
975                 duphead = &de->ud.td_duphead;
976                 LIST_FOREACH(de, duphead, uh.td_dup.entries) {
977                         if (TMPFS_DIRENT_MATCHES(de, cnp->cn_nameptr,
978                             cnp->cn_namelen))
979                                 break;
980                 }
981         } else if (de != NULL) {
982                 if (!TMPFS_DIRENT_MATCHES(de, cnp->cn_nameptr,
983                     cnp->cn_namelen))
984                         de = NULL;
985         }
986         if (de != NULL && f != NULL && de->td_node != f)
987                 de = NULL;
988
989         return (de);
990 }
991
992 /*
993  * Attach duplicate-cookie directory entry nde to dnode and insert to dupindex
994  * list, allocate new cookie value.
995  */
996 static void
997 tmpfs_dir_attach_dup(struct tmpfs_node *dnode,
998     struct tmpfs_dir_duphead *duphead, struct tmpfs_dirent *nde)
999 {
1000         struct tmpfs_dir_duphead *dupindex;
1001         struct tmpfs_dirent *de, *pde;
1002
1003         dupindex = &dnode->tn_dir.tn_dupindex;
1004         de = LIST_FIRST(dupindex);
1005         if (de == NULL || de->td_cookie < TMPFS_DIRCOOKIE_DUP_MAX) {
1006                 if (de == NULL)
1007                         nde->td_cookie = TMPFS_DIRCOOKIE_DUP_MIN;
1008                 else
1009                         nde->td_cookie = de->td_cookie + 1;
1010                 MPASS(tmpfs_dirent_dup(nde));
1011                 LIST_INSERT_HEAD(dupindex, nde, uh.td_dup.index_entries);
1012                 LIST_INSERT_HEAD(duphead, nde, uh.td_dup.entries);
1013                 return;
1014         }
1015
1016         /*
1017          * Cookie numbers are near exhaustion. Scan dupindex list for unused
1018          * numbers. dupindex list is sorted in descending order. Keep it so
1019          * after inserting nde.
1020          */
1021         while (1) {
1022                 pde = de;
1023                 de = LIST_NEXT(de, uh.td_dup.index_entries);
1024                 if (de == NULL && pde->td_cookie != TMPFS_DIRCOOKIE_DUP_MIN) {
1025                         /*
1026                          * Last element of the index doesn't have minimal cookie
1027                          * value, use it.
1028                          */
1029                         nde->td_cookie = TMPFS_DIRCOOKIE_DUP_MIN;
1030                         LIST_INSERT_AFTER(pde, nde, uh.td_dup.index_entries);
1031                         LIST_INSERT_HEAD(duphead, nde, uh.td_dup.entries);
1032                         return;
1033                 } else if (de == NULL) {
1034                         /*
1035                          * We are so lucky have 2^30 hash duplicates in single
1036                          * directory :) Return largest possible cookie value.
1037                          * It should be fine except possible issues with
1038                          * VOP_READDIR restart.
1039                          */
1040                         nde->td_cookie = TMPFS_DIRCOOKIE_DUP_MAX;
1041                         LIST_INSERT_HEAD(dupindex, nde,
1042                             uh.td_dup.index_entries);
1043                         LIST_INSERT_HEAD(duphead, nde, uh.td_dup.entries);
1044                         return;
1045                 }
1046                 if (de->td_cookie + 1 == pde->td_cookie ||
1047                     de->td_cookie >= TMPFS_DIRCOOKIE_DUP_MAX)
1048                         continue;       /* No hole or invalid cookie. */
1049                 nde->td_cookie = de->td_cookie + 1;
1050                 MPASS(tmpfs_dirent_dup(nde));
1051                 MPASS(pde->td_cookie > nde->td_cookie);
1052                 MPASS(nde->td_cookie > de->td_cookie);
1053                 LIST_INSERT_BEFORE(de, nde, uh.td_dup.index_entries);
1054                 LIST_INSERT_HEAD(duphead, nde, uh.td_dup.entries);
1055                 return;
1056         }
1057 }
1058
1059 /*
1060  * Attaches the directory entry de to the directory represented by vp.
1061  * Note that this does not change the link count of the node pointed by
1062  * the directory entry, as this is done by tmpfs_alloc_dirent.
1063  */
1064 void
1065 tmpfs_dir_attach(struct vnode *vp, struct tmpfs_dirent *de)
1066 {
1067         struct tmpfs_node *dnode;
1068         struct tmpfs_dirent *xde, *nde;
1069
1070         ASSERT_VOP_ELOCKED(vp, __func__);
1071         MPASS(de->td_namelen > 0);
1072         MPASS(de->td_hash >= TMPFS_DIRCOOKIE_MIN);
1073         MPASS(de->td_cookie == de->td_hash);
1074
1075         dnode = VP_TO_TMPFS_DIR(vp);
1076         dnode->tn_dir.tn_readdir_lastn = 0;
1077         dnode->tn_dir.tn_readdir_lastp = NULL;
1078
1079         MPASS(!tmpfs_dirent_dup(de));
1080         xde = RB_INSERT(tmpfs_dir, &dnode->tn_dir.tn_dirhead, de);
1081         if (xde != NULL && tmpfs_dirent_duphead(xde))
1082                 tmpfs_dir_attach_dup(dnode, &xde->ud.td_duphead, de);
1083         else if (xde != NULL) {
1084                 /*
1085                  * Allocate new duphead. Swap xde with duphead to avoid
1086                  * adding/removing elements with the same hash.
1087                  */
1088                 MPASS(!tmpfs_dirent_dup(xde));
1089                 tmpfs_alloc_dirent(VFS_TO_TMPFS(vp->v_mount), NULL, NULL, 0,
1090                     &nde);
1091                 /* *nde = *xde; XXX gcc 4.2.1 may generate invalid code. */
1092                 memcpy(nde, xde, sizeof(*xde));
1093                 xde->td_cookie |= TMPFS_DIRCOOKIE_DUPHEAD;
1094                 LIST_INIT(&xde->ud.td_duphead);
1095                 xde->td_namelen = 0;
1096                 xde->td_node = NULL;
1097                 tmpfs_dir_attach_dup(dnode, &xde->ud.td_duphead, nde);
1098                 tmpfs_dir_attach_dup(dnode, &xde->ud.td_duphead, de);
1099         }
1100         dnode->tn_size += sizeof(struct tmpfs_dirent);
1101         dnode->tn_status |= TMPFS_NODE_ACCESSED | TMPFS_NODE_CHANGED | \
1102             TMPFS_NODE_MODIFIED;
1103         tmpfs_update(vp);
1104 }
1105
1106 /*
1107  * Detaches the directory entry de from the directory represented by vp.
1108  * Note that this does not change the link count of the node pointed by
1109  * the directory entry, as this is done by tmpfs_free_dirent.
1110  */
1111 void
1112 tmpfs_dir_detach(struct vnode *vp, struct tmpfs_dirent *de)
1113 {
1114         struct tmpfs_mount *tmp;
1115         struct tmpfs_dir *head;
1116         struct tmpfs_node *dnode;
1117         struct tmpfs_dirent *xde;
1118
1119         ASSERT_VOP_ELOCKED(vp, __func__);
1120
1121         dnode = VP_TO_TMPFS_DIR(vp);
1122         head = &dnode->tn_dir.tn_dirhead;
1123         dnode->tn_dir.tn_readdir_lastn = 0;
1124         dnode->tn_dir.tn_readdir_lastp = NULL;
1125
1126         if (tmpfs_dirent_dup(de)) {
1127                 /* Remove duphead if de was last entry. */
1128                 if (LIST_NEXT(de, uh.td_dup.entries) == NULL) {
1129                         xde = tmpfs_dir_xlookup_hash(dnode, de->td_hash);
1130                         MPASS(tmpfs_dirent_duphead(xde));
1131                 } else
1132                         xde = NULL;
1133                 LIST_REMOVE(de, uh.td_dup.entries);
1134                 LIST_REMOVE(de, uh.td_dup.index_entries);
1135                 if (xde != NULL) {
1136                         if (LIST_EMPTY(&xde->ud.td_duphead)) {
1137                                 RB_REMOVE(tmpfs_dir, head, xde);
1138                                 tmp = VFS_TO_TMPFS(vp->v_mount);
1139                                 MPASS(xde->td_node == NULL);
1140                                 tmpfs_free_dirent(tmp, xde);
1141                         }
1142                 }
1143                 de->td_cookie = de->td_hash;
1144         } else
1145                 RB_REMOVE(tmpfs_dir, head, de);
1146
1147         dnode->tn_size -= sizeof(struct tmpfs_dirent);
1148         dnode->tn_status |= TMPFS_NODE_ACCESSED | TMPFS_NODE_CHANGED | \
1149             TMPFS_NODE_MODIFIED;
1150         tmpfs_update(vp);
1151 }
1152
1153 void
1154 tmpfs_dir_destroy(struct tmpfs_mount *tmp, struct tmpfs_node *dnode)
1155 {
1156         struct tmpfs_dirent *de, *dde, *nde;
1157
1158         RB_FOREACH_SAFE(de, tmpfs_dir, &dnode->tn_dir.tn_dirhead, nde) {
1159                 RB_REMOVE(tmpfs_dir, &dnode->tn_dir.tn_dirhead, de);
1160                 /* Node may already be destroyed. */
1161                 de->td_node = NULL;
1162                 if (tmpfs_dirent_duphead(de)) {
1163                         while ((dde = LIST_FIRST(&de->ud.td_duphead)) != NULL) {
1164                                 LIST_REMOVE(dde, uh.td_dup.entries);
1165                                 dde->td_node = NULL;
1166                                 tmpfs_free_dirent(tmp, dde);
1167                         }
1168                 }
1169                 tmpfs_free_dirent(tmp, de);
1170         }
1171 }
1172
1173 /*
1174  * Helper function for tmpfs_readdir.  Creates a '.' entry for the given
1175  * directory and returns it in the uio space.  The function returns 0
1176  * on success, -1 if there was not enough space in the uio structure to
1177  * hold the directory entry or an appropriate error code if another
1178  * error happens.
1179  */
1180 static int
1181 tmpfs_dir_getdotdent(struct tmpfs_mount *tm, struct tmpfs_node *node,
1182     struct uio *uio)
1183 {
1184         int error;
1185         struct dirent dent;
1186
1187         TMPFS_VALIDATE_DIR(node);
1188         MPASS(uio->uio_offset == TMPFS_DIRCOOKIE_DOT);
1189
1190         dent.d_fileno = node->tn_id;
1191         dent.d_type = DT_DIR;
1192         dent.d_namlen = 1;
1193         dent.d_name[0] = '.';
1194         dent.d_reclen = GENERIC_DIRSIZ(&dent);
1195         dirent_terminate(&dent);
1196
1197         if (dent.d_reclen > uio->uio_resid)
1198                 error = EJUSTRETURN;
1199         else
1200                 error = uiomove(&dent, dent.d_reclen, uio);
1201
1202         tmpfs_set_status(tm, node, TMPFS_NODE_ACCESSED);
1203
1204         return (error);
1205 }
1206
1207 /*
1208  * Helper function for tmpfs_readdir.  Creates a '..' entry for the given
1209  * directory and returns it in the uio space.  The function returns 0
1210  * on success, -1 if there was not enough space in the uio structure to
1211  * hold the directory entry or an appropriate error code if another
1212  * error happens.
1213  */
1214 static int
1215 tmpfs_dir_getdotdotdent(struct tmpfs_mount *tm, struct tmpfs_node *node,
1216     struct uio *uio)
1217 {
1218         struct tmpfs_node *parent;
1219         struct dirent dent;
1220         int error;
1221
1222         TMPFS_VALIDATE_DIR(node);
1223         MPASS(uio->uio_offset == TMPFS_DIRCOOKIE_DOTDOT);
1224
1225         /*
1226          * Return ENOENT if the current node is already removed.
1227          */
1228         TMPFS_ASSERT_LOCKED(node);
1229         parent = node->tn_dir.tn_parent;
1230         if (parent == NULL)
1231                 return (ENOENT);
1232
1233         TMPFS_NODE_LOCK(parent);
1234         dent.d_fileno = parent->tn_id;
1235         TMPFS_NODE_UNLOCK(parent);
1236
1237         dent.d_type = DT_DIR;
1238         dent.d_namlen = 2;
1239         dent.d_name[0] = '.';
1240         dent.d_name[1] = '.';
1241         dent.d_reclen = GENERIC_DIRSIZ(&dent);
1242         dirent_terminate(&dent);
1243
1244         if (dent.d_reclen > uio->uio_resid)
1245                 error = EJUSTRETURN;
1246         else
1247                 error = uiomove(&dent, dent.d_reclen, uio);
1248
1249         tmpfs_set_status(tm, node, TMPFS_NODE_ACCESSED);
1250
1251         return (error);
1252 }
1253
1254 /*
1255  * Helper function for tmpfs_readdir.  Returns as much directory entries
1256  * as can fit in the uio space.  The read starts at uio->uio_offset.
1257  * The function returns 0 on success, -1 if there was not enough space
1258  * in the uio structure to hold the directory entry or an appropriate
1259  * error code if another error happens.
1260  */
1261 int
1262 tmpfs_dir_getdents(struct tmpfs_mount *tm, struct tmpfs_node *node,
1263     struct uio *uio, int maxcookies, u_long *cookies, int *ncookies)
1264 {
1265         struct tmpfs_dir_cursor dc;
1266         struct tmpfs_dirent *de;
1267         off_t off;
1268         int error;
1269
1270         TMPFS_VALIDATE_DIR(node);
1271
1272         off = 0;
1273
1274         /*
1275          * Lookup the node from the current offset.  The starting offset of
1276          * 0 will lookup both '.' and '..', and then the first real entry,
1277          * or EOF if there are none.  Then find all entries for the dir that
1278          * fit into the buffer.  Once no more entries are found (de == NULL),
1279          * the offset is set to TMPFS_DIRCOOKIE_EOF, which will cause the next
1280          * call to return 0.
1281          */
1282         switch (uio->uio_offset) {
1283         case TMPFS_DIRCOOKIE_DOT:
1284                 error = tmpfs_dir_getdotdent(tm, node, uio);
1285                 if (error != 0)
1286                         return (error);
1287                 uio->uio_offset = TMPFS_DIRCOOKIE_DOTDOT;
1288                 if (cookies != NULL)
1289                         cookies[(*ncookies)++] = off = uio->uio_offset;
1290                 /* FALLTHROUGH */
1291         case TMPFS_DIRCOOKIE_DOTDOT:
1292                 error = tmpfs_dir_getdotdotdent(tm, node, uio);
1293                 if (error != 0)
1294                         return (error);
1295                 de = tmpfs_dir_first(node, &dc);
1296                 uio->uio_offset = tmpfs_dirent_cookie(de);
1297                 if (cookies != NULL)
1298                         cookies[(*ncookies)++] = off = uio->uio_offset;
1299                 /* EOF. */
1300                 if (de == NULL)
1301                         return (0);
1302                 break;
1303         case TMPFS_DIRCOOKIE_EOF:
1304                 return (0);
1305         default:
1306                 de = tmpfs_dir_lookup_cookie(node, uio->uio_offset, &dc);
1307                 if (de == NULL)
1308                         return (EINVAL);
1309                 if (cookies != NULL)
1310                         off = tmpfs_dirent_cookie(de);
1311         }
1312
1313         /* Read as much entries as possible; i.e., until we reach the end of
1314          * the directory or we exhaust uio space. */
1315         do {
1316                 struct dirent d;
1317
1318                 /* Create a dirent structure representing the current
1319                  * tmpfs_node and fill it. */
1320                 if (de->td_node == NULL) {
1321                         d.d_fileno = 1;
1322                         d.d_type = DT_WHT;
1323                 } else {
1324                         d.d_fileno = de->td_node->tn_id;
1325                         switch (de->td_node->tn_type) {
1326                         case VBLK:
1327                                 d.d_type = DT_BLK;
1328                                 break;
1329
1330                         case VCHR:
1331                                 d.d_type = DT_CHR;
1332                                 break;
1333
1334                         case VDIR:
1335                                 d.d_type = DT_DIR;
1336                                 break;
1337
1338                         case VFIFO:
1339                                 d.d_type = DT_FIFO;
1340                                 break;
1341
1342                         case VLNK:
1343                                 d.d_type = DT_LNK;
1344                                 break;
1345
1346                         case VREG:
1347                                 d.d_type = DT_REG;
1348                                 break;
1349
1350                         case VSOCK:
1351                                 d.d_type = DT_SOCK;
1352                                 break;
1353
1354                         default:
1355                                 panic("tmpfs_dir_getdents: type %p %d",
1356                                     de->td_node, (int)de->td_node->tn_type);
1357                         }
1358                 }
1359                 d.d_namlen = de->td_namelen;
1360                 MPASS(de->td_namelen < sizeof(d.d_name));
1361                 (void)memcpy(d.d_name, de->ud.td_name, de->td_namelen);
1362                 d.d_reclen = GENERIC_DIRSIZ(&d);
1363                 dirent_terminate(&d);
1364
1365                 /* Stop reading if the directory entry we are treating is
1366                  * bigger than the amount of data that can be returned. */
1367                 if (d.d_reclen > uio->uio_resid) {
1368                         error = EJUSTRETURN;
1369                         break;
1370                 }
1371
1372                 /* Copy the new dirent structure into the output buffer and
1373                  * advance pointers. */
1374                 error = uiomove(&d, d.d_reclen, uio);
1375                 if (error == 0) {
1376                         de = tmpfs_dir_next(node, &dc);
1377                         if (cookies != NULL) {
1378                                 off = tmpfs_dirent_cookie(de);
1379                                 MPASS(*ncookies < maxcookies);
1380                                 cookies[(*ncookies)++] = off;
1381                         }
1382                 }
1383         } while (error == 0 && uio->uio_resid > 0 && de != NULL);
1384
1385         /* Skip setting off when using cookies as it is already done above. */
1386         if (cookies == NULL)
1387                 off = tmpfs_dirent_cookie(de);
1388
1389         /* Update the offset and cache. */
1390         uio->uio_offset = off;
1391         node->tn_dir.tn_readdir_lastn = off;
1392         node->tn_dir.tn_readdir_lastp = de;
1393
1394         tmpfs_set_status(tm, node, TMPFS_NODE_ACCESSED);
1395         return error;
1396 }
1397
1398 int
1399 tmpfs_dir_whiteout_add(struct vnode *dvp, struct componentname *cnp)
1400 {
1401         struct tmpfs_dirent *de;
1402         int error;
1403
1404         error = tmpfs_alloc_dirent(VFS_TO_TMPFS(dvp->v_mount), NULL,
1405             cnp->cn_nameptr, cnp->cn_namelen, &de);
1406         if (error != 0)
1407                 return (error);
1408         tmpfs_dir_attach(dvp, de);
1409         return (0);
1410 }
1411
1412 void
1413 tmpfs_dir_whiteout_remove(struct vnode *dvp, struct componentname *cnp)
1414 {
1415         struct tmpfs_dirent *de;
1416
1417         de = tmpfs_dir_lookup(VP_TO_TMPFS_DIR(dvp), NULL, cnp);
1418         MPASS(de != NULL && de->td_node == NULL);
1419         tmpfs_dir_detach(dvp, de);
1420         tmpfs_free_dirent(VFS_TO_TMPFS(dvp->v_mount), de);
1421 }
1422
1423 /*
1424  * Resizes the aobj associated with the regular file pointed to by 'vp' to the
1425  * size 'newsize'.  'vp' must point to a vnode that represents a regular file.
1426  * 'newsize' must be positive.
1427  *
1428  * Returns zero on success or an appropriate error code on failure.
1429  */
1430 int
1431 tmpfs_reg_resize(struct vnode *vp, off_t newsize, boolean_t ignerr)
1432 {
1433         struct tmpfs_mount *tmp;
1434         struct tmpfs_node *node;
1435         vm_object_t uobj;
1436         vm_page_t m;
1437         vm_pindex_t idx, newpages, oldpages;
1438         off_t oldsize;
1439         int base, rv;
1440
1441         MPASS(vp->v_type == VREG);
1442         MPASS(newsize >= 0);
1443
1444         node = VP_TO_TMPFS_NODE(vp);
1445         uobj = node->tn_reg.tn_aobj;
1446         tmp = VFS_TO_TMPFS(vp->v_mount);
1447
1448         /*
1449          * Convert the old and new sizes to the number of pages needed to
1450          * store them.  It may happen that we do not need to do anything
1451          * because the last allocated page can accommodate the change on
1452          * its own.
1453          */
1454         oldsize = node->tn_size;
1455         oldpages = OFF_TO_IDX(oldsize + PAGE_MASK);
1456         MPASS(oldpages == uobj->size);
1457         newpages = OFF_TO_IDX(newsize + PAGE_MASK);
1458
1459         if (__predict_true(newpages == oldpages && newsize >= oldsize)) {
1460                 node->tn_size = newsize;
1461                 return (0);
1462         }
1463
1464         if (newpages > oldpages &&
1465             tmpfs_pages_check_avail(tmp, newpages - oldpages) == 0)
1466                 return (ENOSPC);
1467
1468         VM_OBJECT_WLOCK(uobj);
1469         if (newsize < oldsize) {
1470                 /*
1471                  * Zero the truncated part of the last page.
1472                  */
1473                 base = newsize & PAGE_MASK;
1474                 if (base != 0) {
1475                         idx = OFF_TO_IDX(newsize);
1476 retry:
1477                         m = vm_page_grab(uobj, idx, VM_ALLOC_NOCREAT);
1478                         if (m != NULL) {
1479                                 MPASS(vm_page_all_valid(m));
1480                         } else if (vm_pager_has_page(uobj, idx, NULL, NULL)) {
1481                                 m = vm_page_alloc(uobj, idx, VM_ALLOC_NORMAL |
1482                                     VM_ALLOC_WAITFAIL);
1483                                 if (m == NULL)
1484                                         goto retry;
1485                                 vm_object_pip_add(uobj, 1);
1486                                 VM_OBJECT_WUNLOCK(uobj);
1487                                 rv = vm_pager_get_pages(uobj, &m, 1, NULL,
1488                                     NULL);
1489                                 VM_OBJECT_WLOCK(uobj);
1490                                 vm_object_pip_wakeup(uobj);
1491                                 if (rv == VM_PAGER_OK) {
1492                                         /*
1493                                          * Since the page was not resident,
1494                                          * and therefore not recently
1495                                          * accessed, immediately enqueue it
1496                                          * for asynchronous laundering.  The
1497                                          * current operation is not regarded
1498                                          * as an access.
1499                                          */
1500                                         vm_page_launder(m);
1501                                 } else {
1502                                         vm_page_free(m);
1503                                         if (ignerr)
1504                                                 m = NULL;
1505                                         else {
1506                                                 VM_OBJECT_WUNLOCK(uobj);
1507                                                 return (EIO);
1508                                         }
1509                                 }
1510                         }
1511                         if (m != NULL) {
1512                                 pmap_zero_page_area(m, base, PAGE_SIZE - base);
1513                                 vm_page_set_dirty(m);
1514                                 vm_page_xunbusy(m);
1515                         }
1516                 }
1517
1518                 /*
1519                  * Release any swap space and free any whole pages.
1520                  */
1521                 if (newpages < oldpages)
1522                         vm_object_page_remove(uobj, newpages, 0, 0);
1523         }
1524         uobj->size = newpages;
1525         VM_OBJECT_WUNLOCK(uobj);
1526
1527         atomic_add_long(&tmp->tm_pages_used, newpages - oldpages);
1528
1529         node->tn_size = newsize;
1530         return (0);
1531 }
1532
1533 void
1534 tmpfs_check_mtime(struct vnode *vp)
1535 {
1536         struct tmpfs_node *node;
1537         struct vm_object *obj;
1538
1539         ASSERT_VOP_ELOCKED(vp, "check_mtime");
1540         if (vp->v_type != VREG)
1541                 return;
1542         obj = vp->v_object;
1543         KASSERT((obj->flags & (OBJ_TMPFS_NODE | OBJ_TMPFS)) ==
1544             (OBJ_TMPFS_NODE | OBJ_TMPFS), ("non-tmpfs obj"));
1545         /* unlocked read */
1546         if (obj->generation != obj->cleangeneration) {
1547                 VM_OBJECT_WLOCK(obj);
1548                 if (obj->generation != obj->cleangeneration) {
1549                         obj->cleangeneration = obj->generation;
1550                         node = VP_TO_TMPFS_NODE(vp);
1551                         node->tn_status |= TMPFS_NODE_MODIFIED |
1552                             TMPFS_NODE_CHANGED;
1553                 }
1554                 VM_OBJECT_WUNLOCK(obj);
1555         }
1556 }
1557
1558 /*
1559  * Change flags of the given vnode.
1560  * Caller should execute tmpfs_update on vp after a successful execution.
1561  * The vnode must be locked on entry and remain locked on exit.
1562  */
1563 int
1564 tmpfs_chflags(struct vnode *vp, u_long flags, struct ucred *cred,
1565     struct thread *p)
1566 {
1567         int error;
1568         struct tmpfs_node *node;
1569
1570         ASSERT_VOP_ELOCKED(vp, "chflags");
1571
1572         node = VP_TO_TMPFS_NODE(vp);
1573
1574         if ((flags & ~(SF_APPEND | SF_ARCHIVED | SF_IMMUTABLE | SF_NOUNLINK |
1575             UF_APPEND | UF_ARCHIVE | UF_HIDDEN | UF_IMMUTABLE | UF_NODUMP |
1576             UF_NOUNLINK | UF_OFFLINE | UF_OPAQUE | UF_READONLY | UF_REPARSE |
1577             UF_SPARSE | UF_SYSTEM)) != 0)
1578                 return (EOPNOTSUPP);
1579
1580         /* Disallow this operation if the file system is mounted read-only. */
1581         if (vp->v_mount->mnt_flag & MNT_RDONLY)
1582                 return EROFS;
1583
1584         /*
1585          * Callers may only modify the file flags on objects they
1586          * have VADMIN rights for.
1587          */
1588         if ((error = VOP_ACCESS(vp, VADMIN, cred, p)))
1589                 return (error);
1590         /*
1591          * Unprivileged processes are not permitted to unset system
1592          * flags, or modify flags if any system flags are set.
1593          */
1594         if (!priv_check_cred(cred, PRIV_VFS_SYSFLAGS)) {
1595                 if (node->tn_flags &
1596                     (SF_NOUNLINK | SF_IMMUTABLE | SF_APPEND)) {
1597                         error = securelevel_gt(cred, 0);
1598                         if (error)
1599                                 return (error);
1600                 }
1601         } else {
1602                 if (node->tn_flags &
1603                     (SF_NOUNLINK | SF_IMMUTABLE | SF_APPEND) ||
1604                     ((flags ^ node->tn_flags) & SF_SETTABLE))
1605                         return (EPERM);
1606         }
1607         node->tn_flags = flags;
1608         node->tn_status |= TMPFS_NODE_CHANGED;
1609
1610         ASSERT_VOP_ELOCKED(vp, "chflags2");
1611
1612         return (0);
1613 }
1614
1615 /*
1616  * Change access mode on the given vnode.
1617  * Caller should execute tmpfs_update on vp after a successful execution.
1618  * The vnode must be locked on entry and remain locked on exit.
1619  */
1620 int
1621 tmpfs_chmod(struct vnode *vp, mode_t mode, struct ucred *cred, struct thread *p)
1622 {
1623         int error;
1624         struct tmpfs_node *node;
1625         mode_t newmode;
1626
1627         ASSERT_VOP_ELOCKED(vp, "chmod");
1628         ASSERT_VOP_IN_SEQC(vp);
1629
1630         node = VP_TO_TMPFS_NODE(vp);
1631
1632         /* Disallow this operation if the file system is mounted read-only. */
1633         if (vp->v_mount->mnt_flag & MNT_RDONLY)
1634                 return EROFS;
1635
1636         /* Immutable or append-only files cannot be modified, either. */
1637         if (node->tn_flags & (IMMUTABLE | APPEND))
1638                 return EPERM;
1639
1640         /*
1641          * To modify the permissions on a file, must possess VADMIN
1642          * for that file.
1643          */
1644         if ((error = VOP_ACCESS(vp, VADMIN, cred, p)))
1645                 return (error);
1646
1647         /*
1648          * Privileged processes may set the sticky bit on non-directories,
1649          * as well as set the setgid bit on a file with a group that the
1650          * process is not a member of.
1651          */
1652         if (vp->v_type != VDIR && (mode & S_ISTXT)) {
1653                 if (priv_check_cred(cred, PRIV_VFS_STICKYFILE))
1654                         return (EFTYPE);
1655         }
1656         if (!groupmember(node->tn_gid, cred) && (mode & S_ISGID)) {
1657                 error = priv_check_cred(cred, PRIV_VFS_SETGID);
1658                 if (error)
1659                         return (error);
1660         }
1661
1662         newmode = node->tn_mode & ~ALLPERMS;
1663         newmode |= mode & ALLPERMS;
1664         atomic_store_short(&node->tn_mode, newmode);
1665
1666         node->tn_status |= TMPFS_NODE_CHANGED;
1667
1668         ASSERT_VOP_ELOCKED(vp, "chmod2");
1669
1670         return (0);
1671 }
1672
1673 /*
1674  * Change ownership of the given vnode.  At least one of uid or gid must
1675  * be different than VNOVAL.  If one is set to that value, the attribute
1676  * is unchanged.
1677  * Caller should execute tmpfs_update on vp after a successful execution.
1678  * The vnode must be locked on entry and remain locked on exit.
1679  */
1680 int
1681 tmpfs_chown(struct vnode *vp, uid_t uid, gid_t gid, struct ucred *cred,
1682     struct thread *p)
1683 {
1684         int error;
1685         struct tmpfs_node *node;
1686         uid_t ouid;
1687         gid_t ogid;
1688         mode_t newmode;
1689
1690         ASSERT_VOP_ELOCKED(vp, "chown");
1691         ASSERT_VOP_IN_SEQC(vp);
1692
1693         node = VP_TO_TMPFS_NODE(vp);
1694
1695         /* Assign default values if they are unknown. */
1696         MPASS(uid != VNOVAL || gid != VNOVAL);
1697         if (uid == VNOVAL)
1698                 uid = node->tn_uid;
1699         if (gid == VNOVAL)
1700                 gid = node->tn_gid;
1701         MPASS(uid != VNOVAL && gid != VNOVAL);
1702
1703         /* Disallow this operation if the file system is mounted read-only. */
1704         if (vp->v_mount->mnt_flag & MNT_RDONLY)
1705                 return EROFS;
1706
1707         /* Immutable or append-only files cannot be modified, either. */
1708         if (node->tn_flags & (IMMUTABLE | APPEND))
1709                 return EPERM;
1710
1711         /*
1712          * To modify the ownership of a file, must possess VADMIN for that
1713          * file.
1714          */
1715         if ((error = VOP_ACCESS(vp, VADMIN, cred, p)))
1716                 return (error);
1717
1718         /*
1719          * To change the owner of a file, or change the group of a file to a
1720          * group of which we are not a member, the caller must have
1721          * privilege.
1722          */
1723         if ((uid != node->tn_uid ||
1724             (gid != node->tn_gid && !groupmember(gid, cred))) &&
1725             (error = priv_check_cred(cred, PRIV_VFS_CHOWN)))
1726                 return (error);
1727
1728         ogid = node->tn_gid;
1729         ouid = node->tn_uid;
1730
1731         node->tn_uid = uid;
1732         node->tn_gid = gid;
1733
1734         node->tn_status |= TMPFS_NODE_CHANGED;
1735
1736         if ((node->tn_mode & (S_ISUID | S_ISGID)) && (ouid != uid || ogid != gid)) {
1737                 if (priv_check_cred(cred, PRIV_VFS_RETAINSUGID)) {
1738                         newmode = node->tn_mode & ~(S_ISUID | S_ISGID);
1739                         atomic_store_short(&node->tn_mode, newmode);
1740                 }
1741         }
1742
1743         ASSERT_VOP_ELOCKED(vp, "chown2");
1744
1745         return (0);
1746 }
1747
1748 /*
1749  * Change size of the given vnode.
1750  * Caller should execute tmpfs_update on vp after a successful execution.
1751  * The vnode must be locked on entry and remain locked on exit.
1752  */
1753 int
1754 tmpfs_chsize(struct vnode *vp, u_quad_t size, struct ucred *cred,
1755     struct thread *p)
1756 {
1757         int error;
1758         struct tmpfs_node *node;
1759
1760         ASSERT_VOP_ELOCKED(vp, "chsize");
1761
1762         node = VP_TO_TMPFS_NODE(vp);
1763
1764         /* Decide whether this is a valid operation based on the file type. */
1765         error = 0;
1766         switch (vp->v_type) {
1767         case VDIR:
1768                 return EISDIR;
1769
1770         case VREG:
1771                 if (vp->v_mount->mnt_flag & MNT_RDONLY)
1772                         return EROFS;
1773                 break;
1774
1775         case VBLK:
1776                 /* FALLTHROUGH */
1777         case VCHR:
1778                 /* FALLTHROUGH */
1779         case VFIFO:
1780                 /* Allow modifications of special files even if in the file
1781                  * system is mounted read-only (we are not modifying the
1782                  * files themselves, but the objects they represent). */
1783                 return 0;
1784
1785         default:
1786                 /* Anything else is unsupported. */
1787                 return EOPNOTSUPP;
1788         }
1789
1790         /* Immutable or append-only files cannot be modified, either. */
1791         if (node->tn_flags & (IMMUTABLE | APPEND))
1792                 return EPERM;
1793
1794         error = tmpfs_truncate(vp, size);
1795         /* tmpfs_truncate will raise the NOTE_EXTEND and NOTE_ATTRIB kevents
1796          * for us, as will update tn_status; no need to do that here. */
1797
1798         ASSERT_VOP_ELOCKED(vp, "chsize2");
1799
1800         return (error);
1801 }
1802
1803 /*
1804  * Change access and modification times of the given vnode.
1805  * Caller should execute tmpfs_update on vp after a successful execution.
1806  * The vnode must be locked on entry and remain locked on exit.
1807  */
1808 int
1809 tmpfs_chtimes(struct vnode *vp, struct vattr *vap,
1810     struct ucred *cred, struct thread *l)
1811 {
1812         int error;
1813         struct tmpfs_node *node;
1814
1815         ASSERT_VOP_ELOCKED(vp, "chtimes");
1816
1817         node = VP_TO_TMPFS_NODE(vp);
1818
1819         /* Disallow this operation if the file system is mounted read-only. */
1820         if (vp->v_mount->mnt_flag & MNT_RDONLY)
1821                 return EROFS;
1822
1823         /* Immutable or append-only files cannot be modified, either. */
1824         if (node->tn_flags & (IMMUTABLE | APPEND))
1825                 return EPERM;
1826
1827         error = vn_utimes_perm(vp, vap, cred, l);
1828         if (error != 0)
1829                 return (error);
1830
1831         if (vap->va_atime.tv_sec != VNOVAL)
1832                 node->tn_status |= TMPFS_NODE_ACCESSED;
1833
1834         if (vap->va_mtime.tv_sec != VNOVAL)
1835                 node->tn_status |= TMPFS_NODE_MODIFIED;
1836
1837         if (vap->va_birthtime.tv_sec != VNOVAL)
1838                 node->tn_status |= TMPFS_NODE_MODIFIED;
1839
1840         tmpfs_itimes(vp, &vap->va_atime, &vap->va_mtime);
1841
1842         if (vap->va_birthtime.tv_sec != VNOVAL)
1843                 node->tn_birthtime = vap->va_birthtime;
1844         ASSERT_VOP_ELOCKED(vp, "chtimes2");
1845
1846         return (0);
1847 }
1848
1849 void
1850 tmpfs_set_status(struct tmpfs_mount *tm, struct tmpfs_node *node, int status)
1851 {
1852
1853         if ((node->tn_status & status) == status || tm->tm_ronly)
1854                 return;
1855         TMPFS_NODE_LOCK(node);
1856         node->tn_status |= status;
1857         TMPFS_NODE_UNLOCK(node);
1858 }
1859
1860 /* Sync timestamps */
1861 void
1862 tmpfs_itimes(struct vnode *vp, const struct timespec *acc,
1863     const struct timespec *mod)
1864 {
1865         struct tmpfs_node *node;
1866         struct timespec now;
1867
1868         ASSERT_VOP_LOCKED(vp, "tmpfs_itimes");
1869         node = VP_TO_TMPFS_NODE(vp);
1870
1871         if ((node->tn_status & (TMPFS_NODE_ACCESSED | TMPFS_NODE_MODIFIED |
1872             TMPFS_NODE_CHANGED)) == 0)
1873                 return;
1874
1875         vfs_timestamp(&now);
1876         TMPFS_NODE_LOCK(node);
1877         if (node->tn_status & TMPFS_NODE_ACCESSED) {
1878                 if (acc == NULL)
1879                          acc = &now;
1880                 node->tn_atime = *acc;
1881         }
1882         if (node->tn_status & TMPFS_NODE_MODIFIED) {
1883                 if (mod == NULL)
1884                         mod = &now;
1885                 node->tn_mtime = *mod;
1886         }
1887         if (node->tn_status & TMPFS_NODE_CHANGED)
1888                 node->tn_ctime = now;
1889         node->tn_status &= ~(TMPFS_NODE_ACCESSED | TMPFS_NODE_MODIFIED |
1890             TMPFS_NODE_CHANGED);
1891         TMPFS_NODE_UNLOCK(node);
1892
1893         /* XXX: FIX? The entropy here is desirable, but the harvesting may be expensive */
1894         random_harvest_queue(node, sizeof(*node), RANDOM_FS_ATIME);
1895 }
1896
1897 int
1898 tmpfs_truncate(struct vnode *vp, off_t length)
1899 {
1900         int error;
1901         struct tmpfs_node *node;
1902
1903         node = VP_TO_TMPFS_NODE(vp);
1904
1905         if (length < 0) {
1906                 error = EINVAL;
1907                 goto out;
1908         }
1909
1910         if (node->tn_size == length) {
1911                 error = 0;
1912                 goto out;
1913         }
1914
1915         if (length > VFS_TO_TMPFS(vp->v_mount)->tm_maxfilesize)
1916                 return (EFBIG);
1917
1918         error = tmpfs_reg_resize(vp, length, FALSE);
1919         if (error == 0)
1920                 node->tn_status |= TMPFS_NODE_CHANGED | TMPFS_NODE_MODIFIED;
1921
1922 out:
1923         tmpfs_update(vp);
1924
1925         return (error);
1926 }
1927
1928 static __inline int
1929 tmpfs_dirtree_cmp(struct tmpfs_dirent *a, struct tmpfs_dirent *b)
1930 {
1931         if (a->td_hash > b->td_hash)
1932                 return (1);
1933         else if (a->td_hash < b->td_hash)
1934                 return (-1);
1935         return (0);
1936 }
1937
1938 RB_GENERATE_STATIC(tmpfs_dir, tmpfs_dirent, uh.td_entries, tmpfs_dirtree_cmp);