growfs.c revision 98542
1/*
2 * Copyright (c) 2000 Christoph Herrmann, Thomas-Henning von Kamptz
3 * Copyright (c) 1980, 1989, 1993 The Regents of the University of California.
4 * All rights reserved.
5 *
6 * This code is derived from software contributed to Berkeley by
7 * Christoph Herrmann and Thomas-Henning von Kamptz, Munich and Frankfurt.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 *    notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 *    notice, this list of conditions and the following disclaimer in the
16 *    documentation and/or other materials provided with the distribution.
17 * 3. All advertising materials mentioning features or use of this software
18 *    must display the following acknowledgment:
19 *      This product includes software developed by the University of
20 *      California, Berkeley and its contributors, as well as Christoph
21 *      Herrmann and Thomas-Henning von Kamptz.
22 * 4. Neither the name of the University nor the names of its contributors
23 *    may be used to endorse or promote products derived from this software
24 *    without specific prior written permission.
25 *
26 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * SUCH DAMAGE.
37 *
38 * $TSHeader: src/sbin/growfs/growfs.c,v 1.5 2000/12/12 19:31:00 tomsoft Exp $
39 *
40 */
41
42#ifndef lint
43static const char copyright[] =
44"@(#) Copyright (c) 2000 Christoph Herrmann, Thomas-Henning von Kamptz\n\
45Copyright (c) 1980, 1989, 1993 The Regents of the University of California.\n\
46All rights reserved.\n";
47#endif /* not lint */
48
49#ifndef lint
50static const char rcsid[] =
51  "$FreeBSD: head/sbin/growfs/growfs.c 98542 2002-06-21 06:18:05Z mckusick $";
52#endif /* not lint */
53
54/* ********************************************************** INCLUDES ***** */
55#include <sys/param.h>
56#include <sys/disklabel.h>
57#include <sys/ioctl.h>
58#include <sys/stat.h>
59
60#include <stdio.h>
61#include <paths.h>
62#include <ctype.h>
63#include <err.h>
64#include <fcntl.h>
65#include <stdlib.h>
66#include <string.h>
67#include <unistd.h>
68#include <ufs/ufs/dinode.h>
69#include <ufs/ffs/fs.h>
70
71#include "debug.h"
72
73/* *************************************************** GLOBALS & TYPES ***** */
74#ifdef FS_DEBUG
75int	_dbg_lvl_ = (DL_INFO);	/* DL_TRC */
76#endif /* FS_DEBUG */
77
78static union {
79	struct fs	fs;
80	char	pad[SBLOCKSIZE];
81} fsun1, fsun2;
82#define	sblock	fsun1.fs	/* the new superblock */
83#define	osblock	fsun2.fs	/* the old superblock */
84
85/*
86 * Possible superblock locations ordered from most to least likely.
87 */
88static int sblock_try[] = SBLOCKSEARCH;
89static ufs2_daddr_t sblockloc;
90
91static union {
92	struct cg	cg;
93	char	pad[MAXBSIZE];
94} cgun1, cgun2;
95#define	acg	cgun1.cg	/* a cylinder cgroup (new) */
96#define	aocg	cgun2.cg	/* an old cylinder group */
97
98static char	ablk[MAXBSIZE];	/* a block */
99
100static struct csum	*fscs;	/* cylinder summary */
101
102union dinode {
103	struct ufs1_dinode dp1;
104	struct ufs2_dinode dp2;
105};
106#define	DIP(dp, field) \
107	((sblock.fs_magic == FS_UFS1_MAGIC) ? \
108	(dp)->dp1.field : (dp)->dp2.field)
109static ufs2_daddr_t 	inoblk;			/* inode block address */
110static char		inobuf[MAXBSIZE];	/* inode block */
111static int		maxino;			/* last valid inode */
112
113/*
114 * An  array of elements of type struct gfs_bpp describes all blocks  to
115 * be relocated in order to free the space needed for the cylinder group
116 * summary for all cylinder groups located in the first cylinder group.
117 */
118struct gfs_bpp {
119	ufs2_daddr_t	old;		/* old block number */
120	ufs2_daddr_t	new;		/* new block number */
121#define GFS_FL_FIRST	1
122#define GFS_FL_LAST	2
123	unsigned int	flags;	/* special handling required */
124	int	found;		/* how many references were updated */
125};
126
127/* ******************************************************** PROTOTYPES ***** */
128static void	growfs(int, int, unsigned int);
129static void	rdfs(ufs2_daddr_t, size_t, void *, int);
130static void	wtfs(ufs2_daddr_t, size_t, void *, int, unsigned int);
131static ufs2_daddr_t alloc(void);
132static int	charsperline(void);
133static void	usage(void);
134static int	isblock(struct fs *, unsigned char *, int);
135static void	clrblock(struct fs *, unsigned char *, int);
136static void	setblock(struct fs *, unsigned char *, int);
137static void	initcg(int, time_t, int, unsigned int);
138static void	updjcg(int, time_t, int, int, unsigned int);
139static void	updcsloc(time_t, int, int, unsigned int);
140static struct disklabel	*get_disklabel(int);
141static void	return_disklabel(int, struct disklabel *, unsigned int);
142static union dinode *ginode(ino_t, int, int);
143static void	frag_adjust(ufs2_daddr_t, int);
144static int	cond_bl_upd(ufs2_daddr_t *, struct gfs_bpp *, int, int,
145		    unsigned int);
146static void	updclst(int);
147static void	updrefs(int, ino_t, struct gfs_bpp *, int, int, unsigned int);
148static void	indirchk(ufs_lbn_t, ufs_lbn_t, ufs2_daddr_t, ufs_lbn_t,
149		    struct gfs_bpp *, int, int, unsigned int);
150
151/* ************************************************************ growfs ***** */
152/*
153 * Here  we actually start growing the filesystem. We basically  read  the
154 * cylinder  summary  from the first cylinder group as we want  to  update
155 * this  on  the fly during our various operations. First  we  handle  the
156 * changes in the former last cylinder group. Afterwards we create all new
157 * cylinder  groups.  Now  we handle the  cylinder  group  containing  the
158 * cylinder  summary  which  might result in a  relocation  of  the  whole
159 * structure.  In the end we write back the updated cylinder summary,  the
160 * new superblock, and slightly patched versions of the super block
161 * copies.
162 */
163static void
164growfs(int fsi, int fso, unsigned int Nflag)
165{
166	DBG_FUNC("growfs")
167	int	i;
168	int	cylno, j;
169	time_t	utime;
170	int	width;
171	char	tmpbuf[100];
172#ifdef FSIRAND
173	static int	randinit=0;
174
175	DBG_ENTER;
176
177	if (!randinit) {
178		randinit = 1;
179		srandomdev();
180	}
181#else /* not FSIRAND */
182
183	DBG_ENTER;
184
185#endif /* FSIRAND */
186	time(&utime);
187
188	/*
189	 * Get the cylinder summary into the memory.
190	 */
191	fscs = (struct csum *)calloc((size_t)1, (size_t)sblock.fs_cssize);
192	if(fscs == NULL) {
193		errx(1, "calloc failed");
194	}
195	for (i = 0; i < osblock.fs_cssize; i += osblock.fs_bsize) {
196		rdfs(fsbtodb(&osblock, osblock.fs_csaddr +
197		    numfrags(&osblock, i)), (size_t)MIN(osblock.fs_cssize - i,
198		    osblock.fs_bsize), (void *)(((char *)fscs)+i), fsi);
199	}
200
201#ifdef FS_DEBUG
202{
203	struct csum	*dbg_csp;
204	int	dbg_csc;
205	char	dbg_line[80];
206
207	dbg_csp=fscs;
208	for(dbg_csc=0; dbg_csc<osblock.fs_ncg; dbg_csc++) {
209		snprintf(dbg_line, sizeof(dbg_line),
210		    "%d. old csum in old location", dbg_csc);
211		DBG_DUMP_CSUM(&osblock,
212		    dbg_line,
213		    dbg_csp++);
214	}
215}
216#endif /* FS_DEBUG */
217	DBG_PRINT0("fscs read\n");
218
219	/*
220	 * Do all needed changes in the former last cylinder group.
221	 */
222	updjcg(osblock.fs_ncg-1, utime, fsi, fso, Nflag);
223
224	/*
225	 * Dump out summary information about filesystem.
226	 */
227#	define B2MBFACTOR (1 / (1024.0 * 1024.0))
228	printf("growfs: %.1fMB (%qd sectors) block size %d, fragment size %d\n",
229	    (float)sblock.fs_size * sblock.fs_fsize * B2MBFACTOR,
230	    fsbtodb(&sblock, sblock.fs_size), sblock.fs_bsize, sblock.fs_fsize);
231	printf("\tusing %d cylinder groups of %.2fMB, %d blks, %d inodes.\n",
232	    sblock.fs_ncg, (float)sblock.fs_fpg * sblock.fs_fsize * B2MBFACTOR,
233	    sblock.fs_fpg / sblock.fs_frag, sblock.fs_ipg);
234	if (sblock.fs_flags & FS_DOSOFTDEP)
235		printf("\twith soft updates\n");
236#	undef B2MBFACTOR
237
238	/*
239	 * Now build the cylinders group blocks and
240	 * then print out indices of cylinder groups.
241	 */
242	printf("super-block backups (for fsck -b #) at:\n");
243	i = 0;
244	width = charsperline();
245
246	/*
247	 * Iterate for only the new cylinder groups.
248	 */
249	for (cylno = osblock.fs_ncg; cylno < sblock.fs_ncg; cylno++) {
250		initcg(cylno, utime, fso, Nflag);
251		j = sprintf(tmpbuf, " %d%s",
252		    (int)fsbtodb(&sblock, cgsblock(&sblock, cylno)),
253		    cylno < (sblock.fs_ncg-1) ? "," : "" );
254		if (i + j >= width) {
255			printf("\n");
256			i = 0;
257		}
258		i += j;
259		printf("%s", tmpbuf);
260		fflush(stdout);
261	}
262	printf("\n");
263
264	/*
265	 * Do all needed changes in the first cylinder group.
266	 * allocate blocks in new location
267	 */
268	updcsloc(utime, fsi, fso, Nflag);
269
270	/*
271	 * Now write the cylinder summary back to disk.
272	 */
273	for (i = 0; i < sblock.fs_cssize; i += sblock.fs_bsize) {
274		wtfs(fsbtodb(&sblock, sblock.fs_csaddr + numfrags(&sblock, i)),
275		    (size_t)MIN(sblock.fs_cssize - i, sblock.fs_bsize),
276		    (void *)(((char *)fscs) + i), fso, Nflag);
277	}
278	DBG_PRINT0("fscs written\n");
279
280#ifdef FS_DEBUG
281{
282	struct csum	*dbg_csp;
283	int	dbg_csc;
284	char	dbg_line[80];
285
286	dbg_csp=fscs;
287	for(dbg_csc=0; dbg_csc<sblock.fs_ncg; dbg_csc++) {
288		snprintf(dbg_line, sizeof(dbg_line),
289		    "%d. new csum in new location", dbg_csc);
290		DBG_DUMP_CSUM(&sblock,
291		    dbg_line,
292		    dbg_csp++);
293	}
294}
295#endif /* FS_DEBUG */
296
297	/*
298	 * Now write the new superblock back to disk.
299	 */
300	sblock.fs_time = utime;
301	wtfs(sblockloc, (size_t)SBLOCKSIZE, (void *)&sblock, fso, Nflag);
302	DBG_PRINT0("sblock written\n");
303	DBG_DUMP_FS(&sblock,
304	    "new initial sblock");
305
306	/*
307	 * Clean up the dynamic fields in our superblock copies.
308	 */
309	sblock.fs_fmod = 0;
310	sblock.fs_clean = 1;
311	sblock.fs_ronly = 0;
312	sblock.fs_cgrotor = 0;
313	sblock.fs_state = 0;
314	memset((void *)&sblock.fs_fsmnt, 0, sizeof(sblock.fs_fsmnt));
315	sblock.fs_flags &= FS_DOSOFTDEP;
316
317	/*
318	 * XXX
319	 * The following fields are currently distributed from the  superblock
320	 * to the copies:
321	 *     fs_minfree
322	 *     fs_rotdelay
323	 *     fs_maxcontig
324	 *     fs_maxbpg
325	 *     fs_minfree,
326	 *     fs_optim
327	 *     fs_flags regarding SOFTPDATES
328	 *
329	 * We probably should rather change the summary for the cylinder group
330	 * statistics here to the value of what would be in there, if the file
331	 * system were created initially with the new size. Therefor we  still
332	 * need to find an easy way of calculating that.
333	 * Possibly we can try to read the first superblock copy and apply the
334	 * "diffed" stats between the old and new superblock by still  copying
335	 * certain parameters onto that.
336	 */
337
338	/*
339	 * Write out the duplicate super blocks.
340	 */
341	for (cylno = 0; cylno < sblock.fs_ncg; cylno++) {
342		wtfs(fsbtodb(&sblock, cgsblock(&sblock, cylno)),
343		    (size_t)SBLOCKSIZE, (void *)&sblock, fso, Nflag);
344	}
345	DBG_PRINT0("sblock copies written\n");
346	DBG_DUMP_FS(&sblock,
347	    "new other sblocks");
348
349	DBG_LEAVE;
350	return;
351}
352
353/* ************************************************************ initcg ***** */
354/*
355 * This creates a new cylinder group structure, for more details please  see
356 * the  source of newfs(8), as this function is taken over almost unchanged.
357 * As  this  is  never called for the  first  cylinder  group,  the  special
358 * provisions for that case are removed here.
359 */
360static void
361initcg(int cylno, time_t utime, int fso, unsigned int Nflag)
362{
363	DBG_FUNC("initcg")
364	static caddr_t iobuf;
365	long i, j, d, dlower, dupper, blkno, start;
366	ufs2_daddr_t cbase, dmax;
367	struct ufs1_dinode *dp1;
368	struct ufs2_dinode *dp2;
369	struct csum *cs;
370
371	if (iobuf == NULL && (iobuf = malloc(sblock.fs_bsize)) == NULL) {
372		errx(37, "panic: cannot allocate I/O buffer");
373	}
374	/*
375	 * Determine block bounds for cylinder group.
376	 * Allow space for super block summary information in first
377	 * cylinder group.
378	 */
379	cbase = cgbase(&sblock, cylno);
380	dmax = cbase + sblock.fs_fpg;
381	if (dmax > sblock.fs_size)
382		dmax = sblock.fs_size;
383	dlower = cgsblock(&sblock, cylno) - cbase;
384	dupper = cgdmin(&sblock, cylno) - cbase;
385	if (cylno == 0)	/* XXX fscs may be relocated */
386		dupper += howmany(sblock.fs_cssize, sblock.fs_fsize);
387	cs = &fscs[cylno];
388	memset(&acg, 0, sblock.fs_cgsize);
389	acg.cg_time = utime;
390	acg.cg_magic = CG_MAGIC;
391	acg.cg_cgx = cylno;
392	acg.cg_niblk = sblock.fs_ipg;
393	acg.cg_initediblk = sblock.fs_ipg;
394	acg.cg_ndblk = dmax - cbase;
395	if (sblock.fs_contigsumsize > 0)
396		acg.cg_nclusterblks = acg.cg_ndblk / sblock.fs_frag;
397	start = &acg.cg_space[0] - (u_char *)(&acg.cg_firstfield);
398	if (sblock.fs_magic == FS_UFS2_MAGIC) {
399		acg.cg_iusedoff = start;
400	} else {
401		acg.cg_old_ncyl = sblock.fs_old_cpg;
402		acg.cg_old_time = acg.cg_time;
403		acg.cg_time = 0;
404		acg.cg_old_niblk = acg.cg_niblk;
405		acg.cg_niblk = 0;
406		acg.cg_initediblk = 0;
407		acg.cg_old_btotoff = start;
408		acg.cg_old_boff = acg.cg_old_btotoff +
409		    sblock.fs_old_cpg * sizeof(int32_t);
410		acg.cg_iusedoff = acg.cg_old_boff +
411		    sblock.fs_old_cpg * sizeof(u_int16_t);
412	}
413	acg.cg_freeoff = acg.cg_iusedoff + howmany(sblock.fs_ipg, NBBY);
414	acg.cg_nextfreeoff = acg.cg_freeoff + howmany(sblock.fs_fpg, NBBY);
415	if (sblock.fs_contigsumsize > 0) {
416		acg.cg_clustersumoff =
417		    roundup(acg.cg_nextfreeoff, sizeof(u_int32_t));
418		acg.cg_clustersumoff -= sizeof(u_int32_t);
419		acg.cg_clusteroff = acg.cg_clustersumoff +
420		    (sblock.fs_contigsumsize + 1) * sizeof(u_int32_t);
421		acg.cg_nextfreeoff = acg.cg_clusteroff +
422		    howmany(fragstoblks(&sblock, sblock.fs_fpg), NBBY);
423	}
424	if (acg.cg_nextfreeoff > sblock.fs_cgsize) {
425		/*
426		 * This should never happen as we would have had that panic
427		 * already on filesystem creation
428		 */
429		errx(37, "panic: cylinder group too big");
430	}
431	acg.cg_cs.cs_nifree += sblock.fs_ipg;
432	if (cylno == 0)
433		for (i = 0; i < ROOTINO; i++) {
434			setbit(cg_inosused(&acg), i);
435			acg.cg_cs.cs_nifree--;
436		}
437	bzero(iobuf, sblock.fs_bsize);
438	for (i = 0; i < sblock.fs_ipg / INOPF(&sblock); i += sblock.fs_frag) {
439		dp1 = (struct ufs1_dinode *)iobuf;
440		dp2 = (struct ufs2_dinode *)iobuf;
441#ifdef FSIRAND
442		for (j = 0; j < INOPB(&sblock); j++)
443			if (sblock.fs_magic == FS_UFS1_MAGIC) {
444				dp1->di_gen = random();
445				dp1++;
446			} else {
447				dp2->di_gen = random();
448				dp2++;
449			}
450#endif
451		wtfs(fsbtodb(&sblock, cgimin(&sblock, cylno) + i),
452		    sblock.fs_bsize, iobuf, fso, Nflag);
453	}
454	if (cylno > 0) {
455		/*
456		 * In cylno 0, beginning space is reserved
457		 * for boot and super blocks.
458		 */
459		for (d = 0; d < dlower; d += sblock.fs_frag) {
460			blkno = d / sblock.fs_frag;
461			setblock(&sblock, cg_blksfree(&acg), blkno);
462			if (sblock.fs_contigsumsize > 0)
463				setbit(cg_clustersfree(&acg), blkno);
464			acg.cg_cs.cs_nbfree++;
465		}
466		sblock.fs_dsize += dlower;
467	}
468	sblock.fs_dsize += acg.cg_ndblk - dupper;
469	if ((i = dupper % sblock.fs_frag)) {
470		acg.cg_frsum[sblock.fs_frag - i]++;
471		for (d = dupper + sblock.fs_frag - i; dupper < d; dupper++) {
472			setbit(cg_blksfree(&acg), dupper);
473			acg.cg_cs.cs_nffree++;
474		}
475	}
476	for (d = dupper; d + sblock.fs_frag <= acg.cg_ndblk;
477	     d += sblock.fs_frag) {
478		blkno = d / sblock.fs_frag;
479		setblock(&sblock, cg_blksfree(&acg), blkno);
480		if (sblock.fs_contigsumsize > 0)
481			setbit(cg_clustersfree(&acg), blkno);
482		acg.cg_cs.cs_nbfree++;
483	}
484	if (d < acg.cg_ndblk) {
485		acg.cg_frsum[acg.cg_ndblk - d]++;
486		for (; d < acg.cg_ndblk; d++) {
487			setbit(cg_blksfree(&acg), d);
488			acg.cg_cs.cs_nffree++;
489		}
490	}
491	if (sblock.fs_contigsumsize > 0) {
492		int32_t *sump = cg_clustersum(&acg);
493		u_char *mapp = cg_clustersfree(&acg);
494		int map = *mapp++;
495		int bit = 1;
496		int run = 0;
497
498		for (i = 0; i < acg.cg_nclusterblks; i++) {
499			if ((map & bit) != 0)
500				run++;
501			else if (run != 0) {
502				if (run > sblock.fs_contigsumsize)
503					run = sblock.fs_contigsumsize;
504				sump[run]++;
505				run = 0;
506			}
507			if ((i & (NBBY - 1)) != NBBY - 1)
508				bit <<= 1;
509			else {
510				map = *mapp++;
511				bit = 1;
512			}
513		}
514		if (run != 0) {
515			if (run > sblock.fs_contigsumsize)
516				run = sblock.fs_contigsumsize;
517			sump[run]++;
518		}
519	}
520	sblock.fs_cstotal.cs_ndir += acg.cg_cs.cs_ndir;
521	sblock.fs_cstotal.cs_nffree += acg.cg_cs.cs_nffree;
522	sblock.fs_cstotal.cs_nbfree += acg.cg_cs.cs_nbfree;
523	sblock.fs_cstotal.cs_nifree += acg.cg_cs.cs_nifree;
524	*cs = acg.cg_cs;
525	wtfs(fsbtodb(&sblock, cgtod(&sblock, cylno)),
526		sblock.fs_bsize, (char *)&acg, fso, Nflag);
527	DBG_DUMP_CG(&sblock,
528	    "new cg",
529	    &acg);
530
531	DBG_LEAVE;
532	return;
533}
534
535/* ******************************************************* frag_adjust ***** */
536/*
537 * Here  we add or subtract (sign +1/-1) the available fragments in  a  given
538 * block to or from the fragment statistics. By subtracting before and adding
539 * after  an operation on the free frag map we can easy update  the  fragment
540 * statistic, which seems to be otherwise an rather complex operation.
541 */
542static void
543frag_adjust(ufs2_daddr_t frag, int sign)
544{
545	DBG_FUNC("frag_adjust")
546	int fragsize;
547	int f;
548
549	DBG_ENTER;
550
551	fragsize=0;
552	/*
553	 * Here frag only needs to point to any fragment in the block we want
554	 * to examine.
555	 */
556	for(f=rounddown(frag, sblock.fs_frag);
557	    f<roundup(frag+1, sblock.fs_frag);
558	    f++) {
559		/*
560		 * Count contiguos free fragments.
561		 */
562		if(isset(cg_blksfree(&acg), f)) {
563			fragsize++;
564		} else {
565			if(fragsize && fragsize<sblock.fs_frag) {
566				/*
567				 * We found something in between.
568				 */
569				acg.cg_frsum[fragsize]+=sign;
570				DBG_PRINT2("frag_adjust [%d]+=%d\n",
571				    fragsize,
572				    sign);
573			}
574			fragsize=0;
575		}
576	}
577	if(fragsize && fragsize<sblock.fs_frag) {
578		/*
579		 * We found something.
580		 */
581		acg.cg_frsum[fragsize]+=sign;
582		DBG_PRINT2("frag_adjust [%d]+=%d\n",
583		    fragsize,
584		    sign);
585	}
586	DBG_PRINT2("frag_adjust [[%d]]+=%d\n",
587	    fragsize,
588	    sign);
589
590	DBG_LEAVE;
591	return;
592}
593
594/* ******************************************************* cond_bl_upd ***** */
595/*
596 * Here we conditionally update a pointer to a fragment. We check for all
597 * relocated blocks if any of it's fragments is referenced by the current
598 * field,  and update the pointer to the respective fragment in  our  new
599 * block.  If  we find a reference we write back the  block  immediately,
600 * as there is no easy way for our general block reading engine to figure
601 * out if a write back operation is needed.
602 */
603static int
604cond_bl_upd(ufs2_daddr_t *block, struct gfs_bpp *field, int fsi, int fso,
605    unsigned int Nflag)
606{
607	DBG_FUNC("cond_bl_upd")
608	struct gfs_bpp *f;
609	ufs2_daddr_t src, dst;
610	int fragnum;
611	void *ibuf;
612
613	DBG_ENTER;
614
615	f = field;
616	for (f = field; f->old != 0; f++) {
617		src = *block;
618		if (fragstoblks(&sblock, src) != f->old)
619			continue;
620		/*
621		 * The fragment is part of the block, so update.
622		 */
623		dst = blkstofrags(&sblock, f->new);
624		fragnum = fragnum(&sblock, src);
625		*block = dst + fragnum;
626		f->found++;
627		DBG_PRINT3("scg (%d->%d)[%d] reference updated\n",
628		    f->old,
629		    f->new,
630		    fragnum);
631
632		/*
633		 * Copy the block back immediately.
634		 *
635		 * XXX	If src is is from an indirect block we have
636		 *	to implement copy on write here in case of
637		 *	active snapshots.
638		 */
639		ibuf = malloc(sblock.fs_bsize);
640		if (!ibuf)
641			errx(1, "malloc failed");
642		src -= fragnum;
643		rdfs(fsbtodb(&sblock, src), (size_t)sblock.fs_bsize, ibuf, fsi);
644		wtfs(dst, (size_t)sblock.fs_bsize, ibuf, fso, Nflag);
645		free(ibuf);
646		/*
647		 * The same block can't be found again in this loop.
648		 */
649		return (1);
650	}
651
652	DBG_LEAVE;
653	return (0);
654}
655
656/* ************************************************************ updjcg ***** */
657/*
658 * Here we do all needed work for the former last cylinder group. It has to be
659 * changed  in  any case, even if the filesystem ended exactly on the  end  of
660 * this  group, as there is some slightly inconsistent handling of the  number
661 * of cylinders in the cylinder group. We start again by reading the  cylinder
662 * group from disk. If the last block was not fully available, we first handle
663 * the  missing  fragments, then we handle all new full blocks  in  that  file
664 * system  and  finally we handle the new last fragmented block  in  the  file
665 * system.  We again have to handle the fragment statistics rotational  layout
666 * tables and cluster summary during all those operations.
667 */
668static void
669updjcg(int cylno, time_t utime, int fsi, int fso, unsigned int Nflag)
670{
671	DBG_FUNC("updjcg")
672	ufs2_daddr_t	cbase, dmax, dupper;
673	struct csum	*cs;
674	int	i,k;
675	int	j=0;
676
677	DBG_ENTER;
678
679	/*
680	 * Read the former last (joining) cylinder group from disk, and make
681	 * a copy.
682	 */
683	rdfs(fsbtodb(&osblock, cgtod(&osblock, cylno)),
684	    (size_t)osblock.fs_cgsize, (void *)&aocg, fsi);
685	DBG_PRINT0("jcg read\n");
686	DBG_DUMP_CG(&sblock,
687	    "old joining cg",
688	    &aocg);
689
690	memcpy((void *)&cgun1, (void *)&cgun2, sizeof(cgun2));
691
692	/*
693	 * If  the  cylinder  group had already it's  new  final  size  almost
694	 * nothing is to be done ... except:
695	 * For some reason the value of cg_ncyl in the last cylinder group has
696	 * to  be  zero instead of fs_cpg. As this is now no longer  the  last
697	 * cylinder group we have to change that value now to fs_cpg.
698	 */
699
700	if(cgbase(&osblock, cylno+1) == osblock.fs_size) {
701		if (sblock.fs_magic == FS_UFS1_MAGIC)
702			acg.cg_old_ncyl=sblock.fs_old_cpg;
703
704		wtfs(fsbtodb(&sblock, cgtod(&sblock, cylno)),
705		    (size_t)sblock.fs_cgsize, (void *)&acg, fso, Nflag);
706		DBG_PRINT0("jcg written\n");
707		DBG_DUMP_CG(&sblock,
708		    "new joining cg",
709		    &acg);
710
711		DBG_LEAVE;
712		return;
713	}
714
715	/*
716	 * Set up some variables needed later.
717	 */
718	cbase = cgbase(&sblock, cylno);
719	dmax = cbase + sblock.fs_fpg;
720	if (dmax > sblock.fs_size)
721		dmax = sblock.fs_size;
722	dupper = cgdmin(&sblock, cylno) - cbase;
723	if (cylno == 0) { /* XXX fscs may be relocated */
724		dupper += howmany(sblock.fs_cssize, sblock.fs_fsize);
725	}
726
727	/*
728	 * Set pointer to the cylinder summary for our cylinder group.
729	 */
730	cs = fscs + cylno;
731
732	/*
733	 * Touch the cylinder group, update all fields in the cylinder group as
734	 * needed, update the free space in the superblock.
735	 */
736	acg.cg_time = utime;
737	if (cylno == sblock.fs_ncg - 1) {
738		/*
739		 * This is still the last cylinder group.
740		 */
741		if (sblock.fs_magic == FS_UFS1_MAGIC)
742			acg.cg_old_ncyl =
743			    sblock.fs_old_ncyl % sblock.fs_old_cpg;
744	} else {
745		acg.cg_old_ncyl = sblock.fs_old_cpg;
746	}
747	DBG_PRINT2("jcg dbg: %d %u",
748	    cylno,
749	    sblock.fs_ncg);
750	if (sblock.fs_magic == FS_UFS1_MAGIC)
751		DBG_PRINT2("%d %u",
752		    acg.cg_old_ncyl,
753		    sblock.fs_old_cpg);
754	DBG_PRINT0("\n");
755	acg.cg_ndblk = dmax - cbase;
756	sblock.fs_dsize += acg.cg_ndblk-aocg.cg_ndblk;
757	if (sblock.fs_contigsumsize > 0) {
758		acg.cg_nclusterblks = acg.cg_ndblk / sblock.fs_frag;
759	}
760
761	/*
762	 * Now  we have to update the free fragment bitmap for our new  free
763	 * space.  There again we have to handle the fragmentation and  also
764	 * the  rotational  layout tables and the cluster summary.  This  is
765	 * also  done per fragment for the first new block if the  old  file
766	 * system end was not on a block boundary, per fragment for the  new
767	 * last block if the new filesystem end is not on a block boundary,
768	 * and per block for all space in between.
769	 *
770	 * Handle the first new block here if it was partially available
771	 * before.
772	 */
773	if(osblock.fs_size % sblock.fs_frag) {
774		if(roundup(osblock.fs_size, sblock.fs_frag)<=sblock.fs_size) {
775			/*
776			 * The new space is enough to fill at least this
777			 * block
778			 */
779			j=0;
780			for(i=roundup(osblock.fs_size-cbase, sblock.fs_frag)-1;
781			    i>=osblock.fs_size-cbase;
782			    i--) {
783				setbit(cg_blksfree(&acg), i);
784				acg.cg_cs.cs_nffree++;
785				j++;
786			}
787
788			/*
789			 * Check  if the fragment just created could join  an
790			 * already existing fragment at the former end of the
791			 * filesystem.
792			 */
793			if(isblock(&sblock, cg_blksfree(&acg),
794			    ((osblock.fs_size - cgbase(&sblock, cylno))/
795			    sblock.fs_frag))) {
796				/*
797				 * The block is now completely available
798				 */
799				DBG_PRINT0("block was\n");
800				acg.cg_frsum[osblock.fs_size%sblock.fs_frag]--;
801				acg.cg_cs.cs_nbfree++;
802				acg.cg_cs.cs_nffree-=sblock.fs_frag;
803				k=rounddown(osblock.fs_size-cbase,
804				    sblock.fs_frag);
805				updclst((osblock.fs_size-cbase)/sblock.fs_frag);
806			} else {
807				/*
808				 * Lets rejoin a possible partially growed
809				 * fragment.
810				 */
811				k=0;
812				while(isset(cg_blksfree(&acg), i) &&
813				    (i>=rounddown(osblock.fs_size-cbase,
814				    sblock.fs_frag))) {
815					i--;
816					k++;
817				}
818				if(k) {
819					acg.cg_frsum[k]--;
820				}
821				acg.cg_frsum[k+j]++;
822			}
823		} else {
824			/*
825			 * We only grow by some fragments within this last
826			 * block.
827			 */
828			for(i=sblock.fs_size-cbase-1;
829				i>=osblock.fs_size-cbase;
830				i--) {
831				setbit(cg_blksfree(&acg), i);
832				acg.cg_cs.cs_nffree++;
833				j++;
834			}
835			/*
836			 * Lets rejoin a possible partially growed fragment.
837			 */
838			k=0;
839			while(isset(cg_blksfree(&acg), i) &&
840			    (i>=rounddown(osblock.fs_size-cbase,
841			    sblock.fs_frag))) {
842				i--;
843				k++;
844			}
845			if(k) {
846				acg.cg_frsum[k]--;
847			}
848			acg.cg_frsum[k+j]++;
849		}
850	}
851
852	/*
853	 * Handle all new complete blocks here.
854	 */
855	for(i=roundup(osblock.fs_size-cbase, sblock.fs_frag);
856	    i+sblock.fs_frag<=dmax-cbase;	/* XXX <= or only < ? */
857	    i+=sblock.fs_frag) {
858		j = i / sblock.fs_frag;
859		setblock(&sblock, cg_blksfree(&acg), j);
860		updclst(j);
861		acg.cg_cs.cs_nbfree++;
862	}
863
864	/*
865	 * Handle the last new block if there are stll some new fragments left.
866	 * Here  we don't have to bother about the cluster summary or the  even
867	 * the rotational layout table.
868	 */
869	if (i < (dmax - cbase)) {
870		acg.cg_frsum[dmax - cbase - i]++;
871		for (; i < dmax - cbase; i++) {
872			setbit(cg_blksfree(&acg), i);
873			acg.cg_cs.cs_nffree++;
874		}
875	}
876
877	sblock.fs_cstotal.cs_nffree +=
878	    (acg.cg_cs.cs_nffree - aocg.cg_cs.cs_nffree);
879	sblock.fs_cstotal.cs_nbfree +=
880	    (acg.cg_cs.cs_nbfree - aocg.cg_cs.cs_nbfree);
881	/*
882	 * The following statistics are not changed here:
883	 *     sblock.fs_cstotal.cs_ndir
884	 *     sblock.fs_cstotal.cs_nifree
885	 * As the statistics for this cylinder group are ready, copy it to
886	 * the summary information array.
887	 */
888	*cs = acg.cg_cs;
889
890	/*
891	 * Write the updated "joining" cylinder group back to disk.
892	 */
893	wtfs(fsbtodb(&sblock, cgtod(&sblock, cylno)), (size_t)sblock.fs_cgsize,
894	    (void *)&acg, fso, Nflag);
895	DBG_PRINT0("jcg written\n");
896	DBG_DUMP_CG(&sblock,
897	    "new joining cg",
898	    &acg);
899
900	DBG_LEAVE;
901	return;
902}
903
904/* ********************************************************** updcsloc ***** */
905/*
906 * Here  we update the location of the cylinder summary. We have  two  possible
907 * ways of growing the cylinder summary.
908 * (1)	We can try to grow the summary in the current location, and  relocate
909 *	possibly used blocks within the current cylinder group.
910 * (2)	Alternatively we can relocate the whole cylinder summary to the first
911 *	new completely empty cylinder group. Once the cylinder summary is  no
912 *	longer in the beginning of the first cylinder group you should  never
913 *	use  a version of fsck which is not aware of the possibility to  have
914 *	this structure in a non standard place.
915 * Option (1) is considered to be less intrusive to the structure of the  file-
916 * system. So we try to stick to that whenever possible. If there is not enough
917 * space  in the cylinder group containing the cylinder summary we have to  use
918 * method  (2). In case of active snapshots in the filesystem we  probably  can
919 * completely avoid implementing copy on write if we stick to method (2) only.
920 */
921static void
922updcsloc(time_t utime, int fsi, int fso, unsigned int Nflag)
923{
924	DBG_FUNC("updcsloc")
925	struct csum	*cs;
926	int	ocscg, ncscg;
927	int	blocks;
928	ufs2_daddr_t	cbase, dupper, odupper, d, f, g;
929	int	ind;
930	int	cylno, inc;
931	struct gfs_bpp	*bp;
932	int	i, l;
933	int	lcs=0;
934	int	block;
935
936	DBG_ENTER;
937
938	if(howmany(sblock.fs_cssize, sblock.fs_fsize) ==
939	    howmany(osblock.fs_cssize, osblock.fs_fsize)) {
940		/*
941		 * No new fragment needed.
942		 */
943		DBG_LEAVE;
944		return;
945	}
946	ocscg=dtog(&osblock, osblock.fs_csaddr);
947	cs=fscs+ocscg;
948	blocks = 1+howmany(sblock.fs_cssize, sblock.fs_bsize)-
949	    howmany(osblock.fs_cssize, osblock.fs_bsize);
950
951	/*
952	 * Read original cylinder group from disk, and make a copy.
953	 * XXX	If Nflag is set in some very rare cases we now miss
954	 *	some changes done in updjcg by reading the unmodified
955	 *	block from disk.
956	 */
957	rdfs(fsbtodb(&osblock, cgtod(&osblock, ocscg)),
958	    (size_t)osblock.fs_cgsize, (void *)&aocg, fsi);
959	DBG_PRINT0("oscg read\n");
960	DBG_DUMP_CG(&sblock,
961	    "old summary cg",
962	    &aocg);
963
964	memcpy((void *)&cgun1, (void *)&cgun2, sizeof(cgun2));
965
966	/*
967	 * Touch the cylinder group, set up local variables needed later
968	 * and update the superblock.
969	 */
970	acg.cg_time = utime;
971
972	/*
973	 * XXX	In the case of having active snapshots we may need much more
974	 *	blocks for the copy on write. We need each block twice,  and
975	 *	also  up to 8*3 blocks for indirect blocks for all  possible
976	 *	references.
977	 */
978	if(/*((int)sblock.fs_time&0x3)>0||*/ cs->cs_nbfree < blocks) {
979		/*
980		 * There  is  not enough space in the old cylinder  group  to
981		 * relocate  all blocks as needed, so we relocate  the  whole
982		 * cylinder  group summary to a new group. We try to use  the
983		 * first complete new cylinder group just created. Within the
984		 * cylinder  group we allign the area immediately  after  the
985		 * cylinder  group  information location in order  to  be  as
986		 * close as possible to the original implementation of ffs.
987		 *
988		 * First  we have to make sure we'll find enough space in  the
989		 * new  cylinder  group. If not, then we  currently  give  up.
990		 * We  start  with freeing everything which was  used  by  the
991		 * fragments of the old cylinder summary in the current group.
992		 * Now  we write back the group meta data, read in the  needed
993		 * meta data from the new cylinder group, and start allocating
994		 * within  that  group. Here we can assume, the  group  to  be
995		 * completely empty. Which makes the handling of fragments and
996		 * clusters a lot easier.
997		 */
998		DBG_TRC;
999		if(sblock.fs_ncg-osblock.fs_ncg < 2) {
1000			errx(2, "panic: not enough space");
1001		}
1002
1003		/*
1004		 * Point "d" to the first fragment not used by the cylinder
1005		 * summary.
1006		 */
1007		d=osblock.fs_csaddr+(osblock.fs_cssize/osblock.fs_fsize);
1008
1009		/*
1010		 * Set up last cluster size ("lcs") already here. Calculate
1011		 * the size for the trailing cluster just behind where  "d"
1012		 * points to.
1013		 */
1014		if(sblock.fs_contigsumsize > 0) {
1015			for(block=howmany(d%sblock.fs_fpg, sblock.fs_frag),
1016			    lcs=0; lcs<sblock.fs_contigsumsize;
1017			    block++, lcs++) {
1018				if(isclr(cg_clustersfree(&acg), block)){
1019					break;
1020				}
1021			}
1022		}
1023
1024		/*
1025		 * Point "d" to the last frag used by the cylinder summary.
1026		 */
1027		d--;
1028
1029		DBG_PRINT1("d=%d\n",
1030		    d);
1031		if((d+1)%sblock.fs_frag) {
1032			/*
1033			 * The end of the cylinder summary is not a complete
1034			 * block.
1035			 */
1036			DBG_TRC;
1037			frag_adjust(d%sblock.fs_fpg, -1);
1038			for(; (d+1)%sblock.fs_frag; d--) {
1039				DBG_PRINT1("d=%d\n",
1040				    d);
1041				setbit(cg_blksfree(&acg), d%sblock.fs_fpg);
1042				acg.cg_cs.cs_nffree++;
1043				sblock.fs_cstotal.cs_nffree++;
1044			}
1045			/*
1046			 * Point  "d" to the last fragment of the  last
1047			 * (incomplete) block of the clinder summary.
1048			 */
1049			d++;
1050			frag_adjust(d%sblock.fs_fpg, 1);
1051
1052			if(isblock(&sblock, cg_blksfree(&acg),
1053			    (d%sblock.fs_fpg)/sblock.fs_frag)) {
1054				DBG_PRINT1("d=%d\n",
1055				    d);
1056				acg.cg_cs.cs_nffree-=sblock.fs_frag;
1057				acg.cg_cs.cs_nbfree++;
1058				sblock.fs_cstotal.cs_nffree-=sblock.fs_frag;
1059				sblock.fs_cstotal.cs_nbfree++;
1060				if(sblock.fs_contigsumsize > 0) {
1061					setbit(cg_clustersfree(&acg),
1062					    (d%sblock.fs_fpg)/sblock.fs_frag);
1063					if(lcs < sblock.fs_contigsumsize) {
1064						if(lcs) {
1065							cg_clustersum(&acg)
1066							    [lcs]--;
1067						}
1068						lcs++;
1069						cg_clustersum(&acg)[lcs]++;
1070					}
1071				}
1072			}
1073			/*
1074			 * Point "d" to the first fragment of the block before
1075			 * the last incomplete block.
1076			 */
1077			d--;
1078		}
1079
1080		DBG_PRINT1("d=%d\n",
1081		    d);
1082		for(d=rounddown(d, sblock.fs_frag); d >= osblock.fs_csaddr;
1083		    d-=sblock.fs_frag) {
1084			DBG_TRC;
1085			DBG_PRINT1("d=%d\n",
1086			    d);
1087			setblock(&sblock, cg_blksfree(&acg),
1088			    (d%sblock.fs_fpg)/sblock.fs_frag);
1089			acg.cg_cs.cs_nbfree++;
1090			sblock.fs_cstotal.cs_nbfree++;
1091			if(sblock.fs_contigsumsize > 0) {
1092				setbit(cg_clustersfree(&acg),
1093				    (d%sblock.fs_fpg)/sblock.fs_frag);
1094				/*
1095				 * The last cluster size is already set up.
1096				 */
1097				if(lcs < sblock.fs_contigsumsize) {
1098					if(lcs) {
1099						cg_clustersum(&acg)[lcs]--;
1100					}
1101					lcs++;
1102					cg_clustersum(&acg)[lcs]++;
1103				}
1104			}
1105		}
1106		*cs = acg.cg_cs;
1107
1108		/*
1109		 * Now write the former cylinder group containing the cylinder
1110		 * summary back to disk.
1111		 */
1112		wtfs(fsbtodb(&sblock, cgtod(&sblock, ocscg)),
1113		    (size_t)sblock.fs_cgsize, (void *)&acg, fso, Nflag);
1114		DBG_PRINT0("oscg written\n");
1115		DBG_DUMP_CG(&sblock,
1116		    "old summary cg",
1117		    &acg);
1118
1119		/*
1120		 * Find the beginning of the new cylinder group containing the
1121		 * cylinder summary.
1122		 */
1123		sblock.fs_csaddr=cgdmin(&sblock, osblock.fs_ncg);
1124		ncscg=dtog(&sblock, sblock.fs_csaddr);
1125		cs=fscs+ncscg;
1126
1127
1128		/*
1129		 * If Nflag is specified, we would now read random data instead
1130		 * of an empty cg structure from disk. So we can't simulate that
1131		 * part for now.
1132		 */
1133		if(Nflag) {
1134			DBG_PRINT0("nscg update skipped\n");
1135			DBG_LEAVE;
1136			return;
1137		}
1138
1139		/*
1140		 * Read the future cylinder group containing the cylinder
1141		 * summary from disk, and make a copy.
1142		 */
1143		rdfs(fsbtodb(&sblock, cgtod(&sblock, ncscg)),
1144		    (size_t)sblock.fs_cgsize, (void *)&aocg, fsi);
1145		DBG_PRINT0("nscg read\n");
1146		DBG_DUMP_CG(&sblock,
1147		    "new summary cg",
1148		    &aocg);
1149
1150		memcpy((void *)&cgun1, (void *)&cgun2, sizeof(cgun2));
1151
1152		/*
1153		 * Allocate all complete blocks used by the new cylinder
1154		 * summary.
1155		 */
1156		for(d=sblock.fs_csaddr; d+sblock.fs_frag <=
1157		    sblock.fs_csaddr+(sblock.fs_cssize/sblock.fs_fsize);
1158		    d+=sblock.fs_frag) {
1159			clrblock(&sblock, cg_blksfree(&acg),
1160			    (d%sblock.fs_fpg)/sblock.fs_frag);
1161			acg.cg_cs.cs_nbfree--;
1162			sblock.fs_cstotal.cs_nbfree--;
1163			if(sblock.fs_contigsumsize > 0) {
1164				clrbit(cg_clustersfree(&acg),
1165				    (d%sblock.fs_fpg)/sblock.fs_frag);
1166			}
1167		}
1168
1169		/*
1170		 * Allocate all fragments used by the cylinder summary in the
1171		 * last block.
1172		 */
1173		if(d<sblock.fs_csaddr+(sblock.fs_cssize/sblock.fs_fsize)) {
1174			for(; d-sblock.fs_csaddr<
1175			    sblock.fs_cssize/sblock.fs_fsize;
1176			    d++) {
1177				clrbit(cg_blksfree(&acg), d%sblock.fs_fpg);
1178				acg.cg_cs.cs_nffree--;
1179				sblock.fs_cstotal.cs_nffree--;
1180			}
1181			acg.cg_cs.cs_nbfree--;
1182			acg.cg_cs.cs_nffree+=sblock.fs_frag;
1183			sblock.fs_cstotal.cs_nbfree--;
1184			sblock.fs_cstotal.cs_nffree+=sblock.fs_frag;
1185			if(sblock.fs_contigsumsize > 0) {
1186				clrbit(cg_clustersfree(&acg),
1187				    (d%sblock.fs_fpg)/sblock.fs_frag);
1188			}
1189
1190			frag_adjust(d%sblock.fs_fpg, +1);
1191		}
1192		/*
1193		 * XXX	Handle the cluster statistics here in the case  this
1194		 *	cylinder group is now almost full, and the remaining
1195		 *	space is less then the maximum cluster size. This is
1196		 *	probably not needed, as you would hardly find a file
1197		 *	system which has only MAXCSBUFS+FS_MAXCONTIG of free
1198		 *	space right behind the cylinder group information in
1199		 *	any new cylinder group.
1200		 */
1201
1202		/*
1203		 * Update our statistics in the cylinder summary.
1204		 */
1205		*cs = acg.cg_cs;
1206
1207		/*
1208		 * Write the new cylinder group containing the cylinder summary
1209		 * back to disk.
1210		 */
1211		wtfs(fsbtodb(&sblock, cgtod(&sblock, ncscg)),
1212		    (size_t)sblock.fs_cgsize, (void *)&acg, fso, Nflag);
1213		DBG_PRINT0("nscg written\n");
1214		DBG_DUMP_CG(&sblock,
1215		    "new summary cg",
1216		    &acg);
1217
1218		DBG_LEAVE;
1219		return;
1220	}
1221	/*
1222	 * We have got enough of space in the current cylinder group, so we
1223	 * can relocate just a few blocks, and let the summary  information
1224	 * grow in place where it is right now.
1225	 */
1226	DBG_TRC;
1227
1228	cbase = cgbase(&osblock, ocscg);	/* old and new are equal */
1229	dupper = sblock.fs_csaddr - cbase +
1230	    howmany(sblock.fs_cssize, sblock.fs_fsize);
1231	odupper = osblock.fs_csaddr - cbase +
1232	    howmany(osblock.fs_cssize, osblock.fs_fsize);
1233
1234	sblock.fs_dsize -= dupper-odupper;
1235
1236	/*
1237	 * Allocate the space for the array of blocks to be relocated.
1238	 */
1239 	bp=(struct gfs_bpp *)malloc(((dupper-odupper)/sblock.fs_frag+2)*
1240	    sizeof(struct gfs_bpp));
1241	if(bp == NULL) {
1242		errx(1, "malloc failed");
1243	}
1244	memset((char *)bp, 0, ((dupper-odupper)/sblock.fs_frag+2)*
1245	    sizeof(struct gfs_bpp));
1246
1247	/*
1248	 * Lock all new frags needed for the cylinder group summary. This  is
1249	 * done per fragment in the first and last block of the new  required
1250	 * area, and per block for all other blocks.
1251	 *
1252	 * Handle the first new  block here (but only if some fragments where
1253	 * already used for the cylinder summary).
1254	 */
1255	ind=0;
1256	frag_adjust(odupper, -1);
1257	for(d=odupper; ((d<dupper)&&(d%sblock.fs_frag)); d++) {
1258		DBG_PRINT1("scg first frag check loop d=%d\n",
1259		    d);
1260		if(isclr(cg_blksfree(&acg), d)) {
1261			if (!ind) {
1262				bp[ind].old=d/sblock.fs_frag;
1263				bp[ind].flags|=GFS_FL_FIRST;
1264				if(roundup(d, sblock.fs_frag) >= dupper) {
1265					bp[ind].flags|=GFS_FL_LAST;
1266				}
1267				ind++;
1268			}
1269		} else {
1270			clrbit(cg_blksfree(&acg), d);
1271			acg.cg_cs.cs_nffree--;
1272			sblock.fs_cstotal.cs_nffree--;
1273		}
1274		/*
1275		 * No cluster handling is needed here, as there was at least
1276		 * one  fragment in use by the cylinder summary in  the  old
1277		 * filesystem.
1278		 * No block-free counter handling here as this block was not
1279		 * a free block.
1280		 */
1281	}
1282	frag_adjust(odupper, 1);
1283
1284	/*
1285	 * Handle all needed complete blocks here.
1286	 */
1287	for(; d+sblock.fs_frag<=dupper; d+=sblock.fs_frag) {
1288		DBG_PRINT1("scg block check loop d=%d\n",
1289		    d);
1290		if(!isblock(&sblock, cg_blksfree(&acg), d/sblock.fs_frag)) {
1291			for(f=d; f<d+sblock.fs_frag; f++) {
1292				if(isset(cg_blksfree(&aocg), f)) {
1293					acg.cg_cs.cs_nffree--;
1294					sblock.fs_cstotal.cs_nffree--;
1295				}
1296			}
1297			clrblock(&sblock, cg_blksfree(&acg), d/sblock.fs_frag);
1298			bp[ind].old=d/sblock.fs_frag;
1299			ind++;
1300		} else {
1301			clrblock(&sblock, cg_blksfree(&acg), d/sblock.fs_frag);
1302			acg.cg_cs.cs_nbfree--;
1303			sblock.fs_cstotal.cs_nbfree--;
1304			if(sblock.fs_contigsumsize > 0) {
1305				clrbit(cg_clustersfree(&acg), d/sblock.fs_frag);
1306				for(lcs=0, l=(d/sblock.fs_frag)+1;
1307				    lcs<sblock.fs_contigsumsize;
1308				    l++, lcs++ ) {
1309					if(isclr(cg_clustersfree(&acg),l)){
1310						break;
1311					}
1312				}
1313				if(lcs < sblock.fs_contigsumsize) {
1314					cg_clustersum(&acg)[lcs+1]--;
1315					if(lcs) {
1316						cg_clustersum(&acg)[lcs]++;
1317					}
1318				}
1319			}
1320		}
1321		/*
1322		 * No fragment counter handling is needed here, as this finally
1323		 * doesn't change after the relocation.
1324		 */
1325	}
1326
1327	/*
1328	 * Handle all fragments needed in the last new affected block.
1329	 */
1330	if(d<dupper) {
1331		frag_adjust(dupper-1, -1);
1332
1333		if(isblock(&sblock, cg_blksfree(&acg), d/sblock.fs_frag)) {
1334			acg.cg_cs.cs_nbfree--;
1335			sblock.fs_cstotal.cs_nbfree--;
1336			acg.cg_cs.cs_nffree+=sblock.fs_frag;
1337			sblock.fs_cstotal.cs_nffree+=sblock.fs_frag;
1338			if(sblock.fs_contigsumsize > 0) {
1339				clrbit(cg_clustersfree(&acg), d/sblock.fs_frag);
1340				for(lcs=0, l=(d/sblock.fs_frag)+1;
1341				    lcs<sblock.fs_contigsumsize;
1342				    l++, lcs++ ) {
1343					if(isclr(cg_clustersfree(&acg),l)){
1344						break;
1345					}
1346				}
1347				if(lcs < sblock.fs_contigsumsize) {
1348					cg_clustersum(&acg)[lcs+1]--;
1349					if(lcs) {
1350						cg_clustersum(&acg)[lcs]++;
1351					}
1352				}
1353			}
1354		}
1355
1356		for(; d<dupper; d++) {
1357			DBG_PRINT1("scg second frag check loop d=%d\n",
1358			    d);
1359			if(isclr(cg_blksfree(&acg), d)) {
1360				bp[ind].old=d/sblock.fs_frag;
1361				bp[ind].flags|=GFS_FL_LAST;
1362			} else {
1363				clrbit(cg_blksfree(&acg), d);
1364				acg.cg_cs.cs_nffree--;
1365				sblock.fs_cstotal.cs_nffree--;
1366			}
1367		}
1368		if(bp[ind].flags & GFS_FL_LAST) { /* we have to advance here */
1369			ind++;
1370		}
1371		frag_adjust(dupper-1, 1);
1372	}
1373
1374	/*
1375	 * If we found a block to relocate just do so.
1376	 */
1377	if(ind) {
1378		for(i=0; i<ind; i++) {
1379			if(!bp[i].old) { /* no more blocks listed */
1380				/*
1381				 * XXX	A relative blocknumber should not be
1382				 *	zero,   which  is   not   explicitly
1383				 *	guaranteed by our code.
1384				 */
1385				break;
1386			}
1387			/*
1388			 * Allocate a complete block in the same (current)
1389			 * cylinder group.
1390			 */
1391			bp[i].new=alloc()/sblock.fs_frag;
1392
1393			/*
1394			 * There is no frag_adjust() needed for the new block
1395			 * as it will have no fragments yet :-).
1396			 */
1397			for(f=bp[i].old*sblock.fs_frag,
1398			    g=bp[i].new*sblock.fs_frag;
1399			    f<(bp[i].old+1)*sblock.fs_frag;
1400			    f++, g++) {
1401				if(isset(cg_blksfree(&aocg), f)) {
1402					setbit(cg_blksfree(&acg), g);
1403					acg.cg_cs.cs_nffree++;
1404					sblock.fs_cstotal.cs_nffree++;
1405				}
1406			}
1407
1408			/*
1409			 * Special handling is required if this was the  first
1410			 * block. We have to consider the fragments which were
1411			 * used by the cylinder summary in the original  block
1412			 * which  re to be free in the copy of our  block.  We
1413			 * have  to be careful if this first block happens  to
1414			 * be also the last block to be relocated.
1415			 */
1416			if(bp[i].flags & GFS_FL_FIRST) {
1417				for(f=bp[i].old*sblock.fs_frag,
1418				    g=bp[i].new*sblock.fs_frag;
1419				    f<odupper;
1420				    f++, g++) {
1421					setbit(cg_blksfree(&acg), g);
1422					acg.cg_cs.cs_nffree++;
1423					sblock.fs_cstotal.cs_nffree++;
1424				}
1425				if(!(bp[i].flags & GFS_FL_LAST)) {
1426					frag_adjust(bp[i].new*sblock.fs_frag,1);
1427				}
1428
1429			}
1430
1431			/*
1432			 * Special handling is required if this is the last
1433			 * block to be relocated.
1434			 */
1435			if(bp[i].flags & GFS_FL_LAST) {
1436				frag_adjust(bp[i].new*sblock.fs_frag, 1);
1437				frag_adjust(bp[i].old*sblock.fs_frag, -1);
1438				for(f=dupper;
1439				    f<roundup(dupper, sblock.fs_frag);
1440				    f++) {
1441					if(isclr(cg_blksfree(&acg), f)) {
1442						setbit(cg_blksfree(&acg), f);
1443						acg.cg_cs.cs_nffree++;
1444						sblock.fs_cstotal.cs_nffree++;
1445					}
1446				}
1447				frag_adjust(bp[i].old*sblock.fs_frag, 1);
1448			}
1449
1450			/*
1451			 * !!! Attach the cylindergroup offset here.
1452			 */
1453			bp[i].old+=cbase/sblock.fs_frag;
1454			bp[i].new+=cbase/sblock.fs_frag;
1455
1456			/*
1457			 * Copy the content of the block.
1458			 */
1459			/*
1460			 * XXX	Here we will have to implement a copy on write
1461			 *	in the case we have any active snapshots.
1462			 */
1463			rdfs(fsbtodb(&sblock, bp[i].old*sblock.fs_frag),
1464			    (size_t)sblock.fs_bsize, (void *)&ablk, fsi);
1465			wtfs(fsbtodb(&sblock, bp[i].new*sblock.fs_frag),
1466			    (size_t)sblock.fs_bsize, (void *)&ablk, fso, Nflag);
1467			DBG_DUMP_HEX(&sblock,
1468			    "copied full block",
1469			    (unsigned char *)&ablk);
1470
1471			DBG_PRINT2("scg (%d->%d) block relocated\n",
1472			    bp[i].old,
1473			    bp[i].new);
1474		}
1475
1476		/*
1477		 * Now we have to update all references to any fragment which
1478		 * belongs  to any block relocated. We iterate now  over  all
1479		 * cylinder  groups,  within those over all non  zero  length
1480		 * inodes.
1481		 */
1482		for(cylno=0; cylno<osblock.fs_ncg; cylno++) {
1483			DBG_PRINT1("scg doing cg (%d)\n",
1484			    cylno);
1485			for(inc=osblock.fs_ipg-1 ; inc>=0 ; inc--) {
1486				updrefs(cylno, (ino_t)inc, bp, fsi, fso, Nflag);
1487			}
1488		}
1489
1490		/*
1491		 * All inodes are checked, now make sure the number of
1492		 * references found make sense.
1493		 */
1494		for(i=0; i<ind; i++) {
1495			if(!bp[i].found || (bp[i].found>sblock.fs_frag)) {
1496				warnx("error: %d refs found for block %d.",
1497				    bp[i].found, bp[i].old);
1498			}
1499
1500		}
1501	}
1502	/*
1503	 * The following statistics are not changed here:
1504	 *     sblock.fs_cstotal.cs_ndir
1505	 *     sblock.fs_cstotal.cs_nifree
1506	 * The following statistics were already updated on the fly:
1507	 *     sblock.fs_cstotal.cs_nffree
1508	 *     sblock.fs_cstotal.cs_nbfree
1509	 * As the statistics for this cylinder group are ready, copy it to
1510	 * the summary information array.
1511	 */
1512
1513	*cs = acg.cg_cs;
1514
1515	/*
1516	 * Write summary cylinder group back to disk.
1517	 */
1518	wtfs(fsbtodb(&sblock, cgtod(&sblock, ocscg)), (size_t)sblock.fs_cgsize,
1519	    (void *)&acg, fso, Nflag);
1520	DBG_PRINT0("scg written\n");
1521	DBG_DUMP_CG(&sblock,
1522	    "new summary cg",
1523	    &acg);
1524
1525	DBG_LEAVE;
1526	return;
1527}
1528
1529/* ************************************************************** rdfs ***** */
1530/*
1531 * Here we read some block(s) from disk.
1532 */
1533static void
1534rdfs(ufs2_daddr_t bno, size_t size, void *bf, int fsi)
1535{
1536	DBG_FUNC("rdfs")
1537	ssize_t	n;
1538
1539	DBG_ENTER;
1540
1541	if (lseek(fsi, (off_t)bno * DEV_BSIZE, 0) < 0) {
1542		err(33, "rdfs: seek error: %ld", (long)bno);
1543	}
1544	n = read(fsi, bf, size);
1545	if (n != (ssize_t)size) {
1546		err(34, "rdfs: read error: %ld", (long)bno);
1547	}
1548
1549	DBG_LEAVE;
1550	return;
1551}
1552
1553/* ************************************************************** wtfs ***** */
1554/*
1555 * Here we write some block(s) to disk.
1556 */
1557static void
1558wtfs(ufs2_daddr_t bno, size_t size, void *bf, int fso, unsigned int Nflag)
1559{
1560	DBG_FUNC("wtfs")
1561	ssize_t	n;
1562
1563	DBG_ENTER;
1564
1565	if (Nflag) {
1566		DBG_LEAVE;
1567		return;
1568	}
1569	if (lseek(fso, (off_t)bno * DEV_BSIZE, SEEK_SET) < 0) {
1570		err(35, "wtfs: seek error: %ld", (long)bno);
1571	}
1572	n = write(fso, bf, size);
1573	if (n != (ssize_t)size) {
1574		err(36, "wtfs: write error: %ld", (long)bno);
1575	}
1576
1577	DBG_LEAVE;
1578	return;
1579}
1580
1581/* ************************************************************* alloc ***** */
1582/*
1583 * Here we allocate a free block in the current cylinder group. It is assumed,
1584 * that  acg contains the current cylinder group. As we may take a block  from
1585 * somewhere in the filesystem we have to handle cluster summary here.
1586 */
1587static ufs2_daddr_t
1588alloc(void)
1589{
1590	DBG_FUNC("alloc")
1591	ufs2_daddr_t	d, blkno;
1592	int	lcs1, lcs2;
1593	int	l;
1594	int	csmin, csmax;
1595	int	dlower, dupper, dmax;
1596
1597	DBG_ENTER;
1598
1599	if (acg.cg_magic != CG_MAGIC) {
1600		warnx("acg: bad magic number");
1601		DBG_LEAVE;
1602		return (0);
1603	}
1604	if (acg.cg_cs.cs_nbfree == 0) {
1605		warnx("error: cylinder group ran out of space");
1606		DBG_LEAVE;
1607		return (0);
1608	}
1609	/*
1610	 * We start seeking for free blocks only from the space available after
1611	 * the  end of the new grown cylinder summary. Otherwise we allocate  a
1612	 * block here which we have to relocate a couple of seconds later again
1613	 * again, and we are not prepared to to this anyway.
1614	 */
1615	blkno=-1;
1616	dlower=cgsblock(&sblock, acg.cg_cgx)-cgbase(&sblock, acg.cg_cgx);
1617	dupper=cgdmin(&sblock, acg.cg_cgx)-cgbase(&sblock, acg.cg_cgx);
1618	dmax=cgbase(&sblock, acg.cg_cgx)+sblock.fs_fpg;
1619	if (dmax > sblock.fs_size) {
1620		dmax = sblock.fs_size;
1621	}
1622	dmax-=cgbase(&sblock, acg.cg_cgx); /* retransform into cg */
1623	csmin=sblock.fs_csaddr-cgbase(&sblock, acg.cg_cgx);
1624	csmax=csmin+howmany(sblock.fs_cssize, sblock.fs_fsize);
1625	DBG_PRINT3("seek range: dl=%d, du=%d, dm=%d\n",
1626	    dlower,
1627	    dupper,
1628	    dmax);
1629	DBG_PRINT2("range cont: csmin=%d, csmax=%d\n",
1630	    csmin,
1631	    csmax);
1632
1633	for(d=0; (d<dlower && blkno==-1); d+=sblock.fs_frag) {
1634		if(d>=csmin && d<=csmax) {
1635			continue;
1636		}
1637		if(isblock(&sblock, cg_blksfree(&acg), fragstoblks(&sblock,
1638		    d))) {
1639			blkno = fragstoblks(&sblock, d);/* Yeah found a block */
1640			break;
1641		}
1642	}
1643	for(d=dupper; (d<dmax && blkno==-1); d+=sblock.fs_frag) {
1644		if(d>=csmin && d<=csmax) {
1645			continue;
1646		}
1647		if(isblock(&sblock, cg_blksfree(&acg), fragstoblks(&sblock,
1648		    d))) {
1649			blkno = fragstoblks(&sblock, d);/* Yeah found a block */
1650			break;
1651		}
1652	}
1653	if(blkno==-1) {
1654		warnx("internal error: couldn't find promised block in cg");
1655		DBG_LEAVE;
1656		return (0);
1657	}
1658
1659	/*
1660	 * This is needed if the block was found already in the first loop.
1661	 */
1662	d=blkstofrags(&sblock, blkno);
1663
1664	clrblock(&sblock, cg_blksfree(&acg), blkno);
1665	if (sblock.fs_contigsumsize > 0) {
1666		/*
1667		 * Handle the cluster allocation bitmap.
1668		 */
1669		clrbit(cg_clustersfree(&acg), blkno);
1670		/*
1671		 * We  possibly have split a cluster here, so we have  to  do
1672		 * recalculate the sizes of the remaining cluster halves now,
1673		 * and use them for updating the cluster summary information.
1674		 *
1675		 * Lets start with the blocks before our allocated block ...
1676		 */
1677		for(lcs1=0, l=blkno-1; lcs1<sblock.fs_contigsumsize;
1678		    l--, lcs1++ ) {
1679			if(isclr(cg_clustersfree(&acg),l)){
1680				break;
1681			}
1682		}
1683		/*
1684		 * ... and continue with the blocks right after our allocated
1685		 * block.
1686		 */
1687		for(lcs2=0, l=blkno+1; lcs2<sblock.fs_contigsumsize;
1688		    l++, lcs2++ ) {
1689			if(isclr(cg_clustersfree(&acg),l)){
1690				break;
1691			}
1692		}
1693
1694		/*
1695		 * Now update all counters.
1696		 */
1697		cg_clustersum(&acg)[MIN(lcs1+lcs2+1,sblock.fs_contigsumsize)]--;
1698		if(lcs1) {
1699			cg_clustersum(&acg)[lcs1]++;
1700		}
1701		if(lcs2) {
1702			cg_clustersum(&acg)[lcs2]++;
1703		}
1704	}
1705	/*
1706	 * Update all statistics based on blocks.
1707	 */
1708	acg.cg_cs.cs_nbfree--;
1709	sblock.fs_cstotal.cs_nbfree--;
1710
1711	DBG_LEAVE;
1712	return (d);
1713}
1714
1715/* *********************************************************** isblock ***** */
1716/*
1717 * Here  we check if all frags of a block are free. For more details  again
1718 * please see the source of newfs(8), as this function is taken over almost
1719 * unchanged.
1720 */
1721static int
1722isblock(struct fs *fs, unsigned char *cp, int h)
1723{
1724	DBG_FUNC("isblock")
1725	unsigned char	mask;
1726
1727	DBG_ENTER;
1728
1729	switch (fs->fs_frag) {
1730	case 8:
1731		DBG_LEAVE;
1732		return (cp[h] == 0xff);
1733	case 4:
1734		mask = 0x0f << ((h & 0x1) << 2);
1735		DBG_LEAVE;
1736		return ((cp[h >> 1] & mask) == mask);
1737	case 2:
1738		mask = 0x03 << ((h & 0x3) << 1);
1739		DBG_LEAVE;
1740		return ((cp[h >> 2] & mask) == mask);
1741	case 1:
1742		mask = 0x01 << (h & 0x7);
1743		DBG_LEAVE;
1744		return ((cp[h >> 3] & mask) == mask);
1745	default:
1746		fprintf(stderr, "isblock bad fs_frag %d\n", fs->fs_frag);
1747		DBG_LEAVE;
1748		return (0);
1749	}
1750}
1751
1752/* ********************************************************** clrblock ***** */
1753/*
1754 * Here we allocate a complete block in the block map. For more details again
1755 * please  see the source of newfs(8), as this function is taken over  almost
1756 * unchanged.
1757 */
1758static void
1759clrblock(struct fs *fs, unsigned char *cp, int h)
1760{
1761	DBG_FUNC("clrblock")
1762
1763	DBG_ENTER;
1764
1765	switch ((fs)->fs_frag) {
1766	case 8:
1767		cp[h] = 0;
1768		break;
1769	case 4:
1770		cp[h >> 1] &= ~(0x0f << ((h & 0x1) << 2));
1771		break;
1772	case 2:
1773		cp[h >> 2] &= ~(0x03 << ((h & 0x3) << 1));
1774		break;
1775	case 1:
1776		cp[h >> 3] &= ~(0x01 << (h & 0x7));
1777		break;
1778	default:
1779		warnx("clrblock bad fs_frag %d", fs->fs_frag);
1780		break;
1781	}
1782
1783	DBG_LEAVE;
1784	return;
1785}
1786
1787/* ********************************************************** setblock ***** */
1788/*
1789 * Here we free a complete block in the free block map. For more details again
1790 * please  see the source of newfs(8), as this function is taken  over  almost
1791 * unchanged.
1792 */
1793static void
1794setblock(struct fs *fs, unsigned char *cp, int h)
1795{
1796	DBG_FUNC("setblock")
1797
1798	DBG_ENTER;
1799
1800	switch (fs->fs_frag) {
1801	case 8:
1802		cp[h] = 0xff;
1803		break;
1804	case 4:
1805		cp[h >> 1] |= (0x0f << ((h & 0x1) << 2));
1806		break;
1807	case 2:
1808		cp[h >> 2] |= (0x03 << ((h & 0x3) << 1));
1809		break;
1810	case 1:
1811		cp[h >> 3] |= (0x01 << (h & 0x7));
1812		break;
1813	default:
1814		warnx("setblock bad fs_frag %d", fs->fs_frag);
1815		break;
1816	}
1817
1818	DBG_LEAVE;
1819	return;
1820}
1821
1822/* ************************************************************ ginode ***** */
1823/*
1824 * This function provides access to an individual inode. We find out in which
1825 * block  the  requested inode is located, read it from disk if  needed,  and
1826 * return  the pointer into that block. We maintain a cache of one  block  to
1827 * not  read the same block again and again if we iterate linearly  over  all
1828 * inodes.
1829 */
1830static union dinode *
1831ginode(ino_t inumber, int fsi, int cg)
1832{
1833	DBG_FUNC("ginode")
1834	static ino_t	startinum = 0;	/* first inode in cached block */
1835
1836	DBG_ENTER;
1837
1838	inumber += (cg * sblock.fs_ipg);
1839	if (inumber < ROOTINO || inumber > maxino)
1840		errx(8, "bad inode number %d to ginode", inumber);
1841	if (startinum == 0 ||
1842	    inumber < startinum || inumber >= startinum + INOPB(&sblock)) {
1843		inoblk = fsbtodb(&sblock, ino_to_fsba(&sblock, inumber));
1844		rdfs(inoblk, (size_t)sblock.fs_bsize, inobuf, fsi);
1845		startinum = (inumber / INOPB(&sblock)) * INOPB(&sblock);
1846	}
1847	DBG_LEAVE;
1848	if (sblock.fs_magic == FS_UFS1_MAGIC)
1849		return ((union dinode *)
1850		    &((struct ufs1_dinode *)inobuf)[inumber % INOPB(&sblock)]);
1851	return ((union dinode *)
1852	    &((struct ufs2_dinode *)inobuf)[inumber % INOPB(&sblock)]);
1853}
1854
1855/* ****************************************************** charsperline ***** */
1856/*
1857 * Figure out how many lines our current terminal has. For more details again
1858 * please  see the source of newfs(8), as this function is taken over  almost
1859 * unchanged.
1860 */
1861static int
1862charsperline(void)
1863{
1864	DBG_FUNC("charsperline")
1865	int	columns;
1866	char	*cp;
1867	struct winsize	ws;
1868
1869	DBG_ENTER;
1870
1871	columns = 0;
1872	if (ioctl(0, TIOCGWINSZ, &ws) != -1) {
1873		columns = ws.ws_col;
1874	}
1875	if (columns == 0 && (cp = getenv("COLUMNS"))) {
1876		columns = atoi(cp);
1877	}
1878	if (columns == 0) {
1879		columns = 80;	/* last resort */
1880	}
1881
1882	DBG_LEAVE;
1883	return columns;
1884}
1885
1886/* ************************************************************** main ***** */
1887/*
1888 * growfs(8)  is a utility which allows to increase the size of  an  existing
1889 * ufs filesystem. Currently this can only be done on unmounted file  system.
1890 * It  recognizes some command line options to specify the new desired  size,
1891 * and  it does some basic checkings. The old filesystem size is  determined
1892 * and  after some more checks like we can really access the new  last  block
1893 * on the disk etc. we calculate the new parameters for the superblock. After
1894 * having  done  this we just call growfs() which will do  the  work.  Before
1895 * we finish the only thing left is to update the disklabel.
1896 * We still have to provide support for snapshots. Therefore we first have to
1897 * understand  what data structures are always replicated in the snapshot  on
1898 * creation,  for all other blocks we touch during our procedure, we have  to
1899 * keep the old blocks unchanged somewhere available for the snapshots. If we
1900 * are lucky, then we only have to handle our blocks to be relocated in  that
1901 * way.
1902 * Also  we  have to consider in what order we actually update  the  critical
1903 * data structures of the filesystem to make sure, that in case of a disaster
1904 * fsck(8) is still able to restore any lost data.
1905 * The  foreseen last step then will be to provide for growing  even  mounted
1906 * file  systems. There we have to extend the mount() system call to  provide
1907 * userland access to the filesystem locking facility.
1908 */
1909int
1910main(int argc, char **argv)
1911{
1912	DBG_FUNC("main")
1913	char	*device, *special, *cp;
1914	char	ch;
1915	unsigned int	size=0;
1916	size_t	len;
1917	unsigned int	Nflag=0;
1918	int	ExpertFlag=0;
1919	struct stat	st;
1920	struct disklabel	*lp;
1921	struct partition	*pp;
1922	int	i,fsi,fso;
1923	char	reply[5];
1924#ifdef FSMAXSNAP
1925	int	j;
1926#endif /* FSMAXSNAP */
1927
1928	DBG_ENTER;
1929
1930	while((ch=getopt(argc, argv, "Ns:vy")) != -1) {
1931		switch(ch) {
1932		case 'N':
1933			Nflag=1;
1934			break;
1935		case 's':
1936			size=(size_t)atol(optarg);
1937			if(size<1) {
1938				usage();
1939			}
1940			break;
1941		case 'v': /* for compatibility to newfs */
1942			break;
1943		case 'y':
1944			ExpertFlag=1;
1945			break;
1946		case '?':
1947			/* FALLTHROUGH */
1948		default:
1949			usage();
1950		}
1951	}
1952	argc -= optind;
1953	argv += optind;
1954
1955	if(argc != 1) {
1956		usage();
1957	}
1958	device=*argv;
1959
1960	/*
1961	 * Now try to guess the (raw)device name.
1962	 */
1963	if (0 == strrchr(device, '/')) {
1964		/*
1965		 * No path prefix was given, so try in that order:
1966		 *     /dev/r%s
1967		 *     /dev/%s
1968		 *     /dev/vinum/r%s
1969		 *     /dev/vinum/%s.
1970		 *
1971		 * FreeBSD now doesn't distinguish between raw and  block
1972		 * devices any longer, but it should still work this way.
1973		 */
1974		len=strlen(device)+strlen(_PATH_DEV)+2+strlen("vinum/");
1975		special=(char *)malloc(len);
1976		if(special == NULL) {
1977			errx(1, "malloc failed");
1978		}
1979		snprintf(special, len, "%sr%s", _PATH_DEV, device);
1980		if (stat(special, &st) == -1) {
1981			snprintf(special, len, "%s%s", _PATH_DEV, device);
1982			if (stat(special, &st) == -1) {
1983				snprintf(special, len, "%svinum/r%s",
1984				    _PATH_DEV, device);
1985				if (stat(special, &st) == -1) {
1986					/* For now this is the 'last resort' */
1987					snprintf(special, len, "%svinum/%s",
1988					    _PATH_DEV, device);
1989				}
1990			}
1991		}
1992		device = special;
1993	}
1994
1995	/*
1996	 * Try to access our devices for writing ...
1997	 */
1998	if (Nflag) {
1999		fso = -1;
2000	} else {
2001		fso = open(device, O_WRONLY);
2002		if (fso < 0) {
2003			err(1, "%s", device);
2004		}
2005	}
2006
2007	/*
2008	 * ... and reading.
2009	 */
2010	fsi = open(device, O_RDONLY);
2011	if (fsi < 0) {
2012		err(1, "%s", device);
2013	}
2014
2015	/*
2016	 * Try  to read a label and gess the slice if not  specified.  This
2017	 * code  should guess the right thing and avaid to bother the  user
2018	 * user with the task of specifying the option -v on vinum volumes.
2019	 */
2020	cp=device+strlen(device)-1;
2021	lp = get_disklabel(fsi);
2022	if(lp->d_type == DTYPE_VINUM) {
2023		pp = &lp->d_partitions[0];
2024	} else if (isdigit(*cp)) {
2025		pp = &lp->d_partitions[2];
2026	} else if (*cp>='a' && *cp<='h') {
2027		pp = &lp->d_partitions[*cp - 'a'];
2028	} else {
2029		errx(1, "unknown device");
2030	}
2031
2032	/*
2033	 * Check if that partition looks suited for growing a filesystem.
2034	 */
2035	if (pp->p_size < 1) {
2036		errx(1, "partition is unavailable");
2037	}
2038	if (pp->p_fstype != FS_BSDFFS) {
2039		errx(1, "partition not 4.2BSD");
2040	}
2041
2042	/*
2043	 * Read the current superblock, and take a backup.
2044	 */
2045	for (i = 0; sblock_try[i] != -1; i++) {
2046		sblockloc = sblock_try[i] / DEV_BSIZE;
2047		rdfs(sblockloc, (size_t)SBLOCKSIZE, (void *)&(osblock), fsi);
2048		if ((osblock.fs_magic == FS_UFS1_MAGIC ||
2049		     (osblock.fs_magic == FS_UFS2_MAGIC &&
2050		      osblock.fs_sblockloc ==
2051			  numfrags(&osblock, sblock_try[i]))) &&
2052		    osblock.fs_bsize <= MAXBSIZE &&
2053		    osblock.fs_bsize >= sizeof(struct fs))
2054			break;
2055	}
2056	if (sblock_try[i] == -1) {
2057		errx(1, "superblock not recognized");
2058	}
2059	memcpy((void *)&fsun1, (void *)&fsun2, sizeof(fsun2));
2060	maxino = sblock.fs_ncg * sblock.fs_ipg;
2061
2062	DBG_OPEN("/tmp/growfs.debug"); /* already here we need a superblock */
2063	DBG_DUMP_FS(&sblock,
2064	    "old sblock");
2065
2066	/*
2067	 * Determine size to grow to. Default to the full size specified in
2068	 * the disk label.
2069	 */
2070	sblock.fs_size = dbtofsb(&osblock, pp->p_size);
2071	if (size != 0) {
2072		if (size > pp->p_size){
2073			errx(1, "There is not enough space (%d < %d)",
2074			    pp->p_size, size);
2075		}
2076		sblock.fs_size = dbtofsb(&osblock, size);
2077	}
2078
2079	/*
2080	 * Are we really growing ?
2081	 */
2082	if(osblock.fs_size >= sblock.fs_size) {
2083		errx(1, "we are not growing (%d->%d)", osblock.fs_size,
2084		    sblock.fs_size);
2085	}
2086
2087
2088#ifdef FSMAXSNAP
2089	/*
2090	 * Check if we find an active snapshot.
2091	 */
2092	if(ExpertFlag == 0) {
2093		for(j=0; j<FSMAXSNAP; j++) {
2094			if(sblock.fs_snapinum[j]) {
2095				errx(1, "active snapshot found in filesystem\n"
2096				    "	please remove all snapshots before "
2097				    "using growfs\n");
2098			}
2099			if(!sblock.fs_snapinum[j]) { /* list is dense */
2100				break;
2101			}
2102		}
2103	}
2104#endif
2105
2106	if (ExpertFlag == 0 && Nflag == 0) {
2107		printf("We strongly recommend you to make a backup "
2108		    "before growing the Filesystem\n\n"
2109		    " Did you backup your data (Yes/No) ? ");
2110		fgets(reply, (int)sizeof(reply), stdin);
2111		if (strcmp(reply, "Yes\n")){
2112			printf("\n Nothing done \n");
2113			exit (0);
2114		}
2115	}
2116
2117	printf("new filesystemsize is: %d frags\n", sblock.fs_size);
2118
2119	/*
2120	 * Try to access our new last block in the filesystem. Even if we
2121	 * later on realize we have to abort our operation, on that block
2122	 * there should be no data, so we can't destroy something yet.
2123	 */
2124	wtfs((ufs2_daddr_t)pp->p_size-1, (size_t)DEV_BSIZE, (void *)&sblock,
2125	    fso, Nflag);
2126
2127	/*
2128	 * Now calculate new superblock values and check for reasonable
2129	 * bound for new filesystem size:
2130	 *     fs_size:    is derived from label or user input
2131	 *     fs_dsize:   should get updated in the routines creating or
2132	 *                 updating the cylinder groups on the fly
2133	 *     fs_cstotal: should get updated in the routines creating or
2134	 *                 updating the cylinder groups
2135	 */
2136
2137	/*
2138	 * Update the number of cylinders and cylinder groups in the filesystem.
2139	 */
2140	if (sblock.fs_magic == FS_UFS1_MAGIC) {
2141		sblock.fs_old_ncyl =
2142		    sblock.fs_size * sblock.fs_old_nspf / sblock.fs_old_spc;
2143		if (sblock.fs_size * sblock.fs_old_nspf >
2144		    sblock.fs_old_ncyl * sblock.fs_old_spc)
2145			sblock.fs_old_ncyl++;
2146	}
2147	sblock.fs_ncg = howmany(sblock.fs_size, sblock.fs_fpg);
2148	maxino = sblock.fs_ncg * sblock.fs_ipg;
2149
2150	if (sblock.fs_size % sblock.fs_fpg != 0 &&
2151	    sblock.fs_size % sblock.fs_fpg < cgdmin(&sblock, sblock.fs_ncg)) {
2152		/*
2153		 * The space in the new last cylinder group is too small,
2154		 * so revert back.
2155		 */
2156		sblock.fs_ncg--;
2157		if (sblock.fs_magic == FS_UFS1_MAGIC)
2158			sblock.fs_old_ncyl = sblock.fs_ncg * sblock.fs_old_cpg;
2159		printf("Warning: %d sector(s) cannot be allocated.\n",
2160		    fsbtodb(&sblock, sblock.fs_size % sblock.fs_fpg));
2161		sblock.fs_size = sblock.fs_ncg * sblock.fs_fpg;
2162	}
2163
2164	/*
2165	 * Update the space for the cylinder group summary information in the
2166	 * respective cylinder group data area.
2167	 */
2168	sblock.fs_cssize =
2169	    fragroundup(&sblock, sblock.fs_ncg * sizeof(struct csum));
2170
2171	if(osblock.fs_size >= sblock.fs_size) {
2172		errx(1, "not enough new space");
2173	}
2174
2175	DBG_PRINT0("sblock calculated\n");
2176
2177	/*
2178	 * Ok, everything prepared, so now let's do the tricks.
2179	 */
2180	growfs(fsi, fso, Nflag);
2181
2182	/*
2183	 * Update the disk label.
2184	 */
2185	pp->p_fsize = sblock.fs_fsize;
2186	pp->p_frag = sblock.fs_frag;
2187	pp->p_cpg = sblock.fs_fpg;
2188
2189	return_disklabel(fso, lp, Nflag);
2190	DBG_PRINT0("label rewritten\n");
2191
2192	close(fsi);
2193	if(fso>-1) close(fso);
2194
2195	DBG_CLOSE;
2196
2197	DBG_LEAVE;
2198	return 0;
2199}
2200
2201/* ************************************************** return_disklabel ***** */
2202/*
2203 * Write the updated disklabel back to disk.
2204 */
2205static void
2206return_disklabel(int fd, struct disklabel *lp, unsigned int Nflag)
2207{
2208	DBG_FUNC("return_disklabel")
2209	u_short	sum;
2210	u_short	*ptr;
2211
2212	DBG_ENTER;
2213
2214	if(!lp) {
2215		DBG_LEAVE;
2216		return;
2217	}
2218	if(!Nflag) {
2219		lp->d_checksum=0;
2220		sum = 0;
2221		ptr=(u_short *)lp;
2222
2223		/*
2224		 * recalculate checksum
2225		 */
2226		while(ptr < (u_short *)&lp->d_partitions[lp->d_npartitions]) {
2227			sum ^= *ptr++;
2228		}
2229		lp->d_checksum=sum;
2230
2231		if (ioctl(fd, DIOCWDINFO, (char *)lp) < 0) {
2232			errx(1, "DIOCWDINFO failed");
2233		}
2234	}
2235	free(lp);
2236
2237	DBG_LEAVE;
2238	return ;
2239}
2240
2241/* ***************************************************** get_disklabel ***** */
2242/*
2243 * Read the disklabel from disk.
2244 */
2245static struct disklabel *
2246get_disklabel(int fd)
2247{
2248	DBG_FUNC("get_disklabel")
2249	static struct	disklabel *lab;
2250
2251	DBG_ENTER;
2252
2253	lab=(struct disklabel *)malloc(sizeof(struct disklabel));
2254	if (!lab) {
2255		errx(1, "malloc failed");
2256	}
2257	if (ioctl(fd, DIOCGDINFO, (char *)lab) < 0) {
2258		errx(1, "DIOCGDINFO failed");
2259	}
2260
2261	DBG_LEAVE;
2262	return (lab);
2263}
2264
2265
2266/* ************************************************************* usage ***** */
2267/*
2268 * Dump a line of usage.
2269 */
2270static void
2271usage(void)
2272{
2273	DBG_FUNC("usage")
2274
2275	DBG_ENTER;
2276
2277	fprintf(stderr, "usage: growfs [-Ny] [-s size] special\n");
2278
2279	DBG_LEAVE;
2280	exit(1);
2281}
2282
2283/* *********************************************************** updclst ***** */
2284/*
2285 * This updates most paramters and the bitmap related to cluster. We have to
2286 * assume, that sblock, osblock, acg are set up.
2287 */
2288static void
2289updclst(int block)
2290{
2291	DBG_FUNC("updclst")
2292	static int	lcs=0;
2293
2294	DBG_ENTER;
2295
2296	if(sblock.fs_contigsumsize < 1) { /* no clustering */
2297		return;
2298	}
2299	/*
2300	 * update cluster allocation map
2301	 */
2302	setbit(cg_clustersfree(&acg), block);
2303
2304	/*
2305	 * update cluster summary table
2306	 */
2307	if(!lcs) {
2308		/*
2309		 * calculate size for the trailing cluster
2310		 */
2311		for(block--; lcs<sblock.fs_contigsumsize; block--, lcs++ ) {
2312			if(isclr(cg_clustersfree(&acg), block)){
2313				break;
2314			}
2315		}
2316	}
2317	if(lcs < sblock.fs_contigsumsize) {
2318		if(lcs) {
2319			cg_clustersum(&acg)[lcs]--;
2320		}
2321		lcs++;
2322		cg_clustersum(&acg)[lcs]++;
2323	}
2324
2325	DBG_LEAVE;
2326	return;
2327}
2328
2329/* *********************************************************** updrefs ***** */
2330/*
2331 * This updates all references to relocated blocks for the given inode.  The
2332 * inode is given as number within the cylinder group, and the number of the
2333 * cylinder group.
2334 */
2335static void
2336updrefs(int cg, ino_t in, struct gfs_bpp *bp, int fsi, int fso, unsigned int
2337    Nflag)
2338{
2339	DBG_FUNC("updrefs")
2340	ufs_lbn_t	len, lbn, numblks;
2341	ufs2_daddr_t	iptr, blksperindir;
2342	union dinode	*ino;
2343	int		i, mode, remaining_blocks, inodeupdated;
2344
2345	DBG_ENTER;
2346
2347	/*
2348	 * XXX We should skip unused inodes even from being read from disk
2349	 *     here by using the bitmap.
2350	 */
2351	ino = ginode(in, fsi, cg);
2352	mode = DIP(ino, di_mode) & IFMT;
2353	if (mode != IFDIR && mode != IFREG && mode != IFLNK) {
2354		DBG_LEAVE;
2355		return; /* only check DIR, FILE, LINK */
2356	}
2357	if (mode == IFLNK && DIP(ino, di_size) < sblock.fs_maxsymlinklen) {
2358		DBG_LEAVE;
2359		return;	/* skip short symlinks */
2360	}
2361	numblks = howmany(DIP(ino, di_size), sblock.fs_bsize);
2362	if (numblks == 0) {
2363		DBG_LEAVE;
2364		return;	/* skip empty file */
2365	}
2366	if (DIP(ino, di_blocks) == 0) {
2367		DBG_LEAVE;
2368		return;	/* skip empty swiss cheesy file or old fastlink */
2369	}
2370	DBG_PRINT2("scg checking inode (%d in %d)\n",
2371	    in,
2372	    cg);
2373
2374	/*
2375	 * Check all the blocks.
2376	 */
2377	inodeupdated = 0;
2378	len = numblks < NDADDR ? numblks : NDADDR;
2379	for (i = 0; i < len; i++) {
2380		iptr = DIP(ino, di_db[i]);
2381		if (iptr == 0)
2382			continue;
2383		if (cond_bl_upd(&iptr, bp, fsi, fso, Nflag)) {
2384			DIP(ino, di_db[i]) = iptr;
2385			inodeupdated++;
2386		}
2387	}
2388	DBG_PRINT0("~~scg direct blocks checked\n");
2389
2390	blksperindir = 1;
2391	len = numblks - NDADDR;
2392	lbn = NDADDR;
2393	for (i = 0; len > 0 && i < NIADDR; i++) {
2394		iptr = DIP(ino, di_ib[i]);
2395		if (iptr == 0)
2396			continue;
2397		if (cond_bl_upd(&iptr, bp, fsi, fso, Nflag)) {
2398			DIP(ino, di_ib[i]) = iptr;
2399			inodeupdated++;
2400		}
2401		indirchk(blksperindir, lbn, iptr, numblks, bp, fsi, fso, Nflag);
2402		blksperindir *= NINDIR(&sblock);
2403		lbn += blksperindir;
2404		len -= blksperindir;
2405		DBG_PRINT1("scg indirect_%d blocks checked\n", i + 1);
2406	}
2407	if (inodeupdated)
2408		wtfs(inoblk, sblock.fs_bsize, inobuf, fso, Nflag);
2409
2410	DBG_LEAVE;
2411	return;
2412}
2413
2414/*
2415 * Recursively check all the indirect blocks.
2416 */
2417static void
2418indirchk(ufs_lbn_t blksperindir, ufs_lbn_t lbn, ufs2_daddr_t blkno,
2419    ufs_lbn_t lastlbn, struct gfs_bpp *bp, int fsi, int fso, unsigned int Nflag)
2420{
2421	DBG_FUNC("indirchk")
2422	void *ibuf;
2423	off_t offset;
2424	int i, last;
2425	ufs2_daddr_t iptr;
2426
2427	DBG_ENTER;
2428
2429	/* read in the indirect block. */
2430	ibuf = malloc(sblock.fs_bsize);
2431	if (!ibuf)
2432		errx(1, "malloc failed");
2433	rdfs(fsbtodb(&sblock, blkno), (size_t)sblock.fs_bsize, ibuf, fsi);
2434	last = howmany(lastlbn - lbn, blksperindir) < NINDIR(&sblock) ?
2435	    howmany(lastlbn - lbn, blksperindir) : NINDIR(&sblock);
2436	for (i = 0; i < last; i++) {
2437		if (sblock.fs_magic == FS_UFS1_MAGIC)
2438			iptr = ((ufs1_daddr_t *)ibuf)[i];
2439		else
2440			iptr = ((ufs2_daddr_t *)ibuf)[i];
2441		if (iptr == 0)
2442			continue;
2443		if (cond_bl_upd(&iptr, bp, fsi, fso, Nflag)) {
2444			if (sblock.fs_magic == FS_UFS1_MAGIC)
2445				((ufs1_daddr_t *)ibuf)[i] = iptr;
2446			else
2447				((ufs2_daddr_t *)ibuf)[i] = iptr;
2448		}
2449		if (blksperindir == 1)
2450			continue;
2451		indirchk(blksperindir / NINDIR(&sblock), lbn + blksperindir * i,
2452		    iptr, lastlbn, bp, fsi, fso, Nflag);
2453	}
2454	free(ibuf);
2455
2456	DBG_LEAVE;
2457	return;
2458}
2459