1/*	$OpenBSD: msdosfs_denode.c,v 1.68 2023/03/08 04:43:08 guenther Exp $	*/
2/*	$NetBSD: msdosfs_denode.c,v 1.23 1997/10/17 11:23:58 ws Exp $	*/
3
4/*-
5 * Copyright (C) 1994, 1995, 1997 Wolfgang Solfrank.
6 * Copyright (C) 1994, 1995, 1997 TooLs GmbH.
7 * All rights reserved.
8 * Original code by Paul Popelka (paulp@uts.amdahl.com) (see below).
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 *    notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 *    notice, this list of conditions and the following disclaimer in the
17 *    documentation and/or other materials provided with the distribution.
18 * 3. All advertising materials mentioning features or use of this software
19 *    must display the following acknowledgement:
20 *	This product includes software developed by TooLs GmbH.
21 * 4. The name of TooLs GmbH may not be used to endorse or promote products
22 *    derived from this software without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY TOOLS GMBH ``AS IS'' AND ANY EXPRESS OR
25 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
26 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
27 * IN NO EVENT SHALL TOOLS GMBH BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
29 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
30 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
31 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
32 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
33 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 */
35/*
36 * Written by Paul Popelka (paulp@uts.amdahl.com)
37 *
38 * You can do anything you want with this software, just don't say you wrote
39 * it, and don't remove this notice.
40 *
41 * This software is provided "as is".
42 *
43 * The author supplies this software to be publicly redistributed on the
44 * understanding that the author is not responsible for the correct
45 * functioning of this software in any circumstances and is not liable for
46 * any damages caused by this software.
47 *
48 * October 1992
49 */
50
51#include <sys/param.h>
52#include <sys/systm.h>
53#include <sys/mount.h>
54#include <sys/malloc.h>
55#include <sys/buf.h>
56#include <sys/vnode.h>
57#include <sys/lock.h>
58#include <sys/kernel.h>		/* defines "time" */
59#include <sys/dirent.h>
60#include <sys/namei.h>
61
62#include <crypto/siphash.h>
63
64#include <msdosfs/bpb.h>
65#include <msdosfs/msdosfsmount.h>
66#include <msdosfs/direntry.h>
67#include <msdosfs/denode.h>
68#include <msdosfs/fat.h>
69
70u_int msdosfs_dehash(dev_t, uint32_t, uint32_t);
71
72struct denode **dehashtbl;
73SIPHASH_KEY dehashkey;
74u_long dehash;			/* size of hash table - 1 */
75#define	DEHASH(dev, dcl, doff) msdosfs_dehash((dev), (dcl), (doff))
76
77static struct denode *msdosfs_hashget(dev_t, uint32_t, uint32_t);
78static int msdosfs_hashins(struct denode *);
79static void msdosfs_hashrem(struct denode *);
80
81int
82msdosfs_init(struct vfsconf *vfsp)
83{
84	dehashtbl = hashinit(initialvnodes / 2, M_MSDOSFSMNT, M_WAITOK, &dehash);
85	arc4random_buf(&dehashkey, sizeof(dehashkey));
86	return (0);
87}
88
89u_int
90msdosfs_dehash(dev_t dev, uint32_t dirclust, uint32_t diroff)
91{
92	SIPHASH_CTX ctx;
93
94	SipHash24_Init(&ctx, &dehashkey);
95	SipHash24_Update(&ctx, &dev, sizeof(dev));
96	SipHash24_Update(&ctx, &dirclust, sizeof(dirclust));
97	SipHash24_Update(&ctx, &diroff, sizeof(diroff));
98
99	return (SipHash24_End(&ctx) & dehash);
100}
101
102static struct denode *
103msdosfs_hashget(dev_t dev, uint32_t dirclust, uint32_t diroff)
104{
105	struct denode *dep;
106
107	for (;;)
108		for (dep = dehashtbl[DEHASH(dev, dirclust, diroff)]; ;
109		     dep = dep->de_next) {
110			if (dep == NULL)
111				return (NULL);
112			if (dirclust == dep->de_dirclust &&
113			    diroff == dep->de_diroffset &&
114			    dev == dep->de_dev &&
115			    dep->de_refcnt != 0) {
116				struct vnode *vp = DETOV(dep);
117
118				if (!vget(vp, LK_EXCLUSIVE))
119					return (dep);
120				break;
121			}
122		}
123	/* NOTREACHED */
124}
125
126static int
127msdosfs_hashins(struct denode *dep)
128{
129	struct denode **depp, *deq;
130
131	depp = &dehashtbl[DEHASH(dep->de_dev, dep->de_dirclust,
132				 dep->de_diroffset)];
133
134	for (deq = *depp; deq; deq = deq->de_next) {
135		if (dep->de_dirclust == deq->de_dirclust &&
136		    dep->de_diroffset == deq->de_diroffset &&
137		    dep->de_dev == deq->de_dev &&
138		    deq->de_refcnt != 0) {
139			return (EEXIST);
140		}
141	}
142
143	if ((deq = *depp) != NULL)
144		deq->de_prev = &dep->de_next;
145	dep->de_next = deq;
146	dep->de_prev = depp;
147	*depp = dep;
148	return (0);
149}
150
151static void
152msdosfs_hashrem(struct denode *dep)
153{
154	struct denode *deq;
155
156	if (dep->de_prev == NULL)
157		return;
158
159	if ((deq = dep->de_next) != NULL)
160		deq->de_prev = dep->de_prev;
161	*dep->de_prev = deq;
162#ifdef DIAGNOSTIC
163	dep->de_next = NULL;
164	dep->de_prev = NULL;
165#endif
166}
167
168/*
169 * If deget() succeeds it returns with the gotten denode locked().
170 *
171 * pmp	     - address of msdosfsmount structure of the filesystem containing
172 *	       the denode of interest.  The pm_dev field and the address of
173 *	       the msdosfsmount structure are used.
174 * dirclust  - which cluster bp contains, if dirclust is 0 (root directory)
175 *	       diroffset is relative to the beginning of the root directory,
176 *	       otherwise it is cluster relative.
177 * diroffset - offset past begin of cluster of denode we want
178 * depp	     - returns the address of the gotten denode.
179 */
180int
181deget(struct msdosfsmount *pmp, uint32_t dirclust, uint32_t diroffset,
182    struct denode **depp)
183{
184	int error;
185	extern const struct vops msdosfs_vops;
186	struct direntry *direntptr;
187	struct denode *ldep;
188	struct vnode *nvp;
189	struct buf *bp;
190
191#ifdef MSDOSFS_DEBUG
192	printf("deget(pmp %p, dirclust %d, diroffset %x, depp %p)\n",
193	    pmp, dirclust, diroffset, depp);
194#endif
195
196	/*
197	 * On FAT32 filesystems, root is a (more or less) normal
198	 * directory
199	 */
200	if (FAT32(pmp) && dirclust == MSDOSFSROOT)
201		dirclust = pmp->pm_rootdirblk;
202
203	/*
204	 * See if the denode is in the denode cache. Use the location of
205	 * the directory entry to compute the hash value. For subdir use
206	 * address of "." entry. For root dir (if not FAT32) use cluster
207	 * MSDOSFSROOT, offset MSDOSFSROOT_OFS
208	 *
209	 * NOTE: The check for de_refcnt > 0 below insures the denode being
210	 * examined does not represent an unlinked but still open file.
211	 * These files are not to be accessible even when the directory
212	 * entry that represented the file happens to be reused while the
213	 * deleted file is still open.
214	 */
215retry:
216	ldep = msdosfs_hashget(pmp->pm_dev, dirclust, diroffset);
217	if (ldep) {
218		*depp = ldep;
219		return (0);
220	}
221
222	/*
223	 * Directory entry was not in cache, have to create a vnode and
224	 * copy it from the passed disk buffer.
225	 */
226	/* getnewvnode() does a vref() on the vnode */
227	error = getnewvnode(VT_MSDOSFS, pmp->pm_mountp, &msdosfs_vops, &nvp);
228	if (error) {
229		*depp = 0;
230		return (error);
231	}
232	ldep = malloc(sizeof(*ldep), M_MSDOSFSNODE, M_WAITOK | M_ZERO);
233	rrw_init_flags(&ldep->de_lock, "denode", RWL_DUPOK | RWL_IS_VNODE);
234	nvp->v_data = ldep;
235	ldep->de_vnode = nvp;
236	ldep->de_flag = 0;
237	ldep->de_devvp = 0;
238	ldep->de_lockf = 0;
239	ldep->de_dev = pmp->pm_dev;
240	ldep->de_dirclust = dirclust;
241	ldep->de_diroffset = diroffset;
242	fc_purge(ldep, 0);	/* init the fat cache for this denode */
243
244	/*
245	 * Insert the denode into the hash queue and lock the denode so it
246	 * can't be accessed until we've read it in and have done what we
247	 * need to it.
248	 */
249	vn_lock(nvp, LK_EXCLUSIVE | LK_RETRY);
250	error = msdosfs_hashins(ldep);
251
252	if (error) {
253		vput (nvp);
254
255		if (error == EEXIST)
256			goto retry;
257
258		return (error);
259	}
260
261	ldep->de_pmp = pmp;
262	ldep->de_devvp = pmp->pm_devvp;
263	ldep->de_refcnt = 1;
264	/*
265	 * Copy the directory entry into the denode area of the vnode.
266	 */
267	if ((dirclust == MSDOSFSROOT
268	     || (FAT32(pmp) && dirclust == pmp->pm_rootdirblk))
269	    && diroffset == MSDOSFSROOT_OFS) {
270		/*
271		 * Directory entry for the root directory. There isn't one,
272		 * so we manufacture one. We should probably rummage
273		 * through the root directory and find a label entry (if it
274		 * exists), and then use the time and date from that entry
275		 * as the time and date for the root denode.
276		 */
277	        nvp->v_flag |= VROOT; /* should be further down         XXX */
278
279		ldep->de_Attributes = ATTR_DIRECTORY;
280		if (FAT32(pmp))
281		        ldep->de_StartCluster = pmp->pm_rootdirblk;
282		        /* de_FileSize will be filled in further down */
283		else {
284		        ldep->de_StartCluster = MSDOSFSROOT;
285		        ldep->de_FileSize = pmp->pm_rootdirsize * pmp->pm_BytesPerSec;
286		}
287		/*
288		 * fill in time and date so that dos2unixtime() doesn't
289		 * spit up when called from msdosfs_getattr() with root
290		 * denode
291		 */
292		ldep->de_CTime = 0x0000;	/* 00:00:00	 */
293		ldep->de_CTimeHundredth = 0;
294		ldep->de_CDate = (0 << DD_YEAR_SHIFT) | (1 << DD_MONTH_SHIFT)
295		    | (1 << DD_DAY_SHIFT);
296		/* Jan 1, 1980	 */
297		ldep->de_ADate = ldep->de_CDate;
298		ldep->de_MTime = ldep->de_CTime;
299		ldep->de_MDate = ldep->de_CDate;
300		/* leave the other fields as garbage */
301	} else {
302		error = readep(pmp, dirclust, diroffset, &bp, &direntptr);
303		if (error)
304			return (error);
305		DE_INTERNALIZE(ldep, direntptr);
306		brelse(bp);
307	}
308
309	/*
310	 * Fill in a few fields of the vnode and finish filling in the
311	 * denode.  Then return the address of the found denode.
312	 */
313	if (ldep->de_Attributes & ATTR_DIRECTORY) {
314		/*
315		 * Since DOS directory entries that describe directories
316		 * have 0 in the filesize field, we take this opportunity
317		 * to find out the length of the directory and plug it into
318		 * the denode structure.
319		 */
320		uint32_t size;
321
322		nvp->v_type = VDIR;
323		if (ldep->de_StartCluster != MSDOSFSROOT) {
324			error = pcbmap(ldep, CLUST_END, 0, &size, 0);
325			if (error == E2BIG) {
326				ldep->de_FileSize = de_cn2off(pmp, size);
327				error = 0;
328			} else if (error) {
329				printf("deget(): pcbmap returned %d\n", error);
330				return (error);
331			}
332		}
333	} else
334		nvp->v_type = VREG;
335	vref(ldep->de_devvp);
336	*depp = ldep;
337	return (0);
338}
339
340int
341deupdat(struct denode *dep, int waitfor)
342{
343	struct buf *bp;
344	struct direntry *dirp;
345	int error;
346	struct timespec ts;
347
348	if (DETOV(dep)->v_mount->mnt_flag & MNT_RDONLY)
349		return (0);
350	getnanotime(&ts);
351	DETIMES(dep, &ts, &ts, &ts);
352	if ((dep->de_flag & DE_MODIFIED) == 0)
353		return (0);
354	dep->de_flag &= ~DE_MODIFIED;
355	if (dep->de_Attributes & ATTR_DIRECTORY)
356		return (0);
357	if (dep->de_refcnt <= 0)
358		return (0);
359	error = readde(dep, &bp, &dirp);
360	if (error)
361		return (error);
362	DE_EXTERNALIZE(dirp, dep);
363	if (waitfor)
364		return (bwrite(bp));
365	else {
366		bdwrite(bp);
367		return (0);
368	}
369}
370
371/*
372 * Truncate the file described by dep to the length specified by length.
373 */
374int
375detrunc(struct denode *dep, uint32_t length, int flags, struct ucred *cred,
376    struct proc *p)
377{
378	int error;
379	int allerror;
380	int vflags;
381	uint32_t eofentry;
382	uint32_t chaintofree = 0;
383	daddr_t bn;
384	int boff;
385	int isadir = dep->de_Attributes & ATTR_DIRECTORY;
386	struct buf *bp;
387	struct msdosfsmount *pmp = dep->de_pmp;
388
389#ifdef MSDOSFS_DEBUG
390	printf("detrunc(): file %.11s, length %u, flags %d\n",
391	    dep->de_Name, length, flags);
392#endif
393
394	/*
395	 * Disallow attempts to truncate the root directory since it is of
396	 * fixed size.  That's just the way dos filesystems are.  We use
397	 * the VROOT bit in the vnode because checking for the directory
398	 * bit and a startcluster of 0 in the denode is not adequate to
399	 * recognize the root directory at this point in a file or
400	 * directory's life.
401	 */
402	if ((DETOV(dep)->v_flag & VROOT) && !FAT32(pmp)) {
403		printf("detrunc(): can't truncate root directory, clust %u, offset %u\n",
404		    dep->de_dirclust, dep->de_diroffset);
405		return (EINVAL);
406	}
407
408	uvm_vnp_setsize(DETOV(dep), length);
409
410	if (dep->de_FileSize < length)
411		return (deextend(dep, length, cred));
412
413	/*
414	 * If the desired length is 0 then remember the starting cluster of
415	 * the file and set the StartCluster field in the directory entry
416	 * to 0.  If the desired length is not zero, then get the number of
417	 * the last cluster in the shortened file.  Then get the number of
418	 * the first cluster in the part of the file that is to be freed.
419	 * Then set the next cluster pointer in the last cluster of the
420	 * file to CLUST_EOFE.
421	 */
422	if (length == 0) {
423		chaintofree = dep->de_StartCluster;
424		dep->de_StartCluster = 0;
425		eofentry = ~0;
426	} else {
427		error = pcbmap(dep, de_clcount(pmp, length) - 1, 0,
428			       &eofentry, 0);
429		if (error) {
430#ifdef MSDOSFS_DEBUG
431			printf("detrunc(): pcbmap fails %d\n", error);
432#endif
433			return (error);
434		}
435	}
436
437	fc_purge(dep, de_clcount(pmp, length));
438
439	/*
440	 * If the new length is not a multiple of the cluster size then we
441	 * must zero the tail end of the new last cluster in case it
442	 * becomes part of the file again because of a seek.
443	 */
444	if ((boff = length & pmp->pm_crbomask) != 0) {
445		if (isadir) {
446			bn = cntobn(pmp, eofentry);
447			error = bread(pmp->pm_devvp, bn, pmp->pm_bpcluster, &bp);
448		} else {
449			bn = de_blk(pmp, length);
450			error = bread(DETOV(dep), bn, pmp->pm_bpcluster, &bp);
451		}
452		if (error) {
453			brelse(bp);
454#ifdef MSDOSFS_DEBUG
455			printf("detrunc(): bread fails %d\n", error);
456#endif
457			return (error);
458		}
459		uvm_vnp_uncache(DETOV(dep));
460		/*
461		 * is this the right place for it?
462		 */
463		bzero(bp->b_data + boff, pmp->pm_bpcluster - boff);
464		if (flags & IO_SYNC)
465			bwrite(bp);
466		else
467			bdwrite(bp);
468	}
469
470	/*
471	 * Write out the updated directory entry.  Even if the update fails
472	 * we free the trailing clusters.
473	 */
474	dep->de_FileSize = length;
475	if (!isadir)
476		dep->de_flag |= DE_UPDATE|DE_MODIFIED;
477	vflags = (length > 0 ? V_SAVE : 0) | V_SAVEMETA;
478	vinvalbuf(DETOV(dep), vflags, cred, p, 0, INFSLP);
479	allerror = deupdat(dep, 1);
480#ifdef MSDOSFS_DEBUG
481	printf("detrunc(): allerror %d, eofentry %d\n",
482	       allerror, eofentry);
483#endif
484
485	/*
486	 * If we need to break the cluster chain for the file then do it
487	 * now.
488	 */
489	if (eofentry != ~0) {
490		error = fatentry(FAT_GET_AND_SET, pmp, eofentry,
491				 &chaintofree, CLUST_EOFE);
492		if (error) {
493#ifdef MSDOSFS_DEBUG
494			printf("detrunc(): fatentry errors %d\n", error);
495#endif
496			return (error);
497		}
498		fc_setcache(dep, FC_LASTFC, de_cluster(pmp, length - 1),
499			    eofentry);
500	}
501
502	/*
503	 * Now free the clusters removed from the file because of the
504	 * truncation.
505	 */
506	if (chaintofree != 0 && !MSDOSFSEOF(pmp, chaintofree))
507		freeclusterchain(pmp, chaintofree);
508
509	return (allerror);
510}
511
512/*
513 * Extend the file described by dep to length specified by length.
514 */
515int
516deextend(struct denode *dep, uint32_t length, struct ucred *cred)
517{
518	struct msdosfsmount *pmp = dep->de_pmp;
519	uint32_t count;
520	int error;
521
522	/*
523	 * The root of a DOS filesystem cannot be extended.
524	 */
525	if ((DETOV(dep)->v_flag & VROOT) && !FAT32(pmp))
526		return (EINVAL);
527
528	/*
529	 * Directories cannot be extended.
530	 */
531	if (dep->de_Attributes & ATTR_DIRECTORY)
532		return (EISDIR);
533
534	if (length <= dep->de_FileSize)
535		panic("deextend: file too large");
536
537	/*
538	 * Compute the number of clusters to allocate.
539	 */
540	count = de_clcount(pmp, length) - de_clcount(pmp, dep->de_FileSize);
541	if (count > 0) {
542		if (count > pmp->pm_freeclustercount)
543			return (ENOSPC);
544		error = extendfile(dep, count, NULL, NULL, DE_CLEAR);
545		if (error) {
546			/* truncate the added clusters away again */
547			(void) detrunc(dep, dep->de_FileSize, 0, cred, curproc);
548			return (error);
549		}
550	}
551
552	dep->de_FileSize = length;
553	dep->de_flag |= DE_UPDATE|DE_MODIFIED;
554	return (deupdat(dep, 1));
555}
556
557/*
558 * Move a denode to its correct hash queue after the file it represents has
559 * been moved to a new directory.
560 */
561void
562reinsert(struct denode *dep)
563{
564	/*
565	 * Fix up the denode cache.  If the denode is for a directory,
566	 * there is nothing to do since the hash is based on the starting
567	 * cluster of the directory file and that hasn't changed.  If for a
568	 * file the hash is based on the location of the directory entry,
569	 * so we must remove it from the cache and re-enter it with the
570	 * hash based on the new location of the directory entry.
571	 */
572	if (dep->de_Attributes & ATTR_DIRECTORY)
573		return;
574	msdosfs_hashrem(dep);
575	msdosfs_hashins(dep);
576}
577
578int
579msdosfs_reclaim(void *v)
580{
581	struct vop_reclaim_args *ap = v;
582	struct vnode *vp = ap->a_vp;
583	struct denode *dep = VTODE(vp);
584#ifdef DIAGNOSTIC
585	extern int prtactive;
586
587	if (prtactive && vp->v_usecount != 0)
588		vprint("msdosfs_reclaim(): pushing active", vp);
589#endif
590
591#ifdef MSDOSFS_DEBUG
592	printf("msdosfs_reclaim(): dep %p, file %.11s, refcnt %ld\n",
593	    dep, dep->de_Name, dep->de_refcnt);
594#endif
595
596	/*
597	 * Remove the denode from its hash chain.
598	 */
599	msdosfs_hashrem(dep);
600	/*
601	 * Purge old data structures associated with the denode.
602	 */
603	cache_purge(vp);
604	if (dep->de_devvp) {
605		vrele(dep->de_devvp);
606		dep->de_devvp = 0;
607	}
608#if 0 /* XXX */
609	dep->de_flag = 0;
610#endif
611	free(dep, M_MSDOSFSNODE, 0);
612	vp->v_data = NULL;
613	return (0);
614}
615
616int
617msdosfs_inactive(void *v)
618{
619	struct vop_inactive_args *ap = v;
620	struct vnode *vp = ap->a_vp;
621	struct denode *dep = VTODE(vp);
622	int error;
623#ifdef DIAGNOSTIC
624	extern int prtactive;
625
626	if (prtactive && vp->v_usecount != 0)
627		vprint("msdosfs_inactive(): pushing active", vp);
628#endif
629
630#ifdef MSDOSFS_DEBUG
631	printf("msdosfs_inactive(): dep %p, de_Name[0] %x\n", dep,
632	    dep->de_Name[0]);
633#endif
634
635	error = 0;
636
637	/*
638	 * Get rid of denodes related to stale file handles.
639	 */
640	if (dep->de_Name[0] == SLOT_DELETED)
641		goto out;
642
643	/*
644	 * If the file has been deleted and it is on a read/write
645	 * filesystem, then truncate the file, and mark the directory slot
646	 * as empty.  (This may not be necessary for the dos filesystem.)
647	 */
648#ifdef MSDOSFS_DEBUG
649	printf("msdosfs_inactive(): dep %p, refcnt %ld, mntflag %x, "
650	    "MNT_RDONLY %x\n", dep, dep->de_refcnt, vp->v_mount->mnt_flag,
651	    MNT_RDONLY);
652#endif
653	if (dep->de_refcnt <= 0 && (vp->v_mount->mnt_flag & MNT_RDONLY) == 0) {
654		error = detrunc(dep, (uint32_t)0, 0, NOCRED, ap->a_p);
655		dep->de_Name[0] = SLOT_DELETED;
656	}
657	deupdat(dep, 0);
658
659out:
660	VOP_UNLOCK(vp);
661	/*
662	 * If we are done with the denode, reclaim it
663	 * so that it can be reused immediately.
664	 */
665#ifdef MSDOSFS_DEBUG
666	printf("msdosfs_inactive(): v_usecount %d, de_Name[0] %x\n",
667	    vp->v_usecount, dep->de_Name[0]);
668#endif
669	if (dep->de_Name[0] == SLOT_DELETED)
670		vrecycle(vp, ap->a_p);
671	return (error);
672}
673