~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/fs/btrfs/volumes.c

Version: ~ [ linux-5.8-rc3 ] ~ [ linux-5.7.5 ] ~ [ linux-5.6.19 ] ~ [ linux-5.5.19 ] ~ [ linux-5.4.48 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.129 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.185 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.228 ] ~ [ linux-4.8.17 ] ~ [ linux-4.7.10 ] ~ [ linux-4.6.7 ] ~ [ linux-4.5.7 ] ~ [ linux-4.4.228 ] ~ [ linux-4.3.6 ] ~ [ linux-4.2.8 ] ~ [ linux-4.1.52 ] ~ [ linux-4.0.9 ] ~ [ linux-3.19.8 ] ~ [ linux-3.18.140 ] ~ [ linux-3.17.8 ] ~ [ linux-3.16.85 ] ~ [ linux-3.15.10 ] ~ [ linux-3.14.79 ] ~ [ linux-3.13.11 ] ~ [ linux-3.12.74 ] ~ [ linux-3.11.10 ] ~ [ linux-3.10.108 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.5 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

  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_device)
638 {
639         struct btrfs_fs_devices *fs_devices, *tmp_fs_devices;
640         struct btrfs_device *device, *tmp_device;
641 
642         list_for_each_entry_safe(fs_devices, tmp_fs_devices, &fs_uuids, fs_list) {
643                 mutex_lock(&fs_devices->device_list_mutex);
644                 if (fs_devices->opened) {
645                         mutex_unlock(&fs_devices->device_list_mutex);
646                         continue;
647                 }
648 
649                 list_for_each_entry_safe(device, tmp_device,
650                                          &fs_devices->devices, dev_list) {
651                         int not_found = 0;
652 
653                         if (skip_device && skip_device == device)
654                                 continue;
655                         if (path && !device->name)
656                                 continue;
657 
658                         rcu_read_lock();
659                         if (path)
660                                 not_found = strcmp(rcu_str_deref(device->name),
661                                                    path);
662                         rcu_read_unlock();
663                         if (not_found)
664                                 continue;
665 
666                         /* delete the stale device */
667                         fs_devices->num_devices--;
668                         list_del(&device->dev_list);
669                         btrfs_free_device(device);
670 
671                         if (fs_devices->num_devices == 0)
672                                 break;
673                 }
674                 mutex_unlock(&fs_devices->device_list_mutex);
675                 if (fs_devices->num_devices == 0) {
676                         btrfs_sysfs_remove_fsid(fs_devices);
677                         list_del(&fs_devices->fs_list);
678                         free_fs_devices(fs_devices);
679                 }
680         }
681 }
682 
683 static int btrfs_open_one_device(struct btrfs_fs_devices *fs_devices,
684                         struct btrfs_device *device, fmode_t flags,
685                         void *holder)
686 {
687         struct request_queue *q;
688         struct block_device *bdev;
689         struct buffer_head *bh;
690         struct btrfs_super_block *disk_super;
691         u64 devid;
692         int ret;
693 
694         if (device->bdev)
695                 return -EINVAL;
696         if (!device->name)
697                 return -EINVAL;
698 
699         ret = btrfs_get_bdev_and_sb(device->name->str, flags, holder, 1,
700                                     &bdev, &bh);
701         if (ret)
702                 return ret;
703 
704         disk_super = (struct btrfs_super_block *)bh->b_data;
705         devid = btrfs_stack_device_id(&disk_super->dev_item);
706         if (devid != device->devid)
707                 goto error_brelse;
708 
709         if (memcmp(device->uuid, disk_super->dev_item.uuid, BTRFS_UUID_SIZE))
710                 goto error_brelse;
711 
712         device->generation = btrfs_super_generation(disk_super);
713 
714         if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_SEEDING) {
715                 clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
716                 fs_devices->seeding = 1;
717         } else {
718                 if (bdev_read_only(bdev))
719                         clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
720                 else
721                         set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
722         }
723 
724         q = bdev_get_queue(bdev);
725         if (!blk_queue_nonrot(q))
726                 fs_devices->rotating = 1;
727 
728         device->bdev = bdev;
729         clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
730         device->mode = flags;
731 
732         fs_devices->open_devices++;
733         if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
734             device->devid != BTRFS_DEV_REPLACE_DEVID) {
735                 fs_devices->rw_devices++;
736                 list_add_tail(&device->dev_alloc_list, &fs_devices->alloc_list);
737         }
738         brelse(bh);
739 
740         return 0;
741 
742 error_brelse:
743         brelse(bh);
744         blkdev_put(bdev, flags);
745 
746         return -EINVAL;
747 }
748 
749 /*
750  * Add new device to list of registered devices
751  *
752  * Returns:
753  * device pointer which was just added or updated when successful
754  * error pointer when failed
755  */
756 static noinline struct btrfs_device *device_list_add(const char *path,
757                            struct btrfs_super_block *disk_super,
758                            bool *new_device_added)
759 {
760         struct btrfs_device *device;
761         struct btrfs_fs_devices *fs_devices;
762         struct rcu_string *name;
763         u64 found_transid = btrfs_super_generation(disk_super);
764         u64 devid = btrfs_stack_device_id(&disk_super->dev_item);
765 
766         fs_devices = find_fsid(disk_super->fsid);
767         if (!fs_devices) {
768                 fs_devices = alloc_fs_devices(disk_super->fsid);
769                 if (IS_ERR(fs_devices))
770                         return ERR_CAST(fs_devices);
771 
772                 mutex_lock(&fs_devices->device_list_mutex);
773                 list_add(&fs_devices->fs_list, &fs_uuids);
774 
775                 device = NULL;
776         } else {
777                 mutex_lock(&fs_devices->device_list_mutex);
778                 device = find_device(fs_devices, devid,
779                                 disk_super->dev_item.uuid);
780         }
781 
782         if (!device) {
783                 if (fs_devices->opened) {
784                         mutex_unlock(&fs_devices->device_list_mutex);
785                         return ERR_PTR(-EBUSY);
786                 }
787 
788                 device = btrfs_alloc_device(NULL, &devid,
789                                             disk_super->dev_item.uuid);
790                 if (IS_ERR(device)) {
791                         mutex_unlock(&fs_devices->device_list_mutex);
792                         /* we can safely leave the fs_devices entry around */
793                         return device;
794                 }
795 
796                 name = rcu_string_strdup(path, GFP_NOFS);
797                 if (!name) {
798                         btrfs_free_device(device);
799                         mutex_unlock(&fs_devices->device_list_mutex);
800                         return ERR_PTR(-ENOMEM);
801                 }
802                 rcu_assign_pointer(device->name, name);
803 
804                 list_add_rcu(&device->dev_list, &fs_devices->devices);
805                 fs_devices->num_devices++;
806 
807                 device->fs_devices = fs_devices;
808                 *new_device_added = true;
809 
810                 if (disk_super->label[0])
811                         pr_info("BTRFS: device label %s devid %llu transid %llu %s\n",
812                                 disk_super->label, devid, found_transid, path);
813                 else
814                         pr_info("BTRFS: device fsid %pU devid %llu transid %llu %s\n",
815                                 disk_super->fsid, devid, found_transid, path);
816 
817         } else if (!device->name || strcmp(device->name->str, path)) {
818                 /*
819                  * When FS is already mounted.
820                  * 1. If you are here and if the device->name is NULL that
821                  *    means this device was missing at time of FS mount.
822                  * 2. If you are here and if the device->name is different
823                  *    from 'path' that means either
824                  *      a. The same device disappeared and reappeared with
825                  *         different name. or
826                  *      b. The missing-disk-which-was-replaced, has
827                  *         reappeared now.
828                  *
829                  * We must allow 1 and 2a above. But 2b would be a spurious
830                  * and unintentional.
831                  *
832                  * Further in case of 1 and 2a above, the disk at 'path'
833                  * would have missed some transaction when it was away and
834                  * in case of 2a the stale bdev has to be updated as well.
835                  * 2b must not be allowed at all time.
836                  */
837 
838                 /*
839                  * For now, we do allow update to btrfs_fs_device through the
840                  * btrfs dev scan cli after FS has been mounted.  We're still
841                  * tracking a problem where systems fail mount by subvolume id
842                  * when we reject replacement on a mounted FS.
843                  */
844                 if (!fs_devices->opened && found_transid < device->generation) {
845                         /*
846                          * That is if the FS is _not_ mounted and if you
847                          * are here, that means there is more than one
848                          * disk with same uuid and devid.We keep the one
849                          * with larger generation number or the last-in if
850                          * generation are equal.
851                          */
852                         mutex_unlock(&fs_devices->device_list_mutex);
853                         return ERR_PTR(-EEXIST);
854                 }
855 
856                 name = rcu_string_strdup(path, GFP_NOFS);
857                 if (!name) {
858                         mutex_unlock(&fs_devices->device_list_mutex);
859                         return ERR_PTR(-ENOMEM);
860                 }
861                 rcu_string_free(device->name);
862                 rcu_assign_pointer(device->name, name);
863                 if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state)) {
864                         fs_devices->missing_devices--;
865                         clear_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state);
866                 }
867         }
868 
869         /*
870          * Unmount does not free the btrfs_device struct but would zero
871          * generation along with most of the other members. So just update
872          * it back. We need it to pick the disk with largest generation
873          * (as above).
874          */
875         if (!fs_devices->opened)
876                 device->generation = found_transid;
877 
878         fs_devices->total_devices = btrfs_super_num_devices(disk_super);
879 
880         mutex_unlock(&fs_devices->device_list_mutex);
881         return device;
882 }
883 
884 static struct btrfs_fs_devices *clone_fs_devices(struct btrfs_fs_devices *orig)
885 {
886         struct btrfs_fs_devices *fs_devices;
887         struct btrfs_device *device;
888         struct btrfs_device *orig_dev;
889 
890         fs_devices = alloc_fs_devices(orig->fsid);
891         if (IS_ERR(fs_devices))
892                 return fs_devices;
893 
894         mutex_lock(&orig->device_list_mutex);
895         fs_devices->total_devices = orig->total_devices;
896 
897         /* We have held the volume lock, it is safe to get the devices. */
898         list_for_each_entry(orig_dev, &orig->devices, dev_list) {
899                 struct rcu_string *name;
900 
901                 device = btrfs_alloc_device(NULL, &orig_dev->devid,
902                                             orig_dev->uuid);
903                 if (IS_ERR(device))
904                         goto error;
905 
906                 /*
907                  * This is ok to do without rcu read locked because we hold the
908                  * uuid mutex so nothing we touch in here is going to disappear.
909                  */
910                 if (orig_dev->name) {
911                         name = rcu_string_strdup(orig_dev->name->str,
912                                         GFP_KERNEL);
913                         if (!name) {
914                                 btrfs_free_device(device);
915                                 goto error;
916                         }
917                         rcu_assign_pointer(device->name, name);
918                 }
919 
920                 list_add(&device->dev_list, &fs_devices->devices);
921                 device->fs_devices = fs_devices;
922                 fs_devices->num_devices++;
923         }
924         mutex_unlock(&orig->device_list_mutex);
925         return fs_devices;
926 error:
927         mutex_unlock(&orig->device_list_mutex);
928         free_fs_devices(fs_devices);
929         return ERR_PTR(-ENOMEM);
930 }
931 
932 /*
933  * After we have read the system tree and know devids belonging to
934  * this filesystem, remove the device which does not belong there.
935  */
936 void btrfs_free_extra_devids(struct btrfs_fs_devices *fs_devices, int step)
937 {
938         struct btrfs_device *device, *next;
939         struct btrfs_device *latest_dev = NULL;
940 
941         mutex_lock(&uuid_mutex);
942 again:
943         /* This is the initialized path, it is safe to release the devices. */
944         list_for_each_entry_safe(device, next, &fs_devices->devices, dev_list) {
945                 if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
946                                                         &device->dev_state)) {
947                         if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
948                              &device->dev_state) &&
949                              (!latest_dev ||
950                               device->generation > latest_dev->generation)) {
951                                 latest_dev = device;
952                         }
953                         continue;
954                 }
955 
956                 if (device->devid == BTRFS_DEV_REPLACE_DEVID) {
957                         /*
958                          * In the first step, keep the device which has
959                          * the correct fsid and the devid that is used
960                          * for the dev_replace procedure.
961                          * In the second step, the dev_replace state is
962                          * read from the device tree and it is known
963                          * whether the procedure is really active or
964                          * not, which means whether this device is
965                          * used or whether it should be removed.
966                          */
967                         if (step == 0 || test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
968                                                   &device->dev_state)) {
969                                 continue;
970                         }
971                 }
972                 if (device->bdev) {
973                         blkdev_put(device->bdev, device->mode);
974                         device->bdev = NULL;
975                         fs_devices->open_devices--;
976                 }
977                 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
978                         list_del_init(&device->dev_alloc_list);
979                         clear_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
980                         if (!test_bit(BTRFS_DEV_STATE_REPLACE_TGT,
981                                       &device->dev_state))
982                                 fs_devices->rw_devices--;
983                 }
984                 list_del_init(&device->dev_list);
985                 fs_devices->num_devices--;
986                 btrfs_free_device(device);
987         }
988 
989         if (fs_devices->seed) {
990                 fs_devices = fs_devices->seed;
991                 goto again;
992         }
993 
994         fs_devices->latest_bdev = latest_dev->bdev;
995 
996         mutex_unlock(&uuid_mutex);
997 }
998 
999 static void free_device_rcu(struct rcu_head *head)
1000 {
1001         struct btrfs_device *device;
1002 
1003         device = container_of(head, struct btrfs_device, rcu);
1004         btrfs_free_device(device);
1005 }
1006 
1007 static void btrfs_close_bdev(struct btrfs_device *device)
1008 {
1009         if (!device->bdev)
1010                 return;
1011 
1012         if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
1013                 sync_blockdev(device->bdev);
1014                 invalidate_bdev(device->bdev);
1015         }
1016 
1017         blkdev_put(device->bdev, device->mode);
1018 }
1019 
1020 static void btrfs_prepare_close_one_device(struct btrfs_device *device)
1021 {
1022         struct btrfs_fs_devices *fs_devices = device->fs_devices;
1023         struct btrfs_device *new_device;
1024         struct rcu_string *name;
1025 
1026         if (device->bdev)
1027                 fs_devices->open_devices--;
1028 
1029         if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1030             device->devid != BTRFS_DEV_REPLACE_DEVID) {
1031                 list_del_init(&device->dev_alloc_list);
1032                 fs_devices->rw_devices--;
1033         }
1034 
1035         if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
1036                 fs_devices->missing_devices--;
1037 
1038         new_device = btrfs_alloc_device(NULL, &device->devid,
1039                                         device->uuid);
1040         BUG_ON(IS_ERR(new_device)); /* -ENOMEM */
1041 
1042         /* Safe because we are under uuid_mutex */
1043         if (device->name) {
1044                 name = rcu_string_strdup(device->name->str, GFP_NOFS);
1045                 BUG_ON(!name); /* -ENOMEM */
1046                 rcu_assign_pointer(new_device->name, name);
1047         }
1048 
1049         list_replace_rcu(&device->dev_list, &new_device->dev_list);
1050         new_device->fs_devices = device->fs_devices;
1051 }
1052 
1053 static int close_fs_devices(struct btrfs_fs_devices *fs_devices)
1054 {
1055         struct btrfs_device *device, *tmp;
1056         struct list_head pending_put;
1057 
1058         INIT_LIST_HEAD(&pending_put);
1059 
1060         if (--fs_devices->opened > 0)
1061                 return 0;
1062 
1063         mutex_lock(&fs_devices->device_list_mutex);
1064         list_for_each_entry_safe(device, tmp, &fs_devices->devices, dev_list) {
1065                 btrfs_prepare_close_one_device(device);
1066                 list_add(&device->dev_list, &pending_put);
1067         }
1068         mutex_unlock(&fs_devices->device_list_mutex);
1069 
1070         /*
1071          * btrfs_show_devname() is using the device_list_mutex,
1072          * sometimes call to blkdev_put() leads vfs calling
1073          * into this func. So do put outside of device_list_mutex,
1074          * as of now.
1075          */
1076         while (!list_empty(&pending_put)) {
1077                 device = list_first_entry(&pending_put,
1078                                 struct btrfs_device, dev_list);
1079                 list_del(&device->dev_list);
1080                 btrfs_close_bdev(device);
1081                 call_rcu(&device->rcu, free_device_rcu);
1082         }
1083 
1084         WARN_ON(fs_devices->open_devices);
1085         WARN_ON(fs_devices->rw_devices);
1086         fs_devices->opened = 0;
1087         fs_devices->seeding = 0;
1088 
1089         return 0;
1090 }
1091 
1092 int btrfs_close_devices(struct btrfs_fs_devices *fs_devices)
1093 {
1094         struct btrfs_fs_devices *seed_devices = NULL;
1095         int ret;
1096 
1097         mutex_lock(&uuid_mutex);
1098         ret = close_fs_devices(fs_devices);
1099         if (!fs_devices->opened) {
1100                 seed_devices = fs_devices->seed;
1101                 fs_devices->seed = NULL;
1102         }
1103         mutex_unlock(&uuid_mutex);
1104 
1105         while (seed_devices) {
1106                 fs_devices = seed_devices;
1107                 seed_devices = fs_devices->seed;
1108                 close_fs_devices(fs_devices);
1109                 free_fs_devices(fs_devices);
1110         }
1111         return ret;
1112 }
1113 
1114 static int open_fs_devices(struct btrfs_fs_devices *fs_devices,
1115                                 fmode_t flags, void *holder)
1116 {
1117         struct btrfs_device *device;
1118         struct btrfs_device *latest_dev = NULL;
1119         int ret = 0;
1120 
1121         flags |= FMODE_EXCL;
1122 
1123         list_for_each_entry(device, &fs_devices->devices, dev_list) {
1124                 /* Just open everything we can; ignore failures here */
1125                 if (btrfs_open_one_device(fs_devices, device, flags, holder))
1126                         continue;
1127 
1128                 if (!latest_dev ||
1129                     device->generation > latest_dev->generation)
1130                         latest_dev = device;
1131         }
1132         if (fs_devices->open_devices == 0) {
1133                 ret = -EINVAL;
1134                 goto out;
1135         }
1136         fs_devices->opened = 1;
1137         fs_devices->latest_bdev = latest_dev->bdev;
1138         fs_devices->total_rw_bytes = 0;
1139 out:
1140         return ret;
1141 }
1142 
1143 static int devid_cmp(void *priv, struct list_head *a, struct list_head *b)
1144 {
1145         struct btrfs_device *dev1, *dev2;
1146 
1147         dev1 = list_entry(a, struct btrfs_device, dev_list);
1148         dev2 = list_entry(b, struct btrfs_device, dev_list);
1149 
1150         if (dev1->devid < dev2->devid)
1151                 return -1;
1152         else if (dev1->devid > dev2->devid)
1153                 return 1;
1154         return 0;
1155 }
1156 
1157 int btrfs_open_devices(struct btrfs_fs_devices *fs_devices,
1158                        fmode_t flags, void *holder)
1159 {
1160         int ret;
1161 
1162         lockdep_assert_held(&uuid_mutex);
1163 
1164         mutex_lock(&fs_devices->device_list_mutex);
1165         if (fs_devices->opened) {
1166                 fs_devices->opened++;
1167                 ret = 0;
1168         } else {
1169                 list_sort(NULL, &fs_devices->devices, devid_cmp);
1170                 ret = open_fs_devices(fs_devices, flags, holder);
1171         }
1172         mutex_unlock(&fs_devices->device_list_mutex);
1173 
1174         return ret;
1175 }
1176 
1177 static void btrfs_release_disk_super(struct page *page)
1178 {
1179         kunmap(page);
1180         put_page(page);
1181 }
1182 
1183 static int btrfs_read_disk_super(struct block_device *bdev, u64 bytenr,
1184                                  struct page **page,
1185                                  struct btrfs_super_block **disk_super)
1186 {
1187         void *p;
1188         pgoff_t index;
1189 
1190         /* make sure our super fits in the device */
1191         if (bytenr + PAGE_SIZE >= i_size_read(bdev->bd_inode))
1192                 return 1;
1193 
1194         /* make sure our super fits in the page */
1195         if (sizeof(**disk_super) > PAGE_SIZE)
1196                 return 1;
1197 
1198         /* make sure our super doesn't straddle pages on disk */
1199         index = bytenr >> PAGE_SHIFT;
1200         if ((bytenr + sizeof(**disk_super) - 1) >> PAGE_SHIFT != index)
1201                 return 1;
1202 
1203         /* pull in the page with our super */
1204         *page = read_cache_page_gfp(bdev->bd_inode->i_mapping,
1205                                    index, GFP_KERNEL);
1206 
1207         if (IS_ERR_OR_NULL(*page))
1208                 return 1;
1209 
1210         p = kmap(*page);
1211 
1212         /* align our pointer to the offset of the super block */
1213         *disk_super = p + (bytenr & ~PAGE_MASK);
1214 
1215         if (btrfs_super_bytenr(*disk_super) != bytenr ||
1216             btrfs_super_magic(*disk_super) != BTRFS_MAGIC) {
1217                 btrfs_release_disk_super(*page);
1218                 return 1;
1219         }
1220 
1221         if ((*disk_super)->label[0] &&
1222                 (*disk_super)->label[BTRFS_LABEL_SIZE - 1])
1223                 (*disk_super)->label[BTRFS_LABEL_SIZE - 1] = '\0';
1224 
1225         return 0;
1226 }
1227 
1228 /*
1229  * Look for a btrfs signature on a device. This may be called out of the mount path
1230  * and we are not allowed to call set_blocksize during the scan. The superblock
1231  * is read via pagecache
1232  */
1233 int btrfs_scan_one_device(const char *path, fmode_t flags, void *holder,
1234                           struct btrfs_fs_devices **fs_devices_ret)
1235 {
1236         struct btrfs_super_block *disk_super;
1237         bool new_device_added = false;
1238         struct btrfs_device *device;
1239         struct block_device *bdev;
1240         struct page *page;
1241         int ret = 0;
1242         u64 bytenr;
1243 
1244         lockdep_assert_held(&uuid_mutex);
1245 
1246         /*
1247          * we would like to check all the supers, but that would make
1248          * a btrfs mount succeed after a mkfs from a different FS.
1249          * So, we need to add a special mount option to scan for
1250          * later supers, using BTRFS_SUPER_MIRROR_MAX instead
1251          */
1252         bytenr = btrfs_sb_offset(0);
1253         flags |= FMODE_EXCL;
1254 
1255         bdev = blkdev_get_by_path(path, flags, holder);
1256         if (IS_ERR(bdev))
1257                 return PTR_ERR(bdev);
1258 
1259         if (btrfs_read_disk_super(bdev, bytenr, &page, &disk_super)) {
1260                 ret = -EINVAL;
1261                 goto error_bdev_put;
1262         }
1263 
1264         device = device_list_add(path, disk_super, &new_device_added);
1265         if (IS_ERR(device)) {
1266                 ret = PTR_ERR(device);
1267         } else {
1268                 *fs_devices_ret = device->fs_devices;
1269                 if (new_device_added)
1270                         btrfs_free_stale_devices(path, device);
1271         }
1272 
1273         btrfs_release_disk_super(page);
1274 
1275 error_bdev_put:
1276         blkdev_put(bdev, flags);
1277 
1278         return ret;
1279 }
1280 
1281 /* helper to account the used device space in the range */
1282 int btrfs_account_dev_extents_size(struct btrfs_device *device, u64 start,
1283                                    u64 end, u64 *length)
1284 {
1285         struct btrfs_key key;
1286         struct btrfs_root *root = device->fs_info->dev_root;
1287         struct btrfs_dev_extent *dev_extent;
1288         struct btrfs_path *path;
1289         u64 extent_end;
1290         int ret;
1291         int slot;
1292         struct extent_buffer *l;
1293 
1294         *length = 0;
1295 
1296         if (start >= device->total_bytes ||
1297                 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
1298                 return 0;
1299 
1300         path = btrfs_alloc_path();
1301         if (!path)
1302                 return -ENOMEM;
1303         path->reada = READA_FORWARD;
1304 
1305         key.objectid = device->devid;
1306         key.offset = start;
1307         key.type = BTRFS_DEV_EXTENT_KEY;
1308 
1309         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1310         if (ret < 0)
1311                 goto out;
1312         if (ret > 0) {
1313                 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1314                 if (ret < 0)
1315                         goto out;
1316         }
1317 
1318         while (1) {
1319                 l = path->nodes[0];
1320                 slot = path->slots[0];
1321                 if (slot >= btrfs_header_nritems(l)) {
1322                         ret = btrfs_next_leaf(root, path);
1323                         if (ret == 0)
1324                                 continue;
1325                         if (ret < 0)
1326                                 goto out;
1327 
1328                         break;
1329                 }
1330                 btrfs_item_key_to_cpu(l, &key, slot);
1331 
1332                 if (key.objectid < device->devid)
1333                         goto next;
1334 
1335                 if (key.objectid > device->devid)
1336                         break;
1337 
1338                 if (key.type != BTRFS_DEV_EXTENT_KEY)
1339                         goto next;
1340 
1341                 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1342                 extent_end = key.offset + btrfs_dev_extent_length(l,
1343                                                                   dev_extent);
1344                 if (key.offset <= start && extent_end > end) {
1345                         *length = end - start + 1;
1346                         break;
1347                 } else if (key.offset <= start && extent_end > start)
1348                         *length += extent_end - start;
1349                 else if (key.offset > start && extent_end <= end)
1350                         *length += extent_end - key.offset;
1351                 else if (key.offset > start && key.offset <= end) {
1352                         *length += end - key.offset + 1;
1353                         break;
1354                 } else if (key.offset > end)
1355                         break;
1356 
1357 next:
1358                 path->slots[0]++;
1359         }
1360         ret = 0;
1361 out:
1362         btrfs_free_path(path);
1363         return ret;
1364 }
1365 
1366 static int contains_pending_extent(struct btrfs_transaction *transaction,
1367                                    struct btrfs_device *device,
1368                                    u64 *start, u64 len)
1369 {
1370         struct btrfs_fs_info *fs_info = device->fs_info;
1371         struct extent_map *em;
1372         struct list_head *search_list = &fs_info->pinned_chunks;
1373         int ret = 0;
1374         u64 physical_start = *start;
1375 
1376         if (transaction)
1377                 search_list = &transaction->pending_chunks;
1378 again:
1379         list_for_each_entry(em, search_list, list) {
1380                 struct map_lookup *map;
1381                 int i;
1382 
1383                 map = em->map_lookup;
1384                 for (i = 0; i < map->num_stripes; i++) {
1385                         u64 end;
1386 
1387                         if (map->stripes[i].dev != device)
1388                                 continue;
1389                         if (map->stripes[i].physical >= physical_start + len ||
1390                             map->stripes[i].physical + em->orig_block_len <=
1391                             physical_start)
1392                                 continue;
1393                         /*
1394                          * Make sure that while processing the pinned list we do
1395                          * not override our *start with a lower value, because
1396                          * we can have pinned chunks that fall within this
1397                          * device hole and that have lower physical addresses
1398                          * than the pending chunks we processed before. If we
1399                          * do not take this special care we can end up getting
1400                          * 2 pending chunks that start at the same physical
1401                          * device offsets because the end offset of a pinned
1402                          * chunk can be equal to the start offset of some
1403                          * pending chunk.
1404                          */
1405                         end = map->stripes[i].physical + em->orig_block_len;
1406                         if (end > *start) {
1407                                 *start = end;
1408                                 ret = 1;
1409                         }
1410                 }
1411         }
1412         if (search_list != &fs_info->pinned_chunks) {
1413                 search_list = &fs_info->pinned_chunks;
1414                 goto again;
1415         }
1416 
1417         return ret;
1418 }
1419 
1420 
1421 /*
1422  * find_free_dev_extent_start - find free space in the specified device
1423  * @device:       the device which we search the free space in
1424  * @num_bytes:    the size of the free space that we need
1425  * @search_start: the position from which to begin the search
1426  * @start:        store the start of the free space.
1427  * @len:          the size of the free space. that we find, or the size
1428  *                of the max free space if we don't find suitable free space
1429  *
1430  * this uses a pretty simple search, the expectation is that it is
1431  * called very infrequently and that a given device has a small number
1432  * of extents
1433  *
1434  * @start is used to store the start of the free space if we find. But if we
1435  * don't find suitable free space, it will be used to store the start position
1436  * of the max free space.
1437  *
1438  * @len is used to store the size of the free space that we find.
1439  * But if we don't find suitable free space, it is used to store the size of
1440  * the max free space.
1441  */
1442 int find_free_dev_extent_start(struct btrfs_transaction *transaction,
1443                                struct btrfs_device *device, u64 num_bytes,
1444                                u64 search_start, u64 *start, u64 *len)
1445 {
1446         struct btrfs_fs_info *fs_info = device->fs_info;
1447         struct btrfs_root *root = fs_info->dev_root;
1448         struct btrfs_key key;
1449         struct btrfs_dev_extent *dev_extent;
1450         struct btrfs_path *path;
1451         u64 hole_size;
1452         u64 max_hole_start;
1453         u64 max_hole_size;
1454         u64 extent_end;
1455         u64 search_end = device->total_bytes;
1456         int ret;
1457         int slot;
1458         struct extent_buffer *l;
1459 
1460         /*
1461          * We don't want to overwrite the superblock on the drive nor any area
1462          * used by the boot loader (grub for example), so we make sure to start
1463          * at an offset of at least 1MB.
1464          */
1465         search_start = max_t(u64, search_start, SZ_1M);
1466 
1467         path = btrfs_alloc_path();
1468         if (!path)
1469                 return -ENOMEM;
1470 
1471         max_hole_start = search_start;
1472         max_hole_size = 0;
1473 
1474 again:
1475         if (search_start >= search_end ||
1476                 test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1477                 ret = -ENOSPC;
1478                 goto out;
1479         }
1480 
1481         path->reada = READA_FORWARD;
1482         path->search_commit_root = 1;
1483         path->skip_locking = 1;
1484 
1485         key.objectid = device->devid;
1486         key.offset = search_start;
1487         key.type = BTRFS_DEV_EXTENT_KEY;
1488 
1489         ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
1490         if (ret < 0)
1491                 goto out;
1492         if (ret > 0) {
1493                 ret = btrfs_previous_item(root, path, key.objectid, key.type);
1494                 if (ret < 0)
1495                         goto out;
1496         }
1497 
1498         while (1) {
1499                 l = path->nodes[0];
1500                 slot = path->slots[0];
1501                 if (slot >= btrfs_header_nritems(l)) {
1502                         ret = btrfs_next_leaf(root, path);
1503                         if (ret == 0)
1504                                 continue;
1505                         if (ret < 0)
1506                                 goto out;
1507 
1508                         break;
1509                 }
1510                 btrfs_item_key_to_cpu(l, &key, slot);
1511 
1512                 if (key.objectid < device->devid)
1513                         goto next;
1514 
1515                 if (key.objectid > device->devid)
1516                         break;
1517 
1518                 if (key.type != BTRFS_DEV_EXTENT_KEY)
1519                         goto next;
1520 
1521                 if (key.offset > search_start) {
1522                         hole_size = key.offset - search_start;
1523 
1524                         /*
1525                          * Have to check before we set max_hole_start, otherwise
1526                          * we could end up sending back this offset anyway.
1527                          */
1528                         if (contains_pending_extent(transaction, device,
1529                                                     &search_start,
1530                                                     hole_size)) {
1531                                 if (key.offset >= search_start) {
1532                                         hole_size = key.offset - search_start;
1533                                 } else {
1534                                         WARN_ON_ONCE(1);
1535                                         hole_size = 0;
1536                                 }
1537                         }
1538 
1539                         if (hole_size > max_hole_size) {
1540                                 max_hole_start = search_start;
1541                                 max_hole_size = hole_size;
1542                         }
1543 
1544                         /*
1545                          * If this free space is greater than which we need,
1546                          * it must be the max free space that we have found
1547                          * until now, so max_hole_start must point to the start
1548                          * of this free space and the length of this free space
1549                          * is stored in max_hole_size. Thus, we return
1550                          * max_hole_start and max_hole_size and go back to the
1551                          * caller.
1552                          */
1553                         if (hole_size >= num_bytes) {
1554                                 ret = 0;
1555                                 goto out;
1556                         }
1557                 }
1558 
1559                 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
1560                 extent_end = key.offset + btrfs_dev_extent_length(l,
1561                                                                   dev_extent);
1562                 if (extent_end > search_start)
1563                         search_start = extent_end;
1564 next:
1565                 path->slots[0]++;
1566                 cond_resched();
1567         }
1568 
1569         /*
1570          * At this point, search_start should be the end of
1571          * allocated dev extents, and when shrinking the device,
1572          * search_end may be smaller than search_start.
1573          */
1574         if (search_end > search_start) {
1575                 hole_size = search_end - search_start;
1576 
1577                 if (contains_pending_extent(transaction, device, &search_start,
1578                                             hole_size)) {
1579                         btrfs_release_path(path);
1580                         goto again;
1581                 }
1582 
1583                 if (hole_size > max_hole_size) {
1584                         max_hole_start = search_start;
1585                         max_hole_size = hole_size;
1586                 }
1587         }
1588 
1589         /* See above. */
1590         if (max_hole_size < num_bytes)
1591                 ret = -ENOSPC;
1592         else
1593                 ret = 0;
1594 
1595 out:
1596         btrfs_free_path(path);
1597         *start = max_hole_start;
1598         if (len)
1599                 *len = max_hole_size;
1600         return ret;
1601 }
1602 
1603 int find_free_dev_extent(struct btrfs_trans_handle *trans,
1604                          struct btrfs_device *device, u64 num_bytes,
1605                          u64 *start, u64 *len)
1606 {
1607         /* FIXME use last free of some kind */
1608         return find_free_dev_extent_start(trans->transaction, device,
1609                                           num_bytes, 0, start, len);
1610 }
1611 
1612 static int btrfs_free_dev_extent(struct btrfs_trans_handle *trans,
1613                           struct btrfs_device *device,
1614                           u64 start, u64 *dev_extent_len)
1615 {
1616         struct btrfs_fs_info *fs_info = device->fs_info;
1617         struct btrfs_root *root = fs_info->dev_root;
1618         int ret;
1619         struct btrfs_path *path;
1620         struct btrfs_key key;
1621         struct btrfs_key found_key;
1622         struct extent_buffer *leaf = NULL;
1623         struct btrfs_dev_extent *extent = NULL;
1624 
1625         path = btrfs_alloc_path();
1626         if (!path)
1627                 return -ENOMEM;
1628 
1629         key.objectid = device->devid;
1630         key.offset = start;
1631         key.type = BTRFS_DEV_EXTENT_KEY;
1632 again:
1633         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1634         if (ret > 0) {
1635                 ret = btrfs_previous_item(root, path, key.objectid,
1636                                           BTRFS_DEV_EXTENT_KEY);
1637                 if (ret)
1638                         goto out;
1639                 leaf = path->nodes[0];
1640                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1641                 extent = btrfs_item_ptr(leaf, path->slots[0],
1642                                         struct btrfs_dev_extent);
1643                 BUG_ON(found_key.offset > start || found_key.offset +
1644                        btrfs_dev_extent_length(leaf, extent) < start);
1645                 key = found_key;
1646                 btrfs_release_path(path);
1647                 goto again;
1648         } else if (ret == 0) {
1649                 leaf = path->nodes[0];
1650                 extent = btrfs_item_ptr(leaf, path->slots[0],
1651                                         struct btrfs_dev_extent);
1652         } else {
1653                 btrfs_handle_fs_error(fs_info, ret, "Slot search failed");
1654                 goto out;
1655         }
1656 
1657         *dev_extent_len = btrfs_dev_extent_length(leaf, extent);
1658 
1659         ret = btrfs_del_item(trans, root, path);
1660         if (ret) {
1661                 btrfs_handle_fs_error(fs_info, ret,
1662                                       "Failed to remove dev extent item");
1663         } else {
1664                 set_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags);
1665         }
1666 out:
1667         btrfs_free_path(path);
1668         return ret;
1669 }
1670 
1671 static int btrfs_alloc_dev_extent(struct btrfs_trans_handle *trans,
1672                                   struct btrfs_device *device,
1673                                   u64 chunk_offset, u64 start, u64 num_bytes)
1674 {
1675         int ret;
1676         struct btrfs_path *path;
1677         struct btrfs_fs_info *fs_info = device->fs_info;
1678         struct btrfs_root *root = fs_info->dev_root;
1679         struct btrfs_dev_extent *extent;
1680         struct extent_buffer *leaf;
1681         struct btrfs_key key;
1682 
1683         WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state));
1684         WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
1685         path = btrfs_alloc_path();
1686         if (!path)
1687                 return -ENOMEM;
1688 
1689         key.objectid = device->devid;
1690         key.offset = start;
1691         key.type = BTRFS_DEV_EXTENT_KEY;
1692         ret = btrfs_insert_empty_item(trans, root, path, &key,
1693                                       sizeof(*extent));
1694         if (ret)
1695                 goto out;
1696 
1697         leaf = path->nodes[0];
1698         extent = btrfs_item_ptr(leaf, path->slots[0],
1699                                 struct btrfs_dev_extent);
1700         btrfs_set_dev_extent_chunk_tree(leaf, extent,
1701                                         BTRFS_CHUNK_TREE_OBJECTID);
1702         btrfs_set_dev_extent_chunk_objectid(leaf, extent,
1703                                             BTRFS_FIRST_CHUNK_TREE_OBJECTID);
1704         btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
1705 
1706         btrfs_set_dev_extent_length(leaf, extent, num_bytes);
1707         btrfs_mark_buffer_dirty(leaf);
1708 out:
1709         btrfs_free_path(path);
1710         return ret;
1711 }
1712 
1713 static u64 find_next_chunk(struct btrfs_fs_info *fs_info)
1714 {
1715         struct extent_map_tree *em_tree;
1716         struct extent_map *em;
1717         struct rb_node *n;
1718         u64 ret = 0;
1719 
1720         em_tree = &fs_info->mapping_tree.map_tree;
1721         read_lock(&em_tree->lock);
1722         n = rb_last(&em_tree->map);
1723         if (n) {
1724                 em = rb_entry(n, struct extent_map, rb_node);
1725                 ret = em->start + em->len;
1726         }
1727         read_unlock(&em_tree->lock);
1728 
1729         return ret;
1730 }
1731 
1732 static noinline int find_next_devid(struct btrfs_fs_info *fs_info,
1733                                     u64 *devid_ret)
1734 {
1735         int ret;
1736         struct btrfs_key key;
1737         struct btrfs_key found_key;
1738         struct btrfs_path *path;
1739 
1740         path = btrfs_alloc_path();
1741         if (!path)
1742                 return -ENOMEM;
1743 
1744         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1745         key.type = BTRFS_DEV_ITEM_KEY;
1746         key.offset = (u64)-1;
1747 
1748         ret = btrfs_search_slot(NULL, fs_info->chunk_root, &key, path, 0, 0);
1749         if (ret < 0)
1750                 goto error;
1751 
1752         BUG_ON(ret == 0); /* Corruption */
1753 
1754         ret = btrfs_previous_item(fs_info->chunk_root, path,
1755                                   BTRFS_DEV_ITEMS_OBJECTID,
1756                                   BTRFS_DEV_ITEM_KEY);
1757         if (ret) {
1758                 *devid_ret = 1;
1759         } else {
1760                 btrfs_item_key_to_cpu(path->nodes[0], &found_key,
1761                                       path->slots[0]);
1762                 *devid_ret = found_key.offset + 1;
1763         }
1764         ret = 0;
1765 error:
1766         btrfs_free_path(path);
1767         return ret;
1768 }
1769 
1770 /*
1771  * the device information is stored in the chunk root
1772  * the btrfs_device struct should be fully filled in
1773  */
1774 static int btrfs_add_dev_item(struct btrfs_trans_handle *trans,
1775                             struct btrfs_fs_info *fs_info,
1776                             struct btrfs_device *device)
1777 {
1778         struct btrfs_root *root = fs_info->chunk_root;
1779         int ret;
1780         struct btrfs_path *path;
1781         struct btrfs_dev_item *dev_item;
1782         struct extent_buffer *leaf;
1783         struct btrfs_key key;
1784         unsigned long ptr;
1785 
1786         path = btrfs_alloc_path();
1787         if (!path)
1788                 return -ENOMEM;
1789 
1790         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1791         key.type = BTRFS_DEV_ITEM_KEY;
1792         key.offset = device->devid;
1793 
1794         ret = btrfs_insert_empty_item(trans, root, path, &key,
1795                                       sizeof(*dev_item));
1796         if (ret)
1797                 goto out;
1798 
1799         leaf = path->nodes[0];
1800         dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
1801 
1802         btrfs_set_device_id(leaf, dev_item, device->devid);
1803         btrfs_set_device_generation(leaf, dev_item, 0);
1804         btrfs_set_device_type(leaf, dev_item, device->type);
1805         btrfs_set_device_io_align(leaf, dev_item, device->io_align);
1806         btrfs_set_device_io_width(leaf, dev_item, device->io_width);
1807         btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
1808         btrfs_set_device_total_bytes(leaf, dev_item,
1809                                      btrfs_device_get_disk_total_bytes(device));
1810         btrfs_set_device_bytes_used(leaf, dev_item,
1811                                     btrfs_device_get_bytes_used(device));
1812         btrfs_set_device_group(leaf, dev_item, 0);
1813         btrfs_set_device_seek_speed(leaf, dev_item, 0);
1814         btrfs_set_device_bandwidth(leaf, dev_item, 0);
1815         btrfs_set_device_start_offset(leaf, dev_item, 0);
1816 
1817         ptr = btrfs_device_uuid(dev_item);
1818         write_extent_buffer(leaf, device->uuid, ptr, BTRFS_UUID_SIZE);
1819         ptr = btrfs_device_fsid(dev_item);
1820         write_extent_buffer(leaf, fs_info->fsid, ptr, BTRFS_FSID_SIZE);
1821         btrfs_mark_buffer_dirty(leaf);
1822 
1823         ret = 0;
1824 out:
1825         btrfs_free_path(path);
1826         return ret;
1827 }
1828 
1829 /*
1830  * Function to update ctime/mtime for a given device path.
1831  * Mainly used for ctime/mtime based probe like libblkid.
1832  */
1833 static void update_dev_time(const char *path_name)
1834 {
1835         struct file *filp;
1836 
1837         filp = filp_open(path_name, O_RDWR, 0);
1838         if (IS_ERR(filp))
1839                 return;
1840         file_update_time(filp);
1841         filp_close(filp, NULL);
1842 }
1843 
1844 static int btrfs_rm_dev_item(struct btrfs_fs_info *fs_info,
1845                              struct btrfs_device *device)
1846 {
1847         struct btrfs_root *root = fs_info->chunk_root;
1848         int ret;
1849         struct btrfs_path *path;
1850         struct btrfs_key key;
1851         struct btrfs_trans_handle *trans;
1852 
1853         path = btrfs_alloc_path();
1854         if (!path)
1855                 return -ENOMEM;
1856 
1857         trans = btrfs_start_transaction(root, 0);
1858         if (IS_ERR(trans)) {
1859                 btrfs_free_path(path);
1860                 return PTR_ERR(trans);
1861         }
1862         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
1863         key.type = BTRFS_DEV_ITEM_KEY;
1864         key.offset = device->devid;
1865 
1866         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1867         if (ret) {
1868                 if (ret > 0)
1869                         ret = -ENOENT;
1870                 btrfs_abort_transaction(trans, ret);
1871                 btrfs_end_transaction(trans);
1872                 goto out;
1873         }
1874 
1875         ret = btrfs_del_item(trans, root, path);
1876         if (ret) {
1877                 btrfs_abort_transaction(trans, ret);
1878                 btrfs_end_transaction(trans);
1879         }
1880 
1881 out:
1882         btrfs_free_path(path);
1883         if (!ret)
1884                 ret = btrfs_commit_transaction(trans);
1885         return ret;
1886 }
1887 
1888 /*
1889  * Verify that @num_devices satisfies the RAID profile constraints in the whole
1890  * filesystem. It's up to the caller to adjust that number regarding eg. device
1891  * replace.
1892  */
1893 static int btrfs_check_raid_min_devices(struct btrfs_fs_info *fs_info,
1894                 u64 num_devices)
1895 {
1896         u64 all_avail;
1897         unsigned seq;
1898         int i;
1899 
1900         do {
1901                 seq = read_seqbegin(&fs_info->profiles_lock);
1902 
1903                 all_avail = fs_info->avail_data_alloc_bits |
1904                             fs_info->avail_system_alloc_bits |
1905                             fs_info->avail_metadata_alloc_bits;
1906         } while (read_seqretry(&fs_info->profiles_lock, seq));
1907 
1908         for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
1909                 if (!(all_avail & btrfs_raid_array[i].bg_flag))
1910                         continue;
1911 
1912                 if (num_devices < btrfs_raid_array[i].devs_min) {
1913                         int ret = btrfs_raid_array[i].mindev_error;
1914 
1915                         if (ret)
1916                                 return ret;
1917                 }
1918         }
1919 
1920         return 0;
1921 }
1922 
1923 static struct btrfs_device * btrfs_find_next_active_device(
1924                 struct btrfs_fs_devices *fs_devs, struct btrfs_device *device)
1925 {
1926         struct btrfs_device *next_device;
1927 
1928         list_for_each_entry(next_device, &fs_devs->devices, dev_list) {
1929                 if (next_device != device &&
1930                     !test_bit(BTRFS_DEV_STATE_MISSING, &next_device->dev_state)
1931                     && next_device->bdev)
1932                         return next_device;
1933         }
1934 
1935         return NULL;
1936 }
1937 
1938 /*
1939  * Helper function to check if the given device is part of s_bdev / latest_bdev
1940  * and replace it with the provided or the next active device, in the context
1941  * where this function called, there should be always be another device (or
1942  * this_dev) which is active.
1943  */
1944 void btrfs_assign_next_active_device(struct btrfs_fs_info *fs_info,
1945                 struct btrfs_device *device, struct btrfs_device *this_dev)
1946 {
1947         struct btrfs_device *next_device;
1948 
1949         if (this_dev)
1950                 next_device = this_dev;
1951         else
1952                 next_device = btrfs_find_next_active_device(fs_info->fs_devices,
1953                                                                 device);
1954         ASSERT(next_device);
1955 
1956         if (fs_info->sb->s_bdev &&
1957                         (fs_info->sb->s_bdev == device->bdev))
1958                 fs_info->sb->s_bdev = next_device->bdev;
1959 
1960         if (fs_info->fs_devices->latest_bdev == device->bdev)
1961                 fs_info->fs_devices->latest_bdev = next_device->bdev;
1962 }
1963 
1964 int btrfs_rm_device(struct btrfs_fs_info *fs_info, const char *device_path,
1965                 u64 devid)
1966 {
1967         struct btrfs_device *device;
1968         struct btrfs_fs_devices *cur_devices;
1969         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
1970         u64 num_devices;
1971         int ret = 0;
1972 
1973         mutex_lock(&uuid_mutex);
1974 
1975         num_devices = fs_devices->num_devices;
1976         btrfs_dev_replace_read_lock(&fs_info->dev_replace);
1977         if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
1978                 WARN_ON(num_devices < 1);
1979                 num_devices--;
1980         }
1981         btrfs_dev_replace_read_unlock(&fs_info->dev_replace);
1982 
1983         ret = btrfs_check_raid_min_devices(fs_info, num_devices - 1);
1984         if (ret)
1985                 goto out;
1986 
1987         ret = btrfs_find_device_by_devspec(fs_info, devid, device_path,
1988                                            &device);
1989         if (ret)
1990                 goto out;
1991 
1992         if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
1993                 ret = BTRFS_ERROR_DEV_TGT_REPLACE;
1994                 goto out;
1995         }
1996 
1997         if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) &&
1998             fs_info->fs_devices->rw_devices == 1) {
1999                 ret = BTRFS_ERROR_DEV_ONLY_WRITABLE;
2000                 goto out;
2001         }
2002 
2003         if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2004                 mutex_lock(&fs_info->chunk_mutex);
2005                 list_del_init(&device->dev_alloc_list);
2006                 device->fs_devices->rw_devices--;
2007                 mutex_unlock(&fs_info->chunk_mutex);
2008         }
2009 
2010         mutex_unlock(&uuid_mutex);
2011         ret = btrfs_shrink_device(device, 0);
2012         mutex_lock(&uuid_mutex);
2013         if (ret)
2014                 goto error_undo;
2015 
2016         /*
2017          * TODO: the superblock still includes this device in its num_devices
2018          * counter although write_all_supers() is not locked out. This
2019          * could give a filesystem state which requires a degraded mount.
2020          */
2021         ret = btrfs_rm_dev_item(fs_info, device);
2022         if (ret)
2023                 goto error_undo;
2024 
2025         clear_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2026         btrfs_scrub_cancel_dev(fs_info, device);
2027 
2028         /*
2029          * the device list mutex makes sure that we don't change
2030          * the device list while someone else is writing out all
2031          * the device supers. Whoever is writing all supers, should
2032          * lock the device list mutex before getting the number of
2033          * devices in the super block (super_copy). Conversely,
2034          * whoever updates the number of devices in the super block
2035          * (super_copy) should hold the device list mutex.
2036          */
2037 
2038         /*
2039          * In normal cases the cur_devices == fs_devices. But in case
2040          * of deleting a seed device, the cur_devices should point to
2041          * its own fs_devices listed under the fs_devices->seed.
2042          */
2043         cur_devices = device->fs_devices;
2044         mutex_lock(&fs_devices->device_list_mutex);
2045         list_del_rcu(&device->dev_list);
2046 
2047         cur_devices->num_devices--;
2048         cur_devices->total_devices--;
2049         /* Update total_devices of the parent fs_devices if it's seed */
2050         if (cur_devices != fs_devices)
2051                 fs_devices->total_devices--;
2052 
2053         if (test_bit(BTRFS_DEV_STATE_MISSING, &device->dev_state))
2054                 cur_devices->missing_devices--;
2055 
2056         btrfs_assign_next_active_device(fs_info, device, NULL);
2057 
2058         if (device->bdev) {
2059                 cur_devices->open_devices--;
2060                 /* remove sysfs entry */
2061                 btrfs_sysfs_rm_device_link(fs_devices, device);
2062         }
2063 
2064         num_devices = btrfs_super_num_devices(fs_info->super_copy) - 1;
2065         btrfs_set_super_num_devices(fs_info->super_copy, num_devices);
2066         mutex_unlock(&fs_devices->device_list_mutex);
2067 
2068         /*
2069          * at this point, the device is zero sized and detached from
2070          * the devices list.  All that's left is to zero out the old
2071          * supers and free the device.
2072          */
2073         if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2074                 btrfs_scratch_superblocks(device->bdev, device->name->str);
2075 
2076         btrfs_close_bdev(device);
2077         call_rcu(&device->rcu, free_device_rcu);
2078 
2079         if (cur_devices->open_devices == 0) {
2080                 while (fs_devices) {
2081                         if (fs_devices->seed == cur_devices) {
2082                                 fs_devices->seed = cur_devices->seed;
2083                                 break;
2084                         }
2085                         fs_devices = fs_devices->seed;
2086                 }
2087                 cur_devices->seed = NULL;
2088                 close_fs_devices(cur_devices);
2089                 free_fs_devices(cur_devices);
2090         }
2091 
2092 out:
2093         mutex_unlock(&uuid_mutex);
2094         return ret;
2095 
2096 error_undo:
2097         if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
2098                 mutex_lock(&fs_info->chunk_mutex);
2099                 list_add(&device->dev_alloc_list,
2100                          &fs_devices->alloc_list);
2101                 device->fs_devices->rw_devices++;
2102                 mutex_unlock(&fs_info->chunk_mutex);
2103         }
2104         goto out;
2105 }
2106 
2107 void btrfs_rm_dev_replace_remove_srcdev(struct btrfs_fs_info *fs_info,
2108                                         struct btrfs_device *srcdev)
2109 {
2110         struct btrfs_fs_devices *fs_devices;
2111 
2112         lockdep_assert_held(&fs_info->fs_devices->device_list_mutex);
2113 
2114         /*
2115          * in case of fs with no seed, srcdev->fs_devices will point
2116          * to fs_devices of fs_info. However when the dev being replaced is
2117          * a seed dev it will point to the seed's local fs_devices. In short
2118          * srcdev will have its correct fs_devices in both the cases.
2119          */
2120         fs_devices = srcdev->fs_devices;
2121 
2122         list_del_rcu(&srcdev->dev_list);
2123         list_del(&srcdev->dev_alloc_list);
2124         fs_devices->num_devices--;
2125         if (test_bit(BTRFS_DEV_STATE_MISSING, &srcdev->dev_state))
2126                 fs_devices->missing_devices--;
2127 
2128         if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state))
2129                 fs_devices->rw_devices--;
2130 
2131         if (srcdev->bdev)
2132                 fs_devices->open_devices--;
2133 }
2134 
2135 void btrfs_rm_dev_replace_free_srcdev(struct btrfs_fs_info *fs_info,
2136                                       struct btrfs_device *srcdev)
2137 {
2138         struct btrfs_fs_devices *fs_devices = srcdev->fs_devices;
2139 
2140         if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &srcdev->dev_state)) {
2141                 /* zero out the old super if it is writable */
2142                 btrfs_scratch_superblocks(srcdev->bdev, srcdev->name->str);
2143         }
2144 
2145         btrfs_close_bdev(srcdev);
2146         call_rcu(&srcdev->rcu, free_device_rcu);
2147 
2148         /* if this is no devs we rather delete the fs_devices */
2149         if (!fs_devices->num_devices) {
2150                 struct btrfs_fs_devices *tmp_fs_devices;
2151 
2152                 /*
2153                  * On a mounted FS, num_devices can't be zero unless it's a
2154                  * seed. In case of a seed device being replaced, the replace
2155                  * target added to the sprout FS, so there will be no more
2156                  * device left under the seed FS.
2157                  */
2158                 ASSERT(fs_devices->seeding);
2159 
2160                 tmp_fs_devices = fs_info->fs_devices;
2161                 while (tmp_fs_devices) {
2162                         if (tmp_fs_devices->seed == fs_devices) {
2163                                 tmp_fs_devices->seed = fs_devices->seed;
2164                                 break;
2165                         }
2166                         tmp_fs_devices = tmp_fs_devices->seed;
2167                 }
2168                 fs_devices->seed = NULL;
2169                 close_fs_devices(fs_devices);
2170                 free_fs_devices(fs_devices);
2171         }
2172 }
2173 
2174 void btrfs_destroy_dev_replace_tgtdev(struct btrfs_fs_info *fs_info,
2175                                       struct btrfs_device *tgtdev)
2176 {
2177         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2178 
2179         WARN_ON(!tgtdev);
2180         mutex_lock(&fs_devices->device_list_mutex);
2181 
2182         btrfs_sysfs_rm_device_link(fs_devices, tgtdev);
2183 
2184         if (tgtdev->bdev)
2185                 fs_devices->open_devices--;
2186 
2187         fs_devices->num_devices--;
2188 
2189         btrfs_assign_next_active_device(fs_info, tgtdev, NULL);
2190 
2191         list_del_rcu(&tgtdev->dev_list);
2192 
2193         mutex_unlock(&fs_devices->device_list_mutex);
2194 
2195         /*
2196          * The update_dev_time() with in btrfs_scratch_superblocks()
2197          * may lead to a call to btrfs_show_devname() which will try
2198          * to hold device_list_mutex. And here this device
2199          * is already out of device list, so we don't have to hold
2200          * the device_list_mutex lock.
2201          */
2202         btrfs_scratch_superblocks(tgtdev->bdev, tgtdev->name->str);
2203 
2204         btrfs_close_bdev(tgtdev);
2205         call_rcu(&tgtdev->rcu, free_device_rcu);
2206 }
2207 
2208 static int btrfs_find_device_by_path(struct btrfs_fs_info *fs_info,
2209                                      const char *device_path,
2210                                      struct btrfs_device **device)
2211 {
2212         int ret = 0;
2213         struct btrfs_super_block *disk_super;
2214         u64 devid;
2215         u8 *dev_uuid;
2216         struct block_device *bdev;
2217         struct buffer_head *bh;
2218 
2219         *device = NULL;
2220         ret = btrfs_get_bdev_and_sb(device_path, FMODE_READ,
2221                                     fs_info->bdev_holder, 0, &bdev, &bh);
2222         if (ret)
2223                 return ret;
2224         disk_super = (struct btrfs_super_block *)bh->b_data;
2225         devid = btrfs_stack_device_id(&disk_super->dev_item);
2226         dev_uuid = disk_super->dev_item.uuid;
2227         *device = btrfs_find_device(fs_info, devid, dev_uuid, disk_super->fsid);
2228         brelse(bh);
2229         if (!*device)
2230                 ret = -ENOENT;
2231         blkdev_put(bdev, FMODE_READ);
2232         return ret;
2233 }
2234 
2235 int btrfs_find_device_missing_or_by_path(struct btrfs_fs_info *fs_info,
2236                                          const char *device_path,
2237                                          struct btrfs_device **device)
2238 {
2239         *device = NULL;
2240         if (strcmp(device_path, "missing") == 0) {
2241                 struct list_head *devices;
2242                 struct btrfs_device *tmp;
2243 
2244                 devices = &fs_info->fs_devices->devices;
2245                 list_for_each_entry(tmp, devices, dev_list) {
2246                         if (test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
2247                                         &tmp->dev_state) && !tmp->bdev) {
2248                                 *device = tmp;
2249                                 break;
2250                         }
2251                 }
2252 
2253                 if (!*device)
2254                         return BTRFS_ERROR_DEV_MISSING_NOT_FOUND;
2255 
2256                 return 0;
2257         } else {
2258                 return btrfs_find_device_by_path(fs_info, device_path, device);
2259         }
2260 }
2261 
2262 /*
2263  * Lookup a device given by device id, or the path if the id is 0.
2264  */
2265 int btrfs_find_device_by_devspec(struct btrfs_fs_info *fs_info, u64 devid,
2266                                  const char *devpath,
2267                                  struct btrfs_device **device)
2268 {
2269         int ret;
2270 
2271         if (devid) {
2272                 ret = 0;
2273                 *device = btrfs_find_device(fs_info, devid, NULL, NULL);
2274                 if (!*device)
2275                         ret = -ENOENT;
2276         } else {
2277                 if (!devpath || !devpath[0])
2278                         return -EINVAL;
2279 
2280                 ret = btrfs_find_device_missing_or_by_path(fs_info, devpath,
2281                                                            device);
2282         }
2283         return ret;
2284 }
2285 
2286 /*
2287  * does all the dirty work required for changing file system's UUID.
2288  */
2289 static int btrfs_prepare_sprout(struct btrfs_fs_info *fs_info)
2290 {
2291         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2292         struct btrfs_fs_devices *old_devices;
2293         struct btrfs_fs_devices *seed_devices;
2294         struct btrfs_super_block *disk_super = fs_info->super_copy;
2295         struct btrfs_device *device;
2296         u64 super_flags;
2297 
2298         lockdep_assert_held(&uuid_mutex);
2299         if (!fs_devices->seeding)
2300                 return -EINVAL;
2301 
2302         seed_devices = alloc_fs_devices(NULL);
2303         if (IS_ERR(seed_devices))
2304                 return PTR_ERR(seed_devices);
2305 
2306         old_devices = clone_fs_devices(fs_devices);
2307         if (IS_ERR(old_devices)) {
2308                 kfree(seed_devices);
2309                 return PTR_ERR(old_devices);
2310         }
2311 
2312         list_add(&old_devices->fs_list, &fs_uuids);
2313 
2314         memcpy(seed_devices, fs_devices, sizeof(*seed_devices));
2315         seed_devices->opened = 1;
2316         INIT_LIST_HEAD(&seed_devices->devices);
2317         INIT_LIST_HEAD(&seed_devices->alloc_list);
2318         mutex_init(&seed_devices->device_list_mutex);
2319 
2320         mutex_lock(&fs_info->fs_devices->device_list_mutex);
2321         list_splice_init_rcu(&fs_devices->devices, &seed_devices->devices,
2322                               synchronize_rcu);
2323         list_for_each_entry(device, &seed_devices->devices, dev_list)
2324                 device->fs_devices = seed_devices;
2325 
2326         mutex_lock(&fs_info->chunk_mutex);
2327         list_splice_init(&fs_devices->alloc_list, &seed_devices->alloc_list);
2328         mutex_unlock(&fs_info->chunk_mutex);
2329 
2330         fs_devices->seeding = 0;
2331         fs_devices->num_devices = 0;
2332         fs_devices->open_devices = 0;
2333         fs_devices->missing_devices = 0;
2334         fs_devices->rotating = 0;
2335         fs_devices->seed = seed_devices;
2336 
2337         generate_random_uuid(fs_devices->fsid);
2338         memcpy(fs_info->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2339         memcpy(disk_super->fsid, fs_devices->fsid, BTRFS_FSID_SIZE);
2340         mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2341 
2342         super_flags = btrfs_super_flags(disk_super) &
2343                       ~BTRFS_SUPER_FLAG_SEEDING;
2344         btrfs_set_super_flags(disk_super, super_flags);
2345 
2346         return 0;
2347 }
2348 
2349 /*
2350  * Store the expected generation for seed devices in device items.
2351  */
2352 static int btrfs_finish_sprout(struct btrfs_trans_handle *trans,
2353                                struct btrfs_fs_info *fs_info)
2354 {
2355         struct btrfs_root *root = fs_info->chunk_root;
2356         struct btrfs_path *path;
2357         struct extent_buffer *leaf;
2358         struct btrfs_dev_item *dev_item;
2359         struct btrfs_device *device;
2360         struct btrfs_key key;
2361         u8 fs_uuid[BTRFS_FSID_SIZE];
2362         u8 dev_uuid[BTRFS_UUID_SIZE];
2363         u64 devid;
2364         int ret;
2365 
2366         path = btrfs_alloc_path();
2367         if (!path)
2368                 return -ENOMEM;
2369 
2370         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2371         key.offset = 0;
2372         key.type = BTRFS_DEV_ITEM_KEY;
2373 
2374         while (1) {
2375                 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2376                 if (ret < 0)
2377                         goto error;
2378 
2379                 leaf = path->nodes[0];
2380 next_slot:
2381                 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2382                         ret = btrfs_next_leaf(root, path);
2383                         if (ret > 0)
2384                                 break;
2385                         if (ret < 0)
2386                                 goto error;
2387                         leaf = path->nodes[0];
2388                         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2389                         btrfs_release_path(path);
2390                         continue;
2391                 }
2392 
2393                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2394                 if (key.objectid != BTRFS_DEV_ITEMS_OBJECTID ||
2395                     key.type != BTRFS_DEV_ITEM_KEY)
2396                         break;
2397 
2398                 dev_item = btrfs_item_ptr(leaf, path->slots[0],
2399                                           struct btrfs_dev_item);
2400                 devid = btrfs_device_id(leaf, dev_item);
2401                 read_extent_buffer(leaf, dev_uuid, btrfs_device_uuid(dev_item),
2402                                    BTRFS_UUID_SIZE);
2403                 read_extent_buffer(leaf, fs_uuid, btrfs_device_fsid(dev_item),
2404                                    BTRFS_FSID_SIZE);
2405                 device = btrfs_find_device(fs_info, devid, dev_uuid, fs_uuid);
2406                 BUG_ON(!device); /* Logic error */
2407 
2408                 if (device->fs_devices->seeding) {
2409                         btrfs_set_device_generation(leaf, dev_item,
2410                                                     device->generation);
2411                         btrfs_mark_buffer_dirty(leaf);
2412                 }
2413 
2414                 path->slots[0]++;
2415                 goto next_slot;
2416         }
2417         ret = 0;
2418 error:
2419         btrfs_free_path(path);
2420         return ret;
2421 }
2422 
2423 int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path)
2424 {
2425         struct btrfs_root *root = fs_info->dev_root;
2426         struct request_queue *q;
2427         struct btrfs_trans_handle *trans;
2428         struct btrfs_device *device;
2429         struct block_device *bdev;
2430         struct list_head *devices;
2431         struct super_block *sb = fs_info->sb;
2432         struct rcu_string *name;
2433         u64 tmp;
2434         int seeding_dev = 0;
2435         int ret = 0;
2436         bool unlocked = false;
2437 
2438         if (sb_rdonly(sb) && !fs_info->fs_devices->seeding)
2439                 return -EROFS;
2440 
2441         bdev = blkdev_get_by_path(device_path, FMODE_WRITE | FMODE_EXCL,
2442                                   fs_info->bdev_holder);
2443         if (IS_ERR(bdev))
2444                 return PTR_ERR(bdev);
2445 
2446         if (fs_info->fs_devices->seeding) {
2447                 seeding_dev = 1;
2448                 down_write(&sb->s_umount);
2449                 mutex_lock(&uuid_mutex);
2450         }
2451 
2452         filemap_write_and_wait(bdev->bd_inode->i_mapping);
2453 
2454         devices = &fs_info->fs_devices->devices;
2455 
2456         mutex_lock(&fs_info->fs_devices->device_list_mutex);
2457         list_for_each_entry(device, devices, dev_list) {
2458                 if (device->bdev == bdev) {
2459                         ret = -EEXIST;
2460                         mutex_unlock(
2461                                 &fs_info->fs_devices->device_list_mutex);
2462                         goto error;
2463                 }
2464         }
2465         mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2466 
2467         device = btrfs_alloc_device(fs_info, NULL, NULL);
2468         if (IS_ERR(device)) {
2469                 /* we can safely leave the fs_devices entry around */
2470                 ret = PTR_ERR(device);
2471                 goto error;
2472         }
2473 
2474         name = rcu_string_strdup(device_path, GFP_KERNEL);
2475         if (!name) {
2476                 ret = -ENOMEM;
2477                 goto error_free_device;
2478         }
2479         rcu_assign_pointer(device->name, name);
2480 
2481         trans = btrfs_start_transaction(root, 0);
2482         if (IS_ERR(trans)) {
2483                 ret = PTR_ERR(trans);
2484                 goto error_free_device;
2485         }
2486 
2487         q = bdev_get_queue(bdev);
2488         set_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state);
2489         device->generation = trans->transid;
2490         device->io_width = fs_info->sectorsize;
2491         device->io_align = fs_info->sectorsize;
2492         device->sector_size = fs_info->sectorsize;
2493         device->total_bytes = round_down(i_size_read(bdev->bd_inode),
2494                                          fs_info->sectorsize);
2495         device->disk_total_bytes = device->total_bytes;
2496         device->commit_total_bytes = device->total_bytes;
2497         device->fs_info = fs_info;
2498         device->bdev = bdev;
2499         set_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state);
2500         clear_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state);
2501         device->mode = FMODE_EXCL;
2502         device->dev_stats_valid = 1;
2503         set_blocksize(device->bdev, BTRFS_BDEV_BLOCKSIZE);
2504 
2505         if (seeding_dev) {
2506                 sb->s_flags &= ~SB_RDONLY;
2507                 ret = btrfs_prepare_sprout(fs_info);
2508                 if (ret) {
2509                         btrfs_abort_transaction(trans, ret);
2510                         goto error_trans;
2511                 }
2512         }
2513 
2514         device->fs_devices = fs_info->fs_devices;
2515 
2516         mutex_lock(&fs_info->fs_devices->device_list_mutex);
2517         mutex_lock(&fs_info->chunk_mutex);
2518         list_add_rcu(&device->dev_list, &fs_info->fs_devices->devices);
2519         list_add(&device->dev_alloc_list,
2520                  &fs_info->fs_devices->alloc_list);
2521         fs_info->fs_devices->num_devices++;
2522         fs_info->fs_devices->open_devices++;
2523         fs_info->fs_devices->rw_devices++;
2524         fs_info->fs_devices->total_devices++;
2525         fs_info->fs_devices->total_rw_bytes += device->total_bytes;
2526 
2527         atomic64_add(device->total_bytes, &fs_info->free_chunk_space);
2528 
2529         if (!blk_queue_nonrot(q))
2530                 fs_info->fs_devices->rotating = 1;
2531 
2532         tmp = btrfs_super_total_bytes(fs_info->super_copy);
2533         btrfs_set_super_total_bytes(fs_info->super_copy,
2534                 round_down(tmp + device->total_bytes, fs_info->sectorsize));
2535 
2536         tmp = btrfs_super_num_devices(fs_info->super_copy);
2537         btrfs_set_super_num_devices(fs_info->super_copy, tmp + 1);
2538 
2539         /* add sysfs device entry */
2540         btrfs_sysfs_add_device_link(fs_info->fs_devices, device);
2541 
2542         /*
2543          * we've got more storage, clear any full flags on the space
2544          * infos
2545          */
2546         btrfs_clear_space_info_full(fs_info);
2547 
2548         mutex_unlock(&fs_info->chunk_mutex);
2549         mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2550 
2551         if (seeding_dev) {
2552                 mutex_lock(&fs_info->chunk_mutex);
2553                 ret = init_first_rw_device(trans, fs_info);
2554                 mutex_unlock(&fs_info->chunk_mutex);
2555                 if (ret) {
2556                         btrfs_abort_transaction(trans, ret);
2557                         goto error_sysfs;
2558                 }
2559         }
2560 
2561         ret = btrfs_add_dev_item(trans, fs_info, device);
2562         if (ret) {
2563                 btrfs_abort_transaction(trans, ret);
2564                 goto error_sysfs;
2565         }
2566 
2567         if (seeding_dev) {
2568                 char fsid_buf[BTRFS_UUID_UNPARSED_SIZE];
2569 
2570                 ret = btrfs_finish_sprout(trans, fs_info);
2571                 if (ret) {
2572                         btrfs_abort_transaction(trans, ret);
2573                         goto error_sysfs;
2574                 }
2575 
2576                 /* Sprouting would change fsid of the mounted root,
2577                  * so rename the fsid on the sysfs
2578                  */
2579                 snprintf(fsid_buf, BTRFS_UUID_UNPARSED_SIZE, "%pU",
2580                                                 fs_info->fsid);
2581                 if (kobject_rename(&fs_info->fs_devices->fsid_kobj, fsid_buf))
2582                         btrfs_warn(fs_info,
2583                                    "sysfs: failed to create fsid for sprout");
2584         }
2585 
2586         ret = btrfs_commit_transaction(trans);
2587 
2588         if (seeding_dev) {
2589                 mutex_unlock(&uuid_mutex);
2590                 up_write(&sb->s_umount);
2591                 unlocked = true;
2592 
2593                 if (ret) /* transaction commit */
2594                         return ret;
2595 
2596                 ret = btrfs_relocate_sys_chunks(fs_info);
2597                 if (ret < 0)
2598                         btrfs_handle_fs_error(fs_info, ret,
2599                                     "Failed to relocate sys chunks after device initialization. This can be fixed using the \"btrfs balance\" command.");
2600                 trans = btrfs_attach_transaction(root);
2601                 if (IS_ERR(trans)) {
2602                         if (PTR_ERR(trans) == -ENOENT)
2603                                 return 0;
2604                         ret = PTR_ERR(trans);
2605                         trans = NULL;
2606                         goto error_sysfs;
2607                 }
2608                 ret = btrfs_commit_transaction(trans);
2609         }
2610 
2611         /* Update ctime/mtime for libblkid */
2612         update_dev_time(device_path);
2613         return ret;
2614 
2615 error_sysfs:
2616         btrfs_sysfs_rm_device_link(fs_info->fs_devices, device);
2617 error_trans:
2618         if (seeding_dev)
2619                 sb->s_flags |= SB_RDONLY;
2620         if (trans)
2621                 btrfs_end_transaction(trans);
2622 error_free_device:
2623         btrfs_free_device(device);
2624 error:
2625         blkdev_put(bdev, FMODE_EXCL);
2626         if (seeding_dev && !unlocked) {
2627                 mutex_unlock(&uuid_mutex);
2628                 up_write(&sb->s_umount);
2629         }
2630         return ret;
2631 }
2632 
2633 static noinline int btrfs_update_device(struct btrfs_trans_handle *trans,
2634                                         struct btrfs_device *device)
2635 {
2636         int ret;
2637         struct btrfs_path *path;
2638         struct btrfs_root *root = device->fs_info->chunk_root;
2639         struct btrfs_dev_item *dev_item;
2640         struct extent_buffer *leaf;
2641         struct btrfs_key key;
2642 
2643         path = btrfs_alloc_path();
2644         if (!path)
2645                 return -ENOMEM;
2646 
2647         key.objectid = BTRFS_DEV_ITEMS_OBJECTID;
2648         key.type = BTRFS_DEV_ITEM_KEY;
2649         key.offset = device->devid;
2650 
2651         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2652         if (ret < 0)
2653                 goto out;
2654 
2655         if (ret > 0) {
2656                 ret = -ENOENT;
2657                 goto out;
2658         }
2659 
2660         leaf = path->nodes[0];
2661         dev_item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_item);
2662 
2663         btrfs_set_device_id(leaf, dev_item, device->devid);
2664         btrfs_set_device_type(leaf, dev_item, device->type);
2665         btrfs_set_device_io_align(leaf, dev_item, device->io_align);
2666         btrfs_set_device_io_width(leaf, dev_item, device->io_width);
2667         btrfs_set_device_sector_size(leaf, dev_item, device->sector_size);
2668         btrfs_set_device_total_bytes(leaf, dev_item,
2669                                      btrfs_device_get_disk_total_bytes(device));
2670         btrfs_set_device_bytes_used(leaf, dev_item,
2671                                     btrfs_device_get_bytes_used(device));
2672         btrfs_mark_buffer_dirty(leaf);
2673 
2674 out:
2675         btrfs_free_path(path);
2676         return ret;
2677 }
2678 
2679 int btrfs_grow_device(struct btrfs_trans_handle *trans,
2680                       struct btrfs_device *device, u64 new_size)
2681 {
2682         struct btrfs_fs_info *fs_info = device->fs_info;
2683         struct btrfs_super_block *super_copy = fs_info->super_copy;
2684         struct btrfs_fs_devices *fs_devices;
2685         u64 old_total;
2686         u64 diff;
2687 
2688         if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
2689                 return -EACCES;
2690 
2691         new_size = round_down(new_size, fs_info->sectorsize);
2692 
2693         mutex_lock(&fs_info->chunk_mutex);
2694         old_total = btrfs_super_total_bytes(super_copy);
2695         diff = round_down(new_size - device->total_bytes, fs_info->sectorsize);
2696 
2697         if (new_size <= device->total_bytes ||
2698             test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
2699                 mutex_unlock(&fs_info->chunk_mutex);
2700                 return -EINVAL;
2701         }
2702 
2703         fs_devices = fs_info->fs_devices;
2704 
2705         btrfs_set_super_total_bytes(super_copy,
2706                         round_down(old_total + diff, fs_info->sectorsize));
2707         device->fs_devices->total_rw_bytes += diff;
2708 
2709         btrfs_device_set_total_bytes(device, new_size);
2710         btrfs_device_set_disk_total_bytes(device, new_size);
2711         btrfs_clear_space_info_full(device->fs_info);
2712         if (list_empty(&device->resized_list))
2713                 list_add_tail(&device->resized_list,
2714                               &fs_devices->resized_devices);
2715         mutex_unlock(&fs_info->chunk_mutex);
2716 
2717         return btrfs_update_device(trans, device);
2718 }
2719 
2720 static int btrfs_free_chunk(struct btrfs_trans_handle *trans,
2721                             struct btrfs_fs_info *fs_info, u64 chunk_offset)
2722 {
2723         struct btrfs_root *root = fs_info->chunk_root;
2724         int ret;
2725         struct btrfs_path *path;
2726         struct btrfs_key key;
2727 
2728         path = btrfs_alloc_path();
2729         if (!path)
2730                 return -ENOMEM;
2731 
2732         key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2733         key.offset = chunk_offset;
2734         key.type = BTRFS_CHUNK_ITEM_KEY;
2735 
2736         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
2737         if (ret < 0)
2738                 goto out;
2739         else if (ret > 0) { /* Logic error or corruption */
2740                 btrfs_handle_fs_error(fs_info, -ENOENT,
2741                                       "Failed lookup while freeing chunk.");
2742                 ret = -ENOENT;
2743                 goto out;
2744         }
2745 
2746         ret = btrfs_del_item(trans, root, path);
2747         if (ret < 0)
2748                 btrfs_handle_fs_error(fs_info, ret,
2749                                       "Failed to delete chunk item.");
2750 out:
2751         btrfs_free_path(path);
2752         return ret;
2753 }
2754 
2755 static int btrfs_del_sys_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2756 {
2757         struct btrfs_super_block *super_copy = fs_info->super_copy;
2758         struct btrfs_disk_key *disk_key;
2759         struct btrfs_chunk *chunk;
2760         u8 *ptr;
2761         int ret = 0;
2762         u32 num_stripes;
2763         u32 array_size;
2764         u32 len = 0;
2765         u32 cur;
2766         struct btrfs_key key;
2767 
2768         mutex_lock(&fs_info->chunk_mutex);
2769         array_size = btrfs_super_sys_array_size(super_copy);
2770 
2771         ptr = super_copy->sys_chunk_array;
2772         cur = 0;
2773 
2774         while (cur < array_size) {
2775                 disk_key = (struct btrfs_disk_key *)ptr;
2776                 btrfs_disk_key_to_cpu(&key, disk_key);
2777 
2778                 len = sizeof(*disk_key);
2779 
2780                 if (key.type == BTRFS_CHUNK_ITEM_KEY) {
2781                         chunk = (struct btrfs_chunk *)(ptr + len);
2782                         num_stripes = btrfs_stack_chunk_num_stripes(chunk);
2783                         len += btrfs_chunk_item_size(num_stripes);
2784                 } else {
2785                         ret = -EIO;
2786                         break;
2787                 }
2788                 if (key.objectid == BTRFS_FIRST_CHUNK_TREE_OBJECTID &&
2789                     key.offset == chunk_offset) {
2790                         memmove(ptr, ptr + len, array_size - (cur + len));
2791                         array_size -= len;
2792                         btrfs_set_super_sys_array_size(super_copy, array_size);
2793                 } else {
2794                         ptr += len;
2795                         cur += len;
2796                 }
2797         }
2798         mutex_unlock(&fs_info->chunk_mutex);
2799         return ret;
2800 }
2801 
2802 static struct extent_map *get_chunk_map(struct btrfs_fs_info *fs_info,
2803                                         u64 logical, u64 length)
2804 {
2805         struct extent_map_tree *em_tree;
2806         struct extent_map *em;
2807 
2808         em_tree = &fs_info->mapping_tree.map_tree;
2809         read_lock(&em_tree->lock);
2810         em = lookup_extent_mapping(em_tree, logical, length);
2811         read_unlock(&em_tree->lock);
2812 
2813         if (!em) {
2814                 btrfs_crit(fs_info, "unable to find logical %llu length %llu",
2815                            logical, length);
2816                 return ERR_PTR(-EINVAL);
2817         }
2818 
2819         if (em->start > logical || em->start + em->len < logical) {
2820                 btrfs_crit(fs_info,
2821                            "found a bad mapping, wanted %llu-%llu, found %llu-%llu",
2822                            logical, length, em->start, em->start + em->len);
2823                 free_extent_map(em);
2824                 return ERR_PTR(-EINVAL);
2825         }
2826 
2827         /* callers are responsible for dropping em's ref. */
2828         return em;
2829 }
2830 
2831 int btrfs_remove_chunk(struct btrfs_trans_handle *trans,
2832                        struct btrfs_fs_info *fs_info, u64 chunk_offset)
2833 {
2834         struct extent_map *em;
2835         struct map_lookup *map;
2836         u64 dev_extent_len = 0;
2837         int i, ret = 0;
2838         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
2839 
2840         em = get_chunk_map(fs_info, chunk_offset, 1);
2841         if (IS_ERR(em)) {
2842                 /*
2843                  * This is a logic error, but we don't want to just rely on the
2844                  * user having built with ASSERT enabled, so if ASSERT doesn't
2845                  * do anything we still error out.
2846                  */
2847                 ASSERT(0);
2848                 return PTR_ERR(em);
2849         }
2850         map = em->map_lookup;
2851         mutex_lock(&fs_info->chunk_mutex);
2852         check_system_chunk(trans, fs_info, map->type);
2853         mutex_unlock(&fs_info->chunk_mutex);
2854 
2855         /*
2856          * Take the device list mutex to prevent races with the final phase of
2857          * a device replace operation that replaces the device object associated
2858          * with map stripes (dev-replace.c:btrfs_dev_replace_finishing()).
2859          */
2860         mutex_lock(&fs_devices->device_list_mutex);
2861         for (i = 0; i < map->num_stripes; i++) {
2862                 struct btrfs_device *device = map->stripes[i].dev;
2863                 ret = btrfs_free_dev_extent(trans, device,
2864                                             map->stripes[i].physical,
2865                                             &dev_extent_len);
2866                 if (ret) {
2867                         mutex_unlock(&fs_devices->device_list_mutex);
2868                         btrfs_abort_transaction(trans, ret);
2869                         goto out;
2870                 }
2871 
2872                 if (device->bytes_used > 0) {
2873                         mutex_lock(&fs_info->chunk_mutex);
2874                         btrfs_device_set_bytes_used(device,
2875                                         device->bytes_used - dev_extent_len);
2876                         atomic64_add(dev_extent_len, &fs_info->free_chunk_space);
2877                         btrfs_clear_space_info_full(fs_info);
2878                         mutex_unlock(&fs_info->chunk_mutex);
2879                 }
2880 
2881                 if (map->stripes[i].dev) {
2882                         ret = btrfs_update_device(trans, map->stripes[i].dev);
2883                         if (ret) {
2884                                 mutex_unlock(&fs_devices->device_list_mutex);
2885                                 btrfs_abort_transaction(trans, ret);
2886                                 goto out;
2887                         }
2888                 }
2889         }
2890         mutex_unlock(&fs_devices->device_list_mutex);
2891 
2892         ret = btrfs_free_chunk(trans, fs_info, chunk_offset);
2893         if (ret) {
2894                 btrfs_abort_transaction(trans, ret);
2895                 goto out;
2896         }
2897 
2898         trace_btrfs_chunk_free(fs_info, map, chunk_offset, em->len);
2899 
2900         if (map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
2901                 ret = btrfs_del_sys_chunk(fs_info, chunk_offset);
2902                 if (ret) {
2903                         btrfs_abort_transaction(trans, ret);
2904                         goto out;
2905                 }
2906         }
2907 
2908         ret = btrfs_remove_block_group(trans, fs_info, chunk_offset, em);
2909         if (ret) {
2910                 btrfs_abort_transaction(trans, ret);
2911                 goto out;
2912         }
2913 
2914 out:
2915         /* once for us */
2916         free_extent_map(em);
2917         return ret;
2918 }
2919 
2920 static int btrfs_relocate_chunk(struct btrfs_fs_info *fs_info, u64 chunk_offset)
2921 {
2922         struct btrfs_root *root = fs_info->chunk_root;
2923         struct btrfs_trans_handle *trans;
2924         int ret;
2925 
2926         /*
2927          * Prevent races with automatic removal of unused block groups.
2928          * After we relocate and before we remove the chunk with offset
2929          * chunk_offset, automatic removal of the block group can kick in,
2930          * resulting in a failure when calling btrfs_remove_chunk() below.
2931          *
2932          * Make sure to acquire this mutex before doing a tree search (dev
2933          * or chunk trees) to find chunks. Otherwise the cleaner kthread might
2934          * call btrfs_remove_chunk() (through btrfs_delete_unused_bgs()) after
2935          * we release the path used to search the chunk/dev tree and before
2936          * the current task acquires this mutex and calls us.
2937          */
2938         lockdep_assert_held(&fs_info->delete_unused_bgs_mutex);
2939 
2940         ret = btrfs_can_relocate(fs_info, chunk_offset);
2941         if (ret)
2942                 return -ENOSPC;
2943 
2944         /* step one, relocate all the extents inside this chunk */
2945         btrfs_scrub_pause(fs_info);
2946         ret = btrfs_relocate_block_group(fs_info, chunk_offset);
2947         btrfs_scrub_continue(fs_info);
2948         if (ret)
2949                 return ret;
2950 
2951         /*
2952          * We add the kobjects here (and after forcing data chunk creation)
2953          * since relocation is the only place we'll create chunks of a new
2954          * type at runtime.  The only place where we'll remove the last
2955          * chunk of a type is the call immediately below this one.  Even
2956          * so, we're protected against races with the cleaner thread since
2957          * we're covered by the delete_unused_bgs_mutex.
2958          */
2959         btrfs_add_raid_kobjects(fs_info);
2960 
2961         trans = btrfs_start_trans_remove_block_group(root->fs_info,
2962                                                      chunk_offset);
2963         if (IS_ERR(trans)) {
2964                 ret = PTR_ERR(trans);
2965                 btrfs_handle_fs_error(root->fs_info, ret, NULL);
2966                 return ret;
2967         }
2968 
2969         /*
2970          * step two, delete the device extents and the
2971          * chunk tree entries
2972          */
2973         ret = btrfs_remove_chunk(trans, fs_info, chunk_offset);
2974         btrfs_end_transaction(trans);
2975         return ret;
2976 }
2977 
2978 static int btrfs_relocate_sys_chunks(struct btrfs_fs_info *fs_info)
2979 {
2980         struct btrfs_root *chunk_root = fs_info->chunk_root;
2981         struct btrfs_path *path;
2982         struct extent_buffer *leaf;
2983         struct btrfs_chunk *chunk;
2984         struct btrfs_key key;
2985         struct btrfs_key found_key;
2986         u64 chunk_type;
2987         bool retried = false;
2988         int failed = 0;
2989         int ret;
2990 
2991         path = btrfs_alloc_path();
2992         if (!path)
2993                 return -ENOMEM;
2994 
2995 again:
2996         key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2997         key.offset = (u64)-1;
2998         key.type = BTRFS_CHUNK_ITEM_KEY;
2999 
3000         while (1) {
3001                 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3002                 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3003                 if (ret < 0) {
3004                         mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3005                         goto error;
3006                 }
3007                 BUG_ON(ret == 0); /* Corruption */
3008 
3009                 ret = btrfs_previous_item(chunk_root, path, key.objectid,
3010                                           key.type);
3011                 if (ret)
3012                         mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3013                 if (ret < 0)
3014                         goto error;
3015                 if (ret > 0)
3016                         break;
3017 
3018                 leaf = path->nodes[0];
3019                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3020 
3021                 chunk = btrfs_item_ptr(leaf, path->slots[0],
3022                                        struct btrfs_chunk);
3023                 chunk_type = btrfs_chunk_type(leaf, chunk);
3024                 btrfs_release_path(path);
3025 
3026                 if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) {
3027                         ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3028                         if (ret == -ENOSPC)
3029                                 failed++;
3030                         else
3031                                 BUG_ON(ret);
3032                 }
3033                 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3034 
3035                 if (found_key.offset == 0)
3036                         break;
3037                 key.offset = found_key.offset - 1;
3038         }
3039         ret = 0;
3040         if (failed && !retried) {
3041                 failed = 0;
3042                 retried = true;
3043                 goto again;
3044         } else if (WARN_ON(failed && retried)) {
3045                 ret = -ENOSPC;
3046         }
3047 error:
3048         btrfs_free_path(path);
3049         return ret;
3050 }
3051 
3052 /*
3053  * return 1 : allocate a data chunk successfully,
3054  * return <0: errors during allocating a data chunk,
3055  * return 0 : no need to allocate a data chunk.
3056  */
3057 static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info *fs_info,
3058                                       u64 chunk_offset)
3059 {
3060         struct btrfs_block_group_cache *cache;
3061         u64 bytes_used;
3062         u64 chunk_type;
3063 
3064         cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3065         ASSERT(cache);
3066         chunk_type = cache->flags;
3067         btrfs_put_block_group(cache);
3068 
3069         if (chunk_type & BTRFS_BLOCK_GROUP_DATA) {
3070                 spin_lock(&fs_info->data_sinfo->lock);
3071                 bytes_used = fs_info->data_sinfo->bytes_used;
3072                 spin_unlock(&fs_info->data_sinfo->lock);
3073 
3074                 if (!bytes_used) {
3075                         struct btrfs_trans_handle *trans;
3076                         int ret;
3077 
3078                         trans = btrfs_join_transaction(fs_info->tree_root);
3079                         if (IS_ERR(trans))
3080                                 return PTR_ERR(trans);
3081 
3082                         ret = btrfs_force_chunk_alloc(trans, fs_info,
3083                                                       BTRFS_BLOCK_GROUP_DATA);
3084                         btrfs_end_transaction(trans);
3085                         if (ret < 0)
3086                                 return ret;
3087 
3088                         btrfs_add_raid_kobjects(fs_info);
3089 
3090                         return 1;
3091                 }
3092         }
3093         return 0;
3094 }
3095 
3096 static int insert_balance_item(struct btrfs_fs_info *fs_info,
3097                                struct btrfs_balance_control *bctl)
3098 {
3099         struct btrfs_root *root = fs_info->tree_root;
3100         struct btrfs_trans_handle *trans;
3101         struct btrfs_balance_item *item;
3102         struct btrfs_disk_balance_args disk_bargs;
3103         struct btrfs_path *path;
3104         struct extent_buffer *leaf;
3105         struct btrfs_key key;
3106         int ret, err;
3107 
3108         path = btrfs_alloc_path();
3109         if (!path)
3110                 return -ENOMEM;
3111 
3112         trans = btrfs_start_transaction(root, 0);
3113         if (IS_ERR(trans)) {
3114                 btrfs_free_path(path);
3115                 return PTR_ERR(trans);
3116         }
3117 
3118         key.objectid = BTRFS_BALANCE_OBJECTID;
3119         key.type = BTRFS_TEMPORARY_ITEM_KEY;
3120         key.offset = 0;
3121 
3122         ret = btrfs_insert_empty_item(trans, root, path, &key,
3123                                       sizeof(*item));
3124         if (ret)
3125                 goto out;
3126 
3127         leaf = path->nodes[0];
3128         item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
3129 
3130         memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
3131 
3132         btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->data);
3133         btrfs_set_balance_data(leaf, item, &disk_bargs);
3134         btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->meta);
3135         btrfs_set_balance_meta(leaf, item, &disk_bargs);
3136         btrfs_cpu_balance_args_to_disk(&disk_bargs, &bctl->sys);
3137         btrfs_set_balance_sys(leaf, item, &disk_bargs);
3138 
3139         btrfs_set_balance_flags(leaf, item, bctl->flags);
3140 
3141         btrfs_mark_buffer_dirty(leaf);
3142 out:
3143         btrfs_free_path(path);
3144         err = btrfs_commit_transaction(trans);
3145         if (err && !ret)
3146                 ret = err;
3147         return ret;
3148 }
3149 
3150 static int del_balance_item(struct btrfs_fs_info *fs_info)
3151 {
3152         struct btrfs_root *root = fs_info->tree_root;
3153         struct btrfs_trans_handle *trans;
3154         struct btrfs_path *path;
3155         struct btrfs_key key;
3156         int ret, err;
3157 
3158         path = btrfs_alloc_path();
3159         if (!path)
3160                 return -ENOMEM;
3161 
3162         trans = btrfs_start_transaction(root, 0);
3163         if (IS_ERR(trans)) {
3164                 btrfs_free_path(path);
3165                 return PTR_ERR(trans);
3166         }
3167 
3168         key.objectid = BTRFS_BALANCE_OBJECTID;
3169         key.type = BTRFS_TEMPORARY_ITEM_KEY;
3170         key.offset = 0;
3171 
3172         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
3173         if (ret < 0)
3174                 goto out;
3175         if (ret > 0) {
3176                 ret = -ENOENT;
3177                 goto out;
3178         }
3179 
3180         ret = btrfs_del_item(trans, root, path);
3181 out:
3182         btrfs_free_path(path);
3183         err = btrfs_commit_transaction(trans);
3184         if (err && !ret)
3185                 ret = err;
3186         return ret;
3187 }
3188 
3189 /*
3190  * This is a heuristic used to reduce the number of chunks balanced on
3191  * resume after balance was interrupted.
3192  */
3193 static void update_balance_args(struct btrfs_balance_control *bctl)
3194 {
3195         /*
3196          * Turn on soft mode for chunk types that were being converted.
3197          */
3198         if (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)
3199                 bctl->data.flags |= BTRFS_BALANCE_ARGS_SOFT;
3200         if (bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)
3201                 bctl->sys.flags |= BTRFS_BALANCE_ARGS_SOFT;
3202         if (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)
3203                 bctl->meta.flags |= BTRFS_BALANCE_ARGS_SOFT;
3204 
3205         /*
3206          * Turn on usage filter if is not already used.  The idea is
3207          * that chunks that we have already balanced should be
3208          * reasonably full.  Don't do it for chunks that are being
3209          * converted - that will keep us from relocating unconverted
3210          * (albeit full) chunks.
3211          */
3212         if (!(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3213             !(bctl->data.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3214             !(bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3215                 bctl->data.flags |= BTRFS_BALANCE_ARGS_USAGE;
3216                 bctl->data.usage = 90;
3217         }
3218         if (!(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3219             !(bctl->sys.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3220             !(bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3221                 bctl->sys.flags |= BTRFS_BALANCE_ARGS_USAGE;
3222                 bctl->sys.usage = 90;
3223         }
3224         if (!(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE) &&
3225             !(bctl->meta.flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3226             !(bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT)) {
3227                 bctl->meta.flags |= BTRFS_BALANCE_ARGS_USAGE;
3228                 bctl->meta.usage = 90;
3229         }
3230 }
3231 
3232 /*
3233  * Clear the balance status in fs_info and delete the balance item from disk.
3234  */
3235 static void reset_balance_state(struct btrfs_fs_info *fs_info)
3236 {
3237         struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3238         int ret;
3239 
3240         BUG_ON(!fs_info->balance_ctl);
3241 
3242         spin_lock(&fs_info->balance_lock);
3243         fs_info->balance_ctl = NULL;
3244         spin_unlock(&fs_info->balance_lock);
3245 
3246         kfree(bctl);
3247         ret = del_balance_item(fs_info);
3248         if (ret)
3249                 btrfs_handle_fs_error(fs_info, ret, NULL);
3250 }
3251 
3252 /*
3253  * Balance filters.  Return 1 if chunk should be filtered out
3254  * (should not be balanced).
3255  */
3256 static int chunk_profiles_filter(u64 chunk_type,
3257                                  struct btrfs_balance_args *bargs)
3258 {
3259         chunk_type = chunk_to_extended(chunk_type) &
3260                                 BTRFS_EXTENDED_PROFILE_MASK;
3261 
3262         if (bargs->profiles & chunk_type)
3263                 return 0;
3264 
3265         return 1;
3266 }
3267 
3268 static int chunk_usage_range_filter(struct btrfs_fs_info *fs_info, u64 chunk_offset,
3269                               struct btrfs_balance_args *bargs)
3270 {
3271         struct btrfs_block_group_cache *cache;
3272         u64 chunk_used;
3273         u64 user_thresh_min;
3274         u64 user_thresh_max;
3275         int ret = 1;
3276 
3277         cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3278         chunk_used = btrfs_block_group_used(&cache->item);
3279 
3280         if (bargs->usage_min == 0)
3281                 user_thresh_min = 0;
3282         else
3283                 user_thresh_min = div_factor_fine(cache->key.offset,
3284                                         bargs->usage_min);
3285 
3286         if (bargs->usage_max == 0)
3287                 user_thresh_max = 1;
3288         else if (bargs->usage_max > 100)
3289                 user_thresh_max = cache->key.offset;
3290         else
3291                 user_thresh_max = div_factor_fine(cache->key.offset,
3292                                         bargs->usage_max);
3293 
3294         if (user_thresh_min <= chunk_used && chunk_used < user_thresh_max)
3295                 ret = 0;
3296 
3297         btrfs_put_block_group(cache);
3298         return ret;
3299 }
3300 
3301 static int chunk_usage_filter(struct btrfs_fs_info *fs_info,
3302                 u64 chunk_offset, struct btrfs_balance_args *bargs)
3303 {
3304         struct btrfs_block_group_cache *cache;
3305         u64 chunk_used, user_thresh;
3306         int ret = 1;
3307 
3308         cache = btrfs_lookup_block_group(fs_info, chunk_offset);
3309         chunk_used = btrfs_block_group_used(&cache->item);
3310 
3311         if (bargs->usage_min == 0)
3312                 user_thresh = 1;
3313         else if (bargs->usage > 100)
3314                 user_thresh = cache->key.offset;
3315         else
3316                 user_thresh = div_factor_fine(cache->key.offset,
3317                                               bargs->usage);
3318 
3319         if (chunk_used < user_thresh)
3320                 ret = 0;
3321 
3322         btrfs_put_block_group(cache);
3323         return ret;
3324 }
3325 
3326 static int chunk_devid_filter(struct extent_buffer *leaf,
3327                               struct btrfs_chunk *chunk,
3328                               struct btrfs_balance_args *bargs)
3329 {
3330         struct btrfs_stripe *stripe;
3331         int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3332         int i;
3333 
3334         for (i = 0; i < num_stripes; i++) {
3335                 stripe = btrfs_stripe_nr(chunk, i);
3336                 if (btrfs_stripe_devid(leaf, stripe) == bargs->devid)
3337                         return 0;
3338         }
3339 
3340         return 1;
3341 }
3342 
3343 /* [pstart, pend) */
3344 static int chunk_drange_filter(struct extent_buffer *leaf,
3345                                struct btrfs_chunk *chunk,
3346                                struct btrfs_balance_args *bargs)
3347 {
3348         struct btrfs_stripe *stripe;
3349         int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3350         u64 stripe_offset;
3351         u64 stripe_length;
3352         int factor;
3353         int i;
3354 
3355         if (!(bargs->flags & BTRFS_BALANCE_ARGS_DEVID))
3356                 return 0;
3357 
3358         if (btrfs_chunk_type(leaf, chunk) & (BTRFS_BLOCK_GROUP_DUP |
3359              BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)) {
3360                 factor = num_stripes / 2;
3361         } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID5) {
3362                 factor = num_stripes - 1;
3363         } else if (btrfs_chunk_type(leaf, chunk) & BTRFS_BLOCK_GROUP_RAID6) {
3364                 factor = num_stripes - 2;
3365         } else {
3366                 factor = num_stripes;
3367         }
3368 
3369         for (i = 0; i < num_stripes; i++) {
3370                 stripe = btrfs_stripe_nr(chunk, i);
3371                 if (btrfs_stripe_devid(leaf, stripe) != bargs->devid)
3372                         continue;
3373 
3374                 stripe_offset = btrfs_stripe_offset(leaf, stripe);
3375                 stripe_length = btrfs_chunk_length(leaf, chunk);
3376                 stripe_length = div_u64(stripe_length, factor);
3377 
3378                 if (stripe_offset < bargs->pend &&
3379                     stripe_offset + stripe_length > bargs->pstart)
3380                         return 0;
3381         }
3382 
3383         return 1;
3384 }
3385 
3386 /* [vstart, vend) */
3387 static int chunk_vrange_filter(struct extent_buffer *leaf,
3388                                struct btrfs_chunk *chunk,
3389                                u64 chunk_offset,
3390                                struct btrfs_balance_args *bargs)
3391 {
3392         if (chunk_offset < bargs->vend &&
3393             chunk_offset + btrfs_chunk_length(leaf, chunk) > bargs->vstart)
3394                 /* at least part of the chunk is inside this vrange */
3395                 return 0;
3396 
3397         return 1;
3398 }
3399 
3400 static int chunk_stripes_range_filter(struct extent_buffer *leaf,
3401                                struct btrfs_chunk *chunk,
3402                                struct btrfs_balance_args *bargs)
3403 {
3404         int num_stripes = btrfs_chunk_num_stripes(leaf, chunk);
3405 
3406         if (bargs->stripes_min <= num_stripes
3407                         && num_stripes <= bargs->stripes_max)
3408                 return 0;
3409 
3410         return 1;
3411 }
3412 
3413 static int chunk_soft_convert_filter(u64 chunk_type,
3414                                      struct btrfs_balance_args *bargs)
3415 {
3416         if (!(bargs->flags & BTRFS_BALANCE_ARGS_CONVERT))
3417                 return 0;
3418 
3419         chunk_type = chunk_to_extended(chunk_type) &
3420                                 BTRFS_EXTENDED_PROFILE_MASK;
3421 
3422         if (bargs->target == chunk_type)
3423                 return 1;
3424 
3425         return 0;
3426 }
3427 
3428 static int should_balance_chunk(struct btrfs_fs_info *fs_info,
3429                                 struct extent_buffer *leaf,
3430                                 struct btrfs_chunk *chunk, u64 chunk_offset)
3431 {
3432         struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3433         struct btrfs_balance_args *bargs = NULL;
3434         u64 chunk_type = btrfs_chunk_type(leaf, chunk);
3435 
3436         /* type filter */
3437         if (!((chunk_type & BTRFS_BLOCK_GROUP_TYPE_MASK) &
3438               (bctl->flags & BTRFS_BALANCE_TYPE_MASK))) {
3439                 return 0;
3440         }
3441 
3442         if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3443                 bargs = &bctl->data;
3444         else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3445                 bargs = &bctl->sys;
3446         else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3447                 bargs = &bctl->meta;
3448 
3449         /* profiles filter */
3450         if ((bargs->flags & BTRFS_BALANCE_ARGS_PROFILES) &&
3451             chunk_profiles_filter(chunk_type, bargs)) {
3452                 return 0;
3453         }
3454 
3455         /* usage filter */
3456         if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE) &&
3457             chunk_usage_filter(fs_info, chunk_offset, bargs)) {
3458                 return 0;
3459         } else if ((bargs->flags & BTRFS_BALANCE_ARGS_USAGE_RANGE) &&
3460             chunk_usage_range_filter(fs_info, chunk_offset, bargs)) {
3461                 return 0;
3462         }
3463 
3464         /* devid filter */
3465         if ((bargs->flags & BTRFS_BALANCE_ARGS_DEVID) &&
3466             chunk_devid_filter(leaf, chunk, bargs)) {
3467                 return 0;
3468         }
3469 
3470         /* drange filter, makes sense only with devid filter */
3471         if ((bargs->flags & BTRFS_BALANCE_ARGS_DRANGE) &&
3472             chunk_drange_filter(leaf, chunk, bargs)) {
3473                 return 0;
3474         }
3475 
3476         /* vrange filter */
3477         if ((bargs->flags & BTRFS_BALANCE_ARGS_VRANGE) &&
3478             chunk_vrange_filter(leaf, chunk, chunk_offset, bargs)) {
3479                 return 0;
3480         }
3481 
3482         /* stripes filter */
3483         if ((bargs->flags & BTRFS_BALANCE_ARGS_STRIPES_RANGE) &&
3484             chunk_stripes_range_filter(leaf, chunk, bargs)) {
3485                 return 0;
3486         }
3487 
3488         /* soft profile changing mode */
3489         if ((bargs->flags & BTRFS_BALANCE_ARGS_SOFT) &&
3490             chunk_soft_convert_filter(chunk_type, bargs)) {
3491                 return 0;
3492         }
3493 
3494         /*
3495          * limited by count, must be the last filter
3496          */
3497         if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT)) {
3498                 if (bargs->limit == 0)
3499                         return 0;
3500                 else
3501                         bargs->limit--;
3502         } else if ((bargs->flags & BTRFS_BALANCE_ARGS_LIMIT_RANGE)) {
3503                 /*
3504                  * Same logic as the 'limit' filter; the minimum cannot be
3505                  * determined here because we do not have the global information
3506                  * about the count of all chunks that satisfy the filters.
3507                  */
3508                 if (bargs->limit_max == 0)
3509                         return 0;
3510                 else
3511                         bargs->limit_max--;
3512         }
3513 
3514         return 1;
3515 }
3516 
3517 static int __btrfs_balance(struct btrfs_fs_info *fs_info)
3518 {
3519         struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3520         struct btrfs_root *chunk_root = fs_info->chunk_root;
3521         struct btrfs_root *dev_root = fs_info->dev_root;
3522         struct list_head *devices;
3523         struct btrfs_device *device;
3524         u64 old_size;
3525         u64 size_to_free;
3526         u64 chunk_type;
3527         struct btrfs_chunk *chunk;
3528         struct btrfs_path *path = NULL;
3529         struct btrfs_key key;
3530         struct btrfs_key found_key;
3531         struct btrfs_trans_handle *trans;
3532         struct extent_buffer *leaf;
3533         int slot;
3534         int ret;
3535         int enospc_errors = 0;
3536         bool counting = true;
3537         /* The single value limit and min/max limits use the same bytes in the */
3538         u64 limit_data = bctl->data.limit;
3539         u64 limit_meta = bctl->meta.limit;
3540         u64 limit_sys = bctl->sys.limit;
3541         u32 count_data = 0;
3542         u32 count_meta = 0;
3543         u32 count_sys = 0;
3544         int chunk_reserved = 0;
3545 
3546         /* step one make some room on all the devices */
3547         devices = &fs_info->fs_devices->devices;
3548         list_for_each_entry(device, devices, dev_list) {
3549                 old_size = btrfs_device_get_total_bytes(device);
3550                 size_to_free = div_factor(old_size, 1);
3551                 size_to_free = min_t(u64, size_to_free, SZ_1M);
3552                 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state) ||
3553                     btrfs_device_get_total_bytes(device) -
3554                     btrfs_device_get_bytes_used(device) > size_to_free ||
3555                     test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
3556                         continue;
3557 
3558                 ret = btrfs_shrink_device(device, old_size - size_to_free);
3559                 if (ret == -ENOSPC)
3560                         break;
3561                 if (ret) {
3562                         /* btrfs_shrink_device never returns ret > 0 */
3563                         WARN_ON(ret > 0);
3564                         goto error;
3565                 }
3566 
3567                 trans = btrfs_start_transaction(dev_root, 0);
3568                 if (IS_ERR(trans)) {
3569                         ret = PTR_ERR(trans);
3570                         btrfs_info_in_rcu(fs_info,
3571                  "resize: unable to start transaction after shrinking device %s (error %d), old size %llu, new size %llu",
3572                                           rcu_str_deref(device->name), ret,
3573                                           old_size, old_size - size_to_free);
3574                         goto error;
3575                 }
3576 
3577                 ret = btrfs_grow_device(trans, device, old_size);
3578                 if (ret) {
3579                         btrfs_end_transaction(trans);
3580                         /* btrfs_grow_device never returns ret > 0 */
3581                         WARN_ON(ret > 0);
3582                         btrfs_info_in_rcu(fs_info,
3583                  "resize: unable to grow device after shrinking device %s (error %d), old size %llu, new size %llu",
3584                                           rcu_str_deref(device->name), ret,
3585                                           old_size, old_size - size_to_free);
3586                         goto error;
3587                 }
3588 
3589                 btrfs_end_transaction(trans);
3590         }
3591 
3592         /* step two, relocate all the chunks */
3593         path = btrfs_alloc_path();
3594         if (!path) {
3595                 ret = -ENOMEM;
3596                 goto error;
3597         }
3598 
3599         /* zero out stat counters */
3600         spin_lock(&fs_info->balance_lock);
3601         memset(&bctl->stat, 0, sizeof(bctl->stat));
3602         spin_unlock(&fs_info->balance_lock);
3603 again:
3604         if (!counting) {
3605                 /*
3606                  * The single value limit and min/max limits use the same bytes
3607                  * in the
3608                  */
3609                 bctl->data.limit = limit_data;
3610                 bctl->meta.limit = limit_meta;
3611                 bctl->sys.limit = limit_sys;
3612         }
3613         key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
3614         key.offset = (u64)-1;
3615         key.type = BTRFS_CHUNK_ITEM_KEY;
3616 
3617         while (1) {
3618                 if ((!counting && atomic_read(&fs_info->balance_pause_req)) ||
3619                     atomic_read(&fs_info->balance_cancel_req)) {
3620                         ret = -ECANCELED;
3621                         goto error;
3622                 }
3623 
3624                 mutex_lock(&fs_info->delete_unused_bgs_mutex);
3625                 ret = btrfs_search_slot(NULL, chunk_root, &key, path, 0, 0);
3626                 if (ret < 0) {
3627                         mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3628                         goto error;
3629                 }
3630 
3631                 /*
3632                  * this shouldn't happen, it means the last relocate
3633                  * failed
3634                  */
3635                 if (ret == 0)
3636                         BUG(); /* FIXME break ? */
3637 
3638                 ret = btrfs_previous_item(chunk_root, path, 0,
3639                                           BTRFS_CHUNK_ITEM_KEY);
3640                 if (ret) {
3641                         mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3642                         ret = 0;
3643                         break;
3644                 }
3645 
3646                 leaf = path->nodes[0];
3647                 slot = path->slots[0];
3648                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
3649 
3650                 if (found_key.objectid != key.objectid) {
3651                         mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3652                         break;
3653                 }
3654 
3655                 chunk = btrfs_item_ptr(leaf, slot, struct btrfs_chunk);
3656                 chunk_type = btrfs_chunk_type(leaf, chunk);
3657 
3658                 if (!counting) {
3659                         spin_lock(&fs_info->balance_lock);
3660                         bctl->stat.considered++;
3661                         spin_unlock(&fs_info->balance_lock);
3662                 }
3663 
3664                 ret = should_balance_chunk(fs_info, leaf, chunk,
3665                                            found_key.offset);
3666 
3667                 btrfs_release_path(path);
3668                 if (!ret) {
3669                         mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3670                         goto loop;
3671                 }
3672 
3673                 if (counting) {
3674                         mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3675                         spin_lock(&fs_info->balance_lock);
3676                         bctl->stat.expected++;
3677                         spin_unlock(&fs_info->balance_lock);
3678 
3679                         if (chunk_type & BTRFS_BLOCK_GROUP_DATA)
3680                                 count_data++;
3681                         else if (chunk_type & BTRFS_BLOCK_GROUP_SYSTEM)
3682                                 count_sys++;
3683                         else if (chunk_type & BTRFS_BLOCK_GROUP_METADATA)
3684                                 count_meta++;
3685 
3686                         goto loop;
3687                 }
3688 
3689                 /*
3690                  * Apply limit_min filter, no need to check if the LIMITS
3691                  * filter is used, limit_min is 0 by default
3692                  */
3693                 if (((chunk_type & BTRFS_BLOCK_GROUP_DATA) &&
3694                                         count_data < bctl->data.limit_min)
3695                                 || ((chunk_type & BTRFS_BLOCK_GROUP_METADATA) &&
3696                                         count_meta < bctl->meta.limit_min)
3697                                 || ((chunk_type & BTRFS_BLOCK_GROUP_SYSTEM) &&
3698                                         count_sys < bctl->sys.limit_min)) {
3699                         mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3700                         goto loop;
3701                 }
3702 
3703                 if (!chunk_reserved) {
3704                         /*
3705                          * We may be relocating the only data chunk we have,
3706                          * which could potentially end up with losing data's
3707                          * raid profile, so lets allocate an empty one in
3708                          * advance.
3709                          */
3710                         ret = btrfs_may_alloc_data_chunk(fs_info,
3711                                                          found_key.offset);
3712                         if (ret < 0) {
3713                                 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3714                                 goto error;
3715                         } else if (ret == 1) {
3716                                 chunk_reserved = 1;
3717                         }
3718                 }
3719 
3720                 ret = btrfs_relocate_chunk(fs_info, found_key.offset);
3721                 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
3722                 if (ret && ret != -ENOSPC)
3723                         goto error;
3724                 if (ret == -ENOSPC) {
3725                         enospc_errors++;
3726                 } else {
3727                         spin_lock(&fs_info->balance_lock);
3728                         bctl->stat.completed++;
3729                         spin_unlock(&fs_info->balance_lock);
3730                 }
3731 loop:
3732                 if (found_key.offset == 0)
3733                         break;
3734                 key.offset = found_key.offset - 1;
3735         }
3736 
3737         if (counting) {
3738                 btrfs_release_path(path);
3739                 counting = false;
3740                 goto again;
3741         }
3742 error:
3743         btrfs_free_path(path);
3744         if (enospc_errors) {
3745                 btrfs_info(fs_info, "%d enospc errors during balance",
3746                            enospc_errors);
3747                 if (!ret)
3748                         ret = -ENOSPC;
3749         }
3750 
3751         return ret;
3752 }
3753 
3754 /**
3755  * alloc_profile_is_valid - see if a given profile is valid and reduced
3756  * @flags: profile to validate
3757  * @extended: if true @flags is treated as an extended profile
3758  */
3759 static int alloc_profile_is_valid(u64 flags, int extended)
3760 {
3761         u64 mask = (extended ? BTRFS_EXTENDED_PROFILE_MASK :
3762                                BTRFS_BLOCK_GROUP_PROFILE_MASK);
3763 
3764         flags &= ~BTRFS_BLOCK_GROUP_TYPE_MASK;
3765 
3766         /* 1) check that all other bits are zeroed */
3767         if (flags & ~mask)
3768                 return 0;
3769 
3770         /* 2) see if profile is reduced */
3771         if (flags == 0)
3772                 return !extended; /* "" is valid for usual profiles */
3773 
3774         /* true if exactly one bit set */
3775         return (flags & (flags - 1)) == 0;
3776 }
3777 
3778 static inline int balance_need_close(struct btrfs_fs_info *fs_info)
3779 {
3780         /* cancel requested || normal exit path */
3781         return atomic_read(&fs_info->balance_cancel_req) ||
3782                 (atomic_read(&fs_info->balance_pause_req) == 0 &&
3783                  atomic_read(&fs_info->balance_cancel_req) == 0);
3784 }
3785 
3786 /* Non-zero return value signifies invalidity */
3787 static inline int validate_convert_profile(struct btrfs_balance_args *bctl_arg,
3788                 u64 allowed)
3789 {
3790         return ((bctl_arg->flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3791                 (!alloc_profile_is_valid(bctl_arg->target, 1) ||
3792                  (bctl_arg->target & ~allowed)));
3793 }
3794 
3795 /*
3796  * Should be called with balance mutexe held
3797  */
3798 int btrfs_balance(struct btrfs_fs_info *fs_info,
3799                   struct btrfs_balance_control *bctl,
3800                   struct btrfs_ioctl_balance_args *bargs)
3801 {
3802         u64 meta_target, data_target;
3803         u64 allowed;
3804         int mixed = 0;
3805         int ret;
3806         u64 num_devices;
3807         unsigned seq;
3808 
3809         if (btrfs_fs_closing(fs_info) ||
3810             atomic_read(&fs_info->balance_pause_req) ||
3811             atomic_read(&fs_info->balance_cancel_req)) {
3812                 ret = -EINVAL;
3813                 goto out;
3814         }
3815 
3816         allowed = btrfs_super_incompat_flags(fs_info->super_copy);
3817         if (allowed & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
3818                 mixed = 1;
3819 
3820         /*
3821          * In case of mixed groups both data and meta should be picked,
3822          * and identical options should be given for both of them.
3823          */
3824         allowed = BTRFS_BALANCE_DATA | BTRFS_BALANCE_METADATA;
3825         if (mixed && (bctl->flags & allowed)) {
3826                 if (!(bctl->flags & BTRFS_BALANCE_DATA) ||
3827                     !(bctl->flags & BTRFS_BALANCE_METADATA) ||
3828                     memcmp(&bctl->data, &bctl->meta, sizeof(bctl->data))) {
3829                         btrfs_err(fs_info,
3830           "balance: mixed groups data and metadata options must be the same");
3831                         ret = -EINVAL;
3832                         goto out;
3833                 }
3834         }
3835 
3836         num_devices = fs_info->fs_devices->num_devices;
3837         btrfs_dev_replace_read_lock(&fs_info->dev_replace);
3838         if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace)) {
3839                 BUG_ON(num_devices < 1);
3840                 num_devices--;
3841         }
3842         btrfs_dev_replace_read_unlock(&fs_info->dev_replace);
3843         allowed = BTRFS_AVAIL_ALLOC_BIT_SINGLE | BTRFS_BLOCK_GROUP_DUP;
3844         if (num_devices > 1)
3845                 allowed |= (BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID1);
3846         if (num_devices > 2)
3847                 allowed |= BTRFS_BLOCK_GROUP_RAID5;
3848         if (num_devices > 3)
3849                 allowed |= (BTRFS_BLOCK_GROUP_RAID10 |
3850                             BTRFS_BLOCK_GROUP_RAID6);
3851         if (validate_convert_profile(&bctl->data, allowed)) {
3852                 int index = btrfs_bg_flags_to_raid_index(bctl->data.target);
3853 
3854                 btrfs_err(fs_info,
3855                           "balance: invalid convert data profile %s",
3856                           get_raid_name(index));
3857                 ret = -EINVAL;
3858                 goto out;
3859         }
3860         if (validate_convert_profile(&bctl->meta, allowed)) {
3861                 int index = btrfs_bg_flags_to_raid_index(bctl->meta.target);
3862 
3863                 btrfs_err(fs_info,
3864                           "balance: invalid convert metadata profile %s",
3865                           get_raid_name(index));
3866                 ret = -EINVAL;
3867                 goto out;
3868         }
3869         if (validate_convert_profile(&bctl->sys, allowed)) {
3870                 int index = btrfs_bg_flags_to_raid_index(bctl->sys.target);
3871 
3872                 btrfs_err(fs_info,
3873                           "balance: invalid convert system profile %s",
3874                           get_raid_name(index));
3875                 ret = -EINVAL;
3876                 goto out;
3877         }
3878 
3879         /* allow to reduce meta or sys integrity only if force set */
3880         allowed = BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
3881                         BTRFS_BLOCK_GROUP_RAID10 |
3882                         BTRFS_BLOCK_GROUP_RAID5 |
3883                         BTRFS_BLOCK_GROUP_RAID6;
3884         do {
3885                 seq = read_seqbegin(&fs_info->profiles_lock);
3886 
3887                 if (((bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3888                      (fs_info->avail_system_alloc_bits & allowed) &&
3889                      !(bctl->sys.target & allowed)) ||
3890                     ((bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) &&
3891                      (fs_info->avail_metadata_alloc_bits & allowed) &&
3892                      !(bctl->meta.target & allowed))) {
3893                         if (bctl->flags & BTRFS_BALANCE_FORCE) {
3894                                 btrfs_info(fs_info,
3895                                 "balance: force reducing metadata integrity");
3896                         } else {
3897                                 btrfs_err(fs_info,
3898         "balance: reduces metadata integrity, use --force if you want this");
3899                                 ret = -EINVAL;
3900                                 goto out;
3901                         }
3902                 }
3903         } while (read_seqretry(&fs_info->profiles_lock, seq));
3904 
3905         /* if we're not converting, the target field is uninitialized */
3906         meta_target = (bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
3907                 bctl->meta.target : fs_info->avail_metadata_alloc_bits;
3908         data_target = (bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) ?
3909                 bctl->data.target : fs_info->avail_data_alloc_bits;
3910         if (btrfs_get_num_tolerated_disk_barrier_failures(meta_target) <
3911                 btrfs_get_num_tolerated_disk_barrier_failures(data_target)) {
3912                 int meta_index = btrfs_bg_flags_to_raid_index(meta_target);
3913                 int data_index = btrfs_bg_flags_to_raid_index(data_target);
3914 
3915                 btrfs_warn(fs_info,
3916         "balance: metadata profile %s has lower redundancy than data profile %s",
3917                            get_raid_name(meta_index), get_raid_name(data_index));
3918         }
3919 
3920         ret = insert_balance_item(fs_info, bctl);
3921         if (ret && ret != -EEXIST)
3922                 goto out;
3923 
3924         if (!(bctl->flags & BTRFS_BALANCE_RESUME)) {
3925                 BUG_ON(ret == -EEXIST);
3926                 BUG_ON(fs_info->balance_ctl);
3927                 spin_lock(&fs_info->balance_lock);
3928                 fs_info->balance_ctl = bctl;
3929                 spin_unlock(&fs_info->balance_lock);
3930         } else {
3931                 BUG_ON(ret != -EEXIST);
3932                 spin_lock(&fs_info->balance_lock);
3933                 update_balance_args(bctl);
3934                 spin_unlock(&fs_info->balance_lock);
3935         }
3936 
3937         ASSERT(!test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
3938         set_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
3939         mutex_unlock(&fs_info->balance_mutex);
3940 
3941         ret = __btrfs_balance(fs_info);
3942 
3943         mutex_lock(&fs_info->balance_mutex);
3944         clear_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags);
3945 
3946         if (bargs) {
3947                 memset(bargs, 0, sizeof(*bargs));
3948                 btrfs_update_ioctl_balance_args(fs_info, bargs);
3949         }
3950 
3951         if ((ret && ret != -ECANCELED && ret != -ENOSPC) ||
3952             balance_need_close(fs_info)) {
3953                 reset_balance_state(fs_info);
3954                 clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
3955         }
3956 
3957         wake_up(&fs_info->balance_wait_q);
3958 
3959         return ret;
3960 out:
3961         if (bctl->flags & BTRFS_BALANCE_RESUME)
3962                 reset_balance_state(fs_info);
3963         else
3964                 kfree(bctl);
3965         clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
3966 
3967         return ret;
3968 }
3969 
3970 static int balance_kthread(void *data)
3971 {
3972         struct btrfs_fs_info *fs_info = data;
3973         int ret = 0;
3974 
3975         mutex_lock(&fs_info->balance_mutex);
3976         if (fs_info->balance_ctl) {
3977                 btrfs_info(fs_info, "balance: resuming");
3978                 ret = btrfs_balance(fs_info, fs_info->balance_ctl, NULL);
3979         }
3980         mutex_unlock(&fs_info->balance_mutex);
3981 
3982         return ret;
3983 }
3984 
3985 int btrfs_resume_balance_async(struct btrfs_fs_info *fs_info)
3986 {
3987         struct task_struct *tsk;
3988 
3989         mutex_lock(&fs_info->balance_mutex);
3990         if (!fs_info->balance_ctl) {
3991                 mutex_unlock(&fs_info->balance_mutex);
3992                 return 0;
3993         }
3994         mutex_unlock(&fs_info->balance_mutex);
3995 
3996         if (btrfs_test_opt(fs_info, SKIP_BALANCE)) {
3997                 btrfs_info(fs_info, "balance: resume skipped");
3998                 return 0;
3999         }
4000 
4001         /*
4002          * A ro->rw remount sequence should continue with the paused balance
4003          * regardless of who pauses it, system or the user as of now, so set
4004          * the resume flag.
4005          */
4006         spin_lock(&fs_info->balance_lock);
4007         fs_info->balance_ctl->flags |= BTRFS_BALANCE_RESUME;
4008         spin_unlock(&fs_info->balance_lock);
4009 
4010         tsk = kthread_run(balance_kthread, fs_info, "btrfs-balance");
4011         return PTR_ERR_OR_ZERO(tsk);
4012 }
4013 
4014 int btrfs_recover_balance(struct btrfs_fs_info *fs_info)
4015 {
4016         struct btrfs_balance_control *bctl;
4017         struct btrfs_balance_item *item;
4018         struct btrfs_disk_balance_args disk_bargs;
4019         struct btrfs_path *path;
4020         struct extent_buffer *leaf;
4021         struct btrfs_key key;
4022         int ret;
4023 
4024         path = btrfs_alloc_path();
4025         if (!path)
4026                 return -ENOMEM;
4027 
4028         key.objectid = BTRFS_BALANCE_OBJECTID;
4029         key.type = BTRFS_TEMPORARY_ITEM_KEY;
4030         key.offset = 0;
4031 
4032         ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4033         if (ret < 0)
4034                 goto out;
4035         if (ret > 0) { /* ret = -ENOENT; */
4036                 ret = 0;
4037                 goto out;
4038         }
4039 
4040         bctl = kzalloc(sizeof(*bctl), GFP_NOFS);
4041         if (!bctl) {
4042                 ret = -ENOMEM;
4043                 goto out;
4044         }
4045 
4046         leaf = path->nodes[0];
4047         item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_balance_item);
4048 
4049         bctl->flags = btrfs_balance_flags(leaf, item);
4050         bctl->flags |= BTRFS_BALANCE_RESUME;
4051 
4052         btrfs_balance_data(leaf, item, &disk_bargs);
4053         btrfs_disk_balance_args_to_cpu(&bctl->data, &disk_bargs);
4054         btrfs_balance_meta(leaf, item, &disk_bargs);
4055         btrfs_disk_balance_args_to_cpu(&bctl->meta, &disk_bargs);
4056         btrfs_balance_sys(leaf, item, &disk_bargs);
4057         btrfs_disk_balance_args_to_cpu(&bctl->sys, &disk_bargs);
4058 
4059         /*
4060          * This should never happen, as the paused balance state is recovered
4061          * during mount without any chance of other exclusive ops to collide.
4062          *
4063          * This gives the exclusive op status to balance and keeps in paused
4064          * state until user intervention (cancel or umount). If the ownership
4065          * cannot be assigned, show a message but do not fail. The balance
4066          * is in a paused state and must have fs_info::balance_ctl properly
4067          * set up.
4068          */
4069         if (test_and_set_bit(BTRFS_FS_EXCL_OP, &fs_info->flags))
4070                 btrfs_warn(fs_info,
4071         "balance: cannot set exclusive op status, resume manually");
4072 
4073         mutex_lock(&fs_info->balance_mutex);
4074         BUG_ON(fs_info->balance_ctl);
4075         spin_lock(&fs_info->balance_lock);
4076         fs_info->balance_ctl = bctl;
4077         spin_unlock(&fs_info->balance_lock);
4078         mutex_unlock(&fs_info->balance_mutex);
4079 out:
4080         btrfs_free_path(path);
4081         return ret;
4082 }
4083 
4084 int btrfs_pause_balance(struct btrfs_fs_info *fs_info)
4085 {
4086         int ret = 0;
4087 
4088         mutex_lock(&fs_info->balance_mutex);
4089         if (!fs_info->balance_ctl) {
4090                 mutex_unlock(&fs_info->balance_mutex);
4091                 return -ENOTCONN;
4092         }
4093 
4094         if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4095                 atomic_inc(&fs_info->balance_pause_req);
4096                 mutex_unlock(&fs_info->balance_mutex);
4097 
4098                 wait_event(fs_info->balance_wait_q,
4099                            !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4100 
4101                 mutex_lock(&fs_info->balance_mutex);
4102                 /* we are good with balance_ctl ripped off from under us */
4103                 BUG_ON(test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4104                 atomic_dec(&fs_info->balance_pause_req);
4105         } else {
4106                 ret = -ENOTCONN;
4107         }
4108 
4109         mutex_unlock(&fs_info->balance_mutex);
4110         return ret;
4111 }
4112 
4113 int btrfs_cancel_balance(struct btrfs_fs_info *fs_info)
4114 {
4115         mutex_lock(&fs_info->balance_mutex);
4116         if (!fs_info->balance_ctl) {
4117                 mutex_unlock(&fs_info->balance_mutex);
4118                 return -ENOTCONN;
4119         }
4120 
4121         /*
4122          * A paused balance with the item stored on disk can be resumed at
4123          * mount time if the mount is read-write. Otherwise it's still paused
4124          * and we must not allow cancelling as it deletes the item.
4125          */
4126         if (sb_rdonly(fs_info->sb)) {
4127                 mutex_unlock(&fs_info->balance_mutex);
4128                 return -EROFS;
4129         }
4130 
4131         atomic_inc(&fs_info->balance_cancel_req);
4132         /*
4133          * if we are running just wait and return, balance item is
4134          * deleted in btrfs_balance in this case
4135          */
4136         if (test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags)) {
4137                 mutex_unlock(&fs_info->balance_mutex);
4138                 wait_event(fs_info->balance_wait_q,
4139                            !test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4140                 mutex_lock(&fs_info->balance_mutex);
4141         } else {
4142                 mutex_unlock(&fs_info->balance_mutex);
4143                 /*
4144                  * Lock released to allow other waiters to continue, we'll
4145                  * reexamine the status again.
4146                  */
4147                 mutex_lock(&fs_info->balance_mutex);
4148 
4149                 if (fs_info->balance_ctl) {
4150                         reset_balance_state(fs_info);
4151                         clear_bit(BTRFS_FS_EXCL_OP, &fs_info->flags);
4152                         btrfs_info(fs_info, "balance: canceled");
4153                 }
4154         }
4155 
4156         BUG_ON(fs_info->balance_ctl ||
4157                 test_bit(BTRFS_FS_BALANCE_RUNNING, &fs_info->flags));
4158         atomic_dec(&fs_info->balance_cancel_req);
4159         mutex_unlock(&fs_info->balance_mutex);
4160         return 0;
4161 }
4162 
4163 static int btrfs_uuid_scan_kthread(void *data)
4164 {
4165         struct btrfs_fs_info *fs_info = data;
4166         struct btrfs_root *root = fs_info->tree_root;
4167         struct btrfs_key key;
4168         struct btrfs_path *path = NULL;
4169         int ret = 0;
4170         struct extent_buffer *eb;
4171         int slot;
4172         struct btrfs_root_item root_item;
4173         u32 item_size;
4174         struct btrfs_trans_handle *trans = NULL;
4175 
4176         path = btrfs_alloc_path();
4177         if (!path) {
4178                 ret = -ENOMEM;
4179                 goto out;
4180         }
4181 
4182         key.objectid = 0;
4183         key.type = BTRFS_ROOT_ITEM_KEY;
4184         key.offset = 0;
4185 
4186         while (1) {
4187                 ret = btrfs_search_forward(root, &key, path,
4188                                 BTRFS_OLDEST_GENERATION);
4189                 if (ret) {
4190                         if (ret > 0)
4191                                 ret = 0;
4192                         break;
4193                 }
4194 
4195                 if (key.type != BTRFS_ROOT_ITEM_KEY ||
4196                     (key.objectid < BTRFS_FIRST_FREE_OBJECTID &&
4197                      key.objectid != BTRFS_FS_TREE_OBJECTID) ||
4198                     key.objectid > BTRFS_LAST_FREE_OBJECTID)
4199                         goto skip;
4200 
4201                 eb = path->nodes[0];
4202                 slot = path->slots[0];
4203                 item_size = btrfs_item_size_nr(eb, slot);
4204                 if (item_size < sizeof(root_item))
4205                         goto skip;
4206 
4207                 read_extent_buffer(eb, &root_item,
4208                                    btrfs_item_ptr_offset(eb, slot),
4209                                    (int)sizeof(root_item));
4210                 if (btrfs_root_refs(&root_item) == 0)
4211                         goto skip;
4212 
4213                 if (!btrfs_is_empty_uuid(root_item.uuid) ||
4214                     !btrfs_is_empty_uuid(root_item.received_uuid)) {
4215                         if (trans)
4216                                 goto update_tree;
4217 
4218                         btrfs_release_path(path);
4219                         /*
4220                          * 1 - subvol uuid item
4221                          * 1 - received_subvol uuid item
4222                          */
4223                         trans = btrfs_start_transaction(fs_info->uuid_root, 2);
4224                         if (IS_ERR(trans)) {
4225                                 ret = PTR_ERR(trans);
4226                                 break;
4227                         }
4228                         continue;
4229                 } else {
4230                         goto skip;
4231                 }
4232 update_tree:
4233                 if (!btrfs_is_empty_uuid(root_item.uuid)) {
4234                         ret = btrfs_uuid_tree_add(trans, root_item.uuid,
4235                                                   BTRFS_UUID_KEY_SUBVOL,
4236                                                   key.objectid);
4237                         if (ret < 0) {
4238                                 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4239                                         ret);
4240                                 break;
4241                         }
4242                 }
4243 
4244                 if (!btrfs_is_empty_uuid(root_item.received_uuid)) {
4245                         ret = btrfs_uuid_tree_add(trans,
4246                                                   root_item.received_uuid,
4247                                                  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4248                                                   key.objectid);
4249                         if (ret < 0) {
4250                                 btrfs_warn(fs_info, "uuid_tree_add failed %d",
4251                                         ret);
4252                                 break;
4253                         }
4254                 }
4255 
4256 skip:
4257                 if (trans) {
4258                         ret = btrfs_end_transaction(trans);
4259                         trans = NULL;
4260                         if (ret)
4261                                 break;
4262                 }
4263 
4264                 btrfs_release_path(path);
4265                 if (key.offset < (u64)-1) {
4266                         key.offset++;
4267                 } else if (key.type < BTRFS_ROOT_ITEM_KEY) {
4268                         key.offset = 0;
4269                         key.type = BTRFS_ROOT_ITEM_KEY;
4270                 } else if (key.objectid < (u64)-1) {
4271                         key.offset = 0;
4272                         key.type = BTRFS_ROOT_ITEM_KEY;
4273                         key.objectid++;
4274                 } else {
4275                         break;
4276                 }
4277                 cond_resched();
4278         }
4279 
4280 out:
4281         btrfs_free_path(path);
4282         if (trans && !IS_ERR(trans))
4283                 btrfs_end_transaction(trans);
4284         if (ret)
4285                 btrfs_warn(fs_info, "btrfs_uuid_scan_kthread failed %d", ret);
4286         else
4287                 set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
4288         up(&fs_info->uuid_tree_rescan_sem);
4289         return 0;
4290 }
4291 
4292 /*
4293  * Callback for btrfs_uuid_tree_iterate().
4294  * returns:
4295  * 0    check succeeded, the entry is not outdated.
4296  * < 0  if an error occurred.
4297  * > 0  if the check failed, which means the caller shall remove the entry.
4298  */
4299 static int btrfs_check_uuid_tree_entry(struct btrfs_fs_info *fs_info,
4300                                        u8 *uuid, u8 type, u64 subid)
4301 {
4302         struct btrfs_key key;
4303         int ret = 0;
4304         struct btrfs_root *subvol_root;
4305 
4306         if (type != BTRFS_UUID_KEY_SUBVOL &&
4307             type != BTRFS_UUID_KEY_RECEIVED_SUBVOL)
4308                 goto out;
4309 
4310         key.objectid = subid;
4311         key.type = BTRFS_ROOT_ITEM_KEY;
4312         key.offset = (u64)-1;
4313         subvol_root = btrfs_read_fs_root_no_name(fs_info, &key);
4314         if (IS_ERR(subvol_root)) {
4315                 ret = PTR_ERR(subvol_root);
4316                 if (ret == -ENOENT)
4317                         ret = 1;
4318                 goto out;
4319         }
4320 
4321         switch (type) {
4322         case BTRFS_UUID_KEY_SUBVOL:
4323                 if (memcmp(uuid, subvol_root->root_item.uuid, BTRFS_UUID_SIZE))
4324                         ret = 1;
4325                 break;
4326         case BTRFS_UUID_KEY_RECEIVED_SUBVOL:
4327                 if (memcmp(uuid, subvol_root->root_item.received_uuid,
4328                            BTRFS_UUID_SIZE))
4329                         ret = 1;
4330                 break;
4331         }
4332 
4333 out:
4334         return ret;
4335 }
4336 
4337 static int btrfs_uuid_rescan_kthread(void *data)
4338 {
4339         struct btrfs_fs_info *fs_info = (struct btrfs_fs_info *)data;
4340         int ret;
4341 
4342         /*
4343          * 1st step is to iterate through the existing UUID tree and
4344          * to delete all entries that contain outdated data.
4345          * 2nd step is to add all missing entries to the UUID tree.
4346          */
4347         ret = btrfs_uuid_tree_iterate(fs_info, btrfs_check_uuid_tree_entry);
4348         if (ret < 0) {
4349                 btrfs_warn(fs_info, "iterating uuid_tree failed %d", ret);
4350                 up(&fs_info->uuid_tree_rescan_sem);
4351                 return ret;
4352         }
4353         return btrfs_uuid_scan_kthread(data);
4354 }
4355 
4356 int btrfs_create_uuid_tree(struct btrfs_fs_info *fs_info)
4357 {
4358         struct btrfs_trans_handle *trans;
4359         struct btrfs_root *tree_root = fs_info->tree_root;
4360         struct btrfs_root *uuid_root;
4361         struct task_struct *task;
4362         int ret;
4363 
4364         /*
4365          * 1 - root node
4366          * 1 - root item
4367          */
4368         trans = btrfs_start_transaction(tree_root, 2);
4369         if (IS_ERR(trans))
4370                 return PTR_ERR(trans);
4371 
4372         uuid_root = btrfs_create_tree(trans, fs_info,
4373                                       BTRFS_UUID_TREE_OBJECTID);
4374         if (IS_ERR(uuid_root)) {
4375                 ret = PTR_ERR(uuid_root);
4376                 btrfs_abort_transaction(trans, ret);
4377                 btrfs_end_transaction(trans);
4378                 return ret;
4379         }
4380 
4381         fs_info->uuid_root = uuid_root;
4382 
4383         ret = btrfs_commit_transaction(trans);
4384         if (ret)
4385                 return ret;
4386 
4387         down(&fs_info->uuid_tree_rescan_sem);
4388         task = kthread_run(btrfs_uuid_scan_kthread, fs_info, "btrfs-uuid");
4389         if (IS_ERR(task)) {
4390                 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4391                 btrfs_warn(fs_info, "failed to start uuid_scan task");
4392                 up(&fs_info->uuid_tree_rescan_sem);
4393                 return PTR_ERR(task);
4394         }
4395 
4396         return 0;
4397 }
4398 
4399 int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
4400 {
4401         struct task_struct *task;
4402 
4403         down(&fs_info->uuid_tree_rescan_sem);
4404         task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
4405         if (IS_ERR(task)) {
4406                 /* fs_info->update_uuid_tree_gen remains 0 in all error case */
4407                 btrfs_warn(fs_info, "failed to start uuid_rescan task");
4408                 up(&fs_info->uuid_tree_rescan_sem);
4409                 return PTR_ERR(task);
4410         }
4411 
4412         return 0;
4413 }
4414 
4415 /*
4416  * shrinking a device means finding all of the device extents past
4417  * the new size, and then following the back refs to the chunks.
4418  * The chunk relocation code actually frees the device extent
4419  */
4420 int btrfs_shrink_device(struct btrfs_device *device, u64 new_size)
4421 {
4422         struct btrfs_fs_info *fs_info = device->fs_info;
4423         struct btrfs_root *root = fs_info->dev_root;
4424         struct btrfs_trans_handle *trans;
4425         struct btrfs_dev_extent *dev_extent = NULL;
4426         struct btrfs_path *path;
4427         u64 length;
4428         u64 chunk_offset;
4429         int ret;
4430         int slot;
4431         int failed = 0;
4432         bool retried = false;
4433         bool checked_pending_chunks = false;
4434         struct extent_buffer *l;
4435         struct btrfs_key key;
4436         struct btrfs_super_block *super_copy = fs_info->super_copy;
4437         u64 old_total = btrfs_super_total_bytes(super_copy);
4438         u64 old_size = btrfs_device_get_total_bytes(device);
4439         u64 diff;
4440 
4441         new_size = round_down(new_size, fs_info->sectorsize);
4442         diff = round_down(old_size - new_size, fs_info->sectorsize);
4443 
4444         if (test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4445                 return -EINVAL;
4446 
4447         path = btrfs_alloc_path();
4448         if (!path)
4449                 return -ENOMEM;
4450 
4451         path->reada = READA_BACK;
4452 
4453         mutex_lock(&fs_info->chunk_mutex);
4454 
4455         btrfs_device_set_total_bytes(device, new_size);
4456         if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4457                 device->fs_devices->total_rw_bytes -= diff;
4458                 atomic64_sub(diff, &fs_info->free_chunk_space);
4459         }
4460         mutex_unlock(&fs_info->chunk_mutex);
4461 
4462 again:
4463         key.objectid = device->devid;
4464         key.offset = (u64)-1;
4465         key.type = BTRFS_DEV_EXTENT_KEY;
4466 
4467         do {
4468                 mutex_lock(&fs_info->delete_unused_bgs_mutex);
4469                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
4470                 if (ret < 0) {
4471                         mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4472                         goto done;
4473                 }
4474 
4475                 ret = btrfs_previous_item(root, path, 0, key.type);
4476                 if (ret)
4477                         mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4478                 if (ret < 0)
4479                         goto done;
4480                 if (ret) {
4481                         ret = 0;
4482                         btrfs_release_path(path);
4483                         break;
4484                 }
4485 
4486                 l = path->nodes[0];
4487                 slot = path->slots[0];
4488                 btrfs_item_key_to_cpu(l, &key, path->slots[0]);
4489 
4490                 if (key.objectid != device->devid) {
4491                         mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4492                         btrfs_release_path(path);
4493                         break;
4494                 }
4495 
4496                 dev_extent = btrfs_item_ptr(l, slot, struct btrfs_dev_extent);
4497                 length = btrfs_dev_extent_length(l, dev_extent);
4498 
4499                 if (key.offset + length <= new_size) {
4500                         mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4501                         btrfs_release_path(path);
4502                         break;
4503                 }
4504 
4505                 chunk_offset = btrfs_dev_extent_chunk_offset(l, dev_extent);
4506                 btrfs_release_path(path);
4507 
4508                 /*
4509                  * We may be relocating the only data chunk we have,
4510                  * which could potentially end up with losing data's
4511                  * raid profile, so lets allocate an empty one in
4512                  * advance.
4513                  */
4514                 ret = btrfs_may_alloc_data_chunk(fs_info, chunk_offset);
4515                 if (ret < 0) {
4516                         mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4517                         goto done;
4518                 }
4519 
4520                 ret = btrfs_relocate_chunk(fs_info, chunk_offset);
4521                 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
4522                 if (ret && ret != -ENOSPC)
4523                         goto done;
4524                 if (ret == -ENOSPC)
4525                         failed++;
4526         } while (key.offset-- > 0);
4527 
4528         if (failed && !retried) {
4529                 failed = 0;
4530                 retried = true;
4531                 goto again;
4532         } else if (failed && retried) {
4533                 ret = -ENOSPC;
4534                 goto done;
4535         }
4536 
4537         /* Shrinking succeeded, else we would be at "done". */
4538         trans = btrfs_start_transaction(root, 0);
4539         if (IS_ERR(trans)) {
4540                 ret = PTR_ERR(trans);
4541                 goto done;
4542         }
4543 
4544         mutex_lock(&fs_info->chunk_mutex);
4545 
4546         /*
4547          * We checked in the above loop all device extents that were already in
4548          * the device tree. However before we have updated the device's
4549          * total_bytes to the new size, we might have had chunk allocations that
4550          * have not complete yet (new block groups attached to transaction
4551          * handles), and therefore their device extents were not yet in the
4552          * device tree and we missed them in the loop above. So if we have any
4553          * pending chunk using a device extent that overlaps the device range
4554          * that we can not use anymore, commit the current transaction and
4555          * repeat the search on the device tree - this way we guarantee we will
4556          * not have chunks using device extents that end beyond 'new_size'.
4557          */
4558         if (!checked_pending_chunks) {
4559                 u64 start = new_size;
4560                 u64 len = old_size - new_size;
4561 
4562                 if (contains_pending_extent(trans->transaction, device,
4563                                             &start, len)) {
4564                         mutex_unlock(&fs_info->chunk_mutex);
4565                         checked_pending_chunks = true;
4566                         failed = 0;
4567                         retried = false;
4568                         ret = btrfs_commit_transaction(trans);
4569                         if (ret)
4570                                 goto done;
4571                         goto again;
4572                 }
4573         }
4574 
4575         btrfs_device_set_disk_total_bytes(device, new_size);
4576         if (list_empty(&device->resized_list))
4577                 list_add_tail(&device->resized_list,
4578                               &fs_info->fs_devices->resized_devices);
4579 
4580         WARN_ON(diff > old_total);
4581         btrfs_set_super_total_bytes(super_copy,
4582                         round_down(old_total - diff, fs_info->sectorsize));
4583         mutex_unlock(&fs_info->chunk_mutex);
4584 
4585         /* Now btrfs_update_device() will change the on-disk size. */
4586         ret = btrfs_update_device(trans, device);
4587         if (ret < 0) {
4588                 btrfs_abort_transaction(trans, ret);
4589                 btrfs_end_transaction(trans);
4590         } else {
4591                 ret = btrfs_commit_transaction(trans);
4592         }
4593 done:
4594         btrfs_free_path(path);
4595         if (ret) {
4596                 mutex_lock(&fs_info->chunk_mutex);
4597                 btrfs_device_set_total_bytes(device, old_size);
4598                 if (test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
4599                         device->fs_devices->total_rw_bytes += diff;
4600                 atomic64_add(diff, &fs_info->free_chunk_space);
4601                 mutex_unlock(&fs_info->chunk_mutex);
4602         }
4603         return ret;
4604 }
4605 
4606 static int btrfs_add_system_chunk(struct btrfs_fs_info *fs_info,
4607                            struct btrfs_key *key,
4608                            struct btrfs_chunk *chunk, int item_size)
4609 {
4610         struct btrfs_super_block *super_copy = fs_info->super_copy;
4611         struct btrfs_disk_key disk_key;
4612         u32 array_size;
4613         u8 *ptr;
4614 
4615         mutex_lock(&fs_info->chunk_mutex);
4616         array_size = btrfs_super_sys_array_size(super_copy);
4617         if (array_size + item_size + sizeof(disk_key)
4618                         > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
4619                 mutex_unlock(&fs_info->chunk_mutex);
4620                 return -EFBIG;
4621         }
4622 
4623         ptr = super_copy->sys_chunk_array + array_size;
4624         btrfs_cpu_key_to_disk(&disk_key, key);
4625         memcpy(ptr, &disk_key, sizeof(disk_key));
4626         ptr += sizeof(disk_key);
4627         memcpy(ptr, chunk, item_size);
4628         item_size += sizeof(disk_key);
4629         btrfs_set_super_sys_array_size(super_copy, array_size + item_size);
4630         mutex_unlock(&fs_info->chunk_mutex);
4631 
4632         return 0;
4633 }
4634 
4635 /*
4636  * sort the devices in descending order by max_avail, total_avail
4637  */
4638 static int btrfs_cmp_device_info(const void *a, const void *b)
4639 {
4640         const struct btrfs_device_info *di_a = a;
4641         const struct btrfs_device_info *di_b = b;
4642 
4643         if (di_a->max_avail > di_b->max_avail)
4644                 return -1;
4645         if (di_a->max_avail < di_b->max_avail)
4646                 return 1;
4647         if (di_a->total_avail > di_b->total_avail)
4648                 return -1;
4649         if (di_a->total_avail < di_b->total_avail)
4650                 return 1;
4651         return 0;
4652 }
4653 
4654 static void check_raid56_incompat_flag(struct btrfs_fs_info *info, u64 type)
4655 {
4656         if (!(type & BTRFS_BLOCK_GROUP_RAID56_MASK))
4657                 return;
4658 
4659         btrfs_set_fs_incompat(info, RAID56);
4660 }
4661 
4662 #define BTRFS_MAX_DEVS(info) ((BTRFS_MAX_ITEM_SIZE(info)        \
4663                         - sizeof(struct btrfs_chunk))           \
4664                         / sizeof(struct btrfs_stripe) + 1)
4665 
4666 #define BTRFS_MAX_DEVS_SYS_CHUNK ((BTRFS_SYSTEM_CHUNK_ARRAY_SIZE        \
4667                                 - 2 * sizeof(struct btrfs_disk_key)     \
4668                                 - 2 * sizeof(struct btrfs_chunk))       \
4669                                 / sizeof(struct btrfs_stripe) + 1)
4670 
4671 static int __btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
4672                                u64 start, u64 type)
4673 {
4674         struct btrfs_fs_info *info = trans->fs_info;
4675         struct btrfs_fs_devices *fs_devices = info->fs_devices;
4676         struct btrfs_device *device;
4677         struct map_lookup *map = NULL;
4678         struct extent_map_tree *em_tree;
4679         struct extent_map *em;
4680         struct btrfs_device_info *devices_info = NULL;
4681         u64 total_avail;
4682         int num_stripes;        /* total number of stripes to allocate */
4683         int data_stripes;       /* number of stripes that count for
4684                                    block group size */
4685         int sub_stripes;        /* sub_stripes info for map */
4686         int dev_stripes;        /* stripes per dev */
4687         int devs_max;           /* max devs to use */
4688         int devs_min;           /* min devs needed */
4689         int devs_increment;     /* ndevs has to be a multiple of this */
4690         int ncopies;            /* how many copies to data has */
4691         int ret;
4692         u64 max_stripe_size;
4693         u64 max_chunk_size;
4694         u64 stripe_size;
4695         u64 num_bytes;
4696         int ndevs;
4697         int i;
4698         int j;
4699         int index;
4700 
4701         BUG_ON(!alloc_profile_is_valid(type, 0));
4702 
4703         if (list_empty(&fs_devices->alloc_list)) {
4704                 if (btrfs_test_opt(info, ENOSPC_DEBUG))
4705                         btrfs_debug(info, "%s: no writable device", __func__);
4706                 return -ENOSPC;
4707         }
4708 
4709         index = btrfs_bg_flags_to_raid_index(type);
4710 
4711         sub_stripes = btrfs_raid_array[index].sub_stripes;
4712         dev_stripes = btrfs_raid_array[index].dev_stripes;
4713         devs_max = btrfs_raid_array[index].devs_max;
4714         devs_min = btrfs_raid_array[index].devs_min;
4715         devs_increment = btrfs_raid_array[index].devs_increment;
4716         ncopies = btrfs_raid_array[index].ncopies;
4717 
4718         if (type & BTRFS_BLOCK_GROUP_DATA) {
4719                 max_stripe_size = SZ_1G;
4720                 max_chunk_size = 10 * max_stripe_size;
4721                 if (!devs_max)
4722                         devs_max = BTRFS_MAX_DEVS(info);
4723         } else if (type & BTRFS_BLOCK_GROUP_METADATA) {
4724                 /* for larger filesystems, use larger metadata chunks */
4725                 if (fs_devices->total_rw_bytes > 50ULL * SZ_1G)
4726                         max_stripe_size = SZ_1G;
4727                 else
4728                         max_stripe_size = SZ_256M;
4729                 max_chunk_size = max_stripe_size;
4730                 if (!devs_max)
4731                         devs_max = BTRFS_MAX_DEVS(info);
4732         } else if (type & BTRFS_BLOCK_GROUP_SYSTEM) {
4733                 max_stripe_size = SZ_32M;
4734                 max_chunk_size = 2 * max_stripe_size;
4735                 if (!devs_max)
4736                         devs_max = BTRFS_MAX_DEVS_SYS_CHUNK;
4737         } else {
4738                 btrfs_err(info, "invalid chunk type 0x%llx requested",
4739                        type);
4740                 BUG_ON(1);
4741         }
4742 
4743         /* we don't want a chunk larger than 10% of writeable space */
4744         max_chunk_size = min(div_factor(fs_devices->total_rw_bytes, 1),
4745                              max_chunk_size);
4746 
4747         devices_info = kcalloc(fs_devices->rw_devices, sizeof(*devices_info),
4748                                GFP_NOFS);
4749         if (!devices_info)
4750                 return -ENOMEM;
4751 
4752         /*
4753          * in the first pass through the devices list, we gather information
4754          * about the available holes on each device.
4755          */
4756         ndevs = 0;
4757         list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
4758                 u64 max_avail;
4759                 u64 dev_offset;
4760 
4761                 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state)) {
4762                         WARN(1, KERN_ERR
4763                                "BTRFS: read-only device in alloc_list\n");
4764                         continue;
4765                 }
4766 
4767                 if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA,
4768                                         &device->dev_state) ||
4769                     test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state))
4770                         continue;
4771 
4772                 if (device->total_bytes > device->bytes_used)
4773                         total_avail = device->total_bytes - device->bytes_used;
4774                 else
4775                         total_avail = 0;
4776 
4777                 /* If there is no space on this device, skip it. */
4778                 if (total_avail == 0)
4779                         continue;
4780 
4781                 ret = find_free_dev_extent(trans, device,
4782                                            max_stripe_size * dev_stripes,
4783                                            &dev_offset, &max_avail);
4784                 if (ret && ret != -ENOSPC)
4785                         goto error;
4786 
4787                 if (ret == 0)
4788                         max_avail = max_stripe_size * dev_stripes;
4789 
4790                 if (max_avail < BTRFS_STRIPE_LEN * dev_stripes) {
4791                         if (btrfs_test_opt(info, ENOSPC_DEBUG))
4792                                 btrfs_debug(info,
4793                         "%s: devid %llu has no free space, have=%llu want=%u",
4794                                             __func__, device->devid, max_avail,
4795                                             BTRFS_STRIPE_LEN * dev_stripes);
4796                         continue;
4797                 }
4798 
4799                 if (ndevs == fs_devices->rw_devices) {
4800                         WARN(1, "%s: found more than %llu devices\n",
4801                              __func__, fs_devices->rw_devices);
4802                         break;
4803                 }
4804                 devices_info[ndevs].dev_offset = dev_offset;
4805                 devices_info[ndevs].max_avail = max_avail;
4806                 devices_info[ndevs].total_avail = total_avail;
4807                 devices_info[ndevs].dev = device;
4808                 ++ndevs;
4809         }
4810 
4811         /*
4812          * now sort the devices by hole size / available space
4813          */
4814         sort(devices_info, ndevs, sizeof(struct btrfs_device_info),
4815              btrfs_cmp_device_info, NULL);
4816 
4817         /* round down to number of usable stripes */
4818         ndevs = round_down(ndevs, devs_increment);
4819 
4820         if (ndevs < devs_min) {
4821                 ret = -ENOSPC;
4822                 if (btrfs_test_opt(info, ENOSPC_DEBUG)) {
4823                         btrfs_debug(info,
4824         "%s: not enough devices with free space: have=%d minimum required=%d",
4825                                     __func__, ndevs, devs_min);
4826                 }
4827                 goto error;
4828         }
4829 
4830         ndevs = min(ndevs, devs_max);
4831 
4832         /*
4833          * The primary goal is to maximize the number of stripes, so use as
4834          * many devices as possible, even if the stripes are not maximum sized.
4835          *
4836          * The DUP profile stores more than one stripe per device, the
4837          * max_avail is the total size so we have to adjust.
4838          */
4839         stripe_size = div_u64(devices_info[ndevs - 1].max_avail, dev_stripes);
4840         num_stripes = ndevs * dev_stripes;
4841 
4842         /*
4843          * this will have to be fixed for RAID1 and RAID10 over
4844          * more drives
4845          */
4846         data_stripes = num_stripes / ncopies;
4847 
4848         if (type & BTRFS_BLOCK_GROUP_RAID5)
4849                 data_stripes = num_stripes - 1;
4850 
4851         if (type & BTRFS_BLOCK_GROUP_RAID6)
4852                 data_stripes = num_stripes - 2;
4853 
4854         /*
4855          * Use the number of data stripes to figure out how big this chunk
4856          * is really going to be in terms of logical address space,
4857          * and compare that answer with the max chunk size
4858          */
4859         if (stripe_size * data_stripes > max_chunk_size) {
4860                 stripe_size = div_u64(max_chunk_size, data_stripes);
4861 
4862                 /* bump the answer up to a 16MB boundary */
4863                 stripe_size = round_up(stripe_size, SZ_16M);
4864 
4865                 /*
4866                  * But don't go higher than the limits we found while searching
4867                  * for free extents
4868                  */
4869                 stripe_size = min(devices_info[ndevs - 1].max_avail,
4870                                   stripe_size);
4871         }
4872 
4873         /* align to BTRFS_STRIPE_LEN */
4874         stripe_size = round_down(stripe_size, BTRFS_STRIPE_LEN);
4875 
4876         map = kmalloc(map_lookup_size(num_stripes), GFP_NOFS);
4877         if (!map) {
4878                 ret = -ENOMEM;
4879                 goto error;
4880         }
4881         map->num_stripes = num_stripes;
4882 
4883         for (i = 0; i < ndevs; ++i) {
4884                 for (j = 0; j < dev_stripes; ++j) {
4885                         int s = i * dev_stripes + j;
4886                         map->stripes[s].dev = devices_info[i].dev;
4887                         map->stripes[s].physical = devices_info[i].dev_offset +
4888                                                    j * stripe_size;
4889                 }
4890         }
4891         map->stripe_len = BTRFS_STRIPE_LEN;
4892         map->io_align = BTRFS_STRIPE_LEN;
4893         map->io_width = BTRFS_STRIPE_LEN;
4894         map->type = type;
4895         map->sub_stripes = sub_stripes;
4896 
4897         num_bytes = stripe_size * data_stripes;
4898 
4899         trace_btrfs_chunk_alloc(info, map, start, num_bytes);
4900 
4901         em = alloc_extent_map();
4902         if (!em) {
4903                 kfree(map);
4904                 ret = -ENOMEM;
4905                 goto error;
4906         }
4907         set_bit(EXTENT_FLAG_FS_MAPPING, &em->flags);
4908         em->map_lookup = map;
4909         em->start = start;
4910         em->len = num_bytes;
4911         em->block_start = 0;
4912         em->block_len = em->len;
4913         em->orig_block_len = stripe_size;
4914 
4915         em_tree = &info->mapping_tree.map_tree;
4916         write_lock(&em_tree->lock);
4917         ret = add_extent_mapping(em_tree, em, 0);
4918         if (ret) {
4919                 write_unlock(&em_tree->lock);
4920                 free_extent_map(em);
4921                 goto error;
4922         }
4923 
4924         list_add_tail(&em->list, &trans->transaction->pending_chunks);
4925         refcount_inc(&em->refs);
4926         write_unlock(&em_tree->lock);
4927 
4928         ret = btrfs_make_block_group(trans, info, 0, type, start, num_bytes);
4929         if (ret)
4930                 goto error_del_extent;
4931 
4932         for (i = 0; i < map->num_stripes; i++) {
4933                 num_bytes = map->stripes[i].dev->bytes_used + stripe_size;
4934                 btrfs_device_set_bytes_used(map->stripes[i].dev, num_bytes);
4935         }
4936 
4937         atomic64_sub(stripe_size * map->num_stripes, &info->free_chunk_space);
4938 
4939         free_extent_map(em);
4940         check_raid56_incompat_flag(info, type);
4941 
4942         kfree(devices_info);
4943         return 0;
4944 
4945 error_del_extent:
4946         write_lock(&em_tree->lock);
4947         remove_extent_mapping(em_tree, em);
4948         write_unlock(&em_tree->lock);
4949 
4950         /* One for our allocation */
4951         free_extent_map(em);
4952         /* One for the tree reference */
4953         free_extent_map(em);
4954         /* One for the pending_chunks list reference */
4955         free_extent_map(em);
4956 error:
4957         kfree(devices_info);
4958         return ret;
4959 }
4960 
4961 int btrfs_finish_chunk_alloc(struct btrfs_trans_handle *trans,
4962                                 struct btrfs_fs_info *fs_info,
4963                                 u64 chunk_offset, u64 chunk_size)
4964 {
4965         struct btrfs_root *extent_root = fs_info->extent_root;
4966         struct btrfs_root *chunk_root = fs_info->chunk_root;
4967         struct btrfs_key key;
4968         struct btrfs_device *device;
4969         struct btrfs_chunk *chunk;
4970         struct btrfs_stripe *stripe;
4971         struct extent_map *em;
4972         struct map_lookup *map;
4973         size_t item_size;
4974         u64 dev_offset;
4975         u64 stripe_size;
4976         int i = 0;
4977         int ret = 0;
4978 
4979         em = get_chunk_map(fs_info, chunk_offset, chunk_size);
4980         if (IS_ERR(em))
4981                 return PTR_ERR(em);
4982 
4983         map = em->map_lookup;
4984         item_size = btrfs_chunk_item_size(map->num_stripes);
4985         stripe_size = em->orig_block_len;
4986 
4987         chunk = kzalloc(item_size, GFP_NOFS);
4988         if (!chunk) {
4989                 ret = -ENOMEM;
4990                 goto out;
4991         }
4992 
4993         /*
4994          * Take the device list mutex to prevent races with the final phase of
4995          * a device replace operation that replaces the device object associated
4996          * with the map's stripes, because the device object's id can change
4997          * at any time during that final phase of the device replace operation
4998          * (dev-replace.c:btrfs_dev_replace_finishing()).
4999          */
5000         mutex_lock(&fs_info->fs_devices->device_list_mutex);
5001         for (i = 0; i < map->num_stripes; i++) {
5002                 device = map->stripes[i].dev;
5003                 dev_offset = map->stripes[i].physical;
5004 
5005                 ret = btrfs_update_device(trans, device);
5006                 if (ret)
5007                         break;
5008                 ret = btrfs_alloc_dev_extent(trans, device, chunk_offset,
5009                                              dev_offset, stripe_size);
5010                 if (ret)
5011                         break;
5012         }
5013         if (ret) {
5014                 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
5015                 goto out;
5016         }
5017 
5018         stripe = &chunk->stripe;
5019         for (i = 0; i < map->num_stripes; i++) {
5020                 device = map->stripes[i].dev;
5021                 dev_offset = map->stripes[i].physical;
5022 
5023                 btrfs_set_stack_stripe_devid(stripe, device->devid);
5024                 btrfs_set_stack_stripe_offset(stripe, dev_offset);
5025                 memcpy(stripe->dev_uuid, device->uuid, BTRFS_UUID_SIZE);
5026                 stripe++;
5027         }
5028         mutex_unlock(&fs_info->fs_devices->device_list_mutex);
5029 
5030         btrfs_set_stack_chunk_length(chunk, chunk_size);
5031         btrfs_set_stack_chunk_owner(chunk, extent_root->root_key.objectid);
5032         btrfs_set_stack_chunk_stripe_len(chunk, map->stripe_len);
5033         btrfs_set_stack_chunk_type(chunk, map->type);
5034         btrfs_set_stack_chunk_num_stripes(chunk, map->num_stripes);
5035         btrfs_set_stack_chunk_io_align(chunk, map->stripe_len);
5036         btrfs_set_stack_chunk_io_width(chunk, map->stripe_len);
5037         btrfs_set_stack_chunk_sector_size(chunk, fs_info->sectorsize);
5038         btrfs_set_stack_chunk_sub_stripes(chunk, map->sub_stripes);
5039 
5040         key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
5041         key.type = BTRFS_CHUNK_ITEM_KEY;
5042         key.offset = chunk_offset;
5043 
5044         ret = btrfs_insert_item(trans, chunk_root, &key, chunk, item_size);
5045         if (ret == 0 && map->type & BTRFS_BLOCK_GROUP_SYSTEM) {
5046                 /*
5047                  * TODO: Cleanup of inserted chunk root in case of
5048                  * failure.
5049                  */
5050                 ret = btrfs_add_system_chunk(fs_info, &key, chunk, item_size);
5051         }
5052 
5053 out:
5054         kfree(chunk);
5055         free_extent_map(em);
5056         return ret;
5057 }
5058 
5059 /*
5060  * Chunk allocation falls into two parts. The first part does works
5061  * that make the new allocated chunk useable, but not do any operation
5062  * that modifies the chunk tree. The second part does the works that
5063  * require modifying the chunk tree. This division is important for the
5064  * bootstrap process of adding storage to a seed btrfs.
5065  */
5066 int btrfs_alloc_chunk(struct btrfs_trans_handle *trans,
5067                       struct btrfs_fs_info *fs_info, u64 type)
5068 {
5069         u64 chunk_offset;
5070 
5071         lockdep_assert_held(&fs_info->chunk_mutex);
5072         chunk_offset = find_next_chunk(fs_info);
5073         return __btrfs_alloc_chunk(trans, chunk_offset, type);
5074 }
5075 
5076 static noinline int init_first_rw_device(struct btrfs_trans_handle *trans,
5077                                          struct btrfs_fs_info *fs_info)
5078 {
5079         u64 chunk_offset;
5080         u64 sys_chunk_offset;
5081         u64 alloc_profile;
5082         int ret;
5083 
5084         chunk_offset = find_next_chunk(fs_info);
5085         alloc_profile = btrfs_metadata_alloc_profile(fs_info);
5086         ret = __btrfs_alloc_chunk(trans, chunk_offset, alloc_profile);
5087         if (ret)
5088                 return ret;
5089 
5090         sys_chunk_offset = find_next_chunk(fs_info);
5091         alloc_profile = btrfs_system_alloc_profile(fs_info);
5092         ret = __btrfs_alloc_chunk(trans, sys_chunk_offset, alloc_profile);
5093         return ret;
5094 }
5095 
5096 static inline int btrfs_chunk_max_errors(struct map_lookup *map)
5097 {
5098         int max_errors;
5099 
5100         if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
5101                          BTRFS_BLOCK_GROUP_RAID10 |
5102                          BTRFS_BLOCK_GROUP_RAID5 |
5103                          BTRFS_BLOCK_GROUP_DUP)) {
5104                 max_errors = 1;
5105         } else if (map->type & BTRFS_BLOCK_GROUP_RAID6) {
5106                 max_errors = 2;
5107         } else {
5108                 max_errors = 0;
5109         }
5110 
5111         return max_errors;
5112 }
5113 
5114 int btrfs_chunk_readonly(struct btrfs_fs_info *fs_info, u64 chunk_offset)
5115 {
5116         struct extent_map *em;
5117         struct map_lookup *map;
5118         int readonly = 0;
5119         int miss_ndevs = 0;
5120         int i;
5121 
5122         em = get_chunk_map(fs_info, chunk_offset, 1);
5123         if (IS_ERR(em))
5124                 return 1;
5125 
5126         map = em->map_lookup;
5127         for (i = 0; i < map->num_stripes; i++) {
5128                 if (test_bit(BTRFS_DEV_STATE_MISSING,
5129                                         &map->stripes[i].dev->dev_state)) {
5130                         miss_ndevs++;
5131                         continue;
5132                 }
5133                 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE,
5134                                         &map->stripes[i].dev->dev_state)) {
5135                         readonly = 1;
5136                         goto end;
5137                 }
5138         }
5139 
5140         /*
5141          * If the number of missing devices is larger than max errors,
5142          * we can not write the data into that chunk successfully, so
5143          * set it readonly.
5144          */
5145         if (miss_ndevs > btrfs_chunk_max_errors(map))
5146                 readonly = 1;
5147 end:
5148         free_extent_map(em);
5149         return readonly;
5150 }
5151 
5152 void btrfs_mapping_init(struct btrfs_mapping_tree *tree)
5153 {
5154         extent_map_tree_init(&tree->map_tree);
5155 }
5156 
5157 void btrfs_mapping_tree_free(struct btrfs_mapping_tree *tree)
5158 {
5159         struct extent_map *em;
5160 
5161         while (1) {
5162                 write_lock(&tree->map_tree.lock);
5163                 em = lookup_extent_mapping(&tree->map_tree, 0, (u64)-1);
5164                 if (em)
5165                         remove_extent_mapping(&tree->map_tree, em);
5166                 write_unlock(&tree->map_tree.lock);
5167                 if (!em)
5168                         break;
5169                 /* once for us */
5170                 free_extent_map(em);
5171                 /* once for the tree */
5172                 free_extent_map(em);
5173         }
5174 }
5175 
5176 int btrfs_num_copies(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5177 {
5178         struct extent_map *em;
5179         struct map_lookup *map;
5180         int ret;
5181 
5182         em = get_chunk_map(fs_info, logical, len);
5183         if (IS_ERR(em))
5184                 /*
5185                  * We could return errors for these cases, but that could get
5186                  * ugly and we'd probably do the same thing which is just not do
5187                  * anything else and exit, so return 1 so the callers don't try
5188                  * to use other copies.
5189                  */
5190                 return 1;
5191 
5192         map = em->map_lookup;
5193         if (map->type & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1))
5194                 ret = map->num_stripes;
5195         else if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5196                 ret = map->sub_stripes;
5197         else if (map->type & BTRFS_BLOCK_GROUP_RAID5)
5198                 ret = 2;
5199         else if (map->type & BTRFS_BLOCK_GROUP_RAID6)
5200                 /*
5201                  * There could be two corrupted data stripes, we need
5202                  * to loop retry in order to rebuild the correct data.
5203                  * 
5204                  * Fail a stripe at a time on every retry except the
5205                  * stripe under reconstruction.
5206                  */
5207                 ret = map->num_stripes;
5208         else
5209                 ret = 1;
5210         free_extent_map(em);
5211 
5212         btrfs_dev_replace_read_lock(&fs_info->dev_replace);
5213         if (btrfs_dev_replace_is_ongoing(&fs_info->dev_replace) &&
5214             fs_info->dev_replace.tgtdev)
5215                 ret++;
5216         btrfs_dev_replace_read_unlock(&fs_info->dev_replace);
5217 
5218         return ret;
5219 }
5220 
5221 unsigned long btrfs_full_stripe_len(struct btrfs_fs_info *fs_info,
5222                                     u64 logical)
5223 {
5224         struct extent_map *em;
5225         struct map_lookup *map;
5226         unsigned long len = fs_info->sectorsize;
5227 
5228         em = get_chunk_map(fs_info, logical, len);
5229 
5230         if (!WARN_ON(IS_ERR(em))) {
5231                 map = em->map_lookup;
5232                 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5233                         len = map->stripe_len * nr_data_stripes(map);
5234                 free_extent_map(em);
5235         }
5236         return len;
5237 }
5238 
5239 int btrfs_is_parity_mirror(struct btrfs_fs_info *fs_info, u64 logical, u64 len)
5240 {
5241         struct extent_map *em;
5242         struct map_lookup *map;
5243         int ret = 0;
5244 
5245         em = get_chunk_map(fs_info, logical, len);
5246 
5247         if(!WARN_ON(IS_ERR(em))) {
5248                 map = em->map_lookup;
5249                 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
5250                         ret = 1;
5251                 free_extent_map(em);
5252         }
5253         return ret;
5254 }
5255 
5256 static int find_live_mirror(struct btrfs_fs_info *fs_info,
5257                             struct map_lookup *map, int first,
5258                             int dev_replace_is_ongoing)
5259 {
5260         int i;
5261         int num_stripes;
5262         int preferred_mirror;
5263         int tolerance;
5264         struct btrfs_device *srcdev;
5265 
5266         ASSERT((map->type &
5267                  (BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10)));
5268 
5269         if (map->type & BTRFS_BLOCK_GROUP_RAID10)
5270                 num_stripes = map->sub_stripes;
5271         else
5272                 num_stripes = map->num_stripes;
5273 
5274         preferred_mirror = first + current->pid % num_stripes;
5275 
5276         if (dev_replace_is_ongoing &&
5277             fs_info->dev_replace.cont_reading_from_srcdev_mode ==
5278              BTRFS_DEV_REPLACE_ITEM_CONT_READING_FROM_SRCDEV_MODE_AVOID)
5279                 srcdev = fs_info->dev_replace.srcdev;
5280         else
5281                 srcdev = NULL;
5282 
5283         /*
5284          * try to avoid the drive that is the source drive for a
5285          * dev-replace procedure, only choose it if no other non-missing
5286          * mirror is available
5287          */
5288         for (tolerance = 0; tolerance < 2; tolerance++) {
5289                 if (map->stripes[preferred_mirror].dev->bdev &&
5290                     (tolerance || map->stripes[preferred_mirror].dev != srcdev))
5291                         return preferred_mirror;
5292                 for (i = first; i < first + num_stripes; i++) {
5293                         if (map->stripes[i].dev->bdev &&
5294                             (tolerance || map->stripes[i].dev != srcdev))
5295                                 return i;
5296                 }
5297         }
5298 
5299         /* we couldn't find one that doesn't fail.  Just return something
5300          * and the io error handling code will clean up eventually
5301          */
5302         return preferred_mirror;
5303 }
5304 
5305 static inline int parity_smaller(u64 a, u64 b)
5306 {
5307         return a > b;
5308 }
5309 
5310 /* Bubble-sort the stripe set to put the parity/syndrome stripes last */
5311 static void sort_parity_stripes(struct btrfs_bio *bbio, int num_stripes)
5312 {
5313         struct btrfs_bio_stripe s;
5314         int i;
5315         u64 l;
5316         int again = 1;
5317 
5318         while (again) {
5319                 again = 0;
5320                 for (i = 0; i < num_stripes - 1; i++) {
5321                         if (parity_smaller(bbio->raid_map[i],
5322                                            bbio->raid_map[i+1])) {
5323                                 s = bbio->stripes[i];
5324                                 l = bbio->raid_map[i];
5325                                 bbio->stripes[i] = bbio->stripes[i+1];
5326                                 bbio->raid_map[i] = bbio->raid_map[i+1];
5327                                 bbio->stripes[i+1] = s;
5328                                 bbio->raid_map[i+1] = l;
5329 
5330                                 again = 1;
5331                         }
5332                 }
5333         }
5334 }
5335 
5336 static struct btrfs_bio *alloc_btrfs_bio(int total_stripes, int real_stripes)
5337 {
5338         struct btrfs_bio *bbio = kzalloc(
5339                  /* the size of the btrfs_bio */
5340                 sizeof(struct btrfs_bio) +
5341                 /* plus the variable array for the stripes */
5342                 sizeof(struct btrfs_bio_stripe) * (total_stripes) +
5343                 /* plus the variable array for the tgt dev */
5344                 sizeof(int) * (real_stripes) +
5345                 /*
5346                  * plus the raid_map, which includes both the tgt dev
5347                  * and the stripes
5348                  */
5349                 sizeof(u64) * (total_stripes),
5350                 GFP_NOFS|__GFP_NOFAIL);
5351 
5352         atomic_set(&bbio->error, 0);
5353         refcount_set(&bbio->refs, 1);
5354 
5355         return bbio;
5356 }
5357 
5358 void btrfs_get_bbio(struct btrfs_bio *bbio)
5359 {
5360         WARN_ON(!refcount_read(&bbio->refs));
5361         refcount_inc(&bbio->refs);
5362 }
5363 
5364 void btrfs_put_bbio(struct btrfs_bio *bbio)
5365 {
5366         if (!bbio)
5367                 return;
5368         if (refcount_dec_and_test(&bbio->refs))
5369                 kfree(bbio);
5370 }
5371 
5372 /* can REQ_OP_DISCARD be sent with other REQ like REQ_OP_WRITE? */
5373 /*
5374  * Please note that, discard won't be sent to target device of device
5375  * replace.
5376  */
5377 static int __btrfs_map_block_for_discard(struct btrfs_fs_info *fs_info,
5378                                          u64 logical, u64 length,
5379                                          struct btrfs_bio **bbio_ret)
5380 {
5381         struct extent_map *em;
5382         struct map_lookup *map;
5383         struct btrfs_bio *bbio;
5384         u64 offset;
5385         u64 stripe_nr;
5386         u64 stripe_nr_end;
5387         u64 stripe_end_offset;
5388         u64 stripe_cnt;
5389         u64 stripe_len;
5390         u64 stripe_offset;
5391         u64 num_stripes;
5392         u32 stripe_index;
5393         u32 factor = 0;
5394         u32 sub_stripes = 0;
5395         u64 stripes_per_dev = 0;
5396         u32 remaining_stripes = 0;
5397         u32 last_stripe = 0;
5398         int ret = 0;
5399         int i;
5400 
5401         /* discard always return a bbio */
5402         ASSERT(bbio_ret);
5403 
5404         em = get_chunk_map(fs_info, logical, length);
5405         if (IS_ERR(em))
5406                 return PTR_ERR(em);
5407 
5408         map = em->map_lookup;
5409         /* we don't discard raid56 yet */
5410         if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
5411                 ret = -EOPNOTSUPP;
5412                 goto out;
5413         }
5414 
5415         offset = logical - em->start;
5416         length = min_t(u64, em->len - offset, length);
5417 
5418         stripe_len = map->stripe_len;
5419         /*
5420          * stripe_nr counts the total number of stripes we have to stride
5421          * to get to this block
5422          */
5423         stripe_nr = div64_u64(offset, stripe_len);
5424 
5425         /* stripe_offset is the offset of this block in its stripe */
5426         stripe_offset = offset - stripe_nr * stripe_len;
5427 
5428         stripe_nr_end = round_up(offset + length, map->stripe_len);
5429         stripe_nr_end = div64_u64(stripe_nr_end, map->stripe_len);
5430         stripe_cnt = stripe_nr_end - stripe_nr;
5431         stripe_end_offset = stripe_nr_end * map->stripe_len -
5432                             (offset + length);
5433         /*
5434          * after this, stripe_nr is the number of stripes on this
5435          * device we have to walk to find the data, and stripe_index is
5436          * the number of our device in the stripe array
5437          */
5438         num_stripes = 1;
5439         stripe_index = 0;
5440         if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5441                          BTRFS_BLOCK_GROUP_RAID10)) {
5442                 if (map->type & BTRFS_BLOCK_GROUP_RAID0)
5443                         sub_stripes = 1;
5444                 else
5445                         sub_stripes = map->sub_stripes;
5446 
5447                 factor = map->num_stripes / sub_stripes;
5448                 num_stripes = min_t(u64, map->num_stripes,
5449                                     sub_stripes * stripe_cnt);
5450                 stripe_nr = div_u64_rem(stripe_nr, factor, &stripe_index);
5451                 stripe_index *= sub_stripes;
5452                 stripes_per_dev = div_u64_rem(stripe_cnt, factor,
5453                                               &remaining_stripes);
5454                 div_u64_rem(stripe_nr_end - 1, factor, &last_stripe);
5455                 last_stripe *= sub_stripes;
5456         } else if (map->type & (BTRFS_BLOCK_GROUP_RAID1 |
5457                                 BTRFS_BLOCK_GROUP_DUP)) {
5458                 num_stripes = map->num_stripes;
5459         } else {
5460                 stripe_nr = div_u64_rem(stripe_nr, map->num_stripes,
5461                                         &stripe_index);
5462         }
5463 
5464         bbio = alloc_btrfs_bio(num_stripes, 0);
5465         if (!bbio) {
5466                 ret = -ENOMEM;
5467                 goto out;
5468         }
5469 
5470         for (i = 0; i < num_stripes; i++) {
5471                 bbio->stripes[i].physical =
5472                         map->stripes[stripe_index].physical +
5473                         stripe_offset + stripe_nr * map->stripe_len;
5474                 bbio->stripes[i].dev = map->stripes[stripe_index].dev;
5475 
5476                 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
5477                                  BTRFS_BLOCK_GROUP_RAID10)) {
5478                         bbio->stripes[i].length = stripes_per_dev *
5479                                 map->stripe_len;
5480 
5481                         if (i / sub_stripes < remaining_stripes)
5482                                 bbio->stripes[i].length +=
5483                                         map->stripe_len;
5484 
5485                         /*
5486                          * Special for the first stripe and
5487                          * the last stripe:
5488                          *
5489                          * |-------|...|-------|
5490                          *     |----------|
5491                          *    off     end_off
5492                          */
5493                         if (i < sub_stripes)
5494                                 bbio->stripes[i].length -=
5495                                         stripe_offset;
5496 
5497                         if (stripe_index >= last_stripe &&
5498                             stripe_index <= (last_stripe +
5499                                              sub_stripes - 1))
5500                                 bbio->stripes[i].length -=
5501                                         stripe_end_offset;
5502 
5503                         if (i == sub_stripes - 1)
5504                                 stripe_offset = 0;
5505                 } else {
5506                         bbio->stripes[i].length = length;
5507                 }
5508 
5509                 stripe_index++;
5510                 if (stripe_index == map->num_stripes) {
5511                         stripe_index = 0;
5512                         stripe_nr++;
5513                 }
5514         }
5515 
5516         *bbio_ret = bbio;
5517         bbio->map_type = map->type;
5518         bbio->num_stripes = num_stripes;
5519 out:
5520         free_extent_map(em);
5521         return ret;
5522 }
5523 
5524 /*
5525  * In dev-replace case, for repair case (that's the only case where the mirror
5526  * is selected explicitly when calling btrfs_map_block), blocks left of the
5527  * left cursor can also be read from the target drive.
5528  *
5529  * For REQ_GET_READ_MIRRORS, the target drive is added as the last one to the
5530  * array of stripes.
5531  * For READ, it also needs to be supported using the same mirror number.
5532  *
5533  * If the requested block is not left of the left cursor, EIO is returned. This
5534  * can happen because btrfs_num_copies() returns one more in the dev-replace
5535  * case.
5536  */
5537 static int get_extra_mirror_from_replace(struct btrfs_fs_info *fs_info,
5538                                          u64 logical, u64 length,
5539                                          u64 srcdev_devid, int *mirror_num,
5540                                          u64 *physical)
5541 {
5542         struct btrfs_bio *bbio = NULL;
5543         int num_stripes;
5544         int index_srcdev = 0;
5545         int found = 0;
5546         u64 physical_of_found = 0;
5547         int i;
5548         int ret = 0;
5549 
5550         ret = __btrfs_map_block(fs_info, BTRFS_MAP_GET_READ_MIRRORS,
5551                                 logical, &length, &bbio, 0, 0);
5552         if (ret) {
5553                 ASSERT(bbio == NULL);
5554                 return ret;
5555         }
5556 
5557         num_stripes = bbio->num_stripes;
5558         if (*mirror_num > num_stripes) {
5559                 /*
5560                  * BTRFS_MAP_GET_READ_MIRRORS does not contain this mirror,
5561                  * that means that the requested area is not left of the left
5562                  * cursor
5563                  */
5564                 btrfs_put_bbio(bbio);
5565                 return -EIO;
5566         }
5567 
5568         /*
5569          * process the rest of the function using the mirror_num of the source
5570          * drive. Therefore look it up first.  At the end, patch the device
5571          * pointer to the one of the target drive.
5572          */
5573         for (i = 0; i < num_stripes; i++) {
5574                 if (bbio->stripes[i].dev->devid != srcdev_devid)
5575                         continue;
5576 
5577                 /*
5578                  * In case of DUP, in order to keep it simple, only add the
5579                  * mirror with the lowest physical address
5580                  */
5581                 if (found &&
5582                     physical_of_found <= bbio->stripes[i].physical)
5583                         continue;
5584 
5585                 index_srcdev = i;
5586                 found = 1;
5587                 physical_of_found = bbio->stripes[i].physical;
5588         }
5589 
5590         btrfs_put_bbio(bbio);
5591 
5592         ASSERT(found);
5593         if (!found)
5594                 return -EIO;
5595 
5596         *mirror_num = index_srcdev + 1;
5597         *physical = physical_of_found;
5598         return ret;
5599 }
5600 
5601 static void handle_ops_on_dev_replace(enum btrfs_map_op op,
5602                                       struct btrfs_bio **bbio_ret,
5603                                       struct btrfs_dev_replace *dev_replace,
5604                                       int *num_stripes_ret, int *max_errors_ret)
5605 {
5606         struct btrfs_bio *bbio = *bbio_ret;
5607         u64 srcdev_devid = dev_replace->srcdev->devid;
5608         int tgtdev_indexes = 0;
5609         int num_stripes = *num_stripes_ret;
5610         int max_errors = *max_errors_ret;
5611         int i;
5612 
5613         if (op == BTRFS_MAP_WRITE) {
5614                 int index_where_to_add;
5615 
5616                 /*
5617                  * duplicate the write operations while the dev replace
5618                  * procedure is running. Since the copying of the old disk to
5619                  * the new disk takes place at run time while the filesystem is
5620                  * mounted writable, the regular write operations to the old
5621                  * disk have to be duplicated to go to the new disk as well.
5622                  *
5623                  * Note that device->missing is handled by the caller, and that
5624                  * the write to the old disk is already set up in the stripes
5625                  * array.
5626                  */
5627                 index_where_to_add = num_stripes;
5628                 for (i = 0; i < num_stripes; i++) {
5629                         if (bbio->stripes[i].dev->devid == srcdev_devid) {
5630                                 /* write to new disk, too */
5631                                 struct btrfs_bio_stripe *new =
5632                                         bbio->stripes + index_where_to_add;
5633                                 struct btrfs_bio_stripe *old =
5634                                         bbio->stripes + i;
5635 
5636                                 new->physical = old->physical;
5637                                 new->length = old->length;
5638                                 new->dev = dev_replace->tgtdev;
5639                                 bbio->tgtdev_map[i] = index_where_to_add;
5640                                 index_where_to_add++;
5641                                 max_errors++;
5642                                 tgtdev_indexes++;
5643                         }
5644                 }
5645                 num_stripes = index_where_to_add;
5646         } else if (op == BTRFS_MAP_GET_READ_MIRRORS) {
5647                 int index_srcdev = 0;
5648                 int found = 0;
5649                 u64 physical_of_found = 0;
5650 
5651                 /*
5652                  * During the dev-replace procedure, the target drive can also
5653                  * be used to read data in case it is needed to repair a corrupt
5654                  * block elsewhere. This is possible if the requested area is
5655                  * left of the left cursor. In this area, the target drive is a
5656                  * full copy of the source drive.
5657                  */
5658                 for (i = 0; i < num_stripes; i++) {
5659                         if (bbio->stripes[i].dev->devid == srcdev_devid) {
5660                                 /*
5661                                  * In case of DUP, in order to keep it simple,
5662                                  * only add the mirror with the lowest physical
5663                                  * address
5664                                  */
5665                                 if (found &&
5666                                     physical_of_found <=
5667                                      bbio->stripes[i].physical)
5668                                         continue;
5669                                 index_srcdev = i;
5670                                 found = 1;
5671                                 physical_of_found = bbio->stripes[i].physical;
5672                         }
5673                 }
5674                 if (found) {
5675                         struct btrfs_bio_stripe *tgtdev_stripe =
5676                                 bbio->stripes + num_stripes;
5677 
5678                         tgtdev_stripe->physical = physical_of_found;
5679                         tgtdev_stripe->length =
5680                                 bbio->stripes[index_srcdev].length;
5681                         tgtdev_stripe->dev = dev_replace->tgtdev;
5682                         bbio->tgtdev_map[index_srcdev] = num_stripes;
5683 
5684                         tgtdev_indexes++;
5685                         num_stripes++;
5686                 }
5687         }
5688 
5689         *num_stripes_ret = num_stripes;
5690         *max_errors_ret = max_errors;
5691         bbio->num_tgtdevs = tgtdev_indexes;
5692         *bbio_ret = bbio;
5693 }
5694 
5695 static bool need_full_stripe(enum btrfs_map_op op)
5696 {
5697         return (op == BTRFS_MAP_WRITE || op == BTRFS_MAP_GET_READ_MIRRORS);
5698 }