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