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