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