btrfs-progs: corrupt btrfs items in btrfs-corrup-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_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         return BTRFS_METADATA_BLOCK_BAD;
350 }
351
352 static enum btrfs_key_field convert_key_field(char *field)
353 {
354         if (!strncmp(field, "objectid", FIELD_BUF_LEN))
355                 return BTRFS_KEY_OBJECTID;
356         if (!strncmp(field, "type", FIELD_BUF_LEN))
357                 return BTRFS_KEY_TYPE;
358         if (!strncmp(field, "offset", FIELD_BUF_LEN))
359                 return BTRFS_KEY_OFFSET;
360         return BTRFS_KEY_BAD;
361 }
362
363 static enum btrfs_item_field convert_item_field(char *field)
364 {
365         if (!strncmp(field, "offset", FIELD_BUF_LEN))
366                 return BTRFS_ITEM_OFFSET;
367         return BTRFS_ITEM_BAD;
368 }
369
370 static enum btrfs_dir_item_field convert_dir_item_field(char *field)
371 {
372         if (!strncmp(field, "name", FIELD_BUF_LEN))
373                 return BTRFS_DIR_ITEM_NAME;
374         if (!strncmp(field, "location_objectid", FIELD_BUF_LEN))
375                 return BTRFS_DIR_ITEM_LOCATION_OBJECTID;
376         return BTRFS_DIR_ITEM_BAD;
377 }
378
379 static u64 generate_u64(u64 orig)
380 {
381         u64 ret;
382         do {
383                 ret = rand();
384         } while (ret == orig);
385         return ret;
386 }
387
388 static u32 generate_u32(u32 orig)
389 {
390         u32 ret;
391         do {
392                 ret = rand();
393         } while (ret == orig);
394         return ret;
395 }
396
397 static u8 generate_u8(u8 orig)
398 {
399         u8 ret;
400         do {
401                 ret = rand();
402         } while (ret == orig);
403         return ret;
404 }
405
406 static int corrupt_key(struct btrfs_root *root, struct btrfs_key *key,
407                        char *field)
408 {
409         enum btrfs_key_field corrupt_field = convert_key_field(field);
410         struct btrfs_path *path;
411         struct btrfs_trans_handle *trans;
412         int ret;
413
414         root = root->fs_info->fs_root;
415         if (corrupt_field == BTRFS_KEY_BAD) {
416                 fprintf(stderr, "Invalid field %s\n", field);
417                 return -EINVAL;
418         }
419
420         path = btrfs_alloc_path();
421         if (!path)
422                 return -ENOMEM;
423
424         trans = btrfs_start_transaction(root, 1);
425         if (IS_ERR(trans)) {
426                 btrfs_free_path(path);
427                 return PTR_ERR(trans);
428         }
429
430         ret = btrfs_search_slot(trans, root, key, path, 0, 1);
431         if (ret < 0)
432                 goto out;
433         if (ret > 0) {
434                 fprintf(stderr, "Couldn't find the key to corrupt\n");
435                 ret = -ENOENT;
436                 goto out;
437         }
438
439         switch (corrupt_field) {
440         case BTRFS_KEY_OBJECTID:
441                 key->objectid = generate_u64(key->objectid);
442                 break;
443         case BTRFS_KEY_TYPE:
444                 key->type = generate_u8(key->type);
445                 break;
446         case BTRFS_KEY_OFFSET:
447                 key->offset = generate_u64(key->objectid);
448                 break;
449         default:
450                 fprintf(stderr, "Invalid field %s, %d\n", field,
451                         corrupt_field);
452                 ret = -EINVAL;
453                 goto out;
454         }
455
456         btrfs_set_item_key_unsafe(root, path, key);
457 out:
458         btrfs_free_path(path);
459         btrfs_commit_transaction(trans, root);
460         return ret;
461 }
462
463 static int corrupt_dir_item(struct btrfs_root *root, struct btrfs_key *key,
464                             char *field)
465 {
466         struct btrfs_trans_handle *trans;
467         struct btrfs_dir_item *di;
468         struct btrfs_path *path;
469         char *name;
470         struct btrfs_key location;
471         struct btrfs_disk_key disk_key;
472         unsigned long name_ptr;
473         enum btrfs_dir_item_field corrupt_field =
474                 convert_dir_item_field(field);
475         u64 bogus;
476         u16 name_len;
477         int ret;
478
479         if (corrupt_field == BTRFS_DIR_ITEM_BAD) {
480                 fprintf(stderr, "Invalid field %s\n", field);
481                 return -EINVAL;
482         }
483
484         path = btrfs_alloc_path();
485         if (!path)
486                 return -ENOMEM;
487
488         trans = btrfs_start_transaction(root, 1);
489         if (IS_ERR(trans)) {
490                 btrfs_free_path(path);
491                 return PTR_ERR(trans);
492         }
493
494         ret = btrfs_search_slot(trans, root, key, path, 0, 1);
495         if (ret) {
496                 if (ret > 0)
497                         ret = -ENOENT;
498                 fprintf(stderr, "Error searching for dir item %d\n", ret);
499                 goto out;
500         }
501
502         di = btrfs_item_ptr(path->nodes[0], path->slots[0],
503                             struct btrfs_dir_item);
504
505         switch (corrupt_field) {
506         case BTRFS_DIR_ITEM_NAME:
507                 name_len = btrfs_dir_name_len(path->nodes[0], di);
508                 name = malloc(name_len);
509                 if (!name) {
510                         ret = -ENOMEM;
511                         goto out;
512                 }
513                 name_ptr = (unsigned long)(di + 1);
514                 read_extent_buffer(path->nodes[0], name, name_ptr, name_len);
515                 name[0]++;
516                 write_extent_buffer(path->nodes[0], name, name_ptr, name_len);
517                 btrfs_mark_buffer_dirty(path->nodes[0]);
518                 free(name);
519                 goto out;
520         case BTRFS_DIR_ITEM_LOCATION_OBJECTID:
521                 btrfs_dir_item_key_to_cpu(path->nodes[0], di, &location);
522                 bogus = generate_u64(location.objectid);
523                 location.objectid = bogus;
524                 btrfs_cpu_key_to_disk(&disk_key, &location);
525                 btrfs_set_dir_item_key(path->nodes[0], di, &disk_key);
526                 btrfs_mark_buffer_dirty(path->nodes[0]);
527                 goto out;
528         default:
529                 ret = -EINVAL;
530                 goto out;
531         }
532 out:
533         btrfs_commit_transaction(trans, root);
534         btrfs_free_path(path);
535         return ret;
536 }
537
538 static int corrupt_inode(struct btrfs_trans_handle *trans,
539                          struct btrfs_root *root, u64 inode, char *field)
540 {
541         struct btrfs_inode_item *ei;
542         struct btrfs_path *path;
543         struct btrfs_key key;
544         enum btrfs_inode_field corrupt_field = convert_inode_field(field);
545         u64 bogus;
546         u64 orig;
547         int ret;
548
549         if (corrupt_field == BTRFS_INODE_FIELD_BAD) {
550                 fprintf(stderr, "Invalid field %s\n", field);
551                 return -EINVAL;
552         }
553
554         key.objectid = inode;
555         key.type = BTRFS_INODE_ITEM_KEY;
556         key.offset = (u64)-1;
557
558         path = btrfs_alloc_path();
559         if (!path)
560                 return -ENOMEM;
561
562         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
563         if (ret < 0)
564                 goto out;
565         if (ret) {
566                 if (!path->slots[0]) {
567                         fprintf(stderr, "Couldn't find inode %Lu\n", inode);
568                         ret = -ENOENT;
569                         goto out;
570                 }
571                 path->slots[0]--;
572                 ret = 0;
573         }
574
575         btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
576         if (key.objectid != inode) {
577                 fprintf(stderr, "Couldn't find inode %Lu\n", inode);
578                 ret = -ENOENT;
579                 goto out;
580         }
581
582         ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
583                             struct btrfs_inode_item);
584         switch (corrupt_field) {
585         case BTRFS_INODE_FIELD_ISIZE:
586                 orig = btrfs_inode_size(path->nodes[0], ei);
587                 bogus = generate_u64(orig);
588                 btrfs_set_inode_size(path->nodes[0], ei, bogus);
589                 break;
590         default:
591                 ret = -EINVAL;
592                 break;
593         }
594         btrfs_mark_buffer_dirty(path->nodes[0]);
595 out:
596         btrfs_free_path(path);
597         return ret;
598 }
599
600 static int corrupt_file_extent(struct btrfs_trans_handle *trans,
601                                struct btrfs_root *root, u64 inode, u64 extent,
602                                char *field)
603 {
604         struct btrfs_file_extent_item *fi;
605         struct btrfs_path *path;
606         struct btrfs_key key;
607         enum btrfs_file_extent_field corrupt_field;
608         u64 bogus;
609         u64 orig;
610         int ret = 0;
611
612         corrupt_field = convert_file_extent_field(field);
613         if (corrupt_field == BTRFS_FILE_EXTENT_BAD) {
614                 fprintf(stderr, "Invalid field %s\n", field);
615                 return -EINVAL;
616         }
617
618         key.objectid = inode;
619         key.type = BTRFS_EXTENT_DATA_KEY;
620         key.offset = extent;
621
622         path = btrfs_alloc_path();
623         if (!path)
624                 return -ENOMEM;
625
626         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
627         if (ret < 0)
628                 goto out;
629         if (ret) {
630                 fprintf(stderr, "Couldn't find extent %llu for inode %llu\n",
631                         extent, inode);
632                 ret = -ENOENT;
633                 goto out;
634         }
635
636         fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
637                             struct btrfs_file_extent_item);
638         switch (corrupt_field) {
639         case BTRFS_FILE_EXTENT_DISK_BYTENR:
640                 orig = btrfs_file_extent_disk_bytenr(path->nodes[0], fi);
641                 bogus = generate_u64(orig);
642                 btrfs_set_file_extent_disk_bytenr(path->nodes[0], fi, bogus);
643                 break;
644         default:
645                 ret = -EINVAL;
646                 break;
647         }
648         btrfs_mark_buffer_dirty(path->nodes[0]);
649 out:
650         btrfs_free_path(path);
651         return ret;
652 }
653
654 static int corrupt_metadata_block(struct btrfs_root *root, u64 block,
655                                   char *field)
656 {
657         struct btrfs_trans_handle *trans;
658         struct btrfs_path *path;
659         struct extent_buffer *eb;
660         struct btrfs_key key, root_key;
661         enum btrfs_metadata_block_field corrupt_field;
662         u64 root_objectid;
663         u64 orig, bogus;
664         u8 level;
665         int ret;
666
667         corrupt_field = convert_metadata_block_field(field);
668         if (corrupt_field == BTRFS_METADATA_BLOCK_BAD) {
669                 fprintf(stderr, "Invalid field %s\n", field);
670                 return -EINVAL;
671         }
672
673         eb = read_tree_block(root, block, root->leafsize, 0);
674         if (!eb) {
675                 fprintf(stderr, "Couldn't read in tree block %s\n", field);
676                 return -EINVAL;
677         }
678         root_objectid = btrfs_header_owner(eb);
679         level = btrfs_header_level(eb);
680         if (level)
681                 btrfs_node_key_to_cpu(eb, &key, 0);
682         else
683                 btrfs_item_key_to_cpu(eb, &key, 0);
684         free_extent_buffer(eb);
685
686         root_key.objectid = root_objectid;
687         root_key.type = BTRFS_ROOT_ITEM_KEY;
688         root_key.offset = (u64)-1;
689
690         root = btrfs_read_fs_root(root->fs_info, &root_key);
691         if (IS_ERR(root)) {
692                 fprintf(stderr, "Couldn't finde owner root %llu\n",
693                         key.objectid);
694                 return PTR_ERR(root);
695         }
696
697         path = btrfs_alloc_path();
698         if (!path)
699                 return -ENOMEM;
700
701         trans = btrfs_start_transaction(root, 1);
702         if (IS_ERR(trans)) {
703                 btrfs_free_path(path);
704                 fprintf(stderr, "Couldn't start transaction %ld\n",
705                         PTR_ERR(trans));
706                 return PTR_ERR(trans);
707         }
708
709         path->lowest_level = level;
710         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
711         if (ret < 0) {
712                 fprintf(stderr, "Error searching to node %d\n", ret);
713                 goto out;
714         }
715         eb = path->nodes[level];
716
717         ret = 0;
718         switch (corrupt_field) {
719         case BTRFS_METADATA_BLOCK_GENERATION:
720                 orig = btrfs_header_generation(eb);
721                 bogus = generate_u64(orig);
722                 btrfs_set_header_generation(eb, bogus);
723                 break;
724         default:
725                 ret = -EINVAL;
726                 break;
727         }
728         btrfs_mark_buffer_dirty(path->nodes[level]);
729 out:
730         btrfs_commit_transaction(trans, root);
731         btrfs_free_path(path);
732         return ret;
733 }
734
735 static int corrupt_btrfs_item(struct btrfs_root *root, struct btrfs_key *key,
736                               char *field)
737 {
738         struct btrfs_trans_handle *trans;
739         struct btrfs_path *path;
740         enum btrfs_item_field corrupt_field;
741         u32 orig, bogus;
742         int ret;
743
744         corrupt_field = convert_item_field(field);
745         if (corrupt_field == BTRFS_ITEM_BAD) {
746                 fprintf(stderr, "Invalid field %s\n", field);
747                 return -EINVAL;
748         }
749
750         path = btrfs_alloc_path();
751         if (!path)
752                 return -ENOMEM;
753
754         trans = btrfs_start_transaction(root, 1);
755         if (IS_ERR(trans)) {
756                 btrfs_free_path(path);
757                 fprintf(stderr, "Couldn't start transaction %ld\n",
758                         PTR_ERR(trans));
759                 return PTR_ERR(trans);
760         }
761
762         ret = btrfs_search_slot(trans, root, key, path, 0, 1);
763         if (ret != 0) {
764                 fprintf(stderr, "Error searching to node %d\n", ret);
765                 goto out;
766         }
767
768         ret = 0;
769         switch (corrupt_field) {
770         case BTRFS_ITEM_OFFSET:
771                 orig = btrfs_item_offset_nr(path->nodes[0], path->slots[0]);
772                 bogus = generate_u32(orig);
773                 btrfs_set_item_offset(path->nodes[0],
774                                       btrfs_item_nr(path->slots[0]), bogus);
775                 break;
776         default:
777                 ret = -EINVAL;
778                 break;
779         }
780         btrfs_mark_buffer_dirty(path->nodes[0]);
781 out:
782         btrfs_commit_transaction(trans, root);
783         btrfs_free_path(path);
784         return ret;
785 }
786
787 static struct option long_options[] = {
788         /* { "byte-count", 1, NULL, 'b' }, */
789         { "logical", 1, NULL, 'l' },
790         { "copy", 1, NULL, 'c' },
791         { "bytes", 1, NULL, 'b' },
792         { "extent-record", 0, NULL, 'e' },
793         { "extent-tree", 0, NULL, 'E' },
794         { "keys", 0, NULL, 'k' },
795         { "chunk-record", 0, NULL, 'u' },
796         { "chunk-tree", 0, NULL, 'U' },
797         { "inode", 1, NULL, 'i'},
798         { "file-extent", 1, NULL, 'x'},
799         { "metadata-block", 1, NULL, 'm'},
800         { "field", 1, NULL, 'f'},
801         { "key", 1, NULL, 'K'},
802         { "item", 0, NULL, 'I'},
803         { "dir-item", 0, NULL, 'D'},
804         { 0, 0, 0, 0}
805 };
806
807 /* corrupt item using NO cow.
808  * Because chunk recover will recover based on whole partition scaning,
809  * If using COW, chunk recover will use the old item to recover,
810  * which is still OK but we want to check the ability to rebuild chunk
811  * not only restore the old ones */
812 int corrupt_item_nocow(struct btrfs_trans_handle *trans,
813                        struct btrfs_root *root, struct btrfs_path *path,
814                        int del)
815 {
816         int ret = 0;
817         struct btrfs_key key;
818         struct extent_buffer *leaf;
819         unsigned long ptr;
820         int slot;
821         u32 item_size;
822
823         leaf = path->nodes[0];
824         slot = path->slots[0];
825         /* Not deleting the first item of a leaf to keep leaf structure */
826         if (slot == 0)
827                 del = 0;
828         /* Only accept valid eb */
829         BUG_ON(!leaf->data || slot >= btrfs_header_nritems(leaf));
830         btrfs_item_key_to_cpu(leaf, &key, slot);
831         if (del) {
832                 fprintf(stdout, "Deleting key and data [%llu, %u, %llu].\n",
833                         key.objectid, key.type, key.offset);
834                 btrfs_del_item(trans, root, path);
835         } else {
836                 fprintf(stdout, "Corrupting key and data [%llu, %u, %llu].\n",
837                         key.objectid, key.type, key.offset);
838                 ptr = btrfs_item_ptr_offset(leaf, slot);
839                 item_size = btrfs_item_size_nr(leaf, slot);
840                 memset_extent_buffer(leaf, 0, ptr, item_size);
841                 btrfs_mark_buffer_dirty(leaf);
842         }
843         return ret;
844 }
845 int corrupt_chunk_tree(struct btrfs_trans_handle *trans,
846                        struct btrfs_root *root)
847 {
848         int ret;
849         int del;
850         int slot;
851         struct btrfs_path *path;
852         struct btrfs_key key;
853         struct btrfs_key found_key;
854         struct extent_buffer *leaf;
855
856         path = btrfs_alloc_path();
857         if (!path)
858                 return -ENOMEM;
859
860         key.objectid = (u64)-1;
861         key.offset = (u64)-1;
862         key.type = (u8)-1;
863
864         /* Here, cow and ins_len must equals 0 for the following reasons:
865          * 1) chunk recover is based on disk scanning, so COW should be
866          *    disabled in case the original chunk being scanned and
867          *    recovered using the old chunk.
868          * 2) if cow = 0, ins_len must also be set to 0, or BUG_ON will be
869          *    triggered.
870          */
871         ret = btrfs_search_slot(trans, root, &key, path, 0, 0);
872         BUG_ON(ret == 0);
873         if (ret < 0) {
874                 fprintf(stderr, "Error searching tree\n");
875                 goto free_out;
876         }
877         /* corrupt/del dev_item first */
878         while (!btrfs_previous_item(root, path, 0, BTRFS_DEV_ITEM_KEY)) {
879                 slot = path->slots[0];
880                 leaf = path->nodes[0];
881                 del = rand() % 3;
882                 /* Never delete the first item to keep the leaf structure */
883                 if (path->slots[0] == 0)
884                         del = 0;
885                 ret = corrupt_item_nocow(trans, root, path, del);
886                 if (ret)
887                         goto free_out;
888         }
889         btrfs_release_path(path);
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 chunk then*/
905         while (!btrfs_previous_item(root, path, 0, BTRFS_CHUNK_ITEM_KEY)) {
906                 slot = path->slots[0];
907                 leaf = path->nodes[0];
908                 del = rand() % 3;
909                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
910                 ret = corrupt_item_nocow(trans, root, path, del);
911                 if (ret)
912                         goto free_out;
913         }
914 free_out:
915         btrfs_free_path(path);
916         return ret;
917 }
918 int find_chunk_offset(struct btrfs_root *root,
919                       struct btrfs_path *path, u64 offset)
920 {
921         struct btrfs_key key;
922         int ret;
923
924         key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
925         key.type = BTRFS_CHUNK_ITEM_KEY;
926         key.offset = offset;
927
928         /* Here, cow and ins_len must equals 0 for following reasons:
929          * 1) chunk recover is based on disk scanning, so COW should
930          *    be disabled in case the original chunk being scanned
931          *    and recovered using the old chunk.
932          * 2) if cow = 0, ins_len must also be set to 0, or BUG_ON
933          *    will be triggered.
934          */
935         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
936         if (ret > 0) {
937                 fprintf(stderr, "Can't find chunk with given offset %llu\n",
938                         offset);
939                 goto out;
940         }
941         if (ret < 0) {
942                 fprintf(stderr, "Error searching chunk");
943                 goto out;
944         }
945 out:
946         return ret;
947
948 }
949 int main(int ac, char **av)
950 {
951         struct cache_tree root_cache;
952         struct btrfs_key key;
953         struct btrfs_root *root;
954         struct extent_buffer *eb;
955         char *dev;
956         /* chunk offset can be 0,so change to (u64)-1 */
957         u64 logical = (u64)-1;
958         int ret = 0;
959         int option_index = 0;
960         u64 copy = 0;
961         u64 bytes = 4096;
962         int extent_rec = 0;
963         int extent_tree = 0;
964         int corrupt_block_keys = 0;
965         int chunk_rec = 0;
966         int chunk_tree = 0;
967         int corrupt_item = 0;
968         int corrupt_di = 0;
969         u64 metadata_block = 0;
970         u64 inode = 0;
971         u64 file_extent = (u64)-1;
972         char field[FIELD_BUF_LEN];
973
974         field[0] = '\0';
975         srand(128);
976         memset(&key, 0, sizeof(key));
977
978         while(1) {
979                 int c;
980                 c = getopt_long(ac, av, "l:c:b:eEkuUi:f:x:m:K:ID", long_options,
981                                 &option_index);
982                 if (c < 0)
983                         break;
984                 switch(c) {
985                         case 'l':
986                                 logical = arg_strtou64(optarg);
987                                 break;
988                         case 'c':
989                                 copy = arg_strtou64(optarg);
990                                 break;
991                         case 'b':
992                                 bytes = arg_strtou64(optarg);
993                                 break;
994                         case 'e':
995                                 extent_rec = 1;
996                                 break;
997                         case 'E':
998                                 extent_tree = 1;
999                                 break;
1000                         case 'k':
1001                                 corrupt_block_keys = 1;
1002                                 break;
1003                         case 'u':
1004                                 chunk_rec = 1;
1005                                 break;
1006                         case 'U':
1007                                 chunk_tree = 1;
1008                         case 'i':
1009                                 inode = arg_strtou64(optarg);
1010                                 break;
1011                         case 'f':
1012                                 strncpy(field, optarg, FIELD_BUF_LEN);
1013                                 break;
1014                         case 'x':
1015                                 file_extent = arg_strtou64(optarg);
1016                                 break;
1017                         case 'm':
1018                                 metadata_block = arg_strtou64(optarg);
1019                                 break;
1020                         case 'K':
1021                                 ret = sscanf(optarg, "%llu,%u,%llu",
1022                                              &key.objectid,
1023                                              (unsigned int *)&key.type,
1024                                              &key.offset);
1025                                 if (ret != 3) {
1026                                         fprintf(stderr, "error reading key "
1027                                                 "%d\n", errno);
1028                                         print_usage();
1029                                 }
1030                                 break;
1031                         case 'D':
1032                                 corrupt_di = 1;
1033                                 break;
1034                         case 'I':
1035                                 corrupt_item = 1;
1036                                 break;
1037                         default:
1038                                 print_usage();
1039                 }
1040         }
1041         set_argv0(av);
1042         ac = ac - optind;
1043         if (check_argc_min(ac, 1))
1044                 print_usage();
1045         dev = av[optind];
1046
1047         radix_tree_init();
1048         cache_tree_init(&root_cache);
1049
1050         root = open_ctree(dev, 0, OPEN_CTREE_WRITES);
1051         if (!root) {
1052                 fprintf(stderr, "Open ctree failed\n");
1053                 exit(1);
1054         }
1055         if (extent_rec) {
1056                 struct btrfs_trans_handle *trans;
1057
1058                 if (logical == (u64)-1)
1059                         print_usage();
1060                 trans = btrfs_start_transaction(root, 1);
1061                 ret = corrupt_extent (trans, root, logical, 0);
1062                 btrfs_commit_transaction(trans, root);
1063                 goto out_close;
1064         }
1065         if (extent_tree) {
1066                 struct btrfs_trans_handle *trans;
1067                 trans = btrfs_start_transaction(root, 1);
1068                 btrfs_corrupt_extent_tree(trans, root->fs_info->extent_root,
1069                                           root->fs_info->extent_root->node);
1070                 btrfs_commit_transaction(trans, root);
1071                 goto out_close;
1072         }
1073         if (chunk_rec) {
1074                 struct btrfs_trans_handle *trans;
1075                 struct btrfs_path *path;
1076                 int del;
1077
1078                 if (logical == (u64)-1)
1079                         print_usage();
1080                 del = rand() % 3;
1081                 path = btrfs_alloc_path();
1082                 if (!path) {
1083                         fprintf(stderr, "path allocation failed\n");
1084                         goto out_close;
1085                 }
1086
1087                 if (find_chunk_offset(root->fs_info->chunk_root, path,
1088                                       logical) != 0) {
1089                         btrfs_free_path(path);
1090                         goto out_close;
1091                 }
1092                 trans = btrfs_start_transaction(root, 1);
1093                 ret = corrupt_item_nocow(trans, root->fs_info->chunk_root,
1094                                          path, del);
1095                 if (ret < 0)
1096                         fprintf(stderr, "Failed to corrupt chunk record\n");
1097                 btrfs_commit_transaction(trans, root);
1098                 goto out_close;
1099         }
1100         if (chunk_tree) {
1101                 struct btrfs_trans_handle *trans;
1102                 trans = btrfs_start_transaction(root, 1);
1103                 ret = corrupt_chunk_tree(trans, root->fs_info->chunk_root);
1104                 if (ret < 0)
1105                         fprintf(stderr, "Failed to corrupt chunk tree\n");
1106                 btrfs_commit_transaction(trans, root);
1107                 goto out_close;
1108         }
1109         if (inode) {
1110                 struct btrfs_trans_handle *trans;
1111
1112                 if (!strlen(field))
1113                         print_usage();
1114
1115                 trans = btrfs_start_transaction(root, 1);
1116                 if (file_extent == (u64)-1) {
1117                         printf("corrupting inode\n");
1118                         ret = corrupt_inode(trans, root, inode, field);
1119                 } else {
1120                         printf("corrupting file extent\n");
1121                         ret = corrupt_file_extent(trans, root, inode,
1122                                                   file_extent, field);
1123                 }
1124                 btrfs_commit_transaction(trans, root);
1125                 goto out_close;
1126         }
1127         if (metadata_block) {
1128                 if (!strlen(field))
1129                         print_usage();
1130                 ret = corrupt_metadata_block(root, metadata_block, field);
1131                 goto out_close;
1132         }
1133         if (corrupt_di) {
1134                 if (!key.objectid || !strlen(field))
1135                         print_usage();
1136                 ret = corrupt_dir_item(root, &key, field);
1137                 goto out_close;
1138         }
1139         if (corrupt_item) {
1140                 if (!key.objectid)
1141                         print_usage();
1142                 ret = corrupt_btrfs_item(root, &key, field);
1143                 goto out_close;
1144         }
1145         if (key.objectid || key.offset || key.type) {
1146                 if (!strlen(field))
1147                         print_usage();
1148                 ret = corrupt_key(root, &key, field);
1149                 goto out_close;
1150         }
1151         /*
1152          * If we made it here and we have extent set then we didn't specify
1153          * inode and we're screwed.
1154          */
1155         if (file_extent != (u64)-1)
1156                 print_usage();
1157
1158         if (logical == (u64)-1)
1159                 print_usage();
1160
1161         if (bytes == 0)
1162                 bytes = root->sectorsize;
1163
1164         bytes = (bytes + root->sectorsize - 1) / root->sectorsize;
1165         bytes *= root->sectorsize;
1166
1167         while (bytes > 0) {
1168                 if (corrupt_block_keys) {
1169                         corrupt_keys_in_block(root, logical);
1170                 } else {
1171                         eb = debug_corrupt_block(root, logical,
1172                                                  root->sectorsize, copy);
1173                         free_extent_buffer(eb);
1174                 }
1175                 logical += root->sectorsize;
1176                 bytes -= root->sectorsize;
1177         }
1178         return ret;
1179 out_close:
1180         close_ctree(root);
1181         return ret;
1182 }