GNU Linux-libre 5.4.257-gnu1
[releases.git] / fs / btrfs / dev-replace.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) STRATO AG 2012.  All rights reserved.
4  */
5
6 #include <linux/sched.h>
7 #include <linux/bio.h>
8 #include <linux/slab.h>
9 #include <linux/blkdev.h>
10 #include <linux/kthread.h>
11 #include <linux/math64.h>
12 #include "misc.h"
13 #include "ctree.h"
14 #include "extent_map.h"
15 #include "disk-io.h"
16 #include "transaction.h"
17 #include "print-tree.h"
18 #include "volumes.h"
19 #include "async-thread.h"
20 #include "check-integrity.h"
21 #include "rcu-string.h"
22 #include "dev-replace.h"
23 #include "sysfs.h"
24
25 static int btrfs_dev_replace_finishing(struct btrfs_fs_info *fs_info,
26                                        int scrub_ret);
27 static void btrfs_dev_replace_update_device_in_mapping_tree(
28                                                 struct btrfs_fs_info *fs_info,
29                                                 struct btrfs_device *srcdev,
30                                                 struct btrfs_device *tgtdev);
31 static int btrfs_dev_replace_kthread(void *data);
32
33 int btrfs_init_dev_replace(struct btrfs_fs_info *fs_info)
34 {
35         struct btrfs_key key;
36         struct btrfs_root *dev_root = fs_info->dev_root;
37         struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
38         struct extent_buffer *eb;
39         int slot;
40         int ret = 0;
41         struct btrfs_path *path = NULL;
42         int item_size;
43         struct btrfs_dev_replace_item *ptr;
44         u64 src_devid;
45
46         path = btrfs_alloc_path();
47         if (!path) {
48                 ret = -ENOMEM;
49                 goto out;
50         }
51
52         key.objectid = 0;
53         key.type = BTRFS_DEV_REPLACE_KEY;
54         key.offset = 0;
55         ret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0);
56         if (ret) {
57 no_valid_dev_replace_entry_found:
58                 /*
59                  * We don't have a replace item or it's corrupted.  If there is
60                  * a replace target, fail the mount.
61                  */
62                 if (btrfs_find_device(fs_info->fs_devices,
63                                       BTRFS_DEV_REPLACE_DEVID, NULL, NULL, false)) {
64                         btrfs_err(fs_info,
65                         "found replace target device without a valid replace item");
66                         ret = -EUCLEAN;
67                         goto out;
68                 }
69                 ret = 0;
70                 dev_replace->replace_state =
71                         BTRFS_IOCTL_DEV_REPLACE_STATE_NEVER_STARTED;
72                 dev_replace->cont_reading_from_srcdev_mode =
73                     BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_ALWAYS;
74                 dev_replace->time_started = 0;
75                 dev_replace->time_stopped = 0;
76                 atomic64_set(&dev_replace->num_write_errors, 0);
77                 atomic64_set(&dev_replace->num_uncorrectable_read_errors, 0);
78                 dev_replace->cursor_left = 0;
79                 dev_replace->committed_cursor_left = 0;
80                 dev_replace->cursor_left_last_write_of_item = 0;
81                 dev_replace->cursor_right = 0;
82                 dev_replace->srcdev = NULL;
83                 dev_replace->tgtdev = NULL;
84                 dev_replace->is_valid = 0;
85                 dev_replace->item_needs_writeback = 0;
86                 goto out;
87         }
88         slot = path->slots[0];
89         eb = path->nodes[0];
90         item_size = btrfs_item_size_nr(eb, slot);
91         ptr = btrfs_item_ptr(eb, slot, struct btrfs_dev_replace_item);
92
93         if (item_size != sizeof(struct btrfs_dev_replace_item)) {
94                 btrfs_warn(fs_info,
95                         "dev_replace entry found has unexpected size, ignore entry");
96                 goto no_valid_dev_replace_entry_found;
97         }
98
99         src_devid = btrfs_dev_replace_src_devid(eb, ptr);
100         dev_replace->cont_reading_from_srcdev_mode =
101                 btrfs_dev_replace_cont_reading_from_srcdev_mode(eb, ptr);
102         dev_replace->replace_state = btrfs_dev_replace_replace_state(eb, ptr);
103         dev_replace->time_started = btrfs_dev_replace_time_started(eb, ptr);
104         dev_replace->time_stopped =
105                 btrfs_dev_replace_time_stopped(eb, ptr);
106         atomic64_set(&dev_replace->num_write_errors,
107                      btrfs_dev_replace_num_write_errors(eb, ptr));
108         atomic64_set(&dev_replace->num_uncorrectable_read_errors,
109                      btrfs_dev_replace_num_uncorrectable_read_errors(eb, ptr));
110         dev_replace->cursor_left = btrfs_dev_replace_cursor_left(eb, ptr);
111         dev_replace->committed_cursor_left = dev_replace->cursor_left;
112         dev_replace->cursor_left_last_write_of_item = dev_replace->cursor_left;
113         dev_replace->cursor_right = btrfs_dev_replace_cursor_right(eb, ptr);
114         dev_replace->is_valid = 1;
115
116         dev_replace->item_needs_writeback = 0;
117         switch (dev_replace->replace_state) {
118         case BTRFS_IOCTL_DEV_REPLACE_STATE_NEVER_STARTED:
119         case BTRFS_IOCTL_DEV_REPLACE_STATE_FINISHED:
120         case BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED:
121                 /*
122                  * We don't have an active replace item but if there is a
123                  * replace target, fail the mount.
124                  */
125                 if (btrfs_find_device(fs_info->fs_devices,
126                                       BTRFS_DEV_REPLACE_DEVID, NULL, NULL, false)) {
127                         btrfs_err(fs_info,
128 "replace without active item, run 'device scan --forget' on the target device");
129                         ret = -EUCLEAN;
130                 } else {
131                         dev_replace->srcdev = NULL;
132                         dev_replace->tgtdev = NULL;
133                 }
134                 break;
135         case BTRFS_IOCTL_DEV_REPLACE_STATE_STARTED:
136         case BTRFS_IOCTL_DEV_REPLACE_STATE_SUSPENDED:
137                 dev_replace->srcdev = btrfs_find_device(fs_info->fs_devices,
138                                                 src_devid, NULL, NULL, true);
139                 dev_replace->tgtdev = btrfs_find_device(fs_info->fs_devices,
140                                                         BTRFS_DEV_REPLACE_DEVID,
141                                                         NULL, NULL, true);
142                 /*
143                  * allow 'btrfs dev replace_cancel' if src/tgt device is
144                  * missing
145                  */
146                 if (!dev_replace->srcdev &&
147                     !btrfs_test_opt(fs_info, DEGRADED)) {
148                         ret = -EIO;
149                         btrfs_warn(fs_info,
150                            "cannot mount because device replace operation is ongoing and");
151                         btrfs_warn(fs_info,
152                            "srcdev (devid %llu) is missing, need to run 'btrfs dev scan'?",
153                            src_devid);
154                 }
155                 if (!dev_replace->tgtdev &&
156                     !btrfs_test_opt(fs_info, DEGRADED)) {
157                         ret = -EIO;
158                         btrfs_warn(fs_info,
159                            "cannot mount because device replace operation is ongoing and");
160                         btrfs_warn(fs_info,
161                            "tgtdev (devid %llu) is missing, need to run 'btrfs dev scan'?",
162                                 BTRFS_DEV_REPLACE_DEVID);
163                 }
164                 if (dev_replace->tgtdev) {
165                         if (dev_replace->srcdev) {
166                                 dev_replace->tgtdev->total_bytes =
167                                         dev_replace->srcdev->total_bytes;
168                                 dev_replace->tgtdev->disk_total_bytes =
169                                         dev_replace->srcdev->disk_total_bytes;
170                                 dev_replace->tgtdev->commit_total_bytes =
171                                         dev_replace->srcdev->commit_total_bytes;
172                                 dev_replace->tgtdev->bytes_used =
173                                         dev_replace->srcdev->bytes_used;
174                                 dev_replace->tgtdev->commit_bytes_used =
175                                         dev_replace->srcdev->commit_bytes_used;
176                         }
177                         set_bit(BTRFS_DEV_STATE_REPLACE_TGT,
178                                 &dev_replace->tgtdev->dev_state);
179
180                         WARN_ON(fs_info->fs_devices->rw_devices == 0);
181                         dev_replace->tgtdev->io_width = fs_info->sectorsize;
182                         dev_replace->tgtdev->io_align = fs_info->sectorsize;
183                         dev_replace->tgtdev->sector_size = fs_info->sectorsize;
184                         dev_replace->tgtdev->fs_info = fs_info;
185                         set_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
186                                 &dev_replace->tgtdev->dev_state);
187                 }
188                 break;
189         }
190
191 out:
192         btrfs_free_path(path);
193         return ret;
194 }
195
196 /*
197  * Initialize a new device for device replace target from a given source dev
198  * and path.
199  *
200  * Return 0 and new device in @device_out, otherwise return < 0
201  */
202 static int btrfs_init_dev_replace_tgtdev(struct btrfs_fs_info *fs_info,
203                                   const char *device_path,
204                                   struct btrfs_device *srcdev,
205                                   struct btrfs_device **device_out)
206 {
207         struct btrfs_device *device;
208         struct block_device *bdev;
209         struct list_head *devices;
210         struct rcu_string *name;
211         u64 devid = BTRFS_DEV_REPLACE_DEVID;
212         int ret = 0;
213
214         *device_out = NULL;
215         if (srcdev->fs_devices->seeding) {
216                 btrfs_err(fs_info, "the filesystem is a seed filesystem!");
217                 return -EINVAL;
218         }
219
220         bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
221                                   fs_info->bdev_holder);
222         if (IS_ERR(bdev)) {
223                 btrfs_err(fs_info, "target device %s is invalid!", device_path);
224                 return PTR_ERR(bdev);
225         }
226
227         sync_blockdev(bdev);
228
229         devices = &fs_info->fs_devices->devices;
230         list_for_each_entry(device, devices, dev_list) {
231                 if (device->bdev == bdev) {
232                         btrfs_err(fs_info,
233                                   "target device is in the filesystem!");
234                         ret = -EEXIST;
235                         goto error;
236                 }
237         }
238
239
240         if (i_size_read(bdev->bd_inode) <
241             btrfs_device_get_total_bytes(srcdev)) {
242                 btrfs_err(fs_info,
243                           "target device is smaller than source device!");
244                 ret = -EINVAL;
245                 goto error;
246         }
247
248
249         device = btrfs_alloc_device(NULL, &devid, NULL);
250         if (IS_ERR(device)) {
251                 ret = PTR_ERR(device);
252                 goto error;
253         }
254
255         name = rcu_string_strdup(device_path, GFP_KERNEL);
256         if (!name) {
257                 btrfs_free_device(device);
258                 ret = -ENOMEM;
259                 goto error;
260         }
261         rcu_assign_pointer(device->name, name);
262
263         set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
264         device->generation = 0;
265         device->io_width = fs_info->sectorsize;
266         device->io_align = fs_info->sectorsize;
267         device->sector_size = fs_info->sectorsize;
268         device->total_bytes = btrfs_device_get_total_bytes(srcdev);
269         device->disk_total_bytes = btrfs_device_get_disk_total_bytes(srcdev);
270         device->bytes_used = btrfs_device_get_bytes_used(srcdev);
271         device->commit_total_bytes = srcdev->commit_total_bytes;
272         device->commit_bytes_used = device->bytes_used;
273         device->fs_info = fs_info;
274         device->bdev = bdev;
275         set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
276         set_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
277         device->mode = FMODE_EXCL;
278         device->dev_stats_valid = 1;
279         set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
280         device->fs_devices = fs_info->fs_devices;
281
282         mutex_lock(&fs_info->fs_devices->device_list_mutex);
283         list_add(&device->dev_list, &fs_info->fs_devices->devices);
284         fs_info->fs_devices->num_devices++;
285         fs_info->fs_devices->open_devices++;
286         mutex_unlock(&fs_info->fs_devices->device_list_mutex);
287
288         *device_out = device;
289         return 0;
290
291 error:
292         blkdev_put(bdev, FMODE_EXCL);
293         return ret;
294 }
295
296 /*
297  * called from commit_transaction. Writes changed device replace state to
298  * disk.
299  */
300 int btrfs_run_dev_replace(struct btrfs_trans_handle *trans)
301 {
302         struct btrfs_fs_info *fs_info = trans->fs_info;
303         int ret;
304         struct btrfs_root *dev_root = fs_info->dev_root;
305         struct btrfs_path *path;
306         struct btrfs_key key;
307         struct extent_buffer *eb;
308         struct btrfs_dev_replace_item *ptr;
309         struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
310
311         down_read(&dev_replace->rwsem);
312         if (!dev_replace->is_valid ||
313             !dev_replace->item_needs_writeback) {
314                 up_read(&dev_replace->rwsem);
315                 return 0;
316         }
317         up_read(&dev_replace->rwsem);
318
319         key.objectid = 0;
320         key.type = BTRFS_DEV_REPLACE_KEY;
321         key.offset = 0;
322
323         path = btrfs_alloc_path();
324         if (!path) {
325                 ret = -ENOMEM;
326                 goto out;
327         }
328         ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
329         if (ret < 0) {
330                 btrfs_warn(fs_info,
331                            "error %d while searching for dev_replace item!",
332                            ret);
333                 goto out;
334         }
335
336         if (ret == 0 &&
337             btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
338                 /*
339                  * need to delete old one and insert a new one.
340                  * Since no attempt is made to recover any old state, if the
341                  * dev_replace state is 'running', the data on the target
342                  * drive is lost.
343                  * It would be possible to recover the state: just make sure
344                  * that the beginning of the item is never changed and always
345                  * contains all the essential information. Then read this
346                  * minimal set of information and use it as a base for the
347                  * new state.
348                  */
349                 ret = btrfs_del_item(trans, dev_root, path);
350                 if (ret != 0) {
351                         btrfs_warn(fs_info,
352                                    "delete too small dev_replace item failed %d!",
353                                    ret);
354                         goto out;
355                 }
356                 ret = 1;
357         }
358
359         if (ret == 1) {
360                 /* need to insert a new item */
361                 btrfs_release_path(path);
362                 ret = btrfs_insert_empty_item(trans, dev_root, path,
363                                               &key, sizeof(*ptr));
364                 if (ret < 0) {
365                         btrfs_warn(fs_info,
366                                    "insert dev_replace item failed %d!", ret);
367                         goto out;
368                 }
369         }
370
371         eb = path->nodes[0];
372         ptr = btrfs_item_ptr(eb, path->slots[0],
373                              struct btrfs_dev_replace_item);
374
375         down_write(&dev_replace->rwsem);
376         if (dev_replace->srcdev)
377                 btrfs_set_dev_replace_src_devid(eb, ptr,
378                         dev_replace->srcdev->devid);
379         else
380                 btrfs_set_dev_replace_src_devid(eb, ptr, (u64)-1);
381         btrfs_set_dev_replace_cont_reading_from_srcdev_mode(eb, ptr,
382                 dev_replace->cont_reading_from_srcdev_mode);
383         btrfs_set_dev_replace_replace_state(eb, ptr,
384                 dev_replace->replace_state);
385         btrfs_set_dev_replace_time_started(eb, ptr, dev_replace->time_started);
386         btrfs_set_dev_replace_time_stopped(eb, ptr, dev_replace->time_stopped);
387         btrfs_set_dev_replace_num_write_errors(eb, ptr,
388                 atomic64_read(&dev_replace->num_write_errors));
389         btrfs_set_dev_replace_num_uncorrectable_read_errors(eb, ptr,
390                 atomic64_read(&dev_replace->num_uncorrectable_read_errors));
391         dev_replace->cursor_left_last_write_of_item =
392                 dev_replace->cursor_left;
393         btrfs_set_dev_replace_cursor_left(eb, ptr,
394                 dev_replace->cursor_left_last_write_of_item);
395         btrfs_set_dev_replace_cursor_right(eb, ptr,
396                 dev_replace->cursor_right);
397         dev_replace->item_needs_writeback = 0;
398         up_write(&dev_replace->rwsem);
399
400         btrfs_mark_buffer_dirty(eb);
401
402 out:
403         btrfs_free_path(path);
404
405         return ret;
406 }
407
408 static char* btrfs_dev_name(struct btrfs_device *device)
409 {
410         if (!device || test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
411                 return "<missing disk>";
412         else
413                 return rcu_str_deref(device->name);
414 }
415
416 static int btrfs_dev_replace_start(struct btrfs_fs_info *fs_info,
417                 const char *tgtdev_name, u64 srcdevid, const char *srcdev_name,
418                 int read_src)
419 {
420         struct btrfs_root *root = fs_info->dev_root;
421         struct btrfs_trans_handle *trans;
422         struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
423         int ret;
424         struct btrfs_device *tgt_device = NULL;
425         struct btrfs_device *src_device = NULL;
426
427         src_device = btrfs_find_device_by_devspec(fs_info, srcdevid,
428                                                   srcdev_name);
429         if (IS_ERR(src_device))
430                 return PTR_ERR(src_device);
431
432         if (btrfs_pinned_by_swapfile(fs_info, src_device)) {
433                 btrfs_warn_in_rcu(fs_info,
434           "cannot replace device %s (devid %llu) due to active swapfile",
435                         btrfs_dev_name(src_device), src_device->devid);
436                 return -ETXTBSY;
437         }
438
439         /*
440          * Here we commit the transaction to make sure commit_total_bytes
441          * of all the devices are updated.
442          */
443         trans = btrfs_attach_transaction(root);
444         if (!IS_ERR(trans)) {
445                 ret = btrfs_commit_transaction(trans);
446                 if (ret)
447                         return ret;
448         } else if (PTR_ERR(trans) != -ENOENT) {
449                 return PTR_ERR(trans);
450         }
451
452         ret = btrfs_init_dev_replace_tgtdev(fs_info, tgtdev_name,
453                                             src_device, &tgt_device);
454         if (ret)
455                 return ret;
456
457         down_write(&dev_replace->rwsem);
458         switch (dev_replace->replace_state) {
459         case BTRFS_IOCTL_DEV_REPLACE_STATE_NEVER_STARTED:
460         case BTRFS_IOCTL_DEV_REPLACE_STATE_FINISHED:
461         case BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED:
462                 break;
463         case BTRFS_IOCTL_DEV_REPLACE_STATE_STARTED:
464         case BTRFS_IOCTL_DEV_REPLACE_STATE_SUSPENDED:
465                 ASSERT(0);
466                 ret = BTRFS_IOCTL_DEV_REPLACE_RESULT_ALREADY_STARTED;
467                 up_write(&dev_replace->rwsem);
468                 goto leave;
469         }
470
471         dev_replace->cont_reading_from_srcdev_mode = read_src;
472         dev_replace->srcdev = src_device;
473         dev_replace->tgtdev = tgt_device;
474
475         btrfs_info_in_rcu(fs_info,
476                       "dev_replace from %s (devid %llu) to %s started",
477                       btrfs_dev_name(src_device),
478                       src_device->devid,
479                       rcu_str_deref(tgt_device->name));
480
481         /*
482          * from now on, the writes to the srcdev are all duplicated to
483          * go to the tgtdev as well (refer to btrfs_map_block()).
484          */
485         dev_replace->replace_state = BTRFS_IOCTL_DEV_REPLACE_STATE_STARTED;
486         dev_replace->time_started = ktime_get_real_seconds();
487         dev_replace->cursor_left = 0;
488         dev_replace->committed_cursor_left = 0;
489         dev_replace->cursor_left_last_write_of_item = 0;
490         dev_replace->cursor_right = 0;
491         dev_replace->is_valid = 1;
492         dev_replace->item_needs_writeback = 1;
493         atomic64_set(&dev_replace->num_write_errors, 0);
494         atomic64_set(&dev_replace->num_uncorrectable_read_errors, 0);
495         up_write(&dev_replace->rwsem);
496
497         ret = btrfs_sysfs_add_device_link(tgt_device->fs_devices, tgt_device);
498         if (ret)
499                 btrfs_err(fs_info, "kobj add dev failed %d", ret);
500
501         btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
502
503         /* Commit dev_replace state and reserve 1 item for it. */
504         trans = btrfs_start_transaction(root, 1);
505         if (IS_ERR(trans)) {
506                 ret = PTR_ERR(trans);
507                 down_write(&dev_replace->rwsem);
508                 dev_replace->replace_state =
509                         BTRFS_IOCTL_DEV_REPLACE_STATE_NEVER_STARTED;
510                 dev_replace->srcdev = NULL;
511                 dev_replace->tgtdev = NULL;
512                 up_write(&dev_replace->rwsem);
513                 goto leave;
514         }
515
516         ret = btrfs_commit_transaction(trans);
517         WARN_ON(ret);
518
519         /* the disk copy procedure reuses the scrub code */
520         ret = btrfs_scrub_dev(fs_info, src_device->devid, 0,
521                               btrfs_device_get_total_bytes(src_device),
522                               &dev_replace->scrub_progress, 0, 1);
523
524         ret = btrfs_dev_replace_finishing(fs_info, ret);
525         if (ret == -EINPROGRESS) {
526                 ret = BTRFS_IOCTL_DEV_REPLACE_RESULT_SCRUB_INPROGRESS;
527         } else if (ret != -ECANCELED) {
528                 WARN_ON(ret);
529         }
530
531         return ret;
532
533 leave:
534         btrfs_destroy_dev_replace_tgtdev(tgt_device);
535         return ret;
536 }
537
538 int btrfs_dev_replace_by_ioctl(struct btrfs_fs_info *fs_info,
539                             struct btrfs_ioctl_dev_replace_args *args)
540 {
541         int ret;
542
543         switch (args->start.cont_reading_from_srcdev_mode) {
544         case BTRFS_IOCTL_DEV_REPLACE_CONT_READING_FROM_SRCDEV_MODE_ALWAYS:
545         case BTRFS_IOCTL_DEV_REPLACE_CONT_READING_FROM_SRCDEV_MODE_AVOID:
546                 break;
547         default:
548                 return -EINVAL;
549         }
550
551         if ((args->start.srcdevid == 0 && args->start.srcdev_name[0] == '\0') ||
552             args->start.tgtdev_name[0] == '\0')
553                 return -EINVAL;
554
555         ret = btrfs_dev_replace_start(fs_info, args->start.tgtdev_name,
556                                         args->start.srcdevid,
557                                         args->start.srcdev_name,
558                                         args->start.cont_reading_from_srcdev_mode);
559         args->result = ret;
560         /* don't warn if EINPROGRESS, someone else might be running scrub */
561         if (ret == BTRFS_IOCTL_DEV_REPLACE_RESULT_SCRUB_INPROGRESS ||
562             ret == BTRFS_IOCTL_DEV_REPLACE_RESULT_NO_ERROR)
563                 return 0;
564
565         return ret;
566 }
567
568 /*
569  * blocked until all in-flight bios operations are finished.
570  */
571 static void btrfs_rm_dev_replace_blocked(struct btrfs_fs_info *fs_info)
572 {
573         set_bit(BTRFS_FS_STATE_DEV_REPLACING, &fs_info->fs_state);
574         wait_event(fs_info->dev_replace.replace_wait, !percpu_counter_sum(
575                    &fs_info->dev_replace.bio_counter));
576 }
577
578 /*
579  * we have removed target device, it is safe to allow new bios request.
580  */
581 static void btrfs_rm_dev_replace_unblocked(struct btrfs_fs_info *fs_info)
582 {
583         clear_bit(BTRFS_FS_STATE_DEV_REPLACING, &fs_info->fs_state);
584         wake_up(&fs_info->dev_replace.replace_wait);
585 }
586
587 /*
588  * When finishing the device replace, before swapping the source device with the
589  * target device we must update the chunk allocation state in the target device,
590  * as it is empty because replace works by directly copying the chunks and not
591  * through the normal chunk allocation path.
592  */
593 static int btrfs_set_target_alloc_state(struct btrfs_device *srcdev,
594                                         struct btrfs_device *tgtdev)
595 {
596         struct extent_state *cached_state = NULL;
597         u64 start = 0;
598         u64 found_start;
599         u64 found_end;
600         int ret = 0;
601
602         lockdep_assert_held(&srcdev->fs_info->chunk_mutex);
603
604         while (!find_first_extent_bit(&srcdev->alloc_state, start,
605                                       &found_start, &found_end,
606                                       CHUNK_ALLOCATED, &cached_state)) {
607                 ret = set_extent_bits(&tgtdev->alloc_state, found_start,
608                                       found_end, CHUNK_ALLOCATED);
609                 if (ret)
610                         break;
611                 start = found_end + 1;
612         }
613
614         free_extent_state(cached_state);
615         return ret;
616 }
617
618 static int btrfs_dev_replace_finishing(struct btrfs_fs_info *fs_info,
619                                        int scrub_ret)
620 {
621         struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
622         struct btrfs_device *tgt_device;
623         struct btrfs_device *src_device;
624         struct btrfs_root *root = fs_info->tree_root;
625         u8 uuid_tmp[BTRFS_UUID_SIZE];
626         struct btrfs_trans_handle *trans;
627         int ret = 0;
628
629         /* don't allow cancel or unmount to disturb the finishing procedure */
630         mutex_lock(&dev_replace->lock_finishing_cancel_unmount);
631
632         down_read(&dev_replace->rwsem);
633         /* was the operation canceled, or is it finished? */
634         if (dev_replace->replace_state !=
635             BTRFS_IOCTL_DEV_REPLACE_STATE_STARTED) {
636                 up_read(&dev_replace->rwsem);
637                 mutex_unlock(&dev_replace->lock_finishing_cancel_unmount);
638                 return 0;
639         }
640
641         tgt_device = dev_replace->tgtdev;
642         src_device = dev_replace->srcdev;
643         up_read(&dev_replace->rwsem);
644
645         /*
646          * flush all outstanding I/O and inode extent mappings before the
647          * copy operation is declared as being finished
648          */
649         ret = btrfs_start_delalloc_roots(fs_info, -1);
650         if (ret) {
651                 mutex_unlock(&dev_replace->lock_finishing_cancel_unmount);
652                 return ret;
653         }
654         btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
655
656         if (!scrub_ret)
657                 btrfs_reada_remove_dev(src_device);
658
659         /*
660          * We have to use this loop approach because at this point src_device
661          * has to be available for transaction commit to complete, yet new
662          * chunks shouldn't be allocated on the device.
663          */
664         while (1) {
665                 trans = btrfs_start_transaction(root, 0);
666                 if (IS_ERR(trans)) {
667                         btrfs_reada_undo_remove_dev(src_device);
668                         mutex_unlock(&dev_replace->lock_finishing_cancel_unmount);
669                         return PTR_ERR(trans);
670                 }
671                 ret = btrfs_commit_transaction(trans);
672                 WARN_ON(ret);
673
674                 /* Prevent write_all_supers() during the finishing procedure */
675                 mutex_lock(&fs_info->fs_devices->device_list_mutex);
676                 /* Prevent new chunks being allocated on the source device */
677                 mutex_lock(&fs_info->chunk_mutex);
678
679                 if (!list_empty(&src_device->post_commit_list)) {
680                         mutex_unlock(&fs_info->fs_devices->device_list_mutex);
681                         mutex_unlock(&fs_info->chunk_mutex);
682                 } else {
683                         break;
684                 }
685         }
686
687         down_write(&dev_replace->rwsem);
688         dev_replace->replace_state =
689                 scrub_ret ? BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED
690                           : BTRFS_IOCTL_DEV_REPLACE_STATE_FINISHED;
691         dev_replace->tgtdev = NULL;
692         dev_replace->srcdev = NULL;
693         dev_replace->time_stopped = ktime_get_real_seconds();
694         dev_replace->item_needs_writeback = 1;
695
696         /*
697          * Update allocation state in the new device and replace the old device
698          * with the new one in the mapping tree.
699          */
700         if (!scrub_ret) {
701                 scrub_ret = btrfs_set_target_alloc_state(src_device, tgt_device);
702                 if (scrub_ret)
703                         goto error;
704                 btrfs_dev_replace_update_device_in_mapping_tree(fs_info,
705                                                                 src_device,
706                                                                 tgt_device);
707         } else {
708                 if (scrub_ret != -ECANCELED)
709                         btrfs_err_in_rcu(fs_info,
710                                  "btrfs_scrub_dev(%s, %llu, %s) failed %d",
711                                  btrfs_dev_name(src_device),
712                                  src_device->devid,
713                                  rcu_str_deref(tgt_device->name), scrub_ret);
714 error:
715                 up_write(&dev_replace->rwsem);
716                 mutex_unlock(&fs_info->chunk_mutex);
717                 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
718                 btrfs_reada_undo_remove_dev(src_device);
719                 btrfs_rm_dev_replace_blocked(fs_info);
720                 if (tgt_device)
721                         btrfs_destroy_dev_replace_tgtdev(tgt_device);
722                 btrfs_rm_dev_replace_unblocked(fs_info);
723                 mutex_unlock(&dev_replace->lock_finishing_cancel_unmount);
724
725                 return scrub_ret;
726         }
727
728         btrfs_info_in_rcu(fs_info,
729                           "dev_replace from %s (devid %llu) to %s finished",
730                           btrfs_dev_name(src_device),
731                           src_device->devid,
732                           rcu_str_deref(tgt_device->name));
733         clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &tgt_device->dev_state);
734         tgt_device->devid = src_device->devid;
735         src_device->devid = BTRFS_DEV_REPLACE_DEVID;
736         memcpy(uuid_tmp, tgt_device->uuid, sizeof(uuid_tmp));
737         memcpy(tgt_device->uuid, src_device->uuid, sizeof(tgt_device->uuid));
738         memcpy(src_device->uuid, uuid_tmp, sizeof(src_device->uuid));
739         btrfs_device_set_total_bytes(tgt_device, src_device->total_bytes);
740         btrfs_device_set_disk_total_bytes(tgt_device,
741                                           src_device->disk_total_bytes);
742         btrfs_device_set_bytes_used(tgt_device, src_device->bytes_used);
743         tgt_device->commit_bytes_used = src_device->bytes_used;
744
745         btrfs_assign_next_active_device(src_device, tgt_device);
746
747         list_add(&tgt_device->dev_alloc_list, &fs_info->fs_devices->alloc_list);
748         fs_info->fs_devices->rw_devices++;
749
750         up_write(&dev_replace->rwsem);
751         btrfs_rm_dev_replace_blocked(fs_info);
752
753         btrfs_rm_dev_replace_remove_srcdev(src_device);
754
755         btrfs_rm_dev_replace_unblocked(fs_info);
756
757         /*
758          * Increment dev_stats_ccnt so that btrfs_run_dev_stats() will
759          * update on-disk dev stats value during commit transaction
760          */
761         atomic_inc(&tgt_device->dev_stats_ccnt);
762
763         /*
764          * this is again a consistent state where no dev_replace procedure
765          * is running, the target device is part of the filesystem, the
766          * source device is not part of the filesystem anymore and its 1st
767          * superblock is scratched out so that it is no longer marked to
768          * belong to this filesystem.
769          */
770         mutex_unlock(&fs_info->chunk_mutex);
771         mutex_unlock(&fs_info->fs_devices->device_list_mutex);
772
773         /* replace the sysfs entry */
774         btrfs_sysfs_rm_device_link(fs_info->fs_devices, src_device);
775         btrfs_rm_dev_replace_free_srcdev(src_device);
776
777         /* write back the superblocks */
778         trans = btrfs_start_transaction(root, 0);
779         if (!IS_ERR(trans))
780                 btrfs_commit_transaction(trans);
781
782         mutex_unlock(&dev_replace->lock_finishing_cancel_unmount);
783
784         return 0;
785 }
786
787 static void btrfs_dev_replace_update_device_in_mapping_tree(
788                                                 struct btrfs_fs_info *fs_info,
789                                                 struct btrfs_device *srcdev,
790                                                 struct btrfs_device *tgtdev)
791 {
792         struct extent_map_tree *em_tree = &fs_info->mapping_tree;
793         struct extent_map *em;
794         struct map_lookup *map;
795         u64 start = 0;
796         int i;
797
798         write_lock(&em_tree->lock);
799         do {
800                 em = lookup_extent_mapping(em_tree, start, (u64)-1);
801                 if (!em)
802                         break;
803                 map = em->map_lookup;
804                 for (i = 0; i < map->num_stripes; i++)
805                         if (srcdev == map->stripes[i].dev)
806                                 map->stripes[i].dev = tgtdev;
807                 start = em->start + em->len;
808                 free_extent_map(em);
809         } while (start);
810         write_unlock(&em_tree->lock);
811 }
812
813 /*
814  * Read progress of device replace status according to the state and last
815  * stored position. The value format is the same as for
816  * btrfs_dev_replace::progress_1000
817  */
818 static u64 btrfs_dev_replace_progress(struct btrfs_fs_info *fs_info)
819 {
820         struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
821         u64 ret = 0;
822
823         switch (dev_replace->replace_state) {
824         case BTRFS_IOCTL_DEV_REPLACE_STATE_NEVER_STARTED:
825         case BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED:
826                 ret = 0;
827                 break;
828         case BTRFS_IOCTL_DEV_REPLACE_STATE_FINISHED:
829                 ret = 1000;
830                 break;
831         case BTRFS_IOCTL_DEV_REPLACE_STATE_STARTED:
832         case BTRFS_IOCTL_DEV_REPLACE_STATE_SUSPENDED:
833                 ret = div64_u64(dev_replace->cursor_left,
834                                 div_u64(btrfs_device_get_total_bytes(
835                                                 dev_replace->srcdev), 1000));
836                 break;
837         }
838
839         return ret;
840 }
841
842 void btrfs_dev_replace_status(struct btrfs_fs_info *fs_info,
843                               struct btrfs_ioctl_dev_replace_args *args)
844 {
845         struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
846
847         down_read(&dev_replace->rwsem);
848         /* even if !dev_replace_is_valid, the values are good enough for
849          * the replace_status ioctl */
850         args->result = BTRFS_IOCTL_DEV_REPLACE_RESULT_NO_ERROR;
851         args->status.replace_state = dev_replace->replace_state;
852         args->status.time_started = dev_replace->time_started;
853         args->status.time_stopped = dev_replace->time_stopped;
854         args->status.num_write_errors =
855                 atomic64_read(&dev_replace->num_write_errors);
856         args->status.num_uncorrectable_read_errors =
857                 atomic64_read(&dev_replace->num_uncorrectable_read_errors);
858         args->status.progress_1000 = btrfs_dev_replace_progress(fs_info);
859         up_read(&dev_replace->rwsem);
860 }
861
862 int btrfs_dev_replace_cancel(struct btrfs_fs_info *fs_info)
863 {
864         struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
865         struct btrfs_device *tgt_device = NULL;
866         struct btrfs_device *src_device = NULL;
867         struct btrfs_trans_handle *trans;
868         struct btrfs_root *root = fs_info->tree_root;
869         int result;
870         int ret;
871
872         if (sb_rdonly(fs_info->sb))
873                 return -EROFS;
874
875         mutex_lock(&dev_replace->lock_finishing_cancel_unmount);
876         down_write(&dev_replace->rwsem);
877         switch (dev_replace->replace_state) {
878         case BTRFS_IOCTL_DEV_REPLACE_STATE_NEVER_STARTED:
879         case BTRFS_IOCTL_DEV_REPLACE_STATE_FINISHED:
880         case BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED:
881                 result = BTRFS_IOCTL_DEV_REPLACE_RESULT_NOT_STARTED;
882                 up_write(&dev_replace->rwsem);
883                 break;
884         case BTRFS_IOCTL_DEV_REPLACE_STATE_STARTED:
885                 tgt_device = dev_replace->tgtdev;
886                 src_device = dev_replace->srcdev;
887                 up_write(&dev_replace->rwsem);
888                 ret = btrfs_scrub_cancel(fs_info);
889                 if (ret < 0) {
890                         result = BTRFS_IOCTL_DEV_REPLACE_RESULT_NOT_STARTED;
891                 } else {
892                         result = BTRFS_IOCTL_DEV_REPLACE_RESULT_NO_ERROR;
893                         /*
894                          * btrfs_dev_replace_finishing() will handle the
895                          * cleanup part
896                          */
897                         btrfs_info_in_rcu(fs_info,
898                                 "dev_replace from %s (devid %llu) to %s canceled",
899                                 btrfs_dev_name(src_device), src_device->devid,
900                                 btrfs_dev_name(tgt_device));
901                 }
902                 break;
903         case BTRFS_IOCTL_DEV_REPLACE_STATE_SUSPENDED:
904                 /*
905                  * Scrub doing the replace isn't running so we need to do the
906                  * cleanup step of btrfs_dev_replace_finishing() here
907                  */
908                 result = BTRFS_IOCTL_DEV_REPLACE_RESULT_NO_ERROR;
909                 tgt_device = dev_replace->tgtdev;
910                 src_device = dev_replace->srcdev;
911                 dev_replace->tgtdev = NULL;
912                 dev_replace->srcdev = NULL;
913                 dev_replace->replace_state =
914                                 BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED;
915                 dev_replace->time_stopped = ktime_get_real_seconds();
916                 dev_replace->item_needs_writeback = 1;
917
918                 up_write(&dev_replace->rwsem);
919
920                 /* Scrub for replace must not be running in suspended state */
921                 btrfs_scrub_cancel(fs_info);
922
923                 trans = btrfs_start_transaction(root, 0);
924                 if (IS_ERR(trans)) {
925                         mutex_unlock(&dev_replace->lock_finishing_cancel_unmount);
926                         return PTR_ERR(trans);
927                 }
928                 ret = btrfs_commit_transaction(trans);
929                 WARN_ON(ret);
930
931                 btrfs_info_in_rcu(fs_info,
932                 "suspended dev_replace from %s (devid %llu) to %s canceled",
933                         btrfs_dev_name(src_device), src_device->devid,
934                         btrfs_dev_name(tgt_device));
935
936                 if (tgt_device)
937                         btrfs_destroy_dev_replace_tgtdev(tgt_device);
938                 break;
939         default:
940                 up_write(&dev_replace->rwsem);
941                 result = -EINVAL;
942         }
943
944         mutex_unlock(&dev_replace->lock_finishing_cancel_unmount);
945         return result;
946 }
947
948 void btrfs_dev_replace_suspend_for_unmount(struct btrfs_fs_info *fs_info)
949 {
950         struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
951
952         mutex_lock(&dev_replace->lock_finishing_cancel_unmount);
953         down_write(&dev_replace->rwsem);
954
955         switch (dev_replace->replace_state) {
956         case BTRFS_IOCTL_DEV_REPLACE_STATE_NEVER_STARTED:
957         case BTRFS_IOCTL_DEV_REPLACE_STATE_FINISHED:
958         case BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED:
959         case BTRFS_IOCTL_DEV_REPLACE_STATE_SUSPENDED:
960                 break;
961         case BTRFS_IOCTL_DEV_REPLACE_STATE_STARTED:
962                 dev_replace->replace_state =
963                         BTRFS_IOCTL_DEV_REPLACE_STATE_SUSPENDED;
964                 dev_replace->time_stopped = ktime_get_real_seconds();
965                 dev_replace->item_needs_writeback = 1;
966                 btrfs_info(fs_info, "suspending dev_replace for unmount");
967                 break;
968         }
969
970         up_write(&dev_replace->rwsem);
971         mutex_unlock(&dev_replace->lock_finishing_cancel_unmount);
972 }
973
974 /* resume dev_replace procedure that was interrupted by unmount */
975 int btrfs_resume_dev_replace_async(struct btrfs_fs_info *fs_info)
976 {
977         struct task_struct *task;
978         struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
979
980         down_write(&dev_replace->rwsem);
981
982         switch (dev_replace->replace_state) {
983         case BTRFS_IOCTL_DEV_REPLACE_STATE_NEVER_STARTED:
984         case BTRFS_IOCTL_DEV_REPLACE_STATE_FINISHED:
985         case BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED:
986                 up_write(&dev_replace->rwsem);
987                 return 0;
988         case BTRFS_IOCTL_DEV_REPLACE_STATE_STARTED:
989                 break;
990         case BTRFS_IOCTL_DEV_REPLACE_STATE_SUSPENDED:
991                 dev_replace->replace_state =
992                         BTRFS_IOCTL_DEV_REPLACE_STATE_STARTED;
993                 break;
994         }
995         if (!dev_replace->tgtdev || !dev_replace->tgtdev->bdev) {
996                 btrfs_info(fs_info,
997                            "cannot continue dev_replace, tgtdev is missing");
998                 btrfs_info(fs_info,
999                            "you may cancel the operation after 'mount -o degraded'");
1000                 dev_replace->replace_state =
1001                                         BTRFS_IOCTL_DEV_REPLACE_STATE_SUSPENDED;
1002                 up_write(&dev_replace->rwsem);
1003                 return 0;
1004         }
1005         up_write(&dev_replace->rwsem);
1006
1007         /*
1008          * This could collide with a paused balance, but the exclusive op logic
1009          * should never allow both to start and pause. We don't want to allow
1010          * dev-replace to start anyway.
1011          */
1012         if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags)) {
1013                 down_write(&dev_replace->rwsem);
1014                 dev_replace->replace_state =
1015                                         BTRFS_IOCTL_DEV_REPLACE_STATE_SUSPENDED;
1016                 up_write(&dev_replace->rwsem);
1017                 btrfs_info(fs_info,
1018                 "cannot resume dev-replace, other exclusive operation running");
1019                 return 0;
1020         }
1021
1022         task = kthread_run(btrfs_dev_replace_kthread, fs_info, "btrfs-devrepl");
1023         return PTR_ERR_OR_ZERO(task);
1024 }
1025
1026 static int btrfs_dev_replace_kthread(void *data)
1027 {
1028         struct btrfs_fs_info *fs_info = data;
1029         struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
1030         u64 progress;
1031         int ret;
1032
1033         progress = btrfs_dev_replace_progress(fs_info);
1034         progress = div_u64(progress, 10);
1035         btrfs_info_in_rcu(fs_info,
1036                 "continuing dev_replace from %s (devid %llu) to target %s @%u%%",
1037                 btrfs_dev_name(dev_replace->srcdev),
1038                 dev_replace->srcdev->devid,
1039                 btrfs_dev_name(dev_replace->tgtdev),
1040                 (unsigned int)progress);
1041
1042         ret = btrfs_scrub_dev(fs_info, dev_replace->srcdev->devid,
1043                               dev_replace->committed_cursor_left,
1044                               btrfs_device_get_total_bytes(dev_replace->srcdev),
1045                               &dev_replace->scrub_progress, 0, 1);
1046         ret = btrfs_dev_replace_finishing(fs_info, ret);
1047         WARN_ON(ret && ret != -ECANCELED);
1048
1049         clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
1050         return 0;
1051 }
1052
1053 int btrfs_dev_replace_is_ongoing(struct btrfs_dev_replace *dev_replace)
1054 {
1055         if (!dev_replace->is_valid)
1056                 return 0;
1057
1058         switch (dev_replace->replace_state) {
1059         case BTRFS_IOCTL_DEV_REPLACE_STATE_NEVER_STARTED:
1060         case BTRFS_IOCTL_DEV_REPLACE_STATE_FINISHED:
1061         case BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED:
1062                 return 0;
1063         case BTRFS_IOCTL_DEV_REPLACE_STATE_STARTED:
1064         case BTRFS_IOCTL_DEV_REPLACE_STATE_SUSPENDED:
1065                 /*
1066                  * return true even if tgtdev is missing (this is
1067                  * something that can happen if the dev_replace
1068                  * procedure is suspended by an umount and then
1069                  * the tgtdev is missing (or "btrfs dev scan") was
1070                  * not called and the filesystem is remounted
1071                  * in degraded state. This does not stop the
1072                  * dev_replace procedure. It needs to be canceled
1073                  * manually if the cancellation is wanted.
1074                  */
1075                 break;
1076         }
1077         return 1;
1078 }
1079
1080 void btrfs_bio_counter_inc_noblocked(struct btrfs_fs_info *fs_info)
1081 {
1082         percpu_counter_inc(&fs_info->dev_replace.bio_counter);
1083 }
1084
1085 void btrfs_bio_counter_sub(struct btrfs_fs_info *fs_info, s64 amount)
1086 {
1087         percpu_counter_sub(&fs_info->dev_replace.bio_counter, amount);
1088         cond_wake_up_nomb(&fs_info->dev_replace.replace_wait);
1089 }
1090
1091 void btrfs_bio_counter_inc_blocked(struct btrfs_fs_info *fs_info)
1092 {
1093         while (1) {
1094                 percpu_counter_inc(&fs_info->dev_replace.bio_counter);
1095                 if (likely(!test_bit(BTRFS_FS_STATE_DEV_REPLACING,
1096                                      &fs_info->fs_state)))
1097                         break;
1098
1099                 btrfs_bio_counter_dec(fs_info);
1100                 wait_event(fs_info->dev_replace.replace_wait,
1101                            !test_bit(BTRFS_FS_STATE_DEV_REPLACING,
1102                                      &fs_info->fs_state));
1103         }
1104 }