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