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