Clear unused space with zeros (btrfs)











up vote
9
down vote

favorite
4












How to clear unused space with zeros ? (I am asking for tool for btrfs filesystem)



I'm looking for something smarter than



cat /dev/zero > /mnt/X/big_zero ; sync; rm /mnt/X/big_zero


Like FSArchiver is looking for "used space" and ignores unused, but opposite site.



Purpose: I'd like to compress partition images, so filling unused space with zeros is highly recommended.



Btw. For ext3,ext4 : Clear unused space with zeros (ext3,ext4) . Here I ask for btrfs



Clarification of "smarter algorithm": As I see that "smarter algorithm" leads to confusion, here I finally decided to add line about it. Dear reader, please think about filesystem as datastructure. For simplification purposes, let's imagine self balancing red-black tree holding map, that is used as association key->value array, where values are integers. Goal is to clear all negative values with zeros. "not smart" algorithm will iterate over it and add key:value pairs to new map (with eventual altering negative to zero). Smart algorithm will just detect places where negative values are stored and clear them in-place.










share|improve this question




















  • 2




    Did you try the sfill suggestion? It looks like it doesn't require extX.
    – Kevin
    Aug 3 '12 at 23:53










  • 1. I know you can fill existing files with zeros with shred, but this probably isn't it, right? 2.How are you making those images? Maybe you can do the truncation there?
    – Zlatko
    Aug 4 '12 at 0:23












  • @kevin: that's why i posted the sfill answer in the original question. i rarely use ext2,3,4 filesystems myself so i find utilities that work only on ext* to be annoyingly useless.
    – cas
    Aug 4 '12 at 3:00










  • I need something "smart". Something what only fills empty space with zeros without touching other places - I mean without affecting internal data-structures, like B-Trees (If your are curious, I've written in question "compression" but I need it also for other purposes, like fs images de-duplication, analysis and research)
    – Grzegorz Wierzowiecki
    Aug 5 '12 at 21:57










  • just use truncate and/or fallocate
    – mikeserv
    Dec 14 '14 at 1:20















up vote
9
down vote

favorite
4












How to clear unused space with zeros ? (I am asking for tool for btrfs filesystem)



I'm looking for something smarter than



cat /dev/zero > /mnt/X/big_zero ; sync; rm /mnt/X/big_zero


Like FSArchiver is looking for "used space" and ignores unused, but opposite site.



Purpose: I'd like to compress partition images, so filling unused space with zeros is highly recommended.



Btw. For ext3,ext4 : Clear unused space with zeros (ext3,ext4) . Here I ask for btrfs



Clarification of "smarter algorithm": As I see that "smarter algorithm" leads to confusion, here I finally decided to add line about it. Dear reader, please think about filesystem as datastructure. For simplification purposes, let's imagine self balancing red-black tree holding map, that is used as association key->value array, where values are integers. Goal is to clear all negative values with zeros. "not smart" algorithm will iterate over it and add key:value pairs to new map (with eventual altering negative to zero). Smart algorithm will just detect places where negative values are stored and clear them in-place.










share|improve this question




















  • 2




    Did you try the sfill suggestion? It looks like it doesn't require extX.
    – Kevin
    Aug 3 '12 at 23:53










  • 1. I know you can fill existing files with zeros with shred, but this probably isn't it, right? 2.How are you making those images? Maybe you can do the truncation there?
    – Zlatko
    Aug 4 '12 at 0:23












  • @kevin: that's why i posted the sfill answer in the original question. i rarely use ext2,3,4 filesystems myself so i find utilities that work only on ext* to be annoyingly useless.
    – cas
    Aug 4 '12 at 3:00










  • I need something "smart". Something what only fills empty space with zeros without touching other places - I mean without affecting internal data-structures, like B-Trees (If your are curious, I've written in question "compression" but I need it also for other purposes, like fs images de-duplication, analysis and research)
    – Grzegorz Wierzowiecki
    Aug 5 '12 at 21:57










  • just use truncate and/or fallocate
    – mikeserv
    Dec 14 '14 at 1:20













up vote
9
down vote

favorite
4









up vote
9
down vote

favorite
4






4





How to clear unused space with zeros ? (I am asking for tool for btrfs filesystem)



I'm looking for something smarter than



cat /dev/zero > /mnt/X/big_zero ; sync; rm /mnt/X/big_zero


Like FSArchiver is looking for "used space" and ignores unused, but opposite site.



Purpose: I'd like to compress partition images, so filling unused space with zeros is highly recommended.



Btw. For ext3,ext4 : Clear unused space with zeros (ext3,ext4) . Here I ask for btrfs



Clarification of "smarter algorithm": As I see that "smarter algorithm" leads to confusion, here I finally decided to add line about it. Dear reader, please think about filesystem as datastructure. For simplification purposes, let's imagine self balancing red-black tree holding map, that is used as association key->value array, where values are integers. Goal is to clear all negative values with zeros. "not smart" algorithm will iterate over it and add key:value pairs to new map (with eventual altering negative to zero). Smart algorithm will just detect places where negative values are stored and clear them in-place.










share|improve this question















How to clear unused space with zeros ? (I am asking for tool for btrfs filesystem)



I'm looking for something smarter than



cat /dev/zero > /mnt/X/big_zero ; sync; rm /mnt/X/big_zero


Like FSArchiver is looking for "used space" and ignores unused, but opposite site.



Purpose: I'd like to compress partition images, so filling unused space with zeros is highly recommended.



Btw. For ext3,ext4 : Clear unused space with zeros (ext3,ext4) . Here I ask for btrfs



Clarification of "smarter algorithm": As I see that "smarter algorithm" leads to confusion, here I finally decided to add line about it. Dear reader, please think about filesystem as datastructure. For simplification purposes, let's imagine self balancing red-black tree holding map, that is used as association key->value array, where values are integers. Goal is to clear all negative values with zeros. "not smart" algorithm will iterate over it and add key:value pairs to new map (with eventual altering negative to zero). Smart algorithm will just detect places where negative values are stored and clear them in-place.







backup storage compression btrfs






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Apr 13 '17 at 12:36









Community

1




1










asked Aug 3 '12 at 23:39









Grzegorz Wierzowiecki

5,1631361104




5,1631361104








  • 2




    Did you try the sfill suggestion? It looks like it doesn't require extX.
    – Kevin
    Aug 3 '12 at 23:53










  • 1. I know you can fill existing files with zeros with shred, but this probably isn't it, right? 2.How are you making those images? Maybe you can do the truncation there?
    – Zlatko
    Aug 4 '12 at 0:23












  • @kevin: that's why i posted the sfill answer in the original question. i rarely use ext2,3,4 filesystems myself so i find utilities that work only on ext* to be annoyingly useless.
    – cas
    Aug 4 '12 at 3:00










  • I need something "smart". Something what only fills empty space with zeros without touching other places - I mean without affecting internal data-structures, like B-Trees (If your are curious, I've written in question "compression" but I need it also for other purposes, like fs images de-duplication, analysis and research)
    – Grzegorz Wierzowiecki
    Aug 5 '12 at 21:57










  • just use truncate and/or fallocate
    – mikeserv
    Dec 14 '14 at 1:20














  • 2




    Did you try the sfill suggestion? It looks like it doesn't require extX.
    – Kevin
    Aug 3 '12 at 23:53










  • 1. I know you can fill existing files with zeros with shred, but this probably isn't it, right? 2.How are you making those images? Maybe you can do the truncation there?
    – Zlatko
    Aug 4 '12 at 0:23












  • @kevin: that's why i posted the sfill answer in the original question. i rarely use ext2,3,4 filesystems myself so i find utilities that work only on ext* to be annoyingly useless.
    – cas
    Aug 4 '12 at 3:00










  • I need something "smart". Something what only fills empty space with zeros without touching other places - I mean without affecting internal data-structures, like B-Trees (If your are curious, I've written in question "compression" but I need it also for other purposes, like fs images de-duplication, analysis and research)
    – Grzegorz Wierzowiecki
    Aug 5 '12 at 21:57










  • just use truncate and/or fallocate
    – mikeserv
    Dec 14 '14 at 1:20








2




2




Did you try the sfill suggestion? It looks like it doesn't require extX.
– Kevin
Aug 3 '12 at 23:53




Did you try the sfill suggestion? It looks like it doesn't require extX.
– Kevin
Aug 3 '12 at 23:53












1. I know you can fill existing files with zeros with shred, but this probably isn't it, right? 2.How are you making those images? Maybe you can do the truncation there?
– Zlatko
Aug 4 '12 at 0:23






1. I know you can fill existing files with zeros with shred, but this probably isn't it, right? 2.How are you making those images? Maybe you can do the truncation there?
– Zlatko
Aug 4 '12 at 0:23














@kevin: that's why i posted the sfill answer in the original question. i rarely use ext2,3,4 filesystems myself so i find utilities that work only on ext* to be annoyingly useless.
– cas
Aug 4 '12 at 3:00




@kevin: that's why i posted the sfill answer in the original question. i rarely use ext2,3,4 filesystems myself so i find utilities that work only on ext* to be annoyingly useless.
– cas
Aug 4 '12 at 3:00












I need something "smart". Something what only fills empty space with zeros without touching other places - I mean without affecting internal data-structures, like B-Trees (If your are curious, I've written in question "compression" but I need it also for other purposes, like fs images de-duplication, analysis and research)
– Grzegorz Wierzowiecki
Aug 5 '12 at 21:57




I need something "smart". Something what only fills empty space with zeros without touching other places - I mean without affecting internal data-structures, like B-Trees (If your are curious, I've written in question "compression" but I need it also for other purposes, like fs images de-duplication, analysis and research)
– Grzegorz Wierzowiecki
Aug 5 '12 at 21:57












just use truncate and/or fallocate
– mikeserv
Dec 14 '14 at 1:20




just use truncate and/or fallocate
– mikeserv
Dec 14 '14 at 1:20










2 Answers
2






active

oldest

votes

















up vote
3
down vote













Here's a modified and much expanded repost of my answer to your previous question:



sfill from the secure-delete package can do what you want.



Unlike zerofree (which works only with ext2, ext3, and ext4 filesystems), sfill will work with any file system.



e.g.



sfill -l -l -z /mnt/X


The sfill/secure-delete home page is now seems to have vanished, but it is packaged for debian and ubuntu. probably other distros too. if you need source code, that can be found in the debian archives if you can't find it anywhere else.



NOTE: sfill only works on a mounted filesystem. If you're zero-filling the image files from the host system rather than from within a VM, you'll need to mount the fs image on the host. The exact method varies depending on what kind of image file it is (e.g. qcow2 or raw).



Mounting 'raw' images is easy and straight-forward. Just use kpartx on the image file to create a loopback device and /dev/mapper/ entries for each partition can then be mounted individually.



here's a partial script modified from a fragment of the script I use to mount net-bootable freedos hard-disk images (used for bios updates on machines where flashrom won't work):



image="myrawimagefile.img"

# use kpartx to build /dev/mapper device nodes
KP=$(kpartx -a -v "$image")

# now mount each partition under ./hd/
for p in $(echo "$KP" | awk '/^add map/ {print $3}') ; do
dm="/dev/mapper/$p"
fp=$(echo "$p" | sed -r -e 's/^loop[0-9]+//')
mkdir -p "./hd/$fp"
mount "$dm" "./hd/$fp"
sfill -l -l -v "./hd/$fp"
umount "$dm"
done

# now remove the loopback device and /dev/mapper entries
kpartx -d "$image"


NOTE: it assumes every partition in the image is mountable. true in my use-case (a freedos hd image with one partition). not true if one of the partitions is, say, swap space. Detecting such partitions and using dd to zero the swap partition is left as an exercise for the reader :)



This method, or a variant of it, should work for LVM volumes too.



If your images are qcow then you can use the qemu-nbd tool from the qemu-utils package, which will present the image file and its partitions as network block devices - e.g. /dev/nbd0 /dev/ndb0p1 - which can be used in a similar fashion to the /dev/mapper devices above.



It's possibly easier and less hassle (but more time-consuming) to use qemu-img to convert from qcow to raw, use the method for raw above, and then convert the modified raw image back to compressed qcow2. This will probably result in slightly smaller images than using qemu-nbd as you'll be compressing the new qcow2 image as it is being created.






share|improve this answer

















  • 1




    What I mean is, that it is not considered "smart" way of filling unused space with zeros. It's most obvious, typical way of doing this. I am not asking about things like that.
    – Grzegorz Wierzowiecki
    Aug 5 '12 at 12:49








  • 1




    Please describe a "smart" algorithm that isn't specific to a particular filesystem family (like zerofill is for ext2/3/4). You wanted a program that could do the job. You didn't say it had to be magical as well.
    – cas
    Aug 5 '12 at 13:08






  • 1




    and, really, if the filesystem is not in use (because, e.g., it's mounted on the host for zerofilling) what does it matter how smart the algorithm is? Trawling through the fs metadata looking for empty sectors isn't going to be any faster or better than just writing a huge fill full of NULs...the filesystem itself is already plenty smart enough for figuring out where empty space is.
    – cas
    Aug 5 '12 at 13:13






  • 2




    On the one hand, for your needs it's enough - so my question already contains code snippet with this solution - so your answer is not providing anything new. On the other hand, my needs require what I specify, because I want to wipe unused space with zeros without modifying internal structures (for example rebalancing "Dancing B-Trees" or other kind of data-structure (e.g. for analyses and de-duplication purposes)
    – Grzegorz Wierzowiecki
    Aug 6 '12 at 9:15






  • 2




    @cas - I think you're missing the fact that zero-filling is an essential step before compacting virtual-hard-drives in VMs. If you have a 500 GB expanding disk, with 10 GB of files and 10 GB of "empty" space (i.e. deleted files), running the naive "giant zero file" approach will take FAR longer, and require the VHD to bloat up to the full 500 GB. I'd bet the OP is assuming the utility has to be FS specific too.
    – Fake Name
    Dec 10 '13 at 8:47


















up vote
1
down vote













The correct and "smart" way to clear the free space is using:



fstrim /mountpoint


Use this on a mounted filesystem.



It's important to note that there is no security advantage to this. If you wish to clear your disk for security, back up your files, zero the entire disk with a command like "shred" and then restore your files.



However the solution works fine if your disk is a thin provision on a sparse filesystem and you wish to recover the unused space.






share|improve this answer





















    Your Answer








    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "106"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f44725%2fclear-unused-space-with-zeros-btrfs%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    3
    down vote













    Here's a modified and much expanded repost of my answer to your previous question:



    sfill from the secure-delete package can do what you want.



    Unlike zerofree (which works only with ext2, ext3, and ext4 filesystems), sfill will work with any file system.



    e.g.



    sfill -l -l -z /mnt/X


    The sfill/secure-delete home page is now seems to have vanished, but it is packaged for debian and ubuntu. probably other distros too. if you need source code, that can be found in the debian archives if you can't find it anywhere else.



    NOTE: sfill only works on a mounted filesystem. If you're zero-filling the image files from the host system rather than from within a VM, you'll need to mount the fs image on the host. The exact method varies depending on what kind of image file it is (e.g. qcow2 or raw).



    Mounting 'raw' images is easy and straight-forward. Just use kpartx on the image file to create a loopback device and /dev/mapper/ entries for each partition can then be mounted individually.



    here's a partial script modified from a fragment of the script I use to mount net-bootable freedos hard-disk images (used for bios updates on machines where flashrom won't work):



    image="myrawimagefile.img"

    # use kpartx to build /dev/mapper device nodes
    KP=$(kpartx -a -v "$image")

    # now mount each partition under ./hd/
    for p in $(echo "$KP" | awk '/^add map/ {print $3}') ; do
    dm="/dev/mapper/$p"
    fp=$(echo "$p" | sed -r -e 's/^loop[0-9]+//')
    mkdir -p "./hd/$fp"
    mount "$dm" "./hd/$fp"
    sfill -l -l -v "./hd/$fp"
    umount "$dm"
    done

    # now remove the loopback device and /dev/mapper entries
    kpartx -d "$image"


    NOTE: it assumes every partition in the image is mountable. true in my use-case (a freedos hd image with one partition). not true if one of the partitions is, say, swap space. Detecting such partitions and using dd to zero the swap partition is left as an exercise for the reader :)



    This method, or a variant of it, should work for LVM volumes too.



    If your images are qcow then you can use the qemu-nbd tool from the qemu-utils package, which will present the image file and its partitions as network block devices - e.g. /dev/nbd0 /dev/ndb0p1 - which can be used in a similar fashion to the /dev/mapper devices above.



    It's possibly easier and less hassle (but more time-consuming) to use qemu-img to convert from qcow to raw, use the method for raw above, and then convert the modified raw image back to compressed qcow2. This will probably result in slightly smaller images than using qemu-nbd as you'll be compressing the new qcow2 image as it is being created.






    share|improve this answer

















    • 1




      What I mean is, that it is not considered "smart" way of filling unused space with zeros. It's most obvious, typical way of doing this. I am not asking about things like that.
      – Grzegorz Wierzowiecki
      Aug 5 '12 at 12:49








    • 1




      Please describe a "smart" algorithm that isn't specific to a particular filesystem family (like zerofill is for ext2/3/4). You wanted a program that could do the job. You didn't say it had to be magical as well.
      – cas
      Aug 5 '12 at 13:08






    • 1




      and, really, if the filesystem is not in use (because, e.g., it's mounted on the host for zerofilling) what does it matter how smart the algorithm is? Trawling through the fs metadata looking for empty sectors isn't going to be any faster or better than just writing a huge fill full of NULs...the filesystem itself is already plenty smart enough for figuring out where empty space is.
      – cas
      Aug 5 '12 at 13:13






    • 2




      On the one hand, for your needs it's enough - so my question already contains code snippet with this solution - so your answer is not providing anything new. On the other hand, my needs require what I specify, because I want to wipe unused space with zeros without modifying internal structures (for example rebalancing "Dancing B-Trees" or other kind of data-structure (e.g. for analyses and de-duplication purposes)
      – Grzegorz Wierzowiecki
      Aug 6 '12 at 9:15






    • 2




      @cas - I think you're missing the fact that zero-filling is an essential step before compacting virtual-hard-drives in VMs. If you have a 500 GB expanding disk, with 10 GB of files and 10 GB of "empty" space (i.e. deleted files), running the naive "giant zero file" approach will take FAR longer, and require the VHD to bloat up to the full 500 GB. I'd bet the OP is assuming the utility has to be FS specific too.
      – Fake Name
      Dec 10 '13 at 8:47















    up vote
    3
    down vote













    Here's a modified and much expanded repost of my answer to your previous question:



    sfill from the secure-delete package can do what you want.



    Unlike zerofree (which works only with ext2, ext3, and ext4 filesystems), sfill will work with any file system.



    e.g.



    sfill -l -l -z /mnt/X


    The sfill/secure-delete home page is now seems to have vanished, but it is packaged for debian and ubuntu. probably other distros too. if you need source code, that can be found in the debian archives if you can't find it anywhere else.



    NOTE: sfill only works on a mounted filesystem. If you're zero-filling the image files from the host system rather than from within a VM, you'll need to mount the fs image on the host. The exact method varies depending on what kind of image file it is (e.g. qcow2 or raw).



    Mounting 'raw' images is easy and straight-forward. Just use kpartx on the image file to create a loopback device and /dev/mapper/ entries for each partition can then be mounted individually.



    here's a partial script modified from a fragment of the script I use to mount net-bootable freedos hard-disk images (used for bios updates on machines where flashrom won't work):



    image="myrawimagefile.img"

    # use kpartx to build /dev/mapper device nodes
    KP=$(kpartx -a -v "$image")

    # now mount each partition under ./hd/
    for p in $(echo "$KP" | awk '/^add map/ {print $3}') ; do
    dm="/dev/mapper/$p"
    fp=$(echo "$p" | sed -r -e 's/^loop[0-9]+//')
    mkdir -p "./hd/$fp"
    mount "$dm" "./hd/$fp"
    sfill -l -l -v "./hd/$fp"
    umount "$dm"
    done

    # now remove the loopback device and /dev/mapper entries
    kpartx -d "$image"


    NOTE: it assumes every partition in the image is mountable. true in my use-case (a freedos hd image with one partition). not true if one of the partitions is, say, swap space. Detecting such partitions and using dd to zero the swap partition is left as an exercise for the reader :)



    This method, or a variant of it, should work for LVM volumes too.



    If your images are qcow then you can use the qemu-nbd tool from the qemu-utils package, which will present the image file and its partitions as network block devices - e.g. /dev/nbd0 /dev/ndb0p1 - which can be used in a similar fashion to the /dev/mapper devices above.



    It's possibly easier and less hassle (but more time-consuming) to use qemu-img to convert from qcow to raw, use the method for raw above, and then convert the modified raw image back to compressed qcow2. This will probably result in slightly smaller images than using qemu-nbd as you'll be compressing the new qcow2 image as it is being created.






    share|improve this answer

















    • 1




      What I mean is, that it is not considered "smart" way of filling unused space with zeros. It's most obvious, typical way of doing this. I am not asking about things like that.
      – Grzegorz Wierzowiecki
      Aug 5 '12 at 12:49








    • 1




      Please describe a "smart" algorithm that isn't specific to a particular filesystem family (like zerofill is for ext2/3/4). You wanted a program that could do the job. You didn't say it had to be magical as well.
      – cas
      Aug 5 '12 at 13:08






    • 1




      and, really, if the filesystem is not in use (because, e.g., it's mounted on the host for zerofilling) what does it matter how smart the algorithm is? Trawling through the fs metadata looking for empty sectors isn't going to be any faster or better than just writing a huge fill full of NULs...the filesystem itself is already plenty smart enough for figuring out where empty space is.
      – cas
      Aug 5 '12 at 13:13






    • 2




      On the one hand, for your needs it's enough - so my question already contains code snippet with this solution - so your answer is not providing anything new. On the other hand, my needs require what I specify, because I want to wipe unused space with zeros without modifying internal structures (for example rebalancing "Dancing B-Trees" or other kind of data-structure (e.g. for analyses and de-duplication purposes)
      – Grzegorz Wierzowiecki
      Aug 6 '12 at 9:15






    • 2




      @cas - I think you're missing the fact that zero-filling is an essential step before compacting virtual-hard-drives in VMs. If you have a 500 GB expanding disk, with 10 GB of files and 10 GB of "empty" space (i.e. deleted files), running the naive "giant zero file" approach will take FAR longer, and require the VHD to bloat up to the full 500 GB. I'd bet the OP is assuming the utility has to be FS specific too.
      – Fake Name
      Dec 10 '13 at 8:47













    up vote
    3
    down vote










    up vote
    3
    down vote









    Here's a modified and much expanded repost of my answer to your previous question:



    sfill from the secure-delete package can do what you want.



    Unlike zerofree (which works only with ext2, ext3, and ext4 filesystems), sfill will work with any file system.



    e.g.



    sfill -l -l -z /mnt/X


    The sfill/secure-delete home page is now seems to have vanished, but it is packaged for debian and ubuntu. probably other distros too. if you need source code, that can be found in the debian archives if you can't find it anywhere else.



    NOTE: sfill only works on a mounted filesystem. If you're zero-filling the image files from the host system rather than from within a VM, you'll need to mount the fs image on the host. The exact method varies depending on what kind of image file it is (e.g. qcow2 or raw).



    Mounting 'raw' images is easy and straight-forward. Just use kpartx on the image file to create a loopback device and /dev/mapper/ entries for each partition can then be mounted individually.



    here's a partial script modified from a fragment of the script I use to mount net-bootable freedos hard-disk images (used for bios updates on machines where flashrom won't work):



    image="myrawimagefile.img"

    # use kpartx to build /dev/mapper device nodes
    KP=$(kpartx -a -v "$image")

    # now mount each partition under ./hd/
    for p in $(echo "$KP" | awk '/^add map/ {print $3}') ; do
    dm="/dev/mapper/$p"
    fp=$(echo "$p" | sed -r -e 's/^loop[0-9]+//')
    mkdir -p "./hd/$fp"
    mount "$dm" "./hd/$fp"
    sfill -l -l -v "./hd/$fp"
    umount "$dm"
    done

    # now remove the loopback device and /dev/mapper entries
    kpartx -d "$image"


    NOTE: it assumes every partition in the image is mountable. true in my use-case (a freedos hd image with one partition). not true if one of the partitions is, say, swap space. Detecting such partitions and using dd to zero the swap partition is left as an exercise for the reader :)



    This method, or a variant of it, should work for LVM volumes too.



    If your images are qcow then you can use the qemu-nbd tool from the qemu-utils package, which will present the image file and its partitions as network block devices - e.g. /dev/nbd0 /dev/ndb0p1 - which can be used in a similar fashion to the /dev/mapper devices above.



    It's possibly easier and less hassle (but more time-consuming) to use qemu-img to convert from qcow to raw, use the method for raw above, and then convert the modified raw image back to compressed qcow2. This will probably result in slightly smaller images than using qemu-nbd as you'll be compressing the new qcow2 image as it is being created.






    share|improve this answer












    Here's a modified and much expanded repost of my answer to your previous question:



    sfill from the secure-delete package can do what you want.



    Unlike zerofree (which works only with ext2, ext3, and ext4 filesystems), sfill will work with any file system.



    e.g.



    sfill -l -l -z /mnt/X


    The sfill/secure-delete home page is now seems to have vanished, but it is packaged for debian and ubuntu. probably other distros too. if you need source code, that can be found in the debian archives if you can't find it anywhere else.



    NOTE: sfill only works on a mounted filesystem. If you're zero-filling the image files from the host system rather than from within a VM, you'll need to mount the fs image on the host. The exact method varies depending on what kind of image file it is (e.g. qcow2 or raw).



    Mounting 'raw' images is easy and straight-forward. Just use kpartx on the image file to create a loopback device and /dev/mapper/ entries for each partition can then be mounted individually.



    here's a partial script modified from a fragment of the script I use to mount net-bootable freedos hard-disk images (used for bios updates on machines where flashrom won't work):



    image="myrawimagefile.img"

    # use kpartx to build /dev/mapper device nodes
    KP=$(kpartx -a -v "$image")

    # now mount each partition under ./hd/
    for p in $(echo "$KP" | awk '/^add map/ {print $3}') ; do
    dm="/dev/mapper/$p"
    fp=$(echo "$p" | sed -r -e 's/^loop[0-9]+//')
    mkdir -p "./hd/$fp"
    mount "$dm" "./hd/$fp"
    sfill -l -l -v "./hd/$fp"
    umount "$dm"
    done

    # now remove the loopback device and /dev/mapper entries
    kpartx -d "$image"


    NOTE: it assumes every partition in the image is mountable. true in my use-case (a freedos hd image with one partition). not true if one of the partitions is, say, swap space. Detecting such partitions and using dd to zero the swap partition is left as an exercise for the reader :)



    This method, or a variant of it, should work for LVM volumes too.



    If your images are qcow then you can use the qemu-nbd tool from the qemu-utils package, which will present the image file and its partitions as network block devices - e.g. /dev/nbd0 /dev/ndb0p1 - which can be used in a similar fashion to the /dev/mapper devices above.



    It's possibly easier and less hassle (but more time-consuming) to use qemu-img to convert from qcow to raw, use the method for raw above, and then convert the modified raw image back to compressed qcow2. This will probably result in slightly smaller images than using qemu-nbd as you'll be compressing the new qcow2 image as it is being created.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Aug 4 '12 at 3:34









    cas

    38.4k44999




    38.4k44999








    • 1




      What I mean is, that it is not considered "smart" way of filling unused space with zeros. It's most obvious, typical way of doing this. I am not asking about things like that.
      – Grzegorz Wierzowiecki
      Aug 5 '12 at 12:49








    • 1




      Please describe a "smart" algorithm that isn't specific to a particular filesystem family (like zerofill is for ext2/3/4). You wanted a program that could do the job. You didn't say it had to be magical as well.
      – cas
      Aug 5 '12 at 13:08






    • 1




      and, really, if the filesystem is not in use (because, e.g., it's mounted on the host for zerofilling) what does it matter how smart the algorithm is? Trawling through the fs metadata looking for empty sectors isn't going to be any faster or better than just writing a huge fill full of NULs...the filesystem itself is already plenty smart enough for figuring out where empty space is.
      – cas
      Aug 5 '12 at 13:13






    • 2




      On the one hand, for your needs it's enough - so my question already contains code snippet with this solution - so your answer is not providing anything new. On the other hand, my needs require what I specify, because I want to wipe unused space with zeros without modifying internal structures (for example rebalancing "Dancing B-Trees" or other kind of data-structure (e.g. for analyses and de-duplication purposes)
      – Grzegorz Wierzowiecki
      Aug 6 '12 at 9:15






    • 2




      @cas - I think you're missing the fact that zero-filling is an essential step before compacting virtual-hard-drives in VMs. If you have a 500 GB expanding disk, with 10 GB of files and 10 GB of "empty" space (i.e. deleted files), running the naive "giant zero file" approach will take FAR longer, and require the VHD to bloat up to the full 500 GB. I'd bet the OP is assuming the utility has to be FS specific too.
      – Fake Name
      Dec 10 '13 at 8:47














    • 1




      What I mean is, that it is not considered "smart" way of filling unused space with zeros. It's most obvious, typical way of doing this. I am not asking about things like that.
      – Grzegorz Wierzowiecki
      Aug 5 '12 at 12:49








    • 1




      Please describe a "smart" algorithm that isn't specific to a particular filesystem family (like zerofill is for ext2/3/4). You wanted a program that could do the job. You didn't say it had to be magical as well.
      – cas
      Aug 5 '12 at 13:08






    • 1




      and, really, if the filesystem is not in use (because, e.g., it's mounted on the host for zerofilling) what does it matter how smart the algorithm is? Trawling through the fs metadata looking for empty sectors isn't going to be any faster or better than just writing a huge fill full of NULs...the filesystem itself is already plenty smart enough for figuring out where empty space is.
      – cas
      Aug 5 '12 at 13:13






    • 2




      On the one hand, for your needs it's enough - so my question already contains code snippet with this solution - so your answer is not providing anything new. On the other hand, my needs require what I specify, because I want to wipe unused space with zeros without modifying internal structures (for example rebalancing "Dancing B-Trees" or other kind of data-structure (e.g. for analyses and de-duplication purposes)
      – Grzegorz Wierzowiecki
      Aug 6 '12 at 9:15






    • 2




      @cas - I think you're missing the fact that zero-filling is an essential step before compacting virtual-hard-drives in VMs. If you have a 500 GB expanding disk, with 10 GB of files and 10 GB of "empty" space (i.e. deleted files), running the naive "giant zero file" approach will take FAR longer, and require the VHD to bloat up to the full 500 GB. I'd bet the OP is assuming the utility has to be FS specific too.
      – Fake Name
      Dec 10 '13 at 8:47








    1




    1




    What I mean is, that it is not considered "smart" way of filling unused space with zeros. It's most obvious, typical way of doing this. I am not asking about things like that.
    – Grzegorz Wierzowiecki
    Aug 5 '12 at 12:49






    What I mean is, that it is not considered "smart" way of filling unused space with zeros. It's most obvious, typical way of doing this. I am not asking about things like that.
    – Grzegorz Wierzowiecki
    Aug 5 '12 at 12:49






    1




    1




    Please describe a "smart" algorithm that isn't specific to a particular filesystem family (like zerofill is for ext2/3/4). You wanted a program that could do the job. You didn't say it had to be magical as well.
    – cas
    Aug 5 '12 at 13:08




    Please describe a "smart" algorithm that isn't specific to a particular filesystem family (like zerofill is for ext2/3/4). You wanted a program that could do the job. You didn't say it had to be magical as well.
    – cas
    Aug 5 '12 at 13:08




    1




    1




    and, really, if the filesystem is not in use (because, e.g., it's mounted on the host for zerofilling) what does it matter how smart the algorithm is? Trawling through the fs metadata looking for empty sectors isn't going to be any faster or better than just writing a huge fill full of NULs...the filesystem itself is already plenty smart enough for figuring out where empty space is.
    – cas
    Aug 5 '12 at 13:13




    and, really, if the filesystem is not in use (because, e.g., it's mounted on the host for zerofilling) what does it matter how smart the algorithm is? Trawling through the fs metadata looking for empty sectors isn't going to be any faster or better than just writing a huge fill full of NULs...the filesystem itself is already plenty smart enough for figuring out where empty space is.
    – cas
    Aug 5 '12 at 13:13




    2




    2




    On the one hand, for your needs it's enough - so my question already contains code snippet with this solution - so your answer is not providing anything new. On the other hand, my needs require what I specify, because I want to wipe unused space with zeros without modifying internal structures (for example rebalancing "Dancing B-Trees" or other kind of data-structure (e.g. for analyses and de-duplication purposes)
    – Grzegorz Wierzowiecki
    Aug 6 '12 at 9:15




    On the one hand, for your needs it's enough - so my question already contains code snippet with this solution - so your answer is not providing anything new. On the other hand, my needs require what I specify, because I want to wipe unused space with zeros without modifying internal structures (for example rebalancing "Dancing B-Trees" or other kind of data-structure (e.g. for analyses and de-duplication purposes)
    – Grzegorz Wierzowiecki
    Aug 6 '12 at 9:15




    2




    2




    @cas - I think you're missing the fact that zero-filling is an essential step before compacting virtual-hard-drives in VMs. If you have a 500 GB expanding disk, with 10 GB of files and 10 GB of "empty" space (i.e. deleted files), running the naive "giant zero file" approach will take FAR longer, and require the VHD to bloat up to the full 500 GB. I'd bet the OP is assuming the utility has to be FS specific too.
    – Fake Name
    Dec 10 '13 at 8:47




    @cas - I think you're missing the fact that zero-filling is an essential step before compacting virtual-hard-drives in VMs. If you have a 500 GB expanding disk, with 10 GB of files and 10 GB of "empty" space (i.e. deleted files), running the naive "giant zero file" approach will take FAR longer, and require the VHD to bloat up to the full 500 GB. I'd bet the OP is assuming the utility has to be FS specific too.
    – Fake Name
    Dec 10 '13 at 8:47












    up vote
    1
    down vote













    The correct and "smart" way to clear the free space is using:



    fstrim /mountpoint


    Use this on a mounted filesystem.



    It's important to note that there is no security advantage to this. If you wish to clear your disk for security, back up your files, zero the entire disk with a command like "shred" and then restore your files.



    However the solution works fine if your disk is a thin provision on a sparse filesystem and you wish to recover the unused space.






    share|improve this answer

























      up vote
      1
      down vote













      The correct and "smart" way to clear the free space is using:



      fstrim /mountpoint


      Use this on a mounted filesystem.



      It's important to note that there is no security advantage to this. If you wish to clear your disk for security, back up your files, zero the entire disk with a command like "shred" and then restore your files.



      However the solution works fine if your disk is a thin provision on a sparse filesystem and you wish to recover the unused space.






      share|improve this answer























        up vote
        1
        down vote










        up vote
        1
        down vote









        The correct and "smart" way to clear the free space is using:



        fstrim /mountpoint


        Use this on a mounted filesystem.



        It's important to note that there is no security advantage to this. If you wish to clear your disk for security, back up your files, zero the entire disk with a command like "shred" and then restore your files.



        However the solution works fine if your disk is a thin provision on a sparse filesystem and you wish to recover the unused space.






        share|improve this answer












        The correct and "smart" way to clear the free space is using:



        fstrim /mountpoint


        Use this on a mounted filesystem.



        It's important to note that there is no security advantage to this. If you wish to clear your disk for security, back up your files, zero the entire disk with a command like "shred" and then restore your files.



        However the solution works fine if your disk is a thin provision on a sparse filesystem and you wish to recover the unused space.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 29 at 21:48









        DustWolf

        1212




        1212






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Unix & Linux Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f44725%2fclear-unused-space-with-zeros-btrfs%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Accessing regular linux commands in Huawei's Dopra Linux

            Can't connect RFCOMM socket: Host is down

            Kernel panic - not syncing: Fatal Exception in Interrupt