Sync usage with man page.
[netbsd-mini2440.git] / libexec / lfs_cleanerd / lfs_cleanerd.c
blobba34bda9da80382dc278c02d2f42e86a14065a70
1 /* $NetBSD: lfs_cleanerd.c,v 1.21 2009/08/06 00:51:55 pooka Exp $ */
3 /*-
4 * Copyright (c) 2005 The NetBSD Foundation, Inc.
5 * All rights reserved.
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Konrad E. Schroder <perseant@hhhh.org>.
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.
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.
33 * The cleaner daemon for the NetBSD Log-structured File System.
34 * Only tested for use with version 2 LFSs.
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>
44 #include <assert.h>
45 #include <err.h>
46 #include <errno.h>
47 #include <fcntl.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>
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"
64 * Global variables.
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 int load_threshold; /* How idle is idle (CPU idle) */
70 int atatime; /* How many segments (bytes) to clean at a time */
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;
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 ufs_getlbns(struct lfs *, struct uvnode *, daddr_t, struct indir *, int *);
97 /* Compat */
98 void pwarn(const char *unused, ...) { /* Does nothing */ };
101 * Log a message if debugging is turned on.
103 void
104 dlog(const char *fmt, ...)
106 va_list ap;
108 if (debug == 0)
109 return;
111 va_start(ap, fmt);
112 vsyslog(LOG_DEBUG, fmt, ap);
113 va_end(ap);
117 * Remove the specified filesystem from the list, due to its having
118 * become unmounted or other error condition.
120 void
121 handle_error(struct clfs **cfsp, int n)
123 syslog(LOG_NOTICE, "%s: detaching cleaner", cfsp[n]->lfs_fsmnt);
124 free(cfsp[n]);
125 if (n != nfss - 1)
126 cfsp[n] = cfsp[nfss - 1];
127 --nfss;
131 * Reinitialize a filesystem if, e.g., its size changed.
134 reinit_fs(struct clfs *fs)
136 char fsname[MNAMELEN];
138 strncpy(fsname, (char *)fs->lfs_fsmnt, MNAMELEN);
139 kops.ko_close(fs->clfs_ifilefd);
140 kops.ko_close(fs->clfs_devfd);
141 fd_reclaim(fs->clfs_devvp);
142 fd_reclaim(fs->lfs_ivnode);
143 free(fs->clfs_dev);
144 free(fs->clfs_segtab);
145 free(fs->clfs_segtabp);
147 return init_fs(fs, fsname);
150 #ifdef REPAIR_ZERO_FINFO
152 * Use fsck's lfs routines to load the Ifile from an unmounted fs.
153 * We interpret "fsname" as the name of the raw disk device.
156 init_unmounted_fs(struct clfs *fs, char *fsname)
158 struct lfs *disc_fs;
159 int i;
161 fs->clfs_dev = fsname;
162 if ((fs->clfs_devfd = kops.ko_open(fs->clfs_dev, O_RDWR)) < 0) {
163 syslog(LOG_ERR, "couldn't open device %s read/write",
164 fs->clfs_dev);
165 return -1;
168 disc_fs = lfs_init(fs->clfs_devfd, 0, 0, 0, 0);
170 fs->lfs_dlfs = disc_fs->lfs_dlfs; /* Structure copy */
171 strncpy(fs->lfs_fsmnt, fsname, MNAMELEN);
172 fs->lfs_ivnode = (struct uvnode *)disc_fs->lfs_ivnode;
173 fs->clfs_devvp = fd_vget(fs->clfs_devfd, fs->lfs_fsize, fs->lfs_ssize,
174 atatime);
176 /* Allocate and clear segtab */
177 fs->clfs_segtab = (struct clfs_seguse *)malloc(fs->lfs_nseg *
178 sizeof(*fs->clfs_segtab));
179 fs->clfs_segtabp = (struct clfs_seguse **)malloc(fs->lfs_nseg *
180 sizeof(*fs->clfs_segtabp));
181 for (i = 0; i < fs->lfs_nseg; i++) {
182 fs->clfs_segtabp[i] = &(fs->clfs_segtab[i]);
183 fs->clfs_segtab[i].flags = 0x0;
185 syslog(LOG_NOTICE, "%s: unmounted cleaner starting", fsname);
187 return 0;
189 #endif
192 * Set up the file descriptors, including the Ifile descriptor.
193 * If we can't get the Ifile, this is not an LFS (or the kernel is
194 * too old to support the fcntl).
195 * XXX Merge this and init_unmounted_fs, switching on whether
196 * XXX "fsname" is a dir or a char special device. Should
197 * XXX also be able to read unmounted devices out of fstab, the way
198 * XXX fsck does.
201 init_fs(struct clfs *fs, char *fsname)
203 struct statvfs sf;
204 int rootfd;
205 int i;
208 * Get the raw device from the block device.
209 * XXX this is ugly. Is there a way to discover the raw device
210 * XXX for a given mount point?
212 if (kops.ko_statvfs(fsname, &sf, ST_WAIT) < 0)
213 return -1;
214 fs->clfs_dev = malloc(strlen(sf.f_mntfromname) + 2);
215 if (fs->clfs_dev == NULL) {
216 syslog(LOG_ERR, "couldn't malloc device name string: %m");
217 return -1;
219 sprintf(fs->clfs_dev, "/dev/r%s", sf.f_mntfromname + 5);
220 if ((fs->clfs_devfd = kops.ko_open(fs->clfs_dev, O_RDONLY, 0)) < 0) {
221 syslog(LOG_ERR, "couldn't open device %s for reading",
222 fs->clfs_dev);
223 return -1;
226 /* Find the Ifile and open it */
227 if ((rootfd = kops.ko_open(fsname, O_RDONLY, 0)) < 0)
228 return -2;
229 if (kops.ko_fcntl(rootfd, LFCNIFILEFH, &fs->clfs_ifilefh) < 0)
230 return -3;
231 if ((fs->clfs_ifilefd = kops.ko_fhopen(&fs->clfs_ifilefh,
232 sizeof(fs->clfs_ifilefh), O_RDONLY)) < 0)
233 return -4;
234 kops.ko_close(rootfd);
236 /* Load in the superblock */
237 if (kops.ko_pread(fs->clfs_devfd, &(fs->lfs_dlfs), sizeof(struct dlfs),
238 LFS_LABELPAD) < 0)
239 return -1;
241 /* If this is not a version 2 filesystem, complain and exit */
242 if (fs->lfs_version != 2) {
243 syslog(LOG_ERR, "%s: not a version 2 LFS", fsname);
244 return -1;
247 /* Assume fsname is the mounted name */
248 strncpy((char *)fs->lfs_fsmnt, fsname, MNAMELEN);
250 /* Set up vnodes for Ifile and raw device */
251 fs->lfs_ivnode = fd_vget(fs->clfs_ifilefd, fs->lfs_bsize, 0, 0);
252 fs->clfs_devvp = fd_vget(fs->clfs_devfd, fs->lfs_fsize, fs->lfs_ssize,
253 atatime);
255 /* Allocate and clear segtab */
256 fs->clfs_segtab = (struct clfs_seguse *)malloc(fs->lfs_nseg *
257 sizeof(*fs->clfs_segtab));
258 fs->clfs_segtabp = (struct clfs_seguse **)malloc(fs->lfs_nseg *
259 sizeof(*fs->clfs_segtabp));
260 if (fs->clfs_segtab == NULL || fs->clfs_segtabp == NULL) {
261 syslog(LOG_ERR, "%s: couldn't malloc segment table: %m",
262 fs->clfs_dev);
263 return -1;
266 for (i = 0; i < fs->lfs_nseg; i++) {
267 fs->clfs_segtabp[i] = &(fs->clfs_segtab[i]);
268 fs->clfs_segtab[i].flags = 0x0;
271 syslog(LOG_NOTICE, "%s: attaching cleaner", fsname);
272 return 0;
276 * Invalidate all the currently held Ifile blocks so they will be
277 * reread when we clean. Check the size while we're at it, and
278 * resize the buffer cache if necessary.
280 void
281 reload_ifile(struct clfs *fs)
283 struct ubuf *bp;
284 struct stat st;
285 int ohashmax;
286 extern int hashmax;
288 while ((bp = LIST_FIRST(&fs->lfs_ivnode->v_dirtyblkhd)) != NULL) {
289 bremfree(bp);
290 buf_destroy(bp);
292 while ((bp = LIST_FIRST(&fs->lfs_ivnode->v_cleanblkhd)) != NULL) {
293 bremfree(bp);
294 buf_destroy(bp);
297 /* If Ifile is larger than buffer cache, rehash */
298 fstat(fs->clfs_ifilefd, &st);
299 if (st.st_size / fs->lfs_bsize > hashmax) {
300 ohashmax = hashmax;
301 bufrehash(st.st_size / fs->lfs_bsize);
302 dlog("%s: resized buffer hash from %d to %d",
303 fs->lfs_fsmnt, ohashmax, hashmax);
308 * Get IFILE entry for the given inode, store in ifpp. The buffer
309 * which contains that data is returned in bpp, and must be brelse()d
310 * by the caller.
312 void
313 lfs_ientry(IFILE **ifpp, struct clfs *fs, ino_t ino, struct ubuf **bpp)
315 int error;
317 error = bread(fs->lfs_ivnode, ino / fs->lfs_ifpb + fs->lfs_cleansz +
318 fs->lfs_segtabsz, fs->lfs_bsize, NOCRED, 0, bpp);
319 if (error)
320 syslog(LOG_ERR, "%s: ientry failed for ino %d",
321 fs->lfs_fsmnt, (int)ino);
322 *ifpp = (IFILE *)(*bpp)->b_data + ino % fs->lfs_ifpb;
323 return;
326 #ifdef TEST_PATTERN
328 * Check ROOTINO for file data. The assumption is that we are running
329 * the "twofiles" test with the rest of the filesystem empty. Files
330 * created by "twofiles" match the test pattern, but ROOTINO and the
331 * executable itself (assumed to be inode 3) should not match.
333 static void
334 check_test_pattern(BLOCK_INFO *bip)
336 int j;
337 unsigned char *cp = bip->bi_bp;
339 /* Check inode sanity */
340 if (bip->bi_lbn == LFS_UNUSED_LBN) {
341 assert(((struct ufs1_dinode *)bip->bi_bp)->di_inumber ==
342 bip->bi_inode);
345 /* These can have the test pattern and it's all good */
346 if (bip->bi_inode > 3)
347 return;
349 for (j = 0; j < bip->bi_size; j++) {
350 if (cp[j] != (j & 0xff))
351 break;
353 assert(j < bip->bi_size);
355 #endif /* TEST_PATTERN */
358 * Parse the partial segment at daddr, adding its information to
359 * bip. Return the address of the next partial segment to read.
361 int32_t
362 parse_pseg(struct clfs *fs, daddr_t daddr, BLOCK_INFO **bipp, int *bic)
364 SEGSUM *ssp;
365 IFILE *ifp;
366 BLOCK_INFO *bip, *nbip;
367 int32_t *iaddrp, idaddr, odaddr;
368 FINFO *fip;
369 struct ubuf *ifbp;
370 struct ufs1_dinode *dip;
371 u_int32_t ck, vers;
372 int fic, inoc, obic;
373 int i;
374 char *cp;
376 odaddr = daddr;
377 obic = *bic;
378 bip = *bipp;
381 * Retrieve the segment header, set up the SEGSUM pointer
382 * as well as the first FINFO and inode address pointer.
384 cp = fd_ptrget(fs->clfs_devvp, daddr);
385 ssp = (SEGSUM *)cp;
386 iaddrp = ((int32_t *)(cp + fs->lfs_ibsize)) - 1;
387 fip = (FINFO *)(cp + sizeof(SEGSUM));
390 * Check segment header magic and checksum
392 if (ssp->ss_magic != SS_MAGIC) {
393 syslog(LOG_WARNING, "%s: sumsum magic number bad at 0x%x:"
394 " read 0x%x, expected 0x%x", fs->lfs_fsmnt,
395 (int32_t)daddr, ssp->ss_magic, SS_MAGIC);
396 return 0x0;
398 ck = cksum(&ssp->ss_datasum, fs->lfs_sumsize - sizeof(ssp->ss_sumsum));
399 if (ck != ssp->ss_sumsum) {
400 syslog(LOG_WARNING, "%s: sumsum checksum mismatch at 0x%x:"
401 " read 0x%x, computed 0x%x", fs->lfs_fsmnt,
402 (int32_t)daddr, ssp->ss_sumsum, ck);
403 return 0x0;
406 /* Initialize data sum */
407 ck = 0;
409 /* Point daddr at next block after segment summary */
410 ++daddr;
413 * Loop over file info and inode pointers. We always move daddr
414 * forward here because we are also computing the data checksum
415 * as we go.
417 fic = inoc = 0;
418 while (fic < ssp->ss_nfinfo || inoc < ssp->ss_ninos) {
420 * We must have either a file block or an inode block.
421 * If we don't have either one, it's an error.
423 if (fic >= ssp->ss_nfinfo && *iaddrp != daddr) {
424 syslog(LOG_WARNING, "%s: bad pseg at %x (seg %d)",
425 fs->lfs_fsmnt, odaddr, dtosn(fs, odaddr));
426 *bipp = bip;
427 return 0x0;
431 * Note each inode from the inode blocks
433 if (inoc < ssp->ss_ninos && *iaddrp == daddr) {
434 cp = fd_ptrget(fs->clfs_devvp, daddr);
435 ck = lfs_cksum_part(cp, sizeof(u_int32_t), ck);
436 dip = (struct ufs1_dinode *)cp;
437 for (i = 0; i < fs->lfs_inopb; i++) {
438 if (dip[i].di_inumber == 0)
439 break;
442 * Check currency before adding it
444 #ifndef REPAIR_ZERO_FINFO
445 lfs_ientry(&ifp, fs, dip[i].di_inumber, &ifbp);
446 idaddr = ifp->if_daddr;
447 brelse(ifbp, 0);
448 if (idaddr != daddr)
449 #endif
450 continue;
453 * A current inode. Add it.
455 ++*bic;
456 nbip = (BLOCK_INFO *)realloc(bip, *bic *
457 sizeof(*bip));
458 if (nbip)
459 bip = nbip;
460 else {
461 --*bic;
462 *bipp = bip;
463 return 0x0;
465 bip[*bic - 1].bi_inode = dip[i].di_inumber;
466 bip[*bic - 1].bi_lbn = LFS_UNUSED_LBN;
467 bip[*bic - 1].bi_daddr = daddr;
468 bip[*bic - 1].bi_segcreate = ssp->ss_create;
469 bip[*bic - 1].bi_version = dip[i].di_gen;
470 bip[*bic - 1].bi_bp = &(dip[i]);
471 bip[*bic - 1].bi_size = DINODE1_SIZE;
473 inoc += i;
474 daddr += btofsb(fs, fs->lfs_ibsize);
475 --iaddrp;
476 continue;
480 * Note each file block from the finfo blocks
482 if (fic >= ssp->ss_nfinfo)
483 continue;
485 /* Count this finfo, whether or not we use it */
486 ++fic;
489 * If this finfo has nblocks==0, it was written wrong.
490 * Kernels with this problem always wrote this zero-sized
491 * finfo last, so just ignore it.
493 if (fip->fi_nblocks == 0) {
494 #ifdef REPAIR_ZERO_FINFO
495 struct ubuf *nbp;
496 SEGSUM *nssp;
498 syslog(LOG_WARNING, "fixing short FINFO at %x (seg %d)",
499 odaddr, dtosn(fs, odaddr));
500 bread(fs->clfs_devvp, odaddr, fs->lfs_fsize,
501 NOCRED, 0, &nbp);
502 nssp = (SEGSUM *)nbp->b_data;
503 --nssp->ss_nfinfo;
504 nssp->ss_sumsum = cksum(&nssp->ss_datasum,
505 fs->lfs_sumsize - sizeof(nssp->ss_sumsum));
506 bwrite(nbp);
507 #endif
508 syslog(LOG_WARNING, "zero-length FINFO at %x (seg %d)",
509 odaddr, dtosn(fs, odaddr));
510 continue;
514 * Check currency before adding blocks
516 #ifdef REPAIR_ZERO_FINFO
517 vers = -1;
518 #else
519 lfs_ientry(&ifp, fs, fip->fi_ino, &ifbp);
520 vers = ifp->if_version;
521 brelse(ifbp, 0);
522 #endif
523 if (vers != fip->fi_version) {
524 size_t size;
526 /* Read all the blocks from the data summary */
527 for (i = 0; i < fip->fi_nblocks; i++) {
528 size = (i == fip->fi_nblocks - 1) ?
529 fip->fi_lastlength : fs->lfs_bsize;
530 cp = fd_ptrget(fs->clfs_devvp, daddr);
531 ck = lfs_cksum_part(cp, sizeof(u_int32_t), ck);
532 daddr += btofsb(fs, size);
534 fip = (FINFO *)(fip->fi_blocks + fip->fi_nblocks);
535 continue;
538 /* Add all the blocks from the finfos (current or not) */
539 nbip = (BLOCK_INFO *)realloc(bip, (*bic + fip->fi_nblocks) *
540 sizeof(*bip));
541 if (nbip)
542 bip = nbip;
543 else {
544 *bipp = bip;
545 return 0x0;
548 for (i = 0; i < fip->fi_nblocks; i++) {
549 bip[*bic + i].bi_inode = fip->fi_ino;
550 bip[*bic + i].bi_lbn = fip->fi_blocks[i];
551 bip[*bic + i].bi_daddr = daddr;
552 bip[*bic + i].bi_segcreate = ssp->ss_create;
553 bip[*bic + i].bi_version = fip->fi_version;
554 bip[*bic + i].bi_size = (i == fip->fi_nblocks - 1) ?
555 fip->fi_lastlength : fs->lfs_bsize;
556 cp = fd_ptrget(fs->clfs_devvp, daddr);
557 ck = lfs_cksum_part(cp, sizeof(u_int32_t), ck);
558 bip[*bic + i].bi_bp = cp;
559 daddr += btofsb(fs, bip[*bic + i].bi_size);
561 #ifdef TEST_PATTERN
562 check_test_pattern(bip + *bic + i); /* XXXDEBUG */
563 #endif
565 *bic += fip->fi_nblocks;
566 fip = (FINFO *)(fip->fi_blocks + fip->fi_nblocks);
569 #ifndef REPAIR_ZERO_FINFO
570 if (ssp->ss_datasum != ck) {
571 syslog(LOG_WARNING, "%s: data checksum bad at 0x%x:"
572 " read 0x%x, computed 0x%x", fs->lfs_fsmnt, odaddr,
573 ssp->ss_datasum, ck);
574 *bic = obic;
575 return 0x0;
577 #endif
579 *bipp = bip;
580 return daddr;
583 static void
584 log_segment_read(struct clfs *fs, int sn)
586 FILE *fp;
587 char *cp;
590 * Write the segment read, and its contents, into a log file in
591 * the current directory. We don't need to log the location of
592 * the segment, since that can be inferred from the segments up
593 * to this point (ss_nextseg field of the previously written segment).
595 * We can use this info later to reconstruct the filesystem at any
596 * given point in time for analysis, by replaying the log forward
597 * indexed by the segment serial numbers; but it is not suitable
598 * for everyday use since the copylog will be simply enormous.
600 cp = fd_ptrget(fs->clfs_devvp, sntod(fs, sn));
602 fp = fopen(copylog_filename, "ab");
603 if (fp != NULL) {
604 if (fwrite(cp, (size_t)fs->lfs_ssize, 1, fp) != 1) {
605 perror("writing segment to copy log");
608 fclose(fp);
612 * Read a segment to populate the BLOCK_INFO structures.
613 * Return the number of partial segments read and parsed.
616 load_segment(struct clfs *fs, int sn, BLOCK_INFO **bipp, int *bic)
618 int32_t daddr;
619 int i, npseg;
621 daddr = sntod(fs, sn);
622 if (daddr < btofsb(fs, LFS_LABELPAD))
623 daddr = btofsb(fs, LFS_LABELPAD);
624 for (i = 0; i < LFS_MAXNUMSB; i++) {
625 if (fs->lfs_sboffs[i] == daddr) {
626 daddr += btofsb(fs, LFS_SBPAD);
627 break;
631 /* Preload the segment buffer */
632 if (fd_preload(fs->clfs_devvp, sntod(fs, sn)) < 0)
633 return -1;
635 if (copylog_filename)
636 log_segment_read(fs, sn);
638 /* Note bytes read for stats */
639 cleaner_stats.segs_cleaned++;
640 cleaner_stats.bytes_read += fs->lfs_ssize;
641 ++fs->clfs_nactive;
643 npseg = 0;
644 while(dtosn(fs, daddr) == sn &&
645 dtosn(fs, daddr + btofsb(fs, fs->lfs_bsize)) == sn) {
646 daddr = parse_pseg(fs, daddr, bipp, bic);
647 if (daddr == 0x0) {
648 ++cleaner_stats.segs_error;
649 break;
651 ++npseg;
654 return npseg;
657 void
658 calc_cb(struct clfs *fs, int sn, struct clfs_seguse *t)
660 time_t now;
661 int64_t age, benefit, cost;
663 time(&now);
664 age = (now < t->lastmod ? 0 : now - t->lastmod);
666 /* Under no circumstances clean active or already-clean segments */
667 if ((t->flags & SEGUSE_ACTIVE) || !(t->flags & SEGUSE_DIRTY)) {
668 t->priority = 0;
669 return;
673 * If the segment is empty, there is no reason to clean it.
674 * Clear its error condition, if any, since we are never going to
675 * try to parse this one.
677 if (t->nbytes == 0) {
678 t->flags &= ~SEGUSE_ERROR; /* Strip error once empty */
679 t->priority = 0;
680 return;
683 if (t->flags & SEGUSE_ERROR) { /* No good if not already empty */
684 /* No benefit */
685 t->priority = 0;
686 return;
689 if (t->nbytes > fs->lfs_ssize) {
690 /* Another type of error */
691 syslog(LOG_WARNING, "segment %d: bad seguse count %d",
692 sn, t->nbytes);
693 t->flags |= SEGUSE_ERROR;
694 t->priority = 0;
695 return;
699 * The non-degenerate case. Use Rosenblum's cost-benefit algorithm.
700 * Calculate the benefit from cleaning this segment (one segment,
701 * minus fragmentation, dirty blocks and a segment summary block)
702 * and weigh that against the cost (bytes read plus bytes written).
703 * We count the summary headers as "dirty" to avoid cleaning very
704 * old and very full segments.
706 benefit = (int64_t)fs->lfs_ssize - t->nbytes -
707 (t->nsums + 1) * fs->lfs_fsize;
708 if (fs->lfs_bsize > fs->lfs_fsize) /* fragmentation */
709 benefit -= (fs->lfs_bsize / 2);
710 if (benefit <= 0) {
711 t->priority = 0;
712 return;
715 cost = fs->lfs_ssize + t->nbytes;
716 t->priority = (256 * benefit * age) / cost;
718 return;
722 * Comparator for BLOCK_INFO structures. Anything not in one of the segments
723 * we're looking at sorts higher; after that we sort first by inode number
724 * and then by block number (unsigned, i.e., negative sorts higher) *but*
725 * sort inodes before data blocks.
727 static int
728 bi_comparator(const void *va, const void *vb)
730 const BLOCK_INFO *a, *b;
732 a = (const BLOCK_INFO *)va;
733 b = (const BLOCK_INFO *)vb;
735 /* Check for out-of-place block */
736 if (a->bi_segcreate == a->bi_daddr &&
737 b->bi_segcreate != b->bi_daddr)
738 return -1;
739 if (a->bi_segcreate != a->bi_daddr &&
740 b->bi_segcreate == b->bi_daddr)
741 return 1;
742 if (a->bi_size <= 0 && b->bi_size > 0)
743 return 1;
744 if (b->bi_size <= 0 && a->bi_size > 0)
745 return -1;
747 /* Check inode number */
748 if (a->bi_inode != b->bi_inode)
749 return a->bi_inode - b->bi_inode;
751 /* Check lbn */
752 if (a->bi_lbn == LFS_UNUSED_LBN) /* Inodes sort lower than blocks */
753 return -1;
754 if (b->bi_lbn == LFS_UNUSED_LBN)
755 return 1;
756 if ((u_int32_t)a->bi_lbn > (u_int32_t)b->bi_lbn)
757 return 1;
758 else
759 return -1;
761 return 0;
765 * Comparator for sort_segments: cost-benefit equation.
767 static int
768 cb_comparator(const void *va, const void *vb)
770 const struct clfs_seguse *a, *b;
772 a = *(const struct clfs_seguse * const *)va;
773 b = *(const struct clfs_seguse * const *)vb;
774 return a->priority > b->priority ? -1 : 1;
777 void
778 toss_old_blocks(struct clfs *fs, BLOCK_INFO **bipp, int *bic, int *sizep)
780 int i, r;
781 BLOCK_INFO *bip = *bipp;
782 struct lfs_fcntl_markv /* {
783 BLOCK_INFO *blkiov;
784 int blkcnt;
785 } */ lim;
787 if (bic == 0 || bip == NULL)
788 return;
791 * Kludge: Store the disk address in segcreate so we know which
792 * ones to toss.
794 for (i = 0; i < *bic; i++)
795 bip[i].bi_segcreate = bip[i].bi_daddr;
797 /* Sort the blocks */
798 heapsort(bip, *bic, sizeof(BLOCK_INFO), bi_comparator);
800 /* Use bmapv to locate the blocks */
801 lim.blkiov = bip;
802 lim.blkcnt = *bic;
803 if ((r = kops.ko_fcntl(fs->clfs_ifilefd, LFCNBMAPV, &lim)) < 0) {
804 syslog(LOG_WARNING, "%s: bmapv returned %d (%m)",
805 fs->lfs_fsmnt, r);
806 return;
809 /* Toss blocks not in this segment */
810 heapsort(bip, *bic, sizeof(BLOCK_INFO), bi_comparator);
812 /* Get rid of stale blocks */
813 if (sizep)
814 *sizep = 0;
815 for (i = 0; i < *bic; i++) {
816 if (bip[i].bi_segcreate != bip[i].bi_daddr)
817 break;
818 if (sizep)
819 *sizep += bip[i].bi_size;
821 *bic = i; /* XXX realloc bip? */
822 *bipp = bip;
824 return;
828 * Clean a segment and mark it invalid.
831 invalidate_segment(struct clfs *fs, int sn)
833 BLOCK_INFO *bip;
834 int i, r, bic;
835 off_t nb;
836 double util;
837 struct lfs_fcntl_markv /* {
838 BLOCK_INFO *blkiov;
839 int blkcnt;
840 } */ lim;
842 dlog("%s: inval seg %d", fs->lfs_fsmnt, sn);
844 bip = NULL;
845 bic = 0;
846 fs->clfs_nactive = 0;
847 if (load_segment(fs, sn, &bip, &bic) <= 0)
848 return -1;
849 toss_old_blocks(fs, &bip, &bic, NULL);
851 /* Record statistics */
852 for (i = nb = 0; i < bic; i++)
853 nb += bip[i].bi_size;
854 util = ((double)nb) / (fs->clfs_nactive * fs->lfs_ssize);
855 cleaner_stats.util_tot += util;
856 cleaner_stats.util_sos += util * util;
857 cleaner_stats.bytes_written += nb;
860 * Use markv to move the blocks.
862 lim.blkiov = bip;
863 lim.blkcnt = bic;
864 if ((r = kops.ko_fcntl(fs->clfs_ifilefd, LFCNMARKV, &lim)) < 0) {
865 syslog(LOG_WARNING, "%s: markv returned %d (%m) "
866 "for seg %d", fs->lfs_fsmnt, r, sn);
867 return r;
871 * Finally call invalidate to invalidate the segment.
873 if ((r = kops.ko_fcntl(fs->clfs_ifilefd, LFCNINVAL, &sn)) < 0) {
874 syslog(LOG_WARNING, "%s: inval returned %d (%m) "
875 "for seg %d", fs->lfs_fsmnt, r, sn);
876 return r;
879 return 0;
883 * Check to see if the given ino/lbn pair is represented in the BLOCK_INFO
884 * array we are sending to the kernel, or if the kernel will have to add it.
885 * The kernel will only add each such pair once, though, so keep track of
886 * previous requests in a separate "extra" BLOCK_INFO array. Returns 1
887 * if the block needs to be added, 0 if it is already represented.
889 static int
890 check_or_add(ino_t ino, int32_t lbn, BLOCK_INFO *bip, int bic, BLOCK_INFO **ebipp, int *ebicp)
892 BLOCK_INFO *t, *ebip = *ebipp;
893 int ebic = *ebicp;
894 int k;
896 for (k = 0; k < bic; k++) {
897 if (bip[k].bi_inode != ino)
898 break;
899 if (bip[k].bi_lbn == lbn) {
900 return 0;
904 /* Look on the list of extra blocks, too */
905 for (k = 0; k < ebic; k++) {
906 if (ebip[k].bi_inode == ino && ebip[k].bi_lbn == lbn) {
907 return 0;
911 ++ebic;
912 t = realloc(ebip, ebic * sizeof(BLOCK_INFO));
913 if (t == NULL)
914 return 1; /* Note *ebipc is not updated */
916 ebip = t;
917 ebip[ebic - 1].bi_inode = ino;
918 ebip[ebic - 1].bi_lbn = lbn;
920 *ebipp = ebip;
921 *ebicp = ebic;
922 return 1;
926 * Look for indirect blocks we will have to write which are not
927 * contained in this collection of blocks. This constitutes
928 * a hidden cleaning cost, since we are unaware of it until we
929 * have already read the segments. Return the total cost, and fill
930 * in *ifc with the part of that cost due to rewriting the Ifile.
932 static off_t
933 check_hidden_cost(struct clfs *fs, BLOCK_INFO *bip, int bic, off_t *ifc)
935 int start;
936 struct indir in[NIADDR + 1];
937 int num;
938 int i, j, ebic;
939 BLOCK_INFO *ebip;
940 int32_t lbn;
942 start = 0;
943 ebip = NULL;
944 ebic = 0;
945 for (i = 0; i < bic; i++) {
946 if (i == 0 || bip[i].bi_inode != bip[start].bi_inode) {
947 start = i;
949 * Look for IFILE blocks, unless this is the Ifile.
951 if (bip[i].bi_inode != fs->lfs_ifile) {
952 lbn = fs->lfs_cleansz + bip[i].bi_inode /
953 fs->lfs_ifpb;
954 *ifc += check_or_add(fs->lfs_ifile, lbn,
955 bip, bic, &ebip, &ebic);
958 if (bip[i].bi_lbn == LFS_UNUSED_LBN)
959 continue;
960 if (bip[i].bi_lbn < NDADDR)
961 continue;
963 ufs_getlbns((struct lfs *)fs, NULL, (daddr_t)bip[i].bi_lbn, in, &num);
964 for (j = 0; j < num; j++) {
965 check_or_add(bip[i].bi_inode, in[j].in_lbn,
966 bip + start, bic - start, &ebip, &ebic);
969 return ebic;
973 * Select segments to clean, add blocks from these segments to a cleaning
974 * list, and send this list through lfs_markv() to move them to new
975 * locations on disk.
978 clean_fs(struct clfs *fs, CLEANERINFO *cip)
980 int i, j, ngood, sn, bic, r, npos;
981 int bytes, totbytes;
982 struct ubuf *bp;
983 SEGUSE *sup;
984 static BLOCK_INFO *bip;
985 struct lfs_fcntl_markv /* {
986 BLOCK_INFO *blkiov;
987 int blkcnt;
988 } */ lim;
989 int mc;
990 BLOCK_INFO *mbip;
991 int inc;
992 off_t nb;
993 off_t goal;
994 off_t extra, if_extra;
995 double util;
997 /* Read the segment table into our private structure */
998 npos = 0;
999 for (i = 0; i < fs->lfs_nseg; i+= fs->lfs_sepb) {
1000 bread(fs->lfs_ivnode, fs->lfs_cleansz + i / fs->lfs_sepb,
1001 fs->lfs_bsize, NOCRED, 0, &bp);
1002 for (j = 0; j < fs->lfs_sepb && i + j < fs->lfs_nseg; j++) {
1003 sup = ((SEGUSE *)bp->b_data) + j;
1004 fs->clfs_segtab[i + j].nbytes = sup->su_nbytes;
1005 fs->clfs_segtab[i + j].nsums = sup->su_nsums;
1006 fs->clfs_segtab[i + j].lastmod = sup->su_lastmod;
1007 /* Keep error status but renew other flags */
1008 fs->clfs_segtab[i + j].flags &= SEGUSE_ERROR;
1009 fs->clfs_segtab[i + j].flags |= sup->su_flags;
1011 /* Compute cost-benefit coefficient */
1012 calc_cb(fs, i + j, fs->clfs_segtab + i + j);
1013 if (fs->clfs_segtab[i + j].priority > 0)
1014 ++npos;
1016 brelse(bp, 0);
1019 /* Sort segments based on cleanliness, fulness, and condition */
1020 heapsort(fs->clfs_segtabp, fs->lfs_nseg, sizeof(struct clfs_seguse *),
1021 cb_comparator);
1023 /* If no segment is cleanable, just return */
1024 if (fs->clfs_segtabp[0]->priority == 0) {
1025 dlog("%s: no segment cleanable", fs->lfs_fsmnt);
1026 return 0;
1029 /* Load some segments' blocks into bip */
1030 bic = 0;
1031 fs->clfs_nactive = 0;
1032 ngood = 0;
1033 if (use_bytes) {
1034 /* Set attainable goal */
1035 goal = fs->lfs_ssize * atatime;
1036 if (goal > (cip->clean - 1) * fs->lfs_ssize / 2)
1037 goal = MAX((cip->clean - 1) * fs->lfs_ssize,
1038 fs->lfs_ssize) / 2;
1040 dlog("%s: cleaning with goal %" PRId64
1041 " bytes (%d segs clean, %d cleanable)",
1042 fs->lfs_fsmnt, goal, cip->clean, npos);
1043 syslog(LOG_INFO, "%s: cleaning with goal %" PRId64
1044 " bytes (%d segs clean, %d cleanable)",
1045 fs->lfs_fsmnt, goal, cip->clean, npos);
1046 totbytes = 0;
1047 for (i = 0; i < fs->lfs_nseg && totbytes < goal; i++) {
1048 if (fs->clfs_segtabp[i]->priority == 0)
1049 break;
1050 /* Upper bound on number of segments at once */
1051 if (ngood * fs->lfs_ssize > 4 * goal)
1052 break;
1053 sn = (fs->clfs_segtabp[i] - fs->clfs_segtab);
1054 dlog("%s: add seg %d prio %" PRIu64
1055 " containing %ld bytes",
1056 fs->lfs_fsmnt, sn, fs->clfs_segtabp[i]->priority,
1057 fs->clfs_segtabp[i]->nbytes);
1058 if ((r = load_segment(fs, sn, &bip, &bic)) > 0) {
1059 ++ngood;
1060 toss_old_blocks(fs, &bip, &bic, &bytes);
1061 totbytes += bytes;
1062 } else if (r == 0)
1063 fd_release(fs->clfs_devvp);
1064 else
1065 break;
1067 } else {
1068 /* Set attainable goal */
1069 goal = atatime;
1070 if (goal > cip->clean - 1)
1071 goal = MAX(cip->clean - 1, 1);
1073 dlog("%s: cleaning with goal %d segments (%d clean, %d cleanable)",
1074 fs->lfs_fsmnt, (int)goal, cip->clean, npos);
1075 for (i = 0; i < fs->lfs_nseg && ngood < goal; i++) {
1076 if (fs->clfs_segtabp[i]->priority == 0)
1077 break;
1078 sn = (fs->clfs_segtabp[i] - fs->clfs_segtab);
1079 dlog("%s: add seg %d prio %" PRIu64,
1080 fs->lfs_fsmnt, sn, fs->clfs_segtabp[i]->priority);
1081 if ((r = load_segment(fs, sn, &bip, &bic)) > 0)
1082 ++ngood;
1083 else if (r == 0)
1084 fd_release(fs->clfs_devvp);
1085 else
1086 break;
1088 toss_old_blocks(fs, &bip, &bic, NULL);
1091 /* If there is nothing to do, try again later. */
1092 if (bic == 0) {
1093 dlog("%s: no blocks to clean in %d cleanable segments",
1094 fs->lfs_fsmnt, (int)ngood);
1095 fd_release_all(fs->clfs_devvp);
1096 return 0;
1099 /* Record statistics */
1100 for (i = nb = 0; i < bic; i++)
1101 nb += bip[i].bi_size;
1102 util = ((double)nb) / (fs->clfs_nactive * fs->lfs_ssize);
1103 cleaner_stats.util_tot += util;
1104 cleaner_stats.util_sos += util * util;
1105 cleaner_stats.bytes_written += nb;
1108 * Check out our blocks to see if there are hidden cleaning costs.
1109 * If there are, we might be cleaning ourselves deeper into a hole
1110 * rather than doing anything useful.
1111 * XXX do something about this.
1113 if_extra = 0;
1114 extra = fs->lfs_bsize * (off_t)check_hidden_cost(fs, bip, bic, &if_extra);
1115 if_extra *= fs->lfs_bsize;
1118 * Use markv to move the blocks.
1120 if (do_small)
1121 inc = MAXPHYS / fs->lfs_bsize - 1;
1122 else
1123 inc = LFS_MARKV_MAXBLKCNT / 2;
1124 for (mc = 0, mbip = bip; mc < bic; mc += inc, mbip += inc) {
1125 lim.blkiov = mbip;
1126 lim.blkcnt = (bic - mc > inc ? inc : bic - mc);
1127 #ifdef TEST_PATTERN
1128 dlog("checking blocks %d-%d", mc, mc + lim.blkcnt - 1);
1129 for (i = 0; i < lim.blkcnt; i++) {
1130 check_test_pattern(mbip + i);
1132 #endif /* TEST_PATTERN */
1133 dlog("sending blocks %d-%d", mc, mc + lim.blkcnt - 1);
1134 if ((r = kops.ko_fcntl(fs->clfs_ifilefd, LFCNMARKV, &lim))<0) {
1135 syslog(LOG_WARNING, "%s: markv returned %d (%m)",
1136 fs->lfs_fsmnt, r);
1137 if (errno != EAGAIN && errno != ESHUTDOWN) {
1138 fd_release_all(fs->clfs_devvp);
1139 return r;
1145 * Report progress (or lack thereof)
1147 syslog(LOG_INFO, "%s: wrote %" PRId64 " dirty + %"
1148 PRId64 " supporting indirect + %"
1149 PRId64 " supporting Ifile = %"
1150 PRId64 " bytes to clean %d segs (%" PRId64 "%% recovery)",
1151 fs->lfs_fsmnt, (int64_t)nb, (int64_t)(extra - if_extra),
1152 (int64_t)if_extra, (int64_t)(nb + extra), ngood,
1153 (ngood ? (int64_t)(100 - (100 * (nb + extra)) /
1154 (ngood * fs->lfs_ssize)) :
1155 (int64_t)0));
1156 if (nb + extra >= ngood * fs->lfs_ssize)
1157 syslog(LOG_WARNING, "%s: cleaner not making forward progress",
1158 fs->lfs_fsmnt);
1161 * Finally call reclaim to prompt cleaning of the segments.
1163 kops.ko_fcntl(fs->clfs_ifilefd, LFCNRECLAIM, NULL);
1165 fd_release_all(fs->clfs_devvp);
1166 return 0;
1170 * Read the cleanerinfo block and apply cleaning policy to determine whether
1171 * the given filesystem needs to be cleaned. Returns 1 if it does, 0 if it
1172 * does not, or -1 on error.
1175 needs_cleaning(struct clfs *fs, CLEANERINFO *cip)
1177 struct ubuf *bp;
1178 struct stat st;
1179 daddr_t fsb_per_seg, max_free_segs;
1180 time_t now;
1181 double loadavg;
1183 /* If this fs is "on hold", don't clean it. */
1184 if (fs->clfs_onhold)
1185 return 0;
1188 * Read the cleanerinfo block from the Ifile. We don't want
1189 * the cached information, so invalidate the buffer before
1190 * handing it back.
1192 if (bread(fs->lfs_ivnode, 0, fs->lfs_bsize, NOCRED, 0, &bp)) {
1193 syslog(LOG_ERR, "%s: can't read inode", fs->lfs_fsmnt);
1194 return -1;
1196 *cip = *(CLEANERINFO *)bp->b_data; /* Structure copy */
1197 brelse(bp, B_INVAL);
1198 cleaner_stats.bytes_read += fs->lfs_bsize;
1201 * If the number of segments changed under us, reinit.
1202 * We don't have to start over from scratch, however,
1203 * since we don't hold any buffers.
1205 if (fs->lfs_nseg != cip->clean + cip->dirty) {
1206 if (reinit_fs(fs) < 0) {
1207 /* The normal case for unmount */
1208 syslog(LOG_NOTICE, "%s: filesystem unmounted", fs->lfs_fsmnt);
1209 return -1;
1211 syslog(LOG_NOTICE, "%s: nsegs changed", fs->lfs_fsmnt);
1214 /* Compute theoretical "free segments" maximum based on usage */
1215 fsb_per_seg = segtod(fs, 1);
1216 max_free_segs = MAX(cip->bfree, 0) / fsb_per_seg + fs->lfs_minfreeseg;
1218 dlog("%s: bfree = %d, avail = %d, clean = %d/%d",
1219 fs->lfs_fsmnt, cip->bfree, cip->avail, cip->clean, fs->lfs_nseg);
1221 /* If the writer is waiting on us, clean it */
1222 if (cip->clean <= fs->lfs_minfreeseg ||
1223 (cip->flags & LFS_CLEANER_MUST_CLEAN))
1224 return 1;
1226 /* If there are enough segments, don't clean it */
1227 if (cip->bfree - cip->avail <= fsb_per_seg &&
1228 cip->avail > fsb_per_seg)
1229 return 0;
1231 /* If we are in dire straits, clean it */
1232 if (cip->bfree - cip->avail > fsb_per_seg &&
1233 cip->avail <= fsb_per_seg)
1234 return 1;
1236 /* If under busy threshold, clean regardless of load */
1237 if (cip->clean < max_free_segs * BUSY_LIM)
1238 return 1;
1240 /* Check busy status; clean if idle and under idle limit */
1241 if (use_fs_idle) {
1242 /* Filesystem idle */
1243 time(&now);
1244 if (fstat(fs->clfs_ifilefd, &st) < 0) {
1245 syslog(LOG_ERR, "%s: failed to stat ifile",
1246 fs->lfs_fsmnt);
1247 return -1;
1249 if (now - st.st_mtime > segwait_timeout &&
1250 cip->clean < max_free_segs * IDLE_LIM)
1251 return 1;
1252 } else {
1253 /* CPU idle - use one-minute load avg */
1254 if (getloadavg(&loadavg, 1) == -1) {
1255 syslog(LOG_ERR, "%s: failed to get load avg",
1256 fs->lfs_fsmnt);
1257 return -1;
1259 if (loadavg < load_threshold &&
1260 cip->clean < max_free_segs * IDLE_LIM)
1261 return 1;
1264 return 0;
1268 * Report statistics. If the signal was SIGUSR2, clear the statistics too.
1269 * If the signal was SIGINT, exit.
1271 static void
1272 sig_report(int sig)
1274 double avg = 0.0, stddev;
1276 avg = cleaner_stats.util_tot / MAX(cleaner_stats.segs_cleaned, 1.0);
1277 stddev = cleaner_stats.util_sos / MAX(cleaner_stats.segs_cleaned -
1278 avg * avg, 1.0);
1279 syslog(LOG_INFO, "bytes read: %" PRId64, cleaner_stats.bytes_read);
1280 syslog(LOG_INFO, "bytes written: %" PRId64, cleaner_stats.bytes_written);
1281 syslog(LOG_INFO, "segments cleaned: %" PRId64, cleaner_stats.segs_cleaned);
1282 #if 0
1283 /* "Empty segments" is meaningless, since the kernel handles those */
1284 syslog(LOG_INFO, "empty segments: %" PRId64, cleaner_stats.segs_empty);
1285 #endif
1286 syslog(LOG_INFO, "error segments: %" PRId64, cleaner_stats.segs_error);
1287 syslog(LOG_INFO, "utilization total: %g", cleaner_stats.util_tot);
1288 syslog(LOG_INFO, "utilization sos: %g", cleaner_stats.util_sos);
1289 syslog(LOG_INFO, "utilization avg: %4.2f", avg);
1290 syslog(LOG_INFO, "utilization sdev: %9.6f", stddev);
1292 if (debug)
1293 bufstats();
1295 if (sig == SIGUSR2)
1296 memset(&cleaner_stats, 0, sizeof(cleaner_stats));
1297 if (sig == SIGINT)
1298 exit(0);
1301 static void
1302 sig_exit(int sig)
1304 exit(0);
1307 static void
1308 usage(void)
1310 errx(1, "usage: lfs_cleanerd [-bcdfmqs] [-i segnum] [-l load] "
1311 "[-n nsegs] [-r report_freq] [-t timeout] fs_name ...");
1314 #ifndef LFS_CLEANER_AS_LIB
1316 * Main.
1319 main(int argc, char **argv)
1322 return lfs_cleaner_main(argc, argv);
1324 #endif
1327 lfs_cleaner_main(int argc, char **argv)
1329 int i, opt, error, r, loopcount, nodetach;
1330 struct timeval tv;
1331 CLEANERINFO ci;
1332 #ifndef USE_CLIENT_SERVER
1333 char *cp, *pidname;
1334 #endif
1337 * Set up defaults
1339 atatime = 1;
1340 segwait_timeout = 300; /* Five minutes */
1341 load_threshold = 0.2;
1342 stat_report = 0;
1343 inval_segment = -1;
1344 copylog_filename = NULL;
1345 nodetach = 0;
1348 * Parse command-line arguments
1350 while ((opt = getopt(argc, argv, "bC:cdDfi:l:mn:qr:st:")) != -1) {
1351 switch (opt) {
1352 case 'b': /* Use bytes written, not segments read */
1353 use_bytes = 1;
1354 break;
1355 case 'C': /* copy log */
1356 copylog_filename = optarg;
1357 break;
1358 case 'c': /* Coalesce files */
1359 do_coalesce++;
1360 break;
1361 case 'd': /* Debug mode. */
1362 nodetach++;
1363 debug++;
1364 break;
1365 case 'D': /* stay-on-foreground */
1366 nodetach++;
1367 break;
1368 case 'f': /* Use fs idle time rather than cpu idle */
1369 use_fs_idle = 1;
1370 break;
1371 case 'i': /* Invalidate this segment */
1372 inval_segment = atoi(optarg);
1373 break;
1374 case 'l': /* Load below which to clean */
1375 load_threshold = atof(optarg);
1376 break;
1377 case 'm': /* [compat only] */
1378 break;
1379 case 'n': /* How many segs to clean at once */
1380 atatime = atoi(optarg);
1381 break;
1382 case 'q': /* Quit after one run */
1383 do_quit = 1;
1384 break;
1385 case 'r': /* Report every stat_report segments */
1386 stat_report = atoi(optarg);
1387 break;
1388 case 's': /* Small writes */
1389 do_small = 1;
1390 break;
1391 case 't': /* timeout */
1392 segwait_timeout = atoi(optarg);
1393 break;
1394 default:
1395 usage();
1396 /* NOTREACHED */
1399 argc -= optind;
1400 argv += optind;
1402 if (argc < 1)
1403 usage();
1404 if (inval_segment >= 0 && argc != 1) {
1405 errx(1, "lfs_cleanerd: may only specify one filesystem when "
1406 "using -i flag");
1409 if (do_coalesce) {
1410 errx(1, "lfs_cleanerd: -c disabled due to reports of file "
1411 "corruption; you may re-enable it by rebuilding the "
1412 "cleaner");
1416 * Set up daemon mode or foreground mode
1418 if (nodetach) {
1419 openlog("lfs_cleanerd", LOG_NDELAY | LOG_PID | LOG_PERROR,
1420 LOG_DAEMON);
1421 signal(SIGINT, sig_report);
1422 } else {
1423 if (daemon(0, 0) == -1)
1424 err(1, "lfs_cleanerd: couldn't become a daemon!");
1425 openlog("lfs_cleanerd", LOG_NDELAY | LOG_PID, LOG_DAEMON);
1426 signal(SIGINT, sig_exit);
1430 * Look for an already-running master daemon. If there is one,
1431 * send it our filesystems to add to its list and exit.
1432 * If there is none, become the master.
1434 #ifdef USE_CLIENT_SERVER
1435 try_to_become_master(argc, argv);
1436 #else
1437 /* XXX think about this */
1438 asprintf(&pidname, "lfs_cleanerd:m:%s", argv[0]);
1439 if (pidname == NULL) {
1440 syslog(LOG_ERR, "malloc failed: %m");
1441 exit(1);
1443 for (cp = pidname; cp != NULL; cp = strchr(cp, '/'))
1444 *cp = '|';
1445 pidfile(pidname);
1446 #endif
1449 * Signals mean daemon should report its statistics
1451 memset(&cleaner_stats, 0, sizeof(cleaner_stats));
1452 signal(SIGUSR1, sig_report);
1453 signal(SIGUSR2, sig_report);
1456 * Start up buffer cache. We only use this for the Ifile,
1457 * and we will resize it if necessary, so it can start small.
1459 bufinit(4);
1461 #ifdef REPAIR_ZERO_FINFO
1463 BLOCK_INFO *bip = NULL;
1464 int bic = 0;
1466 nfss = 1;
1467 fsp = (struct clfs **)malloc(sizeof(*fsp));
1468 fsp[0] = (struct clfs *)calloc(1, sizeof(**fsp));
1470 if (init_unmounted_fs(fsp[0], argv[0]) < 0) {
1471 err(1, "init_unmounted_fs");
1473 dlog("Filesystem has %d segments", fsp[0]->lfs_nseg);
1474 for (i = 0; i < fsp[0]->lfs_nseg; i++) {
1475 load_segment(fsp[0], i, &bip, &bic);
1476 bic = 0;
1478 exit(0);
1480 #endif
1483 * Initialize cleaning structures, open devices, etc.
1485 nfss = argc;
1486 fsp = (struct clfs **)malloc(nfss * sizeof(*fsp));
1487 if (fsp == NULL) {
1488 syslog(LOG_ERR, "couldn't allocate fs table: %m");
1489 exit(1);
1491 for (i = 0; i < nfss; i++) {
1492 fsp[i] = (struct clfs *)calloc(1, sizeof(**fsp));
1493 if ((r = init_fs(fsp[i], argv[i])) < 0) {
1494 syslog(LOG_ERR, "%s: couldn't init: error code %d",
1495 argv[i], r);
1496 handle_error(fsp, i);
1497 --i; /* Do the new #i over again */
1502 * If asked to coalesce, do so and exit.
1504 if (do_coalesce) {
1505 for (i = 0; i < nfss; i++)
1506 clean_all_inodes(fsp[i]);
1507 exit(0);
1511 * If asked to invalidate a segment, do that and exit.
1513 if (inval_segment >= 0) {
1514 invalidate_segment(fsp[0], inval_segment);
1515 exit(0);
1519 * Main cleaning loop.
1521 loopcount = 0;
1522 while (nfss > 0) {
1523 int cleaned_one;
1524 do {
1525 #ifdef USE_CLIENT_SERVER
1526 check_control_socket();
1527 #endif
1528 cleaned_one = 0;
1529 for (i = 0; i < nfss; i++) {
1530 if ((error = needs_cleaning(fsp[i], &ci)) < 0) {
1531 handle_error(fsp, i);
1532 continue;
1534 if (error == 0) /* No need to clean */
1535 continue;
1537 reload_ifile(fsp[i]);
1538 if (clean_fs(fsp[i], &ci) < 0) {
1539 handle_error(fsp, i);
1540 continue;
1542 ++cleaned_one;
1544 ++loopcount;
1545 if (stat_report && loopcount % stat_report == 0)
1546 sig_report(0);
1547 if (do_quit)
1548 exit(0);
1549 } while(cleaned_one);
1550 tv.tv_sec = segwait_timeout;
1551 tv.tv_usec = 0;
1552 /* XXX: why couldn't others work if fsp socket is shutdown? */
1553 error = kops.ko_fcntl(fsp[0]->clfs_ifilefd,LFCNSEGWAITALL,&tv);
1554 if (error) {
1555 if (errno == ESHUTDOWN) {
1556 for (i = 0; i < nfss; i++) {
1557 handle_error(fsp, i);
1558 assert(nfss == 0);
1560 } else
1561 err(1, "LFCNSEGWAITALL");
1565 /* NOTREACHED */
1566 return 0;