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