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