1# $FreeBSD$
2
3use strict;
4use warnings;
5use Test::More tests => 19;
6use Fcntl qw(:DEFAULT :seek);
7
8use constant BLK => 512;
9use constant BLKS_PER_MB => 2048;
10
11my $unit;
12END { system "mdconfig -du$unit" if defined $unit };
13
14sub setsize {
15    my ($partszMB, $unitszMB) = @_;
16
17    open my $fd, "|-", "disklabel -R md$unit /dev/stdin" or die;
18    print $fd "a: ", ($partszMB * BLKS_PER_MB), " 0 4.2BSD 1024 8192\n";
19    print $fd "c: ", ($unitszMB * BLKS_PER_MB), " 0 unused 0 0\n";
20    close $fd;
21}
22
23sub fill {
24    my ($start, $size, $content) = @_;
25
26    my $content512 = $content x (int(512 / length $content) + 1);
27    substr($content512, 512) = "";
28    sysopen my $fd, "/dev/md$unit", O_RDWR or die "/dev/md$unit: $!";
29    seek($fd, $start * BLK, SEEK_SET);
30    while ($size) {
31	syswrite($fd, $content512) == 512 or die "write: $!";
32	$size--;
33    }
34}
35
36SKIP: {
37    skip "Cannot test without UID 0", 19 if $<;
38
39    chomp(my $md = `mdconfig -s40m`);
40    like($md, qr/^md\d+$/, "Created $md with size 40m") or die;
41    $unit = substr $md, 2;
42
43    for my $type (1..2) {
44
45	initialise: {
46	    ok(setsize(10, 40), "Sized ${md}a to 10m");
47	    system "newfs -O $type -U ${md}a >/dev/null";
48	    is($?, 0, "Initialised the filesystem on ${md}a as UFS$type");
49	    chomp(my @out = `fsck -tufs -y ${md}a`);
50	    ok(!grep(/MODIFIED/, @out), "fsck says ${md}a is clean, " .
51		scalar(@out) . " lines of output");
52	}
53
54	extend20_zeroed: {
55	    ok(setsize(20, 40), "Sized ${md}a to 20m");
56	    diag "Filling the extent with zeros";
57	    fill(10 * BLKS_PER_MB, 10 * BLKS_PER_MB, chr(0));
58	    my $out = `growfs -y ${md}a`;
59	    is($?, 0, "Extended the filesystem on ${md}a") or print $out;
60
61	    my ($unallocated) = $out =~ m{\d+ sectors cannot be allocated};
62	    fill(30 * BLKS_PER_MB - $unallocated, $unallocated, chr(0))
63		if $unallocated;
64
65	    chomp(my @out = `fsck -tufs -y ${md}a`);
66	    ok(!grep(/MODIFIED/, @out), "fsck says ${md}a is clean, " .
67		scalar(@out) . " lines of output");
68	}
69
70	extend30_garbaged: {
71	    ok(setsize(30, 40), "Sized ${md}a to 30m");
72	    diag "Filling the extent with garbage";
73	    fill(20 * BLKS_PER_MB, 10 * BLKS_PER_MB, chr(0xaa) . chr(0x55));
74	    my $out = `growfs -y ${md}a`;
75	    is($?, 0, "Extended the filesystem on ${md}a") or print $out;
76
77	    my ($unallocated) = $out =~ m{\d+ sectors cannot be allocated};
78	    fill(30 * BLKS_PER_MB - $unallocated, $unallocated, chr(0))
79		if $unallocated;
80
81	    chomp(my @out = `fsck -tufs -y ${md}a`);
82	    ok(!grep(/MODIFIED/, @out), "fsck says ${md}a is clean, " .
83		scalar(@out) . " lines of output");
84	}
85    }
86
87    system "mdconfig -du$unit";
88    undef $unit;
89}
90