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