GNU Linux-libre 4.19.211-gnu1
[releases.git] / fs / btrfs / volumes.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2007 Oracle.  All rights reserved.
4  */
5
6 #include <linux/sched.h>
7 #include <linux/sched/mm.h>
8 #include <linux/bio.h>
9 #include <linux/slab.h>
10 #include <linux/buffer_head.h>
11 #include <linux/blkdev.h>
12 #include <linux/ratelimit.h>
13 #include <linux/kthread.h>
14 #include <linux/raid/pq.h>
15 #include <linux/semaphore.h>
16 #include <linux/uuid.h>
17 #include <linux/list_sort.h>
18 #include "ctree.h"
19 #include "extent_map.h"
20 #include "disk-io.h"
21 #include "transaction.h"
22 #include "print-tree.h"
23 #include "volumes.h"
24 #include "raid56.h"
25 #include "async-thread.h"
26 #include "check-integrity.h"
27 #include "rcu-string.h"
28 #include "math.h"
29 #include "dev-replace.h"
30 #include "sysfs.h"
31 #include "tree-checker.h"
32
33 const struct btrfs_raid_attr btrfs_raid_array[BTRFS_NR_RAID_TYPES] = {
34         [BTRFS_RAID_RAID10] = {
35                 .sub_stripes    = 2,
36                 .dev_stripes    = 1,
37                 .devs_max       = 0,    /* 0 == as many as possible */
38                 .devs_min       = 4,
39                 .tolerated_failures = 1,
40                 .devs_increment = 2,
41                 .ncopies        = 2,
42                 .raid_name      = "raid10",
43                 .bg_flag        = BTRFS_BLOCK_GROUP_RAID10,
44                 .mindev_error   = BTRFS_ERROR_DEV_RAID10_MIN_NOT_MET,
45         },
46         [BTRFS_RAID_RAID1] = {
47                 .sub_stripes    = 1,
48                 .dev_stripes    = 1,
49                 .devs_max       = 2,
50                 .devs_min       = 2,
51                 .tolerated_failures = 1,
52                 .devs_increment = 2,
53                 .ncopies        = 2,
54                 .raid_name      = "raid1",
55                 .bg_flag        = BTRFS_BLOCK_GROUP_RAID1,
56                 .mindev_error   = BTRFS_ERROR_DEV_RAID1_MIN_NOT_MET,
57         },
58         [BTRFS_RAID_DUP] = {
59                 .sub_stripes    = 1,
60                 .dev_stripes    = 2,
61                 .devs_max       = 1,
62                 .devs_min       = 1,
63                 .tolerated_failures = 0,
64                 .devs_increment = 1,
65                 .ncopies        = 2,
66                 .raid_name      = "dup",
67                 .bg_flag        = BTRFS_BLOCK_GROUP_DUP,
68                 .mindev_error   = 0,
69         },
70         [BTRFS_RAID_RAID0] = {
71                 .sub_stripes    = 1,
72                 .dev_stripes    = 1,
73                 .devs_max       = 0,
74                 .devs_min       = 2,
75                 .tolerated_failures = 0,
76                 .devs_increment = 1,
77                 .ncopies        = 1,
78                 .raid_name      = "raid0",
79                 .bg_flag        = BTRFS_BLOCK_GROUP_RAID0,
80                 .mindev_error   = 0,
81         },
82         [BTRFS_RAID_SINGLE] = {
83                 .sub_stripes    = 1,
84                 .dev_stripes    = 1,
85                 .devs_max       = 1,
86                 .devs_min       = 1,
87                 .tolerated_failures = 0,
88                 .devs_increment = 1,
89                 .ncopies        = 1,
90                 .raid_name      = "single",
91                 .bg_flag        = 0,
92                 .mindev_error   = 0,
93         },
94         [BTRFS_RAID_RAID5] = {
95                 .sub_stripes    = 1,
96                 .dev_stripes    = 1,
97                 .devs_max       = 0,
98                 .devs_min       = 2,
99                 .tolerated_failures = 1,
100                 .devs_increment = 1,
101                 .ncopies        = 1,
102                 .raid_name      = "raid5",
103                 .bg_flag        = BTRFS_BLOCK_GROUP_RAID5,
104                 .mindev_error   = BTRFS_ERROR_DEV_RAID5_MIN_NOT_MET,
105         },
106         [BTRFS_RAID_RAID6] = {
107                 .sub_stripes    = 1,
108                 .dev_stripes    = 1,
109                 .devs_max       = 0,
110                 .devs_min       = 3,
111                 .tolerated_failures = 2,
112                 .devs_increment = 1,
113                 .ncopies        = 1,
114                 .raid_name      = "raid6",
115                 .bg_flag        = BTRFS_BLOCK_GROUP_RAID6,
116                 .mindev_error   = BTRFS_ERROR_DEV_RAID6_MIN_NOT_MET,
117         },
118 };
119
120 const char *get_raid_name(enum btrfs_raid_types type)
121 {
122         if (type >= BTRFS_NR_RAID_TYPES)
123                 return NULL;
124
125         return btrfs_raid_array[type].raid_name;
126 }
127
128 static int init_first_rw_device(struct btrfs_trans_handle *trans,
129                                 struct btrfs_fs_info *fs_info);
130 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info);
131 static void __btrfs_reset_dev_stats(struct btrfs_device *dev);
132 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev);
133 static void btrfs_dev_stat_print_on_load(struct btrfs_device *device);
134 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
135                              enum btrfs_map_op op,
136                              u64 logical, u64 *length,
137                              struct btrfs_bio **bbio_ret,
138                              int mirror_num, int need_raid_map);
139
140 /*
141  * Device locking
142  * ==============
143  *
144  * There are several mutexes that protect manipulation of devices and low-level
145  * structures like chunks but not block groups, extents or files
146  *
147  * uuid_mutex (global lock)
148  * ------------------------
149  * protects the fs_uuids list that tracks all per-fs fs_devices, resulting from
150  * the SCAN_DEV ioctl registration or from mount either implicitly (the first
151  * device) or requested by the device= mount option
152  *
153  * the mutex can be very coarse and can cover long-running operations
154  *
155  * protects: updates to fs_devices counters like missing devices, rw devices,
156  * seeding, structure cloning, openning/closing devices at mount/umount time
157  *
158  * global::fs_devs - add, remove, updates to the global list
159  *
160  * does not protect: manipulation of the fs_devices::devices list in general
161  * but in mount context it could be used to exclude list modifications by eg.
162  * scan ioctl
163  *
164  * btrfs_device::name - renames (write side), read is RCU
165  *
166  * fs_devices::device_list_mutex (per-fs, with RCU)
167  * ------------------------------------------------
168  * protects updates to fs_devices::devices, ie. adding and deleting
169  *
170  * simple list traversal with read-only actions can be done with RCU protection
171  *
172  * may be used to exclude some operations from running concurrently without any
173  * modifications to the list (see write_all_supers)
174  *
175  * Is not required at mount and close times, because our device list is
176  * protected by the uuid_mutex at that point.
177  *
178  * balance_mutex
179  * -------------
180  * protects balance structures (status, state) and context accessed from
181  * several places (internally, ioctl)
182  *
183  * chunk_mutex
184  * -----------
185  * protects chunks, adding or removing during allocation, trim or when a new
186  * device is added/removed
187  *
188  * cleaner_mutex
189  * -------------
190  * a big lock that is held by the cleaner thread and prevents running subvolume
191  * cleaning together with relocation or delayed iputs
192  *
193  *
194  * Lock nesting
195  * ============
196  *
197  * uuid_mutex
198  *   volume_mutex
199  *     device_list_mutex
200  *       chunk_mutex
201  *     balance_mutex
202  *
203  *
204  * Exclusive operations, BTRFS_FS_EXCL_OP
205  * ======================================
206  *
207  * Maintains the exclusivity of the following operations that apply to the
208  * whole filesystem and cannot run in parallel.
209  *
210  * - Balance (*)
211  * - Device add
212  * - Device remove
213  * - Device replace (*)
214  * - Resize
215  *
216  * The device operations (as above) can be in one of the following states:
217  *
218  * - Running state
219  * - Paused state
220  * - Completed state
221  *
222  * Only device operations marked with (*) can go into the Paused state for the
223  * following reasons:
224  *
225  * - ioctl (only Balance can be Paused through ioctl)
226  * - filesystem remounted as read-only
227  * - filesystem unmounted and mounted as read-only
228  * - system power-cycle and filesystem mounted as read-only
229  * - filesystem or device errors leading to forced read-only
230  *
231  * BTRFS_FS_EXCL_OP flag is set and cleared using atomic operations.
232  * During the course of Paused state, the BTRFS_FS_EXCL_OP remains set.
233  * A device operation in Paused or Running state can be canceled or resumed
234  * either by ioctl (Balance only) or when remounted as read-write.
235  * BTRFS_FS_EXCL_OP flag is cleared when the device operation is canceled or
236  * completed.
237  */
238
239 DEFINE_MUTEX(uuid_mutex);
240 static LIST_HEAD(fs_uuids);
241 struct list_head *btrfs_get_fs_uuids(void)
242 {
243         return &fs_uuids;
244 }
245
246 /*
247  * alloc_fs_devices - allocate struct btrfs_fs_devices
248  * @fsid:       if not NULL, copy the uuid to fs_devices::fsid
249  *
250  * Return a pointer to a new struct btrfs_fs_devices on success, or ERR_PTR().
251  * The returned struct is not linked onto any lists and can be destroyed with
252  * kfree() right away.
253  */
254 static struct btrfs_fs_devices *alloc_fs_devices(const u8 *fsid)
255 {
256         struct btrfs_fs_devices *fs_devs;
257
258         fs_devs = kzalloc(sizeof(*fs_devs), GFP_KERNEL);
259         if (!fs_devs)
260                 return ERR_PTR(-ENOMEM);
261
262         mutex_init(&fs_devs->device_list_mutex);
263
264         INIT_LIST_HEAD(&fs_devs->devices);
265         INIT_LIST_HEAD(&fs_devs->resized_devices);
266         INIT_LIST_HEAD(&fs_devs->alloc_list);
267         INIT_LIST_HEAD(&fs_devs->fs_list);
268         if (fsid)
269                 memcpy(fs_devs->fsid, fsid, BTRFS_FSID_SIZE);
270
271         return fs_devs;
272 }
273
274 void btrfs_free_device(struct btrfs_device *device)
275 {
276         rcu_string_free(device->name);
277         bio_put(device->flush_bio);
278         kfree(device);
279 }
280
281 static void free_fs_devices(struct btrfs_fs_devices *fs_devices)
282 {
283         struct btrfs_device *device;
284         WARN_ON(fs_devices->opened);
285         while (!list_empty(&fs_devices->devices)) {
286                 device = list_entry(fs_devices->devices.next,
287                                     struct btrfs_device, dev_list);
288                 list_del(&device->dev_list);
289                 btrfs_free_device(device);
290         }
291         kfree(fs_devices);
292 }
293
294 static void btrfs_kobject_uevent(struct block_device *bdev,
295                                  enum kobject_action action)
296 {
297         int ret;
298
299         ret = kobject_uevent(&disk_to_dev(bdev->bd_disk)->kobj, action);
300         if (ret)
301                 pr_warn("BTRFS: Sending event '%d' to kobject: '%s' (%p): failed\n",
302                         action,
303                         kobject_name(&disk_to_dev(bdev->bd_disk)->kobj),
304                         &disk_to_dev(bdev->bd_disk)->kobj);
305 }
306
307 void __exit btrfs_cleanup_fs_uuids(void)
308 {
309         struct btrfs_fs_devices *fs_devices;
310
311         while (!list_empty(&fs_uuids)) {
312                 fs_devices = list_entry(fs_uuids.next,
313                                         struct btrfs_fs_devices, fs_list);
314                 list_del(&fs_devices->fs_list);
315                 free_fs_devices(fs_devices);
316         }
317 }
318
319 /*
320  * Returns a pointer to a new btrfs_device on success; ERR_PTR() on error.
321  * Returned struct is not linked onto any lists and must be destroyed using
322  * btrfs_free_device.
323  */
324 static struct btrfs_device *__alloc_device(void)
325 {
326         struct btrfs_device *dev;
327
328         dev = kzalloc(sizeof(*dev), GFP_KERNEL);
329         if (!dev)
330                 return ERR_PTR(-ENOMEM);
331
332         /*
333          * Preallocate a bio that's always going to be used for flushing device
334          * barriers and matches the device lifespan
335          */
336         dev->flush_bio = bio_alloc_bioset(GFP_KERNEL, 0, NULL);
337         if (!dev->flush_bio) {
338                 kfree(dev);
339                 return ERR_PTR(-ENOMEM);
340         }
341
342         INIT_LIST_HEAD(&dev->dev_list);
343         INIT_LIST_HEAD(&dev->dev_alloc_list);
344         INIT_LIST_HEAD(&dev->resized_list);
345
346         spin_lock_init(&dev->io_lock);
347
348         atomic_set(&dev->reada_in_flight, 0);
349         atomic_set(&dev->dev_stats_ccnt, 0);
350         btrfs_device_data_ordered_init(dev);
351         INIT_RADIX_TREE(&dev->reada_zones, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
352         INIT_RADIX_TREE(&dev->reada_extents, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
353
354         return dev;
355 }
356
357 static noinline struct btrfs_fs_devices *find_fsid(u8 *fsid)
358 {
359         struct btrfs_fs_devices *fs_devices;
360
361         list_for_each_entry(fs_devices, &fs_uuids, fs_list) {
362                 if (memcmp(fsid, fs_devices->fsid, BTRFS_FSID_SIZE) == 0)
363                         return fs_devices;
364         }
365         return NULL;
366 }
367
368 static int
369 btrfs_get_bdev_and_sb(const char *device_path, fmode_t flags, void *holder,
370                       int flush, struct block_device **bdev,
371                       struct buffer_head **bh)
372 {
373         int ret;
374
375         *bdev = blkdev_get_by_path(device_path, flags, holder);
376
377         if (IS_ERR(*bdev)) {
378                 ret = PTR_ERR(*bdev);
379                 goto error;
380         }
381
382         if (flush)
383                 filemap_write_and_wait((*bdev)->bd_inode->i_mapping);
384         ret = set_blocksize(*bdev, BTRFS_BDEV_BLOCKSIZE);
385         if (ret) {
386                 blkdev_put(*bdev, flags);
387                 goto error;
388         }
389         invalidate_bdev(*bdev);
390         *bh = btrfs_read_dev_super(*bdev);
391         if (IS_ERR(*bh)) {
392                 ret = PTR_ERR(*bh);
393                 blkdev_put(*bdev, flags);
394                 goto error;
395         }
396
397         return 0;
398
399 error:
400         *bdev = NULL;
401         *bh = NULL;
402         return ret;
403 }
404
405 static void requeue_list(struct btrfs_pending_bios *pending_bios,
406                         struct bio *head, struct bio *tail)
407 {
408
409         struct bio *old_head;
410
411         old_head = pending_bios->head;
412         pending_bios->head = head;
413         if (pending_bios->tail)
414                 tail->bi_next = old_head;
415         else
416                 pending_bios->tail = tail;
417 }
418
419 /*
420  * we try to collect pending bios for a device so we don't get a large
421  * number of procs sending bios down to the same device.  This greatly
422  * improves the schedulers ability to collect and merge the bios.
423  *
424  * But, it also turns into a long list of bios to process and that is sure
425  * to eventually make the worker thread block.  The solution here is to
426  * make some progress and then put this work struct back at the end of
427  * the list if the block device is congested.  This way, multiple devices
428  * can make progress from a single worker thread.
429  */
430 static noinline void run_scheduled_bios(struct btrfs_device *device)
431 {
432         struct btrfs_fs_info *fs_info = device->fs_info;
433         struct bio *pending;
434         struct backing_dev_info *bdi;
435         struct btrfs_pending_bios *pending_bios;
436         struct bio *tail;
437         struct bio *cur;
438         int again = 0;
439         unsigned long num_run;
440         unsigned long batch_run = 0;
441         unsigned long last_waited = 0;
442         int force_reg = 0;
443         int sync_pending = 0;
444         struct blk_plug plug;
445
446         /*
447          * this function runs all the bios we've collected for
448          * a particular device.  We don't want to wander off to
449          * another device without first sending all of these down.
450          * So, setup a plug here and finish it off before we return
451          */
452         blk_start_plug(&plug);
453
454         bdi = device->bdev->bd_bdi;
455
456 loop:
457         spin_lock(&device->io_lock);
458
459 loop_lock:
460         num_run = 0;
461
462         /* take all the bios off the list at once and process them
463          * later on (without the lock held).  But, remember the
464          * tail and other pointers so the bios can be properly reinserted
465          * into the list if we hit congestion
466          */
467         if (!force_reg && device->pending_sync_bios.head) {
468                 pending_bios = &device->pending_sync_bios;
469                 force_reg = 1;
470         } else {
471                 pending_bios = &device->pending_bios;
472                 force_reg = 0;
473         }
474
475         pending = pending_bios->head;
476         tail = pending_bios->tail;
477         WARN_ON(pending && !tail);
478
479         /*
480          * if pending was null this time around, no bios need processing
481          * at all and we can stop.  Otherwise it'll loop back up again
482          * and do an additional check so no bios are missed.
483          *
484          * device->running_pending is used to synchronize with the
485          * schedule_bio code.
486          */
487         if (device->pending_sync_bios.head == NULL &&
488             device->pending_bios.head == NULL) {
489                 again = 0;
490                 device->running_pending = 0;
491         } else {
492                 again = 1;
493                 device->running_pending = 1;
494         }
495
496         pending_bios->head = NULL;
497         pending_bios->tail = NULL;
498
499         spin_unlock(&device->io_lock);
500
501         while (pending) {
502
503                 rmb();
504                 /* we want to work on both lists, but do more bios on the
505                  * sync list than the regular list
506                  */
507                 if ((num_run > 32 &&
508                     pending_bios != &device->pending_sync_bios &&
509                     device->pending_sync_bios.head) ||
510                    (num_run > 64 && pending_bios == &device->pending_sync_bios &&
511                     device->pending_bios.head)) {
512                         spin_lock(&device->io_lock);
513                         requeue_list(pending_bios, pending, tail);
514                         goto loop_lock;
515                 }
516
517                 cur = pending;
518                 pending = pending->bi_next;
519                 cur->bi_next = NULL;
520
521                 BUG_ON(atomic_read(&cur->__bi_cnt) == 0);
522
523                 /*
524                  * if we're doing the sync list, record that our
525                  * plug has some sync requests on it
526                  *
527                  * If we're doing the regular list and there are
528                  * sync requests sitting around, unplug before
529                  * we add more
530                  */
531                 if (pending_bios == &device->pending_sync_bios) {
532                         sync_pending = 1;
533                 } else if (sync_pending) {
534                         blk_finish_plug(&plug);
535                         blk_start_plug(&plug);
536                         sync_pending = 0;
537                 }
538
539                 btrfsic_submit_bio(cur);
540                 num_run++;
541                 batch_run++;
542
543                 cond_resched();
544
545                 /*
546                  * we made progress, there is more work to do and the bdi
547                  * is now congested.  Back off and let other work structs
548                  * run instead
549                  */
550                 if (pending && bdi_write_congested(bdi) && batch_run > 8 &&
551                     fs_info->fs_devices->open_devices > 1) {
552                         struct io_context *ioc;
553
554                         ioc = current->io_context;
555
556                         /*
557                          * the main goal here is that we don't want to
558                          * block if we're going to be able to submit
559                          * more requests without blocking.
560                          *
561                          * This code does two great things, it pokes into
562                          * the elevator code from a filesystem _and_
563                          * it makes assumptions about how batching works.
564                          */
565                         if (ioc && ioc->nr_batch_requests > 0 &&
566                             time_before(jiffies, ioc->last_waited + HZ/50UL) &&
567                             (last_waited == 0 ||
568                              ioc->last_waited == last_waited)) {
569                                 /*
570                                  * we want to go through our batch of
571                                  * requests and stop.  So, we copy out
572                                  * the ioc->last_waited time and test
573                                  * against it before looping
574                                  */
575                                 last_waited = ioc->last_waited;
576                                 cond_resched();
577                                 continue;
578                         }
579                         spin_lock(&device->io_lock);
580                         requeue_list(pending_bios, pending, tail);
581                         device->running_pending = 1;
582
583                         spin_unlock(&device->io_lock);
584                         btrfs_queue_work(fs_info->submit_workers,
585                                          &device->work);
586                         goto done;
587                 }
588         }
589
590         cond_resched();
591         if (again)
592                 goto loop;
593
594         spin_lock(&device->io_lock);
595         if (device->pending_bios.head || device->pending_sync_bios.head)
596                 goto loop_lock;
597         spin_unlock(&device->io_lock);
598
599 done:
600         blk_finish_plug(&plug);
601 }
602
603 static void pending_bios_fn(struct btrfs_work *work)
604 {
605         struct btrfs_device *device;
606
607         device = container_of(work, struct btrfs_device, work);
608         run_scheduled_bios(device);
609 }
610
611 /*
612  *  Search and remove all stale (devices which are not mounted) devices.
613  *  When both inputs are NULL, it will search and release all stale devices.
614  *  path:       Optional. When provided will it release all unmounted devices
615  *              matching this path only.
616  *  skip_dev:   Optional. Will skip this device when searching for the stale
617  *              devices.
618  */
619 static void btrfs_free_stale_devices(const char *path,
620                                      struct btrfs_device *skip_device)
621 {
622         struct btrfs_fs_devices *fs_devices, *tmp_fs_devices;
623         struct btrfs_device *device, *tmp_device;
624
625         list_for_each_entry_safe(fs_devices, tmp_fs_devices, &fs_uuids, fs_list) {
626                 mutex_lock(&fs_devices->device_list_mutex);
627                 if (fs_devices->opened) {
628                         mutex_unlock(&fs_devices->device_list_mutex);
629                         continue;
630                 }
631
632                 list_for_each_entry_safe(device, tmp_device,
633                                          &fs_devices->devices, dev_list) {
634                         int not_found = 0;
635
636                         if (skip_device && skip_device == device)
637                                 continue;
638                         if (path && !device->name)
639                                 continue;
640
641                         rcu_read_lock();
642                         if (path)
643                                 not_found = strcmp(rcu_str_deref(device->name),
644                                                    path);
645                         rcu_read_unlock();
646                         if (not_found)
647                                 continue;
648
649                         /* delete the stale device */
650                         fs_devices->num_devices--;
651                         list_del(&device->dev_list);
652                         btrfs_free_device(device);
653
654                         if (fs_devices->num_devices == 0)
655                                 break;
656                 }
657                 mutex_unlock(&fs_devices->device_list_mutex);
658                 if (fs_devices->num_devices == 0) {
659                         btrfs_sysfs_remove_fsid(fs_devices);
660                         list_del(&fs_devices->fs_list);
661                         free_fs_devices(fs_devices);
662                 }
663         }
664 }
665
666 /*
667  * This is only used on mount, and we are protected from competing things
668  * messing with our fs_devices by the uuid_mutex, thus we do not need the
669  * fs_devices->device_list_mutex here.
670  */
671 static int btrfs_open_one_device(struct btrfs_fs_devices *fs_devices,
672                         struct btrfs_device *device, fmode_t flags,
673                         void *holder)
674 {
675         struct request_queue *q;
676         struct block_device *bdev;
677         struct buffer_head *bh;
678         struct btrfs_super_block *disk_super;
679         u64 devid;
680         int ret;
681
682         if (device->bdev)
683                 return -EINVAL;
684         if (!device->name)
685                 return -EINVAL;
686
687         ret = btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
688                                     &bdev, &bh);
689         if (ret)
690                 return ret;
691
692         disk_super = (struct btrfs_super_block *)bh->b_data;
693         devid = btrfs_stack_device_id(&disk_super->dev_item);
694         if (devid != device->devid)
695                 goto error_brelse;
696
697         if (memcmp(device->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE))
698                 goto error_brelse;
699
700         device->generation = btrfs_super_generation(disk_super);
701
702         if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
703                 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
704                 fs_devices->seeding = 1;
705         } else {
706                 if (bdev_read_only(bdev))
707                         clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
708                 else
709                         set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
710         }
711
712         q = bdev_get_queue(bdev);
713         if (!blk_queue_nonrot(q))
714                 fs_devices->rotating = 1;
715
716         device->bdev = bdev;
717         clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
718         device->mode = flags;
719
720         fs_devices->open_devices++;
721         if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
722             device->devid != BTRFS_DEV_REPLACE_DEVID) {
723                 fs_devices->rw_devices++;
724                 list_add_tail(&device->dev_alloc_list, &fs_devices->alloc_list);
725         }
726         brelse(bh);
727
728         return 0;
729
730 error_brelse:
731         brelse(bh);
732         blkdev_put(bdev, flags);
733
734         return -EINVAL;
735 }
736
737 /*
738  * Add new device to list of registered devices
739  *
740  * Returns:
741  * device pointer which was just added or updated when successful
742  * error pointer when failed
743  */
744 static noinline struct btrfs_device *device_list_add(const char *path,
745                            struct btrfs_super_block *disk_super,
746                            bool *new_device_added)
747 {
748         struct btrfs_device *device;
749         struct btrfs_fs_devices *fs_devices;
750         struct rcu_string *name;
751         u64 found_transid = btrfs_super_generation(disk_super);
752         u64 devid = btrfs_stack_device_id(&disk_super->dev_item);
753
754         fs_devices = find_fsid(disk_super->fsid);
755         if (!fs_devices) {
756                 fs_devices = alloc_fs_devices(disk_super->fsid);
757                 if (IS_ERR(fs_devices))
758                         return ERR_CAST(fs_devices);
759
760                 mutex_lock(&fs_devices->device_list_mutex);
761                 list_add(&fs_devices->fs_list, &fs_uuids);
762
763                 device = NULL;
764         } else {
765                 mutex_lock(&fs_devices->device_list_mutex);
766                 device = btrfs_find_device(fs_devices, devid,
767                                 disk_super->dev_item.uuid, NULL, false);
768         }
769
770         if (!device) {
771                 if (fs_devices->opened) {
772                         mutex_unlock(&fs_devices->device_list_mutex);
773                         return ERR_PTR(-EBUSY);
774                 }
775
776                 device = btrfs_alloc_device(NULL, &devid,
777                                             disk_super->dev_item.uuid);
778                 if (IS_ERR(device)) {
779                         mutex_unlock(&fs_devices->device_list_mutex);
780                         /* we can safely leave the fs_devices entry around */
781                         return device;
782                 }
783
784                 name = rcu_string_strdup(path, GFP_NOFS);
785                 if (!name) {
786                         btrfs_free_device(device);
787                         mutex_unlock(&fs_devices->device_list_mutex);
788                         return ERR_PTR(-ENOMEM);
789                 }
790                 rcu_assign_pointer(device->name, name);
791
792                 list_add_rcu(&device->dev_list, &fs_devices->devices);
793                 fs_devices->num_devices++;
794
795                 device->fs_devices = fs_devices;
796                 *new_device_added = true;
797
798                 if (disk_super->label[0])
799                         pr_info("BTRFS: device label %s devid %llu transid %llu %s\n",
800                                 disk_super->label, devid, found_transid, path);
801                 else
802                         pr_info("BTRFS: device fsid %pU devid %llu transid %llu %s\n",
803                                 disk_super->fsid, devid, found_transid, path);
804
805         } else if (!device->name || strcmp(device->name->str, path)) {
806                 /*
807                  * When FS is already mounted.
808                  * 1. If you are here and if the device->name is NULL that
809                  *    means this device was missing at time of FS mount.
810                  * 2. If you are here and if the device->name is different
811                  *    from 'path' that means either
812                  *      a. The same device disappeared and reappeared with
813                  *         different name. or
814                  *      b. The missing-disk-which-was-replaced, has
815                  *         reappeared now.
816                  *
817                  * We must allow 1 and 2a above. But 2b would be a spurious
818                  * and unintentional.
819                  *
820                  * Further in case of 1 and 2a above, the disk at 'path'
821                  * would have missed some transaction when it was away and
822                  * in case of 2a the stale bdev has to be updated as well.
823                  * 2b must not be allowed at all time.
824                  */
825
826                 /*
827                  * For now, we do allow update to btrfs_fs_device through the
828                  * btrfs dev scan cli after FS has been mounted.  We're still
829                  * tracking a problem where systems fail mount by subvolume id
830                  * when we reject replacement on a mounted FS.
831                  */
832                 if (!fs_devices->opened && found_transid < device->generation) {
833                         /*
834                          * That is if the FS is _not_ mounted and if you
835                          * are here, that means there is more than one
836                          * disk with same uuid and devid.We keep the one
837                          * with larger generation number or the last-in if
838                          * generation are equal.
839                          */
840                         mutex_unlock(&fs_devices->device_list_mutex);
841                         return ERR_PTR(-EEXIST);
842                 }
843
844                 /*
845                  * We are going to replace the device path for a given devid,
846                  * make sure it's the same device if the device is mounted
847                  */
848                 if (device->bdev) {
849                         struct block_device *path_bdev;
850
851                         path_bdev = lookup_bdev(path);
852                         if (IS_ERR(path_bdev)) {
853                                 mutex_unlock(&fs_devices->device_list_mutex);
854                                 return ERR_CAST(path_bdev);
855                         }
856
857                         if (device->bdev != path_bdev) {
858                                 bdput(path_bdev);
859                                 mutex_unlock(&fs_devices->device_list_mutex);
860                                 /*
861                                  * device->fs_info may not be reliable here, so
862                                  * pass in a NULL instead. This avoids a
863                                  * possible use-after-free when the fs_info and
864                                  * fs_info->sb are already torn down.
865                                  */
866                                 btrfs_warn_in_rcu(NULL,
867         "duplicate device %s devid %llu generation %llu scanned by %s (%d)",
868                                                   path, devid, found_transid,
869                                                   current->comm,
870                                                   task_pid_nr(current));
871                                 return ERR_PTR(-EEXIST);
872                         }
873                         bdput(path_bdev);
874                         btrfs_info_in_rcu(device->fs_info,
875         "devid %llu device path %s changed to %s scanned by %s (%d)",
876                                           devid, rcu_str_deref(device->name),
877                                           path, current->comm,
878                                           task_pid_nr(current));
879                 }
880
881                 name = rcu_string_strdup(path, GFP_NOFS);
882                 if (!name) {
883                         mutex_unlock(&fs_devices->device_list_mutex);
884                         return ERR_PTR(-ENOMEM);
885                 }
886                 rcu_string_free(device->name);
887                 rcu_assign_pointer(device->name, name);
888                 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
889                         fs_devices->missing_devices--;
890                         clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
891                 }
892         }
893
894         /*
895          * Unmount does not free the btrfs_device struct but would zero
896          * generation along with most of the other members. So just update
897          * it back. We need it to pick the disk with largest generation
898          * (as above).
899          */
900         if (!fs_devices->opened)
901                 device->generation = found_transid;
902
903         fs_devices->total_devices = btrfs_super_num_devices(disk_super);
904
905         mutex_unlock(&fs_devices->device_list_mutex);
906         return device;
907 }
908
909 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
910 {
911         struct btrfs_fs_devices *fs_devices;
912         struct btrfs_device *device;
913         struct btrfs_device *orig_dev;
914
915         fs_devices = alloc_fs_devices(orig->fsid);
916         if (IS_ERR(fs_devices))
917                 return fs_devices;
918
919         mutex_lock(&orig->device_list_mutex);
920         fs_devices->total_devices = orig->total_devices;
921
922         /* We have held the volume lock, it is safe to get the devices. */
923         list_for_each_entry(orig_dev, &orig->devices, dev_list) {
924                 struct rcu_string *name;
925
926                 device = btrfs_alloc_device(NULL, &orig_dev->devid,
927                                             orig_dev->uuid);
928                 if (IS_ERR(device))
929                         goto error;
930
931                 /*
932                  * This is ok to do without rcu read locked because we hold the
933                  * uuid mutex so nothing we touch in here is going to disappear.
934                  */
935                 if (orig_dev->name) {
936                         name = rcu_string_strdup(orig_dev->name->str,
937                                         GFP_KERNEL);
938                         if (!name) {
939                                 btrfs_free_device(device);
940                                 goto error;
941                         }
942                         rcu_assign_pointer(device->name, name);
943                 }
944
945                 list_add(&device->dev_list, &fs_devices->devices);
946                 device->fs_devices = fs_devices;
947                 fs_devices->num_devices++;
948         }
949         mutex_unlock(&orig->device_list_mutex);
950         return fs_devices;
951 error:
952         mutex_unlock(&orig->device_list_mutex);
953         free_fs_devices(fs_devices);
954         return ERR_PTR(-ENOMEM);
955 }
956
957 /*
958  * After we have read the system tree and know devids belonging to
959  * this filesystem, remove the device which does not belong there.
960  */
961 void btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices, int step)
962 {
963         struct btrfs_device *device, *next;
964         struct btrfs_device *latest_dev = NULL;
965
966         mutex_lock(&uuid_mutex);
967 again:
968         /* This is the initialized path, it is safe to release the devices. */
969         list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
970                 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
971                                                         &device->dev_state)) {
972                         if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
973                              &device->dev_state) &&
974                             !test_bit(BTRFS_DEV_STATE_MISSING,
975                                       &device->dev_state) &&
976                              (!latest_dev ||
977                               device->generation > latest_dev->generation)) {
978                                 latest_dev = device;
979                         }
980                         continue;
981                 }
982
983                 /*
984                  * We have already validated the presence of BTRFS_DEV_REPLACE_DEVID,
985                  * in btrfs_init_dev_replace() so just continue.
986                  */
987                 if (device->devid == BTRFS_DEV_REPLACE_DEVID)
988                         continue;
989
990                 if (device->bdev) {
991                         blkdev_put(device->bdev, device->mode);
992                         device->bdev = NULL;
993                         fs_devices->open_devices--;
994                 }
995                 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
996                         list_del_init(&device->dev_alloc_list);
997                         clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
998                         fs_devices->rw_devices--;
999                 }
1000                 list_del_init(&device->dev_list);
1001                 fs_devices->num_devices--;
1002                 btrfs_free_device(device);
1003         }
1004
1005         if (fs_devices->seed) {
1006                 fs_devices = fs_devices->seed;
1007                 goto again;
1008         }
1009
1010         fs_devices->latest_bdev = latest_dev->bdev;
1011
1012         mutex_unlock(&uuid_mutex);
1013 }
1014
1015 static void free_device_rcu(struct rcu_head *head)
1016 {
1017         struct btrfs_device *device;
1018
1019         device = container_of(head, struct btrfs_device, rcu);
1020         btrfs_free_device(device);
1021 }
1022
1023 static void btrfs_close_bdev(struct btrfs_device *device)
1024 {
1025         if (!device->bdev)
1026                 return;
1027
1028         if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1029                 sync_blockdev(device->bdev);
1030                 invalidate_bdev(device->bdev);
1031         }
1032
1033         blkdev_put(device->bdev, device->mode);
1034 }
1035
1036 static void btrfs_close_one_device(struct btrfs_device *device)
1037 {
1038         struct btrfs_fs_devices *fs_devices = device->fs_devices;
1039         struct btrfs_device *new_device;
1040         struct rcu_string *name;
1041
1042         if (device->bdev)
1043                 fs_devices->open_devices--;
1044
1045         if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1046             device->devid != BTRFS_DEV_REPLACE_DEVID) {
1047                 list_del_init(&device->dev_alloc_list);
1048                 fs_devices->rw_devices--;
1049         }
1050
1051         if (device->devid == BTRFS_DEV_REPLACE_DEVID)
1052                 clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
1053
1054         if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
1055                 fs_devices->missing_devices--;
1056
1057         btrfs_close_bdev(device);
1058
1059         new_device = btrfs_alloc_device(NULL, &device->devid,
1060                                         device->uuid);
1061         BUG_ON(IS_ERR(new_device)); /* -ENOMEM */
1062
1063         /* Safe because we are under uuid_mutex */
1064         if (device->name) {
1065                 name = rcu_string_strdup(device->name->str, GFP_NOFS);
1066                 BUG_ON(!name); /* -ENOMEM */
1067                 rcu_assign_pointer(new_device->name, name);
1068         }
1069
1070         list_replace_rcu(&device->dev_list, &new_device->dev_list);
1071         new_device->fs_devices = device->fs_devices;
1072
1073         call_rcu(&device->rcu, free_device_rcu);
1074 }
1075
1076 static int close_fs_devices(struct btrfs_fs_devices *fs_devices)
1077 {
1078         struct btrfs_device *device, *tmp;
1079
1080         if (--fs_devices->opened > 0)
1081                 return 0;
1082
1083         mutex_lock(&fs_devices->device_list_mutex);
1084         list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list) {
1085                 btrfs_close_one_device(device);
1086         }
1087         mutex_unlock(&fs_devices->device_list_mutex);
1088
1089         WARN_ON(fs_devices->open_devices);
1090         WARN_ON(fs_devices->rw_devices);
1091         fs_devices->opened = 0;
1092         fs_devices->seeding = 0;
1093
1094         return 0;
1095 }
1096
1097 int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
1098 {
1099         struct btrfs_fs_devices *seed_devices = NULL;
1100         int ret;
1101
1102         mutex_lock(&uuid_mutex);
1103         ret = close_fs_devices(fs_devices);
1104         if (!fs_devices->opened) {
1105                 seed_devices = fs_devices->seed;
1106                 fs_devices->seed = NULL;
1107         }
1108         mutex_unlock(&uuid_mutex);
1109
1110         while (seed_devices) {
1111                 fs_devices = seed_devices;
1112                 seed_devices = fs_devices->seed;
1113                 close_fs_devices(fs_devices);
1114                 free_fs_devices(fs_devices);
1115         }
1116         return ret;
1117 }
1118
1119 static int open_fs_devices(struct btrfs_fs_devices *fs_devices,
1120                                 fmode_t flags, void *holder)
1121 {
1122         struct btrfs_device *device;
1123         struct btrfs_device *latest_dev = NULL;
1124         int ret = 0;
1125
1126         flags |= FMODE_EXCL;
1127
1128         list_for_each_entry(device, &fs_devices->devices, dev_list) {
1129                 /* Just open everything we can; ignore failures here */
1130                 if (btrfs_open_one_device(fs_devices, device, flags, holder))
1131                         continue;
1132
1133                 if (!latest_dev ||
1134                     device->generation > latest_dev->generation)
1135                         latest_dev = device;
1136         }
1137         if (fs_devices->open_devices == 0) {
1138                 ret = -EINVAL;
1139                 goto out;
1140         }
1141         fs_devices->opened = 1;
1142         fs_devices->latest_bdev = latest_dev->bdev;
1143         fs_devices->total_rw_bytes = 0;
1144 out:
1145         return ret;
1146 }
1147
1148 static int devid_cmp(void *priv, struct list_head *a, struct list_head *b)
1149 {
1150         struct btrfs_device *dev1, *dev2;
1151
1152         dev1 = list_entry(a, struct btrfs_device, dev_list);
1153         dev2 = list_entry(b, struct btrfs_device, dev_list);
1154
1155         if (dev1->devid < dev2->devid)
1156                 return -1;
1157         else if (dev1->devid > dev2->devid)
1158                 return 1;
1159         return 0;
1160 }
1161
1162 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
1163                        fmode_t flags, void *holder)
1164 {
1165         int ret;
1166
1167         lockdep_assert_held(&uuid_mutex);
1168         /*
1169          * The device_list_mutex cannot be taken here in case opening the
1170          * underlying device takes further locks like bd_mutex.
1171          *
1172          * We also don't need the lock here as this is called during mount and
1173          * exclusion is provided by uuid_mutex
1174          */
1175
1176         if (fs_devices->opened) {
1177                 fs_devices->opened++;
1178                 ret = 0;
1179         } else {
1180                 list_sort(NULL, &fs_devices->devices, devid_cmp);
1181                 ret = open_fs_devices(fs_devices, flags, holder);
1182         }
1183
1184         return ret;
1185 }
1186
1187 static void btrfs_release_disk_super(struct page *page)
1188 {
1189         kunmap(page);
1190         put_page(page);
1191 }
1192
1193 static int btrfs_read_disk_super(struct block_device *bdev, u64 bytenr,
1194                                  struct page **page,
1195                                  struct btrfs_super_block **disk_super)
1196 {
1197         void *p;
1198         pgoff_t index;
1199
1200         /* make sure our super fits in the device */
1201         if (bytenr + PAGE_SIZE >= i_size_read(bdev->bd_inode))
1202                 return 1;
1203
1204         /* make sure our super fits in the page */
1205         if (sizeof(**disk_super) > PAGE_SIZE)
1206                 return 1;
1207
1208         /* make sure our super doesn't straddle pages on disk */
1209         index = bytenr >> PAGE_SHIFT;
1210         if ((bytenr + sizeof(**disk_super) - 1) >> PAGE_SHIFT != index)
1211                 return 1;
1212
1213         /* pull in the page with our super */
1214         *page = read_cache_page_gfp(bdev->bd_inode->i_mapping,
1215                                    index, GFP_KERNEL);
1216
1217         if (IS_ERR_OR_NULL(*page))
1218                 return 1;
1219
1220         p = kmap(*page);
1221
1222         /* align our pointer to the offset of the super block */
1223         *disk_super = p + (bytenr & ~PAGE_MASK);
1224
1225         if (btrfs_super_bytenr(*disk_super) != bytenr ||
1226             btrfs_super_magic(*disk_super) != BTRFS_MAGIC) {
1227                 btrfs_release_disk_super(*page);
1228                 return 1;
1229         }
1230
1231         if ((*disk_super)->label[0] &&
1232                 (*disk_super)->label[BTRFS_LABEL_SIZE - 1])
1233                 (*disk_super)->label[BTRFS_LABEL_SIZE - 1] = '\0';
1234
1235         return 0;
1236 }
1237
1238 /*
1239  * Look for a btrfs signature on a device. This may be called out of the mount path
1240  * and we are not allowed to call set_blocksize during the scan. The superblock
1241  * is read via pagecache
1242  */
1243 struct btrfs_device *btrfs_scan_one_device(const char *path, fmode_t flags,
1244                                            void *holder)
1245 {
1246         struct btrfs_super_block *disk_super;
1247         bool new_device_added = false;
1248         struct btrfs_device *device = NULL;
1249         struct block_device *bdev;
1250         struct page *page;
1251         u64 bytenr;
1252
1253         lockdep_assert_held(&uuid_mutex);
1254
1255         /*
1256          * we would like to check all the supers, but that would make
1257          * a btrfs mount succeed after a mkfs from a different FS.
1258          * So, we need to add a special mount option to scan for
1259          * later supers, using BTRFS_SUPER_MIRROR_MAX instead
1260          */
1261         bytenr = btrfs_sb_offset(0);
1262         flags |= FMODE_EXCL;
1263
1264         bdev = blkdev_get_by_path(path, flags, holder);
1265         if (IS_ERR(bdev))
1266                 return ERR_CAST(bdev);
1267
1268         if (btrfs_read_disk_super(bdev, bytenr, &page, &disk_super)) {
1269                 device = ERR_PTR(-EINVAL);
1270                 goto error_bdev_put;
1271         }
1272
1273         device = device_list_add(path, disk_super, &new_device_added);
1274         if (!IS_ERR(device)) {
1275                 if (new_device_added)
1276                         btrfs_free_stale_devices(path, device);
1277         }
1278
1279         btrfs_release_disk_super(page);
1280
1281 error_bdev_put:
1282         blkdev_put(bdev, flags);
1283
1284         return device;
1285 }
1286
1287 static int contains_pending_extent(struct btrfs_transaction *transaction,
1288                                    struct btrfs_device *device,
1289                                    u64 *start, u64 len)
1290 {
1291         struct btrfs_fs_info *fs_info = device->fs_info;
1292         struct extent_map *em;
1293         struct list_head *search_list = &fs_info->pinned_chunks;
1294         int ret = 0;
1295         u64 physical_start = *start;
1296
1297         if (transaction)
1298                 search_list = &transaction->pending_chunks;
1299 again:
1300         list_for_each_entry(em, search_list, list) {
1301                 struct map_lookup *map;
1302                 int i;
1303
1304                 map = em->map_lookup;
1305                 for (i = 0; i < map->num_stripes; i++) {
1306                         u64 end;
1307
1308                         if (map->stripes[i].dev != device)
1309                                 continue;
1310                         if (map->stripes[i].physical >= physical_start + len ||
1311                             map->stripes[i].physical + em->orig_block_len <=
1312                             physical_start)
1313                                 continue;
1314                         /*
1315                          * Make sure that while processing the pinned list we do
1316                          * not override our *start with a lower value, because
1317                          * we can have pinned chunks that fall within this
1318                          * device hole and that have lower physical addresses
1319                          * than the pending chunks we processed before. If we
1320                          * do not take this special care we can end up getting
1321                          * 2 pending chunks that start at the same physical
1322                          * device offsets because the end offset of a pinned
1323                          * chunk can be equal to the start offset of some
1324                          * pending chunk.
1325                          */
1326                         end = map->stripes[i].physical + em->orig_block_len;
1327                         if (end > *start) {
1328                                 *start = end;
1329                                 ret = 1;
1330                         }
1331                 }
1332         }
1333         if (search_list != &fs_info->pinned_chunks) {
1334                 search_list = &fs_info->pinned_chunks;
1335                 goto again;
1336         }
1337
1338         return ret;
1339 }
1340
1341
1342 /*
1343  * find_free_dev_extent_start - find free space in the specified device
1344  * @device:       the device which we search the free space in
1345  * @num_bytes:    the size of the free space that we need
1346  * @search_start: the position from which to begin the search
1347  * @start:        store the start of the free space.
1348  * @len:          the size of the free space. that we find, or the size
1349  *                of the max free space if we don't find suitable free space
1350  *
1351  * this uses a pretty simple search, the expectation is that it is
1352  * called very infrequently and that a given device has a small number
1353  * of extents
1354  *
1355  * @start is used to store the start of the free space if we find. But if we
1356  * don't find suitable free space, it will be used to store the start position
1357  * of the max free space.
1358  *
1359  * @len is used to store the size of the free space that we find.
1360  * But if we don't find suitable free space, it is used to store the size of
1361  * the max free space.
1362  */
1363 int find_free_dev_extent_start(struct btrfs_transaction *transaction,
1364                                struct btrfs_device *device, u64 num_bytes,
1365                                u64 search_start, u64 *start, u64 *len)
1366 {
1367         struct btrfs_fs_info *fs_info = device->fs_info;
1368         struct btrfs_root *root = fs_info->dev_root;
1369         struct btrfs_key key;
1370         struct btrfs_dev_extent *dev_extent;
1371         struct btrfs_path *path;
1372         u64 hole_size;
1373         u64 max_hole_start;
1374         u64 max_hole_size;
1375         u64 extent_end;
1376         u64 search_end = device->total_bytes;
1377         int ret;
1378         int slot;
1379         struct extent_buffer *l;
1380
1381         /*
1382          * We don't want to overwrite the superblock on the drive nor any area
1383          * used by the boot loader (grub for example), so we make sure to start
1384          * at an offset of at least 1MB.
1385          */
1386         search_start = max_t(u64, search_start, SZ_1M);
1387
1388         path = btrfs_alloc_path();
1389         if (!path)
1390                 return -ENOMEM;
1391
1392         max_hole_start = search_start;
1393         max_hole_size = 0;
1394
1395 again:
1396         if (search_start >= search_end ||
1397                 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1398                 ret = -ENOSPC;
1399                 goto out;
1400         }
1401
1402         path->reada = READA_FORWARD;
1403         path->search_commit_root = 1;
1404         path->skip_locking = 1;
1405
1406         key.objectid = device->devid;
1407         key.offset = search_start;
1408         key.type = BTRFS_DEV_EXTENT_KEY;
1409
1410         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1411         if (ret < 0)
1412                 goto out;
1413         if (ret > 0) {
1414                 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1415                 if (ret < 0)
1416                         goto out;
1417         }
1418
1419         while (1) {
1420                 l = path->nodes[0];
1421                 slot = path->slots[0];
1422                 if (slot >= btrfs_header_nritems(l)) {
1423                         ret = btrfs_next_leaf(root, path);
1424                         if (ret == 0)
1425                                 continue;
1426                         if (ret < 0)
1427                                 goto out;
1428
1429                         break;
1430                 }
1431                 btrfs_item_key_to_cpu(l, &key, slot);
1432
1433                 if (key.objectid < device->devid)
1434                         goto next;
1435
1436                 if (key.objectid > device->devid)
1437                         break;
1438
1439                 if (key.type != BTRFS_DEV_EXTENT_KEY)
1440                         goto next;
1441
1442                 if (key.offset > search_start) {
1443                         hole_size = key.offset - search_start;
1444
1445                         /*
1446                          * Have to check before we set max_hole_start, otherwise
1447                          * we could end up sending back this offset anyway.
1448                          */
1449                         if (contains_pending_extent(transaction, device,
1450                                                     &search_start,
1451                                                     hole_size)) {
1452                                 if (key.offset >= search_start) {
1453                                         hole_size = key.offset - search_start;
1454                                 } else {
1455                                         WARN_ON_ONCE(1);
1456                                         hole_size = 0;
1457                                 }
1458                         }
1459
1460                         if (hole_size > max_hole_size) {
1461                                 max_hole_start = search_start;
1462                                 max_hole_size = hole_size;
1463                         }
1464
1465                         /*
1466                          * If this free space is greater than which we need,
1467                          * it must be the max free space that we have found
1468                          * until now, so max_hole_start must point to the start
1469                          * of this free space and the length of this free space
1470                          * is stored in max_hole_size. Thus, we return
1471                          * max_hole_start and max_hole_size and go back to the
1472                          * caller.
1473                          */
1474                         if (hole_size >= num_bytes) {
1475                                 ret = 0;
1476                                 goto out;
1477                         }
1478                 }
1479
1480                 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1481                 extent_end = key.offset + btrfs_dev_extent_length(l,
1482                                                                   dev_extent);
1483                 if (extent_end > search_start)
1484                         search_start = extent_end;
1485 next:
1486                 path->slots[0]++;
1487                 cond_resched();
1488         }
1489
1490         /*
1491          * At this point, search_start should be the end of
1492          * allocated dev extents, and when shrinking the device,
1493          * search_end may be smaller than search_start.
1494          */
1495         if (search_end > search_start) {
1496                 hole_size = search_end - search_start;
1497
1498                 if (contains_pending_extent(transaction, device, &search_start,
1499                                             hole_size)) {
1500                         btrfs_release_path(path);
1501                         goto again;
1502                 }
1503
1504                 if (hole_size > max_hole_size) {
1505                         max_hole_start = search_start;
1506                         max_hole_size = hole_size;
1507                 }
1508         }
1509
1510         /* See above. */
1511         if (max_hole_size < num_bytes)
1512                 ret = -ENOSPC;
1513         else
1514                 ret = 0;
1515
1516 out:
1517         btrfs_free_path(path);
1518         *start = max_hole_start;
1519         if (len)
1520                 *len = max_hole_size;
1521         return ret;
1522 }
1523
1524 int find_free_dev_extent(struct btrfs_trans_handle *trans,
1525                          struct btrfs_device *device, u64 num_bytes,
1526                          u64 *start, u64 *len)
1527 {
1528         /* FIXME use last free of some kind */
1529         return find_free_dev_extent_start(trans->transaction, device,
1530                                           num_bytes, 0, start, len);
1531 }
1532
1533 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1534                           struct btrfs_device *device,
1535                           u64 start, u64 *dev_extent_len)
1536 {
1537         struct btrfs_fs_info *fs_info = device->fs_info;
1538         struct btrfs_root *root = fs_info->dev_root;
1539         int ret;
1540         struct btrfs_path *path;
1541         struct btrfs_key key;
1542         struct btrfs_key found_key;
1543         struct extent_buffer *leaf = NULL;
1544         struct btrfs_dev_extent *extent = NULL;
1545
1546         path = btrfs_alloc_path();
1547         if (!path)
1548                 return -ENOMEM;
1549
1550         key.objectid = device->devid;
1551         key.offset = start;
1552         key.type = BTRFS_DEV_EXTENT_KEY;
1553 again:
1554         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1555         if (ret > 0) {
1556                 ret = btrfs_previous_item(root, path, key.objectid,
1557                                           BTRFS_DEV_EXTENT_KEY);
1558                 if (ret)
1559                         goto out;
1560                 leaf = path->nodes[0];
1561                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1562                 extent = btrfs_item_ptr(leaf, path->slots[0],
1563                                         struct btrfs_dev_extent);
1564                 BUG_ON(found_key.offset > start || found_key.offset +
1565                        btrfs_dev_extent_length(leaf, extent) < start);
1566                 key = found_key;
1567                 btrfs_release_path(path);
1568                 goto again;
1569         } else if (ret == 0) {
1570                 leaf = path->nodes[0];
1571                 extent = btrfs_item_ptr(leaf, path->slots[0],
1572                                         struct btrfs_dev_extent);
1573         } else {
1574                 btrfs_handle_fs_error(fs_info, ret, "Slot search failed");
1575                 goto out;
1576         }
1577
1578         *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1579
1580         ret = btrfs_del_item(trans, root, path);
1581         if (ret) {
1582                 btrfs_handle_fs_error(fs_info, ret,
1583                                       "Failed to remove dev extent item");
1584         } else {
1585                 set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags);
1586         }
1587 out:
1588         btrfs_free_path(path);
1589         return ret;
1590 }
1591
1592 static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1593                                   struct btrfs_device *device,
1594                                   u64 chunk_offset, u64 start, u64 num_bytes)
1595 {
1596         int ret;
1597         struct btrfs_path *path;
1598         struct btrfs_fs_info *fs_info = device->fs_info;
1599         struct btrfs_root *root = fs_info->dev_root;
1600         struct btrfs_dev_extent *extent;
1601         struct extent_buffer *leaf;
1602         struct btrfs_key key;
1603
1604         WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state));
1605         WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
1606         path = btrfs_alloc_path();
1607         if (!path)
1608                 return -ENOMEM;
1609
1610         key.objectid = device->devid;
1611         key.offset = start;
1612         key.type = BTRFS_DEV_EXTENT_KEY;
1613         ret = btrfs_insert_empty_item(trans, root, path, &key,
1614                                       sizeof(*extent));
1615         if (ret)
1616                 goto out;
1617
1618         leaf = path->nodes[0];
1619         extent = btrfs_item_ptr(leaf, path->slots[0],
1620                                 struct btrfs_dev_extent);
1621         btrfs_set_dev_extent_chunk_tree(leaf, extent,
1622                                         BTRFS_CHUNK_TREE_OBJECTID);
1623         btrfs_set_dev_extent_chunk_objectid(leaf, extent,
1624                                             BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1625         btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1626
1627         btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1628         btrfs_mark_buffer_dirty(leaf);
1629 out:
1630         btrfs_free_path(path);
1631         return ret;
1632 }
1633
1634 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1635 {
1636         struct extent_map_tree *em_tree;
1637         struct extent_map *em;
1638         struct rb_node *n;
1639         u64 ret = 0;
1640
1641         em_tree = &fs_info->mapping_tree.map_tree;
1642         read_lock(&em_tree->lock);
1643         n = rb_last(&em_tree->map);
1644         if (n) {
1645                 em = rb_entry(n, struct extent_map, rb_node);
1646                 ret = em->start + em->len;
1647         }
1648         read_unlock(&em_tree->lock);
1649
1650         return ret;
1651 }
1652
1653 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1654                                     u64 *devid_ret)
1655 {
1656         int ret;
1657         struct btrfs_key key;
1658         struct btrfs_key found_key;
1659         struct btrfs_path *path;
1660
1661         path = btrfs_alloc_path();
1662         if (!path)
1663                 return -ENOMEM;
1664
1665         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1666         key.type = BTRFS_DEV_ITEM_KEY;
1667         key.offset = (u64)-1;
1668
1669         ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1670         if (ret < 0)
1671                 goto error;
1672
1673         BUG_ON(ret == 0); /* Corruption */
1674
1675         ret = btrfs_previous_item(fs_info->chunk_root, path,
1676                                   BTRFS_DEV_ITEMS_OBJECTID,
1677                                   BTRFS_DEV_ITEM_KEY);
1678         if (ret) {
1679                 *devid_ret = 1;
1680         } else {
1681                 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1682                                       path->slots[0]);
1683                 *devid_ret = found_key.offset + 1;
1684         }
1685         ret = 0;
1686 error:
1687         btrfs_free_path(path);
1688         return ret;
1689 }
1690
1691 /*
1692  * the device information is stored in the chunk root
1693  * the btrfs_device struct should be fully filled in
1694  */
1695 static int btrfs_add_dev_item(struct btrfs_trans_handle *trans,
1696                             struct btrfs_device *device)
1697 {
1698         int ret;
1699         struct btrfs_path *path;
1700         struct btrfs_dev_item *dev_item;
1701         struct extent_buffer *leaf;
1702         struct btrfs_key key;
1703         unsigned long ptr;
1704
1705         path = btrfs_alloc_path();
1706         if (!path)
1707                 return -ENOMEM;
1708
1709         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1710         key.type = BTRFS_DEV_ITEM_KEY;
1711         key.offset = device->devid;
1712
1713         ret = btrfs_insert_empty_item(trans, trans->fs_info->chunk_root, path,
1714                                       &key, sizeof(*dev_item));
1715         if (ret)
1716                 goto out;
1717
1718         leaf = path->nodes[0];
1719         dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1720
1721         btrfs_set_device_id(leaf, dev_item, device->devid);
1722         btrfs_set_device_generation(leaf, dev_item, 0);
1723         btrfs_set_device_type(leaf, dev_item, device->type);
1724         btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1725         btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1726         btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1727         btrfs_set_device_total_bytes(leaf, dev_item,
1728                                      btrfs_device_get_disk_total_bytes(device));
1729         btrfs_set_device_bytes_used(leaf, dev_item,
1730                                     btrfs_device_get_bytes_used(device));
1731         btrfs_set_device_group(leaf, dev_item, 0);
1732         btrfs_set_device_seek_speed(leaf, dev_item, 0);
1733         btrfs_set_device_bandwidth(leaf, dev_item, 0);
1734         btrfs_set_device_start_offset(leaf, dev_item, 0);
1735
1736         ptr = btrfs_device_uuid(dev_item);
1737         write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1738         ptr = btrfs_device_fsid(dev_item);
1739         write_extent_buffer(leaf, trans->fs_info->fsid, ptr, BTRFS_FSID_SIZE);
1740         btrfs_mark_buffer_dirty(leaf);
1741
1742         ret = 0;
1743 out:
1744         btrfs_free_path(path);
1745         return ret;
1746 }
1747
1748 /*
1749  * Function to update ctime/mtime for a given device path.
1750  * Mainly used for ctime/mtime based probe like libblkid.
1751  */
1752 static void update_dev_time(const char *path_name)
1753 {
1754         struct file *filp;
1755
1756         filp = filp_open(path_name, O_RDWR, 0);
1757         if (IS_ERR(filp))
1758                 return;
1759         file_update_time(filp);
1760         filp_close(filp, NULL);
1761 }
1762
1763 static int btrfs_rm_dev_item(struct btrfs_fs_info *fs_info,
1764                              struct btrfs_device *device)
1765 {
1766         struct btrfs_root *root = fs_info->chunk_root;
1767         int ret;
1768         struct btrfs_path *path;
1769         struct btrfs_key key;
1770         struct btrfs_trans_handle *trans;
1771
1772         path = btrfs_alloc_path();
1773         if (!path)
1774                 return -ENOMEM;
1775
1776         trans = btrfs_start_transaction(root, 0);
1777         if (IS_ERR(trans)) {
1778                 btrfs_free_path(path);
1779                 return PTR_ERR(trans);
1780         }
1781         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1782         key.type = BTRFS_DEV_ITEM_KEY;
1783         key.offset = device->devid;
1784
1785         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1786         if (ret) {
1787                 if (ret > 0)
1788                         ret = -ENOENT;
1789                 btrfs_abort_transaction(trans, ret);
1790                 btrfs_end_transaction(trans);
1791                 goto out;
1792         }
1793
1794         ret = btrfs_del_item(trans, root, path);
1795         if (ret) {
1796                 btrfs_abort_transaction(trans, ret);
1797                 btrfs_end_transaction(trans);
1798         }
1799
1800 out:
1801         btrfs_free_path(path);
1802         if (!ret)
1803                 ret = btrfs_commit_transaction(trans);
1804         return ret;
1805 }
1806
1807 /*
1808  * Verify that @num_devices satisfies the RAID profile constraints in the whole
1809  * filesystem. It's up to the caller to adjust that number regarding eg. device
1810  * replace.
1811  */
1812 static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info,
1813                 u64 num_devices)
1814 {
1815         u64 all_avail;
1816         unsigned seq;
1817         int i;
1818
1819         do {
1820                 seq = read_seqbegin(&fs_info->profiles_lock);
1821
1822                 all_avail = fs_info->avail_data_alloc_bits |
1823                             fs_info->avail_system_alloc_bits |
1824                             fs_info->avail_metadata_alloc_bits;
1825         } while (read_seqretry(&fs_info->profiles_lock, seq));
1826
1827         for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
1828                 if (!(all_avail & btrfs_raid_array[i].bg_flag))
1829                         continue;
1830
1831                 if (num_devices < btrfs_raid_array[i].devs_min) {
1832                         int ret = btrfs_raid_array[i].mindev_error;
1833
1834                         if (ret)
1835                                 return ret;
1836                 }
1837         }
1838
1839         return 0;
1840 }
1841
1842 static struct btrfs_device * btrfs_find_next_active_device(
1843                 struct btrfs_fs_devices *fs_devs, struct btrfs_device *device)
1844 {
1845         struct btrfs_device *next_device;
1846
1847         list_for_each_entry(next_device, &fs_devs->devices, dev_list) {
1848                 if (next_device != device &&
1849                     !test_bit(BTRFS_DEV_STATE_MISSING, &next_device->dev_state)
1850                     && next_device->bdev)
1851                         return next_device;
1852         }
1853
1854         return NULL;
1855 }
1856
1857 /*
1858  * Helper function to check if the given device is part of s_bdev / latest_bdev
1859  * and replace it with the provided or the next active device, in the context
1860  * where this function called, there should be always be another device (or
1861  * this_dev) which is active.
1862  */
1863 void btrfs_assign_next_active_device(struct btrfs_device *device,
1864                                      struct btrfs_device *this_dev)
1865 {
1866         struct btrfs_fs_info *fs_info = device->fs_info;
1867         struct btrfs_device *next_device;
1868
1869         if (this_dev)
1870                 next_device = this_dev;
1871         else
1872                 next_device = btrfs_find_next_active_device(fs_info->fs_devices,
1873                                                                 device);
1874         ASSERT(next_device);
1875
1876         if (fs_info->sb->s_bdev &&
1877                         (fs_info->sb->s_bdev == device->bdev))
1878                 fs_info->sb->s_bdev = next_device->bdev;
1879
1880         if (fs_info->fs_devices->latest_bdev == device->bdev)
1881                 fs_info->fs_devices->latest_bdev = next_device->bdev;
1882 }
1883
1884 int btrfs_rm_device(struct btrfs_fs_info *fs_info, const char *device_path,
1885                 u64 devid)
1886 {
1887         struct btrfs_device *device;
1888         struct btrfs_fs_devices *cur_devices;
1889         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
1890         u64 num_devices;
1891         int ret = 0;
1892
1893         mutex_lock(&uuid_mutex);
1894
1895         num_devices = fs_devices->num_devices;
1896         btrfs_dev_replace_read_lock(&fs_info->dev_replace);
1897         if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
1898                 WARN_ON(num_devices < 1);
1899                 num_devices--;
1900         }
1901         btrfs_dev_replace_read_unlock(&fs_info->dev_replace);
1902
1903         ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
1904         if (ret)
1905                 goto out;
1906
1907         ret = btrfs_find_device_by_devspec(fs_info, devid, device_path,
1908                                            &device);
1909         if (ret)
1910                 goto out;
1911
1912         if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1913                 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
1914                 goto out;
1915         }
1916
1917         if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1918             fs_info->fs_devices->rw_devices == 1) {
1919                 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
1920                 goto out;
1921         }
1922
1923         if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1924                 mutex_lock(&fs_info->chunk_mutex);
1925                 list_del_init(&device->dev_alloc_list);
1926                 device->fs_devices->rw_devices--;
1927                 mutex_unlock(&fs_info->chunk_mutex);
1928         }
1929
1930         mutex_unlock(&uuid_mutex);
1931         ret = btrfs_shrink_device(device, 0);
1932         mutex_lock(&uuid_mutex);
1933         if (ret)
1934                 goto error_undo;
1935
1936         /*
1937          * TODO: the superblock still includes this device in its num_devices
1938          * counter although write_all_supers() is not locked out. This
1939          * could give a filesystem state which requires a degraded mount.
1940          */
1941         ret = btrfs_rm_dev_item(fs_info, device);
1942         if (ret)
1943                 goto error_undo;
1944
1945         clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
1946         btrfs_scrub_cancel_dev(fs_info, device);
1947
1948         /*
1949          * the device list mutex makes sure that we don't change
1950          * the device list while someone else is writing out all
1951          * the device supers. Whoever is writing all supers, should
1952          * lock the device list mutex before getting the number of
1953          * devices in the super block (super_copy). Conversely,
1954          * whoever updates the number of devices in the super block
1955          * (super_copy) should hold the device list mutex.
1956          */
1957
1958         /*
1959          * In normal cases the cur_devices == fs_devices. But in case
1960          * of deleting a seed device, the cur_devices should point to
1961          * its own fs_devices listed under the fs_devices->seed.
1962          */
1963         cur_devices = device->fs_devices;
1964         mutex_lock(&fs_devices->device_list_mutex);
1965         list_del_rcu(&device->dev_list);
1966
1967         cur_devices->num_devices--;
1968         cur_devices->total_devices--;
1969         /* Update total_devices of the parent fs_devices if it's seed */
1970         if (cur_devices != fs_devices)
1971                 fs_devices->total_devices--;
1972
1973         if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
1974                 cur_devices->missing_devices--;
1975
1976         btrfs_assign_next_active_device(device, NULL);
1977
1978         if (device->bdev) {
1979                 cur_devices->open_devices--;
1980                 /* remove sysfs entry */
1981                 btrfs_sysfs_rm_device_link(fs_devices, device);
1982         }
1983
1984         num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
1985         btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
1986         mutex_unlock(&fs_devices->device_list_mutex);
1987
1988         /*
1989          * at this point, the device is zero sized and detached from
1990          * the devices list.  All that's left is to zero out the old
1991          * supers and free the device.
1992          */
1993         if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
1994                 btrfs_scratch_superblocks(device->bdev, device->name->str);
1995
1996         btrfs_close_bdev(device);
1997         call_rcu(&device->rcu, free_device_rcu);
1998
1999         if (cur_devices->open_devices == 0) {
2000                 while (fs_devices) {
2001                         if (fs_devices->seed == cur_devices) {
2002                                 fs_devices->seed = cur_devices->seed;
2003                                 break;
2004                         }
2005                         fs_devices = fs_devices->seed;
2006                 }
2007                 cur_devices->seed = NULL;
2008                 close_fs_devices(cur_devices);
2009                 free_fs_devices(cur_devices);
2010         }
2011
2012 out:
2013         mutex_unlock(&uuid_mutex);
2014         return ret;
2015
2016 error_undo:
2017         if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2018                 mutex_lock(&fs_info->chunk_mutex);
2019                 list_add(&device->dev_alloc_list,
2020                          &fs_devices->alloc_list);
2021                 device->fs_devices->rw_devices++;
2022                 mutex_unlock(&fs_info->chunk_mutex);
2023         }
2024         goto out;
2025 }
2026
2027 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_device *srcdev)
2028 {
2029         struct btrfs_fs_devices *fs_devices;
2030
2031         lockdep_assert_held(&srcdev->fs_info->fs_devices->device_list_mutex);
2032
2033         /*
2034          * in case of fs with no seed, srcdev->fs_devices will point
2035          * to fs_devices of fs_info. However when the dev being replaced is
2036          * a seed dev it will point to the seed's local fs_devices. In short
2037          * srcdev will have its correct fs_devices in both the cases.
2038          */
2039         fs_devices = srcdev->fs_devices;
2040
2041         list_del_rcu(&srcdev->dev_list);
2042         list_del(&srcdev->dev_alloc_list);
2043         fs_devices->num_devices--;
2044         if (test_bit(BTRFS_DEV_STATE_MISSING, &srcdev->dev_state))
2045                 fs_devices->missing_devices--;
2046
2047         if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state))
2048                 fs_devices->rw_devices--;
2049
2050         if (srcdev->bdev)
2051                 fs_devices->open_devices--;
2052 }
2053
2054 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_fs_info *fs_info,
2055                                       struct btrfs_device *srcdev)
2056 {
2057         struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
2058
2059         if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state)) {
2060                 /* zero out the old super if it is writable */
2061                 btrfs_scratch_superblocks(srcdev->bdev, srcdev->name->str);
2062         }
2063
2064         btrfs_close_bdev(srcdev);
2065         call_rcu(&srcdev->rcu, free_device_rcu);
2066
2067         /* if this is no devs we rather delete the fs_devices */
2068         if (!fs_devices->num_devices) {
2069                 struct btrfs_fs_devices *tmp_fs_devices;
2070
2071                 /*
2072                  * On a mounted FS, num_devices can't be zero unless it's a
2073                  * seed. In case of a seed device being replaced, the replace
2074                  * target added to the sprout FS, so there will be no more
2075                  * device left under the seed FS.
2076                  */
2077                 ASSERT(fs_devices->seeding);
2078
2079                 tmp_fs_devices = fs_info->fs_devices;
2080                 while (tmp_fs_devices) {
2081                         if (tmp_fs_devices->seed == fs_devices) {
2082                                 tmp_fs_devices->seed = fs_devices->seed;
2083                                 break;
2084                         }
2085                         tmp_fs_devices = tmp_fs_devices->seed;
2086                 }
2087                 fs_devices->seed = NULL;
2088                 close_fs_devices(fs_devices);
2089                 free_fs_devices(fs_devices);
2090         }
2091 }
2092
2093 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_device *tgtdev)
2094 {
2095         struct btrfs_fs_devices *fs_devices = tgtdev->fs_info->fs_devices;
2096
2097         WARN_ON(!tgtdev);
2098         mutex_lock(&fs_devices->device_list_mutex);
2099
2100         btrfs_sysfs_rm_device_link(fs_devices, tgtdev);
2101
2102         if (tgtdev->bdev)
2103                 fs_devices->open_devices--;
2104
2105         fs_devices->num_devices--;
2106
2107         btrfs_assign_next_active_device(tgtdev, NULL);
2108
2109         list_del_rcu(&tgtdev->dev_list);
2110
2111         mutex_unlock(&fs_devices->device_list_mutex);
2112
2113         /*
2114          * The update_dev_time() with in btrfs_scratch_superblocks()
2115          * may lead to a call to btrfs_show_devname() which will try
2116          * to hold device_list_mutex. And here this device
2117          * is already out of device list, so we don't have to hold
2118          * the device_list_mutex lock.
2119          */
2120         btrfs_scratch_superblocks(tgtdev->bdev, tgtdev->name->str);
2121
2122         btrfs_close_bdev(tgtdev);
2123         call_rcu(&tgtdev->rcu, free_device_rcu);
2124 }
2125
2126 static int btrfs_find_device_by_path(struct btrfs_fs_info *fs_info,
2127                                      const char *device_path,
2128                                      struct btrfs_device **device)
2129 {
2130         int ret = 0;
2131         struct btrfs_super_block *disk_super;
2132         u64 devid;
2133         u8 *dev_uuid;
2134         struct block_device *bdev;
2135         struct buffer_head *bh;
2136
2137         *device = NULL;
2138         ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
2139                                     fs_info->bdev_holder, 0, &bdev, &bh);
2140         if (ret)
2141                 return ret;
2142         disk_super = (struct btrfs_super_block *)bh->b_data;
2143         devid = btrfs_stack_device_id(&disk_super->dev_item);
2144         dev_uuid = disk_super->dev_item.uuid;
2145         *device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
2146                                     disk_super->fsid, true);
2147         brelse(bh);
2148         if (!*device)
2149                 ret = -ENOENT;
2150         blkdev_put(bdev, FMODE_READ);
2151         return ret;
2152 }
2153
2154 int btrfs_find_device_missing_or_by_path(struct btrfs_fs_info *fs_info,
2155                                          const char *device_path,
2156                                          struct btrfs_device **device)
2157 {
2158         *device = NULL;
2159         if (strcmp(device_path, "missing") == 0) {
2160                 struct list_head *devices;
2161                 struct btrfs_device *tmp;
2162
2163                 devices = &fs_info->fs_devices->devices;
2164                 list_for_each_entry(tmp, devices, dev_list) {
2165                         if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
2166                                         &tmp->dev_state) && !tmp->bdev) {
2167                                 *device = tmp;
2168                                 break;
2169                         }
2170                 }
2171
2172                 if (!*device)
2173                         return BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
2174
2175                 return 0;
2176         } else {
2177                 return btrfs_find_device_by_path(fs_info, device_path, device);
2178         }
2179 }
2180
2181 /*
2182  * Lookup a device given by device id, or the path if the id is 0.
2183  */
2184 int btrfs_find_device_by_devspec(struct btrfs_fs_info *fs_info, u64 devid,
2185                                  const char *devpath,
2186                                  struct btrfs_device **device)
2187 {
2188         int ret;
2189
2190         if (devid) {
2191                 ret = 0;
2192                 *device = btrfs_find_device(fs_info->fs_devices, devid,
2193                                             NULL, NULL, true);
2194                 if (!*device)
2195                         ret = -ENOENT;
2196         } else {
2197                 if (!devpath || !devpath[0])
2198                         return -EINVAL;
2199
2200                 ret = btrfs_find_device_missing_or_by_path(fs_info, devpath,
2201                                                            device);
2202         }
2203         return ret;
2204 }
2205
2206 /*
2207  * does all the dirty work required for changing file system's UUID.
2208  */
2209 static int btrfs_prepare_sprout(struct btrfs_fs_info *fs_info)
2210 {
2211         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2212         struct btrfs_fs_devices *old_devices;
2213         struct btrfs_fs_devices *seed_devices;
2214         struct btrfs_super_block *disk_super = fs_info->super_copy;
2215         struct btrfs_device *device;
2216         u64 super_flags;
2217
2218         lockdep_assert_held(&uuid_mutex);
2219         if (!fs_devices->seeding)
2220                 return -EINVAL;
2221
2222         seed_devices = alloc_fs_devices(NULL);
2223         if (IS_ERR(seed_devices))
2224                 return PTR_ERR(seed_devices);
2225
2226         old_devices = clone_fs_devices(fs_devices);
2227         if (IS_ERR(old_devices)) {
2228                 kfree(seed_devices);
2229                 return PTR_ERR(old_devices);
2230         }
2231
2232         list_add(&old_devices->fs_list, &fs_uuids);
2233
2234         memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2235         seed_devices->opened = 1;
2236         INIT_LIST_HEAD(&seed_devices->devices);
2237         INIT_LIST_HEAD(&seed_devices->alloc_list);
2238         mutex_init(&seed_devices->device_list_mutex);
2239
2240         mutex_lock(&fs_devices->device_list_mutex);
2241         list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2242                               synchronize_rcu);
2243         list_for_each_entry(device, &seed_devices->devices, dev_list)
2244                 device->fs_devices = seed_devices;
2245
2246         mutex_lock(&fs_info->chunk_mutex);
2247         list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
2248         mutex_unlock(&fs_info->chunk_mutex);
2249
2250         fs_devices->seeding = 0;
2251         fs_devices->num_devices = 0;
2252         fs_devices->open_devices = 0;
2253         fs_devices->missing_devices = 0;
2254         fs_devices->rotating = 0;
2255         fs_devices->seed = seed_devices;
2256
2257         generate_random_uuid(fs_devices->fsid);
2258         memcpy(fs_info->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2259         memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2260         mutex_unlock(&fs_devices->device_list_mutex);
2261
2262         super_flags = btrfs_super_flags(disk_super) &
2263                       ~BTRFS_SUPER_FLAG_SEEDING;
2264         btrfs_set_super_flags(disk_super, super_flags);
2265
2266         return 0;
2267 }
2268
2269 /*
2270  * Store the expected generation for seed devices in device items.
2271  */
2272 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
2273                                struct btrfs_fs_info *fs_info)
2274 {
2275         struct btrfs_root *root = fs_info->chunk_root;
2276         struct btrfs_path *path;
2277         struct extent_buffer *leaf;
2278         struct btrfs_dev_item *dev_item;
2279         struct btrfs_device *device;
2280         struct btrfs_key key;
2281         u8 fs_uuid[BTRFS_FSID_SIZE];
2282         u8 dev_uuid[BTRFS_UUID_SIZE];
2283         u64 devid;
2284         int ret;
2285
2286         path = btrfs_alloc_path();
2287         if (!path)
2288                 return -ENOMEM;
2289
2290         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2291         key.offset = 0;
2292         key.type = BTRFS_DEV_ITEM_KEY;
2293
2294         while (1) {
2295                 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2296                 if (ret < 0)
2297                         goto error;
2298
2299                 leaf = path->nodes[0];
2300 next_slot:
2301                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2302                         ret = btrfs_next_leaf(root, path);
2303                         if (ret > 0)
2304                                 break;
2305                         if (ret < 0)
2306                                 goto error;
2307                         leaf = path->nodes[0];
2308                         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2309                         btrfs_release_path(path);
2310                         continue;
2311                 }
2312
2313                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2314                 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2315                     key.type != BTRFS_DEV_ITEM_KEY)
2316                         break;
2317
2318                 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2319                                           struct btrfs_dev_item);
2320                 devid = btrfs_device_id(leaf, dev_item);
2321                 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2322                                    BTRFS_UUID_SIZE);
2323                 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2324                                    BTRFS_FSID_SIZE);
2325                 device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
2326                                            fs_uuid, true);
2327                 BUG_ON(!device); /* Logic error */
2328
2329                 if (device->fs_devices->seeding) {
2330                         btrfs_set_device_generation(leaf, dev_item,
2331                                                     device->generation);
2332                         btrfs_mark_buffer_dirty(leaf);
2333                 }
2334
2335                 path->slots[0]++;
2336                 goto next_slot;
2337         }
2338         ret = 0;
2339 error:
2340         btrfs_free_path(path);
2341         return ret;
2342 }
2343
2344 int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path)
2345 {
2346         struct btrfs_root *root = fs_info->dev_root;
2347         struct request_queue *q;
2348         struct btrfs_trans_handle *trans;
2349         struct btrfs_device *device;
2350         struct block_device *bdev;
2351         struct super_block *sb = fs_info->sb;
2352         struct rcu_string *name;
2353         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2354         u64 orig_super_total_bytes;
2355         u64 orig_super_num_devices;
2356         int seeding_dev = 0;
2357         int ret = 0;
2358         bool unlocked = false;
2359
2360         if (sb_rdonly(sb) && !fs_devices->seeding)
2361                 return -EROFS;
2362
2363         bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2364                                   fs_info->bdev_holder);
2365         if (IS_ERR(bdev))
2366                 return PTR_ERR(bdev);
2367
2368         if (fs_devices->seeding) {
2369                 seeding_dev = 1;
2370                 down_write(&sb->s_umount);
2371                 mutex_lock(&uuid_mutex);
2372         }
2373
2374         filemap_write_and_wait(bdev->bd_inode->i_mapping);
2375
2376         mutex_lock(&fs_devices->device_list_mutex);
2377         list_for_each_entry(device, &fs_devices->devices, dev_list) {
2378                 if (device->bdev == bdev) {
2379                         ret = -EEXIST;
2380                         mutex_unlock(
2381                                 &fs_devices->device_list_mutex);
2382                         goto error;
2383                 }
2384         }
2385         mutex_unlock(&fs_devices->device_list_mutex);
2386
2387         device = btrfs_alloc_device(fs_info, NULL, NULL);
2388         if (IS_ERR(device)) {
2389                 /* we can safely leave the fs_devices entry around */
2390                 ret = PTR_ERR(device);
2391                 goto error;
2392         }
2393
2394         name = rcu_string_strdup(device_path, GFP_KERNEL);
2395         if (!name) {
2396                 ret = -ENOMEM;
2397                 goto error_free_device;
2398         }
2399         rcu_assign_pointer(device->name, name);
2400
2401         trans = btrfs_start_transaction(root, 0);
2402         if (IS_ERR(trans)) {
2403                 ret = PTR_ERR(trans);
2404                 goto error_free_device;
2405         }
2406
2407         q = bdev_get_queue(bdev);
2408         set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2409         device->generation = trans->transid;
2410         device->io_width = fs_info->sectorsize;
2411         device->io_align = fs_info->sectorsize;
2412         device->sector_size = fs_info->sectorsize;
2413         device->total_bytes = round_down(i_size_read(bdev->bd_inode),
2414                                          fs_info->sectorsize);
2415         device->disk_total_bytes = device->total_bytes;
2416         device->commit_total_bytes = device->total_bytes;
2417         device->fs_info = fs_info;
2418         device->bdev = bdev;
2419         set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2420         clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
2421         device->mode = FMODE_EXCL;
2422         device->dev_stats_valid = 1;
2423         set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2424
2425         if (seeding_dev) {
2426                 sb->s_flags &= ~SB_RDONLY;
2427                 ret = btrfs_prepare_sprout(fs_info);
2428                 if (ret) {
2429                         btrfs_abort_transaction(trans, ret);
2430                         goto error_trans;
2431                 }
2432         }
2433
2434         device->fs_devices = fs_devices;
2435
2436         mutex_lock(&fs_devices->device_list_mutex);
2437         mutex_lock(&fs_info->chunk_mutex);
2438         list_add_rcu(&device->dev_list, &fs_devices->devices);
2439         list_add(&device->dev_alloc_list, &fs_devices->alloc_list);
2440         fs_devices->num_devices++;
2441         fs_devices->open_devices++;
2442         fs_devices->rw_devices++;
2443         fs_devices->total_devices++;
2444         fs_devices->total_rw_bytes += device->total_bytes;
2445
2446         atomic64_add(device->total_bytes, &fs_info->free_chunk_space);
2447
2448         if (!blk_queue_nonrot(q))
2449                 fs_devices->rotating = 1;
2450
2451         orig_super_total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
2452         btrfs_set_super_total_bytes(fs_info->super_copy,
2453                 round_down(orig_super_total_bytes + device->total_bytes,
2454                            fs_info->sectorsize));
2455
2456         orig_super_num_devices = btrfs_super_num_devices(fs_info->super_copy);
2457         btrfs_set_super_num_devices(fs_info->super_copy,
2458                                     orig_super_num_devices + 1);
2459
2460         /*
2461          * we've got more storage, clear any full flags on the space
2462          * infos
2463          */
2464         btrfs_clear_space_info_full(fs_info);
2465
2466         mutex_unlock(&fs_info->chunk_mutex);
2467
2468         /* Add sysfs device entry */
2469         btrfs_sysfs_add_device_link(fs_devices, device);
2470
2471         mutex_unlock(&fs_devices->device_list_mutex);
2472
2473         if (seeding_dev) {
2474                 mutex_lock(&fs_info->chunk_mutex);
2475                 ret = init_first_rw_device(trans, fs_info);
2476                 mutex_unlock(&fs_info->chunk_mutex);
2477                 if (ret) {
2478                         btrfs_abort_transaction(trans, ret);
2479                         goto error_sysfs;
2480                 }
2481         }
2482
2483         ret = btrfs_add_dev_item(trans, device);
2484         if (ret) {
2485                 btrfs_abort_transaction(trans, ret);
2486                 goto error_sysfs;
2487         }
2488
2489         if (seeding_dev) {
2490                 char fsid_buf[BTRFS_UUID_UNPARSED_SIZE];
2491
2492                 ret = btrfs_finish_sprout(trans, fs_info);
2493                 if (ret) {
2494                         btrfs_abort_transaction(trans, ret);
2495                         goto error_sysfs;
2496                 }
2497
2498                 /* Sprouting would change fsid of the mounted root,
2499                  * so rename the fsid on the sysfs
2500                  */
2501                 snprintf(fsid_buf, BTRFS_UUID_UNPARSED_SIZE, "%pU",
2502                                                 fs_info->fsid);
2503                 if (kobject_rename(&fs_devices->fsid_kobj, fsid_buf))
2504                         btrfs_warn(fs_info,
2505                                    "sysfs: failed to create fsid for sprout");
2506         }
2507
2508         ret = btrfs_commit_transaction(trans);
2509
2510         if (seeding_dev) {
2511                 mutex_unlock(&uuid_mutex);
2512                 up_write(&sb->s_umount);
2513                 unlocked = true;
2514
2515                 if (ret) /* transaction commit */
2516                         return ret;
2517
2518                 ret = btrfs_relocate_sys_chunks(fs_info);
2519                 if (ret < 0)
2520                         btrfs_handle_fs_error(fs_info, ret,
2521                                     "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
2522                 trans = btrfs_attach_transaction(root);
2523                 if (IS_ERR(trans)) {
2524                         if (PTR_ERR(trans) == -ENOENT)
2525                                 return 0;
2526                         ret = PTR_ERR(trans);
2527                         trans = NULL;
2528                         goto error_sysfs;
2529                 }
2530                 ret = btrfs_commit_transaction(trans);
2531         }
2532
2533         /* Update ctime/mtime for libblkid */
2534         update_dev_time(device_path);
2535         return ret;
2536
2537 error_sysfs:
2538         btrfs_sysfs_rm_device_link(fs_devices, device);
2539         mutex_lock(&fs_info->fs_devices->device_list_mutex);
2540         mutex_lock(&fs_info->chunk_mutex);
2541         list_del_rcu(&device->dev_list);
2542         list_del(&device->dev_alloc_list);
2543         fs_info->fs_devices->num_devices--;
2544         fs_info->fs_devices->open_devices--;
2545         fs_info->fs_devices->rw_devices--;
2546         fs_info->fs_devices->total_devices--;
2547         fs_info->fs_devices->total_rw_bytes -= device->total_bytes;
2548         atomic64_sub(device->total_bytes, &fs_info->free_chunk_space);
2549         btrfs_set_super_total_bytes(fs_info->super_copy,
2550                                     orig_super_total_bytes);
2551         btrfs_set_super_num_devices(fs_info->super_copy,
2552                                     orig_super_num_devices);
2553         mutex_unlock(&fs_info->chunk_mutex);
2554         mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2555 error_trans:
2556         if (seeding_dev)
2557                 sb->s_flags |= SB_RDONLY;
2558         if (trans)
2559                 btrfs_end_transaction(trans);
2560 error_free_device:
2561         btrfs_free_device(device);
2562 error:
2563         blkdev_put(bdev, FMODE_EXCL);
2564         if (seeding_dev && !unlocked) {
2565                 mutex_unlock(&uuid_mutex);
2566                 up_write(&sb->s_umount);
2567         }
2568         return ret;
2569 }
2570
2571 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2572                                         struct btrfs_device *device)
2573 {
2574         int ret;
2575         struct btrfs_path *path;
2576         struct btrfs_root *root = device->fs_info->chunk_root;
2577         struct btrfs_dev_item *dev_item;
2578         struct extent_buffer *leaf;
2579         struct btrfs_key key;
2580
2581         path = btrfs_alloc_path();
2582         if (!path)
2583                 return -ENOMEM;
2584
2585         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2586         key.type = BTRFS_DEV_ITEM_KEY;
2587         key.offset = device->devid;
2588
2589         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2590         if (ret < 0)
2591                 goto out;
2592
2593         if (ret > 0) {
2594                 ret = -ENOENT;
2595                 goto out;
2596         }
2597
2598         leaf = path->nodes[0];
2599         dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2600
2601         btrfs_set_device_id(leaf, dev_item, device->devid);
2602         btrfs_set_device_type(leaf, dev_item, device->type);
2603         btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2604         btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2605         btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2606         btrfs_set_device_total_bytes(leaf, dev_item,
2607                                      btrfs_device_get_disk_total_bytes(device));
2608         btrfs_set_device_bytes_used(leaf, dev_item,
2609                                     btrfs_device_get_bytes_used(device));
2610         btrfs_mark_buffer_dirty(leaf);
2611
2612 out:
2613         btrfs_free_path(path);
2614         return ret;
2615 }
2616
2617 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2618                       struct btrfs_device *device, u64 new_size)
2619 {
2620         struct btrfs_fs_info *fs_info = device->fs_info;
2621         struct btrfs_super_block *super_copy = fs_info->super_copy;
2622         struct btrfs_fs_devices *fs_devices;
2623         u64 old_total;
2624         u64 diff;
2625
2626         if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2627                 return -EACCES;
2628
2629         new_size = round_down(new_size, fs_info->sectorsize);
2630
2631         mutex_lock(&fs_info->chunk_mutex);
2632         old_total = btrfs_super_total_bytes(super_copy);
2633         diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
2634
2635         if (new_size <= device->total_bytes ||
2636             test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2637                 mutex_unlock(&fs_info->chunk_mutex);
2638                 return -EINVAL;
2639         }
2640
2641         fs_devices = fs_info->fs_devices;
2642
2643         btrfs_set_super_total_bytes(super_copy,
2644                         round_down(old_total + diff, fs_info->sectorsize));
2645         device->fs_devices->total_rw_bytes += diff;
2646
2647         btrfs_device_set_total_bytes(device, new_size);
2648         btrfs_device_set_disk_total_bytes(device, new_size);
2649         btrfs_clear_space_info_full(device->fs_info);
2650         if (list_empty(&device->resized_list))
2651                 list_add_tail(&device->resized_list,
2652                               &fs_devices->resized_devices);
2653         mutex_unlock(&fs_info->chunk_mutex);
2654
2655         return btrfs_update_device(trans, device);
2656 }
2657
2658 static int btrfs_free_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
2659 {
2660         struct btrfs_fs_info *fs_info = trans->fs_info;
2661         struct btrfs_root *root = fs_info->chunk_root;
2662         int ret;
2663         struct btrfs_path *path;
2664         struct btrfs_key key;
2665
2666         path = btrfs_alloc_path();
2667         if (!path)
2668                 return -ENOMEM;
2669
2670         key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2671         key.offset = chunk_offset;
2672         key.type = BTRFS_CHUNK_ITEM_KEY;
2673
2674         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2675         if (ret < 0)
2676                 goto out;
2677         else if (ret > 0) { /* Logic error or corruption */
2678                 btrfs_handle_fs_error(fs_info, -ENOENT,
2679                                       "Failed lookup while freeing chunk.");
2680                 ret = -ENOENT;
2681                 goto out;
2682         }
2683
2684         ret = btrfs_del_item(trans, root, path);
2685         if (ret < 0)
2686                 btrfs_handle_fs_error(fs_info, ret,
2687                                       "Failed to delete chunk item.");
2688 out:
2689         btrfs_free_path(path);
2690         return ret;
2691 }
2692
2693 static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2694 {
2695         struct btrfs_super_block *super_copy = fs_info->super_copy;
2696         struct btrfs_disk_key *disk_key;
2697         struct btrfs_chunk *chunk;
2698         u8 *ptr;
2699         int ret = 0;
2700         u32 num_stripes;
2701         u32 array_size;
2702         u32 len = 0;
2703         u32 cur;
2704         struct btrfs_key key;
2705
2706         mutex_lock(&fs_info->chunk_mutex);
2707         array_size = btrfs_super_sys_array_size(super_copy);
2708
2709         ptr = super_copy->sys_chunk_array;
2710         cur = 0;
2711
2712         while (cur < array_size) {
2713                 disk_key = (struct btrfs_disk_key *)ptr;
2714                 btrfs_disk_key_to_cpu(&key, disk_key);
2715
2716                 len = sizeof(*disk_key);
2717
2718                 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2719                         chunk = (struct btrfs_chunk *)(ptr + len);
2720                         num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2721                         len += btrfs_chunk_item_size(num_stripes);
2722                 } else {
2723                         ret = -EIO;
2724                         break;
2725                 }
2726                 if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
2727                     key.offset == chunk_offset) {
2728                         memmove(ptr, ptr + len, array_size - (cur + len));
2729                         array_size -= len;
2730                         btrfs_set_super_sys_array_size(super_copy, array_size);
2731                 } else {
2732                         ptr += len;
2733                         cur += len;
2734                 }
2735         }
2736         mutex_unlock(&fs_info->chunk_mutex);
2737         return ret;
2738 }
2739
2740 static struct extent_map *get_chunk_map(struct btrfs_fs_info *fs_info,
2741                                         u64 logical, u64 length)
2742 {
2743         struct extent_map_tree *em_tree;
2744         struct extent_map *em;
2745
2746         em_tree = &fs_info->mapping_tree.map_tree;
2747         read_lock(&em_tree->lock);
2748         em = lookup_extent_mapping(em_tree, logical, length);
2749         read_unlock(&em_tree->lock);
2750
2751         if (!em) {
2752                 btrfs_crit(fs_info, "unable to find logical %llu length %llu",
2753                            logical, length);
2754                 return ERR_PTR(-EINVAL);
2755         }
2756
2757         if (em->start > logical || em->start + em->len < logical) {
2758                 btrfs_crit(fs_info,
2759                            "found a bad mapping, wanted %llu-%llu, found %llu-%llu",
2760                            logical, length, em->start, em->start + em->len);
2761                 free_extent_map(em);
2762                 return ERR_PTR(-EINVAL);
2763         }
2764
2765         /* callers are responsible for dropping em's ref. */
2766         return em;
2767 }
2768
2769 int btrfs_remove_chunk(struct btrfs_trans_handle *trans, u64 chunk_offset)
2770 {
2771         struct btrfs_fs_info *fs_info = trans->fs_info;
2772         struct extent_map *em;
2773         struct map_lookup *map;
2774         u64 dev_extent_len = 0;
2775         int i, ret = 0;
2776         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2777
2778         em = get_chunk_map(fs_info, chunk_offset, 1);
2779         if (IS_ERR(em)) {
2780                 /*
2781                  * This is a logic error, but we don't want to just rely on the
2782                  * user having built with ASSERT enabled, so if ASSERT doesn't
2783                  * do anything we still error out.
2784                  */
2785                 ASSERT(0);
2786                 return PTR_ERR(em);
2787         }
2788         map = em->map_lookup;
2789         mutex_lock(&fs_info->chunk_mutex);
2790         check_system_chunk(trans, map->type);
2791         mutex_unlock(&fs_info->chunk_mutex);
2792
2793         /*
2794          * Take the device list mutex to prevent races with the final phase of
2795          * a device replace operation that replaces the device object associated
2796          * with map stripes (dev-replace.c:btrfs_dev_replace_finishing()).
2797          */
2798         mutex_lock(&fs_devices->device_list_mutex);
2799         for (i = 0; i < map->num_stripes; i++) {
2800                 struct btrfs_device *device = map->stripes[i].dev;
2801                 ret = btrfs_free_dev_extent(trans, device,
2802                                             map->stripes[i].physical,
2803                                             &dev_extent_len);
2804                 if (ret) {
2805                         mutex_unlock(&fs_devices->device_list_mutex);
2806                         btrfs_abort_transaction(trans, ret);
2807                         goto out;
2808                 }
2809
2810                 if (device->bytes_used > 0) {
2811                         mutex_lock(&fs_info->chunk_mutex);
2812                         btrfs_device_set_bytes_used(device,
2813                                         device->bytes_used - dev_extent_len);
2814                         atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
2815                         btrfs_clear_space_info_full(fs_info);
2816                         mutex_unlock(&fs_info->chunk_mutex);
2817                 }
2818
2819                 if (map->stripes[i].dev) {
2820                         ret = btrfs_update_device(trans, map->stripes[i].dev);
2821                         if (ret) {
2822                                 mutex_unlock(&fs_devices->device_list_mutex);
2823                                 btrfs_abort_transaction(trans, ret);
2824                                 goto out;
2825                         }
2826                 }
2827         }
2828         mutex_unlock(&fs_devices->device_list_mutex);
2829
2830         ret = btrfs_free_chunk(trans, chunk_offset);
2831         if (ret) {
2832                 btrfs_abort_transaction(trans, ret);
2833                 goto out;
2834         }
2835
2836         trace_btrfs_chunk_free(fs_info, map, chunk_offset, em->len);
2837
2838         if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
2839                 ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
2840                 if (ret) {
2841                         btrfs_abort_transaction(trans, ret);
2842                         goto out;
2843                 }
2844         }
2845
2846         ret = btrfs_remove_block_group(trans, chunk_offset, em);
2847         if (ret) {
2848                 btrfs_abort_transaction(trans, ret);
2849                 goto out;
2850         }
2851
2852 out:
2853         /* once for us */
2854         free_extent_map(em);
2855         return ret;
2856 }
2857
2858 static int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2859 {
2860         struct btrfs_root *root = fs_info->chunk_root;
2861         struct btrfs_trans_handle *trans;
2862         int ret;
2863
2864         /*
2865          * Prevent races with automatic removal of unused block groups.
2866          * After we relocate and before we remove the chunk with offset
2867          * chunk_offset, automatic removal of the block group can kick in,
2868          * resulting in a failure when calling btrfs_remove_chunk() below.
2869          *
2870          * Make sure to acquire this mutex before doing a tree search (dev
2871          * or chunk trees) to find chunks. Otherwise the cleaner kthread might
2872          * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
2873          * we release the path used to search the chunk/dev tree and before
2874          * the current task acquires this mutex and calls us.
2875          */
2876         lockdep_assert_held(&fs_info->delete_unused_bgs_mutex);
2877
2878         ret = btrfs_can_relocate(fs_info, chunk_offset);
2879         if (ret)
2880                 return -ENOSPC;
2881
2882         /* step one, relocate all the extents inside this chunk */
2883         btrfs_scrub_pause(fs_info);
2884         ret = btrfs_relocate_block_group(fs_info, chunk_offset);
2885         btrfs_scrub_continue(fs_info);
2886         if (ret)
2887                 return ret;
2888
2889         /*
2890          * We add the kobjects here (and after forcing data chunk creation)
2891          * since relocation is the only place we'll create chunks of a new
2892          * type at runtime.  The only place where we'll remove the last
2893          * chunk of a type is the call immediately below this one.  Even
2894          * so, we're protected against races with the cleaner thread since
2895          * we're covered by the delete_unused_bgs_mutex.
2896          */
2897         btrfs_add_raid_kobjects(fs_info);
2898
2899         trans = btrfs_start_trans_remove_block_group(root->fs_info,
2900                                                      chunk_offset);
2901         if (IS_ERR(trans)) {
2902                 ret = PTR_ERR(trans);
2903                 btrfs_handle_fs_error(root->fs_info, ret, NULL);
2904                 return ret;
2905         }
2906
2907         /*
2908          * step two, delete the device extents and the
2909          * chunk tree entries
2910          */
2911         ret = btrfs_remove_chunk(trans, chunk_offset);
2912         btrfs_end_transaction(trans);
2913         return ret;
2914 }
2915
2916 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
2917 {
2918         struct btrfs_root *chunk_root = fs_info->chunk_root;
2919         struct btrfs_path *path;
2920         struct extent_buffer *leaf;
2921         struct btrfs_chunk *chunk;
2922         struct btrfs_key key;
2923         struct btrfs_key found_key;
2924         u64 chunk_type;
2925         bool retried = false;
2926         int failed = 0;
2927         int ret;
2928
2929         path = btrfs_alloc_path();
2930         if (!path)
2931                 return -ENOMEM;
2932
2933 again:
2934         key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2935         key.offset = (u64)-1;
2936         key.type = BTRFS_CHUNK_ITEM_KEY;
2937
2938         while (1) {
2939                 mutex_lock(&fs_info->delete_unused_bgs_mutex);
2940                 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
2941                 if (ret < 0) {
2942                         mutex_unlock(&fs_info->delete_unused_bgs_mutex);
2943                         goto error;
2944                 }
2945                 BUG_ON(ret == 0); /* Corruption */
2946
2947                 ret = btrfs_previous_item(chunk_root, path, key.objectid,
2948                                           key.type);
2949                 if (ret)
2950                         mutex_unlock(&fs_info->delete_unused_bgs_mutex);
2951                 if (ret < 0)
2952                         goto error;
2953                 if (ret > 0)
2954                         break;
2955
2956                 leaf = path->nodes[0];
2957                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2958
2959                 chunk = btrfs_item_ptr(leaf, path->slots[0],
2960                                        struct btrfs_chunk);
2961                 chunk_type = btrfs_chunk_type(leaf, chunk);
2962                 btrfs_release_path(path);
2963
2964                 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
2965                         ret = btrfs_relocate_chunk(fs_info, found_key.offset);
2966                         if (ret == -ENOSPC)
2967                                 failed++;
2968                         else
2969                                 BUG_ON(ret);
2970                 }
2971                 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
2972
2973                 if (found_key.offset == 0)
2974                         break;
2975                 key.offset = found_key.offset - 1;
2976         }
2977         ret = 0;
2978         if (failed && !retried) {
2979                 failed = 0;
2980                 retried = true;
2981                 goto again;
2982         } else if (WARN_ON(failed && retried)) {
2983                 ret = -ENOSPC;
2984         }
2985 error:
2986         btrfs_free_path(path);
2987         return ret;
2988 }
2989
2990 /*
2991  * return 1 : allocate a data chunk successfully,
2992  * return <0: errors during allocating a data chunk,
2993  * return 0 : no need to allocate a data chunk.
2994  */
2995 static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info *fs_info,
2996                                       u64 chunk_offset)
2997 {
2998         struct btrfs_block_group_cache *cache;
2999         u64 bytes_used;
3000         u64 chunk_type;
3001
3002         cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3003         ASSERT(cache);
3004         chunk_type = cache->flags;
3005         btrfs_put_block_group(cache);
3006
3007         if (chunk_type & BTRFS_BLOCK_GROUP_DATA) {
3008                 spin_lock(&fs_info->data_sinfo->lock);
3009                 bytes_used = fs_info->data_sinfo->bytes_used;
3010                 spin_unlock(&fs_info->data_sinfo->lock);
3011
3012                 if (!bytes_used) {
3013                         struct btrfs_trans_handle *trans;
3014                         int ret;
3015
3016                         trans = btrfs_join_transaction(fs_info->tree_root);
3017                         if (IS_ERR(trans))
3018                                 return PTR_ERR(trans);
3019
3020                         ret = btrfs_force_chunk_alloc(trans,
3021                                                       BTRFS_BLOCK_GROUP_DATA);
3022                         btrfs_end_transaction(trans);
3023                         if (ret < 0)
3024                                 return ret;
3025
3026                         btrfs_add_raid_kobjects(fs_info);
3027
3028                         return 1;
3029                 }
3030         }
3031         return 0;
3032 }
3033
3034 static int insert_balance_item(struct btrfs_fs_info *fs_info,
3035                                struct btrfs_balance_control *bctl)
3036 {
3037         struct btrfs_root *root = fs_info->tree_root;
3038         struct btrfs_trans_handle *trans;
3039         struct btrfs_balance_item *item;
3040         struct btrfs_disk_balance_args disk_bargs;
3041         struct btrfs_path *path;
3042         struct extent_buffer *leaf;
3043         struct btrfs_key key;
3044         int ret, err;
3045
3046         path = btrfs_alloc_path();
3047         if (!path)
3048                 return -ENOMEM;
3049
3050         trans = btrfs_start_transaction(root, 0);
3051         if (IS_ERR(trans)) {
3052                 btrfs_free_path(path);
3053                 return PTR_ERR(trans);
3054         }
3055
3056         key.objectid = BTRFS_BALANCE_OBJECTID;
3057         key.type = BTRFS_TEMPORARY_ITEM_KEY;
3058         key.offset = 0;
3059
3060         ret = btrfs_insert_empty_item(trans, root, path, &key,
3061                                       sizeof(*item));
3062         if (ret)
3063                 goto out;
3064
3065         leaf = path->nodes[0];
3066         item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3067
3068         memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
3069
3070         btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3071         btrfs_set_balance_data(leaf, item, &disk_bargs);
3072         btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
3073         btrfs_set_balance_meta(leaf, item, &disk_bargs);
3074         btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
3075         btrfs_set_balance_sys(leaf, item, &disk_bargs);
3076
3077         btrfs_set_balance_flags(leaf, item, bctl->flags);
3078
3079         btrfs_mark_buffer_dirty(leaf);
3080 out:
3081         btrfs_free_path(path);
3082         err = btrfs_commit_transaction(trans);
3083         if (err && !ret)
3084                 ret = err;
3085         return ret;
3086 }
3087
3088 static int del_balance_item(struct btrfs_fs_info *fs_info)
3089 {
3090         struct btrfs_root *root = fs_info->tree_root;
3091         struct btrfs_trans_handle *trans;
3092         struct btrfs_path *path;
3093         struct btrfs_key key;
3094         int ret, err;
3095
3096         path = btrfs_alloc_path();
3097         if (!path)
3098                 return -ENOMEM;
3099
3100         trans = btrfs_start_transaction(root, 0);
3101         if (IS_ERR(trans)) {
3102                 btrfs_free_path(path);
3103                 return PTR_ERR(trans);
3104         }
3105
3106         key.objectid = BTRFS_BALANCE_OBJECTID;
3107         key.type = BTRFS_TEMPORARY_ITEM_KEY;
3108         key.offset = 0;
3109
3110         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3111         if (ret < 0)
3112                 goto out;
3113         if (ret > 0) {
3114                 ret = -ENOENT;
3115                 goto out;
3116         }
3117
3118         ret = btrfs_del_item(trans, root, path);
3119 out:
3120         btrfs_free_path(path);
3121         err = btrfs_commit_transaction(trans);
3122         if (err && !ret)
3123                 ret = err;
3124         return ret;
3125 }
3126
3127 /*
3128  * This is a heuristic used to reduce the number of chunks balanced on
3129  * resume after balance was interrupted.
3130  */
3131 static void update_balance_args(struct btrfs_balance_control *bctl)
3132 {
3133         /*
3134          * Turn on soft mode for chunk types that were being converted.
3135          */
3136         if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
3137                 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
3138         if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
3139                 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
3140         if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
3141                 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
3142
3143         /*
3144          * Turn on usage filter if is not already used.  The idea is
3145          * that chunks that we have already balanced should be
3146          * reasonably full.  Don't do it for chunks that are being
3147          * converted - that will keep us from relocating unconverted
3148          * (albeit full) chunks.
3149          */
3150         if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3151             !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3152             !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3153                 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
3154                 bctl->data.usage = 90;
3155         }
3156         if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3157             !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3158             !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3159                 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
3160                 bctl->sys.usage = 90;
3161         }
3162         if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3163             !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3164             !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3165                 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
3166                 bctl->meta.usage = 90;
3167         }
3168 }
3169
3170 /*
3171  * Clear the balance status in fs_info and delete the balance item from disk.
3172  */
3173 static void reset_balance_state(struct btrfs_fs_info *fs_info)
3174 {
3175         struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3176         int ret;
3177
3178         BUG_ON(!fs_info->balance_ctl);
3179
3180         spin_lock(&fs_info->balance_lock);
3181         fs_info->balance_ctl = NULL;
3182         spin_unlock(&fs_info->balance_lock);
3183
3184         kfree(bctl);
3185         ret = del_balance_item(fs_info);
3186         if (ret)
3187                 btrfs_handle_fs_error(fs_info, ret, NULL);
3188 }
3189
3190 /*
3191  * Balance filters.  Return 1 if chunk should be filtered out
3192  * (should not be balanced).
3193  */
3194 static int chunk_profiles_filter(u64 chunk_type,
3195                                  struct btrfs_balance_args *bargs)
3196 {
3197         chunk_type = chunk_to_extended(chunk_type) &
3198                                 BTRFS_EXTENDED_PROFILE_MASK;
3199
3200         if (bargs->profiles & chunk_type)
3201                 return 0;
3202
3203         return 1;
3204 }
3205
3206 static int chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3207                               struct btrfs_balance_args *bargs)
3208 {
3209         struct btrfs_block_group_cache *cache;
3210         u64 chunk_used;
3211         u64 user_thresh_min;
3212         u64 user_thresh_max;
3213         int ret = 1;
3214
3215         cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3216         chunk_used = btrfs_block_group_used(&cache->item);
3217
3218         if (bargs->usage_min == 0)
3219                 user_thresh_min = 0;
3220         else
3221                 user_thresh_min = div_factor_fine(cache->key.offset,
3222                                         bargs->usage_min);
3223
3224         if (bargs->usage_max == 0)
3225                 user_thresh_max = 1;
3226         else if (bargs->usage_max > 100)
3227                 user_thresh_max = cache->key.offset;
3228         else
3229                 user_thresh_max = div_factor_fine(cache->key.offset,
3230                                         bargs->usage_max);
3231
3232         if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max)
3233                 ret = 0;
3234
3235         btrfs_put_block_group(cache);
3236         return ret;
3237 }
3238
3239 static int chunk_usage_filter(struct btrfs_fs_info *fs_info,
3240                 u64 chunk_offset, struct btrfs_balance_args *bargs)
3241 {
3242         struct btrfs_block_group_cache *cache;
3243         u64 chunk_used, user_thresh;
3244         int ret = 1;
3245
3246         cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3247         chunk_used = btrfs_block_group_used(&cache->item);
3248
3249         if (bargs->usage_min == 0)
3250                 user_thresh = 1;
3251         else if (bargs->usage > 100)
3252                 user_thresh = cache->key.offset;
3253         else
3254                 user_thresh = div_factor_fine(cache->key.offset,
3255                                               bargs->usage);
3256
3257         if (chunk_used < user_thresh)
3258                 ret = 0;
3259
3260         btrfs_put_block_group(cache);
3261         return ret;
3262 }
3263
3264 static int chunk_devid_filter(struct extent_buffer *leaf,
3265                               struct btrfs_chunk *chunk,
3266                               struct btrfs_balance_args *bargs)
3267 {
3268         struct btrfs_stripe *stripe;
3269         int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3270         int i;
3271
3272         for (i = 0; i < num_stripes; i++) {
3273                 stripe = btrfs_stripe_nr(chunk, i);
3274                 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
3275                         return 0;
3276         }
3277
3278         return 1;
3279 }
3280
3281 /* [pstart, pend) */
3282 static int chunk_drange_filter(struct extent_buffer *leaf,
3283                                struct btrfs_chunk *chunk,
3284                                struct btrfs_balance_args *bargs)
3285 {
3286         struct btrfs_stripe *stripe;
3287         int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3288         u64 stripe_offset;
3289         u64 stripe_length;
3290         int factor;
3291         int i;
3292
3293         if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
3294                 return 0;
3295
3296         if (btrfs_chunk_type(leaf, chunk) & (BTRFS_BLOCK_GROUP_DUP |
3297              BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)) {
3298                 factor = num_stripes / 2;
3299         } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID5) {
3300                 factor = num_stripes - 1;
3301         } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID6) {
3302                 factor = num_stripes - 2;
3303         } else {
3304                 factor = num_stripes;
3305         }
3306
3307         for (i = 0; i < num_stripes; i++) {
3308                 stripe = btrfs_stripe_nr(chunk, i);
3309                 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
3310                         continue;
3311
3312                 stripe_offset = btrfs_stripe_offset(leaf, stripe);
3313                 stripe_length = btrfs_chunk_length(leaf, chunk);
3314                 stripe_length = div_u64(stripe_length, factor);
3315
3316                 if (stripe_offset < bargs->pend &&
3317                     stripe_offset + stripe_length > bargs->pstart)
3318                         return 0;
3319         }
3320
3321         return 1;
3322 }
3323
3324 /* [vstart, vend) */
3325 static int chunk_vrange_filter(struct extent_buffer *leaf,
3326                                struct btrfs_chunk *chunk,
3327                                u64 chunk_offset,
3328                                struct btrfs_balance_args *bargs)
3329 {
3330         if (chunk_offset < bargs->vend &&
3331             chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
3332                 /* at least part of the chunk is inside this vrange */
3333                 return 0;
3334
3335         return 1;
3336 }
3337
3338 static int chunk_stripes_range_filter(struct extent_buffer *leaf,
3339                                struct btrfs_chunk *chunk,
3340                                struct btrfs_balance_args *bargs)
3341 {
3342         int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3343
3344         if (bargs->stripes_min <= num_stripes
3345                         && num_stripes <= bargs->stripes_max)
3346                 return 0;
3347
3348         return 1;
3349 }
3350
3351 static int chunk_soft_convert_filter(u64 chunk_type,
3352                                      struct btrfs_balance_args *bargs)
3353 {
3354         if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3355                 return 0;
3356
3357         chunk_type = chunk_to_extended(chunk_type) &
3358                                 BTRFS_EXTENDED_PROFILE_MASK;
3359
3360         if (bargs->target == chunk_type)
3361                 return 1;
3362
3363         return 0;
3364 }
3365
3366 static int should_balance_chunk(struct btrfs_fs_info *fs_info,
3367                                 struct extent_buffer *leaf,
3368                                 struct btrfs_chunk *chunk, u64 chunk_offset)
3369 {
3370         struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3371         struct btrfs_balance_args *bargs = NULL;
3372         u64 chunk_type = btrfs_chunk_type(leaf, chunk);
3373
3374         /* type filter */
3375         if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
3376               (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3377                 return 0;
3378         }
3379
3380         if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3381                 bargs = &bctl->data;
3382         else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3383                 bargs = &bctl->sys;
3384         else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3385                 bargs = &bctl->meta;
3386
3387         /* profiles filter */
3388         if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
3389             chunk_profiles_filter(chunk_type, bargs)) {
3390                 return 0;
3391         }
3392
3393         /* usage filter */
3394         if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
3395             chunk_usage_filter(fs_info, chunk_offset, bargs)) {
3396                 return 0;
3397         } else if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3398             chunk_usage_range_filter(fs_info, chunk_offset, bargs)) {
3399                 return 0;
3400         }
3401
3402         /* devid filter */
3403         if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
3404             chunk_devid_filter(leaf, chunk, bargs)) {
3405                 return 0;
3406         }
3407
3408         /* drange filter, makes sense only with devid filter */
3409         if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
3410             chunk_drange_filter(leaf, chunk, bargs)) {
3411                 return 0;
3412         }
3413
3414         /* vrange filter */
3415         if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
3416             chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
3417                 return 0;
3418         }
3419
3420         /* stripes filter */
3421         if ((bargs->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) &&
3422             chunk_stripes_range_filter(leaf, chunk, bargs)) {
3423                 return 0;
3424         }
3425
3426         /* soft profile changing mode */
3427         if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
3428             chunk_soft_convert_filter(chunk_type, bargs)) {
3429                 return 0;
3430         }
3431
3432         /*
3433          * limited by count, must be the last filter
3434          */
3435         if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
3436                 if (bargs->limit == 0)
3437                         return 0;
3438                 else
3439                         bargs->limit--;
3440         } else if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)) {
3441                 /*
3442                  * Same logic as the 'limit' filter; the minimum cannot be
3443                  * determined here because we do not have the global information
3444                  * about the count of all chunks that satisfy the filters.
3445                  */
3446                 if (bargs->limit_max == 0)
3447                         return 0;
3448                 else
3449                         bargs->limit_max--;
3450         }
3451
3452         return 1;
3453 }
3454
3455 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
3456 {
3457         struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3458         struct btrfs_root *chunk_root = fs_info->chunk_root;
3459         struct btrfs_root *dev_root = fs_info->dev_root;
3460         struct list_head *devices;
3461         struct btrfs_device *device;
3462         u64 old_size;
3463         u64 size_to_free;
3464         u64 chunk_type;
3465         struct btrfs_chunk *chunk;
3466         struct btrfs_path *path = NULL;
3467         struct btrfs_key key;
3468         struct btrfs_key found_key;
3469         struct btrfs_trans_handle *trans;
3470         struct extent_buffer *leaf;
3471         int slot;
3472         int ret;
3473         int enospc_errors = 0;
3474         bool counting = true;
3475         /* The single value limit and min/max limits use the same bytes in the */
3476         u64 limit_data = bctl->data.limit;
3477         u64 limit_meta = bctl->meta.limit;
3478         u64 limit_sys = bctl->sys.limit;
3479         u32 count_data = 0;
3480         u32 count_meta = 0;
3481         u32 count_sys = 0;
3482         int chunk_reserved = 0;
3483
3484         /* step one make some room on all the devices */
3485         devices = &fs_info->fs_devices->devices;
3486         list_for_each_entry(device, devices, dev_list) {
3487                 old_size = btrfs_device_get_total_bytes(device);
3488                 size_to_free = div_factor(old_size, 1);
3489                 size_to_free = min_t(u64, size_to_free, SZ_1M);
3490                 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) ||
3491                     btrfs_device_get_total_bytes(device) -
3492                     btrfs_device_get_bytes_used(device) > size_to_free ||
3493                     test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
3494                         continue;
3495
3496                 ret = btrfs_shrink_device(device, old_size - size_to_free);
3497                 if (ret == -ENOSPC)
3498                         break;
3499                 if (ret) {
3500                         /* btrfs_shrink_device never returns ret > 0 */
3501                         WARN_ON(ret > 0);
3502                         goto error;
3503                 }
3504
3505                 trans = btrfs_start_transaction(dev_root, 0);
3506                 if (IS_ERR(trans)) {
3507                         ret = PTR_ERR(trans);
3508                         btrfs_info_in_rcu(fs_info,
3509                  "resize: unable to start transaction after shrinking device %s (error %d), old size %llu, new size %llu",
3510                                           rcu_str_deref(device->name), ret,
3511                                           old_size, old_size - size_to_free);
3512                         goto error;
3513                 }
3514
3515                 ret = btrfs_grow_device(trans, device, old_size);
3516                 if (ret) {
3517                         btrfs_end_transaction(trans);
3518                         /* btrfs_grow_device never returns ret > 0 */
3519                         WARN_ON(ret > 0);
3520                         btrfs_info_in_rcu(fs_info,
3521                  "resize: unable to grow device after shrinking device %s (error %d), old size %llu, new size %llu",
3522                                           rcu_str_deref(device->name), ret,
3523                                           old_size, old_size - size_to_free);
3524                         goto error;
3525                 }
3526
3527                 btrfs_end_transaction(trans);
3528         }
3529
3530         /* step two, relocate all the chunks */
3531         path = btrfs_alloc_path();
3532         if (!path) {
3533                 ret = -ENOMEM;
3534                 goto error;
3535         }
3536
3537         /* zero out stat counters */
3538         spin_lock(&fs_info->balance_lock);
3539         memset(&bctl->stat, 0, sizeof(bctl->stat));
3540         spin_unlock(&fs_info->balance_lock);
3541 again:
3542         if (!counting) {
3543                 /*
3544                  * The single value limit and min/max limits use the same bytes
3545                  * in the
3546                  */
3547                 bctl->data.limit = limit_data;
3548                 bctl->meta.limit = limit_meta;
3549                 bctl->sys.limit = limit_sys;
3550         }
3551         key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3552         key.offset = (u64)-1;
3553         key.type = BTRFS_CHUNK_ITEM_KEY;
3554
3555         while (1) {
3556                 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
3557                     atomic_read(&fs_info->balance_cancel_req)) {
3558                         ret = -ECANCELED;
3559                         goto error;
3560                 }
3561
3562                 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3563                 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3564                 if (ret < 0) {
3565                         mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3566                         goto error;
3567                 }
3568
3569                 /*
3570                  * this shouldn't happen, it means the last relocate
3571                  * failed
3572                  */
3573                 if (ret == 0)
3574                         BUG(); /* FIXME break ? */
3575
3576                 ret = btrfs_previous_item(chunk_root, path, 0,
3577                                           BTRFS_CHUNK_ITEM_KEY);
3578                 if (ret) {
3579                         mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3580                         ret = 0;
3581                         break;
3582                 }
3583
3584                 leaf = path->nodes[0];
3585                 slot = path->slots[0];
3586                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3587
3588                 if (found_key.objectid != key.objectid) {
3589                         mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3590                         break;
3591                 }
3592
3593                 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3594                 chunk_type = btrfs_chunk_type(leaf, chunk);
3595
3596                 if (!counting) {
3597                         spin_lock(&fs_info->balance_lock);
3598                         bctl->stat.considered++;
3599                         spin_unlock(&fs_info->balance_lock);
3600                 }
3601
3602                 ret = should_balance_chunk(fs_info, leaf, chunk,
3603                                            found_key.offset);
3604
3605                 btrfs_release_path(path);
3606                 if (!ret) {
3607                         mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3608                         goto loop;
3609                 }
3610
3611                 if (counting) {
3612                         mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3613                         spin_lock(&fs_info->balance_lock);
3614                         bctl->stat.expected++;
3615                         spin_unlock(&fs_info->balance_lock);
3616
3617                         if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3618                                 count_data++;
3619                         else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3620                                 count_sys++;
3621                         else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3622                                 count_meta++;
3623
3624                         goto loop;
3625                 }
3626
3627                 /*
3628                  * Apply limit_min filter, no need to check if the LIMITS
3629                  * filter is used, limit_min is 0 by default
3630                  */
3631                 if (((chunk_type & BTRFS_BLOCK_GROUP_DATA) &&
3632                                         count_data < bctl->data.limit_min)
3633                                 || ((chunk_type & BTRFS_BLOCK_GROUP_METADATA) &&
3634                                         count_meta < bctl->meta.limit_min)
3635                                 || ((chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) &&
3636                                         count_sys < bctl->sys.limit_min)) {
3637                         mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3638                         goto loop;
3639                 }
3640
3641                 if (!chunk_reserved) {
3642                         /*
3643                          * We may be relocating the only data chunk we have,
3644                          * which could potentially end up with losing data's
3645                          * raid profile, so lets allocate an empty one in
3646                          * advance.
3647                          */
3648                         ret = btrfs_may_alloc_data_chunk(fs_info,
3649                                                          found_key.offset);
3650                         if (ret < 0) {
3651                                 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3652                                 goto error;
3653                         } else if (ret == 1) {
3654                                 chunk_reserved = 1;
3655                         }
3656                 }
3657
3658                 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3659                 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3660                 if (ret && ret != -ENOSPC)
3661                         goto error;
3662                 if (ret == -ENOSPC) {
3663                         enospc_errors++;
3664                 } else {
3665                         spin_lock(&fs_info->balance_lock);
3666                         bctl->stat.completed++;
3667                         spin_unlock(&fs_info->balance_lock);
3668                 }
3669 loop:
3670                 if (found_key.offset == 0)
3671                         break;
3672                 key.offset = found_key.offset - 1;
3673         }
3674
3675         if (counting) {
3676                 btrfs_release_path(path);
3677                 counting = false;
3678                 goto again;
3679         }
3680 error:
3681         btrfs_free_path(path);
3682         if (enospc_errors) {
3683                 btrfs_info(fs_info, "%d enospc errors during balance",
3684                            enospc_errors);
3685                 if (!ret)
3686                         ret = -ENOSPC;
3687         }
3688
3689         return ret;
3690 }
3691
3692 /**
3693  * alloc_profile_is_valid - see if a given profile is valid and reduced
3694  * @flags: profile to validate
3695  * @extended: if true @flags is treated as an extended profile
3696  */
3697 static int alloc_profile_is_valid(u64 flags, int extended)
3698 {
3699         u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
3700                                BTRFS_BLOCK_GROUP_PROFILE_MASK);
3701
3702         flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
3703
3704         /* 1) check that all other bits are zeroed */
3705         if (flags & ~mask)
3706                 return 0;
3707
3708         /* 2) see if profile is reduced */
3709         if (flags == 0)
3710                 return !extended; /* "0" is valid for usual profiles */
3711
3712         /* true if exactly one bit set */
3713         return (flags & (flags - 1)) == 0;
3714 }
3715
3716 static inline int balance_need_close(struct btrfs_fs_info *fs_info)
3717 {
3718         /* cancel requested || normal exit path */
3719         return atomic_read(&fs_info->balance_cancel_req) ||
3720                 (atomic_read(&fs_info->balance_pause_req) == 0 &&
3721                  atomic_read(&fs_info->balance_cancel_req) == 0);
3722 }
3723
3724 /* Non-zero return value signifies invalidity */
3725 static inline int validate_convert_profile(struct btrfs_balance_args *bctl_arg,
3726                 u64 allowed)
3727 {
3728         return ((bctl_arg->flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3729                 (!alloc_profile_is_valid(bctl_arg->target, 1) ||
3730                  (bctl_arg->target & ~allowed)));
3731 }
3732
3733 /*
3734  * Should be called with balance mutexe held
3735  */
3736 int btrfs_balance(struct btrfs_fs_info *fs_info,
3737                   struct btrfs_balance_control *bctl,
3738                   struct btrfs_ioctl_balance_args *bargs)
3739 {
3740         u64 meta_target, data_target;
3741         u64 allowed;
3742         int mixed = 0;
3743         int ret;
3744         u64 num_devices;
3745         unsigned seq;
3746         bool reducing_integrity;
3747
3748         if (btrfs_fs_closing(fs_info) ||
3749             atomic_read(&fs_info->balance_pause_req) ||
3750             atomic_read(&fs_info->balance_cancel_req)) {
3751                 ret = -EINVAL;
3752                 goto out;
3753         }
3754
3755         allowed = btrfs_super_incompat_flags(fs_info->super_copy);
3756         if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
3757                 mixed = 1;
3758
3759         /*
3760          * In case of mixed groups both data and meta should be picked,
3761          * and identical options should be given for both of them.
3762          */
3763         allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
3764         if (mixed && (bctl->flags & allowed)) {
3765                 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
3766                     !(bctl->flags & BTRFS_BALANCE_METADATA) ||
3767                     memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
3768                         btrfs_err(fs_info,
3769           "balance: mixed groups data and metadata options must be the same");
3770                         ret = -EINVAL;
3771                         goto out;
3772                 }
3773         }
3774
3775         num_devices = fs_info->fs_devices->num_devices;
3776         btrfs_dev_replace_read_lock(&fs_info->dev_replace);
3777         if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
3778                 BUG_ON(num_devices < 1);
3779                 num_devices--;
3780         }
3781         btrfs_dev_replace_read_unlock(&fs_info->dev_replace);
3782         allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE | BTRFS_BLOCK_GROUP_DUP;
3783         if (num_devices > 1)
3784                 allowed |= (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1);
3785         if (num_devices > 2)
3786                 allowed |= BTRFS_BLOCK_GROUP_RAID5;
3787         if (num_devices > 3)
3788                 allowed |= (BTRFS_BLOCK_GROUP_RAID10 |
3789                             BTRFS_BLOCK_GROUP_RAID6);
3790         if (validate_convert_profile(&bctl->data, allowed)) {
3791                 int index = btrfs_bg_flags_to_raid_index(bctl->data.target);
3792
3793                 btrfs_err(fs_info,
3794                           "balance: invalid convert data profile %s",
3795                           get_raid_name(index));
3796                 ret = -EINVAL;
3797                 goto out;
3798         }
3799         if (validate_convert_profile(&bctl->meta, allowed)) {
3800                 int index = btrfs_bg_flags_to_raid_index(bctl->meta.target);
3801
3802                 btrfs_err(fs_info,
3803                           "balance: invalid convert metadata profile %s",
3804                           get_raid_name(index));
3805                 ret = -EINVAL;
3806                 goto out;
3807         }
3808         if (validate_convert_profile(&bctl->sys, allowed)) {
3809                 int index = btrfs_bg_flags_to_raid_index(bctl->sys.target);
3810
3811                 btrfs_err(fs_info,
3812                           "balance: invalid convert system profile %s",
3813                           get_raid_name(index));
3814                 ret = -EINVAL;
3815                 goto out;
3816         }
3817
3818         /* allow to reduce meta or sys integrity only if force set */
3819         allowed = BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
3820                         BTRFS_BLOCK_GROUP_RAID10 |
3821                         BTRFS_BLOCK_GROUP_RAID5 |
3822                         BTRFS_BLOCK_GROUP_RAID6;
3823         do {
3824                 seq = read_seqbegin(&fs_info->profiles_lock);
3825
3826                 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3827                      (fs_info->avail_system_alloc_bits & allowed) &&
3828                      !(bctl->sys.target & allowed)) ||
3829                     ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3830                      (fs_info->avail_metadata_alloc_bits & allowed) &&
3831                      !(bctl->meta.target & allowed)))
3832                         reducing_integrity = true;
3833                 else
3834                         reducing_integrity = false;
3835
3836                 /* if we're not converting, the target field is uninitialized */
3837                 meta_target = (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
3838                         bctl->meta.target : fs_info->avail_metadata_alloc_bits;
3839                 data_target = (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
3840                         bctl->data.target : fs_info->avail_data_alloc_bits;
3841         } while (read_seqretry(&fs_info->profiles_lock, seq));
3842
3843         if (reducing_integrity) {
3844                 if (bctl->flags & BTRFS_BALANCE_FORCE) {
3845                         btrfs_info(fs_info,
3846                                    "balance: force reducing metadata integrity");
3847                 } else {
3848                         btrfs_err(fs_info,
3849           "balance: reduces metadata integrity, use --force if you want this");
3850                         ret = -EINVAL;
3851                         goto out;
3852                 }
3853         }
3854
3855         if (btrfs_get_num_tolerated_disk_barrier_failures(meta_target) <
3856                 btrfs_get_num_tolerated_disk_barrier_failures(data_target)) {
3857                 int meta_index = btrfs_bg_flags_to_raid_index(meta_target);
3858                 int data_index = btrfs_bg_flags_to_raid_index(data_target);
3859
3860                 btrfs_warn(fs_info,
3861         "balance: metadata profile %s has lower redundancy than data profile %s",
3862                            get_raid_name(meta_index), get_raid_name(data_index));
3863         }
3864
3865         ret = insert_balance_item(fs_info, bctl);
3866         if (ret && ret != -EEXIST)
3867                 goto out;
3868
3869         if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
3870                 BUG_ON(ret == -EEXIST);
3871                 BUG_ON(fs_info->balance_ctl);
3872                 spin_lock(&fs_info->balance_lock);
3873                 fs_info->balance_ctl = bctl;
3874                 spin_unlock(&fs_info->balance_lock);
3875         } else {
3876                 BUG_ON(ret != -EEXIST);
3877                 spin_lock(&fs_info->balance_lock);
3878                 update_balance_args(bctl);
3879                 spin_unlock(&fs_info->balance_lock);
3880         }
3881
3882         ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
3883         set_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
3884         mutex_unlock(&fs_info->balance_mutex);
3885
3886         ret = __btrfs_balance(fs_info);
3887
3888         mutex_lock(&fs_info->balance_mutex);
3889         clear_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
3890
3891         if (bargs) {
3892                 memset(bargs, 0, sizeof(*bargs));
3893                 btrfs_update_ioctl_balance_args(fs_info, bargs);
3894         }
3895
3896         if ((ret && ret != -ECANCELED && ret != -ENOSPC) ||
3897             balance_need_close(fs_info)) {
3898                 reset_balance_state(fs_info);
3899                 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
3900         }
3901
3902         wake_up(&fs_info->balance_wait_q);
3903
3904         return ret;
3905 out:
3906         if (bctl->flags & BTRFS_BALANCE_RESUME)
3907                 reset_balance_state(fs_info);
3908         else
3909                 kfree(bctl);
3910         clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
3911
3912         return ret;
3913 }
3914
3915 static int balance_kthread(void *data)
3916 {
3917         struct btrfs_fs_info *fs_info = data;
3918         int ret = 0;
3919
3920         mutex_lock(&fs_info->balance_mutex);
3921         if (fs_info->balance_ctl) {
3922                 btrfs_info(fs_info, "balance: resuming");
3923                 ret = btrfs_balance(fs_info, fs_info->balance_ctl, NULL);
3924         }
3925         mutex_unlock(&fs_info->balance_mutex);
3926
3927         return ret;
3928 }
3929
3930 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
3931 {
3932         struct task_struct *tsk;
3933
3934         mutex_lock(&fs_info->balance_mutex);
3935         if (!fs_info->balance_ctl) {
3936                 mutex_unlock(&fs_info->balance_mutex);
3937                 return 0;
3938         }
3939         mutex_unlock(&fs_info->balance_mutex);
3940
3941         if (btrfs_test_opt(fs_info, SKIP_BALANCE)) {
3942                 btrfs_info(fs_info, "balance: resume skipped");
3943                 return 0;
3944         }
3945
3946         /*
3947          * A ro->rw remount sequence should continue with the paused balance
3948          * regardless of who pauses it, system or the user as of now, so set
3949          * the resume flag.
3950          */
3951         spin_lock(&fs_info->balance_lock);
3952         fs_info->balance_ctl->flags |= BTRFS_BALANCE_RESUME;
3953         spin_unlock(&fs_info->balance_lock);
3954
3955         tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
3956         return PTR_ERR_OR_ZERO(tsk);
3957 }
3958
3959 int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
3960 {
3961         struct btrfs_balance_control *bctl;
3962         struct btrfs_balance_item *item;
3963         struct btrfs_disk_balance_args disk_bargs;
3964         struct btrfs_path *path;
3965         struct extent_buffer *leaf;
3966         struct btrfs_key key;
3967         int ret;
3968
3969         path = btrfs_alloc_path();
3970         if (!path)
3971                 return -ENOMEM;
3972
3973         key.objectid = BTRFS_BALANCE_OBJECTID;
3974         key.type = BTRFS_TEMPORARY_ITEM_KEY;
3975         key.offset = 0;
3976
3977         ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
3978         if (ret < 0)
3979                 goto out;
3980         if (ret > 0) { /* ret = -ENOENT; */
3981                 ret = 0;
3982                 goto out;
3983         }
3984
3985         bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
3986         if (!bctl) {
3987                 ret = -ENOMEM;
3988                 goto out;
3989         }
3990
3991         leaf = path->nodes[0];
3992         item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3993
3994         bctl->flags = btrfs_balance_flags(leaf, item);
3995         bctl->flags |= BTRFS_BALANCE_RESUME;
3996
3997         btrfs_balance_data(leaf, item, &disk_bargs);
3998         btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
3999         btrfs_balance_meta(leaf, item, &disk_bargs);
4000         btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
4001         btrfs_balance_sys(leaf, item, &disk_bargs);
4002         btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
4003
4004         /*
4005          * This should never happen, as the paused balance state is recovered
4006          * during mount without any chance of other exclusive ops to collide.
4007          *
4008          * This gives the exclusive op status to balance and keeps in paused
4009          * state until user intervention (cancel or umount). If the ownership
4010          * cannot be assigned, show a message but do not fail. The balance
4011          * is in a paused state and must have fs_info::balance_ctl properly
4012          * set up.
4013          */
4014         if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags))
4015                 btrfs_warn(fs_info,
4016         "balance: cannot set exclusive op status, resume manually");
4017
4018         btrfs_release_path(path);
4019
4020         mutex_lock(&fs_info->balance_mutex);
4021         BUG_ON(fs_info->balance_ctl);
4022         spin_lock(&fs_info->balance_lock);
4023         fs_info->balance_ctl = bctl;
4024         spin_unlock(&fs_info->balance_lock);
4025         mutex_unlock(&fs_info->balance_mutex);
4026 out:
4027         btrfs_free_path(path);
4028         return ret;
4029 }
4030
4031 int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
4032 {
4033         int ret = 0;
4034
4035         mutex_lock(&fs_info->balance_mutex);
4036         if (!fs_info->balance_ctl) {
4037                 mutex_unlock(&fs_info->balance_mutex);
4038                 return -ENOTCONN;
4039         }
4040
4041         if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4042                 atomic_inc(&fs_info->balance_pause_req);
4043                 mutex_unlock(&fs_info->balance_mutex);
4044
4045                 wait_event(fs_info->balance_wait_q,
4046                            !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4047
4048                 mutex_lock(&fs_info->balance_mutex);
4049                 /* we are good with balance_ctl ripped off from under us */
4050                 BUG_ON(test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4051                 atomic_dec(&fs_info->balance_pause_req);
4052         } else {
4053                 ret = -ENOTCONN;
4054         }
4055
4056         mutex_unlock(&fs_info->balance_mutex);
4057         return ret;
4058 }
4059
4060 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
4061 {
4062         mutex_lock(&fs_info->balance_mutex);
4063         if (!fs_info->balance_ctl) {
4064                 mutex_unlock(&fs_info->balance_mutex);
4065                 return -ENOTCONN;
4066         }
4067
4068         /*
4069          * A paused balance with the item stored on disk can be resumed at
4070          * mount time if the mount is read-write. Otherwise it's still paused
4071          * and we must not allow cancelling as it deletes the item.
4072          */
4073         if (sb_rdonly(fs_info->sb)) {
4074                 mutex_unlock(&fs_info->balance_mutex);
4075                 return -EROFS;
4076         }
4077
4078         atomic_inc(&fs_info->balance_cancel_req);
4079         /*
4080          * if we are running just wait and return, balance item is
4081          * deleted in btrfs_balance in this case
4082          */
4083         if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4084                 mutex_unlock(&fs_info->balance_mutex);
4085                 wait_event(fs_info->balance_wait_q,
4086                            !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4087                 mutex_lock(&fs_info->balance_mutex);
4088         } else {
4089                 mutex_unlock(&fs_info->balance_mutex);
4090                 /*
4091                  * Lock released to allow other waiters to continue, we'll
4092                  * reexamine the status again.
4093                  */
4094                 mutex_lock(&fs_info->balance_mutex);
4095
4096                 if (fs_info->balance_ctl) {
4097                         reset_balance_state(fs_info);
4098                         clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4099                         btrfs_info(fs_info, "balance: canceled");
4100                 }
4101         }
4102
4103         BUG_ON(fs_info->balance_ctl ||
4104                 test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4105         atomic_dec(&fs_info->balance_cancel_req);
4106         mutex_unlock(&fs_info->balance_mutex);
4107         return 0;
4108 }
4109
4110 static int btrfs_uuid_scan_kthread(void *data)
4111 {
4112         struct btrfs_fs_info *fs_info = data;
4113         struct btrfs_root *root = fs_info->tree_root;
4114         struct btrfs_key key;
4115         struct btrfs_path *path = NULL;
4116         int ret = 0;
4117         struct extent_buffer *eb;
4118         int slot;
4119         struct btrfs_root_item root_item;
4120         u32 item_size;
4121         struct btrfs_trans_handle *trans = NULL;
4122
4123         path = btrfs_alloc_path();
4124         if (!path) {
4125                 ret = -ENOMEM;
4126                 goto out;
4127         }
4128
4129         key.objectid = 0;
4130         key.type = BTRFS_ROOT_ITEM_KEY;
4131         key.offset = 0;
4132
4133         while (1) {
4134                 ret = btrfs_search_forward(root, &key, path,
4135                                 BTRFS_OLDEST_GENERATION);
4136                 if (ret) {
4137                         if (ret > 0)
4138                                 ret = 0;
4139                         break;
4140                 }
4141
4142                 if (key.type != BTRFS_ROOT_ITEM_KEY ||
4143                     (key.objectid < BTRFS_FIRST_FREE_OBJECTID &&
4144                      key.objectid != BTRFS_FS_TREE_OBJECTID) ||
4145                     key.objectid > BTRFS_LAST_FREE_OBJECTID)
4146                         goto skip;
4147
4148                 eb = path->nodes[0];
4149                 slot = path->slots[0];
4150                 item_size = btrfs_item_size_nr(eb, slot);
4151                 if (item_size < sizeof(root_item))
4152                         goto skip;
4153
4154                 read_extent_buffer(eb, &root_item,
4155                                    btrfs_item_ptr_offset(eb, slot),
4156                                    (int)sizeof(root_item));
4157                 if (btrfs_root_refs(&root_item) == 0)
4158                         goto skip;
4159
4160                 if (!btrfs_is_empty_uuid(root_item.uuid) ||
4161                     !btrfs_is_empty_uuid(root_item.received_uuid)) {
4162                         if (trans)
4163                                 goto update_tree;
4164
4165                         btrfs_release_path(path);
4166                         /*
4167                          * 1 - subvol uuid item
4168                          * 1 - received_subvol uuid item
4169                          */
4170                         trans = btrfs_start_transaction(fs_info->uuid_root, 2);
4171                         if (IS_ERR(trans)) {
4172                                 ret = PTR_ERR(trans);
4173                                 break;
4174                         }
4175                         continue;
4176                 } else {
4177                         goto skip;
4178                 }
4179 update_tree:
4180                 btrfs_release_path(path);
4181                 if (!btrfs_is_empty_uuid(root_item.uuid)) {
4182                         ret = btrfs_uuid_tree_add(trans, root_item.uuid,
4183                                                   BTRFS_UUID_KEY_SUBVOL,
4184                                                   key.objectid);
4185                         if (ret < 0) {
4186                                 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4187                                         ret);
4188                                 break;
4189                         }
4190                 }
4191
4192                 if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
4193                         ret = btrfs_uuid_tree_add(trans,
4194                                                   root_item.received_uuid,
4195                                                  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4196                                                   key.objectid);
4197                         if (ret < 0) {
4198                                 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4199                                         ret);
4200                                 break;
4201                         }
4202                 }
4203
4204 skip:
4205                 btrfs_release_path(path);
4206                 if (trans) {
4207                         ret = btrfs_end_transaction(trans);
4208                         trans = NULL;
4209                         if (ret)
4210                                 break;
4211                 }
4212
4213                 if (key.offset < (u64)-1) {
4214                         key.offset++;
4215                 } else if (key.type < BTRFS_ROOT_ITEM_KEY) {
4216                         key.offset = 0;
4217                         key.type = BTRFS_ROOT_ITEM_KEY;
4218                 } else if (key.objectid < (u64)-1) {
4219                         key.offset = 0;
4220                         key.type = BTRFS_ROOT_ITEM_KEY;
4221                         key.objectid++;
4222                 } else {
4223                         break;
4224                 }
4225                 cond_resched();
4226         }
4227
4228 out:
4229         btrfs_free_path(path);
4230         if (trans && !IS_ERR(trans))
4231                 btrfs_end_transaction(trans);
4232         if (ret)
4233                 btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret);
4234         else
4235                 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
4236         up(&fs_info->uuid_tree_rescan_sem);
4237         return 0;
4238 }
4239
4240 /*
4241  * Callback for btrfs_uuid_tree_iterate().
4242  * returns:
4243  * 0    check succeeded, the entry is not outdated.
4244  * < 0  if an error occurred.
4245  * > 0  if the check failed, which means the caller shall remove the entry.
4246  */
4247 static int btrfs_check_uuid_tree_entry(struct btrfs_fs_info *fs_info,
4248                                        u8 *uuid, u8 type, u64 subid)
4249 {
4250         struct btrfs_key key;
4251         int ret = 0;
4252         struct btrfs_root *subvol_root;
4253
4254         if (type != BTRFS_UUID_KEY_SUBVOL &&
4255             type != BTRFS_UUID_KEY_RECEIVED_SUBVOL)
4256                 goto out;
4257
4258         key.objectid = subid;
4259         key.type = BTRFS_ROOT_ITEM_KEY;
4260         key.offset = (u64)-1;
4261         subvol_root = btrfs_read_fs_root_no_name(fs_info, &key);
4262         if (IS_ERR(subvol_root)) {
4263                 ret = PTR_ERR(subvol_root);
4264                 if (ret == -ENOENT)
4265                         ret = 1;
4266                 goto out;
4267         }
4268
4269         switch (type) {
4270         case BTRFS_UUID_KEY_SUBVOL:
4271                 if (memcmp(uuid, subvol_root->root_item.uuid, BTRFS_UUID_SIZE))
4272                         ret = 1;
4273                 break;
4274         case BTRFS_UUID_KEY_RECEIVED_SUBVOL:
4275                 if (memcmp(uuid, subvol_root->root_item.received_uuid,
4276                            BTRFS_UUID_SIZE))
4277                         ret = 1;
4278                 break;
4279         }
4280
4281 out:
4282         return ret;
4283 }
4284
4285 static int btrfs_uuid_rescan_kthread(void *data)
4286 {
4287         struct btrfs_fs_info *fs_info = (struct btrfs_fs_info *)data;
4288         int ret;
4289
4290         /*
4291          * 1st step is to iterate through the existing UUID tree and
4292          * to delete all entries that contain outdated data.
4293          * 2nd step is to add all missing entries to the UUID tree.
4294          */
4295         ret = btrfs_uuid_tree_iterate(fs_info, btrfs_check_uuid_tree_entry);
4296         if (ret < 0) {
4297                 btrfs_warn(fs_info, "iterating uuid_tree failed %d", ret);
4298                 up(&fs_info->uuid_tree_rescan_sem);
4299                 return ret;
4300         }
4301         return btrfs_uuid_scan_kthread(data);
4302 }
4303
4304 int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
4305 {
4306         struct btrfs_trans_handle *trans;
4307         struct btrfs_root *tree_root = fs_info->tree_root;
4308         struct btrfs_root *uuid_root;
4309         struct task_struct *task;
4310         int ret;
4311
4312         /*
4313          * 1 - root node
4314          * 1 - root item
4315          */
4316         trans = btrfs_start_transaction(tree_root, 2);
4317         if (IS_ERR(trans))
4318                 return PTR_ERR(trans);
4319
4320         uuid_root = btrfs_create_tree(trans, fs_info,
4321                                       BTRFS_UUID_TREE_OBJECTID);
4322         if (IS_ERR(uuid_root)) {
4323                 ret = PTR_ERR(uuid_root);
4324                 btrfs_abort_transaction(trans, ret);
4325                 btrfs_end_transaction(trans);
4326                 return ret;
4327         }
4328
4329         fs_info->uuid_root = uuid_root;
4330
4331         ret = btrfs_commit_transaction(trans);
4332         if (ret)
4333                 return ret;
4334
4335         down(&fs_info->uuid_tree_rescan_sem);
4336         task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
4337         if (IS_ERR(task)) {
4338                 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4339                 btrfs_warn(fs_info, "failed to start uuid_scan task");
4340                 up(&fs_info->uuid_tree_rescan_sem);
4341                 return PTR_ERR(task);
4342         }
4343
4344         return 0;
4345 }
4346
4347 int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
4348 {
4349         struct task_struct *task;
4350
4351         down(&fs_info->uuid_tree_rescan_sem);
4352         task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
4353         if (IS_ERR(task)) {
4354                 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4355                 btrfs_warn(fs_info, "failed to start uuid_rescan task");
4356                 up(&fs_info->uuid_tree_rescan_sem);
4357                 return PTR_ERR(task);
4358         }
4359
4360         return 0;
4361 }
4362
4363 /*
4364  * shrinking a device means finding all of the device extents past
4365  * the new size, and then following the back refs to the chunks.
4366  * The chunk relocation code actually frees the device extent
4367  */
4368 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
4369 {
4370         struct btrfs_fs_info *fs_info = device->fs_info;
4371         struct btrfs_root *root = fs_info->dev_root;
4372         struct btrfs_trans_handle *trans;
4373         struct btrfs_dev_extent *dev_extent = NULL;
4374         struct btrfs_path *path;
4375         u64 length;
4376         u64 chunk_offset;
4377         int ret;
4378         int slot;
4379         int failed = 0;
4380         bool retried = false;
4381         bool checked_pending_chunks = false;
4382         struct extent_buffer *l;
4383         struct btrfs_key key;
4384         struct btrfs_super_block *super_copy = fs_info->super_copy;
4385         u64 old_total = btrfs_super_total_bytes(super_copy);
4386         u64 old_size = btrfs_device_get_total_bytes(device);
4387         u64 diff;
4388
4389         new_size = round_down(new_size, fs_info->sectorsize);
4390         diff = round_down(old_size - new_size, fs_info->sectorsize);
4391
4392         if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4393                 return -EINVAL;
4394
4395         path = btrfs_alloc_path();
4396         if (!path)
4397                 return -ENOMEM;
4398
4399         path->reada = READA_BACK;
4400
4401         mutex_lock(&fs_info->chunk_mutex);
4402
4403         btrfs_device_set_total_bytes(device, new_size);
4404         if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4405                 device->fs_devices->total_rw_bytes -= diff;
4406                 atomic64_sub(diff, &fs_info->free_chunk_space);
4407         }
4408         mutex_unlock(&fs_info->chunk_mutex);
4409
4410 again:
4411         key.objectid = device->devid;
4412         key.offset = (u64)-1;
4413         key.type = BTRFS_DEV_EXTENT_KEY;
4414
4415         do {
4416                 mutex_lock(&fs_info->delete_unused_bgs_mutex);
4417                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4418                 if (ret < 0) {
4419                         mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4420                         goto done;
4421                 }
4422
4423                 ret = btrfs_previous_item(root, path, 0, key.type);
4424                 if (ret)
4425                         mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4426                 if (ret < 0)
4427                         goto done;
4428                 if (ret) {
4429                         ret = 0;
4430                         btrfs_release_path(path);
4431                         break;
4432                 }
4433
4434                 l = path->nodes[0];
4435                 slot = path->slots[0];
4436                 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
4437
4438                 if (key.objectid != device->devid) {
4439                         mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4440                         btrfs_release_path(path);
4441                         break;
4442                 }
4443
4444                 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
4445                 length = btrfs_dev_extent_length(l, dev_extent);
4446
4447                 if (key.offset + length <= new_size) {
4448                         mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4449                         btrfs_release_path(path);
4450                         break;
4451                 }
4452
4453                 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
4454                 btrfs_release_path(path);
4455
4456                 /*
4457                  * We may be relocating the only data chunk we have,
4458                  * which could potentially end up with losing data's
4459                  * raid profile, so lets allocate an empty one in
4460                  * advance.
4461                  */
4462                 ret = btrfs_may_alloc_data_chunk(fs_info, chunk_offset);
4463                 if (ret < 0) {
4464                         mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4465                         goto done;
4466                 }
4467
4468                 ret = btrfs_relocate_chunk(fs_info, chunk_offset);
4469                 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4470                 if (ret && ret != -ENOSPC)
4471                         goto done;
4472                 if (ret == -ENOSPC)
4473                         failed++;
4474         } while (key.offset-- > 0);
4475
4476         if (failed && !retried) {
4477                 failed = 0;
4478                 retried = true;
4479                 goto again;
4480         } else if (failed && retried) {
4481                 ret = -ENOSPC;
4482                 goto done;
4483         }
4484
4485         /* Shrinking succeeded, else we would be at "done". */
4486         trans = btrfs_start_transaction(root, 0);
4487         if (IS_ERR(trans)) {
4488                 ret = PTR_ERR(trans);
4489                 goto done;
4490         }
4491
4492         mutex_lock(&fs_info->chunk_mutex);
4493
4494         /*
4495          * We checked in the above loop all device extents that were already in
4496          * the device tree. However before we have updated the device's
4497          * total_bytes to the new size, we might have had chunk allocations that
4498          * have not complete yet (new block groups attached to transaction
4499          * handles), and therefore their device extents were not yet in the
4500          * device tree and we missed them in the loop above. So if we have any
4501          * pending chunk using a device extent that overlaps the device range
4502          * that we can not use anymore, commit the current transaction and
4503          * repeat the search on the device tree - this way we guarantee we will
4504          * not have chunks using device extents that end beyond 'new_size'.
4505          */
4506         if (!checked_pending_chunks) {
4507                 u64 start = new_size;
4508                 u64 len = old_size - new_size;
4509
4510                 if (contains_pending_extent(trans->transaction, device,
4511                                             &start, len)) {
4512                         mutex_unlock(&fs_info->chunk_mutex);
4513                         checked_pending_chunks = true;
4514                         failed = 0;
4515                         retried = false;
4516                         ret = btrfs_commit_transaction(trans);
4517                         if (ret)
4518                                 goto done;
4519                         goto again;
4520                 }
4521         }
4522
4523         btrfs_device_set_disk_total_bytes(device, new_size);
4524         if (list_empty(&device->resized_list))
4525                 list_add_tail(&device->resized_list,
4526                               &fs_info->fs_devices->resized_devices);
4527
4528         WARN_ON(diff > old_total);
4529         btrfs_set_super_total_bytes(super_copy,
4530                         round_down(old_total - diff, fs_info->sectorsize));
4531         mutex_unlock(&fs_info->chunk_mutex);
4532
4533         /* Now btrfs_update_device() will change the on-disk size. */
4534         ret = btrfs_update_device(trans, device);
4535         if (ret < 0) {
4536                 btrfs_abort_transaction(trans, ret);
4537                 btrfs_end_transaction(trans);
4538         } else {
4539                 ret = btrfs_commit_transaction(trans);
4540         }
4541 done:
4542         btrfs_free_path(path);
4543         if (ret) {
4544                 mutex_lock(&fs_info->chunk_mutex);
4545                 btrfs_device_set_total_bytes(device, old_size);
4546                 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
4547                         device->fs_devices->total_rw_bytes += diff;
4548                 atomic64_add(diff, &fs_info->free_chunk_space);
4549                 mutex_unlock(&fs_info->chunk_mutex);
4550         }
4551         return ret;
4552 }
4553
4554 static int btrfs_add_system_chunk(struct btrfs_fs_info *fs_info,
4555                            struct btrfs_key *key,
4556                            struct btrfs_chunk *chunk, int item_size)
4557 {
4558         struct btrfs_super_block *super_copy = fs_info->super_copy;
4559         struct btrfs_disk_key disk_key;
4560         u32 array_size;
4561         u8 *ptr;
4562
4563         mutex_lock(&fs_info->chunk_mutex);
4564         array_size = btrfs_super_sys_array_size(super_copy);
4565         if (array_size + item_size + sizeof(disk_key)
4566                         > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
4567                 mutex_unlock(&fs_info->chunk_mutex);
4568                 return -EFBIG;
4569         }
4570
4571         ptr = super_copy->sys_chunk_array + array_size;
4572         btrfs_cpu_key_to_disk(&disk_key, key);
4573         memcpy(ptr, &disk_key, sizeof(disk_key));
4574         ptr += sizeof(disk_key);
4575         memcpy(ptr, chunk, item_size);
4576         item_size += sizeof(disk_key);
4577         btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
4578         mutex_unlock(&fs_info->chunk_mutex);
4579
4580         return 0;
4581 }
4582
4583 /*
4584  * sort the devices in descending order by max_avail, total_avail
4585  */
4586 static int btrfs_cmp_device_info(const void *a, const void *b)
4587 {
4588         const struct btrfs_device_info *di_a = a;
4589         const struct btrfs_device_info *di_b = b;
4590
4591         if (di_a->max_avail > di_b->max_avail)
4592                 return -1;
4593         if (di_a->max_avail < di_b->max_avail)
4594                 return 1;
4595         if (di_a->total_avail > di_b->total_avail)
4596                 return -1;
4597         if (di_a->total_avail < di_b->total_avail)
4598                 return 1;
4599         return 0;
4600 }
4601
4602 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
4603 {
4604         if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
4605                 return;
4606
4607         btrfs_set_fs_incompat(info, RAID56);
4608 }
4609
4610 static int __btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
4611                                u64 start, u64 type)
4612 {
4613         struct btrfs_fs_info *info = trans->fs_info;
4614         struct btrfs_fs_devices *fs_devices = info->fs_devices;
4615         struct btrfs_device *device;
4616         struct map_lookup *map = NULL;
4617         struct extent_map_tree *em_tree;
4618         struct extent_map *em;
4619         struct btrfs_device_info *devices_info = NULL;
4620         u64 total_avail;
4621         int num_stripes;        /* total number of stripes to allocate */
4622         int data_stripes;       /* number of stripes that count for
4623                                    block group size */
4624         int sub_stripes;        /* sub_stripes info for map */
4625         int dev_stripes;        /* stripes per dev */
4626         int devs_max;           /* max devs to use */
4627         int devs_min;           /* min devs needed */
4628         int devs_increment;     /* ndevs has to be a multiple of this */
4629         int ncopies;            /* how many copies to data has */
4630         int ret;
4631         u64 max_stripe_size;
4632         u64 max_chunk_size;
4633         u64 stripe_size;
4634         u64 num_bytes;
4635         int ndevs;
4636         int i;
4637         int j;
4638         int index;
4639
4640         BUG_ON(!alloc_profile_is_valid(type, 0));
4641
4642         if (list_empty(&fs_devices->alloc_list)) {
4643                 if (btrfs_test_opt(info, ENOSPC_DEBUG))
4644                         btrfs_debug(info, "%s: no writable device", __func__);
4645                 return -ENOSPC;
4646         }
4647
4648         index = btrfs_bg_flags_to_raid_index(type);
4649
4650         sub_stripes = btrfs_raid_array[index].sub_stripes;
4651         dev_stripes = btrfs_raid_array[index].dev_stripes;
4652         devs_max = btrfs_raid_array[index].devs_max;
4653         devs_min = btrfs_raid_array[index].devs_min;
4654         devs_increment = btrfs_raid_array[index].devs_increment;
4655         ncopies = btrfs_raid_array[index].ncopies;
4656
4657         if (type & BTRFS_BLOCK_GROUP_DATA) {
4658                 max_stripe_size = SZ_1G;
4659                 max_chunk_size = BTRFS_MAX_DATA_CHUNK_SIZE;
4660                 if (!devs_max)
4661                         devs_max = BTRFS_MAX_DEVS(info);
4662         } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
4663                 /* for larger filesystems, use larger metadata chunks */
4664                 if (fs_devices->total_rw_bytes > 50ULL * SZ_1G)
4665                         max_stripe_size = SZ_1G;
4666                 else
4667                         max_stripe_size = SZ_256M;
4668                 max_chunk_size = max_stripe_size;
4669                 if (!devs_max)
4670                         devs_max = BTRFS_MAX_DEVS(info);
4671         } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
4672                 max_stripe_size = SZ_32M;
4673                 max_chunk_size = 2 * max_stripe_size;
4674                 if (!devs_max)
4675                         devs_max = BTRFS_MAX_DEVS_SYS_CHUNK;
4676         } else {
4677                 btrfs_err(info, "invalid chunk type 0x%llx requested",
4678                        type);
4679                 BUG_ON(1);
4680         }
4681
4682         /* we don't want a chunk larger than 10% of writeable space */
4683         max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
4684                              max_chunk_size);
4685
4686         devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
4687                                GFP_NOFS);
4688         if (!devices_info)
4689                 return -ENOMEM;
4690
4691         /*
4692          * in the first pass through the devices list, we gather information
4693          * about the available holes on each device.
4694          */
4695         ndevs = 0;
4696         list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
4697                 u64 max_avail;
4698                 u64 dev_offset;
4699
4700                 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4701                         WARN(1, KERN_ERR
4702                                "BTRFS: read-only device in alloc_list\n");
4703                         continue;
4704                 }
4705
4706                 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
4707                                         &device->dev_state) ||
4708                     test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4709                         continue;
4710
4711                 if (device->total_bytes > device->bytes_used)
4712                         total_avail = device->total_bytes - device->bytes_used;
4713                 else
4714                         total_avail = 0;
4715
4716                 /* If there is no space on this device, skip it. */
4717                 if (total_avail == 0)
4718                         continue;
4719
4720                 ret = find_free_dev_extent(trans, device,
4721                                            max_stripe_size * dev_stripes,
4722                                            &dev_offset, &max_avail);
4723                 if (ret && ret != -ENOSPC)
4724                         goto error;
4725
4726                 if (ret == 0)
4727                         max_avail = max_stripe_size * dev_stripes;
4728
4729                 if (max_avail < BTRFS_STRIPE_LEN * dev_stripes) {
4730                         if (btrfs_test_opt(info, ENOSPC_DEBUG))
4731                                 btrfs_debug(info,
4732                         "%s: devid %llu has no free space, have=%llu want=%u",
4733                                             __func__, device->devid, max_avail,
4734                                             BTRFS_STRIPE_LEN * dev_stripes);
4735                         continue;
4736                 }
4737
4738                 if (ndevs == fs_devices->rw_devices) {
4739                         WARN(1, "%s: found more than %llu devices\n",
4740                              __func__, fs_devices->rw_devices);
4741                         break;
4742                 }
4743                 devices_info[ndevs].dev_offset = dev_offset;
4744                 devices_info[ndevs].max_avail = max_avail;
4745                 devices_info[ndevs].total_avail = total_avail;
4746                 devices_info[ndevs].dev = device;
4747                 ++ndevs;
4748         }
4749
4750         /*
4751          * now sort the devices by hole size / available space
4752          */
4753         sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
4754              btrfs_cmp_device_info, NULL);
4755
4756         /* round down to number of usable stripes */
4757         ndevs = round_down(ndevs, devs_increment);
4758
4759         if (ndevs < devs_min) {
4760                 ret = -ENOSPC;
4761                 if (btrfs_test_opt(info, ENOSPC_DEBUG)) {
4762                         btrfs_debug(info,
4763         "%s: not enough devices with free space: have=%d minimum required=%d",
4764                                     __func__, ndevs, devs_min);
4765                 }
4766                 goto error;
4767         }
4768
4769         ndevs = min(ndevs, devs_max);
4770
4771         /*
4772          * The primary goal is to maximize the number of stripes, so use as
4773          * many devices as possible, even if the stripes are not maximum sized.
4774          *
4775          * The DUP profile stores more than one stripe per device, the
4776          * max_avail is the total size so we have to adjust.
4777          */
4778         stripe_size = div_u64(devices_info[ndevs - 1].max_avail, dev_stripes);
4779         num_stripes = ndevs * dev_stripes;
4780
4781         /*
4782          * this will have to be fixed for RAID1 and RAID10 over
4783          * more drives
4784          */
4785         data_stripes = num_stripes / ncopies;
4786
4787         if (type & BTRFS_BLOCK_GROUP_RAID5)
4788                 data_stripes = num_stripes - 1;
4789
4790         if (type & BTRFS_BLOCK_GROUP_RAID6)
4791                 data_stripes = num_stripes - 2;
4792
4793         /*
4794          * Use the number of data stripes to figure out how big this chunk
4795          * is really going to be in terms of logical address space,
4796          * and compare that answer with the max chunk size. If it's higher,
4797          * we try to reduce stripe_size.
4798          */
4799         if (stripe_size * data_stripes > max_chunk_size) {
4800                 /*
4801                  * Reduce stripe_size, round it up to a 16MB boundary again and
4802                  * then use it, unless it ends up being even bigger than the
4803                  * previous value we had already.
4804                  */
4805                 stripe_size = min(round_up(div_u64(max_chunk_size,
4806                                                    data_stripes), SZ_16M),
4807                                   stripe_size);
4808         }
4809
4810         /* align to BTRFS_STRIPE_LEN */
4811         stripe_size = round_down(stripe_size, BTRFS_STRIPE_LEN);
4812
4813         map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
4814         if (!map) {
4815                 ret = -ENOMEM;
4816                 goto error;
4817         }
4818         map->num_stripes = num_stripes;
4819
4820         for (i = 0; i < ndevs; ++i) {
4821                 for (j = 0; j < dev_stripes; ++j) {
4822                         int s = i * dev_stripes + j;
4823                         map->stripes[s].dev = devices_info[i].dev;
4824                         map->stripes[s].physical = devices_info[i].dev_offset +
4825                                                    j * stripe_size;
4826                 }
4827         }
4828         map->stripe_len = BTRFS_STRIPE_LEN;
4829         map->io_align = BTRFS_STRIPE_LEN;
4830         map->io_width = BTRFS_STRIPE_LEN;
4831         map->type = type;
4832         map->sub_stripes = sub_stripes;
4833
4834         num_bytes = stripe_size * data_stripes;
4835
4836         trace_btrfs_chunk_alloc(info, map, start, num_bytes);
4837
4838         em = alloc_extent_map();
4839         if (!em) {
4840                 kfree(map);
4841                 ret = -ENOMEM;
4842                 goto error;
4843         }
4844         set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
4845         em->map_lookup = map;
4846         em->start = start;
4847         em->len = num_bytes;
4848         em->block_start = 0;
4849         em->block_len = em->len;
4850         em->orig_block_len = stripe_size;
4851
4852         em_tree = &info->mapping_tree.map_tree;
4853         write_lock(&em_tree->lock);
4854         ret = add_extent_mapping(em_tree, em, 0);
4855         if (ret) {
4856                 write_unlock(&em_tree->lock);
4857                 free_extent_map(em);
4858                 goto error;
4859         }
4860
4861         list_add_tail(&em->list, &trans->transaction->pending_chunks);
4862         refcount_inc(&em->refs);
4863         write_unlock(&em_tree->lock);
4864
4865         ret = btrfs_make_block_group(trans, 0, type, start, num_bytes);
4866         if (ret)
4867                 goto error_del_extent;
4868
4869         for (i = 0; i < map->num_stripes; i++) {
4870                 num_bytes = map->stripes[i].dev->bytes_used + stripe_size;
4871                 btrfs_device_set_bytes_used(map->stripes[i].dev, num_bytes);
4872                 map->stripes[i].dev->has_pending_chunks = true;
4873         }
4874
4875         atomic64_sub(stripe_size * map->num_stripes, &info->free_chunk_space);
4876
4877         free_extent_map(em);
4878         check_raid56_incompat_flag(info, type);
4879
4880         kfree(devices_info);
4881         return 0;
4882
4883 error_del_extent:
4884         write_lock(&em_tree->lock);
4885         remove_extent_mapping(em_tree, em);
4886         write_unlock(&em_tree->lock);
4887
4888         /* One for our allocation */
4889         free_extent_map(em);
4890         /* One for the tree reference */
4891         free_extent_map(em);
4892         /* One for the pending_chunks list reference */
4893         free_extent_map(em);
4894 error:
4895         kfree(devices_info);
4896         return ret;
4897 }
4898
4899 int btrfs_finish_chunk_alloc(struct btrfs_trans_handle *trans,
4900                              u64 chunk_offset, u64 chunk_size)
4901 {
4902         struct btrfs_fs_info *fs_info = trans->fs_info;
4903         struct btrfs_root *extent_root = fs_info->extent_root;
4904         struct btrfs_root *chunk_root = fs_info->chunk_root;
4905         struct btrfs_key key;
4906         struct btrfs_device *device;
4907         struct btrfs_chunk *chunk;
4908         struct btrfs_stripe *stripe;
4909         struct extent_map *em;
4910         struct map_lookup *map;
4911         size_t item_size;
4912         u64 dev_offset;
4913         u64 stripe_size;
4914         int i = 0;
4915         int ret = 0;
4916
4917         em = get_chunk_map(fs_info, chunk_offset, chunk_size);
4918         if (IS_ERR(em))
4919                 return PTR_ERR(em);
4920
4921         map = em->map_lookup;
4922         item_size = btrfs_chunk_item_size(map->num_stripes);
4923         stripe_size = em->orig_block_len;
4924
4925         chunk = kzalloc(item_size, GFP_NOFS);
4926         if (!chunk) {
4927                 ret = -ENOMEM;
4928                 goto out;
4929         }
4930
4931         /*
4932          * Take the device list mutex to prevent races with the final phase of
4933          * a device replace operation that replaces the device object associated
4934          * with the map's stripes, because the device object's id can change
4935          * at any time during that final phase of the device replace operation
4936          * (dev-replace.c:btrfs_dev_replace_finishing()).
4937          */
4938         mutex_lock(&fs_info->fs_devices->device_list_mutex);
4939         for (i = 0; i < map->num_stripes; i++) {
4940                 device = map->stripes[i].dev;
4941                 dev_offset = map->stripes[i].physical;
4942
4943                 ret = btrfs_update_device(trans, device);
4944                 if (ret)
4945                         break;
4946                 ret = btrfs_alloc_dev_extent(trans, device, chunk_offset,
4947                                              dev_offset, stripe_size);
4948                 if (ret)
4949                         break;
4950         }
4951         if (ret) {
4952                 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4953                 goto out;
4954         }
4955
4956         stripe = &chunk->stripe;
4957         for (i = 0; i < map->num_stripes; i++) {
4958                 device = map->stripes[i].dev;
4959                 dev_offset = map->stripes[i].physical;
4960
4961                 btrfs_set_stack_stripe_devid(stripe, device->devid);
4962                 btrfs_set_stack_stripe_offset(stripe, dev_offset);
4963                 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
4964                 stripe++;
4965         }
4966         mutex_unlock(&fs_info->fs_devices->device_list_mutex);
4967
4968         btrfs_set_stack_chunk_length(chunk, chunk_size);
4969         btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
4970         btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
4971         btrfs_set_stack_chunk_type(chunk, map->type);
4972         btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
4973         btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
4974         btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
4975         btrfs_set_stack_chunk_sector_size(chunk, fs_info->sectorsize);
4976         btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
4977
4978         key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
4979         key.type = BTRFS_CHUNK_ITEM_KEY;
4980         key.offset = chunk_offset;
4981
4982         ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
4983         if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
4984                 /*
4985                  * TODO: Cleanup of inserted chunk root in case of
4986                  * failure.
4987                  */
4988                 ret = btrfs_add_system_chunk(fs_info, &key, chunk, item_size);
4989         }
4990
4991 out:
4992         kfree(chunk);
4993         free_extent_map(em);
4994         return ret;
4995 }
4996
4997 /*
4998  * Chunk allocation falls into two parts. The first part does works
4999  * that make the new allocated chunk useable, but not do any operation
5000  * that modifies the chunk tree. The second part does the works that
5001  * require modifying the chunk tree. This division is important for the
5002  * bootstrap process of adding storage to a seed btrfs.
5003  */
5004 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans, u64 type)
5005 {
5006         u64 chunk_offset;
5007
5008         lockdep_assert_held(&trans->fs_info->chunk_mutex);
5009         chunk_offset = find_next_chunk(trans->fs_info);
5010         return __btrfs_alloc_chunk(trans, chunk_offset, type);
5011 }
5012
5013 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans,
5014                                          struct btrfs_fs_info *fs_info)
5015 {
5016         u64 chunk_offset;
5017         u64 sys_chunk_offset;
5018         u64 alloc_profile;
5019         int ret;
5020
5021         chunk_offset = find_next_chunk(fs_info);
5022         alloc_profile = btrfs_metadata_alloc_profile(fs_info);
5023         ret = __btrfs_alloc_chunk(trans, chunk_offset, alloc_profile);
5024         if (ret)
5025                 return ret;
5026
5027         sys_chunk_offset = find_next_chunk(fs_info);
5028         alloc_profile = btrfs_system_alloc_profile(fs_info);
5029         ret = __btrfs_alloc_chunk(trans, sys_chunk_offset, alloc_profile);
5030         return ret;
5031 }
5032
5033 static inline int btrfs_chunk_max_errors(struct map_lookup *map)
5034 {
5035         int max_errors;
5036
5037         if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
5038                          BTRFS_BLOCK_GROUP_RAID10 |
5039                          BTRFS_BLOCK_GROUP_RAID5)) {
5040                 max_errors = 1;
5041         } else if (map->type & BTRFS_BLOCK_GROUP_RAID6) {
5042                 max_errors = 2;
5043         } else {
5044                 max_errors = 0;
5045         }
5046
5047         return max_errors;
5048 }
5049
5050 int btrfs_chunk_readonly(struct btrfs_fs_info *fs_info, u64 chunk_offset)
5051 {
5052         struct extent_map *em;
5053         struct map_lookup *map;
5054         int readonly = 0;
5055         int miss_ndevs = 0;
5056         int i;
5057
5058         em = get_chunk_map(fs_info, chunk_offset, 1);
5059         if (IS_ERR(em))
5060                 return 1;
5061
5062         map = em->map_lookup;
5063         for (i = 0; i < map->num_stripes; i++) {
5064                 if (test_bit(BTRFS_DEV_STATE_MISSING,
5065                                         &map->stripes[i].dev->dev_state)) {
5066                         miss_ndevs++;
5067                         continue;
5068                 }
5069                 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE,
5070                                         &map->stripes[i].dev->dev_state)) {
5071                         readonly = 1;
5072                         goto end;
5073                 }
5074         }
5075
5076         /*
5077          * If the number of missing devices is larger than max errors,
5078          * we can not write the data into that chunk successfully, so
5079          * set it readonly.
5080          */
5081         if (miss_ndevs > btrfs_chunk_max_errors(map))
5082                 readonly = 1;
5083 end:
5084         free_extent_map(em);
5085         return readonly;
5086 }
5087
5088 void btrfs_mapping_init(struct btrfs_mapping_tree *tree)
5089 {
5090         extent_map_tree_init(&tree->map_tree);
5091 }
5092
5093 void btrfs_mapping_tree_free(struct btrfs_mapping_tree *tree)
5094 {
5095         struct extent_map *em;
5096
5097         while (1) {
5098                 write_lock(&tree->map_tree.lock);
5099                 em = lookup_extent_mapping(&tree->map_tree, 0, (u64)-1);
5100                 if (em)
5101                         remove_extent_mapping(&tree->map_tree, em);
5102                 write_unlock(&tree->map_tree.lock);
5103                 if (!em)
5104                         break;
5105                 /* once for us */
5106                 free_extent_map(em);
5107                 /* once for the tree */
5108                 free_extent_map(em);
5109         }
5110 }
5111
5112 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5113 {
5114         struct extent_map *em;
5115         struct map_lookup *map;
5116         int ret;
5117
5118         em = get_chunk_map(fs_info, logical, len);
5119         if (IS_ERR(em))
5120                 /*
5121                  * We could return errors for these cases, but that could get
5122                  * ugly and we'd probably do the same thing which is just not do
5123                  * anything else and exit, so return 1 so the callers don't try
5124                  * to use other copies.
5125                  */
5126                 return 1;
5127
5128         map = em->map_lookup;
5129         if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
5130                 ret = map->num_stripes;
5131         else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5132                 ret = map->sub_stripes;
5133         else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
5134                 ret = 2;
5135         else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5136                 /*
5137                  * There could be two corrupted data stripes, we need
5138                  * to loop retry in order to rebuild the correct data.
5139                  *
5140                  * Fail a stripe at a time on every retry except the
5141                  * stripe under reconstruction.
5142                  */
5143                 ret = map->num_stripes;
5144         else
5145                 ret = 1;
5146         free_extent_map(em);
5147
5148         btrfs_dev_replace_read_lock(&fs_info->dev_replace);
5149         if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace) &&
5150             fs_info->dev_replace.tgtdev)
5151                 ret++;
5152         btrfs_dev_replace_read_unlock(&fs_info->dev_replace);
5153
5154         return ret;
5155 }
5156
5157 unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
5158                                     u64 logical)
5159 {
5160         struct extent_map *em;
5161         struct map_lookup *map;
5162         unsigned long len = fs_info->sectorsize;
5163
5164         em = get_chunk_map(fs_info, logical, len);
5165
5166         if (!WARN_ON(IS_ERR(em))) {
5167                 map = em->map_lookup;
5168                 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5169                         len = map->stripe_len * nr_data_stripes(map);
5170                 free_extent_map(em);
5171         }
5172         return len;
5173 }
5174
5175 int btrfs_is_parity_mirror(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5176 {
5177         struct extent_map *em;
5178         struct map_lookup *map;
5179         int ret = 0;
5180
5181         em = get_chunk_map(fs_info, logical, len);
5182
5183         if(!WARN_ON(IS_ERR(em))) {
5184                 map = em->map_lookup;
5185                 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5186                         ret = 1;
5187                 free_extent_map(em);
5188         }
5189         return ret;
5190 }
5191
5192 static int find_live_mirror(struct btrfs_fs_info *fs_info,
5193                             struct map_lookup *map, int first,
5194                             int dev_replace_is_ongoing)
5195 {
5196         int i;
5197         int num_stripes;
5198         int preferred_mirror;
5199         int tolerance;
5200         struct btrfs_device *srcdev;
5201
5202         ASSERT((map->type &
5203                  (BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)));
5204
5205         if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5206                 num_stripes = map->sub_stripes;
5207         else
5208                 num_stripes = map->num_stripes;
5209
5210         preferred_mirror = first + current->pid % num_stripes;
5211
5212         if (dev_replace_is_ongoing &&
5213             fs_info->dev_replace.cont_reading_from_srcdev_mode ==
5214              BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
5215                 srcdev = fs_info->dev_replace.srcdev;
5216         else
5217                 srcdev = NULL;
5218
5219         /*
5220          * try to avoid the drive that is the source drive for a
5221          * dev-replace procedure, only choose it if no other non-missing
5222          * mirror is available
5223          */
5224         for (tolerance = 0; tolerance < 2; tolerance++) {
5225                 if (map->stripes[preferred_mirror].dev->bdev &&
5226                     (tolerance || map->stripes[preferred_mirror].dev != srcdev))
5227                         return preferred_mirror;
5228                 for (i = first; i < first + num_stripes; i++) {
5229                         if (map->stripes[i].dev->bdev &&
5230                             (tolerance || map->stripes[i].dev != srcdev))
5231                                 return i;
5232                 }
5233         }
5234
5235         /* we couldn't find one that doesn't fail.  Just return something
5236          * and the io error handling code will clean up eventually
5237          */
5238         return preferred_mirror;
5239 }
5240
5241 static inline int parity_smaller(u64 a, u64 b)
5242 {
5243         return a > b;
5244 }
5245
5246 /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
5247 static void sort_parity_stripes(struct btrfs_bio *bbio, int num_stripes)
5248 {
5249         struct btrfs_bio_stripe s;
5250         int i;
5251         u64 l;
5252         int again = 1;
5253
5254         while (again) {
5255                 again = 0;
5256                 for (i = 0; i < num_stripes - 1; i++) {
5257                         if (parity_smaller(bbio->raid_map[i],
5258                                            bbio->raid_map[i+1])) {
5259                                 s = bbio->stripes[i];
5260                                 l = bbio->raid_map[i];
5261                                 bbio->stripes[i] = bbio->stripes[i+1];
5262                                 bbio->raid_map[i] = bbio->raid_map[i+1];
5263                                 bbio->stripes[i+1] = s;
5264                                 bbio->raid_map[i+1] = l;
5265
5266                                 again = 1;
5267                         }
5268                 }
5269         }
5270 }
5271
5272 static struct btrfs_bio *alloc_btrfs_bio(int total_stripes, int real_stripes)
5273 {
5274         struct btrfs_bio *bbio = kzalloc(
5275                  /* the size of the btrfs_bio */
5276                 sizeof(struct btrfs_bio) +
5277                 /* plus the variable array for the stripes */
5278                 sizeof(struct btrfs_bio_stripe) * (total_stripes) +
5279                 /* plus the variable array for the tgt dev */
5280                 sizeof(int) * (real_stripes) +
5281                 /*
5282                  * plus the raid_map, which includes both the tgt dev
5283                  * and the stripes
5284                  */
5285                 sizeof(u64) * (total_stripes),
5286                 GFP_NOFS|__GFP_NOFAIL);
5287
5288         atomic_set(&bbio->error, 0);
5289         refcount_set(&bbio->refs, 1);
5290
5291         return bbio;
5292 }
5293
5294 void btrfs_get_bbio(struct btrfs_bio *bbio)
5295 {
5296         WARN_ON(!refcount_read(&bbio->refs));
5297         refcount_inc(&bbio->refs);
5298 }
5299
5300 void btrfs_put_bbio(struct btrfs_bio *bbio)
5301 {
5302         if (!bbio)
5303                 return;
5304         if (refcount_dec_and_test(&bbio->refs))
5305                 kfree(bbio);
5306 }
5307
5308 /* can REQ_OP_DISCARD be sent with other REQ like REQ_OP_WRITE? */
5309 /*
5310  * Please note that, discard won't be sent to target device of device
5311  * replace.
5312  */
5313 static int __btrfs_map_block_for_discard(struct btrfs_fs_info *fs_info,
5314                                          u64 logical, u64 length,
5315                                          struct btrfs_bio **bbio_ret)
5316 {
5317         struct extent_map *em;
5318         struct map_lookup *map;
5319         struct btrfs_bio *bbio;
5320         u64 offset;
5321         u64 stripe_nr;
5322         u64 stripe_nr_end;
5323         u64 stripe_end_offset;
5324         u64 stripe_cnt;
5325         u64 stripe_len;
5326         u64 stripe_offset;
5327         u64 num_stripes;
5328         u32 stripe_index;
5329         u32 factor = 0;
5330         u32 sub_stripes = 0;
5331         u64 stripes_per_dev = 0;
5332         u32 remaining_stripes = 0;
5333         u32 last_stripe = 0;
5334         int ret = 0;
5335         int i;
5336
5337         /* discard always return a bbio */
5338         ASSERT(bbio_ret);
5339
5340         em = get_chunk_map(fs_info, logical, length);
5341         if (IS_ERR(em))
5342                 return PTR_ERR(em);
5343
5344         map = em->map_lookup;
5345         /* we don't discard raid56 yet */
5346         if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5347                 ret = -EOPNOTSUPP;
5348                 goto out;
5349         }
5350
5351         offset = logical - em->start;
5352         length = min_t(u64, em->len - offset, length);
5353
5354         stripe_len = map->stripe_len;
5355         /*
5356          * stripe_nr counts the total number of stripes we have to stride
5357          * to get to this block
5358          */
5359         stripe_nr = div64_u64(offset, stripe_len);
5360
5361         /* stripe_offset is the offset of this block in its stripe */
5362         stripe_offset = offset - stripe_nr * stripe_len;
5363
5364         stripe_nr_end = round_up(offset + length, map->stripe_len);
5365         stripe_nr_end = div64_u64(stripe_nr_end, map->stripe_len);
5366         stripe_cnt = stripe_nr_end - stripe_nr;
5367         stripe_end_offset = stripe_nr_end * map->stripe_len -
5368                             (offset + length);
5369         /*
5370          * after this, stripe_nr is the number of stripes on this
5371          * device we have to walk to find the data, and stripe_index is
5372          * the number of our device in the stripe array
5373          */
5374         num_stripes = 1;
5375         stripe_index = 0;
5376         if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5377                          BTRFS_BLOCK_GROUP_RAID10)) {
5378                 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5379                         sub_stripes = 1;
5380                 else
5381                         sub_stripes = map->sub_stripes;
5382
5383                 factor = map->num_stripes / sub_stripes;
5384                 num_stripes = min_t(u64, map->num_stripes,
5385                                     sub_stripes * stripe_cnt);
5386                 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5387                 stripe_index *= sub_stripes;
5388                 stripes_per_dev = div_u64_rem(stripe_cnt, factor,
5389                                               &remaining_stripes);
5390                 div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
5391                 last_stripe *= sub_stripes;
5392         } else if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
5393                                 BTRFS_BLOCK_GROUP_DUP)) {
5394                 num_stripes = map->num_stripes;
5395         } else {
5396                 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5397                                         &stripe_index);
5398         }
5399
5400         bbio = alloc_btrfs_bio(num_stripes, 0);
5401         if (!bbio) {
5402                 ret = -ENOMEM;
5403                 goto out;
5404         }
5405
5406         for (i = 0; i < num_stripes; i++) {
5407                 bbio->stripes[i].physical =
5408                         map->stripes[stripe_index].physical +
5409                         stripe_offset + stripe_nr * map->stripe_len;
5410                 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
5411
5412                 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5413                                  BTRFS_BLOCK_GROUP_RAID10)) {
5414                         bbio->stripes[i].length = stripes_per_dev *
5415                                 map->stripe_len;
5416
5417                         if (i / sub_stripes < remaining_stripes)
5418                                 bbio->stripes[i].length +=
5419                                         map->stripe_len;
5420
5421                         /*
5422                          * Special for the first stripe and
5423                          * the last stripe:
5424                          *
5425                          * |-------|...|-------|
5426                          *     |----------|
5427                          *    off     end_off
5428                          */
5429                         if (i < sub_stripes)
5430                                 bbio->stripes[i].length -=
5431                                         stripe_offset;
5432
5433                         if (stripe_index >= last_stripe &&
5434                             stripe_index <= (last_stripe +
5435                                              sub_stripes - 1))
5436                                 bbio->stripes[i].length -=
5437                                         stripe_end_offset;
5438
5439                         if (i == sub_stripes - 1)
5440                                 stripe_offset = 0;
5441                 } else {
5442                         bbio->stripes[i].length = length;
5443                 }
5444
5445                 stripe_index++;
5446                 if (stripe_index == map->num_stripes) {
5447                         stripe_index = 0;
5448                         stripe_nr++;
5449                 }
5450         }
5451
5452         *bbio_ret = bbio;
5453         bbio->map_type = map->type;
5454         bbio->num_stripes = num_stripes;
5455 out:
5456         free_extent_map(em);
5457         return ret;
5458 }
5459
5460 /*
5461  * In dev-replace case, for repair case (that's the only case where the mirror
5462  * is selected explicitly when calling btrfs_map_block), blocks left of the
5463  * left cursor can also be read from the target drive.
5464  *
5465  * For REQ_GET_READ_MIRRORS, the target drive is added as the last one to the
5466  * array of stripes.
5467  * For READ, it also needs to be supported using the same mirror number.
5468  *
5469  * If the requested block is not left of the left cursor, EIO is returned. This
5470  * can happen because btrfs_num_copies() returns one more in the dev-replace
5471  * case.
5472  */
5473 static int get_extra_mirror_from_replace(struct btrfs_fs_info *fs_info,
5474                                          u64 logical, u64 length,
5475                                          u64 srcdev_devid, int *mirror_num,
5476                                          u64 *physical)
5477 {
5478         struct btrfs_bio *bbio = NULL;
5479         int num_stripes;
5480         int index_srcdev = 0;
5481         int found = 0;
5482         u64 physical_of_found = 0;
5483         int i;
5484         int ret = 0;
5485
5486         ret = __btrfs_map_block(fs_info, BTRFS_MAP_GET_READ_MIRRORS,
5487                                 logical, &length, &bbio, 0, 0);
5488         if (ret) {
5489                 ASSERT(bbio == NULL);
5490                 return ret;
5491         }
5492
5493         num_stripes = bbio->num_stripes;
5494         if (*mirror_num > num_stripes) {
5495                 /*
5496                  * BTRFS_MAP_GET_READ_MIRRORS does not contain this mirror,
5497                  * that means that the requested area is not left of the left
5498                  * cursor
5499                  */
5500                 btrfs_put_bbio(bbio);
5501                 return -EIO;
5502         }
5503
5504         /*
5505          * process the rest of the function using the mirror_num of the source
5506          * drive. Therefore look it up first.  At the end, patch the device
5507          * pointer to the one of the target drive.
5508          */
5509         for (i = 0; i < num_stripes; i++) {
5510                 if (bbio->stripes[i].dev->devid != srcdev_devid)
5511                         continue;
5512
5513                 /*
5514                  * In case of DUP, in order to keep it simple, only add the
5515                  * mirror with the lowest physical address
5516                  */
5517                 if (found &&
5518                     physical_of_found <= bbio->stripes[i].physical)
5519                         continue;
5520
5521                 index_srcdev = i;
5522                 found = 1;
5523                 physical_of_found = bbio->stripes[i].physical;
5524         }
5525
5526         btrfs_put_bbio(bbio);
5527
5528         ASSERT(found);
5529         if (!found)
5530                 return -EIO;
5531
5532         *mirror_num = index_srcdev + 1;
5533         *physical = physical_of_found;
5534         return ret;
5535 }
5536
5537 static void handle_ops_on_dev_replace(enum btrfs_map_op op,
5538                                       struct btrfs_bio **bbio_ret,
5539                                       struct btrfs_dev_replace *dev_replace,
5540                                       int *num_stripes_ret, int *max_errors_ret)
5541 {
5542         struct btrfs_bio *bbio = *bbio_ret;
5543         u64 srcdev_devid = dev_replace->srcdev->devid;
5544         int tgtdev_indexes = 0;
5545         int num_stripes = *num_stripes_ret;
5546         int max_errors = *max_errors_ret;
5547         int i;
5548
5549         if (op == BTRFS_MAP_WRITE) {
5550                 int index_where_to_add;
5551
5552                 /*
5553                  * duplicate the write operations while the dev replace
5554                  * procedure is running. Since the copying of the old disk to
5555                  * the new disk takes place at run time while the filesystem is
5556                  * mounted writable, the regular write operations to the old
5557                  * disk have to be duplicated to go to the new disk as well.
5558                  *
5559                  * Note that device->missing is handled by the caller, and that
5560                  * the write to the old disk is already set up in the stripes
5561                  * array.
5562                  */
5563                 index_where_to_add = num_stripes;
5564                 for (i = 0; i < num_stripes; i++) {
5565                         if (bbio->stripes[i].dev->devid == srcdev_devid) {
5566                                 /* write to new disk, too */
5567                                 struct btrfs_bio_stripe *new =
5568                                         bbio->stripes + index_where_to_add;
5569                                 struct btrfs_bio_stripe *old =
5570                                         bbio->stripes + i;
5571
5572                                 new->physical = old->physical;
5573                                 new->length = old->length;
5574                                 new->dev = dev_replace->tgtdev;
5575                                 bbio->tgtdev_map[i] = index_where_to_add;
5576                                 index_where_to_add++;
5577                                 max_errors++;
5578                                 tgtdev_indexes++;
5579                         }
5580                 }
5581                 num_stripes = index_where_to_add;
5582         } else if (op == BTRFS_MAP_GET_READ_MIRRORS) {
5583                 int index_srcdev = 0;
5584                 int found = 0;
5585                 u64 physical_of_found = 0;
5586
5587                 /*
5588                  * During the dev-replace procedure, the target drive can also
5589                  * be used to read data in case it is needed to repair a corrupt
5590                  * block elsewhere. This is possible if the requested area is
5591                  * left of the left cursor. In this area, the target drive is a
5592                  * full copy of the source drive.
5593                  */
5594                 for (i = 0; i < num_stripes; i++) {
5595                         if (bbio->stripes[i].dev->devid == srcdev_devid) {
5596                                 /*
5597                                  * In case of DUP, in order to keep it simple,
5598                                  * only add the mirror with the lowest physical
5599                                  * address
5600                                  */
5601                                 if (found &&
5602                                     physical_of_found <=
5603                                      bbio->stripes[i].physical)
5604                                         continue;
5605                                 index_srcdev = i;
5606                                 found = 1;
5607                                 physical_of_found = bbio->stripes[i].physical;
5608                         }
5609                 }
5610                 if (found) {
5611                         struct btrfs_bio_stripe *tgtdev_stripe =
5612                                 bbio->stripes + num_stripes;
5613
5614                         tgtdev_stripe->physical = physical_of_found;
5615                         tgtdev_stripe->length =
5616                                 bbio->stripes[index_srcdev].length;
5617                         tgtdev_stripe->dev = dev_replace->tgtdev;
5618                         bbio->tgtdev_map[index_srcdev] = num_stripes;
5619
5620                         tgtdev_indexes++;
5621                         num_stripes++;
5622                 }
5623         }
5624
5625         *num_stripes_ret = num_stripes;
5626         *max_errors_ret = max_errors;
5627         bbio->num_tgtdevs = tgtdev_indexes;
5628         *bbio_ret = bbio;
5629 }
5630
5631 static bool need_full_stripe(enum btrfs_map_op op)
5632 {
5633         return (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS);
5634 }
5635
5636 static int __btrfs_map_block(struct btrfs_fs_info *fs_info,
5637                              enum btrfs_map_op op,
5638                              u64 logical, u64 *length,
5639                              struct btrfs_bio **bbio_ret,
5640                              int mirror_num, int need_raid_map)
5641 {
5642         struct extent_map *em;
5643         struct map_lookup *map;
5644         u64 offset;
5645         u64 stripe_offset;
5646         u64 stripe_nr;
5647         u64 stripe_len;
5648         u32 stripe_index;
5649         int i;
5650         int ret = 0;
5651         int num_stripes;
5652         int max_errors = 0;
5653         int tgtdev_indexes = 0;
5654         struct btrfs_bio *bbio = NULL;
5655         struct btrfs_dev_replace *dev_replace = &fs_info->dev_replace;
5656         int dev_replace_is_ongoing = 0;
5657         int num_alloc_stripes;
5658         int patch_the_first_stripe_for_dev_replace = 0;
5659         u64 physical_to_patch_in_first_stripe = 0;
5660         u64 raid56_full_stripe_start = (u64)-1;
5661
5662         if (op == BTRFS_MAP_DISCARD)
5663                 return __btrfs_map_block_for_discard(fs_info, logical,
5664                                                      *length, bbio_ret);
5665
5666         em = get_chunk_map(fs_info, logical, *length);
5667         if (IS_ERR(em))
5668                 return PTR_ERR(em);
5669
5670         map = em->map_lookup;
5671         offset = logical - em->start;
5672
5673         stripe_len = map->stripe_len;
5674         stripe_nr = offset;
5675         /*
5676          * stripe_nr counts the total number of stripes we have to stride
5677          * to get to this block
5678          */
5679         stripe_nr = div64_u64(stripe_nr, stripe_len);
5680
5681         stripe_offset = stripe_nr * stripe_len;
5682         if (offset < stripe_offset) {
5683                 btrfs_crit(fs_info,
5684                            "stripe math has gone wrong, stripe_offset=%llu, offset=%llu, start=%llu, logical=%llu, stripe_len=%llu",
5685                            stripe_offset, offset, em->start, logical,
5686                            stripe_len);
5687                 free_extent_map(em);
5688                 return -EINVAL;
5689         }
5690
5691         /* stripe_offset is the offset of this block in its stripe*/
5692         stripe_offset = offset - stripe_offset;
5693
5694         /* if we're here for raid56, we need to know the stripe aligned start */
5695         if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5696                 unsigned long full_stripe_len = stripe_len * nr_data_stripes(map);
5697                 raid56_full_stripe_start = offset;
5698
5699                 /* allow a write of a full stripe, but make sure we don't
5700                  * allow straddling of stripes
5701                  */
5702                 raid56_full_stripe_start = div64_u64(raid56_full_stripe_start,
5703                                 full_stripe_len);
5704                 raid56_full_stripe_start *= full_stripe_len;
5705         }
5706
5707         if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
5708                 u64 max_len;
5709                 /* For writes to RAID[56], allow a full stripeset across all disks.
5710                    For other RAID types and for RAID[56] reads, just allow a single
5711                    stripe (on a single disk). */
5712                 if ((map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
5713                     (op == BTRFS_MAP_WRITE)) {
5714                         max_len = stripe_len * nr_data_stripes(map) -
5715                                 (offset - raid56_full_stripe_start);
5716                 } else {
5717                         /* we limit the length of each bio to what fits in a stripe */
5718                         max_len = stripe_len - stripe_offset;
5719                 }
5720                 *length = min_t(u64, em->len - offset, max_len);
5721         } else {
5722                 *length = em->len - offset;
5723         }
5724
5725         /* This is for when we're called from btrfs_merge_bio_hook() and all
5726            it cares about is the length */
5727         if (!bbio_ret)
5728                 goto out;
5729
5730         btrfs_dev_replace_read_lock(dev_replace);
5731         dev_replace_is_ongoing = btrfs_dev_replace_is_ongoing(dev_replace);
5732         if (!dev_replace_is_ongoing)
5733                 btrfs_dev_replace_read_unlock(dev_replace);
5734         else
5735                 btrfs_dev_replace_set_lock_blocking(dev_replace);
5736
5737         if (dev_replace_is_ongoing && mirror_num == map->num_stripes + 1 &&
5738             !need_full_stripe(op) && dev_replace->tgtdev != NULL) {
5739                 ret = get_extra_mirror_from_replace(fs_info, logical, *length,
5740                                                     dev_replace->srcdev->devid,
5741                                                     &mirror_num,
5742                                             &physical_to_patch_in_first_stripe);
5743                 if (ret)
5744                         goto out;
5745                 else
5746                         patch_the_first_stripe_for_dev_replace = 1;
5747         } else if (mirror_num > map->num_stripes) {
5748                 mirror_num = 0;
5749         }
5750
5751         num_stripes = 1;
5752         stripe_index = 0;
5753         if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
5754                 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5755                                 &stripe_index);
5756                 if (!need_full_stripe(op))
5757                         mirror_num = 1;
5758         } else if (map->type & BTRFS_BLOCK_GROUP_RAID1) {
5759                 if (need_full_stripe(op))
5760                         num_stripes = map->num_stripes;
5761                 else if (mirror_num)
5762                         stripe_index = mirror_num - 1;
5763                 else {
5764                         stripe_index = find_live_mirror(fs_info, map, 0,
5765                                             dev_replace_is_ongoing);
5766                         mirror_num = stripe_index + 1;
5767                 }
5768
5769         } else if (map->type & BTRFS_BLOCK_GROUP_DUP) {
5770                 if (need_full_stripe(op)) {
5771                         num_stripes = map->num_stripes;
5772                 } else if (mirror_num) {
5773                         stripe_index = mirror_num - 1;
5774                 } else {
5775                         mirror_num = 1;
5776                 }
5777
5778         } else if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
5779                 u32 factor = map->num_stripes / map->sub_stripes;
5780
5781                 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5782                 stripe_index *= map->sub_stripes;
5783
5784                 if (need_full_stripe(op))
5785                         num_stripes = map->sub_stripes;
5786                 else if (mirror_num)
5787                         stripe_index += mirror_num - 1;
5788                 else {
5789                         int old_stripe_index = stripe_index;
5790                         stripe_index = find_live_mirror(fs_info, map,
5791                                               stripe_index,
5792                                               dev_replace_is_ongoing);
5793                         mirror_num = stripe_index - old_stripe_index + 1;
5794                 }
5795
5796         } else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5797                 if (need_raid_map && (need_full_stripe(op) || mirror_num > 1)) {
5798                         /* push stripe_nr back to the start of the full stripe */
5799                         stripe_nr = div64_u64(raid56_full_stripe_start,
5800                                         stripe_len * nr_data_stripes(map));
5801
5802                         /* RAID[56] write or recovery. Return all stripes */
5803                         num_stripes = map->num_stripes;
5804                         max_errors = nr_parity_stripes(map);
5805
5806                         *length = map->stripe_len;
5807                         stripe_index = 0;
5808                         stripe_offset = 0;
5809                 } else {
5810                         /*
5811                          * Mirror #0 or #1 means the original data block.
5812                          * Mirror #2 is RAID5 parity block.
5813                          * Mirror #3 is RAID6 Q block.
5814                          */
5815                         stripe_nr = div_u64_rem(stripe_nr,
5816                                         nr_data_stripes(map), &stripe_index);
5817                         if (mirror_num > 1)
5818                                 stripe_index = nr_data_stripes(map) +
5819                                                 mirror_num - 2;
5820
5821                         /* We distribute the parity blocks across stripes */
5822                         div_u64_rem(stripe_nr + stripe_index, map->num_stripes,
5823                                         &stripe_index);
5824                         if (!need_full_stripe(op) && mirror_num <= 1)
5825                                 mirror_num = 1;
5826                 }
5827         } else {
5828                 /*
5829                  * after this, stripe_nr is the number of stripes on this
5830                  * device we have to walk to find the data, and stripe_index is
5831                  * the number of our device in the stripe array
5832                  */
5833                 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5834                                 &stripe_index);
5835                 mirror_num = stripe_index + 1;
5836         }
5837         if (stripe_index >= map->num_stripes) {
5838                 btrfs_crit(fs_info,
5839                            "stripe index math went horribly wrong, got stripe_index=%u, num_stripes=%u",
5840                            stripe_index, map->num_stripes);
5841                 ret = -EINVAL;
5842                 goto out;
5843         }
5844
5845         num_alloc_stripes = num_stripes;
5846         if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL) {
5847                 if (op == BTRFS_MAP_WRITE)
5848                         num_alloc_stripes <<= 1;
5849                 if (op == BTRFS_MAP_GET_READ_MIRRORS)
5850                         num_alloc_stripes++;
5851                 tgtdev_indexes = num_stripes;
5852         }
5853
5854         bbio = alloc_btrfs_bio(num_alloc_stripes, tgtdev_indexes);
5855         if (!bbio) {
5856                 ret = -ENOMEM;
5857                 goto out;
5858         }
5859         if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL)
5860                 bbio->tgtdev_map = (int *)(bbio->stripes + num_alloc_stripes);
5861
5862         /* build raid_map */
5863         if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK && need_raid_map &&
5864             (need_full_stripe(op) || mirror_num > 1)) {
5865                 u64 tmp;
5866                 unsigned rot;
5867
5868                 bbio->raid_map = (u64 *)((void *)bbio->stripes +
5869                                  sizeof(struct btrfs_bio_stripe) *
5870                                  num_alloc_stripes +
5871                                  sizeof(int) * tgtdev_indexes);
5872
5873                 /* Work out the disk rotation on this stripe-set */
5874                 div_u64_rem(stripe_nr, num_stripes, &rot);
5875
5876                 /* Fill in the logical address of each stripe */
5877                 tmp = stripe_nr * nr_data_stripes(map);
5878                 for (i = 0; i < nr_data_stripes(map); i++)
5879                         bbio->raid_map[(i+rot) % num_stripes] =
5880                                 em->start + (tmp + i) * map->stripe_len;
5881
5882                 bbio->raid_map[(i+rot) % map->num_stripes] = RAID5_P_STRIPE;
5883                 if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5884                         bbio->raid_map[(i+rot+1) % num_stripes] =
5885                                 RAID6_Q_STRIPE;
5886         }
5887
5888
5889         for (i = 0; i < num_stripes; i++) {
5890                 bbio->stripes[i].physical =
5891                         map->stripes[stripe_index].physical +
5892                         stripe_offset +
5893                         stripe_nr * map->stripe_len;
5894                 bbio->stripes[i].dev =
5895                         map->stripes[stripe_index].dev;
5896                 stripe_index++;
5897         }
5898
5899         if (need_full_stripe(op))
5900                 max_errors = btrfs_chunk_max_errors(map);
5901
5902         if (bbio->raid_map)
5903                 sort_parity_stripes(bbio, num_stripes);
5904
5905         if (dev_replace_is_ongoing && dev_replace->tgtdev != NULL &&
5906             need_full_stripe(op)) {
5907                 handle_ops_on_dev_replace(op, &bbio, dev_replace, &num_stripes,
5908                                           &max_errors);
5909         }
5910
5911         *bbio_ret = bbio;
5912         bbio->map_type = map->type;
5913         bbio->num_stripes = num_stripes;
5914         bbio->max_errors = max_errors;
5915         bbio->mirror_num = mirror_num;
5916
5917         /*
5918          * this is the case that REQ_READ && dev_replace_is_ongoing &&
5919          * mirror_num == num_stripes + 1 && dev_replace target drive is
5920          * available as a mirror
5921          */
5922         if (patch_the_first_stripe_for_dev_replace && num_stripes > 0) {
5923                 WARN_ON(num_stripes > 1);
5924                 bbio->stripes[0].dev = dev_replace->tgtdev;
5925                 bbio->stripes[0].physical = physical_to_patch_in_first_stripe;
5926                 bbio->mirror_num = map->num_stripes + 1;
5927         }
5928 out:
5929         if (dev_replace_is_ongoing) {
5930                 btrfs_dev_replace_clear_lock_blocking(dev_replace);
5931                 btrfs_dev_replace_read_unlock(dev_replace);
5932         }
5933         free_extent_map(em);
5934         return ret;
5935 }
5936
5937 int btrfs_map_block(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
5938                       u64 logical, u64 *length,
5939                       struct btrfs_bio **bbio_ret, int mirror_num)
5940 {
5941         return __btrfs_map_block(fs_info, op, logical, length, bbio_ret,
5942                                  mirror_num, 0);
5943 }
5944
5945 /* For Scrub/replace */
5946 int btrfs_map_sblock(struct btrfs_fs_info *fs_info, enum btrfs_map_op op,
5947                      u64 logical, u64 *length,
5948                      struct btrfs_bio **bbio_ret)
5949 {
5950         return __btrfs_map_block(fs_info, op, logical, length, bbio_ret, 0, 1);
5951 }
5952
5953 int btrfs_rmap_block(struct btrfs_fs_info *fs_info, u64 chunk_start,
5954                      u64 physical, u64 **logical, int *naddrs, int *stripe_len)
5955 {
5956         struct extent_map *em;
5957         struct map_lookup *map;
5958         u64 *buf;
5959         u64 bytenr;
5960         u64 length;
5961         u64 stripe_nr;
5962         u64 rmap_len;
5963         int i, j, nr = 0;
5964
5965         em = get_chunk_map(fs_info, chunk_start, 1);
5966         if (IS_ERR(em))
5967                 return -EIO;
5968
5969         map = em->map_lookup;
5970         length = em->len;
5971         rmap_len = map->stripe_len;
5972
5973         if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5974                 length = div_u64(length, map->num_stripes / map->sub_stripes);
5975         else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5976                 length = div_u64(length, map->num_stripes);
5977         else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5978                 length = div_u64(length, nr_data_stripes(map));
5979                 rmap_len = map->stripe_len * nr_data_stripes(map);
5980         }
5981
5982         buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
5983         BUG_ON(!buf); /* -ENOMEM */
5984
5985         for (i = 0; i < map->num_stripes; i++) {
5986                 if (map->stripes[i].physical > physical ||
5987                     map->stripes[i].physical + length <= physical)
5988                         continue;
5989
5990                 stripe_nr = physical - map->stripes[i].physical;
5991                 stripe_nr = div64_u64(stripe_nr, map->stripe_len);
5992
5993                 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
5994                         stripe_nr = stripe_nr * map->num_stripes + i;
5995                         stripe_nr = div_u64(stripe_nr, map->sub_stripes);
5996                 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
5997                         stripe_nr = stripe_nr * map->num_stripes + i;
5998                 } /* else if RAID[56], multiply by nr_data_stripes().
5999                    * Alternatively, just use rmap_len below instead of
6000                    * map->stripe_len */
6001
6002                 bytenr = chunk_start + stripe_nr * rmap_len;
6003                 WARN_ON(nr >= map->num_stripes);
6004                 for (j = 0; j < nr; j++) {
6005                         if (buf[j] == bytenr)
6006                                 break;
6007                 }
6008                 if (j == nr) {
6009                         WARN_ON(nr >= map->num_stripes);
6010                         buf[nr++] = bytenr;
6011                 }
6012         }
6013
6014         *logical = buf;
6015         *naddrs = nr;
6016         *stripe_len = rmap_len;
6017
6018         free_extent_map(em);
6019         return 0;
6020 }
6021
6022 static inline void btrfs_end_bbio(struct btrfs_bio *bbio, struct bio *bio)
6023 {
6024         bio->bi_private = bbio->private;
6025         bio->bi_end_io = bbio->end_io;
6026         bio_endio(bio);
6027
6028         btrfs_put_bbio(bbio);
6029 }
6030
6031 static void btrfs_end_bio(struct bio *bio)
6032 {
6033         struct btrfs_bio *bbio = bio->bi_private;
6034         int is_orig_bio = 0;
6035
6036         if (bio->bi_status) {
6037                 atomic_inc(&bbio->error);
6038                 if (bio->bi_status == BLK_STS_IOERR ||
6039                     bio->bi_status == BLK_STS_TARGET) {
6040                         unsigned int stripe_index =
6041                                 btrfs_io_bio(bio)->stripe_index;
6042                         struct btrfs_device *dev;
6043
6044                         BUG_ON(stripe_index >= bbio->num_stripes);
6045                         dev = bbio->stripes[stripe_index].dev;
6046                         if (dev->bdev) {
6047                                 if (bio_op(bio) == REQ_OP_WRITE)
6048                                         btrfs_dev_stat_inc_and_print(dev,
6049                                                 BTRFS_DEV_STAT_WRITE_ERRS);
6050                                 else if (!(bio->bi_opf & REQ_RAHEAD))
6051                                         btrfs_dev_stat_inc_and_print(dev,
6052                                                 BTRFS_DEV_STAT_READ_ERRS);
6053                                 if (bio->bi_opf & REQ_PREFLUSH)
6054                                         btrfs_dev_stat_inc_and_print(dev,
6055                                                 BTRFS_DEV_STAT_FLUSH_ERRS);
6056                         }
6057                 }
6058         }
6059
6060         if (bio == bbio->orig_bio)
6061                 is_orig_bio = 1;
6062
6063         btrfs_bio_counter_dec(bbio->fs_info);
6064
6065         if (atomic_dec_and_test(&bbio->stripes_pending)) {
6066                 if (!is_orig_bio) {
6067                         bio_put(bio);
6068                         bio = bbio->orig_bio;
6069                 }
6070
6071                 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6072                 /* only send an error to the higher layers if it is
6073                  * beyond the tolerance of the btrfs bio
6074                  */
6075                 if (atomic_read(&bbio->error) > bbio->max_errors) {
6076                         bio->bi_status = BLK_STS_IOERR;
6077                 } else {
6078                         /*
6079                          * this bio is actually up to date, we didn't
6080                          * go over the max number of errors
6081                          */
6082                         bio->bi_status = BLK_STS_OK;
6083                 }
6084
6085                 btrfs_end_bbio(bbio, bio);
6086         } else if (!is_orig_bio) {
6087                 bio_put(bio);
6088         }
6089 }
6090
6091 /*
6092  * see run_scheduled_bios for a description of why bios are collected for
6093  * async submit.
6094  *
6095  * This will add one bio to the pending list for a device and make sure
6096  * the work struct is scheduled.
6097  */
6098 static noinline void btrfs_schedule_bio(struct btrfs_device *device,
6099                                         struct bio *bio)
6100 {
6101         struct btrfs_fs_info *fs_info = device->fs_info;
6102         int should_queue = 1;
6103         struct btrfs_pending_bios *pending_bios;
6104
6105         /* don't bother with additional async steps for reads, right now */
6106         if (bio_op(bio) == REQ_OP_READ) {
6107                 btrfsic_submit_bio(bio);
6108                 return;
6109         }
6110
6111         WARN_ON(bio->bi_next);
6112         bio->bi_next = NULL;
6113
6114         spin_lock(&device->io_lock);
6115         if (op_is_sync(bio->bi_opf))
6116                 pending_bios = &device->pending_sync_bios;
6117         else
6118                 pending_bios = &device->pending_bios;
6119
6120         if (pending_bios->tail)
6121                 pending_bios->tail->bi_next = bio;
6122
6123         pending_bios->tail = bio;
6124         if (!pending_bios->head)
6125                 pending_bios->head = bio;
6126         if (device->running_pending)
6127                 should_queue = 0;
6128
6129         spin_unlock(&device->io_lock);
6130
6131         if (should_queue)
6132                 btrfs_queue_work(fs_info->submit_workers, &device->work);
6133 }
6134
6135 static void submit_stripe_bio(struct btrfs_bio *bbio, struct bio *bio,
6136                               u64 physical, int dev_nr, int async)
6137 {
6138         struct btrfs_device *dev = bbio->stripes[dev_nr].dev;
6139         struct btrfs_fs_info *fs_info = bbio->fs_info;
6140
6141         bio->bi_private = bbio;
6142         btrfs_io_bio(bio)->stripe_index = dev_nr;
6143         bio->bi_end_io = btrfs_end_bio;
6144         bio->bi_iter.bi_sector = physical >> 9;
6145         btrfs_debug_in_rcu(fs_info,
6146         "btrfs_map_bio: rw %d 0x%x, sector=%llu, dev=%lu (%s id %llu), size=%u",
6147                 bio_op(bio), bio->bi_opf, (u64)bio->bi_iter.bi_sector,
6148                 (u_long)dev->bdev->bd_dev, rcu_str_deref(dev->name), dev->devid,
6149                 bio->bi_iter.bi_size);
6150         bio_set_dev(bio, dev->bdev);
6151
6152         btrfs_bio_counter_inc_noblocked(fs_info);
6153
6154         if (async)
6155                 btrfs_schedule_bio(dev, bio);
6156         else
6157                 btrfsic_submit_bio(bio);
6158 }
6159
6160 static void bbio_error(struct btrfs_bio *bbio, struct bio *bio, u64 logical)
6161 {
6162         atomic_inc(&bbio->error);
6163         if (atomic_dec_and_test(&bbio->stripes_pending)) {
6164                 /* Should be the original bio. */
6165                 WARN_ON(bio != bbio->orig_bio);
6166
6167                 btrfs_io_bio(bio)->mirror_num = bbio->mirror_num;
6168                 bio->bi_iter.bi_sector = logical >> 9;
6169                 if (atomic_read(&bbio->error) > bbio->max_errors)
6170                         bio->bi_status = BLK_STS_IOERR;
6171                 else
6172                         bio->bi_status = BLK_STS_OK;
6173                 btrfs_end_bbio(bbio, bio);
6174         }
6175 }
6176
6177 blk_status_t btrfs_map_bio(struct btrfs_fs_info *fs_info, struct bio *bio,
6178                            int mirror_num, int async_submit)
6179 {
6180         struct btrfs_device *dev;
6181         struct bio *first_bio = bio;
6182         u64 logical = (u64)bio->bi_iter.bi_sector << 9;
6183         u64 length = 0;
6184         u64 map_length;
6185         int ret;
6186         int dev_nr;
6187         int total_devs;
6188         struct btrfs_bio *bbio = NULL;
6189
6190         length = bio->bi_iter.bi_size;
6191         map_length = length;
6192
6193         btrfs_bio_counter_inc_blocked(fs_info);
6194         ret = __btrfs_map_block(fs_info, btrfs_op(bio), logical,
6195                                 &map_length, &bbio, mirror_num, 1);
6196         if (ret) {
6197                 btrfs_bio_counter_dec(fs_info);
6198                 return errno_to_blk_status(ret);
6199         }
6200
6201         total_devs = bbio->num_stripes;
6202         bbio->orig_bio = first_bio;
6203         bbio->private = first_bio->bi_private;
6204         bbio->end_io = first_bio->bi_end_io;
6205         bbio->fs_info = fs_info;
6206         atomic_set(&bbio->stripes_pending, bbio->num_stripes);
6207
6208         if ((bbio->map_type & BTRFS_BLOCK_GROUP_RAID56_MASK) &&
6209             ((bio_op(bio) == REQ_OP_WRITE) || (mirror_num > 1))) {
6210                 /* In this case, map_length has been set to the length of
6211                    a single stripe; not the whole write */
6212                 if (bio_op(bio) == REQ_OP_WRITE) {
6213                         ret = raid56_parity_write(fs_info, bio, bbio,
6214                                                   map_length);
6215                 } else {
6216                         ret = raid56_parity_recover(fs_info, bio, bbio,
6217                                                     map_length, mirror_num, 1);
6218                 }
6219
6220                 btrfs_bio_counter_dec(fs_info);
6221                 return errno_to_blk_status(ret);
6222         }
6223
6224         if (map_length < length) {
6225                 btrfs_crit(fs_info,
6226                            "mapping failed logical %llu bio len %llu len %llu",
6227                            logical, length, map_length);
6228                 BUG();
6229         }
6230
6231         for (dev_nr = 0; dev_nr < total_devs; dev_nr++) {
6232                 dev = bbio->stripes[dev_nr].dev;
6233                 if (!dev || !dev->bdev || test_bit(BTRFS_DEV_STATE_MISSING,
6234                                                    &dev->dev_state) ||
6235                     (bio_op(first_bio) == REQ_OP_WRITE &&
6236                     !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))) {
6237                         bbio_error(bbio, first_bio, logical);
6238                         continue;
6239                 }
6240
6241                 if (dev_nr < total_devs - 1)
6242                         bio = btrfs_bio_clone(first_bio);
6243                 else
6244                         bio = first_bio;
6245
6246                 submit_stripe_bio(bbio, bio, bbio->stripes[dev_nr].physical,
6247                                   dev_nr, async_submit);
6248         }
6249         btrfs_bio_counter_dec(fs_info);
6250         return BLK_STS_OK;
6251 }
6252
6253 /*
6254  * Find a device specified by @devid or @uuid in the list of @fs_devices, or
6255  * return NULL.
6256  *
6257  * If devid and uuid are both specified, the match must be exact, otherwise
6258  * only devid is used.
6259  *
6260  * If @seed is true, traverse through the seed devices.
6261  */
6262 struct btrfs_device *btrfs_find_device(struct btrfs_fs_devices *fs_devices,
6263                                         u64 devid, u8 *uuid, u8 *fsid,
6264                                         bool seed)
6265 {
6266         struct btrfs_device *device;
6267
6268         while (fs_devices) {
6269                 if (!fsid ||
6270                     !memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE)) {
6271                         list_for_each_entry(device, &fs_devices->devices,
6272                                             dev_list) {
6273                                 if (device->devid == devid &&
6274                                     (!uuid || memcmp(device->uuid, uuid,
6275                                                      BTRFS_UUID_SIZE) == 0))
6276                                         return device;
6277                         }
6278                 }
6279                 if (seed)
6280                         fs_devices = fs_devices->seed;
6281                 else
6282                         return NULL;
6283         }
6284         return NULL;
6285 }
6286
6287 static struct btrfs_device *add_missing_dev(struct btrfs_fs_devices *fs_devices,
6288                                             u64 devid, u8 *dev_uuid)
6289 {
6290         struct btrfs_device *device;
6291         unsigned int nofs_flag;
6292
6293         /*
6294          * We call this under the chunk_mutex, so we want to use NOFS for this
6295          * allocation, however we don't want to change btrfs_alloc_device() to
6296          * always do NOFS because we use it in a lot of other GFP_KERNEL safe
6297          * places.
6298          */
6299         nofs_flag = memalloc_nofs_save();
6300         device = btrfs_alloc_device(NULL, &devid, dev_uuid);
6301         memalloc_nofs_restore(nofs_flag);
6302         if (IS_ERR(device))
6303                 return device;
6304
6305         list_add(&device->dev_list, &fs_devices->devices);
6306         device->fs_devices = fs_devices;
6307         fs_devices->num_devices++;
6308
6309         set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6310         fs_devices->missing_devices++;
6311
6312         return device;
6313 }
6314
6315 /**
6316  * btrfs_alloc_device - allocate struct btrfs_device
6317  * @fs_info:    used only for generating a new devid, can be NULL if
6318  *              devid is provided (i.e. @devid != NULL).
6319  * @devid:      a pointer to devid for this device.  If NULL a new devid
6320  *              is generated.
6321  * @uuid:       a pointer to UUID for this device.  If NULL a new UUID
6322  *              is generated.
6323  *
6324  * Return: a pointer to a new &struct btrfs_device on success; ERR_PTR()
6325  * on error.  Returned struct is not linked onto any lists and must be
6326  * destroyed with btrfs_free_device.
6327  */
6328 struct btrfs_device *btrfs_alloc_device(struct btrfs_fs_info *fs_info,
6329                                         const u64 *devid,
6330                                         const u8 *uuid)
6331 {
6332         struct btrfs_device *dev;
6333         u64 tmp;
6334
6335         if (WARN_ON(!devid && !fs_info))
6336                 return ERR_PTR(-EINVAL);
6337
6338         dev = __alloc_device();
6339         if (IS_ERR(dev))
6340                 return dev;
6341
6342         if (devid)
6343                 tmp = *devid;
6344         else {
6345                 int ret;
6346
6347                 ret = find_next_devid(fs_info, &tmp);
6348                 if (ret) {
6349                         btrfs_free_device(dev);
6350                         return ERR_PTR(ret);
6351                 }
6352         }
6353         dev->devid = tmp;
6354
6355         if (uuid)
6356                 memcpy(dev->uuid, uuid, BTRFS_UUID_SIZE);
6357         else
6358                 generate_random_uuid(dev->uuid);
6359
6360         btrfs_init_work(&dev->work, btrfs_submit_helper,
6361                         pending_bios_fn, NULL, NULL);
6362
6363         return dev;
6364 }
6365
6366 static void btrfs_report_missing_device(struct btrfs_fs_info *fs_info,
6367                                         u64 devid, u8 *uuid, bool error)
6368 {
6369         if (error)
6370                 btrfs_err_rl(fs_info, "devid %llu uuid %pU is missing",
6371                               devid, uuid);
6372         else
6373                 btrfs_warn_rl(fs_info, "devid %llu uuid %pU is missing",
6374                               devid, uuid);
6375 }
6376
6377 static int read_one_chunk(struct btrfs_fs_info *fs_info, struct btrfs_key *key,
6378                           struct extent_buffer *leaf,
6379                           struct btrfs_chunk *chunk)
6380 {
6381         struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
6382         struct map_lookup *map;
6383         struct extent_map *em;
6384         u64 logical;
6385         u64 length;
6386         u64 devid;
6387         u8 uuid[BTRFS_UUID_SIZE];
6388         int num_stripes;
6389         int ret;
6390         int i;
6391
6392         logical = key->offset;
6393         length = btrfs_chunk_length(leaf, chunk);
6394         num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
6395
6396         /*
6397          * Only need to verify chunk item if we're reading from sys chunk array,
6398          * as chunk item in tree block is already verified by tree-checker.
6399          */
6400         if (leaf->start == BTRFS_SUPER_INFO_OFFSET) {
6401                 ret = btrfs_check_chunk_valid(fs_info, leaf, chunk, logical);
6402                 if (ret)
6403                         return ret;
6404         }
6405
6406         read_lock(&map_tree->map_tree.lock);
6407         em = lookup_extent_mapping(&map_tree->map_tree, logical, 1);
6408         read_unlock(&map_tree->map_tree.lock);
6409
6410         /* already mapped? */
6411         if (em && em->start <= logical && em->start + em->len > logical) {
6412                 free_extent_map(em);
6413                 return 0;
6414         } else if (em) {
6415                 free_extent_map(em);
6416         }
6417
6418         em = alloc_extent_map();
6419         if (!em)
6420                 return -ENOMEM;
6421         map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
6422         if (!map) {
6423                 free_extent_map(em);
6424                 return -ENOMEM;
6425         }
6426
6427         set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
6428         em->map_lookup = map;
6429         em->start = logical;
6430         em->len = length;
6431         em->orig_start = 0;
6432         em->block_start = 0;
6433         em->block_len = em->len;
6434
6435         map->num_stripes = num_stripes;
6436         map->io_width = btrfs_chunk_io_width(leaf, chunk);
6437         map->io_align = btrfs_chunk_io_align(leaf, chunk);
6438         map->stripe_len = btrfs_chunk_stripe_len(leaf, chunk);
6439         map->type = btrfs_chunk_type(leaf, chunk);
6440         map->sub_stripes = btrfs_chunk_sub_stripes(leaf, chunk);
6441         map->verified_stripes = 0;
6442         for (i = 0; i < num_stripes; i++) {
6443                 map->stripes[i].physical =
6444                         btrfs_stripe_offset_nr(leaf, chunk, i);
6445                 devid = btrfs_stripe_devid_nr(leaf, chunk, i);
6446                 read_extent_buffer(leaf, uuid, (unsigned long)
6447                                    btrfs_stripe_dev_uuid_nr(chunk, i),
6448                                    BTRFS_UUID_SIZE);
6449                 map->stripes[i].dev = btrfs_find_device(fs_info->fs_devices,
6450                                                 devid, uuid, NULL, true);
6451                 if (!map->stripes[i].dev &&
6452                     !btrfs_test_opt(fs_info, DEGRADED)) {
6453                         free_extent_map(em);
6454                         btrfs_report_missing_device(fs_info, devid, uuid, true);
6455                         return -ENOENT;
6456                 }
6457                 if (!map->stripes[i].dev) {
6458                         map->stripes[i].dev =
6459                                 add_missing_dev(fs_info->fs_devices, devid,
6460                                                 uuid);
6461                         if (IS_ERR(map->stripes[i].dev)) {
6462                                 free_extent_map(em);
6463                                 btrfs_err(fs_info,
6464                                         "failed to init missing dev %llu: %ld",
6465                                         devid, PTR_ERR(map->stripes[i].dev));
6466                                 return PTR_ERR(map->stripes[i].dev);
6467                         }
6468                         btrfs_report_missing_device(fs_info, devid, uuid, false);
6469                 }
6470                 set_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
6471                                 &(map->stripes[i].dev->dev_state));
6472
6473         }
6474
6475         write_lock(&map_tree->map_tree.lock);
6476         ret = add_extent_mapping(&map_tree->map_tree, em, 0);
6477         write_unlock(&map_tree->map_tree.lock);
6478         if (ret < 0) {
6479                 btrfs_err(fs_info,
6480                           "failed to add chunk map, start=%llu len=%llu: %d",
6481                           em->start, em->len, ret);
6482         }
6483         free_extent_map(em);
6484
6485         return ret;
6486 }
6487
6488 static void fill_device_from_item(struct extent_buffer *leaf,
6489                                  struct btrfs_dev_item *dev_item,
6490                                  struct btrfs_device *device)
6491 {
6492         unsigned long ptr;
6493
6494         device->devid = btrfs_device_id(leaf, dev_item);
6495         device->disk_total_bytes = btrfs_device_total_bytes(leaf, dev_item);
6496         device->total_bytes = device->disk_total_bytes;
6497         device->commit_total_bytes = device->disk_total_bytes;
6498         device->bytes_used = btrfs_device_bytes_used(leaf, dev_item);
6499         device->commit_bytes_used = device->bytes_used;
6500         device->type = btrfs_device_type(leaf, dev_item);
6501         device->io_align = btrfs_device_io_align(leaf, dev_item);
6502         device->io_width = btrfs_device_io_width(leaf, dev_item);
6503         device->sector_size = btrfs_device_sector_size(leaf, dev_item);
6504         WARN_ON(device->devid == BTRFS_DEV_REPLACE_DEVID);
6505         clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
6506
6507         ptr = btrfs_device_uuid(dev_item);
6508         read_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
6509 }
6510
6511 static struct btrfs_fs_devices *open_seed_devices(struct btrfs_fs_info *fs_info,
6512                                                   u8 *fsid)
6513 {
6514         struct btrfs_fs_devices *fs_devices;
6515         int ret;
6516
6517         lockdep_assert_held(&uuid_mutex);
6518         ASSERT(fsid);
6519
6520         fs_devices = fs_info->fs_devices->seed;
6521         while (fs_devices) {
6522                 if (!memcmp(fs_devices->fsid, fsid, BTRFS_FSID_SIZE))
6523                         return fs_devices;
6524
6525                 fs_devices = fs_devices->seed;
6526         }
6527
6528         fs_devices = find_fsid(fsid);
6529         if (!fs_devices) {
6530                 if (!btrfs_test_opt(fs_info, DEGRADED))
6531                         return ERR_PTR(-ENOENT);
6532
6533                 fs_devices = alloc_fs_devices(fsid);
6534                 if (IS_ERR(fs_devices))
6535                         return fs_devices;
6536
6537                 fs_devices->seeding = 1;
6538                 fs_devices->opened = 1;
6539                 return fs_devices;
6540         }
6541
6542         fs_devices = clone_fs_devices(fs_devices);
6543         if (IS_ERR(fs_devices))
6544                 return fs_devices;
6545
6546         ret = open_fs_devices(fs_devices, FMODE_READ, fs_info->bdev_holder);
6547         if (ret) {
6548                 free_fs_devices(fs_devices);
6549                 fs_devices = ERR_PTR(ret);
6550                 goto out;
6551         }
6552
6553         if (!fs_devices->seeding) {
6554                 close_fs_devices(fs_devices);
6555                 free_fs_devices(fs_devices);
6556                 fs_devices = ERR_PTR(-EINVAL);
6557                 goto out;
6558         }
6559
6560         fs_devices->seed = fs_info->fs_devices->seed;
6561         fs_info->fs_devices->seed = fs_devices;
6562 out:
6563         return fs_devices;
6564 }
6565
6566 static int read_one_dev(struct btrfs_fs_info *fs_info,
6567                         struct extent_buffer *leaf,
6568                         struct btrfs_dev_item *dev_item)
6569 {
6570         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6571         struct btrfs_device *device;
6572         u64 devid;
6573         int ret;
6574         u8 fs_uuid[BTRFS_FSID_SIZE];
6575         u8 dev_uuid[BTRFS_UUID_SIZE];
6576
6577         devid = btrfs_device_id(leaf, dev_item);
6578         read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
6579                            BTRFS_UUID_SIZE);
6580         read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
6581                            BTRFS_FSID_SIZE);
6582
6583         if (memcmp(fs_uuid, fs_info->fsid, BTRFS_FSID_SIZE)) {
6584                 fs_devices = open_seed_devices(fs_info, fs_uuid);
6585                 if (IS_ERR(fs_devices))
6586                         return PTR_ERR(fs_devices);
6587         }
6588
6589         device = btrfs_find_device(fs_info->fs_devices, devid, dev_uuid,
6590                                    fs_uuid, true);
6591         if (!device) {
6592                 if (!btrfs_test_opt(fs_info, DEGRADED)) {
6593                         btrfs_report_missing_device(fs_info, devid,
6594                                                         dev_uuid, true);
6595                         return -ENOENT;
6596                 }
6597
6598                 device = add_missing_dev(fs_devices, devid, dev_uuid);
6599                 if (IS_ERR(device)) {
6600                         btrfs_err(fs_info,
6601                                 "failed to add missing dev %llu: %ld",
6602                                 devid, PTR_ERR(device));
6603                         return PTR_ERR(device);
6604                 }
6605                 btrfs_report_missing_device(fs_info, devid, dev_uuid, false);
6606         } else {
6607                 if (!device->bdev) {
6608                         if (!btrfs_test_opt(fs_info, DEGRADED)) {
6609                                 btrfs_report_missing_device(fs_info,
6610                                                 devid, dev_uuid, true);
6611                                 return -ENOENT;
6612                         }
6613                         btrfs_report_missing_device(fs_info, devid,
6614                                                         dev_uuid, false);
6615                 }
6616
6617                 if (!device->bdev &&
6618                     !test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
6619                         /*
6620                          * this happens when a device that was properly setup
6621                          * in the device info lists suddenly goes bad.
6622                          * device->bdev is NULL, and so we have to set
6623                          * device->missing to one here
6624                          */
6625                         device->fs_devices->missing_devices++;
6626                         set_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
6627                 }
6628
6629                 /* Move the device to its own fs_devices */
6630                 if (device->fs_devices != fs_devices) {
6631                         ASSERT(test_bit(BTRFS_DEV_STATE_MISSING,
6632                                                         &device->dev_state));
6633
6634                         list_move(&device->dev_list, &fs_devices->devices);
6635                         device->fs_devices->num_devices--;
6636                         fs_devices->num_devices++;
6637
6638                         device->fs_devices->missing_devices--;
6639                         fs_devices->missing_devices++;
6640
6641                         device->fs_devices = fs_devices;
6642                 }
6643         }
6644
6645         if (device->fs_devices != fs_info->fs_devices) {
6646                 BUG_ON(test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state));
6647                 if (device->generation !=
6648                     btrfs_device_generation(leaf, dev_item))
6649                         return -EINVAL;
6650         }
6651
6652         fill_device_from_item(leaf, dev_item, device);
6653         set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
6654         if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
6655            !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
6656                 device->fs_devices->total_rw_bytes += device->total_bytes;
6657                 atomic64_add(device->total_bytes - device->bytes_used,
6658                                 &fs_info->free_chunk_space);
6659         }
6660         ret = 0;
6661         return ret;
6662 }
6663
6664 int btrfs_read_sys_array(struct btrfs_fs_info *fs_info)
6665 {
6666         struct btrfs_root *root = fs_info->tree_root;
6667         struct btrfs_super_block *super_copy = fs_info->super_copy;
6668         struct extent_buffer *sb;
6669         struct btrfs_disk_key *disk_key;
6670         struct btrfs_chunk *chunk;
6671         u8 *array_ptr;
6672         unsigned long sb_array_offset;
6673         int ret = 0;
6674         u32 num_stripes;
6675         u32 array_size;
6676         u32 len = 0;
6677         u32 cur_offset;
6678         u64 type;
6679         struct btrfs_key key;
6680
6681         ASSERT(BTRFS_SUPER_INFO_SIZE <= fs_info->nodesize);
6682         /*
6683          * This will create extent buffer of nodesize, superblock size is
6684          * fixed to BTRFS_SUPER_INFO_SIZE. If nodesize > sb size, this will
6685          * overallocate but we can keep it as-is, only the first page is used.
6686          */
6687         sb = btrfs_find_create_tree_block(fs_info, BTRFS_SUPER_INFO_OFFSET);
6688         if (IS_ERR(sb))
6689                 return PTR_ERR(sb);
6690         set_extent_buffer_uptodate(sb);
6691         btrfs_set_buffer_lockdep_class(root->root_key.objectid, sb, 0);
6692         /*
6693          * The sb extent buffer is artificial and just used to read the system array.
6694          * set_extent_buffer_uptodate() call does not properly mark all it's
6695          * pages up-to-date when the page is larger: extent does not cover the
6696          * whole page and consequently check_page_uptodate does not find all
6697          * the page's extents up-to-date (the hole beyond sb),
6698          * write_extent_buffer then triggers a WARN_ON.
6699          *
6700          * Regular short extents go through mark_extent_buffer_dirty/writeback cycle,
6701          * but sb spans only this function. Add an explicit SetPageUptodate call
6702          * to silence the warning eg. on PowerPC 64.
6703          */
6704         if (PAGE_SIZE > BTRFS_SUPER_INFO_SIZE)
6705                 SetPageUptodate(sb->pages[0]);
6706
6707         write_extent_buffer(sb, super_copy, 0, BTRFS_SUPER_INFO_SIZE);
6708         array_size = btrfs_super_sys_array_size(super_copy);
6709
6710         array_ptr = super_copy->sys_chunk_array;
6711         sb_array_offset = offsetof(struct btrfs_super_block, sys_chunk_array);
6712         cur_offset = 0;
6713
6714         while (cur_offset < array_size) {
6715                 disk_key = (struct btrfs_disk_key *)array_ptr;
6716                 len = sizeof(*disk_key);
6717                 if (cur_offset + len > array_size)
6718                         goto out_short_read;
6719
6720                 btrfs_disk_key_to_cpu(&key, disk_key);
6721
6722                 array_ptr += len;
6723                 sb_array_offset += len;
6724                 cur_offset += len;
6725
6726                 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
6727                         chunk = (struct btrfs_chunk *)sb_array_offset;
6728                         /*
6729                          * At least one btrfs_chunk with one stripe must be
6730                          * present, exact stripe count check comes afterwards
6731                          */
6732                         len = btrfs_chunk_item_size(1);
6733                         if (cur_offset + len > array_size)
6734                                 goto out_short_read;
6735
6736                         num_stripes = btrfs_chunk_num_stripes(sb, chunk);
6737                         if (!num_stripes) {
6738                                 btrfs_err(fs_info,
6739                                         "invalid number of stripes %u in sys_array at offset %u",
6740                                         num_stripes, cur_offset);
6741                                 ret = -EIO;
6742                                 break;
6743                         }
6744
6745                         type = btrfs_chunk_type(sb, chunk);
6746                         if ((type & BTRFS_BLOCK_GROUP_SYSTEM) == 0) {
6747                                 btrfs_err(fs_info,
6748                             "invalid chunk type %llu in sys_array at offset %u",
6749                                         type, cur_offset);
6750                                 ret = -EIO;
6751                                 break;
6752                         }
6753
6754                         len = btrfs_chunk_item_size(num_stripes);
6755                         if (cur_offset + len > array_size)
6756                                 goto out_short_read;
6757
6758                         ret = read_one_chunk(fs_info, &key, sb, chunk);
6759                         if (ret)
6760                                 break;
6761                 } else {
6762                         btrfs_err(fs_info,
6763                             "unexpected item type %u in sys_array at offset %u",
6764                                   (u32)key.type, cur_offset);
6765                         ret = -EIO;
6766                         break;
6767                 }
6768                 array_ptr += len;
6769                 sb_array_offset += len;
6770                 cur_offset += len;
6771         }
6772         clear_extent_buffer_uptodate(sb);
6773         free_extent_buffer_stale(sb);
6774         return ret;
6775
6776 out_short_read:
6777         btrfs_err(fs_info, "sys_array too short to read %u bytes at offset %u",
6778                         len, cur_offset);
6779         clear_extent_buffer_uptodate(sb);
6780         free_extent_buffer_stale(sb);
6781         return -EIO;
6782 }
6783
6784 /*
6785  * Check if all chunks in the fs are OK for read-write degraded mount
6786  *
6787  * If the @failing_dev is specified, it's accounted as missing.
6788  *
6789  * Return true if all chunks meet the minimal RW mount requirements.
6790  * Return false if any chunk doesn't meet the minimal RW mount requirements.
6791  */
6792 bool btrfs_check_rw_degradable(struct btrfs_fs_info *fs_info,
6793                                         struct btrfs_device *failing_dev)
6794 {
6795         struct btrfs_mapping_tree *map_tree = &fs_info->mapping_tree;
6796         struct extent_map *em;
6797         u64 next_start = 0;
6798         bool ret = true;
6799
6800         read_lock(&map_tree->map_tree.lock);
6801         em = lookup_extent_mapping(&map_tree->map_tree, 0, (u64)-1);
6802         read_unlock(&map_tree->map_tree.lock);
6803         /* No chunk at all? Return false anyway */
6804         if (!em) {
6805                 ret = false;
6806                 goto out;
6807         }
6808         while (em) {
6809                 struct map_lookup *map;
6810                 int missing = 0;
6811                 int max_tolerated;
6812                 int i;
6813
6814                 map = em->map_lookup;
6815                 max_tolerated =
6816                         btrfs_get_num_tolerated_disk_barrier_failures(
6817                                         map->type);
6818                 for (i = 0; i < map->num_stripes; i++) {
6819                         struct btrfs_device *dev = map->stripes[i].dev;
6820
6821                         if (!dev || !dev->bdev ||
6822                             test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state) ||
6823                             dev->last_flush_error)
6824                                 missing++;
6825                         else if (failing_dev && failing_dev == dev)
6826                                 missing++;
6827                 }
6828                 if (missing > max_tolerated) {
6829                         if (!failing_dev)
6830                                 btrfs_warn(fs_info,
6831         "chunk %llu missing %d devices, max tolerance is %d for writeable mount",
6832                                    em->start, missing, max_tolerated);
6833                         free_extent_map(em);
6834                         ret = false;
6835                         goto out;
6836                 }
6837                 next_start = extent_map_end(em);
6838                 free_extent_map(em);
6839
6840                 read_lock(&map_tree->map_tree.lock);
6841                 em = lookup_extent_mapping(&map_tree->map_tree, next_start,
6842                                            (u64)(-1) - next_start);
6843                 read_unlock(&map_tree->map_tree.lock);
6844         }
6845 out:
6846         return ret;
6847 }
6848
6849 int btrfs_read_chunk_tree(struct btrfs_fs_info *fs_info)
6850 {
6851         struct btrfs_root *root = fs_info->chunk_root;
6852         struct btrfs_path *path;
6853         struct extent_buffer *leaf;
6854         struct btrfs_key key;
6855         struct btrfs_key found_key;
6856         int ret;
6857         int slot;
6858         u64 total_dev = 0;
6859
6860         path = btrfs_alloc_path();
6861         if (!path)
6862                 return -ENOMEM;
6863
6864         /*
6865          * uuid_mutex is needed only if we are mounting a sprout FS
6866          * otherwise we don't need it.
6867          */
6868         mutex_lock(&uuid_mutex);
6869         mutex_lock(&fs_info->chunk_mutex);
6870
6871         /*
6872          * It is possible for mount and umount to race in such a way that
6873          * we execute this code path, but open_fs_devices failed to clear
6874          * total_rw_bytes. We certainly want it cleared before reading the
6875          * device items, so clear it here.
6876          */
6877         fs_info->fs_devices->total_rw_bytes = 0;
6878
6879         /*
6880          * Read all device items, and then all the chunk items. All
6881          * device items are found before any chunk item (their object id
6882          * is smaller than the lowest possible object id for a chunk
6883          * item - BTRFS_FIRST_CHUNK_TREE_OBJECTID).
6884          */
6885         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
6886         key.offset = 0;
6887         key.type = 0;
6888         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6889         if (ret < 0)
6890                 goto error;
6891         while (1) {
6892                 leaf = path->nodes[0];
6893                 slot = path->slots[0];
6894                 if (slot >= btrfs_header_nritems(leaf)) {
6895                         ret = btrfs_next_leaf(root, path);
6896                         if (ret == 0)
6897                                 continue;
6898                         if (ret < 0)
6899                                 goto error;
6900                         break;
6901                 }
6902                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6903                 if (found_key.type == BTRFS_DEV_ITEM_KEY) {
6904                         struct btrfs_dev_item *dev_item;
6905                         dev_item = btrfs_item_ptr(leaf, slot,
6906                                                   struct btrfs_dev_item);
6907                         ret = read_one_dev(fs_info, leaf, dev_item);
6908                         if (ret)
6909                                 goto error;
6910                         total_dev++;
6911                 } else if (found_key.type == BTRFS_CHUNK_ITEM_KEY) {
6912                         struct btrfs_chunk *chunk;
6913                         chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
6914                         ret = read_one_chunk(fs_info, &found_key, leaf, chunk);
6915                         if (ret)
6916                                 goto error;
6917                 }
6918                 path->slots[0]++;
6919         }
6920
6921         /*
6922          * After loading chunk tree, we've got all device information,
6923          * do another round of validation checks.
6924          */
6925         if (total_dev != fs_info->fs_devices->total_devices) {
6926                 btrfs_err(fs_info,
6927            "super_num_devices %llu mismatch with num_devices %llu found here",
6928                           btrfs_super_num_devices(fs_info->super_copy),
6929                           total_dev);
6930                 ret = -EINVAL;
6931                 goto error;
6932         }
6933         if (btrfs_super_total_bytes(fs_info->super_copy) <
6934             fs_info->fs_devices->total_rw_bytes) {
6935                 btrfs_err(fs_info,
6936         "super_total_bytes %llu mismatch with fs_devices total_rw_bytes %llu",
6937                           btrfs_super_total_bytes(fs_info->super_copy),
6938                           fs_info->fs_devices->total_rw_bytes);
6939                 ret = -EINVAL;
6940                 goto error;
6941         }
6942         ret = 0;
6943 error:
6944         mutex_unlock(&fs_info->chunk_mutex);
6945         mutex_unlock(&uuid_mutex);
6946
6947         btrfs_free_path(path);
6948         return ret;
6949 }
6950
6951 void btrfs_init_devices_late(struct btrfs_fs_info *fs_info)
6952 {
6953         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6954         struct btrfs_device *device;
6955
6956         while (fs_devices) {
6957                 mutex_lock(&fs_devices->device_list_mutex);
6958                 list_for_each_entry(device, &fs_devices->devices, dev_list)
6959                         device->fs_info = fs_info;
6960                 mutex_unlock(&fs_devices->device_list_mutex);
6961
6962                 fs_devices = fs_devices->seed;
6963         }
6964 }
6965
6966 static void __btrfs_reset_dev_stats(struct btrfs_device *dev)
6967 {
6968         int i;
6969
6970         for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
6971                 btrfs_dev_stat_reset(dev, i);
6972 }
6973
6974 int btrfs_init_dev_stats(struct btrfs_fs_info *fs_info)
6975 {
6976         struct btrfs_key key;
6977         struct btrfs_key found_key;
6978         struct btrfs_root *dev_root = fs_info->dev_root;
6979         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
6980         struct extent_buffer *eb;
6981         int slot;
6982         int ret = 0;
6983         struct btrfs_device *device;
6984         struct btrfs_path *path = NULL;
6985         int i;
6986
6987         path = btrfs_alloc_path();
6988         if (!path) {
6989                 ret = -ENOMEM;
6990                 goto out;
6991         }
6992
6993         mutex_lock(&fs_devices->device_list_mutex);
6994         list_for_each_entry(device, &fs_devices->devices, dev_list) {
6995                 int item_size;
6996                 struct btrfs_dev_stats_item *ptr;
6997
6998                 key.objectid = BTRFS_DEV_STATS_OBJECTID;
6999                 key.type = BTRFS_PERSISTENT_ITEM_KEY;
7000                 key.offset = device->devid;
7001                 ret = btrfs_search_slot(NULL, dev_root, &key, path, 0, 0);
7002                 if (ret) {
7003                         __btrfs_reset_dev_stats(device);
7004                         device->dev_stats_valid = 1;
7005                         btrfs_release_path(path);
7006                         continue;
7007                 }
7008                 slot = path->slots[0];
7009                 eb = path->nodes[0];
7010                 btrfs_item_key_to_cpu(eb, &found_key, slot);
7011                 item_size = btrfs_item_size_nr(eb, slot);
7012
7013                 ptr = btrfs_item_ptr(eb, slot,
7014                                      struct btrfs_dev_stats_item);
7015
7016                 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7017                         if (item_size >= (1 + i) * sizeof(__le64))
7018                                 btrfs_dev_stat_set(device, i,
7019                                         btrfs_dev_stats_value(eb, ptr, i));
7020                         else
7021                                 btrfs_dev_stat_reset(device, i);
7022                 }
7023
7024                 device->dev_stats_valid = 1;
7025                 btrfs_dev_stat_print_on_load(device);
7026                 btrfs_release_path(path);
7027         }
7028         mutex_unlock(&fs_devices->device_list_mutex);
7029
7030 out:
7031         btrfs_free_path(path);
7032         return ret < 0 ? ret : 0;
7033 }
7034
7035 static int update_dev_stat_item(struct btrfs_trans_handle *trans,
7036                                 struct btrfs_device *device)
7037 {
7038         struct btrfs_fs_info *fs_info = trans->fs_info;
7039         struct btrfs_root *dev_root = fs_info->dev_root;
7040         struct btrfs_path *path;
7041         struct btrfs_key key;
7042         struct extent_buffer *eb;
7043         struct btrfs_dev_stats_item *ptr;
7044         int ret;
7045         int i;
7046
7047         key.objectid = BTRFS_DEV_STATS_OBJECTID;
7048         key.type = BTRFS_PERSISTENT_ITEM_KEY;
7049         key.offset = device->devid;
7050
7051         path = btrfs_alloc_path();
7052         if (!path)
7053                 return -ENOMEM;
7054         ret = btrfs_search_slot(trans, dev_root, &key, path, -1, 1);
7055         if (ret < 0) {
7056                 btrfs_warn_in_rcu(fs_info,
7057                         "error %d while searching for dev_stats item for device %s",
7058                               ret, rcu_str_deref(device->name));
7059                 goto out;
7060         }
7061
7062         if (ret == 0 &&
7063             btrfs_item_size_nr(path->nodes[0], path->slots[0]) < sizeof(*ptr)) {
7064                 /* need to delete old one and insert a new one */
7065                 ret = btrfs_del_item(trans, dev_root, path);
7066                 if (ret != 0) {
7067                         btrfs_warn_in_rcu(fs_info,
7068                                 "delete too small dev_stats item for device %s failed %d",
7069                                       rcu_str_deref(device->name), ret);
7070                         goto out;
7071                 }
7072                 ret = 1;
7073         }
7074
7075         if (ret == 1) {
7076                 /* need to insert a new item */
7077                 btrfs_release_path(path);
7078                 ret = btrfs_insert_empty_item(trans, dev_root, path,
7079                                               &key, sizeof(*ptr));
7080                 if (ret < 0) {
7081                         btrfs_warn_in_rcu(fs_info,
7082                                 "insert dev_stats item for device %s failed %d",
7083                                 rcu_str_deref(device->name), ret);
7084                         goto out;
7085                 }
7086         }
7087
7088         eb = path->nodes[0];
7089         ptr = btrfs_item_ptr(eb, path->slots[0], struct btrfs_dev_stats_item);
7090         for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7091                 btrfs_set_dev_stats_value(eb, ptr, i,
7092                                           btrfs_dev_stat_read(device, i));
7093         btrfs_mark_buffer_dirty(eb);
7094
7095 out:
7096         btrfs_free_path(path);
7097         return ret;
7098 }
7099
7100 /*
7101  * called from commit_transaction. Writes all changed device stats to disk.
7102  */
7103 int btrfs_run_dev_stats(struct btrfs_trans_handle *trans,
7104                         struct btrfs_fs_info *fs_info)
7105 {
7106         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7107         struct btrfs_device *device;
7108         int stats_cnt;
7109         int ret = 0;
7110
7111         mutex_lock(&fs_devices->device_list_mutex);
7112         list_for_each_entry(device, &fs_devices->devices, dev_list) {
7113                 stats_cnt = atomic_read(&device->dev_stats_ccnt);
7114                 if (!device->dev_stats_valid || stats_cnt == 0)
7115                         continue;
7116
7117
7118                 /*
7119                  * There is a LOAD-LOAD control dependency between the value of
7120                  * dev_stats_ccnt and updating the on-disk values which requires
7121                  * reading the in-memory counters. Such control dependencies
7122                  * require explicit read memory barriers.
7123                  *
7124                  * This memory barriers pairs with smp_mb__before_atomic in
7125                  * btrfs_dev_stat_inc/btrfs_dev_stat_set and with the full
7126                  * barrier implied by atomic_xchg in
7127                  * btrfs_dev_stats_read_and_reset
7128                  */
7129                 smp_rmb();
7130
7131                 ret = update_dev_stat_item(trans, device);
7132                 if (!ret)
7133                         atomic_sub(stats_cnt, &device->dev_stats_ccnt);
7134         }
7135         mutex_unlock(&fs_devices->device_list_mutex);
7136
7137         return ret;
7138 }
7139
7140 void btrfs_dev_stat_inc_and_print(struct btrfs_device *dev, int index)
7141 {
7142         btrfs_dev_stat_inc(dev, index);
7143         btrfs_dev_stat_print_on_error(dev);
7144 }
7145
7146 static void btrfs_dev_stat_print_on_error(struct btrfs_device *dev)
7147 {
7148         if (!dev->dev_stats_valid)
7149                 return;
7150         btrfs_err_rl_in_rcu(dev->fs_info,
7151                 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7152                            rcu_str_deref(dev->name),
7153                            btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7154                            btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7155                            btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7156                            btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7157                            btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7158 }
7159
7160 static void btrfs_dev_stat_print_on_load(struct btrfs_device *dev)
7161 {
7162         int i;
7163
7164         for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7165                 if (btrfs_dev_stat_read(dev, i) != 0)
7166                         break;
7167         if (i == BTRFS_DEV_STAT_VALUES_MAX)
7168                 return; /* all values == 0, suppress message */
7169
7170         btrfs_info_in_rcu(dev->fs_info,
7171                 "bdev %s errs: wr %u, rd %u, flush %u, corrupt %u, gen %u",
7172                rcu_str_deref(dev->name),
7173                btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_WRITE_ERRS),
7174                btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_READ_ERRS),
7175                btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_FLUSH_ERRS),
7176                btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS),
7177                btrfs_dev_stat_read(dev, BTRFS_DEV_STAT_GENERATION_ERRS));
7178 }
7179
7180 int btrfs_get_dev_stats(struct btrfs_fs_info *fs_info,
7181                         struct btrfs_ioctl_get_dev_stats *stats)
7182 {
7183         struct btrfs_device *dev;
7184         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7185         int i;
7186
7187         mutex_lock(&fs_devices->device_list_mutex);
7188         dev = btrfs_find_device(fs_info->fs_devices, stats->devid,
7189                                 NULL, NULL, true);
7190         mutex_unlock(&fs_devices->device_list_mutex);
7191
7192         if (!dev) {
7193                 btrfs_warn(fs_info, "get dev_stats failed, device not found");
7194                 return -ENODEV;
7195         } else if (!dev->dev_stats_valid) {
7196                 btrfs_warn(fs_info, "get dev_stats failed, not yet valid");
7197                 return -ENODEV;
7198         } else if (stats->flags & BTRFS_DEV_STATS_RESET) {
7199                 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++) {
7200                         if (stats->nr_items > i)
7201                                 stats->values[i] =
7202                                         btrfs_dev_stat_read_and_reset(dev, i);
7203                         else
7204                                 btrfs_dev_stat_reset(dev, i);
7205                 }
7206                 btrfs_info(fs_info, "device stats zeroed by %s (%d)",
7207                            current->comm, task_pid_nr(current));
7208         } else {
7209                 for (i = 0; i < BTRFS_DEV_STAT_VALUES_MAX; i++)
7210                         if (stats->nr_items > i)
7211                                 stats->values[i] = btrfs_dev_stat_read(dev, i);
7212         }
7213         if (stats->nr_items > BTRFS_DEV_STAT_VALUES_MAX)
7214                 stats->nr_items = BTRFS_DEV_STAT_VALUES_MAX;
7215         return 0;
7216 }
7217
7218 void btrfs_scratch_superblocks(struct block_device *bdev, const char *device_path)
7219 {
7220         struct buffer_head *bh;
7221         struct btrfs_super_block *disk_super;
7222         int copy_num;
7223
7224         if (!bdev)
7225                 return;
7226
7227         for (copy_num = 0; copy_num < BTRFS_SUPER_MIRROR_MAX;
7228                 copy_num++) {
7229
7230                 if (btrfs_read_dev_one_super(bdev, copy_num, &bh))
7231                         continue;
7232
7233                 disk_super = (struct btrfs_super_block *)bh->b_data;
7234
7235                 memset(&disk_super->magic, 0, sizeof(disk_super->magic));
7236                 set_buffer_dirty(bh);
7237                 sync_dirty_buffer(bh);
7238                 brelse(bh);
7239         }
7240
7241         /* Notify udev that device has changed */
7242         btrfs_kobject_uevent(bdev, KOBJ_CHANGE);
7243
7244         /* Update ctime/mtime for device path for libblkid */
7245         update_dev_time(device_path);
7246 }
7247
7248 /*
7249  * Update the size of all devices, which is used for writing out the
7250  * super blocks.
7251  */
7252 void btrfs_update_commit_device_size(struct btrfs_fs_info *fs_info)
7253 {
7254         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7255         struct btrfs_device *curr, *next;
7256
7257         if (list_empty(&fs_devices->resized_devices))
7258                 return;
7259
7260         mutex_lock(&fs_devices->device_list_mutex);
7261         mutex_lock(&fs_info->chunk_mutex);
7262         list_for_each_entry_safe(curr, next, &fs_devices->resized_devices,
7263                                  resized_list) {
7264                 list_del_init(&curr->resized_list);
7265                 curr->commit_total_bytes = curr->disk_total_bytes;
7266         }
7267         mutex_unlock(&fs_info->chunk_mutex);
7268         mutex_unlock(&fs_devices->device_list_mutex);
7269 }
7270
7271 /* Must be invoked during the transaction commit */
7272 void btrfs_update_commit_device_bytes_used(struct btrfs_transaction *trans)
7273 {
7274         struct btrfs_fs_info *fs_info = trans->fs_info;
7275         struct extent_map *em;
7276         struct map_lookup *map;
7277         struct btrfs_device *dev;
7278         int i;
7279
7280         if (list_empty(&trans->pending_chunks))
7281                 return;
7282
7283         /* In order to kick the device replace finish process */
7284         mutex_lock(&fs_info->chunk_mutex);
7285         list_for_each_entry(em, &trans->pending_chunks, list) {
7286                 map = em->map_lookup;
7287
7288                 for (i = 0; i < map->num_stripes; i++) {
7289                         dev = map->stripes[i].dev;
7290                         dev->commit_bytes_used = dev->bytes_used;
7291                         dev->has_pending_chunks = false;
7292                 }
7293         }
7294         mutex_unlock(&fs_info->chunk_mutex);
7295 }
7296
7297 void btrfs_set_fs_info_ptr(struct btrfs_fs_info *fs_info)
7298 {
7299         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7300         while (fs_devices) {
7301                 fs_devices->fs_info = fs_info;
7302                 fs_devices = fs_devices->seed;
7303         }
7304 }
7305
7306 void btrfs_reset_fs_info_ptr(struct btrfs_fs_info *fs_info)
7307 {
7308         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
7309         while (fs_devices) {
7310                 fs_devices->fs_info = NULL;
7311                 fs_devices = fs_devices->seed;
7312         }
7313 }
7314
7315 /*
7316  * Multiplicity factor for simple profiles: DUP, RAID1-like and RAID10.
7317  */
7318 int btrfs_bg_type_to_factor(u64 flags)
7319 {
7320         if (flags & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
7321                      BTRFS_BLOCK_GROUP_RAID10))
7322                 return 2;
7323         return 1;
7324 }
7325
7326
7327 static u64 calc_stripe_length(u64 type, u64 chunk_len, int num_stripes)
7328 {
7329         int index = btrfs_bg_flags_to_raid_index(type);
7330         int ncopies = btrfs_raid_array[index].ncopies;
7331         int data_stripes;
7332
7333         switch (type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
7334         case BTRFS_BLOCK_GROUP_RAID5:
7335                 data_stripes = num_stripes - 1;
7336                 break;
7337         case BTRFS_BLOCK_GROUP_RAID6:
7338                 data_stripes = num_stripes - 2;
7339                 break;
7340         default:
7341                 data_stripes = num_stripes / ncopies;
7342                 break;
7343         }
7344         return div_u64(chunk_len, data_stripes);
7345 }
7346
7347 static int verify_one_dev_extent(struct btrfs_fs_info *fs_info,
7348                                  u64 chunk_offset, u64 devid,
7349                                  u64 physical_offset, u64 physical_len)
7350 {
7351         struct extent_map_tree *em_tree = &fs_info->mapping_tree.map_tree;
7352         struct extent_map *em;
7353         struct map_lookup *map;
7354         struct btrfs_device *dev;
7355         u64 stripe_len;
7356         bool found = false;
7357         int ret = 0;
7358         int i;
7359
7360         read_lock(&em_tree->lock);
7361         em = lookup_extent_mapping(em_tree, chunk_offset, 1);
7362         read_unlock(&em_tree->lock);
7363
7364         if (!em) {
7365                 btrfs_err(fs_info,
7366 "dev extent physical offset %llu on devid %llu doesn't have corresponding chunk",
7367                           physical_offset, devid);
7368                 ret = -EUCLEAN;
7369                 goto out;
7370         }
7371
7372         map = em->map_lookup;
7373         stripe_len = calc_stripe_length(map->type, em->len, map->num_stripes);
7374         if (physical_len != stripe_len) {
7375                 btrfs_err(fs_info,
7376 "dev extent physical offset %llu on devid %llu length doesn't match chunk %llu, have %llu expect %llu",
7377                           physical_offset, devid, em->start, physical_len,
7378                           stripe_len);
7379                 ret = -EUCLEAN;
7380                 goto out;
7381         }
7382
7383         for (i = 0; i < map->num_stripes; i++) {
7384                 if (map->stripes[i].dev->devid == devid &&
7385                     map->stripes[i].physical == physical_offset) {
7386                         found = true;
7387                         if (map->verified_stripes >= map->num_stripes) {
7388                                 btrfs_err(fs_info,
7389                                 "too many dev extents for chunk %llu found",
7390                                           em->start);
7391                                 ret = -EUCLEAN;
7392                                 goto out;
7393                         }
7394                         map->verified_stripes++;
7395                         break;
7396                 }
7397         }
7398         if (!found) {
7399                 btrfs_err(fs_info,
7400         "dev extent physical offset %llu devid %llu has no corresponding chunk",
7401                         physical_offset, devid);
7402                 ret = -EUCLEAN;
7403         }
7404
7405         /* Make sure no dev extent is beyond device bondary */
7406         dev = btrfs_find_device(fs_info->fs_devices, devid, NULL, NULL, true);
7407         if (!dev) {
7408                 btrfs_err(fs_info, "failed to find devid %llu", devid);
7409                 ret = -EUCLEAN;
7410                 goto out;
7411         }
7412
7413         /* It's possible this device is a dummy for seed device */
7414         if (dev->disk_total_bytes == 0) {
7415                 dev = btrfs_find_device(fs_info->fs_devices->seed, devid,
7416                                         NULL, NULL, false);
7417                 if (!dev) {
7418                         btrfs_err(fs_info, "failed to find seed devid %llu",
7419                                   devid);
7420                         ret = -EUCLEAN;
7421                         goto out;
7422                 }
7423         }
7424
7425         if (physical_offset + physical_len > dev->disk_total_bytes) {
7426                 btrfs_err(fs_info,
7427 "dev extent devid %llu physical offset %llu len %llu is beyond device boundary %llu",
7428                           devid, physical_offset, physical_len,
7429                           dev->disk_total_bytes);
7430                 ret = -EUCLEAN;
7431                 goto out;
7432         }
7433 out:
7434         free_extent_map(em);
7435         return ret;
7436 }
7437
7438 static int verify_chunk_dev_extent_mapping(struct btrfs_fs_info *fs_info)
7439 {
7440         struct extent_map_tree *em_tree = &fs_info->mapping_tree.map_tree;
7441         struct extent_map *em;
7442         struct rb_node *node;
7443         int ret = 0;
7444
7445         read_lock(&em_tree->lock);
7446         for (node = rb_first(&em_tree->map); node; node = rb_next(node)) {
7447                 em = rb_entry(node, struct extent_map, rb_node);
7448                 if (em->map_lookup->num_stripes !=
7449                     em->map_lookup->verified_stripes) {
7450                         btrfs_err(fs_info,
7451                         "chunk %llu has missing dev extent, have %d expect %d",
7452                                   em->start, em->map_lookup->verified_stripes,
7453                                   em->map_lookup->num_stripes);
7454                         ret = -EUCLEAN;
7455                         goto out;
7456                 }
7457         }
7458 out:
7459         read_unlock(&em_tree->lock);
7460         return ret;
7461 }
7462
7463 /*
7464  * Ensure that all dev extents are mapped to correct chunk, otherwise
7465  * later chunk allocation/free would cause unexpected behavior.
7466  *
7467  * NOTE: This will iterate through the whole device tree, which should be of
7468  * the same size level as the chunk tree.  This slightly increases mount time.
7469  */
7470 int btrfs_verify_dev_extents(struct btrfs_fs_info *fs_info)
7471 {
7472         struct btrfs_path *path;
7473         struct btrfs_root *root = fs_info->dev_root;
7474         struct btrfs_key key;
7475         u64 prev_devid = 0;
7476         u64 prev_dev_ext_end = 0;
7477         int ret = 0;
7478
7479         key.objectid = 1;
7480         key.type = BTRFS_DEV_EXTENT_KEY;
7481         key.offset = 0;
7482
7483         path = btrfs_alloc_path();
7484         if (!path)
7485                 return -ENOMEM;
7486
7487         path->reada = READA_FORWARD;
7488         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7489         if (ret < 0)
7490                 goto out;
7491
7492         if (path->slots[0] >= btrfs_header_nritems(path->nodes[0])) {
7493                 ret = btrfs_next_item(root, path);
7494                 if (ret < 0)
7495                         goto out;
7496                 /* No dev extents at all? Not good */
7497                 if (ret > 0) {
7498                         ret = -EUCLEAN;
7499                         goto out;
7500                 }
7501         }
7502         while (1) {
7503                 struct extent_buffer *leaf = path->nodes[0];
7504                 struct btrfs_dev_extent *dext;
7505                 int slot = path->slots[0];
7506                 u64 chunk_offset;
7507                 u64 physical_offset;
7508                 u64 physical_len;
7509                 u64 devid;
7510
7511                 btrfs_item_key_to_cpu(leaf, &key, slot);
7512                 if (key.type != BTRFS_DEV_EXTENT_KEY)
7513                         break;
7514                 devid = key.objectid;
7515                 physical_offset = key.offset;
7516
7517                 dext = btrfs_item_ptr(leaf, slot, struct btrfs_dev_extent);
7518                 chunk_offset = btrfs_dev_extent_chunk_offset(leaf, dext);
7519                 physical_len = btrfs_dev_extent_length(leaf, dext);
7520
7521                 /* Check if this dev extent overlaps with the previous one */
7522                 if (devid == prev_devid && physical_offset < prev_dev_ext_end) {
7523                         btrfs_err(fs_info,
7524 "dev extent devid %llu physical offset %llu overlap with previous dev extent end %llu",
7525                                   devid, physical_offset, prev_dev_ext_end);
7526                         ret = -EUCLEAN;
7527                         goto out;
7528                 }
7529
7530                 ret = verify_one_dev_extent(fs_info, chunk_offset, devid,
7531                                             physical_offset, physical_len);
7532                 if (ret < 0)
7533                         goto out;
7534                 prev_devid = devid;
7535                 prev_dev_ext_end = physical_offset + physical_len;
7536
7537                 ret = btrfs_next_item(root, path);
7538                 if (ret < 0)
7539                         goto out;
7540                 if (ret > 0) {
7541                         ret = 0;
7542                         break;
7543                 }
7544         }
7545
7546         /* Ensure all chunks have corresponding dev extents */
7547         ret = verify_chunk_dev_extent_mapping(fs_info);
7548 out:
7549         btrfs_free_path(path);
7550         return ret;
7551 }