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