1/*-
2 * SPDX-License-Identifier: BSD-4-Clause
3 *
4 * Copyright (c) 1980, 1989, 1993 The Regents of the University of California.
5 * Copyright (c) 2000 Christoph Herrmann, Thomas-Henning von Kamptz
6 * Copyright (c) 2012 The FreeBSD Foundation
7 * All rights reserved.
8 *
9 * This code is derived from software contributed to Berkeley by
10 * Christoph Herrmann and Thomas-Henning von Kamptz, Munich and Frankfurt.
11 *
12 * Portions of this software were developed by Edward Tomasz Napierala
13 * under sponsorship from the FreeBSD Foundation.
14 *
15 * Redistribution and use in source and binary forms, with or without
16 * modification, are permitted provided that the following conditions
17 * are met:
18 * 1. Redistributions of source code must retain the above copyright
19 *    notice, this list of conditions and the following disclaimer.
20 * 2. Redistributions in binary form must reproduce the above copyright
21 *    notice, this list of conditions and the following disclaimer in the
22 *    documentation and/or other materials provided with the distribution.
23 * 3. All advertising materials mentioning features or use of this software
24 *    must display the following acknowledgment:
25 *      This product includes software developed by the University of
26 *      California, Berkeley and its contributors, as well as Christoph
27 *      Herrmann and Thomas-Henning von Kamptz.
28 * 4. Neither the name of the University nor the names of its contributors
29 *    may be used to endorse or promote products derived from this software
30 *    without specific prior written permission.
31 *
32 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
33 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
34 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
35 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
36 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
37 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
38 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
39 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
40 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
41 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
42 * SUCH DAMAGE.
43 *
44 * $TSHeader: src/sbin/growfs/growfs.c,v 1.5 2000/12/12 19:31:00 tomsoft Exp $
45 *
46 */
47
48#ifndef lint
49static const char copyright[] =
50"@(#) Copyright (c) 2000 Christoph Herrmann, Thomas-Henning von Kamptz\n\
51Copyright (c) 1980, 1989, 1993 The Regents of the University of California.\n\
52All rights reserved.\n";
53#endif /* not lint */
54
55#include <sys/cdefs.h>
56__FBSDID("$FreeBSD$");
57
58#include <sys/param.h>
59#include <sys/ioctl.h>
60#include <sys/stat.h>
61#include <sys/disk.h>
62#include <sys/ucred.h>
63#include <sys/mount.h>
64
65#include <stdio.h>
66#include <paths.h>
67#include <ctype.h>
68#include <err.h>
69#include <errno.h>
70#include <fcntl.h>
71#include <fstab.h>
72#include <inttypes.h>
73#include <limits.h>
74#include <mntopts.h>
75#include <paths.h>
76#include <stdlib.h>
77#include <stdint.h>
78#include <string.h>
79#include <time.h>
80#include <unistd.h>
81#include <ufs/ufs/dinode.h>
82#include <ufs/ffs/fs.h>
83#include <libutil.h>
84#include <libufs.h>
85
86#include "debug.h"
87
88#ifdef FS_DEBUG
89int	_dbg_lvl_ = (DL_INFO);	/* DL_TRC */
90#endif /* FS_DEBUG */
91
92static union {
93	struct fs	fs;
94	char		pad[SBLOCKSIZE];
95} fsun1, fsun2;
96#define	sblock	fsun1.fs	/* the new superblock */
97#define	osblock	fsun2.fs	/* the old superblock */
98
99static union {
100	struct cg	cg;
101	char		pad[MAXBSIZE];
102} cgun1, cgun2;
103#define	acg	cgun1.cg	/* a cylinder cgroup (new) */
104#define	aocg	cgun2.cg	/* an old cylinder group */
105
106static struct csum	*fscs;	/* cylinder summary */
107
108static void	growfs(int, int, unsigned int);
109static void	rdfs(ufs2_daddr_t, size_t, void *, int);
110static void	wtfs(ufs2_daddr_t, size_t, void *, int, unsigned int);
111static int	charsperline(void);
112static void	usage(void);
113static int	isblock(struct fs *, unsigned char *, int);
114static void	clrblock(struct fs *, unsigned char *, int);
115static void	setblock(struct fs *, unsigned char *, int);
116static void	initcg(int, time_t, int, unsigned int);
117static void	updjcg(int, time_t, int, int, unsigned int);
118static void	updcsloc(time_t, int, int, unsigned int);
119static void	frag_adjust(ufs2_daddr_t, int);
120static void	updclst(int);
121static void	mount_reload(const struct statfs *stfs);
122static void	cgckhash(struct cg *);
123
124/*
125 * Here we actually start growing the file system. We basically read the
126 * cylinder summary from the first cylinder group as we want to update
127 * this on the fly during our various operations. First we handle the
128 * changes in the former last cylinder group. Afterwards we create all new
129 * cylinder groups.  Now we handle the cylinder group containing the
130 * cylinder summary which might result in a relocation of the whole
131 * structure.  In the end we write back the updated cylinder summary, the
132 * new superblock, and slightly patched versions of the super block
133 * copies.
134 */
135static void
136growfs(int fsi, int fso, unsigned int Nflag)
137{
138	DBG_FUNC("growfs")
139	time_t modtime;
140	uint cylno;
141	int i, j, width;
142	char tmpbuf[100];
143
144	DBG_ENTER;
145
146	time(&modtime);
147
148	/*
149	 * Get the cylinder summary into the memory.
150	 */
151	fscs = (struct csum *)calloc((size_t)1, (size_t)sblock.fs_cssize);
152	if (fscs == NULL)
153		errx(1, "calloc failed");
154	memcpy(fscs, osblock.fs_csp, osblock.fs_cssize);
155	free(osblock.fs_csp);
156	osblock.fs_csp = NULL;
157	sblock.fs_csp = fscs;
158
159#ifdef FS_DEBUG
160	{
161		struct csum *dbg_csp;
162		u_int32_t dbg_csc;
163		char dbg_line[80];
164
165		dbg_csp = fscs;
166
167		for (dbg_csc = 0; dbg_csc < osblock.fs_ncg; dbg_csc++) {
168			snprintf(dbg_line, sizeof(dbg_line),
169			    "%d. old csum in old location", dbg_csc);
170			DBG_DUMP_CSUM(&osblock, dbg_line, dbg_csp++);
171		}
172	}
173#endif /* FS_DEBUG */
174	DBG_PRINT0("fscs read\n");
175
176	/*
177	 * Do all needed changes in the former last cylinder group.
178	 */
179	updjcg(osblock.fs_ncg - 1, modtime, fsi, fso, Nflag);
180
181	/*
182	 * Dump out summary information about file system.
183	 */
184#ifdef FS_DEBUG
185#define B2MBFACTOR (1 / (1024.0 * 1024.0))
186	printf("growfs: %.1fMB (%jd sectors) block size %d, fragment size %d\n",
187	    (float)sblock.fs_size * sblock.fs_fsize * B2MBFACTOR,
188	    (intmax_t)fsbtodb(&sblock, sblock.fs_size), sblock.fs_bsize,
189	    sblock.fs_fsize);
190	printf("\tusing %d cylinder groups of %.2fMB, %d blks, %d inodes.\n",
191	    sblock.fs_ncg, (float)sblock.fs_fpg * sblock.fs_fsize * B2MBFACTOR,
192	    sblock.fs_fpg / sblock.fs_frag, sblock.fs_ipg);
193	if (sblock.fs_flags & FS_DOSOFTDEP)
194		printf("\twith soft updates\n");
195#undef B2MBFACTOR
196#endif /* FS_DEBUG */
197
198	/*
199	 * Now build the cylinders group blocks and
200	 * then print out indices of cylinder groups.
201	 */
202	printf("super-block backups (for fsck_ffs -b #) at:\n");
203	i = 0;
204	width = charsperline();
205
206	/*
207	 * Iterate for only the new cylinder groups.
208	 */
209	for (cylno = osblock.fs_ncg; cylno < sblock.fs_ncg; cylno++) {
210		initcg(cylno, modtime, fso, Nflag);
211		j = sprintf(tmpbuf, " %jd%s",
212		    (intmax_t)fsbtodb(&sblock, cgsblock(&sblock, cylno)),
213		    cylno < (sblock.fs_ncg - 1) ? "," : "" );
214		if (i + j >= width) {
215			printf("\n");
216			i = 0;
217		}
218		i += j;
219		printf("%s", tmpbuf);
220		fflush(stdout);
221	}
222	printf("\n");
223
224	/*
225	 * Do all needed changes in the first cylinder group.
226	 * allocate blocks in new location
227	 */
228	updcsloc(modtime, fsi, fso, Nflag);
229
230	/*
231	 * Clean up the dynamic fields in our superblock.
232	 *
233	 * XXX
234	 * The following fields are currently distributed from the superblock
235	 * to the copies:
236	 *     fs_minfree
237	 *     fs_rotdelay
238	 *     fs_maxcontig
239	 *     fs_maxbpg
240	 *     fs_minfree,
241	 *     fs_optim
242	 *     fs_flags
243	 *
244	 * We probably should rather change the summary for the cylinder group
245	 * statistics here to the value of what would be in there, if the file
246	 * system were created initially with the new size. Therefor we still
247	 * need to find an easy way of calculating that.
248	 * Possibly we can try to read the first superblock copy and apply the
249	 * "diffed" stats between the old and new superblock by still copying
250	 * certain parameters onto that.
251	 */
252	sblock.fs_time = modtime;
253	sblock.fs_fmod = 0;
254	sblock.fs_clean = 1;
255	sblock.fs_ronly = 0;
256	sblock.fs_cgrotor = 0;
257	sblock.fs_state = 0;
258	memset((void *)&sblock.fs_fsmnt, 0, sizeof(sblock.fs_fsmnt));
259
260	/*
261	 * Now write the new superblock, its summary information,
262	 * and all the alternates back to disk.
263	 */
264	if (!Nflag && sbput(fso, &sblock, sblock.fs_ncg) != 0)
265		errc(2, EIO, "could not write updated superblock");
266	DBG_PRINT0("fscs written\n");
267
268#ifdef FS_DEBUG
269	{
270		struct csum	*dbg_csp;
271		u_int32_t	dbg_csc;
272		char	dbg_line[80];
273
274		dbg_csp = fscs;
275		for (dbg_csc = 0; dbg_csc < sblock.fs_ncg; dbg_csc++) {
276			snprintf(dbg_line, sizeof(dbg_line),
277			    "%d. new csum in new location", dbg_csc);
278			DBG_DUMP_CSUM(&sblock, dbg_line, dbg_csp++);
279		}
280	}
281#endif /* FS_DEBUG */
282
283	DBG_PRINT0("sblock written\n");
284	DBG_DUMP_FS(&sblock, "new initial sblock");
285
286	DBG_PRINT0("sblock copies written\n");
287	DBG_DUMP_FS(&sblock, "new other sblocks");
288
289	DBG_LEAVE;
290	return;
291}
292
293/*
294 * This creates a new cylinder group structure, for more details please see
295 * the source of newfs(8), as this function is taken over almost unchanged.
296 * As this is never called for the first cylinder group, the special
297 * provisions for that case are removed here.
298 */
299static void
300initcg(int cylno, time_t modtime, int fso, unsigned int Nflag)
301{
302	DBG_FUNC("initcg")
303	static caddr_t iobuf;
304	static long iobufsize;
305	long blkno, start;
306	ino_t ino;
307	ufs2_daddr_t i, cbase, dmax;
308	struct ufs1_dinode *dp1;
309	struct ufs2_dinode *dp2;
310	struct csum *cs;
311	uint j, d, dupper, dlower;
312
313	if (iobuf == NULL) {
314		iobufsize = 2 * sblock.fs_bsize;
315		if ((iobuf = malloc(iobufsize)) == NULL)
316			errx(37, "panic: cannot allocate I/O buffer");
317		memset(iobuf, '\0', iobufsize);
318	}
319	/*
320	 * Determine block bounds for cylinder group.
321	 * Allow space for super block summary information in first
322	 * cylinder group.
323	 */
324	cbase = cgbase(&sblock, cylno);
325	dmax = cbase + sblock.fs_fpg;
326	if (dmax > sblock.fs_size)
327		dmax = sblock.fs_size;
328	dlower = cgsblock(&sblock, cylno) - cbase;
329	dupper = cgdmin(&sblock, cylno) - cbase;
330	if (cylno == 0)	/* XXX fscs may be relocated */
331		dupper += howmany(sblock.fs_cssize, sblock.fs_fsize);
332	cs = &fscs[cylno];
333	memset(&acg, 0, sblock.fs_cgsize);
334	acg.cg_time = modtime;
335	acg.cg_magic = CG_MAGIC;
336	acg.cg_cgx = cylno;
337	acg.cg_niblk = sblock.fs_ipg;
338	acg.cg_initediblk = MIN(sblock.fs_ipg, 2 * INOPB(&sblock));
339	acg.cg_ndblk = dmax - cbase;
340	if (sblock.fs_contigsumsize > 0)
341		acg.cg_nclusterblks = acg.cg_ndblk / sblock.fs_frag;
342	start = &acg.cg_space[0] - (u_char *)(&acg.cg_firstfield);
343	if (sblock.fs_magic == FS_UFS2_MAGIC) {
344		acg.cg_iusedoff = start;
345	} else {
346		acg.cg_old_ncyl = sblock.fs_old_cpg;
347		acg.cg_old_time = acg.cg_time;
348		acg.cg_time = 0;
349		acg.cg_old_niblk = acg.cg_niblk;
350		acg.cg_niblk = 0;
351		acg.cg_initediblk = 0;
352		acg.cg_old_btotoff = start;
353		acg.cg_old_boff = acg.cg_old_btotoff +
354		    sblock.fs_old_cpg * sizeof(int32_t);
355		acg.cg_iusedoff = acg.cg_old_boff +
356		    sblock.fs_old_cpg * sizeof(u_int16_t);
357	}
358	acg.cg_freeoff = acg.cg_iusedoff + howmany(sblock.fs_ipg, CHAR_BIT);
359	acg.cg_nextfreeoff = acg.cg_freeoff + howmany(sblock.fs_fpg, CHAR_BIT);
360	if (sblock.fs_contigsumsize > 0) {
361		acg.cg_clustersumoff =
362		    roundup(acg.cg_nextfreeoff, sizeof(u_int32_t));
363		acg.cg_clustersumoff -= sizeof(u_int32_t);
364		acg.cg_clusteroff = acg.cg_clustersumoff +
365		    (sblock.fs_contigsumsize + 1) * sizeof(u_int32_t);
366		acg.cg_nextfreeoff = acg.cg_clusteroff +
367		    howmany(fragstoblks(&sblock, sblock.fs_fpg), CHAR_BIT);
368	}
369	if (acg.cg_nextfreeoff > (unsigned)sblock.fs_cgsize) {
370		/*
371		 * This should never happen as we would have had that panic
372		 * already on file system creation
373		 */
374		errx(37, "panic: cylinder group too big");
375	}
376	acg.cg_cs.cs_nifree += sblock.fs_ipg;
377	if (cylno == 0)
378		for (ino = 0; ino < UFS_ROOTINO; ino++) {
379			setbit(cg_inosused(&acg), ino);
380			acg.cg_cs.cs_nifree--;
381		}
382	/*
383	 * Initialize the initial inode blocks.
384	 */
385	dp1 = (struct ufs1_dinode *)(void *)iobuf;
386	dp2 = (struct ufs2_dinode *)(void *)iobuf;
387	for (i = 0; i < acg.cg_initediblk; i++) {
388		if (sblock.fs_magic == FS_UFS1_MAGIC) {
389			dp1->di_gen = arc4random();
390			dp1++;
391		} else {
392			dp2->di_gen = arc4random();
393			dp2++;
394		}
395	}
396	wtfs(fsbtodb(&sblock, cgimin(&sblock, cylno)), iobufsize, iobuf,
397	    fso, Nflag);
398	/*
399	 * For the old file system, we have to initialize all the inodes.
400	 */
401	if (sblock.fs_magic == FS_UFS1_MAGIC &&
402	    sblock.fs_ipg > 2 * INOPB(&sblock)) {
403		for (i = 2 * sblock.fs_frag;
404		     i < sblock.fs_ipg / INOPF(&sblock);
405		     i += sblock.fs_frag) {
406			dp1 = (struct ufs1_dinode *)(void *)iobuf;
407			for (j = 0; j < INOPB(&sblock); j++) {
408				dp1->di_gen = arc4random();
409				dp1++;
410			}
411			wtfs(fsbtodb(&sblock, cgimin(&sblock, cylno) + i),
412			    sblock.fs_bsize, iobuf, fso, Nflag);
413		}
414	}
415	if (cylno > 0) {
416		/*
417		 * In cylno 0, beginning space is reserved
418		 * for boot and super blocks.
419		 */
420		for (d = 0; d < dlower; d += sblock.fs_frag) {
421			blkno = d / sblock.fs_frag;
422			setblock(&sblock, cg_blksfree(&acg), blkno);
423			if (sblock.fs_contigsumsize > 0)
424				setbit(cg_clustersfree(&acg), blkno);
425			acg.cg_cs.cs_nbfree++;
426		}
427		sblock.fs_dsize += dlower;
428	}
429	sblock.fs_dsize += acg.cg_ndblk - dupper;
430	if ((i = dupper % sblock.fs_frag)) {
431		acg.cg_frsum[sblock.fs_frag - i]++;
432		for (d = dupper + sblock.fs_frag - i; dupper < d; dupper++) {
433			setbit(cg_blksfree(&acg), dupper);
434			acg.cg_cs.cs_nffree++;
435		}
436	}
437	for (d = dupper; d + sblock.fs_frag <= acg.cg_ndblk;
438	    d += sblock.fs_frag) {
439		blkno = d / sblock.fs_frag;
440		setblock(&sblock, cg_blksfree(&acg), blkno);
441		if (sblock.fs_contigsumsize > 0)
442			setbit(cg_clustersfree(&acg), blkno);
443		acg.cg_cs.cs_nbfree++;
444	}
445	if (d < acg.cg_ndblk) {
446		acg.cg_frsum[acg.cg_ndblk - d]++;
447		for (; d < acg.cg_ndblk; d++) {
448			setbit(cg_blksfree(&acg), d);
449			acg.cg_cs.cs_nffree++;
450		}
451	}
452	if (sblock.fs_contigsumsize > 0) {
453		int32_t *sump = cg_clustersum(&acg);
454		u_char *mapp = cg_clustersfree(&acg);
455		int map = *mapp++;
456		int bit = 1;
457		int run = 0;
458
459		for (i = 0; i < acg.cg_nclusterblks; i++) {
460			if ((map & bit) != 0)
461				run++;
462			else if (run != 0) {
463				if (run > sblock.fs_contigsumsize)
464					run = sblock.fs_contigsumsize;
465				sump[run]++;
466				run = 0;
467			}
468			if ((i & (CHAR_BIT - 1)) != CHAR_BIT - 1)
469				bit <<= 1;
470			else {
471				map = *mapp++;
472				bit = 1;
473			}
474		}
475		if (run != 0) {
476			if (run > sblock.fs_contigsumsize)
477				run = sblock.fs_contigsumsize;
478			sump[run]++;
479		}
480	}
481	sblock.fs_cstotal.cs_ndir += acg.cg_cs.cs_ndir;
482	sblock.fs_cstotal.cs_nffree += acg.cg_cs.cs_nffree;
483	sblock.fs_cstotal.cs_nbfree += acg.cg_cs.cs_nbfree;
484	sblock.fs_cstotal.cs_nifree += acg.cg_cs.cs_nifree;
485	*cs = acg.cg_cs;
486
487	cgckhash(&acg);
488	wtfs(fsbtodb(&sblock, cgtod(&sblock, cylno)), sblock.fs_cgsize, &acg,
489	    fso, Nflag);
490	DBG_DUMP_CG(&sblock, "new cg", &acg);
491
492	DBG_LEAVE;
493	return;
494}
495
496/*
497 * Here we add or subtract (sign +1/-1) the available fragments in a given
498 * block to or from the fragment statistics. By subtracting before and adding
499 * after an operation on the free frag map we can easy update the fragment
500 * statistic, which seems to be otherwise a rather complex operation.
501 */
502static void
503frag_adjust(ufs2_daddr_t frag, int sign)
504{
505	DBG_FUNC("frag_adjust")
506	int fragsize;
507	int f;
508
509	DBG_ENTER;
510
511	fragsize = 0;
512	/*
513	 * Here frag only needs to point to any fragment in the block we want
514	 * to examine.
515	 */
516	for (f = rounddown(frag, sblock.fs_frag);
517	    f < roundup(frag + 1, sblock.fs_frag); f++) {
518		/*
519		 * Count contiguous free fragments.
520		 */
521		if (isset(cg_blksfree(&acg), f)) {
522			fragsize++;
523		} else {
524			if (fragsize && fragsize < sblock.fs_frag) {
525				/*
526				 * We found something in between.
527				 */
528				acg.cg_frsum[fragsize] += sign;
529				DBG_PRINT2("frag_adjust [%d]+=%d\n",
530				    fragsize, sign);
531			}
532			fragsize = 0;
533		}
534	}
535	if (fragsize && fragsize < sblock.fs_frag) {
536		/*
537		 * We found something.
538		 */
539		acg.cg_frsum[fragsize] += sign;
540		DBG_PRINT2("frag_adjust [%d]+=%d\n", fragsize, sign);
541	}
542	DBG_PRINT2("frag_adjust [[%d]]+=%d\n", fragsize, sign);
543
544	DBG_LEAVE;
545	return;
546}
547
548/*
549 * Here we do all needed work for the former last cylinder group. It has to be
550 * changed in any case, even if the file system ended exactly on the end of
551 * this group, as there is some slightly inconsistent handling of the number
552 * of cylinders in the cylinder group. We start again by reading the cylinder
553 * group from disk. If the last block was not fully available, we first handle
554 * the missing fragments, then we handle all new full blocks in that file
555 * system and finally we handle the new last fragmented block in the file
556 * system.  We again have to handle the fragment statistics rotational layout
557 * tables and cluster summary during all those operations.
558 */
559static void
560updjcg(int cylno, time_t modtime, int fsi, int fso, unsigned int Nflag)
561{
562	DBG_FUNC("updjcg")
563	ufs2_daddr_t cbase, dmax, dupper;
564	struct csum *cs;
565	int i, k;
566	int j = 0;
567
568	DBG_ENTER;
569
570	/*
571	 * Read the former last (joining) cylinder group from disk, and make
572	 * a copy.
573	 */
574	rdfs(fsbtodb(&osblock, cgtod(&osblock, cylno)),
575	    (size_t)osblock.fs_cgsize, (void *)&aocg, fsi);
576	DBG_PRINT0("jcg read\n");
577	DBG_DUMP_CG(&sblock, "old joining cg", &aocg);
578
579	memcpy((void *)&cgun1, (void *)&cgun2, sizeof(cgun2));
580
581	/*
582	 * If the cylinder group had already its new final size almost
583	 * nothing is to be done ... except:
584	 * For some reason the value of cg_ncyl in the last cylinder group has
585	 * to be zero instead of fs_cpg. As this is now no longer the last
586	 * cylinder group we have to change that value now to fs_cpg.
587	 */
588
589	if (cgbase(&osblock, cylno + 1) == osblock.fs_size) {
590		if (sblock.fs_magic == FS_UFS1_MAGIC)
591			acg.cg_old_ncyl = sblock.fs_old_cpg;
592
593		cgckhash(&acg);
594		wtfs(fsbtodb(&sblock, cgtod(&sblock, cylno)),
595		    (size_t)sblock.fs_cgsize, (void *)&acg, fso, Nflag);
596		DBG_PRINT0("jcg written\n");
597		DBG_DUMP_CG(&sblock, "new joining cg", &acg);
598
599		DBG_LEAVE;
600		return;
601	}
602
603	/*
604	 * Set up some variables needed later.
605	 */
606	cbase = cgbase(&sblock, cylno);
607	dmax = cbase + sblock.fs_fpg;
608	if (dmax > sblock.fs_size)
609		dmax = sblock.fs_size;
610	dupper = cgdmin(&sblock, cylno) - cbase;
611	if (cylno == 0) /* XXX fscs may be relocated */
612		dupper += howmany(sblock.fs_cssize, sblock.fs_fsize);
613
614	/*
615	 * Set pointer to the cylinder summary for our cylinder group.
616	 */
617	cs = fscs + cylno;
618
619	/*
620	 * Touch the cylinder group, update all fields in the cylinder group as
621	 * needed, update the free space in the superblock.
622	 */
623	acg.cg_time = modtime;
624	if ((unsigned)cylno == sblock.fs_ncg - 1) {
625		/*
626		 * This is still the last cylinder group.
627		 */
628		if (sblock.fs_magic == FS_UFS1_MAGIC)
629			acg.cg_old_ncyl =
630			    sblock.fs_old_ncyl % sblock.fs_old_cpg;
631	} else {
632		acg.cg_old_ncyl = sblock.fs_old_cpg;
633	}
634	DBG_PRINT2("jcg dbg: %d %u", cylno, sblock.fs_ncg);
635#ifdef FS_DEBUG
636	if (sblock.fs_magic == FS_UFS1_MAGIC)
637		DBG_PRINT2("%d %u", acg.cg_old_ncyl, sblock.fs_old_cpg);
638#endif
639	DBG_PRINT0("\n");
640	acg.cg_ndblk = dmax - cbase;
641	sblock.fs_dsize += acg.cg_ndblk - aocg.cg_ndblk;
642	if (sblock.fs_contigsumsize > 0)
643		acg.cg_nclusterblks = acg.cg_ndblk / sblock.fs_frag;
644
645	/*
646	 * Now we have to update the free fragment bitmap for our new free
647	 * space.  There again we have to handle the fragmentation and also
648	 * the rotational layout tables and the cluster summary.  This is
649	 * also done per fragment for the first new block if the old file
650	 * system end was not on a block boundary, per fragment for the new
651	 * last block if the new file system end is not on a block boundary,
652	 * and per block for all space in between.
653	 *
654	 * Handle the first new block here if it was partially available
655	 * before.
656	 */
657	if (osblock.fs_size % sblock.fs_frag) {
658		if (roundup(osblock.fs_size, sblock.fs_frag) <=
659		    sblock.fs_size) {
660			/*
661			 * The new space is enough to fill at least this
662			 * block
663			 */
664			j = 0;
665			for (i = roundup(osblock.fs_size - cbase,
666			    sblock.fs_frag) - 1; i >= osblock.fs_size - cbase;
667			    i--) {
668				setbit(cg_blksfree(&acg), i);
669				acg.cg_cs.cs_nffree++;
670				j++;
671			}
672
673			/*
674			 * Check if the fragment just created could join an
675			 * already existing fragment at the former end of the
676			 * file system.
677			 */
678			if (isblock(&sblock, cg_blksfree(&acg),
679			    ((osblock.fs_size - cgbase(&sblock, cylno)) /
680			     sblock.fs_frag))) {
681				/*
682				 * The block is now completely available.
683				 */
684				DBG_PRINT0("block was\n");
685				acg.cg_frsum[osblock.fs_size % sblock.fs_frag]--;
686				acg.cg_cs.cs_nbfree++;
687				acg.cg_cs.cs_nffree -= sblock.fs_frag;
688				k = rounddown(osblock.fs_size - cbase,
689				    sblock.fs_frag);
690				updclst((osblock.fs_size - cbase) /
691				    sblock.fs_frag);
692			} else {
693				/*
694				 * Lets rejoin a possible partially growed
695				 * fragment.
696				 */
697				k = 0;
698				while (isset(cg_blksfree(&acg), i) &&
699				    (i >= rounddown(osblock.fs_size - cbase,
700				    sblock.fs_frag))) {
701					i--;
702					k++;
703				}
704				if (k)
705					acg.cg_frsum[k]--;
706				acg.cg_frsum[k + j]++;
707			}
708		} else {
709			/*
710			 * We only grow by some fragments within this last
711			 * block.
712			 */
713			for (i = sblock.fs_size - cbase - 1;
714			    i >= osblock.fs_size - cbase; i--) {
715				setbit(cg_blksfree(&acg), i);
716				acg.cg_cs.cs_nffree++;
717				j++;
718			}
719			/*
720			 * Lets rejoin a possible partially growed fragment.
721			 */
722			k = 0;
723			while (isset(cg_blksfree(&acg), i) &&
724			    (i >= rounddown(osblock.fs_size - cbase,
725			    sblock.fs_frag))) {
726				i--;
727				k++;
728			}
729			if (k)
730				acg.cg_frsum[k]--;
731			acg.cg_frsum[k + j]++;
732		}
733	}
734
735	/*
736	 * Handle all new complete blocks here.
737	 */
738	for (i = roundup(osblock.fs_size - cbase, sblock.fs_frag);
739	    i + sblock.fs_frag <= dmax - cbase;	/* XXX <= or only < ? */
740	    i += sblock.fs_frag) {
741		j = i / sblock.fs_frag;
742		setblock(&sblock, cg_blksfree(&acg), j);
743		updclst(j);
744		acg.cg_cs.cs_nbfree++;
745	}
746
747	/*
748	 * Handle the last new block if there are stll some new fragments left.
749	 * Here we don't have to bother about the cluster summary or the even
750	 * the rotational layout table.
751	 */
752	if (i < (dmax - cbase)) {
753		acg.cg_frsum[dmax - cbase - i]++;
754		for (; i < dmax - cbase; i++) {
755			setbit(cg_blksfree(&acg), i);
756			acg.cg_cs.cs_nffree++;
757		}
758	}
759
760	sblock.fs_cstotal.cs_nffree +=
761	    (acg.cg_cs.cs_nffree - aocg.cg_cs.cs_nffree);
762	sblock.fs_cstotal.cs_nbfree +=
763	    (acg.cg_cs.cs_nbfree - aocg.cg_cs.cs_nbfree);
764	/*
765	 * The following statistics are not changed here:
766	 *     sblock.fs_cstotal.cs_ndir
767	 *     sblock.fs_cstotal.cs_nifree
768	 * As the statistics for this cylinder group are ready, copy it to
769	 * the summary information array.
770	 */
771	*cs = acg.cg_cs;
772
773	/*
774	 * Write the updated "joining" cylinder group back to disk.
775	 */
776	cgckhash(&acg);
777	wtfs(fsbtodb(&sblock, cgtod(&sblock, cylno)), (size_t)sblock.fs_cgsize,
778	    (void *)&acg, fso, Nflag);
779	DBG_PRINT0("jcg written\n");
780	DBG_DUMP_CG(&sblock, "new joining cg", &acg);
781
782	DBG_LEAVE;
783	return;
784}
785
786/*
787 * Here we update the location of the cylinder summary. We have two possible
788 * ways of growing the cylinder summary:
789 * (1)	We can try to grow the summary in the current location, and relocate
790 *	possibly used blocks within the current cylinder group.
791 * (2)	Alternatively we can relocate the whole cylinder summary to the first
792 *	new completely empty cylinder group. Once the cylinder summary is no
793 *	longer in the beginning of the first cylinder group you should never
794 *	use a version of fsck which is not aware of the possibility to have
795 *	this structure in a non standard place.
796 * Option (2) is considered to be less intrusive to the structure of the file-
797 * system, so that's the one being used.
798 */
799static void
800updcsloc(time_t modtime, int fsi, int fso, unsigned int Nflag)
801{
802	DBG_FUNC("updcsloc")
803	struct csum *cs;
804	int ocscg, ncscg;
805	ufs2_daddr_t d;
806	int lcs = 0;
807	int block;
808
809	DBG_ENTER;
810
811	if (howmany(sblock.fs_cssize, sblock.fs_fsize) ==
812	    howmany(osblock.fs_cssize, osblock.fs_fsize)) {
813		/*
814		 * No new fragment needed.
815		 */
816		DBG_LEAVE;
817		return;
818	}
819	ocscg = dtog(&osblock, osblock.fs_csaddr);
820	cs = fscs + ocscg;
821
822	/*
823	 * Read original cylinder group from disk, and make a copy.
824	 * XXX	If Nflag is set in some very rare cases we now miss
825	 *	some changes done in updjcg by reading the unmodified
826	 *	block from disk.
827	 */
828	rdfs(fsbtodb(&osblock, cgtod(&osblock, ocscg)),
829	    (size_t)osblock.fs_cgsize, (void *)&aocg, fsi);
830	DBG_PRINT0("oscg read\n");
831	DBG_DUMP_CG(&sblock, "old summary cg", &aocg);
832
833	memcpy((void *)&cgun1, (void *)&cgun2, sizeof(cgun2));
834
835	/*
836	 * Touch the cylinder group, set up local variables needed later
837	 * and update the superblock.
838	 */
839	acg.cg_time = modtime;
840
841	/*
842	 * XXX	In the case of having active snapshots we may need much more
843	 *	blocks for the copy on write. We need each block twice, and
844	 *	also up to 8*3 blocks for indirect blocks for all possible
845	 *	references.
846	 */
847	/*
848	 * There is not enough space in the old cylinder group to
849	 * relocate all blocks as needed, so we relocate the whole
850	 * cylinder group summary to a new group. We try to use the
851	 * first complete new cylinder group just created. Within the
852	 * cylinder group we align the area immediately after the
853	 * cylinder group information location in order to be as
854	 * close as possible to the original implementation of ffs.
855	 *
856	 * First we have to make sure we'll find enough space in the
857	 * new cylinder group. If not, then we currently give up.
858	 * We start with freeing everything which was used by the
859	 * fragments of the old cylinder summary in the current group.
860	 * Now we write back the group meta data, read in the needed
861	 * meta data from the new cylinder group, and start allocating
862	 * within that group. Here we can assume, the group to be
863	 * completely empty. Which makes the handling of fragments and
864	 * clusters a lot easier.
865	 */
866	DBG_TRC;
867	if (sblock.fs_ncg - osblock.fs_ncg < 2)
868		errx(2, "panic: not enough space");
869
870	/*
871	 * Point "d" to the first fragment not used by the cylinder
872	 * summary.
873	 */
874	d = osblock.fs_csaddr + (osblock.fs_cssize / osblock.fs_fsize);
875
876	/*
877	 * Set up last cluster size ("lcs") already here. Calculate
878	 * the size for the trailing cluster just behind where "d"
879	 * points to.
880	 */
881	if (sblock.fs_contigsumsize > 0) {
882		for (block = howmany(d % sblock.fs_fpg, sblock.fs_frag),
883		    lcs = 0; lcs < sblock.fs_contigsumsize; block++, lcs++) {
884			if (isclr(cg_clustersfree(&acg), block))
885				break;
886		}
887	}
888
889	/*
890	 * Point "d" to the last frag used by the cylinder summary.
891	 */
892	d--;
893
894	DBG_PRINT1("d=%jd\n", (intmax_t)d);
895	if ((d + 1) % sblock.fs_frag) {
896		/*
897		 * The end of the cylinder summary is not a complete
898		 * block.
899		 */
900		DBG_TRC;
901		frag_adjust(d % sblock.fs_fpg, -1);
902		for (; (d + 1) % sblock.fs_frag; d--) {
903			DBG_PRINT1("d=%jd\n", (intmax_t)d);
904			setbit(cg_blksfree(&acg), d % sblock.fs_fpg);
905			acg.cg_cs.cs_nffree++;
906			sblock.fs_cstotal.cs_nffree++;
907		}
908		/*
909		 * Point "d" to the last fragment of the last
910		 * (incomplete) block of the cylinder summary.
911		 */
912		d++;
913		frag_adjust(d % sblock.fs_fpg, 1);
914
915		if (isblock(&sblock, cg_blksfree(&acg),
916		    (d % sblock.fs_fpg) / sblock.fs_frag)) {
917			DBG_PRINT1("d=%jd\n", (intmax_t)d);
918			acg.cg_cs.cs_nffree -= sblock.fs_frag;
919			acg.cg_cs.cs_nbfree++;
920			sblock.fs_cstotal.cs_nffree -= sblock.fs_frag;
921			sblock.fs_cstotal.cs_nbfree++;
922			if (sblock.fs_contigsumsize > 0) {
923				setbit(cg_clustersfree(&acg),
924				    (d % sblock.fs_fpg) / sblock.fs_frag);
925				if (lcs < sblock.fs_contigsumsize) {
926					if (lcs)
927						cg_clustersum(&acg)[lcs]--;
928					lcs++;
929					cg_clustersum(&acg)[lcs]++;
930				}
931			}
932		}
933		/*
934		 * Point "d" to the first fragment of the block before
935		 * the last incomplete block.
936		 */
937		d--;
938	}
939
940	DBG_PRINT1("d=%jd\n", (intmax_t)d);
941	for (d = rounddown(d, sblock.fs_frag); d >= osblock.fs_csaddr;
942	    d -= sblock.fs_frag) {
943		DBG_TRC;
944		DBG_PRINT1("d=%jd\n", (intmax_t)d);
945		setblock(&sblock, cg_blksfree(&acg),
946		    (d % sblock.fs_fpg) / sblock.fs_frag);
947		acg.cg_cs.cs_nbfree++;
948		sblock.fs_cstotal.cs_nbfree++;
949		if (sblock.fs_contigsumsize > 0) {
950			setbit(cg_clustersfree(&acg),
951			    (d % sblock.fs_fpg) / sblock.fs_frag);
952			/*
953			 * The last cluster size is already set up.
954			 */
955			if (lcs < sblock.fs_contigsumsize) {
956				if (lcs)
957					cg_clustersum(&acg)[lcs]--;
958				lcs++;
959				cg_clustersum(&acg)[lcs]++;
960			}
961		}
962	}
963	*cs = acg.cg_cs;
964
965	/*
966	 * Now write the former cylinder group containing the cylinder
967	 * summary back to disk.
968	 */
969	cgckhash(&acg);
970	wtfs(fsbtodb(&sblock, cgtod(&sblock, ocscg)),
971	    (size_t)sblock.fs_cgsize, (void *)&acg, fso, Nflag);
972	DBG_PRINT0("oscg written\n");
973	DBG_DUMP_CG(&sblock, "old summary cg", &acg);
974
975	/*
976	 * Find the beginning of the new cylinder group containing the
977	 * cylinder summary.
978	 */
979	sblock.fs_csaddr = cgdmin(&sblock, osblock.fs_ncg);
980	ncscg = dtog(&sblock, sblock.fs_csaddr);
981	cs = fscs + ncscg;
982
983	/*
984	 * If Nflag is specified, we would now read random data instead
985	 * of an empty cg structure from disk. So we can't simulate that
986	 * part for now.
987	 */
988	if (Nflag) {
989		DBG_PRINT0("nscg update skipped\n");
990		DBG_LEAVE;
991		return;
992	}
993
994	/*
995	 * Read the future cylinder group containing the cylinder
996	 * summary from disk, and make a copy.
997	 */
998	rdfs(fsbtodb(&sblock, cgtod(&sblock, ncscg)),
999	    (size_t)sblock.fs_cgsize, (void *)&aocg, fsi);
1000	DBG_PRINT0("nscg read\n");
1001	DBG_DUMP_CG(&sblock, "new summary cg", &aocg);
1002
1003	memcpy((void *)&cgun1, (void *)&cgun2, sizeof(cgun2));
1004
1005	/*
1006	 * Allocate all complete blocks used by the new cylinder
1007	 * summary.
1008	 */
1009	for (d = sblock.fs_csaddr; d + sblock.fs_frag <=
1010	    sblock.fs_csaddr + (sblock.fs_cssize / sblock.fs_fsize);
1011	    d += sblock.fs_frag) {
1012		clrblock(&sblock, cg_blksfree(&acg),
1013		    (d % sblock.fs_fpg) / sblock.fs_frag);
1014		acg.cg_cs.cs_nbfree--;
1015		sblock.fs_cstotal.cs_nbfree--;
1016		if (sblock.fs_contigsumsize > 0) {
1017			clrbit(cg_clustersfree(&acg),
1018			    (d % sblock.fs_fpg) / sblock.fs_frag);
1019		}
1020	}
1021
1022	/*
1023	 * Allocate all fragments used by the cylinder summary in the
1024	 * last block.
1025	 */
1026	if (d < sblock.fs_csaddr + (sblock.fs_cssize / sblock.fs_fsize)) {
1027		for (; d - sblock.fs_csaddr <
1028		    sblock.fs_cssize/sblock.fs_fsize; d++) {
1029			clrbit(cg_blksfree(&acg), d % sblock.fs_fpg);
1030			acg.cg_cs.cs_nffree--;
1031			sblock.fs_cstotal.cs_nffree--;
1032		}
1033		acg.cg_cs.cs_nbfree--;
1034		acg.cg_cs.cs_nffree += sblock.fs_frag;
1035		sblock.fs_cstotal.cs_nbfree--;
1036		sblock.fs_cstotal.cs_nffree += sblock.fs_frag;
1037		if (sblock.fs_contigsumsize > 0)
1038			clrbit(cg_clustersfree(&acg),
1039			    (d % sblock.fs_fpg) / sblock.fs_frag);
1040
1041		frag_adjust(d % sblock.fs_fpg, 1);
1042	}
1043	/*
1044	 * XXX	Handle the cluster statistics here in the case this
1045	 *	cylinder group is now almost full, and the remaining
1046	 *	space is less then the maximum cluster size. This is
1047	 *	probably not needed, as you would hardly find a file
1048	 *	system which has only MAXCSBUFS+FS_MAXCONTIG of free
1049	 *	space right behind the cylinder group information in
1050	 *	any new cylinder group.
1051	 */
1052
1053	/*
1054	 * Update our statistics in the cylinder summary.
1055	 */
1056	*cs = acg.cg_cs;
1057
1058	/*
1059	 * Write the new cylinder group containing the cylinder summary
1060	 * back to disk.
1061	 */
1062	cgckhash(&acg);
1063	wtfs(fsbtodb(&sblock, cgtod(&sblock, ncscg)),
1064	    (size_t)sblock.fs_cgsize, (void *)&acg, fso, Nflag);
1065	DBG_PRINT0("nscg written\n");
1066	DBG_DUMP_CG(&sblock, "new summary cg", &acg);
1067
1068	DBG_LEAVE;
1069	return;
1070}
1071
1072/*
1073 * Here we read some block(s) from disk.
1074 */
1075static void
1076rdfs(ufs2_daddr_t bno, size_t size, void *bf, int fsi)
1077{
1078	DBG_FUNC("rdfs")
1079	ssize_t	n;
1080
1081	DBG_ENTER;
1082
1083	if (bno < 0)
1084		err(32, "rdfs: attempting to read negative block number");
1085	if (lseek(fsi, (off_t)bno * DEV_BSIZE, 0) < 0)
1086		err(33, "rdfs: seek error: %jd", (intmax_t)bno);
1087	n = read(fsi, bf, size);
1088	if (n != (ssize_t)size)
1089		err(34, "rdfs: read error: %jd", (intmax_t)bno);
1090
1091	DBG_LEAVE;
1092	return;
1093}
1094
1095/*
1096 * Here we write some block(s) to disk.
1097 */
1098static void
1099wtfs(ufs2_daddr_t bno, size_t size, void *bf, int fso, unsigned int Nflag)
1100{
1101	DBG_FUNC("wtfs")
1102	ssize_t	n;
1103
1104	DBG_ENTER;
1105
1106	if (Nflag) {
1107		DBG_LEAVE;
1108		return;
1109	}
1110	if (lseek(fso, (off_t)bno * DEV_BSIZE, SEEK_SET) < 0)
1111		err(35, "wtfs: seek error: %ld", (long)bno);
1112	n = write(fso, bf, size);
1113	if (n != (ssize_t)size)
1114		err(36, "wtfs: write error: %ld", (long)bno);
1115
1116	DBG_LEAVE;
1117	return;
1118}
1119
1120/*
1121 * Here we check if all frags of a block are free. For more details again
1122 * please see the source of newfs(8), as this function is taken over almost
1123 * unchanged.
1124 */
1125static int
1126isblock(struct fs *fs, unsigned char *cp, int h)
1127{
1128	DBG_FUNC("isblock")
1129	unsigned char mask;
1130
1131	DBG_ENTER;
1132
1133	switch (fs->fs_frag) {
1134	case 8:
1135		DBG_LEAVE;
1136		return (cp[h] == 0xff);
1137	case 4:
1138		mask = 0x0f << ((h & 0x1) << 2);
1139		DBG_LEAVE;
1140		return ((cp[h >> 1] & mask) == mask);
1141	case 2:
1142		mask = 0x03 << ((h & 0x3) << 1);
1143		DBG_LEAVE;
1144		return ((cp[h >> 2] & mask) == mask);
1145	case 1:
1146		mask = 0x01 << (h & 0x7);
1147		DBG_LEAVE;
1148		return ((cp[h >> 3] & mask) == mask);
1149	default:
1150		fprintf(stderr, "isblock bad fs_frag %d\n", fs->fs_frag);
1151		DBG_LEAVE;
1152		return (0);
1153	}
1154}
1155
1156/*
1157 * Here we allocate a complete block in the block map. For more details again
1158 * please see the source of newfs(8), as this function is taken over almost
1159 * unchanged.
1160 */
1161static void
1162clrblock(struct fs *fs, unsigned char *cp, int h)
1163{
1164	DBG_FUNC("clrblock")
1165
1166	DBG_ENTER;
1167
1168	switch ((fs)->fs_frag) {
1169	case 8:
1170		cp[h] = 0;
1171		break;
1172	case 4:
1173		cp[h >> 1] &= ~(0x0f << ((h & 0x1) << 2));
1174		break;
1175	case 2:
1176		cp[h >> 2] &= ~(0x03 << ((h & 0x3) << 1));
1177		break;
1178	case 1:
1179		cp[h >> 3] &= ~(0x01 << (h & 0x7));
1180		break;
1181	default:
1182		warnx("clrblock bad fs_frag %d", fs->fs_frag);
1183		break;
1184	}
1185
1186	DBG_LEAVE;
1187	return;
1188}
1189
1190/*
1191 * Here we free a complete block in the free block map. For more details again
1192 * please see the source of newfs(8), as this function is taken over almost
1193 * unchanged.
1194 */
1195static void
1196setblock(struct fs *fs, unsigned char *cp, int h)
1197{
1198	DBG_FUNC("setblock")
1199
1200	DBG_ENTER;
1201
1202	switch (fs->fs_frag) {
1203	case 8:
1204		cp[h] = 0xff;
1205		break;
1206	case 4:
1207		cp[h >> 1] |= (0x0f << ((h & 0x1) << 2));
1208		break;
1209	case 2:
1210		cp[h >> 2] |= (0x03 << ((h & 0x3) << 1));
1211		break;
1212	case 1:
1213		cp[h >> 3] |= (0x01 << (h & 0x7));
1214		break;
1215	default:
1216		warnx("setblock bad fs_frag %d", fs->fs_frag);
1217		break;
1218	}
1219
1220	DBG_LEAVE;
1221	return;
1222}
1223
1224/*
1225 * Figure out how many lines our current terminal has. For more details again
1226 * please see the source of newfs(8), as this function is taken over almost
1227 * unchanged.
1228 */
1229static int
1230charsperline(void)
1231{
1232	DBG_FUNC("charsperline")
1233	int columns;
1234	char *cp;
1235	struct winsize ws;
1236
1237	DBG_ENTER;
1238
1239	columns = 0;
1240	if (ioctl(0, TIOCGWINSZ, &ws) != -1)
1241		columns = ws.ws_col;
1242	if (columns == 0 && (cp = getenv("COLUMNS")))
1243		columns = atoi(cp);
1244	if (columns == 0)
1245		columns = 80;	/* last resort */
1246
1247	DBG_LEAVE;
1248	return (columns);
1249}
1250
1251static int
1252is_dev(const char *name)
1253{
1254	struct stat devstat;
1255
1256	if (stat(name, &devstat) != 0)
1257		return (0);
1258	if (!S_ISCHR(devstat.st_mode))
1259		return (0);
1260	return (1);
1261}
1262
1263/*
1264 * Return mountpoint on which the device is currently mounted.
1265 */
1266static const struct statfs *
1267dev_to_statfs(const char *dev)
1268{
1269	struct stat devstat, mntdevstat;
1270	struct statfs *mntbuf, *statfsp;
1271	char device[MAXPATHLEN];
1272	char *mntdevname;
1273	int i, mntsize;
1274
1275	/*
1276	 * First check the mounted filesystems.
1277	 */
1278	if (stat(dev, &devstat) != 0)
1279		return (NULL);
1280	if (!S_ISCHR(devstat.st_mode) && !S_ISBLK(devstat.st_mode))
1281		return (NULL);
1282
1283	mntsize = getmntinfo(&mntbuf, MNT_NOWAIT);
1284	for (i = 0; i < mntsize; i++) {
1285		statfsp = &mntbuf[i];
1286		mntdevname = statfsp->f_mntfromname;
1287		if (*mntdevname != '/') {
1288			strcpy(device, _PATH_DEV);
1289			strcat(device, mntdevname);
1290			mntdevname = device;
1291		}
1292		if (stat(mntdevname, &mntdevstat) == 0 &&
1293		    mntdevstat.st_rdev == devstat.st_rdev)
1294			return (statfsp);
1295	}
1296
1297	return (NULL);
1298}
1299
1300static const char *
1301mountpoint_to_dev(const char *mountpoint)
1302{
1303	struct statfs *mntbuf, *statfsp;
1304	struct fstab *fs;
1305	int i, mntsize;
1306
1307	/*
1308	 * First check the mounted filesystems.
1309	 */
1310	mntsize = getmntinfo(&mntbuf, MNT_NOWAIT);
1311	for (i = 0; i < mntsize; i++) {
1312		statfsp = &mntbuf[i];
1313
1314		if (strcmp(statfsp->f_mntonname, mountpoint) == 0)
1315			return (statfsp->f_mntfromname);
1316	}
1317
1318	/*
1319	 * Check the fstab.
1320	 */
1321	fs = getfsfile(mountpoint);
1322	if (fs != NULL)
1323		return (fs->fs_spec);
1324
1325	return (NULL);
1326}
1327
1328static const char *
1329getdev(const char *name)
1330{
1331	static char device[MAXPATHLEN];
1332	const char *cp, *dev;
1333
1334	if (is_dev(name))
1335		return (name);
1336
1337	cp = strrchr(name, '/');
1338	if (cp == NULL) {
1339		snprintf(device, sizeof(device), "%s%s", _PATH_DEV, name);
1340		if (is_dev(device))
1341			return (device);
1342	}
1343
1344	dev = mountpoint_to_dev(name);
1345	if (dev != NULL && is_dev(dev))
1346		return (dev);
1347
1348	return (NULL);
1349}
1350
1351/*
1352 * growfs(8) is a utility which allows to increase the size of an existing
1353 * ufs file system. Currently this can only be done on unmounted file system.
1354 * It recognizes some command line options to specify the new desired size,
1355 * and it does some basic checkings. The old file system size is determined
1356 * and after some more checks like we can really access the new last block
1357 * on the disk etc. we calculate the new parameters for the superblock. After
1358 * having done this we just call growfs() which will do the work.
1359 * We still have to provide support for snapshots. Therefore we first have to
1360 * understand what data structures are always replicated in the snapshot on
1361 * creation, for all other blocks we touch during our procedure, we have to
1362 * keep the old blocks unchanged somewhere available for the snapshots. If we
1363 * are lucky, then we only have to handle our blocks to be relocated in that
1364 * way.
1365 * Also we have to consider in what order we actually update the critical
1366 * data structures of the file system to make sure, that in case of a disaster
1367 * fsck(8) is still able to restore any lost data.
1368 * The foreseen last step then will be to provide for growing even mounted
1369 * file systems. There we have to extend the mount() system call to provide
1370 * userland access to the file system locking facility.
1371 */
1372int
1373main(int argc, char **argv)
1374{
1375	DBG_FUNC("main")
1376	struct fs *fs;
1377	const char *device;
1378	const struct statfs *statfsp;
1379	uint64_t size = 0;
1380	off_t mediasize;
1381	int error, j, fsi, fso, ch, ret, Nflag = 0, yflag = 0;
1382	char *p, reply[5], oldsizebuf[6], newsizebuf[6];
1383	void *testbuf;
1384
1385	DBG_ENTER;
1386
1387	while ((ch = getopt(argc, argv, "Ns:vy")) != -1) {
1388		switch(ch) {
1389		case 'N':
1390			Nflag = 1;
1391			break;
1392		case 's':
1393			size = (off_t)strtoumax(optarg, &p, 0);
1394			if (p == NULL || *p == '\0')
1395				size *= DEV_BSIZE;
1396			else if (*p == 'b' || *p == 'B')
1397				; /* do nothing */
1398			else if (*p == 'k' || *p == 'K')
1399				size <<= 10;
1400			else if (*p == 'm' || *p == 'M')
1401				size <<= 20;
1402			else if (*p == 'g' || *p == 'G')
1403				size <<= 30;
1404			else if (*p == 't' || *p == 'T') {
1405				size <<= 30;
1406				size <<= 10;
1407			} else
1408				errx(1, "unknown suffix on -s argument");
1409			break;
1410		case 'v': /* for compatibility to newfs */
1411			break;
1412		case 'y':
1413			yflag = 1;
1414			break;
1415		case '?':
1416			/* FALLTHROUGH */
1417		default:
1418			usage();
1419		}
1420	}
1421	argc -= optind;
1422	argv += optind;
1423
1424	if (argc != 1)
1425		usage();
1426
1427	/*
1428	 * Now try to guess the device name.
1429	 */
1430	device = getdev(*argv);
1431	if (device == NULL)
1432		errx(1, "cannot find special device for %s", *argv);
1433
1434	statfsp = dev_to_statfs(device);
1435
1436	fsi = open(device, O_RDONLY);
1437	if (fsi < 0)
1438		err(1, "%s", device);
1439
1440	/*
1441	 * Try to guess the slice size if not specified.
1442	 */
1443	if (ioctl(fsi, DIOCGMEDIASIZE, &mediasize) == -1)
1444		err(1,"DIOCGMEDIASIZE");
1445
1446	/*
1447	 * Check if that partition is suitable for growing a file system.
1448	 */
1449	if (mediasize < 1)
1450		errx(1, "partition is unavailable");
1451
1452	/*
1453	 * Read the current superblock, and take a backup.
1454	 */
1455	if ((ret = sbget(fsi, &fs, STDSB)) != 0) {
1456		switch (ret) {
1457		case ENOENT:
1458			errx(1, "superblock not recognized");
1459		default:
1460			errc(1, ret, "unable to read superblock");
1461		}
1462	}
1463	/*
1464	 * Check for filesystem that was unclean at mount time.
1465	 */
1466	if ((fs->fs_flags & (FS_UNCLEAN | FS_NEEDSFSCK)) != 0)
1467		errx(1, "%s is not clean - run fsck.\n", *argv);
1468	memcpy(&osblock, fs, fs->fs_sbsize);
1469	free(fs);
1470	memcpy((void *)&fsun1, (void *)&fsun2, osblock.fs_sbsize);
1471
1472	DBG_OPEN("/tmp/growfs.debug"); /* already here we need a superblock */
1473	DBG_DUMP_FS(&sblock, "old sblock");
1474
1475	/*
1476	 * Determine size to grow to. Default to the device size.
1477	 */
1478	if (size == 0)
1479		size = mediasize;
1480	else {
1481		if (size > (uint64_t)mediasize) {
1482			humanize_number(oldsizebuf, sizeof(oldsizebuf), size,
1483			    "B", HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL);
1484			humanize_number(newsizebuf, sizeof(newsizebuf),
1485			    mediasize,
1486			    "B", HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL);
1487
1488			errx(1, "requested size %s is larger "
1489			    "than the available %s", oldsizebuf, newsizebuf);
1490		}
1491	}
1492
1493	/*
1494	 * Make sure the new size is a multiple of fs_fsize; /dev/ufssuspend
1495	 * only supports fragment-aligned IO requests.
1496	 */
1497	size -= size % osblock.fs_fsize;
1498
1499	if (size <= (uint64_t)(osblock.fs_size * osblock.fs_fsize)) {
1500		humanize_number(oldsizebuf, sizeof(oldsizebuf),
1501		    osblock.fs_size * osblock.fs_fsize,
1502		    "B", HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL);
1503		humanize_number(newsizebuf, sizeof(newsizebuf), size,
1504		    "B", HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL);
1505
1506		errx(1, "requested size %s is not larger than the current "
1507		   "filesystem size %s", newsizebuf, oldsizebuf);
1508	}
1509
1510	sblock.fs_size = dbtofsb(&osblock, size / DEV_BSIZE);
1511	sblock.fs_providersize = dbtofsb(&osblock, mediasize / DEV_BSIZE);
1512
1513	/*
1514	 * Are we really growing?
1515	 */
1516	if (osblock.fs_size >= sblock.fs_size) {
1517		errx(1, "we are not growing (%jd->%jd)",
1518		    (intmax_t)osblock.fs_size, (intmax_t)sblock.fs_size);
1519	}
1520
1521	/*
1522	 * Check if we find an active snapshot.
1523	 */
1524	if (yflag == 0) {
1525		for (j = 0; j < FSMAXSNAP; j++) {
1526			if (sblock.fs_snapinum[j]) {
1527				errx(1, "active snapshot found in file system; "
1528				    "please remove all snapshots before "
1529				    "using growfs");
1530			}
1531			if (!sblock.fs_snapinum[j]) /* list is dense */
1532				break;
1533		}
1534	}
1535
1536	if (yflag == 0 && Nflag == 0) {
1537		if (statfsp != NULL && (statfsp->f_flags & MNT_RDONLY) == 0)
1538			printf("Device is mounted read-write; resizing will "
1539			    "result in temporary write suspension for %s.\n",
1540			    statfsp->f_mntonname);
1541		printf("It's strongly recommended to make a backup "
1542		    "before growing the file system.\n"
1543		    "OK to grow filesystem on %s", device);
1544		if (statfsp != NULL)
1545			printf(", mounted on %s,", statfsp->f_mntonname);
1546		humanize_number(oldsizebuf, sizeof(oldsizebuf),
1547		    osblock.fs_size * osblock.fs_fsize,
1548		    "B", HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL);
1549		humanize_number(newsizebuf, sizeof(newsizebuf),
1550		    sblock.fs_size * sblock.fs_fsize,
1551		    "B", HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL);
1552		printf(" from %s to %s? [yes/no] ", oldsizebuf, newsizebuf);
1553		fflush(stdout);
1554		fgets(reply, (int)sizeof(reply), stdin);
1555		if (strcasecmp(reply, "yes\n")){
1556			printf("Response other than \"yes\"; aborting\n");
1557			exit(0);
1558		}
1559	}
1560
1561	/*
1562	 * Try to access our device for writing.  If it's not mounted,
1563	 * or mounted read-only, simply open it; otherwise, use UFS
1564	 * suspension mechanism.
1565	 */
1566	if (Nflag) {
1567		fso = -1;
1568	} else {
1569		if (statfsp != NULL && (statfsp->f_flags & MNT_RDONLY) == 0) {
1570			fso = open(_PATH_UFSSUSPEND, O_RDWR);
1571			if (fso == -1)
1572				err(1, "unable to open %s", _PATH_UFSSUSPEND);
1573			error = ioctl(fso, UFSSUSPEND, &statfsp->f_fsid);
1574			if (error != 0)
1575				err(1, "UFSSUSPEND");
1576		} else {
1577			fso = open(device, O_WRONLY);
1578			if (fso < 0)
1579				err(1, "%s", device);
1580		}
1581	}
1582
1583	/*
1584	 * Try to access our new last block in the file system.
1585	 */
1586	testbuf = malloc(sblock.fs_fsize);
1587	if (testbuf == NULL)
1588		err(1, "malloc");
1589	rdfs((ufs2_daddr_t)((size - sblock.fs_fsize) / DEV_BSIZE),
1590	    sblock.fs_fsize, testbuf, fsi);
1591	wtfs((ufs2_daddr_t)((size - sblock.fs_fsize) / DEV_BSIZE),
1592	    sblock.fs_fsize, testbuf, fso, Nflag);
1593	free(testbuf);
1594
1595	/*
1596	 * Now calculate new superblock values and check for reasonable
1597	 * bound for new file system size:
1598	 *     fs_size:    is derived from user input
1599	 *     fs_dsize:   should get updated in the routines creating or
1600	 *                 updating the cylinder groups on the fly
1601	 *     fs_cstotal: should get updated in the routines creating or
1602	 *                 updating the cylinder groups
1603	 */
1604
1605	/*
1606	 * Update the number of cylinders and cylinder groups in the file system.
1607	 */
1608	if (sblock.fs_magic == FS_UFS1_MAGIC) {
1609		sblock.fs_old_ncyl =
1610		    sblock.fs_size * sblock.fs_old_nspf / sblock.fs_old_spc;
1611		if (sblock.fs_size * sblock.fs_old_nspf >
1612		    sblock.fs_old_ncyl * sblock.fs_old_spc)
1613			sblock.fs_old_ncyl++;
1614	}
1615	sblock.fs_ncg = howmany(sblock.fs_size, sblock.fs_fpg);
1616
1617	/*
1618	 * Allocate last cylinder group only if there is enough room
1619	 * for at least one data block.
1620	 */
1621	if (sblock.fs_size % sblock.fs_fpg != 0 &&
1622	    sblock.fs_size <= cgdmin(&sblock, sblock.fs_ncg - 1)) {
1623		humanize_number(oldsizebuf, sizeof(oldsizebuf),
1624		    (sblock.fs_size % sblock.fs_fpg) * sblock.fs_fsize,
1625		    "B", HN_AUTOSCALE, HN_B | HN_NOSPACE | HN_DECIMAL);
1626		warnx("no room to allocate last cylinder group; "
1627		    "leaving %s unused", oldsizebuf);
1628		sblock.fs_ncg--;
1629		if (sblock.fs_magic == FS_UFS1_MAGIC)
1630			sblock.fs_old_ncyl = sblock.fs_ncg * sblock.fs_old_cpg;
1631		sblock.fs_size = sblock.fs_ncg * sblock.fs_fpg;
1632	}
1633
1634	/*
1635	 * Update the space for the cylinder group summary information in the
1636	 * respective cylinder group data area.
1637	 */
1638	sblock.fs_cssize =
1639	    fragroundup(&sblock, sblock.fs_ncg * sizeof(struct csum));
1640
1641	if (osblock.fs_size >= sblock.fs_size)
1642		errx(1, "not enough new space");
1643
1644	DBG_PRINT0("sblock calculated\n");
1645
1646	/*
1647	 * Ok, everything prepared, so now let's do the tricks.
1648	 */
1649	growfs(fsi, fso, Nflag);
1650
1651	close(fsi);
1652	if (fso > -1) {
1653		if (statfsp != NULL && (statfsp->f_flags & MNT_RDONLY) == 0) {
1654			error = ioctl(fso, UFSRESUME);
1655			if (error != 0)
1656				err(1, "UFSRESUME");
1657		}
1658		error = close(fso);
1659		if (error != 0)
1660			err(1, "close");
1661		if (statfsp != NULL && (statfsp->f_flags & MNT_RDONLY) != 0)
1662			mount_reload(statfsp);
1663	}
1664
1665	DBG_CLOSE;
1666
1667	DBG_LEAVE;
1668	return (0);
1669}
1670
1671/*
1672 * Dump a line of usage.
1673 */
1674static void
1675usage(void)
1676{
1677	DBG_FUNC("usage")
1678
1679	DBG_ENTER;
1680
1681	fprintf(stderr, "usage: growfs [-Ny] [-s size] special | filesystem\n");
1682
1683	DBG_LEAVE;
1684	exit(1);
1685}
1686
1687/*
1688 * This updates most parameters and the bitmap related to cluster. We have to
1689 * assume that sblock, osblock, acg are set up.
1690 */
1691static void
1692updclst(int block)
1693{
1694	DBG_FUNC("updclst")
1695	static int lcs = 0;
1696
1697	DBG_ENTER;
1698
1699	if (sblock.fs_contigsumsize < 1) /* no clustering */
1700		return;
1701	/*
1702	 * update cluster allocation map
1703	 */
1704	setbit(cg_clustersfree(&acg), block);
1705
1706	/*
1707	 * update cluster summary table
1708	 */
1709	if (!lcs) {
1710		/*
1711		 * calculate size for the trailing cluster
1712		 */
1713		for (block--; lcs < sblock.fs_contigsumsize; block--, lcs++ ) {
1714			if (isclr(cg_clustersfree(&acg), block))
1715				break;
1716		}
1717	}
1718	if (lcs < sblock.fs_contigsumsize) {
1719		if (lcs)
1720			cg_clustersum(&acg)[lcs]--;
1721		lcs++;
1722		cg_clustersum(&acg)[lcs]++;
1723	}
1724
1725	DBG_LEAVE;
1726	return;
1727}
1728
1729static void
1730mount_reload(const struct statfs *stfs)
1731{
1732	char errmsg[255];
1733	struct iovec *iov;
1734	int iovlen;
1735
1736	iov = NULL;
1737	iovlen = 0;
1738	*errmsg = '\0';
1739	build_iovec(&iov, &iovlen, "fstype", __DECONST(char *, "ffs"), 4);
1740	build_iovec(&iov, &iovlen, "fspath", __DECONST(char *, stfs->f_mntonname), (size_t)-1);
1741	build_iovec(&iov, &iovlen, "errmsg", errmsg, sizeof(errmsg));
1742	build_iovec(&iov, &iovlen, "update", NULL, 0);
1743	build_iovec(&iov, &iovlen, "reload", NULL, 0);
1744
1745	if (nmount(iov, iovlen, stfs->f_flags) < 0) {
1746		errmsg[sizeof(errmsg) - 1] = '\0';
1747		err(9, "%s: cannot reload filesystem%s%s", stfs->f_mntonname,
1748		    *errmsg != '\0' ? ": " : "", errmsg);
1749	}
1750}
1751
1752/*
1753 * Calculate the check-hash of the cylinder group.
1754 */
1755static void
1756cgckhash(struct cg *cgp)
1757{
1758
1759	if ((sblock.fs_metackhash & CK_CYLGRP) == 0)
1760		return;
1761	cgp->cg_ckhash = 0;
1762	cgp->cg_ckhash = calculate_crc32c(~0L, (void *)cgp, sblock.fs_cgsize);
1763}
1764