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