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