a361bf465b2705a6dcd9e932e40cd3a3f7e7bd41
[platform/upstream/btrfs-progs.git] / btrfs-corrupt-block.c
1 /*
2  * Copyright (C) 2009 Oracle.  All rights reserved.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public
6  * License v2 as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public
14  * License along with this program; if not, write to the
15  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16  * Boston, MA 021110-1307, USA.
17  */
18
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <fcntl.h>
22 #include <unistd.h>
23 #include <getopt.h>
24 #include "kerncompat.h"
25 #include "ctree.h"
26 #include "volumes.h"
27 #include "disk-io.h"
28 #include "print-tree.h"
29 #include "transaction.h"
30 #include "list.h"
31 #include "version.h"
32 #include "utils.h"
33
34 #define FIELD_BUF_LEN 80
35
36 struct extent_buffer *debug_corrupt_block(struct btrfs_root *root, u64 bytenr,
37                                      u32 blocksize, u64 copy)
38 {
39         int ret;
40         struct extent_buffer *eb;
41         u64 length;
42         struct btrfs_multi_bio *multi = NULL;
43         struct btrfs_device *device;
44         int num_copies;
45         int mirror_num = 1;
46
47         eb = btrfs_find_create_tree_block(root, bytenr, blocksize);
48         if (!eb)
49                 return NULL;
50
51         length = blocksize;
52         while (1) {
53                 ret = btrfs_map_block(&root->fs_info->mapping_tree, READ,
54                                       eb->start, &length, &multi,
55                                       mirror_num, NULL);
56                 BUG_ON(ret);
57                 device = multi->stripes[0].dev;
58                 eb->fd = device->fd;
59                 device->total_ios++;
60                 eb->dev_bytenr = multi->stripes[0].physical;
61
62                 fprintf(stdout,
63                         "mirror %d logical %llu physical %llu device %s\n",
64                         mirror_num, (unsigned long long)bytenr,
65                         (unsigned long long)eb->dev_bytenr, device->name);
66                 kfree(multi);
67
68                 if (!copy || mirror_num == copy) {
69                         ret = read_extent_from_disk(eb, 0, eb->len);
70                         printf("corrupting %llu copy %d\n", eb->start,
71                                mirror_num);
72                         memset(eb->data, 0, eb->len);
73                         write_extent_to_disk(eb);
74                         fsync(eb->fd);
75                 }
76
77                 num_copies = btrfs_num_copies(&root->fs_info->mapping_tree,
78                                               eb->start, eb->len);
79                 if (num_copies == 1)
80                         break;
81
82                 mirror_num++;
83                 if (mirror_num > num_copies)
84                         break;
85         }
86         return eb;
87 }
88
89 static void print_usage(void)
90 {
91         fprintf(stderr, "usage: btrfs-corrupt-block [options] device\n");
92         fprintf(stderr, "\t-l Logical extent to be corrupted\n");
93         fprintf(stderr, "\t-c Copy of the extent to be corrupted"
94                 " (usually 1 or 2, default: 0)\n");
95         fprintf(stderr, "\t-b Number of bytes to be corrupted\n");
96         fprintf(stderr, "\t-e Extent to be corrupted\n");
97         fprintf(stderr, "\t-E The whole extent tree to be corrupted\n");
98         fprintf(stderr, "\t-u Given chunk item to be corrupted\n");
99         fprintf(stderr, "\t-U The whole chunk tree to be corrupted\n");
100         fprintf(stderr, "\t-i The inode item to corrupt (must also specify "
101                 "the field to corrupt)\n");
102         fprintf(stderr, "\t-x The file extent item to corrupt (must also "
103                 "specify -i for the inode and -f for the field to corrupt)\n");
104         fprintf(stderr, "\t-m The metadata block to corrupt (must also "
105                 "specify -f for the field to corrupt)\n");
106         fprintf(stderr, "\t-K The key to corrupt in the format "
107                 "<num>,<num>,<num> (must also specify -f for the field)\n");
108         fprintf(stderr, "\t-f The field in the item to corrupt\n");
109         fprintf(stderr, "\t-I An item to corrupt (must also specify the field "
110                 "to corrupt and a root+key for the item)\n");
111         fprintf(stderr, "\t-D Corrupt a dir item, must specify key and field\n");
112         fprintf(stderr, "\t-d Delete this item (must specify -K)\n");
113         exit(1);
114 }
115
116 static void corrupt_keys(struct btrfs_trans_handle *trans,
117                          struct btrfs_root *root,
118                          struct extent_buffer *eb)
119 {
120         int slot;
121         int bad_slot;
122         int nr;
123         struct btrfs_disk_key bad_key;;
124
125         nr = btrfs_header_nritems(eb);
126         if (nr == 0)
127                 return;
128
129         slot = rand() % nr;
130         bad_slot = rand() % nr;
131
132         if (bad_slot == slot)
133                 return;
134
135         fprintf(stderr,
136                 "corrupting keys in block %llu slot %d swapping with %d\n",
137                 (unsigned long long)eb->start, slot, bad_slot);
138
139         if (btrfs_header_level(eb) == 0) {
140                 btrfs_item_key(eb, &bad_key, bad_slot);
141                 btrfs_set_item_key(eb, &bad_key, slot);
142         } else {
143                 btrfs_node_key(eb, &bad_key, bad_slot);
144                 btrfs_set_node_key(eb, &bad_key, slot);
145         }
146         btrfs_mark_buffer_dirty(eb);
147         if (!trans) {
148                 u16 csum_size =
149                         btrfs_super_csum_size(root->fs_info->super_copy);
150                 csum_tree_block_size(eb, csum_size, 0);
151                 write_extent_to_disk(eb);
152         }
153 }
154
155
156 static int corrupt_keys_in_block(struct btrfs_root *root, u64 bytenr)
157 {
158         struct extent_buffer *eb;
159
160         eb = read_tree_block(root, bytenr, root->leafsize, 0);
161         if (!eb)
162                 return -EIO;;
163
164         corrupt_keys(NULL, root, eb);
165         free_extent_buffer(eb);
166         return 0;
167 }
168
169 static int corrupt_extent(struct btrfs_trans_handle *trans,
170                           struct btrfs_root *root, u64 bytenr, u64 copy)
171 {
172         struct btrfs_key key;
173         struct extent_buffer *leaf;
174         u32 item_size;
175         unsigned long ptr;
176         struct btrfs_path *path;
177         int ret;
178         int slot;
179         int should_del = rand() % 3;
180
181         path = btrfs_alloc_path();
182         if (!path)
183                 return -ENOMEM;
184
185         key.objectid = bytenr;
186         key.type = (u8)-1;
187         key.offset = (u64)-1;
188
189         while(1) {
190                 ret = btrfs_search_slot(trans, root->fs_info->extent_root,
191                                         &key, path, -1, 1);
192                 if (ret < 0)
193                         break;
194
195                 if (ret > 0) {
196                         if (path->slots[0] == 0)
197                                 break;
198                         path->slots[0]--;
199                         ret = 0;
200                 }
201                 leaf = path->nodes[0];
202                 slot = path->slots[0];
203                 btrfs_item_key_to_cpu(leaf, &key, slot);
204                 if (key.objectid != bytenr)
205                         break;
206
207                 if (key.type != BTRFS_EXTENT_ITEM_KEY &&
208                     key.type != BTRFS_TREE_BLOCK_REF_KEY &&
209                     key.type != BTRFS_EXTENT_DATA_REF_KEY &&
210                     key.type != BTRFS_EXTENT_REF_V0_KEY &&
211                     key.type != BTRFS_SHARED_BLOCK_REF_KEY &&
212                     key.type != BTRFS_SHARED_DATA_REF_KEY)
213                         goto next;
214
215                 if (should_del) {
216                         fprintf(stderr,
217                                 "deleting extent record: key %llu %u %llu\n",
218                                 key.objectid, key.type, key.offset);
219
220                         if (key.type == BTRFS_EXTENT_ITEM_KEY) {
221                                 /* make sure this extent doesn't get
222                                  * reused for other purposes */
223                                 btrfs_pin_extent(root->fs_info,
224                                                  key.objectid, key.offset);
225                         }
226
227                         btrfs_del_item(trans, root, path);
228                 } else {
229                         fprintf(stderr,
230                                 "corrupting extent record: key %llu %u %llu\n",
231                                 key.objectid, key.type, key.offset);
232                         ptr = btrfs_item_ptr_offset(leaf, slot);
233                         item_size = btrfs_item_size_nr(leaf, slot);
234                         memset_extent_buffer(leaf, 0, ptr, item_size);
235                         btrfs_mark_buffer_dirty(leaf);
236                 }
237 next:
238                 btrfs_release_path(path);
239
240                 if (key.offset > 0)
241                         key.offset--;
242                 if (key.offset == 0)
243                         break;
244         }
245
246         btrfs_free_path(path);
247         return 0;
248 }
249
250 static void btrfs_corrupt_extent_leaf(struct btrfs_trans_handle *trans,
251                                       struct btrfs_root *root,
252                                       struct extent_buffer *eb)
253 {
254         u32 nr = btrfs_header_nritems(eb);
255         u32 victim = rand() % nr;
256         u64 objectid;
257         struct btrfs_key key;
258
259         btrfs_item_key_to_cpu(eb, &key, victim);
260         objectid = key.objectid;
261         corrupt_extent(trans, root, objectid, 1);
262 }
263
264 static void btrfs_corrupt_extent_tree(struct btrfs_trans_handle *trans,
265                                       struct btrfs_root *root,
266                                       struct extent_buffer *eb)
267 {
268         int i;
269
270         if (!eb)
271                 return;
272
273         if (btrfs_is_leaf(eb)) {
274                 btrfs_corrupt_extent_leaf(trans, root, eb);
275                 return;
276         }
277
278         if (btrfs_header_level(eb) == 1 && eb != root->node) {
279                 if (rand() % 5)
280                         return;
281         }
282
283         for (i = 0; i < btrfs_header_nritems(eb); i++) {
284                 struct extent_buffer *next;
285
286                 next = read_tree_block(root, btrfs_node_blockptr(eb, i),
287                                        root->leafsize,
288                                        btrfs_node_ptr_generation(eb, i));
289                 if (!next)
290                         continue;
291                 btrfs_corrupt_extent_tree(trans, root, next);
292                 free_extent_buffer(next);
293         }
294 }
295
296 enum btrfs_inode_field {
297         BTRFS_INODE_FIELD_ISIZE,
298         BTRFS_INODE_FIELD_BAD,
299 };
300
301 enum btrfs_file_extent_field {
302         BTRFS_FILE_EXTENT_DISK_BYTENR,
303         BTRFS_FILE_EXTENT_BAD,
304 };
305
306 enum btrfs_dir_item_field {
307         BTRFS_DIR_ITEM_NAME,
308         BTRFS_DIR_ITEM_LOCATION_OBJECTID,
309         BTRFS_DIR_ITEM_BAD,
310 };
311
312 enum btrfs_metadata_block_field {
313         BTRFS_METADATA_BLOCK_GENERATION,
314         BTRFS_METADATA_BLOCK_SHIFT_ITEMS,
315         BTRFS_METADATA_BLOCK_BAD,
316 };
317
318 enum btrfs_item_field {
319         BTRFS_ITEM_OFFSET,
320         BTRFS_ITEM_BAD,
321 };
322
323 enum btrfs_key_field {
324         BTRFS_KEY_OBJECTID,
325         BTRFS_KEY_TYPE,
326         BTRFS_KEY_OFFSET,
327         BTRFS_KEY_BAD,
328 };
329
330 static enum btrfs_inode_field convert_inode_field(char *field)
331 {
332         if (!strncmp(field, "isize", FIELD_BUF_LEN))
333                 return BTRFS_INODE_FIELD_ISIZE;
334         return BTRFS_INODE_FIELD_BAD;
335 }
336
337 static enum btrfs_file_extent_field convert_file_extent_field(char *field)
338 {
339         if (!strncmp(field, "disk_bytenr", FIELD_BUF_LEN))
340                 return BTRFS_FILE_EXTENT_DISK_BYTENR;
341         return BTRFS_FILE_EXTENT_BAD;
342 }
343
344 static enum btrfs_metadata_block_field
345 convert_metadata_block_field(char *field)
346 {
347         if (!strncmp(field, "generation", FIELD_BUF_LEN))
348                 return BTRFS_METADATA_BLOCK_GENERATION;
349         if (!strncmp(field, "shift_items", FIELD_BUF_LEN))
350                 return BTRFS_METADATA_BLOCK_SHIFT_ITEMS;
351         return BTRFS_METADATA_BLOCK_BAD;
352 }
353
354 static enum btrfs_key_field convert_key_field(char *field)
355 {
356         if (!strncmp(field, "objectid", FIELD_BUF_LEN))
357                 return BTRFS_KEY_OBJECTID;
358         if (!strncmp(field, "type", FIELD_BUF_LEN))
359                 return BTRFS_KEY_TYPE;
360         if (!strncmp(field, "offset", FIELD_BUF_LEN))
361                 return BTRFS_KEY_OFFSET;
362         return BTRFS_KEY_BAD;
363 }
364
365 static enum btrfs_item_field convert_item_field(char *field)
366 {
367         if (!strncmp(field, "offset", FIELD_BUF_LEN))
368                 return BTRFS_ITEM_OFFSET;
369         return BTRFS_ITEM_BAD;
370 }
371
372 static enum btrfs_dir_item_field convert_dir_item_field(char *field)
373 {
374         if (!strncmp(field, "name", FIELD_BUF_LEN))
375                 return BTRFS_DIR_ITEM_NAME;
376         if (!strncmp(field, "location_objectid", FIELD_BUF_LEN))
377                 return BTRFS_DIR_ITEM_LOCATION_OBJECTID;
378         return BTRFS_DIR_ITEM_BAD;
379 }
380
381 static u64 generate_u64(u64 orig)
382 {
383         u64 ret;
384         do {
385                 ret = rand();
386         } while (ret == orig);
387         return ret;
388 }
389
390 static u32 generate_u32(u32 orig)
391 {
392         u32 ret;
393         do {
394                 ret = rand();
395         } while (ret == orig);
396         return ret;
397 }
398
399 static u8 generate_u8(u8 orig)
400 {
401         u8 ret;
402         do {
403                 ret = rand();
404         } while (ret == orig);
405         return ret;
406 }
407
408 static int corrupt_key(struct btrfs_root *root, struct btrfs_key *key,
409                        char *field)
410 {
411         enum btrfs_key_field corrupt_field = convert_key_field(field);
412         struct btrfs_path *path;
413         struct btrfs_trans_handle *trans;
414         int ret;
415
416         root = root->fs_info->fs_root;
417         if (corrupt_field == BTRFS_KEY_BAD) {
418                 fprintf(stderr, "Invalid field %s\n", field);
419                 return -EINVAL;
420         }
421
422         path = btrfs_alloc_path();
423         if (!path)
424                 return -ENOMEM;
425
426         trans = btrfs_start_transaction(root, 1);
427         if (IS_ERR(trans)) {
428                 btrfs_free_path(path);
429                 return PTR_ERR(trans);
430         }
431
432         ret = btrfs_search_slot(trans, root, key, path, 0, 1);
433         if (ret < 0)
434                 goto out;
435         if (ret > 0) {
436                 fprintf(stderr, "Couldn't find the key to corrupt\n");
437                 ret = -ENOENT;
438                 goto out;
439         }
440
441         switch (corrupt_field) {
442         case BTRFS_KEY_OBJECTID:
443                 key->objectid = generate_u64(key->objectid);
444                 break;
445         case BTRFS_KEY_TYPE:
446                 key->type = generate_u8(key->type);
447                 break;
448         case BTRFS_KEY_OFFSET:
449                 key->offset = generate_u64(key->objectid);
450                 break;
451         default:
452                 fprintf(stderr, "Invalid field %s, %d\n", field,
453                         corrupt_field);
454                 ret = -EINVAL;
455                 goto out;
456         }
457
458         btrfs_set_item_key_unsafe(root, path, key);
459 out:
460         btrfs_free_path(path);
461         btrfs_commit_transaction(trans, root);
462         return ret;
463 }
464
465 static int corrupt_dir_item(struct btrfs_root *root, struct btrfs_key *key,
466                             char *field)
467 {
468         struct btrfs_trans_handle *trans;
469         struct btrfs_dir_item *di;
470         struct btrfs_path *path;
471         char *name;
472         struct btrfs_key location;
473         struct btrfs_disk_key disk_key;
474         unsigned long name_ptr;
475         enum btrfs_dir_item_field corrupt_field =
476                 convert_dir_item_field(field);
477         u64 bogus;
478         u16 name_len;
479         int ret;
480
481         if (corrupt_field == BTRFS_DIR_ITEM_BAD) {
482                 fprintf(stderr, "Invalid field %s\n", field);
483                 return -EINVAL;
484         }
485
486         path = btrfs_alloc_path();
487         if (!path)
488                 return -ENOMEM;
489
490         trans = btrfs_start_transaction(root, 1);
491         if (IS_ERR(trans)) {
492                 btrfs_free_path(path);
493                 return PTR_ERR(trans);
494         }
495
496         ret = btrfs_search_slot(trans, root, key, path, 0, 1);
497         if (ret) {
498                 if (ret > 0)
499                         ret = -ENOENT;
500                 fprintf(stderr, "Error searching for dir item %d\n", ret);
501                 goto out;
502         }
503
504         di = btrfs_item_ptr(path->nodes[0], path->slots[0],
505                             struct btrfs_dir_item);
506
507         switch (corrupt_field) {
508         case BTRFS_DIR_ITEM_NAME:
509                 name_len = btrfs_dir_name_len(path->nodes[0], di);
510                 name = malloc(name_len);
511                 if (!name) {
512                         ret = -ENOMEM;
513                         goto out;
514                 }
515                 name_ptr = (unsigned long)(di + 1);
516                 read_extent_buffer(path->nodes[0], name, name_ptr, name_len);
517                 name[0]++;
518                 write_extent_buffer(path->nodes[0], name, name_ptr, name_len);
519                 btrfs_mark_buffer_dirty(path->nodes[0]);
520                 free(name);
521                 goto out;
522         case BTRFS_DIR_ITEM_LOCATION_OBJECTID:
523                 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &location);
524                 bogus = generate_u64(location.objectid);
525                 location.objectid = bogus;
526                 btrfs_cpu_key_to_disk(&disk_key, &location);
527                 btrfs_set_dir_item_key(path->nodes[0], di, &disk_key);
528                 btrfs_mark_buffer_dirty(path->nodes[0]);
529                 goto out;
530         default:
531                 ret = -EINVAL;
532                 goto out;
533         }
534 out:
535         btrfs_commit_transaction(trans, root);
536         btrfs_free_path(path);
537         return ret;
538 }
539
540 static int corrupt_inode(struct btrfs_trans_handle *trans,
541                          struct btrfs_root *root, u64 inode, char *field)
542 {
543         struct btrfs_inode_item *ei;
544         struct btrfs_path *path;
545         struct btrfs_key key;
546         enum btrfs_inode_field corrupt_field = convert_inode_field(field);
547         u64 bogus;
548         u64 orig;
549         int ret;
550
551         if (corrupt_field == BTRFS_INODE_FIELD_BAD) {
552                 fprintf(stderr, "Invalid field %s\n", field);
553                 return -EINVAL;
554         }
555
556         key.objectid = inode;
557         key.type = BTRFS_INODE_ITEM_KEY;
558         key.offset = (u64)-1;
559
560         path = btrfs_alloc_path();
561         if (!path)
562                 return -ENOMEM;
563
564         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
565         if (ret < 0)
566                 goto out;
567         if (ret) {
568                 if (!path->slots[0]) {
569                         fprintf(stderr, "Couldn't find inode %Lu\n", inode);
570                         ret = -ENOENT;
571                         goto out;
572                 }
573                 path->slots[0]--;
574                 ret = 0;
575         }
576
577         btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
578         if (key.objectid != inode) {
579                 fprintf(stderr, "Couldn't find inode %Lu\n", inode);
580                 ret = -ENOENT;
581                 goto out;
582         }
583
584         ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
585                             struct btrfs_inode_item);
586         switch (corrupt_field) {
587         case BTRFS_INODE_FIELD_ISIZE:
588                 orig = btrfs_inode_size(path->nodes[0], ei);
589                 bogus = generate_u64(orig);
590                 btrfs_set_inode_size(path->nodes[0], ei, bogus);
591                 break;
592         default:
593                 ret = -EINVAL;
594                 break;
595         }
596         btrfs_mark_buffer_dirty(path->nodes[0]);
597 out:
598         btrfs_free_path(path);
599         return ret;
600 }
601
602 static int corrupt_file_extent(struct btrfs_trans_handle *trans,
603                                struct btrfs_root *root, u64 inode, u64 extent,
604                                char *field)
605 {
606         struct btrfs_file_extent_item *fi;
607         struct btrfs_path *path;
608         struct btrfs_key key;
609         enum btrfs_file_extent_field corrupt_field;
610         u64 bogus;
611         u64 orig;
612         int ret = 0;
613
614         corrupt_field = convert_file_extent_field(field);
615         if (corrupt_field == BTRFS_FILE_EXTENT_BAD) {
616                 fprintf(stderr, "Invalid field %s\n", field);
617                 return -EINVAL;
618         }
619
620         key.objectid = inode;
621         key.type = BTRFS_EXTENT_DATA_KEY;
622         key.offset = extent;
623
624         path = btrfs_alloc_path();
625         if (!path)
626                 return -ENOMEM;
627
628         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
629         if (ret < 0)
630                 goto out;
631         if (ret) {
632                 fprintf(stderr, "Couldn't find extent %llu for inode %llu\n",
633                         extent, inode);
634                 ret = -ENOENT;
635                 goto out;
636         }
637
638         fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
639                             struct btrfs_file_extent_item);
640         switch (corrupt_field) {
641         case BTRFS_FILE_EXTENT_DISK_BYTENR:
642                 orig = btrfs_file_extent_disk_bytenr(path->nodes[0], fi);
643                 bogus = generate_u64(orig);
644                 btrfs_set_file_extent_disk_bytenr(path->nodes[0], fi, bogus);
645                 break;
646         default:
647                 ret = -EINVAL;
648                 break;
649         }
650         btrfs_mark_buffer_dirty(path->nodes[0]);
651 out:
652         btrfs_free_path(path);
653         return ret;
654 }
655
656 static void shift_items(struct btrfs_root *root, struct extent_buffer *eb)
657 {
658         int nritems = btrfs_header_nritems(eb);
659         int shift_space = btrfs_leaf_free_space(root, eb) / 2;
660         int slot = nritems / 2;
661         int i = 0;
662         unsigned int data_end = btrfs_item_offset_nr(eb, nritems - 1);
663
664         /* Shift the item data up to and including slot back by shift space */
665         memmove_extent_buffer(eb, btrfs_leaf_data(eb) + data_end - shift_space,
666                               btrfs_leaf_data(eb) + data_end,
667                               btrfs_item_offset_nr(eb, slot - 1) - data_end);
668
669         /* Now update the item pointers. */
670         for (i = nritems - 1; i >= slot; i--) {
671                 u32 offset = btrfs_item_offset_nr(eb, i);
672                 offset -= shift_space;
673                 btrfs_set_item_offset(eb, btrfs_item_nr(i), offset);
674         }
675 }
676
677 static int corrupt_metadata_block(struct btrfs_root *root, u64 block,
678                                   char *field)
679 {
680         struct btrfs_trans_handle *trans;
681         struct btrfs_path *path;
682         struct extent_buffer *eb;
683         struct btrfs_key key, root_key;
684         enum btrfs_metadata_block_field corrupt_field;
685         u64 root_objectid;
686         u64 orig, bogus;
687         u8 level;
688         int ret;
689
690         corrupt_field = convert_metadata_block_field(field);
691         if (corrupt_field == BTRFS_METADATA_BLOCK_BAD) {
692                 fprintf(stderr, "Invalid field %s\n", field);
693                 return -EINVAL;
694         }
695
696         eb = read_tree_block(root, block, root->leafsize, 0);
697         if (!eb) {
698                 fprintf(stderr, "Couldn't read in tree block %s\n", field);
699                 return -EINVAL;
700         }
701         root_objectid = btrfs_header_owner(eb);
702         level = btrfs_header_level(eb);
703         if (level)
704                 btrfs_node_key_to_cpu(eb, &key, 0);
705         else
706                 btrfs_item_key_to_cpu(eb, &key, 0);
707         free_extent_buffer(eb);
708
709         root_key.objectid = root_objectid;
710         root_key.type = BTRFS_ROOT_ITEM_KEY;
711         root_key.offset = (u64)-1;
712
713         root = btrfs_read_fs_root(root->fs_info, &root_key);
714         if (IS_ERR(root)) {
715                 fprintf(stderr, "Couldn't finde owner root %llu\n",
716                         key.objectid);
717                 return PTR_ERR(root);
718         }
719
720         path = btrfs_alloc_path();
721         if (!path)
722                 return -ENOMEM;
723
724         trans = btrfs_start_transaction(root, 1);
725         if (IS_ERR(trans)) {
726                 btrfs_free_path(path);
727                 fprintf(stderr, "Couldn't start transaction %ld\n",
728                         PTR_ERR(trans));
729                 return PTR_ERR(trans);
730         }
731
732         path->lowest_level = level;
733         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
734         if (ret < 0) {
735                 fprintf(stderr, "Error searching to node %d\n", ret);
736                 goto out;
737         }
738         eb = path->nodes[level];
739
740         ret = 0;
741         switch (corrupt_field) {
742         case BTRFS_METADATA_BLOCK_GENERATION:
743                 orig = btrfs_header_generation(eb);
744                 bogus = generate_u64(orig);
745                 btrfs_set_header_generation(eb, bogus);
746                 break;
747         case BTRFS_METADATA_BLOCK_SHIFT_ITEMS:
748                 shift_items(root, path->nodes[level]);
749                 break;
750         default:
751                 ret = -EINVAL;
752                 break;
753         }
754         btrfs_mark_buffer_dirty(path->nodes[level]);
755 out:
756         btrfs_commit_transaction(trans, root);
757         btrfs_free_path(path);
758         return ret;
759 }
760
761 static int corrupt_btrfs_item(struct btrfs_root *root, struct btrfs_key *key,
762                               char *field)
763 {
764         struct btrfs_trans_handle *trans;
765         struct btrfs_path *path;
766         enum btrfs_item_field corrupt_field;
767         u32 orig, bogus;
768         int ret;
769
770         corrupt_field = convert_item_field(field);
771         if (corrupt_field == BTRFS_ITEM_BAD) {
772                 fprintf(stderr, "Invalid field %s\n", field);
773                 return -EINVAL;
774         }
775
776         path = btrfs_alloc_path();
777         if (!path)
778                 return -ENOMEM;
779
780         trans = btrfs_start_transaction(root, 1);
781         if (IS_ERR(trans)) {
782                 btrfs_free_path(path);
783                 fprintf(stderr, "Couldn't start transaction %ld\n",
784                         PTR_ERR(trans));
785                 return PTR_ERR(trans);
786         }
787
788         ret = btrfs_search_slot(trans, root, key, path, 0, 1);
789         if (ret != 0) {
790                 fprintf(stderr, "Error searching to node %d\n", ret);
791                 goto out;
792         }
793
794         ret = 0;
795         switch (corrupt_field) {
796         case BTRFS_ITEM_OFFSET:
797                 orig = btrfs_item_offset_nr(path->nodes[0], path->slots[0]);
798                 bogus = generate_u32(orig);
799                 btrfs_set_item_offset(path->nodes[0],
800                                       btrfs_item_nr(path->slots[0]), bogus);
801                 break;
802         default:
803                 ret = -EINVAL;
804                 break;
805         }
806         btrfs_mark_buffer_dirty(path->nodes[0]);
807 out:
808         btrfs_commit_transaction(trans, root);
809         btrfs_free_path(path);
810         return ret;
811 }
812
813 static int delete_item(struct btrfs_root *root, struct btrfs_key *key)
814 {
815         struct btrfs_trans_handle *trans;
816         struct btrfs_path *path;
817         int ret;
818
819         path = btrfs_alloc_path();
820         if (!path)
821                 return -ENOMEM;
822
823         trans = btrfs_start_transaction(root, 1);
824         if (IS_ERR(trans)) {
825                 btrfs_free_path(path);
826                 fprintf(stderr, "Couldn't start transaction %ld\n",
827                         PTR_ERR(trans));
828                 return PTR_ERR(trans);
829         }
830
831         ret = btrfs_search_slot(trans, root, key, path, -1, 1);
832         if (ret) {
833                 if (ret > 0)
834                         ret = -ENOENT;
835                 fprintf(stderr, "Error searching to node %d\n", ret);
836                 goto out;
837         }
838         ret = btrfs_del_item(trans, root, path);
839         btrfs_mark_buffer_dirty(path->nodes[0]);
840 out:
841         btrfs_commit_transaction(trans, root);
842         btrfs_free_path(path);
843         return ret;
844 }
845
846 /* corrupt item using NO cow.
847  * Because chunk recover will recover based on whole partition scaning,
848  * If using COW, chunk recover will use the old item to recover,
849  * which is still OK but we want to check the ability to rebuild chunk
850  * not only restore the old ones */
851 int corrupt_item_nocow(struct btrfs_trans_handle *trans,
852                        struct btrfs_root *root, struct btrfs_path *path,
853                        int del)
854 {
855         int ret = 0;
856         struct btrfs_key key;
857         struct extent_buffer *leaf;
858         unsigned long ptr;
859         int slot;
860         u32 item_size;
861
862         leaf = path->nodes[0];
863         slot = path->slots[0];
864         /* Not deleting the first item of a leaf to keep leaf structure */
865         if (slot == 0)
866                 del = 0;
867         /* Only accept valid eb */
868         BUG_ON(!leaf->data || slot >= btrfs_header_nritems(leaf));
869         btrfs_item_key_to_cpu(leaf, &key, slot);
870         if (del) {
871                 fprintf(stdout, "Deleting key and data [%llu, %u, %llu].\n",
872                         key.objectid, key.type, key.offset);
873                 btrfs_del_item(trans, root, path);
874         } else {
875                 fprintf(stdout, "Corrupting key and data [%llu, %u, %llu].\n",
876                         key.objectid, key.type, key.offset);
877                 ptr = btrfs_item_ptr_offset(leaf, slot);
878                 item_size = btrfs_item_size_nr(leaf, slot);
879                 memset_extent_buffer(leaf, 0, ptr, item_size);
880                 btrfs_mark_buffer_dirty(leaf);
881         }
882         return ret;
883 }
884 int corrupt_chunk_tree(struct btrfs_trans_handle *trans,
885                        struct btrfs_root *root)
886 {
887         int ret;
888         int del;
889         int slot;
890         struct btrfs_path *path;
891         struct btrfs_key key;
892         struct btrfs_key found_key;
893         struct extent_buffer *leaf;
894
895         path = btrfs_alloc_path();
896         if (!path)
897                 return -ENOMEM;
898
899         key.objectid = (u64)-1;
900         key.offset = (u64)-1;
901         key.type = (u8)-1;
902
903         /* Here, cow and ins_len must equals 0 for the following reasons:
904          * 1) chunk recover is based on disk scanning, so COW should be
905          *    disabled in case the original chunk being scanned and
906          *    recovered using the old chunk.
907          * 2) if cow = 0, ins_len must also be set to 0, or BUG_ON will be
908          *    triggered.
909          */
910         ret = btrfs_search_slot(trans, root, &key, path, 0, 0);
911         BUG_ON(ret == 0);
912         if (ret < 0) {
913                 fprintf(stderr, "Error searching tree\n");
914                 goto free_out;
915         }
916         /* corrupt/del dev_item first */
917         while (!btrfs_previous_item(root, path, 0, BTRFS_DEV_ITEM_KEY)) {
918                 slot = path->slots[0];
919                 leaf = path->nodes[0];
920                 del = rand() % 3;
921                 /* Never delete the first item to keep the leaf structure */
922                 if (path->slots[0] == 0)
923                         del = 0;
924                 ret = corrupt_item_nocow(trans, root, path, del);
925                 if (ret)
926                         goto free_out;
927         }
928         btrfs_release_path(path);
929
930         /* Here, cow and ins_len must equals 0 for the following reasons:
931          * 1) chunk recover is based on disk scanning, so COW should be
932          *    disabled in case the original chunk being scanned and
933          *    recovered using the old chunk.
934          * 2) if cow = 0, ins_len must also be set to 0, or BUG_ON will be
935          *    triggered.
936          */
937         ret = btrfs_search_slot(trans, root, &key, path, 0, 0);
938         BUG_ON(ret == 0);
939         if (ret < 0) {
940                 fprintf(stderr, "Error searching tree\n");
941                 goto free_out;
942         }
943         /* corrupt/del chunk then*/
944         while (!btrfs_previous_item(root, path, 0, BTRFS_CHUNK_ITEM_KEY)) {
945                 slot = path->slots[0];
946                 leaf = path->nodes[0];
947                 del = rand() % 3;
948                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
949                 ret = corrupt_item_nocow(trans, root, path, del);
950                 if (ret)
951                         goto free_out;
952         }
953 free_out:
954         btrfs_free_path(path);
955         return ret;
956 }
957 int find_chunk_offset(struct btrfs_root *root,
958                       struct btrfs_path *path, u64 offset)
959 {
960         struct btrfs_key key;
961         int ret;
962
963         key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
964         key.type = BTRFS_CHUNK_ITEM_KEY;
965         key.offset = offset;
966
967         /* Here, cow and ins_len must equals 0 for following reasons:
968          * 1) chunk recover is based on disk scanning, so COW should
969          *    be disabled in case the original chunk being scanned
970          *    and recovered using the old chunk.
971          * 2) if cow = 0, ins_len must also be set to 0, or BUG_ON
972          *    will be triggered.
973          */
974         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
975         if (ret > 0) {
976                 fprintf(stderr, "Can't find chunk with given offset %llu\n",
977                         offset);
978                 goto out;
979         }
980         if (ret < 0) {
981                 fprintf(stderr, "Error searching chunk");
982                 goto out;
983         }
984 out:
985         return ret;
986
987 }
988 int main(int ac, char **av)
989 {
990         struct cache_tree root_cache;
991         struct btrfs_key key;
992         struct btrfs_root *root;
993         struct extent_buffer *eb;
994         char *dev;
995         /* chunk offset can be 0,so change to (u64)-1 */
996         u64 logical = (u64)-1;
997         int ret = 0;
998         u64 copy = 0;
999         u64 bytes = 4096;
1000         int extent_rec = 0;
1001         int extent_tree = 0;
1002         int corrupt_block_keys = 0;
1003         int chunk_rec = 0;
1004         int chunk_tree = 0;
1005         int corrupt_item = 0;
1006         int corrupt_di = 0;
1007         int delete = 0;
1008         u64 metadata_block = 0;
1009         u64 inode = 0;
1010         u64 file_extent = (u64)-1;
1011         char field[FIELD_BUF_LEN];
1012
1013         field[0] = '\0';
1014         srand(128);
1015         memset(&key, 0, sizeof(key));
1016
1017         while(1) {
1018                 int c;
1019                 int option_index = 0;
1020                 static const struct option long_options[] = {
1021                         /* { "byte-count", 1, NULL, 'b' }, */
1022                         { "logical", 1, NULL, 'l' },
1023                         { "copy", 1, NULL, 'c' },
1024                         { "bytes", 1, NULL, 'b' },
1025                         { "extent-record", 0, NULL, 'e' },
1026                         { "extent-tree", 0, NULL, 'E' },
1027                         { "keys", 0, NULL, 'k' },
1028                         { "chunk-record", 0, NULL, 'u' },
1029                         { "chunk-tree", 0, NULL, 'U' },
1030                         { "inode", 1, NULL, 'i'},
1031                         { "file-extent", 1, NULL, 'x'},
1032                         { "metadata-block", 1, NULL, 'm'},
1033                         { "field", 1, NULL, 'f'},
1034                         { "key", 1, NULL, 'K'},
1035                         { "item", 0, NULL, 'I'},
1036                         { "dir-item", 0, NULL, 'D'},
1037                         { "delete", 0, NULL, 'd'},
1038                         { NULL, 0, NULL, 0 }
1039                 };
1040
1041                 c = getopt_long(ac, av, "l:c:b:eEkuUi:f:x:m:K:IDd", long_options,
1042                                 &option_index);
1043                 if (c < 0)
1044                         break;
1045                 switch(c) {
1046                         case 'l':
1047                                 logical = arg_strtou64(optarg);
1048                                 break;
1049                         case 'c':
1050                                 copy = arg_strtou64(optarg);
1051                                 break;
1052                         case 'b':
1053                                 bytes = arg_strtou64(optarg);
1054                                 break;
1055                         case 'e':
1056                                 extent_rec = 1;
1057                                 break;
1058                         case 'E':
1059                                 extent_tree = 1;
1060                                 break;
1061                         case 'k':
1062                                 corrupt_block_keys = 1;
1063                                 break;
1064                         case 'u':
1065                                 chunk_rec = 1;
1066                                 break;
1067                         case 'U':
1068                                 chunk_tree = 1;
1069                                 break;
1070                         case 'i':
1071                                 inode = arg_strtou64(optarg);
1072                                 break;
1073                         case 'f':
1074                                 strncpy(field, optarg, FIELD_BUF_LEN);
1075                                 break;
1076                         case 'x':
1077                                 file_extent = arg_strtou64(optarg);
1078                                 break;
1079                         case 'm':
1080                                 metadata_block = arg_strtou64(optarg);
1081                                 break;
1082                         case 'K':
1083                                 ret = sscanf(optarg, "%llu,%u,%llu",
1084                                              &key.objectid,
1085                                              (unsigned int *)&key.type,
1086                                              &key.offset);
1087                                 if (ret != 3) {
1088                                         fprintf(stderr, "error reading key "
1089                                                 "%d\n", errno);
1090                                         print_usage();
1091                                 }
1092                                 break;
1093                         case 'D':
1094                                 corrupt_di = 1;
1095                                 break;
1096                         case 'I':
1097                                 corrupt_item = 1;
1098                                 break;
1099                         case 'd':
1100                                 delete = 1;
1101                                 break;
1102                         default:
1103                                 print_usage();
1104                 }
1105         }
1106         set_argv0(av);
1107         ac = ac - optind;
1108         if (check_argc_min(ac, 1))
1109                 print_usage();
1110         dev = av[optind];
1111
1112         radix_tree_init();
1113         cache_tree_init(&root_cache);
1114
1115         root = open_ctree(dev, 0, OPEN_CTREE_WRITES);
1116         if (!root) {
1117                 fprintf(stderr, "Open ctree failed\n");
1118                 exit(1);
1119         }
1120         if (extent_rec) {
1121                 struct btrfs_trans_handle *trans;
1122
1123                 if (logical == (u64)-1)
1124                         print_usage();
1125                 trans = btrfs_start_transaction(root, 1);
1126                 ret = corrupt_extent (trans, root, logical, 0);
1127                 btrfs_commit_transaction(trans, root);
1128                 goto out_close;
1129         }
1130         if (extent_tree) {
1131                 struct btrfs_trans_handle *trans;
1132                 trans = btrfs_start_transaction(root, 1);
1133                 btrfs_corrupt_extent_tree(trans, root->fs_info->extent_root,
1134                                           root->fs_info->extent_root->node);
1135                 btrfs_commit_transaction(trans, root);
1136                 goto out_close;
1137         }
1138         if (chunk_rec) {
1139                 struct btrfs_trans_handle *trans;
1140                 struct btrfs_path *path;
1141                 int del;
1142
1143                 if (logical == (u64)-1)
1144                         print_usage();
1145                 del = rand() % 3;
1146                 path = btrfs_alloc_path();
1147                 if (!path) {
1148                         fprintf(stderr, "path allocation failed\n");
1149                         goto out_close;
1150                 }
1151
1152                 if (find_chunk_offset(root->fs_info->chunk_root, path,
1153                                       logical) != 0) {
1154                         btrfs_free_path(path);
1155                         goto out_close;
1156                 }
1157                 trans = btrfs_start_transaction(root, 1);
1158                 ret = corrupt_item_nocow(trans, root->fs_info->chunk_root,
1159                                          path, del);
1160                 if (ret < 0)
1161                         fprintf(stderr, "Failed to corrupt chunk record\n");
1162                 btrfs_commit_transaction(trans, root);
1163                 goto out_close;
1164         }
1165         if (chunk_tree) {
1166                 struct btrfs_trans_handle *trans;
1167                 trans = btrfs_start_transaction(root, 1);
1168                 ret = corrupt_chunk_tree(trans, root->fs_info->chunk_root);
1169                 if (ret < 0)
1170                         fprintf(stderr, "Failed to corrupt chunk tree\n");
1171                 btrfs_commit_transaction(trans, root);
1172                 goto out_close;
1173         }
1174         if (inode) {
1175                 struct btrfs_trans_handle *trans;
1176
1177                 if (!strlen(field))
1178                         print_usage();
1179
1180                 trans = btrfs_start_transaction(root, 1);
1181                 if (file_extent == (u64)-1) {
1182                         printf("corrupting inode\n");
1183                         ret = corrupt_inode(trans, root, inode, field);
1184                 } else {
1185                         printf("corrupting file extent\n");
1186                         ret = corrupt_file_extent(trans, root, inode,
1187                                                   file_extent, field);
1188                 }
1189                 btrfs_commit_transaction(trans, root);
1190                 goto out_close;
1191         }
1192         if (metadata_block) {
1193                 if (!strlen(field))
1194                         print_usage();
1195                 ret = corrupt_metadata_block(root, metadata_block, field);
1196                 goto out_close;
1197         }
1198         if (corrupt_di) {
1199                 if (!key.objectid || !strlen(field))
1200                         print_usage();
1201                 ret = corrupt_dir_item(root, &key, field);
1202                 goto out_close;
1203         }
1204         if (corrupt_item) {
1205                 if (!key.objectid)
1206                         print_usage();
1207                 ret = corrupt_btrfs_item(root, &key, field);
1208         }
1209         if (delete) {
1210                 if (!key.objectid)
1211                         print_usage();
1212                 ret = delete_item(root, &key);
1213                 goto out_close;
1214         }
1215         if (key.objectid || key.offset || key.type) {
1216                 if (!strlen(field))
1217                         print_usage();
1218                 ret = corrupt_key(root, &key, field);
1219                 goto out_close;
1220         }
1221         /*
1222          * If we made it here and we have extent set then we didn't specify
1223          * inode and we're screwed.
1224          */
1225         if (file_extent != (u64)-1)
1226                 print_usage();
1227
1228         if (logical == (u64)-1)
1229                 print_usage();
1230
1231         if (bytes == 0)
1232                 bytes = root->sectorsize;
1233
1234         bytes = (bytes + root->sectorsize - 1) / root->sectorsize;
1235         bytes *= root->sectorsize;
1236
1237         while (bytes > 0) {
1238                 if (corrupt_block_keys) {
1239                         corrupt_keys_in_block(root, logical);
1240                 } else {
1241                         eb = debug_corrupt_block(root, logical,
1242                                                  root->sectorsize, copy);
1243                         free_extent_buffer(eb);
1244                 }
1245                 logical += root->sectorsize;
1246                 bytes -= root->sectorsize;
1247         }
1248         return ret;
1249 out_close:
1250         close_ctree(root);
1251         return ret;
1252 }