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