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