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