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