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