Home | History | Annotate | Line # | Download | only in lfs_cleanerd
lfs_cleanerd.c revision 1.44
      1 /* $NetBSD: lfs_cleanerd.c,v 1.44 2015/08/02 18:18:09 dholland Exp $	 */
      2 
      3 /*-
      4  * Copyright (c) 2005 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Konrad E. Schroder <perseant (at) hhhh.org>.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     29  * POSSIBILITY OF SUCH DAMAGE.
     30  */
     31 
     32 /*
     33  * The cleaner daemon for the NetBSD Log-structured File System.
     34  * Only tested for use with version 2 LFSs.
     35  */
     36 
     37 #include <sys/syslog.h>
     38 #include <sys/param.h>
     39 #include <sys/mount.h>
     40 #include <sys/stat.h>
     41 #include <ufs/lfs/lfs.h>
     42 
     43 #include <assert.h>
     44 #include <err.h>
     45 #include <errno.h>
     46 #include <fcntl.h>
     47 #include <semaphore.h>
     48 #include <stdio.h>
     49 #include <stdlib.h>
     50 #include <string.h>
     51 #include <unistd.h>
     52 #include <time.h>
     53 #include <util.h>
     54 
     55 #include "bufcache.h"
     56 #include "vnode.h"
     57 #include "lfs_user.h"
     58 #include "fdfs.h"
     59 #include "cleaner.h"
     60 #include "kernelops.h"
     61 #include "mount_lfs.h"
     62 
     63 /*
     64  * Global variables.
     65  */
     66 /* XXX these top few should really be fs-specific */
     67 int use_fs_idle;	/* Use fs idle rather than cpu idle time */
     68 int use_bytes;		/* Use bytes written rather than segments cleaned */
     69 double load_threshold;	/* How idle is idle (CPU idle) */
     70 int atatime;		/* How many segments (bytes) to clean at a time */
     71 
     72 int nfss;		/* Number of filesystems monitored by this cleanerd */
     73 struct clfs **fsp;	/* Array of extended filesystem structures */
     74 int segwait_timeout;	/* Time to wait in lfs_segwait() */
     75 int do_quit;		/* Quit after one cleaning loop */
     76 int do_coalesce;	/* Coalesce filesystem */
     77 int do_small;		/* Use small writes through markv */
     78 char *copylog_filename; /* File to use for fs debugging analysis */
     79 int inval_segment;	/* Segment to invalidate */
     80 int stat_report;	/* Report statistics for this period of cycles */
     81 int debug;		/* Turn on debugging */
     82 struct cleaner_stats {
     83 	double	util_tot;
     84 	double	util_sos;
     85 	off_t	bytes_read;
     86 	off_t	bytes_written;
     87 	off_t	segs_cleaned;
     88 	off_t	segs_empty;
     89 	off_t	segs_error;
     90 } cleaner_stats;
     91 
     92 extern u_int32_t cksum(void *, size_t);
     93 extern u_int32_t lfs_sb_cksum(struct dlfs *);
     94 extern u_int32_t lfs_cksum_part(void *, size_t, u_int32_t);
     95 extern int ulfs_getlbns(struct lfs *, struct uvnode *, daddr_t, struct indir *, int *);
     96 
     97 /* Ugh */
     98 #define FSMNT_SIZE MAX(sizeof(((struct dlfs *)0)->dlfs_fsmnt), \
     99 			sizeof(((struct dlfs64 *)0)->dlfs_fsmnt))
    100 
    101 
    102 /* Compat */
    103 void pwarn(const char *unused, ...) { /* Does nothing */ };
    104 
    105 /*
    106  * Log a message if debugging is turned on.
    107  */
    108 void
    109 dlog(const char *fmt, ...)
    110 {
    111 	va_list ap;
    112 
    113 	if (debug == 0)
    114 		return;
    115 
    116 	va_start(ap, fmt);
    117 	vsyslog(LOG_DEBUG, fmt, ap);
    118 	va_end(ap);
    119 }
    120 
    121 /*
    122  * Remove the specified filesystem from the list, due to its having
    123  * become unmounted or other error condition.
    124  */
    125 void
    126 handle_error(struct clfs **cfsp, int n)
    127 {
    128 	syslog(LOG_NOTICE, "%s: detaching cleaner", lfs_sb_getfsmnt(cfsp[n]));
    129 	free(cfsp[n]);
    130 	if (n != nfss - 1)
    131 		cfsp[n] = cfsp[nfss - 1];
    132 	--nfss;
    133 }
    134 
    135 /*
    136  * Reinitialize a filesystem if, e.g., its size changed.
    137  */
    138 int
    139 reinit_fs(struct clfs *fs)
    140 {
    141 	char fsname[FSMNT_SIZE];
    142 
    143 	memcpy(fsname, lfs_sb_getfsmnt(fs), sizeof(fsname));
    144 	fsname[sizeof(fsname) - 1] = '\0';
    145 
    146 	kops.ko_close(fs->clfs_ifilefd);
    147 	kops.ko_close(fs->clfs_devfd);
    148 	fd_reclaim(fs->clfs_devvp);
    149 	fd_reclaim(fs->lfs_ivnode);
    150 	free(fs->clfs_dev);
    151 	free(fs->clfs_segtab);
    152 	free(fs->clfs_segtabp);
    153 
    154 	return init_fs(fs, fsname);
    155 }
    156 
    157 #ifdef REPAIR_ZERO_FINFO
    158 /*
    159  * Use fsck's lfs routines to load the Ifile from an unmounted fs.
    160  * We interpret "fsname" as the name of the raw disk device.
    161  */
    162 int
    163 init_unmounted_fs(struct clfs *fs, char *fsname)
    164 {
    165 	struct lfs *disc_fs;
    166 	int i;
    167 
    168 	fs->clfs_dev = fsname;
    169 	if ((fs->clfs_devfd = kops.ko_open(fs->clfs_dev, O_RDWR)) < 0) {
    170 		syslog(LOG_ERR, "couldn't open device %s read/write",
    171 		       fs->clfs_dev);
    172 		return -1;
    173 	}
    174 
    175 	disc_fs = lfs_init(fs->clfs_devfd, 0, 0, 0, 0);
    176 
    177 	fs->lfs_dlfs = disc_fs->lfs_dlfs; /* Structure copy */
    178 	strncpy(fs->lfs_fsmnt, fsname, MNAMELEN);
    179 	fs->lfs_ivnode = (struct uvnode *)disc_fs->lfs_ivnode;
    180 	fs->clfs_devvp = fd_vget(fs->clfs_devfd, fs->lfs_fsize, fs->lfs_ssize,
    181 				 atatime);
    182 
    183 	/* Allocate and clear segtab */
    184 	fs->clfs_segtab = (struct clfs_seguse *)malloc(lfs_sb_getnseg(fs) *
    185 						sizeof(*fs->clfs_segtab));
    186 	fs->clfs_segtabp = (struct clfs_seguse **)malloc(lfs_sb_getnseg(fs) *
    187 						sizeof(*fs->clfs_segtabp));
    188 	for (i = 0; i < lfs_sb_getnseg(fs); i++) {
    189 		fs->clfs_segtabp[i] = &(fs->clfs_segtab[i]);
    190 		fs->clfs_segtab[i].flags = 0x0;
    191 	}
    192 	syslog(LOG_NOTICE, "%s: unmounted cleaner starting", fsname);
    193 
    194 	return 0;
    195 }
    196 #endif
    197 
    198 /*
    199  * Set up the file descriptors, including the Ifile descriptor.
    200  * If we can't get the Ifile, this is not an LFS (or the kernel is
    201  * too old to support the fcntl).
    202  * XXX Merge this and init_unmounted_fs, switching on whether
    203  * XXX "fsname" is a dir or a char special device.  Should
    204  * XXX also be able to read unmounted devices out of fstab, the way
    205  * XXX fsck does.
    206  */
    207 int
    208 init_fs(struct clfs *fs, char *fsname)
    209 {
    210 	char mnttmp[FSMNT_SIZE];
    211 	struct statvfs sf;
    212 	int rootfd;
    213 	int i;
    214 	void *sbuf;
    215 	char *bn;
    216 
    217 	/*
    218 	 * Get the raw device from the block device.
    219 	 * XXX this is ugly.  Is there a way to discover the raw device
    220 	 * XXX for a given mount point?
    221 	 */
    222 	if (kops.ko_statvfs(fsname, &sf, ST_WAIT) < 0)
    223 		return -1;
    224 	fs->clfs_dev = malloc(strlen(sf.f_mntfromname) + 2);
    225 	if (fs->clfs_dev == NULL) {
    226 		syslog(LOG_ERR, "couldn't malloc device name string: %m");
    227 		return -1;
    228 	}
    229 	bn = strrchr(sf.f_mntfromname, '/');
    230 	bn = bn ? bn+1 : sf.f_mntfromname;
    231 	strlcpy(fs->clfs_dev, sf.f_mntfromname, bn - sf.f_mntfromname + 1);
    232 	strcat(fs->clfs_dev, "r");
    233 	strcat(fs->clfs_dev, bn);
    234 	if ((fs->clfs_devfd = kops.ko_open(fs->clfs_dev, O_RDONLY, 0)) < 0) {
    235 		syslog(LOG_ERR, "couldn't open device %s for reading",
    236 			fs->clfs_dev);
    237 		return -1;
    238 	}
    239 
    240 	/* Find the Ifile and open it */
    241 	if ((rootfd = kops.ko_open(fsname, O_RDONLY, 0)) < 0)
    242 		return -2;
    243 	if (kops.ko_fcntl(rootfd, LFCNIFILEFH, &fs->clfs_ifilefh) < 0)
    244 		return -3;
    245 	if ((fs->clfs_ifilefd = kops.ko_fhopen(&fs->clfs_ifilefh,
    246 	    sizeof(fs->clfs_ifilefh), O_RDONLY)) < 0)
    247 		return -4;
    248 	kops.ko_close(rootfd);
    249 
    250 	sbuf = malloc(LFS_SBPAD);
    251 	if (sbuf == NULL) {
    252 		syslog(LOG_ERR, "couldn't malloc superblock buffer");
    253 		return -1;
    254 	}
    255 
    256 	/* Load in the superblock */
    257 	if (kops.ko_pread(fs->clfs_devfd, sbuf, LFS_SBPAD, LFS_LABELPAD) < 0) {
    258 		free(sbuf);
    259 		return -1;
    260 	}
    261 
    262 	__CTASSERT(sizeof(struct dlfs) == sizeof(struct dlfs64));
    263 	memcpy(&fs->lfs_dlfs_u, sbuf, sizeof(struct dlfs));
    264 	free(sbuf);
    265 
    266 	/* If it is not LFS, complain and exit! */
    267 	if (fs->lfs_dlfs_u.u_32.dlfs_magic != LFS_MAGIC) {
    268 		syslog(LOG_ERR, "%s: not LFS", fsname);
    269 		return -1;
    270 	}
    271 	fs->lfs_is64 = 0; /* XXX notyet */
    272 
    273 	/* If this is not a version 2 filesystem, complain and exit */
    274 	if (lfs_sb_getversion(fs) != 2) {
    275 		syslog(LOG_ERR, "%s: not a version 2 LFS", fsname);
    276 		return -1;
    277 	}
    278 
    279 	/* Assume fsname is the mounted name */
    280 	strncpy(mnttmp, fsname, sizeof(mnttmp));
    281 	mnttmp[sizeof(mnttmp) - 1] = '\0';
    282 	lfs_sb_setfsmnt(fs, mnttmp);
    283 
    284 	/* Set up vnodes for Ifile and raw device */
    285 	fs->lfs_ivnode = fd_vget(fs->clfs_ifilefd, lfs_sb_getbsize(fs), 0, 0);
    286 	fs->clfs_devvp = fd_vget(fs->clfs_devfd, lfs_sb_getfsize(fs), lfs_sb_getssize(fs),
    287 				 atatime);
    288 
    289 	/* Allocate and clear segtab */
    290 	fs->clfs_segtab = (struct clfs_seguse *)malloc(lfs_sb_getnseg(fs) *
    291 						sizeof(*fs->clfs_segtab));
    292 	fs->clfs_segtabp = (struct clfs_seguse **)malloc(lfs_sb_getnseg(fs) *
    293 						sizeof(*fs->clfs_segtabp));
    294 	if (fs->clfs_segtab == NULL || fs->clfs_segtabp == NULL) {
    295 		syslog(LOG_ERR, "%s: couldn't malloc segment table: %m",
    296 			fs->clfs_dev);
    297 		return -1;
    298 	}
    299 
    300 	for (i = 0; i < lfs_sb_getnseg(fs); i++) {
    301 		fs->clfs_segtabp[i] = &(fs->clfs_segtab[i]);
    302 		fs->clfs_segtab[i].flags = 0x0;
    303 	}
    304 
    305 	syslog(LOG_NOTICE, "%s: attaching cleaner", fsname);
    306 	return 0;
    307 }
    308 
    309 /*
    310  * Invalidate all the currently held Ifile blocks so they will be
    311  * reread when we clean.  Check the size while we're at it, and
    312  * resize the buffer cache if necessary.
    313  */
    314 void
    315 reload_ifile(struct clfs *fs)
    316 {
    317 	struct ubuf *bp;
    318 	struct stat st;
    319 	int ohashmax;
    320 	extern int hashmax;
    321 
    322 	while ((bp = LIST_FIRST(&fs->lfs_ivnode->v_dirtyblkhd)) != NULL) {
    323 		bremfree(bp);
    324 		buf_destroy(bp);
    325 	}
    326 	while ((bp = LIST_FIRST(&fs->lfs_ivnode->v_cleanblkhd)) != NULL) {
    327 		bremfree(bp);
    328 		buf_destroy(bp);
    329 	}
    330 
    331 	/* If Ifile is larger than buffer cache, rehash */
    332 	fstat(fs->clfs_ifilefd, &st);
    333 	if (st.st_size / lfs_sb_getbsize(fs) > hashmax) {
    334 		ohashmax = hashmax;
    335 		bufrehash(st.st_size / lfs_sb_getbsize(fs));
    336 		dlog("%s: resized buffer hash from %d to %d",
    337 		     lfs_sb_getfsmnt(fs), ohashmax, hashmax);
    338 	}
    339 }
    340 
    341 /*
    342  * Get IFILE entry for the given inode, store in ifpp.	The buffer
    343  * which contains that data is returned in bpp, and must be brelse()d
    344  * by the caller.
    345  */
    346 void
    347 lfs_ientry(IFILE **ifpp, struct clfs *fs, ino_t ino, struct ubuf **bpp)
    348 {
    349 	int error;
    350 
    351 	error = bread(fs->lfs_ivnode,
    352 		      ino / lfs_sb_getifpb(fs) + lfs_sb_getcleansz(fs) +
    353 		      lfs_sb_getsegtabsz(fs), lfs_sb_getbsize(fs), 0, bpp);
    354 	if (error)
    355 		syslog(LOG_ERR, "%s: ientry failed for ino %d",
    356 			lfs_sb_getfsmnt(fs), (int)ino);
    357 	*ifpp = (IFILE *)(*bpp)->b_data + ino % lfs_sb_getifpb(fs);
    358 	return;
    359 }
    360 
    361 #ifdef TEST_PATTERN
    362 /*
    363  * Check ULFS_ROOTINO for file data.  The assumption is that we are running
    364  * the "twofiles" test with the rest of the filesystem empty.  Files
    365  * created by "twofiles" match the test pattern, but ULFS_ROOTINO and the
    366  * executable itself (assumed to be inode 3) should not match.
    367  */
    368 static void
    369 check_test_pattern(BLOCK_INFO *bip)
    370 {
    371 	int j;
    372 	unsigned char *cp = bip->bi_bp;
    373 
    374 	/* Check inode sanity */
    375 	if (bip->bi_lbn == LFS_UNUSED_LBN) {
    376 		assert(((struct ulfs1_dinode *)bip->bi_bp)->di_inumber ==
    377 			bip->bi_inode);
    378 	}
    379 
    380 	/* These can have the test pattern and it's all good */
    381 	if (bip->bi_inode > 3)
    382 		return;
    383 
    384 	for (j = 0; j < bip->bi_size; j++) {
    385 		if (cp[j] != (j & 0xff))
    386 			break;
    387 	}
    388 	assert(j < bip->bi_size);
    389 }
    390 #endif /* TEST_PATTERN */
    391 
    392 /*
    393  * Parse the partial segment at daddr, adding its information to
    394  * bip.	 Return the address of the next partial segment to read.
    395  */
    396 static daddr_t
    397 parse_pseg(struct clfs *fs, daddr_t daddr, BLOCK_INFO **bipp, int *bic)
    398 {
    399 	SEGSUM *ssp;
    400 	IFILE *ifp;
    401 	BLOCK_INFO *bip, *nbip;
    402 	int32_t *iaddrp;
    403 	daddr_t idaddr, odaddr;
    404 	FINFO *fip;
    405 	struct ubuf *ifbp;
    406 	struct ulfs1_dinode *dip;
    407 	u_int32_t ck, vers;
    408 	int fic, inoc, obic;
    409 	int i;
    410 	char *cp;
    411 
    412 	odaddr = daddr;
    413 	obic = *bic;
    414 	bip = *bipp;
    415 
    416 	/*
    417 	 * Retrieve the segment header, set up the SEGSUM pointer
    418 	 * as well as the first FINFO and inode address pointer.
    419 	 */
    420 	cp = fd_ptrget(fs->clfs_devvp, daddr);
    421 	ssp = (SEGSUM *)cp;
    422 	/* XXX ondisk32 */
    423 	iaddrp = ((int32_t *)(cp + lfs_sb_getibsize(fs))) - 1;
    424 	fip = (FINFO *)(cp + sizeof(SEGSUM));
    425 
    426 	/*
    427 	 * Check segment header magic and checksum
    428 	 */
    429 	if (ssp->ss_magic != SS_MAGIC) {
    430 		syslog(LOG_WARNING, "%s: sumsum magic number bad at 0x%jx:"
    431 		       " read 0x%x, expected 0x%x", lfs_sb_getfsmnt(fs),
    432 		       (intmax_t)daddr, ssp->ss_magic, SS_MAGIC);
    433 		return 0x0;
    434 	}
    435 	ck = cksum(&ssp->ss_datasum, lfs_sb_getsumsize(fs) - sizeof(ssp->ss_sumsum));
    436 	if (ck != ssp->ss_sumsum) {
    437 		syslog(LOG_WARNING, "%s: sumsum checksum mismatch at 0x%jx:"
    438 		       " read 0x%x, computed 0x%x", lfs_sb_getfsmnt(fs),
    439 		       (intmax_t)daddr, ssp->ss_sumsum, ck);
    440 		return 0x0;
    441 	}
    442 
    443 	/* Initialize data sum */
    444 	ck = 0;
    445 
    446 	/* Point daddr at next block after segment summary */
    447 	++daddr;
    448 
    449 	/*
    450 	 * Loop over file info and inode pointers.  We always move daddr
    451 	 * forward here because we are also computing the data checksum
    452 	 * as we go.
    453 	 */
    454 	fic = inoc = 0;
    455 	while (fic < ssp->ss_nfinfo || inoc < ssp->ss_ninos) {
    456 		/*
    457 		 * We must have either a file block or an inode block.
    458 		 * If we don't have either one, it's an error.
    459 		 */
    460 		if (fic >= ssp->ss_nfinfo && *iaddrp != daddr) {
    461 			syslog(LOG_WARNING, "%s: bad pseg at %jx (seg %d)",
    462 			       lfs_sb_getfsmnt(fs), (intmax_t)odaddr, lfs_dtosn(fs, odaddr));
    463 			*bipp = bip;
    464 			return 0x0;
    465 		}
    466 
    467 		/*
    468 		 * Note each inode from the inode blocks
    469 		 */
    470 		if (inoc < ssp->ss_ninos && *iaddrp == daddr) {
    471 			cp = fd_ptrget(fs->clfs_devvp, daddr);
    472 			ck = lfs_cksum_part(cp, sizeof(u_int32_t), ck);
    473 			dip = (struct ulfs1_dinode *)cp;
    474 			for (i = 0; i < lfs_sb_getinopb(fs); i++) {
    475 				if (dip[i].di_inumber == 0)
    476 					break;
    477 
    478 				/*
    479 				 * Check currency before adding it
    480 				 */
    481 #ifndef REPAIR_ZERO_FINFO
    482 				lfs_ientry(&ifp, fs, dip[i].di_inumber, &ifbp);
    483 				idaddr = ifp->if_daddr;
    484 				brelse(ifbp, 0);
    485 				if (idaddr != daddr)
    486 #endif
    487 					continue;
    488 
    489 				/*
    490 				 * A current inode.  Add it.
    491 				 */
    492 				++*bic;
    493 				nbip = (BLOCK_INFO *)realloc(bip, *bic *
    494 							     sizeof(*bip));
    495 				if (nbip)
    496 					bip = nbip;
    497 				else {
    498 					--*bic;
    499 					*bipp = bip;
    500 					return 0x0;
    501 				}
    502 				bip[*bic - 1].bi_inode = dip[i].di_inumber;
    503 				bip[*bic - 1].bi_lbn = LFS_UNUSED_LBN;
    504 				bip[*bic - 1].bi_daddr = daddr;
    505 				bip[*bic - 1].bi_segcreate = ssp->ss_create;
    506 				bip[*bic - 1].bi_version = dip[i].di_gen;
    507 				bip[*bic - 1].bi_bp = &(dip[i]);
    508 				bip[*bic - 1].bi_size = LFS_DINODE1_SIZE;
    509 			}
    510 			inoc += i;
    511 			daddr += lfs_btofsb(fs, lfs_sb_getibsize(fs));
    512 			--iaddrp;
    513 			continue;
    514 		}
    515 
    516 		/*
    517 		 * Note each file block from the finfo blocks
    518 		 */
    519 		if (fic >= ssp->ss_nfinfo)
    520 			continue;
    521 
    522 		/* Count this finfo, whether or not we use it */
    523 		++fic;
    524 
    525 		/*
    526 		 * If this finfo has nblocks==0, it was written wrong.
    527 		 * Kernels with this problem always wrote this zero-sized
    528 		 * finfo last, so just ignore it.
    529 		 */
    530 		if (fip->fi_nblocks == 0) {
    531 #ifdef REPAIR_ZERO_FINFO
    532 			struct ubuf *nbp;
    533 			SEGSUM *nssp;
    534 
    535 			syslog(LOG_WARNING, "fixing short FINFO at %jx (seg %d)",
    536 			       (intmax_t)odaddr, lfs_dtosn(fs, odaddr));
    537 			bread(fs->clfs_devvp, odaddr, lfs_sb_getfsize(fs),
    538 			    0, &nbp);
    539 			nssp = (SEGSUM *)nbp->b_data;
    540 			--nssp->ss_nfinfo;
    541 			nssp->ss_sumsum = cksum(&nssp->ss_datasum,
    542 				lfs_sb_getsumsize(fs) - sizeof(nssp->ss_sumsum));
    543 			bwrite(nbp);
    544 #endif
    545 			syslog(LOG_WARNING, "zero-length FINFO at %jx (seg %d)",
    546 			       (intmax_t)odaddr, lfs_dtosn(fs, odaddr));
    547 			continue;
    548 		}
    549 
    550 		/*
    551 		 * Check currency before adding blocks
    552 		 */
    553 #ifdef REPAIR_ZERO_FINFO
    554 		vers = -1;
    555 #else
    556 		lfs_ientry(&ifp, fs, fip->fi_ino, &ifbp);
    557 		vers = ifp->if_version;
    558 		brelse(ifbp, 0);
    559 #endif
    560 		if (vers != fip->fi_version) {
    561 			size_t size;
    562 
    563 			/* Read all the blocks from the data summary */
    564 			for (i = 0; i < fip->fi_nblocks; i++) {
    565 				size = (i == fip->fi_nblocks - 1) ?
    566 					fip->fi_lastlength : lfs_sb_getbsize(fs);
    567 				cp = fd_ptrget(fs->clfs_devvp, daddr);
    568 				ck = lfs_cksum_part(cp, sizeof(u_int32_t), ck);
    569 				daddr += lfs_btofsb(fs, size);
    570 			}
    571 			fip = (FINFO *)(fip->fi_blocks + fip->fi_nblocks);
    572 			continue;
    573 		}
    574 
    575 		/* Add all the blocks from the finfos (current or not) */
    576 		nbip = (BLOCK_INFO *)realloc(bip, (*bic + fip->fi_nblocks) *
    577 					     sizeof(*bip));
    578 		if (nbip)
    579 			bip = nbip;
    580 		else {
    581 			*bipp = bip;
    582 			return 0x0;
    583 		}
    584 
    585 		for (i = 0; i < fip->fi_nblocks; i++) {
    586 			bip[*bic + i].bi_inode = fip->fi_ino;
    587 			bip[*bic + i].bi_lbn = fip->fi_blocks[i];
    588 			bip[*bic + i].bi_daddr = daddr;
    589 			bip[*bic + i].bi_segcreate = ssp->ss_create;
    590 			bip[*bic + i].bi_version = fip->fi_version;
    591 			bip[*bic + i].bi_size = (i == fip->fi_nblocks - 1) ?
    592 				fip->fi_lastlength : lfs_sb_getbsize(fs);
    593 			cp = fd_ptrget(fs->clfs_devvp, daddr);
    594 			ck = lfs_cksum_part(cp, sizeof(u_int32_t), ck);
    595 			bip[*bic + i].bi_bp = cp;
    596 			daddr += lfs_btofsb(fs, bip[*bic + i].bi_size);
    597 
    598 #ifdef TEST_PATTERN
    599 			check_test_pattern(bip + *bic + i); /* XXXDEBUG */
    600 #endif
    601 		}
    602 		*bic += fip->fi_nblocks;
    603 		fip = (FINFO *)(fip->fi_blocks + fip->fi_nblocks);
    604 	}
    605 
    606 #ifndef REPAIR_ZERO_FINFO
    607 	if (ssp->ss_datasum != ck) {
    608 		syslog(LOG_WARNING, "%s: data checksum bad at 0x%jx:"
    609 		       " read 0x%x, computed 0x%x", lfs_sb_getfsmnt(fs),
    610 		       (intmax_t)odaddr,
    611 		       ssp->ss_datasum, ck);
    612 		*bic = obic;
    613 		return 0x0;
    614 	}
    615 #endif
    616 
    617 	*bipp = bip;
    618 	return daddr;
    619 }
    620 
    621 static void
    622 log_segment_read(struct clfs *fs, int sn)
    623 {
    624         FILE *fp;
    625 	char *cp;
    626 
    627         /*
    628          * Write the segment read, and its contents, into a log file in
    629          * the current directory.  We don't need to log the location of
    630          * the segment, since that can be inferred from the segments up
    631 	 * to this point (ss_nextseg field of the previously written segment).
    632 	 *
    633 	 * We can use this info later to reconstruct the filesystem at any
    634 	 * given point in time for analysis, by replaying the log forward
    635 	 * indexed by the segment serial numbers; but it is not suitable
    636 	 * for everyday use since the copylog will be simply enormous.
    637          */
    638 	cp = fd_ptrget(fs->clfs_devvp, lfs_sntod(fs, sn));
    639 
    640         fp = fopen(copylog_filename, "ab");
    641         if (fp != NULL) {
    642                 if (fwrite(cp, (size_t)lfs_sb_getssize(fs), 1, fp) != 1) {
    643                         perror("writing segment to copy log");
    644                 }
    645         }
    646         fclose(fp);
    647 }
    648 
    649 /*
    650  * Read a segment to populate the BLOCK_INFO structures.
    651  * Return the number of partial segments read and parsed.
    652  */
    653 int
    654 load_segment(struct clfs *fs, int sn, BLOCK_INFO **bipp, int *bic)
    655 {
    656 	daddr_t daddr;
    657 	int i, npseg;
    658 
    659 	daddr = lfs_sntod(fs, sn);
    660 	if (daddr < lfs_btofsb(fs, LFS_LABELPAD))
    661 		daddr = lfs_btofsb(fs, LFS_LABELPAD);
    662 	for (i = 0; i < LFS_MAXNUMSB; i++) {
    663 		if (lfs_sb_getsboff(fs, i) == daddr) {
    664 			daddr += lfs_btofsb(fs, LFS_SBPAD);
    665 			break;
    666 		}
    667 	}
    668 
    669 	/* Preload the segment buffer */
    670 	if (fd_preload(fs->clfs_devvp, lfs_sntod(fs, sn)) < 0)
    671 		return -1;
    672 
    673 	if (copylog_filename)
    674 		log_segment_read(fs, sn);
    675 
    676 	/* Note bytes read for stats */
    677 	cleaner_stats.segs_cleaned++;
    678 	cleaner_stats.bytes_read += lfs_sb_getssize(fs);
    679 	++fs->clfs_nactive;
    680 
    681 	npseg = 0;
    682 	while(lfs_dtosn(fs, daddr) == sn &&
    683 	      lfs_dtosn(fs, daddr + lfs_btofsb(fs, lfs_sb_getbsize(fs))) == sn) {
    684 		daddr = parse_pseg(fs, daddr, bipp, bic);
    685 		if (daddr == 0x0) {
    686 			++cleaner_stats.segs_error;
    687 			break;
    688 		}
    689 		++npseg;
    690 	}
    691 
    692 	return npseg;
    693 }
    694 
    695 void
    696 calc_cb(struct clfs *fs, int sn, struct clfs_seguse *t)
    697 {
    698 	time_t now;
    699 	int64_t age, benefit, cost;
    700 
    701 	time(&now);
    702 	age = (now < t->lastmod ? 0 : now - t->lastmod);
    703 
    704 	/* Under no circumstances clean active or already-clean segments */
    705 	if ((t->flags & SEGUSE_ACTIVE) || !(t->flags & SEGUSE_DIRTY)) {
    706 		t->priority = 0;
    707 		return;
    708 	}
    709 
    710 	/*
    711 	 * If the segment is empty, there is no reason to clean it.
    712 	 * Clear its error condition, if any, since we are never going to
    713 	 * try to parse this one.
    714 	 */
    715 	if (t->nbytes == 0) {
    716 		t->flags &= ~SEGUSE_ERROR; /* Strip error once empty */
    717 		t->priority = 0;
    718 		return;
    719 	}
    720 
    721 	if (t->flags & SEGUSE_ERROR) {	/* No good if not already empty */
    722 		/* No benefit */
    723 		t->priority = 0;
    724 		return;
    725 	}
    726 
    727 	if (t->nbytes > lfs_sb_getssize(fs)) {
    728 		/* Another type of error */
    729 		syslog(LOG_WARNING, "segment %d: bad seguse count %d",
    730 		       sn, t->nbytes);
    731 		t->flags |= SEGUSE_ERROR;
    732 		t->priority = 0;
    733 		return;
    734 	}
    735 
    736 	/*
    737 	 * The non-degenerate case.  Use Rosenblum's cost-benefit algorithm.
    738 	 * Calculate the benefit from cleaning this segment (one segment,
    739 	 * minus fragmentation, dirty blocks and a segment summary block)
    740 	 * and weigh that against the cost (bytes read plus bytes written).
    741 	 * We count the summary headers as "dirty" to avoid cleaning very
    742 	 * old and very full segments.
    743 	 */
    744 	benefit = (int64_t)lfs_sb_getssize(fs) - t->nbytes -
    745 		  (t->nsums + 1) * lfs_sb_getfsize(fs);
    746 	if (lfs_sb_getbsize(fs) > lfs_sb_getfsize(fs)) /* fragmentation */
    747 		benefit -= (lfs_sb_getbsize(fs) / 2);
    748 	if (benefit <= 0) {
    749 		t->priority = 0;
    750 		return;
    751 	}
    752 
    753 	cost = lfs_sb_getssize(fs) + t->nbytes;
    754 	t->priority = (256 * benefit * age) / cost;
    755 
    756 	return;
    757 }
    758 
    759 /*
    760  * Comparator for BLOCK_INFO structures.  Anything not in one of the segments
    761  * we're looking at sorts higher; after that we sort first by inode number
    762  * and then by block number (unsigned, i.e., negative sorts higher) *but*
    763  * sort inodes before data blocks.
    764  */
    765 static int
    766 bi_comparator(const void *va, const void *vb)
    767 {
    768 	const BLOCK_INFO *a, *b;
    769 
    770 	a = (const BLOCK_INFO *)va;
    771 	b = (const BLOCK_INFO *)vb;
    772 
    773 	/* Check for out-of-place block */
    774 	if (a->bi_segcreate == a->bi_daddr &&
    775 	    b->bi_segcreate != b->bi_daddr)
    776 		return -1;
    777 	if (a->bi_segcreate != a->bi_daddr &&
    778 	    b->bi_segcreate == b->bi_daddr)
    779 		return 1;
    780 	if (a->bi_size <= 0 && b->bi_size > 0)
    781 		return 1;
    782 	if (b->bi_size <= 0 && a->bi_size > 0)
    783 		return -1;
    784 
    785 	/* Check inode number */
    786 	if (a->bi_inode != b->bi_inode)
    787 		return a->bi_inode - b->bi_inode;
    788 
    789 	/* Check lbn */
    790 	if (a->bi_lbn == LFS_UNUSED_LBN) /* Inodes sort lower than blocks */
    791 		return -1;
    792 	if (b->bi_lbn == LFS_UNUSED_LBN)
    793 		return 1;
    794 	if ((u_int32_t)a->bi_lbn > (u_int32_t)b->bi_lbn)
    795 		return 1;
    796 	else
    797 		return -1;
    798 
    799 	return 0;
    800 }
    801 
    802 /*
    803  * Comparator for sort_segments: cost-benefit equation.
    804  */
    805 static int
    806 cb_comparator(const void *va, const void *vb)
    807 {
    808 	const struct clfs_seguse *a, *b;
    809 
    810 	a = *(const struct clfs_seguse * const *)va;
    811 	b = *(const struct clfs_seguse * const *)vb;
    812 	return a->priority > b->priority ? -1 : 1;
    813 }
    814 
    815 void
    816 toss_old_blocks(struct clfs *fs, BLOCK_INFO **bipp, int *bic, int *sizep)
    817 {
    818 	int i, r;
    819 	BLOCK_INFO *bip = *bipp;
    820 	struct lfs_fcntl_markv /* {
    821 		BLOCK_INFO *blkiov;
    822 		int blkcnt;
    823 	} */ lim;
    824 
    825 	if (bic == 0 || bip == NULL)
    826 		return;
    827 
    828 	/*
    829 	 * Kludge: Store the disk address in segcreate so we know which
    830 	 * ones to toss.
    831 	 */
    832 	for (i = 0; i < *bic; i++)
    833 		bip[i].bi_segcreate = bip[i].bi_daddr;
    834 
    835 	/* Sort the blocks */
    836 	heapsort(bip, *bic, sizeof(BLOCK_INFO), bi_comparator);
    837 
    838 	/* Use bmapv to locate the blocks */
    839 	lim.blkiov = bip;
    840 	lim.blkcnt = *bic;
    841 	if ((r = kops.ko_fcntl(fs->clfs_ifilefd, LFCNBMAPV, &lim)) < 0) {
    842 		syslog(LOG_WARNING, "%s: bmapv returned %d (%m)",
    843 		       lfs_sb_getfsmnt(fs), r);
    844 		return;
    845 	}
    846 
    847 	/* Toss blocks not in this segment */
    848 	heapsort(bip, *bic, sizeof(BLOCK_INFO), bi_comparator);
    849 
    850 	/* Get rid of stale blocks */
    851 	if (sizep)
    852 		*sizep = 0;
    853 	for (i = 0; i < *bic; i++) {
    854 		if (bip[i].bi_segcreate != bip[i].bi_daddr)
    855 			break;
    856 		if (sizep)
    857 			*sizep += bip[i].bi_size;
    858 	}
    859 	*bic = i; /* XXX should we shrink bip? */
    860 	*bipp = bip;
    861 
    862 	return;
    863 }
    864 
    865 /*
    866  * Clean a segment and mark it invalid.
    867  */
    868 int
    869 invalidate_segment(struct clfs *fs, int sn)
    870 {
    871 	BLOCK_INFO *bip;
    872 	int i, r, bic;
    873 	off_t nb;
    874 	double util;
    875 	struct lfs_fcntl_markv /* {
    876 		BLOCK_INFO *blkiov;
    877 		int blkcnt;
    878 	} */ lim;
    879 
    880 	dlog("%s: inval seg %d", lfs_sb_getfsmnt(fs), sn);
    881 
    882 	bip = NULL;
    883 	bic = 0;
    884 	fs->clfs_nactive = 0;
    885 	if (load_segment(fs, sn, &bip, &bic) <= 0)
    886 		return -1;
    887 	toss_old_blocks(fs, &bip, &bic, NULL);
    888 
    889 	/* Record statistics */
    890 	for (i = nb = 0; i < bic; i++)
    891 		nb += bip[i].bi_size;
    892 	util = ((double)nb) / (fs->clfs_nactive * lfs_sb_getssize(fs));
    893 	cleaner_stats.util_tot += util;
    894 	cleaner_stats.util_sos += util * util;
    895 	cleaner_stats.bytes_written += nb;
    896 
    897 	/*
    898 	 * Use markv to move the blocks.
    899 	 */
    900 	lim.blkiov = bip;
    901 	lim.blkcnt = bic;
    902 	if ((r = kops.ko_fcntl(fs->clfs_ifilefd, LFCNMARKV, &lim)) < 0) {
    903 		syslog(LOG_WARNING, "%s: markv returned %d (%m) "
    904 		       "for seg %d", lfs_sb_getfsmnt(fs), r, sn);
    905 		return r;
    906 	}
    907 
    908 	/*
    909 	 * Finally call invalidate to invalidate the segment.
    910 	 */
    911 	if ((r = kops.ko_fcntl(fs->clfs_ifilefd, LFCNINVAL, &sn)) < 0) {
    912 		syslog(LOG_WARNING, "%s: inval returned %d (%m) "
    913 		       "for seg %d", lfs_sb_getfsmnt(fs), r, sn);
    914 		return r;
    915 	}
    916 
    917 	return 0;
    918 }
    919 
    920 /*
    921  * Check to see if the given ino/lbn pair is represented in the BLOCK_INFO
    922  * array we are sending to the kernel, or if the kernel will have to add it.
    923  * The kernel will only add each such pair once, though, so keep track of
    924  * previous requests in a separate "extra" BLOCK_INFO array.  Returns 1
    925  * if the block needs to be added, 0 if it is already represented.
    926  */
    927 static int
    928 check_or_add(ino_t ino, int32_t lbn, BLOCK_INFO *bip, int bic, BLOCK_INFO **ebipp, int *ebicp)
    929 {
    930 	BLOCK_INFO *t, *ebip = *ebipp;
    931 	int ebic = *ebicp;
    932 	int k;
    933 
    934 	for (k = 0; k < bic; k++) {
    935 		if (bip[k].bi_inode != ino)
    936 			break;
    937 		if (bip[k].bi_lbn == lbn) {
    938 			return 0;
    939 		}
    940 	}
    941 
    942 	/* Look on the list of extra blocks, too */
    943 	for (k = 0; k < ebic; k++) {
    944 		if (ebip[k].bi_inode == ino && ebip[k].bi_lbn == lbn) {
    945 			return 0;
    946 		}
    947 	}
    948 
    949 	++ebic;
    950 	t = realloc(ebip, ebic * sizeof(BLOCK_INFO));
    951 	if (t == NULL)
    952 		return 1; /* Note *ebicp is unchanged */
    953 
    954 	ebip = t;
    955 	ebip[ebic - 1].bi_inode = ino;
    956 	ebip[ebic - 1].bi_lbn = lbn;
    957 
    958 	*ebipp = ebip;
    959 	*ebicp = ebic;
    960 	return 1;
    961 }
    962 
    963 /*
    964  * Look for indirect blocks we will have to write which are not
    965  * contained in this collection of blocks.  This constitutes
    966  * a hidden cleaning cost, since we are unaware of it until we
    967  * have already read the segments.  Return the total cost, and fill
    968  * in *ifc with the part of that cost due to rewriting the Ifile.
    969  */
    970 static off_t
    971 check_hidden_cost(struct clfs *fs, BLOCK_INFO *bip, int bic, off_t *ifc)
    972 {
    973 	int start;
    974 	struct indir in[ULFS_NIADDR + 1];
    975 	int num;
    976 	int i, j, ebic;
    977 	BLOCK_INFO *ebip;
    978 	int32_t lbn;
    979 
    980 	start = 0;
    981 	ebip = NULL;
    982 	ebic = 0;
    983 	for (i = 0; i < bic; i++) {
    984 		if (i == 0 || bip[i].bi_inode != bip[start].bi_inode) {
    985 			start = i;
    986 			/*
    987 			 * Look for IFILE blocks, unless this is the Ifile.
    988 			 */
    989 			if (bip[i].bi_inode != lfs_sb_getifile(fs)) {
    990 				lbn = lfs_sb_getcleansz(fs) + bip[i].bi_inode /
    991 							lfs_sb_getifpb(fs);
    992 				*ifc += check_or_add(lfs_sb_getifile(fs), lbn,
    993 						     bip, bic, &ebip, &ebic);
    994 			}
    995 		}
    996 		if (bip[i].bi_lbn == LFS_UNUSED_LBN)
    997 			continue;
    998 		if (bip[i].bi_lbn < ULFS_NDADDR)
    999 			continue;
   1000 
   1001 		ulfs_getlbns((struct lfs *)fs, NULL, (daddr_t)bip[i].bi_lbn, in, &num);
   1002 		for (j = 0; j < num; j++) {
   1003 			check_or_add(bip[i].bi_inode, in[j].in_lbn,
   1004 				     bip + start, bic - start, &ebip, &ebic);
   1005 		}
   1006 	}
   1007 	return ebic;
   1008 }
   1009 
   1010 /*
   1011  * Select segments to clean, add blocks from these segments to a cleaning
   1012  * list, and send this list through lfs_markv() to move them to new
   1013  * locations on disk.
   1014  */
   1015 int
   1016 clean_fs(struct clfs *fs, CLEANERINFO *cip)
   1017 {
   1018 	int i, j, ngood, sn, bic, r, npos;
   1019 	int bytes, totbytes;
   1020 	struct ubuf *bp;
   1021 	SEGUSE *sup;
   1022 	static BLOCK_INFO *bip;
   1023 	struct lfs_fcntl_markv /* {
   1024 		BLOCK_INFO *blkiov;
   1025 		int blkcnt;
   1026 	} */ lim;
   1027 	int mc;
   1028 	BLOCK_INFO *mbip;
   1029 	int inc;
   1030 	off_t nb;
   1031 	off_t goal;
   1032 	off_t extra, if_extra;
   1033 	double util;
   1034 
   1035 	/* Read the segment table into our private structure */
   1036 	npos = 0;
   1037 	for (i = 0; i < lfs_sb_getnseg(fs); i+= lfs_sb_getsepb(fs)) {
   1038 		bread(fs->lfs_ivnode,
   1039 		      lfs_sb_getcleansz(fs) + i / lfs_sb_getsepb(fs),
   1040 		      lfs_sb_getbsize(fs), 0, &bp);
   1041 		for (j = 0; j < lfs_sb_getsepb(fs) && i + j < lfs_sb_getnseg(fs); j++) {
   1042 			sup = ((SEGUSE *)bp->b_data) + j;
   1043 			fs->clfs_segtab[i + j].nbytes  = sup->su_nbytes;
   1044 			fs->clfs_segtab[i + j].nsums = sup->su_nsums;
   1045 			fs->clfs_segtab[i + j].lastmod = sup->su_lastmod;
   1046 			/* Keep error status but renew other flags */
   1047 			fs->clfs_segtab[i + j].flags  &= SEGUSE_ERROR;
   1048 			fs->clfs_segtab[i + j].flags  |= sup->su_flags;
   1049 
   1050 			/* Compute cost-benefit coefficient */
   1051 			calc_cb(fs, i + j, fs->clfs_segtab + i + j);
   1052 			if (fs->clfs_segtab[i + j].priority > 0)
   1053 				++npos;
   1054 		}
   1055 		brelse(bp, 0);
   1056 	}
   1057 
   1058 	/* Sort segments based on cleanliness, fulness, and condition */
   1059 	heapsort(fs->clfs_segtabp, lfs_sb_getnseg(fs), sizeof(struct clfs_seguse *),
   1060 		 cb_comparator);
   1061 
   1062 	/* If no segment is cleanable, just return */
   1063 	if (fs->clfs_segtabp[0]->priority == 0) {
   1064 		dlog("%s: no segment cleanable", lfs_sb_getfsmnt(fs));
   1065 		return 0;
   1066 	}
   1067 
   1068 	/* Load some segments' blocks into bip */
   1069 	bic = 0;
   1070 	fs->clfs_nactive = 0;
   1071 	ngood = 0;
   1072 	if (use_bytes) {
   1073 		/* Set attainable goal */
   1074 		goal = lfs_sb_getssize(fs) * atatime;
   1075 		if (goal > (cip->clean - 1) * lfs_sb_getssize(fs) / 2)
   1076 			goal = MAX((cip->clean - 1) * lfs_sb_getssize(fs),
   1077 				   lfs_sb_getssize(fs)) / 2;
   1078 
   1079 		dlog("%s: cleaning with goal %" PRId64
   1080 		     " bytes (%d segs clean, %d cleanable)",
   1081 		     lfs_sb_getfsmnt(fs), goal, cip->clean, npos);
   1082 		syslog(LOG_INFO, "%s: cleaning with goal %" PRId64
   1083 		       " bytes (%d segs clean, %d cleanable)",
   1084 		       lfs_sb_getfsmnt(fs), goal, cip->clean, npos);
   1085 		totbytes = 0;
   1086 		for (i = 0; i < lfs_sb_getnseg(fs) && totbytes < goal; i++) {
   1087 			if (fs->clfs_segtabp[i]->priority == 0)
   1088 				break;
   1089 			/* Upper bound on number of segments at once */
   1090 			if (ngood * lfs_sb_getssize(fs) > 4 * goal)
   1091 				break;
   1092 			sn = (fs->clfs_segtabp[i] - fs->clfs_segtab);
   1093 			dlog("%s: add seg %d prio %" PRIu64
   1094 			     " containing %ld bytes",
   1095 			     lfs_sb_getfsmnt(fs), sn, fs->clfs_segtabp[i]->priority,
   1096 			     fs->clfs_segtabp[i]->nbytes);
   1097 			if ((r = load_segment(fs, sn, &bip, &bic)) > 0) {
   1098 				++ngood;
   1099 				toss_old_blocks(fs, &bip, &bic, &bytes);
   1100 				totbytes += bytes;
   1101 			} else if (r == 0)
   1102 				fd_release(fs->clfs_devvp);
   1103 			else
   1104 				break;
   1105 		}
   1106 	} else {
   1107 		/* Set attainable goal */
   1108 		goal = atatime;
   1109 		if (goal > cip->clean - 1)
   1110 			goal = MAX(cip->clean - 1, 1);
   1111 
   1112 		dlog("%s: cleaning with goal %d segments (%d clean, %d cleanable)",
   1113 		       lfs_sb_getfsmnt(fs), (int)goal, cip->clean, npos);
   1114 		for (i = 0; i < lfs_sb_getnseg(fs) && ngood < goal; i++) {
   1115 			if (fs->clfs_segtabp[i]->priority == 0)
   1116 				break;
   1117 			sn = (fs->clfs_segtabp[i] - fs->clfs_segtab);
   1118 			dlog("%s: add seg %d prio %" PRIu64,
   1119 			     lfs_sb_getfsmnt(fs), sn, fs->clfs_segtabp[i]->priority);
   1120 			if ((r = load_segment(fs, sn, &bip, &bic)) > 0)
   1121 				++ngood;
   1122 			else if (r == 0)
   1123 				fd_release(fs->clfs_devvp);
   1124 			else
   1125 				break;
   1126 		}
   1127 		toss_old_blocks(fs, &bip, &bic, NULL);
   1128 	}
   1129 
   1130 	/* If there is nothing to do, try again later. */
   1131 	if (bic == 0) {
   1132 		dlog("%s: no blocks to clean in %d cleanable segments",
   1133 		       lfs_sb_getfsmnt(fs), (int)ngood);
   1134 		fd_release_all(fs->clfs_devvp);
   1135 		return 0;
   1136 	}
   1137 
   1138 	/* Record statistics */
   1139 	for (i = nb = 0; i < bic; i++)
   1140 		nb += bip[i].bi_size;
   1141 	util = ((double)nb) / (fs->clfs_nactive * lfs_sb_getssize(fs));
   1142 	cleaner_stats.util_tot += util;
   1143 	cleaner_stats.util_sos += util * util;
   1144 	cleaner_stats.bytes_written += nb;
   1145 
   1146 	/*
   1147 	 * Check out our blocks to see if there are hidden cleaning costs.
   1148 	 * If there are, we might be cleaning ourselves deeper into a hole
   1149 	 * rather than doing anything useful.
   1150 	 * XXX do something about this.
   1151 	 */
   1152 	if_extra = 0;
   1153 	extra = lfs_sb_getbsize(fs) * (off_t)check_hidden_cost(fs, bip, bic, &if_extra);
   1154 	if_extra *= lfs_sb_getbsize(fs);
   1155 
   1156 	/*
   1157 	 * Use markv to move the blocks.
   1158 	 */
   1159 	if (do_small)
   1160 		inc = MAXPHYS / lfs_sb_getbsize(fs) - 1;
   1161 	else
   1162 		inc = LFS_MARKV_MAXBLKCNT / 2;
   1163 	for (mc = 0, mbip = bip; mc < bic; mc += inc, mbip += inc) {
   1164 		lim.blkiov = mbip;
   1165 		lim.blkcnt = (bic - mc > inc ? inc : bic - mc);
   1166 #ifdef TEST_PATTERN
   1167 		dlog("checking blocks %d-%d", mc, mc + lim.blkcnt - 1);
   1168 		for (i = 0; i < lim.blkcnt; i++) {
   1169 			check_test_pattern(mbip + i);
   1170 		}
   1171 #endif /* TEST_PATTERN */
   1172 		dlog("sending blocks %d-%d", mc, mc + lim.blkcnt - 1);
   1173 		if ((r = kops.ko_fcntl(fs->clfs_ifilefd, LFCNMARKV, &lim))<0) {
   1174 			int oerrno = errno;
   1175 			syslog(LOG_WARNING, "%s: markv returned %d (errno %d, %m)",
   1176 			       lfs_sb_getfsmnt(fs), r, errno);
   1177 			if (oerrno != EAGAIN && oerrno != ESHUTDOWN) {
   1178 				syslog(LOG_DEBUG, "%s: errno %d, returning",
   1179 				       lfs_sb_getfsmnt(fs), oerrno);
   1180 				fd_release_all(fs->clfs_devvp);
   1181 				return r;
   1182 			}
   1183 			if (oerrno == ESHUTDOWN) {
   1184 				syslog(LOG_NOTICE, "%s: filesystem unmounted",
   1185 				       lfs_sb_getfsmnt(fs));
   1186 				fd_release_all(fs->clfs_devvp);
   1187 				return r;
   1188 			}
   1189 		}
   1190 	}
   1191 
   1192 	/*
   1193 	 * Report progress (or lack thereof)
   1194 	 */
   1195 	syslog(LOG_INFO, "%s: wrote %" PRId64 " dirty + %"
   1196 	       PRId64 " supporting indirect + %"
   1197 	       PRId64 " supporting Ifile = %"
   1198 	       PRId64 " bytes to clean %d segs (%" PRId64 "%% recovery)",
   1199 	       lfs_sb_getfsmnt(fs), (int64_t)nb, (int64_t)(extra - if_extra),
   1200 	       (int64_t)if_extra, (int64_t)(nb + extra), ngood,
   1201 	       (ngood ? (int64_t)(100 - (100 * (nb + extra)) /
   1202 					 (ngood * lfs_sb_getssize(fs))) :
   1203 		(int64_t)0));
   1204 	if (nb + extra >= ngood * lfs_sb_getssize(fs))
   1205 		syslog(LOG_WARNING, "%s: cleaner not making forward progress",
   1206 		       lfs_sb_getfsmnt(fs));
   1207 
   1208 	/*
   1209 	 * Finally call reclaim to prompt cleaning of the segments.
   1210 	 */
   1211 	kops.ko_fcntl(fs->clfs_ifilefd, LFCNRECLAIM, NULL);
   1212 
   1213 	fd_release_all(fs->clfs_devvp);
   1214 	return 0;
   1215 }
   1216 
   1217 /*
   1218  * Read the cleanerinfo block and apply cleaning policy to determine whether
   1219  * the given filesystem needs to be cleaned.  Returns 1 if it does, 0 if it
   1220  * does not, or -1 on error.
   1221  */
   1222 int
   1223 needs_cleaning(struct clfs *fs, CLEANERINFO *cip)
   1224 {
   1225 	struct ubuf *bp;
   1226 	struct stat st;
   1227 	daddr_t fsb_per_seg, max_free_segs;
   1228 	time_t now;
   1229 	double loadavg;
   1230 
   1231 	/* If this fs is "on hold", don't clean it. */
   1232 	if (fs->clfs_onhold)
   1233 		return 0;
   1234 
   1235 	/*
   1236 	 * Read the cleanerinfo block from the Ifile.  We don't want
   1237 	 * the cached information, so invalidate the buffer before
   1238 	 * handing it back.
   1239 	 */
   1240 	if (bread(fs->lfs_ivnode, 0, lfs_sb_getbsize(fs), 0, &bp)) {
   1241 		syslog(LOG_ERR, "%s: can't read inode", lfs_sb_getfsmnt(fs));
   1242 		return -1;
   1243 	}
   1244 	*cip = *(CLEANERINFO *)bp->b_data; /* Structure copy */
   1245 	brelse(bp, B_INVAL);
   1246 	cleaner_stats.bytes_read += lfs_sb_getbsize(fs);
   1247 
   1248 	/*
   1249 	 * If the number of segments changed under us, reinit.
   1250 	 * We don't have to start over from scratch, however,
   1251 	 * since we don't hold any buffers.
   1252 	 */
   1253 	if (lfs_sb_getnseg(fs) != cip->clean + cip->dirty) {
   1254 		if (reinit_fs(fs) < 0) {
   1255 			/* The normal case for unmount */
   1256 			syslog(LOG_NOTICE, "%s: filesystem unmounted", lfs_sb_getfsmnt(fs));
   1257 			return -1;
   1258 		}
   1259 		syslog(LOG_NOTICE, "%s: nsegs changed", lfs_sb_getfsmnt(fs));
   1260 	}
   1261 
   1262 	/* Compute theoretical "free segments" maximum based on usage */
   1263 	fsb_per_seg = lfs_segtod(fs, 1);
   1264 	max_free_segs = MAX(cip->bfree, 0) / fsb_per_seg + lfs_sb_getminfreeseg(fs);
   1265 
   1266 	dlog("%s: bfree = %d, avail = %d, clean = %d/%d",
   1267 	     lfs_sb_getfsmnt(fs), cip->bfree, cip->avail, cip->clean,
   1268 	     lfs_sb_getnseg(fs));
   1269 
   1270 	/* If the writer is waiting on us, clean it */
   1271 	if (cip->clean <= lfs_sb_getminfreeseg(fs) ||
   1272 	    (cip->flags & LFS_CLEANER_MUST_CLEAN))
   1273 		return 1;
   1274 
   1275 	/* If there are enough segments, don't clean it */
   1276 	if (cip->bfree - cip->avail <= fsb_per_seg &&
   1277 	    cip->avail > fsb_per_seg)
   1278 		return 0;
   1279 
   1280 	/* If we are in dire straits, clean it */
   1281 	if (cip->bfree - cip->avail > fsb_per_seg &&
   1282 	    cip->avail <= fsb_per_seg)
   1283 		return 1;
   1284 
   1285 	/* If under busy threshold, clean regardless of load */
   1286 	if (cip->clean < max_free_segs * BUSY_LIM)
   1287 		return 1;
   1288 
   1289 	/* Check busy status; clean if idle and under idle limit */
   1290 	if (use_fs_idle) {
   1291 		/* Filesystem idle */
   1292 		time(&now);
   1293 		if (fstat(fs->clfs_ifilefd, &st) < 0) {
   1294 			syslog(LOG_ERR, "%s: failed to stat ifile",
   1295 			       lfs_sb_getfsmnt(fs));
   1296 			return -1;
   1297 		}
   1298 		if (now - st.st_mtime > segwait_timeout &&
   1299 		    cip->clean < max_free_segs * IDLE_LIM)
   1300 			return 1;
   1301 	} else {
   1302 		/* CPU idle - use one-minute load avg */
   1303 		if (getloadavg(&loadavg, 1) == -1) {
   1304 			syslog(LOG_ERR, "%s: failed to get load avg",
   1305 			       lfs_sb_getfsmnt(fs));
   1306 			return -1;
   1307 		}
   1308 		if (loadavg < load_threshold &&
   1309 		    cip->clean < max_free_segs * IDLE_LIM)
   1310 			return 1;
   1311 	}
   1312 
   1313 	return 0;
   1314 }
   1315 
   1316 /*
   1317  * Report statistics.  If the signal was SIGUSR2, clear the statistics too.
   1318  * If the signal was SIGINT, exit.
   1319  */
   1320 static void
   1321 sig_report(int sig)
   1322 {
   1323 	double avg = 0.0, stddev;
   1324 
   1325 	avg = cleaner_stats.util_tot / MAX(cleaner_stats.segs_cleaned, 1.0);
   1326 	stddev = cleaner_stats.util_sos / MAX(cleaner_stats.segs_cleaned -
   1327 					      avg * avg, 1.0);
   1328 	syslog(LOG_INFO, "bytes read:	     %" PRId64, cleaner_stats.bytes_read);
   1329 	syslog(LOG_INFO, "bytes written:     %" PRId64, cleaner_stats.bytes_written);
   1330 	syslog(LOG_INFO, "segments cleaned:  %" PRId64, cleaner_stats.segs_cleaned);
   1331 #if 0
   1332 	/* "Empty segments" is meaningless, since the kernel handles those */
   1333 	syslog(LOG_INFO, "empty segments:    %" PRId64, cleaner_stats.segs_empty);
   1334 #endif
   1335 	syslog(LOG_INFO, "error segments:    %" PRId64, cleaner_stats.segs_error);
   1336 	syslog(LOG_INFO, "utilization total: %g", cleaner_stats.util_tot);
   1337 	syslog(LOG_INFO, "utilization sos:   %g", cleaner_stats.util_sos);
   1338 	syslog(LOG_INFO, "utilization avg:   %4.2f", avg);
   1339 	syslog(LOG_INFO, "utilization sdev:  %9.6f", stddev);
   1340 
   1341 	if (debug)
   1342 		bufstats();
   1343 
   1344 	if (sig == SIGUSR2)
   1345 		memset(&cleaner_stats, 0, sizeof(cleaner_stats));
   1346 	if (sig == SIGINT)
   1347 		exit(0);
   1348 }
   1349 
   1350 static void
   1351 sig_exit(int sig)
   1352 {
   1353 	exit(0);
   1354 }
   1355 
   1356 static void
   1357 usage(void)
   1358 {
   1359 	errx(1, "usage: lfs_cleanerd [-bcdfmqs] [-i segnum] [-l load] "
   1360 	     "[-n nsegs] [-r report_freq] [-t timeout] fs_name ...");
   1361 }
   1362 
   1363 #ifndef LFS_CLEANER_AS_LIB
   1364 /*
   1365  * Main.
   1366  */
   1367 int
   1368 main(int argc, char **argv)
   1369 {
   1370 
   1371 	return lfs_cleaner_main(argc, argv);
   1372 }
   1373 #endif
   1374 
   1375 int
   1376 lfs_cleaner_main(int argc, char **argv)
   1377 {
   1378 	int i, opt, error, r, loopcount, nodetach;
   1379 	struct timeval tv;
   1380 #ifdef LFS_CLEANER_AS_LIB
   1381 	sem_t *semaddr = NULL;
   1382 #endif
   1383 	CLEANERINFO ci;
   1384 #ifndef USE_CLIENT_SERVER
   1385 	char *cp, *pidname;
   1386 #endif
   1387 
   1388 	/*
   1389 	 * Set up defaults
   1390 	 */
   1391 	atatime	 = 1;
   1392 	segwait_timeout = 300; /* Five minutes */
   1393 	load_threshold	= 0.2;
   1394 	stat_report	= 0;
   1395 	inval_segment	= -1;
   1396 	copylog_filename = NULL;
   1397 	nodetach        = 0;
   1398 
   1399 	/*
   1400 	 * Parse command-line arguments
   1401 	 */
   1402 	while ((opt = getopt(argc, argv, "bC:cdDfi:l:mn:qr:sS:t:")) != -1) {
   1403 		switch (opt) {
   1404 		    case 'b':	/* Use bytes written, not segments read */
   1405 			    use_bytes = 1;
   1406 			    break;
   1407 		    case 'C':	/* copy log */
   1408 			    copylog_filename = optarg;
   1409 			    break;
   1410 		    case 'c':	/* Coalesce files */
   1411 			    do_coalesce++;
   1412 			    break;
   1413 		    case 'd':	/* Debug mode. */
   1414 			    nodetach++;
   1415 			    debug++;
   1416 			    break;
   1417 		    case 'D':	/* stay-on-foreground */
   1418 			    nodetach++;
   1419 			    break;
   1420 		    case 'f':	/* Use fs idle time rather than cpu idle */
   1421 			    use_fs_idle = 1;
   1422 			    break;
   1423 		    case 'i':	/* Invalidate this segment */
   1424 			    inval_segment = atoi(optarg);
   1425 			    break;
   1426 		    case 'l':	/* Load below which to clean */
   1427 			    load_threshold = atof(optarg);
   1428 			    break;
   1429 		    case 'm':	/* [compat only] */
   1430 			    break;
   1431 		    case 'n':	/* How many segs to clean at once */
   1432 			    atatime = atoi(optarg);
   1433 			    break;
   1434 		    case 'q':	/* Quit after one run */
   1435 			    do_quit = 1;
   1436 			    break;
   1437 		    case 'r':	/* Report every stat_report segments */
   1438 			    stat_report = atoi(optarg);
   1439 			    break;
   1440 		    case 's':	/* Small writes */
   1441 			    do_small = 1;
   1442 			    break;
   1443 #ifdef LFS_CLEANER_AS_LIB
   1444 		    case 'S':	/* semaphore */
   1445 			    semaddr = (void*)(uintptr_t)strtoull(optarg,NULL,0);
   1446 			    break;
   1447 #endif
   1448 		    case 't':	/* timeout */
   1449 			    segwait_timeout = atoi(optarg);
   1450 			    break;
   1451 		    default:
   1452 			    usage();
   1453 			    /* NOTREACHED */
   1454 		}
   1455 	}
   1456 	argc -= optind;
   1457 	argv += optind;
   1458 
   1459 	if (argc < 1)
   1460 		usage();
   1461 	if (inval_segment >= 0 && argc != 1) {
   1462 		errx(1, "lfs_cleanerd: may only specify one filesystem when "
   1463 		     "using -i flag");
   1464 	}
   1465 
   1466 	if (do_coalesce) {
   1467 		errx(1, "lfs_cleanerd: -c disabled due to reports of file "
   1468 		     "corruption; you may re-enable it by rebuilding the "
   1469 		     "cleaner");
   1470 	}
   1471 
   1472 	/*
   1473 	 * Set up daemon mode or foreground mode
   1474 	 */
   1475 	if (nodetach) {
   1476 		openlog("lfs_cleanerd", LOG_NDELAY | LOG_PID | LOG_PERROR,
   1477 			LOG_DAEMON);
   1478 		signal(SIGINT, sig_report);
   1479 	} else {
   1480 		if (daemon(0, 0) == -1)
   1481 			err(1, "lfs_cleanerd: couldn't become a daemon!");
   1482 		openlog("lfs_cleanerd", LOG_NDELAY | LOG_PID, LOG_DAEMON);
   1483 		signal(SIGINT, sig_exit);
   1484 	}
   1485 
   1486 	/*
   1487 	 * Look for an already-running master daemon.  If there is one,
   1488 	 * send it our filesystems to add to its list and exit.
   1489 	 * If there is none, become the master.
   1490 	 */
   1491 #ifdef USE_CLIENT_SERVER
   1492 	try_to_become_master(argc, argv);
   1493 #else
   1494 	/* XXX think about this */
   1495 	asprintf(&pidname, "lfs_cleanerd:m:%s", argv[0]);
   1496 	if (pidname == NULL) {
   1497 		syslog(LOG_ERR, "malloc failed: %m");
   1498 		exit(1);
   1499 	}
   1500 	for (cp = pidname; cp != NULL; cp = strchr(cp, '/'))
   1501 		*cp = '|';
   1502 	pidfile(pidname);
   1503 #endif
   1504 
   1505 	/*
   1506 	 * Signals mean daemon should report its statistics
   1507 	 */
   1508 	memset(&cleaner_stats, 0, sizeof(cleaner_stats));
   1509 	signal(SIGUSR1, sig_report);
   1510 	signal(SIGUSR2, sig_report);
   1511 
   1512 	/*
   1513 	 * Start up buffer cache.  We only use this for the Ifile,
   1514 	 * and we will resize it if necessary, so it can start small.
   1515 	 */
   1516 	bufinit(4);
   1517 
   1518 #ifdef REPAIR_ZERO_FINFO
   1519 	{
   1520 		BLOCK_INFO *bip = NULL;
   1521 		int bic = 0;
   1522 
   1523 		nfss = 1;
   1524 		fsp = (struct clfs **)malloc(sizeof(*fsp));
   1525 		fsp[0] = (struct clfs *)calloc(1, sizeof(**fsp));
   1526 
   1527 		if (init_unmounted_fs(fsp[0], argv[0]) < 0) {
   1528 			err(1, "init_unmounted_fs");
   1529 		}
   1530 		dlog("Filesystem has %d segments", fsp[0]->lfs_nseg);
   1531 		for (i = 0; i < fsp[0]->lfs_nseg; i++) {
   1532 			load_segment(fsp[0], i, &bip, &bic);
   1533 			bic = 0;
   1534 		}
   1535 		exit(0);
   1536 	}
   1537 #endif
   1538 
   1539 	/*
   1540 	 * Initialize cleaning structures, open devices, etc.
   1541 	 */
   1542 	nfss = argc;
   1543 	fsp = (struct clfs **)malloc(nfss * sizeof(*fsp));
   1544 	if (fsp == NULL) {
   1545 		syslog(LOG_ERR, "couldn't allocate fs table: %m");
   1546 		exit(1);
   1547 	}
   1548 	for (i = 0; i < nfss; i++) {
   1549 		fsp[i] = (struct clfs *)calloc(1, sizeof(**fsp));
   1550 		if ((r = init_fs(fsp[i], argv[i])) < 0) {
   1551 			syslog(LOG_ERR, "%s: couldn't init: error code %d",
   1552 			       argv[i], r);
   1553 			handle_error(fsp, i);
   1554 			--i; /* Do the new #i over again */
   1555 		}
   1556 	}
   1557 
   1558 	/*
   1559 	 * If asked to coalesce, do so and exit.
   1560 	 */
   1561 	if (do_coalesce) {
   1562 		for (i = 0; i < nfss; i++)
   1563 			clean_all_inodes(fsp[i]);
   1564 		exit(0);
   1565 	}
   1566 
   1567 	/*
   1568 	 * If asked to invalidate a segment, do that and exit.
   1569 	 */
   1570 	if (inval_segment >= 0) {
   1571 		invalidate_segment(fsp[0], inval_segment);
   1572 		exit(0);
   1573 	}
   1574 
   1575 	/*
   1576 	 * Main cleaning loop.
   1577 	 */
   1578 	loopcount = 0;
   1579 #ifdef LFS_CLEANER_AS_LIB
   1580 	if (semaddr)
   1581 		sem_post(semaddr);
   1582 #endif
   1583 	error = 0;
   1584 	while (nfss > 0) {
   1585 		int cleaned_one;
   1586 		do {
   1587 #ifdef USE_CLIENT_SERVER
   1588 			check_control_socket();
   1589 #endif
   1590 			cleaned_one = 0;
   1591 			for (i = 0; i < nfss; i++) {
   1592 				if ((error = needs_cleaning(fsp[i], &ci)) < 0) {
   1593 					syslog(LOG_DEBUG, "%s: needs_cleaning returned %d",
   1594 					       getprogname(), error);
   1595 					handle_error(fsp, i);
   1596 					continue;
   1597 				}
   1598 				if (error == 0) /* No need to clean */
   1599 					continue;
   1600 
   1601 				reload_ifile(fsp[i]);
   1602 				if ((error = clean_fs(fsp[i], &ci)) < 0) {
   1603 					syslog(LOG_DEBUG, "%s: clean_fs returned %d",
   1604 					       getprogname(), error);
   1605 					handle_error(fsp, i);
   1606 					continue;
   1607 				}
   1608 				++cleaned_one;
   1609 			}
   1610 			++loopcount;
   1611 			if (stat_report && loopcount % stat_report == 0)
   1612 				sig_report(0);
   1613 			if (do_quit)
   1614 				exit(0);
   1615 		} while(cleaned_one);
   1616 		tv.tv_sec = segwait_timeout;
   1617 		tv.tv_usec = 0;
   1618 		/* XXX: why couldn't others work if fsp socket is shutdown? */
   1619 		error = kops.ko_fcntl(fsp[0]->clfs_ifilefd,LFCNSEGWAITALL,&tv);
   1620 		if (error) {
   1621 			if (errno == ESHUTDOWN) {
   1622 				for (i = 0; i < nfss; i++) {
   1623 					syslog(LOG_INFO, "%s: shutdown",
   1624 					       getprogname());
   1625 					handle_error(fsp, i);
   1626 					assert(nfss == 0);
   1627 				}
   1628 			} else {
   1629 #ifdef LFS_CLEANER_AS_LIB
   1630 				error = ESHUTDOWN;
   1631 				break;
   1632 #else
   1633 				err(1, "LFCNSEGWAITALL");
   1634 #endif
   1635 			}
   1636 		}
   1637 	}
   1638 
   1639 	/* NOTREACHED */
   1640 	return error;
   1641 }
   1642