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