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