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