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