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