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