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