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