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