2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1980, 1986, 1993
5 * The Regents of the University of California. All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the University nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 static const char sccsid[] = "@(#)utilities.c 8.6 (Berkeley) 5/19/95";
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
40 #include <sys/param.h>
42 #include <sys/types.h>
43 #include <sys/sysctl.h>
45 #include <sys/disklabel.h>
46 #include <sys/ioctl.h>
49 #include <ufs/ufs/dinode.h>
50 #include <ufs/ufs/dir.h>
51 #include <ufs/ffs/fs.h>
69 static struct bufarea *allocbuf(const char *);
70 static void cg_write(struct bufarea *);
71 static void slowio_start(void);
72 static void slowio_end(void);
73 static void printIOstats(void);
75 static long diskreads, totaldiskreads, totalreads; /* Disk cache statistics */
76 static struct timespec startpass, finishpass;
77 struct timeval slowio_starttime;
78 int slowio_delay_usec = 10000; /* Initial IO delay for background fsck */
80 static struct bufarea cgblk; /* backup buffer for cylinder group blocks */
81 static struct bufarea failedbuf; /* returned by failed getdatablk() */
82 static TAILQ_HEAD(bufqueue, bufarea) bufqueuehd; /* head of buffer cache LRU */
83 static LIST_HEAD(bufhash, bufarea) bufhashhd[HASHSIZE]; /* buffer hash list */
84 static struct bufhash freebufs; /* unused buffers */
85 static int numbufs; /* size of buffer cache */
86 static int cachelookups; /* number of cache lookups */
87 static int cachereads; /* number of cache reads */
88 static int flushtries; /* number of tries to reclaim memory */
90 char *buftype[BT_NUMBUFTYPES] = BT_NAMES;
95 diskreads = totaldiskreads = totalreads = 0;
96 bzero(&startpass, sizeof(struct timespec));
97 bzero(&finishpass, sizeof(struct timespec));
98 bzero(&slowio_starttime, sizeof(struct timeval));
99 slowio_delay_usec = 10000;
105 ftypeok(union dinode *dp)
107 switch (DIP(dp, di_mode) & IFMT) {
120 printf("bad file type 0%o\n", DIP(dp, di_mode));
126 reply(const char *question)
132 pfatal("INTERNAL ERROR: GOT TO reply()");
133 persevere = !strcmp(question, "CONTINUE");
135 if (!persevere && (nflag || (fswritefd < 0 && bkgrdflag == 0))) {
136 printf("%s? no\n\n", question);
140 if (yflag || (persevere && nflag)) {
141 printf("%s? yes\n\n", question);
145 printf("%s? [yn] ", question);
146 (void) fflush(stdout);
148 while (c != '\n' && getc(stdin) != '\n') {
154 } while (c != 'y' && c != 'Y' && c != 'n' && c != 'N');
156 if (c == 'y' || c == 'Y')
163 * Look up state information for an inode.
168 static struct inostat unallocated = { USTATE, 0, 0, 0 };
169 struct inostatlist *ilp;
173 errx(EEXIT, "inoinfo: inumber %ju out of range",
175 ilp = &inostathead[inum / sblock.fs_ipg];
176 iloff = inum % sblock.fs_ipg;
177 if (iloff >= ilp->il_numalloced)
178 return (&unallocated);
179 return (&ilp->il_stat[iloff]);
183 * Malloc buffers and set up cache.
190 initbarea(&failedbuf, BT_UNKNOWN);
191 failedbuf.b_errs = -1;
192 failedbuf.b_un.b_buf = NULL;
193 if ((cgblk.b_un.b_buf = Malloc((unsigned int)sblock.fs_bsize)) == NULL)
194 errx(EEXIT, "Initial malloc(%d) failed", sblock.fs_bsize);
195 initbarea(&cgblk, BT_CYLGRP);
196 numbufs = cachelookups = cachereads = 0;
197 TAILQ_INIT(&bufqueuehd);
198 LIST_INIT(&freebufs);
199 for (i = 0; i < HASHSIZE; i++)
200 LIST_INIT(&bufhashhd[i]);
201 for (i = 0; i < BT_NUMBUFTYPES; i++) {
202 readtime[i].tv_sec = totalreadtime[i].tv_sec = 0;
203 readtime[i].tv_nsec = totalreadtime[i].tv_nsec = 0;
204 readcnt[i] = totalreadcnt[i] = 0;
208 static struct bufarea *
209 allocbuf(const char *failreason)
214 bp = (struct bufarea *)Malloc(sizeof(struct bufarea));
215 bufp = Malloc((unsigned int)sblock.fs_bsize);
216 if (bp == NULL || bufp == NULL) {
217 errx(EEXIT, "%s", failreason);
221 bp->b_un.b_buf = bufp;
222 TAILQ_INSERT_HEAD(&bufqueuehd, bp, b_list);
223 initbarea(bp, BT_UNKNOWN);
228 * Manage cylinder group buffers.
230 * Use getblk() here rather than cgget() because the cylinder group
231 * may be corrupted but we want it anyway so we can fix it.
233 static struct bufarea *cgbufs; /* header for cylinder group cache */
234 static int flushtries; /* number of tries to reclaim memory */
239 struct bufarea *cgbp;
242 if ((unsigned) cg >= sblock.fs_ncg)
243 errx(EEXIT, "cglookup: out of range cylinder group %d", cg);
244 if (cgbufs == NULL) {
245 cgbufs = calloc(sblock.fs_ncg, sizeof(struct bufarea));
247 errx(EEXIT, "Cannot allocate cylinder group buffers");
250 if (cgbp->b_un.b_cg != NULL)
254 cgp = Malloc((unsigned int)sblock.fs_cgsize);
257 errx(EEXIT,"Ran out of memory during journal recovery");
258 flush(fswritefd, &cgblk);
259 getblk(&cgblk, cgtod(&sblock, cg), sblock.fs_cgsize);
262 cgbp->b_un.b_cg = cgp;
263 initbarea(cgbp, BT_CYLGRP);
264 getblk(cgbp, cgtod(&sblock, cg), sblock.fs_cgsize);
269 * Mark a cylinder group buffer as dirty.
270 * Update its check-hash if they are enabled.
273 cgdirty(struct bufarea *cgbp)
277 cg = cgbp->b_un.b_cg;
278 if ((sblock.fs_metackhash & CK_CYLGRP) != 0) {
281 calculate_crc32c(~0L, (void *)cg, sblock.fs_cgsize);
287 * Attempt to flush a cylinder group cache entry.
288 * Return whether the flush was successful.
293 struct bufarea *cgbp;
295 if (sujrecovery || flushtries == sblock.fs_ncg || cgbufs == NULL)
297 cgbp = &cgbufs[flushtries++];
298 if (cgbp->b_un.b_cg == NULL)
300 flush(fswritefd, cgbp);
301 free(cgbp->b_un.b_buf);
302 cgbp->b_un.b_buf = NULL;
307 * Manage a cache of filesystem disk blocks.
310 getdatablk(ufs2_daddr_t blkno, long size, int type)
313 struct bufhash *bhdp;
317 * If out of range, return empty buffer with b_err == -1
319 * Skip check for inodes because chkrange() considers
320 * metadata areas invalid to write data.
322 if (type != BT_INODES && chkrange(blkno, size / sblock.fs_fsize)) {
323 failedbuf.b_refcnt++;
326 bhdp = &bufhashhd[HASH(blkno)];
327 LIST_FOREACH(bp, bhdp, b_hash)
328 if (bp->b_bno == fsbtodb(&sblock, blkno)) {
329 if (debug && bp->b_size != size) {
330 prtbuf(bp, "getdatablk: size mismatch");
331 pfatal("getdatablk: b_size %d != size %ld\n",
334 TAILQ_REMOVE(&bufqueuehd, bp, b_list);
338 * Move long-term busy buffer back to the front of the LRU so we
339 * do not endless inspect them for recycling.
341 bp = TAILQ_LAST(&bufqueuehd, bufqueue);
342 if (bp != NULL && bp->b_refcnt != 0) {
343 TAILQ_REMOVE(&bufqueuehd, bp, b_list);
344 TAILQ_INSERT_HEAD(&bufqueuehd, bp, b_list);
347 * Allocate up to the minimum number of buffers before
348 * considering recycling any of them.
350 if (size > sblock.fs_bsize)
351 errx(EEXIT, "Excessive buffer size %ld > %d\n", size,
353 if ((bp = LIST_FIRST(&freebufs)) != NULL) {
354 LIST_REMOVE(bp, b_hash);
355 } else if (numbufs < MINBUFS) {
356 bp = allocbuf("cannot create minimal buffer pool");
357 } else if (sujrecovery) {
359 * SUJ recovery does not want anything written until it
360 * has successfully completed (so it can fail back to
361 * full fsck). Thus, we can only recycle clean buffers.
363 TAILQ_FOREACH_REVERSE(bp, &bufqueuehd, bufqueue, b_list)
364 if ((bp->b_flags & B_DIRTY) == 0 && bp->b_refcnt == 0)
367 bp = allocbuf("Ran out of memory during "
370 LIST_REMOVE(bp, b_hash);
373 * Recycle oldest non-busy buffer.
375 TAILQ_FOREACH_REVERSE(bp, &bufqueuehd, bufqueue, b_list)
376 if (bp->b_refcnt == 0)
379 bp = allocbuf("Ran out of memory for buffers");
381 LIST_REMOVE(bp, b_hash);
383 TAILQ_REMOVE(&bufqueuehd, bp, b_list);
384 flush(fswritefd, bp);
386 LIST_INSERT_HEAD(bhdp, bp, b_hash);
387 getblk(bp, blkno, size);
391 TAILQ_INSERT_HEAD(&bufqueuehd, bp, b_list);
392 if (debug && bp->b_type != type) {
393 printf("getdatablk: buffer type changed to %s",
403 getblk(struct bufarea *bp, ufs2_daddr_t blk, long size)
406 struct timespec start, finish;
408 dblk = fsbtodb(&sblock, blk);
409 if (bp->b_bno == dblk) {
413 readcnt[bp->b_type]++;
414 clock_gettime(CLOCK_REALTIME_PRECISE, &start);
416 bp->b_errs = blread(fsreadfd, bp->b_un.b_buf, dblk, size);
418 clock_gettime(CLOCK_REALTIME_PRECISE, &finish);
419 timespecsub(&finish, &start, &finish);
420 timespecadd(&readtime[bp->b_type], &finish,
421 &readtime[bp->b_type]);
429 brelse(struct bufarea *bp)
432 if (bp->b_refcnt <= 0)
433 prtbuf(bp, "brelse: buffer with negative reference count");
438 binval(struct bufarea *bp)
441 bp->b_flags &= ~B_DIRTY;
442 LIST_REMOVE(bp, b_hash);
443 LIST_INSERT_HEAD(&freebufs, bp, b_hash);
447 flush(int fd, struct bufarea *bp)
451 if ((bp->b_flags & B_DIRTY) == 0)
453 bp->b_flags &= ~B_DIRTY;
455 pfatal("WRITING IN READ_ONLY MODE.\n");
459 pfatal("WRITING %sZERO'ED BLOCK %lld TO DISK\n",
460 (bp->b_errs == bp->b_size / dev_bsize) ? "" : "PARTIALLY ",
461 (long long)bp->b_bno);
464 * Write using the appropriate function.
466 switch (bp->b_type) {
469 pfatal("BUFFER %p DOES NOT MATCH SBLK %p\n",
472 * Superblocks are always pre-copied so we do not need
473 * to check them for copy-on-write.
475 if (sbput(fd, bp->b_un.b_fs, 0) == 0)
480 * Cylinder groups are always pre-copied so we do not
481 * need to check them for copy-on-write.
485 if (cgput(fswritefd, &sblock, bp->b_un.b_cg) == 0)
489 if (debug && sblock.fs_magic == FS_UFS2_MAGIC) {
490 struct ufs2_dinode *dp = bp->b_un.b_dinode2;
493 for (i = 0; i < bp->b_size; dp++, i += sizeof(*dp)) {
494 if (ffs_verify_dinode_ckhash(&sblock, dp) == 0)
496 pwarn("flush: INODE CHECK-HASH FAILED");
498 ip.i_dp = (union dinode *)dp;
499 ip.i_number = bp->b_index + (i / sizeof(*dp));
501 if (preen || reply("FIX") != 0) {
503 printf(" (FIXED)\n");
504 ffs_update_dinode_ckhash(&sblock, dp);
511 copyonwrite(&sblock, bp, std_checkblkavail);
512 blwrite(fd, bp->b_un.b_buf, bp->b_bno, bp->b_size);
518 * If there are any snapshots, ensure that all the blocks that they
519 * care about have been copied, then release the snapshot inodes.
520 * These operations need to be done before we rebuild the cylinder
521 * groups so that any block allocations are properly recorded.
522 * Since all the cylinder group maps have already been copied in
523 * the snapshots, no further snapshot copies will need to be done.
526 snapflush(ufs2_daddr_t (*checkblkavail)(ufs2_daddr_t, long))
533 printf("Check for snapshot copies\n");
534 TAILQ_FOREACH_REVERSE(bp, &bufqueuehd, bufqueue, b_list)
535 if ((bp->b_flags & B_DIRTY) != 0)
536 copyonwrite(&sblock, bp, checkblkavail);
537 for (cnt = 0; cnt < snapcnt; cnt++)
538 irelse(&snaplist[cnt]);
544 * Journaled soft updates does not maintain cylinder group summary
545 * information during cleanup, so this routine recalculates the summary
546 * information and updates the superblock summary in preparation for
547 * writing out the cylinder group.
550 cg_write(struct bufarea *bp)
552 ufs1_daddr_t fragno, cgbno, maxbno;
560 * Fix the frag and cluster summary.
563 cgp->cg_cs.cs_nbfree = 0;
564 cgp->cg_cs.cs_nffree = 0;
565 bzero(&cgp->cg_frsum, sizeof(cgp->cg_frsum));
566 maxbno = fragstoblks(&sblock, sblock.fs_fpg);
567 if (sblock.fs_contigsumsize > 0) {
568 for (i = 1; i <= sblock.fs_contigsumsize; i++)
569 cg_clustersum(cgp)[i] = 0;
570 bzero(cg_clustersfree(cgp), howmany(maxbno, CHAR_BIT));
572 blksfree = cg_blksfree(cgp);
573 for (cgbno = 0; cgbno < maxbno; cgbno++) {
574 if (ffs_isfreeblock(&sblock, blksfree, cgbno))
576 if (ffs_isblock(&sblock, blksfree, cgbno)) {
577 ffs_clusteracct(&sblock, cgp, cgbno, 1);
578 cgp->cg_cs.cs_nbfree++;
581 fragno = blkstofrags(&sblock, cgbno);
582 blk = blkmap(&sblock, blksfree, fragno);
583 ffs_fragacct(&sblock, blk, cgp->cg_frsum, 1);
584 for (i = 0; i < sblock.fs_frag; i++)
585 if (isset(blksfree, fragno + i))
586 cgp->cg_cs.cs_nffree++;
589 * Update the superblock cg summary from our now correct values
590 * before writing the block.
592 csp = &sblock.fs_cs(&sblock, cgp->cg_cgx);
593 sblock.fs_cstotal.cs_ndir += cgp->cg_cs.cs_ndir - csp->cs_ndir;
594 sblock.fs_cstotal.cs_nbfree += cgp->cg_cs.cs_nbfree - csp->cs_nbfree;
595 sblock.fs_cstotal.cs_nifree += cgp->cg_cs.cs_nifree - csp->cs_nifree;
596 sblock.fs_cstotal.cs_nffree += cgp->cg_cs.cs_nffree - csp->cs_nffree;
597 sblock.fs_cs(&sblock, cgp->cg_cgx) = cgp->cg_cs;
601 rwerror(const char *mesg, ufs2_daddr_t blk)
608 pfatal("CANNOT %s: %ld", mesg, (long)blk);
609 if (reply("CONTINUE") == 0)
614 ckfini(int markclean)
616 struct bufarea *bp, *nbp;
617 int ofsmodified, cnt, cg;
621 if ((!(sblock.fs_flags & FS_UNCLEAN)) != markclean) {
622 cmd.value = FS_UNCLEAN;
623 cmd.size = markclean ? -1 : 1;
624 if (sysctlbyname("vfs.ffs.setflags", 0, 0,
625 &cmd, sizeof cmd) == -1)
626 pwarn("CANNOT SET FILE SYSTEM DIRTY FLAG\n");
628 printf("\n***** FILE SYSTEM MARKED %s *****\n",
629 markclean ? "CLEAN" : "DIRTY");
633 } else if (!preen && !markclean) {
634 printf("\n***** FILE SYSTEM STILL DIRTY *****\n");
639 if (debug && cachelookups > 0)
640 printf("cache with %d buffers missed %d of %d (%d%%)\n",
641 numbufs, cachereads, cachelookups,
642 (int)(cachereads * 100 / cachelookups));
644 (void)close(fsreadfd);
649 * To remain idempotent with partial truncations the buffers
650 * must be flushed in this order:
651 * 1) cylinder groups (bitmaps)
652 * 2) indirect, directory, external attribute, and data blocks
655 * This ordering preserves access to the modified pointers
656 * until they are freed.
658 /* Step 1: cylinder groups */
660 printf("Flush Cylinder groups\n");
661 if (cgbufs != NULL) {
662 for (cnt = 0; cnt < sblock.fs_ncg; cnt++) {
663 if (cgbufs[cnt].b_un.b_cg == NULL)
665 flush(fswritefd, &cgbufs[cnt]);
666 free(cgbufs[cnt].b_un.b_cg);
671 flush(fswritefd, &cgblk);
672 free(cgblk.b_un.b_buf);
673 cgblk.b_un.b_buf = NULL;
675 /* Step 2: indirect, directory, external attribute, and data blocks */
677 printf("Flush indirect, directory, external attribute, "
678 "and data blocks\n");
679 if (pdirbp != NULL) {
683 TAILQ_FOREACH_REVERSE_SAFE(bp, &bufqueuehd, bufqueue, b_list, nbp) {
684 switch (bp->b_type) {
685 /* These should not be in the buffer cache list */
690 prtbuf(bp,"ckfini: improper buffer type on cache list");
692 /* These are the ones to flush in this step */
700 /* These are the ones to flush in the next step */
704 if (debug && bp->b_refcnt != 0)
705 prtbuf(bp, "ckfini: clearing in-use buffer");
706 TAILQ_REMOVE(&bufqueuehd, bp, b_list);
707 LIST_REMOVE(bp, b_hash);
709 flush(fswritefd, bp);
710 free(bp->b_un.b_buf);
713 /* Step 3: inode blocks */
715 printf("Flush inode blocks\n");
716 if (icachebp != NULL) {
720 TAILQ_FOREACH_REVERSE_SAFE(bp, &bufqueuehd, bufqueue, b_list, nbp) {
721 if (debug && bp->b_refcnt != 0)
722 prtbuf(bp, "ckfini: clearing in-use buffer");
723 TAILQ_REMOVE(&bufqueuehd, bp, b_list);
724 LIST_REMOVE(bp, b_hash);
726 flush(fswritefd, bp);
727 free(bp->b_un.b_buf);
731 errx(EEXIT, "panic: lost %d buffers", numbufs - cnt);
732 /* Step 4: superblock */
734 printf("Flush the superblock\n");
735 flush(fswritefd, &sblk);
736 if (havesb && cursnapshot == 0 &&
737 sblk.b_bno != sblock.fs_sblockloc / dev_bsize) {
738 if (preen || reply("UPDATE STANDARD SUPERBLOCK")) {
739 /* Change write destination to standard superblock */
740 sblock.fs_sblockactualloc = sblock.fs_sblockloc;
741 sblk.b_bno = sblock.fs_sblockloc / dev_bsize;
743 flush(fswritefd, &sblk);
748 if (cursnapshot == 0 && sblock.fs_clean != markclean) {
749 if ((sblock.fs_clean = markclean) != 0) {
750 sblock.fs_flags &= ~(FS_UNCLEAN | FS_NEEDSFSCK);
751 sblock.fs_pendingblocks = 0;
752 sblock.fs_pendinginodes = 0;
755 ofsmodified = fsmodified;
756 flush(fswritefd, &sblk);
757 fsmodified = ofsmodified;
759 printf("\n***** FILE SYSTEM MARKED %s *****\n",
760 markclean ? "CLEAN" : "DIRTY");
766 printf("\n***** FILE SYSTEM IS CLEAN *****\n");
768 printf("\n***** FILE SYSTEM STILL DIRTY *****\n");
773 * Free allocated tracking structures.
775 if (blockmap != NULL)
778 if (inostathead != NULL) {
779 for (cg = 0; cg < sblock.fs_ncg; cg++)
780 if (inostathead[cg].il_stat != NULL)
781 free((char *)inostathead[cg].il_stat);
787 (void)close(fsreadfd);
788 (void)close(fswritefd);
792 * Print out I/O statistics.
801 if (diskreads == 0) {
802 printf("%s: no I/O\n\n", what);
805 if (startpass.tv_sec == 0)
806 startpass = startprog;
807 printf("%s: I/O statistics\n", what);
809 totaldiskreads += diskreads;
811 for (i = 0; i < BT_NUMBUFTYPES; i++) {
812 timespecadd(&totalreadtime[i], &readtime[i], &totalreadtime[i]);
813 totalreadcnt[i] += readcnt[i];
814 readtime[i].tv_sec = readtime[i].tv_nsec = 0;
817 clock_gettime(CLOCK_REALTIME_PRECISE, &startpass);
827 printf("Final I/O statistics\n");
828 totaldiskreads += diskreads;
829 diskreads = totaldiskreads;
830 startpass = startprog;
831 for (i = 0; i < BT_NUMBUFTYPES; i++) {
832 timespecadd(&totalreadtime[i], &readtime[i], &totalreadtime[i]);
833 totalreadcnt[i] += readcnt[i];
834 readtime[i] = totalreadtime[i];
835 readcnt[i] = totalreadcnt[i];
840 static void printIOstats(void)
842 long long msec, totalmsec;
845 clock_gettime(CLOCK_REALTIME_PRECISE, &finishpass);
846 timespecsub(&finishpass, &startpass, &finishpass);
847 printf("Running time: %jd.%03ld sec\n",
848 (intmax_t)finishpass.tv_sec, finishpass.tv_nsec / 1000000);
849 printf("buffer reads by type:\n");
850 for (totalmsec = 0, i = 0; i < BT_NUMBUFTYPES; i++)
851 totalmsec += readtime[i].tv_sec * 1000 +
852 readtime[i].tv_nsec / 1000000;
855 for (i = 0; i < BT_NUMBUFTYPES; i++) {
859 readtime[i].tv_sec * 1000 + readtime[i].tv_nsec / 1000000;
860 printf("%21s:%8ld %2ld.%ld%% %4jd.%03ld sec %2lld.%lld%%\n",
861 buftype[i], readcnt[i], readcnt[i] * 100 / diskreads,
862 (readcnt[i] * 1000 / diskreads) % 10,
863 (intmax_t)readtime[i].tv_sec, readtime[i].tv_nsec / 1000000,
864 msec * 100 / totalmsec, (msec * 1000 / totalmsec) % 10);
870 blread(int fd, char *buf, ufs2_daddr_t blk, long size)
882 if (pread(fd, buf, (int)size, offset) == size) {
889 * This is handled specially here instead of in rwerror because
890 * rwerror is used for all sorts of errors, not just true read/write
891 * errors. It should be refactored and fixed.
894 pfatal("CANNOT READ_BLK: %ld", (long)blk);
895 errx(EEXIT, "ABORTING DUE TO READ ERRORS");
897 rwerror("READ BLK", blk);
900 memset(buf, 0, (size_t)size);
901 printf("THE FOLLOWING DISK SECTORS COULD NOT BE READ:");
902 for (cp = buf, i = 0; i < size; i += secsize, cp += secsize) {
903 if (pread(fd, cp, (int)secsize, offset + i) != secsize) {
904 if (secsize != dev_bsize && dev_bsize != 1)
905 printf(" %jd (%jd),",
906 (intmax_t)(blk * dev_bsize + i) / secsize,
907 (intmax_t)blk + i / dev_bsize);
909 printf(" %jd,", (intmax_t)blk + i / dev_bsize);
920 blwrite(int fd, char *buf, ufs2_daddr_t blk, ssize_t size)
930 if (pwrite(fd, buf, size, offset) == size) {
935 rwerror("WRITE BLK", blk);
936 printf("THE FOLLOWING SECTORS COULD NOT BE WRITTEN:");
937 for (cp = buf, i = 0; i < size; i += dev_bsize, cp += dev_bsize)
938 if (pwrite(fd, cp, dev_bsize, offset + i) != dev_bsize)
939 printf(" %jd,", (intmax_t)blk + i / dev_bsize);
945 blerase(int fd, ufs2_daddr_t blk, long size)
951 ioarg[0] = blk * dev_bsize;
953 ioctl(fd, DIOCGDELETE, ioarg);
954 /* we don't really care if we succeed or not */
959 * Fill a contiguous region with all-zeroes. Note ZEROBUFSIZE is by
960 * definition a multiple of dev_bsize.
963 blzero(int fd, ufs2_daddr_t blk, long size)
971 zero = calloc(ZEROBUFSIZE, 1);
973 errx(EEXIT, "cannot allocate buffer pool");
975 offset = blk * dev_bsize;
976 if (lseek(fd, offset, 0) < 0)
977 rwerror("SEEK BLK", blk);
979 len = MIN(ZEROBUFSIZE, size);
980 if (write(fd, zero, len) != len)
981 rwerror("WRITE BLK", blk);
982 blk += len / dev_bsize;
988 * Verify cylinder group's magic number and other parameters. If the
989 * test fails, offer an option to rebuild the whole cylinder group.
991 * Return 1 if the cylinder group is good or return 0 if it is bad.
994 #define CHK(lhs, op, rhs, fmt) \
996 pwarn("UFS%d cylinder group %d failed: " \
997 "%s (" #fmt ") %s %s (" #fmt ")\n", \
998 sblock.fs_magic == FS_UFS1_MAGIC ? 1 : 2, cg, \
999 #lhs, (intmax_t)lhs, #op, #rhs, (intmax_t)rhs); \
1003 check_cgmagic(int cg, struct bufarea *cgbp)
1005 struct cg *cgp = cgbp->b_un.b_cg;
1006 uint32_t cghash, calchash;
1007 static int prevfailcg = -1;
1012 * Extended cylinder group checks.
1014 calchash = cgp->cg_ckhash;
1015 if ((sblock.fs_metackhash & CK_CYLGRP) != 0 &&
1016 (ckhashadd & CK_CYLGRP) == 0) {
1017 cghash = cgp->cg_ckhash;
1019 calchash = calculate_crc32c(~0L, (void *)cgp, sblock.fs_cgsize);
1020 cgp->cg_ckhash = cghash;
1023 CHK(cgp->cg_ckhash, !=, calchash, "%jd");
1024 CHK(cg_chkmagic(cgp), ==, 0, "%jd");
1025 CHK(cgp->cg_cgx, !=, cg, "%jd");
1026 CHK(cgp->cg_ndblk, >, sblock.fs_fpg, "%jd");
1027 if (sblock.fs_magic == FS_UFS1_MAGIC) {
1028 CHK(cgp->cg_old_niblk, !=, sblock.fs_ipg, "%jd");
1029 CHK(cgp->cg_old_ncyl, >, sblock.fs_old_cpg, "%jd");
1030 } else if (sblock.fs_magic == FS_UFS2_MAGIC) {
1031 CHK(cgp->cg_niblk, !=, sblock.fs_ipg, "%jd");
1032 CHK(cgp->cg_initediblk, >, sblock.fs_ipg, "%jd");
1034 if (cgbase(&sblock, cg) + sblock.fs_fpg < sblock.fs_size) {
1035 CHK(cgp->cg_ndblk, !=, sblock.fs_fpg, "%jd");
1037 CHK(cgp->cg_ndblk, !=, sblock.fs_size - cgbase(&sblock, cg),
1040 start = sizeof(*cgp);
1041 if (sblock.fs_magic == FS_UFS2_MAGIC) {
1042 CHK(cgp->cg_iusedoff, !=, start, "%jd");
1043 } else if (sblock.fs_magic == FS_UFS1_MAGIC) {
1044 CHK(cgp->cg_niblk, !=, 0, "%jd");
1045 CHK(cgp->cg_initediblk, !=, 0, "%jd");
1046 CHK(cgp->cg_old_ncyl, !=, sblock.fs_old_cpg, "%jd");
1047 CHK(cgp->cg_old_niblk, !=, sblock.fs_ipg, "%jd");
1048 CHK(cgp->cg_old_btotoff, !=, start, "%jd");
1049 CHK(cgp->cg_old_boff, !=, cgp->cg_old_btotoff +
1050 sblock.fs_old_cpg * sizeof(int32_t), "%jd");
1051 CHK(cgp->cg_iusedoff, !=, cgp->cg_old_boff +
1052 sblock.fs_old_cpg * sizeof(u_int16_t), "%jd");
1054 CHK(cgp->cg_freeoff, !=,
1055 cgp->cg_iusedoff + howmany(sblock.fs_ipg, CHAR_BIT), "%jd");
1056 if (sblock.fs_contigsumsize == 0) {
1057 CHK(cgp->cg_nextfreeoff, !=,
1058 cgp->cg_freeoff + howmany(sblock.fs_fpg, CHAR_BIT), "%jd");
1060 CHK(cgp->cg_nclusterblks, !=, cgp->cg_ndblk / sblock.fs_frag,
1062 CHK(cgp->cg_clustersumoff, !=,
1063 roundup(cgp->cg_freeoff + howmany(sblock.fs_fpg, CHAR_BIT),
1064 sizeof(u_int32_t)) - sizeof(u_int32_t), "%jd");
1065 CHK(cgp->cg_clusteroff, !=, cgp->cg_clustersumoff +
1066 (sblock.fs_contigsumsize + 1) * sizeof(u_int32_t), "%jd");
1067 CHK(cgp->cg_nextfreeoff, !=, cgp->cg_clusteroff +
1068 howmany(fragstoblks(&sblock, sblock.fs_fpg), CHAR_BIT),
1073 if (prevfailcg == cg)
1076 pfatal("CYLINDER GROUP %d: INTEGRITY CHECK FAILED", cg);
1082 rebuild_cg(int cg, struct bufarea *cgbp)
1084 struct cg *cgp = cgbp->b_un.b_cg;
1088 * Zero out the cylinder group and then initialize critical fields.
1089 * Bit maps and summaries will be recalculated by later passes.
1091 memset(cgp, 0, (size_t)sblock.fs_cgsize);
1092 cgp->cg_magic = CG_MAGIC;
1094 cgp->cg_niblk = sblock.fs_ipg;
1095 cgp->cg_initediblk = MIN(sblock.fs_ipg, 2 * INOPB(&sblock));
1096 if (cgbase(&sblock, cg) + sblock.fs_fpg < sblock.fs_size)
1097 cgp->cg_ndblk = sblock.fs_fpg;
1099 cgp->cg_ndblk = sblock.fs_size - cgbase(&sblock, cg);
1100 start = sizeof(*cgp);
1101 if (sblock.fs_magic == FS_UFS2_MAGIC) {
1102 cgp->cg_iusedoff = start;
1103 } else if (sblock.fs_magic == FS_UFS1_MAGIC) {
1105 cgp->cg_initediblk = 0;
1106 cgp->cg_old_ncyl = sblock.fs_old_cpg;
1107 cgp->cg_old_niblk = sblock.fs_ipg;
1108 cgp->cg_old_btotoff = start;
1109 cgp->cg_old_boff = cgp->cg_old_btotoff +
1110 sblock.fs_old_cpg * sizeof(int32_t);
1111 cgp->cg_iusedoff = cgp->cg_old_boff +
1112 sblock.fs_old_cpg * sizeof(u_int16_t);
1114 cgp->cg_freeoff = cgp->cg_iusedoff + howmany(sblock.fs_ipg, CHAR_BIT);
1115 cgp->cg_nextfreeoff = cgp->cg_freeoff + howmany(sblock.fs_fpg,CHAR_BIT);
1116 if (sblock.fs_contigsumsize > 0) {
1117 cgp->cg_nclusterblks = cgp->cg_ndblk / sblock.fs_frag;
1118 cgp->cg_clustersumoff =
1119 roundup(cgp->cg_nextfreeoff, sizeof(u_int32_t));
1120 cgp->cg_clustersumoff -= sizeof(u_int32_t);
1121 cgp->cg_clusteroff = cgp->cg_clustersumoff +
1122 (sblock.fs_contigsumsize + 1) * sizeof(u_int32_t);
1123 cgp->cg_nextfreeoff = cgp->cg_clusteroff +
1124 howmany(fragstoblks(&sblock, sblock.fs_fpg), CHAR_BIT);
1126 cgp->cg_ckhash = calculate_crc32c(~0L, (void *)cgp, sblock.fs_cgsize);
1131 * allocate a data block with the specified number of fragments
1134 allocblk(long startcg, long frags,
1135 ufs2_daddr_t (*checkblkavail)(ufs2_daddr_t blkno, long frags))
1137 ufs2_daddr_t blkno, newblk;
1139 if (sujrecovery && checkblkavail == std_checkblkavail) {
1140 pfatal("allocblk: std_checkblkavail used for SUJ recovery\n");
1143 if (frags <= 0 || frags > sblock.fs_frag)
1145 for (blkno = MAX(cgdata(&sblock, startcg), 0);
1146 blkno < maxfsblock - sblock.fs_frag;
1147 blkno += sblock.fs_frag) {
1148 if ((newblk = (*checkblkavail)(blkno, frags)) == 0)
1155 for (blkno = MAX(cgdata(&sblock, 0), 0);
1156 blkno < cgbase(&sblock, startcg) - sblock.fs_frag;
1157 blkno += sblock.fs_frag) {
1158 if ((newblk = (*checkblkavail)(blkno, frags)) == 0)
1169 std_checkblkavail(ufs2_daddr_t blkno, long frags)
1171 struct bufarea *cgbp;
1173 ufs2_daddr_t j, k, baseblk;
1176 if ((u_int64_t)blkno > sblock.fs_size)
1178 for (j = 0; j <= sblock.fs_frag - frags; j++) {
1179 if (testbmap(blkno + j))
1181 for (k = 1; k < frags; k++)
1182 if (testbmap(blkno + j + k))
1188 cg = dtog(&sblock, blkno + j);
1189 cgbp = cglookup(cg);
1190 cgp = cgbp->b_un.b_cg;
1191 if (!check_cgmagic(cg, cgbp))
1192 return (-((cg + 1) * sblock.fs_fpg - sblock.fs_frag));
1193 baseblk = dtogd(&sblock, blkno + j);
1194 for (k = 0; k < frags; k++) {
1195 setbmap(blkno + j + k);
1196 clrbit(cg_blksfree(cgp), baseblk + k);
1199 if (frags == sblock.fs_frag)
1200 cgp->cg_cs.cs_nbfree--;
1202 cgp->cg_cs.cs_nffree -= frags;
1210 * Check whether a file size is within the limits for the filesystem.
1211 * Return 1 when valid and 0 when too big.
1213 * This should match the file size limit in ffs_mountfs().
1216 chkfilesize(mode_t mode, u_int64_t filesize)
1218 u_int64_t kernmaxfilesize;
1220 if (sblock.fs_magic == FS_UFS1_MAGIC)
1221 kernmaxfilesize = (off_t)0x40000000 * sblock.fs_bsize - 1;
1223 kernmaxfilesize = sblock.fs_maxfilesize;
1224 if (filesize > kernmaxfilesize ||
1225 filesize > sblock.fs_maxfilesize ||
1226 (mode == IFDIR && filesize > MAXDIRSIZE)) {
1228 printf("bad file size %ju:", (uintmax_t)filesize);
1235 * Slow down IO so as to leave some disk bandwidth for other processes
1241 /* Delay one in every 8 operations */
1242 slowio_pollcnt = (slowio_pollcnt + 1) & 7;
1243 if (slowio_pollcnt == 0) {
1244 gettimeofday(&slowio_starttime, NULL);
1254 if (slowio_pollcnt != 0)
1257 /* Update the slowdown interval. */
1258 gettimeofday(&tv, NULL);
1259 delay_usec = (tv.tv_sec - slowio_starttime.tv_sec) * 1000000 +
1260 (tv.tv_usec - slowio_starttime.tv_usec);
1261 if (delay_usec < 64)
1263 if (delay_usec > 2500000)
1264 delay_usec = 2500000;
1265 slowio_delay_usec = (slowio_delay_usec * 63 + delay_usec) >> 6;
1266 /* delay by 8 times the average IO delay */
1267 if (slowio_delay_usec > 64)
1268 usleep(slowio_delay_usec * 8);
1275 getpathname(char *namebuf, ino_t curdir, ino_t ino)
1280 struct inodesc idesc;
1281 static int busy = 0;
1283 if (curdir == ino && ino == UFS_ROOTINO) {
1284 (void)strcpy(namebuf, "/");
1287 if (busy || !INO_IS_DVALID(curdir)) {
1288 (void)strcpy(namebuf, "?");
1292 memset(&idesc, 0, sizeof(struct inodesc));
1293 idesc.id_type = DATA;
1294 idesc.id_fix = IGNORE;
1295 cp = &namebuf[MAXPATHLEN - 1];
1297 if (curdir != ino) {
1298 idesc.id_parent = curdir;
1301 while (ino != UFS_ROOTINO) {
1302 idesc.id_number = ino;
1303 idesc.id_func = findino;
1304 idesc.id_name = strdup("..");
1306 if ((ckinode(ip.i_dp, &idesc) & FOUND) == 0) {
1308 free(idesc.id_name);
1312 free(idesc.id_name);
1314 idesc.id_number = idesc.id_parent;
1315 idesc.id_parent = ino;
1316 idesc.id_func = findname;
1317 idesc.id_name = namebuf;
1318 ginode(idesc.id_number, &ip);
1319 if ((ckinode(ip.i_dp, &idesc) & FOUND) == 0) {
1324 len = strlen(namebuf);
1326 memmove(cp, namebuf, (size_t)len);
1328 if (cp < &namebuf[UFS_MAXNAMLEN])
1330 ino = idesc.id_number;
1333 if (ino != UFS_ROOTINO)
1335 memmove(namebuf, cp, (size_t)(&namebuf[MAXPATHLEN] - cp));
1339 catch(int sig __unused)
1347 * When preening, allow a single quit to signal
1348 * a special exit after file system checks complete
1349 * so that reboot sequence may be interrupted.
1352 catchquit(int sig __unused)
1354 printf("returning to single-user after file system check\n");
1356 (void)signal(SIGQUIT, SIG_DFL);
1360 * determine whether an inode should be fixed.
1363 dofix(struct inodesc *idesc, const char *msg)
1366 switch (idesc->id_fix) {
1369 if (idesc->id_type == DATA)
1370 direrror(idesc->id_number, msg);
1374 printf(" (SALVAGED)\n");
1375 idesc->id_fix = FIX;
1378 if (reply("SALVAGE") == 0) {
1379 idesc->id_fix = NOFIX;
1382 idesc->id_fix = FIX;
1393 errx(EEXIT, "UNKNOWN INODESC FIX MODE %d", idesc->id_fix);
1402 * Print details about a buffer.
1405 prtbuf(struct bufarea *bp, const char *fmt, ...)
1410 (void)fprintf(stdout, "%s: ", cdevname);
1411 (void)vfprintf(stdout, fmt, ap);
1413 printf(": bp %p, type %s, bno %jd, size %d, refcnt %d, flags %s, "
1414 "index %jd\n", bp, BT_BUFTYPE(bp->b_type), (intmax_t) bp->b_bno,
1415 bp->b_size, bp->b_refcnt, bp->b_flags & B_DIRTY ? "dirty" : "clean",
1416 (intmax_t) bp->b_index);
1420 * An unexpected inconsistency occurred.
1421 * Die if preening or file system is running with soft dependency protocol,
1422 * otherwise just print message and continue.
1425 pfatal(const char *fmt, ...)
1430 (void)vfprintf(stdout, fmt, ap);
1433 (void)fprintf(stdout,
1434 "\nUNEXPECTED SOFT UPDATE INCONSISTENCY\n");
1436 * Force foreground fsck to clean up inconsistency.
1439 cmd.value = FS_NEEDSFSCK;
1441 if (sysctlbyname("vfs.ffs.setflags", 0, 0,
1442 &cmd, sizeof cmd) == -1)
1443 pwarn("CANNOT SET FS_NEEDSFSCK FLAG\n");
1444 fprintf(stdout, "CANNOT RUN IN BACKGROUND\n");
1450 if (cdevname == NULL)
1451 cdevname = strdup("fsck");
1452 (void)fprintf(stdout, "%s: ", cdevname);
1453 (void)vfprintf(stdout, fmt, ap);
1454 (void)fprintf(stdout,
1455 "\n%s: UNEXPECTED%sINCONSISTENCY; RUN fsck MANUALLY.\n",
1456 cdevname, usedsoftdep ? " SOFT UPDATE " : " ");
1458 * Force foreground fsck to clean up inconsistency.
1461 cmd.value = FS_NEEDSFSCK;
1463 if (sysctlbyname("vfs.ffs.setflags", 0, 0,
1464 &cmd, sizeof cmd) == -1)
1465 pwarn("CANNOT SET FS_NEEDSFSCK FLAG\n");
1472 * Pwarn just prints a message when not preening or running soft dependency
1473 * protocol, or a warning (preceded by filename) when preening.
1476 pwarn(const char *fmt, ...)
1481 (void)fprintf(stdout, "%s: ", cdevname);
1482 (void)vfprintf(stdout, fmt, ap);
1487 * Stub for routines from kernel.
1490 panic(const char *fmt, ...)
1494 pfatal("INTERNAL INCONSISTENCY:");
1495 (void)vfprintf(stdout, fmt, ap);