1/*
2 * Copyright (c) 1980, 1986, 1993
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 * 4. Neither the name of the University nor the names of its contributors
14 *    may be used to endorse or promote products derived from this software
15 *    without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
28 */
29
30#if 0
31#ifndef lint
32static const char sccsid[] = "@(#)utilities.c	8.6 (Berkeley) 5/19/95";
33#endif /* not lint */
34#endif
35#include <sys/cdefs.h>
36__FBSDID("$FreeBSD$");
37
38#include <sys/param.h>
39#include <sys/time.h>
40#include <sys/types.h>
41#include <sys/sysctl.h>
42#include <sys/disk.h>
43#include <sys/disklabel.h>
44#include <sys/ioctl.h>
45#include <sys/stat.h>
46
47#include <ufs/ufs/dinode.h>
48#include <ufs/ufs/dir.h>
49#include <ufs/ffs/fs.h>
50
51#include <err.h>
52#include <errno.h>
53#include <string.h>
54#include <ctype.h>
55#include <fstab.h>
56#include <stdint.h>
57#include <stdio.h>
58#include <stdlib.h>
59#include <time.h>
60#include <unistd.h>
61
62#include "fsck.h"
63
64static void slowio_start(void);
65static void slowio_end(void);
66static void printIOstats(void);
67
68static long diskreads, totaldiskreads, totalreads; /* Disk cache statistics */
69static struct timespec startpass, finishpass;
70struct timeval slowio_starttime;
71int slowio_delay_usec = 10000;	/* Initial IO delay for background fsck */
72int slowio_pollcnt;
73static struct bufarea cgblk;	/* backup buffer for cylinder group blocks */
74static TAILQ_HEAD(buflist, bufarea) bufhead;	/* head of buffer cache list */
75static int numbufs;				/* size of buffer cache */
76static char *buftype[BT_NUMBUFTYPES] = BT_NAMES;
77
78int
79ftypeok(union dinode *dp)
80{
81	switch (DIP(dp, di_mode) & IFMT) {
82
83	case IFDIR:
84	case IFREG:
85	case IFBLK:
86	case IFCHR:
87	case IFLNK:
88	case IFSOCK:
89	case IFIFO:
90		return (1);
91
92	default:
93		if (debug)
94			printf("bad file type 0%o\n", DIP(dp, di_mode));
95		return (0);
96	}
97}
98
99int
100reply(const char *question)
101{
102	int persevere;
103	char c;
104
105	if (preen)
106		pfatal("INTERNAL ERROR: GOT TO reply()");
107	persevere = !strcmp(question, "CONTINUE");
108	printf("\n");
109	if (!persevere && (nflag || (fswritefd < 0 && bkgrdflag == 0))) {
110		printf("%s? no\n\n", question);
111		resolved = 0;
112		return (0);
113	}
114	if (yflag || (persevere && nflag)) {
115		printf("%s? yes\n\n", question);
116		return (1);
117	}
118	do	{
119		printf("%s? [yn] ", question);
120		(void) fflush(stdout);
121		c = getc(stdin);
122		while (c != '\n' && getc(stdin) != '\n') {
123			if (feof(stdin)) {
124				resolved = 0;
125				return (0);
126			}
127		}
128	} while (c != 'y' && c != 'Y' && c != 'n' && c != 'N');
129	printf("\n");
130	if (c == 'y' || c == 'Y')
131		return (1);
132	resolved = 0;
133	return (0);
134}
135
136/*
137 * Look up state information for an inode.
138 */
139struct inostat *
140inoinfo(ino_t inum)
141{
142	static struct inostat unallocated = { USTATE, 0, 0 };
143	struct inostatlist *ilp;
144	int iloff;
145
146	if (inum > maxino)
147		errx(EEXIT, "inoinfo: inumber %d out of range", inum);
148	ilp = &inostathead[inum / sblock.fs_ipg];
149	iloff = inum % sblock.fs_ipg;
150	if (iloff >= ilp->il_numalloced)
151		return (&unallocated);
152	return (&ilp->il_stat[iloff]);
153}
154
155/*
156 * Malloc buffers and set up cache.
157 */
158void
159bufinit(void)
160{
161	struct bufarea *bp;
162	long bufcnt, i;
163	char *bufp;
164
165	pbp = pdirbp = (struct bufarea *)0;
166	bufp = Malloc((unsigned int)sblock.fs_bsize);
167	if (bufp == 0)
168		errx(EEXIT, "cannot allocate buffer pool");
169	cgblk.b_un.b_buf = bufp;
170	initbarea(&cgblk, BT_CYLGRP);
171	TAILQ_INIT(&bufhead);
172	bufcnt = MAXBUFS;
173	if (bufcnt < MINBUFS)
174		bufcnt = MINBUFS;
175	for (i = 0; i < bufcnt; i++) {
176		bp = (struct bufarea *)Malloc(sizeof(struct bufarea));
177		bufp = Malloc((unsigned int)sblock.fs_bsize);
178		if (bp == NULL || bufp == NULL) {
179			if (i >= MINBUFS)
180				break;
181			errx(EEXIT, "cannot allocate buffer pool");
182		}
183		bp->b_un.b_buf = bufp;
184		TAILQ_INSERT_HEAD(&bufhead, bp, b_list);
185		initbarea(bp, BT_UNKNOWN);
186	}
187	numbufs = i;	/* save number of buffers */
188	for (i = 0; i < BT_NUMBUFTYPES; i++) {
189		readtime[i].tv_sec = totalreadtime[i].tv_sec = 0;
190		readtime[i].tv_nsec = totalreadtime[i].tv_nsec = 0;
191		readcnt[i] = totalreadcnt[i] = 0;
192	}
193}
194
195/*
196 * Manage cylinder group buffers.
197 */
198static struct bufarea *cgbufs;	/* header for cylinder group cache */
199static int flushtries;		/* number of tries to reclaim memory */
200
201struct bufarea *
202cgget(int cg)
203{
204	struct bufarea *cgbp;
205	struct cg *cgp;
206
207	if (cgbufs == NULL) {
208		cgbufs = calloc(sblock.fs_ncg, sizeof(struct bufarea));
209		if (cgbufs == NULL)
210			errx(EEXIT, "cannot allocate cylinder group buffers");
211	}
212	cgbp = &cgbufs[cg];
213	if (cgbp->b_un.b_cg != NULL)
214		return (cgbp);
215	cgp = NULL;
216	if (flushtries == 0)
217		cgp = malloc((unsigned int)sblock.fs_cgsize);
218	if (cgp == NULL) {
219		getblk(&cgblk, cgtod(&sblock, cg), sblock.fs_cgsize);
220		return (&cgblk);
221	}
222	cgbp->b_un.b_cg = cgp;
223	initbarea(cgbp, BT_CYLGRP);
224	getblk(cgbp, cgtod(&sblock, cg), sblock.fs_cgsize);
225	return (cgbp);
226}
227
228/*
229 * Attempt to flush a cylinder group cache entry.
230 * Return whether the flush was successful.
231 */
232int
233flushentry(void)
234{
235	struct bufarea *cgbp;
236
237	if (flushtries == sblock.fs_ncg || cgbufs == NULL)
238		return (0);
239	cgbp = &cgbufs[flushtries++];
240	if (cgbp->b_un.b_cg == NULL)
241		return (0);
242	flush(fswritefd, cgbp);
243	free(cgbp->b_un.b_buf);
244	cgbp->b_un.b_buf = NULL;
245	return (1);
246}
247
248/*
249 * Manage a cache of directory blocks.
250 */
251struct bufarea *
252getdatablk(ufs2_daddr_t blkno, long size, int type)
253{
254	struct bufarea *bp;
255
256	TAILQ_FOREACH(bp, &bufhead, b_list)
257		if (bp->b_bno == fsbtodb(&sblock, blkno))
258			goto foundit;
259	TAILQ_FOREACH_REVERSE(bp, &bufhead, buflist, b_list)
260		if ((bp->b_flags & B_INUSE) == 0)
261			break;
262	if (bp == NULL)
263		errx(EEXIT, "deadlocked buffer pool");
264	bp->b_type = type;
265	getblk(bp, blkno, size);
266	/* fall through */
267foundit:
268	if (debug && bp->b_type != type)
269		printf("Buffer type changed from %s to %s\n",
270		    buftype[bp->b_type], buftype[type]);
271	TAILQ_REMOVE(&bufhead, bp, b_list);
272	TAILQ_INSERT_HEAD(&bufhead, bp, b_list);
273	bp->b_flags |= B_INUSE;
274	return (bp);
275}
276
277/*
278 * Timespec operations (from <sys/time.h>).
279 */
280#define	timespecsub(vvp, uvp)						\
281	do {								\
282		(vvp)->tv_sec -= (uvp)->tv_sec;				\
283		(vvp)->tv_nsec -= (uvp)->tv_nsec;			\
284		if ((vvp)->tv_nsec < 0) {				\
285			(vvp)->tv_sec--;				\
286			(vvp)->tv_nsec += 1000000000;			\
287		}							\
288	} while (0)
289#define	timespecadd(vvp, uvp)						\
290	do {								\
291		(vvp)->tv_sec += (uvp)->tv_sec;				\
292		(vvp)->tv_nsec += (uvp)->tv_nsec;			\
293		if ((vvp)->tv_nsec >= 1000000000) {			\
294			(vvp)->tv_sec++;				\
295			(vvp)->tv_nsec -= 1000000000;			\
296		}							\
297	} while (0)
298
299void
300getblk(struct bufarea *bp, ufs2_daddr_t blk, long size)
301{
302	ufs2_daddr_t dblk;
303	struct timespec start, finish;
304
305	dblk = fsbtodb(&sblock, blk);
306	if (bp->b_bno == dblk) {
307		totalreads++;
308	} else {
309		flush(fswritefd, bp);
310		if (debug) {
311			readcnt[bp->b_type]++;
312			clock_gettime(CLOCK_REALTIME_PRECISE, &start);
313		}
314		bp->b_errs = blread(fsreadfd, bp->b_un.b_buf, dblk, size);
315		if (debug) {
316			clock_gettime(CLOCK_REALTIME_PRECISE, &finish);
317			timespecsub(&finish, &start);
318			timespecadd(&readtime[bp->b_type], &finish);
319		}
320		bp->b_bno = dblk;
321		bp->b_size = size;
322	}
323}
324
325void
326flush(int fd, struct bufarea *bp)
327{
328	int i, j;
329
330	if (!bp->b_dirty)
331		return;
332	bp->b_dirty = 0;
333	if (fswritefd < 0) {
334		pfatal("WRITING IN READ_ONLY MODE.\n");
335		return;
336	}
337	if (bp->b_errs != 0)
338		pfatal("WRITING %sZERO'ED BLOCK %lld TO DISK\n",
339		    (bp->b_errs == bp->b_size / dev_bsize) ? "" : "PARTIALLY ",
340		    (long long)bp->b_bno);
341	bp->b_errs = 0;
342	blwrite(fd, bp->b_un.b_buf, bp->b_bno, (long)bp->b_size);
343	if (bp != &sblk)
344		return;
345	for (i = 0, j = 0; i < sblock.fs_cssize; i += sblock.fs_bsize, j++) {
346		blwrite(fswritefd, (char *)sblock.fs_csp + i,
347		    fsbtodb(&sblock, sblock.fs_csaddr + j * sblock.fs_frag),
348		    sblock.fs_cssize - i < sblock.fs_bsize ?
349		    sblock.fs_cssize - i : sblock.fs_bsize);
350	}
351}
352
353void
354rwerror(const char *mesg, ufs2_daddr_t blk)
355{
356
357	if (bkgrdcheck)
358		exit(EEXIT);
359	if (preen == 0)
360		printf("\n");
361	pfatal("CANNOT %s: %ld", mesg, (long)blk);
362	if (reply("CONTINUE") == 0)
363		exit(EEXIT);
364}
365
366void
367ckfini(int markclean)
368{
369	struct bufarea *bp, *nbp;
370	int ofsmodified, cnt;
371
372	if (bkgrdflag) {
373		unlink(snapname);
374		if ((!(sblock.fs_flags & FS_UNCLEAN)) != markclean) {
375			cmd.value = FS_UNCLEAN;
376			cmd.size = markclean ? -1 : 1;
377			if (sysctlbyname("vfs.ffs.setflags", 0, 0,
378			    &cmd, sizeof cmd) == -1)
379				rwerror("SET FILE SYSTEM FLAGS", FS_UNCLEAN);
380			if (!preen) {
381				printf("\n***** FILE SYSTEM MARKED %s *****\n",
382				    markclean ? "CLEAN" : "DIRTY");
383				if (!markclean)
384					rerun = 1;
385			}
386		} else if (!preen && !markclean) {
387			printf("\n***** FILE SYSTEM STILL DIRTY *****\n");
388			rerun = 1;
389		}
390	}
391	if (debug && totalreads > 0)
392		printf("cache with %d buffers missed %ld of %ld (%d%%)\n",
393		    numbufs, totaldiskreads, totalreads,
394		    (int)(totaldiskreads * 100 / totalreads));
395	if (fswritefd < 0) {
396		(void)close(fsreadfd);
397		return;
398	}
399	flush(fswritefd, &sblk);
400	if (havesb && cursnapshot == 0 && sblock.fs_magic == FS_UFS2_MAGIC &&
401	    sblk.b_bno != sblock.fs_sblockloc / dev_bsize &&
402	    !preen && reply("UPDATE STANDARD SUPERBLOCK")) {
403		sblk.b_bno = sblock.fs_sblockloc / dev_bsize;
404		sbdirty();
405		flush(fswritefd, &sblk);
406	}
407	flush(fswritefd, &cgblk);
408	free(cgblk.b_un.b_buf);
409	cnt = 0;
410	TAILQ_FOREACH_REVERSE_SAFE(bp, &bufhead, buflist, b_list, nbp) {
411		TAILQ_REMOVE(&bufhead, bp, b_list);
412		cnt++;
413		flush(fswritefd, bp);
414		free(bp->b_un.b_buf);
415		free((char *)bp);
416	}
417	if (numbufs != cnt)
418		errx(EEXIT, "panic: lost %d buffers", numbufs - cnt);
419	if (cgbufs != NULL) {
420		for (cnt = 0; cnt < sblock.fs_ncg; cnt++) {
421			if (cgbufs[cnt].b_un.b_cg == NULL)
422				continue;
423			flush(fswritefd, &cgbufs[cnt]);
424			free(cgbufs[cnt].b_un.b_cg);
425		}
426		free(cgbufs);
427	}
428	pbp = pdirbp = (struct bufarea *)0;
429	if (cursnapshot == 0 && sblock.fs_clean != markclean) {
430		if ((sblock.fs_clean = markclean) != 0) {
431			sblock.fs_flags &= ~(FS_UNCLEAN | FS_NEEDSFSCK);
432			sblock.fs_pendingblocks = 0;
433			sblock.fs_pendinginodes = 0;
434		}
435		sbdirty();
436		ofsmodified = fsmodified;
437		flush(fswritefd, &sblk);
438		fsmodified = ofsmodified;
439		if (!preen) {
440			printf("\n***** FILE SYSTEM MARKED %s *****\n",
441			    markclean ? "CLEAN" : "DIRTY");
442			if (!markclean)
443				rerun = 1;
444		}
445	} else if (!preen) {
446		if (markclean) {
447			printf("\n***** FILE SYSTEM IS CLEAN *****\n");
448		} else {
449			printf("\n***** FILE SYSTEM STILL DIRTY *****\n");
450			rerun = 1;
451		}
452	}
453	(void)close(fsreadfd);
454	(void)close(fswritefd);
455}
456
457/*
458 * Print out I/O statistics.
459 */
460void
461IOstats(char *what)
462{
463	int i;
464
465	if (debug == 0)
466		return;
467	if (diskreads == 0) {
468		printf("%s: no I/O\n\n", what);
469		return;
470	}
471	if (startpass.tv_sec == 0)
472		startpass = startprog;
473	printf("%s: I/O statistics\n", what);
474	printIOstats();
475	totaldiskreads += diskreads;
476	diskreads = 0;
477	for (i = 0; i < BT_NUMBUFTYPES; i++) {
478		timespecadd(&totalreadtime[i], &readtime[i]);
479		totalreadcnt[i] += readcnt[i];
480		readtime[i].tv_sec = readtime[i].tv_nsec = 0;
481		readcnt[i] = 0;
482	}
483	clock_gettime(CLOCK_REALTIME_PRECISE, &startpass);
484}
485
486void
487finalIOstats(void)
488{
489	int i;
490
491	if (debug == 0)
492		return;
493	printf("Final I/O statistics\n");
494	totaldiskreads += diskreads;
495	diskreads = totaldiskreads;
496	startpass = startprog;
497	for (i = 0; i < BT_NUMBUFTYPES; i++) {
498		timespecadd(&totalreadtime[i], &readtime[i]);
499		totalreadcnt[i] += readcnt[i];
500		readtime[i] = totalreadtime[i];
501		readcnt[i] = totalreadcnt[i];
502	}
503	printIOstats();
504}
505
506static void printIOstats(void)
507{
508	long long msec, totalmsec;
509	int i;
510
511	clock_gettime(CLOCK_REALTIME_PRECISE, &finishpass);
512	timespecsub(&finishpass, &startpass);
513	printf("Running time: %jd.%03ld sec\n",
514		(intmax_t)finishpass.tv_sec, finishpass.tv_nsec / 1000000);
515	printf("buffer reads by type:\n");
516	for (totalmsec = 0, i = 0; i < BT_NUMBUFTYPES; i++)
517		totalmsec += readtime[i].tv_sec * 1000 +
518		    readtime[i].tv_nsec / 1000000;
519	if (totalmsec == 0)
520		totalmsec = 1;
521	for (i = 0; i < BT_NUMBUFTYPES; i++) {
522		if (readcnt[i] == 0)
523			continue;
524		msec =
525		    readtime[i].tv_sec * 1000 + readtime[i].tv_nsec / 1000000;
526		printf("%21s:%8ld %2ld.%ld%% %4jd.%03ld sec %2lld.%lld%%\n",
527		    buftype[i], readcnt[i], readcnt[i] * 100 / diskreads,
528		    (readcnt[i] * 1000 / diskreads) % 10,
529		    (intmax_t)readtime[i].tv_sec, readtime[i].tv_nsec / 1000000,
530		    msec * 100 / totalmsec, (msec * 1000 / totalmsec) % 10);
531	}
532	printf("\n");
533}
534
535int
536blread(int fd, char *buf, ufs2_daddr_t blk, long size)
537{
538	char *cp;
539	int i, errs;
540	off_t offset;
541
542	offset = blk;
543	offset *= dev_bsize;
544	if (bkgrdflag)
545		slowio_start();
546	totalreads++;
547	diskreads++;
548	if (lseek(fd, offset, 0) < 0)
549		rwerror("SEEK BLK", blk);
550	else if (read(fd, buf, (int)size) == size) {
551		if (bkgrdflag)
552			slowio_end();
553		return (0);
554	}
555	rwerror("READ BLK", blk);
556	if (lseek(fd, offset, 0) < 0)
557		rwerror("SEEK BLK", blk);
558	errs = 0;
559	memset(buf, 0, (size_t)size);
560	printf("THE FOLLOWING DISK SECTORS COULD NOT BE READ:");
561	for (cp = buf, i = 0; i < size; i += secsize, cp += secsize) {
562		if (read(fd, cp, (int)secsize) != secsize) {
563			(void)lseek(fd, offset + i + secsize, 0);
564			if (secsize != dev_bsize && dev_bsize != 1)
565				printf(" %jd (%jd),",
566				    (intmax_t)(blk * dev_bsize + i) / secsize,
567				    (intmax_t)blk + i / dev_bsize);
568			else
569				printf(" %jd,", (intmax_t)blk + i / dev_bsize);
570			errs++;
571		}
572	}
573	printf("\n");
574	if (errs)
575		resolved = 0;
576	return (errs);
577}
578
579void
580blwrite(int fd, char *buf, ufs2_daddr_t blk, long size)
581{
582	int i;
583	char *cp;
584	off_t offset;
585
586	if (fd < 0)
587		return;
588	offset = blk;
589	offset *= dev_bsize;
590	if (lseek(fd, offset, 0) < 0)
591		rwerror("SEEK BLK", blk);
592	else if (write(fd, buf, (int)size) == size) {
593		fsmodified = 1;
594		return;
595	}
596	resolved = 0;
597	rwerror("WRITE BLK", blk);
598	if (lseek(fd, offset, 0) < 0)
599		rwerror("SEEK BLK", blk);
600	printf("THE FOLLOWING SECTORS COULD NOT BE WRITTEN:");
601	for (cp = buf, i = 0; i < size; i += dev_bsize, cp += dev_bsize)
602		if (write(fd, cp, (int)dev_bsize) != dev_bsize) {
603			(void)lseek(fd, offset + i + dev_bsize, 0);
604			printf(" %jd,", (intmax_t)blk + i / dev_bsize);
605		}
606	printf("\n");
607	return;
608}
609
610void
611blerase(int fd, ufs2_daddr_t blk, long size)
612{
613	off_t ioarg[2];
614
615	if (fd < 0)
616		return;
617	ioarg[0] = blk * dev_bsize;
618	ioarg[1] = size;
619	ioctl(fd, DIOCGDELETE, ioarg);
620	/* we don't really care if we succeed or not */
621	return;
622}
623
624void
625blzero(int fd, ufs2_daddr_t blk, long size)
626{
627	static char *zero;
628	off_t offset, len;
629
630	if (fd < 0)
631		return;
632	len = ZEROBUFSIZE;
633	if (zero == NULL) {
634		zero = calloc(len, 1);
635		if (zero == NULL)
636			errx(EEXIT, "cannot allocate buffer pool");
637	}
638	offset = blk * dev_bsize;
639	if (lseek(fd, offset, 0) < 0)
640		rwerror("SEEK BLK", blk);
641	while (size > 0) {
642		if (size > len)
643			size = len;
644		else
645			len = size;
646		if (write(fd, zero, len) != len)
647			rwerror("WRITE BLK", blk);
648		blk += len / dev_bsize;
649		size -= len;
650	}
651}
652
653/*
654 * Verify cylinder group's magic number and other parameters.  If the
655 * test fails, offer an option to rebuild the whole cylinder group.
656 */
657int
658check_cgmagic(int cg, struct bufarea *cgbp)
659{
660	struct cg *cgp = cgbp->b_un.b_cg;
661
662	/*
663	 * Extended cylinder group checks.
664	 */
665	if (cg_chkmagic(cgp) &&
666	    ((sblock.fs_magic == FS_UFS1_MAGIC &&
667	      cgp->cg_old_niblk == sblock.fs_ipg &&
668	      cgp->cg_ndblk <= sblock.fs_fpg &&
669	      cgp->cg_old_ncyl <= sblock.fs_old_cpg) ||
670	     (sblock.fs_magic == FS_UFS2_MAGIC &&
671	      cgp->cg_niblk == sblock.fs_ipg &&
672	      cgp->cg_ndblk <= sblock.fs_fpg &&
673	      cgp->cg_initediblk <= sblock.fs_ipg))) {
674		return (1);
675	}
676	pfatal("CYLINDER GROUP %d: BAD MAGIC NUMBER", cg);
677	if (!reply("REBUILD CYLINDER GROUP")) {
678		printf("YOU WILL NEED TO RERUN FSCK.\n");
679		rerun = 1;
680		return (1);
681	}
682	/*
683	 * Zero out the cylinder group and then initialize critical fields.
684	 * Bit maps and summaries will be recalculated by later passes.
685	 */
686	memset(cgp, 0, (size_t)sblock.fs_cgsize);
687	cgp->cg_magic = CG_MAGIC;
688	cgp->cg_cgx = cg;
689	cgp->cg_niblk = sblock.fs_ipg;
690	cgp->cg_initediblk = sblock.fs_ipg < 2 * INOPB(&sblock) ?
691	    sblock.fs_ipg : 2 * INOPB(&sblock);
692	if (cgbase(&sblock, cg) + sblock.fs_fpg < sblock.fs_size)
693		cgp->cg_ndblk = sblock.fs_fpg;
694	else
695		cgp->cg_ndblk = sblock.fs_size - cgbase(&sblock, cg);
696	cgp->cg_iusedoff = &cgp->cg_space[0] - (u_char *)(&cgp->cg_firstfield);
697	if (sblock.fs_magic == FS_UFS1_MAGIC) {
698		cgp->cg_niblk = 0;
699		cgp->cg_initediblk = 0;
700		cgp->cg_old_ncyl = sblock.fs_old_cpg;
701		cgp->cg_old_niblk = sblock.fs_ipg;
702		cgp->cg_old_btotoff = cgp->cg_iusedoff;
703		cgp->cg_old_boff = cgp->cg_old_btotoff +
704		    sblock.fs_old_cpg * sizeof(int32_t);
705		cgp->cg_iusedoff = cgp->cg_old_boff +
706		    sblock.fs_old_cpg * sizeof(u_int16_t);
707	}
708	cgp->cg_freeoff = cgp->cg_iusedoff + howmany(sblock.fs_ipg, CHAR_BIT);
709	cgp->cg_nextfreeoff = cgp->cg_freeoff + howmany(sblock.fs_fpg,CHAR_BIT);
710	if (sblock.fs_contigsumsize > 0) {
711		cgp->cg_nclusterblks = cgp->cg_ndblk / sblock.fs_frag;
712		cgp->cg_clustersumoff =
713		    roundup(cgp->cg_nextfreeoff, sizeof(u_int32_t));
714		cgp->cg_clustersumoff -= sizeof(u_int32_t);
715		cgp->cg_clusteroff = cgp->cg_clustersumoff +
716		    (sblock.fs_contigsumsize + 1) * sizeof(u_int32_t);
717		cgp->cg_nextfreeoff = cgp->cg_clusteroff +
718		    howmany(fragstoblks(&sblock, sblock.fs_fpg), CHAR_BIT);
719	}
720	dirty(cgbp);
721	return (0);
722}
723
724/*
725 * allocate a data block with the specified number of fragments
726 */
727ufs2_daddr_t
728allocblk(long frags)
729{
730	int i, j, k, cg, baseblk;
731	struct bufarea *cgbp;
732	struct cg *cgp;
733
734	if (frags <= 0 || frags > sblock.fs_frag)
735		return (0);
736	for (i = 0; i < maxfsblock - sblock.fs_frag; i += sblock.fs_frag) {
737		for (j = 0; j <= sblock.fs_frag - frags; j++) {
738			if (testbmap(i + j))
739				continue;
740			for (k = 1; k < frags; k++)
741				if (testbmap(i + j + k))
742					break;
743			if (k < frags) {
744				j += k;
745				continue;
746			}
747			cg = dtog(&sblock, i + j);
748			cgbp = cgget(cg);
749			cgp = cgbp->b_un.b_cg;
750			if (!check_cgmagic(cg, cgbp))
751				return (0);
752			baseblk = dtogd(&sblock, i + j);
753			for (k = 0; k < frags; k++) {
754				setbmap(i + j + k);
755				clrbit(cg_blksfree(cgp), baseblk + k);
756			}
757			n_blks += frags;
758			if (frags == sblock.fs_frag)
759				cgp->cg_cs.cs_nbfree--;
760			else
761				cgp->cg_cs.cs_nffree -= frags;
762			dirty(cgbp);
763			return (i + j);
764		}
765	}
766	return (0);
767}
768
769/*
770 * Free a previously allocated block
771 */
772void
773freeblk(ufs2_daddr_t blkno, long frags)
774{
775	struct inodesc idesc;
776
777	idesc.id_blkno = blkno;
778	idesc.id_numfrags = frags;
779	(void)pass4check(&idesc);
780}
781
782/* Slow down IO so as to leave some disk bandwidth for other processes */
783void
784slowio_start()
785{
786
787	/* Delay one in every 8 operations */
788	slowio_pollcnt = (slowio_pollcnt + 1) & 7;
789	if (slowio_pollcnt == 0) {
790		gettimeofday(&slowio_starttime, NULL);
791	}
792}
793
794void
795slowio_end()
796{
797	struct timeval tv;
798	int delay_usec;
799
800	if (slowio_pollcnt != 0)
801		return;
802
803	/* Update the slowdown interval. */
804	gettimeofday(&tv, NULL);
805	delay_usec = (tv.tv_sec - slowio_starttime.tv_sec) * 1000000 +
806	    (tv.tv_usec - slowio_starttime.tv_usec);
807	if (delay_usec < 64)
808		delay_usec = 64;
809	if (delay_usec > 2500000)
810		delay_usec = 2500000;
811	slowio_delay_usec = (slowio_delay_usec * 63 + delay_usec) >> 6;
812	/* delay by 8 times the average IO delay */
813	if (slowio_delay_usec > 64)
814		usleep(slowio_delay_usec * 8);
815}
816
817/*
818 * Find a pathname
819 */
820void
821getpathname(char *namebuf, ino_t curdir, ino_t ino)
822{
823	int len;
824	char *cp;
825	struct inodesc idesc;
826	static int busy = 0;
827
828	if (curdir == ino && ino == ROOTINO) {
829		(void)strcpy(namebuf, "/");
830		return;
831	}
832	if (busy || !INO_IS_DVALID(curdir)) {
833		(void)strcpy(namebuf, "?");
834		return;
835	}
836	busy = 1;
837	memset(&idesc, 0, sizeof(struct inodesc));
838	idesc.id_type = DATA;
839	idesc.id_fix = IGNORE;
840	cp = &namebuf[MAXPATHLEN - 1];
841	*cp = '\0';
842	if (curdir != ino) {
843		idesc.id_parent = curdir;
844		goto namelookup;
845	}
846	while (ino != ROOTINO) {
847		idesc.id_number = ino;
848		idesc.id_func = findino;
849		idesc.id_name = strdup("..");
850		if ((ckinode(ginode(ino), &idesc) & FOUND) == 0)
851			break;
852	namelookup:
853		idesc.id_number = idesc.id_parent;
854		idesc.id_parent = ino;
855		idesc.id_func = findname;
856		idesc.id_name = namebuf;
857		if ((ckinode(ginode(idesc.id_number), &idesc)&FOUND) == 0)
858			break;
859		len = strlen(namebuf);
860		cp -= len;
861		memmove(cp, namebuf, (size_t)len);
862		*--cp = '/';
863		if (cp < &namebuf[MAXNAMLEN])
864			break;
865		ino = idesc.id_number;
866	}
867	busy = 0;
868	if (ino != ROOTINO)
869		*--cp = '?';
870	memmove(namebuf, cp, (size_t)(&namebuf[MAXPATHLEN] - cp));
871}
872
873void
874catch(int sig __unused)
875{
876
877	ckfini(0);
878	exit(12);
879}
880
881/*
882 * When preening, allow a single quit to signal
883 * a special exit after file system checks complete
884 * so that reboot sequence may be interrupted.
885 */
886void
887catchquit(int sig __unused)
888{
889	printf("returning to single-user after file system check\n");
890	returntosingle = 1;
891	(void)signal(SIGQUIT, SIG_DFL);
892}
893
894/*
895 * determine whether an inode should be fixed.
896 */
897int
898dofix(struct inodesc *idesc, const char *msg)
899{
900
901	switch (idesc->id_fix) {
902
903	case DONTKNOW:
904		if (idesc->id_type == DATA)
905			direrror(idesc->id_number, msg);
906		else
907			pwarn("%s", msg);
908		if (preen) {
909			printf(" (SALVAGED)\n");
910			idesc->id_fix = FIX;
911			return (ALTERED);
912		}
913		if (reply("SALVAGE") == 0) {
914			idesc->id_fix = NOFIX;
915			return (0);
916		}
917		idesc->id_fix = FIX;
918		return (ALTERED);
919
920	case FIX:
921		return (ALTERED);
922
923	case NOFIX:
924	case IGNORE:
925		return (0);
926
927	default:
928		errx(EEXIT, "UNKNOWN INODESC FIX MODE %d", idesc->id_fix);
929	}
930	/* NOTREACHED */
931	return (0);
932}
933
934#include <stdarg.h>
935
936/*
937 * An unexpected inconsistency occured.
938 * Die if preening or file system is running with soft dependency protocol,
939 * otherwise just print message and continue.
940 */
941void
942pfatal(const char *fmt, ...)
943{
944	va_list ap;
945	va_start(ap, fmt);
946	if (!preen) {
947		(void)vfprintf(stdout, fmt, ap);
948		va_end(ap);
949		if (usedsoftdep)
950			(void)fprintf(stdout,
951			    "\nUNEXPECTED SOFT UPDATE INCONSISTENCY\n");
952		/*
953		 * Force foreground fsck to clean up inconsistency.
954		 */
955		if (bkgrdflag) {
956			cmd.value = FS_NEEDSFSCK;
957			cmd.size = 1;
958			if (sysctlbyname("vfs.ffs.setflags", 0, 0,
959			    &cmd, sizeof cmd) == -1)
960				pwarn("CANNOT SET FS_NEEDSFSCK FLAG\n");
961			fprintf(stdout, "CANNOT RUN IN BACKGROUND\n");
962			ckfini(0);
963			exit(EEXIT);
964		}
965		return;
966	}
967	if (cdevname == NULL)
968		cdevname = strdup("fsck");
969	(void)fprintf(stdout, "%s: ", cdevname);
970	(void)vfprintf(stdout, fmt, ap);
971	(void)fprintf(stdout,
972	    "\n%s: UNEXPECTED%sINCONSISTENCY; RUN fsck MANUALLY.\n",
973	    cdevname, usedsoftdep ? " SOFT UPDATE " : " ");
974	/*
975	 * Force foreground fsck to clean up inconsistency.
976	 */
977	if (bkgrdflag) {
978		cmd.value = FS_NEEDSFSCK;
979		cmd.size = 1;
980		if (sysctlbyname("vfs.ffs.setflags", 0, 0,
981		    &cmd, sizeof cmd) == -1)
982			pwarn("CANNOT SET FS_NEEDSFSCK FLAG\n");
983	}
984	ckfini(0);
985	exit(EEXIT);
986}
987
988/*
989 * Pwarn just prints a message when not preening or running soft dependency
990 * protocol, or a warning (preceded by filename) when preening.
991 */
992void
993pwarn(const char *fmt, ...)
994{
995	va_list ap;
996	va_start(ap, fmt);
997	if (preen)
998		(void)fprintf(stdout, "%s: ", cdevname);
999	(void)vfprintf(stdout, fmt, ap);
1000	va_end(ap);
1001}
1002
1003/*
1004 * Stub for routines from kernel.
1005 */
1006void
1007panic(const char *fmt, ...)
1008{
1009	va_list ap;
1010	va_start(ap, fmt);
1011	pfatal("INTERNAL INCONSISTENCY:");
1012	(void)vfprintf(stdout, fmt, ap);
1013	va_end(ap);
1014	exit(EEXIT);
1015}
1016