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