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