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