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