btrfs-progs: Fix wrong address accessing by subthread in btrfs-convert
[platform/upstream/btrfs-progs.git] / btrfs-image.c
index 634a714..3684a05 100644 (file)
@@ -16,8 +16,6 @@
  * Boston, MA 021110-1307, USA.
  */
 
-#define _XOPEN_SOURCE 500
-#define _GNU_SOURCE 1
 #include <pthread.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <unistd.h>
 #include <dirent.h>
 #include <zlib.h>
+#include <getopt.h>
+
 #include "kerncompat.h"
 #include "crc32c.h"
 #include "ctree.h"
 #include "disk-io.h"
 #include "transaction.h"
 #include "utils.h"
-#include "version.h"
 #include "volumes.h"
 #include "extent_io.h"
 
@@ -70,7 +69,9 @@ struct fs_chunk {
        u64 logical;
        u64 physical;
        u64 bytes;
-       struct rb_node n;
+       struct rb_node l;
+       struct rb_node p;
+       struct list_head list;
 };
 
 struct async_work {
@@ -107,6 +108,8 @@ struct metadump_struct {
        int done;
        int data;
        int sanitize_names;
+
+       int error;
 };
 
 struct name {
@@ -126,10 +129,14 @@ struct mdrestore_struct {
        pthread_cond_t cond;
 
        struct rb_root chunk_tree;
+       struct rb_root physical_tree;
        struct list_head list;
+       struct list_head overlapping_chunks;
        size_t num_items;
-       u64 leafsize;
+       u32 leafsize;
        u64 devid;
+       u64 alloced_chunks;
+       u64 last_physical_offset;
        u8 uuid[BTRFS_UUID_SIZE];
        u8 fsid[BTRFS_FSID_SIZE];
 
@@ -139,6 +146,7 @@ struct mdrestore_struct {
        int old_restore;
        int fixup_offset;
        int multi_devices;
+       int clear_space_cache;
        struct btrfs_fs_info *info;
 };
 
@@ -162,6 +170,7 @@ static int has_name(struct btrfs_key *key)
        case BTRFS_DIR_INDEX_KEY:
        case BTRFS_INODE_REF_KEY:
        case BTRFS_INODE_EXTREF_KEY:
+       case BTRFS_XATTR_ITEM_KEY:
                return 1;
        default:
                break;
@@ -201,8 +210,8 @@ static int name_cmp(struct rb_node *a, struct rb_node *b, int fuzz)
 
 static int chunk_cmp(struct rb_node *a, struct rb_node *b, int fuzz)
 {
-       struct fs_chunk *entry = rb_entry(a, struct fs_chunk, n);
-       struct fs_chunk *ins = rb_entry(b, struct fs_chunk, n);
+       struct fs_chunk *entry = rb_entry(a, struct fs_chunk, l);
+       struct fs_chunk *ins = rb_entry(b, struct fs_chunk, l);
 
        if (fuzz && ins->logical >= entry->logical &&
            ins->logical < entry->logical + entry->bytes)
@@ -215,6 +224,26 @@ static int chunk_cmp(struct rb_node *a, struct rb_node *b, int fuzz)
        return 0;
 }
 
+static int physical_cmp(struct rb_node *a, struct rb_node *b, int fuzz)
+{
+       struct fs_chunk *entry = rb_entry(a, struct fs_chunk, p);
+       struct fs_chunk *ins = rb_entry(b, struct fs_chunk, p);
+
+       if (fuzz && ins->physical >= entry->physical &&
+           ins->physical < entry->physical + entry->bytes)
+               return 0;
+
+       if (fuzz && entry->physical >= ins->physical &&
+           entry->physical < ins->physical + ins->bytes)
+               return 0;
+
+       if (ins->physical < entry->physical)
+               return -1;
+       else if (ins->physical > entry->physical)
+               return 1;
+       return 0;
+}
+
 static void tree_insert(struct rb_root *root, struct rb_node *ins,
                        int (*cmp)(struct rb_node *a, struct rb_node *b,
                                   int fuzz))
@@ -226,7 +255,7 @@ static void tree_insert(struct rb_root *root, struct rb_node *ins,
        while(*p) {
                parent = *p;
 
-               dir = cmp(*p, ins, 0);
+               dir = cmp(*p, ins, 1);
                if (dir < 0)
                        p = &(*p)->rb_left;
                else if (dir > 0)
@@ -261,6 +290,33 @@ static struct rb_node *tree_search(struct rb_root *root,
        return NULL;
 }
 
+static u64 logical_to_physical(struct mdrestore_struct *mdres, u64 logical, u64 *size)
+{
+       struct fs_chunk *fs_chunk;
+       struct rb_node *entry;
+       struct fs_chunk search;
+       u64 offset;
+
+       if (logical == BTRFS_SUPER_INFO_OFFSET)
+               return logical;
+
+       search.logical = logical;
+       entry = tree_search(&mdres->chunk_tree, &search.l, chunk_cmp, 1);
+       if (!entry) {
+               if (mdres->in != stdin)
+                       printf("Couldn't find a chunk, using logical\n");
+               return logical;
+       }
+       fs_chunk = rb_entry(entry, struct fs_chunk, l);
+       if (fs_chunk->logical > logical || fs_chunk->logical + fs_chunk->bytes < logical)
+               BUG();
+       offset = search.logical - fs_chunk->logical;
+
+       *size = min(*size, fs_chunk->bytes + fs_chunk->logical - logical);
+       return fs_chunk->physical + offset;
+}
+
+
 static char *find_collision(struct metadump_struct *md, char *name,
                            u32 name_len)
 {
@@ -283,6 +339,7 @@ static char *find_collision(struct metadump_struct *md, char *name,
        val = malloc(sizeof(struct name));
        if (!val) {
                fprintf(stderr, "Couldn't sanitize name, enomem\n");
+               free(name);
                return NULL;
        }
 
@@ -294,6 +351,7 @@ static char *find_collision(struct metadump_struct *md, char *name,
        if (!val->sub) {
                fprintf(stderr, "Couldn't sanitize name, enomem\n");
                free(val);
+               free(name);
                return NULL;
        }
 
@@ -310,11 +368,11 @@ static char *find_collision(struct metadump_struct *md, char *name,
                if (val->sub[i] == 127) {
                        do {
                                i++;
-                               if (i > name_len)
+                               if (i >= name_len)
                                        break;
                        } while (val->sub[i] == 127);
 
-                       if (i > name_len)
+                       if (i >= name_len)
                                break;
                        val->sub[i]++;
                        if (val->sub[i] == '/')
@@ -446,6 +504,21 @@ static void sanitize_inode_ref(struct metadump_struct *md,
        }
 }
 
+static void sanitize_xattr(struct metadump_struct *md,
+                          struct extent_buffer *eb, int slot)
+{
+       struct btrfs_dir_item *dir_item;
+       unsigned long data_ptr;
+       u32 data_len;
+
+       dir_item = btrfs_item_ptr(eb, slot, struct btrfs_dir_item);
+       data_len = btrfs_dir_data_len(eb, dir_item);
+
+       data_ptr = (unsigned long)((char *)(dir_item + 1) +
+                                  btrfs_dir_name_len(eb, dir_item));
+       memset_extent_buffer(eb, 0, data_ptr, data_len);
+}
+
 static void sanitize_name(struct metadump_struct *md, u8 *dst,
                          struct extent_buffer *src, struct btrfs_key *key,
                          int slot)
@@ -471,6 +544,9 @@ static void sanitize_name(struct metadump_struct *md, u8 *dst,
        case BTRFS_INODE_EXTREF_KEY:
                sanitize_inode_ref(md, eb, slot, 1);
                break;
+       case BTRFS_XATTR_ITEM_KEY:
+               sanitize_xattr(md, eb, slot);
+               break;
        default:
                break;
        }
@@ -494,7 +570,7 @@ static void zero_items(struct metadump_struct *md, u8 *dst,
        int i, extent_type;
 
        for (i = 0; i < nritems; i++) {
-               item = btrfs_item_nr(src, i);
+               item = btrfs_item_nr(i);
                btrfs_item_key_to_cpu(src, &key, i);
                if (key.type == BTRFS_CSUM_ITEM_KEY) {
                        size = btrfs_item_size_nr(src, i);
@@ -580,6 +656,14 @@ static void *dump_worker(void *data)
 
                        async->bufsize = compressBound(async->size);
                        async->buffer = malloc(async->bufsize);
+                       if (!async->buffer) {
+                               fprintf(stderr, "Error allocing buffer\n");
+                               pthread_mutex_lock(&md->mutex);
+                               if (!md->error)
+                                       md->error = -ENOMEM;
+                               pthread_mutex_unlock(&md->mutex);
+                               pthread_exit(NULL);
+                       }
 
                        ret = compress2(async->buffer,
                                         (unsigned long *)&async->bufsize,
@@ -613,6 +697,35 @@ static void meta_cluster_init(struct metadump_struct *md, u64 start)
                           COMPRESS_ZLIB : COMPRESS_NONE;
 }
 
+static void metadump_destroy(struct metadump_struct *md, int num_threads)
+{
+       int i;
+       struct rb_node *n;
+
+       pthread_mutex_lock(&md->mutex);
+       md->done = 1;
+       pthread_cond_broadcast(&md->cond);
+       pthread_mutex_unlock(&md->mutex);
+
+       for (i = 0; i < num_threads; i++)
+               pthread_join(md->threads[i], NULL);
+
+       pthread_cond_destroy(&md->cond);
+       pthread_mutex_destroy(&md->mutex);
+
+       while ((n = rb_first(&md->name_tree))) {
+               struct name *name;
+
+               name = rb_entry(n, struct name, n);
+               rb_erase(n, &md->name_tree);
+               free(name->val);
+               free(name->sub);
+               free(name);
+       }
+       free(md->threads);
+       free(md->cluster);
+}
+
 static int metadump_init(struct metadump_struct *md, struct btrfs_root *root,
                         FILE *out, int num_threads, int compress_level,
                         int sanitize_names)
@@ -659,53 +772,12 @@ static int metadump_init(struct metadump_struct *md, struct btrfs_root *root,
                        break;
        }
 
-       if (ret) {
-               pthread_mutex_lock(&md->mutex);
-               md->done = 1;
-               pthread_cond_broadcast(&md->cond);
-               pthread_mutex_unlock(&md->mutex);
-
-               for (i--; i >= 0; i--)
-                       pthread_join(md->threads[i], NULL);
-
-               pthread_cond_destroy(&md->cond);
-               pthread_mutex_destroy(&md->mutex);
-               free(md->cluster);
-               free(md->threads);
-       }
+       if (ret)
+               metadump_destroy(md, i + 1);
 
        return ret;
 }
 
-static void metadump_destroy(struct metadump_struct *md)
-{
-       int i;
-       struct rb_node *n;
-
-       pthread_mutex_lock(&md->mutex);
-       md->done = 1;
-       pthread_cond_broadcast(&md->cond);
-       pthread_mutex_unlock(&md->mutex);
-
-       for (i = 0; i < md->num_threads; i++)
-               pthread_join(md->threads[i], NULL);
-
-       pthread_cond_destroy(&md->cond);
-       pthread_mutex_destroy(&md->mutex);
-
-       while ((n = rb_first(&md->name_tree))) {
-               struct name *name;
-
-               name = rb_entry(n, struct name, n);
-               rb_erase(n, &md->name_tree);
-               free(name->val);
-               free(name->sub);
-               free(name);
-       }
-       free(md->threads);
-       free(md->cluster);
-}
-
 static int write_zero(FILE *out, size_t size)
 {
        static char zero[BLOCK_SIZE];
@@ -726,7 +798,7 @@ static int write_buffers(struct metadump_struct *md, u64 *next)
                goto out;
 
        /* wait until all buffers are compressed */
-       while (md->num_items > md->num_ready) {
+       while (!err && md->num_items > md->num_ready) {
                struct timespec ts = {
                        .tv_sec = 0,
                        .tv_nsec = 10000000,
@@ -734,6 +806,13 @@ static int write_buffers(struct metadump_struct *md, u64 *next)
                pthread_mutex_unlock(&md->mutex);
                nanosleep(&ts, NULL);
                pthread_mutex_lock(&md->mutex);
+               err = md->error;
+       }
+
+       if (err) {
+               fprintf(stderr, "One of the threads errored out %s\n",
+                               strerror(err));
+               goto out;
        }
 
        /* setup and write index block */
@@ -844,6 +923,15 @@ static int read_data_extent(struct metadump_struct *md,
        return 0;
 }
 
+static int get_dev_fd(struct btrfs_root *root)
+{
+       struct btrfs_device *dev;
+
+       dev = list_first_entry(&root->fs_info->fs_devices->devices,
+                              struct btrfs_device, dev_list);
+       return dev->fd;
+}
+
 static int flush_pending(struct metadump_struct *md, int done)
 {
        struct async_work *async = NULL;
@@ -880,10 +968,28 @@ static int flush_pending(struct metadump_struct *md, int done)
                        }
                }
 
+               /*
+                * Balance can make the mapping not cover the super block, so
+                * just copy directly from one of the devices.
+                */
+               if (start == BTRFS_SUPER_INFO_OFFSET) {
+                       int fd = get_dev_fd(md->root);
+
+                       ret = pread64(fd, async->buffer, size, start);
+                       if (ret < size) {
+                               free(async->buffer);
+                               free(async);
+                               fprintf(stderr, "Error reading superblock\n");
+                               return -EIO;
+                       }
+                       size = 0;
+                       ret = 0;
+               }
+
                while (!md->data && size > 0) {
                        u64 this_read = min(blocksize, size);
                        eb = read_tree_block(md->root, start, this_read, 0);
-                       if (!eb) {
+                       if (!extent_buffer_uptodate(eb)) {
                                free(async->buffer);
                                free(async);
                                fprintf(stderr,
@@ -1012,7 +1118,7 @@ static int copy_tree_blocks(struct btrfs_root *root, struct extent_buffer *eb,
                        ri = btrfs_item_ptr(eb, i, struct btrfs_root_item);
                        bytenr = btrfs_disk_root_bytenr(eb, ri);
                        tmp = read_tree_block(root, bytenr, root->leafsize, 0);
-                       if (!tmp) {
+                       if (!extent_buffer_uptodate(tmp)) {
                                fprintf(stderr,
                                        "Error reading log root block\n");
                                return -EIO;
@@ -1024,7 +1130,7 @@ static int copy_tree_blocks(struct btrfs_root *root, struct extent_buffer *eb,
                } else {
                        bytenr = btrfs_node_blockptr(eb, i);
                        tmp = read_tree_block(root, bytenr, root->leafsize, 0);
-                       if (!tmp) {
+                       if (!extent_buffer_uptodate(tmp)) {
                                fprintf(stderr, "Error reading log block\n");
                                return -EIO;
                        }
@@ -1080,8 +1186,9 @@ static int copy_space_cache(struct btrfs_root *root,
                return ret;
        }
 
+       leaf = path->nodes[0];
+
        while (1) {
-               leaf = path->nodes[0];
                if (path->slots[0] >= btrfs_header_nritems(leaf)) {
                        ret = btrfs_next_leaf(root, path);
                        if (ret < 0) {
@@ -1114,7 +1221,7 @@ static int copy_space_cache(struct btrfs_root *root,
                if (ret) {
                        fprintf(stderr, "Error adding space cache blocks %d\n",
                                ret);
-                       btrfs_release_path(root, path);
+                       btrfs_release_path(path);
                        return ret;
                }
                path->slots[0]++;
@@ -1135,7 +1242,7 @@ static int copy_from_extent_tree(struct metadump_struct *metadump,
        int ret;
 
        extent_root = metadump->root->fs_info->extent_root;
-       bytenr = BTRFS_SUPER_INFO_OFFSET + 4096;
+       bytenr = BTRFS_SUPER_INFO_OFFSET + BTRFS_SUPER_INFO_SIZE;
        key.objectid = bytenr;
        key.type = BTRFS_EXTENT_ITEM_KEY;
        key.offset = 0;
@@ -1147,8 +1254,9 @@ static int copy_from_extent_tree(struct metadump_struct *metadump,
        }
        ret = 0;
 
+       leaf = path->nodes[0];
+
        while (1) {
-               leaf = path->nodes[0];
                if (path->slots[0] >= btrfs_header_nritems(leaf)) {
                        ret = btrfs_next_leaf(extent_root, path);
                        if (ret < 0) {
@@ -1219,7 +1327,7 @@ static int copy_from_extent_tree(struct metadump_struct *metadump,
                bytenr += num_bytes;
        }
 
-       btrfs_release_path(extent_root, path);
+       btrfs_release_path(path);
 
        return ret;
 }
@@ -1249,7 +1357,8 @@ static int create_metadump(const char *input, FILE *out, int num_threads,
                return ret;
        }
 
-       ret = add_extent(BTRFS_SUPER_INFO_OFFSET, 4096, &metadump, 0);
+       ret = add_extent(BTRFS_SUPER_INFO_OFFSET, BTRFS_SUPER_INFO_SIZE,
+                       &metadump, 0);
        if (ret) {
                fprintf(stderr, "Error adding metadata %d\n", ret);
                err = ret;
@@ -1300,7 +1409,7 @@ out:
                fprintf(stderr, "Error flushing pending %d\n", ret);
        }
 
-       metadump_destroy(&metadump);
+       metadump_destroy(&metadump, num_threads);
 
        btrfs_free_path(path);
        ret = close_ctree(root);
@@ -1328,7 +1437,7 @@ static void update_super_old(u8 *buffer)
 
        btrfs_set_stack_chunk_length(chunk, (u64)-1);
        btrfs_set_stack_chunk_owner(chunk, BTRFS_EXTENT_TREE_OBJECTID);
-       btrfs_set_stack_chunk_stripe_len(chunk, 64 * 1024);
+       btrfs_set_stack_chunk_stripe_len(chunk, BTRFS_STRIPE_LEN);
        btrfs_set_stack_chunk_type(chunk, BTRFS_BLOCK_GROUP_SYSTEM);
        btrfs_set_stack_chunk_io_align(chunk, sectorsize);
        btrfs_set_stack_chunk_io_width(chunk, sectorsize);
@@ -1339,19 +1448,19 @@ static void update_super_old(u8 *buffer)
        btrfs_set_stack_stripe_offset(&chunk->stripe, 0);
        memcpy(chunk->stripe.dev_uuid, super->dev_item.uuid, BTRFS_UUID_SIZE);
        btrfs_set_super_sys_array_size(super, sizeof(*key) + sizeof(*chunk));
-       csum_block(buffer, 4096);
+       csum_block(buffer, BTRFS_SUPER_INFO_SIZE);
 }
 
-static int update_super(u8 *buffer)
+static int update_super(struct mdrestore_struct *mdres, u8 *buffer)
 {
        struct btrfs_super_block *super = (struct btrfs_super_block *)buffer;
        struct btrfs_chunk *chunk;
        struct btrfs_disk_key *disk_key;
        struct btrfs_key key;
+       u64 flags = btrfs_super_flags(super);
        u32 new_array_size = 0;
        u32 array_size;
        u32 cur = 0;
-       u32 new_cur = 0;
        u8 *ptr, *write_ptr;
        int old_num_stripes;
 
@@ -1368,9 +1477,10 @@ static int update_super(u8 *buffer)
                write_ptr += sizeof(*disk_key);
                ptr += sizeof(*disk_key);
                cur += sizeof(*disk_key);
-               new_cur += sizeof(*disk_key);
 
                if (key.type == BTRFS_CHUNK_ITEM_KEY) {
+                       u64 physical, size = 0;
+
                        chunk = (struct btrfs_chunk *)ptr;
                        old_num_stripes = btrfs_stack_chunk_num_stripes(chunk);
                        chunk = (struct btrfs_chunk *)write_ptr;
@@ -1380,11 +1490,16 @@ static int update_super(u8 *buffer)
                        btrfs_set_stack_chunk_sub_stripes(chunk, 0);
                        btrfs_set_stack_chunk_type(chunk,
                                                   BTRFS_BLOCK_GROUP_SYSTEM);
-                       chunk->stripe.devid = super->dev_item.devid;
+                       btrfs_set_stack_stripe_devid(&chunk->stripe,
+                                                    super->dev_item.devid);
+                       physical = logical_to_physical(mdres, key.offset,
+                                                      &size);
+                       if (size != (u64)-1)
+                               btrfs_set_stack_stripe_offset(&chunk->stripe,
+                                                             physical);
                        memcpy(chunk->stripe.dev_uuid, super->dev_item.uuid,
                               BTRFS_UUID_SIZE);
                        new_array_size += sizeof(*chunk);
-                       new_cur += sizeof(*chunk);
                } else {
                        fprintf(stderr, "Bogus key in the sys chunk array "
                                "%d\n", key.type);
@@ -1395,8 +1510,13 @@ static int update_super(u8 *buffer)
                cur += btrfs_chunk_item_size(old_num_stripes);
        }
 
+       if (mdres->clear_space_cache)
+               btrfs_set_super_cache_generation(super, 0);
+
+       flags |= BTRFS_SUPER_FLAG_METADUMP_V2;
+       btrfs_set_super_flags(super, flags);
        btrfs_set_super_sys_array_size(super, new_array_size);
-       csum_block(buffer, 4096);
+       csum_block(buffer, BTRFS_SUPER_INFO_SIZE);
 
        return 0;
 }
@@ -1437,7 +1557,7 @@ static void truncate_item(struct extent_buffer *eb, int slot, u32 new_size)
 
        for (i = slot; i < nritems; i++) {
                u32 ioff;
-               item = btrfs_item_nr(eb, i);
+               item = btrfs_item_nr(i);
                ioff = btrfs_item_offset(eb, item);
                btrfs_set_item_offset(eb, item, ioff + size_diff);
        }
@@ -1445,7 +1565,7 @@ static void truncate_item(struct extent_buffer *eb, int slot, u32 new_size)
        memmove_extent_buffer(eb, btrfs_leaf_data(eb) + data_end + size_diff,
                              btrfs_leaf_data(eb) + data_end,
                              old_data_start + new_size - data_end);
-       item = btrfs_item_nr(eb, slot);
+       item = btrfs_item_nr(slot);
        btrfs_set_item_size(eb, item, new_size);
 }
 
@@ -1485,7 +1605,7 @@ static int fixup_chunk_tree_block(struct mdrestore_struct *mdres,
                for (i = 0; i < btrfs_header_nritems(eb); i++) {
                        struct btrfs_chunk chunk;
                        struct btrfs_key key;
-                       u64 type;
+                       u64 type, physical, size = (u64)-1;
 
                        btrfs_item_key_to_cpu(eb, &key, i);
                        if (key.type != BTRFS_CHUNK_ITEM_KEY)
@@ -1495,16 +1615,24 @@ static int fixup_chunk_tree_block(struct mdrestore_struct *mdres,
                                           btrfs_item_ptr_offset(eb, i),
                                           sizeof(chunk));
 
+                       size = 0;
+                       physical = logical_to_physical(mdres, key.offset,
+                                                      &size);
+
                        /* Zero out the RAID profile */
                        type = btrfs_stack_chunk_type(&chunk);
                        type &= (BTRFS_BLOCK_GROUP_DATA |
                                 BTRFS_BLOCK_GROUP_SYSTEM |
-                                BTRFS_BLOCK_GROUP_METADATA);
+                                BTRFS_BLOCK_GROUP_METADATA |
+                                BTRFS_BLOCK_GROUP_DUP);
                        btrfs_set_stack_chunk_type(&chunk, type);
 
                        btrfs_set_stack_chunk_num_stripes(&chunk, 1);
                        btrfs_set_stack_chunk_sub_stripes(&chunk, 0);
                        btrfs_set_stack_stripe_devid(&chunk.stripe, mdres->devid);
+                       if (size != (u64)-1)
+                               btrfs_set_stack_stripe_offset(&chunk.stripe,
+                                                             physical);
                        memcpy(chunk.stripe.dev_uuid, mdres->uuid,
                               BTRFS_UUID_SIZE);
                        write_extent_buffer(eb, &chunk,
@@ -1519,6 +1647,7 @@ next:
                bytenr += mdres->leafsize;
        }
 
+       free(eb);
        return 0;
 }
 
@@ -1541,12 +1670,12 @@ static void write_backup_supers(int fd, u8 *buf)
 
        for (i = 1; i < BTRFS_SUPER_MIRROR_MAX; i++) {
                bytenr = btrfs_sb_offset(i);
-               if (bytenr + 4096 > size)
+               if (bytenr + BTRFS_SUPER_INFO_SIZE > size)
                        break;
                btrfs_set_super_bytenr(super, bytenr);
-               csum_block(buf, 4096);
-               ret = pwrite64(fd, buf, 4096, bytenr);
-               if (ret < 4096) {
+               csum_block(buf, BTRFS_SUPER_INFO_SIZE);
+               ret = pwrite64(fd, buf, BTRFS_SUPER_INFO_SIZE, bytenr);
+               if (ret < BTRFS_SUPER_INFO_SIZE) {
                        if (ret < 0)
                                fprintf(stderr, "Problem writing out backup "
                                        "super block %d, err %d\n", i, errno);
@@ -1558,32 +1687,6 @@ static void write_backup_supers(int fd, u8 *buf)
        }
 }
 
-static u64 logical_to_physical(struct mdrestore_struct *mdres, u64 logical, u64 *size)
-{
-       struct fs_chunk *fs_chunk;
-       struct rb_node *entry;
-       struct fs_chunk search;
-       u64 offset;
-
-       if (logical == BTRFS_SUPER_INFO_OFFSET)
-               return logical;
-
-       search.logical = logical;
-       entry = tree_search(&mdres->chunk_tree, &search.n, chunk_cmp, 1);
-       if (!entry) {
-               if (mdres->in != stdin)
-                       printf("Couldn't find a chunk, using logical\n");
-               return logical;
-       }
-       fs_chunk = rb_entry(entry, struct fs_chunk, n);
-       if (fs_chunk->logical > logical || fs_chunk->logical + fs_chunk->bytes < logical)
-               BUG();
-       offset = search.logical - fs_chunk->logical;
-
-       *size = min(*size, fs_chunk->bytes + fs_chunk->logical - logical);
-       return fs_chunk->physical + offset;
-}
-
 static void *restore_worker(void *data)
 {
        struct mdrestore_struct *mdres = (struct mdrestore_struct *)data;
@@ -1603,7 +1706,7 @@ static void *restore_worker(void *data)
                if (!mdres->error)
                        mdres->error = -ENOMEM;
                pthread_mutex_unlock(&mdres->mutex);
-               goto out;
+               pthread_exit(NULL);
        }
 
        while (1) {
@@ -1643,7 +1746,7 @@ static void *restore_worker(void *data)
                                if (mdres->old_restore) {
                                        update_super_old(outbuf);
                                } else {
-                                       ret = update_super(outbuf);
+                                       ret = update_super(mdres, outbuf);
                                        if (ret)
                                                err = ret;
                                }
@@ -1657,7 +1760,7 @@ static void *restore_worker(void *data)
                if (!mdres->fixup_offset) {
                        while (size) {
                                u64 chunk_size = size;
-                               if (!mdres->multi_devices)
+                               if (!mdres->multi_devices && !mdres->old_restore)
                                        bytenr = logical_to_physical(mdres,
                                                                     async->start + offset,
                                                                     &chunk_size);
@@ -1708,7 +1811,7 @@ out:
        pthread_exit(NULL);
 }
 
-static void mdrestore_destroy(struct mdrestore_struct *mdres)
+static void mdrestore_destroy(struct mdrestore_struct *mdres, int num_threads)
 {
        struct rb_node *n;
        int i;
@@ -1716,8 +1819,9 @@ static void mdrestore_destroy(struct mdrestore_struct *mdres)
        while ((n = rb_first(&mdres->chunk_tree))) {
                struct fs_chunk *entry;
 
-               entry = rb_entry(n, struct fs_chunk, n);
+               entry = rb_entry(n, struct fs_chunk, l);
                rb_erase(n, &mdres->chunk_tree);
+               rb_erase(&entry->p, &mdres->physical_tree);
                free(entry);
        }
        pthread_mutex_lock(&mdres->mutex);
@@ -1725,7 +1829,7 @@ static void mdrestore_destroy(struct mdrestore_struct *mdres)
        pthread_cond_broadcast(&mdres->cond);
        pthread_mutex_unlock(&mdres->mutex);
 
-       for (i = 0; i < mdres->num_threads; i++)
+       for (i = 0; i < num_threads; i++)
                pthread_join(mdres->threads[i], NULL);
 
        pthread_cond_destroy(&mdres->cond);
@@ -1744,6 +1848,7 @@ static int mdrestore_init(struct mdrestore_struct *mdres,
        pthread_cond_init(&mdres->cond, NULL);
        pthread_mutex_init(&mdres->mutex, NULL);
        INIT_LIST_HEAD(&mdres->list);
+       INIT_LIST_HEAD(&mdres->overlapping_chunks);
        mdres->in = in;
        mdres->out = out;
        mdres->old_restore = old_restore;
@@ -1751,6 +1856,9 @@ static int mdrestore_init(struct mdrestore_struct *mdres,
        mdres->fixup_offset = fixup_offset;
        mdres->info = info;
        mdres->multi_devices = multi_devices;
+       mdres->clear_space_cache = 0;
+       mdres->last_physical_offset = 0;
+       mdres->alloced_chunks = 0;
 
        if (!num_threads)
                return 0;
@@ -1766,7 +1874,7 @@ static int mdrestore_init(struct mdrestore_struct *mdres,
                        break;
        }
        if (ret)
-               mdrestore_destroy(mdres);
+               mdrestore_destroy(mdres, i + 1);
        return ret;
 }
 
@@ -1820,7 +1928,6 @@ static int add_cluster(struct meta_cluster *cluster,
        u32 i, nritems;
        int ret;
 
-       BUG_ON(mdres->num_items);
        mdres->compress_method = header->compress;
 
        bytenr = le64_to_cpu(header->bytenr) + BLOCK_SIZE;
@@ -1972,7 +2079,19 @@ static int read_chunk_block(struct mdrestore_struct *mdres, u8 *buffer,
                fs_chunk->logical = key.offset;
                fs_chunk->physical = btrfs_stack_stripe_offset(&chunk.stripe);
                fs_chunk->bytes = btrfs_stack_chunk_length(&chunk);
-               tree_insert(&mdres->chunk_tree, &fs_chunk->n, chunk_cmp);
+               INIT_LIST_HEAD(&fs_chunk->list);
+               if (tree_search(&mdres->physical_tree, &fs_chunk->p,
+                               physical_cmp, 1) != NULL)
+                       list_add(&fs_chunk->list, &mdres->overlapping_chunks);
+               else
+                       tree_insert(&mdres->physical_tree, &fs_chunk->p,
+                                   physical_cmp);
+               if (fs_chunk->physical + fs_chunk->bytes >
+                   mdres->last_physical_offset)
+                       mdres->last_physical_offset = fs_chunk->physical +
+                               fs_chunk->bytes;
+               mdres->alloced_chunks += fs_chunk->bytes;
+               tree_insert(&mdres->chunk_tree, &fs_chunk->l, chunk_cmp);
        }
 out:
        free(eb);
@@ -1989,6 +2108,7 @@ static int search_for_chunk_blocks(struct mdrestore_struct *mdres,
        u64 current_cluster = cluster_bytenr, bytenr;
        u64 item_bytenr;
        u32 bufsize, nritems, i;
+       u32 max_size = MAX_PENDING_SIZE * 2;
        u8 *buffer, *tmp = NULL;
        int ret = 0;
 
@@ -1998,7 +2118,7 @@ static int search_for_chunk_blocks(struct mdrestore_struct *mdres,
                return -ENOMEM;
        }
 
-       buffer = malloc(MAX_PENDING_SIZE * 2);
+       buffer = malloc(max_size);
        if (!buffer) {
                fprintf(stderr, "Error allocing buffer\n");
                free(cluster);
@@ -2006,7 +2126,7 @@ static int search_for_chunk_blocks(struct mdrestore_struct *mdres,
        }
 
        if (mdres->compress_method == COMPRESS_ZLIB) {
-               tmp = malloc(MAX_PENDING_SIZE * 2);
+               tmp = malloc(max_size);
                if (!tmp) {
                        fprintf(stderr, "Error allocing tmp buffer\n");
                        free(cluster);
@@ -2057,6 +2177,13 @@ static int search_for_chunk_blocks(struct mdrestore_struct *mdres,
                        bufsize = le32_to_cpu(item->size);
                        item_bytenr = le64_to_cpu(item->bytenr);
 
+                       if (bufsize > max_size) {
+                               fprintf(stderr, "item %u size %u too big\n",
+                                       i, bufsize);
+                               ret = -EIO;
+                               break;
+                       }
+
                        if (mdres->compress_method == COMPRESS_ZLIB) {
                                ret = fread(tmp, bufsize, 1, mdres->in);
                                if (ret != 1) {
@@ -2066,7 +2193,7 @@ static int search_for_chunk_blocks(struct mdrestore_struct *mdres,
                                        break;
                                }
 
-                               size = MAX_PENDING_SIZE * 2;
+                               size = max_size;
                                ret = uncompress(buffer,
                                                 (unsigned long *)&size, tmp,
                                                 bufsize);
@@ -2199,6 +2326,7 @@ static int build_chunk_tree(struct mdrestore_struct *mdres,
                buffer = tmp;
        }
 
+       pthread_mutex_lock(&mdres->mutex);
        super = (struct btrfs_super_block *)buffer;
        chunk_root_bytenr = btrfs_super_chunk_root(super);
        mdres->leafsize = btrfs_super_leafsize(super);
@@ -2207,13 +2335,148 @@ static int build_chunk_tree(struct mdrestore_struct *mdres,
                       BTRFS_UUID_SIZE);
        mdres->devid = le64_to_cpu(super->dev_item.devid);
        free(buffer);
+       pthread_mutex_unlock(&mdres->mutex);
 
        return search_for_chunk_blocks(mdres, chunk_root_bytenr, 0);
 }
 
-static int __restore_metadump(const char *input, FILE *out, int old_restore,
-                             int num_threads, int fixup_offset,
-                             const char *target, int multi_devices)
+static int range_contains_super(u64 physical, u64 bytes)
+{
+       u64 super_bytenr;
+       int i;
+
+       for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
+               super_bytenr = btrfs_sb_offset(i);
+               if (super_bytenr >= physical &&
+                   super_bytenr < physical + bytes)
+                       return 1;
+       }
+
+       return 0;
+}
+
+static void remap_overlapping_chunks(struct mdrestore_struct *mdres)
+{
+       struct fs_chunk *fs_chunk;
+
+       while (!list_empty(&mdres->overlapping_chunks)) {
+               fs_chunk = list_first_entry(&mdres->overlapping_chunks,
+                                           struct fs_chunk, list);
+               list_del_init(&fs_chunk->list);
+               if (range_contains_super(fs_chunk->physical,
+                                        fs_chunk->bytes)) {
+                       fprintf(stderr, "Remapping a chunk that had a super "
+                               "mirror inside of it, clearing space cache "
+                               "so we don't end up with corruption\n");
+                       mdres->clear_space_cache = 1;
+               }
+               fs_chunk->physical = mdres->last_physical_offset;
+               tree_insert(&mdres->physical_tree, &fs_chunk->p, physical_cmp);
+               mdres->last_physical_offset += fs_chunk->bytes;
+       }
+}
+
+static int fixup_devices(struct btrfs_fs_info *fs_info,
+                        struct mdrestore_struct *mdres, off_t dev_size)
+{
+       struct btrfs_trans_handle *trans;
+       struct btrfs_dev_item *dev_item;
+       struct btrfs_path *path;
+       struct extent_buffer *leaf;
+       struct btrfs_root *root = fs_info->chunk_root;
+       struct btrfs_key key;
+       u64 devid, cur_devid;
+       int ret;
+
+       path = btrfs_alloc_path();
+       if (!path) {
+               fprintf(stderr, "Error alloc'ing path\n");
+               return -ENOMEM;
+       }
+
+       trans = btrfs_start_transaction(fs_info->tree_root, 1);
+       if (IS_ERR(trans)) {
+               fprintf(stderr, "Error starting transaction %ld\n",
+                       PTR_ERR(trans));
+               btrfs_free_path(path);
+               return PTR_ERR(trans);
+       }
+
+       dev_item = &fs_info->super_copy->dev_item;
+
+       devid = btrfs_stack_device_id(dev_item);
+
+       btrfs_set_stack_device_total_bytes(dev_item, dev_size);
+       btrfs_set_stack_device_bytes_used(dev_item, mdres->alloced_chunks);
+
+       key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
+       key.type = BTRFS_DEV_ITEM_KEY;
+       key.offset = 0;
+
+again:
+       ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
+       if (ret < 0) {
+               fprintf(stderr, "search failed %d\n", ret);
+               exit(1);
+       }
+
+       while (1) {
+               leaf = path->nodes[0];
+               if (path->slots[0] >= btrfs_header_nritems(leaf)) {
+                       ret = btrfs_next_leaf(root, path);
+                       if (ret < 0) {
+                               fprintf(stderr, "Error going to next leaf "
+                                       "%d\n", ret);
+                               exit(1);
+                       }
+                       if (ret > 0) {
+                               ret = 0;
+                               break;
+                       }
+                       leaf = path->nodes[0];
+               }
+
+               btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
+               if (key.type > BTRFS_DEV_ITEM_KEY)
+                       break;
+               if (key.type != BTRFS_DEV_ITEM_KEY) {
+                       path->slots[0]++;
+                       continue;
+               }
+
+               dev_item = btrfs_item_ptr(leaf, path->slots[0],
+                                         struct btrfs_dev_item);
+               cur_devid = btrfs_device_id(leaf, dev_item);
+               if (devid != cur_devid) {
+                       ret = btrfs_del_item(trans, root, path);
+                       if (ret) {
+                               fprintf(stderr, "Error deleting item %d\n",
+                                       ret);
+                               exit(1);
+                       }
+                       btrfs_release_path(path);
+                       goto again;
+               }
+
+               btrfs_set_device_total_bytes(leaf, dev_item, dev_size);
+               btrfs_set_device_bytes_used(leaf, dev_item,
+                                           mdres->alloced_chunks);
+               btrfs_mark_buffer_dirty(leaf);
+               path->slots[0]++;
+       }
+
+       btrfs_free_path(path);
+       ret = btrfs_commit_transaction(trans, fs_info->tree_root);
+       if (ret) {
+               fprintf(stderr, "Commit failed %d\n", ret);
+               return ret;
+       }
+       return 0;
+}
+
+static int restore_metadump(const char *input, FILE *out, int old_restore,
+                           int num_threads, int fixup_offset,
+                           const char *target, int multi_devices)
 {
        struct meta_cluster *cluster = NULL;
        struct meta_cluster_header *header;
@@ -2236,7 +2499,10 @@ static int __restore_metadump(const char *input, FILE *out, int old_restore,
        /* NOTE: open with write mode */
        if (fixup_offset) {
                BUG_ON(!target);
-               info = open_ctree_fs_info_restore(target, 0, 0, 1, 1);
+               info = open_ctree_fs_info(target, 0, 0,
+                                         OPEN_CTREE_WRITES |
+                                         OPEN_CTREE_RESTORE |
+                                         OPEN_CTREE_PARTIAL);
                if (!info) {
                        fprintf(stderr, "%s: open ctree failed\n", __func__);
                        ret = -EIO;
@@ -2258,10 +2524,12 @@ static int __restore_metadump(const char *input, FILE *out, int old_restore,
                goto failed_cluster;
        }
 
-       if (!multi_devices) {
+       if (!multi_devices && !old_restore) {
                ret = build_chunk_tree(&mdrestore, cluster);
                if (ret)
                        goto out;
+               if (!list_empty(&mdrestore.overlapping_chunks))
+                       remap_overlapping_chunks(&mdrestore);
        }
 
        if (in != stdin && fseek(in, 0, SEEK_SET)) {
@@ -2269,7 +2537,7 @@ static int __restore_metadump(const char *input, FILE *out, int old_restore,
                goto out;
        }
 
-       while (1) {
+       while (!mdrestore.error) {
                ret = fread(cluster, BLOCK_SIZE, 1, in);
                if (!ret)
                        break;
@@ -2286,16 +2554,37 @@ static int __restore_metadump(const char *input, FILE *out, int old_restore,
                        fprintf(stderr, "Error adding cluster\n");
                        break;
                }
+       }
+       ret = wait_for_worker(&mdrestore);
 
-               ret = wait_for_worker(&mdrestore);
-               if (ret) {
-                       fprintf(stderr, "One of the threads errored out %d\n",
-                               ret);
-                       break;
+       if (!ret && !multi_devices && !old_restore) {
+               struct btrfs_root *root;
+               struct stat st;
+
+               root = open_ctree_fd(fileno(out), target, 0,
+                                         OPEN_CTREE_PARTIAL |
+                                         OPEN_CTREE_WRITES |
+                                         OPEN_CTREE_NO_DEVICES);
+               if (!root) {
+                       fprintf(stderr, "unable to open %s\n", target);
+                       ret = -EIO;
+                       goto out;
                }
+               info = root->fs_info;
+
+               if (stat(target, &st)) {
+                       fprintf(stderr, "statting %s failed\n", target);
+                       close_ctree(info->chunk_root);
+                       return 1;
+               }
+
+               ret = fixup_devices(info, &mdrestore, st.st_size);
+               close_ctree(info->chunk_root);
+               if (ret)
+                       goto out;
        }
 out:
-       mdrestore_destroy(&mdrestore);
+       mdrestore_destroy(&mdrestore, num_threads);
 failed_cluster:
        free(cluster);
 failed_info:
@@ -2307,19 +2596,6 @@ failed_open:
        return ret;
 }
 
-static int restore_metadump(const char *input, FILE *out, int old_restore,
-                           int num_threads, int multi_devices)
-{
-       return __restore_metadump(input, out, old_restore, num_threads, 0, NULL,
-                                 multi_devices);
-}
-
-static int fixup_metadump(const char *input, FILE *out, int num_threads,
-                         const char *target)
-{
-       return __restore_metadump(input, out, 0, num_threads, 1, target, 1);
-}
-
 static int update_disk_super_on_device(struct btrfs_fs_info *info,
                                       const char *other_dev, u64 cur_devid)
 {
@@ -2366,7 +2642,7 @@ static int update_disk_super_on_device(struct btrfs_fs_info *info,
        read_extent_buffer(leaf, dev_uuid, (unsigned long)btrfs_device_uuid(dev_item), BTRFS_UUID_SIZE);
        read_extent_buffer(leaf, fs_uuid, (unsigned long)btrfs_device_fsid(dev_item), BTRFS_UUID_SIZE);
 
-       btrfs_release_path(info->chunk_root, &path);
+       btrfs_release_path(&path);
 
        printk("update disk super on %s devid=%llu\n", other_dev, devid);
 
@@ -2380,7 +2656,8 @@ static int update_disk_super_on_device(struct btrfs_fs_info *info,
        buf = malloc(BTRFS_SUPER_INFO_SIZE);
        if (!buf) {
                ret = -ENOMEM;
-               exit(1);
+               close(fp);
+               return ret;
        }
 
        memcpy(buf, info->super_copy, BTRFS_SUPER_INFO_SIZE);
@@ -2413,7 +2690,7 @@ out:
        return 0;
 }
 
-static void print_usage(void)
+static void print_usage(int ret)
 {
        fprintf(stderr, "usage: btrfs-image [options] source target\n");
        fprintf(stderr, "\t-r      \trestore metadump image\n");
@@ -2422,15 +2699,19 @@ static void print_usage(void)
        fprintf(stderr, "\t-o      \tdon't mess with the chunk tree when restoring\n");
        fprintf(stderr, "\t-s      \tsanitize file names, use once to just use garbage, use twice if you want crc collisions\n");
        fprintf(stderr, "\t-w      \twalk all trees instead of using extent tree, do this if your extent tree is broken\n");
-       exit(1);
+       fprintf(stderr, "\t-m      \trestore for multiple devices\n");
+       fprintf(stderr, "\n");
+       fprintf(stderr, "\tIn the dump mode, source is the btrfs device and target is the output file (use '-' for stdout).\n");
+       fprintf(stderr, "\tIn the restore mode, source is the dumped image and target is the btrfs device/file.\n");
+       exit(ret);
 }
 
 int main(int argc, char *argv[])
 {
        char *source;
        char *target;
-       int num_threads = 0;
-       int compress_level = 0;
+       u64 num_threads = 1;
+       u64 compress_level = 0;
        int create = 1;
        int old_restore = 0;
        int walk_trees = 0;
@@ -2438,10 +2719,15 @@ int main(int argc, char *argv[])
        int ret;
        int sanitize = 0;
        int dev_cnt = 0;
+       int usage_error = 0;
        FILE *out;
 
        while (1) {
-               int c = getopt(argc, argv, "rc:t:oswm");
+               static const struct option long_options[] = {
+                       { "help", no_argument, NULL, GETOPT_VAL_HELP},
+                       { NULL, 0, NULL, 0 }
+               };
+               int c = getopt_long(argc, argv, "rc:t:oswm", long_options, NULL);
                if (c < 0)
                        break;
                switch (c) {
@@ -2449,14 +2735,14 @@ int main(int argc, char *argv[])
                        create = 0;
                        break;
                case 't':
-                       num_threads = atoi(optarg);
-                       if (num_threads <= 0 || num_threads > 32)
-                               print_usage();
+                       num_threads = arg_strtou64(optarg);
+                       if (num_threads > 32)
+                               print_usage(1);
                        break;
                case 'c':
-                       compress_level = atoi(optarg);
-                       if (compress_level < 0 || compress_level > 9)
-                               print_usage();
+                       compress_level = arg_strtou64(optarg);
+                       if (compress_level > 9)
+                               print_usage(1);
                        break;
                case 'o':
                        old_restore = 1;
@@ -2471,21 +2757,41 @@ int main(int argc, char *argv[])
                        create = 0;
                        multi_devices = 1;
                        break;
+                       case GETOPT_VAL_HELP:
                default:
-                       print_usage();
+                       print_usage(c != GETOPT_VAL_HELP);
                }
        }
 
-       if ((old_restore) && create)
-               print_usage();
-
        argc = argc - optind;
+       set_argv0(argv);
+       if (check_argc_min(argc, 2))
+               print_usage(1);
+
        dev_cnt = argc - 1;
 
-       if (multi_devices && dev_cnt < 2)
-               print_usage();
-       if (!multi_devices && dev_cnt != 1)
-               print_usage();
+       if (create) {
+               if (old_restore) {
+                       fprintf(stderr, "Usage error: create and restore cannot be used at the same time\n");
+                       usage_error++;
+               }
+       } else {
+               if (walk_trees || sanitize || compress_level) {
+                       fprintf(stderr, "Usage error: use -w, -s, -c options for restore makes no sense\n");
+                       usage_error++;
+               }
+               if (multi_devices && dev_cnt < 2) {
+                       fprintf(stderr, "Usage error: not enough devices specified for -m option\n");
+                       usage_error++;
+               }
+               if (!multi_devices && dev_cnt != 1) {
+                       fprintf(stderr, "Usage error: accepts only 1 device without -m option\n");
+                       usage_error++;
+               }
+       }
+
+       if (usage_error)
+               print_usage(1);
 
        source = argv[optind];
        target = argv[optind + 1];
@@ -2500,18 +2806,28 @@ int main(int argc, char *argv[])
                }
        }
 
-       if (num_threads == 0 && compress_level > 0) {
+       if (num_threads == 1 && compress_level > 0) {
                num_threads = sysconf(_SC_NPROCESSORS_ONLN);
                if (num_threads <= 0)
                        num_threads = 1;
        }
 
-       if (create)
+       if (create) {
+               ret = check_mounted(source);
+               if (ret < 0) {
+                       fprintf(stderr, "Could not check mount status: %s\n",
+                               strerror(-ret));
+                       exit(1);
+               } else if (ret)
+                       fprintf(stderr,
+               "WARNING: The device is mounted. Make sure the filesystem is quiescent.\n");
+
                ret = create_metadump(source, out, num_threads,
                                      compress_level, sanitize, walk_trees);
-       else
-               ret = restore_metadump(source, out, old_restore, 1,
-                                      multi_devices);
+       } else {
+               ret = restore_metadump(source, out, old_restore, num_threads,
+                                      0, target, multi_devices);
+       }
        if (ret) {
                printk("%s failed (%s)\n", (create) ? "create" : "restore",
                       strerror(errno));
@@ -2524,7 +2840,9 @@ int main(int argc, char *argv[])
                u64 total_devs;
                int i;
 
-               info = open_ctree_fs_info_restore(target, 0, 0, 0, 1);
+               info = open_ctree_fs_info(target, 0, 0,
+                                         OPEN_CTREE_PARTIAL |
+                                         OPEN_CTREE_RESTORE);
                if (!info) {
                        int e = errno;
                        fprintf(stderr, "unable to open %s error = %s\n",
@@ -2555,19 +2873,29 @@ int main(int argc, char *argv[])
                close_ctree(info->chunk_root);
 
                /* fix metadata block to map correct chunk */
-               ret = fixup_metadump(source, out, 1, target);
+               ret = restore_metadump(source, out, 0, num_threads, 1,
+                                      target, 1);
                if (ret) {
                        fprintf(stderr, "fix metadump failed (error=%d)\n",
                                ret);
                        exit(1);
                }
        }
-
 out:
-       if (out == stdout)
+       if (out == stdout) {
                fflush(out);
-       else
+       } else {
                fclose(out);
+               if (ret && create) {
+                       int unlink_ret;
 
-       return ret;
+                       unlink_ret = unlink(target);
+                       if (unlink_ret)
+                               fprintf(stderr,
+                                       "unlink output file failed : %s\n",
+                                       strerror(errno));
+               }
+       }
+
+       return !!ret;
 }