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