xref: /freebsd/sys/ufs/ffs/ffs_alloc.c (revision e1ebda4458bbaf7d85fb803e20f3afc5441f24d9)
160727d8bSWarner Losh /*-
24d846d26SWarner Losh  * SPDX-License-Identifier: (BSD-2-Clause AND BSD-3-Clause)
351369649SPedro F. Giffuni  *
41c85e6a3SKirk McKusick  * Copyright (c) 2002 Networks Associates Technology, Inc.
51c85e6a3SKirk McKusick  * All rights reserved.
61c85e6a3SKirk McKusick  *
71c85e6a3SKirk McKusick  * This software was developed for the FreeBSD Project by Marshall
81c85e6a3SKirk McKusick  * Kirk McKusick and Network Associates Laboratories, the Security
91c85e6a3SKirk McKusick  * Research Division of Network Associates, Inc. under DARPA/SPAWAR
101c85e6a3SKirk McKusick  * contract N66001-01-C-8035 ("CBOSS"), as part of the DARPA CHATS
111c85e6a3SKirk McKusick  * research program
121c85e6a3SKirk McKusick  *
1360c97629SRobert Watson  * Redistribution and use in source and binary forms, with or without
1460c97629SRobert Watson  * modification, are permitted provided that the following conditions
1560c97629SRobert Watson  * are met:
1660c97629SRobert Watson  * 1. Redistributions of source code must retain the above copyright
1760c97629SRobert Watson  *    notice, this list of conditions and the following disclaimer.
1860c97629SRobert Watson  * 2. Redistributions in binary form must reproduce the above copyright
1960c97629SRobert Watson  *    notice, this list of conditions and the following disclaimer in the
2060c97629SRobert Watson  *    documentation and/or other materials provided with the distribution.
2160c97629SRobert Watson  *
2260c97629SRobert Watson  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
2360c97629SRobert Watson  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2460c97629SRobert Watson  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2560c97629SRobert Watson  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
2660c97629SRobert Watson  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2760c97629SRobert Watson  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2860c97629SRobert Watson  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2960c97629SRobert Watson  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
3060c97629SRobert Watson  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3160c97629SRobert Watson  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3260c97629SRobert Watson  * SUCH DAMAGE.
3360c97629SRobert Watson  *
34df8bae1dSRodney W. Grimes  * Copyright (c) 1982, 1986, 1989, 1993
35df8bae1dSRodney W. Grimes  *	The Regents of the University of California.  All rights reserved.
36df8bae1dSRodney W. Grimes  *
37df8bae1dSRodney W. Grimes  * Redistribution and use in source and binary forms, with or without
38df8bae1dSRodney W. Grimes  * modification, are permitted provided that the following conditions
39df8bae1dSRodney W. Grimes  * are met:
40df8bae1dSRodney W. Grimes  * 1. Redistributions of source code must retain the above copyright
41df8bae1dSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer.
42df8bae1dSRodney W. Grimes  * 2. Redistributions in binary form must reproduce the above copyright
43df8bae1dSRodney W. Grimes  *    notice, this list of conditions and the following disclaimer in the
44df8bae1dSRodney W. Grimes  *    documentation and/or other materials provided with the distribution.
45fbbd9655SWarner Losh  * 3. Neither the name of the University nor the names of its contributors
46df8bae1dSRodney W. Grimes  *    may be used to endorse or promote products derived from this software
47df8bae1dSRodney W. Grimes  *    without specific prior written permission.
48df8bae1dSRodney W. Grimes  *
49df8bae1dSRodney W. Grimes  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
50df8bae1dSRodney W. Grimes  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
51df8bae1dSRodney W. Grimes  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
52df8bae1dSRodney W. Grimes  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
53df8bae1dSRodney W. Grimes  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
54df8bae1dSRodney W. Grimes  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
55df8bae1dSRodney W. Grimes  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
56df8bae1dSRodney W. Grimes  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
57df8bae1dSRodney W. Grimes  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
58df8bae1dSRodney W. Grimes  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
59df8bae1dSRodney W. Grimes  * SUCH DAMAGE.
60df8bae1dSRodney W. Grimes  */
61df8bae1dSRodney W. Grimes 
62f4636c59SDavid E. O'Brien #include <sys/cdefs.h>
6301733a9bSGarrett Wollman #include "opt_quota.h"
6401733a9bSGarrett Wollman 
65df8bae1dSRodney W. Grimes #include <sys/param.h>
66df8bae1dSRodney W. Grimes #include <sys/systm.h>
679626b608SPoul-Henning Kamp #include <sys/bio.h>
68df8bae1dSRodney W. Grimes #include <sys/buf.h>
69e11b2b69SKonstantin Belousov #include <sys/capsicum.h>
70d9183205SBruce Evans #include <sys/conf.h>
71e268f54cSKirk McKusick #include <sys/fcntl.h>
72812b1d41SKirk McKusick #include <sys/file.h>
7313438f68SAlfred Perlstein #include <sys/filedesc.h>
74e11b2b69SKonstantin Belousov #include <sys/gsb_crc32.h>
75e11b2b69SKonstantin Belousov #include <sys/kernel.h>
76e11b2b69SKonstantin Belousov #include <sys/mount.h>
77acd3428bSRobert Watson #include <sys/priv.h>
78df8bae1dSRodney W. Grimes #include <sys/proc.h>
7999aa3b73SKonstantin Belousov #include <sys/stat.h>
80e268f54cSKirk McKusick #include <sys/syscallsubr.h>
81b8dce649SPoul-Henning Kamp #include <sys/sysctl.h>
82df8bae1dSRodney W. Grimes #include <sys/syslog.h>
838c2a54deSKonstantin Belousov #include <sys/taskqueue.h>
84e11b2b69SKonstantin Belousov #include <sys/vnode.h>
85df8bae1dSRodney W. Grimes 
86e268f54cSKirk McKusick #include <security/audit/audit.h>
87e268f54cSKirk McKusick 
888c2a54deSKonstantin Belousov #include <geom/geom.h>
8906753bd3SWarner Losh #include <geom/geom_vfs.h>
908c2a54deSKonstantin Belousov 
91e268f54cSKirk McKusick #include <ufs/ufs/dir.h>
92a64ed089SRobert Watson #include <ufs/ufs/extattr.h>
93df8bae1dSRodney W. Grimes #include <ufs/ufs/quota.h>
94df8bae1dSRodney W. Grimes #include <ufs/ufs/inode.h>
951c680b45SDavid Greenman #include <ufs/ufs/ufs_extern.h>
96cec0f20cSPoul-Henning Kamp #include <ufs/ufs/ufsmount.h>
97df8bae1dSRodney W. Grimes 
98df8bae1dSRodney W. Grimes #include <ufs/ffs/fs.h>
99df8bae1dSRodney W. Grimes #include <ufs/ffs/ffs_extern.h>
1008c2a54deSKonstantin Belousov #include <ufs/ffs/softdep.h>
101df8bae1dSRodney W. Grimes 
102831b1ff7SKirk McKusick typedef ufs2_daddr_t allocfcn_t(struct inode *ip, uint64_t cg,
103831b1ff7SKirk McKusick 				  ufs2_daddr_t bpref, int size, int rsize);
10457a4e3faSBruce Evans 
105831b1ff7SKirk McKusick static ufs2_daddr_t ffs_alloccg(struct inode *, uint64_t, ufs2_daddr_t, int,
106831b1ff7SKirk McKusick 				  int);
1071c85e6a3SKirk McKusick static ufs2_daddr_t
108113db2ddSJeff Roberson 	      ffs_alloccgblk(struct inode *, struct buf *, ufs2_daddr_t, int);
1098c2a54deSKonstantin Belousov static void	ffs_blkfree_cg(struct ufsmount *, struct fs *,
1108c2a54deSKonstantin Belousov 		    struct vnode *, ufs2_daddr_t, long, ino_t,
1118c2a54deSKonstantin Belousov 		    struct workhead *);
1121102b89bSDavid E. O'Brien #ifdef INVARIANTS
11367702352SKirk McKusick static int	ffs_checkfreeblk(struct inode *, ufs2_daddr_t, long);
114cb451ebdSBruce Evans #endif
115c3046779SKirk McKusick static void	ffs_checkcgintegrity(struct fs *, uint64_t, int);
116831b1ff7SKirk McKusick static ufs2_daddr_t ffs_clusteralloc(struct inode *, uint64_t, ufs2_daddr_t,
117831b1ff7SKirk McKusick 				  int);
1186f1e8551SAlfred Perlstein static ino_t	ffs_dirpref(struct inode *);
119831b1ff7SKirk McKusick static ufs2_daddr_t ffs_fragextend(struct inode *, uint64_t, ufs2_daddr_t,
120e870d1e6SKirk McKusick 		    int, int);
121831b1ff7SKirk McKusick static ufs2_daddr_t	ffs_hashalloc(struct inode *, uint64_t, ufs2_daddr_t,
122831b1ff7SKirk McKusick 		    int, int, allocfcn_t *);
123831b1ff7SKirk McKusick static ufs2_daddr_t ffs_nodealloccg(struct inode *, uint64_t, ufs2_daddr_t, int,
124113db2ddSJeff Roberson 		    int);
1251c85e6a3SKirk McKusick static ufs1_daddr_t ffs_mapsearch(struct fs *, struct cg *, ufs2_daddr_t, int);
1261c85e6a3SKirk McKusick static int	ffs_reallocblks_ufs1(struct vop_reallocblks_args *);
1271c85e6a3SKirk McKusick static int	ffs_reallocblks_ufs2(struct vop_reallocblks_args *);
12875e3597aSKirk McKusick static void	ffs_ckhash_cg(struct buf *);
12926f9a767SRodney W. Grimes 
130df8bae1dSRodney W. Grimes /*
131df8bae1dSRodney W. Grimes  * Allocate a block in the filesystem.
132df8bae1dSRodney W. Grimes  *
133df8bae1dSRodney W. Grimes  * The size of the requested block is given, which must be some
134df8bae1dSRodney W. Grimes  * multiple of fs_fsize and <= fs_bsize.
135df8bae1dSRodney W. Grimes  * A preference may be optionally specified. If a preference is given
136df8bae1dSRodney W. Grimes  * the following hierarchy is used to allocate a block:
137df8bae1dSRodney W. Grimes  *   1) allocate the requested block.
138df8bae1dSRodney W. Grimes  *   2) allocate a rotationally optimal block in the same cylinder.
139df8bae1dSRodney W. Grimes  *   3) allocate a block in the same cylinder group.
1402733b242SGordon Bergling  *   4) quadratically rehash into other cylinder groups, until an
141df8bae1dSRodney W. Grimes  *      available block is located.
1426192525bSMike Pritchard  * If no block preference is given the following hierarchy is used
143df8bae1dSRodney W. Grimes  * to allocate a block:
144df8bae1dSRodney W. Grimes  *   1) allocate a block in the cylinder group that contains the
145df8bae1dSRodney W. Grimes  *      inode for the file.
1462733b242SGordon Bergling  *   2) quadratically rehash into other cylinder groups, until an
147df8bae1dSRodney W. Grimes  *      available block is located.
148df8bae1dSRodney W. Grimes  */
14926f9a767SRodney W. Grimes int
ffs_alloc(struct inode * ip,ufs2_daddr_t lbn,ufs2_daddr_t bpref,int size,int flags,struct ucred * cred,ufs2_daddr_t * bnp)150064e6b43SKirk McKusick ffs_alloc(struct inode *ip,
151064e6b43SKirk McKusick 	ufs2_daddr_t lbn,
152064e6b43SKirk McKusick 	ufs2_daddr_t bpref,
153064e6b43SKirk McKusick 	int size,
154064e6b43SKirk McKusick 	int flags,
155064e6b43SKirk McKusick 	struct ucred *cred,
156064e6b43SKirk McKusick 	ufs2_daddr_t *bnp)
157df8bae1dSRodney W. Grimes {
15805f4ff5dSPoul-Henning Kamp 	struct fs *fs;
1598e37fbadSJeff Roberson 	struct ufsmount *ump;
1601c85e6a3SKirk McKusick 	ufs2_daddr_t bno;
161831b1ff7SKirk McKusick 	uint64_t cg, reclaimed;
16298fff6b5SBrian Somers 	int64_t delta;
163d2fc5315SPoul-Henning Kamp #ifdef QUOTA
164d2fc5315SPoul-Henning Kamp 	int error;
165d2fc5315SPoul-Henning Kamp #endif
166d2fc5315SPoul-Henning Kamp 
167df8bae1dSRodney W. Grimes 	*bnp = 0;
168e1db6897SKonstantin Belousov 	ump = ITOUMP(ip);
169e1db6897SKonstantin Belousov 	fs = ump->um_fs;
1708e37fbadSJeff Roberson 	mtx_assert(UFS_MTX(ump), MA_OWNED);
1711102b89bSDavid E. O'Brien #ifdef INVARIANTS
172831b1ff7SKirk McKusick 	if ((uint64_t)size > fs->fs_bsize || fragoff(fs, size) != 0) {
173d9183205SBruce Evans 		printf("dev = %s, bsize = %ld, size = %d, fs = %s\n",
174e1db6897SKonstantin Belousov 		    devtoname(ump->um_dev), (long)fs->fs_bsize, size,
175d9183205SBruce Evans 		    fs->fs_fsmnt);
176df8bae1dSRodney W. Grimes 		panic("ffs_alloc: bad size");
177df8bae1dSRodney W. Grimes 	}
178df8bae1dSRodney W. Grimes 	if (cred == NOCRED)
179edf8a815SDavid Greenman 		panic("ffs_alloc: missing credential");
1801102b89bSDavid E. O'Brien #endif /* INVARIANTS */
18103a2057aSKirk McKusick 	reclaimed = 0;
18203a2057aSKirk McKusick retry:
1838e37fbadSJeff Roberson #ifdef QUOTA
1848e37fbadSJeff Roberson 	UFS_UNLOCK(ump);
1858e37fbadSJeff Roberson 	error = chkdq(ip, btodb(size), cred, 0);
1868e37fbadSJeff Roberson 	if (error)
1878e37fbadSJeff Roberson 		return (error);
1888e37fbadSJeff Roberson 	UFS_LOCK(ump);
1898e37fbadSJeff Roberson #endif
190df8bae1dSRodney W. Grimes 	if (size == fs->fs_bsize && fs->fs_cstotal.cs_nbfree == 0)
191df8bae1dSRodney W. Grimes 		goto nospace;
192cc426dd3SMateusz Guzik 	if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE) &&
193ec1d10e4SPoul-Henning Kamp 	    freespace(fs, fs->fs_minfree) - numfrags(fs, size) < 0)
194df8bae1dSRodney W. Grimes 		goto nospace;
195df8bae1dSRodney W. Grimes 	if (bpref >= fs->fs_size)
196df8bae1dSRodney W. Grimes 		bpref = 0;
197df8bae1dSRodney W. Grimes 	if (bpref == 0)
198df8bae1dSRodney W. Grimes 		cg = ino_to_cg(fs, ip->i_number);
199df8bae1dSRodney W. Grimes 	else
200df8bae1dSRodney W. Grimes 		cg = dtog(fs, bpref);
201113db2ddSJeff Roberson 	bno = ffs_hashalloc(ip, cg, bpref, size, size, ffs_alloccg);
202df8bae1dSRodney W. Grimes 	if (bno > 0) {
20398fff6b5SBrian Somers 		delta = btodb(size);
20498fff6b5SBrian Somers 		DIP_SET(ip, i_blocks, DIP(ip, i_blocks) + delta);
205ec7e66e8SRobert Watson 		if (flags & IO_EXT)
206ac4ec141SMateusz Guzik 			UFS_INODE_SET_FLAG(ip, IN_CHANGE);
207ec7e66e8SRobert Watson 		else
208ac4ec141SMateusz Guzik 			UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_UPDATE);
209df8bae1dSRodney W. Grimes 		*bnp = bno;
210df8bae1dSRodney W. Grimes 		return (0);
211df8bae1dSRodney W. Grimes 	}
212db9b81eaSMike Pritchard nospace:
213df8bae1dSRodney W. Grimes #ifdef QUOTA
2148e37fbadSJeff Roberson 	UFS_UNLOCK(ump);
215df8bae1dSRodney W. Grimes 	/*
216df8bae1dSRodney W. Grimes 	 * Restore user's disk quota because allocation failed.
217df8bae1dSRodney W. Grimes 	 */
2181c85e6a3SKirk McKusick 	(void) chkdq(ip, -btodb(size), cred, FORCE);
2198e37fbadSJeff Roberson 	UFS_LOCK(ump);
220df8bae1dSRodney W. Grimes #endif
221280e091aSJeff Roberson 	if (reclaimed == 0 && (flags & IO_BUFLOCKED) == 0) {
22203a2057aSKirk McKusick 		reclaimed = 1;
2234c821a39SKirk McKusick 		softdep_request_cleanup(fs, ITOV(ip), cred, FLUSH_BLOCKS_WAIT);
22403a2057aSKirk McKusick 		goto retry;
22503a2057aSKirk McKusick 	}
226d79ff54bSChuck Silvers 	if (ffs_fsfail_cleanup_locked(ump, 0)) {
227d79ff54bSChuck Silvers 		UFS_UNLOCK(ump);
228d79ff54bSChuck Silvers 		return (ENXIO);
229d79ff54bSChuck Silvers 	}
2301fd136ecSKirk McKusick 	if (reclaimed > 0 &&
2311fd136ecSKirk McKusick 	    ppsratecheck(&ump->um_last_fullmsg, &ump->um_secs_fullmsg, 1)) {
2328e37fbadSJeff Roberson 		UFS_UNLOCK(ump);
233c9f96392SKirk McKusick 		ffs_fserr(fs, ip->i_number, "filesystem full");
234e1cef627SPaul Saab 		uprintf("\n%s: write failed, filesystem is full\n",
235e1cef627SPaul Saab 		    fs->fs_fsmnt);
2361fd136ecSKirk McKusick 	} else {
2371fd136ecSKirk McKusick 		UFS_UNLOCK(ump);
238e1cef627SPaul Saab 	}
239df8bae1dSRodney W. Grimes 	return (ENOSPC);
240df8bae1dSRodney W. Grimes }
241df8bae1dSRodney W. Grimes 
242df8bae1dSRodney W. Grimes /*
243df8bae1dSRodney W. Grimes  * Reallocate a fragment to a bigger size
244df8bae1dSRodney W. Grimes  *
245df8bae1dSRodney W. Grimes  * The number and size of the old block is given, and a preference
246df8bae1dSRodney W. Grimes  * and new size is also specified. The allocator attempts to extend
247df8bae1dSRodney W. Grimes  * the original block. Failing that, the regular block allocator is
248df8bae1dSRodney W. Grimes  * invoked to get an appropriate block.
249df8bae1dSRodney W. Grimes  */
25026f9a767SRodney W. Grimes int
ffs_realloccg(struct inode * ip,ufs2_daddr_t lbprev,ufs2_daddr_t bprev,ufs2_daddr_t bpref,int osize,int nsize,int flags,struct ucred * cred,struct buf ** bpp)251064e6b43SKirk McKusick ffs_realloccg(struct inode *ip,
252064e6b43SKirk McKusick 	ufs2_daddr_t lbprev,
253064e6b43SKirk McKusick 	ufs2_daddr_t bprev,
254064e6b43SKirk McKusick 	ufs2_daddr_t bpref,
255064e6b43SKirk McKusick 	int osize,
256064e6b43SKirk McKusick 	int nsize,
257064e6b43SKirk McKusick 	int flags,
258064e6b43SKirk McKusick 	struct ucred *cred,
259064e6b43SKirk McKusick 	struct buf **bpp)
260df8bae1dSRodney W. Grimes {
26103a2057aSKirk McKusick 	struct vnode *vp;
26203a2057aSKirk McKusick 	struct fs *fs;
263df8bae1dSRodney W. Grimes 	struct buf *bp;
2648e37fbadSJeff Roberson 	struct ufsmount *ump;
265831b1ff7SKirk McKusick 	uint64_t cg, request, reclaimed;
26659a01b70SKonstantin Belousov 	int error, gbflags;
2677aca6291SKirk McKusick 	ufs2_daddr_t bno;
26898fff6b5SBrian Somers 	int64_t delta;
269df8bae1dSRodney W. Grimes 
27003a2057aSKirk McKusick 	vp = ITOV(ip);
271e1db6897SKonstantin Belousov 	ump = ITOUMP(ip);
272e1db6897SKonstantin Belousov 	fs = ump->um_fs;
2738e37fbadSJeff Roberson 	bp = NULL;
27459a01b70SKonstantin Belousov 	gbflags = (flags & BA_UNMAPPED) != 0 ? GB_UNMAPPED : 0;
27599aa3b73SKonstantin Belousov #ifdef WITNESS
27699aa3b73SKonstantin Belousov 	gbflags |= IS_SNAPSHOT(ip) ? GB_NOWITNESS : 0;
27799aa3b73SKonstantin Belousov #endif
27859a01b70SKonstantin Belousov 
2798e37fbadSJeff Roberson 	mtx_assert(UFS_MTX(ump), MA_OWNED);
2801102b89bSDavid E. O'Brien #ifdef INVARIANTS
28103a2057aSKirk McKusick 	if (vp->v_mount->mnt_kern_flag & MNTK_SUSPENDED)
282f2a2857bSKirk McKusick 		panic("ffs_realloccg: allocation on suspended filesystem");
283831b1ff7SKirk McKusick 	if ((uint64_t)osize > fs->fs_bsize || fragoff(fs, osize) != 0 ||
284831b1ff7SKirk McKusick 	    (uint64_t)nsize > fs->fs_bsize || fragoff(fs, nsize) != 0) {
285df8bae1dSRodney W. Grimes 		printf(
286d9183205SBruce Evans 		"dev = %s, bsize = %ld, osize = %d, nsize = %d, fs = %s\n",
287e1db6897SKonstantin Belousov 		    devtoname(ump->um_dev), (long)fs->fs_bsize, osize,
288b2b795f0SRodney W. Grimes 		    nsize, fs->fs_fsmnt);
289df8bae1dSRodney W. Grimes 		panic("ffs_realloccg: bad size");
290df8bae1dSRodney W. Grimes 	}
291df8bae1dSRodney W. Grimes 	if (cred == NOCRED)
292edf8a815SDavid Greenman 		panic("ffs_realloccg: missing credential");
2931102b89bSDavid E. O'Brien #endif /* INVARIANTS */
29403a2057aSKirk McKusick 	reclaimed = 0;
29503a2057aSKirk McKusick retry:
296cc426dd3SMateusz Guzik 	if (priv_check_cred(cred, PRIV_VFS_BLOCKRESERVE) &&
2978e37fbadSJeff Roberson 	    freespace(fs, fs->fs_minfree) -  numfrags(fs, nsize - osize) < 0) {
298df8bae1dSRodney W. Grimes 		goto nospace;
2998e37fbadSJeff Roberson 	}
3007aca6291SKirk McKusick 	if (bprev == 0) {
301cfbf0a46SMaxime Henrion 		printf("dev = %s, bsize = %ld, bprev = %jd, fs = %s\n",
302e1db6897SKonstantin Belousov 		    devtoname(ump->um_dev), (long)fs->fs_bsize, (intmax_t)bprev,
303ac1e407bSBruce Evans 		    fs->fs_fsmnt);
304df8bae1dSRodney W. Grimes 		panic("ffs_realloccg: bad bprev");
305df8bae1dSRodney W. Grimes 	}
3068e37fbadSJeff Roberson 	UFS_UNLOCK(ump);
307df8bae1dSRodney W. Grimes 	/*
308df8bae1dSRodney W. Grimes 	 * Allocate the extra space in the buffer.
309df8bae1dSRodney W. Grimes 	 */
31059a01b70SKonstantin Belousov 	error = bread_gb(vp, lbprev, osize, NOCRED, gbflags, &bp);
311c1d9efcbSPoul-Henning Kamp 	if (error) {
312df8bae1dSRodney W. Grimes 		return (error);
313df8bae1dSRodney W. Grimes 	}
31422470903SDavid Greenman 
31522470903SDavid Greenman 	if (bp->b_blkno == bp->b_lblkno) {
3161dc349abSEd Maste 		if (lbprev >= UFS_NDADDR)
31722470903SDavid Greenman 			panic("ffs_realloccg: lbprev out of range");
31822470903SDavid Greenman 		bp->b_blkno = fsbtodb(fs, bprev);
31922470903SDavid Greenman 	}
32022470903SDavid Greenman 
321df8bae1dSRodney W. Grimes #ifdef QUOTA
3221c85e6a3SKirk McKusick 	error = chkdq(ip, btodb(nsize - osize), cred, 0);
323c1d9efcbSPoul-Henning Kamp 	if (error) {
324df8bae1dSRodney W. Grimes 		brelse(bp);
325df8bae1dSRodney W. Grimes 		return (error);
326df8bae1dSRodney W. Grimes 	}
327df8bae1dSRodney W. Grimes #endif
328df8bae1dSRodney W. Grimes 	/*
329df8bae1dSRodney W. Grimes 	 * Check for extension in the existing location.
330df8bae1dSRodney W. Grimes 	 */
331abafa4dbSPedro F. Giffuni 	*bpp = NULL;
332df8bae1dSRodney W. Grimes 	cg = dtog(fs, bprev);
3338e37fbadSJeff Roberson 	UFS_LOCK(ump);
3341c85e6a3SKirk McKusick 	bno = ffs_fragextend(ip, cg, bprev, osize, nsize);
335c1d9efcbSPoul-Henning Kamp 	if (bno) {
336df8bae1dSRodney W. Grimes 		if (bp->b_blkno != fsbtodb(fs, bno))
3375ace3b26SMike Pritchard 			panic("ffs_realloccg: bad blockno");
33898fff6b5SBrian Somers 		delta = btodb(nsize - osize);
33998fff6b5SBrian Somers 		DIP_SET(ip, i_blocks, DIP(ip, i_blocks) + delta);
340ec7e66e8SRobert Watson 		if (flags & IO_EXT)
341ac4ec141SMateusz Guzik 			UFS_INODE_SET_FLAG(ip, IN_CHANGE);
342ec7e66e8SRobert Watson 		else
343ac4ec141SMateusz Guzik 			UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_UPDATE);
344f57459b6SDavid Greenman 		allocbuf(bp, nsize);
345df8bae1dSRodney W. Grimes 		bp->b_flags |= B_DONE;
34659a01b70SKonstantin Belousov 		vfs_bio_bzero_buf(bp, osize, nsize - osize);
3476e5982caSAlan Cox 		if ((bp->b_flags & (B_MALLOC | B_VMIO)) == B_VMIO)
3486e5982caSAlan Cox 			vfs_bio_set_valid(bp, osize, nsize - osize);
349df8bae1dSRodney W. Grimes 		*bpp = bp;
350df8bae1dSRodney W. Grimes 		return (0);
351df8bae1dSRodney W. Grimes 	}
352df8bae1dSRodney W. Grimes 	/*
353df8bae1dSRodney W. Grimes 	 * Allocate a new disk location.
354df8bae1dSRodney W. Grimes 	 */
355df8bae1dSRodney W. Grimes 	if (bpref >= fs->fs_size)
356df8bae1dSRodney W. Grimes 		bpref = 0;
357df8bae1dSRodney W. Grimes 	switch ((int)fs->fs_optim) {
358df8bae1dSRodney W. Grimes 	case FS_OPTSPACE:
359df8bae1dSRodney W. Grimes 		/*
360df8bae1dSRodney W. Grimes 		 * Allocate an exact sized fragment. Although this makes
361df8bae1dSRodney W. Grimes 		 * best use of space, we will waste time relocating it if
362df8bae1dSRodney W. Grimes 		 * the file continues to grow. If the fragmentation is
363df8bae1dSRodney W. Grimes 		 * less than half of the minimum free reserve, we choose
364df8bae1dSRodney W. Grimes 		 * to begin optimizing for time.
365df8bae1dSRodney W. Grimes 		 */
366df8bae1dSRodney W. Grimes 		request = nsize;
367e23c0ff5SDavid Greenman 		if (fs->fs_minfree <= 5 ||
368df8bae1dSRodney W. Grimes 		    fs->fs_cstotal.cs_nffree >
3699f043878SKirk McKusick 		    (off_t)fs->fs_dsize * fs->fs_minfree / (2 * 100))
370df8bae1dSRodney W. Grimes 			break;
371df8bae1dSRodney W. Grimes 		log(LOG_NOTICE, "%s: optimization changed from SPACE to TIME\n",
372df8bae1dSRodney W. Grimes 			fs->fs_fsmnt);
373df8bae1dSRodney W. Grimes 		fs->fs_optim = FS_OPTTIME;
374df8bae1dSRodney W. Grimes 		break;
375df8bae1dSRodney W. Grimes 	case FS_OPTTIME:
376df8bae1dSRodney W. Grimes 		/*
377df8bae1dSRodney W. Grimes 		 * At this point we have discovered a file that is trying to
378df8bae1dSRodney W. Grimes 		 * grow a small fragment to a larger fragment. To save time,
379df8bae1dSRodney W. Grimes 		 * we allocate a full sized block, then free the unused portion.
380df8bae1dSRodney W. Grimes 		 * If the file continues to grow, the `ffs_fragextend' call
381df8bae1dSRodney W. Grimes 		 * above will be able to grow it in place without further
382df8bae1dSRodney W. Grimes 		 * copying. If aberrant programs cause disk fragmentation to
383df8bae1dSRodney W. Grimes 		 * grow within 2% of the free reserve, we choose to begin
384df8bae1dSRodney W. Grimes 		 * optimizing for space.
385df8bae1dSRodney W. Grimes 		 */
386df8bae1dSRodney W. Grimes 		request = fs->fs_bsize;
387df8bae1dSRodney W. Grimes 		if (fs->fs_cstotal.cs_nffree <
3889f043878SKirk McKusick 		    (off_t)fs->fs_dsize * (fs->fs_minfree - 2) / 100)
389df8bae1dSRodney W. Grimes 			break;
390df8bae1dSRodney W. Grimes 		log(LOG_NOTICE, "%s: optimization changed from TIME to SPACE\n",
391df8bae1dSRodney W. Grimes 			fs->fs_fsmnt);
392df8bae1dSRodney W. Grimes 		fs->fs_optim = FS_OPTSPACE;
393df8bae1dSRodney W. Grimes 		break;
394df8bae1dSRodney W. Grimes 	default:
395d9183205SBruce Evans 		printf("dev = %s, optim = %ld, fs = %s\n",
396e1db6897SKonstantin Belousov 		    devtoname(ump->um_dev), (long)fs->fs_optim, fs->fs_fsmnt);
397df8bae1dSRodney W. Grimes 		panic("ffs_realloccg: bad optim");
398df8bae1dSRodney W. Grimes 		/* NOTREACHED */
399df8bae1dSRodney W. Grimes 	}
400113db2ddSJeff Roberson 	bno = ffs_hashalloc(ip, cg, bpref, request, nsize, ffs_alloccg);
401df8bae1dSRodney W. Grimes 	if (bno > 0) {
402df8bae1dSRodney W. Grimes 		bp->b_blkno = fsbtodb(fs, bno);
40303a2057aSKirk McKusick 		if (!DOINGSOFTDEP(vp))
4047e038bc2SKirk McKusick 			/*
4057e038bc2SKirk McKusick 			 * The usual case is that a smaller fragment that
4067e038bc2SKirk McKusick 			 * was just allocated has been replaced with a bigger
4077e038bc2SKirk McKusick 			 * fragment or a full-size block. If it is marked as
4087e038bc2SKirk McKusick 			 * B_DELWRI, the current contents have not been written
4097e038bc2SKirk McKusick 			 * to disk. It is possible that the block was written
4107e038bc2SKirk McKusick 			 * earlier, but very uncommon. If the block has never
4117e038bc2SKirk McKusick 			 * been written, there is no need to send a BIO_DELETE
4127e038bc2SKirk McKusick 			 * for it when it is freed. The gain from avoiding the
4137e038bc2SKirk McKusick 			 * TRIMs for the common case of unwritten blocks far
4147e038bc2SKirk McKusick 			 * exceeds the cost of the write amplification for the
4157e038bc2SKirk McKusick 			 * uncommon case of failing to send a TRIM for a block
4167e038bc2SKirk McKusick 			 * that had been written.
4177e038bc2SKirk McKusick 			 */
418e1db6897SKonstantin Belousov 			ffs_blkfree(ump, fs, ump->um_devvp, bprev, (long)osize,
4197e038bc2SKirk McKusick 			    ip->i_number, vp->v_type, NULL,
4207e038bc2SKirk McKusick 			    (bp->b_flags & B_DELWRI) != 0 ?
4217e038bc2SKirk McKusick 			    NOTRIM_KEY : SINGLETON_KEY);
42298fff6b5SBrian Somers 		delta = btodb(nsize - osize);
42398fff6b5SBrian Somers 		DIP_SET(ip, i_blocks, DIP(ip, i_blocks) + delta);
424ec7e66e8SRobert Watson 		if (flags & IO_EXT)
425ac4ec141SMateusz Guzik 			UFS_INODE_SET_FLAG(ip, IN_CHANGE);
426ec7e66e8SRobert Watson 		else
427ac4ec141SMateusz Guzik 			UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_UPDATE);
428f57459b6SDavid Greenman 		allocbuf(bp, nsize);
429df8bae1dSRodney W. Grimes 		bp->b_flags |= B_DONE;
43059a01b70SKonstantin Belousov 		vfs_bio_bzero_buf(bp, osize, nsize - osize);
4316e5982caSAlan Cox 		if ((bp->b_flags & (B_MALLOC | B_VMIO)) == B_VMIO)
4326e5982caSAlan Cox 			vfs_bio_set_valid(bp, osize, nsize - osize);
433df8bae1dSRodney W. Grimes 		*bpp = bp;
434df8bae1dSRodney W. Grimes 		return (0);
435df8bae1dSRodney W. Grimes 	}
436df8bae1dSRodney W. Grimes #ifdef QUOTA
4378e37fbadSJeff Roberson 	UFS_UNLOCK(ump);
438df8bae1dSRodney W. Grimes 	/*
439df8bae1dSRodney W. Grimes 	 * Restore user's disk quota because allocation failed.
440df8bae1dSRodney W. Grimes 	 */
4411c85e6a3SKirk McKusick 	(void) chkdq(ip, -btodb(nsize - osize), cred, FORCE);
4428e37fbadSJeff Roberson 	UFS_LOCK(ump);
443df8bae1dSRodney W. Grimes #endif
444df8bae1dSRodney W. Grimes nospace:
445df8bae1dSRodney W. Grimes 	/*
446df8bae1dSRodney W. Grimes 	 * no space available
447df8bae1dSRodney W. Grimes 	 */
448280e091aSJeff Roberson 	if (reclaimed == 0 && (flags & IO_BUFLOCKED) == 0) {
44903a2057aSKirk McKusick 		reclaimed = 1;
4508e37fbadSJeff Roberson 		UFS_UNLOCK(ump);
4512950ff25SKonstantin Belousov 		if (bp) {
4528e37fbadSJeff Roberson 			brelse(bp);
4532950ff25SKonstantin Belousov 			bp = NULL;
4542950ff25SKonstantin Belousov 		}
4558e37fbadSJeff Roberson 		UFS_LOCK(ump);
4569f62b10cSKirk McKusick 		softdep_request_cleanup(fs, vp, cred, FLUSH_BLOCKS_WAIT);
45703a2057aSKirk McKusick 		goto retry;
45803a2057aSKirk McKusick 	}
459d79ff54bSChuck Silvers 	if (bp)
460d79ff54bSChuck Silvers 		brelse(bp);
461d79ff54bSChuck Silvers 	if (ffs_fsfail_cleanup_locked(ump, 0)) {
462d79ff54bSChuck Silvers 		UFS_UNLOCK(ump);
463d79ff54bSChuck Silvers 		return (ENXIO);
464d79ff54bSChuck Silvers 	}
4651fd136ecSKirk McKusick 	if (reclaimed > 0 &&
4661fd136ecSKirk McKusick 	    ppsratecheck(&ump->um_last_fullmsg, &ump->um_secs_fullmsg, 1)) {
4678e37fbadSJeff Roberson 		UFS_UNLOCK(ump);
468c9f96392SKirk McKusick 		ffs_fserr(fs, ip->i_number, "filesystem full");
469e1cef627SPaul Saab 		uprintf("\n%s: write failed, filesystem is full\n",
470e1cef627SPaul Saab 		    fs->fs_fsmnt);
4711fd136ecSKirk McKusick 	} else {
4721fd136ecSKirk McKusick 		UFS_UNLOCK(ump);
473e1cef627SPaul Saab 	}
474df8bae1dSRodney W. Grimes 	return (ENOSPC);
475df8bae1dSRodney W. Grimes }
476df8bae1dSRodney W. Grimes 
477df8bae1dSRodney W. Grimes /*
478df8bae1dSRodney W. Grimes  * Reallocate a sequence of blocks into a contiguous sequence of blocks.
479df8bae1dSRodney W. Grimes  *
480df8bae1dSRodney W. Grimes  * The vnode and an array of buffer pointers for a range of sequential
481df8bae1dSRodney W. Grimes  * logical blocks to be made contiguous is given. The allocator attempts
4821c85e6a3SKirk McKusick  * to find a range of sequential blocks starting as close as possible
4831c85e6a3SKirk McKusick  * from the end of the allocation for the logical block immediately
4841c85e6a3SKirk McKusick  * preceding the current range. If successful, the physical block numbers
4851c85e6a3SKirk McKusick  * in the buffer pointers and in the inode are changed to reflect the new
4861c85e6a3SKirk McKusick  * allocation. If unsuccessful, the allocation is left unchanged. The
4871c85e6a3SKirk McKusick  * success in doing the reallocation is returned. Note that the error
4881c85e6a3SKirk McKusick  * return is not reflected back to the user. Rather the previous block
4891c85e6a3SKirk McKusick  * allocation will be used.
490df8bae1dSRodney W. Grimes  */
491812b1d41SKirk McKusick 
492*e1ebda44SGleb Smirnoff SYSCTL_DECL(_vfs_ffs);
493812b1d41SKirk McKusick 
494b8dce649SPoul-Henning Kamp static int doasyncfree = 1;
49574a87c38SKirk McKusick SYSCTL_INT(_vfs_ffs, OID_AUTO, doasyncfree, CTLFLAG_RW, &doasyncfree, 0,
49674a87c38SKirk McKusick "do not force synchronous writes when blocks are reallocated");
497996c772fSJohn Dyson 
498cb451ebdSBruce Evans static int doreallocblks = 1;
49974a87c38SKirk McKusick SYSCTL_INT(_vfs_ffs, OID_AUTO, doreallocblks, CTLFLAG_RW, &doreallocblks, 0,
50074a87c38SKirk McKusick "enable block reallocation");
50174a87c38SKirk McKusick 
5024b6a2c49SKirk McKusick static int dotrimcons = 1;
5034b6a2c49SKirk McKusick SYSCTL_INT(_vfs_ffs, OID_AUTO, dotrimcons, CTLFLAG_RWTUN, &dotrimcons, 0,
504a9c2220fSKirk McKusick "enable BIO_DELETE / TRIM consolidation");
505fc6e1715SKirk McKusick 
50674a87c38SKirk McKusick static int maxclustersearch = 10;
50774a87c38SKirk McKusick SYSCTL_INT(_vfs_ffs, OID_AUTO, maxclustersearch, CTLFLAG_RW, &maxclustersearch,
508f9af3151SGordon Bergling 0, "max number of cylinder group to search for contigous blocks");
509996c772fSJohn Dyson 
510af6aeacbSKirk McKusick #ifdef DIAGNOSTIC
511af6aeacbSKirk McKusick static int prtrealloc = 0;
512af6aeacbSKirk McKusick SYSCTL_INT(_debug, OID_AUTO, ffs_prtrealloc, CTLFLAG_RW, &prtrealloc, 0,
513af6aeacbSKirk McKusick 	"print out FFS filesystem block reallocation operations");
514d64dbc87SBruce Evans #endif
5152ea354c3SBruce Evans 
516df8bae1dSRodney W. Grimes int
ffs_reallocblks(struct vop_reallocblks_args * ap)517064e6b43SKirk McKusick ffs_reallocblks(
518df8bae1dSRodney W. Grimes 	struct vop_reallocblks_args /* {
519df8bae1dSRodney W. Grimes 		struct vnode *a_vp;
520df8bae1dSRodney W. Grimes 		struct cluster_save *a_buflist;
521064e6b43SKirk McKusick 	} */ *ap)
522df8bae1dSRodney W. Grimes {
523476dfdc3SWarner Losh 	struct ufsmount *ump;
524d4d289cdSKonstantin Belousov 	int error;
5251c85e6a3SKirk McKusick 
526476dfdc3SWarner Losh 	/*
5274de0d16bSKirk McKusick 	 * We used to skip reallocating the blocks of a file into a
5284de0d16bSKirk McKusick 	 * contiguous sequence if the underlying flash device requested
5294de0d16bSKirk McKusick 	 * BIO_DELETE notifications, because devices that benefit from
5304de0d16bSKirk McKusick 	 * BIO_DELETE also benefit from not moving the data. However,
5314de0d16bSKirk McKusick 	 * the destination for the data is usually moved before the data
5324de0d16bSKirk McKusick 	 * is written to the initially allocated location, so we rarely
5334de0d16bSKirk McKusick 	 * suffer the penalty of extra writes. With the addition of the
534a9c2220fSKirk McKusick 	 * consolidation of contiguous blocks into single BIO_DELETE
5354de0d16bSKirk McKusick 	 * operations, having fewer but larger contiguous blocks reduces
5364de0d16bSKirk McKusick 	 * the number of (slow and expensive) BIO_DELETE operations. So
537a9c2220fSKirk McKusick 	 * when doing BIO_DELETE consolidation, we do block reallocation.
5384de0d16bSKirk McKusick 	 *
5394de0d16bSKirk McKusick 	 * Skip if reallocblks has been disabled globally.
540476dfdc3SWarner Losh 	 */
541e1db6897SKonstantin Belousov 	ump = ap->a_vp->v_mount->mnt_data;
5424de0d16bSKirk McKusick 	if ((((ump->um_flags) & UM_CANDELETE) != 0 && dotrimcons == 0) ||
5434de0d16bSKirk McKusick 	    doreallocblks == 0)
5441c85e6a3SKirk McKusick 		return (ENOSPC);
545476dfdc3SWarner Losh 
546113db2ddSJeff Roberson 	/*
547113db2ddSJeff Roberson 	 * We can't wait in softdep prealloc as it may fsync and recurse
548113db2ddSJeff Roberson 	 * here.  Instead we simply fail to reallocate blocks if this
549113db2ddSJeff Roberson 	 * rare condition arises.
550113db2ddSJeff Roberson 	 */
551cc9958bfSKonstantin Belousov 	if (DOINGSUJ(ap->a_vp))
552113db2ddSJeff Roberson 		if (softdep_prealloc(ap->a_vp, MNT_NOWAIT) != 0)
553113db2ddSJeff Roberson 			return (ENOSPC);
554d4d289cdSKonstantin Belousov 	vn_seqc_write_begin(ap->a_vp);
555d4d289cdSKonstantin Belousov 	error = ump->um_fstype == UFS1 ? ffs_reallocblks_ufs1(ap) :
556d4d289cdSKonstantin Belousov 	    ffs_reallocblks_ufs2(ap);
557d4d289cdSKonstantin Belousov 	vn_seqc_write_end(ap->a_vp);
558d4d289cdSKonstantin Belousov 	return (error);
5591c85e6a3SKirk McKusick }
5601c85e6a3SKirk McKusick 
5611c85e6a3SKirk McKusick static int
ffs_reallocblks_ufs1(struct vop_reallocblks_args * ap)562064e6b43SKirk McKusick ffs_reallocblks_ufs1(
5631c85e6a3SKirk McKusick 	struct vop_reallocblks_args /* {
5641c85e6a3SKirk McKusick 		struct vnode *a_vp;
5651c85e6a3SKirk McKusick 		struct cluster_save *a_buflist;
566064e6b43SKirk McKusick 	} */ *ap)
5671c85e6a3SKirk McKusick {
568df8bae1dSRodney W. Grimes 	struct fs *fs;
569df8bae1dSRodney W. Grimes 	struct inode *ip;
570df8bae1dSRodney W. Grimes 	struct vnode *vp;
5717e038bc2SKirk McKusick 	struct buf *sbp, *ebp, *bp;
572abafa4dbSPedro F. Giffuni 	ufs1_daddr_t *bap, *sbap, *ebap;
573df8bae1dSRodney W. Grimes 	struct cluster_save *buflist;
5748e37fbadSJeff Roberson 	struct ufsmount *ump;
5751c85e6a3SKirk McKusick 	ufs_lbn_t start_lbn, end_lbn;
5761c85e6a3SKirk McKusick 	ufs1_daddr_t soff, newblk, blkno;
5771c85e6a3SKirk McKusick 	ufs2_daddr_t pref;
5781dc349abSEd Maste 	struct indir start_ap[UFS_NIADDR + 1], end_ap[UFS_NIADDR + 1], *idp;
57974a87c38SKirk McKusick 	int i, cg, len, start_lvl, end_lvl, ssize;
580df8bae1dSRodney W. Grimes 
581df8bae1dSRodney W. Grimes 	vp = ap->a_vp;
582df8bae1dSRodney W. Grimes 	ip = VTOI(vp);
583e1db6897SKonstantin Belousov 	ump = ITOUMP(ip);
584e1db6897SKonstantin Belousov 	fs = ump->um_fs;
58528702816SKirk McKusick 	/*
586be1fd823SKirk McKusick 	 * If we are not tracking block clusters or if we have less than 4%
58728702816SKirk McKusick 	 * free blocks left, then do not attempt to cluster. Running with
58828702816SKirk McKusick 	 * less than 5% free block reserve is not recommended and those that
58928702816SKirk McKusick 	 * choose to do so do not expect to have good file layout.
59028702816SKirk McKusick 	 */
591be1fd823SKirk McKusick 	if (fs->fs_contigsumsize <= 0 || freespace(fs, 4) < 0)
592df8bae1dSRodney W. Grimes 		return (ENOSPC);
593df8bae1dSRodney W. Grimes 	buflist = ap->a_buflist;
594df8bae1dSRodney W. Grimes 	len = buflist->bs_nchildren;
595df8bae1dSRodney W. Grimes 	start_lbn = buflist->bs_children[0]->b_lblkno;
596df8bae1dSRodney W. Grimes 	end_lbn = start_lbn + len - 1;
5971102b89bSDavid E. O'Brien #ifdef INVARIANTS
598996c772fSJohn Dyson 	for (i = 0; i < len; i++)
59967702352SKirk McKusick 		if (!ffs_checkfreeblk(ip,
600996c772fSJohn Dyson 		   dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
601996c772fSJohn Dyson 			panic("ffs_reallocblks: unallocated block 1");
602df8bae1dSRodney W. Grimes 	for (i = 1; i < len; i++)
603df8bae1dSRodney W. Grimes 		if (buflist->bs_children[i]->b_lblkno != start_lbn + i)
604996c772fSJohn Dyson 			panic("ffs_reallocblks: non-logical cluster");
605996c772fSJohn Dyson 	blkno = buflist->bs_children[0]->b_blkno;
606996c772fSJohn Dyson 	ssize = fsbtodb(fs, fs->fs_frag);
607996c772fSJohn Dyson 	for (i = 1; i < len - 1; i++)
608996c772fSJohn Dyson 		if (buflist->bs_children[i]->b_blkno != blkno + (i * ssize))
609996c772fSJohn Dyson 			panic("ffs_reallocblks: non-physical cluster %d", i);
610df8bae1dSRodney W. Grimes #endif
611df8bae1dSRodney W. Grimes 	/*
612aa7ddc85SKirk McKusick 	 * If the cluster crosses the boundary for the first indirect
613aa7ddc85SKirk McKusick 	 * block, leave space for the indirect block. Indirect blocks
614aa7ddc85SKirk McKusick 	 * are initially laid out in a position after the last direct
615aa7ddc85SKirk McKusick 	 * block. Block reallocation would usually destroy locality by
616aa7ddc85SKirk McKusick 	 * moving the indirect block out of the way to make room for
617aa7ddc85SKirk McKusick 	 * data blocks if we didn't compensate here. We should also do
618aa7ddc85SKirk McKusick 	 * this for other indirect block boundaries, but it is only
619aa7ddc85SKirk McKusick 	 * important for the first one.
620aa7ddc85SKirk McKusick 	 */
6211dc349abSEd Maste 	if (start_lbn < UFS_NDADDR && end_lbn >= UFS_NDADDR)
622aa7ddc85SKirk McKusick 		return (ENOSPC);
623aa7ddc85SKirk McKusick 	/*
624df8bae1dSRodney W. Grimes 	 * If the latest allocation is in a new cylinder group, assume that
625df8bae1dSRodney W. Grimes 	 * the filesystem has decided to move and do not force it back to
626df8bae1dSRodney W. Grimes 	 * the previous cylinder group.
627df8bae1dSRodney W. Grimes 	 */
628df8bae1dSRodney W. Grimes 	if (dtog(fs, dbtofsb(fs, buflist->bs_children[0]->b_blkno)) !=
629df8bae1dSRodney W. Grimes 	    dtog(fs, dbtofsb(fs, buflist->bs_children[len - 1]->b_blkno)))
630df8bae1dSRodney W. Grimes 		return (ENOSPC);
631df8bae1dSRodney W. Grimes 	if (ufs_getlbns(vp, start_lbn, start_ap, &start_lvl) ||
632df8bae1dSRodney W. Grimes 	    ufs_getlbns(vp, end_lbn, end_ap, &end_lvl))
633df8bae1dSRodney W. Grimes 		return (ENOSPC);
634df8bae1dSRodney W. Grimes 	/*
635df8bae1dSRodney W. Grimes 	 * Get the starting offset and block map for the first block.
636df8bae1dSRodney W. Grimes 	 */
637df8bae1dSRodney W. Grimes 	if (start_lvl == 0) {
6381c85e6a3SKirk McKusick 		sbap = &ip->i_din1->di_db[0];
639df8bae1dSRodney W. Grimes 		soff = start_lbn;
640df8bae1dSRodney W. Grimes 	} else {
641df8bae1dSRodney W. Grimes 		idp = &start_ap[start_lvl - 1];
642df8bae1dSRodney W. Grimes 		if (bread(vp, idp->in_lbn, (int)fs->fs_bsize, NOCRED, &sbp)) {
643df8bae1dSRodney W. Grimes 			brelse(sbp);
644df8bae1dSRodney W. Grimes 			return (ENOSPC);
645df8bae1dSRodney W. Grimes 		}
6461c85e6a3SKirk McKusick 		sbap = (ufs1_daddr_t *)sbp->b_data;
647df8bae1dSRodney W. Grimes 		soff = idp->in_off;
648df8bae1dSRodney W. Grimes 	}
649df8bae1dSRodney W. Grimes 	/*
650df8bae1dSRodney W. Grimes 	 * If the block range spans two block maps, get the second map.
651df8bae1dSRodney W. Grimes 	 */
652abafa4dbSPedro F. Giffuni 	ebap = NULL;
653df8bae1dSRodney W. Grimes 	if (end_lvl == 0 || (idp = &end_ap[end_lvl - 1])->in_off + 1 >= len) {
654df8bae1dSRodney W. Grimes 		ssize = len;
655df8bae1dSRodney W. Grimes 	} else {
6561102b89bSDavid E. O'Brien #ifdef INVARIANTS
657d9e6294eSKen Smith 		if (start_lvl > 0 &&
658d9e6294eSKen Smith 		    start_ap[start_lvl - 1].in_lbn == idp->in_lbn)
659df8bae1dSRodney W. Grimes 			panic("ffs_reallocblk: start == end");
660df8bae1dSRodney W. Grimes #endif
661df8bae1dSRodney W. Grimes 		ssize = len - (idp->in_off + 1);
662df8bae1dSRodney W. Grimes 		if (bread(vp, idp->in_lbn, (int)fs->fs_bsize, NOCRED, &ebp))
663df8bae1dSRodney W. Grimes 			goto fail;
6641c85e6a3SKirk McKusick 		ebap = (ufs1_daddr_t *)ebp->b_data;
665df8bae1dSRodney W. Grimes 	}
666df8bae1dSRodney W. Grimes 	/*
66774a87c38SKirk McKusick 	 * Find the preferred location for the cluster. If we have not
66874a87c38SKirk McKusick 	 * previously failed at this endeavor, then follow our standard
66974a87c38SKirk McKusick 	 * preference calculation. If we have failed at it, then pick up
67074a87c38SKirk McKusick 	 * where we last ended our search.
6718e37fbadSJeff Roberson 	 */
6728e37fbadSJeff Roberson 	UFS_LOCK(ump);
67374a87c38SKirk McKusick 	if (ip->i_nextclustercg == -1)
6748e37fbadSJeff Roberson 		pref = ffs_blkpref_ufs1(ip, start_lbn, soff, sbap);
67574a87c38SKirk McKusick 	else
67674a87c38SKirk McKusick 		pref = cgdata(fs, ip->i_nextclustercg);
6778e37fbadSJeff Roberson 	/*
678df8bae1dSRodney W. Grimes 	 * Search the block map looking for an allocation of the desired size.
67974a87c38SKirk McKusick 	 * To avoid wasting too much time, we limit the number of cylinder
68074a87c38SKirk McKusick 	 * groups that we will search.
681df8bae1dSRodney W. Grimes 	 */
68274a87c38SKirk McKusick 	cg = dtog(fs, pref);
683dc37121dSKonstantin Belousov 	MPASS(cg < fs->fs_ncg);
68474a87c38SKirk McKusick 	for (i = min(maxclustersearch, fs->fs_ncg); i > 0; i--) {
68574a87c38SKirk McKusick 		if ((newblk = ffs_clusteralloc(ip, cg, pref, len)) != 0)
68674a87c38SKirk McKusick 			break;
68774a87c38SKirk McKusick 		cg += 1;
68874a87c38SKirk McKusick 		if (cg >= fs->fs_ncg)
68974a87c38SKirk McKusick 			cg = 0;
69074a87c38SKirk McKusick 	}
69174a87c38SKirk McKusick 	/*
69274a87c38SKirk McKusick 	 * If we have failed in our search, record where we gave up for
69374a87c38SKirk McKusick 	 * next time. Otherwise, fall back to our usual search citerion.
69474a87c38SKirk McKusick 	 */
69574a87c38SKirk McKusick 	if (newblk == 0) {
69674a87c38SKirk McKusick 		ip->i_nextclustercg = cg;
6978e37fbadSJeff Roberson 		UFS_UNLOCK(ump);
698df8bae1dSRodney W. Grimes 		goto fail;
6998e37fbadSJeff Roberson 	}
70074a87c38SKirk McKusick 	ip->i_nextclustercg = -1;
701df8bae1dSRodney W. Grimes 	/*
702df8bae1dSRodney W. Grimes 	 * We have found a new contiguous block.
703df8bae1dSRodney W. Grimes 	 *
704df8bae1dSRodney W. Grimes 	 * First we have to replace the old block pointers with the new
705df8bae1dSRodney W. Grimes 	 * block pointers in the inode and indirect blocks associated
706df8bae1dSRodney W. Grimes 	 * with the file.
707df8bae1dSRodney W. Grimes 	 */
708af6aeacbSKirk McKusick #ifdef DIAGNOSTIC
709996c772fSJohn Dyson 	if (prtrealloc)
710fc8fdae0SMatthew D Fleming 		printf("realloc: ino %ju, lbns %jd-%jd\n\told:",
711fc8fdae0SMatthew D Fleming 		    (uintmax_t)ip->i_number,
7121c85e6a3SKirk McKusick 		    (intmax_t)start_lbn, (intmax_t)end_lbn);
713996c772fSJohn Dyson #endif
714df8bae1dSRodney W. Grimes 	blkno = newblk;
715df8bae1dSRodney W. Grimes 	for (bap = &sbap[soff], i = 0; i < len; i++, blkno += fs->fs_frag) {
716b1897c19SJulian Elischer 		if (i == ssize) {
717df8bae1dSRodney W. Grimes 			bap = ebap;
718b1897c19SJulian Elischer 			soff = -i;
719b1897c19SJulian Elischer 		}
7201102b89bSDavid E. O'Brien #ifdef INVARIANTS
72167702352SKirk McKusick 		if (!ffs_checkfreeblk(ip,
722996c772fSJohn Dyson 		   dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
723996c772fSJohn Dyson 			panic("ffs_reallocblks: unallocated block 2");
724996c772fSJohn Dyson 		if (dbtofsb(fs, buflist->bs_children[i]->b_blkno) != *bap)
725df8bae1dSRodney W. Grimes 			panic("ffs_reallocblks: alloc mismatch");
726df8bae1dSRodney W. Grimes #endif
727af6aeacbSKirk McKusick #ifdef DIAGNOSTIC
728996c772fSJohn Dyson 		if (prtrealloc)
729996c772fSJohn Dyson 			printf(" %d,", *bap);
730996c772fSJohn Dyson #endif
731b1897c19SJulian Elischer 		if (DOINGSOFTDEP(vp)) {
7321c85e6a3SKirk McKusick 			if (sbap == &ip->i_din1->di_db[0] && i < ssize)
733b1897c19SJulian Elischer 				softdep_setup_allocdirect(ip, start_lbn + i,
734b1897c19SJulian Elischer 				    blkno, *bap, fs->fs_bsize, fs->fs_bsize,
735b1897c19SJulian Elischer 				    buflist->bs_children[i]);
736b1897c19SJulian Elischer 			else
737b1897c19SJulian Elischer 				softdep_setup_allocindir_page(ip, start_lbn + i,
738b1897c19SJulian Elischer 				    i < ssize ? sbp : ebp, soff + i, blkno,
739b1897c19SJulian Elischer 				    *bap, buflist->bs_children[i]);
740b1897c19SJulian Elischer 		}
741df8bae1dSRodney W. Grimes 		*bap++ = blkno;
742df8bae1dSRodney W. Grimes 	}
743df8bae1dSRodney W. Grimes 	/*
744df8bae1dSRodney W. Grimes 	 * Next we must write out the modified inode and indirect blocks.
745df8bae1dSRodney W. Grimes 	 * For strict correctness, the writes should be synchronous since
746df8bae1dSRodney W. Grimes 	 * the old block values may have been written to disk. In practise
747df8bae1dSRodney W. Grimes 	 * they are almost never written, but if we are concerned about
748df8bae1dSRodney W. Grimes 	 * strict correctness, the `doasyncfree' flag should be set to zero.
749df8bae1dSRodney W. Grimes 	 *
750df8bae1dSRodney W. Grimes 	 * The test on `doasyncfree' should be changed to test a flag
751df8bae1dSRodney W. Grimes 	 * that shows whether the associated buffers and inodes have
752df8bae1dSRodney W. Grimes 	 * been written. The flag should be set when the cluster is
753df8bae1dSRodney W. Grimes 	 * started and cleared whenever the buffer or inode is flushed.
754df8bae1dSRodney W. Grimes 	 * We can then check below to see if it is set, and do the
755df8bae1dSRodney W. Grimes 	 * synchronous write only when it has been cleared.
756df8bae1dSRodney W. Grimes 	 */
7571c85e6a3SKirk McKusick 	if (sbap != &ip->i_din1->di_db[0]) {
758df8bae1dSRodney W. Grimes 		if (doasyncfree)
759df8bae1dSRodney W. Grimes 			bdwrite(sbp);
760df8bae1dSRodney W. Grimes 		else
761df8bae1dSRodney W. Grimes 			bwrite(sbp);
762df8bae1dSRodney W. Grimes 	} else {
763ac4ec141SMateusz Guzik 		UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_UPDATE);
764de5d1ba5SBruce Evans 		if (!doasyncfree)
765efd6d980SPoul-Henning Kamp 			ffs_update(vp, 1);
766df8bae1dSRodney W. Grimes 	}
767dfd5dee1SPeter Wemm 	if (ssize < len) {
768df8bae1dSRodney W. Grimes 		if (doasyncfree)
769df8bae1dSRodney W. Grimes 			bdwrite(ebp);
770df8bae1dSRodney W. Grimes 		else
771df8bae1dSRodney W. Grimes 			bwrite(ebp);
772dfd5dee1SPeter Wemm 	}
773df8bae1dSRodney W. Grimes 	/*
774df8bae1dSRodney W. Grimes 	 * Last, free the old blocks and assign the new blocks to the buffers.
775df8bae1dSRodney W. Grimes 	 */
776af6aeacbSKirk McKusick #ifdef DIAGNOSTIC
777996c772fSJohn Dyson 	if (prtrealloc)
778996c772fSJohn Dyson 		printf("\n\tnew:");
779996c772fSJohn Dyson #endif
780df8bae1dSRodney W. Grimes 	for (blkno = newblk, i = 0; i < len; i++, blkno += fs->fs_frag) {
7817e038bc2SKirk McKusick 		bp = buflist->bs_children[i];
782b1897c19SJulian Elischer 		if (!DOINGSOFTDEP(vp))
7837e038bc2SKirk McKusick 			/*
7847e038bc2SKirk McKusick 			 * The usual case is that a set of N-contiguous blocks
7857e038bc2SKirk McKusick 			 * that was just allocated has been replaced with a
7867e038bc2SKirk McKusick 			 * set of N+1-contiguous blocks. If they are marked as
7877e038bc2SKirk McKusick 			 * B_DELWRI, the current contents have not been written
7887e038bc2SKirk McKusick 			 * to disk. It is possible that the blocks were written
7897e038bc2SKirk McKusick 			 * earlier, but very uncommon. If the blocks have never
7907e038bc2SKirk McKusick 			 * been written, there is no need to send a BIO_DELETE
7917e038bc2SKirk McKusick 			 * for them when they are freed. The gain from avoiding
7927e038bc2SKirk McKusick 			 * the TRIMs for the common case of unwritten blocks
7937e038bc2SKirk McKusick 			 * far exceeds the cost of the write amplification for
7947e038bc2SKirk McKusick 			 * the uncommon case of failing to send a TRIM for the
7957e038bc2SKirk McKusick 			 * blocks that had been written.
7967e038bc2SKirk McKusick 			 */
797e1db6897SKonstantin Belousov 			ffs_blkfree(ump, fs, ump->um_devvp,
7987e038bc2SKirk McKusick 			    dbtofsb(fs, bp->b_blkno),
7997e038bc2SKirk McKusick 			    fs->fs_bsize, ip->i_number, vp->v_type, NULL,
8007e038bc2SKirk McKusick 			    (bp->b_flags & B_DELWRI) != 0 ?
8017e038bc2SKirk McKusick 			    NOTRIM_KEY : SINGLETON_KEY);
8027e038bc2SKirk McKusick 		bp->b_blkno = fsbtodb(fs, blkno);
8031102b89bSDavid E. O'Brien #ifdef INVARIANTS
80467702352SKirk McKusick 		if (!ffs_checkfreeblk(ip, dbtofsb(fs, bp->b_blkno),
80567702352SKirk McKusick 		    fs->fs_bsize))
806996c772fSJohn Dyson 			panic("ffs_reallocblks: unallocated block 3");
807740e3a15SSheldon Hearn #endif
808af6aeacbSKirk McKusick #ifdef DIAGNOSTIC
809996c772fSJohn Dyson 		if (prtrealloc)
810996c772fSJohn Dyson 			printf(" %d,", blkno);
811996c772fSJohn Dyson #endif
812df8bae1dSRodney W. Grimes 	}
813af6aeacbSKirk McKusick #ifdef DIAGNOSTIC
814996c772fSJohn Dyson 	if (prtrealloc) {
815996c772fSJohn Dyson 		prtrealloc--;
816996c772fSJohn Dyson 		printf("\n");
817996c772fSJohn Dyson 	}
818996c772fSJohn Dyson #endif
819df8bae1dSRodney W. Grimes 	return (0);
820df8bae1dSRodney W. Grimes 
821df8bae1dSRodney W. Grimes fail:
822df8bae1dSRodney W. Grimes 	if (ssize < len)
823df8bae1dSRodney W. Grimes 		brelse(ebp);
8241c85e6a3SKirk McKusick 	if (sbap != &ip->i_din1->di_db[0])
8251c85e6a3SKirk McKusick 		brelse(sbp);
8261c85e6a3SKirk McKusick 	return (ENOSPC);
8271c85e6a3SKirk McKusick }
8281c85e6a3SKirk McKusick 
8291c85e6a3SKirk McKusick static int
ffs_reallocblks_ufs2(struct vop_reallocblks_args * ap)830064e6b43SKirk McKusick ffs_reallocblks_ufs2(
8311c85e6a3SKirk McKusick 	struct vop_reallocblks_args /* {
8321c85e6a3SKirk McKusick 		struct vnode *a_vp;
8331c85e6a3SKirk McKusick 		struct cluster_save *a_buflist;
834064e6b43SKirk McKusick 	} */ *ap)
8351c85e6a3SKirk McKusick {
8361c85e6a3SKirk McKusick 	struct fs *fs;
8371c85e6a3SKirk McKusick 	struct inode *ip;
8381c85e6a3SKirk McKusick 	struct vnode *vp;
8397e038bc2SKirk McKusick 	struct buf *sbp, *ebp, *bp;
840abafa4dbSPedro F. Giffuni 	ufs2_daddr_t *bap, *sbap, *ebap;
8411c85e6a3SKirk McKusick 	struct cluster_save *buflist;
8428e37fbadSJeff Roberson 	struct ufsmount *ump;
8431c85e6a3SKirk McKusick 	ufs_lbn_t start_lbn, end_lbn;
8441c85e6a3SKirk McKusick 	ufs2_daddr_t soff, newblk, blkno, pref;
8451dc349abSEd Maste 	struct indir start_ap[UFS_NIADDR + 1], end_ap[UFS_NIADDR + 1], *idp;
84674a87c38SKirk McKusick 	int i, cg, len, start_lvl, end_lvl, ssize;
8471c85e6a3SKirk McKusick 
8481c85e6a3SKirk McKusick 	vp = ap->a_vp;
8491c85e6a3SKirk McKusick 	ip = VTOI(vp);
850e1db6897SKonstantin Belousov 	ump = ITOUMP(ip);
851e1db6897SKonstantin Belousov 	fs = ump->um_fs;
85228702816SKirk McKusick 	/*
853be1fd823SKirk McKusick 	 * If we are not tracking block clusters or if we have less than 4%
85428702816SKirk McKusick 	 * free blocks left, then do not attempt to cluster. Running with
85528702816SKirk McKusick 	 * less than 5% free block reserve is not recommended and those that
85628702816SKirk McKusick 	 * choose to do so do not expect to have good file layout.
85728702816SKirk McKusick 	 */
858be1fd823SKirk McKusick 	if (fs->fs_contigsumsize <= 0 || freespace(fs, 4) < 0)
8591c85e6a3SKirk McKusick 		return (ENOSPC);
8601c85e6a3SKirk McKusick 	buflist = ap->a_buflist;
8611c85e6a3SKirk McKusick 	len = buflist->bs_nchildren;
8621c85e6a3SKirk McKusick 	start_lbn = buflist->bs_children[0]->b_lblkno;
8631c85e6a3SKirk McKusick 	end_lbn = start_lbn + len - 1;
8641102b89bSDavid E. O'Brien #ifdef INVARIANTS
8651c85e6a3SKirk McKusick 	for (i = 0; i < len; i++)
86667702352SKirk McKusick 		if (!ffs_checkfreeblk(ip,
8671c85e6a3SKirk McKusick 		   dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
8681c85e6a3SKirk McKusick 			panic("ffs_reallocblks: unallocated block 1");
8691c85e6a3SKirk McKusick 	for (i = 1; i < len; i++)
8701c85e6a3SKirk McKusick 		if (buflist->bs_children[i]->b_lblkno != start_lbn + i)
8711c85e6a3SKirk McKusick 			panic("ffs_reallocblks: non-logical cluster");
8721c85e6a3SKirk McKusick 	blkno = buflist->bs_children[0]->b_blkno;
8731c85e6a3SKirk McKusick 	ssize = fsbtodb(fs, fs->fs_frag);
8741c85e6a3SKirk McKusick 	for (i = 1; i < len - 1; i++)
8751c85e6a3SKirk McKusick 		if (buflist->bs_children[i]->b_blkno != blkno + (i * ssize))
8761c85e6a3SKirk McKusick 			panic("ffs_reallocblks: non-physical cluster %d", i);
8771c85e6a3SKirk McKusick #endif
8781c85e6a3SKirk McKusick 	/*
879aa7ddc85SKirk McKusick 	 * If the cluster crosses the boundary for the first indirect
880aa7ddc85SKirk McKusick 	 * block, do not move anything in it. Indirect blocks are
881aa7ddc85SKirk McKusick 	 * usually initially laid out in a position between the data
882aa7ddc85SKirk McKusick 	 * blocks. Block reallocation would usually destroy locality by
883aa7ddc85SKirk McKusick 	 * moving the indirect block out of the way to make room for
884aa7ddc85SKirk McKusick 	 * data blocks if we didn't compensate here. We should also do
885aa7ddc85SKirk McKusick 	 * this for other indirect block boundaries, but it is only
886aa7ddc85SKirk McKusick 	 * important for the first one.
887aa7ddc85SKirk McKusick 	 */
8881dc349abSEd Maste 	if (start_lbn < UFS_NDADDR && end_lbn >= UFS_NDADDR)
889aa7ddc85SKirk McKusick 		return (ENOSPC);
890aa7ddc85SKirk McKusick 	/*
8911c85e6a3SKirk McKusick 	 * If the latest allocation is in a new cylinder group, assume that
8921c85e6a3SKirk McKusick 	 * the filesystem has decided to move and do not force it back to
8931c85e6a3SKirk McKusick 	 * the previous cylinder group.
8941c85e6a3SKirk McKusick 	 */
8951c85e6a3SKirk McKusick 	if (dtog(fs, dbtofsb(fs, buflist->bs_children[0]->b_blkno)) !=
8961c85e6a3SKirk McKusick 	    dtog(fs, dbtofsb(fs, buflist->bs_children[len - 1]->b_blkno)))
8971c85e6a3SKirk McKusick 		return (ENOSPC);
8981c85e6a3SKirk McKusick 	if (ufs_getlbns(vp, start_lbn, start_ap, &start_lvl) ||
8991c85e6a3SKirk McKusick 	    ufs_getlbns(vp, end_lbn, end_ap, &end_lvl))
9001c85e6a3SKirk McKusick 		return (ENOSPC);
9011c85e6a3SKirk McKusick 	/*
9021c85e6a3SKirk McKusick 	 * Get the starting offset and block map for the first block.
9031c85e6a3SKirk McKusick 	 */
9041c85e6a3SKirk McKusick 	if (start_lvl == 0) {
9051c85e6a3SKirk McKusick 		sbap = &ip->i_din2->di_db[0];
9061c85e6a3SKirk McKusick 		soff = start_lbn;
9071c85e6a3SKirk McKusick 	} else {
9081c85e6a3SKirk McKusick 		idp = &start_ap[start_lvl - 1];
9091c85e6a3SKirk McKusick 		if (bread(vp, idp->in_lbn, (int)fs->fs_bsize, NOCRED, &sbp)) {
9101c85e6a3SKirk McKusick 			brelse(sbp);
9111c85e6a3SKirk McKusick 			return (ENOSPC);
9121c85e6a3SKirk McKusick 		}
9131c85e6a3SKirk McKusick 		sbap = (ufs2_daddr_t *)sbp->b_data;
9141c85e6a3SKirk McKusick 		soff = idp->in_off;
9151c85e6a3SKirk McKusick 	}
9161c85e6a3SKirk McKusick 	/*
9171c85e6a3SKirk McKusick 	 * If the block range spans two block maps, get the second map.
9181c85e6a3SKirk McKusick 	 */
919abafa4dbSPedro F. Giffuni 	ebap = NULL;
9201c85e6a3SKirk McKusick 	if (end_lvl == 0 || (idp = &end_ap[end_lvl - 1])->in_off + 1 >= len) {
9211c85e6a3SKirk McKusick 		ssize = len;
9221c85e6a3SKirk McKusick 	} else {
9231102b89bSDavid E. O'Brien #ifdef INVARIANTS
924d9e6294eSKen Smith 		if (start_lvl > 0 &&
925d9e6294eSKen Smith 		    start_ap[start_lvl - 1].in_lbn == idp->in_lbn)
9261c85e6a3SKirk McKusick 			panic("ffs_reallocblk: start == end");
9271c85e6a3SKirk McKusick #endif
9281c85e6a3SKirk McKusick 		ssize = len - (idp->in_off + 1);
9291c85e6a3SKirk McKusick 		if (bread(vp, idp->in_lbn, (int)fs->fs_bsize, NOCRED, &ebp))
9301c85e6a3SKirk McKusick 			goto fail;
9311c85e6a3SKirk McKusick 		ebap = (ufs2_daddr_t *)ebp->b_data;
9321c85e6a3SKirk McKusick 	}
9331c85e6a3SKirk McKusick 	/*
93474a87c38SKirk McKusick 	 * Find the preferred location for the cluster. If we have not
93574a87c38SKirk McKusick 	 * previously failed at this endeavor, then follow our standard
93674a87c38SKirk McKusick 	 * preference calculation. If we have failed at it, then pick up
93774a87c38SKirk McKusick 	 * where we last ended our search.
9388e37fbadSJeff Roberson 	 */
9398e37fbadSJeff Roberson 	UFS_LOCK(ump);
94074a87c38SKirk McKusick 	if (ip->i_nextclustercg == -1)
9418e37fbadSJeff Roberson 		pref = ffs_blkpref_ufs2(ip, start_lbn, soff, sbap);
94274a87c38SKirk McKusick 	else
94374a87c38SKirk McKusick 		pref = cgdata(fs, ip->i_nextclustercg);
9448e37fbadSJeff Roberson 	/*
9451c85e6a3SKirk McKusick 	 * Search the block map looking for an allocation of the desired size.
94674a87c38SKirk McKusick 	 * To avoid wasting too much time, we limit the number of cylinder
94774a87c38SKirk McKusick 	 * groups that we will search.
9481c85e6a3SKirk McKusick 	 */
94974a87c38SKirk McKusick 	cg = dtog(fs, pref);
950dc37121dSKonstantin Belousov 	MPASS(cg < fs->fs_ncg);
95174a87c38SKirk McKusick 	for (i = min(maxclustersearch, fs->fs_ncg); i > 0; i--) {
95274a87c38SKirk McKusick 		if ((newblk = ffs_clusteralloc(ip, cg, pref, len)) != 0)
95374a87c38SKirk McKusick 			break;
95474a87c38SKirk McKusick 		cg += 1;
95574a87c38SKirk McKusick 		if (cg >= fs->fs_ncg)
95674a87c38SKirk McKusick 			cg = 0;
95774a87c38SKirk McKusick 	}
95874a87c38SKirk McKusick 	/*
95974a87c38SKirk McKusick 	 * If we have failed in our search, record where we gave up for
96074a87c38SKirk McKusick 	 * next time. Otherwise, fall back to our usual search citerion.
96174a87c38SKirk McKusick 	 */
96274a87c38SKirk McKusick 	if (newblk == 0) {
96374a87c38SKirk McKusick 		ip->i_nextclustercg = cg;
9648e37fbadSJeff Roberson 		UFS_UNLOCK(ump);
9651c85e6a3SKirk McKusick 		goto fail;
9668e37fbadSJeff Roberson 	}
96774a87c38SKirk McKusick 	ip->i_nextclustercg = -1;
9681c85e6a3SKirk McKusick 	/*
9691c85e6a3SKirk McKusick 	 * We have found a new contiguous block.
9701c85e6a3SKirk McKusick 	 *
9711c85e6a3SKirk McKusick 	 * First we have to replace the old block pointers with the new
9721c85e6a3SKirk McKusick 	 * block pointers in the inode and indirect blocks associated
9731c85e6a3SKirk McKusick 	 * with the file.
9741c85e6a3SKirk McKusick 	 */
975af6aeacbSKirk McKusick #ifdef DIAGNOSTIC
9761c85e6a3SKirk McKusick 	if (prtrealloc)
977dde58752SGleb Kurtsou 		printf("realloc: ino %ju, lbns %jd-%jd\n\told:", (uintmax_t)ip->i_number,
9781c85e6a3SKirk McKusick 		    (intmax_t)start_lbn, (intmax_t)end_lbn);
9791c85e6a3SKirk McKusick #endif
9801c85e6a3SKirk McKusick 	blkno = newblk;
9811c85e6a3SKirk McKusick 	for (bap = &sbap[soff], i = 0; i < len; i++, blkno += fs->fs_frag) {
9821c85e6a3SKirk McKusick 		if (i == ssize) {
9831c85e6a3SKirk McKusick 			bap = ebap;
9841c85e6a3SKirk McKusick 			soff = -i;
9851c85e6a3SKirk McKusick 		}
9861102b89bSDavid E. O'Brien #ifdef INVARIANTS
98767702352SKirk McKusick 		if (!ffs_checkfreeblk(ip,
9881c85e6a3SKirk McKusick 		   dbtofsb(fs, buflist->bs_children[i]->b_blkno), fs->fs_bsize))
9891c85e6a3SKirk McKusick 			panic("ffs_reallocblks: unallocated block 2");
9901c85e6a3SKirk McKusick 		if (dbtofsb(fs, buflist->bs_children[i]->b_blkno) != *bap)
9911c85e6a3SKirk McKusick 			panic("ffs_reallocblks: alloc mismatch");
9921c85e6a3SKirk McKusick #endif
993af6aeacbSKirk McKusick #ifdef DIAGNOSTIC
9941c85e6a3SKirk McKusick 		if (prtrealloc)
99547a56126SDavid E. O'Brien 			printf(" %jd,", (intmax_t)*bap);
9961c85e6a3SKirk McKusick #endif
9971c85e6a3SKirk McKusick 		if (DOINGSOFTDEP(vp)) {
9981c85e6a3SKirk McKusick 			if (sbap == &ip->i_din2->di_db[0] && i < ssize)
9991c85e6a3SKirk McKusick 				softdep_setup_allocdirect(ip, start_lbn + i,
10001c85e6a3SKirk McKusick 				    blkno, *bap, fs->fs_bsize, fs->fs_bsize,
10011c85e6a3SKirk McKusick 				    buflist->bs_children[i]);
10021c85e6a3SKirk McKusick 			else
10031c85e6a3SKirk McKusick 				softdep_setup_allocindir_page(ip, start_lbn + i,
10041c85e6a3SKirk McKusick 				    i < ssize ? sbp : ebp, soff + i, blkno,
10051c85e6a3SKirk McKusick 				    *bap, buflist->bs_children[i]);
10061c85e6a3SKirk McKusick 		}
10071c85e6a3SKirk McKusick 		*bap++ = blkno;
10081c85e6a3SKirk McKusick 	}
10091c85e6a3SKirk McKusick 	/*
10101c85e6a3SKirk McKusick 	 * Next we must write out the modified inode and indirect blocks.
10111c85e6a3SKirk McKusick 	 * For strict correctness, the writes should be synchronous since
10121c85e6a3SKirk McKusick 	 * the old block values may have been written to disk. In practise
10131c85e6a3SKirk McKusick 	 * they are almost never written, but if we are concerned about
10141c85e6a3SKirk McKusick 	 * strict correctness, the `doasyncfree' flag should be set to zero.
10151c85e6a3SKirk McKusick 	 *
10161c85e6a3SKirk McKusick 	 * The test on `doasyncfree' should be changed to test a flag
10171c85e6a3SKirk McKusick 	 * that shows whether the associated buffers and inodes have
10181c85e6a3SKirk McKusick 	 * been written. The flag should be set when the cluster is
10191c85e6a3SKirk McKusick 	 * started and cleared whenever the buffer or inode is flushed.
10201c85e6a3SKirk McKusick 	 * We can then check below to see if it is set, and do the
10211c85e6a3SKirk McKusick 	 * synchronous write only when it has been cleared.
10221c85e6a3SKirk McKusick 	 */
10231c85e6a3SKirk McKusick 	if (sbap != &ip->i_din2->di_db[0]) {
10241c85e6a3SKirk McKusick 		if (doasyncfree)
10251c85e6a3SKirk McKusick 			bdwrite(sbp);
10261c85e6a3SKirk McKusick 		else
10271c85e6a3SKirk McKusick 			bwrite(sbp);
10281c85e6a3SKirk McKusick 	} else {
1029ac4ec141SMateusz Guzik 		UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_UPDATE);
10301c85e6a3SKirk McKusick 		if (!doasyncfree)
1031efd6d980SPoul-Henning Kamp 			ffs_update(vp, 1);
10321c85e6a3SKirk McKusick 	}
10331c85e6a3SKirk McKusick 	if (ssize < len) {
10341c85e6a3SKirk McKusick 		if (doasyncfree)
10351c85e6a3SKirk McKusick 			bdwrite(ebp);
10361c85e6a3SKirk McKusick 		else
10371c85e6a3SKirk McKusick 			bwrite(ebp);
10381c85e6a3SKirk McKusick 	}
10391c85e6a3SKirk McKusick 	/*
10401c85e6a3SKirk McKusick 	 * Last, free the old blocks and assign the new blocks to the buffers.
10411c85e6a3SKirk McKusick 	 */
1042af6aeacbSKirk McKusick #ifdef DIAGNOSTIC
10431c85e6a3SKirk McKusick 	if (prtrealloc)
10441c85e6a3SKirk McKusick 		printf("\n\tnew:");
10451c85e6a3SKirk McKusick #endif
10461c85e6a3SKirk McKusick 	for (blkno = newblk, i = 0; i < len; i++, blkno += fs->fs_frag) {
10477e038bc2SKirk McKusick 		bp = buflist->bs_children[i];
10481c85e6a3SKirk McKusick 		if (!DOINGSOFTDEP(vp))
10497e038bc2SKirk McKusick 			/*
10507e038bc2SKirk McKusick 			 * The usual case is that a set of N-contiguous blocks
10517e038bc2SKirk McKusick 			 * that was just allocated has been replaced with a
10527e038bc2SKirk McKusick 			 * set of N+1-contiguous blocks. If they are marked as
10537e038bc2SKirk McKusick 			 * B_DELWRI, the current contents have not been written
10547e038bc2SKirk McKusick 			 * to disk. It is possible that the blocks were written
10557e038bc2SKirk McKusick 			 * earlier, but very uncommon. If the blocks have never
10567e038bc2SKirk McKusick 			 * been written, there is no need to send a BIO_DELETE
10577e038bc2SKirk McKusick 			 * for them when they are freed. The gain from avoiding
10587e038bc2SKirk McKusick 			 * the TRIMs for the common case of unwritten blocks
10597e038bc2SKirk McKusick 			 * far exceeds the cost of the write amplification for
10607e038bc2SKirk McKusick 			 * the uncommon case of failing to send a TRIM for the
10617e038bc2SKirk McKusick 			 * blocks that had been written.
10627e038bc2SKirk McKusick 			 */
1063e1db6897SKonstantin Belousov 			ffs_blkfree(ump, fs, ump->um_devvp,
10647e038bc2SKirk McKusick 			    dbtofsb(fs, bp->b_blkno),
10657e038bc2SKirk McKusick 			    fs->fs_bsize, ip->i_number, vp->v_type, NULL,
10667e038bc2SKirk McKusick 			    (bp->b_flags & B_DELWRI) != 0 ?
10677e038bc2SKirk McKusick 			    NOTRIM_KEY : SINGLETON_KEY);
10687e038bc2SKirk McKusick 		bp->b_blkno = fsbtodb(fs, blkno);
10691102b89bSDavid E. O'Brien #ifdef INVARIANTS
107067702352SKirk McKusick 		if (!ffs_checkfreeblk(ip, dbtofsb(fs, bp->b_blkno),
107167702352SKirk McKusick 		    fs->fs_bsize))
10721c85e6a3SKirk McKusick 			panic("ffs_reallocblks: unallocated block 3");
10731c85e6a3SKirk McKusick #endif
1074af6aeacbSKirk McKusick #ifdef DIAGNOSTIC
10751c85e6a3SKirk McKusick 		if (prtrealloc)
10762daf9dc8SBruce Evans 			printf(" %jd,", (intmax_t)blkno);
10771c85e6a3SKirk McKusick #endif
10781c85e6a3SKirk McKusick 	}
1079af6aeacbSKirk McKusick #ifdef DIAGNOSTIC
10801c85e6a3SKirk McKusick 	if (prtrealloc) {
10811c85e6a3SKirk McKusick 		prtrealloc--;
10821c85e6a3SKirk McKusick 		printf("\n");
10831c85e6a3SKirk McKusick 	}
10841c85e6a3SKirk McKusick #endif
10851c85e6a3SKirk McKusick 	return (0);
10861c85e6a3SKirk McKusick 
10871c85e6a3SKirk McKusick fail:
10881c85e6a3SKirk McKusick 	if (ssize < len)
10891c85e6a3SKirk McKusick 		brelse(ebp);
10901c85e6a3SKirk McKusick 	if (sbap != &ip->i_din2->di_db[0])
1091df8bae1dSRodney W. Grimes 		brelse(sbp);
1092df8bae1dSRodney W. Grimes 	return (ENOSPC);
1093df8bae1dSRodney W. Grimes }
1094df8bae1dSRodney W. Grimes 
1095df8bae1dSRodney W. Grimes /*
1096df8bae1dSRodney W. Grimes  * Allocate an inode in the filesystem.
1097df8bae1dSRodney W. Grimes  *
1098df8bae1dSRodney W. Grimes  * If allocating a directory, use ffs_dirpref to select the inode.
1099df8bae1dSRodney W. Grimes  * If allocating in a directory, the following hierarchy is followed:
1100df8bae1dSRodney W. Grimes  *   1) allocate the preferred inode.
1101df8bae1dSRodney W. Grimes  *   2) allocate an inode in the same cylinder group.
11022733b242SGordon Bergling  *   3) quadratically rehash into other cylinder groups, until an
1103df8bae1dSRodney W. Grimes  *      available inode is located.
11046192525bSMike Pritchard  * If no inode preference is given the following hierarchy is used
1105df8bae1dSRodney W. Grimes  * to allocate an inode:
1106df8bae1dSRodney W. Grimes  *   1) allocate an inode in cylinder group 0.
11072733b242SGordon Bergling  *   2) quadratically rehash into other cylinder groups, until an
1108df8bae1dSRodney W. Grimes  *      available inode is located.
1109df8bae1dSRodney W. Grimes  */
111026f9a767SRodney W. Grimes int
ffs_valloc(struct vnode * pvp,int mode,struct ucred * cred,struct vnode ** vpp)1111064e6b43SKirk McKusick ffs_valloc(struct vnode *pvp,
1112064e6b43SKirk McKusick 	int mode,
1113064e6b43SKirk McKusick 	struct ucred *cred,
1114064e6b43SKirk McKusick 	struct vnode **vpp)
1115df8bae1dSRodney W. Grimes {
111605f4ff5dSPoul-Henning Kamp 	struct inode *pip;
111705f4ff5dSPoul-Henning Kamp 	struct fs *fs;
111805f4ff5dSPoul-Henning Kamp 	struct inode *ip;
11191c85e6a3SKirk McKusick 	struct timespec ts;
11208e37fbadSJeff Roberson 	struct ufsmount *ump;
1121df8bae1dSRodney W. Grimes 	ino_t ino, ipref;
1122831b1ff7SKirk McKusick 	uint64_t cg;
1123d79ff54bSChuck Silvers 	int error, reclaimed;
1124df8bae1dSRodney W. Grimes 
1125cec0f20cSPoul-Henning Kamp 	*vpp = NULL;
1126df8bae1dSRodney W. Grimes 	pip = VTOI(pvp);
1127e1db6897SKonstantin Belousov 	ump = ITOUMP(pip);
1128e1db6897SKonstantin Belousov 	fs = ump->um_fs;
11298e37fbadSJeff Roberson 
11308e37fbadSJeff Roberson 	UFS_LOCK(ump);
11310a809056SKirk McKusick 	reclaimed = 0;
11320a809056SKirk McKusick retry:
1133df8bae1dSRodney W. Grimes 	if (fs->fs_cstotal.cs_nifree == 0)
1134df8bae1dSRodney W. Grimes 		goto noinodes;
1135df8bae1dSRodney W. Grimes 
1136d8ba45e2SEd Maste 	if ((mode & IFMT) == IFDIR)
1137a61ab64aSKirk McKusick 		ipref = ffs_dirpref(pip);
1138df8bae1dSRodney W. Grimes 	else
1139df8bae1dSRodney W. Grimes 		ipref = pip->i_number;
1140c021e447SKirk McKusick 	if (ipref >= fs->fs_ncg * fs->fs_ipg)
1141df8bae1dSRodney W. Grimes 		ipref = 0;
1142df8bae1dSRodney W. Grimes 	cg = ino_to_cg(fs, ipref);
1143a61ab64aSKirk McKusick 	/*
1144a61ab64aSKirk McKusick 	 * Track number of dirs created one after another
1145a61ab64aSKirk McKusick 	 * in a same cg without intervening by files.
1146a61ab64aSKirk McKusick 	 */
1147d8ba45e2SEd Maste 	if ((mode & IFMT) == IFDIR) {
1148a61ab64aSKirk McKusick 		if (fs->fs_contigdirs[cg] < 255)
1149a61ab64aSKirk McKusick 			fs->fs_contigdirs[cg]++;
1150a61ab64aSKirk McKusick 	} else {
1151a61ab64aSKirk McKusick 		if (fs->fs_contigdirs[cg] > 0)
1152a61ab64aSKirk McKusick 			fs->fs_contigdirs[cg]--;
1153a61ab64aSKirk McKusick 	}
1154113db2ddSJeff Roberson 	ino = (ino_t)ffs_hashalloc(pip, cg, ipref, mode, 0,
1155dbe525ffSPeter Wemm 					(allocfcn_t *)ffs_nodealloccg);
1156df8bae1dSRodney W. Grimes 	if (ino == 0)
1157df8bae1dSRodney W. Grimes 		goto noinodes;
115816040222SKonstantin Belousov 	/*
115916040222SKonstantin Belousov 	 * Get rid of the cached old vnode, force allocation of a new vnode
1160d79ff54bSChuck Silvers 	 * for this inode. If this fails, release the allocated ino and
1161d79ff54bSChuck Silvers 	 * return the error.
116216040222SKonstantin Belousov 	 */
1163d79ff54bSChuck Silvers 	if ((error = ffs_vgetf(pvp->v_mount, ino, LK_EXCLUSIVE, vpp,
11646b9d4fbbSKirk McKusick 	    FFSV_FORCEINSMQ | FFSV_REPLACE | FFSV_NEWINODE)) != 0) {
1165efd6d980SPoul-Henning Kamp 		ffs_vfree(pvp, ino, mode);
1166df8bae1dSRodney W. Grimes 		return (error);
1167df8bae1dSRodney W. Grimes 	}
1168d79ff54bSChuck Silvers 	/*
1169d79ff54bSChuck Silvers 	 * We got an inode, so check mode and panic if it is already allocated.
1170d79ff54bSChuck Silvers 	 */
1171cec0f20cSPoul-Henning Kamp 	ip = VTOI(*vpp);
1172df8bae1dSRodney W. Grimes 	if (ip->i_mode) {
1173dde58752SGleb Kurtsou 		printf("mode = 0%o, inum = %ju, fs = %s\n",
1174dde58752SGleb Kurtsou 		    ip->i_mode, (uintmax_t)ip->i_number, fs->fs_fsmnt);
1175df8bae1dSRodney W. Grimes 		panic("ffs_valloc: dup alloc");
1176df8bae1dSRodney W. Grimes 	}
11771c85e6a3SKirk McKusick 	if (DIP(ip, i_blocks) && (fs->fs_flags & FS_UNCLEAN) == 0) {  /* XXX */
1178831b1ff7SKirk McKusick 		printf("free inode %s/%ju had %ld blocks\n",
1179831b1ff7SKirk McKusick 		    fs->fs_fsmnt, (intmax_t)ino, (long)DIP(ip, i_blocks));
1180b403319bSAlexander Kabaev 		DIP_SET(ip, i_blocks, 0);
1181df8bae1dSRodney W. Grimes 	}
1182df8bae1dSRodney W. Grimes 	ip->i_flags = 0;
1183b403319bSAlexander Kabaev 	DIP_SET(ip, i_flags, 0);
1184fe5e6e2cSKirk McKusick 	if ((mode & IFMT) == IFDIR)
1185fe5e6e2cSKirk McKusick 		DIP_SET(ip, i_dirdepth, DIP(pip, i_dirdepth) + 1);
1186df8bae1dSRodney W. Grimes 	/*
1187df8bae1dSRodney W. Grimes 	 * Set up a new generation number for this inode.
1188df8bae1dSRodney W. Grimes 	 */
118957d2ac2fSKevin Lo 	while (ip->i_gen == 0 || ++ip->i_gen == 0)
119057d2ac2fSKevin Lo 		ip->i_gen = arc4random();
1191b403319bSAlexander Kabaev 	DIP_SET(ip, i_gen, ip->i_gen);
11921c85e6a3SKirk McKusick 	if (fs->fs_magic == FS_UFS2_MAGIC) {
11931c85e6a3SKirk McKusick 		vfs_timestamp(&ts);
1194faab4e27SKirk McKusick 		ip->i_din2->di_birthtime = ts.tv_sec;
1195faab4e27SKirk McKusick 		ip->i_din2->di_birthnsec = ts.tv_nsec;
11961c85e6a3SKirk McKusick 	}
1197448434c3SDon Lewis 	ip->i_flag = 0;
1198d9ca1af7SKonstantin Belousov 	(*vpp)->v_vflag = 0;
1199c73e9e9cSTor Egge 	(*vpp)->v_type = VNON;
1200e1db6897SKonstantin Belousov 	if (fs->fs_magic == FS_UFS2_MAGIC) {
1201c73e9e9cSTor Egge 		(*vpp)->v_op = &ffs_vnodeops2;
1202ac4ec141SMateusz Guzik 		UFS_INODE_SET_FLAG(ip, IN_UFS2);
1203e1db6897SKonstantin Belousov 	} else {
1204c73e9e9cSTor Egge 		(*vpp)->v_op = &ffs_vnodeops1;
1205e1db6897SKonstantin Belousov 	}
1206df8bae1dSRodney W. Grimes 	return (0);
1207df8bae1dSRodney W. Grimes noinodes:
12081508294bSKirk McKusick 	if (reclaimed == 0) {
12090a809056SKirk McKusick 		reclaimed = 1;
12104c821a39SKirk McKusick 		softdep_request_cleanup(fs, pvp, cred, FLUSH_INODES_WAIT);
12110a809056SKirk McKusick 		goto retry;
12120a809056SKirk McKusick 	}
1213d79ff54bSChuck Silvers 	if (ffs_fsfail_cleanup_locked(ump, 0)) {
1214d79ff54bSChuck Silvers 		UFS_UNLOCK(ump);
1215d79ff54bSChuck Silvers 		return (ENXIO);
1216d79ff54bSChuck Silvers 	}
12171fd136ecSKirk McKusick 	if (ppsratecheck(&ump->um_last_fullmsg, &ump->um_secs_fullmsg, 1)) {
12188e37fbadSJeff Roberson 		UFS_UNLOCK(ump);
1219c9f96392SKirk McKusick 		ffs_fserr(fs, pip->i_number, "out of inodes");
1220e1cef627SPaul Saab 		uprintf("\n%s: create/symlink failed, no inodes free\n",
1221e1cef627SPaul Saab 		    fs->fs_fsmnt);
12221fd136ecSKirk McKusick 	} else {
12231fd136ecSKirk McKusick 		UFS_UNLOCK(ump);
1224e1cef627SPaul Saab 	}
1225df8bae1dSRodney W. Grimes 	return (ENOSPC);
1226df8bae1dSRodney W. Grimes }
1227df8bae1dSRodney W. Grimes 
1228df8bae1dSRodney W. Grimes /*
1229a61ab64aSKirk McKusick  * Find a cylinder group to place a directory.
1230df8bae1dSRodney W. Grimes  *
1231a61ab64aSKirk McKusick  * The policy implemented by this algorithm is to allocate a
1232a61ab64aSKirk McKusick  * directory inode in the same cylinder group as its parent
1233a61ab64aSKirk McKusick  * directory, but also to reserve space for its files inodes
1234a61ab64aSKirk McKusick  * and data. Restrict the number of directories which may be
1235a61ab64aSKirk McKusick  * allocated one after another in the same cylinder group
1236a61ab64aSKirk McKusick  * without intervening allocation of files.
1237a61ab64aSKirk McKusick  *
1238a61ab64aSKirk McKusick  * If we allocate a first level directory then force allocation
1239a61ab64aSKirk McKusick  * in another cylinder group.
1240df8bae1dSRodney W. Grimes  */
1241df8bae1dSRodney W. Grimes static ino_t
ffs_dirpref(struct inode * pip)1242064e6b43SKirk McKusick ffs_dirpref(struct inode *pip)
1243df8bae1dSRodney W. Grimes {
124405f4ff5dSPoul-Henning Kamp 	struct fs *fs;
1245fe5e6e2cSKirk McKusick 	int cg, prefcg, curcg, dirsize, cgsize;
1246fe5e6e2cSKirk McKusick 	int depth, range, start, end, numdirs, power, numerator, denominator;
1247831b1ff7SKirk McKusick 	uint64_t avgifree, avgbfree, avgndir, curdirsize;
1248831b1ff7SKirk McKusick 	uint64_t minifree, minbfree, maxndir;
1249831b1ff7SKirk McKusick 	uint64_t maxcontigdirs;
1250a61ab64aSKirk McKusick 
1251e1db6897SKonstantin Belousov 	mtx_assert(UFS_MTX(ITOUMP(pip)), MA_OWNED);
1252e1db6897SKonstantin Belousov 	fs = ITOFS(pip);
1253df8bae1dSRodney W. Grimes 
1254df8bae1dSRodney W. Grimes 	avgifree = fs->fs_cstotal.cs_nifree / fs->fs_ncg;
1255a61ab64aSKirk McKusick 	avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
1256a61ab64aSKirk McKusick 	avgndir = fs->fs_cstotal.cs_ndir / fs->fs_ncg;
1257a61ab64aSKirk McKusick 
1258a61ab64aSKirk McKusick 	/*
1259fe5e6e2cSKirk McKusick 	 * Select a preferred cylinder group to place a new directory.
1260fe5e6e2cSKirk McKusick 	 * If we are near the root of the filesystem we aim to spread
1261fe5e6e2cSKirk McKusick 	 * them out as much as possible. As we descend deeper from the
1262fe5e6e2cSKirk McKusick 	 * root we cluster them closer together around their parent as
1263fe5e6e2cSKirk McKusick 	 * we expect them to be more closely interactive. Higher-level
1264fe5e6e2cSKirk McKusick 	 * directories like usr/src/sys and usr/src/bin should be
1265fe5e6e2cSKirk McKusick 	 * separated while the directories in these areas are more
1266fe5e6e2cSKirk McKusick 	 * likely to be accessed together so should be closer.
1267fe5e6e2cSKirk McKusick 	 *
1268fe5e6e2cSKirk McKusick 	 * We pick a range of cylinder groups around the cylinder group
1269fe5e6e2cSKirk McKusick 	 * of the directory in which we are being created. The size of
1270fe5e6e2cSKirk McKusick 	 * the range for our search is based on our depth from the root
1271fe5e6e2cSKirk McKusick 	 * of our filesystem. We then probe that range based on how many
1272fe5e6e2cSKirk McKusick 	 * directories are already present. The first new directory is at
1273fe5e6e2cSKirk McKusick 	 * 1/2 (middle) of the range; the second is in the first 1/4 of the
1274fe5e6e2cSKirk McKusick 	 * range, then at 3/4, 1/8, 3/8, 5/8, 7/8, 1/16, 3/16, 5/16, etc.
1275a61ab64aSKirk McKusick 	 */
1276fe5e6e2cSKirk McKusick 	depth = DIP(pip, i_dirdepth);
1277fe5e6e2cSKirk McKusick 	range = fs->fs_ncg / (1 << depth);
1278fe5e6e2cSKirk McKusick 	curcg = ino_to_cg(fs, pip->i_number);
1279fe5e6e2cSKirk McKusick 	start = curcg - (range / 2);
1280fe5e6e2cSKirk McKusick 	if (start < 0)
1281fe5e6e2cSKirk McKusick 		start += fs->fs_ncg;
1282fe5e6e2cSKirk McKusick 	end = curcg + (range / 2);
1283fe5e6e2cSKirk McKusick 	if (end >= fs->fs_ncg)
1284fe5e6e2cSKirk McKusick 		end -= fs->fs_ncg;
1285fe5e6e2cSKirk McKusick 	numdirs = pip->i_effnlink - 1;
1286fe5e6e2cSKirk McKusick 	power = fls(numdirs);
1287fe5e6e2cSKirk McKusick 	numerator = (numdirs & ~(1 << (power - 1))) * 2 + 1;
1288fe5e6e2cSKirk McKusick 	denominator = 1 << power;
1289fe5e6e2cSKirk McKusick 	prefcg = (curcg - (range / 2) + (range * numerator / denominator));
1290fe5e6e2cSKirk McKusick 	if (prefcg < 0)
1291fe5e6e2cSKirk McKusick 		prefcg += fs->fs_ncg;
1292fe5e6e2cSKirk McKusick 	if (prefcg >= fs->fs_ncg)
1293fe5e6e2cSKirk McKusick 		prefcg -= fs->fs_ncg;
1294fe5e6e2cSKirk McKusick 	/*
1295fe5e6e2cSKirk McKusick 	 * If this filesystem is not tracking directory depths,
1296fe5e6e2cSKirk McKusick 	 * revert to the old algorithm.
1297fe5e6e2cSKirk McKusick 	 */
1298fe5e6e2cSKirk McKusick 	if (depth == 0 && pip->i_number != UFS_ROOTINO)
1299fe5e6e2cSKirk McKusick 		prefcg = curcg;
1300df8bae1dSRodney W. Grimes 
1301df8bae1dSRodney W. Grimes 	/*
1302a61ab64aSKirk McKusick 	 * Count various limits which used for
1303a61ab64aSKirk McKusick 	 * optimal allocation of a directory inode.
1304a61ab64aSKirk McKusick 	 */
1305fe5e6e2cSKirk McKusick 	maxndir = min(avgndir + (1 << depth), fs->fs_ipg);
13069f206707SDon Lewis 	minifree = avgifree - avgifree / 4;
13079f206707SDon Lewis 	if (minifree < 1)
13089f206707SDon Lewis 		minifree = 1;
13099f206707SDon Lewis 	minbfree = avgbfree - avgbfree / 4;
13109f206707SDon Lewis 	if (minbfree < 1)
13119f206707SDon Lewis 		minbfree = 1;
1312a61ab64aSKirk McKusick 	cgsize = fs->fs_fsize * fs->fs_fpg;
1313a61ab64aSKirk McKusick 	dirsize = fs->fs_avgfilesize * fs->fs_avgfpdir;
1314a61ab64aSKirk McKusick 	curdirsize = avgndir ? (cgsize - avgbfree * fs->fs_bsize) / avgndir : 0;
1315a61ab64aSKirk McKusick 	if (dirsize < curdirsize)
1316a61ab64aSKirk McKusick 		dirsize = curdirsize;
13177fd627f0SBjoern A. Zeeb 	if (dirsize <= 0)
13187fd627f0SBjoern A. Zeeb 		maxcontigdirs = 0;		/* dirsize overflowed */
13197fd627f0SBjoern A. Zeeb 	else
13209f206707SDon Lewis 		maxcontigdirs = min((avgbfree * fs->fs_bsize) / dirsize, 255);
1321a61ab64aSKirk McKusick 	if (fs->fs_avgfpdir > 0)
1322a61ab64aSKirk McKusick 		maxcontigdirs = min(maxcontigdirs,
1323a61ab64aSKirk McKusick 				    fs->fs_ipg / fs->fs_avgfpdir);
1324a61ab64aSKirk McKusick 	if (maxcontigdirs == 0)
1325a61ab64aSKirk McKusick 		maxcontigdirs = 1;
1326a61ab64aSKirk McKusick 
1327a61ab64aSKirk McKusick 	/*
1328a61ab64aSKirk McKusick 	 * Limit number of dirs in one cg and reserve space for
1329a61ab64aSKirk McKusick 	 * regular files, but only if we have no deficit in
1330a61ab64aSKirk McKusick 	 * inodes or space.
1331baa12a84SKirk McKusick 	 *
1332baa12a84SKirk McKusick 	 * We are trying to find a suitable cylinder group nearby
1333baa12a84SKirk McKusick 	 * our preferred cylinder group to place a new directory.
1334baa12a84SKirk McKusick 	 * We scan from our preferred cylinder group forward looking
1335baa12a84SKirk McKusick 	 * for a cylinder group that meets our criterion. If we get
1336baa12a84SKirk McKusick 	 * to the final cylinder group and do not find anything,
1337e24784d3SKirk McKusick 	 * we start scanning forwards from the beginning of the
1338e24784d3SKirk McKusick 	 * filesystem. While it might seem sensible to start scanning
1339e24784d3SKirk McKusick 	 * backwards or even to alternate looking forward and backward,
1340e24784d3SKirk McKusick 	 * this approach fails badly when the filesystem is nearly full.
1341e24784d3SKirk McKusick 	 * Specifically, we first search all the areas that have no space
134208e94183SPedro F. Giffuni 	 * and finally try the one preceding that. We repeat this on
1343e24784d3SKirk McKusick 	 * every request and in the case of the final block end up
1344e24784d3SKirk McKusick 	 * searching the entire filesystem. By jumping to the front
1345e24784d3SKirk McKusick 	 * of the filesystem, our future forward searches always look
1346e24784d3SKirk McKusick 	 * in new cylinder groups so finds every possible block after
1347e24784d3SKirk McKusick 	 * one pass over the filesystem.
1348a61ab64aSKirk McKusick 	 */
1349a61ab64aSKirk McKusick 	for (cg = prefcg; cg < fs->fs_ncg; cg++)
1350a61ab64aSKirk McKusick 		if (fs->fs_cs(fs, cg).cs_ndir < maxndir &&
1351a61ab64aSKirk McKusick 		    fs->fs_cs(fs, cg).cs_nifree >= minifree &&
1352a61ab64aSKirk McKusick 		    fs->fs_cs(fs, cg).cs_nbfree >= minbfree) {
1353a61ab64aSKirk McKusick 			if (fs->fs_contigdirs[cg] < maxcontigdirs)
1354a61ab64aSKirk McKusick 				return ((ino_t)(fs->fs_ipg * cg));
1355a61ab64aSKirk McKusick 		}
13562ce451f0SKirk McKusick 	for (cg = 0; cg < prefcg; cg++)
1357a61ab64aSKirk McKusick 		if (fs->fs_cs(fs, cg).cs_ndir < maxndir &&
1358a61ab64aSKirk McKusick 		    fs->fs_cs(fs, cg).cs_nifree >= minifree &&
1359a61ab64aSKirk McKusick 		    fs->fs_cs(fs, cg).cs_nbfree >= minbfree) {
1360a61ab64aSKirk McKusick 			if (fs->fs_contigdirs[cg] < maxcontigdirs)
1361a61ab64aSKirk McKusick 				return ((ino_t)(fs->fs_ipg * cg));
1362a61ab64aSKirk McKusick 		}
1363a61ab64aSKirk McKusick 	/*
1364a61ab64aSKirk McKusick 	 * This is a backstop when we have deficit in space.
1365a61ab64aSKirk McKusick 	 */
1366a61ab64aSKirk McKusick 	for (cg = prefcg; cg < fs->fs_ncg; cg++)
1367a61ab64aSKirk McKusick 		if (fs->fs_cs(fs, cg).cs_nifree >= avgifree)
1368a61ab64aSKirk McKusick 			return ((ino_t)(fs->fs_ipg * cg));
13692ce451f0SKirk McKusick 	for (cg = 0; cg < prefcg; cg++)
1370a61ab64aSKirk McKusick 		if (fs->fs_cs(fs, cg).cs_nifree >= avgifree)
1371a61ab64aSKirk McKusick 			break;
1372a61ab64aSKirk McKusick 	return ((ino_t)(fs->fs_ipg * cg));
1373a61ab64aSKirk McKusick }
1374a61ab64aSKirk McKusick 
1375a61ab64aSKirk McKusick /*
1376df8bae1dSRodney W. Grimes  * Select the desired position for the next block in a file.  The file is
1377df8bae1dSRodney W. Grimes  * logically divided into sections. The first section is composed of the
1378fdd9a6f4SKirk McKusick  * direct blocks and the next fs_maxbpg blocks. Each additional section
1379fdd9a6f4SKirk McKusick  * contains fs_maxbpg blocks.
1380df8bae1dSRodney W. Grimes  *
1381df8bae1dSRodney W. Grimes  * If no blocks have been allocated in the first section, the policy is to
1382df8bae1dSRodney W. Grimes  * request a block in the same cylinder group as the inode that describes
1383baa12a84SKirk McKusick  * the file. The first indirect is allocated immediately following the last
1384baa12a84SKirk McKusick  * direct block and the data blocks for the first indirect immediately
1385baa12a84SKirk McKusick  * follow it.
1386baa12a84SKirk McKusick  *
1387baa12a84SKirk McKusick  * If no blocks have been allocated in any other section, the indirect
1388baa12a84SKirk McKusick  * block(s) are allocated in the same cylinder group as its inode in an
1389baa12a84SKirk McKusick  * area reserved immediately following the inode blocks. The policy for
1390baa12a84SKirk McKusick  * the data blocks is to place them in a cylinder group with a greater than
1391df8bae1dSRodney W. Grimes  * average number of free blocks. An appropriate cylinder group is found
1392df8bae1dSRodney W. Grimes  * by using a rotor that sweeps the cylinder groups. When a new group of
1393df8bae1dSRodney W. Grimes  * blocks is needed, the sweep begins in the cylinder group following the
1394df8bae1dSRodney W. Grimes  * cylinder group from which the previous allocation was made. The sweep
1395df8bae1dSRodney W. Grimes  * continues until a cylinder group with greater than the average number
1396df8bae1dSRodney W. Grimes  * of free blocks is found. If the allocation is for the first block in an
1397fdd9a6f4SKirk McKusick  * indirect block or the previous block is a hole, then the information on
1398fdd9a6f4SKirk McKusick  * the previous allocation is unavailable; here a best guess is made based
1399fdd9a6f4SKirk McKusick  * on the logical block number being allocated.
1400df8bae1dSRodney W. Grimes  *
1401df8bae1dSRodney W. Grimes  * If a section is already partially allocated, the policy is to
1402fdd9a6f4SKirk McKusick  * allocate blocks contiguously within the section if possible.
1403df8bae1dSRodney W. Grimes  */
14041c85e6a3SKirk McKusick ufs2_daddr_t
ffs_blkpref_ufs1(struct inode * ip,ufs_lbn_t lbn,int indx,ufs1_daddr_t * bap)1405064e6b43SKirk McKusick ffs_blkpref_ufs1(struct inode *ip,
1406064e6b43SKirk McKusick 	ufs_lbn_t lbn,
1407064e6b43SKirk McKusick 	int indx,
1408064e6b43SKirk McKusick 	ufs1_daddr_t *bap)
1409df8bae1dSRodney W. Grimes {
141005f4ff5dSPoul-Henning Kamp 	struct fs *fs;
1411831b1ff7SKirk McKusick 	uint64_t cg, inocg;
1412831b1ff7SKirk McKusick 	uint64_t avgbfree, startcg;
1413fdf34aa3SKirk McKusick 	ufs2_daddr_t pref, prevbn;
1414df8bae1dSRodney W. Grimes 
1415baa12a84SKirk McKusick 	KASSERT(indx <= 0 || bap != NULL, ("need non-NULL bap"));
1416e1db6897SKonstantin Belousov 	mtx_assert(UFS_MTX(ITOUMP(ip)), MA_OWNED);
1417e1db6897SKonstantin Belousov 	fs = ITOFS(ip);
1418aa7ddc85SKirk McKusick 	/*
1419baa12a84SKirk McKusick 	 * Allocation of indirect blocks is indicated by passing negative
1420baa12a84SKirk McKusick 	 * values in indx: -1 for single indirect, -2 for double indirect,
1421baa12a84SKirk McKusick 	 * -3 for triple indirect. As noted below, we attempt to allocate
1422baa12a84SKirk McKusick 	 * the first indirect inline with the file data. For all later
1423baa12a84SKirk McKusick 	 * indirect blocks, the data is often allocated in other cylinder
1424baa12a84SKirk McKusick 	 * groups. However to speed random file access and to speed up
1425baa12a84SKirk McKusick 	 * fsck, the filesystem reserves the first fs_metaspace blocks
1426baa12a84SKirk McKusick 	 * (typically half of fs_minfree) of the data area of each cylinder
1427baa12a84SKirk McKusick 	 * group to hold these later indirect blocks.
1428baa12a84SKirk McKusick 	 */
1429baa12a84SKirk McKusick 	inocg = ino_to_cg(fs, ip->i_number);
1430baa12a84SKirk McKusick 	if (indx < 0) {
1431baa12a84SKirk McKusick 		/*
1432baa12a84SKirk McKusick 		 * Our preference for indirect blocks is the zone at the
1433baa12a84SKirk McKusick 		 * beginning of the inode's cylinder group data area that
1434baa12a84SKirk McKusick 		 * we try to reserve for indirect blocks.
1435baa12a84SKirk McKusick 		 */
1436baa12a84SKirk McKusick 		pref = cgmeta(fs, inocg);
1437baa12a84SKirk McKusick 		/*
1438baa12a84SKirk McKusick 		 * If we are allocating the first indirect block, try to
1439baa12a84SKirk McKusick 		 * place it immediately following the last direct block.
1440baa12a84SKirk McKusick 		 */
14411dc349abSEd Maste 		if (indx == -1 && lbn < UFS_NDADDR + NINDIR(fs) &&
1442dc37121dSKonstantin Belousov 		    ip->i_din1->di_db[UFS_NDADDR - 1] != 0) {
14431dc349abSEd Maste 			pref = ip->i_din1->di_db[UFS_NDADDR - 1] + fs->fs_frag;
1444dc37121dSKonstantin Belousov 			if (dtog(fs, pref) >= fs->fs_ncg)
1445dc37121dSKonstantin Belousov 				pref = 0;
1446dc37121dSKonstantin Belousov 		}
1447baa12a84SKirk McKusick 		return (pref);
1448baa12a84SKirk McKusick 	}
1449baa12a84SKirk McKusick 	/*
1450aa7ddc85SKirk McKusick 	 * If we are allocating the first data block in the first indirect
1451baa12a84SKirk McKusick 	 * block and the indirect has been allocated in the data block area,
1452baa12a84SKirk McKusick 	 * try to place it immediately following the indirect block.
1453aa7ddc85SKirk McKusick 	 */
14541dc349abSEd Maste 	if (lbn == UFS_NDADDR) {
1455aa7ddc85SKirk McKusick 		pref = ip->i_din1->di_ib[0];
1456baa12a84SKirk McKusick 		if (pref != 0 && pref >= cgdata(fs, inocg) &&
1457dc37121dSKonstantin Belousov 		    pref < cgbase(fs, inocg + 1)) {
1458dc37121dSKonstantin Belousov 			if (dtog(fs, pref + fs->fs_frag) >= fs->fs_ncg)
1459dc37121dSKonstantin Belousov 				return (0);
1460aa7ddc85SKirk McKusick 			return (pref + fs->fs_frag);
1461aa7ddc85SKirk McKusick 		}
1462dc37121dSKonstantin Belousov 	}
1463baa12a84SKirk McKusick 	/*
1464baa12a84SKirk McKusick 	 * If we are at the beginning of a file, or we have already allocated
1465baa12a84SKirk McKusick 	 * the maximum number of blocks per cylinder group, or we do not
146608e94183SPedro F. Giffuni 	 * have a block allocated immediately preceding us, then we need
1467baa12a84SKirk McKusick 	 * to decide where to start allocating new blocks.
1468baa12a84SKirk McKusick 	 */
1469fdf34aa3SKirk McKusick 	if (indx ==  0) {
1470fdf34aa3SKirk McKusick 		prevbn = 0;
1471fdf34aa3SKirk McKusick 	} else {
1472fdf34aa3SKirk McKusick 		prevbn = bap[indx - 1];
1473fdf34aa3SKirk McKusick 		if (UFS_CHECK_BLKNO(ITOVFS(ip), ip->i_number, prevbn,
1474fdf34aa3SKirk McKusick 		    fs->fs_bsize) != 0)
1475fdf34aa3SKirk McKusick 			prevbn = 0;
1476fdf34aa3SKirk McKusick 	}
1477fdf34aa3SKirk McKusick 	if (indx % fs->fs_maxbpg == 0 || prevbn == 0) {
1478baa12a84SKirk McKusick 		/*
1479baa12a84SKirk McKusick 		 * If we are allocating a directory data block, we want
1480baa12a84SKirk McKusick 		 * to place it in the metadata area.
1481baa12a84SKirk McKusick 		 */
1482d8ba45e2SEd Maste 		if ((ip->i_mode & IFMT) == IFDIR)
1483baa12a84SKirk McKusick 			return (cgmeta(fs, inocg));
1484baa12a84SKirk McKusick 		/*
1485baa12a84SKirk McKusick 		 * Until we fill all the direct and all the first indirect's
1486baa12a84SKirk McKusick 		 * blocks, we try to allocate in the data area of the inode's
1487baa12a84SKirk McKusick 		 * cylinder group.
1488baa12a84SKirk McKusick 		 */
14891dc349abSEd Maste 		if (lbn < UFS_NDADDR + NINDIR(fs))
1490baa12a84SKirk McKusick 			return (cgdata(fs, inocg));
1491df8bae1dSRodney W. Grimes 		/*
1492df8bae1dSRodney W. Grimes 		 * Find a cylinder with greater than average number of
1493df8bae1dSRodney W. Grimes 		 * unused data blocks.
1494df8bae1dSRodney W. Grimes 		 */
1495fdf34aa3SKirk McKusick 		if (indx == 0 || prevbn == 0)
1496baa12a84SKirk McKusick 			startcg = inocg + lbn / fs->fs_maxbpg;
1497df8bae1dSRodney W. Grimes 		else
1498fdf34aa3SKirk McKusick 			startcg = dtog(fs, prevbn) + 1;
1499df8bae1dSRodney W. Grimes 		startcg %= fs->fs_ncg;
1500df8bae1dSRodney W. Grimes 		avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
1501df8bae1dSRodney W. Grimes 		for (cg = startcg; cg < fs->fs_ncg; cg++)
1502df8bae1dSRodney W. Grimes 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1503df8bae1dSRodney W. Grimes 				fs->fs_cgrotor = cg;
1504baa12a84SKirk McKusick 				return (cgdata(fs, cg));
1505df8bae1dSRodney W. Grimes 			}
1506a57a2c01SKonstantin Belousov 		for (cg = 0; cg < startcg; cg++)
1507df8bae1dSRodney W. Grimes 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
1508df8bae1dSRodney W. Grimes 				fs->fs_cgrotor = cg;
1509baa12a84SKirk McKusick 				return (cgdata(fs, cg));
1510df8bae1dSRodney W. Grimes 			}
15116ab46d52SBruce Evans 		return (0);
1512df8bae1dSRodney W. Grimes 	}
1513df8bae1dSRodney W. Grimes 	/*
1514baa12a84SKirk McKusick 	 * Otherwise, we just always try to lay things out contiguously.
1515df8bae1dSRodney W. Grimes 	 */
1516dc37121dSKonstantin Belousov 	if (dtog(fs, prevbn + fs->fs_frag) >= fs->fs_ncg)
1517dc37121dSKonstantin Belousov 		return (0);
1518fdf34aa3SKirk McKusick 	return (prevbn + fs->fs_frag);
15191c85e6a3SKirk McKusick }
15201c85e6a3SKirk McKusick 
1521df8bae1dSRodney W. Grimes /*
15221c85e6a3SKirk McKusick  * Same as above, but for UFS2
1523df8bae1dSRodney W. Grimes  */
15241c85e6a3SKirk McKusick ufs2_daddr_t
ffs_blkpref_ufs2(struct inode * ip,ufs_lbn_t lbn,int indx,ufs2_daddr_t * bap)1525064e6b43SKirk McKusick ffs_blkpref_ufs2(struct inode *ip,
1526064e6b43SKirk McKusick 	ufs_lbn_t lbn,
1527064e6b43SKirk McKusick 	int indx,
1528064e6b43SKirk McKusick 	ufs2_daddr_t *bap)
15291c85e6a3SKirk McKusick {
15301c85e6a3SKirk McKusick 	struct fs *fs;
1531831b1ff7SKirk McKusick 	uint64_t cg, inocg;
1532831b1ff7SKirk McKusick 	uint64_t avgbfree, startcg;
1533fdf34aa3SKirk McKusick 	ufs2_daddr_t pref, prevbn;
15341c85e6a3SKirk McKusick 
1535baa12a84SKirk McKusick 	KASSERT(indx <= 0 || bap != NULL, ("need non-NULL bap"));
1536e1db6897SKonstantin Belousov 	mtx_assert(UFS_MTX(ITOUMP(ip)), MA_OWNED);
1537e1db6897SKonstantin Belousov 	fs = ITOFS(ip);
1538aa7ddc85SKirk McKusick 	/*
1539baa12a84SKirk McKusick 	 * Allocation of indirect blocks is indicated by passing negative
1540baa12a84SKirk McKusick 	 * values in indx: -1 for single indirect, -2 for double indirect,
1541baa12a84SKirk McKusick 	 * -3 for triple indirect. As noted below, we attempt to allocate
1542baa12a84SKirk McKusick 	 * the first indirect inline with the file data. For all later
1543baa12a84SKirk McKusick 	 * indirect blocks, the data is often allocated in other cylinder
1544baa12a84SKirk McKusick 	 * groups. However to speed random file access and to speed up
1545baa12a84SKirk McKusick 	 * fsck, the filesystem reserves the first fs_metaspace blocks
1546baa12a84SKirk McKusick 	 * (typically half of fs_minfree) of the data area of each cylinder
1547baa12a84SKirk McKusick 	 * group to hold these later indirect blocks.
1548baa12a84SKirk McKusick 	 */
1549baa12a84SKirk McKusick 	inocg = ino_to_cg(fs, ip->i_number);
1550baa12a84SKirk McKusick 	if (indx < 0) {
1551baa12a84SKirk McKusick 		/*
1552baa12a84SKirk McKusick 		 * Our preference for indirect blocks is the zone at the
1553baa12a84SKirk McKusick 		 * beginning of the inode's cylinder group data area that
1554baa12a84SKirk McKusick 		 * we try to reserve for indirect blocks.
1555baa12a84SKirk McKusick 		 */
1556baa12a84SKirk McKusick 		pref = cgmeta(fs, inocg);
1557baa12a84SKirk McKusick 		/*
1558baa12a84SKirk McKusick 		 * If we are allocating the first indirect block, try to
1559baa12a84SKirk McKusick 		 * place it immediately following the last direct block.
1560baa12a84SKirk McKusick 		 */
15611dc349abSEd Maste 		if (indx == -1 && lbn < UFS_NDADDR + NINDIR(fs) &&
1562dc37121dSKonstantin Belousov 		    ip->i_din2->di_db[UFS_NDADDR - 1] != 0) {
15631dc349abSEd Maste 			pref = ip->i_din2->di_db[UFS_NDADDR - 1] + fs->fs_frag;
1564dc37121dSKonstantin Belousov 			if (dtog(fs, pref) >= fs->fs_ncg)
1565dc37121dSKonstantin Belousov 				pref = 0;
1566dc37121dSKonstantin Belousov 		}
1567baa12a84SKirk McKusick 		return (pref);
1568baa12a84SKirk McKusick 	}
1569baa12a84SKirk McKusick 	/*
1570aa7ddc85SKirk McKusick 	 * If we are allocating the first data block in the first indirect
1571baa12a84SKirk McKusick 	 * block and the indirect has been allocated in the data block area,
1572baa12a84SKirk McKusick 	 * try to place it immediately following the indirect block.
1573aa7ddc85SKirk McKusick 	 */
15741dc349abSEd Maste 	if (lbn == UFS_NDADDR) {
1575baa12a84SKirk McKusick 		pref = ip->i_din2->di_ib[0];
1576baa12a84SKirk McKusick 		if (pref != 0 && pref >= cgdata(fs, inocg) &&
1577dc37121dSKonstantin Belousov 		    pref < cgbase(fs, inocg + 1)) {
1578dc37121dSKonstantin Belousov 			if (dtog(fs, pref + fs->fs_frag) >= fs->fs_ncg)
1579dc37121dSKonstantin Belousov 				return (0);
1580aa7ddc85SKirk McKusick 			return (pref + fs->fs_frag);
1581aa7ddc85SKirk McKusick 		}
1582dc37121dSKonstantin Belousov 	}
1583baa12a84SKirk McKusick 	/*
1584baa12a84SKirk McKusick 	 * If we are at the beginning of a file, or we have already allocated
1585baa12a84SKirk McKusick 	 * the maximum number of blocks per cylinder group, or we do not
158608e94183SPedro F. Giffuni 	 * have a block allocated immediately preceding us, then we need
1587baa12a84SKirk McKusick 	 * to decide where to start allocating new blocks.
1588baa12a84SKirk McKusick 	 */
1589fdf34aa3SKirk McKusick 	if (indx ==  0) {
1590fdf34aa3SKirk McKusick 		prevbn = 0;
1591fdf34aa3SKirk McKusick 	} else {
1592fdf34aa3SKirk McKusick 		prevbn = bap[indx - 1];
1593fdf34aa3SKirk McKusick 		if (UFS_CHECK_BLKNO(ITOVFS(ip), ip->i_number, prevbn,
1594fdf34aa3SKirk McKusick 		    fs->fs_bsize) != 0)
1595fdf34aa3SKirk McKusick 			prevbn = 0;
1596fdf34aa3SKirk McKusick 	}
1597fdf34aa3SKirk McKusick 	if (indx % fs->fs_maxbpg == 0 || prevbn == 0) {
1598baa12a84SKirk McKusick 		/*
1599baa12a84SKirk McKusick 		 * If we are allocating a directory data block, we want
1600baa12a84SKirk McKusick 		 * to place it in the metadata area.
1601baa12a84SKirk McKusick 		 */
1602d8ba45e2SEd Maste 		if ((ip->i_mode & IFMT) == IFDIR)
1603baa12a84SKirk McKusick 			return (cgmeta(fs, inocg));
1604baa12a84SKirk McKusick 		/*
1605baa12a84SKirk McKusick 		 * Until we fill all the direct and all the first indirect's
1606baa12a84SKirk McKusick 		 * blocks, we try to allocate in the data area of the inode's
1607baa12a84SKirk McKusick 		 * cylinder group.
1608baa12a84SKirk McKusick 		 */
16091dc349abSEd Maste 		if (lbn < UFS_NDADDR + NINDIR(fs))
1610baa12a84SKirk McKusick 			return (cgdata(fs, inocg));
16111c85e6a3SKirk McKusick 		/*
16121c85e6a3SKirk McKusick 		 * Find a cylinder with greater than average number of
16131c85e6a3SKirk McKusick 		 * unused data blocks.
16141c85e6a3SKirk McKusick 		 */
1615fdf34aa3SKirk McKusick 		if (indx == 0 || prevbn == 0)
1616baa12a84SKirk McKusick 			startcg = inocg + lbn / fs->fs_maxbpg;
16171c85e6a3SKirk McKusick 		else
1618fdf34aa3SKirk McKusick 			startcg = dtog(fs, prevbn) + 1;
16191c85e6a3SKirk McKusick 		startcg %= fs->fs_ncg;
16201c85e6a3SKirk McKusick 		avgbfree = fs->fs_cstotal.cs_nbfree / fs->fs_ncg;
16211c85e6a3SKirk McKusick 		for (cg = startcg; cg < fs->fs_ncg; cg++)
16221c85e6a3SKirk McKusick 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
16231c85e6a3SKirk McKusick 				fs->fs_cgrotor = cg;
1624baa12a84SKirk McKusick 				return (cgdata(fs, cg));
16251c85e6a3SKirk McKusick 			}
1626a57a2c01SKonstantin Belousov 		for (cg = 0; cg < startcg; cg++)
16271c85e6a3SKirk McKusick 			if (fs->fs_cs(fs, cg).cs_nbfree >= avgbfree) {
16281c85e6a3SKirk McKusick 				fs->fs_cgrotor = cg;
1629baa12a84SKirk McKusick 				return (cgdata(fs, cg));
16301c85e6a3SKirk McKusick 			}
16311c85e6a3SKirk McKusick 		return (0);
16321c85e6a3SKirk McKusick 	}
16331c85e6a3SKirk McKusick 	/*
1634baa12a84SKirk McKusick 	 * Otherwise, we just always try to lay things out contiguously.
16351c85e6a3SKirk McKusick 	 */
1636dc37121dSKonstantin Belousov 	if (dtog(fs, prevbn + fs->fs_frag) >= fs->fs_ncg)
1637dc37121dSKonstantin Belousov 		return (0);
1638fdf34aa3SKirk McKusick 	return (prevbn + fs->fs_frag);
1639df8bae1dSRodney W. Grimes }
1640df8bae1dSRodney W. Grimes 
1641df8bae1dSRodney W. Grimes /*
1642df8bae1dSRodney W. Grimes  * Implement the cylinder overflow algorithm.
1643df8bae1dSRodney W. Grimes  *
1644df8bae1dSRodney W. Grimes  * The policy implemented by this algorithm is:
1645df8bae1dSRodney W. Grimes  *   1) allocate the block in its requested cylinder group.
16462733b242SGordon Bergling  *   2) quadratically rehash on the cylinder group number.
1647df8bae1dSRodney W. Grimes  *   3) brute force search for a free block.
16488e37fbadSJeff Roberson  *
16498e37fbadSJeff Roberson  * Must be called with the UFS lock held.  Will release the lock on success
16508e37fbadSJeff Roberson  * and return with it held on failure.
1651df8bae1dSRodney W. Grimes  */
1652df8bae1dSRodney W. Grimes /*VARARGS5*/
16531c85e6a3SKirk McKusick static ufs2_daddr_t
ffs_hashalloc(struct inode * ip,uint64_t cg,ufs2_daddr_t pref,int size,int rsize,allocfcn_t * allocator)1654064e6b43SKirk McKusick ffs_hashalloc(struct inode *ip,
1655831b1ff7SKirk McKusick 	uint64_t cg,
1656064e6b43SKirk McKusick 	ufs2_daddr_t pref,
1657064e6b43SKirk McKusick 	int size,	/* Search size for data blocks, mode for inodes */
1658064e6b43SKirk McKusick 	int rsize,	/* Real allocated size. */
1659064e6b43SKirk McKusick 	allocfcn_t *allocator)
1660df8bae1dSRodney W. Grimes {
166105f4ff5dSPoul-Henning Kamp 	struct fs *fs;
16621c85e6a3SKirk McKusick 	ufs2_daddr_t result;
1663831b1ff7SKirk McKusick 	uint64_t i, icg = cg;
1664df8bae1dSRodney W. Grimes 
1665e1db6897SKonstantin Belousov 	mtx_assert(UFS_MTX(ITOUMP(ip)), MA_OWNED);
16661102b89bSDavid E. O'Brien #ifdef INVARIANTS
1667f2a2857bSKirk McKusick 	if (ITOV(ip)->v_mount->mnt_kern_flag & MNTK_SUSPENDED)
1668f2a2857bSKirk McKusick 		panic("ffs_hashalloc: allocation on suspended filesystem");
1669f2a2857bSKirk McKusick #endif
1670e1db6897SKonstantin Belousov 	fs = ITOFS(ip);
1671df8bae1dSRodney W. Grimes 	/*
1672df8bae1dSRodney W. Grimes 	 * 1: preferred cylinder group
1673df8bae1dSRodney W. Grimes 	 */
1674113db2ddSJeff Roberson 	result = (*allocator)(ip, cg, pref, size, rsize);
1675df8bae1dSRodney W. Grimes 	if (result)
1676df8bae1dSRodney W. Grimes 		return (result);
1677df8bae1dSRodney W. Grimes 	/*
1678df8bae1dSRodney W. Grimes 	 * 2: quadratic rehash
1679df8bae1dSRodney W. Grimes 	 */
1680df8bae1dSRodney W. Grimes 	for (i = 1; i < fs->fs_ncg; i *= 2) {
1681df8bae1dSRodney W. Grimes 		cg += i;
1682df8bae1dSRodney W. Grimes 		if (cg >= fs->fs_ncg)
1683df8bae1dSRodney W. Grimes 			cg -= fs->fs_ncg;
1684113db2ddSJeff Roberson 		result = (*allocator)(ip, cg, 0, size, rsize);
1685df8bae1dSRodney W. Grimes 		if (result)
1686df8bae1dSRodney W. Grimes 			return (result);
1687df8bae1dSRodney W. Grimes 	}
1688df8bae1dSRodney W. Grimes 	/*
1689df8bae1dSRodney W. Grimes 	 * 3: brute force search
1690df8bae1dSRodney W. Grimes 	 * Note that we start at i == 2, since 0 was checked initially,
1691df8bae1dSRodney W. Grimes 	 * and 1 is always checked in the quadratic rehash.
1692df8bae1dSRodney W. Grimes 	 */
1693df8bae1dSRodney W. Grimes 	cg = (icg + 2) % fs->fs_ncg;
1694df8bae1dSRodney W. Grimes 	for (i = 2; i < fs->fs_ncg; i++) {
1695113db2ddSJeff Roberson 		result = (*allocator)(ip, cg, 0, size, rsize);
1696df8bae1dSRodney W. Grimes 		if (result)
1697df8bae1dSRodney W. Grimes 			return (result);
1698df8bae1dSRodney W. Grimes 		cg++;
1699df8bae1dSRodney W. Grimes 		if (cg == fs->fs_ncg)
1700df8bae1dSRodney W. Grimes 			cg = 0;
1701df8bae1dSRodney W. Grimes 	}
170257a4e3faSBruce Evans 	return (0);
1703df8bae1dSRodney W. Grimes }
1704df8bae1dSRodney W. Grimes 
1705df8bae1dSRodney W. Grimes /*
1706df8bae1dSRodney W. Grimes  * Determine whether a fragment can be extended.
1707df8bae1dSRodney W. Grimes  *
1708df8bae1dSRodney W. Grimes  * Check to see if the necessary fragments are available, and
1709df8bae1dSRodney W. Grimes  * if they are, allocate them.
1710df8bae1dSRodney W. Grimes  */
17111c85e6a3SKirk McKusick static ufs2_daddr_t
ffs_fragextend(struct inode * ip,uint64_t cg,ufs2_daddr_t bprev,int osize,int nsize)1712064e6b43SKirk McKusick ffs_fragextend(struct inode *ip,
1713831b1ff7SKirk McKusick 	uint64_t cg,
1714064e6b43SKirk McKusick 	ufs2_daddr_t bprev,
1715064e6b43SKirk McKusick 	int osize,
1716064e6b43SKirk McKusick 	int nsize)
1717df8bae1dSRodney W. Grimes {
171805f4ff5dSPoul-Henning Kamp 	struct fs *fs;
171905f4ff5dSPoul-Henning Kamp 	struct cg *cgp;
1720df8bae1dSRodney W. Grimes 	struct buf *bp;
17218e37fbadSJeff Roberson 	struct ufsmount *ump;
17228e37fbadSJeff Roberson 	int nffree;
1723df8bae1dSRodney W. Grimes 	long bno;
1724df8bae1dSRodney W. Grimes 	int frags, bbase;
1725df8bae1dSRodney W. Grimes 	int i, error;
1726831b1ff7SKirk McKusick 	uint8_t *blksfree;
1727df8bae1dSRodney W. Grimes 
1728e1db6897SKonstantin Belousov 	ump = ITOUMP(ip);
1729e1db6897SKonstantin Belousov 	fs = ump->um_fs;
1730df8bae1dSRodney W. Grimes 	if (fs->fs_cs(fs, cg).cs_nffree < numfrags(fs, nsize - osize))
17316ab46d52SBruce Evans 		return (0);
1732df8bae1dSRodney W. Grimes 	frags = numfrags(fs, nsize);
1733df8bae1dSRodney W. Grimes 	bbase = fragnum(fs, bprev);
1734df8bae1dSRodney W. Grimes 	if (bbase > fragnum(fs, (bprev + frags - 1))) {
1735df8bae1dSRodney W. Grimes 		/* cannot extend across a block boundary */
17366ab46d52SBruce Evans 		return (0);
1737df8bae1dSRodney W. Grimes 	}
17388e37fbadSJeff Roberson 	UFS_UNLOCK(ump);
1739c3046779SKirk McKusick 	if ((error = ffs_getcg(fs, ump->um_devvp, cg, 0, &bp, &cgp)) != 0) {
1740c3046779SKirk McKusick 		ffs_checkcgintegrity(fs, cg, error);
17418e37fbadSJeff Roberson 		goto fail;
1742c3046779SKirk McKusick 	}
1743df8bae1dSRodney W. Grimes 	bno = dtogd(fs, bprev);
17449f043878SKirk McKusick 	blksfree = cg_blksfree(cgp);
1745df8bae1dSRodney W. Grimes 	for (i = numfrags(fs, osize); i < frags; i++)
17468e37fbadSJeff Roberson 		if (isclr(blksfree, bno + i))
17478e37fbadSJeff Roberson 			goto fail;
1748df8bae1dSRodney W. Grimes 	/*
1749df8bae1dSRodney W. Grimes 	 * the current fragment can be extended
1750df8bae1dSRodney W. Grimes 	 * deduct the count on fragment being extended into
1751df8bae1dSRodney W. Grimes 	 * increase the count on the remaining fragment (if any)
1752df8bae1dSRodney W. Grimes 	 * allocate the extended piece
1753df8bae1dSRodney W. Grimes 	 */
1754df8bae1dSRodney W. Grimes 	for (i = frags; i < fs->fs_frag - bbase; i++)
17559f043878SKirk McKusick 		if (isclr(blksfree, bno + i))
1756df8bae1dSRodney W. Grimes 			break;
1757df8bae1dSRodney W. Grimes 	cgp->cg_frsum[i - numfrags(fs, osize)]--;
1758df8bae1dSRodney W. Grimes 	if (i != frags)
1759df8bae1dSRodney W. Grimes 		cgp->cg_frsum[i - frags]++;
17608e37fbadSJeff Roberson 	for (i = numfrags(fs, osize), nffree = 0; i < frags; i++) {
17619f043878SKirk McKusick 		clrbit(blksfree, bno + i);
1762df8bae1dSRodney W. Grimes 		cgp->cg_cs.cs_nffree--;
17638e37fbadSJeff Roberson 		nffree++;
1764df8bae1dSRodney W. Grimes 	}
17658e37fbadSJeff Roberson 	UFS_LOCK(ump);
17668e37fbadSJeff Roberson 	fs->fs_cstotal.cs_nffree -= nffree;
17678e37fbadSJeff Roberson 	fs->fs_cs(fs, cg).cs_nffree -= nffree;
1768df8bae1dSRodney W. Grimes 	fs->fs_fmod = 1;
17698e37fbadSJeff Roberson 	ACTIVECLEAR(fs, cg);
17708e37fbadSJeff Roberson 	UFS_UNLOCK(ump);
1771b1897c19SJulian Elischer 	if (DOINGSOFTDEP(ITOV(ip)))
1772113db2ddSJeff Roberson 		softdep_setup_blkmapdep(bp, UFSTOVFS(ump), bprev,
1773113db2ddSJeff Roberson 		    frags, numfrags(fs, osize));
1774df8bae1dSRodney W. Grimes 	bdwrite(bp);
1775df8bae1dSRodney W. Grimes 	return (bprev);
17768e37fbadSJeff Roberson 
17778e37fbadSJeff Roberson fail:
17788e37fbadSJeff Roberson 	brelse(bp);
17798e37fbadSJeff Roberson 	UFS_LOCK(ump);
17808e37fbadSJeff Roberson 	return (0);
17818e37fbadSJeff Roberson 
1782df8bae1dSRodney W. Grimes }
1783df8bae1dSRodney W. Grimes 
1784df8bae1dSRodney W. Grimes /*
1785df8bae1dSRodney W. Grimes  * Determine whether a block can be allocated.
1786df8bae1dSRodney W. Grimes  *
1787df8bae1dSRodney W. Grimes  * Check to see if a block of the appropriate size is available,
1788df8bae1dSRodney W. Grimes  * and if it is, allocate it.
1789df8bae1dSRodney W. Grimes  */
17901c85e6a3SKirk McKusick static ufs2_daddr_t
ffs_alloccg(struct inode * ip,uint64_t cg,ufs2_daddr_t bpref,int size,int rsize)1791064e6b43SKirk McKusick ffs_alloccg(struct inode *ip,
1792831b1ff7SKirk McKusick 	uint64_t cg,
1793064e6b43SKirk McKusick 	ufs2_daddr_t bpref,
1794064e6b43SKirk McKusick 	int size,
1795064e6b43SKirk McKusick 	int rsize)
1796df8bae1dSRodney W. Grimes {
179705f4ff5dSPoul-Henning Kamp 	struct fs *fs;
179805f4ff5dSPoul-Henning Kamp 	struct cg *cgp;
1799df8bae1dSRodney W. Grimes 	struct buf *bp;
18008e37fbadSJeff Roberson 	struct ufsmount *ump;
18011c85e6a3SKirk McKusick 	ufs1_daddr_t bno;
18021c85e6a3SKirk McKusick 	ufs2_daddr_t blkno;
18031c85e6a3SKirk McKusick 	int i, allocsiz, error, frags;
1804831b1ff7SKirk McKusick 	uint8_t *blksfree;
1805df8bae1dSRodney W. Grimes 
1806e1db6897SKonstantin Belousov 	ump = ITOUMP(ip);
1807e1db6897SKonstantin Belousov 	fs = ump->um_fs;
1808df8bae1dSRodney W. Grimes 	if (fs->fs_cs(fs, cg).cs_nbfree == 0 && size == fs->fs_bsize)
18096ab46d52SBruce Evans 		return (0);
18108e37fbadSJeff Roberson 	UFS_UNLOCK(ump);
181144d37182SKirk McKusick 	if ((error = ffs_getcg(fs, ump->um_devvp, cg, 0, &bp, &cgp)) != 0 ||
1812c3046779SKirk McKusick 	   (cgp->cg_cs.cs_nbfree == 0 && size == fs->fs_bsize)) {
1813c3046779SKirk McKusick 		ffs_checkcgintegrity(fs, cg, error);
18148e37fbadSJeff Roberson 		goto fail;
1815c3046779SKirk McKusick 	}
1816df8bae1dSRodney W. Grimes 	if (size == fs->fs_bsize) {
18178e37fbadSJeff Roberson 		UFS_LOCK(ump);
1818113db2ddSJeff Roberson 		blkno = ffs_alloccgblk(ip, bp, bpref, rsize);
18198e37fbadSJeff Roberson 		ACTIVECLEAR(fs, cg);
18208e37fbadSJeff Roberson 		UFS_UNLOCK(ump);
1821df8bae1dSRodney W. Grimes 		bdwrite(bp);
18221c85e6a3SKirk McKusick 		return (blkno);
1823df8bae1dSRodney W. Grimes 	}
1824df8bae1dSRodney W. Grimes 	/*
1825df8bae1dSRodney W. Grimes 	 * check to see if any fragments are already available
1826df8bae1dSRodney W. Grimes 	 * allocsiz is the size which will be allocated, hacking
1827df8bae1dSRodney W. Grimes 	 * it down to a smaller size if necessary
1828df8bae1dSRodney W. Grimes 	 */
18299f043878SKirk McKusick 	blksfree = cg_blksfree(cgp);
1830df8bae1dSRodney W. Grimes 	frags = numfrags(fs, size);
1831df8bae1dSRodney W. Grimes 	for (allocsiz = frags; allocsiz < fs->fs_frag; allocsiz++)
1832df8bae1dSRodney W. Grimes 		if (cgp->cg_frsum[allocsiz] != 0)
1833df8bae1dSRodney W. Grimes 			break;
1834df8bae1dSRodney W. Grimes 	if (allocsiz == fs->fs_frag) {
1835df8bae1dSRodney W. Grimes 		/*
1836df8bae1dSRodney W. Grimes 		 * no fragments were available, so a block will be
1837df8bae1dSRodney W. Grimes 		 * allocated, and hacked up
1838df8bae1dSRodney W. Grimes 		 */
18398e37fbadSJeff Roberson 		if (cgp->cg_cs.cs_nbfree == 0)
18408e37fbadSJeff Roberson 			goto fail;
18418e37fbadSJeff Roberson 		UFS_LOCK(ump);
1842113db2ddSJeff Roberson 		blkno = ffs_alloccgblk(ip, bp, bpref, rsize);
18438e37fbadSJeff Roberson 		ACTIVECLEAR(fs, cg);
18448e37fbadSJeff Roberson 		UFS_UNLOCK(ump);
1845df8bae1dSRodney W. Grimes 		bdwrite(bp);
18461c85e6a3SKirk McKusick 		return (blkno);
1847df8bae1dSRodney W. Grimes 	}
1848113db2ddSJeff Roberson 	KASSERT(size == rsize,
1849113db2ddSJeff Roberson 	    ("ffs_alloccg: size(%d) != rsize(%d)", size, rsize));
1850df8bae1dSRodney W. Grimes 	bno = ffs_mapsearch(fs, cgp, bpref, allocsiz);
18518e37fbadSJeff Roberson 	if (bno < 0)
18528e37fbadSJeff Roberson 		goto fail;
1853df8bae1dSRodney W. Grimes 	for (i = 0; i < frags; i++)
18549f043878SKirk McKusick 		clrbit(blksfree, bno + i);
1855df8bae1dSRodney W. Grimes 	cgp->cg_cs.cs_nffree -= frags;
1856df8bae1dSRodney W. Grimes 	cgp->cg_frsum[allocsiz]--;
1857df8bae1dSRodney W. Grimes 	if (frags != allocsiz)
1858df8bae1dSRodney W. Grimes 		cgp->cg_frsum[allocsiz - frags]++;
18598e37fbadSJeff Roberson 	UFS_LOCK(ump);
18608e37fbadSJeff Roberson 	fs->fs_cstotal.cs_nffree -= frags;
18618e37fbadSJeff Roberson 	fs->fs_cs(fs, cg).cs_nffree -= frags;
18628e37fbadSJeff Roberson 	fs->fs_fmod = 1;
1863364ed814SKirk McKusick 	blkno = cgbase(fs, cg) + bno;
18648e37fbadSJeff Roberson 	ACTIVECLEAR(fs, cg);
18658e37fbadSJeff Roberson 	UFS_UNLOCK(ump);
1866b1897c19SJulian Elischer 	if (DOINGSOFTDEP(ITOV(ip)))
1867113db2ddSJeff Roberson 		softdep_setup_blkmapdep(bp, UFSTOVFS(ump), blkno, frags, 0);
1868df8bae1dSRodney W. Grimes 	bdwrite(bp);
18691c85e6a3SKirk McKusick 	return (blkno);
18708e37fbadSJeff Roberson 
18718e37fbadSJeff Roberson fail:
18728e37fbadSJeff Roberson 	brelse(bp);
18738e37fbadSJeff Roberson 	UFS_LOCK(ump);
18748e37fbadSJeff Roberson 	return (0);
1875df8bae1dSRodney W. Grimes }
1876df8bae1dSRodney W. Grimes 
1877df8bae1dSRodney W. Grimes /*
1878df8bae1dSRodney W. Grimes  * Allocate a block in a cylinder group.
1879df8bae1dSRodney W. Grimes  *
1880df8bae1dSRodney W. Grimes  * This algorithm implements the following policy:
1881df8bae1dSRodney W. Grimes  *   1) allocate the requested block.
1882df8bae1dSRodney W. Grimes  *   2) allocate a rotationally optimal block in the same cylinder.
1883df8bae1dSRodney W. Grimes  *   3) allocate the next available block on the block rotor for the
1884df8bae1dSRodney W. Grimes  *      specified cylinder group.
1885df8bae1dSRodney W. Grimes  * Note that this routine only allocates fs_bsize blocks; these
1886df8bae1dSRodney W. Grimes  * blocks may be fragmented by the routine that allocates them.
1887df8bae1dSRodney W. Grimes  */
18881c85e6a3SKirk McKusick static ufs2_daddr_t
ffs_alloccgblk(struct inode * ip,struct buf * bp,ufs2_daddr_t bpref,int size)1889064e6b43SKirk McKusick ffs_alloccgblk(struct inode *ip,
1890064e6b43SKirk McKusick 	struct buf *bp,
1891064e6b43SKirk McKusick 	ufs2_daddr_t bpref,
1892064e6b43SKirk McKusick 	int size)
1893df8bae1dSRodney W. Grimes {
1894b1897c19SJulian Elischer 	struct fs *fs;
1895b1897c19SJulian Elischer 	struct cg *cgp;
18968e37fbadSJeff Roberson 	struct ufsmount *ump;
18971c85e6a3SKirk McKusick 	ufs1_daddr_t bno;
18981c85e6a3SKirk McKusick 	ufs2_daddr_t blkno;
1899831b1ff7SKirk McKusick 	uint8_t *blksfree;
1900baa12a84SKirk McKusick 	int i, cgbpref;
1901df8bae1dSRodney W. Grimes 
1902e1db6897SKonstantin Belousov 	ump = ITOUMP(ip);
1903e1db6897SKonstantin Belousov 	fs = ump->um_fs;
19048e37fbadSJeff Roberson 	mtx_assert(UFS_MTX(ump), MA_OWNED);
1905b1897c19SJulian Elischer 	cgp = (struct cg *)bp->b_data;
19069f043878SKirk McKusick 	blksfree = cg_blksfree(cgp);
1907baa12a84SKirk McKusick 	if (bpref == 0) {
19083f8db5b1SKirk McKusick 		bpref = cgbase(fs, cgp->cg_cgx) + cgp->cg_rotor + fs->fs_frag;
1909baa12a84SKirk McKusick 	} else if ((cgbpref = dtog(fs, bpref)) != cgp->cg_cgx) {
1910baa12a84SKirk McKusick 		/* map bpref to correct zone in this cg */
1911baa12a84SKirk McKusick 		if (bpref < cgdata(fs, cgbpref))
1912baa12a84SKirk McKusick 			bpref = cgmeta(fs, cgp->cg_cgx);
1913baa12a84SKirk McKusick 		else
1914baa12a84SKirk McKusick 			bpref = cgdata(fs, cgp->cg_cgx);
1915baa12a84SKirk McKusick 	}
1916df8bae1dSRodney W. Grimes 	/*
1917df8bae1dSRodney W. Grimes 	 * if the requested block is available, use it
1918df8bae1dSRodney W. Grimes 	 */
1919baa12a84SKirk McKusick 	bno = dtogd(fs, blknum(fs, bpref));
19201c85e6a3SKirk McKusick 	if (ffs_isblock(fs, blksfree, fragstoblks(fs, bno)))
1921df8bae1dSRodney W. Grimes 		goto gotit;
1922df8bae1dSRodney W. Grimes 	/*
19231c85e6a3SKirk McKusick 	 * Take the next available block in this cylinder group.
1924df8bae1dSRodney W. Grimes 	 */
1925df8bae1dSRodney W. Grimes 	bno = ffs_mapsearch(fs, cgp, bpref, (int)fs->fs_frag);
1926df8bae1dSRodney W. Grimes 	if (bno < 0)
19276ab46d52SBruce Evans 		return (0);
1928baa12a84SKirk McKusick 	/* Update cg_rotor only if allocated from the data zone */
1929baa12a84SKirk McKusick 	if (bno >= dtogd(fs, cgdata(fs, cgp->cg_cgx)))
1930df8bae1dSRodney W. Grimes 		cgp->cg_rotor = bno;
1931df8bae1dSRodney W. Grimes gotit:
1932df8bae1dSRodney W. Grimes 	blkno = fragstoblks(fs, bno);
19339f043878SKirk McKusick 	ffs_clrblock(fs, blksfree, (long)blkno);
1934113db2ddSJeff Roberson 	ffs_clusteracct(fs, cgp, blkno, -1);
1935df8bae1dSRodney W. Grimes 	cgp->cg_cs.cs_nbfree--;
1936df8bae1dSRodney W. Grimes 	fs->fs_cstotal.cs_nbfree--;
1937df8bae1dSRodney W. Grimes 	fs->fs_cs(fs, cgp->cg_cgx).cs_nbfree--;
1938df8bae1dSRodney W. Grimes 	fs->fs_fmod = 1;
1939364ed814SKirk McKusick 	blkno = cgbase(fs, cgp->cg_cgx) + bno;
1940113db2ddSJeff Roberson 	/*
1941113db2ddSJeff Roberson 	 * If the caller didn't want the whole block free the frags here.
1942113db2ddSJeff Roberson 	 */
1943113db2ddSJeff Roberson 	size = numfrags(fs, size);
1944113db2ddSJeff Roberson 	if (size != fs->fs_frag) {
1945113db2ddSJeff Roberson 		bno = dtogd(fs, blkno);
1946113db2ddSJeff Roberson 		for (i = size; i < fs->fs_frag; i++)
1947113db2ddSJeff Roberson 			setbit(blksfree, bno + i);
1948113db2ddSJeff Roberson 		i = fs->fs_frag - size;
1949113db2ddSJeff Roberson 		cgp->cg_cs.cs_nffree += i;
1950113db2ddSJeff Roberson 		fs->fs_cstotal.cs_nffree += i;
1951113db2ddSJeff Roberson 		fs->fs_cs(fs, cgp->cg_cgx).cs_nffree += i;
1952113db2ddSJeff Roberson 		fs->fs_fmod = 1;
1953113db2ddSJeff Roberson 		cgp->cg_frsum[i]++;
1954113db2ddSJeff Roberson 	}
19558e37fbadSJeff Roberson 	/* XXX Fixme. */
19568e37fbadSJeff Roberson 	UFS_UNLOCK(ump);
1957b1897c19SJulian Elischer 	if (DOINGSOFTDEP(ITOV(ip)))
19587e038bc2SKirk McKusick 		softdep_setup_blkmapdep(bp, UFSTOVFS(ump), blkno, size, 0);
19598e37fbadSJeff Roberson 	UFS_LOCK(ump);
1960b1897c19SJulian Elischer 	return (blkno);
1961df8bae1dSRodney W. Grimes }
1962df8bae1dSRodney W. Grimes 
1963df8bae1dSRodney W. Grimes /*
1964df8bae1dSRodney W. Grimes  * Determine whether a cluster can be allocated.
1965df8bae1dSRodney W. Grimes  *
1966df8bae1dSRodney W. Grimes  * We do not currently check for optimal rotational layout if there
1967df8bae1dSRodney W. Grimes  * are multiple choices in the same cylinder group. Instead we just
1968df8bae1dSRodney W. Grimes  * take the first one that we find following bpref.
1969df8bae1dSRodney W. Grimes  */
19701c85e6a3SKirk McKusick static ufs2_daddr_t
ffs_clusteralloc(struct inode * ip,uint64_t cg,ufs2_daddr_t bpref,int len)1971064e6b43SKirk McKusick ffs_clusteralloc(struct inode *ip,
1972831b1ff7SKirk McKusick 	uint64_t cg,
1973064e6b43SKirk McKusick 	ufs2_daddr_t bpref,
1974064e6b43SKirk McKusick 	int len)
1975df8bae1dSRodney W. Grimes {
197605f4ff5dSPoul-Henning Kamp 	struct fs *fs;
197705f4ff5dSPoul-Henning Kamp 	struct cg *cgp;
1978df8bae1dSRodney W. Grimes 	struct buf *bp;
19798e37fbadSJeff Roberson 	struct ufsmount *ump;
19809c4f551eSKirk McKusick 	int i, run, bit, map, got, error;
19811c85e6a3SKirk McKusick 	ufs2_daddr_t bno;
1982831b1ff7SKirk McKusick 	uint8_t *mapp;
1983996c772fSJohn Dyson 	int32_t *lp;
1984831b1ff7SKirk McKusick 	uint8_t *blksfree;
1985df8bae1dSRodney W. Grimes 
1986e1db6897SKonstantin Belousov 	ump = ITOUMP(ip);
1987e1db6897SKonstantin Belousov 	fs = ump->um_fs;
1988dc37121dSKonstantin Belousov 	MPASS(cg < fs->fs_ncg);
1989996c772fSJohn Dyson 	if (fs->fs_maxcluster[cg] < len)
1990369dc8ceSEivind Eklund 		return (0);
19918e37fbadSJeff Roberson 	UFS_UNLOCK(ump);
199244d37182SKirk McKusick 	if ((error = ffs_getcg(fs, ump->um_devvp, cg, 0, &bp, &cgp)) != 0) {
1993c3046779SKirk McKusick 		ffs_checkcgintegrity(fs, cg, error);
19949c4f551eSKirk McKusick 		UFS_LOCK(ump);
19959c4f551eSKirk McKusick 		return (0);
19969c4f551eSKirk McKusick 	}
1997df8bae1dSRodney W. Grimes 	/*
1998df8bae1dSRodney W. Grimes 	 * Check to see if a cluster of the needed size (or bigger) is
1999df8bae1dSRodney W. Grimes 	 * available in this cylinder group.
2000df8bae1dSRodney W. Grimes 	 */
2001996c772fSJohn Dyson 	lp = &cg_clustersum(cgp)[len];
2002df8bae1dSRodney W. Grimes 	for (i = len; i <= fs->fs_contigsumsize; i++)
2003996c772fSJohn Dyson 		if (*lp++ > 0)
2004df8bae1dSRodney W. Grimes 			break;
2005996c772fSJohn Dyson 	if (i > fs->fs_contigsumsize) {
2006996c772fSJohn Dyson 		/*
2007996c772fSJohn Dyson 		 * This is the first time looking for a cluster in this
2008996c772fSJohn Dyson 		 * cylinder group. Update the cluster summary information
2009996c772fSJohn Dyson 		 * to reflect the true maximum sized cluster so that
2010996c772fSJohn Dyson 		 * future cluster allocation requests can avoid reading
2011996c772fSJohn Dyson 		 * the cylinder group map only to find no clusters.
2012996c772fSJohn Dyson 		 */
2013996c772fSJohn Dyson 		lp = &cg_clustersum(cgp)[len - 1];
2014996c772fSJohn Dyson 		for (i = len - 1; i > 0; i--)
2015996c772fSJohn Dyson 			if (*lp-- > 0)
2016996c772fSJohn Dyson 				break;
20178e37fbadSJeff Roberson 		UFS_LOCK(ump);
2018996c772fSJohn Dyson 		fs->fs_maxcluster[cg] = i;
20199c4f551eSKirk McKusick 		brelse(bp);
20209c4f551eSKirk McKusick 		return (0);
2021996c772fSJohn Dyson 	}
2022df8bae1dSRodney W. Grimes 	/*
2023df8bae1dSRodney W. Grimes 	 * Search the cluster map to find a big enough cluster.
2024df8bae1dSRodney W. Grimes 	 * We take the first one that we find, even if it is larger
2025df8bae1dSRodney W. Grimes 	 * than we need as we prefer to get one close to the previous
2026df8bae1dSRodney W. Grimes 	 * block allocation. We do not search before the current
2027df8bae1dSRodney W. Grimes 	 * preference point as we do not want to allocate a block
2028df8bae1dSRodney W. Grimes 	 * that is allocated before the previous one (as we will
2029df8bae1dSRodney W. Grimes 	 * then have to wait for another pass of the elevator
2030df8bae1dSRodney W. Grimes 	 * algorithm before it will be read). We prefer to fail and
2031df8bae1dSRodney W. Grimes 	 * be recalled to try an allocation in the next cylinder group.
2032df8bae1dSRodney W. Grimes 	 */
2033df8bae1dSRodney W. Grimes 	if (dtog(fs, bpref) != cg)
2034baa12a84SKirk McKusick 		bpref = cgdata(fs, cg);
2035df8bae1dSRodney W. Grimes 	else
2036baa12a84SKirk McKusick 		bpref = blknum(fs, bpref);
2037baa12a84SKirk McKusick 	bpref = fragstoblks(fs, dtogd(fs, bpref));
2038df8bae1dSRodney W. Grimes 	mapp = &cg_clustersfree(cgp)[bpref / NBBY];
2039df8bae1dSRodney W. Grimes 	map = *mapp++;
2040df8bae1dSRodney W. Grimes 	bit = 1 << (bpref % NBBY);
2041996c772fSJohn Dyson 	for (run = 0, got = bpref; got < cgp->cg_nclusterblks; got++) {
2042df8bae1dSRodney W. Grimes 		if ((map & bit) == 0) {
2043df8bae1dSRodney W. Grimes 			run = 0;
2044df8bae1dSRodney W. Grimes 		} else {
2045df8bae1dSRodney W. Grimes 			run++;
2046df8bae1dSRodney W. Grimes 			if (run == len)
2047df8bae1dSRodney W. Grimes 				break;
2048df8bae1dSRodney W. Grimes 		}
2049996c772fSJohn Dyson 		if ((got & (NBBY - 1)) != (NBBY - 1)) {
2050df8bae1dSRodney W. Grimes 			bit <<= 1;
2051df8bae1dSRodney W. Grimes 		} else {
2052df8bae1dSRodney W. Grimes 			map = *mapp++;
2053df8bae1dSRodney W. Grimes 			bit = 1;
2054df8bae1dSRodney W. Grimes 		}
2055df8bae1dSRodney W. Grimes 	}
20569c4f551eSKirk McKusick 	if (got >= cgp->cg_nclusterblks) {
20579c4f551eSKirk McKusick 		UFS_LOCK(ump);
20589c4f551eSKirk McKusick 		brelse(bp);
20599c4f551eSKirk McKusick 		return (0);
20609c4f551eSKirk McKusick 	}
2061df8bae1dSRodney W. Grimes 	/*
2062df8bae1dSRodney W. Grimes 	 * Allocate the cluster that we have found.
2063df8bae1dSRodney W. Grimes 	 */
20649f043878SKirk McKusick 	blksfree = cg_blksfree(cgp);
2065996c772fSJohn Dyson 	for (i = 1; i <= len; i++)
20669f043878SKirk McKusick 		if (!ffs_isblock(fs, blksfree, got - run + i))
2067996c772fSJohn Dyson 			panic("ffs_clusteralloc: map mismatch");
2068364ed814SKirk McKusick 	bno = cgbase(fs, cg) + blkstofrags(fs, got - run + 1);
2069996c772fSJohn Dyson 	if (dtog(fs, bno) != cg)
2070996c772fSJohn Dyson 		panic("ffs_clusteralloc: allocated out of group");
2071df8bae1dSRodney W. Grimes 	len = blkstofrags(fs, len);
20728e37fbadSJeff Roberson 	UFS_LOCK(ump);
2073df8bae1dSRodney W. Grimes 	for (i = 0; i < len; i += fs->fs_frag)
2074113db2ddSJeff Roberson 		if (ffs_alloccgblk(ip, bp, bno + i, fs->fs_bsize) != bno + i)
2075df8bae1dSRodney W. Grimes 			panic("ffs_clusteralloc: lost block");
20768e37fbadSJeff Roberson 	ACTIVECLEAR(fs, cg);
20778e37fbadSJeff Roberson 	UFS_UNLOCK(ump);
207839e68756SDavid Greenman 	bdwrite(bp);
2079df8bae1dSRodney W. Grimes 	return (bno);
2080df8bae1dSRodney W. Grimes }
2081df8bae1dSRodney W. Grimes 
208294f4ac21SKonstantin Belousov static inline struct buf *
getinobuf(struct inode * ip,uint64_t cg,uint32_t cginoblk,int gbflags)2083064e6b43SKirk McKusick getinobuf(struct inode *ip,
2084831b1ff7SKirk McKusick 	uint64_t cg,
2085831b1ff7SKirk McKusick 	uint32_t cginoblk,
2086064e6b43SKirk McKusick 	int gbflags)
208794f4ac21SKonstantin Belousov {
208894f4ac21SKonstantin Belousov 	struct fs *fs;
208994f4ac21SKonstantin Belousov 
2090e1db6897SKonstantin Belousov 	fs = ITOFS(ip);
2091e1db6897SKonstantin Belousov 	return (getblk(ITODEVVP(ip), fsbtodb(fs, ino_to_fsba(fs,
209294f4ac21SKonstantin Belousov 	    cg * fs->fs_ipg + cginoblk)), (int)fs->fs_bsize, 0, 0,
209394f4ac21SKonstantin Belousov 	    gbflags));
209494f4ac21SKonstantin Belousov }
209594f4ac21SKonstantin Belousov 
2096df8bae1dSRodney W. Grimes /*
2097b6fbf003SMark Johnston  * Synchronous inode initialization is needed only when barrier writes do not
2098b6fbf003SMark Johnston  * work as advertised, and will impose a heavy cost on file creation in a newly
2099b6fbf003SMark Johnston  * created filesystem.
2100b6fbf003SMark Johnston  */
2101b6fbf003SMark Johnston static int doasyncinodeinit = 1;
2102b6fbf003SMark Johnston SYSCTL_INT(_vfs_ffs, OID_AUTO, doasyncinodeinit, CTLFLAG_RWTUN,
2103b6fbf003SMark Johnston     &doasyncinodeinit, 0,
2104b6fbf003SMark Johnston     "Perform inode block initialization using asynchronous writes");
2105b6fbf003SMark Johnston 
2106b6fbf003SMark Johnston /*
2107df8bae1dSRodney W. Grimes  * Determine whether an inode can be allocated.
2108df8bae1dSRodney W. Grimes  *
2109df8bae1dSRodney W. Grimes  * Check to see if an inode is available, and if it is,
2110df8bae1dSRodney W. Grimes  * allocate it using the following policy:
2111df8bae1dSRodney W. Grimes  *   1) allocate the requested inode.
2112df8bae1dSRodney W. Grimes  *   2) allocate the next available inode after the requested
2113df8bae1dSRodney W. Grimes  *      inode in the specified cylinder group.
2114df8bae1dSRodney W. Grimes  */
21155006e776SKirk McKusick static ufs2_daddr_t
ffs_nodealloccg(struct inode * ip,uint64_t cg,ufs2_daddr_t ipref,int mode,int unused)2116064e6b43SKirk McKusick ffs_nodealloccg(struct inode *ip,
2117831b1ff7SKirk McKusick 	uint64_t cg,
2118064e6b43SKirk McKusick 	ufs2_daddr_t ipref,
2119064e6b43SKirk McKusick 	int mode,
2120064e6b43SKirk McKusick 	int unused)
2121df8bae1dSRodney W. Grimes {
212205f4ff5dSPoul-Henning Kamp 	struct fs *fs;
212305f4ff5dSPoul-Henning Kamp 	struct cg *cgp;
21241c85e6a3SKirk McKusick 	struct buf *bp, *ibp;
21258e37fbadSJeff Roberson 	struct ufsmount *ump;
2126831b1ff7SKirk McKusick 	uint8_t *inosused, *loc;
21271c85e6a3SKirk McKusick 	struct ufs2_dinode *dp2;
21288f8d3027SEd Schouten 	int error, start, len, i;
2129831b1ff7SKirk McKusick 	uint32_t old_initediblk;
2130df8bae1dSRodney W. Grimes 
2131e1db6897SKonstantin Belousov 	ump = ITOUMP(ip);
2132e1db6897SKonstantin Belousov 	fs = ump->um_fs;
213394f4ac21SKonstantin Belousov check_nifree:
2134df8bae1dSRodney W. Grimes 	if (fs->fs_cs(fs, cg).cs_nifree == 0)
21356ab46d52SBruce Evans 		return (0);
21368e37fbadSJeff Roberson 	UFS_UNLOCK(ump);
213744d37182SKirk McKusick 	if ((error = ffs_getcg(fs, ump->um_devvp, cg, 0, &bp, &cgp)) != 0) {
2138c3046779SKirk McKusick 		ffs_checkcgintegrity(fs, cg, error);
21398e37fbadSJeff Roberson 		UFS_LOCK(ump);
21406ab46d52SBruce Evans 		return (0);
2141df8bae1dSRodney W. Grimes 	}
214294f4ac21SKonstantin Belousov restart:
21439c4f551eSKirk McKusick 	if (cgp->cg_cs.cs_nifree == 0) {
2144df8bae1dSRodney W. Grimes 		brelse(bp);
21458e37fbadSJeff Roberson 		UFS_LOCK(ump);
21466ab46d52SBruce Evans 		return (0);
2147df8bae1dSRodney W. Grimes 	}
21489f043878SKirk McKusick 	inosused = cg_inosused(cgp);
2149df8bae1dSRodney W. Grimes 	if (ipref) {
2150df8bae1dSRodney W. Grimes 		ipref %= fs->fs_ipg;
21519f043878SKirk McKusick 		if (isclr(inosused, ipref))
2152df8bae1dSRodney W. Grimes 			goto gotit;
2153df8bae1dSRodney W. Grimes 	}
2154df8bae1dSRodney W. Grimes 	start = cgp->cg_irotor / NBBY;
2155df8bae1dSRodney W. Grimes 	len = howmany(fs->fs_ipg - cgp->cg_irotor, NBBY);
21568f8d3027SEd Schouten 	loc = memcchr(&inosused[start], 0xff, len);
21578f8d3027SEd Schouten 	if (loc == NULL) {
2158df8bae1dSRodney W. Grimes 		len = start + 1;
2159df8bae1dSRodney W. Grimes 		start = 0;
21608f8d3027SEd Schouten 		loc = memcchr(&inosused[start], 0xff, len);
21618f8d3027SEd Schouten 		if (loc == NULL) {
2162831b1ff7SKirk McKusick 			printf("cg = %ju, irotor = %ld, fs = %s\n",
2163831b1ff7SKirk McKusick 			    (intmax_t)cg, (long)cgp->cg_irotor, fs->fs_fsmnt);
2164df8bae1dSRodney W. Grimes 			panic("ffs_nodealloccg: map corrupted");
2165df8bae1dSRodney W. Grimes 			/* NOTREACHED */
2166df8bae1dSRodney W. Grimes 		}
2167df8bae1dSRodney W. Grimes 	}
21688f8d3027SEd Schouten 	ipref = (loc - inosused) * NBBY + ffs(~*loc) - 1;
2169df8bae1dSRodney W. Grimes gotit:
21701c85e6a3SKirk McKusick 	/*
21711c85e6a3SKirk McKusick 	 * Check to see if we need to initialize more inodes.
21721c85e6a3SKirk McKusick 	 */
21731c85e6a3SKirk McKusick 	if (fs->fs_magic == FS_UFS2_MAGIC &&
21741c85e6a3SKirk McKusick 	    ipref + INOPB(fs) > cgp->cg_initediblk &&
21751c85e6a3SKirk McKusick 	    cgp->cg_initediblk < cgp->cg_niblk) {
217694f4ac21SKonstantin Belousov 		old_initediblk = cgp->cg_initediblk;
217794f4ac21SKonstantin Belousov 
217894f4ac21SKonstantin Belousov 		/*
217994f4ac21SKonstantin Belousov 		 * Free the cylinder group lock before writing the
218094f4ac21SKonstantin Belousov 		 * initialized inode block.  Entering the
218194f4ac21SKonstantin Belousov 		 * babarrierwrite() with the cylinder group lock
218294f4ac21SKonstantin Belousov 		 * causes lock order violation between the lock and
218394f4ac21SKonstantin Belousov 		 * snaplk.
218494f4ac21SKonstantin Belousov 		 *
218594f4ac21SKonstantin Belousov 		 * Another thread can decide to initialize the same
218694f4ac21SKonstantin Belousov 		 * inode block, but whichever thread first gets the
218794f4ac21SKonstantin Belousov 		 * cylinder group lock after writing the newly
218894f4ac21SKonstantin Belousov 		 * allocated inode block will update it and the other
218994f4ac21SKonstantin Belousov 		 * will realize that it has lost and leave the
219094f4ac21SKonstantin Belousov 		 * cylinder group unchanged.
219194f4ac21SKonstantin Belousov 		 */
219294f4ac21SKonstantin Belousov 		ibp = getinobuf(ip, cg, old_initediblk, GB_LOCK_NOWAIT);
219394f4ac21SKonstantin Belousov 		brelse(bp);
219494f4ac21SKonstantin Belousov 		if (ibp == NULL) {
219594f4ac21SKonstantin Belousov 			/*
219694f4ac21SKonstantin Belousov 			 * The inode block buffer is already owned by
219794f4ac21SKonstantin Belousov 			 * another thread, which must initialize it.
219894f4ac21SKonstantin Belousov 			 * Wait on the buffer to allow another thread
219994f4ac21SKonstantin Belousov 			 * to finish the updates, with dropped cg
220094f4ac21SKonstantin Belousov 			 * buffer lock, then retry.
220194f4ac21SKonstantin Belousov 			 */
220294f4ac21SKonstantin Belousov 			ibp = getinobuf(ip, cg, old_initediblk, 0);
220394f4ac21SKonstantin Belousov 			brelse(ibp);
220494f4ac21SKonstantin Belousov 			UFS_LOCK(ump);
220594f4ac21SKonstantin Belousov 			goto check_nifree;
220694f4ac21SKonstantin Belousov 		}
22071c85e6a3SKirk McKusick 		bzero(ibp->b_data, (int)fs->fs_bsize);
22081c85e6a3SKirk McKusick 		dp2 = (struct ufs2_dinode *)(ibp->b_data);
22091c85e6a3SKirk McKusick 		for (i = 0; i < INOPB(fs); i++) {
221057d2ac2fSKevin Lo 			while (dp2->di_gen == 0)
221157d2ac2fSKevin Lo 				dp2->di_gen = arc4random();
22121c85e6a3SKirk McKusick 			dp2++;
22131c85e6a3SKirk McKusick 		}
2214b6fbf003SMark Johnston 
22157839b23fSKirk McKusick 		/*
22167839b23fSKirk McKusick 		 * Rather than adding a soft updates dependency to ensure
22177839b23fSKirk McKusick 		 * that the new inode block is written before it is claimed
22187839b23fSKirk McKusick 		 * by the cylinder group map, we just do a barrier write
22197839b23fSKirk McKusick 		 * here. The barrier write will ensure that the inode block
22207839b23fSKirk McKusick 		 * gets written before the updated cylinder group map can be
22217839b23fSKirk McKusick 		 * written. The barrier write should only slow down bulk
22227839b23fSKirk McKusick 		 * loading of newly created filesystems.
22237839b23fSKirk McKusick 		 */
2224b6fbf003SMark Johnston 		if (doasyncinodeinit)
22257839b23fSKirk McKusick 			babarrierwrite(ibp);
2226b6fbf003SMark Johnston 		else
2227b6fbf003SMark Johnston 			bwrite(ibp);
222894f4ac21SKonstantin Belousov 
222994f4ac21SKonstantin Belousov 		/*
223094f4ac21SKonstantin Belousov 		 * After the inode block is written, try to update the
223194f4ac21SKonstantin Belousov 		 * cg initediblk pointer.  If another thread beat us
223294f4ac21SKonstantin Belousov 		 * to it, then leave it unchanged as the other thread
223394f4ac21SKonstantin Belousov 		 * has already set it correctly.
223494f4ac21SKonstantin Belousov 		 */
223544d37182SKirk McKusick 		error = ffs_getcg(fs, ump->um_devvp, cg, 0, &bp, &cgp);
223694f4ac21SKonstantin Belousov 		UFS_LOCK(ump);
223794f4ac21SKonstantin Belousov 		ACTIVECLEAR(fs, cg);
223894f4ac21SKonstantin Belousov 		UFS_UNLOCK(ump);
22399c4f551eSKirk McKusick 		if (error != 0)
224094f4ac21SKonstantin Belousov 			return (error);
224194f4ac21SKonstantin Belousov 		if (cgp->cg_initediblk == old_initediblk)
224294f4ac21SKonstantin Belousov 			cgp->cg_initediblk += INOPB(fs);
224394f4ac21SKonstantin Belousov 		goto restart;
224494f4ac21SKonstantin Belousov 	}
224594f4ac21SKonstantin Belousov 	cgp->cg_irotor = ipref;
22468e37fbadSJeff Roberson 	UFS_LOCK(ump);
22478e37fbadSJeff Roberson 	ACTIVECLEAR(fs, cg);
22488e37fbadSJeff Roberson 	setbit(inosused, ipref);
22498e37fbadSJeff Roberson 	cgp->cg_cs.cs_nifree--;
22508e37fbadSJeff Roberson 	fs->fs_cstotal.cs_nifree--;
22518e37fbadSJeff Roberson 	fs->fs_cs(fs, cg).cs_nifree--;
22528e37fbadSJeff Roberson 	fs->fs_fmod = 1;
2253d8ba45e2SEd Maste 	if ((mode & IFMT) == IFDIR) {
22548e37fbadSJeff Roberson 		cgp->cg_cs.cs_ndir++;
22558e37fbadSJeff Roberson 		fs->fs_cstotal.cs_ndir++;
22568e37fbadSJeff Roberson 		fs->fs_cs(fs, cg).cs_ndir++;
22578e37fbadSJeff Roberson 	}
22588e37fbadSJeff Roberson 	UFS_UNLOCK(ump);
22598e37fbadSJeff Roberson 	if (DOINGSOFTDEP(ITOV(ip)))
226016f7d822SJeff Roberson 		softdep_setup_inomapdep(bp, ip, cg * fs->fs_ipg + ipref, mode);
2261df8bae1dSRodney W. Grimes 	bdwrite(bp);
2262e870d1e6SKirk McKusick 	return ((ino_t)(cg * fs->fs_ipg + ipref));
2263df8bae1dSRodney W. Grimes }
2264df8bae1dSRodney W. Grimes 
2265df8bae1dSRodney W. Grimes /*
2266df8bae1dSRodney W. Grimes  * Free a block or fragment.
2267df8bae1dSRodney W. Grimes  *
2268df8bae1dSRodney W. Grimes  * The specified block or fragment is placed back in the
2269df8bae1dSRodney W. Grimes  * free map. If a fragment is deallocated, a possible
2270df8bae1dSRodney W. Grimes  * block reassembly is checked.
2271df8bae1dSRodney W. Grimes  */
22728c2a54deSKonstantin Belousov static void
ffs_blkfree_cg(struct ufsmount * ump,struct fs * fs,struct vnode * devvp,ufs2_daddr_t bno,long size,ino_t inum,struct workhead * dephd)2273064e6b43SKirk McKusick ffs_blkfree_cg(struct ufsmount *ump,
2274064e6b43SKirk McKusick 	struct fs *fs,
2275064e6b43SKirk McKusick 	struct vnode *devvp,
2276064e6b43SKirk McKusick 	ufs2_daddr_t bno,
2277064e6b43SKirk McKusick 	long size,
2278064e6b43SKirk McKusick 	ino_t inum,
2279064e6b43SKirk McKusick 	struct workhead *dephd)
2280df8bae1dSRodney W. Grimes {
2281113db2ddSJeff Roberson 	struct mount *mp;
2282c9f96392SKirk McKusick 	struct cg *cgp;
2283df8bae1dSRodney W. Grimes 	struct buf *bp;
2284d79ff54bSChuck Silvers 	daddr_t dbn;
22851c85e6a3SKirk McKusick 	ufs1_daddr_t fragno, cgbno;
22869c4f551eSKirk McKusick 	int i, blk, frags, bbase, error;
2287831b1ff7SKirk McKusick 	uint64_t cg;
2288831b1ff7SKirk McKusick 	uint8_t *blksfree;
228989c9c53dSPoul-Henning Kamp 	struct cdev *dev;
2290df8bae1dSRodney W. Grimes 
2291c9f96392SKirk McKusick 	cg = dtog(fs, bno);
22928a3f2c37SEdward Tomasz Napierala 	if (devvp->v_type == VREG) {
2293c9f96392SKirk McKusick 		/* devvp is a snapshot */
2294e1db6897SKonstantin Belousov 		MPASS(devvp->v_mount->mnt_data == ump);
2295e1db6897SKonstantin Belousov 		dev = ump->um_devvp->v_rdev;
2296bf9c87c8SKonstantin Belousov 	} else if (devvp->v_type == VCHR) {
229776b05e3eSKonstantin Belousov 		/*
229876b05e3eSKonstantin Belousov 		 * devvp is a normal disk device
229976b05e3eSKonstantin Belousov 		 * XXXKIB: devvp is not locked there, v_rdev access depends on
230076b05e3eSKonstantin Belousov 		 * busy mount, which prevents mntfs devvp from reclamation.
230176b05e3eSKonstantin Belousov 		 */
2302c9f96392SKirk McKusick 		dev = devvp->v_rdev;
2303bf9c87c8SKonstantin Belousov 	} else
2304bf9c87c8SKonstantin Belousov 		return;
23051102b89bSDavid E. O'Brien #ifdef INVARIANTS
2306831b1ff7SKirk McKusick 	if ((uint64_t)size > fs->fs_bsize || fragoff(fs, size) != 0 ||
2307b1897c19SJulian Elischer 	    fragnum(fs, bno) + numfrags(fs, size) > fs->fs_frag) {
230847a56126SDavid E. O'Brien 		printf("dev=%s, bno = %jd, bsize = %ld, size = %ld, fs = %s\n",
23091c85e6a3SKirk McKusick 		    devtoname(dev), (intmax_t)bno, (long)fs->fs_bsize,
2310c9f96392SKirk McKusick 		    size, fs->fs_fsmnt);
231167702352SKirk McKusick 		panic("ffs_blkfree_cg: invalid size");
2312df8bae1dSRodney W. Grimes 	}
2313f2a2857bSKirk McKusick #endif
2314831b1ff7SKirk McKusick 	if ((uint64_t)bno >= fs->fs_size) {
2315831b1ff7SKirk McKusick 		printf("bad block %jd, ino %ju\n", (intmax_t)bno,
2316831b1ff7SKirk McKusick 		    (intmax_t)inum);
2317c9f96392SKirk McKusick 		ffs_fserr(fs, inum, "bad block");
2318df8bae1dSRodney W. Grimes 		return;
2319df8bae1dSRodney W. Grimes 	}
2320d79ff54bSChuck Silvers 	if ((error = ffs_getcg(fs, devvp, cg, GB_CVTENXIO, &bp, &cgp)) != 0) {
2321d4a8f5bfSKirk McKusick 		if (!MOUNTEDSOFTDEP(UFSTOVFS(ump)) || devvp->v_type != VCHR)
2322df8bae1dSRodney W. Grimes 			return;
2323d4a8f5bfSKirk McKusick 		/*
2324d4a8f5bfSKirk McKusick 		 * Would like to just downgrade to read-only. Until that
2325d4a8f5bfSKirk McKusick 		 * capability is available, just toss the cylinder group
2326d4a8f5bfSKirk McKusick 		 * update and mark the filesystem as needing to run fsck.
2327d4a8f5bfSKirk McKusick 		 */
2328d4a8f5bfSKirk McKusick 		fs->fs_flags |= FS_NEEDSFSCK;
2329d79ff54bSChuck Silvers 		if (devvp->v_type == VREG)
2330d79ff54bSChuck Silvers 			dbn = fragstoblks(fs, cgtod(fs, cg));
2331d79ff54bSChuck Silvers 		else
2332d79ff54bSChuck Silvers 			dbn = fsbtodb(fs, cgtod(fs, cg));
2333d79ff54bSChuck Silvers 		error = getblkx(devvp, dbn, dbn, fs->fs_cgsize, 0, 0, 0, &bp);
2334d79ff54bSChuck Silvers 		KASSERT(error == 0, ("getblkx failed"));
2335d79ff54bSChuck Silvers 		softdep_setup_blkfree(UFSTOVFS(ump), bp, bno,
2336d4a8f5bfSKirk McKusick 		    numfrags(fs, size), dephd, true);
2337d79ff54bSChuck Silvers 		bp->b_flags |= B_RELBUF | B_NOCACHE;
2338d79ff54bSChuck Silvers 		bp->b_flags &= ~B_CACHE;
2339d79ff54bSChuck Silvers 		bawrite(bp);
2340d79ff54bSChuck Silvers 		return;
2341d79ff54bSChuck Silvers 	}
23427e72e991SKirk McKusick 	cgbno = dtogd(fs, bno);
23439f043878SKirk McKusick 	blksfree = cg_blksfree(cgp);
23448e37fbadSJeff Roberson 	UFS_LOCK(ump);
2345df8bae1dSRodney W. Grimes 	if (size == fs->fs_bsize) {
23467e72e991SKirk McKusick 		fragno = fragstoblks(fs, cgbno);
23477e72e991SKirk McKusick 		if (!ffs_isfreeblock(fs, blksfree, fragno)) {
23488a3f2c37SEdward Tomasz Napierala 			if (devvp->v_type == VREG) {
23498e37fbadSJeff Roberson 				UFS_UNLOCK(ump);
2350c9f96392SKirk McKusick 				/* devvp is a snapshot */
2351c9f96392SKirk McKusick 				brelse(bp);
2352c9f96392SKirk McKusick 				return;
2353c9f96392SKirk McKusick 			}
2354cfbf0a46SMaxime Henrion 			printf("dev = %s, block = %jd, fs = %s\n",
23551c85e6a3SKirk McKusick 			    devtoname(dev), (intmax_t)bno, fs->fs_fsmnt);
235643a3cc77SKirk McKusick 			panic("ffs_blkfree_cg: freeing free block");
2357df8bae1dSRodney W. Grimes 		}
23587e72e991SKirk McKusick 		ffs_setblock(fs, blksfree, fragno);
2359113db2ddSJeff Roberson 		ffs_clusteracct(fs, cgp, fragno, 1);
2360df8bae1dSRodney W. Grimes 		cgp->cg_cs.cs_nbfree++;
2361df8bae1dSRodney W. Grimes 		fs->fs_cstotal.cs_nbfree++;
2362df8bae1dSRodney W. Grimes 		fs->fs_cs(fs, cg).cs_nbfree++;
2363df8bae1dSRodney W. Grimes 	} else {
23647e72e991SKirk McKusick 		bbase = cgbno - fragnum(fs, cgbno);
2365df8bae1dSRodney W. Grimes 		/*
2366df8bae1dSRodney W. Grimes 		 * decrement the counts associated with the old frags
2367df8bae1dSRodney W. Grimes 		 */
23689f043878SKirk McKusick 		blk = blkmap(fs, blksfree, bbase);
2369df8bae1dSRodney W. Grimes 		ffs_fragacct(fs, blk, cgp->cg_frsum, -1);
2370df8bae1dSRodney W. Grimes 		/*
2371df8bae1dSRodney W. Grimes 		 * deallocate the fragment
2372df8bae1dSRodney W. Grimes 		 */
2373df8bae1dSRodney W. Grimes 		frags = numfrags(fs, size);
2374df8bae1dSRodney W. Grimes 		for (i = 0; i < frags; i++) {
23757e72e991SKirk McKusick 			if (isset(blksfree, cgbno + i)) {
2376cfbf0a46SMaxime Henrion 				printf("dev = %s, block = %jd, fs = %s\n",
23771c85e6a3SKirk McKusick 				    devtoname(dev), (intmax_t)(bno + i),
2378ac1e407bSBruce Evans 				    fs->fs_fsmnt);
237943a3cc77SKirk McKusick 				panic("ffs_blkfree_cg: freeing free frag");
2380df8bae1dSRodney W. Grimes 			}
23817e72e991SKirk McKusick 			setbit(blksfree, cgbno + i);
2382df8bae1dSRodney W. Grimes 		}
2383df8bae1dSRodney W. Grimes 		cgp->cg_cs.cs_nffree += i;
2384df8bae1dSRodney W. Grimes 		fs->fs_cstotal.cs_nffree += i;
2385df8bae1dSRodney W. Grimes 		fs->fs_cs(fs, cg).cs_nffree += i;
2386df8bae1dSRodney W. Grimes 		/*
2387df8bae1dSRodney W. Grimes 		 * add back in counts associated with the new frags
2388df8bae1dSRodney W. Grimes 		 */
23899f043878SKirk McKusick 		blk = blkmap(fs, blksfree, bbase);
2390df8bae1dSRodney W. Grimes 		ffs_fragacct(fs, blk, cgp->cg_frsum, 1);
2391df8bae1dSRodney W. Grimes 		/*
2392df8bae1dSRodney W. Grimes 		 * if a complete block has been reassembled, account for it
2393df8bae1dSRodney W. Grimes 		 */
23947e72e991SKirk McKusick 		fragno = fragstoblks(fs, bbase);
23957e72e991SKirk McKusick 		if (ffs_isblock(fs, blksfree, fragno)) {
2396df8bae1dSRodney W. Grimes 			cgp->cg_cs.cs_nffree -= fs->fs_frag;
2397df8bae1dSRodney W. Grimes 			fs->fs_cstotal.cs_nffree -= fs->fs_frag;
2398df8bae1dSRodney W. Grimes 			fs->fs_cs(fs, cg).cs_nffree -= fs->fs_frag;
2399113db2ddSJeff Roberson 			ffs_clusteracct(fs, cgp, fragno, 1);
2400df8bae1dSRodney W. Grimes 			cgp->cg_cs.cs_nbfree++;
2401df8bae1dSRodney W. Grimes 			fs->fs_cstotal.cs_nbfree++;
2402df8bae1dSRodney W. Grimes 			fs->fs_cs(fs, cg).cs_nbfree++;
2403df8bae1dSRodney W. Grimes 		}
2404df8bae1dSRodney W. Grimes 	}
2405df8bae1dSRodney W. Grimes 	fs->fs_fmod = 1;
24068e37fbadSJeff Roberson 	ACTIVECLEAR(fs, cg);
24078e37fbadSJeff Roberson 	UFS_UNLOCK(ump);
2408113db2ddSJeff Roberson 	mp = UFSTOVFS(ump);
2409bf9c87c8SKonstantin Belousov 	if (MOUNTEDSOFTDEP(mp) && devvp->v_type == VCHR)
2410113db2ddSJeff Roberson 		softdep_setup_blkfree(UFSTOVFS(ump), bp, bno,
2411d4a8f5bfSKirk McKusick 		    numfrags(fs, size), dephd, false);
2412df8bae1dSRodney W. Grimes 	bdwrite(bp);
2413df8bae1dSRodney W. Grimes }
2414df8bae1dSRodney W. Grimes 
24157e038bc2SKirk McKusick /*
24167e038bc2SKirk McKusick  * Structures and routines associated with trim management.
2417fc6e1715SKirk McKusick  *
2418fc6e1715SKirk McKusick  * The following requests are passed to trim_lookup to indicate
2419fc6e1715SKirk McKusick  * the actions that should be taken.
24207e038bc2SKirk McKusick  */
2421fc6e1715SKirk McKusick #define	NEW	1	/* if found, error else allocate and hash it */
2422fc6e1715SKirk McKusick #define	OLD	2	/* if not found, error, else return it */
2423fc6e1715SKirk McKusick #define	REPLACE	3	/* if not found, error else unhash and reallocate it */
2424fc6e1715SKirk McKusick #define	DONE	4	/* if not found, error else unhash and return it */
2425fc6e1715SKirk McKusick #define	SINGLE	5	/* don't look up, just allocate it and don't hash it */
2426fc6e1715SKirk McKusick 
24277e038bc2SKirk McKusick MALLOC_DEFINE(M_TRIM, "ufs_trim", "UFS trim structures");
24287e038bc2SKirk McKusick 
24297e038bc2SKirk McKusick #define	TRIMLIST_HASH(ump, key) \
24307e038bc2SKirk McKusick 	(&(ump)->um_trimhash[(key) & (ump)->um_trimlisthashsize])
24317e038bc2SKirk McKusick 
2432fc6e1715SKirk McKusick /*
2433fc6e1715SKirk McKusick  * These structures describe each of the block free requests aggregated
2434fc6e1715SKirk McKusick  * together to make up a trim request.
2435fc6e1715SKirk McKusick  */
2436fc6e1715SKirk McKusick struct trim_blkreq {
2437fc6e1715SKirk McKusick 	TAILQ_ENTRY(trim_blkreq) blkreqlist;
24388c2a54deSKonstantin Belousov 	ufs2_daddr_t bno;
24398c2a54deSKonstantin Belousov 	long size;
24408c2a54deSKonstantin Belousov 	struct workhead *pdephd;
24418c2a54deSKonstantin Belousov 	struct workhead dephd;
24428c2a54deSKonstantin Belousov };
24438c2a54deSKonstantin Belousov 
2444fc6e1715SKirk McKusick /*
2445fc6e1715SKirk McKusick  * Description of a trim request.
2446fc6e1715SKirk McKusick  */
2447fc6e1715SKirk McKusick struct ffs_blkfree_trim_params {
2448fc6e1715SKirk McKusick 	TAILQ_HEAD(, trim_blkreq) blklist;
2449fc6e1715SKirk McKusick 	LIST_ENTRY(ffs_blkfree_trim_params) hashlist;
2450fc6e1715SKirk McKusick 	struct task task;
2451fc6e1715SKirk McKusick 	struct ufsmount *ump;
2452fc6e1715SKirk McKusick 	struct vnode *devvp;
2453fc6e1715SKirk McKusick 	ino_t inum;
2454fc6e1715SKirk McKusick 	ufs2_daddr_t bno;
2455fc6e1715SKirk McKusick 	long size;
2456fc6e1715SKirk McKusick 	long key;
2457fc6e1715SKirk McKusick };
24588c2a54deSKonstantin Belousov 
2459fc6e1715SKirk McKusick static void	ffs_blkfree_trim_completed(struct buf *);
2460fc6e1715SKirk McKusick static void	ffs_blkfree_trim_task(void *ctx, int pending __unused);
2461fc6e1715SKirk McKusick static struct	ffs_blkfree_trim_params *trim_lookup(struct ufsmount *,
2462831b1ff7SKirk McKusick 		    struct vnode *, ufs2_daddr_t, long, ino_t, uint64_t, int);
2463fc6e1715SKirk McKusick static void	ffs_blkfree_sendtrim(struct ffs_blkfree_trim_params *);
24648c2a54deSKonstantin Belousov 
2465fc6e1715SKirk McKusick /*
2466fc6e1715SKirk McKusick  * Called on trim completion to start a task to free the associated block(s).
2467fc6e1715SKirk McKusick  */
24688c2a54deSKonstantin Belousov static void
ffs_blkfree_trim_completed(struct buf * bp)2469064e6b43SKirk McKusick ffs_blkfree_trim_completed(struct buf *bp)
24708c2a54deSKonstantin Belousov {
24718c2a54deSKonstantin Belousov 	struct ffs_blkfree_trim_params *tp;
24728c2a54deSKonstantin Belousov 
247306753bd3SWarner Losh 	tp = bp->b_fsprivate1;
24747e038bc2SKirk McKusick 	free(bp, M_TRIM);
24758c2a54deSKonstantin Belousov 	TASK_INIT(&tp->task, 0, ffs_blkfree_trim_task, tp);
2476c79dff0fSKonstantin Belousov 	taskqueue_enqueue(tp->ump->um_trim_tq, &tp->task);
24778c2a54deSKonstantin Belousov }
24788c2a54deSKonstantin Belousov 
24797e038bc2SKirk McKusick /*
2480fc6e1715SKirk McKusick  * Trim completion task that free associated block(s).
2481fc6e1715SKirk McKusick  */
2482fc6e1715SKirk McKusick static void
ffs_blkfree_trim_task(void * ctx,int pending)2483064e6b43SKirk McKusick ffs_blkfree_trim_task(void *ctx, int pending)
2484fc6e1715SKirk McKusick {
2485fc6e1715SKirk McKusick 	struct ffs_blkfree_trim_params *tp;
2486fc6e1715SKirk McKusick 	struct trim_blkreq *blkelm;
2487fc6e1715SKirk McKusick 	struct ufsmount *ump;
2488fc6e1715SKirk McKusick 
2489fc6e1715SKirk McKusick 	tp = ctx;
2490fc6e1715SKirk McKusick 	ump = tp->ump;
2491fc6e1715SKirk McKusick 	while ((blkelm = TAILQ_FIRST(&tp->blklist)) != NULL) {
2492fc6e1715SKirk McKusick 		ffs_blkfree_cg(ump, ump->um_fs, tp->devvp, blkelm->bno,
2493fc6e1715SKirk McKusick 		    blkelm->size, tp->inum, blkelm->pdephd);
2494fc6e1715SKirk McKusick 		TAILQ_REMOVE(&tp->blklist, blkelm, blkreqlist);
2495fc6e1715SKirk McKusick 		free(blkelm, M_TRIM);
2496fc6e1715SKirk McKusick 	}
2497fc6e1715SKirk McKusick 	vn_finished_secondary_write(UFSTOVFS(ump));
2498fc6e1715SKirk McKusick 	UFS_LOCK(ump);
2499fc6e1715SKirk McKusick 	ump->um_trim_inflight -= 1;
2500fc6e1715SKirk McKusick 	ump->um_trim_inflight_blks -= numfrags(ump->um_fs, tp->size);
2501fc6e1715SKirk McKusick 	UFS_UNLOCK(ump);
2502fc6e1715SKirk McKusick 	free(tp, M_TRIM);
2503fc6e1715SKirk McKusick }
2504fc6e1715SKirk McKusick 
2505fc6e1715SKirk McKusick /*
2506fc6e1715SKirk McKusick  * Lookup a trim request by inode number.
2507fc6e1715SKirk McKusick  * Allocate if requested (NEW, REPLACE, SINGLE).
2508fc6e1715SKirk McKusick  */
2509fc6e1715SKirk McKusick static struct ffs_blkfree_trim_params *
trim_lookup(struct ufsmount * ump,struct vnode * devvp,ufs2_daddr_t bno,long size,ino_t inum,uint64_t key,int alloctype)2510064e6b43SKirk McKusick trim_lookup(struct ufsmount *ump,
2511064e6b43SKirk McKusick 	struct vnode *devvp,
2512064e6b43SKirk McKusick 	ufs2_daddr_t bno,
2513064e6b43SKirk McKusick 	long size,
2514064e6b43SKirk McKusick 	ino_t inum,
2515831b1ff7SKirk McKusick 	uint64_t key,
2516064e6b43SKirk McKusick 	int alloctype)
2517fc6e1715SKirk McKusick {
2518fc6e1715SKirk McKusick 	struct trimlist_hashhead *tphashhead;
2519fc6e1715SKirk McKusick 	struct ffs_blkfree_trim_params *tp, *ntp;
2520fc6e1715SKirk McKusick 
2521fc6e1715SKirk McKusick 	ntp = malloc(sizeof(struct ffs_blkfree_trim_params), M_TRIM, M_WAITOK);
2522fc6e1715SKirk McKusick 	if (alloctype != SINGLE) {
2523fc6e1715SKirk McKusick 		KASSERT(key >= FIRST_VALID_KEY, ("trim_lookup: invalid key"));
2524fc6e1715SKirk McKusick 		UFS_LOCK(ump);
2525fc6e1715SKirk McKusick 		tphashhead = TRIMLIST_HASH(ump, key);
2526fc6e1715SKirk McKusick 		LIST_FOREACH(tp, tphashhead, hashlist)
2527fc6e1715SKirk McKusick 			if (key == tp->key)
2528fc6e1715SKirk McKusick 				break;
2529fc6e1715SKirk McKusick 	}
2530fc6e1715SKirk McKusick 	switch (alloctype) {
2531fc6e1715SKirk McKusick 	case NEW:
2532fc6e1715SKirk McKusick 		KASSERT(tp == NULL, ("trim_lookup: found trim"));
2533fc6e1715SKirk McKusick 		break;
2534fc6e1715SKirk McKusick 	case OLD:
2535fc6e1715SKirk McKusick 		KASSERT(tp != NULL,
2536fc6e1715SKirk McKusick 		    ("trim_lookup: missing call to ffs_blkrelease_start()"));
2537fc6e1715SKirk McKusick 		UFS_UNLOCK(ump);
2538fc6e1715SKirk McKusick 		free(ntp, M_TRIM);
2539fc6e1715SKirk McKusick 		return (tp);
2540fc6e1715SKirk McKusick 	case REPLACE:
2541fc6e1715SKirk McKusick 		KASSERT(tp != NULL, ("trim_lookup: missing REPLACE trim"));
2542fc6e1715SKirk McKusick 		LIST_REMOVE(tp, hashlist);
2543fc6e1715SKirk McKusick 		/* tp will be freed by caller */
2544fc6e1715SKirk McKusick 		break;
2545fc6e1715SKirk McKusick 	case DONE:
2546fc6e1715SKirk McKusick 		KASSERT(tp != NULL, ("trim_lookup: missing DONE trim"));
2547fc6e1715SKirk McKusick 		LIST_REMOVE(tp, hashlist);
2548fc6e1715SKirk McKusick 		UFS_UNLOCK(ump);
2549fc6e1715SKirk McKusick 		free(ntp, M_TRIM);
2550fc6e1715SKirk McKusick 		return (tp);
2551fc6e1715SKirk McKusick 	}
2552fc6e1715SKirk McKusick 	TAILQ_INIT(&ntp->blklist);
2553fc6e1715SKirk McKusick 	ntp->ump = ump;
2554fc6e1715SKirk McKusick 	ntp->devvp = devvp;
2555fc6e1715SKirk McKusick 	ntp->bno = bno;
2556fc6e1715SKirk McKusick 	ntp->size = size;
2557fc6e1715SKirk McKusick 	ntp->inum = inum;
2558fc6e1715SKirk McKusick 	ntp->key = key;
2559fc6e1715SKirk McKusick 	if (alloctype != SINGLE) {
2560fc6e1715SKirk McKusick 		LIST_INSERT_HEAD(tphashhead, ntp, hashlist);
2561fc6e1715SKirk McKusick 		UFS_UNLOCK(ump);
2562fc6e1715SKirk McKusick 	}
2563fc6e1715SKirk McKusick 	return (ntp);
2564fc6e1715SKirk McKusick }
2565fc6e1715SKirk McKusick 
2566fc6e1715SKirk McKusick /*
2567fc6e1715SKirk McKusick  * Dispatch a trim request.
2568fc6e1715SKirk McKusick  */
2569fc6e1715SKirk McKusick static void
ffs_blkfree_sendtrim(struct ffs_blkfree_trim_params * tp)2570064e6b43SKirk McKusick ffs_blkfree_sendtrim(struct ffs_blkfree_trim_params *tp)
2571fc6e1715SKirk McKusick {
2572fc6e1715SKirk McKusick 	struct ufsmount *ump;
2573fc6e1715SKirk McKusick 	struct mount *mp;
2574fc6e1715SKirk McKusick 	struct buf *bp;
2575fc6e1715SKirk McKusick 
2576fc6e1715SKirk McKusick 	/*
2577fc6e1715SKirk McKusick 	 * Postpone the set of the free bit in the cg bitmap until the
2578fc6e1715SKirk McKusick 	 * BIO_DELETE is completed.  Otherwise, due to disk queue
2579fc6e1715SKirk McKusick 	 * reordering, TRIM might be issued after we reuse the block
2580fc6e1715SKirk McKusick 	 * and write some new data into it.
2581fc6e1715SKirk McKusick 	 */
2582fc6e1715SKirk McKusick 	ump = tp->ump;
2583fc6e1715SKirk McKusick 	bp = malloc(sizeof(*bp), M_TRIM, M_WAITOK | M_ZERO);
2584fc6e1715SKirk McKusick 	bp->b_iocmd = BIO_DELETE;
2585fc6e1715SKirk McKusick 	bp->b_iooffset = dbtob(fsbtodb(ump->um_fs, tp->bno));
2586fc6e1715SKirk McKusick 	bp->b_iodone = ffs_blkfree_trim_completed;
2587fc6e1715SKirk McKusick 	bp->b_bcount = tp->size;
2588fc6e1715SKirk McKusick 	bp->b_fsprivate1 = tp;
2589fc6e1715SKirk McKusick 	UFS_LOCK(ump);
2590fc6e1715SKirk McKusick 	ump->um_trim_total += 1;
2591fc6e1715SKirk McKusick 	ump->um_trim_inflight += 1;
2592fc6e1715SKirk McKusick 	ump->um_trim_inflight_blks += numfrags(ump->um_fs, tp->size);
2593fc6e1715SKirk McKusick 	ump->um_trim_total_blks += numfrags(ump->um_fs, tp->size);
2594fc6e1715SKirk McKusick 	UFS_UNLOCK(ump);
2595fc6e1715SKirk McKusick 
2596fc6e1715SKirk McKusick 	mp = UFSTOVFS(ump);
2597fc6e1715SKirk McKusick 	vn_start_secondary_write(NULL, &mp, 0);
2598fc6e1715SKirk McKusick 	g_vfs_strategy(ump->um_bo, bp);
2599fc6e1715SKirk McKusick }
2600fc6e1715SKirk McKusick 
2601fc6e1715SKirk McKusick /*
26027e038bc2SKirk McKusick  * Allocate a new key to use to identify a range of blocks.
26037e038bc2SKirk McKusick  */
2604831b1ff7SKirk McKusick uint64_t
ffs_blkrelease_start(struct ufsmount * ump,struct vnode * devvp,ino_t inum)2605064e6b43SKirk McKusick ffs_blkrelease_start(struct ufsmount *ump,
2606064e6b43SKirk McKusick 	struct vnode *devvp,
2607064e6b43SKirk McKusick 	ino_t inum)
26087e038bc2SKirk McKusick {
26097e038bc2SKirk McKusick 	static u_long masterkey;
2610831b1ff7SKirk McKusick 	uint64_t key;
26117e038bc2SKirk McKusick 
2612fc6e1715SKirk McKusick 	if (((ump->um_flags & UM_CANDELETE) == 0) || dotrimcons == 0)
26137e038bc2SKirk McKusick 		return (SINGLETON_KEY);
26147e038bc2SKirk McKusick 	do {
26157e038bc2SKirk McKusick 		key = atomic_fetchadd_long(&masterkey, 1);
26167e038bc2SKirk McKusick 	} while (key < FIRST_VALID_KEY);
2617fc6e1715SKirk McKusick 	(void) trim_lookup(ump, devvp, 0, 0, inum, key, NEW);
26187e038bc2SKirk McKusick 	return (key);
26197e038bc2SKirk McKusick }
26207e038bc2SKirk McKusick 
26217e038bc2SKirk McKusick /*
26227e038bc2SKirk McKusick  * Deallocate a key that has been used to identify a range of blocks.
26237e038bc2SKirk McKusick  */
26248c2a54deSKonstantin Belousov void
ffs_blkrelease_finish(struct ufsmount * ump,uint64_t key)2625831b1ff7SKirk McKusick ffs_blkrelease_finish(struct ufsmount *ump, uint64_t key)
26267e038bc2SKirk McKusick {
2627fc6e1715SKirk McKusick 	struct ffs_blkfree_trim_params *tp;
26287e038bc2SKirk McKusick 
2629fc6e1715SKirk McKusick 	if (((ump->um_flags & UM_CANDELETE) == 0) || dotrimcons == 0)
26307e038bc2SKirk McKusick 		return;
2631fc6e1715SKirk McKusick 	/*
2632bdd6b77eSKirk McKusick 	 * If the vfs.ffs.dotrimcons sysctl option is enabled while
2633bdd6b77eSKirk McKusick 	 * a file deletion is active, specifically after a call
2634bdd6b77eSKirk McKusick 	 * to ffs_blkrelease_start() but before the call to
2635bdd6b77eSKirk McKusick 	 * ffs_blkrelease_finish(), ffs_blkrelease_start() will
2636bdd6b77eSKirk McKusick 	 * have handed out SINGLETON_KEY rather than starting a
2637bdd6b77eSKirk McKusick 	 * collection sequence. Thus if we get a SINGLETON_KEY
2638bdd6b77eSKirk McKusick 	 * passed to ffs_blkrelease_finish(), we just return rather
2639bdd6b77eSKirk McKusick 	 * than trying to finish the nonexistent sequence.
2640bdd6b77eSKirk McKusick 	 */
2641bdd6b77eSKirk McKusick 	if (key == SINGLETON_KEY) {
2642bdd6b77eSKirk McKusick #ifdef INVARIANTS
2643bdd6b77eSKirk McKusick 		printf("%s: vfs.ffs.dotrimcons enabled on active filesystem\n",
2644bdd6b77eSKirk McKusick 		    ump->um_mountp->mnt_stat.f_mntonname);
2645bdd6b77eSKirk McKusick #endif
2646bdd6b77eSKirk McKusick 		return;
2647bdd6b77eSKirk McKusick 	}
2648bdd6b77eSKirk McKusick 	/*
2649fc6e1715SKirk McKusick 	 * We are done with sending blocks using this key. Look up the key
2650fc6e1715SKirk McKusick 	 * using the DONE alloctype (in tp) to request that it be unhashed
2651fc6e1715SKirk McKusick 	 * as we will not be adding to it. If the key has never been used,
2652fc6e1715SKirk McKusick 	 * tp->size will be zero, so we can just free tp. Otherwise the call
2653fc6e1715SKirk McKusick 	 * to ffs_blkfree_sendtrim(tp) causes the block range described by
2654fc6e1715SKirk McKusick 	 * tp to be issued (and then tp to be freed).
2655fc6e1715SKirk McKusick 	 */
2656fc6e1715SKirk McKusick 	tp = trim_lookup(ump, NULL, 0, 0, 0, key, DONE);
2657fc6e1715SKirk McKusick 	if (tp->size == 0)
2658fc6e1715SKirk McKusick 		free(tp, M_TRIM);
2659fc6e1715SKirk McKusick 	else
2660fc6e1715SKirk McKusick 		ffs_blkfree_sendtrim(tp);
26617e038bc2SKirk McKusick }
26627e038bc2SKirk McKusick 
2663fc6e1715SKirk McKusick /*
2664fc6e1715SKirk McKusick  * Setup to free a block or fragment.
2665fc6e1715SKirk McKusick  *
2666fc6e1715SKirk McKusick  * Check for snapshots that might want to claim the block.
2667fc6e1715SKirk McKusick  * If trims are requested, prepare a trim request. Attempt to
2668fc6e1715SKirk McKusick  * aggregate consecutive blocks into a single trim request.
2669fc6e1715SKirk McKusick  */
26707e038bc2SKirk McKusick void
ffs_blkfree(struct ufsmount * ump,struct fs * fs,struct vnode * devvp,ufs2_daddr_t bno,long size,ino_t inum,__enum_uint8 (vtype)vtype,struct workhead * dephd,uint64_t key)2671064e6b43SKirk McKusick ffs_blkfree(struct ufsmount *ump,
2672064e6b43SKirk McKusick 	struct fs *fs,
2673064e6b43SKirk McKusick 	struct vnode *devvp,
2674064e6b43SKirk McKusick 	ufs2_daddr_t bno,
2675064e6b43SKirk McKusick 	long size,
2676064e6b43SKirk McKusick 	ino_t inum,
2677ba8cc6d7SMateusz Guzik 	__enum_uint8(vtype) vtype,
2678064e6b43SKirk McKusick 	struct workhead *dephd,
2679831b1ff7SKirk McKusick 	uint64_t key)
26808c2a54deSKonstantin Belousov {
2681fc6e1715SKirk McKusick 	struct ffs_blkfree_trim_params *tp, *ntp;
2682fc6e1715SKirk McKusick 	struct trim_blkreq *blkelm;
26838c2a54deSKonstantin Belousov 
268499f6ac66SKirk McKusick 	/*
268599f6ac66SKirk McKusick 	 * Check to see if a snapshot wants to claim the block.
268699f6ac66SKirk McKusick 	 * Check that devvp is a normal disk device, not a snapshot,
268799f6ac66SKirk McKusick 	 * it has a snapshot(s) associated with it, and one of the
268899f6ac66SKirk McKusick 	 * snapshots wants to claim the block.
268999f6ac66SKirk McKusick 	 */
2690bf9c87c8SKonstantin Belousov 	if (devvp->v_type == VCHR &&
269199f6ac66SKirk McKusick 	    (devvp->v_vflag & VV_COPYONWRITE) &&
269243a3cc77SKirk McKusick 	    ffs_snapblkfree(fs, devvp, bno, size, inum, vtype, dephd)) {
269399f6ac66SKirk McKusick 		return;
269499f6ac66SKirk McKusick 	}
269517ff0cf7SKirk McKusick 	/*
26967e038bc2SKirk McKusick 	 * Nothing to delay if TRIM is not required for this block or TRIM
26977e038bc2SKirk McKusick 	 * is disabled or the operation is performed on a snapshot.
269817ff0cf7SKirk McKusick 	 */
26997e038bc2SKirk McKusick 	if (key == NOTRIM_KEY || ((ump->um_flags & UM_CANDELETE) == 0) ||
27007e038bc2SKirk McKusick 	    devvp->v_type == VREG) {
27018c2a54deSKonstantin Belousov 		ffs_blkfree_cg(ump, fs, devvp, bno, size, inum, dephd);
27028c2a54deSKonstantin Belousov 		return;
27038c2a54deSKonstantin Belousov 	}
2704fc6e1715SKirk McKusick 	blkelm = malloc(sizeof(struct trim_blkreq), M_TRIM, M_WAITOK);
2705fc6e1715SKirk McKusick 	blkelm->bno = bno;
2706fc6e1715SKirk McKusick 	blkelm->size = size;
2707fc6e1715SKirk McKusick 	if (dephd == NULL) {
2708fc6e1715SKirk McKusick 		blkelm->pdephd = NULL;
2709fc6e1715SKirk McKusick 	} else {
2710fc6e1715SKirk McKusick 		LIST_INIT(&blkelm->dephd);
2711fc6e1715SKirk McKusick 		LIST_SWAP(dephd, &blkelm->dephd, worklist, wk_list);
2712fc6e1715SKirk McKusick 		blkelm->pdephd = &blkelm->dephd;
2713fc6e1715SKirk McKusick 	}
2714fc6e1715SKirk McKusick 	if (key == SINGLETON_KEY) {
27158c2a54deSKonstantin Belousov 		/*
2716fc6e1715SKirk McKusick 		 * Just a single non-contiguous piece. Use the SINGLE
2717fc6e1715SKirk McKusick 		 * alloctype to return a trim request that will not be
2718fc6e1715SKirk McKusick 		 * hashed for future lookup.
27198c2a54deSKonstantin Belousov 		 */
2720fc6e1715SKirk McKusick 		tp = trim_lookup(ump, devvp, bno, size, inum, key, SINGLE);
2721fc6e1715SKirk McKusick 		TAILQ_INSERT_HEAD(&tp->blklist, blkelm, blkreqlist);
2722fc6e1715SKirk McKusick 		ffs_blkfree_sendtrim(tp);
2723fc6e1715SKirk McKusick 		return;
2724fc6e1715SKirk McKusick 	}
2725fc6e1715SKirk McKusick 	/*
2726fc6e1715SKirk McKusick 	 * The callers of this function are not tracking whether or not
2727fc6e1715SKirk McKusick 	 * the blocks are contiguous. They are just saying that they
2728fc6e1715SKirk McKusick 	 * are freeing a set of blocks. It is this code that determines
2729fc6e1715SKirk McKusick 	 * the pieces of that range that are actually contiguous.
2730fc6e1715SKirk McKusick 	 *
2731fc6e1715SKirk McKusick 	 * Calling ffs_blkrelease_start() will have created an entry
2732fc6e1715SKirk McKusick 	 * that we will use.
2733fc6e1715SKirk McKusick 	 */
2734fc6e1715SKirk McKusick 	tp = trim_lookup(ump, devvp, bno, size, inum, key, OLD);
2735fc6e1715SKirk McKusick 	if (tp->size == 0) {
2736fc6e1715SKirk McKusick 		/*
2737fc6e1715SKirk McKusick 		 * First block of a potential range, set block and size
2738fc6e1715SKirk McKusick 		 * for the trim block.
2739fc6e1715SKirk McKusick 		 */
27408c2a54deSKonstantin Belousov 		tp->bno = bno;
27418c2a54deSKonstantin Belousov 		tp->size = size;
2742fc6e1715SKirk McKusick 		TAILQ_INSERT_HEAD(&tp->blklist, blkelm, blkreqlist);
2743fc6e1715SKirk McKusick 		return;
2744fc6e1715SKirk McKusick 	}
2745fc6e1715SKirk McKusick 	/*
2746fc6e1715SKirk McKusick 	 * If this block is a continuation of the range (either
2747fc6e1715SKirk McKusick 	 * follows at the end or preceeds in the front) then we
2748fc6e1715SKirk McKusick 	 * add it to the front or back of the list and return.
2749fc6e1715SKirk McKusick 	 *
2750fc6e1715SKirk McKusick 	 * If it is not a continuation of the trim that we were
2751fc6e1715SKirk McKusick 	 * building, using the REPLACE alloctype, we request that
2752fc6e1715SKirk McKusick 	 * the old trim request (still in tp) be unhashed and a
2753fc6e1715SKirk McKusick 	 * new range started (in ntp). The ffs_blkfree_sendtrim(tp)
2754fc6e1715SKirk McKusick 	 * call causes the block range described by tp to be issued
2755fc6e1715SKirk McKusick 	 * (and then tp to be freed).
2756fc6e1715SKirk McKusick 	 */
2757fc6e1715SKirk McKusick 	if (bno + numfrags(fs, size) == tp->bno) {
2758fc6e1715SKirk McKusick 		TAILQ_INSERT_HEAD(&tp->blklist, blkelm, blkreqlist);
2759fc6e1715SKirk McKusick 		tp->bno = bno;
2760fc6e1715SKirk McKusick 		tp->size += size;
2761fc6e1715SKirk McKusick 		return;
2762fc6e1715SKirk McKusick 	} else if (bno == tp->bno + numfrags(fs, tp->size)) {
2763fc6e1715SKirk McKusick 		TAILQ_INSERT_TAIL(&tp->blklist, blkelm, blkreqlist);
2764fc6e1715SKirk McKusick 		tp->size += size;
2765fc6e1715SKirk McKusick 		return;
2766fc6e1715SKirk McKusick 	}
2767fc6e1715SKirk McKusick 	ntp = trim_lookup(ump, devvp, bno, size, inum, key, REPLACE);
2768fc6e1715SKirk McKusick 	TAILQ_INSERT_HEAD(&ntp->blklist, blkelm, blkreqlist);
2769fc6e1715SKirk McKusick 	ffs_blkfree_sendtrim(tp);
27708c2a54deSKonstantin Belousov }
27718c2a54deSKonstantin Belousov 
27721102b89bSDavid E. O'Brien #ifdef INVARIANTS
2773996c772fSJohn Dyson /*
277467702352SKirk McKusick  * Verify allocation of a block or fragment.
277567702352SKirk McKusick  * Return 1 if block or fragment is free.
2776996c772fSJohn Dyson  */
2777cb451ebdSBruce Evans static int
ffs_checkfreeblk(struct inode * ip,ufs2_daddr_t bno,long size)277867702352SKirk McKusick ffs_checkfreeblk(struct inode *ip,
2779064e6b43SKirk McKusick 	ufs2_daddr_t bno,
2780064e6b43SKirk McKusick 	long size)
2781996c772fSJohn Dyson {
2782996c772fSJohn Dyson 	struct fs *fs;
2783996c772fSJohn Dyson 	struct cg *cgp;
2784996c772fSJohn Dyson 	struct buf *bp;
27851c85e6a3SKirk McKusick 	ufs1_daddr_t cgbno;
2786c3046779SKirk McKusick 	int i, frags, blkalloced;
2787831b1ff7SKirk McKusick 	uint8_t *blksfree;
2788996c772fSJohn Dyson 
2789e1db6897SKonstantin Belousov 	fs = ITOFS(ip);
2790831b1ff7SKirk McKusick 	if ((uint64_t)size > fs->fs_bsize || fragoff(fs, size) != 0) {
2791ac1e407bSBruce Evans 		printf("bsize = %ld, size = %ld, fs = %s\n",
2792ac1e407bSBruce Evans 		    (long)fs->fs_bsize, size, fs->fs_fsmnt);
279367702352SKirk McKusick 		panic("ffs_checkfreeblk: bad size");
2794996c772fSJohn Dyson 	}
2795831b1ff7SKirk McKusick 	if ((uint64_t)bno >= fs->fs_size)
279667702352SKirk McKusick 		panic("ffs_checkfreeblk: too big block %jd", (intmax_t)bno);
2797c3046779SKirk McKusick 	if (ffs_getcg(fs, ITODEVVP(ip), dtog(fs, bno), 0, &bp, &cgp) != 0)
2798c3046779SKirk McKusick 		return (0);
27999f043878SKirk McKusick 	blksfree = cg_blksfree(cgp);
28001c85e6a3SKirk McKusick 	cgbno = dtogd(fs, bno);
2801996c772fSJohn Dyson 	if (size == fs->fs_bsize) {
280267702352SKirk McKusick 		blkalloced = ffs_isblock(fs, blksfree, fragstoblks(fs, cgbno));
2803996c772fSJohn Dyson 	} else {
2804996c772fSJohn Dyson 		frags = numfrags(fs, size);
280567702352SKirk McKusick 		for (blkalloced = 0, i = 0; i < frags; i++)
28061c85e6a3SKirk McKusick 			if (isset(blksfree, cgbno + i))
280767702352SKirk McKusick 				blkalloced++;
280867702352SKirk McKusick 		if (blkalloced != 0 && blkalloced != frags)
280967702352SKirk McKusick 			panic("ffs_checkfreeblk: partially free fragment");
2810996c772fSJohn Dyson 	}
2811996c772fSJohn Dyson 	brelse(bp);
281267702352SKirk McKusick 	return (blkalloced == 0);
2813996c772fSJohn Dyson }
28141102b89bSDavid E. O'Brien #endif /* INVARIANTS */
2815996c772fSJohn Dyson 
2816df8bae1dSRodney W. Grimes /*
2817df8bae1dSRodney W. Grimes  * Free an inode.
2818df8bae1dSRodney W. Grimes  */
2819df8bae1dSRodney W. Grimes int
ffs_vfree(struct vnode * pvp,ino_t ino,int mode)2820064e6b43SKirk McKusick ffs_vfree(struct vnode *pvp,
2821064e6b43SKirk McKusick 	ino_t ino,
2822064e6b43SKirk McKusick 	int mode)
2823df8bae1dSRodney W. Grimes {
2824e1db6897SKonstantin Belousov 	struct ufsmount *ump;
28258e37fbadSJeff Roberson 
2826b1897c19SJulian Elischer 	if (DOINGSOFTDEP(pvp)) {
2827b1897c19SJulian Elischer 		softdep_freefile(pvp, ino, mode);
2828b1897c19SJulian Elischer 		return (0);
2829b1897c19SJulian Elischer 	}
2830e1db6897SKonstantin Belousov 	ump = VFSTOUFS(pvp->v_mount);
2831e1db6897SKonstantin Belousov 	return (ffs_freefile(ump, ump->um_fs, ump->um_devvp, ino, mode, NULL));
2832b1897c19SJulian Elischer }
2833b1897c19SJulian Elischer 
2834b1897c19SJulian Elischer /*
2835b1897c19SJulian Elischer  * Do the actual free operation.
2836b1897c19SJulian Elischer  * The specified inode is placed back in the free map.
2837b1897c19SJulian Elischer  */
2838b1897c19SJulian Elischer int
ffs_freefile(struct ufsmount * ump,struct fs * fs,struct vnode * devvp,ino_t ino,int mode,struct workhead * wkhd)2839064e6b43SKirk McKusick ffs_freefile(struct ufsmount *ump,
2840064e6b43SKirk McKusick 	struct fs *fs,
2841064e6b43SKirk McKusick 	struct vnode *devvp,
2842064e6b43SKirk McKusick 	ino_t ino,
2843064e6b43SKirk McKusick 	int mode,
2844064e6b43SKirk McKusick 	struct workhead *wkhd)
2845b1897c19SJulian Elischer {
2846c9f96392SKirk McKusick 	struct cg *cgp;
2847df8bae1dSRodney W. Grimes 	struct buf *bp;
2848d79ff54bSChuck Silvers 	daddr_t dbn;
2849e870d1e6SKirk McKusick 	int error;
2850831b1ff7SKirk McKusick 	uint64_t cg;
2851831b1ff7SKirk McKusick 	uint8_t *inosused;
285289c9c53dSPoul-Henning Kamp 	struct cdev *dev;
28532bcfb938SChuck Silvers 	ino_t cgino;
2854df8bae1dSRodney W. Grimes 
2855df8bae1dSRodney W. Grimes 	cg = ino_to_cg(fs, ino);
28568a3f2c37SEdward Tomasz Napierala 	if (devvp->v_type == VREG) {
2857c9f96392SKirk McKusick 		/* devvp is a snapshot */
2858e1db6897SKonstantin Belousov 		MPASS(devvp->v_mount->mnt_data == ump);
2859e1db6897SKonstantin Belousov 		dev = ump->um_devvp->v_rdev;
2860bf9c87c8SKonstantin Belousov 	} else if (devvp->v_type == VCHR) {
2861c9f96392SKirk McKusick 		/* devvp is a normal disk device */
2862c9f96392SKirk McKusick 		dev = devvp->v_rdev;
2863bf9c87c8SKonstantin Belousov 	} else {
2864bf9c87c8SKonstantin Belousov 		bp = NULL;
2865bf9c87c8SKonstantin Belousov 		return (0);
2866c9f96392SKirk McKusick 	}
2867e870d1e6SKirk McKusick 	if (ino >= fs->fs_ipg * fs->fs_ncg)
2868fc8fdae0SMatthew D Fleming 		panic("ffs_freefile: range: dev = %s, ino = %ju, fs = %s",
2869fc8fdae0SMatthew D Fleming 		    devtoname(dev), (uintmax_t)ino, fs->fs_fsmnt);
2870d79ff54bSChuck Silvers 	if ((error = ffs_getcg(fs, devvp, cg, GB_CVTENXIO, &bp, &cgp)) != 0) {
2871d4a8f5bfSKirk McKusick 		if (!MOUNTEDSOFTDEP(UFSTOVFS(ump)) || devvp->v_type != VCHR)
2872b1897c19SJulian Elischer 			return (error);
2873d4a8f5bfSKirk McKusick 		/*
2874d4a8f5bfSKirk McKusick 		 * Would like to just downgrade to read-only. Until that
2875d4a8f5bfSKirk McKusick 		 * capability is available, just toss the cylinder group
2876d4a8f5bfSKirk McKusick 		 * update and mark the filesystem as needing to run fsck.
2877d4a8f5bfSKirk McKusick 		 */
2878d4a8f5bfSKirk McKusick 		fs->fs_flags |= FS_NEEDSFSCK;
2879d79ff54bSChuck Silvers 		if (devvp->v_type == VREG)
2880d79ff54bSChuck Silvers 			dbn = fragstoblks(fs, cgtod(fs, cg));
2881d79ff54bSChuck Silvers 		else
2882d79ff54bSChuck Silvers 			dbn = fsbtodb(fs, cgtod(fs, cg));
2883d79ff54bSChuck Silvers 		error = getblkx(devvp, dbn, dbn, fs->fs_cgsize, 0, 0, 0, &bp);
2884d79ff54bSChuck Silvers 		KASSERT(error == 0, ("getblkx failed"));
2885d4a8f5bfSKirk McKusick 		softdep_setup_inofree(UFSTOVFS(ump), bp, ino, wkhd, true);
2886d79ff54bSChuck Silvers 		bp->b_flags |= B_RELBUF | B_NOCACHE;
2887d79ff54bSChuck Silvers 		bp->b_flags &= ~B_CACHE;
2888d79ff54bSChuck Silvers 		bawrite(bp);
2889d79ff54bSChuck Silvers 		return (error);
2890d79ff54bSChuck Silvers 	}
28919f043878SKirk McKusick 	inosused = cg_inosused(cgp);
28922bcfb938SChuck Silvers 	cgino = ino % fs->fs_ipg;
28932bcfb938SChuck Silvers 	if (isclr(inosused, cgino)) {
2894fc8fdae0SMatthew D Fleming 		printf("dev = %s, ino = %ju, fs = %s\n", devtoname(dev),
28952bcfb938SChuck Silvers 		    (uintmax_t)ino, fs->fs_fsmnt);
2896df8bae1dSRodney W. Grimes 		if (fs->fs_ronly == 0)
2897c021e447SKirk McKusick 			panic("ffs_freefile: freeing free inode");
2898df8bae1dSRodney W. Grimes 	}
28992bcfb938SChuck Silvers 	clrbit(inosused, cgino);
29002bcfb938SChuck Silvers 	if (cgino < cgp->cg_irotor)
29012bcfb938SChuck Silvers 		cgp->cg_irotor = cgino;
2902df8bae1dSRodney W. Grimes 	cgp->cg_cs.cs_nifree++;
29038e37fbadSJeff Roberson 	UFS_LOCK(ump);
2904df8bae1dSRodney W. Grimes 	fs->fs_cstotal.cs_nifree++;
2905df8bae1dSRodney W. Grimes 	fs->fs_cs(fs, cg).cs_nifree++;
2906d8ba45e2SEd Maste 	if ((mode & IFMT) == IFDIR) {
2907df8bae1dSRodney W. Grimes 		cgp->cg_cs.cs_ndir--;
2908df8bae1dSRodney W. Grimes 		fs->fs_cstotal.cs_ndir--;
2909df8bae1dSRodney W. Grimes 		fs->fs_cs(fs, cg).cs_ndir--;
2910df8bae1dSRodney W. Grimes 	}
2911df8bae1dSRodney W. Grimes 	fs->fs_fmod = 1;
29128e37fbadSJeff Roberson 	ACTIVECLEAR(fs, cg);
29138e37fbadSJeff Roberson 	UFS_UNLOCK(ump);
2914bf9c87c8SKonstantin Belousov 	if (MOUNTEDSOFTDEP(UFSTOVFS(ump)) && devvp->v_type == VCHR)
2915d4a8f5bfSKirk McKusick 		softdep_setup_inofree(UFSTOVFS(ump), bp, ino, wkhd, false);
2916df8bae1dSRodney W. Grimes 	bdwrite(bp);
2917df8bae1dSRodney W. Grimes 	return (0);
2918df8bae1dSRodney W. Grimes }
2919df8bae1dSRodney W. Grimes 
2920df8bae1dSRodney W. Grimes /*
292137e2ebfdSKirk McKusick  * Check to see if a file is free.
29229c4f551eSKirk McKusick  * Used to check for allocated files in snapshots.
2923d4a8f5bfSKirk McKusick  * Return 1 if file is free.
292437e2ebfdSKirk McKusick  */
292537e2ebfdSKirk McKusick int
ffs_checkfreefile(struct fs * fs,struct vnode * devvp,ino_t ino)2926064e6b43SKirk McKusick ffs_checkfreefile(struct fs *fs,
2927064e6b43SKirk McKusick 	struct vnode *devvp,
2928064e6b43SKirk McKusick 	ino_t ino)
292937e2ebfdSKirk McKusick {
293037e2ebfdSKirk McKusick 	struct cg *cgp;
293137e2ebfdSKirk McKusick 	struct buf *bp;
29329c4f551eSKirk McKusick 	int ret, error;
2933831b1ff7SKirk McKusick 	uint64_t cg;
2934831b1ff7SKirk McKusick 	uint8_t *inosused;
293537e2ebfdSKirk McKusick 
293637e2ebfdSKirk McKusick 	cg = ino_to_cg(fs, ino);
29371ef3a74eSMatt Macy 	if ((devvp->v_type != VREG) && (devvp->v_type != VCHR))
2938bf9c87c8SKonstantin Belousov 		return (1);
2939e870d1e6SKirk McKusick 	if (ino >= fs->fs_ipg * fs->fs_ncg)
294037e2ebfdSKirk McKusick 		return (1);
294144d37182SKirk McKusick 	if ((error = ffs_getcg(fs, devvp, cg, 0, &bp, &cgp)) != 0)
294237e2ebfdSKirk McKusick 		return (1);
294337e2ebfdSKirk McKusick 	inosused = cg_inosused(cgp);
294437e2ebfdSKirk McKusick 	ino %= fs->fs_ipg;
294537e2ebfdSKirk McKusick 	ret = isclr(inosused, ino);
294637e2ebfdSKirk McKusick 	brelse(bp);
294737e2ebfdSKirk McKusick 	return (ret);
294837e2ebfdSKirk McKusick }
294937e2ebfdSKirk McKusick 
295037e2ebfdSKirk McKusick /*
2951df8bae1dSRodney W. Grimes  * Find a block of the specified size in the specified cylinder group.
2952df8bae1dSRodney W. Grimes  *
2953df8bae1dSRodney W. Grimes  * It is a panic if a request is made to find a block if none are
2954df8bae1dSRodney W. Grimes  * available.
2955df8bae1dSRodney W. Grimes  */
29561c85e6a3SKirk McKusick static ufs1_daddr_t
ffs_mapsearch(struct fs * fs,struct cg * cgp,ufs2_daddr_t bpref,int allocsiz)2957064e6b43SKirk McKusick ffs_mapsearch(struct fs *fs,
2958064e6b43SKirk McKusick 	struct cg *cgp,
2959064e6b43SKirk McKusick 	ufs2_daddr_t bpref,
2960064e6b43SKirk McKusick 	int allocsiz)
2961df8bae1dSRodney W. Grimes {
29621c85e6a3SKirk McKusick 	ufs1_daddr_t bno;
2963df8bae1dSRodney W. Grimes 	int start, len, loc, i;
2964df8bae1dSRodney W. Grimes 	int blk, field, subfield, pos;
2965831b1ff7SKirk McKusick 	uint8_t *blksfree;
2966df8bae1dSRodney W. Grimes 
2967df8bae1dSRodney W. Grimes 	/*
2968df8bae1dSRodney W. Grimes 	 * find the fragment by searching through the free block
2969df8bae1dSRodney W. Grimes 	 * map for an appropriate bit pattern
2970df8bae1dSRodney W. Grimes 	 */
2971df8bae1dSRodney W. Grimes 	if (bpref)
2972df8bae1dSRodney W. Grimes 		start = dtogd(fs, bpref) / NBBY;
2973df8bae1dSRodney W. Grimes 	else
2974df8bae1dSRodney W. Grimes 		start = cgp->cg_frotor / NBBY;
29759f043878SKirk McKusick 	blksfree = cg_blksfree(cgp);
2976df8bae1dSRodney W. Grimes 	len = howmany(fs->fs_fpg, NBBY) - start;
2977831b1ff7SKirk McKusick 	loc = scanc((uint64_t)len, (uint8_t *)&blksfree[start],
29782b8c9fa4SStefan Farfeleder 		fragtbl[fs->fs_frag],
2979831b1ff7SKirk McKusick 		(uint8_t)(1 << (allocsiz - 1 + (fs->fs_frag % NBBY))));
2980df8bae1dSRodney W. Grimes 	if (loc == 0) {
2981df8bae1dSRodney W. Grimes 		len = start + 1;
2982df8bae1dSRodney W. Grimes 		start = 0;
2983831b1ff7SKirk McKusick 		loc = scanc((uint64_t)len, (uint8_t *)&blksfree[0],
29842b8c9fa4SStefan Farfeleder 			fragtbl[fs->fs_frag],
2985831b1ff7SKirk McKusick 			(uint8_t)(1 << (allocsiz - 1 + (fs->fs_frag % NBBY))));
2986df8bae1dSRodney W. Grimes 		if (loc == 0) {
2987df8bae1dSRodney W. Grimes 			printf("start = %d, len = %d, fs = %s\n",
2988df8bae1dSRodney W. Grimes 			    start, len, fs->fs_fsmnt);
2989df8bae1dSRodney W. Grimes 			panic("ffs_alloccg: map corrupted");
2990df8bae1dSRodney W. Grimes 			/* NOTREACHED */
2991df8bae1dSRodney W. Grimes 		}
2992df8bae1dSRodney W. Grimes 	}
2993df8bae1dSRodney W. Grimes 	bno = (start + len - loc) * NBBY;
2994df8bae1dSRodney W. Grimes 	cgp->cg_frotor = bno;
2995df8bae1dSRodney W. Grimes 	/*
2996df8bae1dSRodney W. Grimes 	 * found the byte in the map
2997df8bae1dSRodney W. Grimes 	 * sift through the bits to find the selected frag
2998df8bae1dSRodney W. Grimes 	 */
2999df8bae1dSRodney W. Grimes 	for (i = bno + NBBY; bno < i; bno += fs->fs_frag) {
30009f043878SKirk McKusick 		blk = blkmap(fs, blksfree, bno);
3001df8bae1dSRodney W. Grimes 		blk <<= 1;
3002df8bae1dSRodney W. Grimes 		field = around[allocsiz];
3003df8bae1dSRodney W. Grimes 		subfield = inside[allocsiz];
3004df8bae1dSRodney W. Grimes 		for (pos = 0; pos <= fs->fs_frag - allocsiz; pos++) {
3005df8bae1dSRodney W. Grimes 			if ((blk & field) == subfield)
3006df8bae1dSRodney W. Grimes 				return (bno + pos);
3007df8bae1dSRodney W. Grimes 			field <<= 1;
3008df8bae1dSRodney W. Grimes 			subfield <<= 1;
3009df8bae1dSRodney W. Grimes 		}
3010df8bae1dSRodney W. Grimes 	}
3011831b1ff7SKirk McKusick 	printf("bno = %ju, fs = %s\n", (intmax_t)bno, fs->fs_fsmnt);
3012df8bae1dSRodney W. Grimes 	panic("ffs_alloccg: block not in map");
3013df8bae1dSRodney W. Grimes 	return (-1);
3014df8bae1dSRodney W. Grimes }
3015df8bae1dSRodney W. Grimes 
3016df8bae1dSRodney W. Grimes /*
30179c4f551eSKirk McKusick  * Fetch and verify a cylinder group.
30189c4f551eSKirk McKusick  */
30199c4f551eSKirk McKusick int
ffs_getcg(struct fs * fs,struct vnode * devvp,uint64_t cg,int flags,struct buf ** bpp,struct cg ** cgpp)3020064e6b43SKirk McKusick ffs_getcg(struct fs *fs,
3021064e6b43SKirk McKusick 	struct vnode *devvp,
3022831b1ff7SKirk McKusick 	uint64_t cg,
3023064e6b43SKirk McKusick 	int flags,
3024064e6b43SKirk McKusick 	struct buf **bpp,
3025064e6b43SKirk McKusick 	struct cg **cgpp)
30269c4f551eSKirk McKusick {
30279c4f551eSKirk McKusick 	struct buf *bp;
30289c4f551eSKirk McKusick 	struct cg *cgp;
30296dff61a1SKirk McKusick 	struct mount *mp;
30304e13cca5SKonstantin Belousov 	const struct statfs *sfs;
3031d00066a5SKirk McKusick 	daddr_t blkno;
303244d37182SKirk McKusick 	int error;
30339c4f551eSKirk McKusick 
30349c4f551eSKirk McKusick 	*bpp = NULL;
30359c4f551eSKirk McKusick 	*cgpp = NULL;
303675e3597aSKirk McKusick 	if ((fs->fs_metackhash & CK_CYLGRP) != 0)
303775e3597aSKirk McKusick 		flags |= GB_CKHASH;
30386dff61a1SKirk McKusick 	if (devvp->v_type == VCHR) {
3039d00066a5SKirk McKusick 		blkno = fsbtodb(fs, cgtod(fs, cg));
30406dff61a1SKirk McKusick 		mp = devvp->v_rdev->si_mountpt;
30416dff61a1SKirk McKusick 	} else {
30426dff61a1SKirk McKusick 		blkno = fragstoblks(fs, cgtod(fs, cg));
30436dff61a1SKirk McKusick 		mp = devvp->v_mount;
30446dff61a1SKirk McKusick 	}
3045d00066a5SKirk McKusick 	error = breadn_flags(devvp, blkno, blkno, (int)fs->fs_cgsize, NULL,
3046d00066a5SKirk McKusick 	    NULL, 0, NOCRED, flags, ffs_ckhash_cg, &bp);
30479c4f551eSKirk McKusick 	if (error != 0)
30489c4f551eSKirk McKusick 		return (error);
30499c4f551eSKirk McKusick 	cgp = (struct cg *)bp->b_data;
30500d37a428SKirk McKusick 	if ((fs->fs_metackhash & CK_CYLGRP) != 0 &&
305175e3597aSKirk McKusick 	    (bp->b_flags & B_CKHASH) != 0 &&
30520d37a428SKirk McKusick 	    cgp->cg_ckhash != bp->b_ckhash) {
30536dff61a1SKirk McKusick 		if (ppsratecheck(&VFSTOUFS(mp)->um_last_integritymsg,
30546dff61a1SKirk McKusick 		    &VFSTOUFS(mp)->um_secs_integritymsg, 1)) {
30556dff61a1SKirk McKusick 			sfs = &mp->mnt_stat;
30566dff61a1SKirk McKusick 			printf("UFS %s%s (%s) cylinder checkhash failed: "
30576dff61a1SKirk McKusick 			    "cg %ju, cgp: 0x%x != bp: 0x%jx\n",
30584e13cca5SKonstantin Belousov 			    devvp->v_type == VCHR ? "" : "snapshot of ",
30596dff61a1SKirk McKusick 			    sfs->f_mntfromname, sfs->f_mntonname, (intmax_t)cg,
30606dff61a1SKirk McKusick 			    cgp->cg_ckhash, (uintmax_t)bp->b_ckhash);
30616dff61a1SKirk McKusick 		}
306275e3597aSKirk McKusick 		bp->b_flags &= ~B_CKHASH;
306375e3597aSKirk McKusick 		bp->b_flags |= B_INVAL | B_NOCACHE;
30649c4f551eSKirk McKusick 		brelse(bp);
3065c3046779SKirk McKusick 		return (EINTEGRITY);
30669c4f551eSKirk McKusick 	}
30670d37a428SKirk McKusick 	if (!cg_chkmagic(cgp) || cgp->cg_cgx != cg) {
30686dff61a1SKirk McKusick 		if (ppsratecheck(&VFSTOUFS(mp)->um_last_integritymsg,
30696dff61a1SKirk McKusick 		    &VFSTOUFS(mp)->um_secs_integritymsg, 1)) {
30706dff61a1SKirk McKusick 			sfs = &mp->mnt_stat;
30710d37a428SKirk McKusick 			printf("UFS %s%s (%s)",
30720d37a428SKirk McKusick 			    devvp->v_type == VCHR ? "" : "snapshot of ",
30730d37a428SKirk McKusick 			    sfs->f_mntfromname, sfs->f_mntonname);
30740d37a428SKirk McKusick 			if (!cg_chkmagic(cgp))
30756dff61a1SKirk McKusick 				printf(" cg %ju: bad magic number 0x%x should "
30766dff61a1SKirk McKusick 				    "be 0x%x\n", (intmax_t)cg, cgp->cg_magic,
30776dff61a1SKirk McKusick 				    CG_MAGIC);
30780d37a428SKirk McKusick 			else
30796dff61a1SKirk McKusick 				printf(": wrong cylinder group cg %ju != "
30806dff61a1SKirk McKusick 				    "cgx %u\n", (intmax_t)cg, cgp->cg_cgx);
30816dff61a1SKirk McKusick 		}
30820d37a428SKirk McKusick 		bp->b_flags &= ~B_CKHASH;
30830d37a428SKirk McKusick 		bp->b_flags |= B_INVAL | B_NOCACHE;
30840d37a428SKirk McKusick 		brelse(bp);
3085c3046779SKirk McKusick 		return (EINTEGRITY);
30860d37a428SKirk McKusick 	}
308775e3597aSKirk McKusick 	bp->b_flags &= ~B_CKHASH;
30889c4f551eSKirk McKusick 	bp->b_xflags |= BX_BKGRDWRITE;
308947806d1bSKirk McKusick 	/*
309047806d1bSKirk McKusick 	 * If we are using check hashes on the cylinder group then we want
309147806d1bSKirk McKusick 	 * to limit changing the cylinder group time to when we are actually
309247806d1bSKirk McKusick 	 * going to write it to disk so that its check hash remains correct
309347806d1bSKirk McKusick 	 * in memory. If the CK_CYLGRP flag is set the time is updated in
309447806d1bSKirk McKusick 	 * ffs_bufwrite() as the buffer is queued for writing. Otherwise we
309547806d1bSKirk McKusick 	 * update the time here as we have done historically.
309647806d1bSKirk McKusick 	 */
309775e3597aSKirk McKusick 	if ((fs->fs_metackhash & CK_CYLGRP) != 0)
309875e3597aSKirk McKusick 		bp->b_xflags |= BX_CYLGRP;
309947806d1bSKirk McKusick 	else
31009c4f551eSKirk McKusick 		cgp->cg_old_time = cgp->cg_time = time_second;
31019c4f551eSKirk McKusick 	*bpp = bp;
31029c4f551eSKirk McKusick 	*cgpp = cgp;
31039c4f551eSKirk McKusick 	return (0);
31049c4f551eSKirk McKusick }
31059c4f551eSKirk McKusick 
310675e3597aSKirk McKusick static void
ffs_ckhash_cg(struct buf * bp)3107064e6b43SKirk McKusick ffs_ckhash_cg(struct buf *bp)
310875e3597aSKirk McKusick {
310975e3597aSKirk McKusick 	uint32_t ckhash;
311075e3597aSKirk McKusick 	struct cg *cgp;
311175e3597aSKirk McKusick 
311275e3597aSKirk McKusick 	cgp = (struct cg *)bp->b_data;
311375e3597aSKirk McKusick 	ckhash = cgp->cg_ckhash;
311475e3597aSKirk McKusick 	cgp->cg_ckhash = 0;
311575e3597aSKirk McKusick 	bp->b_ckhash = calculate_crc32c(~0L, bp->b_data, bp->b_bcount);
311675e3597aSKirk McKusick 	cgp->cg_ckhash = ckhash;
311775e3597aSKirk McKusick }
311875e3597aSKirk McKusick 
31199c4f551eSKirk McKusick /*
3120c3046779SKirk McKusick  * Called when a cylinder group read has failed. If an integrity check
3121c3046779SKirk McKusick  * is the cause of failure then the cylinder group will not be usable
3122c3046779SKirk McKusick  * until the filesystem has been unmounted and fsck has been run to
3123c3046779SKirk McKusick  * repair it. To avoid future attempts to allocate resources from the
3124c3046779SKirk McKusick  * cylinder group, its available resources are set to zero in the
3125c3046779SKirk McKusick  * superblock summary information. Since it will appear to have no
3126c3046779SKirk McKusick  * resources available, no further calls will be made to allocate
3127c3046779SKirk McKusick  * resources from it. When resources are freed to the cylinder group
3128c3046779SKirk McKusick  * the resource free routines will find the cylinder group unusable so
3129c3046779SKirk McKusick  * the resource will simply be discarded and thus will not show up in
3130c3046779SKirk McKusick  * the superblock summary information until they are recovered by fsck.
3131c3046779SKirk McKusick  */
3132c3046779SKirk McKusick static void
ffs_checkcgintegrity(struct fs * fs,uint64_t cg,int error)3133c3046779SKirk McKusick ffs_checkcgintegrity(struct fs *fs,
3134c3046779SKirk McKusick 	uint64_t cg,
3135c3046779SKirk McKusick 	int error)
3136c3046779SKirk McKusick {
3137c3046779SKirk McKusick 
3138c3046779SKirk McKusick 	if (error != EINTEGRITY)
3139c3046779SKirk McKusick 		return;
3140c3046779SKirk McKusick 	fs->fs_cstotal.cs_nffree -= fs->fs_cs(fs, cg).cs_nffree;
3141c3046779SKirk McKusick 	fs->fs_cs(fs, cg).cs_nffree = 0;
3142c3046779SKirk McKusick 	fs->fs_cstotal.cs_nbfree -= fs->fs_cs(fs, cg).cs_nbfree;
3143c3046779SKirk McKusick 	fs->fs_cs(fs, cg).cs_nbfree = 0;
3144c3046779SKirk McKusick 	fs->fs_cstotal.cs_nifree -= fs->fs_cs(fs, cg).cs_nifree;
3145c3046779SKirk McKusick 	fs->fs_cs(fs, cg).cs_nifree = 0;
3146c3046779SKirk McKusick 	fs->fs_maxcluster[cg] = 0;
3147220427daSKirk McKusick 	fs->fs_flags |= FS_NEEDSFSCK;
3148c3046779SKirk McKusick 	fs->fs_fmod = 1;
3149c3046779SKirk McKusick }
3150c3046779SKirk McKusick 
3151c3046779SKirk McKusick /*
3152df8bae1dSRodney W. Grimes  * Fserr prints the name of a filesystem with an error diagnostic.
3153df8bae1dSRodney W. Grimes  *
3154df8bae1dSRodney W. Grimes  * The form of the error message is:
3155df8bae1dSRodney W. Grimes  *	fs: error message
3156df8bae1dSRodney W. Grimes  */
31572191e465SKirk McKusick void
ffs_fserr(struct fs * fs,ino_t inum,char * cp)3158064e6b43SKirk McKusick ffs_fserr(struct fs *fs,
3159064e6b43SKirk McKusick 	ino_t inum,
3160064e6b43SKirk McKusick 	char *cp)
3161df8bae1dSRodney W. Grimes {
31622a53bfbeSJohn Baldwin 	struct thread *td = curthread;	/* XXX */
31632a53bfbeSJohn Baldwin 	struct proc *p = td->td_proc;
3164df8bae1dSRodney W. Grimes 
3165fc8fdae0SMatthew D Fleming 	log(LOG_ERR, "pid %d (%s), uid %d inumber %ju on %s: %s\n",
3166fc8fdae0SMatthew D Fleming 	    p->p_pid, p->p_comm, td->td_ucred->cr_uid, (uintmax_t)inum,
3167fc8fdae0SMatthew D Fleming 	    fs->fs_fsmnt, cp);
3168df8bae1dSRodney W. Grimes }
3169812b1d41SKirk McKusick 
3170812b1d41SKirk McKusick /*
3171812b1d41SKirk McKusick  * This function provides the capability for the fsck program to
31724a344442SKirk McKusick  * update an active filesystem. Sixteen operations are provided:
3173812b1d41SKirk McKusick  *
3174812b1d41SKirk McKusick  * adjrefcnt(inode, amt) - adjusts the reference count on the
3175812b1d41SKirk McKusick  *	specified inode by the specified amount. Under normal
3176812b1d41SKirk McKusick  *	operation the count should always go down. Decrementing
3177812b1d41SKirk McKusick  *	the count to zero will cause the inode to be freed.
31789f62b10cSKirk McKusick  * adjblkcnt(inode, amt) - adjust the number of blocks used by the
31799f62b10cSKirk McKusick  *	inode by the specified amount.
3180e4a905d1SKirk McKusick  * adjdepth(inode, amt) - adjust the depth of the specified directory
3181e4a905d1SKirk McKusick  *	inode by the specified amount.
318271d11ee3SJohn Baldwin  * setsize(inode, size) - set the size of the inode to the
3183ac4b20a0SKirk McKusick  *	specified size.
3184a16baf37SXin LI  * adjndir, adjbfree, adjifree, adjffree, adjnumclusters(amt) -
3185a16baf37SXin LI  *	adjust the superblock summary.
3186812b1d41SKirk McKusick  * freedirs(inode, count) - directory inodes [inode..inode + count - 1]
3187812b1d41SKirk McKusick  *	are marked as free. Inodes should never have to be marked
3188812b1d41SKirk McKusick  *	as in use.
3189812b1d41SKirk McKusick  * freefiles(inode, count) - file inodes [inode..inode + count - 1]
3190812b1d41SKirk McKusick  *	are marked as free. Inodes should never have to be marked
3191812b1d41SKirk McKusick  *	as in use.
3192812b1d41SKirk McKusick  * freeblks(blockno, size) - blocks [blockno..blockno + size - 1]
3193812b1d41SKirk McKusick  *	are marked as free. Blocks should never have to be marked
3194812b1d41SKirk McKusick  *	as in use.
3195812b1d41SKirk McKusick  * setflags(flags, set/clear) - the fs_flags field has the specified
3196812b1d41SKirk McKusick  *	flags set (second parameter +1) or cleared (second parameter -1).
3197e268f54cSKirk McKusick  * setcwd(dirinode) - set the current directory to dirinode in the
3198e268f54cSKirk McKusick  *	filesystem associated with the snapshot.
3199e268f54cSKirk McKusick  * setdotdot(oldvalue, newvalue) - Verify that the inode number for ".."
3200e268f54cSKirk McKusick  *	in the current directory is oldvalue then change it to newvalue.
3201e268f54cSKirk McKusick  * unlink(nameptr, oldvalue) - Verify that the inode number associated
3202e268f54cSKirk McKusick  *	with nameptr in the current directory is oldvalue then unlink it.
3203812b1d41SKirk McKusick  */
3204812b1d41SKirk McKusick 
32056f1e8551SAlfred Perlstein static int sysctl_ffs_fsck(SYSCTL_HANDLER_ARGS);
3206812b1d41SKirk McKusick 
32077029da5cSPawel Biernacki SYSCTL_PROC(_vfs_ffs, FFS_ADJ_REFCNT, adjrefcnt,
32087029da5cSPawel Biernacki     CTLFLAG_WR | CTLTYPE_STRUCT | CTLFLAG_NEEDGIANT,
32097029da5cSPawel Biernacki     0, 0, sysctl_ffs_fsck, "S,fsck",
32107029da5cSPawel Biernacki     "Adjust Inode Reference Count");
3211812b1d41SKirk McKusick 
32127029da5cSPawel Biernacki static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_BLKCNT, adjblkcnt,
32137029da5cSPawel Biernacki     CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
32147029da5cSPawel Biernacki     "Adjust Inode Used Blocks Count");
3215812b1d41SKirk McKusick 
3216e4a905d1SKirk McKusick static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_DEPTH, adjdepth,
3217e4a905d1SKirk McKusick     CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
3218e4a905d1SKirk McKusick     "Adjust Directory Inode Depth");
3219e4a905d1SKirk McKusick 
32207029da5cSPawel Biernacki static SYSCTL_NODE(_vfs_ffs, FFS_SET_SIZE, setsize,
32217029da5cSPawel Biernacki     CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
32227029da5cSPawel Biernacki     "Set the inode size");
3223ac4b20a0SKirk McKusick 
32247029da5cSPawel Biernacki static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NDIR, adjndir,
32257029da5cSPawel Biernacki     CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
32267029da5cSPawel Biernacki     "Adjust number of directories");
3227a16baf37SXin LI 
32287029da5cSPawel Biernacki static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NBFREE, adjnbfree,
32297029da5cSPawel Biernacki     CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
32307029da5cSPawel Biernacki     "Adjust number of free blocks");
3231a16baf37SXin LI 
32327029da5cSPawel Biernacki static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NIFREE, adjnifree,
32337029da5cSPawel Biernacki     CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
32347029da5cSPawel Biernacki     "Adjust number of free inodes");
3235a16baf37SXin LI 
32367029da5cSPawel Biernacki static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NFFREE, adjnffree,
32377029da5cSPawel Biernacki     CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
32387029da5cSPawel Biernacki     "Adjust number of free frags");
3239a16baf37SXin LI 
32407029da5cSPawel Biernacki static SYSCTL_NODE(_vfs_ffs, FFS_ADJ_NUMCLUSTERS, adjnumclusters,
32417029da5cSPawel Biernacki     CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
32427029da5cSPawel Biernacki     "Adjust number of free clusters");
3243a16baf37SXin LI 
32447029da5cSPawel Biernacki static SYSCTL_NODE(_vfs_ffs, FFS_DIR_FREE, freedirs,
32457029da5cSPawel Biernacki     CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
32467029da5cSPawel Biernacki     "Free Range of Directory Inodes");
3247812b1d41SKirk McKusick 
32487029da5cSPawel Biernacki static SYSCTL_NODE(_vfs_ffs, FFS_FILE_FREE, freefiles,
32497029da5cSPawel Biernacki     CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
32507029da5cSPawel Biernacki     "Free Range of File Inodes");
3251812b1d41SKirk McKusick 
32527029da5cSPawel Biernacki static SYSCTL_NODE(_vfs_ffs, FFS_BLK_FREE, freeblks,
32537029da5cSPawel Biernacki     CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
32547029da5cSPawel Biernacki     "Free Range of Blocks");
3255812b1d41SKirk McKusick 
32567029da5cSPawel Biernacki static SYSCTL_NODE(_vfs_ffs, FFS_SET_FLAGS, setflags,
32577029da5cSPawel Biernacki     CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
32587029da5cSPawel Biernacki     "Change Filesystem Flags");
3259812b1d41SKirk McKusick 
32607029da5cSPawel Biernacki static SYSCTL_NODE(_vfs_ffs, FFS_SET_CWD, setcwd,
32617029da5cSPawel Biernacki     CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
32627029da5cSPawel Biernacki     "Set Current Working Directory");
3263e268f54cSKirk McKusick 
32647029da5cSPawel Biernacki static SYSCTL_NODE(_vfs_ffs, FFS_SET_DOTDOT, setdotdot,
32657029da5cSPawel Biernacki     CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
32667029da5cSPawel Biernacki     "Change Value of .. Entry");
3267e268f54cSKirk McKusick 
32687029da5cSPawel Biernacki static SYSCTL_NODE(_vfs_ffs, FFS_UNLINK, unlink,
32697029da5cSPawel Biernacki     CTLFLAG_WR | CTLFLAG_NEEDGIANT, sysctl_ffs_fsck,
32707029da5cSPawel Biernacki     "Unlink a Duplicate Name");
3271e268f54cSKirk McKusick 
3272af6aeacbSKirk McKusick #ifdef DIAGNOSTIC
32732621f2c4SKirk McKusick static int fsckcmds = 0;
3274af6aeacbSKirk McKusick SYSCTL_INT(_debug, OID_AUTO, ffs_fsckcmds, CTLFLAG_RW, &fsckcmds, 0,
3275af6aeacbSKirk McKusick 	"print out fsck_ffs-based filesystem update commands");
3276af6aeacbSKirk McKusick #endif /* DIAGNOSTIC */
3277812b1d41SKirk McKusick 
3278812b1d41SKirk McKusick static int
sysctl_ffs_fsck(SYSCTL_HANDLER_ARGS)3279812b1d41SKirk McKusick sysctl_ffs_fsck(SYSCTL_HANDLER_ARGS)
3280812b1d41SKirk McKusick {
3281e268f54cSKirk McKusick 	struct thread *td = curthread;
3282812b1d41SKirk McKusick 	struct fsck_cmd cmd;
3283812b1d41SKirk McKusick 	struct ufsmount *ump;
3284f0725a8eSMateusz Guzik 	struct vnode *vp, *dvp, *fdvp;
3285e268f54cSKirk McKusick 	struct inode *ip, *dp;
3286812b1d41SKirk McKusick 	struct mount *mp;
3287812b1d41SKirk McKusick 	struct fs *fs;
32888d03b99bSMateusz Guzik 	struct pwd *pwd;
32891c85e6a3SKirk McKusick 	ufs2_daddr_t blkno;
3290812b1d41SKirk McKusick 	long blkcnt, blksize;
3291831b1ff7SKirk McKusick 	uint64_t key;
3292f2620e9cSJohn Baldwin 	struct file *fp;
32937008be5bSPawel Jakub Dawidek 	cap_rights_t rights;
3294cc91864cSKirk McKusick 	int filetype, error;
3295812b1d41SKirk McKusick 
3296b2f95756SMark Johnston 	if (req->newptr == NULL || req->newlen > sizeof(cmd))
3297812b1d41SKirk McKusick 		return (EBADRPC);
3298b2f95756SMark Johnston 	if ((error = SYSCTL_IN(req, &cmd, sizeof(cmd))) != 0)
3299812b1d41SKirk McKusick 		return (error);
3300812b1d41SKirk McKusick 	if (cmd.version != FFS_CMD_VERSION)
3301812b1d41SKirk McKusick 		return (ERPCMISMATCH);
33024da8456fSMateusz Guzik 	if ((error = getvnode(td, cmd.handle,
33036b3a9a0fSMateusz Guzik 	    cap_rights_init_one(&rights, CAP_FSCK), &fp)) != 0)
3304812b1d41SKirk McKusick 		return (error);
330596474d2aSKonstantin Belousov 	vp = fp->f_vnode;
3306e268f54cSKirk McKusick 	if (vp->v_type != VREG && vp->v_type != VDIR) {
3307e268f54cSKirk McKusick 		fdrop(fp, td);
3308e268f54cSKirk McKusick 		return (EINVAL);
3309e268f54cSKirk McKusick 	}
3310e268f54cSKirk McKusick 	vn_start_write(vp, &mp, V_WAIT);
3311abafa4dbSPedro F. Giffuni 	if (mp == NULL ||
3312abafa4dbSPedro F. Giffuni 	    strncmp(mp->mnt_stat.f_fstypename, "ufs", MFSNAMELEN)) {
3313f0f3f19fSKirk McKusick 		vn_finished_write(mp);
3314e268f54cSKirk McKusick 		fdrop(fp, td);
3315fca26df0SKirk McKusick 		return (EINVAL);
3316f0f3f19fSKirk McKusick 	}
3317927a12aeSKirk McKusick 	ump = VFSTOUFS(mp);
33189acea164SRobert Wing 	if (mp->mnt_flag & MNT_RDONLY) {
3319f0f3f19fSKirk McKusick 		vn_finished_write(mp);
3320e268f54cSKirk McKusick 		fdrop(fp, td);
3321812b1d41SKirk McKusick 		return (EROFS);
3322f0f3f19fSKirk McKusick 	}
3323812b1d41SKirk McKusick 	fs = ump->um_fs;
3324d8ba45e2SEd Maste 	filetype = IFREG;
3325812b1d41SKirk McKusick 
3326812b1d41SKirk McKusick 	switch (oidp->oid_number) {
3327812b1d41SKirk McKusick 	case FFS_SET_FLAGS:
3328af6aeacbSKirk McKusick #ifdef DIAGNOSTIC
3329812b1d41SKirk McKusick 		if (fsckcmds)
3330812b1d41SKirk McKusick 			printf("%s: %s flags\n", mp->mnt_stat.f_mntonname,
3331812b1d41SKirk McKusick 			    cmd.size > 0 ? "set" : "clear");
3332af6aeacbSKirk McKusick #endif /* DIAGNOSTIC */
3333812b1d41SKirk McKusick 		if (cmd.size > 0)
3334812b1d41SKirk McKusick 			fs->fs_flags |= (long)cmd.value;
3335812b1d41SKirk McKusick 		else
3336812b1d41SKirk McKusick 			fs->fs_flags &= ~(long)cmd.value;
3337812b1d41SKirk McKusick 		break;
3338812b1d41SKirk McKusick 
3339812b1d41SKirk McKusick 	case FFS_ADJ_REFCNT:
3340af6aeacbSKirk McKusick #ifdef DIAGNOSTIC
3341812b1d41SKirk McKusick 		if (fsckcmds) {
3342927a12aeSKirk McKusick 			printf("%s: adjust inode %jd link count by %jd\n",
33432daf9dc8SBruce Evans 			    mp->mnt_stat.f_mntonname, (intmax_t)cmd.value,
33442daf9dc8SBruce Evans 			    (intmax_t)cmd.size);
3345812b1d41SKirk McKusick 		}
3346af6aeacbSKirk McKusick #endif /* DIAGNOSTIC */
3347efd6d980SPoul-Henning Kamp 		if ((error = ffs_vget(mp, (ino_t)cmd.value, LK_EXCLUSIVE, &vp)))
3348f0f3f19fSKirk McKusick 			break;
3349812b1d41SKirk McKusick 		ip = VTOI(vp);
3350812b1d41SKirk McKusick 		ip->i_nlink += cmd.size;
335135a30155SKirk McKusick 		DIP_SET_NLINK(ip, ip->i_nlink);
3352812b1d41SKirk McKusick 		ip->i_effnlink += cmd.size;
3353ac4ec141SMateusz Guzik 		UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_MODIFIED);
3354927a12aeSKirk McKusick 		error = ffs_update(vp, 1);
3355812b1d41SKirk McKusick 		if (DOINGSOFTDEP(vp))
3356812b1d41SKirk McKusick 			softdep_change_linkcnt(ip);
3357812b1d41SKirk McKusick 		vput(vp);
3358812b1d41SKirk McKusick 		break;
3359812b1d41SKirk McKusick 
3360812b1d41SKirk McKusick 	case FFS_ADJ_BLKCNT:
3361af6aeacbSKirk McKusick #ifdef DIAGNOSTIC
3362812b1d41SKirk McKusick 		if (fsckcmds) {
33632daf9dc8SBruce Evans 			printf("%s: adjust inode %jd block count by %jd\n",
33642daf9dc8SBruce Evans 			    mp->mnt_stat.f_mntonname, (intmax_t)cmd.value,
33652daf9dc8SBruce Evans 			    (intmax_t)cmd.size);
3366812b1d41SKirk McKusick 		}
3367af6aeacbSKirk McKusick #endif /* DIAGNOSTIC */
3368efd6d980SPoul-Henning Kamp 		if ((error = ffs_vget(mp, (ino_t)cmd.value, LK_EXCLUSIVE, &vp)))
3369f0f3f19fSKirk McKusick 			break;
3370812b1d41SKirk McKusick 		ip = VTOI(vp);
3371b403319bSAlexander Kabaev 		DIP_SET(ip, i_blocks, DIP(ip, i_blocks) + cmd.size);
3372ac4ec141SMateusz Guzik 		UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_MODIFIED);
3373927a12aeSKirk McKusick 		error = ffs_update(vp, 1);
3374812b1d41SKirk McKusick 		vput(vp);
3375812b1d41SKirk McKusick 		break;
3376812b1d41SKirk McKusick 
3377e4a905d1SKirk McKusick 	case FFS_ADJ_DEPTH:
3378e4a905d1SKirk McKusick #ifdef DIAGNOSTIC
3379e4a905d1SKirk McKusick 		if (fsckcmds) {
3380e4a905d1SKirk McKusick 			printf("%s: adjust directory inode %jd depth by %jd\n",
3381e4a905d1SKirk McKusick 			    mp->mnt_stat.f_mntonname, (intmax_t)cmd.value,
3382e4a905d1SKirk McKusick 			    (intmax_t)cmd.size);
3383e4a905d1SKirk McKusick 		}
3384e4a905d1SKirk McKusick #endif /* DIAGNOSTIC */
3385e4a905d1SKirk McKusick 		if ((error = ffs_vget(mp, (ino_t)cmd.value, LK_EXCLUSIVE, &vp)))
3386e4a905d1SKirk McKusick 			break;
3387e4a905d1SKirk McKusick 		if (vp->v_type != VDIR) {
3388e4a905d1SKirk McKusick 			vput(vp);
3389e4a905d1SKirk McKusick 			error = ENOTDIR;
3390e4a905d1SKirk McKusick 			break;
3391e4a905d1SKirk McKusick 		}
3392e4a905d1SKirk McKusick 		ip = VTOI(vp);
3393e4a905d1SKirk McKusick 		DIP_SET(ip, i_dirdepth, DIP(ip, i_dirdepth) + cmd.size);
3394e4a905d1SKirk McKusick 		UFS_INODE_SET_FLAG(ip, IN_CHANGE | IN_MODIFIED);
3395e4a905d1SKirk McKusick 		error = ffs_update(vp, 1);
3396e4a905d1SKirk McKusick 		vput(vp);
3397e4a905d1SKirk McKusick 		break;
3398e4a905d1SKirk McKusick 
3399ac4b20a0SKirk McKusick 	case FFS_SET_SIZE:
3400af6aeacbSKirk McKusick #ifdef DIAGNOSTIC
3401ac4b20a0SKirk McKusick 		if (fsckcmds) {
3402ac4b20a0SKirk McKusick 			printf("%s: set inode %jd size to %jd\n",
3403ac4b20a0SKirk McKusick 			    mp->mnt_stat.f_mntonname, (intmax_t)cmd.value,
3404ac4b20a0SKirk McKusick 			    (intmax_t)cmd.size);
3405ac4b20a0SKirk McKusick 		}
3406af6aeacbSKirk McKusick #endif /* DIAGNOSTIC */
3407ac4b20a0SKirk McKusick 		if ((error = ffs_vget(mp, (ino_t)cmd.value, LK_EXCLUSIVE, &vp)))
3408ac4b20a0SKirk McKusick 			break;
3409ac4b20a0SKirk McKusick 		ip = VTOI(vp);
3410ac4b20a0SKirk McKusick 		DIP_SET(ip, i_size, cmd.size);
341152488b51SKirk McKusick 		UFS_INODE_SET_FLAG(ip, IN_SIZEMOD | IN_CHANGE | IN_MODIFIED);
3412ac4b20a0SKirk McKusick 		error = ffs_update(vp, 1);
3413ac4b20a0SKirk McKusick 		vput(vp);
3414ac4b20a0SKirk McKusick 		break;
3415ac4b20a0SKirk McKusick 
3416812b1d41SKirk McKusick 	case FFS_DIR_FREE:
3417d8ba45e2SEd Maste 		filetype = IFDIR;
3418812b1d41SKirk McKusick 		/* fall through */
3419812b1d41SKirk McKusick 
3420812b1d41SKirk McKusick 	case FFS_FILE_FREE:
3421af6aeacbSKirk McKusick #ifdef DIAGNOSTIC
3422812b1d41SKirk McKusick 		if (fsckcmds) {
3423812b1d41SKirk McKusick 			if (cmd.size == 1)
3424fc8fdae0SMatthew D Fleming 				printf("%s: free %s inode %ju\n",
3425812b1d41SKirk McKusick 				    mp->mnt_stat.f_mntonname,
3426d8ba45e2SEd Maste 				    filetype == IFDIR ? "directory" : "file",
3427fc8fdae0SMatthew D Fleming 				    (uintmax_t)cmd.value);
3428812b1d41SKirk McKusick 			else
3429fc8fdae0SMatthew D Fleming 				printf("%s: free %s inodes %ju-%ju\n",
3430812b1d41SKirk McKusick 				    mp->mnt_stat.f_mntonname,
3431d8ba45e2SEd Maste 				    filetype == IFDIR ? "directory" : "file",
3432fc8fdae0SMatthew D Fleming 				    (uintmax_t)cmd.value,
3433fc8fdae0SMatthew D Fleming 				    (uintmax_t)(cmd.value + cmd.size - 1));
3434812b1d41SKirk McKusick 		}
3435af6aeacbSKirk McKusick #endif /* DIAGNOSTIC */
3436812b1d41SKirk McKusick 		while (cmd.size > 0) {
34378e37fbadSJeff Roberson 			if ((error = ffs_freefile(ump, fs, ump->um_devvp,
3438113db2ddSJeff Roberson 			    cmd.value, filetype, NULL)))
3439f0f3f19fSKirk McKusick 				break;
3440812b1d41SKirk McKusick 			cmd.size -= 1;
3441812b1d41SKirk McKusick 			cmd.value += 1;
3442812b1d41SKirk McKusick 		}
3443812b1d41SKirk McKusick 		break;
3444812b1d41SKirk McKusick 
3445812b1d41SKirk McKusick 	case FFS_BLK_FREE:
3446af6aeacbSKirk McKusick #ifdef DIAGNOSTIC
3447812b1d41SKirk McKusick 		if (fsckcmds) {
3448812b1d41SKirk McKusick 			if (cmd.size == 1)
344947a56126SDavid E. O'Brien 				printf("%s: free block %jd\n",
3450812b1d41SKirk McKusick 				    mp->mnt_stat.f_mntonname,
34511c85e6a3SKirk McKusick 				    (intmax_t)cmd.value);
3452812b1d41SKirk McKusick 			else
345347a56126SDavid E. O'Brien 				printf("%s: free blocks %jd-%jd\n",
3454812b1d41SKirk McKusick 				    mp->mnt_stat.f_mntonname,
34551c85e6a3SKirk McKusick 				    (intmax_t)cmd.value,
34561c85e6a3SKirk McKusick 				    (intmax_t)cmd.value + cmd.size - 1);
3457812b1d41SKirk McKusick 		}
3458af6aeacbSKirk McKusick #endif /* DIAGNOSTIC */
34591c85e6a3SKirk McKusick 		blkno = cmd.value;
3460812b1d41SKirk McKusick 		blkcnt = cmd.size;
3461812b1d41SKirk McKusick 		blksize = fs->fs_frag - (blkno % fs->fs_frag);
34627e038bc2SKirk McKusick 		key = ffs_blkrelease_start(ump, ump->um_devvp, UFS_ROOTINO);
3463812b1d41SKirk McKusick 		while (blkcnt > 0) {
34647e038bc2SKirk McKusick 			if (blkcnt < blksize)
3465812b1d41SKirk McKusick 				blksize = blkcnt;
34668e37fbadSJeff Roberson 			ffs_blkfree(ump, fs, ump->um_devvp, blkno,
34677e038bc2SKirk McKusick 			    blksize * fs->fs_fsize, UFS_ROOTINO,
34687e038bc2SKirk McKusick 			    VDIR, NULL, key);
3469812b1d41SKirk McKusick 			blkno += blksize;
3470812b1d41SKirk McKusick 			blkcnt -= blksize;
3471812b1d41SKirk McKusick 			blksize = fs->fs_frag;
3472812b1d41SKirk McKusick 		}
34737e038bc2SKirk McKusick 		ffs_blkrelease_finish(ump, key);
3474812b1d41SKirk McKusick 		break;
3475812b1d41SKirk McKusick 
3476a16baf37SXin LI 	/*
3477a16baf37SXin LI 	 * Adjust superblock summaries.  fsck(8) is expected to
3478a16baf37SXin LI 	 * submit deltas when necessary.
3479a16baf37SXin LI 	 */
3480a16baf37SXin LI 	case FFS_ADJ_NDIR:
3481af6aeacbSKirk McKusick #ifdef DIAGNOSTIC
3482a16baf37SXin LI 		if (fsckcmds) {
3483a16baf37SXin LI 			printf("%s: adjust number of directories by %jd\n",
3484a16baf37SXin LI 			    mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
3485a16baf37SXin LI 		}
3486af6aeacbSKirk McKusick #endif /* DIAGNOSTIC */
3487a16baf37SXin LI 		fs->fs_cstotal.cs_ndir += cmd.value;
3488a16baf37SXin LI 		break;
3489e268f54cSKirk McKusick 
3490a16baf37SXin LI 	case FFS_ADJ_NBFREE:
3491af6aeacbSKirk McKusick #ifdef DIAGNOSTIC
3492a16baf37SXin LI 		if (fsckcmds) {
3493a16baf37SXin LI 			printf("%s: adjust number of free blocks by %+jd\n",
3494a16baf37SXin LI 			    mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
3495a16baf37SXin LI 		}
3496af6aeacbSKirk McKusick #endif /* DIAGNOSTIC */
3497a16baf37SXin LI 		fs->fs_cstotal.cs_nbfree += cmd.value;
3498a16baf37SXin LI 		break;
3499e268f54cSKirk McKusick 
3500a16baf37SXin LI 	case FFS_ADJ_NIFREE:
3501af6aeacbSKirk McKusick #ifdef DIAGNOSTIC
3502a16baf37SXin LI 		if (fsckcmds) {
3503a16baf37SXin LI 			printf("%s: adjust number of free inodes by %+jd\n",
3504a16baf37SXin LI 			    mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
3505a16baf37SXin LI 		}
3506af6aeacbSKirk McKusick #endif /* DIAGNOSTIC */
3507a16baf37SXin LI 		fs->fs_cstotal.cs_nifree += cmd.value;
3508a16baf37SXin LI 		break;
3509e268f54cSKirk McKusick 
3510a16baf37SXin LI 	case FFS_ADJ_NFFREE:
3511af6aeacbSKirk McKusick #ifdef DIAGNOSTIC
3512a16baf37SXin LI 		if (fsckcmds) {
3513a16baf37SXin LI 			printf("%s: adjust number of free frags by %+jd\n",
3514a16baf37SXin LI 			    mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
3515a16baf37SXin LI 		}
3516af6aeacbSKirk McKusick #endif /* DIAGNOSTIC */
3517a16baf37SXin LI 		fs->fs_cstotal.cs_nffree += cmd.value;
3518a16baf37SXin LI 		break;
3519e268f54cSKirk McKusick 
3520a16baf37SXin LI 	case FFS_ADJ_NUMCLUSTERS:
3521af6aeacbSKirk McKusick #ifdef DIAGNOSTIC
3522a16baf37SXin LI 		if (fsckcmds) {
3523a16baf37SXin LI 			printf("%s: adjust number of free clusters by %+jd\n",
3524a16baf37SXin LI 			    mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
3525a16baf37SXin LI 		}
3526af6aeacbSKirk McKusick #endif /* DIAGNOSTIC */
3527a16baf37SXin LI 		fs->fs_cstotal.cs_numclusters += cmd.value;
3528a16baf37SXin LI 		break;
3529a16baf37SXin LI 
3530e268f54cSKirk McKusick 	case FFS_SET_CWD:
3531af6aeacbSKirk McKusick #ifdef DIAGNOSTIC
3532e268f54cSKirk McKusick 		if (fsckcmds) {
3533e268f54cSKirk McKusick 			printf("%s: set current directory to inode %jd\n",
3534e268f54cSKirk McKusick 			    mp->mnt_stat.f_mntonname, (intmax_t)cmd.value);
3535e268f54cSKirk McKusick 		}
3536af6aeacbSKirk McKusick #endif /* DIAGNOSTIC */
3537e268f54cSKirk McKusick 		if ((error = ffs_vget(mp, (ino_t)cmd.value, LK_SHARED, &vp)))
3538e268f54cSKirk McKusick 			break;
3539e268f54cSKirk McKusick 		AUDIT_ARG_VNODE1(vp);
3540e268f54cSKirk McKusick 		if ((error = change_dir(vp, td)) != 0) {
3541e268f54cSKirk McKusick 			vput(vp);
3542e268f54cSKirk McKusick 			break;
3543e268f54cSKirk McKusick 		}
3544b249ce48SMateusz Guzik 		VOP_UNLOCK(vp);
3545f0725a8eSMateusz Guzik 		pwd_chdir(td, vp);
3546e268f54cSKirk McKusick 		break;
3547e268f54cSKirk McKusick 
3548e268f54cSKirk McKusick 	case FFS_SET_DOTDOT:
3549af6aeacbSKirk McKusick #ifdef DIAGNOSTIC
3550e268f54cSKirk McKusick 		if (fsckcmds) {
3551e268f54cSKirk McKusick 			printf("%s: change .. in cwd from %jd to %jd\n",
3552e268f54cSKirk McKusick 			    mp->mnt_stat.f_mntonname, (intmax_t)cmd.value,
3553e268f54cSKirk McKusick 			    (intmax_t)cmd.size);
3554e268f54cSKirk McKusick 		}
3555af6aeacbSKirk McKusick #endif /* DIAGNOSTIC */
3556e268f54cSKirk McKusick 		/*
3557e268f54cSKirk McKusick 		 * First we have to get and lock the parent directory
3558e268f54cSKirk McKusick 		 * to which ".." points.
3559e268f54cSKirk McKusick 		 */
3560e268f54cSKirk McKusick 		error = ffs_vget(mp, (ino_t)cmd.value, LK_EXCLUSIVE, &fdvp);
3561e268f54cSKirk McKusick 		if (error)
3562e268f54cSKirk McKusick 			break;
3563e268f54cSKirk McKusick 		/*
3564e268f54cSKirk McKusick 		 * Now we get and lock the child directory containing "..".
3565e268f54cSKirk McKusick 		 */
35668d03b99bSMateusz Guzik 		pwd = pwd_hold(td);
35678d03b99bSMateusz Guzik 		dvp = pwd->pwd_cdir;
3568a92a971bSMateusz Guzik 		if ((error = vget(dvp, LK_EXCLUSIVE)) != 0) {
3569e268f54cSKirk McKusick 			vput(fdvp);
35708d03b99bSMateusz Guzik 			pwd_drop(pwd);
3571e268f54cSKirk McKusick 			break;
3572e268f54cSKirk McKusick 		}
3573e268f54cSKirk McKusick 		dp = VTOI(dvp);
357461846fc4SKonstantin Belousov 		SET_I_OFFSET(dp, 12);	/* XXX mastertemplate.dot_reclen */
3575e268f54cSKirk McKusick 		error = ufs_dirrewrite(dp, VTOI(fdvp), (ino_t)cmd.size,
3576e268f54cSKirk McKusick 		    DT_DIR, 0);
3577e268f54cSKirk McKusick 		cache_purge(fdvp);
3578e268f54cSKirk McKusick 		cache_purge(dvp);
3579e268f54cSKirk McKusick 		vput(dvp);
3580e268f54cSKirk McKusick 		vput(fdvp);
35818d03b99bSMateusz Guzik 		pwd_drop(pwd);
3582e268f54cSKirk McKusick 		break;
3583e268f54cSKirk McKusick 
3584e268f54cSKirk McKusick 	case FFS_UNLINK:
3585af6aeacbSKirk McKusick #ifdef DIAGNOSTIC
3586e268f54cSKirk McKusick 		if (fsckcmds) {
3587e268f54cSKirk McKusick 			char buf[32];
3588e268f54cSKirk McKusick 
358953298164SKirk McKusick 			if (copyinstr((char *)(intptr_t)cmd.value, buf,32,NULL))
3590e268f54cSKirk McKusick 				strncpy(buf, "Name_too_long", 32);
3591e268f54cSKirk McKusick 			printf("%s: unlink %s (inode %jd)\n",
3592e268f54cSKirk McKusick 			    mp->mnt_stat.f_mntonname, buf, (intmax_t)cmd.size);
3593e268f54cSKirk McKusick 		}
3594af6aeacbSKirk McKusick #endif /* DIAGNOSTIC */
3595e268f54cSKirk McKusick 		/*
3596a1304030SMariusz Zaborski 		 * kern_funlinkat will do its own start/finish writes and
3597e268f54cSKirk McKusick 		 * they do not nest, so drop ours here. Setting mp == NULL
3598e268f54cSKirk McKusick 		 * indicates that vn_finished_write is not needed down below.
3599e268f54cSKirk McKusick 		 */
3600e268f54cSKirk McKusick 		vn_finished_write(mp);
3601e268f54cSKirk McKusick 		mp = NULL;
3602a1304030SMariusz Zaborski 		error = kern_funlinkat(td, AT_FDCWD,
3603a1304030SMariusz Zaborski 		    (char *)(intptr_t)cmd.value, FD_NONE, UIO_USERSPACE,
3604a1304030SMariusz Zaborski 		    0, (ino_t)cmd.size);
3605e268f54cSKirk McKusick 		break;
3606e268f54cSKirk McKusick 
3607812b1d41SKirk McKusick 	default:
3608af6aeacbSKirk McKusick #ifdef DIAGNOSTIC
3609812b1d41SKirk McKusick 		if (fsckcmds) {
3610812b1d41SKirk McKusick 			printf("Invalid request %d from fsck\n",
3611812b1d41SKirk McKusick 			    oidp->oid_number);
3612812b1d41SKirk McKusick 		}
3613af6aeacbSKirk McKusick #endif /* DIAGNOSTIC */
3614f0f3f19fSKirk McKusick 		error = EINVAL;
3615f0f3f19fSKirk McKusick 		break;
3616812b1d41SKirk McKusick 	}
3617e268f54cSKirk McKusick 	fdrop(fp, td);
3618f0f3f19fSKirk McKusick 	vn_finished_write(mp);
3619f0f3f19fSKirk McKusick 	return (error);
3620812b1d41SKirk McKusick }
3621