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